ahoy

package
v0.11.1 Latest Latest
Warning

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

Go to latest
Published: Sep 28, 2026 License: MIT Imports: 40 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 ahoy is abcd's install/update engine for `abcd ahoy`. It follows a detect -> contract -> apply architecture: a single detection pass builds an in-memory DetectionResult (the ahoy-state shape) and every sub-verb (install, dry-run, doctor, bare status) is a thin consumer of that one pass. Idempotency is a property of detection, never a version stamp: every check compares actual on-disk/registry state.

The package performs I/O only under a caller-supplied cwd and the user-scope ~/.abcd/ store (and, on install, an owned PATH copy). It never writes to stdout, never calls os.Exit, and never imports a transport (cobra/MCP), so it is fully testable and reusable across surfaces. Interactive decisions are routed through the injected Prompter seam.

Index

Constants

View Source
const (
	// ArtefactMissingGapID is the gap a repository with no declaration raises.
	ArtefactMissingGapID = "artefact.missing"
	// ArtefactInvalidGapID is the diagnostic for a declaration that is present
	// and wrong. It is the user's data, so install reports it and never
	// overwrites it.
	ArtefactInvalidGapID = "artefact.invalid"
)
View Source
const (
	GuardHookRelPath      = ".githooks/pre-commit"
	GuardMergeHookRelPath = ".githooks/pre-merge-commit"
)

The committed guard's two halves, repo-relative and slash-separated (they are os.Root paths as well as report text).

They are COMMITTED hooks, not .git/hooks copies: .git/hooks is per-clone and untracked, so a guard installed there protects one working copy and no one else's. A clone points git at this directory once (`git config core.hooksPath .githooks`) and every checkout inherits the check.

pre-merge-commit exists because git runs NO pre-commit hook for a merge commit. Without it every name the private layer bans walks into history the moment a branch carrying it is merged, and the guard reports nothing because it was never asked.

View Source
const (
	MismatchGapID     = "git_identity.mismatch"
	UnsetGapID        = "git_identity.unset"
	CommitterGapID    = "git_identity.committer"
	ToolIdentityGapID = "git_identity.tool"
)

The identity gap ids the detector raises and the establish step reads.

View Source
const (
	// OracleRoutingMachineGapID is the offer of the machine's routing table.
	OracleRoutingMachineGapID = "oracle_routing.machine_offered"
	// OracleRoutingRepoGapID is the offer of the repository's routing table.
	OracleRoutingRepoGapID = "oracle_routing.repo_offered"
)
View Source
const (
	// ProviderAdapterGapID is the explanation, raised while no provider is
	// configured on this machine.
	ProviderAdapterGapID = "oracle_api.none_configured"
	// ProviderAdapterRefusedGapID names a provider configuration the adapter
	// refuses, so it is never silently unused.
	ProviderAdapterRefusedGapID = "oracle_api.config_refused"
)
View Source
const AttributionHookRelPath = guardHooksDirRelPath + "/prepare-commit-msg"

AttributionHookRelPath is the committed prepare-commit-msg hook, repo-relative and slash-separated (an os.Root path as well as report text). It sits beside the name guard's two halves, in the directory a clone points git at once.

View Source
const GitHubHost = githubHost

GitHubHost is the API host every forge request names explicitly.

View Source
const OptionalPinGapID = "git_identity.unpinned"

OptionalPinGapID is the one optional gap --yes does not cover. Named here so the front doors can point at it without re-deriving the string.

View Source
const RepoSettingsMirrorRelPath = ".abcd/work/rulesets/repo-settings.json"

RepoSettingsMirrorRelPath is the committed mirror of the repo-object settings abcd manages, repo-relative and slash-separated. It sits beside the branch-ruleset mirror, which covers RULESETS only: the security toggles live behind the separate repository-object API, so a settings change had no source of truth in the tree at all and every claim about it rested on a web console (iss-2608270512210664).

View Source
const (
	StatusLineOfferGapID = "statusline.offered"
)

Gap ids. StatusLineOfferGapID is exported for the front doors, which name the optional gaps --yes leaves for an answered prompt.

View Source
const VintageSourceCheckoutTip = "checkout tip"

VintageSourceCheckoutTip is the VintageStatus.Source a dogfood comparison reports — the one reference that is ancestry-guarded and so the one whose staleness may claim a direction (see Staleness).

Variables

View Source
var DependencyTools = []string{"gitleaks"}

DependencyTools names the tools detectDependencies checks for, and so the tools `ahoy install --install-tool` can name: the front door refuses any other, since no gap would ever put it to the question.

Functions

func EnsureMarker

func EnsureMarker(path string, dryRun bool) (changed bool, err error)

EnsureMarker installs, refreshes, or (dryRun) predicts the CURRENT abcd marker block in the file at path. It NEVER copies foreign prose — only the canonical block travels, so an embark can re-inject the block into a target CLAUDE.md without carrying a lifeboat's authored text. With dryRun it writes nothing and reports whether a real run WOULD change the file (the embark probe path); without it, it performs the write (the embark write path) — one code path, so probe cannot mispredict. changed reports whether the file was/would be written; a symlinked or unwritable target returns a non-nil error and changed=false.

It wraps the existing unexported classify/install machinery: dryRun maps classifyMarker(path) → current→(false,nil), missing/outdated→(true,nil), symlink or unplaceable→(false, err); a real run calls installMarkerFile(path) → its error wrapped as (false, err), else (wrote, nil).

