@seanhogg/builderforce-memory 2026.10.53 → 2026.10.55

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (42) hide show
  1. package/dist/knowledge/backfillNoExtract.d.ts +2 -2
  2. package/dist/knowledge/backfillNoExtract.js +2 -2
  3. package/dist/knowledge/extractFile.d.ts.map +1 -1
  4. package/dist/knowledge/extractFile.js +11 -4
  5. package/dist/knowledge/extractFile.js.map +1 -1
  6. package/dist/knowledge/extractJob.d.ts +11 -0
  7. package/dist/knowledge/extractJob.d.ts.map +1 -1
  8. package/dist/knowledge/extractJob.js +10 -0
  9. package/dist/knowledge/extractJob.js.map +1 -1
  10. package/dist/knowledge/index.d.ts +1 -1
  11. package/dist/knowledge/index.d.ts.map +1 -1
  12. package/dist/knowledge/index.js +1 -1
  13. package/dist/knowledge/index.js.map +1 -1
  14. package/dist/knowledge/owedFiles.d.ts +9 -1
  15. package/dist/knowledge/owedFiles.d.ts.map +1 -1
  16. package/dist/knowledge/owedFiles.js +11 -2
  17. package/dist/knowledge/owedFiles.js.map +1 -1
  18. package/dist/knowledge/review.d.ts.map +1 -1
  19. package/dist/knowledge/review.js +11 -15
  20. package/dist/knowledge/review.js.map +1 -1
  21. package/dist/knowledge/reviewFailure.d.ts +39 -0
  22. package/dist/knowledge/reviewFailure.d.ts.map +1 -0
  23. package/dist/knowledge/reviewFailure.js +40 -0
  24. package/dist/knowledge/reviewFailure.js.map +1 -0
  25. package/dist/knowledge/reviewPrefetch.d.ts +2 -2
  26. package/dist/knowledge/reviewPrefetch.d.ts.map +1 -1
  27. package/dist/knowledge/reviewPrefetch.js +6 -6
  28. package/dist/knowledge/reviewPrefetch.js.map +1 -1
  29. package/package.json +3 -3
  30. package/src/contract/exports.snapshot.json +1 -0
  31. package/src/contract/regression.recheck.test.ts +290 -0
  32. package/src/contract/regression.review.test.ts +1 -143
  33. package/src/contract/types.contract.test.ts +6 -1
  34. package/src/knowledge/backfillNoExtract.ts +2 -2
  35. package/src/knowledge/extractFile.ts +6 -4
  36. package/src/knowledge/extractJob.ts +11 -0
  37. package/src/knowledge/index.ts +1 -1
  38. package/src/knowledge/owedFiles.ts +13 -2
  39. package/src/knowledge/review.ordered.test.ts +7 -3
  40. package/src/knowledge/review.ts +10 -10
  41. package/src/knowledge/reviewFailure.ts +54 -0
  42. package/src/knowledge/reviewPrefetch.ts +6 -6
@@ -8,7 +8,7 @@
8
8
 
9
9
  import type { ParsedSection, SourceDocument } from '../ingest/types.js';
10
10
  import type { Extracted, KnowledgePack, KnowledgeParser, KnowledgeStore, NodeRef } from './model.js';
11
- import { BinaryContent, jobOf, runExtractor, type ExtractPool } from './extractJob.js';
11
+ import { BinaryContent, CHANGED_SINCE_PLAN, ExtractFailed, jobOf, runExtractor, type ExtractPool } from './extractJob.js';
12
12
  import { srcRef } from './refs.js';
13
13
  import { entityName, knownKeysOf, resolveEntities } from './resolve.js';
14
14
  import { asPathSource, composePacks, EXTRACTOR_VERSION, resolveRelativePath, stubSource, type ComposedPacks } from './sources.js';
@@ -88,7 +88,9 @@ export async function extractFileDetailed(a: ExtractFileArgs): Promise<FileExtra
88
88
  const ref = srcRef(a.rootId, a.path);
89
89
  // With a pool the main thread never parses: the worker returns the sections when the file will be judged.
90
90
  const wants = !!a.pool && !!a.wantsSections?.(hit.pack);
