ceulen 0.11.0 → 0.13.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (70) hide show
  1. package/CHANGELOG.md +100 -1
  2. package/extensions/index.ts +5 -1
  3. package/extensions/lib/env.test.ts +147 -0
  4. package/extensions/lib/env.ts +180 -0
  5. package/extensions/lib/order.test.ts +74 -0
  6. package/extensions/lib/registry.test.ts +8 -5
  7. package/extensions/lib/registry.ts +23 -4
  8. package/extensions/modules/a2a/configPanel.ts +42 -1
  9. package/extensions/modules/a2a/lib/config.ts +8 -3
  10. package/extensions/modules/a2a/test/configPanel.test.ts +7 -4
  11. package/extensions/modules/advisor/index.ts +6 -3
  12. package/extensions/modules/advisor/test/module.test.ts +31 -0
  13. package/extensions/modules/classifier/index.ts +55 -1
  14. package/extensions/modules/classifier/test/classifier.test.ts +62 -0
  15. package/extensions/modules/composer/test/module.test.ts +2 -2
  16. package/extensions/modules/config/test/renderTools.test.ts +1 -1
  17. package/extensions/modules/jfind/index.ts +115 -0
  18. package/extensions/modules/jfind/lib/cascade.ts +377 -0
  19. package/extensions/modules/jfind/lib/format.ts +12 -0
  20. package/extensions/modules/jfind/lib/judge.ts +74 -0
  21. package/extensions/modules/jfind/lib/lexical.ts +232 -0
  22. package/extensions/modules/jfind/lib/questions.ts +178 -0
  23. package/extensions/modules/jfind/lib/tree.ts +374 -0
  24. package/extensions/modules/jfind/test/cascade.test.ts +305 -0
  25. package/extensions/modules/notify/index.ts +33 -0
  26. package/extensions/modules/notify/lib/notify.ts +99 -0
  27. package/extensions/modules/notify/test/notify.test.ts +95 -0
  28. package/extensions/modules/plan/lib/plan-tools.ts +13 -0
  29. package/extensions/modules/repair/configPanel.ts +7 -1
  30. package/extensions/modules/repair/index.ts +158 -3
  31. package/extensions/modules/repair/lib/auto-generated.ts +89 -0
  32. package/extensions/modules/repair/lib/read-archive.ts +101 -0
  33. package/extensions/modules/repair/lib/read-sqlite.ts +185 -0
  34. package/extensions/modules/repair/lib/settings.ts +4 -1
  35. package/extensions/modules/repair/test/freshness.test.ts +41 -1
  36. package/extensions/modules/repair/test/guard-selector.test.ts +67 -0
  37. package/extensions/modules/repair/test/readers.test.ts +291 -0
  38. package/extensions/modules/repair/test/settings.test.ts +2 -1
  39. package/extensions/modules/router/configPanel.ts +4 -4
  40. package/extensions/modules/router/index.ts +1 -1
  41. package/extensions/modules/router/lib/config.ts +9 -4
  42. package/extensions/modules/router/lib/systemone.ts +17 -4
  43. package/extensions/modules/router/test/unit.test.ts +46 -1
  44. package/extensions/modules/rules/index.ts +13 -3
  45. package/extensions/modules/rules/lib/rules.ts +24 -12
  46. package/extensions/modules/rules/test/lib.test.ts +20 -0
  47. package/extensions/modules/rules/test/module.test.ts +21 -0
  48. package/extensions/modules/sg/index.ts +129 -0
  49. package/extensions/modules/sg/lib/ops.ts +144 -0
  50. package/extensions/modules/sg/lib/sg-cli.ts +104 -0
  51. package/extensions/modules/sg/test/sg.test.ts +128 -0
  52. package/extensions/modules/shells/index.ts +210 -0
  53. package/extensions/modules/shells/lib/sessions.ts +344 -0
  54. package/extensions/modules/shells/test/sessions.test.ts +275 -0
  55. package/extensions/modules/subagent/index.ts +11 -5
  56. package/extensions/modules/subagent/lib/herdr.ts +5 -0
  57. package/extensions/modules/subagent/lib/routing.ts +31 -8
  58. package/extensions/modules/subagent/lib/runner.ts +8 -2
  59. package/extensions/modules/subagent/test/routing.test.ts +45 -0
  60. package/extensions/modules/web/configPanel.ts +67 -8
  61. package/extensions/modules/web/index.ts +34 -0
  62. package/extensions/modules/web/lib/pdf.ts +181 -0
  63. package/extensions/modules/web/test/configPanel.test.ts +7 -3
  64. package/extensions/modules/web/test/extension.test.ts +2 -1
  65. package/extensions/modules/web/test/settings.test.ts +6 -0
  66. package/extensions/modules/web/vendor/pdfjs/LICENSE +177 -0
  67. package/extensions/modules/web/vendor/pdfjs/README.md +16 -0
  68. package/extensions/modules/web/vendor/pdfjs/pdf.min.mjs +21 -0
  69. package/extensions/modules/web/vendor/pdfjs/pdf.worker.mjs +21 -0
  70. 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,76 @@ 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
