ceulen 0.15.2 → 0.16.1

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 (53) hide show
  1. package/CHANGELOG.md +41 -0
  2. package/README.md +1 -1
  3. package/extensions/lib/registry.ts +2 -1
  4. package/extensions/modules/classifier/index.ts +29 -12
  5. package/extensions/modules/classifier/lib/settings.ts +20 -3
  6. package/extensions/modules/classifier/test/classifier.test.ts +12 -4
  7. package/extensions/modules/config/defaultTools.ts +7 -3
  8. package/extensions/modules/config/test/defaultTools.test.ts +16 -0
  9. package/extensions/modules/gh/lib/ops.ts +22 -4
  10. package/extensions/modules/gh/test/gh.test.ts +64 -1
  11. package/extensions/modules/plan/index.ts +116 -4
  12. package/extensions/modules/plan/lib/settings.ts +5 -7
  13. package/extensions/modules/plan/test/module.test.ts +104 -1
  14. package/extensions/modules/plan/test/settings.test.ts +7 -0
  15. package/extensions/modules/repair/configPanel.ts +3 -1
  16. package/extensions/modules/repair/index.ts +21 -16
  17. package/extensions/modules/repair/lib/read-sqlite.ts +18 -7
  18. package/extensions/modules/repair/test/freshness.test.ts +30 -0
  19. package/extensions/modules/repair/test/hardening.test.ts +46 -1
  20. package/extensions/modules/repair/test/readers.test.ts +11 -5
  21. package/extensions/modules/repair/test/settings.test.ts +7 -2
  22. package/extensions/modules/rtk/configPanel.ts +67 -0
  23. package/extensions/modules/rtk/index.ts +76 -9
  24. package/extensions/modules/rtk/lib/settings.ts +65 -0
  25. package/extensions/modules/rtk/test/configPanel.test.ts +72 -0
  26. package/extensions/modules/rtk/test/index.test.js +120 -2
  27. package/extensions/modules/rules/index.ts +4 -1
  28. package/extensions/modules/rules/lib/rules.ts +6 -3
  29. package/extensions/modules/rules/test/lib.test.ts +24 -0
  30. package/extensions/modules/rules/test/module.test.ts +29 -0
  31. package/extensions/modules/shells/lib/sessions.ts +40 -12
  32. package/extensions/modules/shells/test/sessions.test.ts +60 -2
  33. package/extensions/modules/steering/index.ts +12 -1
  34. package/extensions/modules/steering/test/anchor-plan.test.ts +73 -0
  35. package/extensions/modules/subagent/index.ts +19 -3
  36. package/extensions/modules/subagent/lib/herdr.ts +141 -1
  37. package/extensions/modules/subagent/lib/runner.ts +88 -22
  38. package/extensions/modules/subagent/test/herdr-stalled.test.ts +117 -0
  39. package/extensions/modules/subagent/test/worktree.test.ts +156 -1
  40. package/extensions/modules/todo/index.ts +4 -0
  41. package/extensions/modules/todo/test/todo.test.ts +9 -0
  42. package/extensions/modules/web/index.ts +1 -1
  43. package/extensions/modules/web/lib/a11y.ts +30 -15
  44. package/extensions/modules/web/lib/cdp.ts +11 -2
  45. package/extensions/modules/web/lib/chrome.ts +12 -3
  46. package/extensions/modules/web/lib/content.ts +32 -9
  47. package/extensions/modules/web/lib/search.ts +111 -3
  48. package/extensions/modules/web/test/a11y.test.ts +100 -2
  49. package/extensions/modules/web/test/cdp.test.ts +48 -0
  50. package/extensions/modules/web/test/chrome.test.ts +32 -0
  51. package/extensions/modules/web/test/content.test.ts +92 -0
  52. package/extensions/modules/web/test/search.test.ts +75 -0
  53. package/package.json +1 -1
