From ad8a5df97bf377d84bb297b85de62066e069fb97 Mon Sep 17 00:00:00 2001 From: Eric Rakestraw Date: Wed, 2 Dec 2026 16:02:48 +0000 Subject: [PATCH] Plan imports from published product inventories --- docs/operations.md | 6 +- docs/roadmap/implementation.md | 5 +- internal/app/command_dependencies.go | 4 + internal/app/restore_command.go | 42 ++--- internal/app/restore_command_test.go | 11 +- internal/app/restore_inventory_plan_test.go | 165 +++++++++++++++++ internal/app/restore_plan.go | 192 +++++++++++++++++++- internal/app/restore_report.go | 8 +- internal/app/restore_test.go | 18 +- 9 files changed, 414 insertions(+), 37 deletions(-) create mode 100644 internal/app/restore_inventory_plan_test.go diff --git a/docs/operations.md b/docs/operations.md index 0259f49..66ce047 100644 --- a/docs/operations.md +++ b/docs/operations.md @@ -657,7 +657,11 @@ narratio session restore 2026-04-04 `--dry-run` does not write durable session files. It still reads the selected remote current state and may read object identity/content needed to classify the -plan, so it is not a network-free operation. +plan, so it is not a network-free operation. The inventory-based preview maps +published source identities to current canonical local product paths; the remote +destination name does not choose the local filename. Its projected satisfied and +remaining work describes product coverage assuming planned downloads pass +content verification. It does not certify that an import or pipeline run occurred. Default restore scope: diff --git a/docs/roadmap/implementation.md b/docs/roadmap/implementation.md index cd7a419..a310da3 100644 --- a/docs/roadmap/implementation.md +++ b/docs/roadmap/implementation.md @@ -341,7 +341,10 @@ Validation: `go test ./internal/previouscache ./internal/stage ./internal/artifa ## Stage 10: Plan product imports and synthesized completion -Status: Pending +Status: Complete + +Cutover note: the Stage 9 integration failure remains pending Stage 11; dry-run +uses inventory planning while installation still uses the transitional reader. Read `internal/app/restore_plan.go`, product-path mapping, restore reports, and the source registries/current concrete artifact catalog. diff --git a/internal/app/command_dependencies.go b/internal/app/command_dependencies.go index 50e74f5..b4b342a 100644 --- a/internal/app/command_dependencies.go +++ b/internal/app/command_dependencies.go @@ -26,6 +26,7 @@ type commandDependencies struct { 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) } @@ -62,6 +63,9 @@ func normalizeCommandDependencies(deps commandDependencies) commandDependencies if deps.buildRestorePlan == nil { deps.buildRestorePlan = buildRestorePlan } + if deps.buildInventoryRestorePlan == nil { + deps.buildInventoryRestorePlan = buildInventoryRestorePlan + } if deps.executeRestorePlan == nil { deps.executeRestorePlan = executeRestorePlan } diff --git a/internal/app/restore_command.go b/internal/app/restore_command.go index 469f5d7..246c6f8 100644 --- a/internal/app/restore_command.go +++ b/internal/app/restore_command.go @@ -29,9 +29,12 @@ type restoreCommandReport struct { Downloaded int `json:"downloaded"` Conflicts int `json:"conflicts"` Actions []restoreCommandAction `json:"actions"` + Satisfied []string `json:"projected_satisfied,omitempty"` + Remaining []string `json:"projected_remaining,omitempty"` } type restoreCommandAction struct { Kind string `json:"kind"` + SourceID string `json:"source_id,omitempty"` LocalPath string `json:"local_path"` RemoteKey string `json:"remote_key"` Status string `json:"status"` @@ -45,8 +48,9 @@ func restoreSession(ctx context.Context, cfg *config.Config, opts RestorePlanOpt return nil, resultErr } public = &restoreCommandReport{Campaign: diagnostic.Campaign, SessionID: diagnostic.SessionID, RunID: diagnostic.RunID, DryRun: opts.DryRun, Complete: !opts.DryRun && resultErr == nil && diagnostic.Status == "succeeded", Status: diagnostic.Status, Downloaded: diagnostic.Execution.Downloaded, Conflicts: diagnostic.Plan.Conflicts, Actions: []restoreCommandAction{}} + public.Satisfied, public.Remaining = diagnostic.Satisfied, diagnostic.Remaining for _, action := range diagnostic.Actions { - public.Actions = append(public.Actions, restoreCommandAction{Kind: action.Kind, LocalPath: action.LocalRelativePath, RemoteKey: action.RemoteKey, Status: action.Status, Reason: action.Reason, Error: action.Error}) + public.Actions = append(public.Actions, restoreCommandAction{Kind: action.Kind, SourceID: action.SourceID, LocalPath: action.LocalRelativePath, RemoteKey: action.RemoteKey, Status: action.Status, Reason: action.Reason, Error: action.Error}) } return public, resultErr } @@ -59,6 +63,21 @@ func restoreSessionState(ctx context.Context, cfg *config.Config, opts RestorePl if err != nil { return diagnostic, fmt.Errorf("restore: %w", err) } + if opts.DryRun { + current, err := deps.discoverRemotePublication(ctx, cfg, objectStore) + if err != nil { + return nil, fmt.Errorf("restore: %w", err) + } + plan, err := deps.buildInventoryRestorePlan(ctx, cfg, current, objectStore, opts) + if err != nil { + return nil, fmt.Errorf("restore: %w", err) + } + report, err := newRestoreReport(current, plan, opts) + if err != nil { + return nil, fmt.Errorf("restore: %w", err) + } + return report, nil + } current, err := deps.discoverRemoteCurrentState(ctx, cfg, objectStore) if err != nil { return diagnostic, fmt.Errorf("restore: %w", err) @@ -74,27 +93,6 @@ func restoreSessionState(ctx context.Context, cfg *config.Config, opts RestorePl if _, _, err := loadManifestAtPathIfPresent(ctx, &manifest.LocalStore{}, manifestPath); err != nil { return diagnostic, fmt.Errorf("restore: %w", err) } - if opts.DryRun { - plan, err := deps.buildRestorePlan(ctx, cfg, current, objectStore, RestorePlanOptions{ - IncludeAudio: opts.IncludeAudio, - Force: opts.Force, - DryRun: true, - }) - if err != nil { - return diagnostic, fmt.Errorf("restore: %w", err) - } - report, err := newRestoreReport(current, plan, RestorePlanOptions{ - IncludeAudio: opts.IncludeAudio, - Force: opts.Force, - DryRun: true, - }) - if err != nil { - return diagnostic, fmt.Errorf("restore: %w", err) - } - diagnostic = report - return diagnostic, nil - } - artifactStore := artifacts.NewLocalStore(cfg.Pipeline.Workspace.Root) lock, err := acquireWorkspaceLock(ctx, artifactStore, cfg.Pipeline.Workspace.Root, deps.reporter) if err != nil { diff --git a/internal/app/restore_command_test.go b/internal/app/restore_command_test.go index 6e67ced..73f87cb 100644 --- a/internal/app/restore_command_test.go +++ b/internal/app/restore_command_test.go @@ -33,13 +33,15 @@ func TestRestoreCommandDryRunLeavesMissingWorkspaceAbsent(t *testing.T) { pipeline, campaign, session := writeValidConfigFiles(t, t.TempDir()) fake := &storage.FakeBackend{} cfg, _, _, _ := seedRestoreCommittedState(t, fake, pipeline, campaign, session) - seedCommittedRestoreSnapshot(t, cfg, fake, "20260519T010203Z-a1b2c3d4", map[string][]byte{"artifacts/recap.md": []byte("synthetic recap\n")}) + current := seedCommittedRestoreSnapshot(t, cfg, fake, "20260519T010203Z-a1b2c3d4", map[string][]byte{"audio/speaker.flac": []byte("synthetic audio\n")}) + delete(fake.Objects, current.CurrentManifestKey) + 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) { t.Fatalf("fixture session root=%v", err) } var out, diagnostic bytes.Buffer - code := restoreCommandExecutor(fake)([]string{"session", "restore", cfg.Session.SessionID, "--config", pipeline, "--campaign-file", campaign, "--session-file", session, "--dry-run"}, &out, &diagnostic) + code := restoreCommandExecutor(fake)([]string{"session", "restore", cfg.Session.SessionID, "--config", pipeline, "--campaign-file", campaign, "--session-file", session, "--dry-run", "--include-audio"}, &out, &diagnostic) if code != 0 { t.Fatalf("status=%d diagnostics=%s", code, diagnostic.String()) } @@ -47,6 +49,11 @@ func TestRestoreCommandDryRunLeavesMissingWorkspaceAbsent(t *testing.T) { if !report.DryRun || report.Complete || len(report.Actions) == 0 { t.Fatalf("report=%#v", report) } + for _, read := range fake.Reads { + if read.Key == current.CurrentManifestKey { + t.Fatalf("dry run read obsolete execution snapshot %q", read.Key) + } + } if _, err := os.Stat(paths.Root); !os.IsNotExist(err) { t.Fatalf("dry run created workspace: %v", err) } diff --git a/internal/app/restore_inventory_plan_test.go b/internal/app/restore_inventory_plan_test.go new file mode 100644 index 0000000..50fde63 --- /dev/null +++ b/internal/app/restore_inventory_plan_test.go @@ -0,0 +1,165 @@ +package app + +import ( + "context" + "os" + "path/filepath" + "slices" + "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 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 { + t.Fatal(err) + } + if len(plan.Actions) != 1 || plan.Actions[0].SourceID != artifacts.ArtifactTranscriptFinalTrimmed || plan.Actions[0].LocalRelativePath == "transcripts/renamed.json" { + t.Fatalf("unexpected inventory actions: %#v", plan.Actions) + } +} + +func TestInventoryRestoreProjectsSelectedTranscriptProducts(t *testing.T) { + cfg := restorePlanConfig(t) + cfg.Pipeline.Render = &config.RenderConfig{Variants: []string{"trimmed"}} + fake := &storage.FakeBackend{} + current := seedCommittedRestoreSnapshot(t, cfg, fake, "20260519T010203Z-a1b2c3d4", map[string][]byte{ + "transcripts/one.json": []byte(`{"segments":[]}`), + "transcripts/two.md": []byte("synthetic transcript"), + }) + current.Manifest = nil + current.ManifestData = nil + for i := range current.Commit.Artifacts { + item := ¤t.Commit.Artifacts[i] + switch filepath.Ext(item.DestinationKey) { + case ".json": + if item.Type == artifacts.RemoteArtifactTypePublishedOutput { + item.Source = artifacts.ArtifactTranscriptFinalTrimmed + } + case ".md": + item.Source = artifactmodel.SourceTranscriptFinalTrimmedMarkdown + } + } + plan, err := buildInventoryRestorePlan(context.Background(), cfg, current, fake, RestorePlanOptions{}) + if err != nil { + t.Fatal(err) + } + for _, name := range []string{"transcribe", "merge", "polish", "normalize", "trim", "render"} { + if !slices.Contains(plan.Satisfied, name) { + t.Fatalf("%q absent from projected coverage: %#v", name, plan.Satisfied) + } + } + if plan.candidate == nil || plan.candidate.SuppliedProducts == nil || len(plan.candidate.SuppliedProducts.Products) != 2 { + t.Fatalf("projected baseline does not contain both products: %#v", plan.candidate) + } + if _, err := os.Stat(artifacts.SessionManifestPathForCampaign(cfg.Pipeline.Workspace.Root, cfg.Session.Campaign, cfg.Session.SessionID)); !os.IsNotExist(err) { + t.Fatalf("planning wrote a manifest: %v", err) + } +} + +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 { + t.Fatalf("initial plan = %#v, %v", first, err) + } + local := first.Actions[0].LocalPath + if err := os.MkdirAll(filepath.Dir(local), 0755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(local, []byte("different"), 0600); err != nil { + t.Fatal(err) + } + conflict, err := buildInventoryRestorePlan(context.Background(), cfg, current, fake, RestorePlanOptions{}) + if err != nil || conflict.ConflictCount != 1 || slices.Contains(conflict.Satisfied, "trim") { + t.Fatalf("conflicting plan = %#v, %v", conflict, err) + } + forced, err := buildInventoryRestorePlan(context.Background(), cfg, current, fake, RestorePlanOptions{Force: true}) + if err != nil || forced.DownloadCount != 1 || !slices.Contains(forced.Satisfied, "trim") { + t.Fatalf("forced plan = %#v, %v", forced, err) + } +} + +func TestInventoryRestoreUsesCurrentConfiguredProductPath(t *testing.T) { + cfg := restorePlanConfig(t) + cfg.ArtifactCatalog = &config.ArtifactCatalog{Artifacts: map[string]config.ScriptoriumArtifactConfig{ + "recap": {Enabled: true, OutputPath: "artifacts/current-recap.md"}, + }} + 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 { + t.Fatal(err) + } + if len(plan.Actions) != 1 || plan.Actions[0].LocalRelativePath != "artifacts/current-recap.md" || plan.Actions[0].RemoteKey != current.Commit.Artifacts[1].DestinationKey { + t.Fatalf("configured product plan = %#v", plan.Actions) + } +} + +func TestInventoryRestoreRejectsCollidingProductPaths(t *testing.T) { + cfg := restorePlanConfig(t) + cfg.ArtifactCatalog = &config.ArtifactCatalog{Artifacts: map[string]config.ScriptoriumArtifactConfig{ + "first": {Enabled: true, OutputPath: "artifacts/shared.md"}, + "second": {Enabled: true, OutputPath: "artifacts/shared.md"}, + }} + 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 { + t.Fatal("expected colliding local products to fail planning") + } +} + +func TestInventoryRestoreCandidatePreservesLocalProgress(t *testing.T) { + cfg := restorePlanConfig(t) + paths := artifacts.NewLocalStore(cfg.Pipeline.Workspace.Root).SessionPathsFor(cfg.Session.Campaign, cfg.Session.SessionID) + if err := os.MkdirAll(paths.Root, 0755); err != nil { + t.Fatal(err) + } + local := manifest.New(cfg.Session.SessionID, time.Now().UTC()) + local.Campaign = cfg.Session.Campaign + local.Stages["prepare"] = &manifest.StageRecord{Name: "prepare", Status: manifest.StatusSucceeded} + manifestPath := artifacts.SessionManifestPathForCampaign(cfg.Pipeline.Workspace.Root, cfg.Session.Campaign, cfg.Session.SessionID) + if err := (&manifest.LocalStore{}).Save(context.Background(), manifestPath, local); err != nil { + t.Fatal(err) + } + before, err := os.ReadFile(manifestPath) + if err != nil { + t.Fatal(err) + } + 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 { + t.Fatal(err) + } + if plan.candidate.Stages["prepare"] == nil || plan.candidate.Stages["prepare"].Status != manifest.StatusSucceeded { + t.Fatalf("local progress lost from candidate: %#v", plan.candidate.Stages) + } + after, err := os.ReadFile(manifestPath) + if err != nil || string(before) != string(after) { + t.Fatalf("planning changed local manifest: %v", err) + } +} diff --git a/internal/app/restore_plan.go b/internal/app/restore_plan.go index a16fb8c..59717be 100644 --- a/internal/app/restore_plan.go +++ b/internal/app/restore_plan.go @@ -14,6 +14,7 @@ import ( "strings" "gitea.maximumdirect.net/eric/narratio/internal/adapters/storage" + "gitea.maximumdirect.net/eric/narratio/internal/artifactmodel" "gitea.maximumdirect.net/eric/narratio/internal/artifactpolicy" "gitea.maximumdirect.net/eric/narratio/internal/artifacts" "gitea.maximumdirect.net/eric/narratio/internal/config" @@ -43,6 +44,7 @@ const ( // RestoreAction is one deterministic planner action. type RestoreAction struct { Kind RestoreActionKind + SourceID string RemoteKey string LocalRelativePath string LocalPath string @@ -73,6 +75,9 @@ type RestorePlan struct { DownloadCount int SkipSameCount int ConflictCount int + Satisfied []string + Remaining []string + candidate *manifest.Manifest } // RestorePlanOptions control restore planning scope and classification. @@ -85,6 +90,14 @@ 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 } @@ -106,7 +119,12 @@ func buildRestorePlan(ctx context.Context, cfg *config.Config, current *RemoteCu defer func() { _ = sessionRoot.Close() }() } - actions, err := buildCurrentRestoreActions(ctx, cfg, current, store, sessionPaths, sessionRoot, opts) + 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) + } if err != nil { return nil, err } @@ -132,6 +150,11 @@ func buildRestorePlan(ctx context.Context, cfg *config.Config, current *RemoteCu }) plan := &RestorePlan{Actions: actions} + if inventory { + if err := projectInventoryCoverage(ctx, cfg, plan); err != nil { + return nil, err + } + } for _, action := range actions { switch action.Kind { case RestoreActionDownload: @@ -147,6 +170,118 @@ func buildRestorePlan(ctx context.Context, cfg *config.Config, current *RemoteCu return plan, nil } +// projectInventoryCoverage describes completion if all accepted transfers +// validate successfully. It never treats a declaration as verified content. +func projectInventoryCoverage(ctx context.Context, cfg *config.Config, plan *RestorePlan) error { + manifestPath := artifacts.SessionManifestPathForCampaign(cfg.Pipeline.Workspace.Root, cfg.Session.Campaign, cfg.Session.SessionID) + local, _, err := loadManifestAtPathIfPresent(ctx, &manifest.LocalStore{}, manifestPath) + if err != nil { + return err + } + plan.candidate, err = cloneManifestForPlan(local, cfg) + if err != nil { + return fmt.Errorf("clone local restore baseline: %w", err) + } + covered := make(map[string]bool) + available := make(map[string]bool) + pathsBySource := make(map[string]string) + products := newRestoreProductPaths(nil) + 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) + catalog := artifacts.NewArtifactCatalog() + if err := catalog.RegisterBuiltIns(); err != nil { + return err + } + if err := catalog.RegisterConfiguredArtifacts(configured); err != nil { + return err + } + if err := catalog.RegisterExtractionArtifacts(extraction); err != nil { + return err + } + catalog.HydrateAnalyzeArtifacts(paths, local, configured) + 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) + if pathErr == nil && artifacts.ValidateSuppliedProduct(paths, source, canonical, record) == nil { + available[source] = true + pathsBySource[source] = canonical + } + } + } + for _, action := range plan.Actions { + if action.Kind == RestoreActionDownload { + for source, path := range pathsBySource { + if path == action.LocalRelativePath { + delete(available, source) + delete(plan.candidate.SuppliedProducts.Products, source) + } + } + } + if action.SourceID != "" && action.Kind != RestoreActionConflict { + available[action.SourceID] = true + if action.Kind == RestoreActionSkipSame { + resolved, resolveErr := artifacts.ResolveSessionArtifactWithCatalog(paths, local, action.SourceID, catalog) + if resolveErr == nil && resolved.Checksum == action.SHA256 { + continue + } + } + if plan.candidate.SuppliedProducts == nil { + plan.candidate.SuppliedProducts = &manifest.SuppliedProductCollection{Version: manifest.SuppliedProductVersion, Products: make(map[string]manifest.SuppliedProduct)} + } + plan.candidate.SuppliedProducts.Products[action.SourceID] = manifest.SuppliedProduct{Path: action.LocalRelativePath, Checksum: action.SHA256, Size: action.Size} + } + } + // Recalculate supplied coverage from the projected source set, since a + // replacement can remove an otherwise valid local supplied product. + names := []string{"transcribe", "merge", "polish", "normalize", "trim"} + for source := range available { + for _, name := range names { + if artifacts.SuppliedTranscriptSourceCovers(source, name) { + covered[name] = true + } + } + } + if cfg.Pipeline.Render == nil || cfg.Pipeline.Render.Enabled == nil || *cfg.Pipeline.Render.Enabled { + selection := []string{"normalized", "trimmed"} + if cfg.Pipeline.Render != nil { + selection = cfg.Pipeline.Render.Variants + } + variants, err := artifactmodel.SelectRenderVariants(selection) + if err != nil { + return err + } + complete := true + for _, variant := range variants { + complete = complete && available[variant.OutputSource] + } + covered["render"] = covered["render"] || complete + } + if cfg.Pipeline.Notarius != nil && cfg.Pipeline.Notarius.Enabled { + definitions := artifacts.ExtractionDefinitionsFromConfig(cfg.Pipeline.Notarius) + complete := len(definitions) > 0 + for key := range definitions { + complete = complete && available[artifacts.ExtractionArtifactSourceID(key)] + } + covered["extract"] = covered["extract"] || complete + } + if cfg.Pipeline.Render == nil || cfg.Pipeline.Render.Enabled == nil || *cfg.Pipeline.Render.Enabled { + names = append(names, "render") + } + if cfg.Pipeline.Notarius != nil && cfg.Pipeline.Notarius.Enabled { + names = append(names, "extract") + } + for _, name := range names { + if covered[name] { + plan.Satisfied = append(plan.Satisfied, name) + } else { + plan.Remaining = append(plan.Remaining, name) + } + } + return nil +} + func buildCurrentRestoreActions( ctx context.Context, cfg *config.Config, @@ -159,6 +294,61 @@ func buildCurrentRestoreActions( 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) + var actions []RestoreAction + for _, artifact := range current.Commit.Artifacts { + var rel string + var include bool + var err error + if artifact.Type == artifacts.RemoteArtifactTypePublishedOutput { + if _, classifyErr := artifactpolicy.ClassifySource(artifact.Source); classifyErr == nil { + rel, err = products.relativePath(cfg, nil, sessionPaths.Root, artifact.Source) + if err == nil { + include = true + } else if !errors.Is(err, errRestoreProductNotFound) { + return nil, fmt.Errorf("map committed source %q: %w", artifact.Source, err) + } + } + if !include && opts.IncludeAudio { + var candidate string + candidate, include, err = restoreLocalRelativePathForCommittedArtifact(current.SessionPrefix, artifact, true) + if include && restoreRelativePathIsAudio(candidate) { + rel = candidate + } else { + include = false + } + } + } else if artifact.Type == artifacts.RemoteArtifactTypeRunFile { + rel, include, err = restoreLocalRelativePathForCommittedArtifact(current.SessionPrefix, artifact, opts.IncludeAudio) + } + if err != nil && !errors.Is(err, errRestoreProductNotFound) { + return nil, fmt.Errorf("map committed object %q: %w", artifact.DestinationKey, err) + } + if !include { + continue + } + localPath, err := joinWithinSessionRoot(sessionPaths.Root, rel) + if err != nil { + return nil, 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.RemoteArtifactTypePublishedOutput && !restoreRelativePathIsAudio(rel) { + action.SourceID = artifact.Source + } + actions = append(actions, action) + } + return actions, nil +} + func buildCommittedRestoreActions( ctx context.Context, cfg *config.Config, diff --git a/internal/app/restore_report.go b/internal/app/restore_report.go index 02c0313..fd6bf88 100644 --- a/internal/app/restore_report.go +++ b/internal/app/restore_report.go @@ -26,6 +26,8 @@ type RestoreReport struct { Plan RestorePlanSummary `json:"plan"` Execution RestoreExecutionStats `json:"execution"` Actions []RestoreReportAction `json:"actions"` + Satisfied []string `json:"projected_satisfied,omitempty"` + Remaining []string `json:"projected_remaining,omitempty"` reportPathRel string } @@ -43,6 +45,7 @@ type RestoreExecutionStats struct { type RestoreReportAction struct { Kind string `json:"kind"` + SourceID string `json:"source_id,omitempty"` LocalRelativePath string `json:"local_relative_path"` RemoteKey string `json:"remote_key"` Reason string `json:"reason,omitempty"` @@ -72,11 +75,14 @@ func newRestoreReport(current *RemoteCurrentState, plan *RestorePlan, opts Resto SkipSame: plan.SkipSameCount, Conflicts: plan.ConflictCount, }, - Actions: make([]RestoreReportAction, 0, len(plan.Actions)), + Actions: make([]RestoreReportAction, 0, len(plan.Actions)), + Satisfied: append([]string(nil), plan.Satisfied...), + Remaining: append([]string(nil), plan.Remaining...), } for _, action := range plan.Actions { r.Actions = append(r.Actions, RestoreReportAction{ Kind: string(action.Kind), + SourceID: action.SourceID, LocalRelativePath: action.LocalRelativePath, RemoteKey: action.RemoteKey, Reason: action.Reason, diff --git a/internal/app/restore_test.go b/internal/app/restore_test.go index ffc1162..3a05d4e 100644 --- a/internal/app/restore_test.go +++ b/internal/app/restore_test.go @@ -39,7 +39,7 @@ func TestExecuteRestoreHelp(t *testing.T) { func TestExecuteRestoreDryRunPrintsPlanWithoutWriting(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", @@ -47,13 +47,13 @@ func TestExecuteRestoreDryRunPrintsPlanWithoutWriting(t *testing.T) { ManifestData: restoreManifestJSON(t, "2026-05-03", "sample-campaign"), }, 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: RestoreActionDownload, - LocalRelativePath: "manifest.json", - RemoteKey: "dnd/campaigns/sample-campaign/sessions/2026-05-03/runs/20260519T010203Z-a1b2c3d4/session-manifest.json", + LocalRelativePath: "transcripts/final.json", + RemoteKey: "dnd/campaigns/sample-campaign/sessions/2026-05-03/runs/20260519T010203Z-a1b2c3d4/published/transcripts/final.json", Reason: "local file missing", }, }, @@ -88,7 +88,7 @@ func TestExecuteRestoreDryRunPrintsPlanWithoutWriting(t *testing.T) { t.Fatalf("stderr = %q, want empty", stderr.String()) } public := decodeRestoreCommandReport(t, stdout.Bytes()) - if !public.DryRun || public.Complete || len(public.Actions) != 1 || public.Actions[0].LocalPath != "manifest.json" { + if !public.DryRun || public.Complete || len(public.Actions) != 1 || public.Actions[0].LocalPath != "transcripts/final.json" { t.Fatalf("dry-run report=%#v", public) } @@ -187,7 +187,7 @@ func TestExecuteRestoreLoadsSecretsBeforeObjectStoreInit(t *testing.T) { } return &storage.FakeBackend{}, nil }} - 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", @@ -195,13 +195,13 @@ func TestExecuteRestoreLoadsSecretsBeforeObjectStoreInit(t *testing.T) { ManifestData: restoreManifestJSON(t, "2026-05-03", "sample-campaign"), }, 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: RestoreActionDownload, - LocalRelativePath: "manifest.json", - RemoteKey: "dnd/campaigns/sample-campaign/sessions/2026-05-03/runs/20260519T010203Z-a1b2c3d4/session-manifest.json", + LocalRelativePath: "transcripts/final.json", + RemoteKey: "dnd/campaigns/sample-campaign/sessions/2026-05-03/runs/20260519T010203Z-a1b2c3d4/published/transcripts/final.json", Reason: "local file missing", }, },