From 56483f9064ff06b05168972ef145f8ecbce7908b Mon Sep 17 00:00:00 2001 From: Eric Rakestraw Date: Wed, 2 Dec 2026 16:33:08 +0000 Subject: [PATCH] Verify imported products through publication and local execution --- docs/roadmap/implementation.md | 2 +- internal/app/import_workflow_test.go | 272 +++++++++++++++++++++ internal/app/reference_preparation_test.go | 49 ++-- internal/app/restore_baseline_test.go | 6 + internal/app/restore_workflow_test.go | 9 +- internal/stage/publish.go | 24 +- internal/stage/publish_sources.go | 5 + 7 files changed, 334 insertions(+), 33 deletions(-) create mode 100644 internal/app/import_workflow_test.go diff --git a/docs/roadmap/implementation.md b/docs/roadmap/implementation.md index f741dfb..703a01d 100644 --- a/docs/roadmap/implementation.md +++ b/docs/roadmap/implementation.md @@ -399,7 +399,7 @@ Validation: `go test ./internal/app ./internal/manifest ./internal/artifacts`. ## Stage 12: Prove the three operator workflows end to end -Status: Pending +Status: Complete Use real internal collaborators, temporary files, and fake external storage, subprocess, and generation boundaries. Avoid post-restore manifest repairs. diff --git a/internal/app/import_workflow_test.go b/internal/app/import_workflow_test.go new file mode 100644 index 0000000..f5266ac --- /dev/null +++ b/internal/app/import_workflow_test.go @@ -0,0 +1,272 @@ +package app + +import ( + "context" + "os" + "path/filepath" + "strings" + "testing" + "time" + + "gitea.maximumdirect.net/eric/narratio/internal/adapters/scriptorium" + "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" + "gitea.maximumdirect.net/eric/narratio/internal/stage" +) + +func TestLockedProductsRemainUsableAfterImportAndRepublish(t *testing.T) { + ctx := context.Background() + producerRoot := t.TempDir() + pipeline, campaign, session := writeValidConfigFilesWithScriptoriumArtifacts(t, producerRoot) + cfg, err := config.LoadWithSessionOptions(pipeline, campaign, session, config.SessionLoadOptions{}) + if err != nil { + t.Fatal(err) + } + on := true + cfg.Pipeline.Publish.Enabled, cfg.Pipeline.Publish.UploadRun = &on, &on + rules := []config.PublishOutputRule{ + {Source: artifacts.ArtifactTranscriptFinalTrimmed, Dest: "review/transcript.json", Required: &on}, + {Source: artifacts.ConfiguredArtifactSourceID("session_recap"), Dest: "review/recap.md", Required: &on}, + } + cfg.Pipeline.Publish.Outputs = rules + cfg.ArtifactCatalog.PublishOutputs = rules + paths := artifacts.NewLocalStore(producerRoot).SessionPathsFor(cfg.Session.Campaign, cfg.Session.SessionID) + transcript := filepath.Join(paths.TranscriptsDir, "final.trimmed.json") + recap := filepath.Join(paths.ArtifactsDir, "session_recap.md") + aTranscript, aRecap := `{"segments":[]}`, "reviewed recap\n" + mustWriteTestFile(t, transcript, aTranscript) + mustWriteTestFile(t, recap, aRecap) + m := manifest.New(cfg.Session.SessionID, time.Now().UTC()) + m.Campaign = cfg.Session.Campaign + m.RunID = "20260519T010203Z-a1b2c3d4" + m.LocalWorkDir = artifacts.SessionRunRootForCampaign(producerRoot, m.Campaign, m.SessionID, m.RunID) + if err := os.MkdirAll(m.LocalWorkDir, 0755); err != nil { + t.Fatal(err) + } + for _, name := range []string{"prepare", "transcribe", "merge", "polish", "normalize", "trim", "render", "analyze"} { + m.MarkStageSucceeded(name, time.Now().UTC(), nil) + } + setCurrentBuiltInEvidence(t, m, "trim", artifacts.TranscriptOutputKindFinalTrimmed, artifacts.ArtifactTranscriptFinalTrimmed, transcript) + setAppAnalyzeEvidence(m, "session_recap", "artifacts/session_recap.md", []byte(aRecap)) + fake := &storage.FakeBackend{} + env := &stage.Env{Config: cfg, ArtifactStore: artifacts.NewLocalStore(producerRoot), ObjectStore: fake} + publish, err := stage.Select("publish") + if err != nil { + t.Fatal(err) + } + if _, err := publish.Run(ctx, env, m); err != nil { + t.Fatal(err) + } + prefix, err := artifacts.ResolvePublishSessionPrefix(cfg, m) + if err != nil { + t.Fatal(err) + } + for _, rule := range rules { + lock, err := artifacts.NewRemoteLock(rule.Source, "reviewed", time.Now().UTC()) + if err != nil { + t.Fatal(err) + } + if err := artifacts.AddRemoteLock(ctx, fake, prefix, lock, false); err != nil { + t.Fatal(err) + } + } + m.RunID = "20260520T010203Z-a1b2c3d4" + m.LocalWorkDir = artifacts.SessionRunRootForCampaign(producerRoot, m.Campaign, m.SessionID, m.RunID) + if err := os.MkdirAll(m.LocalWorkDir, 0755); err != nil { + t.Fatal(err) + } + normalized := filepath.Join(paths.TranscriptsDir, "final.json") + mustWriteTestFile(t, normalized, `{"segments":[{"text":"new"}]}`) + setCurrentBuiltInEvidence(t, m, "normalize", artifacts.TranscriptOutputKindFinal, artifacts.ArtifactTranscriptFinal, normalized) + off := false + cfg.Pipeline.Trim.Enabled = &off + trim, err := stage.Select("trim") + if err != nil { + t.Fatal(err) + } + trimmed, err := trim.Run(ctx, env, m) + if err != nil { + t.Fatal(err) + } + m.MarkStageSucceeded("trim", time.Now().UTC(), mapResultOutputs("trim", trimmed, m.RunID)) + env.Scriptorium = &scriptorium.FakeRunner{} + env.ManifestStore = &manifest.LocalStore{} + env.SelectedArtifactKeys = []string{"session_recap"} + env.Force = true + analyze, err := stage.Select("analyze") + if err != nil { + t.Fatal(err) + } + generated, err := analyze.Run(ctx, env, m) + if err != nil { + t.Fatal(err) + } + m.MarkStageSucceeded("analyze", time.Now().UTC(), mapResultOutputs("analyze", generated, m.RunID)) + if data, err := os.ReadFile(recap); err != nil || string(data) == aRecap { + t.Fatalf("new local recap was not generated: %q, %v", data, err) + } + env.Force = false + env.SelectedArtifactKeys = nil + if _, err := publish.Run(ctx, env, m); err != nil { + t.Fatal(err) + } + selected, err := artifacts.LoadCurrentInventory(ctx, fake, prefix, artifacts.CurrentStateValidation{}) + if err != nil { + t.Fatal(err) + } + carried := 0 + for _, declaration := range selected.Commit.Artifacts { + if declaration.Type == artifacts.RemoteArtifactTypeSessionManifest { + t.Fatal("publication included an execution snapshot") + } + if declaration.Type == artifacts.RemoteArtifactTypePublishedOutput && !strings.Contains(declaration.DestinationKey, "20260519T010203Z-a1b2c3d4") { + t.Fatalf("locked product was not carried from its original publication: %#v", declaration) + } + if declaration.Type == artifacts.RemoteArtifactTypePublishedOutput { + carried++ + } + } + if carried != len(rules) { + t.Fatalf("carried %d products, want %d", carried, len(rules)) + } + cfg.Pipeline.Workspace.Root = t.TempDir() + cfg.Session.Inputs.AudioDir = "" + deps := normalizeCommandDependencies(restoreCommandDependencies(fake)) + if _, err := restoreSessionState(ctx, cfg, RestorePlanOptions{}, deps); err != nil { + t.Fatal(err) + } + importedPaths := artifacts.NewLocalStore(cfg.Pipeline.Workspace.Root).SessionPathsFor(cfg.Session.Campaign, cfg.Session.SessionID) + mustReadEquals(t, filepath.Join(importedPaths.TranscriptsDir, "final.trimmed.json"), aTranscript) + mustReadEquals(t, filepath.Join(importedPaths.ArtifactsDir, "session_recap.md"), aRecap) + imported, err := (&manifest.LocalStore{}).Load(ctx, importedPaths.ManifestPath) + if err != nil { + t.Fatal(err) + } + if !artifacts.SuppliedTranscriptCoverage(importedPaths, imported.SuppliedProducts)["trim"] { + t.Fatal("carried transcript is not available after import") + } + catalog := artifacts.NewArtifactCatalog() + definitions := artifacts.ConfiguredArtifactDefinitions(cfg.ConcreteArtifacts()) + if err := catalog.RegisterConfiguredArtifacts(definitions); err != nil { + t.Fatal(err) + } + catalog.HydrateAnalyzeArtifacts(importedPaths, imported, definitions) + if _, err := artifacts.ResolveSessionArtifactWithCatalog(importedPaths, imported, artifacts.ConfiguredArtifactSourceID("session_recap"), catalog); err != nil { + t.Fatalf("carried configured product unavailable: %v", err) + } + for _, rule := range rules { + if err := artifacts.RemoveRemoteLock(ctx, fake, prefix, rule.Source); err != nil { + t.Fatal(err) + } + } + imported.RunID = "20260521T010203Z-a1b2c3d4" + imported.LocalWorkDir = artifacts.SessionRunRootForCampaign(cfg.Pipeline.Workspace.Root, imported.Campaign, imported.SessionID, imported.RunID) + if err := os.MkdirAll(imported.LocalWorkDir, 0755); err != nil { + t.Fatal(err) + } + env.ArtifactStore = artifacts.NewLocalStore(cfg.Pipeline.Workspace.Root) + if _, err := publish.Run(ctx, env, imported); err != nil { + t.Fatalf("republish imported products: %v", err) + } + if err := os.WriteFile(filepath.Join(importedPaths.ArtifactsDir, "session_recap.md"), []byte("tampered\n"), 0600); err != nil { + t.Fatal(err) + } + imported.RunID = "20260522T010203Z-a1b2c3d4" + imported.LocalWorkDir = artifacts.SessionRunRootForCampaign(cfg.Pipeline.Workspace.Root, imported.Campaign, imported.SessionID, imported.RunID) + if err := os.MkdirAll(imported.LocalWorkDir, 0755); err != nil { + t.Fatal(err) + } + if _, err := publish.Run(ctx, env, imported); err == nil { + t.Fatal("republish accepted a tampered required product") + } + current, err := artifacts.LoadCurrentInventory(ctx, fake, prefix, artifacts.CurrentStateValidation{}) + if err != nil || current.RunID != "20260521T010203Z-a1b2c3d4" { + t.Fatalf("failed republish changed current publication: %#v, %v", current, err) + } +} + +func TestImportedPartialExtractionRegeneratesCompleteBundle(t *testing.T) { + ctx := context.Background() + root := t.TempDir() + pipeline, campaign, session := writeValidConfigFiles(t, root) + cfg, err := config.LoadWithSessionOptions(pipeline, campaign, session, config.SessionLoadOptions{}) + if err != nil { + t.Fatal(err) + } + cfg.Session.Inputs.AudioDir = "" + binary := filepath.Join(root, "notarius") + configPath := filepath.Join(root, "notarius.yml") + mustWriteTestFile(t, binary, "#!/bin/sh\nexit 0\n") + if err := os.Chmod(binary, 0755); err != nil { + t.Fatal(err) + } + mustWriteTestFile(t, configPath, "pipelines: {}\n") + cfg.Pipeline.Notarius = &config.NotariusConfig{Enabled: true, Binary: binary, ConfigPath: configPath, WorkingDirectory: root, PipelineID: "dnd-session", Timeout: "1m", Outputs: map[string]config.NotariusOutputConfig{ + "npc_registry": {LaneID: "npc-registry"}, "encounters": {LaneID: "encounters"}, + }} + fake := &storage.FakeBackend{} + current := seedCommittedRestoreSnapshot(t, cfg, fake, "20260519T010203Z-a1b2c3d4", map[string][]byte{ + "transcripts/final.trimmed.json": []byte(`{"segments":[]}`), "artifacts/old-npcs.json": []byte(`{"records":[]}`), + }) + setRestoreFixtureSources(t, fake, current, map[string]string{"artifacts/old-npcs.json": artifacts.ExtractionArtifactSourceID("npc_registry")}) + if _, err := restoreSessionState(ctx, cfg, RestorePlanOptions{}, normalizeCommandDependencies(restoreCommandDependencies(fake))); err != nil { + t.Fatal(err) + } + paths := artifacts.NewLocalStore(root).SessionPathsFor(cfg.Session.Campaign, cfg.Session.SessionID) + before, err := (&manifest.LocalStore{}).Load(ctx, paths.ManifestPath) + if err != nil { + t.Fatal(err) + } + if artifacts.SuppliedExtractionComplete(paths, before, artifacts.ExtractionDefinitionsFromConfig(cfg.Pipeline.Notarius)) { + t.Fatal("partial extraction was treated as complete") + } + runner := &materializingNotariusRunner{cfg: cfg.Pipeline.Notarius} + result, err := executePlan(ctx, cfg, mustBoundedPlan(t, "extract", "extract"), RunOptions{Env: &Env{Notarius: runner}}) + if err != nil { + t.Fatal(err) + } + if len(runner.requests) != 1 { + t.Fatalf("extraction requests = %d", len(runner.requests)) + } + after, err := (&manifest.LocalStore{}).Load(ctx, result.ManifestPath) + if err != nil { + t.Fatal(err) + } + if after.Stages["extract"] == nil || after.Stages["extract"].Status != manifest.StatusSucceeded || len(after.Stages["extract"].Outputs) != 2 { + t.Fatalf("generated extraction evidence = %#v", after.Stages["extract"]) + } + if _, ok := after.SuppliedProducts.Products[artifacts.ExtractionArtifactSourceID("npc_registry")]; ok { + t.Fatal("local extraction did not retire the imported product") + } +} + +func TestImportedTrimmedTranscriptDoesNotInventNormalizedInput(t *testing.T) { + ctx := context.Background() + root := t.TempDir() + pipeline, campaign, session := writeValidConfigFiles(t, root) + cfg, err := config.LoadWithSessionOptions(pipeline, campaign, session, config.SessionLoadOptions{}) + if err != nil { + t.Fatal(err) + } + cfg.Session.Inputs.AudioDir = "" + fake := &storage.FakeBackend{} + seedCommittedRestoreSnapshot(t, cfg, fake, "20260519T010203Z-a1b2c3d4", map[string][]byte{"transcripts/final.trimmed.json": []byte(`{"segments":[]}`)}) + if _, err := restoreSessionState(ctx, cfg, RestorePlanOptions{}, normalizeCommandDependencies(restoreCommandDependencies(fake))); err != nil { + t.Fatal(err) + } + plan := mustBoundedPlan(t, "render", "render") + input := &executionInput{plan: plan} + effective, err := resolveEffectiveArtifacts(cfg, nil) + if err != nil { + t.Fatal(err) + } + preview, err := buildSessionPlan(ctx, cfg, input, nil, effective, commandDependencies{}) + if err != nil || !strings.Contains(strings.Join(preview.InputIssues, " "), artifacts.ArtifactTranscriptFinal) { + t.Fatalf("default render preview = %#v, %v", preview, err) + } + if _, err := executePlan(ctx, cfg, plan, RunOptions{}); err == nil || !strings.Contains(err.Error(), artifacts.ArtifactTranscriptFinal) { + t.Fatalf("render accepted absent normalized transcript: %v", err) + } +} diff --git a/internal/app/reference_preparation_test.go b/internal/app/reference_preparation_test.go index 1314216..c51f386 100644 --- a/internal/app/reference_preparation_test.go +++ b/internal/app/reference_preparation_test.go @@ -94,24 +94,27 @@ func TestFullRunWithSuppliedTranscriptPreparesAndRendersSelectedVariant(t *testi cfg.Session.Inputs.AudioS3 = nil cfg.Pipeline.Render.Variants = []string{"trimmed"} cfg.ArtifactCatalog.Artifacts = map[string]config.ScriptoriumArtifactConfig{"recap": {Enabled: true, PromptID: "dnd.recap", OutputPath: "artifacts/recap.md", Inputs: map[string]config.ScriptoriumInputConfig{"party": {Source: artifactpolicy.SourceInputParty, Required: true}, "transcript": {Source: artifacts.ArtifactTranscriptFinalTrimmed, Required: true}}}} - paths := artifacts.NewLocalStore(root).SessionPathsFor(cfg.Session.Campaign, cfg.Session.SessionID) - transcript := filepath.Join(paths.Root, filepath.FromSlash(artifacts.TranscriptPathFinalTrimmed)) - if err := os.MkdirAll(filepath.Dir(transcript), 0755); err != nil { + fake := &storage.FakeBackend{} + seedCommittedRestoreSnapshot(t, cfg, fake, "20260519T010203Z-a1b2c3d4", map[string][]byte{"transcripts/final.trimmed.json": []byte(`{"segments":[]}`)}) + if _, err := restoreSessionState(context.Background(), cfg, RestorePlanOptions{}, normalizeCommandDependencies(restoreCommandDependencies(fake))); err != nil { t.Fatal(err) } - body := []byte(`{"segments":[]}`) - if err := os.WriteFile(transcript, body, 0600); err != nil { - t.Fatal(err) - } - checksum, err := artifacts.SHA256File(transcript) + plan := mustBoundedPlan(t, "", "analyze") + effective, err := resolveEffectiveArtifacts(cfg, nil) if err != nil { t.Fatal(err) } - m := manifest.New(cfg.Session.SessionID, time.Now()) - m.Campaign = cfg.Session.Campaign - m.SuppliedProducts = &manifest.SuppliedProductCollection{Version: manifest.SuppliedProductVersion, Products: map[string]manifest.SuppliedProduct{artifacts.ArtifactTranscriptFinalTrimmed: {Path: artifacts.TranscriptPathFinalTrimmed, Checksum: checksum, Size: int64(len(body))}}} - saveBoundedManifest(t, cfg, m) - plan := mustBoundedPlan(t, "", "analyze") + preview, err := buildSessionPlan(context.Background(), cfg, &executionInput{plan: plan}, nil, effective, commandDependencies{}) + if err != nil { + t.Fatal(err) + } + for _, item := range preview.Stages { + if item.Name == "transcribe" || item.Name == "merge" || item.Name == "polish" || item.Name == "normalize" || item.Name == "trim" { + if item.Action != "skip" { + t.Fatalf("covered stage planned as %s: %#v", item.Action, item) + } + } + } sf := &scriptorium.FakeRunner{} ser := &seriatim.FakeRunner{} result, err := executePlan(context.Background(), cfg, plan, RunOptions{Env: &Env{Scriptorium: sf, Seriatim: ser}}) @@ -131,7 +134,7 @@ func TestFullRunWithSuppliedTranscriptPreparesAndRendersSelectedVariant(t *testi forced := mustBoundedPlan(t, "transcribe", "transcribe") input := &executionInput{plan: forced} input.Force.Value = true - effective, err := resolveEffectiveArtifacts(cfg, nil) + effective, err = resolveEffectiveArtifacts(cfg, nil) if err != nil { t.Fatal(err) } @@ -222,23 +225,11 @@ func TestStandalonePreflightWithSuppliedTranscriptStillProbesProviders(t *testin cfg.Session.Inputs.AudioDir = "" cfg.Session.Inputs.AudioFiles = nil cfg.Session.Inputs.AudioS3 = nil - paths := artifacts.NewLocalStore(root).SessionPathsFor(cfg.Session.Campaign, cfg.Session.SessionID) - path := filepath.Join(paths.Root, filepath.FromSlash(artifacts.TranscriptPathFinalTrimmed)) - if err := os.MkdirAll(filepath.Dir(path), 0755); err != nil { + fake := &storage.FakeBackend{} + seedCommittedRestoreSnapshot(t, cfg, fake, "20260519T010203Z-a1b2c3d4", map[string][]byte{"transcripts/final.trimmed.json": []byte(`{"segments":[]}`)}) + if _, err := restoreSessionState(context.Background(), cfg, RestorePlanOptions{}, normalizeCommandDependencies(restoreCommandDependencies(fake))); err != nil { t.Fatal(err) } - body := []byte(`{"segments":[]}`) - if err := os.WriteFile(path, body, 0600); err != nil { - t.Fatal(err) - } - checksum, err := artifacts.SHA256File(path) - if err != nil { - t.Fatal(err) - } - m := manifest.New(cfg.Session.SessionID, time.Now()) - m.Campaign = cfg.Session.Campaign - m.SuppliedProducts = &manifest.SuppliedProductCollection{Version: manifest.SuppliedProductVersion, Products: map[string]manifest.SuppliedProduct{artifacts.ArtifactTranscriptFinalTrimmed: {Path: artifacts.TranscriptPathFinalTrimmed, Checksum: checksum, Size: int64(len(body))}}} - saveBoundedManifest(t, cfg, m) provider := &audita.FakeRunner{} deps := fakeCommandDependencies(&storage.FakeBackend{}, nil) deps.newAudita = func(*config.Config) (audita.Runner, error) { return provider, nil } diff --git a/internal/app/restore_baseline_test.go b/internal/app/restore_baseline_test.go index a596843..4945be3 100644 --- a/internal/app/restore_baseline_test.go +++ b/internal/app/restore_baseline_test.go @@ -5,6 +5,7 @@ import ( "errors" "os" "path/filepath" + "reflect" "testing" "time" @@ -73,6 +74,8 @@ func TestInventoryImportReplacesProductAndInvalidatesDependents(t *testing.T) { for _, name := range []string{"prepare", "trim", "render", "extract", "analyze"} { local.MarkStageSucceeded(name, time.Now().UTC(), nil) } + setAppAnalyzeEvidence(local, "unrelated", "artifacts/unrelated.md", []byte("existing checkpoint")) + checkpoint := manifest.CloneAnalyzeArtifactCollection(local.Stages["analyze"].AnalyzeArtifacts) if err := (&manifest.LocalStore{}).Save(ctx, paths.ManifestPath, local); err != nil { t.Fatal(err) } @@ -105,6 +108,9 @@ func TestInventoryImportReplacesProductAndInvalidatesDependents(t *testing.T) { t.Fatalf("%s status = %q", name, loaded.Stages[name].Status) } } + if !reflect.DeepEqual(loaded.Stages["analyze"].AnalyzeArtifacts, checkpoint) { + t.Fatalf("unrelated analysis checkpoint changed: %#v", loaded.Stages["analyze"].AnalyzeArtifacts) + } if !artifacts.SuppliedTranscriptCoverage(paths, loaded.SuppliedProducts)["trim"] { t.Fatal("replacement is not available") } diff --git a/internal/app/restore_workflow_test.go b/internal/app/restore_workflow_test.go index e6471a4..1ad4830 100644 --- a/internal/app/restore_workflow_test.go +++ b/internal/app/restore_workflow_test.go @@ -28,12 +28,13 @@ func TestRestoreThenForcedAnalyzeUsesRestoredDurableState(t *testing.T) { seedRestoreObject(fake, sessionPrefix+"artifacts/session_recap.md", []byte("# restored recap\n")) executeRestore := restoreCommandExecutor(fake) + scriptoriumRunner := &scriptorium.FakeRunner{} executor := func(ctx context.Context, cfg *config.Config, plan BoundedPlan, opts RunOptions) (*RunSummary, error) { if opts.Env == nil { opts.Env = &Env{} } - opts.Env.Scriptorium = &scriptorium.NoopRunner{} + opts.Env.Scriptorium = scriptoriumRunner return executePlan(ctx, cfg, plan, opts) } @@ -99,6 +100,9 @@ func TestRestoreThenForcedAnalyzeUsesRestoredDurableState(t *testing.T) { if !runCountsMatch(t, stdout.Bytes(), 1, 0, "analyze") { t.Fatalf("single-stage run stdout = %q, want analyze execution summary", stdout.String()) } + if len(scriptoriumRunner.RunRequests) != 1 || scriptoriumRunner.RunRequests[0].InputPaths["recap"] != filepath.Join(sessionRoot, "artifacts", "session_recap.md") { + t.Fatalf("analysis did not reuse imported prerequisite: %#v", scriptoriumRunner.RunRequests) + } playerHandoutPath := filepath.Join(sessionRoot, "artifacts", "player_handout.md") if _, err := os.Stat(playerHandoutPath); err != nil { @@ -116,6 +120,9 @@ func TestRestoreThenForcedAnalyzeUsesRestoredDurableState(t *testing.T) { if analyzeRec == nil || analyzeRec.Status != manifest.StatusSucceeded { t.Fatalf("post-analyze stage record = %#v, want succeeded", analyzeRec) } + if analyzeRec.AnalyzeArtifacts["player_handout"].Status != manifest.AnalyzeArtifactCurrent || analyzeRec.AnalyzeArtifacts["player_handout"].Fingerprint == "" { + t.Fatalf("generated analysis lacks local evidence: %#v", analyzeRec) + } runRoot := artifacts.SessionRunRootForCampaign(cfg.Pipeline.Workspace.Root, cfg.Session.Campaign, cfg.Session.SessionID, afterAnalyze.RunID) if info, statErr := os.Stat(runRoot); statErr != nil || !info.IsDir() { diff --git a/internal/stage/publish.go b/internal/stage/publish.go index 9563a70..0e0de49 100644 --- a/internal/stage/publish.go +++ b/internal/stage/publish.go @@ -54,7 +54,7 @@ func (publishStage) Run(ctx context.Context, env *Env, m *manifest.Manifest) (*S }, nil } - if err := validatePublishPrerequisites(m); err != nil { + if err := validatePublishPrerequisites(env, m); err != nil { return nil, fmt.Errorf("publish: %w", err) } if env.ObjectStore == nil { @@ -222,10 +222,30 @@ func publishRunUploadDisabled(env *Env) bool { return cfg.UploadRun != nil && !*cfg.UploadRun } -func validatePublishPrerequisites(m *manifest.Manifest) error { +func validatePublishPrerequisites(env *Env, m *manifest.Manifest) error { if m == nil { return fmt.Errorf("manifest is required") } + // Imported products carry their own local availability evidence. The + // publication resolver below independently validates each selected source, + // so their absent historical producer statuses are not prerequisites. + if m.SuppliedProducts != nil && env != nil && env.Config != nil && env.Config.Pipeline != nil && env.Config.Session != nil { + paths := publishSessionPaths(env, m) + catalog, err := newPublishArtifactCatalog(env.Config.ConcreteArtifacts(), env.Config.Pipeline.Notarius) + if err != nil { + return err + } + for source, product := range m.SuppliedProducts.Products { + entry, ok := catalog.Lookup(source) + if !ok { + continue + } + canonical, err := artifacts.ProductRelativePath(paths.Root, entry.CanonicalRelPath) + if err == nil && artifacts.ValidateSuppliedProduct(paths, source, canonical, product) == nil { + return nil + } + } + } for _, stageName := range publishPrerequisiteStages { sr := m.Stages[stageName] if sr == nil { diff --git a/internal/stage/publish_sources.go b/internal/stage/publish_sources.go index 5900b52..e410596 100644 --- a/internal/stage/publish_sources.go +++ b/internal/stage/publish_sources.go @@ -112,6 +112,11 @@ func collectPublishRunFiles(runRoot string, sessionManifest *manifest.Manifest) if strings.TrimSpace(path) == "" { return nil } + // Relative artifact records are session-relative, not paths inside the + // current run archive. Only actual run-local paths belong in this upload. + if !filepath.IsAbs(path) { + return nil + } rel, err := pathsafe.SlashRelativeFromRoot(runRoot, path) if err != nil { return nil