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
@@ -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");
@@ -346,3 +346,34 @@ describe("loop dampener", () => {
346
346
  assert.equal(calls.length, 3);
347
347
  });
348
348
  });
349
+
350
+ // F14 (security review 2026-10-17): validation runs BEFORE the dampener —
351
+ // invalid calls return their validation error every time, never loop guidance.
352
+ describe("validation before dampener (F14)", () => {
353
+ beforeEach(() => {
354
+ process.env.MUNIN_API_KEY = "key";
355
+ process.env.MUNIN_PROJECT = "project";
356
+ });
357
+
358
+ afterEach(() => {
359
+ delete process.env.MUNIN_API_KEY;
360
+ delete process.env.MUNIN_PROJECT;
361
+ delete (MuninClient.prototype as { invoke?: unknown }).invoke;
362
+ });
363
+
364
+ it("4 invalid munin_get calls all reject with the validation error", async () => {
365
+ const { tools, ctx } = harness();
366
+ const calls: string[] = [];
367
+ MuninClient.prototype.invoke = async function () { calls.push("invoke"); return { ok: true }; } as typeof MuninClient.prototype.invoke;
368
+ for (let i = 0; i < 4; i++) {
369
+ let msg = "";
370
+ try {
371
+ await tools.munin_get.execute("id", { key: "" }, undefined, undefined, ctx);
372
+ } catch (e) {
373
+ msg = (e as Error).message;
374
+ }
375
+ assert.match(msg, /key/i, "validation error, not loop guidance");
376
+ }
377
+ assert.equal(calls.length, 0);
378
+ });
379
+ });
@@ -139,13 +139,22 @@ export function readSettingsKey(cwd: string | undefined, key: string, { project
139
139
  * separately).
140
140
  */
141
141
  function toolSubject(toolName: string, input: Record<string, unknown> | undefined): string {
142
- if (toolName === "bash") return String(input?.command || "");
142
+ // F4: a shell start IS a bash command — its rules/promotions key on the
143
+ // command text exactly like bash (output/stdin/kill actions carry no new
144
+ // command and stay subject-less).
145
+ if (toolName === "bash" || (toolName === "shell" && input?.action === "start")) return String(input?.command || "");
143
146
  if (["grep", "find", "ls", "read", "write", "edit"].includes(toolName)) {
144
147
  return String(input?.path || "");
145
148
  }
146
149
  return "";
147
150
  }
148
151
 
152
+ /** Rule/promotion lookup key. shell start resolves under `bash` (a shell
153
+ * start is a bash command — permission.bash rules must see it, F4). */
154
+ function ruleKey(toolName: string, input: Record<string, unknown> | undefined): string {
155
+ return toolName === "shell" && input?.action === "start" ? "bash" : toolName;
156
+ }
157
+
149
158
  /**
150
159
  * Normalized match subjects for path tools. Rules are matched against the
151
160
  * traversal-normalized relative form AND the absolute form — never the raw
@@ -235,7 +244,7 @@ function describe(toolName: string, input: Record<string, unknown> | undefined):
235
244
  const c = String(s).replace(/[\x00-\x1f\x7f]/g, " ").replace(/\s+/g, " ").trim();
236
245
  return c.length > 120 ? c.slice(0, 120) + "…" : c;
237
246
  };
238
- if (toolName === "bash") return `\`bash\`: ${clip(input?.command || "")}`;
247
+ if (toolName === "bash" || (toolName === "shell" && input?.action === "start")) return `\`${toolName}\`: ${clip(input?.command || "")}`;
239
248
  if (input?.path) return `\`${toolName}\`: ${clip(input.path)}`;
240
249
  return `\`${toolName}\``;
241
250
  }
@@ -314,9 +323,10 @@ export function persistAllowlistRule(
314
323
  toolRules[String(subject)] = "allow";
315
324
  perm[toolName] = toolRules;
316
325
  parsed.permission = perm;
317
- // Atomic write: temp file + rename so a crash can't truncate settings.json.
326
+ // Atomic 0600 write: settings.json may hold a2a gateway tokens, so the
327
+ // tmp file must not downgrade the file to 0644 (F5) — mode applies on create.
318
328
  const tmp = `${file}.tmp-${process.pid}`;
319
- writeFileSync(tmp, JSON.stringify(parsed, null, 2) + "\n");
329
+ writeFileSync(tmp, JSON.stringify(parsed, null, 2) + "\n", { mode: 0o600 });
320
330
  renameSync(tmp, file);
321
331
  return { file };
322
332
  } catch (e) {
@@ -428,8 +438,9 @@ export default function permissionModule(pi: ExtensionAPI): void {
428
438
  let matchedRule = "(default)";
429
439
 
430
440
  // 1. tool-specific rules (expand ~ for path patterns so rules can reference $HOME)
431
- if (rules[toolName] !== undefined) {
432
- const toolRules = rules[toolName];
441
+ const ruleSection = ruleKey(toolName, inp);
442
+ if (rules[ruleSection] !== undefined) {
443
+ const toolRules = rules[ruleSection];
433
444
  if (typeof toolRules === "string") {
434
445
  action = toolRules;
435
446
  matchedRule = toolName + " (whole)";
@@ -468,7 +479,7 @@ export default function permissionModule(pi: ExtensionAPI): void {
468
479
  const sessionSubject = PATH_TOOLS.has(toolName)
469
480
  ? normalizedSubjects(String(inp?.path || ""), ctx.cwd, home, (ctx as PathCtx).ppath).rel
470
481
  : toolSubject(toolName, inp);
471
- if (sessionAllowed(toolName, sessionSubject)) return undefined;
482
+ if (sessionAllowed(ruleSection, sessionSubject)) return undefined;
472
483
 
473
484
  // ── "ask" ───────────────────────────────────────────────────────
474
485
  if (yolo || auto) return undefined; // auto-approve (--yolo or --auto)
@@ -489,7 +500,7 @@ export default function permissionModule(pi: ExtensionAPI): void {
489
500
  options,
490
501
  );
491
502
  if (choice === "Allow for this session") {
492
- promoteToSessionAllow(toolName, subject);
503
+ promoteToSessionAllow(ruleSection, subject);
493
504
  return undefined;
494
505
  }
495
506
  if (choice === "Add to permanent allowlist") {
@@ -507,7 +518,7 @@ export default function permissionModule(pi: ExtensionAPI): void {
507
518
  if (written.error) {
508
519
  return { block: true, reason: `could not persist allowlist rule: ${written.error}` };
509
520
  }
510
- promoteToSessionAllow(toolName, subject); // cover the rest of this session too
521
+ promoteToSessionAllow(ruleSection, subject); // cover the rest of this session too
511
522
  try {
512
523
  ctx.ui.notify(`Permission rule added to ${written.file}: ${describe(toolName, inp)} → allow`, "info");
513
524
  } catch { /* best-effort */ }
