ceulen 0.11.0 → 0.13.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 (70) hide show
  1. package/CHANGELOG.md +100 -1
  2. package/extensions/index.ts +5 -1
  3. package/extensions/lib/env.test.ts +147 -0
  4. package/extensions/lib/env.ts +180 -0
  5. package/extensions/lib/order.test.ts +74 -0
  6. package/extensions/lib/registry.test.ts +8 -5
  7. package/extensions/lib/registry.ts +23 -4
  8. package/extensions/modules/a2a/configPanel.ts +42 -1
  9. package/extensions/modules/a2a/lib/config.ts +8 -3
  10. package/extensions/modules/a2a/test/configPanel.test.ts +7 -4
  11. package/extensions/modules/advisor/index.ts +6 -3
  12. package/extensions/modules/advisor/test/module.test.ts +31 -0
  13. package/extensions/modules/classifier/index.ts +55 -1
  14. package/extensions/modules/classifier/test/classifier.test.ts +62 -0
  15. package/extensions/modules/composer/test/module.test.ts +2 -2
  16. package/extensions/modules/config/test/renderTools.test.ts +1 -1
  17. package/extensions/modules/jfind/index.ts +115 -0
  18. package/extensions/modules/jfind/lib/cascade.ts +377 -0
  19. package/extensions/modules/jfind/lib/format.ts +12 -0
  20. package/extensions/modules/jfind/lib/judge.ts +74 -0
  21. package/extensions/modules/jfind/lib/lexical.ts +232 -0
  22. package/extensions/modules/jfind/lib/questions.ts +178 -0
  23. package/extensions/modules/jfind/lib/tree.ts +374 -0
  24. package/extensions/modules/jfind/test/cascade.test.ts +305 -0
  25. package/extensions/modules/notify/index.ts +33 -0
  26. package/extensions/modules/notify/lib/notify.ts +99 -0
  27. package/extensions/modules/notify/test/notify.test.ts +95 -0
  28. package/extensions/modules/plan/lib/plan-tools.ts +13 -0
  29. package/extensions/modules/repair/configPanel.ts +7 -1
  30. package/extensions/modules/repair/index.ts +158 -3
  31. package/extensions/modules/repair/lib/auto-generated.ts +89 -0
  32. package/extensions/modules/repair/lib/read-archive.ts +101 -0
  33. package/extensions/modules/repair/lib/read-sqlite.ts +185 -0
  34. package/extensions/modules/repair/lib/settings.ts +4 -1
  35. package/extensions/modules/repair/test/freshness.test.ts +41 -1
  36. package/extensions/modules/repair/test/guard-selector.test.ts +67 -0
  37. package/extensions/modules/repair/test/readers.test.ts +291 -0
  38. package/extensions/modules/repair/test/settings.test.ts +2 -1
  39. package/extensions/modules/router/configPanel.ts +4 -4
  40. package/extensions/modules/router/index.ts +1 -1
  41. package/extensions/modules/router/lib/config.ts +9 -4
  42. package/extensions/modules/router/lib/systemone.ts +17 -4
  43. package/extensions/modules/router/test/unit.test.ts +46 -1
  44. package/extensions/modules/rules/index.ts +13 -3
  45. package/extensions/modules/rules/lib/rules.ts +24 -12
  46. package/extensions/modules/rules/test/lib.test.ts +20 -0
  47. package/extensions/modules/rules/test/module.test.ts +21 -0
  48. package/extensions/modules/sg/index.ts +129 -0
  49. package/extensions/modules/sg/lib/ops.ts +144 -0
  50. package/extensions/modules/sg/lib/sg-cli.ts +104 -0
  51. package/extensions/modules/sg/test/sg.test.ts +128 -0
  52. package/extensions/modules/shells/index.ts +210 -0
  53. package/extensions/modules/shells/lib/sessions.ts +344 -0
  54. package/extensions/modules/shells/test/sessions.test.ts +275 -0
  55. package/extensions/modules/subagent/index.ts +11 -5
  56. package/extensions/modules/subagent/lib/herdr.ts +5 -0
  57. package/extensions/modules/subagent/lib/routing.ts +31 -8
  58. package/extensions/modules/subagent/lib/runner.ts +8 -2
  59. package/extensions/modules/subagent/test/routing.test.ts +45 -0
  60. package/extensions/modules/web/configPanel.ts +67 -8
  61. package/extensions/modules/web/index.ts +34 -0
  62. package/extensions/modules/web/lib/pdf.ts +181 -0
  63. package/extensions/modules/web/test/configPanel.test.ts +7 -3
  64. package/extensions/modules/web/test/extension.test.ts +2 -1
  65. package/extensions/modules/web/test/settings.test.ts +6 -0
  66. package/extensions/modules/web/vendor/pdfjs/LICENSE +177 -0
  67. package/extensions/modules/web/vendor/pdfjs/README.md +16 -0
  68. package/extensions/modules/web/vendor/pdfjs/pdf.min.mjs +21 -0
  69. package/extensions/modules/web/vendor/pdfjs/pdf.worker.mjs +21 -0
  70. package/package.json +3 -3
@@ -8,7 +8,7 @@ import { mkdtemp, readFile, rm, utimes, writeFile } from "node:fs/promises";
8
8
  import { tmpdir } from "node:os";
9
9
  import { join } from "node:path";
10
10
  import { after, describe, it } from "node:test";