+ function applySpecialView(rawPath: string, cwd: string): { text: string } | null {
120
+ // Special-view peel: the LONGEST existing prefix path split at colons is
121
+ // the stem; the remainder is the sqlite sub-selector or archive member
122
+ // (+ optional line ranges). peelPathSelector can't do this — its grammar
123
+ // only recognizes line selectors, so `db.sqlite:users` never peels.
124
+ let stem = "";
125
+ let remainder = "";
126
+ const parts = rawPath.split(":");
127
+ if (parts.length < 2 || parts[0]!.length <= 1) return null; // no segments / drive letter
128
+ for (let take = parts.length - 1; take >= 1; take--) {
129
+ const candidate = parts.slice(0, take).join(":");
130
+ if (existsSync(resolvePath(cwd, candidate))) {
131
+ stem = candidate;
132
+ remainder = parts.slice(take).join(":");
133
+ break;
134
+ }
135
+ }
136
+ if (!stem) return null;
137
+ const stemAbs = resolvePath(cwd, stem);
138
+ const segments = remainder.split(":");
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
+ 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
+ }
163
+ }
164
+ return { text: res.text };
165
+ }
166
+ return null;
167
+ }
168
+
169
+ /** Slice `header + member lines` by a lines-selector, keeping the header. */
170
+ function sliceMemberLines(lines: string[], selector: ParsedSelector): string | null {
171
+ if (selector.kind !== "lines") return null;
172
+ const header = lines[0]!;
173
+ const body = lines.slice(1);
174
+ const total = body.length;
175
+ const parts = selector.ranges.map((r) => {
176
+ const end = Math.min(r.endLine ?? total, total);
177
+ return `── lines ${r.startLine}-${end} of ${total} ──\n${body.slice(r.startLine - 1, end).join("\n")}`;
178
+ });
179
+ const shown = selector.ranges.reduce((a, r) => a + (Math.min(r.endLine ?? total, total) - r.startLine + 1), 0);
180
+ return `${header}\n[lines ${selector.ranges.map((r) => `${r.startLine}-${r.endLine ?? total}`).join(", ")} of ${total} — ${shown} shown]\n\n${parts.join("\n\n")}`;
181
+ }
182
+
110
183
  /** In-memory slice for multi-range / raw / conflicts selectors. */
