ceulen 0.15.1 → 0.16.1

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 (55) hide show
  1. package/CHANGELOG.md +62 -0
  2. package/README.md +2 -2
  3. package/extensions/lib/registry.test.ts +12 -0
  4. package/extensions/lib/registry.ts +20 -4
  5. package/extensions/modules/classifier/index.ts +29 -12
  6. package/extensions/modules/classifier/lib/settings.ts +20 -3
  7. package/extensions/modules/classifier/test/classifier.test.ts +12 -4
  8. package/extensions/modules/config/defaultTools.ts +8 -5
  9. package/extensions/modules/config/test/defaultTools.test.ts +16 -0
  10. package/extensions/modules/gh/lib/ops.ts +22 -4
  11. package/extensions/modules/gh/test/gh.test.ts +64 -1
  12. package/extensions/modules/munin/index.ts +4 -4
  13. package/extensions/modules/plan/index.ts +116 -4
  14. package/extensions/modules/plan/lib/settings.ts +5 -7
  15. package/extensions/modules/plan/test/module.test.ts +104 -1
  16. package/extensions/modules/plan/test/settings.test.ts +7 -0
  17. package/extensions/modules/repair/configPanel.ts +3 -1
  18. package/extensions/modules/repair/index.ts +21 -16
  19. package/extensions/modules/repair/lib/read-sqlite.ts +18 -7
  20. package/extensions/modules/repair/test/freshness.test.ts +30 -0
  21. package/extensions/modules/repair/test/hardening.test.ts +46 -1
  22. package/extensions/modules/repair/test/readers.test.ts +11 -5
  23. package/extensions/modules/repair/test/settings.test.ts +7 -2
  24. package/extensions/modules/rtk/configPanel.ts +67 -0
  25. package/extensions/modules/rtk/index.ts +76 -9
  26. package/extensions/modules/rtk/lib/settings.ts +65 -0
  27. package/extensions/modules/rtk/test/configPanel.test.ts +72 -0
  28. package/extensions/modules/rtk/test/index.test.js +120 -2
  29. package/extensions/modules/rules/index.ts +4 -1
  30. package/extensions/modules/rules/lib/rules.ts +6 -3
  31. package/extensions/modules/rules/test/lib.test.ts +24 -0
  32. package/extensions/modules/rules/test/module.test.ts +29 -0
  33. package/extensions/modules/shells/lib/sessions.ts +40 -12
  34. package/extensions/modules/shells/test/sessions.test.ts +60 -2
  35. package/extensions/modules/steering/index.ts +12 -1
  36. package/extensions/modules/steering/test/anchor-plan.test.ts +73 -0
  37. package/extensions/modules/subagent/index.ts +19 -3
  38. package/extensions/modules/subagent/lib/herdr.ts +141 -1
  39. package/extensions/modules/subagent/lib/runner.ts +88 -22
  40. package/extensions/modules/subagent/test/herdr-stalled.test.ts +117 -0
  41. package/extensions/modules/subagent/test/worktree.test.ts +156 -1
  42. package/extensions/modules/todo/index.ts +4 -0
  43. package/extensions/modules/todo/test/todo.test.ts +9 -0
  44. package/extensions/modules/web/index.ts +1 -1
  45. package/extensions/modules/web/lib/a11y.ts +30 -15
  46. package/extensions/modules/web/lib/cdp.ts +11 -2
  47. package/extensions/modules/web/lib/chrome.ts +12 -3
  48. package/extensions/modules/web/lib/content.ts +32 -9
  49. package/extensions/modules/web/lib/search.ts +111 -3
  50. package/extensions/modules/web/test/a11y.test.ts +100 -2
  51. package/extensions/modules/web/test/cdp.test.ts +48 -0
  52. package/extensions/modules/web/test/chrome.test.ts +32 -0
  53. package/extensions/modules/web/test/content.test.ts +92 -0
  54. package/extensions/modules/web/test/search.test.ts +75 -0
  55. package/package.json +1 -1
