package app import ( "context" "crypto/sha256" "encoding/hex" "errors" "fmt" "io" "os" "path" "path/filepath" "sort" "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" "gitea.maximumdirect.net/eric/narratio/internal/manifest" "gitea.maximumdirect.net/eric/narratio/internal/pathsafe" "gitea.maximumdirect.net/eric/narratio/internal/previouscache" ) // RestoreActionKind identifies one restore planner action. type RestoreActionKind string const ( RestoreActionDownload RestoreActionKind = "download" RestoreActionSkipSame RestoreActionKind = "skip_same" RestoreActionConflict RestoreActionKind = "conflict" ) // RestoreConflictKind identifies why a local target cannot be restored safely. type RestoreConflictKind string const ( RestoreConflictContentMismatch RestoreConflictKind = "content_mismatch" RestoreConflictDirectory RestoreConflictKind = "directory" RestoreConflictNonRegular RestoreConflictKind = "non_regular" ) // RestoreAction is one deterministic planner action. type RestoreAction struct { Kind RestoreActionKind SourceID string RemoteKey string LocalRelativePath string LocalPath string SHA256 string Generation string Size int64 ETag string ExistsLocal bool SameLocal bool Conflict bool ConflictKind RestoreConflictKind Reason string } // A committed identity declares its size even when it is zero. Legacy raw // audio listings use zero for a missing size and retain unknown-size handling. func restoreExpectedSize(action RestoreAction) *int64 { if action.Size > 0 || action.SHA256 != "" || action.Generation != "" { return &action.Size } return nil } // RestorePlan is the deterministic output of restore planning. type RestorePlan struct { Actions []RestoreAction DownloadCount int SkipSameCount int ConflictCount int Satisfied []string Remaining []string candidate *manifest.Manifest baseline *manifest.Manifest } // RestorePlanOptions control restore planning scope and classification. type RestorePlanOptions struct { IncludeAudio bool Force bool DryRun bool } var errRestoreProductNotFound = errors.New("restore product source is unavailable") func buildInventoryRestorePlan(ctx context.Context, cfg *config.Config, current *RemoteCurrentState, store storage.ObjectStore, opts RestorePlanOptions) (*RestorePlan, error) { if err := ctx.Err(); err != nil { return nil, err } if cfg == nil || cfg.Pipeline == nil || cfg.Session == nil { return nil, fmt.Errorf("resolved config with pipeline/session is required") } if current == nil { return nil, fmt.Errorf("remote current state is required") } if store == nil { return nil, fmt.Errorf("remote object store is required") } sessionPaths := artifacts.NewLocalStore(cfg.Pipeline.Workspace.Root).SessionPathsFor(cfg.Session.Campaign, cfg.Session.SessionID) sessionRoot, err := os.OpenRoot(sessionPaths.Root) if err != nil && !errors.Is(err, os.ErrNotExist) { return nil, fmt.Errorf("open session root for restore planning: %w", err) } if sessionRoot != nil { defer func() { _ = sessionRoot.Close() }() } actions, err := buildInventoryRestoreActions(ctx, cfg, current, store, sessionPaths, sessionRoot, opts) if err != nil { return nil, err } previousActions, err := buildPreviousCacheRestoreActions(ctx, cfg, sessionPaths, sessionRoot, store, opts.Force) if err != nil { return nil, err } actions = append(actions, previousActions...) seenPaths := make(map[string]string, len(actions)) for _, action := range actions { if prior, exists := seenPaths[action.LocalRelativePath]; exists { return nil, fmt.Errorf("multiple committed objects target %q (%q and %q)", action.LocalRelativePath, prior, action.RemoteKey) } seenPaths[action.LocalRelativePath] = action.RemoteKey } sort.Slice(actions, func(i, j int) bool { if actions[i].LocalRelativePath == actions[j].LocalRelativePath { return actions[i].RemoteKey < actions[j].RemoteKey } return actions[i].LocalRelativePath < actions[j].LocalRelativePath }) plan := &RestorePlan{Actions: actions} if err := projectInventoryCoverage(ctx, cfg, plan, store); err != nil { return nil, err } for _, action := range actions { switch action.Kind { case RestoreActionDownload: plan.DownloadCount++ case RestoreActionSkipSame: plan.SkipSameCount++ case RestoreActionConflict: plan.ConflictCount++ } } _ = opts.DryRun 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, store storage.ObjectStore) 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 } 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() 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 { 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 } } } 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 } // Reuse the normal read-only stage projection for preserved local work. // Proposed downloads have not been installed, so the supplied coverage above // remains conditional and local validation may conservatively schedule work. if local != nil { model, cloneErr := cloneManifestForPlan(plan.candidate, cfg) if cloneErr != nil { return cloneErr } if err := invalidateImportedDependencies(model, plan.baseline, plan.Actions); err != nil { return err } effective, effectiveErr := resolveEffectiveArtifacts(cfg, nil) selection, selectionErr := BuildBoundedPlan("", "") if effectiveErr == nil && selectionErr == nil { projection, _ := projectSelectedWork(ctx, cfg, selection, false, nil, effective, artifacts.NewLocalStore(cfg.Pipeline.Workspace.Root), store, model) if err := ctx.Err(); err != nil { return err } if projection != nil { for _, item := range projection.Stages { if item.Decision.action == stageActionSkip && recordedStageStatus(local, item.Name) == manifest.StatusSucceeded { covered[item.Name] = true } } } } } names = []string{"prepare", "transcribe", "merge", "polish", "normalize", "trim", "render", "extract", "analyze", "publish", "notify", "cleanup"} for _, name := range names { if covered[name] { plan.Satisfied = append(plan.Satisfied, name) } else { plan.Remaining = append(plan.Remaining, name) } } return nil } 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() 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, 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 } // restoreProductPaths resolves sources using the current concrete catalog. type restoreProductPaths struct{ catalog *artifacts.ArtifactCatalog } func newRestoreProductPaths() *restoreProductPaths { return &restoreProductPaths{} } 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 } 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.catalog = catalog } entry, ok := index.catalog.Lookup(source) if !ok { return "", fmt.Errorf("%w: %q", errRestoreProductNotFound, source) } 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.RemoteArtifactTypeRunFile { prepared := map[string]bool{ "run:prepare/inputs/session.yml": true, "run:prepare/inputs/campaign.yml": true, "run:prepare/inputs/party.yml": true, "run:prepare/inputs/players.yml": true, "run:prepare/inputs/speakers.yml": true, "run:prepare/inputs/autocorrect.yml": true, "run:prepare/inputs/pipeline.resolved.yml": true, } for _, descriptor := range artifactpolicy.GlossaryInputSources() { prepared["run:prepare/inputs/"+descriptor.Filename] = true } combined, _ := artifactpolicy.DescribePreparedInputSource(artifactpolicy.SourceInputGlossaryCombined) prepared["run:prepare/inputs/"+combined.Filename] = true if prepared[artifact.Source] { identity, err := artifacts.ParseImmutableRunObjectKey(sessionPrefix, artifact.DestinationKey) if err != nil || "run:"+identity.RelativePath != artifact.Source { return "", false, fmt.Errorf("prepared input does not match its run object key") } return strings.TrimPrefix(identity.RelativePath, "prepare/"), true, nil } } if artifact.Type != artifacts.RemoteArtifactTypePublishedOutput { return "", false, nil } identity, err := artifacts.ParsePublishedOutputObjectKey(sessionPrefix, artifact.DestinationKey) if err != nil { return "", false, err } cleanRel, err := pathsafe.NormalizeRelativeDestination(identity.Destination) if err != nil { return "", false, fmt.Errorf("committed destination is unsafe: %w", err) } if cleanRel == config.PathManifestFile { return "", false, fmt.Errorf("published output conflicts with the session manifest path") } if strings.HasPrefix(cleanRel, config.PathTranscriptsSegment+"/") || strings.HasPrefix(cleanRel, config.PathArtifactsDirSegment+"/") { return cleanRel, true, nil } if includeAudio && strings.HasPrefix(cleanRel, config.PathAudioDirSegment+"/") { return cleanRel, true, nil } return "", false, nil } func normalizeRemoteKey(v string) string { return strings.Trim(strings.ReplaceAll(strings.TrimSpace(v), "\\", "/"), "/") } func joinWithinSessionRoot(sessionRoot, relative string) (string, error) { if strings.TrimSpace(sessionRoot) == "" { return "", fmt.Errorf("session root is required") } joined, err := pathsafe.JoinSlashRelativeUnderRoot(sessionRoot, filepath.ToSlash(strings.TrimSpace(relative))) if err != nil { if errors.Is(err, pathsafe.ErrRelativePathRequired) { return "", fmt.Errorf("relative path is required") } if errors.Is(err, pathsafe.ErrRelativePathEscape) || errors.Is(err, pathsafe.ErrRelativePathAbsolute) { return "", fmt.Errorf("relative path escapes session root") } return "", fmt.Errorf("join relative path under session root: %w", err) } return joined, nil } func buildPreviousCacheRestoreActions( ctx context.Context, cfg *config.Config, sessionPaths artifacts.SessionPaths, sessionRoot *os.Root, store storage.ObjectStore, force bool, ) ([]RestoreAction, error) { if cfg == nil || cfg.Pipeline == nil || cfg.Pipeline.Scriptorium == nil { return nil, nil } effective, err := resolveEffectiveArtifacts(cfg, nil) if err != nil { return nil, err } requirements, err := artifacts.CollectPreviousArtifactRequirements(cfg.ConcreteArtifacts(), effective) if err != nil { return nil, err } if len(requirements) == 0 { return nil, nil } plan, err := previouscache.Resolve(ctx, cfg, sessionPaths, requirements, store) if err != nil { return nil, fmt.Errorf("plan previous-session cache restore: %w", err) } actions := make([]RestoreAction, 0, len(plan.Records)) for _, record := range plan.Records { action, err := classifyRestoreAction(ctx, store, storage.ObjectInfo{ Key: record.RemoteKey, Size: record.Size, ETag: record.Generation, }, record.SHA256, record.LocalRelativePath, record.LocalPath, sessionRoot, force) if err != nil { return nil, fmt.Errorf("classify previous-session cache object %q: %w", record.RemoteKey, err) } actions = append(actions, action) } return actions, nil } func classifyRestoreAction( ctx context.Context, store storage.ObjectStore, object storage.ObjectInfo, expectedSHA256 string, localRelPath string, localPath string, sessionRoot *os.Root, force bool, ) (RestoreAction, error) { action := RestoreAction{ RemoteKey: normalizeRemoteKey(object.Key), LocalRelativePath: localRelPath, LocalPath: localPath, SHA256: strings.TrimSpace(expectedSHA256), Size: object.Size, ETag: object.ETag, } if action.SHA256 != "" { action.Generation = strings.TrimSpace(object.ETag) } target, err := inspectRestoreTarget(sessionRoot, localRelPath) if err != nil { return RestoreAction{}, err } if target.kind == restoreTargetMissing { action.Kind = RestoreActionDownload action.Reason = "local file missing" return action, nil } action.ExistsLocal = true if target.kind == restoreTargetDirectory { action.Kind = RestoreActionConflict action.Conflict = true action.ConflictKind = RestoreConflictDirectory action.Reason = "local path is a directory" return action, nil } if target.kind == restoreTargetNonRegular { action.Kind = RestoreActionConflict action.Conflict = true action.ConflictKind = RestoreConflictNonRegular action.Reason = "local path is not a regular file" return action, nil } defer func() { _ = target.file.Close() }() info, err := target.file.Stat() if err != nil { return RestoreAction{}, fmt.Errorf("stat opened local file: %w", err) } if action.SHA256 != "" { localDigest, err := sha256OpenedFile(target.file) if err != nil { return RestoreAction{}, fmt.Errorf("checksum local file: %w", err) } if localDigest == action.SHA256 { action.Kind = RestoreActionSkipSame action.SameLocal = true action.Reason = "local file matches committed content" return action, nil } if force { action.Kind = RestoreActionDownload action.Reason = "local file differs from committed content; overwrite with --force" return action, nil } action.Kind = RestoreActionConflict action.Conflict = true action.ConflictKind = RestoreConflictContentMismatch action.Reason = "local file differs from committed content" return action, nil } if restoreRelativePathIsAudio(localRelPath) { if force { action.Kind = RestoreActionDownload action.Reason = "local audio identity requires verified replacement; overwrite with --force" return action, nil } action.Kind = RestoreActionConflict action.Conflict = true action.ConflictKind = RestoreConflictContentMismatch action.Reason = "local audio identity is not verified; use --force to replace it" return action, nil } if object.Size > 0 && info.Size() != object.Size { if force { action.Kind = RestoreActionDownload action.Reason = "local file differs (size mismatch); overwrite with --force" return action, nil } action.Kind = RestoreActionConflict action.Conflict = true action.ConflictKind = RestoreConflictContentMismatch action.Reason = "local file differs (size mismatch)" return action, nil } localDigest, err := sha256OpenedFile(target.file) if err != nil { return RestoreAction{}, fmt.Errorf("checksum local file: %w", err) } remotePath, err := storage.DownloadObjectToTemp(ctx, store, action.RemoteKey, "narratio-restore-plan-remote-*.tmp", restoreExpectedSize(action)) if err != nil { return RestoreAction{}, fmt.Errorf("download remote object: %w", err) } defer func() { _ = os.Remove(remotePath) }() remoteDigest, err := artifacts.SHA256File(remotePath) if err != nil { return RestoreAction{}, fmt.Errorf("checksum remote object: %w", err) } if remoteDigest == localDigest { action.Kind = RestoreActionSkipSame action.SameLocal = true action.Reason = "local file matches remote content" return action, nil } if force { action.Kind = RestoreActionDownload action.Reason = "local file differs; overwrite with --force" return action, nil } action.Kind = RestoreActionConflict action.Conflict = true action.ConflictKind = RestoreConflictContentMismatch action.Reason = "local file differs" return action, nil } type restoreTargetKind uint8 const ( restoreTargetMissing restoreTargetKind = iota restoreTargetRegular restoreTargetDirectory restoreTargetNonRegular ) type restoreTarget struct { kind restoreTargetKind file *os.File } func inspectRestoreTarget(root *os.Root, relative string) (restoreTarget, error) { name := filepath.Clean(filepath.FromSlash(strings.TrimSpace(relative))) if name == "." || name == ".." || filepath.IsAbs(name) || strings.HasPrefix(name, ".."+string(filepath.Separator)) { return restoreTarget{}, fmt.Errorf("restore path %q is not a normalized relative path", relative) } if root == nil { return restoreTarget{kind: restoreTargetMissing}, nil } parts := strings.Split(name, string(filepath.Separator)) current := root var opened []*os.Root defer func() { for _, directory := range opened { _ = directory.Close() } }() for _, part := range parts[:len(parts)-1] { info, err := current.Lstat(part) if errors.Is(err, os.ErrNotExist) { return restoreTarget{kind: restoreTargetMissing}, nil } if err != nil { return restoreTarget{}, fmt.Errorf("inspect restore ancestor %q: %w", part, err) } if !info.IsDir() || info.Mode()&os.ModeSymlink != 0 { return restoreTarget{kind: restoreTargetNonRegular}, nil } next, err := current.OpenRoot(part) if err != nil { return restoreTarget{}, fmt.Errorf("open restore ancestor %q: %w", part, err) } opened = append(opened, next) current = next } leaf := parts[len(parts)-1] info, err := current.Lstat(leaf) if errors.Is(err, os.ErrNotExist) { return restoreTarget{kind: restoreTargetMissing}, nil } if err != nil { return restoreTarget{}, fmt.Errorf("inspect restore target %q: %w", relative, err) } if info.IsDir() { return restoreTarget{kind: restoreTargetDirectory}, nil } if !info.Mode().IsRegular() || info.Mode()&os.ModeSymlink != 0 { return restoreTarget{kind: restoreTargetNonRegular}, nil } file, err := current.Open(leaf) if err != nil { return restoreTarget{}, fmt.Errorf("open restore target %q: %w", relative, err) } return restoreTarget{kind: restoreTargetRegular, file: file}, nil } func sha256OpenedFile(file *os.File) (string, error) { if _, err := file.Seek(0, io.SeekStart); err != nil { return "", err } hash := sha256.New() if _, err := io.Copy(hash, file); err != nil { return "", err } return hex.EncodeToString(hash.Sum(nil)), nil } func restoreActionIsAudio(action RestoreAction) bool { return restoreRelativePathIsAudio(action.LocalRelativePath) } func restoreRelativePathIsAudio(rel string) bool { cleanRel := path.Clean(strings.TrimSpace(rel)) return cleanRel == config.PathAudioDirSegment || strings.HasPrefix(cleanRel, config.PathAudioDirSegment+"/") }