ceulen 0.15.2 → 0.17.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.
Files changed (57) hide show
  1. package/CHANGELOG.md +69 -0
  2. package/README.md +1 -1
  3. package/extensions/lib/registry.test.ts +5 -2
  4. package/extensions/lib/registry.ts +9 -3
  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 +7 -3
  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 +93 -6
  13. package/extensions/modules/munin/test/extension.test.ts +124 -0
  14. package/extensions/modules/plan/index.ts +116 -4
  15. package/extensions/modules/plan/lib/settings.ts +5 -7
  16. package/extensions/modules/plan/test/module.test.ts +104 -1
  17. package/extensions/modules/plan/test/settings.test.ts +7 -0
  18. package/extensions/modules/repair/configPanel.ts +3 -1
  19. package/extensions/modules/repair/index.ts +21 -16
  20. package/extensions/modules/repair/lib/read-sqlite.ts +18 -7
  21. package/extensions/modules/repair/test/freshness.test.ts +30 -0
  22. package/extensions/modules/repair/test/hardening.test.ts +46 -1
  23. package/extensions/modules/repair/test/readers.test.ts +11 -5
  24. package/extensions/modules/repair/test/settings.test.ts +7 -2
  25. package/extensions/modules/rtk/configPanel.ts +67 -0
  26. package/extensions/modules/rtk/index.ts +76 -9
  27. package/extensions/modules/rtk/lib/settings.ts +65 -0
  28. package/extensions/modules/rtk/test/configPanel.test.ts +72 -0
  29. package/extensions/modules/rtk/test/index.test.js +120 -2
  30. package/extensions/modules/rules/index.ts +4 -1
  31. package/extensions/modules/rules/lib/rules.ts +6 -3
  32. package/extensions/modules/rules/test/lib.test.ts +24 -0
  33. package/extensions/modules/rules/test/module.test.ts +29 -0
  34. package/extensions/modules/shells/lib/sessions.ts +40 -12
  35. package/extensions/modules/shells/test/sessions.test.ts +60 -2
  36. package/extensions/modules/steering/index.ts +12 -1
  37. package/extensions/modules/steering/test/anchor-plan.test.ts +73 -0
  38. package/extensions/modules/subagent/index.ts +19 -3
  39. package/extensions/modules/subagent/lib/herdr.ts +141 -1
  40. package/extensions/modules/subagent/lib/runner.ts +88 -22
  41. package/extensions/modules/subagent/test/herdr-stalled.test.ts +117 -0
  42. package/extensions/modules/subagent/test/worktree.test.ts +156 -1
  43. package/extensions/modules/todo/index.ts +4 -0
  44. package/extensions/modules/todo/test/todo.test.ts +9 -0
  45. package/extensions/modules/web/index.ts +1 -1
  46. package/extensions/modules/web/lib/a11y.ts +30 -15
  47. package/extensions/modules/web/lib/cdp.ts +11 -2
  48. package/extensions/modules/web/lib/chrome.ts +12 -3
  49. package/extensions/modules/web/lib/content.ts +32 -9
  50. package/extensions/modules/web/lib/search.ts +111 -3
  51. package/extensions/modules/web/test/a11y.test.ts +100 -2
  52. package/extensions/modules/web/test/cdp.test.ts +48 -0
  53. package/extensions/modules/web/test/chrome.test.ts +32 -0
  54. package/extensions/modules/web/test/content.test.ts +92 -0
  55. package/extensions/modules/web/test/search.test.ts +75 -0
  56. package/package.json +1 -1
  57. package/skills/munin/SKILL.md +1 -1
@@ -42,6 +42,93 @@ export const herdrCli: { exec: HerdrExec } = { exec: defaultExec };
42
42
  export const HERDR_OFF_ENV = "PI_SUBAGENT_HERDR";
43
43
 
44
44
  const HERDR_NAME_RE = /^[a-z][a-z0-9_-]{0,31}$/;
