ceulen 0.13.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 +42 -0
- package/extensions/modules/a2a/lib/config.ts +15 -1
- package/extensions/modules/a2a/test/config.test.ts +27 -0
- 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 +10 -1
- package/extensions/modules/jfind/lib/cascade.ts +15 -1
- package/extensions/modules/jfind/lib/lexical.ts +18 -6
- package/extensions/modules/jfind/lib/tree.ts +34 -4
- package/extensions/modules/jfind/test/cascade.test.ts +56 -1
- package/extensions/modules/repair/configPanel.ts +11 -8
- package/extensions/modules/repair/index.ts +58 -25
- package/extensions/modules/repair/lib/auto-bg.ts +45 -2
- package/extensions/modules/repair/lib/auto-generated.ts +14 -4
- package/extensions/modules/repair/lib/read-archive.ts +14 -0
- package/extensions/modules/repair/lib/read-sqlite.ts +10 -4
- package/extensions/modules/repair/lib/settings.ts +19 -8
- 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/settings.test.ts +52 -13
- package/extensions/modules/shells/index.ts +31 -14
- package/extensions/modules/shells/lib/sessions.ts +76 -8
- package/extensions/modules/shells/test/output.test.ts +130 -0
- package/extensions/modules/shells/test/sessions.test.ts +127 -5
- package/extensions/modules/web/lib/pdf.ts +4 -2
- package/extensions/modules/web/test/pdf.test.ts +84 -0
- package/package.json +1 -1
|
@@ -115,8 +115,9 @@ function applyReadSelector(args: Record<string, unknown>, cwd: string): unknown
|
|
|
115
115
|
/** Peel `db.sqlite:users` / `pkg.tgz:src/x.ts:50-80` for sqlite/archive
|
|
116
116
|
* views. Returns the model-facing text result, or null when the path is
|
|
117
117
|
* neither (caller falls through to the built-in read). The stem must exist
|
|
118
|
-
* (the caller probes the literal path first — literal-wins preserved).
|
|
119
|
-
|
|
118
|
+
* (the caller probes the literal path first — literal-wins preserved).
|
|
119
|
+
* Exported for tests. */
|
|
120
|
+
export function applySpecialView(rawPath: string, cwd: string): { text: string } | null {
|
|
120
121
|
// Special-view peel: the LONGEST existing prefix path split at colons is
|
|
121
122
|
// the stem; the remainder is the sqlite sub-selector or archive member
|
|
122
123
|
// (+ optional line ranges). peelPathSelector can't do this — its grammar
|
|
@@ -135,7 +136,6 @@ function applySpecialView(rawPath: string, cwd: string): { text: string } | null
|
|
|
135
136
|
}
|
|
136
137
|
if (!stem) return null;
|
|
137
138
|
const stemAbs = resolvePath(cwd, stem);
|
|
138
|
-
const segments = remainder.split(":");
|
|
139
139
|
|
|
140
140
|
if (isSqliteFile(stemAbs)) {
|
|
141
141
|
try {
|
|
@@ -149,17 +149,27 @@ function applySpecialView(rawPath: string, cwd: string): { text: string } | null
|
|
|
149
149
|
const kind = archiveKind(stem);
|
|
150
150
|
if (kind) {
|
|
151
151
|
if (!remainder) return { text: readArchiveListing(stemAbs, kind, stem).text };
|
|
152
|
-
|
|
153
|
-
//
|
|
154
|
-
//
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
152
|
+
// Peel the trailing lines-selector FIRST (`src/x.ts:50-80`): the member
|
|
153
|
+
// lookup must see `src/x.ts`, not the raw remainder with the `:50-80`
|
|
154
|
+
// suffix (which matchMember reports as "no member matching").
|
|
155
|
+
let member = remainder;
|
|
156
|
+
let selector: ParsedSelector | undefined;
|
|
157
|
+
const memberParsed = peelPathSelector(remainder);
|
|
158
|
+
if (memberParsed.selector) {
|
|
159
|
+
member = memberParsed.stem;
|
|
160
|
+
selector = memberParsed.selector;
|
|
161
|
+
}
|
|
162
|
+
const res = readArchiveMember(stemAbs, kind, member, stem);
|
|
163
|
+
// Line ranges slice the member body (line 1 of the result text is the
|
|
164
|
+
// path header); `:raw` compounds ride the same slicer via the raw range.
|
|
165
|
+
if (selector && selector.kind !== "raw" && selector.kind !== "none") {
|
|
166
|
+
const lines = res.text.split("\n");
|
|
167
|
+
if (lines.length > 1 && lines[lines.length - 1] === "") lines.pop();
|
|
168
|
+
const resolved = selector.kind === "tail"
|
|
169
|
+
? resolveTailSelector(selector, lines.length - 1)
|
|
170
|
+
: selector;
|
|
171
|
+
const sliced = sliceMemberLines(lines, resolved);
|
|
172
|
+
if (sliced !== null) return { text: sliced };
|
|
163
173
|
}
|
|
164
174
|
return { text: res.text };
|
|
165
175
|
}
|
|
@@ -298,23 +308,26 @@ async function recordMutatedMtimes(toolName: string, params: any, cwd: string):
|
|
|
298
308
|
}
|
|
299
309
|
}
|
|
300
310
|
|
|
301
|
-
/** V4D patch targets: `*** Update File: <path>` / Add / Delete / rename
|
|
311
|
+
/** V4D patch targets: `*** Update File: <path>` / Add / Delete / rename
|
|
312
|
+
* (both rename arrows — parseFileHeader accepts unicode `→` AND ascii `->`,
|
|
313
|
+
* so the auto-gen guard + mtime refresh must too). */
|
|
302
314
|
function parsePatchTargetPaths(patch: string): string[] {
|
|
303
315
|
const out: string[] = [];
|
|
304
|
-
for (const m of patch.matchAll(/^\*{3} (?:Add|Delete|Update) File: (.+?)(
|
|
316
|
+
for (const m of patch.matchAll(/^\*{3} (?:Add|Delete|Update) File: (.+?)(?:\s*(?:→|->)\s*.+)?$/gm)) {
|
|
305
317
|
const target = m[1].trim();
|
|
306
|
-
if (target && !target.includes("://")) out.push(target
|
|
318
|
+
if (target && !target.includes("://")) out.push(target);
|
|
307
319
|
}
|
|
308
320
|
return out;
|
|
309
321
|
}
|
|
310
322
|
|
|
311
323
|
/** Auto-generated write guard (OMP auto-generated-guard): refuse write/edit
|
|
312
324
|
* on generated files before the write lands. Returns the refusal text, or
|
|
313
|
-
* undefined (allowed). Setting-gated via repair.autoGenGuard (default on
|
|
325
|
+
* undefined (allowed). Setting-gated via repair.autoGenGuard (default on;
|
|
326
|
+
* the cwd threads the trusted-project settings layer). */
|
|
314
327
|
function guardAutoGenerated(toolName: string, params: any, cwd: string): string | undefined {
|
|
315
|
-
if (!readRepairSettings().autoGenGuard) return undefined;
|
|
328
|
+
if (!readRepairSettings(cwd).autoGenGuard) return undefined;
|
|
316
329
|
const paths: string[] = [];
|
|
317
|
-
if ((toolName === "write" || toolName === "edit") && isRecord(params) && typeof params.path === "string") {
|
|
330
|
+
if ((toolName === "write" || toolName === "edit" || toolName === "str_replace_editor") && isRecord(params) && typeof params.path === "string") {
|
|
318
331
|
paths.push(params.path);
|
|
319
332
|
}
|
|
320
333
|
if (toolName === "apply_patch" && isRecord(params) && typeof params.patch === "string") {
|
|
@@ -425,7 +438,10 @@ export function wrapToolDefinition(
|
|
|
425
438
|
// Deviation from upstream: the edit retry/escalation block is gated on the
|
|
426
439
|
// `repair.editRetry` toggle. Read-notice decontamination and the no-op guard
|
|
427
440
|
// stay unconditional (upstream: always on — both are deterministic and safe).
|
|
428
|
-
|
|
441
|
+
// The retry gate receives the execute-time cwd so it honors the trusted
|
|
442
|
+
// project settings layer (prepareArguments has no ctx — the `arguments`
|
|
443
|
+
// toggle stays global-layer only, a documented ceiling).
|
|
444
|
+
shouldEditRetry: (cwd: string) => boolean = () => true,
|
|
429
445
|
): any {
|
|
430
446
|
return {
|
|
431
447
|
...base,
|
|
@@ -574,7 +590,7 @@ export function wrapToolDefinition(
|
|
|
574
590
|
return result;
|
|
575
591
|
} catch (catchedErr: any) {
|
|
576
592
|
let err: any = catchedErr;
|
|
577
|
-
if (!shouldEditRetry()) throw err;
|
|
593
|
+
if (!shouldEditRetry(cwd)) throw err;
|
|
578
594
|
const initialMessage: string = err?.message ? String(err.message) : "";
|
|
579
595
|
if (!isEditMismatchError(initialMessage)) throw err;
|
|
580
596
|
|
|
@@ -675,11 +691,13 @@ export default function repairModule(pi: ExtensionAPI) {
|
|
|
675
691
|
...wrapToolDefinition(
|
|
676
692
|
template,
|
|
677
693
|
factory,
|
|
694
|
+
// ponytail: prepareArguments has no ctx/cwd — the `arguments` toggle
|
|
695
|
+
// reads the global layer only; ceiling is host-level (no ctx in arg prep).
|
|
678
696
|
() => readRepairSettings().arguments,
|
|
679
697
|
onRepair,
|
|
680
698
|
editMismatchCounts,
|
|
681
699
|
() => pi.getActiveTools(),
|
|
682
|
-
() => readRepairSettings().editRetry,
|
|
700
|
+
(cwd: string) => readRepairSettings(cwd).editRetry,
|
|
683
701
|
),
|
|
684
702
|
defaultActive: !disabled.has(template.name),
|
|
685
703
|
});
|
|
@@ -777,7 +795,7 @@ export default function repairModule(pi: ExtensionAPI) {
|
|
|
777
795
|
// Upstream gated these on a detected family; repair is the model-agnostic
|
|
778
796
|
// layer here, so the guards are ungated (only the `repair.guards` toggle). ──
|
|
779
797
|
pi.on("tool_call", (event, ctx) => {
|
|
780
|
-
if (!readRepairSettings().guards) return;
|
|
798
|
+
if (!readRepairSettings(ctx?.cwd).guards) return;
|
|
781
799
|
if (event.toolName === "bash") {
|
|
782
800
|
const command = isRecord(event.input) ? event.input.command : undefined;
|
|
783
801
|
const danger = checkDangerousCommand(command);
|
|
@@ -796,6 +814,21 @@ export default function repairModule(pi: ExtensionAPI) {
|
|
|
796
814
|
const peeled = peelPathSelector(filePath);
|
|
797
815
|
if (peeled.selector) probe = peeled.stem;
|
|
798
816
|
} catch { /* invalid selector — keep the raw path */ }
|
|
817
|
+
// Archive-member reads (`pkg.tgz:src/x.ts`, optionally + `:50-80`) are
|
|
818
|
+
// an ADVERTISED read grammar: the stem probe still carries the member
|
|
819
|
+
// suffix, so it "doesn't exist" and the guard would block the module's
|
|
820
|
+
// own documented form. Mirror applySpecialView: when the longest
|
|
821
|
+
// existing colon-prefix is an archive file, probe that stem.
|
|
822
|
+
if (probe.includes(":")) {
|
|
823
|
+
const parts = probe.split(":");
|
|
824
|
+
for (let take = parts.length - 1; take >= 1; take--) {
|
|
825
|
+
const candidate = parts.slice(0, take).join(":");
|
|
826
|
+
if (existsSync(resolvePath(ctx.cwd, candidate)) && archiveKind(candidate)) {
|
|
827
|
+
probe = candidate;
|
|
828
|
+
break;
|
|
829
|
+
}
|
|
830
|
+
}
|
|
831
|
+
}
|
|
799
832
|
}
|
|
800
833
|
if (filePath && looksLikeCodePath(probe) && !existsSync(resolvePath(ctx.cwd, probe))) {
|
|
801
834
|
const filename = filePath.split("/").pop() ?? filePath;
|
|
@@ -810,7 +843,7 @@ export default function repairModule(pi: ExtensionAPI) {
|
|
|
810
843
|
pi.registerCommand("repair", {
|
|
811
844
|
description: "Show tool-hardening status: repair counts, guards, bash auto-background.",
|
|
812
845
|
handler: async (_args, ctx) => {
|
|
813
|
-
const live = readRepairSettings();
|
|
846
|
+
const live = readRepairSettings(ctx?.cwd);
|
|
814
847
|
const total = [...repairCounts.values()].reduce((a, b) => a + b, 0);
|
|
815
848
|
const lines = [
|
|
816
849
|
"## repair status",
|
|
@@ -93,16 +93,59 @@ export function activeBgLogPaths(): string[] {
|
|
|
93
93
|
return [...jobs.values()].map((j) => j.logPath);
|
|
94
94
|
}
|
|
95
95
|
|
|
96
|
+
// ponytail: test-only seam for the reload-sweep test (a real second load can't
|
|
97
|
+
// run in one tsx process without re-import machinery); upgrade path is none —
|
|
98
|
+
// delete with the test.
|
|
99
|
+
/** Publish the module's registry on the globalThis slot and install the
|
|
100
|
+
* process sweep, exactly as wrapWithAutoBg does at module use time. */
|
|
101
|
+
export function installExitSweepForTests(): void {
|
|
102
|
+
installExitSweep();
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
/** Register a live job directly (sweeper fixture — skips the exec plumbing). */
|
|
106
|
+
export function registerBgJobForTests(job: {
|
|
107
|
+
id: string;
|
|
108
|
+
logPath: string;
|
|
109
|
+
logTruncated?: boolean;
|
|
110
|
+
}): void {
|
|
111
|
+
jobs.set(job.id, {
|
|
112
|
+
id: job.id,
|
|
113
|
+
command: "test",
|
|
114
|
+
controller: new AbortController(),
|
|
115
|
+
logPath: job.logPath,
|
|
116
|
+
tail: "",
|
|
117
|
+
logBytes: 0,
|
|
118
|
+
logTruncated: job.logTruncated ?? false,
|
|
119
|
+
});
|
|
120
|
+
}
|
|
121
|
+
|
|
96
122
|
// Process-death sweep: if pi dies while a job is live (SIGTERM, crash),
|
|
97
123
|
// finishJob never runs and the log file would leak. Sync unlink is the only
|
|
98
124
|
// thing allowed in an 'exit' handler. Hard SIGKILL remains uncleanable (tmp
|
|
99
125
|
// cleaners bound it).
|
|
100
126
|
let exitSweepInstalled = false;
|
|
101
127
|
function installExitSweep(): void {
|
|
102
|
-
|
|
128
|
+
// Key the once-guard on a globalThis slot: a module-level flag RESETS on
|
|
129
|
+
// /reload (fresh module instance) and then stacks duplicate exit/SIGTERM
|
|
130
|
+
// listeners on the same shared process (the theme-slot pattern).
|
|
131
|
+
const key = Symbol.for("ceulen.repair.bgExitSweep");
|
|
132
|
+
const armed = Symbol.for("ceulen.repair.bgExitSweep.armed");
|
|
133
|
+
// Registry indirection: every module load publishes its OWN jobs map, so the
|
|
134
|
+
// single installed sweep reads the CURRENT instance's registry. Without it
|
|
135
|
+
// the closure pins the first load's map and post-/reload jobs leak their
|
|
136
|
+
// tmp logs at process death. The armed marker lives in its own slot so it
|
|
137
|
+
// survives the swap (a marker inside the swapped object would re-arm on
|
|
138
|
+
// every third load).
|
|
139
|
+
// ponytail: ceiling closed here is /reload-only — a whole-new-process
|
|
140
|
+
// "reload" (fresh pi) has no shared listeners to reuse, and a KILLED
|
|
141
|
+
// instance's unswept map would need a tombstone list; neither exists today.
|
|
142
|
+
(globalThis as any)[key] = jobs;
|
|
143
|
+
if ((globalThis as any)[armed] || exitSweepInstalled) return;
|
|
103
144
|
exitSweepInstalled = true;
|
|
145
|
+
(globalThis as any)[armed] = true;
|
|
104
146
|
const sweep = () => {
|
|
105
|
-
|
|
147
|
+
const cur = (globalThis as any)[key] as Map<string, BgJob> | undefined;
|
|
148
|
+
for (const j of (cur ?? jobs).values()) {
|
|
106
149
|
if (j.logTruncated) continue;
|
|
107
150
|
try { unlinkSync(j.logPath); } catch {}
|
|
108
151
|
}
|
|
@@ -6,7 +6,7 @@
|
|
|
6
6
|
// errors BEFORE the write with that remediation; bash stays the honest
|
|
7
7
|
// override hatch. Setting-gated via `repair.autoGenGuard` (default on).
|
|
8
8
|
|
|
9
|
-
import { isAbsolute, resolve as resolvePath } from "node:path";
|
|
9
|
+
import { isAbsolute, relative as relPath, resolve as resolvePath } from "node:path";
|
|
10
10
|
|
|
11
11
|
/** Default generated-file patterns. Suffix/segment match, `**` crosses dirs. */
|
|
12
12
|
export const AUTO_GENERATED_PATTERNS: readonly string[] = [
|
|
@@ -65,14 +65,24 @@ export interface AutoGeneratedMatch {
|
|
|
65
65
|
pattern: string;
|
|
66
66
|
}
|
|
67
67
|
|
|
68
|
-
/** Match an absolute path against the pattern list.
|
|
69
|
-
*
|
|
68
|
+
/** Match an absolute path against the pattern list. Paths OUTSIDE cwd match
|
|
69
|
+
* nothing — the guard only knows cwd-relative patterns, and a garbage
|
|
70
|
+
* `slice(cwd.length+1)` rel path used to spuriously hit `dist/**` and refuse
|
|
71
|
+
* legit out-of-repo writes. `patterns` injectable for tests. */
|
|
70
72
|
export function checkAutoGenerated(
|
|
71
73
|
absPath: string,
|
|
72
74
|
cwd: string,
|
|
73
75
|
patterns: readonly string[] = AUTO_GENERATED_PATTERNS,
|
|
74
76
|
): AutoGeneratedMatch | null {
|
|
75
|
-
|
|
77
|
+
if (!isAbsolute(absPath)) {
|
|
78
|
+
return matchRel(absPath, patterns);
|
|
79
|
+
}
|
|
80
|
+
const rel = relPath(resolvePath(cwd), resolvePath(absPath));
|
|
81
|
+
if (rel.startsWith("..") || isAbsolute(rel)) return null; // outside cwd — unguarded
|
|
82
|
+
return matchRel(rel, patterns);
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
function matchRel(rel: string, patterns: readonly string[]): AutoGeneratedMatch | null {
|
|
76
86
|
for (const pattern of patterns) {
|
|
77
87
|
if (matchesPattern(rel, pattern)) return { pattern };
|
|
78
88
|
}
|
|
@@ -64,6 +64,14 @@ export function matchMember(members: string[], wanted: string): { member: string
|
|
|
64
64
|
return { error: `no member matching "${wanted}"` };
|
|
65
65
|
}
|
|
66
66
|
|
|
67
|
+
/** Refusal for a resolved member whose name tar/unzip would parse as an
|
|
68
|
+
* option (leading `-`, listing forms like `./--x` included): a crafted
|
|
69
|
+
* archive makes tar EXECUTE that option (GNU --checkpoint-action primitive).
|
|
70
|
+
* Such members are unreadable here; bash is the override hatch. */
|
|
71
|
+
function dashOptionError(member: string): string {
|
|
72
|
+
return `refusing member "${member}" — archive member names beginning with "-" are parsed as tar/unzip options (command-injection primitive); extract via bash instead`;
|
|
73
|
+
}
|
|
74
|
+
|
|
67
75
|
/** Extract one member's bytes (tar -xOf / unzip -p). Throws on missing. */
|
|
68
76
|
function extractMember(archive: string, kind: ArchiveKind, member: string): Buffer {
|
|
69
77
|
const cmd = kind === "zip" ? "unzip" : "tar";
|
|
@@ -89,6 +97,12 @@ export function readArchiveMember(archive: string, kind: ArchiveKind, member: st
|
|
|
89
97
|
const members = listMembers(archive, kind);
|
|
90
98
|
const match = matchMember(members, member);
|
|
91
99
|
if ("error" in match) return { text: `${displayPath} : ${member}\n${match.error}` };
|
|
100
|
+
// Option-injection gate: tar/unzip take the member as a positional arg, so
|
|
101
|
+
// a crafted member named `--checkpoint-action=…` (or `./--…`) executes as a
|
|
102
|
+
// tar OPTION. Refuse before extractMember ever spawns.
|
|
103
|
+
if (match.member.replace(/^\.\//, "").startsWith("-")) {
|
|
104
|
+
return { text: `${displayPath} : ${member}\n${dashOptionError(match.member)}` };
|
|
105
|
+
}
|
|
92
106
|
const buf = extractMember(archive, kind, match.member);
|
|
93
107
|
if (buf.length > MEMBER_MAX_BYTES) {
|
|
94
108
|
return { text: `${displayPath} : ${match.member}\nmember is ${buf.length} bytes (cap ${MEMBER_MAX_BYTES}) — extract with bash, then read the file.` };
|
|
@@ -12,7 +12,7 @@
|
|
|
12
12
|
// since Node 22.13 < the repo engines floor). Fallback seam: swap
|
|
13
13
|
// `openDatabase` if a runtime refuses (e.g. sqlite3 CLI).
|
|
14
14
|
|
|
15
|
-
import {
|
|
15
|
+
import { closeSync, openSync, readSync } from "node:fs";
|
|
16
16
|
import { DatabaseSync } from "node:sqlite";
|
|
17
17
|
|
|
18
18
|
/** Row cap for raw queries (OMP MAX_RAW_QUERY_ROWS, trimmed). */
|
|
@@ -54,13 +54,19 @@ export function parseSqliteSelector(selector: string | undefined): SqliteSelecto
|
|
|
54
54
|
throw new Error(`invalid sqlite selector "${second}" — use :${table}:<rowid>, :${table}:<key>=<value>, or :?SELECT …`);
|
|
55
55
|
}
|
|
56
56
|
|
|
57
|
-
/** Sniff: first 16 bytes are the SQLite magic header.
|
|
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). */
|
|
58
59
|
export function isSqliteFile(absPath: string): boolean {
|
|
60
|
+
let fd: number | undefined;
|
|
59
61
|
try {
|
|
60
|
-
|
|
61
|
-
|
|
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"));
|
|
62
66
|
} catch {
|
|
63
67
|
return false;
|
|
68
|
+
} finally {
|
|
69
|
+
if (fd !== undefined) closeSync(fd);
|
|
64
70
|
}
|
|
65
71
|
}
|
|
66
72
|
|
|
@@ -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). */
|
|
@@ -73,15 +78,21 @@ export function settingsPath(): string {
|
|
|
73
78
|
return path.join(agentDir(), "settings.json");
|
|
74
79
|
}
|
|
75
80
|
|
|
76
|
-
/** Effective repair settings: global agent-dir file ⊕ trusted project overlay.
|
|
77
|
-
|
|
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 {
|
|
78
87
|
const out: RepairSettings = { ...DEFAULT_REPAIR_SETTINGS };
|
|
79
88
|
mergeLayer(out, readJson(settingsPath()));
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
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
|
+
}
|
|
85
96
|
return out;
|
|
86
97
|
}
|
|
87
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.
|