| 1 | package cmd |
| 2 | |
| 3 | import ( |
| 4 | "bytes" |
| 5 | "context" |
| 6 | "fmt" |
| 7 | "os" |
| 8 | "os/exec" |
| 9 | "path/filepath" |
| 10 | "strings" |
| 11 | "testing" |
| 12 | |
| 13 | "the-valley/flow/internal/event" |
| 14 | "the-valley/flow/internal/git" |
| 15 | "the-valley/flow/internal/run" |
| 16 | ) |
| 17 | |
| 18 | const testDataRef = "refs/klaus/data" |
| 19 | |
| 20 | // finalizePRLog is a clean run that opened a PR, so _finalize takes the |
| 21 | // normal path (no salvage) through the data-ref sync. Its runs record PR |
| 22 | // delivery, as launch does for a repo on GitHub, since the bare origin's path |
| 23 | // isn't a GitHub URL. |
| 24 | const finalizePRLog = `{"type":"assistant","message":{"content":[{"type":"text","text":"Opened https://github.com/acme/widget/pull/9"}]}} |
| 25 | {"type":"result","subtype":"success","total_cost_usd":1,"duration_ms":1000} |
| 26 | ` |
| 27 | |
| 28 | // TestFinalizeKeepsDataRefLocalByDefault runs the real _finalize against a |
| 29 | // clone with a bare origin: the run lands on the local data ref, and origin |
| 30 | // never receives it. |
| 31 | func TestFinalizeKeepsDataRefLocalByDefault(t *testing.T) { |
| 32 | origin, repo, worktree, branch := setupBareRemote(t) |
| 33 | commitAndPush(t, worktree, branch) |
| 34 | |
| 35 | _, state, _ := finalizeRealRepo(t, repo, worktree, branch, finalizePRLog, run.DeliveryPR) |
| 36 | |
| 37 | files, err := gitOut(t, repo, "ls-tree", "-r", "--name-only", testDataRef) |
| 38 | if err != nil { |
| 39 | t.Fatalf("local %s missing after finalize: %v %s", testDataRef, err, files) |
| 40 | } |
| 41 | for _, want := range []string{"runs/" + state.ID + ".json", "logs/" + state.ID + ".jsonl"} { |
| 42 | if !strings.Contains(files, want) { |
| 43 | t.Errorf("local %s missing %s; has:\n%s", testDataRef, want, files) |
| 44 | } |
| 45 | } |
| 46 | if sha, err := gitOut(t, origin, "rev-parse", "--verify", "--quiet", testDataRef); err == nil { |
| 47 | t.Fatalf("origin has %s at %s; the default config must not push it", testDataRef, sha) |
| 48 | } |
| 49 | local, _ := gitOut(t, repo, "rev-parse", testDataRef) |
| 50 | if want := (run.DataRefPush{Ref: testDataRef, Commit: local, Status: run.DataRefNotAttempted}); state.DataRefPush == nil || *state.DataRefPush != want { |
| 51 | t.Errorf("DataRefPush = %+v, want %+v", state.DataRefPush, want) |
| 52 | } |
| 53 | } |
| 54 | |
| 55 | // TestFinalizePushesDataRefWhenEnabled: push_data_ref: true restores the push. |
| 56 | func TestFinalizePushesDataRefWhenEnabled(t *testing.T) { |
| 57 | origin, repo, worktree, branch := setupBareRemote(t) |
| 58 | commitAndPush(t, worktree, branch) |
| 59 | if err := os.MkdirAll(filepath.Join(repo, ".klaus"), 0o755); err != nil { |
| 60 | t.Fatal(err) |
| 61 | } |
| 62 | if err := os.WriteFile(filepath.Join(repo, ".klaus", "config.json"), []byte(`{"push_data_ref": true}`), 0o644); err != nil { |
| 63 | t.Fatal(err) |
| 64 | } |
| 65 | |
| 66 | _, state, _ := finalizeRealRepo(t, repo, worktree, branch, finalizePRLog, run.DeliveryPR) |
| 67 | |
| 68 | local, err := gitOut(t, repo, "rev-parse", testDataRef) |
| 69 | if err != nil { |
| 70 | t.Fatalf("local %s missing after finalize: %v", testDataRef, err) |
| 71 | } |
| 72 | if remote, err := gitOut(t, origin, "rev-parse", "--verify", testDataRef); err != nil || remote != local { |
| 73 | t.Fatalf("origin %s = %q (%v), want the local commit %s", testDataRef, remote, err, local) |
| 74 | } |
| 75 | if want := (run.DataRefPush{Ref: testDataRef, Commit: local, Status: run.DataRefPublished}); state.DataRefPush == nil || *state.DataRefPush != want { |
| 76 | t.Errorf("DataRefPush = %+v, want %+v", state.DataRefPush, want) |
| 77 | } |
| 78 | } |
| 79 | |
| 80 | // TestFinalizeRecordsRefusedDataRefPush: a receive hook that refuses the data |
| 81 | // ref leaves the run's outcome and local commit as they were, and the run |
| 82 | // records the refusal in the hook's words. |
| 83 | func TestFinalizeRecordsRefusedDataRefPush(t *testing.T) { |
| 84 | origin, repo, worktree, branch := setupBareRemote(t) |
| 85 | commitAndPush(t, worktree, branch) |
| 86 | if err := os.MkdirAll(filepath.Join(repo, ".klaus"), 0o755); err != nil { |
| 87 | t.Fatal(err) |
| 88 | } |
| 89 | if err := os.WriteFile(filepath.Join(repo, ".klaus", "config.json"), []byte(`{"push_data_ref": true}`), 0o644); err != nil { |
| 90 | t.Fatal(err) |
| 91 | } |
| 92 | refuseDataRef(t, origin, "echo 'policy denies refs/klaus/data' >&2") |
| 93 | |
| 94 | store, state, _ := finalizeRealRepo(t, repo, worktree, branch, finalizePRLog, run.DeliveryPR) |
| 95 | |
| 96 | if state.PRURL == nil || state.FailureReason != nil || state.NeedsAttention != nil { |
| 97 | t.Errorf("run outcome changed: pr=%v failure=%v attention=%v", state.PRURL, state.FailureReason, state.NeedsAttention) |
| 98 | } |
| 99 | local, _ := gitOut(t, repo, "rev-parse", testDataRef) |
| 100 | rec := state.DataRefPush |
| 101 | if rec == nil || rec.Status != run.DataRefFailed || rec.Commit != local || rec.Class != git.PushRefused || |
| 102 | !strings.Contains(rec.Message, "remote: policy denies refs/klaus/data") { |
| 103 | t.Fatalf("DataRefPush = %+v, want refused at %s with the hook's line", rec, local) |
| 104 | } |
| 105 | evts := runEvents(t, store.BaseDir(), state.ID) |
| 106 | if e := evts[event.AgentDataRefPushFailed]; e == nil || e["class"] != git.PushRefused || e["commit"] != local { |
| 107 | t.Errorf("agent:data-ref-push-failed = %v", e) |
| 108 | } |
| 109 | if _, ok := evts[event.AgentNeedsAttention]; ok { |
| 110 | t.Error("a refused data ref push emitted agent:needs-attention") |
| 111 | } |
| 112 | } |
| 113 | |
| 114 | // refuseDataRef installs a pre-receive hook on origin that runs say and |
| 115 | // refuses the push. |
| 116 | func refuseDataRef(t *testing.T, origin, say string) { |
| 117 | t.Helper() |
| 118 | hook := "#!/bin/sh\n" + say + "\nexit 1\n" |
| 119 | if err := os.WriteFile(filepath.Join(origin, "hooks", "pre-receive"), []byte(hook), 0o755); err != nil { |
| 120 | t.Fatal(err) |
| 121 | } |
| 122 | } |
| 123 | |
| 124 | // secretPushClient fails every data ref push as a remote does that echoes |
| 125 | // its address, credentials and all, in the ref's status, while git's own |
| 126 | // lines carry destination and a remote helper's command line. |
| 127 | type secretPushClient struct { |
| 128 | *git.ExecClient |
| 129 | destination string |
| 130 | } |
| 131 | |
| 132 | func (c secretPushClient) PushDataRef(_ context.Context, _, dataRef string) (string, error) { |
| 133 | return "", git.ParsePushError(dataRef, "To "+c.destination+"\n"+ |
| 134 | "!\tHEAD:refs/klaus/data\t[remote rejected] (permission denied for https://user:secret@example.org/x?token=secret)\n"+ |
| 135 | "Done\n", |
| 136 | "fatal: unable to access 'https://user:secret@example.org/x?token=secret': retrying\n"+ |
| 137 | "error: helper ext::ssh -i /srv/secret-key example.org %S repo exited\n"+ |
| 138 | "remote: policy denies refs/klaus/data\n"+ |
| 139 | "error: failed to push some refs to 'ext::ssh -i /srv/secret-key example.org %S repo'\n") |
| 140 | } |
| 141 | |
| 142 | // TestDataRefPushFailureKeepsAddressesOut: of a failed push's output, only |
| 143 | // the remote's lines and the ref's status reach the run record, the event, |
| 144 | // finalize's stderr, status, watch, notifications and the dashboard, and |
| 145 | // those that hold an address are withheld whole. |
| 146 | func TestDataRefPushFailureKeepsAddressesOut(t *testing.T) { |
| 147 | for _, tc := range []struct { |
| 148 | name string |
| 149 | client git.Client |
| 150 | origin string // origin's URL, when the push is real |
| 151 | message string // the stored message |
| 152 | kept []string |
| 153 | }{ |
| 154 | {"an address in the remote's reason", secretPushClient{git.NewExecClient(), "https://user:secret@example.org/x?token=secret"}, "", |
| 155 | "remote: policy denies refs/klaus/data\n[remote rejected] " + git.PushWithheld, |
| 156 | []string{"policy denies refs/klaus/data", "[remote rejected]"}}, |
| 157 | {"a destination that forges a status line", secretPushClient{git.NewExecClient(), "\n!\tx:y\t[https://example.org/x?token=secret]\n"}, "", |
| 158 | "remote: policy denies refs/klaus/data\n[remote rejected] " + git.PushWithheld, |
| 159 | []string{"policy denies refs/klaus/data", "[remote rejected]"}}, |
| 160 | {"a destination path made to look like a remote line", git.NewExecClient(), |
| 161 | "/srv/x\nremote: see user:secret@example.org/x?token=secret", git.PushWithheld, []string{git.PushWithheld}}, |
| 162 | } { |
| 163 | t.Run(tc.name, func(t *testing.T) { |
| 164 | home := t.TempDir() |
| 165 | t.Setenv("HOME", home) |
| 166 | t.Setenv("USERPROFILE", home) |
| 167 | _, repo, _, _ := setupBareRemote(t) |
| 168 | if tc.origin != "" { |
| 169 | runGitCmd(t, repo, "remote", "set-url", "origin", tc.origin) |
| 170 | } |
| 171 | store := run.NewHomeDirStoreFromPath(filepath.Join(t.TempDir(), "session")) |
| 172 | if err := store.EnsureDirs(); err != nil { |
| 173 | t.Fatal(err) |
| 174 | } |
| 175 | st := finishedClaudeRun(t, store, home, "20261004-1200-aaaa", "6623bdcf-1dce-4da0-86b3-a46743d208e8") |
| 176 | |
| 177 | stderr := captureStderr(t, func() { |
| 178 | syncRunToDataRef(context.Background(), repo, store, tc.client, testDataRef, true, st) |
| 179 | }) |
| 180 | if rec := st.DataRefPush; rec == nil || rec.Status != run.DataRefFailed || rec.Message != tc.message { |
| 181 | t.Errorf("DataRefPush = %+v, want a failure with message %q", rec, tc.message) |
| 182 | } |
| 183 | record, err := os.ReadFile(filepath.Join(store.StateDir(), st.ID+".json")) |
| 184 | if err != nil { |
| 185 | t.Fatal(err) |
| 186 | } |
| 187 | events, err := os.ReadFile(filepath.Join(store.BaseDir(), "events.jsonl")) |
| 188 | if err != nil { |
| 189 | t.Fatal(err) |
| 190 | } |
| 191 | states, _ := store.List() |
| 192 | var status bytes.Buffer |
| 193 | if err := runStatuses(context.Background(), store, states, &status); err != nil { |
| 194 | t.Fatal(err) |
| 195 | } |
| 196 | evts, _ := event.NewLog(store.BaseDir()).Read() |
| 197 | var watch strings.Builder |
| 198 | for _, e := range evts { |
| 199 | watch.WriteString(formatEvent(e) + "\n") |
| 200 | } |
| 201 | notifications := captureStdout(t, func() { printSummary(evts, nil) }) |
| 202 | dashboard := dashboardModel{states: states}.dataRefWarning() |
| 203 | |
| 204 | for name, out := range map[string]string{"record": string(record), "events": string(events), "stderr": stderr, |
| 205 | "status": status.String(), "watch": watch.String(), "notifications": notifications, "dashboard": dashboard} { |
| 206 | for _, want := range tc.kept { |
| 207 | if !strings.Contains(out, want) { |
| 208 | t.Errorf("%s lacks %q:\n%s", name, want, out) |
| 209 | } |
| 210 | } |
| 211 | for _, leak := range []string{"secret", "token", "user:", "ext::", "https://", "example.org"} { |
| 212 | if strings.Contains(out, leak) { |
| 213 | t.Errorf("%s holds %q:\n%s", name, leak, out) |
| 214 | } |
| 215 | } |
| 216 | } |
| 217 | if !strings.Contains(stderr, "git push origin "+testDataRef) || !strings.Contains(status.String(), "git push origin "+testDataRef) { |
| 218 | t.Errorf("stderr and status should say how to publish by hand:\n%s\n%s", stderr, status.String()) |
| 219 | } |
| 220 | }) |
| 221 | } |
| 222 | } |
| 223 | |
| 224 | // TestInterleavedFinalizesPublishBothRuns: two finalizes in one clone build |
| 225 | // their commits on the same tip. The first moves the ref while the second is |
| 226 | // about to; the second then moves and publishes it before the first pushes. |
| 227 | // Both commits stay on the ref's history, origin ends up with both, and each |
| 228 | // run records published. |
| 229 | func TestInterleavedFinalizesPublishBothRuns(t *testing.T) { |
| 230 | home := t.TempDir() |
| 231 | t.Setenv("HOME", home) |
| 232 | t.Setenv("USERPROFILE", home) |
| 233 | origin, repo, _, _ := setupBareRemote(t) |
| 234 | store := run.NewHomeDirStoreFromPath(filepath.Join(t.TempDir(), "session")) |
| 235 | if err := store.EnsureDirs(); err != nil { |
| 236 | t.Fatal(err) |
| 237 | } |
| 238 | ctx := context.Background() |
| 239 | gc := git.NewExecClient() |
| 240 | if err := gc.EnsureDataRef(ctx, repo, testDataRef); err != nil { |
| 241 | t.Fatal(err) |
| 242 | } |
| 243 | first := finishedClaudeRun(t, store, home, "20261004-1600-aaaa", "6623bdcf-1dce-4da0-86b3-a46743d208e8") |
| 244 | second := finishedClaudeRun(t, store, home, "20261004-1600-bbbb", "11111111-2222-4333-8444-555555555555") |
| 245 | |
| 246 | var firstCommit string |
| 247 | fired := false |
| 248 | t.Cleanup(git.SetBeforeDataRefUpdate(func() { |
| 249 | if fired { |
| 250 | return |
| 251 | } |
| 252 | fired = true |
| 253 | var err error |
| 254 | firstCommit, err = gc.SyncToDataRef(ctx, repo, testDataRef, "Run "+first.ID, |
| 255 | map[string]string{"runs/" + first.ID + ".json": filepath.Join(store.StateDir(), first.ID+".json")}) |
| 256 | if err != nil { |
| 257 | t.Fatalf("first run's sync: %v", err) |
| 258 | } |
| 259 | })) |
| 260 | syncRunToDataRef(ctx, repo, store, gc, testDataRef, true, second) |
| 261 | recordDataRefPush(ctx, store, gc, repo, testDataRef, firstCommit, true, first) |
| 262 | |
| 263 | tip, err := gitOut(t, origin, "rev-parse", "--verify", testDataRef) |
| 264 | if err != nil { |
| 265 | t.Fatalf("origin lacks %s: %v", testDataRef, err) |
| 266 | } |
| 267 | for _, st := range []*run.State{first, second} { |
| 268 | rec := st.DataRefPush |
| 269 | if rec == nil || rec.Status != run.DataRefPublished || rec.Commit == "" { |
| 270 | t.Fatalf("%s DataRefPush = %+v, want published", st.ID, rec) |
| 271 | } |
| 272 | if _, err := gitOut(t, origin, "merge-base", "--is-ancestor", rec.Commit, tip); err != nil { |
| 273 | t.Errorf("%s recorded published, but origin's %s at %s lacks its commit %s", st.ID, testDataRef, tip, rec.Commit) |
| 274 | } |
| 275 | } |
| 276 | if first.DataRefPush.Commit == second.DataRefPush.Commit { |
| 277 | t.Errorf("both runs recorded commit %s", first.DataRefPush.Commit) |
| 278 | } |
| 279 | } |
| 280 | |
| 281 | // historyRewriter rewinds the data ref past the run's commit before each |
| 282 | // push, as a writer that ignores the ref's old value can, so the pushed |
| 283 | // history lacks that commit. |
| 284 | type historyRewriter struct{ *git.ExecClient } |
| 285 | |
| 286 | func (c historyRewriter) PushDataRef(ctx context.Context, repoDir, dataRef string) (string, error) { |
| 287 | if out, err := exec.Command("git", "-C", repoDir, "update-ref", dataRef, dataRef+"^").CombinedOutput(); err != nil { |
| 288 | return "", fmt.Errorf("rewinding %s: %v: %s", dataRef, err, out) |
| 289 | } |
| 290 | return c.ExecClient.PushDataRef(ctx, repoDir, dataRef) |
| 291 | } |
| 292 | |
| 293 | // TestFinalizeRecordsCommitMissingFromPushedHistory: a push that succeeds |
| 294 | // with a history lacking the run's commit records a failure, not a |
| 295 | // publication. |
| 296 | func TestFinalizeRecordsCommitMissingFromPushedHistory(t *testing.T) { |
| 297 | home := t.TempDir() |
| 298 | t.Setenv("HOME", home) |
| 299 | t.Setenv("USERPROFILE", home) |
| 300 | _, repo, _, _ := setupBareRemote(t) |
| 301 | store := run.NewHomeDirStoreFromPath(filepath.Join(t.TempDir(), "session")) |
| 302 | if err := store.EnsureDirs(); err != nil { |
| 303 | t.Fatal(err) |
| 304 | } |
| 305 | st := finishedClaudeRun(t, store, home, "20261004-1700-aaaa", "6623bdcf-1dce-4da0-86b3-a46743d208e8") |
| 306 | |
| 307 | stderr := captureStderr(t, func() { |
| 308 | syncRunToDataRef(context.Background(), repo, store, historyRewriter{git.NewExecClient()}, testDataRef, true, st) |
| 309 | }) |
| 310 | if rec := st.DataRefPush; rec == nil || rec.Status != run.DataRefFailed || rec.Class != git.PushOther || rec.Message != dataRefNotInHistory { |
| 311 | t.Fatalf("DataRefPush = %+v, want a failure saying the commit is not in the pushed history", rec) |
| 312 | } |
| 313 | if !strings.Contains(stderr, dataRefNotInHistory) { |
| 314 | t.Errorf("finalize's warning lacks the failure:\n%s", stderr) |
| 315 | } |
| 316 | } |
| 317 | |
| 318 | // TestOversizedRefusalKeepsNotificationsReadable: a hook that prints more |
| 319 | // than the event log reader's 1 MiB line limit leaves a bounded message, and |
| 320 | // the event log still reads. |
| 321 | func TestOversizedRefusalKeepsNotificationsReadable(t *testing.T) { |
| 322 | home := t.TempDir() |
| 323 | t.Setenv("HOME", home) |
| 324 | t.Setenv("USERPROFILE", home) |
| 325 | origin, repo, _, _ := setupBareRemote(t) |
| 326 | refuseDataRef(t, origin, `line=$(printf '%01024d' 0); i=0; while [ $i -lt 1300 ]; do echo "$line" >&2; i=$((i+1)); done`) |
| 327 | store := run.NewHomeDirStoreFromPath(filepath.Join(t.TempDir(), "session")) |
| 328 | if err := store.EnsureDirs(); err != nil { |
| 329 | t.Fatal(err) |
| 330 | } |
| 331 | st := finishedClaudeRun(t, store, home, "20261004-1500-aaaa", "6623bdcf-1dce-4da0-86b3-a46743d208e8") |
| 332 | captureStderr(t, func() { |
| 333 | syncRunToDataRef(context.Background(), repo, store, git.NewExecClient(), testDataRef, true, st) |
| 334 | }) |
| 335 | |
| 336 | if rec := st.DataRefPush; rec == nil || len(rec.Message) > git.MaxPushMessage || !strings.HasSuffix(rec.Message, git.PushMessageCut) { |
| 337 | t.Fatalf("DataRefPush message is not bounded and marked: %+v", rec) |
| 338 | } |
| 339 | emitEvent(store.BaseDir(), st.ID, event.AgentCompleted, nil) |
| 340 | evts, err := event.NewLog(store.BaseDir()).Read() |
| 341 | if err != nil || len(evts) < 2 || evts[len(evts)-1].Type != event.AgentCompleted { |
| 342 | t.Fatalf("event log after the refusal = %d events, %v; want it to read through the next event", len(evts), err) |
| 343 | } |
| 344 | if out := captureStdout(t, func() { printSummary(evts, nil) }); !strings.Contains(out, "1 data ref push(es) failed at finalize") { |
| 345 | t.Errorf("notifications summary lacks the failure:\n%s", out) |
| 346 | } |
| 347 | } |
| 348 | |
| 349 | // captureStderr returns what fn writes to os.Stderr. |
| 350 | func captureStderr(t *testing.T, fn func()) string { |
| 351 | t.Helper() |
| 352 | f, err := os.CreateTemp(t.TempDir(), "stderr") |
| 353 | if err != nil { |
| 354 | t.Fatal(err) |
| 355 | } |
| 356 | old := os.Stderr |
| 357 | os.Stderr = f |
| 358 | defer func() { os.Stderr = old }() |
| 359 | fn() |
| 360 | out, err := os.ReadFile(f.Name()) |
| 361 | if err != nil { |
| 362 | t.Fatal(err) |
| 363 | } |
| 364 | return string(out) |
| 365 | } |
| 366 | |
| 367 | // finishedClaudeRun saves a finished run whose log and resumable conversation |
| 368 | // exist on disk under home, as _finalize sees one. |
| 369 | func finishedClaudeRun(t *testing.T, store run.StateStore, home, id, sessionID string) *run.State { |
| 370 | t.Helper() |
| 371 | worktree := filepath.Join(home, "worktrees", id) |
| 372 | conv := claudeConversationPath(worktree, sessionID) |
| 373 | if err := os.MkdirAll(filepath.Dir(conv), 0o755); err != nil { |
| 374 | t.Fatal(err) |
| 375 | } |
| 376 | if err := os.WriteFile(conv, []byte(makeConversationJSONL(sessionID, worktree)), 0o600); err != nil { |
| 377 | t.Fatal(err) |
| 378 | } |
| 379 | logFile := filepath.Join(store.LogDir(), id+".jsonl") |
| 380 | if err := os.WriteFile(logFile, []byte(`{"type":"result","subtype":"success"}`+"\n"), 0o644); err != nil { |
| 381 | t.Fatal(err) |
| 382 | } |
| 383 | sid := sessionID |
| 384 | st := &run.State{ |
| 385 | ID: id, |
| 386 | Branch: "feature-x", |
| 387 | Worktree: worktree, |
| 388 | LogFile: &logFile, |
| 389 | CreatedAt: "2026-10-04T" + id[9:11] + ":" + id[11:13] + ":00Z", // id is YYYYMMDD-HHMM-xxxx |
| 390 | ClaudeSessionID: &sid, |
| 391 | } |
| 392 | if err := store.Save(st); err != nil { |
| 393 | t.Fatalf("Save: %v", err) |
| 394 | } |
| 395 | return st |
| 396 | } |
| 397 | |
| 398 | // TestReplayReadsUnpushedDataRef: trajectory replay needs nothing on origin. |
| 399 | // It reads the local data ref finalize committed to, and its best-effort |
| 400 | // fetch neither fails the replay nor rewinds a local ref that is ahead of a |
| 401 | // copy published before push_data_ref existed. |
| 402 | func TestReplayReadsUnpushedDataRef(t *testing.T) { |
| 403 | setup := func(t *testing.T) (home, origin, repo string, store run.StateStore) { |
| 404 | home = t.TempDir() |
| 405 | t.Setenv("HOME", home) |
| 406 | t.Setenv("USERPROFILE", home) |
| 407 | origin, repo, _, _ = setupBareRemote(t) |
| 408 | s := run.NewHomeDirStoreFromPath(filepath.Join(t.TempDir(), "session")) |
| 409 | if err := s.EnsureDirs(); err != nil { |
| 410 | t.Fatalf("EnsureDirs: %v", err) |
| 411 | } |
| 412 | return home, origin, repo, s |
| 413 | } |
| 414 | replay := func(store run.StateStore, repo, home string) replayDecision { |
| 415 | return resolveReplay(context.Background(), replayParams{ |
| 416 | GitClient: git.NewExecClient(), |
| 417 | Store: store, |
| 418 | RepoRoot: repo, |
| 419 | DataRef: testDataRef, |
| 420 | Worktree: filepath.Join(home, "worktrees", "resumed"), |
| 421 | PRBranch: "feature-x", |
| 422 | PRNumber: "7", |
| 423 | ForceReplay: true, // skip the gh paused-label check |
| 424 | ThresholdKB: 300, |
| 425 | }) |
| 426 | } |
| 427 | ctx := context.Background() |
| 428 | |
| 429 | t.Run("origin never had the ref", func(t *testing.T) { |
| 430 | home, origin, repo, store := setup(t) |
| 431 | const sessionID = "6623bdcf-1dce-4da0-86b3-a46743d208e8" |
| 432 | st := finishedClaudeRun(t, store, home, "20261004-1000-aaaa", sessionID) |
| 433 | syncRunToDataRef(ctx, repo, store, git.NewExecClient(), testDataRef, false, st) |
| 434 | |
| 435 | if d := replay(store, repo, home); d.SessionUUID != sessionID { |
| 436 | t.Fatalf("SessionUUID = %q, want %q (%s)", d.SessionUUID, sessionID, d.Reason) |
| 437 | } |
| 438 | if _, err := gitOut(t, origin, "rev-parse", "--verify", "--quiet", testDataRef); err == nil { |
| 439 | t.Errorf("origin gained %s", testDataRef) |
| 440 | } |
| 441 | }) |
| 442 | |
| 443 | t.Run("origin holds a stale published ref", func(t *testing.T) { |
| 444 | home, origin, repo, store := setup(t) |
| 445 | gc := git.NewExecClient() |
| 446 | old := finishedClaudeRun(t, store, home, "20261004-0900-aaaa", "11111111-2222-4333-8444-555555555555") |
| 447 | syncRunToDataRef(ctx, repo, store, gc, testDataRef, true, old) |
| 448 | published, err := gitOut(t, origin, "rev-parse", "--verify", testDataRef) |
| 449 | if err != nil { |
| 450 | t.Fatalf("setup: first run not published: %v", err) |
| 451 | } |
| 452 | |
| 453 | const sessionID = "99999999-8888-4777-8666-555555555555" |
| 454 | newer := finishedClaudeRun(t, store, home, "20261004-1000-bbbb", sessionID) |
| 455 | syncRunToDataRef(ctx, repo, store, gc, testDataRef, false, newer) |
| 456 | local, _ := gitOut(t, repo, "rev-parse", testDataRef) |
| 457 | |
| 458 | d := replay(store, repo, home) |
| 459 | if d.SessionUUID != sessionID || d.SourceRunID != newer.ID { |
| 460 | t.Fatalf("resumed %q from %q, want %q from %q (%s)", d.SessionUUID, d.SourceRunID, sessionID, newer.ID, d.Reason) |
| 461 | } |
| 462 | if got, _ := gitOut(t, repo, "rev-parse", testDataRef); got != local { |
| 463 | t.Errorf("local %s moved from %s to %s during replay's fetch", testDataRef, local, got) |
| 464 | } |
| 465 | if got, _ := gitOut(t, origin, "rev-parse", testDataRef); got != published { |
| 466 | t.Errorf("origin %s = %q, want it left at the published %s", testDataRef, got, published) |
| 467 | } |
| 468 | }) |
| 469 | } |
| 470 | |
| 471 | // TestPushLogPushesOnlyWhenAsked: push-log commits a held-back log to the |
| 472 | // local data ref, and publishes it only with --push. |
| 473 | func TestPushLogPushesOnlyWhenAsked(t *testing.T) { |
| 474 | origin, repo, _, _ := setupBareRemote(t) |
| 475 | t.Setenv("HOME", t.TempDir()) |
| 476 | const sessionID = "20261004-1100-pushlog-session" |
| 477 | t.Setenv(sessionIDEnv, sessionID) |
| 478 | store, err := run.NewHomeDirStore(sessionID) |
| 479 | if err != nil { |
| 480 | t.Fatalf("NewHomeDirStore: %v", err) |
| 481 | } |
| 482 | if err := store.EnsureDirs(); err != nil { |
| 483 | t.Fatalf("EnsureDirs: %v", err) |
| 484 | } |
| 485 | const id = "20261004-1100-aaaa" |
| 486 | logFile := filepath.Join(store.LogDir(), id+".jsonl") |
| 487 | if err := os.WriteFile(logFile, []byte(`{"type":"result","subtype":"success"}`+"\n"), 0o644); err != nil { |
| 488 | t.Fatal(err) |
| 489 | } |
| 490 | if err := store.Save(&run.State{ID: id, Branch: "b", CreatedAt: "2026-10-04T11:00:00Z", LogFile: &logFile, CloneDir: &repo}); err != nil { |
| 491 | t.Fatalf("Save: %v", err) |
| 492 | } |
| 493 | t.Cleanup(func() { pushLogPush = false }) |
| 494 | pushLog := func(push bool) error { |
| 495 | pushLogPush = push |
| 496 | pushLogCmd.SetContext(context.Background()) |
| 497 | return pushLogCmd.RunE(pushLogCmd, []string{id}) |
| 498 | } |
| 499 | |
| 500 | if err := pushLog(false); err != nil { |
| 501 | t.Fatalf("push-log: %v", err) |
| 502 | } |
| 503 | if files, _ := gitOut(t, repo, "ls-tree", "-r", "--name-only", testDataRef); !strings.Contains(files, "logs/"+id+".jsonl") { |
| 504 | t.Fatalf("local %s missing the log; has:\n%s", testDataRef, files) |
| 505 | } |
| 506 | if _, err := gitOut(t, origin, "rev-parse", "--verify", "--quiet", testDataRef); err == nil { |
| 507 | t.Fatalf("push-log without --push published %s", testDataRef) |
| 508 | } |
| 509 | |
| 510 | if err := pushLog(true); err != nil { |
| 511 | t.Fatalf("push-log --push: %v", err) |
| 512 | } |
| 513 | local, _ := gitOut(t, repo, "rev-parse", testDataRef) |
| 514 | if remote, err := gitOut(t, origin, "rev-parse", "--verify", testDataRef); err != nil || remote != local { |
| 515 | t.Fatalf("origin %s = %q (%v), want %s", testDataRef, remote, err, local) |
| 516 | } |
| 517 | |
| 518 | runGitCmd(t, repo, "remote", "set-url", "origin", origin+"-gone") |
| 519 | if err := pushLog(true); err == nil { |
| 520 | t.Error("push-log --push must fail when the push fails") |
| 521 | } |
| 522 | } |
| 523 | |
| 524 | // TestSyncScansAgainstOwnRemote: a valley repo's origin is a private-IP |
| 525 | // scp-style remote. A log naming that origin is stored on the data ref; a log |
| 526 | // naming any other private address is kept off it. |
| 527 | func TestSyncScansAgainstOwnRemote(t *testing.T) { |
| 528 | for _, tc := range []struct { |
| 529 | name, log string |
| 530 | stored bool |
| 531 | }{ |
| 532 | {"own origin", `{"type":"assistant","text":"To 10.0.2.1:the-valley.git"}`, true}, |
| 533 | {"other address", `{"type":"assistant","text":"To 10.0.2.2:the-valley.git"}`, false}, |
| 534 | } { |
| 535 | t.Run(tc.name, func(t *testing.T) { |
| 536 | home := t.TempDir() |
| 537 | t.Setenv("HOME", home) |
| 538 | t.Setenv("USERPROFILE", home) |
| 539 | _, repo, _, _ := setupBareRemote(t) |
| 540 | runGitCmd(t, repo, "remote", "set-url", "origin", "git@10.0.2.1:the-valley.git") |
| 541 | store := run.NewHomeDirStoreFromPath(filepath.Join(t.TempDir(), "session")) |
| 542 | if err := store.EnsureDirs(); err != nil { |
| 543 | t.Fatal(err) |
| 544 | } |
| 545 | st := finishedClaudeRun(t, store, home, "20261015-1000-aaaa", "6623bdcf-1dce-4da0-86b3-a46743d208e8") |
| 546 | if err := os.WriteFile(*st.LogFile, []byte(tc.log+"\n"), 0o644); err != nil { |
| 547 | t.Fatal(err) |
| 548 | } |
| 549 | syncRunToDataRef(context.Background(), repo, store, git.NewExecClient(), testDataRef, false, st) |
| 550 | files, err := gitOut(t, repo, "ls-tree", "-r", "--name-only", testDataRef) |
| 551 | if err != nil { |
| 552 | t.Fatalf("ls-tree: %v %s", err, files) |
| 553 | } |
| 554 | if got := strings.Contains(files, "logs/"+st.ID+".jsonl"); got != tc.stored { |
| 555 | t.Errorf("log stored = %v, want %v; files:\n%s", got, tc.stored, files) |
| 556 | } |
| 557 | }) |
| 558 | } |
| 559 | } |