strictcli v0.39.0 /go/strictcli
On this page

Package strictcli is a strict, zero-dependency CLI framework for Go with mandatory help text, type-safe flags, groups, and schema export.

#go/strictcli

#go/strictcli

Package strictcli is a strict, zero-dependency CLI framework for Go with mandatory help text, type-safe flags, groups, and schema export.

#EffectReadOnly

Go go
const EffectReadOnly = "read_only"

The two legal command classifications. There is no default: every command declares one through WithEffect, and a command registered without it is a registration-time hard error. Deprecated commands are exempt (no handler).

#EffectMutating

Go go
const EffectMutating = "mutating"

#ProcMutate

Go go
const ProcMutate = "proc_mutate"

Effect kinds. CacheWrite has NO public method: it is minted only by framework-internal code (schema dump, test-coverage shards and manifest) and is unreachable from application code.

#ProcSpawn

Go go
const ProcSpawn  = "proc_spawn"

#FileWrite

Go go
const FileWrite  = "file_write"

#NetMutate

Go go
const NetMutate  = "net_mutate"

#CacheWrite

Go go
const CacheWrite = "cache_write"

#SourceCLI

Go go
const SourceCLI     Source = iota // explicitly passed on the command line

#SourceEnv

Go go
const SourceEnv     Source = iota // from an environment variable

#SourceConfig

Go go
const SourceConfig  Source = iota // from a config file

#SourceDefault

Go go
const SourceDefault Source = iota // from the flag's default value

#SourceImplied

Go go
const SourceImplied Source = iota // injected by an Implies dependency

#SourceInfra

Go go
const SourceInfra   Source = iota // default resolved through a RelativeToRoot infra root

#TypeStr

Go go
const TypeStr   FlagType = iota

#TypeBool

Go go
const TypeBool  FlagType = iota

#TypeInt

Go go
const TypeInt   FlagType = iota

#TypeFloat

Go go
const TypeFloat FlagType = iota

#TypeListStr

Go go
const TypeListStr   FlagType = listBit | TypeStr

List types: a repeatable flag whose items are coerced to the element type.

#TypeListInt

Go go
const TypeListInt   FlagType = listBit | TypeInt

#TypeListFloat

Go go
const TypeListFloat FlagType = listBit | TypeFloat

#TypeDictStr

Go go
const TypeDictStr   FlagType = listBit | dictBit | TypeStr

Dict types: a repeatable key=value flag whose values are coerced to the value type.

#TypeDictInt

Go go
const TypeDictInt   FlagType = listBit | dictBit | TypeInt

#TypeDictFloat

Go go
const TypeDictFloat FlagType = listBit | dictBit | TypeFloat

#CheckContext

Go go
type CheckContext interface

CheckContext provides project context to check implementations.

#ConnectionEnvReader

Go go
type ConnectionEnvReader interface

ConnectionEnvReader is an OPTIONAL capability a CheckContext may expose: the value of a declared connection env (WithConnectionEnv), read live -- EXCEPT under --hermetic, where it resolves as absent ("", false) so a check can skip visibly instead of connecting. The check command wraps the tool-supplied CheckContext in a value that satisfies this interface, backed by the app's declared connection envs and the invocation's hermetic state. Checks that need a connection URL type-assert the context to this interface:

if r, ok := ctx.(strictcli.ConnectionEnvReader); ok { dsn, present := r.ConnectionEnvValue("DATABASE_URL") ... }

IsHermetic reports whether the invocation ran under --hermetic. It exists so a check can DISTINGUISH the two cases that ConnectionEnvValue's present=false otherwise conflates: "--hermetic suppressed the connection env" vs "the env var is simply unset". A check that layers config fallbacks below the env must honor hermetic even when the env is unset -- otherwise it falls through to a config URL and connects, violating the hermetic guarantee. The pattern is:

dsn, present := r.ConnectionEnvValue("DATABASE_URL") if !present { if r.IsHermetic() { return rep.Skipped("hermetic: connection suppressed") } // env unset but not hermetic -- config fallback is allowed here }

#CheckOutcome

Go go
type CheckOutcome struct

CheckOutcome is the ceiling-typed result of a check implementation. Its fields are unexported so callers cannot forge one: a valid CheckOutcome is obtained ONLY through reporter methods (Passed/Skipped/Found). The zero value has minted=false and is rejected by the runner (belt-and-braces against an impl that returns something a reporter did not mint).

#WarnReporter

Go go
type WarnReporter struct

WarnReporter is handed to warn-severity check impls. It can mint warn-severity problems and terminal outcomes but structurally LACKS error-minting: there is no Error method in its method set, so an attempt to raise an error-severity problem from a warn check fails to compile.

#ErrorReporter

Go go
type ErrorReporter struct

ErrorReporter is handed to error-severity check impls. It has everything WarnReporter has PLUS Error (mints an error-severity problem).

#CheckSpecMeta

Go go
type CheckSpecMeta struct

CheckSpecMeta carries the declarative metadata of a provider-sourced check, mirroring the fields of a [checks.] table in checks.toml. Severity is cross-checked against the constructor form at materialization time.

#CheckSpec

Go go
type CheckSpec struct

CheckSpec is a fully-formed, ceiling-typed check produced by a provider. It is opaque: construct one ONLY via NewErrorCheckSpec / NewWarnCheckSpec, which bind the reporter form to the severity so the impl cannot mint a problem its declared severity forbids.

#RunChecksOptions

Go go
type RunChecksOptions struct

RunChecksOptions configures which checks to run and how to handle results.

#CheckRunResult

Go go
type CheckRunResult struct

CheckRunResult holds the outcome of running a single check. The verdict is derived from the minted CheckOutcome -- the runner's exit/cascade logic and the formatters all consume the same derived accessors (one source of truth).

#ConfigField

Go go
type ConfigField struct

ConfigField describes a declared config file field.

#ConfigFieldOption

Go go
type ConfigFieldOption func(*ConfigField)

ConfigFieldOption configures a ConfigField.

#Context

Go go
type Context struct

Context provides structured output and provenance for command handlers. It is constructed unconditionally for every dispatch and passed to the handler. Each output method writes to the appropriate stream (stdout or stderr).

#Grant

Go go
type Grant struct

Grant is a per-command, per-effect-kind authorization with a mandatory reason.

A grant is not permission to do something otherwise forbidden; it is a labelled reason that surfaces in the preview so a reviewer reading a dry run sees why a dangerous step is there.

#Forwarding

Go go
type Forwarding struct

Forwarding declares that a handler deliberately accepts and forwards the app's global flag values. In Go the declaration is inert beyond the schema emission (guard v2's enforcement is Python-only, §10.3); it exists so the API surface stays in parity and consumers can label forwarding wrappers uniformly.

