contract

package
v0.5.8 Latest Latest
Warning

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

Go to latest
Published: Nov 25, 2026 License: MIT Imports: 11 Imported by: 1 module, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package contract is the machine-readable description of vigolium's machine output: a JSON Schema (draft 2020-12) for every registered -j document, for each --events line type, for the error envelope, and for standalone documents such as the scan plan. `vigolium schema` prints them, `make schema` writes them to docs/schema, and the contracttest subpackage validates real command output against them in tests.

The schemas are reflected from Go types, never hand-written: a command registers the type of one item and a struct naming its top-level extras, and the envelope spine comes from the public mirror in envelope.go. A field rename then changes the schema, which fails the golden test, which is the point.

It is a leaf package: it imports only pkg/apicontract and the reflector, so any package that owns a machine shape (pkg/cli, pkg/scanevents) can register it without a cycle.

Index

Constants

View Source
const (
	KindRead     = "read"
	KindMutation = "mutation"
	KindScan     = "scan"
)

Envelope kinds, as the `kind` field carries them.

View Source
const (
	// ItemsList: zero or more rows of Item.
	ItemsList = "list"
	// ItemsObject: exactly one object, wrapped as items:[obj].
	ItemsObject = "object"
)

ItemsKind says how a document's `items` array is filled.

Variables

This section is empty.

Functions

func CommandNames

func CommandNames() []string

CommandNames lists the registered commands, sorted.

func DocumentNames

func DocumentNames() []string

DocumentNames lists the registered documents, sorted.

func EventTypes

func EventTypes() []string

EventTypes lists the registered event types in registration order.

func JSONFieldNames

func JSONFieldNames(v any) []string

JSONFieldNames returns the JSON keys a value of v's struct type can carry, in field order. For drift tests that compare a mirror with the real type.

func RegisterCommand

func RegisterCommand(c Command)

RegisterCommand records a command's document shape. It panics on an empty or duplicate name or an unknown kind: both are programming errors caught by the first test that imports the registering package.

func RegisterDocument

func RegisterDocument(d Document)

RegisterDocument records a standalone document's Go type under name.

func RegisterEvent

func RegisterEvent(typ string, f EventFields)

RegisterEvent records one event type's fields. Registration order is the order `vigolium schema event` lists them in.

func RequiredNullableJSONFields added in v0.5.7

func RequiredNullableJSONFields(v any) []string

RequiredNullableJSONFields returns the keys of v's struct type that are required (no omitempty) and may be null (a pointer, slice or map): the keys a shaped document can empty by setting them to null without failing its schema.

func SetEventPayload

func SetEventPayload(payload any, version int, spine []string)

SetEventPayload names the Go type every event line marshals from (one struct, omitempty past the spine), the version carried in "v", and the spine keys every line carries whatever its type.

Types

type Command

type Command struct {
	// Name is the `command` field the document carries: the cobra path without
	// the root ("finding", "scan status").
	Name string
	// Kind is the document's `kind` (KindRead, KindMutation, KindScan); empty
	// when the document carries none.
	Kind string
	// Description is a one-line summary, rendered as the schema's description.
	Description string
	// Item is a zero value of one item's Go type. Nil leaves items untyped.
	Item any
	// ItemsKind is ItemsList (the default) or ItemsObject.
	ItemsKind string
	// Variants are alternative item shapes a flag selects (traffic --curl).
	// The items schema is then anyOf the default and every variant.
	Variants []Variant
	// Extras is a zero value of a struct whose JSON fields are the command's
	// own top-level keys. omitempty fields are optional, the rest required.
	// They override a common envelope extra of the same name.
	Extras any
	// StreamFlag names the flag that turns stdout into a stream of these
	// documents, one per line (NDJSON); "" when there is none.
	StreamFlag string
}

Command describes one command's -j document.

func LookupCommand

func LookupCommand(name string) (Command, bool)

LookupCommand returns the registration for name.

type Document

type Document struct {
	Name        string
	Description string
	Value       any
}

Document is a standalone machine document that is not an envelope (the scan plan, for one).

func LookupDocument

func LookupDocument(name string) (Document, bool)

LookupDocument returns the registration for name.

type Envelope

