-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathaudit_brief.go
More file actions
443 lines (420 loc) · 17 KB
/
Copy pathaudit_brief.go
File metadata and controls
443 lines (420 loc) · 17 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
package repomap
import (
"context"
"fmt"
"slices"
"strings"
)
// AuditBriefReport is the single-pass audit prepass packet used by workflow
// tools that need deterministic local context without rebuilding the map for
// every audit subcommand.
type AuditBriefReport struct {
SchemaVersion int `json:"schema_version"`
Root string `json:"root"`
Risks AuditRiskReport `json:"risks"`
Surface AuditSurfaceReport `json:"surface"`
Effects AuditEffectReport `json:"effects"`
FirstReadQueue []AuditReadGroup `json:"first_read_queue"`
ReviewPlan []AuditReviewLane `json:"review_plan"`
}
// AuditReadGroup is a compact first-read queue grouped by the kind of risk a
// local static packet found.
type AuditReadGroup struct {
ID string `json:"id"`
Group string `json:"group"`
Lane string `json:"lane"`
EvidenceClass string `json:"evidence_class,omitempty"`
Confidence string `json:"confidence,omitempty"`
Reasons []string `json:"reasons"`
Caveat string `json:"caveat,omitempty"`
Files []string `json:"files"`
ReadNext []ReadNextItem `json:"read_next,omitempty"`
OmittedReason string `json:"omitted_reason,omitempty"`
}
// AuditReviewLane is a deterministic per-lane review obligation derived from the
// first-read queue: which files to cover, what gates to discharge, and how to
// verify. It carries no findings — only obligations implied by the static packets.
type AuditReviewLane struct {
ID string `json:"id"`
Lane string `json:"lane"`
Group string `json:"group"`
EvidenceClass string `json:"evidence_class,omitempty"`
Confidence string `json:"confidence,omitempty"`
Files []string `json:"files"`
Caveat string `json:"caveat,omitempty"`
Gates []string `json:"gates"`
Verify []string `json:"verify"`
Why []string `json:"why"`
OmittedReason string `json:"omitted_reason,omitempty"`
}
// AuditBrief computes risks, surface, effects, and a grouped first-read queue
// from one built Map.
func (m *Map) AuditBrief(ctx context.Context, limit int) (AuditBriefReport, error) {
risks := m.AuditRisks(limit)
surface, err := m.AuditSurface(ctx, limit)
if err != nil {
return AuditBriefReport{}, err
}
effects, err := m.AuditEffects(ctx, limit)
if err != nil {
return AuditBriefReport{}, err
}
queue := BuildAuditReadQueue(risks, surface, effects)
goDetected := false
for _, file := range risks.Files {
if file.Language == "go" {
goDetected = true
break
}
}
return AuditBriefReport{
SchemaVersion: 3,
Root: risks.Root,
Risks: compactBriefRisks(risks),
Surface: compactBriefSurface(surface),
Effects: compactBriefEffects(effects),
FirstReadQueue: queue,
ReviewPlan: BuildAuditReviewPlan(queue, goDetected),
}, nil
}
// BuildAuditReadQueue turns audit packets into a deterministic file-read order
// grouped by why the files matter.
func BuildAuditReadQueue(risks AuditRiskReport, surface AuditSurfaceReport, effects AuditEffectReport) []AuditReadGroup {
groups := map[string]*AuditReadGroup{}
add := func(group, lane, reason string, files []string, next []ReadNextItem) {
clean := make([]string, 0, len(files))
for _, file := range files {
if file == "" || isTestPath(file) {
continue
}
clean = append(clean, file)
}
if len(clean) == 0 {
return
}
entry := groups[group]
if entry == nil {
entry = &AuditReadGroup{Group: group, Lane: lane}
groups[group] = entry
}
entry.Reasons = appendUnique(entry.Reasons, reason)
entry.Files = append(entry.Files, clean...)
entry.ReadNext = append(entry.ReadNext, next...)
}
riskFiles := make([]string, 0, len(risks.Files))
for _, file := range risks.Files {
riskFiles = append(riskFiles, file.Path)
}
add("ranked-risk-packets", "architecture", "repomap ranked audit score", riskFiles, nil)
for _, lane := range risks.Lanes {
switch lane.Name {
case "test-risk":
add("test-risk", "test-risk", lane.Reason, lane.Files, nil)
case "dead-code":
add("dead-export-surface", "dead-code", lane.Reason, lane.Files, nil)
case "coupling":
add("coupling-hotspots", "coupling", lane.Reason, lane.Files, nil)
case "parse-fidelity":
add("parse-fidelity", "parse-fidelity", lane.Reason, lane.Files, nil)
}
}
addSurfaceGroup := func(group, lane, reason string, hits []AuditSurfaceHit) {
files := make([]string, 0, len(hits))
next := make([]ReadNextItem, 0, len(hits))
for _, hit := range hits {
files = append(files, hit.Path)
next = append(next, readNextAround(hit.Path, hit.Line, reason))
}
add(group, lane, reason, files, next)
}
addSurfaceGroup("user-surface", "cli-ux", "commands, flags, and output paths", surface.Commands)
addSurfaceGroup("user-surface", "cli-ux", "commands, flags, and output paths", surface.Flags)
addSurfaceGroup("user-surface", "cli-ux", "commands, flags, and output paths", surface.Outputs)
addSurfaceGroup("config-surface", "config", "env vars and config keys", surface.EnvVars)
addSurfaceGroup("config-surface", "config", "env vars and config keys", surface.ConfigKeys)
addSurfaceGroup("api-schema", "api-contracts", "routes and JSON schema fields", surface.Routes)
addSurfaceGroup("api-schema", "api-contracts", "routes and JSON schema fields", surface.SchemaFields)
addSurfaceGroup("dependency-policy", "dependency-policy", "dependency manifests and policy surface", surface.DependencyManifests)
for _, kind := range effects.Kinds {
switch kind.Name {
case "filesystem-write", "database":
add("writes-and-persistence", "data-integrity", kind.Reason, kind.Files, effectReadNext(effects, kind.Files, kind.Reason))
case "http", "serialization":
add("network-and-api-effects", "api-contracts", kind.Reason, kind.Files, effectReadNext(effects, kind.Files, kind.Reason))
case "subprocess", "process-exit":
add("subprocess-and-exit", "error-handling", kind.Reason, kind.Files, effectReadNext(effects, kind.Files, kind.Reason))
case "secret", "crypto", "randomness":
add("secret-and-crypto", "security", kind.Reason, kind.Files, effectReadNext(effects, kind.Files, kind.Reason))
case "time", "filesystem-read":
add("state-and-time", "data-integrity", kind.Reason, kind.Files, effectReadNext(effects, kind.Files, kind.Reason))
case "context-background", "goroutine":
add("lifecycle-concurrency", "lifecycle-concurrency", kind.Reason, kind.Files, effectReadNext(effects, kind.Files, kind.Reason))
case "unbounded-read":
add("resource-bounds", "performance", kind.Reason, kind.Files, effectReadNext(effects, kind.Files, kind.Reason))
}
}
priority := map[string]int{
"user-surface": 0,
"writes-and-persistence": 1,
"network-and-api-effects": 2,
"subprocess-and-exit": 3,
"dependency-policy": 4,
"config-surface": 5,
"secret-and-crypto": 6,
"lifecycle-concurrency": 7,
"resource-bounds": 8,
"test-risk": 9,
"coupling-hotspots": 10,
"dead-export-surface": 11,
"parse-fidelity": 12,
"ranked-risk-packets": 13,
"state-and-time": 14,
"api-schema": 15,
}
out := make([]AuditReadGroup, 0, len(groups))
for _, group := range groups {
group.Files = dedupeStrings(group.Files)
if total := len(group.Files); total > 12 {
group.Files = group.Files[:12]
group.OmittedReason = fmt.Sprintf("showing 12 of %d files; truncated by brief cap", total)
}
var readOmitted string
group.ReadNext, readOmitted = dedupeReadNext(group.ReadNext, 8)
if readOmitted != "" && group.OmittedReason == "" {
group.OmittedReason = readOmitted
}
slices.Sort(group.Reasons)
if len(group.Reasons) > 4 {
group.Reasons = group.Reasons[:4]
}
group.ID = "repomap:queue:" + auditSlug(group.Group)
group.EvidenceClass = auditEvidenceForLanes([]string{group.Lane})
group.Caveat = auditExternalCaveat([]string{group.Lane})
group.Confidence = auditConfidence(group.EvidenceClass, group.Caveat != "")
out = append(out, *group)
}
slices.SortFunc(out, func(a, b AuditReadGroup) int {
ap, bp := priority[a.Group], priority[b.Group]
if ap != bp {
return ap - bp
}
return strings.Compare(a.Group, b.Group)
})
return out
}
func effectReadNext(report AuditEffectReport, files []string, reason string) []ReadNextItem {
fileSet := make(map[string]struct{}, len(files))
for _, file := range files {
fileSet[file] = struct{}{}
}
var out []ReadNextItem
for _, file := range report.Files {
if _, ok := fileSet[file.Path]; !ok {
continue
}
for _, effect := range file.Effects {
out = append(out, readNextAround(effect.Path, effect.Line, reason))
}
}
return out
}
// auditLanePlan is the static gates/verify obligation attached to a review lane.
// verify holds Go-specific commands emitted only when the target has Go sources.
type auditLanePlan struct {
gates []string
verify []string
}
// auditReviewLaneTable maps each first-read-queue lane to its deterministic
// review obligations. Lanes absent here emit no gates/verify (never panic).
var auditReviewLaneTable = map[string]auditLanePlan{
"lifecycle-concurrency": {gates: []string{"context propagation", "goroutine ownership", "shutdown cleanup", "channel-close ownership"}, verify: []string{"go test -race ./..."}},
"cli-ux": {gates: []string{"flag parsing", "help-text accuracy", "exit codes", "output formatting"}, verify: []string{"go build ./..."}},
"api-contracts": {gates: []string{"JSON schema stability", "encoder/decoder round-trip", "backward compatibility"}, verify: []string{"go test ./..."}},
"data-integrity": {gates: []string{"write atomicity", "read-after-write", "rollback on error"}, verify: []string{"go test ./..."}},
"error-handling": {gates: []string{"subprocess timeout", "stderr capture", "exit-code propagation", "error wrapping"}, verify: []string{"go vet ./...", "go test ./..."}},
"security": {gates: []string{"secret handling", "crypto correctness", "randomness source"}},
"dependency-policy": {gates: []string{"dependency necessity", "version pinning", "banned imports"}, verify: []string{"go list -m all"}},
"performance": {gates: []string{"bounded reads", "resource limits"}, verify: []string{"go test ./..."}},
"config": {gates: []string{"config defaults", "env-var precedence"}},
"test-risk": {gates: []string{"untested-export coverage"}, verify: []string{"go test ./..."}},
"coupling": {gates: []string{"fan-out justification", "interface boundaries"}},
"dead-code": {gates: []string{"confirm truly unused before removal"}},
"parse-fidelity": {gates: []string{"low-fidelity parse may miss symbols"}},
"architecture": {gates: []string{"central-dependency blast radius"}, verify: []string{"go build ./..."}},
}
// auditReviewLanePriority gives review lanes a deterministic, audit-meaningful order.
var auditReviewLanePriority = map[string]int{
"cli-ux": 0,
"api-contracts": 1,
"data-integrity": 2,
"error-handling": 3,
"dependency-policy": 4,
"config": 5,
"security": 6,
"lifecycle-concurrency": 7,
"performance": 8,
"test-risk": 9,
"coupling": 10,
"dead-code": 11,
"parse-fidelity": 12,
"architecture": 13,
}
// BuildAuditReviewPlan projects the first-read queue into per-lane review
// obligations: it merges read groups sharing a lane, attaches deterministic
// gates/verify from the static table, and suppresses Go-specific verify commands
// when the target has no Go sources. It invents no findings.
func BuildAuditReviewPlan(queue []AuditReadGroup, goDetected bool) []AuditReviewLane {
type laneAcc struct {
files []string
why []string
}
lanes := map[string]*laneAcc{}
for _, group := range queue {
acc := lanes[group.Lane]
if acc == nil {
acc = &laneAcc{}
lanes[group.Lane] = acc
}
acc.files = append(acc.files, group.Files...)
for _, reason := range group.Reasons {
acc.why = appendUnique(acc.why, reason)
}
}
out := make([]AuditReviewLane, 0, len(lanes))
for lane, acc := range lanes {
files := dedupeStrings(acc.files)
omitted := ""
if total := len(files); total > 12 {
files = files[:12]
omitted = fmt.Sprintf("showing 12 of %d files; truncated by brief cap", total)
}
why := acc.why
slices.Sort(why)
if len(why) > 4 {
why = why[:4]
}
if why == nil {
why = []string{}
}
plan := auditReviewLaneTable[lane]
gates := plan.gates
if gates == nil {
gates = []string{}
}
verify := []string{}
if goDetected && plan.verify != nil {
verify = plan.verify
}
caveat := auditExternalCaveat([]string{lane})
evidence := auditEvidenceForLanes([]string{lane})
out = append(out, AuditReviewLane{
ID: "repomap:review:" + auditSlug(lane),
Lane: lane,
Group: lane,
EvidenceClass: evidence,
Confidence: auditConfidence(evidence, caveat != ""),
Files: files,
Caveat: caveat,
Gates: gates,
Verify: verify,
Why: why,
OmittedReason: omitted,
})
}
slices.SortFunc(out, func(a, b AuditReviewLane) int {
ap, bp := auditReviewLanePriority[a.Lane], auditReviewLanePriority[b.Lane]
if ap != bp {
return ap - bp
}
return strings.Compare(a.Lane, b.Lane)
})
return out
}
func dedupeStrings(items []string) []string {
seen := map[string]bool{}
out := make([]string, 0, len(items))
for _, item := range items {
if seen[item] {
continue
}
seen[item] = true
out = append(out, item)
}
return out
}
func compactBriefRisks(report AuditRiskReport) AuditRiskReport {
for i := range report.Lanes {
if total := len(report.Lanes[i].Files); total > 12 {
report.Lanes[i].Files = report.Lanes[i].Files[:12]
report.Lanes[i].OmittedReason = fmt.Sprintf("showing 12 of %d files; truncated by brief cap", total)
}
}
return report
}
func compactBriefSurface(report AuditSurfaceReport) AuditSurfaceReport {
for i := range report.Files {
total := originalTruncationTotal(report.Truncations, "files["+report.Files[i].Path+"].hits", len(report.Files[i].Hits))
if len(report.Files[i].Hits) > 4 {
report.Files[i].Hits = report.Files[i].Hits[:4]
}
if total > len(report.Files[i].Hits) {
report.Files[i].OmittedReason = fmt.Sprintf("showing %d of %d hits; truncated by audit brief cap", len(report.Files[i].Hits), total)
report.Truncations = append(report.Truncations, AuditTruncation{
Field: "files[" + report.Files[i].Path + "].hits",
Shown: len(report.Files[i].Hits), Total: total, Reason: "audit brief per-file cap",
})
}
}
report.Commands = capBriefSurfaceField(&report, "commands", report.Commands, 24)
report.Flags = capBriefSurfaceField(&report, "flags", report.Flags, 32)
report.EnvVars = capBriefSurfaceField(&report, "env_vars", report.EnvVars, 32)
report.ConfigKeys = capBriefSurfaceField(&report, "config_keys", report.ConfigKeys, 40)
report.SchemaFields = capBriefSurfaceField(&report, "schema_fields", report.SchemaFields, 40)
report.Routes = capBriefSurfaceField(&report, "routes", report.Routes, 32)
report.Outputs = capBriefSurfaceField(&report, "outputs", report.Outputs, 32)
report.DependencyManifests = capBriefSurfaceField(&report, "dependency_manifests", report.DependencyManifests, 16)
return report
}
func compactBriefEffects(report AuditEffectReport) AuditEffectReport {
for i := range report.Files {
total := originalTruncationTotal(report.Truncations, "files["+report.Files[i].Path+"].effects", len(report.Files[i].Effects))
if len(report.Files[i].Effects) > 4 {
report.Files[i].Effects = report.Files[i].Effects[:4]
}
if total > len(report.Files[i].Effects) {
report.Files[i].OmittedReason = fmt.Sprintf("showing %d of %d effects; truncated by audit brief cap", len(report.Files[i].Effects), total)
report.Truncations = append(report.Truncations, AuditTruncation{
Field: "files[" + report.Files[i].Path + "].effects",
Shown: len(report.Files[i].Effects), Total: total, Reason: "audit brief per-file cap",
})
}
}
for i := range report.Kinds {
if total := len(report.Kinds[i].Files); total > 12 {
report.Kinds[i].Files = report.Kinds[i].Files[:12]
report.Kinds[i].OmittedReason = fmt.Sprintf("showing 12 of %d files; truncated by brief cap", total)
}
}
return report
}
func capBriefSurfaceField(report *AuditSurfaceReport, field string, items []AuditSurfaceHit, limit int) []AuditSurfaceHit {
total := originalTruncationTotal(report.Truncations, field, len(items))
if len(items) > limit {
items = items[:limit]
}
if total > len(items) {
report.Truncations = append(report.Truncations, AuditTruncation{
Field: field, Shown: len(items), Total: total, Reason: "audit brief aggregate cap",
})
}
return items
}
func originalTruncationTotal(truncations []AuditTruncation, field string, fallback int) int {
total := fallback
for _, truncation := range truncations {
if truncation.Field == field && truncation.Total > total {
total = truncation.Total
}
}
return total
}