ceulen 0.10.1 → 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 (69) hide show
  1. package/CHANGELOG.md +107 -1
  2. package/README.md +56 -1
  3. package/extensions/index.ts +5 -1
  4. package/extensions/lib/env.test.ts +147 -0
  5. package/extensions/lib/env.ts +180 -0
  6. package/extensions/lib/order.test.ts +74 -0
  7. package/extensions/lib/plan-bridge.ts +18 -0
  8. package/extensions/lib/registry.test.ts +8 -5
  9. package/extensions/lib/registry.ts +22 -3
  10. package/extensions/modules/a2a/configPanel.ts +42 -1
  11. package/extensions/modules/a2a/index.ts +4 -2
  12. package/extensions/modules/a2a/lib/config.ts +8 -3
  13. package/extensions/modules/a2a/test/configPanel.test.ts +7 -4
  14. package/extensions/modules/advisor/index.ts +6 -3
  15. package/extensions/modules/advisor/test/module.test.ts +31 -0
  16. package/extensions/modules/attachments/configPanel.ts +91 -0
  17. package/extensions/modules/attachments/index.ts +274 -0
  18. package/extensions/modules/attachments/lib/clipboard-files.ts +80 -0
  19. package/extensions/modules/attachments/lib/pastes.ts +45 -0
  20. package/extensions/modules/attachments/lib/paths.ts +74 -0
  21. package/extensions/modules/attachments/lib/registry.ts +70 -0
  22. package/extensions/modules/attachments/lib/settings.ts +99 -0
  23. package/extensions/modules/attachments/lib/tray.ts +74 -0
  24. package/extensions/modules/attachments/test/configPanel.test.ts +122 -0
  25. package/extensions/modules/attachments/test/index.test.ts +870 -0
  26. package/extensions/modules/attachments/test/module.test.ts +53 -0
  27. package/extensions/modules/classifier/index.ts +55 -1
  28. package/extensions/modules/classifier/test/classifier.test.ts +62 -0
  29. package/extensions/modules/composer/test/module.test.ts +2 -2
  30. package/extensions/modules/config/index.ts +3 -0
  31. package/extensions/modules/config/test/renderTools.test.ts +1 -1
  32. package/extensions/modules/cron/configPanel.ts +103 -0
  33. package/extensions/modules/cron/index.ts +638 -0
  34. package/extensions/modules/cron/lib/jobs.ts +201 -0
  35. package/extensions/modules/cron/lib/schedule.ts +161 -0
  36. package/extensions/modules/cron/test/cwd-repro.test.ts +98 -0
  37. package/extensions/modules/cron/test/index.test.ts +859 -0
  38. package/extensions/modules/cron/test/schedule.test.ts +93 -0
  39. package/extensions/modules/munin/index.ts +3 -1
  40. package/extensions/modules/permission/index.ts +567 -0
  41. package/extensions/modules/permission/test/permission.test.ts +789 -0
  42. package/extensions/modules/plan/index.ts +5 -0
  43. package/extensions/modules/repair/index.ts +160 -5
  44. package/extensions/modules/repair/test/freshness.test.ts +209 -0
  45. package/extensions/modules/repair/test/guard-selector.test.ts +67 -0
  46. package/extensions/modules/router/configPanel.ts +4 -4
  47. package/extensions/modules/router/index.ts +1 -1
  48. package/extensions/modules/router/lib/config.ts +9 -4
  49. package/extensions/modules/router/lib/systemone.ts +17 -4
  50. package/extensions/modules/router/test/unit.test.ts +46 -1
  51. package/extensions/modules/rules/index.ts +13 -3
  52. package/extensions/modules/rules/lib/rules.ts +24 -12
  53. package/extensions/modules/rules/test/lib.test.ts +20 -0
  54. package/extensions/modules/rules/test/module.test.ts +21 -0
  55. package/extensions/modules/subagent/index.ts +49 -10
  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 +356 -14
  59. package/extensions/modules/subagent/test/routing.test.ts +45 -0
  60. package/extensions/modules/subagent/test/worktree.test.ts +230 -0
  61. package/extensions/modules/usage/index.ts +193 -71
  62. package/extensions/modules/usage/test/context.test.ts +160 -120
  63. package/extensions/modules/web/configPanel.ts +67 -8
  64. package/extensions/modules/web/index.ts +3 -1
  65. package/extensions/modules/web/test/a11y.test.ts +1 -1
  66. package/extensions/modules/web/test/configPanel.test.ts +7 -3
  67. package/extensions/modules/web/test/settings.test.ts +6 -0
  68. package/package.json +2 -2
  69. package/skills/cron/SKILL.md +58 -0
@@ -1,6 +1,6 @@
1
1
  import { describe, it, before, after, mock } from "node:test";
