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.
- package/CHANGELOG.md +100 -1
- package/extensions/index.ts +5 -1
- package/extensions/lib/env.test.ts +147 -0
- package/extensions/lib/env.ts +180 -0
- package/extensions/lib/order.test.ts +74 -0
- package/extensions/lib/registry.test.ts +8 -5
- package/extensions/lib/registry.ts +23 -4
- package/extensions/modules/a2a/configPanel.ts +42 -1
- package/extensions/modules/a2a/lib/config.ts +8 -3
- package/extensions/modules/a2a/test/configPanel.test.ts +7 -4
- package/extensions/modules/advisor/index.ts +6 -3
- package/extensions/modules/advisor/test/module.test.ts +31 -0
- package/extensions/modules/classifier/index.ts +55 -1
- package/extensions/modules/classifier/test/classifier.test.ts +62 -0
- package/extensions/modules/composer/test/module.test.ts +2 -2
- package/extensions/modules/config/test/renderTools.test.ts +1 -1
- package/extensions/modules/jfind/index.ts +115 -0
- package/extensions/modules/jfind/lib/cascade.ts +377 -0
- package/extensions/modules/jfind/lib/format.ts +12 -0
- package/extensions/modules/jfind/lib/judge.ts +74 -0
- package/extensions/modules/jfind/lib/lexical.ts +232 -0
- package/extensions/modules/jfind/lib/questions.ts +178 -0
- package/extensions/modules/jfind/lib/tree.ts +374 -0
- package/extensions/modules/jfind/test/cascade.test.ts +305 -0
- package/extensions/modules/notify/index.ts +33 -0
- package/extensions/modules/notify/lib/notify.ts +99 -0
- package/extensions/modules/notify/test/notify.test.ts +95 -0
- package/extensions/modules/plan/lib/plan-tools.ts +13 -0
- package/extensions/modules/repair/configPanel.ts +7 -1
- package/extensions/modules/repair/index.ts +158 -3
- package/extensions/modules/repair/lib/auto-generated.ts +89 -0
- package/extensions/modules/repair/lib/read-archive.ts +101 -0
- package/extensions/modules/repair/lib/read-sqlite.ts +185 -0
- package/extensions/modules/repair/lib/settings.ts +4 -1
- package/extensions/modules/repair/test/freshness.test.ts +41 -1
- package/extensions/modules/repair/test/guard-selector.test.ts +67 -0
- package/extensions/modules/repair/test/readers.test.ts +291 -0
- package/extensions/modules/repair/test/settings.test.ts +2 -1
- package/extensions/modules/router/configPanel.ts +4 -4
- package/extensions/modules/router/index.ts +1 -1
- package/extensions/modules/router/lib/config.ts +9 -4
- package/extensions/modules/router/lib/systemone.ts +17 -4
- package/extensions/modules/router/test/unit.test.ts +46 -1
- package/extensions/modules/rules/index.ts +13 -3
- package/extensions/modules/rules/lib/rules.ts +24 -12
- package/extensions/modules/rules/test/lib.test.ts +20 -0
- package/extensions/modules/rules/test/module.test.ts +21 -0
- package/extensions/modules/sg/index.ts +129 -0
- package/extensions/modules/sg/lib/ops.ts +144 -0
- package/extensions/modules/sg/lib/sg-cli.ts +104 -0
- package/extensions/modules/sg/test/sg.test.ts +128 -0
- package/extensions/modules/shells/index.ts +210 -0
- package/extensions/modules/shells/lib/sessions.ts +344 -0
- package/extensions/modules/shells/test/sessions.test.ts +275 -0
- package/extensions/modules/subagent/index.ts +11 -5
- package/extensions/modules/subagent/lib/herdr.ts +5 -0
- package/extensions/modules/subagent/lib/routing.ts +31 -8
- package/extensions/modules/subagent/lib/runner.ts +8 -2
- package/extensions/modules/subagent/test/routing.test.ts +45 -0
- package/extensions/modules/web/configPanel.ts +67 -8
- package/extensions/modules/web/index.ts +34 -0
- package/extensions/modules/web/lib/pdf.ts +181 -0
- package/extensions/modules/web/test/configPanel.test.ts +7 -3
- package/extensions/modules/web/test/extension.test.ts +2 -1
- package/extensions/modules/web/test/settings.test.ts +6 -0
- package/extensions/modules/web/vendor/pdfjs/LICENSE +177 -0
- package/extensions/modules/web/vendor/pdfjs/README.md +16 -0
- package/extensions/modules/web/vendor/pdfjs/pdf.min.mjs +21 -0
- package/extensions/modules/web/vendor/pdfjs/pdf.worker.mjs +21 -0
- package/package.json +3 -3
|
@@ -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
|
+
}
|
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
// The judge adapter: OMP's `Judge` seam implemented over pi's public
|
|
2
|
+
// modelRegistry.classify (the classifier module's askJev pattern: settings
|
|
3
|
+
// override → first available classifier model on the router provider, one
|
|
4
|
+
// cold-start forced refresh). Fails LOUD when no classifier model resolves —
|
|
5
|
+
// the caller surfaces the remediation hint.
|
|
6
|
+
|
|
7
|
+
import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
|
|
8
|
+
import type { Request, JudgmentResult, Judge } from "./questions.js";
|
|
9
|
+
|
|
10
|
+
const COOLDOWN_MS = 60_000;
|
|
11
|
+
let lastForcedRefresh = 0;
|
|
12
|
+
|
|
13
|
+
/** Test hook: clear the cold-start cooldown (module state outlives a test). */
|
|
14
|
+
export function resetJudgeCooldown(): void {
|
|
15
|
+
lastForcedRefresh = 0;
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
interface ClassifyAnswer {
|
|
19
|
+
probability?: number;
|
|
20
|
+
noul?: number;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
/**
|
|
24
|
+
* Resolve the classifier model once per call and return a Judge whose
|
|
25
|
+
* `judge()` routes through modelRegistry.classify. Throws when the registry
|
|
26
|
+
* is missing or no classifier model is configured — jfind's execute turns
|
|
27
|
+
* that into the tool's remediation error.
|
|
28
|
+
*/
|
|
29
|
+
export function createJudge(ctx: ExtensionContext): Judge {
|
|
30
|
+
const registry = ctx?.modelRegistry;
|
|
31
|
+
if (!registry) throw new Error("jfind has no model registry to resolve a judge from");
|
|
32
|
+
|
|
33
|
+
const resolve = async () => {
|
|
34
|
+
const available = await registry.getAvailableOfType("classifier", "router");
|
|
35
|
+
return available[0];
|
|
36
|
+
};
|
|
37
|
+
return {
|
|
38
|
+
label: "classifier/system-one",
|
|
39
|
+
async judge(request: Request, options?: { signal?: AbortSignal }): Promise<JudgmentResult> {
|
|
40
|
+
let model = await resolve();
|
|
41
|
+
if (!model && Date.now() - lastForcedRefresh > COOLDOWN_MS) {
|
|
42
|
+
// Cold start: the router catalog's network pull races session start.
|
|
43
|
+
lastForcedRefresh = Date.now();
|
|
44
|
+
try {
|
|
45
|
+
await registry.refresh({ providers: ["router"], force: true });
|
|
46
|
+
} catch {
|
|
47
|
+
/* offline — the remediation error below still fires */
|
|
48
|
+
}
|
|
49
|
+
model = await resolve();
|
|
50
|
+
}
|
|
51
|
+
if (!model) {
|
|
52
|
+
throw new Error(
|
|
53
|
+
"no classifier model available — configure the router provider (router.baseUrl + /login router) so a System One model is in the catalog, or disable jfind",
|
|
54
|
+
);
|
|
55
|
+
}
|
|
56
|
+
const result = await registry.classify(
|
|
57
|
+
model,
|
|
58
|
+
{ state: request.state as never, questions: request.questions as never },
|
|
59
|
+
{ signal: options?.signal as never },
|
|
60
|
+
);
|
|
61
|
+
if (result.stopReason !== "stop") throw new Error(result.errorMessage ?? `classifier failed (${result.stopReason})`);
|
|
62
|
+
const answers: Record<string, { probability?: number }> = {};
|
|
63
|
+
for (const [key, value] of Object.entries(result.answers ?? {})) {
|
|
64
|
+
const a = value as ClassifyAnswer | undefined;
|
|
65
|
+
const p = a && typeof a === "object" ? a.probability ?? a.noul : undefined;
|
|
66
|
+
answers[key] = { probability: typeof p === "number" && Number.isFinite(p) ? p : undefined };
|
|
67
|
+
}
|
|
68
|
+
return {
|
|
69
|
+
answers,
|
|
70
|
+
usage: result.usage ? { input: result.usage.input, output: result.usage.output } : undefined,
|
|
71
|
+
};
|
|
72
|
+
},
|
|
73
|
+
};
|
|
74
|
+
}
|
|
@@ -0,0 +1,232 @@
|
|
|
1
|
+
// ponytail: ported from oh-my-pi packages/coding-agent/src/tools/jfind
|
|
2
|
+
// {text,keywords,lexical}.ts — byte-budgeted text primitives + query keywords
|
|
3
|
+
// + the lexical prior. The native grep/glob engine (pi-natives) is swapped
|
|
4
|
+
// for a plain recursive walk + one streaming regex scan over file contents.
|
|
5
|
+
|
|
6
|
+
/** Split like Rust `str::lines`: `\n`-separated, trailing `\r` stripped, no phantom last line. */
|
|
7
|
+
export function lines(text: string): string[] {
|
|
8
|
+
if (text.length === 0) return [];
|
|
9
|
+
const out = text.split("\n");
|
|
10
|
+
if (out[out.length - 1] === "") out.pop();
|
|
11
|
+
for (let i = 0; i < out.length; i++) {
|
|
12
|
+
const line = out[i]!;
|
|
13
|
+
if (line.endsWith("\r")) out[i] = line.slice(0, -1);
|
|
14
|
+
}
|
|
15
|
+
return out;
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
/** Longest prefix of `text` that fits in `bytes` UTF-8 bytes without splitting a code point. */
|
|
19
|
+
export function clipBytes(text: string, bytes: number): string {
|
|
20
|
+
if (Buffer.byteLength(text) <= bytes) return text;
|
|
21
|
+
let used = 0;
|
|
22
|
+
let end = 0;
|
|
23
|
+
for (const char of text) {
|
|
24
|
+
const width = Buffer.byteLength(char);
|
|
25
|
+
if (used + width > bytes) break;
|
|
26
|
+
used += width;
|
|
27
|
+
end += char.length;
|
|
28
|
+
}
|
|
29
|
+
return text.slice(0, end);
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/** First `count` code points of `text`. */
|
|
33
|
+
export function takeChars(text: string, count: number): string {
|
|
34
|
+
let end = 0;
|
|
35
|
+
let taken = 0;
|
|
36
|
+
for (const char of text) {
|
|
37
|
+
if (taken === count) break;
|
|
38
|
+
end += char.length;
|
|
39
|
+
taken++;
|
|
40
|
+
}
|
|
41
|
+
return text.slice(0, end);
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/** Non-overlapping occurrences of `needle` in `haystack`; 0 for an empty needle. */
|
|
45
|
+
export function countOccurrences(haystack: string, needle: string): number {
|
|
46
|
+
if (needle.length === 0) return 0;
|
|
47
|
+
let count = 0;
|
|
48
|
+
let from = 0;
|
|
49
|
+
for (;;) {
|
|
50
|
+
const at = haystack.indexOf(needle, from);
|
|
51
|
+
if (at === -1) return count;
|
|
52
|
+
count++;
|
|
53
|
+
from = at + needle.length;
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
// ── query keywords (jfind/keywords.ts) ──────────────────────────────────────
|
|
58
|
+
|
|
59
|
+
const STOPWORDS: Record<string, true> = Object.fromEntries(
|
|
60
|
+
[
|
|
61
|
+
"the", "a", "an", "or", "and", "to", "is", "are", "be", "when", "where", "how", "that", "this",
|
|
62
|
+
"of", "in", "on", "at", "for", "with", "by", "its", "it", "as", "from", "into", "like", "gets",
|
|
63
|
+
"get", "up", "which", "what", "does", "do", "code", "file", "files", "over", "all", "user",
|
|
64
|
+
"using", "then", "than", "there", "their", "they", "them", "you", "your", "we", "our", "has",
|
|
65
|
+
"have", "had", "was", "were", "been", "being", "will", "would", "should", "can", "could", "not",
|
|
66
|
+
"but", "if", "so", "such", "via", "per", "any", "some", "each", "every", "also", "just", "only",
|
|
67
|
+
"more", "most", "other", "out", "off", "about", "after", "before", "between", "through",
|
|
68
|
+
"during", "without", "within", "one", "two", "new", "used", "use", "make", "makes", "made",
|
|
69
|
+
"run", "runs", "way", "thing", "things", "something", "actually", "really", "still", "yet",
|
|
70
|
+
].map((word) => [word, true as const]),
|
|
71
|
+
);
|
|
72
|
+
|
|
73
|
+
/** Cheap stem so a substring match covers inflections: spawned→spawn, compacted→compact. */
|
|
74
|
+
function stem(token: string): string {
|
|
75
|
+
for (const suffix of ["ing", "ed", "es", "s"]) {
|
|
76
|
+
if (token.endsWith(suffix)) {
|
|
77
|
+
const base = token.slice(0, -suffix.length);
|
|
78
|
+
if (base.length >= 4) return base;
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
return token;
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
/** Unicode letter, digit, or underscore — the token alphabet of the query. */
|
|
85
|
+
const TOKEN_RE = /[^\p{L}\p{N}_]+/u;
|
|
86
|
+
const DIGITS_RE = /^[0-9]+$/;
|
|
87
|
+
|
|
88
|
+
/** Keywords for the grep prior: quoted phrases whole, then tokens minus stopwords. */
|
|
89
|
+
export function keywordsFromQuery(query: string): string[] {
|
|
90
|
+
const out: string[] = [];
|
|
91
|
+
let rest = "";
|
|
92
|
+
const chars = Array.from(query);
|
|
93
|
+
for (let i = 0; i < chars.length; i++) {
|
|
94
|
+
const c = chars[i]!;
|
|
95
|
+
if (c !== '"' && c !== "'") {
|
|
96
|
+
rest += c;
|
|
97
|
+
continue;
|
|
98
|
+
}
|
|
99
|
+
let phrase = "";
|
|
100
|
+
let closed = false;
|
|
101
|
+
while (++i < chars.length) {
|
|
102
|
+
if (chars[i] === c) {
|
|
103
|
+
closed = true;
|
|
104
|
+
break;
|
|
105
|
+
}
|
|
106
|
+
phrase += chars[i];
|
|
107
|
+
}
|
|
108
|
+
phrase = phrase.trim().toLowerCase();
|
|
109
|
+
if (closed && Buffer.byteLength(phrase) >= 3) {
|
|
110
|
+
out.push(phrase);
|
|
111
|
+
rest += " ";
|
|
112
|
+
continue;
|
|
113
|
+
}
|
|
114
|
+
rest += `${phrase} `;
|
|
115
|
+
}
|
|
116
|
+
for (const token of rest.split(TOKEN_RE)) {
|
|
117
|
+
const lower = token.toLowerCase();
|
|
118
|
+
if (Buffer.byteLength(lower) < 3 || Object.hasOwn(STOPWORDS, lower) || DIGITS_RE.test(lower)) continue;
|
|
119
|
+
const stemmed = stem(lower);
|
|
120
|
+
if (!out.includes(stemmed)) out.push(stemmed);
|
|
121
|
+
}
|
|
122
|
+
return out;
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
/** {@link keywordsFromQuery} plus the caller's extra keywords, lowercased and deduplicated. */
|
|
126
|
+
export function keywords(query: string, extra: readonly string[]): string[] {
|
|
127
|
+
const out = keywordsFromQuery(query);
|
|
128
|
+
for (const raw of extra) {
|
|
129
|
+
const keyword = raw.trim().toLowerCase();
|
|
130
|
+
if (keyword.length > 0 && !out.includes(keyword)) out.push(keyword);
|
|
131
|
+
}
|
|
132
|
+
return out;
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
// ── lexical prior (jfind/lexical.ts, natives swapped for a JS scan) ─────────
|
|
136
|
+
|
|
137
|
+
export interface GrepIndex {
|
|
138
|
+
/** Lowercased, non-empty keywords; `perFileKw` vectors align with this. */
|
|
139
|
+
keywords: string[];
|
|
140
|
+
/** rel file path → per-keyword occurrence counts over matching lines. */
|
|
141
|
+
perFileKw: Map<string, number[]>;
|
|
142
|
+
/** Files the scan offered for reading, including oversized ones. */
|
|
143
|
+
filesScanned: number;
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
/** Regex-escape a literal keyword for the scan alternation. */
|
|
147
|
+
function escapeRegex(keyword: string): string {
|
|
148
|
+
return keyword.replace(/[\\.+*?()|[\]{}^$#&\-~]/g, "\\$&");
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
export interface GrepIndexOptions {
|
|
152
|
+
signal?: AbortSignal;
|
|
153
|
+
/** Files to scan (the walk's rel → abs map), already eligibility-filtered. */
|
|
154
|
+
files: ReadonlyMap<string, string>;
|
|
155
|
+
/** Bytes read per file for the scan. */
|
|
156
|
+
scanLimitBytes?: number;
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
const SCAN_LIMIT_DEFAULT = 512 * 1024;
|
|
160
|
+
|
|
161
|
+
/**
|
|
162
|
+
* Count keyword occurrences (case-insensitive) per file by scanning each
|
|
163
|
+
* eligible file's first `scanLimitBytes`. ponytail: plain read + regex over
|
|
164
|
+
* matching lines (no native grep) — the cascade's ranking only needs counts,
|
|
165
|
+
* and the walk is already eligibility-bounded. Exported for tests.
|
|
166
|
+
*/
|
|
167
|
+
export async function grepIndex(rootAbs: string, rawKeywords: readonly string[], options: GrepIndexOptions): Promise<GrepIndex> {
|
|
168
|
+
void rootAbs;
|
|
169
|
+
const { readFile } = await import("node:fs/promises");
|
|
170
|
+
const keywordsLower = rawKeywords.map((k) => k.toLowerCase()).filter((k) => k.length > 0);
|
|
171
|
+
const index: GrepIndex = { keywords: keywordsLower, perFileKw: new Map(), filesScanned: 0 };
|
|
172
|
+
if (keywordsLower.length === 0) return index;
|
|
173
|
+
const re = new RegExp(keywordsLower.map(escapeRegex).join("|"), "gi");
|
|
174
|
+
for (const [rel, abs] of options.files) {
|
|
175
|
+
if (options.signal?.aborted) break;
|
|
176
|
+
index.filesScanned++;
|
|
177
|
+
let text: string;
|
|
178
|
+
try {
|
|
179
|
+
const buf = await readFile(abs);
|
|
180
|
+
text = buf.subarray(0, options.scanLimitBytes ?? SCAN_LIMIT_DEFAULT).toString("utf8");
|
|
181
|
+
} catch {
|
|
182
|
+
continue; // unreadable — just unranked
|
|
183
|
+
}
|
|
184
|
+
let counts: number[] | undefined;
|
|
185
|
+
for (const match of text.matchAll(re)) {
|
|
186
|
+
if (!counts) counts = Array.from({ length: keywordsLower.length }, () => 0);
|
|
187
|
+
const line = (match[0] ?? "").toLowerCase();
|
|
188
|
+
for (let k = 0; k < keywordsLower.length; k++) {
|
|
189
|
+
counts[k]! += countOccurrences(line, keywordsLower[k]!);
|
|
190
|
+
}
|
|
191
|
+
}
|
|
192
|
+
if (counts) index.perFileKw.set(rel, counts);
|
|
193
|
+
}
|
|
194
|
+
return index;
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
/**
|
|
198
|
+
* Inverse document frequency per keyword, clamped to `[0.5, 6]`: rarity is
|
|
199
|
+
* capped so a word occurring once in a test fixture cannot beat an
|
|
200
|
+
* implementation that contains several query concepts repeatedly.
|
|
201
|
+
*/
|
|
202
|
+
export function idf(index: GrepIndex): number[] {
|
|
203
|
+
return index.keywords.map((_, k) => {
|
|
204
|
+
let df = 0;
|
|
205
|
+
for (const counts of index.perFileKw.values()) {
|
|
206
|
+
if ((counts[k] ?? 0) > 0) df++;
|
|
207
|
+
}
|
|
208
|
+
const weight = Math.log((index.filesScanned + 1) / (df + 1));
|
|
209
|
+
return Math.min(6, Math.max(0.5, weight));
|
|
210
|
+
});
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
/**
|
|
214
|
+
* Lexical rank of a file: rare query terms count more, log-scaled frequency
|
|
215
|
+
* keeps common words in a giant file from overwhelming a compact
|
|
216
|
+
* implementation with several terms, and a keyword in the path is worth two
|
|
217
|
+
* extra log-units.
|
|
218
|
+
*/
|
|
219
|
+
export function fileScore(
|
|
220
|
+
counts: readonly number[],
|
|
221
|
+
weights: readonly number[],
|
|
222
|
+
rel: string,
|
|
223
|
+
keywordsList: readonly string[],
|
|
224
|
+
): number {
|
|
225
|
+
const lower = rel.toLowerCase();
|
|
226
|
+
let score = 0;
|
|
227
|
+
for (let k = 0; k < keywordsList.length; k++) {
|
|
228
|
+
const inPath = lower.includes(keywordsList[k]!) ? 1 : 0;
|
|
229
|
+
score += weights[k]! * (2 * inPath + Math.log1p(counts[k] ?? 0));
|
|
230
|
+
}
|
|
231
|
+
return score;
|
|
232
|
+
}
|