45
+ /**
46
+ * Grace window after herdr's `agent_prompt_stalled` (its built-in allowance is
47
+ * a hard 5000ms): how long we additionally wait for OUTPUT evidence before
48
+ * declaring the dispatch dead. Covers cold-model first-token latency.
49
+ */
50
+ const STALLED_GRACE_MS = 30_000;
51
+
52
+ /** Pre-submission snapshot used as the baseline for stalled-turn recovery. */
53
+ export interface OutputEvidenceStamp {
54
+ /** `${size}:${mtimeMs}` of the report file ("" when absent) — same format the herdr tool's follow-up compare uses. */
55
+ fileStamp: string;
56
+ /** Read-only children only: pane tail before submission (inline replies are the only evidence channel). */
57
+ paneTail?: string;
58
+ }
59
+
60
+ /**
61
+ * herdr 0.9.3's status watcher never observes `working` for pi panes —
62
+ * `state_change_seq` stays frozen across live turns (live-probed 2026-10-10) —
63
+ * so `agent prompt --wait` stalls on dispatches that run fine and `agent
64
+ * wait --until working` never fires. State polling proves nothing; the only
65
+ * trustworthy completion evidence is OUTPUT. Capture the pre-submission
66
+ * baseline: report-file stamp (+ pane tail for read-only children).
67
+ */
68
+ export async function captureEvidenceStamp(
69
+ handle: { resultFile: string; readOnly?: boolean },
70
+ name: string,
71
+ exec: HerdrExec,
72
+ ): Promise<OutputEvidenceStamp> {
73
+ const fileStamp = await fs.stat(handle.resultFile).then((s) => `${s.size}:${s.mtimeMs}`).catch(() => "");
74
+ let paneTail: string | undefined;
75
+ if (handle.readOnly) {
76
+ const read = await exec("herdr", ["agent", "read", name, "--source", "recent-unwrapped", "--lines", "40"], { timeout: 10_000 });
77
+ paneTail = read.code === 0 ? read.stdout : "";
78
+ }
79
+ return { fileStamp, paneTail };
80
+ }
81
+
82
+ /**
83
+ * Wait for output evidence that the stalled turn is (or already was) running:
84
+ * the report file's stamp changing (delivery contract), or — read-only
85
+ * children — the pane tail changing and then staying quiet. Returns true when
86
+ * evidence settled; false on deadline (genuinely silent pane).
87
+ */
88
+ async function waitForOutputEvidence(opts: {
89
+ name: string;
90
+ resultFile: string;
91
+ readOnly?: boolean;
92
+ stamp: OutputEvidenceStamp;
93
+ deadlineMs: number;
94
+ pollMs?: number;
95
+ signal?: AbortSignal;
96
+ exec: HerdrExec;
97
+ }): Promise<boolean> {
98
+ const pollMs = opts.pollMs ?? 1_000;
99
+ const deadline = Date.now() + opts.deadlineMs;
100
+ const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));
101
+ const fileStampNow = () =>
102
+ fs.stat(opts.resultFile).then((s) => `${s.size}:${s.mtimeMs}`).catch(() => "");
103
+ const readTail = async () => {
104
+ const read = await opts.exec("herdr", ["agent", "read", opts.name, "--source", "recent-unwrapped", "--lines", "40"], { timeout: 10_000 });
105
+ return read.code === 0 ? read.stdout : "";
106
+ };
107
+ let stableCount = 0;
108
+ let lastTail = "";
109
+ for (;;) {
110
+ if (opts.signal?.aborted) return false;
111
+ if (!opts.readOnly) {
112
+ const stamp = await fileStampNow();
113
+ // A changed stamp means the child (re)wrote its report — settled.
114
+ // "" → exists is the fast-child case (wrote before the stall fired).
115
+ if (stamp && stamp !== opts.stamp.fileStamp) return true;
116
+ } else {
117
+ const tail = await readTail();
118
+ if (tail !== opts.stamp.paneTail) {
119
+ // Changed from the baseline: require quiescence (3 identical polls)
120
+ // so a mid-stream snapshot is not collected as the final reply.
121
+ if (tail === lastTail) stableCount++;
122
+ else { stableCount = 1; lastTail = tail; }
123
+ if (stableCount >= 3) return true;
124
+ } else {
125
+ stableCount = 0;
126
+ }
127
+ }
128
+ if (Date.now() >= deadline) return false;
129
+ await sleep(pollMs);
130
+ }
131
+ }
45
132
  /** Reject herdr tasks above this size — the prompt travels as a CLI argv element. */
46
133
  export const MAX_HERDR_TASK_BYTES = 64 * 1024;
