@seanhogg/builderforce-memory 2026.10.42 → 2026.10.44
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/dist/knowledge/externals.d.ts +9 -0
- package/dist/knowledge/externals.d.ts.map +1 -0
- package/dist/knowledge/externals.js +8 -0
- package/dist/knowledge/externals.js.map +1 -0
- package/dist/knowledge/extractFile.d.ts +15 -0
- package/dist/knowledge/extractFile.d.ts.map +1 -1
- package/dist/knowledge/extractFile.js +40 -17
- package/dist/knowledge/extractFile.js.map +1 -1
- package/dist/knowledge/extractJob.d.ts +64 -0
- package/dist/knowledge/extractJob.d.ts.map +1 -0
- package/dist/knowledge/extractJob.js +47 -0
- package/dist/knowledge/extractJob.js.map +1 -0
- package/dist/knowledge/index.d.ts +11 -1
- package/dist/knowledge/index.d.ts.map +1 -1
- package/dist/knowledge/index.js +7 -1
- package/dist/knowledge/index.js.map +1 -1
- package/dist/knowledge/judge.d.ts +23 -5
- package/dist/knowledge/judge.d.ts.map +1 -1
- package/dist/knowledge/judge.js +14 -76
- package/dist/knowledge/judge.js.map +1 -1
- package/dist/knowledge/judgeCalls.d.ts +52 -0
- package/dist/knowledge/judgeCalls.d.ts.map +1 -0
- package/dist/knowledge/judgeCalls.js +107 -0
- package/dist/knowledge/judgeCalls.js.map +1 -0
- package/dist/knowledge/modelLimiter.d.ts +20 -0
- package/dist/knowledge/modelLimiter.d.ts.map +1 -0
- package/dist/knowledge/modelLimiter.js +63 -0
- package/dist/knowledge/modelLimiter.js.map +1 -0
- package/dist/knowledge/review.d.ts +6 -2
- package/dist/knowledge/review.d.ts.map +1 -1
- package/dist/knowledge/review.js +108 -112
- package/dist/knowledge/review.js.map +1 -1
- package/dist/knowledge/reviewJudge.d.ts +95 -0
- package/dist/knowledge/reviewJudge.d.ts.map +1 -0
- package/dist/knowledge/reviewJudge.js +119 -0
- package/dist/knowledge/reviewJudge.js.map +1 -0
- package/dist/knowledge/reviewModel.d.ts +30 -2
- package/dist/knowledge/reviewModel.d.ts.map +1 -1
- package/dist/knowledge/reviewPrefetch.d.ts +53 -0
- package/dist/knowledge/reviewPrefetch.d.ts.map +1 -0
- package/dist/knowledge/reviewPrefetch.js +65 -0
- package/dist/knowledge/reviewPrefetch.js.map +1 -0
- package/dist/knowledge/reviewRun.d.ts +70 -0
- package/dist/knowledge/reviewRun.d.ts.map +1 -0
- package/dist/knowledge/reviewRun.js +88 -0
- package/dist/knowledge/reviewRun.js.map +1 -0
- package/dist/knowledge/reviewRunModel.d.ts +35 -0
- package/dist/knowledge/reviewRunModel.d.ts.map +1 -0
- package/dist/knowledge/reviewRunModel.js +27 -0
- package/dist/knowledge/reviewRunModel.js.map +1 -0
- package/package.json +3 -3
- package/src/knowledge/externals.test.ts +21 -0
- package/src/knowledge/externals.ts +10 -0
- package/src/knowledge/extractFile.ts +49 -17
- package/src/knowledge/extractJob.ts +91 -0
- package/src/knowledge/index.ts +11 -1
- package/src/knowledge/judge.ts +24 -70
- package/src/knowledge/judgeCalls.ts +136 -0
- package/src/knowledge/modelLimiter.test.ts +68 -0
- package/src/knowledge/modelLimiter.ts +68 -0
- package/src/knowledge/review.failures.test.ts +277 -0
- package/src/knowledge/review.ordered.test.ts +114 -0
- package/src/knowledge/review.ts +102 -100
- package/src/knowledge/reviewJudge.ts +155 -0
- package/src/knowledge/reviewModel.ts +30 -2
- package/src/knowledge/reviewPrefetch.ts +86 -0
- package/src/knowledge/reviewRun.test.ts +96 -0
- package/src/knowledge/reviewRun.ts +137 -0
- package/src/knowledge/reviewRunModel.ts +53 -0
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* knowledge/extractJob.ts — the pure, serializable unit of extraction (PRD 41 A8).
|
|
3
|
+
*
|
|
4
|
+
* An {@link ExtractJob} is plain data (no functions, no store), so it can cross a
|
|
5
|
+
* `worker_threads` boundary: a host's pool posts the job to a worker, the worker calls
|
|
6
|
+
* {@link extractJob} with the packs it loaded itself, and the {@link Extracted} comes back.
|
|
7
|
+
* The in-thread default of `reviewDirectory` runs the very same {@link runExtractor}, so a
|
|
8
|
+
* review with and without `ReviewArgs.extractPool` extracts the same bytes. The extract
|
|
9
|
+
* CACHE (store reads/writes) never crosses the boundary: the review consults it around the pool.
|
|
10
|
+
*/
|
|
11
|
+
|
|
12
|
+
import type { ParsedSection, SourceDocument } from '../ingest/types.js';
|
|
13
|
+
import type { ExtractContext, Extracted, KnowledgePack, KnowledgeParser, NodeRef } from './model.js';
|
|
14
|
+
import { basenameOf, srcRef } from './refs.js';
|
|
15
|
+
import { asPathSource, composePacks, EXTRACTOR_VERSION, resolveRelativePath, type ComposedPacks } from './sources.js';
|
|
16
|
+
|
|
17
|
+
/** Everything the extractor needs for one file, as structured-cloneable data. */
|
|
18
|
+
export interface ExtractJob {
|
|
19
|
+
rootId: string;
|
|
20
|
+
/** Root-relative path. */
|
|
21
|
+
path: string;
|
|
22
|
+
/** Content hash of the file. */
|
|
23
|
+
hash: string;
|
|
24
|
+
/** The document as read (plain data). */
|
|
25
|
+
doc: SourceDocument;
|
|
26
|
+
/** The known entity keys (`mentions`), as entries of the review's map. */
|
|
27
|
+
knownKeys: ReadonlyArray<readonly [string, NodeRef]>;
|
|
28
|
+
/** The file will be judged: return its parsed sections too (the main thread never parses when a pool is supplied). */
|
|
29
|
+
needSections?: boolean;
|
|
30
|
+
/** The extract is already cached and only the sections are wanted: skip extracting. Implies `needSections`. */
|
|
31
|
+
sectionsOnly?: boolean;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/** What a worker returns: the file's extract(s) — `[]` when no pack accepts it — and, if asked, its sections. */
|
|
35
|
+
export interface ExtractJobResult {
|
|
36
|
+
extracted: Extracted[];
|
|
37
|
+
sections?: ParsedSection[];
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/**
|
|
41
|
+
* A host's extraction pool: called for a changed file whose extract is not cached (or, with
|
|
42
|
+
* `sectionsOnly`, whose sections are needed). `signal` is the review's: a stopped review should
|
|
43
|
+
* terminate in-flight worker jobs.
|
|
44
|
+
*/
|
|
45
|
+
export type ExtractPool = (job: ExtractJob, signal?: AbortSignal) => Promise<ExtractJobResult>;
|
|
46
|
+
|
|
47
|
+
/** The ONE extraction of an already-resolved source: stamps {@link EXTRACTOR_VERSION}. */
|
|
48
|
+
export function runExtractor(
|
|
49
|
+
hit: { parser: KnowledgeParser; pack: KnowledgePack },
|
|
50
|
+
src: SourceDocument,
|
|
51
|
+
sections: ParsedSection[],
|
|
52
|
+
ctx: ExtractContext,
|
|
53
|
+
file: { path: string; hash: string },
|
|
54
|
+
): Extracted {
|
|
55
|
+
const ref = srcRef(ctx.rootId, file.path);
|
|
56
|
+
return hit.parser.extract
|
|
57
|
+
? { ...hit.parser.extract(src, sections, ctx), sourceHash: file.hash, extractorVersion: EXTRACTOR_VERSION }
|
|
58
|
+
: {
|
|
59
|
+
sourceRef: ref, sourceHash: file.hash, extractorVersion: EXTRACTOR_VERSION, edges: [], keys: [{ ref, key: file.path }],
|
|
60
|
+
nodes: [{ ref, kind: 'file', label: basenameOf(file.path), pack: hit.pack.id, importance: 0, origin: 'extracted', sourceHash: file.hash }],
|
|
61
|
+
};
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/** The job as a serializable value for `doc` (what a pool receives). */
|
|
65
|
+
export function jobOf(
|
|
66
|
+
f: {
|
|
67
|
+
rootId: string; path: string; hash: string; doc: SourceDocument; knownKeys: ReadonlyMap<string, NodeRef>;
|
|
68
|
+
needSections?: boolean; sectionsOnly?: boolean;
|
|
69
|
+
},
|
|
70
|
+
): ExtractJob {
|
|
71
|
+
return {
|
|
72
|
+
rootId: f.rootId, path: f.path, hash: f.hash, doc: f.doc, knownKeys: [...f.knownKeys],
|
|
73
|
+
...(f.needSections ? { needSections: true } : {}), ...(f.sectionsOnly ? { sectionsOnly: true } : {}),
|
|
74
|
+
};
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
/**
|
|
78
|
+
* Extracts one file from a job — pure: no store, no clock. `extracted` is `[]` when no pack's parser
|
|
79
|
+
* accepts the file. `packs` is the worker's own pack list (or its composition, to compose once).
|
|
80
|
+
*/
|
|
81
|
+
export function extractJob(job: ExtractJob, packs: readonly KnowledgePack[] | ComposedPacks): ExtractJobResult {
|
|
82
|
+
const composed = Array.isArray(packs) ? composePacks(packs as readonly KnowledgePack[]) : (packs as ComposedPacks);
|
|
83
|
+
const src = asPathSource(job.doc, job.path, job.hash);
|
|
84
|
+
const hit = composed.resolve(src);
|
|
85
|
+
if (!hit) return { extracted: [] };
|
|
86
|
+
const sections = hit.parser.parse(src);
|
|
87
|
+
const wantSections = job.needSections || job.sectionsOnly;
|
|
88
|
+
if (job.sectionsOnly) return { extracted: [], sections };
|
|
89
|
+
const ctx: ExtractContext = { rootId: job.rootId, knownKeys: new Map(job.knownKeys), resolvePath: resolveRelativePath };
|
|
90
|
+
return { extracted: [runExtractor(hit, src, sections, ctx, job)], ...(wantSections ? { sections } : {}) };
|
|
91
|
+
}
|
package/src/knowledge/index.ts
CHANGED
|
@@ -16,6 +16,7 @@ export type {
|
|
|
16
16
|
export {
|
|
17
17
|
buildOutline, outlineOf, outlineRef, OUTLINE_MAX_FILES, OUTLINE_MAX_LINKS, OUTLINE_BADGE_KEYS, OUTLINE_VERDICTS, OUTLINE_FLAG_CYCLE,
|
|
18
18
|
} from './outline.js';
|
|
19
|
+
export { EXTERNAL_SERVICE_IDS, type ExternalServiceId } from './externals.js';
|
|
19
20
|
|
|
20
21
|
export { buildGraph, graphDigest, oneLineLabel, DEFAULT_MAX_NODES, MAX_NODES_CAP } from './build.js';
|
|
21
22
|
export { truncateGraph, TRUNCATION_HARD_CAP, UNANCHORED_AREA } from './truncate.js';
|
|
@@ -42,9 +43,18 @@ export type { ExtractorState } from './owedFiles.js';
|
|
|
42
43
|
export { reviewDirectory, assertStoredBatch } from './review.js';
|
|
43
44
|
export { extractFile, extractFileDetailed, knownKeysOfEntities } from './extractFile.js';
|
|
44
45
|
export type { ExtractFileArgs, FileExtraction } from './extractFile.js';
|
|
46
|
+
export { extractJob, jobOf } from './extractJob.js';
|
|
47
|
+
export type { ExtractJob, ExtractJobResult, ExtractPool } from './extractJob.js';
|
|
48
|
+
export { putExtract } from './extractFile.js';
|
|
49
|
+
export { createModelLimiter, isRateLimit } from './modelLimiter.js';
|
|
50
|
+
export type { ModelLimiter } from './modelLimiter.js';
|
|
51
|
+
export { reasonOf } from './reviewRunModel.js';
|
|
52
|
+
export type { ReviewFailure, ReviewPhase, ReviewStep, ReviewStepOutcome } from './reviewRunModel.js';
|
|
53
|
+
export { startRun, applyRunEvent, runRate, runEta, REVIEW_RUN_STEP_RING } from './reviewRun.js';
|
|
54
|
+
export type { ReviewRun, ReviewRunEvent, ReviewRunKind, ReviewRunLane, ReviewRunOutcome, ReviewRunPhase } from './reviewRun.js';
|
|
45
55
|
export {
|
|
46
56
|
validateExtract, validateCompare, clampQuote, clampClaim, MAX_QUOTE_LINES, MAX_QUOTE_CHARS, MAX_CLAIM_TEXT_CHARS,
|
|
47
|
-
DEFAULT_REVIEW_MODEL_CALLS, REVIEW_FACT_SOURCE,
|
|
57
|
+
DEFAULT_REVIEW_MODEL_CALLS, DEFAULT_REVIEW_JUDGE_CONCURRENCY, REVIEW_FACT_SOURCE,
|
|
48
58
|
} from './judge.js';
|
|
49
59
|
export {
|
|
50
60
|
composePacks, ignoreMatcher, ignoreSourcesOf, isBinaryPath, isBinaryText, isDocumentPath, mediaTypeOfPath,
|
package/src/knowledge/judge.ts
CHANGED
|
@@ -11,17 +11,19 @@
|
|
|
11
11
|
* (calls and a deadline) is shared across the whole review.
|
|
12
12
|
*/
|
|
13
13
|
|
|
14
|
-
import { hashText } from '../ingest/hash.js';
|
|
15
14
|
import type {
|
|
16
15
|
JudgedClaim, JudgedEntity, JudgementPort, JudgementResult, NodeRef, StoredFact, StoredRelation,
|
|
17
16
|
} from './model.js';
|
|
18
17
|
import type { SimilarPair } from '../retrieval/knowledge-index/types.js';
|
|
19
|
-
import {
|
|
20
|
-
import {
|
|
18
|
+
import type { ModelLimiter } from './modelLimiter.js';
|
|
19
|
+
import { normalizeKey } from './resolve.js';
|
|
20
|
+
import { compareStr } from './refs.js';
|
|
21
21
|
|
|
22
22
|
export const DEFAULT_REVIEW_MODEL_CALLS = 200;
|
|
23
23
|
/** How many changed files a review reads + extracts ahead of its (sequential) judge/write stage. */
|
|
24
24
|
export const DEFAULT_REVIEW_CONCURRENCY = 8;
|
|
25
|
+
/** How many files a review judges at once (writes stay in plan order; PRD 41 A8). */
|
|
26
|
+
export const DEFAULT_REVIEW_JUDGE_CONCURRENCY = 4;
|
|
25
27
|
export const REVIEW_FACT_SOURCE = 'knowledge-review';
|
|
26
28
|
const MAX_TERM = 200;
|
|
27
29
|
const MAX_NAME = 120;
|
|
@@ -101,7 +103,7 @@ export const JUDGE_CONCURRENCY = 6;
|
|
|
101
103
|
* the pool immediately — in-flight calls keep running but no new work is scheduled, matching the
|
|
102
104
|
* serial loops' "stop at the first throw" behaviour.
|
|
103
105
|
*/
|
|
104
|
-
async function runPool<T>(items: readonly T[], concurrency: number, worker: (item: T) => Promise<void>): Promise<void> {
|
|
106
|
+
export async function runPool<T>(items: readonly T[], concurrency: number, worker: (item: T) => Promise<void>): Promise<void> {
|
|
105
107
|
let next = 0;
|
|
106
108
|
let error: Error | null = null;
|
|
107
109
|
const lanes = Array.from({ length: Math.max(1, Math.min(concurrency, items.length)) }, async () => {
|
|
@@ -194,17 +196,32 @@ export function validateCompare(result: unknown, a: NodeRef, b: NodeRef): { rela
|
|
|
194
196
|
return { confidence: 0, invalid: Math.max(invalid, 1) };
|
|
195
197
|
}
|
|
196
198
|
|
|
197
|
-
/**
|
|
198
|
-
|
|
199
|
+
/** What a host of many concurrent calls adds to {@link call}: a shared in-flight cap and a look at each failure. */
|
|
200
|
+
export interface CallHooks {
|
|
201
|
+
limiter?: ModelLimiter;
|
|
202
|
+
onError?(err: unknown): void;
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
/**
|
|
206
|
+
* One model call; `undefined` when the port throws (an abort is re-thrown) — the item was NOT judged.
|
|
207
|
+
* `used` is counted before any wait for the limiter, so the budget cannot be overshot by queued calls.
|
|
208
|
+
*/
|
|
209
|
+
export async function call(
|
|
210
|
+
port: JudgementPort, req: Parameters<JudgementPort['judge']>[0], b: JudgeBudget, hooks: CallHooks = {},
|
|
211
|
+
): Promise<{ result: unknown } | undefined> {
|
|
199
212
|
b.used += 1;
|
|
200
213
|
try {
|
|
201
|
-
|
|
214
|
+
const run = () => port.judge(req);
|
|
215
|
+
return { result: await (hooks.limiter ? hooks.limiter.run(run, req.signal) : run()) };
|
|
202
216
|
} catch (err) {
|
|
203
217
|
if (req.signal?.aborted) throw err;
|
|
218
|
+
hooks.onError?.(err);
|
|
204
219
|
return undefined;
|
|
205
220
|
}
|
|
206
221
|
}
|
|
207
222
|
|
|
223
|
+
export { judgeSections } from './judgeCalls.js';
|
|
224
|
+
|
|
208
225
|
export interface SectionToJudge { ref: NodeRef; text: string }
|
|
209
226
|
|
|
210
227
|
export interface ExtractArgs {
|
|
@@ -222,69 +239,6 @@ export interface ExtractArgs {
|
|
|
222
239
|
onJudged(ref: NodeRef): void;
|
|
223
240
|
}
|
|
224
241
|
|
|
225
|
-
/** Judges each section within the budget; the rest — and any whose call failed — are counted `unjudged`. */
|
|
226
|
-
export async function judgeSections(a: ExtractArgs): Promise<Array<{ ref: NodeRef; text: string }>> {
|
|
227
|
-
const claims: Array<{ ref: NodeRef; text: string }> = [];
|
|
228
|
-
const anchor = { path: a.path, contentHash: a.fileHash };
|
|
229
|
-
// Judged in a bounded pool: the budget check and `call`'s synchronous `used` increment happen
|
|
230
|
-
// on the same tick (no await between), so concurrency cannot overshoot `modelCalls`; the
|
|
231
|
-
// batch/entities/onJudged mutations below are synchronous, hence race-free across workers.
|
|
232
|
-
// The claims array's order may differ from serial execution — its consumer is order-insensitive.
|
|
233
|
-
const abortError = () => a.signal?.reason ?? new Error('aborted');
|
|
234
|
-
await runPool(a.sections, JUDGE_CONCURRENCY, async (section) => {
|
|
235
|
-
// Honoured per section, not only when the port throws: the caller drops this file whole.
|
|
236
|
-
if (a.signal?.aborted) throw abortError();
|
|
237
|
-
if (!budgetLeft(a.budget)) { a.batch.unjudged += 1; return; }
|
|
238
|
-
const answer = await call(a.port, {
|
|
239
|
-
kind: 'extract', items: [{ ref: section.ref, text: section.text, sourceHash: a.fileHash }],
|
|
240
|
-
...(a.signal ? { signal: a.signal } : {}),
|
|
241
|
-
}, a.budget);
|
|
242
|
-
// A failed call judged nothing: not counted judged, so the file stays changed and is retried.
|
|
243
|
-
if (!answer) { a.batch.unjudged += 1; return; }
|
|
244
|
-
// The abort can land while a call is in flight (the port sees the signal): a section that
|
|
245
|
-
// finished after the abort must not count as judged, or the caller would not re-judge it.
|
|
246
|
-
if (a.signal?.aborted) throw abortError();
|
|
247
|
-
const v = validateExtract(answer.result, section.ref);
|
|
248
|
-
a.batch.invalid += v.invalid;
|
|
249
|
-
a.batch.judged += 1;
|
|
250
|
-
a.onJudged(section.ref);
|
|
251
|
-
const rel = (from: NodeRef, to: NodeRef, kind: string) =>
|
|
252
|
-
a.batch.relation({ from, to, kind, weight: 1, origin: 'model', sourceHash: a.fileHash });
|
|
253
|
-
|
|
254
|
-
const entityRefs = new Map<string, NodeRef>();
|
|
255
|
-
for (const e of v.entities) {
|
|
256
|
-
const key = entityKey(a.pack, e.name);
|
|
257
|
-
const prior = a.entities.get(key);
|
|
258
|
-
const anchors = [...(prior?.fileAnchors ?? []).filter((x) => x.path !== a.path), anchor]
|
|
259
|
-
.sort((x, y) => compareStr(x.path, y.path));
|
|
260
|
-
const fact: StoredFact = {
|
|
261
|
-
key, content: prior?.content ?? `${e.name} (${e.type})`, source: REVIEW_FACT_SOURCE,
|
|
262
|
-
importance: prior?.importance ?? 0.5, origin: prior?.origin ?? 'model', fileAnchors: anchors,
|
|
263
|
-
};
|
|
264
|
-
a.entities.set(key, fact);
|
|
265
|
-
a.batch.fact(fact);
|
|
266
|
-
entityRefs.set(normalizeKey(e.name), key);
|
|
267
|
-
rel(section.ref, key, 'mentions');
|
|
268
|
-
}
|
|
269
|
-
for (const c of v.claims) {
|
|
270
|
-
const key = `claim:${hashText([section.ref, c.subject, c.predicate, c.object].join('\u0000'))}`;
|
|
271
|
-
const text = `${c.subject} ${c.predicate} ${c.object}`;
|
|
272
|
-
a.batch.fact({
|
|
273
|
-
key, content: claimContent(text, c.quote), source: REVIEW_FACT_SOURCE,
|
|
274
|
-
importance: 0.5, origin: 'model', fileAnchors: [anchor],
|
|
275
|
-
});
|
|
276
|
-
const ref = factRef(key);
|
|
277
|
-
rel(ref, section.ref, 'about');
|
|
278
|
-
for (const term of [c.subject, c.object]) {
|
|
279
|
-
const ent = entityRefs.get(normalizeKey(term));
|
|
280
|
-
if (ent) rel(ref, ent, 'mentions');
|
|
281
|
-
}
|
|
282
|
-
claims.push({ ref, text });
|
|
283
|
-
}
|
|
284
|
-
});
|
|
285
|
-
return claims;
|
|
286
|
-
}
|
|
287
|
-
|
|
288
242
|
export interface CompareArgs {
|
|
289
243
|
port: JudgementPort;
|
|
290
244
|
pairs: readonly SimilarPair[];
|
|
@@ -0,0 +1,136 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* knowledge/judgeCalls.ts — judging one file's sections, in two stages (PRD 41 A8).
|
|
3
|
+
*
|
|
4
|
+
* • {@link callSections} — the CALL stage: one model call per section within a budget slice, touching
|
|
5
|
+
* no shared state, so several files can be in it at once (optionally under ONE shared
|
|
6
|
+
* {@link ModelLimiter}).
|
|
7
|
+
* • {@link applyAnswers} — the APPLY stage: merges answers into the batch and the shared entity map.
|
|
8
|
+
* Synchronous; the review's one ordered writer calls it in plan order, which keeps the stored
|
|
9
|
+
* bytes independent of how many files were judged at once.
|
|
10
|
+
*
|
|
11
|
+
* {@link judgeSections} is both stages for one file.
|
|
12
|
+
*/
|
|
13
|
+
|
|
14
|
+
import { hashText } from '../ingest/hash.js';
|
|
15
|
+
import {
|
|
16
|
+
budgetLeft, call, claimContent, JUDGE_CONCURRENCY, REVIEW_FACT_SOURCE, runPool, validateExtract,
|
|
17
|
+
type ExtractArgs, type JudgeBudget, type SectionToJudge,
|
|
18
|
+
} from './judge.js';
|
|
19
|
+
import type { ModelLimiter } from './modelLimiter.js';
|
|
20
|
+
import type { JudgementPort, NodeRef, StoredFact } from './model.js';
|
|
21
|
+
import { compareStr, factRef } from './refs.js';
|
|
22
|
+
import { entityKey, normalizeKey } from './resolve.js';
|
|
23
|
+
import { reasonOf } from './reviewRunModel.js';
|
|
24
|
+
|
|
25
|
+
/** A section's validated answer: the output of the call stage, applied later by {@link applyAnswers}. */
|
|
26
|
+
export interface SectionAnswer { section: SectionToJudge; v: ReturnType<typeof validateExtract> }
|
|
27
|
+
|
|
28
|
+
export interface CallSectionsArgs {
|
|
29
|
+
port: JudgementPort;
|
|
30
|
+
fileHash: string;
|
|
31
|
+
sections: readonly SectionToJudge[];
|
|
32
|
+
/** This file's slice of the review budget (its own `used`). */
|
|
33
|
+
budget: JudgeBudget;
|
|
34
|
+
/** Shared across the files of a review: caps the calls in flight and adapts to rate limits. */
|
|
35
|
+
limiter?: ModelLimiter;
|
|
36
|
+
signal?: AbortSignal;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
export interface CallSectionsResult {
|
|
40
|
+
answers: SectionAnswer[];
|
|
41
|
+
/** Sections cut by the budget or whose call failed. */
|
|
42
|
+
unjudged: number;
|
|
43
|
+
/** Calls the port (or the provider behind it) failed. */
|
|
44
|
+
errors: number;
|
|
45
|
+
/** The first failure's message, single line. */
|
|
46
|
+
firstError?: string;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
/** Answers come back in section order. Throws on abort. */
|
|
51
|
+
export async function callSections(a: CallSectionsArgs): Promise<CallSectionsResult> {
|
|
52
|
+
const slots: Array<SectionAnswer | undefined> = new Array(a.sections.length);
|
|
53
|
+
let unjudged = 0;
|
|
54
|
+
let errors = 0;
|
|
55
|
+
let firstError: string | undefined;
|
|
56
|
+
const hooks = {
|
|
57
|
+
...(a.limiter ? { limiter: a.limiter } : {}),
|
|
58
|
+
onError: (err: unknown) => { errors += 1; firstError ??= reasonOf(err); },
|
|
59
|
+
};
|
|
60
|
+
// The budget check and `call`'s synchronous `used` increment happen on the same tick (no await
|
|
61
|
+
// between), so concurrency cannot overshoot `modelCalls`.
|
|
62
|
+
const abortError = () => a.signal?.reason ?? new Error('aborted');
|
|
63
|
+
await runPool(a.sections.map((section, idx) => ({ section, idx })), JUDGE_CONCURRENCY, async ({ section, idx }) => {
|
|
64
|
+
// Honoured per section, not only when the port throws: the caller drops this file whole.
|
|
65
|
+
if (a.signal?.aborted) throw abortError();
|
|
66
|
+
if (!budgetLeft(a.budget)) { unjudged += 1; return; }
|
|
67
|
+
const answer = await call(a.port, {
|
|
68
|
+
kind: 'extract', items: [{ ref: section.ref, text: section.text, sourceHash: a.fileHash }],
|
|
69
|
+
...(a.signal ? { signal: a.signal } : {}),
|
|
70
|
+
}, a.budget, hooks);
|
|
71
|
+
// A failed call judged nothing: not counted judged, so the file stays changed and is retried.
|
|
72
|
+
if (!answer) { unjudged += 1; return; }
|
|
73
|
+
// The abort can land while a call is in flight (the port sees the signal): a section that
|
|
74
|
+
// finished after the abort must not count as judged, or the caller would not re-judge it.
|
|
75
|
+
if (a.signal?.aborted) throw abortError();
|
|
76
|
+
slots[idx] = { section, v: validateExtract(answer.result, section.ref) };
|
|
77
|
+
});
|
|
78
|
+
return { answers: slots.filter((s): s is SectionAnswer => !!s), unjudged, errors, ...(firstError !== undefined ? { firstError } : {}) };
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
/** Judges each section within the budget; the rest — and any whose call failed — are counted `unjudged`. */
|
|
82
|
+
export async function judgeSections(a: ExtractArgs): Promise<Array<{ ref: NodeRef; text: string }>> {
|
|
83
|
+
const { answers, unjudged } = await callSections({
|
|
84
|
+
port: a.port, fileHash: a.fileHash, sections: a.sections, budget: a.budget, ...(a.signal ? { signal: a.signal } : {}),
|
|
85
|
+
});
|
|
86
|
+
a.batch.unjudged += unjudged;
|
|
87
|
+
return applyAnswers(a, answers);
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
/** Merges answers into the batch and the shared entities map, in the order given. */
|
|
91
|
+
export function applyAnswers(
|
|
92
|
+
a: Pick<ExtractArgs, 'pack' | 'path' | 'fileHash' | 'batch' | 'entities' | 'onJudged'>,
|
|
93
|
+
answers: readonly SectionAnswer[],
|
|
94
|
+
): Array<{ ref: NodeRef; text: string }> {
|
|
95
|
+
const claims: Array<{ ref: NodeRef; text: string }> = [];
|
|
96
|
+
const anchor = { path: a.path, contentHash: a.fileHash };
|
|
97
|
+
for (const { section, v } of answers) {
|
|
98
|
+
a.batch.invalid += v.invalid;
|
|
99
|
+
a.batch.judged += 1;
|
|
100
|
+
a.onJudged(section.ref);
|
|
101
|
+
const rel = (from: NodeRef, to: NodeRef, kind: string) =>
|
|
102
|
+
a.batch.relation({ from, to, kind, weight: 1, origin: 'model', sourceHash: a.fileHash });
|
|
103
|
+
|
|
104
|
+
const entityRefs = new Map<string, NodeRef>();
|
|
105
|
+
for (const e of v.entities) {
|
|
106
|
+
const key = entityKey(a.pack, e.name);
|
|
107
|
+
const prior = a.entities.get(key);
|
|
108
|
+
const anchors = [...(prior?.fileAnchors ?? []).filter((x) => x.path !== a.path), anchor]
|
|
109
|
+
.sort((x, y) => compareStr(x.path, y.path));
|
|
110
|
+
const fact: StoredFact = {
|
|
111
|
+
key, content: prior?.content ?? `${e.name} (${e.type})`, source: REVIEW_FACT_SOURCE,
|
|
112
|
+
importance: prior?.importance ?? 0.5, origin: prior?.origin ?? 'model', fileAnchors: anchors,
|
|
113
|
+
};
|
|
114
|
+
a.entities.set(key, fact);
|
|
115
|
+
a.batch.fact(fact);
|
|
116
|
+
entityRefs.set(normalizeKey(e.name), key);
|
|
117
|
+
rel(section.ref, key, 'mentions');
|
|
118
|
+
}
|
|
119
|
+
for (const c of v.claims) {
|
|
120
|
+
const key = `claim:${hashText([section.ref, c.subject, c.predicate, c.object].join('\u0000'))}`;
|
|
121
|
+
const text = `${c.subject} ${c.predicate} ${c.object}`;
|
|
122
|
+
a.batch.fact({
|
|
123
|
+
key, content: claimContent(text, c.quote), source: REVIEW_FACT_SOURCE,
|
|
124
|
+
importance: 0.5, origin: 'model', fileAnchors: [anchor],
|
|
125
|
+
});
|
|
126
|
+
const ref = factRef(key);
|
|
127
|
+
rel(ref, section.ref, 'about');
|
|
128
|
+
for (const term of [c.subject, c.object]) {
|
|
129
|
+
const ent = entityRefs.get(normalizeKey(term));
|
|
130
|
+
if (ent) rel(ref, ent, 'mentions');
|
|
131
|
+
}
|
|
132
|
+
claims.push({ ref, text });
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
return claims;
|
|
136
|
+
}
|
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* src/knowledge/modelLimiter.test.ts
|
|
3
|
+
* The review's ONE cap on model calls in flight (PRD 41 A8): bounded, AIMD on rate limits, and
|
|
4
|
+
* nothing starts once the signal has aborted.
|
|
5
|
+
*/
|
|
6
|
+
|
|
7
|
+
import { createModelLimiter, isRateLimit } from './modelLimiter.js';
|
|
8
|
+
|
|
9
|
+
const rateLimited = () => Object.assign(new Error('429 rate limited'), { status: 429 });
|
|
10
|
+
const ok = async () => 'ok';
|
|
11
|
+
|
|
12
|
+
describe('createModelLimiter', () => {
|
|
13
|
+
it('never has more calls in flight than its width', async () => {
|
|
14
|
+
const limiter = createModelLimiter(3);
|
|
15
|
+
let live = 0;
|
|
16
|
+
let max = 0;
|
|
17
|
+
await Promise.all(Array.from({ length: 12 }, () => limiter.run(async () => {
|
|
18
|
+
live += 1; max = Math.max(max, live);
|
|
19
|
+
await new Promise((r) => setTimeout(r, 1));
|
|
20
|
+
live -= 1;
|
|
21
|
+
})));
|
|
22
|
+
expect(max).toBe(3);
|
|
23
|
+
});
|
|
24
|
+
|
|
25
|
+
it('halves on a rate limit (minimum 1) and grows back by 1 per growEvery successes', async () => {
|
|
26
|
+
const limiter = createModelLimiter(8, { growEvery: 3 });
|
|
27
|
+
await expect(limiter.run(async () => { throw rateLimited(); })).rejects.toThrow('429');
|
|
28
|
+
expect(limiter.width).toBe(4);
|
|
29
|
+
await expect(limiter.run(async () => { throw rateLimited(); })).rejects.toThrow('429');
|
|
30
|
+
expect(limiter.width).toBe(2);
|
|
31
|
+
await expect(limiter.run(async () => { throw rateLimited(); })).rejects.toThrow('429');
|
|
32
|
+
await expect(limiter.run(async () => { throw rateLimited(); })).rejects.toThrow('429');
|
|
33
|
+
expect(limiter.width).toBe(1);
|
|
34
|
+
|
|
35
|
+
for (let i = 0; i < 3; i++) await limiter.run(ok);
|
|
36
|
+
expect(limiter.width).toBe(2);
|
|
37
|
+
for (let i = 0; i < 3 * 10; i++) await limiter.run(ok);
|
|
38
|
+
expect(limiter.width).toBe(8); // back at the cap, never above
|
|
39
|
+
});
|
|
40
|
+
|
|
41
|
+
it('a failure that is not a rate limit leaves the width alone', async () => {
|
|
42
|
+
const limiter = createModelLimiter(4);
|
|
43
|
+
await expect(limiter.run(async () => { throw new Error('boom'); })).rejects.toThrow('boom');
|
|
44
|
+
expect(limiter.width).toBe(4);
|
|
45
|
+
});
|
|
46
|
+
|
|
47
|
+
it('rejects a waiting call whose signal aborted instead of starting it', async () => {
|
|
48
|
+
const limiter = createModelLimiter(1);
|
|
49
|
+
const controller = new AbortController();
|
|
50
|
+
let started = 0;
|
|
51
|
+
const first = limiter.run(async () => { started += 1; await new Promise((r) => setTimeout(r, 5)); });
|
|
52
|
+
const waiting = limiter.run(async () => { started += 1; }, controller.signal);
|
|
53
|
+
controller.abort();
|
|
54
|
+
await expect(waiting).rejects.toBeDefined();
|
|
55
|
+
await first;
|
|
56
|
+
expect(started).toBe(1);
|
|
57
|
+
});
|
|
58
|
+
});
|
|
59
|
+
|
|
60
|
+
describe('isRateLimit', () => {
|
|
61
|
+
it('recognises a 429 status or the usual wording', () => {
|
|
62
|
+
expect(isRateLimit({ status: 429 })).toBe(true);
|
|
63
|
+
expect(isRateLimit(new Error('Rate limit exceeded'))).toBe(true);
|
|
64
|
+
expect(isRateLimit(new Error('HTTP 429'))).toBe(true);
|
|
65
|
+
expect(isRateLimit(new Error('401 unauthorized'))).toBe(false);
|
|
66
|
+
expect(isRateLimit(null)).toBe(false);
|
|
67
|
+
});
|
|
68
|
+
});
|
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* knowledge/modelLimiter.ts — ONE cap on the model calls in flight across every file of a review
|
|
3
|
+
* (PRD 41 A8), so judging N files at once does not multiply the provider's load.
|
|
4
|
+
*
|
|
5
|
+
* AIMD: a rate-limit answer halves the width (minimum 1); every `growEvery` successful calls grow it
|
|
6
|
+
* by 1, back up to the cap. Waiting calls start in order; one whose signal has aborted is rejected
|
|
7
|
+
* instead of started, so nothing starts after an abort.
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
export interface ModelLimiter {
|
|
11
|
+
/** Calls allowed in flight right now (1..max). */
|
|
12
|
+
readonly width: number;
|
|
13
|
+
readonly max: number;
|
|
14
|
+
run<T>(fn: () => Promise<T>, signal?: AbortSignal): Promise<T>;
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
/** An error that says the provider is rate limiting us (HTTP 429 or the usual wording). */
|
|
18
|
+
export function isRateLimit(err: unknown): boolean {
|
|
19
|
+
const e = err as { status?: unknown; statusCode?: unknown; message?: unknown } | null;
|
|
20
|
+
if (e?.status === 429 || e?.statusCode === 429) return true;
|
|
21
|
+
return typeof e?.message === 'string' && /\b429\b|rate.?limit|too many requests/i.test(e.message);
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
interface Waiter { start(): void; reject(reason: unknown): void; signal: AbortSignal | undefined }
|
|
25
|
+
|
|
26
|
+
export function createModelLimiter(max: number, opts: { growEvery?: number } = {}): ModelLimiter {
|
|
27
|
+
const cap = Math.max(1, Math.floor(max));
|
|
28
|
+
const growEvery = Math.max(1, Math.floor(opts.growEvery ?? 20));
|
|
29
|
+
let width = cap;
|
|
30
|
+
let active = 0;
|
|
31
|
+
let successes = 0;
|
|
32
|
+
const waiting: Waiter[] = [];
|
|
33
|
+
|
|
34
|
+
const pump = () => {
|
|
35
|
+
while (active < width && waiting.length > 0) {
|
|
36
|
+
const w = waiting.shift()!;
|
|
37
|
+
if (w.signal?.aborted) { w.reject(w.signal.reason ?? new Error('aborted')); continue; }
|
|
38
|
+
active += 1;
|
|
39
|
+
w.start();
|
|
40
|
+
}
|
|
41
|
+
};
|
|
42
|
+
|
|
43
|
+
return {
|
|
44
|
+
get width() { return width; },
|
|
45
|
+
max: cap,
|
|
46
|
+
run<T>(fn: () => Promise<T>, signal?: AbortSignal): Promise<T> {
|
|
47
|
+
return new Promise<T>((resolve, reject) => {
|
|
48
|
+
waiting.push({
|
|
49
|
+
signal, reject,
|
|
50
|
+
start: () => {
|
|
51
|
+
(async () => fn())().then(
|
|
52
|
+
(v) => {
|
|
53
|
+
successes += 1;
|
|
54
|
+
if (successes >= growEvery && width < cap) { width += 1; successes = 0; }
|
|
55
|
+
resolve(v);
|
|
56
|
+
},
|
|
57
|
+
(err) => {
|
|
58
|
+
if (isRateLimit(err)) { width = Math.max(1, Math.floor(width / 2)); successes = 0; }
|
|
59
|
+
reject(err);
|
|
60
|
+
},
|
|
61
|
+
).finally(() => { active -= 1; pump(); });
|
|
62
|
+
},
|
|
63
|
+
});
|
|
64
|
+
pump();
|
|
65
|
+
});
|
|
66
|
+
},
|
|
67
|
+
};
|
|
68
|
+
}
|