ceulen 0.13.0 → 0.15.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 (65) hide show
  1. package/CHANGELOG.md +66 -0
  2. package/README.md +5 -3
  3. package/extensions/index.ts +33 -1
  4. package/extensions/lib/registry.ts +31 -52
  5. package/extensions/modules/a2a/index.ts +0 -9
  6. package/extensions/modules/a2a/lib/config.ts +15 -1
  7. package/extensions/modules/a2a/test/config.test.ts +27 -0
  8. package/extensions/modules/a2a/test/extension.test.ts +1 -19
  9. package/extensions/modules/advisor/commands/advisor.ts +3 -9
  10. package/extensions/modules/advisor/test/configPanel.test.ts +1 -1
  11. package/extensions/modules/advisor/test/module.test.ts +0 -11
  12. package/extensions/modules/classifier/index.ts +0 -3
  13. package/extensions/modules/composer/test/module.test.ts +0 -22
  14. package/extensions/modules/config/defaultTools.ts +5 -3
  15. package/extensions/modules/config/index.ts +18 -204
  16. package/extensions/modules/config/test/defaultTools.test.ts +3 -4
  17. package/extensions/modules/config/test/panel.test.ts +9 -72
  18. package/extensions/modules/fff/index.ts +19 -8
  19. package/extensions/modules/fff/test/index.test.ts +31 -4
  20. package/extensions/modules/gh/configPanel.ts +9 -6
  21. package/extensions/modules/gh/index.ts +0 -3
  22. package/extensions/modules/gh/test/gh.test.ts +61 -0
  23. package/extensions/modules/jfind/index.ts +10 -4
  24. package/extensions/modules/jfind/lib/cascade.ts +15 -1
  25. package/extensions/modules/jfind/lib/lexical.ts +18 -6
  26. package/extensions/modules/jfind/lib/tree.ts +34 -4
  27. package/extensions/modules/jfind/test/cascade.test.ts +56 -1
  28. package/extensions/modules/munin/index.ts +5 -7
  29. package/extensions/modules/notify/index.ts +0 -3
  30. package/extensions/modules/plan/index.ts +1 -7
  31. package/extensions/modules/repair/configPanel.ts +11 -8
  32. package/extensions/modules/repair/index.ts +58 -33
  33. package/extensions/modules/repair/lib/auto-bg.ts +45 -2
  34. package/extensions/modules/repair/lib/auto-generated.ts +14 -4
  35. package/extensions/modules/repair/lib/read-archive.ts +14 -0
  36. package/extensions/modules/repair/lib/read-sqlite.ts +10 -4
  37. package/extensions/modules/repair/lib/settings.ts +19 -8
  38. package/extensions/modules/repair/test/auto-bg.test.ts +66 -0
  39. package/extensions/modules/repair/test/hardening.test.ts +214 -0
  40. package/extensions/modules/repair/test/settings.test.ts +52 -13
  41. package/extensions/modules/rules/index.ts +0 -4
  42. package/extensions/modules/rules/lib/rules.ts +1 -1
  43. package/extensions/modules/rules/test/module.test.ts +2 -29
  44. package/extensions/modules/serena/index.ts +1 -6
  45. package/extensions/modules/serena/lib/guidance.ts +9 -5
  46. package/extensions/modules/sg/index.ts +0 -5
  47. package/extensions/modules/shells/index.ts +31 -16
  48. package/extensions/modules/shells/lib/sessions.ts +76 -8
  49. package/extensions/modules/shells/test/output.test.ts +130 -0
  50. package/extensions/modules/shells/test/sessions.test.ts +127 -5
  51. package/extensions/modules/steering/lib/think.ts +0 -2
  52. package/extensions/modules/steering/test/think.test.ts +1 -5
  53. package/extensions/modules/todo/index.ts +0 -2
  54. package/extensions/modules/usage/index.ts +19 -9
  55. package/extensions/modules/usage/test/context.test.ts +18 -7
  56. package/extensions/modules/ux/index.ts +1 -5
  57. package/extensions/modules/ux/test/extension.test.ts +0 -5
  58. package/extensions/modules/web/index.ts +0 -9
  59. package/extensions/modules/web/lib/pdf.ts +4 -2
  60. package/extensions/modules/web/test/extension.test.ts +8 -18
  61. package/extensions/modules/web/test/pdf.test.ts +84 -0
  62. package/package.json +1 -1
  63. package/extensions/lib/tools.ts +0 -47
  64. package/extensions/modules/config/test/renderTools.test.ts +0 -71
  65. package/extensions/modules/config/test/tools.test.ts +0 -146