91
- let sections: ParsedSection[] = a.pool ? [] : hit.parser.parse(src);
91
+ // The parser and the extractor run in this thread only without a pool; their errors are the PROVEN-final failures (ExtractFailed).
92
+ const proven = <T>(work: () => T): T => { try { return work(); } catch (error) { throw new ExtractFailed(error instanceof Error ? error.message : String(error), { cause: error }); } };
93
+ let sections: ParsedSection[] = a.pool ? [] : proven(() => hit.parser.parse(src));
92
94
  const tLookup = Date.now();
93
95
  const cached = await a.store.getExtracted?.(a.hash);
94
96
  const lookupMs = Date.now() - tLookup;
@@ -117,14 +119,14 @@ export async function extractFileDetailed(a: ExtractFileArgs): Promise<FileExtra
117
119
  const mine = out.extracted.find((e) => e.sourceRef === ref);
118
120
  if (!mine) throw new Error(`extract pool returned no extract for ${a.path}`);
119
121
  // The pool read other bytes than the plan hashed: nothing is stored under the planned hash.
120
- if (mine.sourceHash !== a.hash) throw new Error('changed since plan');
122
+ if (mine.sourceHash !== a.hash) throw new Error(CHANGED_SINCE_PLAN); // transient: the bytes may settle
121
123
  if (wants) {
122
124
  if (!out.sections) throw new Error(`extract pool returned no sections for ${a.path}`);
123
125
  sections = out.sections;
124
126
  }
125
127
  extracted = mine;
126
128
  } else {
127
- extracted = runExtractor(hit, src, sections, { rootId: a.rootId, knownKeys, resolvePath: resolveRelativePath }, a);
129
+ extracted = proven(() => runExtractor(hit, src, sections, { rootId: a.rootId, knownKeys, resolvePath: resolveRelativePath }, a));
128
130
  }
129
131
  if (a.writeCache !== false) await putExtract(a.store, a.hash, extracted, cached ?? []);
130
132
  return { extracted, parser: hit.parser, pack: hit.pack, sections, cached: false };
@@ -40,6 +40,17 @@ export type ExtractJobSource =
40
40
 
41
41
  export type ExtractJob = ExtractJobBase & ExtractJobSource;
42
42
 
43
+ /** The planned bytes are not the bytes read: nothing is stored under the planned hash. Always TRANSIENT (the bytes may settle). */
44
+ export const CHANGED_SINCE_PLAN = 'changed since plan';
45
+
46
+ /**
47
+ * A failure PROVEN final: the parser or extractor itself threw on these bytes (in-thread, or a pool's worker reporting it). Every other
48
+ * failure (a read, a timeout, a crashed or disposed worker, a failing store, a changed-since-plan) is transient: the file may extract next time.
49
+ */
50
+ export class ExtractFailed extends Error {
51
+ constructor(message: string, options?: { cause?: unknown }) { super(message); this.name = 'ExtractFailed'; if (options?.cause !== undefined) (this as { cause?: unknown }).cause = options.cause; }
52
+ }
53
+
43
54
  /** Thrown by the extract stage when the pool found the file binary; the review records a `skipped` step. */
