ceulen 0.11.0 → 0.12.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 (36) hide show
  1. package/CHANGELOG.md +51 -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 +8 -3
  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 +1 -1
  16. package/extensions/modules/repair/index.ts +26 -2
  17. package/extensions/modules/repair/test/freshness.test.ts +41 -1
  18. package/extensions/modules/repair/test/guard-selector.test.ts +67 -0
  19. package/extensions/modules/router/configPanel.ts +4 -4
  20. package/extensions/modules/router/index.ts +1 -1
  21. package/extensions/modules/router/lib/config.ts +9 -4
  22. package/extensions/modules/router/lib/systemone.ts +17 -4
  23. package/extensions/modules/router/test/unit.test.ts +46 -1
  24. package/extensions/modules/rules/index.ts +13 -3
  25. package/extensions/modules/rules/lib/rules.ts +24 -12
  26. package/extensions/modules/rules/test/lib.test.ts +20 -0
  27. package/extensions/modules/rules/test/module.test.ts +21 -0
  28. package/extensions/modules/subagent/index.ts +11 -5
  29. package/extensions/modules/subagent/lib/herdr.ts +5 -0
  30. package/extensions/modules/subagent/lib/routing.ts +31 -8
  31. package/extensions/modules/subagent/lib/runner.ts +8 -2
  32. package/extensions/modules/subagent/test/routing.test.ts +45 -0
  33. package/extensions/modules/web/configPanel.ts +67 -8
  34. package/extensions/modules/web/test/configPanel.test.ts +7 -3
  35. package/extensions/modules/web/test/settings.test.ts +6 -0
  36. package/package.json +2 -2
@@ -28,6 +28,16 @@ import { clearRuleCache, loadRules, type RuleModel } from "./lib/rules";
28
28
  /** Cap on a single rule body returned by rule_get (chars). */
29
29
  const RULE_GET_MAX_CHARS = 20000;
30
30
 
