ceulen 0.20.0 → 0.25.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 (53) hide show
  1. package/CHANGELOG.md +176 -0
  2. package/extensions/lib/env.test.ts +45 -0
  3. package/extensions/lib/env.ts +56 -3
  4. package/extensions/lib/registry.ts +8 -0
  5. package/extensions/lib/skill-path.test.ts +1 -1
  6. package/extensions/modules/a2a/lib/gateway.ts +3 -0
  7. package/extensions/modules/a2a/lib/persistence.ts +3 -2
  8. package/extensions/modules/a2a/test/persistence.test.ts +12 -0
  9. package/extensions/modules/classifier/index.ts +12 -1
  10. package/extensions/modules/classifier/lib/settings.ts +21 -0
  11. package/extensions/modules/classifier/lib/think-gate.ts +211 -0
  12. package/extensions/modules/classifier/test/classifier.test.ts +285 -1
  13. package/extensions/modules/composer/lib/shapes.ts +2 -1
  14. package/extensions/modules/cron/index.ts +1 -0
  15. package/extensions/modules/cron/lib/jobs.ts +2 -1
  16. package/extensions/modules/cron/test/cwd-repro.test.ts +10 -1
  17. package/extensions/modules/goal/configPanel.ts +63 -0
  18. package/extensions/modules/goal/index.ts +545 -0
  19. package/extensions/modules/goal/lib/settings.ts +73 -0
  20. package/extensions/modules/goal/lib/state.ts +223 -0
  21. package/extensions/modules/goal/test/goal.test.ts +522 -0
  22. package/extensions/modules/jfind/index.ts +13 -4
  23. package/extensions/modules/jfind/lib/cascade.ts +5 -2
  24. package/extensions/modules/jfind/lib/tree.ts +8 -3
  25. package/extensions/modules/jfind/test/cascade.test.ts +28 -1
  26. package/extensions/modules/munin/configPanel.ts +13 -3
  27. package/extensions/modules/munin/index.ts +7 -4
  28. package/extensions/modules/munin/test/configPanel.test.ts +9 -3
  29. package/extensions/modules/munin/test/extension.test.ts +31 -0
  30. package/extensions/modules/permission/index.ts +20 -9
  31. package/extensions/modules/permission/test/permission.test.ts +33 -1
  32. package/extensions/modules/plan/index.ts +36 -7
  33. package/extensions/modules/plan/lib/shell-gate.ts +93 -26
  34. package/extensions/modules/plan/test/module.test.ts +114 -1
  35. package/extensions/modules/plan/test/shell-gate.test.ts +64 -0
  36. package/extensions/modules/repair/lib/guards.ts +4 -1
  37. package/extensions/modules/repair/test/guards.test.ts +9 -0
  38. package/extensions/modules/router/lib/client.ts +24 -0
  39. package/extensions/modules/router/test/unit.test.ts +33 -3
  40. package/extensions/modules/sg/index.ts +3 -3
  41. package/extensions/modules/sg/lib/ops.ts +15 -1
  42. package/extensions/modules/sg/test/sg.test.ts +16 -2
  43. package/extensions/modules/subagent/index.ts +12 -1
  44. package/extensions/modules/subagent/lib/herdr.ts +37 -3
  45. package/extensions/modules/subagent/lib/history.ts +6 -2
  46. package/extensions/modules/subagent/lib/settings.ts +2 -1
  47. package/extensions/modules/subagent/test/extension.test.ts +31 -0
  48. package/extensions/modules/subagent/test/file-modes.test.ts +40 -0
  49. package/extensions/modules/subagent/test/herdr-stalled.test.ts +39 -0
  50. package/extensions/modules/web/lib/chatgpt.ts +2 -1
  51. package/extensions/scripts/probe-thinking.mjs +108 -0
  52. package/package.json +4 -4
  53. package/skills/review/SKILL.md +45 -0
