package app import ( "bytes" "context" "os" "path/filepath" "strings" "testing" "time" "gitea.maximumdirect.net/eric/narratio/internal/adapters/storage" "gitea.maximumdirect.net/eric/narratio/internal/artifacts" "gitea.maximumdirect.net/eric/narratio/internal/config" ) func TestRestoreHoldsTransitionLockBeforePlanning(t *testing.T) { workspaceRoot := t.TempDir() pipelinePath, campaignPath, sessionPath := writeValidConfigFiles(t, workspaceRoot) fake := &storage.FakeBackend{} cfg, _, _, _ := seedRestoreCommittedState(t, fake, pipelinePath, campaignPath, sessionPath) current, err := discoverRemotePublication(context.Background(), cfg, fake) if err != nil { t.Fatalf("discoverRemotePublication() error = %v", err) } planning := make(chan struct{}) releasePlanning := make(chan struct{}) deps := restoreCommandDependencies(fake) deps.discoverRemotePublication = func(context.Context, *config.Config, storage.ObjectStore) (*RemoteCurrentState, error) { return current, nil } deps.buildInventoryRestorePlan = func(ctx context.Context, cfg *config.Config, current *RemoteCurrentState, store storage.ObjectStore, opts RestorePlanOptions) (*RestorePlan, error) { close(planning) <-releasePlanning return buildInventoryRestorePlan(ctx, cfg, current, store, opts) } restoreDone := make(chan error, 1) go func() { restoreDone <- invokeNativeCommandWith(context.Background(), []string{"session", "restore", cfg.Session.SessionID, "--config", pipelinePath, "--campaign-file", campaignPath, "--session-file", sessionPath, }, &bytes.Buffer{}, executePlan, deps) }() <-planning runnerCtx, cancelRunner := context.WithTimeout(context.Background(), 100*time.Millisecond) defer cancelRunner() if _, err := executeStages(runnerCtx, cfg, nil, RunOptions{}); err == nil || !strings.Contains(err.Error(), "acquire workspace lock") { t.Fatalf("runner while restore plans error = %v, want workspace-lock failure", err) } close(releasePlanning) if err := <-restoreDone; err != nil { t.Fatalf("Restore() error = %v", err) } } func TestExecuteStagesRefusesIncompleteRestore(t *testing.T) { cfg := testConfig(t) paths := artifacts.NewLocalStore(cfg.Pipeline.Workspace.Root).SessionPathsFor(cfg.Session.Campaign, cfg.Session.SessionID) if err := writeRestoreMarker(paths); err != nil { t.Fatalf("writeRestoreMarker() error = %v", err) } _, err := executeStages(context.Background(), cfg, nil, RunOptions{}) if err == nil || !strings.Contains(err.Error(), "restore is incomplete") { t.Fatalf("executeStages() error = %v, want incomplete restore failure", err) } } func TestForcedRestoreRetryClearsIncompleteMarker(t *testing.T) { workspaceRoot := t.TempDir() pipelinePath, campaignPath, sessionPath := writeValidConfigFilesWithScriptoriumArtifacts(t, workspaceRoot) fake := &storage.FakeBackend{} cfg, sessionPrefix, _, _ := seedRestoreCommittedState(t, fake, pipelinePath, campaignPath, sessionPath) current := seedCommittedRestoreSnapshot(t, cfg, fake, "20260519T010203Z-a1b2c3d4", map[string][]byte{ "artifacts/session_recap.md": []byte("remote recap\n"), "transcripts/full.json": []byte(`{"segments":[]}`), }) setRestoreFixtureSources(t, fake, current, map[string]string{"artifacts/session_recap.md": artifacts.ConfiguredArtifactSourceID("session_recap"), "transcripts/full.json": artifacts.ArtifactTranscriptFinalTrimmed}) sessionRoot := artifacts.SessionWorkDirForCampaign(workspaceRoot, cfg.Session.Campaign, cfg.Session.SessionID) mustWriteTestFile(t, filepath.Join(sessionRoot, "artifacts", "session_recap.md"), "local recap\n") mustWriteTestFile(t, filepath.Join(sessionRoot, "transcripts", "final.trimmed.json"), "local transcript\n") committedTranscriptKey := artifacts.S3RunRelativeDestinationKey(artifacts.S3RunPrefix(sessionPrefix, "20260519T010203Z-a1b2c3d4"), "published/transcripts/full.json") fake.ReadHook = func(call storage.FakeReadCall) error { if call.Key == committedTranscriptKey { return context.Canceled } return nil } executeRestore := restoreCommandExecutor(fake) var stdout bytes.Buffer var stderr bytes.Buffer args := []string{"session", "restore", cfg.Session.SessionID, "--config", pipelinePath, "--campaign-file", campaignPath, "--session-file", sessionPath, "--force"} if code := executeRestore(args, &stdout, &stderr); code == 0 { t.Fatal("forced restore exit code = 0, want partial-install failure") } markerPath := artifacts.SessionRestoreMarkerPathForCampaign(workspaceRoot, cfg.Session.Campaign, cfg.Session.SessionID) if _, err := os.Stat(markerPath); err != nil { t.Fatalf("incomplete restore marker missing after partial forced restore: %v", err) } mustReadEquals(t, filepath.Join(sessionRoot, "artifacts", "session_recap.md"), "remote recap\n") fake.ReadHook = nil stdout.Reset() stderr.Reset() if code := executeRestore(args, &stdout, &stderr); code != 0 { t.Fatalf("restore retry exit code = %d, want 0; stderr=%q", code, stderr.String()) } if _, err := os.Stat(markerPath); !os.IsNotExist(err) { t.Fatalf("incomplete restore marker should be cleared after retry; stat err=%v", err) } mustReadEquals(t, filepath.Join(sessionRoot, "transcripts", "final.trimmed.json"), `{"segments":[]}`) }