ceulen 0.11.0 → 0.13.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 (70) hide show
  1. package/CHANGELOG.md +100 -1
  2. package/extensions/index.ts +5 -1
  3. package/extensions/lib/env.test.ts +147 -0
  4. package/extensions/lib/env.ts +180 -0
  5. package/extensions/lib/order.test.ts +74 -0
  6. package/extensions/lib/registry.test.ts +8 -5
  7. package/extensions/lib/registry.ts +23 -4
  8. package/extensions/modules/a2a/configPanel.ts +42 -1
  9. package/extensions/modules/a2a/lib/config.ts +8 -3
  10. package/extensions/modules/a2a/test/configPanel.test.ts +7 -4
  11. package/extensions/modules/advisor/index.ts +6 -3
  12. package/extensions/modules/advisor/test/module.test.ts +31 -0
  13. package/extensions/modules/classifier/index.ts +55 -1
  14. package/extensions/modules/classifier/test/classifier.test.ts +62 -0
  15. package/extensions/modules/composer/test/module.test.ts +2 -2
  16. package/extensions/modules/config/test/renderTools.test.ts +1 -1
  17. package/extensions/modules/jfind/index.ts +115 -0
  18. package/extensions/modules/jfind/lib/cascade.ts +377 -0
  19. package/extensions/modules/jfind/lib/format.ts +12 -0
  20. package/extensions/modules/jfind/lib/judge.ts +74 -0
  21. package/extensions/modules/jfind/lib/lexical.ts +232 -0
  22. package/extensions/modules/jfind/lib/questions.ts +178 -0
  23. package/extensions/modules/jfind/lib/tree.ts +374 -0
  24. package/extensions/modules/jfind/test/cascade.test.ts +305 -0
  25. package/extensions/modules/notify/index.ts +33 -0
  26. package/extensions/modules/notify/lib/notify.ts +99 -0
  27. package/extensions/modules/notify/test/notify.test.ts +95 -0
  28. package/extensions/modules/plan/lib/plan-tools.ts +13 -0
  29. package/extensions/modules/repair/configPanel.ts +7 -1
  30. package/extensions/modules/repair/index.ts +158 -3
  31. package/extensions/modules/repair/lib/auto-generated.ts +89 -0
  32. package/extensions/modules/repair/lib/read-archive.ts +101 -0
  33. package/extensions/modules/repair/lib/read-sqlite.ts +185 -0
  34. package/extensions/modules/repair/lib/settings.ts +4 -1
  35. package/extensions/modules/repair/test/freshness.test.ts +41 -1
  36. package/extensions/modules/repair/test/guard-selector.test.ts +67 -0
  37. package/extensions/modules/repair/test/readers.test.ts +291 -0
  38. package/extensions/modules/repair/test/settings.test.ts +2 -1
  39. package/extensions/modules/router/configPanel.ts +4 -4
  40. package/extensions/modules/router/index.ts +1 -1
  41. package/extensions/modules/router/lib/config.ts +9 -4
  42. package/extensions/modules/router/lib/systemone.ts +17 -4
  43. package/extensions/modules/router/test/unit.test.ts +46 -1
  44. package/extensions/modules/rules/index.ts +13 -3
  45. package/extensions/modules/rules/lib/rules.ts +24 -12
  46. package/extensions/modules/rules/test/lib.test.ts +20 -0
  47. package/extensions/modules/rules/test/module.test.ts +21 -0
  48. package/extensions/modules/sg/index.ts +129 -0
  49. package/extensions/modules/sg/lib/ops.ts +144 -0
  50. package/extensions/modules/sg/lib/sg-cli.ts +104 -0
  51. package/extensions/modules/sg/test/sg.test.ts +128 -0
  52. package/extensions/modules/shells/index.ts +210 -0
  53. package/extensions/modules/shells/lib/sessions.ts +344 -0
  54. package/extensions/modules/shells/test/sessions.test.ts +275 -0
  55. package/extensions/modules/subagent/index.ts +11 -5
  56. package/extensions/modules/subagent/lib/herdr.ts +5 -0
  57. package/extensions/modules/subagent/lib/routing.ts +31 -8
  58. package/extensions/modules/subagent/lib/runner.ts +8 -2
  59. package/extensions/modules/subagent/test/routing.test.ts +45 -0
  60. package/extensions/modules/web/configPanel.ts +67 -8
  61. package/extensions/modules/web/index.ts +34 -0
  62. package/extensions/modules/web/lib/pdf.ts +181 -0
  63. package/extensions/modules/web/test/configPanel.test.ts +7 -3
  64. package/extensions/modules/web/test/extension.test.ts +2 -1
  65. package/extensions/modules/web/test/settings.test.ts +6 -0
  66. package/extensions/modules/web/vendor/pdfjs/LICENSE +177 -0
  67. package/extensions/modules/web/vendor/pdfjs/README.md +16 -0
  68. package/extensions/modules/web/vendor/pdfjs/pdf.min.mjs +21 -0
  69. package/extensions/modules/web/vendor/pdfjs/pdf.worker.mjs +21 -0
  70. package/package.json +3 -3
