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.
- package/CHANGELOG.md +49 -0
- package/extensions/lib/registry.ts +15 -1
- 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 +132 -1
- 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/readers.test.ts +291 -0
- package/extensions/modules/repair/test/settings.test.ts +2 -1
- 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/web/index.ts +34 -0
- package/extensions/modules/web/lib/pdf.ts +181 -0
- package/extensions/modules/web/test/extension.test.ts +2 -1
- 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,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
|
+
}
|
|
@@ -0,0 +1,178 @@
|
|
|
1
|
+
// ponytail: ported from oh-my-pi packages/coding-agent/src/tools/jfind
|
|
2
|
+
// questions.ts — the three request shapes (filename batch, sketch batch,
|
|
3
|
+
// passage verification), each one state + one noul question per entry.
|
|
4
|
+
// OMP's prompt.render templates are inlined as template strings; the `Judge`
|
|
5
|
+
// interface is replaced by a minimal local one over modelRegistry.classify.
|
|
6
|
+
|
|
7
|
+
import { plainContent, type Passage, type HeatRange } from "./tree.js";
|
|
8
|
+
import type { FileEntry } from "./tree.js";
|
|
9
|
+
|
|
10
|
+
/** Minimal judge seam — implemented over modelRegistry.classify in
|
|
11
|
+
* judge.ts; tests inject a fake. */
|
|
12
|
+
export interface Judge {
|
|
13
|
+
readonly label: string;
|
|
14
|
+
judge(request: Request, options?: { signal?: AbortSignal }): Promise<JudgmentResult>;
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
/** One noul question (OMP judgment/types.ts shape, trimmed). */
|
|
18
|
+
export interface NoulQuestion {
|
|
19
|
+
type: "noul";
|
|
20
|
+
instructions: string;
|
|
21
|
+
criteria?: { true?: string; false?: string };
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
export interface Request {
|
|
25
|
+
state: Record<string, unknown>;
|
|
26
|
+
questions: Record<string, NoulQuestion>;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
export interface JudgmentResult {
|
|
30
|
+
answers: Record<string, { probability?: number }>;
|
|
31
|
+
usage?: { input?: number; output?: number };
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
const TASK =
|
|
35
|
+
"Semantic grep over a source tree: locate files whose content matches the search description. Entries are judged by name, size, position in the tree, and (for folders) a sample of what they contain.";
|
|
36
|
+
|
|
37
|
+
const TREE_FORMAT =
|
|
38
|
+
"`tree` is a directory listing. Lines starting with # are headers: `# dir/` is a folder; more #s means deeper nesting under the header above; a header may fold several levels (`# a/b/c/`). Every judgeable entry carries a tag like e017 right after the #s: files as `e017 name (size)`. Untagged header lines are only structure.";
|
|
39
|
+
|
|
40
|
+
const FILE_CRITERIA = {
|
|
41
|
+
no: "The file is unrelated by name and location; generated executable implementation can still be relevant.",
|
|
42
|
+
yes: "A file at this path plausibly contains code, text, or data matching the search.",
|
|
43
|
+
};
|
|
44
|
+
|
|
45
|
+
const SKETCH_CRITERIA = {
|
|
46
|
+
no: "Unrelated code; mere mentions, declarations, call sites, tests or configuration without implementation.",
|
|
47
|
+
yes: "Likely substantive implementation, definition or explanation of any part of the requested behavior. A matching helper for one step counts. Excerpts omit most source: favor recall.",
|
|
48
|
+
};
|
|
49
|
+
|
|
50
|
+
const PASSAGE_CRITERIA = {
|
|
51
|
+
no: "This passage only mentions, calls, imports, tests, or configures the subject, or contains unrelated code sharing keywords.",
|
|
52
|
+
yes: "This passage contains an implementation, definition, or substantive explanation of an important part of the search. A helper implementing one requested step counts even when other steps are elsewhere.",
|
|
53
|
+
};
|
|
54
|
+
|
|
55
|
+
/** Question key of the `i`th entry in a filename batch. */
|
|
56
|
+
export function entryKey(i: number): string {
|
|
57
|
+
return `e${String(i).padStart(3, "0")}`;
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/** Question key of the `k`th passage in a sketch or verification batch. */
|
|
61
|
+
export function passageKey(k: number): string {
|
|
62
|
+
return `p${String(k).padStart(2, "0")}`;
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/** Copy of `record` with keys in lexicographic order (wire parity with OMP). */
|
|
66
|
+
function sorted<T>(record: Record<string, T>): Record<string, T> {
|
|
67
|
+
const out: Record<string, T> = {};
|
|
68
|
+
for (const key of Object.keys(record).sort()) out[key] = record[key]!;
|
|
69
|
+
return out;
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
const NAME_INSTRUCTIONS =
|
|
73
|
+
'Is the file tagged {{key}} ("{{name}}") likely to contain what this search is looking for: "{{query}}"? Judge by its name, size, and place in `tree`; apply `criteria.file`.';
|
|
74
|
+
|
|
75
|
+
/** Model-facing listing of `entries` as a prefix-folded directory tree. */
|
|
76
|
+
function renderTree(entries: readonly FileEntry[], tagOf: (index: number) => string): string {
|
|
77
|
+
// ponytail: flat prefix-fold without pi-utils' path-tree builder — group
|
|
78
|
+
// by directory prefix, one # per depth.
|
|
79
|
+
const lines: string[] = [];
|
|
80
|
+
let lastDirs: string[] = [];
|
|
81
|
+
entries.forEach((entry, index) => {
|
|
82
|
+
const parts = entry.rel.split("/");
|
|
83
|
+
const dirs = parts.slice(0, -1);
|
|
84
|
+
let common = 0;
|
|
85
|
+
while (common < dirs.length && common < lastDirs.length && dirs[common] === lastDirs[common]) common++;
|
|
86
|
+
for (let d = common; d < dirs.length; d++) {
|
|
87
|
+
if (lines.length > 0 && d === common) lines.push("");
|
|
88
|
+
lines.push(`${"#".repeat(d + 2)} ${dirs[d]!}/`);
|
|
89
|
+
}
|
|
90
|
+
const name = parts[parts.length - 1]!;
|
|
91
|
+
lines.push(`${"#".repeat(dirs.length + 2)} ${tagOf(index)} ${name} (${humanSize(entry.size)})`);
|
|
92
|
+
lastDirs = dirs;
|
|
93
|
+
});
|
|
94
|
+
return lines.join("\n");
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
const SIZE_UNITS = ["B", "KB", "MB", "GB", "TB"];
|
|
98
|
+
|
|
99
|
+
function humanSize(bytes: number): string {
|
|
100
|
+
let value = bytes;
|
|
101
|
+
let unit = 0;
|
|
102
|
+
while (value >= 1024 && unit < SIZE_UNITS.length - 1) {
|
|
103
|
+
value /= 1024;
|
|
104
|
+
unit++;
|
|
105
|
+
}
|
|
106
|
+
return unit === 0 ? `${bytes} B` : `${value.toFixed(1)} ${SIZE_UNITS[unit]}`;
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
/** One noul per file over a shared tree-rendered listing of the batch. */
|
|
110
|
+
export function nameBatch(project: string, query: string, entries: readonly FileEntry[]): Request {
|
|
111
|
+
const questions: Record<string, NoulQuestion> = {};
|
|
112
|
+
entries.forEach((entry, i) => {
|
|
113
|
+
const key = entryKey(i);
|
|
114
|
+
const name = entry.rel.slice(entry.rel.lastIndexOf("/") + 1);
|
|
115
|
+
questions[key] = {
|
|
116
|
+
type: "noul",
|
|
117
|
+
instructions: NAME_INSTRUCTIONS.replaceAll("{{key}}", key).replaceAll("{{name}}", name).replaceAll("{{query}}", query),
|
|
118
|
+
};
|
|
119
|
+
});
|
|
120
|
+
return {
|
|
121
|
+
state: {
|
|
122
|
+
criteria: { file: FILE_CRITERIA },
|
|
123
|
+
format: TREE_FORMAT,
|
|
124
|
+
project,
|
|
125
|
+
search: query,
|
|
126
|
+
task: TASK,
|
|
127
|
+
tree: renderTree(entries, entryKey),
|
|
128
|
+
},
|
|
129
|
+
questions,
|
|
130
|
+
};
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
/** One sketch card: the file it came from and its budgeted verbatim lines. */
|
|
134
|
+
export interface SketchCard {
|
|
135
|
+
fileKey: string;
|
|
136
|
+
rel: string;
|
|
137
|
+
sketch: string;
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
/** Mixed-file packing of sketch cards. */
|
|
141
|
+
export function sketchBatch(query: string, cards: readonly SketchCard[]): Request {
|
|
142
|
+
const files: Record<string, string> = {};
|
|
143
|
+
const passages: Record<string, [string, string]> = {};
|
|
144
|
+
const questions: Record<string, NoulQuestion> = {};
|
|
145
|
+
cards.forEach((card, k) => {
|
|
146
|
+
const key = passageKey(k);
|
|
147
|
+
files[card.fileKey] = card.rel;
|
|
148
|
+
passages[key] = [card.fileKey, card.sketch];
|
|
149
|
+
questions[key] = {
|
|
150
|
+
type: "noul",
|
|
151
|
+
instructions: `Could passage ${key} implement a requested step of search? Apply criteria.`,
|
|
152
|
+
};
|
|
153
|
+
});
|
|
154
|
+
return {
|
|
155
|
+
state: { criteria: SKETCH_CRITERIA, files: sorted(files), passages, search: query },
|
|
156
|
+
questions,
|
|
157
|
+
};
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
/** Verification of complete passages from one file, judged independently. */
|
|
161
|
+
export function passageBatch(query: string, rel: string, passages: readonly Passage[]): Request {
|
|
162
|
+
const entries: Record<string, string> = {};
|
|
163
|
+
const questions: Record<string, NoulQuestion> = {};
|
|
164
|
+
passages.forEach((passage, k) => {
|
|
165
|
+
const key = passageKey(k);
|
|
166
|
+
entries[key] = plainContent(passage);
|
|
167
|
+
questions[key] = {
|
|
168
|
+
type: "noul",
|
|
169
|
+
instructions: `Does \`passages.${key}\` substantively implement, define, or explain part of "${query}"? Apply \`criteria\`.`,
|
|
170
|
+
};
|
|
171
|
+
});
|
|
172
|
+
return {
|
|
173
|
+
state: { criteria: PASSAGE_CRITERIA, file: rel, passages: entries, search: query },
|
|
174
|
+
questions,
|
|
175
|
+
};
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
export type { HeatRange };
|