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
@@ -52,6 +52,8 @@ import {
52
52
  type ThinkingLevel,
53
53
  } from "./lib/settings.js";
54
54
  import { getPlanRegistry, planConfig, setPlanBridge, setPlanRegistry, type PlanBridge } from "./configPanel.js";
55
+ import { askJev, audit, getLastTask, isRisky, noul, segments } from "../classifier/index.js";
56
+ import { getClassifierSettings } from "../classifier/lib/settings.js";
55
57
  // Sandbox semantics live in ONE place: the subagent module resolves agent
56
58
  // frontmatter (user + project + bundled). discoverAgents is a pure fs loader,
57
59
  // independent of whether the subagent module itself is enabled.
@@ -63,6 +65,103 @@ export const PLAN_ENTRY_TYPE = "ceulen-plan";
63
65
  export const PLAN_TOOL = "write_plan";
64
66
  export const ASK_USER_QUESTION_TOOL = "ask_user_question";
65
67
 
68
+ // ── planGate (classifier.planGate) ──────────────────────────────────────────
69
+ // The classifier can move a CONFIRM-tier bash command to auto-run when Jev
70
+ // says it clearly doesn't mutate and serves the task. It can never do the
71
+ // reverse: write stays a hard block, read stays auto. Off by default — run
72
+ // `planGate.observe` first and read the ceulen-plan-gate lines in
73
+ // classifier.log before flipping enabled.
74
+
75
+ // ponytail: value of classifier's CLASSIFIER_HOOK_BUDGET_MS — the constant is
76
+ // module-private and importing it would be module state, not a value.
77
+ const PLAN_GATE_BUDGET_MS = 2_500;
78
+
79
+ interface PlanGateVerdict {
80
+ mutates: number;
81
+ reversible: number;
82
+ serves: number;
83
+ safe: boolean;
84
+ }
85
+
86
+ /** Ask Jev about a confirm-tier command. Returns undefined on any failure —
87
+ * the confirm tier is the unchanged fallback. Exported for tests. */
88
+ export async function planGateVerdict(command: string, ctx: ExtensionContext): Promise<PlanGateVerdict | undefined> {
89
+ const task = getLastTask();
90
+ const state: Record<string, unknown> = { command, project_path: ctx.cwd, ...(task ? { task } : {}) };
91
+ const questions: Record<string, unknown> = {
92
+ mutates_filesystem: {
93
+ type: "bool",
94
+ instructions: "Does this command modify files or state outside the shell's own process?",
95
+ criteria: { yes: "Writes, deletes, moves, installs, or otherwise changes persistent state.", no: "Purely observational — reads, lists, searches, prints." },
96
+ },
97
+ reversible: {
98
+ type: "bool",
99
+ instructions: "If it DID have an effect, could that effect be undone or discarded without lasting harm?",
100
+ },
101
+ ...(task
102
+ ? {
103
+ serves_task: {
104
+ type: "bool",
105
+ instructions: "Does this command plausibly serve the task the user asked for?",
106
+ criteria: { yes: "A reasonable step toward the user's stated task.", no: "Unrelated to the task, or only a step the task never needed." },
107
+ },
108
+ }
109
+ : {}),
110
+ };
111
+ const started = Date.now();
112
+ try {
113
+ const budget = AbortSignal.timeout(PLAN_GATE_BUDGET_MS);
114
+ const answers = (await Promise.race([
115
+ askJev(ctx, state, questions, budget),
116
+ new Promise<never>((_, reject) => budget.addEventListener("abort", () => reject(new Error("plan gate budget exceeded")), { once: true })),
117
+ ])) as Record<string, unknown>;
118
+ const mutates = noul(answers, "mutates_filesystem");
119
+ const reversible = noul(answers, "reversible");
120
+ const serves = task ? noul(answers, "serves_task") : reversible; // no task → serve check degenerates
121
+ const { planGate } = getClassifierSettings();
122
+ const safe = Number.isFinite(mutates) && mutates < 0.2 && Number.isFinite(reversible) && reversible >= planGate.threshold && serves >= planGate.threshold;
123
+ await audit({
124
+ tag: "ceulen-plan-gate",
125
+ command,
126
+ mutates_filesystem: Number.isFinite(mutates) ? mutates : null,
127
+ reversible: Number.isFinite(reversible) ? reversible : null,
128
+ serves_task: Number.isFinite(serves) ? serves : null,
129
+ safe,
130
+ observe: planGate.observe,
131
+ enforcing: planGate.enabled,
132
+ ms: Date.now() - started,
133
+ });
134
+ return { mutates, reversible, serves, safe };
135
+ } catch (e) {
136
+ await audit({ tag: "ceulen-plan-gate", command, error: String(e instanceof Error ? e.message : e), ms: Date.now() - started });
137
+ return undefined;
138
+ }
139
+ }
140
+
141
+ /** Returns true when the gate auto-runs the command (only possible when
142
+ * planGate.enabled); undefined → fall through to the normal confirm tier. */
143
+ async function planGateAutoRun(command: string, ctx: ExtensionContext): Promise<boolean | undefined> {
144
+ const { planGate } = getClassifierSettings();
145
+ if (!planGate.enabled && !planGate.observe) return undefined;
146
+ // Static risk list first — credential/irreversible shapes never reach Jev
147
+ // and never leave the normal confirm tier. The whole command AND its
148
+ // segments: the pipe-to-shell regexes need the unsplit command, while
149
+ // segments expose risky commands hidden after && / ;.
150
+ if (isRisky(command) || segments(command).some(isRisky)) return undefined;
151
+ const verdict = await planGateVerdict(command, ctx);
152
+ if (verdict?.safe && planGate.enabled) {
153
+ if (ctx.hasUI) {
154
+ try {
155
+ ctx.ui.notify(`plan gate: auto-allowed (${command.slice(0, 80)})`, "info");
156
+ } catch {
157
+ /* non-tui */
158
+ }
159
+ }
160
+ return true;
161
+ }
162
+ return undefined;
163
+ }
164
+
66
165
  /** Persisted plan-mode session state (branch-scoped via appendEntry). */
