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
@@ -19,14 +19,8 @@ export function truncationMarker(bytes: number): string {
19
19
  return `[… ${bytes} bytes truncated …]`;
20
20
  }
21
21
 
22
- function trimPartialHead(lines: string[], total: number, keep: number): { lines: string[]; total: number } {
23
- let dropped = 0;
24
- while (lines.length > 0 && total - dropped > keep) {
25
- dropped += Buffer.byteLength(lines[0], "utf8") + 1;
26
- lines.shift();
27
- }
28
- return { lines, total: total - dropped };
29
- }
22
+ // ponytail: trimPartialHead deleted — the partial is now bounded in enforceCap
23
+ // itself (byte-aware clip), so a second head-trimmer has no job left.
30
24
 
31
25
  /**
32
26
  * Line-buffered ring for one output stream. `push` splits on \n and keeps the
@@ -52,6 +46,7 @@ export class RingBuffer {
52
46
  this.lifetimeLineCount += parts.length;
53
47
  this.totalBytes += Buffer.byteLength(chunk, "utf8");
54
48
  this.lifetimeBytes += Buffer.byteLength(chunk, "utf8");
49
+ // Cap check counts the partial too — newline-free output must be bounded.
55
50
  if (this.totalBytes > TOTAL_BYTES) this.enforceCap();
56
51
  }
57
52
 
@@ -59,13 +54,24 @@ export class RingBuffer {
59
54
  this.capped = true;
60
55
  const lineBytes = (ls: string[]) => ls.reduce((n, l) => n + Buffer.byteLength(l, "utf8") + 1, 0);
61
56
  const keepTail = TOTAL_BYTES - HEAD_KEEP_BYTES - Buffer.byteLength(truncationMarker(1), "utf8") - 1;
57
+ // Fold PREVIOUS markers into one: their claimed drops carry forward so a
58
+ // re-trip never stacks marker lines or loses the older drops' accounting.
59
+ let carriedDrops = 0;
60
+ const lines = this.linesArr.filter((l) => {
61
+ const m = /^\[… (\d+) bytes truncated …\]$/.exec(l);
62
+ if (m) {
63
+ carriedDrops += Number(m[1]);
64
+ return false;
65
+ }
66
+ return true;
67
+ });
62
68
  // Split the whole lines into HEAD (first bytes) + TAIL (last bytes),
63
69
  // dropping the middle; the first line of each side is taken even when it
64
70
  // alone busts its budget (one giant line must still be visible).
65
71
  let head: string[] = [];
66
72
  const tail: string[] = [];
67
73
  let tailBytes = 0;
68
- const rest = [...this.linesArr];
74
+ const rest = [...lines];
69
75
  while (rest.length > 0) {
70
76
  const l = rest[rest.length - 1]!;
71
77
  const b = Buffer.byteLength(l, "utf8") + 1;
@@ -83,10 +89,27 @@ export class RingBuffer {
83
89
  rest.shift();
84
90
  headBytes += b;
85
91
  }
86
- const droppedBytes = lineBytes(rest);
92
+ let droppedBytes = lineBytes(rest) + carriedDrops;
93
+ // The unterminated partial is bounded by its OWN TOTAL_BYTES cap, keeping
94
+ // the newest tail — newline-free output (minified JSON, `yes`) must not
95
+ // grow memory unbounded. (Clipping against the lines' leftover budget
96
+ // would zero a small spinner after one giant line.) Bytes dropped from
97
+ // the partial's head count into droppedBytes so the marker stays truthful.
98
+ let partial = this.partial;
99
+ const partialBytes = Buffer.byteLength(partial, "utf8");
100
+ if (partialBytes > TOTAL_BYTES) {
101
+ // Byte-aware clip of the newest tail (multi-byte chars snap forward).
102
+ const buf = Buffer.from(partial, "utf8");
103
+ let start = buf.length - TOTAL_BYTES;
104
+ while (start < buf.length && start > 0 && (buf[start]! & 0xc0) === 0x80) start++;
105
+ droppedBytes += start;
106
+ partial = buf.subarray(start).toString("utf8");
107
+ }
87
108
  this.linesArr = [...head, truncationMarker(Math.max(droppedBytes, 1)), ...tail];
88
109
  this.tailStart = head.length + 1;
89
- this.totalBytes = lineBytes(this.linesArr);
110
+ this.partial = partial;
111
+ // Recompute counts the partial: the next push's cap check sees it.
112
+ this.totalBytes = lineBytes(this.linesArr) + Buffer.byteLength(this.partial, "utf8");
90
113
  }
91
114
 
92
115
  /** Everything visible so far: complete lines plus the unterminated tail. */
