ceulen 0.15.2 → 0.17.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (57) hide show
  1. package/CHANGELOG.md +69 -0
  2. package/README.md +1 -1
  3. package/extensions/lib/registry.test.ts +5 -2
  4. package/extensions/lib/registry.ts +9 -3
  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 +7 -3
  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 +93 -6
  13. package/extensions/modules/munin/test/extension.test.ts +124 -0
  14. package/extensions/modules/plan/index.ts +116 -4
  15. package/extensions/modules/plan/lib/settings.ts +5 -7
  16. package/extensions/modules/plan/test/module.test.ts +104 -1
  17. package/extensions/modules/plan/test/settings.test.ts +7 -0
  18. package/extensions/modules/repair/configPanel.ts +3 -1
  19. package/extensions/modules/repair/index.ts +21 -16
  20. package/extensions/modules/repair/lib/read-sqlite.ts +18 -7
  21. package/extensions/modules/repair/test/freshness.test.ts +30 -0
  22. package/extensions/modules/repair/test/hardening.test.ts +46 -1
  23. package/extensions/modules/repair/test/readers.test.ts +11 -5
  24. package/extensions/modules/repair/test/settings.test.ts +7 -2
  25. package/extensions/modules/rtk/configPanel.ts +67 -0
  26. package/extensions/modules/rtk/index.ts +76 -9
  27. package/extensions/modules/rtk/lib/settings.ts +65 -0
  28. package/extensions/modules/rtk/test/configPanel.test.ts +72 -0
  29. package/extensions/modules/rtk/test/index.test.js +120 -2
  30. package/extensions/modules/rules/index.ts +4 -1
  31. package/extensions/modules/rules/lib/rules.ts +6 -3
  32. package/extensions/modules/rules/test/lib.test.ts +24 -0
  33. package/extensions/modules/rules/test/module.test.ts +29 -0
  34. package/extensions/modules/shells/lib/sessions.ts +40 -12
  35. package/extensions/modules/shells/test/sessions.test.ts +60 -2
  36. package/extensions/modules/steering/index.ts +12 -1
  37. package/extensions/modules/steering/test/anchor-plan.test.ts +73 -0
  38. package/extensions/modules/subagent/index.ts +19 -3
  39. package/extensions/modules/subagent/lib/herdr.ts +141 -1
  40. package/extensions/modules/subagent/lib/runner.ts +88 -22
  41. package/extensions/modules/subagent/test/herdr-stalled.test.ts +117 -0
  42. package/extensions/modules/subagent/test/worktree.test.ts +156 -1
  43. package/extensions/modules/todo/index.ts +4 -0
  44. package/extensions/modules/todo/test/todo.test.ts +9 -0
  45. package/extensions/modules/web/index.ts +1 -1
  46. package/extensions/modules/web/lib/a11y.ts +30 -15
  47. package/extensions/modules/web/lib/cdp.ts +11 -2
  48. package/extensions/modules/web/lib/chrome.ts +12 -3
  49. package/extensions/modules/web/lib/content.ts +32 -9
  50. package/extensions/modules/web/lib/search.ts +111 -3
  51. package/extensions/modules/web/test/a11y.test.ts +100 -2
  52. package/extensions/modules/web/test/cdp.test.ts +48 -0
  53. package/extensions/modules/web/test/chrome.test.ts +32 -0
  54. package/extensions/modules/web/test/content.test.ts +92 -0
  55. package/extensions/modules/web/test/search.test.ts +75 -0
  56. package/package.json +1 -1
  57. package/skills/munin/SKILL.md +1 -1
@@ -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
  });
