| 1 | package main |
| 2 | |
| 3 | import ( |
| 4 | "encoding/json" |
| 5 | "os" |
| 6 | "os/exec" |
| 7 | "path/filepath" |
| 8 | "reflect" |
| 9 | "testing" |
| 10 | |
| 11 | "reasonix/desktop/internal/workspacestate" |
| 12 | "reasonix/internal/agent" |
| 13 | "reasonix/internal/provider" |
| 14 | ) |
| 15 | |
| 16 | func TestHistoricalImportRetrySettlesWorkspaceConflict(t *testing.T) { |
| 17 | app, projectRoot, path := historicalRecoveryFixture(t) |
| 18 | app.ctx = t.Context() |
| 19 | installNoopRuntimeEvents(app) |
| 20 | t.Cleanup(app.stopHistoricalImports) |
| 21 | elsewhere := historicalRecoveryGitRoot(t, robustTempDir(t)) |
| 22 | if err := agent.SaveBranchMetaPreserveUpdated(path, agent.BranchMeta{Scope: "project", WorkspaceRoot: elsewhere}); err != nil { |
| 23 | t.Fatal(err) |
| 24 | } |
| 25 | if _, err := app.ListHistoricalSessions(); err != nil { |
| 26 | t.Fatal(err) |
| 27 | } |
| 28 | if _, err := app.StartHistoricalImport(nil); err != nil { |
| 29 | t.Fatal(err) |
| 30 | } |
| 31 | first := awaitHistoricalBatch(t, app) |
| 32 | if len(first.Items) != 1 || first.Items[0].Status != "failed" || first.Items[0].ErrorCode != "workspace_conflict" { |
| 33 | t.Fatalf("fixture must create actual conflict: %+v", first) |
| 34 | } |
| 35 | before, err := app.workspaceRegistry().Load(t.Context()) |
| 36 | if err != nil { |
| 37 | t.Fatal(err) |
| 38 | } |
| 39 | if len(before.RecoveryEntries) != 1 { |
| 40 | t.Fatalf("conflict did not create one recovery entry: %+v", before.RecoveryEntries) |
| 41 | } |
| 42 | if err := agent.SaveBranchMetaPreserveUpdated(path, agent.BranchMeta{Scope: "project", WorkspaceRoot: projectRoot}); err != nil { |
| 43 | t.Fatal(err) |
| 44 | } |
| 45 | if _, err := app.StartHistoricalImport(nil); err != nil { |
| 46 | t.Fatal(err) |
| 47 | } |
| 48 | after := awaitHistoricalBatch(t, app) |
| 49 | if len(after.Items) != 1 || after.Items[0].Status != "imported" { |
| 50 | t.Fatalf("retry failed: %+v", after) |
| 51 | } |
| 52 | state, err := app.workspaceRegistry().Load(t.Context()) |
| 53 | if err != nil { |
| 54 | t.Fatal(err) |
| 55 | } |
| 56 | histories := v5MigrationHistories(t, app) |
| 57 | if len(histories) != 1 { |
| 58 | t.Fatalf("retry did not produce readable history: %+v", histories) |
| 59 | } |
| 60 | pending := 0 |
| 61 | for _, entry := range state.RecoveryEntries { |
| 62 | if entry.Status == "pending" { |
| 63 | pending++ |
| 64 | } |
| 65 | } |
| 66 | t.Logf("actual workspace_conflict -> repaired metadata -> imported + readable; recovery entries still pending=%d", pending) |
| 67 | if pending != 0 { |
| 68 | t.Errorf("successful retry left %d stale pending recovery entries", pending) |
| 69 | } |
| 70 | } |
| 71 | |
| 72 | func TestHistoricalImportReceiptReplaySettlesWorkspaceConflict(t *testing.T) { |
| 73 | testHistoricalImportReceiptReplay(t, workspacestate.Active, false, false) |
| 74 | } |
| 75 | |
| 76 | func TestHistoricalImportArchivedReceiptReplaySettlesWorkspaceConflict(t *testing.T) { |
| 77 | for _, test := range []struct { |
| 78 | name string |
| 79 | removeMapping, missingTarget bool |
| 80 | }{ |
| 81 | {name: "existing-mapping"}, {name: "repaired-mapping", removeMapping: true}, {name: "unreadable-target", missingTarget: true}, |
| 82 | } { |
| 83 | t.Run(test.name, func(t *testing.T) { |
| 84 | testHistoricalImportReceiptReplay(t, workspacestate.Archived, test.removeMapping, test.missingTarget) |
| 85 | }) |
| 86 | } |
| 87 | } |
| 88 | |
| 89 | func TestHistoricalImportDeletedReceiptReplayPreservesRecovery(t *testing.T) { |
| 90 | testHistoricalImportReceiptReplay(t, workspacestate.Deleted, false, false) |
| 91 | } |
| 92 | |
| 93 | func testHistoricalImportReceiptReplay(t *testing.T, lifecycle string, removeMapping, missingTarget bool) { |
| 94 | t.Helper() |
| 95 | app, projectRoot, path := historicalRecoveryFixture(t) |
| 96 | source := desktopMigrationSource{scope: "project", workspaceRoot: projectRoot} |
| 97 | if err := app.migrateLegacySession(t.Context(), path, source, ""); err != nil { |
| 98 | t.Fatal(err) |
| 99 | } |
| 100 | state, err := app.workspaceRegistry().Load(t.Context()) |
| 101 | if err != nil { |
| 102 | t.Fatal(err) |
| 103 | } |
| 104 | if len(state.SourceMappings) != 1 { |
| 105 | t.Fatalf("fixture did not publish exactly one source: %+v", state.SourceMappings) |
| 106 | } |
| 107 | var mapping workspacestate.SourceMapping |
| 108 | for _, imported := range state.SourceMappings { |
| 109 | mapping = imported |
| 110 | } |
| 111 | if got := v5MigrationHistories(t, app); len(got) != 1 { |
| 112 | t.Fatalf("fixture did not import readable history: %+v", got) |
| 113 | } |
| 114 | // Simulate a receipt written by an earlier build, which imported successfully |
| 115 | // but left its exact source-version conflict pending. |
| 116 | if err := app.sourceRecovery(t.Context(), path, "legacy", "workspace_conflict", "project", projectRoot, mapping.HeadID); err != nil { |
| 117 | t.Fatal(err) |
| 118 | } |
| 119 | if lifecycle != workspacestate.Active { |
| 120 | if err := app.workspaceRegistry().ArchiveSession(t.Context(), mapping.SessionID); err != nil { |
| 121 | t.Fatal(err) |
| 122 | } |
| 123 | } |
| 124 | state, err = app.workspaceRegistry().Load(t.Context()) |
| 125 | if err != nil { |
| 126 | t.Fatal(err) |
| 127 | } |
| 128 | if lifecycle == workspacestate.Deleted { |
| 129 | if err := app.workspaceRegistry().BeginPurge(t.Context(), mapping.SessionID, state.Generation); err != nil { |
| 130 | t.Fatal(err) |
| 131 | } |
| 132 | } |
| 133 | if removeMapping { |
| 134 | delete(state.SourceMappings, mapping.SourceKey) |
| 135 | body, err := json.Marshal(state) |
| 136 | if err != nil { |
| 137 | t.Fatal(err) |
| 138 | } |
| 139 | if err := os.WriteFile(app.workspaceRegistry().Path(), body, 0600); err != nil { |
| 140 | t.Fatal(err) |
| 141 | } |
| 142 | } |
| 143 | if missingTarget { |
| 144 | app.closeSessionServices() |
| 145 | if err := os.Rename(filepath.Join(app.desktopSessions.root, mapping.SessionID), filepath.Join(t.TempDir(), "unavailable-target")); err != nil { |
| 146 | t.Fatal(err) |
| 147 | } |
| 148 | } |
| 149 | for range 2 { |
| 150 | err := app.migrateLegacySession(t.Context(), path, source, "") |
| 151 | if missingTarget && err == nil { |
| 152 | t.Fatal("unreadable archived target accepted") |
| 153 | } |
| 154 | if !missingTarget && err != nil { |
| 155 | t.Fatal(err) |
| 156 | } |
| 157 | state, err := app.workspaceRegistry().Load(t.Context()) |
| 158 | if err != nil { |
| 159 | t.Fatal(err) |
| 160 | } |
| 161 | if len(state.RecoveryEntries) != 1 { |
| 162 | t.Fatalf("unexpected recovery entries: %+v", state.RecoveryEntries) |
| 163 | } |
| 164 | for _, entry := range state.RecoveryEntries { |
| 165 | wantStatus, wantTarget := "restored", mapping.SessionID |
| 166 | if lifecycle == workspacestate.Deleted || missingTarget { |
| 167 | wantStatus, wantTarget = "pending", "" |
| 168 | } |
| 169 | if entry.Status != wantStatus || entry.SessionID != wantTarget { |
| 170 | t.Fatalf("completed receipt left stale recovery: %+v", entry) |
| 171 | } |
| 172 | } |
| 173 | if got := state.SessionStates[mapping.SessionID].Lifecycle; got != lifecycle { |
| 174 | t.Fatalf("replay changed lifecycle: %s", got) |
| 175 | } |
| 176 | // BeginPurge only tombstones; physical removal belongs to the purge |
| 177 | // worker. Its recovery must remain pending without reviving lifecycle. |
| 178 | if !missingTarget && lifecycle != workspacestate.Deleted { |
| 179 | if got := v5MigrationHistories(t, app); len(got) != 1 { |
| 180 | t.Fatalf("receipt replay duplicated or lost history: %+v", got) |
| 181 | } |
| 182 | } |
| 183 | } |
| 184 | } |
| 185 | |
| 186 | func TestHistoricalImportPartialRetryPreservesOtherConflict(t *testing.T) { |
| 187 | app, firstRoot, firstPath := historicalRecoveryFixture(t) |
| 188 | secondRoot, secondPath := historicalRecoveryLegacySource(t) |
| 189 | elsewhere := historicalRecoveryGitRoot(t, robustTempDir(t)) |
| 190 | app.ctx = t.Context() |
| 191 | installNoopRuntimeEvents(app) |
| 192 | t.Cleanup(app.stopHistoricalImports) |
| 193 | for _, path := range []string{firstPath, secondPath} { |
| 194 | if err := agent.SaveBranchMetaPreserveUpdated(path, agent.BranchMeta{Scope: "project", WorkspaceRoot: elsewhere}); err != nil { |
| 195 | t.Fatal(err) |
| 196 | } |
| 197 | } |
| 198 | if _, err := app.ListHistoricalSessions(); err != nil { |
| 199 | t.Fatal(err) |
| 200 | } |
| 201 | if _, err := app.StartHistoricalImport(nil); err != nil { |
| 202 | t.Fatal(err) |
| 203 | } |
| 204 | first := awaitHistoricalBatch(t, app) |
| 205 | if len(first.Items) != 2 || first.Failed != 2 { |
| 206 | t.Fatalf("expected two real conflicts: %+v", first) |
| 207 | } |
| 208 | for index, repair := range []struct{ root, path string }{{firstRoot, firstPath}, {secondRoot, secondPath}} { |
| 209 | if err := agent.SaveBranchMetaPreserveUpdated(repair.path, agent.BranchMeta{Scope: "project", WorkspaceRoot: repair.root}); err != nil { |
| 210 | t.Fatal(err) |
| 211 | } |
| 212 | if _, err := app.StartHistoricalImport(nil); err != nil { |
| 213 | t.Fatal(err) |
| 214 | } |
| 215 | batch := awaitHistoricalBatch(t, app) |
| 216 | if batch.Failed != 1-index { |
| 217 | t.Fatalf("retry failed unexpected sources: %+v", batch) |
| 218 | } |
| 219 | state, err := app.workspaceRegistry().Load(t.Context()) |
| 220 | if err != nil { |
| 221 | t.Fatal(err) |
| 222 | } |
| 223 | pending := 0 |
| 224 | for _, entry := range state.RecoveryEntries { |
| 225 | if entry.Status == "pending" { |
| 226 | pending++ |
| 227 | if entry.SourceKey != desktopSourceKey(secondPath, "") { |
| 228 | t.Fatalf("wrong conflict remains pending: %+v", entry) |
| 229 | } |
| 230 | } |
| 231 | } |
| 232 | if pending != 1-index { |
| 233 | t.Fatalf("retry settled an unresolved sibling or kept repaired conflict: pending=%d", pending) |
| 234 | } |
| 235 | if got := v5MigrationHistories(t, app); len(got) != index+1 { |
| 236 | t.Fatalf("partial retry histories: %+v", got) |
| 237 | } |
| 238 | } |
| 239 | if _, err := app.StartHistoricalImport(nil); err != nil { |
| 240 | t.Fatal(err) |
| 241 | } |
| 242 | if batch := awaitHistoricalBatch(t, app); batch.Failed != 0 { |
| 243 | t.Fatalf("repeat failed: %+v", batch) |
| 244 | } |
| 245 | if got := v5MigrationHistories(t, app); len(got) != 2 { |
| 246 | t.Fatalf("repeat duplicated or lost history: %+v", got) |
| 247 | } |
| 248 | } |
| 249 | |
| 250 | // Use independent repositories so a runner's enclosing worktree cannot fold |
| 251 | // unrelated fixture projects or source directories into the same identity. |
| 252 | func historicalRecoveryGitRoot(t *testing.T, dir string) string { |
| 253 | t.Helper() |
| 254 | if err := os.MkdirAll(dir, 0o700); err != nil { |
| 255 | t.Fatal(err) |
| 256 | } |
| 257 | if out, err := exec.Command("git", "init", "--quiet", dir).CombinedOutput(); err != nil { |
| 258 | t.Fatalf("initialize fixture repository: %v: %s", err, out) |
| 259 | } |
| 260 | if !sameDesktopPath(canonicalRuntimeRoot(dir), dir) { |
| 261 | t.Fatalf("fixture root collapsed: %q -> %q", dir, canonicalRuntimeRoot(dir)) |
| 262 | } |
| 263 | return dir |
| 264 | } |
| 265 | |
| 266 | func historicalRecoveryFixture(t *testing.T) (*App, string, string) { |
| 267 | t.Helper() |
| 268 | isolateDesktopUserDirs(t) |
| 269 | historicalRecoveryGitRoot(t, globalWorkspaceRoot()) |
| 270 | projectRoot, path := historicalRecoveryLegacySource(t) |
| 271 | app := NewApp() |
| 272 | t.Cleanup(app.closeSessionServices) |
| 273 | app.desktopSessions.root = historicalRecoveryGitRoot(t, filepath.Join(t.TempDir(), "by-id")) |
| 274 | app.desktopSessions.workspaceState = workspacestate.NewStore(filepath.Join(t.TempDir(), "workspace-state-v1.json")) |
| 275 | return app, projectRoot, path |
| 276 | } |
| 277 | |
| 278 | func historicalRecoveryLegacySource(t *testing.T) (string, string) { |
| 279 | t.Helper() |
| 280 | projectRoot := historicalRecoveryGitRoot(t, robustTempDir(t)) |
| 281 | if err := addProject(projectRoot, "Legacy project"); err != nil { |
| 282 | t.Fatal(err) |
| 283 | } |
| 284 | dir := historicalRecoveryGitRoot(t, desktopSessionDir(projectRoot)) |
| 285 | path := filepath.Join(dir, "legacy.jsonl") |
| 286 | legacy := agent.NewSession("system") |
| 287 | legacy.Add(provider.Message{ID: "user", Role: provider.RoleUser, Content: "legacy content"}) |
| 288 | if err := legacy.Save(path); err != nil { |
| 289 | t.Fatal(err) |
| 290 | } |
| 291 | if err := agent.SaveBranchMetaPreserveUpdated(path, agent.BranchMeta{Scope: "project", WorkspaceRoot: projectRoot}); err != nil { |
| 292 | t.Fatal(err) |
| 293 | } |
| 294 | return projectRoot, path |
| 295 | } |
| 296 | |
| 297 | func TestHistoricalReviewedImportRetrySettlesBaseRecovery(t *testing.T) { |
| 298 | app, root, path := historicalRecoveryFixture(t) |
| 299 | app.ctx = t.Context() |
| 300 | installNoopRuntimeEvents(app) |
| 301 | t.Cleanup(app.stopHistoricalImports) |
| 302 | listed, err := app.ListHistoricalSessions() |
| 303 | if err != nil || len(listed.Items) != 1 { |
| 304 | t.Fatalf("list: %+v %v", listed, err) |
| 305 | } |
| 306 | base, err := app.ImportHistoricalSession(listed.Items[0].ID) |
| 307 | if err != nil { |
| 308 | t.Fatal(err) |
| 309 | } |
| 310 | original, err := app.workspaceRegistry().Load(t.Context()) |
| 311 | if err != nil { |
| 312 | t.Fatal(err) |
| 313 | } |
| 314 | body, err := os.ReadFile(path) |
| 315 | if err != nil { |
| 316 | t.Fatal(err) |
| 317 | } |
| 318 | if err := os.WriteFile(path, append(body, '\n'), 0600); err != nil { |
| 319 | t.Fatal(err) |
| 320 | } |
| 321 | id, source, err := app.historicalSourceForSelector(SessionSelector{Ref: &base.Session}) |
| 322 | if err != nil { |
| 323 | t.Fatal(err) |
| 324 | } |
| 325 | update := app.checkHistoricalSourceUpdate(t.Context(), id, source) |
| 326 | if update.Status != "available" || update.Source == nil { |
| 327 | t.Fatalf("updated source: %+v", update) |
| 328 | } |
| 329 | elsewhere := historicalRecoveryGitRoot(t, robustTempDir(t)) |
| 330 | if err := agent.SaveBranchMetaPreserveUpdated(path, agent.BranchMeta{Scope: "project", WorkspaceRoot: elsewhere}); err != nil { |
| 331 | t.Fatal(err) |
| 332 | } |
| 333 | prepare := func() (SessionPreparationView, SessionRestoreResult, error) { |
| 334 | prepared, err := app.PrepareHistoricalSourceVersion(*update.Source, update.Version) |
| 335 | if err != nil { |
| 336 | return prepared, SessionRestoreResult{}, err |
| 337 | } |
| 338 | app.historicalImports.mu.Lock() |
| 339 | call := app.historicalImports.operations[prepared.OperationID] |
| 340 | app.historicalImports.mu.Unlock() |
| 341 | result, err := waitHistoricalImport(call) |
| 342 | return prepared, result, err |
| 343 | } |
| 344 | if _, _, err := prepare(); err == nil { |
| 345 | t.Fatal("reviewed source with conflicting workspace was accepted") |
| 346 | } |
| 347 | failed, err := app.workspaceRegistry().Load(t.Context()) |
| 348 | if err != nil { |
| 349 | t.Fatal(err) |
| 350 | } |
| 351 | if len(failed.RecoveryEntries) != 1 { |
| 352 | t.Fatalf("missing actual conflict: %+v", failed.RecoveryEntries) |
| 353 | } |
| 354 | for _, entry := range failed.RecoveryEntries { |
| 355 | if entry.Reason != "workspace_conflict" || entry.Status != "pending" || entry.SourceKey != id || entry.Fingerprint != update.Version { |
| 356 | t.Fatalf("wrong conflict: %+v", entry) |
| 357 | } |
| 358 | } |
| 359 | if err := agent.SaveBranchMetaPreserveUpdated(path, agent.BranchMeta{Scope: "project", WorkspaceRoot: root}); err != nil { |
| 360 | t.Fatal(err) |
| 361 | } |
| 362 | for range 2 { |
| 363 | _, result, err := prepare() |
| 364 | if err != nil { |
| 365 | t.Fatal(err) |
| 366 | } |
| 367 | if result.Session.SessionID == base.Session.SessionID { |
| 368 | t.Fatal("reviewed version reused original adoption") |
| 369 | } |
| 370 | state, err := app.workspaceRegistry().Load(t.Context()) |
| 371 | if err != nil { |
| 372 | t.Fatal(err) |
| 373 | } |
| 374 | if !reflect.DeepEqual(state.SourceMappings[id], original.SourceMappings[id]) { |
| 375 | t.Fatal("review import changed original adoption") |
| 376 | } |
| 377 | if got := state.SourceMappings[id+":review:"+update.Version]; got.SessionID != result.Session.SessionID { |
| 378 | t.Fatalf("review mapping missing: %+v", got) |
| 379 | } |
| 380 | for _, entry := range state.RecoveryEntries { |
| 381 | if entry.Status != "restored" || entry.SessionID != result.Session.SessionID { |
| 382 | t.Fatalf("reviewed retry left base recovery pending: %+v", entry) |
| 383 | } |
| 384 | } |
| 385 | if got := v5MigrationHistories(t, app); len(got) != 2 { |
| 386 | t.Fatalf("reviewed retry duplicated or lost history: %+v", got) |
| 387 | } |
| 388 | } |
| 389 | } |
| 390 |