Restore prepared inputs and flat session products

This commit is contained in:
2026-11-30 01:53:11 +00:00
parent e19ba81406
commit 3118bc35ba
12 changed files with 282 additions and 62 deletions

View File

@@ -416,10 +416,6 @@ func writeValidConfigFiles(t *testing.T, workspaceRoot string, transcribeURL ...
campaigns:
root: ` + campaignRoot + `
default_campaign_id: sample-campaign
cache:
root: ` + filepath.Join(workspaceRoot, "cache") + `
spool:
root: ` + filepath.Join(workspaceRoot, "spool") + `
storage:
backend: s3
s3:

View File

@@ -1,12 +1,15 @@
package app
import (
"bytes"
"context"
"errors"
"fmt"
"path/filepath"
"gitea.maximumdirect.net/eric/narratio/internal/artifacts"
"gitea.maximumdirect.net/eric/narratio/internal/config"
"gitea.maximumdirect.net/eric/narratio/internal/fileops"
"gitea.maximumdirect.net/eric/narratio/internal/manifest"
"go.maximumdirect.net/commandkit"
)
@@ -60,6 +63,13 @@ func restoreSessionState(ctx context.Context, cfg *config.Config, opts RestorePl
if err != nil {
return diagnostic, fmt.Errorf("restore: %w", err)
}
if current == nil || len(current.ManifestData) == 0 {
return diagnostic, fmt.Errorf("restore: verified remote session manifest is required")
}
destinationRoot := artifacts.SessionWorkDirForCampaign(cfg.Pipeline.Workspace.Root, cfg.Session.Campaign, cfg.Session.SessionID)
if _, err := prepareRestoredManifest(ctx, cfg, current, bytes.NewReader(current.ManifestData), destinationRoot, true); err != nil {
return diagnostic, fmt.Errorf("restore: validate remote session manifest: %w", err)
}
manifestPath := artifacts.SessionManifestPathForCampaign(cfg.Pipeline.Workspace.Root, cfg.Session.Campaign, cfg.Session.SessionID)
if _, _, err := loadManifestAtPathIfPresent(ctx, &manifest.LocalStore{}, manifestPath); err != nil {
return diagnostic, fmt.Errorf("restore: %w", err)
@@ -126,11 +136,26 @@ func restoreSessionState(ctx context.Context, cfg *config.Config, opts RestorePl
diagnostic = report
restoreRunID, err := artifacts.NewRunID()
if err != nil {
return diagnostic, fmt.Errorf("restore: generate diagnostic run id: %w", err)
}
sessionPaths := artifactStore.SessionPathsFor(cfg.Session.Campaign, cfg.Session.SessionID)
if _, err := fileops.BeginAttemptViews(sessionPaths.Root, restoreRunID, "restore"); err != nil {
return diagnostic, fmt.Errorf("restore: prepare diagnostic views: %w", err)
}
report.reportPathRel = filepath.ToSlash(filepath.Join("runs", restoreRunID, "restore", "logs", "restore.json"))
defer func() {
if resultErr != nil {
report.setFailed(resultErr)
_, reportErr := persistRestoreReport(artifactStore, cfg, report)
resultErr = errors.Join(resultErr, reportErr)
}
}()
if plan.ConflictCount > 0 {
conflictErr := fmt.Errorf("restore conflict: %d conflicting path(s); --force can replace eligible regular files but not unresolved conflicts (download=%d skip_same=%d conflicts=%d)", plan.ConflictCount, plan.DownloadCount, plan.SkipSameCount, plan.ConflictCount)
report.setFailed(conflictErr)
_, reportErr := persistRestoreReport(artifactStore, cfg, report)
return diagnostic, errors.Join(conflictErr, reportErr)
return diagnostic, conflictErr
}
if err := writeRestoreMarker(artifactStore.SessionPathsFor(cfg.Session.Campaign, cfg.Session.SessionID)); err != nil {
return diagnostic, fmt.Errorf("restore: mark incomplete restore: %w", err)
@@ -139,10 +164,6 @@ func restoreSessionState(ctx context.Context, cfg *config.Config, opts RestorePl
result, err := deps.executeRestorePlan(ctx, cfg, current, plan, report, objectStore)
err = errors.Join(err, ctx.Err())
if err != nil {
report.setFailed(err)
if _, reportErr := persistRestoreReport(artifactStore, cfg, report); reportErr != nil {
return diagnostic, fmt.Errorf("restore: execute plan and persist report: %w", errors.Join(err, reportErr))
}
return diagnostic, fmt.Errorf("restore: execute plan: %w", err)
}
if result == nil {

View File

@@ -43,6 +43,40 @@ func TestCommittedRestorePlanUsesOnlyDeclaredObjects(t *testing.T) {
}
}
func TestCommittedRestoreInstallsPreparedInputsAndFlatProducts(t *testing.T) {
cfg := restorePlanConfig(t)
fake := &storage.FakeBackend{}
current := seedCommittedRestoreSnapshot(t, cfg, fake, "20260519T010203Z-a1b2c3d4", map[string][]byte{
"artifacts/session_recap.md": []byte("recap"),
})
for _, name := range []string{"autocorrect.yml", "players.yml", "speakers.yml", "pipeline.resolved.yml", "glossaries/party.yml", "glossaries/campaign.yml", "glossaries/setting.yml", "glossaries/spells.yml", "glossaries/combined.yml"} {
rel := "prepare/inputs/" + name
key := artifacts.S3RunRelativeDestinationKey(artifacts.S3RunPrefix(current.SessionPrefix, current.RunID), rel)
fake.SeedObject(storage.FakeObject{Key: key, Data: []byte("prepared " + name)})
current.Commit.Artifacts = append(current.Commit.Artifacts, remoteRestoreArtifact(fake, artifacts.RemoteArtifactTypeRunFile, "run:"+rel, key))
}
for i := range current.Commit.Artifacts {
item := &current.Commit.Artifacts[i]
if item.Type == artifacts.RemoteArtifactTypePublishedOutput {
key := artifacts.S3RunRelativeDestinationKey(artifacts.S3RunPrefix(current.SessionPrefix, current.RunID), "published/custom/nested/recap.md")
fake.SeedObject(storage.FakeObject{Key: key, Data: []byte("recap")})
item.DestinationKey, item.Generation = key, fake.Objects[key].ETag
}
}
plan, err := buildRestorePlan(context.Background(), cfg, current, fake, RestorePlanOptions{})
if err != nil {
t.Fatal(err)
}
if _, err := executeRestorePlan(context.Background(), cfg, current, plan, nil, fake); err != nil {
t.Fatal(err)
}
root := artifacts.SessionWorkDirForCampaign(cfg.Pipeline.Workspace.Root, cfg.Session.Campaign, cfg.Session.SessionID)
mustReadEquals(t, filepath.Join(root, "artifacts", "session_recap.md"), "recap")
for _, name := range []string{"autocorrect.yml", "glossaries/combined.yml", "speakers.yml"} {
mustReadEquals(t, filepath.Join(root, "inputs", filepath.FromSlash(name)), "prepared "+name)
}
}
func TestCommittedRestoreDoesNotRequirePolishRunDiagnostics(t *testing.T) {
cfg := restorePlanConfig(t)
fake := &storage.FakeBackend{}
@@ -391,6 +425,19 @@ func seedCommittedRestoreSnapshot(t *testing.T, cfg *config.Config, fake *storag
remoteManifest := manifest.New(cfg.Session.SessionID, time.Now().UTC())
remoteManifest.Campaign = cfg.Session.Campaign
remoteManifest.RunID = runID
for relative := range outputs {
parts := strings.Split(relative, "/")
if len(parts) != 2 || (parts[0] != "transcripts" && parts[0] != "artifacts") {
continue
}
sourceKey := strings.NewReplacer("/", "_", ".", "_", "-", "_").Replace(relative)
record := remoteManifest.Stages["fixture"]
if record == nil {
record = &manifest.StageRecord{Name: "fixture", Status: manifest.StatusSucceeded}
remoteManifest.Stages["fixture"] = record
}
record.Outputs = append(record.Outputs, manifest.ArtifactRecord{SourceID: artifacts.ConfiguredArtifactSourceID(sourceKey), LocalPath: relative})
}
manifestData, err := json.Marshal(remoteManifest)
if err != nil {
t.Fatalf("marshal manifest: %v", err)

View File

@@ -138,7 +138,11 @@ func TestExecuteRestoreNonDryRunRestoresDurableFiles(t *testing.T) {
sessionRoot := artifacts.SessionWorkDirForCampaign(workspaceRoot, cfg.Session.Campaign, cfg.Session.SessionID)
mustReadEquals(t, filepath.Join(sessionRoot, "transcripts", "full.json"), `{"segments":[1,2,3]}`)
mustReadEquals(t, filepath.Join(sessionRoot, "artifacts", "session_recap.md"), "# recap\n")
reportPath := filepath.Join(sessionRoot, "reports", "restore-latest.json")
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)
@@ -256,7 +260,7 @@ func TestExecuteRestoreIncludeAudioRestoresAudio(t *testing.T) {
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, "reports", "restore-latest.json"))
report := mustReadRestoreReport(t, filepath.Join(sessionRoot, "logs", "restore", "restore.json"))
if !report.IncludeAudio {
t.Fatalf("report include_audio = %v, want true", report.IncludeAudio)
}
@@ -320,15 +324,16 @@ func TestExecuteRestoreRestoresPreviousCacheWhenPresent(t *testing.T) {
}
sessionRoot := artifacts.SessionWorkDirForCampaign(workspaceRoot, cfg.Session.Campaign, cfg.Session.SessionID)
previousManifestBytes, err := os.ReadFile(filepath.Join(sessionRoot, "previous", "manifest.json"))
previousManifestBytes, err := os.ReadFile(filepath.Join(sessionRoot, "inputs", "previous", "manifest.json"))
if err != nil {
t.Fatalf("read restored previous manifest: %v", err)
}
if !strings.Contains(string(previousManifestBytes), `"session_id": "2026-04-26"`) {
var previousManifest manifest.Manifest
if err := json.Unmarshal(previousManifestBytes, &previousManifest); err != nil || previousManifest.SessionID != "2026-04-26" {
t.Fatalf("restored previous manifest = %q, want previous session id", string(previousManifestBytes))
}
mustReadEquals(t, filepath.Join(sessionRoot, "previous", "artifacts", "session_recap.md"), "# previous recap\n")
report := mustReadRestoreReport(t, filepath.Join(sessionRoot, "reports", "restore-latest.json"))
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 != 3 {
t.Fatalf("report execution.downloaded = %d, want 3", report.Execution.Downloaded)
}
@@ -351,7 +356,7 @@ func TestExecuteRestoreDryRunReportsPreviousCacheWithoutWriting(t *testing.T) {
if code != 0 {
t.Fatalf("exit code = %d, want 0; stderr=%q", code, stderr.String())
}
if !strings.Contains(stdout.String(), "previous/artifacts/session_recap.md") {
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 {
@@ -359,7 +364,7 @@ func TestExecuteRestoreDryRunReportsPreviousCacheWithoutWriting(t *testing.T) {
}
sessionRoot := artifacts.SessionWorkDirForCampaign(workspaceRoot, cfg.Session.Campaign, cfg.Session.SessionID)
if _, err := os.Stat(filepath.Join(sessionRoot, "previous", "artifacts", "session_recap.md")); !os.IsNotExist(err) {
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)
}
}
@@ -369,8 +374,8 @@ func TestExecuteRestoreConflictWithoutForceDoesNotOverwrite(t *testing.T) {
pipelinePath, campaignPath, sessionPath := writeValidConfigFiles(t, workspaceRoot)
fake := &storage.FakeBackend{}
cfg, sessionPrefix, _, _ := seedRestoreCommittedState(t, fake, pipelinePath, campaignPath, sessionPath)
seedRestoreObject(fake, sessionPrefix+"transcripts/full.json", []byte("remote-transcript"))
cfg, _, _, _ := seedRestoreCommittedState(t, fake, pipelinePath, campaignPath, sessionPath)
seedCommittedRestoreSnapshot(t, cfg, fake, "20260519T010203Z-a1b2c3d4", map[string][]byte{"transcripts/full.json": []byte("remote-transcript")})
sessionRoot := artifacts.SessionWorkDirForCampaign(workspaceRoot, cfg.Session.Campaign, cfg.Session.SessionID)
mustWriteTestFile(t, filepath.Join(sessionRoot, "transcripts", "full.json"), "local-transcript")
@@ -387,7 +392,7 @@ func TestExecuteRestoreConflictWithoutForceDoesNotOverwrite(t *testing.T) {
t.Fatalf("stderr = %q, want conflict failure", stderr.String())
}
mustReadEquals(t, filepath.Join(sessionRoot, "transcripts", "full.json"), "local-transcript")
report := mustReadRestoreReport(t, filepath.Join(sessionRoot, "reports", "restore-latest.json"))
report := mustReadRestoreReport(t, filepath.Join(sessionRoot, "logs", "restore", "restore.json"))
if report.Status != "failed" {
t.Fatalf("report status = %q, want failed", report.Status)
}
@@ -401,8 +406,8 @@ func TestExecuteRestoreForceOverwritesDifferingFile(t *testing.T) {
pipelinePath, campaignPath, sessionPath := writeValidConfigFiles(t, workspaceRoot)
fake := &storage.FakeBackend{}
cfg, sessionPrefix, _, _ := seedRestoreCommittedState(t, fake, pipelinePath, campaignPath, sessionPath)
seedRestoreObject(fake, sessionPrefix+"transcripts/full.json", []byte("remote-transcript"))
cfg, _, _, _ := seedRestoreCommittedState(t, fake, pipelinePath, campaignPath, sessionPath)
seedCommittedRestoreSnapshot(t, cfg, fake, "20260519T010203Z-a1b2c3d4", map[string][]byte{"transcripts/full.json": []byte("remote-transcript")})
sessionRoot := artifacts.SessionWorkDirForCampaign(workspaceRoot, cfg.Session.Campaign, cfg.Session.SessionID)
mustWriteTestFile(t, filepath.Join(sessionRoot, "transcripts", "full.json"), "local-transcript")
@@ -416,7 +421,7 @@ func TestExecuteRestoreForceOverwritesDifferingFile(t *testing.T) {
t.Fatalf("exit code = %d, want 0; stderr=%q", code, stderr.String())
}
mustReadEquals(t, filepath.Join(sessionRoot, "transcripts", "full.json"), "remote-transcript")
report := mustReadRestoreReport(t, filepath.Join(sessionRoot, "reports", "restore-latest.json"))
report := mustReadRestoreReport(t, filepath.Join(sessionRoot, "logs", "restore", "restore.json"))
if !report.Force {
t.Fatalf("report force = %v, want true", report.Force)
}
@@ -435,7 +440,7 @@ func TestExecuteRestoreForceOverwritesDifferingPreviousCacheFile(t *testing.T) {
seedRestorePreviousCurrent(t, fake, cfg, "# remote previous recap\n")
sessionRoot := artifacts.SessionWorkDirForCampaign(workspaceRoot, cfg.Session.Campaign, cfg.Session.SessionID)
mustWriteTestFile(t, filepath.Join(sessionRoot, "previous", "artifacts", "session_recap.md"), "# local previous recap\n")
mustWriteTestFile(t, filepath.Join(sessionRoot, "inputs", "previous", "artifacts", "session_recap.md"), "# local previous recap\n")
executeRestore := restoreCommandExecutor(fake)
@@ -445,7 +450,7 @@ func TestExecuteRestoreForceOverwritesDifferingPreviousCacheFile(t *testing.T) {
if code != 0 {
t.Fatalf("exit code = %d, want 0; stderr=%q", code, stderr.String())
}
mustReadEquals(t, filepath.Join(sessionRoot, "previous", "artifacts", "session_recap.md"), "# remote previous recap\n")
mustReadEquals(t, filepath.Join(sessionRoot, "inputs", "previous", "artifacts", "session_recap.md"), "# remote previous recap\n")
}
func TestExecuteRestoreLockConflictFailsAndWritesNothing(t *testing.T) {
@@ -453,8 +458,8 @@ func TestExecuteRestoreLockConflictFailsAndWritesNothing(t *testing.T) {
pipelinePath, campaignPath, sessionPath := writeValidConfigFiles(t, workspaceRoot)
fake := &storage.FakeBackend{}
cfg, sessionPrefix, _, _ := seedRestoreCommittedState(t, fake, pipelinePath, campaignPath, sessionPath)
seedRestoreObject(fake, sessionPrefix+"transcripts/full.json", []byte("remote-transcript"))
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.AcquireSessionLockFor(cfg.Session.Campaign, cfg.Session.SessionID)
@@ -479,8 +484,8 @@ func TestExecuteRestoreLockConflictFailsAndWritesNothing(t *testing.T) {
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(), "acquire session lock") {
t.Fatalf("Restore() error = %v, want lock failure", err)
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)
@@ -613,7 +618,7 @@ func TestExecuteRestoreInvalidManifestReportsFailureAndRetainsRecoveryMarker(t *
t.Fatalf("partial restore report=%#v", public)
}
mustReadEquals(t, filepath.Join(sessionRoot, "transcripts", "full.json"), "remote-transcript")
report := mustReadRestoreReport(t, filepath.Join(sessionRoot, "reports", "restore-latest.json"))
report := mustReadRestoreReport(t, filepath.Join(sessionRoot, "logs", "restore", "restore.json"))
if report.Status != "failed" {
t.Fatalf("report status = %q, want failed", report.Status)
}

View File

@@ -110,6 +110,11 @@ func rebaseRestoredManifestPaths(cfg *config.Config, m *manifest.Manifest, desti
// from becoming a usable local reference.
record.Logs = nil
record.GeneratedConfigs = nil
for key, artifact := range record.AnalyzeArtifacts {
artifact.Logs = nil
artifact.GeneratedConfigs = nil
record.AnalyzeArtifacts[key] = artifact
}
}
if runID := strings.TrimSpace(m.RunID); runID != "" {

View File

@@ -17,6 +17,7 @@ import (
"gitea.maximumdirect.net/eric/narratio/internal/artifactpolicy"
"gitea.maximumdirect.net/eric/narratio/internal/artifacts"
"gitea.maximumdirect.net/eric/narratio/internal/config"
"gitea.maximumdirect.net/eric/narratio/internal/manifest"
"gitea.maximumdirect.net/eric/narratio/internal/pathsafe"
"gitea.maximumdirect.net/eric/narratio/internal/previouscache"
)
@@ -72,6 +73,8 @@ type RestorePlanOptions struct {
DryRun bool
}
var errRestoreProductNotFound = errors.New("restore product source is unavailable")
func buildRestorePlan(ctx context.Context, cfg *config.Config, current *RemoteCurrentState, store storage.ObjectStore, opts RestorePlanOptions) (*RestorePlan, error) {
if err := ctx.Err(); err != nil {
return nil, err
@@ -94,7 +97,7 @@ func buildRestorePlan(ctx context.Context, cfg *config.Config, current *RemoteCu
defer func() { _ = sessionRoot.Close() }()
}
actions, err := buildCurrentRestoreActions(ctx, current, store, sessionPaths, sessionRoot, opts)
actions, err := buildCurrentRestoreActions(ctx, cfg, current, store, sessionPaths, sessionRoot, opts)
if err != nil {
return nil, err
}
@@ -104,6 +107,13 @@ func buildRestorePlan(ctx context.Context, cfg *config.Config, current *RemoteCu
return nil, err
}
actions = append(actions, previousActions...)
seenPaths := make(map[string]string, len(actions))
for _, action := range actions {
if prior, exists := seenPaths[action.LocalRelativePath]; exists {
return nil, fmt.Errorf("multiple committed objects target %q (%q and %q)", action.LocalRelativePath, prior, action.RemoteKey)
}
seenPaths[action.LocalRelativePath] = action.RemoteKey
}
sort.Slice(actions, func(i, j int) bool {
if actions[i].LocalRelativePath == actions[j].LocalRelativePath {
@@ -130,17 +140,19 @@ func buildRestorePlan(ctx context.Context, cfg *config.Config, current *RemoteCu
func buildCurrentRestoreActions(
ctx context.Context,
cfg *config.Config,
current *RemoteCurrentState,
store storage.ObjectStore,
sessionPaths artifacts.SessionPaths,
sessionRoot *os.Root,
opts RestorePlanOptions,
) ([]RestoreAction, error) {
return buildCommittedRestoreActions(ctx, current, store, sessionPaths, sessionRoot, opts)
return buildCommittedRestoreActions(ctx, cfg, current, store, sessionPaths, sessionRoot, opts)
}
func buildCommittedRestoreActions(
ctx context.Context,
cfg *config.Config,
current *RemoteCurrentState,
store storage.ObjectStore,
sessionPaths artifacts.SessionPaths,
@@ -156,6 +168,18 @@ func buildCommittedRestoreActions(
if err != nil {
return nil, fmt.Errorf("map committed object %q: %w", artifact.DestinationKey, err)
}
if artifact.Type == artifacts.RemoteArtifactTypePublishedOutput && current.Manifest != nil {
identity, _ := artifacts.ParsePublishedOutputObjectKey(current.SessionPrefix, artifact.DestinationKey)
if _, sourceErr := artifactpolicy.ClassifySource(artifact.Source); sourceErr == nil {
productPath, productErr := restoreProductRelativePath(cfg, current.Manifest, sessionPaths.Root, artifact.Source)
if productErr != nil && (!strings.HasPrefix(identity.Destination, config.PathAudioDirSegment+"/") || !errors.Is(productErr, errRestoreProductNotFound)) {
return nil, fmt.Errorf("map committed source %q: %w", artifact.Source, productErr)
}
if productErr == nil {
rel, include = productPath, true
}
}
}
if !include {
continue
}
@@ -177,15 +201,86 @@ func buildCommittedRestoreActions(
return actions, nil
}
// restoreProductRelativePath takes local product identity from the committed
// session evidence; the remote publication destination is only an object key.
func restoreProductRelativePath(cfg *config.Config, m *manifest.Manifest, destinationRoot, source string) (string, error) {
producerRoot, hasProducerRoot := restoredManifestSessionRoot(m)
var paths []string
for _, record := range m.Stages {
if record == nil {
continue
}
for _, output := range record.Outputs {
if output.SourceID == source {
paths = append(paths, output.LocalPath)
}
}
for _, artifact := range record.AnalyzeArtifacts {
if artifact.Output != nil && artifact.Output.SourceID == source {
paths = append(paths, artifact.Output.LocalPath)
}
}
}
var result string
for _, value := range paths {
local, err := rebaseRestoredLocalReference("published output", value, producerRoot, hasProducerRoot, destinationRoot)
if err != nil {
return "", err
}
rel, err := filepath.Rel(destinationRoot, local)
if err != nil {
return "", err
}
rel = filepath.ToSlash(rel)
parts := strings.Split(rel, "/")
if len(parts) != 2 || (parts[0] != config.PathArtifactsDirSegment && parts[0] != config.PathTranscriptsSegment) || parts[1] == "" || parts[1] == "." || parts[1] == ".." {
return "", fmt.Errorf("product path %q is not a flat canonical product", rel)
}
if result != "" && result != rel {
return "", fmt.Errorf("conflicting product paths for %q", source)
}
result = rel
}
if result == "" {
catalog := artifacts.NewArtifactCatalog()
if err := catalog.RegisterBuiltIns(); err != nil {
return "", err
}
if err := catalog.RegisterConfiguredArtifacts(artifacts.ConfiguredArtifactDefinitions(cfg.ConcreteArtifacts())); err != nil {
return "", err
}
if err := catalog.RegisterExtractionArtifacts(artifacts.ExtractionDefinitionsFromConfig(cfg.Pipeline.Notarius)); err != nil {
return "", err
}
if entry, ok := catalog.Lookup(source); ok {
result = filepath.ToSlash(entry.CanonicalRelPath)
parts := strings.Split(result, "/")
if len(parts) != 2 || (parts[0] != config.PathArtifactsDirSegment && parts[0] != config.PathTranscriptsSegment) || parts[1] == "" || parts[1] == "." || parts[1] == ".." {
return "", fmt.Errorf("configured product path %q is not flat", result)
}
} else {
return "", fmt.Errorf("%w: %q", errRestoreProductNotFound, source)
}
}
return result, nil
}
func restoreLocalRelativePathForCommittedArtifact(sessionPrefix string, artifact artifacts.RemoteArtifact, includeAudio bool) (string, bool, error) {
if artifact.Type == artifacts.RemoteArtifactTypeSessionManifest {
return config.PathManifestFile, true, nil
}
if artifact.Type == artifacts.RemoteArtifactTypeRunFile {
prepared := map[string]bool{"run:prepare/inputs/session.yml": true, "run:prepare/inputs/campaign.yml": true, "run:prepare/inputs/party.yml": true}
prepared := map[string]bool{
"run:prepare/inputs/session.yml": true, "run:prepare/inputs/campaign.yml": true,
"run:prepare/inputs/party.yml": true, "run:prepare/inputs/players.yml": true,
"run:prepare/inputs/speakers.yml": true, "run:prepare/inputs/autocorrect.yml": true,
"run:prepare/inputs/pipeline.resolved.yml": true,
}
for _, descriptor := range artifactpolicy.GlossaryInputSources() {
prepared["run:prepare/inputs/"+descriptor.Filename] = true
}
combined, _ := artifactpolicy.DescribePreparedInputSource(artifactpolicy.SourceInputGlossaryCombined)
prepared["run:prepare/inputs/"+combined.Filename] = true
if prepared[artifact.Source] {
identity, err := artifacts.ParseImmutableRunObjectKey(sessionPrefix, artifact.DestinationKey)
if err != nil || "run:"+identity.RelativePath != artifact.Source {

View File

@@ -41,6 +41,42 @@ func TestRestorePlanDefaultScope(t *testing.T) {
}
}
func TestRestorePlanMapsNestedPublishedDestinationToFlatProduct(t *testing.T) {
cfg := restorePlanConfig(t)
store := &storage.FakeBackend{}
current := seedCommittedRestoreSnapshot(t, cfg, store, "20260519T010203Z-a1b2c3d4", map[string][]byte{
"artifacts/session_recap.md": []byte("recap"),
})
for i := range current.Commit.Artifacts {
item := &current.Commit.Artifacts[i]
if item.Type != artifacts.RemoteArtifactTypePublishedOutput {
continue
}
key := artifacts.S3RunRelativeDestinationKey(artifacts.S3RunPrefix(current.SessionPrefix, current.RunID), "published/custom/nested/recap.md")
store.SeedObject(storage.FakeObject{Key: key, Data: []byte("recap")})
item.DestinationKey, item.Generation = key, store.Objects[key].ETag
}
plan, err := buildRestorePlan(context.Background(), cfg, current, store, RestorePlanOptions{})
if err != nil {
t.Fatal(err)
}
action := restoreActionForPath(t, plan, "artifacts/session_recap.md")
if !strings.HasSuffix(action.RemoteKey, "/published/custom/nested/recap.md") {
t.Fatalf("remote key = %q", action.RemoteKey)
}
}
func TestRestorePreparedInputMappingIncludesGeneratedInputs(t *testing.T) {
for _, name := range []string{"autocorrect.yml", "speakers.yml", "players.yml", "pipeline.resolved.yml", "glossaries/combined.yml"} {
sessionPrefix := "dnd/campaigns/c/sessions/s/"
artifact := artifacts.RemoteArtifact{Type: artifacts.RemoteArtifactTypeRunFile, Source: "run:prepare/inputs/" + name, DestinationKey: artifacts.S3RunRelativeDestinationKey(artifacts.S3RunPrefix(sessionPrefix, "run-1"), "prepare/inputs/"+name)}
got, included, err := restoreLocalRelativePathForCommittedArtifact(sessionPrefix, artifact, false)
if err != nil || !included || got != "inputs/"+name {
t.Fatalf("%s: path=%q included=%v error=%v", name, got, included, err)
}
}
}
func TestRestorePlanIncludeAudio(t *testing.T) {
cfg := restorePlanConfig(t)
current := restorePlanCurrentState(t, cfg)
@@ -112,7 +148,7 @@ func TestRestorePlanIncludesPreviousCacheByDefault(t *testing.T) {
}
got := actionRelPaths(plan.Actions)
want := []string{"manifest.json", "previous/artifacts/session_recap.md", "previous/manifest.json"}
want := []string{"inputs/previous/artifacts/session_recap.md", "inputs/previous/manifest.json", "manifest.json"}
if !slices.Equal(got, want) {
t.Fatalf("action local paths = %#v, want %#v", got, want)
}
@@ -154,7 +190,7 @@ func TestRestorePlanMissingOptionalPreviousCacheSkipsArtifact(t *testing.T) {
}
got := actionRelPaths(plan.Actions)
want := []string{"manifest.json", "previous/manifest.json"}
want := []string{"inputs/previous/manifest.json", "manifest.json"}
if !slices.Equal(got, want) {
t.Fatalf("action local paths = %#v, want %#v", got, want)
}
@@ -184,7 +220,7 @@ func TestRestorePlanPreviousCacheConflictRequiresForce(t *testing.T) {
seedCurrentRestoreObject(t, store, current, current.CurrentManifestKey, []byte(`{"session_id":"2026-05-03"}`))
seedRestorePreviousCurrent(t, store, cfg, "# remote previous recap\n")
sessionRoot := artifacts.SessionWorkDirForCampaign(cfg.Pipeline.Workspace.Root, cfg.Session.Campaign, cfg.Session.SessionID)
mustWriteTestFile(t, filepath.Join(sessionRoot, "previous", "artifacts", "session_recap.md"), "# local previous recap\n")
mustWriteTestFile(t, filepath.Join(sessionRoot, "inputs", "previous", "artifacts", "session_recap.md"), "# local previous recap\n")
plan, err := buildRestorePlan(context.Background(), cfg, current, store, RestorePlanOptions{})
if err != nil {
@@ -410,6 +446,9 @@ func seedRestoreObject(store *storage.FakeBackend, key string, data []byte) {
name := strings.TrimPrefix(relative, "published/")
name = strings.TrimSuffix(strings.TrimPrefix(name, "artifacts/"), filepath.Ext(name))
source = artifacts.ConfiguredArtifactSourceID(name)
if name == "encounters" {
source = artifacts.ExtractionArtifactSourceID(name)
}
}
artifact := remoteRestoreArtifact(store, typeID, source, destination)
replaced := false

View File

@@ -76,10 +76,10 @@ func TestForcedRestoreRetryClearsIncompleteMarker(t *testing.T) {
pipelinePath, campaignPath, sessionPath := writeValidConfigFiles(t, workspaceRoot)
fake := &storage.FakeBackend{}
cfg, sessionPrefix, _, _ := seedRestoreCommittedState(t, fake, pipelinePath, campaignPath, sessionPath)
artifactKey := sessionPrefix + "artifacts/session_recap.md"
transcriptKey := sessionPrefix + "transcripts/full.json"
seedRestoreObject(fake, artifactKey, []byte("remote recap\n"))
seedRestoreObject(fake, transcriptKey, []byte("remote transcript\n"))
seedCommittedRestoreSnapshot(t, cfg, fake, "20260519T010203Z-a1b2c3d4", map[string][]byte{
"artifacts/session_recap.md": []byte("remote recap\n"),
"transcripts/full.json": []byte("remote transcript\n"),
})
sessionRoot := artifacts.SessionWorkDirForCampaign(workspaceRoot, cfg.Session.Campaign, cfg.Session.SessionID)
mustWriteTestFile(t, filepath.Join(sessionRoot, "artifacts", "session_recap.md"), "local recap\n")

View File

@@ -3,6 +3,7 @@ package app
import (
"encoding/json"
"fmt"
"strings"
"path/filepath"
@@ -71,8 +72,7 @@ func newRestoreReport(current *RemoteCurrentState, plan *RestorePlan, opts Resto
SkipSame: plan.SkipSameCount,
Conflicts: plan.ConflictCount,
},
Actions: make([]RestoreReportAction, 0, len(plan.Actions)),
reportPathRel: filepath.ToSlash(filepath.Join(config.PathReportsDirSegment, "restore-latest.json")),
Actions: make([]RestoreReportAction, 0, len(plan.Actions)),
}
for _, action := range plan.Actions {
r.Actions = append(r.Actions, RestoreReportAction{
@@ -163,6 +163,9 @@ func persistRestoreReport(store artifacts.Store, cfg *config.Config, report *Res
if report == nil {
return "", fmt.Errorf("restore report is required")
}
if strings.TrimSpace(report.reportPathRel) == "" {
return "", fmt.Errorf("restore report path is required")
}
sessionRoot := artifacts.SessionWorkDirForCampaign(cfg.Pipeline.Workspace.Root, cfg.Session.Campaign, cfg.Session.SessionID)
reportPath := filepath.Join(sessionRoot, filepath.FromSlash(report.reportPathRel))
payload, err := json.MarshalIndent(report, "", " ")

View File

@@ -41,9 +41,10 @@ func TestExecuteRestoreDryRunPrintsPlanWithoutWriting(t *testing.T) {
deps := restoreCommandDependencies(&storage.FakeBackend{})
deps.discoverRemoteCurrentState = func(context.Context, *config.Config, storage.ObjectStore) (*RemoteCurrentState, error) {
return &RemoteCurrentState{
SessionID: "2026-05-03",
Campaign: "sample-campaign",
RunID: "20260519T010203Z-a1b2c3d4",
SessionID: "2026-05-03",
Campaign: "sample-campaign",
RunID: "20260519T010203Z-a1b2c3d4",
ManifestData: restoreManifestJSON(t, "2026-05-03", "sample-campaign"),
}, nil
}
deps.buildRestorePlan = func(context.Context, *config.Config, *RemoteCurrentState, storage.ObjectStore, RestorePlanOptions) (*RestorePlan, error) {
@@ -95,7 +96,7 @@ func TestExecuteRestoreDryRunPrintsPlanWithoutWriting(t *testing.T) {
if _, err := os.Stat(manifestPath); !os.IsNotExist(err) {
t.Fatalf("manifest should not be created during dry-run restore planning; stat err=%v", err)
}
reportPath := filepath.Join(workspaceRoot, "work", "sample-campaign", "2026-05-03", "reports", "restore-latest.json")
reportPath := filepath.Join(workspaceRoot, "work", "sample-campaign", "2026-05-03", "logs", "restore", "restore.json")
if _, err := os.Stat(reportPath); !os.IsNotExist(err) {
t.Fatalf("restore report should not be written during dry-run; stat err=%v", err)
}
@@ -188,9 +189,10 @@ func TestExecuteRestoreLoadsSecretsBeforeObjectStoreInit(t *testing.T) {
}}
deps.discoverRemoteCurrentState = func(context.Context, *config.Config, storage.ObjectStore) (*RemoteCurrentState, error) {
return &RemoteCurrentState{
SessionID: "2026-05-03",
Campaign: "sample-campaign",
RunID: "20260519T010203Z-a1b2c3d4",
SessionID: "2026-05-03",
Campaign: "sample-campaign",
RunID: "20260519T010203Z-a1b2c3d4",
ManifestData: restoreManifestJSON(t, "2026-05-03", "sample-campaign"),
}, nil
}
deps.buildRestorePlan = func(context.Context, *config.Config, *RemoteCurrentState, storage.ObjectStore, RestorePlanOptions) (*RestorePlan, error) {
@@ -234,9 +236,10 @@ func TestExecuteRestoreNonDryRunConflictDoesNotWrite(t *testing.T) {
deps := restoreCommandDependencies(&storage.FakeBackend{})
deps.discoverRemoteCurrentState = func(context.Context, *config.Config, storage.ObjectStore) (*RemoteCurrentState, error) {
return &RemoteCurrentState{
SessionID: "2026-05-03",
Campaign: "sample-campaign",
RunID: "20260519T010203Z-a1b2c3d4",
SessionID: "2026-05-03",
Campaign: "sample-campaign",
RunID: "20260519T010203Z-a1b2c3d4",
ManifestData: restoreManifestJSON(t, "2026-05-03", "sample-campaign"),
}, nil
}
deps.buildRestorePlan = func(context.Context, *config.Config, *RemoteCurrentState, storage.ObjectStore, RestorePlanOptions) (*RestorePlan, error) {
@@ -267,7 +270,7 @@ func TestExecuteRestoreNonDryRunConflictDoesNotWrite(t *testing.T) {
func TestExecuteRestoreForceStillBlocksUnresolvedConflict(t *testing.T) {
deps := restoreCommandDependencies(&storage.FakeBackend{})
deps.discoverRemoteCurrentState = func(context.Context, *config.Config, storage.ObjectStore) (*RemoteCurrentState, error) {
return &RemoteCurrentState{SessionID: "2026-05-03", Campaign: "sample-campaign", RunID: "20260519T010203Z-a1b2c3d4"}, nil
return &RemoteCurrentState{SessionID: "2026-05-03", Campaign: "sample-campaign", RunID: "20260519T010203Z-a1b2c3d4", ManifestData: restoreManifestJSON(t, "2026-05-03", "sample-campaign")}, nil
}
deps.buildRestorePlan = func(context.Context, *config.Config, *RemoteCurrentState, storage.ObjectStore, RestorePlanOptions) (*RestorePlan, error) {
return &RestorePlan{Actions: []RestoreAction{{Kind: RestoreActionConflict, LocalRelativePath: "artifacts/session_recap.md", Reason: "local path is a directory"}}, ConflictCount: 1}, nil
@@ -295,9 +298,10 @@ func TestExecuteRestoreNonDryRunForceExecutesPlan(t *testing.T) {
deps := restoreCommandDependencies(&storage.FakeBackend{})
deps.discoverRemoteCurrentState = func(context.Context, *config.Config, storage.ObjectStore) (*RemoteCurrentState, error) {
return &RemoteCurrentState{
SessionID: "2026-05-03",
Campaign: "sample-campaign",
RunID: "20260519T010203Z-a1b2c3d4",
SessionID: "2026-05-03",
Campaign: "sample-campaign",
RunID: "20260519T010203Z-a1b2c3d4",
ManifestData: restoreManifestJSON(t, "2026-05-03", "sample-campaign"),
}, nil
}
deps.buildRestorePlan = func(context.Context, *config.Config, *RemoteCurrentState, storage.ObjectStore, RestorePlanOptions) (*RestorePlan, error) {
@@ -346,7 +350,6 @@ campaign: sample-campaign
inputs:
audio_dir: ./audio
speakers_file: ./speakers.yml
autocorrect_file: ./autocorrect.yml
glossary_file: ./glossary.yml
`
if err := os.WriteFile(pipelinePath, []byte(pipelineYAML), 0o644); err != nil {

View File

@@ -32,7 +32,7 @@ func TestResolveUsesExactCommittedDeclaration(t *testing.T) {
t.Fatalf("PreviousRunID = %q, want previous-run", plan.PreviousRunID)
}
got := recordRelPaths(plan.Records)
want := []string{"previous/artifacts/session_recap.md", "previous/manifest.json"}
want := []string{"inputs/previous/artifacts/session_recap.md", "inputs/previous/manifest.json"}
if strings.Join(got, ",") != strings.Join(want, ",") {
t.Fatalf("record rel paths = %#v, want %#v", got, want)
}
@@ -73,7 +73,7 @@ func TestResolveDerivesLocalPathFromCommittedDestination(t *testing.T) {
if len(plan.Records) != 2 {
t.Fatalf("records len = %d, want 2", len(plan.Records))
}
if plan.Records[0].LocalRelativePath != "previous/artifacts/session_recap.md" {
if plan.Records[0].LocalRelativePath != "inputs/previous/artifacts/session_recap.md" {
t.Fatalf("artifact local relative path = %q", plan.Records[0].LocalRelativePath)
}
}
@@ -116,7 +116,7 @@ func TestResolveUsesCommittedSourceMappingForCustomDestination(t *testing.T) {
if artifact.RemoteKey != customKey {
t.Fatalf("remote key = %q, want exact configured source destination %q", artifact.RemoteKey, customKey)
}
if artifact.LocalRelativePath != "previous/artifacts/history/recap-v2.txt" {
if artifact.LocalRelativePath != "inputs/previous/artifacts/history/recap-v2.txt" {
t.Fatalf("local relative path = %q, want committed-destination cache path", artifact.LocalRelativePath)
}
}