guard

package
v0.16.1 Latest Latest
Warning

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

Go to latest
Published: Nov 4, 2026 License: MIT Imports: 30 Imported by: 0 modules, 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 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

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

View Source
const AllowWindow = 10 * time.Minute

AllowWindow is how long a one-shot allow waits to be used.

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

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

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

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

View Source
const ShapeUnguardedVariablePath = "unguarded-variable-path"

ShapeUnguardedVariablePath names the shape in an entry's arg_shapes.

Variables

View Source
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")
	// ErrWeakenedSinceBase is the refusal of a registry weaker than the one at
	// the commit an agent's run started on (LoadRepoAt): an agent abcd started
	// without a terminal is judged against that one, and accepts only a
	// stronger one.
	ErrWeakenedSinceBase = errors.New("guard: registry weaker than at the run's base")
)

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

View Source
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 AllowStoreDisplay added in v0.16.0

func AllowStoreDisplay() string

AllowStoreDisplay names the store for a message, in the tilde form.

func ForgeMentionsOptedIn added in v0.16.0

func ForgeMentionsOptedIn(repoRoot string) bool

ForgeMentionsOptedIn reports whether the repository at repoRoot also opted into the mention check: `outbound.declare_mentions: true` beside `outbound.forge: true`. `abcd land` asks it before it judges the body it composes, so a body is held to the rules the guard would hold it to.

func ForgeTextOptedIn added in v0.14.2

func ForgeTextOptedIn(repoRoot string) bool

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.

func Validate

func Validate(r Registry) error

Validate checks the registry schema: the schema version, every entry id, and every entry's tier, pattern command, successor, and why. A per-repo override is validated AFTER merging, so an override can never produce an entry the bundled defaults would not have been allowed to ship.

Types

type Allowed added in v0.16.0

type Allowed struct {
	Command   string    `json:"command"`
	AllowedAt time.Time `json:"allowed_at"`
	ExpiresAt time.Time `json:"expires_at"`
}

Allowed is one one-shot allow.

func GrantAllow added in v0.16.0

func GrantAllow(home, rootSHA, command string, now time.Time) (Allowed, error)

GrantAllow records a one-shot allow of command for the repository whose root commit is rootSHA, in home, at now. A second grant of the same line before it is used replaces the first, restarting its window.

func TakeAllow added in v0.16.0

func TakeAllow(home, rootSHA, command string, now time.Time) (a Allowed, ok bool)

TakeAllow uses the one-shot allow of command, when one is recorded, still in its window, and readable as the person's own: it is removed as it is used, so a second run of the line finds none. A record past its window is removed and not used. ok is false whenever the line may not run on it.

type Approval added in v0.16.0

type Approval struct {
	// Allow is true when the guard approves the call.
	Allow bool
	// EntryID names what refused it: a registry entry, a reading's signal or
	// one of the reserved ids above. Empty on an allow.
	EntryID string
	// Reason is the refusal the agent is handed: what was refused, why, and
	// what to run instead. Empty on an allow.
	Reason string
}

Approval is abcd's answer to one permission prompt.

func ApprovePrompt added in v0.16.0

func ApprovePrompt(ld Loaded, files *Files, tool string, input json.RawMessage) (Approval, json.RawMessage)

ApprovePrompt answers a permission prompt for tool with input, the tool's parameters as the harness sent them. Only the shell is judged; a prompt for any other tool is refused, since nobody is there to approve it, and so is a shell call that asks to run outside the host's sandbox. On an allow the second value is the input to run: the command judged and its description, re-encoded, and nothing else the call carried, so a repeated key can never run a command other than the one the guard read and no field the guard did not read rides along on its approval.

type BranchAct added in v0.16.0

type BranchAct struct {
	Kind BranchActKind
	// Name is the branch the act leaves: the one created, checked out, or
	// renamed to.
	Name string
	// From is a rename's old name, "" for the current branch.
	From string
}

BranchAct is one branch a shell command creates, checks out into a new worktree or renames, as the created-branch recorder of the away mode reads it (spc-2610180914469489 step 3). It is a reading of the command line only: whether the branch exists is the recorder's question.

