@seanhogg/builderforce-memory 2026.10.56 → 2026.10.59

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 (49) hide show
  1. package/dist/knowledge/build.d.ts +2 -1
  2. package/dist/knowledge/build.d.ts.map +1 -1
  3. package/dist/knowledge/build.js +5 -2
  4. package/dist/knowledge/build.js.map +1 -1
  5. package/dist/knowledge/communities.d.ts +74 -0
  6. package/dist/knowledge/communities.d.ts.map +1 -0
  7. package/dist/knowledge/communities.js +143 -0
  8. package/dist/knowledge/communities.js.map +1 -0
  9. package/dist/knowledge/index.d.ts +3 -1
  10. package/dist/knowledge/index.d.ts.map +1 -1
  11. package/dist/knowledge/index.js +1 -0
  12. package/dist/knowledge/index.js.map +1 -1
  13. package/dist/knowledge/louvain.d.ts +38 -0
  14. package/dist/knowledge/louvain.d.ts.map +1 -0
  15. package/dist/knowledge/louvain.js +164 -0
  16. package/dist/knowledge/louvain.js.map +1 -0
  17. package/dist/knowledge/model.d.ts +25 -2
  18. package/dist/knowledge/model.d.ts.map +1 -1
  19. package/dist/knowledge/outline.d.ts.map +1 -1
  20. package/dist/knowledge/outline.js +4 -0
  21. package/dist/knowledge/outline.js.map +1 -1
  22. package/dist/knowledge/review.d.ts +2 -1
  23. package/dist/knowledge/review.d.ts.map +1 -1
  24. package/dist/knowledge/review.js +36 -5
  25. package/dist/knowledge/review.js.map +1 -1
  26. package/dist/knowledge/reviewRun.js +1 -1
  27. package/dist/knowledge/reviewRun.js.map +1 -1
  28. package/dist/knowledge/reviewRunModel.d.ts +1 -1
  29. package/dist/knowledge/reviewRunModel.d.ts.map +1 -1
  30. package/dist/knowledge/trace.d.ts.map +1 -1
  31. package/dist/knowledge/trace.js +24 -3
  32. package/dist/knowledge/trace.js.map +1 -1
  33. package/package.json +3 -3
  34. package/src/contract/exports.snapshot.json +9 -0
  35. package/src/contract/regression.review.test.ts +55 -0
  36. package/src/contract/types.contract.test.ts +10 -2
  37. package/src/knowledge/build.test.ts +1 -1
  38. package/src/knowledge/build.ts +5 -2
  39. package/src/knowledge/communities.test.ts +322 -0
  40. package/src/knowledge/communities.ts +167 -0
  41. package/src/knowledge/index.ts +7 -2
  42. package/src/knowledge/louvain.ts +147 -0
  43. package/src/knowledge/model.ts +26 -3
  44. package/src/knowledge/outline.test.ts +17 -5
  45. package/src/knowledge/outline.ts +4 -0
  46. package/src/knowledge/review.ts +28 -6
  47. package/src/knowledge/reviewRun.ts +1 -1
  48. package/src/knowledge/reviewRunModel.ts +1 -1
  49. package/src/knowledge/trace.ts +24 -4
@@ -6,6 +6,7 @@
6
6
  * (also `cycle` when the edge carries the cycle flag). Lanes are the partitions the trace
7
7
  * touches — code layers or doc folders — and `toMermaid` draws them as a sequence diagram.
8
8
  */
9
+ import { placementOf } from './communities.js';
9
10
  import { partitionOrder } from './partitions.js';
10
11
  import { compareStr } from './refs.js';
11
12
  export const DEFAULT_TRACE_EDGE_KINDS = ['references', 'links', 'mentions'];
@@ -13,11 +14,24 @@ export const DEFAULT_TRACE_DEPTH = 4;
13
14
  export const DEFAULT_TRACE_STEPS = 60;
14
15
  /** The lane of a node with no partition. */
15
16
  export const UNPARTITIONED_LANE = '(none)';
