Verify imported products through publication and local execution

This commit is contained in:
2026-12-02 16:33:08 +00:00
parent e7fada4372
commit 56483f9064
7 changed files with 334 additions and 33 deletions

View File

@@ -399,7 +399,7 @@ Validation: `go test ./internal/app ./internal/manifest ./internal/artifacts`.
## Stage 12: Prove the three operator workflows end to end ## Stage 12: Prove the three operator workflows end to end
Status: Pending Status: Complete
Use real internal collaborators, temporary files, and fake external storage, Use real internal collaborators, temporary files, and fake external storage,
subprocess, and generation boundaries. Avoid post-restore manifest repairs. subprocess, and generation boundaries. Avoid post-restore manifest repairs.

View File

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

View File

@@ -94,24 +94,27 @@ func TestFullRunWithSuppliedTranscriptPreparesAndRendersSelectedVariant(t *testi
cfg.Session.Inputs.AudioS3 = nil cfg.Session.Inputs.AudioS3 = nil
cfg.Pipeline.Render.Variants = []string{"trimmed"} 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}}}} 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) fake := &storage.FakeBackend{}
transcript := filepath.Join(paths.Root, filepath.FromSlash(artifacts.TranscriptPathFinalTrimmed)) seedCommittedRestoreSnapshot(t, cfg, fake, "20260519T010203Z-a1b2c3d4", map[string][]byte{"transcripts/final.trimmed.json": []byte(`{"segments":[]}`)})
if err := os.MkdirAll(filepath.Dir(transcript), 0755); err != nil { if _, err := restoreSessionState(context.Background(), cfg, RestorePlanOptions{}, normalizeCommandDependencies(restoreCommandDependencies(fake))); err != nil {
t.Fatal(err) t.Fatal(err)
} }
body := []byte(`{"segments":[]}`) plan := mustBoundedPlan(t, "", "analyze")
if err := os.WriteFile(transcript, body, 0600); err != nil { effective, err := resolveEffectiveArtifacts(cfg, nil)
t.Fatal(err)
}
checksum, err := artifacts.SHA256File(transcript)
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }
m := manifest.New(cfg.Session.SessionID, time.Now()) preview, err := buildSessionPlan(context.Background(), cfg, &executionInput{plan: plan}, nil, effective, commandDependencies{})
m.Campaign = cfg.Session.Campaign if err != nil {
m.SuppliedProducts = &manifest.SuppliedProductCollection{Version: manifest.SuppliedProductVersion, Products: map[string]manifest.SuppliedProduct{artifacts.ArtifactTranscriptFinalTrimmed: {Path: artifacts.TranscriptPathFinalTrimmed, Checksum: checksum, Size: int64(len(body))}}} t.Fatal(err)
saveBoundedManifest(t, cfg, m) }
plan := mustBoundedPlan(t, "", "analyze") 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{} sf := &scriptorium.FakeRunner{}
ser := &seriatim.FakeRunner{} ser := &seriatim.FakeRunner{}
result, err := executePlan(context.Background(), cfg, plan, RunOptions{Env: &Env{Scriptorium: sf, Seriatim: ser}}) 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") forced := mustBoundedPlan(t, "transcribe", "transcribe")
input := &executionInput{plan: forced} input := &executionInput{plan: forced}
input.Force.Value = true input.Force.Value = true
effective, err := resolveEffectiveArtifacts(cfg, nil) effective, err = resolveEffectiveArtifacts(cfg, nil)
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }
@@ -222,23 +225,11 @@ func TestStandalonePreflightWithSuppliedTranscriptStillProbesProviders(t *testin
cfg.Session.Inputs.AudioDir = "" cfg.Session.Inputs.AudioDir = ""
cfg.Session.Inputs.AudioFiles = nil cfg.Session.Inputs.AudioFiles = nil
cfg.Session.Inputs.AudioS3 = nil cfg.Session.Inputs.AudioS3 = nil
paths := artifacts.NewLocalStore(root).SessionPathsFor(cfg.Session.Campaign, cfg.Session.SessionID) fake := &storage.FakeBackend{}
path := filepath.Join(paths.Root, filepath.FromSlash(artifacts.TranscriptPathFinalTrimmed)) seedCommittedRestoreSnapshot(t, cfg, fake, "20260519T010203Z-a1b2c3d4", map[string][]byte{"transcripts/final.trimmed.json": []byte(`{"segments":[]}`)})
if err := os.MkdirAll(filepath.Dir(path), 0755); err != nil { if _, err := restoreSessionState(context.Background(), cfg, RestorePlanOptions{}, normalizeCommandDependencies(restoreCommandDependencies(fake))); err != nil {
t.Fatal(err) 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{} provider := &audita.FakeRunner{}
deps := fakeCommandDependencies(&storage.FakeBackend{}, nil) deps := fakeCommandDependencies(&storage.FakeBackend{}, nil)
deps.newAudita = func(*config.Config) (audita.Runner, error) { return provider, nil } deps.newAudita = func(*config.Config) (audita.Runner, error) { return provider, nil }

View File

@@ -5,6 +5,7 @@ import (
"errors" "errors"
"os" "os"
"path/filepath" "path/filepath"
"reflect"
"testing" "testing"
"time" "time"
@@ -73,6 +74,8 @@ func TestInventoryImportReplacesProductAndInvalidatesDependents(t *testing.T) {
for _, name := range []string{"prepare", "trim", "render", "extract", "analyze"} { for _, name := range []string{"prepare", "trim", "render", "extract", "analyze"} {
local.MarkStageSucceeded(name, time.Now().UTC(), nil) 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 { if err := (&manifest.LocalStore{}).Save(ctx, paths.ManifestPath, local); err != nil {
t.Fatal(err) t.Fatal(err)
} }
@@ -105,6 +108,9 @@ func TestInventoryImportReplacesProductAndInvalidatesDependents(t *testing.T) {
t.Fatalf("%s status = %q", name, loaded.Stages[name].Status) 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"] { if !artifacts.SuppliedTranscriptCoverage(paths, loaded.SuppliedProducts)["trim"] {
t.Fatal("replacement is not available") t.Fatal("replacement is not available")
} }

View File

@@ -28,12 +28,13 @@ func TestRestoreThenForcedAnalyzeUsesRestoredDurableState(t *testing.T) {
seedRestoreObject(fake, sessionPrefix+"artifacts/session_recap.md", []byte("# restored recap\n")) seedRestoreObject(fake, sessionPrefix+"artifacts/session_recap.md", []byte("# restored recap\n"))
executeRestore := restoreCommandExecutor(fake) executeRestore := restoreCommandExecutor(fake)
scriptoriumRunner := &scriptorium.FakeRunner{}
executor := func(ctx context.Context, cfg *config.Config, plan BoundedPlan, opts RunOptions) (*RunSummary, error) { executor := func(ctx context.Context, cfg *config.Config, plan BoundedPlan, opts RunOptions) (*RunSummary, error) {
if opts.Env == nil { if opts.Env == nil {
opts.Env = &Env{} opts.Env = &Env{}
} }
opts.Env.Scriptorium = &scriptorium.NoopRunner{} opts.Env.Scriptorium = scriptoriumRunner
return executePlan(ctx, cfg, plan, opts) return executePlan(ctx, cfg, plan, opts)
} }
@@ -99,6 +100,9 @@ func TestRestoreThenForcedAnalyzeUsesRestoredDurableState(t *testing.T) {
if !runCountsMatch(t, stdout.Bytes(), 1, 0, "analyze") { if !runCountsMatch(t, stdout.Bytes(), 1, 0, "analyze") {
t.Fatalf("single-stage run stdout = %q, want analyze execution summary", stdout.String()) 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") playerHandoutPath := filepath.Join(sessionRoot, "artifacts", "player_handout.md")
if _, err := os.Stat(playerHandoutPath); err != nil { if _, err := os.Stat(playerHandoutPath); err != nil {
@@ -116,6 +120,9 @@ func TestRestoreThenForcedAnalyzeUsesRestoredDurableState(t *testing.T) {
if analyzeRec == nil || analyzeRec.Status != manifest.StatusSucceeded { if analyzeRec == nil || analyzeRec.Status != manifest.StatusSucceeded {
t.Fatalf("post-analyze stage record = %#v, want succeeded", analyzeRec) 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) 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() { if info, statErr := os.Stat(runRoot); statErr != nil || !info.IsDir() {

View File

@@ -54,7 +54,7 @@ func (publishStage) Run(ctx context.Context, env *Env, m *manifest.Manifest) (*S
}, nil }, nil
} }
if err := validatePublishPrerequisites(m); err != nil { if err := validatePublishPrerequisites(env, m); err != nil {
return nil, fmt.Errorf("publish: %w", err) return nil, fmt.Errorf("publish: %w", err)
} }
if env.ObjectStore == nil { if env.ObjectStore == nil {
@@ -222,10 +222,30 @@ func publishRunUploadDisabled(env *Env) bool {
return cfg.UploadRun != nil && !*cfg.UploadRun return cfg.UploadRun != nil && !*cfg.UploadRun
} }
func validatePublishPrerequisites(m *manifest.Manifest) error { func validatePublishPrerequisites(env *Env, m *manifest.Manifest) error {
if m == nil { if m == nil {
return fmt.Errorf("manifest is required") 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 { for _, stageName := range publishPrerequisiteStages {
sr := m.Stages[stageName] sr := m.Stages[stageName]
if sr == nil { if sr == nil {

View File

@@ -112,6 +112,11 @@ func collectPublishRunFiles(runRoot string, sessionManifest *manifest.Manifest)
if strings.TrimSpace(path) == "" { if strings.TrimSpace(path) == "" {
return nil 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) rel, err := pathsafe.SlashRelativeFromRoot(runRoot, path)
if err != nil { if err != nil {
return nil return nil