diff --git a/docs/internal/manifest.md b/docs/internal/manifest.md index 42cf9b5..7eb7ac6 100644 --- a/docs/internal/manifest.md +++ b/docs/internal/manifest.md @@ -16,8 +16,16 @@ manifest placement belongs in - remote identity metadata (`s3_bucket`, `s3_session_prefix`, `s3_run_prefix`) - `inputs` records - durable `artifacts` records +- optional versioned `supplied_products` records, keyed by source ID - per-stage `stages` map, including the ordinary cleanup stage record +Supplied records hold a canonical session-relative path, SHA-256 checksum, +byte size, and optional product contract. The manifest store validates their +structure; artifact helpers check the recorded path and actual content. A +separate coverage helper derives transcript work satisfied by valid supplied +transcripts without creating records for absent intermediate products. These +foundations are not yet connected to restore or execution decisions. + Session, campaign, and run identities in local and downloaded manifests must be portable opaque segments. Unsafe legacy identities are rejected with migration guidance rather than being normalized into a different workspace or remote @@ -205,8 +213,8 @@ it promote the saved target record and manifest `updated_at` into live state; it preserves an existing target record's identity and leaves unrelated live stage records in place. -The copy boundary includes stage records, input and artifact slices, aggregate -output/log/configuration slices, and the typed analyze and transcribe +The copy boundary includes stage records, input and artifact slices, supplied +product records, aggregate output/log/configuration slices, and the typed analyze and transcribe collections that callbacks or `LocalStore.Save` may modify. Metadata and other pointer fields remain shared read-only because neither checkpoint callback nor the store mutates them. This is a bounded execution helper, not a general diff --git a/docs/policy/architecture.md b/docs/policy/architecture.md index 8b1f89d..27eb0cb 100644 --- a/docs/policy/architecture.md +++ b/docs/policy/architecture.md @@ -115,10 +115,12 @@ Each stage has one explicit responsibility and declares: - failure behavior. Stages write and validate run-local results before materializing canonical -outputs where that distinction applies. A stage is complete only after its +outputs where that distinction applies. Executed work is complete after its required outputs have been written, validated, and recorded in durable manifest -state. Later stages depend on recorded success and artifact resolution, not -merely on incidental files existing on disk. +state. Validated supplied products recorded in that state can also satisfy work +according to the application's fixed coverage rules. Consumers resolve actual +recorded products; completion does not imply that an absent intermediate file +exists. A failed or interrupted stage must not be presented as successful. Failure should preserve enough local state and diagnostics for inspection, recovery, @@ -154,16 +156,17 @@ adapter and publish metadata. Resume and skip decisions are manifest-driven. Filesystem state may be inspected and validated, but file presence alone does not replace recorded -stage state. Each invocation retains an in-memory command summary and a -run-local workspace identity, but neither is a durable progress ledger. The +stage state or accepted supplied-product records. Each invocation retains an +in-memory command summary and a run-local workspace identity, but neither is a +durable progress ledger. The physical run directory is created on demand only when an executing stage requires it; a fully reused invocation or a cleanup-only invocation does not leave an empty run directory. -Restore treats committed remote current state as its authority. It must plan -deterministically, confine remote-to-local paths, protect local conflicts, and -install the validated session manifest after other restored durable files. The -physical workflow and recovery procedures belong in +Restore treats the pointer-selected publication inventory as its authority. It +must plan deterministically, confine remote-to-local paths, protect local +conflicts, and save a merged local baseline after accepting restored products. +The physical workflow and recovery procedures belong in [Operations](../operations.md). Restore and runner transitions for one session use the same local lock. A @@ -206,8 +209,9 @@ Missing configuration or inspection capabilities are addressed upstream. projections and concrete character-family artifacts as separate domain objects before execution, without modifying configuration. - Resume uses stage- or artifact-owned semantic evidence for observable - result-affecting configuration; overlay identity and an effective digest are - provenance, never blanket cache keys. + result-affecting configuration of locally generated work. Accepted supplied + products do not require historical generation evidence; overlay identity and + an effective digest are provenance, never blanket cache keys. - Session templating remains narrow and deterministic rather than becoming a general configuration language. - Secret values are supplied indirectly and are not persisted in ordinary @@ -234,8 +238,8 @@ and [ADR 0002](../adr/0002-assign-subprocess-content-ownership.md). Artifact resolution is deterministic and manifest-aware. Producers materialize canonical outputs before reporting success, and consumers resolve declared artifact identities rather than infer files from unrelated directory contents. -Configured products become current through validated promotion and manifest -records; directory presence alone never establishes availability. +Configured products become current through validated promotion or accepted +supplied-product records; directory presence alone never establishes availability. Writes, moves, replacements, and deletions must use narrow, explicit, root-confined destinations. Symlinks, traversal, broad roots, and ambiguous diff --git a/docs/roadmap/implementation.md b/docs/roadmap/implementation.md index ec1fb04..f0309bd 100644 --- a/docs/roadmap/implementation.md +++ b/docs/roadmap/implementation.md @@ -115,7 +115,7 @@ part of this work. ## Stage 1: Introduce durable supplied-product records and fixed coverage -Status: Pending +Status: Complete Read `internal/manifest/manifest.go`, manifest validation/store code, `internal/artifactmodel`, and transcript/product registries. diff --git a/internal/artifacts/supplied.go b/internal/artifacts/supplied.go new file mode 100644 index 0000000..04e4a59 --- /dev/null +++ b/internal/artifacts/supplied.go @@ -0,0 +1,80 @@ +package artifacts + +import ( + "fmt" + "os" + "path/filepath" + + "gitea.maximumdirect.net/eric/narratio/internal/artifactpolicy" + "gitea.maximumdirect.net/eric/narratio/internal/manifest" +) + +// ValidateSuppliedProduct checks a recorded product against its current canonical +// location and actual local content. Configured product paths come from the +// current concrete catalog; built-in paths are fixed by the registry. +func ValidateSuppliedProduct(paths SessionPaths, source, canonicalPath string, record manifest.SuppliedProduct) error { + collection := &manifest.SuppliedProductCollection{Version: manifest.SuppliedProductVersion, Products: map[string]manifest.SuppliedProduct{source: record}} + if err := manifest.ValidateSuppliedProducts(collection); err != nil { + return err + } + classified, _ := artifactpolicy.ClassifySource(source) + kind := contentText + if spec, ok := artifactRegistry[source]; ok { + canonicalPath = spec.CanonicalRelPath + kind = spec.ContentKind + } else if classified.Kind == artifactpolicy.SourceKindExtraction { + kind = contentJSON + } + if record.Path != canonicalPath { + return fmt.Errorf("supplied product %q has noncanonical path %q", source, record.Path) + } + path := filepath.Join(paths.Root, filepath.FromSlash(record.Path)) + if err := requireSafeSessionRegularFile(paths.Root, path); err != nil { + return fmt.Errorf("supplied product %q: %w", source, err) + } + info, err := os.Stat(path) + if err != nil { + return err + } + if info.Size() != record.Size { + return fmt.Errorf("supplied product %q: size mismatch", source) + } + if err := validateResolvedContent(path, kind); err != nil { + return fmt.Errorf("supplied product %q: %w", source, err) + } + checksum, err := SHA256File(path) + if err != nil { + return err + } + if checksum != record.Checksum { + return fmt.Errorf("supplied product %q: checksum mismatch", source) + } + return nil +} + +// SuppliedTranscriptCoverage returns transcript work satisfied by valid supplied +// products. It neither records nor creates the intermediate products. +func SuppliedTranscriptCoverage(paths SessionPaths, collection *manifest.SuppliedProductCollection) map[string]bool { + covered := map[string]bool{} + if collection == nil || manifest.ValidateSuppliedProducts(collection) != nil { + return covered + } + for _, entry := range []struct { + source string + stages []string + }{ + {ArtifactTranscriptBase, []string{"transcribe", "merge"}}, + {ArtifactTranscriptPolished, []string{"transcribe", "merge", "polish"}}, + {ArtifactTranscriptFinal, []string{"transcribe", "merge", "polish", "normalize"}}, + {ArtifactTranscriptFinalTrimmed, []string{"transcribe", "merge", "polish", "normalize", "trim"}}, + } { + record, ok := collection.Products[entry.source] + if !ok || ValidateSuppliedProduct(paths, entry.source, "", record) != nil { + continue + } + for _, name := range entry.stages { + covered[name] = true + } + } + return covered +} diff --git a/internal/artifacts/supplied_test.go b/internal/artifacts/supplied_test.go new file mode 100644 index 0000000..38efa59 --- /dev/null +++ b/internal/artifacts/supplied_test.go @@ -0,0 +1,96 @@ +package artifacts + +import ( + "os" + "path/filepath" + "reflect" + "testing" + + "gitea.maximumdirect.net/eric/narratio/internal/manifest" +) + +func TestSuppliedTranscriptCoverage(t *testing.T) { + cases := []struct { + source string + want map[string]bool + }{ + {ArtifactTranscriptBase, map[string]bool{"transcribe": true, "merge": true}}, + {ArtifactTranscriptPolished, map[string]bool{"transcribe": true, "merge": true, "polish": true}}, + {ArtifactTranscriptFinal, map[string]bool{"transcribe": true, "merge": true, "polish": true, "normalize": true}}, + {ArtifactTranscriptFinalTrimmed, map[string]bool{"transcribe": true, "merge": true, "polish": true, "normalize": true, "trim": true}}, + {ArtifactTranscriptFinalMarkdown, map[string]bool{}}, + {ArtifactTranscriptFinalTrimmedMarkdown, map[string]bool{}}, + {ArtifactBoundsSession, map[string]bool{}}, + } + for _, tc := range cases { + t.Run(tc.source, func(t *testing.T) { + paths := SessionPaths{Root: t.TempDir()} + spec := artifactRegistry[tc.source] + path := filepath.Join(paths.Root, filepath.FromSlash(spec.CanonicalRelPath)) + if err := os.MkdirAll(filepath.Dir(path), 0755); err != nil { + t.Fatal(err) + } + content := []byte(`{"segments":[]}`) + if spec.ContentKind == contentText { + content = []byte("transcript") + } + if err := os.WriteFile(path, content, 0600); err != nil { + t.Fatal(err) + } + checksum, err := SHA256File(path) + if err != nil { + t.Fatal(err) + } + products := &manifest.SuppliedProductCollection{Version: manifest.SuppliedProductVersion, Products: map[string]manifest.SuppliedProduct{tc.source: {Path: spec.CanonicalRelPath, Checksum: checksum, Size: int64(len(content))}}} + if got := SuppliedTranscriptCoverage(paths, products); !reflect.DeepEqual(got, tc.want) { + t.Fatalf("coverage %v, want %v", got, tc.want) + } + if err := ValidateSuppliedProduct(paths, tc.source, "", products.Products[tc.source]); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(path, []byte("tampered"), 0600); err != nil { + t.Fatal(err) + } + if got := SuppliedTranscriptCoverage(paths, products); len(got) != 0 { + t.Fatalf("tampered coverage: %v", got) + } + if err := os.Remove(path); err != nil { + t.Fatal(err) + } + if err := ValidateSuppliedProduct(paths, tc.source, "", products.Products[tc.source]); err == nil { + t.Fatal("missing product accepted") + } + }) + } +} + +func TestSuppliedIndependentProducts(t *testing.T) { + paths := SessionPaths{Root: t.TempDir()} + for _, tc := range []struct{ source, path, content string }{ + {ConfiguredArtifactSourceID("summary"), "artifacts/summary.md", "summary"}, + {ExtractionArtifactSourceID("events"), "artifacts/events.json", `{"events":[]}`}, + } { + path := filepath.Join(paths.Root, filepath.FromSlash(tc.path)) + if err := os.MkdirAll(filepath.Dir(path), 0755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(path, []byte(tc.content), 0600); err != nil { + t.Fatal(err) + } + checksum, err := SHA256File(path) + if err != nil { + t.Fatal(err) + } + record := manifest.SuppliedProduct{Path: tc.path, Checksum: checksum, Size: int64(len(tc.content))} + if err := ValidateSuppliedProduct(paths, tc.source, tc.path, record); err != nil { + t.Fatal(err) + } + if err := ValidateSuppliedProduct(paths, tc.source, "artifacts/other", record); err == nil { + t.Fatal("accepted noncanonical product") + } + products := &manifest.SuppliedProductCollection{Version: manifest.SuppliedProductVersion, Products: map[string]manifest.SuppliedProduct{tc.source: record}} + if got := SuppliedTranscriptCoverage(paths, products); len(got) != 0 { + t.Fatalf("independent product coverage: %v", got) + } + } +} diff --git a/internal/manifest/manifest.go b/internal/manifest/manifest.go index 3d7c171..a533e1b 100644 --- a/internal/manifest/manifest.go +++ b/internal/manifest/manifest.go @@ -85,22 +85,23 @@ type SelectedOverlayProvenance struct { // Manifest is the durable run-state record for a session execution. type Manifest struct { - SchemaVersion string `json:"schema_version"` - SessionID string `json:"session_id"` - Campaign string `json:"campaign,omitempty"` - RunID string `json:"run_id,omitempty"` - LocalWorkDir string `json:"local_workdir,omitempty"` - S3Bucket string `json:"s3_bucket,omitempty"` - S3SessionPrefix string `json:"s3_session_prefix,omitempty"` - S3RunPrefix string `json:"s3_run_prefix,omitempty"` - PipelineVersion string `json:"pipeline_version,omitempty"` - EffectiveConfig *EffectiveConfigProvenance `json:"effective_config,omitempty"` - CreatedAt time.Time `json:"created_at"` - UpdatedAt time.Time `json:"updated_at"` - LastError *ErrorRecord `json:"last_error,omitempty"` - Inputs []InputRecord `json:"inputs,omitempty"` - Artifacts []ArtifactRecord `json:"artifacts,omitempty"` - Stages map[string]*StageRecord `json:"stages"` + SchemaVersion string `json:"schema_version"` + SessionID string `json:"session_id"` + Campaign string `json:"campaign,omitempty"` + RunID string `json:"run_id,omitempty"` + LocalWorkDir string `json:"local_workdir,omitempty"` + S3Bucket string `json:"s3_bucket,omitempty"` + S3SessionPrefix string `json:"s3_session_prefix,omitempty"` + S3RunPrefix string `json:"s3_run_prefix,omitempty"` + PipelineVersion string `json:"pipeline_version,omitempty"` + EffectiveConfig *EffectiveConfigProvenance `json:"effective_config,omitempty"` + CreatedAt time.Time `json:"created_at"` + UpdatedAt time.Time `json:"updated_at"` + LastError *ErrorRecord `json:"last_error,omitempty"` + Inputs []InputRecord `json:"inputs,omitempty"` + Artifacts []ArtifactRecord `json:"artifacts,omitempty"` + SuppliedProducts *SuppliedProductCollection `json:"supplied_products,omitempty"` + Stages map[string]*StageRecord `json:"stages"` } // New constructs a new manifest with deterministic timestamps. diff --git a/internal/manifest/store.go b/internal/manifest/store.go index 8a4fa7e..ada5f7e 100644 --- a/internal/manifest/store.go +++ b/internal/manifest/store.go @@ -117,6 +117,9 @@ func (s *LocalStore) Save(ctx context.Context, path string, m *Manifest) error { if err := validateSessionStages(m.Stages); err != nil { return fmt.Errorf("save manifest: %w", err) } + if err := ValidateSuppliedProducts(m.SuppliedProducts); err != nil { + return fmt.Errorf("save manifest: %w", err) + } for name, stage := range m.Stages { normalizeAnalyzeArtifactCollection(stage.AnalyzeArtifacts) if err := validateTranscribeStageState(name, stage.TranscribeStateVersion, stage.TranscribeSpeakers); err != nil { @@ -162,6 +165,9 @@ func validateLoadedManifest(m *Manifest) error { if err := validateSessionStages(m.Stages); err != nil { return err } + if err := ValidateSuppliedProducts(m.SuppliedProducts); err != nil { + return err + } for name, stage := range m.Stages { if err := validateTranscribeStageState(name, stage.TranscribeStateVersion, stage.TranscribeSpeakers); err != nil { return fmt.Errorf("stages.%s: %w", name, err) diff --git a/internal/manifest/supplied.go b/internal/manifest/supplied.go new file mode 100644 index 0000000..3e17c08 --- /dev/null +++ b/internal/manifest/supplied.go @@ -0,0 +1,73 @@ +package manifest + +import ( + "fmt" + + "gitea.maximumdirect.net/eric/narratio/internal/artifactmodel" + "gitea.maximumdirect.net/eric/narratio/internal/artifactpolicy" +) + +// SuppliedProductVersion identifies the supported supplied-product collection. +const SuppliedProductVersion = 1 + +// SuppliedProductCollection records accepted local products independently of execution. +type SuppliedProductCollection struct { + Version int `json:"version"` + Products map[string]SuppliedProduct `json:"products"` +} + +// SuppliedProduct identifies the actual local bytes and their interpretation. +type SuppliedProduct struct { + Path string `json:"path"` + Checksum string `json:"checksum"` + Size int64 `json:"size"` + Contract *artifactmodel.ContractMetadata `json:"contract,omitempty"` +} + +// ValidateSuppliedProducts validates durable record structure, not filesystem content. +func ValidateSuppliedProducts(collection *SuppliedProductCollection) error { + if collection == nil { + return nil + } + if collection.Version != SuppliedProductVersion { + return fmt.Errorf("unsupported supplied product version %d", collection.Version) + } + if collection.Products == nil { + return fmt.Errorf("supplied products are required") + } + for id, record := range collection.Products { + source, err := artifactpolicy.ClassifySource(id) + if err != nil || source.ID != id || source.Kind == artifactpolicy.SourceKindPreviousArtifact { + return fmt.Errorf("invalid supplied product source %q", id) + } + if err := validateCanonicalRelativePath("path", record.Path); err != nil { + return fmt.Errorf("supplied product %q: %w", id, err) + } + if err := validateSHA256("checksum", record.Checksum); err != nil { + return fmt.Errorf("supplied product %q: %w", id, err) + } + if record.Size <= 0 { + return fmt.Errorf("supplied product %q: size must be positive", id) + } + } + return nil +} + +// CloneSuppliedProducts isolates mutable product records and contract metadata. +func CloneSuppliedProducts(collection *SuppliedProductCollection) *SuppliedProductCollection { + if collection == nil { + return nil + } + clone := *collection + if collection.Products != nil { + clone.Products = make(map[string]SuppliedProduct, len(collection.Products)) + for id, record := range collection.Products { + if record.Contract != nil { + contract := *record.Contract + record.Contract = &contract + } + clone.Products[id] = record + } + } + return &clone +} diff --git a/internal/manifest/supplied_test.go b/internal/manifest/supplied_test.go new file mode 100644 index 0000000..9be48c7 --- /dev/null +++ b/internal/manifest/supplied_test.go @@ -0,0 +1,70 @@ +package manifest + +import ( + "context" + "os" + "path/filepath" + "reflect" + "strings" + "testing" + "time" + + "gitea.maximumdirect.net/eric/narratio/internal/artifactmodel" +) + +func TestSuppliedProductsPersistence(t *testing.T) { + ctx := context.Background() + store := &LocalStore{} + path := filepath.Join(t.TempDir(), "manifest.json") + m := New("session", time.Now()) + if err := store.Save(ctx, path, m); err != nil { + t.Fatal(err) + } + data, err := os.ReadFile(path) + if err != nil { + t.Fatal(err) + } + if strings.Contains(string(data), "supplied_products") { + t.Fatal("ordinary manifest contains supplied products") + } + m.SuppliedProducts = &SuppliedProductCollection{Version: SuppliedProductVersion, Products: map[string]SuppliedProduct{ + artifactmodel.SourceTranscriptFinalTrimmed: {Path: artifactmodel.TranscriptPathFinalTrimmed, Checksum: strings.Repeat("a", 64), Size: 42, Contract: &artifactmodel.ContractMetadata{MediaType: "application/json", SchemaID: "example", SchemaVersion: "1"}}, + }} + if err := store.Save(ctx, path, m); err != nil { + t.Fatal(err) + } + loaded, err := store.Load(ctx, path) + if err != nil { + t.Fatal(err) + } + if !reflect.DeepEqual(m.SuppliedProducts, loaded.SuppliedProducts) { + t.Fatalf("round trip: %#v", loaded.SuppliedProducts) + } + cloned := CloneSuppliedProducts(loaded.SuppliedProducts) + rec := cloned.Products[artifactmodel.SourceTranscriptFinalTrimmed] + rec.Contract.MediaType = "changed" + if loaded.SuppliedProducts.Products[artifactmodel.SourceTranscriptFinalTrimmed].Contract.MediaType == "changed" { + t.Fatal("clone shares contract") + } + for _, mutate := range []func(*SuppliedProductCollection){ + func(c *SuppliedProductCollection) { c.Version++ }, + func(c *SuppliedProductCollection) { + r := c.Products[artifactmodel.SourceTranscriptFinalTrimmed] + r.Path = "../escape" + c.Products[artifactmodel.SourceTranscriptFinalTrimmed] = r + }, + func(c *SuppliedProductCollection) { + r := c.Products[artifactmodel.SourceTranscriptFinalTrimmed] + r.Checksum = "bad" + c.Products[artifactmodel.SourceTranscriptFinalTrimmed] = r + }, + } { + candidate := CloneSuppliedProducts(m.SuppliedProducts) + mutate(candidate) + m.SuppliedProducts = candidate + if err := store.Save(ctx, path, m); err == nil { + t.Fatal("saved invalid supplied products") + } + m.SuppliedProducts = CloneSuppliedProducts(loaded.SuppliedProducts) + } +} diff --git a/internal/stage/checkpoint.go b/internal/stage/checkpoint.go index 5d5d932..affeab9 100644 --- a/internal/stage/checkpoint.go +++ b/internal/stage/checkpoint.go @@ -74,6 +74,7 @@ func cloneManifestForCheckpoint(source *manifest.Manifest) *manifest.Manifest { clone := *source clone.Inputs = append([]manifest.InputRecord(nil), source.Inputs...) clone.Artifacts = append([]manifest.ArtifactRecord(nil), source.Artifacts...) + clone.SuppliedProducts = manifest.CloneSuppliedProducts(source.SuppliedProducts) if source.Stages == nil { clone.Stages = nil return &clone