#Unsettled

Go go
type Unsettled struct

Unsettled is Go's VOID carrier: the value returned by write, mkdir, remove, rename and chmod in BOTH modes. It never carries a value, only a brand, and exists solely to give every Go effect method one uniform return shape. Its extractors panic in both modes, and it is never forwardable -- passing one into a later effect is a call-time hard error.

The [0]func() field makes the struct non-comparable: u == v is a compile error. That is the only compile-time protection Go can offer (§17).

#Completed

Go go
type Completed struct

Completed is the result of a subprocess that ran to completion, and a settleable carrier. Stdout/Stderr are the child's output decoded as UTF-8 strictly with a single trailing newline removed -- the form that can be forwarded straight into a later effect's argv.

#Spawned

Go go
type Spawned struct

Spawned is a handle for a started-but-not-awaited child process, and a settleable carrier. It has NO scalar projection: forwarding a Spawned into a string position is a call-time hard error.

#Response

Go go
type Response struct

Response is the result of an HTTP request, and a settleable carrier. Header names are lower-cased.

#EffectOption

Go go
type EffectOption struct

EffectOption is one trailing option on an effects-handle call. Its canonical snake_case name is what errEffectOptionNotAccepted renders, so the message is byte-identical across the three implementations even though the constructor is spelled Stream(bool).

#Effects

Go go
type Effects struct

Effects is the effects handle reached as ctx.Effects().

Exactly eight methods, and the set is CLOSED: there is no escape hatch that mints an unlisted effect, and CacheWrite has no public method at all.

#InvokeError

Go go
type InvokeError struct

InvokeError is returned by App.Call() when invocation fails (unknown command, missing flags, mutex violations, etc.).

#CallOption

Go go
type CallOption func(*callOptions)

CallOption configures one App.Call. Go's Call takes its kwargs as a map, so consent cannot ride in them the way Python's keyword-only argument does -- it is a variadic option instead, which is this package's existing shape for "a declaration that is not data".

#Outcome

Go go
type Outcome struct

Outcome is the opaque, branded result of a command handler. It is constructed only via Exit or ExitData and carries an exit code plus, optionally, structured data. When data is present, the framework JSON-prints it to stdout as one compact line and makes it available to Test and Call.

#Source

Go go
type Source int

Source represents where a flag value came from.

#FlagType

Go go
type FlagType int

FlagType represents the type of a flag value. Scalar types: TypeStr, TypeBool, TypeInt, TypeFloat. Compound types encode the item/value type in the upper bits: list types = 0x100 | scalar, dict types = 0x200 | scalar.

#Flag

Go go
type Flag struct

Flag represents a --flag declaration.

#Arg

Go go
type Arg struct

Arg represents a positional argument.

#FlagSet

Go go
type FlagSet struct

FlagSet is a reusable bundle of flags.

#MutexGroup

Go go
type MutexGroup struct

MutexGroup is a group of mutually exclusive flags. Exactly one must be provided.

#CoRequired

Go go
type CoRequired struct

CoRequired declares flags that must all appear together or none.

#Requires

Go go
type Requires struct

Requires declares that one flag depends on another being present.

#Implies

Go go
type Implies struct

Implies declares that providing one bool flag automatically sets another bool flag to a value. If the user explicitly provides a contradicting value for the target, it is a parse error.

#Dependency

Go go
type Dependency interface

Dependency is either a CoRequired, Requires, or Implies constraint.

#InfraRootPath

Go go
type InfraRootPath struct

InfraRootPath is an opaque marker produced by RelativeToRoot. It represents a filesystem path built from a declared infrastructure root (identified by its env var name) joined with zero or more path parts. Config-path markers resolve eagerly at construction; flag-default markers resolve when defaults are applied at parse time. A marker referencing an undeclared root is a registration-time hard error.

#PassthroughHandler

Go go
type PassthroughHandler func(ctx *Context, name string, args []string, globals map[string]interface{}) int

PassthroughHandler is the handler type for passthrough commands.

#Command

Go go
type Command struct

Command is a leaf command with a handler.

#Group

Go go
type Group struct

Group is a container for nested commands and subgroups (arbitrary depth).

#Result

Go go
type Result struct

Result is returned by App.Test().

#App

Go go
type App struct

App is the root CLI application.

#AppOption

Go go
type AppOption func(*App)

AppOption configures an App.

#FlagOption

Go go
type FlagOption func(*Flag)

FlagOption configures a Flag.

#ArgOption

Go go
type ArgOption func(*Arg)

ArgOption configures an Arg.

#CmdOption

Go go
type CmdOption func(*Command)

CmdOption configures a Command during registration.

#Tool

Go go
type Tool struct

Tool is a descriptor for exposing CLI commands to tool-using LLM agents.

Effect and Consequential publish the effects-regime classification BESIDE the argument schema (never inside it): a consumer rendering this tool must be able to see that the command changes things and that calling it requires stating consent. Same vocabulary as the schema dump: Effect is mandatory, Consequential defaults to false.

