ceulen 0.13.0 → 0.15.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 (65) hide show
  1. package/CHANGELOG.md +66 -0
  2. package/README.md +5 -3
  3. package/extensions/index.ts +33 -1
  4. package/extensions/lib/registry.ts +31 -52
  5. package/extensions/modules/a2a/index.ts +0 -9
  6. package/extensions/modules/a2a/lib/config.ts +15 -1
  7. package/extensions/modules/a2a/test/config.test.ts +27 -0
  8. package/extensions/modules/a2a/test/extension.test.ts +1 -19
  9. package/extensions/modules/advisor/commands/advisor.ts +3 -9
  10. package/extensions/modules/advisor/test/configPanel.test.ts +1 -1
  11. package/extensions/modules/advisor/test/module.test.ts +0 -11
  12. package/extensions/modules/classifier/index.ts +0 -3
  13. package/extensions/modules/composer/test/module.test.ts +0 -22
  14. package/extensions/modules/config/defaultTools.ts +5 -3
  15. package/extensions/modules/config/index.ts +18 -204
  16. package/extensions/modules/config/test/defaultTools.test.ts +3 -4
  17. package/extensions/modules/config/test/panel.test.ts +9 -72
  18. package/extensions/modules/fff/index.ts +19 -8
  19. package/extensions/modules/fff/test/index.test.ts +31 -4
  20. package/extensions/modules/gh/configPanel.ts +9 -6
  21. package/extensions/modules/gh/index.ts +0 -3
  22. package/extensions/modules/gh/test/gh.test.ts +61 -0
  23. package/extensions/modules/jfind/index.ts +10 -4
  24. package/extensions/modules/jfind/lib/cascade.ts +15 -1
  25. package/extensions/modules/jfind/lib/lexical.ts +18 -6
  26. package/extensions/modules/jfind/lib/tree.ts +34 -4
  27. package/extensions/modules/jfind/test/cascade.test.ts +56 -1
  28. package/extensions/modules/munin/index.ts +5 -7
  29. package/extensions/modules/notify/index.ts +0 -3
  30. package/extensions/modules/plan/index.ts +1 -7
  31. package/extensions/modules/repair/configPanel.ts +11 -8
  32. package/extensions/modules/repair/index.ts +58 -33
  33. package/extensions/modules/repair/lib/auto-bg.ts +45 -2
  34. package/extensions/modules/repair/lib/auto-generated.ts +14 -4
  35. package/extensions/modules/repair/lib/read-archive.ts +14 -0
  36. package/extensions/modules/repair/lib/read-sqlite.ts +10 -4
  37. package/extensions/modules/repair/lib/settings.ts +19 -8
  38. package/extensions/modules/repair/test/auto-bg.test.ts +66 -0
  39. package/extensions/modules/repair/test/hardening.test.ts +214 -0
  40. package/extensions/modules/repair/test/settings.test.ts +52 -13
  41. package/extensions/modules/rules/index.ts +0 -4
  42. package/extensions/modules/rules/lib/rules.ts +1 -1
  43. package/extensions/modules/rules/test/module.test.ts +2 -29
  44. package/extensions/modules/serena/index.ts +1 -6
  45. package/extensions/modules/serena/lib/guidance.ts +9 -5
  46. package/extensions/modules/sg/index.ts +0 -5
  47. package/extensions/modules/shells/index.ts +31 -16
  48. package/extensions/modules/shells/lib/sessions.ts +76 -8
  49. package/extensions/modules/shells/test/output.test.ts +130 -0
  50. package/extensions/modules/shells/test/sessions.test.ts +127 -5
  51. package/extensions/modules/steering/lib/think.ts +0 -2
  52. package/extensions/modules/steering/test/think.test.ts +1 -5
  53. package/extensions/modules/todo/index.ts +0 -2
  54. package/extensions/modules/usage/index.ts +19 -9
  55. package/extensions/modules/usage/test/context.test.ts +18 -7
  56. package/extensions/modules/ux/index.ts +1 -5
  57. package/extensions/modules/ux/test/extension.test.ts +0 -5
  58. package/extensions/modules/web/index.ts +0 -9
  59. package/extensions/modules/web/lib/pdf.ts +4 -2
  60. package/extensions/modules/web/test/extension.test.ts +8 -18
  61. package/extensions/modules/web/test/pdf.test.ts +84 -0
  62. package/package.json +1 -1
  63. package/extensions/lib/tools.ts +0 -47
  64. package/extensions/modules/config/test/renderTools.test.ts +0 -71
  65. package/extensions/modules/config/test/tools.test.ts +0 -146