2
2
  import assert from "node:assert/strict";
3
- import { mkdirSync, writeFileSync, unlinkSync, existsSync, readFileSync, rmSync, statSync } from "node:fs";
3
+ import { mkdirSync, mkdtempSync, writeFileSync, unlinkSync, existsSync, readFileSync, rmSync, statSync } from "node:fs";
4
4
  import { homedir } from "node:os";
5
5
  import { join } from "node:path";
6
6
  import { tmpdir } from "node:os";
@@ -91,6 +91,26 @@ describe("config", () => {
91
91
  });
92
92
  });
93
93
 
94
+ it("the repo overlay resolves from opts.cwd, not process.cwd() (session-cwd convention)", async () => {
95
+ // Live-found defect (reviewer 2026-10-06): REPO_SETTINGS_PATH was bound
96
+ // to process.cwd() at import — RPC/a2a child sessions with a different
97
+ // session cwd consulted the wrong file under the right trust verdict.
98
+ const { getSettings } = await import("../lib/config.js");
99
+ writeSettings({ baseUrl: "http://global" });
100
+ const dirA = mkdtempSync(join(tmpdir(), "router-cwd-a-"));
101
+ const dirB = mkdtempSync(join(tmpdir(), "router-cwd-b-"));
102
+ try {
103
+ mkdirSync(join(dirB, ".pi"), { recursive: true });
104
+ writeFileSync(join(dirB, ".pi", "settings.json"), JSON.stringify({ router: { baseUrl: "http://repo-b/v1" } }));
105
+ assert.equal(getSettings({ trustProject: true, cwd: dirA }).baseUrl, "http://global", "A has no repo file → global");
106
+ assert.equal(getSettings({ trustProject: true, cwd: dirB }).baseUrl, "http://repo-b/v1", "B's repo file serves B's session");
107
+ assert.equal(getSettings({ trustProject: false, cwd: dirB }).baseUrl, "http://global", "untrusted B → global regardless of cwd");
108
+ } finally {
109
+ rmSync(dirA, { recursive: true, force: true });
110
+ rmSync(dirB, { recursive: true, force: true });
111
+ }
112
+ });
113
+
94
114
  it("trusted: env still beats repo", async () => {
95
115
  try { unlinkSync(settingsPath()); } catch { /* ignore */ }
96
116
  process.env.ROUTER_BASE_URL = "http://from-env";
@@ -922,6 +942,31 @@ describe("provider classifier catalog", () => {
922
942
  }
923
943
  });
924
944
 
945
+ it("classify carries a default 30s deadline — a silent endpoint fails open, never hangs the turn", async () => {
946
+ const { systemoneClassify } = await import("../lib/systemone.js");
947
+ const model = {
948
+ api: "typesafe-system-one",
949
+ provider: "router",
950
+ id: "combo/jev",
951
+ baseUrl: "http://h/v1",
952
+ cost: { input: 0, output: 0 },
953
+ } as never;
954
+ const context = { state: {}, questions: { q: { type: "noul", instructions: "x?", criteria: { yes: "y", no: "n" } } } } as never;
955
+ const realFetch = globalThis.fetch;
956
+ // Never-resolving fetch: without the default deadline this promise never
957
+ // settles (the live 8h hang). AbortSignal.timeout must cut it short.
958
+ globalThis.fetch = ((_input: unknown, init?: RequestInit) => new Promise<Response>((_resolve, reject) => {
959
+ init?.signal?.addEventListener("abort", () => reject(new Error("aborted: deadline")));
960
+ })) as unknown as typeof fetch;
961
+ try {
962
+ const result = await systemoneClassify(model, context, { apiKey: "sk" } as never);
963
+ assert.equal(result.stopReason, "error", "deadline expiry must surface as stopReason error, not a hang");
964
+ assert.match(result.errorMessage ?? "", /deadline/i);
965
+ } finally {
966
+ globalThis.fetch = realFetch;
967
+ }
968
+ });
969
+
925
970
  it("registerProvider carries the typesafe-system-one classifier implementation", async () => {
926
971
  const { registerProvider, PROVIDER_ID } = await import("../lib/provider.js");
927
972
  let registered: { name: string; config: Record<string, unknown> } | null = null;
@@ -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
+
@@ -17,7 +17,7 @@
17
17
  */
18
18
 
19
19
  import * as path from "node:path";
20
- import * as fsPromises from "node:fs/promises";
20
+ import * as fs from "node:fs/promises";
21
21
  import { Container, Markdown, SelectList, Spacer, Text } from "@earendil-works/pi-tui";
22
22
  import { Type } from "typebox";
23
23
  import {
@@ -35,14 +35,18 @@ import { StringEnum } from "./lib/schema.ts";
35
35
  import { type AgentColor, type AgentConfig, type AgentScope, discoverAgents, formatAgentList, getModelCandidates, invalidateAgentCache } from "./lib/agents.ts";
36
36
  import {
37
37
  type SubAgentProgress,
38
+ type WorktreeOwner,
38
39
  type SubAgentResult,
39
40
  formatPatchBlock,
40
41
  getFinalOutput,
41
42
  getResultOutput,
42
43
  isFailedResult,
43
44
  mapWithConcurrencyLimit,
45
+ pidAlive,
44
46
  runSubAgent,
45
47
  startHeartbeat,
48
+ sweepStaleWorktrees,
49
+ WORKTREE_DIR_NAME,
46
50
  } from "./lib/runner.ts";
47
51
  import {
48
52
  flushWarnings,
@@ -58,6 +62,7 @@ import {
58
62
  MAX_PARALLEL_TASKS,
59
63
  MAX_CHAIN_LENGTH,
60
64
  MAX_INSTRUCTIONS_LENGTH,
65
+ MAX_TIMEOUT_MS,
61
66
  } from "./lib/security.ts";
62
67
  import {
63
68
  aggregateUsage,
@@ -148,7 +153,7 @@ const TaskItem = Type.Object({
148
153
  task: Type.String({ description: "Task to delegate to the agent" }),
149
154
  cwd: Type.Optional(Type.String({ description: "Working directory for the agent" })),
150
155
  solutionSpace: Type.Optional(Type.String({ description: "How open-ended this task's problem is — feeds model-tier/thinking routing." })),
151
- 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." })),
152
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." })),
153
158
  });
154
159
 
@@ -156,7 +161,7 @@ const ChainItem = Type.Object({
156
161
  agent: Type.String({ description: "Name of the agent to invoke" }),
157
162
  task: Type.String({ description: "Task with optional {previous} placeholder for prior output" }),
158
163
  cwd: Type.Optional(Type.String({ description: "Working directory for the agent" })),
159
- 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." })),
160
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." })),
161
166
  });
162
167
 
@@ -199,7 +204,7 @@ const SubagentParams = Type.Object({
199
204
  // Project-agent confirmation is enforced via trusted configuration.
200
205
  // See Security model section in README.
201
206
  cwd: Type.Optional(Type.String({ description: "Working directory (single mode, must be inside workspace)" })),
202
- 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." })),
203
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." })),
204
209
  instructions: Type.Optional(Type.String({ description: "Bounded repository/task instructions passed to each child (max 16 KB)" })),
205
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'." })),
@@ -296,6 +301,9 @@ export default function (pi: ExtensionAPI) {
296
301
  });
297
302
  // Clear any widget from a prior session.
298
303
  if (ctx.mode === "tui") widget.clearWidgetIfIdle(ctx);
304
+ // Reclaim crashed runs' worktree sandboxes (fire-and-forget: never blocks
305
+ // startup; a no-.pi-worktrees repo costs one rev-parse).
306
+ void sweepStaleWorktrees(ctx.cwd).catch(() => { /* best effort */ });
299
307
  // Mark prior-session running tasks as interrupted (we can't resume them),
300
308
  // but keep entries for background tasks still live in this process — only
301
309
  // shutdown aborts them, so a session reload must not mislabel them.
@@ -388,10 +396,10 @@ export default function (pi: ExtensionAPI) {
388
396
  return container;
389
397
  });
390
398
  pi.registerCommand("subagent", {
391
- description: "Configure model roles (/subagent), list agents (/subagent list), agent details (/subagent <name>), role detail (/subagent @role), reload definitions (/subagent reload), history (/subagent history)",
399
+ description: "Configure model roles (/subagent), list agents (/subagent list), agent details (/subagent <name>), role detail (/subagent @role), reload definitions (/subagent reload), history (/subagent history), worktree sandboxes (/subagent worktrees [clean])",
392
400
  getArgumentCompletions: (prefix) => {
393
401
  const ctx = currentCtx;
394
- const keywords = ["list", "all", "agents", "roles", "reload", "refresh", "history"];
402
+ const keywords = ["list", "all", "agents", "roles", "reload", "refresh", "history", "worktrees"];
395
403
  const vocab = [...keywords];
396
404
  if (ctx) {
397
405
  const discovery = discoverAgents(ctx.cwd, "both", bundledAgentsDir);
@@ -407,6 +415,32 @@ export default function (pi: ExtensionAPI) {
407
415
  const cmd = args.trim().toLowerCase();
408
416
  const discovery = discoverAgents(ctx.cwd, "both", bundledAgentsDir);
409
417
 
418
+ // /subagent worktrees [clean] — worktree sandbox inventory + GC.
419
+ if (cmd === "worktrees" || cmd.startsWith("worktrees ")) {
420
+ const force = cmd.includes("clean");
421
+ const ownerLabel = async (): Promise<string> => {
422
+ const base = path.join(path.resolve(ctx.cwd), WORKTREE_DIR_NAME);
423
+ let entries: string[] = [];
424
+ try { entries = (await fs.readdir(base)).filter((e) => e !== ".gitignore"); } catch { return "No worktree sandboxes."; }
425
+ if (entries.length === 0) return "No worktree sandboxes.";
426
+ const lines = await Promise.all(entries.map(async (entry) => {
427
+ let owner: WorktreeOwner | undefined;
428
+ try { owner = JSON.parse(await fs.readFile(path.join(base, `${entry}.owner.json`), "utf8")) as WorktreeOwner; } catch { /* stale/legacy */ }
429
+ const state = !owner ? "stale (no marker)"
430
+ : pidAlive(owner.pid) ? `live (pid ${owner.pid})`
431
+ : `dead (pid ${owner.pid}, ${Math.round((Date.now() - (owner.createdAt ?? Date.now())) / 60000)}min old)`;
432
+ return ` ${entry} — ${state}`;
433
+ }));
434
+ return `Worktree sandboxes (${entries.length}):
435
+ ${lines.join("\n")}`;
436
+ };
437
+ const result = force ? await sweepStaleWorktrees(ctx.cwd) : null;
438
+ const listing = await ownerLabel();
439
+ const sweepLine = result ? `\n\nSwept ${result.removed.length} stale sandbox(es): ${result.removed.map((r) => path.basename(r)).join(", ") || "none"}.` : "\n\n(/subagent worktrees clean to sweep stale entries)";
440
+ pi.sendMessage({ customType: "ceulen-subagent", content: `${listing}${sweepLine}`, display: true });
441
+ return;
442
+ }
443
+
410
444
  // /subagent history — list recent task delegations (durable metadata).
411
445
  if (cmd === "history" || cmd === "hist") {
412
446
  const piDir = path.join(ctx.cwd, CONFIG_DIR_NAME);
@@ -1053,10 +1087,15 @@ export default function (pi: ExtensionAPI) {
1053
1087
  return { error: `No model resolved for agent "${agentName}" (tried: ${resolved.attempted.join(", ") || "none"}).` };
1054
1088
  }
1055
1089
  // herdr children run full pi — they need SOME lifetime cap so an
1056
- // 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.
1057
1096
  const timeouts = resolveChildTimeouts({ requested: timeoutMs, agentTimeoutMins: agent.timeout, idleTimeoutMins: subSettings.idleTimeoutMins, hardTimeoutMins: subSettings.hardTimeoutMins });
1058
1097
  if (timeouts.error) return { error: timeouts.error };
1059
- const hardTimeoutMs = timeouts.hardTimeoutMs ?? timeouts.timeoutMs ?? 0;
1098
+ const hardTimeoutMs = timeouts.hardTimeoutMs ?? MAX_TIMEOUT_MS;
1060
1099
  if (!hardTimeoutMs) return { error: "Invalid herdr timeout configuration." };
1061
1100
  const safe = resolveSafeCwd({ workspaceRoot, childCwd: cwd, allowExternalCwd });
1062
1101
  if (safe.error) return { error: safe.error };
@@ -2115,7 +2154,7 @@ export default function (pi: ExtensionAPI) {
2115
2154
  if (params.wait) {
2116
2155
  const timeoutMs = params.timeout ?? 120_000;
2117
2156
  const fileStampBefore = entry
2118
- ? await fsPromises.stat(entry.resultFile).then((s) => `${s.size}:${s.mtimeMs}`).catch(() => "")
2157
+ ? await fs.stat(entry.resultFile).then((s) => `${s.size}:${s.mtimeMs}`).catch(() => "")
2119
2158
  : "";
2120
2159
  // Abortable: an aborted tool call interrupts the wait (esc to the
2121
2160
  // child) instead of blocking until the CLI timeout.
@@ -2151,7 +2190,7 @@ export default function (pi: ExtensionAPI) {
2151
2190
  // if THIS prompt changed it — otherwise the previous run's report
2152
2191
  // would come back as the answer.
2153
2192
  if (collected.source === "file") {
2154
- const stampAfter = await fsPromises.stat(entry.resultFile).then((s) => `${s.size}:${s.mtimeMs}`).catch(() => "");
2193
+ const stampAfter = await fs.stat(entry.resultFile).then((s) => `${s.size}:${s.mtimeMs}`).catch(() => "");
2155
2194
  if (stampAfter === fileStampBefore) {
2156
2195
  // Unchanged file = the previous run's report — don't return
2157
2196
  // it as the answer to this prompt.
@@ -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