67
166
  export interface PlanState {
68
167
  enabled: boolean;
@@ -492,11 +591,20 @@ export default function planModule(pi: ExtensionAPI): void {
492
591
  }
493
592
 
494
593
  /** Approve + execute in the current session. Shared by /plan-approve and
495
- * the auto-approve settle path (no command context needed). */
594
+ * the auto-approve settle path (no command context needed). A failure
595
+ * (e.g. materializePlan hitting an unwritable plans dir) must not swallow
596
+ * the approval: the ready flag is restored so /plan-approve can retry. */
496
597
  async function executeInCurrentSession(ctx: ExtensionContext): Promise<void> {
497
- await materializePlan();
498
- const relativePlan = await exitPlanForExecution(ctx);
499
- pi.sendUserMessage(buildExecutionPrompt(relativePlan, "current"), { deliverAs: "followUp" });
598
+ try {
599
+ await materializePlan();
600
+ const relativePlan = await exitPlanForExecution(ctx);
601
+ pi.sendUserMessage(buildExecutionPrompt(relativePlan, "current"), { deliverAs: "followUp" });
602
+ } catch (error) {
603
+ planReadyForReview = true;
604
+ persistState();
605
+ const reason = error instanceof Error ? error.message : String(error);
606
+ ctx.ui.notify(`Auto-approve failed: ${reason} — run /plan-approve to retry.`, "error");
607
+ }
500
608
  }
501
609
 
502
610
  /** Approve + hand the plan to a fresh session (command context only:
@@ -831,6 +939,10 @@ export default function planModule(pi: ExtensionAPI): void {
831
939
  reason: `plan mode: writing to the filesystem is not allowed while planning. "${command}" may modify files. Exit plan mode to run this command, or use ${PLAN_TOOL} to add file content to the plan.`,
832
940
  };
833
941
  }
942
+ // planGate (classifier.planGate, off by default): may AUTO-RUN a safe
943
+ // confirm-tier command. Any other answer → the confirm tier below,
944
+ // unchanged. Never reached for read (already auto) or write (hard block).
945
+ if (await planGateAutoRun(command, ctx)) return;
834
946
  if (!ctx.hasUI) return { block: true, reason: `plan mode: this command requires confirmation but UI is not available.\nCommand: ${command}` };
835
947
  const firstToken = command.trim().split(/\s+/)[0] || "bash";
836
948
  const allowKey = INTERPRETER_TOKENS.has(firstToken) ? `bash-cmd:${command.trim()}` : `bash:${firstToken}`;
@@ -148,16 +148,14 @@ export function planPath(cwd: string, title: string, plansDir: string = DEFAULT_
148
148
  return path.join(cwd, expandPlansDir(plansDir), `${stamp}-${slug}.md`);
149
149
  }
150
150
 
151
- /** True when `resolved` is a file inside the configured plans dir; `{yyyymm}`
152
- * matches any single path segment so monthly subfolders stay inside. */
151
+ /** True when `resolved` is a file inside the configured plans dir; a
152
+ * `{yyyymm}` pattern segment must match an actual 6-digit month segment
153
+ * (segment-wise — a bare wildcard splice would let ANY segment stand in). */
153
154
  export function isInsidePlansDir(resolved: string, plansDir: string, cwd: string): boolean {
154
155
  const pattern = path.resolve(cwd, plansDir).split(/[\\/]/).filter(Boolean);
155
156
  const actual = path.resolve(cwd, resolved).split(/[\\/]/).filter(Boolean);
156
- const wildcard = pattern.indexOf("{yyyymm}");
157
- const root = wildcard === -1 ? pattern : pattern.filter((seg) => seg !== "{yyyymm}");
158
- if (actual.length <= root.length) return false;
159
- if (wildcard !== -1) actual.splice(wildcard, 1);
160
- return root.every((seg, i) => actual[i] === seg);
157
+ if (actual.length <= pattern.length) return false;
158
+ return pattern.every((seg, i) => (seg === "{yyyymm}" ? /^\d{6}$/.test(actual[i] ?? "") : actual[i] === seg));
161
159
  }
162
160
 
163
161
  /** Relative path with forward slashes (prompt text). */
@@ -2,7 +2,7 @@
2
2
  // Handlers fire through the fake-pi harness (module seams, no real session).
3
3
  import assert from "node:assert/strict";
4
4
  import { readdirSync } from "node:fs";
5
- import { existsSync, mkdtempSync, readFileSync, rmSync } from "node:fs";
5
+ import { existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
6
6
  import { tmpdir } from "node:os";
7
7
  import { join } from "node:path";
8
8
  import { after, beforeEach, describe, it } from "node:test";
@@ -111,6 +111,92 @@ describe("plan mode — tool gating", () => {
111
111
  });
112
112
  });