44
55
  export class BinaryContent extends Error {
45
56
  constructor() { super('binary'); this.name = 'BinaryContent'; }
@@ -49,7 +49,7 @@ export { orderForJudging } from './judgePriority.js';
49
49
  export type { JudgeSignals } from './judgePriority.js';
50
50
  export { extractFile, extractFileDetailed, knownKeysOfEntities } from './extractFile.js';
51
51
  export type { ExtractFileArgs, FileExtraction } from './extractFile.js';
52
- export { extractJob, jobOf } from './extractJob.js';
52
+ export { ExtractFailed, extractJob, jobOf } from './extractJob.js';
53
53
  export type { ExtractJob, ExtractJobResult, ExtractPool } from './extractJob.js';
54
54
  export { putExtract, putNoExtract } from './extractFile.js';
55
55
  export { createModelLimiter, isRateLimit } from './modelLimiter.js';
@@ -31,6 +31,7 @@ import { EXTRACTOR_VERSION, extractorManifestKey } from './sources.js';
31
31
 
32
32
  const VERSION_ID = 'version';
33
33
  const OWED_PREFIX = 'owed:';
34
+ const FAIL_PREFIX = 'fail:';
34
35
  /** What a version upgrade costs per file: the one new section a re-extraction may add (an upper bound). */
35
36
  const UPGRADE_CALLS = 1;
36
37
 
@@ -39,21 +40,28 @@ export interface ExtractorState {
39
40
  version: number | undefined;
40
41
  /** Paths a previous run left unfinished under that version → model calls each still costs. */
41
42
  owed: ReadonlyMap<string, number>;
43
+ /** Consecutive transient failures of a path at one content hash (stored beside its owed entry); a success or a new hash resets it. Optional: a caller that builds a state by hand need not know it. */
44
+ failures?: ReadonlyMap<string, { hash: string; count: number }>;
42
45
  }
43
46
 
44
47
  export async function loadExtractorState(manifest: IngestManifest, rootId: string): Promise<ExtractorState> {
45
48
  let version: number | undefined;
46
49
  const owed = new Map<string, number>();
50
+ const failures = new Map<string, { hash: string; count: number }>();
47
51
  for (const { id, hash } of (await manifest.get(extractorManifestKey(rootId))) ?? []) {
48
52
  if (id === VERSION_ID) {
49
53
  const v = Number(hash);
50
54
  if (Number.isFinite(v)) version = v;
55
+ } else if (id.startsWith(FAIL_PREFIX)) {
56
+ const at = hash.indexOf(':');
57
+ const count = Number(hash.slice(0, at));
58
+ if (at > 0 && Number.isInteger(count) && count > 0) failures.set(id.slice(FAIL_PREFIX.length), { hash: hash.slice(at + 1), count });
51
59
  } else if (id.startsWith(OWED_PREFIX)) {
52
60
  const calls = Number(hash);
53
61
  owed.set(id.slice(OWED_PREFIX.length), Number.isFinite(calls) && calls >= 0 ? calls : UPGRADE_CALLS);
54
62
  }
55
63
  }
56
- return { version, owed };
64
+ return { version, owed, failures };
57
65
  }
58
66
 
59
67
  /** True when `path` is owed a re-extraction: another extractor version than today's, or left unfinished before. */
@@ -102,9 +110,12 @@ export function owedAfterRun(a: {
102
110
  }
103
111
 
104
112
  /** Records today's version and exactly the files still owed after this run. */
105
- export async function saveExtractorState(manifest: IngestManifest, rootId: string, owed: ReadonlyMap<string, number>): Promise<void> {
113
+ export async function saveExtractorState(
114
+ manifest: IngestManifest, rootId: string, owed: ReadonlyMap<string, number>, failures: ReadonlyMap<string, { hash: string; count: number }> = new Map(),
115
+ ): Promise<void> {
106
116
  await manifest.set(extractorManifestKey(rootId), [
107
117
  { id: VERSION_ID, hash: String(EXTRACTOR_VERSION) },
108
118
  ...[...owed].sort((a, b) => compareStr(a[0], b[0])).map(([path, calls]) => ({ id: `${OWED_PREFIX}${path}`, hash: String(calls) })),
119
+ ...[...failures].filter(([path]) => owed.has(path)).sort((a, b) => compareStr(a[0], b[0])).map(([path, f]) => ({ id: `${FAIL_PREFIX}${path}`, hash: `${f.count}:${f.hash}` })),
109
120
  ]);
110
121
  }
@@ -78,6 +78,10 @@ async function runTwice(shape: Shape) {
78
78
  return { first, second, inFlight: max };
79
79
  }
80
80
 
81
+ // Each case runs four full reviews of the fixture (two widths, first + incremental); under a
82
+ // parallel jest run that exceeds the 5 s default, so the budget is explicit.
83
+ const ORDERED_REVIEW_TIMEOUT_MS = 30_000;
84
+
81
85
  describe('parallel review, ordered writer', () => {
82
86
  it('stores the same bytes and manifests at 8/4 as at 1/1, on a first and an incremental review', async () => {
83
87
  const wide = await runTwice({ concurrency: 8, judgeConcurrency: 4, modelCalls: 500 });
@@ -90,7 +94,7 @@ describe('parallel review, ordered writer', () => {
90
94
  expect(wide.second.bytes).not.toBe(wide.first.bytes);
91
95
  expect(wide.second.bytes).toBe(narrow.second.bytes);
92
96
  expect(wide.second.manifests).toBe(narrow.second.manifests);
93
- });
97
+ }, ORDERED_REVIEW_TIMEOUT_MS);
94
98
 
95
99
  it('stores the same bytes through an extraction pool at width as in-thread at 1/1', async () => {
96
100
  const pooled = await runTwice({ concurrency: 8, judgeConcurrency: 4, modelCalls: 500, pool: true });
@@ -98,7 +102,7 @@ describe('parallel review, ordered writer', () => {
98
102
  expect(pooled.first.bytes).toBe(narrow.first.bytes);
99
103
  expect(pooled.second.bytes).toBe(narrow.second.bytes);
100
104
  expect(pooled.second.manifests).toBe(narrow.second.manifests);
101
- });
105
+ }, ORDERED_REVIEW_TIMEOUT_MS);
102
106
 
103
107
  it('spends a short model-call budget in plan order whatever the widths', async () => {
104
108
  const wide = await runTwice({ concurrency: 8, judgeConcurrency: 4, modelCalls: 17 });
@@ -110,5 +114,5 @@ describe('parallel review, ordered writer', () => {
110
114
  expect(wide.first.bytes).toBe(narrow.first.bytes);
111
115
  expect(wide.second.bytes).toBe(narrow.second.bytes);
112
116
  expect(wide.second.manifests).toBe(narrow.second.manifests);
113
- });
117
+ }, ORDERED_REVIEW_TIMEOUT_MS);
114
118
  });
@@ -33,6 +33,7 @@ import { planDetail, refreshPlan } from './plan.js';
33
33
  import { composePacks, filesManifestKey, judgedManifestKey, manifestMap, saveManifestMap } from './sources.js';
34
34
  import { knownKeysOfEntities, putExtract, putNoExtract } from './extractFile.js';
35
35
  import { backfillCandidates, backfillNoExtract } from './backfillNoExtract.js';
36
+ import { recordFailure } from './reviewFailure.js';
36
37
  import { prefetchOrdered } from './orderedPool.js';
37
38
  import {
38
39
  DEFAULT_REVIEW_CONCURRENCY, DEFAULT_REVIEW_JUDGE_CONCURRENCY, DEFAULT_REVIEW_MODEL_CALLS, JUDGE_CONCURRENCY, JudgedBatch,
@@ -173,6 +174,8 @@ async function reviewRun(args: ReviewArgs, flush: () => Promise<void>): Promise<
173
174
  const finished = new Set<string>();
174
175
  /** Files that failed for a reason that says nothing final about them, at the manifest's own bytes: owed, so the next review retries them. */
175
176
  const unreadable = new Set<string>();
177
+ /** Consecutive transient failures by path at one hash (saved beside the owed record). */
178
+ const failures = new Map(detail.extractor.failures ?? []);
176
179
  const measured = new Map<string, number>();
177
180
  // Read + binary check + extract run ahead with bounded concurrency (extraction only reads `knownKeys`,
178
181
  // fixed above, and the content-hash extract cache); with `args.extractPool` the width is the pool's.
@@ -213,17 +216,12 @@ async function reviewRun(args: ReviewArgs, flush: () => Promise<void>): Promise<
213
216
  if (job.kind === 'read-error') report.readErrors += 1; else report.extractErrors += 1;
214
217
  fail(f.path, 'extract', job.kind === 'read-error' ? `read: ${job.reason}` : job.reason);
215
218
  measured.set(f.path, owedCalls(detail.extractor, f.path)); // learns nothing: keep what it was owed
216
- // A FINAL failure gets a terminal answer, so a replica does not hold the file back and ask for it forever: the manifest's bytes are
217
- // gone (the hash moved), or the extraction failed deterministically (not a timeout, a stop or a changed-since-plan). Never when the
218
- // run was stopped. A transient failure at the manifest's own bytes keeps the re-check request AND makes the file owed, so the next
219
- // normal review retries it. (`[]` rather than a sibling member: the reason is already in `report.failures`.)
220
- const known = detail.prior.get(f.path);
221
- const transient = job.kind === 'read-error' || job.transient === true; // a read error says nothing final about the bytes
222
- if (known && !runSignal.aborted) {
223
- if (known !== f.hash || !transient) { await putNoExtract(store, known); await settledRecheck(known); } else unreadable.add(f.path);
224
- }
219
+ // The ONE failure path (reviewFailure.ts): a transient failure keeps the re-check request and makes the file owed; only a proven-final
220
+ // one (or the third in a row at the same bytes) is answered with a terminal `[]`.
221
+ if (await recordFailure({ store, detail, stopped: () => runSignal.aborted, unreadable, failures, settledRecheck }, f, job)) finished.add(f.path); // final: settled, not re-read while its bytes stand
225
222
  return true;
226
223
  }
224
+ failures.delete(f.path); // it read and extracted (or was decided): the run of failures at this hash ends
227
225
  // Recorded, so a file found binary on read is not re-read by every later review.
228
226
  if (job.kind === 'binary') {
229
227
  filesNow.set(f.path, f.hash);
@@ -314,6 +312,8 @@ async function reviewRun(args: ReviewArgs, flush: () => Promise<void>): Promise<
314
312
  await Promise.allSettled(queue.map((s) => s.judge?.result)); // nothing outlives the run
315
313
  }
316
314
  if (applied < work.length) report.aborted = true;
315
+ // A Stop ends the run: the file in hand was finished and applied above, but nothing after it (retire, analyzers, the digest stamp) runs.
316
+ report.aborted ||= runSignal.aborted;
317
317
 
318
318
  // Pass 2 (`only`) is judging alone: the map pass already retired the removed files and ran the analyzers.
319
319
  if (!report.aborted && !args.only) {
@@ -373,7 +373,7 @@ async function reviewRun(args: ReviewArgs, flush: () => Promise<void>): Promise<
373
373
  // content-changed or not, and the owed paths the plan did not list that the manifest still holds.
374
374
  await saveExtractorState(manifest, rootId, owedAfterRun({
375
375
  state: detail.extractor, changed, prior: detail.prior, finished, carried: detail.carried, live: filesNow, measured, unreadable,
376
- }));
376
+ }), failures);
377
377
  await write(report.aborted ? scopeRecord : { ...scopeRecord, lastDigest: report.digest, lastReviewedAt: new Date(now()).toISOString() });
378
378
  report.durationMs = now() - started;
379
379
  progress({ phase: 'done', done: work.length, total: work.length });
@@ -0,0 +1,54 @@
1
+ /**
2
+ * knowledge/reviewFailure.ts — what a review does with a file whose read or extraction failed (the ONE failure path).
3
+ *
4
+ * A failure is TRANSIENT unless proven final (see {@link ExtractFailed}): a read, a timeout, a crashed or disposed worker, a failing store, a stop.
5
+ * A replica that holds the file back and asks about it needs an answer, but only a final one may be terminal (`[]` = nothing extracted):
6
+ *
7
+ * - final: the manifest's bytes are gone (the hash moved), or the parser/extractor threw on them. `[]` is stored under the manifest's hash
8
+ * and the request is settled — unless an unchanged planned file still carries that hash (its content is readable: do not hide it);
9
+ * - transient at the manifest's own bytes: the request is kept and the path is made OWED, so the next normal review retries it;
10
+ * after {@link MAX_TRANSIENT_FAILURES} in a row at the same hash it is treated as final, so a file that never reads cannot hold a root forever.
11
+ * A final failure is STICKY: the review counts the file as settled, so it is not re-read (or re-reported) until its bytes change or the extractor version moves;
12
+ * - never anything when the run was stopped.
13
+ */
14
+
15
+ import { putNoExtract } from './extractFile.js';
16
+ import type { KnowledgeStore } from './model.js';
17
+ import type { PlanDetail } from './plan.js';
18
+ import type { Prefetch } from './reviewPrefetch.js';
19
+
20
+ /** Consecutive transient failures at one hash after which the failure is recorded as final. */
21
+ export const MAX_TRANSIENT_FAILURES = 3;
22
+
23
+ export interface FailureContext {
24
+ store: KnowledgeStore;
25
+ detail: PlanDetail;
26
+ stopped: () => boolean;
27
+ /** Paths to record as owed (a transient failure at the manifest's own bytes). */
28
+ unreadable: Set<string>;
29
+ /** Consecutive transient failures by path (persisted beside the owed entry). */
30
+ failures: Map<string, { hash: string; count: number }>;
31
+ settledRecheck: (hash: string) => Promise<void>;
32
+ }
33
+
34
+ /** True when the failure was recorded as FINAL: the review then counts the file as settled, so it is not re-read (and re-reported) while its bytes stay as they are. */
35
+ export async function recordFailure(ctx: FailureContext, f: { path: string; hash: string }, job: Extract<Prefetch, { kind: 'read-error' | 'failed' }>): Promise<boolean> {
36
+ const known = ctx.detail.prior.get(f.path);
37
+ if (!known || ctx.stopped()) return false;
38
+ const transient = job.kind === 'read-error' || job.transient === true;
39
+ if (known === f.hash && transient) {
40
+ const prev = ctx.failures.get(f.path);
41
+ const count = (prev?.hash === known ? prev.count : 0) + 1;
42
+ if (count < MAX_TRANSIENT_FAILURES) {
43
+ ctx.failures.set(f.path, { hash: known, count });
44
+ ctx.unreadable.add(f.path);
45
+ return false;
46
+ }
47
+ }
48
+ ctx.failures.delete(f.path);
49
+ // An unchanged planned file that still carries `known` is readable content: a terminal `[]` would hide it.
50
+ if (ctx.detail.files.some((g) => g.path !== f.path && !g.changed && g.hash === known)) return true;
51
+ await putNoExtract(ctx.store, known);
52
+ await ctx.settledRecheck(known);
53
+ return true;
54
+ }
@@ -12,9 +12,9 @@
12
12
  import type { SourceDocument } from '../ingest/types.js';
13
13
  import type { KnowledgePack, KnowledgeStore, NodeRef, ReviewArgs } from './model.js';
14
14
  import { extractFileDetailed, type FileExtraction } from './extractFile.js';
15
- import { BinaryContent } from './extractJob.js';
15
+ import { BinaryContent, CHANGED_SINCE_PLAN, ExtractFailed } from './extractJob.js';
16
16
  import { judgesPack } from './reviewJudge.js';
17
- import { createDeadlines, JobTimeout } from './jobDeadline.js';
17
+ import { createDeadlines } from './jobDeadline.js';
18
18
  import { createModelLimiter } from './modelLimiter.js';
19
19
  import { Lanes, reasonOf, type ReviewStep } from './reviewRunModel.js';
20
20
  import { isBinaryText, type ComposedPacks } from './sources.js';
@@ -58,8 +58,7 @@ export function extractStepOf(path: string, job: Prefetch): ReviewStep {
58
58
  }
59
59
  }
