Files
narratio/internal/app/restore_execution_test.go

743 lines
35 KiB
Go

package app
import (
"bytes"
"context"
"encoding/json"
"io"
"maps"
"os"
"path/filepath"
"strings"
"testing"
"gitea.maximumdirect.net/eric/narratio/internal/adapters/storage"
"gitea.maximumdirect.net/eric/narratio/internal/artifacts"
"gitea.maximumdirect.net/eric/narratio/internal/config"
"gitea.maximumdirect.net/eric/narratio/internal/manifest"
)
func TestExecuteRestoreIgnoresUnsupportedRemoteSnapshot(t *testing.T) {
for _, marker := range []string{"narratio.session-manifest.v1", "", "narratio.session-manifest.v99"} {
t.Run(marker, func(t *testing.T) {
root := t.TempDir()
pipeline, campaign, session := writeValidConfigFiles(t, root)
fake := &storage.FakeBackend{}
cfg, _, _, _ := seedRestoreCommittedState(t, fake, pipeline, campaign, session)
current := seedCommittedRestoreSnapshot(t, cfg, fake, "20260519T010203Z-a1b2c3d4", nil)
old := fake.Objects[artifacts.S3RunSessionManifestKey(current.SessionPrefix, current.RunID)].Data
data := bytes.Replace(old, []byte("narratio.session-manifest.v2"), []byte(marker), 1)
if marker == "" {
data = bytes.Replace(data, []byte(`"schema_version":"",`), nil, 1)
}
fake.SeedObject(storage.FakeObject{Key: artifacts.S3RunSessionManifestKey(current.SessionPrefix, current.RunID), Data: data})
for i := range current.Commit.Artifacts {
if current.Commit.Artifacts[i].Type == artifacts.RemoteArtifactTypeSessionManifest {
current.Commit.Artifacts[i] = remoteRestoreArtifact(fake, artifacts.RemoteArtifactTypeSessionManifest, "session.manifest", artifacts.S3RunSessionManifestKey(current.SessionPrefix, current.RunID))
}
}
commitData, err := artifacts.EncodeRemoteCommitManifest(*current.Commit)
if err != nil {
t.Fatal(err)
}
commitKey := artifacts.S3RunCommitKey(current.SessionPrefix, current.RunID)
fake.SeedObject(storage.FakeObject{Key: commitKey, Data: commitData})
pointerData, err := artifacts.EncodeCurrentCommitPointer(artifacts.CurrentCommitPointer{FormatVersion: artifacts.RemoteCommitFormatVersion, Campaign: cfg.Session.Campaign, SessionID: cfg.Session.SessionID, RunID: current.RunID, CommitKey: commitKey, CommitSHA256: restoreCommitSHA256(commitData), CommitSize: int64(len(commitData)), CommitGeneration: fake.Objects[commitKey].ETag})
if err != nil {
t.Fatal(err)
}
fake.SeedObject(storage.FakeObject{Key: artifacts.S3CurrentCommitPointerKey(current.SessionPrefix), Data: pointerData})
fake.Reads = nil
var stdout, stderr bytes.Buffer
code := restoreCommandExecutor(fake)([]string{"session", "restore", cfg.Session.SessionID, "--config", pipeline, "--campaign-file", campaign, "--session-file", session, "--force"}, &stdout, &stderr)
if code != 0 {
t.Fatalf("exit %d, stderr %q", code, stderr.String())
}
for _, read := range fake.Reads {
if read.Key == artifacts.S3RunSessionManifestKey(current.SessionPrefix, current.RunID) {
t.Fatalf("restore read obsolete snapshot %q", read.Key)
}
}
})
}
}
func TestExecuteRestoreRejectsUnsupportedLocalStateEvenWithForce(t *testing.T) {
for _, marker := range []string{"narratio.session-manifest.v1", "", "narratio.session-manifest.v99"} {
t.Run(marker, func(t *testing.T) {
root := t.TempDir()
pipeline, campaign, session := writeValidConfigFiles(t, root)
fake := &storage.FakeBackend{}
cfg, _, _, _ := seedRestoreCommittedState(t, fake, pipeline, campaign, session)
seedCommittedRestoreSnapshot(t, cfg, fake, "20260519T010203Z-a1b2c3d4", nil)
path := artifacts.SessionManifestPathForCampaign(root, cfg.Session.Campaign, cfg.Session.SessionID)
if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil {
t.Fatal(err)
}
data := bytes.Replace(restoreManifestJSON(t, cfg.Session.SessionID, cfg.Session.Campaign), []byte("narratio.session-manifest.v2"), []byte(marker), 1)
if marker == "" {
data = bytes.Replace(data, []byte(`,"schema_version":""`), nil, 1)
}
if err := os.WriteFile(path, data, 0o644); err != nil {
t.Fatal(err)
}
var stdout, stderr bytes.Buffer
code := restoreCommandExecutor(fake)([]string{"session", "restore", cfg.Session.SessionID, "--config", pipeline, "--campaign-file", campaign, "--session-file", session, "--force"}, &stdout, &stderr)
if code == 0 {
t.Fatal("expected restore failure")
}
after, err := os.ReadFile(path)
if err != nil {
t.Fatal(err)
}
if !bytes.Equal(after, data) {
t.Fatal("manifest changed")
}
entries, err := os.ReadDir(filepath.Dir(path))
if err != nil {
t.Fatal(err)
}
if len(entries) != 1 || entries[0].Name() != "manifest.json" {
t.Fatalf("session files changed: %v", entries)
}
})
}
}
func TestExecuteRestoreNonDryRunRestoresDurableFiles(t *testing.T) {
workspaceRoot := t.TempDir()
pipelinePath, campaignPath, sessionPath := writeValidConfigFilesWithScriptoriumArtifacts(t, workspaceRoot)
fake := &storage.FakeBackend{}
cfg, sessionPrefix, manifestKey, runIDKey := seedRestoreCommittedState(t, fake, pipelinePath, campaignPath, sessionPath)
seedRestoreObject(fake, sessionPrefix+"transcripts/full.json", []byte(`{"segments":[1,2,3]}`))
seedRestoreObject(fake, sessionPrefix+"artifacts/session_recap.md", []byte("# recap\n"))
seedRestoreObject(fake, sessionPrefix+"audio/alice.flac", []byte("remote-audio"))
seedRestoreObject(fake, runIDKey, []byte("20260519T010203Z-a1b2c3d4\n"))
seedRestoreObject(fake, manifestKey, restoreManifestJSON(t, cfg.Session.SessionID, cfg.Session.Campaign))
current := seedCommittedRestoreSnapshot(t, cfg, fake, "20260519T010203Z-a1b2c3d4", map[string][]byte{
"transcripts/full.json": []byte(`{"segments":[1,2,3]}`),
"artifacts/session_recap.md": []byte("# recap\n"),
"audio/alice.flac": []byte("remote-audio"),
})
setRestoreFixtureSources(t, fake, current, map[string]string{"transcripts/full.json": artifacts.ArtifactTranscriptFinalTrimmed, "artifacts/session_recap.md": artifacts.ConfiguredArtifactSourceID("session_recap")})
executeRestore := restoreCommandExecutor(fake)
var stdout bytes.Buffer
var stderr bytes.Buffer
code := executeRestore([]string{"session", "restore", "2026-05-03", "--config", pipelinePath, "--campaign-file", campaignPath, "--session-file", sessionPath}, &stdout, &stderr)
if code != 0 {
t.Fatalf("exit code = %d, want 0; stderr=%q", code, stderr.String())
}
if stderr.Len() != 0 {
t.Fatalf("stderr = %q, want empty", stderr.String())
}
if !decodeRestoreCommandReport(t, stdout.Bytes()).Complete {
t.Fatalf("stdout = %q, want completion summary", stdout.String())
}
sessionRoot := artifacts.SessionWorkDirForCampaign(workspaceRoot, cfg.Session.Campaign, cfg.Session.SessionID)
mustReadEquals(t, filepath.Join(sessionRoot, "transcripts", "final.trimmed.json"), `{"segments":[1,2,3]}`)
mustReadEquals(t, filepath.Join(sessionRoot, "artifacts", "session_recap.md"), "# recap\n")
reportPath := filepath.Join(sessionRoot, "logs", "restore", "restore.json")
view, err := os.Readlink(filepath.Join(sessionRoot, "logs", "restore"))
if err != nil || !strings.HasPrefix(view, "../runs/") || !strings.HasSuffix(view, "/restore/logs") {
t.Fatalf("restore log view = %q, %v", view, err)
}
report := mustReadRestoreReport(t, reportPath)
if report.Status != "succeeded" {
t.Fatalf("report status = %q, want succeeded", report.Status)
}
if report.Execution.Downloaded != 2 {
t.Fatalf("report execution.downloaded = %d, want 2", report.Execution.Downloaded)
}
if len(report.Actions) == 0 {
t.Fatal("report actions is empty")
}
if _, err := os.Stat(filepath.Join(sessionRoot, "audio", "alice.flac")); !os.IsNotExist(err) {
t.Fatalf("audio should not be restored by default; stat err=%v", err)
}
}
func TestExecuteRestoreImportsExtractionWithoutProducerMetadata(t *testing.T) {
workspaceRoot := t.TempDir()
pipelinePath, campaignPath, sessionPath := writeValidConfigFiles(t, workspaceRoot)
appendRestoreWorkflowScriptoriumConfig(t, pipelinePath, `
notarius:
enabled: false
outputs:
encounters:
lane_id: encounters
`)
fake := &storage.FakeBackend{}
cfg, _, _, _ := seedRestoreCommittedState(t, fake, pipelinePath, campaignPath, sessionPath)
current := seedCommittedRestoreSnapshot(t, cfg, fake, "20260519T010203Z-a1b2c3d4", map[string][]byte{"artifacts/renamed.json": []byte(`{"encounters":[]}`)})
setRestoreFixtureSources(t, fake, current, map[string]string{"artifacts/renamed.json": artifacts.ExtractionArtifactSourceID("encounters")})
var stdout, stderr bytes.Buffer
code := restoreCommandExecutor(fake)([]string{"session", "restore", cfg.Session.SessionID, "--config", pipelinePath, "--campaign-file", campaignPath, "--session-file", sessionPath}, &stdout, &stderr)
if code != 0 {
t.Fatalf("exit code = %d, stderr=%q", code, stderr.String())
}
paths := artifacts.NewLocalStore(workspaceRoot).SessionPathsFor(cfg.Session.Campaign, cfg.Session.SessionID)
mustReadEquals(t, filepath.Join(paths.ArtifactsDir, "encounters.json"), `{"encounters":[]}`)
restored, err := (&manifest.LocalStore{}).Load(context.Background(), paths.ManifestPath)
if err != nil {
t.Fatal(err)
}
product, ok := restored.SuppliedProducts.Products[artifacts.ExtractionArtifactSourceID("encounters")]
if !ok || product.Path != "artifacts/encounters.json" || restored.Stages["extract"] != nil || restored.Stages["transcribe"] != nil {
t.Fatalf("imported extraction authority = %#v, stages = %#v", product, restored.Stages)
}
}
func TestExecuteRestoreIncludeAudioRestoresAudio(t *testing.T) {
workspaceRoot := t.TempDir()
pipelinePath, campaignPath, sessionPath := writeValidConfigFiles(t, workspaceRoot)
fake := &storage.FakeBackend{}
cfg, sessionPrefix, _, _ := seedRestoreCommittedState(t, fake, pipelinePath, campaignPath, sessionPath)
seedRestoreObject(fake, sessionPrefix+"audio/alice.flac", []byte("remote-audio"))
executeRestore := restoreCommandExecutor(fake)
var stdout bytes.Buffer
var stderr bytes.Buffer
code := executeRestore([]string{"session", "restore", "2026-05-03", "--config", pipelinePath, "--campaign-file", campaignPath, "--session-file", sessionPath, "--include-audio"}, &stdout, &stderr)
if code != 0 {
t.Fatalf("exit code = %d, want 0; stderr=%q", code, stderr.String())
}
sessionRoot := artifacts.SessionWorkDirForCampaign(workspaceRoot, cfg.Session.Campaign, cfg.Session.SessionID)
mustReadEquals(t, filepath.Join(sessionRoot, "audio", "alice.flac"), "remote-audio")
report := mustReadRestoreReport(t, filepath.Join(sessionRoot, "logs", "restore", "restore.json"))
if !report.IncludeAudio {
t.Fatalf("report include_audio = %v, want true", report.IncludeAudio)
}
}
func TestExecuteRestoreIncludeAudioDownloadsAfterWorkspaceDeletion(t *testing.T) {
workspaceRoot := t.TempDir()
pipelinePath, campaignPath, sessionPath := writeValidConfigFiles(t, workspaceRoot)
fake := &storage.FakeBackend{}
cfg, sessionPrefix, _, _ := seedRestoreCommittedState(t, fake, pipelinePath, campaignPath, sessionPath)
audioKey := sessionPrefix + "audio/alice.flac"
seedRestoreObject(fake, audioKey, []byte("remote-audio"))
executeRestore := restoreCommandExecutor(fake)
var stdout bytes.Buffer
var stderr bytes.Buffer
code := executeRestore([]string{"session", "restore", "2026-05-03", "--config", pipelinePath, "--campaign-file", campaignPath, "--session-file", sessionPath, "--include-audio"}, &stdout, &stderr)
if code != 0 {
t.Fatalf("first restore exit code = %d, want 0; stderr=%q", code, stderr.String())
}
committedAudioKey := artifacts.S3RunRelativeDestinationKey(artifacts.S3RunPrefix(sessionPrefix, "20260519T010203Z-a1b2c3d4"), "published/audio/alice.flac")
if got := fakeDownloadCount(fake, committedAudioKey); got != 1 {
t.Fatalf("audio downloads after first restore = %d, want 1", got)
}
sessionRoot := artifacts.SessionWorkDirForCampaign(workspaceRoot, cfg.Session.Campaign, cfg.Session.SessionID)
mustReadEquals(t, filepath.Join(sessionRoot, "audio", "alice.flac"), "remote-audio")
if err := os.RemoveAll(sessionRoot); err != nil {
t.Fatalf("remove session root: %v", err)
}
stdout.Reset()
stderr.Reset()
code = executeRestore([]string{"session", "restore", "2026-05-03", "--config", pipelinePath, "--campaign-file", campaignPath, "--session-file", sessionPath, "--include-audio"}, &stdout, &stderr)
if code != 0 {
t.Fatalf("second restore exit code = %d, want 0; stderr=%q", code, stderr.String())
}
if got := fakeDownloadCount(fake, committedAudioKey); got != 2 {
t.Fatalf("audio downloads after restored session was removed = %d, want 2", got)
}
mustReadEquals(t, filepath.Join(sessionRoot, "audio", "alice.flac"), "remote-audio")
}
func TestExecuteRestoreRestoresPreviousCacheWhenPresent(t *testing.T) {
workspaceRoot := t.TempDir()
pipelinePath, campaignPath, sessionPath := writeValidConfigFiles(t, workspaceRoot)
appendRestoreWorkflowPreviousInputConfig(t, pipelinePath, sessionPath)
fake := &storage.FakeBackend{}
cfg, _, _, _ := seedRestoreCommittedState(t, fake, pipelinePath, campaignPath, sessionPath)
seedRestorePreviousCurrent(t, fake, cfg, "# previous recap\n")
executeRestore := restoreCommandExecutor(fake)
var stdout bytes.Buffer
var stderr bytes.Buffer
code := executeRestore([]string{"session", "restore", "2026-05-03", "--config", pipelinePath, "--campaign-file", campaignPath, "--session-file", sessionPath}, &stdout, &stderr)
if code != 0 {
t.Fatalf("exit code = %d, want 0; stderr=%q", code, stderr.String())
}
sessionRoot := artifacts.SessionWorkDirForCampaign(workspaceRoot, cfg.Session.Campaign, cfg.Session.SessionID)
if _, err := os.Stat(filepath.Join(sessionRoot, "inputs", "previous", "manifest.json")); !os.IsNotExist(err) {
t.Fatalf("unexpected previous execution manifest: %v", err)
}
mustReadEquals(t, filepath.Join(sessionRoot, "inputs", "previous", "artifacts", "session_recap.md"), "# previous recap\n")
report := mustReadRestoreReport(t, filepath.Join(sessionRoot, "logs", "restore", "restore.json"))
if report.Execution.Downloaded != 1 {
t.Fatalf("report execution.downloaded = %d, want 1", report.Execution.Downloaded)
}
}
func TestExecuteRestoreDryRunReportsPreviousCacheWithoutWriting(t *testing.T) {
workspaceRoot := t.TempDir()
pipelinePath, campaignPath, sessionPath := writeValidConfigFiles(t, workspaceRoot)
appendRestoreWorkflowPreviousInputConfig(t, pipelinePath, sessionPath)
fake := &storage.FakeBackend{}
cfg, _, _, _ := seedRestoreCommittedState(t, fake, pipelinePath, campaignPath, sessionPath)
seedRestorePreviousCurrent(t, fake, cfg, "# previous recap\n")
sessionRoot := artifacts.SessionWorkDirForCampaign(workspaceRoot, cfg.Session.Campaign, cfg.Session.SessionID)
mustWriteTestFile(t, filepath.Join(sessionRoot, "inputs", "existing.txt"), "durable input")
before := snapshotSessionTree(t, sessionRoot)
executeRestore := restoreCommandExecutor(fake)
var stdout bytes.Buffer
var stderr bytes.Buffer
code := executeRestore([]string{"session", "restore", "2026-05-03", "--config", pipelinePath, "--campaign-file", campaignPath, "--session-file", sessionPath, "--dry-run"}, &stdout, &stderr)
if code != 0 {
t.Fatalf("exit code = %d, want 0; stderr=%q", code, stderr.String())
}
if !strings.Contains(stdout.String(), "inputs/previous/artifacts/session_recap.md") {
t.Fatalf("stdout = %q, want planned previous-cache artifact", stdout.String())
}
if !decodeRestoreCommandReport(t, stdout.Bytes()).DryRun {
t.Fatalf("stdout = %q, want dry-run remote-read notice", stdout.String())
}
after := snapshotSessionTree(t, sessionRoot)
for path, value := range before {
if value == "directory" {
delete(before, path)
}
}
for path, value := range after {
if value == "directory" {
delete(after, path)
}
}
if !maps.Equal(before, after) {
t.Fatalf("dry-run changed durable files: before=%v after=%v", before, after)
}
if strings.Contains(stdout.String(), "previous/artifacts/unrelated.md") {
t.Fatalf("unrelated history included: %s", stdout.String())
}
if _, err := os.Stat(filepath.Join(sessionRoot, "inputs", "previous", "artifacts", "session_recap.md")); !os.IsNotExist(err) {
t.Fatalf("previous artifact should not be written during dry-run; stat err=%v", err)
}
}
func TestExecuteRestoreConflictWithoutForceDoesNotOverwrite(t *testing.T) {
workspaceRoot := t.TempDir()
pipelinePath, campaignPath, sessionPath := writeValidConfigFiles(t, workspaceRoot)
fake := &storage.FakeBackend{}
cfg, _, _, _ := seedRestoreCommittedState(t, fake, pipelinePath, campaignPath, sessionPath)
current := seedCommittedRestoreSnapshot(t, cfg, fake, "20260519T010203Z-a1b2c3d4", map[string][]byte{"transcripts/full.json": []byte(`{"segments":[]}`)})
setRestoreFixtureSources(t, fake, current, map[string]string{"transcripts/full.json": artifacts.ArtifactTranscriptFinalTrimmed})
sessionRoot := artifacts.SessionWorkDirForCampaign(workspaceRoot, cfg.Session.Campaign, cfg.Session.SessionID)
mustWriteTestFile(t, filepath.Join(sessionRoot, "transcripts", "final.trimmed.json"), "local-transcript")
executeRestore := restoreCommandExecutor(fake)
var stdout bytes.Buffer
var stderr bytes.Buffer
code := executeRestore([]string{"session", "restore", "2026-05-03", "--config", pipelinePath, "--campaign-file", campaignPath, "--session-file", sessionPath}, &stdout, &stderr)
if code == 0 {
t.Fatal("exit code = 0, want non-zero")
}
if !strings.Contains(stderr.String(), "conflicting path") {
t.Fatalf("stderr = %q, want conflict failure", stderr.String())
}
mustReadEquals(t, filepath.Join(sessionRoot, "transcripts", "final.trimmed.json"), "local-transcript")
report := mustReadRestoreReport(t, filepath.Join(sessionRoot, "logs", "restore", "restore.json"))
if report.Status != "failed" {
t.Fatalf("report status = %q, want failed", report.Status)
}
if report.Plan.Conflicts != 1 {
t.Fatalf("report plan.conflicts = %d, want 1", report.Plan.Conflicts)
}
}
func TestExecuteRestoreForceOverwritesDifferingFile(t *testing.T) {
workspaceRoot := t.TempDir()
pipelinePath, campaignPath, sessionPath := writeValidConfigFiles(t, workspaceRoot)
fake := &storage.FakeBackend{}
cfg, _, _, _ := seedRestoreCommittedState(t, fake, pipelinePath, campaignPath, sessionPath)
current := seedCommittedRestoreSnapshot(t, cfg, fake, "20260519T010203Z-a1b2c3d4", map[string][]byte{"transcripts/full.json": []byte(`{"segments":[]}`)})
setRestoreFixtureSources(t, fake, current, map[string]string{"transcripts/full.json": artifacts.ArtifactTranscriptFinalTrimmed})
sessionRoot := artifacts.SessionWorkDirForCampaign(workspaceRoot, cfg.Session.Campaign, cfg.Session.SessionID)
mustWriteTestFile(t, filepath.Join(sessionRoot, "transcripts", "final.trimmed.json"), "local-transcript")
executeRestore := restoreCommandExecutor(fake)
var stdout bytes.Buffer
var stderr bytes.Buffer
code := executeRestore([]string{"session", "restore", "2026-05-03", "--config", pipelinePath, "--campaign-file", campaignPath, "--session-file", sessionPath, "--force"}, &stdout, &stderr)
if code != 0 {
t.Fatalf("exit code = %d, want 0; stderr=%q", code, stderr.String())
}
mustReadEquals(t, filepath.Join(sessionRoot, "transcripts", "final.trimmed.json"), `{"segments":[]}`)
report := mustReadRestoreReport(t, filepath.Join(sessionRoot, "logs", "restore", "restore.json"))
if !report.Force {
t.Fatalf("report force = %v, want true", report.Force)
}
if _, err := os.Stat(artifacts.SessionRestoreMarkerPathForCampaign(workspaceRoot, cfg.Session.Campaign, cfg.Session.SessionID)); !os.IsNotExist(err) {
t.Fatalf("restore marker should be cleared after success; stat err=%v", err)
}
}
func TestExecuteRestoreForceOverwritesDifferingPreviousCacheFile(t *testing.T) {
workspaceRoot := t.TempDir()
pipelinePath, campaignPath, sessionPath := writeValidConfigFiles(t, workspaceRoot)
appendRestoreWorkflowPreviousInputConfig(t, pipelinePath, sessionPath)
fake := &storage.FakeBackend{}
cfg, _, _, _ := seedRestoreCommittedState(t, fake, pipelinePath, campaignPath, sessionPath)
seedRestorePreviousCurrent(t, fake, cfg, "# remote previous recap\n")
sessionRoot := artifacts.SessionWorkDirForCampaign(workspaceRoot, cfg.Session.Campaign, cfg.Session.SessionID)
mustWriteTestFile(t, filepath.Join(sessionRoot, "inputs", "previous", "artifacts", "session_recap.md"), "# local previous recap\n")
executeRestore := restoreCommandExecutor(fake)
var stdout bytes.Buffer
var stderr bytes.Buffer
code := executeRestore([]string{"session", "restore", "2026-05-03", "--config", pipelinePath, "--campaign-file", campaignPath, "--session-file", sessionPath, "--force"}, &stdout, &stderr)
if code != 0 {
t.Fatalf("exit code = %d, want 0; stderr=%q", code, stderr.String())
}
mustReadEquals(t, filepath.Join(sessionRoot, "inputs", "previous", "artifacts", "session_recap.md"), "# remote previous recap\n")
}
func TestExecuteRestoreLockConflictFailsAndWritesNothing(t *testing.T) {
workspaceRoot := t.TempDir()
pipelinePath, campaignPath, sessionPath := writeValidConfigFiles(t, workspaceRoot)
fake := &storage.FakeBackend{}
cfg, _, _, _ := seedRestoreCommittedState(t, fake, pipelinePath, campaignPath, sessionPath)
seedCommittedRestoreSnapshot(t, cfg, fake, "20260519T010203Z-a1b2c3d4", map[string][]byte{"transcripts/full.json": []byte("remote-transcript")})
store := artifacts.NewLocalStore(workspaceRoot)
lock, err := store.AcquireWorkspaceLock()
if err != nil {
t.Fatalf("AcquireWorkspaceLock() error = %v", err)
}
defer func() { _ = store.ReleaseWorkspaceLock(lock) }()
deps := restoreCommandDependencies(fake)
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
discover := deps.discoverRemotePublication
if discover == nil {
discover = discoverRemotePublication
}
deps.discoverRemotePublication = func(ctx context.Context, cfg *config.Config, store storage.ObjectStore) (*RemoteCurrentState, error) {
current, err := discover(ctx, cfg, store)
// Cancel after discovery so configuration and storage startup have no
// incidental deadline. The held lock must prevent installation.
cancel()
return current, err
}
err = invokeNativeCommandWith(ctx, []string{"session", "restore", "2026-05-03", "--config", pipelinePath, "--campaign-file", campaignPath, "--session-file", sessionPath}, &bytes.Buffer{}, executePlan, deps)
if err == nil || !strings.Contains(err.Error(), "context canceled") {
t.Fatalf("Restore() error = %v, want cancellation", err)
}
sessionRoot := artifacts.SessionWorkDirForCampaign(workspaceRoot, cfg.Session.Campaign, cfg.Session.SessionID)
if _, err := os.Stat(filepath.Join(sessionRoot, "transcripts", "full.json")); !os.IsNotExist(err) {
t.Fatalf("transcript should not be restored when lock acquisition fails; stat err=%v", err)
}
}
func TestExecuteRestoreInvalidProductRetainsManifestAndRecoveryMarker(t *testing.T) {
workspaceRoot := t.TempDir()
pipelinePath, campaignPath, sessionPath := writeValidConfigFiles(t, workspaceRoot)
store := &storage.FakeBackend{}
cfg, _, _, _ := seedRestoreCommittedState(t, store, pipelinePath, campaignPath, sessionPath)
current := seedCommittedRestoreSnapshot(t, cfg, store, "20260519T010203Z-a1b2c3d4", map[string][]byte{"transcripts/remote.json": []byte("invalid json")})
setRestoreFixtureSources(t, store, current, map[string]string{"transcripts/remote.json": artifacts.ArtifactTranscriptFinalTrimmed})
paths := artifacts.NewLocalStore(workspaceRoot).SessionPathsFor(cfg.Session.Campaign, cfg.Session.SessionID)
existing := manifest.New(cfg.Session.SessionID, nowUTC())
existing.Campaign = cfg.Session.Campaign
if err := (&manifest.LocalStore{}).Save(context.Background(), paths.ManifestPath, existing); err != nil {
t.Fatal(err)
}
before, err := os.ReadFile(paths.ManifestPath)
if err != nil {
t.Fatal(err)
}
var stdout, stderr bytes.Buffer
code := restoreCommandExecutor(store)([]string{"session", "restore", cfg.Session.SessionID, "--config", pipelinePath, "--campaign-file", campaignPath, "--session-file", sessionPath}, &stdout, &stderr)
if code == 0 || !strings.Contains(stderr.String(), "validate imported product") {
t.Fatalf("exit %d, stderr %q", code, stderr.String())
}
public := decodeRestoreCommandReport(t, stdout.Bytes())
if public.Complete || public.Status != "failed" || public.Downloaded == 0 {
t.Fatalf("partial report = %#v", public)
}
report := mustReadRestoreReport(t, filepath.Join(paths.Root, "logs", "restore", "restore.json"))
if report.Status != "failed" || report.Error == "" {
t.Fatalf("failure report = %#v", report)
}
after, err := os.ReadFile(paths.ManifestPath)
if err != nil || !bytes.Equal(before, after) {
t.Fatalf("local manifest changed: %v", err)
}
if _, err := os.Stat(paths.RestoreMarkerPath); err != nil {
t.Fatalf("recovery marker missing: %v", err)
}
}
func TestExecuteRestorePlanPathMismatchFails(t *testing.T) {
cfg := restorePlanConfig(t)
current := restorePlanCurrentState(t, cfg)
store := &storage.FakeBackend{}
seedRestoreObject(store, current.SessionPrefix+"transcripts/full.json", []byte("remote-transcript"))
plan := &RestorePlan{Actions: []RestoreAction{{
Kind: RestoreActionDownload,
RemoteKey: current.SessionPrefix + "transcripts/full.json",
LocalRelativePath: "transcripts/full.json",
LocalPath: "/tmp/escape.txt",
}}}
report, err := newRestoreReport(current, plan, RestorePlanOptions{})
if err != nil {
t.Fatalf("newRestoreReport() error = %v", err)
}
_, err = executeRestorePlan(context.Background(), cfg, current, plan, report, store)
if err == nil {
t.Fatal("expected error, got nil")
}
if !strings.Contains(err.Error(), "local path mismatch") {
t.Fatalf("error = %v, want local path mismatch", err)
}
}
func TestExecuteRestorePlanRejectsAncestorSymlinkCreatedAfterPlanning(t *testing.T) {
cfg := restorePlanConfig(t)
current := restorePlanCurrentState(t, cfg)
store := &storage.FakeBackend{}
seedCurrentRestoreObject(t, store, current, artifacts.S3RunSessionManifestKey(current.SessionPrefix, current.RunID), []byte(`{"session_id":"2026-05-03"}`))
seedCurrentRestoreObject(t, store, current, current.SessionPrefix+"artifacts/session_recap.md", []byte("remote-content\n"))
plan, err := buildInventoryRestorePlan(context.Background(), cfg, current, store, RestorePlanOptions{Force: true})
if err != nil {
t.Fatalf("buildInventoryRestorePlan() error = %v", err)
}
sessionRoot := artifacts.SessionWorkDirForCampaign(cfg.Pipeline.Workspace.Root, cfg.Session.Campaign, cfg.Session.SessionID)
outside := t.TempDir()
if err := os.Symlink(outside, filepath.Join(sessionRoot, "artifacts")); err != nil {
t.Skipf("Symlink() unavailable: %v", err)
}
report, err := newRestoreReport(current, plan, RestorePlanOptions{Force: true})
if err != nil {
t.Fatalf("newRestoreReport() error = %v", err)
}
_, err = executeRestorePlan(context.Background(), cfg, current, plan, report, store)
if err == nil || !strings.Contains(err.Error(), "not a directory") {
t.Fatalf("executeRestorePlan() error = %v, want ancestor conflict", err)
}
if _, err := os.Stat(filepath.Join(outside, "session_recap.md")); !os.IsNotExist(err) {
t.Fatalf("outside target was changed: %v", err)
}
}
func mustReadRestoreReport(t *testing.T, path string) *RestoreReport {
t.Helper()
data, err := os.ReadFile(path)
if err != nil {
t.Fatalf("ReadFile(%q): %v", path, err)
}
var report RestoreReport
if err := json.Unmarshal(data, &report); err != nil {
t.Fatalf("Unmarshal restore report %q: %v", path, err)
}
return &report
}
func restoreCommandDependencies(objectStore storage.ObjectStore) commandDependencies {
return commandDependencies{newObjectStore: func(context.Context, *config.Config) (storage.ObjectStore, error) {
return objectStore, nil
}}
}
func restoreCommandExecutor(objectStore storage.ObjectStore) func([]string, io.Writer, io.Writer) int {
deps := restoreCommandDependencies(objectStore)
return func(args []string, stdout, stderr io.Writer) int {
return executeWithDependencies(args, stdout, stderr, deps, executePlan)
}
}
func seedRestoreCommittedState(t *testing.T, fake *storage.FakeBackend, pipelinePath, campaignPath, sessionPath string) (*config.Config, string, string, string) {
t.Helper()
cfg, err := config.LoadWithSessionOptions(pipelinePath, campaignPath, sessionPath, config.SessionLoadOptions{})
if err != nil {
t.Fatalf("LoadWithSessionOptions() error = %v", err)
}
if err := config.Validate(cfg); err != nil {
t.Fatalf("Validate() error = %v", err)
}
current := seedCommittedRestoreSnapshot(t, cfg, fake, "20260519T010203Z-a1b2c3d4", nil)
return cfg, current.SessionPrefix, artifacts.S3RunSessionManifestKey(current.SessionPrefix, current.RunID), artifacts.S3CurrentCommitPointerKey(current.SessionPrefix)
}
// setRestoreFixtureSources replaces synthetic source names in the inventory
// and reseals the pointer so command tests exercise real product identities.
func setRestoreFixtureSources(t *testing.T, fake *storage.FakeBackend, current *RemoteCurrentState, sources map[string]string) {
t.Helper()
for i := range current.Commit.Artifacts {
item := &current.Commit.Artifacts[i]
if item.Type != artifacts.RemoteArtifactTypePublishedOutput {
continue
}
identity, err := artifacts.ParsePublishedOutputObjectKey(current.SessionPrefix, item.DestinationKey)
if err != nil {
t.Fatal(err)
}
if source, ok := sources[identity.Destination]; ok {
item.Source = source
}
}
data, err := artifacts.EncodeRemoteCommitManifest(*current.Commit)
if err != nil {
t.Fatal(err)
}
key := artifacts.S3RunCommitKey(current.SessionPrefix, current.RunID)
fake.SeedObject(storage.FakeObject{Key: key, Data: data})
pointer, err := artifacts.EncodeCurrentCommitPointer(artifacts.CurrentCommitPointer{FormatVersion: artifacts.RemoteCommitFormatVersion, Campaign: current.Campaign, SessionID: current.SessionID, RunID: current.RunID, CommitKey: key, CommitSHA256: restoreCommitSHA256(data), CommitSize: int64(len(data)), CommitGeneration: fake.Objects[key].ETag})
if err != nil {
t.Fatal(err)
}
fake.SeedObject(storage.FakeObject{Key: artifacts.S3CurrentCommitPointerKey(current.SessionPrefix), Data: pointer})
}
func appendRestoreWorkflowPreviousInputConfig(t *testing.T, pipelinePath, sessionPath string) {
t.Helper()
appendRestoreWorkflowScriptoriumConfig(t, pipelinePath, `
scriptorium:
binary: scriptorium
artifacts:
session_recap:
enabled: false
prompt_id: dnd.session_recap
output_path: artifacts/session_recap.md
inputs:
previous_recap:
source: narratio.previous_session.artifact.session_recap
required: true
child:
enabled: true
prompt_id: dnd.child
output_path: artifacts/child.md
depends_on: [session_recap]
unrelated:
enabled: false
prompt_id: dnd.other
output_path: artifacts/other.md
inputs:
history:
source: narratio.previous_session.artifact.unrelated
required: true
`)
appendRestoreWorkflowScriptoriumConfig(t, sessionPath, `
previous_session_id: 2026-04-26
`)
}
func seedRestorePreviousCurrent(t *testing.T, fake *storage.FakeBackend, cfg *config.Config, artifactBody string) {
t.Helper()
seedRestorePreviousCurrentManifestOnly(t, fake, cfg)
previousPrefix := artifacts.S3SessionPrefix(cfg.Pipeline.Storage.S3.RootPrefix, cfg.Session.Campaign, cfg.Session.PreviousSessionID)
previousRunID := "20260426T010203Z-a1b2c3d4"
key := artifacts.S3RunRelativeDestinationKey(artifacts.S3RunPrefix(previousPrefix, previousRunID), "published/artifacts/session_recap.md")
seedRestoreObject(fake, key, []byte(artifactBody))
}
func seedRestorePreviousCurrentManifestOnly(t *testing.T, fake *storage.FakeBackend, cfg *config.Config) {
t.Helper()
previousRunID := "20260426T010203Z-a1b2c3d4"
m := manifest.New(cfg.Session.PreviousSessionID, nowUTC())
m.Campaign = cfg.Session.Campaign
m.RunID = previousRunID
data, err := json.Marshal(m)
if err != nil {
t.Fatalf("marshal previous restore manifest: %v", err)
}
manifestData := append(data, '\n')
previousPrefix := artifacts.S3SessionPrefix(cfg.Pipeline.Storage.S3.RootPrefix, cfg.Session.Campaign, cfg.Session.PreviousSessionID)
manifestKey := artifacts.S3RunSessionManifestKey(previousPrefix, previousRunID)
seedRestoreObject(fake, manifestKey, manifestData)
commit := artifacts.RemoteCommitManifest{FormatVersion: artifacts.RemoteCommitFormatVersion, Campaign: cfg.Session.Campaign, SessionID: cfg.Session.PreviousSessionID, RunID: previousRunID, Artifacts: []artifacts.RemoteArtifact{{Type: artifacts.RemoteArtifactTypeSessionManifest, Source: "session.manifest", DestinationKey: manifestKey, SHA256: restoreCommitSHA256(manifestData), Size: int64(len(manifestData)), Generation: fake.Objects[manifestKey].ETag}}}
commitData, err := artifacts.EncodeRemoteCommitManifest(commit)
if err != nil {
t.Fatalf("encode previous restore commit: %v", err)
}
commitKey := artifacts.S3RunCommitKey(previousPrefix, previousRunID)
seedRestoreObject(fake, commitKey, commitData)
pointerData, err := artifacts.EncodeCurrentCommitPointer(artifacts.CurrentCommitPointer{FormatVersion: artifacts.RemoteCommitFormatVersion, Campaign: cfg.Session.Campaign, SessionID: cfg.Session.PreviousSessionID, RunID: previousRunID, CommitKey: commitKey, CommitSHA256: restoreCommitSHA256(commitData), CommitSize: int64(len(commitData)), CommitGeneration: fake.Objects[commitKey].ETag})
if err != nil {
t.Fatalf("encode previous restore pointer: %v", err)
}
seedRestoreObject(fake, artifacts.S3CurrentCommitPointerKey(previousPrefix), pointerData)
}
func mustReadEquals(t *testing.T, path, want string) {
t.Helper()
data, err := os.ReadFile(path)
if err != nil {
t.Fatalf("ReadFile(%q): %v", path, err)
}
if string(data) != want {
t.Fatalf("file %q = %q, want %q", path, string(data), want)
}
}
func fakeDownloadCount(fake *storage.FakeBackend, key string) int {
count := 0
for _, call := range fake.Reads {
if call.Key == key {
count++
}
}
return count
}
func TestExecuteRestoreInstallsOptionalPrerequisiteHistory(t *testing.T) {
workspaceRoot := t.TempDir()
pipelinePath, campaignPath, sessionPath := writeValidConfigFiles(t, workspaceRoot)
appendRestoreWorkflowPreviousInputConfig(t, pipelinePath, sessionPath)
data, err := os.ReadFile(pipelinePath)
if err != nil {
t.Fatal(err)
}
data = bytes.Replace(data, []byte(" required: true\n child:"), []byte(" required: false\n child:"), 1)
if err := os.WriteFile(pipelinePath, data, 0600); err != nil {
t.Fatal(err)
}
fake := &storage.FakeBackend{}
cfg, _, _, _ := seedRestoreCommittedState(t, fake, pipelinePath, campaignPath, sessionPath)
seedRestorePreviousCurrent(t, fake, cfg, "optional history\n")
var stdout, stderr bytes.Buffer
code := restoreCommandExecutor(fake)([]string{"session", "restore", cfg.Session.SessionID, "--config", pipelinePath, "--campaign-file", campaignPath, "--session-file", sessionPath}, &stdout, &stderr)
if code != 0 {
t.Fatalf("restore exit = %d; stderr = %s", code, stderr.String())
}
root := artifacts.SessionWorkDirForCampaign(workspaceRoot, cfg.Session.Campaign, cfg.Session.SessionID)
mustReadEquals(t, filepath.Join(root, "inputs", "previous", "artifacts", "session_recap.md"), "optional history\n")
}