@@ -220,7 +243,9 @@ const EXIT_WAIT_MS = 2_000;
220
243
  export class SessionStore {
221
244
  private map = new Map<string, ShellSession>();
222
245
 
223
- /** Register a session. Throws (listing live sessions) when 10 are already LIVE. */
246
+ /** Register a session. Throws (listing live sessions) when 10 are already LIVE.
247
+ * Also evicts exited sessions beyond the keep count — the kill-action call
248
+ * alone let naturally-exited sessions accumulate forever (2 rings each). */
224
249
  add(session: ShellSession): void {
225
250
  const live = this.list().filter((s) => s.exitedAt === undefined);
226
251
  if (live.length >= MAX_LIVE_SESSIONS && session.exitedAt === undefined) {
@@ -230,6 +255,9 @@ export class SessionStore {
230
255
  );
231
256
  }
232
257
  this.map.set(session.id, session);
258
+ // Registration is the enforcement point (F9): every start passes through
259
+ // here, so the exited cap holds even when nothing ever kills explicitly.
260
+ while (this.evictOldestExited());
233
261
  }
234
262
 
235
263
  get(id: string): ShellSession | undefined {
@@ -93,6 +93,44 @@ describe("RingBuffer", () => {
93
93
  assert.equal(rb.isTruncated(), true);
94
94
  assert.match(rb.lines().at(-1)!, /^spinner…/);
95
95
  });
96
+
97
+ it("F8: bounds a newline-free flood — partial capped, lifetime and marker truthful", () => {
98
+ const rb = new RingBuffer();
99
+ const CHUNK = "x".repeat(1024 * 1024); // 1MB, no newline
100
+ for (let i = 0; i < 10; i++) rb.push(CHUNK);
101
+ // Memory is bounded: the partial alone stays within the cap (+ grace for
102
+ // the head/marker lines the split keeps).
103
+ const partialBytes = Buffer.byteLength(rb.peekPartial(), "utf8");
104
+ assert.ok(partialBytes <= TOTAL_BYTES, `partial ${partialBytes}B must be ≤ TOTAL_BYTES`);
105
+ // The newest tail survived, not the head.
106
+ assert.ok(rb.peekPartial().endsWith("x"));
107
+ assert.ok(rb.peekPartial().length > 0);
108
+ // Lifetime accounting is pre-truncation truth: ~10MB written.
109
+ assert.ok(Math.abs(rb.totalWritten() - 10 * 1024 * 1024) < 4096);
110
+ assert.equal(rb.isTruncated(), true);
111
+ // The marker reports the REAL dropped byte count (unpatched: "1 bytes").
112
+ const marker = rb.lines().find((l) => l.startsWith("[…"));
113
+ assert.ok(marker, "has a truncation marker");
114
+ const dropped = Number(/\[… (\d+) bytes truncated …\]/.exec(marker!)?.[1]);
115
+ // Cumulative truth: 10MB in, ≤TOTAL_BYTES (partial) + head kept → dropped
116
+ // ≈ 10MB − 262144 − grace; the unpatched marker degenerated to "1 bytes".
117
+ assert.ok(dropped >= 9 * 1024 * 1024, `marker reports real dropped bytes, got ${dropped}`);
118
+ // Exactly ONE marker — repeated cap trips fold, never stack.
119
+ assert.equal(rb.lines().filter((l) => l.startsWith("[…")).length, 1);
120
+ });
121
+
122
+ it("F8: a newline-free flood clips to the newest tail (byte-aware, multibyte snapped)", () => {
123
+ const rb = new RingBuffer();
124
+ // One chunk far over the cap; the clip window is the NEWEST TOTAL_BYTES.
125
+ const chunk = "a".repeat(TOTAL_BYTES + 50_000) + "é".repeat(1000);
126
+ rb.push(chunk);
127
+ const partial = rb.peekPartial();
128
+ assert.ok(Buffer.byteLength(partial, "utf8") <= TOTAL_BYTES);
129
+ assert.ok(partial.endsWith("é".repeat(1000)), "newest tail kept intact");
130
+ // The clipped window starts exactly 262144 bytes (UTF-8) before the end.
131
+ const expectedStart = chunk.length - (262_144 - 2000); // é is 2 bytes each
132
+ assert.ok(partial.startsWith(chunk.slice(expectedStart - 2, expectedStart)), "clip is byte-aware");
133
+ });
96
134
  });
97
135
 
98
136
  // ── ids + resolution ────────────────────────────────────────────────────────
