ceulen 0.19.0 → 0.23.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 (48) hide show
  1. package/CHANGELOG.md +131 -0
  2. package/extensions/lib/env.test.ts +45 -0
  3. package/extensions/lib/env.ts +56 -3
  4. package/extensions/lib/skill-path.test.ts +1 -1
  5. package/extensions/modules/a2a/lib/gateway.ts +3 -0
  6. package/extensions/modules/a2a/lib/persistence.ts +3 -2
  7. package/extensions/modules/a2a/test/persistence.test.ts +12 -0
  8. package/extensions/modules/classifier/index.ts +12 -1
  9. package/extensions/modules/classifier/lib/settings.ts +21 -0
  10. package/extensions/modules/classifier/lib/think-gate.ts +211 -0
  11. package/extensions/modules/classifier/test/classifier.test.ts +285 -1
  12. package/extensions/modules/config/piSettings.ts +6 -0
  13. package/extensions/modules/config/test/piSettings.test.ts +9 -0
  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/jfind/index.ts +13 -4
  18. package/extensions/modules/jfind/lib/cascade.ts +5 -2
  19. package/extensions/modules/jfind/lib/tree.ts +8 -3
  20. package/extensions/modules/jfind/test/cascade.test.ts +28 -1
  21. package/extensions/modules/munin/configPanel.ts +13 -3
  22. package/extensions/modules/munin/index.ts +7 -4
  23. package/extensions/modules/munin/test/configPanel.test.ts +9 -3
  24. package/extensions/modules/munin/test/extension.test.ts +31 -0
  25. package/extensions/modules/permission/index.ts +20 -9
  26. package/extensions/modules/permission/test/permission.test.ts +33 -1
  27. package/extensions/modules/plan/index.ts +36 -7
  28. package/extensions/modules/plan/lib/shell-gate.ts +93 -26
  29. package/extensions/modules/plan/test/module.test.ts +114 -1
  30. package/extensions/modules/plan/test/shell-gate.test.ts +64 -0
  31. package/extensions/modules/repair/lib/guards.ts +4 -1
  32. package/extensions/modules/repair/test/guards.test.ts +9 -0
  33. package/extensions/modules/router/lib/client.ts +24 -0
  34. package/extensions/modules/router/test/unit.test.ts +33 -3
  35. package/extensions/modules/sg/index.ts +3 -3
  36. package/extensions/modules/sg/lib/ops.ts +15 -1
  37. package/extensions/modules/sg/test/sg.test.ts +16 -2
  38. package/extensions/modules/subagent/index.ts +12 -1
  39. package/extensions/modules/subagent/lib/herdr.ts +37 -3
  40. package/extensions/modules/subagent/lib/history.ts +6 -2
  41. package/extensions/modules/subagent/lib/settings.ts +2 -1
  42. package/extensions/modules/subagent/test/extension.test.ts +31 -0
  43. package/extensions/modules/subagent/test/file-modes.test.ts +40 -0
  44. package/extensions/modules/subagent/test/herdr-stalled.test.ts +39 -0
  45. package/extensions/modules/web/lib/chatgpt.ts +2 -1
  46. package/extensions/scripts/probe-thinking.mjs +108 -0
  47. package/package.json +3 -3
  48. package/skills/review/SKILL.md +45 -0
@@ -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
+ });
@@ -546,6 +546,12 @@ function piRowSpecs(m: SettingsManager, lookup?: PiMenuLookup): PiRowSpec[] {
546
546
  description: "Preferred transport for providers that support multiple transports.",
547
547
  set: (v) => m.setTransport(str(v) as never),
548
548
  },