#NewErrorCheckSpec

Go go
func NewErrorCheckSpec(meta CheckSpecMeta, impl func(CheckContext, *ErrorReporter) CheckOutcome) CheckSpec

NewErrorCheckSpec builds an error-severity check spec. The impl receives an *ErrorReporter (which can mint both error- and warn-severity problems). The meta's Severity must be "error" -- a mismatch is a hard error at materialization (the provider analog of the TOML/register severity check).

#NewWarnCheckSpec

Go go
func NewWarnCheckSpec(meta CheckSpecMeta, impl func(CheckContext, *WarnReporter) CheckOutcome) CheckSpec

NewWarnCheckSpec builds a warn-severity check spec. The impl receives a *WarnReporter, which structurally lacks error-minting: a warn check cannot cascade. The meta's Severity must be "warn".

#FormatCheckResults

Go go
func FormatCheckResults(results []CheckRunResult, verbose bool) string

FormatCheckResults formats check results as a human-readable string. Layout: the derived status label, name, and message, with minted problems listed under the check row grouped by severity (error problems first, then warn problems), each tagged with its severity. Problems are shown for fail/warn/skip outcomes or when verbose is true. No trailing newline -- callers use fmt.Println().

#FormatCheckResultsJSON

Go go
func FormatCheckResultsJSON(results []CheckRunResult) string

FormatCheckResultsJSON formats check results as a JSON array string. Each entry carries the derived status plus the minted problems (each with its severity and text). Empty problems serialize as [] rather than null. No trailing newline.

#ConfigFieldType

Go go
func ConfigFieldType(t FlagType) ConfigFieldOption

ConfigFieldType sets the type for a config field (default: TypeStr).

#ConfigFieldHelp

Go go
func ConfigFieldHelp(help string) ConfigFieldOption

ConfigFieldHelp sets the help text for a config field (required).

#ConfigFieldDefault

Go go
func ConfigFieldDefault(v interface{}) ConfigFieldOption

ConfigFieldDefault sets the default value for a config field.

#Resource

Go go
func Resource(token string) EffectOption

Resource declares an opaque resource token naming what the effect produces. Declared metadata only: it never gates, skips, orders or deduplicates anything.

#SkipIfCurrent

Go go
func SkipIfCurrent(token string) EffectOption

SkipIfCurrent declares a preview-only conditional annotation. In dry mode it renders a suffix on the log line; in real mode the effect executes unconditionally. There is no currency machinery of any kind behind it.

#UseGrant

Go go
func UseGrant(name string) EffectOption

UseGrant names a grant declared on the running command. Its kind must match the effect's kind.

#Cwd

Go go
func Cwd(dir string) EffectOption

Cwd sets the working directory of a run or spawn.

#EffectEnv

Go go
func EffectEnv(env map[string]string) EffectOption

EffectEnv merges environment entries OVER the inherited environment, never replacing it.

Named EffectEnv rather than Env because the package already exports Env(varName string) FlagOption and Go has no overloading.

#Check

Go go
func Check(check bool) EffectOption

Check opts a single call out of the "a failed operation is an error" rule: with Check(false) the result is returned with its real exit code / status and the handler decides.

#Stream

Go go
func Stream(stream bool) EffectOption

Stream makes a run inherit stdout/stderr instead of capturing them; the returned Stdout/Stderr are then empty strings.

#Body

Go go
func Body(body []byte) EffectOption

Body sets an HTTP request body. A body is a payload, not a name: it is not a carrier-accepting position.

Go go
func Header(name, value string) EffectOption

Header adds one HTTP request header. Repeat it for several headers.

#WithApproveConsequential

Go go
func WithApproveConsequential() CallOption

WithApproveConsequential is the caller's explicit consent on the programmatic path, the counterpart of the CLI's --approve-consequential. A command that declares itself consequential is refused without it; read-only and plain mutating commands are unaffected.

#Exit

Go go
func Exit(code int) Outcome

Exit returns an Outcome that terminates the command with the given exit code and emits no data.

#ExitData

Go go
func ExitData(code int, data interface{}) Outcome

ExitData returns an Outcome that terminates the command with the given exit code and emits data. The framework JSON-marshals data to stdout and captures it for programmatic callers (Test/Call). Data emission is possible ONLY through this constructor.

#IsScalarType

Go go
func IsScalarType(t FlagType) bool

IsScalarType returns true for the four primitive types.

#IsListType

Go go
func IsListType(t FlagType) bool

IsListType returns true for list compound types.

#IsDictType

Go go
func IsDictType(t FlagType) bool

IsDictType returns true for dict compound types.

#IsCompoundType

Go go
func IsCompoundType(t FlagType) bool

IsCompoundType returns true for any compound type (list or dict).

#ItemType

Go go
func ItemType(t FlagType) FlagType

ItemType returns the scalar element type for a compound type. For scalar types, returns the type itself.

#ListOf

Go go
func ListOf(itemType FlagType) FlagType

ListOf creates a list type from a scalar item type. Panics if the item type is not one of TypeStr, TypeInt, TypeFloat.

#DictOf

Go go
func DictOf(valueType FlagType) FlagType

DictOf creates a dict type from a scalar value type. Panics if the value type is not one of TypeStr, TypeInt, TypeFloat.

#RelativeToRoot

Go go
func RelativeToRoot(envVar string, parts ...string) InfraRootPath

RelativeToRoot returns a marker representing a path relative to a declared infrastructure root. envVar names the root (declared via WithInfraRoot); parts are joined onto the resolved root path. Accepted by flag Default(...) and WithConfigPathRelativeToRoot.

#WithEnvPrefix

Go go
func WithEnvPrefix(prefix string) AppOption

WithEnvPrefix sets the environment variable prefix for the app.

#WithConfig

Go go
func WithConfig() AppOption

WithConfig enables config file support.

#WithConfigPath

Go go
func WithConfigPath(path string) AppOption

