ceulen 0.17.0 → 0.19.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 (117) hide show
  1. package/CHANGELOG.md +85 -0
  2. package/extensions/modules/a2a/lib/client.ts +2 -1
  3. package/extensions/modules/advisor/commands/advisor.ts +22 -12
  4. package/extensions/modules/advisor/test/module.test.ts +26 -0
  5. package/extensions/modules/plan/index.ts +64 -0
  6. package/extensions/modules/plan/lib/plan-tools.ts +11 -0
  7. package/extensions/modules/plan/lib/shell-gate.ts +168 -14
  8. package/extensions/modules/plan/test/module.test.ts +125 -1
  9. package/extensions/modules/plan/test/shell-gate.test.ts +53 -1
  10. package/extensions/modules/steering/index.ts +25 -6
  11. package/extensions/modules/steering/test/anchor-regressions.test.ts +38 -0
  12. package/package.json +3 -3
  13. package/scripts/validate-themes.mjs +31 -3
  14. package/themes/alabaster.json +2 -17
  15. package/themes/amethyst.json +2 -19
  16. package/themes/anthracite.json +2 -22
  17. package/themes/basalt.json +3 -31
  18. package/themes/birch.json +2 -19
  19. package/themes/catppuccin-mocha.json +1 -7
  20. package/themes/dark-abyss.json +2 -17
  21. package/themes/dark-arctic.json +2 -23
  22. package/themes/dark-aurora.json +2 -18
  23. package/themes/dark-catppuccin.json +2 -25
  24. package/themes/dark-cavern.json +2 -18
  25. package/themes/dark-celestial.json +2 -18
  26. package/themes/dark-copper.json +2 -18
  27. package/themes/dark-cosmos.json +2 -17
  28. package/themes/dark-cyberpunk.json +2 -21
  29. package/themes/dark-dracula.json +2 -20
  30. package/themes/dark-eclipse.json +2 -18
  31. package/themes/dark-ember.json +2 -18
  32. package/themes/dark-equinox.json +2 -17
  33. package/themes/dark-forest.json +2 -21
  34. package/themes/dark-github.json +2 -24
  35. package/themes/dark-gruvbox.json +2 -30
  36. package/themes/dark-lavender.json +2 -18
  37. package/themes/dark-lunar.json +2 -17
  38. package/themes/dark-midnight.json +2 -18
  39. package/themes/dark-monochrome.json +2 -19
  40. package/themes/dark-monokai.json +2 -21
  41. package/themes/dark-nebula.json +2 -18
  42. package/themes/dark-neon-noir.json +2 -21
  43. package/themes/dark-nord.json +2 -21
  44. package/themes/dark-ocean.json +2 -22
  45. package/themes/dark-one.json +2 -21
  46. package/themes/dark-poimandres.json +4 -41
  47. package/themes/dark-rainforest.json +2 -17
  48. package/themes/dark-reef.json +2 -18
  49. package/themes/dark-retro.json +2 -18
  50. package/themes/dark-rose-pine.json +3 -21
  51. package/themes/dark-sakura.json +2 -18
  52. package/themes/dark-slate.json +2 -18
  53. package/themes/dark-solarized.json +2 -23
  54. package/themes/dark-solstice.json +2 -17
  55. package/themes/dark-starfall.json +2 -17
  56. package/themes/dark-sunset.json +2 -23
  57. package/themes/dark-swamp.json +2 -18
  58. package/themes/dark-synthwave.json +2 -25
  59. package/themes/dark-taiga.json +2 -17
  60. package/themes/dark-terminal.json +2 -18
  61. package/themes/dark-tokyo-night.json +2 -23
  62. package/themes/dark-tundra.json +2 -18
  63. package/themes/dark-twilight.json +2 -17
  64. package/themes/dark-volcanic.json +2 -17
  65. package/themes/dark.json +2 -6
  66. package/themes/graphite.json +2 -21
  67. package/themes/light-arctic.json +2 -27
  68. package/themes/light-aurora-day.json +2 -18
  69. package/themes/light-canyon.json +2 -17
  70. package/themes/light-catppuccin.json +3 -24
  71. package/themes/light-cirrus.json +2 -18
  72. package/themes/light-coral.json +2 -18
  73. package/themes/light-cyberpunk.json +2 -19
  74. package/themes/light-dawn.json +2 -17
  75. package/themes/light-dunes.json +2 -17
  76. package/themes/light-eucalyptus.json +2 -18
  77. package/themes/light-forest.json +3 -24
  78. package/themes/light-frost.json +2 -18
  79. package/themes/light-github.json +3 -39
  80. package/themes/light-glacier.json +2 -17
  81. package/themes/light-gruvbox.json +3 -30
  82. package/themes/light-haze.json +2 -18
  83. package/themes/light-honeycomb.json +2 -18
  84. package/themes/light-lagoon.json +2 -17
  85. package/themes/light-lavender.json +2 -18
  86. package/themes/light-meadow.json +2 -17
  87. package/themes/light-mint.json +2 -18
  88. package/themes/light-monochrome.json +2 -21
  89. package/themes/light-ocean.json +2 -20
  90. package/themes/light-one.json +2 -20
  91. package/themes/light-opal.json +2 -18
  92. package/themes/light-orchard.json +2 -18
  93. package/themes/light-paper.json +2 -18
  94. package/themes/light-poimandres.json +4 -41
  95. package/themes/light-prism.json +2 -19
  96. package/themes/light-retro.json +3 -21
  97. package/themes/light-sand.json +2 -18
  98. package/themes/light-savanna.json +2 -17
  99. package/themes/light-solarized.json +2 -22
  100. package/themes/light-soleil.json +2 -18
  101. package/themes/light-sunset.json +2 -22
  102. package/themes/light-synthwave.json +2 -22
  103. package/themes/light-tokyo-night.json +3 -28
  104. package/themes/light-wetland.json +2 -17
  105. package/themes/light-zenith.json +2 -18
  106. package/themes/light.json +2 -6
  107. package/themes/limestone.json +2 -19
  108. package/themes/mahogany.json +2 -19
  109. package/themes/marble.json +2 -19
  110. package/themes/mirage.json +2 -6
  111. package/themes/obsidian.json +2 -19
  112. package/themes/onyx.json +2 -17
  113. package/themes/pearl.json +2 -21
  114. package/themes/porcelain.json +2 -17
  115. package/themes/quartz.json +2 -19
  116. package/themes/sandstone.json +2 -20
  117. package/themes/titanium.json +2 -17