@@ -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
- if (!rewritingEnabled()) return null;
126
- if (typeof command !== "string" || command.trim() === "") return null;
127
- if (command.trimStart().startsWith("rtk ")) return null;
128
- const rewritten = await rewriteCommand(pi, command, ctx, signal);
129
- if (rewritten && rewritten !== command && !isSafeRewrite(command, rewritten)) return null;
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\nYour bash commands are transparently rewritten through RTK for token savings. " +
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 rewritten = await maybeRewriteCommand(pi, originalCommand, ctx, ctx.signal);
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";
@@ -0,0 +1,65 @@
1
+ // rtk settings — global agent dir only (`rtk` section), read per bash call so
2
+ // a /config save applies without /reload:
3
+ //
4
+ // "rtk": {
5
+ // "mode": "supported-only" | "off", // off = kill switch (session-scoped; RTK_DISABLED=1 stays the env-level bypass)
6
+ // "chained": "never" | "only-all-modeled" // never = skip the rewrite spawn entirely for chain-bearing commands
7
+ // }
8
+ //
9
+ // No write side needs env precedence — these are switches, not secrets, and a
10
+ // repo file must not change how the model's commands execute (global only).
11
+
12
+ import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs";
13
+ import { homedir } from "node:os";
14
+ import { dirname, join } from "node:path";
15
+
16
+ export interface RtkSettings {
17
+ mode: "supported-only" | "off";
18
+ chained: "never" | "only-all-modeled";
19
+ }
20
+
21
+ function settingsPath(): string {
22
+ const dir = process.env.PI_CODING_AGENT_DIR || join(homedir(), ".pi", "agent");
23
+ return join(dir, "settings.json");
24
+ }
25
+
26
+ /** Read the `rtk` settings; unknown values fall back to the defaults
27
+ * (supported-only + only-all-modeled = rewrite single modeled commands,
28
+ * let rtk's own fail-open decide chains). Exported for tests. */
29
+ export function readRtkSettings(): RtkSettings {
30
+ let raw: Record<string, unknown> = {};
31
+ try {
32
+ if (existsSync(settingsPath())) {
33
+ raw = JSON.parse(readFileSync(settingsPath(), "utf8")) as Record<string, unknown>;
34
+ }
35
+ } catch {
36
+ raw = {}; // unreadable → defaults below
37
+ }
38
+ const c = raw.rtk && typeof raw.rtk === "object" ? (raw.rtk as Record<string, unknown>) : {};
39
+ return {
40
+ mode: c.mode === "off" ? "off" : "supported-only",
41
+ chained: c.chained === "never" ? "never" : "only-all-modeled",
42
+ };
43
+ }
44
+
45
+ /** Read-modify-write non-secret `rtk` fields into the GLOBAL settings.json
46
+ * (merge, never clobber; atomic tmp+rename; a corrupt file refuses to
47
+ * clobber). Exported for tests / the config panel. */
48
+ export function writeRtkSection(patch: { mode?: "supported-only" | "off"; chained?: "never" | "only-all-modeled" }): void {
49
+ let settings: Record<string, unknown>;
50
+ try {
51
+ settings = existsSync(settingsPath())
52
+ ? (JSON.parse(readFileSync(settingsPath(), "utf8")) as Record<string, unknown>)
53
+ : {};
54
+ } catch {
55
+ throw new Error(`${settingsPath()} is not valid JSON — fix or remove it before saving.`);
56
+ }
57
+ const c = (settings.rtk ?? {}) as Record<string, unknown>;
58
+ if (patch.mode !== undefined) c.mode = patch.mode;
59
+ if (patch.chained !== undefined) c.chained = patch.chained;
60
+ settings.rtk = c;
61
+ mkdirSync(dirname(settingsPath()), { recursive: true });
62
+ const tmp = settingsPath() + ".tmp";
63
+ writeFileSync(tmp, JSON.stringify(settings, null, 2) + "\n", { mode: 0o600 });
64
+ renameSync(tmp, settingsPath());
65
+ }
@@ -0,0 +1,72 @@
1
+ // rtk's /config contribution: row keys, closed sets, save routing (only
2
+ // rtk.* edits persist), round-trip through the working copy.
3
+ import assert from "node:assert/strict";
4
+ import { mkdtempSync, readFileSync, rmSync } from "node:fs";
5
+ import { tmpdir } from "node:os";
6
+ import { join } from "node:path";
7
+ import { after, beforeEach, describe, it } from "node:test";
8
+ import { buildRtkGroups, rtkConfig } from "../configPanel.js";
9
+ import { readRtkSettings } from "../lib/settings.js";
10
+
11
+ const realAgentDir = process.env.PI_CODING_AGENT_DIR;
12
+ let AGENT: string;
13
+
14
+ beforeEach(() => {
15
+ AGENT = mkdtempSync(join(tmpdir(), "ceulen-rtk-cfg-"));
16
+ process.env.PI_CODING_AGENT_DIR = AGENT;
17
+ });
18
+
19
+ after(() => {
20
+ if (realAgentDir === undefined) delete process.env.PI_CODING_AGENT_DIR;
21
+ else process.env.PI_CODING_AGENT_DIR = realAgentDir;
22
+ });
23
+
24
+ const fakeCtx = (notified: string[] = []): any => ({
25
+ cwd: AGENT,
26
+ ui: { notify: (message: string) => { notified.push(message); } },
27
+ });
28
+
29
+ describe("rtk config panel", () => {
30
+ it("rows: mode + chained on the Shell tab, both closed sets", () => {
31
+ const groups = buildRtkGroups(readRtkSettings());
32
+ assert.equal(groups.length, 1);
33
+ const group = groups[0];
34
+ assert.equal(group.tab, "Shell");
35
+ assert.equal(group.label, "RTK rewrite");
36
+ assert.deepEqual(group.rows.map((r) => r.key), ["rtk.mode", "rtk.chained"]);
37
+ assert.deepEqual(group.rows[0].values, ["supported-only", "off"]);
38
+ assert.deepEqual(group.rows[1].values, ["only-all-modeled", "never"]);
39
+ });
40
+
41
+ it("applyRows round-trips a working copy and save persists it", async () => {
42
+ const cfg = rtkConfig();
43
+ const groups = cfg.groups();
44
+ const modeRow = groups[0]!.rows.find((r) => r.key === "rtk.mode")!;
45
+ const chainedRow = groups[0]!.rows.find((r) => r.key === "rtk.chained")!;
46
+ modeRow.set("off");
47
+ chainedRow.set("never");
48
+ const notified: string[] = [];
49
+ await cfg.save(new Set(["rtk.mode", "rtk.chained"]), fakeCtx(notified));
50
+ const saved = readRtkSettings();
51
+ assert.equal(saved.mode, "off");
52
+ assert.equal(saved.chained, "never");
53
+ assert.ok(notified[0]!.includes("mode off"));
54
+ });
55
+
56
+ it("save no-ops without an owned edit; sibling sections survive the write", async () => {
57
+ const { writeFileSync } = await import("node:fs");
58
+ writeFileSync(join(AGENT, "settings.json"), JSON.stringify({ theme: "dark" }));
59
+ const cfg = rtkConfig();
60
+ const notified: string[] = [];
61
+ await cfg.save(new Set(["plan.autoApprove"]), fakeCtx(notified));
62
+ assert.deepEqual(readRtkSettings(), { mode: "supported-only", chained: "only-all-modeled" });
63
+
64
+ const groups = cfg.groups();
65
+ const modeRow = groups[0]!.rows.find((r) => r.key === "rtk.mode")!;
66
+ modeRow.set("off");
67
+ await cfg.save(new Set(["rtk.mode"]), fakeCtx(notified));
68
+ const raw = JSON.parse(readFileSync(join(AGENT, "settings.json"), "utf8"));
69
+ assert.equal(raw.theme, "dark", "sibling section survives");
70
+ assert.equal(raw.rtk.mode, "off");
71
+ });
72
+ });