pi-todo-ledger 0.13.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,6 +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
+ > A branch-bound todo's completion uses [witnessed runs](#witnessed-runs-todowitness), not the agent's report: this session must run the anchor itself.
51
52
  > Use it to find which checks were run and on which revision, so the next round can reuse a green run.
52
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.
53
54
 
@@ -284,7 +285,7 @@ The figures are an estimate from what pi wrote in the child's transcript, bookke
284
285
 
285
286
  ### Branch binding (`metadata.boundBranch`)
286
287
 
287
- 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.
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.
288
289
  The ledger owns this namespace:
289
290
 
290
291
  ```json
@@ -310,28 +311,28 @@ The binding is set two ways:
310
311
  If git does not answer while the launch is read (a timeout, a signal), the owner is still bound and the launch's result carries a warning that the todo is not bound to a branch.
311
312
  - An agent may set it through `metadata` on `create` or `update`, for example when it created the worktree itself. A binding made by hand has no `start`: an agent cannot set one.
312
313
 
313
- While the todo is open, a `todo` call cannot remove the binding or change its `ref`, `base` or `start`; only a launch can rebind.
314
+ While the todo is open, a `todo` call cannot remove the binding or change its `ref`, `base` or `start`; only a launch can rebind. Nor can it change the anchor's command parts (see [Witnessed runs](#witnessed-runs-todowitness)).
314
315
  `repo` may change, while the branch stays the same, only when the bound repository cannot be read (a clone that moved), and `worktree` may change.
315
316
  Deleting the todo, with `delete` or an `update` to `deleted`, stays allowed.
316
317
 
317
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:
318
319
 
319
- 1. The branch exists, and a 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. 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.
320
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.
321
322
  3. The branch no longer exists (deleted after a merge), and the base holds a tested commit of the branch's own work.
322
323
 
323
- A tested commit of the branch's own work is a commit that a passing evidence entry names, that the repository knows, and that descends from the binding's `start` without being it.
324
+ A tested commit of the branch's own work is a commit that a witnessed passing evidence entry names, that the repository knows, and that descends from the binding's `start` without being it.
324
325
  The `start` must resolve in `repo`, and in rule 2 it must also be an ancestor of the head.
325
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.
326
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.
327
- Otherwise the call is refused and nothing changes. The refusal names the todo, the branch, its head sha and the evidence shas seen, and says to run the anchor on the head 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:
328
329
 
329
330
  ```text