@@ -0,0 +1,275 @@
1
+ // shells unit tests — fake-child logic tests + a couple of REAL spawn
2
+ // integration tests (posix only). No network, no sleeps beyond ms timers.
3
+
4
+ import assert from "node:assert/strict";
5
+ import { spawn as realSpawn } from "node:child_process";
6
+ import { EventEmitter } from "node:events";
7
+ import os from "node:os";
8
+ import path from "node:path";
9
+ import { after, describe, it } from "node:test";
10
+ import {
11
+ RingBuffer,
12
+ SessionStore,
13
+ createSession,
14
+ killSession,
15
+ nextId,
16
+ resetIdCounter,
17
+ resolveSession,
18
+ TOTAL_BYTES,
19
+ truncationMarker,
20
+ type ShellSession,
21
+ type SpawnFn,
22
+ } from "../lib/sessions.js";
23
+
24
+ /** A fake child: EventEmitter surface used by createSession, capture mode. */
25
+ function fakeChild(): { child: any; writes: string[]; killCalls: string[]; emitExit: (code: number | null, signal?: NodeJS.Signals | null) => void } {
26
+ const child = new EventEmitter() as any;
27
+ child.pid = 42_424;
28
+ child.stdin = { write: (d: string) => child.__writes.push(d), get writable() { return !child.__closed; } };
29
+ child.stdout = new EventEmitter();
30
+ child.stderr = new EventEmitter();
31
+ child.kill = (sig: NodeJS.Signals = "SIGTERM") => {
32
+ child.__kills.push(sig);
33
+ return true;
34
+ };
35
+ child.__writes = [] as string[];
36
+ child.__kills = [] as string[];
37
+ child.__closed = false;
38
+ child.__emitExit = (code: number | null, signal?: NodeJS.Signals | null) => {
39
+ child.__closed = true;
40
+ child.emit("exit", code, signal ?? null);
41
+ };
42
+ return { child, writes: child.__writes, killCalls: child.__kills, emitExit: child.__emitExit };
43
+ }
44
+
45
+ const noopSpawn: SpawnFn = () => fakeChild().child as never;
46
+
47
+ // ── RingBuffer ──────────────────────────────────────────────────────────────
48
+
49
+ describe("RingBuffer", () => {
50
+ it("buffers lines including the unterminated tail", () => {
51
+ const rb = new RingBuffer();
52
+ rb.push("one\ntwo\nthr");
53
+ assert.deepEqual(rb.lines(), ["one", "two", "thr"]); // tail visible
54
+ assert.equal(rb.peekPartial(), "thr");
55
+ rb.push("ee\nfour\n");
56
+ assert.deepEqual(rb.lines(), ["one", "two", "three", "four"]);
57
+ });
58
+
59
+ it("reports totalWritten and truncation state", () => {
60
+ const rb = new RingBuffer();
61
+ rb.push("a\n");
62
+ assert.equal(rb.totalWritten(), 2);
63
+ assert.equal(rb.isTruncated(), false);
64
+ rb.push("x".repeat(TOTAL_BYTES + 10));
65
+ assert.equal(rb.isTruncated(), true);
66
+ assert.ok(rb.totalWritten() > TOTAL_BYTES); // lifetime count is pre-truncation
67
+ });
68
+
69
+ it("keeps head + tail with a marker when the cap trips", () => {
70
+ const rb = new RingBuffer();
71
+ rb.push("HEAD-LINE\n");
72
+ rb.push("x".repeat(TOTAL_BYTES) + "\n");
73
+ rb.push("TAIL-LINE\n");
74
+ const lines = rb.lines();
75
+ assert.equal(lines[0], "HEAD-LINE");
76
+ assert.equal(lines.at(-1), "TAIL-LINE");
77
+ const marker = lines.find((l) => l.startsWith("[…"));
78
+ assert.ok(marker, "has a truncation marker line");
79
+ assert.match(marker!, /^\[… \d+(?:\.\d+)? (Ki?B|bytes) truncated …\]$/);
80
+ });
81
+
82
+ it("truncationMarker formats", () => {
83
+ assert.equal(truncationMarker(5), "[… 5 bytes truncated …]");
84
+ });
85
+ });
86
+
87
+ // ── ids + resolution ────────────────────────────────────────────────────────
88
+
89
+ describe("ids and resolveSession", () => {
90
+ it("nextId is monotonic; resetIdCounter resets", () => {
91
+ resetIdCounter(0);
92
+ assert.equal(nextId(), "s1");
93
+ assert.equal(nextId(), "s2");
94
+ resetIdCounter(9);
95
+ assert.equal(nextId(), "s10");
96
+ resetIdCounter();
97
+ });
98
+
99
+ function session(over: Partial<ShellSession>): ShellSession {
100
+ return {
101
+ id: "s1",
102
+ pid: 1,
103
+ child: {} as never,
104
+ cwd: "/",
105
+ command: "true",
106
+ startedAt: Date.now(),
107
+ stdout: new RingBuffer(),
108
+ stderr: new RingBuffer(),
109
+ lastOutputOffset: 0,
110
+ ...over,
111
+ };
112
+ }
113
+
114
+ it("resolves by id first, then unique name", () => {
115
+ const store = new SessionStore();
116
+ const a = session({ id: "s1", name: "dev" });
117
+ const b = session({ id: "s2" });
118
+ store.add(a);
119
+ store.add(b);
120
+ assert.equal(resolveSession(store, "s2"), b);
121
+ assert.equal(resolveSession(store, "dev"), a);
122
+ });
123
+
124
+ it("ambiguous name errors with the listing; unknown errors too", () => {
125
+ const store = new SessionStore();
126
+ store.add(session({ id: "s1", name: "dev" }));
127
+ store.add(session({ id: "s2", name: "dev" }));
128
+ assert.throws(() => resolveSession(store, "dev"), /ambiguous.*dev/s);
129
+ assert.throws(() => resolveSession(store, "nope"), /no session 'nope'/);
130
+ });
131
+ });
132
+
133
+ // ── SessionStore ────────────────────────────────────────────────────────────
134
+
135
+ describe("SessionStore", () => {
136
+ function live(over: Partial<ShellSession>): ShellSession {
137
+ return {
138
+ id: `s${Math.random()}`,
139
+ pid: 1,
140
+ child: {} as never,
141
+ cwd: "/",
142
+ command: "true",
143
+ startedAt: Date.now(),
144
+ stdout: new RingBuffer(),
145
+ stderr: new RingBuffer(),
146
+ lastOutputOffset: 0,
147
+ ...over,
148
+ };
149
+ }
150
+
151
+ it("refuses an 11th live session, listing them", () => {
152
+ const store = new SessionStore();
153
+ for (let i = 0; i < 10; i++) store.add(live({ id: `s${i}` }));
154
+ assert.throws(() => store.add(live({ id: "s11" })), /refusing to start an 11th live shell session[\s\S]*s9/);
155
+ // Exited sessions don't count toward the live cap.
156
+ const dead = live({ id: "sx", exitedAt: Date.now(), exitCode: 0 });
157
+ store.add(dead);
158
+ assert.equal(store.list().length, 11);
159
+ });
160
+
161
+ it("evictOldestExited keeps at most 5 exited", () => {
162
+ const store = new SessionStore();
163
+ for (let i = 0; i < 7; i++) store.add(live({ id: `d${i}`, exitedAt: 1_000 + i, exitCode: 0 }));
164
+ let evicted = 0;
165
+ while (store.evictOldestExited()) evicted++;
166
+ assert.equal(evicted, 2);
167
+ assert.equal(store.list().length, 5);
168
+ assert.equal(store.list()[0]!.id, "d2"); // oldest two gone
169
+ });
170
+
171
+ it("killAll skips exited sessions and escalates for live ones", { timeout: 10_000 }, async () => {
172
+ const store = new SessionStore();
173
+ const fc = fakeChild();
174
+ const s = store.list().length; // 0
175
+ store.add({
176
+ id: "s1", pid: fc.child.pid, child: fc.child, cwd: "/", command: "x",
177
+ startedAt: Date.now(), stdout: new RingBuffer(), stderr: new RingBuffer(), lastOutputOffset: 0,
178
+ });
179
+ store.add({
180
+ id: "s2", pid: 1, child: fakeChild().child, cwd: "/", command: "x",
181
+ startedAt: Date.now(), exitedAt: Date.now(), exitCode: 0,
182
+ stdout: new RingBuffer(), stderr: new RingBuffer(), lastOutputOffset: 0,
183
+ });
184
+ await store.killAll("SIGTERM");
185
+ // Group signal fails (bogus pid) → falls back to child.kill; escalation
186
+ // to SIGKILL after the 2s wait hits the live session only.
187
+ assert.ok(fc.killCalls.includes("SIGTERM"));
188
+ assert.ok(fc.killCalls.includes("SIGKILL"));
189
+ assert.equal(s, 0);
190
+ });
191
+ });
192
+
193
+ // ── createSession ───────────────────────────────────────────────────────────
194
+
195
+ describe("createSession", () => {
196
+ it("wires streams, exit, stdin; rejects duplicate live names", () => {
197
+ const store = new SessionStore();
198
+ resetIdCounter(0);
199
+ const fc = fakeChild();
200
+ const s = createSession(store, () => fc.child as never, { command: "npm run dev", cwd: "/", name: "dev" });
201
+ assert.equal(s.id, "s1");
202
+ assert.equal(s.pid, 42_424);
203
+ fc.child.stdout.emit("data", Buffer.from("hello\n"));
204
+ fc.child.stderr.emit("data", Buffer.from("oops\n"));
205
+ assert.deepEqual(s.stdout.lines(), ["hello"]);
206
+ assert.deepEqual(s.stderr.lines(), ["oops"]);
207
+ assert.throws(() => createSession(store, noopSpawn, { command: "x", cwd: "/", name: "dev" }), /already exists/);
208
+ // Exit marks the session and frees the name.
209
+ fc.emitExit(0);
210
+ assert.equal(s.exitedAt !== undefined, true);
211
+ const again = createSession(store, noopSpawn, { command: "x", cwd: "/", name: "dev" });
212
+ assert.equal(again.id, "s2");
213
+ });
214
+
215
+ it("spawn failure cleans up the placeholder", () => {
216
+ const store = new SessionStore();
217
+ assert.throws(() => createSession(store, () => { throw new Error("bad cwd"); }, { command: "x", cwd: "/" }), /failed to start 'x': bad cwd/);
218
+ assert.equal(store.list().length, 0);
219
+ });
220
+
221
+ it("killSession escalates to SIGKILL after the wait", async () => {
222
+ const store = new SessionStore();
223
+ const fc = fakeChild(); // never emits exit on its own
224
+ const s = createSession(store, () => fc.child as never, { command: "sleep 30", cwd: "/" });
225
+ const started = Date.now();
226
+ const r = await killSession(s, "SIGTERM", 60);
227
+ assert.ok(Date.now() - started >= 50);
228
+ assert.equal(r.signal, "SIGKILL");
229
+ assert.ok(fc.killCalls.length >= 1);
230
+ });
231
+
232
+ it("killSession returns early for already-exited sessions", async () => {
233
+ const store = new SessionStore();
234
+ const fc = fakeChild();
235
+ const s = createSession(store, () => fc.child as never, { command: "x", cwd: "/" });
236
+ fc.emitExit(3);
237
+ const r = await killSession(s);
238
+ assert.equal(r.code, 3);
239
+ });
240
+ });
241
+
242
+ // ── REAL spawn integration (posix) ──────────────────────────────────────────
243
+
244
+ const posixIt = process.platform === "win32" ? it.skip : it;
245
+
246
+ describe("real spawns", () => {
247
+ const tmp = os.tmpdir();
248
+
249
+ posixIt("echo lands in the buffer via createSession", async () => {
250
+ const store = new SessionStore();
251
+ const s = createSession(store, realSpawn as unknown as SpawnFn, { command: "echo real-hello", cwd: tmp });
252
+ assert.notEqual(s.pid, 0);
253
+ // Wait for exit + buffer flush (event-driven, capped).
254
+ await new Promise<void>((r) => {
255
+ const t = setInterval(() => {
256
+ if (s.exitedAt !== undefined && s.stdout.lines().length > 0) {
257
+ clearInterval(t);
258
+ r();
259
+ }
260
+ }, 25);
261
+ setTimeout(() => { clearInterval(t); r(); }, 5_000);
262
+ });
263
+ assert.deepEqual(s.stdout.lines(), ["real-hello"]);
264
+ await killSession(s, "SIGKILL", 500).catch(() => {});
265
+ });
266
+
267
+ posixIt("killAll reaps a sleep child (process group)", async () => {
268
+ const store = new SessionStore();
269
+ const s = createSession(store, realSpawn as unknown as SpawnFn, { command: "sleep 30", cwd: tmp });
270
+ await store.killAll("SIGKILL");
271
+ assert.ok(s.exitedAt !== undefined || s.exitCode !== null || s.child.killed);
272
+ });
273
+ });
274
+
275
+ after(() => resetIdCounter());
@@ -62,6 +62,7 @@ import {
62
62
  MAX_PARALLEL_TASKS,
63
63
  MAX_CHAIN_LENGTH,
64
64
  MAX_INSTRUCTIONS_LENGTH,
65
+ MAX_TIMEOUT_MS,
65
66
  } from "./lib/security.ts";
