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
@@ -1,5 +1,8 @@
1
1
  import assert from "node:assert/strict";
2
2
  import test from "node:test";
3
+ import { mkdtempSync, rmSync } from "node:fs";
4
+ import { tmpdir } from "node:os";
5
+ import { join } from "node:path";
3
6
 
4
7
  // Orchestration tests for index.ts: availability gating, env bypass, and the
5
8
  // safe-rewrite decision on the tool_call path, via a stubbed pi + ctx.
@@ -7,6 +10,18 @@ import test from "node:test";
7
10
  // tests in this file — tests are ordered to lean on it, and session_start
8
11
  // (which re-checks unconditionally) re-establishes availability where needed.
9
12
 
13
+ // Isolate the agent dir for the WHOLE file: readRtkSettings reads the global
14
+ // `rtk` section per bash call, and a host settings.json with `chained: "never"`
15
+ // would silently disable every chain rewrite under test.
16
+ const HOST_AGENT_DIR = process.env.PI_CODING_AGENT_DIR;
17
+ const TEMP_AGENT_DIR = mkdtempSync(join(tmpdir(), "ceulen-rtk-index-"));
18
+ process.env.PI_CODING_AGENT_DIR = TEMP_AGENT_DIR;
19
+ test.after(() => {
20
+ if (HOST_AGENT_DIR === undefined) delete process.env.PI_CODING_AGENT_DIR;
21
+ else process.env.PI_CODING_AGENT_DIR = HOST_AGENT_DIR;
22
+ rmSync(TEMP_AGENT_DIR, { recursive: true, force: true });
23
+ });
24
+
10
25
  function createHarness() {
11
26
  const state = { versionCalls: 0, rewriteCalls: 0, rewritten: null, versionAvailable: false };
12
27
  const handlers = {};
@@ -121,11 +136,114 @@ test("before_agent_start: prompt note injected only when rtk is available", asyn
121
136
  const resOff = await off.handlers.before_agent_start({ systemPrompt: "BASE" });
122
137
  assert.equal(resOff, undefined, "no systemPrompt modification when unavailable");
123
138
 
124
- // Available → the note is appended truthfully.
139
+ // Available → the static note is appended truthfully.
125
140
  const on = createHarness();
126
141
  on.state.versionAvailable = true;
127
142
  ext(on.pi);
128
143
  await on.handlers.session_start({}, on.ctx);
129
144
  const resOn = await on.handlers.before_agent_start({ systemPrompt: "BASE" });
130
- assert.match(resOn.systemPrompt, /transparently rewritten through RTK/);
145
+ assert.match(resOn.systemPrompt, /rewritten through RTK where RTK supports them/);
146
+ assert.match(resOn.systemPrompt, /chains, redirects, inline scripts, and unsupported commands pass through unchanged/);
147
+
148
+ // Static-policy note: byte-identical across two firings (prefix-cache head).
149
+ const resOn2 = await on.handlers.before_agent_start({ systemPrompt: "BASE" });
150
+ assert.equal(resOn2.systemPrompt, resOn.systemPrompt);
151
+ assert.equal(
152
+ resOn.systemPrompt.slice("BASE".length),
153
+ "\n\nYour bash commands are rewritten through RTK where RTK supports them (git, ls, rg, read, test runners as single commands); chains, redirects, inline scripts, and unsupported commands pass through unchanged.",
154
+ );
155
+ });
156
+
157
+ test("chain pass-through fires the [pi-rtk] notify once for two consecutive identical chains", async () => {
158
+ const notifications = [];
159
+ const h = createHarness();
160
+ h.state.versionAvailable = true;
161
+ h.state.rewritten = ""; // rtk consulted, returns empty = unmodeled → pass-through
162
+ h.ctx.hasUI = true;
163
+ h.ctx.ui.notify = (message) => notifications.push(message);
164
+ const ext = (await import("../index.ts")).default;
165
+ ext(h.pi);
166
+
167
+ await h.handlers.session_start({}, h.ctx);
168
+ const chain = "npm test 2>&1 | tail -8";
169
+ const afterFirst = await fireToolCall(h, chain);
170
+ assert.equal(afterFirst, chain, "unmodeled chain executes unchanged");
171
+ const afterSecond = await fireToolCall(h, chain);
172
+ assert.equal(afterSecond, chain);
173
+ const passNotes = notifications.filter((n) => n.startsWith("[pi-rtk] passed through unchanged:"));
174
+ assert.equal(passNotes.length, 1, `dedupe: one notify for two identical chains, got ${passNotes.length}`);
175
+
176
+ // A different chain notifies again.
177
+ await fireToolCall(h, "npx tsc --noEmit 2>&1 | head -20");
178
+ assert.equal(notifications.filter((n) => n.startsWith("[pi-rtk] passed through unchanged:")).length, 2);
179
+
180
+ // session_start resets the dedupe.
181
+ await h.handlers.session_start({}, h.ctx);
182
+ await fireToolCall(h, chain);
183
+ assert.equal(notifications.filter((n) => n.startsWith("[pi-rtk] passed through unchanged:")).length, 3);
184
+ });
185
+
186
+ test("pass-through notify does not fire when rtk was not consulted", async () => {
187
+ const notifications = [];
188
+ const h = createHarness();
189
+ h.state.versionAvailable = true;
190
+ h.ctx.hasUI = true;
191
+ h.ctx.ui.notify = (message) => notifications.push(message);
192
+ const ext = (await import("../index.ts")).default;
193
+ ext(h.pi);
194
+
195
+ await h.handlers.session_start({}, h.ctx);
196
+ process.env.RTK_DISABLED = "1";
197
+ try {
198
+ await fireToolCall(h, "npm test 2>&1 | tail -8");
199
+ assert.equal(notifications.filter((n) => n.includes("passed through")).length, 0, "env bypass = not consulted");
200
+ } finally {
201
+ delete process.env.RTK_DISABLED;
202
+ }
203
+ // hasUI=false suppresses notifies entirely.
204
+ h.ctx.hasUI = false;
205
+ await fireToolCall(h, "npm test 2>&1 | tail -8");
206
+ assert.equal(notifications.filter((n) => n.includes("passed through")).length, 0);
207
+ });
208
+
209
+ test("rtk settings: mode off is a kill switch; chained never skips the spawn", async () => {
210
+ // Isolate the agent dir so read/writeRtkSettings never touch the real file.
211
+ const { mkdtempSync, rmSync } = await import("node:fs");
212
+ const { tmpdir } = await import("node:os");
213
+ const { join } = await import("node:path");
214
+ const dir = mkdtempSync(join(tmpdir(), "ceulen-rtk-test-"));
215
+ const realAgentDir = process.env.PI_CODING_AGENT_DIR;
216
+ process.env.PI_CODING_AGENT_DIR = dir;
217
+ try {
218
+ const { writeRtkSection } = await import("../lib/settings.ts");
219
+
220
+ const h = createHarness();
221
+ h.state.versionAvailable = true;
222
+ h.state.rewritten = "rtk git status";
223
+ const ext = (await import("../index.ts")).default;
224
+ ext(h.pi);
225
+ await h.handlers.session_start({}, h.ctx);
226
+
227
+ // mode: off → no rewrite, no spawn.
228
+ writeRtkSection({ mode: "off" });
229
+ assert.equal(await fireToolCall(h, "git status"), "git status");
230
+ assert.equal(h.state.rewriteCalls, 0);
231
+
232
+ // back to supported-only → rewrites again.
233
+ writeRtkSection({ mode: "supported-only" });
234
+ assert.equal(await fireToolCall(h, "git status"), "rtk git status");
235
+
236
+ // chained: never → a chain never reaches the binary...
237
+ writeRtkSection({ chained: "never" });
238
+ const callsBefore = h.state.rewriteCalls;
239
+ assert.equal(await fireToolCall(h, "ls -la; pwd; cat a.txt"), "ls -la; pwd; cat a.txt");
240
+ assert.equal(h.state.rewriteCalls, callsBefore, "no spawn for a chain under chained: never");
241
+ // ...but a quoted operator is not a chain separator.
242
+ assert.equal(await fireToolCall(h, "git commit -m \"fix: a|b\""), "rtk git status");
243
+ assert.equal(h.state.rewriteCalls, callsBefore + 1, "quoted | is not a chain operator");
244
+ } finally {
245
+ if (realAgentDir === undefined) delete process.env.PI_CODING_AGENT_DIR;
246
+ else process.env.PI_CODING_AGENT_DIR = realAgentDir;
247
+ rmSync(dir, { recursive: true, force: true });
248
+ }
131
249
  });