@@ -192,9 +230,29 @@ describe("SessionStore", () => {
192
230
  for (let i = 0; i < 7; i++) store.add(live({ id: `d${i}`, exitedAt: 1_000 + i, exitCode: 0 }));
193
231
  let evicted = 0;
194
232
  while (store.evictOldestExited()) evicted++;
195
- assert.equal(evicted, 2);
233
+ assert.equal(evicted, 0); // F9: registration already enforced the cap
196
234
  assert.equal(store.list().length, 5);
197
- assert.equal(store.list()[0]!.id, "d2"); // oldest two gone
235
+ assert.equal(store.list()[0]!.id, "d2"); // oldest two gone at add time
236
+ });
237
+
238
+ it("F9: the exited cap is enforced at registration — a 6th naturally-exited session evicts the oldest", () => {
239
+ const store = new SessionStore();
240
+ // 5 exited registered, then two more sessions EXIT NATURALLY after
241
+ // registration (the unpatched path — evictOldestExited was kill-only).
242
+ for (let i = 0; i < 5; i++) store.add(live({ id: `x${i}`, exitedAt: 1_000 + i, exitCode: 0 }));
243
+ const sixth = live({ id: "x5", exitedAt: 1_005, exitCode: 0 });
244
+ store.add(live({ id: "x5" })); // register live (cap counts it)
245
+ (store.get("x5") as ShellSession).exitedAt = 1_005; // natural exit
246
+ const seventh = live({ id: "x6" });
247
+ store.add(seventh);
248
+ (store.get("x6") as ShellSession).exitedAt = 1_006;
249
+ const eighth = live({ id: "x7" });
250
+ store.add(eighth); // 7 exited → evicts down to 5 at registration
251
+ (store.get("x7") as ShellSession).exitedAt = 1_007;
252
+ store.add(live({ id: "x8" })); // 6 exited again → oldest evicted NOW
253
+ assert.equal(store.list().filter((s) => s.exitedAt !== undefined).length <= 5, true);
254
+ assert.ok(store.get("x7"), "newest survived");
255
+ assert.equal(store.get("x0"), undefined, "oldest evicted");
198
256
  });
199
257
 
