lint

package
v0.7.1 Latest Latest
Warning

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

Go to latest
Published: Sep 2, 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 lint is abcd's record-drift gate: it reads a JSON config and lints the markdown design record, returning findings. It performs no I/O beyond reading files under a caller-supplied repo root — no printing, no os.Exit — so it is fully testable and reusable across surfaces.

Index

Constants

View Source
const (
	// OutcomeAlive means the URL resolved to a live document.
	OutcomeAlive = "alive"
	// OutcomeBroken means it did not, and the gate must block on it.
	OutcomeBroken = "broken"
)

The outcomes a checked citation can have. Two values, not a free string: the gate branches on this, so an unrecognised outcome is a refusal at load.

View Source
const (
	// VerificationAutomatic means the refresh verb's fetcher established it.
	VerificationAutomatic = "automatic"
	// VerificationManual means a human confirmed it after the fetcher could not.
	VerificationManual = "manual"
)

The verification labels. This is the "automatic or manual" axis of AC 2 — WHO established the outcome, never how.

View Source
const BaselineSchemaVersion = 1

BaselineSchemaVersion is the only baseline schema this build understands. A document declaring anything else is refused rather than best-effort parsed: the gate must never enforce a record whose meaning it is guessing at.

View Source
const CitationNagWindowDays = 30

CitationNagWindowDays is how far ahead of the blocking threshold the release preflight starts naming entries. A month is enough notice to clear a manual queue before a release, and short enough that the nag still means something.

View Source
const DefaultBaselinePath = ".abcd/citations-baseline.json"

DefaultBaselinePath is the committed baseline's repo-relative home. It sits beside the other committed machine records under .abcd/ (docs-lint.json, record-lint.json, rules.json) rather than inside the development record, because it is configuration the gate reads on every commit, not design material.

Variables

This section is empty.

Functions

func DaysBetween

func DaysBetween(from, to time.Time) int

DaysBetween counts whole calendar days, both ends normalised to UTC midnight. Comparing instants would make the 180-day boundary depend on the hour the gate happened to run.

It is exported because the refresh verb decides which entries are stale enough to re-check and MUST get the same answer as the gate that will later warn on them. Two copies of this arithmetic is two chances for a boundary to drift, which would surface as a URL the verb thinks current and the gate thinks overdue, with nothing to say which is right.

func DeriveReleaseContentSha added in v0.6.8

func DeriveReleaseContentSha(root, released string) (string, error)

DeriveReleaseContentSha resolves the reviewed CONTENT commit a release's semantic gate must be armed against, by reading the RECEIPTS DIRECTORY of the released tree rather than by walking commit ancestry (HEAD^2^ / HEAD^).

The old HEAD-ancestry derivation is unsafe under a batched merge queue (iss-355): main advances one push per batch, so `github.sha` is the batch TIP, and `HEAD^2^` of that tip resolves the LAST-merged PR's pre-merge commit — an unrelated PR whenever the release roll is not the final entry in its batch. The `git merge-base --is-ancestor` guard passes for that unrelated commit (it is on the released lineage), and the run wedges after the immutable tag exactly as iss-326 records, by a route the pre-merge check cannot close because batch composition is decided by the queue.

The receipts name the commit they gate: a semantic-pass receipt lives at .abcd/work/reviews/<content-sha>/<gate>.json, so <content-sha> is carried by the directory name, present in the released tree, and independent of where the release roll sat in its batch. This derivation therefore enumerates the receipt subdirectories of the released tree, keeps those whose name is a commit that is an ancestor of `released`, and returns the NEAREST such ancestor — the content commit of THIS release, since every earlier release's receipts sit further back on the shared history.

It fails closed: an unreadable listing, no receipt directory on the released lineage, or two equidistant candidates all return an error rather than a guess, so an armed gate never resolves to the wrong commit or to nothing.

func HandleLess

func HandleLess(a, b string) bool

HandleLess orders two record handles by store prefix, then NUMERICALLY — so adr-9 precedes adr-10, which a plain string sort gets backwards and which a reader of any rendered list notices immediately.

It is exported alongside the graph because every consumer that renders a record list needs exactly this order, and the obvious second implementation is a plain string sort that looks right until the store passes nine records.

func SaveBaseline

func SaveBaseline(path string, b Baseline) error

SaveBaseline validates and writes a baseline atomically. Validation runs on the way OUT as well as in, so a producer bug can never commit a record the gate would then refuse to load.

func ValidateBannedToken

func ValidateBannedToken(t BannedToken) error

ValidateBannedToken reports whether one banned-token entry is loadable by THIS linter — the engine that enforces the public banlist layer. It exists so a writer of that config (`abcd banlist add --public`) validates through the same compile the gate itself performs, on the exact string it is about to store, rather than through a second reading that could accept an entry the gate then refuses. The error is returned for the caller to discard or wrap: it quotes the expression, which is safe for a public pattern and never safe for a private one.

Types

type BannedToken

type BannedToken struct {
	ID       string `json:"id"`
	Pattern  string `json:"pattern"`
	Message  string `json:"message"`
	Severity string `json:"severity"`
	// Successor is the machine-readable old->new mapping: what to use instead of
	// the banned token. It is REQUIRED (a ban with no successor left its
	// replacement in prose only, iss-51) and is auto-cited in the finding message.
	Successor string `json:"successor"`
	// AllowContext lists regexps that, if any matches the same line, suppress
	// the finding (the token is legitimate in that context). It is REQUIRED to be
	// non-empty: every ban must declare where its token is legitimately allowed.
	AllowContext []string `json:"allow_context"`
	// SkipCodeFences omits fenced-code lines from scanning. A nil pointer means
	// the default (true); set false to also scan inside fences.
	SkipCodeFences *bool `json:"skip_code_fences"`
}