31
+ /** Trust gate (AGENTS.md/subagent convention): an untrusted checkout's
32
+ * RULES.md must not reach the system prompt or rule_get. Fail closed. */
33
+ function projectTrusted(ctx: { isProjectTrusted?: () => boolean } | undefined): boolean {
34
+ try {
35
+ return ctx?.isProjectTrusted?.() === true;
36
+ } catch {
37
+ return false;
38
+ }
39
+ }
40
+
31
41
  function statusLines(model: RuleModel, cwd: string): string {
32
42
  if (model.files.length === 0) {
33
43
  return [
@@ -54,7 +64,7 @@ export default function rulesExtension(pi: ExtensionAPI): void {
54
64
  pi.on("before_agent_start", async (event, ctx): Promise<BeforeAgentStartEventResult | undefined> => {
55
65
  let model: RuleModel;
56
66
  try {
57
- model = loadRules(ctx?.cwd ?? process.cwd());
67
+ model = loadRules(ctx?.cwd ?? process.cwd(), undefined, projectTrusted(ctx));
58
68
  } catch {
59
69
  return undefined; // never break a turn over rule discovery
60
70
  }
@@ -73,7 +83,7 @@ export default function rulesExtension(pi: ExtensionAPI): void {
73
83
  }),
74
84
  defaultActive: !disabledTools.has("rule_get"),
75
85
  async execute(_id: string, params: { name: string }, _signal, _onUpdate, ctx) {
76
- const model = loadRules(ctx?.cwd ?? process.cwd());
86
+ const model = loadRules(ctx?.cwd ?? process.cwd(), undefined, projectTrusted(ctx));
77
87
  const wanted = (params.name ?? "").trim();
78
88
  const rule = model.rules.find((item) => item.name === wanted);
79
89
  if (!rule) {
@@ -114,7 +124,7 @@ export default function rulesExtension(pi: ExtensionAPI): void {
114
124
  ctx.ui.notify(`[rules] unknown argument "${arg}" — use /rules or /rules reload`, "error");
115
125
  return;
116
126
  }
117
- ctx.ui.notify(statusLines(loadRules(ctx.cwd), ctx.cwd), "info");
127
+ ctx.ui.notify(statusLines(loadRules(ctx.cwd, undefined, projectTrusted(ctx)), ctx.cwd), "info");
118
128
  },
119
129
  });
120
130
  }
@@ -142,15 +142,21 @@ export function defaultUserRulesDir(): string {
142
142
  }
143
143
 
144
144
  /** `<dir>/.pi/RULES.md` from cwd up to the filesystem root, then the user file. */
145
- export function discoverRuleFiles(cwd: string, userDir = defaultUserRulesDir()): string[] {
145
+ export function discoverRuleFiles(cwd: string, userDir = defaultUserRulesDir(), trusted = true): string[] {
146
146
  const files: string[] = [];
147
- let dir = path.resolve(cwd);
148
- for (;;) {
149
- const candidate = path.join(dir, PROJECT_DIR, RULES_FILE);
150
- if (existsSync(candidate)) files.push(candidate);
151
- const parent = path.dirname(dir);
152
- if (parent === dir) break;
153
- dir = parent;
147
+ // Untrusted project: repo-controlled RULES.md (and its @imports) must never
148
+ // reach the system prompt — the same gate as pi's AGENTS.md context files
149
+ // and every other project-file consumer here (subagent agents, settings
150
+ // overlays). Only the user-level file applies.
151
+ if (trusted) {
152
+ let dir = path.resolve(cwd);
153
+ for (;;) {
154
+ const candidate = path.join(dir, PROJECT_DIR, RULES_FILE);
155
+ if (existsSync(candidate)) files.push(candidate);
156
+ const parent = path.dirname(dir);
157
+ if (parent === dir) break;
158
+ dir = parent;
159
+ }
154
160
  }
155
161
  const user = path.join(userDir, RULES_FILE);
156
162
  if (existsSync(user)) files.push(user);
@@ -193,6 +199,13 @@ function expandImports(text: string, baseDir: string, state: ImportState, depth:
193
199
  if (state.seen.has(resolved)) return whole;
194
200
 
195
201
  let content: string;
202
+ // Track the target even when the read FAILS: a previously-missing
203
+ // import being CREATED must invalidate the cache — signature() emits
204
+ // `<file>:missing` for absent entries, so the existence flip changes
205
+ // the signature and the next load re-reads (live finding, reviewer
206
+ // 2026-10-06 — creating the file a missing-marker points at is the
207
+ // most likely user fix, and it silently kept serving the marker).
208
+ state.read.add(resolved);
196
209
  try {
197
210
  content = readFileSync(resolved, "utf8");
198
211
  } catch {
@@ -202,7 +215,6 @@ function expandImports(text: string, baseDir: string, state: ImportState, depth:
202
215
  return `${lead}[import depth limit reached: @${cleaned}]`;
203
216
  }
204
217
  state.seen.add(resolved);
205
- state.read.add(resolved);
206
218
  const nested = expandImports(content.trim(), path.dirname(resolved), state, depth + 1);
207
219
  return `${lead}${nested}`;
208
220
  });
@@ -282,9 +294,9 @@ export function clearRuleCache(): void {
282
294
  cache = null;
283
295
  }
284
296
 
285
- export function loadRules(cwd = process.cwd(), userDir = defaultUserRulesDir()): RuleModel {
286
- const key = `${path.resolve(cwd)}\u0000${userDir}`;
287
- const files = discoverRuleFiles(cwd, userDir);
297
+ export function loadRules(cwd = process.cwd(), userDir = defaultUserRulesDir(), trusted = true): RuleModel {
298
+ const key = `${path.resolve(cwd)}\u0000${userDir}\u0000${trusted ? "t" : "u"}`;
299
+ const files = discoverRuleFiles(cwd, userDir, trusted);
288
300
  // Track RULES.md files AND previously imported files, so editing an imported
289
301
  // doc invalidates the cache too.
290
302
  const tracked = new Set([...files, ...(cache?.tracked ?? [])]);
@@ -254,6 +254,26 @@ describe("mtime cache", () => {
254
254
  assert.ok(loadRules(cwd, userDir).rules[0].body.includes("BODY-V2"));
255
255
  });
256
256
 
257
+ it("creating a previously-missing @import target invalidates the cache (no /rules reload)", () => {
258
+ // Live finding (reviewer 2026-10-06): only successfully-read files were
259
+ // tracked, so creating the file a [missing import] marker points at
260
+ // changed no tracked mtime — the marker kept serving until RULES.md
261
+ // itself was edited. Missing targets are now tracked (existence flip
262
+ // changes the signature).
263
+ const { cwd, userDir } = workspace();
264
+ write(path.join(cwd, ".pi/RULES.md"), "## a\n@later.md\n");
265
+ assert.ok(loadRules(cwd, userDir).rules[0].body.includes("[missing import: @later.md]"));
266
+
267
+ const target = path.join(cwd, ".pi/later.md");
268
+ writeFileSync(target, "ARRIVED\n", "utf8");
269
+ const future = new Date(Date.now() + 5000);
270
+ utimesSync(target, future, future);
271
+
272
+ const body = loadRules(cwd, userDir).rules[0].body;
273
+ assert.ok(body.includes("ARRIVED"), `imported content served without cache drop; got: ${body}`);
274
+ assert.ok(!body.includes("[missing import"));
275
+ });
276
+
257
277
  it("returns the cached model unchanged when nothing on disk moved", () => {
258
278
  const { cwd, userDir } = workspace();
259
279
  write(path.join(cwd, ".pi/RULES.md"), "## a\nstable\n");
@@ -219,4 +219,25 @@ describe("rules module — /rules command", () => {
219
219
  await commands.get("rules").handler("bogus", context(workspace(), notes));
220
220
  assert.equal(notes[0].level, "error");
221
221
  });
222
+
223
+ it("UNTRUSTED project: repo RULES.md never reaches the prompt; user file still applies", async () => {
224
+ // Live-found defect (reviewer 2026-10-06): the composer had no trust gate —
225
+ // an untrusted checkout's RULES.md (and its @imports) landed in every
226
+ // request's system prompt. Same gate as pi's AGENTS.md context files.
227
+ const cwd = workspace({ ".pi/RULES.md": "## project-rule\nPROJECT-SECRET-MARKER\n" });
228
+ const { events } = harness();
229
+ const untrusted = { ...context(cwd), isProjectTrusted: () => false };
230
+ const result = await events.get("before_agent_start")!({ systemPrompt: "BASE", prompt: "p" }, untrusted);
231
+ assert.equal(result, undefined, "no project rules for an untrusted checkout");
232
+
233
+ // rule_get honors the same gate (no on-demand exfiltration of bodies).
234
+ const { tools } = harness();
235
+ const got = await tools.get("rule_get")!.execute("t1", { name: "project-rule" }, undefined, undefined, untrusted);
236
+ assert.match(JSON.stringify(got), /not found/i, "untrusted: rule body not served");
237
+
238
+ // Trusted sees them again (and the cache key carries the flag).
239
+ const trustedResult = await events.get("before_agent_start")!({ systemPrompt: "BASE", prompt: "p" }, context(cwd));
240
+ assert.ok(trustedResult?.systemPrompt.includes("PROJECT-SECRET-MARKER"));
241
+ });
222
242
  });
243
+
@@ -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
  }
@@ -115,12 +115,16 @@ describe("web configPanel", () => {
115
115
  const notifications: string[] = [];
116
116
  const ctx = { cwd: "/nonexistent", ui: { notify: (m: string) => notifications.push(m) }, isProjectTrusted: () => false } as never;
117
117
  await cfg.save(new Set(["web.brave.apiKey", "web.crawl4ai.timeoutMs"]), ctx);
118
+ // Secrets NEVER land in settings.json — brave (a secret row) goes to
119
+ // .env.local; only the non-secret timeout hits settings.json.
120
+ const envFile = fs.readFileSync(path.join(dir, ".env.local"), "utf8");
121
+ assert.match(envFile, /BRAVE_API_KEY=panel-key/);
118
122
  const raw = JSON.parse(fs.readFileSync(path.join(dir, "settings.json"), "utf8"));
119
- assert.equal(raw.web["brave.apiKey"], "panel-key");
123
+ assert.equal(raw.web["brave.apiKey"], undefined, "secret must not be written to settings.json");
120
124
  assert.equal(raw.web["crawl4ai.timeoutMs"], 45000);
121
- assert.equal(Object.keys(raw.web).length, 2, "only changed keys written");
125
+ assert.equal(Object.keys(raw.web).length, 1, "only the non-secret changed key written to settings.json");
122
126
  const note = notifications.join(" ");
123
- assert.ok(note.includes("settings.json"), note);
127
+ assert.ok(note.includes(".env.local"), note);
124
128
  assert.ok(note.includes("BRAVE_API_KEY"), "env override disclosed");
125
129
  } finally {
126
130
  if (old === undefined) delete process.env.BRAVE_API_KEY;
@@ -22,6 +22,12 @@ function setup(): void {
22
22
  fs.mkdirSync(agentDir, { recursive: true });
23
23
  fs.mkdirSync(projectDir, { recursive: true });
24
24
  process.env.PI_CODING_AGENT_DIR = agentDir;
25
+ // env.ts ingests <real agentDir>/.env.local at import — once the secrets
26
+ // migration has run on this machine, FIRECRAWL_API_KEY etc. sit in the
27
+ // test process env and "unset everywhere" is a lie. Scrub the mapped
28
+ // vars for the suite's lifetime (the web module re-reads settings layers,
29
+ // not env, for these assertions).
30
+ for (const v of ["BRAVE_API_KEY", "FIRECRAWL_API_KEY", "CRAWL4AI_API_TOKEN", "GEMINI_WEB_SECURE_1PSID", "ZAI_API_KEY", "WEB_IMAGE_API_KEY", "WEB_CHAT_API_KEY", "SEARXNG_BASE_URL"]) delete process.env[v];
25
31
  // Trust: the real trust.json walk won't see our temp project → untrusted by
26
32
  // default. isProjectTrusted(cwd, dirs) is injected nowhere here, so trust
27
33
  // tests go through writeWebSection/readWebSettings with explicit trusted
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "ceulen",
3
- "version": "0.11.0",
3
+ "version": "0.12.0",
4
4
  "description": "Ceulen — the Pi coding agent, fully dressed: one bundle extension carrying the full toolkit with a single /ceulen config command.",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -40,7 +40,7 @@
40
40
  "homepage": "https://github.com/ceulen-dev/ceulen#readme",
41
41
  "bugs": "https://github.com/ceulen-dev/ceulen/issues",
42
42
  "scripts": {
43
- "test": "node scripts/validate-themes.mjs && node --import tsx --test extensions/lib/registry.test.ts extensions/lib/skill-path.test.ts extensions/modules/router/test/unit.test.ts extensions/modules/router/test/guard.test.ts extensions/modules/classifier/test/*.test.ts extensions/modules/advisor/test/*.test.ts extensions/modules/usage/test/*.test.ts extensions/modules/ponytail/test/*.test.ts extensions/modules/ux/test/*.test.ts extensions/modules/config/test/*.test.ts extensions/modules/composer/test/*.test.ts extensions/modules/serena/test/*.test.ts extensions/modules/fff/test/*.test.ts extensions/modules/rtk/test/*.test.js extensions/modules/munin/test/*.test.ts extensions/modules/subagent/test/*.test.ts extensions/modules/zai/test/*.test.ts extensions/modules/repair/test/*.test.ts extensions/modules/steering/test/*.test.ts extensions/modules/plan/test/*.test.ts extensions/modules/todo/test/*.test.ts extensions/modules/web/test/*.test.ts extensions/modules/rules/test/*.test.ts extensions/modules/a2a/test/*.test.ts extensions/modules/gh/test/*.test.ts extensions/modules/attachments/test/*.test.ts extensions/modules/cron/test/*.test.ts extensions/modules/permission/test/*.test.ts",
43
+ "test": "node scripts/validate-themes.mjs && node --import tsx --test extensions/lib/env.test.ts extensions/lib/order.test.ts extensions/lib/registry.test.ts extensions/lib/skill-path.test.ts extensions/modules/router/test/unit.test.ts extensions/modules/router/test/guard.test.ts extensions/modules/classifier/test/*.test.ts extensions/modules/advisor/test/*.test.ts extensions/modules/usage/test/*.test.ts extensions/modules/ponytail/test/*.test.ts extensions/modules/ux/test/*.test.ts extensions/modules/config/test/*.test.ts extensions/modules/composer/test/*.test.ts extensions/modules/serena/test/*.test.ts extensions/modules/fff/test/*.test.ts extensions/modules/rtk/test/*.test.js extensions/modules/munin/test/*.test.ts extensions/modules/subagent/test/*.test.ts extensions/modules/zai/test/*.test.ts extensions/modules/repair/test/*.test.ts extensions/modules/steering/test/*.test.ts extensions/modules/plan/test/*.test.ts extensions/modules/todo/test/*.test.ts extensions/modules/web/test/*.test.ts extensions/modules/rules/test/*.test.ts extensions/modules/a2a/test/*.test.ts extensions/modules/gh/test/*.test.ts extensions/modules/attachments/test/*.test.ts extensions/modules/cron/test/*.test.ts extensions/modules/permission/test/*.test.ts",
44
44
  "typecheck": "tsc --noEmit"
45
45
  },
46
46
  "pi": {