func BranchActs added in v0.16.0

func BranchActs(command string) []BranchAct

BranchActs reads command for the branches it creates, checks out into a new worktree or renames, in the order written. It refuses nothing and decides nothing: a line the tokenizer cannot split, and a word a substitution or a variable prints, are read as no act at all.

type BranchActKind added in v0.16.0

type BranchActKind string

BranchActKind is what a git command does to the branch a BranchAct names.

const (
	// BranchCreate is a branch the command creates: `git worktree add
	// -b|-B <b>`, `git switch -c|-C <b>`, `git checkout -b|-B <b>`, `git
	// branch <b>` and `git branch -c|-C [<old>] <b>`. The recorder keeps it
	// only when no branch of that name exists yet.
	BranchCreate BranchActKind = "create"
	// BranchCheckout is a branch `git worktree add` checks out in a new
	// worktree, creating it when it does not exist: a bare `git worktree add
	// <path>` names the branch after the folder, and `git worktree add <path>
	// <commit-ish>` names the commit-ish.
	BranchCheckout BranchActKind = "checkout"
	// BranchRename is `git branch -m|-M [<old>] <new>`: a record of <old>
	// (the current branch when From is "") is carried to <new>.
	BranchRename BranchActKind = "rename"
)

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"`
	// AllowableOnce marks a block whose only cause is a delete the guard could
	// not prove safe (deletes.go): a person's one-shot allow of the exact line
	// lets it through the hook (allowonce.go). Any other blocker leaves it
	// false, and no allow can pass it.
	AllowableOnce bool `json:"allowable_once,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

func Strictest(ds ...Decision) Decision

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

func UnparsableDecision(err error) Decision

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 DeleteKind added in v0.16.0

type DeleteKind string

DeleteKind is what a DeleteTarget deletes.

const (
	// DeleteRemoteBranch is a branch deleted on a remote: `git push <remote>
	// --delete <branch>` or `git push <remote> :<branch>`.
	DeleteRemoteBranch DeleteKind = "remote-branch"
	// DeleteLocalBranch is a local branch force-deleted: `git branch -D
	// <branch>` or `git branch -d -f <branch>`.
	DeleteLocalBranch DeleteKind = "local-branch"
	// DeleteWorktree is a worktree removed: `git worktree remove [--force]
	// <path>`.
	DeleteWorktree DeleteKind = "worktree"
)

type DeleteProof added in v0.16.0

type DeleteProof struct {
	Safe bool
	// Failed is the check that did not pass, or could not answer.
	Failed string
	// Settle is what a person or agent can do to make the target safe.
	Settle string
}

DeleteProof is a prover's answer for one target: safe, or the check that failed and what would settle it.

type DeleteProver added in v0.16.0

type DeleteProver interface {
	ProveDelete(t DeleteTarget) DeleteProof
}

DeleteProver proves a delete's target safe: merged into the default branch, with no open pull request, in no worktree and held by no live reservation for a branch; clean, used by no live process and on a merged branch for a worktree. It is attached by the front door (ProvingDeletes), because it runs git and the forge client, which the core does not choose.

type DeleteTarget added in v0.16.0

type DeleteTarget struct {
	Kind DeleteKind
	// Dir is the absolute directory git runs in: the command's working
	// directory, or the one `git -C` names.
	Dir string
	// Remote is the remote a remote branch is deleted on.
	Remote string
	// Branch is the branch deleted, without refs/heads/.
	Branch string
	// Path is the absolute path of the worktree removed.
	Path string
}

DeleteTarget is one thing a line deletes, as the line fixes it.

func (DeleteTarget) String added in v0.16.0

func (t DeleteTarget) String() string

String names the target for a refusal.

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.

func (Entry) Lesson added in v0.12.0

func (e Entry) Lesson() string

Lesson is the one-line rule an entry teaches: whether the guard refuses or warns, the entry id, the command it describes, the plain-language why, and the safe successor.

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.

func NewFiles added in v0.13.4

func NewFiles(dir string) *Files

NewFiles returns the reading context for a command run in dir: the host's working directory when it names one, else the session directory, and for `abcd guard check` the process's own. A relative or empty dir resolves no relative path.

