contract

package
v1.0.62-beta.8 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Sep 11, 2026 License: Apache-2.0 Imports: 8 Imported by: 0

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 / 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

View Source
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).

View Source
const (
	PaginationKindCursor    = "cursor"
	PaginationMetaPath      = "meta.pagination"
	PaginationExhaustedPath = "meta.pagination.endpoint_exhausted"
	PaginationNextTokenPath = "meta.pagination.next_token"
)
View Source
const (
	DryRunPreviewInvocation = "invocation"
	DryRunPreviewRequest    = "request"
	DryRunPreviewPlan       = "plan"
	DryRunPreviewDiff       = "diff"
)
View Source
const (
	InterfaceModeMCP       = "mcp"
	InterfaceModeLocal     = "local"
	InterfaceModeComposite = "composite"

	InterfaceAvailable   = "available"
	InterfaceUnavailable = "unavailable"
)

Variables

This section is empty.

Functions

func ClearProductDeclForTest

func ClearProductDeclForTest(productID string)

ClearProductDeclForTest removes a registration (tests only).

func HasProductDecl

func HasProductDecl(productID string) bool

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 StoreProductDeclRawForTest

func StoreProductDeclRawForTest(productID string, value any)

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
	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

type HelpDocumentation struct {
	Label string
	URL   string
}

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

type ProductSelectionDecl struct {
	AgentSummary string
	UseWhen      []string
	AvoidWhen    []string
}

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 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.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL