ceulen 0.12.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 (39) hide show
  1. package/CHANGELOG.md +49 -0
  2. package/extensions/lib/registry.ts +15 -1
  3. package/extensions/modules/composer/test/module.test.ts +2 -2
  4. package/extensions/modules/config/test/renderTools.test.ts +1 -1
  5. package/extensions/modules/jfind/index.ts +115 -0
  6. package/extensions/modules/jfind/lib/cascade.ts +377 -0
  7. package/extensions/modules/jfind/lib/format.ts +12 -0
  8. package/extensions/modules/jfind/lib/judge.ts +74 -0
  9. package/extensions/modules/jfind/lib/lexical.ts +232 -0
  10. package/extensions/modules/jfind/lib/questions.ts +178 -0
  11. package/extensions/modules/jfind/lib/tree.ts +374 -0
  12. package/extensions/modules/jfind/test/cascade.test.ts +305 -0
  13. package/extensions/modules/notify/index.ts +33 -0
  14. package/extensions/modules/notify/lib/notify.ts +99 -0
  15. package/extensions/modules/notify/test/notify.test.ts +95 -0
  16. package/extensions/modules/plan/lib/plan-tools.ts +13 -0
  17. package/extensions/modules/repair/configPanel.ts +7 -1
  18. package/extensions/modules/repair/index.ts +132 -1
  19. package/extensions/modules/repair/lib/auto-generated.ts +89 -0
  20. package/extensions/modules/repair/lib/read-archive.ts +101 -0
  21. package/extensions/modules/repair/lib/read-sqlite.ts +185 -0
  22. package/extensions/modules/repair/lib/settings.ts +4 -1
  23. package/extensions/modules/repair/test/readers.test.ts +291 -0
  24. package/extensions/modules/repair/test/settings.test.ts +2 -1
  25. package/extensions/modules/sg/index.ts +129 -0
  26. package/extensions/modules/sg/lib/ops.ts +144 -0
  27. package/extensions/modules/sg/lib/sg-cli.ts +104 -0
  28. package/extensions/modules/sg/test/sg.test.ts +128 -0
  29. package/extensions/modules/shells/index.ts +210 -0
  30. package/extensions/modules/shells/lib/sessions.ts +344 -0
  31. package/extensions/modules/shells/test/sessions.test.ts +275 -0
  32. package/extensions/modules/web/index.ts +34 -0
  33. package/extensions/modules/web/lib/pdf.ts +181 -0
  34. package/extensions/modules/web/test/extension.test.ts +2 -1
  35. package/extensions/modules/web/vendor/pdfjs/LICENSE +177 -0
  36. package/extensions/modules/web/vendor/pdfjs/README.md +16 -0
  37. package/extensions/modules/web/vendor/pdfjs/pdf.min.mjs +21 -0
  38. package/extensions/modules/web/vendor/pdfjs/pdf.worker.mjs +21 -0
  39. package/package.json +3 -3