@@ -0,0 +1,211 @@
1
+ // think-gate.ts — main-session per-turn thinking gate (classifier.thinkGate).
2
+ //
3
+ // One Jev score question per USER turn ("how much reasoning does this turn
4
+ // need?") sets the session thinking level; the baseline is restored at settle.
5
+ // planGate precedent: default fully OFF, observe-first rollout, 2.5s budget,
6
+ // fail-open everywhere, every verdict audited to classifier.log.
7
+ //
8
+ // Scope guards (each returns without classifying):
9
+ // - custom/triggerTurn messages (cron fires, subagent receipts) — only
10
+ // messageType "user" turns are gated;
11
+ // - plan mode (extensions/lib/plan-bridge.ts — the plan module owns the dial);
12
+ // - CEULEN_THINK_GATE_OFF=1 (herdr pane children — they get dispatch-routed
13
+ // thinking already; a per-turn gate would double-classify and fight it);
14
+ // - stood-down sessions: ANY thinking_level_select event we did not cause
15
+ // (user /think, level cycling, a model switch whose clamp differs) disables
16
+ // the gate until restart — a user who touches the dial owns the dial.
17
+ //
18
+ // Ownership of our own set: pi emits thinking_level_select only when the level
19
+ // actually changes (agent-session.js setThinkingLevel isChanging gate), with
20
+ // {level, previousLevel} — our set always yields level===ours.to &&
21
+ // previousLevel===ours.from; a <1.5s window guards the pathological late emit.
22
+ // Both must hold, else the event reads as manual.
23
+
24
+ import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
25
+ import { askJev, audit } from "../index.js";
26
+ import { getClassifierSettings } from "./settings.js";
27
+ import { isPlanActive } from "../../../lib/plan-bridge.js";
28
+
29
+ const TAG = "ceulen-think-gate";
30
+ const BUDGET_MS = 2_500;
31
+ /** Guards against a pathologically late event being misread as ours (pi emits
32
+ * synchronously off setThinkingLevel, so real ownership arrives in ms). */
33
+ const OWNERSHIP_WINDOW_MS = 1_500;
34
+
35
+ /** Keep in sync with extensions/modules/subagent/lib/routing.ts EFFORT_LADDER
36
+ * (same 5 rungs; a local copy so the classifier module stays dependency-free). */
37
+ const EFFORT_LADDER: readonly string[] = [
38
+ "off: mechanical lookup or trivial edit, no reasoning needed",
39
+ "low: simple, well-specified change; fix already identified",
40
+ "medium: normal multi-step implementation or verification",
41
+ "high: cross-file reasoning, subtle interactions, careful refactor",
42
+ "xhigh: architecture, design tradeoffs, consequential planning",
43
+ ];
44
+ const LEVELS = ["off", "low", "medium", "high", "xhigh"] as const;
45
+ type Level = (typeof LEVELS)[number];
46
+
47
+ interface Ours {
48
+ setAt: number;
49
+ from: Level;
50
+ to: Level;
51
+ }
52
+
53
+ /** Armed BEFORE a setThinkingLevel call: pi's thinking_level_select arrives
54
+ * synchronously off the call site (live-verified 2026-10-19 — the event lands
55
+ * before the line after the call executes), so post-call attribution is too
56
+ * late. The arm is consumed by the next event, whatever its (clamped) values.
57
+ * A no-change set emits nothing; the arm then lingers windowed (5s) and only
58
+ * risks mis-attributing a pathological same-second manual change — fail-open
59
+ * direction: the gate keeps running. */
60
+ let expectEventAt = 0;
61
+ const EXPECT_EVENT_WINDOW_MS = 5_000;
62
+
63
+ export function registerThinkGate(pi: ExtensionAPI): void {
64
+ let ours: Ours | undefined;
65
+ let stoodDown = false;
66
+ let reportedNoModel = false;
67
+
68
+ const reset = () => {
69
+ ours = undefined;
70
+ stoodDown = false;
71
+ reportedNoModel = false;
72
+ expectEventAt = 0;
73
+ };
74
+
75
+ pi.on("session_start", () => reset());
76
+ pi.on("session_shutdown", () => reset());
77
+
78
+ pi.on("before_agent_start", async (event, ctx) => {
79
+ if (event.messageType !== "user" || !event.prompt) return undefined;
80
+ if (process.env.CEULEN_THINK_GATE_OFF) return undefined;
81
+ if (stoodDown || isPlanActive()) return undefined;
82
+ const { thinkGate } = getClassifierSettings();
83
+ if (!thinkGate.enabled && !thinkGate.observe) return undefined;
84
+
85
+ const current = pi.getThinkingLevel() as Level;
86
+ const model = ctx.model;
87
+ const head = event.prompt.slice(0, 4000);
88
+ const finish = (entry: Record<string, unknown>) =>
89
+ // Awaited by the caller: one append per turn is ~1ms and makes the
90
+ // audit-vs-settle ordering deterministic. (The bash hook keeps
91
+ // fire-and-forget — that one is a per-tool-call hot path.)
92
+ audit({ tag: TAG, prompt_head: head.slice(0, 80), model: model?.id, current_level: current, ...entry });
93
+
94
+ let score: number | undefined;
95
+ let confidence: number | undefined;
96
+ let reason: string | undefined;
97
+ try {
98
+ const budget = AbortSignal.timeout(BUDGET_MS);
99
+ const answers = (await Promise.race([
100
+ askJev(
101
+ ctx,
102
+ { prompt: head, model: model?.id, current_level: current },
103
+ {
104
+ effort: {
105
+ type: "score",
106
+ instructions: "How much reasoning does this turn need?",
107
+ criteria: [...EFFORT_LADDER],
108
+ },
109
+ },
110
+ budget,
111
+ ),
112
+ new Promise<never>((_, reject) => budget.addEventListener("abort", () => reject(new Error("think gate budget exceeded")), { once: true })),
113
+ ])) as Record<string, unknown>;
114
+ const effort = answers.effort as { score?: unknown; confidence?: unknown } | undefined;
115
+ if (effort && typeof effort.score === "number" && Number.isFinite(effort.score)) {
116
+ score = effort.score;
117
+ confidence = typeof effort.confidence === "number" ? effort.confidence : undefined;
118
+ } else {
119
+ reason = "malformed answer";
120
+ }
121
+ } catch (e) {
122
+ reason = e instanceof Error ? e.message.slice(0, 80) : "classifier error";
123
+ }
124
+
125
+ if (score === undefined) {
126
+ // Circuit-breaker for the log: a missing classifier model fail-opens on
127
+ // EVERY turn — one audit line per turn is noise, one per session is a
128
+ // trace. First miss writes the line and arms the flag; later misses are
129
+ // silent (a malformed answer re-reports once via its own branch).
130
+ if (reason?.includes("no classifier model")) {
131
+ if (!reportedNoModel) {
132
+ reportedNoModel = true;
133
+ await finish({ applied: false, reason });
134
+ }
135
+ } else {
136
+ await finish({ applied: false, reason });
137
+ }
138
+ return undefined;
139
+ }
140
+ if (confidence !== undefined && confidence < thinkGate.threshold) {
141
+ await finish({ applied: false, reason: `confidence ${confidence} < ${thinkGate.threshold}`, verdict_score: score });
142
+ return undefined;
143
+ }
144
+
145
+ const idx = Math.min(Math.max(Math.round(score), 0), LEVELS.length - 1);
146
+ const verdict = LEVELS[idx];
147
+ if (thinkGate.observe || verdict === current) {
148
+ await finish({ applied: false, reason: thinkGate.observe ? "observe" : "same", verdict, confidence });
149
+ return undefined;
150
+ }
151
+
152
+ // Arm BEFORE the set: pi emits synchronously off the call site (live
153
+ // 2026-10-19) — `ours` and the event arm must be complete when the
154
+ // handler runs.
155
+ ours = { setAt: Date.now(), from: current, to: verdict };
156
+ expectEventAt = Date.now();
157
+ pi.setThinkingLevel(verdict);
158
+ // pi CLAMPS the requested level (GLM-5.3 has no real "off": off→minimal
159
+ // via the zai53 map) — keep the EFFECTIVE level as ours.to so the settle
160
+ // check compares against reality. (Live lesson 2026-10-19: verdict "off"
161
+ // clamped to "minimal"; the raw-verdict comparison restored nothing.)
162
+ ours.to = pi.getThinkingLevel() as Level;
163
+ if (ours.to === ours.from) ours = undefined;
164
+ await finish({ applied: true, verdict, confidence, baseline: current });
165
+ return undefined;
166
+ });
167
+
168
+ pi.on("agent_settled", async () => {
169
+ if (!ours) return;
170
+ const current = pi.getThinkingLevel() as Level;
171
+ const o = ours;
172
+ ours = undefined;
173
+ if (current === o.to) {
174
+ expectEventAt = Date.now();
175
+ pi.setThinkingLevel(o.from);
176
+ // Re-read: the restore is also subject to the clamp — log what actually
177
+ // happened, and skip the audit on a no-op (a no-op emits no event; the
178
+ // lingering arm is windowed and harmless).
179
+ const restoredTo = pi.getThinkingLevel() as Level;
180
+ if (restoredTo !== o.to) {
181
+ await audit({ tag: TAG, restored: restoredTo, verdict: o.to });
182
+ }
183
+ }
184
+ // Level moved by someone else mid-turn: thinking_level_select already
185
+ // stood the gate down; nothing to restore here.
186
+ });
187
+
188
+ pi.on("thinking_level_select", async (event) => {
189
+ // Kill-switch first: a herdr child's pi INIT fires this event (model default
190
+ // re-apply) before any turn — without this guard the child logs a spurious
191
+ // stoodDown even though its gate is env-disabled (live herdr test
192
+ // 2026-10-19). Inert means fully inert.
193
+ if (process.env.CEULEN_THINK_GATE_OFF) return;
194
+ // Our own forward set or settle-restore (armed at the call site; pi emits
195
+ // the CLAMPED values, which we cannot predict — the arm is the attribution).
196
+ if (expectEventAt && Date.now() - expectEventAt < EXPECT_EVENT_WINDOW_MS) {
197
+ expectEventAt = 0;
198
+ return;
199
+ }
200
+ const isOurs = ours !== undefined
201
+ && event.level === ours.to
202
+ && event.previousLevel === ours.from
203
+ && Date.now() - ours.setAt < OWNERSHIP_WINDOW_MS;
204
+ if (isOurs) return;
205
+ if (!stoodDown) {
206
+ stoodDown = true;
207
+ ours = undefined;
208
+ await audit({ tag: TAG, stoodDown: true, level: event.level, previousLevel: event.previousLevel });
209
+ }
210
+ });
211
+ }
@@ -54,6 +54,7 @@ describe("settings", () => {
54
54
  model: "",
55
55
  permission: { enabled: true, threshold: 0.9, mode: "enforce" },
56
56
  planGate: { enabled: false, observe: false, threshold: 0.9 },
57
+ thinkGate: { enabled: false, observe: false, threshold: 0.6 },
57
58
  });
