pi-todo-ledger 0.12.1 → 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
 
@@ -282,6 +283,148 @@ A `todo` call of the session that is running or queued holds the list while its
282
283
  Namespace validators judge the write as any `update`; change guards (see [Change guards](#4-change-guards)) are not asked: they are awaited, and the write records a run that already happened (the boss's decision, 2026-11-28: 「不經過關卡」). A guard such as Straw Boss's train guard therefore never sees or refuses a spend write, which changes only `metadata.herdr`. A validator's refusal leaves the list unchanged and appends `Todo spend: <reason>` to the message.
283
284
  The figures are an estimate from what pi wrote in the child's transcript, bookkeeping rather than a bill. `get` shows them on a `spend:` line.
284
285
 
286
+ ### Branch binding (`metadata.boundBranch`)
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)).
290
+ The ledger owns this namespace:
291
+
292
+ ```json
293
+ { "repo": "/Users/me/projects/app/.git", "ref": "feat/parser", "worktree": "/Users/me/.herdr/worktrees/app/feat-parser", "start": "5f0c2a9e41b7d3c8a6e2f1b0c9d8e7f6a5b4c3d2" }
294
+ ```
295
+
296
+ | Key | Type | Meaning |
297
+ | --- | --- | --- |
298
+ | `repo` | absolute path | Where git reads the branch: the repository's git directory, or any checkout of it. |
299
+ | `ref` | branch name | The branch, as `git branch` names it. |
300
+ | `base` | branch name, optional | The branch it merges into. Without one, the base is `origin/HEAD` as last fetched, else `main`, else `master`. It may not be the branch itself or one of its remote-tracking refs. |
301
+ | `worktree` | absolute path, optional | The worktree the child was launched in; for readers, the check does not use it. |
302
+ | `start` | full commit sha, optional | The branch's head when a launch bound it. Commits after it are the branch's own work. Only a launch records it. |
303
+
304
+ The binding is set two ways:
305
+
306
+ - A `subagent` launch with an `item` (see [`metadata.herdr`](#optional-herdr-launch-identity-metadataherdr)) whose `cwd`, or acknowledged `details.worktree.path`, lies in a linked git worktree on a named branch binds the todo to that branch.
307
+ It sets `repo` to the repository's shared git directory, so the branch stays readable after the worktree is removed, and `start` to the branch's head.
308
+ A launch without a `cwd`, into the launching session's own checkout, into a main checkout, or onto a detached head binds nothing and keeps the binding the todo has.
309
+ A later launch onto the branch the todo is already bound to keeps the binding and its `start`.
310
+ A later launch onto another branch replaces it, with that branch and a new `start`, only when the todo has no binding, its branch no longer exists, or the branch is merged with a tested commit of its own work (rule 2 below).
311
+ Otherwise the binding stays and the launch's result names the branch it stays bound to. A resume keeps it.
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.
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.
314
+
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)).
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.
317
+ Deleting the todo, with `delete` or an `update` to `deleted`, stays allowed.
318
+
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:
320
+
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`.
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.
323
+ 3. The branch no longer exists (deleted after a merge), and the base holds a tested commit of the branch's own work.
324
+
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.
326
+ The `start` must resolve in `repo`, and in rule 2 it must also be an ancestor of the head.
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.
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.
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:
330
+
331
+ ```text
332
+ Error: #3 "Port the parser" is bound to branch feat/parser in /Users/me/projects/app/.git, whose head is c986d17a7fc4eac254bba796e7ddf6d2025b50b7. Its passing evidence names other commits: e780e97ac. The branch is not merged into main. Run the anchor (`npm test -- parser`) yourself in this session on the head c986d17a7fc4eac254bba796e7ddf6d2025b50b7; relayed results do not count. Then record the command you ran as evidence { command, sha: "c986d17a7fc4eac254bba796e7ddf6d2025b50b7", result: "pass" }, in the update that completes the todo or before it. Run it alone on a clean checkout of the branch; a check longer than a bash call may take goes under MonitorCreate in this session, whose exit-0 finish counts the same.
333
+ ```
334
+
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.
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.
337
+
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.
339
+ Only git's own "no such ref" (exit 1 with nothing on stderr) counts as a missing branch.
340
+ There is no force flag.
341
+ A todo without a binding, an update that does not complete, and a todo already completed are not checked.
342
+ Each git command may take up to five seconds; the check runs inside the session's call queue.
343
+
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).
427
+
285
428
  ## 4. Change guards
286
429
 
287
430
  A namespace validator judges one task's value.
@@ -322,7 +465,7 @@ A valid `update` that changes nothing, such as setting `in_progress` on a task a
322
465
  | `cwd` | That session's working directory. |
323
466
  | `noop` | `true` on an `update` that changes nothing, where `before` equals `after`; absent otherwise. |
324
467
 
325
- Guards run after the namespace validators and before anything commits, one at a time in registration order, and the extension awaits each.
468
+ Guards run after the namespace validators and the [head-evidence check](#branch-binding-metadataboundbranch), and before anything commits, one at a time in registration order, and the extension awaits each.
326
469
  `check` returns, or resolves to, a non-empty string to refuse, or `undefined` to accept.
327
470
  The first refusal refuses the whole call as in [Namespaces](#3-namespaces): nothing commits, no entry is written, no event fires, and the tool returns an error result (`isError: true`):
328
471
 
package/README.md CHANGED
@@ -50,6 +50,33 @@ When a bound run ends, the ledger adds its tokens, cost, wall time, and models t
50
50
  Use a name with `/boss send` only if it matches the name Straw Boss shows; a launch named `API worker` may appear there as `api-worker`.
51
51
  You can still set `owner` by hand.
52
52
 
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:
55
+
56
+ ```text
57
+ { "action": "update", "id": 3, "status": "completed", "evidence": [{ "command": "npm test", "sha": "c986d17a7fc4", "result": "pass" }] }
58
+ ```
59
+
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.
73
+ A branch deleted after a squash or rebase merge is refused with the `git branch` command that restores it at its last head.
74
+ A repository or branch that cannot be read, or a git command that times out, is refused with the reason.
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.
76
+ There is no force flag; deleting the todo stays allowed.
77
+ To bind a todo by hand, set `metadata.boundBranch` to `{ "repo": "<path in the repository>", "ref": "<branch>" }`; such a binding completes only on evidence for the head.
78
+ Todos without a binding complete as before.
79
+
53
80
  The panel lists each task's live bound runs under it.
54
81
  A run that belongs to no task, such as a scout sent out on the side, is listed under an `Other workers` group (`其他 worker` in zh-TW) after the tasks, in the same row format; the panel shows that group even when the list is empty.
55
82
  The panel claims every run row it paints, so the host's Subagents box shows only the runs the panel does not.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-todo-ledger",
3
- "version": "0.12.1",
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
@@ -39,9 +39,12 @@ import { FLOW_TOOL_NAME, registerFlowTool } from "./flow/tool.ts";
39
39
  import { makeCommitNow, makeFinishCall } from "./ledger/finish-call.ts";
40
40
  import { TransferWriters } from "./ledger/transfer-writers.ts";
41
41
  import { GuardRegistry } from "./ledger/guards.ts";
42
+ import { BOUND_BRANCH, validateBoundBranch } from "./ledger/head-evidence.ts";
42
43
  import { registerHerdrOwner } from "./ledger/herdr-owner.ts";
43
44
  import { registerHerdrSpend } from "./ledger/herdr-spend.ts";
44
45
  import { NamespaceRegistry } from "./ledger/namespaces.ts";
46
+ import { refuseWitnessed, WITNESSED } from "./ledger/witness.ts";
47
+ import { registerWitnessRecorder } from "./ledger/witness-recorder.ts";
45
48
  import { I18N_NAMESPACE } from "./state/i18n-bridge.ts";
46
49
  import { replayFromBranch } from "./state/replay.ts";
47
50
  import {
@@ -204,6 +207,8 @@ export default function (
204
207
  // `todo:ready` asks the ones that loaded before this extension to register again.
205
208
  const namespaces = new NamespaceRegistry();
206
209
  namespaces.own(FLOW_NAMESPACE, validateFlowMetadata);
210
+ namespaces.own(BOUND_BRANCH, validateBoundBranch);
211
+ namespaces.own(WITNESSED, refuseWitnessed);
207
212
  const guards = new GuardRegistry(options.guardTimeoutMs ?? GUARD_TIMEOUT_MS);
208
213
  pi.events.on(NAMESPACE_EVENT, (payload) => {
209
214
  const ignored = namespaces.register(payload);
@@ -220,6 +225,7 @@ export default function (
220
225
  registerFlowTool(pi, finish);
221
226
  registerHerdrOwner(pi, finish);
222
227
  registerHerdrSpend(pi, makeCommitNow(pi, namespaces));
228
+ registerWitnessRecorder(pi);
223
229
  registerTodosCommand(pi);
224
230
  pi.events.emit(READY_EVENT, { v: CONTRACT_VERSION });
225
231
 
@@ -7,6 +7,8 @@ import type { TaskAction, TaskMutationParams } from "../tool/types.ts";
7
7
  import { CHANGED_EVENT, type GuardOp, SNAPSHOT_ENTRY_TYPE, toChangedEvent, toSnapshot } from "./contract.ts";
8
8
  import type { TransferJournal } from "./transfer-journal.ts";
9
9
  import type { GuardRegistry } from "./guards.ts";
10
+ import { type BindingWriter, headEvidenceRefusal } from "./head-evidence.ts";
11
+ import type { Witness } from "./witness.ts";
10
12
  import { changedTasks, type NamespaceRegistry } from "./namespaces.ts";
11
13
 
12
14
  // If even the physical snapshot cannot be read back, no writer using this process's live slot may replace it.
@@ -21,7 +23,7 @@ export function refuse(action: TaskAction, input: TaskMutationParams, state: Tas
21
23
 
22
24
  /** Shared commit boundary for tool calls and acknowledged Herdr launches. Caller holds the session lock. */
23
25
  export function makeFinishCall(pi: ExtensionAPI, namespaces: NamespaceRegistry, guards: GuardRegistry) {
24
- return async (sessionId: string, cwd: string, action: TaskAction, input: TaskMutationParams, before: TaskState, result: ApplyResult, signal?: AbortSignal, onOriginalBranch?: () => boolean, journal?: TransferJournal) => {
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[]) => {
25
27
  const blocked = blockedWrite(sessionId);
26
28
  if (blocked && action !== "list" && action !== "get") return refuse(action, input, before, blocked);
27
29
  const guardChange = {
@@ -41,7 +43,10 @@ export function makeFinishCall(pi: ExtensionAPI, namespaces: NamespaceRegistry,
41
43
  commitState(sessionId, result.state);
42
44
  return buildToolResult(action, input, result.state, result.op);
43
45
  }
44
- const refusal = namespaces.check(changedTasks(result.op, input, result.state, before)) ?? (await guards.check(guardChange));
46
+ const refusal =
47
+ namespaces.check(changedTasks(result.op, input, result.state, before)) ??
48
+ (await headEvidenceRefusal(result.op, before, result.state, writer, runs)) ??
49
+ (await guards.check(guardChange));
45
50
  if (refusal) return refuse(action, input, before, refusal);
46
51
  if (signal?.aborted) return refuse(action, input, before, ABORTED);
47
52
  if (onOriginalBranch && !onOriginalBranch()) return branchRefusal();
@@ -0,0 +1,154 @@
1
+ /**
2
+ * The git reads behind a todo's branch binding (`metadata.boundBranch`, head-evidence.ts): which branch a launch's worktree is on,
3
+ * a branch's head, and whether a commit is in a base. Only the ledger's tool layer calls these; `src/state/` stays git-free.
4
+ */
5
+
6
+ import { execFile } from "node:child_process";
7
+ import { existsSync, realpathSync } from "node:fs";
8
+
9
+ /** How long one git command may take: a completion waits on a few of them inside the session's call queue. */
10
+ export const GIT_TIMEOUT_MS = 5000;
11
+
12
+ /**
13
+ * How a git command ended: `ok`; `exit`, git's own answer through its exit code (1 with nothing on stderr is "no such ref" or "not an
14
+ * ancestor"); or `died`, when git gave no answer: it timed out, was killed by a signal, or could not start.
15
+ */
16
+ type GitRun = { kind: "ok"; stdout: string } | { kind: "exit"; code: number; stderr: string } | { kind: "died"; why: string };
17
+
18
+ /** A git read that gave no answer; the check refuses rather than guess what git would have said. */
19
+ export class GitReadError extends Error {}
20
+
21
+ function git(cwd: string, args: string[]): Promise<GitRun> {
22
+ return new Promise((resolve) => {
23
+ execFile(
24
+ "git",
25
+ ["-C", cwd, ...args],
26
+ { encoding: "utf8", timeout: GIT_TIMEOUT_MS, env: { ...process.env, GIT_OPTIONAL_LOCKS: "0", GIT_TERMINAL_PROMPT: "0" } },
27
+ (error, stdout, stderr) => {
28
+ if (!error) return resolve({ kind: "ok", stdout: String(stdout).trim() });
29
+ const e = error as { code?: unknown; killed?: boolean; signal?: string | null };
30
+ if (e.killed && e.signal) return resolve({ kind: "died", why: `timeout after ${GIT_TIMEOUT_MS} ms` });
31
+ if (e.signal) return resolve({ kind: "died", why: `git was killed by ${e.signal}` });
32
+ if (typeof e.code !== "number") return resolve({ kind: "died", why: `git could not run: ${typeof e.code === "string" ? e.code : error.message}` });
33
+ resolve({ kind: "exit", code: e.code, stderr: String(stderr).trim() });
34
+ },
35
+ );
36
+ });
37
+ }
38
+
39
+ /** `run`, unless git gave no answer: then a `GitReadError` naming the command. */
40
+ function answered(run: GitRun, what: string): Exclude<GitRun, { kind: "died" }> {
41
+ if (run.kind === "died") throw new GitReadError(`could not read ${what} (${run.why})`);
42
+ return run;
43
+ }
44
+
45
+ const real = (path: string) => {
46
+ try {
47
+ return realpathSync(path);
48
+ } catch {
49
+ return path;
50
+ }
51
+ };
52
+
53
+ /**
54
+ * The branch a child launched into `dir` works on: `{ repo, ref, worktree }` when `dir` is in a linked worktree (not a main checkout)
55
+ * on a named branch, and not the launching session's own checkout (`parentCwd`). `repo` is the repository's shared git directory, so
56
+ * the branch stays readable after the worktree is removed; `start` is the branch's head at launch.
57
+ */
58
+ export async function launchBranch(dir: string, parentCwd: string): Promise<{ repo: string; ref: string; worktree: string; start: string } | undefined> {
59
+ if (!existsSync(dir)) return undefined;
60
+ const what = `the branch of ${dir}`;
61
+ const paths = answered(await git(dir, ["rev-parse", "--path-format=absolute", "--show-toplevel", "--git-dir", "--git-common-dir"]), what);
62
+ if (paths.kind !== "ok") return undefined;
63
+ const [worktree, gitDir, commonDir] = paths.stdout.split("\n");
64
+ if (!worktree || !gitDir || !commonDir || real(gitDir) === real(commonDir)) return undefined;
65
+ const parent = existsSync(parentCwd) ? answered(await git(parentCwd, ["rev-parse", "--path-format=absolute", "--show-toplevel"]), parentCwd) : undefined;
66
+ if (parent?.kind === "ok" && real(parent.stdout) === real(worktree)) return undefined;
67
+ const ref = answered(await git(dir, ["symbolic-ref", "--short", "-q", "HEAD"]), what);
68
+ if (ref.kind !== "ok" || !ref.stdout) return undefined;
69
+ const start = await commitOf(dir, "HEAD");
70
+ if (!start) return undefined;
71
+ return { repo: commonDir, ref: ref.stdout, worktree, start };
72
+ }
73
+
74
+ /** Why `repo` cannot be read as a git repository, or `undefined` when it can. */
75
+ export async function unreadableRepo(repo: string): Promise<string | undefined> {
76
+ if (!existsSync(repo)) return `${repo} does not exist`;
77
+ const run = await git(repo, ["rev-parse", "--git-dir"]);
78
+ if (run.kind === "died") return `could not read ${repo} (${run.why})`;
79
+ return run.kind === "ok" ? undefined : `${repo} is not a readable git repository (${run.stderr.split("\n")[0] || `git exited ${run.code}`})`;
80
+ }
81
+
82
+ /**
83
+ * The full sha of the commit `rev` names in `repo`, or `undefined` when git says it names none (exit 1, nothing on stderr). Any other
84
+ * failure throws a `GitReadError`. `rev` never starts with `-` (validated binding).
85
+ */
86
+ export async function commitOf(repo: string, rev: string): Promise<string | undefined> {
87
+ const run = answered(await git(repo, ["rev-parse", "--verify", "--quiet", `${rev}^{commit}`]), `${rev} in ${repo}`);
88
+ if (run.kind === "ok" && /^[0-9a-f]{40,64}$/.test(run.stdout)) return run.stdout;
89
+ if (run.kind === "exit" && run.code === 1 && !run.stderr) return undefined;
90
+ throw new GitReadError(`could not read ${rev} in ${repo} (${run.kind === "exit" ? run.stderr.split("\n")[0] || `git exited ${run.code}` : "no commit sha"})`);
91
+ }
92
+
93
+ /** Where a branch with no `base` of its own is merged: the remote's default branch as last fetched, else `main`, else `master`. */
94
+ const DEFAULT_BASES = [
95
+ { ref: "refs/remotes/origin/HEAD", name: "origin/HEAD" },
96
+ { ref: "refs/heads/main", name: "main" },
97
+ { ref: "refs/heads/master", name: "master" },
98
+ ];
99
+
100
+ /** The base a branch is judged merged into: `base` when given, else the first default that exists; `undefined` when none resolves. */
101
+ export async function baseOf(repo: string, base: string | undefined): Promise<{ name: string; sha: string } | undefined> {
102
+ for (const candidate of base === undefined ? DEFAULT_BASES : [{ ref: base, name: base }]) {
103
+ const sha = await commitOf(repo, candidate.ref);
104
+ if (sha) return { name: candidate.name, sha };
105
+ }
106
+ return undefined;
107
+ }
108
+
109
+ /** Whether `base` names branch `ref` itself or one of its remote-tracking refs in `repo`. */
110
+ export async function isBranchItself(repo: string, base: string, ref: string): Promise<boolean> {
111
+ const run = answered(await git(repo, ["rev-parse", "--symbolic-full-name", base]), `base ${base} in ${repo}`);
112
+ const full = run.kind === "ok" ? run.stdout : "";
113
+ return full === `refs/heads/${ref}` || (full.startsWith("refs/remotes/") && full.slice("refs/remotes/".length).split("/").slice(1).join("/") === ref);
114
+ }
115
+
116
+ /** The repository's shared git directory, from any path in it; `undefined` when git finds none there. */
117
+ export async function commonDirOf(path: string): Promise<string | undefined> {
118
+ if (!existsSync(path)) return undefined;
119
+ const run = answered(await git(path, ["rev-parse", "--path-format=absolute", "--git-common-dir"]), path);
120
+ return run.kind === "ok" && run.stdout ? real(run.stdout) : undefined;
121
+ }
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
+
144
+ /**
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
146
+ * not have, and a git that dies, throw a `GitReadError`: an unknown commit is never "not an ancestor".
147
+ */
148
+ export async function contains(repo: string, sha: string, base: string): Promise<boolean> {
149
+ const what = `whether ${base} holds ${sha} in ${repo}`;
150
+ const run = answered(await git(repo, ["merge-base", "--is-ancestor", sha, base]), what);
151
+ if (run.kind === "ok") return true;
152
+ if (run.code === 1) return false;
153
+ throw new GitReadError(`could not read ${what} (${run.stderr.split("\n")[0] || `git exited ${run.code}`})`);
154
+ }