pi-todo-ledger 0.13.0 → 0.14.0

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
+ > 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
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
 
@@ -285,6 +286,7 @@ The figures are an estimate from what pi wrote in the child's transcript, bookke
285
286
  ### Branch binding (`metadata.boundBranch`)
286
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
290
  The ledger owns this namespace:
289
291
 
290
292
  ```json
@@ -310,28 +312,28 @@ The binding is set two ways:
310
312
  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
313
  - 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
314
 
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.
315
+ 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
316
  `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
317
  Deleting the todo, with `delete` or an `update` to `deleted`, stays allowed.
316
318
 
317
319
  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
320
 
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`.
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
322
  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
323
  3. The branch no longer exists (deleted after a merge), and the base holds a tested commit of the branch's own work.
322
324
 
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.
325
+ 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
326
  The `start` must resolve in `repo`, and in rule 2 it must also be an ancestor of the head.
325
327
  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
328
  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:
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
330
 
329
331
  ```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.
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
333
  ```
332
334
 
333
335
  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.
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
337
 
336
338
  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
339
  Only git's own "no such ref" (exit 1 with nothing on stderr) counts as a missing branch.
@@ -339,7 +341,89 @@ There is no force flag.
339
341
  A todo without a binding, an update that does not complete, and a todo already completed are not checked.
340
342
  Each git command may take up to five seconds; the check runs inside the session's call queue.
341
343
 
342
- Evidence stays self-reported (see [Task](#task)): the check compares recorded shas with the branch, and runs nothing.
344
+ The check runs nothing: it compares recorded shas with the branch and with the session's witnessed runs.
345
+
346
+ ### Witnessed runs (`todo/witness`)
347
+
348
+ Since 0.14.0 a passing evidence entry counts for a bound todo only when the session witnessed the run it names.
349
+ The ledger watches two kinds of run while any todo of the session is open (`pending` or `in_progress`) and bound:
350
+
351
+ - a call of pi's `bash` tool, including nested calls a tool makes through `ctx.executeTool`;
352
+ - a `MonitorCreate` call of pi-loop-monitor, for a check longer than a bash call may run.
353
+
354
+ #### Which runs are recorded
355
+
356
+ 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.
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 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.
375
+
376
+ #### Which run forms count
377
+
378
+ A plain run is one command: after one leading `cd <dir> &&` and trailing redirections are set aside, what remains must be words only.
379
+
380
+ These count, under `bash` or `MonitorCreate` alike, for the anchor command `npm test`:
381
+
382
+ - `npm test`, and with extra arguments: `npm test -- parser`;
383
+ - one leading `cd`: `cd /path/to/worktree && npm test`;
384
+ - trailing redirections: `npm test > /tmp/log 2>&1`, `npm test >>log`, `npm test 2>/dev/null`, `npm test < in`.
385
+
386
+ These do not:
387
+
388
+ - 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;
390
+ - 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;
392
+ - a comment, group, negation, subshell, function, alias or trap: `true # npm test`, `{ npm test; }`, `! npm test`, `(npm test)`, `npm() { :; }; npm test`;
393
+ - a help or version request: `npm test --help`, `-h`, `--version`;
394
+ - another command: `pnpm test`, `npm test-not-really`, `echo npm test`.
395
+
396
+ #### Matching evidence to runs
397
+
398
+ When a bound todo completes, it is judged against its anchor as it stood before the completing call.
399
+ 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:
401
+
402
+ - 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`.
405
+
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.
409
+
410
+ #### Anchor command parts
411
+
412
+ 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.
413
+ 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.
414
+ Text outside code spans is never a command: `npm test passes` written without backticks has no part.
415
+ Nothing is looked up on `PATH`, so the same anchor reads the same on every machine.
416
+
417
+ 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.
418
+ 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.
419
+ 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.
420
+
421
+ #### Sessions and persistence
422
+
423
+ 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.
424
+ Only entries on the session's current branch count. They persist with the session: replay and `/reload` read them and judge nothing again.
425
+ 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.
426
+ Todos without a binding ignore all of this; their evidence stays as described in [Task](#task).
343
427
 
344
428
  ## 4. Change guards
345
429
 
package/README.md CHANGED
@@ -57,8 +57,19 @@ A bound todo completes only when it carries a passing evidence entry whose `sha`
57
57
  { "action": "update", "id": 3, "status": "completed", "evidence": [{ "command": "npm test", "sha": "c986d17a7fc4", "result": "pass" }] }
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
+ Since 0.14.0 that entry counts only if the session ran its command itself.
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
+ 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.
67
+ Completing a bound todo lists the witnessed runs that tested it.
68
+ 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
+ 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
+ Otherwise the ledger refuses the completion, names the head, and asks the agent to run the anchor itself on it.
72
+ 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
73
  A branch deleted after a squash or rebase merge is refused with the `git branch` command that restores it at its last head.
63
74
  A repository or branch that cannot be read, or a git command that times out, is refused with the reason.
64
75
  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.0",
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 = {
@@ -44,7 +45,7 @@ export function makeFinishCall(pi: ExtensionAPI, namespaces: NamespaceRegistry,
44
45
  }
45
46
  const refusal =
46
47
  namespaces.check(changedTasks(result.op, input, result.state, before)) ??
47
- (await headEvidenceRefusal(result.op, before, result.state, writer)) ??
48
+ (await headEvidenceRefusal(result.op, before, result.state, writer, runs)) ??
48
49
  (await guards.check(guardChange));
49
50
  if (refusal) return refuse(action, input, before, refusal);
50
51
  if (signal?.aborted) return refuse(action, input, before, ABORTED);
@@ -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
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.
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.
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,7 +82,7 @@ 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
+ * 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
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.
@@ -99,30 +100,36 @@ async function ownWorkInBase(binding: BoundBranch, shas: string[], base: string,
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[]): 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);
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[]): 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,19 +139,27 @@ 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);
143
+ const cov = coverage(task.evidence ?? [], task.anchor, runs);
144
+ const shas = cov.tested;
136
145
  const head = await commitOf(binding.repo, `refs/heads/${binding.ref}`);
137
146
  const base = await baseOf(binding.repo, binding.base);
138
147
  const baseWords = binding.base === undefined ? "no base branch (origin/HEAD, main or master)" : `no base ${binding.base}`;
139
148
  if (head) {
140
- if (shas.some((sha) => head.startsWith(sha))) return undefined;
149
+ if (shas.includes(head)) return undefined;
141
150
  // Merged: the base holds the head and a tested commit of the branch's own work. A hand-made binding has no start.
142
151
  const inBase = !!(binding.start && base && (await contains(binding.repo, head, base.sha)));
143
152
  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}.`;