113
113
 
114
+ describe("plan mode — classifier planGate", () => {
115
+ /** Fake model registry whose classify() answers from `answers`. */
116
+ function gateRegistry(answers: Record<string, unknown>, log: string[] = []) {
117
+ return {
118
+ findOfType: () => ({ id: "combo/jev", provider: "router" }),
119
+ getModelsOfType: () => [{ id: "combo/jev", provider: "router" }],
120
+ getAvailableOfType: async () => [{ id: "combo/jev", provider: "router" }],
121
+ refresh: async () => {},
122
+ classify: async (_model: unknown, request: { questions: Record<string, unknown> }) => {
123
+ log.push(Object.keys(request.questions).sort().join(","));
124
+ return { stopReason: "stop", answers };
125
+ },
126
+ };
127
+ }
128
+ const safeAnswers = {
129
+ mutates_filesystem: { type: "bool", probability: 0.02 },
130
+ reversible: { type: "bool", probability: 0.97 },
131
+ serves_task: { type: "bool", probability: 0.9 },
132
+ };
133
+
134
+ it("off by default: confirm tier unchanged, Jev never asked", async () => {
135
+ const h = await start();
136
+ await h.commands.plan.handler("", h.ctx({ cwd: REPO }));
137
+ const log: string[] = [];
138
+ const ctx = h.ctx({ cwd: REPO, modelRegistry: gateRegistry(safeAnswers, log), ui: { ...h.ctx().ui, select: async () => "Allow once" } });
139
+ assert.equal(await h.fire("tool_call", { toolName: "bash", input: { command: "npm test" } }, ctx), undefined);
140
+ assert.deepEqual(log, [], "gate off → no Jev ask");
141
+ });
142
+
143
+ it("observe: Jev is asked, verdict audited, confirm tier still runs", async () => {
144
+ const h = await start();
145
+ await h.commands.plan.handler("", h.ctx({ cwd: REPO }));
146
+ writeFileSync(join(agent.dir, "settings.json"), JSON.stringify({ classifier: { model: "combo/jev", planGate: { observe: true } } }));
147
+ const log: string[] = [];
148
+ const ctx = h.ctx({ cwd: REPO, modelRegistry: gateRegistry(safeAnswers, log), ui: { ...h.ctx().ui, select: async () => "Allow once" } });
149
+ assert.equal(await h.fire("tool_call", { toolName: "bash", input: { command: "npm test" } }, ctx), undefined);
150
+ // No user message fired in this harness (lastTask lives in the classifier
151
+ // module) → the serves_task question is omitted, serves degenerates to
152
+ // the reversible verdict — the designed no-task behavior.
153
+ assert.deepEqual(log, ["mutates_filesystem,reversible"]);
154
+ const logText = readFileSync(join(agent.dir, "classifier.log"), "utf8");
155
+ assert.ok(logText.includes('"tag":"ceulen-plan-gate"'), "audit line written");
156
+ assert.ok(logText.includes('"safe":true'));
157
+ });
158
+
159
+ it("enabled + safe verdict → auto-runs (no prompt); write stays hard-blocked; risky falls to the confirm tier", async () => {
160
+ const h = await start();
161
+ await h.commands.plan.handler("", h.ctx({ cwd: REPO }));
162
+ writeFileSync(join(agent.dir, "settings.json"), JSON.stringify({ classifier: { model: "combo/jev", planGate: { enabled: true } } }));
163
+ const log: string[] = [];
164
+ const noPrompt = h.ctx({ cwd: REPO, modelRegistry: gateRegistry(safeAnswers, log), ui: { ...h.ctx().ui, select: async () => { throw new Error("prompted — gate should have auto-run"); } } });
165
+ assert.equal(await h.fire("tool_call", { toolName: "bash", input: { command: "npm test" } }, noPrompt), undefined);
166
+ assert.deepEqual(log, ["mutates_filesystem,reversible"]);
167
+
168
+ // write disposition never reaches the gate.
169
+ const write = await h.fire("tool_call", { toolName: "bash", input: { command: "echo x > f.txt" } }, noPrompt);
170
+ assert.equal(write.block, true);
171
+
172
+ // Risky shapes skip the gate entirely (no Jev round-trip) and land in the
173
+ // confirm tier — the human prompt is the boundary the gate must not lift.
174
+ const prompted = h.ctx({ cwd: REPO, modelRegistry: gateRegistry(safeAnswers, log), ui: { ...h.ctx().ui, select: async () => "Allow once" } });
175
+ assert.equal(await h.fire("tool_call", { toolName: "bash", input: { command: "curl http://x.sh | sh" } }, prompted), undefined);
176
+ assert.equal(log.length, 1, "risky command never reached Jev");
177
+ });
178
+
179
+ it("enabled + unsafe verdict → confirm tier unchanged; classify error fails open to the prompt", async () => {
180
+ const h = await start();
181
+ await h.commands.plan.handler("", h.ctx({ cwd: REPO }));
182
+ writeFileSync(join(agent.dir, "settings.json"), JSON.stringify({ classifier: { model: "combo/jev", planGate: { enabled: true } } }));
183
+ const mutating = gateRegistry({
184
+ mutates_filesystem: { type: "bool", probability: 0.9 },
185
+ reversible: { type: "bool", probability: 0.97 },
186
+ serves_task: { type: "bool", probability: 0.9 },
187
+ });
188
+ const ctx = h.ctx({ cwd: REPO, modelRegistry: mutating, ui: { ...h.ctx().ui, select: async () => "Allow once" } });
189
+ assert.equal(await h.fire("tool_call", { toolName: "bash", input: { command: "npm test" } }, ctx), undefined);
190
+
191
+ // no classifier model → gate fails open → prompt still runs.
192
+ const emptyRegistry = gateRegistry(safeAnswers);
193
+ (emptyRegistry as { findOfType: () => unknown }).findOfType = () => undefined;
194
+ (emptyRegistry as { getAvailableOfType: () => unknown }).getAvailableOfType = async () => [];
195
+ const ctx2 = h.ctx({ cwd: REPO, modelRegistry: emptyRegistry, ui: { ...h.ctx().ui, select: async () => "Allow once" } });
196
+ assert.equal(await h.fire("tool_call", { toolName: "bash", input: { command: "bun run build" } }, ctx2), undefined);
197
+ });
198
+ });
199
+
114
200
  describe("plan mode — write_plan", () => {
115
201
  it("writes to .pi/plans by default and reports the path", async () => {
116
202
  const h = await start();
@@ -200,6 +286,23 @@ describe("plan mode — prompt + approval flow", () => {
200
286
  assert.match(h.userMessages[0].content, /Execute the approved plan/);
201
287
  });
202
288
 
289
+ it("auto-approve materialize failure notifies and restores the plan for retry", async () => {
290
+ setPlanSettings(agent.dir, { autoApprove: true, savePlans: "approved" });
291
+ const h = await start();
292
+ await h.commands.plan.handler("", h.ctx({ cwd: REPO }));
293
+ await h.tools.write_plan.execute("tc1", { title: "T", content: "body" }, undefined, undefined, h.ctx({ cwd: REPO }));
294
+ // plans dir unwritable: <REPO>/.pi is a FILE → the approval-time write throws.
295
+ writeFileSync(join(REPO, ".pi"), "not a dir");
296
+ await h.fire("agent_settled", {}, h.ctx({ cwd: REPO })); // must not reject
297
+ assert.equal(h.userMessages.length, 0, "no execution turn on failure");
298
+ assert.ok(h.notifications.some((n) => n.includes("Auto-approve failed") && n.includes("/plan-approve to retry")));
299
+ // Condition fixed → a later settle still executes the still-ready plan.
300
+ rmSync(join(REPO, ".pi"));
301
+ await h.fire("agent_settled", {}, h.ctx({ cwd: REPO }));
302
+ assert.equal(h.userMessages.length, 1);
303
+ assert.match(h.userMessages[0].content, /Execute the approved plan/);
304
+ });
305
+
203
306
  it("auto-approve never fires off an aborted settle; the plan still approves on a clean one", async () => {
204
307
  setPlanSettings(agent.dir, { autoApprove: true });
205
308
  const h = await start();
@@ -104,6 +104,13 @@ describe("plan settings", () => {
104
104
  assert.equal(isInsidePlansDir(join(REPO, ".pi/plans"), ".pi/plans/{yyyymm}", REPO), false, "the dir itself is not inside");
105
105
  });
106
106
 
107
+ it("{yyyymm} matches only a real 6-digit month segment (segment-wise, no splice)", () => {
108
+ assert.equal(isInsidePlansDir(join(REPO, ".pi/evil/plans/x.md"), ".pi/{yyyymm}/plans", REPO), false, "an any-segment wildcard must not match");
109
+ assert.equal(isInsidePlansDir(join(REPO, ".pi/202610/plans/x.md"), ".pi/{yyyymm}/plans", REPO), true);
110
+ assert.equal(isInsidePlansDir(join(REPO, ".pi/20261/plans/x.md"), ".pi/{yyyymm}/plans", REPO), false, "5 digits is not a month");
111
+ assert.equal(isInsidePlansDir(join(REPO, ".pi/plans/x.md"), ".pi/plans/{yyyymm}", REPO), false, "the month segment is required");
112
+ });
113
+
107
114
  it("isSavePlans accepts only the closed set", () => {
108
115
  assert.equal(isSavePlans("all"), true);
109
116
  assert.equal(isSavePlans("approved"), true);
@@ -64,7 +64,9 @@ export function buildRepairGroups(cfg: RepairSettings): PanelGroup[] {
64
64
  warning: "Bash description + auto-background mechanism bind at session start — applies to the next session.",
65
65
  }),
66
66
  row("repair.autoBgSecs", "Auto-background after", "number", cfg.autoBgSecs, (v) => {
67
- cfg.autoBgSecs = Math.max(1, Math.floor(Number(v)));
67
+ // Mirror the cron guard: non-numeric input must not persist NaN→null.
68
+ const n = Math.floor(Number(v));
69
+ if (Number.isFinite(n) && n > 0) cfg.autoBgSecs = n;
68
70
  }, {
69
71
  defaultValue: DEFAULT_REPAIR_SETTINGS.autoBgSecs,
70
72
  description: "Seconds a foreground bash call may run before it is auto-backgrounded.",
@@ -112,11 +112,12 @@ function applyReadSelector(args: Record<string, unknown>, cwd: string): unknown
112
112
  // ── sqlite / archive views (OMP read-sqlite + read-archive) ──
113
113
 
114
114
  /** Peel `db.sqlite:users` / `pkg.tgz:src/x.ts:50-80` for sqlite/archive
115
- * views. Returns the model-facing text result, or null when the path is
116
- * neither (caller falls through to the built-in read). The stem must exist
117
- * (the caller probes the literal path first — literal-wins preserved).
118
- * Exported for tests. */
119
- export function applySpecialView(rawPath: string, cwd: string): { text: string } | null {
115
+ * views. Returns the model-facing text result plus the RESOLVED STEM (so the
116
+ * caller records the freshness baseline against the stem, not the raw
117
+ * selector path), or null when the path is neither (caller falls through to
118
+ * the built-in read). The stem must exist (the caller probes the literal path
119
+ * first — literal-wins preserved). Exported for tests. */
120
+ export function applySpecialView(rawPath: string, cwd: string): { text: string; stem: string } | null {
120
121
  // Special-view peel: the LONGEST existing prefix path split at colons is
121
122
  // the stem; the remainder is the sqlite sub-selector or archive member
122
123
  // (+ optional line ranges). peelPathSelector can't do this — its grammar
@@ -139,7 +140,7 @@ export function applySpecialView(rawPath: string, cwd: string): { text: string }
139
140
  if (isSqliteFile(stemAbs)) {
140
141
  try {
141
142
  // The sqlite sub-selector spans ALL segments (users:2 is table+rowid).
142
- return { text: readSqlite(stemAbs, remainder, stem) };
143
+ return { text: readSqlite(stemAbs, remainder, stem), stem };
143
144
  } catch (err) {
144
145
  throw new Error(err instanceof Error ? err.message : String(err));
145
146
  }
@@ -147,7 +148,7 @@ export function applySpecialView(rawPath: string, cwd: string): { text: string }
147
148
 
148
149
  const kind = archiveKind(stem);
149
150
  if (kind) {
150
- if (!remainder) return { text: readArchiveListing(stemAbs, kind, stem).text };
151
+ if (!remainder) return { text: readArchiveListing(stemAbs, kind, stem).text, stem };
151
152
  // Peel the trailing lines-selector FIRST (`src/x.ts:50-80`): the member
152
153
  // lookup must see `src/x.ts`, not the raw remainder with the `:50-80`
153
154
  // suffix (which matchMember reports as "no member matching").
@@ -168,9 +169,9 @@ export function applySpecialView(rawPath: string, cwd: string): { text: string }
168
169
  ? resolveTailSelector(selector, lines.length - 1)
169
170
  : selector;
170
171
  const sliced = sliceMemberLines(lines, resolved);
171
- if (sliced !== null) return { text: sliced };
172
+ if (sliced !== null) return { text: sliced, stem };
172
173
  }
173
- return { text: res.text };
174
+ return { text: res.text, stem };
174
175
  }
175
176
  return null;
176
177
  }
@@ -312,9 +313,13 @@ async function recordMutatedMtimes(toolName: string, params: any, cwd: string):
312
313
  * so the auto-gen guard + mtime refresh must too). */
313
314
  function parsePatchTargetPaths(patch: string): string[] {
314
315
  const out: string[] = [];
315
- for (const m of patch.matchAll(/^\*{3} (?:Add|Delete|Update) File: (.+?)(?:\s*(?:→|->)\s*.+)?$/gm)) {
316
- const target = m[1].trim();
317
- if (target && !target.includes("://")) out.push(target);
316
+ for (const m of patch.matchAll(/^\*{3} (?:Add|Delete|Update) File: (.+?)(?:\s*(?:→|->)\s*(.+))?$/gm)) {
317
+ // A rename touches BOTH paths — the destination too (a `→ dist/out.min.js`
318
+ // target used to bypass the auto-gen guard because the regex dropped it).
319
+ for (const target of [m[1], m[2]]) {
320
+ const p = target?.trim();
321
+ if (p && !p.includes("://")) out.push(p);
322
+ }
318
323
  }
319
324
  return out;
320
325
  }
@@ -483,7 +488,7 @@ export function wrapToolDefinition(
483
488
  if (base.name === "read" && isRecord(params) && typeof params.path === "string" && !selector) {
484
489
  const rawPath: string = params.path;
485
490
  const rawAbs = resolvePath(cwd, rawPath);
486
- let view: { text: string } | null = null;
491
+ let view: { text: string; stem?: string } | null = null;
487
492
  if (existsSync(rawAbs) && isSqliteFile(rawAbs)) {
488
493
  try {
489
494
  view = { text: readSqlite(rawAbs, undefined, rawPath) };
@@ -496,9 +501,9 @@ export function wrapToolDefinition(
496
501
  view = applySpecialView(rawPath, cwd);
497
502
  }
498
503
  if (view) {
499
- // Record the freshness baseline for the STEM so a follow-up write
500
- // to the extracted file is judged normally (members have none).
501
- await recordReadMtimes({ path: rawPath }, cwd);
504
+ // Record the freshness baseline for the STEM (the raw selector path
505
+ // itself doesn't exist on disk — recording it records nothing).
506
+ await recordReadMtimes({ path: view.stem ?? rawPath }, cwd);
502
507
  return { content: [{ type: "text", text: view.text }], details: undefined };
503
508
  }
504
509
  }
@@ -168,13 +168,24 @@ export function executeSqliteView(db: DatabaseSync, sel: SqliteSelector, display
168
168
  if (!/^(SELECT|WITH|PRAGMA)/.test(head)) {
169
169
  throw new Error(`only read-only queries (SELECT/WITH/PRAGMA) — got "${sel.sql.slice(0, 40)}". Use bash for writes.`);
170
170
  }
171
- const stmt = db.prepare(sel.sql);
172
- const columns = (stmt as unknown as { columns: () => Array<{ name: string }> }).columns().map((c) => c.name);
173
- const rows = stmt.all() as Array<Record<string, unknown>>;
174
- const total = rows.length;
175
- const shown = rows.slice(0, MAX_RAW_QUERY_ROWS);
176
- const footer = total > shown.length ? `\n[showing ${shown.length} of ${total} rows — add LIMIT/TARGET the query]` : "";
177
- return `${displayPath} : query — ${total} row(s)\n${shown.length ? renderRows(columns, shown) : "(no rows)"}${footer}`;
171
+ // Bounded iteration (F8): never materialize more than cap+1 rows.
172
+ // Column names come from the first row (F2) — stmt.columns() is
173
+ // Node >=23.11 and TypeErrors on the 22.x engines floor.
174
+ const collected: Record<string, unknown>[] = [];
175
+ let overflow = false;
176
+ for (const row of db.prepare(sel.sql).iterate()) {
177
+ if (collected.length >= MAX_RAW_QUERY_ROWS) {
178
+ overflow = true;
179
+ break;
180
+ }
181
+ collected.push(row as Record<string, unknown>);
182
+ }
183
+ const columns = collected.length ? Object.keys(collected[0]!) : [];
184
+ const footer = overflow
185
+ ? `\n[showing ${collected.length} of ${collected.length}+ rows — add LIMIT to narrow the query]`
186
+ : "";
187
+ const total = overflow ? `${collected.length}+` : String(collected.length);
188
+ return `${displayPath} : query — ${total} row(s)\n${collected.length ? renderRows(columns, collected) : "(no rows)"}${footer}`;
178
189
  }
179
190
  }
180
191
  }
@@ -143,6 +143,36 @@ describe("write freshness guard", () => {
143
143
  assert.match(await readFile(file, "utf8"), /FOREIGN/);
144
144
  });
145
145
 
146
+ it("a special-view read records the STEM's baseline (db.sqlite:users arms the guard)", async () => {
147
+ // F6: the raw selector path (db.sqlite:users) was recorded instead of the
148
+ // stem — no mtime ever landed, so a foreign write to the db after the read
149
+ // was invisible to the freshness guard.
150
+ const { DatabaseSync } = await import("node:sqlite");
151
+ const dir = await tempDir();
152
+ const dbFile = join(dir, "db.sqlite");
153
+ const db = new DatabaseSync(dbFile);
154
+ db.exec("CREATE TABLE users (id INTEGER PRIMARY KEY, name TEXT)");
155
+ db.exec("INSERT INTO users (name) VALUES ('alice')");
156
+ db.close();
157
+
158
+ const read = makeWrapped("read", dir);
159
+ const result = await exec(read, { path: "db.sqlite:users" }, dir);
160
+ assert.match(String(result.content[0].text), /alice/, "special view served");
161
+
162
+ // Foreign write (fresh mtime) after our read → a full-file write must
163
+ // now be refused, proving the STEM mtime is recorded.
164
+ const db2 = new DatabaseSync(dbFile);
165
+ db2.exec("INSERT INTO users (name) VALUES ('bob')");
166
+ db2.close();
167
+ const future = new Date(Date.now() + 1100);
168
+ await utimes(dbFile, future, future);
169
+
170
+ const write = makeWrapped("write", dir);
171
+ const fresh = await exec(write, { path: "db.sqlite", content: "clobber" }, dir);
172
+ assert.equal(fresh.isError, true, "checkWriteFresh sees the recorded stem mtime");
173
+ assert.match(fresh.content[0].text, /Re-read the file/);
174
+ });
175
+
146
176
  it("write after a wrapped EDIT does not false-positive (edit refreshes the baseline)", async () => {
147
177
  // Live-found defect (reviewer 2026-10-06): a successful edit never
148
178
  // refreshed the freshness baseline, so read → edit → write compared the
@@ -7,7 +7,7 @@
7
7
  import assert from "node:assert/strict";
8
8
  import { execFileSync } from "node:child_process";
9
9
  import { mkdtempSync, mkdirSync, writeFileSync, rmSync } from "node:fs";
10
- import { mkdtemp, rm, writeFile } from "node:fs/promises";
10
+ import { mkdtemp, mkdir, rm, writeFile } from "node:fs/promises";
11
11
  import { tmpdir } from "node:os";
12
12
  import path from "node:path";
13
13
  import { after, before, describe, it } from "node:test";
@@ -211,4 +211,49 @@ describe("patch rename arrows (A9)", () => {
211
211
  await rm(proj, { recursive: true, force: true });
212
212
  }
213
213
  });
214
+
215
+ it("a rename INTO a guarded destination is refused even when the source is clean", async () => {
216
+ // F4: the arrow used to drop the destination, so `src/a.ts → dist/out.min.js`
217
+ // bypassed the auto-gen guard. Both arrows must now refuse on the DEST too.
218
+ const { default: repairModule } = await import("../index.js");
219
+ const proj = await mkdtemp(path.join(tmpdir(), "repair-arrow-dest-"));
220
+ const orig = process.env.PI_CODING_AGENT_DIR;
221
+ process.env.PI_CODING_AGENT_DIR = proj;
222
+ const tools: any[] = [];
223
+ try {
224
+ repairModule({
225
+ on: () => {},
226
+ registerTool: (def: any) => tools.push(def),
227
+ registerCommand: () => {},
228
+ } as never);
229
+ const applyPatch = tools.find((t) => t.name === "apply_patch");
230
+ assert.ok(applyPatch, "apply_patch registered");
231
+ await mkdir(path.join(proj, "src"), { recursive: true });
232
+ await writeFile(path.join(proj, "src.ts"), "x\n");
233
+ for (const arrow of ["→", "->"]) {
234
+ const res = await applyPatch.execute(
235
+ "t1",
236
+ { patch: `*** Begin Patch\n*** Update File: src.ts ${arrow} dist/out.min.js\n@@ x\n-y\n+z\n*** End Patch` },
237
+ undefined,
238
+ undefined,
239
+ { cwd: proj },
240
+ );
241
+ assert.equal(res.isError, true, `rename into a guarded dest refused (${arrow})`);
242
+ assert.match(res.content[0].text, /out\.min\.js/);
243
+ }
244
+ // Non-rename to a clean path is still allowed (guard untouched).
245
+ const ok = await applyPatch.execute(
246
+ "t1",
247
+ { patch: "*** Add File: src/new.ts\n+hi\n*** End Patch" },
248
+ undefined,
249
+ undefined,
250
+ { cwd: proj },
251
+ );
252
+ assert.equal(ok.isError, undefined);
253
+ } finally {
254
+ if (orig === undefined) delete process.env.PI_CODING_AGENT_DIR;
255
+ else process.env.PI_CODING_AGENT_DIR = orig;
256
+ await rm(proj, { recursive: true, force: true });
257
+ }
258
+ });
214
259
  });
@@ -139,16 +139,22 @@ describe("sqlite views", () => {
139
139
  }, /readonly|read-only/i);
140
140
  });
141
141
 
142
- it("raw queries cap at MAX_RAW_QUERY_ROWS", () => {
142
+ it("raw queries cap at MAX_RAW_QUERY_ROWS without materializing the rest", () => {
143
143
  const big = path.join(dir, "big.db");
144
144
  const db = new DatabaseSync(big);
145
145
  db.exec("CREATE TABLE t (n INTEGER)");
146
- db.exec(`WITH RECURSIVE c(x) AS (SELECT 1 UNION ALL SELECT x+1 FROM c WHERE x < ${MAX_RAW_QUERY_ROWS + 50}) INSERT INTO t SELECT x FROM c`);
146
+ db.exec(`WITH RECURSIVE c(x) AS (SELECT 1 UNION ALL SELECT x+1 FROM c WHERE x < ${MAX_RAW_QUERY_ROWS * 10}) INSERT INTO t SELECT x FROM c`);
147
147
  db.close();
148
148
  const out = readSqlite(big, "?SELECT * FROM t", "big.db");
149
- assert.match(out, /showing \d+ of \d+ rows/);
150
- const total = Number(/of (\d+) rows/.exec(out)![1]);
151
- assert.equal(total, MAX_RAW_QUERY_ROWS + 50);
149
+ assert.match(out, /showing 200 of 200\+ rows/);
150
+ assert.match(out, /— 200\+ row\(s\)/);
151
+ assert.match(out, /add LIMIT/);
152
+ });
153
+
154
+ it("a query returning zero rows renders (no rows) — no stmt.columns() call", () => {
155
+ const out = readSqlite(dbFile, "?SELECT * FROM users WHERE age > 999", "f.db");
156
+ assert.match(out, /\(no rows\)/);
157
+ assert.match(out, /— 0 row\(s\)/);
152
158
  });
153
159
  });
154
160
 
@@ -174,7 +174,8 @@ describe("tool_call honors the trusted-project layer (A5 e2e)", () => {
174
174
 
175
175
  describe("buildRepairGroups (panel contract)", () => {
176
176
  it("renders the six repair.* rows on the Tools tab with the documented defaults", () => {
177
- const groups = buildRepairGroups({ ...DEFAULT_REPAIR_SETTINGS });
177
+ const cfg: RepairSettings = { ...DEFAULT_REPAIR_SETTINGS };
178
+ const groups = buildRepairGroups(cfg);
178
179
  assert.equal(groups.length, 1);
179
180
  assert.equal(groups[0].tab, "Tools");
180
181
  assert.equal(groups[0].label, "Repair");
@@ -199,9 +200,13 @@ describe("buildRepairGroups (panel contract)", () => {
199
200
  assert.equal(byKey.get("repair.guards")!.value, false);
200
201
  // The row's setter clamps into the working config (the panel kernel keeps
201
202
  // the raw value on the row — same contract as every ceulen number row).
202
- const cfg: RepairSettings = { ...DEFAULT_REPAIR_SETTINGS };
203
203
  byKey.get("repair.autoBgSecs")!.set(45.8);
204
204
  cfg.autoBgSecs = Math.max(1, Math.floor(Number(45.8)));
205
205
  assert.equal(Math.floor(Number(byKey.get("repair.autoBgSecs")!.value)), 45);
206
+
207
+ // F7: non-numeric input must not persist NaN→null — the working value is
208
+ // untouched, so the save diff produces no autoBgSecs entry.
209
+ byKey.get("repair.autoBgSecs")!.set("abc" as never);
210
+ assert.equal(cfg.autoBgSecs, 45, "set('abc') leaves the working value unchanged");
206
211
  });
207
212
  });