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,191 @@
|
|
|
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 { closeSync, openSync, readSync } 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. Reads ONLY those 16
|
|
58
|
+
* bytes (a whole-file read parked multi-GB databases in memory for a sniff). */
|
|
59
|
+
export function isSqliteFile(absPath: string): boolean {
|
|
60
|
+
let fd: number | undefined;
|
|
61
|
+
try {
|
|
62
|
+
fd = openSync(absPath, "r");
|
|
63
|
+
const head = Buffer.alloc(16);
|
|
64
|
+
const read = readSync(fd, head, 0, 16, 0);
|
|
65
|
+
return read >= 16 && head.equals(Buffer.from("SQLite format 3\0", "utf8"));
|
|
66
|
+
} catch {
|
|
67
|
+
return false;
|
|
68
|
+
} finally {
|
|
69
|
+
if (fd !== undefined) closeSync(fd);
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
/** Quote an SQL identifier (double the embedded quotes). */
|
|
74
|
+
function quoteIdent(name: string): string {
|
|
75
|
+
return `"${name.replaceAll('"', '""')}"`;
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
/** One row → aligned key/value lines (repo read style, `—` for null). */
|
|
79
|
+
function renderRow(row: Record<string, unknown>, columns: string[]): string {
|
|
80
|
+
return columns.map((c) => `${c}: ${row[c] === null || row[c] === undefined ? "—" : String(row[c])}`).join("\n");
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
/** Rows → aligned text table. */
|
|
84
|
+
function renderRows(columns: string[], rows: Record<string, unknown>[]): string {
|
|
85
|
+
const cells = rows.map((r) => columns.map((c) => (r[c] === null || r[c] === undefined ? "—" : String(r[c] ?? ""))));
|
|
86
|
+
const widths = columns.map((c, i) => Math.max(c.length, ...cells.map((row) => row[i]!.length)));
|
|
87
|
+
const line = (parts: string[]) => parts.map((p, i) => p.padEnd(widths[i]!)).join(" ").trimEnd();
|
|
88
|
+
return [line(columns), line(widths.map((w) => "─".repeat(w))), ...cells.map(line)].join("\n");
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
function columnsOf(db: DatabaseSync, table: string): string[] {
|
|
92
|
+
return (db.prepare(`PRAGMA table_info(${quoteIdent(table)})`).all() as Array<Record<string, unknown>>).map(
|
|
93
|
+
(c) => String(c.name),
|
|
94
|
+
);
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
function tableNames(db: DatabaseSync): string[] {
|
|
98
|
+
return (
|
|
99
|
+
db.prepare(`SELECT name FROM sqlite_master WHERE type='table' AND name NOT LIKE 'sqlite_%' ORDER BY name`).all() as Array<{
|
|
100
|
+
name: string;
|
|
101
|
+
}>
|
|
102
|
+
).map((r) => r.name);
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
function countRows(db: DatabaseSync, table: string): number {
|
|
106
|
+
const row = db.prepare(`SELECT count(*) AS n FROM ${quoteIdent(table)}`).get() as { n: number };
|
|
107
|
+
return Number(row.n);
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
/** The single seam for tests (a runtime without node:sqlite can swap a CLI
|
|
111
|
+
* driver in here). Opens the db READ-ONLY; caller closes. */
|
|
112
|
+
export function openDatabase(path: string): DatabaseSync {
|
|
113
|
+
return new DatabaseSync(path, { readOnly: true });
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
/** Execute a parsed selector against the db. Returns model-facing text. */
|
|
117
|
+
export function executeSqliteView(db: DatabaseSync, sel: SqliteSelector, displayPath: string): string {
|
|
118
|
+
switch (sel.kind) {
|
|
119
|
+
case "tables": {
|
|
120
|
+
const names = tableNames(db);
|
|
121
|
+
if (names.length === 0) return `${displayPath} — no tables.`;
|
|
122
|
+
const parts = names.map((name) => {
|
|
123
|
+
const cols = columnsOf(db, name);
|
|
124
|
+
return `${name} · ${countRows(db, name)} rows · ${cols.join(", ")}`;
|
|
125
|
+
});
|
|
126
|
+
return `${displayPath} — ${names.length} table(s)\n${parts.join("\n")}`;
|
|
127
|
+
}
|
|
128
|
+
case "table": {
|
|
129
|
+
const names = tableNames(db);
|
|
130
|
+
if (!names.includes(sel.table)) {
|
|
131
|
+
return `no table "${sel.table}" in ${displayPath} — tables: ${names.join(", ") || "(none)"}`;
|
|
132
|
+
}
|
|
133
|
+
const cols = columnsOf(db, sel.table);
|
|
134
|
+
const info = db.prepare(`PRAGMA table_info(${quoteIdent(sel.table)})`).all() as Array<Record<string, unknown>>;
|
|
135
|
+
const schema = info
|
|
136
|
+
.map((c) => ` ${c.name} ${c.type || "ANY"}${Number(c.pk) ? " PRIMARY KEY" : ""}${Number(c.notnull) ? " NOT NULL" : ""}`)
|
|
137
|
+
.join("\n");
|
|
138
|
+
const rows = db
|
|
139
|
+
.prepare(`SELECT * FROM ${quoteIdent(sel.table)} LIMIT ${TABLE_PREVIEW_ROWS}`)
|
|
140
|
+
.all() as Array<Record<string, unknown>>;
|
|
141
|
+
const total = countRows(db, sel.table);
|
|
142
|
+
const footer = total > rows.length ? `\n[${rows.length} of ${total} rows — query with :${sel.table}:<rowid> or :?SELECT]` : "";
|
|
143
|
+
return `${displayPath} : ${sel.table} — ${total} rows\n${schema}\n\n${rows.length ? renderRows(cols, rows) : "(empty)"}${footer}`;
|
|
144
|
+
}
|
|
145
|
+
case "rowid": {
|
|
146
|
+
const cols = columnsOf(db, sel.table);
|
|
147
|
+
const row = db.prepare(`SELECT * FROM ${quoteIdent(sel.table)} WHERE rowid = ?`).get(sel.rowid) as
|
|
148
|
+
| Record<string, unknown>
|
|
149
|
+
| undefined;
|
|
150
|
+
if (!row) return `no row with rowid ${sel.rowid} in ${displayPath} : ${sel.table}`;
|
|
151
|
+
return `${displayPath} : ${sel.table} : rowid ${sel.rowid}\n${renderRow(row, cols)}`;
|
|
152
|
+
}
|
|
153
|
+
case "key": {
|
|
154
|
+
const cols = columnsOf(db, sel.table);
|
|
155
|
+
if (!cols.includes(sel.key)) {
|
|
156
|
+
return `no column "${sel.key}" in ${displayPath} : ${sel.table} — columns: ${cols.join(", ")}`;
|
|
157
|
+
}
|
|
158
|
+
const rows = db
|
|
159
|
+
.prepare(`SELECT * FROM ${quoteIdent(sel.table)} WHERE ${quoteIdent(sel.key)} = ? LIMIT ${KEY_LOOKUP_LIMIT}`)
|
|
160
|
+
.all(sel.value) as Array<Record<string, unknown>>;
|
|
161
|
+
if (rows.length === 0) return `no rows where ${sel.key} = "${sel.value}" in ${displayPath} : ${sel.table}`;
|
|
162
|
+
const body = rows.map((r) => renderRow(r, cols)).join("\n\n---\n\n");
|
|
163
|
+
const footer = rows.length >= KEY_LOOKUP_LIMIT ? `\n[stopped at ${KEY_LOOKUP_LIMIT} rows — narrow the key]` : "";
|
|
164
|
+
return `${displayPath} : ${sel.table} : ${sel.key}="${sel.value}" — ${rows.length} row(s)\n${body}${footer}`;
|
|
165
|
+
}
|
|
166
|
+
case "query": {
|
|
167
|
+
const head = sel.sql.trim().slice(0, 6).toUpperCase();
|
|
168
|
+
if (!/^(SELECT|WITH|PRAGMA)/.test(head)) {
|
|
169
|
+
throw new Error(`only read-only queries (SELECT/WITH/PRAGMA) — got "${sel.sql.slice(0, 40)}". Use bash for writes.`);
|
|
170
|
+
}
|
|
171
|
+
const stmt = db.prepare(sel.sql);
|
|
172
|
+
const columns = (stmt as unknown as { columns: () => Array<{ name: string }> }).columns().map((c) => c.name);
|
|
173
|
+
const rows = stmt.all() as Array<Record<string, unknown>>;
|
|
174
|
+
const total = rows.length;
|
|
175
|
+
const shown = rows.slice(0, MAX_RAW_QUERY_ROWS);
|
|
176
|
+
const footer = total > shown.length ? `\n[showing ${shown.length} of ${total} rows — add LIMIT/TARGET the query]` : "";
|
|
177
|
+
return `${displayPath} : query — ${total} row(s)\n${shown.length ? renderRows(columns, shown) : "(no rows)"}${footer}`;
|
|
178
|
+
}
|
|
179
|
+
}
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
/** Full read view for a sqlite path + selector. Opens/closes the db. */
|
|
183
|
+
export function readSqlite(absPath: string, selector: string | undefined, displayPath: string): string {
|
|
184
|
+
const sel = parseSqliteSelector(selector);
|
|
185
|
+
const db = openDatabase(absPath);
|
|
186
|
+
try {
|
|
187
|
+
return executeSqliteView(db, sel, displayPath);
|
|
188
|
+
} finally {
|
|
189
|
+
db.close();
|
|
190
|
+
}
|
|
191
|
+
}
|
|
@@ -7,11 +7,16 @@
|
|
|
7
7
|
// (autoBg / autoBgSecs) are the exception: the wrapped bash description and
|
|
8
8
|
// the auto-background mechanics bind ONCE at module load, so those rows take
|
|
9
9
|
// effect on the next session.
|
|
10
|
+
//
|
|
11
|
+
// ponytail: the reader used to take a pi ExtensionContext, but every runtime
|
|
12
|
+
// call site lacked one at read time, leaving the trusted-project layer dead;
|
|
13
|
+
// cwd is the minimal honest input (pi's trust semantics come from
|
|
14
|
+
// lib/registry.js isProjectTrusted — the rule the other settings readers use).
|
|
10
15
|
|
|
11
16
|
import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs";
|
|
12
17
|
import os from "node:os";
|
|
13
18
|
import path from "node:path";
|
|
14
|
-
import
|
|
19
|
+
import { isProjectTrusted } from "../../../lib/registry.js";
|
|
15
20
|
|
|
16
21
|
export interface RepairSettings {
|
|
17
22
|
/** Schema-driven argument repair (invalid/truncated JSON, param aliases). */
|
|
@@ -20,6 +25,8 @@ export interface RepairSettings {
|
|
|
20
25
|
editRetry: boolean;
|
|
21
26
|
/** Destructive-bash + read-on-guessed-path guards. */
|
|
22
27
|
guards: boolean;
|
|
28
|
+
/** Refuse write/edit on auto-generated files (lockfiles, dist, min.js). */
|
|
29
|
+
autoGenGuard: boolean;
|
|
23
30
|
/** Auto-background long foreground bash calls. */
|
|
24
31
|
autoBg: boolean;
|
|
25
32
|
/** Foreground threshold (seconds) before auto-backgrounding. */
|
|
@@ -30,6 +37,7 @@ export const DEFAULT_REPAIR_SETTINGS: RepairSettings = {
|
|
|
30
37
|
arguments: true,
|
|
31
38
|
editRetry: true,
|
|
32
39
|
guards: true,
|
|
40
|
+
autoGenGuard: true,
|
|
33
41
|
autoBg: false,
|
|
34
42
|
autoBgSecs: 120,
|
|
35
43
|
};
|
|
@@ -55,7 +63,7 @@ function section(json: Record<string, unknown> | null, key: string): Record<stri
|
|
|
55
63
|
/** Merge one settings layer's `repair` keys over out (field-wise override). */
|
|
56
64
|
function mergeLayer(out: RepairSettings, json: Record<string, unknown> | null): void {
|
|
57
65
|
const s = section(json, "repair");
|
|
58
|
-
for (const key of ["arguments", "editRetry", "guards", "autoBg"] as const) {
|
|
66
|
+
for (const key of ["arguments", "editRetry", "guards", "autoGenGuard", "autoBg"] as const) {
|
|
59
67
|
if (typeof s[key] === "boolean") out[key] = s[key];
|
|
60
68
|
}
|
|
61
69
|
if (typeof s.autoBgSecs === "number" && Number.isFinite(s.autoBgSecs)) {
|
|
@@ -70,15 +78,21 @@ export function settingsPath(): string {
|
|
|
70
78
|
return path.join(agentDir(), "settings.json");
|
|
71
79
|
}
|
|
72
80
|
|
|
73
|
-
/** Effective repair settings: global agent-dir file ⊕ trusted project overlay.
|
|
74
|
-
|
|
81
|
+
/** Effective repair settings: global agent-dir file ⊕ trusted project overlay.
|
|
82
|
+
* `cwd` opts the caller into the project layer: only when <cwd> is TRUSTED
|
|
83
|
+
* does `<cwd>/.pi/settings.json` override the global file field-wise.
|
|
84
|
+
* Runtime call sites pass the execute/hook cwd; ctx-less calls (prepareArguments
|
|
85
|
+
* has none) read the global layer only. */
|
|
86
|
+
export function readRepairSettings(cwd?: string): RepairSettings {
|
|
75
87
|
const out: RepairSettings = { ...DEFAULT_REPAIR_SETTINGS };
|
|
76
88
|
mergeLayer(out, readJson(settingsPath()));
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
89
|
+
if (cwd) {
|
|
90
|
+
try {
|
|
91
|
+
if (isProjectTrusted(cwd)) {
|
|
92
|
+
mergeLayer(out, readJson(path.join(cwd, ".pi", "settings.json")));
|
|
93
|
+
}
|
|
94
|
+
} catch { /* untrusted or unreadable — global only */ }
|
|
95
|
+
}
|
|
82
96
|
return out;
|
|
83
97
|
}
|
|
84
98
|
|
|
@@ -44,6 +44,72 @@ function makeDeps(thresholdSecs = 0.05): { pi: any; deps: AutoBgDeps; messages:
|
|
|
44
44
|
|
|
45
45
|
const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));
|
|
46
46
|
|
|
47
|
+
describe("exit sweep across module reloads (globalThis indirection)", () => {
|
|
48
|
+
// node:test runs each file in its own process, so no other suite's sweep
|
|
49
|
+
// can unlink our fixtures. Restore the process's pre-test listener sets
|
|
50
|
+
// exactly (our handlers are closure-private, unreachable by identity).
|
|
51
|
+
const sigs = ["exit", "SIGTERM", "SIGINT"] as const;
|
|
52
|
+
let pre: Map<string, NodeJS.SignalsListener[]>;
|
|
53
|
+
after(() => {
|
|
54
|
+
delete (globalThis as any)[Symbol.for("ceulen.repair.bgExitSweep")];
|
|
55
|
+
delete (globalThis as any)[Symbol.for("ceulen.repair.bgExitSweep.armed")];
|
|
56
|
+
if (!pre) return;
|
|
57
|
+
for (const sig of pre.keys()) {
|
|
58
|
+
// "exit" is not a Signal but the runtime accepts any event name; the
|
|
59
|
+
// cast is the one place the typed overload can't express that.
|
|
60
|
+
const event = sig as NodeJS.Signals;
|
|
61
|
+
for (const l of process.listeners(event)) {
|
|
62
|
+
if (!pre.get(sig)!.includes(l)) process.removeListener(event, l);
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
});
|
|
66
|
+
|
|
67
|
+
it("sweeps the CURRENT module instance's job map, not just the first one", async () => {
|
|
68
|
+
const { writeFileSync, existsSync, mkdtempSync, rmSync } = await import("node:fs");
|
|
69
|
+
const { tmpdir } = await import("node:os");
|
|
70
|
+
const { join } = await import("node:path");
|
|
71
|
+
|
|
72
|
+
pre = new Map(sigs.map((s) => [s, process.listeners(s as NodeJS.Signals)]));
|
|
73
|
+
|
|
74
|
+
// Simulate /reload: a second load of the auto-bg module with a FRESH jobs
|
|
75
|
+
// map. The once-guard keeps listener count flat; the sweep must follow
|
|
76
|
+
// the slot's indirection instead of the first instance's closure.
|
|
77
|
+
const preExit = process.listeners("exit");
|
|
78
|
+
const added = () => process.listeners("exit").filter((l) => !preExit.includes(l));
|
|
79
|
+
const m1 = await import("../lib/auto-bg.js");
|
|
80
|
+
m1.installExitSweepForTests();
|
|
81
|
+
assert.equal(added().length, 1, "first load installs exactly one exit listener");
|
|
82
|
+
|
|
83
|
+
// tsx treats the query as part of the specifier (fresh module record);
|
|
84
|
+
// a non-literal specifier is the one way TS types it.
|
|
85
|
+
const m2 = await import("../lib/auto-bg.js?reload=2" as string);
|
|
86
|
+
m2.installExitSweepForTests();
|
|
87
|
+
assert.equal(added().length, 1, "second load must NOT stack a second listener");
|
|
88
|
+
|
|
89
|
+
// Register a live job in the SECOND instance's registry (a post-/reload
|
|
90
|
+
// job whose tmp log previously leaked at process death).
|
|
91
|
+
const dir = mkdtempSync(join(tmpdir(), "ceulen-repair-sweep-"));
|
|
92
|
+
const logPath = join(dir, "ceulen-repair-bg-second.log");
|
|
93
|
+
writeFileSync(logPath, "leak probe");
|
|
94
|
+
m2.registerBgJobForTests({ id: "bg-test", logPath, logTruncated: false });
|
|
95
|
+
|
|
96
|
+
// The first instance must NOT know about the second's job (proves the
|
|
97
|
+
// pre-fix bug shape: its closure saw only its own, empty, map).
|
|
98
|
+
assert.equal(m1.bgJobCount(), 0, "first instance's map is separate");
|
|
99
|
+
|
|
100
|
+
try {
|
|
101
|
+
// Fire ONLY the module's registered 'exit' handler, exactly as Node
|
|
102
|
+
// would invoke it at process death.
|
|
103
|
+
for (const l of added() as Array<(c: number) => void>) l(0);
|
|
104
|
+
|
|
105
|
+
assert.equal(existsSync(logPath), false, "post-reload job's tmp log swept at exit");
|
|
106
|
+
} finally {
|
|
107
|
+
rmSync(dir, { recursive: true, force: true });
|
|
108
|
+
}
|
|
109
|
+
});
|
|
110
|
+
});
|
|
111
|
+
|
|
112
|
+
|
|
47
113
|
// Logs the lib deliberately KEEPS (truncated ≥5MB) outlive the job by design —
|
|
48
114
|
// track the ones our tests create and remove them at suite end so runs don't
|
|
49
115
|
// leak 5MB files into the shared tmpdir.
|
|
@@ -0,0 +1,214 @@
|
|
|
1
|
+
// Regression suite for the 2026-10-07 hardening round (reviewer findings):
|
|
2
|
+
// A1 archive member+range reads, A2 guard × archive-member reads, A4 tar
|
|
3
|
+
// option-injection gate, A6 auto-gen guard rel-path correctness, A9 ascii
|
|
4
|
+
// rename-arrow target paths. index.ts helpers are driven through the real
|
|
5
|
+
// module wiring where practical (guard-selector.test.ts precedent).
|
|
6
|
+
|
|
7
|
+
import assert from "node:assert/strict";
|
|
8
|
+
import { execFileSync } from "node:child_process";
|
|
9
|
+
import { mkdtempSync, mkdirSync, writeFileSync, rmSync } from "node:fs";
|
|
10
|
+
import { mkdtemp, rm, writeFile } from "node:fs/promises";
|
|
11
|
+
import { tmpdir } from "node:os";
|
|
12
|
+
import path from "node:path";
|
|
13
|
+
import { after, before, describe, it } from "node:test";
|
|
14
|
+
import { matchMember, readArchiveMember, archiveKind } from "../lib/read-archive.js";
|
|
15
|
+
import { checkAutoGenerated } from "../lib/auto-generated.js";
|
|
16
|
+
import { applySpecialView } from "../index.js";
|
|
17
|
+
import { parsePatch } from "../lib/patch.js";
|
|
18
|
+
|
|
19
|
+
const dir = mkdtempSync(path.join(tmpdir(), "ceulen-repair-hardening-"));
|
|
20
|
+
after(() => rmSync(dir, { recursive: true, force: true }));
|
|
21
|
+
|
|
22
|
+
// ── A1: member + line ranges ────────────────────────────────────────────────
|
|
23
|
+
|
|
24
|
+
describe("archive member+range (A1)", () => {
|
|
25
|
+
const proj = path.join(dir, "a1");
|
|
26
|
+
const archive = path.join(proj, "pkg.tgz");
|
|
27
|
+
before(() => {
|
|
28
|
+
mkdirSync(proj, { recursive: true });
|
|
29
|
+
writeFileSync(path.join(proj, "src.ts"), "ignored on disk\n");
|
|
30
|
+
execFileSync("tar", ["-czf", archive, "-C", proj, "src.ts"]);
|
|
31
|
+
// Overwrite the MEMBER content so the disk copy can't mask a failure.
|
|
32
|
+
writeFileSync(path.join(dir, "member-body.txt"), "one\ntwo\nthree\nfour\nfive\n");
|
|
33
|
+
execFileSync("tar", ["-czf", archive, "-C", dir, "member-body.txt"]);
|
|
34
|
+
rmSync(path.join(dir, "member-body.txt"));
|
|
35
|
+
});
|
|
36
|
+
|
|
37
|
+
it("pkg.tgz:member:50-80 reads the real member, sliced — not an error", () => {
|
|
38
|
+
const out = applySpecialView("pkg.tgz:member-body.txt:2-3", proj);
|
|
39
|
+
assert.ok(out, "special view triggered");
|
|
40
|
+
assert.match(out!.text, /member-body\.txt/);
|
|
41
|
+
assert.match(out!.text, /two/);
|
|
42
|
+
assert.match(out!.text, /three/);
|
|
43
|
+
assert.doesNotMatch(out!.text, /four|five/);
|
|
44
|
+
assert.doesNotMatch(out!.text, /no member matching/);
|
|
45
|
+
});
|
|
46
|
+
|
|
47
|
+
it("member without a range is unchanged", () => {
|
|
48
|
+
const out = applySpecialView("pkg.tgz:member-body.txt", proj);
|
|
49
|
+
assert.ok(out);
|
|
50
|
+
assert.match(out!.text, /one/);
|
|
51
|
+
assert.match(out!.text, /five/);
|
|
52
|
+
});
|
|
53
|
+
|
|
54
|
+
it("a bare-number member does NOT peel as a selector", () => {
|
|
55
|
+
// A member literally named "123" parses as a line selector — it must stay
|
|
56
|
+
// whole for the member lookup (no phantom "" member + sliced error text).
|
|
57
|
+
writeFileSync(path.join(dir, "123"), "numeric member\n");
|
|
58
|
+
execFileSync("tar", ["-czf", path.join(proj, "nums.tgz"), "-C", dir, "123"]);
|
|
59
|
+
const out = applySpecialView(`nums.tgz:123`, proj);
|
|
60
|
+
assert.ok(out);
|
|
61
|
+
assert.match(out!.text, /123/);
|
|
62
|
+
assert.match(out!.text, /numeric member/);
|
|
63
|
+
rmSync(path.join(dir, "123"));
|
|
64
|
+
});
|
|
65
|
+
|
|
66
|
+
it("tail selector :-2 works over the member body", () => {
|
|
67
|
+
const out = applySpecialView("pkg.tgz:member-body.txt:-2", proj);
|
|
68
|
+
assert.ok(out);
|
|
69
|
+
assert.match(out!.text, /four/);
|
|
70
|
+
assert.match(out!.text, /five/);
|
|
71
|
+
assert.doesNotMatch(out!.text, /one\n|two\n|three\n/);
|
|
72
|
+
});
|
|
73
|
+
});
|
|
74
|
+
|
|
75
|
+
// ── A2: guard × archive-member reads ────────────────────────────────────────
|
|
76
|
+
|
|
77
|
+
describe("read guard × archive-member reads (A2)", () => {
|
|
78
|
+
it("pkg.tgz:src/x.ts and pkg.tgz:src/x.ts:50-80 pass the guard when the archive exists", async () => {
|
|
79
|
+
const { default: repairModule } = await import("../index.js");
|
|
80
|
+
const proj = await mkdtemp(path.join(tmpdir(), "repair-guard-arch-"));
|
|
81
|
+
const archive = path.join(proj, "pkg.tgz");
|
|
82
|
+
writeFileSync(path.join(proj, "x.ts"), "member\n");
|
|
83
|
+
execFileSync("tar", ["-czf", archive, "-C", proj, "x.ts"]);
|
|
84
|
+
const handlers: Record<string, (event: unknown, ctx: unknown) => unknown> = {};
|
|
85
|
+
const orig = process.env.PI_CODING_AGENT_DIR;
|
|
86
|
+
process.env.PI_CODING_AGENT_DIR = proj;
|
|
87
|
+
try {
|
|
88
|
+
repairModule({
|
|
89
|
+
on: (event: string, handler: (event: unknown, ctx: unknown) => unknown) => { handlers[event] = handler; },
|
|
90
|
+
registerTool: () => {},
|
|
91
|
+
registerCommand: () => {},
|
|
92
|
+
} as never);
|
|
93
|
+
const call = (p: string) =>
|
|
94
|
+
handlers.tool_call!({ toolName: "read", input: { path: p } }, { cwd: proj }) as { block: boolean } | undefined;
|
|
95
|
+
assert.equal(await call("pkg.tgz:x.ts"), undefined, "member read not blocked");
|
|
96
|
+
assert.equal(await call("pkg.tgz:x.ts:1-2"), undefined, "member+range read not blocked");
|
|
97
|
+
assert.equal(await call("pkg.tgz:missing.ts"), undefined, "missing member in an EXISTING archive still passes (the archive view handles it)");
|
|
98
|
+
const blocked = await call("missing.tgz:x.ts") as { block: boolean } | undefined;
|
|
99
|
+
assert.ok(blocked?.block, "a missing .ts-shaped path still blocks");
|
|
100
|
+
} finally {
|
|
101
|
+
if (orig === undefined) delete process.env.PI_CODING_AGENT_DIR;
|
|
102
|
+
else process.env.PI_CODING_AGENT_DIR = orig;
|
|
103
|
+
await rm(proj, { recursive: true, force: true });
|
|
104
|
+
}
|
|
105
|
+
});
|
|
106
|
+
});
|
|
107
|
+
|
|
108
|
+
// ── A4: tar option-injection gate ───────────────────────────────────────────
|
|
109
|
+
|
|
110
|
+
describe("archive option-injection gate (A4)", () => {
|
|
111
|
+
it("matchMember still matches normal members", () => {
|
|
112
|
+
assert.deepEqual(matchMember(["a.ts", "b.ts"], "a.ts"), { member: "a.ts", via: "exact" });
|
|
113
|
+
});
|
|
114
|
+
|
|
115
|
+
it("readArchiveMember refuses a dash-leading member before any spawn", () => {
|
|
116
|
+
// Build an archive with a member named "--checkpoint-action=exec=evil".
|
|
117
|
+
// bsdtar/GNU tar only treats it as an option during EXTRACTION with
|
|
118
|
+
// positional args — exactly what extractMember does — so listing it works.
|
|
119
|
+
const evilDir = path.join(dir, "a4");
|
|
120
|
+
mkdirSync(evilDir, { recursive: true });
|
|
121
|
+
const archive = path.join(evilDir, "evil.tgz");
|
|
122
|
+
const staging = path.join(evilDir, "stage");
|
|
123
|
+
mkdirSync(staging, { recursive: true });
|
|
124
|
+
writeFileSync(path.join(staging, "safe.txt"), "safe\n");
|
|
125
|
+
execFileSync("tar", ["-czf", path.join(evilDir, "plain.tgz"), "-C", staging, "safe.txt"]);
|
|
126
|
+
// Craft the dash member via a tar file listing manipulation: rename inside
|
|
127
|
+
// a ustar header is fiddly — instead create the file and rely on tar -C.
|
|
128
|
+
const evilFile = path.join(staging, "--checkpoint-action=exec=echo pwned");
|
|
129
|
+
writeFileSync(evilFile, "evil\n");
|
|
130
|
+
execFileSync("tar", ["-czf", archive, "-C", staging, "--", "--checkpoint-action=exec=echo pwned", "safe.txt"]);
|
|
131
|
+
const members = ["--checkpoint-action=exec=echo pwned", "safe.txt"];
|
|
132
|
+
assert.equal(archiveKind(archive), "tgz");
|
|
133
|
+
const out = readArchiveMember(archive, "tgz", "--checkpoint-action=exec=echo pwned", "evil.tgz");
|
|
134
|
+
assert.match(out.text, /refusing member/);
|
|
135
|
+
assert.match(out.text, /parsed as tar\/unzip options/);
|
|
136
|
+
void members;
|
|
137
|
+
});
|
|
138
|
+
|
|
139
|
+
it("a dash-leading request through the matcher surfaces the gate", () => {
|
|
140
|
+
const out = readArchiveMember(path.join(dir, "a4", "plain.tgz"), "tgz", "--checkpoint-action=exec=echo pwned", "p.tgz");
|
|
141
|
+
assert.match(out.text, /refusing member|no member matching/);
|
|
142
|
+
});
|
|
143
|
+
});
|
|
144
|
+
|
|
145
|
+
// ── A6: auto-gen guard rel path ─────────────────────────────────────────────
|
|
146
|
+
|
|
147
|
+
describe("auto-generated rel-path correctness (A6)", () => {
|
|
148
|
+
const cwd = path.join(dir, "a6", "proj");
|
|
149
|
+
before(() => mkdirSync(path.join(cwd, "dist"), { recursive: true }));
|
|
150
|
+
|
|
151
|
+
it("in-cwd absolute paths still match", () => {
|
|
152
|
+
assert.ok(checkAutoGenerated(path.join(cwd, "package-lock.json"), cwd));
|
|
153
|
+
assert.ok(checkAutoGenerated(path.join(cwd, "dist", "x.js"), cwd));
|
|
154
|
+
});
|
|
155
|
+
|
|
156
|
+
it("an absolute path OUTSIDE cwd matches nothing (no garbage rel)", () => {
|
|
157
|
+
const outside = path.resolve(cwd, "../elsewhere/dist/x.js");
|
|
158
|
+
assert.ok(!outside.startsWith(cwd));
|
|
159
|
+
assert.equal(checkAutoGenerated(outside, cwd), null);
|
|
160
|
+
});
|
|
161
|
+
|
|
162
|
+
it("cwd itself resolves to '.' and matches nothing", () => {
|
|
163
|
+
assert.equal(checkAutoGenerated(cwd, cwd), null);
|
|
164
|
+
});
|
|
165
|
+
|
|
166
|
+
it("relative inputs are matched as given", () => {
|
|
167
|
+
assert.ok(checkAutoGenerated("package-lock.json", cwd));
|
|
168
|
+
assert.equal(checkAutoGenerated("src/app.ts", cwd), null);
|
|
169
|
+
});
|
|
170
|
+
});
|
|
171
|
+
|
|
172
|
+
// ── A9: ascii rename arrow in patch target paths ────────────────────────────
|
|
173
|
+
|
|
174
|
+
describe("patch rename arrows (A9)", () => {
|
|
175
|
+
it("parsePatch accepts both arrows (lib contract)", () => {
|
|
176
|
+
assert.equal(parsePatch("*** Update File: a.ts → b.ts\n*** End Patch").ops[0]!.movePath, "b.ts");
|
|
177
|
+
assert.equal(parsePatch("*** Update File: a.ts -> b.ts\n*** End Patch").ops[0]!.movePath, "b.ts");
|
|
178
|
+
});
|
|
179
|
+
|
|
180
|
+
it("the guard/mtime target parser yields the SOURCE path for both arrows", async () => {
|
|
181
|
+
// parsePatchTargetPaths is module-private; drive it through the wrapper:
|
|
182
|
+
// an auto-gen-guarded RENAME with the ascii arrow must be refused because
|
|
183
|
+
// the SOURCE (a lockfile) is the file being touched.
|
|
184
|
+
const { default: repairModule } = await import("../index.js");
|
|
185
|
+
const proj = await mkdtemp(path.join(tmpdir(), "repair-arrow-"));
|
|
186
|
+
const orig = process.env.PI_CODING_AGENT_DIR;
|
|
187
|
+
process.env.PI_CODING_AGENT_DIR = proj;
|
|
188
|
+
const tools: any[] = [];
|
|
189
|
+
try {
|
|
190
|
+
repairModule({
|
|
191
|
+
on: () => {},
|
|
192
|
+
registerTool: (def: any) => tools.push(def),
|
|
193
|
+
registerCommand: () => {},
|
|
194
|
+
} as never);
|
|
195
|
+
const applyPatch = tools.find((t) => t.name === "apply_patch");
|
|
196
|
+
assert.ok(applyPatch, "apply_patch registered");
|
|
197
|
+
for (const arrow of ["→", "->"]) {
|
|
198
|
+
const res = await applyPatch.execute(
|
|
199
|
+
"t1",
|
|
200
|
+
{ patch: `*** Begin Patch\n*** Update File: package-lock.json ${arrow} package-lock2.json\n@@ x\n-y\n+z\n*** End Patch` },
|
|
201
|
+
undefined,
|
|
202
|
+
undefined,
|
|
203
|
+
{ cwd: proj },
|
|
204
|
+
);
|
|
205
|
+
assert.equal(res.isError, true, `ascii arrow: rename of a lockfile refused (${arrow})`);
|
|
206
|
+
assert.match(res.content[0].text, /auto-generated/);
|
|
207
|
+
}
|
|
208
|
+
} finally {
|
|
209
|
+
if (orig === undefined) delete process.env.PI_CODING_AGENT_DIR;
|
|
210
|
+
else process.env.PI_CODING_AGENT_DIR = orig;
|
|
211
|
+
await rm(proj, { recursive: true, force: true });
|
|
212
|
+
}
|
|
213
|
+
});
|
|
214
|
+
});
|