BannedToken is one entry in the banned_tokens family (check A).

type Baseline

type Baseline struct {
	// SchemaVersion pins the document's shape. Required.
	SchemaVersion int `json:"schema_version"`
	// Entries is keyed by the cited URL exactly as it appears in the docs.
	Entries map[string]BaselineEntry `json:"entries"`
}

Baseline is the committed citation record: one entry per cited URL.

func LoadBaseline

func LoadBaseline(path string) (Baseline, error)

LoadBaseline reads, decodes, and validates a committed baseline.

A missing file is returned as the underlying os.ErrNotExist, so the caller can distinguish "this repo has no baseline yet" (a state the gate reports as one finding) from "this repo has a corrupt baseline" (a refusal).

type BaselineEntry

type BaselineEntry struct {
	// URL optionally restates the map key. It is redundant by design — a
	// committed record reads better in a diff when each entry names itself — and
	// is validated to AGREE with its key rather than being a second source of
	// truth. Empty is fine; disagreeing is a refusal.
	URL string `json:"url,omitempty"`
	// FinalURL is the address the citation actually resolved to after redirects.
	// When it differs from the cited URL, the docs are citing a stale address and
	// the gate says so.
	FinalURL string `json:"final_url"`
	// LastChecked is when the outcome was established. This is THE staleness
	// clock — the same clock for automatic and manual entries alike, so a human
	// verification buys no exemption from ageing (AC 3).
	LastChecked string `json:"last_checked"`
	// Outcome is OutcomeAlive or OutcomeBroken.
	Outcome string `json:"outcome"`
	// Verification is VerificationAutomatic or VerificationManual — who
	// established the outcome.
	Verification string `json:"verification"`
	// VerifiedOn is the date that verification was recorded.
	VerifiedOn string `json:"verified_on"`
}

BaselineEntry is one URL's record.

Every field here answers "what is true about this link", and none answers "how did we find out". That omission is the schema's contract (AC 2), pinned by TestBaselineHasNoMethodFieldByConstruction.

func (BaselineEntry) Checked

func (e BaselineEntry) Checked() (time.Time, error)

Checked parses the entry's staleness clock.

type BaselineError

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

BaselineError is a malformed-baseline refusal. It is a distinct type so a caller can tell a bad record from an I/O fault without string matching.

func (*BaselineError) Error

func (e *BaselineError) Error() string

type CitationPolicySet

type CitationPolicySet struct {
	// BaselineRel is repo-relative — the only form that may reach a message or
	// machine output, so no developer-identity path is ever rendered.
	BaselineRel string
	// BaselinePath is absolute, for reading and writing.
	BaselinePath string
	WarnDays     int
	BlockDays    int
}

CitationPolicySet is the resolved citation-baseline policy: where the record lives, in both the form messages use and the form I/O uses, and the two staleness thresholds.

func CitationPolicy

func CitationPolicy(cfg Config, repoRoot string) (CitationPolicySet, error)

CitationPolicy resolves the citation-baseline settings a repo's config declares, filling in spc-17's defaults for anything it leaves unset.

It exists so the refresh verb and the gate read the SAME policy: the verb decides which entries are stale enough to re-check from the very number the lint will later warn on, rather than from a second copy of 180 that drifts.

It is also the containment choke point for the one config value that steers a WRITE. `.abcd/docs-lint.json` is a committed file, so a contributor controls it; `abcd docs cite refresh` then hands `baseline` to SaveBaseline, which MkdirAll's the parent. Without the check below, a `baseline` of "../../../etc/x.json" turns a routine refresh into an arbitrary-file-write primitive that escapes the repository. Every reader and both writers resolve the path through here, so one check covers all four.

type CitationSite

type CitationSite struct {
	File string `json:"file"`
	Line int    `json:"line"`
}

CitationSite is one place a URL is cited: a repo-relative page and a 1-based line. A URL cited from several pages carries one site per occurrence, so the manual queue can tell the maintainer where to look.

type CitationSummary

type CitationSummary struct {
	// Present reports whether a baseline file exists at all.
	Present bool `json:"present"`
	// Cited is how many distinct URLs the documentation cites.
	Cited int `json:"cited"`
	// Recorded is how many of those have a baseline entry; Missing is the rest.
	Recorded int `json:"recorded"`
	Missing  int `json:"missing"`
	// Broken counts entries recorded as broken.
	Broken int `json:"broken"`
	// Manual counts entries a human established. They age on the same clock as
	// automatic ones, so this is reported, never subtracted from the stale count.
	Manual int `json:"manual"`
	// Stale counts entries past the warn threshold (which includes every
	// approaching and overdue one); Overdue counts those past the blocking one;
	// Approaching counts the band just short of blocking.
	Stale       int `json:"stale"`
	Overdue     int `json:"overdue"`
	Approaching int `json:"approaching"`
	// OldestChecked is the earliest last_checked date among cited entries.
	OldestChecked string `json:"oldest_checked,omitempty"`
	// OverdueURLs and ApproachingURLs name what a nag must list, sorted.
	OverdueURLs     []string `json:"overdue_urls,omitempty"`
	ApproachingURLs []string `json:"approaching_urls,omitempty"`
}