11
- import { createReadToolDefinition, createWriteToolDefinition } from "@earendil-works/pi-coding-agent";
11
+ import { createEditToolDefinition, createReadToolDefinition, createWriteToolDefinition } from "@earendil-works/pi-coding-agent";
12
12
  import { appendConflictFooter, checkWriteFresh, wrapToolDefinition } from "../index.js";
13
13
 
14
14
  const dirs: string[] = [];
@@ -121,6 +121,46 @@ describe("write freshness guard", () => {
121
121
  await rm(file);
122
122
  assert.equal(await checkWriteFresh({ path: file }, dir), undefined);
123
123
  });
124
+
125
+ it("a SELECTOR read records the freshness baseline (ranged reads don't blind the guard)", async () => {
126
+ // Live finding (reviewer 2026-10-06): the selector slice path returned
127
+ // early without recordReadMtimes, so read f.ts:5-10 → foreign write →
128
+ // blind full-file write silently clobbered the foreign edit.
129
+ const dir = await tempDir();
130
+ const file = join(dir, "sel.txt");
131
+ await writeFile(file, "l1\nl2\nl3\nl4\nl5\nl6\nl7\nl8\n");
132
+ const read = wrapToolDefinition(createReadToolDefinition(dir), createReadToolDefinition, () => false, () => {});
133
+ const sliced = await exec(read, { path: `${file}:2-4` }, dir);
134
+ assert.equal(sliced.isError, undefined);
135
+ // Foreign edit + mtime bump after our ranged read.
136
+ await writeFile(file, "FOREIGN\nl2\nl3\nl4\nl5\nl6\nl7\nl8\n");
137
+ const future = new Date(Date.now() + 1100);
138
+ await utimes(file, future, future);
139
+ const write = makeWrapped("write", dir);
140
+ const result = await exec(write, { path: file, content: "mine\n" }, dir);
141
+ assert.equal(result.isError, true, "selector read must arm the freshness guard");
142
+ assert.match(result.content[0].text, /Re-read the file/);
143
+ assert.match(await readFile(file, "utf8"), /FOREIGN/);
144
+ });
145
+
146
+ it("write after a wrapped EDIT does not false-positive (edit refreshes the baseline)", async () => {
147
+ // Live-found defect (reviewer 2026-10-06): a successful edit never
148
+ // refreshed the freshness baseline, so read → edit → write compared the
149
+ // write against the stale READ-time mtime and blocked with a false
150
+ // "File changed on disk" — recordMutatedMtimes' edit branch was dead code.
151
+ const dir = await tempDir();
152
+ const file = join(dir, "edit-baseline.txt");
153
+ await writeFile(file, "alpha\n");
154
+ const read = wrapToolDefinition(createReadToolDefinition(dir), createReadToolDefinition, () => false, () => {});
155
+ await exec(read, { path: file }, dir);
156
+ const edit = wrapToolDefinition(createEditToolDefinition(dir), createEditToolDefinition, () => false, () => {});
157
+ const edited = await exec(edit, { path: file, edits: [{ oldText: "alpha", newText: "alpha\nbeta" }] }, dir);
158
+ assert.equal(edited.isError, undefined, "edit succeeded");
159
+ const write = makeWrapped("write", dir);
160
+ const result = await exec(write, { path: file, content: "alpha\nbeta\ngamma\n" }, dir);
161
+ assert.equal(result.isError, undefined, "write after own edit must pass the freshness guard");
162
+ assert.equal(await readFile(file, "utf8"), "alpha\nbeta\ngamma\n");
163
+ });
124
164
  });
125
165
 
126
166
  // ── Conflict-marker footer ──────────────────────────────────────────────────
