@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.
- 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 +3 -1
- package/dist/knowledge/index.d.ts.map +1 -1
- package/dist/knowledge/index.js +1 -0
- 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 +25 -2
- 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/review.d.ts +2 -1
- package/dist/knowledge/review.d.ts.map +1 -1
- package/dist/knowledge/review.js +36 -5
- package/dist/knowledge/review.js.map +1 -1
- package/dist/knowledge/reviewRun.js +1 -1
- package/dist/knowledge/reviewRun.js.map +1 -1
- package/dist/knowledge/reviewRunModel.d.ts +1 -1
- package/dist/knowledge/reviewRunModel.d.ts.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 +9 -0
- package/src/contract/regression.review.test.ts +55 -0
- package/src/contract/types.contract.test.ts +10 -2
- 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 +7 -2
- package/src/knowledge/louvain.ts +147 -0
- package/src/knowledge/model.ts +26 -3
- package/src/knowledge/outline.test.ts +17 -5
- package/src/knowledge/outline.ts +4 -0
- package/src/knowledge/review.ts +28 -6
- package/src/knowledge/reviewRun.ts +1 -1
- package/src/knowledge/reviewRunModel.ts +1 -1
- package/src/knowledge/trace.ts +24 -4
|
@@ -0,0 +1,167 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* knowledge/communities.ts — deterministic community detection over the FILE reference graph
|
|
3
|
+
* (PRD 38 P1: a placement for every file the packs could not place, plus a membership confidence).
|
|
4
|
+
*
|
|
5
|
+
* Louvain modularity maximisation: Q = (1/2m) Σᵢⱼ [Aᵢⱼ − kᵢkⱼ/2m] δ(cᵢ,cⱼ), over the undirected graph
|
|
6
|
+
* whose edge weight is the reference count (both directions summed). Above COMMUNITY_LOUVAIN_MAX_NODES
|
|
7
|
+
* connected files, deterministic label propagation is the fallback. The algorithms live in louvain.ts.
|
|
8
|
+
*
|
|
9
|
+
* Determinism: see louvain.ts; edge weights are merged and summed in a fixed order. Same input (in any
|
|
10
|
+
* order) gives byte-identical output.
|
|
11
|
+
*
|
|
12
|
+
* A file with no references is in no community (absent, never a guess; no folder fallback).
|
|
13
|
+
*
|
|
14
|
+
* Community ids are indexes (0.. in order of each community's smallest member path). They are NOT stable
|
|
15
|
+
* across builds: a changed graph can renumber them. A consumer keeps the id only together with the graph
|
|
16
|
+
* (the outline's `communities` table) that it indexes, never as a long-lived key.
|
|
17
|
+
*/
|
|
18
|
+
|
|
19
|
+
import type { KEdge, KNode, NodeRef, OutlineCommunity } from './model.js';
|
|
20
|
+
import {
|
|
21
|
+
buildAdjacency, COMMUNITY_LP_ITERATIONS, COMMUNITY_MAX_ITERATIONS, COMMUNITY_MAX_PASSES, degreeOf, labelPropagation,
|
|
22
|
+
louvain, modularityOf,
|
|
23
|
+
} from './louvain.js';
|
|
24
|
+
import { basenameOf, compareStr, fileRefOf, pathOfRef, round6 } from './refs.js';
|
|
25
|
+
|
|
26
|
+
export { COMMUNITY_LP_ITERATIONS, COMMUNITY_MAX_ITERATIONS, COMMUNITY_MAX_PASSES };
|
|
27
|
+
|
|
28
|
+
/** Above this many connected files label propagation replaces Louvain. Separate from the outline cap. */
|
|
29
|
+
export const COMMUNITY_LOUVAIN_MAX_NODES = 20000;
|
|
30
|
+
/** The file-to-file edge kinds that count as a reference between two files (code `references`, docs `links`). */
|
|
31
|
+
export const COMMUNITY_EDGE_KINDS: readonly string[] = ['references', 'links'];
|
|
32
|
+
|
|
33
|
+
export type CommunityMethod = 'louvain' | 'label-propagation';
|
|
34
|
+
|
|
35
|
+
export interface CommunityMembership {
|
|
36
|
+
/** Index of the community: 0.. by smallest member path. Not stable across builds. */
|
|
37
|
+
communityId: number;
|
|
38
|
+
/** Share of this file's edge weight that falls inside its community, 0..1. */
|
|
39
|
+
confidence: number;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
export interface CommunityResult {
|
|
43
|
+
/** Only files with at least one reference appear. */
|
|
44
|
+
members: Map<NodeRef, CommunityMembership>;
|
|
45
|
+
/** Q of the returned partition, rounded to 6 decimals (0 with no edges). */
|
|
46
|
+
modularity: number;
|
|
47
|
+
method: CommunityMethod;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/** Where a node sits on the map: the pack's partition when it has one, else its community. */
|
|
51
|
+
export type NodePlacement = { kind: 'partition'; id: string } | { kind: 'community'; id: number };
|
|
52
|
+
|
|
53
|
+
/**
|
|
54
|
+
* Communities over `edges` (any direction; both summed). `maxNodes` is the number of connected files above
|
|
55
|
+
* which label propagation replaces Louvain.
|
|
56
|
+
*/
|
|
57
|
+
export function detectCommunities(
|
|
58
|
+
refs: readonly NodeRef[],
|
|
59
|
+
edges: ReadonlyArray<{ from: NodeRef; to: NodeRef; weight: number }>,
|
|
60
|
+
maxNodes: number = COMMUNITY_LOUVAIN_MAX_NODES,
|
|
61
|
+
): CommunityResult {
|
|
62
|
+
const order = [...new Set(refs)].sort(compareStr);
|
|
63
|
+
const adj = buildAdjacency(order, edges);
|
|
64
|
+
const connected = order.map((_, i) => i).filter((i) => adj[i]!.size > 0);
|
|
65
|
+
const method: CommunityMethod = connected.length > maxNodes ? 'label-propagation' : 'louvain';
|
|
66
|
+
const comm = connected.length === 0 ? order.map((_, i) => i) : method === 'louvain' ? louvain(adj) : labelPropagation(adj);
|
|
67
|
+
|
|
68
|
+
// Ids by first appearance over the sorted connected files: community 0 holds the smallest path.
|
|
69
|
+
const idOf = new Map<number, number>();
|
|
70
|
+
const members = new Map<NodeRef, CommunityMembership>();
|
|
71
|
+
for (const i of connected) {
|
|
72
|
+
if (!idOf.has(comm[i]!)) idOf.set(comm[i]!, idOf.size);
|
|
73
|
+
let inside = 0;
|
|
74
|
+
for (const [j, w] of adj[i]!) if (comm[j] === comm[i]) inside += w;
|
|
75
|
+
members.set(order[i]!, { communityId: idOf.get(comm[i]!)!, confidence: round6(inside / degreeOf(adj[i]!)) });
|
|
76
|
+
}
|
|
77
|
+
return { members, modularity: modularityOf(adj, comm), method };
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/**
|
|
81
|
+
* File-to-file links of the chosen kinds, merged per ordered pair. The weights of a pair are summed in ascending
|
|
82
|
+
* order, so the total never depends on the order the edges arrive in (the sort across pairs is `buildAdjacency`'s).
|
|
83
|
+
*/
|
|
84
|
+
function fileLinks(files: ReadonlySet<NodeRef>, edges: Iterable<KEdge>): Array<{ from: NodeRef; to: NodeRef; weight: number }> {
|
|
85
|
+
const pairs = new Map<string, { from: NodeRef; to: NodeRef; weights: number[] }>();
|
|
86
|
+
for (const e of edges) {
|
|
87
|
+
if (!COMMUNITY_EDGE_KINDS.includes(e.kind) || e.stale) continue;
|
|
88
|
+
const from = fileRefOf(e.from), to = fileRefOf(e.to);
|
|
89
|
+
if (!files.has(from) || !files.has(to)) continue;
|
|
90
|
+
const key = `${from}\u0000${to}`;
|
|
91
|
+
const hit = pairs.get(key);
|
|
92
|
+
if (hit) hit.weights.push(e.weight);
|
|
93
|
+
else pairs.set(key, { from, to, weights: [e.weight] });
|
|
94
|
+
}
|
|
95
|
+
return [...pairs.values()].map((p) => ({
|
|
96
|
+
from: p.from, to: p.to, weight: p.weights.sort((a, b) => a - b).reduce((s, w) => s + w, 0),
|
|
97
|
+
}));
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
/**
|
|
101
|
+
* The one call `buildGraph` makes: stamps `communityId` / `communityConfidence` badges on file nodes that
|
|
102
|
+
* have references (file-to-file edges of COMMUNITY_EDGE_KINDS, stale relations skipped) and returns Q and
|
|
103
|
+
* the method for the graph stats.
|
|
104
|
+
*/
|
|
105
|
+
export function applyCommunities(nodes: Iterable<KNode>, edges: Iterable<KEdge>): { modularity: number; method: CommunityMethod } {
|
|
106
|
+
const files = new Map<NodeRef, KNode>();
|
|
107
|
+
for (const n of nodes) if (n.kind === 'file') files.set(n.ref, n);
|
|
108
|
+
const { members, modularity, method } = detectCommunities([...files.keys()], fileLinks(new Set(files.keys()), edges));
|
|
109
|
+
for (const [ref, m] of members) {
|
|
110
|
+
const n = files.get(ref)!;
|
|
111
|
+
n.badges = { ...n.badges, communityId: m.communityId, communityConfidence: m.confidence };
|
|
112
|
+
}
|
|
113
|
+
return { modularity, method };
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
/** The ONE placement of a node: its partition, else its community, else none (never a guess). */
|
|
117
|
+
export function placementOf(node: Pick<KNode, 'partition' | 'badges'>): NodePlacement | undefined {
|
|
118
|
+
if (node.partition !== undefined) return { kind: 'partition', id: node.partition };
|
|
119
|
+
const id = node.badges?.['communityId'];
|
|
120
|
+
return typeof id === 'number' ? { kind: 'community', id } : undefined;
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
/** Longest directory shared by every path ('' when none). */
|
|
124
|
+
function commonDirectory(paths: readonly string[]): string {
|
|
125
|
+
const dirs = paths.map((p) => p.split('/').slice(0, -1));
|
|
126
|
+
const first = dirs[0] ?? [];
|
|
127
|
+
let n = first.length;
|
|
128
|
+
for (const d of dirs) {
|
|
129
|
+
let i = 0;
|
|
130
|
+
while (i < n && d[i] === first[i]) i++;
|
|
131
|
+
n = i;
|
|
132
|
+
}
|
|
133
|
+
return first.slice(0, n).join('/');
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
/**
|
|
137
|
+
* The outline's `communities` table for the given file nodes: id, a label and the member count, sorted by id.
|
|
138
|
+
* The label is the members' longest common directory (else the path of the most important member), built from
|
|
139
|
+
* the outline-relative path (`prefix` stripped, like `OutlineFile.path`). Labels are unique: two communities with
|
|
140
|
+
* the same label get ` · <top member basename>` appended, then a numeric suffix if they still collide.
|
|
141
|
+
*/
|
|
142
|
+
export function communityTable(files: readonly KNode[], prefix = ''): OutlineCommunity[] {
|
|
143
|
+
const groups = new Map<number, KNode[]>();
|
|
144
|
+
for (const n of files) {
|
|
145
|
+
const id = n.badges?.['communityId'];
|
|
146
|
+
if (typeof id !== 'number') continue;
|
|
147
|
+
const list = groups.get(id) ?? [];
|
|
148
|
+
list.push(n);
|
|
149
|
+
groups.set(id, list);
|
|
150
|
+
}
|
|
151
|
+
const relative = (n: KNode): string => (prefix !== '' && n.ref.startsWith(prefix) ? n.ref.slice(prefix.length) : (pathOfRef(n.ref) ?? n.ref));
|
|
152
|
+
const rows = [...groups.keys()].sort((a, b) => a - b).map((id) => {
|
|
153
|
+
const members = groups.get(id)!;
|
|
154
|
+
const top = [...members].sort((a, b) => b.importance - a.importance || compareStr(a.ref, b.ref))[0]!;
|
|
155
|
+
const topPath = relative(top);
|
|
156
|
+
return { id, size: members.length, base: commonDirectory(members.map(relative)) || topPath, topName: basenameOf(topPath) };
|
|
157
|
+
});
|
|
158
|
+
const count = new Map<string, number>();
|
|
159
|
+
for (const r of rows) count.set(r.base, (count.get(r.base) ?? 0) + 1);
|
|
160
|
+
const withTop = rows.map((r) => ({ ...r, label: count.get(r.base)! > 1 ? `${r.base} · ${r.topName}` : r.base }));
|
|
161
|
+
const seen = new Map<string, number>();
|
|
162
|
+
return withTop.map((r) => {
|
|
163
|
+
const n = (seen.get(r.label) ?? 0) + 1;
|
|
164
|
+
seen.set(r.label, n);
|
|
165
|
+
return { id: r.id, label: n === 1 ? r.label : `${r.label} ${n}`, size: r.size };
|
|
166
|
+
});
|
|
167
|
+
}
|
package/src/knowledge/index.ts
CHANGED
|
@@ -9,9 +9,9 @@
|
|
|
9
9
|
export type {
|
|
10
10
|
NodeRef, Origin, StoredOrigin, KNode, EdgeVerdict, KEdge, Extracted, ExtractContext, Finding, FindingRule,
|
|
11
11
|
PartitionRule, PartitionRegistry, JudgementSpec, JudgementRequest, JudgedClaim, JudgedEntity, JudgementResult,
|
|
12
|
-
JudgementPort, AnalyzerPort, KnowledgeParser, KnowledgePack, StoredFact, StoredRelation, Scope, ScopeRecord,
|
|
12
|
+
JudgementPort, AnalyzerPort, AnalyzerProgress, KnowledgeParser, KnowledgePack, StoredFact, StoredRelation, Scope, ScopeRecord,
|
|
13
13
|
KnowledgeStore, DirectorySource, LiveOverlay, KnowledgeGraph, ReviewPlan, ReviewProgress, ReviewReport,
|
|
14
|
-
ReviewArgs, BuildGraphInput, BuildGraphOptions, TraceStep, Trace, GraphOutline, OutlineFile,
|
|
14
|
+
ReviewArgs, BuildGraphInput, BuildGraphOptions, TraceStep, Trace, GraphOutline, OutlineFile, OutlineCommunity,
|
|
15
15
|
GraphSystem, GraphApp, GraphReadSkip,
|
|
16
16
|
} from './model.js';
|
|
17
17
|
export {
|
|
@@ -23,6 +23,11 @@ export { buildGraph, graphDigest, oneLineLabel, DEFAULT_MAX_NODES, MAX_NODES_CAP
|
|
|
23
23
|
export { placeInSystem, crossesSystems, type SystemPlacement } from './systems.js';
|
|
24
24
|
export { truncateGraph, TRUNCATION_HARD_CAP, UNANCHORED_AREA } from './truncate.js';
|
|
25
25
|
export type { TruncateOptions } from './truncate.js';
|
|
26
|
+
export {
|
|
27
|
+
detectCommunities, applyCommunities, communityTable, placementOf, COMMUNITY_EDGE_KINDS, COMMUNITY_LOUVAIN_MAX_NODES,
|
|
28
|
+
COMMUNITY_MAX_PASSES, COMMUNITY_MAX_ITERATIONS, COMMUNITY_LP_ITERATIONS,
|
|
29
|
+
} from './communities.js';
|
|
30
|
+
export type { CommunityMembership, CommunityMethod, CommunityResult, NodePlacement } from './communities.js';
|
|
26
31
|
export { pageRank, byImportance, areaImportance, PAGERANK_DAMPING, PAGERANK_ITERATIONS } from './importance.js';
|
|
27
32
|
export {
|
|
28
33
|
loadPartitions, partitionOf, partitionOrder, verdictOf, globToRegExp, matchGlob, TOP_LEVEL_FOLDER,
|
|
@@ -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
|
+
}
|
package/src/knowledge/model.ts
CHANGED
|
@@ -149,9 +149,12 @@ export interface JudgementPort {
|
|
|
149
149
|
judge(req: JudgementRequest): Promise<JudgementResult>;
|
|
150
150
|
}
|
|
151
151
|
|
|
152
|
-
/**
|
|
152
|
+
/** Progress an analyzer reports while it runs (files listed/read, tools finished). */
|
|
153
|
+
export interface AnalyzerProgress { done: number; total: number; path?: string }
|
|
154
|
+
|
|
155
|
+
/** Host-run tools for a pack (code: dependency-cruiser/jscpd/knip). Returns extra extracted edges/badges. `onProgress` is optional to call and to honour. */
|
|
153
156
|
export interface AnalyzerPort {
|
|
154
|
-
analyse(rootId: string, signal?: AbortSignal): Promise<Extracted[]>;
|
|
157
|
+
analyse(rootId: string, signal?: AbortSignal, onProgress?: (p: AnalyzerProgress) => void): Promise<Extracted[]>;
|
|
155
158
|
}
|
|
156
159
|
|
|
157
160
|
/** A host-supplied parser that also extracts graph structure. `extract` is the optional ingest extension. */
|
|
@@ -284,7 +287,13 @@ export interface KnowledgeGraph {
|
|
|
284
287
|
findings: Finding[];
|
|
285
288
|
/** Present only when the root held systems to report (see {@link GraphSystem}). */
|
|
286
289
|
meta?: { systems?: GraphSystem[] };
|
|
287
|
-
stats: {
|
|
290
|
+
stats: {
|
|
291
|
+
sources: number; nodes: number; edges: number; stale: number; truncated: boolean;
|
|
292
|
+
/** Q of the file communities (PRD 38 P1), 6 decimals; absent on graphs stored before it existed. */
|
|
293
|
+
modularity?: number;
|
|
294
|
+
/** Which algorithm produced the communities (label propagation above COMMUNITY_LOUVAIN_MAX_NODES connected files). */
|
|
295
|
+
communityMethod?: 'louvain' | 'label-propagation';
|
|
296
|
+
};
|
|
288
297
|
/**
|
|
289
298
|
* Attached only when the graph was truncated (`stats.truncated`): the whole graph's files,
|
|
290
299
|
* so an overview never depends on the cut. Consumers read it through `outlineOf`, never directly.
|
|
@@ -310,6 +319,11 @@ export interface GraphOutline {
|
|
|
310
319
|
apps?: string[];
|
|
311
320
|
/** The root's systems with their file counts, copies and graph reads — `KnowledgeGraph.meta.systems`, carried so the outline stands alone. */
|
|
312
321
|
systemInfo?: GraphSystem[];
|
|
322
|
+
/**
|
|
323
|
+
* The communities the files' `communityId` badge indexes (PRD 38 P1), sorted by id. Absent when no file has one.
|
|
324
|
+
* Ids are per build, not stable across builds.
|
|
325
|
+
*/
|
|
326
|
+
communities?: OutlineCommunity[];
|
|
313
327
|
/** File nodes of the full graph, sorted by ref. */
|
|
314
328
|
files: OutlineFile[];
|
|
315
329
|
/**
|
|
@@ -322,6 +336,15 @@ export interface GraphOutline {
|
|
|
322
336
|
capped: boolean;
|
|
323
337
|
}
|
|
324
338
|
|
|
339
|
+
/** One community of the file reference graph: `id` is the `communityId` badge; `label` the members' common directory (else the top member's path). */
|
|
340
|
+
export interface OutlineCommunity {
|
|
341
|
+
id: number;
|
|
342
|
+
/** Unique within the table. */
|
|
343
|
+
label: string;
|
|
344
|
+
/** Members counted in THIS outline: smaller than the full community when the outline is capped (`capped`). */
|
|
345
|
+
size: number;
|
|
346
|
+
}
|
|
347
|
+
|
|
325
348
|
export interface OutlineFile {
|
|
326
349
|
/** The ref without the outline's prefix. */
|
|
327
350
|
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]!,
|
|
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
|
|
package/src/knowledge/outline.ts
CHANGED
|
@@ -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 } : {}),
|
package/src/knowledge/review.ts
CHANGED
|
@@ -4,7 +4,8 @@
|
|
|
4
4
|
*
|
|
5
5
|
* plan (walk + manifest diff) → per changed file: read · parse (the ONE ParserRegistry,
|
|
6
6
|
* composed from the packs) · extract (cached by content hash) · judge (changed sections
|
|
7
|
-
* of judged kinds, within budget) · write · markStale → analyzers
|
|
7
|
+
* of judged kinds, within budget) · write · markStale → retire · analyse (analyzers, own `analyse`
|
|
8
|
+
* progress phase) → compare near-duplicate
|
|
8
9
|
* claims → manifest + scope digest. Claims whose compare pairs were skipped wait in the
|
|
9
10
|
* compare manifest for *Continue*.
|
|
10
11
|
* Read + extract are prefetched with bounded concurrency (`args.concurrency`; through `args.extractPool`
|
|
@@ -27,7 +28,7 @@
|
|
|
27
28
|
*/
|
|
28
29
|
|
|
29
30
|
import { sha256Hex } from '../retrieval/knowledge-index/sha256.js';
|
|
30
|
-
import type { ReviewArgs, ReviewReport, ScopeRecord, StoredFact, StoredRelation } from './model.js';
|
|
31
|
+
import type { AnalyzerProgress, ReviewArgs, ReviewReport, ScopeRecord, StoredFact, StoredRelation } from './model.js';
|
|
31
32
|
import { owedAfterRun, owedCalls, saveExtractorState } from './owedFiles.js';
|
|
32
33
|
import { planDetail, refreshPlan } from './plan.js';
|
|
33
34
|
import { composePacks, filesManifestKey, judgedManifestKey, manifestMap, saveManifestMap } from './sources.js';
|
|
@@ -317,22 +318,43 @@ async function reviewRun(args: ReviewArgs, flush: () => Promise<void>): Promise<
|
|
|
317
318
|
|
|
318
319
|
// Pass 2 (`only`) is judging alone: the map pass already retired the removed files and ran the analyzers.
|
|
319
320
|
if (!report.aborted && !args.only) {
|
|
321
|
+
// The last file is written: leave "write" now, the analyzers below can take minutes.
|
|
322
|
+
// Opened as 0/1 (not 0/0, which would close the row at once) so the row stays active until the final event below.
|
|
323
|
+
progress({ phase: 'analyse', done: 0, total: 1 });
|
|
320
324
|
await retire(detail.plan.removed);
|
|
321
325
|
// Analyzers run in parallel and a failing one never aborts the review — its extracted
|
|
322
326
|
// output is simply not stored (the file-level facts above are already durable), so a
|
|
323
|
-
// single bad pack cannot sink the whole run.
|
|
327
|
+
// single bad pack cannot sink the whole run. Each pack's latest count is kept and summed; only `done` is
|
|
328
|
+
// monotonic (a total may grow as a pack discovers more work). A callback after its pack settled is dropped.
|
|
329
|
+
const latest = new Map<number, AnalyzerProgress>();
|
|
330
|
+
const sum = () => {
|
|
331
|
+
let done = 0; let total = 0;
|
|
332
|
+
for (const v of latest.values()) { done += v.done; total += v.total; }
|
|
333
|
+
return { done, total: Math.max(1, total) };
|
|
334
|
+
};
|
|
324
335
|
const analysed = await Promise.all(
|
|
325
|
-
packs.filter((p) => p.analyzers).map(async (p) => {
|
|
326
|
-
|
|
336
|
+
packs.filter((p) => p.analyzers).map(async (p, k) => {
|
|
337
|
+
let settled = false;
|
|
338
|
+
const onProgress = (a: AnalyzerProgress) => {
|
|
339
|
+
if (settled) return;
|
|
340
|
+
latest.set(k, { done: a.done, total: a.total });
|
|
341
|
+
progress({ phase: 'analyse', ...sum(), ...(a.path !== undefined ? { path: a.path } : {}) });
|
|
342
|
+
};
|
|
343
|
+
try { return await p.analyzers!.analyse(rootId, signal, onProgress); } catch { return []; } finally { settled = true; }
|
|
327
344
|
}),
|
|
328
345
|
);
|
|
346
|
+
// Close the row whatever the analyzers reported (none, short, or a throw).
|
|
347
|
+
const closing = Math.max(1, sum().total);
|
|
348
|
+
progress({ phase: 'analyse', done: closing, total: closing });
|
|
349
|
+
// A Stop during the analyzers ends the run like one during the write loop (`runSignal` no longer follows `signal` here).
|
|
350
|
+
report.aborted ||= runSignal.aborted || !!signal?.aborted;
|
|
329
351
|
for (const packResults of analysed) {
|
|
330
352
|
for (const ex of packResults) {
|
|
331
353
|
await store.putExtracted?.(ex.sourceHash, [ex]);
|
|
332
354
|
report.extracted += 1;
|
|
333
355
|
}
|
|
334
356
|
}
|
|
335
|
-
progress({ phase: 'resolve', done: 0, total: newClaims.size });
|
|
357
|
+
if (!report.aborted) progress({ phase: 'resolve', done: 0, total: newClaims.size });
|
|
336
358
|
}
|
|
337
359
|
|
|
338
360
|
// The compare phase needs a pack asking for it AND both ports.
|
|
@@ -82,7 +82,7 @@ function withProgress(phases: ReviewRunPhase[], p: ReviewProgress, at: number):
|
|
|
82
82
|
return phases.map((x, j) => (j === i ? next : x));
|
|
83
83
|
}
|
|
84
84
|
|
|
85
|
-
const PHASE_ORDER: readonly ReviewPhase[] = ['plan', 'extract', 'resolve', 'judge', 'compare', 'write', 'index', 'mapped', 'done'];
|
|
85
|
+
const PHASE_ORDER: readonly ReviewPhase[] = ['plan', 'extract', 'resolve', 'judge', 'compare', 'write', 'analyse', 'index', 'mapped', 'done'];
|
|
86
86
|
|
|
87
87
|
/** Lanes are keyed by phase and id: extract workers and judge lanes are different workers. */
|
|
88
88
|
function withLane(lanes: ReviewRunLane[], step: ReviewStep): ReviewRunLane[] {
|
|
@@ -4,7 +4,7 @@
|
|
|
4
4
|
*/
|
|
5
5
|
|
|
6
6
|
/** `mapped` (PRD 41 A10): the mechanical pass is over and the map is complete; judging, if any is owed, follows. */
|
|
7
|
-
export type ReviewPhase = 'plan' | 'extract' | 'resolve' | 'judge' | 'compare' | 'write' | 'index' | 'mapped' | 'done';
|
|
7
|
+
export type ReviewPhase = 'plan' | 'extract' | 'resolve' | 'judge' | 'compare' | 'write' | 'analyse' | 'index' | 'mapped' | 'done';
|
|
8
8
|
|
|
9
9
|
export type ReviewStepOutcome = 'ok' | 'cached' | 'skipped' | 'failed';
|
|
10
10
|
|
package/src/knowledge/trace.ts
CHANGED
|
@@ -7,7 +7,8 @@
|
|
|
7
7
|
* touches — code layers or doc folders — and `toMermaid` draws them as a sequence diagram.
|
|
8
8
|
*/
|
|
9
9
|
|
|
10
|
-
import
|
|
10
|
+
import { placementOf } from './communities.js';
|
|
11
|
+
import type { KEdge, KNode, KnowledgeGraph, NodeRef, PartitionRegistry, Trace, TraceStep } from './model.js';
|
|
11
12
|
import { partitionOrder } from './partitions.js';
|
|
12
13
|
import { compareStr } from './refs.js';
|
|
13
14
|
|
|
@@ -30,11 +31,24 @@ export interface TraceOptions {
|
|
|
30
31
|
registry?: PartitionRegistry;
|
|
31
32
|
}
|
|
32
33
|
|
|
34
|
+
/** The lane of a community: its name, and the id the lanes are sorted by (numerically, not as text). */
|
|
35
|
+
const communityLane = (id: number): string => `community ${id}`;
|
|
36
|
+
|
|
37
|
+
function placementLane(n: KNode, communities: Map<string, number>): string | undefined {
|
|
38
|
+
const p = placementOf(n);
|
|
39
|
+
if (p === undefined) return undefined;
|
|
40
|
+
if (p.kind === 'partition') return p.id;
|
|
41
|
+
communities.set(communityLane(p.id), p.id);
|
|
42
|
+
return communityLane(p.id);
|
|
43
|
+
}
|
|
44
|
+
|
|
33
45
|
export function traceGraph(g: KnowledgeGraph, from: NodeRef, opts: TraceOptions = {}): LanedTrace {
|
|
34
46
|
const kinds = new Set(opts.edgeKinds ?? DEFAULT_TRACE_EDGE_KINDS);
|
|
35
47
|
const maxDepth = opts.maxDepth ?? DEFAULT_TRACE_DEPTH;
|
|
36
48
|
const maxSteps = opts.maxSteps ?? DEFAULT_TRACE_STEPS;
|
|
37
|
-
|
|
49
|
+
// A node's lane is its partition, else its community (PRD 38 P1), else none.
|
|
50
|
+
const communityIds = new Map<string, number>();
|
|
51
|
+
const partition = new Map(g.nodes.map((n) => [n.ref, placementLane(n, communityIds)] as const));
|
|
38
52
|
const out = new Map<NodeRef, KEdge[]>();
|
|
39
53
|
for (const e of g.edges) {
|
|
40
54
|
if (!kinds.has(e.kind)) continue;
|
|
@@ -77,8 +91,14 @@ export function traceGraph(g: KnowledgeGraph, from: NodeRef, opts: TraceOptions
|
|
|
77
91
|
}
|
|
78
92
|
if (opts.registry) {
|
|
79
93
|
const reg = opts.registry;
|
|
80
|
-
|
|
81
|
-
|
|
94
|
+
// Partitions in the registry's order, then communities by numeric id, then everything else by name.
|
|
95
|
+
const key = (l: string): [number, number] => {
|
|
96
|
+
const order = partitionOrder(l, reg);
|
|
97
|
+
if (order !== undefined) return [0, order];
|
|
98
|
+
const community = communityIds.get(l);
|
|
99
|
+
return community !== undefined ? [1, community] : [2, 0];
|
|
100
|
+
};
|
|
101
|
+
lanes.sort((a, b) => key(a)[0] - key(b)[0] || key(a)[1] - key(b)[1] || compareStr(a, b));
|
|
82
102
|
}
|
|
83
103
|
return { from, lanes, steps, truncated, laneOf };
|
|
84
104
|
}
|