CitationSummary is the committed baseline's state against the repo's current citations. Every count is over the CITED set: an entry for a URL the docs no longer cite is not a health problem, it is something the next refresh drops.

func CitationAgeSummary

func CitationAgeSummary(cfg Config, repoRoot string) (CitationSummary, error)

CitationAgeSummary grades the baseline against the wall clock.

func CitationAgeSummaryAt

func CitationAgeSummaryAt(cfg Config, repoRoot string, now time.Time) (CitationSummary, error)

CitationAgeSummaryAt is CitationAgeSummary with the clock supplied, so the band boundaries are testable exactly.

A missing baseline is reported, not an error: a repo that has not refreshed yet is a state a status line must be able to describe. A MALFORMED one is still an error — a record the gate cannot read is not a health report.

func (CitationSummary) Healthy

func (s CitationSummary) Healthy() bool

Healthy reports whether the baseline needs no attention: every citation has a current, unbroken receipt.

type CitedURL

type CitedURL struct {
	URL   string         `json:"url"`
	Sites []CitationSite `json:"sites"`
}

CitedURL is one distinct cited address and everywhere it is cited.

func CollectCitedURLs

func CollectCitedURLs(cfg Config, repoRoot string) ([]CitedURL, error)

CollectCitedURLs walks cfg.Roots and returns the repo's distinct cited URLs, sorted by address so a refresh run and its baseline diff are deterministic.

"Cited" means what the lint means by it: a URL on a footnote-definition line (including its wrapped continuation lines), never one in body prose. A missing root is skipped rather than an error, matching Lint.

type Config

type Config struct {
	// Roots are repo-relative directories the lint walks (markdown record).
	Roots []string `json:"roots"`
	// BannedTokens are line-level substring/regex bans (check family A).
	BannedTokens []BannedToken `json:"banned_tokens"`
	// Rules holds the per-check configuration for the remaining families,
	// keyed by rule id (no_git_metadata, links_resolve, ...).
	Rules map[string]RuleConfig `json:"rules"`
	// ExemptPaths are repo-relative path prefixes whose files skip the
	// content-AUTHORING checks (banned_tokens, persona_registry) — the historical,
	// non-forward-looking part of the record, which is excused from how it is
	// written but never from being well-formed. Both intent-tree checks
	// (intent_lifecycle, intent_impact_valid — they share one scan) stay universal
	// (iss-39); the spec-store checks (spec_lifecycle, spec_id_unique) still skip an
	// exempt file. record_schema is cross-store and never consults this at all.
	ExemptPaths []string `json:"exempt_paths"`
	// ExemptIfStatus lists leading-frontmatter status: values that likewise
	// exempt a file from the content-authoring checks (e.g. superseded records).
	ExemptIfStatus []string `json:"exempt_if_status"`
}

Config is the on-disk record-lint configuration (.abcd/record-lint.json).

func ArmAgentDiff added in v0.6.8

func ArmAgentDiff(cfg Config, diffRange string) Config

ArmAgentDiff returns cfg with agent_contract's changelog sub-check pointed at a git revision range. It is the same arming shape as ArmReceiptGate and for the same reason: the sub-check asks whether a CHANGE announced itself, so it needs a diff, and the caller (a CI invocation, `record-lint -agent-diff`) is the one that knows which. It is deliberately NOT a config key — a range read out of the committed file would let a committer point the gate at an empty diff.

Arming only WIDENS the rule: an empty range leaves the changelog sub-check a no-op while the frontmatter and canary sub-checks run either way. The rule's own Enabled flag is untouched, so this cannot switch a disabled rule on. The input cfg is not mutated (the Rules map is copied).

func ArmCitationOverdue

func ArmCitationOverdue(cfg Config) Config

ArmCitationOverdue returns cfg with the citation staleness blocker armed: an entry past the block threshold becomes a BLOCKER finding rather than the warn the commit gate emits.

It follows ArmReceiptGate's shape deliberately. The promotion is the CALLER's decision — a release gate, not the in-tree config — so a repo cannot defang its own release by writing "overdue_severity": "warn" into a committed file, and an ordinary commit is never calendar-blocked (spc-17). What arming does NOT do is enable a rule the repo turned off: promoting a severity is the release gate's business, adopting a rule is the repo's.

func ArmReceiptGate

func ArmReceiptGate(cfg Config, commit string, requiredGates []string) Config

ArmReceiptGate returns cfg with the receipt_gate rule armed for a release: it is enabled, pointed at the target commit, and its required-gates list is set to the caller's list verbatim. This is how a release runs the gate: the CALLER (a CI workflow) supplies the arming, so the decision to gate, the target commit, and the required-gates list are trust-rooted to the workflow rather than the in-tree, committer-editable config (phase-2 review Finding 2). The caller's list is authoritative even when empty: an empty list clears the gates so checkReceiptGate fails closed, rather than inheriting a config a committer could have shrunk (an argless arming must not silently pick up in-tree gates). The input cfg is not mutated (the Rules map is copied). Other rules are unchanged; the deterministic gates still run alongside.

func LoadConfig

func LoadConfig(path string) (Config, error)