17
+ /** The lane of a community: its name, and the id the lanes are sorted by (numerically, not as text). */
18
+ const communityLane = (id) => `community ${id}`;
19
+ function placementLane(n, communities) {
20
+ const p = placementOf(n);
21
+ if (p === undefined)
22
+ return undefined;
23
+ if (p.kind === 'partition')
24
+ return p.id;
25
+ communities.set(communityLane(p.id), p.id);
26
+ return communityLane(p.id);
27
+ }
16
28
  export function traceGraph(g, from, opts = {}) {
17
29
  const kinds = new Set(opts.edgeKinds ?? DEFAULT_TRACE_EDGE_KINDS);
18
30
  const maxDepth = opts.maxDepth ?? DEFAULT_TRACE_DEPTH;
19
31
  const maxSteps = opts.maxSteps ?? DEFAULT_TRACE_STEPS;
20
- const partition = new Map(g.nodes.map((n) => [n.ref, n.partition]));
32
+ // A node's lane is its partition, else its community (PRD 38 P1), else none.
33
+ const communityIds = new Map();
34
+ const partition = new Map(g.nodes.map((n) => [n.ref, placementLane(n, communityIds)]));
21
35
  const out = new Map();
22
36
  for (const e of g.edges) {
23
37
  if (!kinds.has(e.kind))
@@ -68,8 +82,15 @@ export function traceGraph(g, from, opts = {}) {
68
82
  }
69
83
  if (opts.registry) {
70
84
  const reg = opts.registry;
71
- const order = (l) => partitionOrder(l, reg) ?? Number.MAX_SAFE_INTEGER;
72
- lanes.sort((a, b) => order(a) - order(b) || compareStr(a, b));
85
+ // Partitions in the registry's order, then communities by numeric id, then everything else by name.
86
+ const key = (l) => {
87
+ const order = partitionOrder(l, reg);
88
+ if (order !== undefined)
89
+ return [0, order];
90
+ const community = communityIds.get(l);
91
+ return community !== undefined ? [1, community] : [2, 0];
92
+ };
93
+ lanes.sort((a, b) => key(a)[0] - key(b)[0] || key(a)[1] - key(b)[1] || compareStr(a, b));
73
94
  }
74
95
  return { from, lanes, steps, truncated, laneOf };
75
96
  }
@@ -1 +1 @@
1
- {"version":3,"file":"trace.js","sourceRoot":"","sources":["../../src/knowledge/trace.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AAGH,OAAO,EAAE,cAAc,EAAE,MAAM,iBAAiB,CAAC;AACjD,OAAO,EAAE,UAAU,EAAE,MAAM,WAAW,CAAC;AAEvC,MAAM,CAAC,MAAM,wBAAwB,GAAsB,CAAC,YAAY,EAAE,OAAO,EAAE,UAAU,CAAC,CAAC;AAC/F,MAAM,CAAC,MAAM,mBAAmB,GAAG,CAAC,CAAC;AACrC,MAAM,CAAC,MAAM,mBAAmB,GAAG,EAAE,CAAC;AACtC,4CAA4C;AAC5C,MAAM,CAAC,MAAM,kBAAkB,GAAG,QAAQ,CAAC;AAe3C,MAAM,UAAU,UAAU,CAAC,CAAiB,EAAE,IAAa,EAAE,IAAI,GAAiB,EAAE;IAChF,MAAM,KAAK,GAAG,IAAI,GAAG,CAAC,IAAI,CAAC,SAAS,IAAI,wBA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CAAC,KAAK,CAAC,IAAe,CAAC,CAAC,EAAE,CAAC,CAAC;IAC1H,KAAK,MAAM,CAAC,IAAI,CAAC,CAAC,KAAK,EAAE,CAAC;QACtB,MAAM,KAAK,GAAG,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,KAAK,CAAC;QACtC,MAAM,KAAK,GAAG,CAAC,CAAC,CAAC,OAAO,KAAK,QAAQ,IAAI,CAAC,CAAC,OAAO,KAAK,OAAO,CAAC,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,EAAE,CAAC;aACnG,MAAM,CAAC,OAAO,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,IAAI,CAAC,EAAE,CAAC,CAAC;QACpD,MAAM,IAAI,GAAG,IAAI,CAAC,GAAG,KAAK,CAAC,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC,IAAI,IAAI,KAAK,CAAC,CAAC,CAAC,EAAE,CAAC,EAAE,CAAC,GAAG,KAAK,CAAC;QACvE,KAAK,CAAC,IAAI,CAAC,OAAO,EAAE,CAAC,GAAG,CAAC,MAAM,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,GAAG,KAAK,GAAG,EAAE,CAAC,GAAG,CAAC,MAAM,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,KAAK,IAAI,EAAE,CAAC,CAAC;IACxF,CAAC;IACD,OAAO,GAAG,KAAK,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.56",
3
+ "version": "2026.10.59",
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.56"
120
+ "@seanhogg/builderforce-memory-engine": "^2026.10.59"
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.56"
134
+ "@seanhogg/builderforce-memory-engine": "2026.10.59"
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",
@@ -319,6 +325,7 @@
319
325
  "clampClaim",
320
326
  "clampQuote",
321
327
  "codeTokenize",
328
+ "communityTable",
322
329
  "compareManifestKey",
323
330
  "compareStr",
324
331
  "components",
@@ -328,6 +335,7 @@
328
335
  "createKnowledgeIndex",
329
336
  "createModelLimiter",
330
337
  "crossesSystems",
338
+ "detectCommunities",
331
339
  "entityKey",
332
340
  "entityName",
333
341
  "extractFile",
@@ -376,6 +384,7 @@
376
384
  "partitionSeverity",
377
385
  "pathOfRef",
378
386
  "placeInSystem",
387
+ "placementOf",
379
388
  "planDetail",
380
389
  "planReview",
381
390
  "possibleSameFindings",
@@ -6,6 +6,7 @@
6
6
 
7
7
  import { hashText } from '../ingest/hash.js';
8
8
  import { InMemoryIngestManifest } from '../ingest/IngestionPipeline.js';
9
+ import type { ReviewProgress } from '../knowledge/model.js';
9
10
  import type { ReviewStep } from '../knowledge/reviewRunModel.js';
10
11
  import { extractJob, type ExtractJob, type ExtractPool } from '../knowledge/extractJob.js';
11
12
  import type { JudgementRequest, KnowledgePack, KnowledgeStore } from '../knowledge/model.js';
@@ -158,6 +159,60 @@ describe('regression: pass 2 and pass 1', () => {
158
159
  expect(retired).toEqual([srcRef(ROOT, 'c.md')]);
159
160
  });
160
161
 
162
+ it('regression: the review leaves "write" for an "analyse" phase the moment the last file is written, and forwards analyzer progress', async () => {
163
+ const pack: KnowledgePack = {
164
+ ...quietPack,
165
+ analyzers: { async analyse(_root, _signal, onProgress) { onProgress?.({ done: 1, total: 2 }); onProgress?.({ done: 2, total: 2 }); return []; } },
166
+ };
167
+ const events: Array<{ phase: string; done: number; total: number }> = [];
168
+ const source = memSource({ ...FILES });
169
+ await reviewDirectory(args(source, memStore(), new InMemoryIngestManifest(), {
170
+ judgement: fakeJudge(), packs: [pack], onProgress: (p) => events.push({ phase: p.phase, done: p.done, total: p.total }),
171
+ }));
172
+ const lastWrite = events.map((e) => e.phase).lastIndexOf('write');
173
+ const analyse = events.map((e, i) => (e.phase === 'analyse' ? i : -1)).filter((i) => i >= 0);
174
+ const firstResolve = events.findIndex((e) => e.phase === 'resolve');
175
+ expect(analyse.length).toBe(4);
176
+ expect(analyse[0]!).toBeGreaterThan(lastWrite);
177
+ expect(analyse[3]!).toBeLessThan(firstResolve);
178
+ expect(analyse.map((i) => [events[i]!.done, events[i]!.total])).toEqual([[0, 1], [1, 2], [2, 2], [2, 2]]); // open, two forwarded, close
179
+ });
180
+
181
+ it('regression: an analyzer that never reports keeps the "analyse" row active while it runs, and the row ends before resolve', async () => {
182
+ let release!: () => void;
183
+ const gate = new Promise<void>((r) => { release = r; });
184
+ let entered!: () => void;
185
+ const inside = new Promise<void>((r) => { entered = r; });
186
+ const pack: KnowledgePack = { ...quietPack, analyzers: { async analyse() { entered(); await gate; return []; } } };
187
+ const events: ReviewProgress[] = [];
188
+ const done = reviewDirectory(args(memSource({ ...FILES }), memStore(), new InMemoryIngestManifest(), {
189
+ judgement: fakeJudge(), packs: [pack], onProgress: (p) => events.push(p),
190
+ }));
191
+ await inside;
192
+ const fold = () => events.reduce((run, progress) => applyRunEvent(run, { type: 'progress', progress }, 1), startRun({ id: 'r', root: 'r', kind: 'review', at: 0 }));
193
+ const during = fold().phases.find((p) => p.phase === 'analyse');
194
+ expect(during).toBeDefined();
195
+ expect(during!.endedAt).toBeUndefined();
196
+ release();
197
+ await done;
198
+ const after = fold().phases.find((p) => p.phase === 'analyse')!;
199
+ expect(after.endedAt).toBeDefined();
200
+ expect(after.done).toBe(after.total);
201
+ expect(events.findIndex((e) => e.phase === 'resolve')).toBeGreaterThan(events.map((e) => e.phase).lastIndexOf('analyse'));
202
+ });
203
+
204
+ it('regression: a Stop while the analyzers run ends the review as aborted and never reaches resolve', async () => {
205
+ const stop = new AbortController();
206
+ const pack: KnowledgePack = { ...quietPack, analyzers: { async analyse() { stop.abort(); return []; } } };
207
+ const phases: string[] = [];
208
+ const report = await reviewDirectory(args(memSource({ ...FILES }), memStore(), new InMemoryIngestManifest(), {
209
+ judgement: fakeJudge(), packs: [pack], signal: stop.signal, onProgress: (p) => phases.push(p.phase),
210
+ }));
211
+ expect(report.aborted).toBe(true);
212
+ expect(phases).toContain('analyse');
213
+ expect(phases).not.toContain('resolve');
214
+ });
215
+
161
216
  it('regression: pass 1 neither owes nor stale-marks a file whose sections are all reused', async () => {
162
217
  const store = memStore();
163
218
  const manifest = new InMemoryIngestManifest();
@@ -14,10 +14,11 @@
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
19
  RowChange, RowPersistence,
20
20
  } from '../knowledge/index.js';
21
+ import { placementOf } from '../knowledge/index.js';
21
22
  import { canonicalDump, ExtractFailed, failuresOf, failureTotal, LocalSnapshotStore, localSnapshotStore, type ExtractorState } from '../knowledge/index.js';
22
23
 
23
24
  type Equal<A, B> = (<T>() => T extends A ? 1 : 2) extends (<T>() => T extends B ? 1 : 2) ? true : false;
@@ -73,7 +74,7 @@ export type ReviewStep_fields = Expect<Equal<
73
74
  { path: string; phase: ReviewPhase; ms: number; reason?: string; lane?: number }
74
75
  >>;
75
76
  // `mapped` is the end of the mechanical pass: a view that switches on phases must know it.
76
- export type ReviewPhase_values = Expect<Equal<ReviewPhase, 'plan' | 'extract' | 'resolve' | 'judge' | 'compare' | 'write' | 'index' | 'mapped' | 'done'>>;
77
+ export type ReviewPhase_values = Expect<Equal<ReviewPhase, 'plan' | 'extract' | 'resolve' | 'judge' | 'compare' | 'write' | 'analyse' | 'index' | 'mapped' | 'done'>>;
77
78
 
78
79
  /* ── ExtractJob: a union of "the review read it" (doc) and "the pool reads it" (readByPool) ──────────────────── */
79
80
  const aDocument: SourceDocument = { id: 'a.md', tenantId: 't', content: { kind: 'text', text: '# A\n' } };
@@ -204,6 +205,13 @@ export type GraphOutline_systems = Expect<Equal<
204
205
  { systems?: string[]; apps?: string[]; systemInfo?: GraphSystem[] }
205
206
  >>;
206
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>>;
207
215
  export type KEdge_verdict = Expect<Equal<KEdge['verdict'], 'allowed' | 'same' | 'skips' | 'upward' | undefined>>;
208
216
 
209
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).toEqual({ added: 3, removed: 1, status: 'M' });
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
  });
@@ -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; findings; then truncation.
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;
@@ -0,0 +1,322 @@
1
+ /**
2
+ * src/knowledge/communities.test.ts
3
+ * PRD 38 P1: Louvain communities over the file reference graph (code `references` and docs `links`), the
4
+ * label-propagation fallback above the cap, the membership confidence, determinism, the placement helper
5
+ * and that an unreferenced file gets no badge. Hand computations are in the comments.
6
+ */
7
+
8
+ import {
9
+ applyCommunities, communityTable, COMMUNITY_EDGE_KINDS, detectCommunities, placementOf,
10
+ } from './communities.js';
11
+ import { buildGraph } from './build.js';
12
+ import { buildAdjacency, localMoving } from './louvain.js';
13
+ import { buildOutline } from './outline.js';
14
+ import type { BuildGraphInput, KNode, KnowledgeGraph } from './model.js';
15
+ import { traceGraph } from './trace.js';
16
+ import { edge, extractedOf, fileNode, ref } from './testkit.test-util.js';
17
+
18
+ const E = (a: string, b: string, weight = 1) => ({ from: ref(a), to: ref(b), weight });
19
+ const same = (a: unknown, b: unknown) => expect(JSON.stringify(a)).toBe(JSON.stringify(b));
20
+
21
+ /** Two triangles, a1-a2-a3 and b1-b2-b3, joined by the single edge a3-b1. m = 7. */
22
+ const CLIQUES = ['a1', 'a2', 'a3', 'b1', 'b2', 'b3'].map((p) => `${p}.md`);
23
+ const CLIQUE_EDGES = [
24
+ E('a1.md', 'a2.md'), E('a2.md', 'a3.md'), E('a1.md', 'a3.md'),
25
+ E('b1.md', 'b2.md'), E('b2.md', 'b3.md'), E('b1.md', 'b3.md'),
26
+ E('a3.md', 'b1.md'),
27
+ ];
28
+
29
+ describe('detectCommunities — Louvain', () => {
30
+ const r = detectCommunities(CLIQUES.map(ref), CLIQUE_EDGES);
31
+ const id = (p: string) => r.members.get(ref(p))!.communityId;
32
+
33
+ it('splits two cliques joined by one edge into two communities with Q > 0.3', () => {
34
+ expect(r.method).toBe('louvain');
35
+ expect(new Set([...r.members.values()].map((m) => m.communityId)).size).toBe(2);
36
+ expect(id('a1.md')).toBe(id('a3.md'));
37
+ expect(id('b1.md')).toBe(id('b3.md'));
38
+ expect(id('a1.md')).not.toBe(id('b1.md'));
39
+ expect(r.modularity).toBeGreaterThan(0.3);
40
+ // Hand computed: 2 × (3/7 − (7/14)²) = 0.357143.
41
+ expect(r.modularity).toBe(0.357143);
42
+ });
43
+
44
+ it('community ids are indexes by smallest member path', () => {
45
+ expect(id('a2.md')).toBe(0);
46
+ expect(id('b3.md')).toBe(1);
47
+ });
48
+
49
+ it('confidence is the share of a file\'s edge weight inside its community', () => {
50
+ expect(r.members.get(ref('a1.md'))!.confidence).toBe(1);
51
+ // a3: two edges inside (a1, a2), one out (b1) → 2/3.
52
+ expect(r.members.get(ref('a3.md'))!.confidence).toBe(0.666667);
53
+ expect(r.members.get(ref('b1.md'))!.confidence).toBe(0.666667);
54
+ });
55
+
56
+ it('sums both directions and weights by reference count', () => {
57
+ const weighted = detectCommunities(CLIQUES.map(ref), [...CLIQUE_EDGES, E('b1.md', 'a3.md', 5)]);
58
+ // Hand computed: the a3-b1 bridge weighs 1 + 5 = 6 (m = 12), so a3 and b1 form one community
59
+ // ({a1,a2}, {a3,b1}, {b2,b3}; Q = 0.166667 beats the two triangles' Q = 0). Each has 6 of its 8 edge weight inside.
60
+ const w = (p: string) => weighted.members.get(ref(p))!;
61
+ expect(w('a3.md').communityId).toBe(w('b1.md').communityId);
62
+ expect([w('a1.md').communityId, w('a3.md').communityId, w('b2.md').communityId]).toEqual([0, 1, 2]);
63
+ expect(w('a3.md').confidence).toBe(0.75);
64
+ expect(w('b1.md').confidence).toBe(0.75);
65
+ expect(weighted.modularity).toBe(0.166667);
66
+ });
67
+
68
+ it('a file with no references gets no membership', () => {
69
+ const withIsolated = detectCommunities([...CLIQUES, 'lonely.md'].map(ref), CLIQUE_EDGES);
70
+ expect(withIsolated.members.has(ref('lonely.md'))).toBe(false);
71
+ expect(withIsolated.members.size).toBe(6);
72
+ expect(withIsolated.modularity).toBe(r.modularity);
73
+ });
74
+
75
+ it('no edges: nothing is assigned and Q is 0', () => {
76
+ const none = detectCommunities(CLIQUES.map(ref), []);
77
+ expect(none.members.size).toBe(0);
78
+ expect(none.modularity).toBe(0);
79
+ });
80
+
81
+ it('ignores self references and non-positive weights', () => {
82
+ const noisy = detectCommunities(CLIQUES.map(ref), [...CLIQUE_EDGES, E('a1.md', 'a1.md', 9), E('a1.md', 'b3.md', 0)]);
83
+ same([...noisy.members], [...r.members]);
84
+ });
85
+
86
+ it('shuffled input gives byte-identical output', () => {
87
+ const shuffled = detectCommunities([...CLIQUES].reverse().map(ref), [...CLIQUE_EDGES].reverse().map((e) => ({ ...e })));
88
+ same([...shuffled.members], [...r.members]);
89
+ expect(shuffled.modularity).toBe(r.modularity);
90
+ });
91
+
92
+ it('a ring of ten triangles: the second level merges neighbouring cliques', () => {
93
+ // Clique i is ci{a,b,c}; ci-c links to c(i+1)-a. m = 10 × 3 + 10 = 40, 2m = 80, every clique has degree sum 8.
94
+ // Level 1 forms the ten cliques. Level 2 (nodes of degree 8, self-loop 3, ring edges of weight 1): node 0 joins 1 on a
95
+ // 0.2 gain (1 − 8·8/80), 2 joins 3, … so five pairs. Level 3 (degree 16): 1 − 16·16/80 < 0, no further merge.
96
+ // Q = 5 × (14/80 − (16/80)²) = 0.675.
97
+ const nm = (i: number, x: string) => `c${String(i).padStart(2, '0')}${x}.md`;
98
+ const files: string[] = [];
99
+ const links: ReturnType<typeof E>[] = [];
100
+ for (let i = 0; i < 10; i++) {
101
+ files.push(nm(i, 'a'), nm(i, 'b'), nm(i, 'c'));
102
+ links.push(E(nm(i, 'a'), nm(i, 'b')), E(nm(i, 'b'), nm(i, 'c')), E(nm(i, 'a'), nm(i, 'c')), E(nm(i, 'c'), nm((i + 1) % 10, 'a')));
103
+ }
104
+ const ring = detectCommunities(files.map(ref), links);
105
+ const c = (p: string) => ring.members.get(ref(p))!;
106
+ expect(new Set([...ring.members.values()].map((m) => m.communityId)).size).toBe(5);
107
+ expect(c(nm(0, 'a')).communityId).toBe(c(nm(1, 'c')).communityId);
108
+ expect(c(nm(0, 'a')).communityId).not.toBe(c(nm(2, 'a')).communityId);
109
+ expect([0, 2, 4, 6, 8].map((i) => c(nm(i, 'a')).communityId)).toEqual([0, 1, 2, 3, 4]);
110
+ // c00a has 2 of its 3 links inside the pair (the third comes from c09c); c00c has all 3 (its bridge goes to c01a).
111
+ expect(c(nm(0, 'a')).confidence).toBe(0.666667);
112
+ expect(c(nm(0, 'c')).confidence).toBe(1);
113
+ expect(ring.modularity).toBe(0.675);
114
+ });
115
+
116
+ it('a tie keeps the lowest community id', () => {
117
+ // a0-a1 and b0-b1 weigh 5; x links a1 and b0 with 1 each. Degrees: a0 5, a1 6, b0 6, b1 5, x 2; 2m = 24.
118
+ // x has the same gain on both sides (1 − 11·2/24 = 0.083), so the lowest id (the a side) wins; confidence 1/2.
119
+ const tie = detectCommunities(
120
+ ['a0', 'a1', 'b0', 'b1', 'x'].map((p) => ref(`${p}.md`)),
121
+ [E('a0.md', 'a1.md', 5), E('b0.md', 'b1.md', 5), E('a1.md', 'x.md'), E('x.md', 'b0.md')],
122
+ );
123
+ const t = (p: string) => tie.members.get(ref(p))!;
124
+ expect([t('a0.md').communityId, t('a1.md').communityId, t('x.md').communityId]).toEqual([0, 0, 0]);
125
+ expect([t('b0.md').communityId, t('b1.md').communityId]).toEqual([1, 1]);
126
+ expect(t('x.md').confidence).toBe(0.5);
127
+ });
128
+ });
129
+
130
+ describe('detectCommunities — label propagation above the cap', () => {
131
+ const TRIANGLES = ['x1', 'x2', 'x3', 'y1', 'y2', 'y3'].map((p) => `${p}.md`);
132
+ const TRI_EDGES = [
133
+ E('x1.md', 'x2.md'), E('x2.md', 'x3.md'), E('x1.md', 'x3.md'),
134
+ E('y1.md', 'y2.md'), E('y2.md', 'y3.md'), E('y1.md', 'y3.md'),
135
+ ];
136
+
137
+ it('finds the exact partition of two disjoint triangles', () => {
138
+ // Sorted labels x1..y3 = 0..5. x1 hears labels 1 and 2 (tie → smallest, 1); x2 keeps 1 on a tie; x3 hears 1 twice. Same for y with 4.
139
+ const r = detectCommunities(TRIANGLES.map(ref), TRI_EDGES, 4);
140
+ expect(r.method).toBe('label-propagation');
141
+ expect([...r.members].map(([k, m]) => [k, m.communityId, m.confidence])).toEqual(
142
+ TRIANGLES.map((p, i) => [ref(p), i < 3 ? 0 : 1, 1]),
143
+ );
144
+ // 2 × (6/12 − (6/12)²) = 0.5
145
+ expect(r.modularity).toBe(0.5);
146
+ });
147
+
148
+ it('is deterministic under shuffled input', () => {
149
+ const a = detectCommunities(CLIQUES.map(ref), CLIQUE_EDGES, 4);
150
+ const b = detectCommunities([...CLIQUES].reverse().map(ref), [...CLIQUE_EDGES].reverse(), 4);
151
+ expect(a.method).toBe('label-propagation');
152
+ same([...b.members], [...a.members]);
153
+ expect(a.modularity).toBe(b.modularity);
154
+ });
155
+
156
+ it('a node keeps its own label when it is the larger of two tied labels', () => {
157
+ // Path p0 - p1 - p3 - p2 (edges p0-p1, p1-p3, p2-p3), labels start as the sorted index 0..3. One sweep:
158
+ // p0 hears {1} and takes 1; p1 hears {1 (p0), 3 (p3)}, holds 1 and keeps it; p2 hears {3} and takes 3;
159
+ // p3 hears {1 (p1), 3 (p2)} equally while holding 3, so it KEEPS 3. (A "smallest label wins" rule would give it 1
160
+ // and merge everything into one community.) The second sweep changes nothing.
161
+ const r = detectCommunities(
162
+ ['p0', 'p1', 'p2', 'p3'].map((p) => ref(`${p}.md`)),
163
+ [E('p0.md', 'p1.md'), E('p1.md', 'p3.md'), E('p2.md', 'p3.md')],
164
+ 2,
165
+ );
166
+ expect(r.method).toBe('label-propagation');
167
+ expect([...r.members.values()].map((m) => [m.communityId, m.confidence])).toEqual([[0, 1], [0, 0.5], [1, 1], [1, 0.5]]);
168
+ });
169
+ });
170
+
171
+ describe('Louvain tie rule', () => {
172
+ it('a node stays put when its own community ties a lower-id one', () => {
173
+ // a-b 12, b-d 7, c-d 1 (a..d = indexes 0..3). Degrees a 12, b 19, c 1, d 8; 2m = 40. Sweep 1: a joins b; b stays (6.3 against 3.2);
174
+ // c joins d. d, in {c,d} (id 3), then weighs staying (1 − 1·8/40 = 0.8) against {a,b} (id 1: 7 − 31·8/40 = 0.8): an exact
175
+ // tie, so it stays. A rule that sent ties to the lowest id would pull d into {a,b}.
176
+ const order = ['a', 'b', 'c', 'd'].map((p) => ref(`${p}.md`));
177
+ const adj = buildAdjacency(order, [E('a.md', 'b.md', 12), E('b.md', 'd.md', 7), E('c.md', 'd.md', 1)]);
178
+ const { comm, moved } = localMoving(adj, [0, 0, 0, 0], 40);
179
+ expect(moved).toBe(true);
180
+ expect(comm).toEqual([0, 0, 1, 1]);
181
+ });
182
+ });
183
+
184
+ describe('applyCommunities / buildGraph', () => {
185
+ /** Two triangles in d1/ and d2/ joined by one edge; `lonely.md` has no edges. `kind` is the edge kind of every reference. */
186
+ function input(kind: string): BuildGraphInput {
187
+ const files = ['d1/a.md', 'd1/b.md', 'd1/c.md', 'd2/a.md', 'd2/b.md', 'd2/c.md', 'lonely.md'];
188
+ const pairs: Array<[string, string]> = [
189
+ ['d1/a.md', 'd1/b.md'], ['d1/b.md', 'd1/c.md'], ['d1/a.md', 'd1/c.md'],
190
+ ['d2/a.md', 'd2/b.md'], ['d2/b.md', 'd2/c.md'], ['d2/a.md', 'd2/c.md'], ['d1/c.md', 'd2/a.md'],
191
+ ];
192
+ return {
193
+ rootId: 'r', packs: [],
194
+ extracted: files.map((p) => extractedOf(fileNode(p), pairs.filter(([f]) => f === p).map(([f, t]) => edge(f, t, kind)))),
195
+ facts: [], relations: [],
196
+ };
197
+ }
198
+
199
+ it('counts both `references` and `links`', () => {
200
+ expect(COMMUNITY_EDGE_KINDS).toEqual(['references', 'links']);
201
+ });
202
+
203
+ it.each(['references', 'links'])('a %s-only graph is clustered, reports Q and the method, and leaves an unreferenced file bare', (kind) => {
204
+ const g = buildGraph(input(kind));
205
+ const node = (p: string) => g.nodes.find((n) => n.ref === ref(p))!;
206
+ expect(node('d1/b.md').badges).toMatchObject({ communityId: 0, communityConfidence: 1 });
207
+ expect(node('d2/b.md').badges).toMatchObject({ communityId: 1 });
208
+ expect(node('d1/c.md').badges?.['communityConfidence']).toBe(0.666667);
209
+ expect(node('lonely.md').badges).toBeUndefined();
210
+ expect(g.stats.modularity).toBe(0.357143);
211
+ expect(g.stats.communityMethod).toBe('louvain');
212
+ });
213
+
214
+ it('other edge kinds and stale relations are not references', () => {
215
+ const nodes = CLIQUES.map((p) => fileNode(p));
216
+ const q = applyCommunities(nodes, [
217
+ edge('a1.md', 'a2.md', 'mentions'), edge('a2.md', 'a3.md', 'near-duplicate'), edge('a1.md', 'a3.md', 'links', { stale: true }),
218
+ ]);
219
+ expect(q.modularity).toBe(0);
220
+ expect(nodes.every((n) => n.badges === undefined)).toBe(true);
221
+ });
222
+
223
+ it('equal input in a different order builds byte-identical graphs', () => {
224
+ const base = input('links');
225
+ const rev = { ...base, extracted: [...base.extracted].reverse().map((e) => ({ ...e, edges: [...e.edges].reverse() })) };
226
+ same(buildGraph(rev), buildGraph(base));
227
+ });
228
+
229
+ it('the outline carries the badges and a labelled communities table', () => {
230
+ const o = buildOutline(buildGraph(input('links')));
231
+ expect(o.files.find((x) => x.path.endsWith('d1/c.md'))!.badges).toEqual({ communityId: 0, communityConfidence: 0.666667 });
232
+ expect(o.files.find((x) => x.path.endsWith('lonely.md'))!.badges).toBeUndefined();
233
+ expect(o.communities).toEqual([{ id: 0, label: 'd1', size: 3 }, { id: 1, label: 'd2', size: 3 }]);
234
+ });
235
+
236
+ it('the cut graph keeps modularity in its stats', () => {
237
+ const g = buildGraph(input('links'), { maxNodes: 3 });
238
+ expect(g.stats.truncated).toBe(true);
239
+ expect(g.stats.modularity).toBe(0.357143);
240
+ expect(g.outline!.communities!.length).toBe(2);
241
+ });
242
+ });
243
+
244
+ describe('communityTable', () => {
245
+ it('labels a community with its common directory, else with its most important member', () => {
246
+ const mk = (p: string, importance: number) => fileNode(p, { importance, badges: { communityId: 0 } });
247
+ expect(communityTable([mk('src/a/x.ts', 0.1), mk('src/a/y.ts', 0.2)])).toEqual([{ id: 0, label: 'src/a', size: 2 }]);
248
+ expect(communityTable([mk('src/x.ts', 0.1), mk('lib/y.ts', 0.9)])).toEqual([{ id: 0, label: 'lib/y.ts', size: 2 }]);
249
+ });
250
+
251
+ it('builds the label from the outline-relative path (prefix stripped)', () => {
252
+ const n = fileNode('src/a/x.ts', { badges: { communityId: 0 } });
253
+ expect(communityTable([n], 'src:r::')).toEqual([{ id: 0, label: 'src/a', size: 1 }]);
254
+ });
255
+
256
+ it('makes labels unique: top member basename first, then a numeric suffix', () => {
257
+ const mk = (p: string, id: number, importance: number) => fileNode(p, { importance, badges: { communityId: id } });
258
+ // Communities 0 and 1 share the directory 'src', so each gets its top member's basename; 2 and 3 are already distinct.
259
+ const table = communityTable([
260
+ mk('src/a.ts', 0, 0.9), mk('src/b.ts', 0, 0.1),
261
+ mk('src/c.ts', 1, 0.9), mk('src/d.ts', 1, 0.1),
262
+ mk('src/lib/x.ts', 2, 0.9), mk('src/lib/y.ts', 2, 0.1),
263
+ mk('doc/z.md', 3, 0.5),
264
+ ]);
265
+ expect(table.map((c) => c.label)).toEqual(['src · a.ts', 'src · c.ts', 'src/lib', 'doc']);
266
+ expect(new Set(table.map((c) => c.label)).size).toBe(table.length);
267
+ });
268
+
269
+ it('falls back to a numeric suffix when the top member name also collides', () => {
270
+ const mk = (p: string, id: number) => fileNode(p, { badges: { communityId: id } });
271
+ // Both communities are {src/index.ts + a sibling in src}: same directory, same top basename (ties → smaller ref first).
272
+ const table = communityTable([mk('src/index.ts', 0), mk('src/x.ts', 0), mk('src/index.ts', 1), mk('src/y.ts', 1)]);
273
+ expect(table.map((c) => c.label)).toEqual(['src · index.ts', 'src · index.ts 2']);
274
+ });
275
+ });
276
+
277
+ describe('placementOf', () => {
278
+ it('is the partition when there is one, else the community, else nothing', () => {
279
+ expect(placementOf({ partition: 'domain', badges: { communityId: 3 } })).toEqual({ kind: 'partition', id: 'domain' });
280
+ expect(placementOf({ badges: { communityId: 3, communityConfidence: 0.5 } })).toEqual({ kind: 'community', id: 3 });
281
+ expect(placementOf({ badges: { complexity: 4 } })).toBeUndefined();
282
+ expect(placementOf({})).toBeUndefined();
283
+ });
284
+
285
+ it('a trace puts an unpartitioned file in its community lane', () => {
286
+ const g = buildGraph(input2());
287
+ const t = traceGraph(g, ref('d1/a.md'), { edgeKinds: ['links'] });
288
+ expect(t.laneOf[ref('d1/a.md')]).toBe('community 0');
289
+ expect(t.laneOf[ref('d2/a.md')]).toBe('community 1');
290
+ expect(t.lanes).not.toContain('(none)');
291
+ });
292
+
293
+ it('with a registry the lanes are partitions first, then communities by numeric id', () => {
294
+ const mk = (p: string, extra: Partial<KNode>) => fileNode(p, extra);
295
+ const g: KnowledgeGraph = {
296
+ scope: { rootId: 'r', packs: [], digest: 'd' },
297
+ nodes: [
298
+ mk('a.ts', { badges: { communityId: 10 } }), mk('b.ts', { badges: { communityId: 2 } }),
299
+ mk('c.ts', { partition: 'domain' }), mk('d.ts', {}),
300
+ ],
301
+ edges: [edge('a.ts', 'b.ts', 'links'), edge('b.ts', 'c.ts', 'links'), edge('c.ts', 'd.ts', 'links')],
302
+ findings: [], stats: { sources: 4, nodes: 4, edges: 3, stale: 0, truncated: false },
303
+ };
304
+ const t = traceGraph(g, ref('a.ts'), { edgeKinds: ['links'], registry: { partitions: [{ id: 'domain', order: 0, match: [] }], allow: {} } });
305
+ // 'community 10' sorts before 'community 2' as text; by number it comes after.
306
+ expect(t.lanes).toEqual(['domain', 'community 2', 'community 10', '(none)']);
307
+ });
308
+ });
309
+
310
+ /** d1/a → d1/b → d1/c → d2/a → d2/b, plus the closing links, so both folders cluster. */
311
+ function input2(): BuildGraphInput {
312
+ const pairs: Array<[string, string]> = [
313
+ ['d1/a.md', 'd1/b.md'], ['d1/b.md', 'd1/c.md'], ['d1/a.md', 'd1/c.md'], ['d1/c.md', 'd2/a.md'],
314
+ ['d2/a.md', 'd2/b.md'], ['d2/b.md', 'd2/c.md'], ['d2/a.md', 'd2/c.md'],
315
+ ];
316
+ const files = ['d1/a.md', 'd1/b.md', 'd1/c.md', 'd2/a.md', 'd2/b.md', 'd2/c.md'];
317
+ return {
318
+ rootId: 'r', packs: [],
319
+ extracted: files.map((p) => extractedOf(fileNode(p), pairs.filter(([f]) => f === p).map(([f, t]) => edge(f, t, 'links')))),
320
+ facts: [], relations: [],
321
+ };
322
+ }