package/CHANGELOG.md CHANGED
@@ -1,5 +1,46 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.16.1 — 2026-10-10
4
+
5
+ - **herdr stall recovery rewritten on output evidence** — live probing
6
+ (2026-10-10) showed herdr 0.9.3's status watcher NEVER reports `working`
7
+ for pi panes (`state_change_seq` frozen across live turns), so
8
+ `agent prompt --wait` returned `agent_prompt_stalled` on healthy
9
+ dispatches (every herdr delegation was affected; the child completed its
10
+ work while the parent reported failure). The subagent module now snapshots
11
+ an output-evidence baseline BEFORE submission (`captureEvidenceStamp`:
12
+ report-file stamp + pane tail for read-only children) and, on a stall,
13
+ waits on EVIDENCE for the remaining dispatch budget — a changed report-file
14
+ stamp (delivery contract) or a changed-then-quiet pane tail (3 stable
15
+ polls). Window exhaustion reports timeout semantics (pane interrupted,
16
+ may-still-complete disclosure) — never a phantom hard stall. Verified live
17
+ across all five agent types under 4-way concurrency, including a mid-turn
18
+ Z.ai 429 recovery; 6 new regression tests (`test/herdr-stalled.test.ts`).
19
+
20
+ ## 0.16.0 — 2026-10-09
21
+
22
+ - **RTK selective rewrite** — the prompt note states the policy honestly
23
+ (RTK rewrites only what it models; chains, redirects, and inline scripts
24
+ pass through unchanged, byte-identical every turn for prefix-cache
25
+ stability), per-command truth moved to `[pi-rtk] passed through unchanged`
26
+ notifies (deduped per consecutive identical command), and a new global
27
+ `rtk` settings section (`mode: supported-only|off`, `chained:
28
+ only-all-modeled|never`) read per bash call — `/config` → Shell → RTK.
29
+ Measured on rtk 0.50.0: the rewrite fails open on every chain with an
30
+ unmodeled segment (90% of this repo's real bash traffic), so `chained:
31
+ never` also skips the wasted spawn per chain.
32
+ - **Web search backend router** — in auto mode with ≥2 backends configured,
33
+ `web_search` asks the classifier (one Jev round-trip) to pick brave-first
34
+ (precision/docs/error-strings) vs searxng-first (broad discovery); low
35
+ confidence, timeout, or failure falls back to the unchanged heuristic.
36
+ `SearchDiagnostics.router` + the diagnostics block expose which path ran.
37
+ - **planGate ported** — `classifier.planGate.{enabled,observe,threshold}`
38
+ (default off) lets the plan module's confirm tier auto-run a command when
39
+ Jev says it clearly won't mutate the filesystem and serves the task;
40
+ writes stay hard-blocked, the static RISKY list skips the gate, and every
41
+ verdict audits to classifier.log (`ceulen-plan-gate`). Run
42
+ `observe: true` first to measure the false-auto rate.
43
+
3
44
  ## 0.15.2 — 2026-10-08
4
45
 
5
46
  Deferred-tier re-evaluation from live session usage (211 transcripts, 13K tool
package/README.md CHANGED
@@ -149,7 +149,7 @@ Opt-in `permission` settings section: allow/ask/deny rules per tool with wildcar
149
149
 
150
150
  - **serena** — semantic code tools (find symbol, references, rename, diagnostics) via a persistent language-server worker
151
151
  - **fff** — fast fuzzy file/content search (`ffgrep`, `fffind`) feeding the built-in grep/find experience and `@`-mention completions
152
- - **rtk** — transparently rewrites shell commands to save tokens (`/rtk status`, `RTK_DISABLED=1` to bypass)
152
+ - **rtk** — rewrites shell commands through RTK only where RTK supports them (git, ls, rg, test runners); chains, redirects, and inline scripts pass through byte-identical (`/rtk status`, `/config` → Shell → RTK, `RTK_DISABLED=1` to bypass)
153
153
 
154
154
  ### config — the settings panel
155
155
 
@@ -38,6 +38,7 @@ import uxModule, { uxConfig } from "../modules/ux/index.ts";
38
38
  import serenaModule from "../modules/serena/index.ts";
39
39
  import fffModule from "../modules/fff/index.ts";
40
40
  import rtkModule from "../modules/rtk/index.ts";
41
+ import { rtkConfig } from "../modules/rtk/configPanel.ts";
41
42
  import muninModule from "../modules/munin/index.ts";
42
43
  import { muninConfig } from "../modules/munin/configPanel.ts";
43
44
  import webModule from "../modules/web/index.ts";
@@ -213,7 +214,7 @@ export const MODULES: ModuleEntry[] = [
213
214
  // serena/web/rtk then append to. rtk (a prompt rewriter — it appends the
214
215
  // RTK note) loads BEFORE this entry; nothing after steering touches the
215
216
  // prompt — do not move rtk back after it or add a prompt rewriter here.
216
- { name: "rtk", category: "Shell", describe: "Route shell commands through RTK for token savings.", load: rtkModule },
217
+ { name: "rtk", category: "Shell", describe: "Route shell commands through RTK where RTK supports them; chains and unsupported commands pass through.", load: rtkModule, config: rtkConfig },
217
218
  { name: "steering", category: "Model", describe: "Per-model-family steering (DeepSeek/GLM): first-tool hints, reasoning strip, leak cleaning, error recovery hints, DeepSeek guidance + v4-pro minimal-mode anchor.", load: steeringModule, config: steeringConfig },
218
219
  // ── Shell ──────────────────────────────────────────────────────────────
219
220
  // Permission after rtk: persistent allow/ask/deny gating. Inert until rules
@@ -20,10 +20,10 @@
20
20
  *
21
21
  * Config: `classifier` section of ~/.pi/agent/settings.json (global only —
22
22
  * see lib/settings.ts). /config owns the rows (Model tab → Classifier).
23
- * pi-classifier's planGate is NOT ported and NOT consumed by the plan module:
24
- * pi 1.0.0's `tool_call` hook can only block, never approve, so a gate could
25
- * only have trimmed plan-mode confirm prompts (source preserved in
26
- * pi-extensions git history).
23
+ * planGate (pi-plan's reserved key) is consumed by the plan module's confirm
24
+ * tier: the gate can move a confirm-tier command to AUTO-RUN when Jev says
25
+ * it is clearly reversible and serves the task — never the reverse (write
26
+ * stays a hard block), and it ships observe-only by default.
27
27
  */
28
28
 
29
29
  import { appendFile, mkdir } from "node:fs/promises";
@@ -91,7 +91,7 @@ export function createVerdictCache(cap = 100) {
91
91
  /** Audit line per decision. Best-effort: never throws into the tool path.
92
92
  * 0600 — the log records full bash commands and task text, same
93
93
  * permission discipline as pi's settings/auth files. */
94
- function audit(entry: Record<string, unknown>): Promise<void> {
94
+ export function audit(entry: Record<string, unknown>): Promise<void> {
95
95
  try {
96
96
  const dir = process.env.PI_CODING_AGENT_DIR || join(homedir(), ".pi", "agent");
97
97
  // ponytail: async write so the tool_call hot path never blocks. Never rejects.
@@ -117,7 +117,10 @@ export function resetClassifierRefreshCooldown(): void {
117
117
  lastForcedRefresh = 0;
118
118
  }
119
119
 
120
- async function askJev(ctx: ExtensionContext, state: Record<string, unknown>, questions: Record<string, unknown>, signal?: AbortSignal): Promise<Record<string, unknown>> {
120
+ /** Ask the router's decision model (Jev). Exported for sibling modules that
121
+ * need a typed verdict (web backend routing, plan mode's confirm trim) —
122
+ * callers fail safe around its throws. */
123
+ export async function askJev(ctx: ExtensionContext, state: Record<string, unknown>, questions: Record<string, unknown>, signal?: AbortSignal): Promise<Record<string, unknown>> {
121
124
  const resolve = async () => {
122
125
  const s = getClassifierSettings();
123
126
  let model = s.model ? ctx.modelRegistry.findOfType("classifier", "router", s.model) : undefined;
@@ -154,6 +157,14 @@ async function askJev(ctx: ExtensionContext, state: Record<string, unknown>, que
154
157
  return result.answers as unknown as Record<string, unknown>;
155
158
  }
156
159
 
160
+ /** The most recent user message text (≤4000 chars) — "the current task" for
161
+ * serves_task verdicts. Exported for the plan module's planGate; the
162
+ * classifier's own message_end hook keeps it fresh. */
163
+ let lastTask = "";
164
+ export function getLastTask(): string {
165
+ return lastTask;
166
+ }
167
+
157
168
  export default function (pi: ExtensionAPI) {
158
169
  // The /config contribution reads discovered decision models at open time;
159
170
  // config factories get no ctx, so the module stashes the live registry
@@ -208,21 +219,27 @@ export default function (pi: ExtensionAPI) {
208
219
  });
209
220
 
210
221
  // ── 2. permission auto-approve hook (ported from pi-classifier) ─────────
211
- let lastTask = "";
212
222
  pi.on("message_end", (event) => {
213
223
  const msg = event.message;
214
224
  if (msg?.role !== "user") return;
215
- if (typeof msg.content === "string") lastTask = msg.content.slice(0, 4000);
216
- // Array-shaped content: join the text parts (images etc. contribute nothing).
217
- else if (Array.isArray(msg.content)) {
225
+ if (typeof msg.content === "string") {
226
+ lastTask = msg.content;
227
+ } else if (Array.isArray(msg.content)) {
228
+ // Array-shaped content: join the text parts (images etc. contribute nothing).
218
229
  lastTask = (msg.content as { type?: string; text?: unknown }[])
219
230
  .filter((p) => p?.type === "text" && typeof p.text === "string")
220
231
  .map((p) => p.text as string)
221
- .join("\n")
222
- .slice(0, 4000);
232
+ .join("\n");
233
+ } else {
234
+ lastTask = ""; // unrecognized shape — no task, never a stale one
223
235
  }
236
+ lastTask = lastTask.slice(0, 4000);
224
237
  });
225
238
 
239
+ // Per-registration reset: a second default() call (test fixtures re-run the
240
+ // factory) must not inherit the previous registration's task.
241
+ lastTask = "";
242
+
226
243
  const cache = createVerdictCache();
227
244
 
228
245
  // Failure circuit-breaker (advisor's MAX_CONSECUTIVE_FAILURES precedent):
@@ -11,8 +11,13 @@
11
11
  // }
12
12
  // }
13
13
  //
14
- // `planGate` in the file is left untouched (pi-plan's key; no consumer in
15
- // ceulen until the pi-plan port).
14
+ // `planGate` (pi-plan's key, now consumed by ceulen's plan module):
15
+ //
16
+ // "planGate": {
17
+ // "enabled": false, // allow the gate to AUTO-RUN confident safe confirm-tier commands
18
+ // "observe": false, // log-only audit pass — verdicts land in classifier.log, nothing changes
19
+ // "threshold": 0.9 // p(reversible) must clear it for an auto-run
20
+ // }
16
21
 
17
22
  import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs";
18
23
  import { homedir } from "node:os";
@@ -26,6 +31,11 @@ export interface ClassifierSettings {
26
31
  mode: "observe" | "enforce";
27
32
  threshold: number;
28
33
  };
34
+ planGate: {
35
+ enabled: boolean;
36
+ observe: boolean;
37
+ threshold: number;
38
+ };
29
39
  }
30
40
 
31
41
  function agentDir(): string {
@@ -38,7 +48,8 @@ function settingsPath(): string {
38
48
 
39
49
  /** Read the `classifier` settings. Global only — a repo file must not flip
40
50
  * verdict behavior. Defaults match pi-classifier (enabled/enforce/0.9 since
41
- * the 0.2.0 live audit). Exported for tests. */
51
+ * the 0.2.0 live audit); planGate defaults fully off (observe first, enable
52
+ * after a measured false-auto rate). Exported for tests. */
42
53
  export function getClassifierSettings(): ClassifierSettings {
43
54
  let raw: Record<string, unknown> = {};
44
55
  try {
@@ -50,6 +61,7 @@ export function getClassifierSettings(): ClassifierSettings {
50
61
  }
51
62
  const c = raw.classifier && typeof raw.classifier === "object" ? (raw.classifier as Record<string, unknown>) : {};
52
63
  const perm = c.permission && typeof c.permission === "object" ? (c.permission as Record<string, unknown>) : {};
64
+ const gate = c.planGate && typeof c.planGate === "object" ? (c.planGate as Record<string, unknown>) : {};
53
65
  return {
54
66
  model: typeof c.model === "string" ? c.model.trim() : "",
55
67
  permission: {
@@ -60,6 +72,11 @@ export function getClassifierSettings(): ClassifierSettings {
60
72
  mode: perm.mode === "observe" ? "observe" : "enforce",
61
73
  threshold: typeof perm.threshold === "number" && perm.threshold > 0 && perm.threshold < 1 ? perm.threshold : 0.9,
62
74
  },
75
+ planGate: {
76
+ enabled: gate.enabled === true,
77
+ observe: gate.observe === true,
78
+ threshold: typeof gate.threshold === "number" && gate.threshold > 0 && gate.threshold < 1 ? gate.threshold : 0.9,
79
+ },
63
80
  };
64
81
  }
65
82
 
@@ -50,18 +50,22 @@ describe("settings", () => {
50
50
  it("defaults to enabled/enforce/0.9, empty model (auto); explicit false wins", async () => {
51
51
  const { getClassifierSettings } = await import("../lib/settings.js");
52
52
  const s = getClassifierSettings();
53
- assert.deepEqual(s, { model: "", permission: { enabled: true, threshold: 0.9, mode: "enforce" } });
53
+ assert.deepEqual(s, {
54
+ model: "",
55
+ permission: { enabled: true, threshold: 0.9, mode: "enforce" },
56
+ planGate: { enabled: false, observe: false, threshold: 0.9 },
57
+ });
54
58
  writeFileSync(join(TMP_HOME, "settings.json"), JSON.stringify({ classifier: { permission: { enabled: false } } }));
55
59
  assert.equal(getClassifierSettings().permission.enabled, false);
56
60
  });
57
61
 
58
- it("reads the global classifier section; bad threshold falls back; planGate untouched", async () => {
62
+ it("reads the global classifier section; bad threshold falls back; foreign planGate keys ignored", async () => {
59
63
  const { getClassifierSettings } = await import("../lib/settings.js");
60
64
  writeFileSync(join(TMP_HOME, "settings.json"), JSON.stringify({
61
65
  classifier: {
62
66
  model: "combo/jev",
63
67
  permission: { enabled: true, mode: "enforce", threshold: 7 },
64
- planGate: { enabled: true, mode: "observe" }, // foreign key — must survive writes
68
+ planGate: { enabled: true, mode: "observe" }, // "mode" is a foreign key here — ignored, not consumed
65
69
  },
66
70
  }));
67
71
  const s = getClassifierSettings();
@@ -69,6 +73,7 @@ describe("settings", () => {
69
73
  assert.equal(s.permission.enabled, true);
70
74
  assert.equal(s.permission.mode, "enforce");
71
75
  assert.equal(s.permission.threshold, 0.9); // 7 rejected → default
76
+ assert.deepEqual(s.planGate, { enabled: true, observe: false, threshold: 0.9 }); // mode dropped, enabled read
72
77
  });
73
78
 
74
79
  it("writer merges without clobbering siblings (router, planGate) and clamps bad input", async () => {
@@ -466,6 +471,8 @@ describe("permission hook", () => {
466
471
  });
467
472
 
468
473
  it("no task captured → reversibility question only", async () => {
474
+ // Module-level lastTask (shared with the planGate consumer) persists
475
+ // across the module instance — an array with no text parts clears it.
469
476
  let questionCount = 0;
470
477
  const fx = await hookFixture(stubRegistry({
471
478
  classify: async (_m, context) => {
@@ -474,6 +481,7 @@ describe("permission hook", () => {
474
481
  },
475
482
  }));
476
483
  try {
484
+ fx.messageEnd([{ type: "image", mimeType: "image/png" }]);
477
485
  await fx.call("bun test");
478
486
  assert.equal(questionCount, 1);
479
487
  } finally { fx.cleanup(); }
@@ -504,7 +512,7 @@ describe("permission hook", () => {
504
512
  describe("config contribution", () => {
505
513
  it("builds the Model-tab groups over a working copy and routes owned keys", async () => {
506
514
  const { buildClassifierGroups, classifierConfig, setClassifierRegistry } = await import("../configPanel.js");
507
- const groups = buildClassifierGroups({ model: "", permission: { enabled: true, mode: "enforce", threshold: 0.9 } });
515
+ const groups = buildClassifierGroups({ model: "", permission: { enabled: true, mode: "enforce", threshold: 0.9 }, planGate: { enabled: false, observe: false, threshold: 0.9 } });
508
516
  assert.equal(groups[0].tab, "Model");
509
517
  assert.equal(groups[0].label, "Classifier (Jev)");
510
518
  assert.deepEqual(groups[0].rows.map((r) => r.key), [
@@ -64,10 +64,14 @@ export function builtinToolRows(working: Set<string>): PanelRow[] {
64
64
  );
65
65
  }
66
66
 
67
- /** The absolute defaultTools list that results from toggling `working`
68
- * (BUILTIN_TOOLS order, deterministic). Pure — exported for tests. */
67
+ /** The absolute defaultTools list that results from toggling `working` (BUILTIN_TOOLS
68
+ * order, deterministic; any non-builtin names still in `working` — e.g. seeded
69
+ * from an existing `+name`/arbitrary defaultTools entry — are appended so a
70
+ * toggle save cannot delete them). Pure — exported for tests. */
69
71
  export function nextDefaultTools(working: Set<string>): string[] {
70
- return BUILTIN_TOOLS.map(({ name }) => name).filter((n) => working.has(n));
72
+ const builtins = new Set(BUILTIN_TOOLS.map(({ name }) => name));
73
+ const others = [...working].filter((n) => !builtins.has(n));
74
+ return [...BUILTIN_TOOLS.map(({ name }) => name).filter((n) => working.has(n)), ...others];
71
75
  }
72
76
 
73
77
  /** Write the startup selection into the GLOBAL agent settings.json (the same
@@ -80,6 +80,22 @@ describe("nextDefaultTools", () => {
80
80
  const working = startupToolSet(SettingsManager.inMemory({ defaultTools: ["+codemode", "+grep"] }));
81
81
  assert.deepEqual(nextDefaultTools(working), [...STOCK, "grep", "codemode"]);
82
82
  });
83
+
84
+ it("preserves non-builtin names from the user's defaultTools through a toggle save", () => {
85
+ // A bare list may carry arbitrary names (pi accepts them) — toggling a
86
+ // builtin must not silently delete them.
87
+ const working = startupToolSet(SettingsManager.inMemory({ defaultTools: ["+codemode", "github"] }));
88
+ const rows = builtinToolRows(working);
89
+ rows.find((r) => r.key === `${DEFAULT_TOOLS_PREFIX}grep`)!.set(true);
90
+ const list = nextDefaultTools(working);
91
+ assert.ok(list.includes("github"), "arbitrary name survives");
92
+ assert.ok(list.includes("grep"), "toggled builtin included");
93
+
94
+ const file = tmpFile();
95
+ writeDefaultTools(list, file);
96
+ assert.deepEqual(readJson(file).defaultTools, list, "round-trip keeps both");
97
+ rmSync(path.dirname(file), { recursive: true, force: true });
98
+ });
83
99
  });
84
100
 
85
101
  describe("writeDefaultTools", () => {
@@ -394,6 +394,16 @@ const IMAGE_MIME: Record<string, string> = {
394
394
  png: "image/png", jpg: "image/jpeg", jpeg: "image/jpeg", gif: "image/gif", webp: "image/webp",
395
395
  };
396
396
 
397
+ /** Recognized image magic bytes — isProbablyBinary's NUL sniff is true for
398
+ * every real raster format, so the extension branch must win first (F10a). */
399
+ const IMAGE_MAGIC: Array<{ ext: string; test: (b: Buffer) => boolean }> = [
400
+ { ext: "png", test: (b) => b.subarray(0, 8).equals(Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a])) },
401
+ { ext: "jpg", test: (b) => b[0] === 0xff && b[1] === 0xd8 && b[2] === 0xff },
402
+ { ext: "jpeg", test: (b) => b[0] === 0xff && b[1] === 0xd8 && b[2] === 0xff },
403
+ { ext: "gif", test: (b) => b.subarray(0, 3).toString("latin1") === "GIF" },
404
+ { ext: "webp", test: (b) => b.subarray(0, 4).toString("latin1") === "RIFF" && b.subarray(8, 12).toString("latin1") === "WEBP" },
405
+ ];
406
+
397
407
  export async function executeFileRead(gh: GhRunner, cwd: string, params: GhParams, signal?: AbortSignal): Promise<{ text: string; image?: { data: string; mimeType: string } }> {
398
408
  const repo = await resolveGitHubRepoVia(gh, cwd, normalizeOptionalString(params.repo), undefined, signal);
399
409
  const filePath = requireNonEmpty(params.path, "path");
@@ -426,7 +436,12 @@ export async function executeFileRead(gh: GhRunner, cwd: string, params: GhParam
426
436
  const bytes = Buffer.from(encoded, "base64");
427
437
  const ext = filePath.split(".").pop()?.toLowerCase() ?? "";
428
438
  const mime = IMAGE_MIME[ext];
429
- if (mime && !isProbablyBinary(bytes)) {
439
+ // Recognized image EXTENSION wins FIRST (F10a): real PNG/JPEG/GIF/WebP all
440
+ // contain NUL bytes in the first 8KB, so the binary sniff would report
441
+ // "Cannot read binary file" for every actual image. Magic bytes gate the
442
+ // image block so a text file with an image extension still degrades to the
443
+ // binary/text paths below.
444
+ if (mime && IMAGE_MAGIC.some((m) => m.ext === ext && m.test(bytes))) {
430
445
  return { text: `Image file: ${filePath}`, image: { data: encoded, mimeType: mime } };
431
446
  }
432
447
  if (isProbablyBinary(bytes)) {
@@ -705,8 +720,8 @@ const sleep = (ms: number, signal?: AbortSignal): Promise<void> =>
705
720
 
706
721
  /**
707
722
  * Poll a workflow run until it completes; on failure tail each failed job's
708
- * logs. Watch budget comes from `timeoutMs` (the tool's overall deadline —
709
- * the caller passes gh-cli's 5-min window here).
723
+ * logs. Watch budget comes from `timeoutMs` (gh.runWatchTimeoutSecs, default
724
+ * 600s) — each gh poll stays bounded by gh-cli's own per-spawn deadline.
710
725
  */
711
726
  export async function executeRunWatch(gh: GhRunner, cwd: string, params: GhParams, signal?: AbortSignal, timeoutMs = 600_000): Promise<string> {
712
727
  const runReference = parseRunReference(params.run);
@@ -714,7 +729,10 @@ export async function executeRunWatch(gh: GhRunner, cwd: string, params: GhParam
714
729
  if (runId === undefined) throw new Error("run_watch requires `run` (workflow run ID or Actions run URL)");
715
730
  const repo = await resolveGitHubRepoVia(gh, cwd, normalizeOptionalString(params.repo), runReference.repo, signal);
716
731
  const tail = resolveTailLimit(params.tail);
717
- const deadline = Date.now() + Math.min(timeoutMs, 5 * 60_000 - 5_000);
732
+ // Honor the configured budget as-is (F10b) — the old Math.min(…, 295s) cap
733
+ // silently halved the documented 600s default. Floor 10s so a misconfigured
734
+ // 0/negative still terminates; each poll is bounded by gh-cli's GH_TIMEOUT_MS.
735
+ const deadline = Date.now() + Math.max(10_000, timeoutMs);
718
736
  const watchStartMs = Date.now();
719
737
  const intervalSeconds = () => (Date.now() - watchStartMs < RUN_WATCH_FAST_WINDOW_MS ? RUN_WATCH_INTERVAL_DEFAULT : RUN_WATCH_INTERVAL_SLOW);
720
738
 
@@ -181,15 +181,32 @@ describe("repo_view / file_read", () => {
181
181
 
182
182
  it("file_read flags binary content and returns the image block for images", async () => {
183
183
  const binary = Buffer.from([0x00, 0x01, 0x02]).toString("base64");
184
- const png = Buffer.from("89504e47", "hex").toString("base64");
184
+ // REALISTIC PNG: full signature + IHDR (contains NUL bytes in the first
185
+ // 8KB — the old 4-byte-magic fixture without NULs masked the defect where
186
+ // isProbablyBinary reported every actual image as "Cannot read binary file").
187
+ const png = Buffer.concat([
188
+ Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]), // signature
189
+ Buffer.from([0x00, 0x00, 0x00, 0x0d]), // IHDR length
190
+ Buffer.from("IHDR"),
191
+ Buffer.from([0x00, 0x00, 0x03, 0x20, 0x00, 0x00, 0x01, 0xe0, 0x08, 0x06, 0x00, 0x00, 0x00]), // w/h/depth (NULs)
192
+ Buffer.alloc(512, 0), // IDAT-ish zero-filled body
193
+ ]).toString("base64");
185
194
  const { gh } = fakeGh([
186
195
  { match: (a) => a.some((x) => String(x).includes("bin.dat")), respond: () => ({ stdout: JSON.stringify({ encoding: "base64", content: binary }) }) },
187
196
  { match: (a) => a.some((x) => String(x).includes("img.png")), respond: () => ({ stdout: JSON.stringify({ encoding: "base64", content: png }) }) },
197
+ { match: (a) => a.some((x) => String(x).includes("fake.png")), respond: () => ({ stdout: JSON.stringify({ encoding: "base64", content: Buffer.from("just text, no magic").toString("base64") }) }) },
188
198
  ]);
189
199
  const bin = await executeFileRead(gh, CWD, { repo: "acme/widget", path: "bin.dat" });
190
200
  assert.match(bin.text, /Cannot read binary file/);
201
+ // A real PNG (NUL-heavy) reaches the image block instead of the binary refusal.
191
202
  const img = await executeFileRead(gh, CWD, { repo: "acme/widget", path: "img.png" });
192
203
  assert.equal(img.image?.mimeType, "image/png");
204
+ assert.doesNotMatch(img.text, /Cannot read binary file/);
205
+ // Magic-byte gate: a TEXT file wearing .png is NOT served as an image —
206
+ // it falls through to the plain-text decode path (valid UTF-8, no magic).
207
+ const fake = await executeFileRead(gh, CWD, { repo: "acme/widget", path: "fake.png" });
208
+ assert.equal(fake.image, undefined);
209
+ assert.match(fake.text, /just text, no magic/);
193
210
  });
194
211
  });
195
212
 
@@ -247,6 +264,52 @@ describe("run_watch", () => {
247
264
  assert.match(text, /watch budget elapsed/);
248
265
  });
249
266
 
267
+ it("F10b: the budget-elapsed note fires only after the CONFIGURED window (no 295s silent cap)", { timeout: 8_000 }, async () => {
268
+ const inProgress = { id: 3, name: "CI", status: "in_progress", html_url: "https://ci/3" };
269
+ // The fake gh advances the FAKE clock by 400s while serving the poll —
270
+ // simulating a slow poll. Under the old Math.min(…, 295s) cap the budget
271
+ // was already exhausted at that point and the note fired; under the fixed
272
+ // code 400s < the configured 600s, so the loop KEEPS POLLING (proven by
273
+ // aborting during the inter-poll sleep: it rejects "Operation aborted"
274
+ // instead of returning the note).
275
+ const run = async (jumpMs: number, abortDuringSleep: boolean): Promise<string> => {
276
+ const realNow = Date.now;
277
+ let fakeNow = 1_000_000;
278
+ Date.now = () => fakeNow;
279
+ const controller = new AbortController();
280
+ const { gh } = fakeGh([
281
+ { match: (a) => a[0] === "repo" && a[1] === "view", respond: () => ({ stdout: "https://github.com/acme/widget" }) },
282
+ { match: (a) => a.some((x) => String(x).endsWith("/actions/runs/3")), respond: () => { fakeNow += jumpMs; return { stdout: JSON.stringify(inProgress) }; } },
283
+ { match: (a) => a.some((x) => String(x).includes("/actions/runs/3/jobs")), respond: () => ({ stdout: JSON.stringify({ jobs: [] }) }) },
284
+ ]);
285
+ try {
286
+ const pending = executeRunWatch(gh, CWD, { run: "3" }, controller.signal, 600_000);
287
+ if (abortDuringSleep) {
288
+ // The first poll's sleep (3s real) is pending — abort inside it.
289
+ setTimeout(() => controller.abort(), 50);
290
+ await assert.rejects(() => pending, /Operation aborted/);
291
+ return "kept-polling";
292
+ }
293
+ // No abort: let the loop reach the post-sleep budget check. Nudge the
294
+ // fake clock across the deadline while the real 3s sleep runs.
295
+ const winner = await Promise.race([
296
+ pending.then((t) => t),
297
+ new Promise<string>((resolve) => setTimeout(() => { fakeNow += 900_000; resolve("nudged"); }, 100)),
298
+ new Promise<string>((resolve) => setTimeout(() => resolve("hung"), 5_000)),
299
+ ]);
300
+ controller.abort();
301
+ return winner === "hung" ? "hung" : String(await Promise.race([pending, Promise.resolve("still-pending")]).then((t) => (typeof t === "string" && t.includes("budget")) || t === "still-pending" ? t : "other"));
302
+ } finally {
303
+ Date.now = realNow;
304
+ }
305
+ };
306
+ // 400s fake-elapsed < 600s configured → NO note (old cap: 295s → note).
307
+ assert.equal(await run(400_000, true), "kept-polling");
308
+ // Past the configured 600s → the note fires.
309
+ const late = await run(700_000, false);
310
+ assert.match(late, /watch budget elapsed/);
311
+ });
312
+
250
313
  it("classifies failed jobs and clamps tail", () => {
251
314
  assert.equal(isFailedJob({ id: 1, name: "j", conclusion: "failure" }), true);
252
315
  assert.equal(isFailedJob({ id: 1, name: "j", conclusion: "success" }), false);
@@ -52,6 +52,8 @@ import {
52
52
  type ThinkingLevel,
53
53
  } from "./lib/settings.js";
54
54
  import { getPlanRegistry, planConfig, setPlanBridge, setPlanRegistry, type PlanBridge } from "./configPanel.js";
55
+ import { askJev, audit, getLastTask, isRisky, noul, segments } from "../classifier/index.js";
56
+ import { getClassifierSettings } from "../classifier/lib/settings.js";
55
57
  // Sandbox semantics live in ONE place: the subagent module resolves agent
56
58
  // frontmatter (user + project + bundled). discoverAgents is a pure fs loader,
57
59
  // independent of whether the subagent module itself is enabled.
@@ -63,6 +65,103 @@ export const PLAN_ENTRY_TYPE = "ceulen-plan";
63
65
  export const PLAN_TOOL = "write_plan";
64
66
  export const ASK_USER_QUESTION_TOOL = "ask_user_question";
65
67
 
68
+ // ── planGate (classifier.planGate) ──────────────────────────────────────────
69
+ // The classifier can move a CONFIRM-tier bash command to auto-run when Jev
70
+ // says it clearly doesn't mutate and serves the task. It can never do the
71
+ // reverse: write stays a hard block, read stays auto. Off by default — run
72
+ // `planGate.observe` first and read the ceulen-plan-gate lines in
73
+ // classifier.log before flipping enabled.
74
+
75
+ // ponytail: value of classifier's CLASSIFIER_HOOK_BUDGET_MS — the constant is
76
+ // module-private and importing it would be module state, not a value.
77
+ const PLAN_GATE_BUDGET_MS = 2_500;
78
+
79
+ interface PlanGateVerdict {
80
+ mutates: number;
81
+ reversible: number;
82
+ serves: number;
83
+ safe: boolean;
84
+ }
85
+
86
+ /** Ask Jev about a confirm-tier command. Returns undefined on any failure —
87
+ * the confirm tier is the unchanged fallback. Exported for tests. */
88
+ export async function planGateVerdict(command: string, ctx: ExtensionContext): Promise<PlanGateVerdict | undefined> {
89
+ const task = getLastTask();
90
+ const state: Record<string, unknown> = { command, project_path: ctx.cwd, ...(task ? { task } : {}) };
91
+ const questions: Record<string, unknown> = {
92
+ mutates_filesystem: {
93
+ type: "bool",
94
+ instructions: "Does this command modify files or state outside the shell's own process?",
95
+ criteria: { yes: "Writes, deletes, moves, installs, or otherwise changes persistent state.", no: "Purely observational — reads, lists, searches, prints." },
96
+ },
97
+ reversible: {
98
+ type: "bool",
99
+ instructions: "If it DID have an effect, could that effect be undone or discarded without lasting harm?",
100
+ },
101
+ ...(task
102
+ ? {
103
+ serves_task: {
104
+ type: "bool",
105
+ instructions: "Does this command plausibly serve the task the user asked for?",
106
+ criteria: { yes: "A reasonable step toward the user's stated task.", no: "Unrelated to the task, or only a step the task never needed." },
107
+ },
108
+ }
109
+ : {}),
110
+ };
111
+ const started = Date.now();
112
+ try {
113
+ const budget = AbortSignal.timeout(PLAN_GATE_BUDGET_MS);
114
+ const answers = (await Promise.race([
115
+ askJev(ctx, state, questions, budget),
116
+ new Promise<never>((_, reject) => budget.addEventListener("abort", () => reject(new Error("plan gate budget exceeded")), { once: true })),
117
+ ])) as Record<string, unknown>;
118
+ const mutates = noul(answers, "mutates_filesystem");
119
+ const reversible = noul(answers, "reversible");
120
+ const serves = task ? noul(answers, "serves_task") : reversible; // no task → serve check degenerates
121
+ const { planGate } = getClassifierSettings();
122
+ const safe = Number.isFinite(mutates) && mutates < 0.2 && Number.isFinite(reversible) && reversible >= planGate.threshold && serves >= planGate.threshold;
123
+ await audit({
124
+ tag: "ceulen-plan-gate",
125
+ command,
126
+ mutates_filesystem: Number.isFinite(mutates) ? mutates : null,
127
+ reversible: Number.isFinite(reversible) ? reversible : null,
128
+ serves_task: Number.isFinite(serves) ? serves : null,
129
+ safe,
130
+ observe: planGate.observe,
131
+ enforcing: planGate.enabled,
132
+ ms: Date.now() - started,
133
+ });
134
+ return { mutates, reversible, serves, safe };
135
+ } catch (e) {
136
+ await audit({ tag: "ceulen-plan-gate", command, error: String(e instanceof Error ? e.message : e), ms: Date.now() - started });
137
+ return undefined;
138
+ }
139
+ }
140
+
141
+ /** Returns true when the gate auto-runs the command (only possible when
142
+ * planGate.enabled); undefined → fall through to the normal confirm tier. */
143
+ async function planGateAutoRun(command: string, ctx: ExtensionContext): Promise<boolean | undefined> {
144
+ const { planGate } = getClassifierSettings();
145
+ if (!planGate.enabled && !planGate.observe) return undefined;
146
+ // Static risk list first — credential/irreversible shapes never reach Jev
147
+ // and never leave the normal confirm tier. The whole command AND its
148
+ // segments: the pipe-to-shell regexes need the unsplit command, while
149
+ // segments expose risky commands hidden after && / ;.
150
+ if (isRisky(command) || segments(command).some(isRisky)) return undefined;
151
+ const verdict = await planGateVerdict(command, ctx);
152
+ if (verdict?.safe && planGate.enabled) {
153
+ if (ctx.hasUI) {
154
+ try {
155
+ ctx.ui.notify(`plan gate: auto-allowed (${command.slice(0, 80)})`, "info");
156
+ } catch {
157
+ /* non-tui */
158
+ }
159
+ }
160
+ return true;
161
+ }
162
+ return undefined;
163
+ }
164
+
66
165
  /** Persisted plan-mode session state (branch-scoped via appendEntry). */
67
166
  export interface PlanState {
68
167
  enabled: boolean;
@@ -492,11 +591,20 @@ export default function planModule(pi: ExtensionAPI): void {
492
591
  }
493
592
 
494
593
  /** Approve + execute in the current session. Shared by /plan-approve and
495
- * the auto-approve settle path (no command context needed). */
594
+ * the auto-approve settle path (no command context needed). A failure
595
+ * (e.g. materializePlan hitting an unwritable plans dir) must not swallow
596
+ * the approval: the ready flag is restored so /plan-approve can retry. */
496
597
  async function executeInCurrentSession(ctx: ExtensionContext): Promise<void> {
497
- await materializePlan();
498
- const relativePlan = await exitPlanForExecution(ctx);
499
- pi.sendUserMessage(buildExecutionPrompt(relativePlan, "current"), { deliverAs: "followUp" });
598
+ try {
599
+ await materializePlan();
600
+ const relativePlan = await exitPlanForExecution(ctx);
601
+ pi.sendUserMessage(buildExecutionPrompt(relativePlan, "current"), { deliverAs: "followUp" });
602
+ } catch (error) {
603
+ planReadyForReview = true;
604
+ persistState();
605
+ const reason = error instanceof Error ? error.message : String(error);
606
+ ctx.ui.notify(`Auto-approve failed: ${reason} — run /plan-approve to retry.`, "error");
607
+ }
500
608
  }
501
609
 
502
610
  /** Approve + hand the plan to a fresh session (command context only:
@@ -831,6 +939,10 @@ export default function planModule(pi: ExtensionAPI): void {
831
939
  reason: `plan mode: writing to the filesystem is not allowed while planning. "${command}" may modify files. Exit plan mode to run this command, or use ${PLAN_TOOL} to add file content to the plan.`,
832
940
  };
833
941
  }
942
+ // planGate (classifier.planGate, off by default): may AUTO-RUN a safe
943
+ // confirm-tier command. Any other answer → the confirm tier below,
944
+ // unchanged. Never reached for read (already auto) or write (hard block).
945
+ if (await planGateAutoRun(command, ctx)) return;
834
946
  if (!ctx.hasUI) return { block: true, reason: `plan mode: this command requires confirmation but UI is not available.\nCommand: ${command}` };
835
947
  const firstToken = command.trim().split(/\s+/)[0] || "bash";
836
948
  const allowKey = INTERPRETER_TOKENS.has(firstToken) ? `bash-cmd:${command.trim()}` : `bash:${firstToken}`;
@@ -148,16 +148,14 @@ export function planPath(cwd: string, title: string, plansDir: string = DEFAULT_
148
148
  return path.join(cwd, expandPlansDir(plansDir), `${stamp}-${slug}.md`);
149
149
  }
150
150
 
151
- /** True when `resolved` is a file inside the configured plans dir; `{yyyymm}`
152
- * matches any single path segment so monthly subfolders stay inside. */
151
+ /** True when `resolved` is a file inside the configured plans dir; a
152
+ * `{yyyymm}` pattern segment must match an actual 6-digit month segment
153
+ * (segment-wise — a bare wildcard splice would let ANY segment stand in). */
153
154
  export function isInsidePlansDir(resolved: string, plansDir: string, cwd: string): boolean {
154
155
  const pattern = path.resolve(cwd, plansDir).split(/[\\/]/).filter(Boolean);
155
156
  const actual = path.resolve(cwd, resolved).split(/[\\/]/).filter(Boolean);
156
- const wildcard = pattern.indexOf("{yyyymm}");
157
- const root = wildcard === -1 ? pattern : pattern.filter((seg) => seg !== "{yyyymm}");
158
- if (actual.length <= root.length) return false;
159
- if (wildcard !== -1) actual.splice(wildcard, 1);
160
- return root.every((seg, i) => actual[i] === seg);
157
+ if (actual.length <= pattern.length) return false;
158
+ return pattern.every((seg, i) => (seg === "{yyyymm}" ? /^\d{6}$/.test(actual[i] ?? "") : actual[i] === seg));
161
159
  }
162
160
 
163
161
  /** Relative path with forward slashes (prompt text). */