type Envelope struct {
	SchemaVersion int    `json:"schema_version"`
	Command       string `json:"command"`
	// Kind is the document's shape: read, mutation or scan.
	Kind string `json:"kind,omitempty"`
	// OK is true exactly when the command exited 0, 3 or 4. A result document
	// whose command then failed carries false and Error.
	OK bool `json:"ok"`
	// Error is present exactly when OK is false.
	Error *ErrorBody `json:"error,omitempty"`
	// SoftFail states that --soft-fail forced the process exit status to 0.
	SoftFail bool `json:"soft_fail,omitempty"`
	// Changed, Action and DryRun are the mutation spine (kind "mutation").
	Changed *bool  `json:"changed,omitempty"`
	Action  string `json:"action,omitempty"`
	DryRun  bool   `json:"dry_run,omitempty"`
	// ProjectUUID is the project filter actually applied; DBPath the store the
	// command opened.
	ProjectUUID string `json:"project_uuid,omitempty"`
	DBPath      string `json:"db_path,omitempty"`
	// Total counts the whole result set; Offset/Limit describe this page.
	Total  int64 `json:"total"`
	Offset int   `json:"offset"`
	Limit  int   `json:"limit"`
	// Items is always an array, never null and never an object.
	Items []any `json:"items"`
	// Query / QueryArgv are the ready-to-run follow-up command.
	Query     string   `json:"query,omitempty"`
	QueryArgv []string `json:"query_argv,omitempty"`
	// GeneratedAt is RFC3339 UTC with exactly three fractional digits;
	// GeneratedAtMS the same instant in epoch milliseconds.
	GeneratedAt   string `json:"generated_at,omitempty"`
	GeneratedAtMS int64  `json:"generated_at_ms,omitempty"`
	// Redacted says credential values in this document's raw request/response
	// views were masked (-j under a coding agent, or --redact). The CLI always
	// renders it; optional here so a document from an older binary validates.
	Redacted bool `json:"redacted,omitempty"`
}

Envelope is the public mirror of the CLI's -j envelope spine (pkg/cli agentEnvelope, whose extras map and --json-legacy-keys alias cannot be reflected). A pkg/cli test keeps the two key sets identical.

type EnvelopeCommon

type EnvelopeCommon struct {
	// ProjectSource says where the project selection came from.
	ProjectSource string `json:"project_source" jsonschema:"enum=flag,enum=env,enum=active_file,enum=default"`
	// ProjectScoped states whether a project filter was applied at all.
	ProjectScoped *bool `json:"project_scoped,omitempty"`
	// Warnings are advisories about how the result was produced.
	Warnings []string `json:"warnings,omitempty"`
	// GlobSources reports a --glob-db merge: matched vs loaded files.
	GlobSources *GlobSources `json:"glob_sources,omitempty"`
	// OutputBudget reports a page cut by --max-output-bytes.
	OutputBudget *OutputBudget `json:"output_budget,omitempty"`
	// SendsTraffic marks a command whose job is to send requests to a target.
	SendsTraffic bool `json:"sends_traffic,omitempty"`

	// The -o receipt: the document went to Output instead of stdout, so items
	// is empty and these describe the file.
	Artifact  string            `json:"artifact,omitempty"`
	Output    string            `json:"output,omitempty"`
	Bytes     int               `json:"bytes,omitempty"`
	SHA256    string            `json:"sha256,omitempty"`
	Complete  *bool             `json:"complete,omitempty"`
	Hint      string            `json:"hint,omitempty"`
	Artifacts []ReceiptArtifact `json:"artifacts,omitempty"`
}

EnvelopeCommon are the extras any envelope may carry, whatever the command.

type ErrorBody

type ErrorBody struct {
	Code     apicontract.ErrorCode `json:"code"`
	Message  string                `json:"message"`
	ExitCode int                   `json:"exit_code"`
	// Hint names the next step, in one sentence.
	Hint string `json:"hint,omitempty"`
	// DidYouMean is the nearest valid spelling of what was typed: a flag with
	// its dashes, a command path, or an enum value.
	DidYouMean string `json:"did_you_mean,omitempty"`
	// UsageArgv prints the failing command's flags as a document.
	UsageArgv []string `json:"usage_argv,omitempty"`
}

ErrorBody is the error object: a stable code to branch on, a message for a human, and the exit code the command concluded.

type ErrorEnvelope

