Documentation
¶
Overview ¶
Package contract owns command-framework declaration DTOs and the ProductDecl registry. It is intentionally free of Cobra-keyed runtime stores and Catalog delivery code.
This package is the sole definition point for:
- ContractFinalPayload (DTO only — store lives in corecmd/contractfinal)
- ProductDecl (+ string-keyed registry; not Cobra-keyed)
- SafetySpec / SelectionSpec / InterfaceSpec / DryRunSpec / identity / positionals / RuntimeSchemaConstraints / ParamDecl
- FieldProvenance / FieldCandidateProvenance
Package boundary:
- Types / ProductDecl → corecmd/contract (this package).
- Authoring wrapper → corecmd.ContractDecl (leaf-facing; nested fields are these contract types). Name is ContractDecl, not SchemaDecl: "Schema" in this repo means Catalog / ToolSpec delivery, not the author declaration.
- AnnotateRuntime* writers → internal/corecmd/runtimeannotate (framework-owned; cli may thin re-export; corecmd must not import cli).
- ContractFinal cobra store + Register seam → internal/corecmd/contractfinal (all callers register here directly; corecmd.New registers internally).
- Catalog assembly / ResolveMeta (`RegisterSchemaSourceRoot` → `ResolveSchemaBuild`); go:embed only for reviewed inputs → internal/cli (delivery root).
Description declare vs delivery (not dual authority):
- Construction requires ContractDecl.Description (declaration evidence).
- Catalog delivery prefers Cobra Long when present → provenance cobra_help; without Long, declared Description is delivered → contract_final.
- Title prefers declared ContractDecl/ContractFinal, then Cobra Short, then MCP metadata. Declare is not "wire final value" for description when Long exists; assembly stamps the real winner.
Authoring path: corecmd.ContractDecl → ContractFinalPayload (via contractfinal seam); ProductDecl for product-level Agent routing. Provenance stamp for declared leaf Safety remains "corecmd.contract".
Index ¶
- Constants
- func ClearProductDeclForTest(productID string)
- func HasProductDecl(productID string) bool
- func RegisterProductDecl(decl ProductDecl)
- func RegisteredProductDeclIDs() []string
- func RuntimeSchemaConstraintsEmpty(constraints RuntimeSchemaConstraints) bool
- func StoreProductDeclRawForTest(productID string, value any)
- type ContractFinalPayload
- type DryRunSpec
- type ExampleDisposition
- type ExampleDispositionMode
- type ExampleDispositionReasonCode
- type FieldCandidateProvenance
- type FieldProvenance
- type FormatAlternative
- type HelpDocumentation
- type HelpReferences
- type InterfaceRefSpec
- type InterfaceSpec
- type PaginationSpec
- type ParamDecl
- type ProductDecl
- type ProductSelectionDecl
- type ResultOutcome
- type ResultSpec
- type RuntimeSchemaConstraints
- type RuntimeSchemaPositional
- type SafetySpec
- type SelectionSpec
- type ToolIdentitySpec
- type WaitSpec
Constants ¶
const ( ProductDeclProvenanceSource = "cli.product_decl" ProductDeclSourceRef = "cli.ProductDecl" )
ProductDecl provenance labels. Assembly and Agent-metadata generation stamp ProductSpec.Selection winners with these sources (symmetric to leaf corecmd.contract / corecmd.ContractDecl).
const ( WaitModePoll = "poll" WaitModeEvent = "event" WaitModeAuto = "auto" )
Wait modes. Poll executes the leaf's WaitPoll hook on a cadence. Event consumes the leaf's WaitEvents push stream and correlates events to the accepted resource. Auto prefers the event stream and falls back to polling when the stream ends before a terminal status.
const ( PaginationKindCursor = "cursor" PaginationMetaPath = "meta.pagination" PaginationExhaustedPath = "meta.pagination.endpoint_exhausted" PaginationNextTokenPath = "meta.pagination.next_token" )
const ( DryRunPreviewInvocation = "invocation" DryRunPreviewRequest = "request" DryRunPreviewPlan = "plan" DryRunPreviewDiff = "diff" )
const ( InterfaceModeMCP = "mcp" InterfaceModeLocal = "local" InterfaceModeComposite = "composite" InterfaceAvailable = "available" )
Variables ¶
This section is empty.
Functions ¶
func ClearProductDeclForTest ¶
func ClearProductDeclForTest(productID string)
ClearProductDeclForTest removes a registration (tests only).
func HasProductDecl ¶
HasProductDecl reports whether product-level routing is declared in code.
func RegisterProductDecl ¶
func RegisterProductDecl(decl ProductDecl)
RegisterProductDecl stores a product-level routing declaration. Light runtime write: one map store; no JSON bridge. A non-empty ID with incomplete selection panics: declared products are the final source and have no selection/ fallback for missing prose.
func RegisteredProductDeclIDs ¶
func RegisteredProductDeclIDs() []string
RegisteredProductDeclIDs returns sorted product IDs with an in-code Decl.
func RuntimeSchemaConstraintsEmpty ¶ added in v1.0.63
func RuntimeSchemaConstraintsEmpty(constraints RuntimeSchemaConstraints) bool
RuntimeSchemaConstraintsEmpty reports whether no constraint groups remain.
func StoreProductDeclRawForTest ¶
StoreProductDeclRawForTest stores an arbitrary map value (tests only).
Types ¶
type ContractFinalPayload ¶
type ContractFinalPayload struct {
Title string
Description string
Positionals []RuntimeSchemaPositional
Parameters []ParamDecl
Safety *SafetySpec
DryRun *DryRunSpec
Wait *WaitSpec
Result *ResultSpec
Pagination *PaginationSpec
Interface *InterfaceSpec
Selection *SelectionSpec
Identity *ToolIdentitySpec
}
ContractFinalPayload is the Contract-authored final Schema leaf overlay. Registered in-process by the framework via the corecmd/contractfinal seam; Schema assembly reads it as pass-through. No JSON bridge. Treat as read-only after Register.
The Cobra-keyed runtime store and Register live in internal/corecmd/contractfinal (not this DTO package). AnnotateRuntime* writers live in internal/corecmd/runtimeannotate. All callers register via contractfinal.RegisterRuntimeContractFinal directly (corecmd.New registers internally).
type DryRunSpec ¶
type DryRunSpec struct {
PreviewKind string `json:"preview_kind"`
RemoteReads bool `json:"remote_reads,omitempty"`
}
DryRunSpec is a positive capability declaration. A nil ToolSpec.DryRun means the command has not declared reviewed --dry-run support; the Schema does not publish a negative or inferred capability in that case.
The whole object is one atomic contract field. Runtime execution remains owned by the command runner; Schema only projects the reviewed capability.
func (DryRunSpec) Validate ¶
func (d DryRunSpec) Validate(canonical string) error
Validate checks preview_kind against the closed reviewed set.
type ExampleDisposition ¶
type ExampleDisposition struct {
Index *int `json:"index"`
Mode ExampleDispositionMode `json:"mode"`
ReasonCode ExampleDispositionReasonCode `json:"reason_code"`
Reason string `json:"reason"`
Reviewed bool `json:"reviewed"`
}
ExampleDisposition narrows one exact example to contract-only validation. Index is a pointer so a missing index cannot silently select example zero.
type ExampleDispositionMode ¶
type ExampleDispositionMode string
ExampleDispositionMode controls how an already contract-validated example is exercised by the Agent example gate.
const ( ExampleDispositionModeContract ExampleDispositionMode = "contract" ExampleDispositionModeDryRun ExampleDispositionMode = "dry_run" ExampleDispositionModeContractOnly ExampleDispositionMode = "contract_only" )
type ExampleDispositionReasonCode ¶
type ExampleDispositionReasonCode string
ExampleDispositionReasonCode is the closed taxonomy for reviewed contract-only exceptions to an explicit dry-run capability.
const ( ExampleDispositionReasonLocalState ExampleDispositionReasonCode = "local_state" ExampleDispositionReasonStatefulPreflight ExampleDispositionReasonCode = "stateful_preflight" )
type FieldCandidateProvenance ¶
type FieldCandidateProvenance struct {
Value json.RawMessage `json:"value,omitempty"`
Source string `json:"source"`
SourceRef string `json:"source_ref,omitempty"`
Precedence string `json:"precedence,omitempty"`
ReviewReason string `json:"review_reason,omitempty"`
Selected *bool `json:"selected,omitempty"`
}
FieldCandidateProvenance retains one winning or non-winning source value.
type FieldProvenance ¶
type FieldProvenance struct {
Value json.RawMessage `json:"value,omitempty"`
Source string `json:"source"`
SourceRef string `json:"source_ref,omitempty"`
Precedence string `json:"precedence,omitempty"`
Resolution string `json:"resolution"`
ReviewReason string `json:"review_reason,omitempty"`
Candidates []FieldCandidateProvenance `json:"candidates,omitempty"`
OverriddenCandidates []FieldCandidateProvenance `json:"overridden_candidates,omitempty"`
}
FieldProvenance records how one final field was selected. Value is raw JSON so provenance can describe strings, booleans and structured extension values without weakening the resolved ToolSpec itself.
func ResolvedFieldProvenance ¶
func ResolvedFieldProvenance(value any, source, sourceRef, precedence, resolution, reviewReason string) FieldProvenance
ResolvedFieldProvenance builds a single-winner provenance record for a ContractFinal / ProductDecl pass-through field.
type FormatAlternative ¶ added in v1.0.62
type FormatAlternative struct {
Format string `json:"format"`
}
FormatAlternative is a format-only JSON Schema anyOf branch. The parameter owns its type; branches describe alternative accepted string formats.
type HelpDocumentation ¶ added in v1.0.61
HelpDocumentation is one stable, human-readable documentation link shown in service and leaf Help. It is deliberately not part of SelectionSpec or the public Schema wire: Help references guide further reading without changing the executable command contract.
func SkillDocumentation ¶ added in v1.0.61
func SkillDocumentation(label, skill, relativePath string) HelpDocumentation
SkillDocumentation builds a stable GitHub link to a file in an embedded multi-Skill. Product declarations use this helper so URLs cannot drift from the repository layout while retaining an explicit label and path.
type HelpReferences ¶ added in v1.0.61
type HelpReferences struct {
RelatedSkills []string
Documentation []HelpDocumentation
}
HelpReferences declares the embedded Skills and deeper documentation that are relevant to a product. Leaf Help inherits the declaration by ProductID.
type InterfaceRefSpec ¶
type InterfaceRefSpec struct {
ProductID string `json:"product_id"`
RPCName string `json:"rpc_name"`
}
InterfaceRefSpec identifies the backing operation, independently from the executable command identity.
type InterfaceSpec ¶
type InterfaceSpec struct {
Ref *InterfaceRefSpec
Mode string
Availability string
Reason string
}
InterfaceSpec describes whether and how the Agent may invoke the backing interface.
func (InterfaceSpec) AgentExecutable ¶
func (i InterfaceSpec) AgentExecutable() bool
AgentExecutable reports whether the final contract permits an Agent to invoke this command. Interface mode describes the implementation mechanism; availability is the independent execution gate.
func (InterfaceSpec) Validate ¶
func (i InterfaceSpec) Validate(canonical string) error
Validate enforces the final interface-disposition conflict matrix. It does not prove that an MCP ref exists in the pinned interface registry; that exact lookup is performed by validateSchemaRegistryInterfaces.
type PaginationSpec ¶ added in v1.0.58
type PaginationSpec struct {
Kind string `json:"kind"`
CursorParameter string `json:"cursor_parameter"`
MetaPath string `json:"meta_path"`
EndpointExhaustedPath string `json:"endpoint_exhausted_path"`
NextTokenPath string `json:"next_token_path"`
}
PaginationSpec is a command-level declaration for framework pagination metadata. It is deliberately separate from ResultSpec because pagination is emitted under envelope meta, not inside the business response data.
func NormalizePaginationSpec ¶ added in v1.0.58
func NormalizePaginationSpec(in *PaginationSpec, canonical string) (*PaginationSpec, error)
NormalizePaginationSpec validates the command-specific input parameter and fills the framework-owned public meta paths.
type ParamDecl ¶
type ParamDecl struct {
Name string
Property string
Required *bool
InterfaceType string
Description string
RequiredWhen string
Enum []string
AnyOf []FormatAlternative
}
ParamDecl is one parameter-level Schema fact declared on a command. It is stored at DeclareLeafMetadata time and applied as annotations at assembly time, when all flags are guaranteed to exist on the fully-built command tree.
type ProductDecl ¶
type ProductDecl struct {
ID string
Selection ProductSelectionDecl
HelpReferences HelpReferences
}
ProductDecl is the product-level Schema routing declaration. Assembly writes ProductSpec.Selection with provenance contract_final. HelpReferences remains internal-only and is consumed exclusively by Help rendering.
func LookupProductDecl ¶
func LookupProductDecl(productID string) (ProductDecl, bool)
LookupProductDecl returns the registered product declaration, if any.
type ProductSelectionDecl ¶
ProductSelectionDecl is the product-level Agent routing prose declared in code. Fields mirror the leaf SelectionSpec routing triple: agent summary, use-when, and avoid-when.
type ResultOutcome ¶ added in v1.0.58
type ResultOutcome string
ResultOutcome is one closed unified-output envelope outcome.
const ( ResultOutcomeSuccess ResultOutcome = "success" ResultOutcomePending ResultOutcome = "pending" ResultOutcomePartialFailure ResultOutcome = "partial_failure" ResultOutcomeFailure ResultOutcome = "failure" )
type ResultSpec ¶ added in v1.0.58
type ResultSpec struct {
Outcomes []ResultOutcome `json:"outcomes"`
DataSchema json.RawMessage `json:"data_schema"`
SensitivePaths []string `json:"sensitive_paths,omitempty"`
}
ResultSpec is the reviewed return-value contract for one command and is projected unchanged into both full-leaf and compact-leaf Schema. Outcomes and DataSchema are required; Pagination and SensitivePaths are omitted when absent. DataSchema is a canonical recursive JSON Schema object; every path is relative to the unified-output envelope data value.
func NormalizeResultSpec ¶ added in v1.0.58
func NormalizeResultSpec(in *ResultSpec, canonical string) (*ResultSpec, error)
NormalizeResultSpec returns a validated, canonical, defensively copied result contract. It is shared by declaration, ToolSpec, and snapshot paths.
type RuntimeSchemaConstraints ¶ added in v1.0.63
type RuntimeSchemaConstraints struct {
MutuallyExclusive [][]string `json:"mutually_exclusive,omitempty"`
RequireOneOf [][]string `json:"require_one_of,omitempty"`
RequireTogether [][]string `json:"require_together,omitempty"`
}
RuntimeSchemaConstraints describes cross-parameter rules that cannot be represented by an individual parameter's required bit.
func NormalizeRuntimeSchemaConstraints ¶ added in v1.0.63
func NormalizeRuntimeSchemaConstraints(constraints RuntimeSchemaConstraints) RuntimeSchemaConstraints
NormalizeRuntimeSchemaConstraints trims, deduplicates, and drops undersized groups.
type RuntimeSchemaPositional ¶
type RuntimeSchemaPositional struct {
Name string `json:"name"`
Type string `json:"type,omitempty"`
Description string `json:"description,omitempty"`
Required bool `json:"required"`
Variadic bool `json:"variadic,omitempty"`
Index int `json:"index"`
}
RuntimeSchemaPositional describes one ordered CLI argument. Name is also used by RuntimeSchemaConstraints when a one-of group mixes flags and args.
type SafetySpec ¶
type SafetySpec struct {
Effect string
EffectSource string
Risk string
Confirmation string
Idempotency string
}
SafetySpec is the resolved operation behavior. This model deliberately does not impose a value lattice: precedence policy belongs to the resolver, so a reviewed higher-priority source may intentionally raise or lower a value.
type SelectionSpec ¶
type SelectionSpec struct {
AgentSummary string
AgentSummarySource string
UseWhen []string
AvoidWhen []string
Prerequisites []string
Tips []string
WorkflowRefs []string
Examples []string
// ExampleDispositions narrows an exact example with a reviewed local or
// stateful precondition from dry-run execution to contract validation.
// It does not change the command's declared DryRun capability.
ExampleDispositions []ExampleDisposition
// Reviewed is a legacy-path (hints/registry) marker only. The Contract
// declaration path must not set it: declared selection is final by
// construction, and assembly rejects a declared payload carrying it.
Reviewed *bool
SourceRefs []string
MetadataSource string
}
SelectionSpec contains Agent command-selection guidance. Product specs use the common summary/use/avoid/source subset; tool specs may use every field.
func ProductSelectionFromDecl ¶
func ProductSelectionFromDecl(decl ProductDecl) (SelectionSpec, map[string]FieldProvenance)
ProductSelectionFromDecl projects a ProductDecl into SelectionSpec plus contract_final FieldProvenance for ProductSpec assembly.
func (SelectionSpec) Normalized ¶
func (s SelectionSpec) Normalized() SelectionSpec
Normalized returns a copy with trimmed unique guidance arrays. Guidance and examples are ordered authoring content; determinism comes from sorted registry navigation, not from rewriting semantically meaningful arrays.
type ToolIdentitySpec ¶
type ToolIdentitySpec struct {
ProductID string
SourceProductID string
Name string
CLIName string
CanonicalPath string
Path string
CLIPath string
PrimaryCLIPath string
Group string
Aliases []string
IsAlias bool
Source string
}
ToolIdentitySpec contains only command identity. It is intentionally separate from interface identity: an executable Cobra leaf and an RPC are related by InterfaceSpec, but are not interchangeable sources of truth.
type WaitSpec ¶ added in v1.0.63
type WaitSpec struct {
Mode string `json:"mode"`
PollCommand string `json:"poll_command,omitempty"`
StatusQuery string `json:"status_query"`
Terminal map[string]ResultOutcome `json:"terminal"`
PendingValues []string `json:"pending_values,omitempty"`
// EventKey is the push channel key the WaitEvents hook subscribes to
// (event/auto modes). Declared for the catalog; the transport stays
// leaf-owned.
EventKey string `json:"event_key,omitempty"`
// MatchField is the event-document path holding the resource identifier
// (event/auto modes); its value must equal the ResourceQuery resolution
// of the accepted result.
MatchField string `json:"match_field,omitempty"`
// ResourceQuery is the dotted path into the accepted result data that
// yields the resource identifier correlated against MatchField
// (event/auto modes).
ResourceQuery string `json:"resource_query,omitempty"`
// DefaultTimeoutSecs is the reviewed default for --wait-timeout. Zero
// means the framework default (300s); the user flag always wins.
DefaultTimeoutSecs int `json:"default_timeout_secs"`
}
WaitSpec is a positive capability declaration for terminal-state waiting (approval flows, async exports, batch jobs). A nil ToolSpec.Wait means the command has not declared reviewed --wait support; the flag is not registered and the Schema does not publish the capability.
Like DryRunSpec, the object is one atomic contract field: Schema only projects the reviewed capability; runtime execution stays owned by the command runner through the leaf's WaitPoll / WaitEvents hooks. PollCommand names the read command that observes status — it is a declared, catalog-visible fact (the same command an agent would poll manually), not a framework-owned invocation: how one poll or event subscription executes is decided by the leaf.
func NormalizeWaitSpec ¶ added in v1.0.63
NormalizeWaitSpec returns a validated, canonical, defensively copied wait contract. It is shared by declaration (corecmd.New / AttachContract), ToolSpec, and snapshot paths, mirroring NormalizeResultSpec. Status values are trimmed into their wire form: the wait engine compares backend statuses verbatim against these tables, so a padded declaration (" processing ") would publish a Schema that its own runtime treats as an unknown status. Values collapsing onto one value after trimming (duplicate pending values, duplicate terminal keys, terminal/pending conflicts) are rejected instead of silently merged.
func (WaitSpec) Validate ¶ added in v1.0.63
Validate checks mode requirements and the terminal/pending status maps. Unknown terminal outcomes, unknown modes, and mode/body mismatches fail at declaration so a malformed wait capability cannot reach the wire. Validation delegates to NormalizeWaitSpec so the acceptance rules can never drift from the normalization the wire and the runtime wait engine share.