contract

package
v0.2.1 Latest Latest
Warning

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

Go to latest
Published: Oct 14, 2026 License: MIT Imports: 11 Imported by: 0

Documentation

Overview

Package contract holds the agent contract that every command shares: exit codes, the error registry, answers and their verdict, modes, and command declarations. docs/north-star/contract.md is the source of truth.

Index

Constants

View Source
const ManifestFormat = 1

ManifestFormat is the only manifest format that this version reads.

View Source
const Version = 1

Version is the integer version of the public protocol, carried by every answer as contract_version.

Variables

View Source
var Core = Registry{/* contains filtered or unexported fields */}

Core is the registry of core's own commands.

View Source
var GlobalFlags = []Flag{
	{Name: "help", Shorthand: "h", Summary: "flag.help"},
	{Name: "json", Summary: "flag.json", Env: "NCLY_JSON"},
	{Name: "no-input", Summary: "flag.no_input", Env: "NCLY_NO_INPUT"},
	{Name: "no-color", Summary: "flag.no_color", Env: "NO_COLOR"},
	{Name: "lang", Summary: "flag.lang", Value: "tag", Env: "NCLY_LANG"},
	{Name: "verbose", Shorthand: "v", Summary: "flag.verbose", Env: "NCLY_VERBOSE"},
	{Name: "version", Summary: "flag.version"},
}

GlobalFlags declares the flags that every command accepts.

Functions

func IsDomain

func IsDomain(name string) bool

IsDomain reports whether name can be a domain: lowercase letters and digits that start with a letter.

Types

type Answer

type Answer struct {
	Verdict
	// contains filtered or unexported fields
}

Answer is a decided outcome, ready to print.

func (Answer) Errors

func (a Answer) Errors() []Problem

Errors returns the errors, the leading one first.

func (Answer) MarshalJSON

func (a Answer) MarshalJSON() ([]byte, error)

MarshalJSON renders ok and contract_version, the command's keys, then results, errors, and warnings when they hold entries.

func (Answer) OK

func (a Answer) OK() bool

func (Answer) Warnings

func (a Answer) Warnings() []Problem

func (Answer) WriteJSON

func (a Answer) WriteJSON(stdout, stderr io.Writer) error

WriteJSON prints the answer as one line: on stdout for a success or a report, and at the end of stderr for an answer with errors, after any diagnostics.

type Arg

type Arg struct {
	Name    string
	Summary string
	// Values lists the only accepted values, which completion also offers.
	// An empty list accepts any value.
	Values []string
}

Arg is one positional argument.

type Code

type Code string

Code is a stable machine identifier of an error or a warning.

const (
	UsageInvalid         Code = "USAGE_INVALID"
	ConfirmationRequired Code = "CONFIRMATION_REQUIRED"
	ConfigInvalid        Code = "CONFIG_INVALID"
	ExtensionInvalid     Code = "EXTENSION_INVALID"
	TerminalRequired     Code = "TERMINAL_REQUIRED"
	Runtime              Code = "RUNTIME"
	Temporary            Code = "TEMPORARY"
	Interrupted          Code = "INTERRUPTED"
	Terminated           Code = "TERMINATED"

	ConfigUnknownKey Code = "CONFIG_UNKNOWN_KEY"
)

func (Code) Exit

func (c Code) Exit() (ExitCode, bool)

Exit returns the exit code that one of core's error codes maps to, and false for any other code.

func (Code) IsWarning

func (c Code) IsWarning() bool

IsWarning reports whether c is one of core's warning codes.

type Command

type Command struct {
	// Path holds the words after ncly, such as {"completion"}.
	Path    []string
	Summary string
	Args    []Arg
	Flags   []Flag
	// Examples holds full command lines. Commands are never translated.
	Examples []string
	Effects  Effects
	Modes    Modes
	Result   Result
}

Command declares one command once, for help, completion, validation, and discovery. Text fields hold catalog IDs, never text. The declaration does not describe steps: the domain owns its behavior.

type Effect

type Effect int

