ceulen 0.15.1 → 0.16.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (55) hide show
  1. package/CHANGELOG.md +62 -0
  2. package/README.md +2 -2
  3. package/extensions/lib/registry.test.ts +12 -0
  4. package/extensions/lib/registry.ts +20 -4
  5. package/extensions/modules/classifier/index.ts +29 -12
  6. package/extensions/modules/classifier/lib/settings.ts +20 -3
  7. package/extensions/modules/classifier/test/classifier.test.ts +12 -4
  8. package/extensions/modules/config/defaultTools.ts +8 -5
  9. package/extensions/modules/config/test/defaultTools.test.ts +16 -0
  10. package/extensions/modules/gh/lib/ops.ts +22 -4
  11. package/extensions/modules/gh/test/gh.test.ts +64 -1
  12. package/extensions/modules/munin/index.ts +4 -4
  13. package/extensions/modules/plan/index.ts +116 -4
  14. package/extensions/modules/plan/lib/settings.ts +5 -7
  15. package/extensions/modules/plan/test/module.test.ts +104 -1
  16. package/extensions/modules/plan/test/settings.test.ts +7 -0
  17. package/extensions/modules/repair/configPanel.ts +3 -1
  18. package/extensions/modules/repair/index.ts +21 -16
  19. package/extensions/modules/repair/lib/read-sqlite.ts +18 -7
  20. package/extensions/modules/repair/test/freshness.test.ts +30 -0
  21. package/extensions/modules/repair/test/hardening.test.ts +46 -1
  22. package/extensions/modules/repair/test/readers.test.ts +11 -5
  23. package/extensions/modules/repair/test/settings.test.ts +7 -2
  24. package/extensions/modules/rtk/configPanel.ts +67 -0
  25. package/extensions/modules/rtk/index.ts +76 -9
  26. package/extensions/modules/rtk/lib/settings.ts +65 -0
  27. package/extensions/modules/rtk/test/configPanel.test.ts +72 -0
  28. package/extensions/modules/rtk/test/index.test.js +120 -2
  29. package/extensions/modules/rules/index.ts +4 -1
  30. package/extensions/modules/rules/lib/rules.ts +6 -3
  31. package/extensions/modules/rules/test/lib.test.ts +24 -0
  32. package/extensions/modules/rules/test/module.test.ts +29 -0
  33. package/extensions/modules/shells/lib/sessions.ts +40 -12
  34. package/extensions/modules/shells/test/sessions.test.ts +60 -2
  35. package/extensions/modules/steering/index.ts +12 -1
  36. package/extensions/modules/steering/test/anchor-plan.test.ts +73 -0
  37. package/extensions/modules/subagent/index.ts +19 -3
  38. package/extensions/modules/subagent/lib/herdr.ts +141 -1
  39. package/extensions/modules/subagent/lib/runner.ts +88 -22
  40. package/extensions/modules/subagent/test/herdr-stalled.test.ts +117 -0
  41. package/extensions/modules/subagent/test/worktree.test.ts +156 -1
  42. package/extensions/modules/todo/index.ts +4 -0
  43. package/extensions/modules/todo/test/todo.test.ts +9 -0
  44. package/extensions/modules/web/index.ts +1 -1
  45. package/extensions/modules/web/lib/a11y.ts +30 -15
  46. package/extensions/modules/web/lib/cdp.ts +11 -2
  47. package/extensions/modules/web/lib/chrome.ts +12 -3
  48. package/extensions/modules/web/lib/content.ts +32 -9
  49. package/extensions/modules/web/lib/search.ts +111 -3
  50. package/extensions/modules/web/test/a11y.test.ts +100 -2
  51. package/extensions/modules/web/test/cdp.test.ts +48 -0
  52. package/extensions/modules/web/test/chrome.test.ts +32 -0
  53. package/extensions/modules/web/test/content.test.ts +92 -0
  54. package/extensions/modules/web/test/search.test.ts +75 -0
  55. package/package.json +1 -1
@@ -460,13 +460,23 @@ export const WORKTREE_DIR_NAME = ".pi-worktrees";
460
460
 
461
461
  /** A nested `.gitignore` (content `*`) inside the sandbox base keeps sandboxes
462
462
  * out of the parent's `git status` AND out of untracked baseline capture —
463
- * without touching the user's own .gitignore. */
464
- async function ensureWorktreeBaseGitignore(base: string): Promise<void> {
463
+ * without touching the user's own .gitignore. Returns an error note when the
464
+ * base is unusable (sandboxes would then be enumerable by the baseline
465
+ * capture), undefined on success. */
466
+ async function ensureWorktreeBaseGitignore(base: string): Promise<string | undefined> {
465
467
  const ignoreFile = path.join(base, ".gitignore");
466
468
  try {
467
469
  await fs.mkdir(base, { recursive: true });
468
470
  await fs.writeFile(ignoreFile, "*\n", { flag: "wx" });
469
- } catch { /* exists (or unwritable) — either is fine */ }
471
+ } catch (error) {
472
+ if ((error as NodeJS.ErrnoException)?.code !== "EEXIST") {
473
+ return `could not write ${WORKTREE_DIR_NAME}/.gitignore: ${(error as Error).message}`;
474
+ }
475
+ }
476
+ // EEXIST is acceptable only if the thing at that path IS the ignore file.
477
+ const st = await fs.stat(ignoreFile).catch(() => undefined);
478
+ if (!st?.isFile()) return `${WORKTREE_DIR_NAME}/.gitignore is missing or not a file`;
479
+ return undefined;
470
480
  }
471
481
 
