Shows the repository's TODOs in a scrolling band above the prompt, newest first: TODO.md items, TODO/FIXME/HACK code comments dated with git blame, and the…

A Claude Code mod that lists the repository's TODOs in a band above the prompt, newest first, so the open work is in front of you when a session starts. It also keeps a buffer of findings: what an agent noticed outside its task, recorded with one command for you to review in batch.
╭────────────────────────────────────────────────────────────────────────────────────────────────[-]
│ todos · 12 │
│ ○ src/new.ts:2 cache the answer #9 today │
│ ● TODO.md Write the README before the release 11d │
│ ○ TODO.md Add a CI job for the plugin tests 11d │
│ ● deploy.sh:3 move secrets to the vault #7 11d │
│ ○ src/old.ts:2 FIXME handles CRLF badly 1y │
│ 1–5 of 12 · 2 selected [ Show Claude ] [ Clear ] [ Mine ] [ Hide ] │
╰─────────────────────────────────────────────────────────────────────────────────────────────────╯
/plugin marketplace add bengous/claude-code-plugins
/plugin install todos@bengous-plugins
A mod runs inside Claude Code with your permissions; read hooks/register.ts before you install it. Mods need a Claude Code version that ships them, and they draw only in the terminal and in the Code tab of the Desktop app: see Where mods run.
TODO.md at the repository root: each top-level - or * item, and each unchecked - [ ] box. A checked box is done and left out. A title stops at its first : or ; past ten characters.TODO, FIXME and HACK by default): after //, /*, #, --, <!-- or ;, or after the * that continues a block comment. const TODO_LIST, a TODO inside a sentence, or a comment opened inside a string, such as a test's "// TODO: x", is not one.The comment search is git grep over tracked and untracked files, .gitignore respected. It skips prose, data and diff files (.md, .txt, .json, .jsonl, .csv, .lock, .svg, .log, .patch and a few more), where a marker is text about TODOs or a transcript quoting one.
It also skips the paths your .gitattributes marks -todos, and those it marks linguist-vendored or linguist-generated. TODO.md is read whatever its attributes.
archive/** -todos
An agent that meets a problem unrelated to its task records it, instead of interrupting you or leaving a TODO comment in the code:
todos-finding src/auth.ts:40 'compares the token with =='
todos-finding --security deploy.sh 'prints the deploy key to the log'
bin/ on the Bash tool's PATH, so todos-finding runs as a bare command, in a subagent too. Outside Claude Code, run bin/todos-finding by its path.:<line> when the finding is about one line. The words after it say why.<id>.json, under todos/findings/ in the repository's git common directory, .git/todos/findings/ in a plain clone: every worktree of the repository records into the same buffer, and no commit carries it. It holds the path from the repository's root, the line or null, why, finding or security, and when it was recorded.todos-finding alone, its arguments plain words or quoted strings, with nothing a shell expands or chains ($, a backtick or a backslash in double quotes, ;, &&, |, a redirect). A settings rule or a hook that asks or denies keeps its say, and any other command goes to your permission rules as usual.FINDING why, or SECURITY why in bold red, and counts them in its header apart from the TODOs, the security ones in red: todos · 3 · 2 findings · 1 security. After a todos-finding call the band reads the buffer again, not the TODOs, and a toast names each new finding: New SECURITY finding at deploy.sh: prints the deploy key to the log. Mine counts them as yours.todos-finding --close <id>. A finding stays in the buffer until it is closed.Each TODO is dated with git blame: the time its line was authored. The newest comes first. A line not committed yet, or in an untracked file, dates to the scan and reads today.
/todos scans again and reopens it.rows TODOs at a time under a header and a footer that stay put. A longer list gets a row of arrows under it, 8: ↑ 3 more at the left and 9: ↓ 4 more at the right: type the digit alone into an empty prompt and pause, or click the arrow, and the list moves by a page. PgUp and PgDn scroll it too once the band is focused (ctrl+x tab or a click), Home and End by a page as well, and so does the wheel over the list where Claude Code reads the mouse. At either end of the list a scroll moves the band itself, when it is taller than its room. The footer says which rows show, 1–5 of 12.○ before a TODO picks it: click it, or Tab to it and press Enter. Show Claude puts the picked TODOs in the prompt box at the cursor, under Read these TODOs:, one - path:line: text per TODO (the path from the repository's root, absolute when the session started in another directory; a finding with its id and date), and gives the keys back to the prompt, where you write what Claude should do with them before you send. Clear drops the picks.user.email, uncommitted lines included. All shows every one again.TODO(#42) links to issue 42 when origin is on GitHub.When Claude edits a file with Edit or Write and adds a TODO, a toast names it: New FIXME at deploy.sh:4: rotate the deploy key. A file the scan skips raises none.
# TODO inside a multi-line string, such as a Python """ block, is listed.git blame runs once per file that holds a TODO, as many at a time as the machine has CPUs, sixteen at most (six on Windows, where getconf is missing), so the band of a repository with about a hundred such files opens after close to a second on a 16-CPU machine. Each edit that adds a TODO scans again.+N more.8 or 9 typed alone into an empty prompt, then a pause, pages the list: it does not start your message./todos, drops the pick. A finding keeps its pick until it is closed.bin/ directory.Claude Code asks for them when you enable the plugin; they are also rows in /config.
| Setting | Default | What it does |
|---|---|---|
show_on_start | true | Open the band when a session starts. /todos opens it either way. |
rows | 8 | How many TODOs the band shows at once, the rest a scroll away; it shows fewer in a short terminal. |
markers | TODO,FIXME,HACK | The comment words that mark a TODO, separated by commas. |
mine_only | false | Start each session with Mine on. |
| Path | What it holds |
|---|---|
hooks/register.ts | The hooks: session start, prompt, /todos, the edit toast, the band |
hooks/scan.ts | The scan: git grep, TODO.md, git blame, through a host the hooks build from $ |
hooks/parse.ts | Pure parsing and formatting, covered by bun test |
hooks/findings.ts | The findings buffer's place and record format, shared by the band and the command |
bin/todos-finding | The command on the Bash tool's PATH; it runs cli/finding.ts with bun |
cli/finding.ts | Records a finding and closes one, covered by bun test in a scratch repository |
hooks/register.test.ts | Tests for claude plugin test, run in Claude Code's own test kit |
hooks/register.ts 682 lines1import type { EngineInterface, PluginOptions, Register } from "claude-code";
2import { atom, read, update } from "claude-code";
3
4import type { Finding, Todo, TodoScan } from "../types/index.d.ts";
5import { COMMAND as FINDING_COMMAND, isPlainFindingCommand } from "./findings.ts";
6import {
7 addedTodos,
8 DEFAULT_MARKERS,
9 displayText,
10 formatAge,
11 isMine,
12 isScannedPath,
13 issueNumber,
14 listedTodos,
15 LIST_FILE,
16 parseMarkers,
17 pickedTodos,
18 promptText,
19 reviewText,
20 shortenStart,
21 sourceLabel,
22 todoId,
23} from "./parse.ts";
24import {
25 type Host,
26 isExcludedPath,
27 locate,
28 readFindings,
29 repoRoot,
30 type ScanResult,
31 scanRepo,
32} from "./scan.ts";
33
34const NO_SCAN: TodoScan | null = null;
35
36const scanState = atom({ plugin: "todos", key: "scan" } as const, NO_SCAN);
37
38const isVisible = atom({ plugin: "todos", key: "visible" } as const, false);
39
40const isMineOnly = atom({ plugin: "todos", key: "mineOnly" } as const, false);
41
42const windowOffset = atom({ plugin: "todos", key: "offset" } as const, 0);
43
44const NOTHING_PICKED: readonly string[] = [];
45
46const pickedIds = atom({ plugin: "todos", key: "picked" } as const, NOTHING_PICKED);
47
48const COMMAND = "todos";
49
50const GIT_TIMEOUT_MS = 20_000;
51
52const DEFAULT_ROWS = 8;
53
54// $.state refuses a value over 4,194,304 characters, and a TODO takes a few hundred.
55const KEPT_TODOS = 500;
56
57const MIN_SOURCE_WIDTH = 16;
58
59const SOURCE_SHARE = 0.35;
60
61// The band's border and its header and footer rows.
62const BAND_CHROME_ROWS = 4;
63
64const PAGER_ROWS = 1;
65
66// A bare digit typed into an empty prompt presses a band Button: the list pages without the band's focus.
67const PAGE_UP_HOTKEY = "8";
68
69const PAGE_DOWN_HOTKEY = "9";
70
71// The band's top border and its header.
72const LIST_FIRST_ROW = 2;
73
74type Settings = {
75 readonly showOnStart: boolean;
76 readonly rows: number;
77 readonly markers: readonly string[];
78 readonly mineOnly: boolean;
79};
80
81// Claude Code checks the options against plugin.json's userConfig and fills in its defaults before register runs.
82function settingsOf(options: PluginOptions): Settings {
83 return {
84 showOnStart: options.show_on_start !== false,
85 rows: Math.floor(Number(options.rows ?? DEFAULT_ROWS)),
86 markers: parseMarkers(String(options.markers ?? DEFAULT_MARKERS.join(","))),
87 mineOnly: options.mine_only === true,
88 };
89}
90
91function messageOf(error: Error | string): string {
92 return error instanceof Error ? error.message : error;
93}
94
95function hostOf($: EngineInterface): Host {
96 return {
97 run: (argv, cwd) => $.process.run(argv, { cwd, timeoutMs: GIT_TIMEOUT_MS }),
98 exists: (path) => $.fs.exists(path),
99 read: (path) => $.fs.read(path),
100 listFiles: async (directory) =>
101 (await $.fs.list(directory)).flatMap((entry) => (entry.kind === "file" ? [entry.name] : [])),
102 };
103}
104
105function kept(scan: ScanResult): TodoScan {
106 const mine = scan.todos.filter((todo) => isMine(todo, scan.userEmail));
107
108 return {
109 scannedAt: scan.scannedAt,
110 root: scan.root,
111 issueBase: scan.issueBase,
112 total: scan.todos.length,
113 mineTotal: mine.length,
114 todos: scan.todos.slice(0, KEPT_TODOS),
115 mineTodos: mine.slice(0, KEPT_TODOS),
116 findings: scan.findings.slice(0, KEPT_TODOS),
117 };
118}
119
120function countText(scan: TodoScan, mineOnly: boolean): string {
121 if (scan.total === 0 && scan.findings.length === 0) return "No TODOs in this repository.";
122 const counted = `${scan.total} ${scan.total === 1 ? "TODO" : "TODOs"} above the prompt`;
123 const mine = mineOnly ? `, ${scan.mineTotal} of them yours` : "";
124
125 const count = scan.findings.length;
126
127 const findings =
128 count === 0 ? "" : `; ${count} ${count === 1 ? "finding" : "findings"} to review`;
129
130 return `${counted}${mine}${findings}.`;
131}
132
133function newFindingToast(added: readonly Finding[]): string {
134 const [first, ...others] = added;
135
136 if (first === undefined) return "";
137
138 return `New ${first.marker === "SECURITY" ? "SECURITY finding" : "finding"} at ${sourceLabel(first)}: ${first.text}${others.length > 0 ? ` (+${others.length} more)` : ""}`;
139}
140
141/* oxlint-disable anti-slop/no-unknown-parameters, anti-slop/no-runtime-typeof -- a permission check hands the tool's input as `unknown`: this read IS the boundary. */
142/** The command a permission check reads for Bash; null for any other input. */
143function shellCommand(input: unknown): string | null {
144 return typeof input === "object" &&
145 input !== null &&
146 "command" in input &&
147 typeof input.command === "string"
148 ? input.command
149 : null;
150}
151/* oxlint-enable anti-slop/no-unknown-parameters, anti-slop/no-runtime-typeof */
152
153// Scans overlap when an edit lands during one: only the latest to start writes the band.
154let latestScan = 0;
155
156async function refresh(
157 $: EngineInterface,
158 settings: Settings,
159 cwd: string,
160 reveal: boolean,
161): Promise<TodoScan | null> {
162 const generation = ++latestScan;
163 const host = hostOf($);
164 const root = await repoRoot(host, cwd);
165
166 if (root === null) return null;
167 const scan = await scanRepo(host, root, settings.markers, await $.clock.now());
168 const [failure, ...others] = scan.failures;
169
170 if (failure !== undefined) {
171 $.ui.toast(`${failure}${others.length > 0 ? ` (+${others.length} more)` : ""}`);
172 }
173
174 const state = kept(scan);
175
176 if (generation === latestScan) {
177 await update($, scanState, () => state);
178 await update($, pickedIds, (ids) => pickedTodos(state, ids).map((todo) => todoId(todo)));
179 }
180
181 if (reveal) {
182 await update($, windowOffset, () => 0);
183 await update($, isVisible, () => state.total > 0 || state.findings.length > 0);
184 }
185
186 return state;
187}
188
189async function refreshOrToast(
190 $: EngineInterface,
191 settings: Settings,
192 cwd: string,
193 reveal: boolean,
194): Promise<void> {
195 try {
196 await refresh($, settings, cwd, reveal);
197 } catch (error) {
198 $.ui.toast(messageOf(error instanceof Error ? error : String(error)));
199 }
200}
201
202/**
203 * After a record or a close, the buffer alone is read again: the TODOs did not change, and the scan's own
204 * failures were toasted when it ran. A broken record stays for the next scan to report.
205 */
206async function announceNewFindings(
207 $: EngineInterface,
208 scan: TodoScan,
209 announced: Set<string>,
210): Promise<void> {
211 const known = new Set(scan.findings.map((finding) => finding.id));
212
213 try {
214 const { findings } = await readFindings(hostOf($), scan.root);
215
216 // Taken and marked with no await between: of two calls whose rereads both see a new finding, one announces it.
217 const added = findings.filter(
218 (finding) => !known.has(finding.id) && !announced.has(finding.id),
219 );
220
221 for (const finding of added) announced.add(finding.id);
222 const stored = findings.slice(0, KEPT_TODOS);
223
224 await update($, scanState, (state) =>
225 state?.root === scan.root ? { ...state, findings: stored } : state,
226 );
227
228 const state = await read($, scanState);
229
230 if (state !== null)
231 await update($, pickedIds, (ids) => pickedTodos(state, ids).map((todo) => todoId(todo)));
232
233 const toast = newFindingToast(added);
234
235 if (toast !== "") $.ui.toast(toast);
236 } catch (error) {
237 $.ui.toast(messageOf(error instanceof Error ? error : String(error)));
238 }
239}
240
241function windowStart(offset: number, count: number, windowRows: number): number {
242 return Math.max(0, Math.min(offset, count - windowRows));
243}
244
245function pagedOffset(offset: number, by: number, count: number, windowRows: number): number {
246 return windowStart(windowStart(offset, count, windowRows) + by, count, windowRows);
247}
248
249async function promptRoot($: EngineInterface, scan: TodoScan): Promise<string | null> {
250 return (await $.session.cwd()) === scan.root ? null : scan.root;
251}
252
253/** Puts `text` in the prompt box at the cursor, on a line of its own; false when the box refuses it. */
254async function fillPrompt($: EngineInterface, text: string, what: string): Promise<boolean> {
255 const box = await $.prompt.read();
256 const before = box.text.slice(0, box.cursor);
257
258 // oxlint-disable-next-line unicorn/no-array-fill-with-reference-type -- $.prompt.fill writes the prompt box; it is no Array.prototype.fill
259 const filled = await $.prompt.fill({
260 text: `${before === "" || before.endsWith("\n") ? "" : "\n"}${text}`,
261 mode: "insert",
262 });
263
264 if (!filled.isFilled) {
265 $.ui.toast(
266 `The prompt box did not take the ${what}${filled.refusal === undefined ? "" : ` (${filled.refusal})`}.`,
267 );
268 }
269
270 return filled.isFilled;
271}
272
273async function showClaude($: EngineInterface): Promise<void> {
274 const scan = await read($, scanState);
275
276 if (scan === null) return;
277 const todos = pickedTodos(scan, await read($, pickedIds));
278
279 if (todos.length === 0) return;
280
281 if (await fillPrompt($, promptText(todos, await promptRoot($, scan)), "TODOs"))
282 await update($, pickedIds, () => NOTHING_PICKED);
283}
284
285async function reviewFindings($: EngineInterface): Promise<void> {
286 const scan = await read($, scanState);
287
288 if (scan === null || scan.findings.length === 0) return;
289 await fillPrompt($, reviewText(scan.findings, await promptRoot($, scan)), "findings");
290}
291
292export const register: Register = (on, options) => {
293 const settings = settingsOf(options);
294 // A scroll event's bodyRows is not the band's maxRows, so the scroll hook clamps to the window the band last drew.
295 let drawnRows = settings.rows;
296 let isPagerDrawn = false;
297 const announcedFindings = new Set<string>();
298
299 on("session.start", async ($, e, next) => {
300 try {
301 await $.command.register({
302 name: COMMAND,
303 description: "Show this repository's TODOs above the prompt, newest first",
304 });
305 } catch (error) {
306 $.ui.toast(
307 `/${COMMAND} is not available: ${messageOf(error instanceof Error ? error : String(error))}`,
308 );
309 }
310
311 await update($, isMineOnly, () => settings.mineOnly);
312
313 // Not awaited: Claude Code holds the first prompt until session.start returns, and a scan blames every file it finds.
314 if (e.isInteractive) void refreshOrToast($, settings, e.cwd, settings.showOnStart);
315
316 return next(e);
317 });
318
319 // /clear, /resume and /branch reset $.state, and session.start does not fire again.
320 on("classic.SessionStart", { source: ["clear", "resume", "fork"] }, async ($, e, next) => {
321 await update($, isMineOnly, () => settings.mineOnly);
322 void refreshOrToast($, settings, e.cwd, settings.showOnStart);
323
324 return next(e);
325 });
326
327 on("prompt.submit", async ($, e, next) => {
328 if (await read($, isVisible)) await update($, isVisible, () => false);
329
330 return next(e);
331 });
332
333 on("command.run", { command: COMMAND }, async ($) => {
334 try {
335 const scan = await refresh($, settings, await $.session.cwd(), true);
336
337 if (scan === null) return { text: "Not inside a git repository." };
338
339 return { text: countText(scan, await read($, isMineOnly)) };
340 } catch (error) {
341 return { text: messageOf(error instanceof Error ? error : String(error)) };
342 }
343 });
344
345 on("tool.call", { tool: ["Edit", "Write"] }, async ($, e, next) => {
346 if (e.tool !== "Edit" && e.tool !== "Write") return next(e);
347 const written = e.tool === "Write" ? e.content : e.new_string;
348
349 const name = e.file_path.slice(
350 Math.max(e.file_path.lastIndexOf("/"), e.file_path.lastIndexOf("\\")) + 1,
351 );
352
353 if (name !== LIST_FILE && !settings.markers.some((marker) => written.includes(marker)))
354 return next(e);
355 const located = await locate(hostOf($), e.file_path);
356
357 if (located === null || !isScannedPath(located.path)) return next(e);
358 const before = (await $.fs.exists(e.file_path)) ? await $.fs.read(e.file_path) : "";
359 const result = await next(e);
360
361 if ("deny" in result || result.isError === true) return result;
362 const added = addedTodos(located.path, before, await $.fs.read(e.file_path), settings.markers);
363 const [first, ...others] = added;
364
365 if (
366 first === undefined ||
367 (located.path !== LIST_FILE && (await isExcludedPath(hostOf($), located.root, located.path)))
368 )
369 return result;
370 const where = located.path === LIST_FILE ? located.path : `${located.path}:${first.line}`;
371
372 $.ui.toast(
373 `New ${first.marker} at ${where}: ${first.text === "" ? "(no description)" : first.text}${others.length > 0 ? ` (+${others.length} more)` : ""}`,
374 );
375
376 if ((await read($, scanState))?.root === located.root)
377 void refreshOrToast($, settings, located.root, false);
378
379 return result;
380 });
381
382 // A finding goes to the buffer, not to the person: a plain todos-finding call skips the ask the mode alone would put.
383 // An ask a settings rule or a hook put stays.
384 on("tool.check", { tool: "Bash" }, async ($, e, next) => {
385 const verdict = await next(e);
386 const command = shellCommand(e.input);
387
388 const isModeAsk =
389 verdict.decision === "ask" && verdict.rule === undefined && verdict.hook === undefined;
390
391 if (!isModeAsk || command === null || !isPlainFindingCommand(command)) return verdict;
392
393 return {
394 decision: "allow",
395 reason: `todos: ${FINDING_COMMAND} writes only the repository's findings buffer`,
396 };
397 });
398
399 on("tool.call", { tool: "Bash" }, async ($, e, next) => {
400 if (e.tool !== "Bash" || !e.command.includes(FINDING_COMMAND)) return next(e);
401 const result = await next(e);
402 const scan = await read($, scanState);
403
404 // A failed call may still have changed the buffer: `--close a b` closes a when b is unknown.
405 if ("deny" in result || scan === null) return result;
406 // Not awaited: the call's result goes back to Claude without waiting on the band.
407 void announceNewFindings($, scan, announcedFindings);
408
409 return result;
410 });
411
412 on("ui.scroll", { component: "AbovePrompt" }, async ($, e, next) => {
413 if (e.origin.kind !== "person" || !(await read($, isVisible))) return next(e);
414
415 // Only in a band that fits its window is the pointer's row the tree's row.
416 if (
417 e.pointer !== undefined &&
418 e.contentRows <= e.bodyRows &&
419 (e.pointer.row < LIST_FIRST_ROW ||
420 e.pointer.row >= LIST_FIRST_ROW + drawnRows + (isPagerDrawn ? PAGER_ROWS : 0))
421 )
422 return next(e);
423 const scan = await read($, scanState);
424
425 if (scan === null) return next(e);
426 const count = listedTodos(scan, await read($, isMineOnly)).length;
427 const offset = await read($, windowOffset);
428 const from = windowStart(offset, count, drawnRows);
429
430 const to = pagedOffset(
431 offset,
432 Math.sign(e.by) * Math.min(Math.abs(e.by), drawnRows),
433 count,
434 drawnRows,
435 );
436
437 // At its edge the list hands the move on: the engine scrolls a band taller than its window.
438 if (to === from) return next(e);
439 await update($, windowOffset, () => to);
440
441 return {};
442 });
443
444 on("ui.render", { component: "AbovePrompt" }, async ($, e, next) => {
445 const scan = await read($, scanState);
446
447 if (
448 e.props.hasSurvey ||
449 scan === null ||
450 (scan.total === 0 && scan.findings.length === 0) ||
451 !(await read($, isVisible))
452 ) {
453 return next(e);
454 }
455
456 const { Box, Button, Link, Text } = $.ui.resolve(e);
457 const mineOnly = await read($, isMineOnly);
458 const listed = listedTodos(scan, mineOnly);
459 const listedTotal = (mineOnly ? scan.mineTotal : scan.total) + scan.findings.length;
460
461 const fitRows = (chromeRows: number) =>
462 Math.max(1, Math.min(settings.rows, e.props.maxRows - chromeRows));
463
464 const hasPagerRoom = e.props.maxRows - BAND_CHROME_ROWS - PAGER_ROWS >= 1;
465 const isPaged = hasPagerRoom && listed.length > fitRows(BAND_CHROME_ROWS);
466 const windowRows = fitRows(isPaged ? BAND_CHROME_ROWS + PAGER_ROWS : BAND_CHROME_ROWS);
467 drawnRows = windowRows;
468 isPagerDrawn = isPaged;
469 const start = windowStart(await read($, windowOffset), listed.length, windowRows);
470 const shown = listed.slice(start, start + windowRows);
471 const below = listed.length - start - shown.length;
472 const picked = await read($, pickedIds);
473
474 const labelLimit = Math.max(MIN_SOURCE_WIDTH, Math.floor(e.props.bodyColumns * SOURCE_SHARE));
475 // Measured over the whole list, so the columns hold still while it scrolls.
476 const labels = listed.map((todo) => shortenStart(sourceLabel(todo), labelLimit));
477 const ages = listed.map((todo) => formatAge(scan.scannedAt - todo.authoredAt));
478 const labelWidth = Math.max(0, ...labels.map((label) => label.length));
479 const ageWidth = Math.max(0, ...ages.map((age) => age.length));
480 const unkeptCount = listedTotal - listed.length;
481 const count = mineOnly ? `${scan.mineTotal} of ${scan.total} yours` : `${scan.total}`;
482 const findingCount = scan.findings.length;
483 const securityCount = scan.findings.filter((finding) => finding.marker === "SECURITY").length;
484
485 const footer = [
486 listed.length > shown.length
487 ? `${start + 1}–${start + shown.length} of ${listed.length}`
488 : "",
489 unkeptCount > 0 ? `+${unkeptCount} more` : "",
490 picked.length > 0 ? `${picked.length} selected` : "hides on your next message",
491 picked.length > 0 ? "" : `/${COMMAND} reopens`,
492 ]
493 .filter((part) => part !== "")
494 .join(" · ");
495
496 const issueOf = (tag: string | null) => {
497 const number = issueNumber(tag);
498
499 if (number === null) return [];
500
501 return [
502 Box({
503 flexShrink: 0,
504 children: [
505 scan.issueBase === null
506 ? Text({ dimColor: true, children: `#${number}` })
507 : Link({ href: `${scan.issueBase}/issues/${number}`, label: `#${number}` }),
508 ],
509 }),
510 ];
511 };
512
513 const rowText = (todo: Todo) => {
514 const children = displayText(todo);
515
516 return todo.source === "finding" && todo.marker === "SECURITY"
517 ? Text({ wrap: "truncate-end", color: "red", bold: true, children })
518 : Text({ wrap: "truncate-end", children });
519 };
520
521 const togglePicked = (id: string) =>
522 update($, pickedIds, (ids) =>
523 ids.includes(id) ? ids.filter((other) => other !== id) : [...ids, id],
524 );
525
526 const pageBy = (by: number) =>
527 update($, windowOffset, (offset) => pagedOffset(offset, by, listed.length, windowRows));
528
529 // An arrow at its end stays drawn, dim: unarmed, its digit would land in the prompt and block the other.
530 // Each keeps its own end of the row, so a second click lands on the arrow the first one hit.
531 const pager = isPaged
532 ? [
533 Box({
534 justifyContent: "space-between",
535 children: [
536 Button({
537 key: "up",
538 label: `↑ ${start} more`,
539 hotkey: PAGE_UP_HOTKEY,
540 plain: true,
541 dimColor: start === 0,
542 onPress: () => pageBy(-windowRows),
543 }),
544 Button({
545 key: "down",
546 label: `↓ ${below} more`,
547 hotkey: PAGE_DOWN_HOTKEY,
548 plain: true,
549 dimColor: below === 0,
550 onPress: () => pageBy(windowRows),
551 }),
552 ],
553 }),
554 ]
555 : [];
556
557 const rows = shown.map((todo, index) =>
558 Box({
559 key: `todo:${todoId(todo)}`,
560 gap: 1,
561 children: [
562 Button({
563 key: `pick:${todoId(todo)}`,
564 label: picked.includes(todoId(todo)) ? "●" : "○",
565 plain: true,
566 dimColor: !picked.includes(todoId(todo)),
567 onPress: () => togglePicked(todoId(todo)),
568 }),
569 Box({
570 width: labelWidth,
571 flexShrink: 0,
572 children: [Text({ dimColor: true, children: labels[start + index] ?? "" })],
573 }),
574 Box({
575 flexGrow: 1,
576 flexShrink: 1,
577 minWidth: 0,
578 children: [rowText(todo)],
579 }),
580 ...issueOf(todo.tag),
581 Box({
582 width: ageWidth,
583 flexShrink: 0,
584 children: [Text({ dimColor: true, children: ages[start + index] ?? "" })],
585 }),
586 ],
587 }),
588 );
589
590 const band = Box({
591 flexDirection: "column",
592 borderStyle: "round",
593 borderColor: "cyan",
594 paddingX: 1,
595 children: [
596 Box({
597 gap: 1,
598 children: [
599 Text({ bold: true, color: "cyan", children: "todos" }),
600 Text({ dimColor: true, children: `· ${count}` }),
601 ...(findingCount > 0
602 ? [
603 Text({
604 dimColor: true,
605 children: `· ${findingCount} ${findingCount === 1 ? "finding" : "findings"}`,
606 }),
607 ]
608 : []),
609 ...(securityCount > 0
610 ? [Text({ bold: true, color: "red", children: `· ${securityCount} security` })]
611 : []),
612 ],
613 }),
614 ...(rows.length > 0
615 ? rows
616 : [Text({ dimColor: true, children: "None of these TODOs is yours." })]),
617 ...pager,
618 Box({
619 gap: 1,
620 children: [
621 Box({
622 flexGrow: 1,
623 flexShrink: 1,
624 minWidth: 0,
625 children: [Text({ dimColor: true, wrap: "truncate-end", children: footer })],
626 }),
627 Box({
628 flexShrink: 0,
629 gap: 1,
630 children: [
631 ...(picked.length > 0
632 ? [
633 Button({
634 key: "show",
635 label: "Show Claude",
636 variant: "primary",
637 onPress: () => showClaude($),
638 }),
639 Button({
640 key: "clear",
641 label: "Clear",
642 dimColor: true,
643 onPress: () => update($, pickedIds, () => NOTHING_PICKED),
644 }),
645 ]
646 : []),
647 ...(findingCount > 0
648 ? [
649 Button({
650 key: "review",
651 label: "Review findings",
652 onPress: () => reviewFindings($),
653 }),
654 ]
655 : []),
656 Button({
657 key: "mine",
658 label: mineOnly ? "All" : "Mine",
659 dimColor: true,
660 onPress: async () => {
661 await update($, isMineOnly, (value) => !value);
662 await update($, windowOffset, () => 0);
663 },
664 }),
665 Button({
666 key: "hide",
667 label: "Hide",
668 dimColor: true,
669 onPress: () => update($, isVisible, () => false),
670 }),
671 ],
672 }),
673 ],
674 }),
675 ],
676 });
677
678 // The band is shared: what the mods after this one draw stays below the list.
679 return Box({ flexDirection: "column", children: [band, await next(e)] });
680 });
681};
682types/index.d.ts 57 lines1export type Dated = {
2 readonly authoredAt: number;
3 readonly commit: string | null;
4 readonly authorEmail: string | null;
5};
6
7/** A finding is no line of the repository: `todos-finding` recorded it in the buffer, under its id, about a path and maybe one of its lines. */
8export type Todo = Dated &
9 (
10 | {
11 readonly source: "list" | "comment";
12 readonly path: string;
13 readonly line: number;
14 readonly marker: string;
15 readonly tag: string | null;
16 readonly text: string;
17 }
18 | {
19 readonly source: "finding";
20 readonly id: string;
21 readonly path: string;
22 readonly line: number | null;
23 readonly marker: "FINDING" | "SECURITY";
24 readonly tag: null;
25 readonly text: string;
26 }
27 );
28
29export type Finding = Extract<Todo, { readonly source: "finding" }>;
30
31/**
32 * What the band keeps of a scan: the counts, and only as many TODOs as it scrolls through, since $.state caps a value's size.
33 * The findings are apart: `total` and `mineTotal` count the TODOs alone, and a record rereads the findings without the rest.
34 */
35export type TodoScan = {
36 readonly scannedAt: number;
37 readonly root: string;
38 readonly issueBase: string | null;
39 readonly total: number;
40 readonly mineTotal: number;
41 readonly todos: readonly Todo[];
42 readonly mineTodos: readonly Todo[];
43 readonly findings: readonly Finding[];
44};
45
46declare module "claude-code" {
47 interface PluginState {
48 todos: {
49 scan: TodoScan | null;
50 visible: boolean;
51 mineOnly: boolean;
52 offset: number;
53 picked: readonly string[];
54 };
55 }
56}
57hooks/findings.ts 90 lines1/** Under the repository's git common directory: every worktree records into the same buffer, and no commit carries it. */
2export const FINDINGS_DIR = "todos/findings";
3
4export const COMMAND = "todos-finding";
5
6export const FINDING_ID = /^[0-9a-f]{8}$/u;
7
8const FINDING_FILE = /^([0-9a-f]{8})\.json$/u;
9
10const TARGET_LINE = /^(.+):(\d+)$/u;
11
12// One simple command and nothing a shell expands: single quotes, double quotes without `$`, a backtick or a backslash, and plain words.
13const PLAIN_COMMAND = new RegExp(
14 String.raw`^${COMMAND}(?:[ \t]+(?:'[^']*'|"[^"$\x60\\]*"|[\w./:@%+=,-])+)*[ \t]*$`,
15 "u",
16);
17
18export type FindingKind = "finding" | "security";
19
20/** What `<id>.json` in the buffer holds. */
21export type FindingRecord = {
22 readonly path: string;
23 readonly line: number | null;
24 readonly why: string;
25 readonly kind: FindingKind;
26 readonly recordedAt: string;
27};
28
29export type Target = { readonly path: string; readonly line: number | null };
30
31/** The one rule for a line, at the command and in a record: a whole number from 1. */
32function isLineNumber(value: unknown): value is number {
33 return Number.isInteger(value) && Number(value) > 0;
34}
35
36export function findingIdOf(fileName: string): string | null {
37 return FINDING_FILE.exec(fileName)?.[1] ?? null;
38}
39
40/** `src/a.ts:12` names line 12 of `src/a.ts`; a path without `:<digits>` names the whole file. */
41export function parseTarget(raw: string): Target {
42 const match = TARGET_LINE.exec(raw);
43
44 if (match?.[1] === undefined) return { path: raw, line: null };
45 const line = Number(match[2]);
46
47 if (!isLineNumber(line)) throw new Error(`${raw}: lines start at 1`);
48
49 return { path: match[1], line };
50}
51
52export function formatRecord(record: FindingRecord): string {
53 return `${JSON.stringify(record)}\n`;
54}
55
56/* oxlint-disable anti-slop/no-runtime-typeof -- this function IS the boundary parser: a finding's file arrives as JSON text, a hand edit included, and nothing past it sees the record untyped. */
57export function parseRecord(text: string): FindingRecord {
58 const value: unknown = JSON.parse(text);
59
60 if (
61 typeof value !== "object" ||
62 value === null ||
63 !("path" in value && "line" in value && "why" in value && "kind" in value) ||
64 !("recordedAt" in value)
65 )
66 throw new Error("not an object of path, line, why, kind and recordedAt");
67 const { path, line, why, kind, recordedAt } = value;
68
69 if (typeof path !== "string" || path === "") throw new Error("`path` is not a path");
70
71 if (line !== null && !isLineNumber(line))
72 throw new Error("`line` is neither null nor a line number");
73
74 if (typeof why !== "string" || why.trim() === "") throw new Error("`why` is empty");
75
76 if (kind !== "finding" && kind !== "security")
77 throw new Error('`kind` is neither "finding" nor "security"');
78
79 if (typeof recordedAt !== "string" || Number.isNaN(Date.parse(recordedAt)))
80 throw new Error("`recordedAt` is not a date");
81
82 return { path, line, why, kind, recordedAt };
83}
84/* oxlint-enable anti-slop/no-runtime-typeof */
85
86/** A `todos-finding` call the band lets run unasked: it writes only the buffer, and a shell expands nothing in it. */
87export function isPlainFindingCommand(command: string): boolean {
88 return PLAIN_COMMAND.test(command);
89}
90hooks/parse.ts 435 lines1import type { Finding, Todo, TodoScan } from "../types/index.d.ts";
2import { COMMAND as FINDING_COMMAND, type FindingRecord } from "./findings.ts";
3
4export const DEFAULT_MARKERS: readonly string[] = ["TODO", "FIXME", "HACK"];
5
6export const LIST_FILE = "TODO.md";
7
8/** Prose and data files: a marker there is text about TODOs, or a transcript quoting one, never a comment. */
9export const SKIPPED_EXTENSIONS: readonly string[] = [
10 "md",
11 "mdx",
12 "markdown",
13 "txt",
14 "rst",
15 "adoc",
16 "json",
17 "jsonl",
18 "ndjson",
19 "csv",
20 "tsv",
21 "lock",
22 "svg",
23 "log",
24 "map",
25 "patch",
26 "diff",
27];
28
29const EXCLUDING_ATTRIBUTES = [
30 { name: "todos", value: "unset" },
31 { name: "linguist-vendored", value: "set" },
32 { name: "linguist-vendored", value: "true" },
33 { name: "linguist-generated", value: "set" },
34 { name: "linguist-generated", value: "true" },
35] as const;
36
37export const EXCLUDING_ATTRIBUTE_NAMES: readonly string[] = [
38 ...new Set(EXCLUDING_ATTRIBUTES.map((attribute) => attribute.name)),
39];
40
41function attributeRequirement(name: string, value: string): string {
42 if (value === "unset") return `-${name}`;
43
44 return value === "set" ? name : `${name}=${value}`;
45}
46
47export const ATTRIBUTE_PATHSPECS: readonly string[] = EXCLUDING_ATTRIBUTES.map(
48 ({ name, value }) => `:(exclude,attr:${attributeRequirement(name, value)})`,
49);
50
51const QUOTES = ['"', "'", "`"];
52
53const WORD_CHARACTER = /[\p{L}\p{N}_]/u;
54
55export type CommentTodo = {
56 readonly marker: string;
57 readonly tag: string | null;
58 readonly text: string;
59};
60
61export type GrepHit = CommentTodo & { readonly path: string; readonly line: number };
62
63export type ListItem = { readonly line: number; readonly text: string };
64
65export type Origin = {
66 readonly commit: string | null;
67 readonly authoredAt: number;
68 readonly authorEmail: string | null;
69};
70
71const DAY_MS = 86_400_000;
72
73const UNCOMMITTED_SHA = /^0{40}$/u;
74
75const BLAME_HEADER = /^([0-9a-f]{40}) \d+ (\d+)/u;
76
77const LIST_ITEM = /^[-*] (?:\[ \] )?(.*)$/u;
78
79const DONE_ITEM = /^[-*] \[[xX]\] /u;
80
81const COMMENT_END = /\*\/|-->/u;
82
83const LINE_BREAK = /\r?\n/u;
84
85// The engine refuses a whole band whose text holds a control character or passes 10,000 characters.
86const MAX_TEXT = 200;
87
88const NEVER = /(?!)/uy;
89
90const ISSUE_TAG = /^#(\d+)$/u;
91
92const GITHUB_REMOTE =
93 /^(?:https:\/\/github\.com\/|git@github\.com:|ssh:\/\/git@github\.com\/)([^/\s]+\/[^/\s]+?)(?:\.git)?\/?$/u;
94
95const escapeRegExp = (text: string): string =>
96 text.replaceAll(/[.*+?^${}()|[\]\\]/gu, String.raw`\$&`);
97
98/**
99 * A marker counts only as the first word of a comment: after `//`, `/*`, `#`, `--`, `<!--` or `;`
100 * that starts the line or follows a space, a bracket, `;` or `,`, or after the `*` that continues a block comment.
101 */
102export function commentPattern(markers: readonly string[]): RegExp {
103 if (markers.length === 0) return NEVER;
104 const alternatives = markers.map((marker) => escapeRegExp(marker)).join("|");
105
106 return new RegExp(
107 String.raw`(?:^\s*\*+|(?:^|[\s(){}[\];,])(?:\/\/+|\/\*+|#+|--+|<!--|;+))[\s!]*(${alternatives})\b(?:\(([^)]*)\))?:?\s*(.*)$`,
108 "uy",
109 );
110}
111
112const isControl = (character: string): boolean => {
113 const code = character.codePointAt(0) ?? 0;
114
115 return code < 0x20 || (code >= 0x7f && code < 0xa0);
116};
117
118export function stripControl(text: string): string {
119 return [...text.replaceAll("\t", " ")].filter((character) => !isControl(character)).join("");
120}
121
122export function cleanText(text: string): string {
123 const plain = stripControl(text).trim();
124
125 return plain.length > MAX_TEXT ? `${plain.slice(0, MAX_TEXT - 1)}…` : plain;
126}
127
128/**
129 * A string closes at its quote unescaped and not followed by a letter, so the `'` of `don't` or of
130 * a Rust lifetime closes nothing; -1 when it does not close on this line.
131 */
132function stringEnd(line: string, start: number): number {
133 const quote = line.charAt(start);
134
135 for (let index = start + 1; index < line.length; index += 1) {
136 const character = line.charAt(index);
137
138 if (character === "\\") index += 1;
139 else if (character === quote && !WORD_CHARACTER.test(line.charAt(index + 1))) return index;
140 }
141
142 return -1;
143}
144
145/** The first comment the pattern finds outside a string: a test fixture's `"// TODO"` is not one. */
146export function commentTodo(text: string, pattern: RegExp): CommentTodo | null {
147 const line = text.endsWith("\r") ? text.slice(0, -1) : text;
148
149 for (let index = 0; index < line.length; index += 1) {
150 pattern.lastIndex = index;
151 const match = pattern.exec(line);
152 const marker = match?.[1];
153
154 if (match !== null && marker !== undefined) {
155 const tag = cleanText(match[2] ?? "");
156
157 return {
158 marker,
159 tag: tag === "" ? null : tag,
160 text: cleanText((match[3] ?? "").split(COMMENT_END)[0] ?? ""),
161 };
162 }
163
164 const character = line.charAt(index);
165
166 if (character === "\\") index += 1;
167 else if (QUOTES.includes(character)) index = Math.max(index, stringEnd(line, index));
168 }
169
170 return null;
171}
172
173/** `git grep -z -n` rows: path, NUL, line number, NUL, the line's text. */
174export function parseGrep(stdout: string, markers: readonly string[]): GrepHit[] {
175 const pattern = commentPattern(markers);
176
177 return stdout.split("\n").flatMap((row) => {
178 const [path, line, text] = row.split("\0");
179
180 if (path === undefined || line === undefined || text === undefined) return [];
181 const found = commentTodo(text, pattern);
182
183 return found === null ? [] : [{ ...found, path, line: Number(line) }];
184 });
185}
186
187/** Top-level `- ` or `* ` items, unchecked boxes included and checked ones left out; the title stops at its first `:` or `;` past ten characters. */
188export function parseList(text: string): ListItem[] {
189 return text.split(LINE_BREAK).flatMap((row, index) => {
190 if (DONE_ITEM.test(row)) return [];
191 const item = LIST_ITEM.exec(row)?.[1];
192 const body = item === undefined ? undefined : cleanText(item.replaceAll("`", ""));
193
194 if (body === undefined || body === "") return [];
195 const cut = body.search(/[:;]/u);
196
197 return [{ line: index + 1, text: cut > 10 ? body.slice(0, cut) : body }];
198 });
199}
200
201/** `git blame --line-porcelain` output, keyed by the line's number in the working tree. */
202export function parseBlame(porcelain: string): Map<number, Origin> {
203 const origins = new Map<number, Origin>();
204 let sha = "";
205 let finalLine = 0;
206 let authoredAt = 0;
207 let authorEmail = "";
208
209 for (const row of porcelain.split("\n")) {
210 const header = BLAME_HEADER.exec(row);
211
212 if (header !== null) {
213 sha = header[1] ?? "";
214 finalLine = Number(header[2]);
215 } else if (row.startsWith("author-mail ")) {
216 authorEmail = row.slice("author-mail ".length).replaceAll(/^<|>$/gu, "");
217 } else if (row.startsWith("author-time ")) {
218 authoredAt = Number(row.slice("author-time ".length)) * 1000;
219 } else if (row.startsWith("\t")) {
220 const isUncommitted = UNCOMMITTED_SHA.test(sha);
221 origins.set(finalLine, {
222 commit: isUncommitted ? null : sha.slice(0, 8),
223 authoredAt,
224 authorEmail: isUncommitted ? null : authorEmail,
225 });
226 }
227 }
228
229 return origins;
230}
231
232const SOURCE_RANK = { list: 0, comment: 1, finding: 2 } as const;
233
234export function sortNewestFirst(todos: readonly Todo[]): Todo[] {
235 return todos.toSorted(
236 (a, b) =>
237 b.authoredAt - a.authoredAt ||
238 SOURCE_RANK[a.source] - SOURCE_RANK[b.source] ||
239 a.path.localeCompare(b.path) ||
240 (a.line ?? 0) - (b.line ?? 0),
241 );
242}
243
244export function formatAge(ms: number): string {
245 const days = Math.floor(ms / DAY_MS);
246
247 if (days < 1) return "today";
248
249 if (days < 14) return `${days}d`;
250
251 if (days < 60) return `${Math.floor(days / 7)}w`;
252
253 if (days < 365) return `${Math.floor(days / 30)}mo`;
254
255 return `${Math.floor(days / 365)}y`;
256}
257
258function location(todo: Todo): string {
259 return todo.line === null ? todo.path : `${todo.path}:${todo.line}`;
260}
261
262export function sourceLabel(todo: Todo): string {
263 return stripControl(todo.source === "list" ? todo.path : location(todo));
264}
265
266/** Keeps the end of a path, where the file name and line are. */
267export function shortenStart(text: string, width: number): string {
268 return text.length <= width ? text : `…${text.slice(text.length - width + 1)}`;
269}
270
271export function displayText(todo: Todo): string {
272 const text = todo.text === "" ? "(no description)" : todo.text;
273
274 return todo.source === "list" || todo.marker === "TODO" ? text : `${todo.marker} ${text}`;
275}
276
277/** The line is part of a TODO's: a rescan that moves one drops it from the picked ones. A finding keeps its buffer id. */
278export function todoId(todo: Todo): string {
279 return todo.source === "finding"
280 ? JSON.stringify([todo.source, todo.id])
281 : JSON.stringify([todo.source, todo.path, todo.line, todo.marker, todo.text]);
282}
283
284/** The band's list: the TODOs, all or only yours, and the findings, which are always yours, newest first. */
285export function listedTodos(scan: TodoScan, isMineOnly: boolean): Todo[] {
286 return sortNewestFirst([...(isMineOnly ? scan.mineTodos : scan.todos), ...scan.findings]);
287}
288
289export function pickedTodos(scan: TodoScan, ids: readonly string[]): Todo[] {
290 const byId = new Map(
291 [...scan.todos, ...scan.mineTodos, ...scan.findings].map((todo) => [todoId(todo), todo]),
292 );
293
294 return [...byId.values()].filter((todo) => ids.includes(todoId(todo)));
295}
296
297function promptItem(todo: Todo, root: string | null): string {
298 const where = `${root === null ? "" : `${root}/`}${stripControl(location(todo))}`;
299
300 const note =
301 todo.source === "finding"
302 ? ` (finding ${todo.id}, ${new Date(todo.authoredAt).toISOString().slice(0, 10)})`
303 : todo.tag === null
304 ? ""
305 : ` (${todo.tag})`;
306
307 return `- ${where}: ${displayText(todo)}${note}`;
308}
309
310/**
311 * What Show Claude puts in the prompt box: where each TODO is, and no verb that asks for a fix.
312 * Paths are the repository's: a session started elsewhere gets them under `root`.
313 */
314export function promptText(todos: readonly Todo[], root: string | null): string {
315 return ["Read these TODOs:", ...todos.map((todo) => promptItem(todo, root)), ""].join("\n");
316}
317
318/** What Review findings puts in the prompt box: the batch, security first, and how a handled finding leaves the buffer. */
319export function reviewText(findings: readonly Finding[], root: string | null): string {
320 const ordered = findings.toSorted(
321 (a, b) => Number(b.marker === "SECURITY") - Number(a.marker === "SECURITY"),
322 );
323
324 return [
325 `Review these findings with me: recommend an issue, a fix or a dismissal for each, then carry out what I choose and close each handled one with \`${FINDING_COMMAND} --close <id>\`.`,
326 ...ordered.map((finding) => promptItem(finding, root)),
327 "",
328 ].join("\n");
329}
330
331/** The markers setting: words separated by commas or spaces, each kept once. */
332export function parseMarkers(setting: string): string[] {
333 return [...new Set(setting.split(/[\s,]+/u).filter((word) => word !== ""))];
334}
335
336/** The web address of a GitHub remote, where `TODO(#42)` links to; null for any other host. */
337export function githubWebUrl(remote: string): string | null {
338 const slug = GITHUB_REMOTE.exec(remote.trim())?.[1];
339
340 return slug === undefined ? null : `https://github.com/${slug}`;
341}
342
343export function issueNumber(tag: string | null): number | null {
344 const digits = tag === null ? undefined : ISSUE_TAG.exec(tag)?.[1];
345
346 return digits === undefined ? null : Number(digits);
347}
348
349/** An uncommitted line is the person's own work. */
350export function isMine(todo: Todo, email: string | null): boolean {
351 if (todo.authorEmail === null) return true;
352
353 return email !== null && todo.authorEmail.toLowerCase() === email.toLowerCase();
354}
355
356/** Whether a scan reads this repository-relative path: TODO.md, or a file outside the skipped extensions. */
357export function isScannedPath(path: string): boolean {
358 if (path === LIST_FILE) return true;
359 const name = path.slice(path.lastIndexOf("/") + 1);
360 const dot = name.lastIndexOf(".");
361
362 return dot <= 0 || !SKIPPED_EXTENSIONS.includes(name.slice(dot + 1).toLowerCase());
363}
364
365/** `git check-attr -z` rows: path, attribute and value, each followed by NUL. */
366export function isExcludedByAttributes(stdout: string): boolean {
367 const fields = stdout.split("\0");
368
369 for (let index = 0; index + 2 < fields.length; index += 3) {
370 const [name, value] = [fields[index + 1], fields[index + 2]];
371
372 if (
373 EXCLUDING_ATTRIBUTES.some((attribute) => attribute.name === name && attribute.value === value)
374 )
375 return true;
376 }
377
378 return false;
379}
380
381export type AddedTodo = CommentTodo & { readonly line: number };
382
383const todoKey = (todo: CommentTodo): string => `${todo.marker}\0${todo.text}`;
384
385function todosOfText(path: string, text: string, pattern: RegExp): AddedTodo[] {
386 if (path === LIST_FILE) {
387 return parseList(text).map((item) => ({ ...item, marker: "TODO", tag: null }));
388 }
389
390 return text.split(LINE_BREAK).flatMap((row, index) => {
391 const found = commentTodo(row, pattern);
392
393 return found === null ? [] : [{ ...found, line: index + 1 }];
394 });
395}
396
397/** The TODOs `after` holds and `before` did not, matched by marker and text so that a moved line is not new. */
398export function addedTodos(
399 path: string,
400 before: string,
401 after: string,
402 markers: readonly string[],
403): AddedTodo[] {
404 const pattern = commentPattern(markers);
405 const remaining = new Map<string, number>();
406
407 for (const todo of todosOfText(path, before, pattern)) {
408 remaining.set(todoKey(todo), (remaining.get(todoKey(todo)) ?? 0) + 1);
409 }
410
411 return todosOfText(path, after, pattern).filter((todo) => {
412 const count = remaining.get(todoKey(todo)) ?? 0;
413
414 if (count === 0) return true;
415 remaining.set(todoKey(todo), count - 1);
416
417 return false;
418 });
419}
420
421export function findingOf(id: string, record: FindingRecord): Finding {
422 return {
423 source: "finding",
424 id,
425 path: record.path,
426 line: record.line,
427 marker: record.kind === "security" ? "SECURITY" : "FINDING",
428 tag: null,
429 text: cleanText(record.why.replaceAll(/\s+/gu, " ")),
430 authoredAt: Date.parse(record.recordedAt),
431 commit: null,
432 authorEmail: null,
433 };
434}
435hooks/scan.ts 343 lines1import type { Finding, Todo } from "../types/index.d.ts";
2import { findingIdOf, FINDINGS_DIR, parseRecord } from "./findings.ts";
3import {
4 ATTRIBUTE_PATHSPECS,
5 EXCLUDING_ATTRIBUTE_NAMES,
6 findingOf,
7 githubWebUrl,
8 type GrepHit,
9 isExcludedByAttributes,
10 LIST_FILE,
11 type Origin,
12 parseBlame,
13 parseGrep,
14 parseList,
15 SKIPPED_EXTENSIONS,
16 sortNewestFirst,
17} from "./parse.ts";
18
19const DEFAULT_BLAME_CONCURRENCY = 6;
20
21// Measured on openai/codex with 16 CPUs: 12 blames at once took 964 ms, 16 took 834 ms, and more gained nothing.
22const MAX_BLAME_CONCURRENCY = 16;
23
24const GREP_NO_MATCH = 1;
25
26type Blamed =
27 | { readonly isOk: true; readonly origins: Map<number, Origin> }
28 | { readonly isOk: false; readonly error: string };
29
30export type ScanResult = {
31 readonly scannedAt: number;
32 readonly root: string;
33 readonly userEmail: string | null;
34 readonly issueBase: string | null;
35 readonly todos: readonly Todo[];
36 readonly findings: readonly Finding[];
37 readonly failures: readonly string[];
38};
39
40export type RunResult = {
41 readonly exitCode: number;
42 readonly stdout: string;
43 readonly stderr: string;
44 readonly isStdoutTruncated: boolean;
45};
46
47type Grepped = { readonly hits: readonly GrepHit[]; readonly isTruncated: boolean };
48
49export type Located = { readonly root: string; readonly path: string };
50
51// An untracked file, or a repository with no commit yet, has no history: its lines count as uncommitted.
52const NO_HISTORY = /no such path|no such ref/u;
53
54/** What a scan needs from the machine; the hooks module builds it from `$`, which cannot cross an import. */
55export type Host = {
56 readonly run: (argv: readonly string[], cwd: string) => Promise<RunResult>;
57 readonly exists: (path: string) => Promise<boolean>;
58 readonly read: (path: string) => Promise<string>;
59 readonly listFiles: (directory: string) => Promise<readonly string[]>;
60};
61
62export async function repoRoot(host: Host, cwd: string): Promise<string | null> {
63 const run = await host.run(["git", "rev-parse", "--show-toplevel"], cwd);
64
65 return run.exitCode === 0 ? run.stdout.trim() : null;
66}
67
68/**
69 * Where an edited file sits, as git names it: asked from the file's own directory, so a symlinked
70 * path or a Windows path with backslashes still lands on the repository-relative path.
71 */
72export async function locate(host: Host, filePath: string): Promise<Located | null> {
73 const slash = Math.max(filePath.lastIndexOf("/"), filePath.lastIndexOf("\\"));
74
75 if (slash < 0) return null;
76
77 const run = await host
78 .run(["git", "rev-parse", "--show-toplevel", "--show-prefix"], filePath.slice(0, slash) || "/")
79 .catch(() => null);
80
81 const [root, prefix] = run?.exitCode === 0 ? run.stdout.split("\n") : [];
82
83 if (root === undefined || root === "" || prefix === undefined) return null;
84
85 return { root, path: `${prefix}${filePath.slice(slash + 1)}` };
86}
87
88export async function isExcludedPath(host: Host, root: string, path: string): Promise<boolean> {
89 const run = await host.run(
90 ["git", "check-attr", "-z", ...EXCLUDING_ATTRIBUTE_NAMES, "--", path],
91 root,
92 );
93
94 if (run.exitCode !== 0) throw new Error(`git check-attr ${path} failed: ${run.stderr.trim()}`);
95
96 return isExcludedByAttributes(run.stdout);
97}
98
99async function grepComments(
100 host: Host,
101 root: string,
102 markers: readonly string[],
103): Promise<Grepped> {
104 if (markers.length === 0) return { hits: [], isTruncated: false };
105
106 const run = await host.run(
107 [
108 "git",
109 "grep",
110 // A configured submodule.recurse makes git refuse --untracked.
111 "--no-recurse-submodules",
112 "--untracked",
113 // color.ui=always would wrap each marker in escape codes.
114 "--no-color",
115 "-z",
116 "-n",
117 "-I",
118 "-F",
119 ...markers.flatMap((marker) => ["-e", marker]),
120 "--",
121 ".",
122 ...SKIPPED_EXTENSIONS.map((extension) => `:(exclude,icase)*.${extension}`),
123 ...ATTRIBUTE_PATHSPECS,
124 ],
125 root,
126 );
127
128 if (run.exitCode === GREP_NO_MATCH) return { hits: [], isTruncated: false };
129
130 if (run.exitCode !== 0) throw new Error(`git grep failed: ${run.stderr.trim()}`);
131
132 return { hits: parseGrep(run.stdout, markers), isTruncated: run.isStdoutTruncated };
133}
134
135async function blame(
136 host: Host,
137 root: string,
138 path: string,
139 lines: readonly number[] | null,
140): Promise<Blamed> {
141 const ranges = lines === null ? [] : lines.flatMap((line) => ["-L", `${line},${line}`]);
142 let run: RunResult;
143
144 try {
145 run = await host.run(["git", "blame", "--line-porcelain", ...ranges, "--", path], root);
146 } catch (error) {
147 return {
148 isOk: false,
149 error: `git blame ${path}: ${error instanceof Error ? error.message : String(error)}`,
150 };
151 }
152
153 if (run.exitCode === 0) return { isOk: true, origins: parseBlame(run.stdout) };
154
155 if (NO_HISTORY.test(run.stderr)) return { isOk: true, origins: new Map() };
156
157 return { isOk: false, error: `git blame ${path}: ${run.stderr.trim()}` };
158}
159
160async function mapPool<T, R>(
161 items: readonly T[],
162 limit: number,
163 work: (item: T) => Promise<R>,
164): Promise<R[]> {
165 const results: R[] = [];
166 let next = 0;
167
168 const worker = async (): Promise<void> => {
169 for (let index = next++; index < items.length; index = next++) {
170 const item = items[index];
171
172 if (item !== undefined) results[index] = await work(item);
173 }
174 };
175
176 await Promise.all(Array.from({ length: Math.min(limit, items.length) }, worker));
177
178 return results;
179}
180
181// A hooks module has no `os`: getconf counts the CPUs on Linux and macOS, and Windows, without it, keeps the default.
182async function blameConcurrency(host: Host, root: string): Promise<number> {
183 const run = await host.run(["getconf", "_NPROCESSORS_ONLN"], root).catch(() => null);
184 const count = run?.exitCode === 0 ? Number.parseInt(run.stdout, 10) : Number.NaN;
185
186 return Number.isInteger(count) && count > 0
187 ? Math.min(count, MAX_BLAME_CONCURRENCY)
188 : DEFAULT_BLAME_CONCURRENCY;
189}
190
191/** One line of git output, or null when git exits non-zero: an unset `user.email`, no `origin` remote. */
192async function gitValue(host: Host, root: string, args: readonly string[]): Promise<string | null> {
193 const run = await host.run(["git", ...args], root);
194 const value = run.stdout.trim();
195
196 return run.exitCode === 0 && value !== "" ? value : null;
197}
198
199export type Buffered = {
200 readonly findings: readonly Finding[];
201 readonly failures: readonly string[];
202};
203
204type Read =
205 | { readonly kind: "read"; readonly finding: Finding }
206 | { readonly kind: "gone" }
207 | { readonly kind: "broken"; readonly error: string };
208
209/** The findings `todos-finding` recorded, from the git common directory every worktree of the repository shares, newest first. */
210export async function readFindings(host: Host, root: string): Promise<Buffered> {
211 const common = await gitValue(host, root, [
212 "rev-parse",
213 "--path-format=absolute",
214 "--git-common-dir",
215 ]);
216
217 if (common === null) throw new Error(`git rev-parse --git-common-dir failed in ${root}`);
218 const directory = `${common}/${FINDINGS_DIR}`;
219
220 if (!(await host.exists(directory))) return { findings: [], failures: [] };
221
222 const ids = (await host.listFiles(directory)).flatMap((name) => {
223 const id = findingIdOf(name);
224
225 return id === null ? [] : [id];
226 });
227
228 const read = await Promise.all(
229 ids.map(async (id): Promise<Read> => {
230 const path = `${directory}/${id}.json`;
231
232 try {
233 return { kind: "read", finding: findingOf(id, parseRecord(await host.read(path))) };
234 } catch (error) {
235 // A finding closed between the listing and its read is gone, not broken.
236 if (!(await host.exists(path))) return { kind: "gone" };
237
238 return {
239 kind: "broken",
240 error: `finding ${path}: ${error instanceof Error ? error.message : String(error)}`,
241 };
242 }
243 }),
244 );
245
246 return {
247 findings: read
248 .flatMap((result) => (result.kind === "read" ? [result.finding] : []))
249 .toSorted((a, b) => b.authoredAt - a.authoredAt),
250 failures: read.flatMap((result) => (result.kind === "broken" ? [result.error] : [])),
251 };
252}
253
254/** In a scan, a buffer git cannot locate is one failure among the others: the TODOs still show. */
255async function readFindingsOrFailure(host: Host, root: string): Promise<Buffered> {
256 try {
257 return await readFindings(host, root);
258 } catch (error) {
259 return { findings: [], failures: [error instanceof Error ? error.message : String(error)] };
260 }
261}
262
263async function readList(host: Host, root: string): Promise<string | null> {
264 const path = `${root}/${LIST_FILE}`;
265
266 return (await host.exists(path)) ? host.read(path) : null;
267}
268
269export async function scanRepo(
270 host: Host,
271 root: string,
272 markers: readonly string[],
273 scannedAt: number,
274): Promise<ScanResult> {
275 const [{ hits, isTruncated }, listText, buffered, userEmail, remote, concurrency] =
276 await Promise.all([
277 grepComments(host, root, markers),
278 readList(host, root),
279 readFindingsOrFailure(host, root),
280 gitValue(host, root, ["config", "user.email"]),
281 gitValue(host, root, ["remote", "get-url", "origin"]),
282 blameConcurrency(host, root),
283 ]);
284
285 const listItems = listText === null ? [] : parseList(listText);
286
287 const linesByPath = new Map<string, number[]>();
288
289 for (const hit of hits)
290 linesByPath.set(hit.path, [...(linesByPath.get(hit.path) ?? []), hit.line]);
291
292 const jobs: { readonly path: string; readonly lines: readonly number[] | null }[] = [
293 ...[...linesByPath].map(([path, lines]) => ({ path, lines })),
294 ...(listItems.length > 0 ? [{ path: LIST_FILE, lines: null }] : []),
295 ];
296
297 const blamed = await mapPool(jobs, concurrency, (job) => blame(host, root, job.path, job.lines));
298
299 const originsByPath = new Map<string, Map<number, Origin>>();
300
301 const failures: string[] = [
302 ...(isTruncated ? ["git grep printed over 4 MiB: the list is cut"] : []),
303 ...buffered.failures,
304 ];
305
306 jobs.forEach((job, index) => {
307 const result = blamed[index];
308
309 if (result?.isOk === true) originsByPath.set(job.path, result.origins);
310 else if (result !== undefined) failures.push(result.error);
311 });
312
313 const originOf = (path: string, line: number): Origin =>
314 originsByPath.get(path)?.get(line) ?? {
315 commit: null,
316 authoredAt: scannedAt,
317 authorEmail: null,
318 };
319
320 const todos: Todo[] = [
321 ...listItems.map((item): Todo => ({
322 source: "list",
323 path: LIST_FILE,
324 line: item.line,
325 marker: "TODO",
326 tag: null,
327 text: item.text,
328 ...originOf(LIST_FILE, item.line),
329 })),
330 ...hits.map((hit): Todo => ({ source: "comment", ...hit, ...originOf(hit.path, hit.line) })),
331 ];
332
333 return {
334 scannedAt,
335 root,
336 userEmail,
337 issueBase: remote === null ? null : githubWebUrl(remote),
338 todos: sortNewestFirst(todos),
339 findings: buffered.findings,
340 failures,
341 };
342}
343