pi-todo-ledger 0.12.1 → 0.13.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
@@ -282,6 +282,65 @@ A `todo` call of the session that is running or queued holds the list while its
282
282
  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
283
  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
284
 
285
+ ### Branch binding (`metadata.boundBranch`)
286
+
287
+ Since 0.13.0 a todo can be bound to a git branch, and a bound todo completes only on passing evidence for that branch's current head.
288
+ The ledger owns this namespace:
289
+
290
+ ```json
291
+ { "repo": "/Users/me/projects/app/.git", "ref": "feat/parser", "worktree": "/Users/me/.herdr/worktrees/app/feat-parser", "start": "5f0c2a9e41b7d3c8a6e2f1b0c9d8e7f6a5b4c3d2" }
292
+ ```
293
+
294
+ | Key | Type | Meaning |
295
+ | --- | --- | --- |
296
+ | `repo` | absolute path | Where git reads the branch: the repository's git directory, or any checkout of it. |
297
+ | `ref` | branch name | The branch, as `git branch` names it. |
298
+ | `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. |
299
+ | `worktree` | absolute path, optional | The worktree the child was launched in; for readers, the check does not use it. |
300
+ | `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. |
301
+
302
+ The binding is set two ways:
303
+
304
+ - 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.
305
+ 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.
306
+ 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.
307
+ A later launch onto the branch the todo is already bound to keeps the binding and its `start`.
308
+ 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).
309
+ Otherwise the binding stays and the launch's result names the branch it stays bound to. A resume keeps it.
310
+ 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
+ - An agent may set it through `metadata` on `create` or `update`, for example when it created the worktree itself. A binding made by hand has no `start`: an agent cannot set one.
312
+
313
+ While the todo is open, a `todo` call cannot remove the binding or change its `ref`, `base` or `start`; only a launch can rebind.
314
+ `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
+ Deleting the todo, with `delete` or an `update` to `deleted`, stays allowed.
316
+
317
+ An `update` that moves a bound todo to `completed` reads the branch, after the namespace validators and before the change guards, and commits only if one of these holds:
318
+
319
+ 1. The branch exists, and a passing evidence entry (`result: "pass"`) names its head: the entry's `sha`, seven to 64 hex digits in any case, is a prefix of the head's full sha. The entry may be recorded by an earlier call or in the completing call's own `evidence`.
320
+ 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
+ 3. The branch no longer exists (deleted after a merge), and the base holds a tested commit of the branch's own work.
322
+
323
+ A tested commit of the branch's own work is a commit that a passing evidence entry names, that the repository knows, and that descends from the binding's `start` without being it.
324
+ The `start` must resolve in `repo`, and in rule 2 it must also be an ancestor of the head.
325
+ 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
+ Evidence shas the repository does not know are skipped; when `git merge-base --is-ancestor` gives any answer other than yes or no, such as 128 for an unknown commit, the call is refused as a read error.
327
+ Otherwise the call is refused and nothing changes. The refusal names the todo, the branch, its head sha and the evidence shas seen, and says to run the anchor on the head and record it:
328
+
329
+ ```text
330
+ Error: #3 "Port the parser" is bound to branch feat/parser in /Users/me/projects/app/.git, whose head is c986d17a7fc4eac254bba796e7ddf6d2025b50b7. Its passing evidence names other commits: e780e97ac. The branch is not merged into main. Run the anchor (npm test -- parser) on c986d17a7fc4eac254bba796e7ddf6d2025b50b7 and record it as evidence { sha: "c986d17a7fc4eac254bba796e7ddf6d2025b50b7", result: "pass" }, in the update that completes the todo or before it.
331
+ ```
332
+
333
+ A squash or rebase merge leaves the branch's own commits out of the base, so a branch merged that way and then deleted meets none of the rules.
334
+ Its refusal tells the agent to restore the branch at its last head (the merged commit), with `git -C '<repo>' branch <ref> <last head>`, and to record passing evidence on that commit if it is not the last tested one; after that the first rule completes the todo.
335
+
336
+ 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
+ Only git's own "no such ref" (exit 1 with nothing on stderr) counts as a missing branch.
338
+ There is no force flag.
339
+ A todo without a binding, an update that does not complete, and a todo already completed are not checked.
340
+ Each git command may take up to five seconds; the check runs inside the session's call queue.
341
+
342
+ Evidence stays self-reported (see [Task](#task)): the check compares recorded shas with the branch, and runs nothing.
343
+
285
344
  ## 4. Change guards
286
345
 
287
346
  A namespace validator judges one task's value.
@@ -322,7 +381,7 @@ A valid `update` that changes nothing, such as setting `in_progress` on a task a
322
381
  | `cwd` | That session's working directory. |
323
382
  | `noop` | `true` on an `update` that changes nothing, where `before` equals `after`; absent otherwise. |
324
383
 
325
- Guards run after the namespace validators and before anything commits, one at a time in registration order, and the extension awaits each.
384
+ 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
385
  `check` returns, or resolves to, a non-empty string to refuse, or `undefined` to accept.
327
386
  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
387
 
package/README.md CHANGED
@@ -50,6 +50,22 @@ 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
+ 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.
62
+ A branch deleted after a squash or rebase merge is refused with the `git branch` command that restores it at its last head.
63
+ A repository or branch that cannot be read, or a git command that times out, is refused with the reason.
64
+ 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.
65
+ There is no force flag; deleting the todo stays allowed.
66
+ 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.
67
+ Todos without a binding complete as before.
68
+
53
69
  The panel lists each task's live bound runs under it.
54
70
  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
71
  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.13.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,6 +39,7 @@ 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";
@@ -204,6 +205,7 @@ export default function (
204
205
  // `todo:ready` asks the ones that loaded before this extension to register again.
205
206
  const namespaces = new NamespaceRegistry();
206
207
  namespaces.own(FLOW_NAMESPACE, validateFlowMetadata);
208
+ namespaces.own(BOUND_BRANCH, validateBoundBranch);
207
209
  const guards = new GuardRegistry(options.guardTimeoutMs ?? GUARD_TIMEOUT_MS);
208
210
  pi.events.on(NAMESPACE_EVENT, (payload) => {
209
211
  const ignored = namespaces.register(payload);
@@ -7,6 +7,7 @@ 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";
10
11
  import { changedTasks, type NamespaceRegistry } from "./namespaces.ts";
11
12
 
12
13
  // If even the physical snapshot cannot be read back, no writer using this process's live slot may replace it.
@@ -21,7 +22,7 @@ export function refuse(action: TaskAction, input: TaskMutationParams, state: Tas
21
22
 
22
23
  /** Shared commit boundary for tool calls and acknowledged Herdr launches. Caller holds the session lock. */
23
24
  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) => {
25
+ return async (sessionId: string, cwd: string, action: TaskAction, input: TaskMutationParams, before: TaskState, result: ApplyResult, signal?: AbortSignal, onOriginalBranch?: () => boolean, journal?: TransferJournal, writer: BindingWriter = "tool") => {
25
26
  const blocked = blockedWrite(sessionId);
26
27
  if (blocked && action !== "list" && action !== "get") return refuse(action, input, before, blocked);
27
28
  const guardChange = {
@@ -41,7 +42,10 @@ export function makeFinishCall(pi: ExtensionAPI, namespaces: NamespaceRegistry,
41
42
  commitState(sessionId, result.state);
42
43
  return buildToolResult(action, input, result.state, result.op);
43
44
  }
44
- const refusal = namespaces.check(changedTasks(result.op, input, result.state, before)) ?? (await guards.check(guardChange));
45
+ const refusal =
46
+ namespaces.check(changedTasks(result.op, input, result.state, before)) ??
47
+ (await headEvidenceRefusal(result.op, before, result.state, writer)) ??
48
+ (await guards.check(guardChange));
45
49
  if (refusal) return refuse(action, input, before, refusal);
46
50
  if (signal?.aborted) return refuse(action, input, before, ABORTED);
47
51
  if (onOriginalBranch && !onOriginalBranch()) return branchRefusal();
@@ -0,0 +1,133 @@
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
+ /**
124
+ * 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
+ * not have, and a git that dies, throw a `GitReadError`: an unknown commit is never "not an ancestor".
126
+ */
127
+ export async function contains(repo: string, sha: string, base: string): Promise<boolean> {
128
+ const what = `whether ${base} holds ${sha} in ${repo}`;
129
+ const run = answered(await git(repo, ["merge-base", "--is-ancestor", sha, base]), what);
130
+ if (run.kind === "ok") return true;
131
+ if (run.code === 1) return false;
132
+ throw new GitReadError(`could not read ${what} (${run.stderr.split("\n")[0] || `git exited ${run.code}`})`);
133
+ }
@@ -0,0 +1,216 @@
1
+ /**
2
+ * Head evidence: a todo bound to a branch (`metadata.boundBranch`) completes only on passing evidence for that branch's current head,
3
+ * or once the branch is merged into its base. The ledger owns the namespace and checks it before the change guards; the git reads
4
+ * live in git-branch.ts.
5
+ */
6
+
7
+ import { isAbsolute } from "node:path";
8
+ import type { Op } from "../state/state-reducer.ts";
9
+ import type { TaskState } from "../state/state.ts";
10
+ import { sanitizeTerminalText } from "../tool/sanitize.ts";
11
+ import type { Task } from "../tool/types.ts";
12
+ import type { NamespaceValidator } from "./contract.ts";
13
+ import { baseOf, commitOf, contains, GitReadError, isBranchItself, unreadableRepo } from "./git-branch.ts";
14
+
15
+ export const BOUND_BRANCH = "boundBranch";
16
+
17
+ export interface BoundBranch {
18
+ /** A path in the repository: its git directory (what a launch records) or any checkout of it. May move to another clone while the todo is open, once it cannot be read. */
19
+ repo: string;
20
+ /** The branch name, as `git branch` shows it. */
21
+ ref: string;
22
+ /** The branch it merges into; without one, `origin/HEAD`, else `main`, else `master`. */
23
+ base?: string;
24
+ /** The worktree the launch ran in, for readers; the check does not need it. */
25
+ worktree?: string;
26
+ /** The branch's head when a launch bound it: commits after it are the branch's own work. A binding made by hand has none. */
27
+ start?: string;
28
+ }
29
+
30
+ const FIELDS = ["repo", "ref", "base", "worktree", "start"];
31
+
32
+ function isRecord(value: unknown): value is Record<string, unknown> {
33
+ return typeof value === "object" && value !== null && !Array.isArray(value);
34
+ }
35
+
36
+ /** A branch or revision name git takes as one argument: no leading `-`, no whitespace, none of git's revision syntax. */
37
+ const revName = (value: unknown): value is string =>
38
+ typeof value === "string" && /^[^-\s~^:?*[\\][^\s~^:?*[\\]*$/.test(value) && !value.includes("..") && !value.includes("@{");
39
+
40
+ const escape = (text: string) => text.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
41
+ /** Whether `base` spells branch `ref` itself or one of its remote-tracking refs. */
42
+ const ownRef = (base: string, ref: string) =>
43
+ base === ref || base === `refs/heads/${ref}` || new RegExp(`^(refs/)?remotes/[^/]+/${escape(ref)}$`).test(base);
44
+
45
+ const absolute = (value: unknown): value is string => typeof value === "string" && value.trim() === value && value.length > 0 && isAbsolute(value);
46
+
47
+ /** Why `value` is no `metadata.boundBranch`, or `undefined` when it is one. */
48
+ export function boundBranchError(value: unknown): string | undefined {
49
+ if (!isRecord(value)) return "must be an object { repo, ref, base?, worktree?, start? }";
50
+ const extra = Object.keys(value).filter((k) => !FIELDS.includes(k));
51
+ if (extra.length) return `unknown field ${extra.map((k) => `"${k}"`).join(", ")} (known: ${FIELDS.join(", ")})`;
52
+ if (!absolute(value.repo)) return "repo must be an absolute path in the repository";
53
+ if (!revName(value.ref)) return "ref must be a branch name";
54
+ if (value.base !== undefined && !revName(value.base)) return "base must be a branch name when present";
55
+ if (value.base !== undefined && ownRef(value.base as string, value.ref)) return "base must not be the branch itself or its remote-tracking ref";
56
+ if (value.worktree !== undefined && !absolute(value.worktree)) return "worktree must be an absolute path when present";
57
+ if (value.start !== undefined && !(typeof value.start === "string" && /^[0-9a-f]{40,64}$/.test(value.start))) return "start must be a full commit sha when present";
58
+ return undefined;
59
+ }
60
+
61
+ /** Accepts a valid binding and the removal of the key; whether an open todo may lose its binding is judged with the list (below). */
62
+ export const validateBoundBranch: NamespaceValidator = (value) => (value === undefined ? undefined : boundBranchError(value));
63
+
64
+ export function boundBranchOf(task: Task | undefined): BoundBranch | undefined {
65
+ const value = task?.metadata?.[BOUND_BRANCH];
66
+ return boundBranchError(value) === undefined ? (value as BoundBranch) : undefined;
67
+ }
68
+
69
+ /** Evidence shas that can name a commit: seven to 64 hex digits, compared in lower case. */
70
+ const SHA = /^[0-9a-f]{7,64}$/;
71
+
72
+ function passingShas(task: Task): string[] {
73
+ const shas = (task.evidence ?? []).filter((e) => e.result === "pass" && typeof e.sha === "string").map((e) => e.sha!.trim().toLowerCase());
74
+ return [...new Set(shas.filter((sha) => SHA.test(sha)))];
75
+ }
76
+
77
+ /** `text` as one POSIX shell word. */
78
+ const shellQuote = (text: string) => `'${text.replace(/'/g, "'\\''")}'`;
79
+
80
+ const MAX_LISTED = 5;
81
+ const listed = (shas: string[]) => shas.slice(0, MAX_LISTED).join(", ") + (shas.length > MAX_LISTED ? ` and ${shas.length - MAX_LISTED} more` : "");
82
+
83
+ /**
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
+ * 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
+ * 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
+ * none. Evidence shas `repo` does not know are skipped.
88
+ */
89
+ async function ownWorkInBase(binding: BoundBranch, shas: string[], base: string, head?: string): Promise<boolean> {
90
+ const start = binding.start ? await commitOf(binding.repo, binding.start) : undefined;
91
+ if (!start || (head && !(await contains(binding.repo, start, head)))) return false;
92
+ for (const sha of shas) {
93
+ const commit = await commitOf(binding.repo, sha);
94
+ if (!commit || commit === start) continue;
95
+ if ((await contains(binding.repo, start, commit)) && (await contains(binding.repo, commit, base))) return true;
96
+ }
97
+ return false;
98
+ }
99
+
100
+ /**
101
+ * 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`.
104
+ */
105
+ export async function launchMayRebind(task: Task): Promise<boolean> {
106
+ const binding = boundBranchOf(task);
107
+ if (!binding) return true;
108
+ if (await unreadableRepo(binding.repo)) return false;
109
+ const head = await commitOf(binding.repo, `refs/heads/${binding.ref}`);
110
+ if (!head) return true;
111
+ 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
+ }
114
+
115
+ /** 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> {
117
+ try {
118
+ return await judgeRead(task, binding);
119
+ } catch (error) {
120
+ if (!(error instanceof GitReadError)) throw error;
121
+ return `#${task.id} "${task.subject}" cannot complete: ${error.message} for its bound branch ${binding.ref}. Nothing changed; try again.`;
122
+ }
123
+ }
124
+
125
+ async function judgeRead(task: Task, binding: BoundBranch): Promise<string | undefined> {
126
+ const who = `#${task.id} "${task.subject}"`;
127
+ const branch = `branch ${binding.ref} in ${binding.repo}`;
128
+ const unreadable = await unreadableRepo(binding.repo);
129
+ if (unreadable) {
130
+ return `${who} cannot complete: its bound ${branch} cannot be read: ${unreadable}. Restore the repository, or point metadata.boundBranch.repo at a clone that holds ${binding.ref}.`;
131
+ }
132
+ if (binding.base !== undefined && (await isBranchItself(binding.repo, binding.base, binding.ref))) {
133
+ 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
+ }
135
+ const shas = passingShas(task);
136
+ const head = await commitOf(binding.repo, `refs/heads/${binding.ref}`);
137
+ const base = await baseOf(binding.repo, binding.base);
138
+ const baseWords = binding.base === undefined ? "no base branch (origin/HEAD, main or master)" : `no base ${binding.base}`;
139
+ if (head) {
140
+ if (shas.some((sha) => head.startsWith(sha))) return undefined;
141
+ // Merged: the base holds the head and a tested commit of the branch's own work. A hand-made binding has no start.
142
+ const inBase = !!(binding.start && base && (await contains(binding.repo, head, base.sha)));
143
+ if (inBase && (await ownWorkInBase(binding, shas, base!.sha, head))) return undefined;
144
+ const seen = shas.length ? `Its passing evidence names other commits: ${listed(shas)}.` : "It has no passing evidence on that commit.";
145
+ const merged = !binding.start || !base ? "" : inBase ? ` ${base.name} holds the head, but no tested commit of the branch's own work.` : ` The branch is not merged into ${base.name}.`;
146
+ 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.`;
148
+ }
149
+ // Deleted after a merge: a tested commit of the branch's own work (not the start or before it) is in the base.
150
+ if (base && (await ownWorkInBase(binding, shas, base.sha))) return undefined;
151
+ let why: string;
152
+ if (!binding.start) why = "a binding made by hand has no start to tell the branch's own commits from the base's";
153
+ 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
+ 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}`;
156
+ else why = `it has no passing evidence to show its work is in ${base.name}`;
157
+ // 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
+ // 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();
160
+ 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}` : ""}`;
162
+ 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
+ }
164
+
165
+ /** 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
+ const FROZEN = ["ref", "base", "start"] as const;
167
+
168
+ /** Why `next` may not replace binding `prev` of an open todo through the `todo` tool, or `undefined`. */
169
+ function bindingChange(prev: unknown, next: unknown): string | undefined {
170
+ if (prev === undefined) {
171
+ return isRecord(next) && next.start !== undefined ? "a binding's start is recorded by a launch, never set by hand" : undefined;
172
+ }
173
+ if (next === undefined) return "its binding cannot be removed";
174
+ const was = isRecord(prev) ? prev : {};
175
+ const now = isRecord(next) ? next : {};
176
+ const changed = FROZEN.filter((key) => was[key] !== now[key]);
177
+ return changed.length ? `its binding's ${changed.join(", ")} cannot change` : undefined;
178
+ }
179
+
180
+ /** 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
+ async function repoChange(prev: unknown, next: unknown): Promise<string | undefined> {
182
+ if (!isRecord(prev) || !isRecord(next) || prev.repo === next.repo || typeof prev.repo !== "string") return undefined;
183
+ return (await unreadableRepo(prev.repo)) ? undefined : `its binding's repo can change only when ${prev.repo} cannot be read, and it still reads`;
184
+ }
185
+
186
+ /** Who writes a change: the `todo` tool (an agent), or the ledger recording a `subagent` launch, the only writer that may rebind. */
187
+ export type BindingWriter = "tool" | "launch";
188
+
189
+ /**
190
+ * 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
+ * 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.
193
+ */
194
+ export async function headEvidenceRefusal(op: Op, before: TaskState, after: TaskState, writer: BindingWriter = "tool"): Promise<string | undefined> {
195
+ if (op.kind === "create" && writer === "tool") {
196
+ for (const id of op.taskIds) {
197
+ const why = bindingChange(undefined, after.tasks.find((t) => t.id === id)?.metadata?.[BOUND_BRANCH]);
198
+ if (why) return `#${id}: ${why}.`;
199
+ }
200
+ return undefined;
201
+ }
202
+ if (op.kind !== "update" || !op.changed) return undefined;
203
+ const prev = before.tasks.find((t) => t.id === op.id);
204
+ const next = after.tasks.find((t) => t.id === op.id);
205
+ if (!prev || !next) return undefined;
206
+ const open = prev.status === "pending" || prev.status === "in_progress";
207
+ if (open && writer === "tool" && next.status !== "deleted") {
208
+ const was = prev.metadata?.[BOUND_BRANCH], now = next.metadata?.[BOUND_BRANCH];
209
+ const why = bindingChange(was, now) ?? (await repoChange(was, now));
210
+ 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.`;
211
+ }
212
+ if (op.fromStatus === "completed" || op.toStatus !== "completed") return undefined;
213
+ const binding = boundBranchOf(next);
214
+ const reason = binding ? await judge(next, binding) : undefined;
215
+ return reason && sanitizeTerminalText(reason);
216
+ }
@@ -1,10 +1,13 @@
1
+ import { resolve } from "node:path";
1
2
  import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
2
3
  import { withSessionLock } from "../state/session-lock.ts";
3
4
  import { applyTaskMutation } from "../state/state-reducer.ts";
4
5
  import { getState, listGeneration, sid } from "../state/store.ts";
5
6
  import { sanitizeTerminalText } from "../tool/sanitize.ts";
6
7
  import type { FinishCall } from "./finish-call.ts";
8
+ import { commonDirOf, GitReadError, launchBranch } from "./git-branch.ts";
7
9
  import { runningGuard } from "./guards.ts";
10
+ import { BOUND_BRANCH, boundBranchOf, launchMayRebind } from "./head-evidence.ts";
8
11
 
9
12
  import { bindRun, history, runOfPath } from "./herdr-runs.ts";
10
13
 
@@ -59,6 +62,16 @@ export function registerHerdrOwner(pi: ExtensionAPI, finish: FinishCall) {
59
62
  structuredContent: event.structuredContent,
60
63
  });
61
64
  if (runningGuard(session)) return warn("cannot update the list from its own change guard");
65
+ // A launch into a linked worktree binds the todo to that worktree's branch (head-evidence.ts); a resume keeps the binding it has.
66
+ const dir = resume ? undefined : record(d.worktree) && nonblank(d.worktree.path) ? d.worktree.path : nonblank(event.input.cwd) ? resolve(ctx.cwd, event.input.cwd) : undefined;
67
+ let boundBranch: Awaited<ReturnType<typeof launchBranch>>;
68
+ let notice: string | undefined;
69
+ try {
70
+ boundBranch = dir ? await launchBranch(dir, ctx.cwd) : undefined;
71
+ } catch (error) {
72
+ if (!(error instanceof GitReadError)) throw error;
73
+ notice = `${error.message}; the todo is not bound to a branch`;
74
+ }
62
75
  try {
63
76
  return await withSessionLock(session, async () => {
64
77
  const before = getState(session);
@@ -70,9 +83,24 @@ export function registerHerdrOwner(pi: ExtensionAPI, finish: FinishCall) {
70
83
  : before.tasks.find(t => t.uid === (pinned?.uid ?? item));
71
84
  if (!task || task.status === "deleted") return;
72
85
  const herdr = bindRun(task.metadata?.herdr, run);
73
- const params = { action: "update", id: task.id, owner: herdr.name, metadata: { herdr } };
74
- const result = await finish(session, ctx.cwd, "update", params, before, applyTaskMutation(before, "update", params));
75
- if (result.details.error) return warn(result.details.error);
86
+ // A launch onto the bound branch keeps the binding as it was. One onto another branch rebinds, with a new start, only when the
87
+ // todo has no binding or its branch was deleted or merged (launchMayRebind); else the binding stays and the launch is told so.
88
+ const current = boundBranchOf(task);
89
+ let rebind = false;
90
+ try {
91
+ const same = !!boundBranch && !!current && current.ref === boundBranch.ref && (await commonDirOf(current.repo)) === (await commonDirOf(boundBranch.repo));
92
+ rebind = !!boundBranch && !same && (await launchMayRebind(task));
93
+ 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
+ }
96
+ } catch (error) {
97
+ if (!(error instanceof GitReadError)) throw error;
98
+ notice = `${error.message}; the todo keeps its binding`;
99
+ }
100
+ const params = { action: "update", id: task.id, owner: herdr.name, metadata: { herdr, ...(rebind ? { [BOUND_BRANCH]: boundBranch } : {}) } };
101
+ const result = await finish(session, ctx.cwd, "update", params, before, applyTaskMutation(before, "update", params), undefined, undefined, undefined, "launch");
102
+ if (result.details.error) return warn(notice ? `${notice}; ${result.details.error}` : result.details.error);
103
+ if (notice) return warn(notice);
76
104
  });
77
105
  } catch (error) {
78
106
  // Herdr already launched the child. Don't turn a persistence error into a failed launch/retry.