func GH added in v0.11.1

func GH(cwd string, stdin []byte, args ...string) ([]byte, error)

GH runs one `gh` subcommand under cwd with the same bounds the remote apply uses: a timeout, a capped read, and the caller's own authenticated identity, so a forge write is made by the person who invoked the verb and abcd never holds a forge token. Callers pass `--hostname github.com` explicitly for the reason githubHost states.

func GitHubRepo added in v0.11.1

func GitHubRepo(cwd string) (string, error)

GitHubRepo is the owner/name this checkout's origin remote names, under the same github.com-only, plain-name rules the remote apply writes behind. Every verb that writes to the forge resolves its repository here, so there is one answer to "which repository may this write reach".

func IsOwnedPathCopy added in v0.8.0

func IsOwnedPathCopy(target string) bool

IsOwnedPathCopy reports whether target is the regular file abcd installed as this machine's PATH entry: ~/.abcd/path-entry names that very entry and the bytes still hash to the recorded value. It is the exported face of the same predicate `ahoy` classifies with, published for `abcd update`, which needs a proof of ownership that no release deletion can revoke (iss-2609012000222546, and the itd-130 fidelity audit's ac-1 concern (b): the record was re-stamped after a swap but never consulted as a proof before one). It reads two local files and touches no network.

func Managed added in v0.9.0

func Managed(root string) bool

Managed reports whether the checkout rooted at root is one abcd manages: the exact question classify answers with ManagedRepo, exported as a cheap predicate for the two front doors that ask it on every render — the status verb the harness invokes on each refresh, and the bare board (spc-70).

It is classify's strong-signal rule and nothing more: a marker block in CLAUDE.md or AGENTS.md at the root, or registration in the user-level history index by root commit. A bare `.abcd/` is not a managed signal on its own (iss-88), and a plain git checkout is not managed. No new heuristic lives here; TestManagedAgreesWithClassify holds the two to the same answer on every fixture.

What it does NOT do is run the full detection pass. Detect walks PATH, reads the plugin root, probes guard health and the rest, and a status line that paid for that on every keystroke would be a status line people switch off. The marker is read first, because it settles the ordinary managed case with two file reads and no subprocess; git is asked for the root commit only when the marker is absent AND there is an index to look it up in. Zero network, zero writes.

func PluginDataDirHazard added in v0.11.1

func PluginDataDirHazard(dataDir, cwd string) string

PluginDataDirHazard is dataDirHazard for a front door that reads the harness data directory itself (the session-start skew notice): the reason dataDir cannot be trusted, or "" when it has the shape the harness always gives it. One check, so the surface and core cannot disagree about which directories are believed.

func RefreshPathEntryDigest

func RefreshPathEntryDigest(target, shaHex string)

RefreshPathEntryDigest re-records the provenance hash for the owned PATH copy after `abcd update` swapped the file at target — the one other verb that legitimately changes those bytes, and only after proving the new content against a published release's own checksums. Without this the entry update just refreshed would classify foreign forever after. A record that does not name target, a malformed digest, or no record at all is a no-op: this refreshes provenance, it never creates it.

func ResolvePluginRoot added in v0.7.1

func ResolvePluginRoot() (string, bool)

ResolvePluginRoot is the exported face of resolvePluginRoot for the front doors: the same ladder (ABCD_PLUGIN_ROOT -> CLAUDE_PLUGIN_ROOT -> executable-ancestor -> recorded path-entry root), the same layout check, so a surface never grows a second notion of where the plugin lives.

func SetCurrentVintageForTest

func SetCurrentVintageForTest(f func() vintage.Current) (restore func())