Effect is the strongest change an invocation has made so far, from harmless to unsafe to repeat. It covers the whole invocation, including the items of a batch that succeeded.

const (
	// NoEffect means nothing changed outside Nicely's cache and the run's
	// own temporary files.
	NoEffect Effect = iota
	// RepeatableEffect means every change is covered by a demonstrated
	// idempotent operation.
	RepeatableEffect
	// NonRepeatableEffect means a second invocation would repeat or conflict
	// with a change.
	NonRepeatableEffect
	// UnknownEffect means a change may have happened, with no known result.
	UnknownEffect
	// PaidEffect means a paid request started, even if its response was lost.
	PaidEffect
)

type Effects

type Effects struct {
	UserWrites bool
	Network    bool
	Paid       bool
}

Effects lists every effect a command can have. A command that declares none changes nothing and calls no network.

type ExitCode

type ExitCode int

ExitCode is the process exit status of an invocation.

const (
	ExitOK          ExitCode = 0
	ExitRuntime     ExitCode = 1
	ExitUsage       ExitCode = 2
	ExitTemporary   ExitCode = 75
	ExitHuman       ExitCode = 78
	ExitInterrupted ExitCode = 130
	ExitTerminated  ExitCode = 143
)

func (ExitCode) Known

func (e ExitCode) Known() bool

Known reports whether e is one of the exit codes of the contract.

type ExtensionAnswer

type ExtensionAnswer struct {
	// Line is the answer as the extension wrote it, on the stream that
	// OnStdout names.
	Line []byte
	// contains filtered or unexported fields
}

ExtensionAnswer is an answer that passed the answer check.

func CheckAnswer

func CheckAnswer(m Manifest, kind ResultKind, r Reply) (ExtensionAnswer, error)

CheckAnswer applies the rules of Answer check in contract.md to the reply of a command of the extension that the manifest declares. A broken rule returns a *RuleError.

func (ExtensionAnswer) Failed

func (a ExtensionAnswer) Failed(lead Problem) ([]byte, error)

Failed renders the answer as a failure that lead decides: ok false, an error with lead's code first, and every other key kept, so the caller keeps the data of the work that happened, as Output in contract.md asks. lead goes first when the answer holds no error with its code.

type Flag

type Flag struct {
	Name      string
	Shorthand string
	Summary   string
	// Value names the value, such as tag. A flag without a value is a switch.
	Value string
	Env   string
}

Flag is one flag. Env names the variable with the same effect, for a global flag.

type Item

type Item struct {
	// Data holds the keys of the item, such as url. It marshals to an object.
	Data   any
	Errors []Problem
}

Item is the result of one input of a batch.

func (Item) MarshalJSON

func (it Item) MarshalJSON() ([]byte, error)

MarshalJSON renders the item's own ok, its keys, then its errors.

type Manifest

type Manifest struct {
	Domain   string
	Commands []Command
	// Errors holds the own codes in the order that decides which one leads.
	Errors []OwnCode
}

Manifest declares an extension's commands and its own error codes, as the Manifest section of contract.md defines.

func ParseManifest

func ParseManifest(data []byte, domain string) (Manifest, error)

ParseManifest reads the manifest of the extension of a domain and checks every rule of the Manifest section of contract.md, except the catalog IDs, which need the catalog. An empty domain takes the one that the manifest declares, as for an extension whose manifest is embedded. The versions come first, so a manifest of another format is rejected before its other keys are read.

func (Manifest) CheckCatalog

func (m Manifest) CheckCatalog(has func(id string) bool) error

CheckCatalog reports the first catalog ID of the manifest that the en catalog lacks.

func (Manifest) Command

func (m Manifest) Command(path string) (Command, bool)

Command returns the declaration of a path, such as "hello run".

func (Manifest) Registry

func (m Manifest) Registry() Registry

Registry returns the registry of the extension that the manifest declares, ordered as Output in contract.md defines: each own code comes after core's codes of its exit, except for exit 1, where the own codes come before RUNTIME. Every warning that starts with the domain and an underscore belongs to the extension too.

func (Manifest) Runs