package/CHANGELOG.md CHANGED
@@ -1,5 +1,67 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.16.1 — 2026-10-10
4
+
5
+ - **herdr stall recovery rewritten on output evidence** — live probing
6
+ (2026-10-10) showed herdr 0.9.3's status watcher NEVER reports `working`
7
+ for pi panes (`state_change_seq` frozen across live turns), so
8
+ `agent prompt --wait` returned `agent_prompt_stalled` on healthy
9
+ dispatches (every herdr delegation was affected; the child completed its
10
+ work while the parent reported failure). The subagent module now snapshots
11
+ an output-evidence baseline BEFORE submission (`captureEvidenceStamp`:
12
+ report-file stamp + pane tail for read-only children) and, on a stall,
13
+ waits on EVIDENCE for the remaining dispatch budget — a changed report-file
14
+ stamp (delivery contract) or a changed-then-quiet pane tail (3 stable
15
+ polls). Window exhaustion reports timeout semantics (pane interrupted,
16
+ may-still-complete disclosure) — never a phantom hard stall. Verified live
17
+ across all five agent types under 4-way concurrency, including a mid-turn
18
+ Z.ai 429 recovery; 6 new regression tests (`test/herdr-stalled.test.ts`).
19
+
20
+ ## 0.16.0 — 2026-10-09
21
+
22
+ - **RTK selective rewrite** — the prompt note states the policy honestly
23
+ (RTK rewrites only what it models; chains, redirects, and inline scripts
24
+ pass through unchanged, byte-identical every turn for prefix-cache
25
+ stability), per-command truth moved to `[pi-rtk] passed through unchanged`
26
+ notifies (deduped per consecutive identical command), and a new global
27
+ `rtk` settings section (`mode: supported-only|off`, `chained:
28
+ only-all-modeled|never`) read per bash call — `/config` → Shell → RTK.
29
+ Measured on rtk 0.50.0: the rewrite fails open on every chain with an
30
+ unmodeled segment (90% of this repo's real bash traffic), so `chained:
31
+ never` also skips the wasted spawn per chain.
32
+ - **Web search backend router** — in auto mode with ≥2 backends configured,
33
+ `web_search` asks the classifier (one Jev round-trip) to pick brave-first
34
+ (precision/docs/error-strings) vs searxng-first (broad discovery); low
35
+ confidence, timeout, or failure falls back to the unchanged heuristic.
36
+ `SearchDiagnostics.router` + the diagnostics block expose which path ran.
37
+ - **planGate ported** — `classifier.planGate.{enabled,observe,threshold}`
38
+ (default off) lets the plan module's confirm tier auto-run a command when
39
+ Jev says it clearly won't mutate the filesystem and serves the task;
40
+ writes stay hard-blocked, the static RISKY list skips the gate, and every
41
+ verdict audits to classifier.log (`ceulen-plan-gate`). Run
42
+ `observe: true` first to measure the false-auto rate.
43
+
44
+ ## 0.15.2 — 2026-10-08
45
+
46
+ Deferred-tier re-evaluation from live session usage (211 transcripts, 13K tool
47
+ calls). Four tools promoted from `tool_search`-only back to always-declared:
48
+
49
+ - **munin_search / munin_get** — the Memory Protocol is injected into every
50
+ configured session and its before-acting rule is a search; the old deferred
51
+ tier forced a discovery round-trip in front of the protocol's own workflow.
52
+ - **github** — the top user among deferred tools (61 calls/17 sessions, all
53
+ pre-dating the deferred pass). Since deferral, release verification did not
54
+ discover it via tool_search and fell back to raw bash gh, forfeiting the
55
+ wrapper's deadline, output cap, and read-only guardrails.
56
+ - **ux_audit** — every ux_* skill routes into it pre-code; the ux module is
57
+ always loaded, so the deferred tier was a pure-latency detour.
58
+
59
+ 52 tools stay discover-only (serena, a2a, web cold tools, sg, fff extras,
60
+ munin store/list/…, jfind, cron, shell, notify, rule_get). Declared block goes
61
+ ~438 → ~507 tokens, still ~47% below the pre-deferral ~955. Docs swept
62
+ (AGENTS.md module-convention + module sections, README tool-loading, stale
63
+ defaultTools docstring); +registry tier guard test.
64
+
3
65
  ## 0.15.1 — 2026-10-08
4
66
 
5
67
  pi 1.1.0 compatibility (audit found the API diff purely additive — SettingsManager,
package/README.md CHANGED
@@ -149,7 +149,7 @@ Opt-in `permission` settings section: allow/ask/deny rules per tool with wildcar
149
149
 
150
150
  - **serena** — semantic code tools (find symbol, references, rename, diagnostics) via a persistent language-server worker
151
151
  - **fff** — fast fuzzy file/content search (`ffgrep`, `fffind`) feeding the built-in grep/find experience and `@`-mention completions
152
- - **rtk** — transparently rewrites shell commands to save tokens (`/rtk status`, `RTK_DISABLED=1` to bypass)
152
+ - **rtk** — rewrites shell commands through RTK only where RTK supports them (git, ls, rg, test runners); chains, redirects, and inline scripts pass through byte-identical (`/rtk status`, `/config` → Shell → RTK, `RTK_DISABLED=1` to bypass)
153
153
 
154
154
  ### config — the settings panel
155
155
 
@@ -174,7 +174,7 @@ In `~/.pi/agent/settings.json` or a trusted project's `.pi/settings.json` — a
174
174
 
175
175
  The core set — router, usage, ux, classifier, composer, advisor, and the `/config` panel itself — is always on and never appears in the kill-switch list.
176
176
 
177
- **Tool loading**: most tools register *deferred* — not declared to the model, loaded on demand by `tool_search` (pi activates it for you). Only the hot core (subagent, todo, web search/extract/screenshot/interact, fffgrep/fffind, plan/repair tools, advisor, classify, think) is declared every request, keeping the standing token cost small no matter how many tools ceulen ships.
177
+ **Tool loading**: most tools register *deferred* — not declared to the model, loaded on demand by `tool_search` (pi activates it for you). Declared every request: the hot core (subagent, herdr, todo, write_plan, ask_user_question, apply_patch, str_replace_editor, web_search/extract/screenshot/interact, ffgrep/fffind, advisor, classify, think) plus four tools promoted in the 2026-10-08 usage re-eval — `munin_search`, `munin_get`, `github`, `ux_audit`. Everything else stays discover-only, keeping the standing token cost small no matter how many tools ceulen ships.
178
178
 
179
179
  ## License
180
180
 
@@ -48,6 +48,18 @@ describe("isProjectTrusted", () => {
48
48
  });
49
49
  });
50
50
 
51
+ describe("deferredTools tiers", () => {
52
+ // 2026-10-08 usage re-eval: these four were promoted from deferred to
53
+ // direct. A registry edit that silently reverts them must fail here.
54
+ it("keeps the promoted hot tools out of every deferred list", async () => {
55
+ const { MODULES } = await import("./registry.js");
56
+ const allDeferred = new Set(MODULES.flatMap((m) => m.deferredTools ?? []));
57
+ for (const hot of ["munin_search", "munin_get", "github", "ux_audit"]) {
58
+ assert.equal(allDeferred.has(hot), false, `${hot} must stay direct`);
59
+ }
60
+ });
61
+ });
62
+
51
63
  describe("MODULES load order", () => {
52
64
  // The steering entry must stay behind every before_agent_start prompt
53
65
  // rewriter (its ds-anchor bootstrap REPLACES the final prompt; a rewriter
@@ -38,6 +38,7 @@ import uxModule, { uxConfig } from "../modules/ux/index.ts";
38
38
  import serenaModule from "../modules/serena/index.ts";
39
39
  import fffModule from "../modules/fff/index.ts";
40
40
  import rtkModule from "../modules/rtk/index.ts";
41
+ import { rtkConfig } from "../modules/rtk/configPanel.ts";
41
42
  import muninModule from "../modules/munin/index.ts";
42
43
  import { muninConfig } from "../modules/munin/configPanel.ts";
43
44
  import webModule from "../modules/web/index.ts";
@@ -124,10 +125,20 @@ export const MODULES: ModuleEntry[] = [
124
125
  // ── Appearance ─────────────────────────────────────────────────────────
125
126
  { name: "usage", core: true, category: "Appearance", describe: "Subscription-usage footer (5h/weekly/monthly windows + credits).", load: usageModule },
126
127
  { name: "composer", core: true, category: "Appearance", describe: "Composer shape for the input editor — pick one in /config with a live preview. Core: always on.", load: composerModule, config: composerConfig },
127
- { name: "ux", core: true, category: "Appearance", describe: "Anti-slop UI/UX design discipline: /ux modes, ux_audit tool, design skills. No status-bar footprint.", load: uxModule, config: uxConfig, deferredTools: ["ux_audit"] },
128
+ // ux_audit is DIRECT (2026-10-08 usage re-eval): every ux_* skill routes to
129
+ // it, it must run pre-code in the ux workflow, and it has no fs/network side
130
+ // effects. The ux module is CORE (always loaded), so registration alone
131
+ // declares it — no tool_search detour to start the UX discipline.
132
+ { name: "ux", core: true, category: "Appearance", describe: "Anti-slop UI/UX design discipline: /ux modes, ux_audit tool, design skills. No status-bar footprint.", load: uxModule, config: uxConfig },
128
133
  // ── Memory ─────────────────────────────────────────────────────────────
134
+ // munin_search + munin_get are DIRECT (2026-10-08 usage re-eval): the Memory
135
+ // Protocol is injected into every configured session and its before-acting
136
+ // rule is a search — forcing a tool_search round-trip first was pure
137
+ // latency. The remaining six stay deferred: store/list/recent/delete/
138
+ // capabilities/share are needed only after search/get evidence is in hand
139
+ // (and store/delete/share stay behind plan mode's BLOCKED_TOOLS).
129
140
  { name: "munin", category: "Memory", describe: "Munin long-term memory tools (search/get/store/list/recent/delete/capabilities/share) + memory protocol. Config at project level.", load: muninModule, config: muninConfig, deferredTools: [
130
- "munin_search", "munin_get", "munin_store", "munin_list", "munin_recent", "munin_delete", "munin_capabilities", "munin_share",
141
+ "munin_store", "munin_list", "munin_recent", "munin_delete", "munin_capabilities", "munin_share",
131
142
  ] },
132
143
  // ── Tasks ──────────────────────────────────────────────────────────────
133
144
  { name: "ponytail", category: "Tasks", describe: "Lazy-senior-dev mode: prompts, skills, subagent instructions.", load: ponytailModule, config: ponytailConfig },
@@ -179,7 +190,12 @@ export const MODULES: ModuleEntry[] = [
179
190
  // gh after web: same class of external-fetch tooling; fail-open on a missing
180
191
  // gh binary (registers nothing until installed). Read-only ops only, so
181
192
  // plan mode auto-allows it (plan-tools.ts READ_ONLY_TOOLS).
182
- { name: "gh", category: "Tools", describe: "GitHub tool over the gh CLI: repo/file/PR views, PR diff, five search flavors, Actions run_watch. Read-only; mutating flows stay on bash gh.", load: ghModule, config: ghConfig, deferredTools: ["github"] },
193
+ // github is DIRECT (2026-10-08 usage re-eval): 61 calls across 17 sessions
194
+ // made it the top deferred-tool user — and every one of them happened in the
195
+ // pre-deferral direct era. After the deferred pass, release verification did
196
+ // not discover it via tool_search at all and fell back to raw bash gh,
197
+ // forfeiting the wrapper's deadline, output cap, and read-only guardrails.
198
+ { name: "gh", category: "Tools", describe: "GitHub tool over the gh CLI: repo/file/PR views, PR diff, five search flavors, Actions run_watch. Read-only; mutating flows stay on bash gh.", load: ghModule, config: ghConfig },
183
199
  // sg after gh: the same external-binary fail-open shape, for ast-grep.
184
200
  { name: "sg", category: "Tools", describe: "Structural search & rewrite via the ast-grep CLI: ast_grep search, ast_edit dry-run-default rewrites. Registers nothing until ast-grep/sg is installed.", load: sgModule, deferredTools: ["ast_grep", "ast_edit"] },
185
201
  // notify: harmless desktop ping (bell fallback), herdr multi-pane ergonomics.
@@ -198,7 +214,7 @@ export const MODULES: ModuleEntry[] = [
198
214
  // serena/web/rtk then append to. rtk (a prompt rewriter — it appends the
199
215
  // RTK note) loads BEFORE this entry; nothing after steering touches the
200
216
  // prompt — do not move rtk back after it or add a prompt rewriter here.
201
- { name: "rtk", category: "Shell", describe: "Route shell commands through RTK for token savings.", load: rtkModule },
217
+ { name: "rtk", category: "Shell", describe: "Route shell commands through RTK where RTK supports them; chains and unsupported commands pass through.", load: rtkModule, config: rtkConfig },
202
218
  { name: "steering", category: "Model", describe: "Per-model-family steering (DeepSeek/GLM): first-tool hints, reasoning strip, leak cleaning, error recovery hints, DeepSeek guidance + v4-pro minimal-mode anchor.", load: steeringModule, config: steeringConfig },
203
219
  // ── Shell ──────────────────────────────────────────────────────────────
204
220
  // Permission after rtk: persistent allow/ask/deny gating. Inert until rules
@@ -20,10 +20,10 @@
20
20
  *
21
21
  * Config: `classifier` section of ~/.pi/agent/settings.json (global only —
22
22
  * see lib/settings.ts). /config owns the rows (Model tab → Classifier).
23
- * pi-classifier's planGate is NOT ported and NOT consumed by the plan module:
24
- * pi 1.0.0's `tool_call` hook can only block, never approve, so a gate could
25
- * only have trimmed plan-mode confirm prompts (source preserved in
26
- * pi-extensions git history).
23
+ * planGate (pi-plan's reserved key) is consumed by the plan module's confirm
24
+ * tier: the gate can move a confirm-tier command to AUTO-RUN when Jev says
25
+ * it is clearly reversible and serves the task — never the reverse (write
26
+ * stays a hard block), and it ships observe-only by default.
27
27
  */
28
28
 
29
29
  import { appendFile, mkdir } from "node:fs/promises";
@@ -91,7 +91,7 @@ export function createVerdictCache(cap = 100) {
91
91
  /** Audit line per decision. Best-effort: never throws into the tool path.
92
92
  * 0600 — the log records full bash commands and task text, same
93
93
  * permission discipline as pi's settings/auth files. */
94
- function audit(entry: Record<string, unknown>): Promise<void> {
94
+ export function audit(entry: Record<string, unknown>): Promise<void> {
95
95
  try {
96
96
  const dir = process.env.PI_CODING_AGENT_DIR || join(homedir(), ".pi", "agent");
97
97
  // ponytail: async write so the tool_call hot path never blocks. Never rejects.
@@ -117,7 +117,10 @@ export function resetClassifierRefreshCooldown(): void {
117
117
  lastForcedRefresh = 0;
118
118
  }
119
119
 
120
- async function askJev(ctx: ExtensionContext, state: Record<string, unknown>, questions: Record<string, unknown>, signal?: AbortSignal): Promise<Record<string, unknown>> {
120
+ /** Ask the router's decision model (Jev). Exported for sibling modules that
121
+ * need a typed verdict (web backend routing, plan mode's confirm trim) —
122
+ * callers fail safe around its throws. */
123
+ export async function askJev(ctx: ExtensionContext, state: Record<string, unknown>, questions: Record<string, unknown>, signal?: AbortSignal): Promise<Record<string, unknown>> {
121
124
  const resolve = async () => {
122
125
  const s = getClassifierSettings();
123
126
  let model = s.model ? ctx.modelRegistry.findOfType("classifier", "router", s.model) : undefined;
@@ -154,6 +157,14 @@ async function askJev(ctx: ExtensionContext, state: Record<string, unknown>, que
154
157
  return result.answers as unknown as Record<string, unknown>;
155
158
  }
156
159
 
160
+ /** The most recent user message text (≤4000 chars) — "the current task" for
161
+ * serves_task verdicts. Exported for the plan module's planGate; the
162
+ * classifier's own message_end hook keeps it fresh. */
163
+ let lastTask = "";
164
+ export function getLastTask(): string {
165
+ return lastTask;
166
+ }
167
+
157
168
  export default function (pi: ExtensionAPI) {
158
169
  // The /config contribution reads discovered decision models at open time;
159
170
  // config factories get no ctx, so the module stashes the live registry
@@ -208,21 +219,27 @@ export default function (pi: ExtensionAPI) {
208
219
  });
209
220
 
210
221
  // ── 2. permission auto-approve hook (ported from pi-classifier) ─────────
211
- let lastTask = "";
212
222
  pi.on("message_end", (event) => {
213
223
  const msg = event.message;
214
224
  if (msg?.role !== "user") return;
215
- if (typeof msg.content === "string") lastTask = msg.content.slice(0, 4000);
216
- // Array-shaped content: join the text parts (images etc. contribute nothing).
217
- else if (Array.isArray(msg.content)) {
225
+ if (typeof msg.content === "string") {
226
+ lastTask = msg.content;
227
+ } else if (Array.isArray(msg.content)) {
228
+ // Array-shaped content: join the text parts (images etc. contribute nothing).
218
229
  lastTask = (msg.content as { type?: string; text?: unknown }[])
219
230
  .filter((p) => p?.type === "text" && typeof p.text === "string")
220
231
  .map((p) => p.text as string)
221
- .join("\n")
222
- .slice(0, 4000);
232
+ .join("\n");
233
+ } else {
234
+ lastTask = ""; // unrecognized shape — no task, never a stale one
223
235
  }
236
+ lastTask = lastTask.slice(0, 4000);
224
237
  });
225
238
 
239
+ // Per-registration reset: a second default() call (test fixtures re-run the
240
+ // factory) must not inherit the previous registration's task.
241
+ lastTask = "";
242
+
226
243
  const cache = createVerdictCache();
227
244
 
228
245
  // Failure circuit-breaker (advisor's MAX_CONSECUTIVE_FAILURES precedent):
@@ -11,8 +11,13 @@
11
11
  // }
12
12
  // }
13
13
  //
14
- // `planGate` in the file is left untouched (pi-plan's key; no consumer in
15
- // ceulen until the pi-plan port).
14
+ // `planGate` (pi-plan's key, now consumed by ceulen's plan module):
15
+ //
16
+ // "planGate": {
17
+ // "enabled": false, // allow the gate to AUTO-RUN confident safe confirm-tier commands
18
+ // "observe": false, // log-only audit pass — verdicts land in classifier.log, nothing changes
19
+ // "threshold": 0.9 // p(reversible) must clear it for an auto-run
20
+ // }
16
21
 
17
22
  import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs";
18
23
  import { homedir } from "node:os";
@@ -26,6 +31,11 @@ export interface ClassifierSettings {
26
31
  mode: "observe" | "enforce";
27
32
  threshold: number;
28
33
  };
34
+ planGate: {
35
+ enabled: boolean;
36
+ observe: boolean;
37
+ threshold: number;
38
+ };
29
39
  }
30
40
 
31
41
  function agentDir(): string {
@@ -38,7 +48,8 @@ function settingsPath(): string {
38
48
 
39
49
  /** Read the `classifier` settings. Global only — a repo file must not flip
40
50
  * verdict behavior. Defaults match pi-classifier (enabled/enforce/0.9 since
41
- * the 0.2.0 live audit). Exported for tests. */
51
+ * the 0.2.0 live audit); planGate defaults fully off (observe first, enable
52
+ * after a measured false-auto rate). Exported for tests. */
42
53
  export function getClassifierSettings(): ClassifierSettings {
43
54
  let raw: Record<string, unknown> = {};
44
55
  try {
@@ -50,6 +61,7 @@ export function getClassifierSettings(): ClassifierSettings {
50
61
  }
51
62
  const c = raw.classifier && typeof raw.classifier === "object" ? (raw.classifier as Record<string, unknown>) : {};
52
63
  const perm = c.permission && typeof c.permission === "object" ? (c.permission as Record<string, unknown>) : {};
64
+ const gate = c.planGate && typeof c.planGate === "object" ? (c.planGate as Record<string, unknown>) : {};
53
65
  return {
54
66
  model: typeof c.model === "string" ? c.model.trim() : "",
55
67
  permission: {
@@ -60,6 +72,11 @@ export function getClassifierSettings(): ClassifierSettings {
60
72
  mode: perm.mode === "observe" ? "observe" : "enforce",
61
73
  threshold: typeof perm.threshold === "number" && perm.threshold > 0 && perm.threshold < 1 ? perm.threshold : 0.9,
62
74
  },
75
+ planGate: {
76
+ enabled: gate.enabled === true,
77
+ observe: gate.observe === true,
78
+ threshold: typeof gate.threshold === "number" && gate.threshold > 0 && gate.threshold < 1 ? gate.threshold : 0.9,
79
+ },
63
80
  };
64
81
  }
65
82
 
@@ -50,18 +50,22 @@ describe("settings", () => {
50
50
  it("defaults to enabled/enforce/0.9, empty model (auto); explicit false wins", async () => {
51
51
  const { getClassifierSettings } = await import("../lib/settings.js");
52
52
  const s = getClassifierSettings();
53
- assert.deepEqual(s, { model: "", permission: { enabled: true, threshold: 0.9, mode: "enforce" } });
53
+ assert.deepEqual(s, {
54
+ model: "",
55
+ permission: { enabled: true, threshold: 0.9, mode: "enforce" },
56
+ planGate: { enabled: false, observe: false, threshold: 0.9 },
57
+ });
54
58
  writeFileSync(join(TMP_HOME, "settings.json"), JSON.stringify({ classifier: { permission: { enabled: false } } }));
55
59
  assert.equal(getClassifierSettings().permission.enabled, false);
56
60
  });
57
61
 
58
- it("reads the global classifier section; bad threshold falls back; planGate untouched", async () => {
62
+ it("reads the global classifier section; bad threshold falls back; foreign planGate keys ignored", async () => {
59
63
  const { getClassifierSettings } = await import("../lib/settings.js");
60
64
  writeFileSync(join(TMP_HOME, "settings.json"), JSON.stringify({
61
65
  classifier: {
62
66
  model: "combo/jev",
63
67
  permission: { enabled: true, mode: "enforce", threshold: 7 },
64
- planGate: { enabled: true, mode: "observe" }, // foreign key — must survive writes
68
+ planGate: { enabled: true, mode: "observe" }, // "mode" is a foreign key here — ignored, not consumed
65
69
  },
66
70
  }));
67
71
  const s = getClassifierSettings();
@@ -69,6 +73,7 @@ describe("settings", () => {
69
73
  assert.equal(s.permission.enabled, true);
70
74
  assert.equal(s.permission.mode, "enforce");
71
75
  assert.equal(s.permission.threshold, 0.9); // 7 rejected → default
76
+ assert.deepEqual(s.planGate, { enabled: true, observe: false, threshold: 0.9 }); // mode dropped, enabled read
72
77
  });
73
78
 
74
79
  it("writer merges without clobbering siblings (router, planGate) and clamps bad input", async () => {
@@ -466,6 +471,8 @@ describe("permission hook", () => {
466
471
  });
467
472
 
468
473
  it("no task captured → reversibility question only", async () => {
474
+ // Module-level lastTask (shared with the planGate consumer) persists
475
+ // across the module instance — an array with no text parts clears it.
469
476
  let questionCount = 0;
470
477
  const fx = await hookFixture(stubRegistry({
471
478
  classify: async (_m, context) => {
@@ -474,6 +481,7 @@ describe("permission hook", () => {
474
481
  },
475
482
  }));
476
483
  try {
484
+ fx.messageEnd([{ type: "image", mimeType: "image/png" }]);
477
485
  await fx.call("bun test");
478
486
  assert.equal(questionCount, 1);
479
487
  } finally { fx.cleanup(); }
@@ -504,7 +512,7 @@ describe("permission hook", () => {
504
512
  describe("config contribution", () => {
505
513
  it("builds the Model-tab groups over a working copy and routes owned keys", async () => {
506
514
  const { buildClassifierGroups, classifierConfig, setClassifierRegistry } = await import("../configPanel.js");
507
- const groups = buildClassifierGroups({ model: "", permission: { enabled: true, mode: "enforce", threshold: 0.9 } });
515
+ const groups = buildClassifierGroups({ model: "", permission: { enabled: true, mode: "enforce", threshold: 0.9 }, planGate: { enabled: false, observe: false, threshold: 0.9 } });
508
516
  assert.equal(groups[0].tab, "Model");
509
517
  assert.equal(groups[0].label, "Classifier (Jev)");
510
518
  assert.deepEqual(groups[0].rows.map((r) => r.key), [
@@ -2,8 +2,7 @@
2
2
  * Pi's built-in tools as /config toggles over the `defaultTools` setting.
3
3
  *
4
4
  * Rows live on the Tools tab ("Built-in tools" section): one toggle per
5
- * built-in tool plus the two built-in extension tools (codemode,
6
- * tool_search). The stock four (read, bash, edit, write) default on — pi
5
+ * built-in tool plus codemode (the built-in extension tool). The stock four (read, bash, edit, write) default on — pi
7
6
  * enables exactly those unless `defaultTools` changes them. A plain-list
8
7
  * write only replaces the BUILT-IN startup selection; extension tools with
9
8
  * `defaultActive: true` still self-activate, so ceulen's tools are never
@@ -65,10 +64,14 @@ export function builtinToolRows(working: Set<string>): PanelRow[] {
65
64
  );
66
65
  }
67
66
 
68
- /** The absolute defaultTools list that results from toggling `working`
69
- * (BUILTIN_TOOLS order, deterministic). Pure — exported for tests. */
67
+ /** The absolute defaultTools list that results from toggling `working` (BUILTIN_TOOLS
68
+ * order, deterministic; any non-builtin names still in `working` — e.g. seeded
69
+ * from an existing `+name`/arbitrary defaultTools entry — are appended so a
70
+ * toggle save cannot delete them). Pure — exported for tests. */
70
71
  export function nextDefaultTools(working: Set<string>): string[] {
71
- return BUILTIN_TOOLS.map(({ name }) => name).filter((n) => working.has(n));
72
+ const builtins = new Set(BUILTIN_TOOLS.map(({ name }) => name));
73
+ const others = [...working].filter((n) => !builtins.has(n));
74
+ return [...BUILTIN_TOOLS.map(({ name }) => name).filter((n) => working.has(n)), ...others];
72
75
  }
73
76
 
74
77
  /** Write the startup selection into the GLOBAL agent settings.json (the same
@@ -80,6 +80,22 @@ describe("nextDefaultTools", () => {
80
80
  const working = startupToolSet(SettingsManager.inMemory({ defaultTools: ["+codemode", "+grep"] }));
81
81
  assert.deepEqual(nextDefaultTools(working), [...STOCK, "grep", "codemode"]);
82
82
  });
83
+
84
+ it("preserves non-builtin names from the user's defaultTools through a toggle save", () => {
85
+ // A bare list may carry arbitrary names (pi accepts them) — toggling a
86
+ // builtin must not silently delete them.
87
+ const working = startupToolSet(SettingsManager.inMemory({ defaultTools: ["+codemode", "github"] }));
88
+ const rows = builtinToolRows(working);
89
+ rows.find((r) => r.key === `${DEFAULT_TOOLS_PREFIX}grep`)!.set(true);
90
+ const list = nextDefaultTools(working);
91
+ assert.ok(list.includes("github"), "arbitrary name survives");
92
+ assert.ok(list.includes("grep"), "toggled builtin included");
93
+
94
+ const file = tmpFile();
95
+ writeDefaultTools(list, file);
96
+ assert.deepEqual(readJson(file).defaultTools, list, "round-trip keeps both");
97
+ rmSync(path.dirname(file), { recursive: true, force: true });
98
+ });
83
99
  });
84
100
 
85
101
  describe("writeDefaultTools", () => {
@@ -394,6 +394,16 @@ const IMAGE_MIME: Record<string, string> = {
394
394
  png: "image/png", jpg: "image/jpeg", jpeg: "image/jpeg", gif: "image/gif", webp: "image/webp",
395
395
  };
396
396
 
397
+ /** Recognized image magic bytes — isProbablyBinary's NUL sniff is true for
398
+ * every real raster format, so the extension branch must win first (F10a). */
399
+ const IMAGE_MAGIC: Array<{ ext: string; test: (b: Buffer) => boolean }> = [
400
+ { ext: "png", test: (b) => b.subarray(0, 8).equals(Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a])) },
401
+ { ext: "jpg", test: (b) => b[0] === 0xff && b[1] === 0xd8 && b[2] === 0xff },
402
+ { ext: "jpeg", test: (b) => b[0] === 0xff && b[1] === 0xd8 && b[2] === 0xff },
403
+ { ext: "gif", test: (b) => b.subarray(0, 3).toString("latin1") === "GIF" },
404
+ { ext: "webp", test: (b) => b.subarray(0, 4).toString("latin1") === "RIFF" && b.subarray(8, 12).toString("latin1") === "WEBP" },
405
+ ];
406
+
397
407
  export async function executeFileRead(gh: GhRunner, cwd: string, params: GhParams, signal?: AbortSignal): Promise<{ text: string; image?: { data: string; mimeType: string } }> {
398
408
  const repo = await resolveGitHubRepoVia(gh, cwd, normalizeOptionalString(params.repo), undefined, signal);
399
409
  const filePath = requireNonEmpty(params.path, "path");
@@ -426,7 +436,12 @@ export async function executeFileRead(gh: GhRunner, cwd: string, params: GhParam
426
436
  const bytes = Buffer.from(encoded, "base64");
427
437
  const ext = filePath.split(".").pop()?.toLowerCase() ?? "";
428
438
  const mime = IMAGE_MIME[ext];
429
- if (mime && !isProbablyBinary(bytes)) {
439
+ // Recognized image EXTENSION wins FIRST (F10a): real PNG/JPEG/GIF/WebP all
440
+ // contain NUL bytes in the first 8KB, so the binary sniff would report
441
+ // "Cannot read binary file" for every actual image. Magic bytes gate the
442
+ // image block so a text file with an image extension still degrades to the
443
+ // binary/text paths below.
444
+ if (mime && IMAGE_MAGIC.some((m) => m.ext === ext && m.test(bytes))) {
430
445
  return { text: `Image file: ${filePath}`, image: { data: encoded, mimeType: mime } };
431
446
  }
432
447
  if (isProbablyBinary(bytes)) {
@@ -705,8 +720,8 @@ const sleep = (ms: number, signal?: AbortSignal): Promise<void> =>
705
720
 
706
721
  /**
707
722
  * Poll a workflow run until it completes; on failure tail each failed job's
708
- * logs. Watch budget comes from `timeoutMs` (the tool's overall deadline —
709
- * the caller passes gh-cli's 5-min window here).
723
+ * logs. Watch budget comes from `timeoutMs` (gh.runWatchTimeoutSecs, default
724
+ * 600s) — each gh poll stays bounded by gh-cli's own per-spawn deadline.
710
725
  */
711
726
  export async function executeRunWatch(gh: GhRunner, cwd: string, params: GhParams, signal?: AbortSignal, timeoutMs = 600_000): Promise<string> {
712
727
  const runReference = parseRunReference(params.run);
@@ -714,7 +729,10 @@ export async function executeRunWatch(gh: GhRunner, cwd: string, params: GhParam
714
729
  if (runId === undefined) throw new Error("run_watch requires `run` (workflow run ID or Actions run URL)");
715
730
  const repo = await resolveGitHubRepoVia(gh, cwd, normalizeOptionalString(params.repo), runReference.repo, signal);
716
731
  const tail = resolveTailLimit(params.tail);
717
- const deadline = Date.now() + Math.min(timeoutMs, 5 * 60_000 - 5_000);
732
+ // Honor the configured budget as-is (F10b) — the old Math.min(…, 295s) cap
733
+ // silently halved the documented 600s default. Floor 10s so a misconfigured
734
+ // 0/negative still terminates; each poll is bounded by gh-cli's GH_TIMEOUT_MS.
735
+ const deadline = Date.now() + Math.max(10_000, timeoutMs);
718
736
  const watchStartMs = Date.now();
719
737
  const intervalSeconds = () => (Date.now() - watchStartMs < RUN_WATCH_FAST_WINDOW_MS ? RUN_WATCH_INTERVAL_DEFAULT : RUN_WATCH_INTERVAL_SLOW);
720
738
 
@@ -181,15 +181,32 @@ describe("repo_view / file_read", () => {
181
181
 
182
182
  it("file_read flags binary content and returns the image block for images", async () => {
183
183
  const binary = Buffer.from([0x00, 0x01, 0x02]).toString("base64");
184
- const png = Buffer.from("89504e47", "hex").toString("base64");
184
+ // REALISTIC PNG: full signature + IHDR (contains NUL bytes in the first
185
+ // 8KB — the old 4-byte-magic fixture without NULs masked the defect where
186
+ // isProbablyBinary reported every actual image as "Cannot read binary file").
187
+ const png = Buffer.concat([
188
+ Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]), // signature
189
+ Buffer.from([0x00, 0x00, 0x00, 0x0d]), // IHDR length
190
+ Buffer.from("IHDR"),
191
+ Buffer.from([0x00, 0x00, 0x03, 0x20, 0x00, 0x00, 0x01, 0xe0, 0x08, 0x06, 0x00, 0x00, 0x00]), // w/h/depth (NULs)
192
+ Buffer.alloc(512, 0), // IDAT-ish zero-filled body
193
+ ]).toString("base64");
185
194
  const { gh } = fakeGh([
186
195
  { match: (a) => a.some((x) => String(x).includes("bin.dat")), respond: () => ({ stdout: JSON.stringify({ encoding: "base64", content: binary }) }) },
187
196
  { match: (a) => a.some((x) => String(x).includes("img.png")), respond: () => ({ stdout: JSON.stringify({ encoding: "base64", content: png }) }) },
197
+ { match: (a) => a.some((x) => String(x).includes("fake.png")), respond: () => ({ stdout: JSON.stringify({ encoding: "base64", content: Buffer.from("just text, no magic").toString("base64") }) }) },
188
198
  ]);
189
199
  const bin = await executeFileRead(gh, CWD, { repo: "acme/widget", path: "bin.dat" });
190
200
  assert.match(bin.text, /Cannot read binary file/);
201
+ // A real PNG (NUL-heavy) reaches the image block instead of the binary refusal.
191
202
  const img = await executeFileRead(gh, CWD, { repo: "acme/widget", path: "img.png" });
192
203
  assert.equal(img.image?.mimeType, "image/png");
204
+ assert.doesNotMatch(img.text, /Cannot read binary file/);
205
+ // Magic-byte gate: a TEXT file wearing .png is NOT served as an image —
206
+ // it falls through to the plain-text decode path (valid UTF-8, no magic).
207
+ const fake = await executeFileRead(gh, CWD, { repo: "acme/widget", path: "fake.png" });
208
+ assert.equal(fake.image, undefined);
209
+ assert.match(fake.text, /just text, no magic/);
193
210
  });
194
211
  });
195
212
 
@@ -247,6 +264,52 @@ describe("run_watch", () => {
247
264
  assert.match(text, /watch budget elapsed/);
248
265
  });
249
266
 
267
+ it("F10b: the budget-elapsed note fires only after the CONFIGURED window (no 295s silent cap)", { timeout: 8_000 }, async () => {
268
+ const inProgress = { id: 3, name: "CI", status: "in_progress", html_url: "https://ci/3" };
269
+ // The fake gh advances the FAKE clock by 400s while serving the poll —
270
+ // simulating a slow poll. Under the old Math.min(…, 295s) cap the budget
271
+ // was already exhausted at that point and the note fired; under the fixed
272
+ // code 400s < the configured 600s, so the loop KEEPS POLLING (proven by
273
+ // aborting during the inter-poll sleep: it rejects "Operation aborted"
274
+ // instead of returning the note).
275
+ const run = async (jumpMs: number, abortDuringSleep: boolean): Promise<string> => {
276
+ const realNow = Date.now;
277
+ let fakeNow = 1_000_000;
278
+ Date.now = () => fakeNow;
279
+ const controller = new AbortController();
280
+ const { gh } = fakeGh([
281
+ { match: (a) => a[0] === "repo" && a[1] === "view", respond: () => ({ stdout: "https://github.com/acme/widget" }) },
282
+ { match: (a) => a.some((x) => String(x).endsWith("/actions/runs/3")), respond: () => { fakeNow += jumpMs; return { stdout: JSON.stringify(inProgress) }; } },
283
+ { match: (a) => a.some((x) => String(x).includes("/actions/runs/3/jobs")), respond: () => ({ stdout: JSON.stringify({ jobs: [] }) }) },
284
+ ]);
285
+ try {
286
+ const pending = executeRunWatch(gh, CWD, { run: "3" }, controller.signal, 600_000);
287
+ if (abortDuringSleep) {
288
+ // The first poll's sleep (3s real) is pending — abort inside it.
289
+ setTimeout(() => controller.abort(), 50);
290
+ await assert.rejects(() => pending, /Operation aborted/);
291
+ return "kept-polling";
292
+ }
293
+ // No abort: let the loop reach the post-sleep budget check. Nudge the
294
+ // fake clock across the deadline while the real 3s sleep runs.
295
+ const winner = await Promise.race([
296
+ pending.then((t) => t),
297
+ new Promise<string>((resolve) => setTimeout(() => { fakeNow += 900_000; resolve("nudged"); }, 100)),
298
+ new Promise<string>((resolve) => setTimeout(() => resolve("hung"), 5_000)),
299
+ ]);
300
+ controller.abort();
301
+ return winner === "hung" ? "hung" : String(await Promise.race([pending, Promise.resolve("still-pending")]).then((t) => (typeof t === "string" && t.includes("budget")) || t === "still-pending" ? t : "other"));
302
+ } finally {
303
+ Date.now = realNow;
304
+ }
305
+ };
306
+ // 400s fake-elapsed < 600s configured → NO note (old cap: 295s → note).
307
+ assert.equal(await run(400_000, true), "kept-polling");
308
+ // Past the configured 600s → the note fires.
309
+ const late = await run(700_000, false);
310
+ assert.match(late, /watch budget elapsed/);
311
+ });
312
+
250
313
  it("classifies failed jobs and clamps tail", () => {
251
314
  assert.equal(isFailedJob({ id: 1, name: "j", conclusion: "failure" }), true);
252
315
  assert.equal(isFailedJob({ id: 1, name: "j", conclusion: "success" }), false);
@@ -2,7 +2,8 @@
2
2
  //
3
3
  // Ported from @bacnh85/pi-munin 0.5.12 extensions/index.ts (SDK vendored to
4
4
  // lib/sdk.ts; dotenv dropped — ceulen's bundle env.ts ingests trusted .env).
5
- // Registers the 8 munin_* tools (all deferred — tool_search loads them),
5
+ // Registers the 8 munin_* tools (search/get direct; the other six deferred —
6
+ // tool_search loads them),
6
7
  // /munin-status, the Munin Memory Protocol injection (only when configured),
7
8
  // the tool_result error sanitizer, and the munin skill (resources_discover).
8
9
  // Config lives at PROJECT level (.pi/settings.json `munin` section) — see
@@ -68,9 +69,8 @@ const MUNIN_PROTOCOL_HEADER = `## Munin Memory Protocol
68
69
 
69
70
  Use Munin to recover and preserve verified project knowledge, not as a task log.
70
71
  If Munin is unavailable, state that briefly when it matters and continue from
71
- repository evidence. The munin_* tools are deferred: if none are declared yet,
72
- load them with one tool_search call for "munin" (they stay declared for the
73
- rest of the session).
72
+ repository evidence. munin_search/munin_get are always declared; the other
73
+ munin_* tools load on demand with one tool_search call for "munin".
74
74
 
75
75
  ### Before acting
76
76