diff --git a/command.go b/command.go index a3de019..e06200e 100644 --- a/command.go +++ b/command.go @@ -17,6 +17,10 @@ import ( // before changing an App registry. type Command struct{ record *commandRecord } +// ErrHelpRequested may be returned by CommandSpec.CheckInput to display command +// help without starting invocation features or enforcing their required flags. +var ErrHelpRequested = errors.New("command help requested") + // Declaration is a captured canonical command or application routing rule // accepted by New and App.Register. Use []Declaration when collecting both // kinds. Group and RootGroup children remain Commands; install routing rules @@ -189,7 +193,8 @@ type CommandSpec[I any] struct { Flags []Flag[I] // Arguments declares the command's positional inputs. Arguments []Argument[I] - // CheckInput validates declared combinations of parsed inputs. + // CheckInput validates declared combinations of parsed inputs. Returning + // ErrHelpRequested displays help without running the command or its features. CheckInput func(I) error // Run handles an invocation. It may be nil for a command used as a group. Run func(Invocation, I) Outcome @@ -258,9 +263,15 @@ func (c typedCommand[I]) prepare(flagValues, flagSpellings [][]string, occurrenc input := prepared.build() if c.spec.CheckInput != nil { if err := c.spec.CheckInput(input); err != nil { + if errors.Is(err, ErrHelpRequested) { + return current.renderHelp(current.route.canonicalPath) + } return classifyInputError(err) } } + if current.featureEnabled && current.featureRequiredError != nil { + return classifyInputError(current.featureRequiredError) + } current.startFeatures() if c.privateRun != nil { return c.privateRun(current.commandContext(), input) diff --git a/docs/consumers/guide.md b/docs/consumers/guide.md index 0324925..d4cfa7b 100644 --- a/docs/consumers/guide.md +++ b/docs/consumers/guide.md @@ -401,7 +401,11 @@ An empty suite adds nothing. The flag defaults to false; explicit false and repeated selections use the ordinary Boolean rules. Applications pass `Invocation.Context` into PromptKit and wait for their own work before returning. The observer starts after command input construction and successful `CheckInput`, -before `Run`; validation or acquisition inside `Run` is included. Help, version, +before `Run`; validation or acquisition inside `Run` is included. +`CommandSpec.CheckInput` may return `commandkit.ErrHelpRequested` for a +help-only preflight result; core renders help without starting features or +requiring execution-only invocation flags. ckconfig uses this for bare +`config explain`. Help, version, completion, parse errors, and rejected command inputs do not start observation. The requested summary is text on diagnostics after deferred messages and before diff --git a/docs/roadmap/remediation.md b/docs/roadmap/remediation.md index e0bf5d8..8bfec85 100644 --- a/docs/roadmap/remediation.md +++ b/docs/roadmap/remediation.md @@ -81,7 +81,12 @@ upstream-domain test suite. ## R2: Honor ckconfig's help-only fallback before starting invocation features -**Priority:** P2. **Status:** open. **Plan coverage:** Stages 2–4 and 7–8. +**Priority:** P2. **Status:** complete. **Plan coverage:** Stages 2–4 and 7–8. + +Added the CheckInput help signal and deferred feature requiredness until real +execution. Regression checks cover implicit/explicit/aliased help, malformed +values, real operations, and normal ckprompt installation. All three workspace +suites passed on Go 1.27.4. **Relevant code and contracts:** diff --git a/execute.go b/execute.go index 9f97418..df93074 100644 --- a/execute.go +++ b/execute.go @@ -93,10 +93,13 @@ func (current *execution) prepareFeatures(parsed commandmeta.Result, required bo if offset+count > len(parsed.InvocationFlagValues) || offset+count > len(parsed.InvocationFlagSpellings) { return fmt.Errorf("missing invocation feature flag values") } - start, err := feature.payload.prepare(parsed.InvocationFlagValues[offset:offset+count], parsed.InvocationFlagSpellings[offset:offset+count], parsed.FlagOccurrences, required) + start, err := feature.payload.prepare(parsed.InvocationFlagValues[offset:offset+count], parsed.InvocationFlagSpellings[offset:offset+count], parsed.FlagOccurrences, false) if err != nil { return err } + if required && current.featureRequiredError == nil { + current.featureRequiredError = feature.payload.requiredError(parsed.InvocationFlagValues[offset : offset+count]) + } current.featureStarts = append(current.featureStarts, start) offset += count } @@ -104,16 +107,17 @@ func (current *execution) prepareFeatures(parsed commandmeta.Result, required bo } type execution struct { - app *App - ctx context.Context - reporter *Reporter - featureStarts []func(Invocation) (context.Context, func() Report) - featureEnabled bool - featureReports []func() Report - debugEvents []string - snapshot *routingSnapshot - session *internalcobra.Session - route routeResult + app *App + ctx context.Context + reporter *Reporter + featureStarts []func(Invocation) (context.Context, func() Report) + featureRequiredError error + featureEnabled bool + featureReports []func() Report + debugEvents []string + snapshot *routingSnapshot + session *internalcobra.Session + route routeResult } func (current *execution) startFeatures() { diff --git a/integrations/ckconfig/help_feature_test.go b/integrations/ckconfig/help_feature_test.go new file mode 100644 index 0000000..5a69e1f --- /dev/null +++ b/integrations/ckconfig/help_feature_test.go @@ -0,0 +1,52 @@ +package ckconfig_test + +import ( + "bytes" + "context" + "errors" + "go.maximumdirect.net/ckconfig" + ck "go.maximumdirect.net/commandkit" + "go.maximumdirect.net/configkit" + "strings" + "testing" +) + +func TestExplainHelpExemptsInvocationFeatures(t *testing.T) { + starts, inputs, loads := 0, 0, 0 + feature := ck.NewInvocationFeature(ck.InvocationFeatureSpec[struct{}]{ + NewInput: func() struct{} { inputs++; return struct{}{} }, + Flags: []ck.Flag[struct{}]{ck.BoolFlag(ck.FlagMeta{Name: "observe", Required: true}, false, func(*struct{}, ck.Supplied[bool]) {})}, + Start: func(ck.Invocation, struct{}) (context.Context, func() ck.Report) { + starts++ + return nil, func() ck.Report { return ck.Report{Value: "summary"} } + }, + }) + config := ckconfig.AppCommand(func(context.Context, ckconfig.Selection) (*configkit.Result[struct{}], error) { + loads++ + return nil, errors.New("load failed") + }) + app, err := ck.New(ck.Identity{Name: "test"}, config, ck.WithInvocationFeature(ck.Group("feature", ""), feature), ck.Alias("why", "config explain"), ck.NewCommand(ck.CommandSpec[struct{}]{Name: "run", Run: func(ck.Invocation, struct{}) ck.Outcome { return ck.Success() }})) + if err != nil { + t.Fatal(err) + } + for _, args := range [][]string{{"config", "explain"}, {"config", "explain", "--help"}, {"why", "--observe"}} { + var out, diag bytes.Buffer + result := app.Execute(context.Background(), args, ck.Streams{Out: &out, Err: &diag}) + if result.Status != 0 || !strings.Contains(out.String(), "Usage:") || diag.Len() != 0 || starts != 0 || inputs != 0 || loads != 0 { + t.Fatalf("%v: %#v %q %q starts=%d inputs=%d loads=%d", args, result, out.String(), diag.String(), starts, inputs, loads) + } + } + for _, args := range [][]string{{"config", "explain", "--path=/"}, {"run"}, {"config", "explain", "--observe=bad"}} { + if r := app.Execute(context.Background(), args, ck.Streams{}); r.Kind != ck.OutcomeUsage { + t.Fatalf("%v: %#v", args, r) + } + } + var diag bytes.Buffer + if r := app.Execute(context.Background(), []string{"run", "--observe"}, ck.Streams{Err: &diag}); r.Status != 0 || starts != 1 || !strings.Contains(diag.String(), "summary") { + t.Fatalf("%#v %q", r, diag.String()) + } + app.Execute(context.Background(), []string{"config", "explain", "--path=/", "--observe"}, ck.Streams{}) + if starts != 2 || loads != 1 { + t.Fatalf("starts=%d loads=%d", starts, loads) + } +} diff --git a/integrations/ckconfig/input.go b/integrations/ckconfig/input.go index e362d04..d22ffd1 100644 --- a/integrations/ckconfig/input.go +++ b/integrations/ckconfig/input.go @@ -150,7 +150,13 @@ func newConfigOperationCommand[I, S any](prepared *preparedSuite[I, S], operatio if input == nil { return fmt.Errorf("configuration input must not be nil") } - return prepareConfigOperation(prepared, operation, input) + if err := prepareConfigOperation(prepared, operation, input); err != nil { + return err + } + if input.plan.help { + return commandkit.ErrHelpRequested + } + return nil }, Run: func(invocation commandkit.Invocation, input *configCommandInput[I, S]) commandkit.Outcome { return runConfigOperation(invocation, operation, input) diff --git a/integrations/ckprompt/examples/composed/main_test.go b/integrations/ckprompt/examples/composed/main_test.go index 572c746..66791eb 100644 --- a/integrations/ckprompt/examples/composed/main_test.go +++ b/integrations/ckprompt/examples/composed/main_test.go @@ -1024,3 +1024,17 @@ func TestNarrowSuiteReportsReturnedCancellation(t *testing.T) { t.Fatalf("%#v %q", out, diag.String()) } } + +func TestExplainHelpDoesNotReportUsage(t *testing.T) { + app, err := newApp() + if err != nil { + t.Fatal(err) + } + for _, args := range [][]string{{"config", "explain", "--show-tokens"}, {"config", "explain", "--help", "--show-tokens"}} { + var out, diag bytes.Buffer + result := app.Execute(context.Background(), args, commandkit.Streams{Out: &out, Err: &diag}) + if result.Status != 0 || !strings.Contains(out.String(), "Usage:") || diag.Len() != 0 { + t.Fatalf("%v: %#v %q %q", args, result, out.String(), diag.String()) + } + } +} diff --git a/invocation_feature.go b/invocation_feature.go index 4025912..a7672f5 100644 --- a/invocation_feature.go +++ b/invocation_feature.go @@ -30,6 +30,7 @@ type InvocationFeatureSpec[I any] struct { type invocationFeaturePayload interface { bridgeFlags() []commandmeta.Flag + requiredError([][]string) error prepare([][]string, [][]string, []commandmeta.FlagOccurrence, bool) (func(Invocation) (context.Context, func() Report), error) } @@ -39,6 +40,15 @@ func (f typedInvocationFeature[I]) bridgeFlags() []commandmeta.Flag { return (typedCommand[I]{spec: CommandSpec[I]{Flags: f.spec.Flags}}).bridgeFlags() } +func (f typedInvocationFeature[I]) requiredError(values [][]string) error { + for i, flag := range f.spec.Flags { + if flag.binding.meta.Required && !flag.binding.deferredRequired && len(values[i]) == 0 { + return fmt.Errorf("required flag --%s was not supplied", flag.binding.meta.Name) + } + } + return nil +} + func (f typedInvocationFeature[I]) prepare(values, spellings [][]string, occurrences []commandmeta.FlagOccurrence, required bool) (func(Invocation) (context.Context, func() Report), error) { input, err := prepareInputWithOccurrences(CommandSpec[I]{NewInput: f.spec.NewInput, Flags: f.spec.Flags}, values, spellings, occurrences, nil, required) if err != nil {