153
+ const onHead = cov.misses.find((m) => head.startsWith(m.sha));
154
+ const left = cov.missing(head);
155
+ 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.`
157
+ : onHead
158
+ ? `Its passing evidence on that commit is no run this session witnessed: ${onHead.why}.`
159
+ : claimed.length ? `Its passing evidence names other commits: ${listed(claimed)}.` : "It has no passing evidence on that commit.";
160
+ 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
161
  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.`;
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.`;
148
163
  }
149
164
  // Deleted after a merge: a tested commit of the branch's own work (not the start or before it) is in the base.
150
165
  if (base && (await ownWorkInBase(binding, shas, base.sha))) return undefined;
@@ -152,16 +167,37 @@ async function judgeRead(task: Task, binding: BoundBranch): Promise<string | und
152
167
  if (!binding.start) why = "a binding made by hand has no start to tell the branch's own commits from the base's";
153
168
  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
169
  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}`;
170
+ 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}`;
171
+ 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
172
  else why = `it has no passing evidence to show its work is in ${base.name}`;
157
173
  // 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
174
  // 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();
175
+ const lastTested = shas.at(-1);
160
176
  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}` : ""}`;
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}` : ""}`;
162
178
  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
179
  }
164
180
 
181
+ /**
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.
185
+ */
186
+ export function witnessNote(prev: Task | undefined, next: Task | undefined, runs: () => readonly Witness[]): string | undefined {
187
+ if (!prev || !next || !boundBranchOf(prev)) return undefined;
188
+ const notes: string[] = [];
189
+ 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;
199
+ }
200
+
165
201
  /** 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
202
  const FROZEN = ["ref", "base", "start"] as const;
167
203
 
@@ -177,6 +213,21 @@ function bindingChange(prev: unknown, next: unknown): string | undefined {
177
213
  return changed.length ? `its binding's ${changed.join(", ")} cannot change` : undefined;