WithConfigPath overrides the default config file path.

#WithConfigFormat

Go go
func WithConfigFormat(format string) AppOption

WithConfigFormat sets the config file format ("json" or "toml").

#WithNoDefaultConfigPath

Go go
func WithNoDefaultConfigPath() AppOption

WithNoDefaultConfigPath makes the app load NO config file unless --config is explicitly passed on the command line. Without this option (the default), the app loads from the XDG default path.

#WithConfigConflictMode

Go go
func WithConfigConflictMode(mode string) AppOption

WithConfigConflictMode sets the conflict resolution mode for config values. Valid values: "cli-wins" (default) and "error". In "error" mode, a flag set by both config AND cli (or config AND env) is a hard error. Implied sources are excluded from conflict checks.

#WithInfraRoot

Go go
func WithInfraRoot(envVar, defaultPath string) AppOption

WithInfraRoot declares an infrastructure location root: an env var that, when set, overrides defaultPath as the base directory for the tool's data. Multiple roots are allowed (keyed by env var name). Roots are resolved eagerly at construction and are immune to --hermetic (hermetic suppresses config and behavioral env, never location). A leading ~ in the value or default is expanded to the user's home directory.

#WithHandshakeEnv

Go go
func WithHandshakeEnv(envVar, help string) AppOption

WithHandshakeEnv declares a handshake env var: a cross-tool protocol signal set by the invoking process. It has no default and no resolution semantics beyond "read live at access time" via ctx.InfraValue.

#WithConnectionEnv

Go go
func WithConnectionEnv(envVar, help string) AppOption

WithConnectionEnv declares a connection env var: a behavioral "reach outside the process" signal such as a database or service connection URL. It is declared once at app level (name + help) and surfaced in --help and the schema dump alongside the other infrastructure env vars. Unlike roots and handshakes it is hermetic-SUPPRESSED: under --hermetic it resolves as absent. It has no default and is read lazily. Flags bind to it by reference via ConnectionURLFlag. A connection env must not collide with a declared root or handshake var, and duplicate declarations are a hard error.

#WithConfigPathRelativeToRoot

Go go
func WithConfigPathRelativeToRoot(envVar string, parts ...string) AppOption

WithConfigPathRelativeToRoot overrides the config file path with a location relative to a declared infrastructure root. The marker is resolved eagerly at construction into the absolute config path override.

#WithChecks

Go go
func WithChecks(path string) AppOption

WithChecks enables the check system with an explicit path to checks.toml.

#WithChecksEmbed

Go go
func WithChecksEmbed(data []byte) AppOption

