| 1 | package cmd |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "os" |
| 6 | "path/filepath" |
| 7 | "strings" |
| 8 | "testing" |
| 9 | |
| 10 | "the-valley/flow/internal/git" |
| 11 | "the-valley/flow/internal/run" |
| 12 | ) |
| 13 | |
| 14 | const testDataRef = "refs/klaus/data" |
| 15 | |
| 16 | // finalizePRLog is a clean run that opened a PR, so _finalize takes the |
| 17 | // normal path (no salvage) through the data-ref sync. Its runs record PR |
| 18 | // delivery, as launch does for a repo on GitHub, since the bare origin's path |
| 19 | // isn't a GitHub URL. |
| 20 | const finalizePRLog = `{"type":"assistant","message":{"content":[{"type":"text","text":"Opened https://github.com/acme/widget/pull/9"}]}} |
| 21 | {"type":"result","subtype":"success","total_cost_usd":1,"duration_ms":1000} |
| 22 | ` |
| 23 | |
| 24 | // TestFinalizeKeepsDataRefLocalByDefault runs the real _finalize against a |
| 25 | // clone with a bare origin: the run lands on the local data ref, and origin |
| 26 | // never receives it. |
| 27 | func TestFinalizeKeepsDataRefLocalByDefault(t *testing.T) { |
| 28 | origin, repo, worktree, branch := setupBareRemote(t) |
| 29 | commitAndPush(t, worktree, branch) |
| 30 | |
| 31 | _, state, _ := finalizeRealRepo(t, repo, worktree, branch, finalizePRLog, run.DeliveryPR) |
| 32 | |
| 33 | files, err := gitOut(t, repo, "ls-tree", "-r", "--name-only", testDataRef) |
| 34 | if err != nil { |
| 35 | t.Fatalf("local %s missing after finalize: %v %s", testDataRef, err, files) |
| 36 | } |
| 37 | for _, want := range []string{"runs/" + state.ID + ".json", "logs/" + state.ID + ".jsonl"} { |
| 38 | if !strings.Contains(files, want) { |
| 39 | t.Errorf("local %s missing %s; has:\n%s", testDataRef, want, files) |
| 40 | } |
| 41 | } |
| 42 | if sha, err := gitOut(t, origin, "rev-parse", "--verify", "--quiet", testDataRef); err == nil { |
| 43 | t.Fatalf("origin has %s at %s; the default config must not push it", testDataRef, sha) |
| 44 | } |
| 45 | } |
| 46 | |
| 47 | // TestFinalizePushesDataRefWhenEnabled: push_data_ref: true restores the push. |
| 48 | func TestFinalizePushesDataRefWhenEnabled(t *testing.T) { |
| 49 | origin, repo, worktree, branch := setupBareRemote(t) |
| 50 | commitAndPush(t, worktree, branch) |
| 51 | if err := os.MkdirAll(filepath.Join(repo, ".klaus"), 0o755); err != nil { |
| 52 | t.Fatal(err) |
| 53 | } |
| 54 | if err := os.WriteFile(filepath.Join(repo, ".klaus", "config.json"), []byte(`{"push_data_ref": true}`), 0o644); err != nil { |
| 55 | t.Fatal(err) |
| 56 | } |
| 57 | |
| 58 | finalizeRealRepo(t, repo, worktree, branch, finalizePRLog, run.DeliveryPR) |
| 59 | |
| 60 | local, err := gitOut(t, repo, "rev-parse", testDataRef) |
| 61 | if err != nil { |
| 62 | t.Fatalf("local %s missing after finalize: %v", testDataRef, err) |
| 63 | } |
| 64 | if remote, err := gitOut(t, origin, "rev-parse", "--verify", testDataRef); err != nil || remote != local { |
| 65 | t.Fatalf("origin %s = %q (%v), want the local commit %s", testDataRef, remote, err, local) |
| 66 | } |
| 67 | } |
| 68 | |
| 69 | // finishedClaudeRun saves a finished run whose log and resumable conversation |
| 70 | // exist on disk under home, as _finalize sees one. |
| 71 | func finishedClaudeRun(t *testing.T, store run.StateStore, home, id, sessionID string) *run.State { |
| 72 | t.Helper() |
| 73 | worktree := filepath.Join(home, "worktrees", id) |
| 74 | conv := claudeConversationPath(worktree, sessionID) |
| 75 | if err := os.MkdirAll(filepath.Dir(conv), 0o755); err != nil { |
| 76 | t.Fatal(err) |
| 77 | } |
| 78 | if err := os.WriteFile(conv, []byte(makeConversationJSONL(sessionID, worktree)), 0o600); err != nil { |
| 79 | t.Fatal(err) |
| 80 | } |
| 81 | logFile := filepath.Join(store.LogDir(), id+".jsonl") |
| 82 | if err := os.WriteFile(logFile, []byte(`{"type":"result","subtype":"success"}`+"\n"), 0o644); err != nil { |
| 83 | t.Fatal(err) |
| 84 | } |
| 85 | sid := sessionID |
| 86 | st := &run.State{ |
| 87 | ID: id, |
| 88 | Branch: "feature-x", |
| 89 | Worktree: worktree, |
| 90 | LogFile: &logFile, |
| 91 | CreatedAt: "2026-10-04T" + id[9:11] + ":" + id[11:13] + ":00Z", // id is YYYYMMDD-HHMM-xxxx |
| 92 | ClaudeSessionID: &sid, |
| 93 | } |
| 94 | if err := store.Save(st); err != nil { |
| 95 | t.Fatalf("Save: %v", err) |
| 96 | } |
| 97 | return st |
| 98 | } |
| 99 | |
| 100 | // TestReplayReadsUnpushedDataRef: trajectory replay needs nothing on origin. |
| 101 | // It reads the local data ref finalize committed to, and its best-effort |
| 102 | // fetch neither fails the replay nor rewinds a local ref that is ahead of a |
| 103 | // copy published before push_data_ref existed. |
| 104 | func TestReplayReadsUnpushedDataRef(t *testing.T) { |
| 105 | setup := func(t *testing.T) (home, origin, repo string, store run.StateStore) { |
| 106 | home = t.TempDir() |
| 107 | t.Setenv("HOME", home) |
| 108 | t.Setenv("USERPROFILE", home) |
| 109 | origin, repo, _, _ = setupBareRemote(t) |
| 110 | s := run.NewHomeDirStoreFromPath(filepath.Join(t.TempDir(), "session")) |
| 111 | if err := s.EnsureDirs(); err != nil { |
| 112 | t.Fatalf("EnsureDirs: %v", err) |
| 113 | } |
| 114 | return home, origin, repo, s |
| 115 | } |
| 116 | replay := func(store run.StateStore, repo, home string) replayDecision { |
| 117 | return resolveReplay(context.Background(), replayParams{ |
| 118 | GitClient: git.NewExecClient(), |
| 119 | Store: store, |
| 120 | RepoRoot: repo, |
| 121 | DataRef: testDataRef, |
| 122 | Worktree: filepath.Join(home, "worktrees", "resumed"), |
| 123 | PRBranch: "feature-x", |
| 124 | PRNumber: "7", |
| 125 | ForceReplay: true, // skip the gh paused-label check |
| 126 | ThresholdKB: 300, |
| 127 | }) |
| 128 | } |
| 129 | ctx := context.Background() |
| 130 | |
| 131 | t.Run("origin never had the ref", func(t *testing.T) { |
| 132 | home, origin, repo, store := setup(t) |
| 133 | const sessionID = "6623bdcf-1dce-4da0-86b3-a46743d208e8" |
| 134 | st := finishedClaudeRun(t, store, home, "20261004-1000-aaaa", sessionID) |
| 135 | syncRunToDataRef(ctx, repo, store, git.NewExecClient(), testDataRef, false, st) |
| 136 | |
| 137 | if d := replay(store, repo, home); d.SessionUUID != sessionID { |
| 138 | t.Fatalf("SessionUUID = %q, want %q (%s)", d.SessionUUID, sessionID, d.Reason) |
| 139 | } |
| 140 | if _, err := gitOut(t, origin, "rev-parse", "--verify", "--quiet", testDataRef); err == nil { |
| 141 | t.Errorf("origin gained %s", testDataRef) |
| 142 | } |
| 143 | }) |
| 144 | |
| 145 | t.Run("origin holds a stale published ref", func(t *testing.T) { |
| 146 | home, origin, repo, store := setup(t) |
| 147 | gc := git.NewExecClient() |
| 148 | old := finishedClaudeRun(t, store, home, "20261004-0900-aaaa", "11111111-2222-4333-8444-555555555555") |
| 149 | syncRunToDataRef(ctx, repo, store, gc, testDataRef, true, old) |
| 150 | published, err := gitOut(t, origin, "rev-parse", "--verify", testDataRef) |
| 151 | if err != nil { |
| 152 | t.Fatalf("setup: first run not published: %v", err) |
| 153 | } |
| 154 | |
| 155 | const sessionID = "99999999-8888-4777-8666-555555555555" |
| 156 | newer := finishedClaudeRun(t, store, home, "20261004-1000-bbbb", sessionID) |
| 157 | syncRunToDataRef(ctx, repo, store, gc, testDataRef, false, newer) |
| 158 | local, _ := gitOut(t, repo, "rev-parse", testDataRef) |
| 159 | |
| 160 | d := replay(store, repo, home) |
| 161 | if d.SessionUUID != sessionID || d.SourceRunID != newer.ID { |
| 162 | t.Fatalf("resumed %q from %q, want %q from %q (%s)", d.SessionUUID, d.SourceRunID, sessionID, newer.ID, d.Reason) |
| 163 | } |
| 164 | if got, _ := gitOut(t, repo, "rev-parse", testDataRef); got != local { |
| 165 | t.Errorf("local %s moved from %s to %s during replay's fetch", testDataRef, local, got) |
| 166 | } |
| 167 | if got, _ := gitOut(t, origin, "rev-parse", testDataRef); got != published { |
| 168 | t.Errorf("origin %s = %q, want it left at the published %s", testDataRef, got, published) |
| 169 | } |
| 170 | }) |
| 171 | } |
| 172 | |
| 173 | // TestPushLogPushesOnlyWhenAsked: push-log commits a held-back log to the |
| 174 | // local data ref, and publishes it only with --push. |
| 175 | func TestPushLogPushesOnlyWhenAsked(t *testing.T) { |
| 176 | origin, repo, _, _ := setupBareRemote(t) |
| 177 | t.Setenv("HOME", t.TempDir()) |
| 178 | const sessionID = "20261004-1100-pushlog-session" |
| 179 | t.Setenv(sessionIDEnv, sessionID) |
| 180 | store, err := run.NewHomeDirStore(sessionID) |
| 181 | if err != nil { |
| 182 | t.Fatalf("NewHomeDirStore: %v", err) |
| 183 | } |
| 184 | if err := store.EnsureDirs(); err != nil { |
| 185 | t.Fatalf("EnsureDirs: %v", err) |
| 186 | } |
| 187 | const id = "20261004-1100-aaaa" |
| 188 | logFile := filepath.Join(store.LogDir(), id+".jsonl") |
| 189 | if err := os.WriteFile(logFile, []byte(`{"type":"result","subtype":"success"}`+"\n"), 0o644); err != nil { |
| 190 | t.Fatal(err) |
| 191 | } |
| 192 | if err := store.Save(&run.State{ID: id, Branch: "b", CreatedAt: "2026-10-04T11:00:00Z", LogFile: &logFile, CloneDir: &repo}); err != nil { |
| 193 | t.Fatalf("Save: %v", err) |
| 194 | } |
| 195 | t.Cleanup(func() { pushLogPush = false }) |
| 196 | pushLog := func(push bool) error { |
| 197 | pushLogPush = push |
| 198 | pushLogCmd.SetContext(context.Background()) |
| 199 | return pushLogCmd.RunE(pushLogCmd, []string{id}) |
| 200 | } |
| 201 | |
| 202 | if err := pushLog(false); err != nil { |
| 203 | t.Fatalf("push-log: %v", err) |
| 204 | } |
| 205 | if files, _ := gitOut(t, repo, "ls-tree", "-r", "--name-only", testDataRef); !strings.Contains(files, "logs/"+id+".jsonl") { |
| 206 | t.Fatalf("local %s missing the log; has:\n%s", testDataRef, files) |
| 207 | } |
| 208 | if _, err := gitOut(t, origin, "rev-parse", "--verify", "--quiet", testDataRef); err == nil { |
| 209 | t.Fatalf("push-log without --push published %s", testDataRef) |
| 210 | } |
| 211 | |
| 212 | if err := pushLog(true); err != nil { |
| 213 | t.Fatalf("push-log --push: %v", err) |
| 214 | } |
| 215 | local, _ := gitOut(t, repo, "rev-parse", testDataRef) |
| 216 | if remote, err := gitOut(t, origin, "rev-parse", "--verify", testDataRef); err != nil || remote != local { |
| 217 | t.Fatalf("origin %s = %q (%v), want %s", testDataRef, remote, err, local) |
| 218 | } |
| 219 | |
| 220 | runGitCmd(t, repo, "remote", "set-url", "origin", origin+"-gone") |
| 221 | if err := pushLog(true); err == nil { |
| 222 | t.Error("push-log --push must fail when the push fails") |
| 223 | } |
| 224 | } |
| 225 | |
| 226 | // TestSyncScansAgainstOwnRemote: a valley repo's origin is a private-IP |
| 227 | // scp-style remote. A log naming that origin is stored on the data ref; a log |
| 228 | // naming any other private address is kept off it. |
| 229 | func TestSyncScansAgainstOwnRemote(t *testing.T) { |
| 230 | for _, tc := range []struct { |
| 231 | name, log string |
| 232 | stored bool |
| 233 | }{ |
| 234 | {"own origin", `{"type":"assistant","text":"To 10.0.2.1:the-valley.git"}`, true}, |
| 235 | {"other address", `{"type":"assistant","text":"To 10.0.2.2:the-valley.git"}`, false}, |
| 236 | } { |
| 237 | t.Run(tc.name, func(t *testing.T) { |
| 238 | home := t.TempDir() |
| 239 | t.Setenv("HOME", home) |
| 240 | t.Setenv("USERPROFILE", home) |
| 241 | _, repo, _, _ := setupBareRemote(t) |
| 242 | runGitCmd(t, repo, "remote", "set-url", "origin", "git@10.0.2.1:the-valley.git") |
| 243 | store := run.NewHomeDirStoreFromPath(filepath.Join(t.TempDir(), "session")) |
| 244 | if err := store.EnsureDirs(); err != nil { |
| 245 | t.Fatal(err) |
| 246 | } |
| 247 | st := finishedClaudeRun(t, store, home, "20261015-1000-aaaa", "6623bdcf-1dce-4da0-86b3-a46743d208e8") |
| 248 | if err := os.WriteFile(*st.LogFile, []byte(tc.log+"\n"), 0o644); err != nil { |
| 249 | t.Fatal(err) |
| 250 | } |
| 251 | syncRunToDataRef(context.Background(), repo, store, git.NewExecClient(), testDataRef, false, st) |
| 252 | files, err := gitOut(t, repo, "ls-tree", "-r", "--name-only", testDataRef) |
| 253 | if err != nil { |
| 254 | t.Fatalf("ls-tree: %v %s", err, files) |
| 255 | } |
| 256 | if got := strings.Contains(files, "logs/"+st.ID+".jsonl"); got != tc.stored { |
| 257 | t.Errorf("log stored = %v, want %v; files:\n%s", got, tc.stored, files) |
| 258 | } |
| 259 | }) |
| 260 | } |
| 261 | } |