Run downstream preflight after preparation

This commit is contained in:
2026-11-27 16:45:46 +00:00
parent b9b154e59e
commit d178e2c437
8 changed files with 256 additions and 34 deletions

View File

@@ -12,6 +12,11 @@ import (
// NoopRunner is a deterministic no-op audita adapter.
type NoopRunner struct{}
// Preflight accepts the synthetic request in no-op environments.
func (*NoopRunner) Preflight(ctx context.Context, _ PolishRequest) (PreflightResult, error) {
return PreflightResult{}, ctx.Err()
}
// Run returns requested output path with placeholder metadata.
func (n *NoopRunner) Run(ctx context.Context, req PolishRequest) (PolishResult, error) {
if err := ctx.Err(); err != nil {
@@ -31,9 +36,20 @@ func (n *NoopRunner) Run(ctx context.Context, req PolishRequest) (PolishResult,
// FakeRunner captures polish requests and returns deterministic responses.
type FakeRunner struct {
Requests []PolishRequest
Err error
Result PolishResult
Requests []PolishRequest
Err error
Result PolishResult
PreflightRequests []PolishRequest
PreflightErr error
}
// Preflight records a readiness request in deterministic tests.
func (f *FakeRunner) Preflight(ctx context.Context, req PolishRequest) (PreflightResult, error) {
if err := ctx.Err(); err != nil {
return PreflightResult{}, err
}
f.PreflightRequests = append(f.PreflightRequests, req)
return PreflightResult{}, f.PreflightErr
}
// Run records request and returns configured response.

View File

@@ -85,15 +85,16 @@ func executePlanWithDependencies(ctx context.Context, cfg *config.Config, plan B
if err := initializeLockedInvocation(runtime); err != nil {
return nil, err
}
if err := inspectInvocationRequirements(runtime); err != nil {
return nil, err
}
if err := composeInvocation(runtime); err != nil {
return nil, err
}
runtime.env.Info("selected run destinations", "session", runtime.identity.SessionID, "run", runtime.identity.RunID, "manifest", runtime.manifestPath, "workspace", runtime.identity.LocalWorkDir)
downstreamChecked := false
for index, selected := range runtime.stages {
if selected.Name() != "prepare" && !downstreamChecked {
downstreamChecked = true
if err := inspectInvocationRequirements(runtime, index); err != nil {
return nil, err
}
}
if err := ctx.Err(); err != nil {
return nil, err
}

View File

@@ -4,11 +4,11 @@ import (
"fmt"
"gitea.maximumdirect.net/eric/narratio/internal/adapters/notify"
"gitea.maximumdirect.net/eric/narratio/internal/stage"
)
func composeInvocation(runtime *invocationRuntime) error {
func composeInvocation(runtime *invocationRuntime, stages []stage.Stage) error {
env := runtime.env
stages := runtime.stages
dependencies := runtime.dependencies
if err := runtime.ctx.Err(); err != nil {

View File

@@ -0,0 +1,169 @@
package app
import (
"context"
"errors"
"os"
"path/filepath"
"reflect"
"testing"
"gitea.maximumdirect.net/eric/narratio/internal/adapters/audita"
"gitea.maximumdirect.net/eric/narratio/internal/artifactpolicy"
"gitea.maximumdirect.net/eric/narratio/internal/config"
"gitea.maximumdirect.net/eric/narratio/internal/manifest"
"gitea.maximumdirect.net/eric/narratio/internal/stage"
)
type preparationFixture struct {
runs *int
stale *bool
}
func (p preparationFixture) Name() string { return "prepare" }
func (p preparationFixture) ValidateResume(context.Context, *stage.Env, *manifest.Manifest) (stage.ResumeValidation, error) {
if p.stale != nil && *p.stale {
return stage.NonResumable("source changed"), nil
}
return stage.Resumable(), nil
}
func (p preparationFixture) Run(_ context.Context, env *stage.Env, m *manifest.Manifest) (*stage.StageResult, error) {
*p.runs++
paths := env.ArtifactStore.SessionPathsFor(env.Config.Session.Campaign, m.SessionID)
m.Inputs = nil
for _, d := range artifactpolicy.GlossaryInputSources() {
path := filepath.Join(paths.InputsDir, d.Filename)
if err := os.MkdirAll(filepath.Dir(path), 0755); err != nil {
return nil, err
}
if err := os.WriteFile(path, []byte("synthetic: {entries: []}\n"), 0644); err != nil {
return nil, err
}
checksum, err := env.ArtifactStore.Checksum(path)
if err != nil {
return nil, err
}
m.Inputs = append(m.Inputs, manifest.InputRecord{Kind: d.ManifestKind, Path: path, Checksum: checksum})
}
return &stage.StageResult{}, nil
}
func TestDownstreamPreflightAfterPreparePreservesStateOnFailure(t *testing.T) {
cfg := testConfig(t)
var prepared, polished int
failure := errors.New("synthetic provider failure")
runner := &audita.FakeRunner{PreflightErr: failure}
selected := []stage.Stage{preparationFixture{runs: &prepared}, countingStage{name: "polish", runs: &polished}}
summary, err := executeStages(context.Background(), cfg, selected, RunOptions{Env: &Env{Audita: runner}})
if !errors.Is(err, failure) || summary == nil || prepared != 1 || polished != 0 || len(runner.PreflightRequests) != 1 {
t.Fatalf("summary=%+v prepared=%d polished=%d calls=%d err=%v", summary, prepared, polished, len(runner.PreflightRequests), err)
}
if summary.StageResults[0].Outcome != "completed" || summary.StageResults[1].Attempted || summary.StageResults[1].Outcome != "not_attempted" {
t.Fatalf("stage results: %+v", summary.StageResults)
}
stored, err := (&manifest.LocalStore{}).Load(context.Background(), summary.ManifestPath)
if err != nil {
t.Fatal(err)
}
if stored.Stages["prepare"].Status != manifest.StatusSucceeded || stored.Stages["polish"] != nil {
t.Fatalf("manifest: %+v", stored.Stages)
}
runner.PreflightErr = nil
summary, err = executeStages(context.Background(), cfg, selected, RunOptions{Env: &Env{Audita: runner}})
if err != nil || prepared != 1 || polished != 1 || summary.StageResults[0].Outcome != "reused" {
t.Fatalf("retry: %+v prepared=%d polished=%d err=%v", summary, prepared, polished, err)
}
if len(runner.PreflightRequests) != 2 || len(runner.PreflightRequests[1].GlossaryFiles) != 4 {
t.Fatalf("requests: %+v", runner.PreflightRequests)
}
again, err := executeStages(context.Background(), cfg, selected, RunOptions{Env: &Env{Audita: runner}})
if err != nil || len(runner.PreflightRequests) != 2 || again.StageResults[1].Outcome != "reused" {
t.Fatalf("reuse: %+v calls=%d err=%v", again, len(runner.PreflightRequests), err)
}
if _, err := os.Stat(summaryRunRoot(cfg, again.RunID)); !errors.Is(err, os.ErrNotExist) {
t.Fatalf("reused invocation created run directory: %v", err)
}
initialized := 0
deps := invocationDependencies{newAudita: func(*config.Config) (audita.Runner, error) { initialized++; return &audita.FakeRunner{}, nil }}
_, err = executePlanWithDependencies(context.Background(), cfg, BoundedPlan{stages: selected}, RunOptions{}, deps)
if err != nil || initialized != 0 {
t.Fatalf("reused work initialized Audita: %d %v", initialized, err)
}
}
func TestPrepareOnlyDoesNotInitializeDownstream(t *testing.T) {
cfg := testConfig(t)
var prepared int
calls := 0
deps := invocationDependencies{newAudita: func(*config.Config) (audita.Runner, error) { calls++; return &audita.FakeRunner{}, nil }}
_, err := executePlanWithDependencies(context.Background(), cfg, BoundedPlan{stages: []stage.Stage{countingStage{name: "prepare", runs: &prepared}}}, RunOptions{}, deps)
if err != nil || prepared != 1 || calls != 0 {
t.Fatalf("prepare=%d calls=%d err=%v", prepared, calls, err)
}
}
func TestFailedPreparationDoesNotRunDownstreamPreflight(t *testing.T) {
cfg := testConfig(t)
failure := errors.New("preparation failed")
runner := &audita.FakeRunner{}
var polished int
summary, err := executeStages(context.Background(), cfg, []stage.Stage{failingStage{name: "prepare", err: failure}, countingStage{name: "polish", runs: &polished}}, RunOptions{Env: &Env{Audita: runner}})
if !errors.Is(err, failure) || len(runner.PreflightRequests) != 0 || polished != 0 || summary == nil || summary.StageResults[1].Attempted {
t.Fatalf("summary=%+v calls=%d err=%v", summary, len(runner.PreflightRequests), err)
}
}
func TestAuditaPreflightFailureDoesNotInvalidateForcedPolish(t *testing.T) {
cfg := testConfig(t)
var prepared, polished int
runner := &audita.FakeRunner{}
selected := []stage.Stage{preparationFixture{runs: &prepared}, countingStage{name: "polish", runs: &polished}}
first, err := executeStages(context.Background(), cfg, selected, RunOptions{Env: &Env{Audita: runner}})
if err != nil {
t.Fatal(err)
}
store := &manifest.LocalStore{}
before, err := store.Load(context.Background(), first.ManifestPath)
if err != nil {
t.Fatal(err)
}
failure := errors.New("provider unavailable")
runner.PreflightErr = failure
second, err := executeStages(context.Background(), cfg, []stage.Stage{countingStage{name: "polish", runs: &polished}}, RunOptions{Force: true, Env: &Env{Audita: runner}})
if !errors.Is(err, failure) || second == nil || second.StageResults[0].Attempted || polished != 1 {
t.Fatalf("summary=%+v runs=%d err=%v", second, polished, err)
}
after, err := store.Load(context.Background(), first.ManifestPath)
if err != nil {
t.Fatal(err)
}
if !reflect.DeepEqual(before.Stages["polish"], after.Stages["polish"]) {
t.Fatalf("preflight changed prior polish: before=%+v after=%+v", before.Stages["polish"], after.Stages["polish"])
}
}
func TestPreparationInvalidationExposesPolishToPreflight(t *testing.T) {
cfg := testConfig(t)
var prepared, polished int
stale := false
runner := &audita.FakeRunner{}
selected := []stage.Stage{preparationFixture{runs: &prepared, stale: &stale}, countingStage{name: "polish", runs: &polished}}
_, err := executeStages(context.Background(), cfg, selected, RunOptions{Env: &Env{Audita: runner}})
if err != nil {
t.Fatal(err)
}
stale = true
failure := errors.New("provider unavailable after preparation")
runner.PreflightErr = failure
summary, err := executeStages(context.Background(), cfg, selected, RunOptions{Env: &Env{Audita: runner}})
if !errors.Is(err, failure) || prepared != 2 || polished != 1 || summary.StageResults[0].Outcome != "completed" || summary.StageResults[1].Attempted {
t.Fatalf("summary=%+v prepare=%d polish=%d err=%v", summary, prepared, polished, err)
}
stored, err := (&manifest.LocalStore{}).Load(context.Background(), summary.ManifestPath)
if err != nil {
t.Fatal(err)
}
if stored.Stages["polish"].Status != manifest.StatusStale {
t.Fatalf("polish state: %+v", stored.Stages["polish"])
}
}

View File

@@ -2,39 +2,60 @@ package app
import (
"fmt"
"path/filepath"
"gitea.maximumdirect.net/eric/narratio/internal/adapters/audita"
"gitea.maximumdirect.net/eric/narratio/internal/preflight"
"gitea.maximumdirect.net/eric/narratio/internal/stage"
)
func inspectInvocationRequirements(runtime *invocationRuntime) error {
if !stagesContainAny(runtime.stages, "trim", "analyze") {
func inspectInvocationRequirements(runtime *invocationRuntime, start int) error {
remaining := runtime.plan
remaining.stages = append([]stage.Stage(nil), runtime.stages[start:]...)
projection, err := projectSelectedWork(runtime.ctx, runtime.cfg, remaining, runtime.opts.Force, runtime.opts.SelectedArtifacts, runtime.effectiveArtifacts, runtime.artifactStore, runtime.manifest)
if err != nil {
return fmt.Errorf("project downstream preflight work: %w", err)
}
targets, err := executionDownstreamTargets(runtime.cfg, runtime.identity.SessionID, projection)
if err != nil {
return fmt.Errorf("select downstream preflight targets: %w", err)
}
if !targets.Polish && len(targets.Scriptorium) == 0 {
return nil
}
projection, err := projectSelectedWork(runtime.ctx, runtime.cfg, runtime.plan, runtime.opts.Force, runtime.opts.SelectedArtifacts, runtime.effectiveArtifacts, runtime.artifactStore, runtime.manifest)
if err != nil {
return fmt.Errorf("project prompt inspection work: %w", err)
}
targets, err := executionInspectionTargets(runtime.cfg, runtime.identity.SessionID, projection)
if err != nil {
return fmt.Errorf("select prompt inspection targets: %w", err)
}
if len(targets) == 0 {
return nil
}
if runtime.env.Scriptorium == nil {
if len(targets.Scriptorium) > 0 && runtime.env.Scriptorium == nil {
runtime.env.Scriptorium = runtime.dependencies.newScriptorium()
}
if runtime.env.Scriptorium == nil {
return fmt.Errorf("initialize scriptorium runner: no runner available")
var checker preflight.AuditaChecker
var request audita.PolishRequest
if targets.Polish {
if runtime.env.Audita == nil {
runner, err := runtime.dependencies.newAudita(runtime.cfg)
if err != nil {
return fmt.Errorf("initialize audita runner: %w", err)
}
runtime.env.Audita = runner
}
var ok bool
checker, ok = runtime.env.Audita.(preflight.AuditaChecker)
if !ok || checker == nil {
return fmt.Errorf("audita runner does not support preflight")
}
root := filepath.Join(runtime.identity.LocalWorkDir, "polish")
output := filepath.Join(root, "outputs", "transcripts", "polished.json")
request, _, err = stage.BuildPolishRequest(runtime.paths, runtime.manifest, "", output, filepath.Join(root, "logs"), filepath.Join(root, "debug"))
if err != nil {
return fmt.Errorf("build audita preflight: %w", err)
}
}
result, err := preflight.Check(runtime.ctx, runtime.env.Scriptorium, targets)
result, err := preflight.CheckDownstream(runtime.ctx, runtime.env.Scriptorium, checker, targets, request)
for _, finding := range result.Findings {
if finding.Severity == preflight.SeverityWarning {
runtime.env.Warn(formatPromptFinding(finding), "stage", finding.Stage, "artifact", finding.Artifact, "prompt", finding.PromptID, "issue", finding.IssueCode, "input", finding.InputName, "variable", finding.VariableName)
}
}
if err != nil {
return fmt.Errorf("scriptorium preflight: %w", err)
return fmt.Errorf("downstream preflight: %w", err)
}
return nil
}

View File

@@ -43,13 +43,13 @@ func preflightTestConfig(t *testing.T) *config.Config {
return cfg
}
func TestPreflightRunsBeforeAttemptsAndWarningsAllowExecution(t *testing.T) {
func TestPreflightFollowsPreparationAndWarningsAllowExecution(t *testing.T) {
cfg := preflightTestConfig(t)
var earlierRuns int
reporter := &warningRecorder{}
runner := &observingInspector{inspect: func(req scriptorium.RequirementsRequest) {
if earlierRuns != 0 {
t.Fatal("inspection ran after first attempt")
if earlierRuns != 1 {
t.Fatal("inspection did not follow preparation")
}
if req.PromptID != "recap" {
t.Fatalf("request = %+v", req)
@@ -126,7 +126,7 @@ func TestPreflightInspectionFailureAndUnrelatedSelection(t *testing.T) {
runner := &scriptorium.FakeRunner{RequirementsErr: want}
var attempts int
summary, err := executeStages(context.Background(), cfg, []stage.Stage{countingStage{name: "prepare", runs: &attempts}, mustSelectStage(t, "analyze")}, RunOptions{Env: &Env{Scriptorium: runner}})
if !errors.Is(err, want) || attempts != 0 || summary == nil || summary.StageResults[0].Attempted {
if !errors.Is(err, want) || attempts != 1 || summary == nil || !summary.StageResults[0].Attempted || summary.StageResults[1].Attempted {
t.Fatalf("summary = %+v, attempts = %d, error = %v", summary, attempts, err)
}
runner.RequirementsRequests = nil

View File

@@ -31,6 +31,11 @@ func executeSelectedStage(runtime *invocationRuntime, selected stage.Stage) (out
}
env := runtime.env
m := runtime.manifest
if selected.Name() == "prepare" {
if err := composeInvocation(runtime, []stage.Stage{selected}); err != nil {
return outcome, err
}
}
env.Force = runtime.opts.Force
semanticConfig, err := currentStageSemanticConfig(selected, env)
@@ -65,6 +70,9 @@ func executeSelectedStage(runtime *invocationRuntime, selected stage.Stage) (out
env.Progress("reusing stage", "stage", selected.Name())
return stageExecutionOutcome{skipped: true, reused: true, reason: "already_succeeded"}, nil
}
if err := composeInvocation(runtime, []stage.Stage{selected}); err != nil {
return outcome, err
}
if err := runtime.ensureRunWorkspaceFor(selected); err != nil {
return outcome, err
}