WithChecksEmbed enables the check system with inline TOML data (e.g., from //go:embed).

#WithProcObserveAllowlist

Go go
func WithProcObserveAllowlist(prefixes [][]string) AppOption

WithProcObserveAllowlist declares app-level observe authorization: a list of argv PREFIXES, matched element-wise against the leading elements of an effect's argv by string equality. A ctx.Effects().Run whose argv matches any listed prefix is an observe -- it executes even in dry mode, returns a real value, and is never written to the would-do log.

#WithTestCoverage

Go go
func WithTestCoverage() AppOption

WithTestCoverage enables CLI test-coverage instrumentation. Every Test() and Call() invocation records the resolved command path to per-process shard files (.strictcli/coverage/-.jsonl). A built-in cli-test-coverage check (auto-registered via the provider mechanism) merges shards and hard-FAILs listing every command with zero coverage.

#Short

Go go
func Short(s string) FlagOption

Short sets the single-character short form for a flag.

#Default

Go go
func Default(v interface{}) FlagOption

Default sets the default value for a flag.

#Env

Go go
func Env(varName string) FlagOption

Env sets the environment variable name for a flag.

#Prefixed

Go go
func Prefixed(b bool) FlagOption

Prefixed controls whether env var prefix validation is applied.

#Choices

Go go
func Choices(vals ...interface{}) FlagOption

Choices sets the allowed values for a flag.

#Repeatable

Go go
func Repeatable() FlagOption

Repeatable marks a flag as accepting multiple occurrences.

#Unique

Go go
func Unique(b bool) FlagOption

Unique controls whether a repeatable flag rejects duplicate values.

#ConflictMode

Go go
func ConflictMode(mode string) FlagOption

ConflictMode sets the per-flag config conflict mode, overriding the app-level default (WithConfigConflictMode). Must be "cli-wins" or "error". This applies only to flags; standalone ConfigFields have no CLI/env conflict surface, and a flag-colliding ConfigField inherits the flag's handling.

#ConnectionURLFlag

Go go
func ConnectionURLFlag(envVar string) FlagOption

ConnectionURLFlag marks a flag as a connection-URL (URL-class) flag bound to the declared connection env named envVar (see WithConnectionEnv). The value resolves from the CLI token if present, else from the connection env (lazily, hermetic-suppressed), with no default. Binding to an env that was not declared via WithConnectionEnv is a registration-time hard error, as is marking a flag URL-class without a binding.

#EnvSeparator

Go go
func EnvSeparator(sep string) FlagOption

EnvSeparator sets the character used to split an env var value into multiple values for a repeatable flag (e.g., "," to split "a,b,c" into ["a","b","c"]).

#ValidateFn

Go go
func ValidateFn(fn func(interface{}) error) FlagOption

ValidateFn sets a validation function for a flag.

#NegatableOpt

Go go
func NegatableOpt(b bool) FlagOption

Negatable controls whether a bool flag supports --no-X negation.

#ArgRequired

Go go
func ArgRequired(b bool) ArgOption

ArgRequired sets whether an arg is required.

#ArgDefault

Go go
func ArgDefault(v interface{}) ArgOption

ArgDefault sets the default value for an arg.

#Variadic

Go go
func Variadic() ArgOption

Variadic marks a positional argument as variadic (collects remaining values).

#ArgType

Go go
func ArgType(t FlagType) ArgOption

ArgType sets the type for a positional argument.

#ArgChoices

Go go
func ArgChoices(vals ...interface{}) ArgOption

ArgChoices sets the allowed values for a positional argument.

#WithArgs

Go go
func WithArgs(args ...Arg) CmdOption

WithArgs adds positional arguments to a command.

#WithFlags

Go go
func WithFlags(flags ...Flag) CmdOption

WithFlags adds flags to a command.

#WithFlagSets

Go go
func WithFlagSets(flagSets ...FlagSet) CmdOption

WithFlagSets adds flag sets (reusable flag bundles) to a command.

#WithMutex

Go go
func WithMutex(groups ...MutexGroup) CmdOption

WithMutex adds mutex groups to a command.

#WithDependencies

Go go
func WithDependencies(deps ...Dependency) CmdOption

WithDependencies adds dependency constraints to a command.

#WithPassthrough

Go go
func WithPassthrough(handler PassthroughHandler) CmdOption

WithPassthrough marks a command as passthrough (skips parsing, forwards raw args).

#WithHidden

Go go
func WithHidden() CmdOption

WithHidden marks a command as hidden (excluded from help but still routable).

#WithInteractive

Go go
func WithInteractive() CmdOption

WithInteractive marks a command as interactive (visible in help but excluded from tool export).

#WithEffect

Go go
func WithEffect(effect string) CmdOption

WithEffect declares a command's mandatory effect classification: either EffectReadOnly or EffectMutating. There is no default and nothing is inferred -- a command registered without it is a registration-time hard error, and so is a value that is neither constant.

A mutating command participates in dry mode and may call the mutating members of ctx.Effects(). A read_only command may not, and calling any mutating member is a hard error at call time. Classification does NOT decide whether a command prompts -- WithConsequential does (§8).

#WithConsequential

Go go
func WithConsequential() CmdOption

WithConsequential declares that a command's effects are worth interrupting someone for. It is the ONLY thing that makes the framework prompt (§8.1): a plain mutating command never does.

It is deliberately not mandatory. Classification answers "should a dry run record rather than execute?", which almost everything that touches anything answers yes to; consequentiality is a separate, much rarer judgement, and making it mandatory would push every registration to answer it reflexively.

Declaring it on a read_only command is a registration-time hard error: a command that changes nothing has nothing to confirm.

#WithDryRunUnsupported

Go go
func WithDryRunUnsupported(reason string) CmdOption

WithDryRunUnsupported declares that --dry-run is refused for this command, with a mandatory reason. It is the opt-out from the regime's baseline, where a mutating command's effects are recorded rather than executed under --dry-run.

Declare it when a preview would LIE: when the command's effects escape the effects handle, or when its later steps read state its earlier (recorded, therefore un-performed) steps would have written. A refusal that names the reason is honest; a preview that silently diverges from the real run is not.

The reason is mandatory and non-empty, and is shown both in the command's help and in the parse-time refusal. Declaring this on a read_only command is a registration-time hard error: a command that changes nothing has no effects a preview could misrepresent.

#WithGrants

Go go
func WithGrants(grants ...Grant) CmdOption

WithGrants declares per-effect-kind authorizations for a command. A grant is not permission to do something otherwise forbidden; it is a labelled reason that surfaces in the preview so a reviewer reading a dry run sees why a dangerous step is there.

#WithForwarding

Go go
func WithForwarding(reason string) CmdOption

WithForwarding declares that a handler deliberately accepts and forwards the app's global flag values. The reason is mandatory and non-empty, and is emitted in the schema so a consumer's audit gate can review every forwarding site. In Go the declaration is inert beyond the schema emission -- guard v2's enforcement is Python-only.

#WithConfigFields

Go go
func WithConfigFields(fields ...string) CmdOption

WithConfigFields binds config fields to a command. At startup, bound required config fields are validated to be present with correct types in the config file. Each field name must exist in app.configFields (validated at Run/Test time).

#WithTags

Go go
func WithTags(tags ...string) CmdOption

WithTags adds tags to a command.

#StringFlag

Go go
func StringFlag(name, help string, opts ...FlagOption) Flag

StringFlag creates a string-typed flag.

#BoolFlag

Go go
func BoolFlag(name, help string, opts ...FlagOption) Flag

BoolFlag creates a boolean-typed flag.

#IntFlag

Go go
func IntFlag(name, help string, opts ...FlagOption) Flag

IntFlag creates an integer-typed flag.

#FloatFlag

Go go
func FloatFlag(name, help string, opts ...FlagOption) Flag

FloatFlag creates a float-typed flag.

#ListFlag

Go go
func ListFlag(itemType FlagType, name, help string, opts ...FlagOption) Flag

ListFlag creates a list-typed flag. itemType must be TypeStr, TypeInt, or TypeFloat. List flags are automatically repeatable. The Unique option is supported. CLI usage: --flag val1 --flag val2 (each value coerced to itemType).

#DictFlag

Go go
func DictFlag(valueType FlagType, name, help string, opts ...FlagOption) Flag

DictFlag creates a dict-typed flag. valueType must be TypeStr, TypeInt, or TypeFloat. Dict flags are automatically repeatable (multiple key=value pairs). CLI usage: --flag key=value --flag key2=value2 Also accepts JSON: --flag '{"key": "value"}'

#NewArg

Go go
func NewArg(name, help string, opts ...ArgOption) Arg

NewArg creates a positional argument.

#NewApp

Go go
func NewApp(name, version, help string, opts ...AppOption) *App

NewApp creates a new CLI application.

#checkContextWithConn.ConnectionEnvValue

Go go
func (w checkContextWithConn) ConnectionEnvValue(envVar string) (string, bool)

ConnectionEnvValue implements ConnectionEnvReader.

#checkContextWithConn.IsHermetic

Go go
func (w checkContextWithConn) IsHermetic() bool

IsHermetic implements ConnectionEnvReader: reports whether the invocation ran under --hermetic. Mirrors the hermetic flag captured on the framework infra snapshot; false when no infra is present.

#reporterCore.Note

Go go
func (r *reporterCore) Note(text string)

Note records an informational note. Non-empty text is required. Notes are allowed on EVERY outcome, including a pass -- they never cause the problems-present hard-errors that passed()/skipped() enforce. Notes are verdict-inert: they surface only under --verbose and in JSON output.

#reporterCore.Warn

Go go
func (r *reporterCore) Warn(text string)

Warn mints a warn-severity problem. Non-empty text is required.

Reporter validation messages are worded identically to the Python implementation (method-agnostic phrasing, no "Warn:"/"warn:" prefix) so the two implementations are byte-for-byte in parity -- see conformance/ check_error_parity.py, which scans these panics.

#reporterCore.Passed

Go go
func (r *reporterCore) Passed(message string) CheckOutcome

Passed finalizes a terminal PASS outcome. It hard-errors if any problems were accumulated (an impl that found problems cannot claim it passed -- use Found).

#reporterCore.Skipped

Go go
func (r *reporterCore) Skipped(reason string) CheckOutcome

Skipped finalizes a terminal SKIP outcome. It hard-errors if any problems were accumulated.

#reporterCore.Found

Go go
func (r *reporterCore) Found(message string) CheckOutcome

Found finalizes an outcome carrying the accumulated problems. It hard-errors when no problems were accumulated (nothing found means the check passed -- say so explicitly with Passed).

#ErrorReporter.Error

Go go
func (r *ErrorReporter) Error(text string)

Error mints an error-severity problem. Non-empty text is required. This method exists only on ErrorReporter -- see the WarnReporter doc comment.

#App.RegisterCheckProvider

Go go
func (a *App) RegisterCheckProvider(provider func() []CheckSpec)

RegisterCheckProvider registers a provider function that supplies check specs at materialization time. Registering a provider enables the check system (so a TOML-less app gains a working check command). Multiple providers may be registered; their specs are materialized in registration order. A registered provider is re-run whenever the registry is materialized fresh (first read or after a cwd change / ResetCheckProviderCache).

Reentrancy: a provider must not trigger check execution during materialization (e.g. by calling RunChecks or the check command). Doing so re-enters materialization while it is in progress -- behavior is undefined (unbounded recursion). A provider's job is to return specs, nothing else.

#App.ResetCheckProviderCache

Go go
func (a *App) ResetCheckProviderCache()

ResetCheckProviderCache drops every provider-sourced definition and clears the materialization memo so the next registry read re-runs all providers. Intended for tests and long-lived singletons. It does NOT unregister the providers themselves.

#App.RunChecks

Go go
func (a *App) RunChecks(ctx CheckContext, opts RunChecksOptions) ([]CheckRunResult, []string, int, error)

RunChecks executes checks programmatically and returns the executed results, the ordered names of checks left unexecuted by the purity partition, the exit code, and any error. The exit code follows the same rules as the check command: 0 for all pass (or warn with IgnoreWarnings), 1 for any failure/warn/cascade-skip. impureListed is empty unless opts.PureOnly is set; listed checks contribute nothing to the exit code (a consumer renders them as e.g. "would run: (impure)").

#CheckRunResult.Status

Go go
func (r CheckRunResult) Status() string

Status returns the derived label ("pass", "fail", "warn", "skip") used for display and JSON output.

#CheckRunResult.Gated

Go go
func (r CheckRunResult) Gated() bool

Gated reports whether the outcome carries an error-severity problem (derived FAIL). Cascade (skipping dependents) and the FAIL exit key on this predicate.

#CheckRunResult.Warned

Go go
func (r CheckRunResult) Warned() bool

Warned reports whether the outcome carries only warn-severity problems (derived WARN). The --ignore-warnings predicate keys on this.

#App.ConfigField

Go go
func (a *App) ConfigField(name string, opts ...ConfigFieldOption)

ConfigField declares a config field on the app. Panics on invalid configuration (programmer error).

#Context.DryRun

Go go
func (c *Context) DryRun() bool { return c.reserved.dryRun }

DryRun reports whether the framework-owned --dry-run flag was passed.

#Context.ApproveConsequential

Go go
func (c *Context) ApproveConsequential() bool

ApproveConsequential reports whether the framework-owned --approve-consequential flag was passed.

#Context.Quiet

Go go
func (c *Context) Quiet() bool { return c.reserved.quiet }

Quiet reports whether the framework-owned --quiet flag was passed.

#Context.Verbose

Go go
func (c *Context) Verbose() bool { return c.reserved.verbose }

Verbose reports whether the framework-owned --verbose flag was passed.

#Context.Effects

Go go
func (c *Context) Effects() *Effects

Effects returns the effects handle for this run. Panics when the Context was constructed outside a command dispatch.

#Context.InfraValue

Go go
func (c *Context) InfraValue(envVar string) (string, bool)

InfraValue returns the value of a declared infrastructure env var.

For a declared location root (WithInfraRoot), it returns the value resolved eagerly at construction (env var if set, else the declared default) and true. The resolved value is always available, so the boolean is always true for roots.

For a declared handshake var (WithHandshakeEnv), it reads the environment LIVE at call time (handshakes are set by the invoking process and carry no construction-time value), returning (value, isSet).

For a declared connection env (WithConnectionEnv), it reads the environment LIVE at call time and returns (value, isSet) -- EXCEPT under --hermetic, where it resolves as absent ("", false) so connection-dependent behavior skips visibly instead of connecting.

Panics if envVar is not a declared root, handshake, or connection var -- declare everything.

#Context.ConnectionEnvValue

Go go
func (c *Context) ConnectionEnvValue(envVar string) (string, bool)

ConnectionEnvValue returns the value of a declared connection env (WithConnectionEnv), read LIVE at call time -- EXCEPT under --hermetic, where it resolves as absent ("", false). Panics if envVar is not a declared connection env. This is the check-side and handler-side accessor for the connection-URL kind; see also InfraValue, which resolves all three kinds.

#Context.Info

Go go
func (c *Context) Info(msg string)

Info writes an informational message to stdout (hidden under --quiet).

#Context.Warn

Go go
func (c *Context) Warn(msg string)

Warn writes a warning message to stderr (never suppressed).

#Context.Debug

Go go
func (c *Context) Debug(msg string)

Debug writes a debug message to stdout (shown only under --verbose). --quiet DOMINATES --verbose: passing both hides debug output.

#Context.Error

Go go
func (c *Context) Error(msg string)

Error writes an error message to stderr (never suppressed).

#Context.Source

Go go
func (c *Context) Source(name string) string

Source returns the provenance source label for a flag. Returns one of: "cli", "env", "config", "default", "implied", "infra". ("infra" indicates the value came from a RelativeToRoot default resolved through a declared infrastructure root.) Panics if the flag name is not found.

#Unsettled.String

Go go
func (u Unsettled) String() string { panic(u.truncate()) }

String panics: stringifying a carrier is extraction, not forwarding.

#Unsettled.Bytes

Go go
func (u Unsettled) Bytes() []byte { panic(u.truncate()) }

Bytes panics: extraction.

#Unsettled.Int

Go go
func (u Unsettled) Int() int64 { panic(u.truncate()) }

Int panics: extraction.

#Unsettled.Bool

Go go
func (u Unsettled) Bool() bool { panic(u.truncate()) }

Bool panics: extraction (and branching).

#Completed.ExitCode

Go go
func (c Completed) ExitCode() int

ExitCode returns the child's exit status. Panics when unsettled.

#Completed.Stdout

Go go
func (c Completed) Stdout() string

Stdout returns the child's captured stdout. Panics when unsettled.

#Completed.Stderr

Go go
func (c Completed) Stderr() string

Stderr returns the child's captured stderr. Panics when unsettled.

#Spawned.PID

Go go
func (s Spawned) PID() int

PID returns the child's process id. Panics when unsettled.

#Spawned.Wait

Go go
func (s Spawned) Wait(opts ...EffectOption) (Completed, error)

Wait waits for the child and returns its Completed result. It honours Check(bool) and nothing else: with the default true a nonzero exit is an error, mirroring run's opt-out. Calling Wait on an unsettled Spawned is extraction and truncates.

#Response.Status

Go go
func (r Response) Status() int

Status returns the HTTP status code. Panics when unsettled.

#Response.Body

Go go
func (r Response) Body() []byte

Body returns the raw response body. Panics when unsettled.

#Response.Header

Go go
func (r Response) Header(name string) string

Header returns a response header by (case-insensitive) name. Panics when unsettled.

#Effects.Run

Go go
func (e *Effects) Run(argv []interface{}, opts ...EffectOption) (Completed, error)

Run runs a subprocess to completion (PROC_MUTATE), or performs an observe when the argv matches an app-level proc_observe_allowlist prefix.

#Effects.Spawn

Go go
func (e *Effects) Spawn(argv []interface{}, opts ...EffectOption) (Spawned, error)

Spawn starts a subprocess without waiting (PROC_SPAWN).

Spawning is itself an effect: a dry run RECORDS the spawn instead of performing it, which is why no cross-process mode token exists.

#Effects.Write

Go go
func (e *Effects) Write(path interface{}, content interface{}, opts ...EffectOption) (Unsettled, error)

Write writes bytes to a path (FILE_WRITE).

#Effects.Mkdir

Go go
func (e *Effects) Mkdir(path interface{}, opts ...EffectOption) (Unsettled, error)

Mkdir creates a directory, parents included; an already-existing directory is not an error.

#Effects.Remove

Go go
func (e *Effects) Remove(path interface{}, opts ...EffectOption) (Unsettled, error)

Remove removes a file, a symlink or a directory tree recursively; a missing path is not an error.

#Effects.Rename

Go go
func (e *Effects) Rename(src interface{}, dst interface{}, opts ...EffectOption) (Unsettled, error)

Rename moves/renames a path (FILE_WRITE).

#Effects.Chmod

Go go
func (e *Effects) Chmod(path interface{}, mode int, opts ...EffectOption) (Unsettled, error)

Chmod changes a path's mode (FILE_WRITE). The mode renders in the log as leading-zero octal.

#Effects.HTTP

Go go
func (e *Effects) HTTP(method string, url interface{}, opts ...EffectOption) (Response, error)

HTTP performs a network request (NET_MUTATE).

#App.EffectLog

Go go
func (a *App) EffectLog() []map[string]interface{}

EffectLog returns the structured effect records of the most recent dispatch. Test-only surface, beside Test() and the provenance accessors.

#InvokeError.Error

Go go
func (e *InvokeError) Error() string

Error returns the error message describing the invocation failure.

#App.Call

Go go
func (a *App) Call(commandPath string, kwargs map[string]interface{}, opts ...CallOption) (interface{}, error)

Call invokes a command programmatically and returns its result.

Unlike invoke(), this is the public API. It returns an InvokeError for parse/validation errors instead of os.Exit, making it safe for programmatic use.

commandPath uses dot-separated segments: "deploy", "dns.zone.create". kwargs keys use underscored parameter names (e.g., "dry_run", not "--dry-run").

For passthrough commands, the special key "_args" must contain a []string of raw arguments to forward to the handler.

Returns:

  • - For handlers that return ExitData: the data value
  • - For handlers that return Exit: the exit code (int)
  • - For passthrough handlers: the exit code (int)

Returns an InvokeError if invocation fails (unknown command, missing required flags, mutex violations, dependency errors, etc.).

#App.ServeMCP

Go go
func (a *App) ServeMCP()

ServeMCP starts a JSON-RPC 2.0 server on stdin/stdout implementing the Model Context Protocol. It reads one JSON object per line from stdin and writes one JSON object per line to stdout. The server handles initialize, tools/list, and tools/call requests.

#App.DumpSchemaDict

Go go
func (a *App) DumpSchemaDict() map[string]interface{}

DumpSchemaDict returns the app's full schema as a map, excluding project_id.

This is the public, CWD-free accessor for the schema. Unlike the --dump-schema flag (which writes .strictcli/schema.json and derives project_id from go.mod in the current working directory), this method reads only the in-memory App and performs no filesystem or CWD access, and cannot fail. The returned map is equivalent to the written schema file with the project_id field removed.

#App.SetExitHook

Go go
func (a *App) SetExitHook(fn func())

SetExitHook registers a function to run immediately before Run's terminal os.Exit, after the handler has returned and the would-do log has been written.

Test-only surface, beside Test() and EffectLog(). Go has no stdlib at-exit facility and Run ends in os.Exit, so a caller that needs to read a post-dispatch diagnostic -- EffectLog() above all -- has no other seam. It gives Go what Python's atexit and Node's process.on("exit") give their harnesses for free. It changes no behavior: the hook runs after every observable output the run produces, and its own errors are the caller's.

#App.RegisterErrorCheck

Go go
func (a *App) RegisterErrorCheck(name string, fn func(CheckContext, *ErrorReporter) CheckOutcome)

RegisterErrorCheck registers an error-severity check implementation for a check declared with severity = "error" in checks.toml. The impl receives an *ErrorReporter (which can mint both error- and warn-severity problems) and must return a CheckOutcome obtained from that reporter.

Panics if checks are not enabled, the name is not declared, it is already registered, or the declared severity is not "error" (see registerCheckImpl).

#App.RegisterWarnCheck

Go go
func (a *App) RegisterWarnCheck(name string, fn func(CheckContext, *WarnReporter) CheckOutcome)

RegisterWarnCheck registers a warn-severity check implementation for a check declared with severity = "warn" in checks.toml. The impl receives a *WarnReporter, which structurally lacks error-minting: a warn check cannot produce an error-severity problem, so it can never cascade.

Panics under the same conditions as RegisterErrorCheck, with the severity cross-check requiring the declared severity to be "warn".

#App.SetCheckContext

Go go
func (a *App) SetCheckContext(factory func() CheckContext)

SetCheckContext sets the factory function that provides CheckContext to check implementations.

#App.TagContract

Go go
func (a *App) TagContract(tag, requiresFlag string)

TagContract declares that any command tagged with the given tag must have a flag with the given name. Validated at Run/Test time.

#App.Command

Go go
func (a *App) Command(name, help string, handler func(ctx *Context, kwargs map[string]interface{}) Outcome, opts ...CmdOption)

Command registers a top-level command with the given name, help text, and handler.

#App.Passthrough

Go go
func (a *App) Passthrough(name, help string, handler PassthroughHandler, opts ...CmdOption)

Passthrough registers a passthrough command (raw args, no parsing). Accepts CmdOptions for validation purposes (e.g., to detect invalid passthrough+flags).

It routes through the same single validated registration path as every other command -- there is no direct-Command-construction bypass left -- so a passthrough is classified with WithEffect like everything else.

#App.GlobalFlag

Go go
func (a *App) GlobalFlag(f Flag)

GlobalFlag registers a global flag on the app.

#App.Group

Go go
func (a *App) Group(name, help string, tags ...string) *Group

Group creates and registers a command group.

#Group.Group

Go go
func (g *Group) Group(name, help string, tags ...string) *Group

Group creates and registers a child subgroup.

#Group.Command

Go go
func (g *Group) Command(name, help string, handler func(ctx *Context, kwargs map[string]interface{}) Outcome, opts ...CmdOption)

Command registers a command within a group.

#App.Deprecated

Go go
func (a *App) Deprecated(name, message string, opts ...CmdOption)

Deprecated registers a deprecated command on the app. Invoking a deprecated command prints the message to stderr and exits 1.

#Group.Deprecated

Go go
func (g *Group) Deprecated(name, message string, opts ...CmdOption)

Deprecated registers a deprecated subcommand on the group. Invoking a deprecated subcommand prints the message to stderr and exits 1.

#App.Commands

Go go
func (a *App) Commands() map[string]*Command

Commands returns the registered top-level commands.

#App.Groups

Go go
func (a *App) Groups() map[string]*Group

Groups returns the registered command groups.

#App.GlobalFlags

Go go
func (a *App) GlobalFlags() []Flag

GlobalFlags returns the registered global flags.

#App.DeprecatedCommands

Go go
func (a *App) DeprecatedCommands() map[string]string

DeprecatedCommands returns the deprecated command map (name -> message).

#Group.DeprecatedCommands

Go go
func (g *Group) DeprecatedCommands() map[string]string

DeprecatedCommands returns the deprecated subcommand map (name -> message).

#App.Run

Go go
func (a *App) Run()

Run executes the CLI, reading from os.Args.

#App.Test

Go go
func (a *App) Test(argv []string) Result

Test runs the CLI with the given argv, capturing output and exit code.

#App.JsonSchema

Go go
func (a *App) JsonSchema(commandPath string) map[string]interface{}

JsonSchema produces a JSON Schema parameters object for a command's flags and positional args.

commandPath is a dot-separated path to the command (e.g. "deploy" or "config.show").

Returns a JSON Schema object with "type": "object", "properties", "required", and "additionalProperties": false.

Panics if the command path is invalid or resolves to a group.

#App.AsTools

Go go
func (a *App) AsTools() []Tool

AsTools exports non-hidden, non-interactive leaf commands as Tool descriptors. Returns a list of Tool objects, one per eligible command plus a router tool. Each tool's Execute function wraps App.Call().

Search