-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdiff.js
More file actions
367 lines (323 loc) · 11.8 KB
/
diff.js
File metadata and controls
367 lines (323 loc) · 11.8 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
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
/**
* @module diff
* Graph diff computation between two historical points in time.
*
* Compares two materialized graph snapshots and reports node/edge changes.
*
* ## Edge identity invariant
* Edge uniqueness is `(source, target, type)` — guaranteed by git-warp's
* `addEdge` semantics (re-adding the same triple updates props, doesn't
* duplicate). The `edgeKey()` helper relies on this invariant.
*
* ## System prefix exclusion
* System-generated prefixes (`decision`, `commit`, `epoch`) are excluded
* from diff output, matching `src/export.js` behavior.
*
* ## Prefix filter edge inclusion rule
* When `prefix` option is specified, an edge is included **only if both
* endpoints pass the prefix filter**. No partial cross-prefix edges.
*/
import { initGraph } from './graph.js';
import { getEpochForRef } from './epoch.js';
import { extractPrefix } from './validators.js';
/** Node prefixes excluded from diff (system-generated). */
const EXCLUDED_PREFIXES = new Set(['decision', 'commit', 'epoch']);
/**
* @typedef {object} EdgeDiffEntry
* @property {string} source
* @property {string} target
* @property {string} type
*/
/**
* @typedef {object} DiffEndpoint
* @property {string} ref - Original git ref
* @property {string} sha - Resolved commit SHA (short)
* @property {number} tick - Lamport tick used for materialization
* @property {boolean} nearest - Whether a nearest-epoch fallback was used
*/
/**
* @typedef {object} DiffResult
* @property {number} schemaVersion
* @property {DiffEndpoint} from
* @property {DiffEndpoint} to
* @property {{ added: string[], removed: string[], total: { before: number, after: number } | null }} nodes
* @property {{ added: EdgeDiffEntry[], removed: EdgeDiffEntry[], total: { before: number, after: number } | null }} edges
* @property {{ nodesByPrefix: Record<string, {before: number, after: number}>, edgesByType: Record<string, {before: number, after: number}> }} summary
* @property {{ materializeMs: { a: number, b: number }, diffMs: number, nodeCount: { a: number, b: number }, edgeCount: { a: number, b: number } }} stats
*/
/**
* Compute a unique key for an edge based on (source, target, type).
* Uses null byte separator to avoid collisions.
*
* @param {{ from: string, to: string, label: string }} edge
* @returns {string}
*/
export function edgeKey(edge) {
return `${edge.from}\0${edge.to}\0${edge.label}`;
}
/**
* Stable comparator for edges: sort by (type, source, target).
*
* @param {EdgeDiffEntry} a
* @param {EdgeDiffEntry} b
* @returns {number}
*/
export function compareEdge(a, b) {
return a.type.localeCompare(b.type)
|| a.source.localeCompare(b.source)
|| a.target.localeCompare(b.target);
}
/**
* Compute summary counts for nodes by prefix and edges by type.
*
* @param {string[]} nodesA
* @param {string[]} nodesB
* @param {Array<{from: string, to: string, label: string}>} edgesA
* @param {Array<{from: string, to: string, label: string}>} edgesB
* @returns {{ nodesByPrefix: Record<string, {before: number, after: number}>, edgesByType: Record<string, {before: number, after: number}> }}
*/
export function computeSummary(nodesA, nodesB, edgesA, edgesB) {
// Nodes by prefix
const prefixCountA = {};
const prefixCountB = {};
for (const id of nodesA) {
const p = extractPrefix(id) ?? '(none)';
prefixCountA[p] = (prefixCountA[p] ?? 0) + 1;
}
for (const id of nodesB) {
const p = extractPrefix(id) ?? '(none)';
prefixCountB[p] = (prefixCountB[p] ?? 0) + 1;
}
const allPrefixes = new Set([...Object.keys(prefixCountA), ...Object.keys(prefixCountB)]);
const nodesByPrefix = {};
for (const p of [...allPrefixes].sort()) {
nodesByPrefix[p] = { before: prefixCountA[p] ?? 0, after: prefixCountB[p] ?? 0 };
}
// Edges by type
const typeCountA = {};
const typeCountB = {};
for (const e of edgesA) {
typeCountA[e.label] = (typeCountA[e.label] ?? 0) + 1;
}
for (const e of edgesB) {
typeCountB[e.label] = (typeCountB[e.label] ?? 0) + 1;
}
const allTypes = new Set([...Object.keys(typeCountA), ...Object.keys(typeCountB)]);
const edgesByType = {};
for (const t of [...allTypes].sort()) {
edgesByType[t] = { before: typeCountA[t] ?? 0, after: typeCountB[t] ?? 0 };
}
return { nodesByPrefix, edgesByType };
}
/**
* Compare two materialized graph instances and return a diff.
* This is a pure comparison — both graphs must already be materialized.
*
* @param {import('@git-stunts/git-warp').default} graphA - "before" graph
* @param {import('@git-stunts/git-warp').default} graphB - "after" graph
* @param {{ prefix?: string }} [opts]
* @returns {Promise<{ nodes: { added: string[], removed: string[], total: { before: number, after: number } }, edges: { added: EdgeDiffEntry[], removed: EdgeDiffEntry[], total: { before: number, after: number } }, summary: object }>}
*/
export async function diffSnapshots(graphA, graphB, opts = {}) {
const prefixFilter = opts.prefix ?? null;
const allNodesA = await graphA.getNodes();
const allNodesB = await graphB.getNodes();
// Filter nodes: exclude system prefixes, apply prefix filter
const filterNode = (id) => {
const prefix = extractPrefix(id);
if (prefix && EXCLUDED_PREFIXES.has(prefix)) return false;
if (prefixFilter && prefix !== prefixFilter) return false;
return true;
};
const nodesA = allNodesA.filter(filterNode);
const nodesB = allNodesB.filter(filterNode);
const setA = new Set(nodesA);
const setB = new Set(nodesB);
const addedNodes = nodesB.filter(id => !setA.has(id)).sort();
const removedNodes = nodesA.filter(id => !setB.has(id)).sort();
// Edges: only include edges where both endpoints are in the filtered node set
const allEdgesA = await graphA.getEdges();
const allEdgesB = await graphB.getEdges();
const filterEdge = (edge, nodeSet) => {
return nodeSet.has(edge.from) && nodeSet.has(edge.to);
};
const edgesA = allEdgesA.filter(e => filterEdge(e, setA));
const edgesB = allEdgesB.filter(e => filterEdge(e, setB));
const edgeMapA = new Set(edgesA.map(edgeKey));
const edgeMapB = new Set(edgesB.map(edgeKey));
const addedEdges = edgesB
.filter(e => !edgeMapA.has(edgeKey(e)))
.map(e => ({ source: e.from, target: e.to, type: e.label }))
.sort(compareEdge);
const removedEdges = edgesA
.filter(e => !edgeMapB.has(edgeKey(e)))
.map(e => ({ source: e.from, target: e.to, type: e.label }))
.sort(compareEdge);
const summary = computeSummary(nodesA, nodesB, edgesA, edgesB);
return {
nodes: {
added: addedNodes,
removed: removedNodes,
total: { before: nodesA.length, after: nodesB.length },
},
edges: {
added: addedEdges,
removed: removedEdges,
total: { before: edgesA.length, after: edgesB.length },
},
summary,
};
}
/**
* Parse diff ref arguments from CLI args.
* Supports: `A..B`, `A B`, `A` (shorthand for `A..HEAD`).
* Rejects: `A..B..C`, `..B`, `A..`, empty.
*
* @param {string[]} args - Non-flag arguments after the `diff` command
* @returns {{ refA: string, refB: string }}
*/
export function parseDiffRefs(args) {
if (!args || args.length === 0) {
throw new Error('Usage: git mind diff <ref-a>..<ref-b> or git mind diff <ref-a> <ref-b> or git mind diff <ref>');
}
// Two-arg syntax: A B
if (args.length >= 2) {
return { refA: args[0], refB: args[1] };
}
// Single arg — might be range syntax or shorthand
const arg = args[0];
// Check for range syntax
const parts = arg.split('..');
if (parts.length > 2) {
throw new Error(`Malformed range: "${arg}". Expected "ref-a..ref-b", got multiple ".." separators.`);
}
if (parts.length === 2) {
if (!parts[0]) {
throw new Error(`Malformed range: "${arg}". Left side of ".." is empty.`);
}
if (!parts[1]) {
throw new Error(`Malformed range: "${arg}". Right side of ".." is empty.`);
}
return { refA: parts[0], refB: parts[1] };
}
// Single ref — shorthand for ref..HEAD
return { refA: arg, refB: 'HEAD' };
}
/** Boolean flags that don't consume the next arg. */
const DIFF_BOOLEAN_FLAGS = new Set(['json']);
/**
* Collect positional args from a diff command's arg list,
* skipping --flag and their consumed values.
*
* @param {string[]} args - Args after the `diff` command word
* @returns {string[]} Positional (non-flag) arguments
*/
export function collectDiffPositionals(args) {
const positionals = [];
for (let i = 0; i < args.length; i++) {
if (args[i].startsWith('--')) {
const name = args[i].slice(2);
if (!DIFF_BOOLEAN_FLAGS.has(name)) i++; // skip the flag's value
} else {
positionals.push(args[i]);
}
}
return positionals;
}
/**
* Full diff orchestrator: resolve epochs, materialize graphs, compute diff.
*
* Opens three graph instances:
* 1. Resolver — unmaterialized, used to resolve both refs to epoch ticks
* 2. Graph A — materialized at tick A ("before")
* 3. Graph B — materialized at tick B ("after")
*
* Three instances are needed because `materialize({ ceiling })` is
* destructive (no unmaterialize).
*
* @param {string} cwd - Repository working directory
* @param {string} refA - "before" git ref
* @param {string} refB - "after" git ref
* @param {{ prefix?: string }} [opts]
* @returns {Promise<DiffResult>}
*/
export async function computeDiff(cwd, refA, refB, opts = {}) {
// 1. Resolve both refs to epochs using a resolver graph
const resolver = await initGraph(cwd, { writerId: 'diff-resolver' });
const resultA = await getEpochForRef(resolver, cwd, refA);
if (!resultA) {
throw new Error(`No epoch found for "${refA}" or its ancestors. Run "git mind process-commit" to record epoch markers.`);
}
const resultB = await getEpochForRef(resolver, cwd, refB);
if (!resultB) {
throw new Error(`No epoch found for "${refB}" or its ancestors. Run "git mind process-commit" to record epoch markers.`);
}
const tickA = resultA.epoch.tick;
const tickB = resultB.epoch.tick;
// Same tick → skipped diff (not computed, graph unchanged)
if (tickA === tickB) {
return {
schemaVersion: 1,
from: {
ref: refA,
sha: resultA.sha.slice(0, 8),
tick: tickA,
nearest: resultA.epoch.nearest ?? false,
},
to: {
ref: refB,
sha: resultB.sha.slice(0, 8),
tick: tickB,
nearest: resultB.epoch.nearest ?? false,
},
nodes: { added: [], removed: [], total: null },
edges: { added: [], removed: [], total: null },
summary: { nodesByPrefix: {}, edgesByType: {} },
stats: {
sameTick: true,
skipped: true,
materializeMs: { a: 0, b: 0 },
diffMs: 0,
nodeCount: { a: 0, b: 0 },
edgeCount: { a: 0, b: 0 },
},
};
}
// 2. Materialize two separate graph instances
const startA = Date.now();
const graphA = await initGraph(cwd, { writerId: 'diff-a' });
await graphA.materialize({ ceiling: tickA });
const msA = Date.now() - startA;
const startB = Date.now();
const graphB = await initGraph(cwd, { writerId: 'diff-b' });
await graphB.materialize({ ceiling: tickB });
const msB = Date.now() - startB;
// 3. Compute diff
const startDiff = Date.now();
const diff = await diffSnapshots(graphA, graphB, { prefix: opts.prefix });
const msDiff = Date.now() - startDiff;
return {
schemaVersion: 1,
from: {
ref: refA,
sha: resultA.sha.slice(0, 8),
tick: tickA,
nearest: resultA.epoch.nearest ?? false,
},
to: {
ref: refB,
sha: resultB.sha.slice(0, 8),
tick: tickB,
nearest: resultB.epoch.nearest ?? false,
},
nodes: diff.nodes,
edges: diff.edges,
summary: diff.summary,
stats: {
materializeMs: { a: msA, b: msB },
diffMs: msDiff,
nodeCount: { a: diff.nodes.total.before, b: diff.nodes.total.after },
edgeCount: { a: diff.edges.total.before, b: diff.edges.total.after },
},
};
}