60
60
 
61
- /** The failure reason of a file whose bytes no longer match the planned hash. */
62
- export const CHANGED_SINCE_PLAN = 'changed since plan';
61
+ export { CHANGED_SINCE_PLAN };
63
62
 
64
63
  /** Per-job ceilings of the extract path (PRD 41 A10 rule 2). */
65
64
  export const DEFAULT_READ_TIMEOUT_MS = 5_000;
@@ -108,8 +107,9 @@ export function createPrefetch(c: PrefetchContext): (f: { path: string; hash: st
108
107
  return { kind: 'extracted', ...(doc ? { doc } : {}), extraction };
109
108
  } catch (error) {
110
109
  if (error instanceof BinaryContent) return { kind: 'binary' };
111
- // A timeout or a stop says nothing final about the file; any other extraction error is deterministic.
112
- return { kind: 'failed', reason: reasonOf(error), ...(error instanceof JobTimeout || c.signal.aborted ? { transient: true as const } : {}) };
110
+ // Transient UNLESS proven final: only the parser or extractor throwing on these bytes (ExtractFailed) is. A read, a timeout, a crashed or
111
+ // disposed worker, a failing store, a stop: all say nothing final about the file.
112
+ return { kind: 'failed', reason: reasonOf(error), ...((error instanceof ExtractFailed || (error as { name?: unknown } | null)?.name === 'ExtractFailed') && !c.signal.aborted ? {} : { transient: true as const }) };
113
113
  }
114
114
  };
115
115