pi-todo-ledger 0.14.0 → 0.14.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CONTRACT.md CHANGED
@@ -48,7 +48,7 @@ A `todo` `update` call adds its `evidence` items after the existing ones, and no
48
48
  > Evidence is self-reported bookkeeping, not proof.
49
49
  > When recording new evidence, the extension checks its shape and time; when importing or replaying a snapshot, it preserves the recorded time.
50
50
  > It runs nothing and cannot tell whether the command ran or how it ended.
51
- > The one exception is a todo bound to a branch: since 0.14.0 its completion counts only evidence that matches a run the session's own `bash` tool finished (see [Witnessed runs](#witnessed-runs-todowitness)).
51
+ > A branch-bound todo's completion uses [witnessed runs](#witnessed-runs-todowitness), not the agent's report: this session must run the anchor itself.
52
52
  > Use it to find which checks were run and on which revision, so the next round can reuse a green run.
53
53
  > A consumer that judges whether a check passed after the last change, such as a guard that blocks closing a task, keeps the session's real tool results (the command's own output on the branch) as the source of truth and treats evidence only as a pointer to them.
54
54
 
@@ -285,8 +285,7 @@ The figures are an estimate from what pi wrote in the child's transcript, bookke
285
285
 
286
286
  ### Branch binding (`metadata.boundBranch`)
287
287
 
