From e19ba814067b3727d4aa3005561c6b32873f780f Mon Sep 17 00:00:00 2001 From: Eric Rakestraw Date: Mon, 30 Nov 2026 01:44:30 +0000 Subject: [PATCH] Publish prepared inputs and flat extraction products --- docs/roadmap/implementation.md | 7 ++ internal/stage/publish_prepared_test.go | 49 ++++++++++- internal/stage/publish_sources.go | 14 ++- internal/stage/publish_test.go | 112 ++++++++---------------- 4 files changed, 103 insertions(+), 79 deletions(-) diff --git a/docs/roadmap/implementation.md b/docs/roadmap/implementation.md index 6041de3..b0ccf3f 100644 --- a/docs/roadmap/implementation.md +++ b/docs/roadmap/implementation.md @@ -666,6 +666,13 @@ prepared audio is fetched again; separate subprocess caches are never targeted. ## Stage 18 — Publish new-format products and prepared inputs +**Complete.** Commit: `Publish prepared inputs and flat extraction products`. +Verification: focused publication and output-planning tests passed with Go +1.27.4, covering committed prepared inputs, flat extraction evidence, previous +input enumeration, declared diagnostics and private capture exclusion, locks, +failures, and pointer ordering. Restore mapping of these prepared inputs follows +in the next stage. + **Read:** roadmap durable lifecycle sections; [Publish Internals](../internal/stage-publish.md). Entry points: publish source/output planning, transfer and commit code, runtime catalog/evidence, and archive enumeration. diff --git a/internal/stage/publish_prepared_test.go b/internal/stage/publish_prepared_test.go index c4db7b5..4e022df 100644 --- a/internal/stage/publish_prepared_test.go +++ b/internal/stage/publish_prepared_test.go @@ -1,9 +1,14 @@ package stage import ( + "context" "os" "path/filepath" + "strings" "testing" + + "gitea.maximumdirect.net/eric/narratio/internal/adapters/storage" + "gitea.maximumdirect.net/eric/narratio/internal/artifacts" ) func TestPublishPreparedInputsRetainVerifiedBytesAndRejectTampering(t *testing.T) { @@ -14,11 +19,13 @@ func TestPublishPreparedInputsRetainVerifiedBytesAndRejectTampering(t *testing.T if err != nil { t.Fatal(err) } - if len(files) != 8 { + if len(files) != 12 { t.Fatalf("prepared archive files = %d", len(files)) } - if _, err := os.Stat(filepath.Join(runRoot, "prepare", "inputs", "glossaries", "combined.yml")); err != nil { - t.Fatal(err) + for _, name := range []string{"glossaries/combined.yml", "autocorrect.yml", "speakers.yml", "players.yml", "pipeline.resolved.yml"} { + if _, err := os.Stat(filepath.Join(runRoot, "prepare", "inputs", filepath.FromSlash(name))); err != nil { + t.Fatal(err) + } } for _, file := range files { path := filepath.Join(runRoot, filepath.FromSlash(file.RelativePath)) @@ -50,3 +57,39 @@ func TestPublishPreparedInputsRetainVerifiedBytesAndRejectTampering(t *testing.T t.Fatalf("changed archive after failed validation: %v", err) } } + +func TestPublishDeclaresPreparedInputsInImmutableCommit(t *testing.T) { + preparedEnv, preparedManifest, _ := prepareResumeLocalFixture(t) + preparedPaths := sessionPathsForEnv(preparedEnv, preparedManifest.SessionID) + env, m, _ := publishFixture(t) + paths := publishSessionPaths(env, m) + env.ArtifactStore = artifacts.NewLocalStore(env.Config.Pipeline.Workspace.Root) + for _, record := range preparedManifest.Inputs { + rel, err := filepath.Rel(preparedPaths.InputsDir, record.Path) + if err != nil || rel == ".." || strings.HasPrefix(rel, ".."+string(filepath.Separator)) { + continue + } + data, err := os.ReadFile(record.Path) + if err != nil { + t.Fatal(err) + } + record.Path = filepath.Join(paths.InputsDir, rel) + writeStageTestFile(t, record.Path, string(data)) + m.Inputs = append(m.Inputs, record) + } + if _, err := (publishStage{}).Run(context.Background(), env, m); err != nil { + t.Fatal(err) + } + fake := env.ObjectStore.(*storage.FakeBackend) + commit, err := artifacts.DecodeRemoteCommitManifest(fake.Objects[artifacts.S3RunCommitKey(m.S3SessionPrefix, m.RunID)].Data) + if err != nil { + t.Fatal(err) + } + for _, name := range []string{"autocorrect.yml", "players.yml", "speakers.yml", "pipeline.resolved.yml", "glossaries/party.yml", "glossaries/campaign.yml", "glossaries/setting.yml", "glossaries/spells.yml", "glossaries/combined.yml"} { + source := "run:prepare/inputs/" + name + declaration := remoteArtifactForSource(t, commit, source) + if declaration.DestinationKey != m.S3RunPrefix+strings.TrimPrefix(source, "run:") || declaration.SHA256 == "" { + t.Fatalf("prepared input declaration = %#v", declaration) + } + } +} diff --git a/internal/stage/publish_sources.go b/internal/stage/publish_sources.go index 7fb7a77..02e2f8b 100644 --- a/internal/stage/publish_sources.go +++ b/internal/stage/publish_sources.go @@ -29,7 +29,11 @@ type publishUploadFile struct { // collectPublishPreparedInputs copies the prepared documents into this run's // archive, retaining their manifest checksums for the ordinary upload path. func collectPublishPreparedInputs(store artifacts.Store, paths artifacts.SessionPaths, runRoot string, records []manifest.InputRecord) ([]publishUploadFile, error) { - filenames := map[string]string{"session_config": "session.yml", "campaign_config": "campaign.yml", "party": "party.yml"} + filenames := map[string]string{ + "session_config": "session.yml", "campaign_config": "campaign.yml", + "party": "party.yml", "players": "players.yml", "speakers": "speakers.yml", + "autocorrect": "autocorrect.yml", "pipeline_resolved": "pipeline.resolved.yml", + } glossaries := map[string]artifactpolicy.PreparedInputSourceDescriptor{} for _, descriptor := range artifactpolicy.GlossaryInputSources() { filenames[descriptor.ManifestKind] = descriptor.Filename @@ -39,11 +43,19 @@ func collectPublishPreparedInputs(store artifacts.Store, paths artifacts.Session filenames[combined.ManifestKind] = combined.Filename glossaries[combined.ManifestKind] = combined var result []publishUploadFile + seen := make(map[string]bool) for _, record := range records { name, ok := filenames[record.Kind] if !ok { continue } + if seen[record.Kind] { + return nil, fmt.Errorf("duplicate prepared input %q", record.Kind) + } + seen[record.Kind] = true + if filepath.Clean(record.Path) != filepath.Join(paths.InputsDir, filepath.FromSlash(name)) || strings.TrimSpace(record.Checksum) == "" { + return nil, fmt.Errorf("prepared input %q lacks canonical path or checksum", record.Kind) + } if descriptor, ok := glossaries[record.Kind]; ok { if _, err := artifacts.ResolvePreparedInput(paths, &manifest.Manifest{Inputs: records}, descriptor.SourceID); err != nil { return nil, fmt.Errorf("verify prepared glossary: %w", err) diff --git a/internal/stage/publish_test.go b/internal/stage/publish_test.go index 9d2e0e2..2b42f35 100644 --- a/internal/stage/publish_test.go +++ b/internal/stage/publish_test.go @@ -67,8 +67,7 @@ func TestPublishFailsWhenPrerequisiteNotSucceeded(t *testing.T) { func TestPublishUploadsRunFilesPublishedOutputsAndCurrentPointer(t *testing.T) { env, m, runRoot := publishFixture(t) fake := env.ObjectStore.(*storage.FakeBackend) - lanePath := configurePublishExtractionFixture(t, env, m) - durableBundleRoot := filepath.Dir(filepath.Dir(lanePath)) + configurePublishExtractionFixture(t, env, m) runBundleRoot := filepath.Join(runRoot, "extract", "notarius-output", "notarius-run-1") for rel, contents := range map[string]string{ "index.json": `{"lanes":[]}`, @@ -96,11 +95,11 @@ func TestPublishUploadsRunFilesPublishedOutputsAndCurrentPointer(t *testing.T) { sessionPrefix := m.S3SessionPrefix wantRunUploads := []string{ "analyze/outputs/artifacts/session_recap.md", - "merge/config/seriatim.generated.yml", + "merge/logs/seriatim.generated.yml", "prepare/inputs/session.yml", "prepare/outputs/audio/speaker.flac", - "logs/audita.stderr.log", - "polish/reports/audita.report.json", + "polish/logs/audita.stderr.log", + "polish/logs/report.json", "transcribe/outputs/transcripts/raw/speaker.json", "trim/outputs/transcripts/final.trimmed.json", } @@ -116,12 +115,6 @@ func TestPublishUploadsRunFilesPublishedOutputsAndCurrentPointer(t *testing.T) { t.Fatalf("run-local Notarius bundle member was uploaded at %q", key) } } - for _, upload := range fake.Uploads { - localPath := filepath.Clean(upload.LocalPath) - if localPath == durableBundleRoot || strings.HasPrefix(localPath, durableBundleRoot+string(filepath.Separator)) { - t.Fatalf("durable Notarius bundle member was implicitly uploaded from %q", upload.LocalPath) - } - } trimmedKey := publishOutputRemoteKey(runPrefix, "transcripts/final.trimmed.json") recapKey := publishOutputRemoteKey(runPrefix, "artifacts/session_recap.md") @@ -195,9 +188,9 @@ func TestPublishUploadsPreviousCacheWhenPresent(t *testing.T) { env.Config.Session.Campaign, env.Config.Session.SessionID, ) - writeStageTestFile(t, filepath.Join(sessionRoot, "previous", "manifest.json"), "{\"session_id\":\"2026-04-12\"}\n") - writeStageTestFile(t, filepath.Join(sessionRoot, "previous", "artifacts", "session_recap.md"), "# previous recap\n") - writePublishPreviousManifest(t, filepath.Join(sessionRoot, "previous"), "2026-04-12", filepath.Join(sessionRoot, "previous", "artifacts", "session_recap.md")) + writeStageTestFile(t, filepath.Join(sessionRoot, "inputs", "previous", "manifest.json"), "{\"session_id\":\"2026-04-12\"}\n") + writeStageTestFile(t, filepath.Join(sessionRoot, "inputs", "previous", "artifacts", "session_recap.md"), "# previous recap\n") + writePublishPreviousManifest(t, filepath.Join(sessionRoot, "inputs", "previous"), "2026-04-12", filepath.Join(sessionRoot, "inputs", "previous", "artifacts", "session_recap.md")) result, err := publishStage{}.Run(context.Background(), env, m) if err != nil { @@ -233,7 +226,7 @@ func TestPublishRejectsDeclaredLeafSymlinkBeforeUploading(t *testing.T) { env, m, runRoot := publishFixture(t) sentinel := filepath.Join(t.TempDir(), "outside.txt") writeStageTestFile(t, sentinel, "outside secret\n") - target := filepath.Join(runRoot, "logs", "audita.stderr.log") + target := filepath.Join(runRoot, "polish", "logs", "audita.stderr.log") if err := os.Remove(target); err != nil { t.Fatal(err) } @@ -269,7 +262,7 @@ func TestPublishRejectsDeclaredSourceWithSymlinkedAncestor(t *testing.T) { env, m, runRoot := publishFixture(t) outside := t.TempDir() writeStageTestFile(t, filepath.Join(outside, "audita.stderr.log"), "outside secret\n") - logsDir := filepath.Join(runRoot, "logs") + logsDir := filepath.Join(runRoot, "polish", "logs") if err := os.Rename(logsDir, logsDir+"-original"); err != nil { t.Fatal(err) } @@ -286,7 +279,7 @@ func TestPublishRejectsDeclaredSourceWithSymlinkedAncestor(t *testing.T) { func TestPublishRejectsDeclaredSourceReplacement(t *testing.T) { _, m, runRoot := publishFixture(t) - target := filepath.Join(runRoot, "logs", "audita.stderr.log") + target := filepath.Join(runRoot, "polish", "logs", "audita.stderr.log") checksum, err := artifacts.SHA256File(target) if err != nil { t.Fatal(err) @@ -299,14 +292,14 @@ func TestPublishRejectsDeclaredSourceReplacement(t *testing.T) { writeStageTestFile(t, target, "replacement\n") _, err = openPublishRunFiles(runRoot, files) - if err == nil || !strings.Contains(err.Error(), `source "logs/audita.stderr.log" does not match its declared checksum`) { + if err == nil || !strings.Contains(err.Error(), `source "polish/logs/audita.stderr.log" does not match its declared checksum`) { t.Fatalf("openPublishRunFiles() error = %v, want replacement rejection", err) } } func TestPublishRejectsDeclaredDirectoryBeforeUploading(t *testing.T) { env, m, runRoot := publishFixture(t) - target := filepath.Join(runRoot, "logs", "audita.stderr.log") + target := filepath.Join(runRoot, "polish", "logs", "audita.stderr.log") if err := os.Remove(target); err != nil { t.Fatal(err) } @@ -324,6 +317,11 @@ func TestPublishRejectsDeclaredDirectoryBeforeUploading(t *testing.T) { func TestPublishDoesNotUploadUndeclaredRunFile(t *testing.T) { env, m, runRoot := publishFixture(t) writeStageTestFile(t, filepath.Join(runRoot, "unlisted.txt"), "outside of manifest\n") + writeStageTestFile(t, filepath.Join(runRoot, "polish", "debug", "capture.json"), "private audita capture\n") + writeStageTestFile(t, filepath.Join(runRoot, "extract", "debug", "capture.json"), "private notarius capture\n") + renderDebug := filepath.Join(runRoot, "analyze", "debug", "session_recap.render.json") + writeStageTestFile(t, renderDebug, `{"rendered":true}`) + m.Stages["analyze"].Logs = append(m.Stages["analyze"].Logs, renderDebug) paths := artifacts.NewLocalStore(env.Config.Pipeline.Workspace.Root).SessionPathsFor(m.Campaign, m.SessionID) cacheFile := filepath.Join(artifacts.SessionNotariusReferenceCacheDir(paths), strings.Repeat("a", 64), "party.yml") writeStageTestFile(t, cacheFile, "local Notarius reference cache\n") @@ -335,8 +333,11 @@ func TestPublishDoesNotUploadUndeclaredRunFile(t *testing.T) { if _, exists := fake.Objects[m.S3RunPrefix+"unlisted.txt"]; exists { t.Fatal("undeclared run file was uploaded") } + if _, exists := fake.Objects[m.S3RunPrefix+"analyze/debug/session_recap.render.json"]; !exists { + t.Fatal("declared render diagnostic was not uploaded") + } for _, object := range fake.Objects { - if strings.Contains(string(object.Data), "outside of manifest") || strings.Contains(string(object.Data), "local Notarius reference cache") { + if strings.Contains(string(object.Data), "outside of manifest") || strings.Contains(string(object.Data), "local Notarius reference cache") || strings.Contains(string(object.Data), "private audita capture") || strings.Contains(string(object.Data), "private notarius capture") { t.Fatalf("undeclared or cache bytes were uploaded in %q", object.Key) } } @@ -408,7 +409,7 @@ func TestPublishRejectsDeclaredPreviousSymlinkBeforeUploading(t *testing.T) { env.Config.Session.Campaign, env.Config.Session.SessionID, ), - config.PathPreviousDirSegment, + config.PathInputsDirSegment, config.PathPreviousDirSegment, ) target := filepath.Join(previousDir, "artifacts", "session_recap.md") sentinel := filepath.Join(t.TempDir(), "outside.md") @@ -476,7 +477,6 @@ func TestPublishUploadsExplicitExtractionAndPreservesManifestMetadata(t *testing t.Fatalf("Run() error = %v", err) } fake := env.ObjectStore.(*storage.FakeBackend) - durableBundleRoot := filepath.Dir(filepath.Dir(lanePath)) publishedKey := publishOutputRemoteKey(m.S3RunPrefix, "artifacts/encounters.json") if got := string(fake.Objects[publishedKey].Data); got != `{"encounters":[]}` { t.Fatalf("published extraction = %q", got) @@ -489,12 +489,6 @@ func TestPublishUploadsExplicitExtractionAndPreservesManifestMetadata(t *testing t.Fatalf("Notarius bundle member was implicitly published at %q", key) } } - for _, upload := range fake.Uploads { - localPath := filepath.Clean(upload.LocalPath) - if (localPath == durableBundleRoot || strings.HasPrefix(localPath, durableBundleRoot+string(filepath.Separator))) && localPath != filepath.Clean(lanePath) { - t.Fatalf("durable Notarius bundle member other than selected lane was uploaded from %q", upload.LocalPath) - } - } if result.Metadata["published_files_uploaded"] != 1 { t.Fatalf("published_files_uploaded = %#v, want 1", result.Metadata["published_files_uploaded"]) } @@ -507,12 +501,11 @@ func TestPublishUploadsExplicitExtractionAndPreservesManifestMetadata(t *testing t.Fatalf("unmarshal committed session manifest: %v", err) } extractRecord := current.Stages["extract"] - if extractRecord == nil || len(extractRecord.Outputs) != 2 { + if extractRecord == nil || len(extractRecord.Outputs) != 1 { t.Fatalf("extract record = %#v", extractRecord) } lane := extractRecord.Outputs[0] - if lane.LocalPath != lanePath || lane.Contract == nil || lane.Contract.SchemaID != "encounters" || - lane.ExternalProvenance == nil || lane.ExternalProvenance.RunID != "notarius-run-1" { + if lane.LocalPath != lanePath || lane.ExternalProvenance == nil || lane.ExternalProvenance.ArtifactID != "encounters" || lane.Size != int64(len(`{"encounters":[]}`)) { t.Fatalf("serialized extraction metadata = %#v", lane) } } @@ -1177,9 +1170,9 @@ func publishFixture(t *testing.T) (*Env, *manifest.Manifest, string) { "transcribe/outputs/transcripts/raw/speaker.json": "{}\n", "trim/outputs/transcripts/final.trimmed.json": "{\"segments\":[]}\n", "analyze/outputs/artifacts/session_recap.md": "# recap\n", - "polish/reports/audita.report.json": "{}\n", - "merge/config/seriatim.generated.yml": "key: value\n", - "logs/audita.stderr.log": "stderr\n", + "polish/logs/report.json": "{}\n", + "merge/logs/seriatim.generated.yml": "key: value\n", + "polish/logs/audita.stderr.log": "stderr\n", } { writeStageTestFile(t, filepath.Join(runRoot, filepath.FromSlash(rel)), contents) } @@ -1246,9 +1239,8 @@ func recordPublishRunDiagnostics(m *manifest.Manifest, runRoot string) { m.Stages["transcribe"].Outputs = []manifest.ArtifactRecord{{LocalPath: filepath.Join(runRoot, "transcribe", "outputs", "transcripts", "raw", "speaker.json")}} m.Stages["trim"].Outputs = append(m.Stages["trim"].Outputs, manifest.ArtifactRecord{LocalPath: filepath.Join(runRoot, "trim", "outputs", "transcripts", "final.trimmed.json")}) m.Stages["analyze"].Outputs = append(m.Stages["analyze"].Outputs, manifest.ArtifactRecord{LocalPath: filepath.Join(runRoot, "analyze", "outputs", "artifacts", "session_recap.md")}) - m.Stages["polish"].Outputs = []manifest.ArtifactRecord{{LocalPath: filepath.Join(runRoot, "polish", "reports", "audita.report.json")}} - m.Stages["polish"].Logs = []string{filepath.Join(runRoot, "logs", "audita.stderr.log")} - m.Stages["merge"].GeneratedConfigs = []string{filepath.Join(runRoot, "merge", "config", "seriatim.generated.yml")} + m.Stages["polish"].Logs = []string{filepath.Join(runRoot, "polish", "logs", "report.json"), filepath.Join(runRoot, "polish", "logs", "audita.stderr.log")} + m.Stages["merge"].GeneratedConfigs = []string{filepath.Join(runRoot, "merge", "logs", "seriatim.generated.yml")} } func writePublishPreviousManifest(t *testing.T, previousDir, sessionID string, archivePaths ...string) { @@ -1268,32 +1260,14 @@ func writePublishPreviousManifest(t *testing.T, previousDir, sessionID string, a func configurePublishExtractionFixture(t *testing.T, env *Env, m *manifest.Manifest) string { t.Helper() - env.Config.Pipeline.Notarius = &config.NotariusConfig{ - Enabled: true, PipelineID: "campaign.extract", - Outputs: map[string]config.NotariusOutputConfig{ - "encounters": { - LaneID: "encounters", MediaType: "application/json", SchemaID: "encounters", - SchemaVersion: "1", ModuleKey: "encounters", - }, - }, - } + env.Config.Pipeline.Notarius = &config.NotariusConfig{Enabled: true, PipelineID: "campaign.extract", Outputs: map[string]config.NotariusOutputConfig{"encounters": {LaneID: "encounters"}}} paths := publishSessionPaths(env, m) producerRunID := "extract-run-1" - bundleRoot := filepath.Join(paths.ArtifactsDir, "notarius", producerRunID) - lanePath := filepath.Join(bundleRoot, "lanes", "encounters.json") - indexPath := filepath.Join(bundleRoot, "index.json") - writeStageTestFile(t, lanePath, `{"encounters":[]}`) - writeStageTestFile(t, indexPath, `{"lanes":[]}`) - writeStageTestFile(t, filepath.Join(bundleRoot, "manifest.json"), `{"run_id":"notarius-run-1"}`) - writeStageTestFile(t, filepath.Join(bundleRoot, "rejected.json"), `[]`) - writeStageTestFile(t, filepath.Join(bundleRoot, "warnings.json"), `[]`) - writeStageTestFile(t, filepath.Join(bundleRoot, "pipeline", "chunk-map.json"), `{"chunks":[]}`) - writeStageTestFile(t, filepath.Join(bundleRoot, "unknown", "notes.txt"), "internal bundle note\n") - laneChecksum, err := artifacts.SHA256File(lanePath) - if err != nil { - t.Fatal(err) - } - indexChecksum, err := artifacts.SHA256File(indexPath) + lanePath := filepath.Join(paths.ArtifactsDir, "encounters.json") + content := `{"encounters":[]}` + writeStageTestFile(t, lanePath, content) + writeStageTestFile(t, filepath.Join(paths.Root, "runs", producerRunID, "extract", "notarius-output", "bundle", "manifest.json"), "private bundle") + checksum, err := artifacts.SHA256File(lanePath) if err != nil { t.Fatal(err) } @@ -1303,20 +1277,8 @@ func configurePublishExtractionFixture(t *testing.T, env *Env, m *manifest.Manif } m.Stages["extract"] = &manifest.StageRecord{ Name: "extract", Status: manifest.StatusSucceeded, - Metadata: map[string]any{ - "narratio_run_id": producerRunID, "bundle_root": bundleRoot, - "receipt": map[string]any{"run_id": "notarius-run-1", "pipeline_id": "campaign.extract"}, - "direct_input": input.Metadata(), - }, - Outputs: []manifest.ArtifactRecord{ - { - Kind: "notarius_lane", SourceID: artifacts.ExtractionArtifactSourceID("encounters"), LocalPath: lanePath, - ProducerRunID: producerRunID, Checksum: laneChecksum, - Contract: &artifactmodel.ContractMetadata{MediaType: "application/json", SchemaID: "encounters", SchemaVersion: "1", ModuleKey: "encounters"}, - ExternalProvenance: &artifactmodel.ExternalProvenance{System: "notarius", RunID: "notarius-run-1", PipelineID: "campaign.extract", ArtifactID: "encounters"}, - }, - {Kind: "notarius_index", LocalPath: indexPath, ProducerRunID: producerRunID, Checksum: indexChecksum}, - }, + Metadata: map[string]any{"narratio_run_id": producerRunID, "completion": map[string]any{"pipeline": "campaign.extract"}, "direct_input": input.Metadata()}, + Outputs: []manifest.ArtifactRecord{{Kind: "notarius_lane", SourceID: artifacts.ExtractionArtifactSourceID("encounters"), LocalPath: lanePath, ProducerRunID: producerRunID, Checksum: checksum, Size: int64(len(content)), ExternalProvenance: &artifactmodel.ExternalProvenance{System: "notarius", PipelineID: "campaign.extract", ArtifactID: "encounters"}}}, } return lanePath }