func (m Manifest) Runs(c Command) bool

Runs reports whether a command starts the extension. The domain alone prints its help, as Usage in contract.md says, and so does a command with children and no arguments, which only groups them.

type Mode

type Mode int

Mode says whether ncly may ask a human questions.

const (
	NonInteractive Mode = iota
	Interactive
)

func DetectMode

func DetectMode(stdinTerminal, stdoutTerminal, noInput, json bool, lookupEnv func(string) (string, bool)) Mode

DetectMode applies the Modes section of contract.md. noInput and json are the resolved values of --no-input and --json, each flag over its variable: machine output never waits for a human. A set CI variable, even empty, means a machine runs ncly.

type Modes

type Modes struct {
	DryRun   bool
	Recorded bool
	Resume   bool
}

Modes lists the execution modes a command supports. A mode it does not declare is unsupported.

type Outcome

type Outcome struct {
	// Data holds the command's keys, kept on failure when they still apply,
	// such as output_dir. It marshals to an object.
	Data any
	// Results holds one item per attempted input, in input order. It stays
	// nil for a command that does not process several items.
	Results  []Item
	Errors   []Problem
	Warnings []Problem
	Effect   Effect
	Signal   Signal
	// HumanNeeded marks a report whose findings need a human, such as a
	// failed check of doctor. The report answers ok false and exit 78 on
	// stdout, without errors.
	HumanNeeded bool
}

Outcome is everything a command reports once its work stops.

type OwnCode

type OwnCode struct {
	Code Code
	Exit ExitCode
}

OwnCode is an error code that an extension declares.

type Problem

type Problem struct {
	Code    Code   `json:"code"`
	Message string `json:"message"`
	Hint    string `json:"hint"`
}

Problem is one entry of errors or warnings.

type Registry

type Registry struct {
	// contains filtered or unexported fields
}

Registry holds the codes that an answer may use, as Error codes in contract.md defines: core's, and those of the extension that answers. Its error codes compete to lead in its order.

func (Registry) Decide

func (r Registry) Decide(o Outcome) Verdict

Decide computes the verdict of an outcome. The order in which failures arrived never changes it.

func (Registry) Finish

func (r Registry) Finish(o Outcome, summarize func(Code) Problem) Answer

Finish decides an outcome and puts an error with the verdict's code first. When no error carries that code, as for an incomplete batch or a signal, summarize supplies one in the active language.

type Reply

type Reply struct {
	Exit   int
	Stdout []byte
	// Last is the last line of stderr, the answer of a failure.
	Last []byte
}

Reply is what an extension wrote under --json, as core holds it once the extension has exited.

func (Reply) OnStdout

func (r Reply) OnStdout(kind ResultKind) bool

OnStdout reports whether the answer of a command of this kind belongs on stdout: a success, and a report whose findings need a human.

type Result

type Result struct {
	Kind ResultKind
}

Result describes what a command answers.

type ResultKind

type ResultKind string

ResultKind tells how a command answers, and so how core checks the answer of an extension's command. A manifest that names no kind gets ResultObject.

const (
	ResultObject ResultKind = "object"
	ResultBatch  ResultKind = "batch"
	ResultReport ResultKind = "report"
	ResultText   ResultKind = "text"
)

type RuleError

type RuleError struct {
	Rule string
	Data map[string]any
}

RuleError names the first rule that a manifest or an answer breaks. Rule is the catalog ID of the message that explains it, and Data fills that message.

func (*RuleError) Error

func (e *RuleError) Error() string

type Signal

type Signal int

Signal records the signal that stopped an invocation, if any.

const (
	NoSignal Signal = iota
	Interrupt
	Terminate
)

func StopSignal

func StopSignal(sig os.Signal) Signal

StopSignal names the signal that stopped an invocation: Interrupt for Ctrl-C, and Terminate for any other, such as SIGTERM.

type Verdict

type Verdict struct {
	Exit ExitCode
	Lead Code
}

Verdict is the exit code of an outcome and the code of its leading error.

Jump to

Keyboard shortcuts

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