@@ -3,7 +3,7 @@
3
3
  // delta tests: plan-mode deferral via the shared plan-bridge flag.
4
4
  import assert from "node:assert/strict";
5
5
  import test from "node:test";
6
- import { mkdtempSync, mkdirSync, writeFileSync, rmSync, readFileSync, existsSync } from "node:fs";
6
+ import { mkdtempSync, mkdirSync, writeFileSync, rmSync, readFileSync, existsSync, statSync } from "node:fs";
7
7
  import { join, win32 } from "node:path";
8
8
  import { tmpdir } from "node:os";
9
9
 
@@ -787,3 +787,35 @@ test("plan-bridge flag round-trips", () => {
787
787
  setPlanActive(prev);
788
788
  }
789
789
  });
790
+
791
+
792
+ // F5 (security review 2026-10-17): settings.json may hold a2a tokens - the
793
+ // atomic-write tmp file must not downgrade the mode to 0644.
794
+ test("allowlist persist keeps settings.json at 0600", () => {
795
+ const cwd = mkdtempSync(join(tmpdir(), "perm-mode-"));
796
+ mkdirSync(join(cwd, ".pi"), { recursive: true });
797
+ const file = join(cwd, ".pi", "settings.json");
798
+ writeFileSync(file, JSON.stringify({ permission: { bash: { "*": "ask" } } }), { mode: 0o600 });
799
+ const written = persistAllowlistRule("bash", "npm run build", { cwd });
800
+ assert.equal(written.error, undefined);
801
+ assert.equal(statSync(file).mode & 0o777, 0o600, "mode must survive the rewrite");
802
+ });
803
+
804
+ // F4 (security review 2026-10-17): a shell START spawns shell:true with a
805
+ // command - it must be visible to bash rules exactly like the bash tool.
806
+ test("shell action:start keys on permission.bash rules; deny blocks, ask shows the command", async () => {
807
+ const pi = harness({ rules: { bash: { "*": "ask", "rm *": "deny" } } });
808
+ const denied = (await pi.handler({ toolName: "shell", input: { action: "start", command: "rm -rf /tmp/perm-shell" } }, ctx())) as { block?: boolean; reason?: string };
809
+ assert.equal(denied.block, true, "shell start must honor bash deny rules");
810
+ assert.match(denied.reason ?? "", /denied by permission rule/);
811
+ // ask via bash rules - the dialog shows the actual command text
812
+ const titles: string[] = [];
813
+ const c = ctx({ selectChoice: "Deny" });
814
+ c.ui.select = async (t: string) => { titles.push(t); return "Deny"; };
815
+ const asked = (await pi.handler({ toolName: "shell", input: { action: "start", command: "git status" } }, c)) as { block?: boolean };
816
+ assert.equal(asked.block, true, "user picked Deny");
817
+ assert.match(titles[0] ?? "", /git status/, "approval dialog must show the command");
818
+ // non-start actions stay invisible to bash rules (no command to key on)
819
+ const other = await pi.handler({ toolName: "shell", input: { action: "output", shellId: "s1" } }, ctx());
820
+ assert.equal(other, undefined, "shell output/kill carry no command -> no opinion");
821
+ });
@@ -65,6 +65,13 @@ export const PLAN_ENTRY_TYPE = "ceulen-plan";
65
65
  export const PLAN_TOOL = "write_plan";