330
- 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) on c986d17a7fc4eac254bba796e7ddf6d2025b50b7 and record it as evidence { sha: "c986d17a7fc4eac254bba796e7ddf6d2025b50b7", result: "pass" }, in the update that completes the todo or before it.
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.
331
332
  ```
332
333
 
333
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.
334
- 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 record passing evidence on that commit if it is not the last tested 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.
335
336
 
336
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.
337
338
  Only git's own "no such ref" (exit 1 with nothing on stderr) counts as a missing branch.
@@ -339,7 +340,106 @@ There is no force flag.
339
340
  A todo without a binding, an update that does not complete, and a todo already completed are not checked.
340
341
  Each git command may take up to five seconds; the check runs inside the session's call queue.
341
342
 
342
- Evidence stays self-reported (see [Task](#task)): the check compares recorded shas with the branch, and runs nothing.
343
+ The check runs nothing: it compares recorded shas with the branch and with the session's witnessed runs.
344
+
345
+ ### Witnessed runs (`todo/witness`)
346
+
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.
348
+ The ledger watches two kinds of run while any todo of the session is open (`pending` or `in_progress`) and bound:
349
+
350
+ - a call of pi's `bash` tool, including nested calls a tool makes through `ctx.executeTool`;
351
+ - a `MonitorCreate` call of pi-loop-monitor, for a check longer than a bash call may run.
352
+
353
+ #### Which runs are recorded
354
+
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).
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
+ 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
+ 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
+
361
+ A `bash` run is recorded when the call ends with exit 0 (no error result, `exit_code` 0).
362
+ A monitor is recorded when pi-loop-monitor's `monitor:finished` event on `pi.events` says status `completed` and exit code 0.
363
+ `monitor:started` names no tool call, so the ledger ties a monitor to the one `MonitorCreate` call of the session pending on the same command; when two calls are pending on the same command, neither monitor is recorded.
364
+ Either way, when the run ends, `HEAD` must still be that head, and `git status` may list only new untracked paths: output the run wrote itself, such as a coverage report, since the checkout had none when it started. Any other line, a changed, staged or deleted tracked file, refuses.
365
+ A stopped or failed monitor, and a monitor this session did not start, are not recorded.
366
+ The ledger then appends one custom entry to the session branch:
367
+
368
+ ```json
369
+ { "type": "custom", "customType": "todo/witness", "data": { "v": 1, "session": "<session id>", "toolCallId": "<bash or MonitorCreate call id>", "monitorId": "<for a monitor>", "command": "npm test -- parser", "at": "2026-12-01T05:12:09.411Z", "checkout": "/Users/me/.herdr/worktrees/app/feat-parser", "heads": [{ "repo": "/Users/me/projects/app/.git", "ref": "feat/parser", "sha": "c986d17a7fc4eac254bba796e7ddf6d2025b50b7" }] } }
370
+ ```
371
+
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
+ 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 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.
379
+
380
+ #### Which run forms count
381
+
382
+ For a single check, after one leading `cd <dir> &&` and trailing redirections are set aside, what remains must be words only.
383
+
384
+ These count, under `bash` or `MonitorCreate` alike, for the anchor command `npm test`:
385
+
386
+ - `npm test`, and with extra arguments: `npm test -- parser`;
387
+ - one leading `cd`: `cd /path/to/worktree && npm test`;
388
+ - trailing redirections: `npm test > /tmp/log 2>&1`, `npm test >>log`, `npm test 2>/dev/null`, `npm test < in`.
389
+
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:
402
+
403
+ - a pipe, even with `set -o pipefail`: `npm test 2>&1 | tail`, `npm test | tee log`;
404
+ - other chains or lists: `npm test; echo done`, `npm test || true`, `wrapper.sh && cd <dir> && npm test`, a background `&`, a newline;
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` ``);
406
+ - any expansion other than the batch's exact HEAD assertion, including inside double quotes: `cd $WT && npm test`, `npm test "$(date)"`, a backtick;
407
+ - a comment, group, negation, subshell, function, alias or trap: `true # npm test`, `{ npm test; }`, `! npm test`, `(npm test)`, `npm() { :; }; npm test`;
408
+ - a help or version request: `npm test --help`, `-h`, `--version`;
409
+ - another command: `pnpm test`, `npm test-not-really`, `echo npm test`.
410
+
411
+ #### Matching evidence to runs
412
+
413
+ When a bound todo completes, it is judged against its anchor as it stood before the completing call.
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`)".
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:
417
+
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;
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`.
421
+
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.
425
+
426
+ #### Anchor command parts
427
+
428
+ An anchor's command parts are its code spans that name a command: the span is a plain run, and after any `NAME=value` assignments it starts with a path (`./`, `../`, `/` or `~/`), or with a lower-case name (letters, digits, `_`, `+`, `-`) followed by at least one argument.
429
+ So `` `npm test` ``, `` `make check` ``, `` `./scripts/check.sh` `` and `` `CI=1 npm test` `` are parts. `` `feat/x` ``, `` `package.json` ``, `` `metadata.boundBranch` `` and one-word spans such as `` `main` ``, `` `src` `` or `` `true` `` are not, so they neither lock the anchor nor need a run. A span that holds several commands (`` `npm test && npm run check` ``) is no part either: write one command per code span.
430
+ Text outside code spans is never a command: `npm test passes` written without backticks has no part.
431
+ Nothing is looked up on `PATH`, so the same anchor reads the same on every machine.
432
+
433
+ While a bound todo is open, a `todo` call cannot change its anchor's command parts. Text around the same spans may change. An anchor with no part may gain parts once, so a todo bound with a prose anchor can still name its check; after that the parts stay. The update that does so says on its result that the anchor's command was set after binding.
434
+ A launch that binds a todo whose anchor has no part says so on its result, so the launcher can set the command before the worker finishes.
435
+ That one edit is no weaker than the alternative: a todo that could not gain a command would be deleted and redone unbound, with no check at all. The anchor stays visible on the todo.
436
+
437
+ #### Sessions and persistence
438
+
439
+ Only the session that ran the command counts it: the ledger skips an entry whose `data.session` is not the session's id, so the entries a fork copies from its parent count for the parent, not the fork, and a subagent's runs never count for its launcher.
440
+ Only entries on the session's current branch count. They persist with the session: replay and `/reload` read them and judge nothing again.
441
+ The ledger owns `metadata.witnessed`: a `todo` call or import that sets it is refused (`metadata.witnessed refused #<id>: …`), and no `todo:namespace` registration replaces that validator.
442
+ Todos without a binding ignore all of this; their evidence stays as described in [Task](#task).
343
443
 
344
444
  ## 4. Change guards
345
445
 
package/README.md CHANGED
@@ -51,14 +51,28 @@ 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
- Otherwise the ledger refuses the completion and names the head to run the anchor on.
61
- 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.
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
+ 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
+ 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
+ It runs in the session's directory, or in the one a single leading `cd <dir> &&` names.
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.
68
+ Completing a bound todo lists the witnessed runs that tested it.
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.
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.
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.
74
+ Otherwise the ledger refuses the completion, names the head, and asks the agent to run the anchor itself on it.
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.
62
76
  A branch deleted after a squash or rebase merge is refused with the `git branch` command that restores it at its last head.
63
77
  A repository or branch that cannot be read, or a git command that times out, is refused with the reason.
64
78
  While the todo is open its binding stays. A later launch onto another branch, such as a reviewer's worktree, rebinds it only once the bound branch is deleted or merged; `repo` may move to another clone only when the bound one cannot be read.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-todo-ledger",
3
- "version": "0.13.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",
package/src/index.ts CHANGED
@@ -43,6 +43,8 @@ import { BOUND_BRANCH, validateBoundBranch } from "./ledger/head-evidence.ts";
43
43
  import { registerHerdrOwner } from "./ledger/herdr-owner.ts";
44
44
  import { registerHerdrSpend } from "./ledger/herdr-spend.ts";
45
45
  import { NamespaceRegistry } from "./ledger/namespaces.ts";
46
+ import { refuseWitnessed, WITNESSED } from "./ledger/witness.ts";
47
+ import { registerWitnessRecorder } from "./ledger/witness-recorder.ts";
46
48
  import { I18N_NAMESPACE } from "./state/i18n-bridge.ts";
47
49
  import { replayFromBranch } from "./state/replay.ts";
48
50
  import {
@@ -206,6 +208,7 @@ export default function (
206
208
  const namespaces = new NamespaceRegistry();
207
209
  namespaces.own(FLOW_NAMESPACE, validateFlowMetadata);
208
210
  namespaces.own(BOUND_BRANCH, validateBoundBranch);
211
+ namespaces.own(WITNESSED, refuseWitnessed);
209
212
  const guards = new GuardRegistry(options.guardTimeoutMs ?? GUARD_TIMEOUT_MS);
210
213
  pi.events.on(NAMESPACE_EVENT, (payload) => {
211
214
  const ignored = namespaces.register(payload);
@@ -222,6 +225,7 @@ export default function (
222
225
  registerFlowTool(pi, finish);
223
226
  registerHerdrOwner(pi, finish);
224
227
  registerHerdrSpend(pi, makeCommitNow(pi, namespaces));
228
+ registerWitnessRecorder(pi);
225
229
  registerTodosCommand(pi);
226
230
  pi.events.emit(READY_EVENT, { v: CONTRACT_VERSION });
227
231
 
@@ -8,6 +8,7 @@ import { CHANGED_EVENT, type GuardOp, SNAPSHOT_ENTRY_TYPE, toChangedEvent, toSna
8
8
  import type { TransferJournal } from "./transfer-journal.ts";
9
9
  import type { GuardRegistry } from "./guards.ts";
10
10
  import { type BindingWriter, headEvidenceRefusal } from "./head-evidence.ts";
11
+ import type { Witness } from "./witness.ts";
11
12
  import { changedTasks, type NamespaceRegistry } from "./namespaces.ts";
12
13
 
13
14
  // If even the physical snapshot cannot be read back, no writer using this process's live slot may replace it.
@@ -22,7 +23,7 @@ export function refuse(action: TaskAction, input: TaskMutationParams, state: Tas
22
23
 
23
24
  /** Shared commit boundary for tool calls and acknowledged Herdr launches. Caller holds the session lock. */
24
25
  export function makeFinishCall(pi: ExtensionAPI, namespaces: NamespaceRegistry, guards: GuardRegistry) {
25
- return async (sessionId: string, cwd: string, action: TaskAction, input: TaskMutationParams, before: TaskState, result: ApplyResult, signal?: AbortSignal, onOriginalBranch?: () => boolean, journal?: TransferJournal, writer: BindingWriter = "tool") => {
26
+ return async (sessionId: string, cwd: string, action: TaskAction, input: TaskMutationParams, before: TaskState, result: ApplyResult, signal?: AbortSignal, onOriginalBranch?: () => boolean, journal?: TransferJournal, writer: BindingWriter = "tool", runs?: () => readonly Witness[]) => {
26
27
  const blocked = blockedWrite(sessionId);
27
28
  if (blocked && action !== "list" && action !== "get") return refuse(action, input, before, blocked);
28
29
  const guardChange = {
@@ -42,9 +43,10 @@ export function makeFinishCall(pi: ExtensionAPI, namespaces: NamespaceRegistry,
42
43
  commitState(sessionId, result.state);
43
44
  return buildToolResult(action, input, result.state, result.op);
44
45
  }
46
+ let witnessNote: string | undefined;
45
47
  const refusal =
46
48
  namespaces.check(changedTasks(result.op, input, result.state, before)) ??
47
- (await headEvidenceRefusal(result.op, before, result.state, writer)) ??
49
+ (await headEvidenceRefusal(result.op, before, result.state, writer, runs, (note) => { witnessNote = note; })) ??
48
50
  (await guards.check(guardChange));
49
51
  if (refusal) return refuse(action, input, before, refusal);
50
52
  if (signal?.aborted) return refuse(action, input, before, ABORTED);
@@ -74,7 +76,8 @@ export function makeFinishCall(pi: ExtensionAPI, namespaces: NamespaceRegistry,
74
76
  if (action === "clear") replaceState(sessionId, result.state);
75
77
  else commitState(sessionId, result.state);
76
78
  pi.events.emit(CHANGED_EVENT, toChangedEvent(sessionId, result.state));
77
- 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;
78
81
  };
79
82
  }
80
83
 
@@ -120,6 +120,27 @@ export async function commonDirOf(path: string): Promise<string | undefined> {
120
120
  return run.kind === "ok" && run.stdout ? real(run.stdout) : undefined;
121
121
  }
122
122
 
123
+ /** The shared git directory and HEAD commit of the checkout at `dir`; `undefined` when `dir` is no git checkout or HEAD names no commit. */
124
+ export async function headAt(dir: string): Promise<{ commonDir: string; head: string } | undefined> {
125
+ const commonDir = await commonDirOf(dir);
126
+ const head = commonDir ? await commitOf(dir, "HEAD") : undefined;
127
+ return commonDir && head ? { commonDir, head } : undefined;
128
+ }
129
+
130
+ /**
131
+ * The `git status --porcelain --untracked-files=normal` lines of the checkout at `dir` (ignored files aside): one per changed or untracked
132
+ * path, untracked ones starting with `?? `. `undefined` when git cannot tell.
133
+ */
134
+ export async function statusAt(dir: string): Promise<string[] | undefined> {
135
+ const status = answered(await git(dir, ["status", "--porcelain", "--untracked-files=normal"]), `the status of ${dir}`);
136
+ return status.kind === "ok" ? status.stdout.split("\n").filter(Boolean) : undefined;
137
+ }
138
+
139
+ /** Whether the checkout at `dir` has no uncommitted change and no untracked file (ignored files aside); false when git cannot tell. */
140
+ export async function cleanAt(dir: string): Promise<boolean> {
141
+ return (await statusAt(dir))?.length === 0;
142
+ }
143
+
123
144
  /**
124
145
  * Whether commit `sha` is `base` or one of its ancestors: git's exit 0 or 1. Any other answer, such as 128 for a commit `repo` does
125
146
  * not have, and a git that dies, throw a `GitReadError`: an unknown commit is never "not an ancestor".
@@ -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. The ledger owns the namespace and checks it before the change guards; the git reads
4
- * 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";
@@ -11,6 +11,7 @@ import { sanitizeTerminalText } from "../tool/sanitize.ts";
11
11
  import type { Task } from "../tool/types.ts";
12
12
  import type { NamespaceValidator } from "./contract.ts";
13
13
  import { baseOf, commitOf, contains, GitReadError, isBranchItself, unreadableRepo } from "./git-branch.ts";
14
+ import { anchorParts, coverage, type Witness } from "./witness.ts";
14
15
 
15
16
  export const BOUND_BRANCH = "boundBranch";
16
17
 
@@ -81,48 +82,54 @@ const MAX_LISTED = 5;
81
82
  const listed = (shas: string[]) => shas.slice(0, MAX_LISTED).join(", ") + (shas.length > MAX_LISTED ? ` and ${shas.length - MAX_LISTED} more` : "");
82
83
 
83
84
  /**
84
- * Whether the base holds a tested commit of the branch's own work: a passing evidence sha 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
85
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
86
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
87
88
  * none. Evidence shas `repo` does not know are skipped.
88
89
  */
89
- 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> {
90
91
  const start = binding.start ? await commitOf(binding.repo, binding.start) : undefined;
91
- if (!start || (head && !(await contains(binding.repo, start, head)))) return false;
92
+ if (!start || (head && !(await contains(binding.repo, start, head)))) return undefined;
92
93
  for (const sha of shas) {
93
94
  const commit = await commitOf(binding.repo, sha);
94
95
  if (!commit || commit === start) continue;
95
- 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;
96
97
  }
97
- return false;
98
+ return undefined;
98
99
  }
99
100
 
100
101
  /**
101
102
  * Whether a launch onto another branch may replace `task`'s binding: the todo has none, its branch no longer exists, or the branch merged
102
- * with a tested commit of its own work. Otherwise the binding stays, so a reviewer's worktree never takes over a worker's todo. A git
103
- * read that gives no answer throws a `GitReadError`.
103
+ * with a tested commit of its own work, one of the launching session's witnessed `runs`. Otherwise the binding stays, so a reviewer's
104
+ * worktree never takes over a worker's todo. A git read that gives no answer throws a `GitReadError`.
104
105
  */
105
- export async function launchMayRebind(task: Task): Promise<boolean> {
106
+ export async function launchMayRebind(task: Task, runs: readonly Witness[]): Promise<boolean> {
106
107
  const binding = boundBranchOf(task);
107
108
  if (!binding) return true;
108
109
  if (await unreadableRepo(binding.repo)) return false;
109
110
  const head = await commitOf(binding.repo, `refs/heads/${binding.ref}`);
110
111
  if (!head) return true;
111
112
  const base = await baseOf(binding.repo, binding.base);
112
- return !!(base && (await contains(binding.repo, head, base.sha)) && (await ownWorkInBase(binding, passingShas(task), base.sha, head)));
113
+ return !!(base && (await contains(binding.repo, head, base.sha)) && (await ownWorkInBase(binding, coverage(task.evidence ?? [], task.anchor, runs).tested, base.sha, head)));
113
114
  }
114
115
 
116
+ /** Why a bound todo whose anchor has no command part cannot complete; a launch that binds one says it too. */
117
+ export const ANCHOR_MUST_NAME_A_COMMAND =
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
+
115
120
  /** Why bound `task` may not complete, or `undefined` when it may; a git read that gave no answer refuses. */
116
- async function judge(task: Task, binding: BoundBranch): Promise<string | undefined> {
121
+ async function judge(task: Task, binding: BoundBranch, runs: readonly Witness[], report: (note: string) => void): Promise<string | undefined> {
122
+ // Only a run of a command the anchor names can show the check passed; a prose anchor names none.
123
+ if (!anchorParts(task.anchor)) return `#${task.id} "${task.subject}" cannot complete: ${ANCHOR_MUST_NAME_A_COMMAND}.`;
117
124
  try {
118
- return await judgeRead(task, binding);
125
+ return await judgeRead(task, binding, runs, report);
119
126
  } catch (error) {
120
127
  if (!(error instanceof GitReadError)) throw error;
121
128
  return `#${task.id} "${task.subject}" cannot complete: ${error.message} for its bound branch ${binding.ref}. Nothing changed; try again.`;
122
129
  }
123
130
  }
124
131
 
125
- async function judgeRead(task: Task, binding: BoundBranch): Promise<string | undefined> {
132
+ async function judgeRead(task: Task, binding: BoundBranch, runs: readonly Witness[], report: (note: string) => void): Promise<string | undefined> {
126
133
  const who = `#${task.id} "${task.subject}"`;
127
134
  const branch = `branch ${binding.ref} in ${binding.repo}`;
128
135
  const unreadable = await unreadableRepo(binding.repo);
@@ -132,36 +139,61 @@ async function judgeRead(task: Task, binding: BoundBranch): Promise<string | und
132
139
  if (binding.base !== undefined && (await isBranchItself(binding.repo, binding.base, binding.ref))) {
133
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.`;
134
141
  }
135
- const shas = passingShas(task);
142
+ const claimed = passingShas(task);
136
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
+ };
137
151
  const base = await baseOf(binding.repo, binding.base);
138
152
  const baseWords = binding.base === undefined ? "no base branch (origin/HEAD, main or master)" : `no base ${binding.base}`;
139
153
  if (head) {
140
- if (shas.some((sha) => head.startsWith(sha))) return undefined;
154
+ if (shas.includes(head)) return accept(head);
141
155
  // Merged: the base holds the head and a tested commit of the branch's own work. A hand-made binding has no start.
142
156
  const inBase = !!(binding.start && base && (await contains(binding.repo, head, base.sha)));
143
- if (inBase && (await ownWorkInBase(binding, shas, base!.sha, head))) return undefined;
144
- const seen = shas.length ? `Its passing evidence names other commits: ${listed(shas)}.` : "It has no passing evidence on that commit.";
145
- const merged = !binding.start || !base ? "" : inBase ? ` ${base.name} holds the head, but no tested commit of the branch's own work.` : ` The branch is not merged into ${base.name}.`;
157
+ const mergedWork = inBase && await ownWorkInBase(binding, shas, base!.sha, head);
158
+ if (mergedWork) return accept(mergedWork);
159
+ const onHead = cov.misses.find((m) => head.startsWith(m.sha));
160
+ const left = cov.missing(head);
161
+ const seen = cov.parts && left.length < cov.parts.length
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.`
163
+ : onHead
164
+ ? `Its passing evidence on that commit is no run this session witnessed: ${onHead.why}.`
165
+ : claimed.length ? `Its passing evidence names other commits: ${listed(claimed)}.` : "It has no passing evidence on that commit.";
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}.`;
146
167
  const anchor = task.anchor ? `the anchor (${task.anchor})` : "the anchor";
147
- return `${who} is bound to ${branch}, whose head is ${head}. ${seen}${merged} Run ${anchor} on ${head} and record it as evidence { sha: "${head}", result: "pass" }, in the update that completes the todo or before it.`;
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.`;
148
169
  }
149
170
  // Deleted after a merge: a tested commit of the branch's own work (not the start or before it) is in the base.
150
- 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);
151
173
  let why: string;
152
174
  if (!binding.start) why = "a binding made by hand has no start to tell the branch's own commits from the base's";
153
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`;
154
176
  else if (!base) why = `the repository has ${baseWords} to show it merged`;
155
- else if (shas.length) why = `none of the commits its passing evidence names (${listed(shas)}) is a commit of its own work in ${base.name}`;
177
+ else if (shas.length) why = `none of the commits its witnessed runs tested (${listed(shas)}) is a commit of its own work in ${base.name}`;
178
+ else if (claimed.length) why = `none of its passing evidence (${listed(claimed)}) is a run this session witnessed: ${cov.misses[0]?.why ?? "no witnessed run covers every command of the anchor"}`;
156
179
  else why = `it has no passing evidence to show its work is in ${base.name}`;
157
180
  // A squash or rebase merge leaves the branch's own commits out of the base: restoring the branch at its last head lets the head
158
181
  // rule judge it.
159
- const lastTested = (task.evidence ?? []).filter((e) => e.result === "pass" && typeof e.sha === "string" && SHA.test(e.sha.trim().toLowerCase())).at(-1)?.sha?.trim();
182
+ const lastTested = shas.at(-1);
160
183
  const command = `\`git -C ${shellQuote(binding.repo)} branch ${binding.ref} <last head>\``;
161
- const restore = `restore it at its last head (the merged commit) with ${command}, and record passing evidence on that commit${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}` : ""}`;
162
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}.`;
163
186
  }
164
187
 
188
+ /**
189
+ * Tell the caller when its update set the anchor's command after binding (the one edit anchorChange allows).
190
+ */
191
+ export function anchorChangeNote(prev: Task | undefined, next: Task | undefined): string | undefined {
192
+ if (!prev || !next || !boundBranchOf(prev)) return undefined;
193
+ const gained = !anchorParts(prev.anchor) && anchorParts(next.anchor);
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;
195
+ }
196
+
165
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. */
166
198
  const FROZEN = ["ref", "base", "start"] as const;
167
199
 
@@ -177,6 +209,21 @@ function bindingChange(prev: unknown, next: unknown): string | undefined {
177
209
  return changed.length ? `its binding's ${changed.join(", ")} cannot change` : undefined;
178
210
  }
179
211
 
212
+ /**
213
+ * Why an open bound todo's anchor may not change from `prev` to `next`: its command parts are what a witnessed run must have run, so they
214
+ * stay as they were. An edit that keeps them (other text around the same code spans) passes. An anchor without a command part may gain
215
+ * parts once, so a todo launched with a prose anchor can still name its check; after that they stay. The completing call itself is
216
+ * judged on the anchor before it, so it cannot do that edit.
217
+ */
218
+ function anchorChange(prev: string | undefined, next: string | undefined): string | undefined {
219
+ if (prev === next) return undefined;
220
+ const was = anchorParts(prev);
221
+ if (!was) return undefined;
222
+ const now = anchorParts(next) ?? [];
223
+ const same = was.length === now.length && was.every((part) => now.includes(part));
224
+ return same ? undefined : `its anchor's command ${was.map((p) => `"${p}"`).join(" and ")} cannot change`;
225
+ }
226
+
180
227
  /** Why an open todo's binding may not move from `prev`'s repo to `next`'s: only away from a repository that cannot be read. */
181
228
  async function repoChange(prev: unknown, next: unknown): Promise<string | undefined> {
182
229
  if (!isRecord(prev) || !isRecord(next) || prev.repo === next.repo || typeof prev.repo !== "string") return undefined;
@@ -189,9 +236,16 @@ export type BindingWriter = "tool" | "launch";
189
236
  /**
190
237
  * Why a call may not commit under the head-evidence rule, or `undefined`. A `todo` call may not set a binding's `start`, nor change
191
238
  * the binding of an open todo other than its `repo` (once it cannot be read) and `worktree` (deleting the todo stays allowed); a launch may.
192
- * An `update` that completes a bound todo is judged against its branch.
239
+ * An `update` that completes a bound todo is judged against its branch and this session's witnessed runs, read from `runs` only then.
193
240
  */
194
- export async function headEvidenceRefusal(op: Op, before: TaskState, after: TaskState, writer: BindingWriter = "tool"): Promise<string | undefined> {
241
+ export async function headEvidenceRefusal(
242
+ op: Op,
243
+ before: TaskState,
244
+ after: TaskState,
245
+ writer: BindingWriter = "tool",
246
+ runs: () => readonly Witness[] = () => [],
247
+ report: (note: string) => void = () => {},
248
+ ): Promise<string | undefined> {
195
249
  if (op.kind === "create" && writer === "tool") {
196
250
  for (const id of op.taskIds) {
197
251
  const why = bindingChange(undefined, after.tasks.find((t) => t.id === id)?.metadata?.[BOUND_BRANCH]);
@@ -208,9 +262,12 @@ export async function headEvidenceRefusal(op: Op, before: TaskState, after: Task
208
262
  const was = prev.metadata?.[BOUND_BRANCH], now = next.metadata?.[BOUND_BRANCH];
209
263
  const why = bindingChange(was, now) ?? (await repoChange(was, now));
210
264
  if (why) return `#${next.id} is still open: ${why}. A binding (metadata.boundBranch) stays as it was made until the todo completes; delete the todo if it is wrong.`;
265
+ const anchor = boundBranchOf(prev) ? anchorChange(prev.anchor, next.anchor) : undefined;
266
+ if (anchor) return `#${next.id} is still open and bound to a branch: ${anchor}. A witnessed run must run the anchor's command as it stood; delete the todo if it is wrong.`;
211
267
  }
212
268
  if (op.fromStatus === "completed" || op.toStatus !== "completed") return undefined;
213
269
  const binding = boundBranchOf(next);
214
- const reason = binding ? await judge(next, binding) : undefined;
270
+ // Judged against the anchor as it stood before this call: a completing update cannot bring its own anchor.
271
+ const reason = binding ? await judge({ ...next, anchor: prev.anchor }, binding, runs(), report) : undefined;
215
272
  return reason && sanitizeTerminalText(reason);
216
273
  }
@@ -7,7 +7,8 @@ import { sanitizeTerminalText } from "../tool/sanitize.ts";
7
7
  import type { FinishCall } from "./finish-call.ts";
8
8
  import { commonDirOf, GitReadError, launchBranch } from "./git-branch.ts";
9
9
  import { runningGuard } from "./guards.ts";
10
- import { BOUND_BRANCH, boundBranchOf, launchMayRebind } from "./head-evidence.ts";
10
+ import { ANCHOR_MUST_NAME_A_COMMAND, BOUND_BRANCH, boundBranchOf, launchMayRebind } from "./head-evidence.ts";
11
+ import { anchorParts, witnessesOn } from "./witness.ts";
11
12
 
12
13
  import { bindRun, history, runOfPath } from "./herdr-runs.ts";
13
14
 
@@ -89,9 +90,9 @@ export function registerHerdrOwner(pi: ExtensionAPI, finish: FinishCall) {
89
90
  let rebind = false;
90
91
  try {
91
92
  const same = !!boundBranch && !!current && current.ref === boundBranch.ref && (await commonDirOf(current.repo)) === (await commonDirOf(boundBranch.repo));
92
- rebind = !!boundBranch && !same && (await launchMayRebind(task));
93
+ rebind = !!boundBranch && !same && (await launchMayRebind(task, witnessesOn(ctx)));
93
94
  if (boundBranch && !same && !rebind && current) {
94
- notice = `the todo stays bound to branch ${current.ref} in ${current.repo}, not ${boundBranch.ref}; a launch rebinds it only once that branch is deleted or merged with a tested commit of its own work`;
95
+ notice = `the todo stays bound to branch ${current.ref} in ${current.repo}, not ${boundBranch.ref}; a launch rebinds it only once that branch is deleted, or merged with a commit of its own work whose anchor run was witnessed in this session (the launching one)`;
95
96
  }
96
97
  } catch (error) {
97
98
  if (!(error instanceof GitReadError)) throw error;
@@ -100,6 +101,13 @@ export function registerHerdrOwner(pi: ExtensionAPI, finish: FinishCall) {
100
101
  const params = { action: "update", id: task.id, owner: herdr.name, metadata: { herdr, ...(rebind ? { [BOUND_BRANCH]: boundBranch } : {}) } };
101
102
  const result = await finish(session, ctx.cwd, "update", params, before, applyTaskMutation(before, "update", params), undefined, undefined, undefined, "launch");
102
103
  if (result.details.error) return warn(notice ? `${notice}; ${result.details.error}` : result.details.error);
104
+ // A bound todo completes only on a witnessed run of its anchor's command: say so now, while the anchor can still gain one.
105
+ const after = getState(session).tasks.find((t) => t.id === task.id);
106
+ const binding = boundBranchOf(after);
107
+ if (binding && !anchorParts(after?.anchor)) {
108
+ const unnamed = `the todo is bound to branch ${binding.ref} but its anchor names no command in backticks: ${ANCHOR_MUST_NAME_A_COMMAND}. Set the anchor's command once with update (anchor: "\`npm test\`"); after that it cannot change while the todo is open`;
109
+ notice = notice ? `${notice}; ${unnamed}` : unnamed;
110
+ }
103
111
  if (notice) return warn(notice);
104
112
  });
105
113
  } catch (error) {
@@ -0,0 +1,266 @@
1
+ /**
2
+ * Records witnessed runs (witness.ts). When this session calls `bash` while one of its todos is open and bound to a branch, the ledger
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
+ * 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
+ * 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 anchor matching every check in the call reads no git.
7
+ *
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
+ * 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`
10
+ * names the monitor, and its `monitor:finished` event with status `completed` and exit code 0 records it, once HEAD is seen unmoved.
11
+ */
12
+
13
+ import { homedir } from "node:os";
14
+ import { resolve } from "node:path";
15
+ import type { ExtensionAPI, ToolResultEvent } from "@earendil-works/pi-coding-agent";
16
+ import { getState, listGeneration, sid } from "../state/store.ts";
17
+ import { sanitizeTerminalText } from "../tool/sanitize.ts";
18
+ import { cleanAt, commitOf, commonDirOf, GitReadError, headAt, statusAt } from "./git-branch.ts";
19
+ import { type BoundBranch, boundBranchOf } from "./head-evidence.ts";
20
+ import { anchorParts, checkRun, type CheckRun, matchedParts, MAX_WITNESSED_COMMAND, mentionedParts, parseRun, WITNESS_ENTRY_TYPE, type Witness, type WitnessHead } from "./witness.ts";
21
+
22
+ const record = (x: unknown): x is Record<string, unknown> => typeof x === "object" && x !== null && !Array.isArray(x);
23
+
24
+ /** A run that may be witnessed, as read before it started. */
25
+ interface Capture {
26
+ session: string;
27
+ toolCallId: string;
28
+ command: string;
29
+ /** The checkout the command runs in. */
30
+ dir: string;
31
+ /** Its HEAD before the run. */
32
+ head: string;
33
+ /** The open bound todos' bindings whose branch head is that HEAD. */
34
+ bindings: BoundBranch[];
35
+ /** Set for a `MonitorCreate` call: its run is judged when the monitor finishes. */
36
+ monitor?: true;
37
+ /** The pi-loop-monitor monitor that runs it, once `monitor:started` named it. */
38
+ monitorId?: string;
39
+ }
40
+
41
+ const MONITOR_TOOL = "MonitorCreate";
42
+
43
+ /** Why a run is not witnessed, said on its result. A git read that gave no answer (`once`) is said once per session, not on every run. */
44
+ interface Note {
45
+ note: string;
46
+ once?: true;
47
+ /** Command-position hints are delivered once per anchor part, across tools in this session. */
48
+ mentions?: string[];
49
+ }
50
+
51
+ interface OpenAnchor {
52
+ binding: BoundBranch;
53
+ parts: string[];
54
+ }
55
+
56
+ function openAnchors(session: string): OpenAnchor[] {
57
+ return getState(session).tasks.flatMap((task) => {
58
+ const binding = task.status === "pending" || task.status === "in_progress" ? boundBranchOf(task) : undefined;
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);
69
+ }
70
+ return [...bindings.values()];
71
+ }
72
+
73
+ const commandWord = (words: string[]) => words.find((w) => !/^[A-Za-z_][A-Za-z0-9_]*=/.test(w));
74
+
75
+ /** Common git directories of bound repositories read so far, by `repo` path: a path's repository does not change under it. */
76
+ const commonDirs = new Map<string, string>();
77
+
78
+ /** The common git directory of `repo`, or `undefined` when it cannot be read: such a binding cannot match, and its refusal says why. */
79
+ async function commonDirOrNone(repo: string): Promise<string | undefined> {
80
+ const known = commonDirs.get(repo);
81
+ if (known) return known;
82
+ try {
83
+ const dir = await commonDirOf(repo);
84
+ if (dir) commonDirs.set(repo, dir);
85
+ return dir;
86
+ } catch (error) {
87
+ if (!(error instanceof GitReadError)) throw error;
88
+ return undefined;
89
+ }
90
+ }
91
+
92
+ /**
93
+ * Reads, before a run of `command` in session `session` with cwd `cwd`, whether it may be witnessed: a `Capture`, a reason it may not
94
+ * (`{ note }`, said on the run's result), or `undefined` when the run concerns no bound branch.
95
+ */
96
+ async function capture(session: string, cwd: string, toolCallId: string, command: string): Promise<Capture | Note | undefined> {
97
+ if (command.length > MAX_WITNESSED_COMMAND) 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
+ }
111
+ const dir = run.cd === undefined ? cwd : resolve(cwd, run.cd.replace(/^~(?=$|\/)/, homedir()));
112
+ try {
113
+ const here = await headAt(dir);
114
+ if (!here || (run.pin && run.pin !== here.head)) return undefined;
115
+ // The bindings first, read in parallel; `git status`, the costly read, only for a checkout of a bound branch's head.
116
+ const matched = await Promise.all(
117
+ bindings.map(async (binding) =>
118
+ (await commonDirOrNone(binding.repo)) === here.commonDir && (await commitOf(dir, `refs/heads/${binding.ref}`)) === here.head ? binding : undefined,
119
+ ),
120
+ );
121
+ const mine = matched.filter((b): b is BoundBranch => !!b);
122
+ if (!mine.length) return undefined;
123
+ if (!(await cleanAt(dir))) return { note: `not witnessed: ${dir} has uncommitted changes or untracked files, so the run does not test ${here.head}` };
124
+ return { session, toolCallId, command, dir, head: here.head, bindings: mine };
125
+ } catch (error) {
126
+ if (!(error instanceof GitReadError)) throw error;
127
+ return { note: `not witnessed: ${error.message}`, once: true };
128
+ }
129
+ }
130
+
131
+ /** The heads a captured run witnessed, read again after it ended, or why none: its HEAD moved, a tracked file changed, or git gave no answer. */
132
+ async function confirm(run: Capture): Promise<WitnessHead[] | Note> {
133
+ try {
134
+ const now = await commitOf(run.dir, "HEAD");
135
+ if (now !== run.head) return { note: `not witnessed: HEAD of ${run.dir} moved from ${run.head} to ${now ?? "nothing"} during the run` };
136
+ // The checkout was clean when the run started, so an untracked path now is the run's own output (a coverage report); any other
137
+ // line is a change to what it tested.
138
+ const changed = (await statusAt(run.dir))?.filter((line) => !line.startsWith("?? ")) ?? ["(git status gave no listing)"];
139
+ if (changed.length) return { note: `not witnessed: ${run.dir} changed while it ran (${changed.slice(0, 3).join(", ")}), so the run may not have tested ${run.head}` };
140
+ const still = await Promise.all(run.bindings.map(async (b) => (await commitOf(run.dir, `refs/heads/${b.ref}`)) === run.head));
141
+ return run.bindings.filter((_, k) => still[k]).map((b) => ({ repo: b.repo, ref: b.ref, sha: run.head }));
142
+ } catch (error) {
143
+ if (!(error instanceof GitReadError)) throw error;
144
+ return { note: `not witnessed: ${error.message}`, once: true };
145
+ }
146
+ }
147
+
148
+ export function registerWitnessRecorder(pi: ExtensionAPI) {
149
+ /** Runs read before they started, by session and tool call id; a call that never ends is dropped at the end of the turn. */
150
+ const pending = new Map<string, Map<string, Capture | Note>>();
151
+
152
+ const witness = (run: Capture, heads: WitnessHead[]) => {
153
+ if (!heads.length) return;
154
+ const entry: Witness = {
155
+ v: 1, session: run.session, toolCallId: run.toolCallId, ...(run.monitorId === undefined ? {} : { monitorId: run.monitorId }),
156
+ command: run.command, at: new Date().toISOString(), checkout: run.dir, heads,
157
+ };
158
+ pi.appendEntry(WITNESS_ENTRY_TYPE, entry);
159
+ };
160
+
161
+ /** One-time diagnostics already delivered, by session. */
162
+ const said = new Map<string, Set<string>>();
163
+ const say = (session: string, event: ToolResultEvent, why: Note) => {
164
+ if (!why.once && !why.mentions) return note(event, why.note);
165
+ const seen = said.get(session) ?? new Set<string>();
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);
175
+ return note(event, why.note);
176
+ };
177
+
178
+ /** Monitors this session started on a candidate run, by monitor id, until they finish. */
179
+ const monitors = new Map<string, Capture>();
180
+
181
+ pi.on("tool_call", async (event, ctx) => {
182
+ if ((event.toolName !== "bash" && event.toolName !== MONITOR_TOOL) || typeof event.input.command !== "string") return;
183
+ const session = sid(ctx);
184
+ // A monitor's shell runs in the pi process's directory, not the session's.
185
+ const cwd = event.toolName === MONITOR_TOOL ? process.cwd() : ctx.cwd;
186
+ const read = await capture(session, cwd, event.toolCallId, event.input.command);
187
+ if (!read) return;
188
+ if (event.toolName === MONITOR_TOOL && !("note" in read)) read.monitor = true;
189
+ const calls = pending.get(session) ?? new Map<string, Capture | Note>();
190
+ calls.set(event.toolCallId, read);
191
+ pending.set(session, calls);
192
+ });
193
+ pi.on("agent_end", (_event, ctx) => {
194
+ pending.delete(sid(ctx));
195
+ });
196
+ pi.on("session_shutdown", (_event, ctx) => {
197
+ try {
198
+ const session = sid(ctx);
199
+ pending.delete(session);
200
+ said.delete(session);
201
+ for (const [id, run] of monitors) if (run.session === session) monitors.delete(id);
202
+ } catch { /* a stale context: its session is gone with it */ }
203
+ });
204
+
205
+ // pi-loop-monitor emits `monitor:started` inside the MonitorCreate call that starts it, after that call's tool_call: the one call
206
+ // of this session pending on the same command is the one that started it.
207
+ pi.events.on("monitor:started", (raw) => {
208
+ if (!record(raw) || typeof raw.monitorId !== "string" || typeof raw.command !== "string") return;
209
+ const candidates: Array<{ calls: Map<string, Capture | Note>; toolCallId: string; read: Capture }> = [];
210
+ for (const calls of pending.values()) {
211
+ for (const [toolCallId, read] of calls) {
212
+ if (!("note" in read) && read.monitor && read.command === raw.command) candidates.push({ calls, toolCallId, read });
213
+ }
214
+ }
215
+ // The event names no call: with two calls pending on the same command, either could own the monitor, so neither is witnessed.
216
+ if (candidates.length > 1) {
217
+ const why: Note = { note: `not witnessed: two MonitorCreate calls ran the same command at once (${raw.command}), so the ledger cannot tell their monitors apart`, once: true };
218
+ for (const { calls, toolCallId } of candidates) calls.set(toolCallId, why);
219
+ return;
220
+ }
221
+ const [only] = candidates;
222
+ if (!only) return;
223
+ only.read.monitorId = raw.monitorId;
224
+ monitors.set(raw.monitorId, only.read);
225
+ only.calls.delete(only.toolCallId);
226
+ });
227
+ pi.events.on("monitor:finished", async (raw) => {
228
+ if (!record(raw) || typeof raw.monitorId !== "string") return;
229
+ const run = monitors.get(raw.monitorId);
230
+ monitors.delete(raw.monitorId);
231
+ if (!run || raw.status !== "completed" || raw.exitCode !== 0) return;
232
+ const heads = await confirm(run);
233
+ // A session shut down meanwhile has no list to record on.
234
+ if (!Array.isArray(heads) || listGeneration(run.session) === undefined) return;
235
+ try {
236
+ witness(run, heads);
237
+ } catch { /* a stale extension context: the session was replaced */ }
238
+ });
239
+
240
+ pi.on("tool_result", async (event, ctx) => {
241
+ if (event.toolName !== "bash" && event.toolName !== MONITOR_TOOL) return;
242
+ const session = sid(ctx);
243
+ const calls = pending.get(session);
244
+ const read = calls?.get(event.toolCallId);
245
+ calls?.delete(event.toolCallId);
246
+ if (!calls?.size) pending.delete(session);
247
+ if (event.toolName === MONITOR_TOOL) {
248
+ // A monitor is judged when it finishes; its start only reports why it cannot be witnessed.
249
+ return read && "note" in read ? say(session, event, read) : undefined;
250
+ }
251
+ if (!read || event.isError) return;
252
+ const out = event.structuredContent;
253
+ if (record(out) && out.exit_code !== undefined && out.exit_code !== 0) return;
254
+ const result = "note" in read ? read : await confirm(read);
255
+ if (Array.isArray(result)) return witness(read as Capture, result);
256
+ return say(session, event, result);
257
+ });
258
+ }
259
+
260
+ /** `event`'s result with a line saying why its run is not witnessed. */
261
+ function note(event: ToolResultEvent, why: string) {
262
+ return {
263
+ content: [...event.content, { type: "text" as const, text: `Todo witness: ${sanitizeTerminalText(why)}` }],
264
+ structuredContent: event.structuredContent,
265
+ };
266
+ }
@@ -0,0 +1,331 @@
1
+ /**
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.
4
+ */
5
+
6
+ import { sid } from "../state/store.ts";
7
+ import type { Evidence } from "../tool/types.ts";
8
+ import type { NamespaceValidator } from "./contract.ts";
9
+
10
+ export const WITNESS_ENTRY_TYPE = "todo/witness";
11
+
12
+ /** A bound branch's head, read right after the run finished. */
13
+ export interface WitnessHead {
14
+ repo: string;
15
+ ref: string;
16
+ sha: string;
17
+ }
18
+
19
+ /** A bash call or MonitorCreate monitor this session ran to exit 0 on a clean bound head. One run may cover several checks. */
20
+ export interface Witness {
21
+ v: 1;
22
+ /** The session that ran it; a copy of the entry in another session (a fork) does not count there. */
23
+ session: string;
24
+ toolCallId: string;
25
+ /** The command as the tool ran it. */
26
+ command: string;
27
+ /** ISO 8601 time the run was recorded. */
28
+ at: string;
29
+ /** The checkout the command ran in: the session's cwd, or the directory of its leading `cd`. */
30
+ checkout?: string;
31
+ /** The head the checkout had before and after the run, once per open bound todo's branch whose head it was. */
32
+ heads: WitnessHead[];
33
+ }
34
+
35
+ /** Commands longer than this are not recorded: a check run is never one, and each record stays small. */
36
+ export const MAX_WITNESSED_COMMAND = 8192;
37
+
38
+ /** The key reserved for witnessed runs: they are recorded by the ledger, never written through `todo`. */
39
+ export const WITNESSED = "witnessed";
40
+
41
+ export const refuseWitnessed: NamespaceValidator = (value) =>
42
+ value === undefined ? undefined : `runs are witnessed by the ledger itself from this session's own bash results (${WITNESS_ENTRY_TYPE} entries), never written through todo`;
43
+
44
+ const record = (x: unknown): x is Record<string, unknown> => typeof x === "object" && x !== null && !Array.isArray(x);
45
+ const FULL_SHA = /^[0-9a-f]{40,64}$/;
46
+ const SHA = /^[0-9a-f]{7,64}$/;
47
+
48
+ function isWitness(data: unknown): data is Witness {
49
+ return (
50
+ record(data) && data.v === 1 && typeof data.session === "string" && typeof data.toolCallId === "string" && typeof data.command === "string" && typeof data.at === "string" &&
51
+ (data.checkout === undefined || typeof data.checkout === "string") &&
52
+ Array.isArray(data.heads) && data.heads.every((h) => record(h) && typeof h.repo === "string" && typeof h.ref === "string" && typeof h.sha === "string" && FULL_SHA.test(h.sha))
53
+ );
54
+ }
55
+
56
+ /** This session's witnessed runs on the branch pi is on, oldest first. */
57
+ export function witnessesOn(ctx: { sessionManager: { getSessionId(): string; getBranch(): Iterable<unknown> } }): Witness[] {
58
+ const session = sid(ctx);
59
+ const runs: Witness[] = [];
60
+ for (const entry of ctx.sessionManager.getBranch()) {
61
+ if (!record(entry) || entry.type !== "custom" || entry.customType !== WITNESS_ENTRY_TYPE) continue;
62
+ if (isWitness(entry.data) && entry.data.session === session) runs.push(entry.data);
63
+ }
64
+ return runs;
65
+ }
66
+
67
+ /** `text` with every run of whitespace made one space. */
68
+ export const normalize = (text: string) => text.replace(/\s+/g, " ").trim();
69
+
70
+ /**
71
+ * Whether code span `span` names a command: it is a plain run (parseRun; a leading `cd <dir> &&` is set aside), and after any `NAME=value`
72
+ * assignments its first word is either a path that starts with `./`, `../`, `/` or `~/`, or a lower-case name (letters, digits, `_`, `+`,
73
+ * `-`; no `.` or `/`) followed by at least one argument. A span such as `feat/x`, `package.json`, `metadata.boundBranch`, or one word
74
+ * (`main`, `src`, `true`) names no command.
75
+ */
76
+ function namesCommand(span: string): boolean {
77
+ const run = parseRun(span);
78
+ if (!run) return false;
79
+ const words = run.words.slice(run.words.findIndex((w) => !/^[A-Za-z_][A-Za-z0-9_]*=/.test(w)));
80
+ const first = words[0] ?? "";
81
+ if (/^(\.{1,2}|~)?\/\S/.test(first)) return true;
82
+ return /^[a-z0-9_][a-z0-9_+-]*$/.test(first) && words.length > 1;
83
+ }
84
+
85
+ /**
86
+ * The command parts of an anchor, whitespace normalized: its code spans that name a command (`` `npm test` ``, namesCommand).
87
+ * `undefined` when it has none, as for prose and for no anchor: a todo bound to a branch then cannot complete (head-evidence.ts).
88
+ */
89
+ export function anchorParts(anchor: string | undefined): string[] | undefined {
90
+ const spans = [...(anchor ?? "").matchAll(/`([^`]+)`/g)].map((m) => normalize(m[1])).filter(namesCommand);
91
+ return spans.length ? [...new Set(spans)] : undefined;
92
+ }
93
+
94
+ /** One shell token: an operator, or a word as written (quotes kept). */
95
+ interface Token {
96
+ op?: string;
97
+ word?: string;
98
+ start: number;
99
+ end: number;
100
+ }
101
+
102
+ /** Operators, longest first. */
103
+ const OPS = ["&>>", "&&", "||", ";;", "|&", "&>", ">>", ">&", ">|", "<<", "<&", "<>", "&", "|", ";", "(", ")", "<", ">", "\n"];
104
+ const opAt = (command: string, i: number) => OPS.find((op) => command.startsWith(op, i));
105
+ const blank = (c: string) => c === " " || c === "\t" || c === "\r";
106
+
107
+ /**
108
+ * `command` as shell tokens, or `undefined` when it holds what a plain run never needs: an expansion (`$`, a backtick, also inside
109
+ * double quotes) or an unclosed quote. Hints alone may use the known prefix up to that point.
110
+ */
111
+ function lex(command: string, mode: "complete" | "hintPrefix" = "complete"): Token[] | undefined {
112
+ const tokens: Token[] = [];
113
+ const stop = () => mode === "hintPrefix" ? tokens : undefined;
114
+ let i = 0;
115
+ while (i < command.length) {
116
+ if (blank(command[i])) {
117
+ i++;
118
+ continue;
119
+ }
120
+ const op = opAt(command, i);
121
+ if (op) {
122
+ tokens.push({ op, start: i, end: i + op.length });
123
+ i += op.length;
124
+ continue;
125
+ }
126
+ const start = i;
127
+ while (i < command.length && !blank(command[i]) && !opAt(command, i)) {
128
+ const c = command[i];
129
+ if (c === "$" || c === "`") return stop();
130
+ if (c === "'") {
131
+ const close = command.indexOf("'", i + 1);
132
+ if (close < 0) return stop();
133
+ i = close + 1;
134
+ } else if (c === '"') {
135
+ let j = i + 1;
136
+ for (; j < command.length && command[j] !== '"'; j++) {
137
+ if (command[j] === "$" || command[j] === "`") return stop();
138
+ if (command[j] === "\\") j++;
139
+ }
140
+ if (j >= command.length) return stop();
141
+ i = j + 1;
142
+ } else i += c === "\\" ? 2 : 1;
143
+ }
144
+ tokens.push({ word: command.slice(start, i), start, end: i });
145
+ }
146
+ return tokens;
147
+ }
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
+
170
+ /** Redirections a run may end with: they change where output goes, not how the command exits. */
171
+ const REDIRECTS = new Set([">", ">>", ">&", "&>", "&>>", ">|", "<", "<>"]);
172
+ /** Words that make a command print help or a version instead of running its check. */
173
+ const HELP = new Set(["--help", "-h", "--version"]);
174
+
175
+ const unquote = (word: string) => word.replace(/^(['"])(.*)\1$/s, "$2");
176
+
177
+ /** A run read as one plain command: the directory of one leading `cd <dir> &&`, and the words after it, trailing redirections dropped. */
178
+ export interface PlainRun {
179
+ cd?: string;
180
+ words: string[];
181
+ /** `words` joined by one space. */
182
+ core: string;
183
+ }
184
+
185
+ /**
186
+ * `command` as one plain command, or `undefined` when it is anything else. One leading `cd <dir> &&` and trailing redirections
187
+ * (`2>&1`, `> log`, `>>log`) are set aside; what remains must be words only: no other operator (`;`, `|`, `&&`, `||`, `&`, `(`, a
188
+ * newline), no expansion, no comment, no group or negation, so no function, alias or trap can stand in for the command.
189
+ */
190
+ export function parseRun(command: string): PlainRun | undefined {
191
+ const tokens = lex(command.trim());
192
+ if (!tokens?.length) return undefined;
193
+ let from = 0;
194
+ let cd: string | undefined;
195
+ if (tokens[0].word === "cd" && tokens[1]?.word && tokens[2]?.op === "&&") {
196
+ cd = unquote(tokens[1].word);
197
+ from = 3;
198
+ }
199
+ let to = tokens.length;
200
+ while (to - from >= 3 && tokens[to - 1].word && REDIRECTS.has(tokens[to - 2].op ?? "")) {
201
+ to -= 2;
202
+ const fd = tokens[to - 1];
203
+ if (fd.word && /^\d+$/.test(fd.word) && fd.end === tokens[to].start && to - 1 > from) to -= 1;
204
+ }
205
+ const words = tokens.slice(from, to);
206
+ if (!words.length || words.some((t) => !t.word || t.word.startsWith("#") || t.word === "{" || t.word === "}" || t.word === "!")) return undefined;
207
+ const list = words.map((t) => t.word!);
208
+ return { ...(cd === undefined ? {} : { cd }), words: list, core: list.join(" ") };
209
+ }
210
+
211
+ /** `command` as a plain run (parseRun) that asks for no help or version, else `undefined`. */
212
+ export function plainRun(command: string): PlainRun | undefined {
213
+ const run = parseRun(command);
214
+ return run && !run.words.some((w) => HELP.has(w)) ? run : undefined;
215
+ }
216
+
217
+ /**
218
+ * Whether `command` runs the anchor command `part` alone: as plain runs, its words start with the part's (each side's leading `cd` set
219
+ * aside), and the words after them are extra arguments other than `--help`, `-h` or `--version`.
220
+ */
221
+ export function runsPart(command: string, part: string): boolean {
222
+ const run = plainRun(command);
223
+ return !!run && matchesPart(run, part);
224
+ }
225
+
226
+ function matchesPart(run: PlainRun, part: string): boolean {
227
+ const want = parseRun(part);
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];
269
+ }
270
+
271
+ /** Whether evidence `command` (normalized) names witnessed `run`: its whole command, or its plain command without the leading cd and redirections. */
272
+ const names = (command: string, run: Witness) => normalize(run.command) === command || parseRun(run.command)?.core === command;
273
+
274
+ /**
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.
277
+ */
278
+ export function coverage(evidence: readonly Evidence[], anchor: string | undefined, runs: readonly Witness[], direct?: (head: WitnessHead) => boolean) {
279
+ const parts = anchorParts(anchor);
280
+ const covered = new Map<string, Set<number>>();
281
+ const used = new Map<string, Array<{ command: string; checkout?: string }>>();
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);
297
+ for (const entry of evidence) {
298
+ const sha = (entry.sha ?? "").trim().toLowerCase();
299
+ if (entry.result !== "pass" || !SHA.test(sha)) continue;
300
+ const command = normalize(entry.command);
301
+ const ran = runs.filter((run) => names(command, run));
302
+ if (!ran.length) {
303
+ misses.push({ sha, why: `this session witnessed no run of "${command}"` });
304
+ continue;
305
+ }
306
+ const onSha = ran.flatMap((run) => run.heads.filter((h) => h.sha.startsWith(sha)).map((head) => ({ run, head })));
307
+ if (!onSha.length) {
308
+ const seen = [...new Set(ran.flatMap((r) => r.heads.map((h) => h.sha.slice(0, 12))))];
309
+ misses.push({ sha, why: `this session ran "${command}" on ${seen.join(", ")}, not on ${sha}` });
310
+ continue;
311
+ }
312
+ let hit = false;
313
+ for (const { run, head } of onSha) {
314
+ if (add(run, head)) hit = true;
315
+ }
316
+ if (!hit) {
317
+ const want = parts ? `the anchor's command ${parts.map((p) => `"${p}"`).join(" or ")}` : "a command of the anchor, which names none";
318
+ misses.push({ sha, why: `"${command}" does not match ${want} as a plain check or a declared fail-fast batch` });
319
+ }
320
+ }
321
+ return {
322
+ parts,
323
+ /** Full shas of the commits every command part was witnessed on. */
324
+ tested: parts ? [...covered].filter(([, set]) => set.size === parts.length).map(([sha]) => sha) : [],
325
+ misses,
326
+ /** The witnessed runs that tested `sha`, a full sha: their commands and checkouts. */
327
+ used: (sha: string) => used.get(sha) ?? [],
328
+ /** The command parts no witnessed run covers on `sha`, a full sha. */
329
+ missing: (sha: string) => (parts ?? []).filter((_, k) => !covered.get(sha)?.has(k)),
330
+ };
331
+ }
package/src/todo.ts CHANGED
@@ -21,6 +21,8 @@ import type { TransferWriters } from "./ledger/transfer-writers.ts";
21
21
  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
+ import { witnessesOn } from "./ledger/witness.ts";
25
+ import { anchorChangeNote } from "./ledger/head-evidence.ts";
24
26
  import { formatStatusLabel, t } from "./state/i18n-bridge.ts";
25
27
  import { listOnBranch } from "./state/replay.ts";
26
28
  import { selectTasksByStatus, selectTodoCounts, selectVisibleTasks } from "./state/selectors.ts";
@@ -122,7 +124,12 @@ export function registerTodoTool(pi: ExtensionAPI, finish: FinishCall, writers:
122
124
  } else {
123
125
  result = applyTaskMutation(before, action, input);
124
126
  }
125
- return finish(sessionId, ctx.cwd, action, input, before, result, signal, transfer ? onOriginalBranch : undefined, journal);
127
+ // A completion of a bound todo counts only this session's witnessed runs, read from the branch when it is judged.
128
+ const done = await finish(sessionId, ctx.cwd, action, input, before, result, signal, transfer ? onOriginalBranch : undefined, journal, "tool", () => witnessesOn(ctx));
129
+ if (action !== "update" || ("isError" in done && done.isError)) return done;
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
+ return note ? { ...done, content: [...done.content, { type: "text" as const, text: note }] } : done;
126
133
  });
127
134
  },
128
135