LoadConfig reads and decodes a record-lint config file. The config is a trust boundary: it is a committed, cross-repo-clonable file (a hostile clone can commit .abcd/docs-lint.json as a git mode-120000 symlink), and the read is reachable automatically through the session hooks (ahoy.Detect), so it is guarded exactly like its .abcd/*.json siblings guard.Load and rules.Load — a symlinked config directory or leaf is refused, a FIFO/device leaf returns immediately instead of hanging the open, and an over-cap file is rejected rather than read into an OOM. Error strings stay path-free (iss-29); the os.IsNotExist branch is preserved so callers that default an absent config still work.

func LoadConfigInRoot added in v0.6.8

func LoadConfigInRoot(root *os.Root, rel string) (Config, error)

LoadConfigInRoot reads and validates a lint config confined to root: every path component is resolved inside root, so a symlinked ancestor cannot walk the read out of the tree, and the leaf is size- and regular-file-guarded the same way LoadConfig's is. Callers that already hold an os.Root for the repo (the site build, for one) use this so their config read matches the ancestor-symlink containment their other reads have, rather than re-opening by absolute path.

type ContestedItem added in v0.7.0

type ContestedItem struct {
	Item string `json:"item"`
	Run  string `json:"run"`
	Path string `json:"path"`
	// Standing is every standing id, sorted — the whole fault, not a sample.
	Standing []string `json:"standing"`
}

ContestedItem is one item with more than one standing answer.

type Finding

type Finding struct {
	File     string
	Line     int
	RuleID   string
	Severity string
	Message  string
}

Finding is one lint violation. File is repo-relative; Line is 1-based (0 when the finding is not tied to a specific line, e.g. a missing directory README).

func Lint

func Lint(cfg Config, repoRoot string) ([]Finding, error)

Lint runs every enabled check family against the record under repoRoot and returns the findings sorted deterministically. An error is returned only for malformed configuration (e.g. an uncompilable regexp, or a persona_registry roster that is missing, unparsable, or empty); a walkable-but-missing root is skipped, not an error.

func LintAt

func LintAt(cfg Config, repoRoot string, now time.Time) ([]Finding, error)

LintAt is Lint with the clock supplied by the caller. Only the citation baseline's staleness arithmetic reads it, but it is a parameter rather than a wall-clock read inside the check so the 180- and 365-day boundaries are testable exactly, and so a gate's verdict is a function of its inputs.

type IndexSpec

type IndexSpec struct {
	// ID names the region: the document fences it with `<!-- index: <id> -->`
	// and `<!-- /index -->`.
	ID string `json:"id"`
	// Doc is the enumerating document, repo-relative.
	Doc string `json:"doc"`
	// Dir is the enumerated directory, repo-relative. In absent mode it is the
	// base each listed path resolves against.
	Dir string `json:"dir"`
	// Entry is the regexp a backticked token in the region must match to count as
	// an entry. It is what keeps the rule off the prose around the list: a token
	// the pattern does not describe (a flag, a tool name) is not an entry.
	Entry string `json:"entry"`
	// DirEntry is the mirror of Entry on the directory side: the regexp a file's
	// stem must match to be an entry, reduced to submatch 1 when the pattern has a
	// group. It is what lets a document enumerate records by IDENTITY rather than
	// by filename — `itd-8` for `itd-8-with-code-bundling.md` — without a second
	// rule: without it the two sides can only agree when the document transcribes
	// whole slugs, which is a listing nobody writes by hand. Empty compares whole
	// stems.
	DirEntry string `json:"dir_entry"`
	// Suffix is the file extension an exact index enumerates (".md" lists file
	// stems); empty enumerates the directory's immediate subdirectories.
	Suffix string `json:"suffix"`
	// Mode is "exact" (default — the listing and the directory must agree) or
	// "absent" (every listed path must NOT exist, the planned-seams shape).
	Mode string `json:"mode"`
}

IndexSpec is one index_drift pair — a hand-written enumeration of a directory's contents, and the directory it must agree with.

type IntentLink struct {
	// ID is the intent id (itd-N), taken from the frontmatter when well-formed
	// and from the filename otherwise.
	ID string
	// Bucket is the lifecycle directory holding it (drafts, planned, shipped,
	// disciplines, superseded), or "" for a file outside a known bucket.
	Bucket string
	// Path is the record's repo-relative path.
	Path string
	// SpecID is the raw spec_id frontmatter value (which may be a YAML null).
	SpecID string
}

IntentLink is one intent record as the link index sees it: which bucket holds it (the lifecycle state, because directory-as-truth) and which spec it names.

type OpenHold added in v0.7.0

type OpenHold struct {
	Item          string `json:"item"`
	Disposition   string `json:"disposition"`
	ExitCondition string `json:"exit_condition"`
	Path          string `json:"path"`
}

OpenHold is one standing `held` disposition, rendered with the exit condition that is the only thing distinguishing a hold from a parking space.

type OutstandingItem added in v0.7.0

type OutstandingItem struct {
	Item string `json:"item"`
	Run  string `json:"run"`
	Path string `json:"path"`
}

OutstandingItem is one reading item nobody has answered.

type OutstandingReadings added in v0.7.0

type OutstandingReadings struct {
	Undispositioned []OutstandingItem `json:"undispositioned"`
	// Unadmitted names widening PROPOSALS that are neither admitted nor declined
	// (spc-67). The widening position's answer set is wider than a disposition —
	// an admission record carrying its grounds answers a proposal, and so does a
	// decline — so the same question needs one more branch here rather than a
	// parallel rule beside it: two rules asking one question diverge, and the
	// first divergence between them is silent.
	//
	// Acceptance at the widening position IS admission, so an accepted proposal
	// with no admission record is an admission whose grounds were never written.
	// That is the case this leg exists for: uniform adoption of everything a
	// reading proposes is equally consistent with careful judgement and with
	// abdication, and only the grounds tell the two apart.
	Unadmitted []OutstandingItem `json:"unadmitted,omitempty"`
	OpenHolds  []OpenHold        `json:"open_holds"`
	// Unsafe names the repo-relative directories the walk declined to enter
	// because they are not real directories. core/capture REFUSES these outright,
	// because its read is followed by a write; this walk is genuinely read-only,
	// so it declines and SAYS SO instead. Going quiet is the thing it must not do:
	// a tree nobody walked looks exactly like a tree with nothing in it, and "no
	// outstanding items" is the one answer this report must never give by
	// accident.
	Unsafe []UnsafePath `json:"unsafe,omitempty"`
	// Cyclic names items whose dispositions supersede one another, so every
	// answer is retired and none stands. It is a ledger fault, not an unanswered
	// item: reporting it as outstanding would be a confident wrong statement about
	// an item that has been answered twice, and would invite exactly the fresh
	// uncited answer the write path refuses.
	Cyclic []OutstandingItem `json:"cyclic,omitempty"`
	// Contested names items on which more than one disposition stands. It is not
	// an exotic state: two branches each answer an item, both merge without
	// conflict, and neither cites the other. Picking the first by id resolved that
	// silently — an `accepted` sorting first hid a `held` and its exit condition,
	// and no line said two answers stood. The report names every standing id and
	// resolves nothing, because which answer is in force is the researcher's
	// judgement and there is nothing here to make it from.
	Contested []ContestedItem `json:"contested,omitempty"`
	// Unreadable names items whose SOLE standing answer is a record no reader can
	// read. Such a record has no state, so it matched none of the report's cases
	// and the item simply vanished from the board — and an item whose only answer
	// is unreadable is the case most in need of a line, not least.
	Unreadable []UnreadableAnswer `json:"unreadable,omitempty"`
}

OutstandingReadings is the whole report, ordered deterministically.

func ReadReadingOutstanding added in v0.7.0

func ReadReadingOutstanding(repoRoot, issuesDir string) (OutstandingReadings, error)

ReadReadingOutstanding builds the report from the ledger at issuesDir (repo-relative). It is exported because the report has two surfaces — the lint findings and the bare capture status board — and two implementations of one question would be two answers to it. An absent readings tree is not an error: a repository that has commissioned no reading is in a state, not a fault.

func (OutstandingReadings) Empty added in v0.7.0

func (r OutstandingReadings) Empty() bool

Empty reports whether there is nothing outstanding — the ordinary state of a repository that has commissioned no reading, and the state a surface renders as silence rather than as a heading with nothing under it.

type RecordEdge

type RecordEdge struct {
	From  string `json:"from"`
	To    string `json:"to"`
	Field string `json:"field"`
}

RecordEdge is one typed reference: the record that declares it, the handle it names, and the frontmatter field it was read out of. The field is kept rather than collapsed into a relation name because the same relation is spelled from both ends (an intent's `spec_id` and a spec's `intent` are one link) and only the consumer knows whether it wants them folded.

type RecordGraph

type RecordGraph struct {
	Nodes    []RecordNode `json:"nodes"`
	Edges    []RecordEdge `json:"edges"`
	Dangling []RecordEdge `json:"dangling"`
	// Retired are the ids some record declares it superseded, bounded by each
	// store's allocation high-water mark exactly as the rule bounds them. The
	// ADR lifecycle prunes a superseded file and keeps the trace in its
	// successor's `supersedes`, so a handle naming a retired id is accounted for
	// even though no file answers to it — and a consumer counting unresolved
	// references needs that distinction to avoid reporting the record's own
	// bookkeeping as breakage.
	Retired []string `json:"retired"`
}

RecordGraph is the whole corpus: every record, every typed reference that resolves to one, and every reference that names a record no file carries.

func LoadRecordGraph

func LoadRecordGraph(cfg Config, repoRoot string) (RecordGraph, error)

LoadRecordGraph reads every configured record store once and returns the corpus as a graph. It is the record_schema rule's scan, exported: cfg is the same lint configuration the rule runs from, and a store the configuration does not name (or whose directory is absent) contributes nothing, exactly as it contributes no findings.

The result is fully ordered — nodes by store then id number, edges by their two endpoints and field — so a caller that serialises it gets the same bytes from the same tree.

type RecordNode

type RecordNode struct {
	// ID is the record's prose handle (adr-47, itd-135, spc-38, iss-100).
	ID string `json:"id"`
	// Type is the store's name: adr, intent, spec, issue.
	Type string `json:"type"`
	// Lifecycle is the bucket directory the record sits in (drafts, planned,
	// shipped, open, resolved …). It is empty for a flat store, whose records
	// carry their state in frontmatter rather than in a directory.
	Lifecycle string `json:"lifecycle"`
	// Title is the record's H1, or its first body line where the store's records
	// carry no heading, or the handle where the file is empty.
	Title string `json:"title"`
	// Path is the record file, repo-relative and slash-separated.
	Path string `json:"path"`
	// Date is the frontmatter `date` where the record carries one, else empty.
	// A record without one is dated from git by the consumer, not here.
	Date string `json:"date,omitempty"`
	// Status, Kind and Severity are the frontmatter fields the stores use to
	// grade a record, carried where present and empty where not.
	Status   string `json:"status,omitempty"`
	Kind     string `json:"kind,omitempty"`
	Severity string `json:"severity,omitempty"`
}

RecordNode is one record in the corpus.

type RuleConfig

type RuleConfig struct {
	Enabled  bool   `json:"enabled"`
	Severity string `json:"severity"`
	// Fields is the no_git_metadata banned frontmatter key list.
	Fields []string `json:"fields"`
	// Exempt is the directory_coverage glob allowlist.
	Exempt []string `json:"exempt"`
	// IntentsDir is the intents subdirectory (relative to a root) read by the
	// intent-tree rules, intent_lifecycle and intent_impact_valid. Rules that name
	// the same directory share one scan of it. spec_lifecycle also reads it to
	// resolve the intent corpus its specs link to.
	IntentsDir string `json:"intents_dir"`
	// SpecsDir is the spec_lifecycle specs subdirectory (relative to a root),
	// mirroring IntentsDir. Default "specs".
	SpecsDir string `json:"specs_dir"`
	// IssuesDir is the issue-ledger root (repo-relative) read by the ledger rules,
	// issue_id_unique and issue_impact_valid; it holds the open/, resolved/, and
	// wontfix/ status directories. Default .abcd/work/issues. It lies outside Roots
	// — the rules read the ledger and run once, sharing one scan of it.
	// reading_outstanding reads the same root's SIBLING families (readings/,
	// dispositions/), which is why they are named relative to it rather than
	// configured twice.
	IssuesDir string `json:"issues_dir"`
	// Allowlist is the stray_root_docs permitted basename-stem list (upper-cased,
	// extension-stripped) for top-level markdown files.
	Allowlist []string `json:"allowlist"`
	// Registry is a rule's registry file, repo-relative. For persona_registry it
	// is the persona roster (.abcd/development/personas.json); for
	// surface_coverage it is the brief surface table
	// (.abcd/development/brief/04-surfaces/README.md).
	Registry string `json:"registry"`
	// CommandsDir is the surface_coverage plugin-command directory (commands);
	// each *.md file (README and BareCommand excepted) is a shipped command
	// surface. It lies outside Roots — the rule reads the surface tree and
	// cross-checks the brief. The directory is flat: a harness maps a
	// subdirectory of it to an extra namespace segment, so a file one level down
	// registers as /<plugin>:<dir>:<verb> rather than the documented
	// /<plugin>:<verb>.
	CommandsDir string `json:"commands_dir"`
	// BareCommand is the CommandsDir file stem that backs the plugin's BARE
	// top-level command rather than a /<plugin>:<verb> surface — for abcd, the
	// `abcd.md` whose registry row is the bare `/abcd`. It is excluded from the
	// command-surface set the way README is, because the registry names it
	// without a sub-verb and matching it by name would demand a row that cannot
	// exist. Empty means the plugin has no such file.
	BareCommand string `json:"bare_command"`
	// SkillsDir is the surface_coverage skills directory (skills); each immediate
	// subdirectory is a shipped skill surface. Also outside Roots.
	SkillsDir string `json:"skills_dir"`
	// Snapshot is the committed command-tree snapshot surface_coverage's
	// sub-verb pass checks table rows against (spc-27), repo-relative — for
	// abcd, .abcd/development/release/surface.json, whose bytes the surface
	// drift test keeps equal to the live cobra tree. Empty leaves the sub-verb
	// grain unarmed (the pre-spc-27 surface-grain check only).
	Snapshot string `json:"snapshot"`
	// HostDelegated lists surfaces whose workflow runs in the host agent with
	// no Go verb (consult, ingest, prepare-this-repo): their sub-verb tables
	// are format-checked only, never compared to the cobra tree. Explicit
	// config, never a hard-coded skip — an unlisted surface gets the full
	// comparison.
	HostDelegated []string `json:"host_delegated"`
	// OperatorInternal lists top-level verbs absent from the surface registry
	// by design (spec, rules, hook, completion — operator plumbing, not
	// product surface): the sub-verb reverse sweep does not demand a surface
	// file for them. Explicit config, same rationale as HostDelegated.
	OperatorInternal []string `json:"operator_internal"`
	// Target is the context_status_free single-file target, repo-relative
	// (.abcd/work/CONTEXT.md). The rule runs even though the target lies outside
	// Roots; a missing target is not an error.
	Target string `json:"target"`
	// Patterns is the context_status_free line-match regexp list; when empty the
	// rule falls back to contextStatusDefaultPatterns.
	Patterns []string `json:"patterns"`
	// Section is the context_citation_currency heading matcher: the rule reads only
	// the section of Target whose heading matches (the sharp-edges list), because a
	// citation to a terminal record is legitimate everywhere else. Empty falls back
	// to defaultContextSection.
	Section string `json:"section"`
	// ReceiptsDir is the receipt_gate directory of sha-keyed semantic-pass
	// receipts (VSA-shaped JSON), repo-relative (default .abcd/work/reviews).
	// Outside Roots.
	ReceiptsDir string `json:"receipts_dir"`
	// RequiredGates lists the semantic gates that must each have a PROMOTE receipt
	// for the target commit before a release (e.g. docs-currency-reviewer,
	// iss35-brief-surface-crosscheck).
	RequiredGates []string `json:"required_gates"`
	// Commit is the receipt_gate target commit sha whose receipts are verified.
	// Release-time input (release.yml supplies the tagged commit); empty while the
	// rule is disabled for ordinary development.
	Commit string `json:"commit"`
	// Runbook is the gate_lockstep runbook path (its numbered "Deterministic
	// gates" list), repo-relative.
	Runbook string `json:"runbook"`
	// Workflow is the gate_lockstep CI workflow path — the source of truth for the
	// deterministic gate list, repo-relative.
	Workflow string `json:"workflow"`
	// Job is the gate_lockstep workflow job whose step names are the gate list.
	Job string `json:"job"`
	// IgnoreSteps are workflow step names that are setup, not gates, and so are
	// excluded from the lockstep comparison.
	IgnoreSteps []string `json:"ignore_steps"`
	// MinGates is the gate_lockstep non-empty floor: each side must parse at least
	// this many gates or the rule fails closed (an under-count means the parser or
	// a heading/job rename silently dropped gates). It is the safety net that makes
	// the hand-parse fail-closed. Enforced as at least 1 when the rule is enabled.
	MinGates int `json:"min_gates"`
	// GlossaryDir is the forbidden_synonyms (GL002) glossary directory, repo-relative
	// (default .abcd/development/brief/glossary). The rule walks it for term files and
	// reads each term's forbidden_synonyms frontmatter list — the glossary is the
	// single source of truth for what a forbidden synonym is.
	GlossaryDir string `json:"glossary_dir"`
	// Enforce is the forbidden_synonyms subset that GL002 mechanically gates. Each
	// entry MUST be declared as a forbidden_synonym by some glossary term (the rule
	// errors otherwise, so the config can never gate a word the glossary does not
	// forbid). Enforcement is a deliberate subset because most forbidden synonyms
	// ("user", "release", "project", "feature", ...) are common English words whose
	// live-prose false-positive rate blows the detector's budget; "epic" is the
	// mechanically-clean member (itd-43). Promotion path: add a synonym here once the
	// corpus is swept clean of its non-substituting uses.
	Enforce []string `json:"enforce"`
	// ExemptPrefixes are repo-relative path prefixes whose files GL002 skips — the
	// historical, git-tracked records the rename intent (itd-43 AC1) exempts:
	// research/, decisions/ (dated ADRs), plans/ (dated), shipped/superseded intents,
	// the issue ledger, and review records. The glossary directory itself is always
	// exempt (a term file names its own forbidden synonyms legitimately).
	ExemptPrefixes []string `json:"exempt_prefixes"`
	// AllowContext lists regexps that, if any matches a line, suppress every GL002
	// finding on that line — the legitimate-mention escape (naming the old token in an
	// external reference like `epic-review`, or the rename itself `epic->spec`).
	AllowContext []string `json:"allow_context"`
	// CrosswalkHeading is the citation_crosswalk_rows heading matcher: a table is
	// judged a crosswalk only when its nearest preceding heading matches this
	// regexp. Default defaultCrosswalkHeading. Keying on the heading rather than on
	// table shape is what keeps the rule off every ordinary table in the corpus.
	CrosswalkHeading string `json:"crosswalk_heading"`
	// RefusedDomains is the citation_source_policy list of aggregator domains a
	// citation may not point at. Matching is host-normalised (case-folded, www.
	// dropped) and covers subdomains. It ships EMPTY: naming a domain is a
	// project's editorial policy, never something the gate invents for it.
	RefusedDomains []string `json:"refused_domains"`
	// Baseline is the citation_baseline record's repo-relative path. Default
	// DefaultBaselinePath.
	Baseline string `json:"baseline"`
	// WarnAfterDays is the citation_baseline staleness warn threshold in days
	// (spc-17: 180). Zero means the default.
	WarnAfterDays int `json:"warn_after_days"`
	// BlockAfterDays is the age at which an entry becomes OVERDUE and is reported
	// under the citation_baseline_overdue rule id (spc-17: 365). Zero means the
	// default.
	BlockAfterDays int `json:"block_after_days"`
	// OverdueSeverity is the severity of a citation_baseline_overdue finding. It
	// defaults to warn because the COMMIT gate never calendar-blocks (spc-17);
	// the release gate is what promotes it to a blocker.
	OverdueSeverity string `json:"overdue_severity"`
	// RecordStores are the record_schema stores: the repo-relative directory of
	// each identified record store, keyed by id prefix (adr, itd, spc, iss). The
	// rule reasons ACROSS the stores, which straddle Roots (the issue ledger is
	// working-tier, the rest is the design record), so each is named repo-relative
	// here. An unnamed or absent store contributes nothing. Only the LOCATIONS are
	// configurable — which lifecycle buckets each store declares is the record's
	// schema and lives in code, so a config can never quietly add or hide one.
	RecordStores map[string]string `json:"record_stores"`
	// Indexes are the index_drift pairs: each names a marked region in a document
	// and the directory that region enumerates. The rule reads documents outside
	// Roots (a package or command README lives beside its code), so the pairs are
	// declared here rather than discovered by the walk.
	Indexes []IndexSpec `json:"indexes"`
	// Changelog is the delivery_state changelog, repo-relative. Default
	// "CHANGELOG.md". It sits at the repo root, outside Roots.
	Changelog string `json:"changelog"`
	// IntentsRoot is the delivery_state intents store, repo-relative — the whole
	// store, not a subdirectory of a root, because the rule resolves a cited id to
	// the lifecycle bucket holding it and the changelog it reads is repo-scoped.
	// Default .abcd/development/intents.
	IntentsRoot string `json:"intents_root"`
	// DeliverySections are additional changelog change-type headings delivery_state
	// reads as delivery claims. They are UNIONED with deliveryStateSections, never
	// substituted for them: a repo names its own headings here to widen the gate,
	// and a config that could narrow it could silently disarm it.
	DeliverySections []string `json:"delivery_sections"`
	// AgentsDir is the agent_contract prompt tree, repo-relative (default
	// "agents"). It lies outside Roots — an agent prompt is not a record, so the
	// rule walks the tree itself rather than the tree being added to Roots and
	// judged by the record stores' schema.
	AgentsDir string `json:"agents_dir"`
	// DiffRange is the agent_contract changelog sub-check's git revision range.
	// It is supplied by the CALLER (ArmAgentDiff, from a CI invocation) rather
	// than read out of the in-tree config, for the reason ArmReceiptGate states:
	// the decision to check a diff, and which diff, is trust-rooted to the
	// workflow, not to the committer-editable file. Empty makes the sub-check a
	// no-op — there is no diff to make a statement about.
	DiffRange string `json:"-"`
}

RuleConfig is the shared shape for the non-token check families. Only the fields relevant to a given rule are populated.

type SpecLink struct {
	// ID is the spec id (spc-N) from frontmatter, "" when malformed or absent.
	ID string
	// Bucket is the lifecycle directory holding it: "open" or "closed".
	Bucket string
	// Path is the spec's repo-relative path.
	Path string
	// IntentID is the raw intent frontmatter value — the back-link.
	IntentID string
	// contains filtered or unexported fields
}

SpecLink is one spec record as the link index sees it. The unexported fields carry what the spec-lifecycle lint needs from the same read — the frontmatter with its line numbers, and whether the file is content-exempt — so the tree is walked once for both consumers.

type SpecLinkIndex

type SpecLinkIndex struct {
	Intents []IntentLink
	Specs   []SpecLink
}

SpecLinkIndex is ONE traversal of the intent buckets and the spec store, shared by every consumer that must reason about the intent↔spec link.

It exists because two consumers ask opposite questions of the same two trees. spec_lifecycle walks the specs and asks whether each names an intent that agrees with it; the release cut walks the intents and asks whether any still sitting in planned/ has a spec that has already CLOSED — a merged feature whose record never moved, which is invisible to the shipped/-tree diff and would silently under-bump the release. Two walks would be two answers about one tree, so there is one scan and two readings of it.

func ScanSpecLinks(repoRoot, intentsDir, specsDir string, top Config) (SpecLinkIndex, error)

ScanSpecLinks reads the intent buckets and the spec store once, both relative to repoRoot. A missing tree contributes nothing and is not an error, mirroring the rest of the record lint: an unpopulated repository is a state, not a fault. A tree that is present but cannot be read IS a fault and is returned: both halves fail closed, so no consumer ever reads an index that says "nothing here" about records it merely failed to open.

top supplies the content exemptions. They are recorded per spec rather than applied here, because they exempt a file from the lint's CONTENT checks — they do not mean the record stopped existing, which is the only thing the release cut asks about.

func (SpecLinkIndex) IntentSpecID

func (x SpecLinkIndex) IntentSpecID() map[string]string

IntentSpecID maps each known intent id to its raw spec_id value.

func (SpecLinkIndex) KnownIntents

func (x SpecLinkIndex) KnownIntents() map[string]bool

KnownIntents is the set of intent ids present anywhere in the corpus.

func (SpecLinkIndex) SpecBucket

func (x SpecLinkIndex) SpecBucket(specID string) (string, bool)

SpecBucket resolves a spec_id value to the lifecycle bucket holding that spec.

Matching is on the spec NUMBER, not the literal string, because a spec_id is written both bare (`spc-9`) and with its slug (`spc-9-thing`) across the record; comparing literals would silently fail to resolve half the corpus and make a fail-closed gate fail open.

type TokenChecker

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

TokenChecker is a compiled banned-token set, ready to run over text.

func NewTokenChecker

func NewTokenChecker(tokens []BannedToken) (*TokenChecker, error)

NewTokenChecker compiles a configuration's banned_tokens. It refuses the same entries `LintAt` refuses, on the same compile, so a caller cannot arm a set the gate itself would not load.

func (*TokenChecker) Len

func (tc *TokenChecker) Len() int

Len reports how many bans are armed. A checker with none is inert, and a caller that would otherwise walk a whole tree to find nothing can say so.

func (*TokenChecker) LintComposed

func (tc *TokenChecker) LintComposed(name, text string, fenced bool, source []string) []Finding

LintComposed lints text that has been LIFTED out of a source file — a span the website selected and rendered — and so no longer carries the source's line structure, its fence markers, or its line-level allow comments.

The escape has to keep working across that lift, or every ban would harden silently the moment its text was composed. `source` is the source file's own lines, and a match is exempt when some source line both CONTAINS the matched text and carries the token's allow context: the same line-level judgement the file walk makes, made about the line the composed text actually came from.

`fenced` says whether the text was rendered as a code block, so a ban that skips code fences in a file skips it here for the same reason. It is a parameter rather than something read back out of the text because composed text HAS no fence markers: looking for them would find a backtick that is content and silently stop checking from there, which is a gate passing by not looking.

Passing a nil `source` is the strict reading — no line can grant an escape — which is what a caller with no source to point at should get.

type UnreadableAnswer added in v0.7.0

type UnreadableAnswer struct {
	Item        string `json:"item"`
	Run         string `json:"run"`
	Path        string `json:"path"`
	Disposition string `json:"disposition"`
}

UnreadableAnswer is one item whose standing disposition cannot be read.

type UnsafePath added in v0.7.0

type UnsafePath struct {
	Path   string `json:"path"`
	Reason string `json:"reason"`
}

UnsafePath is one path the walk declined to read, with the reason it declined. The reason travels with the path because one line served every failure and was false for most of them: an oversized or permission-refused REGULAR FILE was described as "not a real directory", which sends the reader to look for a symlink that is not there.

Jump to

Keyboard shortcuts

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