diff --git a/docs/roadmap/implementation.md b/docs/roadmap/implementation.md index a1affef0..a6583a9d 100644 --- a/docs/roadmap/implementation.md +++ b/docs/roadmap/implementation.md @@ -304,6 +304,8 @@ one prompt; no new configuration or report-storage options are needed. ## Stage 6: Install The Command And Small Native Readiness Report +**Status:** Complete. + **Goal:** Both command spellings expose the complete non-capture preflight flow. **Inspect:** `application.go`, pipeline command declarations, Stage 1 helpers, diff --git a/internal/cli/application.go b/internal/cli/application.go index 7c8d1ae4..66af671c 100644 --- a/internal/cli/application.go +++ b/internal/cli/application.go @@ -42,8 +42,9 @@ func NewApplication(version string, options Options) (*commandkit.App, error) { definitions = ckprompt.WithNamespaces(definitions, promptkit.Namespaces{}) declarations := []commandkit.Declaration{ commandkit.Completion("notarius"), - pipelineCommands(newState, func() (pipeline.ModuleCatalog, error) { return effectiveCatalog(options) }, pipelineRunCommand(version, newState, func() (pipeline.Registries, error) { return effectiveRegistries(options) }, options)), + pipelineCommands(newState, func() (pipeline.ModuleCatalog, error) { return effectiveCatalog(options) }, pipelineRunCommand(version, newState, func() (pipeline.Registries, error) { return effectiveRegistries(options) }, options), pipelinePreflightCommand(newState, func() (pipeline.Registries, error) { return effectiveRegistries(options) })), commandkit.Alias("run", "pipeline run"), + commandkit.Alias("preflight", "pipeline preflight"), ckconfig.Command(ckconfig.Suite[struct{}, *nativeLoaders]{ NewState: newState, CheckInput: func(_ string, selection ckconfig.Selection, _ struct{}) error { diff --git a/internal/cli/pipeline_preflight.go b/internal/cli/pipeline_preflight.go new file mode 100644 index 00000000..dc88314f --- /dev/null +++ b/internal/cli/pipeline_preflight.go @@ -0,0 +1,133 @@ +package cli + +import ( + "fmt" + "text/template" + + "gitea.maximumdirect.net/eric/notarius/internal/framework/contracts" + "gitea.maximumdirect.net/eric/notarius/internal/framework/pipeline" + "gitea.maximumdirect.net/eric/notarius/internal/preflight" + "go.maximumdirect.net/commandkit" +) + +type preflightScope struct { + Pipeline string `json:"pipeline,omitempty" yaml:"pipeline,omitempty"` + Path string `json:"path,omitempty" yaml:"path,omitempty"` + Profile string `json:"profile,omitempty" yaml:"profile,omitempty"` + Backend string `json:"backend,omitempty" yaml:"backend,omitempty"` + Bindings []preflight.BindingScope `json:"bindings,omitempty" yaml:"bindings,omitempty"` +} + +type preflightCheck struct { + ID string `json:"id" yaml:"id"` + Scope preflightScope `json:"scope" yaml:"scope"` + Result string `json:"result" yaml:"result"` + Message string `json:"message" yaml:"message"` + Code string `json:"code,omitempty" yaml:"code,omitempty"` +} + +type preflightReport struct { + Pipeline string `json:"pipeline" yaml:"pipeline"` + Ready bool `json:"ready" yaml:"ready"` + Checks []preflightCheck `json:"checks" yaml:"checks"` + DebugDirectory string `json:"debug_directory,omitempty" yaml:"debug_directory,omitempty"` +} + +var preflightTemplate = template.Must(commandkit.ParseTextTemplate("pipeline-preflight", `Pipeline {{printf "%q" .Pipeline}} is {{if .Ready}}ready{{else}}not ready{{end}}. +{{range .Checks}}{{if ne .Result "passed"}}{{.Result}}: {{.Message}} +{{end}}{{end}}`, nil)) + +func pipelinePreflightCommand(newState func() *nativeLoaders, modules func() (pipeline.Registries, error)) commandkit.Command { + return commandkit.NewCommand(commandkit.CommandSpec[pipelineRunInput]{Name: "preflight", Summary: "Check readiness for a configured pipeline invocation.", Flags: runFlags(), Arguments: pipelineRunArguments(), CheckInput: checkPipelineRunInput, + Run: func(invocation commandkit.Invocation, input pipelineRunInput) commandkit.Outcome { + return executePreflight(invocation, input, newState(), modules) + }, + }) +} + +func executePreflight(invocation commandkit.Invocation, input pipelineRunInput, state *nativeLoaders, modules func() (pipeline.Registries, error)) commandkit.Outcome { + ctx := invocation.Context + loaded, failure := loadPipelineInvocation(ctx, invocation, input, state) + if failure != nil { + return *failure + } + report := preflightReport{Pipeline: input.PipelineID, Checks: []preflightCheck{}} + add := func(id string, scope preflightScope, result, message string) { + report.Checks = append(report.Checks, preflightCheck{ID: id, Scope: scope, Result: result, Message: message}) + } + finish := func(outcome commandkit.Outcome) commandkit.Outcome { + report.Ready = outcome.Status == 0 + for _, check := range report.Checks { + if check.Result == "passed" { + _ = invocation.Reporter().Info(check.Message) + } + } + if err := invocation.Reporter().Report(commandkit.Report{Value: report, TextTemplate: preflightTemplate}); err != nil { + if outcome.Status == 0 { + return commandkit.Failure("Could not present pipeline readiness.") + } + } + return outcome + } + selected, failure := selectPipelineInvocation(ctx, loaded, input, modules) + if failure != nil { + add("selection", preflightScope{Pipeline: input.PipelineID}, "failed", failure.Explanation.Message) + return finish(*failure) + } + add("selection", preflightScope{Pipeline: input.PipelineID}, "passed", "Pipeline selection and resources are valid.") + local, failure := preparePipelineInvocation(loaded, selected, input) + if failure != nil { + add("preparation", preflightScope{Pipeline: input.PipelineID}, "failed", failure.Explanation.Message) + return finish(*failure) + } + for _, diagnostic := range local.diagnostics { + for _, sample := range diagnostic.Samples { + message := sample.Message + if diagnostic.Disposition == contracts.DiagnosticDispositionWarning { + report.Checks = append(report.Checks, preflightCheck{ID: "reference", Scope: preflightScope{Path: sample.Scope}, Result: "warning", Code: diagnostic.ReasonCode, Message: message}) + } else { + _ = invocation.Reporter().Info(message) + } + } + } + add("preparation", preflightScope{Pipeline: input.PipelineID}, "passed", "References and modules are prepared.") + if _, err := local.prepared.ParseSource(ctx, contracts.ParseRequest{Path: input.InputFile.Value, Raw: local.raw}); err != nil { + add("input", preflightScope{Path: input.InputFile.Value}, "failed", err.Error()) + return finish(commandkit.Failure(err.Error()).WithCause(err)) + } + add("input", preflightScope{Path: input.InputFile.Value}, "passed", "Source input is valid.") + outputErr, cacheErr := probePipelineDestinations(loaded.config.Output.Directory, loaded.config.CacheDirectory, local.resolved) + if outputErr != nil { + add("output", preflightScope{Path: loaded.config.Output.Directory}, "failed", outputErr.Error()) + return finish(commandkit.Failure(outputErr.Error()).WithCause(outputErr)) + } + add("output", preflightScope{Path: loaded.config.Output.Directory}, "passed", "Output destination is accessible.") + if pipelineUsesCache(local.resolved) { + if cacheErr != nil { + add("cache", preflightScope{Path: loaded.config.CacheDirectory}, "warning", cacheErr.Error()) + } else { + add("cache", preflightScope{Path: loaded.config.CacheDirectory}, "passed", "Cache destination is accessible.") + } + } + targets, err := preflight.DiscoverTargets(ctx, selected.effective.ResolvedPipeline, selected.catalog, selected.engine) + if err != nil { + add("targets", preflightScope{Pipeline: input.PipelineID}, "failed", err.Error()) + return finish(pipelineResourceFailure(err)) + } + observations, err := preflight.RunSmokeChecks(ctx, selected.engine, targets, input.Overrides.Execution.Execution, input.Overrides.Execution.TransientRetries) + for _, observation := range observations { + if !observation.Applicable { + continue + } + scope := preflightScope{Profile: observation.ProfileID, Backend: observation.BackendID, Bindings: observation.Bindings} + if observation.Err != nil { + add(string(observation.Kind), scope, "failed", observation.Err.Error()) + } else { + add(string(observation.Kind), scope, "passed", fmt.Sprintf("%s check passed for profile %q.", observation.Kind, observation.ProfileID)) + } + } + if err != nil { + return finish(commandkit.Failure(err.Error()).WithCause(err)) + } + return finish(commandkit.Success()) +} diff --git a/internal/cli/pipeline_preflight_test.go b/internal/cli/pipeline_preflight_test.go new file mode 100644 index 00000000..2ecb093c --- /dev/null +++ b/internal/cli/pipeline_preflight_test.go @@ -0,0 +1,184 @@ +package cli + +import ( + "bytes" + "context" + "encoding/json" + "errors" + "os" + "path/filepath" + "strings" + "testing" + + "go.maximumdirect.net/commandkit" + "go.maximumdirect.net/promptkit" + "go.yaml.in/yaml/v4" +) + +type readinessClient struct { + calls int + content string +} + +func (client *readinessClient) Generate(context.Context, promptkit.GenerateRequest) (*promptkit.GenerateResponse, error) { + client.calls++ + return &promptkit.GenerateResponse{Content: client.content}, nil +} + +func TestPreflightRoutesAndReports(t *testing.T) { + probe := &runProbe{} + _, config, input, _ := runFixture(t, probe) + client := &readinessClient{content: `{"status":"ok"}`} + app, err := NewApplication("test", Options{Registries: runRegistries(t, probe), LLMClient: client}) + if err != nil { + t.Fatal(err) + } + for _, test := range []struct { + args []string + format string + }{ + {[]string{"preflight", "demo"}, "json"}, + {[]string{"pipeline", "preflight", "demo"}, "yaml"}, + } { + args := append(test.args, "--config", config, "--input-file", input, "--cache", "bypass", "--format", test.format) + var out, stderr bytes.Buffer + outcome := app.Execute(context.Background(), args, commandkit.Streams{Out: &out, Err: &stderr}) + if outcome.Status != 0 { + t.Fatalf("%v: %+v %s", args, outcome, stderr.String()) + } + var report preflightReport + if test.format == "json" { + err = json.Unmarshal(out.Bytes(), &report) + } else { + err = yaml.Unmarshal(out.Bytes(), &report) + } + if err != nil || !report.Ready || report.Pipeline != "demo" || len(report.Checks) == 0 { + t.Fatalf("report=%+v error=%v output=%s", report, err, out.String()) + } + } + if client.calls != 2 || probe.parsed != 2 { + t.Fatalf("calls=%d parses=%d", client.calls, probe.parsed) + } + client.content = `{"status":"bad"}` + var out, stderr bytes.Buffer + outcome := app.Execute(context.Background(), []string{"preflight", "demo", "--config", config, "--input-file", input, "--cache", "bypass", "--format", "json"}, commandkit.Streams{Out: &out, Err: &stderr}) + var failed preflightReport + if err := json.Unmarshal(out.Bytes(), &failed); err != nil || outcome.Status == 0 || failed.Ready || len(failed.Checks) == 0 { + t.Fatalf("outcome=%+v report=%+v error=%v", outcome, failed, err) + } + if outcome.Cause == nil { + t.Fatal("failed readiness lost its cause") + } +} + +func TestPreflightLocalFailureStopsBeforeProvider(t *testing.T) { + probe := &runProbe{} + _, config, input, _ := runFixture(t, probe) + client := &readinessClient{content: `{"status":"ok"}`} + app, err := NewApplication("test", Options{Registries: runRegistries(t, probe), LLMClient: client}) + if err != nil { + t.Fatal(err) + } + var out, stderr bytes.Buffer + outcome := app.Execute(context.Background(), []string{"preflight", "demo", "--config", config, "--input-file", input + "-missing", "--format", "json"}, commandkit.Streams{Out: &out, Err: &stderr}) + var report preflightReport + if err := json.Unmarshal(out.Bytes(), &report); err != nil || outcome.Status == 0 || report.Ready || client.calls != 0 { + t.Fatalf("outcome=%+v report=%+v error=%v calls=%d", outcome, report, err, client.calls) + } + if !errors.Is(outcome.Cause, context.Canceled) && outcome.Cause == nil { + t.Fatal("missing input cause") + } + out.Reset() + stderr.Reset() + outcome = app.Execute(context.Background(), []string{"preflight", "demo", "--config", config}, commandkit.Streams{Out: &out, Err: &stderr}) + if outcome.Status == 0 || out.Len() != 0 || client.calls != 0 { + t.Fatalf("missing required flag: %+v %q", outcome, out.String()) + } +} + +func TestPreflightHelpIsLazy(t *testing.T) { + app, err := NewApplication("test", Options{LookupEnv: func(string) (string, bool) { t.Fatal("help loaded configuration"); return "", false }}) + if err != nil { + t.Fatal(err) + } + for _, args := range [][]string{{"preflight", "--help"}, {"pipeline", "preflight", "--help"}} { + var out, stderr bytes.Buffer + outcome := app.Execute(context.Background(), args, commandkit.Streams{Out: &out, Err: &stderr}) + if outcome.Status != 0 || !strings.Contains(out.String(), "--input-file") { + t.Fatalf("%v: %+v %s", args, outcome, stderr.String()) + } + } +} + +func TestPreflightNativeTextVisibility(t *testing.T) { + probe := &runProbe{} + _, config, input, _ := runFixture(t, probe) + client := &readinessClient{content: `{"status":"ok"}`} + app, err := NewApplication("test", Options{Registries: runRegistries(t, probe), LLMClient: client}) + if err != nil { + t.Fatal(err) + } + for _, test := range []struct { + flag string + summary, detail bool + }{{"", true, false}, {"--verbose", true, true}, {"--quiet", false, false}} { + args := []string{"preflight", "demo", "--config", config, "--input-file", input, "--cache", "bypass"} + if test.flag != "" { + args = append(args, test.flag) + } + var out, stderr bytes.Buffer + outcome := app.Execute(context.Background(), args, commandkit.Streams{Out: &out, Err: &stderr}) + if outcome.Status != 0 || strings.Contains(out.String(), "is ready") != test.summary || strings.Contains(stderr.String(), "Source input is valid") != test.detail { + t.Fatalf("%s: outcome=%+v stdout=%q stderr=%q", test.flag, outcome, out.String(), stderr.String()) + } + } +} + +func TestPreflightReportDeliveryFailureDoesNotRepeatChecks(t *testing.T) { + probe := &runProbe{} + _, config, input, _ := runFixture(t, probe) + client := &readinessClient{content: `{"status":"ok"}`} + app, err := NewApplication("test", Options{Registries: runRegistries(t, probe), LLMClient: client}) + if err != nil { + t.Fatal(err) + } + cause := errors.New("output unavailable") + var stderr bytes.Buffer + outcome := app.Execute(context.Background(), []string{"preflight", "demo", "--config", config, "--input-file", input, "--cache", "bypass", "--format", "json"}, commandkit.Streams{Out: failingResultWriter{cause: cause}, Err: &stderr}) + if outcome.Status == 0 || client.calls != 1 || probe.parsed != 1 { + t.Fatalf("outcome=%+v calls=%d parses=%d", outcome, client.calls, probe.parsed) + } +} + +func TestPreflightCacheFailureWarnsWithoutPreventingReadiness(t *testing.T) { + probe := &runProbe{} + _, config, input, _ := runFixture(t, probe) + client := &readinessClient{content: `{"status":"ok"}`} + app, err := NewApplication("test", Options{Registries: runRegistries(t, probe), LLMClient: client}) + if err != nil { + t.Fatal(err) + } + file := filepath.Join(t.TempDir(), "not-a-directory") + if err := os.WriteFile(file, []byte("x"), 0o600); err != nil { + t.Fatal(err) + } + encoded, err := json.Marshal(filepath.Join(file, "cache")) + if err != nil { + t.Fatal(err) + } + var out, stderr bytes.Buffer + outcome := app.Execute(context.Background(), []string{"preflight", "demo", "--config", config, "--input-file", input, "--set", "/cache_directory=" + string(encoded), "--format", "json"}, commandkit.Streams{Out: &out, Err: &stderr}) + var report preflightReport + if err := json.Unmarshal(out.Bytes(), &report); err != nil || outcome.Status != 0 || !report.Ready { + t.Fatalf("outcome=%+v report=%+v error=%v stderr=%s", outcome, report, err, stderr.String()) + } + found := false + for _, check := range report.Checks { + if check.ID == "cache" && check.Result == "warning" { + found = true + } + } + if !found { + t.Fatalf("missing cache warning: %+v", report) + } +} diff --git a/internal/cli/pipeline_run_test.go b/internal/cli/pipeline_run_test.go index f26c9e89..b2086e13 100644 --- a/internal/cli/pipeline_run_test.go +++ b/internal/cli/pipeline_run_test.go @@ -163,7 +163,7 @@ func runRegistries(t *testing.T, probe *runProbe) pipeline.Registries { check(jsonoutput.Register(registries.Outputs)) check(pipeline.RegisterArtifactCodec(registries.ArtifactCodecs, inspectionCodec{})) slots := runReferenceSlots() - check(pipeline.RegisterExtractorBuilder(registries.Extractors, pipeline.ModuleSpec{Key: "fixture/extract", Stage: pipeline.StageExtract, ArtifactKind: "test/inspection", ExecutionClass: contracts.ExecutionClassLLMBacked, Prompts: []string{"inspect-initial", "inspect-correction"}, ReferenceSlots: slots}, func(options map[string]any) error { return pipeline.RejectUnknownOptions(options) }, func(request pipeline.BuildRequest) (contracts.Extractor[inspectionArtifact], error) { + check(pipeline.RegisterExtractorBuilder(registries.Extractors, pipeline.ModuleSpec{Key: "fixture/extract", Stage: pipeline.StageExtract, ArtifactKind: "test/inspection", ExecutionClass: contracts.ExecutionClassLLMBacked, Prompts: []string{"inspect-initial", "inspect-correction"}, InitialPrompts: []string{"inspect-initial"}, ReferenceSlots: slots}, func(options map[string]any) error { return pipeline.RejectUnknownOptions(options) }, func(request pipeline.BuildRequest) (contracts.Extractor[inspectionArtifact], error) { probe.engines = append(probe.engines, request.Dependencies.Engine) return &runProducer{key: "fixture/extract", engine: request.Dependencies.Engine, probe: probe}, nil }))