@@ -0,0 +1,67 @@
1
+ // Live-found defect (reviewer 2026-10-06): the always-on read-on-guessed-path
2
+ // guard hard-blocked every numeric path-selector read. The tool_call hook ran
3
+ // on the RAW path (`f.ts:50-200`) while the selector peels only inside
4
+ // execute, so existsSync probed a path that never exists on disk. This suite
5
+ // fires the REAL registered hook: a selector read whose stem exists must
6
+ // pass; genuinely missing paths (plain or with a selector suffix) still block.
7
+
8
+ import assert from "node:assert/strict";
9
+ import { mkdtemp, rm, writeFile } from "node:fs/promises";
10
+ import { tmpdir } from "node:os";
11
+ import { join } from "node:path";
12
+ import { after, describe, it } from "node:test";
13
+ import repairModule from "../index.js";
14
+
15
+ type Hook = (event: unknown, ctx: unknown) => unknown;
16
+ const dirs: string[] = [];
17
+ const originalAgentDir = process.env.PI_CODING_AGENT_DIR;
18
+
19
+ after(async () => {
20
+ if (originalAgentDir === undefined) delete process.env.PI_CODING_AGENT_DIR;
21
+ else process.env.PI_CODING_AGENT_DIR = originalAgentDir;
22
+ await Promise.all(dirs.map((d) => rm(d, { recursive: true, force: true })));
23
+ });
24
+
25
+ async function fixture() {
26
+ const dir = await mkdtemp(join(tmpdir(), "repair-guard-"));
27
+ dirs.push(dir);
28
+ process.env.PI_CODING_AGENT_DIR = dir; // neutral settings: guards default ON
29
+ await writeFile(join(dir, "f.ts"), "line1\nline2\nline3\nline4\nline5\n");
30
+ const handlers: Record<string, Hook> = {};
31
+ repairModule({
32
+ on: (event: string, handler: Hook) => { handlers[event] = handler; },
33
+ registerTool: () => {},
34
+ registerCommand: () => {},
35
+ } as never);
36
+ const call = (path: string) => handlers.tool_call!({ toolName: "read", input: { path } }, { cwd: dir });
37
+ return { dir, call };
38
+ }
39
+
40
+ describe("read guard × path-selector interaction", () => {
41
+ it("a selector read whose STEM exists passes the guard", async () => {
42
+ const { call } = await fixture();
43
+ assert.equal(await call("f.ts:2-4"), undefined, "existing stem + numeric selector must not be blocked");
44
+ assert.equal(await call("f.ts:5"), undefined);
45
+ assert.equal(await call("f.ts:-2"), undefined);
46
+ assert.equal(await call("f.ts:1-2,5"), undefined);
47
+ assert.equal(await call("f.ts:conflicts"), undefined, ":conflicts never matched looksLikeCodePath anyway");
48
+ });
49
+
50
+ it("missing paths still block — plain and selector-suffixed", async () => {
51
+ const { call } = await fixture();
52
+ const plain = await call("missing.ts") as { block: boolean; reason: string } | undefined;
53
+ assert.ok(plain?.block, "plain missing code path blocked");
54
+ const sel = await call("missing.ts:50") as { block: boolean; reason: string } | undefined;
55
+ assert.ok(sel?.block, "missing stem with selector blocked (peeled probe also missing)");
56
+ assert.match(sel.reason, /Path not found/);
57
+ });
58
+
59
+ it("an invalid selector on an existing file falls back to the raw probe (execute's loud error path)", async () => {
60
+ const { call } = await fixture();
61
+ // `:not-a-selector` doesn't parse → probe stays raw → raw doesn't exist →
62
+ // looksLikeCodePath(raw without digit-suffix strip)... the raw path
63
+ // "f.ts:zz" is not a code path (extension test on the full string fails),
64
+ // so the guard passes and execute surfaces the literal-not-found error.
65
+ assert.equal(await call("f.ts:zz"), undefined);
66
+ });
67
+ });
@@ -0,0 +1,291 @@
1
+ // read-sqlite / read-archive / auto-generated unit tests — temp fixtures via
2
+ // node:sqlite + tar, matcher tables, grammar parse table. No module wiring.
3
+
4
+ import assert from "node:assert/strict";
5
+ import { execFileSync } from "node:child_process";
6
+ import { mkdtempSync, mkdirSync, writeFileSync, rmSync } from "node:fs";
7
+ import { tmpdir } from "node:os";
8
+ import path from "node:path";
9
+ import { after, before, describe, it } from "node:test";
10
+ import { DatabaseSync } from "node:sqlite";
11
+ import {
12
+ MAX_RAW_QUERY_ROWS,
13
+ executeSqliteView,
14
+ isSqliteFile,
15
+ openDatabase,
16
+ parseSqliteSelector,
17
+ readSqlite,
18
+ } from "../lib/read-sqlite.js";
19
+ import {
20
+ MEMBER_MAX_BYTES,
21
+ archiveKind,
22
+ listMembers,
23
+ matchMember,
24
+ readArchiveListing,
25
+ readArchiveMember,
26
+ } from "../lib/read-archive.js";
27
+ import {
28
+ AUTO_GENERATED_PATTERNS,
29
+ autoGeneratedError,
30
+ checkAutoGenerated,
31
+ matchesPattern,
32
+ } from "../lib/auto-generated.js";
33
+
34
+ const dir = mkdtempSync(path.join(tmpdir(), "ceulen-repair-readers-"));
35
+ after(() => rmSync(dir, { recursive: true, force: true }));
36
+
37
+ function makeDb(file: string): void {
38
+ const db = new DatabaseSync(file);
39
+ db.exec("CREATE TABLE users (id INTEGER PRIMARY KEY, name TEXT, age INTEGER)");
40
+ db.exec("INSERT INTO users (name, age) VALUES ('alice', 30), ('bob', 41), ('carol', 25)");
41
+ db.exec("CREATE TABLE orders (id INTEGER PRIMARY KEY, user_id INTEGER, total REAL)");
42
+ db.close();
43
+ }
44
+
45
+ // ── parseSqliteSelector ─────────────────────────────────────────────────────
46
+
47
+ describe("parseSqliteSelector", () => {
48
+ it("empty → tables", () => {
49
+ assert.deepEqual(parseSqliteSelector(undefined), { kind: "tables" });
50
+ assert.deepEqual(parseSqliteSelector(""), { kind: "tables" });
51
+ assert.deepEqual(parseSqliteSelector(" "), { kind: "tables" });
52
+ });
53
+ it("table / rowid / key / query forms", () => {
54
+ assert.deepEqual(parseSqliteSelector("users"), { kind: "table", table: "users" });
55
+ assert.deepEqual(parseSqliteSelector("users:42"), { kind: "rowid", table: "users", rowid: 42 });
56
+ assert.deepEqual(parseSqliteSelector("users:name=alice"), { kind: "key", table: "users", key: "name", value: "alice" });
57
+ assert.deepEqual(parseSqliteSelector("users:name="), { kind: "key", table: "users", key: "name", value: "" });
58
+ assert.deepEqual(parseSqliteSelector("users:note=\"a:b\""), { kind: "key", table: "users", key: "note", value: "a:b" });
59
+ assert.deepEqual(parseSqliteSelector("?SELECT 1"), { kind: "query", sql: "SELECT 1" });
60
+ assert.deepEqual(parseSqliteSelector("WITH x AS (SELECT 1) SELECT * FROM x"), {
61
+ kind: "query",
62
+ sql: "WITH x AS (SELECT 1) SELECT * FROM x",
63
+ });
64
+ assert.deepEqual(parseSqliteSelector("pragma table_list"), { kind: "query", sql: "pragma table_list" });
65
+ });
66
+ it("garbage throws with a remediation shape", () => {
67
+ assert.throws(() => parseSqliteSelector("users:notafield"), /invalid sqlite selector/);
68
+ assert.throws(() => parseSqliteSelector(":nope"), /invalid sqlite selector/);
69
+ });
70
+ });
71
+
72
+ // ── sqlite views ────────────────────────────────────────────────────────────
73
+
74
+ describe("sqlite views", () => {
75
+ const dbFile = path.join(dir, "fixture.db");
76
+ makeDb(dbFile);
77
+
78
+ it("isSqliteFile sniffs the magic header, not the extension", () => {
79
+ assert.equal(isSqliteFile(dbFile), true);
80
+ const fake = path.join(dir, "fake.db");
81
+ writeFileSync(fake, "definitely not sqlite".repeat(10));
82
+ assert.equal(isSqliteFile(fake), false);
83
+ assert.equal(isSqliteFile(path.join(dir, "missing.db")), false);
84
+ });
85
+
86
+ it("tables view lists names, counts, columns", () => {
87
+ const db = openDatabase(dbFile);
88
+ try {
89
+ const out = executeSqliteView(db, { kind: "tables" }, "fixture.db");
90
+ assert.match(out, /fixture\.db — 2 table\(s\)/);
91
+ assert.match(out, /users · 3 rows · id, name, age/);
92
+ assert.match(out, /orders/);
93
+ } finally {
94
+ db.close();
95
+ }
96
+ });
97
+
98
+ it("table view shows schema + preview rows + truncation footer", () => {
99
+ const out = readSqlite(dbFile, "users", "fixture.db");
100
+ assert.match(out, /fixture\.db : users — 3 rows/);
101
+ assert.match(out, /id INTEGER PRIMARY KEY/);
102
+ assert.match(out, /alice/);
103
+ assert.doesNotMatch(out, /\[\d+ of .* rows/); // 3 rows fit the preview
104
+ });
105
+
106
+ it("rowid lookup and miss", () => {
107
+ assert.match(readSqlite(dbFile, "users:2", "f.db"), /bob/);
108
+ assert.match(readSqlite(dbFile, "users:999", "f.db"), /no row with rowid 999/);
109
+ });
110
+
111
+ it("key lookup: quoted values, unknown column, no hits", () => {
112
+ assert.match(readSqlite(dbFile, "users:name=\"alice\"", "f.db"), /alice/);
113
+ assert.match(readSqlite(dbFile, "users:nope=x", "f.db"), /no column "nope"/);
114
+ assert.match(readSqlite(dbFile, "users:name=zed", "f.db"), /no rows where name = "zed"/);
115
+ });
116
+
117
+ it("unknown table names the tables", () => {
118
+ assert.match(readSqlite(dbFile, "nope", "fixture.db"), /tables: orders, users/);
119
+ });
120
+
121
+ it("raw query renders + read-only head guard", () => {
122
+ const out = readSqlite(dbFile, "?SELECT name, age FROM users WHERE age > 26 ORDER BY age", "f.db");
123
+ assert.match(out, /alice/);
124
+ assert.match(out, /bob/);
125
+ assert.throws(() => readSqlite(dbFile, "?DROP TABLE users", "f.db"), /only read-only queries/);
126
+ // A bare non-SELECT statement is not a valid table selector either — it
127
+ // lands on the table branch and names the tables (no silent execution).
128
+ assert.match(readSqlite(dbFile, "DROP TABLE users", "f.db"), /no table/);
129
+ });
130
+
131
+ it("the db file is genuinely opened read-only", () => {
132
+ assert.throws(() => {
133
+ const db = openDatabase(dbFile);
134
+ try {
135
+ db.exec("CREATE TABLE t (x)");
136
+ } finally {
137
+ db.close();
138
+ }
139
+ }, /readonly|read-only/i);
140
+ });
141
+
142
+ it("raw queries cap at MAX_RAW_QUERY_ROWS", () => {
143
+ const big = path.join(dir, "big.db");
144
+ const db = new DatabaseSync(big);
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`);
147
+ db.close();
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);
152
+ });
153
+ });
154
+
155
+ // ── archives ────────────────────────────────────────────────────────────────
156
+
157
+ describe("archive views", () => {
158
+ const archive = path.join(dir, "fixture.tgz");
159
+ const zip = path.join(dir, "fixture.zip");
160
+ const subdir = path.join(dir, "payload");
161
+ before(() => {
162
+ mkdirSync(path.join(subdir, "nested"), { recursive: true });
163
+ writeFileSync(path.join(subdir, "hello.ts"), "line one\nline two\nline three\nline four\nline five\n");
164
+ writeFileSync(path.join(subdir, "nested", "deep.md"), "# deep\ncontent here\n");
165
+ execFileSync("tar", ["-czf", archive, "-C", subdir, "hello.ts", "nested/deep.md"]);
166
+ execFileSync("zip", ["-qr", zip, "."], { cwd: subdir });
167
+ });
168
+
169
+ it("archiveKind classifies extensions", () => {
170
+ assert.equal(archiveKind("a.tgz"), "tgz");
171
+ assert.equal(archiveKind("a.tar.gz"), "tgz");
172
+ assert.equal(archiveKind("a.tar"), "tar");
173
+ assert.equal(archiveKind("a.zip"), "zip");
174
+ assert.equal(archiveKind("a.gz"), null);
175
+ assert.equal(archiveKind("a.tar.bz2"), null);
176
+ });
177
+
178
+ it("listing shows members with a count header", () => {
179
+ const out = readArchiveListing(archive, "tgz", "fixture.tgz").text;
180
+ assert.match(out, /fixture\.tgz — 2 member\(s\)/);
181
+ assert.match(out, /hello\.ts/);
182
+ assert.match(out, /nested\/deep\.md/);
183
+ });
184
+
185
+ it("member read: exact and unique-suffix match", () => {
186
+ const exact = readArchiveMember(archive, "tgz", "hello.ts", "f.tgz").text;
187
+ assert.match(exact, /f\.tgz : hello\.ts/);
188
+ assert.match(exact, /line two/);
189
+ const suffix = readArchiveMember(archive, "tgz", "deep.md", "f.tgz").text;
190
+ assert.match(suffix, /matched .*deep\.md/);
191
+ assert.match(suffix, /content here/);
192
+ });
193
+
194
+ it("ambiguous / missing members error with candidates", () => {
195
+ writeFileSync(path.join(subdir, "other.ts"), "x\n");
196
+ execFileSync("tar", ["-czf", archive, "-C", subdir, "hello.ts", "nested/deep.md", "other.ts"]);
197
+ const amb = readArchiveMember(archive, "tgz", ".ts", "f.tgz").text;
198
+ assert.match(amb, /ambiguous member "\.ts"/);
199
+ assert.match(amb, /hello\.ts/);
200
+ const missing = readArchiveMember(archive, "tgz", "zzz.txt", "f.tgz").text;
201
+ assert.match(missing, /no member matching "zzz\.txt"/);
202
+ });
203
+
204
+ it("member + line ranges slice the body, keeping the header", () => {
205
+ // Route through the module's own slicing helper via the full path form:
206
+ // simulate what index.ts does with pkg.tgz:hello.ts:2-3
207
+ const res = readArchiveMember(archive, "tgz", "hello.ts", "fixture.tgz");
208
+ const lines = res.text.split("\n");
209
+ if (lines.length > 1 && lines[lines.length - 1] === "") lines.pop();
210
+ const header = lines[0]!;
211
+ const body = lines.slice(1);
212
+ assert.equal(header, "fixture.tgz : hello.ts");
213
+ assert.equal(body.length, 5);
214
+ });
215
+
216
+ it("zip: listing + member via unzip", { skip: process.platform === "win32" }, () => {
217
+ const listing = readArchiveListing(zip, "zip", "fixture.zip").text;
218
+ assert.match(listing, /hello\.ts/);
219
+ const member = readArchiveMember(zip, "zip", "hello.ts", "fixture.zip").text;
220
+ assert.match(member, /line three/);
221
+ });
222
+
223
+ it("matchMember semantics table", () => {
224
+ const members = ["./a/b.ts", "./a/c.ts", "x/c.ts", "d.ts"];
225
+ assert.deepEqual(matchMember(members, "d.ts"), { member: "d.ts", via: "exact" });
226
+ assert.deepEqual(matchMember(members, "a/b.ts"), { member: "./a/b.ts", via: "exact" });
227
+ assert.deepEqual(matchMember(members, "b.ts"), { member: "./a/b.ts", via: "suffix" });
228
+ assert.match((matchMember(members, "a/") as { error: string }).error ?? "", /ambiguous|no member/);
229
+ assert.match((matchMember(members, "c.ts") as { error: string }).error, /ambiguous member "c\.ts"/);
230
+ });
231
+
232
+ it("listMembers drops directories and PaxHeaders", () => {
233
+ const members = listMembers(archive, "tgz");
234
+ for (const m of members) {
235
+ assert.doesNotMatch(m, /\/$/);
236
+ assert.doesNotMatch(m, /PaxHeader/);
237
+ }
238
+ });
239
+ });
240
+
241
+ // ── auto-generated guard ────────────────────────────────────────────────────
242
+
243
+ describe("auto-generated guard", () => {
244
+ const cwd = path.join(dir, "proj");
245
+ before(() => mkdirSync(path.join(cwd, "dist", "deep"), { recursive: true }));
246
+
247
+ it("matchesPattern: **, *, plain", () => {
248
+ assert.equal(matchesPattern("package-lock.json", "package-lock.json"), true);
249
+ assert.equal(matchesPattern("dist/x.js", "dist/**"), true);
250
+ assert.equal(matchesPattern("dist/deep/y.js", "dist/**"), true);
251
+ assert.equal(matchesPattern("dist.js", "dist/**"), false);
252
+ assert.equal(matchesPattern("app.min.js", "*.min.js"), true);
253
+ assert.equal(matchesPattern("a/b/app.min.js", "*.min.js"), true);
254
+ assert.equal(matchesPattern("src/app.js", "*.min.js"), false);
255
+ assert.equal(matchesPattern("src/app.js", "src/**"), true);
256
+ assert.equal(matchesPattern("other/src/app.js", "src/**"), false);
257
+ });
258
+
259
+ it("checkAutoGenerated: lockfiles, minified, build dirs, snapshots", () => {
260
+ for (const rel of ["package-lock.json", "yarn.lock", "app.min.js", "dist/x.js", "dist/deep/y.js", "out/z.js", "__snapshots__/a.snap", "x.snap"]) {
261
+ const m = checkAutoGenerated(rel, cwd);
262
+ assert.ok(m, `${rel} should be guarded`);
263
+ }
264
+ assert.equal(checkAutoGenerated("src/app.ts", cwd), null);
265
+ assert.equal(checkAutoGenerated("packages/app/README.md", cwd), null);
266
+ });
267
+
268
+ it("absolute paths resolve against cwd", () => {
269
+ assert.ok(checkAutoGenerated(path.join(cwd, "package-lock.json"), cwd));
270
+ assert.equal(checkAutoGenerated(path.join(cwd, "src", "app.ts"), cwd), null);
271
+ });
272
+
273
+ it("error text names the pattern + regenerate + bash hatch", () => {
274
+ const m = checkAutoGenerated("package-lock.json", cwd)!;
275
+ const msg = autoGeneratedError("package-lock.json", m);
276
+ assert.match(msg, /package-lock\.json/);
277
+ assert.match(msg, /matched package-lock\.json/);
278
+ assert.match(msg, /npm install/);
279
+ assert.match(msg, /bash/);
280
+ });
281
+
282
+ it("default pattern list covers the documented set", () => {
283
+ for (const p of ["package-lock.json", "pnpm-lock.yaml", "Cargo.lock", "*.min.js", "dist/**", "__pycache__/**"]) {
284
+ assert.ok(AUTO_GENERATED_PATTERNS.includes(p), `${p} missing from defaults`);
285
+ }
286
+ });
287
+
288
+ it("member size cap constant is 1 MiB", () => {
289
+ assert.equal(MEMBER_MAX_BYTES, 1024 * 1024);
290
+ });
291
+ });
@@ -134,7 +134,7 @@ describe("projectShadow", () => {
134
134
  });
135
135
 
136
136
  describe("buildRepairGroups (panel contract)", () => {
137
- it("renders the five repair.* rows on the Tools tab with the documented defaults", () => {
137
+ it("renders the six repair.* rows on the Tools tab with the documented defaults", () => {
138
138
  const groups = buildRepairGroups({ ...DEFAULT_REPAIR_SETTINGS });
139
139
  assert.equal(groups.length, 1);
140
140
  assert.equal(groups[0].tab, "Tools");
@@ -144,6 +144,7 @@ describe("buildRepairGroups (panel contract)", () => {
144
144
  "repair.arguments",
145
145
  "repair.editRetry",
146
146
  "repair.guards",
147
+ "repair.autoGenGuard",
147
148
  "repair.autoBg",
148
149
  "repair.autoBgSecs",
149
150
  ]);
@@ -15,8 +15,8 @@ import { refreshActiveModel } from "./lib/refresh.js";
15
15
  * shown), so the panel never hides what the next request will actually use.
16
16
  * `trusted` is required — the caller decides, mirroring the rule the save-time
17
17
  * ctx applies (see zai's precedent). */
18
- export function readRouterSettings(trusted: boolean): RouterSettings {
19
- return getSettings({ trustProject: trusted });
18
+ export function readRouterSettings(trusted: boolean, cwd?: string): RouterSettings {
19
+ return getSettings({ trustProject: trusted, cwd });
20
20
  }
21
21
 
22
22
  /** Build the router panel groups over a working copy (mutated by row setters).
@@ -66,7 +66,7 @@ export async function saveRouterConfig(pi: ExtensionAPI, before: RouterSettings,
66
66
  enableReasoning: working.enableReasoning !== before.enableReasoning ? working.enableReasoning : undefined,
67
67
  });
68
68
  const trusted = ctx.isProjectTrusted?.() === true;
69
- const effective = readRouterSettings(trusted);
69
+ const effective = readRouterSettings(trusted, ctx.cwd);
70
70
  registerProvider(pi, effective);
71
71
  try {
72
72
  await maybeRefreshCatalog(ctx, { force: true });
@@ -91,7 +91,7 @@ export function routerConfig(pi: ExtensionAPI): ModuleConfig {
91
91
  // Baseline = what the next request resolves: the factory gets no ctx, so the
92
92
  // shared trust helper decides (same rule save-time ctx.isProjectTrusted
93
93
  // applies) — an untrusted checkout must not show phantom project values.
94
- const before = readRouterSettings(isProjectTrusted(process.cwd()));
94
+ const before = readRouterSettings(isProjectTrusted(process.cwd()), process.cwd());
95
95
  const working = structuredClone(before);
96
96
  return {
97
97
  groups: () => buildRouterGroups(working),
@@ -41,7 +41,7 @@ export default function (pi: ExtensionAPI) {
41
41
  lastCtx = ctx;
42
42
  // Now ctx exists: trust-gate the repo scope. A trusted repo may add/override
43
43
  // the endpoint; an untrusted one is ignored (attacker-redirect guard).
44
- const s = getSettings({ trustProject: ctx.isProjectTrusted?.() === true });
44
+ const s = getSettings({ trustProject: ctx.isProjectTrusted?.() === true, cwd: ctx.cwd });
45
45
  if (!s.baseUrl) {
46
46
  ctx.ui.notify(
47
47
  "router provider not configured — set `router.baseUrl` in ~/.pi/agent/settings.json (or ROUTER_BASE_URL), then /login router.",
@@ -13,8 +13,13 @@ export interface RouterSettings {
13
13
 
14
14
  // ── Constants ────────────────────────────────────────────────────────────────
15
15
 
16
- /** Repo-scope settings (`.pi/settings.json` in the working directory). */
17
- const REPO_SETTINGS_PATH = join(process.cwd(), ".pi", "settings.json");
16
+ /** Repo-scope settings path for one session cwd (zai/advisor/munin convention:
17
+ * resolved per call, never bound to process.cwd() at import — RPC/a2a child
18
+ * sessions and --cwd launches differ from the process dir, and the trust
19
+ * verdict applies to the SESSION's repo, so the file must too). */
20
+ function repoSettingsPath(cwd?: string): string {
21
+ return join(cwd ?? process.cwd(), ".pi", "settings.json");
22
+ }
18
23
 
19
24
  function agentDir(): string {
20
25
  return process.env.PI_CODING_AGENT_DIR || join(homedir(), ".pi", "agent");
@@ -41,10 +46,10 @@ const envReasoning = () => process.env.ROUTER_ENABLE_REASONING ?? process.env.NI
41
46
  * untrusted checkout must not redirect `router.baseUrl` to an attacker
42
47
  * endpoint while the auth.json credential is sent there as Bearer.
43
48
  * Repo-scope `router.apiKey` is ignored (secrets must not come from a checked-in file). */
44
- export function getSettings(opts: { trustProject?: boolean } = {}): RouterSettings {
49
+ export function getSettings(opts: { trustProject?: boolean; cwd?: string } = {}): RouterSettings {
45
50
  const saved = readRouterSection(readFileJson(globalSettingsPath())) ?? {};
46
51
  const repo = opts.trustProject
47
- ? readRouterSection(readFileJson(REPO_SETTINGS_PATH)) ?? {}
52
+ ? readRouterSection(readFileJson(repoSettingsPath(opts.cwd))) ?? {}
48
53
  : {};
49
54
  return {
50
55
  baseUrl: normalizeUrl(envBaseUrl() || repo.baseUrl || saved.baseUrl || ""),
@@ -22,7 +22,13 @@ function isRecord(value: unknown): value is Record<string, unknown> {
22
22
  }
23
23
 
24
24
  function url(model: ClassifierModelT): string {
25
- return `${model.baseUrl.replace(/\/+$/u, "")}/systemone`;
25
+ // Same /v1 convention as fetchSystemoneModels/fetchModels (client.ts):
26
+ // a baseUrl like http://host:20128 must POST to /v1/systemone or every
27
+ // classify silently 404s while model DISCOVERY worked (found live by
28
+ // review 2026-10-06) — never double the segment.
29
+ return /\/v1\/?$/.test(model.baseUrl)
30
+ ? `${model.baseUrl.replace(/\/+$/u, "")}/systemone`
31
+ : `${model.baseUrl.replace(/\/+$/u, "")}/v1/systemone`;
26
32
  }
27
33
 
28
34
  function requiredNumber(label: string, value: unknown, field: string): number {
@@ -127,10 +133,17 @@ export const systemoneClassify: ClassifierImpl["classify"] = async (model, conte
127
133
  "content-type": "application/json",
128
134
  ...(options.headers ?? {}),
129
135
  };
130
- const timeoutSignal = options.timeoutMs !== undefined ? AbortSignal.timeout(options.timeoutMs) : undefined;
131
- const signal = options.signal && timeoutSignal
136
+ // pi's model-runtime passes no timeoutMs for classify calls, and an
137
+ // unanswered fetch parks the caller's turn FOREVER (live incident
138
+ // 2026-10-06: two dispatches stuck 8h in kevent on an ESTABLISHED socket).
139
+ // A routing verdict is cheap — default to a hard 30s deadline unless the
140
+ // caller asked for something else. Never rejects (contract): the timeout
141
+ // surfaces as stopReason:"error" and callers fail open.
142
+ const timeoutMs = options?.timeoutMs ?? 30_000;
143
+ const timeoutSignal = AbortSignal.timeout(timeoutMs);
144
+ const signal = options?.signal
132
145
  ? AbortSignal.any([options.signal, timeoutSignal])
133
- : (options.signal ?? timeoutSignal);
146
+ : timeoutSignal;
134
147
  const response = await fetch(url(model), {
135
148
  method: "POST",
136
149
  headers,
@@ -1,6 +1,6 @@
1
1
  import { describe, it, before, after, mock } from "node:test";
2
2
  import assert from "node:assert/strict";
3
- import { mkdirSync, writeFileSync, unlinkSync, existsSync, readFileSync, rmSync, statSync } from "node:fs";
3
+ import { mkdirSync, mkdtempSync, writeFileSync, unlinkSync, existsSync, readFileSync, rmSync, statSync } from "node:fs";
4
4
  import { homedir } from "node:os";
5
5
  import { join } from "node:path";
6
6
  import { tmpdir } from "node:os";
@@ -91,6 +91,26 @@ describe("config", () => {
91
91
  });
92
92
  });
93
93
 
94
+ it("the repo overlay resolves from opts.cwd, not process.cwd() (session-cwd convention)", async () => {
95
+ // Live-found defect (reviewer 2026-10-06): REPO_SETTINGS_PATH was bound
96
+ // to process.cwd() at import — RPC/a2a child sessions with a different
97
+ // session cwd consulted the wrong file under the right trust verdict.
98
+ const { getSettings } = await import("../lib/config.js");
99
+ writeSettings({ baseUrl: "http://global" });
100
+ const dirA = mkdtempSync(join(tmpdir(), "router-cwd-a-"));
101
+ const dirB = mkdtempSync(join(tmpdir(), "router-cwd-b-"));
102
+ try {
103
+ mkdirSync(join(dirB, ".pi"), { recursive: true });
104
+ writeFileSync(join(dirB, ".pi", "settings.json"), JSON.stringify({ router: { baseUrl: "http://repo-b/v1" } }));
105
+ assert.equal(getSettings({ trustProject: true, cwd: dirA }).baseUrl, "http://global", "A has no repo file → global");
106
+ assert.equal(getSettings({ trustProject: true, cwd: dirB }).baseUrl, "http://repo-b/v1", "B's repo file serves B's session");
107
+ assert.equal(getSettings({ trustProject: false, cwd: dirB }).baseUrl, "http://global", "untrusted B → global regardless of cwd");
108
+ } finally {
109
+ rmSync(dirA, { recursive: true, force: true });
110
+ rmSync(dirB, { recursive: true, force: true });
111
+ }
112
+ });
113
+
94
114
  it("trusted: env still beats repo", async () => {
95
115
  try { unlinkSync(settingsPath()); } catch { /* ignore */ }
96
116
  process.env.ROUTER_BASE_URL = "http://from-env";
@@ -922,6 +942,31 @@ describe("provider classifier catalog", () => {
922
942
  }
923
943
  });
924
944
 
945
+ it("classify carries a default 30s deadline — a silent endpoint fails open, never hangs the turn", async () => {
946
+ const { systemoneClassify } = await import("../lib/systemone.js");
947
+ const model = {
948
+ api: "typesafe-system-one",
949
+ provider: "router",
950
+ id: "combo/jev",
951
+ baseUrl: "http://h/v1",
952
+ cost: { input: 0, output: 0 },
953
+ } as never;
954
+ const context = { state: {}, questions: { q: { type: "noul", instructions: "x?", criteria: { yes: "y", no: "n" } } } } as never;
955
+ const realFetch = globalThis.fetch;
956
+ // Never-resolving fetch: without the default deadline this promise never
957
+ // settles (the live 8h hang). AbortSignal.timeout must cut it short.
958
+ globalThis.fetch = ((_input: unknown, init?: RequestInit) => new Promise<Response>((_resolve, reject) => {
959
+ init?.signal?.addEventListener("abort", () => reject(new Error("aborted: deadline")));
960
+ })) as unknown as typeof fetch;
961
+ try {
962
+ const result = await systemoneClassify(model, context, { apiKey: "sk" } as never);
963
+ assert.equal(result.stopReason, "error", "deadline expiry must surface as stopReason error, not a hang");
964
+ assert.match(result.errorMessage ?? "", /deadline/i);
965
+ } finally {
966
+ globalThis.fetch = realFetch;
967
+ }
968
+ });
969
+
925
970
  it("registerProvider carries the typesafe-system-one classifier implementation", async () => {
926
971
  const { registerProvider, PROVIDER_ID } = await import("../lib/provider.js");
927
972
  let registered: { name: string; config: Record<string, unknown> } | null = null;
@@ -28,6 +28,16 @@ import { clearRuleCache, loadRules, type RuleModel } from "./lib/rules";
28
28
  /** Cap on a single rule body returned by rule_get (chars). */
29
29
  const RULE_GET_MAX_CHARS = 20000;
30
30
 
31
+ /** Trust gate (AGENTS.md/subagent convention): an untrusted checkout's
32
+ * RULES.md must not reach the system prompt or rule_get. Fail closed. */
33
+ function projectTrusted(ctx: { isProjectTrusted?: () => boolean } | undefined): boolean {
34
+ try {
35
+ return ctx?.isProjectTrusted?.() === true;
36
+ } catch {
37
+ return false;
38
+ }
39
+ }
40
+
31
41
  function statusLines(model: RuleModel, cwd: string): string {
32
42
  if (model.files.length === 0) {
33
43
  return [
@@ -54,7 +64,7 @@ export default function rulesExtension(pi: ExtensionAPI): void {
54
64
  pi.on("before_agent_start", async (event, ctx): Promise<BeforeAgentStartEventResult | undefined> => {
55
65
  let model: RuleModel;
56
66
  try {
57
- model = loadRules(ctx?.cwd ?? process.cwd());
67
+ model = loadRules(ctx?.cwd ?? process.cwd(), undefined, projectTrusted(ctx));
58
68
  } catch {
59
69
  return undefined; // never break a turn over rule discovery
60
70
  }
@@ -73,7 +83,7 @@ export default function rulesExtension(pi: ExtensionAPI): void {
73
83
  }),
74
84
  defaultActive: !disabledTools.has("rule_get"),
75
85
  async execute(_id: string, params: { name: string }, _signal, _onUpdate, ctx) {
76
- const model = loadRules(ctx?.cwd ?? process.cwd());
86
+ const model = loadRules(ctx?.cwd ?? process.cwd(), undefined, projectTrusted(ctx));
77
87
  const wanted = (params.name ?? "").trim();
78
88
  const rule = model.rules.find((item) => item.name === wanted);
79
89
  if (!rule) {
@@ -114,7 +124,7 @@ export default function rulesExtension(pi: ExtensionAPI): void {
114
124
  ctx.ui.notify(`[rules] unknown argument "${arg}" — use /rules or /rules reload`, "error");
115
125
  return;
116
126
  }
117
- ctx.ui.notify(statusLines(loadRules(ctx.cwd), ctx.cwd), "info");
127
+ ctx.ui.notify(statusLines(loadRules(ctx.cwd, undefined, projectTrusted(ctx)), ctx.cwd), "info");
118
128
  },
119
129
  });
120
130
  }