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
package/CHANGELOG.md CHANGED
@@ -1,5 +1,54 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.13.0 — 2026-10-08
4
+
5
+ - **Tool-parity wave** (8h OMP/industry survey plan): 4 new modules + 4
6
+ read/write upgrades, all live-verified end-to-end (real spawns, real
7
+ classifier round-trips, real osascript):
8
+ - **shells** (new module): one `shell` tool — start/list/output/stdin/kill
9
+ over persistent background processes (dev servers, watchers, long
10
+ builds). Own process group per session (group kill via `kill(-pid)`),
11
+ 256 KB line rings (head+tail + truncation marker), 10 live/5 exited
12
+ caps, `since:"last"` output cursor, killAll on session_shutdown.
13
+ Plan-blocked.
14
+ - **read-sqlite** (repair): the wrapped read opens `db.sqlite` views —
15
+ table list, `:users` schema+rows, `:users:42` rowid, `:users:name=alice`
16
+ key lookup, `:?SELECT…` read-only query. `node:sqlite` READ-ONLY per
17
+ call; db is genuinely un-writable.
18
+ - **read-archive** (repair): `.tar`/`.tgz`/`.zip` member listing +
19
+ content through the read path; exact-then-unique-suffix member match,
20
+ 1 MB cap, binary refusal; `pkg.tgz:src/x.ts:50-80` slices the member.
21
+ - **auto-generated guard** (repair): writes/edits to lockfiles, minified
22
+ bundles, build dirs and snapshots are refused with a regenerate hint
23
+ (bash stays the deliberate override); `repair.autoGenGuard` setting,
24
+ default on, /config row on Tools → Repair.
25
+ - **read_pdf** (web, 13th tool): local PDF text via vendored pdf.js 4.10
26
+ (Apache-2.0, lazy import, workerless) — no external binaries; pages
27
+ grammar `"3"`, `"1-5"`, `"2,4,6-8"`, 10-page cap/call. Plan read-only.
28
+ - **sg** (new module): `ast_grep` (structural search, `$VAR`/`$$$ALL`
29
+ meta-variables, multi-pattern merge+dedupe) + `ast_edit` (pattern →
30
+ rewrite across files; DRY-RUN by default, staleness re-check after
31
+ apply warns on self-matching rewrites). Fail-open on a missing
32
+ ast-grep binary. Pattern-parse failures render a hint on ast-grep 0.4x
33
+ (exit 8 "Cannot parse query") as well as legacy sg. Plan read-only
34
+ search, blocked rewrite.
35
+ - **jfind** (new module): semantic code find — describe a behavior, get
36
+ files + line ranges, strongest first. OMP cascade port (lexical IDF
37
+ prior → filename judging → sketch routing → passage verification); the
38
+ judge routes through the router's System One classifier models. Plan
39
+ read-only.
40
+ - **notify** (new module): one `notify` tool — desktop notification via
41
+ osascript/notify-send, bell fallback, harmless by construction.
42
+ - Wiring: registry entries + per-tool kill-switches + plan-mode tiers, test
43
+ globs, /config tool-section count 16→20, composer disabled-list, AGENTS.md
44
+ sections, `@types/node` ^24 (node:sqlite types).
45
+ - Tests: 2750 (was 2661) — suites for shells sessions, readers, sg ops,
46
+ jfind cascade (fake-judge), notify.
47
+ - Live-verified (2026-10-08 round): shells ring/group-kill/stdin,
48
+ sqlite+archive views + guard refusal through real pi runs, pdf extraction,
49
+ sg dry-run/apply/staleness, jfind cascade vs the real classifier, notify
50
+ osascript delivery; one fix shipped (sg pattern-error detection, above).
51
+
3
52
  ## 0.12.0 — 2026-10-08
4
53
 
