-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcommit_prep_helpers.go
More file actions
348 lines (326 loc) · 10.4 KB
/
Copy pathcommit_prep_helpers.go
File metadata and controls
348 lines (326 loc) · 10.4 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
package repomap
// commit_prep_helpers.go — Types and pure helpers for the commit prep pipeline.
// The CLI (internal/cli/commit_prep.go) imports these; keeping them in the root
// package avoids re-exporting through the cli package and keeps the logic testable
// without Cobra.
import (
"context"
"crypto/sha256"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"io/fs"
"os"
"path/filepath"
"sort"
"strings"
"unicode/utf8"
)
// PrepPayload is the JSON document emitted by `repomap commit prep --json`.
type PrepPayload struct {
Preflight PrepPreflight `json:"preflight"`
ModeHint string `json:"mode_hint"` // "FULL" | "LOCAL"
PrepToken string `json:"prep_token"`
Status string `json:"status"` // "ready" | "needs_judgment" | "abort"
AbortReason string `json:"abort_reason,omitempty"`
Plan []PrepPlanGroup `json:"plan"`
Review []PrepReviewItem `json:"review"`
LowConfSubjects []PrepLowConf `json:"low_conf_subjects"`
ReleaseRecipe bool `json:"release_recipe"`
SessionRepos []string `json:"session_repos"`
ReleaseGate *PrepReleaseGate `json:"release_gate,omitempty"`
}
// PrepPreflight mirrors the cpt.md context block fields.
type PrepPreflight struct {
Branch string `json:"branch"`
Working string `json:"working"`
Remote string `json:"remote"`
Unpushed string `json:"unpushed"`
LatestTag string `json:"latest_tag"`
GHAuth string `json:"gh_auth"`
}
// PrepPlanGroup is one consolidated commit in the plan.
type PrepPlanGroup struct {
Type string `json:"type"`
Scope string `json:"scope"`
Subject string `json:"subject"`
Files []string `json:"files"`
Confidence float64 `json:"confidence"`
}
// PrepReviewItem is one finding that needs LLM judgment (capped at 5; snippet ≤200 chars).
type PrepReviewItem struct {
ID string `json:"id"`
File string `json:"file"`
Line int `json:"line"`
Snippet string `json:"snippet"`
Detail string `json:"detail"`
DefaultAction string `json:"default_action"`
}
// PrepLowConf is one group requiring LLM subject polish (capped at 3; diff_slice ≤500 chars).
type PrepLowConf struct {
GroupID string `json:"group_id"`
Files []string `json:"files"`
DiffSlice string `json:"diff_slice"`
}
// PrepReleaseGate holds the result of running the release gate.
type PrepReleaseGate struct {
Applied []any `json:"applied"`
BuildOK bool `json:"build_ok"`
}
// PrepState is persisted to tmpdir and loaded by `commit finish`.
type PrepState struct {
Analysis *CommitAnalysis `json:"analysis"`
Plan []CommitGroup `json:"plan"`
SessionRepos []string `json:"session_repos"`
ReleaseRecipe bool `json:"release_recipe"`
ReleaseGate *PrepReleaseGate `json:"release_gate,omitempty"`
RepoRoot string `json:"repo_root"`
HeadSHA string `json:"head_sha,omitempty"` // HEAD at prep time; finish refuses on mismatch
FileHashes map[string]string `json:"file_hashes,omitempty"` // planned rel path → sha256 hex ("absent" for planned deletions)
}
// LoadPrepState reads a persisted PrepState from tmpdir by token.
func LoadPrepState(token string) (*PrepState, error) {
path := filepath.Join(os.TempDir(), "prep-"+token+".json")
data, err := os.ReadFile(path)
if err != nil {
return nil, fmt.Errorf("prep state not found for token %q (looked at %s): %w", token, path, err)
}
var s PrepState
if err := json.Unmarshal(data, &s); err != nil {
return nil, fmt.Errorf("parse prep state: %w", err)
}
return &s, nil
}
// PersistPrepState writes state to tmpdir and returns the prep_token.
func PersistPrepState(state *PrepState) (string, error) {
data, err := json.Marshal(state)
if err != nil {
return "", err
}
sum := sha256.Sum256(data)
token := hex.EncodeToString(sum[:8])
path := filepath.Join(os.TempDir(), "prep-"+token+".json")
if err := atomicWriteFile(path, data, 0o600); err != nil {
return "", fmt.Errorf("write state: %w", err)
}
return token, nil
}
// BuildReviewItems extracts REVIEW findings into PrepReviewItems, capped at maxItems.
func BuildReviewItems(findings []Finding, maxItems int) []PrepReviewItem {
var out []PrepReviewItem
for _, f := range findings {
if f.DefaultAction != ActionReview {
continue
}
snippet := f.Snippet
if len(snippet) > 200 {
cut := 200
for cut > 0 && !utf8.RuneStart(snippet[cut]) {
cut--
}
snippet = snippet[:cut]
}
out = append(out, PrepReviewItem{
ID: fmt.Sprintf("%s:%d", f.File, f.Line),
File: f.File,
Line: f.Line,
Snippet: snippet,
Detail: f.Detail,
DefaultAction: f.DefaultAction,
})
if len(out) >= maxItems {
break
}
}
return out
}
// GroupsToPlan converts CommitGroups to PrepPlanGroups for the payload.
func GroupsToPlan(groups []CommitGroup) []PrepPlanGroup {
out := make([]PrepPlanGroup, 0, len(groups))
for _, g := range groups {
out = append(out, PrepPlanGroup{
Type: g.Type,
Scope: g.Scope,
Subject: g.SuggestedMsg,
Files: g.Files,
Confidence: g.Confidence,
})
}
return out
}
// LoadDiffSlice extracts the diff slice for a group's files, capped at maxChars.
func LoadDiffSlice(diffsPath string, g CommitGroup, maxChars int) string {
if diffsPath == "" || len(g.DiffOffsets) == 0 {
return ""
}
data, err := os.ReadFile(diffsPath)
if err != nil {
return ""
}
var sb strings.Builder
for _, f := range g.Files {
offsets, ok := g.DiffOffsets[f]
if !ok {
continue
}
start, end := offsets[0], offsets[1]
if start < 0 || end > len(data) || start >= end {
continue
}
sb.WriteString(string(data[start:end]))
if sb.Len() >= maxChars {
break
}
}
s := sb.String()
if len(s) > maxChars {
s = s[:maxChars]
}
return s
}
// DetectSessionRepos returns repos likely touched in this session.
// Checks known companion repos; always includes repoRoot itself.
func DetectSessionRepos(repoRoot string) []string {
repos := []string{repoRoot}
home, err := os.UserHomeDir()
if err != nil {
return repos
}
for _, c := range []string{
filepath.Join(home, ".claude"),
filepath.Join(home, "go", "src", "dotcommander-plugins"),
} {
if c == repoRoot {
continue
}
if _, err := os.Stat(filepath.Join(c, ".git")); err == nil {
repos = append(repos, c)
}
}
return repos
}
// DetectJustfileRelease returns true when a Justfile with a `release` recipe exists.
func DetectJustfileRelease(repoRoot string) bool {
data, err := os.ReadFile(filepath.Join(repoRoot, "Justfile"))
if err != nil {
return false
}
for _, line := range strings.Split(string(data), "\n") {
if strings.HasPrefix(line, "release ") || line == "release:" {
return true
}
}
return false
}
// LoadFindings reads a findings JSON file. Returns nil, nil when absent.
func LoadFindings(path string) ([]Finding, error) {
if path == "" {
return nil, nil
}
data, err := os.ReadFile(path)
if err != nil {
return nil, err
}
var findings []Finding
if err := json.Unmarshal(data, &findings); err != nil {
return nil, err
}
return findings, nil
}
// ModeHint derives FULL/LOCAL from preflight signals.
//
// FULL = remote present AND gh auth logged in → push + tag
// LOCAL = anything else → no push, no tag
//
// Permissive on auth string format: any "logged in" substring is truthy
// unless the line also says "not logged in" (gh's own negative phrasing).
func ModeHint(p PrepPreflight) string {
hasRemote := p.Remote != "" && p.Remote != "(none)"
auth := strings.ToLower(p.GHAuth)
hasAuth := strings.Contains(auth, "logged in") && !strings.Contains(auth, "not logged in")
if hasRemote && hasAuth {
return "FULL"
}
return "LOCAL"
}
// BuildPrepStateBinding captures the git state a plan was computed against:
// the HEAD SHA plus a sha256 of each planned file's current worktree content.
// Planned files absent from the worktree (deletions) record the sentinel
// "absent". commit finish refuses to execute when either no longer matches.
func BuildPrepStateBinding(ctx context.Context, repoRoot string, groups []CommitGroup) (string, map[string]string, error) {
headSHA, err := gitHeadSHA(ctx, repoRoot)
if err != nil {
return "", nil, fmt.Errorf("resolve HEAD: %w", err)
}
hashes := make(map[string]string)
for _, g := range groups {
for _, f := range g.Files {
if _, ok := hashes[f]; ok {
continue
}
h, hErr := sha256OfFile(filepath.Join(repoRoot, f))
if hErr != nil {
if errors.Is(hErr, fs.ErrNotExist) {
hashes[f] = "absent"
continue
}
return "", nil, fmt.Errorf("hash %s: %w", f, hErr)
}
hashes[f] = h
}
}
return headSHA, hashes, nil
}
// VerifyPrepStateFresh checks that the repo still matches the state captured
// at prep time. Fail-closed: legacy states without a binding are rejected.
func VerifyPrepStateFresh(ctx context.Context, state *PrepState) error {
if state.HeadSHA == "" {
return fmt.Errorf("prep state predates freshness binding; re-run commit prep")
}
head, err := gitHeadSHA(ctx, state.RepoRoot)
if err != nil {
return fmt.Errorf("resolve HEAD: %w", err)
}
if head != state.HeadSHA {
return fmt.Errorf("HEAD moved since prep (%.8s → %.8s); re-run commit prep", state.HeadSHA, head)
}
var changed []string
for f, want := range state.FileHashes {
got, hErr := sha256OfFile(filepath.Join(state.RepoRoot, f))
if hErr != nil {
if errors.Is(hErr, fs.ErrNotExist) {
got = "absent"
} else {
return fmt.Errorf("hash %s: %w", f, hErr)
}
}
if got != want {
changed = append(changed, f)
}
}
if len(changed) > 0 {
sort.Strings(changed)
return fmt.Errorf("file(s) changed since prep: %s — re-run commit prep", strings.Join(changed, ", "))
}
return nil
}
// PersistPrepStateAt rewrites the state file for an existing token in place.
// Used by commit finish after review decisions mutate planned files, so a
// retry of the same token still passes freshness verification.
func PersistPrepStateAt(token string, state *PrepState) error {
data, err := json.Marshal(state)
if err != nil {
return err
}
return atomicWriteFile(filepath.Join(os.TempDir(), "prep-"+token+".json"), data, 0o600)
}
// DeletePrepState removes the state file for a token. Missing file is not an
// error — deletion is idempotent.
func DeletePrepState(token string) error {
err := os.Remove(filepath.Join(os.TempDir(), "prep-"+token+".json"))
if err != nil && !errors.Is(err, fs.ErrNotExist) {
return err
}
return nil
}