66
67
  import {
67
68
  aggregateUsage,
@@ -152,7 +153,7 @@ const TaskItem = Type.Object({
152
153
  task: Type.String({ description: "Task to delegate to the agent" }),
153
154
  cwd: Type.Optional(Type.String({ description: "Working directory for the agent" })),
154
155
  solutionSpace: Type.Optional(Type.String({ description: "How open-ended this task's problem is — feeds model-tier/thinking routing." })),
155
- timeout: Type.Optional(Type.Number({ description: "Inactivity timeout in ms; aborts on no activity within timeout. Default: 3 min (PI_SUBAGENT_INACTIVITY_TIMEOUT_MINS). The agent always has a lifetime cap: default 20 min or (PI_SUBAGENT_HARD_TIMEOUT_MINS)." })),
156
+ timeout: Type.Optional(Type.Number({ description: "Inactivity timeout in ms; aborts after this long with no child activity. Default: 3 min (subagent.idleTimeoutMins). Hard lifetime cap is opt-in via subagent.hardTimeoutMins (default off); herdr panes are additionally capped at 60 min wall clock." })),
156
157
  merge: Type.Optional(StringEnum(["3way"] as const, { description: "With a worktree-sandboxed agent, apply its diff to the parent checkout via git apply --3way after it completes. Conflicts are reported, not resolved. Default: patch returned only." })),
157
158
  });
158
159
 
@@ -160,7 +161,7 @@ const ChainItem = Type.Object({
160
161
  agent: Type.String({ description: "Name of the agent to invoke" }),
161
162
  task: Type.String({ description: "Task with optional {previous} placeholder for prior output" }),
162
163
  cwd: Type.Optional(Type.String({ description: "Working directory for the agent" })),
163
- timeout: Type.Optional(Type.Number({ description: "Inactivity timeout in ms; aborts on no activity within timeout. Default: 3 min (PI_SUBAGENT_INACTIVITY_TIMEOUT_MINS). The agent always has a lifetime cap: default 20 min or (PI_SUBAGENT_HARD_TIMEOUT_MINS)." })),
164
+ timeout: Type.Optional(Type.Number({ description: "Inactivity timeout in ms; aborts after this long with no child activity. Default: 3 min (subagent.idleTimeoutMins). Hard lifetime cap is opt-in via subagent.hardTimeoutMins (default off); herdr panes are additionally capped at 60 min wall clock." })),
164
165
  merge: Type.Optional(StringEnum(["3way"] as const, { description: "With a worktree-sandboxed agent, apply its diff to the parent checkout via git apply --3way after the step completes. Conflicts are reported, not resolved." })),
165
166
  });
166
167
 
@@ -203,7 +204,7 @@ const SubagentParams = Type.Object({
203
204
  // Project-agent confirmation is enforced via trusted configuration.
204
205
  // See Security model section in README.
205
206
  cwd: Type.Optional(Type.String({ description: "Working directory (single mode, must be inside workspace)" })),
206
- timeout: Type.Optional(Type.Number({ description: "Inactivity timeout for the whole run, in ms; resets on activity, aborts on silence. Default 3 min (PI_SUBAGENT_INACTIVITY_TIMEOUT_MINS). Lifetime cap: 20 min or (PI_SUBAGENT_HARD_TIMEOUT_MINS)." })),
207
+ timeout: Type.Optional(Type.Number({ description: "Inactivity timeout in ms; aborts after this long with no child activity. Default: 3 min (subagent.idleTimeoutMins). Hard lifetime cap is opt-in via subagent.hardTimeoutMins (default off); herdr panes are additionally capped at 60 min wall clock." })),
207
208
  merge: Type.Optional(StringEnum(["3way"] as const, { description: "Single mode: with a worktree-sandboxed agent, apply its diff to the parent checkout via git apply --3way after it completes. Conflicts are reported, not resolved. Default: patch returned only." })),
208
209
  instructions: Type.Optional(Type.String({ description: "Bounded repository/task instructions passed to each child (max 16 KB)" })),
209
210
  solutionSpace: Type.Optional(Type.String({ description: "Single/parallel mode: how open-ended the child's problem is (design given vs choices open). Feeds model-tier/thinking routing; never mention siblings. e.g. 'one fix: rename, names given' vs 'several retry API shapes; error classes to choose'." })),
@@ -1086,10 +1087,15 @@ ${lines.join("\n")}`;
1086
1087
  return { error: `No model resolved for agent "${agentName}" (tried: ${resolved.attempted.join(", ") || "none"}).` };
1087
1088
  }
1088
1089
  // herdr children run full pi — they need SOME lifetime cap so an
1089
- // unattended pane can't run forever; fall back to the idle window.
1090
+ // unattended pane can't run forever. The IDLE window is NOT a lifetime
1091
+ // cap (live incident 2026-10-06: a healthy 13-min chapter write was
1092
+ // abandoned at the default 3-min idle window — the pane kept working,
1093
+ // the parent read "timeout"). Wall-clock cap = the OPT-IN hard cap;
1094
+ // when it is off, the unattended-pane guard is the MAX absolute cap
1095
+ // (60 min), NOT the idle window.
1090
1096
  const timeouts = resolveChildTimeouts({ requested: timeoutMs, agentTimeoutMins: agent.timeout, idleTimeoutMins: subSettings.idleTimeoutMins, hardTimeoutMins: subSettings.hardTimeoutMins });
1091
1097
  if (timeouts.error) return { error: timeouts.error };
1092
- const hardTimeoutMs = timeouts.hardTimeoutMs ?? timeouts.timeoutMs ?? 0;
1098
+ const hardTimeoutMs = timeouts.hardTimeoutMs ?? MAX_TIMEOUT_MS;
1093
1099
  if (!hardTimeoutMs) return { error: "Invalid herdr timeout configuration." };
1094
1100
  const safe = resolveSafeCwd({ workspaceRoot, childCwd: cwd, allowExternalCwd });
1095
1101
  if (safe.error) return { error: safe.error };
@@ -982,6 +982,11 @@ export async function executeHerdrTask(
982
982
  if (timedOut) {
983
983
  // Wall-clock cap: interrupt the child so it stops burning tokens.
984
984
  await cancelAgent(handle.name, exec);
985
+ // The interrupt is best-effort (esc/ctrl+c to a TUI); a pane deep in a
986
+ // tool call can finish its current write AFTER this result returns —
987
+ // say so instead of implying the pane is gone (live incident: parent
988
+ // read "timeout", child completed and wrote its file 10 min later).
989
+ prompt.error = `${prompt.error} (pane interrupted; it may still complete its current write — check ${path.basename(handle.resultFile)} or the pane before re-dispatching)`;
985
990
  } else if (!aborted) {
986
991
  advisorRounds = await awaitAdvisorCycle({
987
992
  name: handle.name,
@@ -128,7 +128,7 @@ export async function classifyTask(
128
128
  task: string,
129
129
  solutionSpace: string | undefined,
130
130
  roles: RolesConfig,
131
- opts: { askDispatch?: boolean } = {},
131
+ opts: { askDispatch?: boolean; deadlineMs?: number } = {},
132
132
  ): Promise<RoutingVerdict | undefined> {
133
133
  if (settings.mode !== "classify") return undefined;
134
134
  const pins = pinsFor(agent, roles);
@@ -145,7 +145,19 @@ export async function classifyTask(
145
145
  const wantDispatch = opts.askDispatch === true;
146
146
 
147
147
  try {
148
- const result = await ctx.modelRegistry.classify(
148
+ // Belt-and-braces deadline: routing is advisory, so NOTHING about it may
149
+ // hang a dispatch. The systemone transport carries its own default
150
+ // timeout, but a provider that ignores the signal (the transport
151
+ // contract only says "never rejects") must not park the dispatch — RACE
152
+ // the ask against a hard cap and fail open to the static chain (live
153
+ // incident 2026-10-06: two dispatches stuck 8h on a silent endpoint).
154
+ const deadlineMs = opts.deadlineMs ?? 45_000;
155
+ const deadline = AbortSignal.timeout(deadlineMs);
156
+ const timedOut = new Promise<{ __deadline: true }>((resolve) => {
157
+ deadline.addEventListener("abort", () => resolve({ __deadline: true }), { once: true });
158
+ });
159
+ const result = (await Promise.race([
160
+ ctx.modelRegistry.classify(
149
161
  model as never,
150
162
  {
151
163
  state: {
@@ -180,10 +192,16 @@ export async function classifyTask(
180
192
  : {}),
181
193
  },
182
194
  } as never,
183
- );
184
- if (result.stopReason !== "stop") {
195
+ { signal: deadline } as never,
196
+ ),
197
+ timedOut,
198
+ ])) as { __deadline?: true; stopReason?: string; errorMessage?: string; answers?: Record<string, unknown> };
199
+ if (result.__deadline) {
200
+ return { applied: false, reason: `classifier deadline (${deadlineMs}ms) — failing open to static chain` };
201
+ }
202
+ if (result.stopReason !== "stop" || !result.answers) {
185
203
  if (process.env.CEULEN_ROUTING_DEBUG) process.stderr.write(`[routing] stopReason=${result.stopReason} err=${result.errorMessage ?? "-"}\n`);
186
- return { applied: false, reason: `classifier ${result.stopReason}` };
204
+ return { applied: false, reason: `classifier ${result.stopReason ?? "no answers"}` };
187
205
  }
188
206
 
189
207
  const tierAnswer = result.answers.tier as { choice?: string; probabilities?: Record<string, number> } | undefined;
@@ -212,9 +230,14 @@ export async function classifyTask(
212
230
  if (wantDispatch) {
213
231
  const dispatchAnswer = result.answers.dispatch as { choice?: string; probabilities?: Record<string, number> } | undefined;
214
232
  if (dispatchAnswer?.choice === "pane" || dispatchAnswer?.choice === "background") {
215
- const probs = dispatchAnswer.probabilities ?? {};
216
- const top = Math.max(...Object.values(probs), 0);
217
- if (top >= settings.threshold) dispatch = dispatchAnswer.choice;
233
+ // Gate on the CHOSEN label's own probability — a high-probability
234
+ // rival must not clear the threshold for a low-confidence choice,
235
+ // and a missing/out-of-range value fails open to the pane default
236
+ // (same rule as the tier gate above).
237
+ const prob = dispatchAnswer.probabilities?.[dispatchAnswer.choice];
238
+ if (typeof prob === "number" && Number.isFinite(prob) && prob >= 0 && prob <= 1 && prob >= settings.threshold) {
239
+ dispatch = dispatchAnswer.choice;
240
+ }
218
241
  }
219
242
  }
220
243
 
@@ -295,7 +295,10 @@ export async function runSubAgent(options: {
295
295
  } as any);
296
296
  session = created.session;
297
297
  } catch (error) {
298
- if (worktreeDir) await removeWorktree(cwd, worktreeDir, exec);
298
+ // Lock on the RESOLVED repo root (createWorktree/applyWorktreePatch3way do): a
299
+ // child dispatched with a subdirectory cwd must not key the per-repo lock
300
+ // differently — parallel siblings would race git's O_EXCL index.lock.
301
+ if (worktreeDir) await removeWorktree(worktreeRepoRoot ?? cwd, worktreeDir, exec);
299
302
  throw error;
300
303
  }
301
304
  let unsubscribe: (() => void) | undefined;
@@ -370,7 +373,10 @@ export async function runSubAgent(options: {
370
373
  } finally {
371
374
  unsubscribe?.(); removeAbort?.();
372
375
  try { session.dispose(); } catch { /* best effort */ }
373
- if (worktreeDir) await removeWorktree(cwd, worktreeDir, exec);
376
+ // Lock on the RESOLVED repo root (createWorktree/applyWorktreePatch3way do): a
377
+ // child dispatched with a subdirectory cwd must not key the per-repo lock
378
+ // differently — parallel siblings would race git's O_EXCL index.lock.
379
+ if (worktreeDir) await removeWorktree(worktreeRepoRoot ?? cwd, worktreeDir, exec);
374
380
  }
375
381
  } catch (error) {
376
382
  result.exitCode = 1;
@@ -509,6 +509,51 @@ test("classifyTask: a confident dispatch answer alone counts as applied", async
509
509
  assert.equal(verdict?.applied, true, "dispatch alone can carry the verdict");
510
510
  });
511
511
 
512
+ test("classifyTask: dispatch gates on the CHOSEN label's own probability — a high rival must not clear it", async () => {
513
+ // Live-found defect (reviewer 2026-10-06): the old gate took Math.max over
514
+ // ALL probabilities, so choice "background" at 0.4 applied because rival
515
+ // "pane" scored 0.65 — silently detaching a task the classifier wanted in
516
+ // a pane. Mirrors the tier question's chosen-label rule.
517
+ const rival = dispatchCtx({
518
+ ...TIER_AND_EFFORT,
519
+ dispatch: { choice: "background", probabilities: { background: 0.4, pane: 0.65 } },
520
+ });
521
+ const v1 = await classifyTask(rival, { ...DEFAULT_ROUTING, mode: "classify" }, WORKER, "long job", undefined, ROLES, { askDispatch: true });
522
+ assert.equal(v1?.dispatch, undefined, "rival probability must not clear the threshold for the choice");
523
+
524
+ const confident = dispatchCtx({
525
+ ...TIER_AND_EFFORT,
526
+ dispatch: { choice: "background", probabilities: { background: 0.72, pane: 0.28 } },
527
+ });
528
+ const v2 = await classifyTask(confident, { ...DEFAULT_ROUTING, mode: "classify" }, WORKER, "long job", undefined, ROLES, { askDispatch: true });
529
+ assert.equal(v2?.dispatch, "background");
530
+
531
+ // Out-of-range / bogus probabilities fail open (no dispatch override).
532
+ const bogus = dispatchCtx({
533
+ ...TIER_AND_EFFORT,
534
+ dispatch: { choice: "background", probabilities: { background: 7 } },
535
+ });
536
+ const v3 = await classifyTask(bogus, { ...DEFAULT_ROUTING, mode: "classify" }, WORKER, "long job", undefined, ROLES, { askDispatch: true });
537
+ assert.equal(v3?.dispatch, undefined, "out-of-range probability fails open to the pane default");
538
+ });
539
+
540
+ test("classifyTask: a never-resolving classify hits the deadline and fails open to the static chain", async () => {
541
+ // The 2026-10-06 live incident class: a silent endpoint parked the dispatch
542
+ // forever. The deadline race must return a fail-open verdict instead.
543
+ const ctx = {
544
+ modelRegistry: {
545
+ getAvailableOfType: async () => [{ provider: "router", id: "jev" }],
546
+ classify: () => new Promise(() => {}),
547
+ },
548
+ } as never;
549
+ const t0 = Date.now();
550
+ const verdict = await classifyTask(ctx, { ...DEFAULT_ROUTING, mode: "classify" }, WORKER, "anything", undefined, ROLES, { deadlineMs: 100 });
551
+ const ms = Date.now() - t0;
552
+ assert.ok(ms < 2_000, `deadline raced (${ms}ms) instead of hanging`);
553
+ assert.equal(verdict?.applied, false, "deadline expiry fails open");
554
+ assert.match(verdict?.reason ?? "", /deadline/);
555
+ });
556
+
512
557
  test("classifyTask: an unresolvable chain suppresses the tier question (typo fails loud, not papered over)", async () => {
513
558
  let asked: Record<string, unknown> = {};
514
559
  const ctx = dispatchCtx(
@@ -12,6 +12,7 @@ import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
12
12
  import { row, type PanelGroup } from "../../lib/panel.js";
13
13
  import type { ModuleConfig } from "../../lib/registry.js";
14
14
  import { agentDirs } from "../../lib/registry.js";
15
+ import { writeSecretEnvs } from "../../lib/env.js";
15
16
  import { findEnvValue } from "./lib/config.js";
16
17
  import {
17
18
  DEFAULT_SEARXNG_BASE_URL,
@@ -21,9 +22,19 @@ import {
21
22
  import {
22
23
  ENV_TO_SETTINGS_KEY,
23
24
  readProjectWebSection,
25
+ readWebSettings,
24
26
  sectionValue,
25
27
  writeWebSection,
26
28
  } from "./lib/settings.js";
29
+ import { secretsEnvFile } from "../../lib/env.js";
30
+
31
+ function secretsEnvFilePath(): string {
32
+ return secretsEnvFile();
33
+ }
34
+
35
+ function readWebSettingsGlobal() {
36
+ return readWebSettings(process.cwd(), false);
37
+ }
27
38
 
28
39
  /** One row's definition: settings key, label, effective value, default. */
29
40
  interface WebRowSpec {
@@ -136,7 +147,7 @@ export function buildWebGroups(working: Record<string, string>): PanelGroup[] {
136
147
  } : {}),
137
148
  description: spec.description,
138
149
  ...(spec.secret
139
- ? { warning: "Stored in the settings file — prefer the env var on shared machines." }
150
+ ? { warning: "Saved to <agentDir>/.env.local (0600) — never settings.json. The matching env var overrides any settings value." }
140
151
  : {}),
141
152
  },
142
153
  ),
@@ -174,7 +185,11 @@ export function diffWebPatch(
174
185
 
175
186
  /** web's ModuleConfig for the central /config panel. cwd/trust come from the
176
187
  * save ctx (factories receive none); reads use process.cwd(), matching
177
- * munin's panel pattern. */
188
+ * munin's panel pattern. SECRET rows persist to <agentDir>/.env.local (0600)
189
+ * — never settings.json (live finding: real API keys sat in plaintext
190
+ * settings.json). Env already wins at read time, so the effective value is
191
+ * unchanged; the first save also MIGRATES any settings-stored secret into
192
+ * .env.local and scrubs it from settings.json. */
178
193
  export function webConfig(): ModuleConfig {
179
194
  const read = () => {
180
195
  const values = readWebRowValues(process.cwd(), true);
@@ -192,11 +207,55 @@ export function webConfig(): ModuleConfig {
192
207
  // written (masked rows start empty — an untouched masked row diffs to
193
208
  // no change).
194
209
  const patch = diffWebPatch(working, before);
195
- writeWebSection(patch, target);
196
- const notes = [`Web config saved to ${target} — effective immediately (read per tool call).`];
197
- // Disclose env vars that still override saved values, and a trusted
198
- // project file that shadows a field.
199
- const envOverrides = webRowSpecs().filter((s) => patch[s.key] !== undefined && process.env[s.envVar]).map((s) => s.envVar);
210
+ const specs = webRowSpecs();
211
+ const preSaveEnv = new Set(Object.keys(process.env).filter((k) => specs.some((s) => s.envVar === k)));
212
+ const secretPatch: Record<string, string> = {};
213
+ const settingsPatch: Record<string, string | number> = {};
214
+ for (const [key, value] of Object.entries(patch)) {
215
+ const spec = specs.find((s) => s.key === key);
216
+ // Secrets (typed this session) → .env.local only. A value that CLEARS a
217
+ // secret row (empty string) is dropped: deleting the env line would
218
+ // re-expose a settings-stored value or leave nothing — clearing is a
219
+ // rare deliberate act, do it by editing .env.local by hand.
220
+ if (spec?.secret && value !== "") {
221
+ secretPatch[spec.envVar] = String(value);
222
+ } else if (spec?.secret && value === "") {
223
+ continue;
224
+ } else {
225
+ settingsPatch[key] = value;
226
+ }
227
+ }
228
+ // Migration: secrets already sitting in settings.json (pre-fix saves)
229
+ // move into .env.local (onlyAbsent — env was already winning) and are
230
+ // scrubbed from settings.json. URL rows stay in settings.json untouched.
231
+ const migrate: Record<string, string> = {};
232
+ for (const spec of specs) {
233
+ if (!spec.secret) continue;
234
+ if (secretPatch[spec.envVar] !== undefined) continue;
235
+ const stored = sectionValue(readWebSettingsGlobal(), spec.key);
236
+ if (typeof stored === "string" && stored !== "") migrate[spec.envVar] = stored;
237
+ }
238
+ if (Object.keys(migrate).length > 0) writeSecretEnvs(migrate, { onlyAbsent: true });
239
+ const scrubKeys = Object.keys(migrate);
240
+ if (scrubKeys.length > 0) {
241
+ const scrubPatch: Record<string, string> = {};
242
+ for (const envName of scrubKeys) {
243
+ const spec = specs.find((s) => s.envVar === envName)!;
244
+ scrubPatch[spec.key] = ""; // writeWebSection deletes empty keys
245
+ }
246
+ writeWebSection(scrubPatch, target);
247
+ }
248
+ const written = Object.keys(secretPatch).length > 0 ? writeSecretEnvs(secretPatch) : [];
249
+ if (Object.keys(settingsPatch).length > 0) writeWebSection(settingsPatch, target);
250
+ const notes = [] as string[];
251
+ if (written.length) notes.push(`Secrets saved to ${secretsEnvFilePath()} — effective immediately (env wins at read time).`);
252
+ if (scrubKeys.length) notes.push(`Migrated ${scrubKeys.length} secret(s) out of settings.json into .env.local.`);
253
+ if (Object.keys(settingsPatch).length > 0) notes.push(`Web config saved to ${target} — effective immediately (read per tool call).`);
254
+ // Disclose env vars that PRE-EXISTED this save and still override it.
255
+ // Snapshot BEFORE writeSecretEnvs mirrors the new values into
256
+ // process.env — otherwise every edited secret row would falsely read
257
+ // as "still overridden by env" (it just became the env value).
258
+ const envOverrides = specs.filter((s) => patch[s.key] !== undefined && preSaveEnv.has(s.envVar)).map((s) => s.envVar);
200
259
  if (envOverrides.length) notes.push(`Still overridden by env: ${envOverrides.join(", ")}.`);
201
260
  // Resolve through the SAME lookup the runtime uses, so a hand-written
202
261
  // NESTED project entry (web.brave.apiKey as {brave:{apiKey}}) is
@@ -209,7 +268,7 @@ export function webConfig(): ModuleConfig {
209
268
  })
210
269
  : [];
211
270
  if (shadowed.length) notes.push(`A trusted project .pi/settings.json web section shadows: ${shadowed.join(", ")}.`);
212
- ctx.ui.notify(notes.join(" "), "info");
271
+ if (notes.length) ctx.ui.notify(notes.join(" "), "info");
213
272
  },
214
273
  };
215
274
  }