Documentation
¶
Overview ¶
Package guard is abcd's transport-agnostic shell-hazard registry (itd-103, spc-16). It owns one registry of dangerous command patterns and the deterministic decision that a harness hook calls at execution time: given a candidate command line it returns allow, warn, or block — never writing to stdout, never exiting, never knowing a transport. Front doors under internal/surface format the decision, and the fail-open-loud behaviour on a broken guard lives in the hook shim, not here.
The model is a set of binary-bundled default entries (embedded from defaults/guard.json) merged with an optional per-repo <repoRoot>/.abcd/guard.json override. Each entry declares an id, a command-position pattern over shell tokens, a tier (blocker/warn), the safe successor, a plain-language why, and the known-bad/known-good fixtures that prove it. Bundled entries are held to an admission gate (fixtures present, known-good at least 40% of the corpus, 100% true-negative rate) enforced by TestBundledEntriesPassAdmissionGate, so an entry cannot ship without proof.
Matching is shell-token-aware and applies in COMMAND POSITION only: the candidate is tokenised with shell quoting honoured, so a hazard named inside a quoted string argument (an incident capture whose text mentions "cd scratch && rm -rf *") never fires. Quoting affects tokenisation, not argument semantics — `git push '--force'` still fires, because the shell hands the same argv either way.
Index ¶
- Constants
- Variables
- func ForgeTextOptedIn(repoRoot string) bool
- func Validate(r Registry) error
- type Decision
- type Entry
- type Files
- type Fixtures
- type FlagValue
- type LoadPosture
- type Loaded
- type PathArg
- type Pattern
- type Registry
- func (r Registry) Check(command string) (Decision, error)
- func (r Registry) Lessons() []string
- func (r Registry) LessonsOver(bundled Registry) []string
- func (r Registry) ReadingFrom(f *Files) Registry
- func (r Registry) RecallTerms() []string
- func (r Registry) ScriptLesson() string
- func (r Registry) ShellCLesson() string
- type Verdict
- type Workdir
Constants ¶
const ( TierBlocker = "blocker" TierWarn = "warn" )
Tier values, mirroring the record-lint severity family: a blocker refuses the command, a warn lets it through with the warning attached.
const MaxWorkdirBytes = 4096
MaxWorkdirBytes caps a host-supplied working directory: PATH_MAX on Linux, and above macOS's 1024, so no path a host could chdir into is refused.
const RepoMark = "(repo)"
RepoMark is the provenance a lesson carries when its words are a repository's own rather than abcd's: an entry the repository's .abcd/guard.json added, or a bundled entry it reworded (ruling CK1). It follows the entry id, as a rules override's "(repo override)" follows the domain name, so whose words an agent is being taught is never invisible (GHSA-22f8-qf5r-gjgq).
const RepoRelPath = ".abcd/guard.json"
RepoRelPath is the per-repo override file, relative to the repo worktree. It is a dedicated committed file rather than a rules.json domain: the entry schema is structured, and the rules loader's kill switch must never silently disable a safety guard (spc-16, "Config home"). Disabling the guard is itself a committed, reviewable act.
const SchemaVersion = 1
SchemaVersion is the guard config schema this build implements. It is independent of the rules loader's schema: the two features keep separate switches so a rules kill switch can never silently disable a safety guard.
const ShapeUnguardedVariablePath = "unguarded-variable-path"
ShapeUnguardedVariablePath names the shape in an entry's arg_shapes.
Variables ¶
var ( // ErrUnparsableCommand is a candidate command line the shell tokenizer // cannot split — an unterminated quote (`'`, `"`, `$'…'`, or one in a // here-document delimiter word) in COMMAND text, which no shell runs // either. Text inside a here-document BODY is never command text, so a // quote there is data and does not reach this error. A state bash DOES run // (a trailing backslash, an unterminated here-document) is never this // error, so those get a verdict of their own. The hook answers this one // with UnparsableDecision, a block, and the check verb reports it as a // fault: neither front door runs a line the guard could not read. ErrUnparsableCommand = errors.New("guard: unparsable command line") // ErrMalformedConfig is a per-repo .abcd/guard.json that is unreadable or // is not valid JSON. ErrMalformedConfig = errors.New("guard: malformed config") // ErrSchemaVersion is a config declaring a schema_version this build does // not implement. ErrSchemaVersion = errors.New("guard: unsupported schema_version") // ErrUnknownTier is an entry whose tier is neither blocker nor warn. ErrUnknownTier = errors.New("guard: unknown tier") // ErrInvalidEntry is an entry that fails the registry schema (bad id, no // pattern command, missing successor or why). ErrInvalidEntry = errors.New("guard: invalid entry") // ErrUncommittedOverride is a working-tree .abcd/guard.json that WEAKENS the // registry — switches the guard off, or changes a blocker's tier or pattern — // in an edit HEAD does not carry. Weakening the guard is a committed, // reviewable act (spc-16), so the edit is refused and the committed registry // stays in force until it is committed (iss-147). ErrUncommittedOverride = errors.New("guard: uncommitted override") )
The guard sentinels. Every error the package returns wraps one of these, so a front door can render the failure loudly without string-matching. Core never decides what a failure means for a session — it only names it, and offers the decision a front door that must answer may give (UnparsableDecision).
var ErrMalformedWorkdir = errors.New("guard: malformed working directory")
ErrMalformedWorkdir is a host-supplied working directory that no directory could be named by — a NUL byte, a control character, invalid UTF-8, a value over MaxWorkdirBytes, or a relative value with no absolute session directory to resolve it against. The value is written by the model, so it is untrusted input; the front door refuses the call rather than guess where it would run.
Functions ¶
func ForgeTextOptedIn ¶ added in v0.14.2
ForgeTextOptedIn reports whether the repository at repoRoot opted into the forge-text check: `.abcd/config.json` carries `outbound.forge: true`, a JSON boolean. Anything else — no file, a file that does not parse, a symlinked .abcd or config.json, a value that is not true — is not opted in. It is the one reader of the key; `abcd ahoy` asks it too.
Types ¶
type Decision ¶
type Decision struct {
Verdict Verdict `json:"verdict"`
// EntryID, Tier, Successor, and Why describe the winning entry; they are
// empty on an allow.
EntryID string `json:"entry_id,omitempty"`
Tier string `json:"tier,omitempty"`
Successor string `json:"successor,omitempty"`
Why string `json:"why,omitempty"`
// Message is the ready-to-surface sentence: the why plus the successor, so
// the refusal itself teaches the safe form.
Message string `json:"message,omitempty"`
// Matches lists every entry the command tripped (blocker ids first, then
// warn, each in id order), so a warn plane can surface all of them. It
// includes the reserved synthetic id when an execute-a-string payload raised
// an entry-less verdict.
Matches []string `json:"matches,omitempty"`
// Family and Reason describe an entry-less (synthetic) verdict — an
// execute-a-string wrapper, or a brace group the tokenizer cannot expand:
// the family that raised it and the plain-language reason. They are empty on
// an ordinary registry match. The raw payload is deliberately not carried —
// nothing reads it yet.
Family string `json:"family,omitempty"`
Reason string `json:"reason,omitempty"`
// Diagnostics are notes about the check that change no verdict: a script
// the command runs that does not exist, so there was nothing to read
// (script.go). They ride on any verdict, an allow included.
Diagnostics []string `json:"diagnostics,omitempty"`
}
Decision is what core returns for one candidate command. It carries no formatting and no exit status — the front door decides how to render it, and the hook shim decides what to do with a broken guard.
func Strictest ¶ added in v0.10.0
Strictest returns the most severe of the decisions — block over warn over allow — keeping the earliest on a tie, so a caller that lists the session's decision first keeps its lesson whenever the other registry adds nothing stricter. No decisions at all is an allow.
func UnparsableDecision ¶ added in v0.11.0
UnparsableDecision is the verdict a front door that must answer — the pre-tool-use hook — gives a command line Check refused with ErrUnparsableCommand. It is a BLOCK, not a pass: where the tokenizer reads the line right, no shell runs it either (an unterminated quote in command text), so the block costs nothing; where it reads it wrong, bash runs a line the guard never read, and letting it through made every such misreading a bypass of every blocker (review4-guard finding 2: `$'\c'` read as swallowing its own closing quote). err is named in the reason, so the way past is plain.
type Entry ¶
type Entry struct {
ID string `json:"id,omitempty"`
Pattern Pattern `json:"pattern"`
Tier string `json:"tier"`
Successor string `json:"successor"`
Why string `json:"why"`
Fixtures Fixtures `json:"fixtures,omitempty"`
// EverydayVerb, when true, marks the entry's command head as an everyday
// English verb (`kill`) rather than a shell-only word (`pkill`, `rm`). It
// changes nothing the guard refuses: it narrows the teaching plane's recall
// (RecallTerms), which offers such a head only joined to an operand or flag
// shape the pattern declares, so prose that merely uses the verb does not
// recall the shell lessons (iss-2609300123431381). It is a pointer, as
// Pattern.AfterCD is, so a per-repo override can lift the mark as well as
// set it.
EverydayVerb *bool `json:"everyday_verb,omitempty"`
}
Entry is one hazard. The map key in Registry.Entries is its id; ID is filled from that key on load, so the key is always authoritative — a declared id is accepted (the documented entry shape spells one out) and then overwritten, never used to rename the entry.
type Files ¶ added in v0.13.4
type Files struct {
// contains filtered or unexported fields
}
Files is the directory a command runs in, and the files the guard has read for it. A front door that checks one command against several registries hands each the same Files, so each file is read once per command.
type Fixtures ¶
type Fixtures struct {
KnownBad []string `json:"known_bad,omitempty"`
KnownGood []string `json:"known_good,omitempty"`
}
Fixtures is an entry's proof corpus: command lines it must fire on, and command lines it must not. The admission gate in fixtures_test.go enforces both sides plus the 40% known-good floor.
type FlagValue ¶
type FlagValue struct {
// Flag is an alternation group written with "|" ("-X|--method"), matching
// the spelling Pattern.Flags uses.
Flag string `json:"flag"`
// Values are the accepted settings. They are compared case-insensitively:
// an HTTP method's case is not what makes it destructive, and a constraint a
// change of case walks past is not a constraint.
Values []string `json:"values"`
}
FlagValue is one flag-with-value constraint: some argument must set one of Flag's "|"-separated alternatives to one of Values.
type LoadPosture ¶ added in v0.11.0
type LoadPosture uint8
LoadPosture is what a load produced, and so what a front door owes the session. It is decided here, once, so the hook, the check verb, the health report and any later surface format the same answer rather than each re-deriving it from the registry's size (iss-2608291814576261).
const ( // LoadClean: every layer loaded, or there was no repo layer to load. LoadClean LoadPosture = iota // LoadRepoDropped: the repo layer was refused — unreadable, invalid, or an // uncommitted weakening edit — and the registry holds what could be trusted: // the bundled hazards, plus the committed repo layer when only a // working-tree edit was refused. It is armed. A session keeps checking // against it and is told, loudly, that the repo layer was dropped; a caller // that asked a question (the check verb) is told the registry it asked about // is not the one in force. LoadRepoDropped // embedded defaults make it unreachable in practice; a session reaching it // runs unguarded, and must say so. LoadUnavailable )
type Loaded ¶ added in v0.11.0
type Loaded struct {
Registry Registry
Posture LoadPosture
Err error
}
Loaded is the typed result of loading a repo's hazard registry: the registry to check against, the posture the load ended in, and the error behind any posture but LoadClean.
type PathArg ¶
type PathArg struct {
// Root is the first path segment the operand must have ("repos").
Root string `json:"root"`
// Segments is the EXACT number of segments the operand must hold, counting
// Root: three for `repos/{owner}/{repo}`. Exact rather than a maximum,
// because it is the deeper paths — not the shallower ones — that stay
// allowed.
Segments int `json:"segments"`
}
PathArg is one operand constraint for a slash-separated resource path.
type Pattern ¶
type Pattern struct {
// Command is the executable that must stand in command position. It is
// compared against the segment's argv[0] by basename, so /bin/rm matches rm.
Command string `json:"command"`
// Subcommand, when set, must be the first non-flag argument (git push,
// git reset). ValueFlags lets a global option that consumes the next token
// be skipped while looking for it.
Subcommand string `json:"subcommand,omitempty"`
// Subcommand2, when set, must be the SECOND non-flag argument — the
// two-level grammar `gh repo delete`, which one Subcommand cannot express
// (`gh repo list` and `gh repo delete` share their first level, and only one
// of them is a hazard).
Subcommand2 string `json:"subcommand2,omitempty"`
// ValueFlags are flags of Command that consume the FOLLOWING token, so the
// scan for Subcommand steps over the value rather than reading it as the
// subcommand (`git -C /repo push`).
ValueFlags []string `json:"value_flags,omitempty"`
// Flags are argument constraints. Each element is one alternation group
// written with "|" ("--force|-f"); every group must be satisfied by some
// argument token. A long alternative also matches its --flag=value form; a
// single-letter short alternative also matches inside a bundled cluster
// (-rf satisfies -r and -f).
Flags []string `json:"flags,omitempty"`
// FlagValues constrain what a flag is SET TO, not merely that it is present.
// `gh api -X DELETE repos/owner/repo` deletes the repository and
// `gh api -X GET repos/owner/repo` reads it, so an entry that could only ask
// whether -X appears would have to choose between missing the first and
// refusing the second. Every listed constraint must be satisfied.
FlagValues []FlagValue `json:"flag_values,omitempty"`
// ArgPaths constrain an operand that names a slash-separated resource path,
// by its first segment AND its exact depth. Depth is the point: DELETE on
// `repos/{owner}/{repo}` destroys the repository, while DELETE on a deeper
// path under it (a branch ref, a release) is ordinary work that stays
// allowed. Every listed constraint must be satisfied.
ArgPaths []PathArg `json:"arg_paths,omitempty"`
// ArgPrefixes constrain an OPERAND rather than a flag: every listed prefix
// must be carried by some non-flag argument. It is what describes a hazard
// spelled without any flag at all — `git push origin +main:main`, where the
// leading `+` on the refspec is a force push by another name and Flags has
// nothing to look at.
ArgPrefixes []string `json:"arg_prefixes,omitempty"`
// ArgValues constrain an OPERAND to one exact word: some non-flag argument
// must be one of the listed words, compared by its known text. It is what
// separates `rm -rf /` and `rm -rf ~`, which destroy the machine or the
// home directory, from `rm -rf /tmp/build`, which a prefix could not tell
// apart. The words are compared as written, before the shell expands them:
// `$HOME` is the word `$HOME`, and `*` the word `*`. An operand is also
// compared as a path with its redundant separators taken out: `//*` is
// the word `/*`, and `$HOME/./` the word `$HOME/`.
ArgValues []string `json:"arg_values,omitempty"`
// ArgShapes constrain an OPERAND by a shape of the word as the line wrote
// it, which neither a fixed prefix nor an exact word can say: every listed
// shape must be carried by some non-flag argument. The shapes are a closed
// set the matcher knows (argShapes), so a misspelt name is refused at load
// rather than describing an operand nothing can be.
//
// ShapeUnguardedVariablePath is an operand that begins with a variable
// whose value can be empty, directly followed by `/` (`"$VAR"/*`,
// `${VAR}/x`, `"$VAR/x"`): empty or unset, it names a path from the
// filesystem root. `"${VAR:?}"/x` is not it, nor is a default that cannot
// be empty (`"${TMPDIR:-/tmp}"/x`), a variable later in the path
// (`./build/$name`), or a bare `"$VAR"`, which empties to no path at all.
// `$HOME` and `$PWD` are not counted: the login and the shell set them,
// and the entries that name them own a delete of them.
ArgShapes []string `json:"arg_shapes,omitempty"`
// MinOperands, when set, requires at least that many non-flag arguments
// (value_flags stepped over). It is what separates a kill BY PATTERN —
// `pkill make`, whose operand is the pattern — from `pkill -g 4242`, which
// names a process group and carries no pattern at all.
MinOperands int `json:"min_operands,omitempty"`
// ArgsFrom, when set, additionally requires that the command's arguments
// come, at least in part, from the output of a command matching one of
// these patterns: a command substitution in a word after the command, or,
// where `xargs` runs the command, the commands before it in the pipeline
// that feeds xargs. It is what reads `kill $(pgrep -f make)` and `pgrep -f
// make | xargs kill` as the kill by name they are, while `kill 4242` and
// `kill $(cat pidfile)` stay a kill of the pid named. A pattern listed here
// is a plain one: it may not itself carry args_from or after_cd.
ArgsFrom []Pattern `json:"args_from,omitempty"`
// AfterCD, when true, additionally requires that some EARLIER command in the
// same chain is a `cd`, `pushd` or `popd` — the cd-chain structure (`cd
// scratch && rm -rf *`) whose hazard is that a failed directory change
// silently redirects the command. A nil
// pointer means false; it is a pointer so a per-repo override can turn the
// requirement off as well as on.
AfterCD *bool `json:"after_cd,omitempty"`
}
Pattern is a command-position match expressed over shell tokens, never raw text. All declared constraints must hold for the pattern to fire.
func (Pattern) Describe ¶ added in v0.12.0
Describe renders the pattern as the command it matches, in plain words: the command head, then each declared constraint in the order the matcher applies them. Every constraint an entry declares appears, so a lesson never describes a narrower or broader command than the guard refuses.
type Registry ¶
type Registry struct {
SchemaVersion int `json:"schema_version"`
Disabled bool `json:"disabled"`
Entries map[string]Entry `json:"entries"`
// contains filtered or unexported fields
}
Registry is the merged, validated hazard model: the bundled defaults overlaid with the per-repo override.
func Defaults ¶
func Defaults() Registry
Defaults returns a deep copy of the binary-bundled registry, safe for the caller to mutate.
func Load ¶
Load returns the bundled defaults merged with <repoRoot>/.abcd/guard.json when that file exists. An absent file yields the defaults unchanged.
A repo override that cannot be read, parsed, or validated is a fail-SAFE fallback, not a fail-open one: Load returns the bundled defaults ALONGSIDE the error (never an empty registry), so a broken repo layer drops only the repo's own overrides while the built-in hazards stay armed. Returning empty here would disable the whole guard on one broken committed file — the fail-open the bundled hazards never depended on (iss-2608261551087492). The error is still returned so the caller (the hook shim) can announce the dropped repo layer loudly while continuing to check against the bundled registry.
func Merge ¶
Merge overlays over onto base. Entry fields are per-field: a field set on the override wins, an absent field inherits the bundled entry (so {"tier":"warn"} retiers an entry while keeping its pattern, successor, and why). New entry keys are added. The kill switch is sticky — either side can disable the guard, and neither can silently re-enable the other's refusal to run it.
func (Registry) Check ¶
Check evaluates one candidate command line against the registry. A disabled registry allows everything (the escape is committed and reviewable, never an in-session override). A command line the tokenizer cannot split is an error, not an allow — core names the failure and the caller decides what it means.
func (Registry) Lessons ¶ added in v0.12.0
Lessons renders every entry's Lesson in entry-id order: the rules of the teaching plane, one per registry entry.
func (Registry) LessonsOver ¶ added in v0.12.0
LessonsOver renders r's lessons as Lessons does, one per entry in id order, and marks with RepoMark every lesson bundled does not teach word for word: an entry bundled lacks, or one whose lesson a repository layer changed (its tier, pattern, why or successor). A change no lesson shows — a fixture — leaves the bundled lesson unmarked, because the words taught are still abcd's. The registry is the guard's registry in force for the repository, so the plane teaches exactly what the guard enforces there.
func (Registry) ReadingFrom ¶ added in v0.13.4
ReadingFrom returns r reading the files a command names from f.
func (Registry) RecallTerms ¶ added in v0.12.0
RecallTerms returns the command head of every entry, sorted and unique: the command followed by its subcommands, as it stands in command position (`git push`, `gh repo delete`, `rm`). They are the registry's own recall vocabulary for the teaching plane — narrow by construction, because the head carries the subcommand: `git push` recalls it and the bare word "push" does not.
An entry marked EverydayVerb offers its head only joined to a shape its own pattern declares (recallShapes), never bare: `kill` is an ordinary English verb, and "kill the feature flag" is not shell work (iss-2609300123431381). The mark is the registry's, so the exclusion has one source; an unmarked entry with the same head still offers it bare.
func (Registry) ScriptLesson ¶ added in v0.13.4
ScriptLesson is the rule the teaching plane carries for the script reading (adr-2610091150447054), which no registry entry describes: what the guard reads before it judges a command, what blocks, and what it does not see. It is written beside the reading (script.go) so the two change together, and opens with the guard-off lead under a disabled registry, as every lesson does.
func (Registry) ShellCLesson ¶ added in v0.15.1
ShellCLesson is the rule the teaching plane carries for the refusal, in the shape every entry's lesson takes: the lead, the id, the command, the why and what to run instead. Under a disabled registry it opens with the guard-off lead, as every lesson does.
type Verdict ¶
type Verdict string
Verdict is the decision a front door acts on.
const ( // VerdictAllow means no entry matched: run the command. VerdictAllow Verdict = "allow" // VerdictWarn means a warn-tier entry matched: run the command with the // warning surfaced. VerdictWarn Verdict = "warn" // VerdictBlock means a blocker-tier entry matched: refuse, and reply with // the successor as the block message. VerdictBlock Verdict = "block" )
type Workdir ¶ added in v0.10.0
type Workdir struct {
// Path is absolute and lexically clean. Empty means the host supplied none
// and the command runs in the session directory.
Path string
// Exists reports whether Path named a directory at check time. A workdir that
// does not is one the probed host refuses to run in, so there is no
// directory whose registry could apply.
Exists bool
}
Workdir is a host-supplied per-call working directory after validation.
func ResolveWorkdir ¶ added in v0.10.0
ResolveWorkdir validates raw, a host-supplied per-call working directory, and resolves it against sessionDir the way the probed host does. An empty raw is no workdir at all. A refusal wraps ErrMalformedWorkdir and names what it found, never echoing a control byte back.