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.
Files changed (50) hide show
  1. package/CHANGELOG.md +91 -0
  2. package/extensions/lib/registry.ts +15 -1
  3. package/extensions/modules/a2a/lib/config.ts +15 -1
  4. package/extensions/modules/a2a/test/config.test.ts +27 -0
  5. package/extensions/modules/composer/test/module.test.ts +2 -2
  6. package/extensions/modules/config/test/renderTools.test.ts +1 -1
  7. package/extensions/modules/fff/index.ts +19 -0
  8. package/extensions/modules/fff/test/index.test.ts +31 -4
  9. package/extensions/modules/gh/configPanel.ts +9 -6
  10. package/extensions/modules/gh/test/gh.test.ts +61 -0
  11. package/extensions/modules/jfind/index.ts +124 -0
  12. package/extensions/modules/jfind/lib/cascade.ts +391 -0
  13. package/extensions/modules/jfind/lib/format.ts +12 -0
  14. package/extensions/modules/jfind/lib/judge.ts +74 -0
  15. package/extensions/modules/jfind/lib/lexical.ts +244 -0
  16. package/extensions/modules/jfind/lib/questions.ts +178 -0
  17. package/extensions/modules/jfind/lib/tree.ts +404 -0
  18. package/extensions/modules/jfind/test/cascade.test.ts +360 -0
  19. package/extensions/modules/notify/index.ts +33 -0
  20. package/extensions/modules/notify/lib/notify.ts +99 -0
  21. package/extensions/modules/notify/test/notify.test.ts +95 -0
  22. package/extensions/modules/plan/lib/plan-tools.ts +13 -0
  23. package/extensions/modules/repair/configPanel.ts +18 -9
  24. package/extensions/modules/repair/index.ts +173 -9
  25. package/extensions/modules/repair/lib/auto-bg.ts +45 -2
  26. package/extensions/modules/repair/lib/auto-generated.ts +99 -0
  27. package/extensions/modules/repair/lib/read-archive.ts +115 -0
  28. package/extensions/modules/repair/lib/read-sqlite.ts +191 -0
  29. package/extensions/modules/repair/lib/settings.ts +23 -9
  30. package/extensions/modules/repair/test/auto-bg.test.ts +66 -0
  31. package/extensions/modules/repair/test/hardening.test.ts +214 -0
  32. package/extensions/modules/repair/test/readers.test.ts +291 -0
  33. package/extensions/modules/repair/test/settings.test.ts +54 -14
  34. package/extensions/modules/sg/index.ts +129 -0
  35. package/extensions/modules/sg/lib/ops.ts +144 -0
  36. package/extensions/modules/sg/lib/sg-cli.ts +104 -0
  37. package/extensions/modules/sg/test/sg.test.ts +128 -0
  38. package/extensions/modules/shells/index.ts +227 -0
  39. package/extensions/modules/shells/lib/sessions.ts +412 -0
  40. package/extensions/modules/shells/test/output.test.ts +130 -0
  41. package/extensions/modules/shells/test/sessions.test.ts +397 -0
  42. package/extensions/modules/web/index.ts +34 -0
  43. package/extensions/modules/web/lib/pdf.ts +183 -0
  44. package/extensions/modules/web/test/extension.test.ts +2 -1
  45. package/extensions/modules/web/test/pdf.test.ts +84 -0
  46. package/extensions/modules/web/vendor/pdfjs/LICENSE +177 -0
  47. package/extensions/modules/web/vendor/pdfjs/README.md +16 -0
  48. package/extensions/modules/web/vendor/pdfjs/pdf.min.mjs +21 -0
  49. package/extensions/modules/web/vendor/pdfjs/pdf.worker.mjs +21 -0
  50. package/package.json +3 -3
@@ -53,6 +53,9 @@ import {
53
53
  stripReadContamination,
54
54
  } from "./lib/edit-repair.js";
55
55
  import { createStrReplaceEditorToolDefinition } from "./lib/editor.js";
56
+ import { checkAutoGenerated, autoGeneratedError } from "./lib/auto-generated.js";
57
+ import { archiveKind, readArchiveListing, readArchiveMember } from "./lib/read-archive.js";
58
+ import { isSqliteFile, readSqlite } from "./lib/read-sqlite.js";
56
59
  import { checkDangerousCommand, isRecord, looksLikeCodePath } from "./lib/guards.js";
