From 93c869525042d834a0d6a9f63411d1e9747e8178 Mon Sep 17 00:00:00 2001 From: Eric Rakestraw Date: Wed, 2 Dec 2026 15:13:04 +0000 Subject: [PATCH] Resolve supplied products from local records --- docs/internal/artifacts.md | 27 +++++--- docs/roadmap/implementation.md | 2 +- internal/artifacts/analyze_evidence.go | 8 +++ internal/artifacts/artifact_resolver.go | 8 +++ internal/artifacts/catalog.go | 1 + internal/artifacts/extraction_catalog.go | 10 +++ internal/artifacts/supplied.go | 50 +++++++++++++++ internal/artifacts/supplied_test.go | 70 +++++++++++++++++++++ internal/stage/extract_resume.go | 5 +- internal/stage/supplied_publication_test.go | 66 +++++++++++++++++++ 10 files changed, 235 insertions(+), 12 deletions(-) create mode 100644 internal/stage/supplied_publication_test.go diff --git a/docs/internal/artifacts.md b/docs/internal/artifacts.md index 4ac2d94..cc30d0b 100644 --- a/docs/internal/artifacts.md +++ b/docs/internal/artifacts.md @@ -71,9 +71,10 @@ lookups remain concrete configured-artifact identities. Family publish policies are likewise expanded into ordinary configured-source publish actions during domain catalog derivation. Configured outputs, including non-executable prerequisites, become available -only when the versioned analyze state identifies a current result whose source, +when the versioned analyze state identifies a current result whose source, contract, canonical configured path, size, and checksum match a confined -no-follow regular file. An incidental canonical file is unavailable, and a +no-follow regular file, or when a supplied record validates against that path +and its bytes. An incidental canonical file is unavailable, and a manifest with an unsupported aggregate-only representation is rejected before catalog construction. Extraction entries are registered from configuration and become available only @@ -89,6 +90,7 @@ Current provenance values: - `generated.current_analyze_run` - `manifest.current_analyze_artifact` +- `manifest.supplied_product` - `manifest.inputs.previous_cache` - `current_session.previous_cache` @@ -96,10 +98,11 @@ Current provenance values: Built-ins: -- resolve only from the current manifest's succeeded registered producer; -- require exactly one output with the registered source ID and output kind, a - safe session-rooted path, producer run ID, canonical checksum, and valid - content; and +- resolve from validated supplied records or the current manifest's succeeded + registered producer; +- for generated products, require exactly one output with the registered source + ID and output kind, a safe session-rooted path, producer run ID, canonical + checksum, and valid content; and - verify the registered checksum against the durable bytes. Incidental files, canonical filenames, duplicate outputs, failed/stale producer records, and malformed evidence are unavailable. @@ -107,9 +110,10 @@ Built-ins: Configured sources (`narratio.artifact.*`): - resolve only through runtime catalog availability; +- accept a validated supplied record without historical analyze evidence; - use the shared typed analyze-evidence inspection in `analyze_evidence.go` for prior current-session results; -- require the supported analyze-state and fingerprint versions, a `current` +- for generated products, require the supported analyze-state and fingerprint versions, a `current` record for the exact configured key and source ID, a complete contract, the configured canonical relative path, positive stored size, and stored checksum matching bytes read from a confined no-follow regular file; and @@ -133,8 +137,11 @@ Prepared stable sources (`narratio.input.*`): Extraction sources (`narratio.extraction.*`): +- accept individually validated supplied products without historical Notarius + metadata or transcript fingerprints; all configured products must be present + to satisfy extraction as a whole; - use the shared product evidence inspection in `extraction_evidence.go`; -- require a current successful extract record with the exact configured source, +- for locally generated products, require a current successful extract record with the exact configured source, Notarius provenance, a confined regular flat product with matching size and checksum, and the current resolved trimmed-transcript identity; @@ -280,8 +287,8 @@ physical layout. - source ID formats are stable contracts; - artifact resolution is deterministic and manifest-aware; -- extraction sources are available only from a compatible successful manifest - record; +- extraction sources require compatible local generation evidence or a valid + supplied-product record; - previous-session source resolution in `analyze` is local-only; - remote current-state key construction remains centralized in artifacts helpers. diff --git a/docs/roadmap/implementation.md b/docs/roadmap/implementation.md index 80ec4ec..e7bcf1e 100644 --- a/docs/roadmap/implementation.md +++ b/docs/roadmap/implementation.md @@ -162,7 +162,7 @@ Validation: `go test ./internal/config ./internal/stage ./internal/doccheck`. ## Stage 3: Resolve supplied built-in and extraction products -Status: Pending +Status: Complete Read `artifact_resolver.go`, `prepared_input.go`, `extraction_evidence.go`, `extraction_input.go`, and catalog/bootstrap code under `internal/artifacts`. diff --git a/internal/artifacts/analyze_evidence.go b/internal/artifacts/analyze_evidence.go index 2c26071..df92602 100644 --- a/internal/artifacts/analyze_evidence.go +++ b/internal/artifacts/analyze_evidence.go @@ -131,6 +131,14 @@ func (c *ArtifactCatalog) HydrateAnalyzeArtifacts( if !ok { continue } + if c.hydrateSuppliedProduct(paths, m, entry.SourceID, definition.OutputPath) { + continue + } + if m != nil && m.SuppliedProducts != nil { + if _, exists := m.SuppliedProducts.Products[entry.SourceID]; exists { + continue + } + } evidence := InspectAnalyzeEvidence(paths, m, entry.ConfiguredKey, definition) if evidence.State != AnalyzeEvidenceCurrent { continue diff --git a/internal/artifacts/artifact_resolver.go b/internal/artifacts/artifact_resolver.go index ae22611..6bc9008 100644 --- a/internal/artifacts/artifact_resolver.go +++ b/internal/artifacts/artifact_resolver.go @@ -187,6 +187,14 @@ func ResolveSessionArtifact(paths SessionPaths, m *manifest.Manifest, source str return ResolvedSessionArtifact{}, err } spec := artifactRegistry[id] + if m != nil && m.SuppliedProducts != nil { + if record, ok := m.SuppliedProducts.Products[id]; ok { + if err := ValidateSuppliedProduct(paths, id, spec.CanonicalRelPath, record); err != nil { + return ResolvedSessionArtifact{}, fmt.Errorf("validate supplied %q: %w", id, err) + } + return ResolvedSessionArtifact{ID: id, Path: filepath.Join(paths.Root, filepath.FromSlash(record.Path)), ProducerStage: spec.ProducerStage, OutputKind: spec.OutputKind, Provenance: ArtifactProvenanceSupplied, Contract: cloneArtifactContract(record.Contract), Checksum: record.Checksum, Size: record.Size}, nil + } + } candidate, err := manifestArtifactCandidate(paths, m, spec) if err != nil { diff --git a/internal/artifacts/catalog.go b/internal/artifacts/catalog.go index 403fffd..da6fc20 100644 --- a/internal/artifacts/catalog.go +++ b/internal/artifacts/catalog.go @@ -15,6 +15,7 @@ const ( ArtifactProvenanceGeneratedCurrentAnalyzeRun = "generated.current_analyze_run" ArtifactProvenanceCurrentAnalyzeManifest = "manifest.current_analyze_artifact" ArtifactProvenanceCurrentExtractManifest = "manifest.current_extract_run" + ArtifactProvenanceSupplied = "manifest.supplied_product" ) // ConfiguredArtifactDefinition describes one configured analyze artifact. diff --git a/internal/artifacts/extraction_catalog.go b/internal/artifacts/extraction_catalog.go index 2aaa09e..ab4454c 100644 --- a/internal/artifacts/extraction_catalog.go +++ b/internal/artifacts/extraction_catalog.go @@ -38,6 +38,11 @@ func (c *ArtifactCatalog) HydrateExtractionArtifactsExcept( if c == nil || m == nil || len(configured) == 0 { return } + for _, entry := range c.ListExtraction() { + if _, ok := configured[entry.ExtractionKey]; ok && !excluded[entry.SourceID] { + c.hydrateSuppliedProduct(paths, m, entry.SourceID, entry.CanonicalRelPath) + } + } input, err := ResolveExtractionInputIdentity(paths, m) if err != nil { return @@ -47,6 +52,11 @@ func (c *ArtifactCatalog) HydrateExtractionArtifactsExcept( return } for sourceID, output := range proof.Outputs { + if m.SuppliedProducts != nil { + if _, exists := m.SuppliedProducts.Products[sourceID]; exists { + continue + } + } _ = c.markAvailableFromExtractManifest( sourceID, output.Path, proof.ProducerRunID, output.Checksum, output.Size, output.Contract, diff --git a/internal/artifacts/supplied.go b/internal/artifacts/supplied.go index 04e4a59..d705169 100644 --- a/internal/artifacts/supplied.go +++ b/internal/artifacts/supplied.go @@ -78,3 +78,53 @@ func SuppliedTranscriptCoverage(paths SessionPaths, collection *manifest.Supplie } return covered } + +// hydrateSuppliedProduct publishes one valid supplied identity to the runtime catalog. +func (c *ArtifactCatalog) hydrateSuppliedProduct(paths SessionPaths, m *manifest.Manifest, source, configuredPath string) bool { + if c == nil || m == nil || m.SuppliedProducts == nil { + return false + } + record, ok := m.SuppliedProducts.Products[source] + if !ok { + return false + } + canonical, err := ProductRelativePath(paths.Root, configuredPath) + if err != nil || ValidateSuppliedProduct(paths, source, canonical, record) != nil { + return false + } + path := filepath.Join(paths.Root, filepath.FromSlash(record.Path)) + if err := c.markAvailable(source, path, ArtifactProvenanceSupplied); err != nil { + return false + } + entry := c.entries[source] + entry.CanonicalRelPath = canonical + entry.Contract = cloneArtifactContract(record.Contract) + entry.Checksum = record.Checksum + entry.Size = record.Size + c.entries[source] = entry + return true +} + +// SuppliedExtractionComplete reports whether every configured extraction product +// is available as a valid supplied product, independent of generation history. +func SuppliedExtractionComplete(paths SessionPaths, m *manifest.Manifest, configured map[string]ExtractionArtifactDefinition) bool { + if m == nil || m.SuppliedProducts == nil || len(configured) == 0 { + return false + } + for key, definition := range configured { + source := ExtractionArtifactSourceID(key) + filename := definition.Filename + if filename == "" { + filename = key + ".json" + } + path, err := ProductRelativePath(paths.Root, filepath.Join("artifacts", filename)) + if err != nil { + return false + } + record, ok := m.SuppliedProducts.Products[source] + if !ok || ValidateSuppliedProduct(paths, source, path, record) != nil { + return false + } + } + return true +} diff --git a/internal/artifacts/supplied_test.go b/internal/artifacts/supplied_test.go index 38efa59..a1909f8 100644 --- a/internal/artifacts/supplied_test.go +++ b/internal/artifacts/supplied_test.go @@ -1,10 +1,13 @@ package artifacts import ( + "context" + "errors" "os" "path/filepath" "reflect" "testing" + "time" "gitea.maximumdirect.net/eric/narratio/internal/manifest" ) @@ -94,3 +97,70 @@ func TestSuppliedIndependentProducts(t *testing.T) { } } } + +func TestSuppliedProductsResolveAfterReload(t *testing.T) { + paths := SessionPaths{Root: t.TempDir()} + m := manifest.New("session", time.Now()) + m.SuppliedProducts = &manifest.SuppliedProductCollection{Version: manifest.SuppliedProductVersion, Products: map[string]manifest.SuppliedProduct{}} + add := func(source, path, content string) { + absolute := filepath.Join(paths.Root, filepath.FromSlash(path)) + if err := os.MkdirAll(filepath.Dir(absolute), 0755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(absolute, []byte(content), 0600); err != nil { + t.Fatal(err) + } + checksum, err := SHA256File(absolute) + if err != nil { + t.Fatal(err) + } + m.SuppliedProducts.Products[source] = manifest.SuppliedProduct{Path: path, Size: int64(len(content)), Checksum: checksum} + } + add(ArtifactTranscriptFinalTrimmed, TranscriptPathFinalTrimmed, `{"segments":[]}`) + add(ArtifactBoundsSession, "artifacts/session_bounds.json", `{}`) + add(ConfiguredArtifactSourceID("summary"), "artifacts/summary.md", "summary") + add(ExtractionArtifactSourceID("events"), "artifacts/events.json", `{"events":[]}`) + store := &manifest.LocalStore{} + manifestPath := filepath.Join(paths.Root, "manifest.json") + if err := store.Save(context.Background(), manifestPath, m); err != nil { + t.Fatal(err) + } + loaded, err := store.Load(context.Background(), manifestPath) + if err != nil { + t.Fatal(err) + } + for _, source := range []string{ArtifactTranscriptFinalTrimmed, ArtifactBoundsSession} { + resolved, err := ResolveSessionArtifact(paths, loaded, source) + if err != nil || resolved.Provenance != ArtifactProvenanceSupplied { + t.Fatalf("resolve %s: %+v %v", source, resolved, err) + } + } + if _, err := ResolveSessionArtifact(paths, loaded, ArtifactTranscriptFinal); !errors.Is(err, ErrSessionArtifactNotFound) { + t.Fatalf("absent intermediate: %v", err) + } + configured := map[string]ConfiguredArtifactDefinition{"summary": {Enabled: true, OutputPath: "artifacts/summary.md"}} + extraction := map[string]ExtractionArtifactDefinition{"events": {Filename: "events.json"}, "npcs": {Filename: "npcs.json"}} + catalog, err := BootstrapRuntimeCatalog(configured, EffectiveArtifactSet{}, extraction) + if err != nil { + t.Fatal(err) + } + catalog.HydrateAnalyzeArtifacts(paths, loaded, configured) + catalog.HydrateExtractionArtifacts(paths, loaded, extraction) + for _, source := range []string{ConfiguredArtifactSourceID("summary"), ExtractionArtifactSourceID("events")} { + resolved, err := ResolveSessionArtifactWithCatalog(paths, loaded, source, catalog) + if err != nil || resolved.Provenance != ArtifactProvenanceSupplied { + t.Fatalf("resolve %s: %+v %v", source, resolved, err) + } + } + if SuppliedExtractionComplete(paths, loaded, extraction) { + t.Fatal("partial extraction reported complete") + } + if _, err := ResolveSessionArtifactWithCatalog(paths, loaded, ExtractionArtifactSourceID("npcs"), catalog); !errors.Is(err, ErrSessionArtifactNotFound) { + t.Fatalf("missing lane: %v", err) + } + add(ExtractionArtifactSourceID("npcs"), "artifacts/npcs.json", `{}`) + loaded.SuppliedProducts = manifest.CloneSuppliedProducts(m.SuppliedProducts) + if !SuppliedExtractionComplete(paths, loaded, extraction) { + t.Fatal("complete supplied extraction not recognized") + } +} diff --git a/internal/stage/extract_resume.go b/internal/stage/extract_resume.go index 2c95d90..6c4b1ce 100644 --- a/internal/stage/extract_resume.go +++ b/internal/stage/extract_resume.go @@ -29,6 +29,10 @@ func (extractStage) ValidateResume(_ context.Context, env *Env, m *manifest.Mani return ResumeValidation{}, fmt.Errorf("extract resume: session ID is required") } paths := sessionPathsForEnv(env, sessionID) + definitions := artifacts.ExtractionDefinitionsFromConfig(cfg) + if artifacts.SuppliedExtractionComplete(paths, m, definitions) { + return Resumable(), nil + } input, err := artifacts.ResolveExtractionInputIdentity(paths, m) if err != nil { return NonResumable("final-trimmed transcript evidence is unavailable or changed"), nil @@ -45,7 +49,6 @@ func (extractStage) ValidateResume(_ context.Context, env *Env, m *manifest.Mani if record == nil || metadataString(record.Metadata, "configuration_fingerprint") != fingerprint { return NonResumable("Notarius invocation contract changed"), nil } - definitions := artifacts.ExtractionDefinitionsFromConfig(cfg) proof := artifacts.InspectExtractionEvidence(paths, m, definitions, input) if proof.State == artifacts.ExtractionEvidenceUnsafe { return ResumeValidation{}, fmt.Errorf("extract resume: %s", proof.Reason) diff --git a/internal/stage/supplied_publication_test.go b/internal/stage/supplied_publication_test.go new file mode 100644 index 0000000..059ff97 --- /dev/null +++ b/internal/stage/supplied_publication_test.go @@ -0,0 +1,66 @@ +package stage + +import ( + "context" + "path/filepath" + "testing" + + "gitea.maximumdirect.net/eric/narratio/internal/artifacts" + "gitea.maximumdirect.net/eric/narratio/internal/manifest" +) + +func TestDiscoverPublicationFromSuppliedProducts(t *testing.T) { + env, m, _ := setupRenderEnv(t) + paths := sessionPathsForEnv(env, m.SessionID) + m.SuppliedProducts = &manifest.SuppliedProductCollection{Version: manifest.SuppliedProductVersion, Products: map[string]manifest.SuppliedProduct{}} + for _, item := range []struct{ source, path, body string }{ + {artifacts.ArtifactTranscriptFinalTrimmed, artifacts.TranscriptPathFinalTrimmed, `{"segments":[]}`}, + {artifacts.ConfiguredArtifactSourceID("summary"), "artifacts/summary.md", "summary"}, + } { + path := filepath.Join(paths.Root, filepath.FromSlash(item.path)) + writeFile(t, path, item.body) + checksum, err := artifacts.SHA256File(path) + if err != nil { + t.Fatal(err) + } + m.SuppliedProducts.Products[item.source] = manifest.SuppliedProduct{Path: item.path, Checksum: checksum, Size: int64(len(item.body))} + } + configured := map[string]artifacts.ConfiguredArtifactDefinition{"summary": {Enabled: true, OutputPath: "artifacts/summary.md"}} + catalog, err := artifacts.BootstrapRuntimeCatalog(configured, artifacts.EffectiveArtifactSet{}, nil) + if err != nil { + t.Fatal(err) + } + catalog.HydrateAnalyzeArtifacts(paths, m, configured) + actions := []PublicationAction{{Source: artifacts.ArtifactTranscriptFinalTrimmed, Selected: true}, {Source: artifacts.ConfiguredArtifactSourceID("summary"), Selected: true}} + found, err := discoverPublishOutputs(paths, m, catalog, actions, nil) + if err != nil { + t.Fatal(err) + } + if len(found) != 2 { + t.Fatalf("found %v", found) + } + for _, product := range found { + if product.Provenance != artifacts.ArtifactProvenanceSupplied { + t.Fatalf("product %+v", product) + } + } +} + +func TestExtractResumeAcceptsSuppliedProductsWithoutHistory(t *testing.T) { + env, m, _ := setupExtractEnv(t) + m.Stages = map[string]*manifest.StageRecord{} + paths := sessionPathsForEnv(env, m.SessionID) + source := artifacts.ExtractionArtifactSourceID("npc_registry") + path := filepath.Join(paths.Root, "artifacts", "npc_registry.json") + body := `{"npcs":[]}` + writeFile(t, path, body) + checksum, err := artifacts.SHA256File(path) + if err != nil { + t.Fatal(err) + } + m.SuppliedProducts = &manifest.SuppliedProductCollection{Version: manifest.SuppliedProductVersion, Products: map[string]manifest.SuppliedProduct{source: {Path: "artifacts/npc_registry.json", Checksum: checksum, Size: int64(len(body))}}} + result, err := (extractStage{}).ValidateResume(context.Background(), env, m) + if err != nil || !result.Resumable { + t.Fatalf("validation %+v: %v", result, err) + } +}