@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.
Files changed (69) 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 +5 -3
  10. package/dist/knowledge/index.d.ts.map +1 -1
  11. package/dist/knowledge/index.js +2 -1
  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 +17 -0
  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/stores/extractLogWriter.d.ts +26 -0
  23. package/dist/knowledge/stores/extractLogWriter.d.ts.map +1 -0
  24. package/dist/knowledge/stores/extractLogWriter.js +60 -0
  25. package/dist/knowledge/stores/extractLogWriter.js.map +1 -0
  26. package/dist/knowledge/stores/localSnapshotStore.d.ts +48 -39
  27. package/dist/knowledge/stores/localSnapshotStore.d.ts.map +1 -1
  28. package/dist/knowledge/stores/localSnapshotStore.js +137 -179
  29. package/dist/knowledge/stores/localSnapshotStore.js.map +1 -1
  30. package/dist/knowledge/stores/rowDelta.d.ts +97 -0
  31. package/dist/knowledge/stores/rowDelta.d.ts.map +1 -0
  32. package/dist/knowledge/stores/rowDelta.js +141 -0
  33. package/dist/knowledge/stores/rowDelta.js.map +1 -0
  34. package/dist/knowledge/stores/rowMemory.d.ts +31 -0
  35. package/dist/knowledge/stores/rowMemory.d.ts.map +1 -0
  36. package/dist/knowledge/stores/rowMemory.js +85 -0
  37. package/dist/knowledge/stores/rowMemory.js.map +1 -0
  38. package/dist/knowledge/stores/rowSync.d.ts +56 -0
  39. package/dist/knowledge/stores/rowSync.d.ts.map +1 -0
  40. package/dist/knowledge/stores/rowSync.js +119 -0
  41. package/dist/knowledge/stores/rowSync.js.map +1 -0
  42. package/dist/knowledge/stores/snapshotFormat.d.ts +17 -0
  43. package/dist/knowledge/stores/snapshotFormat.d.ts.map +1 -1
  44. package/dist/knowledge/stores/snapshotFormat.js +19 -0
  45. package/dist/knowledge/stores/snapshotFormat.js.map +1 -1
  46. package/dist/knowledge/trace.d.ts.map +1 -1
  47. package/dist/knowledge/trace.js +24 -3
  48. package/dist/knowledge/trace.js.map +1 -1
  49. package/package.json +3 -3
  50. package/src/contract/exports.snapshot.json +10 -0
  51. package/src/contract/regression.rows.test.ts +377 -0
  52. package/src/contract/types.contract.test.ts +37 -5
  53. package/src/knowledge/build.test.ts +1 -1
  54. package/src/knowledge/build.ts +5 -2
  55. package/src/knowledge/communities.test.ts +322 -0
  56. package/src/knowledge/communities.ts +167 -0
  57. package/src/knowledge/index.ts +10 -3
  58. package/src/knowledge/louvain.ts +147 -0
  59. package/src/knowledge/model.ts +21 -1
  60. package/src/knowledge/outline.test.ts +17 -5
  61. package/src/knowledge/outline.ts +4 -0
  62. package/src/knowledge/stores/extractLogWriter.ts +57 -0
  63. package/src/knowledge/stores/localSnapshotStore.ts +138 -168
  64. package/src/knowledge/stores/rowDelta.test.ts +91 -0
  65. package/src/knowledge/stores/rowDelta.ts +166 -0
  66. package/src/knowledge/stores/rowMemory.ts +82 -0
  67. package/src/knowledge/stores/rowSync.ts +118 -0
  68. package/src/knowledge/stores/snapshotFormat.ts +30 -0
  69. package/src/knowledge/trace.ts +24 -4
