ceulen 0.12.0 → 0.14.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.
- package/CHANGELOG.md +91 -0
- package/extensions/lib/registry.ts +15 -1
- package/extensions/modules/a2a/lib/config.ts +15 -1
- package/extensions/modules/a2a/test/config.test.ts +27 -0
- package/extensions/modules/composer/test/module.test.ts +2 -2
- package/extensions/modules/config/test/renderTools.test.ts +1 -1
- package/extensions/modules/fff/index.ts +19 -0
- package/extensions/modules/fff/test/index.test.ts +31 -4
- package/extensions/modules/gh/configPanel.ts +9 -6
- package/extensions/modules/gh/test/gh.test.ts +61 -0
- package/extensions/modules/jfind/index.ts +124 -0
- package/extensions/modules/jfind/lib/cascade.ts +391 -0
- package/extensions/modules/jfind/lib/format.ts +12 -0
- package/extensions/modules/jfind/lib/judge.ts +74 -0
- package/extensions/modules/jfind/lib/lexical.ts +244 -0
- package/extensions/modules/jfind/lib/questions.ts +178 -0
- package/extensions/modules/jfind/lib/tree.ts +404 -0
- package/extensions/modules/jfind/test/cascade.test.ts +360 -0
- package/extensions/modules/notify/index.ts +33 -0
- package/extensions/modules/notify/lib/notify.ts +99 -0
- package/extensions/modules/notify/test/notify.test.ts +95 -0
- package/extensions/modules/plan/lib/plan-tools.ts +13 -0
- package/extensions/modules/repair/configPanel.ts +18 -9
- package/extensions/modules/repair/index.ts +173 -9
- package/extensions/modules/repair/lib/auto-bg.ts +45 -2
- package/extensions/modules/repair/lib/auto-generated.ts +99 -0
- package/extensions/modules/repair/lib/read-archive.ts +115 -0
- package/extensions/modules/repair/lib/read-sqlite.ts +191 -0
- package/extensions/modules/repair/lib/settings.ts +23 -9
- package/extensions/modules/repair/test/auto-bg.test.ts +66 -0
- package/extensions/modules/repair/test/hardening.test.ts +214 -0
- package/extensions/modules/repair/test/readers.test.ts +291 -0
- package/extensions/modules/repair/test/settings.test.ts +54 -14
- package/extensions/modules/sg/index.ts +129 -0
- package/extensions/modules/sg/lib/ops.ts +144 -0
- package/extensions/modules/sg/lib/sg-cli.ts +104 -0
- package/extensions/modules/sg/test/sg.test.ts +128 -0
- package/extensions/modules/shells/index.ts +227 -0
- package/extensions/modules/shells/lib/sessions.ts +412 -0
- package/extensions/modules/shells/test/output.test.ts +130 -0
- package/extensions/modules/shells/test/sessions.test.ts +397 -0
- package/extensions/modules/web/index.ts +34 -0
- package/extensions/modules/web/lib/pdf.ts +183 -0
- package/extensions/modules/web/test/extension.test.ts +2 -1
- package/extensions/modules/web/test/pdf.test.ts +84 -0
- package/extensions/modules/web/vendor/pdfjs/LICENSE +177 -0
- package/extensions/modules/web/vendor/pdfjs/README.md +16 -0
- package/extensions/modules/web/vendor/pdfjs/pdf.min.mjs +21 -0
- package/extensions/modules/web/vendor/pdfjs/pdf.worker.mjs +21 -0
- package/package.json +3 -3
|
@@ -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
|
+
});
|
|
@@ -7,7 +7,6 @@ import { after, beforeEach, describe, it } from "node:test";
|
|
|
7
7
|
import { mkdtemp, mkdir, readFile, rm, writeFile } from "node:fs/promises";
|
|
8
8
|
import { tmpdir } from "node:os";
|
|
9
9
|
import { join } from "node:path";
|
|
10
|
-
import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
|
|
11
10
|
import {
|
|
12
11
|
DEFAULT_REPAIR_SETTINGS,
|
|
13
12
|
projectShadow,
|
|
@@ -29,14 +28,17 @@ async function tempDir(): Promise<string> {
|
|
|
29
28
|
return dir;
|
|
30
29
|
}
|
|
31
30
|
|
|
32
|
-
|
|
33
|
-
|
|
31
|
+
/** The settings reader resolves trust via lib/registry isProjectTrusted —
|
|
32
|
+
* <agentDir>/trust.json. Write the trust entry instead of a ctx stub. */
|
|
33
|
+
async function setProjectTrust(trusted: boolean): Promise<void> {
|
|
34
|
+
await writeFile(join(agentDir, "trust.json"), JSON.stringify({ [cwd]: trusted }));
|
|
34
35
|
}
|
|
35
36
|
|
|
36
37
|
beforeEach(async () => {
|
|
37
38
|
agentDir = await tempDir();
|
|
38
39
|
cwd = await tempDir();
|
|
39
40
|
process.env.PI_CODING_AGENT_DIR = agentDir;
|
|
41
|
+
await setProjectTrust(true);
|
|
40
42
|
});
|
|
41
43
|
|
|
42
44
|
after(async () => {
|
|
@@ -56,12 +58,12 @@ async function writeProject(cwdPath: string, repair: unknown): Promise<void> {
|
|
|
56
58
|
|
|
57
59
|
describe("readRepairSettings", () => {
|
|
58
60
|
it("defaults: repair on, guards on, autoBg off @120s", () => {
|
|
59
|
-
assert.deepEqual(readRepairSettings(
|
|
61
|
+
assert.deepEqual(readRepairSettings(cwd), DEFAULT_REPAIR_SETTINGS);
|
|
60
62
|
});
|
|
61
63
|
|
|
62
64
|
it("reads the global agent-dir `repair` section", async () => {
|
|
63
65
|
await writeGlobal({ arguments: false, autoBg: true, autoBgSecs: 30 });
|
|
64
|
-
const s = readRepairSettings(
|
|
66
|
+
const s = readRepairSettings(cwd);
|
|
65
67
|
assert.equal(s.arguments, false);
|
|
66
68
|
assert.equal(s.autoBg, true);
|
|
67
69
|
assert.equal(s.autoBgSecs, 30);
|
|
@@ -71,7 +73,7 @@ describe("readRepairSettings", () => {
|
|
|
71
73
|
it("trusted project file overrides the global layer field-wise", async () => {
|
|
72
74
|
await writeGlobal({ guards: false, autoBgSecs: 30 });
|
|
73
75
|
await writeProject(cwd, { guards: true, autoBgSecs: 45, autoBg: true });
|
|
74
|
-
const s = readRepairSettings(
|
|
76
|
+
const s = readRepairSettings(cwd);
|
|
75
77
|
assert.equal(s.guards, true, "project wins");
|
|
76
78
|
assert.equal(s.autoBgSecs, 45, "project wins");
|
|
77
79
|
assert.equal(s.autoBg, true, "project-only key");
|
|
@@ -80,29 +82,36 @@ describe("readRepairSettings", () => {
|
|
|
80
82
|
it("an UNTRUSTED project file is ignored entirely", async () => {
|
|
81
83
|
await writeGlobal({ guards: false });
|
|
82
84
|
await writeProject(cwd, { guards: true, autoBg: true });
|
|
83
|
-
|
|
85
|
+
await setProjectTrust(false);
|
|
86
|
+
const s = readRepairSettings(cwd);
|
|
84
87
|
assert.equal(s.guards, false, "global value survives an untrusted project");
|
|
85
88
|
assert.equal(s.autoBg, false);
|
|
89
|
+
await setProjectTrust(true); // restore for the later suites
|
|
90
|
+
});
|
|
91
|
+
|
|
92
|
+
it("no cwd argument → global layer only (ctx-less callers)", async () => {
|
|
93
|
+
await writeProject(cwd, { autoBgSecs: 45 });
|
|
94
|
+
assert.equal(readRepairSettings().autoBgSecs, 120, "project layer skipped without cwd");
|
|
86
95
|
});
|
|
87
96
|
|
|
88
97
|
it("clamps autoBgSecs: fractional floors to ≥1, garbage falls back", async () => {
|
|
89
98
|
await writeGlobal({ autoBgSecs: 0.5 });
|
|
90
|
-
assert.equal(readRepairSettings(
|
|
99
|
+
assert.equal(readRepairSettings(cwd).autoBgSecs, 1, "0.5 → floor 0 → clamped to 1");
|
|
91
100
|
await writeGlobal({ autoBgSecs: -10 });
|
|
92
|
-
assert.equal(readRepairSettings(
|
|
101
|
+
assert.equal(readRepairSettings(cwd).autoBgSecs, 1);
|
|
93
102
|
await writeGlobal({ autoBgSecs: "abc" });
|
|
94
|
-
assert.equal(readRepairSettings(
|
|
103
|
+
assert.equal(readRepairSettings(cwd).autoBgSecs, 120, "non-number → default");
|
|
95
104
|
await writeGlobal({ autoBgSecs: 30.9 });
|
|
96
|
-
assert.equal(readRepairSettings(
|
|
105
|
+
assert.equal(readRepairSettings(cwd).autoBgSecs, 30);
|
|
97
106
|
});
|
|
98
107
|
|
|
99
108
|
it("ignores wrong-typed booleans and a corrupt file", async () => {
|
|
100
109
|
await writeGlobal({ arguments: "yes", guards: 0 });
|
|
101
|
-
let s = readRepairSettings(
|
|
110
|
+
let s = readRepairSettings(cwd);
|
|
102
111
|
assert.equal(s.arguments, true);
|
|
103
112
|
assert.equal(s.guards, true);
|
|
104
113
|
await writeFile(settingsPath(), "{ not json");
|
|
105
|
-
s = readRepairSettings(
|
|
114
|
+
s = readRepairSettings(cwd);
|
|
106
115
|
assert.deepEqual(s, DEFAULT_REPAIR_SETTINGS);
|
|
107
116
|
});
|
|
108
117
|
});
|
|
@@ -133,8 +142,38 @@ describe("projectShadow", () => {
|
|
|
133
142
|
});
|
|
134
143
|
});
|
|
135
144
|
|
|
145
|
+
describe("tool_call honors the trusted-project layer (A5 e2e)", () => {
|
|
146
|
+
it("project autoGenGuard:false blocks a guarded write through the REAL wrapped tool", async () => {
|
|
147
|
+
await writeGlobal({}); // global layer silent
|
|
148
|
+
await writeProject(cwd, { autoGenGuard: false });
|
|
149
|
+
const { wrapToolDefinition } = await import("../index.js");
|
|
150
|
+
const { createWriteToolDefinition } = await import("@earendil-works/pi-coding-agent");
|
|
151
|
+
const wrapped = wrapToolDefinition(createWriteToolDefinition(cwd), createWriteToolDefinition, () => false, () => {});
|
|
152
|
+
const res: any = await wrapped.execute("t1", { path: join(cwd, "package-lock.json"), content: "{}" }, undefined, undefined, { cwd });
|
|
153
|
+
assert.equal(res.isError, undefined, "project layer OFF → guard must NOT fire, write lands");
|
|
154
|
+
assert.match(await readFile(join(cwd, "package-lock.json"), "utf8"), /\{\}/);
|
|
155
|
+
// And with the project layer silent again, the same write is refused.
|
|
156
|
+
await rm(join(cwd, ".pi"), { recursive: true, force: true });
|
|
157
|
+
const res2: any = await wrapped.execute("t2", { path: join(cwd, "package-lock.json"), content: "{}" }, undefined, undefined, { cwd });
|
|
158
|
+
assert.equal(res2.isError, true);
|
|
159
|
+
assert.match(res2.content[0].text, /auto-generated/);
|
|
160
|
+
});
|
|
161
|
+
|
|
162
|
+
it("an UNTRUSTED project file never reaches the guard", async () => {
|
|
163
|
+
await setProjectTrust(false);
|
|
164
|
+
await writeGlobal({});
|
|
165
|
+
await writeProject(cwd, { autoGenGuard: false });
|
|
166
|
+
const { wrapToolDefinition } = await import("../index.js");
|
|
167
|
+
const { createWriteToolDefinition } = await import("@earendil-works/pi-coding-agent");
|
|
168
|
+
const wrapped = wrapToolDefinition(createWriteToolDefinition(cwd), createWriteToolDefinition, () => false, () => {});
|
|
169
|
+
const res: any = await wrapped.execute("t3", { path: join(cwd, "yarn.lock"), content: "{}" }, undefined, undefined, { cwd });
|
|
170
|
+
assert.equal(res.isError, true);
|
|
171
|
+
assert.match(res.content[0].text, /auto-generated/, "untrusted project layer ignored — global/default governs");
|
|
172
|
+
});
|
|
173
|
+
});
|
|
174
|
+
|
|
136
175
|
describe("buildRepairGroups (panel contract)", () => {
|
|
137
|
-
it("renders the
|
|
176
|
+
it("renders the six repair.* rows on the Tools tab with the documented defaults", () => {
|
|
138
177
|
const groups = buildRepairGroups({ ...DEFAULT_REPAIR_SETTINGS });
|
|
139
178
|
assert.equal(groups.length, 1);
|
|
140
179
|
assert.equal(groups[0].tab, "Tools");
|
|
@@ -144,6 +183,7 @@ describe("buildRepairGroups (panel contract)", () => {
|
|
|
144
183
|
"repair.arguments",
|
|
145
184
|
"repair.editRetry",
|
|
146
185
|
"repair.guards",
|
|
186
|
+
"repair.autoGenGuard",
|
|
147
187
|
"repair.autoBg",
|
|
148
188
|
"repair.autoBgSecs",
|
|
149
189
|
]);
|
|
@@ -0,0 +1,129 @@
|
|
|
1
|
+
// sg module — structural search & rewrite via the ast-grep CLI (gh-module
|
|
2
|
+
// fail-open pattern): `ast_grep` search + `ast_edit` multi-op rewrites with a
|
|
3
|
+
// dry-run default. Missing binary → the module registers nothing and the
|
|
4
|
+
// /config Enable row stays reachable.
|
|
5
|
+
|
|
6
|
+
import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
|
|
7
|
+
import { Type } from "typebox";
|
|
8
|
+
import { readDisabledTools } from "../../lib/tools.js";
|
|
9
|
+
import { realSg, sgAvailable, type SgRunner } from "./lib/sg-cli.js";
|
|
10
|
+
import { buildRunArgs, formatMatches, mergeMatches, parseSearch } from "./lib/ops.js";
|
|
11
|
+
|
|
12
|
+
const LANGUAGE_PARAM = Type.Optional(
|
|
13
|
+
Type.String({ description: 'Tree-sitter language id when the files\' extension is ambiguous — "ts", "tsx", "py", "rust", "go", "java"… (optional; inferred from the extension).' }),
|
|
14
|
+
);
|
|
15
|
+
|
|
16
|
+
async function runSearch(rg: SgRunner, cwd: string, opts: { pattern: string; language?: string; globs?: string[]; paths?: string[] }, signal?: AbortSignal) {
|
|
17
|
+
return parseSearch(await rg.run(cwd, buildRunArgs({ ...opts, json: true }), signal), opts.pattern);
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
export default function sgModule(pi: ExtensionAPI): void {
|
|
21
|
+
// No sg/ast-grep binary → no tools; /config's Enable row still renders
|
|
22
|
+
// (install + /reload activates).
|
|
23
|
+
if (!sgAvailable()) return;
|
|
24
|
+
|
|
25
|
+
const disabled = readDisabledTools();
|
|
26
|
+
|
|
27
|
+
pi.registerTool({
|
|
28
|
+
name: "ast_grep",
|
|
29
|
+
label: "AST Grep",
|
|
30
|
+
defaultActive: !disabled.has("ast_grep"),
|
|
31
|
+
description:
|
|
32
|
+
"Structural code search via the ast-grep CLI: match AST patterns with meta-variables ($VAR = one node, $$$ALL = many) instead of regex — `$FUNC($$$ARGS)` finds every call. " +
|
|
33
|
+
"Patterns are snippets of real code in the target language. Use for syntax-aware searches regex mangles (calls, imports, JSX). Returns path:line:col + matched text.",
|
|
34
|
+
promptSnippet: "Structural AST code search (ast-grep patterns)",
|
|
35
|
+
promptGuidelines: [
|
|
36
|
+
"Write the pattern as real code with $NAME holes; it must parse in the target language.",
|
|
37
|
+
"Prefer this over regex grep when the shape of the code matters (calls, assignments, JSX tags).",
|
|
38
|
+
"A pattern that fails to parse returns a hint — simplify the pattern or set `language`.",
|
|
39
|
+
],
|
|
40
|
+
parameters: Type.Object({
|
|
41
|
+
pattern: Type.String({ description: "ast-grep pattern (real code with $VAR / $$$ALL meta-variables)." }),
|
|
42
|
+
patterns: Type.Optional(Type.Array(Type.String(), { description: "Extra OR patterns — each is searched and results are merged+deduped." })),
|
|
43
|
+
language: LANGUAGE_PARAM,
|
|
44
|
+
globs: Type.Optional(Type.Array(Type.String(), { description: 'Glob filter, e.g. ["*.ts", "!*.test.ts"].' })),
|
|
45
|
+
paths: Type.Optional(Type.Array(Type.String(), { description: 'Files/directories to search (default ["."]).' })),
|
|
46
|
+
}),
|
|
47
|
+
async execute(_toolCallId, params, signal, _onUpdate, ctx) {
|
|
48
|
+
const cwd = ctx?.cwd || process.cwd();
|
|
49
|
+
const p = params as { pattern: string; patterns?: string[]; language?: string; globs?: string[]; paths?: string[] };
|
|
50
|
+
const all = [p.pattern, ...(p.patterns ?? [])];
|
|
51
|
+
try {
|
|
52
|
+
const runs = await Promise.all(
|
|
53
|
+
all.map((pattern) => runSearch(realSg, cwd, { pattern, language: p.language, globs: p.globs, paths: p.paths }, signal)),
|
|
54
|
+
);
|
|
55
|
+
const merged = mergeMatches(runs);
|
|
56
|
+
const patternError = merged.patternError;
|
|
57
|
+
if (patternError) {
|
|
58
|
+
return { content: [{ type: "text", text: patternError }], isError: true as const, details: { pattern: p.pattern } };
|
|
59
|
+
}
|
|
60
|
+
return {
|
|
61
|
+
content: [{ type: "text", text: formatMatches(merged.matches, all.join(" | ")) }],
|
|
62
|
+
details: { matches: merged.matches.length },
|
|
63
|
+
};
|
|
64
|
+
} catch (err) {
|
|
65
|
+
return { content: [{ type: "text", text: err instanceof Error ? err.message : String(err) }], isError: true as const, details: { pattern: p.pattern } };
|
|
66
|
+
}
|
|
67
|
+
},
|
|
68
|
+
});
|
|
69
|
+
|
|
70
|
+
pi.registerTool({
|
|
71
|
+
name: "ast_edit",
|
|
72
|
+
label: "AST Edit",
|
|
73
|
+
defaultActive: !disabled.has("ast_edit"),
|
|
74
|
+
description:
|
|
75
|
+
"Structural code rewrite via the ast-grep CLI: one pattern → rewrite pair applied across files (the rewrite reuses $VAR / $$$ALL meta-variables). " +
|
|
76
|
+
"DRY-RUN BY DEFAULT: returns the per-file diff without touching disk. Pass write:true to apply (files are rewritten in place; NOT atomic across files). " +
|
|
77
|
+
"After applying, the match count is re-checked and reported so silent misses (a rewrite that generates new matches) are visible.",
|
|
78
|
+
promptSnippet: "Structural AST rewrite (ast-grep), dry-run by default",
|
|
79
|
+
promptGuidelines: [
|
|
80
|
+
"Always inspect the dry-run diff before write:true — rewrites apply to every match in scope.",
|
|
81
|
+
"The rewrite is a code template reusing the pattern's meta-variables ($VAR stays, text around it changes).",
|
|
82
|
+
"Scope rewrites with paths/globs; use for mechanical multi-file refactors, not one-line edits (edit wins there).",
|
|
83
|
+
],
|
|
84
|
+
parameters: Type.Object({
|
|
85
|
+
pattern: Type.String({ description: "ast-grep pattern (real code with $VAR / $$$ALL meta-variables)." }),
|
|
86
|
+
rewrite: Type.String({ description: "Rewrite template reusing the pattern's meta-variables." }),
|
|
87
|
+
language: LANGUAGE_PARAM,
|
|
88
|
+
globs: Type.Optional(Type.Array(Type.String(), { description: 'Glob filter, e.g. ["src/**"].' })),
|
|
89
|
+
paths: Type.Optional(Type.Array(Type.String(), { description: 'Files/directories to rewrite (default ["."]).' })),
|
|
90
|
+
write: Type.Optional(Type.Boolean({ default: false, description: "false (default) = dry-run diff only; true = rewrite the files on disk." })),
|
|
91
|
+
}),
|
|
92
|
+
async execute(_toolCallId, params, signal, _onUpdate, ctx) {
|
|
93
|
+
const cwd = ctx?.cwd || process.cwd();
|
|
94
|
+
const p = params as { pattern: string; rewrite: string; language?: string; globs?: string[]; paths?: string[]; write?: boolean };
|
|
95
|
+
try {
|
|
96
|
+
const before = await runSearch(realSg, cwd, { pattern: p.pattern, language: p.language, globs: p.globs, paths: p.paths }, signal);
|
|
97
|
+
if (before.patternError) {
|
|
98
|
+
return { content: [{ type: "text", text: before.patternError }], isError: true as const, details: { pattern: p.pattern } };
|
|
99
|
+
}
|
|
100
|
+
if (before.noMatches) {
|
|
101
|
+
return { content: [{ type: "text", text: `no matches for ${p.pattern} — nothing to rewrite` }], details: { matches: 0 } };
|
|
102
|
+
}
|
|
103
|
+
if (p.write !== true) {
|
|
104
|
+
const preview = await realSg.run(cwd, buildRunArgs({ pattern: p.pattern, rewrite: p.rewrite, language: p.language, globs: p.globs, paths: p.paths }), signal);
|
|
105
|
+
const files = [...new Set(before.matches.map((m) => m.file))];
|
|
106
|
+
let text = `DRY-RUN — ${before.matches.length} match(es) across ${files.length} file(s) would change:\n${files.map((f) => ` ${f}`).join("\n")}\n\n${preview.stdout.trim()}`;
|
|
107
|
+
if (text.length > 16_000) text = `${text.slice(0, 16_000)}\n[… preview truncated — narrow paths/globs …]`;
|
|
108
|
+
return { content: [{ type: "text", text }], details: { matches: before.matches.length, files } };
|
|
109
|
+
}
|
|
110
|
+
const apply = await realSg.run(cwd, buildRunArgs({ pattern: p.pattern, rewrite: p.rewrite, language: p.language, globs: p.globs, paths: p.paths, update: true }), signal);
|
|
111
|
+
if (apply.exitCode !== 0) {
|
|
112
|
+
throw new Error(`sg -U rewrite failed (exit ${apply.exitCode}): ${apply.stderr.slice(0, 300) || apply.stdout.slice(0, 300)}`);
|
|
113
|
+
}
|
|
114
|
+
// Staleness check: a rewrite that produces fresh matches means the
|
|
115
|
+
// rule isn't idempotent — surface it instead of silently looping
|
|
116
|
+
// later callers into re-applying.
|
|
117
|
+
const after = await runSearch(realSg, cwd, { pattern: p.pattern, language: p.language, globs: p.globs, paths: p.paths }, signal);
|
|
118
|
+
const files = [...new Set(before.matches.map((m) => m.file))];
|
|
119
|
+
let text = `rewrote ${before.matches.length} match(es) across ${files.length} file(s):\n${files.map((f) => ` ${f}`).join("\n")}`;
|
|
120
|
+
if (!after.noMatches) {
|
|
121
|
+
text += `\nnote: ${after.matches.length} match(es) REMAIN post-rewrite — the rewrite generates new matches for its own pattern; re-running would loop.`;
|
|
122
|
+
}
|
|
123
|
+
return { content: [{ type: "text", text }], details: { matches: before.matches.length, files, remaining: after.matches.length } };
|
|
124
|
+
} catch (err) {
|
|
125
|
+
return { content: [{ type: "text", text: err instanceof Error ? err.message : String(err) }], isError: true as const, details: { pattern: p.pattern } };
|
|
126
|
+
}
|
|
127
|
+
},
|
|
128
|
+
});
|
|
129
|
+
}
|