@@ -41,7 +41,6 @@ import {
41
41
  defineTool,
42
42
  } from "@earendil-works/pi-coding-agent";
43
43
  import { Type } from "typebox";
44
- import { readDisabledTools } from "../../lib/tools.js";
45
44
  import { abortAllBgJobs, bashAutoBgClause, setBgDeliveryEnabled, wrapWithAutoBg } from "./lib/auto-bg.js";
46
45
  import {
47
46
  computeRetryEdit,
@@ -115,8 +114,9 @@ function applyReadSelector(args: Record<string, unknown>, cwd: string): unknown
115
114
  /** Peel `db.sqlite:users` / `pkg.tgz:src/x.ts:50-80` for sqlite/archive
116
115
  * views. Returns the model-facing text result, or null when the path is
117
116
  * 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
- function applySpecialView(rawPath: string, cwd: string): { text: string } | null {
117
+ * (the caller probes the literal path first — literal-wins preserved).
118
+ * Exported for tests. */
119
+ export function applySpecialView(rawPath: string, cwd: string): { text: string } | null {
120
120
  // Special-view peel: the LONGEST existing prefix path split at colons is
121
121
  // the stem; the remainder is the sqlite sub-selector or archive member
122
122
  // (+ optional line ranges). peelPathSelector can't do this — its grammar
@@ -135,7 +135,6 @@ function applySpecialView(rawPath: string, cwd: string): { text: string } | null
135
135
  }
136
136
  if (!stem) return null;
137
137
  const stemAbs = resolvePath(cwd, stem);
138
- const segments = remainder.split(":");
139
138
 
140
139
  if (isSqliteFile(stemAbs)) {
141
140
  try {
@@ -149,17 +148,27 @@ function applySpecialView(rawPath: string, cwd: string): { text: string } | null
149
148
  const kind = archiveKind(stem);
150
149
  if (kind) {
151
150
  if (!remainder) return { text: readArchiveListing(stemAbs, kind, stem).text };
152
- const res = readArchiveMember(stemAbs, kind, remainder, stem);
153
- // A trailing :50-80 range on the member reuses the line slicer over the
154
- // member body (line 1 of the result text is the path header).
155
- if (segments.length > 1) {
156
- const memberParsed = peelPathSelector(`x:${remainder}`);
157
- if (memberParsed.selector) {
158
- const lines = res.text.split("\n");
159
- if (lines.length > 1 && lines[lines.length - 1] === "") lines.pop();
160
- const sliced = sliceMemberLines(lines, memberParsed.selector);
161
- if (sliced !== null) return { text: sliced };
162
- }
151
+ // Peel the trailing lines-selector FIRST (`src/x.ts:50-80`): the member
152
+ // lookup must see `src/x.ts`, not the raw remainder with the `:50-80`
153
+ // suffix (which matchMember reports as "no member matching").
154
+ let member = remainder;
155
+ let selector: ParsedSelector | undefined;
156
+ const memberParsed = peelPathSelector(remainder);
157
+ if (memberParsed.selector) {
158
+ member = memberParsed.stem;
159
+ selector = memberParsed.selector;
160
+ }
161
+ const res = readArchiveMember(stemAbs, kind, member, stem);
162
+ // Line ranges slice the member body (line 1 of the result text is the
163
+ // path header); `:raw` compounds ride the same slicer via the raw range.
164
+ if (selector && selector.kind !== "raw" && selector.kind !== "none") {
165
+ const lines = res.text.split("\n");
166
+ if (lines.length > 1 && lines[lines.length - 1] === "") lines.pop();
167
+ const resolved = selector.kind === "tail"
168
+ ? resolveTailSelector(selector, lines.length - 1)
169
+ : selector;
170
+ const sliced = sliceMemberLines(lines, resolved);
171
+ if (sliced !== null) return { text: sliced };
163
172
  }
164
173
  return { text: res.text };
165
174
  }
@@ -298,23 +307,26 @@ async function recordMutatedMtimes(toolName: string, params: any, cwd: string):
298
307
  }
299
308
  }
300
309
 
301
- /** V4D patch targets: `*** Update File: <path>` / Add / Delete / rename. */
310
+ /** V4D patch targets: `*** Update File: <path>` / Add / Delete / rename
311
+ * (both rename arrows — parseFileHeader accepts unicode `→` AND ascii `->`,
312
+ * so the auto-gen guard + mtime refresh must too). */
302
313
  function parsePatchTargetPaths(patch: string): string[] {
303
314
  const out: string[] = [];
304
- for (const m of patch.matchAll(/^\*{3} (?:Add|Delete|Update) File: (.+?)(?: → .+)?$/gm)) {
315
+ for (const m of patch.matchAll(/^\*{3} (?:Add|Delete|Update) File: (.+?)(?:\s*(?:→|->)\s*.+)?$/gm)) {
305
316
  const target = m[1].trim();
306
- if (target && !target.includes("://")) out.push(target.split(" → ")[0].trim());
317
+ if (target && !target.includes("://")) out.push(target);
307
318
  }
308
319
  return out;
309
320
  }
310
321
 
311
322
  /** Auto-generated write guard (OMP auto-generated-guard): refuse write/edit
312
323
  * on generated files before the write lands. Returns the refusal text, or
313
- * undefined (allowed). Setting-gated via repair.autoGenGuard (default on). */
324
+ * undefined (allowed). Setting-gated via repair.autoGenGuard (default on;
325
+ * the cwd threads the trusted-project settings layer). */
314
326
  function guardAutoGenerated(toolName: string, params: any, cwd: string): string | undefined {
315
- if (!readRepairSettings().autoGenGuard) return undefined;
327
+ if (!readRepairSettings(cwd).autoGenGuard) return undefined;
316
328
  const paths: string[] = [];
317
- if ((toolName === "write" || toolName === "edit") && isRecord(params) && typeof params.path === "string") {
329
+ if ((toolName === "write" || toolName === "edit" || toolName === "str_replace_editor") && isRecord(params) && typeof params.path === "string") {
318
330
  paths.push(params.path);
319
331
  }
320
332
  if (toolName === "apply_patch" && isRecord(params) && typeof params.patch === "string") {
@@ -425,7 +437,10 @@ export function wrapToolDefinition(
425
437
  // Deviation from upstream: the edit retry/escalation block is gated on the
426
438
  // `repair.editRetry` toggle. Read-notice decontamination and the no-op guard
427
439
  // stay unconditional (upstream: always on — both are deterministic and safe).
428
- shouldEditRetry: () => boolean = () => true,
440
+ // The retry gate receives the execute-time cwd so it honors the trusted
441
+ // project settings layer (prepareArguments has no ctx — the `arguments`
442
+ // toggle stays global-layer only, a documented ceiling).
443
+ shouldEditRetry: (cwd: string) => boolean = () => true,
429
444
  ): any {
430
445
  return {
431
446
  ...base,
@@ -574,7 +589,7 @@ export function wrapToolDefinition(
574
589
  return result;
575
590
  } catch (catchedErr: any) {
576
591
  let err: any = catchedErr;
577
- if (!shouldEditRetry()) throw err;
592
+ if (!shouldEditRetry(cwd)) throw err;
578
593
  const initialMessage: string = err?.message ? String(err.message) : "";
579
594
  if (!isEditMismatchError(initialMessage)) throw err;
580
595
 
@@ -638,10 +653,6 @@ export default function repairModule(pi: ExtensionAPI) {
638
653
  const autoBgOn = settings.autoBg;
639
654
  const autoBgSecs = settings.autoBgSecs;
640
655
 
641
- // Per-tool kill-switch: a tool named in ceulen.disabledTools registers
642
- // inactive, so /config's live tool toggles keep working over the wrapped
643
- // built-ins too. The persisted list re-applies on every load.
644
- const disabled = readDisabledTools();
645
656
  const repairCounts = new Map<string, number>();
646
657
  // Per-file edit-mismatch counters — escalate to apply_patch after repeated
647
658
  // unresolvable misses on the same file (26% retry-fail tail).
@@ -675,13 +686,14 @@ export default function repairModule(pi: ExtensionAPI) {
675
686
  ...wrapToolDefinition(
676
687
  template,
677
688
  factory,
689
+ // ponytail: prepareArguments has no ctx/cwd — the `arguments` toggle
690
+ // reads the global layer only; ceiling is host-level (no ctx in arg prep).
678
691
  () => readRepairSettings().arguments,
679
692
  onRepair,
680
693
  editMismatchCounts,
681
694
  () => pi.getActiveTools(),
682
- () => readRepairSettings().editRetry,
695
+ (cwd: string) => readRepairSettings(cwd).editRetry,
683
696
  ),
684
- defaultActive: !disabled.has(template.name),
685
697
  });
686
698
  }
687
699
 
@@ -736,7 +748,6 @@ export default function repairModule(pi: ExtensionAPI) {
736
748
  }
737
749
  },
738
750
  }),
739
- defaultActive: !disabled.has("apply_patch"),
740
751
  });
741
752
 
742
753
  // ── str_replace_editor: DSH Minimal-pair editor (byte-faithful schema) ──
@@ -754,7 +765,6 @@ export default function repairModule(pi: ExtensionAPI) {
754
765
  }
755
766
  return result;
756
767
  },
757
- defaultActive: !disabled.has("str_replace_editor"),
758
768
  });