@@ -113,7 +113,10 @@ export default function rulesExtension(pi: ExtensionAPI): void {
113
113
  const arg = (args ?? "").trim().toLowerCase();
114
114
  if (arg === "reload") {
115
115
  clearRuleCache();
116
- ctx.ui.notify(`[rules] cache dropped — re-reading ${loadRules(ctx.cwd).files.length} source(s)`, "info");
116
+ // Same trust gate as the status path: without it, an untrusted project
117
+ // reported phantom sources and the cache key never matched the
118
+ // composer's (trusted=false) key.
119
+ ctx.ui.notify(`[rules] cache dropped — re-reading ${loadRules(ctx.cwd, undefined, projectTrusted(ctx)).files.length} source(s)`, "info");
117
120
  return;
118
121
  }
119
122
  if (arg !== "") {
@@ -244,12 +244,15 @@ export function readRulesFile(source: string, state: ImportState = { seen: new S
244
244
  }
245
245
 
246
246
  function buildModel(files: string[], cwd: string): { model: RuleModel; imported: string[] } {
247
- const state: ImportState = { seen: new Set(), read: new Set() };
247
+ // `read` is shared across files (cache signature); `seen` is PER FILE —
248
+ // a repeat guard, not a global: the same @import from two RULES.md files
249
+ // must expand in both, or the second serves a literal token.
250
+ const read = new Set<string>();
248
251
  const rules: LoadedRule[] = [];
249
252
  const claimed = new Set<string>();
250
253
 
251
254
  for (const file of files) {
252
- for (const rule of readRulesFile(file, state)) {
255
+ for (const rule of readRulesFile(file, { seen: new Set(), read })) {
253
256
  // Name-based dedup, first-wins (precedence order = discovery order).
254
257
  if (claimed.has(rule.name)) continue;
255
258
  claimed.add(rule.name);
@@ -266,7 +269,7 @@ function buildModel(files: string[], cwd: string): { model: RuleModel; imported:
266
269
  };
267
270
  model.block = composeRulesBlock(model, cwd);
268
271
  model.blockChars = model.block?.length ?? 0;
269
- return { model, imported: [...state.read] };
272
+ return { model, imported: [...read] };
270
273
  }
271
274
 
272
275
  // ---------------------------------------------------------------------------
@@ -125,6 +125,30 @@ describe("@import expansion", () => {
125
125
  assert.equal(body.match(/BBB/g)?.length, 1);
126
126
  });
127
127
 
128
+ it("the same absolute import from TWO files expands in both (seen is per file)", () => {
129
+ // F3: ImportState.seen was shared across all RULES.md files, so the same
130
+ // @import from a second file stayed a literal token.
131
+ const { cwd, userDir } = workspace();
132
+ const shared = path.join(cwd, ".pi/shared.md");
133
+ write(shared, "SHARED-CONTENT\n");
134
+ write(path.join(cwd, ".pi/RULES.md"), "## a\n@" + shared + "\n");
135
+ write(path.join(userDir, "RULES.md"), "## b\n@" + shared + "\n");
136
+
137
+ const model = loadRules(cwd, userDir);
138
+ assert.equal(model.rules.length, 2);
139
+ for (const rule of model.rules) {
140
+ assert.ok(rule.body.includes("SHARED-CONTENT"), `${rule.name}: expanded`);
141
+ assert.ok(!rule.body.includes("@"), `${rule.name}: no literal token left`);
142
+ }
143
+ });
144
+
145
+ it("repeats WITHIN one file stay literal (cycle guard untouched)", () => {
146
+ const { cwd, userDir } = workspace();
147
+ write(path.join(cwd, ".pi/RULES.md"), "## a\n@x.md\n@x.md\n");
148
+ write(path.join(cwd, ".pi/x.md"), "XXX\n");
149
+ assert.equal(loadRules(cwd, userDir).rules[0].body.match(/XXX/g)?.length, 1);
150
+ });
151
+
128
152
  it("marks a missing import in one line instead of failing", () => {
129
153
  const { cwd, userDir } = workspace();
130
154
  write(path.join(cwd, ".pi/RULES.md"), "## a\nsee @nope/missing.md for details\n");
@@ -15,6 +15,7 @@ import os from "node:os";
15
15
  import path from "node:path";
16
16
 
17
17
  import rulesExtension from "../index.ts";
18
+ import { clearRuleCache, loadRules } from "../lib/rules.ts";
18
19
 
19
20
  const temps: string[] = [];
20
21
  const envBackup = process.env.PI_CODING_AGENT_DIR;
@@ -193,6 +194,34 @@ describe("rules module — /rules command", () => {
193
194
  assert.equal(notes[0].level, "error");
194
195
  });
195
196
 
197
+ it("UNTRUSTED project: reload counts only user-level sources and the cache key matches the composer's", async () => {
198
+ // F5: /rules reload called loadRules without the trust gate — the phantom
199
+ // trusted=true model also poisoned the mtime cache with a key the composer
200
+ // (trusted=false) could never hit.
201
+ const cwd = workspace({ ".pi/RULES.md": "## project-rule\nPROJECT-SECRET-MARKER\n" });
202
+ const userFile = write(path.join(agentDir, "RULES.md"), "## user-rule\nUSER-MARKER\n");
203
+ const { commands } = harness();
204
+ const notes: Harness["notes"] = [];
205
+ const untrusted = { ...context(cwd, notes), isProjectTrusted: () => false };
206
+
207
+ await commands.get("rules").handler("reload", untrusted);
208
+ assert.ok(notes[0].message.includes("1 source(s)"), `only user-level source: ${notes[0].message}`);
209
+ assert.ok(!notes[0].message.includes(path.join(cwd, ".pi/RULES.md")));
210
+
211
+ // The composer now hits the reload-populated cache: loadRules with the
212
+ // SAME (cwd, trusted=false) key the composer uses returns the identical
213
+ // model object — the reload-run cache is a hit, not a re-parse.
214
+ const { events } = harness();
215
+ const first = await events.get("before_agent_start")!({ systemPrompt: "BASE", prompt: "p" }, untrusted);
216
+ assert.ok(first?.systemPrompt.includes("USER-MARKER"));
217
+ assert.ok(!first?.systemPrompt.includes("PROJECT-SECRET-MARKER"));
218
+ assert.equal(loadRules(cwd, undefined, false), loadRules(cwd, undefined, false), "cache hit — same model object");
219
+ await events.get("before_agent_start")!({ systemPrompt: "BASE", prompt: "p" }, untrusted);
220
+
221
+ rmSync(userFile);
222
+ clearRuleCache();
223
+ });
224
+
196
225
  it("UNTRUSTED project: repo RULES.md never reaches the prompt; user file still applies", async () => {
197
226
  // Live-found defect (reviewer 2026-10-06): the composer had no trust gate —
198
227
  // an untrusted checkout's RULES.md (and its @imports) landed in every
@@ -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);