@@ -0,0 +1,147 @@
1
+ /**
2
+ * knowledge/louvain.ts — the community-detection algorithms behind communities.ts: Louvain modularity
3
+ * maximisation and deterministic label propagation, over an undirected weighted adjacency. Pure; internal
4
+ * to the knowledge module (the public surface is communities.ts).
5
+ *
6
+ * Determinism: nodes are visited in index order; at most COMMUNITY_MAX_PASSES aggregation passes of at most
7
+ * COMMUNITY_MAX_ITERATIONS sweeps; a node stays put on a tie, otherwise the lowest community id wins;
8
+ * no randomness.
9
+ */
10
+
11
+ import type { NodeRef } from './model.js';
12
+ import { compareStr, round6 } from './refs.js';
13
+
14
+ export const COMMUNITY_MAX_PASSES = 10;
15
+ export const COMMUNITY_MAX_ITERATIONS = 20;
16
+ export const COMMUNITY_LP_ITERATIONS = 20;
17
+ const EPS = 1e-12;
18
+
19
+ export type Adj = Array<Map<number, number>>;
20
+
21
+ /** Undirected weighted graph over the sorted refs; self-references and non-positive weights are dropped. */
22
+ export function buildAdjacency(order: readonly NodeRef[], edges: ReadonlyArray<{ from: NodeRef; to: NodeRef; weight: number }>): Adj {
23
+ const index = new Map(order.map((r, i) => [r, i] as const));
24
+ const adj: Adj = order.map(() => new Map());
25
+ // Sorted, so the floating-point sums are the same whatever order the edges arrive in.
26
+ const sorted = [...edges].sort((x, y) => compareStr(x.from, y.from) || compareStr(x.to, y.to) || x.weight - y.weight);
27
+ for (const e of sorted) {
28
+ const a = index.get(e.from), b = index.get(e.to);
29
+ if (a === undefined || b === undefined || a === b || !(e.weight > 0)) continue;
30
+ adj[a]!.set(b, (adj[a]!.get(b) ?? 0) + e.weight);
31
+ adj[b]!.set(a, (adj[b]!.get(a) ?? 0) + e.weight);
32
+ }
33
+ return adj;
34
+ }
35
+
36
+ export const degreeOf = (m: Map<number, number>): number => {
37
+ let s = 0;
38
+ for (const w of m.values()) s += w;
39
+ return s;
40
+ };
41
+
42
+ /** Community ids renumbered 0.. in order of first appearance, so the next level is order-independent. */
43
+ function relabel(comm: readonly number[]): { labels: number[]; count: number } {
44
+ const next = new Map<number, number>();
45
+ const labels = comm.map((c) => {
46
+ if (!next.has(c)) next.set(c, next.size);
47
+ return next.get(c)!;
48
+ });
49
+ return { labels, count: next.size };
50
+ }
51
+
52
+ /**
53
+ * One Louvain level: each node moves to the neighbouring community with the best modularity gain. It moves only
54
+ * for a strictly better gain (a tie keeps it where it is; among tied better communities the lowest id wins).
55
+ * `self` is each node's internal weight (aggregated levels), `twoM` the total degree.
56
+ */
57
+ export function localMoving(adj: Adj, self: readonly number[], twoM: number): { comm: number[]; count: number; moved: boolean } {
58
+ const n = adj.length;
59
+ const comm = Array.from({ length: n }, (_, i) => i);
60
+ const k = adj.map((m, i) => degreeOf(m) + 2 * self[i]!);
61
+ const tot = [...k];
62
+ let moved = false;
63
+ for (let it = 0; it < COMMUNITY_MAX_ITERATIONS; it++) {
64
+ let changed = false;
65
+ for (let i = 0; i < n; i++) {
66
+ const own = comm[i]!;
67
+ const links = new Map<number, number>();
68
+ for (const [j, w] of adj[i]!) links.set(comm[j]!, (links.get(comm[j]!) ?? 0) + w);
69
+ tot[own]! -= k[i]!;
70
+ const gain = (c: number) => (links.get(c) ?? 0) - (tot[c]! * k[i]!) / twoM;
71
+ let best = own, bestGain = gain(own);
72
+ for (const c of [...links.keys()].sort((a, b) => a - b)) {
73
+ if (c === own) continue;
74
+ const g = gain(c);
75
+ if (g > bestGain + EPS) { best = c; bestGain = g; }
76
+ }
77
+ tot[best]! += k[i]!;
78
+ if (best !== own) { comm[i] = best; changed = true; moved = true; }
79
+ }
80
+ if (!changed) break;
81
+ }
82
+ const { labels, count } = relabel(comm);
83
+ return { comm: labels, count, moved };
84
+ }
85
+
86
+ /** Louvain: local moving, then aggregation, up to COMMUNITY_MAX_PASSES; returns a community label per node. */
87
+ export function louvain(adj0: Adj): number[] {
88
+ let adj = adj0;
89
+ let self: number[] = adj0.map(() => 0);
90
+ const twoM = adj0.reduce((s, m) => s + degreeOf(m), 0);
91
+ let membership = adj0.map((_, i) => i);
92
+ for (let pass = 0; pass < COMMUNITY_MAX_PASSES; pass++) {
93
+ const { comm, count, moved } = localMoving(adj, self, twoM);
94
+ if (!moved) break;
95
+ membership = membership.map((c) => comm[c]!);
96
+ const nextAdj: Adj = Array.from({ length: count }, () => new Map());
97
+ const nextSelf: number[] = new Array<number>(count).fill(0);
98
+ for (let i = 0; i < adj.length; i++) {
99
+ nextSelf[comm[i]!]! += self[i]!;
100
+ for (const [j, w] of adj[i]!) {
101
+ const a = comm[i]!, b = comm[j]!;
102
+ if (a === b) nextSelf[a]! += w / 2; // each internal pair is seen from both ends
103
+ else nextAdj[a]!.set(b, (nextAdj[a]!.get(b) ?? 0) + w);
104
+ }
105
+ }
106
+ adj = nextAdj;
107
+ self = nextSelf;
108
+ if (count === 1) break;
109
+ }
110
+ return membership;
111
+ }
112
+
113
+ /** Deterministic label propagation: sorted order, each node takes the heaviest neighbour label; it keeps its own on a tie, else the smallest label wins. */
114
+ export function labelPropagation(adj: Adj): number[] {
115
+ const label = adj.map((_, i) => i);
116
+ for (let it = 0; it < COMMUNITY_LP_ITERATIONS; it++) {
117
+ let changed = false;
118
+ for (let i = 0; i < adj.length; i++) {
119
+ const votes = new Map<number, number>();
120
+ for (const [j, w] of adj[i]!) votes.set(label[j]!, (votes.get(label[j]!) ?? 0) + w);
121
+ let best = label[i]!, bestW = votes.get(best) ?? 0;
122
+ for (const l of [...votes.keys()].sort((a, b) => a - b)) {
123
+ if (votes.get(l)! > bestW + EPS) { best = l; bestW = votes.get(l)!; }
124
+ }
125
+ if (best !== label[i]) { label[i] = best; changed = true; }
126
+ }
127
+ if (!changed) break;
128
+ }
129
+ return label;
130
+ }
131
+
132
+ /** Q = Σc [Lc/m − (Dc/2m)²] for a partition of the undirected graph, 6 decimals. */
133
+ export function modularityOf(adj: Adj, comm: readonly number[]): number {
134
+ let twoM = 0;
135
+ const inside = new Map<number, number>(), degree = new Map<number, number>();
136
+ for (let i = 0; i < adj.length; i++) {
137
+ for (const [j, w] of adj[i]!) {
138
+ twoM += w;
139
+ degree.set(comm[i]!, (degree.get(comm[i]!) ?? 0) + w);
140
+ if (comm[i] === comm[j]) inside.set(comm[i]!, (inside.get(comm[i]!) ?? 0) + w);
141
+ }
142
+ }
143
+ if (twoM === 0) return 0;
144
+ let q = 0;
145
+ for (const [c, d] of degree) q += (inside.get(c) ?? 0) / twoM - (d / twoM) ** 2;
146
+ return round6(q);
147
+ }
@@ -284,7 +284,13 @@ export interface KnowledgeGraph {
284
284
  findings: Finding[];
285
285
  /** Present only when the root held systems to report (see {@link GraphSystem}). */
286
286
  meta?: { systems?: GraphSystem[] };
287
- stats: { sources: number; nodes: number; edges: number; stale: number; truncated: boolean };
287
+ stats: {
288
+ sources: number; nodes: number; edges: number; stale: number; truncated: boolean;
289
+ /** Q of the file communities (PRD 38 P1), 6 decimals; absent on graphs stored before it existed. */
290
+ modularity?: number;
291
+ /** Which algorithm produced the communities (label propagation above COMMUNITY_LOUVAIN_MAX_NODES connected files). */
292
+ communityMethod?: 'louvain' | 'label-propagation';
293
+ };
288
294
  /**
289
295
  * Attached only when the graph was truncated (`stats.truncated`): the whole graph's files,
290
296
  * so an overview never depends on the cut. Consumers read it through `outlineOf`, never directly.
@@ -310,6 +316,11 @@ export interface GraphOutline {
310
316
  apps?: string[];
311
317
  /** The root's systems with their file counts, copies and graph reads — `KnowledgeGraph.meta.systems`, carried so the outline stands alone. */
312
318
  systemInfo?: GraphSystem[];
319
+ /**
320
+ * The communities the files' `communityId` badge indexes (PRD 38 P1), sorted by id. Absent when no file has one.
321
+ * Ids are per build, not stable across builds.
322
+ */
323
+ communities?: OutlineCommunity[];
313
324
  /** File nodes of the full graph, sorted by ref. */
314
325
  files: OutlineFile[];
315
326
  /**
@@ -322,6 +333,15 @@ export interface GraphOutline {
322
333
  capped: boolean;
323
334
  }
324
335
 
336
+ /** One community of the file reference graph: `id` is the `communityId` badge; `label` the members' common directory (else the top member's path). */
337
+ export interface OutlineCommunity {
338
+ id: number;
339
+ /** Unique within the table. */
340
+ label: string;
341
+ /** Members counted in THIS outline: smaller than the full community when the outline is capped (`capped`). */
342
+ size: number;
343
+ }
344
+
325
345
  export interface OutlineFile {
326
346
  /** The ref without the outline's prefix. */
327
347
  path: string;
@@ -13,9 +13,9 @@ import { edge, extractedOf, fileNode, ref, ROOT } from './testkit.test-util.js';
13
13
  const PACK: KnowledgePack = { id: 'docs', parsers: [] };
14
14
  const pad = (i: number) => `p/${String(i).padStart(6, '0')}.ts`;
15
15
 
16
- function chain(extra: Partial<KNode> = {}): BuildGraphInput {
16
+ function chain(extra: Partial<KNode> = {}, kind = 'references'): BuildGraphInput {
17
17
  const paths = Array.from({ length: 40 }, (_, i) => `d${i % 4}/f${String(i).padStart(2, '0')}.md`);
18
- const extracted = paths.map((p, i) => extractedOf(fileNode(p, extra), i + 1 < paths.length ? [edge(p, paths[i + 1]!, 'references')] : []));
18
+ const extracted = paths.map((p, i) => extractedOf(fileNode(p, extra), i + 1 < paths.length ? [edge(p, paths[i + 1]!, kind)] : []));
19
19
  return { rootId: ROOT, packs: [PACK], extracted, facts: [], relations: [] };
20
20
  }
21
21
 
@@ -77,19 +77,31 @@ describe('buildGraph outline', () => {
77
77
  expect(JSON.stringify(a.outline)).toBe(JSON.stringify(b.outline));
78
78
  });
79
79
 
80
+ // 'mentions' edges are not references, so these files have no community badges (PRD 38 P1) and the cases below are about the whitelist alone.
80
81
  it('keeps only the whitelisted badges', () => {
81
- const g = buildGraph(chain({ badges: { complexity: 7, entry: 'main', secret: 'x', added: 3, status: 'M' } }), { maxNodes: 6 });
82
+ const g = buildGraph(chain({ badges: { complexity: 7, entry: 'main', secret: 'x', added: 3, status: 'M' } }, 'mentions'), { maxNodes: 6 });
82
83
  for (const f of g.outline!.files) expect(f.badges).toEqual({ complexity: 7, entry: 'main', added: 3, status: 'M' });
83
84
  });
84
85
 
85
86
  it('keeps the externals string badge and still drops unlisted ones', () => {
86
- const g = buildGraph(chain({ badges: { externals: 'react,zod', notListed: 'x' } }), { maxNodes: 6 });
87
+ const g = buildGraph(chain({ badges: { externals: 'react,zod', notListed: 'x' } }, 'mentions'), { maxNodes: 6 });
87
88
  for (const f of g.outline!.files) expect(f.badges).toEqual({ externals: 'react,zod' });
88
89
  });
89
90
 
90
91
  it('omits badges when none of the whitelisted keys are present', () => {
91
- const g = buildGraph(chain({ badges: { other: 3 } }), { maxNodes: 6 });
92
+ const g = buildGraph(chain({ badges: { other: 3 } }, 'mentions'), { maxNodes: 6 });
92
93
  for (const f of g.outline!.files) expect(f.badges).toBeUndefined();
94
+ expect(g.outline!.communities).toBeUndefined();
95
+ });
96
+
97
+ it('carries the community badges and the communities table of referenced files', () => {
98
+ const g = buildGraph(chain(), { maxNodes: 6 });
99
+ for (const f of g.outline!.files) expect(Object.keys(f.badges ?? {}).sort()).toEqual(['communityConfidence', 'communityId']);
100
+ const table = g.outline!.communities!;
101
+ expect(table.length).toBeGreaterThan(0);
102
+ expect(table.reduce((s, c) => s + c.size, 0)).toBe(g.outline!.files.length);
103
+ expect(table.map((c) => c.id)).toEqual([...table.map((c) => c.id)].sort((a, b) => a - b));
104
+ for (const f of g.outline!.files) expect(table.some((c) => c.id === f.badges!['communityId'])).toBe(true);
93
105
  });
94
106
  });
95
107
 
@@ -5,6 +5,7 @@
5
5
  */
6
6
 
7
7
  import type { EdgeVerdict, GraphOutline, KnowledgeGraph, NodeRef, OutlineFile } from './model.js';
8
+ import { communityTable } from './communities.js';
8
9
  import { byImportance } from './importance.js';
9
10
  import { compareStr, fileRefOf } from './refs.js';
10
11
 
@@ -17,6 +18,7 @@ export const OUTLINE_MAX_LINKS = 60000;
17
18
  export const OUTLINE_BADGE_KEYS: readonly string[] = [
18
19
  'complexity', 'maxComplexity', 'coverage', 'churn', 'owner', 'patterns', 'cloneGroup', 'unused', 'unusedExports',
19
20
  'entry', 'layerRule', 'unusedDependencies', 'externals', 'added', 'removed', 'changed', 'status',
21
+ 'communityId', 'communityConfidence',
20
22
  ];
21
23
  /** Verdict codes of a link, least to worst; code 0 is "no verdict". */
22
24
  export const OUTLINE_VERDICTS: readonly ('none' | EdgeVerdict)[] = ['none', 'same', 'allowed', 'skips', 'upward'];
@@ -112,8 +114,10 @@ export function buildOutline(full: KnowledgeGraph): GraphOutline {
112
114
  }
113
115
  list.sort((a, b) => a.from - b.from || a.to - b.to);
114
116
  const links = list.map((m) => [m.from, m.to, m.verdict, m.cycle ? OUTLINE_FLAG_CYCLE : 0] as [number, number, number, number]);
117
+ const communities = communityTable(fileNodes, prefix);
115
118
  return {
116
119
  prefix, areas, partitions,
120
+ ...(communities.length > 0 ? { communities } : {}),
117
121
  ...(systems.length > 0 ? { systems } : {}),
118
122
  ...(apps.length > 0 ? { apps } : {}),
119
123
  ...(full.meta?.systems ? { systemInfo: full.meta.systems } : {}),
@@ -0,0 +1,57 @@
1
+ /**
2
+ * knowledge/stores/extractLogWriter.ts — the write side of the extract cache's append-only log (PRD 41 A10 rule 7), moved
3
+ * out of {@link LocalSnapshotStore}. It owns what is not yet appended and whether the log's last line is torn; the store
4
+ * owns WHEN to flush (inside `persistIfDirty`). No behaviour of its own beyond the log port.
5
+ */
6
+
7
+ import type { Extracted } from '../model.js';
8
+ import type { ExtractedLogPersistence } from './localSnapshotStore.js';
9
+ import { parseLog } from './snapshotFormat.js';
10
+
11
+ export class ExtractLogWriter {
12
+ /** Entries not yet appended. */
13
+ private pending = new Map<string, Extracted[]>();
14
+ /** The log's last line is torn (no newline), so the next append starts on a fresh line. */
15
+ private torn = false;
16
+
17
+ constructor(private readonly port: ExtractedLogPersistence) {}
18
+
19
+ read(): Promise<string | undefined> { return this.port.read(); }
20
+
21
+ /** Queues an entry for the next {@link flush}. */
22
+ queue(hash: string, entries: Extracted[]): void { this.pending.set(hash, entries); }
23
+
24
+ /** Fills `into` from the log's text (last line per hash wins) and compacts the log when dead bytes exceed live bytes. */
25
+ async load(text: string | undefined, into: Map<string, Extracted[]>): Promise<void> {
26
+ const parsed = parseLog(text);
27
+ for (const [h, e] of parsed.entries) into.set(h, e);
28
+ this.torn = !!text && !text.endsWith('\n');
29
+ // Needs the port's `replace`; a failure is ignored (the log stays correct, only larger). Another window appending between
30
+ // this read and the replace loses those lines from the cache — a cache miss, re-extracted next review.
31
+ if (!this.port.replace || parsed.deadBytes <= parsed.liveBytes) return;
32
+ try {
33
+ await this.port.replace([...parsed.liveLines.values()].join(''));
34
+ this.torn = false;
35
+ } catch { /* keep the uncompacted log */ }
36
+ }
37
+
38
+ /**
39
+ * Appends the not-yet-logged entries as ONE `append` of complete lines. A failed append keeps them pending and marks the
40
+ * log torn (it may hold a partial line), so the next append starts on a fresh line.
41
+ */
42
+ async flush(): Promise<void> {
43
+ if (this.pending.size === 0) return;
44
+ const batch = this.pending;
45
+ this.pending = new Map();
46
+ let text = this.torn ? '\n' : '';
47
+ for (const [h, e] of batch) text += `${JSON.stringify({ h, e })}\n`;
48
+ try {
49
+ await this.port.append(text);
50
+ this.torn = false;
51
+ } catch (err) {
52
+ this.torn = true;
53
+ for (const [h, e] of batch) if (!this.pending.has(h)) this.pending.set(h, e);
54
+ throw err;
55
+ }
56
+ }
57
+ }