-
Notifications
You must be signed in to change notification settings - Fork 11
Expand file tree
/
Copy pathdiff.go
More file actions
494 lines (453 loc) · 16.8 KB
/
Copy pathdiff.go
File metadata and controls
494 lines (453 loc) · 16.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
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
// Package diff computes the delta between two architecture snapshots.
//
// Unlike a linter, which judges a snapshot against an external ideal, a diff
// judges the current snapshot against the codebase's OWN prior state. That makes
// it a ratchet rather than a ruler: it reports only what CHANGED — facts added or
// removed, new coupling edges, findings that newly appeared or were resolved —
// and stays silent about pre-existing state. A pattern that was "wrong" before and
// after (e.g. an API-first route with no loaded consumer) produces no delta, so
// the diff is structurally immune to the false-signal problem.
//
// Compute is pure and deterministic: identical inputs always yield byte-identical
// output (every collection is sorted by a stable key), so a diff is reproducible
// and even diffs-of-diffs are stable.
package diff
import (
"encoding/json"
"fmt"
"regexp"
"sort"
"strings"
"github.com/enola-labs/enola/internal/facts"
)
// Edge is a directed relation between two facts, identified at the
// name level (not file/line) so that moving a symbol between files does not churn
// its edges — what matters for coupling is "X depends on Y", not where X lives.
type Edge struct {
Source string `json:"source"`
Kind string `json:"kind"`
Target string `json:"target"`
Repo string `json:"repo,omitempty"`
}
// FactChange records a fact present in both snapshots whose own attributes
// (props such as signature, exported, cyclomatic) changed. Line-only shifts are
// deliberately NOT treated as changes — an edit above a symbol moves every symbol
// below it, which would flood the diff with noise that says nothing architectural.
type FactChange struct {
Before facts.Fact `json:"before"`
After facts.Fact `json:"after"`
}
// SnapshotDiff is the delta between a baseline and a current snapshot.
type SnapshotDiff struct {
BaselineRepo string `json:"baseline_repo,omitempty"`
CurrentRepo string `json:"current_repo,omitempty"`
BaselineGeneratedAt string `json:"baseline_generated_at,omitempty"`
CurrentGeneratedAt string `json:"current_generated_at,omitempty"`
// Structural changes.
FactsAdded []facts.Fact `json:"facts_added,omitempty"`
FactsRemoved []facts.Fact `json:"facts_removed,omitempty"`
FactsChanged []FactChange `json:"facts_changed,omitempty"`
EdgesAdded []Edge `json:"edges_added,omitempty"`
EdgesRemoved []Edge `json:"edges_removed,omitempty"`
// Findings delta (the ratchet core). FindingsNew are regressions introduced
// by the change; FindingsResolved are issues the change cleared. Each carries
// through its original Confidence and Description (caveats intact) untouched —
// the diff manufactures no verdicts. Only findings with a STRUCTURAL CAUSE in
// this change (an evidence entity that was added/removed/changed) land here.
FindingsNew []facts.Insight `json:"findings_new,omitempty"`
FindingsResolved []facts.Insight `json:"findings_resolved,omitempty"`
// Incidental finding shifts: findings that appeared or cleared with NO
// structural cause in this change — a moving statistical threshold (mean+2σ) or
// a re-ranked top-N list whose membership shifted because some OTHER finding
// left the window. These are surfaced separately so they don't masquerade as
// regressions/improvements the change actually caused.
FindingsNewIncidental []facts.Insight `json:"findings_new_incidental,omitempty"`
FindingsResolvedIncidental []facts.Insight `json:"findings_resolved_incidental,omitempty"`
}
// Compute returns the delta from baseline to current. A nil snapshot is treated
// as empty (so the first diff against no baseline reports everything as added).
func Compute(baseline, current *facts.Snapshot) *SnapshotDiff {
d := &SnapshotDiff{}
if baseline != nil {
d.BaselineRepo = baseline.Meta.RepoPath
d.BaselineGeneratedAt = baseline.Meta.GeneratedAt
}
if current != nil {
d.CurrentRepo = current.Meta.RepoPath
d.CurrentGeneratedAt = current.Meta.GeneratedAt
}
baseFacts := snapFacts(baseline)
curFacts := snapFacts(current)
baseByKey := make(map[string]facts.Fact, len(baseFacts))
for _, f := range baseFacts {
baseByKey[factKey(f)] = f
}
curByKey := make(map[string]facts.Fact, len(curFacts))
for _, f := range curFacts {
curByKey[factKey(f)] = f
}
for k, cf := range curByKey {
bf, ok := baseByKey[k]
if !ok {
d.FactsAdded = append(d.FactsAdded, cf)
continue
}
if propsChanged(bf, cf) {
d.FactsChanged = append(d.FactsChanged, FactChange{Before: bf, After: cf})
}
}
for k, bf := range baseByKey {
if _, ok := curByKey[k]; !ok {
d.FactsRemoved = append(d.FactsRemoved, bf)
}
}
baseEdges := edgeSet(baseFacts)
curEdges := edgeSet(curFacts)
for k, e := range curEdges {
if _, ok := baseEdges[k]; !ok {
d.EdgesAdded = append(d.EdgesAdded, e)
}
}
for k, e := range baseEdges {
if _, ok := curEdges[k]; !ok {
d.EdgesRemoved = append(d.EdgesRemoved, e)
}
}
baseFind := make(map[string]facts.Insight, len(snapInsights(baseline)))
for _, in := range snapInsights(baseline) {
baseFind[findingKey(in)] = in
}
curFind := make(map[string]facts.Insight)
for _, in := range snapInsights(current) {
curFind[findingKey(in)] = in
}
// A finding only counts as a real regression/improvement if this change
// structurally touched something it cites — otherwise its appearance/clearance
// is incidental (a moving mean+2σ threshold, or a top-N list re-ranking after
// some other finding left the window). touched is the set of names the change
// added/removed/altered, including edge endpoints (so a finding that flips
// because a NEW caller changed a symbol's fan-in is still counted as real).
touched := d.touchedNames()
for k, in := range curFind {
if _, ok := baseFind[k]; ok {
continue
}
if findingHasStructuralCause(in, touched) {
d.FindingsNew = append(d.FindingsNew, in)
} else {
d.FindingsNewIncidental = append(d.FindingsNewIncidental, in)
}
}
for k, in := range baseFind {
if _, ok := curFind[k]; ok {
continue
}
if findingHasStructuralCause(in, touched) {
d.FindingsResolved = append(d.FindingsResolved, in)
} else {
d.FindingsResolvedIncidental = append(d.FindingsResolvedIncidental, in)
}
}
d.sortAll()
return d
}
// touchedNames is the set of entity names this change structurally affected:
// added/removed/changed facts plus the endpoints of added/removed edges. A
// finding is attributed to the change when one of its evidence entities is in
// this set.
func (d *SnapshotDiff) touchedNames() map[string]struct{} {
m := make(map[string]struct{})
add := func(n string) {
if n != "" {
m[n] = struct{}{}
}
}
for _, f := range d.FactsAdded {
add(f.Name)
}
for _, f := range d.FactsRemoved {
add(f.Name)
}
for _, c := range d.FactsChanged {
add(c.After.Name)
}
for _, e := range d.EdgesAdded {
add(e.Source)
add(e.Target)
}
for _, e := range d.EdgesRemoved {
add(e.Source)
add(e.Target)
}
return m
}
// findingHasStructuralCause reports whether any entity the finding cites was
// structurally touched by this change. Evidence-less findings can't be attributed,
// so they default to real (never silently hidden).
func findingHasStructuralCause(in facts.Insight, touched map[string]struct{}) bool {
if len(in.Evidence) == 0 {
return true
}
for _, ev := range in.Evidence {
for _, e := range []string{ev.Fact, ev.Symbol, ev.File} {
if e == "" {
continue
}
if _, ok := touched[e]; ok {
return true
}
}
}
return false
}
// Empty reports whether the diff contains no changes of any kind.
func (d *SnapshotDiff) Empty() bool {
return len(d.FactsAdded) == 0 && len(d.FactsRemoved) == 0 && len(d.FactsChanged) == 0 &&
len(d.EdgesAdded) == 0 && len(d.EdgesRemoved) == 0 &&
len(d.FindingsNew) == 0 && len(d.FindingsResolved) == 0 &&
len(d.FindingsNewIncidental) == 0 && len(d.FindingsResolvedIncidental) == 0
}
// Focused returns a copy of the diff narrowed to entries that reference focus
// (case-insensitive substring against fact name/file, edge source/target, and
// finding title/evidence). An empty focus returns the diff unchanged. This lets
// an agent verify just the area it touched.
func (d *SnapshotDiff) Focused(focus string) *SnapshotDiff {
focus = strings.ToLower(strings.TrimSpace(focus))
if focus == "" {
return d
}
out := &SnapshotDiff{
BaselineRepo: d.BaselineRepo,
CurrentRepo: d.CurrentRepo,
BaselineGeneratedAt: d.BaselineGeneratedAt,
CurrentGeneratedAt: d.CurrentGeneratedAt,
}
for _, f := range d.FactsAdded {
if factMatches(f, focus) {
out.FactsAdded = append(out.FactsAdded, f)
}
}
for _, f := range d.FactsRemoved {
if factMatches(f, focus) {
out.FactsRemoved = append(out.FactsRemoved, f)
}
}
for _, c := range d.FactsChanged {
if factMatches(c.After, focus) || factMatches(c.Before, focus) {
out.FactsChanged = append(out.FactsChanged, c)
}
}
for _, e := range d.EdgesAdded {
if edgeMatches(e, focus) {
out.EdgesAdded = append(out.EdgesAdded, e)
}
}
for _, e := range d.EdgesRemoved {
if edgeMatches(e, focus) {
out.EdgesRemoved = append(out.EdgesRemoved, e)
}
}
for _, in := range d.FindingsNew {
if insightMatches(in, focus) {
out.FindingsNew = append(out.FindingsNew, in)
}
}
for _, in := range d.FindingsResolved {
if insightMatches(in, focus) {
out.FindingsResolved = append(out.FindingsResolved, in)
}
}
for _, in := range d.FindingsNewIncidental {
if insightMatches(in, focus) {
out.FindingsNewIncidental = append(out.FindingsNewIncidental, in)
}
}
for _, in := range d.FindingsResolvedIncidental {
if insightMatches(in, focus) {
out.FindingsResolvedIncidental = append(out.FindingsResolvedIncidental, in)
}
}
return out
}
// --- identity keys ---
// factKey identifies a fact by (kind, repo, file, name) plus a kind-specific
// discriminator. File is included so a symbol moved to another file shows as
// remove+add (acceptable for v1; the agent that moved it knows it did). Line is
// intentionally excluded — it is not identity, so a line shift never churns the diff.
//
// The discriminator exists because (kind, repo, file, name) is NOT unique for
// every kind: the same DB table is referenced by several SQL operations in one
// file, and the same route path is served under multiple HTTP methods. Without it
// those distinct facts collapse to one key, and the diff falsely reports the
// survivor as "changed" run-to-run — the colliding facts' map-iteration
// representative differs between an on-disk baseline and the in-memory current.
func factKey(f facts.Fact) string {
return f.Kind + "\x00" + f.Repo + "\x00" + f.File + "\x00" + f.Name + "\x00" + factDiscriminator(f)
}
// factDiscriminator returns the props that distinguish facts which legitimately
// share (kind, repo, file, name). It is kind-specific because only a few kinds
// have multiple facts per name; for the rest the fully-qualified name is unique.
// It deliberately uses identity-bearing props (a route's method, a storage
// reference's operation), not mutable ones, so a genuine attribute change still
// surfaces as "changed" rather than remove+add.
func factDiscriminator(f facts.Fact) string {
switch f.Kind {
case facts.KindRoute:
return propString(f.Props, "method")
case facts.KindStorage:
return propString(f.Props, "operation") + "|" + propString(f.Props, "storage_kind")
default:
return ""
}
}
// propString returns the named prop as a string, or "" if absent.
func propString(props map[string]any, key string) string {
if props == nil {
return ""
}
if v, ok := props[key]; ok {
return fmt.Sprintf("%v", v)
}
return ""
}
func edgeKey(e Edge) string {
return e.Repo + "\x00" + e.Source + "\x00" + e.Kind + "\x00" + e.Target
}
// titleNumber matches the volatile metrics embedded in finding titles (counts,
// ratios, percentages) so they can be stripped for a stable identity.
var titleNumber = regexp.MustCompile(`[0-9]+(\.[0-9]+)?`)
// normalizeTitle removes the volatile numbers from a finding title, leaving the
// stable subject. "Large public surface: x/y exports 67 of 67 symbols (100%)"
// and the same line with different counts collapse to one identity.
func normalizeTitle(s string) string {
return titleNumber.ReplaceAllString(s, "#")
}
// findingKey identifies an insight so a finding stays the SAME finding across
// snapshots even as its metrics drift or a ranked list re-orders.
//
// Most explainers name their subject (module/symbol/repo/pattern) in the title
// and vary only by counts, so the number-normalized title is the stable identity.
// This is what stops whole-codebase "summary" findings (e.g. the layers pattern,
// whose evidence enumerates every module) from churning resolve+introduce on any
// edit. Cycles are the exception: their title carries only a member count, so two
// distinct cycles would collide — they are keyed on their sorted member modules
// (the evidence), which is also what makes a cycle stay identified as long as its
// membership holds.
func findingKey(in facts.Insight) string {
if in.Source == "cycles" {
return in.Source + "\x00" + sortedEvidenceEntities(in)
}
return in.Source + "\x00" + normalizeTitle(in.Title)
}
// sortedEvidenceEntities joins a finding's cited entities (Fact/Symbol/File) in
// sorted order — a stable identity for set-defined findings like cycles.
func sortedEvidenceEntities(in facts.Insight) string {
var ents []string
for _, ev := range in.Evidence {
if e := firstNonEmpty(ev.Fact, ev.Symbol, ev.File); e != "" {
ents = append(ents, e)
}
}
sort.Strings(ents)
return strings.Join(ents, "\x1f")
}
// --- helpers ---
func snapFacts(s *facts.Snapshot) []facts.Fact {
if s == nil {
return nil
}
return s.Facts
}
func snapInsights(s *facts.Snapshot) []facts.Insight {
if s == nil {
return nil
}
return s.Insights
}
// edgeSet returns the deduplicated set of edges across all facts, keyed by edgeKey.
func edgeSet(ff []facts.Fact) map[string]Edge {
set := make(map[string]Edge)
for _, f := range ff {
for _, r := range f.Relations {
e := Edge{Source: f.Name, Kind: r.Kind, Target: r.Target, Repo: f.Repo}
set[edgeKey(e)] = e
}
}
return set
}
// propsChanged reports whether two facts sharing an identity differ in their
// props. encoding/json sorts map keys, so the marshaled form is order-stable.
func propsChanged(a, b facts.Fact) bool {
if len(a.Props) == 0 && len(b.Props) == 0 {
return false
}
return propsJSON(a.Props) != propsJSON(b.Props)
}
func propsJSON(p map[string]any) string {
if len(p) == 0 {
return ""
}
b, err := json.Marshal(p)
if err != nil {
return ""
}
return string(b)
}
func firstNonEmpty(ss ...string) string {
for _, s := range ss {
if s != "" {
return s
}
}
return ""
}
func factMatches(f facts.Fact, focusLC string) bool {
return strings.Contains(strings.ToLower(f.Name), focusLC) ||
strings.Contains(strings.ToLower(f.File), focusLC)
}
func edgeMatches(e Edge, focusLC string) bool {
return strings.Contains(strings.ToLower(e.Source), focusLC) ||
strings.Contains(strings.ToLower(e.Target), focusLC)
}
func insightMatches(in facts.Insight, focusLC string) bool {
if strings.Contains(strings.ToLower(in.Title), focusLC) {
return true
}
for _, ev := range in.Evidence {
if strings.Contains(strings.ToLower(ev.Fact), focusLC) ||
strings.Contains(strings.ToLower(ev.Symbol), focusLC) ||
strings.Contains(strings.ToLower(ev.File), focusLC) {
return true
}
}
return false
}
// sortAll orders every collection by its stable key so output is deterministic.
func (d *SnapshotDiff) sortAll() {
sort.Slice(d.FactsAdded, func(i, j int) bool { return factKey(d.FactsAdded[i]) < factKey(d.FactsAdded[j]) })
sort.Slice(d.FactsRemoved, func(i, j int) bool { return factKey(d.FactsRemoved[i]) < factKey(d.FactsRemoved[j]) })
sort.Slice(d.FactsChanged, func(i, j int) bool {
return factKey(d.FactsChanged[i].After) < factKey(d.FactsChanged[j].After)
})
sort.Slice(d.EdgesAdded, func(i, j int) bool { return edgeKey(d.EdgesAdded[i]) < edgeKey(d.EdgesAdded[j]) })
sort.Slice(d.EdgesRemoved, func(i, j int) bool { return edgeKey(d.EdgesRemoved[i]) < edgeKey(d.EdgesRemoved[j]) })
sort.Slice(d.FindingsNew, func(i, j int) bool { return findingKey(d.FindingsNew[i]) < findingKey(d.FindingsNew[j]) })
sort.Slice(d.FindingsResolved, func(i, j int) bool {
return findingKey(d.FindingsResolved[i]) < findingKey(d.FindingsResolved[j])
})
sort.Slice(d.FindingsNewIncidental, func(i, j int) bool {
return findingKey(d.FindingsNewIncidental[i]) < findingKey(d.FindingsNewIncidental[j])
})
sort.Slice(d.FindingsResolvedIncidental, func(i, j int) bool {
return findingKey(d.FindingsResolvedIncidental[i]) < findingKey(d.FindingsResolvedIncidental[j])
})
}
// KindCounts returns counts of facts by kind for the given slice, used by the
// renderer's structural-change summary.
func KindCounts(ff []facts.Fact) map[string]int {
m := make(map[string]int)
for _, f := range ff {
m[f.Kind]++
}
return m
}