func (*Files) WithRunDirs added in v0.16.0

func (f *Files) WithRunDirs(dirs ...string) *Files

WithRunDirs returns f with dirs as the run's own directories, each a clean absolute path; any other is left out.

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
	// LoadUnavailable: there is no registry to check against at all. The
	// 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.

func LoadRepo added in v0.11.0

func LoadRepo(repoRoot string) Loaded

LoadRepo loads <repoRoot>'s registry and decides the fail-safe posture.

func LoadRepoAt added in v0.16.0

func LoadRepoAt(repoRoot, base string) Loaded

LoadRepoAt is LoadRepo for an agent abcd started without a terminal, judged against the registry the run started on: base, the commit the run's working tree was cut from. The working tree's registry is the one in force only where it is at least as strong as base's: a weakening of any entry, a warn as much as a blocker, committed during the run or not, leaves no registry in force (ErrWeakenedSinceBase), and so does a base that names no commit.

type MergeMode added in v0.16.0

type MergeMode func() (human bool, reading string)

MergeMode reports whether the repository's facilitator mode is human, and how it reads ("facilitator.mode is human (repo layer, …)"), for the refusal. A mode that cannot be read is reported human, with why.

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"`
	// ArgPrefixesLiteral, when true, requires each arg_prefixes prefix to be
	// the operand's own text before its first substitution, as typed. By
	// default a substitution is read as printing nothing, so `"$(x)"+main:main`
	// carries `+`, which is the safe reading for a refusal. A warning about a
	// prefix that ordinary spellings place after a substitution
	// (`"$(git branch --show-current)":main` is a push, not a delete) sets it,
	// so the text a substitution prints is never read as the prefix's
	// absence. It is a pointer, as AfterCD is, so a per-repo override can
	// lift it as well as set it.
	ArgPrefixesLiteral *bool `json:"arg_prefixes_literal,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"`
	// Env, when set, additionally requires that the line sets one of these
	// environment variables for the command: as an assignment before it
	// (`NAME=value cmd`), as an operand of a wrapper that sets the
	// environment (`env NAME=value cmd`), or by an `export NAME` or `export
	// NAME=value` earlier in the line, or a `declare -x` or `typeset -x` of
	// it, which exports it as export does. It is what reads a
	// program that takes a setting from its environment as well as from its
	// flags: opencode reads its permission setting from OPENCODE_PERMISSION.
	// Names are compared exactly, as the environment does.
	Env []string `json:"env,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

func (p Pattern) Describe() string

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

func Load(repoRoot string) (Registry, error)

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

func Merge(base, over Registry) Registry

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

func (r Registry) Check(command string) (Decision, error)

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) DeleteLesson added in v0.16.0

func (r Registry) DeleteLesson() string

DeleteLesson is the rule the teaching plane carries for the delete proof, which no registry entry describes: the delete entries teach a warn, and in a repository the guard refuses each one it cannot prove safe. It is generated from the refusal's own words, so the lesson and the refusal cannot part, and opens with the guard-off lead under a disabled registry, as every lesson does.

func (Registry) Lessons added in v0.12.0

func (r Registry) Lessons() []string

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

func (r Registry) LessonsOver(bundled Registry) []string

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) ProvingDeletes added in v0.16.0

func (r Registry) ProvingDeletes(p DeleteProver) Registry

ProvingDeletes returns the registry with p proving its deletes. A registry loaded for a repository with no prover refuses every delete its entries name.

func (Registry) ReadingFrom added in v0.13.4

func (r Registry) ReadingFrom(f *Files) Registry

ReadingFrom returns r reading the files a command names from f.

func (Registry) RecallTerms added in v0.12.0

func (r Registry) RecallTerms() []string

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

func (r Registry) ScriptLesson() string

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

func (r Registry) ShellCLesson() string

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.

func (Registry) WithMergeMode added in v0.16.0

func (r Registry) WithMergeMode(m MergeMode) Registry

WithMergeMode returns r judging the merge commands by the mode m reports.

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

func ResolveWorkdir(sessionDir, raw string) (Workdir, error)

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.

Jump to

Keyboard shortcuts

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