From 2dc057b97e5fe8e856ecce56ac115e9e0400bdc2 Mon Sep 17 00:00:00 2001 From: Eric Rakestraw Date: Fri, 27 Nov 2026 01:15:40 +0000 Subject: [PATCH] Prepare normalized processing plans and fixed chunks --- docs/roadmap/implementation.md | 2 + internal/cli/process.go | 8 +- internal/cli/process_inputs.go | 15 ++-- internal/cli/process_pipeline.go | 4 +- internal/cli/process_prepare_output.go | 55 ++++++++++++ internal/framework/preflight/plan.go | 75 ++++++++++++++++ internal/framework/preflight/plan_test.go | 73 ++++++++++++++++ internal/framework/preflight/preflight.go | 78 +---------------- .../framework/preflight/preflight_test.go | 48 ---------- .../framework/preflight/readiness_test.go | 17 +--- .../processreport/partial_validation_test.go | 3 +- .../framework/runner/cancellation_test.go | 12 +-- internal/framework/runner/evidence_test.go | 4 +- .../framework/runner/ordered_workflow_test.go | 2 +- .../framework/runner/prepared_input_test.go | 30 +++++++ internal/framework/runner/repair_test.go | 10 +-- internal/framework/runner/runner.go | 44 +--------- internal/framework/runner/runner_test.go | 87 +++++++++---------- internal/framework/runner/window_test.go | 8 +- 19 files changed, 315 insertions(+), 260 deletions(-) create mode 100644 internal/cli/process_prepare_output.go create mode 100644 internal/framework/preflight/plan.go create mode 100644 internal/framework/preflight/plan_test.go delete mode 100644 internal/framework/preflight/preflight_test.go create mode 100644 internal/framework/runner/prepared_input_test.go diff --git a/docs/roadmap/implementation.md b/docs/roadmap/implementation.md index e159ed6..2e273f3 100644 --- a/docs/roadmap/implementation.md +++ b/docs/roadmap/implementation.md @@ -123,6 +123,8 @@ This is present readiness, not a guarantee that a later write will succeed. ## Stage 3: Build the domain preparation plan once +**Completed.** + Work: 1. Refactor `framework/preflight` into the provider-independent local planning diff --git a/internal/cli/process.go b/internal/cli/process.go index 4743800..c6a95f9 100644 --- a/internal/cli/process.go +++ b/internal/cli/process.go @@ -6,7 +6,6 @@ import ( "sync" "gitea.maximumdirect.net/eric/audita/v4/internal/appconfig" - "gitea.maximumdirect.net/eric/audita/v4/internal/core/normalization" "gitea.maximumdirect.net/eric/audita/v4/internal/core/outputschema" "gitea.maximumdirect.net/eric/audita/v4/internal/core/reporting" "gitea.maximumdirect.net/eric/audita/v4/internal/core/schema" @@ -74,13 +73,8 @@ func runProcess(inv commandkit.Invocation, input processInput) commandkit.Outcom } loaded.RawTranscript = nil cfg := &loaded.Configuration.Config.Application - normalizer := normalization.NewNormalizer(normalization.NormalizationConfig{ - MaxSegmentGap: cfg.Normalization.MaxSegmentGap, EllipsisGap: cfg.Normalization.EllipsisGap, - MaxSegmentDuration: cfg.Normalization.MaxSegmentDuration, MaxSegmentTokens: cfg.Normalization.MaxSegmentTokens, - }) - transcript := loaded.Source.Canonical() + normalized, summary := prepared.Prepared.Plan.Transcript, prepared.Prepared.Plan.Summary loaded.Source = nil - normalized, summary := normalizer.Normalize(transcript) if debug != nil { warn(debug.WriteNormalizedTranscript(normalized)) warn(debug.WriteNormalizationSummary(summary)) diff --git a/internal/cli/process_inputs.go b/internal/cli/process_inputs.go index bc8b857..13c2cbc 100644 --- a/internal/cli/process_inputs.go +++ b/internal/cli/process_inputs.go @@ -81,7 +81,7 @@ func loadProcessInputs(ctx context.Context, input processInput, mode commandkit. // preparedProcess groups the output resources and the facts needed for reports. type preparedProcess struct { - Prepared *preflight.Prepared + Prepared *preparedOutput RunID string Started time.Time } @@ -127,17 +127,17 @@ func prepareProcess(ctx context.Context, input processInput, loaded *processInpu return renderReportBundle(processreport.Failed(failedSnapshot, primary, "initialization", failures)) } } - var debug *preflight.DebugInput + var debug *debugInput var warnings []error if input.Debug.Value { var effective bytes.Buffer if err := loaded.Configuration.WriteEffective(&effective); err != nil { warnings = append(warnings, err) } - debug = &preflight.DebugInput{WorkDir: cfg.Diagnostics.WorkDir, RunID: runID, EffectiveConfig: effective.Bytes(), Metadata: diagnostics.InvocationMetadata{Operation: "process", TranscriptPath: input.Transcript, OutputPath: input.Output.Value, Overlay: input.Overlay.Value, ConfigVersion: &cfg.Version, RunID: runID, StartedAt: started}} + debug = &debugInput{WorkDir: cfg.Diagnostics.WorkDir, RunID: runID, EffectiveConfig: effective.Bytes(), Metadata: diagnostics.InvocationMetadata{Operation: "process", TranscriptPath: input.Transcript, OutputPath: input.Output.Value, Overlay: input.Overlay.Value, ConfigVersion: &cfg.Version, RunID: runID, StartedAt: started}} } checkedBackends := make(map[string]struct{}) - prepared, err := preflight.Prepare(ctx, preflight.Input{InspectProfile: func(ctx context.Context, id string) error { + inspectProfile := func(ctx context.Context, id string) error { profile, err := loaded.Runtime.Engine.InspectProfile(ctx, id) if errors.Is(err, pk.ErrProfileNotFound) { return &preflight.SelectionError{Cause: err} @@ -157,7 +157,12 @@ func prepareProcess(ctx context.Context, input processInput, loaded *processInpu checkedBackends[backend] = struct{}{} } return err - }, Config: cfg, Transcript: loaded.Source, Output: diagnostics.OutputSelection{InputTranscriptPath: input.Transcript, TranscriptPath: input.Output.Value, ReportDir: reportDir, ReportingEnabled: cfg.Reporting.Enabled, ProtectedPaths: loaded.ProtectedPaths, Stdout: stdout}, InitialReports: initial, FailedReports: failed, Debug: debug}) + } + plan, err := preflight.BuildPlan(ctx, cfg, loaded.Source, inspectProfile) + if err != nil { + return nil, err + } + prepared, err := prepareOutput(ctx, plan, diagnostics.OutputSelection{InputTranscriptPath: input.Transcript, TranscriptPath: input.Output.Value, ReportDir: reportDir, ReportingEnabled: cfg.Reporting.Enabled, ProtectedPaths: loaded.ProtectedPaths, Stdout: stdout}, initial, failed, debug) if err != nil { return nil, err } diff --git a/internal/cli/process_pipeline.go b/internal/cli/process_pipeline.go index 96d82f1..a6214f1 100644 --- a/internal/cli/process_pipeline.go +++ b/internal/cli/process_pipeline.go @@ -17,7 +17,7 @@ import ( func executePipeline(ctx context.Context, loaded *processInputs, prepared *preparedProcess, normalized *schema.Transcript, warn func(error), progress func(string)) (processResult, error) { cfg := &loaded.Configuration.Config.Application - specs := prepared.Prepared.Specs + specs := prepared.Prepared.Plan.Specs debug := prepared.Prepared.Debug evidence := runner.EvidenceSelection{Reports: cfg.Reporting.Enabled, Debug: debug != nil} var observer *llm.ObservationCollector @@ -62,7 +62,7 @@ func executePipeline(ctx context.Context, loaded *processInputs, prepared *prepa interactions = writer } output, runErr := runner.New(modules.NewFactory()).Run(ctx, runner.RunInput{ - Config: cfg, Transcript: normalized, ModuleSpecs: specs, + Sections: prepared.Prepared.Plan.Sections, Transcript: normalized, ModuleSpecs: specs, Interactions: interactions, Evidence: &evidence, Progress: runnerProgress(progress), }) if debug != nil { diff --git a/internal/cli/process_prepare_output.go b/internal/cli/process_prepare_output.go new file mode 100644 index 0000000..efe34b3 --- /dev/null +++ b/internal/cli/process_prepare_output.go @@ -0,0 +1,55 @@ +package cli + +import ( + "context" + "errors" + + "gitea.maximumdirect.net/eric/audita/v4/internal/core/diagnostics" + "gitea.maximumdirect.net/eric/audita/v4/internal/framework/preflight" +) + +type debugInput struct { + WorkDir string + RunID string + Metadata diagnostics.InvocationMetadata + EffectiveConfig []byte +} + +type preparedOutput struct { + Plan *preflight.Plan + Output *diagnostics.OutputSession + Debug *diagnostics.RunDirectory + Warnings []error +} + +func prepareOutput(ctx context.Context, plan *preflight.Plan, selection diagnostics.OutputSelection, initial diagnostics.ReportBundle, failed diagnostics.ReportRenderer, debug *debugInput) (*preparedOutput, error) { + checked, err := diagnostics.CheckOutput(selection) + if err != nil { + return nil, err + } + if err := ctx.Err(); err != nil { + return nil, err + } + session := diagnostics.NewOutputSession(checked) + if err := session.Prepare(); err != nil { + return nil, err + } + if err := ctx.Err(); err != nil { + return nil, errors.Join(err, session.Close()) + } + if err := session.Initialize(ctx, initial, failed); err != nil { + return nil, errors.Join(err, session.Close()) + } + cancelOutput := func(err error) error { return session.Finish(ctx, err, nil, failed) } + if err := ctx.Err(); err != nil { + return nil, cancelOutput(err) + } + result := &preparedOutput{Plan: plan, Output: session} + if debug != nil { + result.Debug, result.Warnings = diagnostics.PrepareDebug(debug.WorkDir, debug.RunID, debug.Metadata, debug.EffectiveConfig) + } + if err := ctx.Err(); err != nil { + return nil, cancelOutput(err) + } + return result, nil +} diff --git a/internal/framework/preflight/plan.go b/internal/framework/preflight/plan.go new file mode 100644 index 0000000..0a2423b --- /dev/null +++ b/internal/framework/preflight/plan.go @@ -0,0 +1,75 @@ +package preflight + +import ( + "context" + "errors" + "fmt" + + "gitea.maximumdirect.net/eric/audita/v4/internal/core/chunking" + "gitea.maximumdirect.net/eric/audita/v4/internal/core/config" + "gitea.maximumdirect.net/eric/audita/v4/internal/core/normalization" + "gitea.maximumdirect.net/eric/audita/v4/internal/core/schema" + "gitea.maximumdirect.net/eric/audita/v4/internal/framework/contracts" +) + +// Plan holds the local processing decisions for one invocation. +type Plan struct { + Config *config.Config + Specs []contracts.ModuleRunSpec + Transcript *schema.Transcript + Summary *normalization.NormalizationSummary + Sections []chunking.Section + Profiles []string +} + +// BuildPlan resolves processing selections, normalizes the input, and fixes its chunks. +func BuildPlan(ctx context.Context, cfg *config.Config, source *schema.SourceTranscript, inspect func(context.Context, string) error) (*Plan, error) { + if cfg == nil { + return nil, fmt.Errorf("application configuration is required") + } + if source == nil { + return nil, fmt.Errorf("transcript is required") + } + var profiles []string + var inspectAndCollect func(context.Context, string) error + if inspect != nil { + inspectAndCollect = func(ctx context.Context, id string) error { + if err := inspect(ctx, id); err != nil { + return err + } + profiles = append(profiles, id) + return nil + } + } + specs, err := ProcessingPlan(ctx, cfg, inspectAndCollect) + if err != nil { + return nil, err + } + if err := ctx.Err(); err != nil { + return nil, err + } + normalizer := normalization.NewNormalizer(normalization.NormalizationConfig{ + MaxSegmentGap: cfg.Normalization.MaxSegmentGap, EllipsisGap: cfg.Normalization.EllipsisGap, + MaxSegmentDuration: cfg.Normalization.MaxSegmentDuration, MaxSegmentTokens: cfg.Normalization.MaxSegmentTokens, + }) + transcript, summary := normalizer.Normalize(source.Canonical()) + if err := ctx.Err(); err != nil { + return nil, fmt.Errorf("normalize transcript: %w", err) + } + chunker := chunking.NewChunker(chunking.ChunkingConfig{ + MaxSectionTokens: cfg.Chunking.MaxSectionTokens, MinSectionTokens: cfg.Chunking.MinSectionTokens, + TargetSections: cfg.Chunking.TargetSections, + }) + sections, err := chunker.ChunkTranscript(transcript) + if err != nil { + var infeasible *chunking.InfeasibleTargetError + if errors.As(err, &infeasible) { + return nil, &SelectionError{Cause: fmt.Errorf("chunk normalized transcript: %w", err)} + } + return nil, fmt.Errorf("chunk normalized transcript: %w", err) + } + if err := ctx.Err(); err != nil { + return nil, fmt.Errorf("chunk normalized transcript: %w", err) + } + return &Plan{Config: cfg, Specs: specs, Transcript: transcript, Summary: summary, Sections: sections, Profiles: profiles}, nil +} diff --git a/internal/framework/preflight/plan_test.go b/internal/framework/preflight/plan_test.go new file mode 100644 index 0000000..9590954 --- /dev/null +++ b/internal/framework/preflight/plan_test.go @@ -0,0 +1,73 @@ +package preflight + +import ( + "context" + "errors" + "slices" + "strings" + "testing" + + "gitea.maximumdirect.net/eric/audita/v4/internal/core/chunking" + "gitea.maximumdirect.net/eric/audita/v4/internal/core/config" + "gitea.maximumdirect.net/eric/audita/v4/internal/core/schema" +) + +func TestBuildPlanResolvesProfilesAndChunks(t *testing.T) { + proposal, validation, repair, unused := "proposal", "validation", "repair", "unused" + cfg := &config.Config{ + Chunking: config.Chunking{MaxSectionTokens: 100}, + Pipeline: config.Pipeline{Stages: []config.Stage{ + {Module: "grammar", LLM: config.LLM{ProposalProfile: &proposal, ValidationProfile: &validation, CorrectionRepairProfile: &unused}}, + {Module: "grammar", LLM: config.LLM{ProposalProfile: &validation, ValidationProfile: &proposal, CorrectionRepairProfile: &repair, CorrectionRepairAttempts: 1}}, + }}, + } + source := &schema.SourceTranscript{Segments: []schema.SourceSegment{{Speaker: "A", Start: 0, End: 1, Text: "hello"}, {Speaker: "B", Start: 2, End: 3, Text: "world"}}} + var inspected []string + plan, err := BuildPlan(context.Background(), cfg, source, func(_ context.Context, id string) error { inspected = append(inspected, id); return nil }) + if err != nil { + t.Fatal(err) + } + if !slices.Equal(plan.Profiles, []string{proposal, validation, repair}) || !slices.Equal(plan.Profiles, inspected) { + t.Fatalf("profiles %v, inspected %v", plan.Profiles, inspected) + } + if len(plan.Specs) != 2 || len(plan.Transcript.Segments) != 2 || plan.Summary.InputSegmentCount != 2 || len(plan.Sections) != 1 || plan.Sections[0].StartSegmentID != 1 || plan.Sections[0].EndSegmentID != 2 { + t.Fatalf("unexpected plan: %+v", plan) + } + count := 3 + cfg.Chunking.TargetSections = &count + _, err = BuildPlan(context.Background(), cfg, source, func(context.Context, string) error { return nil }) + var selection *SelectionError + var infeasible *chunking.InfeasibleTargetError + if !errors.As(err, &selection) || !errors.As(err, &infeasible) { + t.Fatalf("expected input selection failure, got %v", err) + } +} + +func TestBuildPlanEmptyPipeline(t *testing.T) { + cfg := &config.Config{Chunking: config.Chunking{MaxSectionTokens: 100}} + plan, err := BuildPlan(context.Background(), cfg, &schema.SourceTranscript{Segments: []schema.SourceSegment{{Speaker: "A", Text: "hello"}}}, nil) + if err != nil || len(plan.Profiles) != 0 || len(plan.Specs) != 0 || len(plan.Sections) != 1 { + t.Fatalf("plan %+v, error %v", plan, err) + } +} + +func TestBuildPlanRetainsNormalizedContentAndGuidance(t *testing.T) { + profile := "selected" + cfg := &config.Config{ + Chunking: config.Chunking{MaxSectionTokens: 100}, + Normalization: config.Normalization{MaxSegmentGap: 2, EllipsisGap: 2, MaxSegmentDuration: 10, MaxSegmentTokens: 100}, + GlossaryCollections: map[string]config.GlossaryCollection{"terms": {Instruction: "Use the shared vocabulary", Entries: []config.GlossaryEntry{{ID: "one", Name: "Example"}}}}, + Pipeline: config.Pipeline{Stages: []config.Stage{{Module: "glossary", Glossaries: []string{"terms"}, LLM: config.LLM{ProposalProfile: &profile, ValidationProfile: &profile}}}}, + } + source := &schema.SourceTranscript{Segments: []schema.SourceSegment{{Speaker: "A", Start: 0, End: 1, Text: "hello"}, {Speaker: "A", Start: 1.1, End: 2, Text: "world"}}} + plan, err := BuildPlan(context.Background(), cfg, source, func(context.Context, string) error { return nil }) + if err != nil { + t.Fatal(err) + } + if len(plan.Transcript.Segments) != 1 || plan.Transcript.Segments[0].Text != "hello world" || plan.Summary.MergesPerformed != 1 || len(plan.Sections) != 1 || plan.Sections[0].Segments[0].Text != "hello world" { + t.Fatalf("normalization or chunks: %+v", plan) + } + if !strings.Contains(plan.Specs[0].GlossaryVariables.InstructionsBlock, "Use the shared vocabulary") { + t.Fatalf("guidance missing: %+v", plan.Specs[0]) + } +} diff --git a/internal/framework/preflight/preflight.go b/internal/framework/preflight/preflight.go index d31f753..8c3aa5f 100644 --- a/internal/framework/preflight/preflight.go +++ b/internal/framework/preflight/preflight.go @@ -1,92 +1,16 @@ -// Package preflight checks resolved processing inputs and prepares output resources. +// Package preflight prepares provider-independent processing inputs. package preflight import ( "context" - "errors" "fmt" "slices" "gitea.maximumdirect.net/eric/audita/v4/internal/core/config" - "gitea.maximumdirect.net/eric/audita/v4/internal/core/diagnostics" "gitea.maximumdirect.net/eric/audita/v4/internal/core/modulecatalog" - "gitea.maximumdirect.net/eric/audita/v4/internal/core/schema" "gitea.maximumdirect.net/eric/audita/v4/internal/framework/contracts" ) -// Input contains already acquired application and transcript inputs. -type Input struct { - InspectProfile func(context.Context, string) error - Config *config.Config - Transcript *schema.SourceTranscript - Output diagnostics.OutputSelection - InitialReports diagnostics.ReportBundle - FailedReports diagnostics.ReportRenderer - Debug *DebugInput -} - -type DebugInput struct { - WorkDir string - RunID string - Metadata diagnostics.InvocationMetadata - EffectiveConfig []byte -} - -type Prepared struct { - Specs []contracts.ModuleRunSpec - Output *diagnostics.OutputSession - Debug *diagnostics.RunDirectory - Warnings []error -} - -// Prepare validates invocation inputs and collisions before acquiring outputs. -func Prepare(ctx context.Context, input Input) (*Prepared, error) { - if err := ctx.Err(); err != nil { - return nil, err - } - if input.Config == nil { - return nil, fmt.Errorf("application configuration is required") - } - if input.Transcript == nil { - return nil, fmt.Errorf("transcript is required") - } - specs, err := ProcessingPlan(ctx, input.Config, input.InspectProfile) - if err != nil { - return nil, err - } - checked, err := diagnostics.CheckOutput(input.Output) - if err != nil { - return nil, err - } - if err := ctx.Err(); err != nil { - return nil, err - } - session := diagnostics.NewOutputSession(checked) - if err := session.Prepare(); err != nil { - return nil, err - } - if err := ctx.Err(); err != nil { - return nil, errors.Join(err, session.Close()) - } - if err := session.Initialize(ctx, input.InitialReports, input.FailedReports); err != nil { - return nil, errors.Join(err, session.Close()) - } - cancelOutput := func(err error) error { - return session.Finish(ctx, err, nil, input.FailedReports) - } - if err := ctx.Err(); err != nil { - return nil, cancelOutput(err) - } - result := &Prepared{Specs: specs, Output: session} - if input.Debug != nil { - result.Debug, result.Warnings = diagnostics.PrepareDebug(input.Debug.WorkDir, input.Debug.RunID, input.Debug.Metadata, input.Debug.EffectiveConfig) - } - if err := ctx.Err(); err != nil { - return nil, cancelOutput(err) - } - return result, nil -} - // SelectionError indicates that resolved operator settings cannot be used for processing. type SelectionError struct{ Cause error } diff --git a/internal/framework/preflight/preflight_test.go b/internal/framework/preflight/preflight_test.go deleted file mode 100644 index 2c4ce4f..0000000 --- a/internal/framework/preflight/preflight_test.go +++ /dev/null @@ -1,48 +0,0 @@ -package preflight - -import ( - "context" - "os" - "path/filepath" - "testing" - - "gitea.maximumdirect.net/eric/audita/v4/internal/core/config" - "gitea.maximumdirect.net/eric/audita/v4/internal/core/diagnostics" - "gitea.maximumdirect.net/eric/audita/v4/internal/core/schema" -) - -func TestReadinessAndCollisionPrecedeOutputPreparation(t *testing.T) { - dir := t.TempDir() - output := filepath.Join(dir, "output.json") - if _, err := Prepare(context.Background(), Input{Config: &config.Config{}, Output: diagnostics.OutputSelection{TranscriptPath: output}}); err == nil { - t.Fatal("missing transcript accepted") - } - if _, err := os.Stat(output); !os.IsNotExist(err) { - t.Fatalf("output created: %v", err) - } - if _, err := Prepare(context.Background(), Input{Config: &config.Config{}, Transcript: &schema.SourceTranscript{}, Output: diagnostics.OutputSelection{TranscriptPath: output, ProtectedPaths: []string{output}}}); err == nil { - t.Fatal("collision accepted") - } - entries, err := os.ReadDir(dir) - if err != nil || len(entries) != 0 { - t.Fatalf("prepared before check: %v %v", entries, err) - } -} - -func TestOptionalDebugFailureDoesNotPreventPreparation(t *testing.T) { - dir := t.TempDir() - blocked := filepath.Join(dir, "file") - if err := os.WriteFile(blocked, []byte("x"), 0600); err != nil { - t.Fatal(err) - } - result, err := Prepare(context.Background(), Input{Config: &config.Config{}, Transcript: &schema.SourceTranscript{}, Output: diagnostics.OutputSelection{TranscriptPath: filepath.Join(dir, "output")}, Debug: &DebugInput{WorkDir: blocked, RunID: "run"}}) - if err != nil { - t.Fatal(err) - } - if len(result.Warnings) == 0 || result.Debug != nil { - t.Fatalf("debug=%v warnings=%v", result.Debug, result.Warnings) - } - if err := result.Output.Close(); err != nil { - t.Fatal(err) - } -} diff --git a/internal/framework/preflight/readiness_test.go b/internal/framework/preflight/readiness_test.go index f17c520..6caa7af 100644 --- a/internal/framework/preflight/readiness_test.go +++ b/internal/framework/preflight/readiness_test.go @@ -4,35 +4,28 @@ import ( "context" "errors" "fmt" - "os" - "path/filepath" "slices" "strings" "testing" "gitea.maximumdirect.net/eric/audita/v4/internal/core/config" - "gitea.maximumdirect.net/eric/audita/v4/internal/core/diagnostics" "gitea.maximumdirect.net/eric/audita/v4/internal/core/schema" ) -func TestLaterEmptyGlossaryFailsBeforeOutputPreparation(t *testing.T) { +func TestLaterEmptyGlossaryFailsBeforeProfileInspection(t *testing.T) { profile, id := "selected", "spells" cfg := &config.Config{Pipeline: config.Pipeline{Stages: []config.Stage{ {Module: "grammar", LLM: config.LLM{ProposalProfile: &profile, ValidationProfile: &profile}}, {Module: "glossary", ID: &id, Glossaries: []string{"empty"}, LLM: config.LLM{ProposalProfile: &profile, ValidationProfile: &profile}}, }}} - output := filepath.Join(t.TempDir(), "transcript.json") calls := 0 - _, err := Prepare(context.Background(), Input{Config: cfg, Transcript: &schema.SourceTranscript{}, Output: diagnostics.OutputSelection{TranscriptPath: output}, InspectProfile: func(context.Context, string) error { calls++; return nil }}) + _, err := BuildPlan(context.Background(), cfg, &schema.SourceTranscript{}, func(context.Context, string) error { calls++; return nil }) if err == nil || !strings.Contains(err.Error(), "stage 2") || !strings.Contains(err.Error(), "spells") || !strings.Contains(err.Error(), "empty") { t.Fatalf("unexpected error: %v", err) } if calls != 0 { t.Fatal("inspected profiles before checking all glossary selections") } - if _, err := os.Stat(output); !os.IsNotExist(err) { - t.Fatalf("output exists: %v", err) - } } func TestEmptyPipelineNeedsNoProfile(t *testing.T) { @@ -54,14 +47,10 @@ func TestCorrectionRepairReadinessDependsOnBudget(t *testing.T) { t.Fatal(err) } cfg.Pipeline.Stages[0].LLM.CorrectionRepairAttempts = 1 - output := filepath.Join(t.TempDir(), "transcript.json") - _, err := Prepare(context.Background(), Input{Config: cfg, Transcript: &schema.SourceTranscript{}, Output: diagnostics.OutputSelection{TranscriptPath: output}, InspectProfile: inspect}) + _, err := BuildPlan(context.Background(), cfg, &schema.SourceTranscript{}, inspect) if err == nil || !strings.Contains(err.Error(), "correction repair") { t.Fatalf("readiness error: %v", err) } - if _, err := os.Stat(output); !os.IsNotExist(err) { - t.Fatalf("output exists: %v", err) - } } func TestProcessingPlanReusesOnlyMatchingGlossaryViews(t *testing.T) { diff --git a/internal/framework/processreport/partial_validation_test.go b/internal/framework/processreport/partial_validation_test.go index 54e48e4..d17e06a 100644 --- a/internal/framework/processreport/partial_validation_test.go +++ b/internal/framework/processreport/partial_validation_test.go @@ -8,6 +8,7 @@ import ( "strings" "testing" + "gitea.maximumdirect.net/eric/audita/v4/internal/core/chunking" "gitea.maximumdirect.net/eric/audita/v4/internal/core/config" "gitea.maximumdirect.net/eric/audita/v4/internal/core/schema" "gitea.maximumdirect.net/eric/audita/v4/internal/framework/contracts" @@ -73,7 +74,7 @@ func TestFatalBatchRetainsEarlierDecisionsInLedger(t *testing.T) { client := &interruptedValidationClient{cause: origin} cfg := config.Config{Chunking: config.Chunking{MaxSectionTokens: 8192, MinSectionTokens: 1}, Validation: config.Validation{MaxPromptTokens: 150}} result, err := runner.New(partialModule{validator}).Run(context.Background(), runner.RunInput{ - Config: &cfg, Transcript: &schema.Transcript{Segments: []schema.Segment{{ID: 1, Text: "hello"}}}, + Sections: []chunking.Section{{Index: 0, StartSegmentID: 1, EndSegmentID: 1, Segments: []schema.Segment{{ID: 1, Text: "hello"}}}}, Transcript: &schema.Transcript{Segments: []schema.Segment{{ID: 1, Text: "hello"}}}, ModuleSpecs: []contracts.ModuleRunSpec{{ModuleKey: "grammar", InstanceName: "grammar", ValidationClient: client, Settings: config.Stage{Validation: cfg.Validation}}}, Evidence: &runner.EvidenceSelection{Reports: true, Debug: true}, }) if !errors.Is(err, origin) || client.calls != 3 { diff --git a/internal/framework/runner/cancellation_test.go b/internal/framework/runner/cancellation_test.go index bd3bb39..711e17b 100644 --- a/internal/framework/runner/cancellation_test.go +++ b/internal/framework/runner/cancellation_test.go @@ -165,9 +165,9 @@ func TestValidatorFailureCancelsActiveAndPendingProviderWork(t *testing.T) { func TestCanceledEmptyPipelineReturnsCancellation(t *testing.T) { ctx, cancel := context.WithCancel(context.Background()) cancel() - out, err := New(fakeFactory{}).Run(ctx, RunInput{ + out, err := New(fakeFactory{}).Run(ctx, preparedTestInput(testRunInput{ Transcript: &schema.Transcript{Segments: []schema.Segment{{ID: 71, Text: "original"}}}, - }) + })) if !errors.Is(err, context.Canceled) || out.FinalTranscript == nil || out.FinalTranscript.Segments[0].Text != "original" { t.Fatalf("canceled entry: result=%+v error=%v", out, err) } @@ -205,11 +205,11 @@ func TestRunnerRetainsLaterProposalEvidenceWhenEarlierSectionFails(t *testing.T) cfg := runnerTestConfig() cfg.Chunking.MaxSectionTokens = 3 cfg.Chunking.MinSectionTokens = 0 - out, err := New(fakeFactory{modules: map[string]contracts.TranscriptModule{"grammar": module}}).Run(ctx, RunInput{ + out, err := New(fakeFactory{modules: map[string]contracts.TranscriptModule{"grammar": module}}).Run(ctx, preparedTestInput(testRunInput{ Config: &cfg, Evidence: &EvidenceSelection{Reports: true, Debug: true}, Transcript: &schema.Transcript{Segments: []schema.Segment{{ID: 71, Text: "original text"}, {ID: 93, Text: "other text"}}}, ModuleSpecs: []contracts.ModuleRunSpec{{ModuleKey: "grammar", InstanceName: "grammar"}}, - }) + })) if !errors.Is(err, origin) || len(out.Candidates) != 1 || len(out.WorkUnits) != 2 { t.Fatalf("interrupted evidence: candidates=%+v work=%+v error=%v", out.Candidates, out.WorkUnits, err) } @@ -243,10 +243,10 @@ func TestRunnerCancellationAfterApprovalKeepsCommittedModuleText(t *testing.T) { "first": fakeModule{key: "first", policy: proposals.ReplacementPolicyRequireUnique, proposeF: propose("teh", "the")}, "second": fakeModule{key: "second", policy: proposals.ReplacementPolicyRequireUnique, proposeF: propose("cat", "dog"), validators: []validators.Validator{last}}, }}) - out, err := r.Run(ctx, RunInput{ + out, err := r.Run(ctx, preparedTestInput(testRunInput{ Transcript: &schema.Transcript{Segments: []schema.Segment{{ID: 1, Text: "teh cat"}}}, ModuleSpecs: []contracts.ModuleRunSpec{{ModuleKey: "first", InstanceName: "first"}, {Index: 1, ModuleKey: "second", InstanceName: "second"}}, - }) + })) var failure *ExecutionFailure if !errors.Is(err, context.Canceled) || !errors.As(err, &failure) || failure.Origin == nil || *failure.Origin.StageIndex != 1 || len(out.ModuleResults) != 2 || out.ModuleResults[0].Status != ModuleStatusSuccess || out.ModuleResults[1].Status != ModuleStatusFailed || diff --git a/internal/framework/runner/evidence_test.go b/internal/framework/runner/evidence_test.go index 807de90..419ecf0 100644 --- a/internal/framework/runner/evidence_test.go +++ b/internal/framework/runner/evidence_test.go @@ -50,9 +50,9 @@ func evidenceFixture(size int) (*Runner, RunInput) { }, nil }, } - return New(fakeFactory{modules: map[string]contracts.TranscriptModule{"grammar": module}}), RunInput{ + return New(fakeFactory{modules: map[string]contracts.TranscriptModule{"grammar": module}}), preparedTestInput(testRunInput{ Config: &cfg, Transcript: transcript, ModuleSpecs: []contracts.ModuleRunSpec{{ModuleKey: "grammar", InstanceName: "grammar"}}, - } + }) } func TestEvidenceSelectionKeepsTotalsAndRequestedRecords(t *testing.T) { diff --git a/internal/framework/runner/ordered_workflow_test.go b/internal/framework/runner/ordered_workflow_test.go index 9f69825..a18ef25 100644 --- a/internal/framework/runner/ordered_workflow_test.go +++ b/internal/framework/runner/ordered_workflow_test.go @@ -51,7 +51,7 @@ func TestOrderedWorkflowUsesIndependentSelectionsAndPriorEdits(t *testing.T) { {Module: "grammar", Glossaries: []string{"party", "spells"}, ProtectedTerms: []string{"party", "spells"}}, }}} seen := make(chan contracts.ProposalRequest, 3) - output, err := New(orderedFactory{seen: seen}).Run(context.Background(), RunInput{Transcript: &schema.Transcript{Segments: []schema.Segment{{ID: 1, Text: "party spell"}}}, ModuleSpecs: contracts.ResolveModuleRunSpecs(cfg)}) + output, err := New(orderedFactory{seen: seen}).Run(context.Background(), preparedTestInput(testRunInput{Transcript: &schema.Transcript{Segments: []schema.Segment{{ID: 1, Text: "party spell"}}}, ModuleSpecs: contracts.ResolveModuleRunSpecs(cfg)})) if err != nil { t.Fatal(err) } diff --git a/internal/framework/runner/prepared_input_test.go b/internal/framework/runner/prepared_input_test.go new file mode 100644 index 0000000..2b62781 --- /dev/null +++ b/internal/framework/runner/prepared_input_test.go @@ -0,0 +1,30 @@ +package runner + +import ( + "gitea.maximumdirect.net/eric/audita/v4/internal/core/chunking" + "gitea.maximumdirect.net/eric/audita/v4/internal/core/config" + "gitea.maximumdirect.net/eric/audita/v4/internal/core/schema" + "gitea.maximumdirect.net/eric/audita/v4/internal/framework/contracts" + "gitea.maximumdirect.net/eric/audita/v4/internal/framework/structuredoutput" +) + +type testRunInput struct { + Config *config.Config + Transcript *schema.Transcript + ModuleSpecs []contracts.ModuleRunSpec + Interactions structuredoutput.InteractionSink + Evidence *EvidenceSelection + Progress func(Progress) +} + +func preparedTestInput(input testRunInput) RunInput { + cfg := chunking.ChunkingConfig{MaxSectionTokens: int(^uint(0) >> 1)} + if input.Config != nil { + cfg = chunking.ChunkingConfig{MaxSectionTokens: input.Config.Chunking.MaxSectionTokens, MinSectionTokens: input.Config.Chunking.MinSectionTokens, TargetSections: input.Config.Chunking.TargetSections} + } + sections, err := chunking.NewChunker(cfg).ChunkTranscript(input.Transcript) + if err != nil { + panic(err) + } + return RunInput{Sections: sections, Transcript: input.Transcript, ModuleSpecs: input.ModuleSpecs, Interactions: input.Interactions, Evidence: input.Evidence, Progress: input.Progress} +} diff --git a/internal/framework/runner/repair_test.go b/internal/framework/runner/repair_test.go index ecdd0ad..1fe97c6 100644 --- a/internal/framework/runner/repair_test.go +++ b/internal/framework/runner/repair_test.go @@ -219,13 +219,13 @@ func TestRunnerChecksRepairCapabilityBeforeSubmittingProposals(t *testing.T) { return contracts.ProposalResult{}, nil }}} r := New(fakeFactory{modules: map[string]contracts.TranscriptModule{"grammar": module}}) - out, err := r.Run(context.Background(), RunInput{ + out, err := r.Run(context.Background(), preparedTestInput(testRunInput{ Transcript: &schema.Transcript{Segments: []schema.Segment{{ID: 1, Text: "cat"}}}, ModuleSpecs: []contracts.ModuleRunSpec{{ ModuleKey: "grammar", InstanceName: "grammar", Settings: config.Stage{LLM: config.LLM{CorrectionRepairAttempts: 1}}, }}, - }) + })) var failure *structuredoutput.Failure if !errors.As(err, &failure) || failure.Class != outcomes.FailureFatal || failure.Reason != outcomes.ReasonSetupFailure || calls != 0 || len(out.WorkUnits) != 1 || out.WorkUnits[0].State != outcomes.WorkNotStarted { @@ -242,7 +242,7 @@ func TestRunnerAppliesRevisionsInOriginalOrder(t *testing.T) { return contracts.ProposalResult{Proposals: candidates, SegmentReferences: []int{1, 1, 1}, Exchange: &structuredoutput.Exchange{}}, nil }}} runner := New(fakeFactory{modules: map[string]contracts.TranscriptModule{"grammar": module}}) - out, err := runner.Run(context.Background(), RunInput{Transcript: &schema.Transcript{Segments: []schema.Segment{{ID: 1, Text: "cat and bird"}}}, ModuleSpecs: []contracts.ModuleRunSpec{{ModuleKey: "grammar", InstanceName: "grammar", RepairCoordinator: client, Settings: config.Stage{LLM: config.LLM{CorrectionRepairAttempts: 1}}}}}) + out, err := runner.Run(context.Background(), preparedTestInput(testRunInput{Transcript: &schema.Transcript{Segments: []schema.Segment{{ID: 1, Text: "cat and bird"}}}, ModuleSpecs: []contracts.ModuleRunSpec{{ModuleKey: "grammar", InstanceName: "grammar", RepairCoordinator: client, Settings: config.Stage{LLM: config.LLM{CorrectionRepairAttempts: 1}}}}})) if err != nil { t.Fatal(err) } @@ -281,13 +281,13 @@ func TestRunnerAttributesApplicationFilteringToEachRepair(t *testing.T) { }, }} r := New(fakeFactory{modules: map[string]contracts.TranscriptModule{"grammar": module}}) - out, err := r.Run(context.Background(), RunInput{ + out, err := r.Run(context.Background(), preparedTestInput(testRunInput{ Transcript: &schema.Transcript{Segments: []schema.Segment{{ID: 1, Text: "cat and bird"}}}, ModuleSpecs: []contracts.ModuleRunSpec{{ ModuleKey: "grammar", InstanceName: "grammar", RepairCoordinator: client, Settings: config.Stage{LLM: config.LLM{CorrectionRepairAttempts: 1}}, }}, - }) + })) if err != nil { t.Fatal(err) } diff --git a/internal/framework/runner/runner.go b/internal/framework/runner/runner.go index fa0dc81..6005c7c 100644 --- a/internal/framework/runner/runner.go +++ b/internal/framework/runner/runner.go @@ -9,7 +9,6 @@ import ( "sync" "gitea.maximumdirect.net/eric/audita/v4/internal/core/chunking" - "gitea.maximumdirect.net/eric/audita/v4/internal/core/config" "gitea.maximumdirect.net/eric/audita/v4/internal/core/glossary" "gitea.maximumdirect.net/eric/audita/v4/internal/core/modulecatalog" "gitea.maximumdirect.net/eric/audita/v4/internal/core/schema" @@ -114,7 +113,7 @@ func selectEvidence(selection *EvidenceSelection) evidenceNeeds { // RunInput is the deterministic runner input. type RunInput struct { - Config *config.Config + Sections []chunking.Section Transcript *schema.Transcript ModuleSpecs []contracts.ModuleRunSpec Interactions structuredoutput.InteractionSink @@ -145,12 +144,8 @@ func (r *Runner) Run(ctx context.Context, input RunInput) (RunOutput, error) { return RunOutput{}, &ExecutionFailure{Phase: "setup", Cause: errors.New("runner module factory is required")} } - working := input.Transcript.Clone() results := make([]ModuleResult, 0, len(input.ModuleSpecs)) - sections, err := chunkWorkingTranscript(input.Config, working) - if err != nil { - return RunOutput{FinalTranscript: working}, &ExecutionFailure{Phase: "chunking", Cause: fmt.Errorf("chunk normalized transcript: %w", err)} - } + sections := input.Sections evidence := selectEvidence(input.Evidence) totals := outcomes.WorkTotals{Total: len(input.ModuleSpecs) * len(sections)} var inventory []contracts.SectionMetadata @@ -1031,41 +1026,6 @@ func reorderValidatorsForPipeline(in []validators.Validator) ([]validators.Valid return ordered, order } -func chunkWorkingTranscript(cfg *config.Config, transcript *schema.Transcript) ([]chunking.Section, error) { - if cfg == nil { - if transcript == nil || len(transcript.Segments) == 0 { - return []chunking.Section{}, nil - } - return []chunking.Section{ - { - Index: 0, - EstimatedTokens: estimateTranscriptTokens(transcript), - Segments: append([]schema.Segment(nil), transcript.Segments...), - StartSegmentID: transcript.Segments[0].ID, - EndSegmentID: transcript.Segments[len(transcript.Segments)-1].ID, - }, - }, nil - } - chunker := chunking.NewChunker(chunking.ChunkingConfig{ - MaxSectionTokens: cfg.Chunking.MaxSectionTokens, - MinSectionTokens: cfg.Chunking.MinSectionTokens, - TargetSections: cfg.Chunking.TargetSections, - }) - return chunker.ChunkTranscript(transcript) -} - -func estimateTranscriptTokens(transcript *schema.Transcript) int { - if transcript == nil || len(transcript.Segments) == 0 { - return 0 - } - estimator := chunking.NewSimpleTokenEstimator() - total := 0 - for _, segment := range transcript.Segments { - total += estimator.EstimateTokens(segment.Text) - } - return total -} - func transcriptFromSection(section chunking.Section) *schema.Transcript { segments := make([]schema.Segment, len(section.Segments)) copy(segments, section.Segments) diff --git a/internal/framework/runner/runner_test.go b/internal/framework/runner/runner_test.go index 73817bf..8fba27e 100644 --- a/internal/framework/runner/runner_test.go +++ b/internal/framework/runner/runner_test.go @@ -88,7 +88,7 @@ func TestRunnerRecoverableProposalFailureAllowsLaterModule(t *testing.T) { return []proposals.CorrectionProposal{{TargetSegmentID: 1, OriginalText: "teh", CorrectedText: "the"}}, nil }} r := New(fakeFactory{modules: map[string]contracts.TranscriptModule{"first": failed, "second": second}}) - out, err := r.Run(context.Background(), RunInput{Transcript: &schema.Transcript{Segments: []schema.Segment{{ID: 1, Text: "teh"}}}, ModuleSpecs: []contracts.ModuleRunSpec{{ModuleKey: "first", InstanceName: "first"}, {ModuleKey: "second", InstanceName: "second"}}}) + out, err := r.Run(context.Background(), preparedTestInput(testRunInput{Transcript: &schema.Transcript{Segments: []schema.Segment{{ID: 1, Text: "teh"}}}, ModuleSpecs: []contracts.ModuleRunSpec{{ModuleKey: "first", InstanceName: "first"}, {ModuleKey: "second", InstanceName: "second"}}})) if err != nil { t.Fatal(err) } @@ -128,7 +128,7 @@ func TestRunnerOnlyFullyValidatedCandidatesApplyAndRecoveriesMerge(t *testing.T) }, Operations: []outcomes.Operation{{Reference: outcomes.Reference{Kind: outcomes.OperationProposal}, Succeeded: true, RecoveryReasons: []outcomes.RecoveryReason{outcomes.RecoveryOutputRepaired}}}}, nil }} r := New(fakeFactory{modules: map[string]contracts.TranscriptModule{"m": module}}) - out, err := r.Run(context.Background(), RunInput{Transcript: &schema.Transcript{Segments: []schema.Segment{{ID: 1, Text: "teh cat"}}}, ModuleSpecs: []contracts.ModuleRunSpec{{ModuleKey: "m", InstanceName: "m"}}}) + out, err := r.Run(context.Background(), preparedTestInput(testRunInput{Transcript: &schema.Transcript{Segments: []schema.Segment{{ID: 1, Text: "teh cat"}}}, ModuleSpecs: []contracts.ModuleRunSpec{{ModuleKey: "m", InstanceName: "m"}}})) if err != nil { t.Fatal(err) } @@ -168,7 +168,7 @@ func TestCandidateCaptureIsExplicitAndIncludesFilteredProposals(t *testing.T) { return []proposals.CorrectionProposal{{TargetSegmentID: 0, OriginalText: "bad", CorrectedText: "good"}}, nil }} r := New(fakeFactory{modules: map[string]contracts.TranscriptModule{"grammar": module}}) - input := RunInput{Transcript: &schema.Transcript{Segments: []schema.Segment{{ID: 1, Text: "bad"}}}, ModuleSpecs: []contracts.ModuleRunSpec{{ModuleKey: "grammar", InstanceName: "grammar"}}} + input := preparedTestInput(testRunInput{Transcript: &schema.Transcript{Segments: []schema.Segment{{ID: 1, Text: "bad"}}}, ModuleSpecs: []contracts.ModuleRunSpec{{ModuleKey: "grammar", InstanceName: "grammar"}}}) without, err := r.Run(context.Background(), input) if err != nil { t.Fatal(err) @@ -272,7 +272,7 @@ func TestRunnerOneModuleAppliesProposal(t *testing.T) { }}, }}) - out, err := r.Run(context.Background(), RunInput{Transcript: transcript, ModuleSpecs: []contracts.ModuleRunSpec{{ModuleKey: "grammar", InstanceName: "grammar"}}}) + out, err := r.Run(context.Background(), preparedTestInput(testRunInput{Transcript: transcript, ModuleSpecs: []contracts.ModuleRunSpec{{ModuleKey: "grammar", InstanceName: "grammar"}}})) if err != nil { t.Fatalf("Run error: %v", err) } @@ -298,7 +298,7 @@ func TestRunnerModulesRunSequentially(t *testing.T) { }}, }}) - out, err := r.Run(context.Background(), RunInput{Transcript: transcript, ModuleSpecs: []contracts.ModuleRunSpec{{ModuleKey: "m1", InstanceName: "m1"}, {ModuleKey: "m2", InstanceName: "m2"}}}) + out, err := r.Run(context.Background(), preparedTestInput(testRunInput{Transcript: transcript, ModuleSpecs: []contracts.ModuleRunSpec{{ModuleKey: "m1", InstanceName: "m1"}, {ModuleKey: "m2", InstanceName: "m2"}}})) if err != nil { t.Fatalf("Run error: %v", err) } @@ -344,7 +344,7 @@ func TestRunnerKeepsSectionMembershipAfterTextGrowth(t *testing.T) { return nil, nil }}, }}) - out, err := r.Run(context.Background(), RunInput{Config: &cfg, Transcript: transcript, ModuleSpecs: []contracts.ModuleRunSpec{{ModuleKey: "grow", InstanceName: "grow"}, {ModuleKey: "inspect", InstanceName: "inspect"}}}) + out, err := r.Run(context.Background(), preparedTestInput(testRunInput{Config: &cfg, Transcript: transcript, ModuleSpecs: []contracts.ModuleRunSpec{{ModuleKey: "grow", InstanceName: "grow"}, {ModuleKey: "inspect", InstanceName: "inspect"}}})) if err != nil { t.Fatal(err) } @@ -368,23 +368,18 @@ func TestRunnerKeepsSectionMembershipAfterTextGrowth(t *testing.T) { } } -func TestRunnerInventoriesEmptyWorkAndRejectsImpossibleChunking(t *testing.T) { +func TestRunnerInventoriesEmptyWork(t *testing.T) { r := New(fakeFactory{modules: map[string]contracts.TranscriptModule{}}) - empty, err := r.Run(context.Background(), RunInput{Transcript: &schema.Transcript{}}) + empty, err := r.Run(context.Background(), preparedTestInput(testRunInput{Transcript: &schema.Transcript{}})) if err != nil || len(empty.Sections) != 0 || len(empty.WorkUnits) != 0 || len(empty.FinalTranscript.Segments) != 0 { t.Fatalf("empty transcript and pipeline: %+v, %v", empty, err) } input := &schema.Transcript{Segments: []schema.Segment{{ID: 1, Text: "one"}, {ID: 2, Text: "two"}}} - noModules, err := r.Run(context.Background(), RunInput{Transcript: input}) + noModules, err := r.Run(context.Background(), preparedTestInput(testRunInput{Transcript: input})) if err != nil || len(noModules.Sections) != 1 || len(noModules.WorkUnits) != 0 || len(noModules.FinalTranscript.Segments) != 2 { t.Fatalf("empty pipeline inventory: %+v, %v", noModules, err) } - cfg := runnerTestConfig() - target := 3 - cfg.Chunking.TargetSections = &target - if _, err := r.Run(context.Background(), RunInput{Config: &cfg, Transcript: input}); err == nil { - t.Fatal("impossible section target was accepted") - } + } func TestRunnerProposalsExecutePerChunkSection(t *testing.T) { @@ -416,13 +411,13 @@ func TestRunnerProposalsExecutePerChunkSection(t *testing.T) { }}, }}) - out, err := r.Run(context.Background(), RunInput{ + out, err := r.Run(context.Background(), preparedTestInput(testRunInput{ Config: &cfg, Transcript: transcript, ModuleSpecs: []contracts.ModuleRunSpec{ {ModuleKey: "m", InstanceName: "m"}, }, - }) + })) if err != nil { t.Fatalf("Run error: %v", err) } @@ -516,13 +511,13 @@ func TestRunnerValidationStartsBeforeAllSectionProposalsComplete(t *testing.T) { resultCh := make(chan error, 1) go func() { - _, err := r.Run(context.Background(), RunInput{ + _, err := r.Run(context.Background(), preparedTestInput(testRunInput{ Config: &cfg, Transcript: transcript, ModuleSpecs: []contracts.ModuleRunSpec{ {ModuleKey: "m", InstanceName: "m"}, }, - }) + })) resultCh <- err }() @@ -545,7 +540,7 @@ func TestRunnerSkippedRecorded(t *testing.T) { return []proposals.CorrectionProposal{{TargetSegmentID: 1, OriginalText: "word", CorrectedText: "term"}}, nil }}, }}) - out, err := r.Run(context.Background(), RunInput{Transcript: transcript, ModuleSpecs: []contracts.ModuleRunSpec{{ModuleKey: "m", InstanceName: "m"}}}) + out, err := r.Run(context.Background(), preparedTestInput(testRunInput{Transcript: transcript, ModuleSpecs: []contracts.ModuleRunSpec{{ModuleKey: "m", InstanceName: "m"}}})) if err != nil { t.Fatalf("Run error: %v", err) } @@ -566,7 +561,7 @@ func TestRunnerFailureReturnsPartialProgress(t *testing.T) { }}, }}) - out, err := r.Run(context.Background(), RunInput{Transcript: transcript, ModuleSpecs: []contracts.ModuleRunSpec{{ModuleKey: "m1", InstanceName: "m1"}, {Index: 1, ModuleKey: "m2", InstanceName: "m2"}}}) + out, err := r.Run(context.Background(), preparedTestInput(testRunInput{Transcript: transcript, ModuleSpecs: []contracts.ModuleRunSpec{{ModuleKey: "m1", InstanceName: "m1"}, {Index: 1, ModuleKey: "m2", InstanceName: "m2"}}})) var failure *ExecutionFailure if !errors.Is(err, origin) || !errors.As(err, &failure) || failure.Phase != "proposal" || !failure.HasSection || *failure.Origin.StageIndex != 1 || failure.Origin.ModuleInstance != "m2" || failure.Origin.SectionIndex != 0 { @@ -589,7 +584,7 @@ func TestRunnerDoesNotMutateInputTranscript(t *testing.T) { }}, }}) - _, err := r.Run(context.Background(), RunInput{Config: ptrConfig(runnerTestConfig()), Transcript: transcript, ModuleSpecs: []contracts.ModuleRunSpec{{ModuleKey: "m", InstanceName: "m"}}}) + _, err := r.Run(context.Background(), preparedTestInput(testRunInput{Config: ptrConfig(runnerTestConfig()), Transcript: transcript, ModuleSpecs: []contracts.ModuleRunSpec{{ModuleKey: "m", InstanceName: "m"}}})) if err != nil { t.Fatalf("Run error: %v", err) } @@ -625,7 +620,7 @@ func TestRunnerValidatorApprovedProposalApplied(t *testing.T) { }, }}) - out, err := r.Run(context.Background(), RunInput{Transcript: transcript, ModuleSpecs: []contracts.ModuleRunSpec{{ModuleKey: "m", InstanceName: "m"}}}) + out, err := r.Run(context.Background(), preparedTestInput(testRunInput{Transcript: transcript, ModuleSpecs: []contracts.ModuleRunSpec{{ModuleKey: "m", InstanceName: "m"}}})) if err != nil { t.Fatalf("Run error: %v", err) } @@ -651,7 +646,7 @@ func TestRunnerValidatorRejectedProposalNotApplied(t *testing.T) { return []proposals.CorrectionProposal{{TargetSegmentID: 1, OriginalText: "teh", CorrectedText: "the"}}, nil }}, }}) - out, err := r.Run(context.Background(), RunInput{Transcript: transcript, ModuleSpecs: []contracts.ModuleRunSpec{{ModuleKey: "m", InstanceName: "m"}}}) + out, err := r.Run(context.Background(), preparedTestInput(testRunInput{Transcript: transcript, ModuleSpecs: []contracts.ModuleRunSpec{{ModuleKey: "m", InstanceName: "m"}}})) if err != nil { t.Fatalf("Run error: %v", err) } @@ -692,7 +687,7 @@ func TestRunnerMultipleValidatorsRunInOrderAndFilterSurvivors(t *testing.T) { }}, }}) - out, err := r.Run(context.Background(), RunInput{Transcript: transcript, ModuleSpecs: []contracts.ModuleRunSpec{{ModuleKey: "m", InstanceName: "m"}}}) + out, err := r.Run(context.Background(), preparedTestInput(testRunInput{Transcript: transcript, ModuleSpecs: []contracts.ModuleRunSpec{{ModuleKey: "m", InstanceName: "m"}}})) if err != nil { t.Fatalf("Run error: %v", err) } @@ -715,7 +710,7 @@ func TestRunnerValidatorCardinalityErrorStopsPipelineWithPartialProgress(t *test }} r := New(fakeFactory{modules: map[string]contracts.TranscriptModule{"m1": good, "m2": bad}}) - out, err := r.Run(context.Background(), RunInput{Transcript: transcript, ModuleSpecs: []contracts.ModuleRunSpec{{ModuleKey: "m1", InstanceName: "m1"}, {ModuleKey: "m2", InstanceName: "m2"}}}) + out, err := r.Run(context.Background(), preparedTestInput(testRunInput{Transcript: transcript, ModuleSpecs: []contracts.ModuleRunSpec{{ModuleKey: "m1", InstanceName: "m1"}, {ModuleKey: "m2", InstanceName: "m2"}}})) if err == nil { t.Fatal("expected cardinality error") } @@ -743,7 +738,7 @@ func TestRunnerApplicationSkipAfterValidatorApprovalReported(t *testing.T) { }, }, }}) - out, err := r.Run(context.Background(), RunInput{Transcript: transcript, ModuleSpecs: []contracts.ModuleRunSpec{{ModuleKey: "m", InstanceName: "m"}}}) + out, err := r.Run(context.Background(), preparedTestInput(testRunInput{Transcript: transcript, ModuleSpecs: []contracts.ModuleRunSpec{{ModuleKey: "m", InstanceName: "m"}}})) if err != nil { t.Fatalf("Run error: %v", err) } @@ -777,7 +772,7 @@ func TestRunnerApplyConflictAfterTwoInitiallyValidDeletions(t *testing.T) { }, }, }}) - out, err := r.Run(context.Background(), RunInput{Transcript: transcript, ModuleSpecs: []contracts.ModuleRunSpec{{ModuleKey: "m", InstanceName: "m"}}, Evidence: &EvidenceSelection{Reports: true, Debug: true}}) + out, err := r.Run(context.Background(), preparedTestInput(testRunInput{Transcript: transcript, ModuleSpecs: []contracts.ModuleRunSpec{{ModuleKey: "m", InstanceName: "m"}}, Evidence: &EvidenceSelection{Reports: true, Debug: true}})) if err != nil { t.Fatal(err) } @@ -833,11 +828,11 @@ func TestRunnerLLMValidatorApprovalApplied(t *testing.T) { }}, }}) cfg := runnerTestConfig() - out, err := r.Run(context.Background(), RunInput{ + out, err := r.Run(context.Background(), preparedTestInput(testRunInput{ Config: &cfg, Transcript: &schema.Transcript{Segments: []schema.Segment{{ID: 1, Text: "There were gestures at the temple."}}}, ModuleSpecs: []contracts.ModuleRunSpec{{ModuleKey: "m", InstanceName: "m", ValidationClient: client, Settings: config.Stage{Validation: cfg.Validation}}}, - }) + })) if err != nil { t.Fatalf("Run error: %v", err) } @@ -855,11 +850,11 @@ func TestRunnerLLMValidatorRejectionPreventsApplication(t *testing.T) { }}, }}) cfg := runnerTestConfig() - out, err := r.Run(context.Background(), RunInput{ + out, err := r.Run(context.Background(), preparedTestInput(testRunInput{ Config: &cfg, Transcript: &schema.Transcript{Segments: []schema.Segment{{ID: 1, Text: "There were gestures at the temple."}}}, ModuleSpecs: []contracts.ModuleRunSpec{{ModuleKey: "m", InstanceName: "m", ValidationClient: client, Settings: config.Stage{Validation: cfg.Validation}}}, - }) + })) if err != nil { t.Fatalf("Run error: %v", err) } @@ -883,11 +878,11 @@ func TestRunnerLLMValidatorMalformedResponseRejectsBatchAndKeepsPartialProgress( }}, }}) cfg := runnerTestConfig() - out, err := r.Run(context.Background(), RunInput{ + out, err := r.Run(context.Background(), preparedTestInput(testRunInput{ Config: &cfg, Transcript: &schema.Transcript{Segments: []schema.Segment{{ID: 1, Text: "teh cat"}}}, ModuleSpecs: []contracts.ModuleRunSpec{{ModuleKey: "m1", InstanceName: "m1"}, {ModuleKey: "m2", InstanceName: "m2", ValidationClient: client, Settings: config.Stage{Validation: cfg.Validation}}}, - }) + })) if err != nil { t.Fatalf("expected malformed validator response to downgrade, got %v", err) } @@ -932,10 +927,10 @@ func TestRunnerReconciledSurvivorsCompleteLaterValidation(t *testing.T) { }} r := New(fakeFactory{modules: map[string]contracts.TranscriptModule{"m": module}}) cfg := runnerTestConfig() - out, err := r.Run(context.Background(), RunInput{ + out, err := r.Run(context.Background(), preparedTestInput(testRunInput{ Config: &cfg, Transcript: &schema.Transcript{Segments: []schema.Segment{{ID: 1, Text: "teh cat bad"}}}, ModuleSpecs: []contracts.ModuleRunSpec{{ModuleKey: "m", InstanceName: "m", ValidationClient: client, Settings: config.Stage{Validation: cfg.Validation}}}, - }) + })) if err != nil || out.FinalTranscript.Segments[0].Text != "the cat bad" || len(laterIndices) != 2 || laterIndices[0] != 0 || laterIndices[1] != 2 || client.calls != 1 { t.Fatalf("survivor routing: text=%q later=%v calls=%d err=%v", out.FinalTranscript.Segments[0].Text, laterIndices, client.calls, err) } @@ -958,11 +953,11 @@ func TestRunnerLLMValidatorMissingDecisionRejectsBatch(t *testing.T) { }}, }}) cfg := runnerTestConfig() - _, err := r.Run(context.Background(), RunInput{ + _, err := r.Run(context.Background(), preparedTestInput(testRunInput{ Config: &cfg, Transcript: &schema.Transcript{Segments: []schema.Segment{{ID: 1, Text: "There were gestures at the temple."}}}, ModuleSpecs: []contracts.ModuleRunSpec{{ModuleKey: "m", InstanceName: "m", ValidationClient: client, Settings: config.Stage{Validation: cfg.Validation}}}, - }) + })) if err != nil { t.Fatalf("expected missing decision downgrade, got %v", err) } @@ -980,11 +975,11 @@ func TestRunnerLLMValidatorDuplicateDecisionRejectsBatch(t *testing.T) { }}, }}) cfg := runnerTestConfig() - _, err := r.Run(context.Background(), RunInput{ + _, err := r.Run(context.Background(), preparedTestInput(testRunInput{ Config: &cfg, Transcript: &schema.Transcript{Segments: []schema.Segment{{ID: 1, Text: "There were gestures at the temple."}}}, ModuleSpecs: []contracts.ModuleRunSpec{{ModuleKey: "m", InstanceName: "m", ValidationClient: client, Settings: config.Stage{Validation: cfg.Validation}}}, - }) + })) if err != nil { t.Fatalf("expected duplicate decision downgrade, got %v", err) } @@ -1012,11 +1007,11 @@ func TestRunnerLLMValidatorBatching(t *testing.T) { }, nil }}, }}) - out, err := r.Run(context.Background(), RunInput{ + out, err := r.Run(context.Background(), preparedTestInput(testRunInput{ Config: &cfg, Transcript: &schema.Transcript{Segments: []schema.Segment{{ID: 1, Text: "alpha gamma"}}}, ModuleSpecs: []contracts.ModuleRunSpec{{ModuleKey: "m", InstanceName: "m", ValidationClient: client, Settings: config.Stage{Validation: cfg.Validation}}}, - }) + })) if err != nil { t.Fatalf("unexpected run error: %v", err) } @@ -1039,12 +1034,12 @@ func TestRunnerLLMValidatorDiagnosticsWritten(t *testing.T) { return []proposals.CorrectionProposal{{TargetSegmentID: 1, OriginalText: "gestures", CorrectedText: "Jesters"}}, nil }}, }}) - out, err := r.Run(context.Background(), RunInput{ + out, err := r.Run(context.Background(), preparedTestInput(testRunInput{ Config: &cfg, Transcript: &schema.Transcript{Segments: []schema.Segment{{ID: 1, Text: "There were gestures at the temple."}}}, ModuleSpecs: []contracts.ModuleRunSpec{{ModuleKey: "m", InstanceName: "m", ValidationClient: client, Settings: config.Stage{Validation: cfg.Validation}}}, Interactions: llm.NewDiagnosticsWriter(diagDir), - }) + })) if err != nil { t.Fatalf("Run error: %v", err) } @@ -1126,10 +1121,10 @@ func TestRunnerProposalIndexOrderingIsDeterministicAcrossParallelSections(t *tes r := New(fakeFactory{modules: map[string]contracts.TranscriptModule{"grammar": &grammar.Module{}}}) ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) defer cancel() - out, err := r.Run(ctx, RunInput{ + out, err := r.Run(ctx, preparedTestInput(testRunInput{ Config: &cfg, Transcript: transcript, Interactions: interactions, ModuleSpecs: []contracts.ModuleRunSpec{{ModuleKey: "grammar", InstanceName: "grammar", ProposalClient: client}}, - }) + })) if err != nil { t.Fatal(err) } diff --git a/internal/framework/runner/window_test.go b/internal/framework/runner/window_test.go index f9bb936..7bafcde 100644 --- a/internal/framework/runner/window_test.go +++ b/internal/framework/runner/window_test.go @@ -129,9 +129,9 @@ func TestLaterSectionsValidateWhileEarlierProposalUsesSharedBackend(t *testing.T } finished := make(chan result, 1) go func() { - out, err := r.Run(ctx, RunInput{Config: &cfg, Transcript: transcript, + out, err := r.Run(ctx, preparedTestInput(testRunInput{Config: &cfg, Transcript: transcript, ModuleSpecs: []contracts.ModuleRunSpec{{ModuleKey: "grammar", InstanceName: "grammar", Settings: config.Stage{Validation: cfg.Validation}, ProposalClient: role, ValidationClient: role}}, - }) + })) finished <- result{out, err} }() select { @@ -232,14 +232,14 @@ func TestLaterRepairArtifactsUseOrderedProposalIndices(t *testing.T) { cfg := runnerTestConfig() cfg.Chunking.MaxSectionTokens = 1 cfg.Chunking.MinSectionTokens = 0 - out, err := New(fakeFactory{modules: map[string]contracts.TranscriptModule{"grammar": module}}).Run(ctx, RunInput{ + out, err := New(fakeFactory{modules: map[string]contracts.TranscriptModule{"grammar": module}}).Run(ctx, preparedTestInput(testRunInput{ Config: &cfg, Interactions: writer, Evidence: &EvidenceSelection{Reports: true, Debug: true}, Transcript: &schema.Transcript{Segments: []schema.Segment{{ID: 71, Text: "alpha"}, {ID: 93, Text: "bravo"}}}, ModuleSpecs: []contracts.ModuleRunSpec{{ ModuleKey: "grammar", InstanceName: "grammar", ProposalClient: proposal, ValidationClient: validation, RepairCoordinator: repair, Settings: config.Stage{Validation: cfg.Validation, LLM: config.LLM{CorrectionRepairAttempts: 2}}, }}, - }) + })) if (!canceled && err != nil) || (canceled && !errors.Is(err, context.Canceled)) { t.Fatal(err) }