549
+ {
550
+ key: "pi.sessionShareDestination", tab: "Providers", section: "Protocol", label: "Session share destination",
551
+ kind: "string", value: m.getSessionShareDestination(), values: ["auto", "gist", "radius"], defaultValue: "auto",
552
+ description: "Where to upload sessions with /share (auto prefers Radius when authenticated, otherwise GitHub Gist).",
553
+ set: (v) => m.setSessionShareDestination(str(v) as never),
554
+ },
549
555
  {
550
556
  key: "pi.httpIdleTimeoutMs", tab: "Providers", section: "Timeouts", label: "HTTP idle timeout",
551
557
  kind: "string", value: httpTimeoutLabel(m.getHttpIdleTimeoutMs()), defaultValue: "5 min",
@@ -12,6 +12,15 @@ const rowsOf = (m: SettingsManager) => buildPiSettingsGroups(m).flatMap((g) => g
12
12
  const rowAt = (m: SettingsManager, key: string) => rowsOf(m).find((r) => r.key === key)!;
13
13
 
14
14
  describe("pi settings contribution", () => {
15
+ it("session share destination row round-trips auto/gist/radius", () => {
16
+ const m = SettingsManager.inMemory();
17
+ assert.equal(rowAt(m, "pi.sessionShareDestination").value, "auto");
18
+ for (const v of ["gist", "radius", "auto"] as const) {
19
+ rowAt(m, "pi.sessionShareDestination").set(v);
20
+ assert.equal(m.getSessionShareDestination(), v);
21
+ }
22
+ });
23
+
15
24
  it("builds OMP-taxonomy tabs with unique keys and sections", () => {
16
25
  const groups = buildPiSettingsGroups(SettingsManager.inMemory());
17
26
  const keys = groups.flatMap((g) => g.rows.map((r) => r.key));
@@ -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
+ });
@@ -3,8 +3,8 @@
3
3
  // modelRegistry.classify (System One via the router provider).
4
4
 
5
5
  import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
6
- import { existsSync, statSync } from "node:fs";
7
- import { resolve as resolvePath } from "node:path";
6
+ import { existsSync, lstatSync } from "node:fs";
7
+ import { relative as relPath, resolve as resolvePath } from "node:path";
8
8
  import { Type } from "typebox";
9
9
  import { formatBytes } from "./lib/format.js";
10
10
  import { runCascade, FIND_TIMEOUT_MS, type CascadeResult } from "./lib/cascade.js";
@@ -46,8 +46,17 @@ export default function jfindModule(pi: ExtensionAPI): void {
46
46
  let root = resolvePath(cwd);
47
47
  if (scopeInput.length > 0) {
48
48
  root = resolvePath(cwd, scopeInput);
49
+ // F8: the scope is a content boundary — file contents ship to the
50
+ // third-party classifier, so the root must stay inside the workspace
51
+ // (the fff contract). resolvePath against cwd first, so absolute
52
+ // paths inside cwd still work; escapes and out-of-tree absolutes throw.
53
+ const rel = relPath(cwd, root);
54
+ if (rel.startsWith("..") || rel === "" || (root.length > cwd.length && !root.startsWith(cwd + "/") && !root.startsWith(cwd + "\\"))) {
55
+ throw new Error(`Path must be inside the workspace: ${scopeInput}`);
56
+ }
49
57
  if (!existsSync(root)) throw new Error(`Path not found: ${scopeInput}`);
50
- if (!statSync(root).isFile() && !statSync(root).isDirectory()) {
58
+ const st = lstatSync(root);
59
+ if (st.isSymbolicLink() || (!st.isFile() && !st.isDirectory())) {
51
60
  throw new Error(`Path is neither a file nor a directory: ${scopeInput}`);
52
61
  }
53
62
  }
@@ -81,7 +90,7 @@ export default function jfindModule(pi: ExtensionAPI): void {
81
90
  }
82
91
  // A single-file scope that lists zero eligible files used to fall through
83
92
  // to a silent "no hits" — surface the eligibility refusal instead.
84
- if (result.stats.listed === 0 && scopeInput.length > 0 && statSync(root).isFile()) {
93
+ if (result.stats.listed === 0 && scopeInput.length > 0 && lstatSync(root).isFile()) {
85
94
  return {
86
95
  content: [{ type: "text", text: `not searchable: ${scopeInput} (deny-listed, binary, secret, or empty by jfind's eligibility rules)` }],
87
96
  details: { query },
@@ -6,7 +6,7 @@
6
6
  // budgets, and constants.
7
7
 
8
8
  import { basename } from "node:path";
9
- import { statSync } from "node:fs";
9
+ import { lstatSync } from "node:fs";
10
10
  import {
11
11
  fileScore,
12
12
  grepIndex,
@@ -375,7 +375,10 @@ class Cascade {
375
375
  * scope used to list zero files and report "no hits" silently. Wrap it as a
376
376
  * one-entry walk so the documented scope works. Exported for tests. */
377
377
  export function scopeFiles(root: string): FileEntry[] {
378
- const st = statSync(root);
378
+ // lstat + regular-file check (F8): a single-file scope must not be a
379
+ // symlink (its target could ship out-of-tree contents to the classifier).
380
+ const st = lstatSync(root);
381
+ if (st.isSymbolicLink()) return [];
379
382
  if (!st.isDirectory()) {
380
383
  const rel = basename(root);
381
384
  return eligibleFile(rel, st.size, rel.startsWith(".")) ? [{ path: root, rel, size: st.size }] : [];
@@ -5,7 +5,7 @@
5
5
 
6
6
  import { lines, clipBytes, countOccurrences } from "./lexical.js";
7
7
  import { execFileSync } from "node:child_process";
8
- import { closeSync, openSync, readdirSync, readSync, statSync } from "node:fs";
8
+ import { closeSync, lstatSync, openSync, readdirSync, readSync, statSync } from "node:fs";
9
9
  import { join } from "node:path";
10
10
 
11
11
  // ── eligibility deny-lists (tree.ts, verbatim) ──────────────────────────────
@@ -155,7 +155,12 @@ export function listFiles(rootAbs: string, includeHidden = false): FileEntry[] {
155
155
  const abs = join(rootAbs, rel);
156
156
  let size = 0;
157
157
  try {
158
- size = statSync(abs).size;
158
+ // lstat: a symlink's TARGET size/status must not leak out-of-tree
159
+ // file metadata (F8) — git never tracks symlinks as regular files
160
+ // here anyway, so skipping keeps the walk in-tree.
161
+ const st = lstatSync(abs);
162
+ if (st.isSymbolicLink()) continue;
163
+ size = st.size;
159
164
  } catch {
160
165
  continue;
161
166
  }
@@ -180,7 +185,7 @@ export function listFiles(rootAbs: string, includeHidden = false): FileEntry[] {
180
185
  const rel = relPrefix ? `${relPrefix}/${name}` : name;
181
186
  let st;
182
187
  try {
183
- st = statSync(abs);
188
+ st = lstatSync(abs); // F8: never follow symlinks out of the root
184
189
  } catch {
185
190
  continue;
186
191
  }
@@ -2,7 +2,7 @@
2
2
  // network; the classifier is injected through the Judge seam.
3
3
 
4
4
  import assert from "node:assert/strict";
5
- import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
5
+ import { mkdirSync, mkdtempSync, rmSync, symlinkSync, writeFileSync } from "node:fs";
6
6
  import { tmpdir } from "node:os";
7
7
  import path from "node:path";
8
8
  import { after, before, describe, it } from "node:test";
@@ -358,3 +358,30 @@ describe("cascade", () => {
358
358
  assert.ok(Buffer.byteLength(sliced.text) <= 1024 + 8, "slice ends on a line boundary");
359
359
  });
360
360
  });
361
+
362
+ // ── F8 (security review 2026-10-17): symlinks never escape the root ──────
363
+
364
+ describe("F8 symlink + scope containment", () => {
365
+ it("listFiles skips symlinks pointing outside the root", () => {
366
+ const outDir = mkdtempSync(path.join(tmpdir(), "ceulen-jfind-out-"));
367
+ const secret = path.join(outDir, "secret.txt");
368
+ writeFileSync(secret, "top secret");
369
+ const root = mkdtempSync(path.join(tmpdir(), "ceulen-jfind-root-"));
370
+ writeFileSync(path.join(root, "real.txt"), "hello");
371
+ try {
372
+ symlinkSync(secret, path.join(root, "leak.txt"));
373
+ } catch {
374
+ return; // filesystem without symlink support
375
+ }
376
+ try {
377
+ const listed = listFiles(root);
378
+ assert.ok(listed.some((e) => e.rel === "real.txt"), "real file listed");
379
+ assert.ok(!listed.some((e) => e.rel === "leak.txt"), "symlink excluded from the walk");
380
+ // single-file symlink scope yields nothing
381
+ assert.deepEqual(scopeFiles(path.join(root, "leak.txt")), [], "symlink file scope refused");
382
+ } finally {
383
+ rmSync(root, { recursive: true, force: true });
384
+ rmSync(outDir, { recursive: true, force: true });
385
+ }
386
+ });
387
+ });
@@ -14,6 +14,7 @@ import {
14
14
  projectSettingsPath,
15
15
  writeMuninSection,
16
16
  } from "./lib/helpers.js";
17
+ import { writeSecretEnvs } from "../../lib/env.js";
17
18
 
18
19
  export interface MuninSettings {
19
20
  project: string;
@@ -63,7 +64,7 @@ export function buildMuninGroups(cfg: MuninSettings): PanelGroup[] {
63
64
  }, {
64
65
  mask: true,
65
66
  description: "Bearer credential for the Munin server. MUNIN_API_KEY env / .env overrides it.",
66
- warning: "Stored in this repo's .pi/settings.json — add it to .gitignore.",
67
+ warning: "Secrets never land in settings.json — the save writes <agentDir>/.env.local (0600), which already wins at read time.",
67
68
  }),
68
69
  ],
69
70
  },
@@ -87,15 +88,24 @@ export function muninConfig(): ModuleConfig {
87
88
  if (![...edited].some((k) => k.startsWith(OWNED_PREFIX))) return;
88
89
  const trusted = ctx.isProjectTrusted?.() === true;
89
90
  const target = projectSettingsPath(ctx.cwd);
91
+ // F7: the API key is a secret — it persists to <agentDir>/.env.local
92
+ // (0600, mirrored into process.env so the live session resolves it at
93
+ // once) and NEVER into the git-trackable project settings.json.
94
+ let apiKeyNote = "";
95
+ if (working.apiKey !== before.apiKey) {
96
+ writeSecretEnvs({ MUNIN_API_KEY: working.apiKey });
97
+ apiKeyNote = working.apiKey
98
+ ? " API key saved to your agent dir's .env.local."
99
+ : " API key cleared from .env.local settings tracking (set MUNIN_API_KEY env to silence a stored key).";
100
+ }
90
101
  writeMuninSection(
91
102
  {
92
103
  project: working.project !== before.project ? working.project : undefined,
93
104
  baseUrl: working.baseUrl !== before.baseUrl ? working.baseUrl : undefined,
94
- apiKey: working.apiKey !== before.apiKey ? working.apiKey : undefined,
95
105
  },
96
106
  target,
97
107
  );
98
- const notes: string[] = [`Munin config saved to ${target}.`];
108
+ const notes: string[] = [`Munin config saved to ${target}.${apiKeyNote}`];
99
109
  if (!trusted) {
100
110
  notes.push("This project is NOT trusted — pi ignores .pi/settings.json until you trust this repo.");
101
111
  }
@@ -356,10 +356,12 @@ function makeTools(dampenCheck: (name: string, params: Record<string, unknown>)
356
356
  ),
357
357
  }),
358
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 } };
361
359
  const { query, topK = 10, tags, tag_mode, since, before, include_total } = params as Record<string, any>;
362
360
  validateSearchQuery(query);
361
+ // F14: validation BEFORE the dampener - an invalid call must return
362
+ // its validation error, never loop guidance.
363
+ const dampened = dampenCheck("munin_search", params as Record<string, unknown>);
364
+ if (dampened) return { content: [{ type: "text" as const, text: dampened.text }], details: { dampened: true, ...dampened } };
363
365
  const tagMode = validateTagMode(tag_mode);
364
366
  const result = await withMuninClient(params as Record<string, unknown>, async (client, projectId) => {
365
367
  const searchParams: Record<string, unknown> = { query, topK };
@@ -390,10 +392,11 @@ function makeTools(dampenCheck: (name: string, params: Record<string, unknown>)
390
392
  key: Type.String({ description: "Key to retrieve." }),
391
393
  }),
392
394
  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 } };
395
395
  const { key: rawKey } = params as Record<string, any>;
396
396
  const key = validateMemoryKey(rawKey);
397
+ // F14: validation BEFORE the dampener (see munin_search).
398
+ const dampened = dampenCheck("munin_get", params as Record<string, unknown>);
399
+ if (dampened) return { content: [{ type: "text" as const, text: dampened.text }], details: { dampened: true, ...dampened } };
397
400
  const result = await withMuninClient(params as Record<string, unknown>, async (client, projectId) => {
398
401
  return callMunin(client, projectId, "get", { key });
399
402
  }, ctx);
@@ -21,7 +21,7 @@ describe("buildMuninGroups", () => {
21
21
  assert.deepEqual(groups[0]!.rows.map((r) => r.key), ["munin.project", "munin.baseUrl", "munin.apiKey"]);
22
22
  const keyRow = groups[0]!.rows[2]!;
23
23
  assert.equal(keyRow.mask, true);
24
- assert.match(keyRow.warning ?? "", /\.gitignore/);
24
+ assert.match(keyRow.warning ?? "", /\.env\.local/, "F7: the warning names the secret store");
25
25
  assert.equal(groups[0]!.rows[1]!.defaultValue, "https://munin.kalera.ai");
26
26
  });
27
27
 
@@ -104,6 +104,10 @@ describe("muninConfig save", () => {
104
104
  dirs = [];
105
105
  originalEnv = Object.fromEntries(ENV_KEYS.map((key) => [key, process.env[key]]));
106
106
  for (const key of ENV_KEYS) delete process.env[key];
107
+ // F7: the apiKey save writes <agentDir>/.env.local — point it at a
108
+ // throwaway dir so the test never touches the real one.
109
+ dirs.push(mkdtempSync(join(tmpdir(), "munin-agent-")));
110
+ process.env.PI_CODING_AGENT_DIR = dirs[dirs.length - 1];
107
111
  cwd = mkdtempSync(join(tmpdir(), "munin-save-"));
108
112
  dirs.push(cwd);
109
113
  });
@@ -131,7 +135,7 @@ describe("muninConfig save", () => {
131
135
  assert.equal(readFileSyncSafe(projectSettingsPath(cwd)), null);
132
136
  });
133
137
 
134
- it("writes changed fields to the project file; untrusted save warns", async () => {
138
+ it("writes changed fields to the project file; the API key diverts to .env.local (F7)", async () => {
135
139
  const notes: { message: string; level?: string }[] = [];
136
140
  const contrib = muninConfig();
137
141
  // Simulate the panel edit: mutate the working copy the rows close over.
@@ -144,8 +148,10 @@ describe("muninConfig save", () => {
144
148
  const json = JSON.parse(readFileSync(projectSettingsPath(cwd), "utf8"));
145
149
  assert.equal(json.munin.project, "saved-project");
146
150
  assert.equal(json.munin.baseUrl, "https://saved.example.test");
147
- assert.equal(json.munin.apiKey, "saved-key");
151
+ assert.equal(json.munin.apiKey, undefined, "F7: the key never lands in settings.json");
152
+ assert.equal(process.env.MUNIN_API_KEY, "saved-key", "F7: key mirrored into env (live session resolves it)");
148
153
  const note = notes[0]!;
154
+ assert.match(note.message, /\.env\.local/);
149
155
  assert.match(note.message, /saved to .*\.pi\/settings\.json/);
150
156
  assert.match(note.message, /NOT trusted/);
151
157
  assert.equal(note.level, "warning");