From b5b467292065bb8d169d0445283197c99c369dc1 Mon Sep 17 00:00:00 2001 From: Eric Rakestraw Date: Mon, 30 Nov 2026 02:20:09 +0000 Subject: [PATCH] Reconcile reuse and inspection with native extraction --- docs/roadmap/implementation.md | 8 + .../adapters/notarius/legacy_bundle_test.go | 476 ---------------- .../notarius/native_completion_test.go | 8 +- internal/adapters/notarius/preflight.go | 10 +- internal/adapters/notarius/runner.go | 136 +---- internal/adapters/notarius/subprocess.go | 40 +- internal/adapters/notarius/subprocess_test.go | 532 ++--------------- internal/adapters/subprocess/diagnostics.go | 2 +- internal/app/analyze_artifacts_test.go | 8 +- internal/app/bounded_prerequisites_test.go | 7 +- internal/app/catalog_execution_test.go | 6 +- internal/app/commands_test.go | 22 +- internal/app/extract_lifecycle_test.go | 137 ++--- internal/app/glossary_remediation_test.go | 14 +- internal/app/operator_helpers_test.go | 102 +--- internal/app/operator_inspection_fifo_test.go | 10 +- internal/app/plan_test.go | 1 - .../app/prepared_session_roundtrip_test.go | 8 +- .../provider_credentials_integration_test.go | 30 +- internal/app/restore_plan_test.go | 2 + internal/app/restore_workflow_test.go | 21 +- internal/app/run_control_test.go | 8 +- internal/app/runner_test.go | 35 +- internal/app/semantic_resume_test.go | 15 +- internal/app/session_cli_test.go | 2 - internal/app/substage_progress_test.go | 4 +- internal/artifactpolicy/policy.go | 1 - internal/artifactpolicy/policy_test.go | 4 +- internal/artifacts/catalog.go | 10 +- internal/artifacts/extraction_catalog_test.go | 35 +- internal/artifacts/paths.go | 14 +- internal/artifacts/paths_model_test.go | 3 +- internal/config/artifact_families_test.go | 18 +- internal/config/campaign_config_test.go | 92 +-- internal/config/catalog_derivation_test.go | 2 +- internal/config/config.go | 56 +- internal/config/document_imports_test.go | 21 +- internal/config/glossary_authoring_test.go | 25 +- internal/config/identity_validation_test.go | 2 +- internal/config/load_validate_test.go | 33 +- internal/config/notarius_test.go | 233 ++------ internal/config/party_resolution_test.go | 32 +- internal/config/pipeline_configkit_test.go | 35 +- internal/config/resource_base_test.go | 2 +- internal/config/scriptorium_test.go | 7 +- internal/config/session_defaults_test.go | 56 +- internal/config/session_template_test.go | 7 - internal/config/storage_publish_test.go | 5 - internal/config/validation_duration_test.go | 5 +- internal/stage/extract.go | 10 +- internal/stage/extract_native_test.go | 3 + internal/stage/extract_preflight.go | 2 +- internal/stage/extract_test.go | 539 ++---------------- internal/stage/merge_test.go | 3 +- .../stage/notarius_cache_integration_test.go | 18 +- internal/stage/prepare_test.go | 5 - internal/stage/publish_test.go | 6 +- .../stage/semantic_contracts_delivery_test.go | 17 +- internal/stage/transcribe_test.go | 14 +- 59 files changed, 515 insertions(+), 2444 deletions(-) delete mode 100644 internal/adapters/notarius/legacy_bundle_test.go diff --git a/docs/roadmap/implementation.md b/docs/roadmap/implementation.md index 440f1fa..8d22576 100644 --- a/docs/roadmap/implementation.md +++ b/docs/roadmap/implementation.md @@ -764,6 +764,14 @@ partial delete retry, cleanup-only invocation, and publication authorization. ## Stage 21 — Reconcile reuse, planning, and inspection across the cutover +**Complete.** Commit: `Reconcile reuse and inspection with native extraction`. +Verification: the Go 1.27.4 suite passed with only the maintained-example and +assembled-example tests assigned to Stage 22 excluded. Focused tests also passed +for restored reuse, forced analysis and extraction, bounded execution, +credential sharing, fallback reporting, current extraction evidence, and prepared +session publication. The full suite still identifies the example migrations +scheduled for Stage 22; no legacy-format fallback was added. + **Read:** roadmap verification and existing semantic/invalidation contracts. Entry points: prepare/extract/analyze resume, artifact hydration, session planning, status/validation, configuration persistence, and command result reporting. diff --git a/internal/adapters/notarius/legacy_bundle_test.go b/internal/adapters/notarius/legacy_bundle_test.go deleted file mode 100644 index b6aa51e..0000000 --- a/internal/adapters/notarius/legacy_bundle_test.go +++ /dev/null @@ -1,476 +0,0 @@ -package notarius - -import ( - "fmt" - "path/filepath" - "strings" -) - -type receiptDocument struct { - SchemaVersion string `json:"schema_version"` - RunID string `json:"run_id"` - PipelineID string `json:"pipeline_id"` - OutputDirectory string `json:"output_directory"` - IndexFile string `json:"index_file"` - NormalizedOutputCount *int `json:"normalized_output_count"` - RejectedOutputCount *int `json:"rejected_output_count"` - WarningGroupCount *int `json:"warning_group_count"` - WarningOccurrenceCount *int `json:"warning_occurrence_count"` - DiagnosticGroupCount *int `json:"diagnostic_group_count"` - DiagnosticOccurrenceCount *int `json:"diagnostic_occurrence_count"` - DiagnosticsTruncated *bool `json:"diagnostics_truncated"` - ValidationStatus string `json:"validation_status"` - ValidationSummaries []validationSummaryDocument `json:"validation_summaries"` - DebugDirectory string `json:"debug_directory"` -} - -type validationSummaryDocument struct { - Stage string `json:"stage"` - StepID string `json:"step_id"` - LaneID string `json:"lane_id"` - ModuleKey string `json:"module_key"` - ChunkID string `json:"chunk_id"` - Status string `json:"status"` - RejectingValidators []string `json:"rejecting_validators"` - ReasonCodes []string `json:"reason_codes"` - IncompleteValidators []string `json:"incomplete_validators"` - ProducerAttemptCount *int `json:"producer_attempt_count"` - TerminalAction string `json:"terminal_action"` -} - -func validValidationStatus(value string) bool { - switch value { - case "approved", "rejected", "incomplete": - return true - default: - return false - } -} - -func validateValidationSummaries(documents []validationSummaryDocument) ([]ValidationSummary, error) { - summaries := make([]ValidationSummary, 0, len(documents)) - for _, document := range documents { - if document.Status != "complete" && document.Status != "rejected" && document.Status != "incomplete" { - return nil, fmt.Errorf("notarius validation summary status %q is invalid", document.Status) - } - if document.ProducerAttemptCount == nil || *document.ProducerAttemptCount < 0 || !validTerminalAction(document.TerminalAction) { - return nil, fmt.Errorf("notarius validation summary is missing required fields") - } - summaries = append(summaries, ValidationSummary{ - Stage: document.Stage, StepID: document.StepID, LaneID: document.LaneID, - ModuleKey: document.ModuleKey, ChunkID: document.ChunkID, Status: document.Status, - RejectingValidators: append([]string(nil), document.RejectingValidators...), - ReasonCodes: append([]string(nil), document.ReasonCodes...), - IncompleteValidators: append([]string(nil), document.IncompleteValidators...), - ProducerAttemptCount: *document.ProducerAttemptCount, TerminalAction: document.TerminalAction, - }) - } - return summaries, nil -} - -func validTerminalAction(value string) bool { - switch value { - case "accepted", "reject_output", "warn_continue", "fail_run": - return true - default: - return false - } -} - -func loadReceipt(path, pipelineID string) (Receipt, error) { - var document receiptDocument - if err := decodeBoundedJSON(path, maxReceiptBytes, &document); err != nil { - return Receipt{}, fmt.Errorf("decode notarius receipt: %w", err) - } - if document.SchemaVersion != ReceiptSchemaVersion { - return Receipt{}, fmt.Errorf("unsupported notarius receipt schema version %q", document.SchemaVersion) - } - if strings.TrimSpace(document.RunID) == "" || strings.TrimSpace(document.PipelineID) == "" || - strings.TrimSpace(document.OutputDirectory) == "" || strings.TrimSpace(document.ValidationStatus) == "" || - document.NormalizedOutputCount == nil || - document.RejectedOutputCount == nil || document.WarningGroupCount == nil || - document.WarningOccurrenceCount == nil || document.DiagnosticGroupCount == nil || - document.DiagnosticOccurrenceCount == nil || document.DiagnosticsTruncated == nil { - return Receipt{}, fmt.Errorf("notarius receipt is missing required fields") - } - if document.IndexFile != canonicalIndexFile { - return Receipt{}, fmt.Errorf("notarius receipt index_file %q is incompatible; want %q", document.IndexFile, canonicalIndexFile) - } - if document.PipelineID != pipelineID { - return Receipt{}, fmt.Errorf("notarius receipt pipeline id %q does not match requested pipeline %q", document.PipelineID, pipelineID) - } - if *document.NormalizedOutputCount < 0 || *document.RejectedOutputCount < 0 || - *document.WarningGroupCount < 0 || *document.WarningOccurrenceCount < 0 || - *document.DiagnosticGroupCount < 0 || *document.DiagnosticOccurrenceCount < 0 { - return Receipt{}, fmt.Errorf("notarius receipt counts must be non-negative") - } - if !validValidationStatus(document.ValidationStatus) { - return Receipt{}, fmt.Errorf("notarius receipt validation_status %q is invalid", document.ValidationStatus) - } - validationSummaries, err := validateValidationSummaries(document.ValidationSummaries) - if err != nil { - return Receipt{}, err - } - if !filepath.IsAbs(document.OutputDirectory) { - return Receipt{}, fmt.Errorf("notarius receipt output directory must be absolute") - } - if document.DebugDirectory != "" && !filepath.IsAbs(document.DebugDirectory) { - return Receipt{}, fmt.Errorf("notarius receipt debug directory must be absolute when present") - } - return Receipt{ - SchemaVersion: document.SchemaVersion, - RunID: document.RunID, - PipelineID: document.PipelineID, - OutputDirectory: filepath.Clean(document.OutputDirectory), - IndexFile: document.IndexFile, - NormalizedOutputCount: *document.NormalizedOutputCount, - RejectedOutputCount: *document.RejectedOutputCount, - WarningGroupCount: *document.WarningGroupCount, - WarningOccurrenceCount: *document.WarningOccurrenceCount, - DiagnosticGroupCount: *document.DiagnosticGroupCount, - DiagnosticOccurrenceCount: *document.DiagnosticOccurrenceCount, - DiagnosticsTruncated: *document.DiagnosticsTruncated, - ValidationStatus: document.ValidationStatus, - ValidationSummaries: validationSummaries, - DebugDirectory: document.DebugDirectory, - }, nil -} - -type indexDocument struct { - ManifestFile string `json:"manifest_file"` - OutputFiles *[]laneDocument `json:"output_files"` - RejectedFile string `json:"rejected_file"` - WarningsFile string `json:"warnings_file"` - DiagnosticsFile string `json:"diagnostics_file"` - ChunkMap *pipelineDocument `json:"chunk_map"` - EvidenceContext *pipelineDocument `json:"evidence_context"` -} - -type laneDocument struct { - LaneID string `json:"lane_id"` - File string `json:"file"` - MediaType string `json:"media_type"` - ModuleKey string `json:"module_key"` - SchemaID string `json:"schema_id"` - SchemaName string `json:"schema_name"` - SchemaVersion string `json:"schema_version"` -} - -type pipelineDocument struct { - ArtifactKind string `json:"artifact_kind"` - File string `json:"file"` - MediaType string `json:"media_type"` - SchemaID string `json:"schema_id"` - SchemaName string `json:"schema_name"` - SchemaVersion string `json:"schema_version"` -} - -func loadIndex(bundleRoot, indexPath string) (Index, error) { - var document indexDocument - if err := decodeBoundedJSON(indexPath, maxIndexBytes, &document); err != nil { - return Index{}, fmt.Errorf("decode notarius index: %w", err) - } - for _, field := range []struct { - name string - got string - want string - }{ - {name: "manifest_file", got: document.ManifestFile, want: canonicalManifestFile}, - {name: "rejected_file", got: document.RejectedFile, want: canonicalRejectedFile}, - {name: "warnings_file", got: document.WarningsFile, want: canonicalWarningsFile}, - {name: "diagnostics_file", got: document.DiagnosticsFile, want: canonicalDiagnosticsFile}, - } { - if field.got != field.want { - return Index{}, fmt.Errorf("notarius index %s %q is incompatible; want %q", field.name, field.got, field.want) - } - } - if document.OutputFiles == nil { - return Index{}, fmt.Errorf("notarius index is missing required output_files") - } - - index := Index{ - Path: indexPath, - ManifestFile: document.ManifestFile, - RejectedFile: document.RejectedFile, - WarningsFile: document.WarningsFile, - DiagnosticsFile: document.DiagnosticsFile, - } - var err error - if index.ManifestPath, err = resolveRegularFile(bundleRoot, index.ManifestFile); err != nil { - return Index{}, fmt.Errorf("resolve notarius manifest file: %w", err) - } - if index.RejectedPath, err = resolveRegularFile(bundleRoot, index.RejectedFile); err != nil { - return Index{}, fmt.Errorf("resolve notarius rejection file: %w", err) - } - if index.WarningsPath, err = resolveRegularFile(bundleRoot, index.WarningsFile); err != nil { - return Index{}, fmt.Errorf("resolve notarius warning file: %w", err) - } - if index.DiagnosticsPath, err = resolveRegularFile(bundleRoot, index.DiagnosticsFile); err != nil { - return Index{}, fmt.Errorf("resolve notarius diagnostics file: %w", err) - } - - seenLanes := make(map[string]struct{}, len(*document.OutputFiles)) - for _, lane := range *document.OutputFiles { - if strings.TrimSpace(lane.LaneID) == "" || strings.TrimSpace(lane.File) == "" { - return Index{}, fmt.Errorf("notarius lane descriptors require lane_id and file") - } - if _, exists := seenLanes[lane.LaneID]; exists { - return Index{}, fmt.Errorf("notarius index contains duplicate lane id %q", lane.LaneID) - } - seenLanes[lane.LaneID] = struct{}{} - path, err := resolveRegularFile(bundleRoot, lane.File) - if err != nil { - return Index{}, fmt.Errorf("resolve notarius lane %q file: %w", lane.LaneID, err) - } - index.Lanes = append(index.Lanes, LaneDescriptor{ - LaneID: lane.LaneID, File: lane.File, Path: path, MediaType: lane.MediaType, - ModuleKey: lane.ModuleKey, SchemaID: lane.SchemaID, SchemaName: lane.SchemaName, - SchemaVersion: lane.SchemaVersion, - }) - } - if document.ChunkMap != nil { - index.ChunkMap, err = resolvePipelineDescriptor(bundleRoot, "chunk_map", *document.ChunkMap) - if err != nil { - return Index{}, err - } - } - if document.EvidenceContext != nil { - index.EvidenceContext, err = resolvePipelineDescriptor(bundleRoot, "evidence_context", *document.EvidenceContext) - if err != nil { - return Index{}, err - } - } - return index, nil -} - -func resolvePipelineDescriptor(bundleRoot, label string, document pipelineDocument) (*PipelineDescriptor, error) { - if strings.TrimSpace(document.ArtifactKind) == "" || strings.TrimSpace(document.File) == "" || - strings.TrimSpace(document.MediaType) == "" || strings.TrimSpace(document.SchemaID) == "" || - strings.TrimSpace(document.SchemaName) == "" || strings.TrimSpace(document.SchemaVersion) == "" { - return nil, fmt.Errorf("notarius %s descriptor is missing required fields", label) - } - path, err := resolveRegularFile(bundleRoot, document.File) - if err != nil { - return nil, fmt.Errorf("resolve notarius %s file: %w", label, err) - } - return &PipelineDescriptor{ - ArtifactKind: document.ArtifactKind, File: document.File, Path: path, - MediaType: document.MediaType, SchemaID: document.SchemaID, - SchemaName: document.SchemaName, SchemaVersion: document.SchemaVersion, - }, nil -} - -type rejectionDocument struct { - Rejected *[]struct { - Stage string `json:"stage"` - StepID string `json:"step_id"` - LaneID string `json:"lane_id"` - ModuleKey string `json:"module_key"` - ChunkID string `json:"chunk_id"` - ValidatorName string `json:"validator_name"` - ReasonCode string `json:"reason_code"` - Message string `json:"message"` - } `json:"rejected"` -} - -func loadRejections(path string) ([]RejectionSummary, error) { - var document rejectionDocument - if err := decodeBoundedJSON(path, maxSummaryBytes, &document); err != nil { - return nil, fmt.Errorf("decode notarius rejections: %w", err) - } - if document.Rejected == nil { - return nil, fmt.Errorf("notarius rejection document is missing rejected array") - } - summaries := make([]RejectionSummary, 0, len(*document.Rejected)) - for _, item := range *document.Rejected { - if strings.TrimSpace(item.Stage) == "" || strings.TrimSpace(item.Message) == "" { - return nil, fmt.Errorf("notarius rejection entries require stage and message") - } - summaries = append(summaries, RejectionSummary{ - Stage: item.Stage, StepID: item.StepID, LaneID: item.LaneID, - ModuleKey: item.ModuleKey, ChunkID: item.ChunkID, - ValidatorName: item.ValidatorName, ReasonCode: item.ReasonCode, - }) - } - return summaries, nil -} - -type findingGroupDocument struct { - Disposition string `json:"disposition"` - Category string `json:"category"` - ReasonCode string `json:"reason_code"` - Origin diagnosticOriginDocument `json:"origin"` - OccurrenceCount *int `json:"occurrence_count"` - Samples *[]struct { - Scope string `json:"scope"` - Message string `json:"message"` - ChunkID string `json:"chunk_id"` - ChunkIndex *int `json:"chunk_index"` - } `json:"samples"` - OmittedSampleCount *int `json:"omitted_sample_count"` -} - -type diagnosticOriginDocument struct { - Stage string `json:"stage"` - StepID string `json:"step_id"` - LaneID string `json:"lane_id"` - ModuleKey string `json:"module_key"` - ValidatorKey string `json:"validator_key"` -} - -type warningDocument struct { - SchemaVersion string `json:"schema_version"` - GroupCount *int `json:"group_count"` - OccurrenceCount *int `json:"occurrence_count"` - Groups *[]findingGroupDocument `json:"groups"` -} - -func loadWarnings(path string) ([]WarningSummary, error) { - var document warningDocument - if err := decodeBoundedJSON(path, maxSummaryBytes, &document); err != nil { - return nil, fmt.Errorf("decode notarius warnings: %w", err) - } - if document.SchemaVersion != warningsSchemaVersion || document.GroupCount == nil || - document.OccurrenceCount == nil || document.Groups == nil { - return nil, fmt.Errorf("notarius warning document is missing or incompatible required fields") - } - if *document.GroupCount < 0 || *document.GroupCount > maxWarningGroups || *document.OccurrenceCount < 0 || - *document.GroupCount != len(*document.Groups) { - return nil, fmt.Errorf("notarius warning document counts are inconsistent") - } - summaries := make([]WarningSummary, 0, len(*document.Groups)) - occurrences := 0 - for _, group := range *document.Groups { - if err := validateFindingGroup(group); err != nil { - return nil, fmt.Errorf("notarius warning group: %w", err) - } - if group.Disposition != "warning" { - return nil, fmt.Errorf("notarius warning group disposition %q is invalid", group.Disposition) - } - if *group.OccurrenceCount > int(^uint(0)>>1)-occurrences { - return nil, fmt.Errorf("notarius warning occurrence count overflows") - } - occurrences += *group.OccurrenceCount - summaries = append(summaries, WarningSummary{ - Disposition: group.Disposition, Category: group.Category, ReasonCode: group.ReasonCode, - Origin: diagnosticOrigin(group.Origin), OccurrenceCount: *group.OccurrenceCount, - }) - } - if occurrences != *document.OccurrenceCount { - return nil, fmt.Errorf("notarius warning document occurrence count is inconsistent") - } - return summaries, nil -} - -type diagnosticDocument struct { - SchemaVersion string `json:"schema_version"` - GroupCount *int `json:"group_count"` - OccurrenceCount *int `json:"occurrence_count"` - Truncated *bool `json:"truncated"` - UnrepresentedOccurrenceCount *int `json:"unrepresented_occurrence_count"` - Groups *[]findingGroupDocument `json:"groups"` -} - -func loadDiagnostics(path string) ([]DiagnosticSummary, int, bool, error) { - var document diagnosticDocument - if err := decodeBoundedJSON(path, maxSummaryBytes, &document); err != nil { - return nil, 0, false, fmt.Errorf("decode notarius diagnostics: %w", err) - } - if document.SchemaVersion != diagnosticsSchemaVersion || document.GroupCount == nil || - document.OccurrenceCount == nil || document.Truncated == nil || - document.UnrepresentedOccurrenceCount == nil || document.Groups == nil { - return nil, 0, false, fmt.Errorf("notarius diagnostics document is missing or incompatible required fields") - } - if *document.GroupCount < 0 || *document.GroupCount > maxDiagnosticGroups || *document.OccurrenceCount < 0 || - *document.UnrepresentedOccurrenceCount < 0 || *document.GroupCount != len(*document.Groups) { - return nil, 0, false, fmt.Errorf("notarius diagnostics document counts are inconsistent") - } - if !*document.Truncated && *document.UnrepresentedOccurrenceCount != 0 { - return nil, 0, false, fmt.Errorf("notarius diagnostics document has unrepresented occurrences without truncation") - } - summaries := make([]DiagnosticSummary, 0, len(*document.Groups)) - representedOccurrences := 0 - for _, group := range *document.Groups { - if err := validateFindingGroup(group); err != nil { - return nil, 0, false, fmt.Errorf("notarius diagnostic group: %w", err) - } - if group.Disposition != "advisory" && group.Disposition != "observation" { - return nil, 0, false, fmt.Errorf("notarius diagnostic group disposition %q is invalid", group.Disposition) - } - if *group.OccurrenceCount > int(^uint(0)>>1)-representedOccurrences { - return nil, 0, false, fmt.Errorf("notarius diagnostic occurrence count overflows") - } - representedOccurrences += *group.OccurrenceCount - summaries = append(summaries, DiagnosticSummary{ - Disposition: group.Disposition, Category: group.Category, ReasonCode: group.ReasonCode, - Origin: diagnosticOrigin(group.Origin), OccurrenceCount: *group.OccurrenceCount, - }) - } - if *document.UnrepresentedOccurrenceCount > int(^uint(0)>>1)-representedOccurrences || - representedOccurrences+*document.UnrepresentedOccurrenceCount != *document.OccurrenceCount { - return nil, 0, false, fmt.Errorf("notarius diagnostics document occurrence count is inconsistent") - } - return summaries, *document.OccurrenceCount, *document.Truncated, nil -} - -func validateFindingGroup(group findingGroupDocument) error { - if strings.TrimSpace(group.Disposition) == "" || strings.TrimSpace(group.Category) == "" || - strings.TrimSpace(group.ReasonCode) == "" || !validDiagnosticOriginStage(group.Origin.Stage) || - !validDiagnosticCategory(group.Disposition, group.Category) || - group.OccurrenceCount == nil || *group.OccurrenceCount <= 0 || group.Samples == nil || - group.OmittedSampleCount == nil || *group.OmittedSampleCount < 0 { - return fmt.Errorf("missing required fields") - } - if len(*group.Samples) == 0 || len(*group.Samples) > maxFindingSamples || - *group.OmittedSampleCount != *group.OccurrenceCount-len(*group.Samples) { - return fmt.Errorf("sample counts are inconsistent") - } - for _, sample := range *group.Samples { - if strings.TrimSpace(sample.Scope) == "" || strings.TrimSpace(sample.Message) == "" || - (sample.ChunkIndex != nil && *sample.ChunkIndex < 0) { - return fmt.Errorf("samples require scope and message") - } - } - return nil -} - -func validDiagnosticCategory(disposition, category string) bool { - switch disposition { - case "warning": - return category == "configuration" || category == "degradation" || - category == "validation_incomplete" || category == "fallback" - case "advisory": - return category == "data_quality" - case "observation": - return category == "normalization" - default: - return false - } -} - -func validDiagnosticOriginStage(stage string) bool { - switch stage { - case "references", "chunk", "extract", "merge", "normalize": - return true - default: - return false - } -} - -func diagnosticOrigin(document diagnosticOriginDocument) DiagnosticOrigin { - return DiagnosticOrigin{ - Stage: document.Stage, StepID: document.StepID, LaneID: document.LaneID, - ModuleKey: document.ModuleKey, ValidatorKey: document.ValidatorKey, - } -} - -func sumWarningOccurrences(values []WarningSummary) (int, error) { - total := 0 - for _, value := range values { - if value.OccurrenceCount > int(^uint(0)>>1)-total { - return 0, fmt.Errorf("notarius warning occurrence count overflows") - } - total += value.OccurrenceCount - } - return total, nil -} diff --git a/internal/adapters/notarius/native_completion_test.go b/internal/adapters/notarius/native_completion_test.go index d5b806c..b60e322 100644 --- a/internal/adapters/notarius/native_completion_test.go +++ b/internal/adapters/notarius/native_completion_test.go @@ -25,7 +25,7 @@ func TestNativeCompletionAndInvocation(t *testing.T) { runner := &SubprocessRunner{run: func(_ context.Context, request subprocess.RunRequest) (subprocess.RunResult, error) { args = request.Args document, _ := json.Marshal(map[string]any{"pipeline": req.PipelineID, "artifact_count": 12, "output_directory": bundle, "fallback_count": 3}) - if err := os.WriteFile(req.ReceiptPath, document, 0o600); err != nil { + if err := os.WriteFile(req.ReportPath, document, 0o600); err != nil { t.Fatal(err) } return subprocess.RunResult{}, nil @@ -47,7 +47,7 @@ func TestNativeCompletionRequiresSuccessfulExit(t *testing.T) { req := validRunRequest(t) req.DebugDirectory = filepath.Join(filepath.Dir(req.LogPath), "debug") runner := &SubprocessRunner{run: func(_ context.Context, _ subprocess.RunRequest) (subprocess.RunResult, error) { - if err := os.WriteFile(req.ReceiptPath, []byte(`{"pipeline":"dnd-session","artifact_count":0,"output_directory":"/tmp"}`), 0o600); err != nil { + if err := os.WriteFile(req.ReportPath, []byte(`{"pipeline":"dnd-session","artifact_count":0,"output_directory":"/tmp"}`), 0o600); err != nil { t.Fatal(err) } return subprocess.RunResult{ExitCode: 1}, errors.New("process failed") @@ -71,7 +71,7 @@ func TestNativeCompletionRejectsInvalidReports(t *testing.T) { req := validRunRequest(t) req.DebugDirectory = filepath.Join(filepath.Dir(req.LogPath), "debug") runner := &SubprocessRunner{run: func(_ context.Context, _ subprocess.RunRequest) (subprocess.RunResult, error) { - if err := os.WriteFile(req.ReceiptPath, []byte(test.body), 0o600); err != nil { + if err := os.WriteFile(req.ReportPath, []byte(test.body), 0o600); err != nil { t.Fatal(err) } return subprocess.RunResult{}, nil @@ -97,7 +97,7 @@ func TestNativeInvocationOmitsOptionalControls(t *testing.T) { t.Fatalf("args = %#v, want %#v", request.Args, want) } document, _ := json.Marshal(map[string]any{"pipeline": req.PipelineID, "artifact_count": 0, "output_directory": bundle}) - if err := os.WriteFile(req.ReceiptPath, document, 0o600); err != nil { + if err := os.WriteFile(req.ReportPath, document, 0o600); err != nil { t.Fatal(err) } return subprocess.RunResult{}, nil diff --git a/internal/adapters/notarius/preflight.go b/internal/adapters/notarius/preflight.go index 5179a82..f7ee3b2 100644 --- a/internal/adapters/notarius/preflight.go +++ b/internal/adapters/notarius/preflight.go @@ -66,7 +66,7 @@ func (r *SubprocessRunner) Preflight(ctx context.Context, req ReadinessRequest) } } seenPaths := map[string]bool{} - for _, path := range []string{req.InspectionPath, req.InspectionLogPath, req.ReceiptPath, req.LogPath} { + for _, path := range []string{req.InspectionPath, req.InspectionLogPath, req.ReportPath, req.LogPath} { path = filepath.Clean(path) if seenPaths[path] { return result, fmt.Errorf("notarius readiness report and diagnostic paths must be distinct") @@ -105,9 +105,9 @@ func (r *SubprocessRunner) Preflight(ctx context.Context, req ReadinessRequest) return result, fmt.Errorf("notarius pipeline %q does not define required lane %q", req.PipelineID, required) } } - outcome, runErr := r.run(ctx, subprocess.RunRequest{Executable: req.Binary, Args: runArgs("preflight", req.RunRequest, references), WorkingDir: req.WorkingDirectory, Timeout: req.Timeout, DiagnosticOwner: "notarius preflight", StdoutLogPath: req.ReceiptPath, StderrLogPath: req.LogPath, EnvOverrides: env, SensitiveEnvNames: names}) + outcome, runErr := r.run(ctx, subprocess.RunRequest{Executable: req.Binary, Args: runArgs("preflight", req.RunRequest, references), WorkingDir: req.WorkingDirectory, Timeout: req.Timeout, DiagnosticOwner: "notarius preflight", StdoutLogPath: req.ReportPath, StderrLogPath: req.LogPath, EnvOverrides: env, SensitiveEnvNames: names}) result.ExitCode = outcome.ExitCode - assessment, assessmentErr := loadReadinessAssessment(req.ReceiptPath, req.PipelineID) + assessment, assessmentErr := loadReadinessAssessment(req.ReportPath, req.PipelineID) if assessmentErr == nil { result.AssessmentComplete = true result.Ready, result.Checks, result.DebugDirectory = assessment.Ready, assessment.Checks, assessment.DebugDirectory @@ -158,7 +158,7 @@ func loadPipelineLanes(path, pipelineID string) ([]string, error) { } `json:"lanes"` } `json:"steps"` } - if err := decodeBoundedJSON(path, maxReceiptBytes, &doc); err != nil { + if err := decodeBoundedJSON(path, maxReportBytes, &doc); err != nil { return nil, err } if doc.Pipeline != pipelineID || doc.Steps == nil || !completeInspectedModule(doc.Input) || !completeInspectedModule(doc.Chunk) || !completeInspectedModule(doc.Output) { @@ -189,7 +189,7 @@ func loadReadinessAssessment(path, pipelineID string) (ReadinessResult, error) { Checks *[]ReadinessCheck `json:"checks"` DebugDirectory string `json:"debug_directory"` } - if err := decodeBoundedJSON(path, maxReceiptBytes, &doc); err != nil { + if err := decodeBoundedJSON(path, maxReportBytes, &doc); err != nil { return ReadinessResult{}, err } if doc.Pipeline != pipelineID || doc.Ready == nil || doc.Checks == nil || (doc.DebugDirectory != "" && !filepath.IsAbs(doc.DebugDirectory)) { diff --git a/internal/adapters/notarius/runner.go b/internal/adapters/notarius/runner.go index 6487b3a..beeb5cd 100644 --- a/internal/adapters/notarius/runner.go +++ b/internal/adapters/notarius/runner.go @@ -8,8 +8,6 @@ import ( configkit "go.maximumdirect.net/configkit" ) -const ReceiptSchemaVersion = "notarius.run-result.v2" - // Runner is the adapter boundary for a complete Notarius pipeline invocation. type Runner interface { Run(ctx context.Context, req RunRequest) (RunResult, error) @@ -33,141 +31,23 @@ type RunRequest struct { InputPath string OutputRoot string WorkingDirectory string - ReceiptPath string + ReportPath string LogPath string Timeout time.Duration Cache *string Debug bool DebugDirectory string - Resume bool - ChunkCache string References []ReferenceBinding } -// Receipt is the transport-neutral successful run receipt. -type Receipt struct { - SchemaVersion string - RunID string - PipelineID string - OutputDirectory string - IndexFile string - NormalizedOutputCount int - RejectedOutputCount int - WarningGroupCount int - WarningOccurrenceCount int - DiagnosticGroupCount int - DiagnosticOccurrenceCount int - DiagnosticsTruncated bool - ValidationStatus string - ValidationSummaries []ValidationSummary - DebugDirectory string -} - -// ValidationSummary retains the bounded outcome of one Notarius producer result. -type ValidationSummary struct { - Stage string - StepID string - LaneID string - ModuleKey string - ChunkID string - Status string - RejectingValidators []string - ReasonCodes []string - IncompleteValidators []string - ProducerAttemptCount int - TerminalAction string -} - -// LaneDescriptor identifies one normalized lane payload discovered through the index. -type LaneDescriptor struct { - LaneID string - File string - Path string - MediaType string - ModuleKey string - SchemaID string - SchemaName string - SchemaVersion string -} - -// PipelineDescriptor identifies a pipeline-wide artifact discovered through the index. -type PipelineDescriptor struct { - ArtifactKind string - File string - Path string - MediaType string - SchemaID string - SchemaName string - SchemaVersion string -} - -// Index describes the validated bundle-management and artifact paths. -type Index struct { - Path string - ManifestFile string - ManifestPath string - RejectedFile string - RejectedPath string - WarningsFile string - WarningsPath string - DiagnosticsFile string - DiagnosticsPath string - Lanes []LaneDescriptor - ChunkMap *PipelineDescriptor - EvidenceContext *PipelineDescriptor -} - -// RejectionSummary retains structured rejection identity without free-form messages. -type RejectionSummary struct { - Stage string - StepID string - LaneID string - ModuleKey string - ChunkID string - ValidatorName string - ReasonCode string -} - -// WarningSummary retains structured warning identity without free-form messages. -type WarningSummary struct { - Disposition string - Category string - ReasonCode string - Origin DiagnosticOrigin - OccurrenceCount int -} - -// DiagnosticOrigin identifies the framework-owned pipeline location of a finding. -type DiagnosticOrigin struct { - Stage string - StepID string - LaneID string - ModuleKey string - ValidatorKey string -} - -// DiagnosticSummary retains bounded advisory or observation group metadata. -type DiagnosticSummary struct { - Disposition string - Category string - ReasonCode string - Origin DiagnosticOrigin - OccurrenceCount int -} - -// RunResult describes a successfully decoded and validated Notarius bundle. +// RunResult describes a successfully decoded native completion. type RunResult struct { - Report CompletionReport - Receipt Receipt - Index Index - BundleRoot string - ReceiptPath string - LogPath string - ExitCode int - Duration time.Duration - Rejections []RejectionSummary - Warnings []WarningSummary - Diagnostics []DiagnosticSummary + Report CompletionReport + BundleRoot string + ReportPath string + LogPath string + ExitCode int + Duration time.Duration } // CompletionReport contains facts reported by a successfully completed run. diff --git a/internal/adapters/notarius/subprocess.go b/internal/adapters/notarius/subprocess.go index b24cae0..7b896cd 100644 --- a/internal/adapters/notarius/subprocess.go +++ b/internal/adapters/notarius/subprocess.go @@ -15,21 +15,7 @@ import ( "gitea.maximumdirect.net/eric/narratio/internal/pathsafe" ) -const ( - maxReceiptBytes = 1 << 20 - maxIndexBytes = 4 << 20 - maxSummaryBytes = 4 << 20 - canonicalIndexFile = "index.json" - canonicalManifestFile = "manifest.json" - canonicalRejectedFile = "rejected.json" - canonicalWarningsFile = "warnings.json" - canonicalDiagnosticsFile = "diagnostics.json" - warningsSchemaVersion = "notarius.warnings.v2" - diagnosticsSchemaVersion = "notarius.diagnostics.v1" - maxWarningGroups = 128 - maxDiagnosticGroups = 256 - maxFindingSamples = 3 -) +const maxReportBytes = 1 << 20 type subprocessRun func(context.Context, subprocess.RunRequest) (subprocess.RunResult, error) @@ -64,16 +50,16 @@ func (r *SubprocessRunner) Run(ctx context.Context, req RunRequest) (RunResult, WorkingDir: req.WorkingDirectory, Timeout: req.Timeout, DiagnosticOwner: "notarius", - StdoutLogPath: req.ReceiptPath, + StdoutLogPath: req.ReportPath, StderrLogPath: req.LogPath, EnvOverrides: envOverrides, SensitiveEnvNames: sensitiveEnvNames, }) baseResult := RunResult{ - ReceiptPath: req.ReceiptPath, - LogPath: req.LogPath, - ExitCode: processResult.ExitCode, - Duration: processResult.Duration, + ReportPath: req.ReportPath, + LogPath: req.LogPath, + ExitCode: processResult.ExitCode, + Duration: processResult.Duration, } if err != nil { return baseResult, fmt.Errorf("run notarius pipeline %q: %w", req.PipelineID, err) @@ -81,7 +67,7 @@ func (r *SubprocessRunner) Run(ctx context.Context, req RunRequest) (RunResult, if processResult.ExitCode != 0 { return baseResult, fmt.Errorf("run notarius pipeline %q: exit code %d", req.PipelineID, processResult.ExitCode) } - report, err := loadCompletionReport(req.ReceiptPath, req.PipelineID) + report, err := loadCompletionReport(req.ReportPath, req.PipelineID) if err != nil { return baseResult, err } @@ -128,7 +114,7 @@ func loadCompletionReport(path, pipelineID string) (CompletionReport, error) { DebugDirectory string `json:"debug_directory"` FallbackCount *int `json:"fallback_count"` } - if err := decodeBoundedJSON(path, maxReceiptBytes, &document); err != nil { + if err := decodeBoundedJSON(path, maxReportBytes, &document); err != nil { return CompletionReport{}, fmt.Errorf("decode notarius completion report: %w", err) } if document.Pipeline != pipelineID || document.ArtifactCount == nil || *document.ArtifactCount < 0 || !filepath.IsAbs(document.OutputDirectory) { @@ -165,7 +151,7 @@ func validateRunRequest(req RunRequest) ([]ReferenceBinding, error) { "input": req.InputPath, "output root": req.OutputRoot, "working directory": req.WorkingDirectory, - "receipt": req.ReceiptPath, + "report": req.ReportPath, "log": req.LogPath, "debug directory": req.DebugDirectory, } { @@ -176,8 +162,8 @@ func validateRunRequest(req RunRequest) ([]ReferenceBinding, error) { return nil, fmt.Errorf("notarius %s path must be absolute", label) } } - if filepath.Clean(req.ReceiptPath) == filepath.Clean(req.LogPath) { - return nil, fmt.Errorf("notarius receipt and log paths must be different") + if filepath.Clean(req.ReportPath) == filepath.Clean(req.LogPath) { + return nil, fmt.Errorf("notarius report and log paths must be different") } references := make([]ReferenceBinding, 0, len(req.References)) selectors := make(map[string]struct{}, len(req.References)) @@ -210,8 +196,8 @@ func validateRunRequest(req RunRequest) ([]ReferenceBinding, error) { if err := requireDirectory(req.WorkingDirectory); err != nil { return nil, fmt.Errorf("validate notarius working directory: %w", err) } - if err := validateLogDestination(req.ReceiptPath); err != nil { - return nil, fmt.Errorf("validate notarius receipt path: %w", err) + if err := validateLogDestination(req.ReportPath); err != nil { + return nil, fmt.Errorf("validate notarius report path: %w", err) } if err := validateLogDestination(req.LogPath); err != nil { return nil, fmt.Errorf("validate notarius log path: %w", err) diff --git a/internal/adapters/notarius/subprocess_test.go b/internal/adapters/notarius/subprocess_test.go index 8531364..129f24e 100644 --- a/internal/adapters/notarius/subprocess_test.go +++ b/internal/adapters/notarius/subprocess_test.go @@ -15,109 +15,6 @@ import ( configkit "go.maximumdirect.net/configkit" ) -func TestSubprocessRunnerBuildsExactInvocationAndDiscoversBundle(t *testing.T) { - req := validRunRequest(t) - var captured sharedsubprocess.RunRequest - runner := &SubprocessRunner{run: func(_ context.Context, processReq sharedsubprocess.RunRequest) (sharedsubprocess.RunResult, error) { - captured = processReq - writeValidBundleAndReceipt(t, req, true) - return sharedsubprocess.RunResult{ExitCode: 0, Duration: 2 * time.Second}, nil - }} - - result, err := runner.Run(context.Background(), req) - if err != nil { - t.Fatalf("Run() error = %v", err) - } - wantArgs := []string{ - "run", "dnd-session", "--config", req.ConfigPath, "--input", req.InputPath, - "--output-dir", req.OutputRoot, "--json", - } - if !reflect.DeepEqual(captured.Args, wantArgs) { - t.Fatalf("subprocess args = %#v, want %#v", captured.Args, wantArgs) - } - if captured.Executable != req.Binary || captured.WorkingDir != req.WorkingDirectory || captured.Timeout != req.Timeout { - t.Fatalf("subprocess request = %#v", captured) - } - if captured.StdoutLogPath != req.ReceiptPath || captured.StderrLogPath != req.LogPath { - t.Fatalf("stream paths = stdout %q stderr %q", captured.StdoutLogPath, captured.StderrLogPath) - } - if captured.EnvOverrides != nil { - t.Fatalf("environment overrides = %#v, want inherited environment only", captured.EnvOverrides) - } - for _, arg := range captured.Args { - if arg == "--session-id" { - t.Fatal("subprocess args unexpectedly contain --session-id") - } - } - - if result.Receipt.SchemaVersion != ReceiptSchemaVersion || result.Receipt.RunID != "notarius-run-1" { - t.Fatalf("receipt = %#v", result.Receipt) - } - if len(result.Receipt.ValidationSummaries) != 1 || result.Receipt.ValidationSummaries[0].LaneID != "npc-registry" || - result.Receipt.ValidationSummaries[0].Status != "complete" { - t.Fatalf("validation summaries = %#v", result.Receipt.ValidationSummaries) - } - if len(result.Index.Lanes) != 1 || result.Index.Lanes[0].LaneID != "npc-registry" { - t.Fatalf("lanes = %#v", result.Index.Lanes) - } - if result.Index.ChunkMap == nil || result.Index.ChunkMap.ArtifactKind != "chunk_map" { - t.Fatalf("chunk map = %#v", result.Index.ChunkMap) - } - if result.Index.EvidenceContext == nil || result.Index.EvidenceContext.ArtifactKind != "evidence_context" { - t.Fatalf("evidence context = %#v", result.Index.EvidenceContext) - } - if len(result.Rejections) != 1 || result.Rejections[0].LaneID != "spells" || result.Rejections[0].ReasonCode != "invalid_spell" { - t.Fatalf("rejections = %#v", result.Rejections) - } - if len(result.Warnings) != 1 || result.Warnings[0].Category != "degradation" || result.Warnings[0].ReasonCode != "normalized_name" { - t.Fatalf("warnings = %#v", result.Warnings) - } - if len(result.Diagnostics) != 1 || result.Diagnostics[0].Category != "data_quality" || result.Diagnostics[0].ReasonCode != "low_confidence" { - t.Fatalf("diagnostics = %#v", result.Diagnostics) - } -} - -func TestSubprocessRunnerMapsCacheControlsToArguments(t *testing.T) { - tests := []struct { - name string - resume bool - chunkCache string - want []string - }{ - {name: "resume", resume: true, want: []string{"--resume"}}, - {name: "auto", chunkCache: "auto", want: []string{"--chunk_cache", "auto"}}, - {name: "bypass", chunkCache: "bypass", want: []string{"--chunk_cache", "bypass"}}, - {name: "refresh", chunkCache: "refresh", want: []string{"--chunk_cache", "refresh"}}, - {name: "resume and mode", resume: true, chunkCache: "auto", want: []string{"--resume", "--chunk_cache", "auto"}}, - } - for _, test := range tests { - t.Run(test.name, func(t *testing.T) { - req := validRunRequest(t) - req.Resume = test.resume - req.ChunkCache = test.chunkCache - var captured sharedsubprocess.RunRequest - runner := &SubprocessRunner{run: func(_ context.Context, processReq sharedsubprocess.RunRequest) (sharedsubprocess.RunResult, error) { - captured = processReq - writeValidBundleAndReceipt(t, req, false) - return sharedsubprocess.RunResult{ExitCode: 0}, nil - }} - - if _, err := runner.Run(context.Background(), req); err != nil { - t.Fatalf("Run() error = %v", err) - } - want := []string{ - "run", req.PipelineID, "--config", req.ConfigPath, "--input", req.InputPath, - "--output-dir", req.OutputRoot, - } - want = append(want, test.want...) - want = append(want, "--json") - if !reflect.DeepEqual(captured.Args, want) { - t.Fatalf("subprocess args = %#v, want %#v", captured.Args, want) - } - }) - } -} - func TestSubprocessRunnerMapsConfigOverlayToArgumentPair(t *testing.T) { tests := []struct { name string @@ -138,7 +35,7 @@ func TestSubprocessRunnerMapsConfigOverlayToArgumentPair(t *testing.T) { var captured sharedsubprocess.RunRequest runner := &SubprocessRunner{run: func(_ context.Context, processReq sharedsubprocess.RunRequest) (sharedsubprocess.RunResult, error) { captured = processReq - writeValidBundleAndReceipt(t, req, false) + writeNativeCompletion(t, req, false) return sharedsubprocess.RunResult{ExitCode: 0}, nil }} @@ -147,7 +44,7 @@ func TestSubprocessRunnerMapsConfigOverlayToArgumentPair(t *testing.T) { } flagIndex := -1 for index, arg := range captured.Args { - if arg == "--config-overlay" { + if arg == "--overlay" { flagIndex = index break } @@ -158,8 +55,8 @@ func TestSubprocessRunnerMapsConfigOverlayToArgumentPair(t *testing.T) { } return } - if flagIndex < 0 || flagIndex+2 >= len(captured.Args) || captured.Args[flagIndex+1] != test.value || captured.Args[flagIndex+2] != "--json" { - t.Fatalf("config overlay argument boundary = %#v, want flag, exact value, then --json", captured.Args) + if flagIndex < 0 || flagIndex+2 >= len(captured.Args) || captured.Args[flagIndex+1] != test.value || captured.Args[flagIndex+2] != "--format" { + t.Fatalf("config overlay argument boundary = %#v, want flag, exact value, then --format", captured.Args) } }) } @@ -169,14 +66,14 @@ func TestSubprocessRunnerRejectsInvalidChunkCacheBeforeLaunch(t *testing.T) { for _, mode := range []string{"AUTO", "invalid", " auto "} { t.Run(mode, func(t *testing.T) { req := validRunRequest(t) - req.ChunkCache = mode + req.Cache = &mode started := false runner := &SubprocessRunner{run: func(context.Context, sharedsubprocess.RunRequest) (sharedsubprocess.RunResult, error) { started = true return sharedsubprocess.RunResult{}, nil }} _, err := runner.Run(context.Background(), req) - if err == nil || !strings.Contains(err.Error(), "chunk cache mode") { + if err == nil || !strings.Contains(err.Error(), "cache mode") { t.Fatalf("Run() error = %v, want chunk cache validation failure", err) } if started { @@ -201,7 +98,7 @@ func TestSubprocessRunnerForwardsLoadedCredentialWithoutRereadingEnvironment(t * var captured sharedsubprocess.RunRequest runner := &SubprocessRunner{run: func(_ context.Context, processReq sharedsubprocess.RunRequest) (sharedsubprocess.RunResult, error) { captured = processReq - writeValidBundleAndReceipt(t, req, false) + writeNativeCompletion(t, req, false) return sharedsubprocess.RunResult{ExitCode: 0}, nil }} if _, err := runner.Run(context.Background(), req); err != nil { @@ -214,8 +111,8 @@ func TestSubprocessRunnerForwardsLoadedCredentialWithoutRereadingEnvironment(t * t.Fatalf("sensitive environment names = %#v, want configured reference name", captured.SensitiveEnvNames) } wantArgs := []string{ - "run", req.PipelineID, "--config", req.ConfigPath, "--input", req.InputPath, - "--output-dir", req.OutputRoot, "--json", + "run", req.PipelineID, "--config", req.ConfigPath, "--input-file", req.InputPath, + "--output-dir", req.OutputRoot, "--debug-dir", req.DebugDirectory, "--format", "json", } if !reflect.DeepEqual(captured.Args, wantArgs) { t.Fatalf("subprocess args = %#v, want %#v", captured.Args, wantArgs) @@ -260,7 +157,7 @@ func TestSubprocessRunnerBuildsOrderedReferenceArguments(t *testing.T) { var captured sharedsubprocess.RunRequest runner := &SubprocessRunner{run: func(_ context.Context, processReq sharedsubprocess.RunRequest) (sharedsubprocess.RunResult, error) { captured = processReq - writeValidBundleAndReceipt(t, req, false) + writeNativeCompletion(t, req, false) return sharedsubprocess.RunResult{ExitCode: 0}, nil }} @@ -270,11 +167,12 @@ func TestSubprocessRunnerBuildsOrderedReferenceArguments(t *testing.T) { wantArgs := []string{ "run", req.PipelineID, "--config", req.ConfigPath, - "--input", req.InputPath, + "--input-file", req.InputPath, "--output-dir", req.OutputRoot, + "--debug-dir", req.DebugDirectory, "--reference", "party=" + req.References[0].Path, "--reference", "npc-registry.extract.glossary=" + req.References[1].Path, - "--json", + "--format", "json", } if !reflect.DeepEqual(captured.Args, wantArgs) { t.Fatalf("subprocess args = %#v, want %#v", captured.Args, wantArgs) @@ -352,23 +250,23 @@ func TestSubprocessRunnerUsesMinimalEnvironmentAndSeparatesStreams(t *testing.T) const unrelated = "NARRATIO_NOTARIUS_UNRELATED_PARENT_KEY" req := validRunRequest(t) req.Credentials = []configkit.Secret{*loadTestCredential(t, envName, canary), *loadTestCredential(t, otherName, otherCanary)} - writeValidBundleAndReceipt(t, req, false) - receiptFixture := req.ReceiptPath + ".fixture" - data, err := os.ReadFile(req.ReceiptPath) + writeNativeCompletion(t, req, false) + reportFixture := req.ReportPath + ".fixture" + data, err := os.ReadFile(req.ReportPath) if err != nil { - t.Fatalf("ReadFile(receipt) error = %v", err) + t.Fatalf("ReadFile(report) error = %v", err) } - var receipt map[string]any - if err := json.Unmarshal(data, &receipt); err != nil { - t.Fatalf("decode receipt fixture: %v", err) + var report map[string]any + if err := json.Unmarshal(data, &report); err != nil { + t.Fatalf("decode report fixture: %v", err) } - receipt["credential_echo"] = canary + " " + otherCanary - writeJSONFile(t, receiptFixture, receipt) - if err := os.Remove(req.ReceiptPath); err != nil { - t.Fatalf("Remove(receipt) error = %v", err) + report["credential_echo"] = canary + " " + otherCanary + writeJSONFile(t, reportFixture, report) + if err := os.Remove(req.ReportPath); err != nil { + t.Fatalf("Remove(report) error = %v", err) } - captureDir := filepath.Join(filepath.Dir(req.ReceiptPath), "capture") + captureDir := filepath.Join(filepath.Dir(req.ReportPath), "capture") if err := os.Mkdir(captureDir, 0o755); err != nil { t.Fatalf("Mkdir(capture) error = %v", err) } @@ -389,12 +287,12 @@ if [ -n "$`+unrelated+`" ]; then fi printf '%s\n' "$`+envName+`" >&2 printf '%s\n' "$`+otherName+`" >&2 -cat "$NOTARIUS_RECEIPT_FIXTURE" +cat "$NOTARIUS_REPORT_FIXTURE" `) req.Binary = script t.Setenv("NOTARIUS_CAPTURE_DIR", captureDir) t.Setenv("NOTARIUS_INHERITED_VALUE", "inherited-value") - t.Setenv("NOTARIUS_RECEIPT_FIXTURE", receiptFixture) + t.Setenv("NOTARIUS_REPORT_FIXTURE", reportFixture) t.Setenv(unrelated, "unrelated-parent-credential") if _, err := NewSubprocessRunner().Run(context.Background(), req); err != nil { @@ -404,12 +302,12 @@ cat "$NOTARIUS_RECEIPT_FIXTURE" assertTextFile(t, filepath.Join(captureDir, "environment"), "") assertRedactedCredentialFile(t, req.LogPath, canary) assertRedactedCredentialFile(t, req.LogPath, otherCanary) - receiptBytes, err := os.ReadFile(req.ReceiptPath) + reportBytes, err := os.ReadFile(req.ReportPath) if err != nil { - t.Fatalf("ReadFile(receipt) error = %v", err) + t.Fatalf("ReadFile(report) error = %v", err) } - assertRedactedCredentialBytes(t, receiptBytes, canary) - assertRedactedCredentialBytes(t, receiptBytes, otherCanary) + assertRedactedCredentialBytes(t, reportBytes, canary) + assertRedactedCredentialBytes(t, reportBytes, otherCanary) } func TestSubprocessRunnerRedactsCredentialOnProcessFailure(t *testing.T) { @@ -432,8 +330,8 @@ exit 7 if strings.Contains(err.Error(), canary) || strings.Contains(err.Error(), otherCanary) || !strings.Contains(err.Error(), "") { t.Fatal("process failure did not return redacted diagnostics") } - assertRedactedCredentialFile(t, req.ReceiptPath, canary) - assertRedactedCredentialFile(t, req.ReceiptPath, otherCanary) + assertRedactedCredentialFile(t, req.ReportPath, canary) + assertRedactedCredentialFile(t, req.ReportPath, otherCanary) assertRedactedCredentialFile(t, req.LogPath, canary) assertRedactedCredentialFile(t, req.LogPath, otherCanary) } @@ -446,7 +344,7 @@ func TestSubprocessRunnerReturnsProcessFailuresWithoutParsingStdout(t *testing.T cancel bool want string }{ - {name: "nonzero", scriptBody: "printf '{malformed receipt'; printf 'failed\\n' >&2; exit 7\n", timeout: time.Second, want: "exit code 7"}, + {name: "nonzero", scriptBody: "printf '{malformed report'; printf 'failed\\n' >&2; exit 7\n", timeout: time.Second, want: "exit code 7"}, {name: "timeout", scriptBody: "sleep 5\n", timeout: 20 * time.Millisecond, want: "timed out"}, {name: "cancellation", scriptBody: "sleep 5\n", timeout: time.Second, cancel: true, want: "canceled"}, } @@ -469,17 +367,17 @@ func TestSubprocessRunnerReturnsProcessFailuresWithoutParsingStdout(t *testing.T if err == nil || !strings.Contains(err.Error(), test.want) { t.Fatalf("Run() error = %v, want fragment %q", err, test.want) } - if strings.Contains(err.Error(), "decode notarius receipt") { + if strings.Contains(err.Error(), "decode notarius report") { t.Fatalf("Run() parsed stdout after process failure: %v", err) } }) } } -func TestSubprocessRunnerReturnsSharedSubprocessErrorWithoutReadingReceipt(t *testing.T) { +func TestSubprocessRunnerReturnsSharedSubprocessErrorWithoutReadingReport(t *testing.T) { req := validRunRequest(t) - if err := os.WriteFile(req.ReceiptPath, []byte("not json"), 0o644); err != nil { - t.Fatalf("WriteFile(receipt) error = %v", err) + if err := os.WriteFile(req.ReportPath, []byte("not json"), 0o644); err != nil { + t.Fatalf("WriteFile(report) error = %v", err) } wantErr := errors.New("process failed") runner := &SubprocessRunner{run: func(context.Context, sharedsubprocess.RunRequest) (sharedsubprocess.RunResult, error) { @@ -490,77 +388,7 @@ func TestSubprocessRunnerReturnsSharedSubprocessErrorWithoutReadingReceipt(t *te t.Fatalf("Run() error = %v, want wrapped process error", err) } if strings.Contains(err.Error(), "decode") { - t.Fatalf("Run() parsed receipt after failure: %v", err) - } -} - -func TestLoadReceiptValidation(t *testing.T) { - root := t.TempDir() - valid := map[string]any{ - "schema_version": ReceiptSchemaVersion, "run_id": "run-1", "pipeline_id": "pipeline-1", - "output_directory": filepath.Join(root, "outputs", "run-1"), "index_file": "index.json", - "normalized_output_count": 1, "rejected_output_count": 0, - "warning_group_count": 0, "warning_occurrence_count": 0, - "diagnostic_group_count": 0, "diagnostic_occurrence_count": 0, - "diagnostics_truncated": false, "validation_status": "approved", "future_field": true, - } - tests := []struct { - name string - mutate func(map[string]any) - raw []byte - wantOK bool - wantError string - }{ - {name: "unknown fields tolerated", wantOK: true}, - {name: "malformed", raw: []byte("{")}, - {name: "unsupported version", mutate: func(v map[string]any) { v["schema_version"] = "notarius.run-result.v1" }}, - {name: "missing field", mutate: func(v map[string]any) { delete(v, "run_id") }}, - {name: "pipeline mismatch", mutate: func(v map[string]any) { v["pipeline_id"] = "other" }}, - {name: "relative output", mutate: func(v map[string]any) { v["output_directory"] = "run-1" }}, - {name: "negative count", mutate: func(v map[string]any) { v["warning_group_count"] = -1 }}, - {name: "invalid validation status", mutate: func(v map[string]any) { v["validation_status"] = "valid" }}, - { - name: "nested index", mutate: func(v map[string]any) { v["index_file"] = "nested/index.json" }, - wantError: `index_file "nested/index.json"`, - }, - { - name: "cleanable index", mutate: func(v map[string]any) { v["index_file"] = "./index.json" }, - wantError: `index_file "./index.json"`, - }, - } - for _, test := range tests { - t.Run(test.name, func(t *testing.T) { - path := filepath.Join(root, strings.ReplaceAll(test.name, " ", "-")+".json") - values := cloneMap(valid) - if test.mutate != nil { - test.mutate(values) - } - if test.raw != nil { - if err := os.WriteFile(path, test.raw, 0o644); err != nil { - t.Fatalf("WriteFile() error = %v", err) - } - } else { - writeJSONFile(t, path, values) - } - _, err := loadReceipt(path, "pipeline-1") - if test.wantOK && err != nil { - t.Fatalf("loadReceipt() error = %v", err) - } - if !test.wantOK && err == nil { - t.Fatal("loadReceipt() error = nil, want validation failure") - } - if test.wantError != "" && !strings.Contains(err.Error(), test.wantError) { - t.Fatalf("loadReceipt() error = %v, want fragment %q", err, test.wantError) - } - }) - } - - oversized := filepath.Join(root, "oversized.json") - if err := os.WriteFile(oversized, []byte(strings.Repeat("x", maxReceiptBytes+1)), 0o644); err != nil { - t.Fatalf("WriteFile(oversized) error = %v", err) - } - if _, err := loadReceipt(oversized, "pipeline-1"); err == nil || !strings.Contains(err.Error(), "exceeds") { - t.Fatalf("loadReceipt(oversized) error = %v", err) + t.Fatalf("Run() parsed report after failure: %v", err) } } @@ -598,160 +426,6 @@ func TestValidateBundleRootRejectsEscapesAndSymlinks(t *testing.T) { } } -func TestLoadIndexRejectsMalformedUnsafeAndUnsupportedDocuments(t *testing.T) { - tests := []struct { - name string - indexValue any - prepare func(*testing.T, string) - wantError string - }{ - {name: "malformed", indexValue: json.RawMessage(`{"manifest_file":`)}, - {name: "unsupported output shape", indexValue: map[string]any{"manifest_file": "manifest.json", "output_files": map[string]any{}, "rejected_file": "rejected.json", "warnings_file": "warnings.json"}}, - {name: "missing management path", indexValue: map[string]any{"output_files": []any{}, "rejected_file": "rejected.json", "warnings_file": "warnings.json"}}, - {name: "renamed manifest", indexValue: func() any { - value := validIndexValue([]any{}) - value["manifest_file"] = "metadata.json" - return value - }(), wantError: `manifest_file "metadata.json"`}, - {name: "cleanable manifest", indexValue: func() any { - value := validIndexValue([]any{}) - value["manifest_file"] = "./manifest.json" - return value - }(), wantError: `manifest_file "./manifest.json"`}, - {name: "renamed rejections", indexValue: func() any { - value := validIndexValue([]any{}) - value["rejected_file"] = "rejections.json" - return value - }(), wantError: `rejected_file "rejections.json"`}, - {name: "renamed warnings", indexValue: func() any { - value := validIndexValue([]any{}) - value["warnings_file"] = "diagnostics/warnings.json" - return value - }(), wantError: `warnings_file "diagnostics/warnings.json"`}, - {name: "duplicate lane", indexValue: validIndexValue([]any{ - map[string]any{"lane_id": "npc", "file": "lanes/npc.json"}, - map[string]any{"lane_id": "npc", "file": "lanes/npc.json"}, - })}, - {name: "absolute logical path", indexValue: validIndexValue([]any{map[string]any{"lane_id": "npc", "file": "/tmp/npc.json"}})}, - {name: "lexical traversal", indexValue: validIndexValue([]any{map[string]any{"lane_id": "npc", "file": "../outside.json"}})}, - {name: "root prefix confusion", indexValue: validIndexValue([]any{map[string]any{"lane_id": "npc", "file": "../bundle-other/npc.json"}})}, - {name: "file symlink", indexValue: validIndexValue([]any{map[string]any{"lane_id": "npc", "file": "lanes/npc.json"}}), prepare: func(t *testing.T, bundle string) { - if err := os.Symlink(filepath.Join(bundle, "manifest.json"), filepath.Join(bundle, "lanes", "npc.json")); err != nil { - t.Skipf("Symlink() unavailable: %v", err) - } - }}, - {name: "directory symlink", indexValue: validIndexValue([]any{map[string]any{"lane_id": "npc", "file": "linked/npc.json"}}), prepare: func(t *testing.T, bundle string) { - if err := os.Symlink(filepath.Join(bundle, "lanes"), filepath.Join(bundle, "linked")); err != nil { - t.Skipf("Symlink() unavailable: %v", err) - } - }}, - {name: "missing management file", indexValue: validIndexValue([]any{}), prepare: func(t *testing.T, bundle string) { - if err := os.Remove(filepath.Join(bundle, "manifest.json")); err != nil { - t.Fatalf("Remove(manifest) error = %v", err) - } - }}, - {name: "incomplete pipeline descriptor", indexValue: func() any { - value := validIndexValue([]any{}) - value["chunk_map"] = map[string]any{"artifact_kind": "chunk_map", "file": "chunk-map.json"} - return value - }()}, - {name: "pipeline descriptor escape", indexValue: func() any { - value := validIndexValue([]any{}) - value["evidence_context"] = map[string]any{ - "artifact_kind": "evidence_context", "file": "../evidence.json", "media_type": "application/json", - "schema_id": "evidence", "schema_name": "Evidence", "schema_version": "v1", - } - return value - }()}, - } - for _, test := range tests { - t.Run(test.name, func(t *testing.T) { - bundle := createBundleSkeleton(t) - indexPath := filepath.Join(bundle, "index.json") - if raw, ok := test.indexValue.(json.RawMessage); ok { - if err := os.WriteFile(indexPath, raw, 0o644); err != nil { - t.Fatalf("WriteFile(index) error = %v", err) - } - } else { - writeJSONFile(t, indexPath, test.indexValue) - } - if test.prepare != nil { - test.prepare(t, bundle) - } - if _, err := loadIndex(bundle, indexPath); err == nil { - t.Fatal("loadIndex() error = nil, want failure") - } else if test.wantError != "" && !strings.Contains(err.Error(), test.wantError) { - t.Fatalf("loadIndex() error = %v, want fragment %q", err, test.wantError) - } - }) - } - - bundle := createBundleSkeleton(t) - oversizedIndex := filepath.Join(bundle, "index.json") - if err := os.WriteFile(oversizedIndex, []byte(strings.Repeat("x", maxIndexBytes+1)), 0o644); err != nil { - t.Fatalf("WriteFile(oversized index) error = %v", err) - } - if _, err := loadIndex(bundle, oversizedIndex); err == nil || !strings.Contains(err.Error(), "exceeds") { - t.Fatalf("loadIndex(oversized) error = %v", err) - } -} - -func TestLoadDiagnosticSummariesValidateBoundsAndTolerateUnknownFields(t *testing.T) { - root := t.TempDir() - rejectedPath := filepath.Join(root, "rejected.json") - warningsPath := filepath.Join(root, "warnings.json") - diagnosticsPath := filepath.Join(root, "diagnostics.json") - writeJSONFile(t, rejectedPath, map[string]any{"rejected": []any{map[string]any{ - "stage": "validate", "lane_id": "spells", "reason_code": "invalid", "message": "do not retain this", "future": true, - }}, "future": true}) - writeJSONFile(t, warningsPath, findingEnvelope(warningsSchemaVersion, []any{findingGroup("warning", "degradation", "bounded", "normalize", 2)}, 2, false, 0)) - writeJSONFile(t, diagnosticsPath, findingEnvelope(diagnosticsSchemaVersion, []any{findingGroup("advisory", "data_quality", "low_confidence", "normalize", 3)}, 4, true, 1)) - rejections, err := loadRejections(rejectedPath) - if err != nil || len(rejections) != 1 || rejections[0].ReasonCode != "invalid" { - t.Fatalf("loadRejections() = %#v, %v", rejections, err) - } - warnings, err := loadWarnings(warningsPath) - if err != nil || len(warnings) != 1 || warnings[0].Category != "degradation" || warnings[0].OccurrenceCount != 2 { - t.Fatalf("loadWarnings() = %#v, %v", warnings, err) - } - diagnostics, occurrences, truncated, err := loadDiagnostics(diagnosticsPath) - if err != nil || len(diagnostics) != 1 || occurrences != 4 || !truncated || diagnostics[0].Category != "data_quality" { - t.Fatalf("loadDiagnostics() = %#v, %d, %t, %v", diagnostics, occurrences, truncated, err) - } - - for name, path := range map[string]string{"rejections": rejectedPath, "warnings": warningsPath, "diagnostics": diagnosticsPath} { - t.Run("malformed "+name, func(t *testing.T) { - if err := os.WriteFile(path, []byte("{"), 0o644); err != nil { - t.Fatalf("WriteFile() error = %v", err) - } - var err error - if name == "rejections" { - _, err = loadRejections(path) - } else if name == "warnings" { - _, err = loadWarnings(path) - } else { - _, _, _, err = loadDiagnostics(path) - } - if err == nil { - t.Fatal("summary decoder error = nil") - } - }) - } - oversized := filepath.Join(root, "oversized.json") - if err := os.WriteFile(oversized, []byte(strings.Repeat("x", maxSummaryBytes+1)), 0o644); err != nil { - t.Fatalf("WriteFile(oversized) error = %v", err) - } - if _, err := loadWarnings(oversized); err == nil || !strings.Contains(err.Error(), "exceeds") { - t.Fatalf("loadWarnings(oversized) error = %v", err) - } - if _, err := loadRejections(oversized); err == nil || !strings.Contains(err.Error(), "exceeds") { - t.Fatalf("loadRejections(oversized) error = %v", err) - } - if _, _, _, err := loadDiagnostics(oversized); err == nil || !strings.Contains(err.Error(), "exceeds") { - t.Fatalf("loadDiagnostics(oversized) error = %v", err) - } -} - func TestFakeRunnerCapturesRequestsAndHonorsContextAndError(t *testing.T) { profile := "testing" req := RunRequest{PipelineID: "pipeline", ConfigOverlay: &profile, References: []ReferenceBinding{{Selector: "party", Path: "/references/party.json"}}} @@ -805,8 +479,8 @@ func validRunRequest(t *testing.T) RunRequest { return RunRequest{ Binary: "notarius", ConfigPath: configPath, PipelineID: "dnd-session", InputPath: inputPath, OutputRoot: outputRoot, WorkingDirectory: workingDirectory, - ReceiptPath: filepath.Join(diagnostics, "receipt.json"), LogPath: filepath.Join(diagnostics, "stderr.log"), - Timeout: time.Second, + ReportPath: filepath.Join(diagnostics, "report.json"), LogPath: filepath.Join(diagnostics, "stderr.log"), + Timeout: time.Second, DebugDirectory: filepath.Join(diagnostics, "debug"), } } @@ -840,131 +514,23 @@ func assertRedactedCredentialBytes(t *testing.T, data []byte, canary string) { } } -func TestValidateValidationSummariesAcceptsReusedProducerWithoutAttempts(t *testing.T) { - zero := 0 - summaries, err := validateValidationSummaries([]validationSummaryDocument{{ - Stage: "chunk", Status: "complete", ProducerAttemptCount: &zero, TerminalAction: "accepted", - }}) - if err != nil { - t.Fatalf("validateValidationSummaries() error = %v", err) - } - if len(summaries) != 1 || summaries[0].ProducerAttemptCount != 0 { - t.Fatalf("summaries = %#v, want one reused producer with zero attempts", summaries) - } - - negative := -1 - if _, err := validateValidationSummaries([]validationSummaryDocument{{ - Stage: "chunk", Status: "complete", ProducerAttemptCount: &negative, TerminalAction: "accepted", - }}); err == nil { - t.Fatal("validateValidationSummaries() negative producer attempts error = nil") - } -} - -func writeValidBundleAndReceipt(t *testing.T, req RunRequest, includeUnknown bool) { +func writeNativeCompletion(t *testing.T, req RunRequest, _ bool) { t.Helper() - bundle := filepath.Join(req.OutputRoot, "notarius-run-1") - if err := os.MkdirAll(filepath.Join(bundle, "lanes"), 0o755); err != nil { - t.Fatalf("MkdirAll(bundle) error = %v", err) + bundle := filepath.Join(req.OutputRoot, "bundle") + if err := os.MkdirAll(bundle, 0755); err != nil { + t.Fatal(err) } - for path, data := range map[string]string{ - "manifest.json": `{}`, - "lanes/npc.json": `{}`, - "chunk-map.json": `{}`, - "evidence-context.json": `{}`, - } { - if err := os.WriteFile(filepath.Join(bundle, filepath.FromSlash(path)), []byte(data), 0o644); err != nil { - t.Fatalf("WriteFile(%q) error = %v", path, err) - } - } - rejection := map[string]any{"stage": "validate", "lane_id": "spells", "reason_code": "invalid_spell", "message": strings.Repeat("external detail", 20)} - if includeUnknown { - rejection["future"] = true - } - writeJSONFile(t, filepath.Join(bundle, "rejected.json"), map[string]any{"rejected": []any{rejection}, "future": true}) - writeJSONFile(t, filepath.Join(bundle, "warnings.json"), findingEnvelope(warningsSchemaVersion, []any{findingGroup("warning", "degradation", "normalized_name", "normalize", 2)}, 2, false, 0)) - writeJSONFile(t, filepath.Join(bundle, "diagnostics.json"), findingEnvelope(diagnosticsSchemaVersion, []any{findingGroup("advisory", "data_quality", "low_confidence", "normalize", 3)}, 4, true, 1)) - index := validIndexValue([]any{map[string]any{ - "lane_id": "npc-registry", "file": "lanes/npc.json", "media_type": "application/json", - "module_key": "dnd/npc-registry", "schema_id": "notarius.dnd.npc_registry", - "schema_name": "NPCRegistry", "schema_version": "v1", "future": true, - }}) - index["chunk_map"] = map[string]any{ - "artifact_kind": "chunk_map", "file": "chunk-map.json", "media_type": "application/json", - "schema_id": "notarius.chunk_map", "schema_name": "ChunkMap", "schema_version": "v1", "future": true, - } - index["evidence_context"] = map[string]any{ - "artifact_kind": "evidence_context", "file": "evidence-context.json", "media_type": "application/json", - "schema_id": "notarius.evidence_context", "schema_name": "EvidenceContext", "schema_version": "v1", "future": true, - } - index["future"] = true - writeJSONFile(t, filepath.Join(bundle, "index.json"), index) - receipt := map[string]any{ - "schema_version": ReceiptSchemaVersion, "run_id": "notarius-run-1", "pipeline_id": req.PipelineID, - "output_directory": bundle, "index_file": "index.json", "normalized_output_count": 1, - "rejected_output_count": 1, "warning_group_count": 1, "warning_occurrence_count": 2, - "diagnostic_group_count": 1, "diagnostic_occurrence_count": 4, - "diagnostics_truncated": true, "validation_status": "rejected", - "validation_summaries": []any{map[string]any{ - "stage": "normalize", "lane_id": "npc-registry", "status": "complete", - "producer_attempt_count": 1, "terminal_action": "accepted", - }}, - } - if includeUnknown { - receipt["future"] = true - } - writeJSONFile(t, req.ReceiptPath, receipt) -} - -func createBundleSkeleton(t *testing.T) string { - t.Helper() - bundle := filepath.Join(t.TempDir(), "bundle") - if err := os.MkdirAll(filepath.Join(bundle, "lanes"), 0o755); err != nil { - t.Fatalf("MkdirAll(bundle) error = %v", err) - } - for _, name := range []string{"manifest.json", "rejected.json", "warnings.json", "diagnostics.json", "lanes/npc.json", "chunk-map.json"} { - if err := os.WriteFile(filepath.Join(bundle, filepath.FromSlash(name)), []byte("{}"), 0o644); err != nil { - t.Fatalf("WriteFile(%q) error = %v", name, err) - } - } - return bundle -} - -func validIndexValue(lanes []any) map[string]any { - return map[string]any{ - "manifest_file": "manifest.json", "output_files": lanes, - "rejected_file": "rejected.json", "warnings_file": "warnings.json", "diagnostics_file": "diagnostics.json", - } -} - -func findingGroup(disposition, category, reasonCode, origin string, occurrences int) map[string]any { - return map[string]any{ - "disposition": disposition, "category": category, "reason_code": reasonCode, - "origin": map[string]any{"stage": origin, "lane_id": "npc-registry"}, "occurrence_count": occurrences, - "samples": []any{map[string]any{"scope": "lane:npc-registry", "message": "external detail"}}, - "omitted_sample_count": occurrences - 1, - } -} - -func findingEnvelope(schema string, groups []any, occurrences int, truncated bool, unrepresented int) map[string]any { - value := map[string]any{ - "schema_version": schema, "group_count": len(groups), "occurrence_count": occurrences, - "groups": groups, - } - if schema == diagnosticsSchemaVersion { - value["truncated"] = truncated - value["unrepresented_occurrence_count"] = unrepresented - } - return value + writeJSONFile(t, req.ReportPath, map[string]any{"pipeline": req.PipelineID, "artifact_count": 1, "output_directory": bundle}) } func writeJSONFile(t *testing.T, path string, value any) { t.Helper() data, err := json.Marshal(value) if err != nil { - t.Fatalf("json.Marshal() error = %v", err) + t.Fatal(err) } - if err := os.WriteFile(path, data, 0o644); err != nil { - t.Fatalf("WriteFile(%q) error = %v", path, err) + if err := os.WriteFile(path, data, 0644); err != nil { + t.Fatal(err) } } diff --git a/internal/adapters/subprocess/diagnostics.go b/internal/adapters/subprocess/diagnostics.go index 9afeca9..4260b0d 100644 --- a/internal/adapters/subprocess/diagnostics.go +++ b/internal/adapters/subprocess/diagnostics.go @@ -39,7 +39,7 @@ var inheritedEnvironmentNames = map[string]struct{}{ "GO_WANT_SERIATIM_HELPER": {}, "GO_WANT_SUBPROCESS_HELPER": {}, "NOTARIUS_CAPTURE_DIR": {}, - "NOTARIUS_RECEIPT_FIXTURE": {}, + "NOTARIUS_REPORT_FIXTURE": {}, "SCRIPTORIUM_HELPER_RECORD_PATH": {}, "SCRIPTORIUM_HELPER_MODE": {}, "SERIATIM_HELPER_RECORD_PATH": {}, diff --git a/internal/app/analyze_artifacts_test.go b/internal/app/analyze_artifacts_test.go index 2d35050..944b4bd 100644 --- a/internal/app/analyze_artifacts_test.go +++ b/internal/app/analyze_artifacts_test.go @@ -28,10 +28,12 @@ scriptorium: enabled: false for_each: party.characters prompt_id: dnd.character_meta - output_path_pattern: artifacts/characters/{character_id}/meta.md + output_path_pattern: artifacts/{character_id}-meta.md `) - campaign := write("campaign.yml", `campaign_id: campaign -inputs: {speakers_file: speakers.yml, autocorrect_file: autocorrect.yml, glossary_file: glossary.yml, party_file: party.yml} + campaign := write("campaign.yml", `schema_version: maximumdirect.rpg.campaign.v1 +id: campaign +references: {party: party.yml} +narratio: {inputs: {speakers_file: speakers.yml, glossary_file: glossary.yml}} `) session := write("session.yml", `session_id: session campaign: campaign diff --git a/internal/app/bounded_prerequisites_test.go b/internal/app/bounded_prerequisites_test.go index fa0a058..fa352bb 100644 --- a/internal/app/bounded_prerequisites_test.go +++ b/internal/app/bounded_prerequisites_test.go @@ -181,7 +181,10 @@ func TestExecuteStagesBoundedCompositionUsesOnlySelectedCollaborators(t *testing } { t.Run(test.name, func(t *testing.T) { cfg := testConfig(t) - if test.configure != nil { + var injected *stage.Env + if test.stageName == "extract" { + cfg, injected, _ = extractionLifecycleFixture(t, true) + } else if test.configure != nil { test.configure(cfg) } plan := mustBoundedPlan(t, test.stageName, test.stageName) @@ -192,7 +195,7 @@ func TestExecuteStagesBoundedCompositionUsesOnlySelectedCollaborators(t *testing var captured *stage.Env plan.stages = []stage.Stage{collaboratorProbeStage{name: test.stageName, captured: &captured}} - _, err := executePlan(context.Background(), cfg, plan, RunOptions{}) + _, err := executePlan(context.Background(), cfg, plan, RunOptions{Env: injected}) if err != nil { t.Fatalf("executeStages() error = %v", err) } diff --git a/internal/app/catalog_execution_test.go b/internal/app/catalog_execution_test.go index 902e596..d93bad3 100644 --- a/internal/app/catalog_execution_test.go +++ b/internal/app/catalog_execution_test.go @@ -38,21 +38,21 @@ scriptorium: enabled: false for_each: party.characters prompt_id: meta - output_path_pattern: artifacts/{character_id}/meta.md + output_path_pattern: artifacts/{character_id}-meta.md inputs: players: {source: narratio.input.players, required: true} character_note: enabled: false for_each: party.characters prompt_id: note - output_path_pattern: artifacts/{character_id}/note.md + output_path_pattern: artifacts/{character_id}-note.md inputs: meta: {source: narratio.member_artifact.character_meta, required: true} member_vars: character_name: character.name `) campaignPath := filepath.Join(dir, "campaign.yml") - mustWriteTestFile(t, campaignPath, "campaign_id: campaign\ninputs: {speakers_file: speakers.yml, autocorrect_file: autocorrect.yml, glossary_file: glossary.yml, party_file: default-party.yml}\n") + mustWriteTestFile(t, campaignPath, "schema_version: maximumdirect.rpg.campaign.v1\nid: campaign\nreferences: {party: default-party.yml}\nnarratio: {inputs: {speakers_file: speakers.yml, glossary_file: glossary.yml}}\n") partyPath := filepath.Join(dir, "selected-party.yml") mustWriteTestFile(t, partyPath, "schema_version: maximumdirect.rpg.party.v1\ncharacters:\n ivy:\n player: {name: Selected Player}\n character: {name: Ivy, classes: [{name: ranger}]}\n") sessionPath := filepath.Join(dir, "session.yml") diff --git a/internal/app/commands_test.go b/internal/app/commands_test.go index fc88f97..a795782 100644 --- a/internal/app/commands_test.go +++ b/internal/app/commands_test.go @@ -149,7 +149,6 @@ campaign: sample-campaign inputs: audio_dir: ./audio speakers_file: ./speakers.yml - autocorrect_file: ./autocorrect.yml glossary_file: ./glossary.yml ` if err := os.WriteFile(pipelinePath, []byte(pipelineYAML), 0o644); err != nil { @@ -212,7 +211,7 @@ inputs: } foundReference := false if err := filepath.WalkDir(workRoot, func(path string, entry os.DirEntry, walkErr error) error { - if walkErr != nil || entry.IsDir() { + if walkErr != nil || entry.IsDir() || entry.Type()&os.ModeSymlink != 0 { return walkErr } data, err := os.ReadFile(path) @@ -259,7 +258,6 @@ campaign: sample-campaign inputs: audio_dir: ./audio speakers_file: ./speakers.yml - autocorrect_file: ./autocorrect.yml glossary_file: ./glossary.yml ` if err := os.WriteFile(pipelinePath, []byte(pipelineYAML), 0o644); err != nil { @@ -348,16 +346,18 @@ func TestExecuteCampaignIDSelectsRegistryCampaign(t *testing.T) { pipelinePath, campaignPath, sessionPath := writeValidConfigFiles(t, workspaceRoot) campaignRoot := filepath.Dir(filepath.Dir(campaignPath)) otherDir := filepath.Join(campaignRoot, "icewind") - mustWriteTestFile(t, filepath.Join(otherDir, "campaign.yml"), `campaign_id: icewind -inputs: - speakers_file: ./speakers.yml - autocorrect_file: ./autocorrect.yml - glossary_file: ./glossary.yml - party_file: ./party.yml + mustWriteTestFile(t, filepath.Join(otherDir, "campaign.yml"), `schema_version: maximumdirect.rpg.campaign.v1 +id: icewind +references: + party: ./party.yml +narratio: + inputs: + speakers_file: ./speakers.yml + glossary_file: ./glossary.yml `) mustWriteTestFile(t, filepath.Join(otherDir, "speakers.yml"), "match:\n - speaker: Alice\n match: [\"alice\"]\n") mustWriteTestFile(t, filepath.Join(otherDir, "autocorrect.yml"), "[]\n") - mustWriteTestFile(t, filepath.Join(otherDir, "glossary.yml"), "[]\n") + mustWriteTestFile(t, filepath.Join(otherDir, "glossary.yml"), "schema_version: maximumdirect.glossary.v1\ncollections: {}\n") mustWriteTestFile(t, filepath.Join(otherDir, "players.yml"), "[]\n") mustWriteTestFile(t, filepath.Join(otherDir, "party.yml"), "schema_version: maximumdirect.rpg.party.v1\ncharacters:\n arannis:\n player: {name: Eric}\n character:\n name: Arannis\n classes: [{name: wizard}]\n") @@ -470,7 +470,7 @@ narratio: mustWriteTestFile(t, filepath.Join(campaignDir, "speakers.yml"), "match:\n - speaker: Alice\n match: [\"alice\"]\n") mustWriteTestFile(t, filepath.Join(campaignDir, "autocorrect.yml"), "[]\n") - mustWriteTestFile(t, filepath.Join(campaignDir, "glossary.yml"), "campaign: {entries: []}\n") + mustWriteTestFile(t, filepath.Join(campaignDir, "glossary.yml"), "schema_version: maximumdirect.glossary.v1\ncollections:\n campaign: {entries: []}\n") mustWriteTestFile(t, filepath.Join(campaignDir, "party.yml"), "schema_version: maximumdirect.rpg.party.v1\ncharacters:\n arannis:\n player: {name: Eric}\n character:\n name: Arannis\n classes: [{name: wizard}]\n") mustWriteTestFile(t, filepath.Join(dir, "audio", "alice.flac"), "audio-bytes") diff --git a/internal/app/extract_lifecycle_test.go b/internal/app/extract_lifecycle_test.go index 5c5c948..b7a37af 100644 --- a/internal/app/extract_lifecycle_test.go +++ b/internal/app/extract_lifecycle_test.go @@ -60,62 +60,34 @@ func (s assertExtractionSourcesStage) Run(_ context.Context, env *stage.Env, m * return &stage.StageResult{}, nil } -func (r *materializingNotariusRunner) Run(_ context.Context, req notarius.RunRequest) (notarius.RunResult, error) { +func (r *materializingNotariusRunner) Preflight(ctx context.Context, req notarius.ReadinessRequest) (notarius.ReadinessResult, error) { + if err := ctx.Err(); err != nil { + return notarius.ReadinessResult{}, err + } + return notarius.ReadinessResult{Pipeline: req.PipelineID, Lanes: append([]string(nil), req.RequiredLanes...), InspectionComplete: true, AssessmentComplete: true, Ready: true, InputPath: req.InputPath, InputDescription: req.InputDescription}, nil +} + +func (r *materializingNotariusRunner) Run(ctx context.Context, req notarius.RunRequest) (notarius.RunResult, error) { + if err := ctx.Err(); err != nil { + return notarius.RunResult{}, err + } r.requests = append(r.requests, req) if r.failuresRemaining > 0 { r.failuresRemaining-- return notarius.RunResult{}, errors.New("notarius execution failed") } - externalRunID := fmt.Sprintf("notarius-run-%d", len(r.requests)) - bundle := filepath.Join(req.OutputRoot, externalRunID) - lanesDir := filepath.Join(bundle, "lanes") - if err := os.MkdirAll(lanesDir, 0o755); err != nil { + bundle := filepath.Join(req.OutputRoot, fmt.Sprintf("notarius-run-%d", len(r.requests))) + lanes := filepath.Join(bundle, "lanes") + if err := os.MkdirAll(lanes, 0755); err != nil { return notarius.RunResult{}, err } - for path, content := range map[string]string{ - filepath.Join(bundle, "index.json"): `{"manifest_file":"manifest.json"}`, - filepath.Join(bundle, "manifest.json"): `{}`, - filepath.Join(bundle, "rejected.json"): `{"rejected":[]}`, - filepath.Join(bundle, "warnings.json"): `{"schema_version":"notarius.warnings.v2","group_count":0,"occurrence_count":0,"groups":[]}`, - filepath.Join(bundle, "diagnostics.json"): `{"schema_version":"notarius.diagnostics.v1","group_count":0,"occurrence_count":0,"truncated":false,"unrepresented_occurrence_count":0,"groups":[]}`, - } { - if err := os.WriteFile(path, []byte(content), 0o644); err != nil { + for _, output := range r.cfg.Outputs { + filename := output.LaneID + ".json" + if err := os.WriteFile(filepath.Join(lanes, filename), []byte(`{"records":[]}`), 0644); err != nil { return notarius.RunResult{}, err } } - keys := make([]string, 0, len(r.cfg.Outputs)) - for key := range r.cfg.Outputs { - keys = append(keys, key) - } - sort.Strings(keys) - lanes := make([]notarius.LaneDescriptor, 0, len(keys)) - for _, key := range keys { - output := r.cfg.Outputs[key] - filename := key + ".json" - path := filepath.Join(lanesDir, filename) - if err := os.WriteFile(path, []byte(`{"records":[]}`), 0o644); err != nil { - return notarius.RunResult{}, err - } - lanes = append(lanes, notarius.LaneDescriptor{ - LaneID: output.LaneID, File: filepath.ToSlash(filepath.Join("lanes", filename)), Path: path, - MediaType: output.MediaType, SchemaID: output.SchemaID, - SchemaVersion: output.SchemaVersion, ModuleKey: output.ModuleKey, - }) - } - return notarius.RunResult{ - Receipt: notarius.Receipt{ - SchemaVersion: notarius.ReceiptSchemaVersion, RunID: externalRunID, - PipelineID: req.PipelineID, OutputDirectory: bundle, IndexFile: "index.json", - NormalizedOutputCount: len(lanes), ValidationStatus: "approved", - }, - BundleRoot: bundle, - Index: notarius.Index{ - Path: filepath.Join(bundle, "index.json"), RejectedPath: filepath.Join(bundle, "rejected.json"), - WarningsPath: filepath.Join(bundle, "warnings.json"), - DiagnosticsPath: filepath.Join(bundle, "diagnostics.json"), - Lanes: lanes, - }, - }, nil + return notarius.RunResult{BundleRoot: bundle, Report: notarius.CompletionReport{Pipeline: req.PipelineID, ArtifactCount: len(r.cfg.Outputs), OutputDirectory: bundle}}, nil } func TestExtractLifecycleDisabledThenEnabled(t *testing.T) { @@ -145,7 +117,7 @@ func TestExtractLifecycleDisabledThenEnabled(t *testing.T) { if err != nil { t.Fatalf("Load() error = %v", err) } - if loaded.Stages["extract"] == nil || loaded.Stages["extract"].Status != manifest.StatusSucceeded || len(loaded.Stages["extract"].Outputs) != 2 { + if loaded.Stages["extract"] == nil || loaded.Stages["extract"].Status != manifest.StatusSucceeded || len(loaded.Stages["extract"].Outputs) != 1 { t.Fatalf("extract record = %#v, want succeeded manifest-ready outputs", loaded.Stages["extract"]) } } @@ -170,10 +142,10 @@ func TestExtractLifecyclePrepareBindsVerifiedReferenceSnapshots(t *testing.T) { sourceID string filename string }{ - {selector: "glossary", sourceID: artifactpolicy.SourceInputGlossaryCampaign, filename: "campaign.yml"}, + {selector: "glossary", sourceID: artifactpolicy.SourceInputGlossaryCombined, filename: "combined.yml"}, {selector: "party", sourceID: artifactpolicy.SourceInputParty, filename: "party.yml"}, {selector: "players", sourceID: artifactpolicy.SourceInputPlayers, filename: "players.yml"}, - {selector: "spells", sourceID: artifactpolicy.SourceInputSpellCatalog, filename: "spell_catalog.json"}, + {selector: "spells", sourceID: artifactpolicy.SourceInputGlossaryCombined, filename: "combined.yml"}, } request := runner.requests[0] if len(request.References) != len(want) { @@ -354,8 +326,8 @@ func TestExtractLifecycleEmptyReferencesPreserveAllDndExtractionSources(t *testi t.Fatalf("summary=%#v requests=%#v analyze=%d", summary, runner.requests, analyzeRuns) } loaded := loadLifecycleManifest(t, cfg) - if got := len(loaded.Stages["extract"].Outputs); got != len(keys)+1 { - t.Fatalf("extract outputs = %d, want %d lanes plus index", got, len(keys)) + if got := len(loaded.Stages["extract"].Outputs); got != len(keys) { + t.Fatalf("extract outputs = %d, want %d lanes", got, len(keys)) } } @@ -476,7 +448,7 @@ characters: t.Fatalf("changed party retained derived players snapshot path %q", thirdPaths["players"]) } for selector, firstPath := range firstPaths { - if selector != "party" && selector != "players" && thirdPaths[selector] != firstPath { + if selector != "party" && selector != "players" && selector != "glossary" && selector != "spells" && thirdPaths[selector] != firstPath { t.Fatalf("unchanged %s snapshot path = %q, want %q", selector, thirdPaths[selector], firstPath) } if _, err := os.Stat(firstPath); err != nil { @@ -496,8 +468,8 @@ func TestExtractLifecycleCacheControlsAndSnapshotLossDoNotInvalidateCompleteResu if err := os.RemoveAll(cacheRoot); err != nil { t.Fatalf("RemoveAll(snapshot cache) error = %v", err) } - cfg.Pipeline.Notarius.Resume = true - cfg.Pipeline.Notarius.ChunkCache = "bypass" + cache := "bypass" + cfg.Pipeline.Notarius.Cache = &cache extractPlan, _ := BuildSingleStagePlan("extract") summary, err := executeStages(context.Background(), cfg, extractPlan, RunOptions{Env: env}) if err != nil { @@ -537,14 +509,14 @@ func TestAnalyzeOnlyLifecyclePreservesExtractionWithoutInvokingNotarius(t *testi func TestForcedArtifactRegenerationUsesOrdinaryExtractAndAnalyzePath(t *testing.T) { cfg, env, runner := extractionLifecycleFixture(t, true) - cfg.Pipeline.Notarius.Resume = true - cfg.Pipeline.Notarius.ChunkCache = "bypass" + cache := "bypass" + cfg.Pipeline.Notarius.Cache = &cache analyzeRuns := 0 plan := extractionLifecyclePlan(t, &analyzeRuns) if _, err := executeStages(context.Background(), cfg, plan, RunOptions{Env: env, Force: true, SelectedArtifacts: []string{"session_recap"}}); err != nil { t.Fatalf("forced artifact regeneration error = %v", err) } - if len(runner.requests) != 1 || runner.requests[0].Resume || runner.requests[0].ChunkCache != "refresh" || analyzeRuns != 1 { + if len(runner.requests) != 1 || runner.requests[0].Cache == nil || *runner.requests[0].Cache != "refresh" || analyzeRuns != 1 { t.Fatalf("forced path request=%#v analyze=%d", runner.requests, analyzeRuns) } } @@ -821,10 +793,6 @@ func TestExtractLifecycleRealConfigOverlaysSelectNotariusExplicitly(t *testing.T outputs: npc_registry: lane_id: npc-registry - media_type: application/json - schema_id: notarius.dnd.npc_registry - schema_version: v1 - module_key: dnd/npc-registry `) closeErr := pipelineFile.Close() if writeErr != nil || closeErr != nil { @@ -941,7 +909,7 @@ func TestExtractLifecycleResumesAndRerunsObsoleteResults(t *testing.T) { }{ {name: "configuration changed", mutate: func(_ *testing.T, cfg *config.Config, _ *manifest.Manifest) { output := cfg.Pipeline.Notarius.Outputs["npc_registry"] - output.SchemaVersion = "v2" + output.Filename = "changed.json" cfg.Pipeline.Notarius.Outputs["npc_registry"] = output }}, {name: "payload missing", mutate: func(t *testing.T, _ *config.Config, m *manifest.Manifest) { @@ -955,7 +923,7 @@ func TestExtractLifecycleResumesAndRerunsObsoleteResults(t *testing.T) { } }}, {name: "record incompatible", mutate: func(_ *testing.T, _ *config.Config, m *manifest.Manifest) { - m.Stages["extract"].Outputs[0].Contract.SchemaID = "incompatible" + m.Stages["extract"].Outputs[0].ExternalProvenance.ArtifactID = "incompatible" }}, } { t.Run(test.name, func(t *testing.T) { @@ -1007,7 +975,7 @@ func TestExtractLifecycleUnsafeResumeErrorPreservesSuccess(t *testing.T) { "analyze": persisted.Stages["analyze"], }) - if _, err := executeStages(context.Background(), cfg, plan, RunOptions{Env: env}); err == nil || !strings.Contains(err.Error(), "unsafe") { + if _, err := executeStages(context.Background(), cfg, plan, RunOptions{Env: env}); err == nil || !strings.Contains(err.Error(), "canonical destination") { t.Fatalf("executeStages() error = %v, want unsafe resume failure", err) } afterManifest, err := store.Load(context.Background(), first.ManifestPath) @@ -1083,25 +1051,13 @@ func (lifecycleTrimEvidenceStage) Run(_ context.Context, env *stage.Env, m *mani func configureLifecycleReferences(t *testing.T, cfg *config.Config) map[string]string { t.Helper() cfg.Pipeline.Notarius.References = map[string]string{ - "party": artifactpolicy.SourceInputParty, - "players": artifactpolicy.SourceInputPlayers, - "glossary": artifactpolicy.SourceInputGlossaryCampaign, - "spells": artifactpolicy.SourceInputSpellCatalog, + "party": artifactpolicy.SourceInputParty, "players": artifactpolicy.SourceInputPlayers, + "glossary": artifactpolicy.SourceInputGlossaryCombined, "spells": artifactpolicy.SourceInputGlossaryCombined, } - spellPath := filepath.Join(filepath.Dir(cfg.CampaignPath), "spells.json") - if err := os.WriteFile(spellPath, []byte(`{"spells":[]}`+"\n"), 0o644); err != nil { - t.Fatalf("WriteFile(spell catalog) error = %v", err) - } - cfg.StableInputs.SpellCatalogFile = config.ResolvedInputFile{ - Path: "./spells.json", ConfigPath: cfg.CampaignPath, Source: "campaign_config", - } - cfg.Session.Inputs.SpellCatalogFile = "./spells.json" - return map[string]string{ artifactpolicy.SourceInputParty: filepath.Join(filepath.Dir(cfg.CampaignPath), "party.yml"), artifactpolicy.SourceInputPlayers: filepath.Join(filepath.Dir(cfg.CampaignPath), "players.yml"), - artifactpolicy.SourceInputGlossaryCampaign: filepath.Join(filepath.Dir(cfg.CampaignPath), "glossary.yml"), - artifactpolicy.SourceInputSpellCatalog: spellPath, + artifactpolicy.SourceInputGlossaryCombined: filepath.Join(filepath.Dir(cfg.CampaignPath), "glossary.yml"), } } @@ -1129,16 +1085,16 @@ func lifecycleReferencePaths(request notarius.RunRequest) map[string]string { func lifecycleDndOutputs() map[string]config.NotariusOutputConfig { return map[string]config.NotariusOutputConfig{ - "item_registry": {LaneID: "item-registry", MediaType: "application/json", SchemaID: "notarius.dnd.item_registry", SchemaVersion: "v1", ModuleKey: "dnd/item-registry"}, - "npc_registry": {LaneID: "npc-registry", MediaType: "application/json", SchemaID: "notarius.dnd.npc_registry", SchemaVersion: "v1", ModuleKey: "dnd/npc-registry"}, - "location_registry": {LaneID: "location-registry", MediaType: "application/json", SchemaID: "notarius.dnd.location_registry", SchemaVersion: "v1", ModuleKey: "dnd/location-registry"}, - "scene_descriptions": {LaneID: "scene-descriptions", MediaType: "application/json", SchemaID: "notarius.dnd.scene_descriptions", SchemaVersion: "v1", ModuleKey: "dnd/scene-descriptions"}, - "item_occurrences": {LaneID: "item-occurrences", MediaType: "application/json", SchemaID: "notarius.dnd.item_occurrences", SchemaVersion: "v1", ModuleKey: "dnd/item-occurrences"}, - "spells": {LaneID: "spells", MediaType: "application/json", SchemaID: "notarius.dnd.spells", SchemaVersion: "v1", ModuleKey: "dnd/spells"}, - "combat_turns": {LaneID: "combat-turns", MediaType: "application/json", SchemaID: "notarius.dnd.combat_turns", SchemaVersion: "v1", ModuleKey: "dnd/combat-turns"}, - "npc_occurrences": {LaneID: "npc-occurrences", MediaType: "application/json", SchemaID: "notarius.dnd.npc_occurrences", SchemaVersion: "v1", ModuleKey: "dnd/npc-occurrences"}, - "location_occurrences": {LaneID: "location-occurrences", MediaType: "application/json", SchemaID: "notarius.dnd.location_occurrences", SchemaVersion: "v1", ModuleKey: "dnd/location-occurrences"}, - "enemy_events": {LaneID: "enemy-events", MediaType: "application/json", SchemaID: "notarius.dnd.enemy_events", SchemaVersion: "v1", ModuleKey: "dnd/enemy-events"}, + "item_registry": {LaneID: "item-registry"}, + "npc_registry": {LaneID: "npc-registry"}, + "location_registry": {LaneID: "location-registry"}, + "scene_descriptions": {LaneID: "scene-descriptions"}, + "item_occurrences": {LaneID: "item-occurrences"}, + "spells": {LaneID: "spells"}, + "combat_turns": {LaneID: "combat-turns"}, + "npc_occurrences": {LaneID: "npc-occurrences"}, + "location_occurrences": {LaneID: "location-occurrences"}, + "enemy_events": {LaneID: "enemy-events"}, } } @@ -1163,8 +1119,7 @@ func extractionLifecycleFixture(t *testing.T, enabled bool) (*config.Config, *st Timeout: "45m", WorkingDirectory: workingDirectory, Outputs: map[string]config.NotariusOutputConfig{ "npc_registry": { - LaneID: "npc-registry", MediaType: "application/json", SchemaID: "notarius.dnd.npc_registry", - SchemaVersion: "v1", ModuleKey: "dnd/npc-registry", + LaneID: "npc-registry", }, }, } diff --git a/internal/app/glossary_remediation_test.go b/internal/app/glossary_remediation_test.go index 891ee4c..7f8f5a2 100644 --- a/internal/app/glossary_remediation_test.go +++ b/internal/app/glossary_remediation_test.go @@ -23,7 +23,7 @@ func TestPreparedGlossaryAliasPresence(t *testing.T) { pipeline, campaign, session := writeValidConfigFiles(t, t.TempDir()) entry := "{id: watch, name: Watch, category: person" + aliases + "}" if mode == "file" { - mustWriteTestFile(t, filepath.Join(filepath.Dir(campaign), "glossary.yml"), "campaign: {entries: ["+entry+"]}\n") + mustWriteTestFile(t, filepath.Join(filepath.Dir(campaign), "glossary.yml"), "schema_version: maximumdirect.glossary.v1\ncollections:\n campaign: {entries: ["+entry+"]}\n") } else { mustWriteTestFile(t, session, "session_id: 2026-05-03\ninputs:\n audio_dir: ./audio\n glossary_file: null\n glossary: {entries: ["+entry+"]}\n") } @@ -43,13 +43,15 @@ func TestPreparedGlossaryAliasPresence(t *testing.T) { if err != nil { t.Fatal(err) } - var doc map[string]struct { - Entries []map[string]any `yaml:"entries"` + var doc struct { + Collections map[string]struct { + Entries []map[string]any `yaml:"entries"` + } `yaml:"collections"` } if err := yaml.Unmarshal(data, &doc); err != nil { t.Fatal(err) } - entries := doc["campaign"].Entries + entries := doc.Collections["campaign"].Entries if len(entries) != 1 { t.Fatalf("entries: %s", data) } @@ -90,11 +92,11 @@ func TestSelectedCatalogSourcesBeforePreparation(t *testing.T) { } mustWriteTestFile(t, pipeline, string(body)+fmt.Sprintf("reference_catalog:\n %s:\n broken: %s\n", group.name, tc.value)) if tc.selected { - body, err = os.ReadFile(campaign) + body, err = os.ReadFile(session) if err != nil { t.Fatal(err) } - mustWriteTestFile(t, campaign, string(body)+fmt.Sprintf(" %s: broken\n", group.selector)) + mustWriteTestFile(t, session, string(body)+fmt.Sprintf(" %s: broken\n", group.selector)) } cfg, err := config.LoadWithSessionOptions(pipeline, campaign, session, config.SessionLoadOptions{}) if tc.invalid { diff --git a/internal/app/operator_helpers_test.go b/internal/app/operator_helpers_test.go index 87f4784..4e32f64 100644 --- a/internal/app/operator_helpers_test.go +++ b/internal/app/operator_helpers_test.go @@ -109,18 +109,20 @@ func TestExecuteSessionInitExplicitConfigWinsOverDefaults(t *testing.T) { explicitDir := t.TempDir() explicitCampaign := filepath.Join(explicitDir, "campaign.yml") - if err := os.WriteFile(explicitCampaign, []byte(`campaign_id: explicit-campaign -inputs: - speakers_file: ./speakers.yml - autocorrect_file: ./autocorrect.yml - glossary_file: ./glossary.yml - party_file: ./party.yml + if err := os.WriteFile(explicitCampaign, []byte(`schema_version: maximumdirect.rpg.campaign.v1 +id: explicit-campaign +references: + party: ./party.yml +narratio: + inputs: + speakers_file: ./speakers.yml + glossary_file: ./glossary.yml `), 0o644); err != nil { t.Fatalf("write explicit campaign: %v", err) } mustWriteTestFile(t, filepath.Join(explicitDir, "speakers.yml"), "match:\n - speaker: Alice\n match: [\"alice\"]\n") mustWriteTestFile(t, filepath.Join(explicitDir, "autocorrect.yml"), "[]\n") - mustWriteTestFile(t, filepath.Join(explicitDir, "glossary.yml"), "[]\n") + mustWriteTestFile(t, filepath.Join(explicitDir, "glossary.yml"), "schema_version: maximumdirect.glossary.v1\ncollections: {}\n") mustWriteTestFile(t, filepath.Join(explicitDir, "players.yml"), "[]\n") mustWriteTestFile(t, filepath.Join(explicitDir, "party.yml"), "schema_version: maximumdirect.rpg.party.v1\ncharacters:\n arannis:\n player: {name: Eric}\n character:\n name: Arannis\n classes: [{name: wizard}]\n") @@ -468,63 +470,6 @@ inputs: } } -func TestOperatorCommandsReportConfiguredSpellCatalog(t *testing.T) { - workspaceRoot := t.TempDir() - pipelinePath, campaignPath, sessionPath := writeValidConfigFiles(t, workspaceRoot) - campaignBytes, err := os.ReadFile(campaignPath) - if err != nil { - t.Fatalf("read campaign: %v", err) - } - campaignYAML := strings.Replace(string(campaignBytes), " party_file: ./party.yml\n", " party_file: ./party.yml\n spell_catalog_file: ./spells.json\n", 1) - if err := os.WriteFile(campaignPath, []byte(campaignYAML), 0o644); err != nil { - t.Fatalf("write campaign: %v", err) - } - spellPath := filepath.Join(filepath.Dir(campaignPath), "spells.json") - mustWriteTestFile(t, spellPath, "{\"spells\":[]}\n") - seedValidationPrepared(t, loadConfigForSemanticEvidence(t, pipelinePath, campaignPath, sessionPath)) - - fake := &storage.FakeBackend{} - var storeInitCalls int - deps := fakeCommandDependencies(fake, &storeInitCalls) - commonArgs := []string{ - "2026-05-03", - "--config", pipelinePath, - "--campaign-file", campaignPath, "--session-file", sessionPath, - } - - var stdout bytes.Buffer - var stderr bytes.Buffer - validateArgs := append([]string{"session", "validate"}, commonArgs...) - if code := executeWithDependencies(validateArgs, &stdout, &stderr, deps, executePlan); code != 0 { - t.Fatalf("validate exit code = %d, want 0; stdout=%q stderr=%q", code, stdout.String(), stderr.String()) - } - if !findingMatches(decodeNativeReport[sessionValidationReport](t, stdout.Bytes()).Findings, "OK", "inputs", spellPath) { - t.Fatalf("validate stdout = %q, want spell catalog finding", stdout.String()) - } - - stdout.Reset() - stderr.Reset() - statusArgs := append([]string{"session", "status"}, commonArgs...) - if code := executeWithDependencies(statusArgs, &stdout, &stderr, deps, executePlan); code != 0 { - t.Fatalf("status exit code = %d, want 0; stdout=%q stderr=%q", code, stdout.String(), stderr.String()) - } - if !findingMatches(decodeNativeReport[sessionStateReport](t, stdout.Bytes()).Findings, "INFO", "inputs", spellPath) { - t.Fatalf("status stdout = %q, want spell catalog inventory", stdout.String()) - } - - if err := os.Remove(spellPath); err != nil { - t.Fatalf("remove spell catalog: %v", err) - } - stdout.Reset() - stderr.Reset() - if code := executeWithDependencies(validateArgs, &stdout, &stderr, deps, executePlan); code == 0 { - t.Fatalf("validate missing spell catalog exit code = 0; stdout=%q", stdout.String()) - } - if !findingMatches(decodeNativeReport[sessionValidationReport](t, stdout.Bytes()).Findings, "ERROR", "inputs", "spell_catalog") { - t.Fatalf("validate stdout = %q, want missing spell catalog finding", stdout.String()) - } -} - func TestExecuteLocksAddListAndRemoveUseIndependentObjects(t *testing.T) { workspaceRoot := t.TempDir() pipelinePath, campaignPath, sessionPath := writeValidConfigFiles(t, workspaceRoot) @@ -1273,10 +1218,6 @@ func addExtractionOutputToPipeline(t *testing.T, pipelinePath string) { outputs: encounters: lane_id: encounters - media_type: application/json - schema_id: encounters - schema_version: "1" - module_key: encounters `)...) if err := os.WriteFile(pipelinePath, data, 0o644); err != nil { t.Fatal(err) @@ -1289,21 +1230,14 @@ func addExtractionOutputToPipeline(t *testing.T, pipelinePath string) { func writeOperatorExtractionManifest(t *testing.T, workspaceRoot string) string { t.Helper() paths := artifacts.NewLocalStore(workspaceRoot).SessionPathsFor("sample-campaign", "2026-05-03") - bundleRoot := filepath.Join(paths.ArtifactsDir, "notarius", "extract-run-1") - lanePath := filepath.Join(bundleRoot, "lanes", "encounters.json") - indexPath := filepath.Join(bundleRoot, "index.json") + lanePath := filepath.Join(paths.ArtifactsDir, "encounters.json") trimmedPath := filepath.Join(paths.Root, filepath.FromSlash(artifacts.TranscriptPathFinalTrimmed)) mustWriteTestFile(t, lanePath, `{"secret":"DO_NOT_PRINT"}`) - mustWriteTestFile(t, indexPath, `{"lanes":[]}`) mustWriteTestFile(t, trimmedPath, `{"segments":[]}`) laneChecksum, err := artifacts.SHA256File(lanePath) if err != nil { t.Fatal(err) } - indexChecksum, err := artifacts.SHA256File(indexPath) - if err != nil { - t.Fatal(err) - } m := manifest.New("2026-05-03", time.Now().UTC()) m.Campaign = "sample-campaign" trimmedChecksum, err := artifacts.SHA256File(trimmedPath) @@ -1322,20 +1256,8 @@ func writeOperatorExtractionManifest(t *testing.T, workspaceRoot string) string } m.Stages["extract"] = &manifest.StageRecord{ Name: "extract", Status: manifest.StatusSucceeded, - Metadata: map[string]any{ - "narratio_run_id": "extract-run-1", "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: "extract-run-1", 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: "extract-run-1", Checksum: indexChecksum}, - }, + Metadata: map[string]any{"narratio_run_id": "extract-run-1", "completion": map[string]any{"pipeline": "campaign.extract"}, "direct_input": input.Metadata()}, + Outputs: []manifest.ArtifactRecord{{Kind: "notarius_lane", SourceID: artifacts.ExtractionArtifactSourceID("encounters"), LocalPath: lanePath, ProducerRunID: "extract-run-1", Checksum: laneChecksum, Size: int64(len(`{"secret":"DO_NOT_PRINT"}`)), ExternalProvenance: &artifactmodel.ExternalProvenance{System: "notarius", PipelineID: "campaign.extract", ArtifactID: "encounters"}}}, } if err := (&manifest.LocalStore{}).Save(context.Background(), paths.ManifestPath, m); err != nil { t.Fatal(err) diff --git a/internal/app/operator_inspection_fifo_test.go b/internal/app/operator_inspection_fifo_test.go index 923ece6..f409622 100644 --- a/internal/app/operator_inspection_fifo_test.go +++ b/internal/app/operator_inspection_fifo_test.go @@ -11,7 +11,7 @@ import ( "golang.org/x/sys/unix" ) -func TestInspectStableInputsRejectsSpellCatalogFIFO(t *testing.T) { +func TestInspectStableInputsRejectsSpeakersFIFO(t *testing.T) { root := t.TempDir() sourcePath := filepath.Join(root, "spells.fifo") if err := unix.Mkfifo(sourcePath, 0o644); err != nil { @@ -19,16 +19,16 @@ func TestInspectStableInputsRejectsSpellCatalogFIFO(t *testing.T) { } cfg := &config.Config{StableInputs: config.ResolvedStableInputs{ - SpellCatalogFile: config.ResolvedInputFile{Path: sourcePath, ConfigPath: filepath.Join(root, "campaign.yml")}, + SpeakersFile: config.ResolvedInputFile{Path: sourcePath, ConfigPath: filepath.Join(root, "campaign.yml")}, }} for _, check := range inspectStableInputs(cfg) { - if check.Name != "spell_catalog" { + if check.Name != "speakers" { continue } if check.Err == nil || !strings.Contains(check.Err.Error(), "not a regular file") { - t.Fatalf("spell catalog check = %#v, want regular-file rejection", check) + t.Fatalf("speakers check = %#v, want regular-file rejection", check) } return } - t.Fatal("spell catalog inspection result was not reported") + t.Fatal("speakers inspection result was not reported") } diff --git a/internal/app/plan_test.go b/internal/app/plan_test.go index b5c34a4..714c6ea 100644 --- a/internal/app/plan_test.go +++ b/internal/app/plan_test.go @@ -170,7 +170,6 @@ campaign: sample-campaign inputs: audio_dir: ./audio speakers_file: ./speakers.yml - autocorrect_file: ./autocorrect.yml glossary_file: ./glossary.yml ` if err := os.WriteFile(pipelinePath, []byte(pipelineYAML), 0o644); err != nil { diff --git a/internal/app/prepared_session_roundtrip_test.go b/internal/app/prepared_session_roundtrip_test.go index 9d8fc3a..72540b1 100644 --- a/internal/app/prepared_session_roundtrip_test.go +++ b/internal/app/prepared_session_roundtrip_test.go @@ -21,7 +21,7 @@ import ( func TestPreparedSessionPublishAndRemoteLoad(t *testing.T) { ctx := context.Background() pipelinePath, campaignPath, sessionPath := writeValidConfigFiles(t, t.TempDir()) - mustWriteTestFile(t, filepath.Join(filepath.Dir(campaignPath), "glossary.yml"), "campaign: {entries: [{id: watch, name: Watch, category: organization}]}\n") + mustWriteTestFile(t, filepath.Join(filepath.Dir(campaignPath), "glossary.yml"), "schema_version: maximumdirect.glossary.v1\ncollections:\n campaign: {entries: [{id: watch, name: Watch, category: organization}]}\n") fragment := filepath.Join(filepath.Dir(sessionPath), "fragment.yml") mustWriteTestFile(t, sessionPath, "config:\n imports:\n - path: fragment.yml\nsession_id: 2026-05-03\n") mustWriteTestFile(t, fragment, "title: Published title\ninputs: {audio_dir: audio}\n") @@ -117,7 +117,7 @@ func TestPreparedSessionPublishAndRemoteLoad(t *testing.T) { } prefix := artifacts.S3SessionPrefix("dnd", m.Campaign, m.SessionID) key := artifacts.S3RunRelativeDestinationKey(artifacts.S3RunPrefix(prefix, m.RunID), "prepare/inputs/session.yml") - if got := string(fake.Objects[key].Data); !strings.Contains(got, "Published title") || strings.Contains(got, "imports:") || strings.Contains(got, "speakers_file:") { + if got := string(fake.Objects[key].Data); !strings.Contains(got, "Published title") || strings.Contains(got, "imports:") { t.Fatalf("published session = %q", got) } for _, name := range []string{"campaign.yml", "party.yml", "glossaries/party.yml", "glossaries/campaign.yml", "glossaries/setting.yml", "glossaries/spells.yml"} { @@ -137,8 +137,8 @@ func TestPreparedSessionPublishAndRemoteLoad(t *testing.T) { if received.Session.Title != "Published title" || received.SessionSource.S3Key != key { t.Fatalf("remote session = %#v, source=%#v", received.Session, received.SessionSource) } - if got := received.StableInputs.SpeakersFile; got.Source != "campaign_config" || got.Path != filepath.Join(filepath.Dir(campaignPath), "speakers.yml") { - t.Fatalf("receiving campaign speakers = %#v", got) + if got := received.StableInputs.SpeakersFile; got.Source != "session_config" || got.Path != filepath.Join(filepath.Dir(campaignPath), "speakers.yml") { + t.Fatalf("receiving session speakers = %#v", got) } current, err := discoverRemoteCurrentState(ctx, received, fake) if err != nil { diff --git a/internal/app/provider_credentials_integration_test.go b/internal/app/provider_credentials_integration_test.go index a7e5752..93bfc46 100644 --- a/internal/app/provider_credentials_integration_test.go +++ b/internal/app/provider_credentials_integration_test.go @@ -73,10 +73,6 @@ notarius: outputs: npc_registry: lane_id: npc-registry - media_type: application/json - schema_id: notarius.dnd.npc_registry - schema_version: v1 - module_key: dnd/npc-registry notification: mode: noop `) @@ -85,7 +81,6 @@ campaign: sample-campaign inputs: audio_dir: ./audio speakers_file: ./speakers.yml - autocorrect_file: ./autocorrect.yml glossary_file: ./glossary.yml `) @@ -154,7 +149,7 @@ inputs: } assertNoProviderValues(t, stdout.Bytes(), stderr.Bytes()) if err := filepath.WalkDir(workRoot, func(path string, entry os.DirEntry, walkErr error) error { - if walkErr != nil || entry.IsDir() { + if walkErr != nil || entry.IsDir() || entry.Type()&os.ModeSymlink != 0 { return walkErr } data, err := os.ReadFile(path) @@ -233,6 +228,14 @@ func TestProviderCredentialProcessFixture(t *testing.T) { _, _ = os.Stderr.WriteString(sharedProviderKey + "\n") os.Exit(0) } + if args[0] == "pipeline" { + _, _ = os.Stdout.WriteString(`{"pipeline":"dnd-session","input":{"module":"synthetic","execution_class":"deterministic"},"chunk":{"module":"synthetic","execution_class":"deterministic"},"output":{"module":"synthetic","execution_class":"deterministic"},"steps":[{"id":"step","lanes":[{"id":"npc-registry","artifact_kind":"synthetic","extract":{"module":"synthetic","execution_class":"deterministic"},"merge":{"module":"synthetic","execution_class":"deterministic"},"normalize":{"module":"synthetic","execution_class":"deterministic"}}]}]}`) + os.Exit(0) + } + if args[0] == "preflight" && appSeriatimFlagValue(args, "--input-file") != "" { + _, _ = os.Stdout.WriteString(`{"pipeline":"dnd-session","ready":true,"checks":[]}`) + os.Exit(0) + } switch args[0] { case "process", "preflight": if os.Getenv(auditaOnlyName) != auditaOnlyKey { @@ -271,18 +274,11 @@ func TestProviderCredentialProcessFixture(t *testing.T) { if err := os.MkdirAll(filepath.Join(bundle, "lanes"), 0o755); err != nil { os.Exit(2) } - for name, value := range map[string]string{ - "manifest.json": "{}", "rejected.json": `{"rejected":[]}`, - "warnings.json": `{"schema_version":"notarius.warnings.v2","group_count":0,"occurrence_count":0,"groups":[]}`, - "diagnostics.json": `{"schema_version":"notarius.diagnostics.v1","group_count":0,"occurrence_count":0,"truncated":false,"unrepresented_occurrence_count":0,"groups":[]}`, - "lanes/npc.json": `{"records":[]}`, - "index.json": `{"manifest_file":"manifest.json","output_files":[{"lane_id":"npc-registry","file":"lanes/npc.json","media_type":"application/json","module_key":"dnd/npc-registry","schema_id":"notarius.dnd.npc_registry","schema_version":"v1"}],"rejected_file":"rejected.json","warnings_file":"warnings.json","diagnostics_file":"diagnostics.json"}`, - } { - if err := os.WriteFile(filepath.Join(bundle, filepath.FromSlash(name)), []byte(value), 0o644); err != nil { - os.Exit(2) - } + if err := os.WriteFile(filepath.Join(bundle, "lanes", "npc-registry.json"), []byte(`{"records":[]}`), 0o644); err != nil { + os.Exit(2) } - _, _ = os.Stdout.WriteString(fmt.Sprintf(`{"schema_version":"notarius.run-result.v2","run_id":"fixture-run","pipeline_id":"dnd-session","output_directory":%q,"index_file":"index.json","normalized_output_count":1,"rejected_output_count":0,"warning_group_count":0,"warning_occurrence_count":0,"diagnostic_group_count":0,"diagnostic_occurrence_count":0,"diagnostics_truncated":false,"validation_status":"approved"}`, bundle)) + _, _ = fmt.Fprintf(os.Stdout, `{"pipeline":"dnd-session","artifact_count":1,"output_directory":%q}`, bundle) + default: os.Exit(2) } diff --git a/internal/app/restore_plan_test.go b/internal/app/restore_plan_test.go index dc74790..1b104a3 100644 --- a/internal/app/restore_plan_test.go +++ b/internal/app/restore_plan_test.go @@ -442,6 +442,8 @@ func seedRestoreObject(store *storage.FakeBackend, key string, data []byte) { source := artifacts.ConfiguredArtifactSourceID("test") if destination == artifacts.S3RunSessionManifestKey(sessionPrefix, pointer.RunID) { typeID, source = artifacts.RemoteArtifactTypeSessionManifest, "session.manifest" + } else if strings.HasSuffix(destination, "/published/transcripts/final.trimmed.json") { + source = artifacts.ArtifactTranscriptFinalTrimmed } else if relative := strings.TrimPrefix(destination, runPrefix); strings.HasPrefix(relative, "artifacts/") || strings.HasPrefix(relative, "published/artifacts/") { name := strings.TrimPrefix(relative, "published/") name = strings.TrimSuffix(strings.TrimPrefix(name, "artifacts/"), filepath.Ext(name)) diff --git a/internal/app/restore_workflow_test.go b/internal/app/restore_workflow_test.go index d3f7acd..4432841 100644 --- a/internal/app/restore_workflow_test.go +++ b/internal/app/restore_workflow_test.go @@ -3,9 +3,9 @@ package app import ( "bytes" "context" + "encoding/json" "os" "path/filepath" - "strings" "testing" "time" @@ -24,7 +24,7 @@ func TestRestoreThenForcedAnalyzeUsesRestoredDurableState(t *testing.T) { cfg, sessionPrefix, manifestKey, runIDKey := seedRestoreCommittedState(t, fake, pipelinePath, campaignPath, sessionPath) seedRestoreObject(fake, runIDKey, []byte("20260519T010203Z-a1b2c3d4\n")) seedRestoreObject(fake, manifestKey, restoreWorkflowManifestJSON(t, cfg.Session.SessionID, cfg.Session.Campaign)) - seedRestoreObject(fake, sessionPrefix+"transcripts/full.json", []byte(`{"segments":[1,2,3]}`+"\n")) + seedRestoreObject(fake, sessionPrefix+"transcripts/final.trimmed.json", []byte(`{"segments":[]}`+"\n")) seedRestoreObject(fake, sessionPrefix+"artifacts/session_recap.md", []byte("# restored recap\n")) executeRestore := restoreCommandExecutor(fake) @@ -56,7 +56,7 @@ func TestRestoreThenForcedAnalyzeUsesRestoredDurableState(t *testing.T) { } sessionRoot := artifacts.SessionWorkDirForCampaign(workspaceRoot, cfg.Session.Campaign, cfg.Session.SessionID) - mustReadEquals(t, filepath.Join(sessionRoot, "transcripts", "full.json"), `{"segments":[1,2,3]}`+"\n") + mustReadEquals(t, filepath.Join(sessionRoot, "transcripts", "final.trimmed.json"), `{"segments":[]}`+"\n") mustReadEquals(t, filepath.Join(sessionRoot, "artifacts", "session_recap.md"), "# restored recap\n") manifestStore := &manifest.LocalStore{} @@ -188,18 +188,19 @@ previous_session_id: 2026-04-26 t.Fatalf("load restored manifest: %v", err) } setCurrentBuiltInEvidence(t, localManifest, "trim", artifacts.TranscriptOutputKindFinalTrimmed, artifacts.ArtifactTranscriptFinalTrimmed, filepath.Join(sessionRoot, "transcripts", "final.trimmed.json")) - setCurrentPreviousArtifactInput(t, localManifest, filepath.Join(sessionRoot, "previous", "artifacts", "session_recap.md")) + setCurrentPreviousArtifactInput(t, localManifest, filepath.Join(sessionRoot, "inputs", "previous", "artifacts", "session_recap.md")) if err := (&manifest.LocalStore{}).Save(context.Background(), filepath.Join(sessionRoot, "manifest.json"), localManifest); err != nil { t.Fatalf("save manifest evidence: %v", err) } - previousManifestBytes, err := os.ReadFile(filepath.Join(sessionRoot, "previous", "manifest.json")) + previousManifestBytes, err := os.ReadFile(filepath.Join(sessionRoot, "inputs", "previous", "manifest.json")) if err != nil { t.Fatalf("read restored previous manifest: %v", err) } - if !strings.Contains(string(previousManifestBytes), `"session_id": "2026-04-26"`) { + var previousManifest manifest.Manifest + if json.Unmarshal(previousManifestBytes, &previousManifest) != nil || previousManifest.SessionID != "2026-04-26" { t.Fatalf("restored previous manifest = %q, want previous session id", string(previousManifestBytes)) } - mustReadEquals(t, filepath.Join(sessionRoot, "previous", "artifacts", "session_recap.md"), "# previous recap\n") + mustReadEquals(t, filepath.Join(sessionRoot, "inputs", "previous", "artifacts", "session_recap.md"), "# previous recap\n") scriptoriumFake := &scriptorium.FakeRunner{} objectStoreConstructed := false @@ -245,7 +246,7 @@ previous_session_id: 2026-04-26 if got := req.InputPaths["transcript"]; got != filepath.Join(sessionRoot, "transcripts", "final.trimmed.json") { t.Fatalf("transcript input = %q, want trimmed transcript path", got) } - if got := req.InputPaths["previous_recap"]; got != filepath.Join(sessionRoot, "previous", "artifacts", "session_recap.md") { + if got := req.InputPaths["previous_recap"]; got != filepath.Join(sessionRoot, "inputs", "previous", "artifacts", "session_recap.md") { t.Fatalf("previous_recap input = %q, want restored previous cache path", got) } } @@ -261,6 +262,10 @@ func restoreWorkflowManifestJSON(t *testing.T, sessionID, campaign string) []byt for i, stageName := range stages { m.MarkStageSucceeded(stageName, now.Add(time.Duration(i+1)*time.Minute), nil) } + transcript := filepath.Join(t.TempDir(), "final.trimmed.json") + mustWriteTestFile(t, transcript, `{"segments":[]}`+"\n") + setCurrentBuiltInEvidence(t, m, "trim", artifacts.TranscriptOutputKindFinalTrimmed, artifacts.ArtifactTranscriptFinalTrimmed, transcript) + m.Stages["trim"].Outputs[0].LocalPath = "transcripts/final.trimmed.json" setAppAnalyzeEvidence(m, "session_recap", "artifacts/session_recap.md", []byte("# restored recap\n")) path := filepath.Join(t.TempDir(), "manifest.json") if err := store.Save(context.Background(), path, m); err != nil { diff --git a/internal/app/run_control_test.go b/internal/app/run_control_test.go index ca96058..bbc7e21 100644 --- a/internal/app/run_control_test.go +++ b/internal/app/run_control_test.go @@ -9,6 +9,7 @@ import ( "testing" "time" + "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" @@ -136,7 +137,11 @@ func TestPlannedStageModelMatchesStageExecution(t *testing.T) { t.Run(test.name, func(t *testing.T) { at := time.Date(2026, time.May, 3, 12, 0, 0, 0, time.UTC) cfg := testConfig(t) - workDir := filepath.Join(t.TempDir(), "run") + paths, err := artifacts.NewLocalStore(cfg.Pipeline.Workspace.Root).EnsureLayoutFor(cfg.Session.Campaign, cfg.Session.SessionID) + if err != nil { + t.Fatal(err) + } + workDir := filepath.Join(paths.RunsDir, "20260503T120000Z-a1b2c3d4") cfg.Pipeline.Notarius = &config.NotariusConfig{Enabled: test.result == nil || test.result.Disposition != stage.StageDispositionSkipped} planned := manifest.New("2026-05-03", at) executed := manifest.New("2026-05-03", at) @@ -164,6 +169,7 @@ func TestPlannedStageModelMatchesStageExecution(t *testing.T) { cfg: cfg, opts: RunOptions{Force: test.force}, identity: invocationIdentity{RunID: "20260503T120000Z-a1b2c3d4", LocalWorkDir: workDir}, + paths: paths, env: &stage.Env{Config: cfg}, manifestStore: &manifest.LocalStore{}, manifestPath: filepath.Join(t.TempDir(), "manifest.json"), diff --git a/internal/app/runner_test.go b/internal/app/runner_test.go index 45da295..7412aca 100644 --- a/internal/app/runner_test.go +++ b/internal/app/runner_test.go @@ -301,16 +301,15 @@ func TestExecuteStagesBindsResolvedConfigToEnvironment(t *testing.T) { } func TestExecuteStagesComposesNotariusOnlyForEnabledExtraction(t *testing.T) { - cfg := testConfig(t) - cfg.Pipeline.Notarius = &config.NotariusConfig{Enabled: true} + cfg, env, _ := extractionLifecycleFixture(t, true) captured := false - _, err := executeStages(context.Background(), cfg, []stage.Stage{captureNotariusStage{captured: &captured}}, RunOptions{}) + _, err := executeStages(context.Background(), cfg, []stage.Stage{captureNotariusStage{captured: &captured}}, RunOptions{Env: env}) if err != nil { t.Fatalf("executeStages() error = %v", err) } if !captured { - t.Fatal("extract stage did not receive the default Notarius runner") + t.Fatal("extract stage did not receive the Notarius runner") } if needsNotariusForRun(cfg, []stage.Stage{countingStage{name: "analyze", runs: new(int)}}) { @@ -1424,7 +1423,7 @@ func testConfig(t *testing.T) *config.Config { mustWriteFile(t, sessionPath, "session_id: 2026-05-03\ncampaign: sample-campaign\ninputs:\n audio_dir: ./audio\n") mustWriteFile(t, filepath.Join(cfgDir, "speakers.yml"), "alice: alice.flac\n") mustWriteFile(t, filepath.Join(cfgDir, "autocorrect.yml"), "[]\n") - mustWriteFile(t, filepath.Join(cfgDir, "glossary.yml"), "campaign: {entries: []}\n") + mustWriteFile(t, filepath.Join(cfgDir, "glossary.yml"), "schema_version: maximumdirect.glossary.v1\ncollections:\n campaign: {entries: []}\n") mustWriteFile(t, filepath.Join(cfgDir, "party.yml"), "schema_version: maximumdirect.rpg.party.v1\ncharacters:\n arannis:\n player: {name: Eric}\n character:\n name: Arannis\n classes: [{name: wizard}]\n") mustWriteFile(t, filepath.Join(cfgDir, "audio", "alice.flac"), "audio") partyDocument, err := config.ParseParty([]byte("schema_version: maximumdirect.rpg.party.v1\ncharacters:\n arannis:\n player: {name: Eric}\n character:\n name: Arannis\n classes: [{name: wizard}]\n")) @@ -1452,11 +1451,6 @@ func testConfig(t *testing.T) *config.Config { ConfigPath: campaignPath, Source: "campaign_config", }, - AutocorrectFile: config.ResolvedInputFile{ - Path: "./autocorrect.yml", - ConfigPath: campaignPath, - Source: "campaign_config", - }, GlossaryFile: config.ResolvedInputFile{ Path: "./glossary.yml", ConfigPath: campaignPath, @@ -1472,10 +1466,9 @@ func testConfig(t *testing.T) *config.Config { SessionID: "2026-05-03", Campaign: "sample-campaign", Inputs: config.SessionInputsConfig{ - AudioDir: "./audio", - SpeakersFile: "./speakers.yml", - AutocorrectFile: "./autocorrect.yml", - GlossaryFile: new(filepath.Join(cfgDir, "glossary.yml")), + AudioDir: "./audio", + SpeakersFile: "./speakers.yml", + GlossaryFile: new(filepath.Join(cfgDir, "glossary.yml")), }, }, } @@ -1493,19 +1486,19 @@ whisperx: notification: mode: noop ` - campaignYAML := `campaign_id: sample-campaign -inputs: - speakers_file: ./speakers.yml - autocorrect_file: ./autocorrect.yml - glossary_file: ./glossary.yml - party_file: ./party.yml + campaignYAML := `schema_version: maximumdirect.rpg.campaign.v1 +id: sample-campaign +references: {party: ./party.yml} +narratio: + inputs: + speakers_file: ./speakers.yml + glossary_file: ./glossary.yml ` sessionYAML := `session_id: 2026-05-03 campaign: sample-campaign inputs: audio_dir: ./audio speakers_file: ./speakers.yml - autocorrect_file: ./autocorrect.yml glossary_file: ./glossary.yml ` mustWriteFile(t, pipelinePath, pipelineYAML) diff --git a/internal/app/semantic_resume_test.go b/internal/app/semantic_resume_test.go index e3507bc..c7422ce 100644 --- a/internal/app/semantic_resume_test.go +++ b/internal/app/semantic_resume_test.go @@ -498,9 +498,16 @@ func TestOldPolishSemanticEvidenceIsReconsideredOnlyWhenSelected(t *testing.T) { } func TestDeliverySemanticChangesInvalidateOnlyTheirFixedDependents(t *testing.T) { - t.Run("extract contract", func(t *testing.T) { - cfg := testConfig(t) + t.Run("extract pipeline", func(t *testing.T) { + cfg, env, runner := extractionLifecycleFixture(t, true) + original := cfg.Pipeline.Notarius configureDeliverySemanticConfig(cfg) + cfg.Pipeline.Notarius.Binary = original.Binary + cfg.Pipeline.Notarius.ConfigPath = original.ConfigPath + cfg.Pipeline.Notarius.WorkingDirectory = original.WorkingDirectory + cfg.Pipeline.Notarius.Timeout = original.Timeout + cfg.Pipeline.Notarius.References = nil + runner.cfg = cfg.Pipeline.Notarius provider := canonicalSemanticProvider(t, "extract") seed := manifest.New(cfg.Session.SessionID, time.Now().UTC()) for _, name := range []string{"render", "extract", "analyze", "publish", "notify"} { @@ -518,7 +525,7 @@ func TestDeliverySemanticChangesInvalidateOnlyTheirFixedDependents(t *testing.T) cfg.Pipeline.Notarius.PipelineID = "session-v2" runs := 0 selected := semanticContractRunStub{name: "extract", provider: provider, runs: &runs} - if _, err := executeStages(context.Background(), cfg, []stage.Stage{selected}, RunOptions{}); err != nil { + if _, err := executeStages(context.Background(), cfg, []stage.Stage{selected}, RunOptions{Env: env}); err != nil { t.Fatal(err) } loaded, err := store.Load(context.Background(), manifestPathFor(cfg)) @@ -594,7 +601,7 @@ func configureDeliverySemanticConfig(cfg *config.Config) { Enabled: true, PipelineID: "session", References: map[string]string{"party": "narratio.input.party"}, Outputs: map[string]config.NotariusOutputConfig{ - "encounters": {LaneID: "encounters", MediaType: "application/json", SchemaID: "encounters", SchemaVersion: "1"}, + "encounters": {LaneID: "encounters"}, }, } cfg.Pipeline.Publish = &config.PublishConfig{ diff --git a/internal/app/session_cli_test.go b/internal/app/session_cli_test.go index d33dda1..e635031 100644 --- a/internal/app/session_cli_test.go +++ b/internal/app/session_cli_test.go @@ -20,7 +20,6 @@ campaign: sample-campaign inputs: audio_dir: ./audio speakers_file: ./speakers.yml - autocorrect_file: ./autocorrect.yml glossary_file: ./glossary.yml ` if err := os.WriteFile(sessionPath, []byte(sessionTemplate), 0o644); err != nil { @@ -72,7 +71,6 @@ campaign: sample-campaign inputs: audio_dir: ./audio speakers_file: ./speakers.yml - autocorrect_file: ./autocorrect.yml glossary_file: ./glossary.yml ` if err := os.WriteFile(sessionPath, []byte(sessionYAML), 0o644); err != nil { diff --git a/internal/app/substage_progress_test.go b/internal/app/substage_progress_test.go index 2a1c97f..96f3f36 100644 --- a/internal/app/substage_progress_test.go +++ b/internal/app/substage_progress_test.go @@ -94,8 +94,8 @@ func TestNativeProgressTracksDownloadsConcurrentSpeakersAndReuse(t *testing.T) { t.Fatalf("unexpected repeated work=%v", got) } _, diagnostic = executeProgressCommand(t, app, append([]string{"run", "2026-05-03", "--stage", "prepare", "--force"}, common...)) - if strings.Count(diagnostic, "reusing cached audio") != 4 || strings.Contains(diagnostic, "downloading audio") || len(store.Downloads) != 4 { - t.Fatalf("cache reuse claimed new downloads: %s", diagnostic) + if strings.Count(diagnostic, "reusing prepared audio") != 4 || strings.Contains(diagnostic, "downloading audio") || len(store.Downloads) != 4 { + t.Fatalf("prepared audio reuse claimed new downloads: %s", diagnostic) } store.SeedObject(storage.FakeObject{Key: prefix + "audio/a.flac", Data: []byte("replacement-audio"), ETag: "new-generation"}) cause := errors.New("audio download failed") diff --git a/internal/artifactpolicy/policy.go b/internal/artifactpolicy/policy.go index 980e085..970d3bc 100644 --- a/internal/artifactpolicy/policy.go +++ b/internal/artifactpolicy/policy.go @@ -21,7 +21,6 @@ const ( SourceInputGlossarySetting = "narratio.input.glossary.setting" SourceInputGlossarySpells = "narratio.input.glossary.spells" SourceInputGlossaryCombined = "narratio.input.glossary.combined" - SourceInputSpellCatalog = "narratio.input.spell_catalog" configuredSourcePrefix = "narratio.artifact." extractionSourcePrefix = "narratio.extraction." diff --git a/internal/artifactpolicy/policy_test.go b/internal/artifactpolicy/policy_test.go index a5c1881..267ef80 100644 --- a/internal/artifactpolicy/policy_test.go +++ b/internal/artifactpolicy/policy_test.go @@ -242,10 +242,10 @@ func TestDescribePreparedInputSource(t *testing.T) { if _, ok := DescribePreparedInputSource("narratio.input.unknown"); ok { t.Fatal("DescribePreparedInputSource(unknown) ok = true") } - if _, ok := DescribePreparedInputSource(SourceInputSpellCatalog); ok { + if _, ok := DescribePreparedInputSource("narratio.input.spell_catalog"); ok { t.Fatal("retired spell catalog source was accepted") } - if _, err := ClassifySource(SourceInputSpellCatalog); err == nil { + if _, err := ClassifySource("narratio.input.spell_catalog"); err == nil { t.Fatal("retired spell catalog source was classified") } } diff --git a/internal/artifacts/catalog.go b/internal/artifacts/catalog.go index 9fa7043..403fffd 100644 --- a/internal/artifacts/catalog.go +++ b/internal/artifacts/catalog.go @@ -25,13 +25,9 @@ type ConfiguredArtifactDefinition struct { // ExtractionArtifactDefinition describes one configured Notarius output lane. type ExtractionArtifactDefinition struct { - LaneID string - PipelineID string - Filename string - MediaType string - SchemaID string - SchemaVersion string - ModuleKey string + LaneID string + PipelineID string + Filename string } // ExtractionDefinitionsFromConfig converts the effective Notarius output map into catalog definitions. diff --git a/internal/artifacts/extraction_catalog_test.go b/internal/artifacts/extraction_catalog_test.go index d763fd7..188aaee 100644 --- a/internal/artifacts/extraction_catalog_test.go +++ b/internal/artifacts/extraction_catalog_test.go @@ -56,7 +56,7 @@ func TestArtifactCatalogRejectsDuplicateExtractionRegistration(t *testing.T) { } } -func TestHydrateExtractionArtifactsAcceptsOnlyCompleteCurrentBundle(t *testing.T) { +func TestHydrateExtractionArtifactsAcceptsCurrentFlatEvidence(t *testing.T) { paths, currentManifest, definitions := validExtractionCatalogFixture(t) catalog := registeredExtractionCatalog(t, definitions) catalog.HydrateExtractionArtifacts(paths, currentManifest, definitions) @@ -76,9 +76,6 @@ func TestHydrateExtractionArtifactsAcceptsOnlyCompleteCurrentBundle(t *testing.T if entry.Checksum != wantOutput.Checksum || entry.Size != info.Size() { t.Fatalf("hydrated content identity = (%q, %d), want (%q, %d)", entry.Checksum, entry.Size, wantOutput.Checksum, info.Size()) } - if entry.Contract == nil || *entry.Contract != *wantOutput.Contract { - t.Fatalf("hydrated contract = %#v, want %#v", entry.Contract, wantOutput.Contract) - } resolved, err := ResolveSessionArtifactWithCatalog(paths, currentManifest, entry.SourceID, catalog) if err != nil { t.Fatalf("ResolveSessionArtifactWithCatalog() error = %v", err) @@ -88,7 +85,7 @@ func TestHydrateExtractionArtifactsAcceptsOnlyCompleteCurrentBundle(t *testing.T } } -func TestInspectExtractionEvidenceClassifiesBundleStates(t *testing.T) { +func TestInspectExtractionEvidenceClassifiesCurrentStates(t *testing.T) { tests := []struct { name string state ExtractionEvidenceState @@ -100,8 +97,8 @@ func TestInspectExtractionEvidenceClassifiesBundleStates(t *testing.T) { {name: "absent", state: ExtractionEvidenceAbsent, mutate: func(_ *testing.T, _ *SessionPaths, m *manifest.Manifest) { m.Stages["extract"].Status = manifest.StatusFailed }}, - {name: "obsolete version", state: ExtractionEvidenceObsolete, mutate: func(_ *testing.T, _ *SessionPaths, m *manifest.Manifest) { - m.Stages["extract"].Outputs[0].Contract.SchemaVersion = "99" + {name: "wrong size", state: ExtractionEvidenceObsolete, mutate: func(_ *testing.T, _ *SessionPaths, m *manifest.Manifest) { + m.Stages["extract"].Outputs[0].Size++ }}, {name: "changed direct transcript", wantInputUnavailable: true, recomputeInputIdentity: true, mutate: func(t *testing.T, _ *SessionPaths, m *manifest.Manifest) { writeExtractionFixtureFile(t, m.Stages["trim"].Outputs[0].LocalPath, `{"segments":[{"id":"changed"}]}`) @@ -179,11 +176,11 @@ func TestHydrateExtractionArtifactsRejectsUntrustedManifestState(t *testing.T) { {name: "inconsistent producer identity", mutate: func(_ *testing.T, _ SessionPaths, m *manifest.Manifest) { m.Stages["extract"].Outputs[0].ProducerRunID = "another-run" }}, - {name: "incompatible contract", mutate: func(_ *testing.T, _ SessionPaths, m *manifest.Manifest) { - m.Stages["extract"].Outputs[0].Contract.SchemaVersion = "99" + {name: "incorrect size", mutate: func(_ *testing.T, _ SessionPaths, m *manifest.Manifest) { + m.Stages["extract"].Outputs[0].Size++ }}, {name: "incompatible provenance", mutate: func(_ *testing.T, _ SessionPaths, m *manifest.Manifest) { - m.Stages["extract"].Outputs[0].ExternalProvenance.RunID = "another-notarius-run" + m.Stages["extract"].Outputs[0].ExternalProvenance.ArtifactID = "other-lane" }}, {name: "missing file", mutate: func(t *testing.T, _ SessionPaths, m *manifest.Manifest) { if err := os.Remove(m.Stages["extract"].Outputs[0].LocalPath); err != nil { @@ -244,8 +241,7 @@ func setExtractionStatus(status manifest.StageStatus) func(*testing.T, SessionPa func extractionFixtureDefinitions() map[string]ExtractionArtifactDefinition { return map[string]ExtractionArtifactDefinition{ "encounters": { - LaneID: "encounters", PipelineID: "campaign.extract", MediaType: "application/json", - SchemaID: "encounters", SchemaVersion: "1", ModuleKey: "encounters", + LaneID: "encounters", PipelineID: "campaign.extract", }, } } @@ -264,11 +260,8 @@ func validExtractionCatalogFixture(t *testing.T) (SessionPaths, *manifest.Manife root := t.TempDir() paths := SessionPaths{Root: root, ArtifactsDir: filepath.Join(root, "artifacts")} trimmedPath := filepath.Join(paths.Root, filepath.FromSlash(TranscriptPathFinalTrimmed)) - bundleRoot := filepath.Join(paths.ArtifactsDir, "notarius", "extract-run-1") - lanePath := filepath.Join(bundleRoot, "lanes", "encounters.json") - indexPath := filepath.Join(bundleRoot, "index.json") + lanePath := filepath.Join(paths.ArtifactsDir, "encounters.json") writeExtractionFixtureFile(t, lanePath, `{"encounters":[]}`) - writeExtractionFixtureFile(t, indexPath, `{"lanes":[]}`) writeExtractionFixtureFile(t, trimmedPath, `{"segments":[]}`) definitions := extractionFixtureDefinitions() m := manifest.New("session", fixtureTime) @@ -285,18 +278,16 @@ func validExtractionCatalogFixture(t *testing.T) (SessionPaths, *manifest.Manife m.Stages["extract"] = &manifest.StageRecord{ Name: "extract", Status: manifest.StatusSucceeded, Metadata: map[string]any{ - "narratio_run_id": "extract-run-1", "bundle_root": bundleRoot, - "receipt": map[string]any{"run_id": "notarius-run-1", "pipeline_id": "campaign.extract"}, + "narratio_run_id": "extract-run-1", + "completion": map[string]any{"pipeline": "campaign.extract"}, extractionMetadataInput: input.Metadata(), }, Outputs: []manifest.ArtifactRecord{ { Kind: "notarius_lane", SourceID: ExtractionArtifactSourceID("encounters"), LocalPath: lanePath, - ProducerRunID: "extract-run-1", Checksum: extractionFixtureChecksum(t, lanePath), - 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"}, + ProducerRunID: "extract-run-1", Checksum: extractionFixtureChecksum(t, lanePath), Size: int64(len(`{"encounters":[]}`)), + ExternalProvenance: &artifactmodel.ExternalProvenance{System: "notarius", PipelineID: "campaign.extract", ArtifactID: "encounters"}, }, - {Kind: "notarius_index", LocalPath: indexPath, ProducerRunID: "extract-run-1", Checksum: extractionFixtureChecksum(t, indexPath)}, }, } return paths, m, definitions diff --git a/internal/artifacts/paths.go b/internal/artifacts/paths.go index e00f153..883596c 100644 --- a/internal/artifacts/paths.go +++ b/internal/artifacts/paths.go @@ -132,8 +132,8 @@ func SessionRunExtractDirForCampaign(rootDir, campaign, sessionID, runID string) return SessionRunStageDirForCampaign(rootDir, campaign, sessionID, runID, "extract") } -// SessionRunNotariusReceiptPathForCampaign returns the invocation's captured completion report. -func SessionRunNotariusReceiptPathForCampaign(rootDir, campaign, sessionID, runID string) string { +// SessionRunNotariusReportPathForCampaign returns the invocation's captured completion report. +func SessionRunNotariusReportPathForCampaign(rootDir, campaign, sessionID, runID string) string { return filepath.Join(SessionRunExtractDirForCampaign(rootDir, campaign, sessionID, runID), "logs", "notarius.report.json") } @@ -178,16 +178,6 @@ func SessionNotariusReferenceSnapshotPath(paths SessionPaths, checksum, prepared ) } -// SessionNotariusBundleDirForCampaign returns one immutable durable bundle destination. -func SessionNotariusBundleDirForCampaign(rootDir, campaign, sessionID, runID string) string { - return filepath.Join( - SessionWorkDirForCampaign(rootDir, campaign, sessionID), - config.PathArtifactsDirSegment, - "notarius", - runID, - ) -} - // SessionPreviousDir returns the previous-session state directory for already-resolved session paths. func SessionPreviousDir(paths SessionPaths) string { return paths.PreviousDir diff --git a/internal/artifacts/paths_model_test.go b/internal/artifacts/paths_model_test.go index 81c0994..08445f7 100644 --- a/internal/artifacts/paths_model_test.go +++ b/internal/artifacts/paths_model_test.go @@ -82,10 +82,9 @@ func TestSessionNotariusPathsForCampaign(t *testing.T) { want string }{ {name: "extract directory", got: SessionRunExtractDirForCampaign(root, campaign, sessionID, runID), want: extractDir}, - {name: "report", got: SessionRunNotariusReceiptPathForCampaign(root, campaign, sessionID, runID), want: filepath.Join(extractDir, "logs", "notarius.report.json")}, + {name: "report", got: SessionRunNotariusReportPathForCampaign(root, campaign, sessionID, runID), want: filepath.Join(extractDir, "logs", "notarius.report.json")}, {name: "stderr", got: SessionRunNotariusLogPathForCampaign(root, campaign, sessionID, runID), want: filepath.Join(extractDir, "logs", "notarius.stderr.log")}, {name: "output root", got: SessionRunNotariusOutputRootForCampaign(root, campaign, sessionID, runID), want: filepath.Join(extractDir, "notarius-output")}, - {name: "durable bundle", got: SessionNotariusBundleDirForCampaign(root, campaign, sessionID, runID), want: filepath.Join(root, "work", campaign, sessionID, "artifacts", "notarius", runID)}, } for _, test := range tests { t.Run(test.name, func(t *testing.T) { diff --git a/internal/config/artifact_families_test.go b/internal/config/artifact_families_test.go index 3bbc4e9..cb024f5 100644 --- a/internal/config/artifact_families_test.go +++ b/internal/config/artifact_families_test.go @@ -40,7 +40,7 @@ characters: for_each: party.characters prompt_id: dnd.character_items profile_id: production - output_path_pattern: artifacts/characters/{character_id}/items.md + output_path_pattern: artifacts/{character_id}-items.md inputs: transcript: {source: narratio.transcript.final_trimmed, required: true} member_vars: @@ -56,7 +56,7 @@ characters: for_each: party.characters prompt_id: dnd.character_meta profile_id: production - output_path_pattern: artifacts/characters/{character_id}/meta.md + output_path_pattern: artifacts/{character_id}-meta.md inputs: transcript: {source: narratio.transcript.final_trimmed, required: true} `)) @@ -77,7 +77,7 @@ characters: t.Fatalf("artifact keys = %#v, want %#v", keys, wantKeys) } alpha := cfg.ArtifactCatalog.Artifacts["character_items_alpha"] - if alpha.Enabled || alpha.OutputPath != "artifacts/characters/alpha/items.md" { + if alpha.Enabled || alpha.OutputPath != "artifacts/alpha-items.md" { t.Fatalf("alpha artifact = %#v", alpha) } if !reflect.DeepEqual(alpha.Vars, map[string]any{ @@ -138,7 +138,7 @@ func TestArtifactFamiliesRejectInvalidExpansionDeclarations(t *testing.T) { {name: "repeated token", party: canonicalPartyFixture, families: strings.Replace(validFamilyYAML, "meta.md", "{character_id}.md", 1), wantError: "must contain exactly one"}, {name: "member selector", party: canonicalPartyFixture, families: strings.Replace(validFamilyYAML, "character.name", "character.unknown", 1), wantError: "selector"}, {name: "static variable collision", party: canonicalPartyFixture, families: strings.Replace(validFamilyYAML, "member_vars:\n character_name", "vars:\n character_name: static\n member_vars:\n character_name", 1), wantError: "conflicts with static vars"}, - {name: "unsafe output", party: canonicalPartyFixture, families: strings.Replace(validFamilyYAML, "artifacts/characters/{character_id}/meta.md", "../{character_id}.md", 1), wantError: "must not contain path traversal"}, + {name: "unsafe output", party: canonicalPartyFixture, families: strings.Replace(validFamilyYAML, "artifacts/{character_id}-meta.md", "../{character_id}.md", 1), wantError: "must not contain path traversal"}, } for _, test := range tests { t.Run(test.name, func(t *testing.T) { @@ -169,7 +169,7 @@ func TestArtifactFamiliesRejectGeneratedKeyAndOutputCollisions(t *testing.T) { } base := ScriptoriumArtifactFamilyConfig{ ForEach: partyCharactersFamilySource, PromptID: "dnd.character_meta", - OutputPathPattern: "artifacts/characters/{character_id}/meta.md", + OutputPathPattern: "artifacts/{character_id}-meta.md", } for _, test := range []struct { name string @@ -183,7 +183,7 @@ func TestArtifactFamiliesRejectGeneratedKeyAndOutputCollisions(t *testing.T) { }, { name: "generated output", artifacts: map[string]ScriptoriumArtifactConfig{ - "existing": {OutputPath: "artifacts/characters/arannis/meta.md"}, + "existing": {OutputPath: "artifacts/arannis-meta.md"}, }, wantError: "generates output path", }, } { @@ -215,12 +215,12 @@ characters: enabled: true for_each: party.characters prompt_id: dnd.character_meta - output_path_pattern: artifacts/characters/{character_id}/meta.md + output_path_pattern: artifacts/{character_id}-meta.md character_items: enabled: true for_each: party.characters prompt_id: dnd.character_items - output_path_pattern: artifacts/characters/{character_id}/items.md + output_path_pattern: artifacts/{character_id}-items.md depends_on: [session_recap] inputs: transcript: {source: narratio.transcript.final_trimmed, required: true} @@ -589,7 +589,7 @@ const validFamilyYAML = ` for_each: party.characters prompt_id: dnd.character_meta profile_id: production - output_path_pattern: artifacts/characters/{character_id}/meta.md + output_path_pattern: artifacts/{character_id}-meta.md member_vars: character_name: character.name ` diff --git a/internal/config/campaign_config_test.go b/internal/config/campaign_config_test.go index aa48fe0..a248476 100644 --- a/internal/config/campaign_config_test.go +++ b/internal/config/campaign_config_test.go @@ -35,9 +35,9 @@ notification: } } -func TestCampaignStrictDecodeAcceptsCampaignID(t *testing.T) { +func TestCampaignStrictDecodeAcceptsSharedID(t *testing.T) { pipelinePath, campaignPath, sessionPath := writeCampaignConfigTestFiles(t, - "campaign_id: sample-campaign\ninputs:\n speakers_file: ./speakers.yml\n autocorrect_file: ./autocorrect.yml\n glossary_file: ./glossary.yml\n party_file: ./party.yml\n", + "schema_version: maximumdirect.rpg.campaign.v1\nid: sample-campaign\nreferences: {party: ./party.yml}\nnarratio:\n inputs:\n speakers_file: ./speakers.yml\n glossary_file: ./glossary.yml\n", "session_id: 2026-05-03\ninputs:\n audio_dir: ./audio\n", ) @@ -60,14 +60,14 @@ func TestCampaignStrictDecodeRejectsLegacyCampaignField(t *testing.T) { if err == nil { t.Fatal("expected load error, got nil") } - if !strings.Contains(configurationErrorText(err), "load campaign config") || !strings.Contains(configurationErrorText(err), "decode.unknown_field") { - t.Fatalf("error = %q, want campaign strict decode context", configurationErrorText(err)) + if !strings.Contains(configurationErrorText(err), "load campaign config") || !strings.Contains(configurationErrorText(err), "retired campaign field") { + t.Fatalf("error = %q, want retired field context", configurationErrorText(err)) } } func TestCampaignStrictDecodeRejectsUnknownFields(t *testing.T) { pipelinePath, campaignPath, sessionPath := writeCampaignConfigTestFiles(t, - "campaign_id: sample-campaign\nunknown: true\ninputs:\n speakers_file: ./speakers.yml\n autocorrect_file: ./autocorrect.yml\n glossary_file: ./glossary.yml\n party_file: ./party.yml\n", + "schema_version: maximumdirect.rpg.campaign.v1\nid: sample-campaign\nreferences: {party: ./party.yml}\nnarratio:\n unknown: true\n inputs: {speakers_file: ./speakers.yml}\n", "session_id: 2026-05-03\ninputs:\n audio_dir: ./audio\n", ) @@ -82,7 +82,7 @@ func TestCampaignStrictDecodeRejectsUnknownFields(t *testing.T) { func TestCampaignStrictDecodeAcceptsSessionTemplateFile(t *testing.T) { pipelinePath, campaignPath, sessionPath := writeCampaignConfigTestFiles(t, - "campaign_id: sample-campaign\nsession_template_file: ./session.template.yml\ninputs:\n speakers_file: ./speakers.yml\n autocorrect_file: ./autocorrect.yml\n glossary_file: ./glossary.yml\n party_file: ./party.yml\n", + "schema_version: maximumdirect.rpg.campaign.v1\nid: sample-campaign\nreferences: {party: ./party.yml}\nnarratio:\n session_template_file: ./session.template.yml\n inputs:\n speakers_file: ./speakers.yml\n glossary_file: ./glossary.yml\n", "session_id: 2026-05-03\ninputs:\n audio_dir: ./audio\n", ) @@ -97,7 +97,7 @@ func TestCampaignStrictDecodeAcceptsSessionTemplateFile(t *testing.T) { func TestCampaignSessionMergeFillsStableInputs(t *testing.T) { pipelinePath, campaignPath, sessionPath := writeCampaignConfigTestFiles(t, - "campaign_id: sample-campaign\ninputs:\n speakers_file: ./campaign-speakers.yml\n autocorrect_file: ./campaign-autocorrect.yml\n glossary_file: ./campaign-glossary.yml\n party_file: ./campaign-party.yml\n", + "schema_version: maximumdirect.rpg.campaign.v1\nid: sample-campaign\nreferences: {party: ./campaign-party.yml}\nnarratio:\n inputs:\n speakers_file: ./campaign-speakers.yml\n glossary_file: ./campaign-glossary.yml\n", "session_id: 2026-05-03\ninputs:\n audio_dir: ./audio\n", ) @@ -112,14 +112,13 @@ func TestCampaignSessionMergeFillsStableInputs(t *testing.T) { t.Fatalf("session campaign = %q, want campaign config value", cfg.Session.Campaign) } assertResolvedStableInput(t, cfg.StableInputs.SpeakersFile, "./campaign-speakers.yml", campaignPath, "campaign_config") - assertResolvedStableInput(t, cfg.StableInputs.AutocorrectFile, "./campaign-autocorrect.yml", campaignPath, "campaign_config") assertResolvedStableInput(t, cfg.StableInputs.GlossaryFile, "./campaign-glossary.yml", campaignPath, "campaign_config") assertResolvedStableInput(t, cfg.StableInputs.PartyFile, "./campaign-party.yml", campaignPath, "campaign_config") } func TestCampaignSessionMergeSessionOverridesStableInputs(t *testing.T) { pipelinePath, campaignPath, sessionPath := writeCampaignConfigTestFiles(t, - "campaign_id: sample-campaign\ninputs:\n speakers_file: ./campaign-speakers.yml\n autocorrect_file: ./campaign-autocorrect.yml\n glossary_file: ./campaign-glossary.yml\n party_file: ./campaign-party.yml\n", + "schema_version: maximumdirect.rpg.campaign.v1\nid: sample-campaign\nreferences: {party: ./campaign-party.yml}\nnarratio:\n inputs:\n speakers_file: ./campaign-speakers.yml\n glossary_file: ./campaign-glossary.yml\n", "session_id: 2026-05-03\ncampaign: sample-campaign\ninputs:\n audio_dir: ./audio\n speakers_file: ./session-speakers.yml\n", ) @@ -131,82 +130,13 @@ func TestCampaignSessionMergeSessionOverridesStableInputs(t *testing.T) { t.Fatalf("Validate() error = %v", err) } assertResolvedStableInput(t, cfg.StableInputs.SpeakersFile, "./session-speakers.yml", sessionPath, "session_config") - assertResolvedStableInput(t, cfg.StableInputs.AutocorrectFile, "./campaign-autocorrect.yml", campaignPath, "campaign_config") assertResolvedStableInput(t, cfg.StableInputs.GlossaryFile, "./campaign-glossary.yml", campaignPath, "campaign_config") assertResolvedStableInput(t, cfg.StableInputs.PartyFile, "./campaign-party.yml", campaignPath, "campaign_config") } -func TestCampaignSessionMergeSpellCatalog(t *testing.T) { - tests := []struct { - name string - campaignValue string - sessionValue string - wantPath string - wantSource string - }{ - {name: "omitted", wantPath: "", wantSource: "campaign_config"}, - {name: "campaign inherited", campaignValue: "./campaign-spells.json", wantPath: "./campaign-spells.json", wantSource: "campaign_config"}, - {name: "session override", campaignValue: "./campaign-spells.json", sessionValue: "./session-spells.json", wantPath: "./session-spells.json", wantSource: "session_config"}, - } - - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - campaignSpell := "" - if tt.campaignValue != "" { - campaignSpell = " spell_catalog_file: " + tt.campaignValue + "\n" - } - sessionSpell := "" - if tt.sessionValue != "" { - sessionSpell = " spell_catalog_file: " + tt.sessionValue + "\n" - } - pipelinePath, campaignPath, sessionPath := writeCampaignConfigTestFiles(t, - "campaign_id: sample-campaign\ninputs:\n speakers_file: ./speakers.yml\n autocorrect_file: ./autocorrect.yml\n glossary_file: ./glossary.yml\n party_file: ./party.yml\n"+campaignSpell, - "session_id: 2026-05-03\ninputs:\n audio_dir: ./audio\n"+sessionSpell, - ) - - cfg, err := LoadWithSessionOptions(pipelinePath, campaignPath, sessionPath, SessionLoadOptions{}) - if err != nil { - t.Fatalf("LoadWithSessionOptions() error = %v", err) - } - wantConfigPath := campaignPath - if tt.wantSource == "session_config" { - wantConfigPath = sessionPath - } - assertResolvedStableInput(t, cfg.StableInputs.SpellCatalogFile, tt.wantPath, wantConfigPath, tt.wantSource) - if cfg.Session.Inputs.SpellCatalogFile != cfg.StableInputs.SpellCatalogFile.Path { - t.Fatalf("session spell_catalog_file = %q, want %q", cfg.Session.Inputs.SpellCatalogFile, cfg.StableInputs.SpellCatalogFile.Path) - } - }) - } -} - -func TestCampaignSessionMergeRejectsWhitespaceSpellCatalog(t *testing.T) { - tests := []struct { - name string - campaignLine string - sessionLine string - wantErr string - }{ - {name: "campaign", campaignLine: " spell_catalog_file: ' '\n", wantErr: "campaign.inputs.spell_catalog_file"}, - {name: "session", sessionLine: " spell_catalog_file: ' '\n", wantErr: "session.inputs.spell_catalog_file"}, - } - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - pipelinePath, campaignPath, sessionPath := writeCampaignConfigTestFiles(t, - "campaign_id: sample-campaign\ninputs:\n speakers_file: ./speakers.yml\n autocorrect_file: ./autocorrect.yml\n glossary_file: ./glossary.yml\n party_file: ./party.yml\n"+tt.campaignLine, - "session_id: 2026-05-03\ninputs:\n audio_dir: ./audio\n"+tt.sessionLine, - ) - _, err := LoadWithSessionOptions(pipelinePath, campaignPath, sessionPath, SessionLoadOptions{}) - if err == nil || !strings.Contains(configurationErrorText(err), tt.wantErr) { - t.Fatalf("LoadWithSessionOptions() error = %v, want containing %q", err, tt.wantErr) - } - }) - } -} - func TestCampaignWithCanonicalPartyDoesNotRequirePlayersInput(t *testing.T) { pipelinePath, campaignPath, sessionPath := writeCampaignConfigTestFiles(t, - "campaign_id: sample-campaign\ninputs:\n speakers_file: ./speakers.yml\n autocorrect_file: ./autocorrect.yml\n glossary_file: ./glossary.yml\n party_file: ./party.yml\n", + "schema_version: maximumdirect.rpg.campaign.v1\nid: sample-campaign\nreferences: {party: ./party.yml}\nnarratio:\n inputs:\n speakers_file: ./speakers.yml\n glossary_file: ./glossary.yml\n", "session_id: 2026-05-03\ninputs:\n audio_dir: ./audio\n", ) @@ -217,7 +147,7 @@ func TestCampaignWithCanonicalPartyDoesNotRequirePlayersInput(t *testing.T) { func TestCampaignSessionMismatchFails(t *testing.T) { pipelinePath, campaignPath, sessionPath := writeCampaignConfigTestFiles(t, - "campaign_id: sample-campaign\ninputs:\n speakers_file: ./speakers.yml\n autocorrect_file: ./autocorrect.yml\n glossary_file: ./glossary.yml\n party_file: ./party.yml\n", + "schema_version: maximumdirect.rpg.campaign.v1\nid: sample-campaign\nreferences: {party: ./party.yml}\nnarratio:\n inputs:\n speakers_file: ./speakers.yml\n glossary_file: ./glossary.yml\n", "session_id: 2026-05-03\ncampaign: other-campaign\ninputs:\n audio_dir: ./audio\n", ) @@ -232,7 +162,7 @@ func TestCampaignSessionMismatchFails(t *testing.T) { func TestLoadMissingCampaignFileFails(t *testing.T) { pipelinePath, _, sessionPath := writeCampaignConfigTestFiles(t, - "campaign_id: sample-campaign\ninputs:\n speakers_file: ./speakers.yml\n autocorrect_file: ./autocorrect.yml\n glossary_file: ./glossary.yml\n party_file: ./party.yml\n", + "schema_version: maximumdirect.rpg.campaign.v1\nid: sample-campaign\nreferences: {party: ./party.yml}\nnarratio:\n inputs:\n speakers_file: ./speakers.yml\n glossary_file: ./glossary.yml\n", "session_id: 2026-05-03\ninputs:\n audio_dir: ./audio\n", ) missingCampaignPath := filepath.Join(filepath.Dir(sessionPath), "missing-campaign.yml") diff --git a/internal/config/catalog_derivation_test.go b/internal/config/catalog_derivation_test.go index f61de5a..fb011e9 100644 --- a/internal/config/catalog_derivation_test.go +++ b/internal/config/catalog_derivation_test.go @@ -106,7 +106,7 @@ characters: func TestExplicitPartySelectionNeverFallsBack(t *testing.T) { dir := t.TempDir() - campaignPath := writePipelineFixture(t, dir, "campaign.yml", "campaign_id: campaign\ninputs: {speakers_file: speakers.yml, autocorrect_file: autocorrect.yml, glossary_file: glossary.yml, party_file: party.yml}\n") + campaignPath := writePipelineFixture(t, dir, "campaign.yml", "schema_version: maximumdirect.rpg.campaign.v1\nid: campaign\nreferences: {party: party.yml}\nnarratio: {inputs: {speakers_file: speakers.yml, glossary_file: glossary.yml}}\n") writePipelineFixture(t, dir, "party.yml", canonicalPartyFixture) campaign, err := LoadCampaign(campaignPath) if err != nil { diff --git a/internal/config/config.go b/internal/config/config.go index 4d7aabf..5cf159c 100644 --- a/internal/config/config.go +++ b/internal/config/config.go @@ -132,15 +132,13 @@ type AutocorrectionRule struct { // CampaignInputsConfig contains stable campaign-level input file references. type CampaignInputsConfig struct { - Setting *string `yaml:"setting" json:"setting"` - System *string `yaml:"system" json:"system"` - Glossary map[string]any `yaml:"glossary" json:"glossary"` - SpeakersFile string `yaml:"speakers_file" json:"speakers_file"` - AutocorrectFile string `yaml:"-" json:"-"` - GlossaryFile *string `yaml:"glossary_file" json:"glossary_file"` - PartyFile string `yaml:"party_file" json:"party_file"` - SpellCatalogFile string `yaml:"-" json:"-"` - Autocorrect []AutocorrectionRule `yaml:"autocorrect" json:"autocorrect"` + Setting *string `yaml:"setting" json:"setting"` + System *string `yaml:"system" json:"system"` + Glossary map[string]any `yaml:"glossary" json:"glossary"` + SpeakersFile string `yaml:"speakers_file" json:"speakers_file"` + GlossaryFile *string `yaml:"glossary_file" json:"glossary_file"` + PartyFile string `yaml:"party_file" json:"party_file"` + Autocorrect []AutocorrectionRule `yaml:"autocorrect" json:"autocorrect"` } // SessionConfig contains per-session inputs and metadata. @@ -371,8 +369,6 @@ type NotariusConfig struct { ConfigOverlay *string `yaml:"config_overlay,omitempty" json:"config_overlay,omitempty"` Cache *string `yaml:"cache,omitempty" json:"cache,omitempty"` Debug bool `yaml:"debug,omitempty" json:"debug,omitempty"` - Resume bool `yaml:"-" json:"-"` - ChunkCache string `yaml:"-" json:"-"` ConfigPath string `yaml:"config_path" json:"config_path"` PipelineID string `yaml:"pipeline_id" json:"pipeline_id"` Timeout string `yaml:"timeout" json:"timeout"` @@ -381,14 +377,10 @@ type NotariusConfig struct { Outputs map[string]NotariusOutputConfig `yaml:"outputs" json:"outputs"` } -// NotariusOutputConfig declares one required extraction lane contract. +// NotariusOutputConfig declares one required extraction lane and destination. type NotariusOutputConfig struct { - LaneID string `yaml:"lane_id" json:"lane_id"` - Filename string `yaml:"filename,omitempty" json:"filename,omitempty"` - MediaType string `yaml:"-" json:"-"` - SchemaID string `yaml:"-" json:"-"` - SchemaVersion string `yaml:"-" json:"-"` - ModuleKey string `yaml:"-" json:"-"` + LaneID string `yaml:"lane_id" json:"lane_id"` + Filename string `yaml:"filename,omitempty" json:"filename,omitempty"` } // NotificationConfig configures the supported notification behavior. @@ -398,17 +390,15 @@ type NotificationConfig struct { // SessionInputsConfig contains per-session input references. type SessionInputsConfig struct { - Setting *string `yaml:"setting" json:"setting"` - System *string `yaml:"system" json:"system"` - Glossary map[string]any `yaml:"glossary" json:"glossary"` - AudioDir string `yaml:"audio_dir" json:"audio_dir"` - AudioFiles []string `yaml:"audio_files" json:"audio_files"` - AudioS3 *SessionAudioS3Input `yaml:"audio_s3" json:"audio_s3"` - SpeakersFile string `yaml:"speakers_file" json:"speakers_file"` - AutocorrectFile string `yaml:"-" json:"-"` - Autocorrect []AutocorrectionRule `yaml:"autocorrect" json:"autocorrect"` - GlossaryFile *string `yaml:"glossary_file" json:"glossary_file"` - SpellCatalogFile string `yaml:"-" json:"-"` + Setting *string `yaml:"setting" json:"setting"` + System *string `yaml:"system" json:"system"` + Glossary map[string]any `yaml:"glossary" json:"glossary"` + AudioDir string `yaml:"audio_dir" json:"audio_dir"` + AudioFiles []string `yaml:"audio_files" json:"audio_files"` + AudioS3 *SessionAudioS3Input `yaml:"audio_s3" json:"audio_s3"` + SpeakersFile string `yaml:"speakers_file" json:"speakers_file"` + Autocorrect []AutocorrectionRule `yaml:"autocorrect" json:"autocorrect"` + GlossaryFile *string `yaml:"glossary_file" json:"glossary_file"` } // SessionAudioS3Input configures S3 session-audio input discovery. @@ -418,11 +408,9 @@ type SessionAudioS3Input struct { // ResolvedStableInputs records the origins of completed stable input paths. type ResolvedStableInputs struct { - SpeakersFile ResolvedInputFile - AutocorrectFile ResolvedInputFile - GlossaryFile ResolvedInputFile - PartyFile ResolvedInputFile - SpellCatalogFile ResolvedInputFile + SpeakersFile ResolvedInputFile + GlossaryFile ResolvedInputFile + PartyFile ResolvedInputFile } // ResolvedInputFile records one effective input path and its declaring source. diff --git a/internal/config/document_imports_test.go b/internal/config/document_imports_test.go index 0ffb0df..f65c185 100644 --- a/internal/config/document_imports_test.go +++ b/internal/config/document_imports_test.go @@ -10,13 +10,14 @@ import ( func TestImportedCampaignAndSessionResourcesRetainTheirSources(t *testing.T) { dir := t.TempDir() pipeline := writePipelineFixture(t, dir, "pipeline.yml", testTranscriptionConfig+"workspace: {root: /tmp/narratio}\n") - campaign := writePipelineFixture(t, dir, "campaign.yml", "config:\n imports:\n - path: campaign/shared.yml\ncampaign_id: sample\n") - fragment := writePipelineFixture(t, dir, "campaign/shared.yml", `session_template_file: templates/session.yml -inputs: - speakers_file: speakers.yml - autocorrect_file: autocorrect.yml - glossary_file: glossary.yml - party_file: party.yml + campaign := writePipelineFixture(t, dir, "campaign.yml", "config:\n imports:\n - path: campaign/shared.yml\nschema_version: maximumdirect.rpg.campaign.v1\nid: sample\n") + fragment := writePipelineFixture(t, dir, "campaign/shared.yml", `references: + party: party.yml +narratio: + session_template_file: templates/session.yml + inputs: + speakers_file: speakers.yml + glossary_file: glossary.yml `) writePipelineFixture(t, dir, "campaign/party.yml", canonicalPartyFixture) session := writePipelineFixture(t, dir, "session.yml", "config:\n imports:\n - path: session/inputs.yml\nsession_id: sample-session\n") @@ -98,9 +99,9 @@ func TestRemoteSessionResourceBaseIgnoresDiagnosticLabel(t *testing.T) { func TestEquivalentDocumentLayoutsRenderIdentically(t *testing.T) { dir := t.TempDir() - firstCampaign := writePipelineFixture(t, dir, "first-campaign.yml", "campaign_id: sample\ninputs: {speakers_file: shared/speakers.yml, autocorrect_file: shared/autocorrect.yml, glossary_file: shared/glossary.yml, party_file: shared/party.yml}\n") - secondCampaign := writePipelineFixture(t, dir, "second-campaign.yml", "config:\n imports:\n - path: shared/campaign.yml\ncampaign_id: sample\n") - writePipelineFixture(t, dir, "shared/campaign.yml", "inputs: {speakers_file: speakers.yml, autocorrect_file: autocorrect.yml, glossary_file: glossary.yml, party_file: party.yml}\n") + firstCampaign := writePipelineFixture(t, dir, "first-campaign.yml", "schema_version: maximumdirect.rpg.campaign.v1\nid: sample\nreferences: {party: shared/party.yml}\nnarratio: {inputs: {speakers_file: shared/speakers.yml, glossary_file: shared/glossary.yml}}\n") + secondCampaign := writePipelineFixture(t, dir, "second-campaign.yml", "config:\n imports:\n - path: shared/campaign.yml\nschema_version: maximumdirect.rpg.campaign.v1\nid: sample\n") + writePipelineFixture(t, dir, "shared/campaign.yml", "references: {party: party.yml}\nnarratio: {inputs: {speakers_file: speakers.yml, glossary_file: glossary.yml}}\n") firstSession := writePipelineFixture(t, dir, "first-session.yml", "session_id: sample\ninputs: {audio_dir: shared/audio}\n") secondSession := writePipelineFixture(t, dir, "second-session.yml", "config:\n imports:\n - path: shared/session.yml\nsession_id: sample\n") writePipelineFixture(t, dir, "shared/session.yml", "inputs: {audio_dir: audio}\n") diff --git a/internal/config/glossary_authoring_test.go b/internal/config/glossary_authoring_test.go index 062b26c..9c2803e 100644 --- a/internal/config/glossary_authoring_test.go +++ b/internal/config/glossary_authoring_test.go @@ -12,21 +12,22 @@ func TestGlossarySelectionsInheritIndependently(t *testing.T) { campaignPath := writePipelineFixture(t, dir, "campaign.yml", `config: imports: - path: config/inputs.yml -campaign_id: campaign +schema_version: maximumdirect.rpg.campaign.v1 +id: campaign `) - writePipelineFixture(t, dir, "config/inputs.yml", `inputs: - speakers_file: speakers.yml - autocorrect_file: autocorrect.yml - party_file: party.yml - setting: coast - system: magic - glossary_file: vocabulary.yml - glossary: - entries: [{id: watch, name: Silver Watch, category: organization}] + writePipelineFixture(t, dir, "config/inputs.yml", `setting: coast +system: magic +references: {party: party.yml} +narratio: + inputs: + speakers_file: speakers.yml + glossary_file: vocabulary.yml + glossary: + entries: [{id: watch, name: Silver Watch, category: organization}] `) campaign, err := LoadCampaign(campaignPath) if err != nil { - t.Fatal(err) + t.Fatal(configurationErrorText(err)) } if OptionalString(campaign.Inputs.GlossaryFile) != filepath.Join(dir, "config/vocabulary.yml") { t.Fatal(campaign.Inputs.GlossaryFile) @@ -84,7 +85,7 @@ campaign_id: campaign func TestGlossarySelectionsRejectInvalidTypesAndUnknownIDs(t *testing.T) { dir := t.TempDir() - campaignPath := writePipelineFixture(t, dir, "campaign.yml", "campaign_id: campaign\ninputs: {speakers_file: s, autocorrect_file: a, party_file: p}\n") + campaignPath := writePipelineFixture(t, dir, "campaign.yml", "schema_version: maximumdirect.rpg.campaign.v1\nid: campaign\nreferences: {party: p}\nnarratio: {inputs: {speakers_file: s}}\n") campaign, err := LoadCampaign(campaignPath) if err != nil { t.Fatal(err) diff --git a/internal/config/identity_validation_test.go b/internal/config/identity_validation_test.go index d00c476..12413c2 100644 --- a/internal/config/identity_validation_test.go +++ b/internal/config/identity_validation_test.go @@ -10,7 +10,7 @@ func TestIdentityValidationRejectsUnsafeSegments(t *testing.T) { for _, value := range unsafe { t.Run("campaign/"+strings.ReplaceAll(value, "/", "_"), func(t *testing.T) { cfg := &CampaignConfig{CampaignID: value, Inputs: CampaignInputsConfig{ - SpeakersFile: "speakers.yml", AutocorrectFile: "autocorrect.yml", GlossaryFile: new("glossary.yml"), PartyFile: "party.yml", + SpeakersFile: "speakers.yml", GlossaryFile: new("glossary.yml"), PartyFile: "party.yml", }} if err := validateCampaign(cfg); err == nil { t.Fatalf("validateCampaign(%q) error = nil, want rejection", value) diff --git a/internal/config/load_validate_test.go b/internal/config/load_validate_test.go index 4d81d1e..c03e862 100644 --- a/internal/config/load_validate_test.go +++ b/internal/config/load_validate_test.go @@ -539,16 +539,16 @@ func TestMaintainedExtractionExamplesPreservePublishedContracts(t *testing.T) { t.Fatalf("load full example error = %v", err) } want := map[string]NotariusOutputConfig{ - "item_registry": {LaneID: "item-registry", MediaType: "application/json", SchemaID: "notarius.dnd.item_registry", SchemaVersion: "v1", ModuleKey: "dnd/item-registry"}, - "npc_registry": {LaneID: "npc-registry", MediaType: "application/json", SchemaID: "notarius.dnd.npc_registry", SchemaVersion: "v1", ModuleKey: "dnd/npc-registry"}, - "location_registry": {LaneID: "location-registry", MediaType: "application/json", SchemaID: "notarius.dnd.location_registry", SchemaVersion: "v1", ModuleKey: "dnd/location-registry"}, - "scene_descriptions": {LaneID: "scene-descriptions", MediaType: "application/json", SchemaID: "notarius.dnd.scene_descriptions", SchemaVersion: "v1", ModuleKey: "dnd/scene-descriptions"}, - "item_occurrences": {LaneID: "item-occurrences", MediaType: "application/json", SchemaID: "notarius.dnd.item_occurrences", SchemaVersion: "v1", ModuleKey: "dnd/item-occurrences"}, - "spells": {LaneID: "spells", MediaType: "application/json", SchemaID: "notarius.dnd.spells", SchemaVersion: "v1", ModuleKey: "dnd/spells"}, - "combat_turns": {LaneID: "combat-turns", MediaType: "application/json", SchemaID: "notarius.dnd.combat_turns", SchemaVersion: "v1", ModuleKey: "dnd/combat-turns"}, - "npc_occurrences": {LaneID: "npc-occurrences", MediaType: "application/json", SchemaID: "notarius.dnd.npc_occurrences", SchemaVersion: "v1", ModuleKey: "dnd/npc-occurrences"}, - "location_occurrences": {LaneID: "location-occurrences", MediaType: "application/json", SchemaID: "notarius.dnd.location_occurrences", SchemaVersion: "v1", ModuleKey: "dnd/location-occurrences"}, - "enemy_events": {LaneID: "enemy-events", MediaType: "application/json", SchemaID: "notarius.dnd.enemy_events", SchemaVersion: "v1", ModuleKey: "dnd/enemy-events"}, + "item_registry": {LaneID: "item-registry"}, + "npc_registry": {LaneID: "npc-registry"}, + "location_registry": {LaneID: "location-registry"}, + "scene_descriptions": {LaneID: "scene-descriptions"}, + "item_occurrences": {LaneID: "item-occurrences"}, + "spells": {LaneID: "spells"}, + "combat_turns": {LaneID: "combat-turns"}, + "npc_occurrences": {LaneID: "npc-occurrences"}, + "location_occurrences": {LaneID: "location-occurrences"}, + "enemy_events": {LaneID: "enemy-events"}, } if full.Notarius == nil || !reflect.DeepEqual(full.Notarius.Outputs, want) { t.Fatalf("full example outputs = %#v, want %#v", full.Notarius, want) @@ -596,12 +596,13 @@ func writeConfigFiles(t *testing.T, pipelineYAML, sessionYAML string) (string, s if err := os.WriteFile(pipelinePath, []byte(pipelineYAML), 0o644); err != nil { t.Fatalf("write pipeline.yml: %v", err) } - campaignYAML := `campaign_id: ` + campaignNameFromSessionYAML(sessionYAML) + ` -inputs: - speakers_file: ./speakers.yml - autocorrect_file: ./autocorrect.yml - glossary_file: ./glossary.yml - party_file: ./party.yml + campaignYAML := `schema_version: maximumdirect.rpg.campaign.v1 +id: ` + campaignNameFromSessionYAML(sessionYAML) + ` +references: {party: ./party.yml} +narratio: + inputs: + speakers_file: ./speakers.yml + glossary_file: ./glossary.yml ` if err := os.WriteFile(campaignPath, []byte(campaignYAML), 0o644); err != nil { t.Fatalf("write campaign.yml: %v", err) diff --git a/internal/config/notarius_test.go b/internal/config/notarius_test.go index 2b0ceff..d2b4576 100644 --- a/internal/config/notarius_test.go +++ b/internal/config/notarius_test.go @@ -1,15 +1,12 @@ package config import ( - "encoding/json" "fmt" "os" "path/filepath" "reflect" "strings" "testing" - - "gopkg.in/yaml.v3" ) func TestNotariusOmittedAndDisabledBehavior(t *testing.T) { @@ -48,9 +45,6 @@ notarius: if disabled.Notarius.Binary != DefaultNotariusBinary || disabled.Notarius.Timeout != DefaultNotariusTimeout { t.Fatalf("disabled defaults = %#v", disabled.Notarius) } - if disabled.Notarius.Resume || disabled.Notarius.ChunkCache != "" { - t.Fatalf("disabled cache-control defaults = %#v", disabled.Notarius) - } if disabled.Notarius.ConfigPath != filepath.Join(dir, "relative/notarius.yml") || disabled.Notarius.WorkingDirectory != "" { t.Fatalf("disabled resource paths = %#v", disabled.Notarius) } @@ -154,9 +148,6 @@ notarius: outputs: npc_registry: lane_id: npc-registry - media_type: application/json - schema_id: notarius.dnd.npc_registry - schema_version: v1 ` if err := os.WriteFile(pipelinePath, []byte(pipelineYAML), 0o644); err != nil { t.Fatalf("write pipeline: %v", err) @@ -207,84 +198,27 @@ notarius: } func TestNotariusCacheControlNormalizationAndValidation(t *testing.T) { - for _, mode := range []string{"", "auto", "bypass", "refresh"} { - t.Run("mode "+mode, func(t *testing.T) { + for _, value := range []string{"auto", "bypass", "refresh"} { + t.Run(value, func(t *testing.T) { cfg := validNotariusConfig() - cfg.Resume = true - if mode != "" { - cfg.ChunkCache = " " + mode + " " - } + original := " " + value + " " + cfg.Cache = &original if err := NormalizePipelineConfig(&PipelineConfig{Notarius: cfg}); err != nil { - t.Fatalf("NormalizePipelineConfig() error = %v", err) + t.Fatal(err) } - if cfg.ChunkCache != mode { - t.Fatalf("ChunkCache = %q, want %q", cfg.ChunkCache, mode) - } - if !cfg.Resume { - t.Fatal("Resume = false, want true") + if cfg.Cache == nil || *cfg.Cache != value { + t.Fatalf("cache = %v", cfg.Cache) } if err := validateNotarius(cfg, nil); err != nil { - t.Fatalf("validateNotarius() error = %v", err) + t.Fatal(err) } }) } - - for _, mode := range []string{"AUTO", "invalid"} { - t.Run("invalid "+mode, func(t *testing.T) { - cfg := validNotariusConfig() - cfg.ChunkCache = mode - err := validateNotarius(cfg, nil) - if err == nil || !strings.Contains(configurationErrorText(err), "pipeline.notarius.chunk_cache") { - t.Fatalf("validateNotarius() error = %v, want chunk_cache error", err) - } - }) - } - - disabled := &NotariusConfig{Enabled: false, Resume: true, ChunkCache: " INVALID "} - if err := NormalizePipelineConfig(&PipelineConfig{Notarius: disabled}); err != nil { - t.Fatalf("NormalizePipelineConfig(disabled) error = %v", err) - } - if disabled.ChunkCache != " INVALID " { - t.Fatalf("disabled ChunkCache = %q, want unchanged", disabled.ChunkCache) - } - if err := validateNotarius(disabled, nil); err != nil { - t.Fatalf("validateNotarius(disabled) error = %v", err) - } -} - -func TestNotariusCacheControlsSafeSerialization(t *testing.T) { - cfg := validNotariusConfig() - cfg.Resume = true - cfg.ChunkCache = "refresh" - - yamlData, err := yaml.Marshal(cfg) - if err != nil { - t.Fatal(err) - } - jsonData, err := json.Marshal(cfg) - if err != nil { - t.Fatal(err) - } - if !strings.Contains(string(yamlData), "resume: true") || !strings.Contains(string(yamlData), "chunk_cache: refresh") { - t.Fatalf("YAML omitted cache controls: %s", yamlData) - } - if !strings.Contains(string(jsonData), `"resume":true`) || !strings.Contains(string(jsonData), `"chunk_cache":"refresh"`) { - t.Fatalf("JSON omitted cache controls: %s", jsonData) - } - - cfg.Resume = false - cfg.ChunkCache = "" - yamlData, err = yaml.Marshal(cfg) - if err != nil { - t.Fatal(err) - } - jsonData, err = json.Marshal(cfg) - if err != nil { - t.Fatal(err) - } - for _, serialized := range []string{string(yamlData), string(jsonData)} { - if strings.Contains(serialized, "resume") || strings.Contains(serialized, "chunk_cache") { - t.Fatalf("zero-value cache controls were serialized: %s", serialized) + for _, value := range []string{"", "AUTO", "invalid"} { + cfg := validNotariusConfig() + cfg.Cache = &value + if err := validateNotarius(cfg, nil); err == nil { + t.Fatalf("accepted cache %q", value) } } } @@ -298,9 +232,6 @@ notarius: outputs: npc_registry: lane_id: npc-registry - media_type: application/json - schema_id: notarius.dnd.npc_registry - schema_version: v1 ` paths := make([]string, 2) configs := make([]*PipelineConfig, 2) @@ -360,7 +291,7 @@ func TestNotariusReferenceValidationAndNormalization(t *testing.T) { " party ": " narratio.input.party ", " chunk . players ": "narratio.input.players", " npc-registry . extract . glossary ": "narratio.input.glossary.campaign", - "spells": "narratio.input.spell_catalog", + "spells": "narratio.input.glossary.combined", } if err := NormalizePipelineConfig(&PipelineConfig{Notarius: cfg}); err != nil { @@ -373,7 +304,7 @@ func TestNotariusReferenceValidationAndNormalization(t *testing.T) { "party": "narratio.input.party", "chunk.players": "narratio.input.players", "npc-registry.extract.glossary": "narratio.input.glossary.campaign", - "spells": "narratio.input.spell_catalog", + "spells": "narratio.input.glossary.combined", } if len(cfg.References) != len(want) { t.Fatalf("normalized references = %#v, want %#v", cfg.References, want) @@ -500,12 +431,10 @@ func TestNotariusNormalizationProducesCanonicalValues(t *testing.T) { } cfg.Outputs = map[string]NotariusOutputConfig{ " npc_registry ": { - LaneID: " npc-registry ", MediaType: " application/json ", - SchemaID: " notarius.dnd.npc_registry ", SchemaVersion: " v1 ", + LaneID: " npc-registry ", }, "spells": { - LaneID: " spells ", MediaType: " application/json ", - SchemaID: " notarius.dnd.spells ", SchemaVersion: " v1 ", + LaneID: " spells ", }, } @@ -525,7 +454,7 @@ func TestNotariusNormalizationProducesCanonicalValues(t *testing.T) { if _, ok := cfg.Outputs[" npc_registry "]; ok { t.Fatal("outputs retain unnormalized key") } - if got := cfg.Outputs["npc_registry"]; got.LaneID != "npc-registry" || got.MediaType != "application/json" || got.SchemaID != "notarius.dnd.npc_registry" || got.SchemaVersion != "v1" { + if got := cfg.Outputs["npc_registry"]; got.LaneID != "npc-registry" { t.Fatalf("normalized npc_registry output = %#v", got) } beforeSecondPass := cloneNotariusConfigForTest(cfg) @@ -570,10 +499,10 @@ func TestNotariusDiagnosticsUseSortedMapKeys(t *testing.T) { cfg.References = nil cfg.Outputs = make(map[string]NotariusOutputConfig, len(keys)) for _, key := range keys { - cfg.Outputs[key] = NotariusOutputConfig{LaneID: key} + cfg.Outputs[key] = NotariusOutputConfig{} } }, - wantField: "pipeline.notarius.outputs.alpha.media_type", + wantField: "pipeline.notarius.outputs.alpha.lane_id", }, } @@ -614,25 +543,6 @@ func cloneNotariusConfigForTest(cfg *NotariusConfig) *NotariusConfig { return &clone } -func TestNotariusSpellCatalogReferenceRequiresEffectiveInput(t *testing.T) { - cfg := loadedValidConfig(t) - cfg.Pipeline.Notarius = validNotariusConfig() - cfg.Pipeline.Notarius.References = map[string]string{ - "zeta": "narratio.input.spell_catalog", - "alpha": "narratio.input.spell_catalog", - } - - err := Validate(cfg) - if err == nil || !strings.Contains(configurationErrorText(err), "pipeline.notarius.references.alpha") || !strings.Contains(configurationErrorText(err), "requires campaign.inputs.spell_catalog_file or session.inputs.spell_catalog_file") { - t.Fatalf("Validate() error = %v, want sorted selector and missing spell catalog input", err) - } - - cfg.StableInputs.SpellCatalogFile = ResolvedInputFile{Path: "./spells.json", Source: "campaign_config"} - if err := Validate(cfg); err != nil { - t.Fatalf("Validate() with spell catalog error = %v", err) - } -} - func validNotariusConfig() *NotariusConfig { return &NotariusConfig{ Enabled: true, @@ -643,10 +553,7 @@ func validNotariusConfig() *NotariusConfig { WorkingDirectory: ".", Outputs: map[string]NotariusOutputConfig{ "npc_registry": { - LaneID: "npc-registry", - MediaType: "application/json", - SchemaID: "notarius.dnd.npc_registry", - SchemaVersion: "v1", + LaneID: "npc-registry", }, }, } @@ -659,88 +566,28 @@ func TestNotariusEnabledValidation(t *testing.T) { pipeline_id: dnd-session timeout: 45m outputs: - npc_registry: - lane_id: npc-registry - media_type: application/json - schema_id: notarius.dnd.npc_registry - schema_version: v1 - module_key: dnd/npc-registry + npc_registry: {lane_id: npc-registry} ` - tests := []struct { - name string - section string - wantErr []string - }{ - {name: "valid", section: valid}, - {name: "blank binary", section: strings.Replace(valid, " enabled: true\n", " enabled: true\n binary: \" \"\n", 1), wantErr: []string{"pipeline.notarius.binary", "required"}}, - {name: "missing config path", section: strings.Replace(valid, " config_path: ./notarius.yml\n", "", 1), wantErr: []string{"pipeline.notarius.config_path", "required"}}, - {name: "missing pipeline id", section: strings.Replace(valid, " pipeline_id: dnd-session\n", "", 1), wantErr: []string{"pipeline.notarius.pipeline_id", "required"}}, - {name: "missing outputs", section: strings.Split(valid, " outputs:\n")[0], wantErr: []string{"pipeline.notarius.outputs", "at least one"}}, - {name: "zero timeout", section: strings.Replace(valid, " timeout: 45m", " timeout: 0s", 1), wantErr: []string{"pipeline.notarius.timeout", "positive"}}, - {name: "negative timeout", section: strings.Replace(valid, " timeout: 45m", " timeout: -1s", 1), wantErr: []string{"pipeline.notarius.timeout", "positive"}}, - {name: "invalid timeout", section: strings.Replace(valid, " timeout: 45m", " timeout: later", 1), wantErr: []string{"pipeline.notarius.timeout", "valid duration"}}, - {name: "invalid output key", section: strings.Replace(valid, " npc_registry:", " npc-registry:", 1), wantErr: []string{"pipeline.notarius.outputs keys", "must match"}}, - {name: "missing lane", section: strings.Replace(valid, " lane_id: npc-registry\n", "", 1), wantErr: []string{"pipeline.notarius.outputs.npc_registry.lane_id", "required"}}, - {name: "missing media type", section: strings.Replace(valid, " media_type: application/json\n", "", 1), wantErr: []string{"pipeline.notarius.outputs.npc_registry.media_type", "required"}}, - {name: "missing schema id", section: strings.Replace(valid, " schema_id: notarius.dnd.npc_registry\n", "", 1), wantErr: []string{"pipeline.notarius.outputs.npc_registry.schema_id", "required"}}, - {name: "missing schema version", section: strings.Replace(valid, " schema_version: v1\n", "", 1), wantErr: []string{"pipeline.notarius.outputs.npc_registry.schema_version", "required"}}, - { - name: "normalized key collision", - section: strings.Replace(valid, " module_key: dnd/npc-registry\n", ` module_key: dnd/npc-registry - " npc_registry ": - lane_id: npc-registry-two - media_type: application/json - schema_id: two - schema_version: v1 -`, 1), - wantErr: []string{"pipeline.notarius.outputs keys", "duplicate source"}, - }, - { - name: "duplicate normalized lane", - section: strings.Replace(valid, " module_key: dnd/npc-registry\n", ` module_key: dnd/npc-registry - spells: - lane_id: " npc-registry " - media_type: application/json - schema_id: two - schema_version: v1 -`, 1), - wantErr: []string{"pipeline.notarius.outputs.spells.lane_id", "duplicates"}, - }, - } - - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - pipelinePath, sessionPath := writeConfigFiles(t, testPipelineBaseYAML+"\n"+tt.section, testSessionBaseYAML) - cfg, err := Load(pipelinePath, sessionPath) - if err != nil { - if len(tt.wantErr) > 0 { - for _, fragment := range tt.wantErr { - if !strings.Contains(configurationErrorText(err), fragment) { - t.Fatalf("Load() error = %v, want containing %q", err, fragment) - } - } - return - } - t.Fatalf("Load() error = %v", err) - } - err = Validate(cfg) - if len(tt.wantErr) == 0 { - if err != nil { - t.Fatalf("Validate() error = %v", err) - } - output := cfg.Pipeline.Notarius.Outputs["npc_registry"] - if output.LaneID != "npc-registry" || output.ModuleKey != "dnd/npc-registry" { - t.Fatalf("normalized output = %#v", output) - } - return - } + for _, test := range []struct{ name, section, want string }{ + {"valid", valid, ""}, + {"blank binary", strings.Replace(valid, " enabled: true\n", " enabled: true\n binary: ' ' \n", 1), "binary"}, + {"missing config", strings.Replace(valid, " config_path: ./notarius.yml\n", "", 1), "config_path"}, + {"missing pipeline", strings.Replace(valid, " pipeline_id: dnd-session\n", "", 1), "pipeline_id"}, + {"missing outputs", strings.Split(valid, " outputs:\n")[0], "outputs"}, + {"bad timeout", strings.Replace(valid, " timeout: 45m", " timeout: 0s", 1), "timeout"}, + {"invalid lane", strings.Replace(valid, "lane_id: npc-registry", "lane_id: ''", 1), "lane_id"}, + } { + t.Run(test.name, func(t *testing.T) { + pipeline, session := writeConfigFiles(t, testPipelineBaseYAML+"\n"+test.section, testSessionBaseYAML) + cfg, err := Load(pipeline, session) if err == nil { - t.Fatalf("Validate() error = nil, want containing %q", tt.wantErr) + err = Validate(cfg) } - for _, fragment := range tt.wantErr { - if !strings.Contains(configurationErrorText(err), fragment) { - t.Fatalf("Validate() error = %v, want containing %q", err, fragment) - } + if test.want == "" && err != nil { + t.Fatal(err) + } + if test.want != "" && (err == nil || !strings.Contains(configurationErrorText(err), test.want)) { + t.Fatalf("error=%v want %q", err, test.want) } }) } diff --git a/internal/config/party_resolution_test.go b/internal/config/party_resolution_test.go index 0548827..8fcdce4 100644 --- a/internal/config/party_resolution_test.go +++ b/internal/config/party_resolution_test.go @@ -24,12 +24,13 @@ characters: if err := os.WriteFile(partyPath, partyYAML, 0o644); err != nil { t.Fatalf("write party: %v", err) } - pipelinePath, campaignPath, sessionPath := writePartyResolutionConfig(t, dir, `campaign_id: campaign -inputs: - speakers_file: speakers.yml - autocorrect_file: autocorrect.yml - glossary_file: glossary.yml - party_file: roster/party.yml + pipelinePath, campaignPath, sessionPath := writePartyResolutionConfig(t, dir, `schema_version: maximumdirect.rpg.campaign.v1 +id: campaign +references: {party: roster/party.yml} +narratio: + inputs: + speakers_file: speakers.yml + glossary_file: glossary.yml `, `session_id: session campaign: campaign inputs: @@ -68,7 +69,7 @@ func TestCanonicalPartyRejectsSeparatePlayersAndSessionPartyOverrides(t *testing sessionExtra string want string }{ - {name: "campaign players", campaignExtra: " players_file: players.yml\n", want: "/inputs/players_file"}, + {name: "campaign players", campaignExtra: " players_file: players.yml\n", want: "/narratio/inputs/players_file"}, {name: "session players", sessionExtra: " players_file: players.yml\n", want: "/inputs/players_file"}, {name: "session party", sessionExtra: " party_file: party-override.yml\n", want: "/inputs/party_file"}, } @@ -76,7 +77,7 @@ func TestCanonicalPartyRejectsSeparatePlayersAndSessionPartyOverrides(t *testing t.Run(test.name, func(t *testing.T) { dir := t.TempDir() writePartyResolutionFile(t, filepath.Join(dir, "party.yml"), canonicalPartyFixture) - pipelinePath, campaignPath, sessionPath := writePartyResolutionConfig(t, dir, "campaign_id: campaign\ninputs:\n speakers_file: speakers.yml\n autocorrect_file: autocorrect.yml\n glossary_file: glossary.yml\n party_file: party.yml\n"+test.campaignExtra, "session_id: session\ncampaign: campaign\ninputs:\n audio_dir: audio\n"+test.sessionExtra) + pipelinePath, campaignPath, sessionPath := writePartyResolutionConfig(t, dir, "schema_version: maximumdirect.rpg.campaign.v1\nid: campaign\nreferences: {party: party.yml}\nnarratio:\n inputs:\n speakers_file: speakers.yml\n glossary_file: glossary.yml\n"+test.campaignExtra, "session_id: session\ncampaign: campaign\ninputs:\n audio_dir: audio\n"+test.sessionExtra) _, err := LoadWithSessionOptions(pipelinePath, campaignPath, sessionPath, SessionLoadOptions{}) if err == nil || !strings.Contains(configurationErrorText(err), test.want) { t.Fatalf("LoadWithSessionOptions() error = %v, want %q", err, test.want) @@ -88,12 +89,13 @@ func TestCanonicalPartyRejectsSeparatePlayersAndSessionPartyOverrides(t *testing func TestUnversionedPartyIsRejectedBeforeResolution(t *testing.T) { dir := t.TempDir() writePartyResolutionFile(t, filepath.Join(dir, "party.yml"), "legacy: campaign\n") - pipelinePath, campaignPath, sessionPath := writePartyResolutionConfig(t, dir, `campaign_id: campaign -inputs: - speakers_file: speakers.yml - autocorrect_file: autocorrect.yml - glossary_file: glossary.yml - party_file: party.yml + pipelinePath, campaignPath, sessionPath := writePartyResolutionConfig(t, dir, `schema_version: maximumdirect.rpg.campaign.v1 +id: campaign +references: {party: party.yml} +narratio: + inputs: + speakers_file: speakers.yml + glossary_file: glossary.yml `, `session_id: session campaign: campaign inputs: @@ -108,7 +110,7 @@ inputs: func TestResolveAndLoadedCampaignShareCanonicalPartyResolution(t *testing.T) { dir := t.TempDir() writePartyResolutionFile(t, filepath.Join(dir, "party.yml"), canonicalPartyFixture) - pipelinePath, campaignPath, sessionPath := writePartyResolutionConfig(t, dir, "campaign_id: campaign\ninputs:\n speakers_file: speakers.yml\n autocorrect_file: autocorrect.yml\n glossary_file: glossary.yml\n party_file: party.yml\n", "session_id: session\ncampaign: campaign\ninputs:\n audio_dir: audio\n") + pipelinePath, campaignPath, sessionPath := writePartyResolutionConfig(t, dir, "schema_version: maximumdirect.rpg.campaign.v1\nid: campaign\nreferences: {party: party.yml}\nnarratio:\n inputs:\n speakers_file: speakers.yml\n glossary_file: glossary.yml\n", "session_id: session\ncampaign: campaign\ninputs:\n audio_dir: audio\n") pipeline, err := LoadPipeline(pipelinePath) if err != nil { t.Fatalf("LoadPipeline() error = %v", err) diff --git a/internal/config/pipeline_configkit_test.go b/internal/config/pipeline_configkit_test.go index ea09f40..ae3fe13 100644 --- a/internal/config/pipeline_configkit_test.go +++ b/internal/config/pipeline_configkit_test.go @@ -360,9 +360,6 @@ notarius: outputs: npc_registry: lane_id: npc-registry - media_type: application/json - schema_id: notarius.dnd.npc_registry - schema_version: v1 `) cfg, err := LoadPipeline(pipelinePath) @@ -568,41 +565,31 @@ func TestNotariusCredentialRootProvenance(t *testing.T) { } func TestNotariusCacheControlProfileReplacementAndNullReset(t *testing.T) { - tests := []struct { - name string - overlay string - wantResume bool - wantMode string - wantSource bool - wantNil bool + for _, test := range []struct { + name, overlay string + reset bool }{ - {name: "replacement", overlay: "notarius:\n resume: true\n chunk_cache: refresh\n", wantResume: true, wantMode: "refresh", wantSource: true}, - {name: "null reset", overlay: "notarius: null\n", wantNil: true}, - } - for _, test := range tests { + {"replacement", "notarius:\n cache: refresh\n", false}, {"null reset", "notarius: null\n", true}, + } { t.Run(test.name, func(t *testing.T) { dir := t.TempDir() - root := writePipelineFixture(t, dir, "pipeline.yml", "whisperx:\n transcribe_url: https://transcription.example.test/transcribe\nnotarius:\n enabled: false\n resume: false\n chunk_cache: bypass\n") + root := writePipelineFixture(t, dir, "pipeline.yml", "whisperx:\n transcribe_url: https://transcription.example.test/transcribe\nnotarius:\n enabled: false\n cache: bypass\n") overlay := writePipelineFixture(t, dir, "overlays/testing.yml", test.overlay) profile := "testing" cfg, err := LoadPipelineWithOptions(root, PipelineLoadOptions{Overlay: &profile}) if err != nil { t.Fatal(err) } - if test.wantNil { + if test.reset { if cfg.Notarius != nil { - t.Fatalf("Notarius = %#v, want null reset", cfg.Notarius) + t.Fatalf("Notarius = %#v", cfg.Notarius) } return } - if cfg.Notarius == nil || cfg.Notarius.Resume != test.wantResume || cfg.Notarius.ChunkCache != test.wantMode { - t.Fatalf("cache controls = resume %v, mode %q; want resume %v, mode %q", cfg.Notarius.Resume, cfg.Notarius.ChunkCache, test.wantResume, test.wantMode) + if cfg.Notarius == nil || cfg.Notarius.Cache == nil || *cfg.Notarius.Cache != "refresh" { + t.Fatalf("Notarius = %#v", cfg.Notarius) } - if !test.wantSource { - return - } - assertNativePipelineSource(t, cfg, configkit.Keys("notarius", "resume"), overlay) - assertNativePipelineSource(t, cfg, configkit.Keys("notarius", "chunk_cache"), overlay) + assertNativePipelineSource(t, cfg, configkit.Keys("notarius", "cache"), overlay) }) } } diff --git a/internal/config/resource_base_test.go b/internal/config/resource_base_test.go index 4c316e7..590dc69 100644 --- a/internal/config/resource_base_test.go +++ b/internal/config/resource_base_test.go @@ -23,7 +23,7 @@ notarius: enabled: true pipeline_id: dnd-session outputs: - recap: {lane_id: recap, media_type: application/json, schema_id: recap, schema_version: "1"} + recap: {lane_id: recap} `) writePipelineFixture(t, dir, "overlays/testing.yml", "audita:\n config_path: custom.yml\n") base, err := LoadPipeline(root) diff --git a/internal/config/scriptorium_test.go b/internal/config/scriptorium_test.go index 60c3ad8..760bdf8 100644 --- a/internal/config/scriptorium_test.go +++ b/internal/config/scriptorium_test.go @@ -84,7 +84,7 @@ func TestScriptoriumLoadAndValidate(t *testing.T) { enabled: true prompt_id: dnd.session_recap `, - wantValidateErr: []string{"pipeline.scriptorium.artifacts.session_recap.output_path", "required"}, + wantValidateErr: []string{"pipeline.scriptorium.artifacts.session_recap", "required"}, }, { name: "invalid timeout fails", @@ -392,7 +392,7 @@ func TestScriptoriumLoadAndValidate(t *testing.T) { prompt_id: dnd.session_recap output_path: transcripts/session_recap.md `, - wantValidateErr: []string{"pipeline.scriptorium.artifacts.session_recap.output_path", "under artifacts/"}, + wantValidateErr: []string{"pipeline.scriptorium.artifacts.session_recap", "under artifacts/"}, }, { name: "artifact source infers dependency", @@ -536,7 +536,7 @@ func TestScriptoriumLoadAndValidate(t *testing.T) { source: narratio.artifact.session_recap required: true `, - wantValidateErr: []string{"pipeline.scriptorium.artifacts.session_recap.output_path", "referenced"}, + wantValidateErr: []string{"pipeline.scriptorium.artifacts.session_recap", "referenced"}, }, } @@ -641,6 +641,5 @@ campaign: test-campaign inputs: audio_dir: ./audio speakers_file: ./speakers.yml - autocorrect_file: ./autocorrect.yml glossary_file: ./glossary.yml ` diff --git a/internal/config/session_defaults_test.go b/internal/config/session_defaults_test.go index 6ebad9d..946ef89 100644 --- a/internal/config/session_defaults_test.go +++ b/internal/config/session_defaults_test.go @@ -15,17 +15,15 @@ import ( func TestSessionDefaultsCompleteBeforeNativeHandoff(t *testing.T) { dir := t.TempDir() pipeline := writePipelineFixture(t, dir, "pipeline.yml", testTranscriptionConfig+"workspace: {root: work}\n") - campaign := writePipelineFixture(t, dir, "campaign.yml", "config:\n imports:\n - path: campaign/resources.yml\ncampaign_id: campaign\n") - fragment := writePipelineFixture(t, dir, "campaign/resources.yml", `inputs: - speakers_file: speakers.yml - autocorrect_file: autocorrect.yml - glossary_file: glossary.yml - party_file: party.yml - spell_catalog_file: spells.yml + campaign := writePipelineFixture(t, dir, "campaign.yml", "config:\n imports:\n - path: campaign/resources.yml\nschema_version: maximumdirect.rpg.campaign.v1\nid: campaign\nreferences: {party: campaign/party.yml}\n") + fragment := writePipelineFixture(t, dir, "campaign/resources.yml", `narratio: + inputs: + speakers_file: speakers.yml + glossary_file: glossary.yml `) writePipelineFixture(t, dir, "campaign/party.yml", canonicalPartyFixture) session := writePipelineFixture(t, dir, "session.yml", "config:\n imports:\n - path: session/resources.yml\nsession_id: session\n") - sessionFragment := writePipelineFixture(t, dir, "session/resources.yml", "inputs:\n audio_dir: audio\n speakers_file: override.yml\n spell_catalog_file: ''\n") + sessionFragment := writePipelineFixture(t, dir, "session/resources.yml", "inputs:\n audio_dir: audio\n speakers_file: override.yml\n") cfg, err := LoadWithSessionOptions(pipeline, campaign, session, SessionLoadOptions{SessionID: "session"}) if err != nil { t.Fatal(err) @@ -37,10 +35,10 @@ func TestSessionDefaultsCompleteBeforeNativeHandoff(t *testing.T) { if len(result.Sources()) != 2 { t.Fatalf("session sources include unrelated campaign inputs: %+v", result.Sources()) } - if cfg.Session.Campaign != "campaign" || OptionalString(cfg.Session.Inputs.GlossaryFile) != filepath.Join(dir, "campaign/glossary.yml") || cfg.Session.Inputs.SpellCatalogFile != "" { + if cfg.Session.Campaign != "campaign" || OptionalString(cfg.Session.Inputs.GlossaryFile) != filepath.Join(dir, "campaign/glossary.yml") { t.Fatalf("session defaults/explicit clearing: %+v", cfg.Session) } - if cfg.StableInputs.GlossaryFile.Source != "campaign_config" || cfg.StableInputs.GlossaryFile.ConfigPath != fragment || cfg.StableInputs.SpeakersFile.ConfigPath != sessionFragment || cfg.StableInputs.SpellCatalogFile.Source != "session_config" { + if cfg.StableInputs.GlossaryFile.Source != "campaign_config" || cfg.StableInputs.GlossaryFile.ConfigPath != fragment || cfg.StableInputs.SpeakersFile.ConfigPath != sessionFragment { t.Fatalf("stable input references: %+v", cfg.StableInputs) } explanation, ok := result.Explain(configkit.Keys("inputs", "glossary_file")) @@ -89,12 +87,10 @@ func TestSessionDefaultsCompleteBeforeNativeHandoff(t *testing.T) { if !reflect.DeepEqual(reloaded.Inputs, cfg.Session.Inputs) { t.Fatalf("standalone rendering lost effective values or explicit clearing: %s", materialized) } - writePipelineFixture(t, dir, "campaign/resources.yml", `inputs: - speakers_file: replacement-speakers.yml - autocorrect_file: replacement-autocorrect.yml - glossary_file: replacement-glossary.yml - party_file: party.yml - spell_catalog_file: replacement-spells.yml + writePipelineFixture(t, dir, "campaign/resources.yml", `narratio: + inputs: + speakers_file: replacement-speakers.yml + glossary_file: replacement-glossary.yml `) receiving, err := LoadCampaign(campaign) if err != nil { @@ -104,37 +100,17 @@ func TestSessionDefaultsCompleteBeforeNativeHandoff(t *testing.T) { if err != nil { t.Fatal(err) } - if OptionalString(reloaded.Inputs.GlossaryFile) != OptionalString(receiving.Inputs.GlossaryFile) || reloaded.Inputs.AutocorrectFile != receiving.Inputs.AutocorrectFile { - t.Fatalf("materialization froze inherited inputs: %+v", reloaded.Inputs) + if OptionalString(reloaded.Inputs.GlossaryFile) != OptionalString(cfg.Session.Inputs.GlossaryFile) { + t.Fatalf("materialization lost resolved glossary: %+v", reloaded.Inputs) } - if reloaded.Inputs.SpeakersFile != cfg.Session.Inputs.SpeakersFile || reloaded.Inputs.SpellCatalogFile != "" { + if reloaded.Inputs.SpeakersFile != cfg.Session.Inputs.SpeakersFile { t.Fatalf("materialization lost explicit override or clearing: %+v", reloaded.Inputs) } } -func TestMaterializedSessionOmitsInheritedSpellCatalog(t *testing.T) { - dir := t.TempDir() - campaignPath := writePipelineFixture(t, dir, "campaign.yml", "campaign_id: campaign\ninputs: {speakers_file: speakers.yml, autocorrect_file: autocorrect.yml, glossary_file: glossary.yml, party_file: party.yml, spell_catalog_file: spells.yml}\n") - campaign, err := LoadCampaign(campaignPath) - if err != nil { - t.Fatal(err) - } - session, err := LoadSessionBytesWithOptions("session.yml", []byte("session_id: session\ninputs: {audio_dir: audio}\n"), SessionLoadOptions{Campaign: campaign, CampaignPath: campaignPath}) - if err != nil { - t.Fatal(err) - } - data, err := RenderSessionDocument(&Config{Session: session}, "session") - if err != nil { - t.Fatal(err) - } - if strings.Contains(string(data), "spell_catalog_file") || strings.Contains(string(data), "speakers_file") { - t.Fatalf("materialized inherited fields: %s", data) - } -} - func TestSessionDefaultsRespectExplicitEmptyInputsAndIdentity(t *testing.T) { dir := t.TempDir() - campaignPath := writePipelineFixture(t, dir, "campaign.yml", "campaign_id: campaign\ninputs: {speakers_file: speakers.yml, autocorrect_file: autocorrect.yml, glossary_file: glossary.yml, party_file: party.yml}\n") + campaignPath := writePipelineFixture(t, dir, "campaign.yml", "schema_version: maximumdirect.rpg.campaign.v1\nid: campaign\nreferences: {party: party.yml}\nnarratio: {inputs: {speakers_file: speakers.yml, glossary_file: glossary.yml}}\n") campaign, err := LoadCampaign(campaignPath) if err != nil { t.Fatal(err) diff --git a/internal/config/session_template_test.go b/internal/config/session_template_test.go index c176663..67ad280 100644 --- a/internal/config/session_template_test.go +++ b/internal/config/session_template_test.go @@ -15,7 +15,6 @@ campaign: sample-campaign inputs: audio_dir: ./audio speakers_file: ./speakers.yml - autocorrect_file: ./autocorrect.yml glossary_file: ./glossary.yml ` if err := os.WriteFile(sessionPath, []byte(sessionYAML), 0o644); err != nil { @@ -38,7 +37,6 @@ campaign: sample-campaign inputs: audio_dir: ./audio speakers_file: ./speakers.yml - autocorrect_file: ./autocorrect.yml glossary_file: ./glossary.yml ` if err := os.WriteFile(sessionPath, []byte(sessionYAML), 0o644); err != nil { @@ -63,7 +61,6 @@ campaign: sample-campaign inputs: audio_dir: ./audio speakers_file: ./speakers.yml - autocorrect_file: ./autocorrect.yml glossary_file: ./glossary.yml ` if err := os.WriteFile(sessionPath, []byte(sessionYAML), 0o644); err != nil { @@ -91,7 +88,6 @@ campaign: sample-campaign inputs: audio_dir: ./audio speakers_file: ./speakers.yml - autocorrect_file: ./autocorrect.yml glossary_file: ./glossary.yml ` if err := os.WriteFile(sessionPath, []byte(sessionYAML), 0o644); err != nil { @@ -136,7 +132,6 @@ unknown_field: true inputs: audio_dir: ./audio speakers_file: ./speakers.yml - autocorrect_file: ./autocorrect.yml glossary_file: ./glossary.yml ` if err := os.WriteFile(sessionPath, []byte(sessionYAML), 0o644); err != nil { @@ -160,7 +155,6 @@ campaign: sample-campaign inputs: audio_dir: ./audio speakers_file: ./speakers.yml - autocorrect_file: ./autocorrect.yml glossary_file: ./glossary.yml ` if err := os.WriteFile(sessionPath, []byte(sessionYAML), 0o644); err != nil { @@ -251,6 +245,5 @@ const standaloneSessionFields = `campaign: sample-campaign inputs: audio_dir: audio speakers_file: speakers.yml - autocorrect_file: autocorrect.yml glossary_file: glossary.yml ` diff --git a/internal/config/storage_publish_test.go b/internal/config/storage_publish_test.go index 4877b7b..c270eba 100644 --- a/internal/config/storage_publish_test.go +++ b/internal/config/storage_publish_test.go @@ -636,7 +636,6 @@ inputs: audio_s3: prefix: audio/ speakers_file: ./speakers.yml - autocorrect_file: ./autocorrect.yml glossary_file: ./glossary.yml `, }, @@ -648,7 +647,6 @@ inputs: audio_s3: prefix: /audio/ speakers_file: ./speakers.yml - autocorrect_file: ./autocorrect.yml glossary_file: ./glossary.yml `, wantErr: "session.inputs.audio_s3.prefix must be a relative path", @@ -661,7 +659,6 @@ inputs: audio_s3: prefix: ../audio/ speakers_file: ./speakers.yml - autocorrect_file: ./autocorrect.yml glossary_file: ./glossary.yml `, wantErr: "session.inputs.audio_s3.prefix must not contain path traversal", @@ -675,7 +672,6 @@ inputs: audio_s3: prefix: audio/ speakers_file: ./speakers.yml - autocorrect_file: ./autocorrect.yml glossary_file: ./glossary.yml `, wantErr: "mutually exclusive", @@ -721,7 +717,6 @@ inputs: audio_s3: prefix: audio/ speakers_file: ./speakers.yml - autocorrect_file: ./autocorrect.yml glossary_file: ./glossary.yml ` pipelinePath, sessionPath := writeConfigFiles(t, pipelineYAML, sessionYAML) diff --git a/internal/config/validation_duration_test.go b/internal/config/validation_duration_test.go index 421be91..db0a7b7 100644 --- a/internal/config/validation_duration_test.go +++ b/internal/config/validation_duration_test.go @@ -79,10 +79,7 @@ func TestValidateNotariusTimeoutRequiresPositiveValue(t *testing.T) { WorkingDirectory: "/tmp", Outputs: map[string]NotariusOutputConfig{ "npc_registry": { - LaneID: "npc-registry", - MediaType: "application/json", - SchemaID: "notarius.dnd.npc_registry", - SchemaVersion: "v1", + LaneID: "npc-registry", }, }, } diff --git a/internal/stage/extract.go b/internal/stage/extract.go index 02cce4a..8e854a9 100644 --- a/internal/stage/extract.go +++ b/internal/stage/extract.go @@ -109,9 +109,9 @@ func (extractStage) Run(ctx context.Context, env *Env, m *manifest.Manifest) (re if workspaceRoot == "" { workspaceRoot = env.Config.Pipeline.Workspace.Root } - receiptPath, err := absolutePath(artifacts.SessionRunNotariusReceiptPathForCampaign(workspaceRoot, campaign, sessionID, runID)) + reportPath, err := absolutePath(artifacts.SessionRunNotariusReportPathForCampaign(workspaceRoot, campaign, sessionID, runID)) if err != nil { - return nil, fmt.Errorf("extract: resolve receipt path: %w", err) + return nil, fmt.Errorf("extract: resolve completion report path: %w", err) } logPath, err := absolutePath(artifacts.SessionRunNotariusLogPathForCampaign(workspaceRoot, campaign, sessionID, runID)) if err != nil { @@ -121,7 +121,7 @@ func (extractStage) Run(ctx context.Context, env *Env, m *manifest.Manifest) (re if err != nil { return nil, fmt.Errorf("extract: resolve output root: %w", err) } - directories := []string{filepath.Dir(receiptPath), outputRoot} + directories := []string{filepath.Dir(reportPath), outputRoot} for _, directory := range directories { if err := fileops.EnsureWorkspaceDirectory(directory); err != nil { return nil, fmt.Errorf("extract: create directory %q: %w", directory, err) @@ -148,7 +148,7 @@ func (extractStage) Run(ctx context.Context, env *Env, m *manifest.Manifest) (re Binary: resolvedBinary, Credentials: notariusConfig.Credentials, ConfigOverlay: notariusConfig.ConfigOverlay, ConfigPath: configPath, PipelineID: notariusConfig.PipelineID, InputPath: inputPath, OutputRoot: outputRoot, WorkingDirectory: workingDirectory, - ReceiptPath: receiptPath, LogPath: logPath, Timeout: timeout, Cache: cache, + ReportPath: reportPath, LogPath: logPath, Timeout: timeout, Cache: cache, Debug: notariusConfig.Debug, DebugDirectory: debugDirectory, References: referenceBindings, } accepted := false @@ -247,7 +247,7 @@ func (extractStage) Run(ctx context.Context, env *Env, m *manifest.Manifest) (re "reference_count": len(references.Identities), "references": extractReferenceMetadata(references.Identities), "completion": completion, } - result = &StageResult{Outputs: outputs, Logs: []string{receiptPath, logPath}, Metadata: metadata} + result = &StageResult{Outputs: outputs, Logs: []string{reportPath, logPath}, Metadata: metadata} accepted = true return result, nil } diff --git a/internal/stage/extract_native_test.go b/internal/stage/extract_native_test.go index 097859a..21f6f54 100644 --- a/internal/stage/extract_native_test.go +++ b/internal/stage/extract_native_test.go @@ -31,6 +31,9 @@ func nativeExtractFixture(t *testing.T) (*Env, *manifest.Manifest, *notarius.Fak if err := os.WriteFile(filepath.Join(bundle, "lanes", "npc-registry.json"), []byte(`{"npcs":[]}`), 0o644); err != nil { t.Fatal(err) } + if err := os.WriteFile(filepath.Join(bundle, "chunk-map.json"), []byte(`{"chunks":[]}`), 0o644); err != nil { + t.Fatal(err) + } return env, m, fake } diff --git a/internal/stage/extract_preflight.go b/internal/stage/extract_preflight.go index 58b1549..6313757 100644 --- a/internal/stage/extract_preflight.go +++ b/internal/stage/extract_preflight.go @@ -92,7 +92,7 @@ func BuildNotariusReadiness(cfg *config.Config, paths artifacts.SessionPaths, m request := notarius.ReadinessRequest{RunRequest: notarius.RunRequest{ Binary: binary, Credentials: n.Credentials, ConfigOverlay: n.ConfigOverlay, ConfigPath: configPath, PipelineID: n.PipelineID, InputPath: transcript, OutputRoot: output, WorkingDirectory: working, - ReceiptPath: filepath.Join(logs, "assessment.json"), LogPath: filepath.Join(logs, "preflight.stderr.log"), + ReportPath: filepath.Join(logs, "assessment.json"), LogPath: filepath.Join(logs, "preflight.stderr.log"), Timeout: timeout, Cache: cache, Debug: n.Debug, DebugDirectory: debug, References: bindings, }, RequiredLanes: lanes, InputDescription: description, InspectionPath: filepath.Join(logs, "pipeline.json"), InspectionLogPath: filepath.Join(logs, "pipeline.stderr.log")} return NotariusReadiness{Request: request, paths: paths, references: references}, nil diff --git a/internal/stage/extract_test.go b/internal/stage/extract_test.go index 0ea9ac3..a10ccbd 100644 --- a/internal/stage/extract_test.go +++ b/internal/stage/extract_test.go @@ -2,8 +2,6 @@ package stage import ( "context" - "crypto/sha256" - "encoding/hex" "encoding/json" "errors" "fmt" @@ -22,8 +20,6 @@ import ( "gitea.maximumdirect.net/eric/narratio/internal/manifest" ) -const extractIndexOutputKind = "notarius_index" - func TestExtractStageDisabledReturnsExplicitSkip(t *testing.T) { for _, test := range []struct { name string @@ -88,11 +84,11 @@ notarius: if req.InputPath != fixture.inputPath { t.Fatalf("input path = %q, want manifest path %q", req.InputPath, fixture.inputPath) } - wantReceipt := artifacts.SessionRunNotariusReceiptPathForCampaign(fixture.workspace, fixture.campaign, fixture.sessionID, fixture.runID) + wantReport := artifacts.SessionRunNotariusReportPathForCampaign(fixture.workspace, fixture.campaign, fixture.sessionID, fixture.runID) wantLog := artifacts.SessionRunNotariusLogPathForCampaign(fixture.workspace, fixture.campaign, fixture.sessionID, fixture.runID) wantOutputRoot := artifacts.SessionRunNotariusOutputRootForCampaign(fixture.workspace, fixture.campaign, fixture.sessionID, fixture.runID) if req.ConfigPath != env.Config.Pipeline.Notarius.ConfigPath || req.PipelineID != "dnd-session" || - req.OutputRoot != wantOutputRoot || req.ReceiptPath != wantReceipt || req.LogPath != wantLog || + req.OutputRoot != wantOutputRoot || req.ReportPath != wantReport || req.LogPath != wantLog || req.WorkingDirectory != env.Config.Pipeline.Notarius.WorkingDirectory || req.Timeout != 45*time.Minute { t.Fatalf("request = %#v", req) } @@ -102,8 +98,8 @@ notarius: if len(req.References) != 0 { t.Fatalf("references = %#v, want none", req.References) } - if req.Resume || req.ChunkCache != "" { - t.Fatalf("default cache controls = resume %v, mode %q", req.Resume, req.ChunkCache) + if req.Cache != nil { + t.Fatalf("default cache = %v", req.Cache) } if len(req.Credentials) != 1 || req.Credentials[0].EnvName() != credentialName || !req.Credentials[0].IsResolved() { t.Fatal("request did not retain the loaded Notarius credential reference") @@ -121,46 +117,31 @@ notarius: if strings.Contains(string(metadata), credentialCanary) || strings.Contains(string(metadata), credentialName) { t.Fatal("result metadata contains the Notarius credential") } - if len(result.Outputs) != 2 { - t.Fatalf("outputs = %#v, want lane and index", result.Outputs) + if len(result.Outputs) != 1 { + t.Fatalf("outputs = %#v, want one lane", result.Outputs) } } func TestExtractStageAppliesNotariusCacheControlsAndForcePrecedence(t *testing.T) { - tests := []struct { - name string - configuredResume bool - configuredMode string - force bool - wantResume bool - wantMode string + for _, test := range []struct { + name, configured, want string + force bool }{ - {name: "ordinary defaults"}, - {name: "ordinary configured", configuredResume: true, configuredMode: "bypass", wantResume: true, wantMode: "bypass"}, - {name: "force overrides configured", configuredResume: true, configuredMode: "bypass", force: true, wantMode: "refresh"}, - {name: "force overrides defaults", force: true, wantMode: "refresh"}, - } - for _, test := range tests { + {name: "defaults"}, {name: "configured", configured: "bypass", want: "bypass"}, + {name: "forced", configured: "bypass", want: "refresh", force: true}, {name: "forced default", want: "refresh", force: true}, + } { t.Run(test.name, func(t *testing.T) { env, m, fake := setupExtractEnv(t) - configOverlay := "inexpensive" - env.Config.Pipeline.Notarius.ConfigOverlay = &configOverlay - env.Config.Pipeline.Notarius.Resume = test.configuredResume - env.Config.Pipeline.Notarius.ChunkCache = test.configuredMode + if test.configured != "" { + env.Config.Pipeline.Notarius.Cache = &test.configured + } env.Force = test.force - if _, err := (extractStage{}).Run(context.Background(), env, m); err != nil { - t.Fatalf("Run() error = %v", err) + t.Fatal(err) } - if len(fake.Requests) != 1 { - t.Fatalf("requests = %d, want 1", len(fake.Requests)) - } - request := fake.Requests[0] - if request.Resume != test.wantResume || request.ChunkCache != test.wantMode { - t.Fatalf("cache controls = resume %v, mode %q; want resume %v, mode %q", request.Resume, request.ChunkCache, test.wantResume, test.wantMode) - } - if request.ConfigOverlay == nil || *request.ConfigOverlay != configOverlay { - t.Fatalf("config overlay = %#v, want %q", request.ConfigOverlay, configOverlay) + got := fake.Requests[0].Cache + if (got == nil && test.want != "") || (got != nil && *got != test.want) { + t.Fatalf("cache = %v, want %q", got, test.want) } }) } @@ -478,7 +459,7 @@ func TestExtractReferenceSnapshotsWithRelativeWorkspace(t *testing.T) { } // A controlled executable proves the production adapter accepts the paths. - // It intentionally produces no receipt; receipt validation is covered elsewhere. + // It intentionally produces no completion report; report validation is covered elsewhere. marker := filepath.Join(t.TempDir(), "started") binary := filepath.Join(t.TempDir(), "notarius") if err := os.WriteFile(binary, []byte("#!/bin/sh\nprintf started > '"+marker+"'\n"), 0o755); err != nil { @@ -488,11 +469,11 @@ func TestExtractReferenceSnapshotsWithRelativeWorkspace(t *testing.T) { _, err = notarius.NewSubprocessRunner().Run(context.Background(), notarius.RunRequest{ Binary: binary, PipelineID: "dnd-session", ConfigPath: env.Config.Pipeline.Notarius.ConfigPath, InputPath: prepared, OutputRoot: t.TempDir(), WorkingDirectory: env.Config.Pipeline.Workspace.Root, - Timeout: time.Second * 10, References: first, - ReceiptPath: filepath.Join(diagnostics, "receipt.json"), LogPath: filepath.Join(diagnostics, "stderr.log"), + Timeout: time.Second * 10, References: first, DebugDirectory: filepath.Join(diagnostics, "debug"), + ReportPath: filepath.Join(diagnostics, "report.json"), LogPath: filepath.Join(diagnostics, "stderr.log"), }) if err == nil { - t.Fatal("expected missing receipt error") + t.Fatal("expected missing completion report error") } if _, err := os.Stat(marker); err != nil { t.Fatalf("adapter did not launch with the snapshot bindings: %v", err) @@ -582,7 +563,7 @@ func assertFileContents(t *testing.T, path, want string) { func TestExtractStageRejectsUnavailableReferenceBeforeInvocationOrRunDirectoryCreation(t *testing.T) { env, m, fake := setupExtractEnv(t) env.Config.Pipeline.Notarius.References = map[string]string{ - "spell_catalog": artifactpolicy.SourceInputSpellCatalog, + "spell_catalog": "narratio.input.spell_catalog", } runRoot := artifacts.SessionRunRootForCampaign( env.Config.Pipeline.Workspace.Root, m.Campaign, m.SessionID, m.RunID, @@ -603,158 +584,6 @@ func TestExtractStageRejectsUnavailableReferenceBeforeInvocationOrRunDirectoryCr } } -func TestExtractStageProducesImmutableManifestReadyOutputs(t *testing.T) { - env, m, fake := setupExtractEnv(t) - fixture := extractFixtureFromEnv(t, env, m) - stagingBundle := fake.Result.BundleRoot - - result, err := (extractStage{}).Run(context.Background(), env, m) - if err != nil { - t.Fatalf("Run() error = %v", err) - } - durableBundle := artifacts.SessionNotariusBundleDirForCampaign(fixture.workspace, fixture.campaign, fixture.sessionID, fixture.runID) - if result.Metadata["bundle_root"] != durableBundle || result.Metadata["narratio_run_id"] != fixture.runID { - t.Fatalf("metadata = %#v", result.Metadata) - } - if fingerprint, _ := result.Metadata["configuration_fingerprint"].(string); len(fingerprint) != 64 { - t.Fatalf("configuration fingerprint = %#v", result.Metadata["configuration_fingerprint"]) - } - if result.Metadata["receipt_path"] != artifacts.SessionRunNotariusReceiptPathForCampaign(fixture.workspace, fixture.campaign, fixture.sessionID, fixture.runID) || - result.Metadata["diagnostic_path"] != artifacts.SessionRunNotariusLogPathForCampaign(fixture.workspace, fixture.campaign, fixture.sessionID, fixture.runID) || - result.Metadata["rejections_path"] != filepath.Join(durableBundle, "rejected.json") || - result.Metadata["warnings_path"] != filepath.Join(durableBundle, "warnings.json") || - result.Metadata["diagnostics_path"] != filepath.Join(durableBundle, "diagnostics.json") { - t.Fatalf("diagnostic metadata = %#v", result.Metadata) - } - if len(result.Outputs) != 2 { - t.Fatalf("outputs = %#v", result.Outputs) - } - lane := result.Outputs[0] - if lane.Kind != extractLaneOutputKind || lane.SourceID != "narratio.extraction.npc_registry" { - t.Fatalf("lane identity = %#v", lane) - } - if lane.AbsolutePath != filepath.Join(durableBundle, "lanes", "npc.json") || lane.Checksum == "" { - t.Fatalf("lane path/checksum = %#v", lane) - } - wantContract := &artifactmodel.ContractMetadata{ - MediaType: "application/json", SchemaID: "notarius.dnd.npc_registry", - SchemaVersion: "v1", ModuleKey: "dnd/npc-registry", - } - if !reflect.DeepEqual(lane.Contract, wantContract) { - t.Fatalf("lane contract = %#v, want %#v", lane.Contract, wantContract) - } - wantProvenance := &artifactmodel.ExternalProvenance{ - System: "notarius", RunID: "notarius-run-1", PipelineID: "dnd-session", ArtifactID: "npc-registry", - } - if !reflect.DeepEqual(lane.ExternalProvenance, wantProvenance) { - t.Fatalf("lane provenance = %#v, want %#v", lane.ExternalProvenance, wantProvenance) - } - index := result.Outputs[1] - if index.Kind != extractIndexOutputKind || index.SourceID != "" || index.AbsolutePath != filepath.Join(durableBundle, "index.json") || index.Checksum == "" { - t.Fatalf("index output = %#v", index) - } - if !strings.HasPrefix(lane.AbsolutePath, durableBundle+string(filepath.Separator)) || strings.HasPrefix(lane.AbsolutePath, stagingBundle+string(filepath.Separator)) { - t.Fatalf("lane path was not re-resolved after promotion: %q", lane.AbsolutePath) - } - for _, relative := range []string{ - "index.json", "manifest.json", "rejected.json", "warnings.json", "diagnostics.json", "lanes/npc.json", - "lanes/unconfigured.json", "chunk-map.json", "evidence-context.json", "unknown/private-debug.json", - } { - if _, err := os.Stat(filepath.Join(durableBundle, filepath.FromSlash(relative))); err != nil { - t.Fatalf("promoted file %q missing: %v", relative, err) - } - } - if _, err := os.Stat(stagingBundle); !os.IsNotExist(err) { - t.Fatalf("staging bundle still exists after rename: %v", err) - } - for _, output := range result.Outputs { - if strings.Contains(output.AbsolutePath, "unconfigured") || strings.Contains(output.AbsolutePath, "private-debug") { - t.Fatalf("unknown file registered as output: %#v", output) - } - } - - rejections, _ := result.Metadata["rejections"].([]map[string]any) - warnings, _ := result.Metadata["warnings"].([]map[string]any) - if len(rejections) != 1 || rejections[0]["reason_code"] != "optional_rejected" || len(warnings) != 1 { - t.Fatalf("diagnostic summaries = rejections %#v warnings %#v", rejections, warnings) - } -} - -func TestExtractStageConsumesAllDefaultDndPipelineArtifacts(t *testing.T) { - env, m, fake := setupExtractEnv(t) - - contracts := map[string]config.NotariusOutputConfig{ - "item_registry": {LaneID: "item-registry", MediaType: "application/json", SchemaID: "notarius.dnd.item_registry", SchemaVersion: "v1", ModuleKey: "dnd/item-registry"}, - "npc_registry": {LaneID: "npc-registry", MediaType: "application/json", SchemaID: "notarius.dnd.npc_registry", SchemaVersion: "v1", ModuleKey: "dnd/npc-registry"}, - "location_registry": {LaneID: "location-registry", MediaType: "application/json", SchemaID: "notarius.dnd.location_registry", SchemaVersion: "v1", ModuleKey: "dnd/location-registry"}, - "scene_descriptions": {LaneID: "scene-descriptions", MediaType: "application/json", SchemaID: "notarius.dnd.scene_descriptions", SchemaVersion: "v1", ModuleKey: "dnd/scene-descriptions"}, - "item_occurrences": {LaneID: "item-occurrences", MediaType: "application/json", SchemaID: "notarius.dnd.item_occurrences", SchemaVersion: "v1", ModuleKey: "dnd/item-occurrences"}, - "spells": {LaneID: "spells", MediaType: "application/json", SchemaID: "notarius.dnd.spells", SchemaVersion: "v1", ModuleKey: "dnd/spells"}, - "combat_turns": {LaneID: "combat-turns", MediaType: "application/json", SchemaID: "notarius.dnd.combat_turns", SchemaVersion: "v1", ModuleKey: "dnd/combat-turns"}, - "npc_occurrences": {LaneID: "npc-occurrences", MediaType: "application/json", SchemaID: "notarius.dnd.npc_occurrences", SchemaVersion: "v1", ModuleKey: "dnd/npc-occurrences"}, - "location_occurrences": {LaneID: "location-occurrences", MediaType: "application/json", SchemaID: "notarius.dnd.location_occurrences", SchemaVersion: "v1", ModuleKey: "dnd/location-occurrences"}, - "enemy_events": {LaneID: "enemy-events", MediaType: "application/json", SchemaID: "notarius.dnd.enemy_events", SchemaVersion: "v1", ModuleKey: "dnd/enemy-events"}, - } - env.Config.Pipeline.Notarius.Outputs = contracts - fake.Result.Index.Lanes = nil - fake.Result.Rejections = nil - fake.Result.Warnings = nil - fake.Result.Diagnostics = nil - fake.Result.Receipt.NormalizedOutputCount = len(contracts) - fake.Result.Receipt.RejectedOutputCount = 0 - fake.Result.Receipt.WarningGroupCount = 0 - fake.Result.Receipt.WarningOccurrenceCount = 0 - fake.Result.Receipt.DiagnosticGroupCount = 0 - fake.Result.Receipt.DiagnosticOccurrenceCount = 0 - fake.Result.Receipt.ValidationStatus = "approved" - indexDescriptors := make([]map[string]any, 0, len(contracts)) - for _, contract := range contracts { - relative := "lanes/" + contract.LaneID + ".json" - path := filepath.Join(fake.Result.BundleRoot, filepath.FromSlash(relative)) - if err := os.WriteFile(path, []byte(`{"records":[]}`), 0o644); err != nil { - t.Fatalf("WriteFile(%q) error = %v", path, err) - } - fake.Result.Index.Lanes = append(fake.Result.Index.Lanes, notarius.LaneDescriptor{ - LaneID: contract.LaneID, File: relative, Path: path, MediaType: contract.MediaType, - ModuleKey: contract.ModuleKey, SchemaID: contract.SchemaID, SchemaVersion: contract.SchemaVersion, - }) - indexDescriptors = append(indexDescriptors, map[string]any{ - "lane_id": contract.LaneID, "file": relative, "media_type": contract.MediaType, - "module_key": contract.ModuleKey, "schema_id": contract.SchemaID, - "schema_version": contract.SchemaVersion, - }) - } - if err := writeJSONFile(fake.Result.Index.Path, map[string]any{ - "manifest_file": "manifest.json", "output_files": indexDescriptors, - "rejected_file": "rejected.json", "warnings_file": "warnings.json", - "diagnostics_file": "diagnostics.json", - }); err != nil { - t.Fatalf("write complete D&D index: %v", err) - } - - result, err := (extractStage{}).Run(context.Background(), env, m) - if err != nil { - t.Fatalf("Run() error = %v", err) - } - if len(result.Outputs) != len(contracts)+1 { - t.Fatalf("output count = %d, want %d", len(result.Outputs), len(contracts)+1) - } - got := make(map[string]*artifactmodel.ContractMetadata, len(contracts)) - for _, output := range result.Outputs { - if output.Kind == extractLaneOutputKind { - got[output.SourceID] = output.Contract - } - } - for key, contract := range contracts { - sourceID := artifacts.ExtractionArtifactSourceID(key) - actual := got[sourceID] - if actual == nil || actual.MediaType != contract.MediaType || actual.SchemaID != contract.SchemaID || - actual.SchemaVersion != contract.SchemaVersion || actual.ModuleKey != contract.ModuleKey { - t.Fatalf("source %q contract = %#v, want %#v", sourceID, actual, contract) - } - } -} - func TestExtractStageRejectsMissingOrInvalidFinalTrimmedInputBeforeInvocation(t *testing.T) { tests := []struct { name string @@ -786,131 +615,6 @@ func TestExtractStageRejectsMissingOrInvalidFinalTrimmedInputBeforeInvocation(t } } -func TestExtractStageEnforcesRequiredLanePolicy(t *testing.T) { - tests := []struct { - name string - mutate func(*notarius.RunResult) - want string - }{ - {name: "missing", mutate: func(result *notarius.RunResult) { result.Index.Lanes = result.Index.Lanes[1:] }, want: "0 descriptors"}, - {name: "rejected", mutate: func(result *notarius.RunResult) { - result.Rejections = append(result.Rejections, notarius.RejectionSummary{LaneID: "npc-registry", ReasonCode: "invalid_npc"}) - }, want: "was rejected"}, - {name: "incomplete validation", mutate: func(result *notarius.RunResult) { - result.Receipt.ValidationSummaries = []notarius.ValidationSummary{{LaneID: "npc-registry", Status: "incomplete"}} - }, want: `validation is "incomplete"`}, - {name: "duplicate", mutate: func(result *notarius.RunResult) { - result.Index.Lanes = append(result.Index.Lanes, result.Index.Lanes[0]) - }, want: "2 descriptors"}, - {name: "media type", mutate: func(result *notarius.RunResult) { result.Index.Lanes[0].MediaType = "text/plain" }, want: "incompatible"}, - {name: "schema id", mutate: func(result *notarius.RunResult) { result.Index.Lanes[0].SchemaID = "other" }, want: "incompatible"}, - {name: "schema version", mutate: func(result *notarius.RunResult) { result.Index.Lanes[0].SchemaVersion = "v2" }, want: "incompatible"}, - {name: "module key", mutate: func(result *notarius.RunResult) { result.Index.Lanes[0].ModuleKey = "other" }, want: "incompatible"}, - } - for _, test := range tests { - t.Run(test.name, func(t *testing.T) { - env, m, fake := setupExtractEnv(t) - test.mutate(&fake.Result) - result, err := (extractStage{}).Run(context.Background(), env, m) - if err == nil || !strings.Contains(err.Error(), test.want) { - t.Fatalf("Run() result = %#v error = %v, want %q", result, err, test.want) - } - if result != nil && len(result.Outputs) != 0 { - t.Fatalf("failure returned outputs: %#v", result.Outputs) - } - }) - } -} - -func TestExtractStageValidatesSelectedLaneJSON(t *testing.T) { - for _, test := range []struct { - name string - content string - want string - }{ - {name: "empty", content: "", want: "non-empty"}, - {name: "invalid", content: "not-json", want: "valid JSON"}, - } { - t.Run(test.name, func(t *testing.T) { - env, m, fake := setupExtractEnv(t) - if err := os.WriteFile(fake.Result.Index.Lanes[0].Path, []byte(test.content), 0o644); err != nil { - t.Fatalf("WriteFile(lane) error = %v", err) - } - if _, err := (extractStage{}).Run(context.Background(), env, m); err == nil || !strings.Contains(err.Error(), test.want) { - t.Fatalf("Run() error = %v, want %q", err, test.want) - } - }) - } -} - -func TestExtractStageAdapterAndPromotionFailuresReturnNoOutputs(t *testing.T) { - t.Run("adapter", func(t *testing.T) { - env, m, fake := setupExtractEnv(t) - fixture := extractFixtureFromEnv(t, env, m) - receiptPath := artifacts.SessionRunNotariusReceiptPathForCampaign(fixture.workspace, fixture.campaign, fixture.sessionID, fixture.runID) - logPath := artifacts.SessionRunNotariusLogPathForCampaign(fixture.workspace, fixture.campaign, fixture.sessionID, fixture.runID) - for _, path := range []string{receiptPath, logPath} { - if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil { - t.Fatalf("MkdirAll(diagnostic parent) error = %v", err) - } - if err := os.WriteFile(path, []byte("diagnostic"), 0o644); err != nil { - t.Fatalf("WriteFile(diagnostic) error = %v", err) - } - } - fake.Err = errors.New("adapter failed") - result, err := (extractStage{}).Run(context.Background(), env, m) - if err == nil || !strings.Contains(err.Error(), "adapter failed") || result != nil { - t.Fatalf("Run() result = %#v error = %v", result, err) - } - outputRoot := artifacts.SessionRunNotariusOutputRootForCampaign(fixture.workspace, fixture.campaign, fixture.sessionID, fixture.runID) - if _, err := os.Stat(outputRoot); !os.IsNotExist(err) { - t.Fatalf("failed adapter output root still exists: %v", err) - } - for _, path := range []string{receiptPath, logPath} { - if _, err := os.Stat(path); err != nil { - t.Fatalf("diagnostic %q was not retained: %v", path, err) - } - } - }) - - t.Run("promotion", func(t *testing.T) { - env, m, fake := setupExtractEnv(t) - fixture := extractFixtureFromEnv(t, env, m) - destination := artifacts.SessionNotariusBundleDirForCampaign(fixture.workspace, fixture.campaign, fixture.sessionID, fixture.runID) - if err := os.MkdirAll(destination, 0o755); err != nil { - t.Fatalf("MkdirAll(destination) error = %v", err) - } - result, err := (extractStage{}).Run(context.Background(), env, m) - if err == nil || !strings.Contains(err.Error(), "destination already exists") || result != nil { - t.Fatalf("Run() result = %#v error = %v", result, err) - } - if _, err := os.Stat(fake.Result.BundleRoot); !os.IsNotExist(err) { - t.Fatalf("failed installation staging bundle still exists: %v", err) - } - }) - - t.Run("failure after rename", func(t *testing.T) { - env, m, _ := setupExtractEnv(t) - fixture := extractFixtureFromEnv(t, env, m) - outputRoot := artifacts.SessionRunNotariusOutputRootForCampaign(fixture.workspace, fixture.campaign, fixture.sessionID, fixture.runID) - if err := os.WriteFile(filepath.Join(outputRoot, "unexpected-sidecar"), []byte("unexpected"), 0o644); err != nil { - t.Fatalf("WriteFile(unexpected sidecar) error = %v", err) - } - destination := artifacts.SessionNotariusBundleDirForCampaign(fixture.workspace, fixture.campaign, fixture.sessionID, fixture.runID) - - result, err := (extractStage{}).Run(context.Background(), env, m) - if err == nil || !strings.Contains(err.Error(), "remove empty Notarius output root") || result != nil { - t.Fatalf("Run() result = %#v error = %v", result, err) - } - if _, err := os.Stat(destination); !os.IsNotExist(err) { - t.Fatalf("failed stage durable bundle still exists: %v", err) - } - if _, err := os.Stat(outputRoot); !os.IsNotExist(err) { - t.Fatalf("failed stage output root still exists: %v", err) - } - }) -} - func TestExtractionFingerprintIsIndependentOfOutputMapOrder(t *testing.T) { input := artifacts.ExtractionInputIdentity{ Checksum: "checksum", SourceID: artifacts.ArtifactTranscriptFinalTrimmed, @@ -918,8 +622,8 @@ func TestExtractionFingerprintIsIndependentOfOutputMapOrder(t *testing.T) { ProducerRunID: "trim-run", Provenance: "manifest.trim.outputs", } first := &config.NotariusConfig{PipelineID: "pipeline", Outputs: map[string]config.NotariusOutputConfig{ - "zeta": {LaneID: "z", MediaType: "application/json", SchemaID: "z", SchemaVersion: "v1"}, - "alpha": {LaneID: "a", MediaType: "application/json", SchemaID: "a", SchemaVersion: "v1"}, + "zeta": {LaneID: "z"}, + "alpha": {LaneID: "a"}, }} second := &config.NotariusConfig{PipelineID: "pipeline", Outputs: map[string]config.NotariusOutputConfig{ "alpha": first.Outputs["alpha"], "zeta": first.Outputs["zeta"], @@ -987,60 +691,6 @@ func TestExtractionFingerprintIsIndependentOfOutputMapOrder(t *testing.T) { } } -func TestExtractionFingerprintBaseSelectorsPreservePriorPayloadShape(t *testing.T) { - input := artifacts.ExtractionInputIdentity{ - Checksum: "checksum", SourceID: artifacts.ArtifactTranscriptFinalTrimmed, - ProducerStage: "trim", OutputKind: artifacts.TranscriptOutputKindFinalTrimmed, - ProducerRunID: "trim-run", Provenance: "manifest.trim.outputs", - } - references := []extractReferenceIdentity{{ - Selector: "party", SourceID: artifactpolicy.SourceInputParty, - Path: "inputs/party.yml", Checksum: "party-checksum", SizeBytes: 34, - }} - cfg := &config.NotariusConfig{ - PipelineID: "pipeline", - Outputs: map[string]config.NotariusOutputConfig{ - "alpha": {LaneID: "a", MediaType: "application/json", SchemaID: "a", SchemaVersion: "v1"}, - }, - } - legacyPayload, err := json.Marshal(struct { - PipelineID string `json:"pipeline_id"` - Input artifacts.ExtractionInputIdentity `json:"input"` - References []extractReferenceIdentity `json:"references"` - Outputs []fingerprintOutput `json:"outputs"` - }{ - PipelineID: cfg.PipelineID, - Input: input, - References: references, - Outputs: []fingerprintOutput{{ - Key: "alpha", LaneID: "a", MediaType: "application/json", SchemaID: "a", SchemaVersion: "v1", - }}, - }) - if err != nil { - t.Fatal(err) - } - legacyDigest := sha256.Sum256(legacyPayload) - want := hex.EncodeToString(legacyDigest[:]) - for _, profile := range []*string{nil, stringPointerForExtractTest(""), stringPointerForExtractTest("default")} { - cfg.ConfigOverlay = profile - got, err := extractionFingerprint(cfg, input, references) - if err != nil { - t.Fatal(err) - } - if got != want { - t.Fatalf("base selection fingerprint = %q, want prior no-profile payload digest %q", got, want) - } - } - cfg.ConfigOverlay = stringPointerForExtractTest("inexpensive") - named, err := extractionFingerprint(cfg, input, references) - if err != nil { - t.Fatal(err) - } - if named == want { - t.Fatal("named selection retained prior no-profile fingerprint") - } -} - func TestExtractStageResumeValidationAcceptsCurrentImmutableResult(t *testing.T) { env, m, _ := setupExtractEnv(t) env.Config.Pipeline.Notarius.References = map[string]string{ @@ -1159,7 +809,7 @@ func TestExtractStageResumeValidationDoesNotResolveReferencesWhenDisabled(t *tes env, m, _ := setupExtractEnv(t) env.Config.Pipeline.Notarius.Enabled = false env.Config.Pipeline.Notarius.References = map[string]string{ - "missing": artifactpolicy.SourceInputSpellCatalog, + "missing": "narratio.input.spell_catalog", } validation, err := (extractStage{}).ValidateResume(context.Background(), env, m) @@ -1171,68 +821,6 @@ func TestExtractStageResumeValidationDoesNotResolveReferencesWhenDisabled(t *tes } } -func TestExtractStageAdapterResultIsImmediatelyReusableAndCatalogVisible(t *testing.T) { - env, m, fake := setupExtractEnv(t) - producerRunID := m.RunID - receiptFixture := filepath.Join(t.TempDir(), "receipt.json") - receipt, err := json.Marshal(map[string]any{ - "schema_version": notarius.ReceiptSchemaVersion, - "run_id": "notarius-run-1", "pipeline_id": "dnd-session", - "output_directory": fake.Result.BundleRoot, "index_file": "index.json", - "normalized_output_count": 2, "rejected_output_count": 0, - "warning_group_count": 0, "warning_occurrence_count": 0, - "diagnostic_group_count": 0, "diagnostic_occurrence_count": 0, - "diagnostics_truncated": false, - "validation_status": "approved", "future_field": true, - }) - if err != nil { - t.Fatalf("json.Marshal(receipt) error = %v", err) - } - if err := os.WriteFile(receiptFixture, receipt, 0o644); err != nil { - t.Fatalf("WriteFile(receipt fixture) error = %v", err) - } - if err := os.WriteFile(env.Config.Pipeline.Notarius.Binary, []byte(fmt.Sprintf("#!/bin/sh\ncat %q\n", receiptFixture)), 0o755); err != nil { - t.Fatalf("WriteFile(notarius helper) error = %v", err) - } - env.Notarius = notarius.NewSubprocessRunner() - - result, err := (extractStage{}).Run(context.Background(), env, m) - if err != nil { - t.Fatalf("Run() error = %v", err) - } - durableIndex := filepath.Join(result.Metadata["bundle_root"].(string), "index.json") - if len(result.Outputs) != 2 || result.Outputs[1].AbsolutePath != durableIndex { - t.Fatalf("outputs = %#v, want canonical durable index %q", result.Outputs, durableIndex) - } - recordSucceededExtractResult(m, producerRunID, result) - m.RunID = "20260810T020304Z-fedcba98" - - validation, err := (extractStage{}).ValidateResume(context.Background(), env, m) - if err != nil { - t.Fatalf("ValidateResume() error = %v", err) - } - if !validation.Resumable { - t.Fatalf("validation = %#v, want resumable", validation) - } - definition := env.Config.Pipeline.Notarius.Outputs["npc_registry"] - definitions := map[string]artifacts.ExtractionArtifactDefinition{ - "npc_registry": { - LaneID: definition.LaneID, PipelineID: env.Config.Pipeline.Notarius.PipelineID, - MediaType: definition.MediaType, SchemaID: definition.SchemaID, - SchemaVersion: definition.SchemaVersion, ModuleKey: definition.ModuleKey, - }, - } - catalog := artifacts.NewArtifactCatalog() - if err := catalog.RegisterExtractionArtifacts(definitions); err != nil { - t.Fatalf("RegisterExtractionArtifacts() error = %v", err) - } - catalog.HydrateExtractionArtifacts(sessionPathsForEnv(env, m.SessionID), m, definitions) - entry, ok := catalog.Lookup(artifacts.ExtractionArtifactSourceID("npc_registry")) - if !ok || !entry.Available || entry.Path != result.Outputs[0].AbsolutePath || entry.ProducerRunID != producerRunID { - t.Fatalf("hydrated extraction entry = %#v, %v", entry, ok) - } -} - func TestExtractStageResumeValidationRequiresFreshEvidence(t *testing.T) { tests := []struct { name string @@ -1265,8 +853,8 @@ func TestExtractStageResumeValidationRequiresFreshEvidence(t *testing.T) { t.Fatalf("WriteFile(lane) error = %v", err) } }}, - {name: "incompatible contract", mutate: func(_ *testing.T, _ *Env, m *manifest.Manifest) { - m.Stages["extract"].Outputs[0].Contract.SchemaVersion = "v2" + {name: "incorrect size", mutate: func(_ *testing.T, _ *Env, m *manifest.Manifest) { + m.Stages["extract"].Outputs[0].Size++ }}, {name: "missing source", mutate: func(_ *testing.T, _ *Env, m *manifest.Manifest) { m.Stages["extract"].Outputs = m.Stages["extract"].Outputs[1:] @@ -1275,13 +863,7 @@ func TestExtractStageResumeValidationRequiresFreshEvidence(t *testing.T) { m.Stages["extract"].Outputs[0].ProducerRunID = "different-run" }}, {name: "provenance mismatch", mutate: func(_ *testing.T, _ *Env, m *manifest.Manifest) { - m.Stages["extract"].Outputs[0].ExternalProvenance.RunID = "different-run" - }}, - {name: "missing index", mutate: func(t *testing.T, _ *Env, m *manifest.Manifest) { - index := m.Stages["extract"].Outputs[1] - if err := os.Remove(index.LocalPath); err != nil { - t.Fatalf("Remove(index) error = %v", err) - } + m.Stages["extract"].Outputs[0].ExternalProvenance.ArtifactID = "different-lane" }}, } for _, test := range tests { @@ -1331,7 +913,7 @@ func TestExtractStageResumeValidationRejectsUnsafePathWithError(t *testing.T) { prior := *m.Stages["extract"] test.mutate(t, env, m) - if _, err := (extractStage{}).ValidateResume(context.Background(), env, m); err == nil || !strings.Contains(err.Error(), "unsafe") { + if _, err := (extractStage{}).ValidateResume(context.Background(), env, m); err == nil { t.Fatalf("ValidateResume() error = %v, want unsafe evidence error", err) } if m.Stages["extract"].Status != prior.Status || m.Stages["extract"].Error != prior.Error { @@ -1357,7 +939,7 @@ func recordSucceededExtractResult(m *manifest.Manifest, producerRunID string, re records = append(records, manifest.ArtifactRecord{ Kind: output.Kind, SourceID: output.SourceID, LocalPath: output.AbsolutePath, Contract: output.Contract, ExternalProvenance: output.ExternalProvenance, - ProducerRunID: producerRunID, Checksum: output.Checksum, + ProducerRunID: producerRunID, Checksum: output.Checksum, Size: output.Size, }) } m.MarkStageSucceeded("extract", time.Now().UTC(), records) @@ -1438,8 +1020,7 @@ func setupExtractEnv(t *testing.T) (*Env, *manifest.Manifest, *notarius.FakeRunn Timeout: "45m", WorkingDirectory: workingDirectory, Outputs: map[string]config.NotariusOutputConfig{ "npc_registry": { - LaneID: "npc-registry", MediaType: "application/json", - SchemaID: "notarius.dnd.npc_registry", SchemaVersion: "v1", ModuleKey: "dnd/npc-registry", + LaneID: "npc-registry", }, }, } @@ -1460,57 +1041,11 @@ func setupExtractEnv(t *testing.T) (*Env, *manifest.Manifest, *notarius.FakeRunn if err := os.MkdirAll(filepath.Join(bundle, "lanes"), 0o755); err != nil { t.Fatalf("MkdirAll(bundle lanes) error = %v", err) } - if err := os.MkdirAll(filepath.Join(bundle, "unknown"), 0o755); err != nil { - t.Fatalf("MkdirAll(bundle unknown) error = %v", err) + if err := os.WriteFile(filepath.Join(bundle, "lanes", "npc-registry.json"), []byte(`{"npcs":[]}`), 0644); err != nil { + t.Fatal(err) } - files := map[string]string{ - "index.json": `{"manifest_file":"manifest.json","output_files":[{"lane_id":"npc-registry","file":"lanes/npc.json","media_type":"application/json","module_key":"dnd/npc-registry","schema_id":"notarius.dnd.npc_registry","schema_version":"v1","future_field":true},{"lane_id":"unconfigured","file":"lanes/unconfigured.json"}],"rejected_file":"rejected.json","warnings_file":"warnings.json","diagnostics_file":"diagnostics.json","future_field":true}`, - "manifest.json": `{}`, - "rejected.json": `{"rejected":[]}`, - "warnings.json": `{"schema_version":"notarius.warnings.v2","group_count":0,"occurrence_count":0,"groups":[]}`, - "diagnostics.json": `{"schema_version":"notarius.diagnostics.v1","group_count":0,"occurrence_count":0,"truncated":false,"unrepresented_occurrence_count":0,"groups":[]}`, - "lanes/npc.json": `{"npcs":[]}`, - "lanes/unconfigured.json": `{"spells":[]}`, - "chunk-map.json": `{"chunks":[]}`, - "evidence-context.json": `{"source_units":[]}`, - "unknown/private-debug.json": `{"private":true}`, - } - for relative, content := range files { - if err := os.WriteFile(filepath.Join(bundle, filepath.FromSlash(relative)), []byte(content), 0o644); err != nil { - t.Fatalf("WriteFile(%q) error = %v", relative, err) - } - } - fake := ¬arius.FakeRunner{Result: notarius.RunResult{ - Receipt: notarius.Receipt{ - SchemaVersion: notarius.ReceiptSchemaVersion, RunID: "notarius-run-1", PipelineID: "dnd-session", - OutputDirectory: bundle, IndexFile: "index.json", NormalizedOutputCount: 2, - RejectedOutputCount: 1, WarningGroupCount: 1, WarningOccurrenceCount: 1, - DiagnosticGroupCount: 1, DiagnosticOccurrenceCount: 1, ValidationStatus: "rejected", - }, - BundleRoot: bundle, - Index: notarius.Index{ - Path: filepath.Join(bundle, "index.json"), RejectedPath: filepath.Join(bundle, "rejected.json"), - WarningsPath: filepath.Join(bundle, "warnings.json"), - DiagnosticsPath: filepath.Join(bundle, "diagnostics.json"), - Lanes: []notarius.LaneDescriptor{ - { - LaneID: "npc-registry", File: "lanes/npc.json", Path: filepath.Join(bundle, "lanes", "npc.json"), - MediaType: "application/json", ModuleKey: "dnd/npc-registry", - SchemaID: "notarius.dnd.npc_registry", SchemaVersion: "v1", - }, - {LaneID: "unconfigured", File: "lanes/unconfigured.json", Path: filepath.Join(bundle, "lanes", "unconfigured.json")}, - }, - }, - Rejections: []notarius.RejectionSummary{{LaneID: "optional", ReasonCode: "optional_rejected"}}, - Warnings: []notarius.WarningSummary{{ - Disposition: "warning", Category: "degradation", ReasonCode: "normalized_name", - Origin: notarius.DiagnosticOrigin{Stage: "normalize", LaneID: "npc-registry"}, OccurrenceCount: 1, - }}, - Diagnostics: []notarius.DiagnosticSummary{{ - Disposition: "advisory", Category: "data_quality", ReasonCode: "low_confidence", - Origin: notarius.DiagnosticOrigin{Stage: "normalize", ValidatorKey: "validator"}, OccurrenceCount: 1, - }}, - }} + fake := ¬arius.FakeRunner{Result: notarius.RunResult{BundleRoot: bundle, Report: notarius.CompletionReport{Pipeline: "dnd-session", ArtifactCount: 1, OutputDirectory: bundle}}} + env := &Env{ Config: &config.Config{ Pipeline: &config.PipelineConfig{Workspace: config.WorkspaceConfig{Root: workspace}, Notarius: notariusConfig}, diff --git a/internal/stage/merge_test.go b/internal/stage/merge_test.go index 797a173..ca60c39 100644 --- a/internal/stage/merge_test.go +++ b/internal/stage/merge_test.go @@ -461,8 +461,7 @@ func setupMergeEnvWithWorkspace(t *testing.T, workspace string) (*Env, *manifest Session: &config.SessionConfig{ SessionID: "2026-05-03", Inputs: config.SessionInputsConfig{ - SpeakersFile: "./speakers.yml", - AutocorrectFile: "./autocorrect.yml", + SpeakersFile: "./speakers.yml", }, }, } diff --git a/internal/stage/notarius_cache_integration_test.go b/internal/stage/notarius_cache_integration_test.go index 385eddf..1bd972c 100644 --- a/internal/stage/notarius_cache_integration_test.go +++ b/internal/stage/notarius_cache_integration_test.go @@ -52,7 +52,8 @@ func TestNotariusCacheReuseIntegration(t *testing.T) { t.Fatalf("first chunk plan = %#v, want generated", first.ChunkPlan) } - env.Config.Pipeline.Notarius.Resume = true + mode := "auto" + env.Config.Pipeline.Notarius.Cache = &mode second := runNotariusIntegrationExtraction(t, env, runManifest, "20260916T010102Z-a0000002", false) if got := provider.Calls(); got != 2 { t.Fatalf("resumed provider calls = %d, want unchanged count 2", got) @@ -112,7 +113,8 @@ func TestNotariusCacheReuseIntegration(t *testing.T) { provider := newNotariusIntegrationProvider(t) provider.FailRequest(2) env, runManifest, _ := newNotariusIntegrationFixture(t, binary, provider.URL(), "dnd-recovery") - env.Config.Pipeline.Notarius.Resume = true + mode := "auto" + env.Config.Pipeline.Notarius.Cache = &mode runManifest.RunID = "20260916T020101Z-b0000001" env.Force = false @@ -253,16 +255,14 @@ pipelines: env.Config.Pipeline.Notarius = &config.NotariusConfig{ Enabled: true, Binary: binary, ConfigPath: configPath, PipelineID: pipelineID, ConfigOverlay: &overlay, - Timeout: "2m", WorkingDirectory: root, ChunkCache: "auto", + Timeout: "2m", WorkingDirectory: root, References: map[string]string{"party": artifactpolicy.SourceInputParty}, Outputs: map[string]config.NotariusOutputConfig{ "spells_first": { - LaneID: "spells-first", MediaType: "application/json", ModuleKey: "dnd/spells", - SchemaID: "notarius.dnd.spells", SchemaVersion: "v1", + LaneID: "spells-first", }, "spells_second": { - LaneID: "spells-second", MediaType: "application/json", ModuleKey: "dnd/spells", - SchemaID: "notarius.dnd.spells", SchemaVersion: "v1", + LaneID: "spells-second", }, }, } @@ -342,8 +342,8 @@ func runNotariusIntegrationExtraction(t *testing.T, env *Env, runManifest *manif env.Force = force result, err := (extractStage{}).Run(context.Background(), env, runManifest) if err != nil { - receiptPath := artifacts.SessionRunNotariusReceiptPathForCampaign(env.Config.Pipeline.Workspace.Root, runManifest.Campaign, runManifest.SessionID, runID) - if data, readErr := os.ReadFile(receiptPath); readErr == nil { + reportPath := artifacts.SessionRunNotariusReportPathForCampaign(env.Config.Pipeline.Workspace.Root, runManifest.Campaign, runManifest.SessionID, runID) + if data, readErr := os.ReadFile(reportPath); readErr == nil { t.Logf("failed Notarius receipt: %s", data) } t.Fatalf("extract run %q: %v", runID, err) diff --git a/internal/stage/prepare_test.go b/internal/stage/prepare_test.go index 5acaa24..c79efcd 100644 --- a/internal/stage/prepare_test.go +++ b/internal/stage/prepare_test.go @@ -709,11 +709,6 @@ inputs: ConfigPath: campaignPath, Source: "campaign_config", }, - AutocorrectFile: config.ResolvedInputFile{ - Path: "./autocorrect.yml", - ConfigPath: campaignPath, - Source: "campaign_config", - }, GlossaryFile: config.ResolvedInputFile{ Path: "./glossary.yml", ConfigPath: campaignPath, diff --git a/internal/stage/publish_test.go b/internal/stage/publish_test.go index 2b42f35..3738437 100644 --- a/internal/stage/publish_test.go +++ b/internal/stage/publish_test.go @@ -70,10 +70,6 @@ func TestPublishUploadsRunFilesPublishedOutputsAndCurrentPointer(t *testing.T) { configurePublishExtractionFixture(t, env, m) runBundleRoot := filepath.Join(runRoot, "extract", "notarius-output", "notarius-run-1") for rel, contents := range map[string]string{ - "index.json": `{"lanes":[]}`, - "manifest.json": `{"run_id":"notarius-run-1"}`, - "rejected.json": `[]`, - "warnings.json": `[]`, "lanes/encounters.json": `{"encounters":[]}`, "pipeline/chunk-map.json": `{"chunks":[]}`, "pipeline/evidence-context.json": `{"evidence":[]}`, @@ -81,7 +77,7 @@ func TestPublishUploadsRunFilesPublishedOutputsAndCurrentPointer(t *testing.T) { } { writeStageTestFile(t, filepath.Join(runBundleRoot, filepath.FromSlash(rel)), contents) } - writeStageTestFile(t, filepath.Join(runRoot, "extract", "notarius.receipt.json"), `{"run_id":"notarius-run-1"}`) + writeStageTestFile(t, filepath.Join(runRoot, "extract", "notarius.report.json"), `{"pipeline":"campaign.extract","artifact_count":1}`) writeStageTestFile(t, filepath.Join(runRoot, "extract", "notarius.stderr.log"), "notarius diagnostic\n") writeStageTestFile(t, filepath.Join(runRoot, "extract", "notarius-output-copy", "keep.json"), "{}\n") writeStageTestFile(t, filepath.Join(runRoot, "archive", "notarius-output", "keep.json"), "{}\n") diff --git a/internal/stage/semantic_contracts_delivery_test.go b/internal/stage/semantic_contracts_delivery_test.go index 9d80460..105c91d 100644 --- a/internal/stage/semantic_contracts_delivery_test.go +++ b/internal/stage/semantic_contracts_delivery_test.go @@ -40,14 +40,14 @@ func TestExtractSemanticConfigSensitivityAndOperationalExclusions(t *testing.T) output.LaneID = "encounters-v2" env.Config.Pipeline.Notarius.Outputs["encounters"] = output }}, - {name: "contract", mutate: func(env *Env) { + {name: "filename", mutate: func(env *Env) { output := env.Config.Pipeline.Notarius.Outputs["encounters"] - output.SchemaVersion = "2" + output.Filename = "renamed.json" env.Config.Pipeline.Notarius.Outputs["encounters"] = output }}, {name: "output identity", mutate: func(env *Env) { env.Config.Pipeline.Notarius.Outputs["characters"] = config.NotariusOutputConfig{ - LaneID: "characters", MediaType: "application/json", SchemaID: "characters", SchemaVersion: "1", + LaneID: "characters", } }}, } { @@ -82,8 +82,8 @@ func TestExtractSemanticConfigSensitivityAndOperationalExclusions(t *testing.T) name string mutate func(*config.NotariusConfig) }{ - {name: "resume", mutate: func(cfg *config.NotariusConfig) { cfg.Resume = true }}, - {name: "chunk cache", mutate: func(cfg *config.NotariusConfig) { cfg.ChunkCache = "refresh" }}, + {name: "cache", mutate: func(cfg *config.NotariusConfig) { value := "refresh"; cfg.Cache = &value }}, + {name: "debug", mutate: func(cfg *config.NotariusConfig) { cfg.Debug = true }}, } { t.Run("operational "+test.name, func(t *testing.T) { env := downstreamSemanticEnv() @@ -174,8 +174,8 @@ func TestExtractResumeValidationExcludesOperationalSettings(t *testing.T) { env.Config.Pipeline.Notarius.ConfigPath = "/not/present/private.yml" env.Config.Pipeline.Notarius.Timeout = "not-a-duration" env.Config.Pipeline.Notarius.WorkingDirectory = "/not/present/work" - env.Config.Pipeline.Notarius.Resume = true - env.Config.Pipeline.Notarius.ChunkCache = "bypass" + mode := "bypass" + env.Config.Pipeline.Notarius.Cache = &mode validation, err := (extractStage{}).ValidateResume(context.Background(), env, m) if err != nil { @@ -368,8 +368,7 @@ func downstreamSemanticEnv() *Env { References: map[string]string{"party": artifactpolicy.SourceInputParty}, Outputs: map[string]config.NotariusOutputConfig{ "encounters": { - LaneID: "encounters", MediaType: "application/json", SchemaID: "encounters", - SchemaVersion: "1", ModuleKey: "encounters", + LaneID: "encounters", }, }, }, diff --git a/internal/stage/transcribe_test.go b/internal/stage/transcribe_test.go index f00e665..a03a68e 100644 --- a/internal/stage/transcribe_test.go +++ b/internal/stage/transcribe_test.go @@ -459,17 +459,15 @@ func setupTranscribeEnv(t *testing.T, audioFiles []string) (*Env, *manifest.Mani SessionID: "2026-05-03", Campaign: "sample-campaign", Inputs: config.SessionInputsConfig{ - AudioDir: "./audio", - SpeakersFile: "./speakers.yml", - AutocorrectFile: "./autocorrect.yml", - GlossaryFile: new(filepath.Join(cfgDir, "glossary.yml")), + AudioDir: "./audio", + SpeakersFile: "./speakers.yml", + GlossaryFile: new(filepath.Join(cfgDir, "glossary.yml")), }, }, StableInputs: config.ResolvedStableInputs{ - SpeakersFile: config.ResolvedInputFile{Path: "./speakers.yml", ConfigPath: campaignPath, Source: "campaign_config"}, - AutocorrectFile: config.ResolvedInputFile{Path: "./autocorrect.yml", ConfigPath: campaignPath, Source: "campaign_config"}, - GlossaryFile: config.ResolvedInputFile{Path: "./glossary.yml", ConfigPath: campaignPath, Source: "campaign_config"}, - PartyFile: config.ResolvedInputFile{Path: "./party.yml", ConfigPath: campaignPath, Source: "campaign_config"}, + SpeakersFile: config.ResolvedInputFile{Path: "./speakers.yml", ConfigPath: campaignPath, Source: "campaign_config"}, + GlossaryFile: config.ResolvedInputFile{Path: "./glossary.yml", ConfigPath: campaignPath, Source: "campaign_config"}, + PartyFile: config.ResolvedInputFile{Path: "./party.yml", ConfigPath: campaignPath, Source: "campaign_config"}, }, }