@@ -39,6 +39,8 @@ export class RingBuffer {
39
39
  private partial = ""; // unterminated tail not yet a line
40
40
  private totalBytes = 0;
41
41
  private lifetimeBytes = 0;
42
+ private lifetimeLineCount = 0; // complete lines ever pushed — never shrinks
43
+ private tailStart = 0; // once capped: index of the first tail line (the marker sits at tailStart - 1)
42
44
  private capped = false;
43
45
 
44
46
  push(chunk: string): void {
@@ -47,6 +49,7 @@ export class RingBuffer {
47
49
  this.partial = "";
48
50
  this.partial = parts.pop() ?? "";
49
51
  for (const line of parts) this.linesArr.push(line);
52
+ this.lifetimeLineCount += parts.length;
50
53
  this.totalBytes += Buffer.byteLength(chunk, "utf8");
51
54
  this.lifetimeBytes += Buffer.byteLength(chunk, "utf8");
52
55
  if (this.totalBytes > TOTAL_BYTES) this.enforceCap();
@@ -82,6 +85,7 @@ export class RingBuffer {
82
85
  }
83
86
  const droppedBytes = lineBytes(rest);
84
87
  this.linesArr = [...head, truncationMarker(Math.max(droppedBytes, 1)), ...tail];
88
+ this.tailStart = head.length + 1;
85
89
  this.totalBytes = lineBytes(this.linesArr);
86
90
  }
87
91
 
@@ -90,6 +94,31 @@ export class RingBuffer {
90
94
  return this.capAware();
91
95
  }
92
96
 
97
+ /** Complete lines ever pushed (lifetime — immune to cap shrinks). */
98
+ lifetimeLines(): number {
99
+ return this.lifetimeLineCount;
100
+ }
101
+
102
+ /**
103
+ * Visible lines pushed after lifetime line `seen` — the since:"last"
104
+ * cursor read. The cursor lives in lifetime space, so a cap shrink can
105
+ * never strand it above the window: unseen lines are the NEWEST ones,
106
+ * which the tail region (after the marker) always holds. When more lines
107
+ * arrived than the window kept, the whole recent region + marker returns
108
+ * instead of nothing; lines the cap dropped are simply gone.
109
+ */
110
+ linesSince(seen: number): string[] {
111
+ const behind = this.lifetimeLineCount - Math.max(0, seen);
112
+ if (behind <= 0) return [];
113
+ const all = this.capAware();
114
+ const hasPartial = this.partial !== "";
115
+ const completeCount = all.length - (hasPartial ? 1 : 0);
116
+ const floor = this.capped ? this.tailStart - 1 : 0; // never re-show the dropped middle / marker
117
+ const start = Math.max(floor, completeCount - behind);
118
+ const fresh = all.slice(start, completeCount);
119
+ return hasPartial ? [...fresh, this.partial] : fresh;
120
+ }
121
+
93
122
  /** Bytes written to this stream over its lifetime (pre-truncation). */
94
123
  totalWritten(): number {
95
124
  return this.lifetimeBytes;
@@ -106,7 +135,9 @@ export class RingBuffer {
106
135
  }
107
136
 
108
137
  private capAware(): string[] {
109
- if (this.capped) return [...this.linesArr];
138
+ // The partial survives capping too: spinner/progress output that hasn't
139
+ // got its newline yet must stay visible once the head+tail split is on.
140
+ if (this.capped) return this.partial ? [...this.linesArr, this.partial] : [...this.linesArr];
110
141
  const out = this.partial ? [...this.linesArr, this.partial] : [...this.linesArr];
111
142
  return out;
112
143
  }
@@ -124,8 +155,9 @@ export interface ShellSession {
124
155
  exitCode?: number | null;
125
156
  stdout: RingBuffer;
126
157
  stderr: RingBuffer;
127
- /** Output cursor for `since: "last"` — lines already returned by an output call. */
128
- lastOutputOffset: number;
158
+ /** Per-stream output cursors for `since: "last"` — lines already returned by an output call. */
159
+ lastStdoutOffset: number;
160
+ lastStderrOffset: number;
129
161
  }
130
162
 
131
163
  // ---------------------------------------------------------------------------
@@ -166,11 +198,17 @@ export function listSessionsLine(s: ShellSession): string {
166
198
  export function resolveSession(store: SessionStore, idOrName: string): ShellSession {
167
199
  const byId = store.get(idOrName);
168
200
  if (byId) return byId;
169
- const byName = store.list().filter((s) => s.name === idOrName);
170
- if (byName.length === 1) return byName[0]!;
201
+ // Prefer LIVE matches: restarting a session under the same name must not
202
+ // make the name ambiguous just because an old exited one lingers. Only
203
+ // when NO live match exists fall back to the full match list (original
204
+ // ambiguity semantics over exited sessions).
205
+ const all = store.list().filter((s) => s.name === idOrName);
206
+ const live = all.filter((s) => s.exitedAt === undefined);
207
+ const candidates = live.length > 0 ? live : all;
208
+ if (candidates.length === 1) return candidates[0]!;
171
209
  const listing = store.list().map(listSessionsLine).join("\n") || "(no sessions)";
172
- if (byName.length > 1) {
173
- throw new Error(`session name '${idOrName}' is ambiguous (${byName.length} sessions):\n${listing}`);
210
+ if (candidates.length > 1) {
211
+ throw new Error(`session name '${idOrName}' is ambiguous (${candidates.length} sessions):\n${listing}`);
174
212
  }
175
213
  throw new Error(`no session '${idOrName}'. Active sessions:\n${listing}`);
176
214
  }
@@ -214,6 +252,11 @@ export class SessionStore {
214
252
  this.map.delete(id);
215
253
  }
216
254
 
255
+ /** Drop every session (session_start: a fresh session can't reach old children). */
256
+ clear(): void {
257
+ this.map.clear();
258
+ }
259
+
217
260
  /** Remove the OLDEST exited session if more than 5 have accumulated. */
218
261
  evictOldestExited(): ShellSession | undefined {
219
262
  const exited = this.list().filter((s) => s.exitedAt !== undefined);
@@ -246,6 +289,16 @@ function signalProcessGroup(s: ShellSession, signal: NodeJS.Signals): void {
246
289
  // detached: true → the child leads its own process group; -pid signals the
247
290
  // whole group (the shell AND any grandchildren). Fall back to child.kill
248
291
  // when the group is gone (already reaped) or the call fails (Windows).
292
+ // pid 0 (spawn never succeeded) MUST NOT reach process.kill: kill(-0) ==
293
+ // kill(0) == SIGTERM for every process in pi's OWN group — host death.
294
+ if (s.pid <= 0) {
295
+ try {
296
+ s.child.kill(signal);
297
+ } catch {
298
+ // spawn never succeeded / already dead — exit handling deals with it
299
+ }
300
+ return;
301
+ }
249
302
  try {
250
303
  process.kill(-s.pid, signal);
251
304
  } catch {
@@ -307,7 +360,8 @@ export function createSession(
307
360
  startedAt: Date.now(),
308
361
  stdout: new RingBuffer(),
309
362
  stderr: new RingBuffer(),
310
- lastOutputOffset: 0,
363
+ lastStdoutOffset: 0,
364
+ lastStderrOffset: 0,
311
365
  } as ShellSession); // placeholder so the live-cap check sees THIS session too
312
366
  const placeholder = store.list().at(-1)!;
313
367
  let child: ChildProcess;
@@ -333,11 +387,25 @@ export function createSession(
333
387
  store.replace(placeholder.id, session);
334
388
  child.stdout?.on("data", (d: Buffer) => session.stdout.push(d.toString()));
335
389
  child.stderr?.on("data", (d: Buffer) => session.stderr.push(d.toString()));
390
+ // A stdin write that races child exit EPIPEs; with no listener Node turns
391
+ // that into an uncaughtException killing pi. Contain and record instead.
392
+ child.stdin?.on("error", () => {
393
+ session.stderr.push("[shells] stdin write failed (process exited)");
394
+ });
336
395
  child.on("exit", (code) => {
337
396
  session.exitedAt = Date.now();
338
397
  session.exitCode = code;
339
398
  });
340
399
  child.on("error", (err: Error) => {
400
+ // Spawn failure (ENOENT cwd/binary) arrives as 'error' with pid undefined
401
+ // and NO 'exit'. Mark it exited so kill/killAll never signal a pid-0
402
+ // "process group" — which would hit pi's own group. Windows quirk:
403
+ // 'error' can also fire on a LIVE pid-carrying process (kill-EPIPE),
404
+ // so only the never-spawned case (no pid) counts as exit.
405
+ if (child.pid === undefined) {
406
+ session.exitedAt = Date.now();
407
+ session.exitCode = null;
408
+ }
341
409
  session.stderr.push(`[shells] spawn error: ${err.message}`);
342
410
  });
343
411
  return session;
@@ -0,0 +1,130 @@
1
+ // Unit tests for the tool's output rendering + store lifecycle wiring
2
+ // (index.ts): per-stream `since:"last"` cursors and the session_start clear.
3
+ // index.ts is loaded through a stub ExtensionAPI; spawn is not touched.
4
+
5
+ import assert from "node:assert/strict";
6
+ import { describe, it } from "node:test";
7
+ import { RingBuffer, SessionStore, type ShellSession } from "../lib/sessions.js";
8
+ import mod, { getStoreForTests } from "../index.js";
9
+
10
+ /** Drive the module against a stub pi and return the registered tool + handlers. */
11
+ function load(): { tool: any; handlers: Record<string, Function>; store: SessionStore } {
12
+ const handlers: Record<string, Function> = {};
13
+ let tool: any;
14
+ const fakePi: any = {
15
+ on: (ev: string, fn: Function) => { handlers[ev] = fn; },
16
+ registerTool: (t: any) => { tool = t; },
17
+ };
18
+ mod(fakePi);
19
+ // Reach the store for cursor/clear assertions (module closes over it).
20
+ return { tool, handlers, store: getStoreForTests()! };
21
+ }
22
+
23
+ function session(over: Partial<ShellSession>): ShellSession {
24
+ return {
25
+ id: "s1",
26
+ pid: 1,
27
+ child: {} as never,
28
+ cwd: "/",
29
+ command: "true",
30
+ startedAt: Date.now(),
31
+ stdout: new RingBuffer(),
32
+ stderr: new RingBuffer(),
33
+ lastStdoutOffset: 0,
34
+ lastStderrOffset: 0,
35
+ ...over,
36
+ };
37
+ }
38
+
39
+ describe("output cursors (since:\"last\")", () => {
40
+ it("advances per-stream, independently", async () => {
41
+ const { tool, store } = load();
42
+ const s = session({ id: "s1" });
43
+ s.stdout.push("out-1\n");
44
+ s.stderr.push("err-1\n");
45
+ store.add(s);
46
+
47
+ const read = async () => {
48
+ const r = await tool.execute("t", { action: "output", id: "s1", since: "last" }, undefined as never, undefined as never, { cwd: "/" } as never);
49
+ return (r.content[0] as { text: string }).text;
50
+ };
51
+
52
+ let text = await read();
53
+ assert.match(text, /out-1/);
54
+ assert.match(text, /err-1/);
55
+ assert.equal(s.lastStdoutOffset, 1);
56
+ assert.equal(s.lastStderrOffset, 1);
57
+
58
+ // Only stderr advances now: stdout cursor must stay put.
59
+ s.stderr.push("err-2\n");
60
+ text = await read();
61
+ assert.doesNotMatch(text, /out-1/);
62
+ assert.match(text, /err-2/);
63
+ assert.equal(s.lastStdoutOffset, 1, "stdout cursor unchanged when only stderr grew");
64
+ assert.equal(s.lastStderrOffset, 2);
65
+
66
+ // Only stdout grows past stderr — stderr must not repeat (the old
67
+ // single-cursor bug showed stderr again whenever stdout was longer).
68
+ s.stdout.push("out-2\n");
69
+ text = await read();
70
+ assert.match(text, /out-2/);
71
+ assert.doesNotMatch(text, /err-1/);
72
+ assert.doesNotMatch(text, /err-2/);
73
+ assert.equal(s.lastStdoutOffset, 2);
74
+ assert.equal(s.lastStderrOffset, 2);
75
+ });
76
+
77
+ it("since:\"start\" never moves the cursors", async () => {
78
+ const { tool, store } = load();
79
+ const s = session({ id: "s1" });
80
+ s.stdout.push("a\nb\n");
81
+ store.add(s);
82
+ await tool.execute("t", { action: "output", id: "s1" }, undefined as never, undefined as never, { cwd: "/" } as never);
83
+ assert.equal(s.lastStdoutOffset, 0);
84
+ assert.equal(s.lastStderrOffset, 0);
85
+ });
86
+
87
+ it("re-clamps a cursor left above a ring-cap-shrunk array and recovers", async () => {
88
+ const { tool, store } = load();
89
+ const s = session({ id: "s1" });
90
+ store.add(s);
91
+ const read = async () => {
92
+ const r = await tool.execute("t", { action: "output", id: "s1", since: "last" }, undefined as never, undefined as never, { cwd: "/" } as never);
93
+ return (r.content[0] as { text: string }).text;
94
+ };
95
+
96
+ // Fill the ring PAST its cap (1KB lines, two big chunks): enforceCap()
97
+ // rebuilds the array to head + marker + tail (~260 lines). The drain
98
+ // poll reports the truncation and records that line count as the cursor.
99
+ s.stdout.push("HEAD-LINE\n");
100
+ const kbLine = `${"A".repeat(999)}\n`.repeat(420); // ~420KB per chunk
101
+ s.stdout.push(kbLine);
102
+ s.stdout.push(kbLine);
103
+ const text1 = await read();
104
+ assert.match(text1, /truncated/);
105
+ assert.equal(s.lastStdoutOffset, s.stdout.lifetimeLines(), "drain records the lifetime cursor");
106
+
107
+ // Two huge lines re-cap and SHRINK the window far below the recorded
108
+ // index-space position. A window-index cursor (the old design) strands
109
+ // above the shrunk array forever — the lifetime cursor cannot.
110
+ s.stdout.push(`${"x".repeat(99_999)}\n${"y".repeat(99_999)}\n`);
111
+ await read();
112
+ assert.ok(s.lastStdoutOffset > s.stdout.lines().length, "cursor is lifetime space, above the shrunk window (previously the blackout)");
113
+ assert.equal(s.lastStdoutOffset, s.stdout.lifetimeLines(), "cursor stays synced to lifetime lines after the shrink");
114
+
115
+ // Recovery: new pushes must surface again, not "no new output yet".
116
+ for (let i = 0; i < 12; i++) s.stdout.push(`${"NEW-".padEnd(4999, "N")}\n`.repeat(60));
117
+ const text2 = await read();
118
+ assert.match(text2, /NEW-/);
119
+ assert.doesNotMatch(text2, /no new output yet/);
120
+ });
121
+ });
122
+
123
+ describe("session_start wiring", () => {
124
+ it("clears the store (no-op bug regression)", async () => {
125
+ const { handlers, store } = load();
126
+ store.add(session({ id: "s1" }));
127
+ (handlers.session_start as (e: unknown, ctx: unknown) => void)({}, {});
128
+ assert.equal(store.list().length, 0);
129
+ });
130
+ });
@@ -25,7 +25,9 @@ import {
25
25
  function fakeChild(): { child: any; writes: string[]; killCalls: string[]; emitExit: (code: number | null, signal?: NodeJS.Signals | null) => void } {
26
26
  const child = new EventEmitter() as any;
27
27
  child.pid = 42_424;
28
- child.stdin = { write: (d: string) => child.__writes.push(d), get writable() { return !child.__closed; } };
28
+ // stdin must be an EventEmitter: createSession registers an 'error'
29
+ // listener on it (EPIPE containment).
30
+ child.stdin = Object.assign(new EventEmitter(), { write: (d: string) => child.__writes.push(d) });
29
31
  child.stdout = new EventEmitter();
30
32
  child.stderr = new EventEmitter();
31
33
  child.kill = (sig: NodeJS.Signals = "SIGTERM") => {
@@ -82,6 +84,15 @@ describe("RingBuffer", () => {
82
84
  it("truncationMarker formats", () => {
83
85
  assert.equal(truncationMarker(5), "[… 5 bytes truncated …]");
84
86
  });
87
+
88
+ it("keeps the unterminated partial line after the cap trips", () => {
89
+ const rb = new RingBuffer();
90
+ rb.push("HEAD-LINE\n");
91
+ rb.push("x".repeat(TOTAL_BYTES) + "\n"); // cap trips
92
+ rb.push("spinner…"); // no trailing newline, arrives after capping
93
+ assert.equal(rb.isTruncated(), true);
94
+ assert.match(rb.lines().at(-1)!, /^spinner…/);
95
+ });
85
96
  });
86
97
 
87
98
  // ── ids + resolution ────────────────────────────────────────────────────────
@@ -106,7 +117,7 @@ describe("ids and resolveSession", () => {
106
117
  startedAt: Date.now(),
107
118
  stdout: new RingBuffer(),
108
119
  stderr: new RingBuffer(),
109
- lastOutputOffset: 0,
120
+ lastStdoutOffset: 0, lastStderrOffset: 0,
110
121
  ...over,
111
122
  };
112
123
  }
@@ -128,6 +139,24 @@ describe("ids and resolveSession", () => {
128
139
  assert.throws(() => resolveSession(store, "dev"), /ambiguous.*dev/s);
129
140
  assert.throws(() => resolveSession(store, "nope"), /no session 'nope'/);
130
141
  });
142
+
143
+ it("prefers a live match over an exited one with the same name", () => {
144
+ const store = new SessionStore();
145
+ const dead = session({ id: "s1", name: "dev", exitedAt: Date.now(), exitCode: 0 });
146
+ const live = session({ id: "s2", name: "dev" });
147
+ store.add(dead);
148
+ store.add(live);
149
+ assert.equal(resolveSession(store, "dev"), live);
150
+ // Ambiguity is judged among LIVE sessions only.
151
+ const live2 = session({ id: "s3", name: "dev" });
152
+ store.add(live2);
153
+ assert.throws(() => resolveSession(store, "dev"), /ambiguous \(2 sessions\)/);
154
+ // All matches exited → fall back to the FULL list (original semantics:
155
+ // ambiguity is decided over the fallback set).
156
+ live.exitedAt = Date.now();
157
+ live2.exitedAt = Date.now();
158
+ assert.throws(() => resolveSession(store, "dev"), /ambiguous \(3 sessions\)/);
159
+ });
131
160
  });
132
161
 
133
162
  // ── SessionStore ────────────────────────────────────────────────────────────
@@ -143,7 +172,7 @@ describe("SessionStore", () => {
143
172
  startedAt: Date.now(),
144
173
  stdout: new RingBuffer(),
145
174
  stderr: new RingBuffer(),
146
- lastOutputOffset: 0,
175
+ lastStdoutOffset: 0, lastStderrOffset: 0,
147
176
  ...over,
148
177
  };
149
178
  }
@@ -168,18 +197,26 @@ describe("SessionStore", () => {
168
197
  assert.equal(store.list()[0]!.id, "d2"); // oldest two gone
169
198
  });
170
199
 
200
+ it("clear drops every session", () => {
201
+ const store = new SessionStore();
202
+ store.add(live({ id: "s1" }));
203
+ store.add(live({ id: "s2" }));
204
+ store.clear();
205
+ assert.equal(store.list().length, 0);
206
+ });
207
+
171
208
  it("killAll skips exited sessions and escalates for live ones", { timeout: 10_000 }, async () => {
172
209
  const store = new SessionStore();
173
210
  const fc = fakeChild();
174
211
  const s = store.list().length; // 0
175
212
  store.add({
176
213
  id: "s1", pid: fc.child.pid, child: fc.child, cwd: "/", command: "x",
177
- startedAt: Date.now(), stdout: new RingBuffer(), stderr: new RingBuffer(), lastOutputOffset: 0,
214
+ startedAt: Date.now(), stdout: new RingBuffer(), stderr: new RingBuffer(), lastStdoutOffset: 0, lastStderrOffset: 0,
178
215
  });
179
216
  store.add({
180
217
  id: "s2", pid: 1, child: fakeChild().child, cwd: "/", command: "x",
181
218
  startedAt: Date.now(), exitedAt: Date.now(), exitCode: 0,
182
- stdout: new RingBuffer(), stderr: new RingBuffer(), lastOutputOffset: 0,
219
+ stdout: new RingBuffer(), stderr: new RingBuffer(), lastStdoutOffset: 0, lastStderrOffset: 0,
183
220
  });
184
221
  await store.killAll("SIGTERM");
185
222
  // Group signal fails (bogus pid) → falls back to child.kill; escalation
@@ -218,6 +255,78 @@ describe("createSession", () => {
218
255
  assert.equal(store.list().length, 0);
219
256
  });
220
257
 
258
+ it("marks an async spawn failure exited and never signals pi's own group", async () => {
259
+ const store = new SessionStore();
260
+ resetIdCounter(0);
261
+ // Async failure: child emits 'error' with pid undefined (bad cwd etc.).
262
+ const fc = fakeChild();
263
+ fc.child.pid = undefined;
264
+ const s = createSession(store, () => {
265
+ queueMicrotask(() => fc.child.emit("error", new Error("ENOENT: spawn bad-cwd")));
266
+ return fc.child as never;
267
+ }, { command: "x", cwd: "/nonexistent-cwd" });
268
+ assert.equal(s.pid, 0);
269
+ await new Promise<void>((r) => setImmediate(r));
270
+ assert.ok(s.exitedAt !== undefined, "spawn failure marks the session exited");
271
+ assert.equal(s.exitCode, null);
272
+
273
+ // kill on the zombie resolves early — nothing to signal, and never
274
+ // process.kill(-0) (== kill(0) == SIGTERM for every process in pi's
275
+ // own group).
276
+ const origKill = process.kill;
277
+ const groupCalls: [number | undefined, NodeJS.Signals][] = [];
278
+ (process as any).kill = (pid: number | undefined, sig?: NodeJS.Signals) => {
279
+ if (typeof pid === "number" && pid <= 0) groupCalls.push([pid, sig as NodeJS.Signals]);
280
+ return true;
281
+ };
282
+ try {
283
+ const r = await killSession(s, "SIGKILL", 50);
284
+ assert.deepEqual(r, { code: null, signal: null }); // early exit, no signal
285
+ assert.deepEqual(groupCalls, [], "no negative/zero-pid group signal may be issued");
286
+ } finally {
287
+ (process as any).kill = origKill;
288
+ }
289
+ assert.deepEqual(fc.killCalls, [] as string[], "exited session is not signalled");
290
+ });
291
+
292
+ it("kill on a live pid-0 session falls back to child.kill, not the host group", async () => {
293
+ const store = new SessionStore();
294
+ // Race window: session registered, spawn 'error' not yet fired → still
295
+ // live with pid 0. killSession must reach for child.kill only.
296
+ const fc = fakeChild();
297
+ fc.child.pid = undefined;
298
+ const s = createSession(store, () => fc.child as never, { command: "x", cwd: "/" });
299
+ assert.equal(s.pid, 0);
300
+ const origKill = process.kill;
301
+ const groupCalls: [number | undefined, NodeJS.Signals][] = [];
302
+ (process as any).kill = (pid: number | undefined, sig?: NodeJS.Signals) => {
303
+ if (typeof pid === "number" && pid <= 0) groupCalls.push([pid, sig as NodeJS.Signals]);
304
+ return true;
305
+ };
306
+ try {
307
+ const r = await killSession(s, "SIGTERM", 50);
308
+ assert.equal(r.signal, "SIGKILL"); // escalated: fake never exits
309
+ assert.deepEqual(groupCalls, [], "no negative/zero-pid group signal may be issued");
310
+ } finally {
311
+ (process as any).kill = origKill;
312
+ }
313
+ assert.ok(fc.killCalls.includes("SIGTERM"));
314
+ assert.ok(fc.killCalls.includes("SIGKILL"), "falls back to child.kill");
315
+ });
316
+
317
+ it("frees the name after an async spawn failure", async () => {
318
+ const store = new SessionStore();
319
+ const fc = fakeChild();
320
+ fc.child.pid = undefined;
321
+ createSession(store, () => {
322
+ queueMicrotask(() => fc.child.emit("error", new Error("ENOENT")));
323
+ return fc.child as never;
324
+ }, { command: "x", cwd: "/", name: "dev" });
325
+ await new Promise<void>((r) => setImmediate(r));
326
+ const again = createSession(store, noopSpawn, { command: "y", cwd: "/", name: "dev" });
327
+ assert.ok(again.id.length > 0);
328
+ });
329
+
221
330
  it("killSession escalates to SIGKILL after the wait", async () => {
222
331
  const store = new SessionStore();
223
332
  const fc = fakeChild(); // never emits exit on its own
@@ -237,6 +346,19 @@ describe("createSession", () => {
237
346
  const r = await killSession(s);
238
347
  assert.equal(r.code, 3);
239
348
  });
349
+
350
+ it("contains a stdin EPIPE that races child exit (no uncaught error)", () => {
351
+ const store = new SessionStore();
352
+ const fc = fakeChild();
353
+ const s = createSession(store, () => fc.child as never, { command: "sh -c 'exit 0'", cwd: "/" });
354
+ fc.emitExit(0);
355
+ // A write that raced the exit already EPIPEd: the 'error' event lands on
356
+ // stdin with no writer left. On a real child that would be an
357
+ // uncaughtException killing pi; on an EventEmitter, emitting 'error'
358
+ // with no listener THROWS — so doesNotThrow is the no-crash assertion.
359
+ assert.doesNotThrow(() => fc.child.stdin.emit("error", new Error("EPIPE")));
360
+ assert.deepEqual(s.stderr.lines(), ["[shells] stdin write failed (process exited)"]);
361
+ });
240
362
  });
241
363
 
242
364
  // ── REAL spawn integration (posix) ──────────────────────────────────────────
@@ -19,7 +19,6 @@
19
19
  import { Text } from "@earendil-works/pi-tui";
20
20
  import { Type } from "typebox";
21
21
 
22
- import { readDisabledTools } from "../../../lib/tools.js";
23
22
 
24
23
  /** The dim marker shown in place of the thoughts. */
25
24
  export const THINK_MARKER = "·";
@@ -46,7 +45,6 @@ export function thinkTool() {
46
45
  promptGuidelines: ["Use the think tool to plan before complex multi-step work."],
47
46
  // kill-switch: ceulen.disabledTools names it → registers inactive (the
48
47
  // config module's tool rows flip it live via setActiveTools).
49
- defaultActive: !readDisabledTools().has("think"),
50
48
  parameters: Type.Object(
51
49
  { thoughts: Type.String({ description: "private scratchpad; not shown to user" }) },
52
50
  { additionalProperties: false },
@@ -54,9 +54,6 @@ describe("think tool", () => {
54
54
  assert.match((plain as unknown as { render(w: number): string[] }).render(80).join(""), /· think \(1 chars\)/);
55
55
  });
56
56
 
57
- it("defaultActive is true unless the kill-switch names think", () => {
58
- assert.equal(thinkTool().defaultActive, true, "isolated dir has no ceulen.disabledTools");
59
- });
60
57
  });
61
58
 
62
59
  describe("module gating", () => {
@@ -66,12 +63,11 @@ describe("think tool", () => {
66
63
  assert.equal(pi.tools.length, 0, "no tool when the gate is off");
67
64
  });
68
65
 
69
- it("thinkTool: true registers the think tool, active unless disabled", () => {
66
+ it("thinkTool: true registers the think tool", () => {
70
67
  setSteeringSettings(iso.dir, { thinkTool: true });
71
68
  const pi = createFakePi();
72
69
  assert.equal(pi.tools.length, 1);
73
70
  assert.equal(pi.tools[0]!.name, "think");
74
- assert.equal(pi.tools[0]!.defaultActive, true);
75
71
  });
76
72
  });
77
73
  });
@@ -47,7 +47,6 @@ import {
47
47
  type WidgetTheme,
48
48
  } from "./lib/render.ts";
49
49
  import { readLingerSecs } from "./lib/settings.ts";
50
- import { readDisabledTools } from "../../lib/tools.js";
51
50
 
52
51
  export const TODO_TOOL = "todo";
53
52
  export const TODO_ENTRY_TYPE = "ceulen-todo";
@@ -394,7 +393,6 @@ export default function todoModule(pi: ExtensionAPI): void {
394
393
  "External waits (user, another agent, a service): block with the blocker ids, which suppresses the stop reminder; unblock when actionable, and append a clearing phase when the blocker is agent-actionable.",
395
394
  "Phase ids are stable for the list's lifetime; when the board loses text, view it — never guess.",
396
395
  ],
397
- defaultActive: !readDisabledTools().has(TODO_TOOL),
398
396
  parameters: todoSchema,
399
397
  // TUI-only: the colored board (status colors, strikethrough on done).
400
398
  // The LLM-facing text content stays the plain board — this only swaps
@@ -1688,7 +1688,7 @@ export interface ContextBreakdown {
1688
1688
  /** Human-readable model name, e.g. "GLM-5.3". */
1689
1689
  modelName?: string;
1690
1690
  systemPrompt: { total: number; sections: Record<string, number> };
1691
- tools: { total: number; activeCount: number; registeredCount: number; bySource: Record<string, { tokens: number; count: number }> };
1691
+ tools: { total: number; activeCount: number; registeredCount: number; deferred: { count: number; tokens: number }; bySource: Record<string, { tokens: number; count: number }> };
1692
1692
  /** Per-tool costs, descending — powers the "top tools" list. */
1693
1693
  toolCosts: { name: string; tokens: number; source: string }[];
1694
1694
  skills: { total: number; count: number };
@@ -1751,14 +1751,24 @@ export function computeContextBreakdown(input: ContextBreakdownInput): ContextBr
1751
1751
  const bySource: Record<string, { tokens: number; count: number }> = {};
1752
1752
  const toolCosts: { name: string; tokens: number; source: string }[] = [];
1753
1753
  let toolsTotal = 0;
1754
+ // Deferred/inactive tools are NOT in the prompt (pi only declares active
1755
+ // `direct` tools); count their schemas separately so the report reflects
1756
+ // what the model actually receives.
1757
+ let deferredCount = 0;
1758
+ let deferredTokens = 0;
1754
1759
  for (const t of tools) {
1755
1760
  const cost = toolTokens(t);
1756
- toolsTotal += cost;
1757
- const src = t.sourceInfo?.source ?? "unknown";
1758
- const bucket = (bySource[src] ??= { tokens: 0, count: 0 });
1759
- bucket.tokens += cost;
1760
- bucket.count += 1;
1761
- toolCosts.push({ name: t.name, tokens: cost, source: src });
1761
+ if (activeSet.has(t.name)) {
1762
+ toolsTotal += cost;
1763
+ const src = t.sourceInfo?.source ?? "unknown";
1764
+ const bucket = (bySource[src] ??= { tokens: 0, count: 0 });
1765
+ bucket.tokens += cost;
1766
+ bucket.count += 1;
1767
+ toolCosts.push({ name: t.name, tokens: cost, source: src });
1768
+ } else {
1769
+ deferredCount += 1;
1770
+ deferredTokens += cost;
1771
+ }
1762
1772
  }
1763
1773
  toolCosts.sort((a, b) => b.tokens - a.tokens);
1764
1774
 
@@ -1826,7 +1836,7 @@ export function computeContextBreakdown(input: ContextBreakdownInput): ContextBr
1826
1836
  modelLabel: model && "provider" in model && model.provider ? `${model.provider}/${model.id ?? "?"}` : undefined,
1827
1837
  modelName: model && "name" in model ? model.name : undefined,
1828
1838
  systemPrompt: { total: systemTotal, sections },
1829
- tools: { total: toolsTotal, activeCount: activeSet.size, registeredCount: tools.length, bySource },
1839
+ tools: { total: toolsTotal, activeCount: activeSet.size, registeredCount: tools.length, deferred: { count: deferredCount, tokens: deferredTokens }, bySource },
1830
1840
  toolCosts,
1831
1841
  skills: { total: sections.skills ?? 0, count: countSkills(skillsRaw) },
1832
1842
  memoryFiles: {
@@ -1898,7 +1908,7 @@ export function renderContextPanel(b: ContextBreakdown): string[] {
1898
1908
  for (const name of sectionNames) lines.push(` ${name}: ${k(b.systemPrompt.sections[name])}`);
1899
1909
  }
1900
1910
  if (b.toolCosts.length > 0) {
1901
- lines.push("", `Tools (${b.tools.registeredCount}${b.tools.activeCount !== b.tools.registeredCount ? ` · ${b.tools.activeCount} active` : ""}):`);
1911
+ lines.push("", `Tools (${b.tools.activeCount} active · ${k(b.tools.total)} tokens in prompt${b.tools.deferred.count > 0 ? ` · ${b.tools.deferred.count} deferred not in prompt (${k(b.tools.deferred.tokens)})` : ""}):`);
1902
1912
  for (const t of b.toolCosts.slice(0, 5)) lines.push(` ${t.name}: ${k(t.tokens)}`);
1903
1913
  const top = Object.entries(b.tools.bySource).sort((x, y) => y[1].tokens - x[1].tokens).slice(0, 3);
1904
1914
  for (const [src, s] of top) lines.push(` ${shortSource(src)}: ${k(s.tokens)} · ${s.count} tool${s.count === 1 ? "" : "s"}`);
@@ -161,12 +161,16 @@ test("computeContextBreakdown splits sections, groups tools by source, reserves
161
161
  assert.equal(b.systemPrompt.sections.preamble, 100);
162
162
  assert.equal(b.systemPrompt.sections.project_context, 2000);
163
163
  assert.equal(b.systemPrompt.sections.rules, undefined);
164
- // Tools: (400 + ~22)/4=106, (800 + ~43)/4=211, 800/4=200 → grouped by source.
164
+ // Tools: (400+~20)/4=105, (800+~40)/4=210, 800/4=201. Only the two
165
+ // ACTIVE tools count toward the prompt; web_extract (inactive) is deferred.
165
166
  assert.equal(b.tools.registeredCount, 3);
166
167
  assert.equal(b.tools.activeCount, 2);
167
- assert.equal(b.tools.bySource["@bacnh85/pi-web"].count, 2);
168
+ assert.equal(b.tools.deferred.count, 1);
169
+ assert.equal(b.tools.deferred.tokens, 201);
170
+ assert.equal(b.tools.bySource["@bacnh85/pi-web"].count, 1);
168
171
  assert.equal(b.tools.bySource.pi.count, 1);
169
172
  assert.equal(b.tools.total, b.tools.bySource.pi.tokens + b.tools.bySource["@bacnh85/pi-web"].tokens);
173
+ assert.equal(b.tools.total, 105 + 210);
170
174
  // Skills parsed from the skills section.
171
175
  assert.equal(b.skills.count, 2);
172
176
  assert.ok(b.skills.total > 0 && b.skills.total < 300);
@@ -177,7 +181,7 @@ test("computeContextBreakdown splits sections, groups tools by source, reserves
177
181
  assert.equal(b.messages.count, 2);
178
182
  assert.equal(b.messages.total, 50 + 100);
179
183
  // Per-tool costs, descending (powers the top-tools list).
180
- assert.deepEqual(b.toolCosts.map((t) => t.name), ["web_search", "web_extract", "read"]);
184
+ assert.deepEqual(b.toolCosts.map((t) => t.name), ["web_search", "read"]);
181
185
  // Reserved is the compaction slice only; free space excludes it (pi's trigger:
182
186
  // tokens > window - reserveTokens). Model output is NOT reserved.
183
187
  assert.deepEqual(b.reserved, { compaction: 16384 });
@@ -258,18 +262,25 @@ test("renderContextPanel lays the legend beside a 20x10 grid (OMP geometry)", ()
258
262
  });
259
263
 
260
264
  test("renderContextPanel fires recommendations above thresholds", () => {
261
- // Tiny-ish window so the 516-token tool fixture crosses the 40% recommendation threshold.
262
- const b = computeContextBreakdown(fixtureInput({ ctx: fixtureCtx(), model: { maxTokens: 8192, contextWindow: 1200 } }));
265
+ // Tiny-ish window so the 315-token active-tool fixture crosses the 40% recommendation threshold.
266
+ const b = computeContextBreakdown(fixtureInput({ ctx: fixtureCtx(), model: { maxTokens: 8192, contextWindow: 700 } }));
263
267
  const lines = renderContextPanel(b);
264
- assert.ok(lines.some((l) => l.includes("5.0K/1.2K tokens (416.7%)")), lines.join("\n"));
268
+ assert.ok(lines.some((l) => l.includes("5.0K/700 tokens (714.3%)")), lines.join("\n"));
265
269
  assert.ok(lines.some((l) => l.includes("pi-web:")), lines.join("\n"));
266
270
  assert.ok(!lines.some((l) => l.includes("@bacnh85/")), "package labels are shortened");
267
271
  assert.ok(lines.some((l) => l.includes("project_context: 2.0K")));
268
- // tools (516) > 40% of the 1200-token window → recommendation fires.
272
+ // active tools (317) > 40% of the 700-token window → recommendation fires.
269
273
  assert.ok(lines.some((l) => l.startsWith("- ") && l.includes("setActiveTools")), lines.join("\n"));
270
274
  assert.ok(!lines.some((l) => l.includes("trimming AGENTS.md")));
271
275
  });
272
276
 
277
+ test("renderContextPanel discloses the deferred tier separately", () => {
278
+ const b = computeContextBreakdown(fixtureInput());
279
+ const lines = renderContextPanel(b);
280
+ assert.ok(lines.some((l) => l.includes("2 active ·") && l.includes("tokens in prompt")), lines.join("\n"));
281
+ assert.ok(lines.some((l) => l.includes("1 deferred not in prompt (201)")), lines.join("\n"));
282
+ });
283
+
273
284
  test("renderContextPanel fires memory + skills recommendations above thresholds", () => {
274
285
  const ctx = fixtureCtx();
275
286
  const big = "m".repeat(4 * 4000); // 4000 tokens