Repository navigation
Expand file tree
/
Copy pathbuild.ts
More file actions
257 lines (238 loc) · 10.6 KB
/
Copy pathbuild.ts
File metadata and controls
257 lines (238 loc) · 10.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
// Dependency-graph report — the numbers the layering gate does not enforce.
//
// node --experimental-strip-types scripts/depgraph/build.ts [--out <path>]
//
// Emits a JSON graph plus a short text summary. It reuses scripts/layering/model.ts, the same
// module check.ts uses in CI, so the file set, zone partition, edge kinds and cycle definition
// are the ones actually enforced — a second extractor would describe a graph nobody gates.
//
// What it adds over `pnpm check:layering`: value edges whose target is also reachable at distance
// >= 2 (module reachability, NOT a removability claim), cycles that are
// deliberately outside R4 (type-only and dynamic), per-zone size, and per-file fan-in/fan-out.
// See README.md for which question each field answers.
import { execFileSync } from 'node:child_process';
import fs from 'node:fs';
import path from 'node:path';
import { pathToFileURL } from 'node:url';
import { zoneRank } from '../layering/model.ts';
import { runAffected } from './affected-run.ts';
import { loadGraph } from './load.ts';
import { graphEntries, type EntryManifest } from './entries.ts';
import { computeLevels, markTransitivelyReachableEdges, type GraphData } from './model.ts';
import {
computeCohesionSummary,
createDominatorAnalyzer,
computeZoneSccSummary,
type CohesionSummary,
type DominatorSummary,
type ZoneSccSummary,
} from './structure-summary.ts';
const repoRoot = execFileSync('git', ['rev-parse', '--show-toplevel'], {
encoding: 'utf8',
}).trim();
/**
* The daemon is the one process entry point whose eager-load closure is worth asking about by
* default; `--dominator-entry` overrides it for any other file.
*/
const DEFAULT_DOMINATOR_ENTRY = 'src/daemon.ts';
/** Compact wire form. Nodes and edges are index-addressed to keep the payload small. */
type Payload = {
generated: { commit: string; files: number; edges: number };
zones: { id: string; rank: number | null; classification: string; files: number; loc: number }[];
zoneEdges: GraphData['zoneEdges'];
nodes: {
id: string;
z: number;
loc: number;
in: number;
out: number;
lvl: number;
cyc: number;
}[];
/**
* `[fromIndex, toIndex, kind, flags]`; kind 0=value 1=type 2=dynamic,
* flags bit0=R5 back-edge, bit1=target also reachable at distance >= 2, bit2=R6 type inversion.
*/
edges: [number, number, number, number][];
/** Labels aligned with `edges`; one edge may carry multiple declared-authority labels. */
edgeAuthorities: GraphData['edgeAuthorities'];
authorityCounts: GraphData['authorityCounts'];
cycles: { kind: string; path: number[] }[];
/** Type-only spine inversions per zone pair, by the gate's counting rule. */
typeInversions: Record<string, number>;
/**
* Report-only structural summaries (scripts/depgraph/structure-summary.ts): no layering or
* check-affected gate reads these fields today.
*/
entries: EntryManifest;
entrySummaries: Record<string, DominatorSummary>;
dominatorSummary: DominatorSummary;
zoneSccSummary: ZoneSccSummary;
cohesionSummary: CohesionSummary;
};
function headCommit(): string {
if (process.env.VERCEL_GIT_COMMIT_SHA) return process.env.VERCEL_GIT_COMMIT_SHA.slice(0, 10);
try {
return execFileSync('git', ['rev-parse', 'HEAD'], {
cwd: repoRoot,
encoding: 'utf8',
})
.trim()
.slice(0, 10);
} catch {
return 'unknown';
}
}
const EDGE_KIND_CODES = { value: 0, type: 1, dynamic: 2 } as const;
/** Wire code for an edge kind, so the payload carries a number rather than a string per edge. */
function edgeKindCode(kind: GraphData['edges'][number]['kind']): number {
return EDGE_KIND_CODES[kind];
}
/**
* Bitfield: 1 = spine back-edge (R5), 2 = target also reachable at distance >= 2, 4 = type-only
* inversion (R6). Bit 2 is reachability, NOT removability — see markTransitivelyReachableEdges.
*/
function edgeFlags(edge: GraphData['edges'][number]): number {
return (
(edge.backEdge ? 1 : 0) | (edge.transitivelyReachable ? 2 : 0) | (edge.typeInversion ? 4 : 0)
);
}
/** Transitive reachability is undefined on a value cycle; the report then lists the cycle instead. */
function hasValueCycle(graph: Pick<GraphData, 'cycles'>): boolean {
return graph.cycles.some((cycle) => cycle.kind === 'value');
}
function buildPayload(dominatorEntry: string): Payload {
const graph = loadGraph(repoRoot);
const dominatorsOf = createDominatorAnalyzer(graph);
const dominatorSummary = dominatorsOf(dominatorEntry);
if (!hasValueCycle(graph)) markTransitivelyReachableEdges(graph.edges);
const levels = computeLevels(graph.nodes, graph.edges);
const zoneIndex = new Map(graph.zones.map((zone, index) => [zone.id, index]));
const nodeIndex = new Map(graph.nodes.map((node, index) => [node.id, index]));
const entries = graphEntries(repoRoot, new Set(nodeIndex.keys()));
const hot = graph.nodes
.filter((n) => n.fanIn > 0)
.sort((a, b) => b.fanIn + b.fanOut - (a.fanIn + a.fanOut))
.slice(0, 300);
const selected = new Set([
...Object.values(entries)
.flat()
.map((e) => e.id),
...hot.map((n) => n.id.replace(/^src\//, '')),
dominatorEntry.replace(/^src\//, ''),
]);
const originalIds = new Map(graph.nodes.map((n) => [n.id.replace(/^src\//, ''), n.id]));
const entrySummaries = Object.fromEntries(
[...selected].map((id) => {
const original = originalIds.get(id);
if (!original)
throw new Error(`Graph entry ${id} does not identify a production source file.`);
const summary = original === dominatorEntry ? dominatorSummary : dominatorsOf(original);
return [id, { ...summary, bottlenecks: summary.bottlenecks.slice(0, 8) }];
}),
);
return {
generated: { commit: headCommit(), files: graph.nodes.length, edges: graph.edges.length },
zones: graph.zones.map((zone) => ({ ...zone, rank: zoneRank(zone.id) })),
zoneEdges: graph.zoneEdges,
nodes: graph.nodes.map((node) => ({
id: node.id.replace(/^src\//, ''),
z: zoneIndex.get(node.zone)!,
loc: node.loc,
in: node.fanIn,
out: node.fanOut,
lvl: levels.get(node.id) ?? 0,
cyc: node.cycle,
})),
edges: graph.edges.map((edge) => [
nodeIndex.get(edge.from)!,
nodeIndex.get(edge.to)!,
edgeKindCode(edge.kind),
edgeFlags(edge),
]),
edgeAuthorities: graph.edgeAuthorities,
authorityCounts: graph.authorityCounts,
cycles: graph.cycles.map((cycle) => ({
kind: cycle.kind,
path: cycle.path.map((file) => nodeIndex.get(file)!),
})),
typeInversions: graph.typeInversions,
entries,
entrySummaries,
dominatorSummary,
zoneSccSummary: computeZoneSccSummary(graph),
cohesionSummary: computeCohesionSummary(graph),
};
}
/** The text summary printed after the JSON is written; every count is read back from `payload`. */
function formatSummary(payload: Payload, jsonPath: string): string {
const valueCycles = payload.cycles.filter((cycle) => cycle.kind === 'value').length;
const otherCycles = payload.cycles.length - valueCycles;
const backEdges = payload.edges.filter(([, , , flags]) => flags & 1).length;
const transitivelyReachable =
valueCycles > 0
? 'not computed while a value-import cycle exists'
: payload.edges.filter(([, , , flags]) => flags & 2).length;
const typeInversions = Object.values(payload.typeInversions).reduce((sum, n) => sum + n, 0);
const authorityCounts = Object.entries(payload.authorityCounts)
.map(([label, count]) => `${label}=${count}`)
.join(', ');
const { dominatorSummary, zoneSccSummary, cohesionSummary } = payload;
const topBottleneck = dominatorSummary.bottlenecks[0];
const leastCohesive = cohesionSummary.zoneCohesion[0];
return (
`Dependency graph: ${payload.generated.files} files, ${payload.generated.edges} edges, ` +
`${payload.zones.length} zones\n` +
` value-import cycles (R4): ${valueCycles}\n` +
` type-only/dynamic cycles (not gate-rejected): ${otherCycles}\n` +
` spine back-edges (R5): ${backEdges}\n` +
` type-only spine inversions (R6): ${typeInversions}\n` +
` value edges whose target is also reachable at distance >= 2: ${transitivelyReachable}\n` +
` declared-authority labels: ${authorityCounts}\n` +
` (reachability only — not a removability claim, see scripts/depgraph/README.md)\n` +
` dominator summary for ${dominatorSummary.entry}: ${dominatorSummary.reachableFiles} of ` +
`${dominatorSummary.totalFiles} files loaded eagerly` +
(topBottleneck
? `, biggest branch ${topBottleneck.file} (${topBottleneck.files} files, ${topBottleneck.loc} loc)\n`
: '\n') +
` zone-level SCCs: ${zoneSccSummary.components.length} cyclic group(s) across ` +
`${zoneSccSummary.zones} zones\n` +
` modularity: declared zones ${cohesionSummary.modularity.declaredZones.toFixed(3)}, ` +
`detected communities ${cohesionSummary.modularity.detectedCommunities.toFixed(3)}` +
(leastCohesive
? `, least cohesive zone ${leastCohesive.zone} (${(leastCohesive.cohesionShare * 100).toFixed(0)}%)\n`
: '\n') +
` wrote ${path.relative(repoRoot, jsonPath)}\n`
);
}
/**
* A flag's value, or `undefined` when the flag is absent, trailing with nothing after it, or
* given an empty string — the last case matters because `?? <default>` only catches nullish
* values, and an empty `--out ""` must fall back the same way a missing one does, not resolve to
* the current directory and crash the subsequent write with EISDIR.
*/
function flagValue(argv: readonly string[], flag: string): string | undefined {
const index = argv.indexOf(flag);
const value = index >= 0 ? argv[index + 1] : undefined;
return value ? value : undefined;
}
async function main(argv: readonly string[]): Promise<number> {
// `affected` is the query subcommand (scripts/depgraph/affected-run.ts); with no subcommand
// this stays the whole-graph report.
if (argv[0] === 'affected') return await runAffected(argv.slice(1), repoRoot);
const jsonPath = path.resolve(
flagValue(argv, '--out') ?? path.join(repoRoot, '.tmp/depgraph/graph.json'),
);
const dominatorEntry = flagValue(argv, '--dominator-entry') ?? DEFAULT_DOMINATOR_ENTRY;
const payload = buildPayload(dominatorEntry);
fs.mkdirSync(path.dirname(jsonPath), { recursive: true });
fs.writeFileSync(jsonPath, `${JSON.stringify(payload, null, 2)}\n`);
process.stdout.write(formatSummary(payload, jsonPath));
return 0;
}
if (import.meta.url === pathToFileURL(process.argv[1] ?? '').href) {
process.exitCode = await main(process.argv.slice(2)).catch((error: unknown) => {
process.stderr.write(`depgraph: ${error instanceof Error ? error.message : error}\n`);
return 1;
});
}