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
@@ -0,0 +1,178 @@
1
+ // ponytail: ported from oh-my-pi packages/coding-agent/src/tools/jfind
2
+ // questions.ts — the three request shapes (filename batch, sketch batch,
3
+ // passage verification), each one state + one noul question per entry.
4
+ // OMP's prompt.render templates are inlined as template strings; the `Judge`
5
+ // interface is replaced by a minimal local one over modelRegistry.classify.
6
+
7
+ import { plainContent, type Passage, type HeatRange } from "./tree.js";
8
+ import type { FileEntry } from "./tree.js";
9
+
10
+ /** Minimal judge seam — implemented over modelRegistry.classify in
11
+ * judge.ts; tests inject a fake. */
12
+ export interface Judge {
13
+ readonly label: string;
14
+ judge(request: Request, options?: { signal?: AbortSignal }): Promise<JudgmentResult>;
15
+ }
16
+
17
+ /** One noul question (OMP judgment/types.ts shape, trimmed). */
18
+ export interface NoulQuestion {
19
+ type: "noul";
20
+ instructions: string;
21
+ criteria?: { true?: string; false?: string };
22
+ }
23
+
24
+ export interface Request {
25
+ state: Record<string, unknown>;
26
+ questions: Record<string, NoulQuestion>;
27
+ }
28
+
29
+ export interface JudgmentResult {
30
+ answers: Record<string, { probability?: number }>;
31
+ usage?: { input?: number; output?: number };
32
+ }
33
+
34
+ const TASK =
35
+ "Semantic grep over a source tree: locate files whose content matches the search description. Entries are judged by name, size, position in the tree, and (for folders) a sample of what they contain.";
36
+
37
+ const TREE_FORMAT =
38
+ "`tree` is a directory listing. Lines starting with # are headers: `# dir/` is a folder; more #s means deeper nesting under the header above; a header may fold several levels (`# a/b/c/`). Every judgeable entry carries a tag like e017 right after the #s: files as `e017 name (size)`. Untagged header lines are only structure.";
39
+
40
+ const FILE_CRITERIA = {
41
+ no: "The file is unrelated by name and location; generated executable implementation can still be relevant.",
42
+ yes: "A file at this path plausibly contains code, text, or data matching the search.",
43
+ };
44
+
45
+ const SKETCH_CRITERIA = {
46
+ no: "Unrelated code; mere mentions, declarations, call sites, tests or configuration without implementation.",
47
+ yes: "Likely substantive implementation, definition or explanation of any part of the requested behavior. A matching helper for one step counts. Excerpts omit most source: favor recall.",
48
+ };
49
+
50
+ const PASSAGE_CRITERIA = {
51
+ no: "This passage only mentions, calls, imports, tests, or configures the subject, or contains unrelated code sharing keywords.",
52
+ yes: "This passage contains an implementation, definition, or substantive explanation of an important part of the search. A helper implementing one requested step counts even when other steps are elsewhere.",
53
+ };
54
+
55
+ /** Question key of the `i`th entry in a filename batch. */
56
+ export function entryKey(i: number): string {
57
+ return `e${String(i).padStart(3, "0")}`;
58
+ }
59
+
60
+ /** Question key of the `k`th passage in a sketch or verification batch. */
61
+ export function passageKey(k: number): string {
62
+ return `p${String(k).padStart(2, "0")}`;
63
+ }
64
+
65
+ /** Copy of `record` with keys in lexicographic order (wire parity with OMP). */
66
+ function sorted<T>(record: Record<string, T>): Record<string, T> {
67
+ const out: Record<string, T> = {};
68
+ for (const key of Object.keys(record).sort()) out[key] = record[key]!;
69
+ return out;
70
+ }
71
+
72
+ const NAME_INSTRUCTIONS =
73
+ 'Is the file tagged {{key}} ("{{name}}") likely to contain what this search is looking for: "{{query}}"? Judge by its name, size, and place in `tree`; apply `criteria.file`.';
74
+
75
+ /** Model-facing listing of `entries` as a prefix-folded directory tree. */
76
+ function renderTree(entries: readonly FileEntry[], tagOf: (index: number) => string): string {
77
+ // ponytail: flat prefix-fold without pi-utils' path-tree builder — group
78
+ // by directory prefix, one # per depth.
79
+ const lines: string[] = [];
80
+ let lastDirs: string[] = [];
81
+ entries.forEach((entry, index) => {
82
+ const parts = entry.rel.split("/");
83
+ const dirs = parts.slice(0, -1);
84
+ let common = 0;
85
+ while (common < dirs.length && common < lastDirs.length && dirs[common] === lastDirs[common]) common++;
86
+ for (let d = common; d < dirs.length; d++) {
87
+ if (lines.length > 0 && d === common) lines.push("");
88
+ lines.push(`${"#".repeat(d + 2)} ${dirs[d]!}/`);
89
+ }
90
+ const name = parts[parts.length - 1]!;
91
+ lines.push(`${"#".repeat(dirs.length + 2)} ${tagOf(index)} ${name} (${humanSize(entry.size)})`);
92
+ lastDirs = dirs;
93
+ });
94
+ return lines.join("\n");
95
+ }
96
+
97
+ const SIZE_UNITS = ["B", "KB", "MB", "GB", "TB"];
98
+
99
+ function humanSize(bytes: number): string {
100
+ let value = bytes;
101
+ let unit = 0;
102
+ while (value >= 1024 && unit < SIZE_UNITS.length - 1) {
103
+ value /= 1024;
104
+ unit++;
105
+ }
106
+ return unit === 0 ? `${bytes} B` : `${value.toFixed(1)} ${SIZE_UNITS[unit]}`;
107
+ }
108
+
109
+ /** One noul per file over a shared tree-rendered listing of the batch. */
110
+ export function nameBatch(project: string, query: string, entries: readonly FileEntry[]): Request {
111
+ const questions: Record<string, NoulQuestion> = {};
112
+ entries.forEach((entry, i) => {
113
+ const key = entryKey(i);
114
+ const name = entry.rel.slice(entry.rel.lastIndexOf("/") + 1);
115
+ questions[key] = {
116
+ type: "noul",
117
+ instructions: NAME_INSTRUCTIONS.replaceAll("{{key}}", key).replaceAll("{{name}}", name).replaceAll("{{query}}", query),
118
+ };
119
+ });
120
+ return {
121
+ state: {
122
+ criteria: { file: FILE_CRITERIA },
123
+ format: TREE_FORMAT,
124
+ project,
125
+ search: query,
126
+ task: TASK,
127
+ tree: renderTree(entries, entryKey),
128
+ },
129
+ questions,
130
+ };
131
+ }
132
+
133
+ /** One sketch card: the file it came from and its budgeted verbatim lines. */
134
+ export interface SketchCard {
135
+ fileKey: string;
136
+ rel: string;
137
+ sketch: string;
138
+ }
139
+
140
+ /** Mixed-file packing of sketch cards. */
141
+ export function sketchBatch(query: string, cards: readonly SketchCard[]): Request {
142
+ const files: Record<string, string> = {};
143
+ const passages: Record<string, [string, string]> = {};
144
+ const questions: Record<string, NoulQuestion> = {};
145
+ cards.forEach((card, k) => {
146
+ const key = passageKey(k);
147
+ files[card.fileKey] = card.rel;
148
+ passages[key] = [card.fileKey, card.sketch];
149
+ questions[key] = {
150
+ type: "noul",
151
+ instructions: `Could passage ${key} implement a requested step of search? Apply criteria.`,
152
+ };
153
+ });
154
+ return {
155
+ state: { criteria: SKETCH_CRITERIA, files: sorted(files), passages, search: query },
156
+ questions,
157
+ };
158
+ }
159
+
160
+ /** Verification of complete passages from one file, judged independently. */
161
+ export function passageBatch(query: string, rel: string, passages: readonly Passage[]): Request {
162
+ const entries: Record<string, string> = {};
163
+ const questions: Record<string, NoulQuestion> = {};
164
+ passages.forEach((passage, k) => {
165
+ const key = passageKey(k);
166
+ entries[key] = plainContent(passage);
167
+ questions[key] = {
168
+ type: "noul",
169
+ instructions: `Does \`passages.${key}\` substantively implement, define, or explain part of "${query}"? Apply \`criteria\`.`,
170
+ };
171
+ });
172
+ return {
173
+ state: { criteria: PASSAGE_CRITERIA, file: rel, passages: entries, search: query },
174
+ questions,
175
+ };
176
+ }
177
+
178
+ export type { HeatRange };
@@ -0,0 +1,374 @@
1
+ // ponytail: ported from oh-my-pi packages/coding-agent/src/tools/jfind
2
+ // {tree,passages}.ts — the eligible file walk (native glob → a plain
3
+ // .gitignore-respecting fs walk with the same deny-lists) and the
4
+ // byte-bounded source windows/sketches/heat merging.
5
+
6
+ import { lines, clipBytes, countOccurrences } from "./lexical.js";
7
+ import { execFileSync } from "node:child_process";
8
+ import { readdirSync, readFileSync, statSync } from "node:fs";
9
+ import { join } from "node:path";
10
+
11
+ // ── eligibility deny-lists (tree.ts, verbatim) ──────────────────────────────
12
+
13
+ const DENY_DIRS: Record<string, true> = {
14
+ ".git": true,
15
+ node_modules: true,
16
+ target: true,
17
+ dist: true,
18
+ build: true,
19
+ out: true,
20
+ ".next": true,
21
+ ".nuxt": true,
22
+ ".turbo": true,
23
+ ".cache": true,
24
+ __pycache__: true,
25
+ ".venv": true,
26
+ venv: true,
27
+ ".tox": true,
28
+ coverage: true,
29
+ ".idea": true,
30
+ ".vscode": true,
31
+ ".gradle": true,
32
+ ".mypy_cache": true,
33
+ ".pytest_cache": true,
34
+ ".ruff_cache": true,
35
+ ".parcel-cache": true,
36
+ };
37
+
38
+ const DENY_FILES: Record<string, true> = {
39
+ "Cargo.lock": true,
40
+ "package-lock.json": true,
41
+ "yarn.lock": true,
42
+ "pnpm-lock.yaml": true,
43
+ "bun.lock": true,
44
+ "bun.lockb": true,
45
+ "poetry.lock": true,
46
+ "Pipfile.lock": true,
47
+ "composer.lock": true,
48
+ "Gemfile.lock": true,
49
+ "go.sum": true,
50
+ "flake.lock": true,
51
+ ".DS_Store": true,
52
+ "Thumbs.db": true,
53
+ };
54
+
55
+ const SECRET_FILES: Record<string, true> = {
56
+ ".env": true,
57
+ ".envrc": true,
58
+ ".netrc": true,
59
+ ".npmrc": true,
60
+ ".pypirc": true,
61
+ ".pgpass": true,
62
+ ".boto": true,
63
+ ".s3cfg": true,
64
+ ".dockercfg": true,
65
+ ".git-credentials": true,
66
+ ".htpasswd": true,
67
+ htpasswd: true,
68
+ credentials: true,
69
+ "credentials.json": true,
70
+ "client_secret.json": true,
71
+ "service-account.json": true,
72
+ id_rsa: true,
73
+ id_dsa: true,
74
+ id_ecdsa: true,
75
+ id_ed25519: true,
76
+ };
77
+
78
+ const SECRET_EXT = [
79
+ "pem", "key", "p12", "pfx", "jks", "keystore", "bks", "ppk", "kdbx", "gpg", "pgp", "asc", "der",
80
+ "crt", "cer", "tfvars", "tfvars.json", "tfstate", "tfstate.backup",
81
+ ];
82
+
83
+ const BINARY_EXT = [
84
+ "png", "jpg", "jpeg", "gif", "webp", "avif", "ico", "bmp", "tiff", "psd", "svg", "woff", "woff2",
85
+ "ttf", "otf", "eot", "zip", "gz", "tgz", "tar", "bz2", "xz", "zst", "7z", "rar", "pdf", "mp3",
86
+ "mp4", "mov", "avi", "mkv", "wav", "ogg", "flac", "wasm", "so", "dylib", "dll", "exe", "o", "a",
87
+ "class", "jar", "pyc", "pyo", "bin", "dat", "db", "sqlite", "sqlite3", "lock", "map", "min.js",
88
+ "min.css", "snap", "pb", "onnx", "safetensors", "parquet", "arrow", "ipynb",
89
+ ];
90
+
91
+ const ENV_TEMPLATES: Record<string, true> = {
92
+ ".env.example": true,
93
+ ".env.sample": true,
94
+ ".env.template": true,
95
+ ".env.dist": true,
96
+ };
97
+
98
+ function hasExt(lower: string, exts: readonly string[]): boolean {
99
+ return exts.some((ext) => lower.length > ext.length && lower.endsWith(`.${ext}`));
100
+ }
101
+
102
+ /** Credential material: exact names, `.env.*` variants (except templates), key/vault extensions. */
103
+ function secret(name: string): boolean {
104
+ if (Object.hasOwn(SECRET_FILES, name)) return true;
105
+ if (name.startsWith(".env.")) return !Object.hasOwn(ENV_TEMPLATES, name);
106
+ return hasExt(name.toLowerCase(), SECRET_EXT);
107
+ }
108
+
109
+ /** Whether a root-relative regular file is searchable. */
110
+ export function eligibleFile(rel: string, size: number, includeHidden: boolean): boolean {
111
+ if (size <= 0) return false;
112
+ const segments = rel.split("/");
113
+ const name = segments[segments.length - 1]!;
114
+ for (let i = 0; i < segments.length - 1; i++) {
115
+ const dir = segments[i]!;
116
+ if (Object.hasOwn(DENY_DIRS, dir) || (!includeHidden && dir.startsWith("."))) return false;
117
+ }
118
+ if (!includeHidden && name.startsWith(".")) return false;
119
+ return !Object.hasOwn(DENY_FILES, name) && !secret(name) && !hasExt(name.toLowerCase(), BINARY_EXT);
120
+ }
121
+
122
+ /** One eligible file under the search root. */
123
+ export interface FileEntry {
124
+ /** Absolute host path. */
125
+ path: string;
126
+ /** Root-relative display path with `/` separators. */
127
+ rel: string;
128
+ size: number;
129
+ }
130
+
131
+ /** ponytail: fixed-cap walk (3000 files) — gitignore-aware via `git ls-files`
132
+ * when inside a repo, plain walk otherwise; native glob not available. */
133
+ const LIST_CAP = 3000;
134
+
135
+ /** Every eligible file under `root` (directory), in path order. Symlinks are
136
+ * never followed; deny-lists mirror OMP's. Exported for tests. */
137
+ export function listFiles(rootAbs: string, includeHidden = false): FileEntry[] {
138
+ // Prefer git's own view (respects .gitignore) when this is a checkout.
139
+ const files: FileEntry[] = [];
140
+ let gitFiles: string[] | undefined;
141
+ try {
142
+ gitFiles = execFileSync("git", ["ls-files", "--cached", "--others", "--exclude-standard"], {
143
+ cwd: rootAbs,
144
+ encoding: "utf8",
145
+ timeout: 10_000,
146
+ })
147
+ .split("\n")
148
+ .filter(Boolean);
149
+ } catch {
150
+ gitFiles = undefined; // not a repo / no git — plain walk below
151
+ }
152
+ if (gitFiles) {
153
+ for (const rel of gitFiles) {
154
+ if (files.length >= LIST_CAP) break;
155
+ const abs = join(rootAbs, rel);
156
+ let size = 0;
157
+ try {
158
+ size = statSync(abs).size;
159
+ } catch {
160
+ continue;
161
+ }
162
+ if (!eligibleFile(rel.replaceAll("\\", "/"), size, includeHidden)) continue;
163
+ files.push({ path: abs, rel: rel.replaceAll("\\", "/"), size });
164
+ }
165
+ files.sort((a, b) => (a.rel < b.rel ? -1 : a.rel > b.rel ? 1 : 0));
166
+ return files;
167
+ }
168
+ const walk = (dir: string, relPrefix: string): void => {
169
+ if (files.length >= LIST_CAP) return;
170
+ let entries: string[];
171
+ try {
172
+ entries = readdirSync(dir);
173
+ } catch {
174
+ return;
175
+ }
176
+ for (const name of entries.sort()) {
177
+ if (files.length >= LIST_CAP) return;
178
+ if (!includeHidden && name.startsWith(".")) continue;
179
+ const abs = join(dir, name);
180
+ const rel = relPrefix ? `${relPrefix}/${name}` : name;
181
+ let st;
182
+ try {
183
+ st = statSync(abs);
184
+ } catch {
185
+ continue;
186
+ }
187
+ if (st.isDirectory()) {
188
+ if (Object.hasOwn(DENY_DIRS, name)) continue;
189
+ walk(abs, rel);
190
+ } else if (st.isFile()) {
191
+ if (eligibleFile(rel, st.size, includeHidden)) files.push({ path: abs, rel, size: st.size });
192
+ }
193
+ }
194
+ };
195
+ walk(rootAbs, "");
196
+ files.sort((a, b) => (a.rel < b.rel ? -1 : a.rel > b.rel ? 1 : 0));
197
+ return files;
198
+ }
199
+
200
+ // ── passages (passages.ts, verbatim) ────────────────────────────────────────
201
+
202
+ /** A contiguous run of tagged source lines (`L<n>| text`), 1-based inclusive. */
203
+ export interface Passage {
204
+ start: number;
205
+ end: number;
206
+ text: string;
207
+ /** Lexical score used for window selection and tie-breaking. */
208
+ score: number;
209
+ }
210
+
211
+ /** A judged line range with its yes-probability and a one-line preview. */
212
+ export interface HeatRange {
213
+ start: number;
214
+ end: number;
215
+ p: number;
216
+ snippet: string;
217
+ }
218
+
219
+ /** Contiguous whole-line windows bounded by bytes, including the final line. */
220
+ export function windows(text: string, bytes: number, keywords: readonly string[], weights: readonly number[]): Passage[] {
221
+ const source = lines(text);
222
+ const passages: Passage[] = [];
223
+ let start = 0;
224
+ while (start < source.length) {
225
+ let end = start;
226
+ let content = "";
227
+ let used = 0;
228
+ while (end < source.length) {
229
+ const line = source[end]!;
230
+ const prefix = `L${end + 1}| `;
231
+ const overhead = prefix.length + 1;
232
+ if (end > start && used + Buffer.byteLength(line) + overhead > bytes) break;
233
+ const piece = `${prefix}${clipBytes(line, Math.max(0, bytes - (used + overhead)))}\n`;
234
+ content += piece;
235
+ used += Buffer.byteLength(piece);
236
+ end++;
237
+ if (used >= bytes) break;
238
+ }
239
+ const lower = content.toLowerCase();
240
+ let score = 0;
241
+ for (let k = 0; k < keywords.length; k++) {
242
+ score += weights[k]! * Math.log1p(countOccurrences(lower, keywords[k]!));
243
+ }
244
+ passages.push({ start: start + 1, end, text: content, score });
245
+ start = end;
246
+ }
247
+ return passages;
248
+ }
249
+
250
+ /**
251
+ * Keep the best lexical windows and, when no words match, distribute the
252
+ * budget evenly through the file instead of always falling back to its
253
+ * opening bytes. Returned in file order.
254
+ */
255
+ export function selectWindows(passages: Passage[], limit: number): Passage[] {
256
+ let selected = passages;
257
+ if (selected.length > limit) {
258
+ if (selected.every((passage) => passage.score === 0)) {
259
+ const len = selected.length;
260
+ const step = Math.max(limit - 1, 1);
261
+ const keep = new Set<number>();
262
+ for (let k = 0; k < limit; k++) keep.add(Math.floor((k * (len - 1)) / step));
263
+ selected = selected.filter((_, index) => keep.has(index));
264
+ } else {
265
+ selected = [...selected].sort((a, b) => b.score - a.score || a.start - b.start).slice(0, limit);
266
+ }
267
+ }
268
+ return [...selected].sort((a, b) => a.start - b.start);
269
+ }
270
+
271
+ /** Passage text with the generated `L<n>| ` tags stripped. */
272
+ export function plainContent(passage: Passage): string {
273
+ let out = "";
274
+ const tagged = lines(passage.text);
275
+ for (let i = 0; i < tagged.length; i++) {
276
+ const line = tagged[i]!;
277
+ const prefix = `L${passage.start + i}| `;
278
+ out += `${line.startsWith(prefix) ? line.slice(prefix.length) : line}\n`;
279
+ }
280
+ return out;
281
+ }
282
+
283
+ /** Bytes reserved per selected sketch line for its `<line>: ` tag and separator. */
284
+ const SKETCH_LINE_OVERHEAD = 12;
285
+ /** Minimum bytes worth spending on one more sketch line. */
286
+ const SKETCH_MIN_LINE = 24;
287
+ /** Longest single sketch line. */
288
+ const SKETCH_MAX_LINE = 180;
289
+
290
+ /**
291
+ * A budgeted map of verbatim source lines, not an invented summary. Lines are
292
+ * ranked by keyword weight (plus a nudge for call-like lines) so deep
293
+ * implementation text can outrank headers, then emitted in file order.
294
+ */
295
+ export function sketch(passage: Passage, keywords: readonly string[], weights: readonly number[], budget: number): string {
296
+ const plain = lines(plainContent(passage));
297
+ const ranked: { index: number; score: number }[] = [];
298
+ for (let index = 0; index < plain.length; index++) {
299
+ const line = plain[index]!;
300
+ if (line.trim().length === 0) continue;
301
+ const lower = line.toLowerCase();
302
+ let score = line.includes("(") ? 0.1 : 0;
303
+ for (let k = 0; k < keywords.length; k++) {
304
+ if (lower.includes(keywords[k]!)) score += weights[k]!;
305
+ }
306
+ ranked.push({ index, score });
307
+ }
308
+ ranked.sort((a, b) => b.score - a.score || a.index - b.index);
309
+ const selected: { index: number; text: string }[] = [];
310
+ let used = 0;
311
+ for (const { index } of ranked) {
312
+ const available = Math.max(0, budget - (used + SKETCH_LINE_OVERHEAD));
313
+ if (available < SKETCH_MIN_LINE) break;
314
+ const line = plain[index]!.trim();
315
+ const text = `${passage.start + index}: ${clipBytes(line, Math.min(available, SKETCH_MAX_LINE))}`;
316
+ used += Buffer.byteLength(text) + 1;
317
+ selected.push({ index, text });
318
+ }
319
+ selected.sort((a, b) => a.index - b.index);
320
+ return selected.map((entry) => entry.text).join("\n");
321
+ }
322
+
323
+ /** Read a file's text prefix; binary/empty are expected misses. */
324
+ export interface ReadText {
325
+ text: string;
326
+ truncated: boolean;
327
+ }
328
+
329
+ const BINARY_PROBE_BYTES = 8192;
330
+
331
+ /** Read up to `maxBytes` of a text file; rejects binaries and blank files. */
332
+ export function readTextFile(absPath: string, maxBytes: number): ReadText {
333
+ let buf = readFileSync(absPath);
334
+ const probe = buf.subarray(0, Math.min(buf.length, BINARY_PROBE_BYTES));
335
+ if (probe.includes(0)) throw new Error("binary");
336
+ const truncated = buf.length > maxBytes;
337
+ if (truncated) {
338
+ buf = buf.subarray(0, maxBytes);
339
+ const newline = buf.lastIndexOf(0x0a);
340
+ if (newline !== -1) buf = buf.subarray(0, newline + 1);
341
+ }
342
+ const text = buf.toString("utf8");
343
+ if (lines(text).every((line) => line.trim().length === 0)) throw new Error("empty");
344
+ return { text, truncated };
345
+ }
346
+
347
+ /**
348
+ * Union the judged-positive spans; never bridge an unjudged gap. A merged
349
+ * span keeps the max probability. Strongest first, then earliest.
350
+ */
351
+ export function mergeHeat(heat: readonly HeatRange[], threshold: number): HeatRange[] {
352
+ const kept = heat
353
+ .filter((range) => range.p >= threshold && range.p > 0 && range.start <= range.end)
354
+ .sort((a, b) => a.start - b.start || a.end - b.end);
355
+ const merged: HeatRange[] = [];
356
+ for (const range of kept) {
357
+ const last = merged[merged.length - 1];
358
+ if (last && range.start <= last.end + 1) {
359
+ last.end = Math.max(last.end, range.end);
360
+ if (range.p > last.p) last.p = range.p;
361
+ continue;
362
+ }
363
+ merged.push({ ...range });
364
+ }
365
+ return merged.sort((a, b) => b.p - a.p || a.start - b.start);
366
+ }
367
+
368
+ /** The most relevant ranges, strongest first, then earliest. */
369
+ export function rankedHeat(heat: readonly HeatRange[], limit: number): HeatRange[] {
370
+ return heat
371
+ .filter((range) => range.p > 0)
372
+ .sort((a, b) => b.p - a.p || a.start - b.start)
373
+ .slice(0, limit);
374
+ }