47
134
  /**
@@ -565,6 +652,18 @@ export async function promptAndWait(opts: {
565
652
  text: string;
566
653
  timeoutMs: number;
567
654
  exec: HerdrExec;
655
+ /** Output-evidence baseline + channels for stalled-turn recovery. Without
656
+ * it a stall is a hard failure (CLI-faithful behaviour). With it, the
657
+ * evidence wait spans the remaining dispatch budget — a long task is not
658
+ * a stalled task — and exhaustion reports TIMEOUT (the caller then
659
+ * interrupts the pane), never a phantom stall. */
660
+ evidence?: {
661
+ resultFile: string;
662
+ readOnly?: boolean;
663
+ stamp: OutputEvidenceStamp;
664
+ graceMs?: number;
665
+ signal?: AbortSignal;
666
+ };
568
667
  }): Promise<PromptOutcome> {
569
668
  const res = await opts.exec(
570
669
  "herdr",
@@ -580,7 +679,37 @@ export async function promptAndWait(opts: {
580
679
  return { state: "unknown", delivered: true, error: `timeout after ${opts.timeoutMs}ms` };
581
680
  }
582
681
  if (/stalled/i.test(errText)) {
583
- return { state: "unknown", delivered: false, error: "agent_prompt_stalled: no agent activity observed after submission" };
682
+ // herdr's --wait requires an observed working/blocked state within
683
+ // 5000ms — but its status watcher NEVER reports `working` for pi panes
684
+ // (state_change_seq frozen across live turns, live probe 2026-10-10), so
685
+ // the stall fires on healthy dispatches and no state probe can recover
686
+ // it. The only trustworthy completion evidence is OUTPUT: a changed
687
+ // report-file stamp (delivery contract) or a changed-then-quiet pane
688
+ // tail (read-only inline replies). Without evidence channels, the
689
+ // stall stays a hard failure.
690
+ if (opts.evidence) {
691
+ const settled = await waitForOutputEvidence({
692
+ name: opts.name,
693
+ resultFile: opts.evidence.resultFile,
694
+ readOnly: opts.evidence.readOnly,
695
+ stamp: opts.evidence.stamp,
696
+ // The CLI consumed ~5s observing its stall window; the evidence
697
+ // wait gets the full dispatch budget (floored at the grace minimum
698
+ // so very short timeouts still get a fair window).
699
+ deadlineMs: opts.evidence.graceMs ?? Math.max(STALLED_GRACE_MS, opts.timeoutMs),
700
+ signal: opts.evidence.signal,
701
+ exec: opts.exec,
702
+ });
703
+ if (settled) {
704
+ return { state: await getAgentState(opts.name, opts.exec), delivered: true };
705
+ }
706
+ // Evidence window exhausted with the full budget spent: report
707
+ // timeout semantics (executeHerdrTask's timedOut branch interrupts
708
+ // the child and discloses the maybe-late write) — the dispatch was
709
+ // delivered and may STILL complete, so never a hard stall here.
710
+ return { state: "unknown", delivered: true, error: `timeout after ${opts.timeoutMs}ms (no output evidence — likely still working or blocked in its pane)` };
711
+ }
712
+ return { state: "unknown", delivered: false, error: "agent_prompt_stalled: no output evidence within the grace window — check the pane (a dialog can also look silent), then prompt again" };
584
713
  }
585
714
  // Unexpected error — still report the last known state.
586
715
  const state = await getAgentState(opts.name, opts.exec);
@@ -964,6 +1093,11 @@ export async function executeHerdrTask(
964
1093
  try {
965
1094
  pollTimer = setInterval(() => { void poll(); }, 2_000);
966
1095
  pollTimer.unref?.();
1096
+ // Pre-submission output baseline: herdr's stall fires on healthy pi
1097
+ // dispatches (its watcher never reports `working`), so recovery waits on
1098
+ // evidence, not state. Snapshot BEFORE the prompt so any change proves
1099
+ // the turn produced output.
1100
+ const stamp = await captureEvidenceStamp(handle, handle.name, exec);
967
1101
  // A pre-aborted dispatch must not submit the task to the live child at
968
1102
  // all (mirrors the SDK path's early return on an aborted signal).
969
1103
  const prompt = opts.signal?.aborted
@@ -973,6 +1107,12 @@ export async function executeHerdrTask(
973
1107
  text: wrapTaskPrompt(handle.task, handle.resultFile, handle.readOnly),
974
1108
  timeoutMs: handle.timeoutMs,
975
1109
  exec,
1110
+ evidence: {
1111
+ resultFile: handle.resultFile,
1112
+ readOnly: handle.readOnly,
1113
+ stamp,
1114
+ signal: opts.signal,
1115
+ },
976
1116
  });
977
1117
  let output = "";
978
1118
  let outputSource: "file" | "pane" | "none" = "none";
@@ -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`);