178
214
  }
179
215
 
216
+ /**
217
+ * 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
218
+ * 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
219
+ * parts once, so a todo launched with a prose anchor can still name its check; after that they stay. The completing call itself is
220
+ * judged on the anchor before it, so it cannot do that edit.
221
+ */
222
+ function anchorChange(prev: string | undefined, next: string | undefined): string | undefined {
223
+ if (prev === next) return undefined;
224
+ const was = anchorParts(prev);
225
+ if (!was) return undefined;
226
+ const now = anchorParts(next) ?? [];
227
+ const same = was.length === now.length && was.every((part) => now.includes(part));
228
+ return same ? undefined : `its anchor's command ${was.map((p) => `"${p}"`).join(" and ")} cannot change`;
229
+ }
230
+
180
231
  /** 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
232
  async function repoChange(prev: unknown, next: unknown): Promise<string | undefined> {
182
233
  if (!isRecord(prev) || !isRecord(next) || prev.repo === next.repo || typeof prev.repo !== "string") return undefined;
@@ -189,9 +240,15 @@ export type BindingWriter = "tool" | "launch";
189
240
  /**
190
241
  * 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
242
  * 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.
243
+ * An `update` that completes a bound todo is judged against its branch and this session's witnessed runs, read from `runs` only then.
193
244
  */