package/CHANGELOG.md CHANGED
@@ -1,5 +1,90 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.19.0 — 2026-10-15
4
+
5
+ Plan-mode false-block rework — mined from two weeks of session history
6
+ (155 sessions: 54 hard-blocked read-only commands, 28 headless confirm-blocks,
7
+ 15 user rejects; several reproduced live during the analysis itself):
8
+
9
+ - **plan/shell-gate**: `classifyCommand`'s redirect/substitution pre-check was
10
+ quote-blind and substitution-hostile. Six false-positive classes fixed:
11
+ `<`/`>` inside quoted strings (`jq 'select(.x > "1")'`, `grep -oE "[^<]"`)
12
+ are data, not redirects; `$(…)`/backticks/`<(…)` classify their INNER command
13
+ recursively (read inner → read, unknown → confirm, write inner → write)
14
+ instead of blanket-hard-block; heredocs feeding an interpreter
15
+ (`python3 - <<'EOF'`) demote from write-block to the confirm tier; bare
16
+ `env` (`env | grep -i PI_`) reads instead of writing; sed's s-command flag
17
+ scan no longer parses file PATHS (`…/modules/plan/index.ts` faked
18
+ `s/modules/plan/index` with flags containing `e`), is anchored against
19
+ word-char/`/`-preceded `s`, and treats a substitution AS the script as
20
+ uninspectable → confirm. True writers (`echo x > f`, `rm`, `cat > f <<EOF`)
21
+ stay hard-blocked. Regression fixture table pins 29 real commands from the
22
+ logs.
23
+ - **plan/plan-tools**: `READ_ONLY_TOOLS` gains the research set —
24
+ `web_search`, `web_extract`, `web_map`, `web_screenshot`, `web_pdf`,
25
+ `tool_search`, `todo`. `web_interact`/`web_crawl`/`web_research`/
26
+ `web_image`/`web_chat` stay at the confirm tier (external side effects).
27
+ - **classifier.planGate.observe**: recommended-first configuration step (a
28
+ settings change, not code): observe mode logs safe/unsafe verdicts for
29
+ confirm-tier commands to classifier.log under `ceulen-plan-gate`; review
30
+ before flipping `classifier.planGate.enabled` to auto-run safe commands
31
+ without prompting.
32
+ - **test**: fix the plan handoff test flake (two `write_plan` calls in the
33
+ same millisecond shared a `<timestamp>-<slug>` filename; the test now
34
+ sleeps 2ms — the module keeps overwrite semantics).
35
+
36
+ ## 0.18.0 — 2026-10-14
37
+
38
+ pi 1.2.0 compatibility + the ask_user_question confirmation loop (incident
39
+ report 2026-10-14, session 01a12a6c: six consecutive permission dialogs, each
40
+ answered, with the dispatch they were asking about never sent):
41
+
42
+ - **Themes broke on pi 1.2.0 — all 104 shipped themes failed to load**
43
+ (`Error: Failed to load theme "titanium": Theme not found: titanium` →
44
+ system fallback). pi 1.2.0 validates themes at startup against a schema with
45
+ `additionalProperties: false` at both the root object and `colors`; 100 of
46
+ the 104 themes carried non-schema keys inherited from the pi-themes port
47
+ (`statusLine*` ×14, `pythonMode`, `link`, `toolText`) that pi and ceulen both
48
+ ignore. Validation threw, the resource loader swallowed it as a diagnostic,
49
+ and the theme silently vanished. All 104 themes are now schema-clean (their
50
+ 255 orphaned `vars` pruned, `$schema` repointed to
51
+ `https://pi.dev/schemas/theme.schema.json`), and `scripts/validate-themes.mjs`
52
+ — which runs in `npm test` — gained ALLOWED/ROOT/EXPORT gates mirroring pi's
53
+ closed schema, so a stray key fails the suite instead of vanishing at boot.
54
+ Verified against pi 1.2.0's own validator: 4/104 → 104/104, all 104 also
55
+ build a Theme instance.
56
+ - **Peer deps widened** to `>=0.99.1 <1.3.0` for both `@earendil-works/pi-coding-agent`
57
+ and `@earendil-works/pi-tui` — the old range excluded 1.2.0 semver-wise. Dev
58
+ lockfile refreshed; typecheck + full suite now run against 1.2.0 types.
59
+ - **steering**: pi 1.2.0 made `BeforeAgentStartEvent` a union on `messageType`
60
+ (`prompt`/`images` only on the `"user"` variant) and now fires
61
+ `before_agent_start` for `sendMessage({triggerTurn:true})` runs too (cron
62
+ fires, repair auto-bg follow-ups, subagent receipts). The first-tool hints
63
+ read `event.prompt` (3 type errors) and the ds-anchor bootstrap could be
64
+ consumed by a machine-initiated run — running a cron task under the DSH
65
+ minimal prompt with bash/str_replace_editor only. Custom runs now skip the
66
+ bootstrap and the prompt-derived hints; the bootstrap stays pending for the
67
+ next user turn. Tested as "not custom" (not `=== "user"`), since pi ≤1.1.0
68
+ sends no `messageType`. 2 new tests.
69
+ - **plan**: `ask_user_question` gains a two-arm loop dampener. Either arm alone
70
+ has a hole: an identical-args guard misses the incident's reworded repeats
71
+ ("Ready to execute…dispatch…peer now?" → "Execute: dispatch to peer now?" →
72
+ "Dispatch now?" → "Dispatch?"). Arm A refuses a near-duplicate of an
73
+ already-answered question (stopword-filtered content-word containment, cut at
74
+ 0.8 — the incident's rewording scores 1.00 every time, the closest distinct
75
+ pair 0.67; replaying the incident it fires at ask #2). Arm B is the
76
+ wording-blind backstop: a 4th ask with no other tool call in between. The
77
+ guard returns the earlier question + answer and an instruction to act instead
78
+ of opening another dialog; any other tool call or a new session clears it.
79
+ 8 new tests.
80
+ - **advisor**: a whole-chain consult failure now wraps the raw provider error
81
+ (`400 insufficient credits` is what spun the model into asking) with what it
82
+ means and what to do — continue without guidance, do not stall the user.
83
+ 1 new test.
84
+ - **a2a**: the reply-timeout error now points at `a2a_status` and
85
+ `async_dispatch: true` before re-sending, and notes a duplicate synchronous
86
+ send can double-deliver.
87
+
3
88
  ## 0.17.0 — 2026-10-13
4
89
 
5
90
  - **Munin loop fixed** (incident report 2026-10-12; two sessions on
@@ -224,7 +224,8 @@ async function postJsonRpc(
224
224
  } catch (e: any) {
225
225
  if (ctrl.signal.aborted) {
226
226
  throw new Error(
227
- `reply timed out after ${timeoutMs}ms; delivery status unknown (requestId=${String(body.id)})`,
227
+ `reply timed out after ${timeoutMs}ms; delivery status unknown (requestId=${String(body.id)}). ` +
228
+ `The peer may still be working: check a2a_status before re-sending, and use async_dispatch: true for a peer that is routinely slow — a second synchronous send can double-deliver the work.`,
228
229
  );
229
230
  }
230
231
  throw new Error(`connection failed — ${e?.message || String(e)}`);
@@ -119,18 +119,28 @@ export function registerAdvisor(pi: ExtensionAPI, state: AdvisorState): AdvisorH
119
119
  // must not leave its partial output above the next candidate's response.
120
120
  let output = "";
121
121
  let attempt = 0;
122
- const result = await runIsolatedChain(ctx, models, {
123
- systemPrompt: `${SYSTEM}\n\nPRIMARY AGENT SYSTEM PROMPT:\n${ctx.getSystemPrompt()}`,
124
- messages: [{
125
- role: "user",
126
- content: [{ type: "text", text: `<transcript>${transcriptEvidence}</transcript>\n\nProvide strategic guidance for the executor.` }],
127
- timestamp: Date.now(),
128
- }],
129
- }, (delta, forAttempt) => {
130
- if (forAttempt !== attempt) { attempt = forAttempt; output = ""; }
131
- output += delta;
132
- onUpdate?.({ content: [{ type: "text", text: output }], details: { models } });
133
- }, signal);
122
+ let result;
123
+ try {
124
+ result = await runIsolatedChain(ctx, models, {
125
+ systemPrompt: `${SYSTEM}\n\nPRIMARY AGENT SYSTEM PROMPT:\n${ctx.getSystemPrompt()}`,
126
+ messages: [{
127
+ role: "user",
128
+ content: [{ type: "text", text: `<transcript>${transcriptEvidence}</transcript>\n\nProvide strategic guidance for the executor.` }],
129
+ timestamp: Date.now(),
130
+ }],
131
+ }, (delta, forAttempt) => {
132
+ if (forAttempt !== attempt) { attempt = forAttempt; output = ""; }
133
+ output += delta;
134
+ onUpdate?.({ content: [{ type: "text", text: output }], details: { models } });
135
+ }, signal);
136
+ } catch (error) {
137
+ // The whole chain failed (provider/key/quota — e.g. a 400 "insufficient
138
+ // credits"). A bare provider string reads to weak models as "the session
139
+ // is broken, so stall and ask the user" — the 2026-10-14 ask-loop
140
+ // incident started exactly here. Say what it means and what to do.
141
+ const reason = error instanceof Error ? error.message : String(error);
142
+ throw new Error(`Advisor unavailable (chain ${chain}): ${reason}\nContinue the task without advisor guidance. Do not tell the user the advisor failed and do not ask them to retry it — it is an optional second opinion, not a gate.`);
143
+ }
134
144
  return {
135
145
  content: [{ type: "text", text: `Advice from ${result.model}:\n${result.text}\n\nAdvisor usage: ${usageLine(result.usage.input, result.usage.output, result.usage.cost)}` }],
136
146
  details: { models, served: result.model },
@@ -683,3 +683,29 @@ describe("writeAdvisorSettings integration", () => {
683
683
  function cmdStatus(state: any, ctx: any): void {
684
684
  state.commands.get("advisor").handler("status", ctx);
685
685
  }
686
+
687
+ describe("consult tool — chain exhaustion message", () => {
688
+ it("wraps a raw provider failure with what it means and what to do", async () => {
689
+ writeSettings({ advisor: { enabled: true, models: [MODEL] } });
690
+ const { pi, state } = createFakePi();
691
+ advisorModule(pi);
692
+ const ctx = available(fakeCtx([]));
693
+ await fire(pi, state, "session_start", ctx);
694
+ const tool = state.tools.get("advisor");
695
+ assert.ok(tool, "consult tool registered");
696
+ // The provider rejects the call (the 400 "insufficient credits" shape).
697
+ ctx.modelRegistry.streamSimple = () => {
698
+ throw new Error('400: {"message":"You have insufficient credits to make this request."}');
699
+ };
700
+ await assert.rejects(
701
+ () => tool.execute("tc1", {}, undefined, undefined, ctx),
702
+ (err: Error) => {
703
+ assert.match(err.message, /Advisor unavailable \(chain /, "names the failed chain");
704
+ assert.match(err.message, /insufficient credits/, "keeps the provider reason");
705
+ assert.match(err.message, /Continue the task without advisor guidance/, "tells the model to proceed");
706
+ assert.match(err.message, /Do not tell the user the advisor failed/, "forbids the stall-and-ask loop");
707
+ return true;
708
+ },
709
+ );
710
+ });
711
+ });
@@ -519,10 +519,64 @@ export default function planModule(pi: ExtensionAPI): void {
519
519
  // ponytail: ctx.ui.select is not reentrant — serialize concurrent dialogs.
520
520
  let askQuestionQueue: Promise<unknown> = Promise.resolve();
521
521
 
522
+ // Ask-loop dampener (2026-10-14 incident, session 01a12a6c): a glm-5.3-flash
523
+ // run asked permission 6 times in a row — each answered "Send it" — without
524
+ // ever emitting the a2a_call it was asking about. The wording drifted each
525
+ // time ("Ready to execute…dispatch now?" → "Execute: dispatch to peer now?" →
526
+ // "Dispatch now?" → "Dispatch?"), so an identical-args guard catches nothing.
527
+ // TWO independent arms, because either alone leaves a hole:
528
+ // A. near-duplicate — catches the incident's reworded repeats immediately.
529
+ // B. consecutive count — wording-independent backstop for a loop that drifts
530
+ // past the similarity cut (a 4th ask with NO tool call in between is a
531
+ // loop whatever it says; three distinct questions is a legitimate flow).
532
+ // ANY other tool call (see the tool_call hook) or a new session clears both.
533
+ let asksSinceToolCall = 0;
534
+ const ASK_RUN_LIMIT = 4;
535
+ let answeredAsks: { question: string; tokens: Set<string>; answer: string }[] = [];
536
+ // Filler words carry no intent and are removed first: without this "Should I
537
+ // dispatch the diagnosis to the peer now?" and "Should I revert the config
538
+ // now?" overlap on should/i/the/now and read as the same question.
539
+ const ASK_STOPWORDS = new Set([
540
+ "a", "an", "and", "are", "be", "before", "can", "do", "does", "for", "from", "go", "i", "if",
541
+ "in", "is", "it", "its", "me", "my", "now", "of", "on", "or", "please", "ready", "should",
542
+ "so", "that", "the", "then", "this", "to", "up", "use", "we", "what", "when", "which", "with",
543
+ "you", "your",
544
+ ]);
545
+ const askTokens = (q: string): Set<string> =>
546
+ new Set((q.toLowerCase().match(/[a-z0-9]+/g) ?? []).filter((t) => !ASK_STOPWORDS.has(t) && t.length > 1));
547
+ // 0.8 keeps the recall we need without tripping on same-verb/different-object
548
+ // questions. Measured on the incident's real wording drift (identical intent):
549
+ // "Ready to execute…dispatch…peer now?" vs "Execute: dispatch to peer now?" /
550
+ // "Dispatch now?" / "Dispatch?" all score 1.00, while the closest DISTINCT pair
551
+ // ("Should I restart the radius unit?" vs "…nginx unit?") scores 0.67.
552
+ /** Content words the shorter question shares with the longer, ≥0.8 → "same intent". */
553
+ const isNearDuplicate = (a: Set<string>, b: Set<string>): boolean => {
554
+ if (a.size === 0 || b.size === 0) return false;
555
+ const [small, big] = a.size <= b.size ? [a, b] : [b, a];
556
+ let shared = 0;
557
+ for (const token of small) if (big.has(token)) shared += 1;
558
+ return shared / small.size >= 0.8;
559
+ };
560
+
522
561
  async function executeAskQuestion(_toolCallId: string, params: unknown, _signal: unknown, _onUpdate: unknown, ctx: ExtensionToolContext) {
523
562
  const typedParams = params as PlanQuestionParams;
524
563
  const { options, recommendedIndex } = validateQuestionParams(typedParams);
525
564
  const textBlock = (text: string) => ({ type: "text" as const, text });
565
+ const tokens = askTokens(typedParams.question);
566
+ const repeat = answeredAsks.find((entry) => isNearDuplicate(tokens, entry.tokens));
567
+ asksSinceToolCall += 1;
568
+ const prior = repeat ?? answeredAsks[answeredAsks.length - 1];
569
+ if (repeat || (asksSinceToolCall >= ASK_RUN_LIMIT && prior)) {
570
+ return {
571
+ content: [textBlock(
572
+ `Loop guard: ${repeat
573
+ ? `you already asked this and the user answered — "${repeat.question}" → "${repeat.answer}".`
574
+ : `this is ask_user_question call #${asksSinceToolCall} in a row with no other tool call in between; the last answer was "${prior.question}" → "${prior.answer}".`} ` +
575
+ `Act on that answer now instead of asking again. If something genuinely blocks you, do the work that resolves it or say what the blocker is in plain text (a further question is allowed after any other tool call).`,
576
+ )],
577
+ details: { question: typedParams.question, options, answer: prior.answer, cancelled: false, loopGuard: true },
578
+ };
579
+ }
526
580
  const cancelled = {
527
581
  content: [textBlock("User cancelled the question.")],
528
582
  details: { question: typedParams.question, options, answer: null, cancelled: true, wasCustom: false },
@@ -546,6 +600,8 @@ export default function planModule(pi: ExtensionAPI): void {
546
600
  if (choice === otherLabel) {
547
601
  const answer = (await ctx.ui.editor("Your answer", ""))?.trim();
548
602
  if (!answer) return cancelled;
603
+ answeredAsks.push({ question: typedParams.question, tokens, answer });
604
+ if (answeredAsks.length > 8) answeredAsks.shift();
549
605
  return {
550
606
  content: [textBlock(`User wrote: ${answer}`)],
551
607
  details: { question: typedParams.question, options, answer, wasCustom: true, cancelled: false },
@@ -553,6 +609,8 @@ export default function planModule(pi: ExtensionAPI): void {
553
609
  }
554
610
  const selectedIndex = displayLabels.indexOf(choice);
555
611
  const answer = options[selectedIndex]?.label ?? choice;
612
+ answeredAsks.push({ question: typedParams.question, tokens, answer });
613
+ if (answeredAsks.length > 8) answeredAsks.shift();
556
614
  return {
557
615
  content: [textBlock(`User selected: ${answer}`)],
558
616
  details: { question: typedParams.question, options, answer, selectedIndex, wasCustom: false, cancelled: false },
@@ -871,6 +929,8 @@ export default function planModule(pi: ExtensionAPI): void {
871
929
 
872
930
  pi.on("session_start", async (event, ctx) => {
873
931
  sessionAllows.clear();
932
+ answeredAsks = [];
933
+ asksSinceToolCall = 0;
874
934
  refreshSettings(ctx);
875
935
  setPlanRegistry(ctx.modelRegistry);
876
936
  void probeDiffDrivers(ctx.cwd); // best-effort: textconv-aware bash gating
@@ -923,6 +983,10 @@ export default function planModule(pi: ExtensionAPI): void {
923
983
  * blocked mutators → hard error; bash writers → hard-block; bash reads →
924
984
  * auto-allow; unknown executables + non-read tools → confirm tier. */
925
985
  pi.on("tool_call", async (event, ctx) => {
986
+ // Ask-loop dampener: any tool call other than the question itself breaks the
987
+ // run (munin dampener contract). Deliberately above the
988
+ // plan-mode early return — the loop it guards is not plan-specific.
989
+ if (event.toolName !== ASK_USER_QUESTION_TOOL) { answeredAsks = []; asksSinceToolCall = 0; }
926
990
  if (!planModeEnabled) return;
927
991
  if (BLOCKED_TOOLS.has(event.toolName)) {
928
992
  return { block: true, reason: `plan mode: ${event.toolName} is not available while planning. Use ${PLAN_TOOL} to write the plan file.` };
@@ -33,6 +33,17 @@ export const READ_ONLY_TOOLS = new Set([
33
33
  // Rendered-page accessibility audit — reads the page in a local headless
34
34
  // Chrome, mutates nothing.
35
35
  "web_a11y",
36
+ // Web research reads: search results, page→markdown, site URL map, page
37
+ // capture/PDF text. Plan mode IS research; these fetch remote content and
38
+ // write nothing (web_interact/web_crawl/web_research/web_image/web_chat
39
+ // act on external services and stay at the confirm tier).
40
+ "web_search", "web_extract", "web_map", "web_screenshot", "web_pdf",
41
+ // tool_search loads a deferred tool onto the request — no side effects; it
42
+ // is the only path to the deferred munin/web reads inside plan mode.
43
+ "tool_search",
44
+ // Todo phases persist session-transcript entries only (pi.appendEntry) —
45
+ // never the repo; OMP plans track phases while planning.
46
+ "todo",
36
47
  // PDF text extraction (vendored pdf.js, in-process) — reads a local file.
37
48
  "read_pdf",
38
49
  // Semantic find — read-only judging over the workspace; costs model calls
@@ -3,6 +3,15 @@
3
3
  // keep the rules byte-faithful. Local changes: exported standalone functions,
4
4
  // no plan/file state.
5
5
  //
6
+ // 2026-10-15 rework (session-history evidence: 54 hard-blocked read-only
7
+ // commands over 2 weeks — see .pi/plans/2026-10-15T08-50-03-167Z*.md): the
8
+ // redirect/substitution pre-check became quote-aware; `$(…)`/`` `…` ``/
9
+ // `<(…)` substitutions classify their INNER command instead of blanket-write;
10
+ // heredocs feeding an interpreter drop from write to the confirm tier; bare
11
+ // `env` (no args) reads; sed's s-command flag scan no longer parses file
12
+ // PATHS as `s/pattern/repl/flags`. Deliberate deviations from upstream —
13
+ // keep them when re-vendoring.
14
+ //
6
15
  // Classifies one shell command for plan mode WITHOUT attempting to interpret
7
16
  // arbitrary executables:
8
17
  // read — provably no filesystem writes → auto-run
@@ -99,13 +108,48 @@ const FLOW_KEYWORD = /^(?:while|until|do|done)(?:\s+|$)/;
99
108
  // sed read-only gate: `w` (file write), `e` (executes pattern space), -f
100
109
  // (script file, uninspectable), -i (in-place) are the writers. Everything else
101
110
  // is stdout-only.
102
- const S_COMMAND_FLAGS = /s([^\w\s])(?:\\.|(?!\1)[\s\S])*?\1(?:\\.|(?!\1)[\s\S])*?\1([a-z0-9]*)/gi;
111
+ // `s` must not follow a word char or `/` — `s/modules/plan/index` inside a
112
+ // PATH (`…/modules/plan/index.ts`, observed inside a substitution span) is
113
+ // not an s-command. Address forms (`2s/…`) missed here are backstopped by
114
+ // the standalone `w`-flag checks below.
115
+ const S_COMMAND_FLAGS = /(?<![\/\w])s([^\w\s])(?:\\.|(?!\1)[\s\S])*?\1(?:\\.|(?!\1)[\s\S])*?\1([a-z0-9]*)/gi;
116
+
117
+ /** Quoted spans of a command — sed script arguments in practice. The s-command
118
+ * flag scan runs over ONLY these: file path operands like
119
+ * `extensions/modules/plan/index.ts` must not be parsed as
120
+ * `s/modules/plan/index` (flags "index" contain `e` → false "not read-only",
121
+ * observed live: `sed -n '800,845p' …/plan/index.ts` blocked). */
122
+ function quotedSpans(cmd: string): string[] {
123
+ const spans: string[] = [];
124
+ let quote: "'" | '"' | null = null;
125
+ let cur = "";
126
+ for (const ch of cmd) {
127
+ if (quote) {
128
+ cur += ch;
129
+ if (ch === quote) {
130
+ spans.push(cur);
131
+ cur = "";
132
+ quote = null;
133
+ }
134
+ } else if (ch === "'" || ch === '"') {
135
+ quote = ch;
136
+ }
137
+ }
138
+ return spans;
139
+ }
103
140
 
104
141
  function isSedReadOnly(inspection: string): boolean {
105
142
  if (/(?:^|\s)-[a-zA-Z]*[if][a-zA-Z]*\b|--in-place\b|--file\b/i.test(inspection)) return false;
106
- if (/(?<![A-Za-z])w|w(?![A-Za-z])/i.test(inspection)) return false;
107
- if (/(?:^|[^A-Za-z-])e(?:[\s;}]|$|['"])/i.test(inspection)) return false;
108
- for (const m of inspection.matchAll(S_COMMAND_FLAGS)) {
143
+ // The w/e flag checks and the s-command scan apply to the SCRIPT (the
144
+ // quoted arguments), never to file-path operands.
145
+ const script = quotedSpans(inspection).join("\n") || inspection;
146
+ // A runtime-computed script (`sed -n "$(grep …)p"`) is uninspectable —
147
+ // its `w`/`e` flags are only known at execution. Same reasoning as the
148
+ // heredoc rule: demote to confirm, never auto-read.
149
+ if (/\$\(|`/.test(script)) return false;
150
+ if (/(?<![A-Za-z])w|w(?![A-Za-z])/i.test(script)) return false;
151
+ if (/(?:^|[^A-Za-z-])e(?:[\s;}]|$|['"])/i.test(script)) return false;
152
+ for (const m of script.matchAll(S_COMMAND_FLAGS)) {
109
153
  if (/[ew]/i.test(m[2])) return false;
110
154
  }
111
155
  return true;
@@ -156,7 +200,15 @@ export function classifySegment(seg: string): CommandDisposition {
156
200
  // command/type/which: only pure executable lookups are reads. POSIX `command NAME`
157
201
  // EXECUTES NAME, so bare `command` stays a writer wrapper; only `command -v/-V` is a lookup.
158
202
  if (/^(?:type|which)\b/i.test(inspection) || /^command\s+-[vV]\b/i.test(inspection)) return "read";
159
- if (/^(?:(?:rm|rmdir|mv|cp|mkdir|touch|chmod|chown|ln|install|truncate|dd|mktemp|command)|sudo|env|nohup|time)\b/i.test(inspection)) return "write";
203
+ // `env` is transparent: `env` alone (or piped — each pipe stage is its own
204
+ // segment) PRINTS the environment; `env VAR=x cmd…` runs the remainder.
205
+ // Observed live: `env | grep -i "PI_"` hard-blocked as a writer.
206
+ if (/^env(?:\s|$)/i.test(inspection)) {
207
+ const rest = inspection.replace(/^env\s*/i, "").trim();
208
+ if (!rest) return "read";
209
+ return classifySegment(rest);
210
+ }
211
+ if (/^(?:(?:rm|rmdir|mv|cp|mkdir|touch|chmod|chown|ln|install|truncate|dd|mktemp|command)|sudo|nohup|time)\b/i.test(inspection)) return "write";
160
212
  if (/^sed\b/i.test(inspection)) {
161
213
  if (/\s(?:-i\S*|--in-place(?:=\S*)?)(?:\s|$)/i.test(inspection) || /\b(?:\d+)?w\s+/i.test(inspection) || /\/w\s/i.test(inspection) || /(?:^|[^A-Za-z-])\d+w[a-zA-Z0-9.]/i.test(inspection)) return "write";
162
214
  return isSedReadOnly(inspection) ? "read" : "confirm";
@@ -180,21 +232,123 @@ export function classifySegment(seg: string): CommandDisposition {
180
232
  return /^(?:rg|grep|find|fd|ls|pwd|cat|head|tail|wc|sort|uniq|cut|echo|printf|jq|strings|stat|file|du|tree|lsof|basename|dirname|realpath|cd|read|diff|cmp)\b/i.test(inspection) ? "read" : "confirm";
181
233
  }
182
234
 
235
+ /** Executing substitutions (`$(…)`, backticks, `<(…)`, `>(…)`) OUTSIDE single
236
+ * quotes (single-quoted text is literal — no substitution happens). Inner
237
+ * commands are classified recursively; a substitution is only as safe as
238
+ * what it runs. Nesting handled by depth; unclosed spans read to end. */
239
+ function findExecutingSubstitutions(cmd: string): string[] {
240
+ const inners: string[] = [];
241
+ let quote: "'" | '"' | null = null;
242
+ for (let i = 0; i < cmd.length; i++) {
243
+ const ch = cmd[i];
244
+ if (quote) {
245
+ if (ch === quote && cmd[i - 1] !== "\\") quote = null;
246
+ continue;
247
+ }
248
+ if (ch === "'" || ch === '"') {
249
+ quote = ch;
250
+ continue;
251
+ }
252
+ const opener = ch === "`" ? "`" : ch === "$" && cmd[i + 1] === "(" ? "$(" : (ch === "<" || ch === ">") && cmd[i + 1] === "(" ? ch + "(" : null;
253
+ 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;
274
+ }
275
+ return inners;
276
+ }
277
+
278
+ /** Disposition of every executing substitution in the command, or null when
279
+ * there are none. read only when EVERY inner command is read. */
280
+ function substitutionDisposition(cmd: string): CommandDisposition | null {
281
+ const inners = findExecutingSubstitutions(cmd);
282
+ if (inners.length === 0) return null;
283
+ let worst: CommandDisposition = "read";
284
+ for (const inner of inners) {
285
+ const d = classifyCommand(inner);
286
+ if (d === "write") return "write";
287
+ if (d === "confirm") worst = "confirm";
288
+ }
289
+ return worst;
290
+ }
291
+
183
292
  /** Classify a full (possibly compound) command. Any known writer wins; the
184
- * whole command is read only when every segment is read. */
293
+ * whole command is read only when every segment is read, there is no
294
+ * file-writing redirection, and no substitution/heredoc demotes it. */
185
295
  export function classifyCommand(cmd: string): CommandDisposition {
186
296
  const c = cmd.trim();
187
297
  if (!c) return "confirm";
188
- // Redirections (stdout/stderr to files, here-docs) can create/modify files.
189
- // Discarding forms are read-safe: n>/dev/null, n>>/dev/null and fd dups
190
- // (2>&1, 2>&-). Command substitution and heredocs are always writes.
191
- const cNoDiscard = c.replace(/\d*>+\s*\/dev\/null(?![\w.\/-])|\d*>&[\d-]/g, "");
192
- if (/[<>]/.test(cNoDiscard) || /\$\(|`/.test(c) || /--output(?:=|\s)/i.test(c)) return "write";
193
- const segments = splitShellSegments(cNoDiscard);
298
+ // File-writing redirections stay a hard write — but only REAL ones:
299
+ // quote-aware, so `<`/`>` inside quoted strings (jq `select(.x > "1")`
300
+ // programs, `grep -oE "[^<]"` patterns — the two biggest live false-block
301
+ // classes) are data, not redirects. Discarding forms stay read-safe:
302
+ // n>/dev/null and fd dups (2>&1, 2>&-).
303
+ let quote: "'" | '"' | null = null;
304
+ let heredocMark = false;
305
+ let inputRedirect = false; // unquoted `<` file/process input — demotes read
306
+ for (let i = 0; i < c.length; i++) {
307
+ const ch = c[i];
308
+ if (quote) {
309
+ if (ch === quote && c[i - 1] !== "\\") quote = null;
310
+ continue;
311
+ }
312
+ if (ch === "'" || ch === '"') {
313
+ quote = ch;
314
+ continue;
315
+ }
316
+ if (ch === "<" || ch === ">") {
317
+ const run = c.slice(i).match(/^[<>]+/)?.[0] ?? "";
318
+ const rest = c.slice(i + run.length);
319
+ if (ch === ">") {
320
+ // Writers: `>`/`>>` to a file. Read-safe: n>/dev/null, 2>&1, 2>&-.
321
+ if (/^\s*\/dev\/null(?![\w.\/-])/.test(rest) || /^\s*&[\d-]/.test(rest)) {
322
+ i += run.length + (rest.match(/^\s*\S+/)?.[0].length ?? 0);
323
+ continue;
324
+ }
325
+ return "write";
326
+ }
327
+ if (run.length >= 2) {
328
+ heredocMark = true; // `<<`/`<<-` heredoc marker
329
+ i += run.length - 1;
330
+ continue;
331
+ }
332
+ inputRedirect = true; // `<` file input or `<(…)`, `>(…)` — executes/reads, demotes
333
+ }
334
+ }
335
+ const sub = substitutionDisposition(c);
336
+ if (sub === "write") return "write";
337
+ // `sort --output` — the one flag-form file writer checked pre-split.
338
+ if (/--output(?:=|\s)/i.test(c)) return "write";
339
+ // Strip discard redirects before segmenting: `2>&1`'s `&` is an fd dup,
340
+ // NOT a background separator (splitting on it yields a phantom "1"
341
+ // segment that classifies confirm). The write-scan above already ran.
342
+ const segments = splitShellSegments(c.replace(/\d*>+\s*\/dev\/null(?![\w.\/-])|\d*>&[\d-]/g, ""));
194
343
  if (segments.length > 1) {
195
344
  if (segments.some((seg) => classifySegment(seg) === "write")) return "write";
196
- if (segments.every((seg) => classifySegment(seg) === "read")) return "read";
345
+ if (segments.every((seg) => classifySegment(seg) === "read")) {
346
+ if (sub === "confirm" || heredocMark || inputRedirect) return "confirm";
347
+ return "read";
348
+ }
197
349
  return "confirm";
198
350
  }
199
- return classifySegment(c);
351
+ const single = classifySegment(c);
352
+ if (single === "read" && (sub === "confirm" || heredocMark || inputRedirect)) return "confirm";
353
+ return single;
200
354
  }