ceulen 0.12.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 (39) hide show
  1. package/CHANGELOG.md +49 -0
  2. package/extensions/lib/registry.ts +15 -1
  3. package/extensions/modules/composer/test/module.test.ts +2 -2
  4. package/extensions/modules/config/test/renderTools.test.ts +1 -1
  5. package/extensions/modules/jfind/index.ts +115 -0
  6. package/extensions/modules/jfind/lib/cascade.ts +377 -0
  7. package/extensions/modules/jfind/lib/format.ts +12 -0
  8. package/extensions/modules/jfind/lib/judge.ts +74 -0
  9. package/extensions/modules/jfind/lib/lexical.ts +232 -0
  10. package/extensions/modules/jfind/lib/questions.ts +178 -0
  11. package/extensions/modules/jfind/lib/tree.ts +374 -0
  12. package/extensions/modules/jfind/test/cascade.test.ts +305 -0
  13. package/extensions/modules/notify/index.ts +33 -0
  14. package/extensions/modules/notify/lib/notify.ts +99 -0
  15. package/extensions/modules/notify/test/notify.test.ts +95 -0
  16. package/extensions/modules/plan/lib/plan-tools.ts +13 -0
  17. package/extensions/modules/repair/configPanel.ts +7 -1
  18. package/extensions/modules/repair/index.ts +132 -1
  19. package/extensions/modules/repair/lib/auto-generated.ts +89 -0
  20. package/extensions/modules/repair/lib/read-archive.ts +101 -0
  21. package/extensions/modules/repair/lib/read-sqlite.ts +185 -0
  22. package/extensions/modules/repair/lib/settings.ts +4 -1
  23. package/extensions/modules/repair/test/readers.test.ts +291 -0
  24. package/extensions/modules/repair/test/settings.test.ts +2 -1
  25. package/extensions/modules/sg/index.ts +129 -0
  26. package/extensions/modules/sg/lib/ops.ts +144 -0
  27. package/extensions/modules/sg/lib/sg-cli.ts +104 -0
  28. package/extensions/modules/sg/test/sg.test.ts +128 -0
  29. package/extensions/modules/shells/index.ts +210 -0
  30. package/extensions/modules/shells/lib/sessions.ts +344 -0
  31. package/extensions/modules/shells/test/sessions.test.ts +275 -0
  32. package/extensions/modules/web/index.ts +34 -0
  33. package/extensions/modules/web/lib/pdf.ts +181 -0
  34. package/extensions/modules/web/test/extension.test.ts +2 -1
  35. package/extensions/modules/web/vendor/pdfjs/LICENSE +177 -0
  36. package/extensions/modules/web/vendor/pdfjs/README.md +16 -0
  37. package/extensions/modules/web/vendor/pdfjs/pdf.min.mjs +21 -0
  38. package/extensions/modules/web/vendor/pdfjs/pdf.worker.mjs +21 -0
  39. package/package.json +3 -3
