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.
- package/CHANGELOG.md +62 -0
- package/README.md +2 -2
- package/extensions/lib/registry.test.ts +12 -0
- package/extensions/lib/registry.ts +20 -4
- 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 +8 -5
- 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/munin/index.ts +4 -4
- 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
|
@@ -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";
|
|
@@ -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
|
+
});
|
|
@@ -1,5 +1,8 @@
|
|
|
1
1
|
import assert from "node:assert/strict";
|
|
2
2
|
import test from "node:test";
|
|
3
|
+
import { mkdtempSync, rmSync } from "node:fs";
|
|
4
|
+
import { tmpdir } from "node:os";
|
|
5
|
+
import { join } from "node:path";
|
|
3
6
|
|
|
4
7
|
// Orchestration tests for index.ts: availability gating, env bypass, and the
|
|
5
8
|
// safe-rewrite decision on the tool_call path, via a stubbed pi + ctx.
|
|
@@ -7,6 +10,18 @@ import test from "node:test";
|
|
|
7
10
|
// tests in this file — tests are ordered to lean on it, and session_start
|
|
8
11
|
// (which re-checks unconditionally) re-establishes availability where needed.
|
|
9
12
|
|
|
13
|
+
// Isolate the agent dir for the WHOLE file: readRtkSettings reads the global
|
|
14
|
+
// `rtk` section per bash call, and a host settings.json with `chained: "never"`
|
|
15
|
+
// would silently disable every chain rewrite under test.
|
|
16
|
+
const HOST_AGENT_DIR = process.env.PI_CODING_AGENT_DIR;
|
|
17
|
+
const TEMP_AGENT_DIR = mkdtempSync(join(tmpdir(), "ceulen-rtk-index-"));
|
|
18
|
+
process.env.PI_CODING_AGENT_DIR = TEMP_AGENT_DIR;
|
|
19
|
+
test.after(() => {
|
|
20
|
+
if (HOST_AGENT_DIR === undefined) delete process.env.PI_CODING_AGENT_DIR;
|
|
21
|
+
else process.env.PI_CODING_AGENT_DIR = HOST_AGENT_DIR;
|
|
22
|
+
rmSync(TEMP_AGENT_DIR, { recursive: true, force: true });
|
|
23
|
+
});
|
|
24
|
+
|
|
10
25
|
function createHarness() {
|
|
11
26
|
const state = { versionCalls: 0, rewriteCalls: 0, rewritten: null, versionAvailable: false };
|
|
12
27
|
const handlers = {};
|
|
@@ -121,11 +136,114 @@ test("before_agent_start: prompt note injected only when rtk is available", asyn
|
|
|
121
136
|
const resOff = await off.handlers.before_agent_start({ systemPrompt: "BASE" });
|
|
122
137
|
assert.equal(resOff, undefined, "no systemPrompt modification when unavailable");
|
|
123
138
|
|
|
124
|
-
// Available → the note is appended truthfully.
|
|
139
|
+
// Available → the static note is appended truthfully.
|
|
125
140
|
const on = createHarness();
|
|
126
141
|
on.state.versionAvailable = true;
|
|
127
142
|
ext(on.pi);
|
|
128
143
|
await on.handlers.session_start({}, on.ctx);
|
|
129
144
|
const resOn = await on.handlers.before_agent_start({ systemPrompt: "BASE" });
|
|
130
|
-
assert.match(resOn.systemPrompt, /
|
|
145
|
+
assert.match(resOn.systemPrompt, /rewritten through RTK where RTK supports them/);
|
|
146
|
+
assert.match(resOn.systemPrompt, /chains, redirects, inline scripts, and unsupported commands pass through unchanged/);
|
|
147
|
+
|
|
148
|
+
// Static-policy note: byte-identical across two firings (prefix-cache head).
|
|
149
|
+
const resOn2 = await on.handlers.before_agent_start({ systemPrompt: "BASE" });
|
|
150
|
+
assert.equal(resOn2.systemPrompt, resOn.systemPrompt);
|
|
151
|
+
assert.equal(
|
|
152
|
+
resOn.systemPrompt.slice("BASE".length),
|
|
153
|
+
"\n\nYour bash commands are rewritten through RTK where RTK supports them (git, ls, rg, read, test runners as single commands); chains, redirects, inline scripts, and unsupported commands pass through unchanged.",
|
|
154
|
+
);
|
|
155
|
+
});
|
|
156
|
+
|
|
157
|
+
test("chain pass-through fires the [pi-rtk] notify once for two consecutive identical chains", async () => {
|
|
158
|
+
const notifications = [];
|
|
159
|
+
const h = createHarness();
|
|
160
|
+
h.state.versionAvailable = true;
|
|
161
|
+
h.state.rewritten = ""; // rtk consulted, returns empty = unmodeled → pass-through
|
|
162
|
+
h.ctx.hasUI = true;
|
|
163
|
+
h.ctx.ui.notify = (message) => notifications.push(message);
|
|
164
|
+
const ext = (await import("../index.ts")).default;
|
|
165
|
+
ext(h.pi);
|
|
166
|
+
|
|
167
|
+
await h.handlers.session_start({}, h.ctx);
|
|
168
|
+
const chain = "npm test 2>&1 | tail -8";
|
|
169
|
+
const afterFirst = await fireToolCall(h, chain);
|
|
170
|
+
assert.equal(afterFirst, chain, "unmodeled chain executes unchanged");
|
|
171
|
+
const afterSecond = await fireToolCall(h, chain);
|
|
172
|
+
assert.equal(afterSecond, chain);
|
|
173
|
+
const passNotes = notifications.filter((n) => n.startsWith("[pi-rtk] passed through unchanged:"));
|
|
174
|
+
assert.equal(passNotes.length, 1, `dedupe: one notify for two identical chains, got ${passNotes.length}`);
|
|
175
|
+
|
|
176
|
+
// A different chain notifies again.
|
|
177
|
+
await fireToolCall(h, "npx tsc --noEmit 2>&1 | head -20");
|
|
178
|
+
assert.equal(notifications.filter((n) => n.startsWith("[pi-rtk] passed through unchanged:")).length, 2);
|
|
179
|
+
|
|
180
|
+
// session_start resets the dedupe.
|
|
181
|
+
await h.handlers.session_start({}, h.ctx);
|
|
182
|
+
await fireToolCall(h, chain);
|
|
183
|
+
assert.equal(notifications.filter((n) => n.startsWith("[pi-rtk] passed through unchanged:")).length, 3);
|
|
184
|
+
});
|
|
185
|
+
|
|
186
|
+
test("pass-through notify does not fire when rtk was not consulted", async () => {
|
|
187
|
+
const notifications = [];
|
|
188
|
+
const h = createHarness();
|
|
189
|
+
h.state.versionAvailable = true;
|
|
190
|
+
h.ctx.hasUI = true;
|
|
191
|
+
h.ctx.ui.notify = (message) => notifications.push(message);
|
|
192
|
+
const ext = (await import("../index.ts")).default;
|
|
193
|
+
ext(h.pi);
|
|
194
|
+
|
|
195
|
+
await h.handlers.session_start({}, h.ctx);
|
|
196
|
+
process.env.RTK_DISABLED = "1";
|
|
197
|
+
try {
|
|
198
|
+
await fireToolCall(h, "npm test 2>&1 | tail -8");
|
|
199
|
+
assert.equal(notifications.filter((n) => n.includes("passed through")).length, 0, "env bypass = not consulted");
|
|
200
|
+
} finally {
|
|
201
|
+
delete process.env.RTK_DISABLED;
|
|
202
|
+
}
|
|
203
|
+
// hasUI=false suppresses notifies entirely.
|
|
204
|
+
h.ctx.hasUI = false;
|
|
205
|
+
await fireToolCall(h, "npm test 2>&1 | tail -8");
|
|
206
|
+
assert.equal(notifications.filter((n) => n.includes("passed through")).length, 0);
|
|
207
|
+
});
|
|
208
|
+
|
|
209
|
+
test("rtk settings: mode off is a kill switch; chained never skips the spawn", async () => {
|
|
210
|
+
// Isolate the agent dir so read/writeRtkSettings never touch the real file.
|
|
211
|
+
const { mkdtempSync, rmSync } = await import("node:fs");
|
|
212
|
+
const { tmpdir } = await import("node:os");
|
|
213
|
+
const { join } = await import("node:path");
|
|
214
|
+
const dir = mkdtempSync(join(tmpdir(), "ceulen-rtk-test-"));
|
|
215
|
+
const realAgentDir = process.env.PI_CODING_AGENT_DIR;
|
|
216
|
+
process.env.PI_CODING_AGENT_DIR = dir;
|
|
217
|
+
try {
|
|
218
|
+
const { writeRtkSection } = await import("../lib/settings.ts");
|
|
219
|
+
|
|
220
|
+
const h = createHarness();
|
|
221
|
+
h.state.versionAvailable = true;
|
|
222
|
+
h.state.rewritten = "rtk git status";
|
|
223
|
+
const ext = (await import("../index.ts")).default;
|
|
224
|
+
ext(h.pi);
|
|
225
|
+
await h.handlers.session_start({}, h.ctx);
|
|
226
|
+
|
|
227
|
+
// mode: off → no rewrite, no spawn.
|
|
228
|
+
writeRtkSection({ mode: "off" });
|
|
229
|
+
assert.equal(await fireToolCall(h, "git status"), "git status");
|
|
230
|
+
assert.equal(h.state.rewriteCalls, 0);
|
|
231
|
+
|
|
232
|
+
// back to supported-only → rewrites again.
|
|
233
|
+
writeRtkSection({ mode: "supported-only" });
|
|
234
|
+
assert.equal(await fireToolCall(h, "git status"), "rtk git status");
|
|
235
|
+
|
|
236
|
+
// chained: never → a chain never reaches the binary...
|
|
237
|
+
writeRtkSection({ chained: "never" });
|
|
238
|
+
const callsBefore = h.state.rewriteCalls;
|
|
239
|
+
assert.equal(await fireToolCall(h, "ls -la; pwd; cat a.txt"), "ls -la; pwd; cat a.txt");
|
|
240
|
+
assert.equal(h.state.rewriteCalls, callsBefore, "no spawn for a chain under chained: never");
|
|
241
|
+
// ...but a quoted operator is not a chain separator.
|
|
242
|
+
assert.equal(await fireToolCall(h, "git commit -m \"fix: a|b\""), "rtk git status");
|
|
243
|
+
assert.equal(h.state.rewriteCalls, callsBefore + 1, "quoted | is not a chain operator");
|
|
244
|
+
} finally {
|
|
245
|
+
if (realAgentDir === undefined) delete process.env.PI_CODING_AGENT_DIR;
|
|
246
|
+
else process.env.PI_CODING_AGENT_DIR = realAgentDir;
|
|
247
|
+
rmSync(dir, { recursive: true, force: true });
|
|
248
|
+
}
|
|
131
249
|
});
|
|
@@ -113,7 +113,10 @@ export default function rulesExtension(pi: ExtensionAPI): void {
|
|
|
113
113
|
const arg = (args ?? "").trim().toLowerCase();
|
|
114
114
|
if (arg === "reload") {
|
|
115
115
|
clearRuleCache();
|
|
116
|
-
|
|
116
|
+
// Same trust gate as the status path: without it, an untrusted project
|
|
117
|
+
// reported phantom sources and the cache key never matched the
|
|
118
|
+
// composer's (trusted=false) key.
|
|
119
|
+
ctx.ui.notify(`[rules] cache dropped — re-reading ${loadRules(ctx.cwd, undefined, projectTrusted(ctx)).files.length} source(s)`, "info");
|
|
117
120
|
return;
|
|
118
121
|
}
|
|
119
122
|
if (arg !== "") {
|
|
@@ -244,12 +244,15 @@ export function readRulesFile(source: string, state: ImportState = { seen: new S
|
|
|
244
244
|
}
|
|
245
245
|
|
|
246
246
|
function buildModel(files: string[], cwd: string): { model: RuleModel; imported: string[] } {
|
|
247
|
-
|
|
247
|
+
// `read` is shared across files (cache signature); `seen` is PER FILE —
|
|
248
|
+
// a repeat guard, not a global: the same @import from two RULES.md files
|
|
249
|
+
// must expand in both, or the second serves a literal token.
|
|
250
|
+
const read = new Set<string>();
|
|
248
251
|
const rules: LoadedRule[] = [];
|
|
249
252
|
const claimed = new Set<string>();
|
|
250
253
|
|
|
251
254
|
for (const file of files) {
|
|
252
|
-
for (const rule of readRulesFile(file,
|
|
255
|
+
for (const rule of readRulesFile(file, { seen: new Set(), read })) {
|
|
253
256
|
// Name-based dedup, first-wins (precedence order = discovery order).
|
|
254
257
|
if (claimed.has(rule.name)) continue;
|
|
255
258
|
claimed.add(rule.name);
|
|
@@ -266,7 +269,7 @@ function buildModel(files: string[], cwd: string): { model: RuleModel; imported:
|
|
|
266
269
|
};
|
|
267
270
|
model.block = composeRulesBlock(model, cwd);
|
|
268
271
|
model.blockChars = model.block?.length ?? 0;
|
|
269
|
-
return { model, imported: [...
|
|
272
|
+
return { model, imported: [...read] };
|
|
270
273
|
}
|
|
271
274
|
|
|
272
275
|
// ---------------------------------------------------------------------------
|
|
@@ -125,6 +125,30 @@ describe("@import expansion", () => {
|
|
|
125
125
|
assert.equal(body.match(/BBB/g)?.length, 1);
|
|
126
126
|
});
|
|
127
127
|
|
|
128
|
+
it("the same absolute import from TWO files expands in both (seen is per file)", () => {
|
|
129
|
+
// F3: ImportState.seen was shared across all RULES.md files, so the same
|
|
130
|
+
// @import from a second file stayed a literal token.
|
|
131
|
+
const { cwd, userDir } = workspace();
|
|
132
|
+
const shared = path.join(cwd, ".pi/shared.md");
|
|
133
|
+
write(shared, "SHARED-CONTENT\n");
|
|
134
|
+
write(path.join(cwd, ".pi/RULES.md"), "## a\n@" + shared + "\n");
|
|
135
|
+
write(path.join(userDir, "RULES.md"), "## b\n@" + shared + "\n");
|
|
136
|
+
|
|
137
|
+
const model = loadRules(cwd, userDir);
|
|
138
|
+
assert.equal(model.rules.length, 2);
|
|
139
|
+
for (const rule of model.rules) {
|
|
140
|
+
assert.ok(rule.body.includes("SHARED-CONTENT"), `${rule.name}: expanded`);
|
|
141
|
+
assert.ok(!rule.body.includes("@"), `${rule.name}: no literal token left`);
|
|
142
|
+
}
|
|
143
|
+
});
|
|
144
|
+
|
|
145
|
+
it("repeats WITHIN one file stay literal (cycle guard untouched)", () => {
|
|
146
|
+
const { cwd, userDir } = workspace();
|
|
147
|
+
write(path.join(cwd, ".pi/RULES.md"), "## a\n@x.md\n@x.md\n");
|
|
148
|
+
write(path.join(cwd, ".pi/x.md"), "XXX\n");
|
|
149
|
+
assert.equal(loadRules(cwd, userDir).rules[0].body.match(/XXX/g)?.length, 1);
|
|
150
|
+
});
|
|
151
|
+
|
|
128
152
|
it("marks a missing import in one line instead of failing", () => {
|
|
129
153
|
const { cwd, userDir } = workspace();
|
|
130
154
|
write(path.join(cwd, ".pi/RULES.md"), "## a\nsee @nope/missing.md for details\n");
|
|
@@ -15,6 +15,7 @@ import os from "node:os";
|
|
|
15
15
|
import path from "node:path";
|
|
16
16
|
|
|
17
17
|
import rulesExtension from "../index.ts";
|
|
18
|
+
import { clearRuleCache, loadRules } from "../lib/rules.ts";
|
|
18
19
|
|
|
19
20
|
const temps: string[] = [];
|
|
20
21
|
const envBackup = process.env.PI_CODING_AGENT_DIR;
|
|
@@ -193,6 +194,34 @@ describe("rules module — /rules command", () => {
|
|
|
193
194
|
assert.equal(notes[0].level, "error");
|
|
194
195
|
});
|
|
195
196
|
|
|
197
|
+
it("UNTRUSTED project: reload counts only user-level sources and the cache key matches the composer's", async () => {
|
|
198
|
+
// F5: /rules reload called loadRules without the trust gate — the phantom
|
|
199
|
+
// trusted=true model also poisoned the mtime cache with a key the composer
|
|
200
|
+
// (trusted=false) could never hit.
|
|
201
|
+
const cwd = workspace({ ".pi/RULES.md": "## project-rule\nPROJECT-SECRET-MARKER\n" });
|
|
202
|
+
const userFile = write(path.join(agentDir, "RULES.md"), "## user-rule\nUSER-MARKER\n");
|
|
203
|
+
const { commands } = harness();
|
|
204
|
+
const notes: Harness["notes"] = [];
|
|
205
|
+
const untrusted = { ...context(cwd, notes), isProjectTrusted: () => false };
|
|
206
|
+
|
|
207
|
+
await commands.get("rules").handler("reload", untrusted);
|
|
208
|
+
assert.ok(notes[0].message.includes("1 source(s)"), `only user-level source: ${notes[0].message}`);
|
|
209
|
+
assert.ok(!notes[0].message.includes(path.join(cwd, ".pi/RULES.md")));
|
|
210
|
+
|
|
211
|
+
// The composer now hits the reload-populated cache: loadRules with the
|
|
212
|
+
// SAME (cwd, trusted=false) key the composer uses returns the identical
|
|
213
|
+
// model object — the reload-run cache is a hit, not a re-parse.
|
|
214
|
+
const { events } = harness();
|
|
215
|
+
const first = await events.get("before_agent_start")!({ systemPrompt: "BASE", prompt: "p" }, untrusted);
|
|
216
|
+
assert.ok(first?.systemPrompt.includes("USER-MARKER"));
|
|
217
|
+
assert.ok(!first?.systemPrompt.includes("PROJECT-SECRET-MARKER"));
|
|
218
|
+
assert.equal(loadRules(cwd, undefined, false), loadRules(cwd, undefined, false), "cache hit — same model object");
|
|
219
|
+
await events.get("before_agent_start")!({ systemPrompt: "BASE", prompt: "p" }, untrusted);
|
|
220
|
+
|
|
221
|
+
rmSync(userFile);
|
|
222
|
+
clearRuleCache();
|
|
223
|
+
});
|
|
224
|
+
|
|
196
225
|
it("UNTRUSTED project: repo RULES.md never reaches the prompt; user file still applies", async () => {
|
|
197
226
|
// Live-found defect (reviewer 2026-10-06): the composer had no trust gate —
|
|
198
227
|
// an untrusted checkout's RULES.md (and its @imports) landed in every
|