SetCurrentVintageForTest overrides the build-vintage seam and returns a restore func. It is a test-only seam (in the manner of this package's history hooks): a go-test binary is itself unstamped, so without an override every install path in a front-door test package would hit the itd-111 unknown-vintage refusal. Front-door test packages, which cannot reach the unexported seam, install a deterministic vintage through this. Production never calls it — it reads the embedded build info.

func StripMarkerBlock

func StripMarkerBlock(content []byte) ([]byte, bool)

StripMarkerBlock returns content with every abcd marker block (a balanced BEGIN…END fence and its surrounding blank lines) removed, and reports whether anything was stripped. Content with no block is returned unchanged. It is the pure, path-free form of removeMarkerFile, exported for the lifeboat packer: carrying a stale marker block into a packed record would plant a dead rules-loader in whatever repo later embarks it, so a verbatim copy is passed through this first. Only a balanced pair is matched, so an unbalanced fence or a literal mention of the delimiter text outside a pair is left intact.

func VersionTransition

func VersionTransition(cwd string) (recorded, running string, changed bool)

VersionTransition reports a version change performed since this repo was last set up: the last-recorded setup_version (written into .abcd/config.json by install) against the running binary's version. It is AC6's report only — the fetch that changed the binary is provisioning's job (itd-105/108), out of this intent. changed is false when either side is undeterminable or they match; the report is direction-neutral, since a repo set up by a newer binary and now run through an older one is the same inequality read backwards.

Types

type ApplyResult

type ApplyResult struct {
	Category     GapCategory
	GapsResolved []string
	GapsSkipped  []string
	Notes        []string
}

ApplyResult is the outcome of one apply step.

type BanlistHealth

type BanlistHealth struct {
	// Hook and MergeHook are the committed guard's two halves. A merge commit runs
	// NO pre-commit hook, so a repo with only the first half is uncovered for exactly
	// the commit that merges someone else's branch.
	Hook      HookState `json:"hook"`
	MergeHook HookState `json:"merge_hook"`
	// HooksPathArmed reports whether THIS clone's local git config points at the
	// committed hooks directory. False is not a fault — the hooks path can be armed
	// by a user-level dispatcher this deliberately does not claim to see — so the
	// surfaces phrase it as an instruction, never as an accusation.
	HooksPathArmed bool `json:"hooks_path_armed"`
	// PublicFamily is the committed layer's state, including the case where it is
	// present and readable but git ignores the file, so CI never sees it.
	PublicFamily PublicFamilyState `json:"public_family"`
	// HookEOLPinned reports whether .gitattributes keeps the committed hooks at LF.
	// Meaningful only where abcd owns the hooks: pinning the EOL of a directory whose
	// contents are someone else's is not abcd's call.
	HookEOLPinned bool `json:"hook_eol_pinned"`
	// PublicConfigIgnored is git's verdict on the config's PATH, whether or not a
	// file is there yet. It is what makes the absent-family gap honest: writing a
	// config into a path git ignores delivers no enforcement, so abcd does not offer
	// to.
	PublicConfigIgnored bool `json:"public_config_ignored"`
	// PublicConfigWritable reports whether scaffolding may create the config here. It
	// is NOT the negation of PublicConfigIgnored: a probe git could not answer is
	// neither ignored nor safe, and it fails closed inside anything repo-shaped.
	PublicConfigWritable bool `json:"public_config_writable"`
	// PrivateStore reports whether THIS MACHINE has opted in. False is the honest
	// "inactive here" state, never silence: an absent store checks nothing, and the
	// guard says so at commit time for the same reason.
	PrivateStore bool `json:"private_store"`
	// PrivateStoreIgnored is git's verdict on the store's path. A present store git
	// would track is one `git add -A` from committing the patterns it exists to keep
	// out of history.
	PrivateStoreIgnored bool `json:"private_store_ignored"`
	// PrivateKeyed, PrivateEntries and PrivateUnparsed are the store's SHAPE, never
	// its content: a format flag and two counts, taken from the shared parser. A line
	// that does not parse stops every commit until it is fixed.
	PrivateKeyed    bool `json:"private_keyed"`
	PrivateEntries  int  `json:"private_entries"`
	PrivateUnparsed int  `json:"private_unparsed"`
	// PrivateUnreadable reports a store that exists and cannot be read for what it
	// is — a damaged format declaration, an unreadable file. The guard refuses every
	// commit in that state, so a status board must not render it as healthy.
	PrivateUnreadable bool `json:"private_unreadable"`
	// Reach is PrivateReachNote, unconditionally.
	Reach string `json:"reach"`
}

BanlistHealth is the two-layer name guard's state in one repo: which of the scaffolded artefacts are there, what shape the private layer is in, and — always — how far it reaches (spc-20 AC7).

Reach is carried in the struct rather than added by a renderer because this report is read on two surfaces at once. A human sees a line; a machine consumer reads the fields. "hook: installed" beside a populated private store reads as "covered" to both of them, and it is not: the guard runs on machines that opted in, for the commits git asks a hook about, and nowhere else. The caveat travels with the state it qualifies.

type ChoiceHelp added in v0.11.1

type ChoiceHelp struct {
	Value   string `json:"value"`
	Meaning string `json:"meaning"`
}

ChoiceHelp explains one answer to an install question in plain language: what choosing it does to the person's repository or machine, and what it asks of them (keys, tools, cost) where it asks anything.

type DetectionResult

type DetectionResult struct {
	FolderKind       FolderKind     `json:"folder_kind"`
	Adopted          *bool          `json:"adopted"` // nil on detect/dry-run
	RootSHA          string         `json:"root_sha"`
	PluginRootStatus string         `json:"plugin_root_status"` // "resolved" | "missing"
	RepoIdentity     RepoIdentity   `json:"repo_identity"`
	Signals          map[string]any `json:"signals"`
	// Guard is the execution-time shell guard's health. It is reported on every
	// pass over a repo, healthy or not: a guard that fails open looks exactly like
	// a working one from inside a session, so the state has to be legible from
	// outside.
	//
	// A POINTER, omitted entirely for an unmanaged folder — like Banlist below and
	// for the same reason: its fields are definite booleans, so a never-computed
	// zero value would serialise four `false` facts (and no detail) that read as "a
	// broken guard" to a consumer that never asked about a repo, in a document that
	// simultaneously reports the plugin root resolved.
	Guard *GuardHealth `json:"guard,omitempty"`
	// Banlist is the two-layer name guard's state. Like Guard it is reported on
	// every pass over a repo — and it carries its own reach, because a private layer
	// that looks installed says nothing about what a pull request is checked against.
	//
	// A POINTER, omitted entirely for an unmanaged folder: the states it reports are
	// named strings ("absent", "foreign") and its ignore flag is warning-polarity, so
	// a zero value would serialise undeclared states and a false that reads as "the
	// store is trackable" to a consumer that never asked about a repo.
	Banlist *BanlistHealth `json:"banlist,omitempty"`
	Gaps    []Gap          `json:"gaps"`
	// contains filtered or unexported fields
}

DetectionResult is the canonical envelope. dry-run marshals exactly this (with Adopted=nil).

func Detect

func Detect(cwd string) (DetectionResult, error)

Detect runs the full detection pass over cwd and returns the canonical envelope. Total over a normal folder: broken-plugin conditions surface as gaps, never as a hard error. An error is returned only for malformed input.

func DryRun

func DryRun(cwd string) (DetectionResult, error)

DryRun runs Detect and returns the envelope (Adopted=nil). Zero writes.

type DoctorReport

type DoctorReport struct {
	Detection DetectionResult `json:"detection"`
	AuditGaps []Gap           `json:"audit_gaps"`
}

DoctorReport is the outcome of Doctor: the detection envelope plus read-only cross-machine reconciliation gaps.

func Doctor

func Doctor(cwd string) (DoctorReport, error)

Doctor runs the detection pass plus a read-only cross-machine audit. Zero writes.

type DogfoodReport

type DogfoodReport struct {
	IsDogfood bool            // cwd is abcd's own source checkout (the binary was built from it)
	Outcome   vintage.Outcome // Fresh (silent) / Stale / Unknown (a dirty rebuild)
	Revision  string          // the binary's embedded revision (full)
	Tip       string          // the checkout tip it should match (full)
}

DogfoodReport is the source-checkout-tip comparison the session-start notice consumes. It is scoped to the dogfood case on purpose: a pinned install in a user's own repo must never be nagged, so IsDogfood gates the whole notice.

func DogfoodStaleness

func DogfoodStaleness(cwd string) DogfoodReport

DogfoodStaleness reports whether the running binary trails the tip of the source checkout it was built from, for the session-start notice. It reads the binary's own build vintage and compares against cwd's HEAD.

type FolderKind

type FolderKind string

FolderKind is the classification of the folder ahoy runs in. There is no workspace layer: abcd manages exactly one kind of folder, a repository.

const (
	// ManagedRepo is a git repo abcd already manages (a strong marker fired).
	ManagedRepo FolderKind = "managed-repo"
	// UnmanagedRepo is a git repo with no abcd markers yet (adoptable).
	UnmanagedRepo FolderKind = "unmanaged-repo"
	// UnmanagedFolder is not a git repo and has no abcd markers.
	UnmanagedFolder FolderKind = "unmanaged-folder"
)

type Gap

type Gap struct {
	ID         string      `json:"id"`
	Category   GapCategory `json:"category"`
	Scope      string      `json:"scope"` // "repo" | "machine"
	Title      string      `json:"title"`
	Detail     string      `json:"detail"`
	FixHint    string      `json:"fix_hint"`
	Required   bool        `json:"required"`   // advisory gaps set false
	Resolvable bool        `json:"resolvable"` // false => diagnostic only
	// Tool is the tool registry's explanation for a dependency gap (itd-63):
	// what the tool is, whether this capability needs it, what works without
	// it, and the exact install step. Absent on every other gap.
	Tool *tools.Explanation `json:"tool,omitempty"`
}

Gap is one detected discrepancy between desired and actual state.

type GapCategory

type GapCategory string

GapCategory groups gaps for the one-approval-per-category apply protocol.

const (
	// SafeAutocreate covers artefacts written without a per-item prompt once
	// the category is approved (the .abcd/ skeleton, history-store dirs).
	SafeAutocreate GapCategory = "safe-autocreate"
	// ConfigChange covers transparent-confirm changes (visibility, symlink).
	ConfigChange GapCategory = "config-change"
	// PluginOwned covers the marker block and the (verify-only) hook manifest.
	PluginOwned GapCategory = "plugin-owned"
	// Dependency covers the external tools a capability uses (itd-63): each gap
	// carries the tool registry's explanation, and a tool is installed only on
	// an answer the front door's confirmation returns, never on the category
	// approval alone.
	Dependency GapCategory = "dependency"
	// UserState covers ~/.abcd/history registry state (guided, never auto-edited).
	UserState GapCategory = "user-state"
	// StatusLine covers the host harness's status-line wiring (spc-70). Its one
	// gap is advisory and is never written under --yes: the wiring rewrites a
	// harness-wide user setting and takes element choices, so only an answered
	// prompt writes it.
	StatusLine GapCategory = "status-line"
	// OracleRouting covers accepting abcd's proposed model-tier routing table,
	// at the machine and, offered separately, at the repository
	// (itd-2609170822093401). Its gaps are advisory and never written under
	// --yes: a routing table decides which model every delegated step asks
	// for, so only an answered prompt accepts one.
	OracleRouting GapCategory = "oracle-routing"
)

type GuardHealth

type GuardHealth struct {
	// PluginRootResolved reports whether the plugin root was found at all. It
	// gates the two checks below: without it the manifest is never opened and the
	// binary is never looked for, so HookInstalled and BinaryReachable carry no
	// information. A report that folded "not checked" into "false" would accuse a
	// plugin install that may be perfectly armed — the state every dev build that
	// runs from source is in.
	PluginRootResolved bool `json:"plugin_root_resolved"`
	// HookInstalled reports whether the plugin's hook manifest declares the
	// pre-tool-use entry that runs the guard. Meaningful only when
	// PluginRootResolved.
	HookInstalled bool `json:"hook_installed"`
	// BinaryReachable reports whether the binary that entry invokes exists and
	// is executable. When it is not, the shim fails open on every command.
	// Meaningful only when PluginRootResolved.
	BinaryReachable bool `json:"binary_reachable"`
	// RegistryLoadable reports whether ANY hazard registry is armed — the
	// bundled defaults, with this repo's .abcd/guard.json merged in when it
	// loads. Since the fail-safe load (iss-2608261551087492) a broken repo file
	// no longer clears this: guard.Load falls back to the bundled defaults, so
	// false here means no registry at all — the only genuinely-unguarded
	// registry state, which the embedded defaults make unreachable in practice.
	// A broken repo layer over an armed bundle is RepoOverridesDropped instead.
	RegistryLoadable bool `json:"registry_loadable"`
	// RepoOverridesDropped reports the fail-safe degraded state: this repo's
	// .abcd/guard.json does not load, so its overrides are dropped while the
	// bundled hazards stay armed. Mild and expected — commands are still
	// checked — but never silent: the broken committed file needs fixing, and
	// hiding it would let a repo's own tightened hazards quietly lapse.
	RepoOverridesDropped bool `json:"repo_overrides_dropped,omitempty"`
	// Disabled reports a deliberately switched-off registry. It is not a fault —
	// .abcd/guard.json is the only route, and a switch-off takes effect only
	// once HEAD carries it (iss-147), so the change is a reviewed commit. A
	// disabled guard that looks armed is exactly the state this report exists
	// to prevent.
	Disabled bool `json:"disabled"`
	// Entries is how many hazards the loaded registry holds, so "loadable" is
	// backed by a number rather than a boolean nobody can check.
	Entries int `json:"entries"`
	// Detail is a one-line human reason when something needs attention; empty
	// when there is nothing to report. It can be non-empty while Healthy() is
	// true: dropped repo overrides leave commands checked but still need fixing.
	Detail string `json:"detail,omitempty"`
}

GuardHealth is the answer to "is the execution-time guard actually on?", split into the three things that can independently be false. It exists because a guard that fails open is indistinguishable from a guard that is working, from inside the session — so the state has to be visible from outside it too (itd-103 AC 1, spc-16 "Fail-open-loud and health").

func (GuardHealth) Healthy

func (g GuardHealth) Healthy() bool

Healthy reports whether commands in a session are actually being checked: the hook runs, the binary it calls exists, and the registry loads.

type HookState

type HookState string

HookState is what occupies one of the guard's two hook paths.

const (
	HookAbsent    HookState = "absent"
	HookInstalled HookState = "installed"
	// HookForeign is a hook abcd did not write. It is NOT a failure of the repo —
	// a maintainer's own pre-commit hook is legitimate — but it is a state in which
	// nothing checks the banlist, so it can never be reported as installed.
	HookForeign HookState = "foreign"
	// HookUnreadable is a path that exists and cannot be read as a hook (a symlink,
	// a directory, an oversize file). Like GuardHealth's unknown state it asserts
	// nothing it did not check.
	HookUnreadable HookState = "unreadable"
)

type InstallConfig

type InstallConfig struct {
	Visibility    string // private | public
	DocsTarget    string // claude_md | agents_md | both | skip
	OracleBackend string // host-delegated | native | cli | api | mcp
	ScanDeep      *bool  // nil = unset (gap not emitted)
}

InstallConfig is the four configuration values collected/loaded during install.

type InstallOptions

type InstallOptions struct {
	Adopt              *bool                // --adopt / --refuse-adopt / nil
	Yes                bool                 // approve every resolvable category
	ApprovedCategories map[GapCategory]bool // nil => interactive; explicit => partial subset
	ValueOverrides     map[string]string    // visibility/docs_target/oracle_backend/scan_deep
	// Dev requests the track-latest dogfood mode: the PATH entry becomes a shim
	// that rebuilds abcd from the source tip on every call and execs the fresh
	// binary (failing loudly on a broken build), instead of a symlink to the
	// pinned built binary. --dev.
	Dev bool
	// BinDir is an explicit directory for the PATH entry (--bin-dir), the only
	// way to reach a system-wide location. Empty means the default single-user
	// location (~/.local/bin), or an existing owned install adopted in place.
	// abcd NEVER escalates privileges: a BinDir it cannot write to is a loud
	// error, never a silent skip and never a re-run under sudo.
	BinDir string
	// Attribution opts this repo into the committed prepare-commit-msg prompt that
	// asks every commit to declare whether a tool assisted it. --attribution.
	//
	// Opt-IN, never a default: the hook stamps a convention onto every commit
	// message, which is an opinion a repo adopts rather than one abcd may assume.
	// The choice is PERSISTED (`attribution.hook` in config.json), so a later plain
	// install keeps the hook instead of making the maintainer re-pass the flag to
	// keep something they already chose.
	Attribution bool
	// AllowStaleBinary overrides the itd-111 staleness refusal: an install run
	// through a binary that is stale against its source tip, or whose vintage
	// cannot be determined, otherwise refuses before any write. The override is
	// the documented escape when a rebuild is not an option. --allow-stale-binary.
	AllowStaleBinary bool
	// ConfirmTool is asked, once per missing tool, whether to run the tool
	// registry's install step (itd-63). The front door supplies it: the CLI
	// asks at a terminal, or answers yes for a tool the person named with
	// --install-tool. Nil is a no for every tool, so a caller that asks nothing
	// installs nothing. The category approval never stands in for it.
	ConfirmTool tools.Confirm
	// ApproveDependency answers the dependency category's question yes without
	// asking it: the front door sets it when the person named a tool to
	// install (--install-tool), which is that answer given in advance. Every
	// other category is still asked, or pre-answered, as before.
	ApproveDependency bool
}

InstallOptions encodes the non-interactive prompt-protocol flags.

type InstallResult

type InstallResult struct {
	Status             string   `json:"status"` // already_up_to_date | clean | partial | aborted | refused
	Writes             []string `json:"writes"`
	Changes            []string `json:"changes,omitempty"`   // value overwrites an explicit override forced ("visibility: private -> public")
	Remaining          []string `json:"remaining"`           // required+resolvable gap ids left
	DeclinedCategories []string `json:"declined_categories"` // sorted category wire values
	// Notes carries an apply step's loud refusal — a thing abcd deliberately did
	// not do, and why. A refusal that only shows up as a still-open gap reads as a
	// silent failure, so the reason travels with the result.
	Notes []string `json:"notes,omitempty"`
	// OptionalSkipped names the optional gaps a --yes run deliberately did not
	// apply: the advisory git-identity pin, the status-line offer and the two
	// model-tier routing offers (which accept a table only on an answer). --yes
	// approves every resolvable CATEGORY, but it never writes the pin, because
	// the pin captures whatever git identity happens to be configured and an
	// unattended run would canonicalise a sandbox or agent identity; and it never
	// wires the status line, because that rewrites a harness-wide user setting
	// and takes element choices only a prompt can carry. The exclusion is
	// reported rather than assumed: a run that says "already up to date" while
	// leaving optional work on the table has to say so (iss-166).
	OptionalSkipped []string `json:"optional_skipped,omitempty"`
	// Headline says in one plain sentence what the run amounted to, and Summary
	// explains every reported item (each write, each declined kind of change,
	// the required work still outstanding, the optional steps left undone) as
	// what it is, why it matters and what, if anything, to do. They are for
	// the person who ran the install; the fields above stay the exact record
	// (iss-164).
	Headline string        `json:"headline"`
	Summary  []SummaryItem `json:"summary"`
	// contains filtered or unexported fields
}

InstallResult is the outcome of Install.

func Install

func Install(cwd string, opts InstallOptions, p Prompter) (InstallResult, error)

Install runs detect + apply over the approved categories. It is idempotent: a re-run with zero required+resolvable gaps writes nothing and reports "already_up_to_date".

type MarkerReceipt

type MarkerReceipt struct {
	Removed []string `json:"removed"` // relative filenames a block was stripped from
	Skipped []string `json:"skipped"` // relative filenames left untouched
}

MarkerReceipt records the per-target outcome of the uninstall marker removal.

type PromptHelp added in v0.11.1

type PromptHelp struct {
	Key     string       `json:"key"`
	About   string       `json:"about"`
	Choices []ChoiceHelp `json:"choices"`
}

PromptHelp is the canonical explanation of one value question the install asks through Prompter.Prompt: what is being decided, and what each answer means. It lives in core so every front door renders the same words and none has to invent them (iss-163) — a front door that describes an answer on its own can describe it wrongly, or circularly ("native — uses the native backend").

The prompt itself stays key, choices and default, so a scripted answer stream lines up with the questions as before; the help is looked up by the same key and rendered beside it.

func HelpFor added in v0.11.1

func HelpFor(key string) (PromptHelp, bool)

HelpFor returns the canonical help for the value question keyed key, and false for a key the install does not ask about, so a front door renders nothing rather than a guess.

func (PromptHelp) Meaning added in v0.11.1

func (h PromptHelp) Meaning(value string) string

Meaning returns what answering value means, or "" for a value the question does not offer.

type Prompter

type Prompter interface {
	// Confirm asks a yes/no question and returns the answer.
	Confirm(question string) bool
	// Prompt asks the user to pick one of choices, defaulting to def.
	Prompt(key string, choices []string, def string) string
}

Prompter is the interactive seam. The CLI supplies interactive impls; non-interactive modes supply refusing impls that auto-decline rather than block on stdin.

type PublicFamilyState

type PublicFamilyState string

PublicFamilyState classifies the public layer's config for detection.

const (
	PublicFamilyPresent PublicFamilyState = "present"
	// PublicFamilyAbsent is no docs-lint config at all — scaffolding writes one.
	PublicFamilyAbsent PublicFamilyState = "absent"
	// PublicFamilyUnusable is a config that parses to no usable banned_tokens array.
	// abcd must not rewrite it: the config gates CI and a contributor owns it.
	PublicFamilyUnusable PublicFamilyState = "unusable"
	// PublicFamilyUnreadable is an I/O fault — an oversize file, a symlink, a
	// permission error. It is reported apart from "unusable" because "add a
	// banned_tokens array" is not the fix for a file nobody can open.
	PublicFamilyUnreadable PublicFamilyState = "unreadable"
	// PublicFamilyIgnored is the contradiction: a readable family in a file git
	// ignores. The layer's whole claim is that it is committed and CI-enforced, and
	// an ignored config is enforced by nobody — most sharply under
	// `visibility: public`, where the abcd fence ignores the whole `.abcd/` namespace
	// and public exposure is the risk the layer exists for.
	PublicFamilyIgnored PublicFamilyState = "ignored"
)

type RefusingPrompter

type RefusingPrompter struct{}

RefusingPrompter auto-declines every confirm and returns the default for every prompt. It is the safe default for non-interactive callers.

func (RefusingPrompter) Confirm

func (RefusingPrompter) Confirm(string) bool

Confirm always declines.

func (RefusingPrompter) Prompt

func (RefusingPrompter) Prompt(_ string, _ []string, def string) string

Prompt always returns the supplied default.

type RemoteMergeHygiene added in v0.6.8

type RemoteMergeHygiene struct {
	DeleteBranchOnMerge *bool `json:"delete_branch_on_merge,omitempty"`
	AllowMergeCommit    *bool `json:"allow_merge_commit,omitempty"`
	AllowSquashMerge    *bool `json:"allow_squash_merge,omitempty"`
	AllowRebaseMerge    *bool `json:"allow_rebase_merge,omitempty"`
}

RemoteMergeHygiene is the repo-object settings that gate MERGE behaviour. abcd mirrors them and does not set them: they encode a maintainer's workflow, not a security posture, and a verb that drove them would be changing how the project merges on the strength of a default nobody chose.

They are here because they had no source of truth in the tree at all (iss-2608270512210664): the branch-ruleset mirror beside this one covers RULESETS, and these live behind the separate repository-object API — so every claim a contribution document made about them rested on a web console. Each is a pointer, omitted when the response does not carry it, because "false" and "the API did not say" are different facts.

type RemoteResult added in v0.6.8

type RemoteResult struct {
	// Repo is the owner/name the verb resolved from this repo's origin remote, and
	// the ONLY repository it acts on. It is reported so a caller can see which
	// repository a write reached before believing the rest of the result.
	Repo string `json:"repo"`
	// Status is one of: already_up_to_date | clean | pending | aborted | opted_out |
	// refused. "aborted" is a confirmation the caller declined; "refused" is a gate
	// abcd itself closed. They are reported apart because only one of them is a
	// decision the caller can revisit by answering differently.
	Status string `json:"status"`
	// Observed is the state GitHub reported before anything was changed.
	Observed RemoteSecurity `json:"observed"`
	// Merge is the merge-hygiene snapshot read in the same request: mirrored, never
	// driven.
	Merge RemoteMergeHygiene `json:"merge_hygiene"`
	// Desired is the state abcd holds this repo to.
	Desired RemoteSecurity `json:"desired"`
	// Changes are the toggles an apply changed — or, from the read, would change.
	Changes []string `json:"changes,omitempty"`
	// Writes are the tree paths this run wrote.
	Writes []string `json:"writes,omitempty"`
	// Notes carry what abcd deliberately did not do, and why. A refusal that shows
	// up only as an unchanged toggle reads as a silent failure, so the reason
	// travels with the result.
	Notes []string `json:"notes,omitempty"`
}

RemoteResult is the outcome of a remote config read or apply.

func RemoteApply added in v0.6.8

func RemoteApply(cwd string, p Prompter) (RemoteResult, error)

RemoteApply enables GitHub-native secret scanning and secret-scanning push protection on the managed repo this checkout points at, and mirrors the desired state into the tree so a later verify reads the same intent (itd-153).

It answers to adr-44 and invariant 10: a remote write happens only through a dedicated verb the user invokes AND CONFIRMS. Four gates stand before any change leaves the machine — the folder must be a repo abcd manages, the repository must be the one this checkout's own origin names, the config must not carry the opt-out, and the caller must say yes to the specific toggles named — and every one of them refuses or aborts rather than guesses. A nil prompter is the RefusingPrompter, so a caller that forgot the seam gets no write by omission.

The READ comes first and needs no ceremony (adr-44 rule 1: reading remote state is the default), which is also what lets the confirmation name exactly what would change. Then secret scanning, then push protection: GitHub refuses push protection on a repo whose secret scanning is off.

func RemoteRead added in v0.6.8

func RemoteRead(cwd string) (RemoteResult, error)

RemoteRead reports the managed repo's GitHub-native secret-scanning state and what an apply would change. It writes NOTHING — not to the remote, not to the tree — so the bare invocation of the verb it backs holds abcd's convention that looking is never acting.

type RemoteSecurity added in v0.6.8

type RemoteSecurity struct {
	SecretScanning string `json:"secret_scanning"`
	PushProtection string `json:"secret_scanning_push_protection"`
}

RemoteSecurity is the pair of GitHub-native secret-scanning toggles, as observed or as desired. A toggle GitHub did not report reads "unknown", never "disabled": the two demand opposite responses, and reporting an unread state as off would send an operator to enable something that may already be on.

type RepoIdentity

type RepoIdentity struct {
	Name    string `json:"name"`
	Github  string `json:"github"`
	RootSHA string `json:"root_sha"`
}

RepoIdentity is the deterministic identity of the repo under cwd.

type StatusLineReceipt added in v0.9.0

type StatusLineReceipt struct {
	Restored bool   `json:"restored"`
	Note     string `json:"note"`
}

StatusLineReceipt records the outcome of the uninstall status-line restore: whether the harness's status line was handed back to the command recorded before abcd took the row, and — restored or not — why. The note is rendered for a human and carries no home path.

type SummaryItem added in v0.11.1

type SummaryItem struct {
	What   string   `json:"what"`
	Why    string   `json:"why"`
	Action string   `json:"action"`
	Refs   []string `json:"refs,omitempty"`
}

SummaryItem explains one thing an install reports, for the person who ran it rather than for abcd's implementers (iss-164): what it is, why it matters for their work, and what, if anything, they should do. Refs names the exact entries of the result it explains (write paths, category names, step ids), so the plain words and the precise record can always be matched up.

type SymlinkReceipt

type SymlinkReceipt struct {
	Target  string `json:"target"`
	Removed bool   `json:"removed"`
	Note    string `json:"note"`
}

SymlinkReceipt records the outcome of the uninstall symlink removal.

type TerminalPrompter added in v0.11.1

type TerminalPrompter interface {
	Prompter
	AtTerminal() bool
}

TerminalPrompter is a Prompter that can say whether a person is answering at a terminal. A prompter that does not implement it is treated as having no one at a terminal, which is the fail-closed reading.

type UninstallReceipt

type UninstallReceipt struct {
	Marker     MarkerReceipt     `json:"marker"`
	Symlink    SymlinkReceipt    `json:"symlink"`
	StatusLine StatusLineReceipt `json:"status_line"`
}

UninstallReceipt is the outcome of Uninstall.

func Uninstall

func Uninstall(cwd, binDir string) (UninstallReceipt, error)

Uninstall removes the marker block and the owned PATH entry (the spc-35 owned copy plus its provenance record, or a legacy pinned symlink) only. It never mutates hooks.json or the .abcd/ namespace, and leaves the download cache to the harness's own uninstall.

binDir names the directory to look in, for the one case detection cannot derive: an install placed by `--bin-dir` in a directory that is not on PATH is invisible to a PATH scan, so uninstall would otherwise orphan it. Empty means the derived location — an abcd-owned entry anywhere on PATH, else the default.

type UpdateTarget

type UpdateTarget struct {
	Path         string           // first `abcd` on PATH ("" when absent)
	ResolvedPath string           // Path with symlinked ancestors/leaf resolved
	Kind         UpdateTargetKind //
	LaterOwned   string           // an abcd-owned entry shadowed behind Path ("" when none)
}

UpdateTarget names the first `abcd` PATH occupant — the binary that actually answers when the user types `abcd` — classified by the same ownership predicate detection and install use (one canonical predicate, iss-345).

func ResolveUpdateTarget

func ResolveUpdateTarget() UpdateTarget

ResolveUpdateTarget classifies the entry `abcd update` would act on. It walks PATH in order — the dispatch is keyed on what actually runs, not on one blessed location — and, when PATH holds nothing, reports the plugin root as the target when the running executable lives there (the plugin-invocation case still deserves the plugin-root refusal, not a "nothing installed" one).

type UpdateTargetKind

type UpdateTargetKind string

UpdateTargetKind classifies the PATH entry `abcd update` would act on. The update verb's dispatch (spc-32) keys on this: only a regular file whose provenance the verb can establish is ever swapped; every other shape is a named refusal, because another mechanism already owns it.

const (
	// UpdateTargetAbsent: no `abcd` anywhere on PATH.
	UpdateTargetAbsent UpdateTargetKind = "absent"
	// UpdateTargetPluginRoot: an owned symlink resolving into the current
	// plugin root — the plugin update owns that binary (itd-108 one-cut
	// coherence), never the update verb.
	UpdateTargetPluginRoot UpdateTargetKind = "plugin-root"
	// UpdateTargetDevShim: the track-latest dev shim — a chosen install mode.
	UpdateTargetDevShim UpdateTargetKind = "dev-shim"
	// UpdateTargetDangling: an abcd-owned entry whose binary is gone (the
	// iss-345 stranded shape included) — `ahoy install` is the heal.
	UpdateTargetDangling UpdateTargetKind = "owned-dangling"
	// UpdateTargetSuperseded: an owned symlink into a sibling plugin-cache
	// vintage the harness has moved past — the binary still exists, so it is
	// not stranded, but it answers an older release than the plugin now holds
	// (iss-2609161805447092). `ahoy install` is the heal.
	UpdateTargetSuperseded UpdateTargetKind = "owned-superseded"
	// UpdateTargetFile: a regular file. Ownership is decided by the update
	// verb's provenance check (digest against a published release), not here.
	UpdateTargetFile UpdateTargetKind = "file"
	// UpdateTargetForeign: a symlink abcd does not own, or an entry that
	// cannot be classified. Never touched.
	UpdateTargetForeign UpdateTargetKind = "foreign"
)

type VintageStatus

type VintageStatus struct {
	Mode     string         // install mode ("dev (tip build)" / "pinned" / "" / shadowed)
	Report   vintage.Report // outcome + current + expected
	Source   string         // reference name: "checkout tip" / "plugin manifest pin"; "" when the current vintage is undeterminable
	RepoRoot string         // the source checkout root, when the tip was the reference
}

VintageStatus is the assembled vintage picture for a repo: the install mode, the comparator's report, and the human name of the reference compared against. It is the single source the `version` and `ahoy` renders, the session-start notice, and the install refusal all consume — one comparison, many renders.

func Vintage

func Vintage(cwd string) VintageStatus

Vintage assembles the running binary's vintage picture for cwd. It resolves the install mode and the plugin root, reads the binary's own build vintage, and picks the applicable disk reference: the source checkout tip when cwd is abcd's own checkout (the dogfood case), otherwise the plugin-cache manifest pin. It never touches the network.

func (VintageStatus) DisplayVintage

func (v VintageStatus) DisplayVintage() string

DisplayVintage renders the vintage for a one-line surface: a short revision for a checkout-tip comparison, the version verbatim for a pinned one, and "unknown" when it could not be determined.

func (VintageStatus) Staleness

func (v VintageStatus) Staleness() string

Staleness renders the comparator verdict in the words a surface prints.

Jump to

Keyboard shortcuts

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