111
184
  async function readWithSelector(
112
185
  stem: string,
@@ -235,6 +308,26 @@ function parsePatchTargetPaths(patch: string): string[] {
235
308
  return out;
236
309
  }
237
310
 
311
+ /** Auto-generated write guard (OMP auto-generated-guard): refuse write/edit
312
+ * on generated files before the write lands. Returns the refusal text, or
313
+ * undefined (allowed). Setting-gated via repair.autoGenGuard (default on). */
314
+ function guardAutoGenerated(toolName: string, params: any, cwd: string): string | undefined {
315
+ if (!readRepairSettings().autoGenGuard) return undefined;
316
+ const paths: string[] = [];
317
+ if ((toolName === "write" || toolName === "edit") && isRecord(params) && typeof params.path === "string") {
318
+ paths.push(params.path);
319
+ }
320
+ if (toolName === "apply_patch" && isRecord(params) && typeof params.patch === "string") {
321
+ paths.push(...parsePatchTargetPaths(params.patch));
322
+ }
323
+ for (const p of paths) {
324
+ if (p.includes("://")) continue;
325
+ const match = checkAutoGenerated(p, cwd);
326
+ if (match) return autoGeneratedError(p, match);
327
+ }
328
+ return undefined;
329
+ }
330
+
238
331
  /** Public seam for tools registered outside wrapToolDefinition (apply_patch,
239
332
  * str_replace_editor) to refresh the freshness baseline after their own
240
333
  * successful mutations. */
@@ -340,7 +433,7 @@ export function wrapToolDefinition(
340
433
  // per wrapped instance (cache-safe: byte-stable for the session).
341
434
  description:
342
435
  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.`
436
+ ? `${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
437
  : base.description,
345
438
  prepareArguments(args: unknown) {
346
439
  let prepared = base.prepareArguments ? base.prepareArguments(args as never) : args;
@@ -366,6 +459,35 @@ export function wrapToolDefinition(
366
459
  base.name === "read" && isRecord(params) ? (params.__mtSelector as ParsedSelector | undefined) : undefined;
367
460
  if (isRecord(params)) delete params.__mtSelector;
368
461
 
462
+ // sqlite / archive views: plain `db.sqlite` (exists literally, would
463
+ // read binary garbage) and peeled `db.sqlite:users` /
464
+ // `pkg.tgz:src/x.ts:50-80` forms (applySpecialView peels internally).
465
+ // Literal-wins is preserved: a raw path that exists and is NOT sqlite
466
+ // falls through to the normal read; the peeled forms only trigger when
467
+ // the raw path is missing (standard selector order).
468
+ if (base.name === "read" && isRecord(params) && typeof params.path === "string" && !selector) {
469
+ const rawPath: string = params.path;
470
+ const rawAbs = resolvePath(cwd, rawPath);
471
+ let view: { text: string } | null = null;
472
+ if (existsSync(rawAbs) && isSqliteFile(rawAbs)) {
473
+ try {
474
+ view = { text: readSqlite(rawAbs, undefined, rawPath) };
475
+ } catch (err) {
476
+ throw new Error(err instanceof Error ? err.message : String(err));
477
+ }
478
+ } else if (existsSync(rawAbs) && archiveKind(rawPath)) {
479
+ view = { text: readArchiveListing(rawAbs, archiveKind(rawPath)!, rawPath).text };
480
+ } else if (!existsSync(rawAbs) && rawPath.includes(":")) {
481
+ view = applySpecialView(rawPath, cwd);
482
+ }
483
+ if (view) {
484
+ // Record the freshness baseline for the STEM so a follow-up write
485
+ // to the extracted file is judged normally (members have none).
486
+ await recordReadMtimes({ path: rawPath }, cwd);
487
+ return { content: [{ type: "text", text: view.text }], details: undefined };
488
+ }
489
+ }
490
+
369
491
  // Selector peel (execute-time: needs ctx.cwd for the literal-wins probe).
370
492
  if (base.name === "read" && !selector && isRecord(params) && typeof params.path === "string" && params.path.includes(":")) {
371
493
  params = applyReadSelector(params, cwd);
@@ -384,6 +506,10 @@ export function wrapToolDefinition(
384
506
  typeof params.offset === "number" ? params.offset : undefined,
385
507
  typeof params.limit === "number" ? params.limit : undefined,
386
508
  );
509
+ // Selector reads record the freshness baseline too (params.path is
510
+ // the peeled stem here) — a ranged read must not blind the write
511
+ // guard for the rest of the file (live finding, reviewer 2026-10-06).
512
+ await recordReadMtimes(params, cwd);
387
513
  return { ...result, details: base.name === "read" ? undefined : result.details };
388
514
  }
389
515
 
@@ -393,6 +519,8 @@ export function wrapToolDefinition(
393
519
  // THIS session read earlier but someone else changed since must
394
520
  // fail loudly instead of clobbering the foreign edit.
395
521
  if (base.name === "write") {
522
+ const gen = guardAutoGenerated(base.name, params, cwd);
523
+ if (gen) return { content: [{ type: "text", text: gen }], isError: true, details: undefined };
396
524
  const stale = await checkWriteFresh(params, cwd);
397
525
  if (stale) {
398
526
  return { content: [{ type: "text", text: stale }], isError: true, details: undefined };
@@ -432,9 +560,17 @@ export function wrapToolDefinition(
432
560
  const noopIdx = (Array.isArray(params?.edits) ? params.edits : typeof params?.oldText === "string" ? [{ oldText: params.oldText, newText: params.newText }] : [])
433
561
  .findIndex((e: any) => isRecord(e) && e.oldText === e.newText);
434
562
  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.`);
563
+ const genBlock = guardAutoGenerated("edit", params, cwd);
564
+ if (genBlock) return { content: [{ type: "text", text: genBlock }], isError: true, details: undefined };
435
565
  try {
436
566
  const result = await freshDef.execute(toolCallId, params, signal, onUpdate, ctx);
437
567
  editMismatchCounts?.delete(resolvePath(cwd, typeof params?.path === "string" ? params.path : ""));
568
+ // Own edit refreshes the freshness baseline (same contract as write/
569
+ // apply_patch/str_replace_editor): without this, read → edit → write
570
+ // false-positives — the write compares against the stale READ-time
571
+ // mtime (live finding, reviewer 2026-10-06; recordMutatedMtimes'
572
+ // edit branch was dead code for exactly this reason).
573
+ await recordMutatedMtimes("edit", params, cwd);
438
574
  return result;
439
575
  } catch (catchedErr: any) {
440
576
  let err: any = catchedErr;
@@ -461,7 +597,9 @@ export function wrapToolDefinition(
461
597
  else fixedParams.oldText = retry.fixedEdits[0].oldText;
462
598
  onRepair(base.name, ["trim-match-retry"]);
463
599
  try {
464
- return await freshDef.execute(toolCallId, fixedParams, signal, onUpdate, ctx);
600
+ const retried = await freshDef.execute(toolCallId, fixedParams, signal, onUpdate, ctx);
601
+ await recordMutatedMtimes("edit", fixedParams, cwd); // params.path unchanged by the retry
602
+ return retried;
465
603
  } catch (retryErr: any) {
466
604
  // A failed trim-retry is still a miss — fall through to the
467
605
  // unresolvable path below so it counts toward escalation.
@@ -569,6 +707,8 @@ export default function repairModule(pi: ExtensionAPI) {
569
707
  renderShell: "self",
570
708
  async execute(_toolCallId, params, _signal, _onUpdate, ctx) {
571
709
  const cwd = ctx?.cwd || process.cwd();
710
+ const genBlock = guardAutoGenerated("apply_patch", params, cwd);
711
+ if (genBlock) return { content: [{ type: "text", text: genBlock }], isError: true, details: undefined };
572
712
  let parsed;
573
713
  try {
574
714
  parsed = parsePatch(params.patch);
@@ -604,6 +744,8 @@ export default function repairModule(pi: ExtensionAPI) {
604
744
  pi.registerTool({
605
745
  ...strReplaceDef,
606
746
  async execute(toolCallId: string, params: any, signal: any, onUpdate: any, ctx: any) {
747
+ const genBlock = guardAutoGenerated("str_replace_editor", params, ctx?.cwd || process.cwd());
748
+ if (genBlock) return { content: [{ type: "text", text: genBlock }], isError: true, details: undefined };
607
749
  const result = await strReplaceDef.execute(toolCallId, params, signal, onUpdate, ctx);
608
750
  // Refresh the freshness baseline for the edited file (same rationale as
609
751
  // apply_patch above) — only on success, only for plain file paths.
@@ -643,7 +785,19 @@ export default function repairModule(pi: ExtensionAPI) {
643
785
  }
644
786
  if (event.toolName === "read" && isRecord(event.input) && ctx.cwd) {
645
787
  const filePath = typeof event.input.path === "string" ? event.input.path.trim() : "";
646
- if (filePath && looksLikeCodePath(filePath) && !existsSync(resolvePath(ctx.cwd, filePath))) {
788
+ // Selector reads (`file.ts:50-200`) probe the STEM: this hook runs on
789
+ // the RAW path, but the selector is only peeled inside execute —
790
+ // probing the un-peeled path would hard-block the module's own
791
+ // advertised read grammar (live finding, reviewer 2026-10-06). An
792
+ // invalid selector keeps the raw path so execute surfaces the loud error.
793
+ let probe = filePath;
794
+ if (filePath && !existsSync(resolvePath(ctx.cwd, probe))) {
795
+ try {
796
+ const peeled = peelPathSelector(filePath);
797
+ if (peeled.selector) probe = peeled.stem;
798
+ } catch { /* invalid selector — keep the raw path */ }
799
+ }
800
+ if (filePath && looksLikeCodePath(probe) && !existsSync(resolvePath(ctx.cwd, probe))) {
647
801
  const filename = filePath.split("/").pop() ?? filePath;
648
802
  const relDir = dirname(filePath);
649
803
  const dirPart = relDir !== "." ? ` under ${relDir}/` : "";
@@ -665,6 +819,7 @@ export default function repairModule(pi: ExtensionAPI) {
665
819
  ` Argument repair: ${live.arguments ? "on" : "off"}`,
666
820
  ` Edit mismatch repair: ${live.editRetry ? "on" : "off"}`,
667
821
  ` Tool-call guards: ${live.guards ? "on" : "off"}`,
822
+ ` Auto-generated write guard: ${live.autoGenGuard ? "on" : "off"}`,
668
823
  ` 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)` : ""}`,
669
824
  "",
670
825
  `**Repairs this session:** ${total} total`,
@@ -0,0 +1,89 @@
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, 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. `patterns` injectable
69
+ * for tests; caller passes cwd-relative resolution. */
70
+ export function checkAutoGenerated(
71
+ absPath: string,
72
+ cwd: string,
73
+ patterns: readonly string[] = AUTO_GENERATED_PATTERNS,
74
+ ): AutoGeneratedMatch | null {
75
+ const rel = isAbsolute(absPath) ? resolvePath(absPath).slice(cwd.length + 1) : absPath;
76
+ for (const pattern of patterns) {
77
+ if (matchesPattern(rel, pattern)) return { pattern };
78
+ }
79
+ return null;
80
+ }
81
+
82
+ /** The model-facing refusal. Names the pattern + the bash override hatch. */
83
+ export function autoGeneratedError(path: string, match: AutoGeneratedMatch): string {
84
+ return (
85
+ `${path} is auto-generated (matched ${match.pattern}) — edit its source and regenerate ` +
86
+ `(npm install / cargo build / tsc …) instead of editing the output. ` +
87
+ `If you really must, use bash to write it deliberately.`
88
+ );
89
+ }
@@ -0,0 +1,101 @@
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
+ /** Extract one member's bytes (tar -xOf / unzip -p). Throws on missing. */
68
+ function extractMember(archive: string, kind: ArchiveKind, member: string): Buffer {
69
+ const cmd = kind === "zip" ? "unzip" : "tar";
70
+ const args = kind === "zip" ? ["-p", archive, member] : ["-xOf", archive, member];
71
+ // execFileSync with a Buffer return keeps binary bytes intact.
72
+ return execFileSync(cmd, args, { timeout: TAR_TIMEOUT_MS, maxBuffer: 8 * 1024 * 1024 });
73
+ }
74
+
75
+ export interface ArchiveReadResult {
76
+ text: string;
77
+ }
78
+
79
+ /** Read an archive (no selector) → listing. */
80
+ export function readArchiveListing(archive: string, kind: ArchiveKind, displayPath: string): ArchiveReadResult {
81
+ const members = listMembers(archive, kind);
82
+ const shown = members.slice(0, LISTING_MAX);
83
+ const footer = members.length > shown.length ? `\n[showing ${shown.length} of ${members.length} members]` : "";
84
+ return { text: `${displayPath} — ${members.length} member(s)\n${shown.join("\n")}${footer}` };
85
+ }
86
+
87
+ /** Read one member (optionally pre-sliced by the caller's line ranges). */
88
+ export function readArchiveMember(archive: string, kind: ArchiveKind, member: string, displayPath: string): ArchiveReadResult {
89
+ const members = listMembers(archive, kind);
90
+ const match = matchMember(members, member);
91
+ if ("error" in match) return { text: `${displayPath} : ${member}\n${match.error}` };
92
+ const buf = extractMember(archive, kind, match.member);
93
+ if (buf.length > MEMBER_MAX_BYTES) {
94
+ return { text: `${displayPath} : ${match.member}\nmember is ${buf.length} bytes (cap ${MEMBER_MAX_BYTES}) — extract with bash, then read the file.` };
95
+ }
96
+ if (buf.subarray(0, 8192).includes(0)) {
97
+ return { text: `${displayPath} : ${match.member}\nbinary member — extract with bash (tar -xOf / unzip -p), then read the file.` };
98
+ }
99
+ const text = buf.toString("utf8");
100
+ return { text: `${displayPath} : ${match.member}${match.via === "suffix" ? ` (matched ${match.member})` : ""}\n${text}` };
101
+ }
@@ -0,0 +1,185 @@
1
+ // read-sqlite — sqlite views for the wrapped read (OMP read-sqlite.ts +
2
+ // sqlite-reader.ts semantics on the repair selector grammar).
3
+ //
4
+ // Grammar (parsed from the selector AFTER the path stem resolves to a real
5
+ // sqlite file — see parseSqliteSelector):
6
+ // db.sqlite → table list
7
+ // db.sqlite:users → schema + first 10 rows
8
+ // db.sqlite:users:42 → row by rowid
9
+ // db.sqlite:users:name=alice → row(s) by key equality (LIMIT 20)
10
+ // db.sqlite:SELECT … → read-only query (SELECT/WITH/PRAGMA only)
11
+ // Engine: node:sqlite DatabaseSync opened READ-ONLY per call (unflagged
12
+ // since Node 22.13 < the repo engines floor). Fallback seam: swap
13
+ // `openDatabase` if a runtime refuses (e.g. sqlite3 CLI).
14
+
15
+ import { readFileSync } from "node:fs";
16
+ import { DatabaseSync } from "node:sqlite";
17
+
18
+ /** Row cap for raw queries (OMP MAX_RAW_QUERY_ROWS, trimmed). */
19
+ export const MAX_RAW_QUERY_ROWS = 200;
20
+ /** Rows shown under a bare table view. */
21
+ export const TABLE_PREVIEW_ROWS = 10;
22
+ /** Row cap for key-lookups. */
23
+ export const KEY_LOOKUP_LIMIT = 20;
24
+
25
+ export type SqliteSelector =
26
+ | { kind: "tables" }
27
+ | { kind: "table"; table: string }
28
+ | { kind: "rowid"; table: string; rowid: number }
29
+ | { kind: "key"; table: string; key: string; value: string }
30
+ | { kind: "query"; sql: string };
31
+
32
+ /**
33
+ * Parse a sqlite sub-selector (everything after the file path). Exported for
34
+ * tests. Empty → tables view. A numeric segment after a table is a rowid;
35
+ * `key=value` is a key lookup; a leading `?` or a SELECT/WITH/PRAGMA head is
36
+ * a raw query.
37
+ */
38
+ export function parseSqliteSelector(selector: string | undefined): SqliteSelector {
39
+ const trimmed = (selector ?? "").trim();
40
+ if (!trimmed) return { kind: "tables" };
41
+ // `?…` marks a query explicitly (the head guard still enforces read-only);
42
+ // a bare SELECT/WITH/PRAGMA head is accepted uncannily.
43
+ if (trimmed.startsWith("?")) return { kind: "query", sql: trimmed.slice(1).trim() };
44
+ if (/^(select|with|pragma)\b/i.test(trimmed)) return { kind: "query", sql: trimmed };
45
+ const parts = trimmed.split(":");
46
+ const table = parts[0]!.trim();
47
+ if (!table) throw new Error(`invalid sqlite selector "${trimmed}" — expected :table, :table:rowid, :table:key=value or :?SELECT`);
48
+ if (parts.length === 1) return { kind: "table", table };
49
+ const second = parts.slice(1).join(":").trim();
50
+ const rowid = /^\d+$/.exec(second);
51
+ if (rowid) return { kind: "rowid", table, rowid: Number(second) };
52
+ const kv = /^([A-Za-z_][\w]*)=(.*)$/s.exec(second);
53
+ if (kv) return { kind: "key", table, key: kv[1]!, value: kv[2]!.replace(/^"(.*)"$/s, "$1") };
54
+ throw new Error(`invalid sqlite selector "${second}" — use :${table}:<rowid>, :${table}:<key>=<value>, or :?SELECT …`);
55
+ }
56
+
57
+ /** Sniff: first 16 bytes are the SQLite magic header. */
58
+ export function isSqliteFile(absPath: string): boolean {
59
+ try {
60
+ const fd = readFileSync(absPath);
61
+ return fd.length >= 16 && fd.subarray(0, 16).equals(Buffer.from("SQLite format 3\0", "utf8"));
62
+ } catch {
63
+ return false;
64
+ }
65
+ }
66
+
67
+ /** Quote an SQL identifier (double the embedded quotes). */
68
+ function quoteIdent(name: string): string {
69
+ return `"${name.replaceAll('"', '""')}"`;
70
+ }
71
+
72
+ /** One row → aligned key/value lines (repo read style, `—` for null). */
73
+ function renderRow(row: Record<string, unknown>, columns: string[]): string {
74
+ return columns.map((c) => `${c}: ${row[c] === null || row[c] === undefined ? "—" : String(row[c])}`).join("\n");
75
+ }
76
+
77
+ /** Rows → aligned text table. */
78
+ function renderRows(columns: string[], rows: Record<string, unknown>[]): string {
79
+ const cells = rows.map((r) => columns.map((c) => (r[c] === null || r[c] === undefined ? "—" : String(r[c] ?? ""))));
80
+ const widths = columns.map((c, i) => Math.max(c.length, ...cells.map((row) => row[i]!.length)));
81
+ const line = (parts: string[]) => parts.map((p, i) => p.padEnd(widths[i]!)).join(" ").trimEnd();
82
+ return [line(columns), line(widths.map((w) => "─".repeat(w))), ...cells.map(line)].join("\n");
83
+ }
84
+
85
+ function columnsOf(db: DatabaseSync, table: string): string[] {
86
+ return (db.prepare(`PRAGMA table_info(${quoteIdent(table)})`).all() as Array<Record<string, unknown>>).map(
87
+ (c) => String(c.name),
88
+ );
89
+ }
90
+
91
+ function tableNames(db: DatabaseSync): string[] {
92
+ return (
93
+ db.prepare(`SELECT name FROM sqlite_master WHERE type='table' AND name NOT LIKE 'sqlite_%' ORDER BY name`).all() as Array<{
94
+ name: string;
95
+ }>
96
+ ).map((r) => r.name);
97
+ }
98
+
99
+ function countRows(db: DatabaseSync, table: string): number {
100
+ const row = db.prepare(`SELECT count(*) AS n FROM ${quoteIdent(table)}`).get() as { n: number };
101
+ return Number(row.n);
102
+ }
103
+
104
+ /** The single seam for tests (a runtime without node:sqlite can swap a CLI
105
+ * driver in here). Opens the db READ-ONLY; caller closes. */
106
+ export function openDatabase(path: string): DatabaseSync {
107
+ return new DatabaseSync(path, { readOnly: true });
108
+ }
109
+
110
+ /** Execute a parsed selector against the db. Returns model-facing text. */
111
+ export function executeSqliteView(db: DatabaseSync, sel: SqliteSelector, displayPath: string): string {
112
+ switch (sel.kind) {
113
+ case "tables": {
114
+ const names = tableNames(db);
115
+ if (names.length === 0) return `${displayPath} — no tables.`;
116
+ const parts = names.map((name) => {
117
+ const cols = columnsOf(db, name);
118
+ return `${name} · ${countRows(db, name)} rows · ${cols.join(", ")}`;
119
+ });
120
+ return `${displayPath} — ${names.length} table(s)\n${parts.join("\n")}`;
121
+ }
122
+ case "table": {
123
+ const names = tableNames(db);
124
+ if (!names.includes(sel.table)) {
125
+ return `no table "${sel.table}" in ${displayPath} — tables: ${names.join(", ") || "(none)"}`;
126
+ }
127
+ const cols = columnsOf(db, sel.table);
128
+ const info = db.prepare(`PRAGMA table_info(${quoteIdent(sel.table)})`).all() as Array<Record<string, unknown>>;
129
+ const schema = info
130
+ .map((c) => ` ${c.name} ${c.type || "ANY"}${Number(c.pk) ? " PRIMARY KEY" : ""}${Number(c.notnull) ? " NOT NULL" : ""}`)
131
+ .join("\n");
132
+ const rows = db
133
+ .prepare(`SELECT * FROM ${quoteIdent(sel.table)} LIMIT ${TABLE_PREVIEW_ROWS}`)
134
+ .all() as Array<Record<string, unknown>>;
135
+ const total = countRows(db, sel.table);
136
+ const footer = total > rows.length ? `\n[${rows.length} of ${total} rows — query with :${sel.table}:<rowid> or :?SELECT]` : "";
137
+ return `${displayPath} : ${sel.table} — ${total} rows\n${schema}\n\n${rows.length ? renderRows(cols, rows) : "(empty)"}${footer}`;
138
+ }
139
+ case "rowid": {
140
+ const cols = columnsOf(db, sel.table);
141
+ const row = db.prepare(`SELECT * FROM ${quoteIdent(sel.table)} WHERE rowid = ?`).get(sel.rowid) as
142
+ | Record<string, unknown>
143
+ | undefined;
144
+ if (!row) return `no row with rowid ${sel.rowid} in ${displayPath} : ${sel.table}`;
145
+ return `${displayPath} : ${sel.table} : rowid ${sel.rowid}\n${renderRow(row, cols)}`;
146
+ }
147
+ case "key": {
148
+ const cols = columnsOf(db, sel.table);
149
+ if (!cols.includes(sel.key)) {
150
+ return `no column "${sel.key}" in ${displayPath} : ${sel.table} — columns: ${cols.join(", ")}`;
151
+ }
152
+ const rows = db
153
+ .prepare(`SELECT * FROM ${quoteIdent(sel.table)} WHERE ${quoteIdent(sel.key)} = ? LIMIT ${KEY_LOOKUP_LIMIT}`)
154
+ .all(sel.value) as Array<Record<string, unknown>>;
155
+ if (rows.length === 0) return `no rows where ${sel.key} = "${sel.value}" in ${displayPath} : ${sel.table}`;
156
+ const body = rows.map((r) => renderRow(r, cols)).join("\n\n---\n\n");
157
+ const footer = rows.length >= KEY_LOOKUP_LIMIT ? `\n[stopped at ${KEY_LOOKUP_LIMIT} rows — narrow the key]` : "";
158
+ return `${displayPath} : ${sel.table} : ${sel.key}="${sel.value}" — ${rows.length} row(s)\n${body}${footer}`;
159
+ }
160
+ case "query": {
161
+ const head = sel.sql.trim().slice(0, 6).toUpperCase();
162
+ if (!/^(SELECT|WITH|PRAGMA)/.test(head)) {
163
+ throw new Error(`only read-only queries (SELECT/WITH/PRAGMA) — got "${sel.sql.slice(0, 40)}". Use bash for writes.`);
164
+ }
165
+ const stmt = db.prepare(sel.sql);
166
+ const columns = (stmt as unknown as { columns: () => Array<{ name: string }> }).columns().map((c) => c.name);
167
+ const rows = stmt.all() as Array<Record<string, unknown>>;
168
+ const total = rows.length;
169
+ const shown = rows.slice(0, MAX_RAW_QUERY_ROWS);
170
+ const footer = total > shown.length ? `\n[showing ${shown.length} of ${total} rows — add LIMIT/TARGET the query]` : "";
171
+ return `${displayPath} : query — ${total} row(s)\n${shown.length ? renderRows(columns, shown) : "(no rows)"}${footer}`;
172
+ }
173
+ }
174
+ }
175
+
176
+ /** Full read view for a sqlite path + selector. Opens/closes the db. */
177
+ export function readSqlite(absPath: string, selector: string | undefined, displayPath: string): string {
178
+ const sel = parseSqliteSelector(selector);
179
+ const db = openDatabase(absPath);
180
+ try {
181
+ return executeSqliteView(db, sel, displayPath);
182
+ } finally {
183
+ db.close();
184
+ }
185
+ }
@@ -20,6 +20,8 @@ export interface RepairSettings {
20
20
  editRetry: boolean;
21
21
  /** Destructive-bash + read-on-guessed-path guards. */
22
22
  guards: boolean;
23
+ /** Refuse write/edit on auto-generated files (lockfiles, dist, min.js). */
24
+ autoGenGuard: boolean;
23
25
  /** Auto-background long foreground bash calls. */
24
26
  autoBg: boolean;
25
27
  /** Foreground threshold (seconds) before auto-backgrounding. */
@@ -30,6 +32,7 @@ export const DEFAULT_REPAIR_SETTINGS: RepairSettings = {
30
32
  arguments: true,
31
33
  editRetry: true,
32
34
  guards: true,
35
+ autoGenGuard: true,
33
36
  autoBg: false,
34
37
  autoBgSecs: 120,
35
38
  };
@@ -55,7 +58,7 @@ function section(json: Record<string, unknown> | null, key: string): Record<stri
55
58
  /** Merge one settings layer's `repair` keys over out (field-wise override). */
56
59
  function mergeLayer(out: RepairSettings, json: Record<string, unknown> | null): void {
57
60
  const s = section(json, "repair");
58
- for (const key of ["arguments", "editRetry", "guards", "autoBg"] as const) {
61
+ for (const key of ["arguments", "editRetry", "guards", "autoGenGuard", "autoBg"] as const) {
59
62
  if (typeof s[key] === "boolean") out[key] = s[key];
60
63
  }
61
64
  if (typeof s.autoBgSecs === "number" && Number.isFinite(s.autoBgSecs)) {