From b4bc5e5640fd6674945b55c2e128199b22c6c76b Mon Sep 17 00:00:00 2001 From: Eric Rakestraw Date: Fri, 27 Nov 2026 01:17:45 +0000 Subject: [PATCH] Run processing from the prepared invocation --- docs/roadmap/implementation.md | 2 + internal/cli/examples_integration_test.go | 2 +- internal/cli/process.go | 4 +- internal/cli/process_inputs.go | 98 ++++++++++++------- internal/cli/process_inputs_test.go | 40 ++++++++ .../cli/process_ordered_integration_test.go | 6 +- internal/cli/process_output_test.go | 2 +- internal/cli/process_pipeline.go | 10 +- internal/cli/process_prepare_output.go | 10 +- .../processreport/partial_validation_test.go | 5 +- .../framework/runner/prepared_input_test.go | 3 +- internal/framework/runner/runner.go | 17 ++-- 12 files changed, 133 insertions(+), 66 deletions(-) diff --git a/docs/roadmap/implementation.md b/docs/roadmap/implementation.md index 2e273f3..8f3ee31 100644 --- a/docs/roadmap/implementation.md +++ b/docs/roadmap/implementation.md @@ -161,6 +161,8 @@ session or model call, and processing can consume it without repeating this work ## Stage 4: Make processing consume the prepared invocation +**Completed.** + Work: 1. Factor shared CLI acquisition/local preparation out of `loadProcessInputs` diff --git a/internal/cli/examples_integration_test.go b/internal/cli/examples_integration_test.go index 9287c9e..90bba17 100644 --- a/internal/cli/examples_integration_test.go +++ b/internal/cli/examples_integration_test.go @@ -113,7 +113,7 @@ func TestMaintainedProjectsWithControlledProvider(t *testing.T) { t.Fatal(err) } defer prepared.Prepared.Output.Close() - if _, err := executePipeline(context.Background(), inputs, prepared, source.Canonical(), func(error) {}, nil); err != nil { + if _, err := executePipeline(context.Background(), prepared, func(error) {}, nil); err != nil { t.Fatal(err) } if int(calls.Load()) != len(loaded.Config.Application.Pipeline.Stages) { diff --git a/internal/cli/process.go b/internal/cli/process.go index c6a95f9..6ab35a8 100644 --- a/internal/cli/process.go +++ b/internal/cli/process.go @@ -73,7 +73,7 @@ func runProcess(inv commandkit.Invocation, input processInput) commandkit.Outcom } loaded.RawTranscript = nil cfg := &loaded.Configuration.Config.Application - normalized, summary := prepared.Prepared.Plan.Transcript, prepared.Prepared.Plan.Summary + normalized, summary := prepared.Invocation.Plan.Transcript, prepared.Invocation.Plan.Summary loaded.Source = nil if debug != nil { warn(debug.WriteNormalizedTranscript(normalized)) @@ -83,7 +83,7 @@ func runProcess(inv commandkit.Invocation, input processInput) commandkit.Outcom return finishProcess(inv, input, prepared, reporting.Snapshot{}, nil, &runner.ExecutionFailure{Phase: "normalization", Cause: err}) } reporter := inv.Reporter() - result, runErr := executePipeline(inv.Context, loaded, prepared, normalized, warn, func(message string) { + result, runErr := executePipeline(inv.Context, prepared, warn, func(message string) { _ = reporter.Progress(message) }) if runErr != nil { diff --git a/internal/cli/process_inputs.go b/internal/cli/process_inputs.go index 13c2cbc..74dc2bf 100644 --- a/internal/cli/process_inputs.go +++ b/internal/cli/process_inputs.go @@ -38,9 +38,16 @@ type runtimePreparationError struct{ cause error } func (e *runtimePreparationError) Error() string { return e.cause.Error() } func (e *runtimePreparationError) Unwrap() error { return e.cause } -func loadProcessInputs(ctx context.Context, input processInput, mode commandkit.ReportingMode) (*processInputs, error) { +func checkQuietDestination(input processInput, mode commandkit.ReportingMode) error { if mode == commandkit.ReportingModeQuiet && input.Output.Value == "" { - return nil, fmt.Errorf("quiet processing requires an output file or /dev/null") + return fmt.Errorf("quiet processing requires an output file or /dev/null") + } + return nil +} + +func loadProcessInputs(ctx context.Context, input processInput, mode commandkit.ReportingMode) (*processInputs, error) { + if err := checkQuietDestination(input, mode); err != nil { + return nil, err } selection := ckconfig.Selection{Config: input.Config, Overlay: input.Overlay, Overrides: input.Overrides} acquired, err := acquireApplication(ctx, selection, acquisitionInput{GlossaryFiles: input.GlossaryFiles}) @@ -81,13 +88,46 @@ func loadProcessInputs(ctx context.Context, input processInput, mode commandkit. // preparedProcess groups the output resources and the facts needed for reports. type preparedProcess struct { - Prepared *preparedOutput - RunID string - Started time.Time + Prepared *preparedOutput + Invocation *preparedInvocation + RunID string + Started time.Time } -func prepareProcess(ctx context.Context, input processInput, loaded *processInputs, stdout io.Writer) (*preparedProcess, error) { +type preparedInvocation struct { + Loaded *processInputs + Plan *preflight.Plan + Destinations *diagnostics.CheckedDestinations +} + +func prepareLocal(ctx context.Context, input processInput, loaded *processInputs, stdout io.Writer) (*preparedInvocation, error) { cfg := &loaded.Configuration.Config.Application + checkedBackends := make(map[string]struct{}) + 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} + } + if err != nil || profile.Backend == nil { + return err + } + backend := *profile.Backend + if _, ok := checkedBackends[backend]; ok { + return nil + } + _, err = loaded.Runtime.Engine.InspectBackend(ctx, backend) + if errors.Is(err, pk.ErrBackendNotFound) { + return &preflight.SelectionError{Cause: err} + } + if err == nil { + checkedBackends[backend] = struct{}{} + } + return err + } + plan, err := preflight.BuildPlan(ctx, cfg, loaded.Source, inspectProfile) + if err != nil { + return nil, err + } reportDir := "" reportDirSet := false for _, override := range input.Overrides { @@ -104,6 +144,22 @@ func prepareProcess(ctx context.Context, input processInput, loaded *processInpu } } } + checked, err := diagnostics.CheckOutput(diagnostics.OutputSelection{InputTranscriptPath: input.Transcript, TranscriptPath: input.Output.Value, ReportDir: reportDir, ReportingEnabled: cfg.Reporting.Enabled, ProtectedPaths: loaded.ProtectedPaths, Stdout: stdout}) + if err != nil { + return nil, err + } + if err := ctx.Err(); err != nil { + return nil, err + } + return &preparedInvocation{Loaded: loaded, Plan: plan, Destinations: checked}, nil +} + +func prepareProcess(ctx context.Context, input processInput, loaded *processInputs, stdout io.Writer) (*preparedProcess, error) { + local, err := prepareLocal(ctx, input, loaded, stdout) + if err != nil { + return nil, err + } + cfg := local.Plan.Config runID, err := generateRunID() if err != nil { return nil, err @@ -136,38 +192,12 @@ func prepareProcess(ctx context.Context, input processInput, loaded *processInpu } 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{}) - 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} - } - if err != nil || profile.Backend == nil { - return err - } - backend := *profile.Backend - if _, ok := checkedBackends[backend]; ok { - return nil - } - _, err = loaded.Runtime.Engine.InspectBackend(ctx, backend) - if errors.Is(err, pk.ErrBackendNotFound) { - return &preflight.SelectionError{Cause: err} - } - if err == nil { - checkedBackends[backend] = struct{}{} - } - return err - } - 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) + prepared, err := prepareOutput(ctx, local.Destinations, initial, failed, debug) if err != nil { return nil, err } prepared.Warnings = append(warnings, prepared.Warnings...) - return &preparedProcess{Prepared: prepared, RunID: runID, Started: started}, nil + return &preparedProcess{Prepared: prepared, Invocation: local, RunID: runID, Started: started}, nil } func generateRunID() (string, error) { diff --git a/internal/cli/process_inputs_test.go b/internal/cli/process_inputs_test.go index 94e716a..68dcef8 100644 --- a/internal/cli/process_inputs_test.go +++ b/internal/cli/process_inputs_test.go @@ -2,6 +2,7 @@ package cli import ( "context" + "errors" "io" "os" "path/filepath" @@ -9,6 +10,8 @@ import ( "strings" "testing" + "gitea.maximumdirect.net/eric/audita/v4/internal/framework/preflight" + commandkit "go.maximumdirect.net/commandkit" ck "go.maximumdirect.net/configkit" ) @@ -106,3 +109,40 @@ func TestCollectionFlagJSON(t *testing.T) { } } } + +func TestInfeasibleChunkingPrecedesOutputInitialization(t *testing.T) { + dir := t.TempDir() + configPath := filepath.Join(dir, "config.yml") + transcriptPath := filepath.Join(dir, "transcript.json") + outputPath := filepath.Join(dir, "output.json") + if err := os.WriteFile(configPath, []byte("version: 3\npipeline:\n stages: []\n"), 0644); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(transcriptPath, []byte(`[{"speaker":"Alice","start":0,"end":1,"text":"hello"}]`), 0644); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(outputPath, []byte("existing"), 0644); err != nil { + t.Fatal(err) + } + input := processInput{Config: commandkit.Supplied[string]{Value: configPath, Set: true}, Transcript: transcriptPath, Output: commandkit.Supplied[string]{Value: outputPath, Set: true}, Debug: commandkit.Supplied[bool]{Value: true, Set: true}} + loaded, err := loadProcessInputs(context.Background(), input, commandkit.ReportingModeOrdinary) + if err != nil { + t.Fatal(err) + } + count := 2 + loaded.Configuration.Config.Application.Chunking.TargetSections = &count + _, err = prepareProcess(context.Background(), input, loaded, io.Discard) + var selection *preflight.SelectionError + if !errors.As(err, &selection) { + t.Fatalf("expected selection error, got %v", err) + } + data, err := os.ReadFile(outputPath) + if err != nil || string(data) != "existing" { + t.Fatalf("output changed: %q %v", data, err) + } + for _, name := range []string{"errors.yml", "recoveries.yml", "report.md"} { + if _, err := os.Stat(filepath.Join(dir, name)); !os.IsNotExist(err) { + t.Fatalf("unexpected report %s: %v", name, err) + } + } +} diff --git a/internal/cli/process_ordered_integration_test.go b/internal/cli/process_ordered_integration_test.go index 1771eff..811a87d 100644 --- a/internal/cli/process_ordered_integration_test.go +++ b/internal/cli/process_ordered_integration_test.go @@ -121,7 +121,7 @@ pipeline: t.Fatal(err) } defer prepared.Prepared.Output.Close() - result, err := executePipeline(context.Background(), inputs, prepared, source.Canonical(), func(error) {}, nil) + result, err := executePipeline(context.Background(), prepared, func(error) {}, nil) if err != nil { t.Fatal(err) } @@ -235,7 +235,7 @@ func TestRecoverableModelFailureKeepsNormalizedTranscript(t *testing.T) { t.Fatal(err) } defer prepared.Prepared.Output.Close() - result, err := executePipeline(context.Background(), inputs, prepared, source.Canonical(), func(error) {}, nil) + result, err := executePipeline(context.Background(), prepared, func(error) {}, nil) if err != nil { t.Fatal(err) } @@ -296,7 +296,7 @@ func TestMalformedPermissivePromptKeepsLaterWork(t *testing.T) { t.Fatal(err) } defer prepared.Prepared.Output.Close() - result, err := executePipeline(context.Background(), inputs, prepared, source.Canonical(), func(error) {}, nil) + result, err := executePipeline(context.Background(), prepared, func(error) {}, nil) if err != nil { t.Fatal(err) } diff --git a/internal/cli/process_output_test.go b/internal/cli/process_output_test.go index 5ccc8a3..3d8109c 100644 --- a/internal/cli/process_output_test.go +++ b/internal/cli/process_output_test.go @@ -156,7 +156,7 @@ func TestCanceledEmptyPipelineLeavesTranscriptAndFinalizesReports(t *testing.T) t.Fatal(err) } defer prepared.Prepared.Output.Close() - result, err := executePipeline(inv.Context, loaded, prepared, loaded.Source.Canonical(), func(error) {}, nil) + result, err := executePipeline(inv.Context, prepared, func(error) {}, nil) if err != nil { t.Fatal(err) } diff --git a/internal/cli/process_pipeline.go b/internal/cli/process_pipeline.go index a6214f1..8811120 100644 --- a/internal/cli/process_pipeline.go +++ b/internal/cli/process_pipeline.go @@ -6,7 +6,6 @@ import ( "gitea.maximumdirect.net/eric/audita/v4/internal/core/diagnostics" "gitea.maximumdirect.net/eric/audita/v4/internal/core/reporting" - "gitea.maximumdirect.net/eric/audita/v4/internal/core/schema" "gitea.maximumdirect.net/eric/audita/v4/internal/framework/llm" "gitea.maximumdirect.net/eric/audita/v4/internal/framework/outcomes" "gitea.maximumdirect.net/eric/audita/v4/internal/framework/processreport" @@ -15,9 +14,10 @@ import ( "gitea.maximumdirect.net/eric/audita/v4/internal/modules" ) -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.Plan.Specs +func executePipeline(ctx context.Context, prepared *preparedProcess, warn func(error), progress func(string)) (processResult, error) { + loaded := prepared.Invocation.Loaded + cfg := prepared.Invocation.Plan.Config + specs := prepared.Invocation.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{ - Sections: prepared.Prepared.Plan.Sections, Transcript: normalized, ModuleSpecs: specs, + Plan: prepared.Invocation.Plan, 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 index efe34b3..22f610a 100644 --- a/internal/cli/process_prepare_output.go +++ b/internal/cli/process_prepare_output.go @@ -5,7 +5,6 @@ import ( "errors" "gitea.maximumdirect.net/eric/audita/v4/internal/core/diagnostics" - "gitea.maximumdirect.net/eric/audita/v4/internal/framework/preflight" ) type debugInput struct { @@ -16,17 +15,12 @@ type debugInput struct { } 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 - } +func prepareOutput(ctx context.Context, checked *diagnostics.CheckedDestinations, initial diagnostics.ReportBundle, failed diagnostics.ReportRenderer, debug *debugInput) (*preparedOutput, error) { if err := ctx.Err(); err != nil { return nil, err } @@ -44,7 +38,7 @@ func prepareOutput(ctx context.Context, plan *preflight.Plan, selection diagnost if err := ctx.Err(); err != nil { return nil, cancelOutput(err) } - result := &preparedOutput{Plan: plan, Output: session} + result := &preparedOutput{Output: session} if debug != nil { result.Debug, result.Warnings = diagnostics.PrepareDebug(debug.WorkDir, debug.RunID, debug.Metadata, debug.EffectiveConfig) } diff --git a/internal/framework/processreport/partial_validation_test.go b/internal/framework/processreport/partial_validation_test.go index d17e06a..e4b6c80 100644 --- a/internal/framework/processreport/partial_validation_test.go +++ b/internal/framework/processreport/partial_validation_test.go @@ -13,6 +13,7 @@ import ( "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/outcomes" + "gitea.maximumdirect.net/eric/audita/v4/internal/framework/preflight" "gitea.maximumdirect.net/eric/audita/v4/internal/framework/proposals" "gitea.maximumdirect.net/eric/audita/v4/internal/framework/runner" "gitea.maximumdirect.net/eric/audita/v4/internal/framework/structuredoutput" @@ -74,8 +75,8 @@ 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{ - 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}, + Plan: &preflight.Plan{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"}}}, + Specs: []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 { t.Fatalf("fatal cause/calls: %v %d", err, client.calls) diff --git a/internal/framework/runner/prepared_input_test.go b/internal/framework/runner/prepared_input_test.go index 2b62781..5289f4d 100644 --- a/internal/framework/runner/prepared_input_test.go +++ b/internal/framework/runner/prepared_input_test.go @@ -5,6 +5,7 @@ import ( "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/preflight" "gitea.maximumdirect.net/eric/audita/v4/internal/framework/structuredoutput" ) @@ -26,5 +27,5 @@ func preparedTestInput(input testRunInput) RunInput { if err != nil { panic(err) } - return RunInput{Sections: sections, Transcript: input.Transcript, ModuleSpecs: input.ModuleSpecs, Interactions: input.Interactions, Evidence: input.Evidence, Progress: input.Progress} + return RunInput{Plan: &preflight.Plan{Sections: sections, Transcript: input.Transcript, Specs: input.ModuleSpecs, Config: input.Config}, Interactions: input.Interactions, Evidence: input.Evidence, Progress: input.Progress} } diff --git a/internal/framework/runner/runner.go b/internal/framework/runner/runner.go index 6005c7c..cdac45d 100644 --- a/internal/framework/runner/runner.go +++ b/internal/framework/runner/runner.go @@ -14,6 +14,7 @@ import ( "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/outcomes" + "gitea.maximumdirect.net/eric/audita/v4/internal/framework/preflight" "gitea.maximumdirect.net/eric/audita/v4/internal/framework/promptcontext" "gitea.maximumdirect.net/eric/audita/v4/internal/framework/proposals" "gitea.maximumdirect.net/eric/audita/v4/internal/framework/structuredoutput" @@ -113,9 +114,7 @@ func selectEvidence(selection *EvidenceSelection) evidenceNeeds { // RunInput is the deterministic runner input. type RunInput struct { - Sections []chunking.Section - Transcript *schema.Transcript - ModuleSpecs []contracts.ModuleRunSpec + Plan *preflight.Plan Interactions structuredoutput.InteractionSink Evidence *EvidenceSelection Progress func(Progress) @@ -138,16 +137,16 @@ func New(factory ModuleFactory) *Runner { func (r *Runner) Run(ctx context.Context, input RunInput) (RunOutput, error) { if err := ctx.Err(); err != nil { - return RunOutput{FinalTranscript: input.Transcript.Clone()}, &ExecutionFailure{Phase: "processing", Cause: err} + return RunOutput{FinalTranscript: input.Plan.Transcript.Clone()}, &ExecutionFailure{Phase: "processing", Cause: err} } if r == nil || r.factory == nil { return RunOutput{}, &ExecutionFailure{Phase: "setup", Cause: errors.New("runner module factory is required")} } - results := make([]ModuleResult, 0, len(input.ModuleSpecs)) - sections := input.Sections + results := make([]ModuleResult, 0, len(input.Plan.Specs)) + sections := input.Plan.Sections evidence := selectEvidence(input.Evidence) - totals := outcomes.WorkTotals{Total: len(input.ModuleSpecs) * len(sections)} + totals := outcomes.WorkTotals{Total: len(input.Plan.Specs) * len(sections)} var inventory []contracts.SectionMetadata var workUnits []WorkUnitOutcome var candidates []proposals.EnrichedCorrectionProposal @@ -157,7 +156,7 @@ func (r *Runner) Run(ctx context.Context, input RunInput) (RunOutput, error) { inventory[i] = contracts.SectionMetadataFromSection(section) } workUnits = make([]WorkUnitOutcome, 0, totals.Total) - for moduleIndex, spec := range input.ModuleSpecs { + for moduleIndex, spec := range input.Plan.Specs { for _, section := range inventory { workUnits = append(workUnits, newWorkUnit(spec, section, moduleIndex)) } @@ -170,7 +169,7 @@ func (r *Runner) Run(ctx context.Context, input RunInput) (RunOutput, error) { } } - for moduleIndex, spec := range input.ModuleSpecs { + for moduleIndex, spec := range input.Plan.Specs { progress := Progress{ModuleIndex: spec.Index, ModuleKey: spec.ModuleKey, ModuleID: spec.ID} sectionCount := len(sections) progress.emit(input.Progress, "started", nil, §ionCount)