5
54
  - **Secrets never land in settings.json** (user policy: URLs fine, credentials
@@ -50,6 +50,10 @@ import { attachmentsConfig } from "../modules/attachments/configPanel.ts";
50
50
  import cronModule from "../modules/cron/index.ts";
51
51
  import { cronConfig } from "../modules/cron/configPanel.ts";
52
52
  import permissionModule from "../modules/permission/index.ts";
53
+ import shellsModule from "../modules/shells/index.ts";
54
+ import sgModule from "../modules/sg/index.ts";
55
+ import jfindModule from "../modules/jfind/index.ts";
56
+ import notifyModule from "../modules/notify/index.ts";
53
57
  import configModule from "../modules/config/index.ts";
54
58
 
55
59
  /** A module's contribution to the central `/config` panel. */
@@ -156,11 +160,14 @@ export const MODULES: ModuleEntry[] = [
156
160
  { name: "fff", category: "Tools", describe: "FFF fuzzy file/content search (ffgrep, fffind) + @-mention completions.", load: fffModule, tools: [
157
161
  "ffgrep", "ffind", "fff_multi_grep", "resolve_file", "related_files",
158
162
  ] },
163
+ // jfind after fff: the semantic sibling of the lexical search pair (its
164
+ // judge resolves through the router's classifier models at execute time).
165
+ { name: "jfind", category: "Tools", describe: "Semantic code find: describe what code does, get files + line ranges (lexical prior + System One judge cascade).", load: jfindModule, tools: ["jfind"] },
159
166
  // Web after fff: same class of append-only before_agent_start guidance
160
167
  // (conditional on web_* tools being active) — no prompt-rewrite contract
161
168
  // beyond fff's shipped precedent.
162
169
  { name: "web", category: "Tools", describe: "Unified web tools: search (SearXNG/Brave/Firecrawl), extract & crawl (JSDOM/Firecrawl/Crawl4AI/agy), screenshot/PDF, CDP browser interaction, Gemini research, image generation, one-off chat.", load: webModule, config: webConfig, tools: [
163
- "web_search", "web_extract", "web_map", "web_crawl", "web_screenshot", "web_pdf", "web_interact", "web_research", "web_image", "web_chat", "web_status", "web_a11y",
170
+ "web_search", "web_extract", "web_map", "web_crawl", "web_screenshot", "web_pdf", "web_interact", "web_research", "web_image", "web_chat", "web_status", "web_a11y", "read_pdf",
164
171
  ] },
165
172
  { name: "rules", category: "Context", describe: "Sticky RULES.md constraints carried in every request + a rulebook of on-demand rules served by rule_get. Nearest-first project walk over user-level.", load: rulesModule, tools: ["rule_get"] },
166
173
  // Attachments: paste/drop files become real attachments. No tools/commands —
@@ -170,6 +177,10 @@ export const MODULES: ModuleEntry[] = [
170
177
  // gh binary (registers nothing until installed). Read-only ops only, so
171
178
  // plan mode auto-allows it (plan-tools.ts READ_ONLY_TOOLS).
172
179
  { name: "gh", category: "Tools", describe: "GitHub tool over the gh CLI: repo/file/PR views, PR diff, five search flavors, Actions run_watch. Read-only; mutating flows stay on bash gh.", load: ghModule, config: ghConfig, tools: ["github"] },
180
+ // sg after gh: the same external-binary fail-open shape, for ast-grep.
181
+ { name: "sg", category: "Tools", describe: "Structural search & rewrite via the ast-grep CLI: ast_grep search, ast_edit dry-run-default rewrites. Registers nothing until ast-grep/sg is installed.", load: sgModule, tools: ["ast_grep", "ast_edit"] },
182
+ // notify: harmless desktop ping (bell fallback), herdr multi-pane ergonomics.
183
+ { name: "notify", category: "Tools", describe: "Desktop notification tool: ping the user when long work settles or input is needed (osascript / notify-send / bell).", load: notifyModule, tools: ["notify"] },
173
184
  // rtk is a PROMPT REWRITER (its before_agent_start appends the RTK note), so
174
185
  // it must load BEFORE steering — during a ds-anchor bootstrap, steering's
175
186
  // minimal prompt replaces everything, including this note (byte-identity);
@@ -190,6 +201,9 @@ export const MODULES: ModuleEntry[] = [
190
201
  // Permission after rtk: persistent allow/ask/deny gating. Inert until rules
191
202
  // exist; defers to plan mode via the shared plan-bridge flag (order-free).
192
203
  { name: "permission", category: "Shell", describe: "Persistent allow/ask/deny permission rules per tool (wildcards, external-directory boundary, doom-loop guard) — opt-in via the `permission` settings section; inert until configured.", load: permissionModule },
204
+ // Background shell sessions (the bash-escape-hatch tool is BLOCKED in plan
205
+ // mode via plan-tools.ts — keep that in sync when renaming).
206
+ { name: "shells", category: "Shell", describe: "Background shell sessions: start/list/output/stdin/kill over persistent processes (dev servers, watchers). Killed on session shutdown; blocked in plan mode.", load: shellsModule, tools: ["shell"] },
193
207
  // ── Plugins ────────────────────────────────────────────────────────────
194
208
  // Config last: it owns /config and reads the contrib map. CORE: the panel is
195
209
  // the only in-app way back from a misconfiguration — it can never be the
@@ -306,8 +306,8 @@ describe("core module contract", () => {
306
306
  it("nextDisabled excludes core modules; withEnableRow adds no row for them", async () => {
307
307
  const { nextDisabled, withEnableRow } = await import("../../config/index.js");
308
308
  // working = enabled set; nextDisabled lists the NOT-enabled non-core modules.
309
- assert.deepEqual(nextDisabled(new Set(["munin"])), ["zai", "ponytail", "subagent", "plan", "a2a", "todo", "cron", "repair", "serena", "fff", "web", "rules", "attachments", "gh", "rtk", "steering", "permission"]);
310
- assert.deepEqual(nextDisabled(new Set(["router", "classifier", "ux", "munin", "usage", "ponytail", "subagent", "plan", "a2a", "todo", "cron", "repair", "serena", "fff", "web", "gh", "rules", "steering", "zai", "rtk", "config", "attachments", "permission"])), [], "all-on → nothing disabled");
309
+ assert.deepEqual(nextDisabled(new Set(["munin"])), ["zai", "ponytail", "subagent", "plan", "a2a", "todo", "cron", "repair", "serena", "fff", "jfind", "web", "rules", "attachments", "gh", "sg", "notify", "rtk", "steering", "permission", "shells"]);
310
+ assert.deepEqual(nextDisabled(new Set(["router", "classifier", "ux", "munin", "usage", "ponytail", "subagent", "plan", "a2a", "todo", "cron", "repair", "serena", "fff", "jfind", "web", "gh", "sg", "notify", "rules", "steering", "zai", "rtk", "config", "attachments", "permission", "shells"])), [], "all-on → nothing disabled");
311
311
  for (const core of ["composer", "advisor", "router", "classifier", "usage", "ux", "config"]) {
312
312
  assert.ok(!nextDisabled(new Set()).includes(core), `core (${core}) is never disableable`);
313
313
  }
@@ -34,7 +34,7 @@ function toolGroups(): PanelGroup[] {
34
34
  describe("render smoke — ported modules' /config sections", () => {
35
35
  it("renders Enable + per-tool rows inside the boxed frame with zero overflow", () => {
36
36
  const groups = toolGroups();
37
- assert.equal(groups.length, 16, "serena + fff + ux + munin + classifier + advisor + subagent + repair + plan + todo + web + rules + a2a + gh + cron + steering·think (rtk has no tools)");
37
+ assert.equal(groups.length, 20, "serena + fff + jfind + ux + munin + classifier + advisor + subagent + repair + plan + todo + web + rules + a2a + gh + sg + notify + cron + shells + steering·think (rtk has no tools)");
38
38
  const m = new ConfigPanelModel(groups, theme, "Settings");
39
39
  m.getHeight = () => 40;
40
40
  for (const w of [110, 100, 80, 60]) {
@@ -0,0 +1,115 @@
1
+ // jfind — semantic code find: describe what code does, get files + line
2
+ // ranges. Ported from OMP's jfind cascade; the judge routes through pi's
3
+ // modelRegistry.classify (System One via the router provider).
4
+
5
+ import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
6
+ import { existsSync, statSync } from "node:fs";
7
+ import { resolve as resolvePath } from "node:path";
8
+ import { Type } from "typebox";
9
+ import { readDisabledTools } from "../../lib/tools.js";
10
+ import { formatBytes } from "./lib/format.js";
11
+ import { runCascade, FIND_TIMEOUT_MS, type CascadeResult } from "./lib/cascade.js";
12
+ import { createJudge } from "./lib/judge.js";
13
+ import { rankedHeat } from "./lib/tree.js";
14
+
15
+ /** Line ranges shown per hit in the model-facing text, strongest first. */
16
+ const RANGES_SHOWN = 3;
17
+
18
+ function formatBytesCeulen(bytes: number): string {
19
+ return formatBytes(bytes);
20
+ }
21
+
22
+ export default function jfindModule(pi: ExtensionAPI): void {
23
+ const disabled = readDisabledTools();
24
+ pi.registerTool({
25
+ name: "jfind",
26
+ label: "Semantic Find",
27
+ defaultActive: !disabled.has("jfind"),
28
+ description:
29
+ "Semantic code find: describe a BEHAVIOR (\"where do we parse CLI flags\", \"retry with backoff around provider calls\") and get the files and line ranges that implement it, strongest first. " +
30
+ "A lexical keyword scan ranks candidates, then a System One judge (the router's classifier models) ranks filenames, passage sketches, and full passages in three waves. " +
31
+ "Use when grep/ffgrep can't phrase the search as a literal pattern; needs a classifier model to be configured (router catalog). Slower than grep (a few seconds of judging).",
32
+ promptSnippet: "Semantic find: locate code by describing what it does",
33
+ promptGuidelines: [
34
+ "Describe the behavior, not the keywords: jfind judges passages semantically.",
35
+ 'Put must-have identifiers in quotes ("spawn", "writeStdin") — quoted phrases become hard lexical keywords.',
36
+ "No hits doesn't mean the code doesn't exist — fall back to ffgrep/fffind for literal patterns.",
37
+ ],
38
+ parameters: Type.Object({
39
+ query: Type.String({ description: 'What the code does, e.g. "parse cron expressions into next-fire times".' }),
40
+ keywords: Type.Optional(Type.Array(Type.String(), { description: "Extra literal keywords folded into the lexical prior." })),
41
+ path: Type.Optional(Type.String({ description: "Search scope: a directory (default the session cwd) or a single file." })),
42
+ }),
43
+ async execute(_toolCallId, params, signal, onUpdate, ctx) {
44
+ const query = (params.query as string).trim();
45
+ if (query.length === 0) throw new Error("`query` must be a non-empty description");
46
+ const cwd = ctx?.cwd || process.cwd();
47
+ const scopeInput = typeof params.path === "string" ? params.path.trim() : "";
48
+ let root = resolvePath(cwd);
49
+ if (scopeInput.length > 0) {
50
+ root = resolvePath(cwd, scopeInput);
51
+ if (!existsSync(root)) throw new Error(`Path not found: ${scopeInput}`);
52
+ if (!statSync(root).isFile() && !statSync(root).isDirectory()) {
53
+ throw new Error(`Path is neither a file nor a directory: ${scopeInput}`);
54
+ }
55
+ }
56
+ let judge;
57
+ try {
58
+ judge = createJudge(ctx);
59
+ } catch (err) {
60
+ return {
61
+ content: [{ type: "text", text: err instanceof Error ? err.message : String(err) }],
62
+ isError: true as const,
63
+ details: { query },
64
+ };
65
+ }
66
+ const timeout = AbortSignal.timeout(FIND_TIMEOUT_MS);
67
+ const combined = signal ? AbortSignal.any([signal, timeout]) : timeout;
68
+ let result: CascadeResult;
69
+ try {
70
+ result = await runCascade({
71
+ root,
72
+ query,
73
+ extraKeywords: (params.keywords as string[] | undefined) ?? [],
74
+ judge,
75
+ signal: combined,
76
+ onProgress: (message) => onUpdate?.({ content: [{ type: "text", text: message }], details: undefined }),
77
+ });
78
+ } catch (err) {
79
+ if (timeout.aborted && !signal?.aborted) {
80
+ throw new Error(`jfind timed out after ${Math.round(FIND_TIMEOUT_MS / 1000)}s — narrow the query or scope (path param)`);
81
+ }
82
+ throw err;
83
+ }
84
+ const { stats, threshold, keywords } = result;
85
+ const scope = scopeInput.length > 0 ? ` in ${scopeInput}` : "";
86
+ const out: string[] = [];
87
+ if (result.hits.length === 0) {
88
+ out.push(`no hits for "${query}"${scope} (τ ${threshold.toFixed(2)})`);
89
+ } else {
90
+ out.push(`${result.hits.length} hit(s) for "${query}"${scope} (τ ${threshold.toFixed(2)}), strongest first`, "");
91
+ for (const hit of result.hits) {
92
+ const coverage = hit.truncated ? `${hit.linesSeen} lines judged, partial` : `${hit.linesSeen} lines judged`;
93
+ out.push(`${hit.rel} ${hit.contentScore.toFixed(2)} ${coverage}`);
94
+ for (const range of rankedHeat(hit.ranges, RANGES_SHOWN)) {
95
+ const span = range.start === range.end ? String(range.start) : `${range.start}-${range.end}`;
96
+ out.push(` ${hit.rel}:${span} ${range.p.toFixed(2)} ${range.snippet}`);
97
+ }
98
+ }
99
+ }
100
+ out.push(
101
+ "",
102
+ `listed ${stats.listed} · judged ${stats.judged} · read ${stats.filesRead} files (${formatBytesCeulen(stats.fileBytes)}) · ${stats.requests} requests · ${stats.inputTokens + stats.outputTokens} tokens · keywords: ${keywords.join(", ")}`,
103
+ );
104
+ if (stats.failures.length > 0) {
105
+ out.push(`${stats.errors} of ${stats.requests} requests failed:`, ...stats.failures.map((f) => ` ${f}`));
106
+ }
107
+ const allFailed = stats.requests > 0 && stats.errors === stats.requests;
108
+ return {
109
+ content: [{ type: "text", text: out.join("\n") }],
110
+ isError: allFailed,
111
+ details: { query, keywords, threshold, hits: result.hits.length, stats },
112
+ };
113
+ },
114
+ });
115
+ }
@@ -0,0 +1,377 @@
1
+ // ponytail: ported from oh-my-pi packages/coding-agent/src/tools/jfind
2
+ // cascade.ts — the four-wave semantic find cascade (lexical scan → filename
3
+ // ranking → sketch routing → passage verification). The InternalUrlFilesystem
4
+ // and pi-natives scan are swapped for plain fs (listFiles/readTextFile in
5
+ // tree.ts + grepIndex in lexical.ts); everything else keeps OMP's shapes,
6
+ // budgets, and constants.
7
+
8
+ import { basename } from "node:path";
9
+ import {
10
+ fileScore,
11
+ grepIndex,
12
+ idf,
13
+ keywords as deriveKeywords,
14
+ type GrepIndex,
15
+ } from "./lexical.js";
16
+ import {
17
+ entryKey,
18
+ passageKey,
19
+ nameBatch,
20
+ passageBatch,
21
+ sketchBatch,
22
+ type Judge,
23
+ type Request,
24
+ type SketchCard,
25
+ } from "./questions.js";
26
+ import {
27
+ listFiles,
28
+ mergeHeat,
29
+ plainContent,
30
+ readTextFile,
31
+ selectWindows,
32
+ sketch,
33
+ windows,
34
+ type FileEntry,
35
+ type HeatRange,
36
+ type Passage,
37
+ } from "./tree.js";
38
+ import { lines, takeChars } from "./lexical.js";
39
+
40
+ /** Requests in flight per dispatched phase. */
41
+ const PARALLEL = 4;
42
+ /** Files per filename-ranking request. */
43
+ const NAME_BATCH = 64;
44
+ /** Lexically ranked files that receive a filename judgment. */
45
+ const CANDIDATES = 128;
46
+ /** Files whose content is read and sketched. */
47
+ const FILES = 20;
48
+ /** Windows kept per read file. */
49
+ const WINDOWS = 24;
50
+ /** Bytes per window, tags included. */
51
+ const WINDOW_BYTES = 8192;
52
+ /** Bytes per sketch card. */
53
+ const SKETCH_BYTES = 384;
54
+ /** Complete passages verified across all files. */
55
+ const FULL_LIMIT = 40;
56
+ /** Sketch probability below which a passage is not verified. */
57
+ const CUTOFF = 0.45;
58
+ /** Verified-passage probability at or above which a file is a hit. */
59
+ const THRESHOLD = 0.2;
60
+ /** Bytes of a file read for windowing. */
61
+ const READ_LIMIT = 4 * 1024 * 1024;
62
+ /** Sketch state budget per request. */
63
+ const SKETCH_STATE_BYTES = 18_000;
64
+ /** Hard cap on sketch cards per request. */
65
+ const SKETCH_CARDS_MAX = 48;
66
+ /** Passage state budget per verification request, tags included. */
67
+ const VERIFY_STATE_BYTES = 24 * 1024;
68
+ /** Distinct failure messages retained for the report. */
69
+ const FAILURES_KEPT = 5;
70
+ /** ponytail: classify round-trips are costlier than OMP's native judge, so
71
+ * the budget tightened from 20s; a stalled judge fails instead of blocking. */
72
+ export const FIND_TIMEOUT_MS = 45_000;
73
+
74
+ export interface FindHit {
75
+ rel: string;
76
+ nameScore?: number;
77
+ contentScore: number;
78
+ ranges: HeatRange[];
79
+ linesSeen: number;
80
+ truncated: boolean;
81
+ }
82
+
83
+ export interface FindStats {
84
+ listed: number;
85
+ requests: number;
86
+ errors: number;
87
+ judged: number;
88
+ filesRead: number;
89
+ fileBytes: number;
90
+ inputTokens: number;
91
+ outputTokens: number;
92
+ windowsJudged: number;
93
+ windowsPruned: number;
94
+ mapCards: number;
95
+ failures: string[];
96
+ }
97
+
98
+ export interface CascadeOptions {
99
+ root: string;
100
+ query: string;
101
+ extraKeywords: readonly string[];
102
+ judge: Judge;
103
+ signal?: AbortSignal;
104
+ onProgress?: (message: string) => void;
105
+ }
106
+
107
+ export interface CascadeResult {
108
+ hits: FindHit[];
109
+ threshold: number;
110
+ keywords: string[];
111
+ stats: FindStats;
112
+ }
113
+
114
+ interface FilePlan {
115
+ node: number;
116
+ total: number;
117
+ truncated: boolean;
118
+ passages: Passage[];
119
+ }
120
+
121
+ type Outcome = { ok: true; result: { answers: Record<string, { probability?: number }>; usage?: { input?: number; output?: number } } } | { ok: false; error: unknown };
122
+
123
+ function noul(outcome: Outcome, key: string): number | undefined {
124
+ if (!outcome.ok) return undefined;
125
+ const p = outcome.result.answers[key]?.probability;
126
+ return p !== undefined && Number.isFinite(p) && p >= 0 && p <= 1 ? p : undefined;
127
+ }
128
+
129
+ function chunks<T>(items: readonly T[], size: number): T[][] {
130
+ const out: T[][] = [];
131
+ for (let start = 0; start < items.length; start += size) out.push(items.slice(start, start + size));
132
+ return out;
133
+ }
134
+
135
+ function compareRel(a: FileEntry, b: FileEntry): number {
136
+ return a.rel < b.rel ? -1 : a.rel > b.rel ? 1 : 0;
137
+ }
138
+
139
+ class Cascade {
140
+ readonly #options: CascadeOptions;
141
+ readonly stats: FindStats = {
142
+ listed: 0,
143
+ requests: 0,
144
+ errors: 0,
145
+ judged: 0,
146
+ filesRead: 0,
147
+ fileBytes: 0,
148
+ inputTokens: 0,
149
+ outputTokens: 0,
150
+ windowsJudged: 0,
151
+ windowsPruned: 0,
152
+ mapCards: 0,
153
+ failures: [],
154
+ };
155
+
156
+ constructor(options: CascadeOptions) {
157
+ this.#options = options;
158
+ }
159
+
160
+ #fail(phase: string, error: unknown): void {
161
+ const message = `${phase}: ${error instanceof Error ? error.message : String(error)}`;
162
+ const { failures } = this.stats;
163
+ if (failures.length < FAILURES_KEPT && !failures.includes(message)) failures.push(message);
164
+ }
165
+
166
+ async #ask(request: Request): Promise<Outcome> {
167
+ const { judge, signal } = this.#options;
168
+ try {
169
+ const result = await judge.judge(request, { signal });
170
+ this.stats.requests++;
171
+ this.stats.inputTokens += result.usage?.input ?? 0;
172
+ this.stats.outputTokens += result.usage?.output ?? 0;
173
+ return { ok: true, result };
174
+ } catch (error) {
175
+ if (this.#options.signal?.aborted) throw error;
176
+ this.stats.requests++;
177
+ this.stats.errors++;
178
+ return { ok: false, error };
179
+ }
180
+ }
181
+
182
+ /** At most PARALLEL requests in flight; drains fully before the next phase. */
183
+ async #dispatch<J extends { request: Request }>(jobs: readonly J[], settle: (job: J, outcome: Outcome) => void): Promise<void> {
184
+ let next = 0;
185
+ const worker = async () => {
186
+ while (next < jobs.length) {
187
+ if (this.#options.signal?.aborted) throw new Error("aborted");
188
+ const job = jobs[next++]!;
189
+ settle(job, await this.#ask(job.request));
190
+ }
191
+ };
192
+ await Promise.all(Array.from({ length: Math.min(PARALLEL, jobs.length) }, worker));
193
+ }
194
+
195
+ async run(): Promise<CascadeResult> {
196
+ const { root, query, judge: _judge, signal, onProgress } = this.#options;
197
+ const keywords = deriveKeywords(query, this.#options.extraKeywords);
198
+
199
+ onProgress?.("lexical scan");
200
+ const entries = listFiles(root);
201
+ const fileMap = new Map(entries.map((e) => [e.rel, e.path]));
202
+ const index: GrepIndex = await grepIndex(root, keywords, { files: fileMap, signal });
203
+ this.stats.listed = entries.length;
204
+ const weights = idf(index);
205
+ const noCounts = Array.from({ length: keywords.length }, () => 0);
206
+ const ranked = entries
207
+ .map((entry, node) => ({
208
+ node,
209
+ lex: fileScore(index.perFileKw.get(entry.rel) ?? noCounts, weights, entry.rel, keywords),
210
+ }))
211
+ .sort((a, b) => b.lex - a.lex || compareRel(entries[a.node]!, entries[b.node]!))
212
+ .slice(0, CANDIDATES);
213
+ const nameScore = Array.from<number | undefined>({ length: entries.length });
214
+
215
+ // Wave 1: filename ranking over the lexical shortlist.
216
+ const project = basename(root);
217
+ const nameJobs = chunks(
218
+ ranked.map((candidate) => candidate.node),
219
+ NAME_BATCH,
220
+ ).map((batch) => ({
221
+ batch,
222
+ request: nameBatch(project, query, batch.map((node) => entries[node]!)),
223
+ }));
224
+ let named = 0;
225
+ onProgress?.(`filename ranking 0/${ranked.length}`);
226
+ await this.#dispatch(nameJobs, (job, outcome) => {
227
+ named += job.batch.length;
228
+ if (!outcome.ok) this.#fail("filenames", outcome.error);
229
+ job.batch.forEach((node, k) => {
230
+ const p = noul(outcome, entryKey(k));
231
+ nameScore[node] = p;
232
+ if (p === undefined) {
233
+ if (outcome.ok) this.stats.errors++;
234
+ } else {
235
+ this.stats.judged++;
236
+ }
237
+ });
238
+ onProgress?.(`filename ranking ${named}/${ranked.length}`);
239
+ });
240
+
241
+ // The two strongest lexical candidates are read regardless of the name
242
+ // judgment; the rest of the budget follows name score, then lexical rank.
243
+ const selected = ranked.slice(0, Math.min(FILES, 2)).map((candidate) => candidate.node);
244
+ ranked.sort((a, b) => (nameScore[b.node] ?? 0) - (nameScore[a.node] ?? 0) || b.lex - a.lex);
245
+ for (const candidate of ranked) {
246
+ if (selected.length >= FILES) break;
247
+ if (!selected.includes(candidate.node)) selected.push(candidate.node);
248
+ }
249
+ onProgress?.(`reading ${selected.length} files`);
250
+ const plans: (FilePlan | undefined)[] = await Promise.all(
251
+ selected.map(async (node): Promise<FilePlan | undefined> => {
252
+ const entry = entries[node]!;
253
+ try {
254
+ const read = readTextFile(entry.path, READ_LIMIT);
255
+ const passages = selectWindows(windows(read.text, WINDOW_BYTES, keywords, weights), WINDOWS);
256
+ if (passages.length === 0) return undefined;
257
+ return { node, total: lines(read.text).length, truncated: read.truncated, passages };
258
+ } catch (error) {
259
+ const msg = error instanceof Error ? error.message : String(error);
260
+ if (msg !== "binary" && msg !== "empty") this.#fail(`read ${entry.rel}`, error);
261
+ return undefined;
262
+ }
263
+ }),
264
+ );
265
+ const files = plans.filter((plan): plan is FilePlan => plan !== undefined);
266
+
267
+ // Wave 2: sketch routing over mixed-file cards.
268
+ const cards: { f: number; p: number }[] = [];
269
+ files.forEach((plan, f) => plan.passages.forEach((_, p) => cards.push({ f, p })));
270
+ const sketchJobs = chunks(
271
+ cards,
272
+ Math.min(SKETCH_CARDS_MAX, Math.max(1, Math.floor(SKETCH_STATE_BYTES / SKETCH_BYTES))),
273
+ ).map((batch) => {
274
+ const sketches: SketchCard[] = batch.map(({ f, p }) => ({
275
+ fileKey: `f${f}`,
276
+ rel: entries[files[f]!.node]!.rel,
277
+ sketch: sketch(files[f]!.passages[p]!, keywords, weights, SKETCH_BYTES),
278
+ }));
279
+ return { batch, request: sketchBatch(query, sketches) };
280
+ });
281
+ this.stats.mapCards += cards.length;
282
+ onProgress?.(`scoring ${cards.length} passage sketches across ${files.length} files`);
283
+ const candidates: { f: number; p: number; score: number }[] = [];
284
+ await this.#dispatch(sketchJobs, (job, outcome) => {
285
+ if (!outcome.ok) this.#fail("sketches", outcome.error);
286
+ job.batch.forEach(({ f, p }, k) => {
287
+ const score = noul(outcome, passageKey(k));
288
+ if (score === undefined && outcome.ok) this.stats.errors++;
289
+ // Failure is unknown, never grounds for a negative judgment.
290
+ candidates.push({ f, p, score: score ?? 1 });
291
+ });
292
+ });
293
+ candidates.sort(
294
+ (a, b) =>
295
+ b.score - a.score ||
296
+ files[b.f]!.passages[b.p]!.score - files[a.f]!.passages[a.p]!.score ||
297
+ compareRel(entries[files[a.f]!.node]!, entries[files[b.f]!.node]!) ||
298
+ files[a.f]!.passages[a.p]!.start - files[b.f]!.passages[b.p]!.start,
299
+ );
300
+ const survivors = candidates.filter((candidate) => candidate.score >= CUTOFF).slice(0, FULL_LIMIT);
301
+ this.stats.windowsPruned += cards.length - survivors.length;
302
+ const chosen = new Map<number, number[]>();
303
+ for (const { f, p } of survivors) {
304
+ const list = chosen.get(f);
305
+ if (list) list.push(p);
306
+ else chosen.set(f, [p]);
307
+ }
308
+
309
+ // Wave 3: verification of complete passages, grouped per file.
310
+ const verifyJobs: { f: number; passages: Passage[]; request: Request }[] = [];
311
+ for (const f of [...chosen.keys()].sort((a, b) => a - b)) {
312
+ const rel = entries[files[f]!.node]!.rel;
313
+ const ps = chosen.get(f)!.sort((a, b) => a - b);
314
+ for (const group of chunks(ps, Math.max(1, Math.floor(VERIFY_STATE_BYTES / WINDOW_BYTES)))) {
315
+ const passages = group.map((p) => files[f]!.passages[p]!);
316
+ verifyJobs.push({ f, passages, request: passageBatch(query, rel, passages) });
317
+ }
318
+ }
319
+ onProgress?.(`verifying ${survivors.length} passages in ${chosen.size} files`);
320
+ const results = new Map<number, { score: number; heat: HeatRange[]; lines: number; bytes: number }>();
321
+ await this.#dispatch(verifyJobs, (job, outcome) => {
322
+ if (!outcome.ok) {
323
+ this.#fail("verification", outcome.error);
324
+ return;
325
+ }
326
+ let entry = results.get(job.f);
327
+ if (!entry) {
328
+ entry = { score: 0, heat: [], lines: 0, bytes: 0 };
329
+ results.set(job.f, entry);
330
+ }
331
+ job.passages.forEach((passage, k) => {
332
+ const score = noul(outcome, passageKey(k));
333
+ if (score === undefined) {
334
+ this.stats.errors++;
335
+ return;
336
+ }
337
+ const text = plainContent(passage);
338
+ entry.score = Math.max(entry.score, score);
339
+ entry.heat.push({
340
+ start: passage.start,
341
+ end: passage.end,
342
+ p: score,
343
+ snippet: takeChars(lines(text).find((line) => line.trim().length > 0) ?? "", 100),
344
+ });
345
+ entry.lines += passage.end - passage.start + 1;
346
+ entry.bytes += Buffer.byteLength(text);
347
+ this.stats.windowsJudged++;
348
+ });
349
+ });
350
+
351
+ const hits: FindHit[] = [];
352
+ for (const [f, entry] of results) {
353
+ const plan = files[f]!;
354
+ this.stats.filesRead++;
355
+ this.stats.fileBytes += entry.bytes;
356
+ if (entry.score < THRESHOLD) continue;
357
+ hits.push({
358
+ rel: entries[plan.node]!.rel,
359
+ nameScore: nameScore[plan.node],
360
+ contentScore: entry.score,
361
+ ranges: mergeHeat(entry.heat, THRESHOLD),
362
+ linesSeen: entry.lines,
363
+ truncated: plan.truncated || entry.lines < plan.total,
364
+ });
365
+ }
366
+ this.stats.filesRead += files.length - results.size;
367
+ hits.sort((a, b) => b.contentScore - a.contentScore);
368
+ return { hits, threshold: THRESHOLD, keywords, stats: this.stats };
369
+ }
370
+ }
371
+
372
+ /** One cascade search. Judge failures degrade coverage and land in
373
+ * `stats.failures` — never thrown. */
374
+ export function runCascade(options: CascadeOptions): Promise<CascadeResult> {
375
+ return new Cascade(options).run();
376
+ }
377
+
@@ -0,0 +1,12 @@
1
+ /** `812 B`, `3.4 KB`, … (OMP formatBytes, trimmed). */
2
+ export function formatBytes(bytes: number): string {
3
+ if (!Number.isFinite(bytes) || bytes <= 0) return "0 B";
4
+ const units = ["B", "KB", "MB", "GB", "TB"];
5
+ let value = bytes;
6
+ let unit = 0;
7
+ while (value >= 1024 && unit < units.length - 1) {
8
+ value /= 1024;
9
+ unit++;
10
+ }
11
+ return unit === 0 ? `${Math.round(value)} B` : `${value.toFixed(1)} ${units[unit]}`;
12
+ }