194
- export async function headEvidenceRefusal(op: Op, before: TaskState, after: TaskState, writer: BindingWriter = "tool"): Promise<string | undefined> {
245
+ export async function headEvidenceRefusal(
246
+ op: Op,
247
+ before: TaskState,
248
+ after: TaskState,
249
+ writer: BindingWriter = "tool",
250
+ runs: () => readonly Witness[] = () => [],
251
+ ): Promise<string | undefined> {
195
252
  if (op.kind === "create" && writer === "tool") {
196
253
  for (const id of op.taskIds) {
197
254
  const why = bindingChange(undefined, after.tasks.find((t) => t.id === id)?.metadata?.[BOUND_BRANCH]);
@@ -208,9 +265,12 @@ export async function headEvidenceRefusal(op: Op, before: TaskState, after: Task
208
265
  const was = prev.metadata?.[BOUND_BRANCH], now = next.metadata?.[BOUND_BRANCH];
209
266
  const why = bindingChange(was, now) ?? (await repoChange(was, now));
210
267
  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.`;
268
+ const anchor = boundBranchOf(prev) ? anchorChange(prev.anchor, next.anchor) : undefined;
269
+ 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
270
  }
212
271
  if (op.fromStatus === "completed" || op.toStatus !== "completed") return undefined;
213
272
  const binding = boundBranchOf(next);
214
- const reason = binding ? await judge(next, binding) : undefined;
273
+ // 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;
215
275
  return reason && sanitizeTerminalText(reason);
216
276
  }
@@ -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,235 @@
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 todo, and a command that is no plain run, read 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, MAX_WITNESSED_COMMAND, plainRun, runsPart, 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
+ }
48
+
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) {
53
+ 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);
56
+ }
57
+ return [...bindings.values()];
58
+ }
59
+
60
+ /** Common git directories of bound repositories read so far, by `repo` path: a path's repository does not change under it. */
61
+ const commonDirs = new Map<string, string>();
62
+
63
+ /** The common git directory of `repo`, or `undefined` when it cannot be read: such a binding cannot match, and its refusal says why. */
64
+ async function commonDirOrNone(repo: string): Promise<string | undefined> {
65
+ const known = commonDirs.get(repo);
66
+ if (known) return known;
67
+ try {
68
+ const dir = await commonDirOf(repo);
69
+ if (dir) commonDirs.set(repo, dir);
70
+ return dir;
71
+ } catch (error) {
72
+ if (!(error instanceof GitReadError)) throw error;
73
+ return undefined;
74
+ }
75
+ }
76
+
77
+ /**
78
+ * Reads, before a run of `command` in session `session` with cwd `cwd`, whether it may be witnessed: a `Capture`, a reason it may not
79
+ * (`{ note }`, said on the run's result), or `undefined` when the run concerns no bound branch.
80
+ */
81
+ async function capture(session: string, cwd: string, toolCallId: string, command: string): Promise<Capture | Note | undefined> {
82
+ 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;
87
+ const dir = run.cd === undefined ? cwd : resolve(cwd, run.cd.replace(/^~(?=$|\/)/, homedir()));
88
+ try {
89
+ const here = await headAt(dir);
90
+ if (!here) return undefined;
91
+ // The bindings first, read in parallel; `git status`, the costly read, only for a checkout of a bound branch's head.
92
+ const matched = await Promise.all(
93
+ bindings.map(async (binding) =>
94
+ (await commonDirOrNone(binding.repo)) === here.commonDir && (await commitOf(dir, `refs/heads/${binding.ref}`)) === here.head ? binding : undefined,
95
+ ),
96
+ );
97
+ const mine = matched.filter((b): b is BoundBranch => !!b);
98
+ if (!mine.length) return undefined;
99
+ if (!(await cleanAt(dir))) return { note: `not witnessed: ${dir} has uncommitted changes or untracked files, so the run does not test ${here.head}` };
100
+ return { session, toolCallId, command, dir, head: here.head, bindings: mine };
101
+ } catch (error) {
102
+ if (!(error instanceof GitReadError)) throw error;
103
+ return { note: `not witnessed: ${error.message}`, once: true };
104
+ }
105
+ }
106
+
107
+ /** 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. */
108
+ async function confirm(run: Capture): Promise<WitnessHead[] | Note> {
109
+ try {
110
+ const now = await commitOf(run.dir, "HEAD");
111
+ if (now !== run.head) return { note: `not witnessed: HEAD of ${run.dir} moved from ${run.head} to ${now ?? "nothing"} during the run` };
112
+ // The checkout was clean when the run started, so an untracked path now is the run's own output (a coverage report); any other
113
+ // line is a change to what it tested.
114
+ const changed = (await statusAt(run.dir))?.filter((line) => !line.startsWith("?? ")) ?? ["(git status gave no listing)"];
115
+ 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}` };
116
+ const still = await Promise.all(run.bindings.map(async (b) => (await commitOf(run.dir, `refs/heads/${b.ref}`)) === run.head));
117
+ return run.bindings.filter((_, k) => still[k]).map((b) => ({ repo: b.repo, ref: b.ref, sha: run.head }));
118
+ } catch (error) {
119
+ if (!(error instanceof GitReadError)) throw error;
120
+ return { note: `not witnessed: ${error.message}`, once: true };
121
+ }
122
+ }
123
+
124
+ export function registerWitnessRecorder(pi: ExtensionAPI) {
125
+ /** Runs read before they started, by session and tool call id; a call that never ends is dropped at the end of the turn. */
126
+ const pending = new Map<string, Map<string, Capture | Note>>();
127
+
128
+ const witness = (run: Capture, heads: WitnessHead[]) => {
129
+ if (!heads.length) return;
130
+ const entry: Witness = {
131
+ v: 1, session: run.session, toolCallId: run.toolCallId, ...(run.monitorId === undefined ? {} : { monitorId: run.monitorId }),
132
+ command: run.command, at: new Date().toISOString(), checkout: run.dir, heads,
133
+ };
134
+ pi.appendEntry(WITNESS_ENTRY_TYPE, entry);
135
+ };
136
+
137
+ /** The read failures already said, by session. */
138
+ const said = new Map<string, Set<string>>();
139
+ const say = (session: string, event: ToolResultEvent, why: Note) => {
140
+ const seen = said.get(session) ?? new Set<string>();
141
+ if (why.once && seen.has(why.note)) return undefined;
142
+ seen.add(why.note);
143
+ said.set(session, seen);
144
+ return note(event, why.note);
145
+ };
146
+
147
+ /** Monitors this session started on a candidate run, by monitor id, until they finish. */
148
+ const monitors = new Map<string, Capture>();
149
+
150
+ pi.on("tool_call", async (event, ctx) => {
151
+ if ((event.toolName !== "bash" && event.toolName !== MONITOR_TOOL) || typeof event.input.command !== "string") return;
152
+ const session = sid(ctx);
153
+ // A monitor's shell runs in the pi process's directory, not the session's.
154
+ const cwd = event.toolName === MONITOR_TOOL ? process.cwd() : ctx.cwd;
155
+ const read = await capture(session, cwd, event.toolCallId, event.input.command);
156
+ if (!read) return;
157
+ if (event.toolName === MONITOR_TOOL && !("note" in read)) read.monitor = true;
158
+ const calls = pending.get(session) ?? new Map<string, Capture | Note>();
159
+ calls.set(event.toolCallId, read);
160
+ pending.set(session, calls);
161
+ });
162
+ pi.on("agent_end", (_event, ctx) => {
163
+ pending.delete(sid(ctx));
164
+ });
165
+ pi.on("session_shutdown", (_event, ctx) => {
166
+ try {
167
+ const session = sid(ctx);
168
+ pending.delete(session);
169
+ said.delete(session);
170
+ for (const [id, run] of monitors) if (run.session === session) monitors.delete(id);
171
+ } catch { /* a stale context: its session is gone with it */ }
172
+ });
173
+
174
+ // pi-loop-monitor emits `monitor:started` inside the MonitorCreate call that starts it, after that call's tool_call: the one call
175
+ // of this session pending on the same command is the one that started it.
176
+ pi.events.on("monitor:started", (raw) => {
177
+ if (!record(raw) || typeof raw.monitorId !== "string" || typeof raw.command !== "string") return;
178
+ const candidates: Array<{ calls: Map<string, Capture | Note>; toolCallId: string; read: Capture }> = [];
179
+ for (const calls of pending.values()) {
180
+ for (const [toolCallId, read] of calls) {
181
+ if (!("note" in read) && read.monitor && read.command === raw.command) candidates.push({ calls, toolCallId, read });
182
+ }
183
+ }
184
+ // The event names no call: with two calls pending on the same command, either could own the monitor, so neither is witnessed.
185
+ if (candidates.length > 1) {
186
+ 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 };
187
+ for (const { calls, toolCallId } of candidates) calls.set(toolCallId, why);
188
+ return;
189
+ }
190
+ const [only] = candidates;
191
+ if (!only) return;
192
+ only.read.monitorId = raw.monitorId;
193
+ monitors.set(raw.monitorId, only.read);
194
+ only.calls.delete(only.toolCallId);
195
+ });
196
+ pi.events.on("monitor:finished", async (raw) => {
197
+ if (!record(raw) || typeof raw.monitorId !== "string") return;
198
+ const run = monitors.get(raw.monitorId);
199
+ monitors.delete(raw.monitorId);
200
+ if (!run || raw.status !== "completed" || raw.exitCode !== 0) return;
201
+ const heads = await confirm(run);
202
+ // A session shut down meanwhile has no list to record on.
203
+ if (!Array.isArray(heads) || listGeneration(run.session) === undefined) return;
204
+ try {
205
+ witness(run, heads);
206
+ } catch { /* a stale extension context: the session was replaced */ }
207
+ });
208
+
209
+ pi.on("tool_result", async (event, ctx) => {
210
+ if (event.toolName !== "bash" && event.toolName !== MONITOR_TOOL) return;
211
+ const session = sid(ctx);
212
+ const calls = pending.get(session);
213
+ const read = calls?.get(event.toolCallId);
214
+ calls?.delete(event.toolCallId);
215
+ if (!calls?.size) pending.delete(session);
216
+ if (event.toolName === MONITOR_TOOL) {
217
+ // A monitor is judged when it finishes; its start only reports why it cannot be witnessed.
218
+ return read && "note" in read ? say(session, event, read) : undefined;
219
+ }
220
+ if (!read || event.isError) return;
221
+ const out = event.structuredContent;
222
+ if (record(out) && out.exit_code !== undefined && out.exit_code !== 0) return;
223
+ const result = "note" in read ? read : await confirm(read);
224
+ if (Array.isArray(result)) return witness(read as Capture, result);
225
+ return say(session, event, result);
226
+ });
227
+ }
228
+
229
+ /** `event`'s result with a line saying why its run is not witnessed. */
230
+ function note(event: ToolResultEvent, why: string) {
231
+ return {
232
+ content: [...event.content, { type: "text" as const, text: `Todo witness: ${sanitizeTerminalText(why)}` }],
233
+ structuredContent: event.structuredContent,
234
+ };
235
+ }
@@ -0,0 +1,261 @@
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.
5
+ */
6
+
7
+ import { sid } from "../state/store.ts";
8
+ import type { Evidence } from "../tool/types.ts";
9
+ import type { NamespaceValidator } from "./contract.ts";
10
+
11
+ export const WITNESS_ENTRY_TYPE = "todo/witness";
12
+
13
+ /** A bound branch's head, read right after the run finished. */
14
+ export interface WitnessHead {
15
+ repo: string;
16
+ ref: string;
17
+ sha: string;
18
+ }
19
+
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. */
21
+ export interface Witness {
22
+ v: 1;
23
+ /** The session that ran it; a copy of the entry in another session (a fork) does not count there. */
24
+ session: string;
25
+ toolCallId: string;
26
+ /** The command as the tool ran it. */
27
+ command: string;
28
+ /** ISO 8601 time the run was recorded. */
29
+ at: string;
30
+ /** The checkout the command ran in: the session's cwd, or the directory of its leading `cd`. */
31
+ checkout?: string;
32
+ /** The head the checkout had before and after the run, once per open bound todo's branch whose head it was. */
33
+ heads: WitnessHead[];
34
+ }
35
+
36
+ /** Commands longer than this are not recorded: a check run is never one, and each record stays small. */
37
+ export const MAX_WITNESSED_COMMAND = 8192;
38
+
39
+ /** The key reserved for witnessed runs: they are recorded by the ledger, never written through `todo`. */
40
+ export const WITNESSED = "witnessed";
41
+
42
+ export const refuseWitnessed: NamespaceValidator = (value) =>
43
+ 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`;
44
+
45
+ const record = (x: unknown): x is Record<string, unknown> => typeof x === "object" && x !== null && !Array.isArray(x);
46
+ const FULL_SHA = /^[0-9a-f]{40,64}$/;
47
+ const SHA = /^[0-9a-f]{7,64}$/;
48
+
49
+ function isWitness(data: unknown): data is Witness {
50
+ return (
51
+ record(data) && data.v === 1 && typeof data.session === "string" && typeof data.toolCallId === "string" && typeof data.command === "string" && typeof data.at === "string" &&
52
+ (data.checkout === undefined || typeof data.checkout === "string") &&
53
+ 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))
54
+ );
55
+ }
56
+
57
+ /** This session's witnessed runs on the branch pi is on, oldest first. */
58
+ export function witnessesOn(ctx: { sessionManager: { getSessionId(): string; getBranch(): Iterable<unknown> } }): Witness[] {
59
+ const session = sid(ctx);
60
+ const runs: Witness[] = [];
61
+ for (const entry of ctx.sessionManager.getBranch()) {
62
+ if (!record(entry) || entry.type !== "custom" || entry.customType !== WITNESS_ENTRY_TYPE) continue;
63
+ if (isWitness(entry.data) && entry.data.session === session) runs.push(entry.data);
64
+ }
65
+ return runs;
66
+ }
67
+
68
+ /** `text` with every run of whitespace made one space. */
69
+ export const normalize = (text: string) => text.replace(/\s+/g, " ").trim();
70
+
71
+ /**
72
+ * 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`
73
+ * assignments its first word is either a path that starts with `./`, `../`, `/` or `~/`, or a lower-case name (letters, digits, `_`, `+`,
74
+ * `-`; no `.` or `/`) followed by at least one argument. A span such as `feat/x`, `package.json`, `metadata.boundBranch`, or one word
75
+ * (`main`, `src`, `true`) names no command.
76
+ */
77
+ function namesCommand(span: string): boolean {
78
+ const run = parseRun(span);
79
+ if (!run) return false;
80
+ const words = run.words.slice(run.words.findIndex((w) => !/^[A-Za-z_][A-Za-z0-9_]*=/.test(w)));
81
+ const first = words[0] ?? "";
82
+ if (/^(\.{1,2}|~)?\/\S/.test(first)) return true;
83
+ return /^[a-z0-9_][a-z0-9_+-]*$/.test(first) && words.length > 1;
84
+ }
85
+
86
+ /**
87
+ * The command parts of an anchor, whitespace normalized: its code spans that name a command (`` `npm test` ``, namesCommand).
88
+ * `undefined` when it has none, as for prose and for no anchor: a todo bound to a branch then cannot complete (head-evidence.ts).
89
+ */
90
+ export function anchorParts(anchor: string | undefined): string[] | undefined {
91
+ const spans = [...(anchor ?? "").matchAll(/`([^`]+)`/g)].map((m) => normalize(m[1])).filter(namesCommand);
92
+ return spans.length ? [...new Set(spans)] : undefined;
93
+ }
94
+
95
+ /** One shell token: an operator, or a word as written (quotes kept). */
96
+ interface Token {
97
+ op?: string;
98
+ word?: string;
99
+ start: number;
100
+ end: number;
101
+ }
102
+
103
+ /** Operators, longest first. */
104
+ const OPS = ["&>>", "&&", "||", ";;", "|&", "&>", ">>", ">&", ">|", "<<", "<&", "<>", "&", "|", ";", "(", ")", "<", ">", "\n"];
105
+ const opAt = (command: string, i: number) => OPS.find((op) => command.startsWith(op, i));
106
+ const blank = (c: string) => c === " " || c === "\t" || c === "\r";
107
+
108
+ /**
109
+ * `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.
111
+ */
112
+ function lex(command: string): Token[] | undefined {
113
+ const tokens: Token[] = [];
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 undefined;
130
+ if (c === "'") {
131
+ const close = command.indexOf("'", i + 1);
132
+ if (close < 0) return undefined;
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 undefined;
138
+ if (command[j] === "\\") j++;
139
+ }
140
+ if (j >= command.length) return undefined;
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
+ /** Redirections a run may end with: they change where output goes, not how the command exits. */
150
+ const REDIRECTS = new Set([">", ">>", ">&", "&>", "&>>", ">|", "<", "<>"]);
151
+ /** Words that make a command print help or a version instead of running its check. */
152
+ const HELP = new Set(["--help", "-h", "--version"]);
153
+
154
+ const unquote = (word: string) => word.replace(/^(['"])(.*)\1$/s, "$2");
155
+
156
+ /** A run read as one plain command: the directory of one leading `cd <dir> &&`, and the words after it, trailing redirections dropped. */
157
+ export interface PlainRun {
158
+ cd?: string;
159
+ words: string[];
160
+ /** `words` joined by one space. */
161
+ core: string;
162
+ }
163
+
164
+ /**
165
+ * `command` as one plain command, or `undefined` when it is anything else. One leading `cd <dir> &&` and trailing redirections
166
+ * (`2>&1`, `> log`, `>>log`) are set aside; what remains must be words only: no other operator (`;`, `|`, `&&`, `||`, `&`, `(`, a
167
+ * newline), no expansion, no comment, no group or negation, so no function, alias or trap can stand in for the command.
168
+ */
169
+ export function parseRun(command: string): PlainRun | undefined {
170
+ const tokens = lex(command.trim());
171
+ if (!tokens?.length) return undefined;
172
+ let from = 0;
173
+ let cd: string | undefined;
174
+ if (tokens[0].word === "cd" && tokens[1]?.word && tokens[2]?.op === "&&") {
175
+ cd = unquote(tokens[1].word);
176
+ from = 3;
177
+ }
178
+ let to = tokens.length;
179
+ while (to - from >= 3 && tokens[to - 1].word && REDIRECTS.has(tokens[to - 2].op ?? "")) {
180
+ to -= 2;
181
+ const fd = tokens[to - 1];
182
+ if (fd.word && /^\d+$/.test(fd.word) && fd.end === tokens[to].start && to - 1 > from) to -= 1;
183
+ }
184
+ const words = tokens.slice(from, to);
185
+ if (!words.length || words.some((t) => !t.word || t.word.startsWith("#") || t.word === "{" || t.word === "}" || t.word === "!")) return undefined;
186
+ const list = words.map((t) => t.word!);
187
+ return { ...(cd === undefined ? {} : { cd }), words: list, core: list.join(" ") };
188
+ }
189
+
190
+ /** `command` as a plain run (parseRun) that asks for no help or version, else `undefined`. */
191
+ export function plainRun(command: string): PlainRun | undefined {
192
+ const run = parseRun(command);
193
+ return run && !run.words.some((w) => HELP.has(w)) ? run : undefined;
194
+ }
195
+
196
+ /**
197
+ * Whether `command` runs the anchor command `part` alone: as plain runs, its words start with the part's (each side's leading `cd` set
198
+ * aside), and the words after them are extra arguments other than `--help`, `-h` or `--version`.
199
+ */
200
+ export function runsPart(command: string, part: string): boolean {
201
+ const run = plainRun(command);
202
+ const want = parseRun(part);
203
+ return !!run && !!want && run.words.length >= want.words.length && want.words.every((w, k) => run.words[k] === w);
204
+ }
205
+
206
+ /** Whether evidence `command` (normalized) names witnessed `run`: its whole command, or its plain command without the leading cd and redirections. */
207
+ const names = (command: string, run: Witness) => normalize(run.command) === command || parseRun(run.command)?.core === command;
208
+
209
+ /**
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.
213
+ */
214
+ export function coverage(evidence: readonly Evidence[], anchor: string | undefined, runs: readonly Witness[]) {
215
+ const parts = anchorParts(anchor);
216
+ const covered = new Map<string, Set<number>>();
217
+ const used = new Map<string, Array<{ command: string; checkout?: string }>>();
218
+ const misses: Array<{ sha: string; why: string }> = [];
219
+ for (const entry of evidence) {
220
+ const sha = (entry.sha ?? "").trim().toLowerCase();
221
+ if (entry.result !== "pass" || !SHA.test(sha)) continue;
222
+ const command = normalize(entry.command);
223
+ const ran = runs.filter((run) => names(command, run));
224
+ if (!ran.length) {
225
+ misses.push({ sha, why: `this session witnessed no run of "${command}"` });
226
+ continue;
227
+ }
228
+ const onSha = ran.flatMap((run) => run.heads.filter((h) => h.sha.startsWith(sha)).map((head) => ({ run, head })));
229
+ if (!onSha.length) {
230
+ const seen = [...new Set(ran.flatMap((r) => r.heads.map((h) => h.sha.slice(0, 12))))];
231
+ misses.push({ sha, why: `this session ran "${command}" on ${seen.join(", ")}, not on ${sha}` });
232
+ continue;
233
+ }
234
+ let hit = false;
235
+ 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);
245
+ }
246
+ if (!hit) {
247
+ 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` });
249
+ }
250
+ }
251
+ return {
252
+ parts,
253
+ /** Full shas of the commits every command part was witnessed on. */
254
+ tested: parts ? [...covered].filter(([, set]) => set.size === parts.length).map(([sha]) => sha) : [],
255
+ misses,
256
+ /** The witnessed runs that tested `sha`, a full sha: their commands and checkouts. */
257
+ used: (sha: string) => used.get(sha) ?? [],
258
+ /** The command parts no witnessed run covers on `sha`, a full sha. */
259
+ missing: (sha: string) => (parts ?? []).filter((_, k) => !covered.get(sha)?.has(k)),
260
+ };
261
+ }
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 { witnessNote } 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
+ // 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));
132
+ return note ? { ...done, content: [...done.content, { type: "text" as const, text: note }] } : done;
126
133
  });
127
134
  },
128
135