@seanhogg/builderforce-memory 2026.10.80 → 2026.10.82
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/build.d.ts.map +1 -1
- package/dist/knowledge/build.js +40 -3
- package/dist/knowledge/build.js.map +1 -1
- package/dist/knowledge/cooperative.d.ts +51 -0
- package/dist/knowledge/cooperative.d.ts.map +1 -0
- package/dist/knowledge/cooperative.js +58 -0
- package/dist/knowledge/cooperative.js.map +1 -0
- package/dist/knowledge/ignoreMatcher.d.ts +25 -0
- package/dist/knowledge/ignoreMatcher.d.ts.map +1 -0
- package/dist/knowledge/ignoreMatcher.js +121 -0
- package/dist/knowledge/ignoreMatcher.js.map +1 -0
- package/dist/knowledge/index.d.ts +5 -1
- package/dist/knowledge/index.d.ts.map +1 -1
- package/dist/knowledge/index.js +3 -0
- package/dist/knowledge/index.js.map +1 -1
- package/dist/knowledge/merkle.d.ts +20 -5
- package/dist/knowledge/merkle.d.ts.map +1 -1
- package/dist/knowledge/merkle.js +25 -7
- package/dist/knowledge/merkle.js.map +1 -1
- package/dist/knowledge/plan.d.ts +6 -0
- package/dist/knowledge/plan.d.ts.map +1 -1
- package/dist/knowledge/plan.js +18 -4
- package/dist/knowledge/plan.js.map +1 -1
- package/dist/knowledge/reviewAnalyse.d.ts.map +1 -1
- package/dist/knowledge/reviewAnalyse.js +6 -1
- package/dist/knowledge/reviewAnalyse.js.map +1 -1
- package/dist/knowledge/reviewFinish.d.ts.map +1 -1
- package/dist/knowledge/reviewFinish.js +7 -1
- package/dist/knowledge/reviewFinish.js.map +1 -1
- package/dist/knowledge/reviewModel.d.ts +10 -0
- package/dist/knowledge/reviewModel.d.ts.map +1 -1
- package/dist/knowledge/rules/factStore.d.ts.map +1 -1
- package/dist/knowledge/rules/factStore.js +24 -1
- package/dist/knowledge/rules/factStore.js.map +1 -1
- package/dist/knowledge/rules/fixpointRules.d.ts +68 -0
- package/dist/knowledge/rules/fixpointRules.d.ts.map +1 -0
- package/dist/knowledge/rules/fixpointRules.js +0 -0
- package/dist/knowledge/rules/fixpointRules.js.map +1 -0
- package/dist/knowledge/sources.d.ts +9 -9
- package/dist/knowledge/sources.d.ts.map +1 -1
- package/dist/knowledge/sources.js +11 -50
- package/dist/knowledge/sources.js.map +1 -1
- package/dist/knowledge/statManifest.d.ts +89 -0
- package/dist/knowledge/statManifest.d.ts.map +1 -0
- package/dist/knowledge/statManifest.js +125 -0
- package/dist/knowledge/statManifest.js.map +1 -0
- package/dist/stats/estimators.d.ts +8 -1
- package/dist/stats/estimators.d.ts.map +1 -1
- package/dist/stats/estimators.js +18 -7
- package/dist/stats/estimators.js.map +1 -1
- package/package.json +1 -1
- package/src/contract/exports.snapshot.json +11 -0
- package/src/contract/regression.assets.test.ts +3 -3
- package/src/contract/regression.contentHash.test.ts +2 -2
- package/src/contract/regression.factStoreBatchedLoad.test.ts +62 -0
- package/src/contract/regression.ignoreMatcher.test.ts +116 -0
- package/src/contract/regression.listing.test.ts +1 -1
- package/src/contract/regression.merkleCooperative.test.ts +79 -0
- package/src/contract/types.contract.test.ts +9 -5
- package/src/knowledge/build.ts +32 -3
- package/src/knowledge/cooperative.test.ts +57 -0
- package/src/knowledge/cooperative.ts +76 -0
- package/src/knowledge/docs.test.ts +30 -0
- package/src/knowledge/ignoreMatcher.ts +143 -0
- package/src/knowledge/index.ts +8 -1
- package/src/knowledge/merkle.test.ts +84 -47
- package/src/knowledge/merkle.ts +38 -8
- package/src/knowledge/plan.ts +22 -4
- package/src/knowledge/review.readAhead.test.ts +4 -1
- package/src/knowledge/reviewAnalyse.ts +6 -1
- package/src/knowledge/reviewFinish.ts +7 -1
- package/src/knowledge/reviewModel.ts +6 -0
- package/src/knowledge/rules/factStore.ts +22 -1
- package/src/knowledge/rules/fixpointRules.test.ts +94 -0
- package/src/knowledge/rules/fixpointRules.ts +0 -0
- package/src/knowledge/sources.ts +12 -46
- package/src/knowledge/statManifest.test.ts +122 -0
- package/src/knowledge/statManifest.ts +176 -0
- package/src/stats/estimators.ts +18 -7
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@seanhogg/builderforce-memory",
|
|
3
|
-
"version": "2026.10.
|
|
3
|
+
"version": "2026.10.82",
|
|
4
4
|
"description": "BuilderForce Agent Memory — runtime layer. SSM execution, Transformer orchestration, online distillation, enterprise RAG (ingestion pipelines, vector-store adapters, tenant/ACL-scoped hybrid retrieval), multi-agent graph orchestration, LLM telemetry and cost accounting, persistent agent memory, and token-saving agent-run memory (code maps, a prompt-cache-safe working memory, chunked transcript windowing) for BuilderForce.ai agents.",
|
|
5
5
|
"main": "dist/index.js",
|
|
6
6
|
"module": "dist/index.js",
|
|
@@ -318,6 +318,7 @@
|
|
|
318
318
|
"MAX_CALL_SITES_PER_EDGE",
|
|
319
319
|
"MAX_CLAIM_TEXT_CHARS",
|
|
320
320
|
"MAX_FINDING_NODES",
|
|
321
|
+
"MAX_FIXPOINT_ITERATIONS",
|
|
321
322
|
"MAX_MOUNT_DEPTH",
|
|
322
323
|
"MAX_NODES_CAP",
|
|
323
324
|
"MAX_QUOTE_CHARS",
|
|
@@ -331,6 +332,7 @@
|
|
|
331
332
|
"OUTLINE_VERDICTS",
|
|
332
333
|
"PAGERANK_DAMPING",
|
|
333
334
|
"PAGERANK_ITERATIONS",
|
|
335
|
+
"RACY_WINDOW_MS",
|
|
334
336
|
"REVIEW_FACT_SOURCE",
|
|
335
337
|
"REVIEW_RUN_FAILURE_CHUNK",
|
|
336
338
|
"REVIEW_RUN_STEP_RING",
|
|
@@ -381,6 +383,7 @@
|
|
|
381
383
|
"contradictionRule",
|
|
382
384
|
"createKnowledgeIndex",
|
|
383
385
|
"createModelLimiter",
|
|
386
|
+
"createStatPrefilter",
|
|
384
387
|
"crossesSystems",
|
|
385
388
|
"decodeCoChange",
|
|
386
389
|
"dedupeSymbolEdges",
|
|
@@ -394,6 +397,7 @@
|
|
|
394
397
|
"entityKey",
|
|
395
398
|
"entityName",
|
|
396
399
|
"evaluateRules",
|
|
400
|
+
"evaluateRulesFixpoint",
|
|
397
401
|
"extractFile",
|
|
398
402
|
"extractFileDetailed",
|
|
399
403
|
"extractJob",
|
|
@@ -432,8 +436,10 @@
|
|
|
432
436
|
"isDocumentPath",
|
|
433
437
|
"isFactsCurrent",
|
|
434
438
|
"isFileFactsV3",
|
|
439
|
+
"isRacy",
|
|
435
440
|
"isRateLimit",
|
|
436
441
|
"isRootFilePath",
|
|
442
|
+
"isRowSourceInput",
|
|
437
443
|
"isSymbolEdgeKind",
|
|
438
444
|
"jobOf",
|
|
439
445
|
"joinRoutePath",
|
|
@@ -446,6 +452,7 @@
|
|
|
446
452
|
"loadFactGraph",
|
|
447
453
|
"loadKnowledgeIndex",
|
|
448
454
|
"loadPartitions",
|
|
455
|
+
"loadStatManifest",
|
|
449
456
|
"localSnapshotStore",
|
|
450
457
|
"matchGlob",
|
|
451
458
|
"matchLineage",
|
|
@@ -475,6 +482,7 @@
|
|
|
475
482
|
"planDetail",
|
|
476
483
|
"planReview",
|
|
477
484
|
"possibleSameFindings",
|
|
485
|
+
"prefilterStats",
|
|
478
486
|
"projectFileFacts",
|
|
479
487
|
"putExtract",
|
|
480
488
|
"putNoExtract",
|
|
@@ -493,6 +501,7 @@
|
|
|
493
501
|
"runKnowledgeRules",
|
|
494
502
|
"runRate",
|
|
495
503
|
"saveFactGraph",
|
|
504
|
+
"saveStatManifest",
|
|
496
505
|
"sha256",
|
|
497
506
|
"sha256Hex",
|
|
498
507
|
"slowestSteps",
|
|
@@ -500,6 +509,8 @@
|
|
|
500
509
|
"splitSourceRef",
|
|
501
510
|
"srcRef",
|
|
502
511
|
"startRun",
|
|
512
|
+
"statManifestKey",
|
|
513
|
+
"statMatches",
|
|
503
514
|
"stationTransitions",
|
|
504
515
|
"sweepFactStore",
|
|
505
516
|
"toCards",
|
|
@@ -172,8 +172,8 @@ describe('regression: the asset lifecycle', () => {
|
|
|
172
172
|
expect((await stateOf(manifest)).version).toBe(EXTRACTOR_VERSION);
|
|
173
173
|
});
|
|
174
174
|
|
|
175
|
-
it('regression: EXTRACTOR_VERSION is
|
|
176
|
-
expect(EXTRACTOR_VERSION).toBe(
|
|
175
|
+
it('regression: EXTRACTOR_VERSION is 7, so cached code extracts re-run after the PRD 43 deploy-unit and concurrency code-pack changes', () => {
|
|
176
|
+
expect(EXTRACTOR_VERSION).toBe(7);
|
|
177
177
|
});
|
|
178
178
|
|
|
179
179
|
it('regression: a removed asset is retired like any removed file', async () => {
|
|
@@ -233,7 +233,7 @@ describe('regression: an oversized claimed document stays an asset', () => {
|
|
|
233
233
|
const again = await reviewDirectory(args(source, store, manifest, { packs: [withPdf] }));
|
|
234
234
|
expect(again.extracted).toBe(1);
|
|
235
235
|
expect((await store.getExtracted(hashText('small pdf text')))![0]!.nodes[0]!.badges?.asset).toBeUndefined();
|
|
236
|
-
});
|
|
236
|
+
}, 30_000); // CPU-bound (a 3 MB text hashed by two plans and two reviews): ~2 s alone, 5–6.5 s beside other suites.
|
|
237
237
|
|
|
238
238
|
it('regression: an oversized claimed pdf still owes no calls after an aborted run and a refreshed (Continue) plan', async () => {
|
|
239
239
|
const source = memSource({ 'big.pdf': 'x'.repeat(3 * 1024 * 1024) });
|
|
@@ -21,10 +21,10 @@ const listing = (files: Record<string, string>, eol: (s: string) => string = (s)
|
|
|
21
21
|
Object.entries(files).map(([path, text]) => ({ path, hash: contentHash(utf8(eol(text))) }));
|
|
22
22
|
|
|
23
23
|
describe('regression: cross-OS content identity', () => {
|
|
24
|
-
it('regression: a Windows autocrlf checkout and a Linux checkout hash differently', () => {
|
|
24
|
+
it('regression: a Windows autocrlf checkout and a Linux checkout hash differently', async () => {
|
|
25
25
|
const linux = listing(COMMIT);
|
|
26
26
|
const windows = listing(COMMIT, autocrlf);
|
|
27
27
|
expect(windows).toEqual(linux);
|
|
28
|
-
expect(merkleTree(windows).root).toBe(merkleTree(linux).root);
|
|
28
|
+
expect((await merkleTree(windows)).root).toBe((await merkleTree(linux)).root);
|
|
29
29
|
});
|
|
30
30
|
});
|
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* src/contract/regression.factStoreBatchedLoad.test.ts — `loadFactGraph` reads objects in bounded `getObjects` batches.
|
|
3
|
+
*
|
|
4
|
+
* Before: one `getObjects` call with EVERY referenced hash, which the VS Code host's SQLite port serves as one synchronous
|
|
5
|
+
* transaction on the extension host's main thread (seconds on a large workspace). Now the load asks in bounded batches and
|
|
6
|
+
* yields between them; the loaded graph is exactly what the single call produced.
|
|
7
|
+
*/
|
|
8
|
+
|
|
9
|
+
import type { FileFacts } from '../knowledge/facts/fileFacts.js';
|
|
10
|
+
import { buildFactGraph, factGraphDump } from '../knowledge/rules/factGraph.js';
|
|
11
|
+
import { loadFactGraph, memoryFactStore, saveFactGraph, type FactStorePort } from '../knowledge/rules/factStore.js';
|
|
12
|
+
import { emptyFacts, FIXTURE_RULES } from '../knowledge/rules/rules.testkit.test-util.js';
|
|
13
|
+
|
|
14
|
+
const FILES = 1300;
|
|
15
|
+
|
|
16
|
+
const tree = (): Array<readonly [string, FileFacts]> =>
|
|
17
|
+
Array.from({ length: FILES }, (_, i) => [
|
|
18
|
+
`src/f${i}.ts`,
|
|
19
|
+
{ ...emptyFacts(`c${i}`), exports: [{ name: `e${i}`, kind: 'function', signatureHash: `s${i}` }] },
|
|
20
|
+
] as const);
|
|
21
|
+
|
|
22
|
+
describe('regression: batched fact store load', () => {
|
|
23
|
+
it('regression: a load asks getObjects in bounded batches covering every hash once, and returns the same graph as one call', async () => {
|
|
24
|
+
const graph = buildFactGraph(tree(), FIXTURE_RULES).graph;
|
|
25
|
+
const store = memoryFactStore();
|
|
26
|
+
await saveFactGraph(store, graph);
|
|
27
|
+
|
|
28
|
+
const calls: string[][] = [];
|
|
29
|
+
const batched: FactStorePort = { ...store, getObjects: (hashes) => { calls.push([...hashes]); return store.getObjects(hashes); } };
|
|
30
|
+
// The reference: a port that answers every hash at once whatever it is asked, as the single call did.
|
|
31
|
+
const all = [...graph.objects.keys()];
|
|
32
|
+
const whole: FactStorePort = { ...store, getObjects: () => store.getObjects(all) };
|
|
33
|
+
|
|
34
|
+
const loaded = await loadFactGraph(batched, { verify: 'manifest' });
|
|
35
|
+
const reference = await loadFactGraph(whole, { verify: 'manifest' });
|
|
36
|
+
expect(factGraphDump(loaded.graph)).toBe(factGraphDump(reference.graph));
|
|
37
|
+
expect(factGraphDump(loaded.graph)).toBe(factGraphDump(graph));
|
|
38
|
+
|
|
39
|
+
expect(calls.length).toBeGreaterThan(1);
|
|
40
|
+
expect(Math.max(...calls.map((c) => c.length))).toBeLessThanOrEqual(512);
|
|
41
|
+
const asked = calls.flat();
|
|
42
|
+
expect(asked.length).toBe(new Set(asked).size);
|
|
43
|
+
expect(new Set(asked)).toEqual(new Set(all));
|
|
44
|
+
});
|
|
45
|
+
|
|
46
|
+
it('regression: an object missing from a later batch is still fact_store_object_missing', async () => {
|
|
47
|
+
const graph = buildFactGraph(tree(), FIXTURE_RULES).graph;
|
|
48
|
+
const store = memoryFactStore();
|
|
49
|
+
await saveFactGraph(store, graph);
|
|
50
|
+
const sorted = [...graph.objects.keys()].sort();
|
|
51
|
+
const gone = sorted[sorted.length - 1]!;
|
|
52
|
+
const port: FactStorePort = {
|
|
53
|
+
...store,
|
|
54
|
+
getObjects: async (hashes) => {
|
|
55
|
+
const got = new Map(await store.getObjects(hashes));
|
|
56
|
+
got.delete(gone);
|
|
57
|
+
return got;
|
|
58
|
+
},
|
|
59
|
+
};
|
|
60
|
+
await expect(loadFactGraph(port, { verify: 'manifest' })).rejects.toThrow(`fact_store_object_missing:${gone}`);
|
|
61
|
+
});
|
|
62
|
+
});
|
|
@@ -0,0 +1,116 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* src/contract/regression.ignoreMatcher.test.ts — the memoized `ignoreMatcher` answers exactly as the algorithm it replaced.
|
|
3
|
+
*
|
|
4
|
+
* Before: for every path the matcher built every ancestor folder and tested EVERY rule against every ancestor (and the
|
|
5
|
+
* path): O(files × rules × depth) regex tests on the VS Code extension host's main thread, which a 34k-file multi-repo
|
|
6
|
+
* tree (every nested `.gitignore` adds its rules) stalled for seconds. The reference below IS that algorithm, kept
|
|
7
|
+
* verbatim, and is the oracle over a randomized tree with many nested `.gitignore` bases.
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
import { ignoreMatcher } from '../knowledge/sources.js';
|
|
11
|
+
import { matchGlob } from '../knowledge/partitions.js';
|
|
12
|
+
|
|
13
|
+
const DEFAULT_IGNORES = ['.git/', 'node_modules/', '.builderforce/', '.gitignore', '*.lock'];
|
|
14
|
+
|
|
15
|
+
/** The matcher as it was before the memoization (sources.ts, 2026-11-14), verbatim. */
|
|
16
|
+
function referenceMatcher(texts: ReadonlyArray<string | { text: string; base: string }>): (path: string) => boolean {
|
|
17
|
+
const rules: Array<{ glob: string; negate: boolean; dirOnly: boolean }> = [];
|
|
18
|
+
const lines = [
|
|
19
|
+
...DEFAULT_IGNORES.map((line) => ({ line, base: '' })),
|
|
20
|
+
...texts.flatMap((t) => {
|
|
21
|
+
const { text, base } = typeof t === 'string' ? { text: t, base: '' } : t;
|
|
22
|
+
return text.split(/\r?\n/).map((line) => ({ line, base }));
|
|
23
|
+
}),
|
|
24
|
+
];
|
|
25
|
+
for (const { line, base } of lines) {
|
|
26
|
+
let p = line.replace(/\s+$/, '');
|
|
27
|
+
if (!p || p.startsWith('#')) continue;
|
|
28
|
+
const negate = p.startsWith('!');
|
|
29
|
+
if (negate) p = p.slice(1);
|
|
30
|
+
const dirOnly = p.endsWith('/');
|
|
31
|
+
if (dirOnly) p = p.slice(0, -1);
|
|
32
|
+
const anchored = p.includes('/');
|
|
33
|
+
p = p.replace(/^\//, '');
|
|
34
|
+
const prefix = base ? `${base}/` : '';
|
|
35
|
+
if (p) rules.push({ glob: anchored ? `${prefix}${p}` : `${prefix}**/${p}`, negate, dirOnly });
|
|
36
|
+
}
|
|
37
|
+
return (path) => {
|
|
38
|
+
const segments = path.split('/');
|
|
39
|
+
const dirs = segments.slice(0, -1).map((_, i) => segments.slice(0, i + 1).join('/'));
|
|
40
|
+
let ignored = false;
|
|
41
|
+
for (const r of rules) {
|
|
42
|
+
const hit = (r.dirOnly ? dirs : [...dirs, path]).some((c) => matchGlob(c, r.glob));
|
|
43
|
+
if (hit) ignored = !r.negate;
|
|
44
|
+
}
|
|
45
|
+
return ignored;
|
|
46
|
+
};
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/** A small deterministic PRNG (mulberry32), so a failure reproduces. */
|
|
50
|
+
function rng(seed: number): () => number {
|
|
51
|
+
let a = seed >>> 0;
|
|
52
|
+
return () => {
|
|
53
|
+
a = (a + 0x6d2b79f5) >>> 0;
|
|
54
|
+
let t = a;
|
|
55
|
+
t = Math.imul(t ^ (t >>> 15), t | 1);
|
|
56
|
+
t ^= t + Math.imul(t ^ (t >>> 7), t | 61);
|
|
57
|
+
return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
|
|
58
|
+
};
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
const SEGMENTS = ['src', 'lib', 'dist', 'build', 'out', 'node_modules', 'docs', 'test', 'tmp', 'cache', 'a', 'b', 'repo1', 'repo2', 'pkg', '.git', 'vendor', 'gen'];
|
|
62
|
+
const FILES = ['index.ts', 'a.md', 'b.js', 'yarn.lock', '.gitignore', 'x.log', 'notes.txt', 'keep.log', 'main.min.js', 'copy*.txt', 'data.json'];
|
|
63
|
+
const PATTERNS = [
|
|
64
|
+
'dist/', 'build', '*.log', '!keep.log', '/out', 'tmp/', '*.min.js', 'cache/**', '!src/keep.log', 'docs/*.md', '!docs/',
|
|
65
|
+
'gen/**/*.ts', '**/vendor', 'a/b', '!a', '*.json', '# a comment', '', 'test/', '!test/index.ts', 'copy\\*.txt', '{a,b}.md',
|
|
66
|
+
'lib/?.js', '!yarn.lock', 'node_modules/', '/src/*.ts', 'pkg/**/b.js',
|
|
67
|
+
];
|
|
68
|
+
|
|
69
|
+
function randomTree(seed: number, opts: { paths: number; bases: number; rulesPerBase: number }) {
|
|
70
|
+
const next = rng(seed);
|
|
71
|
+
const pick = <T>(xs: readonly T[]): T => xs[Math.floor(next() * xs.length)]!;
|
|
72
|
+
const dir = (depth: number) => Array.from({ length: depth }, () => pick(SEGMENTS)).join('/');
|
|
73
|
+
const texts: Array<{ text: string; base: string }> = [];
|
|
74
|
+
for (let i = 0; i < opts.bases; i++) {
|
|
75
|
+
const base = i === 0 ? '' : dir(1 + Math.floor(next() * 4));
|
|
76
|
+
const text = Array.from({ length: opts.rulesPerBase }, () => pick(PATTERNS)).join(i % 2 ? '\r\n' : '\n');
|
|
77
|
+
texts.push({ text, base });
|
|
78
|
+
}
|
|
79
|
+
const paths = Array.from({ length: opts.paths }, () => {
|
|
80
|
+
const depth = Math.floor(next() * 7);
|
|
81
|
+
return depth === 0 ? pick(FILES) : `${dir(depth)}/${pick(FILES)}`;
|
|
82
|
+
});
|
|
83
|
+
return { texts, paths };
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
describe('regression: ignoreMatcher memoization', () => {
|
|
87
|
+
it('regression: answers exactly as the unmemoized matcher over a randomized tree with many nested .gitignore bases', () => {
|
|
88
|
+
for (const seed of [1, 2, 3, 42, 1337]) {
|
|
89
|
+
const { texts, paths } = randomTree(seed, { paths: 2000, bases: 40, rulesPerBase: 8 });
|
|
90
|
+
const fast = ignoreMatcher(texts);
|
|
91
|
+
const ref = referenceMatcher(texts);
|
|
92
|
+
const mismatches = paths.filter((p) => fast(p) !== ref(p));
|
|
93
|
+
expect(mismatches).toEqual([]);
|
|
94
|
+
// Both outcomes occur, so the comparison is not vacuous.
|
|
95
|
+
expect(new Set(paths.map(ref)).size).toBe(2);
|
|
96
|
+
// Asking again (served from the folder memo) changes nothing.
|
|
97
|
+
expect(paths.filter((p) => fast(p) !== ref(p))).toEqual([]);
|
|
98
|
+
}
|
|
99
|
+
// Plain string texts (base ''), and degenerate paths.
|
|
100
|
+
const plain = ['dist/\n!keep.log', '*.log'];
|
|
101
|
+
const paths = ['dist/a.log', 'src/keep.log', 'a/dist/x.ts', 'x.log', 'dist', 'keep.log', '', '/abs/x.log', 'a//b.log'];
|
|
102
|
+
expect(paths.map(ignoreMatcher(plain))).toEqual(paths.map(referenceMatcher(plain)));
|
|
103
|
+
});
|
|
104
|
+
|
|
105
|
+
it('perf guard: 30k paths × 300 rules finishes well within a few seconds', () => {
|
|
106
|
+
const { texts, paths } = randomTree(7, { paths: 30_000, bases: 60, rulesPerBase: 5 }); // ≈300 rules with the defaults
|
|
107
|
+
const fast = ignoreMatcher(texts);
|
|
108
|
+
const start = performance.now();
|
|
109
|
+
let ignored = 0;
|
|
110
|
+
for (const p of paths) if (fast(p)) ignored++;
|
|
111
|
+
const ms = performance.now() - start;
|
|
112
|
+
expect(ignored).toBeGreaterThan(0);
|
|
113
|
+
// Measured 2026-11-14 on this shape (folders nearly all distinct, the memo's worst case): the reference ≈4.6 s, this ≈0.2 s.
|
|
114
|
+
expect(ms).toBeLessThan(2000);
|
|
115
|
+
});
|
|
116
|
+
});
|
|
@@ -22,7 +22,7 @@ describe('regression: a host listing cannot break the plan', () => {
|
|
|
22
22
|
expect(detail.files.map((f) => f.path)).toEqual([NFC, 'ok.md']);
|
|
23
23
|
expect(detail.files[0]!.listedPath).toBe(NFD); // the first by (normalized, listed) bytewise
|
|
24
24
|
expect(detail.plan.skipped).toContainEqual({ path: NFC, reason: 'duplicate-path' });
|
|
25
|
-
expect(detail.plan.merkleRoot).toBe(merkleTree(detail.files).root);
|
|
25
|
+
expect(detail.plan.merkleRoot).toBe((await merkleTree(detail.files)).root);
|
|
26
26
|
});
|
|
27
27
|
|
|
28
28
|
it('regression: a `.`/`..` path or a path listed twice is skipped with a reason, never thrown', async () => {
|
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* src/contract/regression.merkleCooperative.test.ts — merkleTree, canonicalListing and changedPaths became async and
|
|
3
|
+
* cooperative (they yield to the event loop on a work budget). A yield must never change a result: a run that pauses at
|
|
4
|
+
* every check equals a run that never pauses. The root of a small fixed listing is pinned as a literal, so any future
|
|
5
|
+
* change to hashing or ordering fails loudly here.
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
import type { CooperativeBudget } from '../knowledge/cooperative.js';
|
|
9
|
+
import { canonicalListing, changedPaths, merkleTree } from '../knowledge/merkle.js';
|
|
10
|
+
|
|
11
|
+
/** Always due: the loops pause at every check. */
|
|
12
|
+
const forced = (): CooperativeBudget & { pauses: number } => {
|
|
13
|
+
const b = { pauses: 0, due: () => true, pause: async () => { b.pauses++; await Promise.resolve(); } };
|
|
14
|
+
return b;
|
|
15
|
+
};
|
|
16
|
+
/** Never due: the loops run straight through. */
|
|
17
|
+
const unforced = (): CooperativeBudget => ({ due: () => false, pause: async () => { throw new Error('unforced budget paused'); } });
|
|
18
|
+
|
|
19
|
+
const hex = (n: number) => n.toString(16).padStart(64, '0');
|
|
20
|
+
|
|
21
|
+
/** ~8k paths across nested directories, listed out of order, with re-spelled, invalid and duplicate entries mixed in. */
|
|
22
|
+
const LARGE: Array<{ path: string; hash: string }> = (() => {
|
|
23
|
+
const out: Array<{ path: string; hash: string }> = [];
|
|
24
|
+
for (let i = 0; i < 8000; i++) out.push({ path: `d${i % 13}/s${i % 7}/t${i % 5}/f${i}.ts`, hash: hex(i) });
|
|
25
|
+
out.reverse();
|
|
26
|
+
out.push({ path: './d0/dup.ts', hash: hex(1) }, { path: 'd0/dup.ts', hash: hex(2) }, { path: '../up.ts', hash: hex(3) }, { path: 'd1/./x.ts', hash: hex(4) });
|
|
27
|
+
return out;
|
|
28
|
+
})();
|
|
29
|
+
|
|
30
|
+
/** LARGE with some files changed, one removed and one added. */
|
|
31
|
+
const LARGE_AFTER = LARGE.filter((f) => f.path !== 'd3/s3/t3/f3.ts')
|
|
32
|
+
.map((f) => (f.path.endsWith('7.ts') ? { ...f, hash: hex(1_000_000 + Number.parseInt(f.hash, 16)) } : f))
|
|
33
|
+
.concat({ path: 'new/added.ts', hash: hex(42) });
|
|
34
|
+
|
|
35
|
+
describe('regression: cooperative merkle yields never change a result', () => {
|
|
36
|
+
it('regression: a budget that is always due pauses, and canonicalListing / merkleTree / changedPaths equal the unforced run', async () => {
|
|
37
|
+
const budget = forced();
|
|
38
|
+
|
|
39
|
+
const listForced = await canonicalListing(LARGE, { budget });
|
|
40
|
+
const listPlain = await canonicalListing(LARGE, { budget: unforced() });
|
|
41
|
+
expect(listForced).toEqual(listPlain);
|
|
42
|
+
expect(listPlain.skipped.length).toBeGreaterThan(0);
|
|
43
|
+
|
|
44
|
+
const afterForced = await canonicalListing(LARGE_AFTER, { budget });
|
|
45
|
+
const afterPlain = await canonicalListing(LARGE_AFTER, { budget: unforced() });
|
|
46
|
+
expect(afterForced).toEqual(afterPlain);
|
|
47
|
+
|
|
48
|
+
const beforeTreeForced = await merkleTree(listForced.kept, { budget });
|
|
49
|
+
const beforeTreePlain = await merkleTree(listPlain.kept, { budget: unforced() });
|
|
50
|
+
const afterTreeForced = await merkleTree(afterForced.kept, { budget });
|
|
51
|
+
const afterTreePlain = await merkleTree(afterPlain.kept, { budget: unforced() });
|
|
52
|
+
expect(beforeTreeForced.root).toBe(beforeTreePlain.root);
|
|
53
|
+
expect(afterTreeForced.root).toBe(afterTreePlain.root);
|
|
54
|
+
expect(beforeTreeForced.dirs).toEqual(beforeTreePlain.dirs);
|
|
55
|
+
expect(beforeTreeForced.entries).toEqual(beforeTreePlain.entries);
|
|
56
|
+
|
|
57
|
+
const changedForced = await changedPaths(beforeTreeForced, afterTreeForced, { budget });
|
|
58
|
+
const changedPlain = await changedPaths(beforeTreePlain, afterTreePlain, { budget: unforced() });
|
|
59
|
+
expect(changedForced).toEqual(changedPlain);
|
|
60
|
+
expect(changedPlain).toContain('d3/s3/t3/f3.ts');
|
|
61
|
+
expect(changedPlain).toContain('new/added.ts');
|
|
62
|
+
expect(changedPlain).toContain('d7/s0/t2/f7.ts');
|
|
63
|
+
|
|
64
|
+
expect(budget.pauses).toBeGreaterThan(0);
|
|
65
|
+
});
|
|
66
|
+
|
|
67
|
+
it('regression: the root of a small fixed listing is pinned (hashing and ordering are frozen)', async () => {
|
|
68
|
+
const FILES = [
|
|
69
|
+
{ path: 'README.md', hash: hex(1) },
|
|
70
|
+
{ path: 'src/index.ts', hash: hex(2) },
|
|
71
|
+
{ path: 'src/lib/util.ts', hash: hex(3) },
|
|
72
|
+
{ path: 'src/lib/zeta.ts', hash: hex(4) },
|
|
73
|
+
{ path: 'docs/guide.md', hash: hex(5) },
|
|
74
|
+
];
|
|
75
|
+
const root = '0e62f74f5b92a6d4723875995eba326617d27e27b7a55db60a84d1051ab1deb4';
|
|
76
|
+
expect((await merkleTree(FILES)).root).toBe(root);
|
|
77
|
+
expect((await merkleTree([...FILES].reverse(), { budget: forced() })).root).toBe(root);
|
|
78
|
+
});
|
|
79
|
+
});
|
|
@@ -12,7 +12,7 @@
|
|
|
12
12
|
*/
|
|
13
13
|
|
|
14
14
|
import type { ParsedSection, SourceDocument } from '../ingest/types.js';
|
|
15
|
-
import type { changedPaths, contentHash, CONTENT_HASH_RULE, merkleTree, MerkleEntry, MerkleTree, PlanDetail, ReviewPlan } from '../knowledge/index.js';
|
|
15
|
+
import type { changedPaths, contentHash, CONTENT_HASH_RULE, merkleTree, MerkleEntry, MerkleOptions, MerkleTree, PlanDetail, ReviewPlan } from '../knowledge/index.js';
|
|
16
16
|
import type { BASELINE_CONTENT_HASH_RULE, canonicalListing, contentHashRuleOf, ListingSkipReason } from '../knowledge/index.js';
|
|
17
17
|
import type {
|
|
18
18
|
DirectorySource, Extracted, ExtractJob, ExtractJobResult, GraphApp, GraphOutline, GraphReadSkip, GraphSystem, KEdge, KNode, KnowledgeGraph, KnowledgeStore,
|
|
@@ -158,8 +158,8 @@ export type MerkleEntry_shape = Expect<Equal<MerkleEntry, { name: string; kind:
|
|
|
158
158
|
export type MerkleTree_shape = Expect<Equal<MerkleTree, {
|
|
159
159
|
root: string; dirs: ReadonlyMap<string, string>; entries: ReadonlyMap<string, ReadonlyArray<MerkleEntry>>;
|
|
160
160
|
}>>;
|
|
161
|
-
export type merkleTree_signature = Expect<Equal<typeof merkleTree, (files: ReadonlyArray<{ path: string; hash: string }
|
|
162
|
-
export type changedPaths_signature = Expect<Equal<typeof changedPaths, (before: MerkleTree, after: MerkleTree) => string[]
|
|
161
|
+
export type merkleTree_signature = Expect<Equal<typeof merkleTree, (files: ReadonlyArray<{ path: string; hash: string }>, opts?: MerkleOptions) => Promise<MerkleTree>>>;
|
|
162
|
+
export type changedPaths_signature = Expect<Equal<typeof changedPaths, (before: MerkleTree, after: MerkleTree, opts?: MerkleOptions) => Promise<string[]>>>;
|
|
163
163
|
export type ReviewPlan_merkleRoot = Expect<Equal<ReviewPlan['merkleRoot'], string | undefined>>;
|
|
164
164
|
export type PlanDetail_merkle = Expect<Equal<PlanDetail['merkle'], MerkleTree | undefined>>;
|
|
165
165
|
export type BASELINE_CONTENT_HASH_RULE_type = Expect<Equal<typeof BASELINE_CONTENT_HASH_RULE, 'eol-lf@1'>>;
|
|
@@ -170,9 +170,13 @@ export type ReviewPlan_skipped_reason = Expect<Equal<
|
|
|
170
170
|
>>;
|
|
171
171
|
export type PlannedFile_listedPath = Expect<Equal<PlannedFile['listedPath'], string | undefined>>;
|
|
172
172
|
export type canonicalListing_skipped = Expect<Equal<
|
|
173
|
-
ReturnType<typeof canonicalListing<{ path: string }
|
|
173
|
+
Awaited<ReturnType<typeof canonicalListing<{ path: string }>>>['skipped'], Array<{ path: string; reason: ListingSkipReason }>
|
|
174
174
|
>>;
|
|
175
|
-
export type
|
|
175
|
+
export type canonicalListing_signature = Expect<Equal<typeof canonicalListing, <T extends { path: string }>(entries: readonly T[], opts?: MerkleOptions) => Promise<{
|
|
176
|
+
kept: Array<T & { listedPath?: string }>;
|
|
177
|
+
skipped: Array<{ path: string; reason: ListingSkipReason }>;
|
|
178
|
+
}>>>;
|
|
179
|
+
export type ListingSkipReason_values =Expect<Equal<ListingSkipReason, 'invalid-path' | 'duplicate-path'>>;
|
|
176
180
|
|
|
177
181
|
/* ── DirectorySource: optional per-path hooks ──────────────────────────────────────────────────────────────── */
|
|
178
182
|
// hashOf takes the path (a host whose read() transforms bytes returns the listing hash for it); a one-argument hashOf still satisfies it.
|
package/src/knowledge/build.ts
CHANGED
|
@@ -36,6 +36,7 @@ import {
|
|
|
36
36
|
} from './refs.js';
|
|
37
37
|
import { buildOutline } from './outline.js';
|
|
38
38
|
import { truncateGraph } from './truncate.js';
|
|
39
|
+
import { LINKABLE_DOC_EXT } from './sources.js';
|
|
39
40
|
|
|
40
41
|
export const DEFAULT_MAX_NODES = 400;
|
|
41
42
|
export const MAX_NODES_CAP = 2000;
|
|
@@ -268,19 +269,47 @@ function repointByName(e: KEdge, rootId: string, resolve: (name: string) => stri
|
|
|
268
269
|
return fileRefOf(e.from) === to ? null : { ...edge, to };
|
|
269
270
|
}
|
|
270
271
|
|
|
271
|
-
/**
|
|
272
|
+
/**
|
|
273
|
+
* A missing `src:` endpoint becomes a `missing` placeholder (a broken link); a missing fact drops the edge.
|
|
274
|
+
* A `links` target with no file of its own name is resolved against the files present NOW — an extensionless
|
|
275
|
+
* document target may name a sibling file like `troubleshooting.md`: an extract is cached, so it must record
|
|
276
|
+
* the written target, but whether the file exists is decided here. (The docs pack's broken-link rule only
|
|
277
|
+
* judges extensionless/document targets, so those are the only ones resolved.)
|
|
278
|
+
*/
|
|
272
279
|
function closeEndpoints(g: GraphBuilder): void {
|
|
280
|
+
const byFolderExt = new Map<string, NodeRef>();
|
|
281
|
+
for (const n of g.nodes.values()) {
|
|
282
|
+
if (n.kind !== 'file') continue;
|
|
283
|
+
const path = pathOfRef(n.ref);
|
|
284
|
+
if (path === undefined || path.startsWith('../')) continue;
|
|
285
|
+
const slash = path.lastIndexOf('/');
|
|
286
|
+
const folder = slash === -1 ? '' : path.slice(0, slash + 1);
|
|
287
|
+
const dot = path.lastIndexOf('.');
|
|
288
|
+
if (dot === -1 || dot < slash + 1) continue;
|
|
289
|
+
for (const ext of LINKABLE_DOC_EXT) {
|
|
290
|
+
if (ext === path.slice(dot + 1).toLowerCase()) { byFolderExt.set(folder + path.slice(slash + 1, dot), n.ref); break; }
|
|
291
|
+
}
|
|
292
|
+
}
|
|
273
293
|
for (const [id, e] of [...g.edges.entries()].sort((a, b) => compareStr(a[0], b[0]))) {
|
|
274
|
-
const
|
|
294
|
+
const { from } = e;
|
|
295
|
+
let { to } = e;
|
|
296
|
+
// An extensionless `links` target may name an existing sibling document; otherwise a placeholder is fabricated below.
|
|
297
|
+
if (e.kind === 'links' && !g.nodes.has(to)) {
|
|
298
|
+
const path = pathOfRef(to);
|
|
299
|
+
const resolved = path === undefined ? undefined : byFolderExt.get(path);
|
|
300
|
+
if (resolved !== undefined) to = resolved;
|
|
301
|
+
}
|
|
302
|
+
const ends = [from, to].filter((end) => !g.nodes.has(end));
|
|
275
303
|
if (ends.some((end) => pathOfRef(end) === undefined)) { g.edges.delete(id); continue; }
|
|
276
304
|
for (const end of ends) {
|
|
277
305
|
const path = pathOfRef(end)!;
|
|
278
|
-
const other = g.nodes.get(end ===
|
|
306
|
+
const other = g.nodes.get(end === from ? to : from);
|
|
279
307
|
g.node({
|
|
280
308
|
ref: end, kind: 'missing', label: basenameOf(path) || path, pack: other?.pack ?? FALLBACK_PACK_ID,
|
|
281
309
|
importance: 0, origin: 'extracted', badges: { missing: 1 },
|
|
282
310
|
});
|
|
283
311
|
}
|
|
312
|
+
if (to !== e.to) g.edges.set(id, { ...e, to });
|
|
284
313
|
}
|
|
285
314
|
}
|
|
286
315
|
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* src/knowledge/cooperative.test.ts — the yield is chosen once, in order setImmediate > scheduler.yield > MessageChannel >
|
|
3
|
+
* setTimeout, from functions captured at pick time (fake timers installed later never reach it).
|
|
4
|
+
*/
|
|
5
|
+
|
|
6
|
+
import { jest } from '@jest/globals';
|
|
7
|
+
import { cooperativeBudget, pickYield, yieldToEventLoop, type YieldHost } from './cooperative.js';
|
|
8
|
+
|
|
9
|
+
/** A MessageChannel stand-in that delivers on a real immediate, and counts posts. */
|
|
10
|
+
function fakeChannel(posts: { n: number }): YieldHost['MessageChannel'] {
|
|
11
|
+
return class {
|
|
12
|
+
port1: { onmessage: ((ev: unknown) => void) | null } = { onmessage: null };
|
|
13
|
+
port2 = { postMessage: (_: unknown) => { posts.n++; setImmediate(() => this.port1.onmessage?.({})); } };
|
|
14
|
+
};
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
describe('cooperative yield selection', () => {
|
|
18
|
+
it('prefers setImmediate, then scheduler.yield, then MessageChannel, then setTimeout', () => {
|
|
19
|
+
const timeout = (fn: () => void) => setTimeout(fn, 0);
|
|
20
|
+
const posts = { n: 0 };
|
|
21
|
+
const all: YieldHost = { setImmediate, scheduler: { yield: async () => undefined }, MessageChannel: fakeChannel(posts), setTimeout: timeout };
|
|
22
|
+
expect(pickYield(all).kind).toBe('setImmediate');
|
|
23
|
+
expect(pickYield({ ...all, setImmediate: undefined }).kind).toBe('scheduler.yield');
|
|
24
|
+
expect(pickYield({ ...all, setImmediate: undefined, scheduler: {} }).kind).toBe('MessageChannel');
|
|
25
|
+
expect(pickYield({ setTimeout: timeout }).kind).toBe('setTimeout');
|
|
26
|
+
});
|
|
27
|
+
|
|
28
|
+
it('the MessageChannel fallback resolves each yield, in order', async () => {
|
|
29
|
+
const posts = { n: 0 };
|
|
30
|
+
const { yield: y } = pickYield({ MessageChannel: fakeChannel(posts) });
|
|
31
|
+
const order: number[] = [];
|
|
32
|
+
await Promise.all([y().then(() => order.push(1)), y().then(() => order.push(2))]);
|
|
33
|
+
expect(order).toEqual([1, 2]);
|
|
34
|
+
expect(posts.n).toBe(2);
|
|
35
|
+
});
|
|
36
|
+
|
|
37
|
+
it('the setTimeout fallback is captured at pick time: replacing the host timer afterwards does not reach it', async () => {
|
|
38
|
+
let used = 0;
|
|
39
|
+
const host: YieldHost = { setTimeout: (fn) => { used++; return setTimeout(fn, 0); } };
|
|
40
|
+
const { yield: y } = pickYield(host);
|
|
41
|
+
host.setTimeout = () => { throw new Error('a later (fake) timer was used'); };
|
|
42
|
+
await y();
|
|
43
|
+
expect(used).toBe(1);
|
|
44
|
+
});
|
|
45
|
+
|
|
46
|
+
it('fake timers installed after load do not stall the module yield or the budget', async () => {
|
|
47
|
+
jest.useFakeTimers();
|
|
48
|
+
try {
|
|
49
|
+
await yieldToEventLoop();
|
|
50
|
+
const budget = cooperativeBudget(0);
|
|
51
|
+
expect(budget.due()).toBe(true);
|
|
52
|
+
await budget.pause();
|
|
53
|
+
} finally {
|
|
54
|
+
jest.useRealTimers();
|
|
55
|
+
}
|
|
56
|
+
});
|
|
57
|
+
});
|
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* knowledge/cooperative.ts — THE cooperative-yield helper of long synchronous loops (the plan's walk, the fact store's load).
|
|
3
|
+
*
|
|
4
|
+
* A host may run a review on its UI thread (the VS Code extension host does): a loop over tens of thousands of files must
|
|
5
|
+
* hand the event loop back every few milliseconds or the host stalls. {@link cooperativeBudget} times the work since the
|
|
6
|
+
* last yield and {@link yieldToEventLoop} returns to the event loop (a macrotask, so I/O and input run in between).
|
|
7
|
+
*
|
|
8
|
+
* Portable: `setImmediate`, `scheduler.yield`, a `MessageChannel` or `setTimeout(0)` ({@link pickYield}) and
|
|
9
|
+
* `performance.now()` — Node, browsers and Workers alike. All are captured when the module loads, so a test's fake timers
|
|
10
|
+
* never stall a yield.
|
|
11
|
+
*/
|
|
12
|
+
|
|
13
|
+
/** Default work budget between two yields, in ms. */
|
|
14
|
+
export const COOPERATIVE_BUDGET_MS = 12;
|
|
15
|
+
|
|
16
|
+
/** The host globals the yield may use. */
|
|
17
|
+
export interface YieldHost {
|
|
18
|
+
setImmediate?: (fn: () => void) => unknown;
|
|
19
|
+
scheduler?: { yield?: () => Promise<void> };
|
|
20
|
+
MessageChannel?: new () => { port1: { onmessage: ((ev: unknown) => void) | null }; port2: { postMessage(msg: unknown): void } };
|
|
21
|
+
setTimeout?: (fn: () => void, ms?: number) => unknown;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
export type YieldKind = 'setImmediate' | 'scheduler.yield' | 'MessageChannel' | 'setTimeout';
|
|
25
|
+
|
|
26
|
+
/**
|
|
27
|
+
* THE choice of how to return to the event loop, made ONCE (at module load for `globalThis`): `setImmediate` (Node), else
|
|
28
|
+
* `scheduler.yield` (Chromium), else a `MessageChannel` message (browsers, Workers — a hidden tab throttles `setTimeout(0)` to
|
|
29
|
+
* ≥ 1 s, a message is not throttled), else `setTimeout(0)`. Every function is captured here, so fake timers installed later
|
|
30
|
+
* never reach it.
|
|
31
|
+
*/
|
|
32
|
+
export function pickYield(host: YieldHost): { kind: YieldKind; yield: () => Promise<void> } {
|
|
33
|
+
const immediate = host.setImmediate;
|
|
34
|
+
if (typeof immediate === 'function') return { kind: 'setImmediate', yield: () => new Promise((r) => { immediate.call(host, r); }) };
|
|
35
|
+
const scheduler = host.scheduler;
|
|
36
|
+
const schedulerYield = scheduler?.yield;
|
|
37
|
+
if (typeof schedulerYield === 'function') return { kind: 'scheduler.yield', yield: () => schedulerYield.call(scheduler) };
|
|
38
|
+
if (typeof host.MessageChannel === 'function') {
|
|
39
|
+
const channel = new host.MessageChannel();
|
|
40
|
+
const waiting: Array<() => void> = [];
|
|
41
|
+
channel.port1.onmessage = () => { waiting.shift()?.(); };
|
|
42
|
+
return { kind: 'MessageChannel', yield: () => new Promise((r) => { waiting.push(r); channel.port2.postMessage(0); }) };
|
|
43
|
+
}
|
|
44
|
+
const timeout = host.setTimeout;
|
|
45
|
+
if (typeof timeout === 'function') return { kind: 'setTimeout', yield: () => new Promise((r) => { timeout.call(host, r, 0); }) };
|
|
46
|
+
// No timer at all: a resolved promise still lets other microtasks run.
|
|
47
|
+
return { kind: 'setTimeout', yield: () => Promise.resolve() };
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
const g = globalThis as YieldHost & { performance?: { now(): number } };
|
|
51
|
+
const picked = pickYield(g);
|
|
52
|
+
const clock: () => number = g.performance && typeof g.performance.now === 'function' ? g.performance.now.bind(g.performance) : Date.now;
|
|
53
|
+
|
|
54
|
+
/** Returns to the event loop once (one macrotask). */
|
|
55
|
+
export function yieldToEventLoop(): Promise<void> {
|
|
56
|
+
return picked.yield();
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
export interface CooperativeBudget {
|
|
60
|
+
/** Whether the work since the last yield exceeded the budget (cheap: one clock read). */
|
|
61
|
+
due(): boolean;
|
|
62
|
+
/** Yields to the event loop and restarts the budget. */
|
|
63
|
+
pause(): Promise<void>;
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/** A work budget: `if (budget.due()) await budget.pause();` inside a long loop. */
|
|
67
|
+
export function cooperativeBudget(budgetMs = COOPERATIVE_BUDGET_MS): CooperativeBudget {
|
|
68
|
+
let since = clock();
|
|
69
|
+
return {
|
|
70
|
+
due: () => clock() - since >= budgetMs,
|
|
71
|
+
pause: async () => {
|
|
72
|
+
await yieldToEventLoop();
|
|
73
|
+
since = clock();
|
|
74
|
+
},
|
|
75
|
+
};
|
|
76
|
+
}
|
|
@@ -119,3 +119,33 @@ describe('docs findings and cards', () => {
|
|
|
119
119
|
expect(setup.hash).toMatch(/^[0-9a-f]{64}$/);
|
|
120
120
|
});
|
|
121
121
|
});
|
|
122
|
+
|
|
123
|
+
describe('extensionless link resolution (build time)', () => {
|
|
124
|
+
const LINK_FILES: Record<string, string> = {
|
|
125
|
+
'gateway/index.md': '# Gateway\n\nSee [trouble](/gateway/troubleshooting), [rel](./authentication) and [gone](/gateway/nope).\n',
|
|
126
|
+
'gateway/troubleshooting.md': '# Trouble\n\nx\n',
|
|
127
|
+
'gateway/authentication.md': '# Auth\n\ny\n',
|
|
128
|
+
};
|
|
129
|
+
const linkSource = (path: string): SourceDocument =>
|
|
130
|
+
asPathSource({ id: path, tenantId: 't', content: { kind: 'text', text: LINK_FILES[path]! } }, path, `h:${path}`);
|
|
131
|
+
const linkExtract = (path: string): Extracted => {
|
|
132
|
+
const src = linkSource(path);
|
|
133
|
+
return markdownParser.extract!(src, markdownParser.parse(src), ctx);
|
|
134
|
+
};
|
|
135
|
+
const lg = buildGraph({ rootId: ROOT, extracted: Object.keys(LINK_FILES).map(linkExtract), facts: [], relations: [], packs: [DOCS_PACK] });
|
|
136
|
+
|
|
137
|
+
it('resolves an extensionless link to the existing sibling document, not a missing placeholder', () => {
|
|
138
|
+
expect(lg.nodes.some((n) => n.kind === 'missing' && n.ref === ref('gateway/troubleshooting'))).toBe(false);
|
|
139
|
+
expect(lg.nodes.some((n) => n.kind === 'missing' && n.ref === ref('gateway/authentication'))).toBe(false);
|
|
140
|
+
// the links edge now targets the real .md file node, in the same folder as the written target
|
|
141
|
+
expect(lg.edges.some((e) => e.kind === 'links' && e.to === ref('gateway/troubleshooting.md'))).toBe(true);
|
|
142
|
+
expect(lg.edges.some((e) => e.kind === 'links' && e.to === ref('gateway/authentication.md'))).toBe(true);
|
|
143
|
+
});
|
|
144
|
+
|
|
145
|
+
it('still reports a link with no matching file as broken', () => {
|
|
146
|
+
expect(lg.nodes.find((n) => n.ref === ref('gateway/nope'))?.kind).toBe('missing');
|
|
147
|
+
const broken = lg.findings.filter((f) => f.kind === 'broken-link');
|
|
148
|
+
expect(broken).toHaveLength(1);
|
|
149
|
+
expect(broken[0]!.nodes).toEqual([ref('gateway/index.md'), ref('gateway/nope')]);
|
|
150
|
+
});
|
|
151
|
+
});
|