-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcommit_analyze.go
More file actions
362 lines (331 loc) · 10.3 KB
/
commit_analyze.go
File metadata and controls
362 lines (331 loc) · 10.3 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
package repomap
import (
"context"
"crypto/rand"
"crypto/sha256"
"encoding/hex"
"encoding/json"
"fmt"
"os"
"path/filepath"
"strings"
)
// DefaultConfidenceCutoff is the minimum per-edge weight required to form
// a cluster. Set slightly below WeightSymbolDep so that symbol-dep is the
// lowest cluster-forming edge type; co-change (0.5) and sibling (0.3) are
// below the cutoff by design — they refine an already-clustered group but
// never pull files together on their own.
//
// Invariant enforced by Test_EdgeWeights_ClusteringContract: every
// cluster-forming weight (test-pair, symbol-dep) must exceed this cutoff;
// every refine-only weight (co-change, sibling) must be below it.
const DefaultConfidenceCutoff = WeightSymbolDep - 0.05
// AnalyzeOptions configures a commit-analyze run.
type AnalyzeOptions struct {
Root string // repo root (usually ".")
Tag bool // --tag: activate release gate (go.mod bump before commit)
ConfidenceCutoff float64 // default 0.75
Tmpdir string // override temp directory (tests)
}
// AnalyzeCommit is the public entrypoint called by the CLI. Collects git
// state, parses all dirty files, runs grouping + messages + secrets, writes
// side files, returns the CommitAnalysis ready for JSON emit.
func AnalyzeCommit(ctx context.Context, opts AnalyzeOptions) (*CommitAnalysis, error) {
root := opts.Root
if root == "" {
root = "."
}
abs, err := filepath.Abs(root)
if err != nil {
return nil, fmt.Errorf("resolve root: %w", err)
}
root = abs
if opts.ConfidenceCutoff == 0 {
opts.ConfidenceCutoff = DefaultConfidenceCutoff
}
tmpdir := opts.Tmpdir
if tmpdir == "" {
tmpdir, err = makeTmpdir()
if err != nil {
return nil, fmt.Errorf("tmpdir: %w", err)
}
} else if err := os.MkdirAll(tmpdir, 0o700); err != nil {
return nil, fmt.Errorf("tmpdir mkdir: %w", err)
}
gs, err := collectGitState(ctx, root)
if err != nil {
return nil, err
}
classifyFiles(gs.Files)
refs := CommitRefs{
Plan: filepath.Join(tmpdir, "plan.txt"),
Diffs: filepath.Join(tmpdir, "diffs.patch"),
Untracked: filepath.Join(tmpdir, "untracked.txt"),
History: filepath.Join(tmpdir, "history.txt"),
Findings: filepath.Join(tmpdir, "findings.json"),
}
// Early-exit: nothing to commit.
if len(gs.Files) == 0 {
return &CommitAnalysis{
Version: 1,
Tmpdir: tmpdir,
EarlyExit: true,
EarlyReason: "no changes in working tree",
Complexity: "simple",
Remote: RemoteInfo{OriginURL: gs.OriginURL, Visibility: gs.Visibility},
Secrets: SecretsSummary{Clean: true},
Refs: refs,
}, nil
}
// Write reference files in parallel-safe order. History is always useful;
// diffs + untracked are written unconditionally so agents can read on demand.
if err := writeFile(refs.History, []byte(gs.HistoryRaw)); err != nil {
return nil, fmt.Errorf("write history: %w", err)
}
if err := collectFullDiff(ctx, root, refs.Diffs); err != nil {
return nil, fmt.Errorf("write diffs: %w", err)
}
if err := untrackedConfigContent(ctx, root, gs.Files, refs.Untracked); err != nil {
return nil, fmt.Errorf("write untracked: %w", err)
}
// Parse all dirty source files (skipping deletions). repomap's parser
// dispatch handles language routing.
postSymbols := parseDirtyFiles(root, gs.Files)
// Symbol deltas for message generation. parseSkipped lists files where the
// post-parse returned zero symbols despite HEAD having symbols — those are
// almost certainly transient parse failures (mid-write, malformed input)
// and we deliberately do NOT emit removed-symbol deltas for them.
deltas, parseSkipped := computeSymbolDeltas(ctx, root, gs.Files, postSymbols)
// Dep bumps.
bumps := detectDepBumps(ctx, root, gs.Files)
// Secrets scan. Visibility is passed in so findings get a deterministic
// default_action that the agent can act on without per-finding LLM calls.
findings, summary := scanSecrets(ctx, root, gs.Files, gs.Visibility)
if err := writeFindings(refs.Findings, findings); err != nil {
return nil, fmt.Errorf("write findings: %w", err)
}
// Groups.
groups := buildGroups(gs, postSymbols, opts.ConfidenceCutoff)
suggestMessages(groups, gs, deltas, bumps)
// Count groups flagged as breaking changes.
breakingCount := 0
for _, g := range groups {
if g.Breaking {
breakingCount++
}
}
// Config files / artifacts / history style (top-level summary fields).
configFiles := collectConfigFiles(gs.Files)
artifacts := collectArtifacts(gs.Files)
histStyle := classifyHistoryStyle(gs.HistoryRaw)
// Surface tag + recent subjects so the agent never needs to re-run
// `git log` / `git tag` just for style inference or version lookup.
var latestTag string
if len(gs.Tags) > 0 {
latestTag = gs.Tags[0]
}
recentSubjects := splitLines(gs.HistoryRaw)
if len(recentSubjects) > 5 {
recentSubjects = recentSubjects[:5]
}
// Plan file.
plan := RenderPlan(groups)
if err := writeFile(refs.Plan, []byte(plan)); err != nil {
return nil, fmt.Errorf("write plan: %w", err)
}
var diagnostics []string
for _, p := range parseSkipped {
diagnostics = append(diagnostics, "parse-skipped: "+p+" (post-parse returned no symbols; treated as parse failure, no delta emitted)")
}
analysis := &CommitAnalysis{
Version: 1,
Tmpdir: tmpdir,
EarlyExit: false,
Complexity: classifyComplexity(gs.Files, groups),
Counts: countFiles(gs.Files),
HistoryStyle: histStyle,
LatestTag: latestTag,
RecentSubjects: recentSubjects,
Remote: RemoteInfo{OriginURL: gs.OriginURL, Visibility: gs.Visibility},
Secrets: summary,
Artifacts: artifacts,
ConfigFiles: configFiles,
DepBumps: bumps,
Groups: groups,
BreakingCount: breakingCount,
PlanHash: planHash(plan),
Refs: refs,
Diagnostics: diagnostics,
}
return analysis, nil
}
// parseDirtyFiles runs repomap's language-appropriate parser on each dirty
// source file and returns path → symbols. Deletions and unknown languages
// are skipped.
func parseDirtyFiles(root string, files []fileChange) map[string]*FileSymbols {
bl, _ := LoadBlocklistConfig(root)
out := make(map[string]*FileSymbols, len(files))
for _, f := range files {
if f.Status == "D" || f.IndexStatus == "D" {
continue
}
if f.Language == "" {
continue
}
abs := filepath.Join(root, f.Path)
if f.Language == "go" {
if sym, err := ParseGoFile(abs, root); err == nil && sym != nil {
bl.filterSymbols(sym)
out[f.Path] = sym
}
continue
}
if sym := parseNonGoFile(abs, root, f.Language); sym != nil {
bl.filterSymbols(sym)
out[f.Path] = sym
}
}
return out
}
// countFiles returns the per-status tally.
func countFiles(files []fileChange) CommitCounts {
var c CommitCounts
for _, f := range files {
c.Total++
switch {
case f.Status == "?":
c.Untracked++
case f.IndexStatus != "." && f.IndexStatus != " ":
c.Staged++
default:
c.Unstaged++
}
}
return c
}
// collectConfigFiles returns paths of all .md/.yaml/.json/.toml/.env/.cfg/.ini
// files in the changeset — the set that BLOCKING content review runs over.
func collectConfigFiles(files []fileChange) []string {
var out []string
for _, f := range files {
if f.IsConfig {
out = append(out, f.Path)
}
}
return out
}
// collectArtifacts returns paths that match artifact patterns (candidates for
// gitignore rather than commit).
func collectArtifacts(files []fileChange) []string {
var out []string
for _, f := range files {
if f.IsArtifact {
out = append(out, f.Path)
}
}
return out
}
// classifyHistoryStyle inspects the last 20 commit subjects and returns
// "conventional" | "mixed" | "freeform". ≥80% conventional → conventional,
// ≥20% conventional → mixed, else freeform.
func classifyHistoryStyle(raw string) string {
lines := splitLines(raw)
if len(lines) == 0 {
return "freeform"
}
conv := 0
for _, line := range lines {
if isConventional(line) {
conv++
}
}
ratio := float64(conv) / float64(len(lines))
switch {
case ratio >= 0.8:
return "conventional"
case ratio >= 0.2:
return "mixed"
default:
return "freeform"
}
}
// isConventional is a permissive "type(scope): subject" matcher.
func isConventional(subject string) bool {
colon := strings.Index(subject, ":")
if colon <= 0 || colon >= len(subject)-1 {
return false
}
head := subject[:colon]
// Strip optional (scope) and breaking-change marker (!).
if paren := strings.Index(head, "("); paren > 0 {
head = head[:paren]
}
head = strings.TrimRight(head, "!")
switch strings.TrimSpace(head) {
case "feat", "fix", "docs", "chore", "test", "refactor", "perf", "style",
"ci", "build", "revert", "deps":
return true
}
return false
}
// classifyComplexity is a rough heuristic used to tell the agent how much
// care is warranted: simple | medium | complex.
func classifyComplexity(files []fileChange, groups []CommitGroup) string {
switch {
case len(files) <= 3 && len(groups) <= 1:
return "simple"
case len(files) <= 15 && len(groups) <= 4:
return "medium"
default:
return "complex"
}
}
// makeTmpdir returns a per-run directory under $TMPDIR with an 8-byte random suffix.
func makeTmpdir() (string, error) {
var buf [8]byte
if _, err := rand.Read(buf[:]); err != nil {
return "", err
}
name := "commit-" + hex.EncodeToString(buf[:])
dir := filepath.Join(os.TempDir(), name)
if err := os.MkdirAll(dir, 0o700); err != nil {
return "", err
}
return dir, nil
}
// RenderPlan emits commit-execute.sh's native format:
//
// COMMIT
// MSG: feat(scope): subject
// FILES: path1
// FILES: path2
// COMMIT
// ...
// END
//
// Release gate (--tag + go.mod bump) is left to the agent to apply before
// invoking commit-execute.sh; the tool reports it via dep_bumps, not the plan.
func RenderPlan(groups []CommitGroup) string {
var b strings.Builder
for _, g := range groups {
b.WriteString("COMMIT\n")
fmt.Fprintf(&b, "MSG: %s\n", g.SuggestedMsg)
for _, f := range g.Files {
fmt.Fprintf(&b, "FILES: %s\n", f)
}
}
b.WriteString("END\n")
return b.String()
}
func planHash(plan string) string {
sum := sha256.Sum256([]byte(plan))
return "sha256:" + hex.EncodeToString(sum[:])
}
// EncodeJSON serializes a CommitAnalysis for stdout. Compact by default; set
// pretty=true for human inspection.
func EncodeJSON(a *CommitAnalysis, pretty bool) ([]byte, error) {
if pretty {
return json.MarshalIndent(a, "", " ")
}
return json.Marshal(a)
}