type ErrorEnvelope struct {
	SchemaVersion int    `json:"schema_version"`
	Command       string `json:"command"`
	// OK is always false on an error document.
	OK    bool      `json:"ok"`
	Error ErrorBody `json:"error"`
	// DBPath names the store the command had opened, when it got that far.
	DBPath string `json:"db_path,omitempty"`
	// SoftFail states that --soft-fail forced the process exit status to 0.
	SoftFail bool `json:"soft_fail,omitempty"`
	// AgenticScanUUID names the agent run the command had started, when the
	// failure came after it did.
	AgenticScanUUID string `json:"agentic_scan_uuid,omitempty"`
	GeneratedAt     string `json:"generated_at"`
	GeneratedAtMS   int64  `json:"generated_at_ms"`
}

ErrorEnvelope is the public mirror of the CLI's -j error document (pkg/cli agentErrorEnvelope): what a failed -j command prints to stdout instead of a result. A pkg/cli test keeps the two key sets identical.

type EventFields

type EventFields struct {
	Required    []string
	Optional    []string
	Description string
}

EventFields is one event type's row of the field table: which payload keys a line of that type always carries and which it may carry. The spine (see SetEventPayload) is implied.

func LookupEvent

func LookupEvent(typ string) (EventFields, bool)

LookupEvent returns one event type's field table.

type GlobSkipped

type GlobSkipped struct {
	File  string `json:"file"`
	Error string `json:"error"`
}

GlobSkipped is one --glob-db file the merge left out, and why.

type GlobSources

type GlobSources struct {
	Pattern     string        `json:"pattern"`
	Matched     int           `json:"matched"`
	Loaded      int           `json:"loaded"`
	Skipped     []GlobSkipped `json:"skipped"`
	ParseErrors int           `json:"parse_errors"`
}

GlobSources is the glob_sources extra of a --glob-db read.

type OutputBudget

type OutputBudget struct {
	MaxBytes int `json:"max_bytes"`
	Returned int `json:"returned"`
	Omitted  int `json:"omitted"`
	// NextOffset is the --offset of the next page. Absent when there is no
	// next page to follow, where FullResult says how to get every row instead.
	NextOffset *int `json:"next_offset,omitempty"`
	// FullResult replaces NextOffset on a command that sends requests (a
	// second page would send them again) or does not page at all; it says why.
	FullResult string `json:"full_result,omitempty"`
	// DroppedKeys names the top-level keys emptied (set to null) to fit the
	// budget, in the order they were dropped, before any item was cut.
	DroppedKeys []string `json:"dropped_keys,omitempty"`
}

OutputBudget is the output_budget extra of a page --max-output-bytes cut.

type ReceiptArtifact added in v0.5.7

type ReceiptArtifact struct {
	Format string `json:"format"`
	Path   string `json:"path"`
	Bytes  int64  `json:"bytes"`
}

ReceiptArtifact is one file a command wrote.

type Schema

type Schema = jsonschema.Schema

Schema is a JSON Schema node (draft 2020-12).

func CommandSchema

func CommandSchema(name string) (*Schema, error)

CommandSchema builds the full -j document schema for a registered command.

func DocumentSchema

func DocumentSchema(name string) (*Schema, error)

DocumentSchema builds the schema of a registered standalone document.

func ErrorSchema

func ErrorSchema() *Schema

ErrorSchema builds the schema of the -j error document. error.code is the closed apicontract vocabulary; exit_code is one of the documented non-zero exit codes.

func EventSchema

func EventSchema(typ string) (*Schema, error)

EventSchema builds the schema of one event type's line.

func EventsSchema

func EventsSchema() (*Schema, error)

EventsSchema builds the schema of any --events line: oneOf the per-type schemas, each pinned by its "type" const.

type Variant

type Variant struct {
	Flag string
	Item any
}

Variant is an alternative item shape selected by a flag.

Directories

Path Synopsis
Package contracttest validates real machine output against the registered contract schemas, so a test that already captures a command's -j document (or an --events line, or an error envelope) can assert that the document matches what `vigolium schema` promises.
Package contracttest validates real machine output against the registered contract schemas, so a test that already captures a command's -j document (or an --events line, or an error envelope) can assert that the document matches what `vigolium schema` promises.

Jump to

Keyboard shortcuts

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