57
60
  import { repairToolArguments, type RepairKind } from "./lib/input-repair.js";
58
61
  import { applyPatchToFiles, parsePatch, PatchParseError } from "./lib/patch.js";
@@ -107,6 +110,86 @@ function applyReadSelector(args: Record<string, unknown>, cwd: string): unknown
107
110
  return out;
108
111
  }
109
112
 
113
+ // ── sqlite / archive views (OMP read-sqlite + read-archive) ──
114
+
115
+ /** Peel `db.sqlite:users` / `pkg.tgz:src/x.ts:50-80` for sqlite/archive
116
+ * views. Returns the model-facing text result, or null when the path is
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
+ * Exported for tests. */
120
+ export function applySpecialView(rawPath: string, cwd: string): { text: string } | null {
121
+ // Special-view peel: the LONGEST existing prefix path split at colons is
122
+ // the stem; the remainder is the sqlite sub-selector or archive member
123
+ // (+ optional line ranges). peelPathSelector can't do this — its grammar
124
+ // only recognizes line selectors, so `db.sqlite:users` never peels.
125
+ let stem = "";
126
+ let remainder = "";
127
+ const parts = rawPath.split(":");
128
+ if (parts.length < 2 || parts[0]!.length <= 1) return null; // no segments / drive letter
129
+ for (let take = parts.length - 1; take >= 1; take--) {
130
+ const candidate = parts.slice(0, take).join(":");
131
+ if (existsSync(resolvePath(cwd, candidate))) {
132
+ stem = candidate;
133
+ remainder = parts.slice(take).join(":");
134
+ break;
135
+ }
136
+ }
137
+ if (!stem) return null;
138
+ const stemAbs = resolvePath(cwd, stem);
139
+
140
+ if (isSqliteFile(stemAbs)) {
141
+ try {
142
+ // The sqlite sub-selector spans ALL segments (users:2 is table+rowid).
143
+ return { text: readSqlite(stemAbs, remainder, stem) };
144
+ } catch (err) {
145
+ throw new Error(err instanceof Error ? err.message : String(err));
146
+ }
147
+ }
148
+
149
+ const kind = archiveKind(stem);
150
+ if (kind) {
151
+ if (!remainder) return { text: readArchiveListing(stemAbs, kind, stem).text };
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 };
173
+ }
174
+ return { text: res.text };
175
+ }
176
+ return null;
177
+ }
178
+
179
+ /** Slice `header + member lines` by a lines-selector, keeping the header. */
180
+ function sliceMemberLines(lines: string[], selector: ParsedSelector): string | null {
181
+ if (selector.kind !== "lines") return null;
182
+ const header = lines[0]!;
183
+ const body = lines.slice(1);
184
+ const total = body.length;
185
+ const parts = selector.ranges.map((r) => {
186
+ const end = Math.min(r.endLine ?? total, total);
187
+ return `── lines ${r.startLine}-${end} of ${total} ──\n${body.slice(r.startLine - 1, end).join("\n")}`;
188
+ });
189
+ const shown = selector.ranges.reduce((a, r) => a + (Math.min(r.endLine ?? total, total) - r.startLine + 1), 0);
190
+ return `${header}\n[lines ${selector.ranges.map((r) => `${r.startLine}-${r.endLine ?? total}`).join(", ")} of ${total} — ${shown} shown]\n\n${parts.join("\n\n")}`;
191
+ }
192
+
110
193
  /** In-memory slice for multi-range / raw / conflicts selectors. */
111
194
  async function readWithSelector(
112
195
  stem: string,
@@ -225,16 +308,39 @@ async function recordMutatedMtimes(toolName: string, params: any, cwd: string):
225
308
  }
226
309
  }
227
310
 
