Merge imported products into local session state

This commit is contained in:
2026-12-02 16:24:33 +00:00
parent ad8a5df97b
commit e7fada4372
26 changed files with 638 additions and 1254 deletions

View File

@@ -14,20 +14,18 @@ import (
)
type commandDependencies struct {
reporter logging.Reporter
pipelineSearch *configkit.Search
preparePipelineSource func(configkit.Source) (*configkit.SecretsReport, configkit.Source, error)
loadPipelineSource func(configkit.Source, config.PipelineLoadOptions) (*config.PipelineConfig, error)
newObjectStore func(context.Context, *config.Config) (storage.ObjectStore, error)
newWorkspaceStore func(string) artifacts.Store
newScriptorium func() scriptorium.Runner
newAudita func(*config.Config) (audita.Runner, error)
newNotarius func() notarius.Runner
discoverRemoteCurrentState func(context.Context, *config.Config, storage.ObjectStore) (*RemoteCurrentState, error)
discoverRemotePublication func(context.Context, *config.Config, storage.ObjectStore) (*RemoteCurrentState, error)
buildRestorePlan func(context.Context, *config.Config, *RemoteCurrentState, storage.ObjectStore, RestorePlanOptions) (*RestorePlan, error)
buildInventoryRestorePlan func(context.Context, *config.Config, *RemoteCurrentState, storage.ObjectStore, RestorePlanOptions) (*RestorePlan, error)
executeRestorePlan func(context.Context, *config.Config, *RemoteCurrentState, *RestorePlan, *RestoreReport, storage.ObjectStore) (*RestoreExecutionResult, error)
reporter logging.Reporter
pipelineSearch *configkit.Search
preparePipelineSource func(configkit.Source) (*configkit.SecretsReport, configkit.Source, error)
loadPipelineSource func(configkit.Source, config.PipelineLoadOptions) (*config.PipelineConfig, error)
newObjectStore func(context.Context, *config.Config) (storage.ObjectStore, error)
newWorkspaceStore func(string) artifacts.Store
newScriptorium func() scriptorium.Runner
newAudita func(*config.Config) (audita.Runner, error)
newNotarius func() notarius.Runner
discoverRemotePublication func(context.Context, *config.Config, storage.ObjectStore) (*RemoteCurrentState, error)
buildInventoryRestorePlan func(context.Context, *config.Config, *RemoteCurrentState, storage.ObjectStore, RestorePlanOptions) (*RestorePlan, error)
executeRestorePlan func(context.Context, *config.Config, *RemoteCurrentState, *RestorePlan, *RestoreReport, storage.ObjectStore) (*RestoreExecutionResult, error)
}
func normalizeCommandDependencies(deps commandDependencies) commandDependencies {
@@ -54,15 +52,9 @@ func normalizeCommandDependencies(deps commandDependencies) commandDependencies
if deps.newScriptorium == nil {
deps.newScriptorium = defaultScriptoriumRunner
}
if deps.discoverRemoteCurrentState == nil {
deps.discoverRemoteCurrentState = discoverRemoteCurrentState
}
if deps.discoverRemotePublication == nil {
deps.discoverRemotePublication = discoverRemotePublication
}
if deps.buildRestorePlan == nil {
deps.buildRestorePlan = buildRestorePlan
}
if deps.buildInventoryRestorePlan == nil {
deps.buildInventoryRestorePlan = buildInventoryRestorePlan
}

View File

@@ -140,11 +140,11 @@ func TestPreparedSessionPublishAndRemoteLoad(t *testing.T) {
if got := received.StableInputs.SpeakersFile; got.Source != "session_config" || got.Path != filepath.Join(filepath.Dir(campaignPath), "speakers.yml") {
t.Fatalf("receiving session speakers = %#v", got)
}
current, err := discoverRemoteCurrentState(ctx, received, fake)
current, err := discoverRemotePublication(ctx, received, fake)
if err != nil {
t.Fatal(err)
}
plan, err := buildRestorePlan(ctx, received, current, fake, RestorePlanOptions{Force: true})
plan, err := buildInventoryRestorePlan(ctx, received, current, fake, RestorePlanOptions{Force: true})
if err != nil {
t.Fatal(err)
}
@@ -161,6 +161,9 @@ func TestPreparedSessionPublishAndRemoteLoad(t *testing.T) {
}
}
paths := store.SessionPathsFor(m.Campaign, m.SessionID)
if err := (&manifest.LocalStore{}).Save(ctx, paths.ManifestPath, m); err != nil {
t.Fatal(err)
}
for _, name := range []string{"session.yml", "campaign.yml", "party.yml", "glossaries/party.yml", "glossaries/campaign.yml", "glossaries/setting.yml", "glossaries/spells.yml"} {
if name == "glossaries/campaign.yml" {
if err := os.WriteFile(filepath.Join(paths.InputsDir, name), []byte("local change"), 0644); err != nil {
@@ -212,7 +215,7 @@ func TestPreparedSessionPublishAndRemoteLoad(t *testing.T) {
if string(fake.Objects[key].Data) != committedBytes {
t.Fatal("authoring update changed committed input")
}
if _, err := discoverRemoteCurrentState(ctx, authored, fake); err != nil {
if _, err := discoverRemotePublication(ctx, authored, fake); err != nil {
t.Fatalf("committed state after authoring update: %v", err)
}
// Remove the authored override to exercise committed-snapshot integrity below.

View File

@@ -560,9 +560,9 @@ func TestPublicationInspectionAndSessionConfigIgnoreExecutionSnapshot(t *testing
current.Commit.Artifacts = filtered
}
if tc.body == nil {
delete(fake.Objects, current.CurrentManifestKey)
delete(fake.Objects, artifacts.S3RunSessionManifestKey(current.SessionPrefix, current.RunID))
} else {
fake.SeedObject(storage.FakeObject{Key: current.CurrentManifestKey, Data: tc.body})
fake.SeedObject(storage.FakeObject{Key: artifacts.S3RunSessionManifestKey(current.SessionPrefix, current.RunID), Data: tc.body})
}
commitData, err := artifacts.EncodeRemoteCommitManifest(*current.Commit)
if err != nil {
@@ -595,7 +595,7 @@ func TestPublicationInspectionAndSessionConfigIgnoreExecutionSnapshot(t *testing
t.Fatalf("session %s", data)
}
for _, read := range fake.Reads {
if read.Key == current.CurrentManifestKey {
if read.Key == artifacts.S3RunSessionManifestKey(current.SessionPrefix, current.RunID) {
t.Fatal("execution snapshot was read")
}
}

View File

@@ -0,0 +1,172 @@
package app
import (
"context"
"errors"
"os"
"path/filepath"
"testing"
"time"
"gitea.maximumdirect.net/eric/narratio/internal/adapters/storage"
"gitea.maximumdirect.net/eric/narratio/internal/artifacts"
"gitea.maximumdirect.net/eric/narratio/internal/manifest"
)
func TestInventoryImportInstallsValidatedBaselineAndRetriesSave(t *testing.T) {
ctx := context.Background()
cfg := restorePlanConfig(t)
fake := &storage.FakeBackend{}
current := seedCommittedRestoreSnapshot(t, cfg, fake, "20260519T010203Z-a1b2c3d4", map[string][]byte{"transcripts/remote.json": []byte(`{"segments":[]}`)})
current.Commit.Artifacts[1].Source = artifacts.ArtifactTranscriptFinalTrimmed
plan, err := buildInventoryRestorePlan(ctx, cfg, current, fake, RestorePlanOptions{})
if err != nil {
t.Fatal(err)
}
if _, err := executeRestorePlan(ctx, cfg, current, plan, nil, fake); err != nil {
t.Fatal(err)
}
if err := installInventoryBaseline(ctx, cfg, plan, &failingRestoreManifestStore{}); err == nil {
t.Fatal("expected final manifest save to fail")
}
path := artifacts.SessionManifestPathForCampaign(cfg.Pipeline.Workspace.Root, cfg.Session.Campaign, cfg.Session.SessionID)
if _, err := os.Stat(path); !os.IsNotExist(err) {
t.Fatalf("failed save installed manifest: %v", err)
}
retry, err := buildInventoryRestorePlan(ctx, cfg, current, fake, RestorePlanOptions{})
if err != nil || retry.SkipSameCount != 1 {
t.Fatalf("retry plan = %#v, %v", retry, err)
}
if err := installInventoryBaseline(ctx, cfg, retry, &manifest.LocalStore{}); err != nil {
t.Fatal(err)
}
loaded, err := (&manifest.LocalStore{}).Load(ctx, path)
if err != nil {
t.Fatal(err)
}
paths := artifacts.NewLocalStore(cfg.Pipeline.Workspace.Root).SessionPathsFor(cfg.Session.Campaign, cfg.Session.SessionID)
if !artifacts.SuppliedTranscriptCoverage(paths, loaded.SuppliedProducts)["trim"] {
t.Fatalf("trimmed transcript unavailable after retry: %#v", loaded.SuppliedProducts)
}
if loaded.Stages["publish"] != nil || loaded.Stages["cleanup"] != nil {
t.Fatalf("import fabricated execution: %#v", loaded.Stages)
}
}
func TestInventoryImportReplacesProductAndInvalidatesDependents(t *testing.T) {
ctx := context.Background()
cfg := restorePlanConfig(t)
paths := artifacts.NewLocalStore(cfg.Pipeline.Workspace.Root).SessionPathsFor(cfg.Session.Campaign, cfg.Session.SessionID)
localPath := filepath.Join(paths.Root, "transcripts", "final.trimmed.json")
oldData := []byte(`{"segments":[]}`)
if err := os.MkdirAll(filepath.Dir(localPath), 0755); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(localPath, oldData, 0600); err != nil {
t.Fatal(err)
}
local := manifest.New(cfg.Session.SessionID, time.Now().UTC())
local.Campaign = cfg.Session.Campaign
local.SuppliedProducts = &manifest.SuppliedProductCollection{Version: manifest.SuppliedProductVersion, Products: map[string]manifest.SuppliedProduct{
artifacts.ArtifactTranscriptFinalTrimmed: {Path: "transcripts/final.trimmed.json", Checksum: restoreCommitSHA256(oldData), Size: int64(len(oldData))},
}}
for _, name := range []string{"prepare", "trim", "render", "extract", "analyze"} {
local.MarkStageSucceeded(name, time.Now().UTC(), nil)
}
if err := (&manifest.LocalStore{}).Save(ctx, paths.ManifestPath, local); err != nil {
t.Fatal(err)
}
fake := &storage.FakeBackend{}
current := seedCommittedRestoreSnapshot(t, cfg, fake, "20260519T010203Z-a1b2c3d4", map[string][]byte{"transcripts/remote.json": []byte(`{"segments":[{"text":"changed"}]}`)})
current.Commit.Artifacts[1].Source = artifacts.ArtifactTranscriptFinalTrimmed
conflict, err := buildInventoryRestorePlan(ctx, cfg, current, fake, RestorePlanOptions{})
if err != nil || conflict.ConflictCount != 1 {
t.Fatalf("conflict plan = %#v, %v", conflict, err)
}
plan, err := buildInventoryRestorePlan(ctx, cfg, current, fake, RestorePlanOptions{Force: true})
if err != nil {
t.Fatal(err)
}
if _, err := executeRestorePlan(ctx, cfg, current, plan, nil, fake); err != nil {
t.Fatal(err)
}
if err := installInventoryBaseline(ctx, cfg, plan, &manifest.LocalStore{}); err != nil {
t.Fatal(err)
}
loaded, err := (&manifest.LocalStore{}).Load(ctx, paths.ManifestPath)
if err != nil {
t.Fatal(err)
}
if loaded.Stages["prepare"].Status != manifest.StatusSucceeded {
t.Fatal("unrelated preparation was invalidated")
}
for _, name := range []string{"trim", "render", "extract", "analyze"} {
if loaded.Stages[name].Status != manifest.StatusStale {
t.Fatalf("%s status = %q", name, loaded.Stages[name].Status)
}
}
if !artifacts.SuppliedTranscriptCoverage(paths, loaded.SuppliedProducts)["trim"] {
t.Fatal("replacement is not available")
}
}
func TestInventoryImportPreservesIdenticalLocalAuthority(t *testing.T) {
ctx := context.Background()
cfg := restorePlanConfig(t)
paths := artifacts.NewLocalStore(cfg.Pipeline.Workspace.Root).SessionPathsFor(cfg.Session.Campaign, cfg.Session.SessionID)
localPath := filepath.Join(paths.Root, "transcripts", "final.trimmed.json")
body := []byte(`{"segments":[]}`)
if err := os.MkdirAll(filepath.Dir(localPath), 0755); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(localPath, body, 0600); err != nil {
t.Fatal(err)
}
local := manifest.New(cfg.Session.SessionID, time.Now().UTC())
local.Campaign = cfg.Session.Campaign
local.RunID = "20260519T010203Z-a1b2c3d4"
setCurrentBuiltInEvidence(t, local, "trim", artifacts.TranscriptOutputKindFinalTrimmed, artifacts.ArtifactTranscriptFinalTrimmed, localPath)
local.MarkStageSucceeded("render", time.Now().UTC(), nil)
if err := (&manifest.LocalStore{}).Save(ctx, paths.ManifestPath, local); err != nil {
t.Fatal(err)
}
fake := &storage.FakeBackend{}
current := seedCommittedRestoreSnapshot(t, cfg, fake, "20260519T010203Z-a1b2c3d4", map[string][]byte{"transcripts/remote.json": body})
current.Commit.Artifacts[1].Source = artifacts.ArtifactTranscriptFinalTrimmed
plan, err := buildInventoryRestorePlan(ctx, cfg, current, fake, RestorePlanOptions{})
if err != nil || plan.SkipSameCount != 1 {
t.Fatalf("identical plan = %#v, %v", plan, err)
}
if err := installInventoryBaseline(ctx, cfg, plan, &manifest.LocalStore{}); err != nil {
t.Fatal(err)
}
loaded, err := (&manifest.LocalStore{}).Load(ctx, paths.ManifestPath)
if err != nil {
t.Fatal(err)
}
if loaded.SuppliedProducts != nil || loaded.Stages["trim"].Status != manifest.StatusSucceeded || loaded.Stages["render"].Status != manifest.StatusSucceeded {
t.Fatalf("identical import changed existing authority: %#v", loaded)
}
}
func TestInventoryImportRejectsWrongLocalSessionIdentity(t *testing.T) {
ctx := context.Background()
cfg := restorePlanConfig(t)
paths := artifacts.NewLocalStore(cfg.Pipeline.Workspace.Root).SessionPathsFor(cfg.Session.Campaign, cfg.Session.SessionID)
local := manifest.New("another-session", time.Now().UTC())
local.Campaign = cfg.Session.Campaign
if err := (&manifest.LocalStore{}).Save(ctx, paths.ManifestPath, local); err != nil {
t.Fatal(err)
}
fake := &storage.FakeBackend{}
current := seedCommittedRestoreSnapshot(t, cfg, fake, "20260519T010203Z-a1b2c3d4", nil)
if _, err := buildInventoryRestorePlan(ctx, cfg, current, fake, RestorePlanOptions{}); err == nil {
t.Fatal("expected a local session identity mismatch")
}
}
type failingRestoreManifestStore struct{ manifest.LocalStore }
func (failingRestoreManifestStore) Save(context.Context, string, *manifest.Manifest) error {
return errors.New("synthetic save failure")
}

View File

@@ -1,7 +1,6 @@
package app
import (
"bytes"
"context"
"errors"
"fmt"
@@ -78,17 +77,10 @@ func restoreSessionState(ctx context.Context, cfg *config.Config, opts RestorePl
}
return report, nil
}
current, err := deps.discoverRemoteCurrentState(ctx, cfg, objectStore)
current, err := deps.discoverRemotePublication(ctx, cfg, objectStore)
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)
@@ -117,7 +109,7 @@ func restoreSessionState(ctx context.Context, cfg *config.Config, opts RestorePl
// Classification and installation share the same transition lock as a
// runner. This prevents a runner from making reuse decisions against state
// that restore is about to replace.
plan, err := deps.buildRestorePlan(ctx, cfg, current, objectStore, RestorePlanOptions{
plan, err := deps.buildInventoryRestorePlan(ctx, cfg, current, objectStore, RestorePlanOptions{
IncludeAudio: opts.IncludeAudio,
Force: opts.Force,
})
@@ -167,6 +159,9 @@ func restoreSessionState(ctx context.Context, cfg *config.Config, opts RestorePl
if result == nil {
return diagnostic, fmt.Errorf("restore execution returned no result")
}
if err := installInventoryBaseline(ctx, cfg, plan, &manifest.LocalStore{}); err != nil {
return diagnostic, fmt.Errorf("restore: install local baseline: %w", err)
}
report.Execution.Downloaded = result.DownloadedCount
report.setSucceeded()
if err := clearRestoreMarker(artifactStore.SessionPathsFor(cfg.Session.Campaign, cfg.Session.SessionID)); err != nil {
@@ -181,7 +176,7 @@ func restoreSessionState(ctx context.Context, cfg *config.Config, opts RestorePl
func restoreCommand(deps commandDependencies) commandkit.Command {
common := newConfigurationFlags(func(input **restoreCommandInput) *configurationSelection { return &(*input).Selection })
return commandkit.NewCommand(commandkit.CommandSpec[*restoreCommandInput]{Name: "restore", Summary: "Restore the committed remote session snapshot.", NewInput: func() *restoreCommandInput { return &restoreCommandInput{} },
return commandkit.NewCommand(commandkit.CommandSpec[*restoreCommandInput]{Name: "restore", Summary: "Import products from the current remote publication.", NewInput: func() *restoreCommandInput { return &restoreCommandInput{} },
Flags: []commandkit.Flag[*restoreCommandInput]{common.Config, common.Overlay, common.Campaign, common.CampaignFile, common.SessionFile, common.PartyFile,
commandkit.ValueFlag(commandkit.FlagMeta{Name: "previous-session-id", Usage: "Assert the previous session identity."}, nil, stringValue, func(input **restoreCommandInput, value commandkit.Supplied[string]) {
(*input).PreviousSession = value.Value

View File

@@ -34,7 +34,7 @@ func TestRestoreCommandDryRunLeavesMissingWorkspaceAbsent(t *testing.T) {
fake := &storage.FakeBackend{}
cfg, _, _, _ := seedRestoreCommittedState(t, fake, pipeline, campaign, session)
current := seedCommittedRestoreSnapshot(t, cfg, fake, "20260519T010203Z-a1b2c3d4", map[string][]byte{"audio/speaker.flac": []byte("synthetic audio\n")})
delete(fake.Objects, current.CurrentManifestKey)
delete(fake.Objects, artifacts.S3RunSessionManifestKey(current.SessionPrefix, current.RunID))
fake.Reads = nil
paths := artifacts.NewLocalStore(cfg.Pipeline.Workspace.Root).SessionPathsFor(cfg.Session.Campaign, cfg.Session.SessionID)
if _, err := os.Stat(paths.Root); !os.IsNotExist(err) {
@@ -50,7 +50,7 @@ func TestRestoreCommandDryRunLeavesMissingWorkspaceAbsent(t *testing.T) {
t.Fatalf("report=%#v", report)
}
for _, read := range fake.Reads {
if read.Key == current.CurrentManifestKey {
if read.Key == artifacts.S3RunSessionManifestKey(current.SessionPrefix, current.RunID) {
t.Fatalf("dry run read obsolete execution snapshot %q", read.Key)
}
}

View File

@@ -23,17 +23,17 @@ func TestCommittedRestorePlanUsesOnlyDeclaredObjects(t *testing.T) {
cfg := restorePlanConfig(t)
fake := &storage.FakeBackend{}
current := seedCommittedRestoreSnapshot(t, cfg, fake, "20260519T010203Z-a1b2c3d4", map[string][]byte{
"transcripts/full.json": []byte(`{"segments":[1]}`),
"transcripts/final.trimmed.json": []byte(`{"segments":[1]}`),
})
fake.SeedObject(storage.FakeObject{Key: current.SessionPrefix + "artifacts/stale.md", Data: []byte("stale")})
fake.SeedObject(storage.FakeObject{Key: artifacts.S3RunRelativeDestinationKey(artifacts.S3RunPrefix(current.SessionPrefix, "20260519T010204Z-e5f6a7b8"), "transcripts/other.json"), Data: []byte("other")})
plan, err := buildRestorePlan(context.Background(), cfg, current, fake, RestorePlanOptions{})
plan, err := buildInventoryRestorePlan(context.Background(), cfg, current, fake, RestorePlanOptions{})
if err != nil {
t.Fatalf("buildRestorePlan() error = %v", err)
t.Fatalf("buildInventoryRestorePlan() error = %v", err)
}
got := actionRelPaths(plan.Actions)
want := []string{"manifest.json", "transcripts/full.json"}
want := []string{"transcripts/final.trimmed.json"}
if len(got) != len(want) {
t.Fatalf("action paths = %#v, want %#v", got, want)
}
@@ -64,7 +64,7 @@ func TestCommittedRestoreInstallsPreparedInputsAndFlatProducts(t *testing.T) {
item.DestinationKey, item.Generation = key, fake.Objects[key].ETag
}
}
plan, err := buildRestorePlan(context.Background(), cfg, current, fake, RestorePlanOptions{})
plan, err := buildInventoryRestorePlan(context.Background(), cfg, current, fake, RestorePlanOptions{})
if err != nil {
t.Fatal(err)
}
@@ -88,7 +88,7 @@ func TestCommittedRestoreUsesAbsoluteConfiguredProductDestination(t *testing.T)
current := seedCommittedRestoreSnapshot(t, cfg, fake, "20260519T010203Z-a1b2c3d4", map[string][]byte{
"artifacts/session_recap.md": []byte("recap"),
})
plan, err := buildRestorePlan(context.Background(), cfg, current, fake, RestorePlanOptions{})
plan, err := buildInventoryRestorePlan(context.Background(), cfg, current, fake, RestorePlanOptions{})
if err != nil {
t.Fatal(err)
}
@@ -102,16 +102,14 @@ func TestCommittedRestoreDoesNotRequirePolishRunDiagnostics(t *testing.T) {
cfg := restorePlanConfig(t)
fake := &storage.FakeBackend{}
current := seedCommittedRestoreSnapshot(t, cfg, fake, "20260519T010203Z-a1b2c3d4", map[string][]byte{
"transcripts/full.json": []byte(`{"segments":[]}`),
"transcripts/final.trimmed.json": []byte(`{"segments":[]}`),
})
diagnostic := filepath.Join(cfg.Pipeline.Workspace.Root, "runs", current.RunID, "polish", "outputs", "transcripts", "errors.yml")
current.Manifest.Stages["polish"] = &manifest.StageRecord{
Name: "polish", Status: manifest.StatusSucceeded,
Logs: []string{diagnostic},
}
plan, err := buildRestorePlan(context.Background(), cfg, current, fake, RestorePlanOptions{})
diagnosticKey := artifacts.S3RunRelativeDestinationKey(artifacts.S3RunPrefix(current.SessionPrefix, current.RunID), "polish/logs/errors.yml")
fake.SeedObject(storage.FakeObject{Key: diagnosticKey, Data: []byte("diagnostic")})
current.Commit.Artifacts = append(current.Commit.Artifacts, remoteRestoreArtifact(fake, artifacts.RemoteArtifactTypeRunFile, "run:polish/logs/errors.yml", diagnosticKey))
plan, err := buildInventoryRestorePlan(context.Background(), cfg, current, fake, RestorePlanOptions{})
if err != nil {
t.Fatalf("buildRestorePlan() error = %v", err)
t.Fatalf("buildInventoryRestorePlan() error = %v", err)
}
for _, action := range plan.Actions {
if strings.Contains(action.LocalRelativePath, "errors.yml") {
@@ -124,7 +122,7 @@ func TestCommittedRestoreDownloadsCarriedOutputFromDeclaredRun(t *testing.T) {
cfg := restorePlanConfig(t)
fake := &storage.FakeBackend{}
current := seedCommittedRestoreSnapshot(t, cfg, fake, "20260519T010203Z-a1b2c3d4", map[string][]byte{
"transcripts/full.json": []byte("carried\n"),
"transcripts/final.trimmed.json": []byte("carried\n"),
})
declaration := &current.Commit.Artifacts[1]
oldKey := artifacts.S3RunRelativeDestinationKey(artifacts.S3RunPrefix(current.SessionPrefix, "20260512T010203Z-11223344"), "published/transcripts/full.json")
@@ -136,11 +134,11 @@ func TestCommittedRestoreDownloadsCarriedOutputFromDeclaredRun(t *testing.T) {
t.Fatalf("carried commit validation: %v", err)
}
plan, err := buildRestorePlan(context.Background(), cfg, current, fake, RestorePlanOptions{})
plan, err := buildInventoryRestorePlan(context.Background(), cfg, current, fake, RestorePlanOptions{})
if err != nil {
t.Fatalf("buildRestorePlan() error = %v", err)
t.Fatalf("buildInventoryRestorePlan() error = %v", err)
}
action := restoreActionForPath(t, plan, "transcripts/full.json")
action := restoreActionForPath(t, plan, "transcripts/final.trimmed.json")
if action.RemoteKey != oldKey {
t.Fatalf("restore remote key = %q, want exact carried key %q", action.RemoteKey, oldKey)
}
@@ -152,54 +150,18 @@ func TestCommittedRestoreDownloadsCarriedOutputFromDeclaredRun(t *testing.T) {
}
}
func TestCommittedRestoreReusesVerifiedManifestCandidate(t *testing.T) {
cfg := restorePlanConfig(t)
fake := &storage.FakeBackend{}
current := seedCommittedRestoreSnapshot(t, cfg, fake, "20260519T010203Z-a1b2c3d4", nil)
plan, err := buildRestorePlan(context.Background(), cfg, current, fake, RestorePlanOptions{})
if err != nil {
t.Fatalf("buildRestorePlan() error = %v", err)
}
if _, err := executeRestorePlan(context.Background(), cfg, current, plan, nil, fake); err != nil {
t.Fatalf("executeRestorePlan() error = %v", err)
}
if got := fakeReadCount(fake, current.CurrentManifestKey); got != 1 {
t.Fatalf("manifest reads = %d, want one discovery read reused by restore", got)
}
}
func TestCommittedRestoreRejectsChangedGenerationForVerifiedManifestCandidate(t *testing.T) {
cfg := restorePlanConfig(t)
fake := &storage.FakeBackend{}
current := seedCommittedRestoreSnapshot(t, cfg, fake, "20260519T010203Z-a1b2c3d4", nil)
plan, err := buildRestorePlan(context.Background(), cfg, current, fake, RestorePlanOptions{})
if err != nil {
t.Fatalf("buildRestorePlan() error = %v", err)
}
fake.SeedObject(storage.FakeObject{Key: current.CurrentManifestKey, Data: []byte("changed manifest"), ETag: "changed-generation"})
_, err = executeRestorePlan(context.Background(), cfg, current, plan, nil, fake)
if err == nil || !strings.Contains(err.Error(), "generation mismatch") {
t.Fatalf("executeRestorePlan() error = %v, want generation mismatch", err)
}
if got := fakeReadCount(fake, current.CurrentManifestKey); got != 1 {
t.Fatalf("manifest reads = %d, want no second transfer for rejected candidate", got)
}
}
func TestCommittedStatusReportsOnlyDeclaredPublishedOutputs(t *testing.T) {
cfg := restorePlanConfig(t)
cfg.Pipeline.Publish = &config.PublishConfig{Outputs: []config.PublishOutputRule{{
Source: "narratio.transcript.final_trimmed",
Dest: "transcripts/full.json",
Dest: "transcripts/final.trimmed.json",
}}}
fake := &storage.FakeBackend{}
current := seedCommittedRestoreSnapshot(t, cfg, fake, "20260519T010203Z-a1b2c3d4", map[string][]byte{
"transcripts/full.json": []byte("declared\n"),
"transcripts/final.trimmed.json": []byte("declared\n"),
})
current.Commit.Artifacts[1].Source = "narratio.transcript.final_trimmed"
fake.SeedObject(storage.FakeObject{Key: current.SessionPrefix + "transcripts/full.json", Data: []byte("mutable stale copy\n")})
fake.SeedObject(storage.FakeObject{Key: current.SessionPrefix + "transcripts/final.trimmed.json", Data: []byte("mutable stale copy\n")})
cfg.ArtifactCatalog = &config.ArtifactCatalog{PublishOutputs: cfg.Pipeline.Publish.Outputs}
outputs, err := inspectPublishedOutputs(context.Background(), cfg, fake, nil, current, nil, true, "available")
@@ -213,26 +175,25 @@ func TestCommittedStatusReportsCarriedOutputOriginAndChecksExactKey(t *testing.T
cfg := restorePlanConfig(t)
cfg.Pipeline.Publish = &config.PublishConfig{Outputs: []config.PublishOutputRule{{
Source: "narratio.transcript.final_trimmed",
Dest: "transcripts/full.json",
Dest: "transcripts/final.trimmed.json",
}}}
cfg.ArtifactCatalog = &config.ArtifactCatalog{PublishOutputs: cfg.Pipeline.Publish.Outputs}
fake := &storage.FakeBackend{}
current := seedCommittedRestoreSnapshot(t, cfg, fake, "20260519T010203Z-a1b2c3d4", map[string][]byte{
"transcripts/full.json": []byte("carried\n"),
"transcripts/final.trimmed.json": []byte("carried\n"),
})
const originRun = "20260512T010203Z-11223344"
oldKey := artifacts.S3RunRelativeDestinationKey(artifacts.S3RunPrefix(current.SessionPrefix, originRun), "published/transcripts/original.json")
fake.SeedObject(storage.FakeObject{Key: oldKey, Data: []byte("carried\n")})
current.Commit.Artifacts[1].Source = "narratio.transcript.final_trimmed"
current.Commit.Artifacts[1].DestinationKey = oldKey
current.Manifest = nil
outputs, err := inspectPublishedOutputs(context.Background(), cfg, fake, nil, current, nil, true, "available")
if err != nil || len(outputs) != 1 {
t.Fatalf("outputs=%#v err=%v", outputs, err)
}
output := outputs[0]
if output.State != "published" || output.Destination != "transcripts/full.json" || output.DeclaredDestination != "transcripts/original.json" || output.DeclaredKey != oldKey || output.OriginRun != originRun {
if output.State != "published" || output.Destination != "transcripts/final.trimmed.json" || output.DeclaredDestination != "transcripts/original.json" || output.DeclaredKey != oldKey || output.OriginRun != originRun {
t.Fatalf("carried output=%#v", output)
}
if len(fake.ExistsKeys) == 0 || fake.ExistsKeys[len(fake.ExistsKeys)-1] != oldKey {
@@ -259,31 +220,27 @@ func TestCommittedPublishOutputOutcomesRecognizesAllStates(t *testing.T) {
}
}
func TestCommittedRestoreKeepsSelectedSnapshotWhenPointerChanges(t *testing.T) {
func TestCommittedRestoreKeepsSelectedInventoryWhenPointerChanges(t *testing.T) {
cfg := restorePlanConfig(t)
fake := &storage.FakeBackend{}
first := seedCommittedRestoreSnapshot(t, cfg, fake, "20260519T010203Z-a1b2c3d4", map[string][]byte{
"transcripts/full.json": []byte("from first commit\n"),
"transcripts/final.trimmed.json": []byte("from first commit\n"),
})
plan, err := buildRestorePlan(context.Background(), cfg, first, fake, RestorePlanOptions{})
plan, err := buildInventoryRestorePlan(context.Background(), cfg, first, fake, RestorePlanOptions{})
if err != nil {
t.Fatalf("buildRestorePlan() error = %v", err)
t.Fatalf("buildInventoryRestorePlan() error = %v", err)
}
_ = seedCommittedRestoreSnapshot(t, cfg, fake, "20260519T010204Z-e5f6a7b8", map[string][]byte{
"transcripts/full.json": []byte("from second commit\n"),
"transcripts/final.trimmed.json": []byte("from second commit\n"),
})
if _, err := executeRestorePlan(context.Background(), cfg, first, plan, nil, fake); err != nil {
t.Fatalf("executeRestorePlan() error = %v", err)
}
root := artifacts.SessionWorkDirForCampaign(cfg.Pipeline.Workspace.Root, cfg.Session.Campaign, cfg.Session.SessionID)
mustReadEquals(t, filepath.Join(root, "transcripts", "full.json"), "from first commit\n")
restored, err := (&manifest.LocalStore{}).Load(context.Background(), filepath.Join(root, "manifest.json"))
if err != nil {
t.Fatalf("load restored manifest: %v", err)
}
if restored.RunID != first.RunID {
t.Fatalf("restored run id = %q, want %q", restored.RunID, first.RunID)
mustReadEquals(t, filepath.Join(root, "transcripts", "final.trimmed.json"), "from first commit\n")
if _, err := os.Stat(filepath.Join(root, "manifest.json")); !os.IsNotExist(err) {
t.Fatalf("transfer unexpectedly installed a remote manifest: %v", err)
}
}
@@ -291,13 +248,13 @@ func TestCommittedRestoreRejectsChangedDeclaredObjectBeforeManifestInstall(t *te
cfg := restorePlanConfig(t)
fake := &storage.FakeBackend{}
current := seedCommittedRestoreSnapshot(t, cfg, fake, "20260519T010203Z-a1b2c3d4", map[string][]byte{
"transcripts/full.json": []byte("committed bytes\n"),
"transcripts/final.trimmed.json": []byte("committed bytes\n"),
})
plan, err := buildRestorePlan(context.Background(), cfg, current, fake, RestorePlanOptions{})
plan, err := buildInventoryRestorePlan(context.Background(), cfg, current, fake, RestorePlanOptions{})
if err != nil {
t.Fatalf("buildRestorePlan() error = %v", err)
t.Fatalf("buildInventoryRestorePlan() error = %v", err)
}
key := artifacts.S3RunRelativeDestinationKey(artifacts.S3RunPrefix(current.SessionPrefix, current.RunID), "published/transcripts/full.json")
key := artifacts.S3RunRelativeDestinationKey(artifacts.S3RunPrefix(current.SessionPrefix, current.RunID), "published/transcripts/final.trimmed.json")
fake.SeedObject(storage.FakeObject{Key: key, Data: []byte("changed bytes\n")})
if _, err := executeRestorePlan(context.Background(), cfg, current, plan, nil, fake); err == nil {
@@ -313,13 +270,13 @@ func TestCommittedRestoreRejectsChangedDeclaredObjectGeneration(t *testing.T) {
cfg := restorePlanConfig(t)
fake := &storage.FakeBackend{}
current := seedCommittedRestoreSnapshot(t, cfg, fake, "20260519T010203Z-a1b2c3d4", map[string][]byte{
"transcripts/full.json": []byte("committed bytes\n"),
"transcripts/final.trimmed.json": []byte("committed bytes\n"),
})
plan, err := buildRestorePlan(context.Background(), cfg, current, fake, RestorePlanOptions{})
plan, err := buildInventoryRestorePlan(context.Background(), cfg, current, fake, RestorePlanOptions{})
if err != nil {
t.Fatalf("buildRestorePlan() error = %v", err)
t.Fatalf("buildInventoryRestorePlan() error = %v", err)
}
key := artifacts.S3RunRelativeDestinationKey(artifacts.S3RunPrefix(current.SessionPrefix, current.RunID), "published/transcripts/full.json")
key := artifacts.S3RunRelativeDestinationKey(artifacts.S3RunPrefix(current.SessionPrefix, current.RunID), "published/transcripts/final.trimmed.json")
fake.SeedObject(storage.FakeObject{Key: key, Data: []byte("committed bytes\n"), ETag: "replacement-generation"})
if _, err := executeRestorePlan(context.Background(), cfg, current, plan, nil, fake); err == nil {
@@ -348,9 +305,9 @@ func TestCommittedRestoreRejectsChangedAudioBeforeInstall(t *testing.T) {
current := seedCommittedRestoreSnapshot(t, cfg, fake, "20260519T010203Z-a1b2c3d4", map[string][]byte{
"audio/alice.flac": []byte("original-audio"),
})
plan, err := buildRestorePlan(context.Background(), cfg, current, fake, RestorePlanOptions{IncludeAudio: true})
plan, err := buildInventoryRestorePlan(context.Background(), cfg, current, fake, RestorePlanOptions{IncludeAudio: true})
if err != nil {
t.Fatalf("buildRestorePlan() error = %v", err)
t.Fatalf("buildInventoryRestorePlan() error = %v", err)
}
key := artifacts.S3RunRelativeDestinationKey(artifacts.S3RunPrefix(current.SessionPrefix, current.RunID), "published/audio/alice.flac")
generation := test.generation
@@ -384,13 +341,13 @@ func TestCommittedRestoreRejectsMissingDeclaredObjectBeforeManifestInstall(t *te
cfg := restorePlanConfig(t)
fake := &storage.FakeBackend{}
current := seedCommittedRestoreSnapshot(t, cfg, fake, "20260519T010203Z-a1b2c3d4", map[string][]byte{
"transcripts/full.json": []byte("committed bytes\n"),
"transcripts/final.trimmed.json": []byte("committed bytes\n"),
})
plan, err := buildRestorePlan(context.Background(), cfg, current, fake, RestorePlanOptions{})
plan, err := buildInventoryRestorePlan(context.Background(), cfg, current, fake, RestorePlanOptions{})
if err != nil {
t.Fatalf("buildRestorePlan() error = %v", err)
t.Fatalf("buildInventoryRestorePlan() error = %v", err)
}
missingKey := artifacts.S3RunRelativeDestinationKey(artifacts.S3RunPrefix(current.SessionPrefix, current.RunID), "published/transcripts/full.json")
missingKey := artifacts.S3RunRelativeDestinationKey(artifacts.S3RunPrefix(current.SessionPrefix, current.RunID), "published/transcripts/final.trimmed.json")
fake.ReadHook = func(call storage.FakeReadCall) error {
if call.Key == missingKey {
return os.ErrNotExist
@@ -411,22 +368,22 @@ func TestCommittedRestoreForceRetainsDirectoryConflict(t *testing.T) {
cfg := restorePlanConfig(t)
fake := &storage.FakeBackend{}
current := seedCommittedRestoreSnapshot(t, cfg, fake, "20260519T010203Z-a1b2c3d4", map[string][]byte{
"transcripts/full.json": []byte("committed bytes\n"),
"transcripts/final.trimmed.json": []byte("committed bytes\n"),
})
root := artifacts.SessionWorkDirForCampaign(cfg.Pipeline.Workspace.Root, cfg.Session.Campaign, cfg.Session.SessionID)
if err := os.MkdirAll(filepath.Join(root, "transcripts", "full.json"), 0o755); err != nil {
if err := os.MkdirAll(filepath.Join(root, "transcripts", "final.trimmed.json"), 0o755); err != nil {
t.Fatalf("MkdirAll() error = %v", err)
}
plan, err := buildRestorePlan(context.Background(), cfg, current, fake, RestorePlanOptions{Force: true})
plan, err := buildInventoryRestorePlan(context.Background(), cfg, current, fake, RestorePlanOptions{Force: true})
if err != nil {
t.Fatalf("buildRestorePlan() error = %v", err)
t.Fatalf("buildInventoryRestorePlan() error = %v", err)
}
if plan.ConflictCount != 1 {
t.Fatalf("ConflictCount = %d, want 1", plan.ConflictCount)
}
for _, action := range plan.Actions {
if action.LocalRelativePath == "transcripts/full.json" && action.ConflictKind != RestoreConflictDirectory {
if action.LocalRelativePath == "transcripts/final.trimmed.json" && action.ConflictKind != RestoreConflictDirectory {
t.Fatalf("ConflictKind = %q, want %q", action.ConflictKind, RestoreConflictDirectory)
}
}
@@ -469,7 +426,14 @@ func seedCommittedRestoreSnapshot(t *testing.T, cfg *config.Config, fake *storag
key := artifacts.S3RunRelativeDestinationKey(artifacts.S3RunPrefix(sessionPrefix, runID), "published/"+relative)
fake.SeedObject(storage.FakeObject{Key: key, Data: outputs[relative]})
sourceKey := strings.NewReplacer("/", "_", ".", "_", "-", "_").Replace(relative)
artifactsByKey = append(artifactsByKey, remoteRestoreArtifact(fake, artifacts.RemoteArtifactTypePublishedOutput, artifacts.ConfiguredArtifactSourceID(sourceKey), key))
source := artifacts.ConfiguredArtifactSourceID(sourceKey)
if relative == "transcripts/final.trimmed.json" {
source = artifacts.ArtifactTranscriptFinalTrimmed
}
if relative == "artifacts/session_recap.md" {
source = artifacts.ConfiguredArtifactSourceID("session_recap")
}
artifactsByKey = append(artifactsByKey, remoteRestoreArtifact(fake, artifacts.RemoteArtifactTypePublishedOutput, source, key))
}
commit := artifacts.RemoteCommitManifest{
FormatVersion: artifacts.RemoteCommitFormatVersion,
@@ -499,9 +463,9 @@ func seedCommittedRestoreSnapshot(t *testing.T, cfg *config.Config, fake *storag
t.Fatalf("encode current pointer: %v", err)
}
fake.SeedObject(storage.FakeObject{Key: artifacts.S3CurrentCommitPointerKey(sessionPrefix), Data: pointerData})
current, err := discoverRemoteCurrentState(context.Background(), cfg, fake)
current, err := discoverRemotePublication(context.Background(), cfg, fake)
if err != nil {
t.Fatalf("discoverRemoteCurrentState() error = %v", err)
t.Fatalf("discoverRemotePublication() error = %v", err)
}
return current
}
@@ -555,13 +519,13 @@ func (s *oversizedRestoreStore) Read(ctx context.Context, key string) (storage.O
}
func TestRestoreStopsOversizedResponsesBeforeInstallation(t *testing.T) {
for _, path := range []string{"transcripts/full.json", "audio/alice.flac"} {
for _, path := range []string{"transcripts/final.trimmed.json", "audio/alice.flac"} {
t.Run(path, func(t *testing.T) {
cfg := restorePlanConfig(t)
fake := &storage.FakeBackend{}
const content = "committed data"
current := seedCommittedRestoreSnapshot(t, cfg, fake, "20260519T010203Z-a1b2c3d4", map[string][]byte{path: []byte(content)})
plan, err := buildRestorePlan(context.Background(), cfg, current, fake, RestorePlanOptions{IncludeAudio: true})
plan, err := buildInventoryRestorePlan(context.Background(), cfg, current, fake, RestorePlanOptions{IncludeAudio: true})
if err != nil {
t.Fatal(err)
}

View File

@@ -8,20 +8,16 @@ import (
"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"
)
// RemoteCurrentState captures discovered committed remote published current state for one session.
type RemoteCurrentState struct {
Bucket string
SessionPrefix string
CurrentManifestKey string
RunID string
SessionID string
Campaign string
Manifest *manifest.Manifest
ManifestData []byte
Commit *artifacts.RemoteCommitManifest
Bucket string
SessionPrefix string
RunID string
SessionID string
Campaign string
Commit *artifacts.RemoteCommitManifest
}
func discoverRemotePublication(ctx context.Context, cfg *config.Config, store storage.ObjectStore) (*RemoteCurrentState, error) {
@@ -42,43 +38,3 @@ func discoverRemotePublication(ctx context.Context, cfg *config.Config, store st
}
return &RemoteCurrentState{Bucket: bucket, SessionPrefix: prefix, RunID: current.Commit.RunID, SessionID: current.Commit.SessionID, Campaign: current.Commit.Campaign, Commit: current.Commit}, nil
}
func discoverRemoteCurrentState(ctx context.Context, cfg *config.Config, store storage.ObjectStore) (*RemoteCurrentState, error) {
if cfg == nil || cfg.Pipeline == nil || cfg.Session == nil {
return nil, fmt.Errorf("resolved config with pipeline/session is required")
}
if store == nil {
return nil, fmt.Errorf("remote object store is required")
}
bucket := artifacts.ResolvePublishBucket(cfg, nil)
if strings.TrimSpace(bucket) == "" {
return nil, fmt.Errorf("publish bucket is required")
}
sessionPrefix, err := artifacts.ResolvePublishSessionPrefix(cfg, nil)
if err != nil {
return nil, fmt.Errorf("resolve publish session prefix: %w", err)
}
requestedSession := strings.TrimSpace(cfg.Session.SessionID)
requestedCampaign := strings.TrimSpace(cfg.Session.Campaign)
current, err := artifacts.LoadCurrentState(ctx, store, sessionPrefix, artifacts.CurrentStateValidation{
ExpectedSessionID: requestedSession,
ExpectedCampaign: requestedCampaign,
ValidateRunID: true,
})
if err != nil {
return nil, fmt.Errorf("remote %w", err)
}
return &RemoteCurrentState{
Bucket: bucket,
SessionPrefix: sessionPrefix,
CurrentManifestKey: current.CurrentManifestKey,
RunID: current.RunID,
SessionID: strings.TrimSpace(current.Manifest.SessionID),
Campaign: strings.TrimSpace(current.Manifest.Campaign),
Manifest: current.Manifest,
ManifestData: append([]byte(nil), current.ManifestData...),
Commit: current.Commit,
}, nil
}

View File

@@ -12,9 +12,9 @@ import (
func TestDiscoverRemoteCurrentStateRequiresCommittedPointer(t *testing.T) {
cfg := &config.Config{Pipeline: &config.PipelineConfig{Storage: config.StorageConfig{S3: &config.StorageS3Config{Bucket: "test-bucket", RootPrefix: "dnd"}}}, Session: &config.SessionConfig{Campaign: "sample-campaign", SessionID: "2026-05-03"}}
_, err := discoverRemoteCurrentState(context.Background(), cfg, &storage.FakeBackend{})
_, err := discoverRemotePublication(context.Background(), cfg, &storage.FakeBackend{})
if err == nil {
t.Fatal("discoverRemoteCurrentState() error = nil, want missing committed pointer")
t.Fatal("discoverRemotePublication() error = nil, want missing committed pointer")
}
}

View File

@@ -1,7 +1,6 @@
package app
import (
"bytes"
"context"
"crypto/sha256"
"encoding/hex"
@@ -17,7 +16,6 @@ import (
"gitea.maximumdirect.net/eric/narratio/internal/audio"
"gitea.maximumdirect.net/eric/narratio/internal/config"
"gitea.maximumdirect.net/eric/narratio/internal/fileops"
"gitea.maximumdirect.net/eric/narratio/internal/manifest"
)
// RestoreExecutionResult captures concrete file-install results for one restore execution.
@@ -58,23 +56,11 @@ func executeRestorePlan(
return nil, fmt.Errorf("open session root for restore: %w", err)
}
defer func() { _ = root.Close() }()
manifestActions := make([]RestoreAction, 0, 1)
actions := make([]RestoreAction, 0, len(plan.Actions))
var actions []RestoreAction
for _, action := range plan.Actions {
if action.Kind != RestoreActionDownload {
continue
if action.Kind == RestoreActionDownload {
actions = append(actions, action)
}
if action.LocalRelativePath == config.PathManifestFile {
manifestActions = append(manifestActions, action)
continue
}
actions = append(actions, action)
}
if len(manifestActions) > 1 {
return nil, fmt.Errorf("restore plan includes multiple manifest download actions")
}
if len(manifestActions) == 1 {
actions = append(actions, manifestActions[0])
}
result := &RestoreExecutionResult{}
@@ -127,10 +113,6 @@ func executeRestoreDownloadAction(
}
temporaryPath, err := downloadRestoreTemp(safeLocalPath, func(destination io.Writer) error {
if len(action.VerifiedContent) > 0 {
_, err := io.Copy(destination, bytes.NewReader(action.VerifiedContent))
return err
}
_, err := storage.StreamObject(ctx, store, action.RemoteKey, destination, restoreExpectedSize(action))
return err
})
@@ -142,33 +124,6 @@ func executeRestoreDownloadAction(
return err
}
if isRestoreManifest(action.LocalRelativePath) {
file, err := os.Open(temporaryPath)
if err != nil {
return fmt.Errorf("open restored manifest: %w", err)
}
destinationRoot := sessionRoot
requireCurrentIdentity := action.LocalRelativePath == config.PathManifestFile
if !requireCurrentIdentity {
destinationRoot = filepath.Dir(safeLocalPath)
}
restored, prepareErr := prepareRestoredManifest(ctx, cfg, current, file, destinationRoot, requireCurrentIdentity)
closeErr := file.Close()
if prepareErr != nil {
return prepareErr
}
if closeErr != nil {
return fmt.Errorf("close restored manifest: %w", closeErr)
}
if err := validateRestoreDestinationLeaf(parent, leaf); err != nil {
return err
}
if err := (&manifest.LocalStore{}).Save(ctx, safeLocalPath, restored); err != nil {
return fmt.Errorf("install rebased manifest atomically: %w", err)
}
return nil
}
if err := validateRestoreDestinationLeaf(parent, leaf); err != nil {
return err
}
@@ -247,11 +202,6 @@ func validateRestoreDestinationLeaf(parent *os.Root, leaf string) error {
return nil
}
func isRestoreManifest(relativePath string) bool {
clean := filepath.ToSlash(filepath.Clean(strings.TrimSpace(relativePath)))
return clean == config.PathManifestFile || clean == config.PathPreviousDirSegment+"/"+config.PathManifestFile
}
func downloadRestoreTemp(destination string, download func(io.Writer) error) (string, error) {
if strings.TrimSpace(destination) == "" {
return "", fmt.Errorf("restore destination path is required")

View File

@@ -10,16 +10,14 @@ import (
"path/filepath"
"strings"
"testing"
"time"
"gitea.maximumdirect.net/eric/narratio/internal/adapters/storage"
"gitea.maximumdirect.net/eric/narratio/internal/artifactmodel"
"gitea.maximumdirect.net/eric/narratio/internal/artifacts"
"gitea.maximumdirect.net/eric/narratio/internal/config"
"gitea.maximumdirect.net/eric/narratio/internal/manifest"
)
func TestExecuteRestoreRejectsUnsupportedRemoteState(t *testing.T) {
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()
@@ -27,15 +25,15 @@ func TestExecuteRestoreRejectsUnsupportedRemoteState(t *testing.T) {
fake := &storage.FakeBackend{}
cfg, _, _, _ := seedRestoreCommittedState(t, fake, pipeline, campaign, session)
current := seedCommittedRestoreSnapshot(t, cfg, fake, "20260519T010203Z-a1b2c3d4", nil)
old := fake.Objects[current.CurrentManifestKey].Data
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: current.CurrentManifestKey, Data: data})
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", current.CurrentManifestKey)
current.Commit.Artifacts[i] = remoteRestoreArtifact(fake, artifacts.RemoteArtifactTypeSessionManifest, "session.manifest", artifacts.S3RunSessionManifestKey(current.SessionPrefix, current.RunID))
}
}
commitData, err := artifacts.EncodeRemoteCommitManifest(*current.Commit)
@@ -49,14 +47,16 @@ func TestExecuteRestoreRejectsUnsupportedRemoteState(t *testing.T) {
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 || !strings.Contains(stderr.String(), "schema_version") {
if code != 0 {
t.Fatalf("exit %d, stderr %q", code, stderr.String())
}
path := artifacts.SessionWorkDirForCampaign(root, cfg.Session.Campaign, cfg.Session.SessionID)
if _, err := os.Stat(path); !os.IsNotExist(err) {
t.Fatalf("session root exists after failed discovery: %v", err)
for _, read := range fake.Reads {
if read.Key == artifacts.S3RunSessionManifestKey(current.SessionPrefix, current.RunID) {
t.Fatalf("restore read obsolete snapshot %q", read.Key)
}
}
})
}
@@ -106,7 +106,7 @@ func TestExecuteRestoreRejectsUnsupportedLocalStateEvenWithForce(t *testing.T) {
func TestExecuteRestoreNonDryRunRestoresDurableFiles(t *testing.T) {
workspaceRoot := t.TempDir()
pipelinePath, campaignPath, sessionPath := writeValidConfigFiles(t, workspaceRoot)
pipelinePath, campaignPath, sessionPath := writeValidConfigFilesWithScriptoriumArtifacts(t, workspaceRoot)
fake := &storage.FakeBackend{}
cfg, sessionPrefix, manifestKey, runIDKey := seedRestoreCommittedState(t, fake, pipelinePath, campaignPath, sessionPath)
@@ -115,11 +115,12 @@ func TestExecuteRestoreNonDryRunRestoresDurableFiles(t *testing.T) {
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))
seedCommittedRestoreSnapshot(t, cfg, fake, "20260519T010203Z-a1b2c3d4", map[string][]byte{
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)
@@ -137,7 +138,7 @@ 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, "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"))
@@ -148,8 +149,8 @@ func TestExecuteRestoreNonDryRunRestoresDurableFiles(t *testing.T) {
if report.Status != "succeeded" {
t.Fatalf("report status = %q, want succeeded", report.Status)
}
if report.Execution.Downloaded != 3 {
t.Fatalf("report execution.downloaded = %d, want 3", report.Execution.Downloaded)
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")
@@ -159,86 +160,34 @@ func TestExecuteRestoreNonDryRunRestoresDurableFiles(t *testing.T) {
}
}
func TestExecuteRestoreRoundTripsPublishedExtractionAndManifestMetadata(t *testing.T) {
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, sessionPrefix, manifestKey, runIDKey := seedRestoreCommittedState(t, fake, pipelinePath, campaignPath, sessionPath)
seedRestoreObject(fake, sessionPrefix+"artifacts/encounters.json", []byte(`{"encounters":[]}`))
seedRestoreObject(fake, runIDKey, []byte("20260519T010203Z-a1b2c3d4\n"))
remoteManifest := manifest.New(cfg.Session.SessionID, time.Now().UTC())
remoteManifest.Campaign = cfg.Session.Campaign
remoteManifest.RunID = "20260519T010203Z-a1b2c3d4"
producerRoot := "/prior/workspace/work/sample-campaign/2026-05-03"
remoteManifest.LocalWorkDir = filepath.Join(producerRoot, "runs", remoteManifest.RunID)
rawRelative := "transcripts/raw/alice.json"
rawOutput := manifest.ArtifactRecord{
Kind: "transcript_raw", LocalPath: filepath.Join(producerRoot, filepath.FromSlash(rawRelative)),
ProducerRunID: remoteManifest.RunID, Checksum: strings.Repeat("b", 64),
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())
}
remoteManifest.MarkStageSucceeded("transcribe", time.Now().UTC(), []manifest.ArtifactRecord{rawOutput})
remoteManifest.Stages["transcribe"].TranscribeStateVersion = manifest.TranscribeStateContractVersion
remoteManifest.Stages["transcribe"].TranscribeSpeakers = map[string]manifest.TranscribeSpeakerRecord{
"alice": {
FingerprintVersion: manifest.TranscribeFingerprintContractVersion,
Fingerprint: strings.Repeat("c", 64),
AudioPath: "audio/alice.flac",
AudioSHA256: strings.Repeat("a", 64),
AudioSize: 12,
Output: manifest.ArtifactRecord{
Kind: "transcript_raw", LocalPath: rawRelative,
ProducerRunID: remoteManifest.RunID, Checksum: strings.Repeat("b", 64),
},
OutputSize: 15,
ProducerRunID: remoteManifest.RunID,
},
}
remoteManifest.Stages["extract"] = &manifest.StageRecord{
Name: "extract", Status: manifest.StatusSucceeded,
Outputs: []manifest.ArtifactRecord{{
Kind: "notarius_lane", SourceID: artifacts.ExtractionArtifactSourceID("encounters"),
LocalPath: filepath.Join(producerRoot, "artifacts", "encounters.json"),
Contract: &artifactmodel.ContractMetadata{
MediaType: "application/json", SchemaID: "encounters", SchemaVersion: "1",
},
ExternalProvenance: &artifactmodel.ExternalProvenance{
System: "notarius", RunID: "notarius-run-1", PipelineID: "campaign.extract", ArtifactID: "encounters",
},
}},
}
manifestBody, err := json.Marshal(remoteManifest)
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)
}
seedRestoreObject(fake, manifestKey, manifestBody)
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)
mustReadEquals(t, filepath.Join(sessionRoot, "artifacts", "encounters.json"), `{"encounters":[]}`)
restored, err := (&manifest.LocalStore{}).Load(context.Background(), filepath.Join(sessionRoot, "manifest.json"))
if err != nil {
t.Fatalf("load restored manifest: %v", err)
}
lane := restored.Stages["extract"].Outputs[0]
if lane.Contract == nil || lane.Contract.SchemaID != "encounters" || lane.ExternalProvenance == nil || lane.ExternalProvenance.RunID != "notarius-run-1" {
t.Fatalf("restored extraction metadata = %#v", lane)
}
if want := filepath.Join(sessionRoot, "artifacts", "encounters.json"); lane.LocalPath != want {
t.Fatalf("rebased extraction path = %q, want %q", lane.LocalPath, want)
}
speaker := restored.Stages["transcribe"].TranscribeSpeakers["alice"]
if speaker.AudioPath != "audio/alice.flac" || speaker.Output.LocalPath != rawRelative {
t.Fatalf("restored speaker paths = %#v, want session-relative paths", speaker)
}
if _, err := os.Stat(filepath.Join(sessionRoot, filepath.FromSlash(rawRelative))); !os.IsNotExist(err) {
t.Fatalf("unpublished raw transcript should not be restored; stat err=%v", 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)
}
}
@@ -330,8 +279,8 @@ func TestExecuteRestoreRestoresPreviousCacheWhenPresent(t *testing.T) {
}
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 != 2 {
t.Fatalf("report execution.downloaded = %d, want 2", report.Execution.Downloaded)
if report.Execution.Downloaded != 1 {
t.Fatalf("report execution.downloaded = %d, want 1", report.Execution.Downloaded)
}
}
@@ -390,10 +339,11 @@ func TestExecuteRestoreConflictWithoutForceDoesNotOverwrite(t *testing.T) {
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")})
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", "full.json"), "local-transcript")
mustWriteTestFile(t, filepath.Join(sessionRoot, "transcripts", "final.trimmed.json"), "local-transcript")
executeRestore := restoreCommandExecutor(fake)
@@ -406,7 +356,7 @@ func TestExecuteRestoreConflictWithoutForceDoesNotOverwrite(t *testing.T) {
if !strings.Contains(stderr.String(), "conflicting path") {
t.Fatalf("stderr = %q, want conflict failure", stderr.String())
}
mustReadEquals(t, filepath.Join(sessionRoot, "transcripts", "full.json"), "local-transcript")
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)
@@ -422,10 +372,11 @@ func TestExecuteRestoreForceOverwritesDifferingFile(t *testing.T) {
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")})
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", "full.json"), "local-transcript")
mustWriteTestFile(t, filepath.Join(sessionRoot, "transcripts", "final.trimmed.json"), "local-transcript")
executeRestore := restoreCommandExecutor(fake)
@@ -435,7 +386,7 @@ func TestExecuteRestoreForceOverwritesDifferingFile(t *testing.T) {
if code != 0 {
t.Fatalf("exit code = %d, want 0; stderr=%q", code, stderr.String())
}
mustReadEquals(t, filepath.Join(sessionRoot, "transcripts", "full.json"), "remote-transcript")
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)
@@ -487,11 +438,11 @@ func TestExecuteRestoreLockConflictFailsAndWritesNothing(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
discover := deps.discoverRemoteCurrentState
discover := deps.discoverRemotePublication
if discover == nil {
discover = discoverRemoteCurrentState
discover = discoverRemotePublication
}
deps.discoverRemoteCurrentState = func(ctx context.Context, cfg *config.Config, store storage.ObjectStore) (*RemoteCurrentState, error) {
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.
@@ -509,147 +460,42 @@ func TestExecuteRestoreLockConflictFailsAndWritesNothing(t *testing.T) {
}
}
func TestExecuteRestorePlanInvalidManifestDoesNotCorruptExistingManifest(t *testing.T) {
cfg := restorePlanConfig(t)
store := &storage.FakeBackend{}
current := seedCommittedRestoreSnapshot(t, cfg, store, "20260519T010203Z-a1b2c3d4", map[string][]byte{
"transcripts/full.json": []byte("remote-transcript"),
})
sessionRoot := artifacts.SessionWorkDirForCampaign(cfg.Pipeline.Workspace.Root, cfg.Session.Campaign, cfg.Session.SessionID)
existing := manifest.New(cfg.Session.SessionID, nowUTC())
existing.Campaign = cfg.Session.Campaign
existingPath := filepath.Join(sessionRoot, "manifest.json")
manifestStore := &manifest.LocalStore{}
if err := manifestStore.Save(context.Background(), existingPath, existing); err != nil {
t.Fatalf("save existing local manifest: %v", err)
}
existingData, err := os.ReadFile(existingPath)
if err != nil {
t.Fatalf("read existing local manifest: %v", err)
}
plan, err := buildRestorePlan(context.Background(), cfg, current, store, RestorePlanOptions{Force: true})
if err != nil {
t.Fatalf("buildRestorePlan() error = %v", err)
}
invalidManifest := []byte("{invalid json")
foundManifest := false
manifestKey := ""
manifestGeneration := ""
for index := range plan.Actions {
if plan.Actions[index].LocalRelativePath != config.PathManifestFile {
continue
}
foundManifest = true
plan.Actions[index].VerifiedContent = invalidManifest
plan.Actions[index].SHA256 = restoreCommitSHA256(invalidManifest)
plan.Actions[index].Size = int64(len(invalidManifest))
manifestKey = plan.Actions[index].RemoteKey
manifestGeneration = plan.Actions[index].Generation
}
if !foundManifest {
t.Fatal("restore plan has no manifest action")
}
store.SeedObject(storage.FakeObject{Key: manifestKey, Data: invalidManifest, ETag: manifestGeneration})
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(), "validate manifest decode") {
t.Fatalf("executeRestorePlan() error = %v, want manifest validation failure", err)
}
mustReadEquals(t, filepath.Join(sessionRoot, "transcripts", "full.json"), "remote-transcript")
afterData, err := os.ReadFile(existingPath)
if err != nil {
t.Fatalf("read local manifest after failure: %v", err)
}
if string(afterData) != string(existingData) {
t.Fatalf("local manifest changed after failed restore; before=%q after=%q", string(existingData), string(afterData))
}
}
func TestExecuteRestoreInvalidManifestReportsFailureAndRetainsRecoveryMarker(t *testing.T) {
func TestExecuteRestoreInvalidProductRetainsManifestAndRecoveryMarker(t *testing.T) {
workspaceRoot := t.TempDir()
pipelinePath, campaignPath, sessionPath := writeValidConfigFiles(t, workspaceRoot)
cfg, err := config.LoadWithSessionOptions(pipelinePath, campaignPath, sessionPath, config.SessionLoadOptions{})
if err != nil {
t.Fatalf("LoadWithSessionOptions() error = %v", err)
}
store := &storage.FakeBackend{}
seedCommittedRestoreSnapshot(t, cfg, store, "20260519T010203Z-a1b2c3d4", map[string][]byte{
"transcripts/full.json": []byte("remote-transcript"),
})
sessionRoot := artifacts.SessionWorkDirForCampaign(workspaceRoot, cfg.Session.Campaign, cfg.Session.SessionID)
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
existingPath := filepath.Join(sessionRoot, "manifest.json")
manifestStore := &manifest.LocalStore{}
if err := manifestStore.Save(context.Background(), existingPath, existing); err != nil {
t.Fatalf("save existing local manifest: %v", err)
if err := (&manifest.LocalStore{}).Save(context.Background(), paths.ManifestPath, existing); err != nil {
t.Fatal(err)
}
existingData, err := os.ReadFile(existingPath)
before, err := os.ReadFile(paths.ManifestPath)
if err != nil {
t.Fatalf("read existing local manifest: %v", err)
t.Fatal(err)
}
deps := restoreCommandDependencies(store)
deps.buildRestorePlan = func(ctx context.Context, cfg *config.Config, current *RemoteCurrentState, objectStore storage.ObjectStore, opts RestorePlanOptions) (*RestorePlan, error) {
plan, err := buildRestorePlan(ctx, cfg, current, objectStore, opts)
if err != nil {
return nil, err
}
invalidManifest := []byte("{invalid json")
for index := range plan.Actions {
if plan.Actions[index].LocalRelativePath != config.PathManifestFile {
continue
}
plan.Actions[index].VerifiedContent = invalidManifest
plan.Actions[index].SHA256 = restoreCommitSHA256(invalidManifest)
plan.Actions[index].Size = int64(len(invalidManifest))
store.SeedObject(storage.FakeObject{
Key: plan.Actions[index].RemoteKey,
Data: invalidManifest,
ETag: plan.Actions[index].Generation,
})
return plan, nil
}
t.Fatal("restore plan has no manifest action")
return nil, nil
}
var stdout bytes.Buffer
var stderr bytes.Buffer
code := executeWithDependencies([]string{"session", "restore", cfg.Session.SessionID, "--config", pipelinePath, "--campaign-file", campaignPath, "--session-file", sessionPath, "--force"}, &stdout, &stderr, deps, executePlan)
if code == 0 {
t.Fatal("exit code = 0, want non-zero")
}
if !strings.Contains(stderr.String(), "validate manifest decode") {
t.Fatalf("stderr = %q, want manifest validation failure", stderr.String())
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 restore report=%#v", public)
t.Fatalf("partial report = %#v", public)
}
mustReadEquals(t, filepath.Join(sessionRoot, "transcripts", "full.json"), "remote-transcript")
report := mustReadRestoreReport(t, filepath.Join(sessionRoot, "logs", "restore", "restore.json"))
if report.Status != "failed" {
t.Fatalf("report status = %q, want failed", report.Status)
report := mustReadRestoreReport(t, filepath.Join(paths.Root, "logs", "restore", "restore.json"))
if report.Status != "failed" || report.Error == "" {
t.Fatalf("failure report = %#v", report)
}
if strings.TrimSpace(report.Error) == "" {
t.Fatal("report error is empty, want failure context")
after, err := os.ReadFile(paths.ManifestPath)
if err != nil || !bytes.Equal(before, after) {
t.Fatalf("local manifest changed: %v", err)
}
afterData, err := os.ReadFile(existingPath)
if err != nil {
t.Fatalf("read local manifest after failure: %v", err)
}
if string(afterData) != string(existingData) {
t.Fatalf("local manifest changed after failed restore; before=%q after=%q", string(existingData), string(afterData))
}
markerPath := artifacts.SessionRestoreMarkerPathForCampaign(workspaceRoot, cfg.Session.Campaign, cfg.Session.SessionID)
if _, err := os.Stat(markerPath); err != nil {
t.Fatalf("incomplete restore marker should remain after failed forced restore: %v", err)
if _, err := os.Stat(paths.RestoreMarkerPath); err != nil {
t.Fatalf("recovery marker missing: %v", err)
}
}
@@ -683,11 +529,11 @@ func TestExecuteRestorePlanRejectsAncestorSymlinkCreatedAfterPlanning(t *testing
cfg := restorePlanConfig(t)
current := restorePlanCurrentState(t, cfg)
store := &storage.FakeBackend{}
seedCurrentRestoreObject(t, store, current, current.CurrentManifestKey, []byte(`{"session_id":"2026-05-03"}`))
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 := buildRestorePlan(context.Background(), cfg, current, store, RestorePlanOptions{Force: true})
plan, err := buildInventoryRestorePlan(context.Background(), cfg, current, store, RestorePlanOptions{Force: true})
if err != nil {
t.Fatalf("buildRestorePlan() error = %v", err)
t.Fatalf("buildInventoryRestorePlan() error = %v", err)
}
sessionRoot := artifacts.SessionWorkDirForCampaign(cfg.Pipeline.Workspace.Root, cfg.Session.Campaign, cfg.Session.SessionID)
@@ -746,7 +592,37 @@ func seedRestoreCommittedState(t *testing.T, fake *storage.FakeBackend, pipeline
}
current := seedCommittedRestoreSnapshot(t, cfg, fake, "20260519T010203Z-a1b2c3d4", nil)
return cfg, current.SessionPrefix, current.CurrentManifestKey, artifacts.S3CurrentCommitPointerKey(current.SessionPrefix)
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) {

View File

@@ -19,8 +19,6 @@ func TestInventoryRestoreMapsSourceInsteadOfRemoteDestination(t *testing.T) {
cfg := restorePlanConfig(t)
fake := &storage.FakeBackend{}
current := seedCommittedRestoreSnapshot(t, cfg, fake, "20260519T010203Z-a1b2c3d4", map[string][]byte{"transcripts/renamed.json": []byte(`{"segments":[]}`)})
current.Manifest = nil
current.ManifestData = nil
current.Commit.Artifacts[1].Source = artifacts.ArtifactTranscriptFinalTrimmed
plan, err := buildInventoryRestorePlan(context.Background(), cfg, current, fake, RestorePlanOptions{})
if err != nil {
@@ -39,8 +37,6 @@ func TestInventoryRestoreProjectsSelectedTranscriptProducts(t *testing.T) {
"transcripts/one.json": []byte(`{"segments":[]}`),
"transcripts/two.md": []byte("synthetic transcript"),
})
current.Manifest = nil
current.ManifestData = nil
for i := range current.Commit.Artifacts {
item := &current.Commit.Artifacts[i]
switch filepath.Ext(item.DestinationKey) {
@@ -73,7 +69,6 @@ func TestInventoryRestoreConflictsDoNotContributeCoverage(t *testing.T) {
cfg := restorePlanConfig(t)
fake := &storage.FakeBackend{}
current := seedCommittedRestoreSnapshot(t, cfg, fake, "20260519T010203Z-a1b2c3d4", map[string][]byte{"transcripts/remote.json": []byte(`{"segments":[]}`)})
current.Manifest = nil
current.Commit.Artifacts[1].Source = artifacts.ArtifactTranscriptFinalTrimmed
first, err := buildInventoryRestorePlan(context.Background(), cfg, current, fake, RestorePlanOptions{})
if err != nil || len(first.Actions) != 1 {
@@ -103,7 +98,6 @@ func TestInventoryRestoreUsesCurrentConfiguredProductPath(t *testing.T) {
}}
fake := &storage.FakeBackend{}
current := seedCommittedRestoreSnapshot(t, cfg, fake, "20260519T010203Z-a1b2c3d4", map[string][]byte{"artifacts/remote-name.md": []byte("synthetic recap")})
current.Manifest = nil
current.Commit.Artifacts[1].Source = artifacts.ConfiguredArtifactSourceID("recap")
plan, err := buildInventoryRestorePlan(context.Background(), cfg, current, fake, RestorePlanOptions{})
if err != nil {
@@ -122,7 +116,6 @@ func TestInventoryRestoreRejectsCollidingProductPaths(t *testing.T) {
}}
fake := &storage.FakeBackend{}
current := seedCommittedRestoreSnapshot(t, cfg, fake, "20260519T010203Z-a1b2c3d4", map[string][]byte{"artifacts/a.md": []byte("a"), "artifacts/b.md": []byte("b")})
current.Manifest = nil
current.Commit.Artifacts[1].Source = artifacts.ConfiguredArtifactSourceID("first")
current.Commit.Artifacts[2].Source = artifacts.ConfiguredArtifactSourceID("second")
if _, err := buildInventoryRestorePlan(context.Background(), cfg, current, fake, RestorePlanOptions{}); err == nil {
@@ -149,7 +142,6 @@ func TestInventoryRestoreCandidatePreservesLocalProgress(t *testing.T) {
}
fake := &storage.FakeBackend{}
current := seedCommittedRestoreSnapshot(t, cfg, fake, "20260519T010203Z-a1b2c3d4", map[string][]byte{"transcripts/remote.json": []byte(`{"segments":[]}`)})
current.Manifest = nil
current.Commit.Artifacts[1].Source = artifacts.ArtifactTranscriptFinalTrimmed
plan, err := buildInventoryRestorePlan(context.Background(), cfg, current, fake, RestorePlanOptions{})
if err != nil {

View File

@@ -3,211 +3,90 @@ package app
import (
"context"
"fmt"
"io"
"path"
"path/filepath"
"strings"
"time"
"gitea.maximumdirect.net/eric/narratio/internal/artifactmodel"
"gitea.maximumdirect.net/eric/narratio/internal/artifacts"
"gitea.maximumdirect.net/eric/narratio/internal/config"
"gitea.maximumdirect.net/eric/narratio/internal/manifest"
)
func prepareRestoredManifest(
ctx context.Context,
cfg *config.Config,
current *RemoteCurrentState,
source io.Reader,
destinationRoot string,
requireCurrentIdentity bool,
) (*manifest.Manifest, error) {
manifestStore := &manifest.LocalStore{}
m, err := manifestStore.LoadReader(ctx, source)
if err != nil {
return nil, fmt.Errorf("validate manifest decode: %w", err)
// installInventoryBaseline accepts only products whose installed bytes validate.
// The caller holds the workspace lock and retains the recovery marker until
// this final manifest save succeeds.
func installInventoryBaseline(ctx context.Context, cfg *config.Config, plan *RestorePlan, store manifest.Store) error {
if plan == nil || plan.candidate == nil || plan.baseline == nil || store == nil {
return fmt.Errorf("planned local baseline is required")
}
if requireCurrentIdentity {
if err := validateRestoredManifestIdentity(cfg, current, m); err != nil {
return nil, err
paths := artifacts.NewLocalStore(cfg.Pipeline.Workspace.Root).SessionPathsFor(cfg.Session.Campaign, cfg.Session.SessionID)
for _, action := range plan.Actions {
if action.Kind == RestoreActionConflict {
return fmt.Errorf("conflicting product cannot be accepted")
}
}
if err := rebaseRestoredManifestPaths(cfg, m, destinationRoot); err != nil {
return nil, err
}
return m, nil
}
func validateRestoredManifestIdentity(cfg *config.Config, current *RemoteCurrentState, m *manifest.Manifest) error {
if cfg == nil || cfg.Session == nil {
return fmt.Errorf("resolved session config is required")
}
requestedSession := strings.TrimSpace(cfg.Session.SessionID)
requestedCampaign := strings.TrimSpace(cfg.Session.Campaign)
manifestSession := strings.TrimSpace(m.SessionID)
manifestCampaign := strings.TrimSpace(m.Campaign)
if manifestSession != requestedSession {
return fmt.Errorf("manifest session_id %q does not match requested session_id %q", manifestSession, requestedSession)
}
if manifestCampaign == "" {
return fmt.Errorf("manifest campaign is required")
}
if manifestCampaign != requestedCampaign {
return fmt.Errorf("manifest campaign %q does not match requested campaign %q", manifestCampaign, requestedCampaign)
}
if current != nil {
if expected := strings.TrimSpace(current.SessionID); expected != "" && manifestSession != expected {
return fmt.Errorf("manifest session_id %q does not match discovered session_id %q", manifestSession, expected)
if action.SourceID == "" {
continue
}
if expected := strings.TrimSpace(current.Campaign); expected != "" && manifestCampaign != expected {
return fmt.Errorf("manifest campaign %q does not match discovered campaign %q", manifestCampaign, expected)
record := manifest.SuppliedProduct{Path: action.LocalRelativePath, Checksum: action.SHA256, Size: action.Size}
if err := artifacts.ValidateSuppliedProduct(paths, action.SourceID, action.LocalRelativePath, record); err != nil {
return fmt.Errorf("validate imported product %q: %w", action.SourceID, err)
}
if expected := strings.TrimSpace(current.RunID); expected != "" && strings.TrimSpace(m.RunID) != expected {
return fmt.Errorf("manifest run_id %q does not match discovered run_id %q", strings.TrimSpace(m.RunID), expected)
if priorSourceChecksum(plan.baseline, action.SourceID) == action.SHA256 {
continue
}
}
return nil
}
func rebaseRestoredManifestPaths(cfg *config.Config, m *manifest.Manifest, destinationRoot string) error {
if cfg == nil || cfg.Pipeline == nil || m == nil {
return fmt.Errorf("resolved config and manifest are required")
}
destinationRoot = filepath.Clean(strings.TrimSpace(destinationRoot))
if destinationRoot == "" || destinationRoot == "." {
return fmt.Errorf("restored manifest destination root is required")
}
producerRoot, hasProducerRoot := restoredManifestSessionRoot(m)
rebase := func(field, value string) (string, error) {
return rebaseRestoredLocalReference(field, value, producerRoot, hasProducerRoot, destinationRoot)
}
for i := range m.Inputs {
value, err := rebase("inputs.path", m.Inputs[i].Path)
if err != nil {
producer := importedProductProducer(action.SourceID)
if producer == "" {
return fmt.Errorf("unknown imported product source %q", action.SourceID)
}
at := time.Now().UTC()
if existing := plan.candidate.Stages[producer]; existing != nil && existing.Status == manifest.StatusSucceeded {
plan.candidate.MarkStageStale(producer, at, staleReasonChangedResult)
}
if _, err := invalidateDependentSucceededStagesWithReason(plan.candidate, producer, at, staleReasonChangedResult); err != nil {
return err
}
m.Inputs[i].Path = value
}
for i := range m.Artifacts {
value, err := rebase("artifacts.local_path", m.Artifacts[i].LocalPath)
if err != nil {
return err
return store.Save(ctx, paths.ManifestPath, plan.candidate)
}
func importedProductProducer(source string) string {
if spec, ok := artifactmodel.LookupRuntimeTranscriptArtifact(source); ok {
return spec.ProducerStage
}
if source == artifacts.ArtifactBoundsSession {
return "trim"
}
if artifacts.IsExtractionArtifactSource(source) {
return "extract"
}
if artifacts.IsConfiguredArtifactSource(source) {
return "analyze"
}
return ""
}
func priorSourceChecksum(m *manifest.Manifest, source string) string {
if m == nil {
return ""
}
if m.SuppliedProducts != nil {
if product, ok := m.SuppliedProducts.Products[source]; ok {
return product.Checksum
}
m.Artifacts[i].LocalPath = value
}
for stageName, record := range m.Stages {
for _, record := range m.Stages {
if record == nil {
continue
}
for i := range record.Outputs {
value, err := rebase("stages."+stageName+".outputs.local_path", record.Outputs[i].LocalPath)
if err != nil {
return err
for _, output := range record.Outputs {
if output.SourceID == source {
return output.Checksum
}
record.Outputs[i].LocalPath = value
}
// Logs and generated configuration files are invocation-local diagnostics,
// not restored artifacts. Dropping them prevents a producer-machine path
// 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
for _, artifact := range record.AnalyzeArtifacts {
if artifact.Output != nil && artifact.Output.SourceID == source {
return artifact.Output.Checksum
}
}
}
if runID := strings.TrimSpace(m.RunID); runID != "" {
m.LocalWorkDir = filepath.Join(destinationRoot, config.PathRunsDirSegment, runID)
} else {
m.LocalWorkDir = destinationRoot
}
return nil
}
func restoredManifestSessionRoot(m *manifest.Manifest) (string, bool) {
if m == nil {
return "", false
}
runRoot := portableCleanPath(m.LocalWorkDir)
runID := strings.TrimSpace(m.RunID)
if !portableAbsolutePath(runRoot) || runID == "" || path.Base(runRoot) != runID {
return "", false
}
runsDir := path.Dir(runRoot)
if path.Base(runsDir) != config.PathRunsDirSegment {
return "", false
}
return path.Dir(runsDir), true
}
func rebaseRestoredLocalReference(field, value, producerRoot string, hasProducerRoot bool, destinationRoot string) (string, error) {
value = strings.TrimSpace(value)
if value == "" {
return "", nil
}
if portableDrivePath(value) && !portableAbsolutePath(value) {
return "", fmt.Errorf("%s has an unsafe relative path %q", field, value)
}
if portableAbsolutePath(value) {
if !hasProducerRoot {
return "", fmt.Errorf("%s has an absolute path without a producer session root", field)
}
relative, ok := portableRelativeWithinRoot(producerRoot, value)
if !ok || relative == "" {
return "", fmt.Errorf("%s absolute path is outside the producer session root", field)
}
resolved, err := joinWithinSessionRoot(destinationRoot, relative)
if err != nil {
return "", fmt.Errorf("%s: %w", field, err)
}
return resolved, nil
}
resolved, err := joinWithinSessionRoot(destinationRoot, strings.ReplaceAll(value, "\\", "/"))
if err != nil {
return "", fmt.Errorf("%s has an unsafe relative path: %w", field, err)
}
return resolved, nil
}
func portableRelativeWithinRoot(root, candidate string) (string, bool) {
root = strings.TrimSuffix(portableCleanPath(root), "/")
candidate = portableCleanPath(candidate)
if root == "" || candidate == "" {
return "", false
}
compareRoot, compareCandidate := root, candidate
if portableDrivePath(root) || portableDrivePath(candidate) || strings.HasPrefix(root, "//") || strings.HasPrefix(candidate, "//") {
compareRoot = strings.ToLower(compareRoot)
compareCandidate = strings.ToLower(compareCandidate)
}
if compareCandidate == compareRoot {
return "", true
}
if !strings.HasPrefix(compareCandidate, compareRoot+"/") {
return "", false
}
return strings.TrimPrefix(candidate, root+"/"), true
}
func portableCleanPath(value string) string {
value = strings.ReplaceAll(strings.TrimSpace(value), "\\", "/")
if value == "" {
return ""
}
return path.Clean(value)
}
func portableAbsolutePath(value string) bool {
value = strings.TrimSpace(value)
return strings.HasPrefix(value, "/") || strings.HasPrefix(value, "\\") || (len(value) >= 3 && isASCIIAlpha(value[0]) && value[1] == ':' && (value[2] == '/' || value[2] == '\\'))
}
func portableDrivePath(value string) bool {
value = strings.TrimSpace(value)
return len(value) >= 2 && isASCIIAlpha(value[0]) && value[1] == ':'
}
func isASCIIAlpha(value byte) bool {
return (value >= 'a' && value <= 'z') || (value >= 'A' && value <= 'Z')
return ""
}

View File

@@ -57,7 +57,6 @@ type RestoreAction struct {
Conflict bool
ConflictKind RestoreConflictKind
Reason string
VerifiedContent []byte
}
// A committed identity declares its size even when it is zero. Legacy raw
@@ -78,6 +77,7 @@ type RestorePlan struct {
Satisfied []string
Remaining []string
candidate *manifest.Manifest
baseline *manifest.Manifest
}
// RestorePlanOptions control restore planning scope and classification.
@@ -89,15 +89,7 @@ type RestorePlanOptions struct {
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) {
return buildRestorePlanWithInventory(ctx, cfg, current, store, opts, false)
}
func buildInventoryRestorePlan(ctx context.Context, cfg *config.Config, current *RemoteCurrentState, store storage.ObjectStore, opts RestorePlanOptions) (*RestorePlan, error) {
return buildRestorePlanWithInventory(ctx, cfg, current, store, opts, true)
}
func buildRestorePlanWithInventory(ctx context.Context, cfg *config.Config, current *RemoteCurrentState, store storage.ObjectStore, opts RestorePlanOptions, inventory bool) (*RestorePlan, error) {
if err := ctx.Err(); err != nil {
return nil, err
}
@@ -119,12 +111,7 @@ func buildRestorePlanWithInventory(ctx context.Context, cfg *config.Config, curr
defer func() { _ = sessionRoot.Close() }()
}
var actions []RestoreAction
if inventory {
actions, err = buildInventoryRestoreActions(ctx, cfg, current, store, sessionPaths, sessionRoot, opts)
} else {
actions, err = buildCurrentRestoreActions(ctx, cfg, current, store, sessionPaths, sessionRoot, opts)
}
actions, err := buildInventoryRestoreActions(ctx, cfg, current, store, sessionPaths, sessionRoot, opts)
if err != nil {
return nil, err
}
@@ -150,10 +137,8 @@ func buildRestorePlanWithInventory(ctx context.Context, cfg *config.Config, curr
})
plan := &RestorePlan{Actions: actions}
if inventory {
if err := projectInventoryCoverage(ctx, cfg, plan); err != nil {
return nil, err
}
if err := projectInventoryCoverage(ctx, cfg, plan); err != nil {
return nil, err
}
for _, action := range actions {
switch action.Kind {
@@ -178,14 +163,24 @@ func projectInventoryCoverage(ctx context.Context, cfg *config.Config, plan *Res
if err != nil {
return err
}
if local != nil {
identity := invocationIdentity{Campaign: cfg.Session.Campaign, SessionID: cfg.Session.SessionID}
if err := identity.validateSessionManifest(local); err != nil {
return fmt.Errorf("validate local restore baseline: %w", err)
}
}
plan.candidate, err = cloneManifestForPlan(local, cfg)
if err != nil {
return fmt.Errorf("clone local restore baseline: %w", err)
}
plan.baseline, err = cloneManifestForPlan(local, cfg)
if err != nil {
return fmt.Errorf("clone existing local state: %w", err)
}
covered := make(map[string]bool)
available := make(map[string]bool)
pathsBySource := make(map[string]string)
products := newRestoreProductPaths(nil)
products := newRestoreProductPaths()
paths := artifacts.NewLocalStore(cfg.Pipeline.Workspace.Root).SessionPathsFor(cfg.Session.Campaign, cfg.Session.SessionID)
configured := artifacts.ConfiguredArtifactDefinitions(cfg.ConcreteArtifacts())
extraction := artifacts.ExtractionDefinitionsFromConfig(cfg.Pipeline.Notarius)
@@ -203,10 +198,10 @@ func projectInventoryCoverage(ctx context.Context, cfg *config.Config, plan *Res
catalog.HydrateExtractionArtifacts(paths, local, extraction)
if local != nil && local.SuppliedProducts != nil {
for source, record := range local.SuppliedProducts.Products {
canonical, pathErr := products.relativePath(cfg, nil, paths.Root, source)
pathsBySource[source] = record.Path
canonical, pathErr := products.relativePath(cfg, paths.Root, source)
if pathErr == nil && artifacts.ValidateSuppliedProduct(paths, source, canonical, record) == nil {
available[source] = true
pathsBySource[source] = canonical
}
}
}
@@ -282,33 +277,22 @@ func projectInventoryCoverage(ctx context.Context, cfg *config.Config, plan *Res
return nil
}
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, cfg, current, store, sessionPaths, sessionRoot, opts)
}
// buildInventoryRestoreActions maps product identities through the current
// catalog. Remote destinations identify transfer objects, not local names.
func buildInventoryRestoreActions(ctx context.Context, cfg *config.Config, current *RemoteCurrentState, store storage.ObjectStore, sessionPaths artifacts.SessionPaths, sessionRoot *os.Root, opts RestorePlanOptions) ([]RestoreAction, error) {
if current == nil || current.Commit == nil {
return nil, fmt.Errorf("committed remote inventory is required")
}
products := newRestoreProductPaths(nil)
products := newRestoreProductPaths()
var actions []RestoreAction
for _, artifact := range current.Commit.Artifacts {
var rel string
var include bool
var err error
if artifact.Type == artifacts.RemoteArtifactTypePublishedOutput {
if _, err := artifacts.ParsePublishedOutputObjectKey(current.SessionPrefix, artifact.DestinationKey); err != nil {
return nil, fmt.Errorf("map committed object %q: %w", artifact.DestinationKey, err)
}
if _, classifyErr := artifactpolicy.ClassifySource(artifact.Source); classifyErr == nil {
rel, err = products.relativePath(cfg, nil, sessionPaths.Root, artifact.Source)
rel, err = products.relativePath(cfg, sessionPaths.Root, artifact.Source)
if err == nil {
include = true
} else if !errors.Is(err, errRestoreProductNotFound) {
@@ -349,146 +333,41 @@ func buildInventoryRestoreActions(ctx context.Context, cfg *config.Config, curre
return actions, nil
}
func buildCommittedRestoreActions(
ctx context.Context,
cfg *config.Config,
current *RemoteCurrentState,
store storage.ObjectStore,
sessionPaths artifacts.SessionPaths,
sessionRoot *os.Root,
opts RestorePlanOptions,
) ([]RestoreAction, error) {
if current == nil || current.Commit == nil {
return nil, fmt.Errorf("committed remote current state is required")
}
actions := make([]RestoreAction, 0, len(current.Commit.Artifacts))
products := newRestoreProductPaths(current.Manifest)
for _, artifact := range current.Commit.Artifacts {
rel, include, err := restoreLocalRelativePathForCommittedArtifact(current.SessionPrefix, artifact, opts.IncludeAudio)
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 := products.relativePath(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
}
localPath, err := joinWithinSessionRoot(sessionPaths.Root, rel)
if err != nil {
return nil, fmt.Errorf("map committed object %q: %w", artifact.DestinationKey, err)
}
action, err := classifyRestoreAction(ctx, store, storage.ObjectInfo{
Key: artifact.DestinationKey, Size: artifact.Size, ETag: artifact.Generation,
}, artifact.SHA256, rel, localPath, sessionRoot, opts.Force)
if err != nil {
return nil, fmt.Errorf("classify committed object %q: %w", artifact.DestinationKey, err)
}
if artifact.Type == artifacts.RemoteArtifactTypeSessionManifest && artifact.DestinationKey == current.CurrentManifestKey {
action.VerifiedContent = append([]byte(nil), current.ManifestData...)
}
actions = append(actions, action)
}
return actions, nil
}
// restoreProductPaths resolves sources using the current concrete catalog.
type restoreProductPaths struct{ catalog *artifacts.ArtifactCatalog }
// restoreProductPaths indexes evidence once, retaining duplicates for the
// per-source agreement checks. Unselected paths are not validated here.
type restoreProductPaths struct {
bySource map[string][]string
fallback *artifacts.ArtifactCatalog
}
func newRestoreProductPaths() *restoreProductPaths { return &restoreProductPaths{} }
func newRestoreProductPaths(m *manifest.Manifest) *restoreProductPaths {
index := &restoreProductPaths{bySource: make(map[string][]string)}
if m == nil {
return index
}
for _, record := range m.Stages {
if record == nil {
continue
}
for _, output := range record.Outputs {
index.bySource[output.SourceID] = append(index.bySource[output.SourceID], output.LocalPath)
}
for _, artifact := range record.AnalyzeArtifacts {
if artifact.Output != nil {
output := artifact.Output
index.bySource[output.SourceID] = append(index.bySource[output.SourceID], output.LocalPath)
}
}
}
return index
}
// relativePath takes local product identity from the committed session
// evidence; the remote publication destination is only an object key.
func (index *restoreProductPaths) relativePath(cfg *config.Config, m *manifest.Manifest, destinationRoot, source string) (string, error) {
producerRoot, hasProducerRoot := restoredManifestSessionRoot(m)
var result string
for _, value := range index.bySource[source] {
local, err := rebaseRestoredLocalReference("published output", value, producerRoot, hasProducerRoot, destinationRoot)
if err != nil {
func (index *restoreProductPaths) relativePath(cfg *config.Config, destinationRoot, source string) (string, error) {
if index.catalog == nil {
catalog := artifacts.NewArtifactCatalog()
if err := catalog.RegisterBuiltIns(); err != nil {
return "", err
}
rel, err := filepath.Rel(destinationRoot, local)
if err != nil {
if err := catalog.RegisterConfiguredArtifacts(artifacts.ConfiguredArtifactDefinitions(cfg.ConcreteArtifacts())); 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 err := catalog.RegisterExtractionArtifacts(artifacts.ExtractionDefinitionsFromConfig(cfg.Pipeline.Notarius)); err != nil {
return "", err
}
if result != "" && result != rel {
return "", fmt.Errorf("conflicting product paths for %q", source)
}
result = rel
index.catalog = catalog
}
if result == "" {
if index.fallback == nil {
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
}
index.fallback = catalog
}
if entry, ok := index.fallback.Lookup(source); ok {
relative, err := artifacts.ProductRelativePath(destinationRoot, entry.CanonicalRelPath)
if err != nil {
return "", err
}
result = relative
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)
}
entry, ok := index.catalog.Lookup(source)
if !ok {
return "", fmt.Errorf("%w: %q", errRestoreProductNotFound, source)
}
return result, nil
rel, err := artifacts.ProductRelativePath(destinationRoot, entry.CanonicalRelPath)
if err != nil {
return "", err
}
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("configured product path %q is not flat", rel)
}
return rel, 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,

View File

@@ -18,26 +18,26 @@ func TestRestorePlanDefaultScope(t *testing.T) {
current := restorePlanCurrentState(t, cfg)
store := &storage.FakeBackend{}
seedCurrentRestoreObject(t, store, current, current.CurrentManifestKey, []byte(`{"session_id":"2026-05-03"}`))
seedCurrentRestoreObject(t, store, current, current.SessionPrefix+"transcripts/full.json", []byte(`{"segments":[1]}`))
seedCurrentRestoreObject(t, store, current, artifacts.S3RunSessionManifestKey(current.SessionPrefix, current.RunID), []byte(`{"session_id":"2026-05-03"}`))
seedCurrentRestoreObject(t, store, current, current.SessionPrefix+"transcripts/final.trimmed.json", []byte(`{"segments":[1]}`))
seedCurrentRestoreObject(t, store, current, current.SessionPrefix+"artifacts/session_recap.md", []byte("# recap\n"))
seedCurrentRestoreObject(t, store, current, current.SessionPrefix+"audio/alice.flac", []byte("audio"))
seedRestoreObject(store, current.SessionPrefix+"runs/20260519T010203Z-a1b2/manifest.json", []byte("{}"))
seedRestoreObject(store, current.SessionPrefix+"logs/publish.log", []byte("log"))
seedRestoreObject(store, current.SessionPrefix+"cache/notarius/references/ignored/party.yml", []byte("cache"))
plan, err := buildRestorePlan(context.Background(), cfg, current, store, RestorePlanOptions{})
plan, err := buildInventoryRestorePlan(context.Background(), cfg, current, store, RestorePlanOptions{})
if err != nil {
t.Fatalf("buildRestorePlan() error = %v", err)
t.Fatalf("buildInventoryRestorePlan() error = %v", err)
}
got := actionRelPaths(plan.Actions)
want := []string{"artifacts/session_recap.md", "manifest.json", "transcripts/full.json"}
want := []string{"artifacts/session_recap.md", "transcripts/final.trimmed.json"}
if !slices.Equal(got, want) {
t.Fatalf("action local paths = %#v, want %#v", got, want)
}
if plan.DownloadCount != 3 || plan.SkipSameCount != 0 || plan.ConflictCount != 0 {
t.Fatalf("counts = download=%d skip_same=%d conflict=%d, want 3/0/0", plan.DownloadCount, plan.SkipSameCount, plan.ConflictCount)
if plan.DownloadCount != 2 || plan.SkipSameCount != 0 || plan.ConflictCount != 0 {
t.Fatalf("counts = download=%d skip_same=%d conflict=%d, want 2/0/0", plan.DownloadCount, plan.SkipSameCount, plan.ConflictCount)
}
}
@@ -55,8 +55,9 @@ func TestRestorePlanMapsNestedPublishedDestinationToFlatProduct(t *testing.T) {
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
item.Source = artifacts.ConfiguredArtifactSourceID("session_recap")
}
plan, err := buildRestorePlan(context.Background(), cfg, current, store, RestorePlanOptions{})
plan, err := buildInventoryRestorePlan(context.Background(), cfg, current, store, RestorePlanOptions{})
if err != nil {
t.Fatal(err)
}
@@ -82,15 +83,15 @@ func TestRestorePlanIncludeAudio(t *testing.T) {
current := restorePlanCurrentState(t, cfg)
store := &storage.FakeBackend{}
seedCurrentRestoreObject(t, store, current, current.CurrentManifestKey, []byte(`{"session_id":"2026-05-03"}`))
seedCurrentRestoreObject(t, store, current, artifacts.S3RunSessionManifestKey(current.SessionPrefix, current.RunID), []byte(`{"session_id":"2026-05-03"}`))
seedCurrentRestoreObject(t, store, current, current.SessionPrefix+"audio/alice.flac", []byte("audio"))
plan, err := buildRestorePlan(context.Background(), cfg, current, store, RestorePlanOptions{IncludeAudio: true})
plan, err := buildInventoryRestorePlan(context.Background(), cfg, current, store, RestorePlanOptions{IncludeAudio: true})
if err != nil {
t.Fatalf("buildRestorePlan() error = %v", err)
t.Fatalf("buildInventoryRestorePlan() error = %v", err)
}
got := actionRelPaths(plan.Actions)
want := []string{"audio/alice.flac", "manifest.json"}
want := []string{"audio/alice.flac"}
if !slices.Equal(got, want) {
t.Fatalf("action local paths = %#v, want %#v", got, want)
}
@@ -101,14 +102,14 @@ func TestRestorePlanExistingAudioRequiresVerifiedReplacement(t *testing.T) {
current := restorePlanCurrentState(t, cfg)
store := &storage.FakeBackend{}
seedCurrentRestoreObject(t, store, current, current.CurrentManifestKey, []byte(`{"session_id":"2026-05-03"}`))
seedCurrentRestoreObject(t, store, current, artifacts.S3RunSessionManifestKey(current.SessionPrefix, current.RunID), []byte(`{"session_id":"2026-05-03"}`))
seedCurrentRestoreObject(t, store, current, current.SessionPrefix+"audio/alice.flac", []byte("audio"))
sessionRoot := artifacts.SessionWorkDirForCampaign(cfg.Pipeline.Workspace.Root, cfg.Session.Campaign, cfg.Session.SessionID)
mustWriteTestFile(t, filepath.Join(sessionRoot, "audio", "alice.flac"), "local")
plan, err := buildRestorePlan(context.Background(), cfg, current, store, RestorePlanOptions{IncludeAudio: true})
plan, err := buildInventoryRestorePlan(context.Background(), cfg, current, store, RestorePlanOptions{IncludeAudio: true})
if err != nil {
t.Fatalf("buildRestorePlan() error = %v", err)
t.Fatalf("buildInventoryRestorePlan() error = %v", err)
}
for _, read := range store.Reads {
if read.Key == current.SessionPrefix+"audio/alice.flac" {
@@ -124,9 +125,9 @@ func TestRestorePlanExistingAudioRequiresVerifiedReplacement(t *testing.T) {
t.Fatalf("audio action kind = %q, want %q", audioAction.Kind, RestoreActionConflict)
}
forcedPlan, err := buildRestorePlan(context.Background(), cfg, current, store, RestorePlanOptions{IncludeAudio: true, Force: true})
forcedPlan, err := buildInventoryRestorePlan(context.Background(), cfg, current, store, RestorePlanOptions{IncludeAudio: true, Force: true})
if err != nil {
t.Fatalf("forced buildRestorePlan() error = %v", err)
t.Fatalf("forced buildInventoryRestorePlan() error = %v", err)
}
for _, action := range forcedPlan.Actions {
if action.LocalRelativePath == "audio/alice.flac" && action.Kind != RestoreActionDownload {
@@ -141,16 +142,16 @@ func TestRestorePlanIncludesPreviousCacheByDefault(t *testing.T) {
current := restorePlanCurrentState(t, cfg)
store := &storage.FakeBackend{}
seedCurrentRestoreObject(t, store, current, current.CurrentManifestKey, []byte(`{"session_id":"2026-05-03"}`))
seedCurrentRestoreObject(t, store, current, artifacts.S3RunSessionManifestKey(current.SessionPrefix, current.RunID), []byte(`{"session_id":"2026-05-03"}`))
seedRestorePreviousCurrent(t, store, cfg, "# previous recap\n")
plan, err := buildRestorePlan(context.Background(), cfg, current, store, RestorePlanOptions{})
plan, err := buildInventoryRestorePlan(context.Background(), cfg, current, store, RestorePlanOptions{})
if err != nil {
t.Fatalf("buildRestorePlan() error = %v", err)
t.Fatalf("buildInventoryRestorePlan() error = %v", err)
}
got := actionRelPaths(plan.Actions)
want := []string{"inputs/previous/artifacts/session_recap.md", "manifest.json"}
want := []string{"inputs/previous/artifacts/session_recap.md"}
if !slices.Equal(got, want) {
t.Fatalf("action local paths = %#v, want %#v", got, want)
}
@@ -161,17 +162,17 @@ func TestRestorePlanIgnoresCurrentSessionArchivedPreviousCache(t *testing.T) {
current := restorePlanCurrentState(t, cfg)
store := &storage.FakeBackend{}
seedCurrentRestoreObject(t, store, current, current.CurrentManifestKey, []byte(`{"session_id":"2026-05-03"}`))
seedCurrentRestoreObject(t, store, current, artifacts.S3RunSessionManifestKey(current.SessionPrefix, current.RunID), []byte(`{"session_id":"2026-05-03"}`))
seedRestoreObject(store, current.SessionPrefix+"previous/manifest.json", []byte(`{"session_id":"2026-04-26"}`))
seedRestoreObject(store, current.SessionPrefix+"previous/artifacts/session_recap.md", []byte("# previous recap\n"))
plan, err := buildRestorePlan(context.Background(), cfg, current, store, RestorePlanOptions{})
plan, err := buildInventoryRestorePlan(context.Background(), cfg, current, store, RestorePlanOptions{})
if err != nil {
t.Fatalf("buildRestorePlan() error = %v", err)
t.Fatalf("buildInventoryRestorePlan() error = %v", err)
}
got := actionRelPaths(plan.Actions)
want := []string{"manifest.json"}
want := []string{}
if !slices.Equal(got, want) {
t.Fatalf("action local paths = %#v, want %#v", got, want)
}
@@ -183,16 +184,16 @@ func TestRestorePlanMissingOptionalPreviousCacheSkipsArtifact(t *testing.T) {
current := restorePlanCurrentState(t, cfg)
store := &storage.FakeBackend{}
seedCurrentRestoreObject(t, store, current, current.CurrentManifestKey, []byte(`{"session_id":"2026-05-03"}`))
seedCurrentRestoreObject(t, store, current, artifacts.S3RunSessionManifestKey(current.SessionPrefix, current.RunID), []byte(`{"session_id":"2026-05-03"}`))
seedRestorePreviousCurrentManifestOnly(t, store, cfg)
plan, err := buildRestorePlan(context.Background(), cfg, current, store, RestorePlanOptions{})
plan, err := buildInventoryRestorePlan(context.Background(), cfg, current, store, RestorePlanOptions{})
if err != nil {
t.Fatalf("buildRestorePlan() error = %v", err)
t.Fatalf("buildInventoryRestorePlan() error = %v", err)
}
got := actionRelPaths(plan.Actions)
want := []string{"manifest.json"}
want := []string{}
if !slices.Equal(got, want) {
t.Fatalf("action local paths = %#v, want %#v", got, want)
}
@@ -204,12 +205,12 @@ func TestRestorePlanMissingRequiredPreviousCacheFails(t *testing.T) {
current := restorePlanCurrentState(t, cfg)
store := &storage.FakeBackend{}
seedCurrentRestoreObject(t, store, current, current.CurrentManifestKey, []byte(`{"session_id":"2026-05-03"}`))
seedCurrentRestoreObject(t, store, current, artifacts.S3RunSessionManifestKey(current.SessionPrefix, current.RunID), []byte(`{"session_id":"2026-05-03"}`))
seedRestorePreviousCurrentManifestOnly(t, store, cfg)
_, err := buildRestorePlan(context.Background(), cfg, current, store, RestorePlanOptions{})
_, err := buildInventoryRestorePlan(context.Background(), cfg, current, store, RestorePlanOptions{})
if err == nil || !strings.Contains(err.Error(), "required previous-session artifact") {
t.Fatalf("buildRestorePlan() error = %v, want required previous artifact failure", err)
t.Fatalf("buildInventoryRestorePlan() error = %v, want required previous artifact failure", err)
}
}
@@ -219,22 +220,22 @@ func TestRestorePlanPreviousCacheConflictRequiresForce(t *testing.T) {
current := restorePlanCurrentState(t, cfg)
store := &storage.FakeBackend{}
seedCurrentRestoreObject(t, store, current, current.CurrentManifestKey, []byte(`{"session_id":"2026-05-03"}`))
seedCurrentRestoreObject(t, store, current, artifacts.S3RunSessionManifestKey(current.SessionPrefix, current.RunID), []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, "inputs", "previous", "artifacts", "session_recap.md"), "# local previous recap\n")
plan, err := buildRestorePlan(context.Background(), cfg, current, store, RestorePlanOptions{})
plan, err := buildInventoryRestorePlan(context.Background(), cfg, current, store, RestorePlanOptions{})
if err != nil {
t.Fatalf("buildRestorePlan() error = %v", err)
t.Fatalf("buildInventoryRestorePlan() error = %v", err)
}
if plan.ConflictCount != 1 {
t.Fatalf("ConflictCount = %d, want 1", plan.ConflictCount)
}
plan, err = buildRestorePlan(context.Background(), cfg, current, store, RestorePlanOptions{Force: true})
plan, err = buildInventoryRestorePlan(context.Background(), cfg, current, store, RestorePlanOptions{Force: true})
if err != nil {
t.Fatalf("buildRestorePlan(force) error = %v", err)
t.Fatalf("buildInventoryRestorePlan(force) error = %v", err)
}
if plan.ConflictCount != 0 {
t.Fatalf("force ConflictCount = %d, want 0", plan.ConflictCount)
@@ -246,17 +247,17 @@ func TestRestorePlanClassifiesSameAndConflict(t *testing.T) {
current := restorePlanCurrentState(t, cfg)
store := &storage.FakeBackend{}
seedCurrentRestoreObject(t, store, current, current.CurrentManifestKey, []byte(`{"session_id":"2026-05-03"}`))
seedCurrentRestoreObject(t, store, current, current.SessionPrefix+"transcripts/full.json", []byte(`{"segments":[1]}`))
seedCurrentRestoreObject(t, store, current, artifacts.S3RunSessionManifestKey(current.SessionPrefix, current.RunID), []byte(`{"session_id":"2026-05-03"}`))
seedCurrentRestoreObject(t, store, current, current.SessionPrefix+"transcripts/final.trimmed.json", []byte(`{"segments":[1]}`))
seedCurrentRestoreObject(t, store, current, current.SessionPrefix+"artifacts/session_recap.md", []byte("remote-content\n"))
sessionRoot := artifacts.SessionWorkDirForCampaign(cfg.Pipeline.Workspace.Root, cfg.Session.Campaign, cfg.Session.SessionID)
mustWriteTestFile(t, filepath.Join(sessionRoot, "transcripts", "full.json"), `{"segments":[1]}`)
mustWriteTestFile(t, filepath.Join(sessionRoot, "transcripts", "final.trimmed.json"), `{"segments":[1]}`)
mustWriteTestFile(t, filepath.Join(sessionRoot, "artifacts", "session_recap.md"), "different\n")
plan, err := buildRestorePlan(context.Background(), cfg, current, store, RestorePlanOptions{})
plan, err := buildInventoryRestorePlan(context.Background(), cfg, current, store, RestorePlanOptions{})
if err != nil {
t.Fatalf("buildRestorePlan() error = %v", err)
t.Fatalf("buildInventoryRestorePlan() error = %v", err)
}
if plan.SkipSameCount != 1 {
@@ -270,8 +271,8 @@ func TestRestorePlanClassifiesSameAndConflict(t *testing.T) {
for _, action := range plan.Actions {
actionByRel[action.LocalRelativePath] = action
}
if actionByRel["transcripts/full.json"].Kind != RestoreActionSkipSame {
t.Fatalf("transcripts/full.json kind = %q, want %q", actionByRel["transcripts/full.json"].Kind, RestoreActionSkipSame)
if actionByRel["transcripts/final.trimmed.json"].Kind != RestoreActionSkipSame {
t.Fatalf("transcripts/full.json kind = %q, want %q", actionByRel["transcripts/final.trimmed.json"].Kind, RestoreActionSkipSame)
}
if actionByRel["artifacts/session_recap.md"].Kind != RestoreActionConflict {
t.Fatalf("artifacts/session_recap.md kind = %q, want %q", actionByRel["artifacts/session_recap.md"].Kind, RestoreActionConflict)
@@ -283,15 +284,15 @@ func TestRestorePlanForceTurnsConflictsIntoDownloads(t *testing.T) {
current := restorePlanCurrentState(t, cfg)
store := &storage.FakeBackend{}
seedCurrentRestoreObject(t, store, current, current.CurrentManifestKey, []byte(`{"session_id":"2026-05-03"}`))
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"))
sessionRoot := artifacts.SessionWorkDirForCampaign(cfg.Pipeline.Workspace.Root, cfg.Session.Campaign, cfg.Session.SessionID)
mustWriteTestFile(t, filepath.Join(sessionRoot, "artifacts", "session_recap.md"), "different\n")
plan, err := buildRestorePlan(context.Background(), cfg, current, store, RestorePlanOptions{Force: true})
plan, err := buildInventoryRestorePlan(context.Background(), cfg, current, store, RestorePlanOptions{Force: true})
if err != nil {
t.Fatalf("buildRestorePlan() error = %v", err)
t.Fatalf("buildInventoryRestorePlan() error = %v", err)
}
actionByRel := map[string]RestoreAction{}
@@ -342,15 +343,15 @@ func TestRestorePlanSymlinksRemainNonRegularConflicts(t *testing.T) {
cfg := restorePlanConfig(t)
current := restorePlanCurrentState(t, cfg)
store := &storage.FakeBackend{}
seedCurrentRestoreObject(t, store, current, current.CurrentManifestKey, []byte(`{"session_id":"2026-05-03"}`))
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"))
sessionRoot := artifacts.SessionWorkDirForCampaign(cfg.Pipeline.Workspace.Root, cfg.Session.Campaign, cfg.Session.SessionID)
tt.setup(t, sessionRoot)
for _, options := range []RestorePlanOptions{{DryRun: true}, {Force: true}} {
plan, err := buildRestorePlan(context.Background(), cfg, current, store, options)
plan, err := buildInventoryRestorePlan(context.Background(), cfg, current, store, options)
if err != nil {
t.Fatalf("buildRestorePlan(%+v) error = %v", options, err)
t.Fatalf("buildInventoryRestorePlan(%+v) error = %v", options, err)
}
action := restoreActionForPath(t, plan, "artifacts/session_recap.md")
if action.Kind != RestoreActionConflict || action.ConflictKind != RestoreConflictNonRegular {
@@ -377,10 +378,10 @@ func TestRestorePlanTraversalUnsafeKeyFails(t *testing.T) {
current := restorePlanCurrentState(t, cfg)
store := &storage.FakeBackend{}
seedCurrentRestoreObject(t, store, current, current.CurrentManifestKey, []byte(`{"session_id":"2026-05-03"}`))
seedCurrentRestoreObject(t, store, current, artifacts.S3RunSessionManifestKey(current.SessionPrefix, current.RunID), []byte(`{"session_id":"2026-05-03"}`))
seedCurrentRestoreObject(t, store, current, current.SessionPrefix+"artifacts/../../escape.txt", []byte("bad"))
_, err := buildRestorePlan(context.Background(), cfg, current, store, RestorePlanOptions{})
_, err := buildInventoryRestorePlan(context.Background(), cfg, current, store, RestorePlanOptions{})
if err == nil {
t.Fatal("expected error, got nil")
}
@@ -394,11 +395,16 @@ func seedCurrentRestoreObject(t *testing.T, store *storage.FakeBackend, current
artifactType := artifacts.RemoteArtifactTypePublishedOutput
sourceKey := strings.NewReplacer("/", "_", ".", "_", "-", "_").Replace(strings.TrimPrefix(key, current.SessionPrefix))
source := artifacts.ConfiguredArtifactSourceID(sourceKey)
if strings.HasSuffix(key, "/transcripts/final.trimmed.json") {
source = artifacts.ArtifactTranscriptFinalTrimmed
}
if strings.HasSuffix(key, "/artifacts/session_recap.md") {
source = artifacts.ConfiguredArtifactSourceID("session_recap")
}
destination := key
if key == current.CurrentManifestKey {
if key == artifacts.S3RunSessionManifestKey(current.SessionPrefix, current.RunID) {
artifactType = artifacts.RemoteArtifactTypeSessionManifest
source = "session.manifest"
current.ManifestData = append([]byte(nil), data...)
} else if strings.HasPrefix(key, current.SessionPrefix) {
destination = artifacts.S3RunPrefix(current.SessionPrefix, current.RunID) + "published/" + strings.TrimPrefix(key, current.SessionPrefix)
}
@@ -500,6 +506,7 @@ func restorePlanConfig(t *testing.T) *config.Config {
RootPrefix: "dnd",
}},
},
ArtifactCatalog: &config.ArtifactCatalog{Artifacts: map[string]config.ScriptoriumArtifactConfig{"session_recap": {Enabled: true, OutputPath: "artifacts/session_recap.md"}}},
Session: &config.SessionConfig{
SessionID: "2026-05-03",
Campaign: "sample-campaign",
@@ -533,12 +540,11 @@ func restorePlanCurrentState(t *testing.T, cfg *config.Config) *RemoteCurrentSta
t.Helper()
sessionPrefix := artifacts.S3SessionPrefix("dnd", cfg.Session.Campaign, cfg.Session.SessionID)
return &RemoteCurrentState{
Bucket: "test-bucket",
SessionPrefix: sessionPrefix,
CurrentManifestKey: artifacts.S3RunSessionManifestKey(sessionPrefix, "20260519T010203Z-a1b2c3d4"),
RunID: "20260519T010203Z-a1b2c3d4",
SessionID: cfg.Session.SessionID,
Campaign: cfg.Session.Campaign,
Bucket: "test-bucket",
SessionPrefix: sessionPrefix,
RunID: "20260519T010203Z-a1b2c3d4",
SessionID: cfg.Session.SessionID,
Campaign: cfg.Session.Campaign,
Commit: &artifacts.RemoteCommitManifest{
FormatVersion: artifacts.RemoteCommitFormatVersion,
Campaign: cfg.Session.Campaign,
@@ -553,13 +559,13 @@ func TestRestorePlanIncludesAvailableOptionalPrerequisiteHistory(t *testing.T) {
configureRestorePlanPreviousRequirement(cfg, false)
current := restorePlanCurrentState(t, cfg)
store := &storage.FakeBackend{}
seedCurrentRestoreObject(t, store, current, current.CurrentManifestKey, []byte(`{"session_id":"2026-05-03"}`))
seedCurrentRestoreObject(t, store, current, artifacts.S3RunSessionManifestKey(current.SessionPrefix, current.RunID), []byte(`{"session_id":"2026-05-03"}`))
seedRestorePreviousCurrent(t, store, cfg, "optional history\n")
plan, err := buildRestorePlan(context.Background(), cfg, current, store, RestorePlanOptions{})
plan, err := buildInventoryRestorePlan(context.Background(), cfg, current, store, RestorePlanOptions{})
if err != nil {
t.Fatal(err)
}
want := []string{"inputs/previous/artifacts/session_recap.md", "manifest.json"}
want := []string{"inputs/previous/artifacts/session_recap.md"}
if got := actionRelPaths(plan.Actions); !slices.Equal(got, want) {
t.Fatalf("actions = %v, want %v", got, want)
}

View File

@@ -1,35 +0,0 @@
package app
import (
"testing"
"gitea.maximumdirect.net/eric/narratio/internal/manifest"
)
func TestRestoreProductPathsRetainsAgreementChecks(t *testing.T) {
cfg := restorePlanConfig(t)
const source = "narratio.artifact.session_recap"
for _, conflicting := range []bool{false, true} {
m := &manifest.Manifest{Stages: map[string]*manifest.StageRecord{
"analyze": {Outputs: []manifest.ArtifactRecord{{SourceID: source, LocalPath: "artifacts/session_recap.md"}},
AnalyzeArtifacts: map[string]manifest.AnalyzeArtifactRecord{
"session_recap": {Output: &manifest.ArtifactRecord{SourceID: source, LocalPath: "artifacts/session_recap.md"}},
}},
"other": {Outputs: []manifest.ArtifactRecord{{SourceID: "unselected", LocalPath: "../outside"}}},
}}
if conflicting {
m.Stages["analyze"].AnalyzeArtifacts["session_recap"].Output.LocalPath = "artifacts/other.md"
}
index := newRestoreProductPaths(m)
path, err := index.relativePath(cfg, m, t.TempDir(), source)
if conflicting && err == nil {
t.Fatal("conflicting evidence accepted")
}
if !conflicting && (err != nil || path != "artifacts/session_recap.md") {
t.Fatalf("agreeing evidence: %q, %v", path, err)
}
if _, err := index.relativePath(cfg, m, t.TempDir(), "unselected"); err == nil {
t.Fatal("requested unsafe evidence accepted")
}
}
}

View File

@@ -12,7 +12,6 @@ import (
"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 TestRestoreHoldsTransitionLockBeforePlanning(t *testing.T) {
@@ -21,20 +20,20 @@ func TestRestoreHoldsTransitionLockBeforePlanning(t *testing.T) {
fake := &storage.FakeBackend{}
cfg, _, _, _ := seedRestoreCommittedState(t, fake, pipelinePath, campaignPath, sessionPath)
current, err := discoverRemoteCurrentState(context.Background(), cfg, fake)
current, err := discoverRemotePublication(context.Background(), cfg, fake)
if err != nil {
t.Fatalf("discoverRemoteCurrentState() error = %v", err)
t.Fatalf("discoverRemotePublication() error = %v", err)
}
planning := make(chan struct{})
releasePlanning := make(chan struct{})
deps := restoreCommandDependencies(fake)
deps.discoverRemoteCurrentState = func(context.Context, *config.Config, storage.ObjectStore) (*RemoteCurrentState, error) {
deps.discoverRemotePublication = func(context.Context, *config.Config, storage.ObjectStore) (*RemoteCurrentState, error) {
return current, nil
}
deps.buildRestorePlan = func(context.Context, *config.Config, *RemoteCurrentState, storage.ObjectStore, RestorePlanOptions) (*RestorePlan, error) {
deps.buildInventoryRestorePlan = func(ctx context.Context, cfg *config.Config, current *RemoteCurrentState, store storage.ObjectStore, opts RestorePlanOptions) (*RestorePlan, error) {
close(planning)
<-releasePlanning
return &RestorePlan{}, nil
return buildInventoryRestorePlan(ctx, cfg, current, store, opts)
}
restoreDone := make(chan error, 1)
@@ -73,17 +72,18 @@ func TestExecuteStagesRefusesIncompleteRestore(t *testing.T) {
func TestForcedRestoreRetryClearsIncompleteMarker(t *testing.T) {
workspaceRoot := t.TempDir()
pipelinePath, campaignPath, sessionPath := writeValidConfigFiles(t, workspaceRoot)
pipelinePath, campaignPath, sessionPath := writeValidConfigFilesWithScriptoriumArtifacts(t, workspaceRoot)
fake := &storage.FakeBackend{}
cfg, sessionPrefix, _, _ := seedRestoreCommittedState(t, fake, pipelinePath, campaignPath, sessionPath)
seedCommittedRestoreSnapshot(t, cfg, fake, "20260519T010203Z-a1b2c3d4", map[string][]byte{
current := seedCommittedRestoreSnapshot(t, cfg, fake, "20260519T010203Z-a1b2c3d4", map[string][]byte{
"artifacts/session_recap.md": []byte("remote recap\n"),
"transcripts/full.json": []byte("remote transcript\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", "full.json"), "local transcript\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 {
@@ -114,68 +114,5 @@ func TestForcedRestoreRetryClearsIncompleteMarker(t *testing.T) {
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", "full.json"), "remote transcript\n")
}
func TestRebaseRestoredManifestPathsRejectsUnsafeReferencesAndRebasesPortablePaths(t *testing.T) {
for _, test := range []struct {
name string
workDir string
output string
wantPath string
wantError string
}{
{
name: "unix absolute path within producer root",
workDir: "/producer/work/sample-campaign/2026-05-03/runs/20260519T010203Z-a1b2c3d4",
output: "/producer/work/sample-campaign/2026-05-03/artifacts/recap.md",
wantPath: "artifacts/recap.md",
},
{
name: "windows absolute path within producer root",
workDir: `C:\producer\work\sample-campaign\2026-05-03\runs\20260519T010203Z-a1b2c3d4`,
output: `C:\producer\work\sample-campaign\2026-05-03\artifacts\recap.md`,
wantPath: "artifacts/recap.md",
},
{
name: "absolute path outside producer root",
workDir: "/producer/work/sample-campaign/2026-05-03/runs/20260519T010203Z-a1b2c3d4",
output: "/another-machine/recap.md",
wantError: "outside the producer session root",
},
{
name: "relative traversal",
workDir: "/producer/work/sample-campaign/2026-05-03/runs/20260519T010203Z-a1b2c3d4",
output: "../recap.md",
wantError: "unsafe relative path",
},
} {
t.Run(test.name, func(t *testing.T) {
cfg := testConfig(t)
m := manifest.New(cfg.Session.SessionID, nowUTC())
m.Campaign = cfg.Session.Campaign
m.RunID = "20260519T010203Z-a1b2c3d4"
m.LocalWorkDir = test.workDir
m.Stages["analyze"] = &manifest.StageRecord{Outputs: []manifest.ArtifactRecord{{Kind: "recap", LocalPath: test.output}}}
m.MarkStageFailed("cleanup", nowUTC(), "retry local deletion")
destination := artifacts.SessionWorkDirForCampaign(cfg.Pipeline.Workspace.Root, cfg.Session.Campaign, cfg.Session.SessionID)
err := rebaseRestoredManifestPaths(cfg, m, destination)
if test.wantError != "" {
if err == nil || !strings.Contains(err.Error(), test.wantError) {
t.Fatalf("rebaseRestoredManifestPaths() error = %v, want %q", err, test.wantError)
}
return
}
if err != nil {
t.Fatalf("rebaseRestoredManifestPaths() error = %v", err)
}
if got, want := m.Stages["analyze"].Outputs[0].LocalPath, filepath.Join(destination, test.wantPath); got != want {
t.Fatalf("rebased local path = %q, want %q", got, want)
}
if got := m.Stages["cleanup"].Status; got != manifest.StatusFailed {
t.Fatalf("cleanup status = %q, want preserved failed state", got)
}
})
}
mustReadEquals(t, filepath.Join(sessionRoot, "transcripts", "final.trimmed.json"), `{"segments":[]}`)
}

View File

@@ -41,10 +41,9 @@ func TestExecuteRestoreDryRunPrintsPlanWithoutWriting(t *testing.T) {
deps := restoreCommandDependencies(&storage.FakeBackend{})
deps.discoverRemotePublication = func(context.Context, *config.Config, storage.ObjectStore) (*RemoteCurrentState, error) {
return &RemoteCurrentState{
SessionID: "2026-05-03",
Campaign: "sample-campaign",
RunID: "20260519T010203Z-a1b2c3d4",
ManifestData: restoreManifestJSON(t, "2026-05-03", "sample-campaign"),
SessionID: "2026-05-03",
Campaign: "sample-campaign",
RunID: "20260519T010203Z-a1b2c3d4",
}, nil
}
deps.buildInventoryRestorePlan = func(context.Context, *config.Config, *RemoteCurrentState, storage.ObjectStore, RestorePlanOptions) (*RestorePlan, error) {
@@ -132,7 +131,7 @@ func TestExecuteRestoreFailsWhenStorageBackendNotConfigured(t *testing.T) {
func TestExecuteRestoreDiscoveryErrorSurfaced(t *testing.T) {
deps := restoreCommandDependencies(&storage.FakeBackend{})
deps.discoverRemoteCurrentState = func(context.Context, *config.Config, storage.ObjectStore) (*RemoteCurrentState, error) {
deps.discoverRemotePublication = func(context.Context, *config.Config, storage.ObjectStore) (*RemoteCurrentState, error) {
return nil, fmt.Errorf("remote current commit pointer missing: %q", "dnd/campaigns/sample-campaign/sessions/2026-05-03/current/commit-pointer.json")
}
@@ -189,10 +188,9 @@ func TestExecuteRestoreLoadsSecretsBeforeObjectStoreInit(t *testing.T) {
}}
deps.discoverRemotePublication = func(context.Context, *config.Config, storage.ObjectStore) (*RemoteCurrentState, error) {
return &RemoteCurrentState{
SessionID: "2026-05-03",
Campaign: "sample-campaign",
RunID: "20260519T010203Z-a1b2c3d4",
ManifestData: restoreManifestJSON(t, "2026-05-03", "sample-campaign"),
SessionID: "2026-05-03",
Campaign: "sample-campaign",
RunID: "20260519T010203Z-a1b2c3d4",
}, nil
}
deps.buildInventoryRestorePlan = func(context.Context, *config.Config, *RemoteCurrentState, storage.ObjectStore, RestorePlanOptions) (*RestorePlan, error) {
@@ -234,15 +232,14 @@ func TestExecuteRestoreLoadsSecretsBeforeObjectStoreInit(t *testing.T) {
func TestExecuteRestoreNonDryRunConflictDoesNotWrite(t *testing.T) {
deps := restoreCommandDependencies(&storage.FakeBackend{})
deps.discoverRemoteCurrentState = func(context.Context, *config.Config, storage.ObjectStore) (*RemoteCurrentState, error) {
deps.discoverRemotePublication = func(context.Context, *config.Config, storage.ObjectStore) (*RemoteCurrentState, error) {
return &RemoteCurrentState{
SessionID: "2026-05-03",
Campaign: "sample-campaign",
RunID: "20260519T010203Z-a1b2c3d4",
ManifestData: restoreManifestJSON(t, "2026-05-03", "sample-campaign"),
SessionID: "2026-05-03",
Campaign: "sample-campaign",
RunID: "20260519T010203Z-a1b2c3d4",
}, nil
}
deps.buildRestorePlan = func(context.Context, *config.Config, *RemoteCurrentState, storage.ObjectStore, RestorePlanOptions) (*RestorePlan, error) {
deps.buildInventoryRestorePlan = func(context.Context, *config.Config, *RemoteCurrentState, storage.ObjectStore, RestorePlanOptions) (*RestorePlan, error) {
return &RestorePlan{
Actions: []RestoreAction{
{Kind: RestoreActionConflict, LocalRelativePath: "transcripts/full.json", RemoteKey: "k", Reason: "local file differs"},
@@ -269,10 +266,10 @@ 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", ManifestData: restoreManifestJSON(t, "2026-05-03", "sample-campaign")}, nil
deps.discoverRemotePublication = func(context.Context, *config.Config, storage.ObjectStore) (*RemoteCurrentState, error) {
return &RemoteCurrentState{SessionID: "2026-05-03", Campaign: "sample-campaign", RunID: "20260519T010203Z-a1b2c3d4"}, nil
}
deps.buildRestorePlan = func(context.Context, *config.Config, *RemoteCurrentState, storage.ObjectStore, RestorePlanOptions) (*RestorePlan, error) {
deps.buildInventoryRestorePlan = 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
}
executed := false
@@ -296,16 +293,19 @@ func TestExecuteRestoreForceStillBlocksUnresolvedConflict(t *testing.T) {
func TestExecuteRestoreNonDryRunForceExecutesPlan(t *testing.T) {
deps := restoreCommandDependencies(&storage.FakeBackend{})
deps.discoverRemoteCurrentState = func(context.Context, *config.Config, storage.ObjectStore) (*RemoteCurrentState, error) {
deps.discoverRemotePublication = func(context.Context, *config.Config, storage.ObjectStore) (*RemoteCurrentState, error) {
return &RemoteCurrentState{
SessionID: "2026-05-03",
Campaign: "sample-campaign",
RunID: "20260519T010203Z-a1b2c3d4",
ManifestData: restoreManifestJSON(t, "2026-05-03", "sample-campaign"),
SessionID: "2026-05-03",
Campaign: "sample-campaign",
RunID: "20260519T010203Z-a1b2c3d4",
}, nil
}
deps.buildRestorePlan = func(context.Context, *config.Config, *RemoteCurrentState, storage.ObjectStore, RestorePlanOptions) (*RestorePlan, error) {
return &RestorePlan{
deps.buildInventoryRestorePlan = func(_ context.Context, cfg *config.Config, _ *RemoteCurrentState, _ storage.ObjectStore, _ RestorePlanOptions) (*RestorePlan, error) {
baseline, err := cloneManifestForPlan(nil, cfg)
if err != nil {
return nil, err
}
return &RestorePlan{candidate: baseline, baseline: baseline,
Actions: []RestoreAction{
{Kind: RestoreActionDownload, LocalRelativePath: "transcripts/full.json", RemoteKey: "k", Reason: "local file differs; overwrite with --force"},
},

View File

@@ -69,13 +69,12 @@ func TestRestoreThenForcedAnalyzeUsesRestoredDurableState(t *testing.T) {
if _, err := os.Stat(producerRun); !os.IsNotExist(err) {
t.Fatalf("restore unexpectedly required producer run: %v", err)
}
upstreamCompletedAt := map[string]time.Time{}
for _, stageName := range []string{"prepare", "transcribe", "merge", "polish", "normalize", "trim", "render", "extract"} {
rec := beforeAnalyze.Stages[stageName]
if rec == nil || rec.Status != manifest.StatusSucceeded || rec.CompletedAt == nil {
t.Fatalf("restored manifest stage %q = %#v, want succeeded with completion timestamp", stageName, rec)
}
upstreamCompletedAt[stageName] = *rec.CompletedAt
paths := artifacts.NewLocalStore(workspaceRoot).SessionPathsFor(cfg.Session.Campaign, cfg.Session.SessionID)
if !artifacts.SuppliedTranscriptCoverage(paths, beforeAnalyze.SuppliedProducts)["trim"] {
t.Fatalf("imported transcript is unavailable: %#v", beforeAnalyze.SuppliedProducts)
}
if beforeAnalyze.Stages["trim"] != nil {
t.Fatal("import invented a trim execution")
}
stdout.Reset()
@@ -110,19 +109,8 @@ func TestRestoreThenForcedAnalyzeUsesRestoredDurableState(t *testing.T) {
if err != nil {
t.Fatalf("load session manifest after single-stage analysis: %v", err)
}
for _, stageName := range []string{"prepare", "transcribe", "merge", "polish", "normalize", "trim", "render", "extract"} {
rec := afterAnalyze.Stages[stageName]
if rec == nil || rec.Status != manifest.StatusSucceeded || rec.CompletedAt == nil {
t.Fatalf("post-analyze manifest stage %q = %#v, want succeeded with completion timestamp", stageName, rec)
}
if !rec.CompletedAt.Equal(upstreamCompletedAt[stageName]) {
t.Fatalf(
"stage %q completion changed: before=%s after=%s",
stageName,
upstreamCompletedAt[stageName].Format(time.RFC3339Nano),
rec.CompletedAt.Format(time.RFC3339Nano),
)
}
if !artifacts.SuppliedTranscriptCoverage(paths, afterAnalyze.SuppliedProducts)["trim"] {
t.Fatal("analysis lost the imported transcript baseline")
}
analyzeRec := afterAnalyze.Stages["analyze"]
if analyzeRec == nil || analyzeRec.Status != manifest.StatusSucceeded {
@@ -135,7 +123,7 @@ func TestRestoreThenForcedAnalyzeUsesRestoredDurableState(t *testing.T) {
}
}
func TestRestoreThenAnalyzeUsesRestoredPreviousCacheWithoutObjectStore(t *testing.T) {
func TestRestoreThenAnalyzePreparesPreviousCache(t *testing.T) {
workspaceRoot := t.TempDir()
pipelinePath, campaignPath, sessionPath := writeValidConfigFiles(t, workspaceRoot)
appendRestoreWorkflowScriptoriumConfig(t, pipelinePath, `
@@ -217,7 +205,7 @@ previous_session_id: 2026-04-26
return executePlanWithDependencies(ctx, cfg, plan, opts, invocationDependencies{
newObjectStore: func(context.Context, *config.Config) (storage.ObjectStore, error) {
objectStoreConstructed = true
return nil, context.Canceled
return fakeStore, nil
},
})
}
@@ -241,8 +229,8 @@ previous_session_id: 2026-04-26
if stderr.Len() != 0 {
t.Fatalf("single-stage run stderr = %q, want empty", stderr.String())
}
if objectStoreConstructed {
t.Fatal("single-stage analysis should not construct object store for previous-session input resolution")
if !objectStoreConstructed {
t.Fatal("reference preparation did not resolve previous-session inputs")
}
if len(scriptoriumFake.RunRequests) != 2 {
t.Fatalf("scriptorium run requests = %d, want 2", len(scriptoriumFake.RunRequests))

View File

@@ -150,7 +150,6 @@ func TestPublishedOutputInspectionKeepsCarriedIdentityWithoutPayloadReads(t *tes
fake.SeedObject(storage.FakeObject{Key: key, Data: []byte("carried\n")})
current.Commit.Artifacts[1].Source = "narratio.transcript.final_trimmed"
current.Commit.Artifacts[1].DestinationKey = key
current.Manifest = nil
reads := len(fake.Reads)
outputs, err := inspectPublishedOutputs(context.Background(), cfg, fake, nil, current, []artifacts.RemoteLock{{Source: "narratio.transcript.final_trimmed"}}, true, "current")
if err != nil {
@@ -247,7 +246,6 @@ func TestPublishedOutputInspectionNormalizesAcceptedSources(t *testing.T) {
current := seedCommittedRestoreSnapshot(t, cfg, fake, "20260519T010203Z-a1b2c3d4", map[string][]byte{"transcripts/full.json": []byte("published\n")})
declaration := &current.Commit.Artifacts[1]
declaration.Source = canonical
current.Manifest = nil
outputs, err := inspectPublishedOutputs(context.Background(), cfg, fake, nil, current, []artifacts.RemoteLock{{Source: canonical}}, true, "current")
if err != nil || len(outputs) != 1 {
t.Fatalf("outputs=%#v err=%v", outputs, err)

View File

@@ -7,7 +7,6 @@ import (
"strings"
"gitea.maximumdirect.net/eric/narratio/internal/adapters/storage"
"gitea.maximumdirect.net/eric/narratio/internal/manifest"
)
var (
@@ -27,14 +26,11 @@ func (e *CurrentCommitPointerMissingError) Unwrap() error {
}
type CurrentState struct {
SessionPrefix string
CurrentManifestKey string
CurrentPointerKey string
RunID string
Manifest *manifest.Manifest
ManifestData []byte
Commit *RemoteCommitManifest
Pointer *CurrentCommitPointer
SessionPrefix string
CurrentPointerKey string
RunID string
Commit *RemoteCommitManifest
Pointer *CurrentCommitPointer
}
type CurrentStateValidation struct {
@@ -44,19 +40,6 @@ type CurrentStateValidation struct {
ValidateRunID bool
}
func LoadCurrentState(
ctx context.Context,
store storage.ObjectStore,
sessionPrefix string,
validation CurrentStateValidation,
) (*CurrentState, error) {
state, err := LoadCurrentInventory(ctx, store, sessionPrefix, validation)
if err != nil {
return nil, err
}
return loadCommittedCurrentState(ctx, store, state, validation)
}
// LoadCurrentInventory reads the selected publication identity and declarations
// without fetching an execution snapshot.
func LoadCurrentInventory(
@@ -83,62 +66,3 @@ func LoadCurrentInventory(
}
return loadCommittedInventory(ctx, store, prefix, pointerKey, validation)
}
func ValidateCurrentStateIdentity(state *CurrentState, validation CurrentStateValidation) error {
if state == nil || state.Manifest == nil {
return fmt.Errorf("current state with manifest is required")
}
expectedSessionID := strings.TrimSpace(validation.ExpectedSessionID)
expectedCampaign := strings.TrimSpace(validation.ExpectedCampaign)
expectedRunID := strings.TrimSpace(validation.ExpectedRunID)
manifestSessionID := strings.TrimSpace(state.Manifest.SessionID)
manifestCampaign := strings.TrimSpace(state.Manifest.Campaign)
manifestRunID := strings.TrimSpace(state.Manifest.RunID)
if manifestCampaign != "" {
if err := ValidateSessionIdentity(manifestCampaign, manifestSessionID); err != nil {
return fmt.Errorf("current manifest contains unsafe identities: %w", err)
}
}
if manifestRunID != "" {
if err := ValidateRunIdentity(manifestRunID); err != nil {
return fmt.Errorf("current manifest contains an unsafe run id: %w", err)
}
}
if expectedSessionID != "" && manifestSessionID != expectedSessionID {
return fmt.Errorf(
"current manifest session_id %q does not match expected session_id %q",
manifestSessionID,
expectedSessionID,
)
}
if expectedCampaign != "" {
if manifestCampaign == "" {
return fmt.Errorf("current manifest campaign is required")
}
if manifestCampaign != expectedCampaign {
return fmt.Errorf(
"current manifest campaign %q does not match expected campaign %q",
manifestCampaign,
expectedCampaign,
)
}
}
if expectedRunID == "" && validation.ValidateRunID {
expectedRunID = strings.TrimSpace(state.RunID)
}
if expectedRunID != "" {
if manifestRunID == "" {
return fmt.Errorf("current manifest run_id is required")
}
if manifestRunID != expectedRunID {
return fmt.Errorf(
"current run pointer %q references run %q but current manifest run_id is %q",
state.CurrentPointerKey,
expectedRunID,
manifestRunID,
)
}
}
return nil
}

View File

@@ -1,13 +1,11 @@
package artifacts
import (
"bytes"
"context"
"fmt"
"strings"
"gitea.maximumdirect.net/eric/narratio/internal/adapters/storage"
"gitea.maximumdirect.net/eric/narratio/internal/manifest"
)
const (
@@ -15,8 +13,6 @@ const (
MaxCurrentCommitPointerBytes int64 = 64 << 10
// MaxRemoteCommitManifestBytes bounds an immutable commit manifest.
MaxRemoteCommitManifestBytes int64 = 4 << 20
// MaxRemoteSessionManifestBytes bounds the selected session manifest.
MaxRemoteSessionManifestBytes int64 = 8 << 20
)
func loadCommittedInventory(
@@ -64,32 +60,6 @@ func loadCommittedInventory(
return &CurrentState{SessionPrefix: sessionPrefix, CurrentPointerKey: pointerKey, RunID: commit.RunID, Commit: commit, Pointer: pointer}, nil
}
func loadCommittedCurrentState(ctx context.Context, store storage.ObjectStore, state *CurrentState, validation CurrentStateValidation) (*CurrentState, error) {
sessionManifest, ok := state.Commit.Artifact(RemoteArtifactTypeSessionManifest)
if !ok {
return nil, fmt.Errorf("remote commit must declare exactly one session manifest artifact")
}
manifestData, err := readVerifiedRemoteObject(ctx, store, sessionManifest.DestinationKey, sessionManifest.SHA256, sessionManifest.Size, sessionManifest.Generation, "committed session manifest", MaxRemoteSessionManifestBytes)
if err != nil {
return nil, fmt.Errorf("read committed session manifest %q: %w", sessionManifest.DestinationKey, err)
}
m, err := decodeCommittedManifest(ctx, manifestData)
if err != nil {
return nil, err
}
if err := validateCommitManifestIdentity(state.Commit, m); err != nil {
return nil, err
}
state.CurrentManifestKey = sessionManifest.DestinationKey
state.Manifest = m
state.ManifestData = append([]byte(nil), manifestData...)
if err := ValidateCurrentStateIdentity(state, validation); err != nil {
return nil, err
}
return state, nil
}
func validatePointerCommitIdentity(pointer *CurrentCommitPointer, commit *RemoteCommitManifest) error {
if pointer == nil || commit == nil {
return fmt.Errorf("current commit pointer and remote commit are required")
@@ -100,18 +70,6 @@ func validatePointerCommitIdentity(pointer *CurrentCommitPointer, commit *Remote
return nil
}
func validateCommitManifestIdentity(commit *RemoteCommitManifest, m *manifest.Manifest) error {
if commit == nil || m == nil {
return fmt.Errorf("remote commit and committed session manifest are required")
}
if commit.Campaign != strings.TrimSpace(m.Campaign) ||
commit.SessionID != strings.TrimSpace(m.SessionID) ||
commit.RunID != strings.TrimSpace(m.RunID) {
return fmt.Errorf("selected remote commit identity does not match committed session manifest")
}
return nil
}
func readVerifiedRemoteObject(
ctx context.Context,
store storage.ObjectStore,
@@ -148,11 +106,3 @@ func readCurrentStateControlObject(ctx context.Context, store storage.ObjectStor
}
return info, data, nil
}
func decodeCommittedManifest(ctx context.Context, data []byte) (*manifest.Manifest, error) {
m, err := (&manifest.LocalStore{}).LoadReader(ctx, bytes.NewReader(data))
if err != nil {
return nil, fmt.Errorf("committed session manifest decode failed: %w; republish this session to replace unsupported remote state", err)
}
return m, nil
}

View File

@@ -13,10 +13,10 @@ import (
func TestLoadCurrentStateRequiresCommitPointer(t *testing.T) {
store := &storage.FakeBackend{}
prefix := S3SessionPrefix("dnd", "sample-campaign", "2026-05-03")
_, err := LoadCurrentState(context.Background(), store, prefix, CurrentStateValidation{})
_, err := LoadCurrentInventory(context.Background(), store, prefix, CurrentStateValidation{})
var missing *CurrentCommitPointerMissingError
if !errors.As(err, &missing) || !errors.Is(err, ErrCurrentCommitPointerMissing) {
t.Fatalf("LoadCurrentState() error = %v, want missing commit pointer", err)
t.Fatalf("LoadCurrentInventory() error = %v, want missing commit pointer", err)
}
if missing.Key != S3CurrentCommitPointerKey(prefix) {
t.Fatalf("missing pointer key = %q", missing.Key)

View File

@@ -163,13 +163,13 @@ func TestLoadCurrentStateReadsVerifiedRemoteCommit(t *testing.T) {
commit := testRemoteCommit(t, "20260519T010203Z-a1b2c3d4")
seedRemoteCommit(t, store, testCurrentSessionPrefix(), commit, "commit-generation", "manifest-generation")
state, err := LoadCurrentState(context.Background(), store, testCurrentSessionPrefix(), CurrentStateValidation{
state, err := LoadCurrentInventory(context.Background(), store, testCurrentSessionPrefix(), CurrentStateValidation{
ExpectedCampaign: commit.Campaign,
ExpectedSessionID: commit.SessionID,
ValidateRunID: true,
})
if err != nil {
t.Fatalf("LoadCurrentState() error = %v", err)
t.Fatalf("LoadCurrentInventory() error = %v", err)
}
if state.Commit == nil || state.Pointer == nil {
t.Fatalf("state does not expose selected immutable commit: %#v", state)
@@ -177,11 +177,11 @@ func TestLoadCurrentStateReadsVerifiedRemoteCommit(t *testing.T) {
if state.CurrentPointerKey != S3CurrentCommitPointerKey(testCurrentSessionPrefix()) {
t.Fatalf("CurrentPointerKey = %q", state.CurrentPointerKey)
}
if state.Manifest.RunID != commit.RunID {
t.Fatalf("manifest run ID = %q, want %q", state.Manifest.RunID, commit.RunID)
if state.RunID != commit.RunID {
t.Fatalf("inventory run ID = %q, want %q", state.RunID, commit.RunID)
}
wantReads := []string{state.CurrentPointerKey, state.Pointer.CommitKey, state.CurrentManifestKey}
wantReads := []string{state.CurrentPointerKey, state.Pointer.CommitKey}
if len(store.Reads) != len(wantReads) {
t.Fatalf("committed current-state reads = %#v, want %q", store.Reads, wantReads)
}
@@ -197,21 +197,8 @@ func TestLoadCurrentStateUsesMetadataFromOpenedObjectVersion(t *testing.T) {
commit := testRemoteCommit(t, "20260519T010203Z-a1b2c3d4")
seedRemoteCommit(t, store, testCurrentSessionPrefix(), commit, "commit-generation", "manifest-generation")
if _, err := LoadCurrentState(context.Background(), store, testCurrentSessionPrefix(), CurrentStateValidation{}); err != nil {
t.Fatalf("LoadCurrentState() error = %v, want verification from Read metadata", err)
}
}
func TestDecodeCommittedManifestGuidesRemoteRecovery(t *testing.T) {
_, err := decodeCommittedManifest(context.Background(), []byte(`{"session_id":"2026-05-03"}`))
if err == nil {
t.Fatal("decodeCommittedManifest() error = nil, want unsupported schema failure")
}
if !strings.Contains(err.Error(), "schema_version is required") || !strings.Contains(err.Error(), "republish this session") {
t.Fatalf("decodeCommittedManifest() error = %v, want schema and republish guidance", err)
}
if strings.Contains(err.Error(), "local state") {
t.Fatalf("decodeCommittedManifest() error = %v, must not describe remote state as local", err)
if _, err := LoadCurrentInventory(context.Background(), store, testCurrentSessionPrefix(), CurrentStateValidation{}); err != nil {
t.Fatalf("LoadCurrentInventory() error = %v, want verification from Read metadata", err)
}
}
@@ -241,44 +228,12 @@ func TestLoadCurrentStateRejectsPointerCommitIdentityMismatch(t *testing.T) {
}
store.SeedObject(storage.FakeObject{Key: S3CurrentCommitPointerKey(prefix), Data: pointerData})
_, err = LoadCurrentState(context.Background(), store, prefix, CurrentStateValidation{})
_, err = LoadCurrentInventory(context.Background(), store, prefix, CurrentStateValidation{})
if err == nil || !strings.Contains(err.Error(), "does not match selected remote commit") {
t.Fatalf("error = %v, want pointer/commit identity mismatch", err)
}
}
func TestLoadCurrentStateRejectsCommitManifestIdentityMismatch(t *testing.T) {
store := &storage.FakeBackend{}
commit := testRemoteCommit(t, "20260519T010203Z-a1b2c3d4")
pointer := seedRemoteCommit(t, store, testCurrentSessionPrefix(), commit, "commit-generation", "manifest-generation")
wrongManifest := testManifestJSON(t, "2026-05-03", "wrong-campaign", commit.RunID)
store.SeedObject(storage.FakeObject{
Key: commit.Artifacts[0].DestinationKey,
Data: wrongManifest,
ETag: "manifest-generation",
})
commit.Artifacts[0].SHA256 = remoteObjectSHA256(wrongManifest)
commit.Artifacts[0].Size = int64(len(wrongManifest))
commitData, err := EncodeRemoteCommitManifest(commit)
if err != nil {
t.Fatalf("EncodeRemoteCommitManifest() error = %v", err)
}
store.SeedObject(storage.FakeObject{Key: pointer.CommitKey, Data: commitData, ETag: "commit-generation"})
pointer.CommitSHA256 = remoteObjectSHA256(commitData)
pointer.CommitSize = int64(len(commitData))
pointerData, err := EncodeCurrentCommitPointer(*pointer)
if err != nil {
t.Fatalf("EncodeCurrentCommitPointer() error = %v", err)
}
store.SeedObject(storage.FakeObject{Key: S3CurrentCommitPointerKey(testCurrentSessionPrefix()), Data: pointerData})
_, err = LoadCurrentState(context.Background(), store, testCurrentSessionPrefix(), CurrentStateValidation{})
if err == nil || !strings.Contains(err.Error(), "does not match committed session manifest") {
t.Fatalf("error = %v, want commit/manifest identity mismatch", err)
}
}
func TestLoadCurrentStateRejectsCommitChecksumOrGenerationMismatch(t *testing.T) {
tests := []struct {
name string
@@ -313,7 +268,7 @@ func TestLoadCurrentStateRejectsCommitChecksumOrGenerationMismatch(t *testing.T)
}
store.SeedObject(storage.FakeObject{Key: S3CurrentCommitPointerKey(testCurrentSessionPrefix()), Data: pointerData})
_, err = LoadCurrentState(context.Background(), store, testCurrentSessionPrefix(), CurrentStateValidation{})
_, err = LoadCurrentInventory(context.Background(), store, testCurrentSessionPrefix(), CurrentStateValidation{})
if err == nil || !strings.Contains(err.Error(), test.want) {
t.Fatalf("error = %v, want %q", err, test.want)
}
@@ -435,7 +390,7 @@ func TestCurrentInventoryDoesNotReadExecutionSnapshot(t *testing.T) {
if err != nil {
t.Fatal(err)
}
if current.Manifest != nil || current.Commit.RunID != runID {
if current.Commit.RunID != runID {
t.Fatalf("inventory %+v", current)
}
for _, read := range store.Reads {