472
482
  /** Owner marker: a SIBLING file inside the (gitignored) sandbox base —
@@ -476,9 +486,14 @@ async function ensureWorktreeBaseGitignore(base: string): Promise<void> {
476
486
  * concurrent-merge race test). */
477
487
  export const OWNER_SUFFIX = ".owner.json";
478
488
 
489
+ /** Atomic write (tmp + rename) — a concurrent sweep reader must never see a
490
+ * partial marker and mistake a live sandbox for stale. */
479
491
  async function writeOwnerMarker(base: string, id: string): Promise<void> {
480
492
  const owner: WorktreeOwner = { pid: process.pid, id, createdAt: Date.now() };
481
- await fs.writeFile(path.join(base, `${id}${OWNER_SUFFIX}`), JSON.stringify(owner), { encoding: "utf8", mode: 0o600 });
493
+ const target = path.join(base, `${id}${OWNER_SUFFIX}`);
494
+ const tmp = `${target}.tmp-${process.pid}-${Math.random().toString(36).slice(2, 8)}`;
495
+ await fs.writeFile(tmp, JSON.stringify(owner), { encoding: "utf8", mode: 0o600, flag: "wx" });
496
+ await fs.rename(tmp, target);
482
497
  }
483
498
 
484
499
  async function readOwnerMarker(base: string, entry: string): Promise<WorktreeOwner | undefined> {
@@ -510,10 +525,13 @@ export interface SweepResult {
510
525
  /** Remove crashed runs' worktree sandboxes under <repoRoot>/.pi-worktrees.
511
526
  * Source of truth is the DIRECTORY (covers both backends); the git
512
527
  * registration check only decides HOW a stale dir is removed. Never removes
513
- * a sandbox whose marker pid is alive. Best-effort throughout. */
528
+ * a sandbox whose marker pid is alive — except under opts.force, which may
529
+ * also remove FOREIGN live-pid sandboxes (pid recycling can false-KEEP);
530
+ * this process's own live sandboxes stay protected. Best-effort throughout. */
514
531
  export async function sweepStaleWorktrees(
515
532
  cwd: string,
516
533
  exec?: (command: string, args: string[], options?: { cwd?: string; timeout?: number }) => Promise<{ code: number; stdout: string; stderr: string }>,
534
+ opts?: { force?: boolean },
517
535
  ): Promise<SweepResult> {
518
536
  const removed: string[] = [];
519
537
  try {
@@ -534,17 +552,35 @@ export async function sweepStaleWorktrees(
534
552
  (list.ok ? list.stdout : "").split("\n").filter((l) => l.startsWith("worktree ")).map((l) => l.slice("worktree ".length).trim()),
535
553
  );
536
554
  for (const entry of entries) {
537
- if (entry.endsWith(OWNER_SUFFIX)) continue; // marker files, not sandboxes
555
+ if (entry.endsWith(OWNER_SUFFIX)) {
556
+ // Orphan marker (creation failed after the write, or the sandbox was
557
+ // already swept): the dir is gone, so drop the marker instead of
558
+ // skipping it forever — it would otherwise render as a phantom row
559
+ // in /subagent worktrees for the life of the checkout.
560
+ const orphanDir = path.join(base, entry.slice(0, -OWNER_SUFFIX.length));
561
+ if (!(await fs.stat(orphanDir).then((s) => s.isDirectory()).catch(() => false))) {
562
+ await fs.rm(path.join(base, entry), { force: true }).catch(() => { /* best effort */ });
563
+ }
564
+ continue; // marker files, not sandboxes
565
+ }
538
566
  const dir = path.join(base, entry);
539
567
  // The nested .gitignore is a FILE, not a sandbox — never scan/rm it.
540
568
  if (!(await fs.stat(dir).then((s) => s.isDirectory()).catch(() => false))) continue;
541
569
  const owner = await readOwnerMarker(base, entry);
542
- if (owner && pidAlive(owner.pid)) { kept++; continue; }
570
+ if (owner && pidAlive(owner.pid) && (!opts?.force || owner.pid === process.pid)) { kept++; continue; }
543
571
  // ponytail: pid recycling can false-KEEP a stale sandbox (safe
544
- // direction); `/subagent worktrees clean` is the manual override.
572
+ // direction); `/subagent worktrees clean` passes force, which lifts
573
+ // the keep-gate for foreign live pids only.
545
574
  try {
546
- if (registered.has(dir)) await runGit(repoRoot, ["worktree", "remove", "--force", dir], exec);
575
+ let removeFailed = false;
576
+ if (registered.has(dir)) {
577
+ const rmRes = await runGit(repoRoot, ["worktree", "remove", "--force", dir], exec);
578
+ removeFailed = !rmRes.ok;
579
+ }
547
580
  await fs.rm(dir, { recursive: true, force: true });
581
+ // rm -rf alone leaves a stale .git/worktrees registration behind —
582
+ // prune it (after the dir is gone; prune only drops missing dirs).
583
+ if (removeFailed) await runGit(repoRoot, ["worktree", "prune"], exec);
548
584
  await fs.rm(path.join(base, `${entry}${OWNER_SUFFIX}`), { force: true });
549
585
  removed.push(dir);
550
586
  } catch { /* best effort per dir */ }
@@ -648,7 +684,13 @@ async function createCowClone(
648
684
  const entries = await fs.readdir(repoRoot, { withFileTypes: true });
649
685
  for (const entry of entries) {
650
686
  if (entry.name === WORKTREE_DIR_NAME) continue;
651
- const res = await run("cp", ["-cR", path.join(repoRoot, entry.name), path.join(staging, entry.name)], { timeout: 300_000 });
687
+ const args = ["-cR", path.join(repoRoot, entry.name), path.join(staging, entry.name)];
688
+ // The live .git mutates under us — copy it under the same per-repo lock
689
+ // the sibling mutators (worktree add/remove, git apply --3way) hold, or
690
+ // a concurrent mutation can tear the copy.
691
+ const res = entry.name === ".git"
692
+ ? await withRepoLock(repoRoot, () => run("cp", args, { timeout: 300_000 }))
693
+ : await run("cp", args, { timeout: 300_000 });
652
694
  if (res.code !== 0) return false;
653
695
  }
654
696
  await fs.mkdir(path.dirname(wtPath), { recursive: true });
@@ -740,19 +782,43 @@ export async function createWorktree(
740
782
  const repoRoot = root.stdout.trim();
741
783
  if (!repoRoot) return { ok: false, error: "empty git root" };
742
784
  const id = `pi-subagent-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 8)}`;
743
- const wtPath = path.join(repoRoot, WORKTREE_DIR_NAME, id);
744
- await ensureWorktreeBaseGitignore(path.join(repoRoot, WORKTREE_DIR_NAME));
745
- if (await createCowClone(repoRoot, wtPath, exec)) {
746
- await writeOwnerMarker(path.join(repoRoot, WORKTREE_DIR_NAME), id).catch(() => { /* best effort */ });
747
- return { ok: true, path: wtPath, repoRoot };
785
+ const base = path.join(repoRoot, WORKTREE_DIR_NAME);
786
+ const wtPath = path.join(base, id);
787
+ const ignoreError = await ensureWorktreeBaseGitignore(base);
788
+ if (ignoreError) return { ok: false, error: ignoreError };
789
+ // Owner marker BEFORE the sandbox becomes visible at wtPath (CoW rename /
790
+ // `worktree add`): the GC sweep treats a missing marker as stale and
791
+ // rm -rf's the dir, so a marker published late — or failing to publish —
792
+ // must never leave an unprotected live sandbox behind.
793
+ const markerError = await writeOwnerMarker(base, id).then(
794
+ () => undefined,
795
+ (error) => (error instanceof Error ? error.message : String(error)),
796
+ );
797
+ if (markerError) return { ok: false, error: `owner marker unwritable (${markerError}) — refusing to create an unprotected sandbox` };
798
+ let outcome: { ok: boolean; path?: string; repoRoot?: string; error?: string; cow?: boolean };
799
+ try {
800
+ if (await createCowClone(repoRoot, wtPath, exec)) {
801
+ outcome = { ok: true, path: wtPath, repoRoot };
802
+ } else {
803
+ // Fallback: detached git worktree (clean HEAD; the caller seeds the
804
+ // parent's WIP via applyBaselineToWorktree). worktree add mutates the
805
+ // parent's shared .git/worktrees registry. The marker already covers it.
806
+ const add = await withRepoLock(repoRoot, () => runGit(repoRoot, ["worktree", "add", "--detach", wtPath, "HEAD"], exec));
807
+ outcome = add.ok
808
+ ? { ok: true, path: wtPath, repoRoot, cow: false }
809
+ : { ok: false, error: add.stderr.trim() || "git worktree add failed" };
810
+ }
811
+ } catch (error) {
812
+ // A rejecting exec (or any throw) after the marker write lands here.
813
+ outcome = { ok: false, error: error instanceof Error ? error.message : String(error) };
814
+ }
815
+ if (!outcome.ok) {
816
+ // No sandbox was published — drop the marker so it cannot litter the
817
+ // base as an orphan: the sweep skips marker entries and /subagent
818
+ // worktrees would render it as a phantom row forever.
819
+ await fs.rm(path.join(base, `${id}${OWNER_SUFFIX}`), { force: true }).catch(() => { /* best effort */ });
748
820
  }
749
- // Fallback: detached git worktree (clean HEAD; the caller seeds the
750
- // parent's WIP via applyBaselineToWorktree). worktree add mutates the
751
- // parent's shared .git/worktrees registry.
752
- const add = await withRepoLock(repoRoot, () => runGit(repoRoot, ["worktree", "add", "--detach", wtPath, "HEAD"], exec));
753
- if (!add.ok) return { ok: false, error: add.stderr.trim() || "git worktree add failed" };
754
- await writeOwnerMarker(path.join(repoRoot, WORKTREE_DIR_NAME), id).catch(() => { /* best effort */ });
755
- return { ok: true, path: wtPath, repoRoot, cow: false };
821
+ return outcome;
756
822
  } catch (error) {
757
823
  return { ok: false, error: error instanceof Error ? error.message : String(error) };
758
824
  }
@@ -0,0 +1,117 @@
1
+ // promptAndWait's agent_prompt_stalled recovery — OUTPUT-evidence based.
2
+ // herdr 0.9.3's status watcher never observes `working` for pi panes
3
+ // (state_change_seq frozen across live turns; live probe 2026-10-10), so its
4
+ // `agent prompt --wait` stalls on healthy dispatches and NO state probe can
5
+ // recover it. Recovery waits on evidence instead: a changed report-file stamp
6
+ // (delivery contract) or a changed-then-quiet pane tail (read-only inline
7
+ // replies). Silence through the grace window is a genuine stall.
8
+
9
+ import assert from "node:assert/strict";
10
+ import { mkdtempSync, writeFileSync, statSync } from "node:fs";
11
+ import { tmpdir } from "node:os";
12
+ import { join } from "node:path";
13
+ import { test } from "node:test";
14
+
15
+ import { captureEvidenceStamp, promptAndWait } from "../lib/herdr.ts";
16
+
17
+ type FakeRes = { code: number; stdout?: string; stderr?: string };
18
+ type Call = { args: string[]; res: { code: number; stdout: string; stderr: string } };
19
+
20
+ /** Scripted exec: args-signature (first 2 tokens, e.g. "agent read") → responses consumed in order. */
21
+ function fakeExec(script: Map<string, FakeRes[]>, calls: Call[]) {
22
+ return async (_cmd: string, args: string[]) => {
23
+ const key = args.slice(0, 2).join(" ");
24
+ const res = { code: 0, stdout: "", stderr: "", ...script.get(key)?.shift() };
25
+ calls.push({ args, res });
26
+ return res;
27
+ };
28
+ }
29
+
30
+ const idleInfo = JSON.stringify({ result: { agent: { name: "a1", agent_status: "idle" } } });
31
+ const STALLED = { code: 1, stderr: "error: agent_prompt_stalled: no working within 5000ms" };
32
+
33
+ function tmpResultFile(): string {
34
+ return join(mkdtempSync(join(tmpdir(), "ceulen-herdr-stalled-")), "report.md");
35
+ }
36
+
37
+ test("captureEvidenceStamp: missing file → empty stamp; existing → size:mtime", async () => {
38
+ const missing = join(tmpdir(), "ceulen-herdr-stamped-", "nope.md");
39
+ const exec = fakeExec(new Map(), []);
40
+ assert.equal((await captureEvidenceStamp({ resultFile: missing }, "a1", exec)).fileStamp, "");
41
+ const f = tmpResultFile();
42
+ writeFileSync(f, "hello");
43
+ const st = statSync(f);
44
+ assert.equal((await captureEvidenceStamp({ resultFile: f }, "a1", exec)).fileStamp, `${st.size}:${st.mtimeMs}`);
45
+ });
46
+
47
+ test("stalled recovery: report file appears during grace → success (fast-child case)", async () => {
48
+ const resultFile = tmpResultFile();
49
+ // Baseline taken BEFORE the file exists (like a first dispatch); the child
50
+ // writing its report is the settle evidence.
51
+ const stamp = await captureEvidenceStamp({ resultFile }, "a1", fakeExec(new Map(), []));
52
+ writeFileSync(resultFile, "# report\n");
53
+ const calls: Call[] = [];
54
+ const script = new Map<string, FakeRes[]>([
55
+ ["agent prompt", [STALLED]],
56
+ ["agent get", [{ code: 0, stdout: idleInfo }]],
57
+ ]);
58
+ const outcome = await promptAndWait({
59
+ name: "a1", text: "t", timeoutMs: 5_000, exec: fakeExec(script, calls),
60
+ evidence: { resultFile, stamp, graceMs: 5_000 },
61
+ });
62
+ assert.equal(outcome.delivered, true);
63
+ assert.equal(outcome.error, undefined);
64
+ assert.equal(outcome.state, "idle");
65
+ });
66
+
67
+ test("stalled recovery: read-only child's pane tail changed + stayed quiet → success", async () => {
68
+ const calls: Call[] = [];
69
+ const script = new Map<string, FakeRes[]>([
70
+ ["agent prompt", [STALLED]],
71
+ ["agent read", [{ code: 0, stdout: "REPLY-DONE" }]],
72
+ ["agent get", [{ code: 0, stdout: idleInfo }]],
73
+ ]);
74
+ const outcome = await promptAndWait({
75
+ name: "a1", text: "t", timeoutMs: 5_000, exec: fakeExec(script, calls),
76
+ evidence: { resultFile: tmpResultFile(), readOnly: true, stamp: { fileStamp: "", paneTail: "PRE-PROMPT" }, graceMs: 15_000 },
77
+ });
78
+ assert.equal(outcome.delivered, true);
79
+ assert.equal(outcome.state, "idle");
80
+ });
81
+
82
+ test("stalled recovery: silence through the evidence window → timeout semantics (delivered, may still complete)", async () => {
83
+ const resultFile = tmpResultFile(); // never written
84
+ const calls: Call[] = [];
85
+ const script = new Map<string, FakeRes[]>([
86
+ ["agent prompt", [STALLED]],
87
+ ]);
88
+ const outcome = await promptAndWait({
89
+ name: "a1", text: "t", timeoutMs: 5_000, exec: fakeExec(script, calls),
90
+ evidence: { resultFile, stamp: { fileStamp: "" }, graceMs: 200 },
91
+ });
92
+ // Exhausted evidence wait = spent budget: the caller interrupts the pane;
93
+ // the dispatch was delivered, so never a hard stall.
94
+ assert.equal(outcome.delivered, true);
95
+ assert.match(outcome.error ?? "", /timeout/);
96
+ });
97
+
98
+ test("stalled without evidence channels → immediate hard fail (CLI-faithful, unchanged)", async () => {
99
+ const calls: Call[] = [];
100
+ const script = new Map<string, FakeRes[]>([["agent prompt", [STALLED]]]);
101
+ const outcome = await promptAndWait({ name: "a1", text: "t", timeoutMs: 5_000, exec: fakeExec(script, calls) });
102
+ assert.equal(outcome.delivered, false);
103
+ assert.match(outcome.error ?? "", /agent_prompt_stalled/);
104
+ // No evidence polling happened (no `agent read` calls).
105
+ assert.equal(calls.filter((c) => c.args[1] === "read").length, 0);
106
+ });
107
+
108
+ test("no regression: plain timeout still short-circuits before the stalled branch", async () => {
109
+ const calls: Call[] = [];
110
+ const script = new Map<string, FakeRes[]>([
111
+ ["agent prompt", [{ code: 1, stderr: "error: timeout after 1000ms" }]],
112
+ ]);
113
+ const outcome = await promptAndWait({ name: "a1", text: "t", timeoutMs: 1000, exec: fakeExec(script, calls) });
114
+ assert.equal(outcome.delivered, true);
115
+ assert.match(outcome.error ?? "", /timeout/);
116
+ assert.equal(calls.filter((c) => c.args[1] === "read").length, 0);
117
+ });
@@ -5,7 +5,8 @@
5
5
  // git version; on-disk effects use real temp dirs.
6
6
 
7
7
  import assert from "node:assert/strict";
8
- import { mkdtemp, mkdir, readFile, readdir, rm, stat, writeFile } from "node:fs/promises";
8
+ import { chmod, mkdtemp, mkdir, readFile, readdir, rm, stat, writeFile } from "node:fs/promises";
9
+ import { readdirSync } from "node:fs";
9
10
  import { tmpdir } from "node:os";
10
11
  import { join } from "node:path";
11
12
  import { after, describe, it } from "node:test";
@@ -125,6 +126,42 @@ describe("sweepStaleWorktrees", () => {
125
126
  assert.deepEqual(result, { removed: [], kept: 0 });
126
127
  assert.equal(exec.calls.length, 1);
127
128
  });
129
+
130
+ it("orphan marker (no matching dir) is reclaimed by the sweep", async () => {
131
+ const repo = await tempDir("wt-sweep-orphan-");
132
+ const base = join(repo, WORKTREE_DIR_NAME);
133
+ await mkdir(base, { recursive: true });
134
+ await writeFile(join(base, "orphan.owner.json"), JSON.stringify({ pid: process.pid, id: "orphan", createdAt: Date.now() }));
135
+ const exec = fakeExec([
136
+ { match: (_c, args) => args[0] === "rev-parse", stdout: `${repo}\n` },
137
+ { match: (_c, args) => args[0] === "worktree" && args[1] === "list", stdout: "" },
138
+ ]);
139
+ const result = await sweepStaleWorktrees(repo, exec);
140
+ assert.deepEqual(result, { removed: [], kept: 0 });
141
+ await assert.rejects(stat(join(base, "orphan.owner.json")), "orphan marker must be dropped");
142
+ });
143
+
144
+ it("force: foreign live-pid sandbox removed, non-force keeps it, own pid stays protected", async () => {
145
+ const repo = await tempDir("wt-sweep-force-");
146
+ const base = join(repo, WORKTREE_DIR_NAME);
147
+ await mkdir(join(base, "foreign"), { recursive: true });
148
+ await mkdir(join(base, "mine"), { recursive: true });
149
+ await writeFile(join(base, "foreign.owner.json"), JSON.stringify({ pid: 1, id: "foreign", createdAt: Date.now() }));
150
+ await writeFile(join(base, "mine.owner.json"), JSON.stringify({ pid: process.pid, id: "mine", createdAt: Date.now() }));
151
+ const exec = fakeExec([
152
+ { match: (_c, args) => args[0] === "rev-parse", stdout: `${repo}\n` },
153
+ { match: (_c, args) => args[0] === "worktree" && args[1] === "list", stdout: "" },
154
+ ]);
155
+ const plain = await sweepStaleWorktrees(repo, exec);
156
+ assert.equal(plain.kept, 2); // pid 1 (launchd/init) is alive — the false-KEEP
157
+ await stat(join(base, "foreign"));
158
+
159
+ const forced = await sweepStaleWorktrees(repo, exec, { force: true });
160
+ assert.deepEqual(forced.removed.map((r) => r.split("/").pop()), ["foreign"]);
161
+ assert.equal(forced.kept, 1);
162
+ await assert.rejects(stat(join(base, "foreign")));
163
+ await stat(join(base, "mine")); // this process's own live sandbox survives force
164
+ });
128
165
  });
129
166
 
130
167
  // ── Baseline capture: PURE READS on the parent ─────────────────────────────
@@ -227,4 +264,122 @@ describe("createWorktree", () => {
227
264
  assert.equal(result.ok, false);
228
265
  assert.match(result.error!, /not a git repo/);
229
266
  });
267
+
268
+ it("owner marker exists at the moment `worktree add` runs (git fallback path)", async () => {
269
+ const repo = await tempDir("wt-marker-add-");
270
+ await mkdir(join(repo, ".git"), { recursive: true });
271
+ const base = join(repo, WORKTREE_DIR_NAME);
272
+ let sawMarker: boolean | undefined;
273
+ const exec = fakeExec([
274
+ { match: (_c, args) => args[0] === "rev-parse", stdout: `${repo}\n` },
275
+ { match: (c) => c === "cp", code: 1, stderr: "cp failed" }, // force the git-worktree fallback
276
+ ]);
277
+ const wrapped: Exec = async (command, args, options) => {
278
+ if (command === "git" && args[0] === "worktree" && args[1] === "add") {
279
+ sawMarker = readdirSync(base).some((f) => f.endsWith(".owner.json"));
280
+ }
281
+ return exec(command, args, options);
282
+ };
283
+ const result = await createWorktree(repo, wrapped);
284
+ assert.equal(result.ok, true);
285
+ assert.equal(result.cow, false);
286
+ assert.equal(sawMarker, true, "marker must exist before the sandbox is registered");
287
+ });
288
+
289
+ it("marker-write failure → createWorktree fails; never ok without a marker", async () => {
290
+ if (typeof process.getuid === "function" && process.getuid() === 0) return; // root ignores dir perms
291
+ const repo = await tempDir("wt-marker-eacces-");
292
+ await mkdir(join(repo, ".git"), { recursive: true });
293
+ const base = join(repo, WORKTREE_DIR_NAME);
294
+ await mkdir(base, { recursive: true });
295
+ await writeFile(join(base, ".gitignore"), "*\n"); // the gitignore check passes; the MARKER write is what fails
296
+ await chmod(base, 0o500);
297
+ try {
298
+ const exec = fakeExec([{ match: (_c, args) => args[0] === "rev-parse", stdout: `${repo}\n` }]);
299
+ const result = await createWorktree(repo, exec);
300
+ assert.equal(result.ok, false);
301
+ assert.match(result.error!, /marker/);
302
+ assert.ok(!exec.calls.some((c) => c.command === "git" && c.args[0] === "worktree"), "no sandbox registered");
303
+ } finally {
304
+ await chmod(base, 0o700);
305
+ }
306
+ });
307
+
308
+ it("a rejecting `worktree add` after the marker write → ok:false AND no orphan marker", async () => {
309
+ const repo = await tempDir("wt-add-throws-");
310
+ await mkdir(join(repo, ".git"), { recursive: true });
311
+ const base = join(repo, WORKTREE_DIR_NAME);
312
+ const exec = fakeExec([
313
+ { match: (_c, args) => args[0] === "rev-parse", stdout: `${repo}\n` },
314
+ { match: (c) => c === "cp", code: 1, stderr: "cp failed" }, // force the git-worktree fallback
315
+ ]);
316
+ const wrapped: Exec = async (command, args, options) => {
317
+ if (command === "git" && args[0] === "worktree" && args[1] === "add") throw new Error("worktree add exploded");
318
+ return exec(command, args, options);
319
+ };
320
+ const result = await createWorktree(repo, wrapped);
321
+ assert.equal(result.ok, false);
322
+ assert.match(result.error!, /exploded/);
323
+ const leftovers = (await readdir(base).catch(() => [] as string[])).filter((f) => f.endsWith(".owner.json"));
324
+ assert.deepEqual(leftovers, [], "no orphan marker may survive a failed creation");
325
+ });
326
+
327
+ it("CoW copies the live .git under the repo lock (no torn copy)", { skip: process.platform !== "darwin" }, async () => {
328
+ const repo = await tempDir("wt-cow-lock-");
329
+ await mkdir(join(repo, ".git"), { recursive: true });
330
+ await writeFile(join(repo, "file.txt"), "x");
331
+ const order: string[] = [];
332
+ let release!: () => void;
333
+ const gate = new Promise<void>((r) => { release = r; });
334
+ const holder = withRepoLock(repo, async () => { order.push("lock-start"); await gate; order.push("lock-end"); });
335
+ await new Promise((r) => setTimeout(r, 10));
336
+ assert.deepEqual(order, ["lock-start"], "holder acquired the lock first");
337
+ const exec = fakeExec([
338
+ { match: (_c, args) => args[0] === "rev-parse", stdout: `${repo}\n` },
339
+ { match: (c) => c === "cp" },
340
+ ]);
341
+ const wrapped: Exec = async (command, args, options) => {
342
+ if (command === "cp" && args[1]?.endsWith("/.git")) order.push("cow-git");
343
+ return exec(command, args, options);
344
+ };
345
+ const pending = createWorktree(repo, wrapped);
346
+ await new Promise((r) => setTimeout(r, 20));
347
+ assert.ok(!order.includes("cow-git"), "cp .git waits for the lock");
348
+ release();
349
+ await holder;
350
+ const result = await pending;
351
+ assert.ok(result.ok, result.error);
352
+ assert.equal(result.cow, undefined, "CoW path ran");
353
+ assert.deepEqual(order, ["lock-start", "lock-end", "cow-git"]);
354
+ });
355
+
356
+ it("base .gitignore as a DIRECTORY → createWorktree fails loudly", async () => {
357
+ const repo = await tempDir("wt-gitignore-dir-");
358
+ await mkdir(join(repo, ".git"), { recursive: true });
359
+ await mkdir(join(repo, WORKTREE_DIR_NAME, ".gitignore"), { recursive: true });
360
+ const exec = fakeExec([{ match: (_c, args) => args[0] === "rev-parse", stdout: `${repo}\n` }]);
361
+ const result = await createWorktree(repo, exec);
362
+ assert.equal(result.ok, false);
363
+ assert.match(result.error!, /\.gitignore/);
364
+ assert.ok(!exec.calls.some((c) => c.command === "cp" || c.args[0] === "worktree"), "no sandbox materialized");
365
+ });
366
+ });
367
+
368
+ // ── Sweep: registry stays consistent when `worktree remove` fails ───────────
369
+
370
+ describe("sweepStaleWorktrees — prune fallback", () => {
371
+ it("a registered dir whose `worktree remove` exits 1 gets `worktree prune`", async () => {
372
+ const repo = await tempDir("wt-sweep-prune-");
373
+ const base = join(repo, WORKTREE_DIR_NAME);
374
+ await mkdir(join(base, "stuck"), { recursive: true });
375
+ const exec = fakeExec([
376
+ { match: (_c, args) => args[0] === "rev-parse", stdout: `${repo}\n` },
377
+ { match: (_c, args) => args[0] === "worktree" && args[1] === "list", stdout: `worktree ${join(base, "stuck")}\n` },
378
+ { match: (_c, args) => args[0] === "worktree" && args[1] === "remove", code: 1, stderr: "remove failed" },
379
+ ]);
380
+ const result = await sweepStaleWorktrees(repo, exec);
381
+ assert.deepEqual(result.removed.map((r) => r.split("/").pop()), ["stuck"]);
382
+ assert.ok(exec.calls.some((c) => c.args[0] === "worktree" && c.args[1] === "prune"), "prune issued after failed remove");
383
+ await assert.rejects(stat(join(base, "stuck"))); // the dir is still gone
384
+ });
230
385
  });
@@ -233,6 +233,9 @@ export function applyTodo(current: readonly TodoPhase[], params: TodoParams): Ap
233
233
  for (const [i, p] of list.entries()) {
234
234
  const title = p.title.trim();
235
235
  if (!title) return fail("Every phase needs a title");
236
+ // Blocked is DERIVED from unmet blockedBy edges — a stored "blocked"
237
+ // status never clears (unblock touches blockedBy only), so refuse it.
238
+ if (p.status === "blocked") return fail(`"${title}": status "blocked" is derived from unmet blockedBy edges and is never stored — pass blockedBy: [ids] (or omit status)`);
236
239
  if (seenTitle.has(title)) return fail(`Duplicate phase title "${title}"`);
237
240
  seenTitle.add(title);
238
241
  const id = p.id?.trim() || autoId(i, taken);
@@ -255,6 +258,7 @@ export function applyTodo(current: readonly TodoPhase[], params: TodoParams): Ap
255
258
  const p = list[0];
256
259
  const title = p.title.trim();
257
260
  if (!title) return fail("Every phase needs a title");
261
+ if (p.status === "blocked") return fail(`"${title}": status "blocked" is derived from unmet blockedBy edges and is never stored — pass blockedBy: [ids] (or omit status)`);
258
262
  if (phases.some((x) => x.title === title)) return fail(`Phase "${title}" already exists`);
259
263
  const id = p.id?.trim() || autoId(phases.length, new Set(phases.map((x) => x.id)));
260
264
  if (byId.has(id)) return fail(`Phase id "${id}" already exists`);
@@ -110,6 +110,15 @@ describe("todo state machine", () => {
110
110
  assert.deepEqual(partial[1].blockedBy, ["p1"], "unblock drops only the named edge");
111
111
  });
112
112
 
113
+ it("init/append reject a stored status:\"blocked\" — blocked is derived from blockedBy", () => {
114
+ assert.match(fail([], { action: "init", phases: [{ title: "A", status: "blocked" }] })[0], /blockedBy/);
115
+ const seeded2 = run([], { action: "init", phases: [{ title: "A" }] });
116
+ assert.match(fail(seeded2, { action: "append", phases: [{ title: "B", status: "blocked" }] })[0], /blockedBy/);
117
+ // Normal flows unchanged: blocking goes through blockedBy edges.
118
+ const blocked = run(seeded(), { action: "block", id: "p1", blockedBy: ["p3"] });
119
+ assert.deepEqual(blocked[0].blockedBy, ["p3"]);
120
+ });
121
+
113
122
  it("append adds one phase with a fresh id and rejects duplicates", () => {
114
123
  const appended = run(seeded(), { action: "append", phases: [{ title: "Ship it" }] });
115
124
  assert.deepEqual(appended.map((p) => p.id), ["p1", "p2", "p3", "p4"]);
@@ -210,7 +210,7 @@ export default function piWebExtension(pi: ExtensionAPI) {
210
210
  _ctx: ctx,
211
211
  });
212
212
  const attempts = diagnostics.attempts.map((a) => `${a.backend}: ${a.status}${a.message ? ` (${a.message})` : ""}`).join("\n");
213
- const text = `${formatUnifiedSearchResults(diagnostics.results)}\n\n--- Search diagnostics ---\nSelected backend: ${diagnostics.selectedBackend}\n${attempts}`;
213
+ const text = `${formatUnifiedSearchResults(diagnostics.results)}\n\n--- Search diagnostics ---\nSelected backend: ${diagnostics.selectedBackend}\nRouter: ${diagnostics.router}\n${attempts}`;
214
214
  return { content: [{ type: "text" as const, text: truncateText(text) }], details: diagnostics };
215
215
  },
216
216
  });
@@ -15,7 +15,7 @@ import { readFileSync } from "node:fs";
15
15
  import path from "node:path";
16
16
  import { fileURLToPath } from "node:url";
17
17
 
18
- import { launchCdp, unwrapEvaluate, waitForLoad, type WsFactory } from "./cdp";
18
+ import { launchCdp, raceBounded, unwrapEvaluate, waitForLoad, type WsFactory } from "./cdp";
19
19
 
20
20
  // ── OMP shapes (browser/a11y/audit.ts) ─────────────────────────────────────
21
21
 
@@ -198,9 +198,11 @@ function runnerExpression(options: BrowserA11yOptions): string {
198
198
  const r = await window.axe.run(context, opts);
199
199
  return JSON.stringify({ __axeOk: r });
200
200
  } catch (err) {
201
- // Error inside the page: the CDP connection layer resolves responses to
202
- // msg.result only, so a top-level exceptionDetails never reaches
203
- // unwrapEvaluate — carry the failure through the value instead.
201
+ // Belt and braces: unwrapEvaluate already surfaces exceptionDetails loudly
202
+ // (the connection layer preserves them, including Runtime.evaluate's
203
+ // nested shape), so an in-page throw would reject the evaluate promise —
204
+ // the in-page try/catch just carries a friendlier message through the
205
+ // {__axeError} value instead.
204
206
  return JSON.stringify({ __axeError: err instanceof Error ? err.message : String(err) });
205
207
  }
206
208
  })()`;
@@ -216,26 +218,39 @@ export async function runA11yAudit(opts: RunA11yOpts): Promise<BrowserA11yResult
216
218
  const browser = await launchCdp({ wsFactory: opts.wsFactory });
217
219
  const onAbort = () => browser.cleanup();
218
220
  opts.signal?.addEventListener("abort", onAbort, { once: true });
221
+ // timeoutError matcher for the tests (and readable tool errors).
222
+ const auditTimeoutError = (ms: number) =>
223
+ `audit timed out after ${Math.round(ms / 1000)}s — page/renderer likely wedged`;
219
224
  let sessionId: string | undefined;
225
+ const bounded = <T>(p: Promise<T>): Promise<T> =>
226
+ raceBounded(p, timeoutMs, auditTimeoutError(timeoutMs));
220
227
  try {
221
228
  const connection = browser.connection;
222
- const target = await connection.send("Target.createTarget", { url: "about:blank" });
229
+ // The whole post-launch CDP phase is bounded: a wedged renderer (hung
230
+ // navigate/evaluate) must reject at the documented budget instead of
231
+ // parking web_a11y forever. finally below tears Chrome down either way.
232
+ const target = await bounded(connection.send("Target.createTarget", { url: "about:blank" }));
223
233
  const targetId = target.targetId as string;
224
- sessionId = ((await connection.send("Target.attachToTarget", { targetId, flatten: true })) as { sessionId: string })
225
- .sessionId;
234
+ sessionId = ((await bounded(
235
+ connection.send("Target.attachToTarget", { targetId, flatten: true }),
236
+ )) as { sessionId: string }).sessionId;
226
237
  const send = (method: string, params?: Record<string, unknown>) => connection.send(method, params, sessionId);
227
- await send("Page.enable");
238
+ await bounded(send("Page.enable"));
228
239
  const loaded = waitForLoad(connection, sessionId);
229
- await send("Page.navigate", { url: opts.url });
230
- await loaded;
240
+ await bounded(send("Page.navigate", { url: opts.url }));
241
+ await bounded(loaded);
231
242
  const evaluate = async (expression: string, awaitPromise = false) =>
232
- unwrapEvaluate(await send("Runtime.evaluate", { expression, awaitPromise, returnByValue: true }));
233
- // Bootstrap: the UMD build defines window.axe in the page world.
234
- evaluate(axeSource());
243
+ unwrapEvaluate(await bounded(send("Runtime.evaluate", { expression, awaitPromise, returnByValue: true })));
244
+ // Bootstrap: the UMD build defines window.axe in the page world. Awaited —
245
+ // CDP serializes commands so ordering holds, and a failed bootstrap must
246
+ // fail the audit loudly rather than escape as an unhandled rejection
247
+ // (which kills pi; see cdp.ts incident 2026-09-20). The runner's
248
+ // window.axe check remains as backup for a silently swallowed failure.
249
+ await evaluate(axeSource());
235
250
  // Runner: axe.run is async and huge — awaitPromise + returnByValue, and
236
251
  // stringified (JSON survives returnByValue losslessly). In-page failures
237
- // ride back as {__axeError} because the connection layer drops top-level
238
- // exceptionDetails (see runnerExpression).
252
+ // ride back as {__axeError}; CDP-level exceptions surface via
253
+ // unwrapEvaluate (exceptionDetails preserved — see runnerExpression).
239
254
  const raw = String(await evaluate(runnerExpression(opts), true));
240
255
  let parsed: { __axeOk?: unknown; __axeError?: string };
241
256
  try {
@@ -39,6 +39,8 @@ export interface CdpFrame {
39
39
  params?: Record<string, unknown>;
40
40
  result?: Record<string, unknown>;
41
41
  error?: { message: string; data?: string };
42
+ /** Sibling-of-result protocol error report (e.g. Runtime domains): kept so unwrapEvaluate can fail loudly. */
43
+ exceptionDetails?: { text?: string; exception?: { description?: string; value?: unknown } };
42
44
  sessionId?: string;
43
45
  }
44
46
 
@@ -108,6 +110,13 @@ export class CdpConnection {
108
110
  this.pending.delete(msg.id);
109
111
  if (msg.error) {
110
112
  p.reject(new Error(`${msg.error.message}${msg.error.data ? `: ${msg.error.data}` : ""}`));
113
+ } else if (msg.exceptionDetails) {
114
+ // Shape-compatible: keep the result payload and surface the SIBLING
115
+ // exceptionDetails so unwrapEvaluate can fail loudly. (The nested
116
+ // Runtime.evaluate shape — exceptionDetails inside msg.result — was
117
+ // already preserved by the plain branch; this covers domains that
118
+ // report it beside result.)
119
+ p.resolve({ ...(msg.result ?? {}), exceptionDetails: msg.exceptionDetails });
111
120
  } else {
112
121
  p.resolve(msg.result ?? {});
113
122
  }
@@ -347,9 +356,9 @@ function stepLabel(step: InteractStep): string {
347
356
  * Bound any CDP await: a wedged renderer (hung evaluate, dialog race) must
348
357
  * fail loudly instead of hanging the call. Used for steps AND the post-loop
349
358
  * probe/auto-screenshot — without it a step timeout would still hang forever
350
- * on the unbounded probe that follows.
359
+ * on the unbounded probe that follows. Also bounds web_a11y's whole audit.
351
360
  */
352
- function raceBounded<T>(p: Promise<T>, ms: number, timeoutError: string): Promise<T> {
361
+ export function raceBounded<T>(p: Promise<T>, ms: number, timeoutError: string): Promise<T> {
353
362
  let timer: ReturnType<typeof setTimeout> | undefined;
354
363
  const timeout = new Promise<T>((_, reject) => {
355
364
  timer = setTimeout(() => reject(new Error(timeoutError)), ms);