58
59
  writeFileSync(join(TMP_HOME, "settings.json"), JSON.stringify({ classifier: { permission: { enabled: false } } }));
59
60
  assert.equal(getClassifierSettings().permission.enabled, false);
@@ -320,6 +321,7 @@ function hookFixture(registry: RegistryStub, settings: Record<string, unknown> =
320
321
  const hookCtx = { ...fakeCtx, modelRegistry: registry };
321
322
  return {
322
323
  call: (command: string, ctx = hookCtx) => handlers.tool_call(bashEvent(command), ctx),
324
+ callEvent: (event: { toolName: string; input: Record<string, unknown> }, ctx = hookCtx) => handlers.tool_call(event, ctx),
323
325
  messageEnd: (content: unknown) => handlers.message_end({ message: { role: "user", content } }, {}),
324
326
  logPath: join(dir, "classifier.log"),
325
327
  cleanup: () => {
@@ -512,7 +514,7 @@ describe("permission hook", () => {
512
514
  describe("config contribution", () => {
513
515
  it("builds the Model-tab groups over a working copy and routes owned keys", async () => {
514
516
  const { buildClassifierGroups, classifierConfig, setClassifierRegistry } = await import("../configPanel.js");
515
- const groups = buildClassifierGroups({ model: "", permission: { enabled: true, mode: "enforce", threshold: 0.9 }, planGate: { enabled: false, observe: false, threshold: 0.9 } });
517
+ const groups = buildClassifierGroups({ model: "", permission: { enabled: true, mode: "enforce", threshold: 0.9 }, planGate: { enabled: false, observe: false, threshold: 0.9 }, thinkGate: { enabled: false, observe: false, threshold: 0.6 } });
516
518
  assert.equal(groups[0].tab, "Model");
517
519
  assert.equal(groups[0].label, "Classifier (Jev)");
518
520
  assert.deepEqual(groups[0].rows.map((r) => r.key), [
@@ -543,3 +545,285 @@ describe("config contribution", () => {
543
545
  await cfg.save(new Set(["router.baseUrl"]), { ui: { notify: () => {} }, cwd: "/p" } as never);
544
546
  });
545
547
  });
548
+
549
+ // F4 (security review 2026-10-17): a shell START runs shell:true with a
550
+ // command — same exposure as bash, so the risky hook annotates it too.
551
+ describe("permission hook — shell start parity (F4)", () => {
552
+ it("risky shell-start never reaches Jev; benign shell-start is consulted", async () => {
553
+ let classifyCalls = 0;
554
+ const counts = () => ({ classify: async () => { classifyCalls++; return { stopReason: "stop", answers: {} }; } });
555
+ const fx = await hookFixture(stubRegistry(counts()));
556
+ try {
557
+ const shellEvent = (input: Record<string, unknown>) => ({ toolName: "shell", input, toolCallId: "t2" });
558
+ // risky: static list refuses, no Jev round-trip
559
+ assert.equal(await fx.callEvent(shellEvent({ action: "start", command: "rm -rf /tmp/f4x" })), undefined);
560
+ assert.equal(classifyCalls, 0);
561
+ // benign: the hook consults Jev exactly like a bash call
562
+ await fx.callEvent(shellEvent({ action: "start", command: "git status" }));
563
+ assert.equal(classifyCalls, 1);
564
+ // non-start actions are not commands — never consulted
565
+ await fx.callEvent(shellEvent({ action: "output", shellId: "s1" }));
566
+ assert.equal(classifyCalls, 1);
567
+ } finally {
568
+ fx.cleanup();
569
+ }
570
+ });
571
+ });
572
+
573
+ // ── think gate (main-session per-turn thinking level) ──────────────────────
574
+
575
+ interface GateFixture {
576
+ turn: (prompt: string, overrides?: { messageType?: string }) => Promise<unknown>;
577
+ settle: () => Promise<unknown>;
578
+ levelSelect: (level: string, previousLevel: string) => Promise<unknown>;
579
+ calls: () => number;
580
+ sets: () => { level: string }[];
581
+ log: () => Record<string, unknown>[];
582
+ cleanup: () => void;
583
+ }
584
+
585
+ /** Gate fixture: settings file in a temp agent dir, registry stub answers the
586
+ * effort question, fake pi records setThinkingLevel calls (emitting
587
+ * thinking_level_select on change — pi's isChanging contract). */
588
+ async function gateFixture(
589
+ registry: RegistryStub,
590
+ settings: Record<string, unknown>,
591
+ env: Record<string, string | undefined> = {},
592
+ initialLevel = "medium",
593
+ /** Simulate a level-capped model: the clamp DOWNWARD the advisor flagged
594
+ * (xhigh→high). Default: no downward cap. */
595
+ capAt: string | undefined = undefined,
596
+ ): Promise<GateFixture> {
597
+ const dir = mkdtempSync(join(tmpdir(), "ceulen-cl-gate-"));
598
+ const prevHome = process.env.PI_CODING_AGENT_DIR;
599
+ process.env.PI_CODING_AGENT_DIR = dir;
600
+ writeFileSync(join(dir, "settings.json"), JSON.stringify({ classifier: { model: "combo/jev", ...settings } }));
601
+ const prevEnv: Record<string, string | undefined> = {};
602
+ for (const k of Object.keys(env)) { prevEnv[k] = process.env[k]; if (env[k] === undefined) delete process.env[k]; else process.env[k] = env[k]; }
603
+ const handlers: Record<string, (event: unknown, ctx: unknown) => Promise<unknown>> = {};
604
+ const sets: { level: string }[] = [];
605
+ // Supported levels per the zai53 map (off→null means pi clamps it forward).
606
+ const supported = ["minimal", "low", "medium", "high", "xhigh", "max"];
607
+ const clamp = (level: string): string => {
608
+ if (capAt && supported.indexOf(level) > supported.indexOf(capAt)) return capAt; // clamp DOWN (capped model)
609
+ if (supported.includes(level)) return level;
610
+ if (level === "off") return "minimal"; // pi rounds UP from off
611
+ return level;
612
+ };
613
+ let currentLevel = initialLevel;
614
+ const fakePi = {
615
+ on(event: string, handler: (event: unknown, ctx: unknown) => Promise<unknown>) { handlers[event] = handler; },
616
+ registerTool() {},
617
+ registerCommand() {},
618
+ getThinkingLevel: () => currentLevel,
619
+ setThinkingLevel: (level: string) => {
620
+ const prev = currentLevel;
621
+ currentLevel = clamp(level);
622
+ sets.push({ level: currentLevel });
623
+ if (currentLevel !== prev) void handlers.thinking_level_select({ level: currentLevel, previousLevel: prev }, {});
624
+ },
625
+ };
626
+ let classifyCalls = 0;
627
+ const countingRegistry: RegistryStub = {
628
+ ...registry,
629
+ classify: async (m, c, o) => { classifyCalls++; return registry.classify(m, c, o); },
630
+ };
631
+ const ctx = { cwd: "/tmp/proj", model: { id: "zai/glm-5.3" }, modelRegistry: countingRegistry };
632
+ const mod = await import("../index.js");
633
+ mod.default(fakePi as never);
634
+ return {
635
+ turn: (prompt, overrides = {}) =>
636
+ handlers.before_agent_start({ messageType: overrides.messageType ?? "user", prompt }, ctx),
637
+ settle: () => handlers.agent_settled({}, ctx),
638
+ levelSelect: (level, previousLevel) => handlers.thinking_level_select({ level, previousLevel }, {}),
639
+ calls: () => classifyCalls,
640
+ sets: () => sets,
641
+ log: () => {
642
+ try {
643
+ return readFileSync(join(dir, "classifier.log"), "utf8").trim().split("\n").filter(Boolean).map((l) => JSON.parse(l) as Record<string, unknown>);
644
+ } catch { return []; }
645
+ },
646
+ cleanup: () => {
647
+ if (prevHome === undefined) delete process.env.PI_CODING_AGENT_DIR;
648
+ else process.env.PI_CODING_AGENT_DIR = prevHome;
649
+ for (const k of Object.keys(prevEnv)) { if (prevEnv[k] === undefined) delete process.env[k]; else process.env[k] = prevEnv[k]!; }
650
+ rmSync(dir, { recursive: true, force: true });
651
+ },
652
+ };
653
+ }
654
+
655
+ const scoreAnswer = (score: number, confidence = 0.9): Partial<RegistryStub> => ({
656
+ classify: async () => ({ stopReason: "stop", answers: { effort: { type: "score", score, confidence } } }),
657
+ });
658
+
659
+ describe("think gate", () => {
660
+ it("defaults off → no classify calls, no sets", async () => {
661
+ const fx = await gateFixture(stubRegistry(scoreAnswer(4)), {});
662
+ try {
663
+ await fx.turn("redesign the routing architecture");
664
+ assert.equal(fx.calls(), 0);
665
+ assert.deepEqual(fx.sets(), []);
666
+ } finally { fx.cleanup(); }
667
+ });
668
+
669
+ it("observe mode: verdict produced + audited, no setThinkingLevel", async () => {
670
+ const fx = await gateFixture(stubRegistry(scoreAnswer(4)), { thinkGate: { observe: true } });
671
+ try {
672
+ await fx.turn("redesign the routing architecture");
673
+ assert.equal(fx.calls(), 1);
674
+ assert.deepEqual(fx.sets(), []);
675
+ const applied = fx.log().filter((l) => l.tag === "ceulen-think-gate" && l.verdict === "xhigh");
676
+ assert.ok(applied.length >= 1, "observe verdict audited");
677
+ assert.equal(applied[0]!.applied, false);
678
+ } finally { fx.cleanup(); }
679
+ });
680
+
681
+ it("enabled + confident: sets the mapped level, restores baseline at settle", async () => {
682
+ const fx = await gateFixture(stubRegistry(scoreAnswer(4)), { thinkGate: { enabled: true } });
683
+ try {
684
+ await fx.turn("redesign the routing architecture");
685
+ assert.deepEqual(fx.sets(), [{ level: "xhigh" }]);
686
+ assert.equal((fx.log().find((l) => l.applied === true) ?? {}).verdict, "xhigh");
687
+ await fx.settle();
688
+ assert.equal(fx.sets().length, 2);
689
+ const restore = fx.log().find((l) => l.restored !== undefined);
690
+ assert.equal(restore!.restored, "medium");
691
+ } finally { fx.cleanup(); }
692
+ });
693
+
694
+ it("score maps through the ladder (pi-effective levels): 0→minimal, 1→low, 2→medium, 3→high, 4→xhigh, clamped", async () => {
695
+ // "off" is not a real level on thinking models — pi clamps it forward to
696
+ // "minimal" (zai53 map) — so the assertions are pi-EFFECTIVE levels. The
697
+ // raw verdict is visible in the audit entry instead.
698
+ for (const [score, want, initial] of [[0, "minimal", "medium"], [1, "low", "medium"], [2, "medium", "low"], [3, "high", "medium"], [4, "xhigh", "medium"], [9, "xhigh", "medium"], [-3, "minimal", "medium"]] as const) {
699
+ const fx = await gateFixture(stubRegistry(scoreAnswer(score)), { thinkGate: { enabled: true } }, {}, initial);
700
+ try {
701
+ await fx.turn("task");
702
+ assert.equal(fx.sets()[0]?.level, want, `score ${score}`);
703
+ if (score === 0) assert.equal(fx.log().find((l) => l.applied === true)?.verdict, "off");
704
+ } finally { fx.cleanup(); }
705
+ }
706
+ });
707
+
708
+ it("verdict == current level → no set, audited same", async () => {
709
+ const fx = await gateFixture(stubRegistry(scoreAnswer(2)), { thinkGate: { enabled: true } }); // medium == current
710
+ try {
711
+ await fx.turn("normal multi-step task");
712
+ assert.deepEqual(fx.sets(), []);
713
+ const entry = fx.log().find((l) => l.reason === "same");
714
+ assert.ok(entry, "same audited");
715
+ } finally { fx.cleanup(); }
716
+ });
717
+
718
+ it("low confidence → fail open, no set", async () => {
719
+ const fx = await gateFixture(stubRegistry(scoreAnswer(4, 0.3)), { thinkGate: { enabled: true, threshold: 0.6 } });
720
+ try {
721
+ await fx.turn("hard task");
722
+ assert.deepEqual(fx.sets(), []);
723
+ } finally { fx.cleanup(); }
724
+ });
725
+
726
+ it("classifier throws → fail open, audited reason", async () => {
727
+ const fx = await gateFixture(stubRegistry({ classify: async () => { throw new Error("boom"); } }), { thinkGate: { enabled: true } });
728
+ try {
729
+ await fx.turn("hard task");
730
+ assert.deepEqual(fx.sets(), []);
731
+ assert.ok(fx.log().some((l) => l.applied === false && String(l.reason).includes("boom")));
732
+ } finally { fx.cleanup(); }
733
+ });
734
+
735
+ it("no classifier model → fail open, one audit line per session (not per turn)", async () => {
736
+ const fx = await gateFixture(stubRegistry({ getAvailableOfType: async () => [], classify: async () => { throw new Error("no classifier model — configure the router provider"); } }), { thinkGate: { enabled: true } });
737
+ try {
738
+ await fx.turn("task one");
739
+ await fx.turn("task two");
740
+ const misses = fx.log().filter((l) => String(l.reason ?? "").includes("no classifier model"));
741
+ assert.equal(misses.length, 1);
742
+ } finally { fx.cleanup(); }
743
+ });
744
+
745
+ it("user thinking_level_select → stands down; later turns skip classify", async () => {
746
+ const fx = await gateFixture(stubRegistry(scoreAnswer(4)), { thinkGate: { enabled: true } });
747
+ try {
748
+ await fx.levelSelect("low", "medium"); // user touched the dial
749
+ await fx.turn("hard task");
750
+ assert.equal(fx.calls(), 0);
751
+ assert.ok(fx.log().some((l) => l.stoodDown === true));
752
+ } finally { fx.cleanup(); }
753
+ });
754
+
755
+ it("our own set's level_select event does NOT stand down (ownership match)", async () => {
756
+ const fx = await gateFixture(stubRegistry(scoreAnswer(1)), { thinkGate: { enabled: true } });
757
+ try {
758
+ await fx.turn("trivial lookup"); // sets low; fake pi fired level_select(low, medium)
759
+ assert.deepEqual(fx.sets(), [{ level: "low" }]);
760
+ assert.equal(fx.log().some((l) => l.stoodDown === true), false);
761
+ await fx.settle(); // restore works
762
+ assert.equal(fx.sets().length, 2);
763
+ } finally { fx.cleanup(); }
764
+ });
765
+
766
+ it("CLAMPED set (off→minimal) still owns its event; restore does not stand down", async () => {
767
+ // Live lesson 2026-10-19: verdict "off" clamps to "minimal" on the zai53
768
+ // map — pi emits {level:"minimal", previousLevel:baseline}, which the raw
769
+ // verdict-based ownership test missed → false stand-down after one turn.
770
+ const fx = await gateFixture(stubRegistry(scoreAnswer(0)), { thinkGate: { enabled: true } });
771
+ try {
772
+ await fx.turn("trivial lookup"); // off → clamped to minimal
773
+ assert.deepEqual(fx.sets(), [{ level: "minimal" }]);
774
+ assert.equal(fx.log().some((l) => l.stoodDown === true), false);
775
+ await fx.settle(); // restore minimal→...→medium
776
+ assert.equal(fx.sets().length, 2);
777
+ assert.equal(fx.log().some((l) => l.stoodDown === true), false);
778
+ // Second turn classifies again — the gate survived its own restore.
779
+ await fx.turn("another trivial");
780
+ assert.equal(fx.calls(), 2);
781
+ } finally { fx.cleanup(); }
782
+ });
783
+
784
+ it("DOWNWARD-clamped set (xhigh→high on a capped model) restores the true baseline", async () => {
785
+ // Advisor regression case: a level-capped model clamps xhigh DOWN to
786
+ // high; ours.to must be the clamped effective level (re-read post-set),
787
+ // so settle restores the real baseline instead of falsely standing down.
788
+ const fx = await gateFixture(stubRegistry(scoreAnswer(4)), { thinkGate: { enabled: true } }, {}, "medium", "high");
789
+ try {
790
+ await fx.turn("architecture task"); // xhigh → clamped DOWN to high
791
+ assert.deepEqual(fx.sets(), [{ level: "high" }]);
792
+ assert.equal(fx.log().some((l) => l.stoodDown === true), false);
793
+ await fx.settle();
794
+ assert.equal(fx.sets().length, 2); // baseline medium restored (not a doomed set to xhigh)
795
+ assert.equal(fx.log().find((l) => l.restored !== undefined)?.restored, "medium");
796
+ assert.equal(fx.log().some((l) => l.stoodDown === true), false);
797
+ await fx.turn("next turn classifies");
798
+ assert.equal(fx.calls(), 2);
799
+ } finally { fx.cleanup(); }
800
+ });
801
+
802
+ it("custom-message turn and plan mode are skipped", async () => {
803
+ const { setPlanActive } = await import("../../../lib/plan-bridge.js");
804
+ const fx = await gateFixture(stubRegistry(scoreAnswer(4)), { thinkGate: { enabled: true } });
805
+ try {
806
+ await fx.turn("cron fired this", { messageType: "custom" });
807
+ assert.equal(fx.calls(), 0);
808
+ setPlanActive(true);
809
+ await fx.turn("still planning");
810
+ assert.equal(fx.calls(), 0);
811
+ setPlanActive(false);
812
+ await fx.turn("plan done");
813
+ assert.equal(fx.calls(), 1);
814
+ } finally { fx.cleanup(); }
815
+ });
816
+
817
+ it("CEULEN_THINK_GATE_OFF=1 → inert even when enabled", async () => {
818
+ const fx = await gateFixture(stubRegistry(scoreAnswer(4)), { thinkGate: { enabled: true } }, { CEULEN_THINK_GATE_OFF: "1" });
819
+ try {
820
+ await fx.turn("hard task");
821
+ assert.equal(fx.calls(), 0);
822
+ assert.deepEqual(fx.sets(), []);
823
+ // Fully inert: a level event at child INIT (model default re-apply) must
824
+ // not log a stoodDown (live herdr finding 2026-10-19).
825
+ await fx.levelSelect("max", "minimal");
826
+ assert.equal(fx.log().some((l) => l.stoodDown === true), false);
827
+ } finally { fx.cleanup(); }
828
+ });
829
+ });
@@ -358,7 +358,8 @@ function gaugeFill(w: number, data: BandData | undefined, theme: ShapeTheme): st
358
358
  const scale = windowStart >= 0 ? windowStart : w;
359
359
  const usedCount = Math.min(scale, Math.max(1, Math.round(((pct ?? 0) / 100) * scale)));
360
360
  const percentStart = percentLabel ? Math.min(Math.max(1, scale - percentLabel.length - 1), Math.max(1, usedCount)) : -1;
361
- // pi's compaction fires at contextWindow − reserveTokens (16384 default).
361
+ // pi's compaction STARTS at contextWindow − reserveTokens (16384 default);
362
+ // since pi 1.4.0 the summary itself uses the model's full output limit.
362
363
  const thresholdIdx =
363
364
  data?.autoCompact && w >= 8 && data.window ? Math.min(scale - 1, Math.max(0, Math.round(((data.window - 16384) / data.window) * scale))) : -1;
364
365
  let out = "";
@@ -240,6 +240,7 @@ export function runHeadless(job: CronJob, deps: HeadlessDeps): void {
240
240
  if (escalate) clearTimeout(escalate);
241
241
  try {
242
242
  mkdirSync(logsDir, { recursive: true });
243
+ // 0600: run logs carry full prompts (F12); mode applies on create.
243
244
  appendFileSync(logPath, out + (errMsg ? `\n[error] ${errMsg}\n` : ""));
244
245
  } catch {
245
246
  // log write is best-effort
@@ -87,8 +87,9 @@ export function saveJobs(dir: string, jobs: CronJob[]): void {
87
87
  // ponytail: no cross-process lock — single session per agentDir assumed;
88
88
  // concurrent sessions can lose edits/double-fire (documented in README).
89
89
  mkdirSync(dir, { recursive: true });
90
+ // 0600: jobs.json carries full prompts (F12).
90
91
  const tmp = join(dir, `.jobs.json.tmp-${process.pid}`);
91
- writeFileSync(tmp, JSON.stringify({ jobs }, null, 2) + "\n");
92
+ writeFileSync(tmp, JSON.stringify({ jobs }, null, 2) + "\n", { mode: 0o600 });
92
93
  renameSync(tmp, jobsPath(dir));
93
94
  }
94
95
 
@@ -15,7 +15,7 @@
15
15
  * same fire() closure, so pinning execute() pins both paths.
16
16
  */
17
17
  import assert from "node:assert/strict";
18
- import { mkdtempSync, readFileSync, realpathSync } from "node:fs";
18
+ import { mkdtempSync, readFileSync, realpathSync, statSync } from "node:fs";
19
19
  import { tmpdir } from "node:os";
20
20
  import { join } from "node:path";
21
21
  import { describe, it } from "node:test";
@@ -96,3 +96,12 @@ describe("cwd guard — unpinned fires must not run in a foreign-cwd session", (
96
96
  }
97
97
  });
98
98
  });
99
+
100
+ // F12 (security review 2026-10-17): the job store carries full prompts.
101
+ describe("job store file mode", () => {
102
+ it("jobs.json is created 0600", () => {
103
+ const store = mkdtempSync(join(tmpdir(), "cron-mode-"));
104
+ saveJobs(store, [{ id: "j1", name: "x", schedule: "0 9 * * *", prompt: "p", enabled: true, created: 0, nextRun: 1 } as never]);
105
+ assert.equal(statSync(join(store, "jobs.json")).mode & 0o777, 0o600, "jobs.json must be 0600");
106
+ });
107
+ });
@@ -0,0 +1,63 @@
1
+ /**
2
+ * goal's /config contribution — Tasks tab, Goal mode section 🎯.
3
+ *
4
+ * Rows write the GLOBAL agent-dir settings.json `goal` section (see
5
+ * lib/settings.ts); read per event, so a save applies without /reload.
6
+ */
7
+ import { row, toInt, type PanelGroup } from "../../lib/panel.js";
8
+ import type { ModuleConfig } from "../../lib/registry.js";
9
+ import { readGoalSettings, DEFAULT_GOAL_SETTINGS, type GoalSettings } from "./lib/settings.js";
10
+
11
+ /** Build the panel groups over a working copy (mutated by row setters). */
12
+ export function buildGoalGroups(cfg: GoalSettings): PanelGroup[] {
13
+ return [
14
+ {
15
+ key: "goal",
16
+ label: "Goal mode",
17
+ tab: "Tasks",
18
+ icon: "🎯",
19
+ rows: [
20
+ row("goal.maxTurns", "Max continuation turns", "number", cfg.maxTurns, (v) => {
21
+ const n = toInt(v, cfg.maxTurns);
22
+ if (n > 0) cfg.maxTurns = n;
23
+ }, {
24
+ description: "Hard cap on autonomous continuation turns before the loop stops itself.",
25
+ warning: "Uncapped autonomous loops burn tokens — the cap is the seatbelt.",
26
+ defaultValue: DEFAULT_GOAL_SETTINGS.maxTurns,
27
+ }),
28
+ row("goal.defaultBudget", "Default token budget", "number", cfg.defaultBudget ?? 0, (v) => {
29
+ const n = toInt(v, 0);
30
+ if (n >= 0) cfg.defaultBudget = n;
31
+ }, {
32
+ description: "Default token budget for /goal set without --budget. 0 = unbounded.",
33
+ defaultValue: DEFAULT_GOAL_SETTINGS.defaultBudget,
34
+ }),
35
+ ],
36
+ },
37
+ ];
38
+ }
39
+
40
+ const OWNED_PREFIX = "goal.";
41
+
42
+ /** goal's ModuleConfig for the central /config panel. */
43
+ export function goalConfig(): ModuleConfig {
44
+ const working: GoalSettings = readGoalSettings();
45
+ return {
46
+ groups: () => buildGoalGroups(working),
47
+ save: async (edited, ctx) => {
48
+ if (![...edited].some((k) => k.startsWith(OWNED_PREFIX))) return;
49
+ // Read-modify-write the two owned keys into the GLOBAL settings.json.
50
+ try {
51
+ const { writeGoalSection } = await import("./lib/settings.js");
52
+ const patch: Partial<GoalSettings> = {};
53
+ if (edited.has("goal.maxTurns")) patch.maxTurns = working.maxTurns;
54
+ if (edited.has("goal.defaultBudget")) patch.defaultBudget = working.defaultBudget;
55
+ if (!Object.keys(patch).length) return;
56
+ const file = writeGoalSection(patch);
57
+ ctx.ui.notify(`Goal settings saved to ${file} (applies without /reload).`);
58
+ } catch (e) {
59
+ ctx.ui.notify(`Goal save failed: ${e instanceof Error ? e.message : e}`, "error");
60
+ }
61
+ },
62
+ };
63
+ }