@@ -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
+ }
@@ -0,0 +1,305 @@
1
+ // jfind unit tests — fake judge, fixture tree, cascade end-to-end. No
2
+ // network; the classifier is injected through the Judge seam.
3
+
4
+ import assert from "node:assert/strict";
5
+ import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
6
+ import { tmpdir } from "node:os";
7
+ import path from "node:path";
8
+ import { after, before, describe, it } from "node:test";
9
+ import { clipBytes, countOccurrences, keywords, lines, takeChars } from "../lib/lexical.js";
10
+ import { idf, grepIndex, fileScore } from "../lib/lexical.js";
11
+ import {
12
+ eligibleFile,
13
+ listFiles,
14
+ mergeHeat,
15
+ plainContent,
16
+ rankedHeat,
17
+ selectWindows,
18
+ sketch,
19
+ windows,
20
+ } from "../lib/tree.js";
21
+ import { entryKey, passageKey, nameBatch, sketchBatch, passageBatch, type Judge, type Request } from "../lib/questions.js";
22
+ import { runCascade, type CascadeOptions } from "../lib/cascade.js";
23
+
24
+ const dir = mkdtempSync(path.join(tmpdir(), "ceulen-jfind-"));
25
+ after(() => rmSync(dir, { recursive: true, force: true }));
26
+
27
+ // ── primitives ──────────────────────────────────────────────────────────────
28
+
29
+ describe("text primitives", () => {
30
+ it("lines: no phantom tail, \\r stripped", () => {
31
+ assert.deepEqual(lines("a\nb\r\n"), ["a", "b"]);
32
+ assert.deepEqual(lines(""), []);
33
+ });
34
+ it("clipBytes never splits a code point", () => {
35
+ const s = "aé☃".repeat(10);
36
+ const clipped = clipBytes(s, 5);
37
+ assert.ok(Buffer.byteLength(clipped) <= 5);
38
+ assert.ok(s.startsWith(clipped));
39
+ });
40
+ it("takeChars counts code points", () => {
41
+ assert.equal(takeChars("aé☃x", 2), "aé");
42
+ });
43
+ it("countOccurrences", () => {
44
+ assert.equal(countOccurrences("aXbXc", "X"), 2);
45
+ assert.equal(countOccurrences("abc", ""), 0);
46
+ });
47
+ });
48
+
49
+ describe("keywords", () => {
50
+ it("stopwords dropped, tokens stemmed, quoted phrases whole", () => {
51
+ const kws = keywords('parse "cron expr" into spawn-times', []);
52
+ assert.ok(kws.includes("cron expr"));
53
+ assert.ok(kws.includes("parse"));
54
+ assert.ok(kws.includes("spawn")); // stemmed from spawn-times token split? token is spawn, times
55
+ assert.ok(kws.includes("time")); // stemmed
56
+ assert.ok(!kws.includes("into"));
57
+ });
58
+ it("extra keywords folded, deduped, lowercased", () => {
59
+ const kws = keywords("parse flags", ["Parse", "CLI"]);
60
+ assert.deepEqual(kws.filter((k) => k === "parse").length, 1);
61
+ assert.ok(kws.includes("cli"));
62
+ });
63
+ });
64
+
65
+ // ── lexical prior ───────────────────────────────────────────────────────────
66
+
67
+ describe("lexical prior", () => {
68
+ it("grepIndex counts per file; idf clamps; fileScore boosts path hits", async () => {
69
+ const a = path.join(dir, "scan-a.txt");
70
+ const b = path.join(dir, "scan-b.txt");
71
+ writeFileSync(a, "spawn x\nspawn y\nSPAWN z\nother\n");
72
+ writeFileSync(b, "nothing here\n");
73
+ const files = new Map([
74
+ ["scan-a.txt", a],
75
+ ["scan-b.txt", b],
76
+ ]);
77
+ const index = await grepIndex(dir, ["spawn"], { files });
78
+ assert.equal(index.filesScanned, 2);
79
+ assert.deepEqual(index.perFileKw.get("scan-a.txt"), [3]);
80
+ assert.equal(index.perFileKw.has("scan-b.txt"), false);
81
+ const weights = idf(index);
82
+ assert.equal(weights.length, 1);
83
+ assert.ok(weights[0]! >= 0.5 && weights[0]! <= 6);
84
+ const scoreA = fileScore(index.perFileKw.get("scan-a.txt")!, weights, "scan-a.txt", ["spawn"]);
85
+ const scoreB = fileScore([0], weights, "scan-b.txt", ["spawn"]);
86
+ assert.ok(scoreA > scoreB);
87
+ });
88
+ });
89
+
90
+ // ── tree ────────────────────────────────────────────────────────────────────
91
+
92
+ describe("tree eligibility + walk", () => {
93
+ const proj = path.join(dir, "proj");
94
+ before(() => {
95
+ mkdirSync(path.join(proj, "src"), { recursive: true });
96
+ mkdirSync(path.join(proj, "node_modules"), { recursive: true });
97
+ mkdirSync(path.join(proj, ".git"), { recursive: true });
98
+ writeFileSync(path.join(proj, "src", "impl.ts"), "export const x = 1;\n");
99
+ writeFileSync(path.join(proj, "package-lock.json"), "{}");
100
+ writeFileSync(path.join(proj, "node_modules", "x.js"), "module.exports = 1;\n");
101
+ writeFileSync(path.join(proj, ".git", "config"), "[core]\n");
102
+ writeFileSync(path.join(proj, "secret.key"), "-----BEGIN");
103
+ writeFileSync(path.join(proj, ".env"), "TOP_SECRET=1\n");
104
+ writeFileSync(path.join(proj, ".env.example"), "FOO=\n");
105
+ writeFileSync(path.join(proj, "empty.ts"), "");
106
+ });
107
+
108
+ it("eligibleFile deny-lists build noise, secrets, binaries, empty", () => {
109
+ assert.equal(eligibleFile("src/impl.ts", 10, false), true);
110
+ assert.equal(eligibleFile("package-lock.json", 10, false), false);
111
+ assert.equal(eligibleFile("node_modules/x.js", 10, false), false);
112
+ assert.equal(eligibleFile("secret.key", 10, false), false);
113
+ assert.equal(eligibleFile(".env", 10, false), false);
114
+ assert.equal(eligibleFile(".env.example", 10, false), false); // hidden dotfile: excluded unless includeHidden
115
+ assert.equal(eligibleFile(".env.example", 10, true), true); // template admitted when hidden included
116
+ assert.equal(eligibleFile("empty.ts", 0, false), false);
117
+ assert.equal(eligibleFile("logo.png", 10, false), false);
118
+ assert.equal(eligibleFile(".hidden.ts", 10, false), false);
119
+ assert.equal(eligibleFile(".hidden.ts", 10, true), true);
120
+ });
121
+
122
+ it("listFiles walks the tree, skipping deny dirs; git checkout preferred", () => {
123
+ const files = listFiles(proj);
124
+ const rels = files.map((f) => f.rel);
125
+ assert.ok(rels.includes("src/impl.ts"));
126
+ assert.ok(!rels.includes(".env.example")); // hidden, walk runs includeHidden=false
127
+ assert.ok(!rels.some((r) => r.startsWith("node_modules") || r.startsWith(".git") || r === "package-lock.json" || r === "secret.key" || r === ".env"));
128
+ void proj;
129
+ void mkdirSync; // silence unused import in some tsconfigs
130
+ });
131
+ });
132
+
133
+ // ── passages ────────────────────────────────────────────────────────────────
134
+
135
+ describe("passages", () => {
136
+ const text = Array.from({ length: 30 }, (_, i) => (i === 5 ? "spawn child process" : `line ${i}`)).join("\n");
137
+ it("windows: byte-bounded, 1-based, keyword-scored", () => {
138
+ const ps = windows(text, 256, ["spawn"], [2]);
139
+ assert.ok(ps.length > 1);
140
+ assert.equal(ps[0]!.start, 1);
141
+ const hit = ps.find((p) => p.score > 0);
142
+ assert.ok(hit, "the spawn window scored");
143
+ assert.match(hit!.text, /L6\| spawn child process/);
144
+ });
145
+ it("selectWindows: scores first, even spread on zero scores", () => {
146
+ const ps = windows(text, 256, ["spawn"], [2]);
147
+ const sel = selectWindows(ps, 3);
148
+ assert.ok(sel.length <= 3);
149
+ const all = windows(Array.from({ length: 40 }, (_, i) => `row ${i}`).join("\n"), 128, ["zzz"], [1]);
150
+ const spread = selectWindows(all, 4);
151
+ assert.ok(spread[0]!.start < spread[1]!.start);
152
+ assert.ok(spread.at(-1)!.end >= 39); // reaches the end of the file
153
+ });
154
+ it("plainContent strips the L<n>| tags", () => {
155
+ const p = windows("alpha\nbeta\n", 4096, [], [])[0]!;
156
+ assert.equal(plainContent(p), "alpha\nbeta\n");
157
+ });
158
+ it("sketch: keyword-ranked verbatim lines, budget-bounded", () => {
159
+ const p = windows(text, 8192, ["spawn"], [2])[0]!;
160
+ const s = sketch(p, ["spawn"], [2], 200);
161
+ assert.match(s, /^6: spawn child process/m);
162
+ assert.ok(Buffer.byteLength(s) <= 200 + 180);
163
+ });
164
+ it("mergeHeat unions adjacent positives, keeps max p, drops below threshold", () => {
165
+ const heat = [
166
+ { start: 1, end: 3, p: 0.9, snippet: "a" },
167
+ { start: 4, end: 6, p: 0.5, snippet: "b" },
168
+ { start: 10, end: 12, p: 0.15, snippet: "low" },
169
+ { start: 20, end: 22, p: 0.8, snippet: "c" },
170
+ ];
171
+ const merged = mergeHeat(heat, 0.2);
172
+ assert.equal(merged.length, 2);
173
+ assert.deepEqual([merged[0]!.start, merged[0]!.end], [1, 6]);
174
+ assert.equal(merged[0]!.p, 0.9);
175
+ assert.deepEqual([merged[1]!.start, merged[1]!.end], [20, 22]);
176
+ });
177
+ it("rankedHeat: strongest first, limited", () => {
178
+ const heat = [
179
+ { start: 1, end: 2, p: 0.5, snippet: "a" },
180
+ { start: 5, end: 6, p: 0.9, snippet: "b" },
181
+ ];
182
+ const r = rankedHeat(heat, 1);
183
+ assert.equal(r.length, 1);
184
+ assert.equal(r[0]!.start, 5);
185
+ });
186
+ });
187
+
188
+ // ── questions ───────────────────────────────────────────────────────────────
189
+
190
+ describe("questions", () => {
191
+ it("keys are zero-padded and stable", () => {
192
+ assert.equal(entryKey(0), "e000");
193
+ assert.equal(entryKey(17), "e017");
194
+ assert.equal(passageKey(3), "p03");
195
+ });
196
+ it("nameBatch renders a tree with tags + per-entry noul questions", () => {
197
+ const req = nameBatch("proj", "parse flags", [
198
+ { path: "/x/src/cli.ts", rel: "src/cli.ts", size: 1200 },
199
+ { path: "/x/README.md", rel: "README.md", size: 400 },
200
+ ]);
201
+ assert.match(String(req.state.tree), /# src\//);
202
+ assert.match(String(req.state.tree), /e000 cli\.ts \(1\.2 KB\)/);
203
+ assert.ok(req.questions.e000);
204
+ assert.ok(req.questions.e001);
205
+ assert.match(req.questions.e000!.instructions, /"cli\.ts"/);
206
+ });
207
+ it("sketchBatch + passageBatch carry criteria + query", () => {
208
+ const s = sketchBatch("q", [{ fileKey: "f0", rel: "a.ts", sketch: "1: x" }]);
209
+ assert.deepEqual((s.state.passages as Record<string, unknown>).p00, ["f0", "1: x"]);
210
+ const ps = windows("alpha\nbeta\n", 4096, [], []);
211
+ const v = passageBatch("q", "a.ts", ps);
212
+ assert.match(String((v.state.passages as Record<string, string>).p00!), /alpha/);
213
+ });
214
+ });
215
+
216
+ // ── cascade end-to-end with a scripted judge ────────────────────────────────
217
+
218
+ describe("cascade", () => {
219
+ const proj = path.join(dir, "cascadeproj");
220
+ before(() => {
221
+ mkdirSync(path.join(proj, "src"), { recursive: true });
222
+ writeFileSync(
223
+ path.join(proj, "src", "spawn.ts"),
224
+ [
225
+ "// child spawn helper",
226
+ "export function spawnChild(cmd: string) {",
227
+ ' const child = spawn(cmd, { shell: true });',
228
+ " return child;",
229
+ "}",
230
+ "",
231
+ ].join("\n"),
232
+ );
233
+ writeFileSync(path.join(proj, "src", "unrelated.ts"), "export const unrelated = 1;\n");
234
+ });
235
+
236
+ /** Scripted judge: noul 0.95 for any question whose instructions mention
237
+ * the target file or a passage (sketch/verify waves), 0.05 for the rest. */
238
+ function fakeJudge(positiveRel: string): Judge {
239
+ return {
240
+ label: "fake",
241
+ async judge(request: Request) {
242
+ const answers: Record<string, { probability: number }> = {};
243
+ for (const key of Object.keys(request.questions)) {
244
+ const state = JSON.stringify(request.state);
245
+ const passages = request.state.passages as Record<string, unknown> | undefined;
246
+ const hit = passages
247
+ ? Object.values(passages).some((p) => JSON.stringify(p).includes("spawn"))
248
+ : state.includes(positiveRel);
249
+ answers[key] = { probability: hit || state.includes("spawn") ? 0.95 : 0.05 };
250
+ }
251
+ return { answers, usage: { input: 100, output: 10 } };
252
+ },
253
+ };
254
+ }
255
+
256
+ it("finds the implementing file with heat ranges, strongest first", async () => {
257
+ const judge = fakeJudge("src/spawn.ts");
258
+ const opts: CascadeOptions = {
259
+ root: proj,
260
+ query: "spawn a child process",
261
+ extraKeywords: [],
262
+ judge,
263
+ };
264
+ const result = await runCascade(opts);
265
+ assert.equal(result.threshold, 0.2);
266
+ assert.ok(result.hits.length >= 1, `hits: ${JSON.stringify(result.hits)}, stats: ${JSON.stringify(result.stats)}`);
267
+ const top = result.hits[0]!;
268
+ assert.equal(top.rel, "src/spawn.ts");
269
+ assert.ok(top.contentScore >= 0.2);
270
+ assert.ok(top.ranges.length >= 1);
271
+ assert.ok(top.ranges[0]!.start >= 1);
272
+ assert.match(top.ranges[0]!.snippet, /spawn/);
273
+ assert.ok(result.stats.requests > 0);
274
+ assert.ok(result.stats.judged > 0);
275
+ });
276
+
277
+ it("judge failures degrade to failures[] instead of throwing", async () => {
278
+ const judge: Judge = {
279
+ label: "failing",
280
+ async judge() {
281
+ throw new Error("endpoint down");
282
+ },
283
+ };
284
+ const result = await runCascade({ root: proj, query: "spawn", extraKeywords: [], judge });
285
+ assert.equal(result.hits.length, 0);
286
+ assert.equal(result.stats.errors, result.stats.requests);
287
+ assert.ok(result.stats.failures.length >= 1);
288
+ });
289
+
290
+ it("aborted signal surfaces (does not swallow)", async () => {
291
+ const judge: Judge = {
292
+ label: "aborting",
293
+ async judge(_r, options) {
294
+ options?.signal?.throwIfAborted?.();
295
+ throw new Error("aborted");
296
+ },
297
+ };
298
+ const controller = new AbortController();
299
+ controller.abort();
300
+ await assert.rejects(
301
+ runCascade({ root: proj, query: "spawn", extraKeywords: [], judge, signal: controller.signal }),
302
+ /aborted/,
303
+ );
304
+ });
305
+ });