200
258
  it("clear drops every session", () => {
@@ -47,6 +47,7 @@
47
47
  // reasoning-truncation budget is a function argument.
48
48
 
49
49
  import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
50
+ import { isPlanActive } from "../../lib/plan-bridge.ts";
50
51
  import { detectFamily, type ModelFamily } from "./lib/family.js";
51
52
  import {
52
53
  applyPatchPreferenceGuidance,
@@ -199,6 +200,13 @@ export default function steeringModule(pi: ExtensionAPI): void {
199
200
  // a live a2a gateway session. anchorReady is display-only here.
200
201
  const target = anchorTarget(model);
201
202
  if (target && !anchorReady) anchorReady = true;
203
+ // Plan mode hard-blocks the mutator tools (str_replace_editor is in
204
+ // plan's BLOCKED_TOOLS), so the DSH pair can never reach the payload.
205
+ // Defer — not fail-open — so the session stays anchorable and the
206
+ // fail-open warning never fires: plan-mode replies promote naturally via
207
+ // the entries scan, and with no replies the bootstrap engages on the
208
+ // first post-exit turn (permission-module precedent: plan-bridge).
209
+ if (isPlanActive()) return false;
202
210
  return target && !anchorPromoted;
203
211
  }
204
212
 
@@ -209,6 +217,7 @@ export default function steeringModule(pi: ExtensionAPI): void {
209
217
  const anchorActive = anchorTarget(cmdCtx.model); // includes sessionModel fallback
210
218
  const anchorState = !anchorActive || !anchorReady
211
219
  ? "off"
220
+ : isPlanActive() && !anchorPromoted ? "deferred (plan mode)"
212
221
  : anchorPromoted ? "promoted" : "bootstrapping";
213
222
  const totalErrors = [...errorHistory.values()].reduce((sum, e) => sum + e.count, 0);
214
223
  const status = [
@@ -349,7 +358,9 @@ export default function steeringModule(pi: ExtensionAPI): void {
349
358
  // normal path: full prompt + full catalog.
350
359
  anchorTracePush("bootstrap skipped: durable signal found (resume)");
351
360
  } else if (anchorTarget(ctx.model)) {
352
- anchorTracePush(`bootstrap skipped: already promoted=${anchorPromoted}`);
361
+ anchorTracePush(isPlanActive() && !anchorPromoted
362
+ ? "bootstrap deferred: plan mode active (mutator tools blocked)"
363
+ : `bootstrap skipped: already promoted=${anchorPromoted}`);
353
364
  }
354
365
 
355
366
  remindedThisTurn = false;
@@ -0,0 +1,73 @@
1
+ // ds-anchor × plan mode: the bootstrap DEFERS while plan mode is active.
2
+ // Plan mode strips the mutator tools (str_replace_editor is in plan's
3
+ // BLOCKED_TOOLS), so the DSH pair can never reach the payload — previously
4
+ // the anchor fail-opened PERMANENTLY there: warning + anchorPromoted latch +
5
+ // request #1 shipped with the minimal persona and NO plan-mode contract.
6
+ // Deferral keeps the session anchorable and the warning silent.
7
+
8
+ import assert from "node:assert";
9
+ import { after, before, describe, it } from "node:test";
10
+ import { createFakePi, isolateAgentDir } from "./harness.js";
11
+ import { setPlanActive } from "../../../lib/plan-bridge.ts";
12
+
13
+ const MINIMAL = "You are a helpful software engineer assistant.";
14
+ const PRO = "deepseek-v4-pro";
15
+ // Plan-mode-shaped catalog: reads + plan tools, NO mutator pair.
16
+ const PLAN_TOOLS = ["read", "bash", "grep", "find", "ls", "write_plan", "ask_user_question"];
17
+
18
+ describe("ds-anchor × plan mode", () => {
19
+ let restoreAgentDir: () => void;
20
+ before(() => { restoreAgentDir = isolateAgentDir("ceulen-steering-plan-").restore; });
21
+ after(() => { setPlanActive(false); restoreAgentDir(); });
22
+
23
+ it("defers while plan mode is active: no minimal prompt, no tool filter, no fail-open warning", () => {
24
+ setPlanActive(true);
25
+ const h = createFakePi(PLAN_TOOLS);
26
+ h.setEntries([]);
27
+ h.fire("session_start", {}, h.ctx(PRO));
28
+
29
+ const r = h.fire("before_agent_start", { prompt: "plan it", systemPrompt: "FULL PI PROMPT", systemPromptOptions: {} }, h.ctx(PRO));
30
+ assert.notEqual(r?.systemPrompt, MINIMAL, "no minimal prompt while planning");
31
+ assert.ok(r?.systemPrompt === undefined || r.systemPrompt.includes("FULL PI PROMPT"), "composed prompt preserved (plan contract survives)");
32
+
33
+ // The payload that triggered the live bug: plan-filtered catalog without str_replace_editor.
34
+ const out = h.fire("before_provider_request", { payload: { tools: PLAN_TOOLS.map((name) => ({ name })) } }, h.ctx(PRO));
35
+ assert.equal(out?.tools, undefined, "no tool substitution while planning");
36
+ assert.equal(out?.max_tokens, undefined, "no budget pin while planning");
37
+ assert.equal(h.notifications.length, 0, "no fail-open warning");
38
+ });
39
+
40
+ it("bootstrap engages on the first post-exit turn when no assistant reply landed", () => {
41
+ setPlanActive(true);
42
+ const h = createFakePi(PLAN_TOOLS);
43
+ h.setEntries([]);
44
+ h.fire("session_start", {}, h.ctx(PRO));
45
+ h.fire("before_agent_start", { prompt: "plan it", systemPrompt: "FULL PI PROMPT", systemPromptOptions: {} }, h.ctx(PRO));
46
+ h.fire("before_provider_request", { payload: { tools: PLAN_TOOLS.map((name) => ({ name })) } }, h.ctx(PRO));
47
+ assert.equal(h.notifications.length, 0, "still no warning after exit");
48
+
49
+ setPlanActive(false);
50
+ const r2 = h.fire("before_agent_start", { prompt: "now do it", systemPrompt: "FULL PI PROMPT", systemPromptOptions: {} }, h.ctx(PRO));
51
+ assert.equal(r2?.systemPrompt, MINIMAL, "plan exit with no durable reply → bootstrap fires");
52
+ });
53
+
54
+ it("plan-mode assistant replies promote naturally (no post-exit re-anchor)", () => {
55
+ setPlanActive(true);
56
+ const h = createFakePi(PLAN_TOOLS);
57
+ h.setEntries([]);
58
+ h.fire("session_start", {}, h.ctx(PRO));
59
+ h.setEntries([{ type: "message", message: { role: "assistant", content: [{ type: "text" }] } }]);
60
+
61
+ setPlanActive(false);
62
+ const r = h.fire("before_agent_start", { prompt: "execute", systemPrompt: "FULL PI PROMPT", systemPromptOptions: {} }, h.ctx(PRO));
63
+ assert.notEqual(r?.systemPrompt, MINIMAL, "history diverged from DSH distribution — no re-anchor");
64
+ });
65
+
66
+ it("/steering status discloses the deferral", () => {
67
+ setPlanActive(true);
68
+ const h = createFakePi(PLAN_TOOLS);
69
+ h.setEntries([]);
70
+ h.fire("session_start", {}, h.ctx(PRO));
71
+ assert.ok(h.status(h.ctx(PRO)).includes("deferred (plan mode)"));
72
+ });
73
+ });
@@ -42,6 +42,7 @@ import {
42
42
  getResultOutput,
43
43
  isFailedResult,
44
44
  mapWithConcurrencyLimit,
45
+ OWNER_SUFFIX,
45
46
  pidAlive,
46
47
  runSubAgent,
47
48
  startHeartbeat,
@@ -108,6 +109,7 @@ import {
108
109
  MAX_HERDR_TASK_BYTES,
109
110
  MAX_REPORT_BYTES,
110
111
  prepareHerdrTask,
112
+ captureEvidenceStamp,
111
113
  promptAndWait,
112
114
  resolveEffectiveRunner,
113
115
  truncateHerdrTask,
@@ -421,7 +423,7 @@ export default function (pi: ExtensionAPI) {
421
423
  const ownerLabel = async (): Promise<string> => {
422
424
  const base = path.join(path.resolve(ctx.cwd), WORKTREE_DIR_NAME);
423
425
  let entries: string[] = [];
424
- try { entries = (await fs.readdir(base)).filter((e) => e !== ".gitignore"); } catch { return "No worktree sandboxes."; }
426
+ try { entries = (await fs.readdir(base)).filter((e) => e !== ".gitignore" && !e.endsWith(OWNER_SUFFIX)); } catch { return "No worktree sandboxes."; }
425
427
  if (entries.length === 0) return "No worktree sandboxes.";
426
428
  const lines = await Promise.all(entries.map(async (entry) => {
427
429
  let owner: WorktreeOwner | undefined;
@@ -434,7 +436,7 @@ export default function (pi: ExtensionAPI) {
434
436
  return `Worktree sandboxes (${entries.length}):
435
437
  ${lines.join("\n")}`;
436
438
  };
437
- const result = force ? await sweepStaleWorktrees(ctx.cwd) : null;
439
+ const result = force ? await sweepStaleWorktrees(ctx.cwd, undefined, { force: true }) : null;
438
440
  const listing = await ownerLabel();
439
441
  const sweepLine = result ? `\n\nSwept ${result.removed.length} stale sandbox(es): ${result.removed.map((r) => path.basename(r)).join(", ") || "none"}.` : "\n\n(/subagent worktrees clean to sweep stale entries)";
440
442
  pi.sendMessage({ customType: "ceulen-subagent", content: `${listing}${sweepLine}`, display: true });
@@ -2156,6 +2158,8 @@ ${lines.join("\n")}`;
2156
2158
  const fileStampBefore = entry
2157
2159
  ? await fs.stat(entry.resultFile).then((s) => `${s.size}:${s.mtimeMs}`).catch(() => "")
2158
2160
  : "";
2161
+ // Stalled-turn recovery evidence (same baseline as the runner path).
2162
+ const stamp = entry ? await captureEvidenceStamp(entry, name, herdrCli.exec) : undefined;
2159
2163
  // Abortable: an aborted tool call interrupts the wait (esc to the
2160
2164
  // child) instead of blocking until the CLI timeout.
2161
2165
  const outcome = await new Promise<PromptOutcome>((resolve) => {
@@ -2168,7 +2172,19 @@ ${lines.join("\n")}`;
2168
2172
  resolve({ state: "unknown", delivered: false, error: "aborted: tool call cancelled" });
2169
2173
  };
2170
2174
  _signal?.addEventListener("abort", onAbort, { once: true });
2171
- promptAndWait({ name, text, timeoutMs, exec: herdrCli.exec }).then((o) => {
2175
+ promptAndWait({
2176
+ name,
2177
+ text,
2178
+ timeoutMs,
2179
+ exec: herdrCli.exec,
2180
+ evidence: entry
2181
+ ? {
2182
+ resultFile: entry.resultFile,
2183
+ readOnly: entry.readOnly,
2184
+ stamp: stamp!,
2185
+ }
2186
+ : undefined,
2187
+ }).then((o) => {
2172
2188
  if (settled) return;
2173
2189
  settled = true;
2174
2190
  _signal?.removeEventListener("abort", onAbort);
@@ -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";