66
66
  export const ASK_USER_QUESTION_TOOL = "ask_user_question";
67
67
 
68
+ /** session_start arms the diff-driver probe; the bash tool_call branch awaits
69
+ * it (a settled promise awaits free) before classifying. F13: the old bare
70
+ * `void probeDiffDrivers(...)` raced — an early `git log -p` classified read
71
+ * before the probe resolved in a textconv-configured repo. The probe swallows
72
+ * its own failures, so awaiting it can never reject. */
73
+ let diffDriverProbe: Promise<void> | undefined;
74
+
68
75
  // ── planGate (classifier.planGate) ──────────────────────────────────────────
69
76
  // The classifier can move a CONFIRM-tier bash command to auto-run when Jev
70
77
  // says it clearly doesn't mutate and serves the task. It can never do the
@@ -148,6 +155,10 @@ async function planGateAutoRun(command: string, ctx: ExtensionContext): Promise<
148
155
  // segments: the pipe-to-shell regexes need the unsplit command, while
149
156
  // segments expose risky commands hidden after && / ;.
150
157
  if (isRisky(command) || segments(command).some(isRisky)) return undefined;
158
+ // Quote-splitting beats the pipe regexes (`curl … | 'b''a''s''h'`): the
159
+ // de-quoted copy re-runs the same static check (F11).
160
+ const dequoted = command.replace(/['"\\]/g, "");
161
+ if (dequoted !== command && (isRisky(dequoted) || segments(dequoted).some(isRisky))) return undefined;
151
162
  const verdict = await planGateVerdict(command, ctx);
152
163
  if (verdict?.safe && planGate.enabled) {
153
164
  if (ctx.hasUI) {
@@ -729,10 +740,13 @@ export default function planModule(pi: ExtensionAPI): void {
729
740
  return undefined; // Allow once
730
741
  }
731
742
 
732
- /** True when every named subagent resolves to a read-only sandbox. */
733
- function subagentsReadOnly(names: string[], cwd: string): boolean {
743
+ /** True when every named subagent resolves to a read-only sandbox, resolved
744
+ * at the scope the subagent tool will ACTUALLY run (F3: plan's "both"
745
+ * lookup must not shadow a name with a project agent whose bundled
746
+ * namesake is read-only while the tool runs the full-write bundled one). */
747
+ function subagentsReadOnly(names: string[], cwd: string, scope: "user" | "project" | "both"): boolean {
734
748
  try {
735
- const { agents } = discoverAgents(cwd, "both", path.resolve(import.meta.dirname, "../subagent/agents"));
749
+ const { agents } = discoverAgents(cwd, scope, path.resolve(import.meta.dirname, "../subagent/agents"));
736
750
  return names.length > 0 && names.every((name) => agents.find((a) => a.name === name)?.sandbox === "read-only");
737
751
  } catch {
738
752
  return false; // fail closed → confirm tier
@@ -933,7 +947,8 @@ export default function planModule(pi: ExtensionAPI): void {
933
947
  asksSinceToolCall = 0;
934
948
  refreshSettings(ctx);
935
949
  setPlanRegistry(ctx.modelRegistry);
936
- void probeDiffDrivers(ctx.cwd); // best-effort: textconv-aware bash gating
950
+ void (diffDriverProbe = probeDiffDrivers(ctx.cwd)); // F13: bash branch awaits this before classifying
951
+ diffDriverProbe = probeDiffDrivers(ctx.cwd);
937
952
  restoreStateFromBranch(ctx);
938
953
 
939
954
  // The plan tools must always be visible (unless per-tool kill-switched).
@@ -956,6 +971,10 @@ export default function planModule(pi: ExtensionAPI): void {
956
971
  const preThinking = prePlanThinking;
957
972
  restoreStateFromBranch(ctx);
958
973
  sessionAllows.clear();
974
+ // F15: branch restore swaps the conversation — the ask-loop dampener's
975
+ // memory of answered questions belongs to the OLD branch.
976
+ answeredAsks = [];
977
+ asksSinceToolCall = 0;
959
978
  if (planModeEnabled) {
960
979
  toolsBeforePlan ??= previousToolsBeforePlan ?? pi.getActiveTools();
961
980
  enablePlanTools();
@@ -995,6 +1014,7 @@ export default function planModule(pi: ExtensionAPI): void {
995
1014
 
996
1015
  if (isToolCallEventType("bash", event)) {
997
1016
  const command = String(event.input.command || "");
1017
+ await diffDriverProbe; // F13: classification must see the probe's verdict
998
1018
  const disposition = classifyCommand(command);
999
1019
  if (disposition === "read") return;
1000
1020
  if (disposition === "write") {
@@ -1010,7 +1030,12 @@ export default function planModule(pi: ExtensionAPI): void {
1010
1030
  if (!ctx.hasUI) return { block: true, reason: `plan mode: this command requires confirmation but UI is not available.\nCommand: ${command}` };
1011
1031
  const firstToken = command.trim().split(/\s+/)[0] || "bash";
1012
1032
  const allowKey = INTERPRETER_TOKENS.has(firstToken) ? `bash-cmd:${command.trim()}` : `bash:${firstToken}`;
1013
- if (sessionAllows.has(allowKey)) return;
1033
+ // F2: a session allow is a first-token grant ("npm test"), not a blank
1034
+ // cheque — RISKY-listed commands always re-prompt even under a grant.
1035
+ const dequotedAllow = command.replace(/['"\\]/g, "");
1036
+ const riskyNow = isRisky(command) || segments(command).some(isRisky)
1037
+ || (dequotedAllow !== command && (isRisky(dequotedAllow) || segments(dequotedAllow).some(isRisky)));
1038
+ if (sessionAllows.has(allowKey) && !riskyNow) return;
1014
1039
  const rememberNote = INTERPRETER_TOKENS.has(firstToken)
1015
1040
  ? '"Allow for this session" remembers only this exact command until plan mode toggles.'
1016
1041
  : `"Allow for this session" remembers \`${clip(firstToken)}\` commands until plan mode toggles.`;
@@ -1027,8 +1052,12 @@ export default function planModule(pi: ExtensionAPI): void {
1027
1052
  // Subagent delegation is auto-allowed only when every named agent is read-only.
1028
1053
  if (event.toolName === "subagent") {
1029
1054
  const names = extractSubagentNames(event.input);
1030
- // .pi/agents (project) + ~/.pi/agent/agents (user): the approval scope is "both".
1031
- if (names.length > 0 && subagentsReadOnly(names, ctx.cwd)) return;
1055
+ // F3: resolve at the scope the subagent tool will actually run — plan's
1056
+ // "both" lookup must not shadow a name with a read-only project agent
1057
+ // whose bundled namesake executes full-write.
1058
+ const inputScope = (event.input as { agentScope?: unknown } | undefined)?.agentScope;
1059
+ const scope = inputScope === "project" || inputScope === "both" ? inputScope : "user";
1060
+ if (names.length > 0 && subagentsReadOnly(names, ctx.cwd, scope)) return;
1032
1061
  }
1033
1062
 
1034
1063
  if (!READ_ONLY_TOOLS.has(event.toolName)) {
@@ -21,6 +21,66 @@ import { execFile } from "node:child_process";
21
21
 
22
22
  export type CommandDisposition = "read" | "write" | "confirm";
23
23
 
24
+ /** Bash-faithful close test for the quote char at index `i` (quote is open).
25
+ * Single quotes close on ANY `'` — backslash is a literal character inside
26
+ * them. A double quote closes only when the run of backslashes immediately
27
+ * before it is EVEN: `"a\\"` is literal-backslash + close, `"a\"` is an
28
+ * escaped quote and stays open. The single-char `cmd[i-1] !== "\\"` peek
29
+ * this replaces got both rules wrong (phantom-quote exploit class). */
30
+ function quoteCloses(cmd: string, i: number, quote: "'" | '"'): boolean {
31
+ if (quote === "'") return true;
32
+ let backslashes = 0;
33
+ for (let k = i - 1; k >= 0 && cmd[k] === "\\"; k--) backslashes++;
34
+ return backslashes % 2 === 0;
35
+ }
36
+
37
+ /** Read one substitution (`$(…)`, backtick, `<(…)`, `>(…)`) starting at
38
+ * `start` (the opener's first char). Walks to the matching close: paren
39
+ * depth for the paren forms, escape- and quote-aware inside (single quotes
40
+ * close on any `'`, double quotes on an even backslash run). Unclosed spans
41
+ * read to end. `next` = index of the first char AFTER the close. */
42
+ function readSubstitution(cmd: string, start: number): { inner: string; next: number } {
43
+ const opener = cmd[start] === "`"
44
+ ? "`"
45
+ : cmd[start] === "$" && cmd[start + 1] === "("
46
+ ? "$("
47
+ : `${cmd[start]}(`; // `<(` or `>(`
48
+ let depth = 1;
49
+ let innerQuote: "'" | '"' | null = null;
50
+ let inner = "";
51
+ let j = start + opener.length;
52
+ for (; j < cmd.length && depth > 0; j++) {
53
+ const c = cmd[j];
54
+ if (innerQuote) {
55
+ inner += c;
56
+ if (c === innerQuote && quoteCloses(cmd, j, innerQuote)) innerQuote = null;
57
+ continue;
58
+ }
59
+ if (c === "\\") {
60
+ inner += c;
61
+ if (j + 1 < cmd.length) { inner += cmd[j + 1]; j++; }
62
+ continue;
63
+ }
64
+ if (c === "'" || c === '"') { innerQuote = c; inner += c; continue; }
65
+ if (opener === "`") {
66
+ if (c === "`") depth = 0;
67
+ } else if (c === "(") depth++;
68
+ else if (c === ")") depth--;
69
+ inner += depth > 0 ? c : "";
70
+ }
71
+ return { inner, next: j };
72
+ }
73
+
74
+ /** Substitution openers that EXECUTE — outside quotes: `$(`, backtick,
75
+ * `<(`, `>(`. */
76
+ function substitutionOpener(cmd: string, i: number): string | null {
77
+ const ch = cmd[i];
78
+ if (ch === "`") return "`";
79
+ if (ch === "$" && cmd[i + 1] === "(") return "$(";
80
+ if ((ch === "<" || ch === ">") && cmd[i + 1] === "(") return `${ch}(`;
81
+ return null;
82
+ }
83
+
24
84
  /** Split a shell command on separators (; & | and raw line breaks) that are OUTSIDE quotes. */
25
85
  export function splitShellSegments(cmd: string): string[] {
26
86
  const segments: string[] = [];
@@ -30,7 +90,13 @@ export function splitShellSegments(cmd: string): string[] {
30
90
  const ch = cmd[i];
31
91
  if (quote) {
32
92
  cur += ch;
33
- if (ch === quote) quote = null;
93
+ if (ch === quote && quoteCloses(cmd, i, quote)) quote = null;
94
+ } else if (ch === "\\") {
95
+ // Outside quotes a backslash escapes the NEXT character (`\'`, `\"`,
96
+ // `\;` are literal two-char sequences — no quote opens, nothing
97
+ // separates). Escaped-quote phantom-quote exploit class, fixed.
98
+ cur += ch;
99
+ if (i + 1 < cmd.length) { cur += cmd[i + 1]; i++; }
34
100
  } else if (ch === "'" || ch === '"') {
35
101
  quote = ch;
36
102
  cur += ch;
@@ -123,14 +189,17 @@ function quotedSpans(cmd: string): string[] {
123
189
  const spans: string[] = [];
124
190
  let quote: "'" | '"' | null = null;
125
191
  let cur = "";
126
- for (const ch of cmd) {
192
+ for (let i = 0; i < cmd.length; i++) {
193
+ const ch = cmd[i];
127
194
  if (quote) {
128
195
  cur += ch;
129
- if (ch === quote) {
196
+ if (ch === quote && quoteCloses(cmd, i, quote)) {
130
197
  spans.push(cur);
131
198
  cur = "";
132
199
  quote = null;
133
200
  }
201
+ } else if (ch === "\\") {
202
+ i++; // escaped char outside quotes — never a quote opener
134
203
  } else if (ch === "'" || ch === '"') {
135
204
  quote = ch;
136
205
  }
@@ -242,35 +311,28 @@ function findExecutingSubstitutions(cmd: string): string[] {
242
311
  for (let i = 0; i < cmd.length; i++) {
243
312
  const ch = cmd[i];
244
313
  if (quote) {
245
- if (ch === quote && cmd[i - 1] !== "\\") quote = null;
314
+ if (ch === quote && quoteCloses(cmd, i, quote)) { quote = null; continue; }
315
+ // Single quotes are literal — nothing executes inside them. Inside
316
+ // DOUBLE quotes `$()` and backticks STILL EXECUTE (bash), so keep
317
+ // scanning for live openers there (`echo "$(rm -rf x)"` runs the rm).
318
+ if (quote === "'") continue;
319
+ const dqOpener = ch === "`" ? "`" : ch === "$" && cmd[i + 1] === "(" ? "$(" : null;
320
+ if (!dqOpener) continue;
321
+ const r = readSubstitution(cmd, i);
322
+ inners.push(r.inner);
323
+ i = r.next - 1;
246
324
  continue;
247
325
  }
326
+ if (ch === "\\") { i++; continue; }
248
327
  if (ch === "'" || ch === '"') {
249
328
  quote = ch;
250
329
  continue;
251
330
  }
252
- const opener = ch === "`" ? "`" : ch === "$" && cmd[i + 1] === "(" ? "$(" : (ch === "<" || ch === ">") && cmd[i + 1] === "(" ? ch + "(" : null;
331
+ const opener = substitutionOpener(cmd, i);
253
332
  if (!opener) continue;
254
- // Walk to the matching close (paren depth, or the closing backtick),
255
- // single-quote-aware inside so `'` in the payload doesn't strand us.
256
- let depth = 1;
257
- let j = i + opener.length;
258
- let inner = "";
259
- let innerQuote: "'" | '"' | null = null;
260
- for (; j < cmd.length && depth > 0; j++) {
261
- const c = cmd[j];
262
- if (innerQuote) {
263
- if (c === innerQuote && cmd[j - 1] !== "\\") innerQuote = null;
264
- } else if (c === "'" || c === '"') {
265
- innerQuote = c;
266
- } else if (opener === "`") {
267
- if (c === "`") depth = 0;
268
- } else if (c === "(") depth++;
269
- else if (c === ")") depth--;
270
- inner += depth > 0 ? c : "";
271
- }
272
- inners.push(inner);
273
- i = j - 1;
333
+ const r = readSubstitution(cmd, i);
334
+ inners.push(r.inner);
335
+ i = r.next - 1;
274
336
  }
275
337
  return inners;
276
338
  }
@@ -306,9 +368,10 @@ export function classifyCommand(cmd: string): CommandDisposition {
306
368
  for (let i = 0; i < c.length; i++) {
307
369
  const ch = c[i];
308
370
  if (quote) {
309
- if (ch === quote && c[i - 1] !== "\\") quote = null;
371
+ if (ch === quote && quoteCloses(c, i, quote)) quote = null;
310
372
  continue;
311
373
  }
374
+ if (ch === "\\") { i++; continue; }
312
375
  if (ch === "'" || ch === '"') {
313
376
  quote = ch;
314
377
  continue;
@@ -332,6 +395,10 @@ export function classifyCommand(cmd: string): CommandDisposition {
332
395
  inputRedirect = true; // `<` file input or `<(…)`, `>(…)` — executes/reads, demotes
333
396
  }
334
397
  }
398
+ // Dangling quote (unclosed at end — `echo 'it\'s'`, `ls "a\" ; rm x`):
399
+ // bash rejects the command, and a quote state we cannot trust must never
400
+ // auto-run. Confirm, never read.
401
+ if (quote) return "confirm";
335
402
  const sub = substitutionDisposition(c);
336
403
  if (sub === "write") return "write";
337
404
  // `sort --output` — the one flag-form file writer checked pre-split.