@@ -0,0 +1,185 @@
1
+ // read-sqlite — sqlite views for the wrapped read (OMP read-sqlite.ts +
2
+ // sqlite-reader.ts semantics on the repair selector grammar).
3
+ //
4
+ // Grammar (parsed from the selector AFTER the path stem resolves to a real
5
+ // sqlite file — see parseSqliteSelector):
6
+ // db.sqlite → table list
7
+ // db.sqlite:users → schema + first 10 rows
8
+ // db.sqlite:users:42 → row by rowid
9
+ // db.sqlite:users:name=alice → row(s) by key equality (LIMIT 20)
10
+ // db.sqlite:SELECT … → read-only query (SELECT/WITH/PRAGMA only)
11
+ // Engine: node:sqlite DatabaseSync opened READ-ONLY per call (unflagged
12
+ // since Node 22.13 < the repo engines floor). Fallback seam: swap
13
+ // `openDatabase` if a runtime refuses (e.g. sqlite3 CLI).
14
+
15
+ import { readFileSync } from "node:fs";
16
+ import { DatabaseSync } from "node:sqlite";
17
+
18
+ /** Row cap for raw queries (OMP MAX_RAW_QUERY_ROWS, trimmed). */
19
+ export const MAX_RAW_QUERY_ROWS = 200;
20
+ /** Rows shown under a bare table view. */
21
+ export const TABLE_PREVIEW_ROWS = 10;
22
+ /** Row cap for key-lookups. */
23
+ export const KEY_LOOKUP_LIMIT = 20;
24
+
25
+ export type SqliteSelector =
26
+ | { kind: "tables" }
27
+ | { kind: "table"; table: string }
28
+ | { kind: "rowid"; table: string; rowid: number }
29
+ | { kind: "key"; table: string; key: string; value: string }
30
+ | { kind: "query"; sql: string };
31
+
32
+ /**
33
+ * Parse a sqlite sub-selector (everything after the file path). Exported for
34
+ * tests. Empty → tables view. A numeric segment after a table is a rowid;
35
+ * `key=value` is a key lookup; a leading `?` or a SELECT/WITH/PRAGMA head is
36
+ * a raw query.
37
+ */
38
+ export function parseSqliteSelector(selector: string | undefined): SqliteSelector {
39
+ const trimmed = (selector ?? "").trim();
40
+ if (!trimmed) return { kind: "tables" };
41
+ // `?…` marks a query explicitly (the head guard still enforces read-only);
42
+ // a bare SELECT/WITH/PRAGMA head is accepted uncannily.
43
+ if (trimmed.startsWith("?")) return { kind: "query", sql: trimmed.slice(1).trim() };
44
+ if (/^(select|with|pragma)\b/i.test(trimmed)) return { kind: "query", sql: trimmed };
45
+ const parts = trimmed.split(":");
46
+ const table = parts[0]!.trim();
47
+ if (!table) throw new Error(`invalid sqlite selector "${trimmed}" — expected :table, :table:rowid, :table:key=value or :?SELECT`);
48
+ if (parts.length === 1) return { kind: "table", table };
49
+ const second = parts.slice(1).join(":").trim();
50
+ const rowid = /^\d+$/.exec(second);
51
+ if (rowid) return { kind: "rowid", table, rowid: Number(second) };
52
+ const kv = /^([A-Za-z_][\w]*)=(.*)$/s.exec(second);
53
+ if (kv) return { kind: "key", table, key: kv[1]!, value: kv[2]!.replace(/^"(.*)"$/s, "$1") };
54
+ throw new Error(`invalid sqlite selector "${second}" — use :${table}:<rowid>, :${table}:<key>=<value>, or :?SELECT …`);
55
+ }
56
+
57
+ /** Sniff: first 16 bytes are the SQLite magic header. */
58
+ export function isSqliteFile(absPath: string): boolean {
59
+ try {
60
+ const fd = readFileSync(absPath);
61
+ return fd.length >= 16 && fd.subarray(0, 16).equals(Buffer.from("SQLite format 3\0", "utf8"));
62
+ } catch {
63
+ return false;
64
+ }
65
+ }
66
+
67
+ /** Quote an SQL identifier (double the embedded quotes). */
68
+ function quoteIdent(name: string): string {
69
+ return `"${name.replaceAll('"', '""')}"`;
70
+ }
71
+
72
+ /** One row → aligned key/value lines (repo read style, `—` for null). */
73
+ function renderRow(row: Record<string, unknown>, columns: string[]): string {
74
+ return columns.map((c) => `${c}: ${row[c] === null || row[c] === undefined ? "—" : String(row[c])}`).join("\n");
75
+ }
76
+
77
+ /** Rows → aligned text table. */
78
+ function renderRows(columns: string[], rows: Record<string, unknown>[]): string {
79
+ const cells = rows.map((r) => columns.map((c) => (r[c] === null || r[c] === undefined ? "—" : String(r[c] ?? ""))));
80
+ const widths = columns.map((c, i) => Math.max(c.length, ...cells.map((row) => row[i]!.length)));
81
+ const line = (parts: string[]) => parts.map((p, i) => p.padEnd(widths[i]!)).join(" ").trimEnd();
82
+ return [line(columns), line(widths.map((w) => "─".repeat(w))), ...cells.map(line)].join("\n");
83
+ }
84
+
85
+ function columnsOf(db: DatabaseSync, table: string): string[] {
86
+ return (db.prepare(`PRAGMA table_info(${quoteIdent(table)})`).all() as Array<Record<string, unknown>>).map(
87
+ (c) => String(c.name),
88
+ );
89
+ }
90
+
91
+ function tableNames(db: DatabaseSync): string[] {
92
+ return (
93
+ db.prepare(`SELECT name FROM sqlite_master WHERE type='table' AND name NOT LIKE 'sqlite_%' ORDER BY name`).all() as Array<{
94
+ name: string;
95
+ }>
96
+ ).map((r) => r.name);
97
+ }
98
+
99
+ function countRows(db: DatabaseSync, table: string): number {
100
+ const row = db.prepare(`SELECT count(*) AS n FROM ${quoteIdent(table)}`).get() as { n: number };
101
+ return Number(row.n);
102
+ }
103
+
104
+ /** The single seam for tests (a runtime without node:sqlite can swap a CLI
105
+ * driver in here). Opens the db READ-ONLY; caller closes. */
106
+ export function openDatabase(path: string): DatabaseSync {
107
+ return new DatabaseSync(path, { readOnly: true });
108
+ }
109
+
110
+ /** Execute a parsed selector against the db. Returns model-facing text. */
111
+ export function executeSqliteView(db: DatabaseSync, sel: SqliteSelector, displayPath: string): string {
112
+ switch (sel.kind) {
113
+ case "tables": {
114
+ const names = tableNames(db);
115
+ if (names.length === 0) return `${displayPath} — no tables.`;
116
+ const parts = names.map((name) => {
117
+ const cols = columnsOf(db, name);
118
+ return `${name} · ${countRows(db, name)} rows · ${cols.join(", ")}`;
119
+ });
120
+ return `${displayPath} — ${names.length} table(s)\n${parts.join("\n")}`;
121
+ }
122
+ case "table": {
123
+ const names = tableNames(db);
124
+ if (!names.includes(sel.table)) {
125
+ return `no table "${sel.table}" in ${displayPath} — tables: ${names.join(", ") || "(none)"}`;
126
+ }
127
+ const cols = columnsOf(db, sel.table);
128
+ const info = db.prepare(`PRAGMA table_info(${quoteIdent(sel.table)})`).all() as Array<Record<string, unknown>>;
129
+ const schema = info
130
+ .map((c) => ` ${c.name} ${c.type || "ANY"}${Number(c.pk) ? " PRIMARY KEY" : ""}${Number(c.notnull) ? " NOT NULL" : ""}`)
131
+ .join("\n");
132
+ const rows = db
133
+ .prepare(`SELECT * FROM ${quoteIdent(sel.table)} LIMIT ${TABLE_PREVIEW_ROWS}`)
134
+ .all() as Array<Record<string, unknown>>;
135
+ const total = countRows(db, sel.table);
136
+ const footer = total > rows.length ? `\n[${rows.length} of ${total} rows — query with :${sel.table}:<rowid> or :?SELECT]` : "";
137
+ return `${displayPath} : ${sel.table} — ${total} rows\n${schema}\n\n${rows.length ? renderRows(cols, rows) : "(empty)"}${footer}`;
138
+ }
139
+ case "rowid": {
140
+ const cols = columnsOf(db, sel.table);
141
+ const row = db.prepare(`SELECT * FROM ${quoteIdent(sel.table)} WHERE rowid = ?`).get(sel.rowid) as
142
+ | Record<string, unknown>
143
+ | undefined;
144
+ if (!row) return `no row with rowid ${sel.rowid} in ${displayPath} : ${sel.table}`;
145
+ return `${displayPath} : ${sel.table} : rowid ${sel.rowid}\n${renderRow(row, cols)}`;
146
+ }
147
+ case "key": {
148
+ const cols = columnsOf(db, sel.table);
149
+ if (!cols.includes(sel.key)) {
150
+ return `no column "${sel.key}" in ${displayPath} : ${sel.table} — columns: ${cols.join(", ")}`;
151
+ }
152
+ const rows = db
153
+ .prepare(`SELECT * FROM ${quoteIdent(sel.table)} WHERE ${quoteIdent(sel.key)} = ? LIMIT ${KEY_LOOKUP_LIMIT}`)
154
+ .all(sel.value) as Array<Record<string, unknown>>;
155
+ if (rows.length === 0) return `no rows where ${sel.key} = "${sel.value}" in ${displayPath} : ${sel.table}`;
156
+ const body = rows.map((r) => renderRow(r, cols)).join("\n\n---\n\n");
157
+ const footer = rows.length >= KEY_LOOKUP_LIMIT ? `\n[stopped at ${KEY_LOOKUP_LIMIT} rows — narrow the key]` : "";
158
+ return `${displayPath} : ${sel.table} : ${sel.key}="${sel.value}" — ${rows.length} row(s)\n${body}${footer}`;
159
+ }
160
+ case "query": {
161
+ const head = sel.sql.trim().slice(0, 6).toUpperCase();
162
+ if (!/^(SELECT|WITH|PRAGMA)/.test(head)) {
163
+ throw new Error(`only read-only queries (SELECT/WITH/PRAGMA) — got "${sel.sql.slice(0, 40)}". Use bash for writes.`);
164
+ }
165
+ const stmt = db.prepare(sel.sql);
166
+ const columns = (stmt as unknown as { columns: () => Array<{ name: string }> }).columns().map((c) => c.name);
167
+ const rows = stmt.all() as Array<Record<string, unknown>>;
168
+ const total = rows.length;
169
+ const shown = rows.slice(0, MAX_RAW_QUERY_ROWS);
170
+ const footer = total > shown.length ? `\n[showing ${shown.length} of ${total} rows — add LIMIT/TARGET the query]` : "";
171
+ return `${displayPath} : query — ${total} row(s)\n${shown.length ? renderRows(columns, shown) : "(no rows)"}${footer}`;
172
+ }
173
+ }
174
+ }
175
+
176
+ /** Full read view for a sqlite path + selector. Opens/closes the db. */
177
+ export function readSqlite(absPath: string, selector: string | undefined, displayPath: string): string {
178
+ const sel = parseSqliteSelector(selector);
179
+ const db = openDatabase(absPath);
180
+ try {
181
+ return executeSqliteView(db, sel, displayPath);
182
+ } finally {
183
+ db.close();
184
+ }
185
+ }
@@ -20,6 +20,8 @@ export interface RepairSettings {
20
20
  editRetry: boolean;
21
21
  /** Destructive-bash + read-on-guessed-path guards. */
22
22
  guards: boolean;
23
+ /** Refuse write/edit on auto-generated files (lockfiles, dist, min.js). */
24
+ autoGenGuard: boolean;
23
25
  /** Auto-background long foreground bash calls. */
24
26
  autoBg: boolean;
25
27
  /** Foreground threshold (seconds) before auto-backgrounding. */
@@ -30,6 +32,7 @@ export const DEFAULT_REPAIR_SETTINGS: RepairSettings = {
30
32
  arguments: true,
31
33
  editRetry: true,
32
34
  guards: true,
35
+ autoGenGuard: true,
33
36
  autoBg: false,
34
37
  autoBgSecs: 120,
35
38
  };
@@ -55,7 +58,7 @@ function section(json: Record<string, unknown> | null, key: string): Record<stri
55
58
  /** Merge one settings layer's `repair` keys over out (field-wise override). */
56
59
  function mergeLayer(out: RepairSettings, json: Record<string, unknown> | null): void {
57
60
  const s = section(json, "repair");
58
- for (const key of ["arguments", "editRetry", "guards", "autoBg"] as const) {
61
+ for (const key of ["arguments", "editRetry", "guards", "autoGenGuard", "autoBg"] as const) {
59
62
  if (typeof s[key] === "boolean") out[key] = s[key];
60
63
  }
61
64
  if (typeof s.autoBgSecs === "number" && Number.isFinite(s.autoBgSecs)) {
@@ -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
  ]);
@@ -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
+ }