@seanhogg/builderforce-memory 2026.10.55 → 2026.10.58
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 +2 -1
- package/dist/knowledge/build.d.ts.map +1 -1
- package/dist/knowledge/build.js +5 -2
- package/dist/knowledge/build.js.map +1 -1
- package/dist/knowledge/communities.d.ts +74 -0
- package/dist/knowledge/communities.d.ts.map +1 -0
- package/dist/knowledge/communities.js +143 -0
- package/dist/knowledge/communities.js.map +1 -0
- package/dist/knowledge/index.d.ts +5 -3
- package/dist/knowledge/index.d.ts.map +1 -1
- package/dist/knowledge/index.js +2 -1
- package/dist/knowledge/index.js.map +1 -1
- package/dist/knowledge/louvain.d.ts +38 -0
- package/dist/knowledge/louvain.d.ts.map +1 -0
- package/dist/knowledge/louvain.js +164 -0
- package/dist/knowledge/louvain.js.map +1 -0
- package/dist/knowledge/model.d.ts +17 -0
- package/dist/knowledge/model.d.ts.map +1 -1
- package/dist/knowledge/outline.d.ts.map +1 -1
- package/dist/knowledge/outline.js +4 -0
- package/dist/knowledge/outline.js.map +1 -1
- package/dist/knowledge/stores/extractLogWriter.d.ts +26 -0
- package/dist/knowledge/stores/extractLogWriter.d.ts.map +1 -0
- package/dist/knowledge/stores/extractLogWriter.js +60 -0
- package/dist/knowledge/stores/extractLogWriter.js.map +1 -0
- package/dist/knowledge/stores/localSnapshotStore.d.ts +48 -39
- package/dist/knowledge/stores/localSnapshotStore.d.ts.map +1 -1
- package/dist/knowledge/stores/localSnapshotStore.js +137 -179
- package/dist/knowledge/stores/localSnapshotStore.js.map +1 -1
- package/dist/knowledge/stores/rowDelta.d.ts +97 -0
- package/dist/knowledge/stores/rowDelta.d.ts.map +1 -0
- package/dist/knowledge/stores/rowDelta.js +141 -0
- package/dist/knowledge/stores/rowDelta.js.map +1 -0
- package/dist/knowledge/stores/rowMemory.d.ts +31 -0
- package/dist/knowledge/stores/rowMemory.d.ts.map +1 -0
- package/dist/knowledge/stores/rowMemory.js +85 -0
- package/dist/knowledge/stores/rowMemory.js.map +1 -0
- package/dist/knowledge/stores/rowSync.d.ts +56 -0
- package/dist/knowledge/stores/rowSync.d.ts.map +1 -0
- package/dist/knowledge/stores/rowSync.js +119 -0
- package/dist/knowledge/stores/rowSync.js.map +1 -0
- package/dist/knowledge/stores/snapshotFormat.d.ts +17 -0
- package/dist/knowledge/stores/snapshotFormat.d.ts.map +1 -1
- package/dist/knowledge/stores/snapshotFormat.js +19 -0
- package/dist/knowledge/stores/snapshotFormat.js.map +1 -1
- package/dist/knowledge/trace.d.ts.map +1 -1
- package/dist/knowledge/trace.js +24 -3
- package/dist/knowledge/trace.js.map +1 -1
- package/package.json +3 -3
- package/src/contract/exports.snapshot.json +10 -0
- package/src/contract/regression.rows.test.ts +377 -0
- package/src/contract/types.contract.test.ts +37 -5
- package/src/knowledge/build.test.ts +1 -1
- package/src/knowledge/build.ts +5 -2
- package/src/knowledge/communities.test.ts +322 -0
- package/src/knowledge/communities.ts +167 -0
- package/src/knowledge/index.ts +10 -3
- package/src/knowledge/louvain.ts +147 -0
- package/src/knowledge/model.ts +21 -1
- package/src/knowledge/outline.test.ts +17 -5
- package/src/knowledge/outline.ts +4 -0
- package/src/knowledge/stores/extractLogWriter.ts +57 -0
- package/src/knowledge/stores/localSnapshotStore.ts +138 -168
- package/src/knowledge/stores/rowDelta.test.ts +91 -0
- package/src/knowledge/stores/rowDelta.ts +166 -0
- package/src/knowledge/stores/rowMemory.ts +82 -0
- package/src/knowledge/stores/rowSync.ts +118 -0
- package/src/knowledge/stores/snapshotFormat.ts +30 -0
- package/src/knowledge/trace.ts +24 -4
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"trace.js","sourceRoot":"","sources":["../../src/knowledge/trace.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;
|
|
1
|
+
{"version":3,"file":"trace.js","sourceRoot":"","sources":["../../src/knowledge/trace.ts"],"names":[],"mappings":"A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AK,CAAC,IAAI,CAAC,IAAI,CAAC,IAAI,CAAC;AACnC,CAAC"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@seanhogg/builderforce-memory",
|
|
3
|
-
"version": "2026.10.
|
|
3
|
+
"version": "2026.10.58",
|
|
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",
|
|
@@ -117,7 +117,7 @@
|
|
|
117
117
|
},
|
|
118
118
|
"homepage": "https://github.com/SeanHogg/builderforce-memory/tree/main/packages/memory#readme",
|
|
119
119
|
"peerDependencies": {
|
|
120
|
-
"@seanhogg/builderforce-memory-engine": "^2026.10.
|
|
120
|
+
"@seanhogg/builderforce-memory-engine": "^2026.10.58"
|
|
121
121
|
},
|
|
122
122
|
"devDependencies": {
|
|
123
123
|
"@jest/globals": "^29.7.0",
|
|
@@ -131,7 +131,7 @@
|
|
|
131
131
|
"ts-jest": "^29.2.0",
|
|
132
132
|
"typescript": "npm:@typescript/typescript6@^6.0.2",
|
|
133
133
|
"typescript-7": "npm:typescript@^7.0.2",
|
|
134
|
-
"@seanhogg/builderforce-memory-engine": "2026.10.
|
|
134
|
+
"@seanhogg/builderforce-memory-engine": "2026.10.58"
|
|
135
135
|
},
|
|
136
136
|
"jest": {
|
|
137
137
|
"preset": "ts-jest/presets/default-esm",
|
|
@@ -267,6 +267,11 @@
|
|
|
267
267
|
"./knowledge": [
|
|
268
268
|
"AVG_SECTION_BYTES",
|
|
269
269
|
"CLONE_GROUP_BADGE",
|
|
270
|
+
"COMMUNITY_EDGE_KINDS",
|
|
271
|
+
"COMMUNITY_LOUVAIN_MAX_NODES",
|
|
272
|
+
"COMMUNITY_LP_ITERATIONS",
|
|
273
|
+
"COMMUNITY_MAX_ITERATIONS",
|
|
274
|
+
"COMMUNITY_MAX_PASSES",
|
|
270
275
|
"DEFAULT_INDEX_PARAMS",
|
|
271
276
|
"DEFAULT_MAX_FILE_BYTES",
|
|
272
277
|
"DEFAULT_MAX_NODES",
|
|
@@ -307,6 +312,7 @@
|
|
|
307
312
|
"UNANCHORED_AREA",
|
|
308
313
|
"UNPARTITIONED_LANE",
|
|
309
314
|
"aboutTargets",
|
|
315
|
+
"applyCommunities",
|
|
310
316
|
"applyRunEvent",
|
|
311
317
|
"areaImportance",
|
|
312
318
|
"assertStoredBatch",
|
|
@@ -314,10 +320,12 @@
|
|
|
314
320
|
"buildGraph",
|
|
315
321
|
"buildOutline",
|
|
316
322
|
"byImportance",
|
|
323
|
+
"canonicalDump",
|
|
317
324
|
"canonicalJson",
|
|
318
325
|
"clampClaim",
|
|
319
326
|
"clampQuote",
|
|
320
327
|
"codeTokenize",
|
|
328
|
+
"communityTable",
|
|
321
329
|
"compareManifestKey",
|
|
322
330
|
"compareStr",
|
|
323
331
|
"components",
|
|
@@ -327,6 +335,7 @@
|
|
|
327
335
|
"createKnowledgeIndex",
|
|
328
336
|
"createModelLimiter",
|
|
329
337
|
"crossesSystems",
|
|
338
|
+
"detectCommunities",
|
|
330
339
|
"entityKey",
|
|
331
340
|
"entityName",
|
|
332
341
|
"extractFile",
|
|
@@ -375,6 +384,7 @@
|
|
|
375
384
|
"partitionSeverity",
|
|
376
385
|
"pathOfRef",
|
|
377
386
|
"placeInSystem",
|
|
387
|
+
"placementOf",
|
|
378
388
|
"planDetail",
|
|
379
389
|
"planReview",
|
|
380
390
|
"possibleSameFindings",
|
|
@@ -0,0 +1,377 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* src/contract/regression.rows.test.ts — the row-persisted LocalSnapshotStore (PRD 41 B4, G03), each invariant pinned by one
|
|
3
|
+
* test named `regression: <what broke>`. The host here is a fake `RowPersistence`: a map-backed "database" that records every
|
|
4
|
+
* change it is given and can be held, failed, told another writer changed it, or made to return `reloaded`.
|
|
5
|
+
*/
|
|
6
|
+
|
|
7
|
+
import type { Extracted, NodeRef, ScopeRecord, StoredFact, StoredRelation } from '../knowledge/model.js';
|
|
8
|
+
import { canonicalDump, LocalSnapshotStore, type KnowledgeSnapshot, type RowChange, type RowPersistence } from '../knowledge/stores/localSnapshotStore.js';
|
|
9
|
+
import { memPersistence } from '../knowledge/testkit.test-util.js';
|
|
10
|
+
|
|
11
|
+
const SCOPE: ScopeRecord = { rootId: 'a', title: 'A', packs: ['docs'] };
|
|
12
|
+
const fact = (key: string, content = 'c'): StoredFact => ({ key, content, source: 's', importance: 0.5, origin: 'model', fileAnchors: [] });
|
|
13
|
+
const rel = (from: string, to: string, kind: string): StoredRelation => ({ from: from as NodeRef, to: to as NodeRef, kind, weight: 1, origin: 'model', sourceHash: 'h1' });
|
|
14
|
+
const ex = (name: string) => [{ name }] as unknown as Extracted[];
|
|
15
|
+
const deferred = () => { let resolve!: () => void; const promise = new Promise<void>((r) => { resolve = r; }); return { promise, resolve }; };
|
|
16
|
+
const settle = async () => { for (let i = 0; i < 5; i++) await new Promise((r) => setImmediate(r)); };
|
|
17
|
+
|
|
18
|
+
interface Db {
|
|
19
|
+
scopes: Map<string, ScopeRecord>;
|
|
20
|
+
facts: Map<string, StoredFact>;
|
|
21
|
+
relations: Map<string, StoredRelation>;
|
|
22
|
+
extracted: Map<string, Extracted[]>;
|
|
23
|
+
recheck: Set<string>;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
interface FakeRows extends RowPersistence {
|
|
27
|
+
db: Db;
|
|
28
|
+
applies: RowChange[];
|
|
29
|
+
generation: number;
|
|
30
|
+
loads: number;
|
|
31
|
+
checks: number;
|
|
32
|
+
bodyReads: string[];
|
|
33
|
+
/** Holds every `apply` (after recording it) until resolved. */
|
|
34
|
+
hold?: ReturnType<typeof deferred>;
|
|
35
|
+
failNext: number;
|
|
36
|
+
/** Another writer's change: run after an apply merged, its result is returned as `reloaded`. */
|
|
37
|
+
reload?: () => KnowledgeSnapshot;
|
|
38
|
+
/** `changedElsewhere` answers true once. */
|
|
39
|
+
changed: boolean;
|
|
40
|
+
/** `load` leaves extract bodies out (they load lazily). */
|
|
41
|
+
lazyBodies: boolean;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
const fkey = (root: string, key: string) => `${root}\u0000${key}`;
|
|
45
|
+
const rkey = (root: string, from: string, to: string, kind: string) => `${root}\u0000${from}\u0000${to}\u0000${kind}`;
|
|
46
|
+
|
|
47
|
+
function snapshotOf(db: Db, withExtracted = true): KnowledgeSnapshot {
|
|
48
|
+
const facts: Record<string, StoredFact[]> = {};
|
|
49
|
+
const relations: Record<string, StoredRelation[]> = {};
|
|
50
|
+
for (const [k, f] of db.facts) (facts[k.split('\u0000')[0]!] ??= []).push(f);
|
|
51
|
+
for (const [k, r] of db.relations) (relations[k.split('\u0000')[0]!] ??= []).push(r);
|
|
52
|
+
return {
|
|
53
|
+
version: 1, scopes: [...db.scopes.values()], facts, relations,
|
|
54
|
+
...(withExtracted ? { extracted: Object.fromEntries(db.extracted) } : {}),
|
|
55
|
+
...(db.recheck.size ? { recheck: [...db.recheck] } : {}),
|
|
56
|
+
};
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
function fakeRows(): FakeRows {
|
|
60
|
+
const db: Db = { scopes: new Map(), facts: new Map(), relations: new Map(), extracted: new Map(), recheck: new Set() };
|
|
61
|
+
const f: FakeRows = {
|
|
62
|
+
db, applies: [], generation: 0, loads: 0, checks: 0, bodyReads: [], failNext: 0, changed: false, lazyBodies: false,
|
|
63
|
+
async load() { f.loads += 1; return snapshotOf(db, !f.lazyBodies); },
|
|
64
|
+
async apply(change) {
|
|
65
|
+
f.applies.push(change);
|
|
66
|
+
if (f.hold) await f.hold.promise;
|
|
67
|
+
if (f.failNext > 0) { f.failNext -= 1; throw new Error('disk full'); }
|
|
68
|
+
const { upserts: u, deletes: d } = change;
|
|
69
|
+
for (const s of u.scopes) db.scopes.set(s.rootId, s);
|
|
70
|
+
for (const [root, x] of u.facts) db.facts.set(fkey(root, x.key), x);
|
|
71
|
+
for (const [root, r] of u.relations) db.relations.set(rkey(root, r.from, r.to, r.kind), r);
|
|
72
|
+
for (const [h, e] of u.extracted) db.extracted.set(h, e);
|
|
73
|
+
for (const h of u.recheck) db.recheck.add(h);
|
|
74
|
+
for (const id of d.scopes) db.scopes.delete(id);
|
|
75
|
+
for (const [root, key] of d.facts) db.facts.delete(fkey(root, key));
|
|
76
|
+
for (const [root, from, to, kind] of d.relations) db.relations.delete(rkey(root, from, to, kind));
|
|
77
|
+
for (const h of d.extracted) db.extracted.delete(h);
|
|
78
|
+
for (const h of d.recheck) db.recheck.delete(h);
|
|
79
|
+
f.generation += 1;
|
|
80
|
+
const reload = f.reload;
|
|
81
|
+
f.reload = undefined;
|
|
82
|
+
return { generation: f.generation, ...(reload ? { reloaded: reload() } : {}) };
|
|
83
|
+
},
|
|
84
|
+
async loadAllExtracted() { return Object.fromEntries(db.extracted); },
|
|
85
|
+
async loadExtracted(hash) { f.bodyReads.push(hash); return db.extracted.get(hash); },
|
|
86
|
+
async changedElsewhere() { f.checks += 1; const c = f.changed; f.changed = false; return c; },
|
|
87
|
+
};
|
|
88
|
+
return f;
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
const rowStore = (rows: RowPersistence) => new LocalSnapshotStore(undefined, { rows, now: () => 'T' });
|
|
93
|
+
const loadedFrom = (snap: KnowledgeSnapshot) => {
|
|
94
|
+
const p = memPersistence();
|
|
95
|
+
p.value = JSON.stringify(snap);
|
|
96
|
+
return new LocalSnapshotStore(p, { now: () => 'T' });
|
|
97
|
+
};
|
|
98
|
+
|
|
99
|
+
function prng(seed: number): () => number {
|
|
100
|
+
return () => {
|
|
101
|
+
seed = (seed + 0x6d2b79f5) | 0;
|
|
102
|
+
let t = Math.imul(seed ^ (seed >>> 15), 1 | seed);
|
|
103
|
+
t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;
|
|
104
|
+
return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
|
|
105
|
+
};
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
/** The seeded op sequence both kinds of store run: facts, relations, scopes, extracted, recheck (with clears), stale marks, reads, some inside `batched`. */
|
|
109
|
+
async function driveOps(store: LocalSnapshotStore, seed: number, steps: number, between?: (rand: () => number, pick: (n: number) => number) => void): Promise<void> {
|
|
110
|
+
const rand = prng(seed);
|
|
111
|
+
const pick = (n: number) => Math.floor(rand() * n);
|
|
112
|
+
const op = async () => {
|
|
113
|
+
const kind = pick(8);
|
|
114
|
+
if (kind <= 2) {
|
|
115
|
+
await store.write({
|
|
116
|
+
scope: { ...SCOPE, ...(rand() < 0.5 ? { lastDigest: `d${pick(9)}` } : {}) },
|
|
117
|
+
facts: Array.from({ length: pick(4) }, () => fact(`claim:k${pick(6)}`, `v${pick(99)}`)),
|
|
118
|
+
relations: Array.from({ length: pick(3) }, () => rel(`fact:claim:k${pick(6)}`, `src:a::f${pick(4)}.md#s`, ['about', 'mentions'][pick(2)]!)),
|
|
119
|
+
});
|
|
120
|
+
} else if (kind === 3) await store.markStale({ rootId: 'a' }, `src:a::f${pick(4)}.md#s` as NodeRef, `h${pick(3)}`);
|
|
121
|
+
else if (kind === 4) await store.putExtracted(`x${pick(8)}`, ex(`e${pick(5)}`));
|
|
122
|
+
else if (kind === 5) await store.markRecheck([`h${pick(5)}`, `h${pick(5)}`]);
|
|
123
|
+
else if (kind === 6) await store.clearRecheck([`h${pick(5)}`]);
|
|
124
|
+
else await store.facts({ rootId: 'a' });
|
|
125
|
+
};
|
|
126
|
+
for (let i = 0; i < steps; i++) {
|
|
127
|
+
between?.(rand, pick);
|
|
128
|
+
try {
|
|
129
|
+
if (rand() < 0.3) await store.batched(async () => { for (let j = 0; j < 5; j++) await op(); });
|
|
130
|
+
else await op();
|
|
131
|
+
} catch (err) {
|
|
132
|
+
if (!between) throw err; // only the fuzz injects failures
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
const sameAsHost = async (store: LocalSnapshotStore, rows: FakeRows) => expect(await canonicalDump(store)).toBe(await canonicalDump(loadedFrom(snapshotOf(rows.db))));
|
|
138
|
+
|
|
139
|
+
describe('regression: row persistence', () => {
|
|
140
|
+
it('regression: after N random mutations the rows the host accumulated equal the canonical dump', async () => {
|
|
141
|
+
const rows = fakeRows();
|
|
142
|
+
const store = rowStore(rows);
|
|
143
|
+
await driveOps(store, 20261108, 90);
|
|
144
|
+
const dump = await canonicalDump(store);
|
|
145
|
+
expect(dump).toContain('"facts"');
|
|
146
|
+
expect(dump).toContain('"recheck"');
|
|
147
|
+
await sameAsHost(store, rows); // the accumulated rows
|
|
148
|
+
expect(await canonicalDump(rowStore(rows))).toBe(dump); // and a second store loading them
|
|
149
|
+
});
|
|
150
|
+
|
|
151
|
+
it('regression: parity oracle: the same op sequence on a snapshot-persisted store and a row store gives byte-equal dumps', async () => {
|
|
152
|
+
for (const seed of [1, 2, 3]) {
|
|
153
|
+
const classic = new LocalSnapshotStore(memPersistence(), { now: () => 'T' });
|
|
154
|
+
const rowed = rowStore(fakeRows());
|
|
155
|
+
await driveOps(classic, seed, 60);
|
|
156
|
+
await driveOps(rowed, seed, 60);
|
|
157
|
+
expect(await canonicalDump(rowed)).toBe(await canonicalDump(classic));
|
|
158
|
+
}
|
|
159
|
+
});
|
|
160
|
+
|
|
161
|
+
it('regression: fuzz: failed applies, `reloaded` and another writer changing the store, interleaved with the ops, never lose or reorder this window\'s rows', async () => {
|
|
162
|
+
for (const seed of [11, 12, 13, 14]) {
|
|
163
|
+
const rows = fakeRows();
|
|
164
|
+
const store = rowStore(rows);
|
|
165
|
+
let other = 0;
|
|
166
|
+
const theirs = () => { const key = `claim:o${other++}`; rows.db.facts.set(fkey('b', key), fact(key)); };
|
|
167
|
+
await driveOps(store, seed, 80, (rand) => {
|
|
168
|
+
const r = rand();
|
|
169
|
+
if (r < 0.15) rows.failNext = 1;
|
|
170
|
+
else if (r < 0.3) rows.reload = () => { theirs(); return snapshotOf(rows.db); };
|
|
171
|
+
else if (r < 0.45) { theirs(); rows.changed = true; }
|
|
172
|
+
});
|
|
173
|
+
rows.failNext = 0;
|
|
174
|
+
rows.reload = undefined;
|
|
175
|
+
await store.write({ scope: SCOPE, facts: [], relations: [] }); // flush whatever a failure left marked
|
|
176
|
+
rows.changed = true;
|
|
177
|
+
await store.scopes(); // pick up the other writer's last change
|
|
178
|
+
await sameAsHost(store, rows);
|
|
179
|
+
}
|
|
180
|
+
});
|
|
181
|
+
|
|
182
|
+
it('regression: a changed-elsewhere read that races an apply cannot drop the rows that apply commits', async () => {
|
|
183
|
+
const rows = fakeRows();
|
|
184
|
+
const store = rowStore(rows);
|
|
185
|
+
await store.facts({ rootId: 'a' });
|
|
186
|
+
rows.hold = deferred();
|
|
187
|
+
const write = store.write({ scope: SCOPE, facts: [fact('claim:mine')], relations: [] });
|
|
188
|
+
await settle();
|
|
189
|
+
rows.db.facts.set(fkey('b', 'claim:theirs'), fact('claim:theirs'));
|
|
190
|
+
rows.changed = true;
|
|
191
|
+
const read = store.facts({ rootId: 'b' });
|
|
192
|
+
await settle();
|
|
193
|
+
rows.hold.resolve();
|
|
194
|
+
await Promise.all([write, read]);
|
|
195
|
+
await store.scopes();
|
|
196
|
+
expect((await store.facts({ rootId: 'a' })).map((x) => x.key)).toEqual(['claim:mine']);
|
|
197
|
+
expect((await store.facts({ rootId: 'b' })).map((x) => x.key)).toEqual(['claim:theirs']);
|
|
198
|
+
await sameAsHost(store, rows);
|
|
199
|
+
});
|
|
200
|
+
|
|
201
|
+
it('regression: a read during a held apply resolves without waiting for it', async () => {
|
|
202
|
+
const rows = fakeRows();
|
|
203
|
+
const store = rowStore(rows);
|
|
204
|
+
await store.facts({ rootId: 'a' });
|
|
205
|
+
rows.checks = 0;
|
|
206
|
+
rows.hold = deferred();
|
|
207
|
+
const write = store.write({ scope: SCOPE, facts: [fact('claim:1')], relations: [] });
|
|
208
|
+
await settle();
|
|
209
|
+
rows.changed = true;
|
|
210
|
+
expect((await store.facts({ rootId: 'a' })).map((x) => x.key)).toEqual(['claim:1']); // resolves while the apply is held
|
|
211
|
+
expect(rows.checks).toBe(0); // no check was made behind the apply
|
|
212
|
+
rows.hold.resolve();
|
|
213
|
+
await write;
|
|
214
|
+
});
|
|
215
|
+
|
|
216
|
+
it('regression: a reload arriving while a failed apply is restored keeps the restored rows, and the next apply persists them', async () => {
|
|
217
|
+
const rows = fakeRows();
|
|
218
|
+
const store = rowStore(rows);
|
|
219
|
+
await store.facts({ rootId: 'a' });
|
|
220
|
+
rows.hold = deferred();
|
|
221
|
+
rows.failNext = 1;
|
|
222
|
+
const write = store.write({ scope: SCOPE, facts: [fact('claim:mine')], relations: [] });
|
|
223
|
+
await settle();
|
|
224
|
+
rows.db.facts.set(fkey('b', 'claim:theirs'), fact('claim:theirs'));
|
|
225
|
+
rows.changed = true;
|
|
226
|
+
const read = store.facts({ rootId: 'b' });
|
|
227
|
+
expect(await read).toEqual([]); // answered from memory while the apply was in flight
|
|
228
|
+
rows.hold.resolve();
|
|
229
|
+
await expect(write).rejects.toThrow('disk full');
|
|
230
|
+
expect((await store.facts({ rootId: 'b' })).map((x) => x.key)).toEqual(['claim:theirs']); // the next read reloads
|
|
231
|
+
expect((await store.facts({ rootId: 'a' })).map((x) => x.key)).toEqual(['claim:mine']); // restored marks survived the reload
|
|
232
|
+
await store.markRecheck(['x']);
|
|
233
|
+
expect(rows.db.facts.has(fkey('a', 'claim:mine'))).toBe(true);
|
|
234
|
+
await sameAsHost(store, rows);
|
|
235
|
+
});
|
|
236
|
+
|
|
237
|
+
it('regression: a dump or extractedEntries with lazy bodies reads them all through loadAllExtracted, and throws without it', async () => {
|
|
238
|
+
const rows = fakeRows();
|
|
239
|
+
rows.lazyBodies = true;
|
|
240
|
+
rows.db.extracted.set('h9', ex('nine'));
|
|
241
|
+
const store = rowStore(rows);
|
|
242
|
+
await store.putExtracted('mem', ex('m'));
|
|
243
|
+
expect(Object.keys(await store.extractedEntries()).sort()).toEqual(['h9', 'mem']);
|
|
244
|
+
expect(await canonicalDump(store)).toContain('"h9"');
|
|
245
|
+
|
|
246
|
+
const bare = fakeRows();
|
|
247
|
+
delete bare.loadAllExtracted;
|
|
248
|
+
const partial = rowStore(bare);
|
|
249
|
+
await expect(partial.extractedEntries()).rejects.toThrow('knowledge_dump_needs_all_bodies');
|
|
250
|
+
await expect(canonicalDump(partial)).rejects.toThrow('knowledge_dump_needs_all_bodies');
|
|
251
|
+
});
|
|
252
|
+
|
|
253
|
+
it('regression: preloadExtracted reads the missing bodies once; a miss is remembered until the hash is put', async () => {
|
|
254
|
+
const rows = fakeRows();
|
|
255
|
+
rows.lazyBodies = true;
|
|
256
|
+
for (const h of ['h1', 'h2']) rows.db.extracted.set(h, ex(h));
|
|
257
|
+
const store = rowStore(rows);
|
|
258
|
+
await store.preloadExtracted(['h1', 'h2', 'h1', 'zz']);
|
|
259
|
+
expect([...rows.bodyReads].sort()).toEqual(['h1', 'h2', 'zz']);
|
|
260
|
+
expect(await store.getExtracted('h2')).toEqual(ex('h2'));
|
|
261
|
+
expect(await store.getExtracted('zz')).toBeUndefined();
|
|
262
|
+
expect(rows.bodyReads).toHaveLength(3); // nothing read again
|
|
263
|
+
await store.putExtracted('zz', ex('z'));
|
|
264
|
+
expect(await store.getExtracted('zz')).toEqual(ex('z'));
|
|
265
|
+
});
|
|
266
|
+
|
|
267
|
+
it('regression: a mutation made while apply is pending is persisted by the next apply', async () => {
|
|
268
|
+
const rows = fakeRows();
|
|
269
|
+
const store = rowStore(rows);
|
|
270
|
+
rows.hold = deferred();
|
|
271
|
+
const first = store.write({ scope: SCOPE, facts: [fact('claim:1')], relations: [] });
|
|
272
|
+
await settle();
|
|
273
|
+
expect(rows.applies).toHaveLength(1);
|
|
274
|
+
const second = store.write({ scope: SCOPE, facts: [fact('claim:2')], relations: [] });
|
|
275
|
+
await settle();
|
|
276
|
+
rows.hold.resolve();
|
|
277
|
+
await Promise.all([first, second]);
|
|
278
|
+
expect(rows.applies).toHaveLength(2);
|
|
279
|
+
expect(rows.applies[0]!.upserts.facts.map(([, x]) => x.key)).toEqual(['claim:1']);
|
|
280
|
+
expect(rows.applies[1]!.upserts.facts.map(([, x]) => x.key)).toEqual(['claim:2']);
|
|
281
|
+
expect([...rows.db.facts.values()].map((x) => x.key).sort()).toEqual(['claim:1', 'claim:2']);
|
|
282
|
+
});
|
|
283
|
+
|
|
284
|
+
it('regression: a rejected apply loses nothing: the retry persists the failed rows with the newer value of a row marked since', async () => {
|
|
285
|
+
const rows = fakeRows();
|
|
286
|
+
const store = rowStore(rows);
|
|
287
|
+
rows.failNext = 1;
|
|
288
|
+
await expect(store.write({ scope: SCOPE, facts: [fact('claim:1', 'old'), fact('claim:2')], relations: [rel('fact:claim:1', 'src:a::f.md#s', 'about')] })).rejects.toThrow('disk full');
|
|
289
|
+
expect(rows.db.facts.size).toBe(0);
|
|
290
|
+
await store.markRecheck(['h1']); // a later mutation: persists, and carries the failed rows with it
|
|
291
|
+
await store.write({ scope: SCOPE, facts: [fact('claim:1', 'new')], relations: [] });
|
|
292
|
+
expect([...rows.db.facts.values()].map((x) => [x.key, x.content]).sort()).toEqual([['claim:1', 'new'], ['claim:2', 'c']]);
|
|
293
|
+
expect(rows.db.relations.size).toBe(1);
|
|
294
|
+
expect(rows.db.scopes.has('a')).toBe(true);
|
|
295
|
+
expect([...rows.db.recheck]).toEqual(['h1']);
|
|
296
|
+
expect(await canonicalDump(loadedFrom(snapshotOf(rows.db)))).toBe(await canonicalDump(store));
|
|
297
|
+
});
|
|
298
|
+
|
|
299
|
+
it('regression: recheck survives a reload', async () => {
|
|
300
|
+
const rows = fakeRows();
|
|
301
|
+
const store = rowStore(rows);
|
|
302
|
+
await store.markRecheck(['h2', 'h1', 'h3']);
|
|
303
|
+
await store.clearRecheck(['h2']);
|
|
304
|
+
expect(rows.applies.at(-1)!.deletes.recheck).toEqual(['h2']);
|
|
305
|
+
expect(await rowStore(rows).recheckHashes()).toEqual(['h1', 'h3']);
|
|
306
|
+
});
|
|
307
|
+
|
|
308
|
+
it('regression: `reloaded` replaces memory, and a mark made while apply was pending survives in memory and is persisted next', async () => {
|
|
309
|
+
const rows = fakeRows();
|
|
310
|
+
const store = rowStore(rows);
|
|
311
|
+
await store.write({ scope: SCOPE, facts: [fact('claim:gone')], relations: [] });
|
|
312
|
+
rows.hold = deferred();
|
|
313
|
+
// Another window: deletes `claim:gone`, adds `claim:other`. Its rows come back with this window's apply.
|
|
314
|
+
rows.reload = () => { rows.db.facts.delete(fkey('a', 'claim:gone')); rows.db.facts.set(fkey('a', 'claim:other'), fact('claim:other')); return snapshotOf(rows.db); };
|
|
315
|
+
const first = store.write({ scope: SCOPE, facts: [fact('claim:1')], relations: [] });
|
|
316
|
+
await settle();
|
|
317
|
+
const second = store.write({ scope: SCOPE, facts: [fact('claim:2')], relations: [] }); // marked during the apply
|
|
318
|
+
await settle();
|
|
319
|
+
rows.hold.resolve();
|
|
320
|
+
await Promise.all([first, second]);
|
|
321
|
+
const keys = (await store.facts({ rootId: 'a' })).map((x) => x.key).sort();
|
|
322
|
+
expect(keys).toEqual(['claim:1', 'claim:2', 'claim:other']); // replaced (gone is gone, other is here), claim:2 not lost
|
|
323
|
+
expect(rows.applies.at(-1)!.upserts.facts.map(([, x]) => x.key)).toEqual(['claim:2']);
|
|
324
|
+
expect([...rows.db.facts.values()].map((x) => x.key).sort()).toEqual(keys);
|
|
325
|
+
});
|
|
326
|
+
|
|
327
|
+
it('regression: `reloaded` rebuilds the relations-by-path index, so markStale finds a relation another window wrote', async () => {
|
|
328
|
+
const rows = fakeRows();
|
|
329
|
+
const store = rowStore(rows);
|
|
330
|
+
rows.reload = () => { rows.db.relations.set(rkey('a', 'fact:claim:9', 'src:a::z.md#s', 'about'), rel('fact:claim:9', 'src:a::z.md#s', 'about')); return snapshotOf(rows.db); };
|
|
331
|
+
await store.write({ scope: SCOPE, facts: [], relations: [] });
|
|
332
|
+
await store.markStale({ rootId: 'a' }, 'src:a::z.md#s', 'other-hash');
|
|
333
|
+
expect((await store.relations({ rootId: 'a' }))[0]!.staleAt).toBe('T');
|
|
334
|
+
});
|
|
335
|
+
|
|
336
|
+
it('regression: when another writer changed the store, a read reloads first (one check in flight, none inside a batch)', async () => {
|
|
337
|
+
const rows = fakeRows();
|
|
338
|
+
const store = rowStore(rows);
|
|
339
|
+
await store.facts({ rootId: 'a' });
|
|
340
|
+
rows.checks = 0;
|
|
341
|
+
rows.db.facts.set(fkey('a', 'claim:theirs'), fact('claim:theirs'));
|
|
342
|
+
rows.changed = true;
|
|
343
|
+
const reads = await Promise.all([1, 2, 3, 4, 5].map(() => store.facts({ rootId: 'a' })));
|
|
344
|
+
expect(rows.checks).toBe(1);
|
|
345
|
+
expect(reads.every((r) => r.map((x) => x.key).join() === 'claim:theirs')).toBe(true);
|
|
346
|
+
|
|
347
|
+
rows.db.facts.set(fkey('a', 'claim:later'), fact('claim:later'));
|
|
348
|
+
rows.changed = true;
|
|
349
|
+
rows.checks = 0;
|
|
350
|
+
await store.batched(async () => { expect((await store.facts({ rootId: 'a' })).map((x) => x.key)).toEqual(['claim:theirs']); });
|
|
351
|
+
expect(rows.checks).toBe(0);
|
|
352
|
+
expect((await store.facts({ rootId: 'a' })).map((x) => x.key).sort()).toEqual(['claim:later', 'claim:theirs']); // the next read outside the batch sees it
|
|
353
|
+
});
|
|
354
|
+
|
|
355
|
+
it('regression: an extract body missing from memory is read through loadExtracted once, and kept', async () => {
|
|
356
|
+
const rows = fakeRows();
|
|
357
|
+
rows.lazyBodies = true;
|
|
358
|
+
rows.db.extracted.set('h9', ex('nine'));
|
|
359
|
+
const store = rowStore(rows);
|
|
360
|
+
expect(await store.getExtracted('h9')).toEqual(ex('nine'));
|
|
361
|
+
expect(await store.getExtracted('h9')).toEqual(ex('nine'));
|
|
362
|
+
expect(await store.getExtracted('nope')).toBeUndefined();
|
|
363
|
+
expect(rows.bodyReads).toEqual(['h9', 'nope']);
|
|
364
|
+
await store.putExtracted('h9', ex('nine')); // the same body: no row written
|
|
365
|
+
expect(rows.applies).toHaveLength(0);
|
|
366
|
+
});
|
|
367
|
+
|
|
368
|
+
it('regression: without rows the store writes the same bytes as the dump, and needs one of the two ports', async () => {
|
|
369
|
+
const p = memPersistence();
|
|
370
|
+
const store = new LocalSnapshotStore(p, { now: () => 'T' });
|
|
371
|
+
await store.write({ scope: SCOPE, facts: [fact('claim:1')], relations: [rel('fact:claim:1', 'src:a::f.md#s', 'about')] });
|
|
372
|
+
await store.putExtracted('h1', ex('one'));
|
|
373
|
+
await store.markRecheck(['h1']);
|
|
374
|
+
expect(await canonicalDump(store)).toBe(p.value);
|
|
375
|
+
expect(() => new (LocalSnapshotStore as unknown as new (p: undefined, o: object) => unknown)(undefined, {})).toThrow();
|
|
376
|
+
});
|
|
377
|
+
});
|
|
@@ -14,10 +14,12 @@
|
|
|
14
14
|
import type { ParsedSection, SourceDocument } from '../ingest/types.js';
|
|
15
15
|
import type {
|
|
16
16
|
Extracted, ExtractJob, ExtractJobResult, GraphApp, GraphOutline, GraphReadSkip, GraphSystem, KEdge, KNode, KnowledgeGraph, KnowledgeStore,
|
|
17
|
-
OutlineFile, ReviewFailure, ReviewFailureChunks, ReviewPhase, ReviewReport, ReviewRun, ReviewRunPhase, ReviewStep, ScopeRecord,
|
|
17
|
+
OutlineFile, OutlineCommunity, NodePlacement, ReviewFailure, ReviewFailureChunks, ReviewPhase, ReviewReport, ReviewRun, ReviewRunPhase, ReviewStep, ScopeRecord,
|
|
18
18
|
StoredFact, StoredRelation, ExtractedLogPersistence, KnowledgeSnapshot, LocalSnapshotStoreOptions, SnapshotPersistence,
|
|
19
|
+
RowChange, RowPersistence,
|
|
19
20
|
} from '../knowledge/index.js';
|
|
20
|
-
import {
|
|
21
|
+
import { placementOf } from '../knowledge/index.js';
|
|
22
|
+
import { canonicalDump, ExtractFailed, failuresOf, failureTotal, LocalSnapshotStore, localSnapshotStore, type ExtractorState } from '../knowledge/index.js';
|
|
21
23
|
|
|
22
24
|
type Equal<A, B> = (<T>() => T extends A ? 1 : 2) extends (<T>() => T extends B ? 1 : 2) ? true : false;
|
|
23
25
|
type Expect<T extends true> = T;
|
|
@@ -143,14 +145,37 @@ export const batchedHostStore = {
|
|
|
143
145
|
export type LocalSnapshotStore_is_a_KnowledgeStore = Expect<Equal<LocalSnapshotStore extends KnowledgeStore ? true : false, true>>;
|
|
144
146
|
export type LocalSnapshotStore_public_methods = Expect<Equal<
|
|
145
147
|
keyof LocalSnapshotStore,
|
|
146
|
-
'batched' | 'scopes' | 'facts' | 'relations' | 'write' | 'markStale' | 'getExtracted' | 'extractedEntries' | 'putExtracted' | 'markRecheck' | 'recheckHashes' | 'clearRecheck' | 'hasRecheck'
|
|
148
|
+
'batched' | 'scopes' | 'facts' | 'relations' | 'write' | 'markStale' | 'getExtracted' | 'extractedEntries' | 'preloadExtracted' | 'putExtracted' | 'markRecheck' | 'recheckHashes' | 'clearRecheck' | 'hasRecheck'
|
|
147
149
|
>>;
|
|
148
150
|
export type LocalSnapshotStore_extractedEntries = Expect<Equal<LocalSnapshotStore['extractedEntries'], () => Promise<Record<string, Extracted[]>>>>;
|
|
149
151
|
export type LocalSnapshotStore_constructor = Expect<Equal<
|
|
150
152
|
ConstructorParameters<typeof LocalSnapshotStore>, [persistence: SnapshotPersistence, opts?: LocalSnapshotStoreOptions]
|
|
151
153
|
>>;
|
|
152
|
-
|
|
153
|
-
export type
|
|
154
|
+
// Two overloads: the snapshot-persisted one (the last, so `Parameters` reads it) and the row-persisted one (`undefined` + `opts.rows`).
|
|
155
|
+
export type localSnapshotStore_factory = Expect<Equal<Parameters<typeof localSnapshotStore>, [persistence: SnapshotPersistence, opts?: LocalSnapshotStoreOptions]>>;
|
|
156
|
+
export type localSnapshotStore_factory_returns = Expect<Equal<ReturnType<typeof localSnapshotStore>, LocalSnapshotStore>>;
|
|
157
|
+
export const rowPersistedStore = (rows: RowPersistence): LocalSnapshotStore => localSnapshotStore(undefined, { rows });
|
|
158
|
+
export const rowPersistedStoreByConstructor = (rows: RowPersistence): LocalSnapshotStore => new LocalSnapshotStore(undefined, { rows });
|
|
159
|
+
export const dumpsAStore = (store: LocalSnapshotStore): Promise<string> => canonicalDump(store);
|
|
160
|
+
export type LocalSnapshotStoreOptions_keys = Expect<Equal<keyof LocalSnapshotStoreOptions, 'extractedLog' | 'rows' | 'now' | 'checkpointMs' | 'nowMs'>>;
|
|
161
|
+
export type RowChange_shape = Expect<Equal<RowChange, {
|
|
162
|
+
upserts: {
|
|
163
|
+
scopes: ScopeRecord[]; facts: Array<[rootId: string, fact: StoredFact]>; relations: Array<[rootId: string, relation: StoredRelation]>;
|
|
164
|
+
extracted: Array<[hash: string, entries: Extracted[]]>; recheck: string[];
|
|
165
|
+
};
|
|
166
|
+
deletes: {
|
|
167
|
+
scopes: string[]; facts: Array<[rootId: string, key: string]>;
|
|
168
|
+
relations: Array<[rootId: string, from: string, to: string, kind: string]>;
|
|
169
|
+
extracted: string[]; recheck: string[];
|
|
170
|
+
};
|
|
171
|
+
}>>;
|
|
172
|
+
export type RowPersistence_ports = Expect<Equal<RowPersistence, {
|
|
173
|
+
load(): Promise<KnowledgeSnapshot | undefined>;
|
|
174
|
+
apply(change: RowChange): Promise<{ generation: number; reloaded?: KnowledgeSnapshot }>;
|
|
175
|
+
loadAllExtracted?(): Promise<Record<string, Extracted[]>>;
|
|
176
|
+
loadExtracted?(hash: string): Promise<Extracted[] | undefined>;
|
|
177
|
+
changedElsewhere?(): Promise<boolean>;
|
|
178
|
+
}>>;
|
|
154
179
|
export type SnapshotPersistence_ports = Expect<Equal<
|
|
155
180
|
SnapshotPersistence,
|
|
156
181
|
{ read(): Promise<string | undefined>; write(snapshot: string): Promise<void>; keepAside?(text: string): Promise<void> }
|
|
@@ -180,6 +205,13 @@ export type GraphOutline_systems = Expect<Equal<
|
|
|
180
205
|
{ systems?: string[]; apps?: string[]; systemInfo?: GraphSystem[] }
|
|
181
206
|
>>;
|
|
182
207
|
export type OutlineFile_system_indexes = Expect<Equal<Pick<OutlineFile, 'system' | 'app' | 'copyOf'>, { system?: number; app?: number; copyOf?: number }>>;
|
|
208
|
+
// PRD 38 P1: communities. `communityId` indexes the outline's `communities` table; ids are per build.
|
|
209
|
+
export type KnowledgeGraph_stats_modularity = Expect<Equal<KnowledgeGraph['stats']['modularity'], number | undefined>>;
|
|
210
|
+
export type KnowledgeGraph_stats_communityMethod = Expect<Equal<KnowledgeGraph['stats']['communityMethod'], 'louvain' | 'label-propagation' | undefined>>;
|
|
211
|
+
export type GraphOutline_communities = Expect<Equal<GraphOutline['communities'], OutlineCommunity[] | undefined>>;
|
|
212
|
+
export type OutlineCommunity_fields = Expect<Equal<OutlineCommunity, { id: number; label: string; size: number }>>;
|
|
213
|
+
export type NodePlacement_shape = Expect<Equal<NodePlacement, { kind: 'partition'; id: string } | { kind: 'community'; id: number }>>;
|
|
214
|
+
export type placementOf_signature = Expect<Equal<ReturnType<typeof placementOf>, NodePlacement | undefined>>;
|
|
183
215
|
export type KEdge_verdict = Expect<Equal<KEdge['verdict'], 'allowed' | 'same' | 'skips' | 'upward' | undefined>>;
|
|
184
216
|
|
|
185
217
|
describe('type contract', () => {
|
|
@@ -106,7 +106,7 @@ describe('buildGraph — the join', () => {
|
|
|
106
106
|
...fixture(),
|
|
107
107
|
live: { changes: [{ path: 'a/two.md', status: 'M', added: 3, removed: 1 }], runFiles: ['a/two.md', 'a/one.md'] },
|
|
108
108
|
});
|
|
109
|
-
expect(live.nodes.find((n) => n.ref === ref('a/two.md'))?.badges).
|
|
109
|
+
expect(live.nodes.find((n) => n.ref === ref('a/two.md'))?.badges).toMatchObject({ added: 3, removed: 1, status: 'M' });
|
|
110
110
|
expect(live.edges).toContainEqual(expect.objectContaining({ from: ref('a/one.md'), to: ref('a/two.md'), kind: 'co-changed', origin: 'agent' }));
|
|
111
111
|
});
|
|
112
112
|
});
|
package/src/knowledge/build.ts
CHANGED
|
@@ -8,7 +8,8 @@
|
|
|
8
8
|
* 3. stored relations become edges; near-duplicate pairs become `near-duplicate` edges
|
|
9
9
|
* (an exact `duplicate` between the same pair wins); live changes badge nodes and
|
|
10
10
|
* `runFiles` become `co-changed` edges;
|
|
11
|
-
* 4. partitions, areas, verdicts; PageRank importance;
|
|
11
|
+
* 4. partitions, areas, verdicts; PageRank importance; communities (`communityId` /
|
|
12
|
+
* `communityConfidence` badges, Q in the stats); findings; then truncation.
|
|
12
13
|
*
|
|
13
14
|
* Deterministic: equal input ⇒ byte-identical JSON. Every list is sorted, every sort ends
|
|
14
15
|
* on ref, objects are built with a fixed key order.
|
|
@@ -23,6 +24,7 @@ import type {
|
|
|
23
24
|
import { crossesSystems, placeInSystem } from './systems.js';
|
|
24
25
|
import { computeFindings } from './findings.js';
|
|
25
26
|
import { pageRank } from './importance.js';
|
|
27
|
+
import { applyCommunities } from './communities.js';
|
|
26
28
|
import { loadPartitions, partitionOf, verdictOf } from './partitions.js';
|
|
27
29
|
import { entityName } from './resolve.js';
|
|
28
30
|
import {
|
|
@@ -194,6 +196,7 @@ export function buildGraph(input: BuildGraphInput, opts: BuildGraphOptions = {})
|
|
|
194
196
|
|
|
195
197
|
const rank = pageRank([...g.nodes.keys()], [...g.edges.values()]);
|
|
196
198
|
for (const n of g.nodes.values()) n.importance = rank.get(n.ref) ?? 0;
|
|
199
|
+
const { modularity, method: communityMethod } = applyCommunities(g.nodes.values(), g.edges.values());
|
|
197
200
|
|
|
198
201
|
const allNodes = [...g.nodes.values()].map(finalNode).sort((a, b) => compareStr(a.ref, b.ref));
|
|
199
202
|
const allEdges = [...g.edges.values()].map(finalEdge).sort(compareEdges);
|
|
@@ -202,7 +205,7 @@ export function buildGraph(input: BuildGraphInput, opts: BuildGraphOptions = {})
|
|
|
202
205
|
scope: { rootId, packs, digest: graphDigest(input) },
|
|
203
206
|
nodes: allNodes, edges: allEdges, findings: [],
|
|
204
207
|
...(systems.length > 0 ? { meta: { systems: systemsMeta(systems, allNodes) } } : {}),
|
|
205
|
-
stats: { sources: sources.size, nodes: allNodes.length, edges: allEdges.length, stale: 0, truncated: false },
|
|
208
|
+
stats: { sources: sources.size, nodes: allNodes.length, edges: allEdges.length, stale: 0, truncated: false, modularity, communityMethod },
|
|
206
209
|
};
|
|
207
210
|
full.findings = computeFindings(full, input.packs, registries, input.nearDuplicates ?? []);
|
|
208
211
|
full.stats.stale = allNodes.filter((n) => n.stale).length;
|