759
769
 
760
770
  // ── Session lifecycle ──
@@ -777,7 +787,7 @@ export default function repairModule(pi: ExtensionAPI) {
777
787
  // Upstream gated these on a detected family; repair is the model-agnostic
778
788
  // layer here, so the guards are ungated (only the `repair.guards` toggle). ──
779
789
  pi.on("tool_call", (event, ctx) => {
780
- if (!readRepairSettings().guards) return;
790
+ if (!readRepairSettings(ctx?.cwd).guards) return;
781
791
  if (event.toolName === "bash") {
782
792
  const command = isRecord(event.input) ? event.input.command : undefined;
783
793
  const danger = checkDangerousCommand(command);
@@ -796,6 +806,21 @@ export default function repairModule(pi: ExtensionAPI) {
796
806
  const peeled = peelPathSelector(filePath);
797
807
  if (peeled.selector) probe = peeled.stem;
798
808
  } catch { /* invalid selector — keep the raw path */ }
809
+ // Archive-member reads (`pkg.tgz:src/x.ts`, optionally + `:50-80`) are
810
+ // an ADVERTISED read grammar: the stem probe still carries the member
811
+ // suffix, so it "doesn't exist" and the guard would block the module's
812
+ // own documented form. Mirror applySpecialView: when the longest
813
+ // existing colon-prefix is an archive file, probe that stem.
814
+ if (probe.includes(":")) {
815
+ const parts = probe.split(":");
816
+ for (let take = parts.length - 1; take >= 1; take--) {
817
+ const candidate = parts.slice(0, take).join(":");
818
+ if (existsSync(resolvePath(ctx.cwd, candidate)) && archiveKind(candidate)) {
819
+ probe = candidate;
820
+ break;
821
+ }
822
+ }
823
+ }
799
824
  }
800
825
  if (filePath && looksLikeCodePath(probe) && !existsSync(resolvePath(ctx.cwd, probe))) {
801
826
  const filename = filePath.split("/").pop() ?? filePath;
@@ -810,7 +835,7 @@ export default function repairModule(pi: ExtensionAPI) {
810
835
  pi.registerCommand("repair", {
811
836
  description: "Show tool-hardening status: repair counts, guards, bash auto-background.",
812
837
  handler: async (_args, ctx) => {
813
- const live = readRepairSettings();
838
+ const live = readRepairSettings(ctx?.cwd);
814
839
  const total = [...repairCounts.values()].reduce((a, b) => a + b, 0);
815
840
  const lines = [
816
841
  "## 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
- if (exitSweepInstalled) return;
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
- for (const j of jobs.values()) {
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. `patterns` injectable
69
- * for tests; caller passes cwd-relative resolution. */
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
- const rel = isAbsolute(absPath) ? resolvePath(absPath).slice(cwd.length + 1) : absPath;
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 { readFileSync } from "node:fs";
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
- const fd = readFileSync(absPath);
61
- return fd.length >= 16 && fd.subarray(0, 16).equals(Buffer.from("SQLite format 3\0", "utf8"));
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 type { ExtensionContext } from "@earendil-works/pi-coding-agent";
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
- export function readRepairSettings(ctx?: ExtensionContext): RepairSettings {
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
- try {
81
- if (ctx?.isProjectTrusted?.()) {
82
- mergeLayer(out, readJson(path.join(ctx.cwd, ".pi", "settings.json")));
83
- }
84
- } catch { /* untrusted or ctx without cwd — global only */ }
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.