SLOPSHOPPER

md-taskview

A pane showing the milestone and task tree of spec/*/tasks.md and implementation_plan.md files; press a task to tick it

paneguardcommandtoastprocesstimer
v0.7.0MITupdated 2026-10-26coreyx/claude-md-taskview
A shopper browsing a rack in a slop shop
Preview · a replayed session in a sandbox
claude · ~/work/app · md-taskview
│ ┃ Markdown Tasks ✕ › fix the failing auth test and add an audit log call │ ┃ r: Refresh f: Hide completed e: Expand all │ ┃ No spec/*/tasks.md or spec/*/implementation_ ⏺ Read(src/auth.ts) │ ┃ found in this folder. ⎿ Read 6 lines │ ⏺ Update(src/auth.ts) │ ⎿ Added 2 lines, removed 1 line │ ⏺ Bash(bun test) │ ⎿ 3 pass, 1 fail │ │ ● Done. refresh now rejects expired claims and logs an audit event. │ │ ✻ Worked for 42s · done 4:20 PM │ │ › /md-tasks │ │ ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── › ? for shortcuts

Draws

Pane · Markdown Tasks
r: Refresh f: Hide completed e: Expand all c: Collapse al No spec/*/tasks.md or spec/*/implementation_plan.md found in this folder.
README

Markdown Tasks for Claude Code (claude-md-taskview)

A Claude Code mod that draws the milestone and task tree of your spec/*/tasks.md and spec/*/implementation_plan.md files in a pane beside the transcript, in the terminal and in the Claude Desktop Code tab. It lets you follow an agent's progress through a task list, and tick tasks yourself, without opening an editor.

It is the same product as the Markdown Tasks View extension for VS Code, on a second host. The parser is a copy of the extension's, so both read a task file the same way.

Requirements

Claude Code v2.1.287 or newer. Mods are an early-access part of Claude Code and their API may change between releases.

Install

Try it from a clone, for one session:

git clone https://github.com/coreyx/claude-md-taskview.git
claude --plugin-dir ./claude-md-taskview

Install it for every session:

/plugin install md-taskview --marketplace coreyx/claude-md-taskview

The Desktop Code tab takes no --plugin-dir flag. To try a clone there, name its absolute path in CLAUDE_CODE_PLUGIN_DIRS, in the environment the app starts from or in the env block of ~/.claude/settings.json, then restart the app.

Use

Run /md-tasks in a folder that holds spec/<name>/tasks.md or spec/<name>/implementation_plan.md files. The pane opens beside the transcript; it never opens by itself.

For an implementation_plan.md, the pane shows only the tasks under its ## Proposed Changes heading, with its areas as the top level; the plan's other sections and any checkbox outside that heading are left out and not counted. A plan without that heading is shown whole, minus headings with no tasks. A spec folder holding both files gets a group for each, named <folder> (tasks.md) and <folder> (implementation_plan.md).

  • Each spec folder is a group, with its headings and tasks nested beneath it and a (done/total) count.
  • Press a group or a heading to collapse or expand it.
  • Press a task to move it to its next state. The file on disk changes by exactly one character. In the Desktop Code tab, press a task or heading by its label: its glyph is drawn beside the pressable part there, so that colours show.
  • With the Standard (GFM) template a press toggles not done [ ] and done [x], and nothing else is ever written.
  • With the Obsidian Tasks template a press goes not started [ ], in progress [/], done [x], then back to not started.
  • An in-progress task shows a turning spinner, in blue. It is a static ◐ when animateTaskIcons is off or Claude Code's prefersReducedMotion setting is on. At most twelve spinners turn at once; in-progress tasks past the twelfth show the static ◐.
  • Press the ↗ at the end of a heading or task row to open the file at that line in VS Code. This needs the code command on your PATH.
  • Headings that start with a milestone keyword show a flag, filled once every task beneath is done. A keyword later in a heading, or in the plural, does not count, so ## Notes on Milestone 1 and ## Milestones stay plain headings. The only keyword by default is Milestone.
  • The toolbar refreshes (r), hides or shows completed tasks (f), and expands or collapses everything (e / c).
  • With a multi-state template, each task row ends with a ▾. Press it to open a row of buttons beneath the task, one per state, and press one to set it directly; the task is not changed until you pick. While the picker is open the arrow points up (▴); press it again to close the picker.

The pane re-reads a task file within about two seconds of it changing on disk, and at once after Claude edits one.

The pane looks for spec folders in the session's project folder, where it started, wherever Claude's shell cds to within it. If the project folder has none, the pane looks where Claude is working, in this order:

  1. The folder the shell has moved to.
  2. The folders Claude has read or edited a file in, or added with /add-dir, most recent first.
  3. The working folders kept in settings (permissions.additionalDirectories).

From each of these it looks in that folder and each one above it, and the nearest with spec folders is that project. The pane shows the first project it finds, and a dim line at the top names it. This covers a session that works on another repository, for example one added with /add-dir or a permission grant. By default those tasks are shown only when the session's permissions let Claude read them outright (see followShellFolder, followWorkingFolders and requireReadPermission below).

A folder added for one session is forgotten when the session restarts, by Claude Code and the pane alike. After a restart, add the folder again with /add-dir, or start the session in that folder.

Settings

The settings mirror the extension's settings of the same names. There are two ways to change one.

In Claude Code. Run /config and find the mod's rows. There is one per setting, labelled with its title: "State template" for stateTemplate, "Animate task icons" for animateTaskIcons, and so on. stateTemplate is a picker over its three values. A change made here reloads the mod with the new value, so no restart is needed.

In the settings file. Edit ~/.claude/settings.json and set the value under pluginConfigs. This example switches to the Obsidian Tasks template:

{
  "pluginConfigs": {
    "md-taskview@claude-md-taskview": {
      "options": {
        "stateTemplate": "Obsidian Tasks"
      }
    }
  }
}

The key is the mod's name and its marketplace. A copy loaded with --plugin-dir or CLAUDE_CODE_PLUGIN_DIRS has no marketplace, so its settings are kept under md-taskview@inline instead (/config writes that key; md-taskview is read too). An edit to the file takes effect in the next session you start.

The dialog shown at install does not fill in the defaults of the text settings: those fields start empty. Leave one empty and its default applies; you do not have to type it.

SettingDefaultDescription
specPathPatternspec/*Where spec folders are, relative to the working directory. * matches one folder level.
taskFileNamestasks.md, implementation_plan.mdComma-separated task file names looked for in each spec folder. For implementation_plan.md, only the tasks under ## Proposed Changes are shown.
taskFileName(empty)Deprecated: use taskFileNames. A name set here is added to that list.
followShellFoldertrueWhen the project folder has no spec folders, show the specs of the folder Claude's shell has moved to, or of the nearest folder above it that has any. The walk starts above any node_modules, .git or dist folder the shell is in.
followWorkingFolderstrueWhen the project folder has no spec folders, also look from the folders Claude reads or edits files in, folders added with /add-dir, and working folders kept in settings, after the shell's folder.
requireReadPermissiontrueShow another folder's tasks only when the session's permissions let Claude read them outright. That is a folder added with /add-dir or a "don't ask again" grant, or one a permission rule allows. A folder Claude would have to ask about is not shown, in auto mode too.
stateTemplateStandard (GFM)Standard (GFM): done and not done only. Obsidian Tasks: also in progress [/], cancelled [-], needs clarification [?] and important [!]. Custom: your own template.
customTemplatePath(empty)Path to a *.jsonc state template, used when stateTemplate is Custom.
strikeThroughCompletedtrueStrike through and dim completed and cancelled tasks.
animateTaskIconstrueShow a turning spinner for in-progress tasks. When off, or when Claude Code's prefersReducedMotion is on, a static icon is shown instead.
showProgressCounttrueShow (done/total) beside groups and headings.
hideCompletedByDefaultfalseStart with completed tasks hidden.
useH1AsGroupNamefalseName a group after the first level-1 heading in its task file instead of its folder.
milestoneKeywordsMilestoneComma-separated keywords that mark a heading as a milestone when the heading starts with one (any case, whole word). A keyword later in the heading, or in the plural, does not count.

A custom template uses the same *.jsonc format as the extension; see its README. Give a state an animatedIcon (any value, such as "loading~spin") and it draws with the spinner. A press follows each state's own nextState.

Differences from the VS Code extension

  • Toggling writes straight to disk, with no undo. There is no editor buffer or undo stack. A toggle re-reads the file, checks the bracket is still where it was parsed, and writes the file back. If something else edits the same file in the milliseconds between that read and write, one of the two edits is lost.
  • Live sync is polling. Mods have no file watcher, so the pane checks modification times about every 1.5 seconds.
  • No right-click menus. The ▾ control at the end of a task row opens the state picker, which replaces "Set Task State"; the toolbar replaces the section menus.
  • No editor task actions. The extension's Start, Continue and Mark done actions are CodeLens in its text editor and entries in its tree menu. A pane has neither; pressing a task does the same job.
  • In-progress tasks are blue, where the extension draws them yellow.
  • Reduced motion follows Claude Code, through its prefersReducedMotion setting, not VS Code's accessibility.reducedMotion. The spinner needs the terminal or the Desktop Code tab; other surfaces show the static icon.
  • Jump-to-source opens VS Code only, at the line, in its text editor. There are no Markdown-preview navigation modes and no "Create Sample Spec" command.
  • **Spec folders are found one level per *.** spec/* finds spec/<name>/tasks.md; it does not search deeper folders, as the extension's spec/** patterns do,, and there are no separate include and exclude patterns.
  • Strikethrough is drawn two ways. The terminal strikes a completed task's label through as a text style; on builds too old to style a pressable row's label, it is only dimmed there. The Desktop Code tab ignores that style, so there the label carries a stroke on each character, the way the extension draws it.
  • The pane exists only in Claude Code surfaces (terminal, Desktop Code tab), not in regular Claude chat.

Develop

npm install
npm test            # parser, templates and mutation (vitest, core/*.spec.ts)
npm run validate    # claude plugin validate .
npm run test:mod    # the pane, under claude plugin test . (hooks/*.test.ts)
npm run typecheck   # needs the types Claude Code lays on first load

Claude Code writes its type definitions to .claude-plugin/types/ the first time it loads the mod from this folder in an interactive session (claude --plugin-dir .), so run that once before npm run typecheck.

claude plugin test . runs every *.test.ts under the folder and cannot import vitest, which is why the vitest file is core/core.spec.ts.

core/ holds the parser copied from the extension; core/UPSTREAM.md records the source commit and what was changed, so fixes can be ported between the two repositories by hand.

Two rules of the mods API shape hooks/: $ may only be passed to functions declared at the top of hooks/register.tsx, never into another file, so sync.ts and discover.ts take closures; and types/index.d.ts must be self-contained, so it repeats the types in core/types.ts.

License

MIT License.

Source 13 files
hooks/register.tsx 674 lines
1import { atom, read, update } from 'claude-code';
2import type { Elements, EngineInterface, Register, RenderElement, RenderSurface } from 'claude-code';
3
4import { replaceStateChar } from '../core/mutate';
5import { getNextState } from '../core/templates';
6import type { SpecGroup, TaskNode } from '../core/types';
7import type { SpecGroup as ContractSpecGroup } from '../types';
8import { foldersUpward } from './discover';
9import { buildRows, collapsibleIds, findTask, stateGlyph } from './rows';
10import type { Row, TaskRow } from './rows';
11import { readSettings } from './settings';
12import { createSession, loadTemplate, noteWorkingFolder, poll, refresh } from './sync';
13import type { Host, Session } from './sync';
14
15// types/index.d.ts has to repeat core's types; this line stops compiling if one changes without the other.
16type Same<A, B> = [A] extends [B] ? ([B] extends [A] ? true : never) : never;
17export const contractMatchesCore: Same<SpecGroup, ContractSpecGroup> = true;
18
19const PANE = 'md-tasks';
20const COMMAND = 'md-tasks';
21const POLL_MS = 1500;
22/**
23 * Columns a row moves right per level of nesting. The indent is padding on
24 * the row's Box, never spaces in its text: the Desktop Code tab drops the
25 * spaces a Button's content starts with, which flattened the tree there.
26 */
27const INDENT_COLUMNS = 2;
28const OPEN_TIMEOUT_MS = 15000;
29/**
30 * How many spinners one drawing of the pane may hold; in-progress tasks past
31 * that draw the static glyph. The Desktop Code tab stops every spinner once
32 * too many redraw at once (see FRAME_MS in spinner.tsx).
33 */
34const MAX_SPINNERS = 12;
35/** Columns a control takes at the end of a row: a space and its glyph. */
36const CONTROL_WIDTH = 2;
37// `cmd /c` re-reads its arguments as a command line, so a path holding one of these could run something else.
38const CMD_UNSAFE = /[&|<>^%!"]/;
39/** A path that names where it starts: a drive, or a leading slash or backslash (which covers a UNC share). */
40const ABSOLUTE = /^(?:[a-zA-Z]:[\\/]|[\\/])/;
41
42const groups = atom({ plugin: 'md-taskview', key: 'groups' } as const, []);
43const collapsed = atom({ plugin: 'md-taskview', key: 'collapsed' } as const, []);
44const hideCompleted = atom({ plugin: 'md-taskview', key: 'hideCompleted' } as const, false);
45const error = atom({ plugin: 'md-taskview', key: 'error' } as const, null);
46const picker = atom({ plugin: 'md-taskview', key: 'picker' } as const, null);
47const source = atom({ plugin: 'md-taskview', key: 'source' } as const, null);
48
49/** One styled run of text in a row. */
50interface Part {
51  text: string;
52  color?: string;
53  bold?: boolean;
54  dimColor?: boolean;
55  strikethrough?: boolean;
56}
57
58/** A row the person can press: styled text before and after a label. */
59export interface Pressable {
60  key: string;
61  before: Part[];
62  label: Part;
63  after: Part[];
64  onPress: () => void;
65}
66
67/** The slice of a surface's element table the rows are built from. */
68export type RowElements = Pick<Elements[RenderSurface], 'Box' | 'Button' | 'Text'>;
69
70/**
71 * Draws a pressable row, as one plain Button holding styled Text where that
72 * is drawn as written, else as Text, a string-label Button and Text side by side.
73 *
74 * Builds before 2.1.294 refuse Text inside a Button, throwing as the element
75 * is made, and the row falls back. The Desktop Code tab accepts it but draws a
76 * Button's content as plain text, colour and all, so the pane asks for the
77 * side-by-side form there from the start. A Button's own label cannot be
78 * struck through, so in that form a struck label is only dimmed, unless its
79 * text carries the stroke (see strikeThrough).
80 *
81 * @param el The surface's Box, Button and Text.
82 * @param row What to draw.
83 * @param nesting Whether to draw the side-by-side form: set up front where the rich form draws wrongly, and remembered once a build refuses it, so a long list tries it once.
84 */
85export function drawPressable(el: RowElements, row: Pressable, nesting: { isRefused: boolean }): RenderElement {
86  const { Box, Button, Text } = el;
87  const text = (part: Part): RenderElement => {
88    // Only the props a part sets are passed: a surface may refuse one given as undefined.
89    const { text: content, ...style } = part;
90    return <Text {...style}>{content}</Text>;
91  };
92  const before = row.before.filter((part) => part.text !== '').map(text);
93  const after = row.after.filter((part) => part.text !== '').map(text);
94
95  if (!nesting.isRefused) {
96    try {
97      return (
98        <Button key={row.key} plain onPress={row.onPress}>
99          {before}
100          {text(row.label)}
101          {after}
102        </Button>
103      );
104    } catch {
105      nesting.isRefused = true;
106    }
107  }
108
109  return (
110    <Box>
111      {before}
112      <Button key={row.key} plain dimColor={row.label.dimColor === true} label={row.label.text} onPress={row.onPress} />
113      {after}
114    </Box>
115  );
116}
117
118/**
119 * Strikes text through with a combining stroke after each character, as the
120 * VS Code extension does for its tree. For surfaces that draw a row's label
121 * as plain text, where a `strikethrough` style has nothing to act on.
122 */
123export function strikeThrough(text: string): string {
124  return [...text].map((character) => `${character}̶`).join('');
125}
126
127/** What the module keeps between events, beside the sync session. */
128interface Mod {
129  session: Session;
130  /** True once `/md-tasks` registered as this mod's; until then a command of that name is someone else's. */
131  hasCommand: boolean;
132  /** The `$.store` key this folder's view is saved under. */
133  viewKey: string;
134  /** Per surface, whether the build refused Text inside a Button. */
135  nestingBySurface: Map<string, { isRefused: boolean }>;
136  /** Surfaces where the spinner's `Client` threw as it was made or failed once drawn; they get the static glyph from then on. */
137  spinnerRefused: Set<string>;
138}
139
140// Claude Code follows `$` only into functions declared at the top of this
141// file, never into a closure or across an import. So everything that takes
142// `$` is declared here, and the files under hooks/ get closures instead.
143
144/**
145 * The session's project root, or undefined on a build that cannot say.
146 *
147 * Every path the mod uses is relative to this. A relative path handed to
148 * `$.fs` or `$.process` as it is would be read from the session's working
149 * directory, which a shell `cd` moves: after an agent ran
150 * `cd spec/<name>`, `spec/*` named nothing beneath it and the pane emptied.
151 * The root stays where the session started.
152 */
153async function rootOf($: EngineInterface): Promise<string | undefined> {
154  return $.session.root().catch(() => undefined);
155}
156
157/** Anchors a relative path to the session's project root; an absolute path is left as it is. */
158async function atRoot($: EngineInterface, path: string): Promise<string> {
159  const root = ABSOLUTE.test(path) ? undefined : await rootOf($);
160  if (root === undefined) return path;
161  return path === '.' || path === '' ? root : `${root.replace(/[\\/]+$/, '')}/${path}`;
162}
163
164/**
165 * The folders to look in from the shell when the project root has no spec
166 * folders: the shell's working directory and those above it, up to the root.
167 */
168async function shellFoldersOf($: EngineInterface): Promise<string[]> {
169  const shell = await $.session.cwd().catch(() => undefined);
170  return shell === undefined ? [] : foldersUpward(shell, await rootOf($));
171}
172
173/**
174 * The working folders the settings add to every session, as the engine
175 * merges them (`permissions.additionalDirectories`), anchored to the project
176 * root when relative.
177 *
178 * The folders added for this session alone, by `/add-dir` or a permission
179 * grant, are not in the settings, and the mods API does not list them; the
180 * `classic.DirectoryAdded` and `tool.call` hooks note those as they happen.
181 */
182async function rememberedFolders($: EngineInterface): Promise<string[]> {
183  const settings = await $.settings.read().catch(() => undefined);
184  const permissions = settings?.permissions as { additionalDirectories?: unknown } | undefined;
185  const folders = Array.isArray(permissions?.additionalDirectories) ? permissions.additionalDirectories : [];
186
187  const resolved: string[] = [];
188  for (const folder of folders) {
189    // A `~` path is the home folder's, which the mod cannot name; it is left out rather than misread.
190    if (typeof folder === 'string' && folder.trim() !== '' && !folder.startsWith('~')) {
191      resolved.push(await atRoot($, folder.trim()));
192    }
193  }
194  return resolved;
195}
196
197/**
198 * Whether the session's permissions let Claude read a file outright: asks the
199 * engine's decision for a Read of it, without running it.
200 *
201 * That is `allow` under the project root, under a folder added with `/add-dir`
202 * or a "don't ask again" grant, and for a path a permission rule allows. Any
203 * other folder is `ask`, in auto mode too (where a classifier, not the
204 * person, would decide), and counts as not readable. The mod's own `$.fs` can
205 * read it either way, which is why the check is asked separately.
206 */
207async function mayRead($: EngineInterface, path: string): Promise<boolean> {
208  const check = await $.tool.check({ tool: 'Read', input: { file_path: path } }).catch(() => undefined);
209  return check?.decision === 'allow';
210}
211
212/** What hooks/sync.ts and hooks/discover.ts need from Claude Code, as closures over `$`. */
213function hostOf($: EngineInterface): Host {
214  return {
215    list: async (path) => $.fs.list(await atRoot($, path)),
216    stat: async (path) => $.fs.stat(await atRoot($, path)),
217    read: async (path) => {
218      // `$.fs.read` also has a bytes form, which this mod never asks for.
219      const content = await $.fs.read(await atRoot($, path));
220      return typeof content === 'string' ? content : '';
221    },
222    shellFolders: () => shellFoldersOf($),
223    foldersUpward: async (start) => foldersUpward(start, await rootOf($)),
224    rememberedFolders: () => rememberedFolders($),
225    mayRead: (path) => mayRead($, path),
226    setGroups: (parsed) => update($, groups, () => parsed),
227    setSource: (folder) => update($, source, () => folder),
228    setError: (message) => update($, error, () => message),
229    toast: (text) => $.ui.toast(text),
230  };
231}
232
233/**
234 * Whether the in-progress spinner may turn: the mod's own setting is on and
235 * Claude Code's `prefersReducedMotion` is not. The counterpart of the
236 * extension's check of VS Code's `accessibility.reducedMotion`.
237 */
238async function isMotionAllowed($: EngineInterface, mod: Mod): Promise<boolean> {
239  if (!mod.session.settings.animateTaskIcons) return false;
240
241  // A settings read that fails says nothing about motion, so the spinner stays.
242  const settings = await $.settings.read().catch(() => undefined);
243  return settings?.prefersReducedMotion !== true;
244}
245
246/** Loads what a folder's pane was left showing: its collapsed rows and the completed filter. */
247async function restoreView($: EngineInterface, mod: Mod, cwd: string): Promise<void> {
248  // By root, so a /clear after a shell `cd` still finds the folder's view.
249  mod.viewKey = `view:${(await rootOf($)) ?? cwd}`;
250  const saved = ((await $.store.get(mod.viewKey)) ?? {}) as { collapsed?: unknown; hideCompleted?: unknown };
251  const ids = Array.isArray(saved.collapsed) ? saved.collapsed.filter((id) => typeof id === 'string') : [];
252  const isHidden =
253    typeof saved.hideCompleted === 'boolean' ? saved.hideCompleted : mod.session.settings.hideCompletedByDefault;
254
255  await update($, collapsed, () => ids);
256  await update($, hideCompleted, () => isHidden);
257}
258
259async function saveView($: EngineInterface, mod: Mod): Promise<void> {
260  await $.store.set(mod.viewKey, { collapsed: await read($, collapsed), hideCompleted: await read($, hideCompleted) });
261}
262
263async function setCollapsed($: EngineInterface, mod: Mod, change: (ids: string[]) => string[]): Promise<void> {
264  await update($, collapsed, (ids) => change(ids));
265  await saveView($, mod);
266}
267
268async function toggleHideCompleted($: EngineInterface, mod: Mod): Promise<void> {
269  await update($, hideCompleted, (isHidden) => !isHidden);
270  await saveView($, mod);
271}
272
273/**
274 * Writes one task's new state character to its file.
275 *
276 * There is no editor buffer or undo: the file is re-read, the bracket is
277 * checked against what the pane drew, and the whole file is written back.
278 * When the bracket is no longer there the list is refreshed and nothing is
279 * written.
280 */
281async function setTaskState($: EngineInterface, mod: Mod, task: TaskNode, nextChar: string): Promise<void> {
282  const host = hostOf($);
283  try {
284    const content = await host.read(task.filePath);
285    const changed = replaceStateChar(content, task.bracketRange, task.char, nextChar, task.rawText);
286    if (changed === null) {
287      await refresh(host, mod.session);
288      $.ui.toast('Task moved on disk; list refreshed');
289      return;
290    }
291
292    await $.fs.write(await atRoot($, task.filePath), changed);
293    await refresh(host, mod.session);
294  } catch (failure) {
295    $.ui.toast(`Markdown Tasks: could not update the task (${failure instanceof Error ? failure.message : failure})`);
296  }
297}
298
299/**
300 * Registers `/md-tasks`.
301 *
302 * Not `/tasks`: Claude Code has a command of that name, and registering it
303 * again does not fail, it lists a second `/tasks` beside the built-in one.
304 */
305async function registerCommand($: EngineInterface, mod: Mod): Promise<void> {
306  try {
307    await $.command.register({
308      name: COMMAND,
309      description: 'Show the Markdown task tree of this folder in a pane',
310      immediate: true,
311    });
312    mod.hasCommand = true;
313  } catch (failure) {
314    $.ui.log(`Markdown Tasks: /${COMMAND} could not be registered (${failure instanceof Error ? failure.message : failure})`);
315  }
316}
317
318/**
319 * Opens a task file at a line in VS Code, through its `code` command.
320 *
321 * `code` is tried by itself first. On Windows it is a script that some builds
322 * cannot start without a shell, so `cmd /c code` is the fallback, and only
323 * for a path `cmd` would not read as anything but a path.
324 *
325 * @param filePath The task file, relative to the session's project root, which the command runs in.
326 * @param line Zero-indexed line, as the parser counts.
327 */
328async function openSource($: EngineInterface, filePath: string, line: number): Promise<void> {
329  const target = `${filePath}:${line + 1}`;
330  // Not the session's working directory, which a shell `cd` may have moved below the root.
331  const root = await rootOf($);
332  const opens = (argv: string[]): Promise<boolean> =>
333    $.process
334      .run(argv, { timeoutMs: OPEN_TIMEOUT_MS, ...(root === undefined ? {} : { cwd: root }) })
335      .then((ran) => ran.exitCode === 0)
336      .catch(() => false);
337
338  if (await opens(['code', '-g', target])) return;
339  if (!CMD_UNSAFE.test(target) && (await opens(['cmd', '/c', 'code', '-g', target]))) return;
340
341  $.ui.toast(`Markdown Tasks: could not open ${target} (is the VS Code "code" command on PATH?)`);
342}
343
344/** Answers the mod's command: opens the pane, and prints a line only when that failed. */
345async function openPane($: EngineInterface, mod: Mod): Promise<{ text?: string }> {
346  try {
347    await refresh(hostOf($), mod.session);
348    await $.ui.open({ id: PANE, title: 'Markdown Tasks', focus: true, closeOnEscape: true });
349    return {};
350  } catch (failure) {
351    return { text: `Markdown Tasks: could not open the pane (${failure instanceof Error ? failure.message : failure})` };
352  }
353}
354
355export const register: Register = (on, options) => {
356  const mod: Mod = {
357    session: createSession(readSettings(options)),
358    hasCommand: false,
359    viewKey: 'view',
360    nestingBySurface: new Map(),
361    spinnerRefused: new Set(),
362  };
363  const { session } = mod;
364
365  // The mod's own work never fails a hook: a hook that throws is skipped, and these all sit on a chain.
366  on('session.start', async ($, e, next) => {
367    const host = hostOf($);
368    await loadTemplate(host, session);
369    await restoreView($, mod, e.cwd).catch(() => undefined);
370    await refresh(host, session);
371    $.clock.every(POLL_MS, () => void poll(host, session));
372    // Last, so a name clash cannot keep the rest from being set up.
373    await registerCommand($, mod);
374
375    return next(e);
376  });
377
378  // /clear, /resume and a fork reset $.state without a session.start.
379  on('classic.SessionStart', { source: ['clear', 'resume', 'fork'] }, async ($, e, next) => {
380    await restoreView($, mod, e.cwd).catch(() => undefined);
381    await refresh(hostOf($), session);
382
383    return next(e);
384  });
385
386  on('command.run', { command: COMMAND }, async ($, e, next) => {
387    // If the name could not be registered, a command called this is not the mod's to answer.
388    if (!mod.hasCommand) return next(e);
389
390    return openPane($, mod);
391  });
392
393  // A folder added with /add-dir is where Claude may work next, so its specs can show at once.
394  on('classic.DirectoryAdded', async ($, e, next) => {
395    if (session.settings.followWorkingFolders && noteWorkingFolder(session, e.directory) && !session.isFromRoot) {
396      await refresh(hostOf($), session).catch(() => undefined);
397    }
398
399    return next(e);
400  });
401
402  on('tool.call', { tool: ['Read', 'Edit', 'Write', 'Glob', 'Grep', 'NotebookEdit'] }, async ($, e, next) => {
403    const ran = await next(e);
404    if (ran.isError === true || ('deny' in ran && ran.deny !== undefined)) return ran;
405
406    const filePath = e.tool === 'NotebookEdit' ? e.notebook_path : e.tool === 'Glob' || e.tool === 'Grep' ? e.path : e.file_path;
407    if (typeof filePath !== 'string' || filePath === '') return ran;
408    const path = filePath.replace(/\\/g, '/');
409
410    // Claude's own edit to a task file shows at once, not at the next poll. By name only: a refresh runs
411    // discovery again, so a file of that name outside the spec folders is never added.
412    const fileName = path.split('/').at(-1) ?? '';
413    let isStale =
414      (e.tool === 'Edit' || e.tool === 'Write') &&
415      session.settings.taskFileNames.some((name) => name.toLowerCase() === fileName.toLowerCase());
416
417    // A file Claude reads or edits, wherever it is, says where Claude is working. That covers a folder
418    // granted from a permission dialog, which no event reports. Glob and Grep name a folder to search.
419    if (session.settings.followWorkingFolders && ABSOLUTE.test(path)) {
420      const folder = e.tool === 'Glob' || e.tool === 'Grep' ? path : path.slice(0, path.lastIndexOf('/'));
421      isStale = (noteWorkingFolder(session, folder) && !session.isFromRoot) || isStale;
422    }
423
424    if (isStale) await refresh(hostOf($), session).catch(() => undefined);
425    return ran;
426  });
427
428  // A spinner sits beside its row's Button, not inside it, so a click on the glyph arrives here instead.
429  on('ui.message', { requestId: PANE }, async ($, e, next) => {
430    const heard = await next(e);
431    const isPress = typeof e.data === 'object' && e.data !== null && (e.data as { press?: unknown }).press === true;
432    const task = isPress ? findTask(await read($, groups).catch(() => []), e.element) : undefined;
433    if (task) {
434      await setTaskState($, mod, task, getNextState(session.template, task.char).char);
435    }
436
437    return heard;
438  });
439
440  // A surface reports a spinner that failed there (in the Desktop Code tab, twenty at once did, and
441  // each drew as a stray glyph). That surface gets the static glyph from then on; the engine redraws
442  // the pane by itself after a fault, so nothing more is asked for here.
443  on('ui.fault', { requestId: PANE }, async ($, e, next) => {
444    mod.spinnerRefused.add(e.surface);
445
446    return next(e);
447  });
448
449  on('ui.render', { component: 'Pane', requestId: PANE }, async ($, e) => {
450    const el = $.ui.resolve(e);
451    const { Box, Button, Text } = el;
452
453    // Asked by surface, not by `'Client' in el`: a table is completed with the elements its surface
454    // lacks, and those draw nothing, so a spinner would vanish there instead of falling back.
455    const hasClient = e.surface === 'terminal' || e.surface === 'desktop';
456    const Client = hasClient && 'Client' in el && !mod.spinnerRefused.has(e.surface) ? el.Client : undefined;
457    const isSpinning = Client !== undefined && (await isMotionAllowed($, mod));
458
459    const list = await read($, groups);
460    const collapsedIds = await read($, collapsed);
461    const isHiding = await read($, hideCompleted);
462    const failure = await read($, error);
463    const pickerKey = await read($, picker);
464    const from = await read($, source);
465
466    const { settings, template } = session;
467    // The terminal styles the Text inside a Button. The Desktop Code tab draws a Button's content as
468    // plain text, ignoring colour, dimming and strikethrough, so there rows are drawn side by side:
469    // the glyph and count as Text beside a Button holding the label, a struck label carrying the stroke
470    // in its characters.
471    const stylesButtonText = e.surface === 'terminal';
472    const rows = buildRows(list, { collapsed: new Set(collapsedIds), hideCompleted: isHiding, template, settings });
473    const columns = Math.max(20, e.props.bodyColumns);
474    const nesting = mod.nestingBySurface.get(e.surface) ?? { isRefused: !stylesButtonText };
475    mod.nestingBySurface.set(e.surface, nesting);
476
477    /** Shortens a label so its row stays on one line of the pane. */
478    const fit = (label: string, used: number): string => {
479      const room = Math.max(8, columns - used);
480      return label.length > room ? `${label.slice(0, room - 1)}…` : label;
481    };
482
483    // A multi-state template gets a control on each task row that opens a picker of every state,
484    // in place of the extension's right-click "Set Task State" menu. Two states need no picker.
485    const hasPicker = template.states.length > 2;
486
487    /**
488     * Indents a row and adds its controls after it: on a task row of a
489     * multi-state template the state picker's, then jump-to-source. Pressing
490     * the row itself still toggles it.
491     */
492    const withControls = (
493      rowElement: RenderElement,
494      key: string,
495      filePath: string,
496      line: number,
497      indent: number,
498      isTask: boolean,
499    ): RenderElement => (
500      <Box key={`r-${key}`} paddingLeft={indent}>
501        {rowElement}
502        {isTask && hasPicker && <Text> </Text>}
503        {isTask && hasPicker && (
504          <Button
505            key={`p-${key}`}
506            plain
507            dimColor
508            // A dropdown arrow, pointing up while the picker is open beneath the row.
509            label={pickerKey === key ? '▴' : '▾'}
510            onPress={() => update($, picker, (open) => (open === key ? null : key))}
511          />
512        )}
513        <Text> </Text>
514        <Button key={`o-${key}`} plain dimColor label="↗" onPress={() => void openSource($, filePath, line)} />
515      </Box>
516    );
517    /** Columns the controls at the end of a row take, which its label must leave free. */
518    const controlsWidth = (isTask: boolean): number => (isTask && hasPicker ? 2 : 1) * CONTROL_WIDTH;
519
520    let spinnersDrawn = 0;
521
522    /**
523     * Draws a task row with the spinner for its glyph. A `Client` cannot sit
524     * inside a Button, so the row is the spinner and then the label as the
525     * Button; the spinner posts its own clicks (see the `ui.message` hook).
526     *
527     * @returns The row; or undefined when the pane already holds MAX_SPINNERS, or this build threw on the `Client`, which is then not tried again here.
528     */
529    const drawSpinning = (row: TaskRow, indent: number, onPress: () => void): RenderElement | undefined => {
530      if (Client === undefined || spinnersDrawn >= MAX_SPINNERS) return undefined;
531
532      try {
533        spinnersDrawn += 1;
534        return (
535          <Box>
536            <Client
537              key={`a-${row.key}`}
538              module="./spinner.tsx"
539              props={row.color === undefined ? {} : { color: row.color }}
540              width={1}
541            />
542            <Text> </Text>
543            <Button
544              key={row.key}
545              plain
546              dimColor={row.isStruck}
547              label={fit(row.task.cleanText, indent + 2 + controlsWidth(true))}
548              onPress={onPress}
549            />
550          </Box>
551        );
552      } catch {
553        mod.spinnerRefused.add(e.surface);
554        return undefined;
555      }
556    };
557
558    const drawRow = (row: Row): RenderElement | RenderElement[] => {
559      const indent = row.depth * INDENT_COLUMNS;
560
561      if (row.kind === 'task') {
562        const lead = `${row.glyph} `;
563        const label = fit(row.task.cleanText, indent + lead.length + controlsWidth(true));
564        const press = (): void => void setTaskState($, mod, row.task, getNextState(template, row.task.char).char);
565        const rowElement = withControls(
566          (row.isAnimated && isSpinning && drawSpinning(row, indent, press)) ||
567          drawPressable(
568            el,
569            {
570              key: row.key,
571              before: [{ text: lead, ...(row.color === undefined ? {} : { color: row.color }) }],
572              label: {
573                text: row.isStruck && !stylesButtonText ? strikeThrough(label) : label,
574                ...(row.isStruck ? { strikethrough: true, dimColor: true } : {}),
575              },
576              after: [],
577              onPress: press,
578            },
579            nesting,
580          ),
581          row.key,
582          row.task.filePath,
583          row.task.line,
584          indent,
585          true,
586        );
587        if (!hasPicker || row.key !== pickerKey) return rowElement;
588
589        // The picker is a Button per state, not a Select: in the terminal an open Select takes no
590        // mouse clicks, and a click there selected and copied text instead.
591        return [
592          rowElement,
593          <Box paddingLeft={indent + lead.length} columnGap={1} flexWrap="wrap">
594            {template.states.map((state, index) => (
595              <Button
596                key={`s-${row.key}-${index}`}
597                {...(state === row.state ? { variant: 'primary' as const } : {})}
598                label={`${stateGlyph(state)} ${state.label}`}
599                onPress={async () => {
600                  // The picker closes on a pick, whether or not the state changed.
601                  await update($, picker, () => null);
602                  if (state.char !== row.task.char) await setTaskState($, mod, row.task, state.char);
603                }}
604              />
605            ))}
606          </Box>,
607        ];
608      }
609
610      const chevron = row.isCollapsed ? '▸ ' : '▾ ';
611      const flag = row.kind === 'heading' && row.isMilestone ? (row.isComplete ? '⚑ ' : '⚐ ') : '';
612      const count = row.count === '' ? '' : ` ${row.count}`;
613      const used = indent + chevron.length + flag.length + count.length + controlsWidth(false);
614
615      const rowElement = drawPressable(
616        el,
617        {
618          key: row.key,
619          before: [
620            { text: chevron },
621            { text: flag, ...(row.kind === 'heading' && row.isComplete ? { color: 'success' } : {}) },
622          ],
623          label: { text: fit(row.kind === 'group' ? row.title : row.label, used), bold: row.kind === 'group' },
624          after: [{ text: count, dimColor: true }],
625          onPress: () =>
626            void setCollapsed($, mod, (ids) =>
627              ids.includes(row.id) ? ids.filter((id) => id !== row.id) : [...ids, row.id],
628            ),
629        },
630        nesting,
631      );
632
633      // A group is the outermost level, so it has no indent to carry.
634      if (row.kind === 'heading') return withControls(rowElement, row.key, row.filePath, row.line, indent, false);
635      // Every row sits in a Box keyed after it, so the whole row can be found as one, whichever form it took.
636      return <Box key={`r-${row.key}`}>{rowElement}</Box>;
637    };
638
639    return (
640      <Box flexDirection="column" width={columns}>
641        <Box columnGap={2} flexWrap="wrap">
642          <Button key="refresh" plain hotkey="r" label="Refresh" onPress={() => void refresh(hostOf($), session)} />
643          <Button
644            key="filter"
645            plain
646            hotkey="f"
647            label={isHiding ? 'Show completed' : 'Hide completed'}
648            onPress={() => void toggleHideCompleted($, mod)}
649          />
650          <Button key="expand" plain hotkey="e" label="Expand all" onPress={() => void setCollapsed($, mod, () => [])} />
651          <Button
652            key="collapse"
653            plain
654            hotkey="c"
655            label="Collapse all"
656            onPress={() => void setCollapsed($, mod, () => collapsibleIds(list))}
657          />
658        </Box>
659        {failure !== null && <Text dimColor>{failure}</Text>}
660        {/* Tasks from somewhere other than the project folder say where they are from. */}
661        {from !== null && list.length > 0 && (
662          <Text dimColor>{fit(`From ${from.split('/').at(-1) ?? from}, where Claude is working`, 0)}</Text>
663        )}
664        {list.length === 0 && failure === null && (
665          <Text dimColor>
666            {`No ${settings.taskFileNames.map((name) => `${settings.specPathPattern}/${name}`).join(' or ')} found in this folder.`}
667          </Text>
668        )}
669        {rows.map(drawRow)}
670      </Box>
671    );
672  });
673};
674
core/mutate.ts 62 lines
1import type { BracketRange } from './types';
2
3/**
4 * Non-destructively replaces the character inside a task's checklist brackets.
5 *
6 * The file may have changed since it was parsed, so the bracket is checked
7 * first: the write only goes ahead when `[`, the expected character and `]`
8 * still sit at the parsed columns of the parsed line.
9 *
10 * @param content Current text of the markdown file.
11 * @param bracketRange Where the parse found the brackets.
12 * @param expectedChar Character the parse found between them.
13 * @param nextChar Character to write in its place.
14 * @param expectedLine The whole line as parsed (`TaskNode.rawText`). When
15 *   given, the line must still read the same: a line inserted above would
16 *   otherwise put a different task's bracket at the same columns.
17 * @returns The new content, every other byte and line ending untouched, or
18 *   `null` when the bracket has moved or holds something else.
19 */
20export function replaceStateChar(
21  content: string,
22  bracketRange: BracketRange,
23  expectedChar: string,
24  nextChar: string,
25  expectedLine?: string
26): string | null {
27  // A toggle swaps one character for one: `[]` and `[xx]` have no single slot to write.
28  if (expectedChar.length !== 1 || nextChar.length !== 1) return null;
29  if (bracketRange.closeBracketCol !== bracketRange.charCol + 1) return null;
30
31  const lineStart = lineStartOffset(content, bracketRange.line);
32  if (lineStart === -1) return null;
33
34  const newline = content.indexOf('\n', lineStart);
35  const lineEnd = newline === -1 ? content.length : newline;
36  const openAt = lineStart + bracketRange.openBracketCol;
37  const charAt = lineStart + bracketRange.charCol;
38  const closeAt = lineStart + bracketRange.closeBracketCol;
39
40  if (bracketRange.openBracketCol < 0 || closeAt >= lineEnd) return null;
41  if (content[openAt] !== '[' || content[charAt] !== expectedChar || content[closeAt] !== ']') return null;
42
43  if (expectedLine !== undefined) {
44    // The parser splits on \r?\n, so a CRLF line's text stops before the \r.
45    const textEnd = content[lineEnd - 1] === '\r' ? lineEnd - 1 : lineEnd;
46    if (content.slice(lineStart, textEnd) !== expectedLine) return null;
47  }
48
49  return content.slice(0, charAt) + nextChar + content.slice(charAt + 1);
50}
51
52/** Offset of the first character of a zero-indexed line, or -1 when the content has fewer lines. */
53function lineStartOffset(content: string, line: number): number {
54  let offset = 0;
55  for (let current = 0; current < line; current++) {
56    const newline = content.indexOf('\n', offset);
57    if (newline === -1) return -1;
58    offset = newline + 1;
59  }
60  return offset;
61}
62
core/templates.ts 238 lines
1import type { StateDefinition } from './types';
2
3export interface StateTemplate {
4  name: string;
5  description: string;
6  defaultState: string;
7  states: StateDefinition[];
8}
9
10export const STANDARD_TEMPLATE: StateTemplate = {
11  name: 'Standard (GFM)',
12  description: 'Standard GitHub-Flavored Markdown checklist states',
13  defaultState: ' ',
14  states: [
15    {
16      char: ' ',
17      id: 'pending',
18      label: 'Not Started',
19      icon: 'circle-large-outline',
20      strikethrough: false,
21      countsAsCompleted: false,
22      nextState: 'x',
23    },
24    {
25      char: 'x',
26      id: 'done',
27      label: 'Done',
28      icon: 'pass-filled',
29      color: 'charts.green',
30      strikethrough: true,
31      countsAsCompleted: true,
32      nextState: ' ',
33    },
34  ],
35};
36
37export const OBSIDIAN_TEMPLATE: StateTemplate = {
38  name: 'Obsidian Tasks',
39  description: 'Obsidian Tasks plugin multi-state task conventions',
40  defaultState: ' ',
41  states: [
42    {
43      char: ' ',
44      id: 'not_started',
45      label: 'Not Started',
46      icon: 'circle-large-outline',
47      strikethrough: false,
48      countsAsCompleted: false,
49      nextState: '/',
50    },
51    {
52      char: '/',
53      id: 'in_progress',
54      label: 'In Progress',
55      icon: 'sync',
56      animatedIcon: 'loading~spin',
57      // Upstream draws in-progress yellow; this mod draws it blue.
58      color: 'charts.blue',
59      strikethrough: false,
60      countsAsCompleted: false,
61      nextState: 'x',
62    },
63    {
64      char: 'x',
65      id: 'done',
66      label: 'Done',
67      icon: 'pass-filled',
68      color: 'charts.green',
69      strikethrough: true,
70      countsAsCompleted: true,
71      nextState: ' ',
72    },
73    {
74      char: '-',
75      id: 'cancelled',
76      label: 'Cancelled',
77      icon: 'circle-slash',
78      color: 'disabledForeground',
79      strikethrough: true,
80      countsAsCompleted: false,
81      nextState: ' ',
82    },
83    {
84      char: '?',
85      id: 'clarification',
86      label: 'Needs Clarification',
87      icon: 'question',
88      color: 'charts.purple',
89      strikethrough: false,
90      countsAsCompleted: false,
91      nextState: ' ',
92    },
93    {
94      char: '!',
95      id: 'important',
96      label: 'Important',
97      icon: 'warning',
98      color: 'charts.red',
99      strikethrough: false,
100      countsAsCompleted: false,
101      nextState: ' ',
102    },
103  ],
104};
105
106/**
107 * Returns the state a bracket character maps to in the template, matching
108 * case-insensitively so `[X]` reads as `[x]`.
109 *
110 * @param template Active state template.
111 * @param char Character found inside the checklist brackets.
112 */
113export function getState(template: StateTemplate, char: string): StateDefinition {
114  const lower = char.toLowerCase();
115
116  // Last match wins, as a later duplicate overwrote an earlier one in the upstream index.
117  for (let index = template.states.length - 1; index >= 0; index--) {
118    const state = template.states[index];
119    if (state && state.char.toLowerCase() === lower) {
120      return state;
121    }
122  }
123
124  // Fallback for unmapped bracket character
125  return {
126    char,
127    id: 'unknown',
128    label: `Custom [${char}]`,
129    icon: 'circle-small-filled',
130    strikethrough: false,
131    countsAsCompleted: false,
132    nextState: template.defaultState,
133  };
134}
135
136/**
137 * Returns the state a task moves to when toggled.
138 *
139 * @param template Active state template.
140 * @param char Character currently inside the checklist brackets.
141 */
142export function getNextState(template: StateTemplate, char: string): StateDefinition {
143  const currentState = getState(template, char);
144  const nextChar = currentState.nextState ?? template.defaultState;
145  return getState(template, nextChar);
146}
147
148/**
149 * Checks that a parsed custom template is usable and fills its optional
150 * top-level fields.
151 *
152 * @param obj Value parsed from a `*.jsonc` template file.
153 * @returns The template, or `null` when it has no usable `states`.
154 */
155export function validateTemplate(obj: unknown): StateTemplate | null {
156  if (typeof obj !== 'object' || obj === null) return null;
157
158  const candidate = obj as Partial<StateTemplate>;
159  if (!Array.isArray(candidate.states) || candidate.states.length === 0) return null;
160
161  for (const state of candidate.states as unknown[]) {
162    if (typeof state !== 'object' || state === null) return null;
163    const { char, id, label } = state as Partial<StateDefinition>;
164    // One character per state: a toggle writes exactly one character between the brackets.
165    if (typeof char !== 'string' || char.length !== 1) return null;
166    if (typeof id !== 'string' || typeof label !== 'string') return null;
167  }
168
169  return {
170    name: typeof candidate.name === 'string' ? candidate.name : 'Custom',
171    description: typeof candidate.description === 'string' ? candidate.description : '',
172    defaultState: typeof candidate.defaultState === 'string' ? candidate.defaultState : ' ',
173    states: candidate.states,
174  };
175}
176
177/**
178 * Parses JSON with comments: strips `//` and block comments and trailing
179 * commas outside strings, then hands the rest to `JSON.parse`.
180 *
181 * @param text Contents of a `*.jsonc` file.
182 * @throws SyntaxError when what remains is not valid JSON.
183 */
184export function parseJsonc(text: string): unknown {
185  let out = '';
186  // A comma is held back, with the whitespace after it, until the next token shows whether it trails.
187  let heldComma = '';
188  let index = text.charCodeAt(0) === 0xfeff ? 1 : 0;
189
190  while (index < text.length) {
191    const ch = text[index] ?? '';
192    const next = text[index + 1] ?? '';
193
194    if (ch === '/' && next === '/') {
195      while (index < text.length && text[index] !== '\n') index++;
196      continue;
197    }
198
199    if (ch === '/' && next === '*') {
200      const end = text.indexOf('*/', index + 2);
201      index = end === -1 ? text.length : end + 2;
202      continue;
203    }
204
205    if (heldComma) {
206      if (/\s/.test(ch)) {
207        heldComma += ch;
208        index++;
209        continue;
210      }
211      out += ch === '}' || ch === ']' ? heldComma.slice(1) : heldComma;
212      heldComma = '';
213    }
214
215    if (ch === ',') {
216      heldComma = ch;
217      index++;
218      continue;
219    }
220
221    if (ch === '"') {
222      const start = index;
223      index++;
224      while (index < text.length && text[index] !== '"') {
225        index += text[index] === '\\' ? 2 : 1;
226      }
227      index++;
228      out += text.slice(start, index);
229      continue;
230    }
231
232    out += ch;
233    index++;
234  }
235
236  return JSON.parse(out + heldComma);
237}
238
core/types.ts 68 lines
1export interface BracketRange {
2  line: number;            // Zero-indexed line in document
3  openBracketCol: number;  // Column index of '['
4  charCol: number;         // Column index of the character inside '[ ]'
5  closeBracketCol: number; // Column index of ']'
6}
7
8export interface StateDefinition {
9  char: string;
10  id: string;
11  label: string;
12  icon: string;
13  animatedIcon?: string;   // Shown instead of `icon` when motion is enabled (e.g. 'loading~spin')
14  color?: string;
15  strikethrough?: boolean;
16  countsAsCompleted?: boolean;
17  nextState?: string;
18}
19
20export interface TaskStats {
21  totalCountable: number;
22  completedCount: number;
23  inProgressCount: number;
24  cancelledCount: number;
25}
26
27export interface TaskNode {
28  type: 'task';
29  id: string;
30  filePath: string;
31  rawText: string;
32  cleanText: string;
33  char: string;
34  bracketRange: BracketRange;
35  line: number;
36  indentation: number;
37  subTasks: TaskNode[];
38  isCompleted: boolean;
39  parentHeadingId?: string;
40}
41
42export interface HeadingNode {
43  type: 'heading';
44  id: string;
45  filePath: string;
46  label: string;
47  level: number;
48  line: number;
49  children: HeadingNode[];
50  tasks: TaskNode[];
51  stats: TaskStats;
52}
53
54export interface SpecGroup {
55  type: 'specGroup';
56  id: string;
57  name: string;
58  folderPath: string;
59  taskFilePath: string;
60  headings: HeadingNode[];
61  rootTasks: TaskNode[];
62  stats: TaskStats;
63  /** First top-level '#' heading, kept for useH1AsGroupName after a plan's headings are trimmed. */
64  h1Label?: string;
65}
66
67export type TaskTreeNode = SpecGroup | HeadingNode | TaskNode;
68
hooks/discover.ts 156 lines
1import type { FsEntry, FsStat } from 'claude-code';
2
3import type { Settings } from './settings';
4
5/**
6 * The file calls discovery needs. Claude Code only follows `$` inside the
7 * hooks module's own file, so the module hands these in as closures over
8 * `$.fs` rather than passing `$` itself.
9 */
10export interface Disk {
11  list: (path: string) => Promise<FsEntry[]>;
12  stat: (path: string) => Promise<FsStat>;
13}
14
15/**
16 * A spec folder that holds a task file. Paths use `/` separators and are
17 * relative to the project root, or absolute when found from another folder.
18 */
19export interface DiscoveredSpec {
20  name: string;
21  folderPath: string;
22  taskFilePath: string;
23  mtimeMs: number;
24}
25
26const SKIPPED_FOLDERS = new Set(['node_modules', 'dist', '.git']);
27
28/**
29 * Finds every task file in the spec folders: each of the configured names, in
30 * each folder.
31 *
32 * `$.fs` has no glob and `list` does not recurse, so the pattern is expanded
33 * one path segment at a time: a segment with `*` lists the folders found so
34 * far and keeps the names it matches, any other segment is appended as is.
35 *
36 * A folder holding more than one task file (both `tasks.md` and
37 * `implementation_plan.md`, say) gives one group per file, each named
38 * `<folder> (<file name>)` so they can be told apart, as in the extension.
39 *
40 * @param disk Lists a folder and stats a path.
41 * @param settings Supplies `specPathPattern` and `taskFileNames`.
42 * @param base The folder the pattern starts from: `.` for the project root, or an absolute folder, which the paths found then start with.
43 * @returns The task files, sorted by name.
44 */
45export async function discover(
46  disk: Disk,
47  settings: Pick<Settings, 'specPathPattern' | 'taskFileNames'>,
48  base = '.'
49): Promise<DiscoveredSpec[]> {
50  const segments = settings.specPathPattern
51    .replace(/\\/g, '/')
52    .split('/')
53    .filter((segment) => segment !== '' && segment !== '.');
54
55  let folders = [base];
56  for (const segment of segments) {
57    if (!segment.includes('*')) {
58      folders = folders.map((folder) => join(folder, segment));
59      continue;
60    }
61
62    const matches = segmentMatcher(segment);
63    const expanded: string[] = [];
64    for (const folder of folders) {
65      // A folder named by the pattern but absent on disk is not an error: it holds no specs.
66      const entries = await disk.list(folder).catch(() => []);
67      for (const entry of entries) {
68        if (entry.kind === 'dir' && !SKIPPED_FOLDERS.has(entry.name) && matches(entry.name)) {
69          expanded.push(join(folder, entry.name));
70        }
71      }
72    }
73    folders = expanded;
74  }
75
76  const specs: DiscoveredSpec[] = [];
77  for (const folder of folders) {
78    const found: DiscoveredSpec[] = [];
79    for (const fileName of settings.taskFileNames) {
80      const taskFilePath = join(folder, fileName);
81      const stat = await disk.stat(taskFilePath).catch(() => undefined);
82      if (stat?.kind === 'file') {
83        found.push({ name: baseName(folder), folderPath: folder, taskFilePath, mtimeMs: stat.mtimeMs });
84      }
85    }
86    for (const spec of found) {
87      specs.push(found.length > 1 ? { ...spec, name: `${spec.name} (${baseName(spec.taskFilePath)})` } : spec);
88    }
89  }
90
91  return specs.sort((a, b) => a.name.localeCompare(b.name));
92}
93
94/**
95 * The folders to look in from a place Claude is working when the project root
96 * holds no spec folders: that folder and each folder above it, nearest first.
97 *
98 * Claude works below the project it is on (its shell in `packages/app/src`, or
99 * deep in `node_modules`; a file it reads in `src/`), so the project is the
100 * nearest of these with spec folders, not the folder itself. A walk that starts
101 * inside `node_modules`, `.git` or `dist` starts above it, as those never hold a
102 * project's specs. It stops at the project root, which was looked in already,
103 * and below the top of the drive.
104 *
105 * @param start Where Claude is working: the shell's folder, a working folder, or a folder Claude touched a file in.
106 * @param root The session's project root, if known.
107 * @returns Absolute folders with `/` separators; empty when the start is the root.
108 */
109export function foldersUpward(start: string, root: string | undefined): string[] {
110  const parts = normalize(start).split('/');
111  const skipped = parts.findIndex((part) => SKIPPED_FOLDERS.has(part));
112  let folder = (skipped === -1 ? parts : parts.slice(0, skipped)).join('/');
113  const stop = root === undefined ? undefined : pathKey(root);
114
115  const folders: string[] = [];
116  // A path with no separator after its first character is a drive or the top of the file system.
117  while (folder.lastIndexOf('/') > 0) {
118    if (pathKey(folder) === stop) break;
119    folders.push(folder);
120    folder = folder.slice(0, folder.lastIndexOf('/'));
121  }
122  return folders;
123}
124
125/**
126 * A path in a form that compares equal for the same folder: `/` separators,
127 * no trailing one, and lower case on a Windows drive, where case does not
128 * tell paths apart.
129 */
130export function pathKey(path: string): string {
131  const normalized = normalize(path);
132  return /^[a-zA-Z]:/.test(normalized) ? normalized.toLowerCase() : normalized;
133}
134
135function normalize(path: string): string {
136  return path.replace(/\\/g, '/').replace(/\/+$/, '');
137}
138
139/** Turns one pattern segment into a whole-name test; any run of `*` matches any characters. */
140function segmentMatcher(segment: string): (name: string) => boolean {
141  const source = segment
142    .split(/\*+/)
143    .map((literal) => literal.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'))
144    .join('.*');
145  const pattern = new RegExp(`^${source}$`, 'i');
146  return (name) => pattern.test(name);
147}
148
149function join(folder: string, name: string): string {
150  return folder === '.' ? name : `${folder}/${name}`;
151}
152
153function baseName(folder: string): string {
154  return folder.split('/').at(-1) ?? folder;
155}
156
hooks/rows.ts 224 lines
1import { isMilestoneHeading } from '../core/milestones';
2import type { StateTemplate } from '../core/templates';
3import { getState } from '../core/templates';
4import type { HeadingNode, SpecGroup, StateDefinition, TaskNode, TaskStats } from '../core/types';
5import type { Settings } from './settings';
6
7interface RowBase {
8  /** Element key: short and free of path characters, unlike `id`. */
9  key: string;
10  /** The node's id from the parse, which the collapsed list is kept by. */
11  id: string;
12  /** Nesting depth; the pane indents two columns per level. */
13  depth: number;
14}
15
16export interface GroupRow extends RowBase {
17  kind: 'group';
18  title: string;
19  count: string;
20  isCollapsed: boolean;
21}
22
23export interface HeadingRow extends RowBase {
24  kind: 'heading';
25  label: string;
26  line: number;
27  filePath: string;
28  count: string;
29  isCollapsed: boolean;
30  isMilestone: boolean;
31  /** True when the heading has tasks and all of them are completed. */
32  isComplete: boolean;
33}
34
35export interface TaskRow extends RowBase {
36  kind: 'task';
37  task: TaskNode;
38  state: StateDefinition;
39  glyph: string;
40  /** A theme key for the glyph, or undefined for the default text colour. */
41  color: string | undefined;
42  /** True when the label is drawn struck through and dimmed. */
43  isStruck: boolean;
44  /**
45   * True when the state names an `animatedIcon`. The pane has one animation,
46   * the spinner, so any value means that; whether it is shown is the pane's
47   * call (the setting, reduced motion, the surface).
48   */
49  isAnimated: boolean;
50}
51
52export type Row = GroupRow | HeadingRow | TaskRow;
53
54export interface RowOptions {
55  collapsed: ReadonlySet<string>;
56  hideCompleted: boolean;
57  template: StateTemplate;
58  settings: Pick<Settings, 'showProgressCount' | 'useH1AsGroupName' | 'milestoneKeywords' | 'strikeThroughCompleted'>;
59}
60
61// The extension names VS Code codicons and theme colours; the pane draws text, so each maps to a glyph and a theme key.
62const GLYPH_BY_ICON: Record<string, string> = {
63  'circle-large-outline': '○',
64  sync: '◐',
65  'pass-filled': '●',
66  'circle-slash': '⊘',
67  question: '?',
68  warning: '!',
69  'circle-small-filled': '•',
70};
71
72const THEME_KEY_BY_COLOR: Record<string, string> = {
73  'charts.green': 'success',
74  'charts.yellow': 'warning',
75  'charts.red': 'error',
76  'charts.purple': 'permission',
77  'charts.blue': 'suggestion',
78  'charts.orange': 'warning',
79};
80
81/**
82 * Flattens the parsed groups into the rows the pane draws, top to bottom,
83 * leaving out what a collapsed parent or the "hide completed" filter hides.
84 *
85 * Filtering never changes a count: counts come from the parse.
86 */
87export function buildRows(groups: readonly SpecGroup[], options: RowOptions): Row[] {
88  const rows: Row[] = [];
89
90  groups.forEach((group, groupIndex) => {
91    const isCollapsed = options.collapsed.has(group.id);
92    rows.push({
93      kind: 'group',
94      key: `g-${groupIndex}`,
95      id: group.id,
96      depth: 0,
97      title: groupTitle(group, options),
98      count: countText(group.stats, options, true),
99      isCollapsed,
100    });
101    if (isCollapsed) return;
102
103    // Top-level headings always show, as in the extension; only nested ones are filtered.
104    for (const heading of group.headings) {
105      addHeading(rows, heading, groupIndex, 1, options);
106    }
107    addTasks(rows, group.rootTasks, groupIndex, 1, options);
108  });
109
110  return rows;
111}
112
113/**
114 * Finds the task a task row's key names, in the groups as they are now.
115 *
116 * A key is `t-<group index>-<line>`; the spinner of that row is keyed with an
117 * `a-` in front, so either form is accepted.
118 *
119 * @returns The task, or undefined when the key is no task's or the file has since changed shape.
120 */
121export function findTask(groups: readonly SpecGroup[], key: string): TaskNode | undefined {
122  const match = /^(?:a-)?t-(\d+)-(\d+)$/.exec(key);
123  const group = match ? groups[Number(match[1])] : undefined;
124  if (!match || !group) return undefined;
125
126  const line = Number(match[2]);
127  const among = (tasks: TaskNode[]): TaskNode | undefined => {
128    for (const task of tasks) {
129      const found = task.line === line ? task : among(task.subTasks);
130      if (found) return found;
131    }
132    return undefined;
133  };
134  const under = (headings: HeadingNode[]): TaskNode | undefined => {
135    for (const heading of headings) {
136      const found = among(heading.tasks) ?? under(heading.children);
137      if (found) return found;
138    }
139    return undefined;
140  };
141
142  return among(group.rootTasks) ?? under(group.headings);
143}
144
145/** The glyph a state draws with: its icon's, else its own character, else a dot. */
146export function stateGlyph(state: StateDefinition): string {
147  return GLYPH_BY_ICON[state.icon] ?? (state.char.trim() || '•');
148}
149
150/** Ids of everything that can collapse: every spec group and heading. */
151export function collapsibleIds(groups: readonly SpecGroup[]): string[] {
152  const ids: string[] = [];
153  const visit = (heading: HeadingNode): void => {
154    ids.push(heading.id);
155    heading.children.forEach(visit);
156  };
157
158  for (const group of groups) {
159    ids.push(group.id);
160    group.headings.forEach(visit);
161  }
162  return ids;
163}
164
165function addHeading(rows: Row[], heading: HeadingNode, groupIndex: number, depth: number, options: RowOptions): void {
166  const { totalCountable, completedCount } = heading.stats;
167  const isComplete = totalCountable > 0 && completedCount === totalCountable;
168  const isCollapsed = options.collapsed.has(heading.id);
169
170  rows.push({
171    kind: 'heading',
172    key: `h-${groupIndex}-${heading.line}`,
173    id: heading.id,
174    depth,
175    label: heading.label,
176    line: heading.line,
177    filePath: heading.filePath,
178    count: countText(heading.stats, options, true),
179    isCollapsed,
180    isMilestone: isMilestoneHeading(heading.label, options.settings.milestoneKeywords),
181    isComplete,
182  });
183  if (isCollapsed) return;
184
185  for (const child of heading.children) {
186    const childDone = child.stats.totalCountable > 0 && child.stats.completedCount === child.stats.totalCountable;
187    if (options.hideCompleted && childDone) continue;
188    addHeading(rows, child, groupIndex, depth + 1, options);
189  }
190  addTasks(rows, heading.tasks, groupIndex, depth + 1, options);
191}
192
193function addTasks(rows: Row[], tasks: TaskNode[], groupIndex: number, depth: number, options: RowOptions): void {
194  for (const task of tasks) {
195    if (options.hideCompleted && task.isCompleted) continue;
196
197    const state = getState(options.template, task.char);
198    rows.push({
199      kind: 'task',
200      key: `t-${groupIndex}-${task.line}`,
201      id: task.id,
202      depth,
203      task,
204      state,
205      glyph: stateGlyph(state),
206      color: state.color === undefined ? undefined : THEME_KEY_BY_COLOR[state.color],
207      isStruck: state.strikethrough === true && options.settings.strikeThroughCompleted,
208      isAnimated: state.animatedIcon !== undefined,
209    });
210    addTasks(rows, task.subTasks, groupIndex, depth + 1, options);
211  }
212}
213
214function groupTitle(group: SpecGroup, options: RowOptions): string {
215  // Recorded at parse time, since a plan's H1 is trimmed away with its other sections.
216  if (options.settings.useH1AsGroupName && group.h1Label) return group.h1Label;
217  return group.name;
218}
219
220function countText(stats: TaskStats, options: RowOptions, saysWhenEmpty: boolean): string {
221  if (stats.totalCountable === 0) return saysWhenEmpty ? '(No tasks)' : '';
222  return options.settings.showProgressCount ? `(${stats.completedCount}/${stats.totalCountable})` : '';
223}
224
hooks/settings.ts 89 lines
1import type { PluginOptions } from 'claude-code';
2
3export type TemplateName = 'Standard (GFM)' | 'Obsidian Tasks' | 'Custom';
4
5/** The mod's `userConfig` values, typed and with defaults filled in. */
6export interface Settings {
7  specPathPattern: string;
8  /** The task file names looked for in each spec folder, in order, never empty. */
9  taskFileNames: string[];
10  /** When the project root has no spec folders, look from the shell's folder upward instead. */
11  followShellFolder: boolean;
12  /** When the project root has no spec folders, also look from the session's added working folders and the folders Claude touches files in. */
13  followWorkingFolders: boolean;
14  /** Show a task file found outside the project root only when the session's permissions let Claude read it outright. */
15  requireReadPermission: boolean;
16  stateTemplate: TemplateName;
17  customTemplatePath: string;
18  strikeThroughCompleted: boolean;
19  animateTaskIcons: boolean;
20  showProgressCount: boolean;
21  hideCompletedByDefault: boolean;
22  useH1AsGroupName: boolean;
23  milestoneKeywords: string[];
24}
25
26export const DEFAULT_TASK_FILE_NAMES = ['tasks.md', 'implementation_plan.md'];
27
28/**
29 * The task file names to discover, as the extension resolves them: the
30 * configured list, then the deprecated single `taskFileName` when it is set,
31 * trimmed and de-duplicated case-insensitively, keeping the first spelling
32 * seen. An empty result falls back to the defaults.
33 *
34 * @param list Comma-separated names, as the `taskFileNames` option holds them.
35 * @param legacyName The deprecated `taskFileName` option, or empty.
36 */
37export function resolveTaskFileNames(list: string, legacyName: string): string[] {
38  const resolved: string[] = [];
39  const seen = new Set<string>();
40  for (const raw of [...list.split(','), legacyName]) {
41    const name = raw.trim();
42    if (name !== '' && !seen.has(name.toLowerCase())) {
43      seen.add(name.toLowerCase());
44      resolved.push(name);
45    }
46  }
47  return resolved.length > 0 ? resolved : [...DEFAULT_TASK_FILE_NAMES];
48}
49
50/**
51 * Reads the options Claude Code hands `register` into typed settings.
52 *
53 * A value of the wrong type, or an empty path, falls back to the default the
54 * manifest declares, so a hand-edited settings file cannot break the pane.
55 *
56 * @param options The `userConfig` values, as given to `register(on, options)`.
57 */
58export function readSettings(options: PluginOptions): Settings {
59  const text = (key: string, fallback: string): string => {
60    const value = options[key];
61    return typeof value === 'string' && value.trim() !== '' ? value.trim() : fallback;
62  };
63  const flag = (key: string, fallback: boolean): boolean => {
64    const value = options[key];
65    return typeof value === 'boolean' ? value : fallback;
66  };
67
68  const template = text('stateTemplate', 'Standard (GFM)');
69
70  return {
71    specPathPattern: text('specPathPattern', 'spec/*'),
72    taskFileNames: resolveTaskFileNames(text('taskFileNames', ''), text('taskFileName', '')),
73    followShellFolder: flag('followShellFolder', true),
74    followWorkingFolders: flag('followWorkingFolders', true),
75    requireReadPermission: flag('requireReadPermission', true),
76    stateTemplate: template === 'Obsidian Tasks' || template === 'Custom' ? template : 'Standard (GFM)',
77    customTemplatePath: text('customTemplatePath', ''),
78    strikeThroughCompleted: flag('strikeThroughCompleted', true),
79    animateTaskIcons: flag('animateTaskIcons', true),
80    showProgressCount: flag('showProgressCount', true),
81    hideCompletedByDefault: flag('hideCompletedByDefault', false),
82    useH1AsGroupName: flag('useH1AsGroupName', false),
83    milestoneKeywords: text('milestoneKeywords', 'Milestone')
84      .split(',')
85      .map((keyword) => keyword.trim())
86      .filter((keyword) => keyword !== ''),
87  };
88}
89
hooks/sync.ts 252 lines
1import { parseTasks } from '../core/parse';
2import { isPlanFile, toPlanTaskSection } from '../core/plan';
3import type { StateTemplate } from '../core/templates';
4import { OBSIDIAN_TEMPLATE, STANDARD_TEMPLATE, parseJsonc, validateTemplate } from '../core/templates';
5import type { SpecGroup } from '../core/types';
6import { discover, pathKey } from './discover';
7import type { DiscoveredSpec, Disk } from './discover';
8import type { Settings } from './settings';
9
10/** How often the poll looks for new spec folders, in polls. Between those it only stats the known files. */
11const REDISCOVER_EVERY = 10;
12
13/**
14 * What syncing needs from Claude Code. The hooks module builds one per event
15 * as closures over `$`, because `$` itself may not cross an import.
16 */
17export interface Host extends Disk {
18  read: (path: string) => Promise<string>;
19  /** The shell's folder and those above it, nearest first (see `foldersUpward`). */
20  shellFolders: () => Promise<string[]>;
21  /** A folder and those above it up to the project root, nearest first (see `foldersUpward`). */
22  foldersUpward: (start: string) => Promise<string[]>;
23  /** The working folders the settings keep for every session (`permissions.additionalDirectories`), absolute. */
24  rememberedFolders: () => Promise<string[]>;
25  /** Whether the session's permissions let Claude read a file outright, without asking anyone. */
26  mayRead: (path: string) => Promise<boolean>;
27  /** Writes the parsed groups to state, which redraws the pane. */
28  setGroups: (groups: SpecGroup[]) => Promise<unknown>;
29  /** Writes to state the folder the groups were found in, or null when it is the project root. */
30  setSource: (folder: string | null) => Promise<unknown>;
31  /** Writes the error line to state; null clears it. */
32  setError: (message: string | null) => Promise<unknown>;
33  toast: (text: string) => void;
34}
35
36/**
37 * What the module keeps between events. These are module variables, so a hot
38 * reload starts them over; everything a drawing reads is in `$.state` instead.
39 */
40export interface Session {
41  settings: Settings;
42  template: StateTemplate;
43  /** The task files as last read, with the modification times they had then. */
44  specs: DiscoveredSpec[];
45  polls: number;
46  isPolling: boolean;
47  /** The error last written to state, so an unchanged one does not redraw the pane. */
48  shownError: string | null | undefined;
49  /**
50   * Folders Claude has worked in this session, most recent first: those added
51   * with `/add-dir` and those it read or edited a file in. A module variable,
52   * not `$.state`, so a `/clear` keeps it, as Claude Code keeps the session's
53   * working folders.
54   */
55  workingFolders: string[];
56  /** Whether the last refresh found task files in the project root, which then wins over every other folder. */
57  isFromRoot: boolean;
58}
59
60/** How many of the folders Claude worked in are remembered; the oldest is dropped past this. */
61const MAX_WORKING_FOLDERS = 5;
62
63export function createSession(settings: Settings): Session {
64  return {
65    settings,
66    template: STANDARD_TEMPLATE,
67    specs: [],
68    polls: 0,
69    isPolling: false,
70    shownError: undefined,
71    workingFolders: [],
72    isFromRoot: false,
73  };
74}
75
76/**
77 * Notes a folder Claude has just worked in, moving it to the front of the
78 * session's working folders.
79 *
80 * @returns Whether the most recent folder changed, so a refresh could show something new.
81 */
82export function noteWorkingFolder(session: Session, folder: string): boolean {
83  const key = pathKey(folder);
84  if (session.workingFolders[0] !== undefined && pathKey(session.workingFolders[0]) === key) return false;
85
86  const rest = session.workingFolders.filter((known) => pathKey(known) !== key);
87  session.workingFolders = [folder, ...rest].slice(0, MAX_WORKING_FOLDERS);
88  return true;
89}
90
91/**
92 * Picks the session's state template from the settings, reading a custom one
93 * from disk. An unreadable or invalid custom template falls back to Standard.
94 */
95export async function loadTemplate(host: Host, session: Session): Promise<void> {
96  const { stateTemplate, customTemplatePath } = session.settings;
97  session.template = STANDARD_TEMPLATE;
98
99  if (stateTemplate === 'Obsidian Tasks') {
100    session.template = OBSIDIAN_TEMPLATE;
101  } else if (stateTemplate === 'Custom' && customTemplatePath !== '') {
102    const custom = await host
103      .read(customTemplatePath)
104      .then((text) => validateTemplate(parseJsonc(text)))
105      .catch(() => null);
106    if (custom) {
107      session.template = custom;
108    } else {
109      host.toast('Markdown Tasks: invalid custom template, using Standard (GFM)');
110    }
111  }
112}
113
114/**
115 * The places to look from when the project root has no spec folders, each
116 * as a walk from where Claude is working up to the root, in order of
117 * preference: the shell's folder, then the folders Claude worked in this
118 * session (most recent first), then those the settings keep.
119 */
120async function walksFrom(host: Host, session: Session): Promise<string[][]> {
121  const { settings } = session;
122  const walks: string[][] = [];
123  if (settings.followShellFolder) walks.push(await host.shellFolders());
124  if (settings.followWorkingFolders) {
125    for (const start of [...session.workingFolders, ...(await host.rememberedFolders())]) {
126      walks.push(await host.foldersUpward(start));
127    }
128  }
129  return walks;
130}
131
132/**
133 * Finds the task files to show: the project root's, or, when it has none,
134 * those of the first place Claude is working that has spec folders (see
135 * `walksFrom`). In each walk, the nearest folder with spec folders is the
136 * project there. That covers an agent working in another repository, while
137 * the session's root stays where it started.
138 *
139 * With `requireReadPermission` on, a file found that way is kept only when
140 * the session's permissions let Claude read it outright: it is under one of
141 * the session's working folders, or a permission rule allows it. A project
142 * with none kept gives way to the next place.
143 *
144 * @returns The task files, and the folder they were found in when it is not the project root.
145 */
146export async function findSpecs(
147  host: Host,
148  session: Session
149): Promise<{ specs: DiscoveredSpec[]; source: string | null }> {
150  const { settings } = session;
151  const atRoot = await discover(host, settings);
152  if (atRoot.length > 0) return { specs: atRoot, source: null };
153
154  const looked = new Set<string>();
155  for (const walk of await walksFrom(host, session)) {
156    for (const folder of walk) {
157      // Walks run upward, so one that reaches a folder an earlier walk looked in has nothing new above it.
158      if (looked.has(pathKey(folder))) break;
159      looked.add(pathKey(folder));
160
161      const found = await discover(host, settings, folder);
162      if (found.length === 0) continue;
163
164      const specs: DiscoveredSpec[] = [];
165      for (const spec of found) {
166        if (!settings.requireReadPermission || (await host.mayRead(spec.taskFilePath))) specs.push(spec);
167      }
168      if (specs.length > 0) return { specs, source: folder };
169      // The folders above this project are other projects, so a project Claude may not read ends this walk.
170      break;
171    }
172  }
173  return { specs: atRoot, source: null };
174}
175
176/**
177 * Re-reads every task file and hands the parsed groups to the host. On a read
178 * or parse error the previous groups stay and the error is shown instead.
179 */
180export async function refresh(host: Host, session: Session): Promise<void> {
181  try {
182    const { specs, source } = await findSpecs(host, session);
183    const parsed: SpecGroup[] = [];
184    for (const spec of specs) {
185      const content = await host.read(spec.taskFilePath);
186      const group = parseTasks(content, spec.name, spec.taskFilePath, spec.folderPath, session.template);
187      // A plan shows only its task section, as in the extension's tree.
188      parsed.push(isPlanFile(spec.taskFilePath) ? toPlanTaskSection(group) : group);
189    }
190
191    session.specs = specs;
192    session.isFromRoot = source === null && specs.length > 0;
193    await host.setGroups(parsed);
194    await host.setSource(source);
195    await showError(host, session, null);
196  } catch (failure) {
197    await showError(host, session, `Could not read the task files: ${describe(failure)}`);
198  }
199}
200
201/**
202 * One tick of the live sync: refreshes only when a known task file's
203 * modification time changed, or, every tenth tick, when discovery finds a
204 * different set of spec folders. The mods API has no file watcher.
205 */
206export async function poll(host: Host, session: Session): Promise<void> {
207  // A slow disk must not stack ticks up behind one another.
208  if (session.isPolling) return;
209  session.isPolling = true;
210
211  try {
212    session.polls += 1;
213    const current =
214      session.polls % REDISCOVER_EVERY === 0
215        ? (await findSpecs(host, session)).specs
216        : await restat(host, session.specs);
217    if (signature(current) !== signature(session.specs)) {
218      await refresh(host, session);
219    }
220  } catch (failure) {
221    await showError(host, session, `Could not check the task files: ${describe(failure)}`);
222  } finally {
223    session.isPolling = false;
224  }
225}
226
227/** The known task files with their modification times now; a file that has gone is left out. */
228async function restat(disk: Disk, specs: DiscoveredSpec[]): Promise<DiscoveredSpec[]> {
229  const current: DiscoveredSpec[] = [];
230  for (const spec of specs) {
231    const stat = await disk.stat(spec.taskFilePath).catch(() => undefined);
232    if (stat?.kind === 'file') {
233      current.push({ ...spec, mtimeMs: stat.mtimeMs });
234    }
235  }
236  return current;
237}
238
239function signature(specs: DiscoveredSpec[]): string {
240  return specs.map((spec) => `${spec.taskFilePath}@${spec.mtimeMs}`).join('|');
241}
242
243async function showError(host: Host, session: Session, message: string | null): Promise<void> {
244  if (session.shownError === message) return;
245  session.shownError = message;
246  await host.setError(message);
247}
248
249function describe(failure: unknown): string {
250  return failure instanceof Error ? failure.message : String(failure);
251}
252
hooks/spinner.tsx 36 lines
1import type { ClientModule } from 'claude-code';
2
3const FRAMES = ['⠋', '⠙', '⠹', '⠸', '⠼', '⠴', '⠦', '⠧', '⠇', '⠏'];
4// Slower than the 80 ms a terminal spinner usually runs at. The Desktop Code tab stops spinners that
5// redraw too often in total: twenty at 80 ms failed there, twelve did not, and twenty at 160 ms did not.
6// With MAX_SPINNERS in register.tsx this keeps a full pane at 100 redraws a second.
7const FRAME_MS = 120;
8
9/**
10 * The in-progress spinner: one cell that steps through the frames on the
11 * surface's own clock, so the pane's hook never redraws for it.
12 *
13 * A surface module, drawn where the pane puts a `Client` naming this file. It
14 * has no `$`: a click on it is posted to the hooks module, which treats it as
15 * a press on the task's row.
16 *
17 * @param props `color`, a theme key or raw colour for the glyph; absent, the default text colour.
18 */
19const Spinner: ClientModule<{ color?: string }, number> = (props, surface) => {
20  const { Text } = surface.elements;
21
22  // State is undefined only on the first call, which is when the timer and the listener are set up.
23  if (surface.state === undefined) {
24    surface.setState(0);
25    surface.every(FRAME_MS, () => surface.setState(((surface.state ?? 0) + 1) % FRAMES.length));
26    surface.onPointer((event) => {
27      if (event.type === 'down') surface.post({ press: true });
28    });
29  }
30
31  const frame = FRAMES[surface.state ?? 0] ?? '⠋';
32  return props.color === undefined ? <Text>{frame}</Text> : <Text color={props.color}>{frame}</Text>;
33};
34
35export default Spinner;
36
core/milestones.ts 22 lines
1/**
2 * Whether a heading counts as a milestone: its label starts with one of the
3 * keywords as a whole word, in any case, where letters, digits and `_` all
4 * belong to a word. A keyword later in the heading, in the plural, or inside an
5 * identifier (`Milestone_notes`) does not count, so notes, bookmarks and
6 * overview sections ("Milestones") can mention a milestone without becoming one.
7 *
8 * @param label Heading label, markdown formatting already stripped.
9 * @param keywords Configured milestone keywords.
10 */
11export function isMilestoneHeading(label: string, keywords: string[]): boolean {
12  if (!label || !keywords || keywords.length === 0) return false;
13  const normalizedLabel = label.trim().toLowerCase();
14  return keywords.some((kw) => {
15    const trimmed = kw.trim().toLowerCase();
16    if (!trimmed) return false;
17    const escaped = trimmed.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
18    const pattern = new RegExp(`^${escaped}([^a-zA-Z0-9_]|$)`, 'i');
19    return pattern.test(normalizedLabel);
20  });
21}
22
core/parse.ts 302 lines
1import type { BracketRange, HeadingNode, SpecGroup, TaskNode, TaskStats } from './types';
2import type { StateTemplate } from './templates';
3import { getState } from './templates';
4
5// Regular expressions for ATX headings and checklist items
6const HEADING_REGEX = /^(\#{1,6})\s+(.+)$/;
7const TASK_REGEX = /^(\s*)[-*+]\s+\[(.*?)\]\s*(.*)$/;
8
9/**
10 * Parses markdown text into a structured SpecGroup model.
11 *
12 * @param content Full text content of the markdown file.
13 * @param specName Name of the spec folder/group.
14 * @param filePath Path of the task markdown file.
15 * @param folderPath Path of the parent spec folder.
16 * @param template State template that decides which bracket characters count as completed.
17 */
18export function parseTasks(
19  content: string,
20  specName: string,
21  filePath: string,
22  folderPath: string,
23  template: StateTemplate
24): SpecGroup {
25  const lines = content.split(/\r?\n/);
26  const rootTasks: TaskNode[] = [];
27  const headings: HeadingNode[] = [];
28
29  // Heading stack to manage depth hierarchy (levels 1-6)
30  const headingStack: HeadingNode[] = [];
31
32  // Task stack within the current heading to manage indented sub-tasks
33  let taskStack: TaskNode[] = [];
34  let currentHeading: HeadingNode | undefined = undefined;
35
36  const addTask = (lineIndex: number, lineStr: string, indentLevel: number, char: string, text: string): void => {
37    const cleanText = stripMarkdownFormatting(text.trim());
38
39    // Calculate bracket range columns
40    const openBracketCol = lineStr.indexOf('[');
41    const closeBracketCol = lineStr.indexOf(']', openBracketCol);
42    const bracketRange: BracketRange = {
43      line: lineIndex,
44      openBracketCol,
45      charCol: openBracketCol + 1,
46      closeBracketCol,
47    };
48
49    const stateDef = getState(template, char);
50    const isCompleted = stateDef.countsAsCompleted ?? (char.toLowerCase() === 'x');
51
52    const taskNode: TaskNode = {
53      type: 'task',
54      id: `${filePath}#T${lineIndex}`,
55      filePath,
56      rawText: lineStr,
57      cleanText: cleanText || '(Empty task)',
58      char,
59      bracketRange,
60      line: lineIndex,
61      indentation: indentLevel,
62      subTasks: [],
63      isCompleted,
64      parentHeadingId: currentHeading?.id,
65    };
66
67    // Find parent task in taskStack with lower indentation
68    while ((taskStack.at(-1)?.indentation ?? -Infinity) >= indentLevel) {
69      taskStack.pop();
70    }
71
72    const parentTask = taskStack.at(-1);
73    if (parentTask) {
74      // Indented subtask
75      parentTask.subTasks.push(taskNode);
76    } else {
77      // Top-level task in current heading scope
78      attachTaskToScope(taskNode, currentHeading, rootTasks);
79    }
80
81    taskStack.push(taskNode);
82  };
83
84  for (let lineIndex = 0; lineIndex < lines.length; lineIndex++) {
85    const lineStr = lines[lineIndex] ?? '';
86
87    // 1. Check for ATX Heading (# ... ######)
88    const headingMatch = lineStr.match(HEADING_REGEX);
89    if (headingMatch) {
90      const level = (headingMatch[1] ?? '').length;
91      const headingText = (headingMatch[2] ?? '').trim();
92      const label = stripMarkdownFormatting(headingText);
93
94      // Pop headingStack until we find a parent with a strictly lower level
95      while ((headingStack.at(-1)?.level ?? 0) >= level) {
96        headingStack.pop();
97      }
98
99      // Heading written as a checklist item (### - [x] Task 1.1) is a task, not a section
100      const headingTaskMatch = headingText.match(TASK_REGEX);
101      if (headingTaskMatch) {
102        currentHeading = headingStack.at(-1);
103        // Negative indentation: list items below nest under it, deeper heading tasks nest under shallower ones
104        addTask(lineIndex, lineStr, level - 7, headingTaskMatch[2] ?? '', headingTaskMatch[3] ?? '');
105        continue;
106      }
107
108      const newHeading: HeadingNode = {
109        type: 'heading',
110        id: `${filePath}#H${lineIndex}_L${level}`,
111        filePath,
112        label,
113        level,
114        line: lineIndex,
115        children: [],
116        tasks: [],
117        stats: { totalCountable: 0, completedCount: 0, inProgressCount: 0, cancelledCount: 0 },
118      };
119
120      // Reset task stack for the new heading
121      taskStack = [];
122      currentHeading = newHeading;
123
124      const parentHeading = headingStack.at(-1);
125      if (parentHeading) {
126        // Child heading of the top of the stack
127        parentHeading.children.push(newHeading);
128      } else {
129        // Top-level heading within this spec document
130        headings.push(newHeading);
131      }
132
133      headingStack.push(newHeading);
134      continue;
135    }
136
137    // 2. Check for Checklist Item (- [ ] ...)
138    const taskMatch = lineStr.match(TASK_REGEX);
139    if (taskMatch) {
140      const indentLevel = calculateIndentation(taskMatch[1] ?? '');
141      addTask(lineIndex, lineStr, indentLevel, taskMatch[2] ?? '', taskMatch[3] ?? '');
142    }
143  }
144
145  // Calculate recursive statistics
146  const stats = calculateAggregateStats(rootTasks, headings, template);
147  const h1Label = headings.find((heading) => heading.level === 1)?.label;
148
149  return {
150    type: 'specGroup',
151    id: filePath,
152    name: specName,
153    folderPath,
154    taskFilePath: filePath,
155    headings,
156    rootTasks,
157    stats,
158    ...(h1Label === undefined ? {} : { h1Label }),
159  };
160}
161
162function calculateIndentation(indentStr: string): number {
163  let count = 0;
164  for (const ch of indentStr) {
165    if (ch === '\t') {
166      count += 2;
167    } else {
168      count += 1;
169    }
170  }
171  return count;
172}
173
174function attachTaskToScope(
175  task: TaskNode,
176  heading: HeadingNode | undefined,
177  rootTasks: TaskNode[]
178): void {
179  if (heading) {
180    heading.tasks.push(task);
181  } else {
182    rootTasks.push(task);
183  }
184}
185
186function calculateAggregateStats(
187  rootTasks: TaskNode[],
188  headings: HeadingNode[],
189  template: StateTemplate
190): TaskStats {
191  const totalStats: TaskStats = {
192    totalCountable: 0,
193    completedCount: 0,
194    inProgressCount: 0,
195    cancelledCount: 0,
196  };
197
198  // Count root tasks
199  const rootTaskStats = computeTasksStats(rootTasks, template);
200  addStats(totalStats, rootTaskStats);
201
202  // Count heading trees recursively
203  for (const heading of headings) {
204    const headingStats = computeHeadingStats(heading, template);
205    addStats(totalStats, headingStats);
206  }
207
208  return totalStats;
209}
210
211function computeHeadingStats(heading: HeadingNode, template: StateTemplate): TaskStats {
212  const headingStats = computeTasksStats(heading.tasks, template);
213
214  for (const child of heading.children) {
215    const childStats = computeHeadingStats(child, template);
216    addStats(headingStats, childStats);
217  }
218
219  heading.stats = { ...headingStats };
220  return headingStats;
221}
222
223function computeTasksStats(tasks: TaskNode[], template: StateTemplate): TaskStats {
224  const stats: TaskStats = {
225    totalCountable: 0,
226    completedCount: 0,
227    inProgressCount: 0,
228    cancelledCount: 0,
229  };
230
231  for (const task of tasks) {
232    stats.totalCountable++;
233    const state = getState(template, task.char);
234    if (state.countsAsCompleted) {
235      stats.completedCount++;
236    } else if (state.id === 'in_progress') {
237      stats.inProgressCount++;
238    } else if (state.id === 'cancelled') {
239      stats.cancelledCount++;
240    }
241
242    if (task.subTasks.length > 0) {
243      const subStats = computeTasksStats(task.subTasks, template);
244      addStats(stats, subStats);
245    }
246  }
247
248  return stats;
249}
250
251function addStats(target: TaskStats, source: TaskStats): void {
252  target.totalCountable += source.totalCountable;
253  target.completedCount += source.completedCount;
254  target.inProgressCount += source.inProgressCount;
255  target.cancelledCount += source.cancelledCount;
256}
257
258/**
259 * Strips bold and italic markdown delimiters from text (e.g. `**text**`, `*text*`, `__text__`, `_text_`)
260 * and the backticks of inline code spans, keeping the code itself exactly as written.
261 * Preserves identifiers containing underscores (snake_case) and math operators.
262 */
263export function stripMarkdownFormatting(text: string): string {
264  if (!text) return '';
265
266  // Code spans are set aside behind placeholders first, so emphasis stripping never touches the
267  // '*' and '_' inside them (`__init__` keeps its underscores). A span is a run of backticks, some
268  // content, and a closing run of the same length; an unmatched backtick stays as written.
269  const codeSpans: string[] = [];
270  let clean = text.replace(/(?<!`)(`+)(?!`)(.+?)(?<!`)\1(?!`)/g, (_match, _ticks: string, content: string) => {
271    // As in CommonMark, one space is trimmed from each side when both are present, so `` `a` `` reads `a`
272    const code =
273      content.length > 2 && content.startsWith(' ') && content.endsWith(' ') && content.trim()
274        ? content.slice(1, -1)
275        : content;
276    codeSpans.push(code);
277    return `\uE000${codeSpans.length - 1}\uE001`;
278  });
279
280  // Underscore emphasis must start and end at a word edge: whitespace, a symbol, or punctuation other than
281  // '_' itself, so underscores doubled inside a word (Mile__stone__) stay literal as in CommonMark.
282
283  // 1. Triple delimiters: ***text*** or ___text___ (bold + italic)
284  clean = clean.replace(/\*\*\*([^\*\s](?:.*?[^\*\s])?)\*\*\*/g, '$1');
285  clean = clean.replace(/(?:^|(?<=[\s\p{S}]|[^\P{P}_]))___([^_\s](?:.*?[^_\s])?)___(?=$|[\s\p{S}]|[^\P{P}_])/gu, '$1');
286
287  // 2. Double delimiters: **text** or __text__ (bold)
288  clean = clean.replace(/\*\*([^\*\s](?:.*?[^\*\s])?)\*\*/g, '$1');
289  clean = clean.replace(/(?:^|(?<=[\s\p{S}]|[^\P{P}_]))__([^_\s](?:.*?[^_\s])?)__(?=$|[\s\p{S}]|[^\P{P}_])/gu, '$1');
290
291  // 3. Single delimiter: *text* (italic with asterisks)
292  clean = clean.replace(/(?<!\*)\*([^\*\s](?:.*?[^\*\s])?)\*(?!\*)/g, '$1');
293
294  // 4. Single delimiter: _text_ (italic with underscores - CommonMark word boundary rules)
295  clean = clean.replace(/(?:^|(?<=[\s\p{S}]|[^\P{P}_]))_([^_\s](?:.*?[^_\s])?)_(?=$|[\s\p{S}]|[^\P{P}_])/gu, '$1');
296
297  // 5. Put the code spans back, without their backticks
298  clean = clean.replace(/\uE000(\d+)\uE001/g, (_match, index: string) => codeSpans[Number(index)] ?? '');
299
300  return clean.trim();
301}
302
core/plan.ts 54 lines
1import type { HeadingNode, SpecGroup } from './types';
2
3/** File name of a light-tier spec's plan, whose checklist lives under one section. */
4export const PLAN_FILE_NAME = 'implementation_plan.md';
5
6/** Heading of the plan section that holds its checklist. */
7export const PLAN_TASK_SECTION = 'Proposed Changes';
8
9/**
10 * Whether a task file is an implementation plan, by its base name (case-insensitive).
11 *
12 * @param filePath The task file's path, with `/` or `\` separators.
13 */
14export function isPlanFile(filePath: string): boolean {
15  return (filePath.split(/[\\/]/).at(-1) ?? '').toLowerCase() === PLAN_FILE_NAME;
16}
17
18/**
19 * Narrows a parsed plan to its task section: the headings and tasks under its "Proposed Changes"
20 * heading, without that heading itself, counted on their own. A plan without that heading keeps the
21 * whole document. Either way, headings with no tasks at any depth are dropped, since a plan's other
22 * sections are document scaffolding rather than dividers. The input is not modified.
23 */
24export function toPlanTaskSection(spec: SpecGroup): SpecGroup {
25  const section = findSection(spec.headings);
26  return {
27    ...spec,
28    headings: dropHeadingsWithoutTasks(section ? section.children : spec.headings),
29    rootTasks: section ? section.tasks : spec.rootTasks,
30    stats: { ...(section ? section.stats : spec.stats) },
31  };
32}
33
34/** The first heading, depth-first in document order, whose label is the task section's. */
35function findSection(headings: HeadingNode[]): HeadingNode | undefined {
36  for (const heading of headings) {
37    if (heading.label.trim().toLowerCase() === PLAN_TASK_SECTION.toLowerCase()) {
38      return heading;
39    }
40    const nested = findSection(heading.children);
41    if (nested) {
42      return nested;
43    }
44  }
45  return undefined;
46}
47
48/** Copies the headings that contain at least one task, recursively, leaving the originals untouched. */
49function dropHeadingsWithoutTasks(headings: HeadingNode[]): HeadingNode[] {
50  return headings
51    .filter((heading) => heading.stats.totalCountable > 0)
52    .map((heading) => ({ ...heading, children: dropHeadingsWithoutTasks(heading.children) }));
53}
54