Plan imports from published product inventories

This commit is contained in:
2026-12-02 16:02:48 +00:00
parent 4f50a57a38
commit ad8a5df97b
9 changed files with 414 additions and 37 deletions

View File

@@ -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
}

View File

@@ -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 {

View File

@@ -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)
}

View File

@@ -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 := &current.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)
}
}

View File

@@ -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,

View File

@@ -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,

View File

@@ -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",
},
},