288
- Since 0.13.0 a todo can be bound to a git branch, and a bound todo completes only on passing evidence for that branch's current head.
289
- Since 0.14.0 that evidence counts only when the session witnessed the run it names (see [Witnessed runs](#witnessed-runs-todowitness)).
288
+ A todo can be bound to a git branch. To complete it, run the anchor on the current head in the session that owns the todo (see [Witnessed runs](#witnessed-runs-todowitness)); the merge exceptions are below.
290
289
  The ledger owns this namespace:
291
290
 
292
291
  ```json
@@ -318,7 +317,7 @@ Deleting the todo, with `delete` or an `update` to `deleted`, stays allowed.
318
317
 
319
318
  An `update` that moves a bound todo to `completed` reads the branch, after the namespace validators and before the change guards, and commits only if one of these holds:
320
319
 
321
- 1. The branch exists, and a witnessed passing evidence entry (`result: "pass"`) names its head: the entry's `sha`, seven to 64 hex digits in any case, is a prefix of the head's full sha, and the session witnessed the entry's run on that head. The entry may be recorded by an earlier call or in the completing call's own `evidence`.
320
+ 1. The branch exists and the session witnessed every command of the anchor on its current head. A witness for this binding (`repo`, `ref`, full head sha) needs no hand-written evidence. An explicit passing entry can also identify a witnessed run on the same commit, as below.
322
321
  2. The branch exists, the base holds its head (`git merge-base --is-ancestor`), and the base holds a tested commit of the branch's own work, defined below.
323
322
  3. The branch no longer exists (deleted after a merge), and the base holds a tested commit of the branch's own work.
324
323
 
@@ -326,14 +325,14 @@ A tested commit of the branch's own work is a commit that a witnessed passing ev
326
325
  The `start` must resolve in `repo`, and in rule 2 it must also be an ancestor of the head.
327
326
  A binding made by hand, without a `start`, completes only by the first rule. A merged branch never completes without evidence: a branch with no commits of its own, fast-forwarded to a newer base, has none to show.
328
327
  Evidence shas the repository does not know are skipped; when `git merge-base --is-ancestor` gives any answer other than yes or no, such as 128 for an unknown commit, the call is refused as a read error.
329
- Otherwise the call is refused and nothing changes. The refusal names the todo, the branch, its head sha and the evidence shas seen, or why the evidence on the head was not witnessed, and says to run the anchor on the head in this session and record it:
328
+ Otherwise the call is refused and nothing changes. The refusal names the todo, the branch, its head sha and the evidence shas seen, or why the evidence on the head was not witnessed, and says to run the anchor on the head in this session:
330
329
 
331
330
  ```text
332
- Error: #3 "Port the parser" is bound to branch feat/parser in /Users/me/projects/app/.git, whose head is c986d17a7fc4eac254bba796e7ddf6d2025b50b7. Its passing evidence names other commits: e780e97ac. The branch is not merged into main. Run the anchor (`npm test -- parser`) yourself in this session on the head c986d17a7fc4eac254bba796e7ddf6d2025b50b7; relayed results do not count. Then record the command you ran as evidence { command, sha: "c986d17a7fc4eac254bba796e7ddf6d2025b50b7", result: "pass" }, in the update that completes the todo or before it. Run it alone on a clean checkout of the branch; a check longer than a bash call may take goes under MonitorCreate in this session, whose exit-0 finish counts the same.
331
+ Error: #3 "Port the parser" is bound to branch feat/parser in /Users/me/projects/app/.git, whose head is c986d17a7fc4eac254bba796e7ddf6d2025b50b7. Its passing evidence names other commits: e780e97ac. The branch is not merged into main. Run the anchor (`npm test -- parser`) yourself in this session on the head c986d17a7fc4eac254bba796e7ddf6d2025b50b7; relayed results do not count. Run it on a clean checkout of the head; no matching hand-written evidence is needed. A failed or piped check does not count; a check longer than a bash call may take goes under MonitorCreate in this session, whose exit-0 finish counts the same.
333
332
  ```
334
333
 
335
334
  A squash or rebase merge leaves the branch's own commits out of the base, so a branch merged that way and then deleted meets none of the rules.
336
- Its refusal tells the agent to restore the branch at its last head (the merged commit), with `git -C '<repo>' branch <ref> <last head>`, and to run the anchor on that commit in the session and record it if it is not the last witnessed one; after that the first rule completes the todo.
335
+ Its refusal tells the agent to restore the branch at its last head (the merged commit), with `git -C '<repo>' branch <ref> <last head>`, and to run the anchor on that commit in the session if it is not the last witnessed one; after that the first rule completes the todo.
337
336
 
338
337
  A repository that cannot be read (its path is gone or is no git repository), a git command that gives no answer (`could not read … (timeout after 5000 ms)`, or killed by a signal), and a missing branch that meets no rule each refuse with that reason; none completes silently.
339
338
  Only git's own "no such ref" (exit 1 with nothing on stderr) counts as a missing branch.
@@ -345,7 +344,7 @@ The check runs nothing: it compares recorded shas with the branch and with the s
345
344
 
346
345
  ### Witnessed runs (`todo/witness`)
347
346
 
348
- Since 0.14.0 a passing evidence entry counts for a bound todo only when the session witnessed the run it names.
347
+ The ledger records proof separately from append-only `evidence`. A worker's report on the same commit cannot substitute for a run in this session or invalidate one.
349
348
  The ledger watches two kinds of run while any todo of the session is open (`pending` or `in_progress`) and bound:
350
349
 
351
350
  - a call of pi's `bash` tool, including nested calls a tool makes through `ctx.executeTool`;
@@ -354,7 +353,8 @@ The ledger watches two kinds of run while any todo of the session is open (`pend
354
353
  #### Which runs are recorded
355
354
 
356
355
  Before the run, in its `tool_call` handler, the ledger reads the checkout the command runs in. For `bash` that is the session's directory (`ctx.cwd`), for a monitor the pi process's directory (where its shell starts), or in either case the directory of one leading `cd <dir> &&` (relative to it, `~` for home).
357
- It considers only the open bound todos whose anchor has a command part the command runs (see [Matching evidence to runs](#matching-evidence-to-runs)); a run of no such command, such as `ls` or `cat`, reads no git.
356
+ Before reading git, the ledger looks for an open bound todo whose anchor covers every step of the run (see [Matching evidence to runs](#matching-evidence-to-runs)).
357
+ For example, `npm test && npm run check` must match one todo's anchor; a step from each of two different todos is not enough.
358
358
  It reads the checkout's `HEAD` and shared git directory, then matches those todos' bindings in parallel: a binding matches when it is the same repository (the same shared git directory, read once per `repo` path) and its branch head is that `HEAD`.
359
359
  Only for a match does it run `git status --porcelain --untracked-files=normal`, which must print nothing: no uncommitted change and no untracked file (an untracked file may be a new module the head lacks); ignored files do not count.
360
360
 
@@ -371,11 +371,15 @@ The ledger then appends one custom entry to the session branch:
371
371
 
372
372
  `heads` names each open binding whose branch head the checkout had, all with that one sha. Bindings of other branches and repositories are left out.
373
373
  A run on a dirty checkout, one whose checkout changed or whose `HEAD` moved while it ran, and two monitors told apart by nothing are not recorded; a `bash` result (or the `MonitorCreate` result, where the reason is known at the start) gets a `Todo witness:` line saying why. A git read that gives no answer is said the same way, once per session.
374
- A command that is no plain run (below), a command over 8192 characters, a run in a checkout of no bound branch, and every call of a session with no open bound todo record nothing; a session with no open bound todo reads no git.
374
+ A clean detached worktree with the same shared git directory and the bound head qualifies. Check out that head in a separate call, so the ledger can read the target checkout before the check starts.
375
+ If a parsed run uses an anchor's command word but its steps or arguments do not match, the result explains why and suggests running setup separately.
376
+ For unsupported shell syntax, the ledger gives a hint once per anchor part per session when it recognizes that part at the start of a command segment.
377
+ A quoted search such as `grep -n "npm test" README.md` does not count as an attempted check. Neither hint records a witness or reads git.
378
+ A command outside the supported forms (below), a command over 8192 characters, a run in a checkout of no bound branch, and every call of a session with no open bound todo record nothing; a session with no open bound todo reads no git.
375
379
 
376
380
  #### Which run forms count
377
381
 
378
- A plain run is one command: after one leading `cd <dir> &&` and trailing redirections are set aside, what remains must be words only.
382
+ For a single check, after one leading `cd <dir> &&` and trailing redirections are set aside, what remains must be words only.
379
383
 
380
384
  These count, under `bash` or `MonitorCreate` alike, for the anchor command `npm test`:
381
385
 
@@ -383,12 +387,23 @@ These count, under `bash` or `MonitorCreate` alike, for the anchor command `npm
383
387
  - one leading `cd`: `cd /path/to/worktree && npm test`;
384
388
  - trailing redirections: `npm test > /tmp/log 2>&1`, `npm test >>log`, `npm test 2>/dev/null`, `npm test < in`.
385
389
 
386
- These do not:
390
+ A second accepted form runs declared package checks as a batch. For example, with `pnpm typecheck` and `pnpm test` as separate anchor parts:
391
+
392
+ ```sh
393
+ cd ~/work/app && test "$(git rev-parse HEAD)" = c986d17a7fc4eac254bba796e7ddf6d2025b50b7 && pnpm typecheck && pnpm test
394
+ ```
395
+
396
+ The `cd` and HEAD assertion are optional. The directory in this form must be an unquoted `/`, `~/`, `./` or `../` path with only letters, digits, `_`, `.`, `/`, `+`, `@` or `-` after the prefix.
397
+ The assertion takes a full lowercase commit sha, which must equal the head the ledger reads before the run.
398
+ Each check starts with `npm` or `pnpm`, takes literal arguments (letters, digits, `_`, `@`, `.`, `/`, `:`, `+`, `-`), and must match a part of the same anchor.
399
+ Only `&&` may separate these steps. Exit zero proves every check passed; on failure none counts. Without the assertion a single check uses the plain-run rules above.
400
+
401
+ These do not count:
387
402
 
388
403
  - a pipe, even with `set -o pipefail`: `npm test 2>&1 | tail`, `npm test | tee log`;
389
- - a chain or list: `npm test; echo done`, `npm test || true`, `npm test && npm run check` (it counts for neither part), `wrapper.sh && cd <dir> && npm test`, a background `&`, a newline;
404
+ - other chains or lists: `npm test; echo done`, `npm test || true`, `wrapper.sh && cd <dir> && npm test`, a background `&`, a newline;
390
405
  - a wrapper or prefix the anchor does not have: `timeout 600 npm test`, `env CI=1 npm test`, `CI=1 npm test`, `time npm test`, `npx npm test` (they count only when the anchor is written that way, such as `` `CI=1 npm test` ``);
391
- - an expansion anywhere, also inside double quotes: `cd $WT && npm test`, `npm test "$(date)"`, a backtick;
406
+ - any expansion other than the batch's exact HEAD assertion, including inside double quotes: `cd $WT && npm test`, `npm test "$(date)"`, a backtick;
392
407
  - a comment, group, negation, subshell, function, alias or trap: `true # npm test`, `{ npm test; }`, `! npm test`, `(npm test)`, `npm() { :; }; npm test`;
393
408
  - a help or version request: `npm test --help`, `-h`, `--version`;
394
409
  - another command: `pnpm test`, `npm test-not-really`, `echo npm test`.
@@ -397,15 +412,16 @@ These do not:
397
412
 
398
413
  When a bound todo completes, it is judged against its anchor as it stood before the completing call.
399
414
  A bound todo whose anchor has no command part cannot complete; the refusal, and the notice of a launch that binds such a todo, say: "a branch-bound todo's anchor must name its check as a command in backticks (e.g. `npm test`); put a non-command check (visual check, the boss's acceptance) in a separate todo that is not bound. Write one command per code span, with its arguments (`npm test` and `npm run check`, not `npm test && npm run check`, and not one word such as `main`)".
400
- Each passing evidence entry on a commit counts only when one of the session's witnessed runs matches it:
415
+ A recorded run on the bound head counts directly for the anchor parts it ran. The caller need not copy its command or sha into `evidence`.
416
+ A passing evidence entry can identify a witnessed run for a merged commit or a binding moved to another clone. A pointer counts only when:
401
417
 
402
418
  - the entry's `command`, with every run of whitespace made one space, is the run's command, or the run's plain command without its leading `cd` and redirections;
403
- - a head in the run's `heads` starts with the entry's `sha`, which is then the commit it tested; a head is matched by its sha alone, so a binding whose `repo` moved to another clone keeps its runs;
404
- - the run runs one of the anchor's command parts alone: as plain runs, its words start with the part's words (a part's own leading `cd` and redirections set aside), and any words after them are extra arguments other than `--help`, `-h` and `--version`.
419
+ - a sha in the run's `heads` starts with the entry's `sha` (seven to 64 hex digits, case-insensitive), which is then the commit it tested; a head is matched by its sha alone, so a binding whose `repo` moved to another clone keeps its runs;
420
+ - each check in the run matches a part of the anchor: its words start with the part's words (a part's own leading `cd` and redirections set aside), and any words after them are extra arguments other than `--help`, `-h` and `--version`.
405
421
 
406
- A commit is tested when every command part of the anchor has such a run on it, each part its own run.
407
- Extra arguments can narrow a check (`npm test -- --test-name-pattern=zzz` runs no test); the ledger accepts them, and they stay visible in the evidence's `command` for whoever reads it.
408
- A completing update's result lists the witnessed runs that tested the todo's commits (`#3 completed on runs this session witnessed: "npm test" on c986d17a7fc4 in /Users/me/.herdr/worktrees/app/feat-parser.`), so a coordinator or reviewer sees the check used.
422
+ A commit is tested when witnessed checks cover every command part of the anchor on that same commit, whether separately or in a supported batch.
423
+ Extra arguments can narrow a check (`npm test -- --test-name-pattern=zzz` runs no test); the ledger accepts them, and they stay visible in the witness's `command` for whoever reads it.
424
+ A completing update's result lists the witnessed runs on the commit it accepted (`#3 completed on runs this session witnessed: "npm test" on c986d17a7fc4 in /Users/me/.herdr/worktrees/app/feat-parser.`), so a coordinator or reviewer sees the check used.
409
425
 
410
426
  #### Anchor command parts
411
427
 
package/README.md CHANGED
@@ -51,23 +51,26 @@ Use a name with `/boss send` only if it matches the name Straw Boss shows; a lau
51
51
  You can still set `owner` by hand.
52
52
 
53
53
  A launch whose `cwd` is a linked git worktree on a branch also binds the todo to that branch, in [`metadata.boundBranch`](CONTRACT.md#branch-binding-metadataboundbranch), with the head it started on.
54
- A bound todo completes only when it carries a passing evidence entry whose `sha` names the branch's current head, recorded earlier or in the completing call:
54
+ Once this session has run every check in the anchor on the bound head, complete the todo:
55
55
 
56
56
  ```text
57
- { "action": "update", "id": 3, "status": "completed", "evidence": [{ "command": "npm test", "sha": "c986d17a7fc4", "result": "pass" }] }
57
+ { "action": "update", "id": 3, "status": "completed" }
58
58
  ```
59
59
 
60
- Since 0.14.0 that entry counts only if the session ran its command itself.
60
+ There is no need to copy a witnessed check into `evidence`. An earlier worker report stays in the history; it neither proves nor invalidates the session's own run.
61
61
  While a bound todo is open, the ledger watches the session's `bash` calls and `MonitorCreate` monitors (for checks longer than a bash call may run).
62
62
  A run is recorded in a [`todo/witness`](CONTRACT.md#witnessed-runs-todowitness) entry when it ran in a checkout of the bound branch at its head with no uncommitted change and no untracked file, ended with exit 0, and left the head and tracked files as they were (new untracked output, such as a coverage report, is allowed).
63
63
  It runs in the session's directory, or in the one a single leading `cd <dir> &&` names.
64
- The evidence's `command` must name that run, with or without its leading `cd` and trailing redirections, and its `sha` the commit it ran on.
65
- The run must be the anchor's command alone, optionally with extra arguments: `npm test -- parser` counts for `npm test`, but `npm test | tail`, `npm test || true`, `echo npm test` and `npm test --help` do not.
66
- A bound todo's anchor must name its check as commands in code spans, one command with its arguments per span (`` `npm test` and `npm run check` ``); each needs its own run on the head. One-word spans such as `` `main` `` are no command.
64
+ A check may have extra arguments: `npm test -- parser` counts for `npm test`, but `npm test | tail`, `npm test || true`, `echo npm test` and `npm test --help` do not.
65
+ A bound todo's anchor must name its check as commands in code spans, one command with its arguments per span (`` `npm test` and `npm run check` ``); each must pass on the same head. One-word spans such as `` `main` `` are no command.
66
+ You can run the checks separately or join declared `npm` or `pnpm` checks with `&&`, for example `pnpm typecheck && pnpm test`. A nonzero exit records none of the batch.
67
+ The batch may start with `test "$(git rev-parse HEAD)" = <full-sha>` after the optional `cd`; other shell substitutions do not count.
67
68
  Completing a bound todo lists the witnessed runs that tested it.
68
69
  A bound todo whose anchor names no command cannot complete; put a check that is no command, such as a visual check or the boss's acceptance, in a separate todo that is not bound.
69
70
  A bound anchor without a command may gain its commands once (a launch into a worktree warns when it binds such a todo); after that they cannot change while the todo is open.
70
- A run that failed, a run in another checkout or session such as a worker's, and a result an agent relays do not count.
71
+ A clean linked worktree of the same repository counts, even with a detached HEAD at the bound commit.
72
+ If you need to switch commits, do so in a separate call before running the check; do not pipe the check to `tail`, whose success can hide a failure.
73
+ A run that failed, a run on another commit or in another session such as a worker's, and a result an agent relays do not count.
71
74
  Otherwise the ledger refuses the completion, names the head, and asks the agent to run the anchor itself on it.
72
75
  A launched branch merged into its base (`origin/HEAD`, else `main` or `master`) completes without evidence on its head only when the base also holds a tested commit of the branch's own work, made after the launch and tested by a recorded run.
73
76
  A branch deleted after a squash or rebase merge is refused with the `git branch` command that restores it at its last head.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-todo-ledger",
3
- "version": "0.14.0",
3
+ "version": "0.14.1",
4
4
  "description": "A todo list for pi agents with a public bookkeeping contract: snapshot entries, change events, and namespace validators. Fork of @juicesharp/rpiv-todo",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -43,9 +43,10 @@ export function makeFinishCall(pi: ExtensionAPI, namespaces: NamespaceRegistry,
43
43
  commitState(sessionId, result.state);
44
44
  return buildToolResult(action, input, result.state, result.op);
45
45
  }
46
+ let witnessNote: string | undefined;
46
47
  const refusal =
47
48
  namespaces.check(changedTasks(result.op, input, result.state, before)) ??
48
- (await headEvidenceRefusal(result.op, before, result.state, writer, runs)) ??
49
+ (await headEvidenceRefusal(result.op, before, result.state, writer, runs, (note) => { witnessNote = note; })) ??
49
50
  (await guards.check(guardChange));
50
51
  if (refusal) return refuse(action, input, before, refusal);
51
52
  if (signal?.aborted) return refuse(action, input, before, ABORTED);
@@ -75,7 +76,8 @@ export function makeFinishCall(pi: ExtensionAPI, namespaces: NamespaceRegistry,
75
76
  if (action === "clear") replaceState(sessionId, result.state);
76
77
  else commitState(sessionId, result.state);
77
78
  pi.events.emit(CHANGED_EVENT, toChangedEvent(sessionId, result.state));
78
- return buildToolResult(action, input, result.state, result.op);
79
+ const done = buildToolResult(action, input, result.state, result.op);
80
+ return witnessNote ? { ...done, content: [...done.content, { type: "text" as const, text: witnessNote }] } : done;
79
81
  };
80
82
  }
81
83
 
@@ -1,7 +1,7 @@
1
1
  /**
2
- * Head evidence: a todo bound to a branch (`metadata.boundBranch`) completes only on passing evidence for that branch's current head,
3
- * or once the branch is merged into its base. Evidence counts only when this session witnessed the run it names (witness.ts). The
4
- * ledger owns the namespace and checks it before the change guards; the git reads live in git-branch.ts.
2
+ * A bound todo can complete when this session witnessed every anchor check on the current head; the caller need not copy the runs
3
+ * into evidence. A merged branch with an untested or deleted head needs evidence pointing to witnessed work of its own in the base.
4
+ * The ledger checks metadata.boundBranch before the change guards; the git reads live in git-branch.ts.
5
5
  */
6
6
 
7
7
  import { isAbsolute } from "node:path";
@@ -82,20 +82,20 @@ const MAX_LISTED = 5;
82
82
  const listed = (shas: string[]) => shas.slice(0, MAX_LISTED).join(", ") + (shas.length > MAX_LISTED ? ` and ${shas.length - MAX_LISTED} more` : "");
83
83
 
84
84
  /**
85
- * Whether the base holds a tested commit of the branch's own work: a witnessed commit (`shas`) that `repo` resolves, that `base` holds, and
85
+ * Finds a tested commit of the branch's own work: a witnessed commit (`shas`) that `repo` resolves, that `base` holds, and
86
86
  * that descends from the binding's `start` without being it. The start must resolve in `repo`, and, when the branch still exists, be an
87
87
  * ancestor of its `head`. This is the only way a merged branch completes without evidence on its head; a binding without a start has
88
88
  * none. Evidence shas `repo` does not know are skipped.
89
89
  */
90
- async function ownWorkInBase(binding: BoundBranch, shas: string[], base: string, head?: string): Promise<boolean> {
90
+ async function ownWorkInBase(binding: BoundBranch, shas: string[], base: string, head?: string): Promise<string | undefined> {
91
91
  const start = binding.start ? await commitOf(binding.repo, binding.start) : undefined;
92
- if (!start || (head && !(await contains(binding.repo, start, head)))) return false;
92
+ if (!start || (head && !(await contains(binding.repo, start, head)))) return undefined;
93
93
  for (const sha of shas) {
94
94
  const commit = await commitOf(binding.repo, sha);
95
95
  if (!commit || commit === start) continue;
96
- if ((await contains(binding.repo, start, commit)) && (await contains(binding.repo, commit, base))) return true;
96
+ if ((await contains(binding.repo, start, commit)) && (await contains(binding.repo, commit, base))) return commit;
97
97
  }
98
- return false;
98
+ return undefined;
99
99
  }
100
100
 
101
101
  /**
@@ -118,18 +118,18 @@ export const ANCHOR_MUST_NAME_A_COMMAND =
118
118
  "a branch-bound todo's anchor must name its check as a command in backticks (e.g. `npm test`); put a non-command check (visual check, the boss's acceptance) in a separate todo that is not bound. Write one command per code span, with its arguments (`npm test` and `npm run check`, not `npm test && npm run check`, and not one word such as `main`)";
119
119
 
120
120
  /** Why bound `task` may not complete, or `undefined` when it may; a git read that gave no answer refuses. */
121
- async function judge(task: Task, binding: BoundBranch, runs: readonly Witness[]): Promise<string | undefined> {
121
+ async function judge(task: Task, binding: BoundBranch, runs: readonly Witness[], report: (note: string) => void): Promise<string | undefined> {
122
122
  // Only a run of a command the anchor names can show the check passed; a prose anchor names none.
123
123
  if (!anchorParts(task.anchor)) return `#${task.id} "${task.subject}" cannot complete: ${ANCHOR_MUST_NAME_A_COMMAND}.`;
124
124
  try {
125
- return await judgeRead(task, binding, runs);
125
+ return await judgeRead(task, binding, runs, report);
126
126
  } catch (error) {
127
127
  if (!(error instanceof GitReadError)) throw error;
128
128
  return `#${task.id} "${task.subject}" cannot complete: ${error.message} for its bound branch ${binding.ref}. Nothing changed; try again.`;
129
129
  }
130
130
  }
131
131
 
132
- async function judgeRead(task: Task, binding: BoundBranch, runs: readonly Witness[]): Promise<string | undefined> {
132
+ async function judgeRead(task: Task, binding: BoundBranch, runs: readonly Witness[], report: (note: string) => void): Promise<string | undefined> {
133
133
  const who = `#${task.id} "${task.subject}"`;
134
134
  const branch = `branch ${binding.ref} in ${binding.repo}`;
135
135
  const unreadable = await unreadableRepo(binding.repo);
@@ -140,29 +140,36 @@ async function judgeRead(task: Task, binding: BoundBranch, runs: readonly Witnes
140
140
  return `${who} cannot complete: base ${binding.base} is the branch itself, so it cannot show ${binding.ref} merged. Delete the todo if its binding is wrong.`;
141
141
  }
142
142
  const claimed = passingShas(task);
143
- const cov = coverage(task.evidence ?? [], task.anchor, runs);
144
- const shas = cov.tested;
145
143
  const head = await commitOf(binding.repo, `refs/heads/${binding.ref}`);
144
+ const cov = coverage(task.evidence ?? [], task.anchor, runs, (h) => h.sha === head && h.ref === binding.ref && h.repo === binding.repo);
145
+ const shas = cov.tested;
146
+ const accept = (sha: string) => {
147
+ const checks = cov.used(sha).map((r) => `"${r.command}" on ${sha.slice(0, 12)}${r.checkout ? ` in ${r.checkout}` : ""}`);
148
+ report(sanitizeTerminalText(`#${task.id} completed on runs this session witnessed: ${checks.slice(0, MAX_LISTED).join("; ")}${checks.length > MAX_LISTED ? ` and ${checks.length - MAX_LISTED} more` : ""}.`));
149
+ return undefined;
150
+ };
146
151
  const base = await baseOf(binding.repo, binding.base);
147
152
  const baseWords = binding.base === undefined ? "no base branch (origin/HEAD, main or master)" : `no base ${binding.base}`;
148
153
  if (head) {
149
- if (shas.includes(head)) return undefined;
154
+ if (shas.includes(head)) return accept(head);
150
155
  // Merged: the base holds the head and a tested commit of the branch's own work. A hand-made binding has no start.
151
156
  const inBase = !!(binding.start && base && (await contains(binding.repo, head, base.sha)));
152
- if (inBase && (await ownWorkInBase(binding, shas, base!.sha, head))) return undefined;
157
+ const mergedWork = inBase && await ownWorkInBase(binding, shas, base!.sha, head);
158
+ if (mergedWork) return accept(mergedWork);
153
159
  const onHead = cov.misses.find((m) => head.startsWith(m.sha));
154
160
  const left = cov.missing(head);
155
161
  const seen = cov.parts && left.length < cov.parts.length
156
- ? `Its witnessed runs on that commit still lack the anchor's command ${left.map((p) => `"${p}"`).join(" and ")}; each command of the anchor needs its own run.`
162
+ ? `Its witnessed runs on that commit still lack the anchor's command ${left.map((p) => `"${p}"`).join(" and ")}; each command of the anchor must pass.`
157
163
  : onHead
158
164
  ? `Its passing evidence on that commit is no run this session witnessed: ${onHead.why}.`
159
165
  : claimed.length ? `Its passing evidence names other commits: ${listed(claimed)}.` : "It has no passing evidence on that commit.";
160
166
  const merged = !binding.start || !base ? "" : inBase ? ` ${base.name} holds the head, but no tested commit of the branch's own work that this session witnessed.` : ` The branch is not merged into ${base.name}.`;
161
167
  const anchor = task.anchor ? `the anchor (${task.anchor})` : "the anchor";
162
- return `${who} is bound to ${branch}, whose head is ${head}. ${seen}${merged} Run ${anchor} yourself in this session on the head ${head}; relayed results do not count. Then record the command you ran as evidence { command, sha: "${head}", result: "pass" }, in the update that completes the todo or before it. Run it alone on a clean checkout of the branch; a check longer than a bash call may take goes under MonitorCreate in this session, whose exit-0 finish counts the same.`;
168
+ return `${who} is bound to ${branch}, whose head is ${head}. ${seen}${merged} Run ${anchor} yourself in this session on the head ${head}; relayed results do not count. Run it on a clean checkout of the head; no matching hand-written evidence is needed. A failed or piped check does not count; a check longer than a bash call may take goes under MonitorCreate in this session, whose exit-0 finish counts the same.`;
163
169
  }
164
170
  // Deleted after a merge: a tested commit of the branch's own work (not the start or before it) is in the base.
165
- if (base && (await ownWorkInBase(binding, shas, base.sha))) return undefined;
171
+ const mergedWork = base && await ownWorkInBase(binding, shas, base.sha);
172
+ if (mergedWork) return accept(mergedWork);
166
173
  let why: string;
167
174
  if (!binding.start) why = "a binding made by hand has no start to tell the branch's own commits from the base's";
168
175
  else if (!(await commitOf(binding.repo, binding.start))) why = `its start ${binding.start} is not in ${binding.repo}, so no commit there can show the branch's own work`;
@@ -174,28 +181,17 @@ async function judgeRead(task: Task, binding: BoundBranch, runs: readonly Witnes
174
181
  // rule judge it.
175
182
  const lastTested = shas.at(-1);
176
183
  const command = `\`git -C ${shellQuote(binding.repo)} branch ${binding.ref} <last head>\``;
177
- const restore = `restore it at its last head (the merged commit) with ${command}, and run the anchor yourself in this session on that commit and record it${lastTested ? `, if it is not ${lastTested}` : ""}`;
184
+ const restore = `restore it at its last head (the merged commit) with ${command}, and run the anchor yourself in this session on that commit${lastTested ? `, if it is not ${lastTested}` : ""}`;
178
185
  return `${who} cannot complete: its bound ${branch} no longer exists, and ${why}. If it was merged by squash or rebase, or deleted by mistake, ${restore}.`;
179
186
  }
180
187
 
181
188
  /**
182
- * What a successful `update` of a bound todo should show its caller, or `undefined`: that the anchor's command was set after binding (the
183
- * one edit anchorChange allows), and, on completion, the witnessed runs that tested its commits, so whoever reads the result sees the
184
- * check that was used. `runs` is read only on completion.
189
+ * Tell the caller when its update set the anchor's command after binding (the one edit anchorChange allows).
185
190
  */
186
- export function witnessNote(prev: Task | undefined, next: Task | undefined, runs: () => readonly Witness[]): string | undefined {
191
+ export function anchorChangeNote(prev: Task | undefined, next: Task | undefined): string | undefined {
187
192
  if (!prev || !next || !boundBranchOf(prev)) return undefined;
188
- const notes: string[] = [];
189
193
  const gained = !anchorParts(prev.anchor) && anchorParts(next.anchor);
190
- if (gained) {
191
- notes.push(`#${next.id}: its anchor's command was set after binding: ${gained.map((p) => `"${p}"`).join(" and ")}. It cannot change while the todo is open, and only witnessed runs of it complete the todo.`);
192
- }
193
- if (next.status === "completed" && prev.status !== "completed") {
194
- const cov = coverage(next.evidence ?? [], prev.anchor, runs());
195
- const checks = cov.tested.flatMap((sha) => cov.used(sha).map((r) => `"${r.command}" on ${sha.slice(0, 12)}${r.checkout ? ` in ${r.checkout}` : ""}`));
196
- if (checks.length) notes.push(`#${next.id} completed on runs this session witnessed: ${checks.slice(0, MAX_LISTED).join("; ")}${checks.length > MAX_LISTED ? ` and ${checks.length - MAX_LISTED} more` : ""}.`);
197
- }
198
- return notes.length ? sanitizeTerminalText(notes.join("\n")) : undefined;
194
+ return gained ? sanitizeTerminalText(`#${next.id}: its anchor's command was set after binding: ${gained.map((p) => `"${p}"`).join(" and ")}. It cannot change while the todo is open, and only witnessed runs of it complete the todo.`) : undefined;
199
195
  }
200
196
 
201
197
  /** The fields of a binding that stay as they were made while its todo is open. `repo` may move to another clone once it cannot be read (repoChange); `worktree` may change. */
@@ -248,6 +244,7 @@ export async function headEvidenceRefusal(
248
244
  after: TaskState,
249
245
  writer: BindingWriter = "tool",
250
246
  runs: () => readonly Witness[] = () => [],
247
+ report: (note: string) => void = () => {},
251
248
  ): Promise<string | undefined> {
252
249
  if (op.kind === "create" && writer === "tool") {
253
250
  for (const id of op.taskIds) {
@@ -271,6 +268,6 @@ export async function headEvidenceRefusal(
271
268
  if (op.fromStatus === "completed" || op.toStatus !== "completed") return undefined;
272
269
  const binding = boundBranchOf(next);
273
270
  // Judged against the anchor as it stood before this call: a completing update cannot bring its own anchor.
274
- const reason = binding ? await judge({ ...next, anchor: prev.anchor }, binding, runs()) : undefined;
271
+ const reason = binding ? await judge({ ...next, anchor: prev.anchor }, binding, runs(), report) : undefined;
275
272
  return reason && sanitizeTerminalText(reason);
276
273
  }
@@ -3,7 +3,7 @@
3
3
  * reads, before the run, the checkout the command runs in: the session's cwd, or the directory of one leading `cd <dir> &&`. The run is a
4
4
  * candidate when that checkout has a bound branch's head as its HEAD, no uncommitted change and no untracked file. When the call ends with exit 0 and
5
5
  * HEAD has not moved, the ledger appends a `todo/witness` entry naming the command, the checkout and the heads of those bound branches.
6
- * A session with no open bound todo, and a command that is no plain run, read no git.
6
+ * A session with no open bound anchor matching every check in the call reads no git.
7
7
  *
8
8
  * A long check runs under pi-loop-monitor's `MonitorCreate` instead. A `MonitorCreate` call of this session is read the same way before it
9
9
  * starts (its shell runs in the pi process's directory, or that of its leading `cd`); the `monitor:started` event it causes on `pi.events`
@@ -17,7 +17,7 @@ import { getState, listGeneration, sid } from "../state/store.ts";
17
17
  import { sanitizeTerminalText } from "../tool/sanitize.ts";
18
18
  import { cleanAt, commitOf, commonDirOf, GitReadError, headAt, statusAt } from "./git-branch.ts";
19
19
  import { type BoundBranch, boundBranchOf } from "./head-evidence.ts";
20
- import { anchorParts, MAX_WITNESSED_COMMAND, plainRun, runsPart, WITNESS_ENTRY_TYPE, type Witness, type WitnessHead } from "./witness.ts";
20
+ import { anchorParts, checkRun, type CheckRun, matchedParts, MAX_WITNESSED_COMMAND, mentionedParts, parseRun, WITNESS_ENTRY_TYPE, type Witness, type WitnessHead } from "./witness.ts";
21
21
 
22
22
  const record = (x: unknown): x is Record<string, unknown> => typeof x === "object" && x !== null && !Array.isArray(x);
23
23
 
@@ -44,19 +44,34 @@ const MONITOR_TOOL = "MonitorCreate";
44
44
  interface Note {
45
45
  note: string;
46
46
  once?: true;
47
+ /** Command-position hints are delivered once per anchor part, across tools in this session. */
48
+ mentions?: string[];
47
49
  }
48
50
 
49
- /** The bindings of the session's open bound todos whose anchor `command` runs a command of, one per repository and branch. */
50
- function openBindings(session: string, command: string): BoundBranch[] {
51
- const bindings = new Map<string, BoundBranch>();
52
- for (const task of getState(session).tasks) {
51
+ interface OpenAnchor {
52
+ binding: BoundBranch;
53
+ parts: string[];
54
+ }
55
+
56
+ function openAnchors(session: string): OpenAnchor[] {
57
+ return getState(session).tasks.flatMap((task) => {
53
58
  const binding = task.status === "pending" || task.status === "in_progress" ? boundBranchOf(task) : undefined;
54
- // A run that runs none of the todo's anchor commands can never count for it: it costs no git read.
55
- if (binding && anchorParts(task.anchor)?.some((part) => runsPart(command, part))) bindings.set(`${binding.repo}\0${binding.ref}`, binding);
59
+ const parts = binding && anchorParts(task.anchor);
60
+ return binding && parts ? [{ binding, parts }] : [];
61
+ });
62
+ }
63
+
64
+ /** Every step must match the same anchor; read a matching repository and branch only once. */
65
+ function openBindings(anchors: OpenAnchor[], run: CheckRun): BoundBranch[] {
66
+ const bindings = new Map<string, BoundBranch>();
67
+ for (const { binding, parts } of anchors) {
68
+ if (matchedParts(run, parts).length) bindings.set(`${binding.repo}\0${binding.ref}`, binding);
56
69
  }
57
70
  return [...bindings.values()];
58
71
  }
59
72
 
73
+ const commandWord = (words: string[]) => words.find((w) => !/^[A-Za-z_][A-Za-z0-9_]*=/.test(w));
74
+
60
75
  /** Common git directories of bound repositories read so far, by `repo` path: a path's repository does not change under it. */
61
76
  const commonDirs = new Map<string, string>();
62
77
 
@@ -80,14 +95,23 @@ async function commonDirOrNone(repo: string): Promise<string | undefined> {
80
95
  */
81
96
  async function capture(session: string, cwd: string, toolCallId: string, command: string): Promise<Capture | Note | undefined> {
82
97
  if (command.length > MAX_WITNESSED_COMMAND) return undefined;
83
- const run = plainRun(command);
84
- if (!run) return undefined;
85
- const bindings = openBindings(session, command);
86
- if (!bindings.length) return undefined;
98
+ const anchors = openAnchors(session);
99
+ if (!anchors.length) return undefined;
100
+ const run = checkRun(command);
101
+ if (!run) {
102
+ const mentions = mentionedParts(command, anchors.flatMap(({ parts }) => parts));
103
+ return mentions.length ? { mentions, note: "not witnessed: run checkout or setup in a separate call, then run the check without a pipe or wrapper." } : undefined;
104
+ }
105
+ const bindings = openBindings(anchors, run);
106
+ if (!bindings.length) {
107
+ const runners = new Set(run.steps.map((step) => commandWord(step.words)).filter((word) => word !== undefined));
108
+ const near = anchors.flatMap(({ parts }) => parts).find((part) => runners.has(commandWord(parseRun(part)!.words) ?? ""));
109
+ return near ? { note: `not witnessed: each && step must match a command of the same anchor. Keep the declared arguments in order (e.g. ${near}); extra steps or different selectors do not match. Run setup in a separate call.` } : undefined;
110
+ }
87
111
  const dir = run.cd === undefined ? cwd : resolve(cwd, run.cd.replace(/^~(?=$|\/)/, homedir()));
88
112
  try {
89
113
  const here = await headAt(dir);
90
- if (!here) return undefined;
114
+ if (!here || (run.pin && run.pin !== here.head)) return undefined;
91
115
  // The bindings first, read in parallel; `git status`, the costly read, only for a checkout of a bound branch's head.
92
116
  const matched = await Promise.all(
93
117
  bindings.map(async (binding) =>
@@ -134,13 +158,20 @@ export function registerWitnessRecorder(pi: ExtensionAPI) {
134
158
  pi.appendEntry(WITNESS_ENTRY_TYPE, entry);
135
159
  };
136
160
 
137
- /** The read failures already said, by session. */
161
+ /** One-time diagnostics already delivered, by session. */
138
162
  const said = new Map<string, Set<string>>();
139
163
  const say = (session: string, event: ToolResultEvent, why: Note) => {
164
+ if (!why.once && !why.mentions) return note(event, why.note);
140
165
  const seen = said.get(session) ?? new Set<string>();
141
- if (why.once && seen.has(why.note)) return undefined;
142
- seen.add(why.note);
143
166
  said.set(session, seen);
167
+ if (why.mentions) {
168
+ const fresh = why.mentions.filter((part) => !seen.has(`part:${part}`));
169
+ if (!fresh.length) return undefined;
170
+ for (const part of fresh) seen.add(`part:${part}`);
171
+ return note(event, `${why.note} Anchor: ${fresh.join(", ")}.`);
172
+ }
173
+ if (seen.has(why.note)) return undefined;
174
+ seen.add(why.note);
144
175
  return note(event, why.note);
145
176
  };
146
177
 
@@ -1,7 +1,6 @@
1
1
  /**
2
- * Witnessed runs: a todo bound to a branch (head-evidence.ts) completes only on passing evidence that matches a run this session's own
3
- * `bash` tool finished with exit 0 on the evidence's commit. The ledger records each such run in a `todo/witness` entry on the session
4
- * branch (witness-recorder.ts); this module reads those entries and matches evidence against them. It reads no git.
2
+ * A `todo/witness` entry records a successful bash or monitor check on this session's branch. Its checks can cover an anchor
3
+ * directly on the bound head or corroborate an evidence entry. This module reads the entries and compares commands, not git.
5
4
  */
6
5
 
7
6
  import { sid } from "../state/store.ts";
@@ -17,7 +16,7 @@ export interface WitnessHead {
17
16
  sha: string;
18
17
  }
19
18
 
20
- /** One `bash` run of this session that exited 0 on a clean checkout of a bound branch's head, which did not move while it ran. */
19
+ /** A bash call or MonitorCreate monitor this session ran to exit 0 on a clean bound head. One run may cover several checks. */
21
20
  export interface Witness {
22
21
  v: 1;
23
22
  /** The session that ran it; a copy of the entry in another session (a fork) does not count there. */
@@ -107,10 +106,11 @@ const blank = (c: string) => c === " " || c === "\t" || c === "\r";
107
106
 
108
107
  /**
109
108
  * `command` as shell tokens, or `undefined` when it holds what a plain run never needs: an expansion (`$`, a backtick, also inside
110
- * double quotes) or an unclosed quote.
109
+ * double quotes) or an unclosed quote. Hints alone may use the known prefix up to that point.
111
110
  */
112
- function lex(command: string): Token[] | undefined {
111
+ function lex(command: string, mode: "complete" | "hintPrefix" = "complete"): Token[] | undefined {
113
112
  const tokens: Token[] = [];
113
+ const stop = () => mode === "hintPrefix" ? tokens : undefined;
114
114
  let i = 0;
115
115
  while (i < command.length) {
116
116
  if (blank(command[i])) {
@@ -126,18 +126,18 @@ function lex(command: string): Token[] | undefined {
126
126
  const start = i;
127
127
  while (i < command.length && !blank(command[i]) && !opAt(command, i)) {
128
128
  const c = command[i];
129
- if (c === "$" || c === "`") return undefined;
129
+ if (c === "$" || c === "`") return stop();
130
130
  if (c === "'") {
131
131
  const close = command.indexOf("'", i + 1);
132
- if (close < 0) return undefined;
132
+ if (close < 0) return stop();
133
133
  i = close + 1;
134
134
  } else if (c === '"') {
135
135
  let j = i + 1;
136
136
  for (; j < command.length && command[j] !== '"'; j++) {
137
- if (command[j] === "$" || command[j] === "`") return undefined;
137
+ if (command[j] === "$" || command[j] === "`") return stop();
138
138
  if (command[j] === "\\") j++;
139
139
  }
140
- if (j >= command.length) return undefined;
140
+ if (j >= command.length) return stop();
141
141
  i = j + 1;
142
142
  } else i += c === "\\" ? 2 : 1;
143
143
  }
@@ -146,6 +146,27 @@ function lex(command: string): Token[] | undefined {
146
146
  return tokens;
147
147
  }
148
148
 
149
+ const SEGMENT_BOUNDARIES = new Set(["&&", "||", ";", "&", "|", "|&", "(", "\n"]);
150
+
151
+ /** Unsupported shell forms: hint only for an anchor prefix in command position, never use a partial parse as evidence. */
152
+ export function mentionedParts(command: string, parts: readonly string[]): string[] {
153
+ const tokens = lex(command, "hintPrefix") ?? [];
154
+ const starts: number[] = [];
155
+ let atStart = true, comment = false;
156
+ for (const [i, token] of tokens.entries()) {
157
+ if (token.op === "\n") comment = false;
158
+ if (token.word?.startsWith("#")) comment = true;
159
+ if (comment) continue;
160
+ if (token.op === "<<") break; // Do not treat a here-document's body as shell commands.
161
+ if (atStart && token.word) starts.push(i);
162
+ atStart = SEGMENT_BOUNDARIES.has(token.op ?? "");
163
+ }
164
+ return [...new Set(parts)].filter((part) => {
165
+ const words = parseRun(part)?.words;
166
+ return words && starts.some((i) => words.every((word, k) => tokens[i + k]?.word === word));
167
+ });
168
+ }
169
+
149
170
  /** Redirections a run may end with: they change where output goes, not how the command exits. */
150
171
  const REDIRECTS = new Set([">", ">>", ">&", "&>", "&>>", ">|", "<", "<>"]);
151
172
  /** Words that make a command print help or a version instead of running its check. */
@@ -199,23 +220,80 @@ export function plainRun(command: string): PlainRun | undefined {
199
220
  */
200
221
  export function runsPart(command: string, part: string): boolean {
201
222
  const run = plainRun(command);
223
+ return !!run && matchesPart(run, part);
224
+ }
225
+
226
+ function matchesPart(run: PlainRun, part: string): boolean {
202
227
  const want = parseRun(part);
203
- return !!run && !!want && run.words.length >= want.words.length && want.words.every((w, k) => run.words[k] === w);
228
+ return !!want && run.words.length >= want.words.length && want.words.every((w, k) => run.words[k] === w);
229
+ }
230
+
231
+ /** The checks whose success a single tool exit can prove. No step may change the shell's directory or skip a later check. */
232
+ export interface CheckRun {
233
+ cd?: string;
234
+ pin?: string;
235
+ steps: PlainRun[];
236
+ }
237
+
238
+ export function checkRun(command: string): CheckRun | undefined {
239
+ const one = plainRun(command);
240
+ if (one) return { cd: one.cd, steps: [one] };
241
+ // Deliberately not a shell interpreter. The batch grammar has no quoting, expansion or operator inside a
242
+ // step. Its sole substitution is the literal, read-only HEAD assertion used before long package checks.
243
+ const segments = command.replace(/^[ \t]+|[ \t\n]+$/g, "").split(/[ \t]*&&[ \t]*/);
244
+ if (segments.length < 2) return undefined;
245
+ const cd = /^cd[ \t]+((?:\/|~\/|\.\.?\/)[\w./+@-]*)$/.exec(segments[0])?.[1];
246
+ if (cd) segments.shift();
247
+ const pin = /^test[ \t]+"\$\(git rev-parse HEAD\)"[ \t]+=[ \t]+([0-9a-f]{40}|[0-9a-f]{64})$/.exec(segments[0] ?? "")?.[1];
248
+ if (pin) segments.shift();
249
+ if (!segments.length || (!pin && segments.length < 2)) return undefined;
250
+ const steps: PlainRun[] = [];
251
+ for (const segment of segments) {
252
+ if (!/^(?:npm|pnpm)(?:[ \t]+[\w@./:+-]+)+$/.test(segment)) return undefined;
253
+ const step = plainRun(segment);
254
+ if (!step) return undefined;
255
+ steps.push(step);
256
+ }
257
+ return { cd, pin, steps };
258
+ }
259
+
260
+ /** All steps must run declared parts of this anchor; unrelated setup is not a check. */
261
+ export function matchedParts(run: CheckRun, parts: readonly string[]): number[] {
262
+ const hits = new Set<number>();
263
+ for (const step of run.steps) {
264
+ const matches = parts.flatMap((part, i) => matchesPart(step, part) ? [i] : []);
265
+ if (!matches.length) return [];
266
+ for (const i of matches) hits.add(i);
267
+ }
268
+ return [...hits];
204
269
  }
205
270
 
206
271
  /** Whether evidence `command` (normalized) names witnessed `run`: its whole command, or its plain command without the leading cd and redirections. */
207
272
  const names = (command: string, run: Witness) => normalize(run.command) === command || parseRun(run.command)?.core === command;
208
273
 
209
274
  /**
210
- * What a todo's passing evidence tested, judged against this session's witnessed runs. An entry stands for a commit when a witnessed
211
- * run it names was made on a head that starts with its `sha`, and that run's command runs one of the anchor's command parts alone
212
- * (runsPart). A commit is tested when every command part has such a run on it; an anchor without one tests nothing.
275
+ * A commit is tested when witnessed runs cover every anchor part on it. Direct head witnesses need no evidence pointer;
276
+ * for the existing merge exemptions and relocated repositories, a passing entry must still name the run and commit.
213
277
  */
214
- export function coverage(evidence: readonly Evidence[], anchor: string | undefined, runs: readonly Witness[]) {
278
+ export function coverage(evidence: readonly Evidence[], anchor: string | undefined, runs: readonly Witness[], direct?: (head: WitnessHead) => boolean) {
215
279
  const parts = anchorParts(anchor);
216
280
  const covered = new Map<string, Set<number>>();
217
281
  const used = new Map<string, Array<{ command: string; checkout?: string }>>();
218
282
  const misses: Array<{ sha: string; why: string }> = [];
283
+ const add = (run: Witness, head: WitnessHead): boolean => {
284
+ const plan = checkRun(run.command);
285
+ const found = plan && parts ? matchedParts(plan, parts) : [];
286
+ if (!found.length) return false;
287
+ const set = covered.get(head.sha) ?? new Set<number>();
288
+ for (const k of found) set.add(k);
289
+ covered.set(head.sha, set);
290
+ const checks = used.get(head.sha) ?? [];
291
+ if (!checks.some((r) => r.command === run.command && r.checkout === run.checkout)) checks.push({ command: run.command, checkout: run.checkout });
292
+ used.set(head.sha, checks);
293
+ return true;
294
+ };
295
+ // A witnessed run on the bound head is already proof, whether or not a hand-written entry names it.
296
+ if (direct) for (const run of runs) for (const head of run.heads) if (direct(head)) add(run, head);
219
297
  for (const entry of evidence) {
220
298
  const sha = (entry.sha ?? "").trim().toLowerCase();
221
299
  if (entry.result !== "pass" || !SHA.test(sha)) continue;
@@ -233,19 +311,11 @@ export function coverage(evidence: readonly Evidence[], anchor: string | undefin
233
311
  }
234
312
  let hit = false;
235
313
  for (const { run, head } of onSha) {
236
- const found = (parts ?? []).flatMap((part, k) => (runsPart(run.command, part) ? [k] : []));
237
- if (!found.length) continue;
238
- hit = true;
239
- const set = covered.get(head.sha) ?? new Set<number>();
240
- for (const k of found) set.add(k);
241
- covered.set(head.sha, set);
242
- const runs = used.get(head.sha) ?? [];
243
- if (!runs.some((r) => r.command === run.command && r.checkout === run.checkout)) runs.push({ command: run.command, ...(run.checkout ? { checkout: run.checkout } : {}) });
244
- used.set(head.sha, runs);
314
+ if (add(run, head)) hit = true;
245
315
  }
246
316
  if (!hit) {
247
317
  const want = parts ? `the anchor's command ${parts.map((p) => `"${p}"`).join(" or ")}` : "a command of the anchor, which names none";
248
- misses.push({ sha, why: `"${command}" does not run ${want} alone: only one leading cd, extra arguments and trailing redirections may come with it` });
318
+ misses.push({ sha, why: `"${command}" does not match ${want} as a plain check or a declared fail-fast batch` });
249
319
  }
250
320
  }
251
321
  return {
package/src/todo.ts CHANGED
@@ -22,7 +22,7 @@ import { TransferJournal } from "./ledger/transfer-journal.ts";
22
22
  import { branchWitness } from "./ledger/transfer-branch.ts";
23
23
  import { importMove, sendMove } from "./ledger/move-file.ts";
24
24
  import { witnessesOn } from "./ledger/witness.ts";
25
- import { witnessNote } from "./ledger/head-evidence.ts";
25
+ import { anchorChangeNote } from "./ledger/head-evidence.ts";
26
26
  import { formatStatusLabel, t } from "./state/i18n-bridge.ts";
27
27
  import { listOnBranch } from "./state/replay.ts";
28
28
  import { selectTasksByStatus, selectTodoCounts, selectVisibleTasks } from "./state/selectors.ts";
@@ -127,8 +127,8 @@ export function registerTodoTool(pi: ExtensionAPI, finish: FinishCall, writers:
127
127
  // A completion of a bound todo counts only this session's witnessed runs, read from the branch when it is judged.
128
128
  const done = await finish(sessionId, ctx.cwd, action, input, before, result, signal, transfer ? onOriginalBranch : undefined, journal, "tool", () => witnessesOn(ctx));
129
129
  if (action !== "update" || ("isError" in done && done.isError)) return done;
130
- // A bound todo's result shows an anchor command set after binding, and on completion the witnessed runs that tested it.
131
- const note = witnessNote(before.tasks.find((t) => t.id === input.id), getState(sessionId).tasks.find((t) => t.id === input.id), () => witnessesOn(ctx));
130
+ // The commit boundary supplied the proof of completion; an anchor edit has its own notice.
131
+ const note = anchorChangeNote(before.tasks.find((t) => t.id === input.id), getState(sessionId).tasks.find((t) => t.id === input.id));
132
132
  return note ? { ...done, content: [...done.content, { type: "text" as const, text: note }] } : done;
133
133
  });
134
134
  },