Reconcile reuse and inspection with native extraction
This commit is contained in:
@@ -764,6 +764,14 @@ partial delete retry, cleanup-only invocation, and publication authorization.
|
|||||||
|
|
||||||
## Stage 21 — Reconcile reuse, planning, and inspection across the cutover
|
## 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.
|
**Read:** roadmap verification and existing semantic/invalidation contracts.
|
||||||
Entry points: prepare/extract/analyze resume, artifact hydration, session planning,
|
Entry points: prepare/extract/analyze resume, artifact hydration, session planning,
|
||||||
status/validation, configuration persistence, and command result reporting.
|
status/validation, configuration persistence, and command result reporting.
|
||||||
|
|||||||
@@ -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
|
|
||||||
}
|
|
||||||
@@ -25,7 +25,7 @@ func TestNativeCompletionAndInvocation(t *testing.T) {
|
|||||||
runner := &SubprocessRunner{run: func(_ context.Context, request subprocess.RunRequest) (subprocess.RunResult, error) {
|
runner := &SubprocessRunner{run: func(_ context.Context, request subprocess.RunRequest) (subprocess.RunResult, error) {
|
||||||
args = request.Args
|
args = request.Args
|
||||||
document, _ := json.Marshal(map[string]any{"pipeline": req.PipelineID, "artifact_count": 12, "output_directory": bundle, "fallback_count": 3})
|
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)
|
t.Fatal(err)
|
||||||
}
|
}
|
||||||
return subprocess.RunResult{}, nil
|
return subprocess.RunResult{}, nil
|
||||||
@@ -47,7 +47,7 @@ func TestNativeCompletionRequiresSuccessfulExit(t *testing.T) {
|
|||||||
req := validRunRequest(t)
|
req := validRunRequest(t)
|
||||||
req.DebugDirectory = filepath.Join(filepath.Dir(req.LogPath), "debug")
|
req.DebugDirectory = filepath.Join(filepath.Dir(req.LogPath), "debug")
|
||||||
runner := &SubprocessRunner{run: func(_ context.Context, _ subprocess.RunRequest) (subprocess.RunResult, error) {
|
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)
|
t.Fatal(err)
|
||||||
}
|
}
|
||||||
return subprocess.RunResult{ExitCode: 1}, errors.New("process failed")
|
return subprocess.RunResult{ExitCode: 1}, errors.New("process failed")
|
||||||
@@ -71,7 +71,7 @@ func TestNativeCompletionRejectsInvalidReports(t *testing.T) {
|
|||||||
req := validRunRequest(t)
|
req := validRunRequest(t)
|
||||||
req.DebugDirectory = filepath.Join(filepath.Dir(req.LogPath), "debug")
|
req.DebugDirectory = filepath.Join(filepath.Dir(req.LogPath), "debug")
|
||||||
runner := &SubprocessRunner{run: func(_ context.Context, _ subprocess.RunRequest) (subprocess.RunResult, error) {
|
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)
|
t.Fatal(err)
|
||||||
}
|
}
|
||||||
return subprocess.RunResult{}, nil
|
return subprocess.RunResult{}, nil
|
||||||
@@ -97,7 +97,7 @@ func TestNativeInvocationOmitsOptionalControls(t *testing.T) {
|
|||||||
t.Fatalf("args = %#v, want %#v", request.Args, want)
|
t.Fatalf("args = %#v, want %#v", request.Args, want)
|
||||||
}
|
}
|
||||||
document, _ := json.Marshal(map[string]any{"pipeline": req.PipelineID, "artifact_count": 0, "output_directory": bundle})
|
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)
|
t.Fatal(err)
|
||||||
}
|
}
|
||||||
return subprocess.RunResult{}, nil
|
return subprocess.RunResult{}, nil
|
||||||
|
|||||||
@@ -66,7 +66,7 @@ func (r *SubprocessRunner) Preflight(ctx context.Context, req ReadinessRequest)
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
seenPaths := map[string]bool{}
|
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)
|
path = filepath.Clean(path)
|
||||||
if seenPaths[path] {
|
if seenPaths[path] {
|
||||||
return result, fmt.Errorf("notarius readiness report and diagnostic paths must be distinct")
|
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)
|
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
|
result.ExitCode = outcome.ExitCode
|
||||||
assessment, assessmentErr := loadReadinessAssessment(req.ReceiptPath, req.PipelineID)
|
assessment, assessmentErr := loadReadinessAssessment(req.ReportPath, req.PipelineID)
|
||||||
if assessmentErr == nil {
|
if assessmentErr == nil {
|
||||||
result.AssessmentComplete = true
|
result.AssessmentComplete = true
|
||||||
result.Ready, result.Checks, result.DebugDirectory = assessment.Ready, assessment.Checks, assessment.DebugDirectory
|
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:"lanes"`
|
||||||
} `json:"steps"`
|
} `json:"steps"`
|
||||||
}
|
}
|
||||||
if err := decodeBoundedJSON(path, maxReceiptBytes, &doc); err != nil {
|
if err := decodeBoundedJSON(path, maxReportBytes, &doc); err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
if doc.Pipeline != pipelineID || doc.Steps == nil || !completeInspectedModule(doc.Input) || !completeInspectedModule(doc.Chunk) || !completeInspectedModule(doc.Output) {
|
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"`
|
Checks *[]ReadinessCheck `json:"checks"`
|
||||||
DebugDirectory string `json:"debug_directory"`
|
DebugDirectory string `json:"debug_directory"`
|
||||||
}
|
}
|
||||||
if err := decodeBoundedJSON(path, maxReceiptBytes, &doc); err != nil {
|
if err := decodeBoundedJSON(path, maxReportBytes, &doc); err != nil {
|
||||||
return ReadinessResult{}, err
|
return ReadinessResult{}, err
|
||||||
}
|
}
|
||||||
if doc.Pipeline != pipelineID || doc.Ready == nil || doc.Checks == nil || (doc.DebugDirectory != "" && !filepath.IsAbs(doc.DebugDirectory)) {
|
if doc.Pipeline != pipelineID || doc.Ready == nil || doc.Checks == nil || (doc.DebugDirectory != "" && !filepath.IsAbs(doc.DebugDirectory)) {
|
||||||
|
|||||||
@@ -8,8 +8,6 @@ import (
|
|||||||
configkit "go.maximumdirect.net/configkit"
|
configkit "go.maximumdirect.net/configkit"
|
||||||
)
|
)
|
||||||
|
|
||||||
const ReceiptSchemaVersion = "notarius.run-result.v2"
|
|
||||||
|
|
||||||
// Runner is the adapter boundary for a complete Notarius pipeline invocation.
|
// Runner is the adapter boundary for a complete Notarius pipeline invocation.
|
||||||
type Runner interface {
|
type Runner interface {
|
||||||
Run(ctx context.Context, req RunRequest) (RunResult, error)
|
Run(ctx context.Context, req RunRequest) (RunResult, error)
|
||||||
@@ -33,141 +31,23 @@ type RunRequest struct {
|
|||||||
InputPath string
|
InputPath string
|
||||||
OutputRoot string
|
OutputRoot string
|
||||||
WorkingDirectory string
|
WorkingDirectory string
|
||||||
ReceiptPath string
|
ReportPath string
|
||||||
LogPath string
|
LogPath string
|
||||||
Timeout time.Duration
|
Timeout time.Duration
|
||||||
Cache *string
|
Cache *string
|
||||||
Debug bool
|
Debug bool
|
||||||
DebugDirectory string
|
DebugDirectory string
|
||||||
Resume bool
|
|
||||||
ChunkCache string
|
|
||||||
References []ReferenceBinding
|
References []ReferenceBinding
|
||||||
}
|
}
|
||||||
|
|
||||||
// Receipt is the transport-neutral successful run receipt.
|
// RunResult describes a successfully decoded native completion.
|
||||||
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.
|
|
||||||
type RunResult struct {
|
type RunResult struct {
|
||||||
Report CompletionReport
|
Report CompletionReport
|
||||||
Receipt Receipt
|
BundleRoot string
|
||||||
Index Index
|
ReportPath string
|
||||||
BundleRoot string
|
LogPath string
|
||||||
ReceiptPath string
|
ExitCode int
|
||||||
LogPath string
|
Duration time.Duration
|
||||||
ExitCode int
|
|
||||||
Duration time.Duration
|
|
||||||
Rejections []RejectionSummary
|
|
||||||
Warnings []WarningSummary
|
|
||||||
Diagnostics []DiagnosticSummary
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// CompletionReport contains facts reported by a successfully completed run.
|
// CompletionReport contains facts reported by a successfully completed run.
|
||||||
|
|||||||
@@ -15,21 +15,7 @@ import (
|
|||||||
"gitea.maximumdirect.net/eric/narratio/internal/pathsafe"
|
"gitea.maximumdirect.net/eric/narratio/internal/pathsafe"
|
||||||
)
|
)
|
||||||
|
|
||||||
const (
|
const maxReportBytes = 1 << 20
|
||||||
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
|
|
||||||
)
|
|
||||||
|
|
||||||
type subprocessRun func(context.Context, subprocess.RunRequest) (subprocess.RunResult, error)
|
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,
|
WorkingDir: req.WorkingDirectory,
|
||||||
Timeout: req.Timeout,
|
Timeout: req.Timeout,
|
||||||
DiagnosticOwner: "notarius",
|
DiagnosticOwner: "notarius",
|
||||||
StdoutLogPath: req.ReceiptPath,
|
StdoutLogPath: req.ReportPath,
|
||||||
StderrLogPath: req.LogPath,
|
StderrLogPath: req.LogPath,
|
||||||
EnvOverrides: envOverrides,
|
EnvOverrides: envOverrides,
|
||||||
SensitiveEnvNames: sensitiveEnvNames,
|
SensitiveEnvNames: sensitiveEnvNames,
|
||||||
})
|
})
|
||||||
baseResult := RunResult{
|
baseResult := RunResult{
|
||||||
ReceiptPath: req.ReceiptPath,
|
ReportPath: req.ReportPath,
|
||||||
LogPath: req.LogPath,
|
LogPath: req.LogPath,
|
||||||
ExitCode: processResult.ExitCode,
|
ExitCode: processResult.ExitCode,
|
||||||
Duration: processResult.Duration,
|
Duration: processResult.Duration,
|
||||||
}
|
}
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return baseResult, fmt.Errorf("run notarius pipeline %q: %w", req.PipelineID, err)
|
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 {
|
if processResult.ExitCode != 0 {
|
||||||
return baseResult, fmt.Errorf("run notarius pipeline %q: exit code %d", req.PipelineID, processResult.ExitCode)
|
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 {
|
if err != nil {
|
||||||
return baseResult, err
|
return baseResult, err
|
||||||
}
|
}
|
||||||
@@ -128,7 +114,7 @@ func loadCompletionReport(path, pipelineID string) (CompletionReport, error) {
|
|||||||
DebugDirectory string `json:"debug_directory"`
|
DebugDirectory string `json:"debug_directory"`
|
||||||
FallbackCount *int `json:"fallback_count"`
|
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)
|
return CompletionReport{}, fmt.Errorf("decode notarius completion report: %w", err)
|
||||||
}
|
}
|
||||||
if document.Pipeline != pipelineID || document.ArtifactCount == nil || *document.ArtifactCount < 0 || !filepath.IsAbs(document.OutputDirectory) {
|
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,
|
"input": req.InputPath,
|
||||||
"output root": req.OutputRoot,
|
"output root": req.OutputRoot,
|
||||||
"working directory": req.WorkingDirectory,
|
"working directory": req.WorkingDirectory,
|
||||||
"receipt": req.ReceiptPath,
|
"report": req.ReportPath,
|
||||||
"log": req.LogPath,
|
"log": req.LogPath,
|
||||||
"debug directory": req.DebugDirectory,
|
"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)
|
return nil, fmt.Errorf("notarius %s path must be absolute", label)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if filepath.Clean(req.ReceiptPath) == filepath.Clean(req.LogPath) {
|
if filepath.Clean(req.ReportPath) == filepath.Clean(req.LogPath) {
|
||||||
return nil, fmt.Errorf("notarius receipt and log paths must be different")
|
return nil, fmt.Errorf("notarius report and log paths must be different")
|
||||||
}
|
}
|
||||||
references := make([]ReferenceBinding, 0, len(req.References))
|
references := make([]ReferenceBinding, 0, len(req.References))
|
||||||
selectors := make(map[string]struct{}, 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 {
|
if err := requireDirectory(req.WorkingDirectory); err != nil {
|
||||||
return nil, fmt.Errorf("validate notarius working directory: %w", err)
|
return nil, fmt.Errorf("validate notarius working directory: %w", err)
|
||||||
}
|
}
|
||||||
if err := validateLogDestination(req.ReceiptPath); err != nil {
|
if err := validateLogDestination(req.ReportPath); err != nil {
|
||||||
return nil, fmt.Errorf("validate notarius receipt path: %w", err)
|
return nil, fmt.Errorf("validate notarius report path: %w", err)
|
||||||
}
|
}
|
||||||
if err := validateLogDestination(req.LogPath); err != nil {
|
if err := validateLogDestination(req.LogPath); err != nil {
|
||||||
return nil, fmt.Errorf("validate notarius log path: %w", err)
|
return nil, fmt.Errorf("validate notarius log path: %w", err)
|
||||||
|
|||||||
@@ -15,109 +15,6 @@ import (
|
|||||||
configkit "go.maximumdirect.net/configkit"
|
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) {
|
func TestSubprocessRunnerMapsConfigOverlayToArgumentPair(t *testing.T) {
|
||||||
tests := []struct {
|
tests := []struct {
|
||||||
name string
|
name string
|
||||||
@@ -138,7 +35,7 @@ func TestSubprocessRunnerMapsConfigOverlayToArgumentPair(t *testing.T) {
|
|||||||
var captured sharedsubprocess.RunRequest
|
var captured sharedsubprocess.RunRequest
|
||||||
runner := &SubprocessRunner{run: func(_ context.Context, processReq sharedsubprocess.RunRequest) (sharedsubprocess.RunResult, error) {
|
runner := &SubprocessRunner{run: func(_ context.Context, processReq sharedsubprocess.RunRequest) (sharedsubprocess.RunResult, error) {
|
||||||
captured = processReq
|
captured = processReq
|
||||||
writeValidBundleAndReceipt(t, req, false)
|
writeNativeCompletion(t, req, false)
|
||||||
return sharedsubprocess.RunResult{ExitCode: 0}, nil
|
return sharedsubprocess.RunResult{ExitCode: 0}, nil
|
||||||
}}
|
}}
|
||||||
|
|
||||||
@@ -147,7 +44,7 @@ func TestSubprocessRunnerMapsConfigOverlayToArgumentPair(t *testing.T) {
|
|||||||
}
|
}
|
||||||
flagIndex := -1
|
flagIndex := -1
|
||||||
for index, arg := range captured.Args {
|
for index, arg := range captured.Args {
|
||||||
if arg == "--config-overlay" {
|
if arg == "--overlay" {
|
||||||
flagIndex = index
|
flagIndex = index
|
||||||
break
|
break
|
||||||
}
|
}
|
||||||
@@ -158,8 +55,8 @@ func TestSubprocessRunnerMapsConfigOverlayToArgumentPair(t *testing.T) {
|
|||||||
}
|
}
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
if flagIndex < 0 || flagIndex+2 >= len(captured.Args) || captured.Args[flagIndex+1] != test.value || captured.Args[flagIndex+2] != "--json" {
|
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 --json", captured.Args)
|
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 "} {
|
for _, mode := range []string{"AUTO", "invalid", " auto "} {
|
||||||
t.Run(mode, func(t *testing.T) {
|
t.Run(mode, func(t *testing.T) {
|
||||||
req := validRunRequest(t)
|
req := validRunRequest(t)
|
||||||
req.ChunkCache = mode
|
req.Cache = &mode
|
||||||
started := false
|
started := false
|
||||||
runner := &SubprocessRunner{run: func(context.Context, sharedsubprocess.RunRequest) (sharedsubprocess.RunResult, error) {
|
runner := &SubprocessRunner{run: func(context.Context, sharedsubprocess.RunRequest) (sharedsubprocess.RunResult, error) {
|
||||||
started = true
|
started = true
|
||||||
return sharedsubprocess.RunResult{}, nil
|
return sharedsubprocess.RunResult{}, nil
|
||||||
}}
|
}}
|
||||||
_, err := runner.Run(context.Background(), req)
|
_, 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)
|
t.Fatalf("Run() error = %v, want chunk cache validation failure", err)
|
||||||
}
|
}
|
||||||
if started {
|
if started {
|
||||||
@@ -201,7 +98,7 @@ func TestSubprocessRunnerForwardsLoadedCredentialWithoutRereadingEnvironment(t *
|
|||||||
var captured sharedsubprocess.RunRequest
|
var captured sharedsubprocess.RunRequest
|
||||||
runner := &SubprocessRunner{run: func(_ context.Context, processReq sharedsubprocess.RunRequest) (sharedsubprocess.RunResult, error) {
|
runner := &SubprocessRunner{run: func(_ context.Context, processReq sharedsubprocess.RunRequest) (sharedsubprocess.RunResult, error) {
|
||||||
captured = processReq
|
captured = processReq
|
||||||
writeValidBundleAndReceipt(t, req, false)
|
writeNativeCompletion(t, req, false)
|
||||||
return sharedsubprocess.RunResult{ExitCode: 0}, nil
|
return sharedsubprocess.RunResult{ExitCode: 0}, nil
|
||||||
}}
|
}}
|
||||||
if _, err := runner.Run(context.Background(), req); err != 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)
|
t.Fatalf("sensitive environment names = %#v, want configured reference name", captured.SensitiveEnvNames)
|
||||||
}
|
}
|
||||||
wantArgs := []string{
|
wantArgs := []string{
|
||||||
"run", req.PipelineID, "--config", req.ConfigPath, "--input", req.InputPath,
|
"run", req.PipelineID, "--config", req.ConfigPath, "--input-file", req.InputPath,
|
||||||
"--output-dir", req.OutputRoot, "--json",
|
"--output-dir", req.OutputRoot, "--debug-dir", req.DebugDirectory, "--format", "json",
|
||||||
}
|
}
|
||||||
if !reflect.DeepEqual(captured.Args, wantArgs) {
|
if !reflect.DeepEqual(captured.Args, wantArgs) {
|
||||||
t.Fatalf("subprocess args = %#v, want %#v", 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
|
var captured sharedsubprocess.RunRequest
|
||||||
runner := &SubprocessRunner{run: func(_ context.Context, processReq sharedsubprocess.RunRequest) (sharedsubprocess.RunResult, error) {
|
runner := &SubprocessRunner{run: func(_ context.Context, processReq sharedsubprocess.RunRequest) (sharedsubprocess.RunResult, error) {
|
||||||
captured = processReq
|
captured = processReq
|
||||||
writeValidBundleAndReceipt(t, req, false)
|
writeNativeCompletion(t, req, false)
|
||||||
return sharedsubprocess.RunResult{ExitCode: 0}, nil
|
return sharedsubprocess.RunResult{ExitCode: 0}, nil
|
||||||
}}
|
}}
|
||||||
|
|
||||||
@@ -270,11 +167,12 @@ func TestSubprocessRunnerBuildsOrderedReferenceArguments(t *testing.T) {
|
|||||||
wantArgs := []string{
|
wantArgs := []string{
|
||||||
"run", req.PipelineID,
|
"run", req.PipelineID,
|
||||||
"--config", req.ConfigPath,
|
"--config", req.ConfigPath,
|
||||||
"--input", req.InputPath,
|
"--input-file", req.InputPath,
|
||||||
"--output-dir", req.OutputRoot,
|
"--output-dir", req.OutputRoot,
|
||||||
|
"--debug-dir", req.DebugDirectory,
|
||||||
"--reference", "party=" + req.References[0].Path,
|
"--reference", "party=" + req.References[0].Path,
|
||||||
"--reference", "npc-registry.extract.glossary=" + req.References[1].Path,
|
"--reference", "npc-registry.extract.glossary=" + req.References[1].Path,
|
||||||
"--json",
|
"--format", "json",
|
||||||
}
|
}
|
||||||
if !reflect.DeepEqual(captured.Args, wantArgs) {
|
if !reflect.DeepEqual(captured.Args, wantArgs) {
|
||||||
t.Fatalf("subprocess args = %#v, want %#v", 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"
|
const unrelated = "NARRATIO_NOTARIUS_UNRELATED_PARENT_KEY"
|
||||||
req := validRunRequest(t)
|
req := validRunRequest(t)
|
||||||
req.Credentials = []configkit.Secret{*loadTestCredential(t, envName, canary), *loadTestCredential(t, otherName, otherCanary)}
|
req.Credentials = []configkit.Secret{*loadTestCredential(t, envName, canary), *loadTestCredential(t, otherName, otherCanary)}
|
||||||
writeValidBundleAndReceipt(t, req, false)
|
writeNativeCompletion(t, req, false)
|
||||||
receiptFixture := req.ReceiptPath + ".fixture"
|
reportFixture := req.ReportPath + ".fixture"
|
||||||
data, err := os.ReadFile(req.ReceiptPath)
|
data, err := os.ReadFile(req.ReportPath)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatalf("ReadFile(receipt) error = %v", err)
|
t.Fatalf("ReadFile(report) error = %v", err)
|
||||||
}
|
}
|
||||||
var receipt map[string]any
|
var report map[string]any
|
||||||
if err := json.Unmarshal(data, &receipt); err != nil {
|
if err := json.Unmarshal(data, &report); err != nil {
|
||||||
t.Fatalf("decode receipt fixture: %v", err)
|
t.Fatalf("decode report fixture: %v", err)
|
||||||
}
|
}
|
||||||
receipt["credential_echo"] = canary + " " + otherCanary
|
report["credential_echo"] = canary + " " + otherCanary
|
||||||
writeJSONFile(t, receiptFixture, receipt)
|
writeJSONFile(t, reportFixture, report)
|
||||||
if err := os.Remove(req.ReceiptPath); err != nil {
|
if err := os.Remove(req.ReportPath); err != nil {
|
||||||
t.Fatalf("Remove(receipt) error = %v", err)
|
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 {
|
if err := os.Mkdir(captureDir, 0o755); err != nil {
|
||||||
t.Fatalf("Mkdir(capture) error = %v", err)
|
t.Fatalf("Mkdir(capture) error = %v", err)
|
||||||
}
|
}
|
||||||
@@ -389,12 +287,12 @@ if [ -n "$`+unrelated+`" ]; then
|
|||||||
fi
|
fi
|
||||||
printf '%s\n' "$`+envName+`" >&2
|
printf '%s\n' "$`+envName+`" >&2
|
||||||
printf '%s\n' "$`+otherName+`" >&2
|
printf '%s\n' "$`+otherName+`" >&2
|
||||||
cat "$NOTARIUS_RECEIPT_FIXTURE"
|
cat "$NOTARIUS_REPORT_FIXTURE"
|
||||||
`)
|
`)
|
||||||
req.Binary = script
|
req.Binary = script
|
||||||
t.Setenv("NOTARIUS_CAPTURE_DIR", captureDir)
|
t.Setenv("NOTARIUS_CAPTURE_DIR", captureDir)
|
||||||
t.Setenv("NOTARIUS_INHERITED_VALUE", "inherited-value")
|
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")
|
t.Setenv(unrelated, "unrelated-parent-credential")
|
||||||
|
|
||||||
if _, err := NewSubprocessRunner().Run(context.Background(), req); err != nil {
|
if _, err := NewSubprocessRunner().Run(context.Background(), req); err != nil {
|
||||||
@@ -404,12 +302,12 @@ cat "$NOTARIUS_RECEIPT_FIXTURE"
|
|||||||
assertTextFile(t, filepath.Join(captureDir, "environment"), "")
|
assertTextFile(t, filepath.Join(captureDir, "environment"), "")
|
||||||
assertRedactedCredentialFile(t, req.LogPath, canary)
|
assertRedactedCredentialFile(t, req.LogPath, canary)
|
||||||
assertRedactedCredentialFile(t, req.LogPath, otherCanary)
|
assertRedactedCredentialFile(t, req.LogPath, otherCanary)
|
||||||
receiptBytes, err := os.ReadFile(req.ReceiptPath)
|
reportBytes, err := os.ReadFile(req.ReportPath)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatalf("ReadFile(receipt) error = %v", err)
|
t.Fatalf("ReadFile(report) error = %v", err)
|
||||||
}
|
}
|
||||||
assertRedactedCredentialBytes(t, receiptBytes, canary)
|
assertRedactedCredentialBytes(t, reportBytes, canary)
|
||||||
assertRedactedCredentialBytes(t, receiptBytes, otherCanary)
|
assertRedactedCredentialBytes(t, reportBytes, otherCanary)
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestSubprocessRunnerRedactsCredentialOnProcessFailure(t *testing.T) {
|
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(), "<redacted>") {
|
if strings.Contains(err.Error(), canary) || strings.Contains(err.Error(), otherCanary) || !strings.Contains(err.Error(), "<redacted>") {
|
||||||
t.Fatal("process failure did not return redacted diagnostics")
|
t.Fatal("process failure did not return redacted diagnostics")
|
||||||
}
|
}
|
||||||
assertRedactedCredentialFile(t, req.ReceiptPath, canary)
|
assertRedactedCredentialFile(t, req.ReportPath, canary)
|
||||||
assertRedactedCredentialFile(t, req.ReceiptPath, otherCanary)
|
assertRedactedCredentialFile(t, req.ReportPath, otherCanary)
|
||||||
assertRedactedCredentialFile(t, req.LogPath, canary)
|
assertRedactedCredentialFile(t, req.LogPath, canary)
|
||||||
assertRedactedCredentialFile(t, req.LogPath, otherCanary)
|
assertRedactedCredentialFile(t, req.LogPath, otherCanary)
|
||||||
}
|
}
|
||||||
@@ -446,7 +344,7 @@ func TestSubprocessRunnerReturnsProcessFailuresWithoutParsingStdout(t *testing.T
|
|||||||
cancel bool
|
cancel bool
|
||||||
want string
|
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: "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"},
|
{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) {
|
if err == nil || !strings.Contains(err.Error(), test.want) {
|
||||||
t.Fatalf("Run() error = %v, want fragment %q", err, 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)
|
t.Fatalf("Run() parsed stdout after process failure: %v", err)
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestSubprocessRunnerReturnsSharedSubprocessErrorWithoutReadingReceipt(t *testing.T) {
|
func TestSubprocessRunnerReturnsSharedSubprocessErrorWithoutReadingReport(t *testing.T) {
|
||||||
req := validRunRequest(t)
|
req := validRunRequest(t)
|
||||||
if err := os.WriteFile(req.ReceiptPath, []byte("not json"), 0o644); err != nil {
|
if err := os.WriteFile(req.ReportPath, []byte("not json"), 0o644); err != nil {
|
||||||
t.Fatalf("WriteFile(receipt) error = %v", err)
|
t.Fatalf("WriteFile(report) error = %v", err)
|
||||||
}
|
}
|
||||||
wantErr := errors.New("process failed")
|
wantErr := errors.New("process failed")
|
||||||
runner := &SubprocessRunner{run: func(context.Context, sharedsubprocess.RunRequest) (sharedsubprocess.RunResult, error) {
|
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)
|
t.Fatalf("Run() error = %v, want wrapped process error", err)
|
||||||
}
|
}
|
||||||
if strings.Contains(err.Error(), "decode") {
|
if strings.Contains(err.Error(), "decode") {
|
||||||
t.Fatalf("Run() parsed receipt after failure: %v", err)
|
t.Fatalf("Run() parsed report 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)
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -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) {
|
func TestFakeRunnerCapturesRequestsAndHonorsContextAndError(t *testing.T) {
|
||||||
profile := "testing"
|
profile := "testing"
|
||||||
req := RunRequest{PipelineID: "pipeline", ConfigOverlay: &profile, References: []ReferenceBinding{{Selector: "party", Path: "/references/party.json"}}}
|
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{
|
return RunRequest{
|
||||||
Binary: "notarius", ConfigPath: configPath, PipelineID: "dnd-session", InputPath: inputPath,
|
Binary: "notarius", ConfigPath: configPath, PipelineID: "dnd-session", InputPath: inputPath,
|
||||||
OutputRoot: outputRoot, WorkingDirectory: workingDirectory,
|
OutputRoot: outputRoot, WorkingDirectory: workingDirectory,
|
||||||
ReceiptPath: filepath.Join(diagnostics, "receipt.json"), LogPath: filepath.Join(diagnostics, "stderr.log"),
|
ReportPath: filepath.Join(diagnostics, "report.json"), LogPath: filepath.Join(diagnostics, "stderr.log"),
|
||||||
Timeout: time.Second,
|
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) {
|
func writeNativeCompletion(t *testing.T, req RunRequest, _ bool) {
|
||||||
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) {
|
|
||||||
t.Helper()
|
t.Helper()
|
||||||
bundle := filepath.Join(req.OutputRoot, "notarius-run-1")
|
bundle := filepath.Join(req.OutputRoot, "bundle")
|
||||||
if err := os.MkdirAll(filepath.Join(bundle, "lanes"), 0o755); err != nil {
|
if err := os.MkdirAll(bundle, 0755); err != nil {
|
||||||
t.Fatalf("MkdirAll(bundle) error = %v", err)
|
t.Fatal(err)
|
||||||
}
|
}
|
||||||
for path, data := range map[string]string{
|
writeJSONFile(t, req.ReportPath, map[string]any{"pipeline": req.PipelineID, "artifact_count": 1, "output_directory": bundle})
|
||||||
"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
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func writeJSONFile(t *testing.T, path string, value any) {
|
func writeJSONFile(t *testing.T, path string, value any) {
|
||||||
t.Helper()
|
t.Helper()
|
||||||
data, err := json.Marshal(value)
|
data, err := json.Marshal(value)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatalf("json.Marshal() error = %v", err)
|
t.Fatal(err)
|
||||||
}
|
}
|
||||||
if err := os.WriteFile(path, data, 0o644); err != nil {
|
if err := os.WriteFile(path, data, 0644); err != nil {
|
||||||
t.Fatalf("WriteFile(%q) error = %v", path, err)
|
t.Fatal(err)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -39,7 +39,7 @@ var inheritedEnvironmentNames = map[string]struct{}{
|
|||||||
"GO_WANT_SERIATIM_HELPER": {},
|
"GO_WANT_SERIATIM_HELPER": {},
|
||||||
"GO_WANT_SUBPROCESS_HELPER": {},
|
"GO_WANT_SUBPROCESS_HELPER": {},
|
||||||
"NOTARIUS_CAPTURE_DIR": {},
|
"NOTARIUS_CAPTURE_DIR": {},
|
||||||
"NOTARIUS_RECEIPT_FIXTURE": {},
|
"NOTARIUS_REPORT_FIXTURE": {},
|
||||||
"SCRIPTORIUM_HELPER_RECORD_PATH": {},
|
"SCRIPTORIUM_HELPER_RECORD_PATH": {},
|
||||||
"SCRIPTORIUM_HELPER_MODE": {},
|
"SCRIPTORIUM_HELPER_MODE": {},
|
||||||
"SERIATIM_HELPER_RECORD_PATH": {},
|
"SERIATIM_HELPER_RECORD_PATH": {},
|
||||||
|
|||||||
@@ -28,10 +28,12 @@ scriptorium:
|
|||||||
enabled: false
|
enabled: false
|
||||||
for_each: party.characters
|
for_each: party.characters
|
||||||
prompt_id: dnd.character_meta
|
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
|
campaign := write("campaign.yml", `schema_version: maximumdirect.rpg.campaign.v1
|
||||||
inputs: {speakers_file: speakers.yml, autocorrect_file: autocorrect.yml, glossary_file: glossary.yml, party_file: party.yml}
|
id: campaign
|
||||||
|
references: {party: party.yml}
|
||||||
|
narratio: {inputs: {speakers_file: speakers.yml, glossary_file: glossary.yml}}
|
||||||
`)
|
`)
|
||||||
session := write("session.yml", `session_id: session
|
session := write("session.yml", `session_id: session
|
||||||
campaign: campaign
|
campaign: campaign
|
||||||
|
|||||||
@@ -181,7 +181,10 @@ func TestExecuteStagesBoundedCompositionUsesOnlySelectedCollaborators(t *testing
|
|||||||
} {
|
} {
|
||||||
t.Run(test.name, func(t *testing.T) {
|
t.Run(test.name, func(t *testing.T) {
|
||||||
cfg := testConfig(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)
|
test.configure(cfg)
|
||||||
}
|
}
|
||||||
plan := mustBoundedPlan(t, test.stageName, test.stageName)
|
plan := mustBoundedPlan(t, test.stageName, test.stageName)
|
||||||
@@ -192,7 +195,7 @@ func TestExecuteStagesBoundedCompositionUsesOnlySelectedCollaborators(t *testing
|
|||||||
|
|
||||||
var captured *stage.Env
|
var captured *stage.Env
|
||||||
plan.stages = []stage.Stage{collaboratorProbeStage{name: test.stageName, captured: &captured}}
|
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 {
|
if err != nil {
|
||||||
t.Fatalf("executeStages() error = %v", err)
|
t.Fatalf("executeStages() error = %v", err)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -38,21 +38,21 @@ scriptorium:
|
|||||||
enabled: false
|
enabled: false
|
||||||
for_each: party.characters
|
for_each: party.characters
|
||||||
prompt_id: meta
|
prompt_id: meta
|
||||||
output_path_pattern: artifacts/{character_id}/meta.md
|
output_path_pattern: artifacts/{character_id}-meta.md
|
||||||
inputs:
|
inputs:
|
||||||
players: {source: narratio.input.players, required: true}
|
players: {source: narratio.input.players, required: true}
|
||||||
character_note:
|
character_note:
|
||||||
enabled: false
|
enabled: false
|
||||||
for_each: party.characters
|
for_each: party.characters
|
||||||
prompt_id: note
|
prompt_id: note
|
||||||
output_path_pattern: artifacts/{character_id}/note.md
|
output_path_pattern: artifacts/{character_id}-note.md
|
||||||
inputs:
|
inputs:
|
||||||
meta: {source: narratio.member_artifact.character_meta, required: true}
|
meta: {source: narratio.member_artifact.character_meta, required: true}
|
||||||
member_vars:
|
member_vars:
|
||||||
character_name: character.name
|
character_name: character.name
|
||||||
`)
|
`)
|
||||||
campaignPath := filepath.Join(dir, "campaign.yml")
|
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")
|
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")
|
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")
|
sessionPath := filepath.Join(dir, "session.yml")
|
||||||
|
|||||||
@@ -149,7 +149,6 @@ campaign: sample-campaign
|
|||||||
inputs:
|
inputs:
|
||||||
audio_dir: ./audio
|
audio_dir: ./audio
|
||||||
speakers_file: ./speakers.yml
|
speakers_file: ./speakers.yml
|
||||||
autocorrect_file: ./autocorrect.yml
|
|
||||||
glossary_file: ./glossary.yml
|
glossary_file: ./glossary.yml
|
||||||
`
|
`
|
||||||
if err := os.WriteFile(pipelinePath, []byte(pipelineYAML), 0o644); err != nil {
|
if err := os.WriteFile(pipelinePath, []byte(pipelineYAML), 0o644); err != nil {
|
||||||
@@ -212,7 +211,7 @@ inputs:
|
|||||||
}
|
}
|
||||||
foundReference := false
|
foundReference := false
|
||||||
if err := filepath.WalkDir(workRoot, func(path string, entry os.DirEntry, walkErr error) error {
|
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
|
return walkErr
|
||||||
}
|
}
|
||||||
data, err := os.ReadFile(path)
|
data, err := os.ReadFile(path)
|
||||||
@@ -259,7 +258,6 @@ campaign: sample-campaign
|
|||||||
inputs:
|
inputs:
|
||||||
audio_dir: ./audio
|
audio_dir: ./audio
|
||||||
speakers_file: ./speakers.yml
|
speakers_file: ./speakers.yml
|
||||||
autocorrect_file: ./autocorrect.yml
|
|
||||||
glossary_file: ./glossary.yml
|
glossary_file: ./glossary.yml
|
||||||
`
|
`
|
||||||
if err := os.WriteFile(pipelinePath, []byte(pipelineYAML), 0o644); err != nil {
|
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)
|
pipelinePath, campaignPath, sessionPath := writeValidConfigFiles(t, workspaceRoot)
|
||||||
campaignRoot := filepath.Dir(filepath.Dir(campaignPath))
|
campaignRoot := filepath.Dir(filepath.Dir(campaignPath))
|
||||||
otherDir := filepath.Join(campaignRoot, "icewind")
|
otherDir := filepath.Join(campaignRoot, "icewind")
|
||||||
mustWriteTestFile(t, filepath.Join(otherDir, "campaign.yml"), `campaign_id: icewind
|
mustWriteTestFile(t, filepath.Join(otherDir, "campaign.yml"), `schema_version: maximumdirect.rpg.campaign.v1
|
||||||
inputs:
|
id: icewind
|
||||||
speakers_file: ./speakers.yml
|
references:
|
||||||
autocorrect_file: ./autocorrect.yml
|
party: ./party.yml
|
||||||
glossary_file: ./glossary.yml
|
narratio:
|
||||||
party_file: ./party.yml
|
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, "speakers.yml"), "match:\n - speaker: Alice\n match: [\"alice\"]\n")
|
||||||
mustWriteTestFile(t, filepath.Join(otherDir, "autocorrect.yml"), "[]\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, "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")
|
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, "speakers.yml"), "match:\n - speaker: Alice\n match: [\"alice\"]\n")
|
||||||
mustWriteTestFile(t, filepath.Join(campaignDir, "autocorrect.yml"), "[]\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(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")
|
mustWriteTestFile(t, filepath.Join(dir, "audio", "alice.flac"), "audio-bytes")
|
||||||
|
|
||||||
|
|||||||
@@ -60,62 +60,34 @@ func (s assertExtractionSourcesStage) Run(_ context.Context, env *stage.Env, m *
|
|||||||
return &stage.StageResult{}, nil
|
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)
|
r.requests = append(r.requests, req)
|
||||||
if r.failuresRemaining > 0 {
|
if r.failuresRemaining > 0 {
|
||||||
r.failuresRemaining--
|
r.failuresRemaining--
|
||||||
return notarius.RunResult{}, errors.New("notarius execution failed")
|
return notarius.RunResult{}, errors.New("notarius execution failed")
|
||||||
}
|
}
|
||||||
externalRunID := fmt.Sprintf("notarius-run-%d", len(r.requests))
|
bundle := filepath.Join(req.OutputRoot, fmt.Sprintf("notarius-run-%d", len(r.requests)))
|
||||||
bundle := filepath.Join(req.OutputRoot, externalRunID)
|
lanes := filepath.Join(bundle, "lanes")
|
||||||
lanesDir := filepath.Join(bundle, "lanes")
|
if err := os.MkdirAll(lanes, 0755); err != nil {
|
||||||
if err := os.MkdirAll(lanesDir, 0o755); err != nil {
|
|
||||||
return notarius.RunResult{}, err
|
return notarius.RunResult{}, err
|
||||||
}
|
}
|
||||||
for path, content := range map[string]string{
|
for _, output := range r.cfg.Outputs {
|
||||||
filepath.Join(bundle, "index.json"): `{"manifest_file":"manifest.json"}`,
|
filename := output.LaneID + ".json"
|
||||||
filepath.Join(bundle, "manifest.json"): `{}`,
|
if err := os.WriteFile(filepath.Join(lanes, filename), []byte(`{"records":[]}`), 0644); err != nil {
|
||||||
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 {
|
|
||||||
return notarius.RunResult{}, err
|
return notarius.RunResult{}, err
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
keys := make([]string, 0, len(r.cfg.Outputs))
|
return notarius.RunResult{BundleRoot: bundle, Report: notarius.CompletionReport{Pipeline: req.PipelineID, ArtifactCount: len(r.cfg.Outputs), OutputDirectory: bundle}}, nil
|
||||||
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
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestExtractLifecycleDisabledThenEnabled(t *testing.T) {
|
func TestExtractLifecycleDisabledThenEnabled(t *testing.T) {
|
||||||
@@ -145,7 +117,7 @@ func TestExtractLifecycleDisabledThenEnabled(t *testing.T) {
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatalf("Load() error = %v", err)
|
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"])
|
t.Fatalf("extract record = %#v, want succeeded manifest-ready outputs", loaded.Stages["extract"])
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -170,10 +142,10 @@ func TestExtractLifecyclePrepareBindsVerifiedReferenceSnapshots(t *testing.T) {
|
|||||||
sourceID string
|
sourceID string
|
||||||
filename 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: "party", sourceID: artifactpolicy.SourceInputParty, filename: "party.yml"},
|
||||||
{selector: "players", sourceID: artifactpolicy.SourceInputPlayers, filename: "players.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]
|
request := runner.requests[0]
|
||||||
if len(request.References) != len(want) {
|
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)
|
t.Fatalf("summary=%#v requests=%#v analyze=%d", summary, runner.requests, analyzeRuns)
|
||||||
}
|
}
|
||||||
loaded := loadLifecycleManifest(t, cfg)
|
loaded := loadLifecycleManifest(t, cfg)
|
||||||
if got := len(loaded.Stages["extract"].Outputs); got != len(keys)+1 {
|
if got := len(loaded.Stages["extract"].Outputs); got != len(keys) {
|
||||||
t.Fatalf("extract outputs = %d, want %d lanes plus index", 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"])
|
t.Fatalf("changed party retained derived players snapshot path %q", thirdPaths["players"])
|
||||||
}
|
}
|
||||||
for selector, firstPath := range firstPaths {
|
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)
|
t.Fatalf("unchanged %s snapshot path = %q, want %q", selector, thirdPaths[selector], firstPath)
|
||||||
}
|
}
|
||||||
if _, err := os.Stat(firstPath); err != nil {
|
if _, err := os.Stat(firstPath); err != nil {
|
||||||
@@ -496,8 +468,8 @@ func TestExtractLifecycleCacheControlsAndSnapshotLossDoNotInvalidateCompleteResu
|
|||||||
if err := os.RemoveAll(cacheRoot); err != nil {
|
if err := os.RemoveAll(cacheRoot); err != nil {
|
||||||
t.Fatalf("RemoveAll(snapshot cache) error = %v", err)
|
t.Fatalf("RemoveAll(snapshot cache) error = %v", err)
|
||||||
}
|
}
|
||||||
cfg.Pipeline.Notarius.Resume = true
|
cache := "bypass"
|
||||||
cfg.Pipeline.Notarius.ChunkCache = "bypass"
|
cfg.Pipeline.Notarius.Cache = &cache
|
||||||
extractPlan, _ := BuildSingleStagePlan("extract")
|
extractPlan, _ := BuildSingleStagePlan("extract")
|
||||||
summary, err := executeStages(context.Background(), cfg, extractPlan, RunOptions{Env: env})
|
summary, err := executeStages(context.Background(), cfg, extractPlan, RunOptions{Env: env})
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -537,14 +509,14 @@ func TestAnalyzeOnlyLifecyclePreservesExtractionWithoutInvokingNotarius(t *testi
|
|||||||
|
|
||||||
func TestForcedArtifactRegenerationUsesOrdinaryExtractAndAnalyzePath(t *testing.T) {
|
func TestForcedArtifactRegenerationUsesOrdinaryExtractAndAnalyzePath(t *testing.T) {
|
||||||
cfg, env, runner := extractionLifecycleFixture(t, true)
|
cfg, env, runner := extractionLifecycleFixture(t, true)
|
||||||
cfg.Pipeline.Notarius.Resume = true
|
cache := "bypass"
|
||||||
cfg.Pipeline.Notarius.ChunkCache = "bypass"
|
cfg.Pipeline.Notarius.Cache = &cache
|
||||||
analyzeRuns := 0
|
analyzeRuns := 0
|
||||||
plan := extractionLifecyclePlan(t, &analyzeRuns)
|
plan := extractionLifecyclePlan(t, &analyzeRuns)
|
||||||
if _, err := executeStages(context.Background(), cfg, plan, RunOptions{Env: env, Force: true, SelectedArtifacts: []string{"session_recap"}}); err != nil {
|
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)
|
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)
|
t.Fatalf("forced path request=%#v analyze=%d", runner.requests, analyzeRuns)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -821,10 +793,6 @@ func TestExtractLifecycleRealConfigOverlaysSelectNotariusExplicitly(t *testing.T
|
|||||||
outputs:
|
outputs:
|
||||||
npc_registry:
|
npc_registry:
|
||||||
lane_id: 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()
|
closeErr := pipelineFile.Close()
|
||||||
if writeErr != nil || closeErr != nil {
|
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) {
|
{name: "configuration changed", mutate: func(_ *testing.T, cfg *config.Config, _ *manifest.Manifest) {
|
||||||
output := cfg.Pipeline.Notarius.Outputs["npc_registry"]
|
output := cfg.Pipeline.Notarius.Outputs["npc_registry"]
|
||||||
output.SchemaVersion = "v2"
|
output.Filename = "changed.json"
|
||||||
cfg.Pipeline.Notarius.Outputs["npc_registry"] = output
|
cfg.Pipeline.Notarius.Outputs["npc_registry"] = output
|
||||||
}},
|
}},
|
||||||
{name: "payload missing", mutate: func(t *testing.T, _ *config.Config, m *manifest.Manifest) {
|
{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) {
|
{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) {
|
t.Run(test.name, func(t *testing.T) {
|
||||||
@@ -1007,7 +975,7 @@ func TestExtractLifecycleUnsafeResumeErrorPreservesSuccess(t *testing.T) {
|
|||||||
"analyze": persisted.Stages["analyze"],
|
"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)
|
t.Fatalf("executeStages() error = %v, want unsafe resume failure", err)
|
||||||
}
|
}
|
||||||
afterManifest, err := store.Load(context.Background(), first.ManifestPath)
|
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 {
|
func configureLifecycleReferences(t *testing.T, cfg *config.Config) map[string]string {
|
||||||
t.Helper()
|
t.Helper()
|
||||||
cfg.Pipeline.Notarius.References = map[string]string{
|
cfg.Pipeline.Notarius.References = map[string]string{
|
||||||
"party": artifactpolicy.SourceInputParty,
|
"party": artifactpolicy.SourceInputParty, "players": artifactpolicy.SourceInputPlayers,
|
||||||
"players": artifactpolicy.SourceInputPlayers,
|
"glossary": artifactpolicy.SourceInputGlossaryCombined, "spells": artifactpolicy.SourceInputGlossaryCombined,
|
||||||
"glossary": artifactpolicy.SourceInputGlossaryCampaign,
|
|
||||||
"spells": artifactpolicy.SourceInputSpellCatalog,
|
|
||||||
}
|
}
|
||||||
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{
|
return map[string]string{
|
||||||
artifactpolicy.SourceInputParty: filepath.Join(filepath.Dir(cfg.CampaignPath), "party.yml"),
|
artifactpolicy.SourceInputParty: filepath.Join(filepath.Dir(cfg.CampaignPath), "party.yml"),
|
||||||
artifactpolicy.SourceInputPlayers: filepath.Join(filepath.Dir(cfg.CampaignPath), "players.yml"),
|
artifactpolicy.SourceInputPlayers: filepath.Join(filepath.Dir(cfg.CampaignPath), "players.yml"),
|
||||||
artifactpolicy.SourceInputGlossaryCampaign: filepath.Join(filepath.Dir(cfg.CampaignPath), "glossary.yml"),
|
artifactpolicy.SourceInputGlossaryCombined: filepath.Join(filepath.Dir(cfg.CampaignPath), "glossary.yml"),
|
||||||
artifactpolicy.SourceInputSpellCatalog: spellPath,
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1129,16 +1085,16 @@ func lifecycleReferencePaths(request notarius.RunRequest) map[string]string {
|
|||||||
|
|
||||||
func lifecycleDndOutputs() map[string]config.NotariusOutputConfig {
|
func lifecycleDndOutputs() map[string]config.NotariusOutputConfig {
|
||||||
return 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"},
|
"item_registry": {LaneID: "item-registry"},
|
||||||
"npc_registry": {LaneID: "npc-registry", MediaType: "application/json", SchemaID: "notarius.dnd.npc_registry", SchemaVersion: "v1", ModuleKey: "dnd/npc-registry"},
|
"npc_registry": {LaneID: "npc-registry"},
|
||||||
"location_registry": {LaneID: "location-registry", MediaType: "application/json", SchemaID: "notarius.dnd.location_registry", SchemaVersion: "v1", ModuleKey: "dnd/location-registry"},
|
"location_registry": {LaneID: "location-registry"},
|
||||||
"scene_descriptions": {LaneID: "scene-descriptions", MediaType: "application/json", SchemaID: "notarius.dnd.scene_descriptions", SchemaVersion: "v1", ModuleKey: "dnd/scene-descriptions"},
|
"scene_descriptions": {LaneID: "scene-descriptions"},
|
||||||
"item_occurrences": {LaneID: "item-occurrences", MediaType: "application/json", SchemaID: "notarius.dnd.item_occurrences", SchemaVersion: "v1", ModuleKey: "dnd/item-occurrences"},
|
"item_occurrences": {LaneID: "item-occurrences"},
|
||||||
"spells": {LaneID: "spells", MediaType: "application/json", SchemaID: "notarius.dnd.spells", SchemaVersion: "v1", ModuleKey: "dnd/spells"},
|
"spells": {LaneID: "spells"},
|
||||||
"combat_turns": {LaneID: "combat-turns", MediaType: "application/json", SchemaID: "notarius.dnd.combat_turns", SchemaVersion: "v1", ModuleKey: "dnd/combat-turns"},
|
"combat_turns": {LaneID: "combat-turns"},
|
||||||
"npc_occurrences": {LaneID: "npc-occurrences", MediaType: "application/json", SchemaID: "notarius.dnd.npc_occurrences", SchemaVersion: "v1", ModuleKey: "dnd/npc-occurrences"},
|
"npc_occurrences": {LaneID: "npc-occurrences"},
|
||||||
"location_occurrences": {LaneID: "location-occurrences", MediaType: "application/json", SchemaID: "notarius.dnd.location_occurrences", SchemaVersion: "v1", ModuleKey: "dnd/location-occurrences"},
|
"location_occurrences": {LaneID: "location-occurrences"},
|
||||||
"enemy_events": {LaneID: "enemy-events", MediaType: "application/json", SchemaID: "notarius.dnd.enemy_events", SchemaVersion: "v1", ModuleKey: "dnd/enemy-events"},
|
"enemy_events": {LaneID: "enemy-events"},
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1163,8 +1119,7 @@ func extractionLifecycleFixture(t *testing.T, enabled bool) (*config.Config, *st
|
|||||||
Timeout: "45m", WorkingDirectory: workingDirectory,
|
Timeout: "45m", WorkingDirectory: workingDirectory,
|
||||||
Outputs: map[string]config.NotariusOutputConfig{
|
Outputs: map[string]config.NotariusOutputConfig{
|
||||||
"npc_registry": {
|
"npc_registry": {
|
||||||
LaneID: "npc-registry", MediaType: "application/json", SchemaID: "notarius.dnd.npc_registry",
|
LaneID: "npc-registry",
|
||||||
SchemaVersion: "v1", ModuleKey: "dnd/npc-registry",
|
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -23,7 +23,7 @@ func TestPreparedGlossaryAliasPresence(t *testing.T) {
|
|||||||
pipeline, campaign, session := writeValidConfigFiles(t, t.TempDir())
|
pipeline, campaign, session := writeValidConfigFiles(t, t.TempDir())
|
||||||
entry := "{id: watch, name: Watch, category: person" + aliases + "}"
|
entry := "{id: watch, name: Watch, category: person" + aliases + "}"
|
||||||
if mode == "file" {
|
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 {
|
} else {
|
||||||
mustWriteTestFile(t, session, "session_id: 2026-05-03\ninputs:\n audio_dir: ./audio\n glossary_file: null\n glossary: {entries: ["+entry+"]}\n")
|
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 {
|
if err != nil {
|
||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
}
|
}
|
||||||
var doc map[string]struct {
|
var doc struct {
|
||||||
Entries []map[string]any `yaml:"entries"`
|
Collections map[string]struct {
|
||||||
|
Entries []map[string]any `yaml:"entries"`
|
||||||
|
} `yaml:"collections"`
|
||||||
}
|
}
|
||||||
if err := yaml.Unmarshal(data, &doc); err != nil {
|
if err := yaml.Unmarshal(data, &doc); err != nil {
|
||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
}
|
}
|
||||||
entries := doc["campaign"].Entries
|
entries := doc.Collections["campaign"].Entries
|
||||||
if len(entries) != 1 {
|
if len(entries) != 1 {
|
||||||
t.Fatalf("entries: %s", data)
|
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))
|
mustWriteTestFile(t, pipeline, string(body)+fmt.Sprintf("reference_catalog:\n %s:\n broken: %s\n", group.name, tc.value))
|
||||||
if tc.selected {
|
if tc.selected {
|
||||||
body, err = os.ReadFile(campaign)
|
body, err = os.ReadFile(session)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatal(err)
|
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{})
|
cfg, err := config.LoadWithSessionOptions(pipeline, campaign, session, config.SessionLoadOptions{})
|
||||||
if tc.invalid {
|
if tc.invalid {
|
||||||
|
|||||||
@@ -109,18 +109,20 @@ func TestExecuteSessionInitExplicitConfigWinsOverDefaults(t *testing.T) {
|
|||||||
|
|
||||||
explicitDir := t.TempDir()
|
explicitDir := t.TempDir()
|
||||||
explicitCampaign := filepath.Join(explicitDir, "campaign.yml")
|
explicitCampaign := filepath.Join(explicitDir, "campaign.yml")
|
||||||
if err := os.WriteFile(explicitCampaign, []byte(`campaign_id: explicit-campaign
|
if err := os.WriteFile(explicitCampaign, []byte(`schema_version: maximumdirect.rpg.campaign.v1
|
||||||
inputs:
|
id: explicit-campaign
|
||||||
speakers_file: ./speakers.yml
|
references:
|
||||||
autocorrect_file: ./autocorrect.yml
|
party: ./party.yml
|
||||||
glossary_file: ./glossary.yml
|
narratio:
|
||||||
party_file: ./party.yml
|
inputs:
|
||||||
|
speakers_file: ./speakers.yml
|
||||||
|
glossary_file: ./glossary.yml
|
||||||
`), 0o644); err != nil {
|
`), 0o644); err != nil {
|
||||||
t.Fatalf("write explicit campaign: %v", err)
|
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, "speakers.yml"), "match:\n - speaker: Alice\n match: [\"alice\"]\n")
|
||||||
mustWriteTestFile(t, filepath.Join(explicitDir, "autocorrect.yml"), "[]\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, "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")
|
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) {
|
func TestExecuteLocksAddListAndRemoveUseIndependentObjects(t *testing.T) {
|
||||||
workspaceRoot := t.TempDir()
|
workspaceRoot := t.TempDir()
|
||||||
pipelinePath, campaignPath, sessionPath := writeValidConfigFiles(t, workspaceRoot)
|
pipelinePath, campaignPath, sessionPath := writeValidConfigFiles(t, workspaceRoot)
|
||||||
@@ -1273,10 +1218,6 @@ func addExtractionOutputToPipeline(t *testing.T, pipelinePath string) {
|
|||||||
outputs:
|
outputs:
|
||||||
encounters:
|
encounters:
|
||||||
lane_id: 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 {
|
if err := os.WriteFile(pipelinePath, data, 0o644); err != nil {
|
||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
@@ -1289,21 +1230,14 @@ func addExtractionOutputToPipeline(t *testing.T, pipelinePath string) {
|
|||||||
func writeOperatorExtractionManifest(t *testing.T, workspaceRoot string) string {
|
func writeOperatorExtractionManifest(t *testing.T, workspaceRoot string) string {
|
||||||
t.Helper()
|
t.Helper()
|
||||||
paths := artifacts.NewLocalStore(workspaceRoot).SessionPathsFor("sample-campaign", "2026-05-03")
|
paths := artifacts.NewLocalStore(workspaceRoot).SessionPathsFor("sample-campaign", "2026-05-03")
|
||||||
bundleRoot := filepath.Join(paths.ArtifactsDir, "notarius", "extract-run-1")
|
lanePath := filepath.Join(paths.ArtifactsDir, "encounters.json")
|
||||||
lanePath := filepath.Join(bundleRoot, "lanes", "encounters.json")
|
|
||||||
indexPath := filepath.Join(bundleRoot, "index.json")
|
|
||||||
trimmedPath := filepath.Join(paths.Root, filepath.FromSlash(artifacts.TranscriptPathFinalTrimmed))
|
trimmedPath := filepath.Join(paths.Root, filepath.FromSlash(artifacts.TranscriptPathFinalTrimmed))
|
||||||
mustWriteTestFile(t, lanePath, `{"secret":"DO_NOT_PRINT"}`)
|
mustWriteTestFile(t, lanePath, `{"secret":"DO_NOT_PRINT"}`)
|
||||||
mustWriteTestFile(t, indexPath, `{"lanes":[]}`)
|
|
||||||
mustWriteTestFile(t, trimmedPath, `{"segments":[]}`)
|
mustWriteTestFile(t, trimmedPath, `{"segments":[]}`)
|
||||||
laneChecksum, err := artifacts.SHA256File(lanePath)
|
laneChecksum, err := artifacts.SHA256File(lanePath)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
}
|
}
|
||||||
indexChecksum, err := artifacts.SHA256File(indexPath)
|
|
||||||
if err != nil {
|
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
m := manifest.New("2026-05-03", time.Now().UTC())
|
m := manifest.New("2026-05-03", time.Now().UTC())
|
||||||
m.Campaign = "sample-campaign"
|
m.Campaign = "sample-campaign"
|
||||||
trimmedChecksum, err := artifacts.SHA256File(trimmedPath)
|
trimmedChecksum, err := artifacts.SHA256File(trimmedPath)
|
||||||
@@ -1322,20 +1256,8 @@ func writeOperatorExtractionManifest(t *testing.T, workspaceRoot string) string
|
|||||||
}
|
}
|
||||||
m.Stages["extract"] = &manifest.StageRecord{
|
m.Stages["extract"] = &manifest.StageRecord{
|
||||||
Name: "extract", Status: manifest.StatusSucceeded,
|
Name: "extract", Status: manifest.StatusSucceeded,
|
||||||
Metadata: map[string]any{
|
Metadata: map[string]any{"narratio_run_id": "extract-run-1", "completion": map[string]any{"pipeline": "campaign.extract"}, "direct_input": input.Metadata()},
|
||||||
"narratio_run_id": "extract-run-1", "bundle_root": bundleRoot,
|
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"}}},
|
||||||
"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},
|
|
||||||
},
|
|
||||||
}
|
}
|
||||||
if err := (&manifest.LocalStore{}).Save(context.Background(), paths.ManifestPath, m); err != nil {
|
if err := (&manifest.LocalStore{}).Save(context.Background(), paths.ManifestPath, m); err != nil {
|
||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
|
|||||||
@@ -11,7 +11,7 @@ import (
|
|||||||
"golang.org/x/sys/unix"
|
"golang.org/x/sys/unix"
|
||||||
)
|
)
|
||||||
|
|
||||||
func TestInspectStableInputsRejectsSpellCatalogFIFO(t *testing.T) {
|
func TestInspectStableInputsRejectsSpeakersFIFO(t *testing.T) {
|
||||||
root := t.TempDir()
|
root := t.TempDir()
|
||||||
sourcePath := filepath.Join(root, "spells.fifo")
|
sourcePath := filepath.Join(root, "spells.fifo")
|
||||||
if err := unix.Mkfifo(sourcePath, 0o644); err != nil {
|
if err := unix.Mkfifo(sourcePath, 0o644); err != nil {
|
||||||
@@ -19,16 +19,16 @@ func TestInspectStableInputsRejectsSpellCatalogFIFO(t *testing.T) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
cfg := &config.Config{StableInputs: config.ResolvedStableInputs{
|
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) {
|
for _, check := range inspectStableInputs(cfg) {
|
||||||
if check.Name != "spell_catalog" {
|
if check.Name != "speakers" {
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
if check.Err == nil || !strings.Contains(check.Err.Error(), "not a regular file") {
|
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
|
return
|
||||||
}
|
}
|
||||||
t.Fatal("spell catalog inspection result was not reported")
|
t.Fatal("speakers inspection result was not reported")
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -170,7 +170,6 @@ campaign: sample-campaign
|
|||||||
inputs:
|
inputs:
|
||||||
audio_dir: ./audio
|
audio_dir: ./audio
|
||||||
speakers_file: ./speakers.yml
|
speakers_file: ./speakers.yml
|
||||||
autocorrect_file: ./autocorrect.yml
|
|
||||||
glossary_file: ./glossary.yml
|
glossary_file: ./glossary.yml
|
||||||
`
|
`
|
||||||
if err := os.WriteFile(pipelinePath, []byte(pipelineYAML), 0o644); err != nil {
|
if err := os.WriteFile(pipelinePath, []byte(pipelineYAML), 0o644); err != nil {
|
||||||
|
|||||||
@@ -21,7 +21,7 @@ import (
|
|||||||
func TestPreparedSessionPublishAndRemoteLoad(t *testing.T) {
|
func TestPreparedSessionPublishAndRemoteLoad(t *testing.T) {
|
||||||
ctx := context.Background()
|
ctx := context.Background()
|
||||||
pipelinePath, campaignPath, sessionPath := writeValidConfigFiles(t, t.TempDir())
|
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")
|
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, 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")
|
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)
|
prefix := artifacts.S3SessionPrefix("dnd", m.Campaign, m.SessionID)
|
||||||
key := artifacts.S3RunRelativeDestinationKey(artifacts.S3RunPrefix(prefix, m.RunID), "prepare/inputs/session.yml")
|
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)
|
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"} {
|
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 {
|
if received.Session.Title != "Published title" || received.SessionSource.S3Key != key {
|
||||||
t.Fatalf("remote session = %#v, source=%#v", received.Session, received.SessionSource)
|
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") {
|
if got := received.StableInputs.SpeakersFile; got.Source != "session_config" || got.Path != filepath.Join(filepath.Dir(campaignPath), "speakers.yml") {
|
||||||
t.Fatalf("receiving campaign speakers = %#v", got)
|
t.Fatalf("receiving session speakers = %#v", got)
|
||||||
}
|
}
|
||||||
current, err := discoverRemoteCurrentState(ctx, received, fake)
|
current, err := discoverRemoteCurrentState(ctx, received, fake)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
|
|||||||
@@ -73,10 +73,6 @@ notarius:
|
|||||||
outputs:
|
outputs:
|
||||||
npc_registry:
|
npc_registry:
|
||||||
lane_id: 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:
|
notification:
|
||||||
mode: noop
|
mode: noop
|
||||||
`)
|
`)
|
||||||
@@ -85,7 +81,6 @@ campaign: sample-campaign
|
|||||||
inputs:
|
inputs:
|
||||||
audio_dir: ./audio
|
audio_dir: ./audio
|
||||||
speakers_file: ./speakers.yml
|
speakers_file: ./speakers.yml
|
||||||
autocorrect_file: ./autocorrect.yml
|
|
||||||
glossary_file: ./glossary.yml
|
glossary_file: ./glossary.yml
|
||||||
`)
|
`)
|
||||||
|
|
||||||
@@ -154,7 +149,7 @@ inputs:
|
|||||||
}
|
}
|
||||||
assertNoProviderValues(t, stdout.Bytes(), stderr.Bytes())
|
assertNoProviderValues(t, stdout.Bytes(), stderr.Bytes())
|
||||||
if err := filepath.WalkDir(workRoot, func(path string, entry os.DirEntry, walkErr error) error {
|
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
|
return walkErr
|
||||||
}
|
}
|
||||||
data, err := os.ReadFile(path)
|
data, err := os.ReadFile(path)
|
||||||
@@ -233,6 +228,14 @@ func TestProviderCredentialProcessFixture(t *testing.T) {
|
|||||||
_, _ = os.Stderr.WriteString(sharedProviderKey + "\n")
|
_, _ = os.Stderr.WriteString(sharedProviderKey + "\n")
|
||||||
os.Exit(0)
|
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] {
|
switch args[0] {
|
||||||
case "process", "preflight":
|
case "process", "preflight":
|
||||||
if os.Getenv(auditaOnlyName) != auditaOnlyKey {
|
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 {
|
if err := os.MkdirAll(filepath.Join(bundle, "lanes"), 0o755); err != nil {
|
||||||
os.Exit(2)
|
os.Exit(2)
|
||||||
}
|
}
|
||||||
for name, value := range map[string]string{
|
if err := os.WriteFile(filepath.Join(bundle, "lanes", "npc-registry.json"), []byte(`{"records":[]}`), 0o644); err != nil {
|
||||||
"manifest.json": "{}", "rejected.json": `{"rejected":[]}`,
|
os.Exit(2)
|
||||||
"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)
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
_, _ = 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:
|
default:
|
||||||
os.Exit(2)
|
os.Exit(2)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -442,6 +442,8 @@ func seedRestoreObject(store *storage.FakeBackend, key string, data []byte) {
|
|||||||
source := artifacts.ConfiguredArtifactSourceID("test")
|
source := artifacts.ConfiguredArtifactSourceID("test")
|
||||||
if destination == artifacts.S3RunSessionManifestKey(sessionPrefix, pointer.RunID) {
|
if destination == artifacts.S3RunSessionManifestKey(sessionPrefix, pointer.RunID) {
|
||||||
typeID, source = artifacts.RemoteArtifactTypeSessionManifest, "session.manifest"
|
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/") {
|
} else if relative := strings.TrimPrefix(destination, runPrefix); strings.HasPrefix(relative, "artifacts/") || strings.HasPrefix(relative, "published/artifacts/") {
|
||||||
name := strings.TrimPrefix(relative, "published/")
|
name := strings.TrimPrefix(relative, "published/")
|
||||||
name = strings.TrimSuffix(strings.TrimPrefix(name, "artifacts/"), filepath.Ext(name))
|
name = strings.TrimSuffix(strings.TrimPrefix(name, "artifacts/"), filepath.Ext(name))
|
||||||
|
|||||||
@@ -3,9 +3,9 @@ package app
|
|||||||
import (
|
import (
|
||||||
"bytes"
|
"bytes"
|
||||||
"context"
|
"context"
|
||||||
|
"encoding/json"
|
||||||
"os"
|
"os"
|
||||||
"path/filepath"
|
"path/filepath"
|
||||||
"strings"
|
|
||||||
"testing"
|
"testing"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
@@ -24,7 +24,7 @@ func TestRestoreThenForcedAnalyzeUsesRestoredDurableState(t *testing.T) {
|
|||||||
cfg, sessionPrefix, manifestKey, runIDKey := seedRestoreCommittedState(t, fake, pipelinePath, campaignPath, sessionPath)
|
cfg, sessionPrefix, manifestKey, runIDKey := seedRestoreCommittedState(t, fake, pipelinePath, campaignPath, sessionPath)
|
||||||
seedRestoreObject(fake, runIDKey, []byte("20260519T010203Z-a1b2c3d4\n"))
|
seedRestoreObject(fake, runIDKey, []byte("20260519T010203Z-a1b2c3d4\n"))
|
||||||
seedRestoreObject(fake, manifestKey, restoreWorkflowManifestJSON(t, cfg.Session.SessionID, cfg.Session.Campaign))
|
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"))
|
seedRestoreObject(fake, sessionPrefix+"artifacts/session_recap.md", []byte("# restored recap\n"))
|
||||||
|
|
||||||
executeRestore := restoreCommandExecutor(fake)
|
executeRestore := restoreCommandExecutor(fake)
|
||||||
@@ -56,7 +56,7 @@ func TestRestoreThenForcedAnalyzeUsesRestoredDurableState(t *testing.T) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
sessionRoot := artifacts.SessionWorkDirForCampaign(workspaceRoot, cfg.Session.Campaign, cfg.Session.SessionID)
|
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")
|
mustReadEquals(t, filepath.Join(sessionRoot, "artifacts", "session_recap.md"), "# restored recap\n")
|
||||||
|
|
||||||
manifestStore := &manifest.LocalStore{}
|
manifestStore := &manifest.LocalStore{}
|
||||||
@@ -188,18 +188,19 @@ previous_session_id: 2026-04-26
|
|||||||
t.Fatalf("load restored manifest: %v", err)
|
t.Fatalf("load restored manifest: %v", err)
|
||||||
}
|
}
|
||||||
setCurrentBuiltInEvidence(t, localManifest, "trim", artifacts.TranscriptOutputKindFinalTrimmed, artifacts.ArtifactTranscriptFinalTrimmed, filepath.Join(sessionRoot, "transcripts", "final.trimmed.json"))
|
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 {
|
if err := (&manifest.LocalStore{}).Save(context.Background(), filepath.Join(sessionRoot, "manifest.json"), localManifest); err != nil {
|
||||||
t.Fatalf("save manifest evidence: %v", err)
|
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 {
|
if err != nil {
|
||||||
t.Fatalf("read restored previous manifest: %v", err)
|
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))
|
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{}
|
scriptoriumFake := &scriptorium.FakeRunner{}
|
||||||
objectStoreConstructed := false
|
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") {
|
if got := req.InputPaths["transcript"]; got != filepath.Join(sessionRoot, "transcripts", "final.trimmed.json") {
|
||||||
t.Fatalf("transcript input = %q, want trimmed transcript path", got)
|
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)
|
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 {
|
for i, stageName := range stages {
|
||||||
m.MarkStageSucceeded(stageName, now.Add(time.Duration(i+1)*time.Minute), nil)
|
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"))
|
setAppAnalyzeEvidence(m, "session_recap", "artifacts/session_recap.md", []byte("# restored recap\n"))
|
||||||
path := filepath.Join(t.TempDir(), "manifest.json")
|
path := filepath.Join(t.TempDir(), "manifest.json")
|
||||||
if err := store.Save(context.Background(), path, m); err != nil {
|
if err := store.Save(context.Background(), path, m); err != nil {
|
||||||
|
|||||||
@@ -9,6 +9,7 @@ import (
|
|||||||
"testing"
|
"testing"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
|
"gitea.maximumdirect.net/eric/narratio/internal/artifacts"
|
||||||
"gitea.maximumdirect.net/eric/narratio/internal/config"
|
"gitea.maximumdirect.net/eric/narratio/internal/config"
|
||||||
"gitea.maximumdirect.net/eric/narratio/internal/manifest"
|
"gitea.maximumdirect.net/eric/narratio/internal/manifest"
|
||||||
"gitea.maximumdirect.net/eric/narratio/internal/stage"
|
"gitea.maximumdirect.net/eric/narratio/internal/stage"
|
||||||
@@ -136,7 +137,11 @@ func TestPlannedStageModelMatchesStageExecution(t *testing.T) {
|
|||||||
t.Run(test.name, func(t *testing.T) {
|
t.Run(test.name, func(t *testing.T) {
|
||||||
at := time.Date(2026, time.May, 3, 12, 0, 0, 0, time.UTC)
|
at := time.Date(2026, time.May, 3, 12, 0, 0, 0, time.UTC)
|
||||||
cfg := testConfig(t)
|
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}
|
cfg.Pipeline.Notarius = &config.NotariusConfig{Enabled: test.result == nil || test.result.Disposition != stage.StageDispositionSkipped}
|
||||||
planned := manifest.New("2026-05-03", at)
|
planned := manifest.New("2026-05-03", at)
|
||||||
executed := manifest.New("2026-05-03", at)
|
executed := manifest.New("2026-05-03", at)
|
||||||
@@ -164,6 +169,7 @@ func TestPlannedStageModelMatchesStageExecution(t *testing.T) {
|
|||||||
cfg: cfg,
|
cfg: cfg,
|
||||||
opts: RunOptions{Force: test.force},
|
opts: RunOptions{Force: test.force},
|
||||||
identity: invocationIdentity{RunID: "20260503T120000Z-a1b2c3d4", LocalWorkDir: workDir},
|
identity: invocationIdentity{RunID: "20260503T120000Z-a1b2c3d4", LocalWorkDir: workDir},
|
||||||
|
paths: paths,
|
||||||
env: &stage.Env{Config: cfg},
|
env: &stage.Env{Config: cfg},
|
||||||
manifestStore: &manifest.LocalStore{},
|
manifestStore: &manifest.LocalStore{},
|
||||||
manifestPath: filepath.Join(t.TempDir(), "manifest.json"),
|
manifestPath: filepath.Join(t.TempDir(), "manifest.json"),
|
||||||
|
|||||||
@@ -301,16 +301,15 @@ func TestExecuteStagesBindsResolvedConfigToEnvironment(t *testing.T) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func TestExecuteStagesComposesNotariusOnlyForEnabledExtraction(t *testing.T) {
|
func TestExecuteStagesComposesNotariusOnlyForEnabledExtraction(t *testing.T) {
|
||||||
cfg := testConfig(t)
|
cfg, env, _ := extractionLifecycleFixture(t, true)
|
||||||
cfg.Pipeline.Notarius = &config.NotariusConfig{Enabled: true}
|
|
||||||
captured := false
|
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 {
|
if err != nil {
|
||||||
t.Fatalf("executeStages() error = %v", err)
|
t.Fatalf("executeStages() error = %v", err)
|
||||||
}
|
}
|
||||||
if !captured {
|
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)}}) {
|
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, 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, "speakers.yml"), "alice: alice.flac\n")
|
||||||
mustWriteFile(t, filepath.Join(cfgDir, "autocorrect.yml"), "[]\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, "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")
|
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"))
|
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,
|
ConfigPath: campaignPath,
|
||||||
Source: "campaign_config",
|
Source: "campaign_config",
|
||||||
},
|
},
|
||||||
AutocorrectFile: config.ResolvedInputFile{
|
|
||||||
Path: "./autocorrect.yml",
|
|
||||||
ConfigPath: campaignPath,
|
|
||||||
Source: "campaign_config",
|
|
||||||
},
|
|
||||||
GlossaryFile: config.ResolvedInputFile{
|
GlossaryFile: config.ResolvedInputFile{
|
||||||
Path: "./glossary.yml",
|
Path: "./glossary.yml",
|
||||||
ConfigPath: campaignPath,
|
ConfigPath: campaignPath,
|
||||||
@@ -1472,10 +1466,9 @@ func testConfig(t *testing.T) *config.Config {
|
|||||||
SessionID: "2026-05-03",
|
SessionID: "2026-05-03",
|
||||||
Campaign: "sample-campaign",
|
Campaign: "sample-campaign",
|
||||||
Inputs: config.SessionInputsConfig{
|
Inputs: config.SessionInputsConfig{
|
||||||
AudioDir: "./audio",
|
AudioDir: "./audio",
|
||||||
SpeakersFile: "./speakers.yml",
|
SpeakersFile: "./speakers.yml",
|
||||||
AutocorrectFile: "./autocorrect.yml",
|
GlossaryFile: new(filepath.Join(cfgDir, "glossary.yml")),
|
||||||
GlossaryFile: new(filepath.Join(cfgDir, "glossary.yml")),
|
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
@@ -1493,19 +1486,19 @@ whisperx:
|
|||||||
notification:
|
notification:
|
||||||
mode: noop
|
mode: noop
|
||||||
`
|
`
|
||||||
campaignYAML := `campaign_id: sample-campaign
|
campaignYAML := `schema_version: maximumdirect.rpg.campaign.v1
|
||||||
inputs:
|
id: sample-campaign
|
||||||
speakers_file: ./speakers.yml
|
references: {party: ./party.yml}
|
||||||
autocorrect_file: ./autocorrect.yml
|
narratio:
|
||||||
glossary_file: ./glossary.yml
|
inputs:
|
||||||
party_file: ./party.yml
|
speakers_file: ./speakers.yml
|
||||||
|
glossary_file: ./glossary.yml
|
||||||
`
|
`
|
||||||
sessionYAML := `session_id: 2026-05-03
|
sessionYAML := `session_id: 2026-05-03
|
||||||
campaign: sample-campaign
|
campaign: sample-campaign
|
||||||
inputs:
|
inputs:
|
||||||
audio_dir: ./audio
|
audio_dir: ./audio
|
||||||
speakers_file: ./speakers.yml
|
speakers_file: ./speakers.yml
|
||||||
autocorrect_file: ./autocorrect.yml
|
|
||||||
glossary_file: ./glossary.yml
|
glossary_file: ./glossary.yml
|
||||||
`
|
`
|
||||||
mustWriteFile(t, pipelinePath, pipelineYAML)
|
mustWriteFile(t, pipelinePath, pipelineYAML)
|
||||||
|
|||||||
@@ -498,9 +498,16 @@ func TestOldPolishSemanticEvidenceIsReconsideredOnlyWhenSelected(t *testing.T) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func TestDeliverySemanticChangesInvalidateOnlyTheirFixedDependents(t *testing.T) {
|
func TestDeliverySemanticChangesInvalidateOnlyTheirFixedDependents(t *testing.T) {
|
||||||
t.Run("extract contract", func(t *testing.T) {
|
t.Run("extract pipeline", func(t *testing.T) {
|
||||||
cfg := testConfig(t)
|
cfg, env, runner := extractionLifecycleFixture(t, true)
|
||||||
|
original := cfg.Pipeline.Notarius
|
||||||
configureDeliverySemanticConfig(cfg)
|
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")
|
provider := canonicalSemanticProvider(t, "extract")
|
||||||
seed := manifest.New(cfg.Session.SessionID, time.Now().UTC())
|
seed := manifest.New(cfg.Session.SessionID, time.Now().UTC())
|
||||||
for _, name := range []string{"render", "extract", "analyze", "publish", "notify"} {
|
for _, name := range []string{"render", "extract", "analyze", "publish", "notify"} {
|
||||||
@@ -518,7 +525,7 @@ func TestDeliverySemanticChangesInvalidateOnlyTheirFixedDependents(t *testing.T)
|
|||||||
cfg.Pipeline.Notarius.PipelineID = "session-v2"
|
cfg.Pipeline.Notarius.PipelineID = "session-v2"
|
||||||
runs := 0
|
runs := 0
|
||||||
selected := semanticContractRunStub{name: "extract", provider: provider, runs: &runs}
|
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)
|
t.Fatal(err)
|
||||||
}
|
}
|
||||||
loaded, err := store.Load(context.Background(), manifestPathFor(cfg))
|
loaded, err := store.Load(context.Background(), manifestPathFor(cfg))
|
||||||
@@ -594,7 +601,7 @@ func configureDeliverySemanticConfig(cfg *config.Config) {
|
|||||||
Enabled: true, PipelineID: "session",
|
Enabled: true, PipelineID: "session",
|
||||||
References: map[string]string{"party": "narratio.input.party"},
|
References: map[string]string{"party": "narratio.input.party"},
|
||||||
Outputs: map[string]config.NotariusOutputConfig{
|
Outputs: map[string]config.NotariusOutputConfig{
|
||||||
"encounters": {LaneID: "encounters", MediaType: "application/json", SchemaID: "encounters", SchemaVersion: "1"},
|
"encounters": {LaneID: "encounters"},
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
cfg.Pipeline.Publish = &config.PublishConfig{
|
cfg.Pipeline.Publish = &config.PublishConfig{
|
||||||
|
|||||||
@@ -20,7 +20,6 @@ campaign: sample-campaign
|
|||||||
inputs:
|
inputs:
|
||||||
audio_dir: ./audio
|
audio_dir: ./audio
|
||||||
speakers_file: ./speakers.yml
|
speakers_file: ./speakers.yml
|
||||||
autocorrect_file: ./autocorrect.yml
|
|
||||||
glossary_file: ./glossary.yml
|
glossary_file: ./glossary.yml
|
||||||
`
|
`
|
||||||
if err := os.WriteFile(sessionPath, []byte(sessionTemplate), 0o644); err != nil {
|
if err := os.WriteFile(sessionPath, []byte(sessionTemplate), 0o644); err != nil {
|
||||||
@@ -72,7 +71,6 @@ campaign: sample-campaign
|
|||||||
inputs:
|
inputs:
|
||||||
audio_dir: ./audio
|
audio_dir: ./audio
|
||||||
speakers_file: ./speakers.yml
|
speakers_file: ./speakers.yml
|
||||||
autocorrect_file: ./autocorrect.yml
|
|
||||||
glossary_file: ./glossary.yml
|
glossary_file: ./glossary.yml
|
||||||
`
|
`
|
||||||
if err := os.WriteFile(sessionPath, []byte(sessionYAML), 0o644); err != nil {
|
if err := os.WriteFile(sessionPath, []byte(sessionYAML), 0o644); err != nil {
|
||||||
|
|||||||
@@ -94,8 +94,8 @@ func TestNativeProgressTracksDownloadsConcurrentSpeakersAndReuse(t *testing.T) {
|
|||||||
t.Fatalf("unexpected repeated work=%v", got)
|
t.Fatalf("unexpected repeated work=%v", got)
|
||||||
}
|
}
|
||||||
_, diagnostic = executeProgressCommand(t, app, append([]string{"run", "2026-05-03", "--stage", "prepare", "--force"}, common...))
|
_, 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 {
|
if strings.Count(diagnostic, "reusing prepared audio") != 4 || strings.Contains(diagnostic, "downloading audio") || len(store.Downloads) != 4 {
|
||||||
t.Fatalf("cache reuse claimed new downloads: %s", diagnostic)
|
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"})
|
store.SeedObject(storage.FakeObject{Key: prefix + "audio/a.flac", Data: []byte("replacement-audio"), ETag: "new-generation"})
|
||||||
cause := errors.New("audio download failed")
|
cause := errors.New("audio download failed")
|
||||||
|
|||||||
@@ -21,7 +21,6 @@ const (
|
|||||||
SourceInputGlossarySetting = "narratio.input.glossary.setting"
|
SourceInputGlossarySetting = "narratio.input.glossary.setting"
|
||||||
SourceInputGlossarySpells = "narratio.input.glossary.spells"
|
SourceInputGlossarySpells = "narratio.input.glossary.spells"
|
||||||
SourceInputGlossaryCombined = "narratio.input.glossary.combined"
|
SourceInputGlossaryCombined = "narratio.input.glossary.combined"
|
||||||
SourceInputSpellCatalog = "narratio.input.spell_catalog"
|
|
||||||
|
|
||||||
configuredSourcePrefix = "narratio.artifact."
|
configuredSourcePrefix = "narratio.artifact."
|
||||||
extractionSourcePrefix = "narratio.extraction."
|
extractionSourcePrefix = "narratio.extraction."
|
||||||
|
|||||||
@@ -242,10 +242,10 @@ func TestDescribePreparedInputSource(t *testing.T) {
|
|||||||
if _, ok := DescribePreparedInputSource("narratio.input.unknown"); ok {
|
if _, ok := DescribePreparedInputSource("narratio.input.unknown"); ok {
|
||||||
t.Fatal("DescribePreparedInputSource(unknown) ok = true")
|
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")
|
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")
|
t.Fatal("retired spell catalog source was classified")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -25,13 +25,9 @@ type ConfiguredArtifactDefinition struct {
|
|||||||
|
|
||||||
// ExtractionArtifactDefinition describes one configured Notarius output lane.
|
// ExtractionArtifactDefinition describes one configured Notarius output lane.
|
||||||
type ExtractionArtifactDefinition struct {
|
type ExtractionArtifactDefinition struct {
|
||||||
LaneID string
|
LaneID string
|
||||||
PipelineID string
|
PipelineID string
|
||||||
Filename string
|
Filename string
|
||||||
MediaType string
|
|
||||||
SchemaID string
|
|
||||||
SchemaVersion string
|
|
||||||
ModuleKey string
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// ExtractionDefinitionsFromConfig converts the effective Notarius output map into catalog definitions.
|
// ExtractionDefinitionsFromConfig converts the effective Notarius output map into catalog definitions.
|
||||||
|
|||||||
@@ -56,7 +56,7 @@ func TestArtifactCatalogRejectsDuplicateExtractionRegistration(t *testing.T) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestHydrateExtractionArtifactsAcceptsOnlyCompleteCurrentBundle(t *testing.T) {
|
func TestHydrateExtractionArtifactsAcceptsCurrentFlatEvidence(t *testing.T) {
|
||||||
paths, currentManifest, definitions := validExtractionCatalogFixture(t)
|
paths, currentManifest, definitions := validExtractionCatalogFixture(t)
|
||||||
catalog := registeredExtractionCatalog(t, definitions)
|
catalog := registeredExtractionCatalog(t, definitions)
|
||||||
catalog.HydrateExtractionArtifacts(paths, currentManifest, definitions)
|
catalog.HydrateExtractionArtifacts(paths, currentManifest, definitions)
|
||||||
@@ -76,9 +76,6 @@ func TestHydrateExtractionArtifactsAcceptsOnlyCompleteCurrentBundle(t *testing.T
|
|||||||
if entry.Checksum != wantOutput.Checksum || entry.Size != info.Size() {
|
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())
|
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)
|
resolved, err := ResolveSessionArtifactWithCatalog(paths, currentManifest, entry.SourceID, catalog)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatalf("ResolveSessionArtifactWithCatalog() error = %v", err)
|
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 {
|
tests := []struct {
|
||||||
name string
|
name string
|
||||||
state ExtractionEvidenceState
|
state ExtractionEvidenceState
|
||||||
@@ -100,8 +97,8 @@ func TestInspectExtractionEvidenceClassifiesBundleStates(t *testing.T) {
|
|||||||
{name: "absent", state: ExtractionEvidenceAbsent, mutate: func(_ *testing.T, _ *SessionPaths, m *manifest.Manifest) {
|
{name: "absent", state: ExtractionEvidenceAbsent, mutate: func(_ *testing.T, _ *SessionPaths, m *manifest.Manifest) {
|
||||||
m.Stages["extract"].Status = manifest.StatusFailed
|
m.Stages["extract"].Status = manifest.StatusFailed
|
||||||
}},
|
}},
|
||||||
{name: "obsolete version", state: ExtractionEvidenceObsolete, mutate: func(_ *testing.T, _ *SessionPaths, m *manifest.Manifest) {
|
{name: "wrong size", state: ExtractionEvidenceObsolete, mutate: func(_ *testing.T, _ *SessionPaths, m *manifest.Manifest) {
|
||||||
m.Stages["extract"].Outputs[0].Contract.SchemaVersion = "99"
|
m.Stages["extract"].Outputs[0].Size++
|
||||||
}},
|
}},
|
||||||
{name: "changed direct transcript", wantInputUnavailable: true, recomputeInputIdentity: true, mutate: func(t *testing.T, _ *SessionPaths, m *manifest.Manifest) {
|
{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"}]}`)
|
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) {
|
{name: "inconsistent producer identity", mutate: func(_ *testing.T, _ SessionPaths, m *manifest.Manifest) {
|
||||||
m.Stages["extract"].Outputs[0].ProducerRunID = "another-run"
|
m.Stages["extract"].Outputs[0].ProducerRunID = "another-run"
|
||||||
}},
|
}},
|
||||||
{name: "incompatible contract", mutate: func(_ *testing.T, _ SessionPaths, m *manifest.Manifest) {
|
{name: "incorrect size", mutate: func(_ *testing.T, _ SessionPaths, m *manifest.Manifest) {
|
||||||
m.Stages["extract"].Outputs[0].Contract.SchemaVersion = "99"
|
m.Stages["extract"].Outputs[0].Size++
|
||||||
}},
|
}},
|
||||||
{name: "incompatible provenance", mutate: func(_ *testing.T, _ SessionPaths, m *manifest.Manifest) {
|
{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) {
|
{name: "missing file", mutate: func(t *testing.T, _ SessionPaths, m *manifest.Manifest) {
|
||||||
if err := os.Remove(m.Stages["extract"].Outputs[0].LocalPath); err != nil {
|
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 {
|
func extractionFixtureDefinitions() map[string]ExtractionArtifactDefinition {
|
||||||
return map[string]ExtractionArtifactDefinition{
|
return map[string]ExtractionArtifactDefinition{
|
||||||
"encounters": {
|
"encounters": {
|
||||||
LaneID: "encounters", PipelineID: "campaign.extract", MediaType: "application/json",
|
LaneID: "encounters", PipelineID: "campaign.extract",
|
||||||
SchemaID: "encounters", SchemaVersion: "1", ModuleKey: "encounters",
|
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -264,11 +260,8 @@ func validExtractionCatalogFixture(t *testing.T) (SessionPaths, *manifest.Manife
|
|||||||
root := t.TempDir()
|
root := t.TempDir()
|
||||||
paths := SessionPaths{Root: root, ArtifactsDir: filepath.Join(root, "artifacts")}
|
paths := SessionPaths{Root: root, ArtifactsDir: filepath.Join(root, "artifacts")}
|
||||||
trimmedPath := filepath.Join(paths.Root, filepath.FromSlash(TranscriptPathFinalTrimmed))
|
trimmedPath := filepath.Join(paths.Root, filepath.FromSlash(TranscriptPathFinalTrimmed))
|
||||||
bundleRoot := filepath.Join(paths.ArtifactsDir, "notarius", "extract-run-1")
|
lanePath := filepath.Join(paths.ArtifactsDir, "encounters.json")
|
||||||
lanePath := filepath.Join(bundleRoot, "lanes", "encounters.json")
|
|
||||||
indexPath := filepath.Join(bundleRoot, "index.json")
|
|
||||||
writeExtractionFixtureFile(t, lanePath, `{"encounters":[]}`)
|
writeExtractionFixtureFile(t, lanePath, `{"encounters":[]}`)
|
||||||
writeExtractionFixtureFile(t, indexPath, `{"lanes":[]}`)
|
|
||||||
writeExtractionFixtureFile(t, trimmedPath, `{"segments":[]}`)
|
writeExtractionFixtureFile(t, trimmedPath, `{"segments":[]}`)
|
||||||
definitions := extractionFixtureDefinitions()
|
definitions := extractionFixtureDefinitions()
|
||||||
m := manifest.New("session", fixtureTime)
|
m := manifest.New("session", fixtureTime)
|
||||||
@@ -285,18 +278,16 @@ func validExtractionCatalogFixture(t *testing.T) (SessionPaths, *manifest.Manife
|
|||||||
m.Stages["extract"] = &manifest.StageRecord{
|
m.Stages["extract"] = &manifest.StageRecord{
|
||||||
Name: "extract", Status: manifest.StatusSucceeded,
|
Name: "extract", Status: manifest.StatusSucceeded,
|
||||||
Metadata: map[string]any{
|
Metadata: map[string]any{
|
||||||
"narratio_run_id": "extract-run-1", "bundle_root": bundleRoot,
|
"narratio_run_id": "extract-run-1",
|
||||||
"receipt": map[string]any{"run_id": "notarius-run-1", "pipeline_id": "campaign.extract"},
|
"completion": map[string]any{"pipeline": "campaign.extract"},
|
||||||
extractionMetadataInput: input.Metadata(),
|
extractionMetadataInput: input.Metadata(),
|
||||||
},
|
},
|
||||||
Outputs: []manifest.ArtifactRecord{
|
Outputs: []manifest.ArtifactRecord{
|
||||||
{
|
{
|
||||||
Kind: "notarius_lane", SourceID: ExtractionArtifactSourceID("encounters"), LocalPath: lanePath,
|
Kind: "notarius_lane", SourceID: ExtractionArtifactSourceID("encounters"), LocalPath: lanePath,
|
||||||
ProducerRunID: "extract-run-1", Checksum: extractionFixtureChecksum(t, lanePath),
|
ProducerRunID: "extract-run-1", Checksum: extractionFixtureChecksum(t, lanePath), Size: int64(len(`{"encounters":[]}`)),
|
||||||
Contract: &artifactmodel.ContractMetadata{MediaType: "application/json", SchemaID: "encounters", SchemaVersion: "1", ModuleKey: "encounters"},
|
ExternalProvenance: &artifactmodel.ExternalProvenance{System: "notarius", PipelineID: "campaign.extract", ArtifactID: "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: extractionFixtureChecksum(t, indexPath)},
|
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
return paths, m, definitions
|
return paths, m, definitions
|
||||||
|
|||||||
@@ -132,8 +132,8 @@ func SessionRunExtractDirForCampaign(rootDir, campaign, sessionID, runID string)
|
|||||||
return SessionRunStageDirForCampaign(rootDir, campaign, sessionID, runID, "extract")
|
return SessionRunStageDirForCampaign(rootDir, campaign, sessionID, runID, "extract")
|
||||||
}
|
}
|
||||||
|
|
||||||
// SessionRunNotariusReceiptPathForCampaign returns the invocation's captured completion report.
|
// SessionRunNotariusReportPathForCampaign returns the invocation's captured completion report.
|
||||||
func SessionRunNotariusReceiptPathForCampaign(rootDir, campaign, sessionID, runID string) string {
|
func SessionRunNotariusReportPathForCampaign(rootDir, campaign, sessionID, runID string) string {
|
||||||
return filepath.Join(SessionRunExtractDirForCampaign(rootDir, campaign, sessionID, runID), "logs", "notarius.report.json")
|
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.
|
// SessionPreviousDir returns the previous-session state directory for already-resolved session paths.
|
||||||
func SessionPreviousDir(paths SessionPaths) string {
|
func SessionPreviousDir(paths SessionPaths) string {
|
||||||
return paths.PreviousDir
|
return paths.PreviousDir
|
||||||
|
|||||||
@@ -82,10 +82,9 @@ func TestSessionNotariusPathsForCampaign(t *testing.T) {
|
|||||||
want string
|
want string
|
||||||
}{
|
}{
|
||||||
{name: "extract directory", got: SessionRunExtractDirForCampaign(root, campaign, sessionID, runID), want: extractDir},
|
{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: "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: "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 {
|
for _, test := range tests {
|
||||||
t.Run(test.name, func(t *testing.T) {
|
t.Run(test.name, func(t *testing.T) {
|
||||||
|
|||||||
@@ -40,7 +40,7 @@ characters:
|
|||||||
for_each: party.characters
|
for_each: party.characters
|
||||||
prompt_id: dnd.character_items
|
prompt_id: dnd.character_items
|
||||||
profile_id: production
|
profile_id: production
|
||||||
output_path_pattern: artifacts/characters/{character_id}/items.md
|
output_path_pattern: artifacts/{character_id}-items.md
|
||||||
inputs:
|
inputs:
|
||||||
transcript: {source: narratio.transcript.final_trimmed, required: true}
|
transcript: {source: narratio.transcript.final_trimmed, required: true}
|
||||||
member_vars:
|
member_vars:
|
||||||
@@ -56,7 +56,7 @@ characters:
|
|||||||
for_each: party.characters
|
for_each: party.characters
|
||||||
prompt_id: dnd.character_meta
|
prompt_id: dnd.character_meta
|
||||||
profile_id: production
|
profile_id: production
|
||||||
output_path_pattern: artifacts/characters/{character_id}/meta.md
|
output_path_pattern: artifacts/{character_id}-meta.md
|
||||||
inputs:
|
inputs:
|
||||||
transcript: {source: narratio.transcript.final_trimmed, required: true}
|
transcript: {source: narratio.transcript.final_trimmed, required: true}
|
||||||
`))
|
`))
|
||||||
@@ -77,7 +77,7 @@ characters:
|
|||||||
t.Fatalf("artifact keys = %#v, want %#v", keys, wantKeys)
|
t.Fatalf("artifact keys = %#v, want %#v", keys, wantKeys)
|
||||||
}
|
}
|
||||||
alpha := cfg.ArtifactCatalog.Artifacts["character_items_alpha"]
|
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)
|
t.Fatalf("alpha artifact = %#v", alpha)
|
||||||
}
|
}
|
||||||
if !reflect.DeepEqual(alpha.Vars, map[string]any{
|
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: "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: "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: "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 {
|
for _, test := range tests {
|
||||||
t.Run(test.name, func(t *testing.T) {
|
t.Run(test.name, func(t *testing.T) {
|
||||||
@@ -169,7 +169,7 @@ func TestArtifactFamiliesRejectGeneratedKeyAndOutputCollisions(t *testing.T) {
|
|||||||
}
|
}
|
||||||
base := ScriptoriumArtifactFamilyConfig{
|
base := ScriptoriumArtifactFamilyConfig{
|
||||||
ForEach: partyCharactersFamilySource, PromptID: "dnd.character_meta",
|
ForEach: partyCharactersFamilySource, PromptID: "dnd.character_meta",
|
||||||
OutputPathPattern: "artifacts/characters/{character_id}/meta.md",
|
OutputPathPattern: "artifacts/{character_id}-meta.md",
|
||||||
}
|
}
|
||||||
for _, test := range []struct {
|
for _, test := range []struct {
|
||||||
name string
|
name string
|
||||||
@@ -183,7 +183,7 @@ func TestArtifactFamiliesRejectGeneratedKeyAndOutputCollisions(t *testing.T) {
|
|||||||
},
|
},
|
||||||
{
|
{
|
||||||
name: "generated output", artifacts: map[string]ScriptoriumArtifactConfig{
|
name: "generated output", artifacts: map[string]ScriptoriumArtifactConfig{
|
||||||
"existing": {OutputPath: "artifacts/characters/arannis/meta.md"},
|
"existing": {OutputPath: "artifacts/arannis-meta.md"},
|
||||||
}, wantError: "generates output path",
|
}, wantError: "generates output path",
|
||||||
},
|
},
|
||||||
} {
|
} {
|
||||||
@@ -215,12 +215,12 @@ characters:
|
|||||||
enabled: true
|
enabled: true
|
||||||
for_each: party.characters
|
for_each: party.characters
|
||||||
prompt_id: dnd.character_meta
|
prompt_id: dnd.character_meta
|
||||||
output_path_pattern: artifacts/characters/{character_id}/meta.md
|
output_path_pattern: artifacts/{character_id}-meta.md
|
||||||
character_items:
|
character_items:
|
||||||
enabled: true
|
enabled: true
|
||||||
for_each: party.characters
|
for_each: party.characters
|
||||||
prompt_id: dnd.character_items
|
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]
|
depends_on: [session_recap]
|
||||||
inputs:
|
inputs:
|
||||||
transcript: {source: narratio.transcript.final_trimmed, required: true}
|
transcript: {source: narratio.transcript.final_trimmed, required: true}
|
||||||
@@ -589,7 +589,7 @@ const validFamilyYAML = `
|
|||||||
for_each: party.characters
|
for_each: party.characters
|
||||||
prompt_id: dnd.character_meta
|
prompt_id: dnd.character_meta
|
||||||
profile_id: production
|
profile_id: production
|
||||||
output_path_pattern: artifacts/characters/{character_id}/meta.md
|
output_path_pattern: artifacts/{character_id}-meta.md
|
||||||
member_vars:
|
member_vars:
|
||||||
character_name: character.name
|
character_name: character.name
|
||||||
`
|
`
|
||||||
|
|||||||
@@ -35,9 +35,9 @@ notification:
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestCampaignStrictDecodeAcceptsCampaignID(t *testing.T) {
|
func TestCampaignStrictDecodeAcceptsSharedID(t *testing.T) {
|
||||||
pipelinePath, campaignPath, sessionPath := writeCampaignConfigTestFiles(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",
|
"session_id: 2026-05-03\ninputs:\n audio_dir: ./audio\n",
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -60,14 +60,14 @@ func TestCampaignStrictDecodeRejectsLegacyCampaignField(t *testing.T) {
|
|||||||
if err == nil {
|
if err == nil {
|
||||||
t.Fatal("expected load error, got nil")
|
t.Fatal("expected load error, got nil")
|
||||||
}
|
}
|
||||||
if !strings.Contains(configurationErrorText(err), "load campaign config") || !strings.Contains(configurationErrorText(err), "decode.unknown_field") {
|
if !strings.Contains(configurationErrorText(err), "load campaign config") || !strings.Contains(configurationErrorText(err), "retired campaign field") {
|
||||||
t.Fatalf("error = %q, want campaign strict decode context", configurationErrorText(err))
|
t.Fatalf("error = %q, want retired field context", configurationErrorText(err))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestCampaignStrictDecodeRejectsUnknownFields(t *testing.T) {
|
func TestCampaignStrictDecodeRejectsUnknownFields(t *testing.T) {
|
||||||
pipelinePath, campaignPath, sessionPath := writeCampaignConfigTestFiles(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",
|
"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) {
|
func TestCampaignStrictDecodeAcceptsSessionTemplateFile(t *testing.T) {
|
||||||
pipelinePath, campaignPath, sessionPath := writeCampaignConfigTestFiles(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",
|
"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) {
|
func TestCampaignSessionMergeFillsStableInputs(t *testing.T) {
|
||||||
pipelinePath, campaignPath, sessionPath := writeCampaignConfigTestFiles(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",
|
"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)
|
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.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.GlossaryFile, "./campaign-glossary.yml", campaignPath, "campaign_config")
|
||||||
assertResolvedStableInput(t, cfg.StableInputs.PartyFile, "./campaign-party.yml", campaignPath, "campaign_config")
|
assertResolvedStableInput(t, cfg.StableInputs.PartyFile, "./campaign-party.yml", campaignPath, "campaign_config")
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestCampaignSessionMergeSessionOverridesStableInputs(t *testing.T) {
|
func TestCampaignSessionMergeSessionOverridesStableInputs(t *testing.T) {
|
||||||
pipelinePath, campaignPath, sessionPath := writeCampaignConfigTestFiles(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",
|
"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)
|
t.Fatalf("Validate() error = %v", err)
|
||||||
}
|
}
|
||||||
assertResolvedStableInput(t, cfg.StableInputs.SpeakersFile, "./session-speakers.yml", sessionPath, "session_config")
|
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.GlossaryFile, "./campaign-glossary.yml", campaignPath, "campaign_config")
|
||||||
assertResolvedStableInput(t, cfg.StableInputs.PartyFile, "./campaign-party.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) {
|
func TestCampaignWithCanonicalPartyDoesNotRequirePlayersInput(t *testing.T) {
|
||||||
pipelinePath, campaignPath, sessionPath := writeCampaignConfigTestFiles(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",
|
"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) {
|
func TestCampaignSessionMismatchFails(t *testing.T) {
|
||||||
pipelinePath, campaignPath, sessionPath := writeCampaignConfigTestFiles(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",
|
"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) {
|
func TestLoadMissingCampaignFileFails(t *testing.T) {
|
||||||
pipelinePath, _, sessionPath := writeCampaignConfigTestFiles(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",
|
"session_id: 2026-05-03\ninputs:\n audio_dir: ./audio\n",
|
||||||
)
|
)
|
||||||
missingCampaignPath := filepath.Join(filepath.Dir(sessionPath), "missing-campaign.yml")
|
missingCampaignPath := filepath.Join(filepath.Dir(sessionPath), "missing-campaign.yml")
|
||||||
|
|||||||
@@ -106,7 +106,7 @@ characters:
|
|||||||
|
|
||||||
func TestExplicitPartySelectionNeverFallsBack(t *testing.T) {
|
func TestExplicitPartySelectionNeverFallsBack(t *testing.T) {
|
||||||
dir := t.TempDir()
|
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)
|
writePipelineFixture(t, dir, "party.yml", canonicalPartyFixture)
|
||||||
campaign, err := LoadCampaign(campaignPath)
|
campaign, err := LoadCampaign(campaignPath)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
|
|||||||
@@ -132,15 +132,13 @@ type AutocorrectionRule struct {
|
|||||||
|
|
||||||
// CampaignInputsConfig contains stable campaign-level input file references.
|
// CampaignInputsConfig contains stable campaign-level input file references.
|
||||||
type CampaignInputsConfig struct {
|
type CampaignInputsConfig struct {
|
||||||
Setting *string `yaml:"setting" json:"setting"`
|
Setting *string `yaml:"setting" json:"setting"`
|
||||||
System *string `yaml:"system" json:"system"`
|
System *string `yaml:"system" json:"system"`
|
||||||
Glossary map[string]any `yaml:"glossary" json:"glossary"`
|
Glossary map[string]any `yaml:"glossary" json:"glossary"`
|
||||||
SpeakersFile string `yaml:"speakers_file" json:"speakers_file"`
|
SpeakersFile string `yaml:"speakers_file" json:"speakers_file"`
|
||||||
AutocorrectFile string `yaml:"-" json:"-"`
|
GlossaryFile *string `yaml:"glossary_file" json:"glossary_file"`
|
||||||
GlossaryFile *string `yaml:"glossary_file" json:"glossary_file"`
|
PartyFile string `yaml:"party_file" json:"party_file"`
|
||||||
PartyFile string `yaml:"party_file" json:"party_file"`
|
Autocorrect []AutocorrectionRule `yaml:"autocorrect" json:"autocorrect"`
|
||||||
SpellCatalogFile string `yaml:"-" json:"-"`
|
|
||||||
Autocorrect []AutocorrectionRule `yaml:"autocorrect" json:"autocorrect"`
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// SessionConfig contains per-session inputs and metadata.
|
// SessionConfig contains per-session inputs and metadata.
|
||||||
@@ -371,8 +369,6 @@ type NotariusConfig struct {
|
|||||||
ConfigOverlay *string `yaml:"config_overlay,omitempty" json:"config_overlay,omitempty"`
|
ConfigOverlay *string `yaml:"config_overlay,omitempty" json:"config_overlay,omitempty"`
|
||||||
Cache *string `yaml:"cache,omitempty" json:"cache,omitempty"`
|
Cache *string `yaml:"cache,omitempty" json:"cache,omitempty"`
|
||||||
Debug bool `yaml:"debug,omitempty" json:"debug,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"`
|
ConfigPath string `yaml:"config_path" json:"config_path"`
|
||||||
PipelineID string `yaml:"pipeline_id" json:"pipeline_id"`
|
PipelineID string `yaml:"pipeline_id" json:"pipeline_id"`
|
||||||
Timeout string `yaml:"timeout" json:"timeout"`
|
Timeout string `yaml:"timeout" json:"timeout"`
|
||||||
@@ -381,14 +377,10 @@ type NotariusConfig struct {
|
|||||||
Outputs map[string]NotariusOutputConfig `yaml:"outputs" json:"outputs"`
|
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 {
|
type NotariusOutputConfig struct {
|
||||||
LaneID string `yaml:"lane_id" json:"lane_id"`
|
LaneID string `yaml:"lane_id" json:"lane_id"`
|
||||||
Filename string `yaml:"filename,omitempty" json:"filename,omitempty"`
|
Filename string `yaml:"filename,omitempty" json:"filename,omitempty"`
|
||||||
MediaType string `yaml:"-" json:"-"`
|
|
||||||
SchemaID string `yaml:"-" json:"-"`
|
|
||||||
SchemaVersion string `yaml:"-" json:"-"`
|
|
||||||
ModuleKey string `yaml:"-" json:"-"`
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// NotificationConfig configures the supported notification behavior.
|
// NotificationConfig configures the supported notification behavior.
|
||||||
@@ -398,17 +390,15 @@ type NotificationConfig struct {
|
|||||||
|
|
||||||
// SessionInputsConfig contains per-session input references.
|
// SessionInputsConfig contains per-session input references.
|
||||||
type SessionInputsConfig struct {
|
type SessionInputsConfig struct {
|
||||||
Setting *string `yaml:"setting" json:"setting"`
|
Setting *string `yaml:"setting" json:"setting"`
|
||||||
System *string `yaml:"system" json:"system"`
|
System *string `yaml:"system" json:"system"`
|
||||||
Glossary map[string]any `yaml:"glossary" json:"glossary"`
|
Glossary map[string]any `yaml:"glossary" json:"glossary"`
|
||||||
AudioDir string `yaml:"audio_dir" json:"audio_dir"`
|
AudioDir string `yaml:"audio_dir" json:"audio_dir"`
|
||||||
AudioFiles []string `yaml:"audio_files" json:"audio_files"`
|
AudioFiles []string `yaml:"audio_files" json:"audio_files"`
|
||||||
AudioS3 *SessionAudioS3Input `yaml:"audio_s3" json:"audio_s3"`
|
AudioS3 *SessionAudioS3Input `yaml:"audio_s3" json:"audio_s3"`
|
||||||
SpeakersFile string `yaml:"speakers_file" json:"speakers_file"`
|
SpeakersFile string `yaml:"speakers_file" json:"speakers_file"`
|
||||||
AutocorrectFile string `yaml:"-" json:"-"`
|
Autocorrect []AutocorrectionRule `yaml:"autocorrect" json:"autocorrect"`
|
||||||
Autocorrect []AutocorrectionRule `yaml:"autocorrect" json:"autocorrect"`
|
GlossaryFile *string `yaml:"glossary_file" json:"glossary_file"`
|
||||||
GlossaryFile *string `yaml:"glossary_file" json:"glossary_file"`
|
|
||||||
SpellCatalogFile string `yaml:"-" json:"-"`
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// SessionAudioS3Input configures S3 session-audio input discovery.
|
// SessionAudioS3Input configures S3 session-audio input discovery.
|
||||||
@@ -418,11 +408,9 @@ type SessionAudioS3Input struct {
|
|||||||
|
|
||||||
// ResolvedStableInputs records the origins of completed stable input paths.
|
// ResolvedStableInputs records the origins of completed stable input paths.
|
||||||
type ResolvedStableInputs struct {
|
type ResolvedStableInputs struct {
|
||||||
SpeakersFile ResolvedInputFile
|
SpeakersFile ResolvedInputFile
|
||||||
AutocorrectFile ResolvedInputFile
|
GlossaryFile ResolvedInputFile
|
||||||
GlossaryFile ResolvedInputFile
|
PartyFile ResolvedInputFile
|
||||||
PartyFile ResolvedInputFile
|
|
||||||
SpellCatalogFile ResolvedInputFile
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// ResolvedInputFile records one effective input path and its declaring source.
|
// ResolvedInputFile records one effective input path and its declaring source.
|
||||||
|
|||||||
@@ -10,13 +10,14 @@ import (
|
|||||||
func TestImportedCampaignAndSessionResourcesRetainTheirSources(t *testing.T) {
|
func TestImportedCampaignAndSessionResourcesRetainTheirSources(t *testing.T) {
|
||||||
dir := t.TempDir()
|
dir := t.TempDir()
|
||||||
pipeline := writePipelineFixture(t, dir, "pipeline.yml", testTranscriptionConfig+"workspace: {root: /tmp/narratio}\n")
|
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")
|
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", `session_template_file: templates/session.yml
|
fragment := writePipelineFixture(t, dir, "campaign/shared.yml", `references:
|
||||||
inputs:
|
party: party.yml
|
||||||
speakers_file: speakers.yml
|
narratio:
|
||||||
autocorrect_file: autocorrect.yml
|
session_template_file: templates/session.yml
|
||||||
glossary_file: glossary.yml
|
inputs:
|
||||||
party_file: party.yml
|
speakers_file: speakers.yml
|
||||||
|
glossary_file: glossary.yml
|
||||||
`)
|
`)
|
||||||
writePipelineFixture(t, dir, "campaign/party.yml", canonicalPartyFixture)
|
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")
|
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) {
|
func TestEquivalentDocumentLayoutsRenderIdentically(t *testing.T) {
|
||||||
dir := t.TempDir()
|
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")
|
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\ncampaign_id: sample\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", "inputs: {speakers_file: speakers.yml, autocorrect_file: autocorrect.yml, glossary_file: glossary.yml, party_file: party.yml}\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")
|
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")
|
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")
|
writePipelineFixture(t, dir, "shared/session.yml", "inputs: {audio_dir: audio}\n")
|
||||||
|
|||||||
@@ -12,21 +12,22 @@ func TestGlossarySelectionsInheritIndependently(t *testing.T) {
|
|||||||
campaignPath := writePipelineFixture(t, dir, "campaign.yml", `config:
|
campaignPath := writePipelineFixture(t, dir, "campaign.yml", `config:
|
||||||
imports:
|
imports:
|
||||||
- path: config/inputs.yml
|
- path: config/inputs.yml
|
||||||
campaign_id: campaign
|
schema_version: maximumdirect.rpg.campaign.v1
|
||||||
|
id: campaign
|
||||||
`)
|
`)
|
||||||
writePipelineFixture(t, dir, "config/inputs.yml", `inputs:
|
writePipelineFixture(t, dir, "config/inputs.yml", `setting: coast
|
||||||
speakers_file: speakers.yml
|
system: magic
|
||||||
autocorrect_file: autocorrect.yml
|
references: {party: party.yml}
|
||||||
party_file: party.yml
|
narratio:
|
||||||
setting: coast
|
inputs:
|
||||||
system: magic
|
speakers_file: speakers.yml
|
||||||
glossary_file: vocabulary.yml
|
glossary_file: vocabulary.yml
|
||||||
glossary:
|
glossary:
|
||||||
entries: [{id: watch, name: Silver Watch, category: organization}]
|
entries: [{id: watch, name: Silver Watch, category: organization}]
|
||||||
`)
|
`)
|
||||||
campaign, err := LoadCampaign(campaignPath)
|
campaign, err := LoadCampaign(campaignPath)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatal(err)
|
t.Fatal(configurationErrorText(err))
|
||||||
}
|
}
|
||||||
if OptionalString(campaign.Inputs.GlossaryFile) != filepath.Join(dir, "config/vocabulary.yml") {
|
if OptionalString(campaign.Inputs.GlossaryFile) != filepath.Join(dir, "config/vocabulary.yml") {
|
||||||
t.Fatal(campaign.Inputs.GlossaryFile)
|
t.Fatal(campaign.Inputs.GlossaryFile)
|
||||||
@@ -84,7 +85,7 @@ campaign_id: campaign
|
|||||||
|
|
||||||
func TestGlossarySelectionsRejectInvalidTypesAndUnknownIDs(t *testing.T) {
|
func TestGlossarySelectionsRejectInvalidTypesAndUnknownIDs(t *testing.T) {
|
||||||
dir := t.TempDir()
|
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)
|
campaign, err := LoadCampaign(campaignPath)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
|
|||||||
@@ -10,7 +10,7 @@ func TestIdentityValidationRejectsUnsafeSegments(t *testing.T) {
|
|||||||
for _, value := range unsafe {
|
for _, value := range unsafe {
|
||||||
t.Run("campaign/"+strings.ReplaceAll(value, "/", "_"), func(t *testing.T) {
|
t.Run("campaign/"+strings.ReplaceAll(value, "/", "_"), func(t *testing.T) {
|
||||||
cfg := &CampaignConfig{CampaignID: value, Inputs: CampaignInputsConfig{
|
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 {
|
if err := validateCampaign(cfg); err == nil {
|
||||||
t.Fatalf("validateCampaign(%q) error = nil, want rejection", value)
|
t.Fatalf("validateCampaign(%q) error = nil, want rejection", value)
|
||||||
|
|||||||
@@ -539,16 +539,16 @@ func TestMaintainedExtractionExamplesPreservePublishedContracts(t *testing.T) {
|
|||||||
t.Fatalf("load full example error = %v", err)
|
t.Fatalf("load full example error = %v", err)
|
||||||
}
|
}
|
||||||
want := map[string]NotariusOutputConfig{
|
want := map[string]NotariusOutputConfig{
|
||||||
"item_registry": {LaneID: "item-registry", MediaType: "application/json", SchemaID: "notarius.dnd.item_registry", SchemaVersion: "v1", ModuleKey: "dnd/item-registry"},
|
"item_registry": {LaneID: "item-registry"},
|
||||||
"npc_registry": {LaneID: "npc-registry", MediaType: "application/json", SchemaID: "notarius.dnd.npc_registry", SchemaVersion: "v1", ModuleKey: "dnd/npc-registry"},
|
"npc_registry": {LaneID: "npc-registry"},
|
||||||
"location_registry": {LaneID: "location-registry", MediaType: "application/json", SchemaID: "notarius.dnd.location_registry", SchemaVersion: "v1", ModuleKey: "dnd/location-registry"},
|
"location_registry": {LaneID: "location-registry"},
|
||||||
"scene_descriptions": {LaneID: "scene-descriptions", MediaType: "application/json", SchemaID: "notarius.dnd.scene_descriptions", SchemaVersion: "v1", ModuleKey: "dnd/scene-descriptions"},
|
"scene_descriptions": {LaneID: "scene-descriptions"},
|
||||||
"item_occurrences": {LaneID: "item-occurrences", MediaType: "application/json", SchemaID: "notarius.dnd.item_occurrences", SchemaVersion: "v1", ModuleKey: "dnd/item-occurrences"},
|
"item_occurrences": {LaneID: "item-occurrences"},
|
||||||
"spells": {LaneID: "spells", MediaType: "application/json", SchemaID: "notarius.dnd.spells", SchemaVersion: "v1", ModuleKey: "dnd/spells"},
|
"spells": {LaneID: "spells"},
|
||||||
"combat_turns": {LaneID: "combat-turns", MediaType: "application/json", SchemaID: "notarius.dnd.combat_turns", SchemaVersion: "v1", ModuleKey: "dnd/combat-turns"},
|
"combat_turns": {LaneID: "combat-turns"},
|
||||||
"npc_occurrences": {LaneID: "npc-occurrences", MediaType: "application/json", SchemaID: "notarius.dnd.npc_occurrences", SchemaVersion: "v1", ModuleKey: "dnd/npc-occurrences"},
|
"npc_occurrences": {LaneID: "npc-occurrences"},
|
||||||
"location_occurrences": {LaneID: "location-occurrences", MediaType: "application/json", SchemaID: "notarius.dnd.location_occurrences", SchemaVersion: "v1", ModuleKey: "dnd/location-occurrences"},
|
"location_occurrences": {LaneID: "location-occurrences"},
|
||||||
"enemy_events": {LaneID: "enemy-events", MediaType: "application/json", SchemaID: "notarius.dnd.enemy_events", SchemaVersion: "v1", ModuleKey: "dnd/enemy-events"},
|
"enemy_events": {LaneID: "enemy-events"},
|
||||||
}
|
}
|
||||||
if full.Notarius == nil || !reflect.DeepEqual(full.Notarius.Outputs, want) {
|
if full.Notarius == nil || !reflect.DeepEqual(full.Notarius.Outputs, want) {
|
||||||
t.Fatalf("full example outputs = %#v, want %#v", full.Notarius, 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 {
|
if err := os.WriteFile(pipelinePath, []byte(pipelineYAML), 0o644); err != nil {
|
||||||
t.Fatalf("write pipeline.yml: %v", err)
|
t.Fatalf("write pipeline.yml: %v", err)
|
||||||
}
|
}
|
||||||
campaignYAML := `campaign_id: ` + campaignNameFromSessionYAML(sessionYAML) + `
|
campaignYAML := `schema_version: maximumdirect.rpg.campaign.v1
|
||||||
inputs:
|
id: ` + campaignNameFromSessionYAML(sessionYAML) + `
|
||||||
speakers_file: ./speakers.yml
|
references: {party: ./party.yml}
|
||||||
autocorrect_file: ./autocorrect.yml
|
narratio:
|
||||||
glossary_file: ./glossary.yml
|
inputs:
|
||||||
party_file: ./party.yml
|
speakers_file: ./speakers.yml
|
||||||
|
glossary_file: ./glossary.yml
|
||||||
`
|
`
|
||||||
if err := os.WriteFile(campaignPath, []byte(campaignYAML), 0o644); err != nil {
|
if err := os.WriteFile(campaignPath, []byte(campaignYAML), 0o644); err != nil {
|
||||||
t.Fatalf("write campaign.yml: %v", err)
|
t.Fatalf("write campaign.yml: %v", err)
|
||||||
|
|||||||
@@ -1,15 +1,12 @@
|
|||||||
package config
|
package config
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"encoding/json"
|
|
||||||
"fmt"
|
"fmt"
|
||||||
"os"
|
"os"
|
||||||
"path/filepath"
|
"path/filepath"
|
||||||
"reflect"
|
"reflect"
|
||||||
"strings"
|
"strings"
|
||||||
"testing"
|
"testing"
|
||||||
|
|
||||||
"gopkg.in/yaml.v3"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
func TestNotariusOmittedAndDisabledBehavior(t *testing.T) {
|
func TestNotariusOmittedAndDisabledBehavior(t *testing.T) {
|
||||||
@@ -48,9 +45,6 @@ notarius:
|
|||||||
if disabled.Notarius.Binary != DefaultNotariusBinary || disabled.Notarius.Timeout != DefaultNotariusTimeout {
|
if disabled.Notarius.Binary != DefaultNotariusBinary || disabled.Notarius.Timeout != DefaultNotariusTimeout {
|
||||||
t.Fatalf("disabled defaults = %#v", disabled.Notarius)
|
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 != "" {
|
if disabled.Notarius.ConfigPath != filepath.Join(dir, "relative/notarius.yml") || disabled.Notarius.WorkingDirectory != "" {
|
||||||
t.Fatalf("disabled resource paths = %#v", disabled.Notarius)
|
t.Fatalf("disabled resource paths = %#v", disabled.Notarius)
|
||||||
}
|
}
|
||||||
@@ -154,9 +148,6 @@ notarius:
|
|||||||
outputs:
|
outputs:
|
||||||
npc_registry:
|
npc_registry:
|
||||||
lane_id: 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 {
|
if err := os.WriteFile(pipelinePath, []byte(pipelineYAML), 0o644); err != nil {
|
||||||
t.Fatalf("write pipeline: %v", err)
|
t.Fatalf("write pipeline: %v", err)
|
||||||
@@ -207,84 +198,27 @@ notarius:
|
|||||||
}
|
}
|
||||||
|
|
||||||
func TestNotariusCacheControlNormalizationAndValidation(t *testing.T) {
|
func TestNotariusCacheControlNormalizationAndValidation(t *testing.T) {
|
||||||
for _, mode := range []string{"", "auto", "bypass", "refresh"} {
|
for _, value := range []string{"auto", "bypass", "refresh"} {
|
||||||
t.Run("mode "+mode, func(t *testing.T) {
|
t.Run(value, func(t *testing.T) {
|
||||||
cfg := validNotariusConfig()
|
cfg := validNotariusConfig()
|
||||||
cfg.Resume = true
|
original := " " + value + " "
|
||||||
if mode != "" {
|
cfg.Cache = &original
|
||||||
cfg.ChunkCache = " " + mode + " "
|
|
||||||
}
|
|
||||||
if err := NormalizePipelineConfig(&PipelineConfig{Notarius: cfg}); err != nil {
|
if err := NormalizePipelineConfig(&PipelineConfig{Notarius: cfg}); err != nil {
|
||||||
t.Fatalf("NormalizePipelineConfig() error = %v", err)
|
t.Fatal(err)
|
||||||
}
|
}
|
||||||
if cfg.ChunkCache != mode {
|
if cfg.Cache == nil || *cfg.Cache != value {
|
||||||
t.Fatalf("ChunkCache = %q, want %q", cfg.ChunkCache, mode)
|
t.Fatalf("cache = %v", cfg.Cache)
|
||||||
}
|
|
||||||
if !cfg.Resume {
|
|
||||||
t.Fatal("Resume = false, want true")
|
|
||||||
}
|
}
|
||||||
if err := validateNotarius(cfg, nil); err != nil {
|
if err := validateNotarius(cfg, nil); err != nil {
|
||||||
t.Fatalf("validateNotarius() error = %v", err)
|
t.Fatal(err)
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
for _, value := range []string{"", "AUTO", "invalid"} {
|
||||||
for _, mode := range []string{"AUTO", "invalid"} {
|
cfg := validNotariusConfig()
|
||||||
t.Run("invalid "+mode, func(t *testing.T) {
|
cfg.Cache = &value
|
||||||
cfg := validNotariusConfig()
|
if err := validateNotarius(cfg, nil); err == nil {
|
||||||
cfg.ChunkCache = mode
|
t.Fatalf("accepted cache %q", value)
|
||||||
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)
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -298,9 +232,6 @@ notarius:
|
|||||||
outputs:
|
outputs:
|
||||||
npc_registry:
|
npc_registry:
|
||||||
lane_id: npc-registry
|
lane_id: npc-registry
|
||||||
media_type: application/json
|
|
||||||
schema_id: notarius.dnd.npc_registry
|
|
||||||
schema_version: v1
|
|
||||||
`
|
`
|
||||||
paths := make([]string, 2)
|
paths := make([]string, 2)
|
||||||
configs := make([]*PipelineConfig, 2)
|
configs := make([]*PipelineConfig, 2)
|
||||||
@@ -360,7 +291,7 @@ func TestNotariusReferenceValidationAndNormalization(t *testing.T) {
|
|||||||
" party ": " narratio.input.party ",
|
" party ": " narratio.input.party ",
|
||||||
" chunk . players ": "narratio.input.players",
|
" chunk . players ": "narratio.input.players",
|
||||||
" npc-registry . extract . glossary ": "narratio.input.glossary.campaign",
|
" 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 {
|
if err := NormalizePipelineConfig(&PipelineConfig{Notarius: cfg}); err != nil {
|
||||||
@@ -373,7 +304,7 @@ func TestNotariusReferenceValidationAndNormalization(t *testing.T) {
|
|||||||
"party": "narratio.input.party",
|
"party": "narratio.input.party",
|
||||||
"chunk.players": "narratio.input.players",
|
"chunk.players": "narratio.input.players",
|
||||||
"npc-registry.extract.glossary": "narratio.input.glossary.campaign",
|
"npc-registry.extract.glossary": "narratio.input.glossary.campaign",
|
||||||
"spells": "narratio.input.spell_catalog",
|
"spells": "narratio.input.glossary.combined",
|
||||||
}
|
}
|
||||||
if len(cfg.References) != len(want) {
|
if len(cfg.References) != len(want) {
|
||||||
t.Fatalf("normalized references = %#v, want %#v", cfg.References, 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{
|
cfg.Outputs = map[string]NotariusOutputConfig{
|
||||||
" npc_registry ": {
|
" npc_registry ": {
|
||||||
LaneID: " npc-registry ", MediaType: " application/json ",
|
LaneID: " npc-registry ",
|
||||||
SchemaID: " notarius.dnd.npc_registry ", SchemaVersion: " v1 ",
|
|
||||||
},
|
},
|
||||||
"spells": {
|
"spells": {
|
||||||
LaneID: " spells ", MediaType: " application/json ",
|
LaneID: " spells ",
|
||||||
SchemaID: " notarius.dnd.spells ", SchemaVersion: " v1 ",
|
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -525,7 +454,7 @@ func TestNotariusNormalizationProducesCanonicalValues(t *testing.T) {
|
|||||||
if _, ok := cfg.Outputs[" npc_registry "]; ok {
|
if _, ok := cfg.Outputs[" npc_registry "]; ok {
|
||||||
t.Fatal("outputs retain unnormalized key")
|
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)
|
t.Fatalf("normalized npc_registry output = %#v", got)
|
||||||
}
|
}
|
||||||
beforeSecondPass := cloneNotariusConfigForTest(cfg)
|
beforeSecondPass := cloneNotariusConfigForTest(cfg)
|
||||||
@@ -570,10 +499,10 @@ func TestNotariusDiagnosticsUseSortedMapKeys(t *testing.T) {
|
|||||||
cfg.References = nil
|
cfg.References = nil
|
||||||
cfg.Outputs = make(map[string]NotariusOutputConfig, len(keys))
|
cfg.Outputs = make(map[string]NotariusOutputConfig, len(keys))
|
||||||
for _, key := range 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
|
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 {
|
func validNotariusConfig() *NotariusConfig {
|
||||||
return &NotariusConfig{
|
return &NotariusConfig{
|
||||||
Enabled: true,
|
Enabled: true,
|
||||||
@@ -643,10 +553,7 @@ func validNotariusConfig() *NotariusConfig {
|
|||||||
WorkingDirectory: ".",
|
WorkingDirectory: ".",
|
||||||
Outputs: map[string]NotariusOutputConfig{
|
Outputs: map[string]NotariusOutputConfig{
|
||||||
"npc_registry": {
|
"npc_registry": {
|
||||||
LaneID: "npc-registry",
|
LaneID: "npc-registry",
|
||||||
MediaType: "application/json",
|
|
||||||
SchemaID: "notarius.dnd.npc_registry",
|
|
||||||
SchemaVersion: "v1",
|
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
@@ -659,88 +566,28 @@ func TestNotariusEnabledValidation(t *testing.T) {
|
|||||||
pipeline_id: dnd-session
|
pipeline_id: dnd-session
|
||||||
timeout: 45m
|
timeout: 45m
|
||||||
outputs:
|
outputs:
|
||||||
npc_registry:
|
npc_registry: {lane_id: npc-registry}
|
||||||
lane_id: npc-registry
|
|
||||||
media_type: application/json
|
|
||||||
schema_id: notarius.dnd.npc_registry
|
|
||||||
schema_version: v1
|
|
||||||
module_key: dnd/npc-registry
|
|
||||||
`
|
`
|
||||||
tests := []struct {
|
for _, test := range []struct{ name, section, want string }{
|
||||||
name string
|
{"valid", valid, ""},
|
||||||
section string
|
{"blank binary", strings.Replace(valid, " enabled: true\n", " enabled: true\n binary: ' ' \n", 1), "binary"},
|
||||||
wantErr []string
|
{"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"},
|
||||||
{name: "valid", section: valid},
|
{"missing outputs", strings.Split(valid, " outputs:\n")[0], "outputs"},
|
||||||
{name: "blank binary", section: strings.Replace(valid, " enabled: true\n", " enabled: true\n binary: \" \"\n", 1), wantErr: []string{"pipeline.notarius.binary", "required"}},
|
{"bad timeout", strings.Replace(valid, " timeout: 45m", " timeout: 0s", 1), "timeout"},
|
||||||
{name: "missing config path", section: strings.Replace(valid, " config_path: ./notarius.yml\n", "", 1), wantErr: []string{"pipeline.notarius.config_path", "required"}},
|
{"invalid lane", strings.Replace(valid, "lane_id: npc-registry", "lane_id: ''", 1), "lane_id"},
|
||||||
{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"}},
|
t.Run(test.name, func(t *testing.T) {
|
||||||
{name: "zero timeout", section: strings.Replace(valid, " timeout: 45m", " timeout: 0s", 1), wantErr: []string{"pipeline.notarius.timeout", "positive"}},
|
pipeline, session := writeConfigFiles(t, testPipelineBaseYAML+"\n"+test.section, testSessionBaseYAML)
|
||||||
{name: "negative timeout", section: strings.Replace(valid, " timeout: 45m", " timeout: -1s", 1), wantErr: []string{"pipeline.notarius.timeout", "positive"}},
|
cfg, err := Load(pipeline, session)
|
||||||
{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
|
|
||||||
}
|
|
||||||
if err == nil {
|
if err == nil {
|
||||||
t.Fatalf("Validate() error = nil, want containing %q", tt.wantErr)
|
err = Validate(cfg)
|
||||||
}
|
}
|
||||||
for _, fragment := range tt.wantErr {
|
if test.want == "" && err != nil {
|
||||||
if !strings.Contains(configurationErrorText(err), fragment) {
|
t.Fatal(err)
|
||||||
t.Fatalf("Validate() error = %v, want containing %q", err, fragment)
|
}
|
||||||
}
|
if test.want != "" && (err == nil || !strings.Contains(configurationErrorText(err), test.want)) {
|
||||||
|
t.Fatalf("error=%v want %q", err, test.want)
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -24,12 +24,13 @@ characters:
|
|||||||
if err := os.WriteFile(partyPath, partyYAML, 0o644); err != nil {
|
if err := os.WriteFile(partyPath, partyYAML, 0o644); err != nil {
|
||||||
t.Fatalf("write party: %v", err)
|
t.Fatalf("write party: %v", err)
|
||||||
}
|
}
|
||||||
pipelinePath, campaignPath, sessionPath := writePartyResolutionConfig(t, dir, `campaign_id: campaign
|
pipelinePath, campaignPath, sessionPath := writePartyResolutionConfig(t, dir, `schema_version: maximumdirect.rpg.campaign.v1
|
||||||
inputs:
|
id: campaign
|
||||||
speakers_file: speakers.yml
|
references: {party: roster/party.yml}
|
||||||
autocorrect_file: autocorrect.yml
|
narratio:
|
||||||
glossary_file: glossary.yml
|
inputs:
|
||||||
party_file: roster/party.yml
|
speakers_file: speakers.yml
|
||||||
|
glossary_file: glossary.yml
|
||||||
`, `session_id: session
|
`, `session_id: session
|
||||||
campaign: campaign
|
campaign: campaign
|
||||||
inputs:
|
inputs:
|
||||||
@@ -68,7 +69,7 @@ func TestCanonicalPartyRejectsSeparatePlayersAndSessionPartyOverrides(t *testing
|
|||||||
sessionExtra string
|
sessionExtra string
|
||||||
want 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 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"},
|
{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) {
|
t.Run(test.name, func(t *testing.T) {
|
||||||
dir := t.TempDir()
|
dir := t.TempDir()
|
||||||
writePartyResolutionFile(t, filepath.Join(dir, "party.yml"), canonicalPartyFixture)
|
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{})
|
_, err := LoadWithSessionOptions(pipelinePath, campaignPath, sessionPath, SessionLoadOptions{})
|
||||||
if err == nil || !strings.Contains(configurationErrorText(err), test.want) {
|
if err == nil || !strings.Contains(configurationErrorText(err), test.want) {
|
||||||
t.Fatalf("LoadWithSessionOptions() error = %v, want %q", 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) {
|
func TestUnversionedPartyIsRejectedBeforeResolution(t *testing.T) {
|
||||||
dir := t.TempDir()
|
dir := t.TempDir()
|
||||||
writePartyResolutionFile(t, filepath.Join(dir, "party.yml"), "legacy: campaign\n")
|
writePartyResolutionFile(t, filepath.Join(dir, "party.yml"), "legacy: campaign\n")
|
||||||
pipelinePath, campaignPath, sessionPath := writePartyResolutionConfig(t, dir, `campaign_id: campaign
|
pipelinePath, campaignPath, sessionPath := writePartyResolutionConfig(t, dir, `schema_version: maximumdirect.rpg.campaign.v1
|
||||||
inputs:
|
id: campaign
|
||||||
speakers_file: speakers.yml
|
references: {party: party.yml}
|
||||||
autocorrect_file: autocorrect.yml
|
narratio:
|
||||||
glossary_file: glossary.yml
|
inputs:
|
||||||
party_file: party.yml
|
speakers_file: speakers.yml
|
||||||
|
glossary_file: glossary.yml
|
||||||
`, `session_id: session
|
`, `session_id: session
|
||||||
campaign: campaign
|
campaign: campaign
|
||||||
inputs:
|
inputs:
|
||||||
@@ -108,7 +110,7 @@ inputs:
|
|||||||
func TestResolveAndLoadedCampaignShareCanonicalPartyResolution(t *testing.T) {
|
func TestResolveAndLoadedCampaignShareCanonicalPartyResolution(t *testing.T) {
|
||||||
dir := t.TempDir()
|
dir := t.TempDir()
|
||||||
writePartyResolutionFile(t, filepath.Join(dir, "party.yml"), canonicalPartyFixture)
|
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)
|
pipeline, err := LoadPipeline(pipelinePath)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatalf("LoadPipeline() error = %v", err)
|
t.Fatalf("LoadPipeline() error = %v", err)
|
||||||
|
|||||||
@@ -360,9 +360,6 @@ notarius:
|
|||||||
outputs:
|
outputs:
|
||||||
npc_registry:
|
npc_registry:
|
||||||
lane_id: npc-registry
|
lane_id: npc-registry
|
||||||
media_type: application/json
|
|
||||||
schema_id: notarius.dnd.npc_registry
|
|
||||||
schema_version: v1
|
|
||||||
`)
|
`)
|
||||||
|
|
||||||
cfg, err := LoadPipeline(pipelinePath)
|
cfg, err := LoadPipeline(pipelinePath)
|
||||||
@@ -568,41 +565,31 @@ func TestNotariusCredentialRootProvenance(t *testing.T) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func TestNotariusCacheControlProfileReplacementAndNullReset(t *testing.T) {
|
func TestNotariusCacheControlProfileReplacementAndNullReset(t *testing.T) {
|
||||||
tests := []struct {
|
for _, test := range []struct {
|
||||||
name string
|
name, overlay string
|
||||||
overlay string
|
reset bool
|
||||||
wantResume bool
|
|
||||||
wantMode string
|
|
||||||
wantSource bool
|
|
||||||
wantNil bool
|
|
||||||
}{
|
}{
|
||||||
{name: "replacement", overlay: "notarius:\n resume: true\n chunk_cache: refresh\n", wantResume: true, wantMode: "refresh", wantSource: true},
|
{"replacement", "notarius:\n cache: refresh\n", false}, {"null reset", "notarius: null\n", true},
|
||||||
{name: "null reset", overlay: "notarius: null\n", wantNil: true},
|
} {
|
||||||
}
|
|
||||||
for _, test := range tests {
|
|
||||||
t.Run(test.name, func(t *testing.T) {
|
t.Run(test.name, func(t *testing.T) {
|
||||||
dir := t.TempDir()
|
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)
|
overlay := writePipelineFixture(t, dir, "overlays/testing.yml", test.overlay)
|
||||||
profile := "testing"
|
profile := "testing"
|
||||||
cfg, err := LoadPipelineWithOptions(root, PipelineLoadOptions{Overlay: &profile})
|
cfg, err := LoadPipelineWithOptions(root, PipelineLoadOptions{Overlay: &profile})
|
||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
}
|
}
|
||||||
if test.wantNil {
|
if test.reset {
|
||||||
if cfg.Notarius != nil {
|
if cfg.Notarius != nil {
|
||||||
t.Fatalf("Notarius = %#v, want null reset", cfg.Notarius)
|
t.Fatalf("Notarius = %#v", cfg.Notarius)
|
||||||
}
|
}
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
if cfg.Notarius == nil || cfg.Notarius.Resume != test.wantResume || cfg.Notarius.ChunkCache != test.wantMode {
|
if cfg.Notarius == nil || cfg.Notarius.Cache == nil || *cfg.Notarius.Cache != "refresh" {
|
||||||
t.Fatalf("cache controls = resume %v, mode %q; want resume %v, mode %q", cfg.Notarius.Resume, cfg.Notarius.ChunkCache, test.wantResume, test.wantMode)
|
t.Fatalf("Notarius = %#v", cfg.Notarius)
|
||||||
}
|
}
|
||||||
if !test.wantSource {
|
assertNativePipelineSource(t, cfg, configkit.Keys("notarius", "cache"), overlay)
|
||||||
return
|
|
||||||
}
|
|
||||||
assertNativePipelineSource(t, cfg, configkit.Keys("notarius", "resume"), overlay)
|
|
||||||
assertNativePipelineSource(t, cfg, configkit.Keys("notarius", "chunk_cache"), overlay)
|
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -23,7 +23,7 @@ notarius:
|
|||||||
enabled: true
|
enabled: true
|
||||||
pipeline_id: dnd-session
|
pipeline_id: dnd-session
|
||||||
outputs:
|
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")
|
writePipelineFixture(t, dir, "overlays/testing.yml", "audita:\n config_path: custom.yml\n")
|
||||||
base, err := LoadPipeline(root)
|
base, err := LoadPipeline(root)
|
||||||
|
|||||||
@@ -84,7 +84,7 @@ func TestScriptoriumLoadAndValidate(t *testing.T) {
|
|||||||
enabled: true
|
enabled: true
|
||||||
prompt_id: dnd.session_recap
|
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",
|
name: "invalid timeout fails",
|
||||||
@@ -392,7 +392,7 @@ func TestScriptoriumLoadAndValidate(t *testing.T) {
|
|||||||
prompt_id: dnd.session_recap
|
prompt_id: dnd.session_recap
|
||||||
output_path: transcripts/session_recap.md
|
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",
|
name: "artifact source infers dependency",
|
||||||
@@ -536,7 +536,7 @@ func TestScriptoriumLoadAndValidate(t *testing.T) {
|
|||||||
source: narratio.artifact.session_recap
|
source: narratio.artifact.session_recap
|
||||||
required: true
|
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:
|
inputs:
|
||||||
audio_dir: ./audio
|
audio_dir: ./audio
|
||||||
speakers_file: ./speakers.yml
|
speakers_file: ./speakers.yml
|
||||||
autocorrect_file: ./autocorrect.yml
|
|
||||||
glossary_file: ./glossary.yml
|
glossary_file: ./glossary.yml
|
||||||
`
|
`
|
||||||
|
|||||||
@@ -15,17 +15,15 @@ import (
|
|||||||
func TestSessionDefaultsCompleteBeforeNativeHandoff(t *testing.T) {
|
func TestSessionDefaultsCompleteBeforeNativeHandoff(t *testing.T) {
|
||||||
dir := t.TempDir()
|
dir := t.TempDir()
|
||||||
pipeline := writePipelineFixture(t, dir, "pipeline.yml", testTranscriptionConfig+"workspace: {root: work}\n")
|
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")
|
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", `inputs:
|
fragment := writePipelineFixture(t, dir, "campaign/resources.yml", `narratio:
|
||||||
speakers_file: speakers.yml
|
inputs:
|
||||||
autocorrect_file: autocorrect.yml
|
speakers_file: speakers.yml
|
||||||
glossary_file: glossary.yml
|
glossary_file: glossary.yml
|
||||||
party_file: party.yml
|
|
||||||
spell_catalog_file: spells.yml
|
|
||||||
`)
|
`)
|
||||||
writePipelineFixture(t, dir, "campaign/party.yml", canonicalPartyFixture)
|
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")
|
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"})
|
cfg, err := LoadWithSessionOptions(pipeline, campaign, session, SessionLoadOptions{SessionID: "session"})
|
||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
@@ -37,10 +35,10 @@ func TestSessionDefaultsCompleteBeforeNativeHandoff(t *testing.T) {
|
|||||||
if len(result.Sources()) != 2 {
|
if len(result.Sources()) != 2 {
|
||||||
t.Fatalf("session sources include unrelated campaign inputs: %+v", result.Sources())
|
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)
|
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)
|
t.Fatalf("stable input references: %+v", cfg.StableInputs)
|
||||||
}
|
}
|
||||||
explanation, ok := result.Explain(configkit.Keys("inputs", "glossary_file"))
|
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) {
|
if !reflect.DeepEqual(reloaded.Inputs, cfg.Session.Inputs) {
|
||||||
t.Fatalf("standalone rendering lost effective values or explicit clearing: %s", materialized)
|
t.Fatalf("standalone rendering lost effective values or explicit clearing: %s", materialized)
|
||||||
}
|
}
|
||||||
writePipelineFixture(t, dir, "campaign/resources.yml", `inputs:
|
writePipelineFixture(t, dir, "campaign/resources.yml", `narratio:
|
||||||
speakers_file: replacement-speakers.yml
|
inputs:
|
||||||
autocorrect_file: replacement-autocorrect.yml
|
speakers_file: replacement-speakers.yml
|
||||||
glossary_file: replacement-glossary.yml
|
glossary_file: replacement-glossary.yml
|
||||||
party_file: party.yml
|
|
||||||
spell_catalog_file: replacement-spells.yml
|
|
||||||
`)
|
`)
|
||||||
receiving, err := LoadCampaign(campaign)
|
receiving, err := LoadCampaign(campaign)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -104,37 +100,17 @@ func TestSessionDefaultsCompleteBeforeNativeHandoff(t *testing.T) {
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
}
|
}
|
||||||
if OptionalString(reloaded.Inputs.GlossaryFile) != OptionalString(receiving.Inputs.GlossaryFile) || reloaded.Inputs.AutocorrectFile != receiving.Inputs.AutocorrectFile {
|
if OptionalString(reloaded.Inputs.GlossaryFile) != OptionalString(cfg.Session.Inputs.GlossaryFile) {
|
||||||
t.Fatalf("materialization froze inherited inputs: %+v", reloaded.Inputs)
|
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)
|
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) {
|
func TestSessionDefaultsRespectExplicitEmptyInputsAndIdentity(t *testing.T) {
|
||||||
dir := t.TempDir()
|
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)
|
campaign, err := LoadCampaign(campaignPath)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
|
|||||||
@@ -15,7 +15,6 @@ campaign: sample-campaign
|
|||||||
inputs:
|
inputs:
|
||||||
audio_dir: ./audio
|
audio_dir: ./audio
|
||||||
speakers_file: ./speakers.yml
|
speakers_file: ./speakers.yml
|
||||||
autocorrect_file: ./autocorrect.yml
|
|
||||||
glossary_file: ./glossary.yml
|
glossary_file: ./glossary.yml
|
||||||
`
|
`
|
||||||
if err := os.WriteFile(sessionPath, []byte(sessionYAML), 0o644); err != nil {
|
if err := os.WriteFile(sessionPath, []byte(sessionYAML), 0o644); err != nil {
|
||||||
@@ -38,7 +37,6 @@ campaign: sample-campaign
|
|||||||
inputs:
|
inputs:
|
||||||
audio_dir: ./audio
|
audio_dir: ./audio
|
||||||
speakers_file: ./speakers.yml
|
speakers_file: ./speakers.yml
|
||||||
autocorrect_file: ./autocorrect.yml
|
|
||||||
glossary_file: ./glossary.yml
|
glossary_file: ./glossary.yml
|
||||||
`
|
`
|
||||||
if err := os.WriteFile(sessionPath, []byte(sessionYAML), 0o644); err != nil {
|
if err := os.WriteFile(sessionPath, []byte(sessionYAML), 0o644); err != nil {
|
||||||
@@ -63,7 +61,6 @@ campaign: sample-campaign
|
|||||||
inputs:
|
inputs:
|
||||||
audio_dir: ./audio
|
audio_dir: ./audio
|
||||||
speakers_file: ./speakers.yml
|
speakers_file: ./speakers.yml
|
||||||
autocorrect_file: ./autocorrect.yml
|
|
||||||
glossary_file: ./glossary.yml
|
glossary_file: ./glossary.yml
|
||||||
`
|
`
|
||||||
if err := os.WriteFile(sessionPath, []byte(sessionYAML), 0o644); err != nil {
|
if err := os.WriteFile(sessionPath, []byte(sessionYAML), 0o644); err != nil {
|
||||||
@@ -91,7 +88,6 @@ campaign: sample-campaign
|
|||||||
inputs:
|
inputs:
|
||||||
audio_dir: ./audio
|
audio_dir: ./audio
|
||||||
speakers_file: ./speakers.yml
|
speakers_file: ./speakers.yml
|
||||||
autocorrect_file: ./autocorrect.yml
|
|
||||||
glossary_file: ./glossary.yml
|
glossary_file: ./glossary.yml
|
||||||
`
|
`
|
||||||
if err := os.WriteFile(sessionPath, []byte(sessionYAML), 0o644); err != nil {
|
if err := os.WriteFile(sessionPath, []byte(sessionYAML), 0o644); err != nil {
|
||||||
@@ -136,7 +132,6 @@ unknown_field: true
|
|||||||
inputs:
|
inputs:
|
||||||
audio_dir: ./audio
|
audio_dir: ./audio
|
||||||
speakers_file: ./speakers.yml
|
speakers_file: ./speakers.yml
|
||||||
autocorrect_file: ./autocorrect.yml
|
|
||||||
glossary_file: ./glossary.yml
|
glossary_file: ./glossary.yml
|
||||||
`
|
`
|
||||||
if err := os.WriteFile(sessionPath, []byte(sessionYAML), 0o644); err != nil {
|
if err := os.WriteFile(sessionPath, []byte(sessionYAML), 0o644); err != nil {
|
||||||
@@ -160,7 +155,6 @@ campaign: sample-campaign
|
|||||||
inputs:
|
inputs:
|
||||||
audio_dir: ./audio
|
audio_dir: ./audio
|
||||||
speakers_file: ./speakers.yml
|
speakers_file: ./speakers.yml
|
||||||
autocorrect_file: ./autocorrect.yml
|
|
||||||
glossary_file: ./glossary.yml
|
glossary_file: ./glossary.yml
|
||||||
`
|
`
|
||||||
if err := os.WriteFile(sessionPath, []byte(sessionYAML), 0o644); err != nil {
|
if err := os.WriteFile(sessionPath, []byte(sessionYAML), 0o644); err != nil {
|
||||||
@@ -251,6 +245,5 @@ const standaloneSessionFields = `campaign: sample-campaign
|
|||||||
inputs:
|
inputs:
|
||||||
audio_dir: audio
|
audio_dir: audio
|
||||||
speakers_file: speakers.yml
|
speakers_file: speakers.yml
|
||||||
autocorrect_file: autocorrect.yml
|
|
||||||
glossary_file: glossary.yml
|
glossary_file: glossary.yml
|
||||||
`
|
`
|
||||||
|
|||||||
@@ -636,7 +636,6 @@ inputs:
|
|||||||
audio_s3:
|
audio_s3:
|
||||||
prefix: audio/
|
prefix: audio/
|
||||||
speakers_file: ./speakers.yml
|
speakers_file: ./speakers.yml
|
||||||
autocorrect_file: ./autocorrect.yml
|
|
||||||
glossary_file: ./glossary.yml
|
glossary_file: ./glossary.yml
|
||||||
`,
|
`,
|
||||||
},
|
},
|
||||||
@@ -648,7 +647,6 @@ inputs:
|
|||||||
audio_s3:
|
audio_s3:
|
||||||
prefix: /audio/
|
prefix: /audio/
|
||||||
speakers_file: ./speakers.yml
|
speakers_file: ./speakers.yml
|
||||||
autocorrect_file: ./autocorrect.yml
|
|
||||||
glossary_file: ./glossary.yml
|
glossary_file: ./glossary.yml
|
||||||
`,
|
`,
|
||||||
wantErr: "session.inputs.audio_s3.prefix must be a relative path",
|
wantErr: "session.inputs.audio_s3.prefix must be a relative path",
|
||||||
@@ -661,7 +659,6 @@ inputs:
|
|||||||
audio_s3:
|
audio_s3:
|
||||||
prefix: ../audio/
|
prefix: ../audio/
|
||||||
speakers_file: ./speakers.yml
|
speakers_file: ./speakers.yml
|
||||||
autocorrect_file: ./autocorrect.yml
|
|
||||||
glossary_file: ./glossary.yml
|
glossary_file: ./glossary.yml
|
||||||
`,
|
`,
|
||||||
wantErr: "session.inputs.audio_s3.prefix must not contain path traversal",
|
wantErr: "session.inputs.audio_s3.prefix must not contain path traversal",
|
||||||
@@ -675,7 +672,6 @@ inputs:
|
|||||||
audio_s3:
|
audio_s3:
|
||||||
prefix: audio/
|
prefix: audio/
|
||||||
speakers_file: ./speakers.yml
|
speakers_file: ./speakers.yml
|
||||||
autocorrect_file: ./autocorrect.yml
|
|
||||||
glossary_file: ./glossary.yml
|
glossary_file: ./glossary.yml
|
||||||
`,
|
`,
|
||||||
wantErr: "mutually exclusive",
|
wantErr: "mutually exclusive",
|
||||||
@@ -721,7 +717,6 @@ inputs:
|
|||||||
audio_s3:
|
audio_s3:
|
||||||
prefix: audio/
|
prefix: audio/
|
||||||
speakers_file: ./speakers.yml
|
speakers_file: ./speakers.yml
|
||||||
autocorrect_file: ./autocorrect.yml
|
|
||||||
glossary_file: ./glossary.yml
|
glossary_file: ./glossary.yml
|
||||||
`
|
`
|
||||||
pipelinePath, sessionPath := writeConfigFiles(t, pipelineYAML, sessionYAML)
|
pipelinePath, sessionPath := writeConfigFiles(t, pipelineYAML, sessionYAML)
|
||||||
|
|||||||
@@ -79,10 +79,7 @@ func TestValidateNotariusTimeoutRequiresPositiveValue(t *testing.T) {
|
|||||||
WorkingDirectory: "/tmp",
|
WorkingDirectory: "/tmp",
|
||||||
Outputs: map[string]NotariusOutputConfig{
|
Outputs: map[string]NotariusOutputConfig{
|
||||||
"npc_registry": {
|
"npc_registry": {
|
||||||
LaneID: "npc-registry",
|
LaneID: "npc-registry",
|
||||||
MediaType: "application/json",
|
|
||||||
SchemaID: "notarius.dnd.npc_registry",
|
|
||||||
SchemaVersion: "v1",
|
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -109,9 +109,9 @@ func (extractStage) Run(ctx context.Context, env *Env, m *manifest.Manifest) (re
|
|||||||
if workspaceRoot == "" {
|
if workspaceRoot == "" {
|
||||||
workspaceRoot = env.Config.Pipeline.Workspace.Root
|
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 {
|
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))
|
logPath, err := absolutePath(artifacts.SessionRunNotariusLogPathForCampaign(workspaceRoot, campaign, sessionID, runID))
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -121,7 +121,7 @@ func (extractStage) Run(ctx context.Context, env *Env, m *manifest.Manifest) (re
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, fmt.Errorf("extract: resolve output root: %w", err)
|
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 {
|
for _, directory := range directories {
|
||||||
if err := fileops.EnsureWorkspaceDirectory(directory); err != nil {
|
if err := fileops.EnsureWorkspaceDirectory(directory); err != nil {
|
||||||
return nil, fmt.Errorf("extract: create directory %q: %w", directory, err)
|
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,
|
Binary: resolvedBinary, Credentials: notariusConfig.Credentials, ConfigOverlay: notariusConfig.ConfigOverlay,
|
||||||
ConfigPath: configPath, PipelineID: notariusConfig.PipelineID,
|
ConfigPath: configPath, PipelineID: notariusConfig.PipelineID,
|
||||||
InputPath: inputPath, OutputRoot: outputRoot, WorkingDirectory: workingDirectory,
|
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,
|
Debug: notariusConfig.Debug, DebugDirectory: debugDirectory, References: referenceBindings,
|
||||||
}
|
}
|
||||||
accepted := false
|
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),
|
"reference_count": len(references.Identities), "references": extractReferenceMetadata(references.Identities),
|
||||||
"completion": completion,
|
"completion": completion,
|
||||||
}
|
}
|
||||||
result = &StageResult{Outputs: outputs, Logs: []string{receiptPath, logPath}, Metadata: metadata}
|
result = &StageResult{Outputs: outputs, Logs: []string{reportPath, logPath}, Metadata: metadata}
|
||||||
accepted = true
|
accepted = true
|
||||||
return result, nil
|
return result, nil
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -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 {
|
if err := os.WriteFile(filepath.Join(bundle, "lanes", "npc-registry.json"), []byte(`{"npcs":[]}`), 0o644); err != nil {
|
||||||
t.Fatal(err)
|
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
|
return env, m, fake
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -92,7 +92,7 @@ func BuildNotariusReadiness(cfg *config.Config, paths artifacts.SessionPaths, m
|
|||||||
request := notarius.ReadinessRequest{RunRequest: notarius.RunRequest{
|
request := notarius.ReadinessRequest{RunRequest: notarius.RunRequest{
|
||||||
Binary: binary, Credentials: n.Credentials, ConfigOverlay: n.ConfigOverlay, ConfigPath: configPath,
|
Binary: binary, Credentials: n.Credentials, ConfigOverlay: n.ConfigOverlay, ConfigPath: configPath,
|
||||||
PipelineID: n.PipelineID, InputPath: transcript, OutputRoot: output, WorkingDirectory: working,
|
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,
|
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")}
|
}, 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
|
return NotariusReadiness{Request: request, paths: paths, references: references}, nil
|
||||||
|
|||||||
@@ -2,8 +2,6 @@ package stage
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
"crypto/sha256"
|
|
||||||
"encoding/hex"
|
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
"errors"
|
"errors"
|
||||||
"fmt"
|
"fmt"
|
||||||
@@ -22,8 +20,6 @@ import (
|
|||||||
"gitea.maximumdirect.net/eric/narratio/internal/manifest"
|
"gitea.maximumdirect.net/eric/narratio/internal/manifest"
|
||||||
)
|
)
|
||||||
|
|
||||||
const extractIndexOutputKind = "notarius_index"
|
|
||||||
|
|
||||||
func TestExtractStageDisabledReturnsExplicitSkip(t *testing.T) {
|
func TestExtractStageDisabledReturnsExplicitSkip(t *testing.T) {
|
||||||
for _, test := range []struct {
|
for _, test := range []struct {
|
||||||
name string
|
name string
|
||||||
@@ -88,11 +84,11 @@ notarius:
|
|||||||
if req.InputPath != fixture.inputPath {
|
if req.InputPath != fixture.inputPath {
|
||||||
t.Fatalf("input path = %q, want manifest path %q", 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)
|
wantLog := artifacts.SessionRunNotariusLogPathForCampaign(fixture.workspace, fixture.campaign, fixture.sessionID, fixture.runID)
|
||||||
wantOutputRoot := artifacts.SessionRunNotariusOutputRootForCampaign(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" ||
|
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 {
|
req.WorkingDirectory != env.Config.Pipeline.Notarius.WorkingDirectory || req.Timeout != 45*time.Minute {
|
||||||
t.Fatalf("request = %#v", req)
|
t.Fatalf("request = %#v", req)
|
||||||
}
|
}
|
||||||
@@ -102,8 +98,8 @@ notarius:
|
|||||||
if len(req.References) != 0 {
|
if len(req.References) != 0 {
|
||||||
t.Fatalf("references = %#v, want none", req.References)
|
t.Fatalf("references = %#v, want none", req.References)
|
||||||
}
|
}
|
||||||
if req.Resume || req.ChunkCache != "" {
|
if req.Cache != nil {
|
||||||
t.Fatalf("default cache controls = resume %v, mode %q", req.Resume, req.ChunkCache)
|
t.Fatalf("default cache = %v", req.Cache)
|
||||||
}
|
}
|
||||||
if len(req.Credentials) != 1 || req.Credentials[0].EnvName() != credentialName || !req.Credentials[0].IsResolved() {
|
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")
|
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) {
|
if strings.Contains(string(metadata), credentialCanary) || strings.Contains(string(metadata), credentialName) {
|
||||||
t.Fatal("result metadata contains the Notarius credential")
|
t.Fatal("result metadata contains the Notarius credential")
|
||||||
}
|
}
|
||||||
if len(result.Outputs) != 2 {
|
if len(result.Outputs) != 1 {
|
||||||
t.Fatalf("outputs = %#v, want lane and index", result.Outputs)
|
t.Fatalf("outputs = %#v, want one lane", result.Outputs)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestExtractStageAppliesNotariusCacheControlsAndForcePrecedence(t *testing.T) {
|
func TestExtractStageAppliesNotariusCacheControlsAndForcePrecedence(t *testing.T) {
|
||||||
tests := []struct {
|
for _, test := range []struct {
|
||||||
name string
|
name, configured, want string
|
||||||
configuredResume bool
|
force bool
|
||||||
configuredMode string
|
|
||||||
force bool
|
|
||||||
wantResume bool
|
|
||||||
wantMode string
|
|
||||||
}{
|
}{
|
||||||
{name: "ordinary defaults"},
|
{name: "defaults"}, {name: "configured", configured: "bypass", want: "bypass"},
|
||||||
{name: "ordinary configured", configuredResume: true, configuredMode: "bypass", wantResume: true, wantMode: "bypass"},
|
{name: "forced", configured: "bypass", want: "refresh", force: true}, {name: "forced default", want: "refresh", force: true},
|
||||||
{name: "force overrides configured", configuredResume: true, configuredMode: "bypass", force: true, wantMode: "refresh"},
|
} {
|
||||||
{name: "force overrides defaults", force: true, wantMode: "refresh"},
|
|
||||||
}
|
|
||||||
for _, test := range tests {
|
|
||||||
t.Run(test.name, func(t *testing.T) {
|
t.Run(test.name, func(t *testing.T) {
|
||||||
env, m, fake := setupExtractEnv(t)
|
env, m, fake := setupExtractEnv(t)
|
||||||
configOverlay := "inexpensive"
|
if test.configured != "" {
|
||||||
env.Config.Pipeline.Notarius.ConfigOverlay = &configOverlay
|
env.Config.Pipeline.Notarius.Cache = &test.configured
|
||||||
env.Config.Pipeline.Notarius.Resume = test.configuredResume
|
}
|
||||||
env.Config.Pipeline.Notarius.ChunkCache = test.configuredMode
|
|
||||||
env.Force = test.force
|
env.Force = test.force
|
||||||
|
|
||||||
if _, err := (extractStage{}).Run(context.Background(), env, m); err != nil {
|
if _, err := (extractStage{}).Run(context.Background(), env, m); err != nil {
|
||||||
t.Fatalf("Run() error = %v", err)
|
t.Fatal(err)
|
||||||
}
|
}
|
||||||
if len(fake.Requests) != 1 {
|
got := fake.Requests[0].Cache
|
||||||
t.Fatalf("requests = %d, want 1", len(fake.Requests))
|
if (got == nil && test.want != "") || (got != nil && *got != test.want) {
|
||||||
}
|
t.Fatalf("cache = %v, want %q", got, test.want)
|
||||||
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)
|
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
@@ -478,7 +459,7 @@ func TestExtractReferenceSnapshotsWithRelativeWorkspace(t *testing.T) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// A controlled executable proves the production adapter accepts the paths.
|
// 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")
|
marker := filepath.Join(t.TempDir(), "started")
|
||||||
binary := filepath.Join(t.TempDir(), "notarius")
|
binary := filepath.Join(t.TempDir(), "notarius")
|
||||||
if err := os.WriteFile(binary, []byte("#!/bin/sh\nprintf started > '"+marker+"'\n"), 0o755); err != nil {
|
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{
|
_, err = notarius.NewSubprocessRunner().Run(context.Background(), notarius.RunRequest{
|
||||||
Binary: binary, PipelineID: "dnd-session", ConfigPath: env.Config.Pipeline.Notarius.ConfigPath,
|
Binary: binary, PipelineID: "dnd-session", ConfigPath: env.Config.Pipeline.Notarius.ConfigPath,
|
||||||
InputPath: prepared, OutputRoot: t.TempDir(), WorkingDirectory: env.Config.Pipeline.Workspace.Root,
|
InputPath: prepared, OutputRoot: t.TempDir(), WorkingDirectory: env.Config.Pipeline.Workspace.Root,
|
||||||
Timeout: time.Second * 10, References: first,
|
Timeout: time.Second * 10, References: first, DebugDirectory: filepath.Join(diagnostics, "debug"),
|
||||||
ReceiptPath: filepath.Join(diagnostics, "receipt.json"), LogPath: filepath.Join(diagnostics, "stderr.log"),
|
ReportPath: filepath.Join(diagnostics, "report.json"), LogPath: filepath.Join(diagnostics, "stderr.log"),
|
||||||
})
|
})
|
||||||
if err == nil {
|
if err == nil {
|
||||||
t.Fatal("expected missing receipt error")
|
t.Fatal("expected missing completion report error")
|
||||||
}
|
}
|
||||||
if _, err := os.Stat(marker); err != nil {
|
if _, err := os.Stat(marker); err != nil {
|
||||||
t.Fatalf("adapter did not launch with the snapshot bindings: %v", err)
|
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) {
|
func TestExtractStageRejectsUnavailableReferenceBeforeInvocationOrRunDirectoryCreation(t *testing.T) {
|
||||||
env, m, fake := setupExtractEnv(t)
|
env, m, fake := setupExtractEnv(t)
|
||||||
env.Config.Pipeline.Notarius.References = map[string]string{
|
env.Config.Pipeline.Notarius.References = map[string]string{
|
||||||
"spell_catalog": artifactpolicy.SourceInputSpellCatalog,
|
"spell_catalog": "narratio.input.spell_catalog",
|
||||||
}
|
}
|
||||||
runRoot := artifacts.SessionRunRootForCampaign(
|
runRoot := artifacts.SessionRunRootForCampaign(
|
||||||
env.Config.Pipeline.Workspace.Root, m.Campaign, m.SessionID, m.RunID,
|
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) {
|
func TestExtractStageRejectsMissingOrInvalidFinalTrimmedInputBeforeInvocation(t *testing.T) {
|
||||||
tests := []struct {
|
tests := []struct {
|
||||||
name string
|
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) {
|
func TestExtractionFingerprintIsIndependentOfOutputMapOrder(t *testing.T) {
|
||||||
input := artifacts.ExtractionInputIdentity{
|
input := artifacts.ExtractionInputIdentity{
|
||||||
Checksum: "checksum", SourceID: artifacts.ArtifactTranscriptFinalTrimmed,
|
Checksum: "checksum", SourceID: artifacts.ArtifactTranscriptFinalTrimmed,
|
||||||
@@ -918,8 +622,8 @@ func TestExtractionFingerprintIsIndependentOfOutputMapOrder(t *testing.T) {
|
|||||||
ProducerRunID: "trim-run", Provenance: "manifest.trim.outputs",
|
ProducerRunID: "trim-run", Provenance: "manifest.trim.outputs",
|
||||||
}
|
}
|
||||||
first := &config.NotariusConfig{PipelineID: "pipeline", Outputs: map[string]config.NotariusOutputConfig{
|
first := &config.NotariusConfig{PipelineID: "pipeline", Outputs: map[string]config.NotariusOutputConfig{
|
||||||
"zeta": {LaneID: "z", MediaType: "application/json", SchemaID: "z", SchemaVersion: "v1"},
|
"zeta": {LaneID: "z"},
|
||||||
"alpha": {LaneID: "a", MediaType: "application/json", SchemaID: "a", SchemaVersion: "v1"},
|
"alpha": {LaneID: "a"},
|
||||||
}}
|
}}
|
||||||
second := &config.NotariusConfig{PipelineID: "pipeline", Outputs: map[string]config.NotariusOutputConfig{
|
second := &config.NotariusConfig{PipelineID: "pipeline", Outputs: map[string]config.NotariusOutputConfig{
|
||||||
"alpha": first.Outputs["alpha"], "zeta": first.Outputs["zeta"],
|
"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) {
|
func TestExtractStageResumeValidationAcceptsCurrentImmutableResult(t *testing.T) {
|
||||||
env, m, _ := setupExtractEnv(t)
|
env, m, _ := setupExtractEnv(t)
|
||||||
env.Config.Pipeline.Notarius.References = map[string]string{
|
env.Config.Pipeline.Notarius.References = map[string]string{
|
||||||
@@ -1159,7 +809,7 @@ func TestExtractStageResumeValidationDoesNotResolveReferencesWhenDisabled(t *tes
|
|||||||
env, m, _ := setupExtractEnv(t)
|
env, m, _ := setupExtractEnv(t)
|
||||||
env.Config.Pipeline.Notarius.Enabled = false
|
env.Config.Pipeline.Notarius.Enabled = false
|
||||||
env.Config.Pipeline.Notarius.References = map[string]string{
|
env.Config.Pipeline.Notarius.References = map[string]string{
|
||||||
"missing": artifactpolicy.SourceInputSpellCatalog,
|
"missing": "narratio.input.spell_catalog",
|
||||||
}
|
}
|
||||||
|
|
||||||
validation, err := (extractStage{}).ValidateResume(context.Background(), env, m)
|
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) {
|
func TestExtractStageResumeValidationRequiresFreshEvidence(t *testing.T) {
|
||||||
tests := []struct {
|
tests := []struct {
|
||||||
name string
|
name string
|
||||||
@@ -1265,8 +853,8 @@ func TestExtractStageResumeValidationRequiresFreshEvidence(t *testing.T) {
|
|||||||
t.Fatalf("WriteFile(lane) error = %v", err)
|
t.Fatalf("WriteFile(lane) error = %v", err)
|
||||||
}
|
}
|
||||||
}},
|
}},
|
||||||
{name: "incompatible contract", mutate: func(_ *testing.T, _ *Env, m *manifest.Manifest) {
|
{name: "incorrect size", mutate: func(_ *testing.T, _ *Env, m *manifest.Manifest) {
|
||||||
m.Stages["extract"].Outputs[0].Contract.SchemaVersion = "v2"
|
m.Stages["extract"].Outputs[0].Size++
|
||||||
}},
|
}},
|
||||||
{name: "missing source", mutate: func(_ *testing.T, _ *Env, m *manifest.Manifest) {
|
{name: "missing source", mutate: func(_ *testing.T, _ *Env, m *manifest.Manifest) {
|
||||||
m.Stages["extract"].Outputs = m.Stages["extract"].Outputs[1:]
|
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"
|
m.Stages["extract"].Outputs[0].ProducerRunID = "different-run"
|
||||||
}},
|
}},
|
||||||
{name: "provenance mismatch", mutate: func(_ *testing.T, _ *Env, m *manifest.Manifest) {
|
{name: "provenance mismatch", mutate: func(_ *testing.T, _ *Env, m *manifest.Manifest) {
|
||||||
m.Stages["extract"].Outputs[0].ExternalProvenance.RunID = "different-run"
|
m.Stages["extract"].Outputs[0].ExternalProvenance.ArtifactID = "different-lane"
|
||||||
}},
|
|
||||||
{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)
|
|
||||||
}
|
|
||||||
}},
|
}},
|
||||||
}
|
}
|
||||||
for _, test := range tests {
|
for _, test := range tests {
|
||||||
@@ -1331,7 +913,7 @@ func TestExtractStageResumeValidationRejectsUnsafePathWithError(t *testing.T) {
|
|||||||
prior := *m.Stages["extract"]
|
prior := *m.Stages["extract"]
|
||||||
test.mutate(t, env, m)
|
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)
|
t.Fatalf("ValidateResume() error = %v, want unsafe evidence error", err)
|
||||||
}
|
}
|
||||||
if m.Stages["extract"].Status != prior.Status || m.Stages["extract"].Error != prior.Error {
|
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{
|
records = append(records, manifest.ArtifactRecord{
|
||||||
Kind: output.Kind, SourceID: output.SourceID, LocalPath: output.AbsolutePath,
|
Kind: output.Kind, SourceID: output.SourceID, LocalPath: output.AbsolutePath,
|
||||||
Contract: output.Contract, ExternalProvenance: output.ExternalProvenance,
|
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)
|
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,
|
Timeout: "45m", WorkingDirectory: workingDirectory,
|
||||||
Outputs: map[string]config.NotariusOutputConfig{
|
Outputs: map[string]config.NotariusOutputConfig{
|
||||||
"npc_registry": {
|
"npc_registry": {
|
||||||
LaneID: "npc-registry", MediaType: "application/json",
|
LaneID: "npc-registry",
|
||||||
SchemaID: "notarius.dnd.npc_registry", SchemaVersion: "v1", ModuleKey: "dnd/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 {
|
if err := os.MkdirAll(filepath.Join(bundle, "lanes"), 0o755); err != nil {
|
||||||
t.Fatalf("MkdirAll(bundle lanes) error = %v", err)
|
t.Fatalf("MkdirAll(bundle lanes) error = %v", err)
|
||||||
}
|
}
|
||||||
if err := os.MkdirAll(filepath.Join(bundle, "unknown"), 0o755); err != nil {
|
if err := os.WriteFile(filepath.Join(bundle, "lanes", "npc-registry.json"), []byte(`{"npcs":[]}`), 0644); err != nil {
|
||||||
t.Fatalf("MkdirAll(bundle unknown) error = %v", err)
|
t.Fatal(err)
|
||||||
}
|
}
|
||||||
files := map[string]string{
|
fake := ¬arius.FakeRunner{Result: notarius.RunResult{BundleRoot: bundle, Report: notarius.CompletionReport{Pipeline: "dnd-session", ArtifactCount: 1, OutputDirectory: bundle}}}
|
||||||
"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,
|
|
||||||
}},
|
|
||||||
}}
|
|
||||||
env := &Env{
|
env := &Env{
|
||||||
Config: &config.Config{
|
Config: &config.Config{
|
||||||
Pipeline: &config.PipelineConfig{Workspace: config.WorkspaceConfig{Root: workspace}, Notarius: notariusConfig},
|
Pipeline: &config.PipelineConfig{Workspace: config.WorkspaceConfig{Root: workspace}, Notarius: notariusConfig},
|
||||||
|
|||||||
@@ -461,8 +461,7 @@ func setupMergeEnvWithWorkspace(t *testing.T, workspace string) (*Env, *manifest
|
|||||||
Session: &config.SessionConfig{
|
Session: &config.SessionConfig{
|
||||||
SessionID: "2026-05-03",
|
SessionID: "2026-05-03",
|
||||||
Inputs: config.SessionInputsConfig{
|
Inputs: config.SessionInputsConfig{
|
||||||
SpeakersFile: "./speakers.yml",
|
SpeakersFile: "./speakers.yml",
|
||||||
AutocorrectFile: "./autocorrect.yml",
|
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -52,7 +52,8 @@ func TestNotariusCacheReuseIntegration(t *testing.T) {
|
|||||||
t.Fatalf("first chunk plan = %#v, want generated", first.ChunkPlan)
|
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)
|
second := runNotariusIntegrationExtraction(t, env, runManifest, "20260916T010102Z-a0000002", false)
|
||||||
if got := provider.Calls(); got != 2 {
|
if got := provider.Calls(); got != 2 {
|
||||||
t.Fatalf("resumed provider calls = %d, want unchanged count 2", got)
|
t.Fatalf("resumed provider calls = %d, want unchanged count 2", got)
|
||||||
@@ -112,7 +113,8 @@ func TestNotariusCacheReuseIntegration(t *testing.T) {
|
|||||||
provider := newNotariusIntegrationProvider(t)
|
provider := newNotariusIntegrationProvider(t)
|
||||||
provider.FailRequest(2)
|
provider.FailRequest(2)
|
||||||
env, runManifest, _ := newNotariusIntegrationFixture(t, binary, provider.URL(), "dnd-recovery")
|
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"
|
runManifest.RunID = "20260916T020101Z-b0000001"
|
||||||
env.Force = false
|
env.Force = false
|
||||||
@@ -253,16 +255,14 @@ pipelines:
|
|||||||
env.Config.Pipeline.Notarius = &config.NotariusConfig{
|
env.Config.Pipeline.Notarius = &config.NotariusConfig{
|
||||||
Enabled: true, Binary: binary, ConfigPath: configPath, PipelineID: pipelineID,
|
Enabled: true, Binary: binary, ConfigPath: configPath, PipelineID: pipelineID,
|
||||||
ConfigOverlay: &overlay,
|
ConfigOverlay: &overlay,
|
||||||
Timeout: "2m", WorkingDirectory: root, ChunkCache: "auto",
|
Timeout: "2m", WorkingDirectory: root,
|
||||||
References: map[string]string{"party": artifactpolicy.SourceInputParty},
|
References: map[string]string{"party": artifactpolicy.SourceInputParty},
|
||||||
Outputs: map[string]config.NotariusOutputConfig{
|
Outputs: map[string]config.NotariusOutputConfig{
|
||||||
"spells_first": {
|
"spells_first": {
|
||||||
LaneID: "spells-first", MediaType: "application/json", ModuleKey: "dnd/spells",
|
LaneID: "spells-first",
|
||||||
SchemaID: "notarius.dnd.spells", SchemaVersion: "v1",
|
|
||||||
},
|
},
|
||||||
"spells_second": {
|
"spells_second": {
|
||||||
LaneID: "spells-second", MediaType: "application/json", ModuleKey: "dnd/spells",
|
LaneID: "spells-second",
|
||||||
SchemaID: "notarius.dnd.spells", SchemaVersion: "v1",
|
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
@@ -342,8 +342,8 @@ func runNotariusIntegrationExtraction(t *testing.T, env *Env, runManifest *manif
|
|||||||
env.Force = force
|
env.Force = force
|
||||||
result, err := (extractStage{}).Run(context.Background(), env, runManifest)
|
result, err := (extractStage{}).Run(context.Background(), env, runManifest)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
receiptPath := artifacts.SessionRunNotariusReceiptPathForCampaign(env.Config.Pipeline.Workspace.Root, runManifest.Campaign, runManifest.SessionID, runID)
|
reportPath := artifacts.SessionRunNotariusReportPathForCampaign(env.Config.Pipeline.Workspace.Root, runManifest.Campaign, runManifest.SessionID, runID)
|
||||||
if data, readErr := os.ReadFile(receiptPath); readErr == nil {
|
if data, readErr := os.ReadFile(reportPath); readErr == nil {
|
||||||
t.Logf("failed Notarius receipt: %s", data)
|
t.Logf("failed Notarius receipt: %s", data)
|
||||||
}
|
}
|
||||||
t.Fatalf("extract run %q: %v", runID, err)
|
t.Fatalf("extract run %q: %v", runID, err)
|
||||||
|
|||||||
@@ -709,11 +709,6 @@ inputs:
|
|||||||
ConfigPath: campaignPath,
|
ConfigPath: campaignPath,
|
||||||
Source: "campaign_config",
|
Source: "campaign_config",
|
||||||
},
|
},
|
||||||
AutocorrectFile: config.ResolvedInputFile{
|
|
||||||
Path: "./autocorrect.yml",
|
|
||||||
ConfigPath: campaignPath,
|
|
||||||
Source: "campaign_config",
|
|
||||||
},
|
|
||||||
GlossaryFile: config.ResolvedInputFile{
|
GlossaryFile: config.ResolvedInputFile{
|
||||||
Path: "./glossary.yml",
|
Path: "./glossary.yml",
|
||||||
ConfigPath: campaignPath,
|
ConfigPath: campaignPath,
|
||||||
|
|||||||
@@ -70,10 +70,6 @@ func TestPublishUploadsRunFilesPublishedOutputsAndCurrentPointer(t *testing.T) {
|
|||||||
configurePublishExtractionFixture(t, env, m)
|
configurePublishExtractionFixture(t, env, m)
|
||||||
runBundleRoot := filepath.Join(runRoot, "extract", "notarius-output", "notarius-run-1")
|
runBundleRoot := filepath.Join(runRoot, "extract", "notarius-output", "notarius-run-1")
|
||||||
for rel, contents := range map[string]string{
|
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":[]}`,
|
"lanes/encounters.json": `{"encounters":[]}`,
|
||||||
"pipeline/chunk-map.json": `{"chunks":[]}`,
|
"pipeline/chunk-map.json": `{"chunks":[]}`,
|
||||||
"pipeline/evidence-context.json": `{"evidence":[]}`,
|
"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(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.stderr.log"), "notarius diagnostic\n")
|
||||||
writeStageTestFile(t, filepath.Join(runRoot, "extract", "notarius-output-copy", "keep.json"), "{}\n")
|
writeStageTestFile(t, filepath.Join(runRoot, "extract", "notarius-output-copy", "keep.json"), "{}\n")
|
||||||
writeStageTestFile(t, filepath.Join(runRoot, "archive", "notarius-output", "keep.json"), "{}\n")
|
writeStageTestFile(t, filepath.Join(runRoot, "archive", "notarius-output", "keep.json"), "{}\n")
|
||||||
|
|||||||
@@ -40,14 +40,14 @@ func TestExtractSemanticConfigSensitivityAndOperationalExclusions(t *testing.T)
|
|||||||
output.LaneID = "encounters-v2"
|
output.LaneID = "encounters-v2"
|
||||||
env.Config.Pipeline.Notarius.Outputs["encounters"] = output
|
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 := env.Config.Pipeline.Notarius.Outputs["encounters"]
|
||||||
output.SchemaVersion = "2"
|
output.Filename = "renamed.json"
|
||||||
env.Config.Pipeline.Notarius.Outputs["encounters"] = output
|
env.Config.Pipeline.Notarius.Outputs["encounters"] = output
|
||||||
}},
|
}},
|
||||||
{name: "output identity", mutate: func(env *Env) {
|
{name: "output identity", mutate: func(env *Env) {
|
||||||
env.Config.Pipeline.Notarius.Outputs["characters"] = config.NotariusOutputConfig{
|
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
|
name string
|
||||||
mutate func(*config.NotariusConfig)
|
mutate func(*config.NotariusConfig)
|
||||||
}{
|
}{
|
||||||
{name: "resume", mutate: func(cfg *config.NotariusConfig) { cfg.Resume = true }},
|
{name: "cache", mutate: func(cfg *config.NotariusConfig) { value := "refresh"; cfg.Cache = &value }},
|
||||||
{name: "chunk cache", mutate: func(cfg *config.NotariusConfig) { cfg.ChunkCache = "refresh" }},
|
{name: "debug", mutate: func(cfg *config.NotariusConfig) { cfg.Debug = true }},
|
||||||
} {
|
} {
|
||||||
t.Run("operational "+test.name, func(t *testing.T) {
|
t.Run("operational "+test.name, func(t *testing.T) {
|
||||||
env := downstreamSemanticEnv()
|
env := downstreamSemanticEnv()
|
||||||
@@ -174,8 +174,8 @@ func TestExtractResumeValidationExcludesOperationalSettings(t *testing.T) {
|
|||||||
env.Config.Pipeline.Notarius.ConfigPath = "/not/present/private.yml"
|
env.Config.Pipeline.Notarius.ConfigPath = "/not/present/private.yml"
|
||||||
env.Config.Pipeline.Notarius.Timeout = "not-a-duration"
|
env.Config.Pipeline.Notarius.Timeout = "not-a-duration"
|
||||||
env.Config.Pipeline.Notarius.WorkingDirectory = "/not/present/work"
|
env.Config.Pipeline.Notarius.WorkingDirectory = "/not/present/work"
|
||||||
env.Config.Pipeline.Notarius.Resume = true
|
mode := "bypass"
|
||||||
env.Config.Pipeline.Notarius.ChunkCache = "bypass"
|
env.Config.Pipeline.Notarius.Cache = &mode
|
||||||
|
|
||||||
validation, err := (extractStage{}).ValidateResume(context.Background(), env, m)
|
validation, err := (extractStage{}).ValidateResume(context.Background(), env, m)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -368,8 +368,7 @@ func downstreamSemanticEnv() *Env {
|
|||||||
References: map[string]string{"party": artifactpolicy.SourceInputParty},
|
References: map[string]string{"party": artifactpolicy.SourceInputParty},
|
||||||
Outputs: map[string]config.NotariusOutputConfig{
|
Outputs: map[string]config.NotariusOutputConfig{
|
||||||
"encounters": {
|
"encounters": {
|
||||||
LaneID: "encounters", MediaType: "application/json", SchemaID: "encounters",
|
LaneID: "encounters",
|
||||||
SchemaVersion: "1", ModuleKey: "encounters",
|
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
|
|||||||
@@ -459,17 +459,15 @@ func setupTranscribeEnv(t *testing.T, audioFiles []string) (*Env, *manifest.Mani
|
|||||||
SessionID: "2026-05-03",
|
SessionID: "2026-05-03",
|
||||||
Campaign: "sample-campaign",
|
Campaign: "sample-campaign",
|
||||||
Inputs: config.SessionInputsConfig{
|
Inputs: config.SessionInputsConfig{
|
||||||
AudioDir: "./audio",
|
AudioDir: "./audio",
|
||||||
SpeakersFile: "./speakers.yml",
|
SpeakersFile: "./speakers.yml",
|
||||||
AutocorrectFile: "./autocorrect.yml",
|
GlossaryFile: new(filepath.Join(cfgDir, "glossary.yml")),
|
||||||
GlossaryFile: new(filepath.Join(cfgDir, "glossary.yml")),
|
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
StableInputs: config.ResolvedStableInputs{
|
StableInputs: config.ResolvedStableInputs{
|
||||||
SpeakersFile: config.ResolvedInputFile{Path: "./speakers.yml", ConfigPath: campaignPath, Source: "campaign_config"},
|
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"},
|
||||||
GlossaryFile: config.ResolvedInputFile{Path: "./glossary.yml", ConfigPath: campaignPath, Source: "campaign_config"},
|
PartyFile: config.ResolvedInputFile{Path: "./party.yml", ConfigPath: campaignPath, Source: "campaign_config"},
|
||||||
PartyFile: config.ResolvedInputFile{Path: "./party.yml", ConfigPath: campaignPath, Source: "campaign_config"},
|
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user