228
- /** 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). */
229
314
  function parsePatchTargetPaths(patch: string): string[] {
230
315
  const out: string[] = [];
231
- for (const m of patch.matchAll(/^\*{3} (?:Add|Delete|Update) File: (.+?)(?: → .+)?$/gm)) {
316
+ for (const m of patch.matchAll(/^\*{3} (?:Add|Delete|Update) File: (.+?)(?:\s*(?:→|->)\s*.+)?$/gm)) {
232
317
  const target = m[1].trim();
233
- if (target && !target.includes("://")) out.push(target.split(" → ")[0].trim());
318
+ if (target && !target.includes("://")) out.push(target);
234
319
  }
235
320
  return out;
236
321
  }
237
322
 
323
+ /** Auto-generated write guard (OMP auto-generated-guard): refuse write/edit
324
+ * on generated files before the write lands. Returns the refusal text, or
325
+ * undefined (allowed). Setting-gated via repair.autoGenGuard (default on;
326
+ * the cwd threads the trusted-project settings layer). */
327
+ function guardAutoGenerated(toolName: string, params: any, cwd: string): string | undefined {
328
+ if (!readRepairSettings(cwd).autoGenGuard) return undefined;
329
+ const paths: string[] = [];
330
+ if ((toolName === "write" || toolName === "edit" || toolName === "str_replace_editor") && isRecord(params) && typeof params.path === "string") {
331
+ paths.push(params.path);
332
+ }
333
+ if (toolName === "apply_patch" && isRecord(params) && typeof params.patch === "string") {
334
+ paths.push(...parsePatchTargetPaths(params.patch));
335
+ }
336
+ for (const p of paths) {
337
+ if (p.includes("://")) continue;
338
+ const match = checkAutoGenerated(p, cwd);
339
+ if (match) return autoGeneratedError(p, match);
340
+ }
341
+ return undefined;
342
+ }
343
+
238
344
  /** Public seam for tools registered outside wrapToolDefinition (apply_patch,
239
345
  * str_replace_editor) to refresh the freshness baseline after their own
240
346
  * successful mutations. */
@@ -332,7 +438,10 @@ export function wrapToolDefinition(
332
438
  // Deviation from upstream: the edit retry/escalation block is gated on the
333
439
  // `repair.editRetry` toggle. Read-notice decontamination and the no-op guard
334
440
  // stay unconditional (upstream: always on — both are deterministic and safe).
335
- shouldEditRetry: () => boolean = () => true,
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,
336
445
  ): any {
337
446
  return {
338
447
  ...base,
@@ -340,7 +449,7 @@ export function wrapToolDefinition(
340
449
  // per wrapped instance (cache-safe: byte-stable for the session).
341
450
  description:
342
451
  base.name === "read"
343
- ? `${base.description}\n\nPath suffixes: file.ts:50 starts at line 50; :50-200 inclusive; :50+150 counts lines; :50- to EOF; :-60 last 60 lines; commas join ranges (:5-16,960-973) or single lines (:19,59); :conflicts lists merge-conflict blocks; :raw compounds with a range. A literal path that exists always wins over selector parsing.`
452
+ ? `${base.description}\n\nPath suffixes: file.ts:50 starts at line 50; :50-200 inclusive; :50+150 counts lines; :50- to EOF; :-60 last 60 lines; commas join ranges (:5-16,960-973) or single lines (:19,59); :conflicts lists merge-conflict blocks; :raw compounds with a range. A literal path that exists always wins over selector parsing.\n\nSQLite and archive views: reading a *.db/*.sqlite file lists tables; db.sqlite:users shows schema + rows, :users:42 a rowid row, :users:name=alice a key lookup, :?SELECT … a read-only query. Archives (.tar, .tgz, .zip) list members; pkg.tgz:src/x.ts reads a member, :src/x.ts:50-80 slices it.`
344
453
  : base.description,
345
454
  prepareArguments(args: unknown) {
346
455
  let prepared = base.prepareArguments ? base.prepareArguments(args as never) : args;
@@ -366,6 +475,35 @@ export function wrapToolDefinition(
366
475
  base.name === "read" && isRecord(params) ? (params.__mtSelector as ParsedSelector | undefined) : undefined;
367
476
  if (isRecord(params)) delete params.__mtSelector;
368
477
 
478
+ // sqlite / archive views: plain `db.sqlite` (exists literally, would
479
+ // read binary garbage) and peeled `db.sqlite:users` /
480
+ // `pkg.tgz:src/x.ts:50-80` forms (applySpecialView peels internally).
481
+ // Literal-wins is preserved: a raw path that exists and is NOT sqlite
482
+ // falls through to the normal read; the peeled forms only trigger when
483
+ // the raw path is missing (standard selector order).
484
+ if (base.name === "read" && isRecord(params) && typeof params.path === "string" && !selector) {
485
+ const rawPath: string = params.path;
486
+ const rawAbs = resolvePath(cwd, rawPath);
487
+ let view: { text: string } | null = null;
488
+ if (existsSync(rawAbs) && isSqliteFile(rawAbs)) {
489
+ try {
490
+ view = { text: readSqlite(rawAbs, undefined, rawPath) };
491
+ } catch (err) {
492
+ throw new Error(err instanceof Error ? err.message : String(err));
493
+ }
494
+ } else if (existsSync(rawAbs) && archiveKind(rawPath)) {
495
+ view = { text: readArchiveListing(rawAbs, archiveKind(rawPath)!, rawPath).text };
496
+ } else if (!existsSync(rawAbs) && rawPath.includes(":")) {
497
+ view = applySpecialView(rawPath, cwd);
498
+ }
499
+ if (view) {
500
+ // Record the freshness baseline for the STEM so a follow-up write
501
+ // to the extracted file is judged normally (members have none).
502
+ await recordReadMtimes({ path: rawPath }, cwd);
503
+ return { content: [{ type: "text", text: view.text }], details: undefined };
504
+ }
505
+ }
506
+
369
507
  // Selector peel (execute-time: needs ctx.cwd for the literal-wins probe).
370
508
  if (base.name === "read" && !selector && isRecord(params) && typeof params.path === "string" && params.path.includes(":")) {
371
509
  params = applyReadSelector(params, cwd);
@@ -397,6 +535,8 @@ export function wrapToolDefinition(
397
535
  // THIS session read earlier but someone else changed since must
398
536
  // fail loudly instead of clobbering the foreign edit.
399
537
  if (base.name === "write") {
538
+ const gen = guardAutoGenerated(base.name, params, cwd);
539
+ if (gen) return { content: [{ type: "text", text: gen }], isError: true, details: undefined };
400
540
  const stale = await checkWriteFresh(params, cwd);
401
541
  if (stale) {
402
542
  return { content: [{ type: "text", text: stale }], isError: true, details: undefined };
@@ -436,6 +576,8 @@ export function wrapToolDefinition(
436
576
  const noopIdx = (Array.isArray(params?.edits) ? params.edits : typeof params?.oldText === "string" ? [{ oldText: params.oldText, newText: params.newText }] : [])
437
577
  .findIndex((e: any) => isRecord(e) && e.oldText === e.newText);
438
578
  if (noopIdx !== -1) throw new Error(`edits[${noopIdx}] is a no-op: oldText equals newText. The replacement produces no change — check which region you meant to target.`);
579
+ const genBlock = guardAutoGenerated("edit", params, cwd);
580
+ if (genBlock) return { content: [{ type: "text", text: genBlock }], isError: true, details: undefined };
439
581
  try {
440
582
  const result = await freshDef.execute(toolCallId, params, signal, onUpdate, ctx);
441
583
  editMismatchCounts?.delete(resolvePath(cwd, typeof params?.path === "string" ? params.path : ""));
@@ -448,7 +590,7 @@ export function wrapToolDefinition(
448
590
  return result;
449
591
  } catch (catchedErr: any) {
450
592
  let err: any = catchedErr;
451
- if (!shouldEditRetry()) throw err;
593
+ if (!shouldEditRetry(cwd)) throw err;
452
594
  const initialMessage: string = err?.message ? String(err.message) : "";
453
595
  if (!isEditMismatchError(initialMessage)) throw err;
454
596
 
@@ -549,11 +691,13 @@ export default function repairModule(pi: ExtensionAPI) {
549
691
  ...wrapToolDefinition(
550
692
  template,
551
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).
552
696
  () => readRepairSettings().arguments,
553
697
  onRepair,
554
698
  editMismatchCounts,
555
699
  () => pi.getActiveTools(),
556
- () => readRepairSettings().editRetry,
700
+ (cwd: string) => readRepairSettings(cwd).editRetry,
557
701
  ),
558
702
  defaultActive: !disabled.has(template.name),
559
703
  });
@@ -581,6 +725,8 @@ export default function repairModule(pi: ExtensionAPI) {
581
725
  renderShell: "self",
582
726
  async execute(_toolCallId, params, _signal, _onUpdate, ctx) {
583
727
  const cwd = ctx?.cwd || process.cwd();
728
+ const genBlock = guardAutoGenerated("apply_patch", params, cwd);
729
+ if (genBlock) return { content: [{ type: "text", text: genBlock }], isError: true, details: undefined };
584
730
  let parsed;
585
731
  try {
586
732
  parsed = parsePatch(params.patch);
@@ -616,6 +762,8 @@ export default function repairModule(pi: ExtensionAPI) {
616
762
  pi.registerTool({
617
763
  ...strReplaceDef,
618
764
  async execute(toolCallId: string, params: any, signal: any, onUpdate: any, ctx: any) {
765
+ const genBlock = guardAutoGenerated("str_replace_editor", params, ctx?.cwd || process.cwd());
766
+ if (genBlock) return { content: [{ type: "text", text: genBlock }], isError: true, details: undefined };
619
767
  const result = await strReplaceDef.execute(toolCallId, params, signal, onUpdate, ctx);
620
768
  // Refresh the freshness baseline for the edited file (same rationale as
621
769
  // apply_patch above) — only on success, only for plain file paths.
@@ -647,7 +795,7 @@ export default function repairModule(pi: ExtensionAPI) {
647
795
  // Upstream gated these on a detected family; repair is the model-agnostic
648
796
  // layer here, so the guards are ungated (only the `repair.guards` toggle). ──
649
797
  pi.on("tool_call", (event, ctx) => {
650
- if (!readRepairSettings().guards) return;
798
+ if (!readRepairSettings(ctx?.cwd).guards) return;
651
799
  if (event.toolName === "bash") {
652
800
  const command = isRecord(event.input) ? event.input.command : undefined;
653
801
  const danger = checkDangerousCommand(command);
@@ -666,6 +814,21 @@ export default function repairModule(pi: ExtensionAPI) {
666
814
  const peeled = peelPathSelector(filePath);
667
815
  if (peeled.selector) probe = peeled.stem;
668
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
+ }
669
832
  }
670
833
  if (filePath && looksLikeCodePath(probe) && !existsSync(resolvePath(ctx.cwd, probe))) {
671
834
  const filename = filePath.split("/").pop() ?? filePath;
@@ -680,7 +843,7 @@ export default function repairModule(pi: ExtensionAPI) {
680
843
  pi.registerCommand("repair", {
681
844
  description: "Show tool-hardening status: repair counts, guards, bash auto-background.",
682
845
  handler: async (_args, ctx) => {
683
- const live = readRepairSettings();
846
+ const live = readRepairSettings(ctx?.cwd);
684
847
  const total = [...repairCounts.values()].reduce((a, b) => a + b, 0);
685
848
  const lines = [
686
849
  "## repair status",
@@ -689,6 +852,7 @@ export default function repairModule(pi: ExtensionAPI) {
689
852
  ` Argument repair: ${live.arguments ? "on" : "off"}`,
690
853
  ` Edit mismatch repair: ${live.editRetry ? "on" : "off"}`,
691
854
  ` Tool-call guards: ${live.guards ? "on" : "off"}`,
855
+ ` Auto-generated write guard: ${live.autoGenGuard ? "on" : "off"}`,
692
856
  ` Auto-background bash: ${live.autoBg ? `on @${live.autoBgSecs}s` : "off"}${live.autoBg !== autoBgOn || live.autoBgSecs !== autoBgSecs ? ` (bound at load: ${autoBgOn ? `on @${autoBgSecs}s` : "off"} — next session applies)` : ""}`,
693
857
  "",
694
858
  `**Repairs this session:** ${total} total`,
@@ -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
  }
@@ -0,0 +1,99 @@
1
+ // auto-generated.ts — refuse writes/edits to generated files (OMP
2
+ // auto-generated-guard, native detector swapped for a zero-dep matcher).
3
+ //
4
+ // A hand edit to a lockfile or a dist bundle is always wrong: the fix is to
5
+ // regenerate from source (npm install / cargo build / tsc). The guard hard-
6
+ // errors BEFORE the write with that remediation; bash stays the honest
7
+ // override hatch. Setting-gated via `repair.autoGenGuard` (default on).
8
+
9
+ import { isAbsolute, relative as relPath, resolve as resolvePath } from "node:path";
10
+
11
+ /** Default generated-file patterns. Suffix/segment match, `**` crosses dirs. */
12
+ export const AUTO_GENERATED_PATTERNS: readonly string[] = [
13
+ // Lockfiles — regenerate via the package manager, never hand-edit.
14
+ "package-lock.json",
15
+ "yarn.lock",
16
+ "pnpm-lock.yaml",
17
+ "bun.lock",
18
+ "bun.lockb",
19
+ "Cargo.lock",
20
+ "poetry.lock",
21
+ "composer.lock",
22
+ "Gemfile.lock",
23
+ "flake.lock",
24
+ "Packages.lock.json",
25
+ // Minified bundles
26
+ "*.min.js",
27
+ "*.min.css",
28
+ "*.min.mjs",
29
+ "*.bundle.js",
30
+ // Build outputs (whole directories)
31
+ "dist/**",
32
+ "build/**",
33
+ "out/**",
34
+ "*.egg-info/**",
35
+ "__pycache__/**",
36
+ // Snapshots
37
+ "*.snap",
38
+ "__snapshots__/**",
39
+ ];
40
+
41
+ /** Minimal glob match: `*`/`**` = anything (crossing segments — `*.min.js`
42
+ * must catch a/b/app.min.js), a bare segment matches the path exactly.
43
+ * Zero-dep — the subagent .worktreeinclude matcher's shape. */
44
+ export function matchesPattern(relativePath: string, pattern: string): boolean {
45
+ const p = pattern.replaceAll("\\", "/");
46
+ const f = relativePath.replaceAll("\\", "/").replace(/^\.\//, "");
47
+ if (p === f) return true;
48
+ if (!p.includes("*")) return false; // plain name → equality only (above)
49
+ // Build a regex: * / ** → .* (segment-crossing)
50
+ let re = "^";
51
+ for (let i = 0; i < p.length; i++) {
52
+ const ch = p[i]!;
53
+ if (ch === "*") {
54
+ if (p[i + 1] === "*") i++; // `**` behaves like `*` here
55
+ re += ".*";
56
+ } else {
57
+ re += ch.replace(/[.+?^${}()|[\]\\]/g, "\\$&");
58
+ }
59
+ }
60
+ re += "$";
61
+ return new RegExp(re).test(f);
62
+ }
63
+
64
+ export interface AutoGeneratedMatch {
65
+ pattern: string;
66
+ }
67
+
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. */
72
+ export function checkAutoGenerated(
73
+ absPath: string,
74
+ cwd: string,
75
+ patterns: readonly string[] = AUTO_GENERATED_PATTERNS,
76
+ ): AutoGeneratedMatch | null {
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 {
86
+ for (const pattern of patterns) {
87
+ if (matchesPattern(rel, pattern)) return { pattern };
88
+ }
89
+ return null;
90
+ }
91
+
92
+ /** The model-facing refusal. Names the pattern + the bash override hatch. */
93
+ export function autoGeneratedError(path: string, match: AutoGeneratedMatch): string {
94
+ return (
95
+ `${path} is auto-generated (matched ${match.pattern}) — edit its source and regenerate ` +
96
+ `(npm install / cargo build / tsc …) instead of editing the output. ` +
97
+ `If you really must, use bash to write it deliberately.`
98
+ );
99
+ }
@@ -0,0 +1,115 @@
1
+ // read-archive — archive members through the wrapped read (OMP
2
+ // read-archive.ts idea, ponytail shape: shell out to `tar`/`unzip`, present
3
+ // on every darwin/linux target, instead of vendoring a zip reader).
4
+ //
5
+ // Grammar (peeled progressively by index.ts when the literal path misses):
6
+ // pkg.tgz → member listing
7
+ // pkg.tgz:src/x.ts → member content
8
+ // pkg.tgz:src/x.ts:50-80 → member content, then the existing line ranges
9
+ // Member match: exact first, then unique substring (OMP findSuffixMatch
10
+ // semantics); ambiguous → error listing candidates. 1 MB cap before
11
+ // buffering; NUL byte in the first 8 KB → refusal (binary member).
12
+
13
+ import { execFileSync } from "node:child_process";
14
+
15
+ /** Member bytes buffered before refusing/truncating. */
16
+ export const MEMBER_MAX_BYTES = 1024 * 1024;
17
+ /** Entry-listing cap. */
18
+ export const LISTING_MAX = 500;
19
+ const TAR_TIMEOUT_MS = 10_000;
20
+
21
+ export type ArchiveKind = "tar" | "tgz" | "zip";
22
+
23
+ /** Archive extension → kind (order matters: .tar.gz before .gz-less). */
24
+ export function archiveKind(path: string): ArchiveKind | null {
25
+ const p = path.toLowerCase();
26
+ if (p.endsWith(".tar.gz") || p.endsWith(".tgz")) return "tgz";
27
+ if (p.endsWith(".tar")) return "tar";
28
+ if (p.endsWith(".zip")) return "zip";
29
+ return null;
30
+ }
31
+
32
+ function run(cmd: string, args: string[]): string {
33
+ return execFileSync(cmd, args, { timeout: TAR_TIMEOUT_MS, maxBuffer: 8 * 1024 * 1024, encoding: "utf8" });
34
+ }
35
+
36
+ /** `tar -tf` / `unzip -Z1` listing parsed to member paths. Directories and
37
+ * PaxHeaders are dropped. Exported for tests. */
38
+ export function listMembers(archive: string, kind: ArchiveKind): string[] {
39
+ const out = kind === "zip" ? run("unzip", ["-Z1", archive]) : run("tar", ["-tf", archive]);
40
+ return out
41
+ .split("\n")
42
+ .map((l) => l.trim())
43
+ .filter(
44
+ (l) =>
45
+ l.length > 0 &&
46
+ !l.endsWith("/") &&
47
+ !l.startsWith("PaxHeader") &&
48
+ !l.includes("/PaxHeader") &&
49
+ // bsdtar may print './'-prefixed members
50
+ l !== "." && l !== "./",
51
+ );
52
+ }
53
+
54
+ /** Match a member: exact, then unique substring (OMP findSuffixMatch). */
55
+ export function matchMember(members: string[], wanted: string): { member: string; via: "exact" | "suffix" } | { error: string } {
56
+ const wantedNorm = wanted.replace(/^\.\//, "");
57
+ const exact = members.find((m) => m === wantedNorm || m === `./${wantedNorm}` || m.replace(/^\.\//, "") === wantedNorm);
58
+ if (exact) return { member: exact, via: "exact" };
59
+ const hits = members.filter((m) => m.replace(/^\.\//, "").endsWith(wantedNorm));
60
+ if (hits.length === 1) return { member: hits[0]!, via: "suffix" };
61
+ if (hits.length > 1) {
62
+ return { error: `ambiguous member "${wanted}" — ${hits.length} candidates:\n${hits.slice(0, 10).map((h) => ` ${h}`).join("\n")}` };
63
+ }
64
+ return { error: `no member matching "${wanted}"` };
65
+ }
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
+
75
+ /** Extract one member's bytes (tar -xOf / unzip -p). Throws on missing. */
76
+ function extractMember(archive: string, kind: ArchiveKind, member: string): Buffer {
77
+ const cmd = kind === "zip" ? "unzip" : "tar";
78
+ const args = kind === "zip" ? ["-p", archive, member] : ["-xOf", archive, member];
79
+ // execFileSync with a Buffer return keeps binary bytes intact.
80
+ return execFileSync(cmd, args, { timeout: TAR_TIMEOUT_MS, maxBuffer: 8 * 1024 * 1024 });
81
+ }
82
+
83
+ export interface ArchiveReadResult {
84
+ text: string;
85
+ }
86
+
87
+ /** Read an archive (no selector) → listing. */
88
+ export function readArchiveListing(archive: string, kind: ArchiveKind, displayPath: string): ArchiveReadResult {
89
+ const members = listMembers(archive, kind);
90
+ const shown = members.slice(0, LISTING_MAX);
91
+ const footer = members.length > shown.length ? `\n[showing ${shown.length} of ${members.length} members]` : "";
92
+ return { text: `${displayPath} — ${members.length} member(s)\n${shown.join("\n")}${footer}` };
93
+ }
94
+
95
+ /** Read one member (optionally pre-sliced by the caller's line ranges). */
96
+ export function readArchiveMember(archive: string, kind: ArchiveKind, member: string, displayPath: string): ArchiveReadResult {
97
+ const members = listMembers(archive, kind);
98
+ const match = matchMember(members, member);
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
+ }
106
+ const buf = extractMember(archive, kind, match.member);
107
+ if (buf.length > MEMBER_MAX_BYTES) {
108
+ return { text: `${displayPath} : ${match.member}\nmember is ${buf.length} bytes (cap ${MEMBER_MAX_BYTES}) — extract with bash, then read the file.` };
109
+ }
110
+ if (buf.subarray(0, 8192).includes(0)) {
111
+ return { text: `${displayPath} : ${match.member}\nbinary member — extract with bash (tar -xOf / unzip -p), then read the file.` };
112
+ }
113
+ const text = buf.toString("utf8");
114
+ return { text: `${displayPath} : ${match.member}${match.via === "suffix" ? ` (matched ${match.member})` : ""}\n${text}` };
115
+ }