Documentation
¶
Overview ¶
Package rules is abcd's transport-agnostic modular rules loader (itd-3). It owns the whole capability behind two front doors: the `abcd rules [domain]` CLI verb and the Claude Code prompt-router hook. Nothing here writes to stdout or knows about a harness event — the front doors under internal/surface and the hook entrypoint marshal these results for their transport.
The model is a small set of binary-bundled default domains (embedded below, plus SHELL, generated from the guard's hazard registry in shell.go, and GRILL, generated from the asking rules in grill.go) merged with two optional override layers, in order: the user scope's ~/.abcd.noindex/rules.json (one per machine, spc-23) and then the per-repo <repoRoot>/.abcd/rules.json, so the repo wins a field both set. Each domain carries recall keywords + aliases and a list of rules; a prompt is recall-matched against the active domains and only the matching rules are rendered for injection. A leading *<DOMAIN> star-command activates a domain unconditionally (overriding a dormant state, but never the top-level kill switch).
Validation is hand-rolled Go (zero new dependencies): a rules.json that fails to parse or validate is a fail-closed error the caller surfaces loudly — it never silently degrades to zero injection.
Index ¶
- Constants
- Variables
- func CapPrompt(prompt string) string
- func FenceRuleBody(r string) string
- func Hits(d ResolvedDomain, prompt string) []string
- func Label(name, source string) string
- func LayerPath(source string) string
- func LoadBackstop(repoRoot string) int
- func PruneState(maxAge time.Duration)
- func ReadRepoLayerFile(repoRoot, rel, what string, limit int64) (data []byte, ok bool, err error)
- func ReadUserLayerFile(home, rel, what, holds string, limit int64) (data []byte, ok bool, err error)
- func ReadUserLayerFileIn(dir *os.Root, home, rel, what, holds string, limit int64) (data []byte, ok bool, err error)
- func RenderListing(domains []ResolvedDomain) string
- func ResetFill(home, session string) error
- func ResetState(session string) error
- func ResolveRoot(cwd string) string
- func RulesBudget(reserved int) int
- func SanitizeRuleBody(r string) string
- func SaveState(session string, st SessionState) error
- func Signature(d ResolvedDomain) string
- func SwapOwnerUIDForTest(fn func(string) (uint32, error)) (restore func())
- func SwapUserHomeForTest(fn func() (string, error)) (restore func())
- func TermMatcher(prompt string) func(term string) bool
- func TextStems(text string) []string
- func UnknownFillNotice(st *SessionState, f Fill) string
- func UserHome() string
- func Validate(rs RuleSet) error
- func WriteFill(home, session string, usedPct float64, at time.Time) error
- type Bracket
- type BracketRow
- type Domain
- type Fill
- type InjectResult
- type PromptTerm
- type Resolution
- type ResolvedDomain
- type RuleSet
- type SessionState
Constants ¶
const ( FillSourceStatusLine = "status-line" FillSourceTranscript = "transcript" FillSourceUnknown = "unknown" )
The fill's sources, as the hook's --json envelope names them.
const ( StateActive = "active" StateDormant = "dormant" )
Domain state values. An empty string is treated as active.
const ( SourceBundled = "bundled" SourceUser = "user" SourceRepo = "repo" )
Source labels for ResolvedDomain.Source: where a domain's effective content came from. An override that names a domain — replacing its rules, changing its state, or declaring it outright — makes the domain that override's layer, conservatively: the effective behaviour is that layer's choice even when only the state moved. The LAST layer to name a domain labels it, so a domain the user scope and the repo both name is SourceRepo.
const DefaultRefreshBackstop = 15
DefaultRefreshBackstop is the fixed-N full-refresh backstop (D1): the primary refresh is event-driven (a SessionStart/PreCompact reset clears the ledger), and this large counter only catches always-relevant domains that never recall-match. It is deliberately larger than CARL's every-5.
const GrillDomain = "GRILL"
GrillDomain is the bundled domain that carries the asking rules every abcd interview follows (itd-201; spc-2610030944505997, "GRILL generated from one Go source"): one thing at a time, the thing being decided quoted in full, the question's layout and its limits, options that widen and never recommend, and deferral recorded as an answer.
The domain is GENERATED from internal/core/question, never written in defaults/rules.json: its rules are question.AskingRules(question.Default), the same Limits value the question check in the guard hook enforces, and its recall is question.AskingRecall. A limit changed there changes the rule text with no second edit (itd-2610030810350727 criterion A7), and TestGrillDomainIsGeneratedFromTheAskingRules fails if the two ever part. It reaches every repository abcd manages through the binary, as SHELL does, and is an ordinary bundled domain to every loader contract: per-field user and repository overrides, dormant (a repository silences it with {"GRILL": {"state": "dormant"}}), the kill switch, the *GRILL star command, dedup and provenance. The front doors that load a repository's rules regenerate it at the question limits in force there (LoadWith, withRepoGrillDomain); this init-time domain is the bundled layer, at question.Default, and the form LoadAt and LoadWith with no limits set return.
const HostOutputCap = 10_000
HostOutputCap is the host's cap on one hook's output, in characters (the hooks reference, read 2026-11-04): above it the host saves the output to a file, shows a short preview and does not ask the agent to read the rest. Another host may differ, and this is the one place the figure sits.
const InjectionBudgetBytes = HostOutputCap - hostOutputMargin
InjectionBudgetBytes bounds everything the prompt hook adds on one turn: the rules, the memory notes and pages, the status block and the away block (iss-2611041419354106). The status and away blocks are read first and the rest share what they leave; the memory recall takes what the rules actually left (spc-2610111627213138, "Budget"), never a budget of its own.
const MemoryAll = -1
MemoryAll is a memory figure that is bounded by the per-turn budget alone (InjectionBudgetBytes, less what the rules took), not by a bracket's own.
const MemoryFloorBytes = 2_500
MemoryFloorBytes is what the rules leave for memory notes and pages however many domains match, so a long rule set never silences what was learned. It holds a note at the longest body a note may have, on lines of ordinary length, with its header and line. What the notes leave of it goes back to the rules (cli.injectWithRecall).
const RepoRelPath = ".abcd/rules.json"
RepoRelPath is the per-repo override file, relative to the repo worktree.
const ShellDomain = "SHELL"
ShellDomain is the bundled domain generated from the shell-hazard registry the guard reads (itd-103, as narrowed by itd-2611041636196213). It has two lists. Rules is what is sent as shell work starts: one line saying a guard judges each command, then the lessons of the commands it only warns about, since a warned command still runs. Checked is what the guard carries: the lessons of what it refuses, the delete entries' among them (SplitLessons), which the refusal answers for in the main session and in a sub-agent alike, and `abcd rules SHELL` lists. With the guard switched off nothing refuses, so every lesson stays in Rules, under a first line saying the guard is off.
The domain is GENERATED, never written in defaults/rules.json: an entry added to or removed from the registry changes the domain with no second edit, and TestEveryLessonIsInExactlyOneList fails if a hazard falls out of both lists. The script reading, a variable-built `-c` script that deletes and a delete the guard cannot prove safe have no entry of their own, so their lessons are the guard's (guard.Registry.ScriptLesson, ShellCLesson, DeleteLesson). One recall term stands for each command head the registry matches. To every loader contract (per-field overrides, dormant, the kill switch, the *SHELL star command, dedup, provenance) it is an ordinary bundled domain, and a guardrail domain to noteWithheld.
The bundled defaults carry the domain generated from the bundled registry. Load regenerates it, by the same generator, from the registry the guard enforces in the repository, the bundled entries merged with the repository's own .abcd/guard.json (ruling CK1), each such lesson marked guard.RepoMark. The switches stay independent (spc-16, "Config home"): the guard file decides what is refused, and rules.json overrides, silences or kills what is sent.
const StateTTL = 7 * 24 * time.Hour
StateTTL bounds how long a per-session ledger lives before the reset hook sweeps it (sessions are one-shot; a week is generous headroom).
const TranscriptTailBytes = 256 * 1024
TranscriptTailBytes bounds the transcript read: at most this many bytes, from the end, are read, however long the session's transcript has grown. The figure is the spec's starting point, set here alone.
Variables ¶
var ErrNoFillDirectory = errors.New("rules: the fill directory is not there, so no fill is kept")
ErrNoFillDirectory is WriteFill's answer when the fill directory is not there: the session-start reset makes it, and the status line never does, so a machine whose session-start hook is not installed, or whose folder was swept, keeps no fill. A caller skips the write with no notice: the status line is stateless and cannot say it once.
var ErrNoStateHome = errors.New("no home folder to keep the session ledger in, so every prompt re-injects what it matches")
ErrNoStateHome is SaveState's answer when the account has no home folder: no ledger is kept, so every prompt re-injects each domain it matches. It is returned, not swallowed, so the caller can say why on its diagnostic stream.
var FillDirDisplay = abcdhome.Display("fill") + "/"
FillDirDisplay is the fill directory in the tilde form a message or a help text names it by.
var TrustedRootsDisplay = abcdhome.Display("trusted-roots")
TrustedRootsDisplay is how that file is NAMED in a diagnostic: the tilde form, never the expanded path, so a refusal a user pastes into a shell works and no message carries the developer-identity home path (iss-81, fsutil.RedactHome).
var TrustedRootsRelPath = abcdhome.Rel("trusted-roots")
TrustedRootsRelPath is the home-scoped opt-in that re-admits a marker root the caller does not own, relative to the user's home directory.
var UserDisplayPath = abcdhome.Display("rules.json")
UserDisplayPath is how the user-scope file is NAMED in a diagnostic: the tilde form, never the expanded path, so no message carries the developer-identity home path (iss-81, fsutil.RedactHome) and a refusal a user pastes still names the file.
var UserRelPath = abcdhome.Rel("rules.json")
UserRelPath is the user-scope override file, relative to the home directory: the machine's own conventions, layered between the bundled defaults and every repo's override (itd-117, spc-23).
Functions ¶
func CapPrompt ¶ added in v0.14.2
CapPrompt is prompt cut to the bytes the loader scans (maxPromptBytes), so a huge pasted prompt cannot blow up matching. Every reader of a prompt — InjectWithin, TermMatcher, Hits and the `rules --prompt` diagnostic — caps through it, so a word past the cap matches nowhere.
func FenceRuleBody ¶ added in v0.14.2
FenceRuleBody renders an override's rule body as a fenced code block inside its bullet. The line-start contract the indent pass of sanitizeRuleBody defends is not the only reader of the injected block: a markdown renderer reads "- # x", a setext underline or an "<h2>" HTML block as a heading, which would put an unlabelled heading in front of that reader (iss-2609020219265817). Inside a fence CommonMark honours no construct at all, and the fence is computed rather than escaped construct by construct: tildes, one longer than the longest tilde or backtick run in the body (at least three), so no body line can close it (CommonMark 0.31.2 §4.5). Every non-blank line, the closing fence included, sits at the bullet's content column, so the block stays inside its list item and no line starts flush-left. The body's own text is unchanged apart from the normalisation and control-character mask sanitizeRuleBody also applies. An empty body renders to "" so the caller drops it.
It is exported as the tree's one fence for another party's text under a "- " bullet: the memory recall fences every note body through it (spc-2610111627213138), so a note from a repository's committed .abcd/memory.json can no more put a heading in front of the reader than an override's rule can. One primitive, never a copy. The returned text starts with the opening fence and carries no indent on that first line, so a caller placing it on a line of its own prefixes " " to reach the bullet's content column.
func Hits ¶ added in v0.14.2
func Hits(d ResolvedDomain, prompt string) []string
Hits names what made d match prompt, for the `rules --prompt` diagnostic: "*NAME" when a star-command activated it, otherwise each recall word and alias that hits, in the order the domain declares them. It says nothing of state or the kill switch; Match decides whether d is injected at all.
func Label ¶ added in v0.11.0
Label is a domain name as every provenance surface prints it: bare for a bundled domain, "NAME (user override)" or "NAME (repo override)" for one an override layer named. The rendered heading and the hook's diagnostic both use it, so the two agree byte for byte.
func LayerPath ¶ added in v0.11.0
LayerPath is the display path of the file a layer's source label names: UserDisplayPath for SourceUser, RepoRelPath for SourceRepo, and "" for the bundled defaults, which have no file.
func LoadBackstop ¶
LoadBackstop reads rules.force_refresh_every_n from <repoRoot>/.abcd/config.json — the fixed-N full-refresh backstop (D1). Event-driven reset is the primary refresh, so this only bounds always-relevant domains; a missing file/key or a non-positive value falls back to DefaultRefreshBackstop.
func PruneState ¶
PruneState removes session-state files older than maxAge, bounding the growth of the state folder across many sessions, and sweeps the fill directory (~/.abcd.noindex/fill/, fill.go) by the same age. Best-effort housekeeping: a missing folder or a per-entry error is ignored.
func ReadRepoLayerFile ¶ added in v0.14.2
ReadRepoLayerFile reads <repoRoot>/<rel>, rel a slash path below .abcd/ (".abcd/rules.json"). ok is false when the file is absent; every other failure is an error prefixed "<what>: " naming the file by rel.
A symlinked .abcd directory component is refused before the leaf is touched, so a swapped .abcd cannot redirect the read; the leaf itself is opened once, O_NOFOLLOW and O_NONBLOCK, and judged on its descriptor as a regular file within limit bytes (readGuarded).
func ReadUserLayerFile ¶ added in v0.14.2
func ReadUserLayerFile(home, rel, what, holds string, limit int64) (data []byte, ok bool, err error)
ReadUserLayerFile reads the user scope's file rel (a slash path below home, abcdhome.Rel("rules.json")). ok is false when there is no such file — or no home to hold one — which is the ordinary case and costs nothing: nothing is created, nothing is reported. Every refusal is an error prefixed "<what>: " naming the file in tilde form; holds names what the file carries ("rules", "notes") in the two refusals that say whose they are.
The file injects text into every session on the machine, so it is read as the caller's WORD, through the same primitive as the other home-scoped declarations (fsutil.ReadDeclaration): a regular file — never a symlink, FIFO or device — within the size cap, owned by this session's uid and writable by nobody else. That is the ownership rule the repo root's trust bound applies to a foreign-uid checkout (root.go, foreignOwnerRefusal): a file another account could have written is not this account's convention. And the ~/.abcd.noindex directory itself must not be a symlink when a file sits behind it, the pre-check the repo's .abcd gets — checked only once a file is there, because a machine whose ~/.abcd.noindex is a dotfiles symlink holding no such file reads nothing and must keep behaving exactly as it did. That check is fsutil.ReadHomeDeclaration's (fsutil.HomeScopeLink), the one every other home-scoped reader and writer applies, so the rule cannot drift per file.
Every refusal is an error naming the file in tilde form, never a silent fallback: an unreadable user layer that degraded to a partial injection is the silent shape loud-staging exists to prevent.
func ReadUserLayerFileIn ¶ added in v0.14.2
func ReadUserLayerFileIn(dir *os.Root, home, rel, what, holds string, limit int64) (data []byte, ok bool, err error)
ReadUserLayerFileIn is ReadUserLayerFile over the directory of rel that the caller already holds open, dir (fsutil.EnsureHomeScope's or OpenHomeScope's root for path.Dir(rel)): the file is read relative to that descriptor through fsutil.ReadHomeDeclarationDenyingIn rather than by walking home again. A writer that writes through dir re-reads through it, so a same-uid rename of the directory between its walk and the read cannot make it read one directory and write another (iss-2609290300313698). Every guard on the file, and every refusal's wording, is ReadUserLayerFile's; the directory itself was judged by the walk that opened dir.
func RenderListing ¶ added in v0.17.0
func RenderListing(domains []ResolvedDomain) string
RenderListing renders domains as a reader of `abcd rules` wants them: what the hook sends for each, then what a check carries. Only a domain with a Checked list differs from what the hook renders, and this is never what is injected.
func ResetFill ¶ added in v0.16.1
ResetFill is the fill's half of the reset triggers. It makes the fill directory (0700) when it is not there, through the home scope's guarded walk, so a symlinked ~/.abcd.noindex is refused and no fill directory lands under its target, and it deletes the session's fill file, so a compaction does not leave the hook reading the full session's figure until the status line next refreshes. With no home it does nothing.
A symlinked ~/.abcd.noindex is refused quietly: the error wraps fsutil.ErrHomeScopeSymlinked, which the hook does not report, since a dotfiles home is the machine's layout and the status line simply keeps no fill there. Any other failure is returned for the hook to name.
func ResetState ¶
ResetState clears a session's ledger (the event-driven refresh: the next prompt re-injects every matching domain). A missing file or folder, or no home, is not an error; a folder stateFolder refuses is, so the hook never reports a reset it did not make.
func ResolveRoot ¶ added in v0.7.1
ResolveRoot resolves the repo root the per-repo configuration under .abcd/ is read from — rules.json and config.json here, guard.json for the shell guard, which shares this resolver so a session's rules and its guard can never come from two different places.
The resolution is bounded at the git working tree (GHSA-vvqc-3mv2-5p49). The toplevel git reports for cwd is resolved FIRST; the walk then runs from cwd upward but stops at that toplevel inclusive, so the nearest .abcd directory INSIDE the tree wins (a repo that disabled a domain, or the whole loader, stays disabled from any nested directory — iss-66/B12) and a tree with no .abcd resolves to its own toplevel. A .abcd above the working tree is never reached: an unbounded walk let a directory planted in the shared temp dir govern the injected rules and disarm the guard of every repository beneath it. The per-repo file is a repo-scope setting by design (the configuration chapter and itd-3 both reject a global rules.json), so the bound is the documented contract, not a new policy.
The exact scope of what that closes: any ancestor a session's own working tree sits inside; a plant in a shared directory that is not a repository — the one-command `: > /tmp/.git` or `mkdir /tmp/.git` beside a planted /tmp/.abcd, which the fallback below refuses because a marker must look like a repository; and a REAL repository planted in a shared ancestor by another uid (`git init /tmp`, or a repository laid in a root-owned mode-1777 directory), which the fallback refuses on OWNERSHIP — see foreignOwnerRefusal, and TrustedRootsRelPath for the explicit opt-in that re-admits a foreign-uid checkout the caller means to trust.
The home directory is never a repo root (iss-2609020219198779). Its .abcd is the USER layer (spc-23), and a home that is itself a git working tree (dotfiles-in-home) would otherwise hand every non-repo directory beneath it the home's .abcd a second time, as the repo layer — its guard.json with it, which has no user layer at all, and its config.json as the repo layer over itself as the machine layer. So the walk passes over the home, a toplevel that IS the home takes the non-repo route (cwd, no walk) when nothing nearer carries a .abcd, and a toplevel that CONTAINS the home — a hermetic harness pointing HOME inside its checkout — stays the root, because it is a repository git vouched for and not the home. What this does not reach is a session whose working directory IS the home: the root is then cwd, as it is for any non-repo directory, and a .abcd at the working directory is read. That is the working-directory read the refusal below also leaves standing; making it refuse is a posture change, not a bound on the walk (iss-2609251522588539, and its entry of 2026-09-25, dcn-2609250000000011).
"Not a repository" and "a repository git will not answer for" are DIFFERENT outcomes and only the first resolves to cwd with no walk. abcd runs git under an isolated environment (GIT_CONFIG_GLOBAL=/dev/null, GIT_CONFIG_NOSYSTEM=1) which also discards the developer's safe.directory exceptions, so rev-parse fails inside a checkout owned by another uid; it fails outright when the host launches the hook with git off its PATH. Collapsing those onto cwd dropped the repository's own configuration layer with no error anywhere: from a subdirectory the root became the subdirectory, so guard.json's hazards became allows, the rules kill switch stopped applying, and the private banlist store went missing. A repo-shaped tree therefore falls back to the .git marker (gitutil.RepoShapedRoot), and only a directory with no repository above it keeps the no-walk cwd: outside a working tree there is no boundary to stop at, and a walk that stops nowhere is the defect.
The marker walk is a NAME check that runs to the filesystem root, so it is not by itself a bound: an unprivileged `: > /tmp/.git` would otherwise hand every session in a plain directory beneath /tmp to a planted /tmp/.abcd, git having refused to answer for a directory that is not a repository. The fallback root is accepted only when its .git is a PLAUSIBLE repository — a directory carrying HEAD, or a regular file beginning "gitdir: " (plausibleRepository below, which states the shapes exactly) — and anything else takes the non-repo route: cwd, no walk, nothing above it consulted. That discriminator is what git reads, not a trust boundary on its own: laying out a real repository still passes it. The trust boundary is the ownership gate that runs next — a marker root whose owner is not the caller is refused, loudly, unless the caller has declared it in the user-scope home (iss-2609020259564193). Both bounds apply only where git will not answer; where it does, the toplevel it named stands whoever owns it.
A nested repository or submodule resolves its own toplevel either way and does not inherit the superproject's .abcd — correct scoping, visible to submodule workflows.
func RulesBudget ¶ added in v0.17.0
RulesBudget is what the rules may take of the turn once reserved bytes have gone to the blocks read first and the floor to memory. It is never below 0.
func SanitizeRuleBody ¶ added in v0.14.2
SanitizeRuleBody is the rule body's render-safety pass (sanitizeRuleBody), exported so the memory recall renders a note's head line — its id, its layer and its one-line title — through the same mask a rule body takes: control and bidirectional characters masked, any continuation line indented under the bullet. A note's body is fenced instead (FenceRuleBody).
func SaveState ¶
func SaveState(session string, st SessionState) error
SaveState durably persists the ledger for a session through the canonical fsutil.WriteFileAtomicInRoot (temp-write, fsync, rename, parent-dir fsync) into the folder stateFolder opened, so the write is crash-safe, a reader sees either the old file or the complete new one, and it never follows a link out of that folder. The folder is made 0700 and the file 0600. With no home it keeps nothing and returns ErrNoStateHome.
func Signature ¶
func Signature(d ResolvedDomain) string
Signature is the per-domain dedup key: an FNV-1a hash of the rendered block, so identical rendered content (defaults or override) dedups and any content drift invalidates. FNV is sufficient — this is dedup, not security.
func SwapOwnerUIDForTest ¶ added in v0.14.2
SwapOwnerUIDForTest substitutes the marker root's owner lookup and returns the restore. It is exported because a front door that must print the refusal (Resolution.Notes) is tested from another package. Tests only; never called in production code, and never safe to call from a parallel test.
func SwapUserHomeForTest ¶ added in v0.11.0
SwapUserHomeForTest substitutes the home lookup Load reads the user layer through and returns the restore. It is exported because the front-door tests that load rules live in another package. Tests only; never called in production code, and never safe to call from a parallel test.
func TermMatcher ¶ added in v0.14.2
TermMatcher is the loader's term rule, exported so a memory note's recall word hits on exactly the prompts a domain's recall word does (spc-2610111627213138, "One recall for notes and pages"): it indexes prompt once — capped at the bytes InjectWithin scans, lower-cased, stemmed — and returns the match a domain's every recall word and alias is judged by (word boundary, stems, multi-word phrases). One function, never a copy.
func TextStems ¶ added in v0.16.0
TextStems is the stem of each token of text, in order — lower-cased, split on every run of characters that is not a letter or a digit, each token stemmed as termHit stems a recall keyword's token — so the ranking counts a note's or page's words in the form the term rule compares them in.
func UnknownFillNotice ¶ added in v0.16.1
func UnknownFillNotice(st *SessionState, f Fill) string
UnknownFillNotice is the one line the hook says when how full the session is is unknown, and only the first time this session (the technical facilitator's ruling of 2026-10-11, "Rules full, notes short": the hook says the fill is unknown on stderr on the first prompt of each session). It records in st that it was said, so a caller saves st after it. It is "" when the fill is known or the line was already said this session. The reason is the fill reader's, in abcd's own words.
func UserHome ¶ added in v0.14.2
func UserHome() string
UserHome is the home the user layer is read under, through the seam the tests swap. It is exported so the memory recall reads the machine's memory.json beside the very rules.json Load read: one home for both layers, never a second lookup that a test could leave pointing at the developer's own. "" when there is none.
func Validate ¶
Validate checks structural invariants: schema_version == 1, every domain name matches [A-Z][A-Z0-9_]*, every state is active/dormant (or empty), every domain carries at least one rule, and no rule body is empty or whitespace-only. An empty rule body otherwise passes here and renders as a bare contentless "- " bullet in the injected block (iss-2608261550497978), and a domain with no rules at all — an override of {"rules": []}, or a custom domain declared without any — renders as a heading-only "## NAME" block, suppression wearing the domain's name (GHSA-22f8-qf5r-gjgq sibling). Neither silent shape is acceptable; {"state": "dormant"} is the way to silence a domain.
The ruleless-domain rule is a REFUSAL here and a per-domain skip in Load. It refuses here because Validate is what guards the bundled defaults, where a heading-only domain is a build error. Load reaches Validate with the ruleless domains already dropped and a note naming each (see dropRulelessDomains), because failing a repo's whole file — every domain, on an upgrade — is not proportionate to one malformed entry.
func WriteFill ¶ added in v0.16.1
WriteFill records the context percentage the status line was handed for a session, in the session's fill file, mode 0600, atomically, through the home scope's guarded walk, so never behind a symlinked ~/.abcd.noindex. It is the status line's one write, and the only writer of the file.
It creates nothing but the file: the directory is the session-start reset's to make (ResetFill). A directory that is not there is ErrNoFillDirectory, decided before any level is judged, so a symlinked ~/.abcd.noindex holding no fill directory is a quiet skip like any other absence; one that IS there behind a link, or in a directory another account can change, is refused and the error says so. With no home or no session there is nothing to name the file by, and nothing is written.
Types ¶
type Bracket ¶ added in v0.16.1
type Bracket int
Bracket is a row of the bracket table. The zero value is BracketUnknown, so a caller that hands no fill gets the unknown row: rules in full, as before the brackets, and notes and pages as one line each.
func BracketFor ¶ added in v0.16.1
BracketFor is the bracket a fill falls in: BracketUnknown when no source told how full the session is.
func BracketForUsed ¶ added in v0.16.1
BracketForUsed is the bracket of fill a used share of the window, 0 to 100, falls in. A share outside that range, or not a number, is no fill at all: BracketUnknown.
func (Bracket) Row ¶ added in v0.16.1
func (b Bracket) Row() BracketRow
Row is the bracket's row of the table.
type BracketRow ¶ added in v0.16.1
type BracketRow struct {
Bracket Bracket
// MinFreePercent is the least share of the window, 0 to 100, still free
// at which a bracket of fill holds. The unknown row has none.
MinFreePercent float64
// ShrinkRules sends each matched domain as its heading, its first rule
// and a line naming how many rules it holds and the command that renders
// the rest, instead of in full.
ShrinkRules bool
// MemoryFullBytes bounds the notes and pages sent in full, the
// top-ranked first: MemoryAll for the per-turn budget alone, 0 for none.
MemoryFullBytes int
// MemoryLineBytes bounds the notes and pages sent as one line each, the
// ones not sent in full, the top-ranked first: MemoryAll for the
// per-turn budget alone, 0 for none. Where it is not 0 the top-ranked
// candidate always comes back, as one line at least, past this bound
// (though never past the per-turn budget).
MemoryLineBytes int
}
BracketRow is one row of the table: when it holds and what it sends.
func BracketTable ¶ added in v0.16.1
func BracketTable() []BracketRow
BracketTable returns the table's rows, a copy, in the order they are read.
func (BracketRow) Describe ¶ added in v0.16.1
func (r BracketRow) Describe() string
Describe says, in words, when the row holds and what it sends, for `rules --prompt`: When, a colon, then Sends. The figures come from the row, so the words cannot state a threshold the table does not hold.
func (BracketRow) Sends ¶ added in v0.16.1
func (r BracketRow) Sends() string
Sends says what the row sends, as a sentence: the rules' form, then the notes' and pages'.
func (BracketRow) When ¶ added in v0.16.1
func (r BracketRow) When() string
When says when the row holds: the share of the window still free, or, for the unknown row, that nothing tells.
type Domain ¶
type Domain struct {
State string `json:"state,omitempty"`
Recall []string `json:"recall,omitempty"`
Aliases []string `json:"aliases,omitempty"`
Rules []string `json:"rules,omitempty"`
// Checked holds the rules a check carries rather than the hook: read at the
// refusal and listed by `abcd rules`, never sent ahead of time. Generated
// (only SHELL fills it, shellDomain), so no rule file can declare it and
// no rule can leave what is sent by being named here.
Checked []string `json:"-"`
}
Domain is one keyed rule domain. The map key in RuleSet.Domains is its name; the name is therefore not a serialized field on the value.
type Fill ¶ added in v0.16.1
type Fill struct {
Source string `json:"source"`
UsedPercentage *float64 `json:"used_percentage,omitempty"`
Model string `json:"model,omitempty"`
At string `json:"at,omitempty"`
Reason string `json:"reason,omitempty"`
}
Fill is how full the session is, and where that came from. Source is one of the FillSource constants. UsedPercentage is the share of the context window in use, 0 to 100, and nil exactly when the source is unknown. Model is the window table's name for the model a transcript-derived fill was divided by; At is when the status line recorded its figure. Reason says why the fill is unknown, in abcd's own words: no path and no text from the files read is ever echoed in it.
func ReadFill ¶ added in v0.16.1
ReadFill says how full the session is: from the session's fill file when there is one, otherwise from the tail of the transcript the hook's payload names, otherwise unknown with the reason. It writes nothing and opens only those two files and the directories on the way to them.
type InjectResult ¶
type InjectResult struct {
Text string
Injected []string
Active []string
Sources map[string]string
// Shrunk names, in order, each injected domain sent as its heading and
// first rule rather than in full (renderShrunk), because of its bracket or
// because the turn could not hold it.
Shrunk []string
// Pointed names, in order, each injected domain sent as its heading and the
// command alone, because even its first rule did not fit (renderPointer).
Pointed []string
// Bracket is the bracket the rules were injected in.
Bracket Bracket
State SessionState
}
InjectResult is the outcome of one prompt-router evaluation. Text is empty when nothing new is injected (a healthy no-match renders zero model-facing tokens, per D3). Sources says, per injected name, which layer the domain came from (SourceBundled, SourceUser or SourceRepo): the names alone cannot, and the out-of-band diagnostic must say whose words went into the context.
Active is the FULL set of domain names in force this turn, name-sorted and never nil (ruling J15, iss-2608261550580260): every domain that is not dormant, plus a dormant one this prompt activated with *NAME, and nothing at all under the kill switch. Injected names only what changed; Active is the removal signal a client that snapshots injected rules prunes against — a name it holds that Active omits has stopped, whether it was deleted, renamed or made dormant. It is never rendered into Text, so it costs the model's context nothing; a front door hands it to a machine reader out of band.
func InjectWithin ¶ added in v0.17.0
func InjectWithin(rs RuleSet, prompt string, prev SessionState, backstop int, bracket Bracket, budget int) InjectResult
InjectWithin is the pure heart of the prompt-router hook: it recall-matches prompt, drops any matched domain already injected this session with an unchanged signature, renders the remainder, and returns the updated session state. It performs no I/O and never reflects prompt bytes into the output — the rendered text is abcd's own rule content only.
backstop is the fixed-N full-refresh interval; <= 0 uses DefaultRefreshBackstop. When the (incremented) prompt count is a multiple of the backstop, the ledger is cleared first so always-relevant domains re-inject, and the recalled ledger with it, so a recalled item comes back on the same prompt.
bracket is the context bracket the session's fill puts the prompt in (brackets.go, BracketFor). In a bracket whose row shrinks rules, each matched domain is sent as its heading, its first rule and a line naming how many rules it holds and the command that renders the rest (renderShrunk); BracketUnknown, the zero value, a caller with no fill passes, keeps every domain in full, as before the brackets. The ledger keys on a domain's content, never on the form it was sent in (Signature hashes the full block), so a domain sent shrunk is not sent again in full when the bracket changes, nor the other way round, until a reset clears the ledger.
budget is the bytes the rules may take. A domain that does not fit in full but has room for its first rule goes in its short form and is recorded as sent, the same form and the same record as in a bracket that shrinks, since the form names the command that renders the rest. One with room only for its heading and the command carries no rule, so it is not recorded, and the next turn tries it again.
func (InjectResult) Labels ¶ added in v0.7.1
func (r InjectResult) Labels() []string
Labels returns the injected names in order, each labelled the way the rendered heading is — "PII (repo override)" for a repo-sourced domain, "PII (user override)" for a user-scope one, the bare name otherwise — so the diagnostic and the block agree byte for byte.
type PromptTerm ¶ added in v0.16.0
PromptTerm is one distinct word of a prompt, as the memory recall's ranking weighs it (spc-2610111627213138 step 4): Stem is the root stem gives the token that first used it, and Roots every candidate root the term rule matches its tokens by (stemVariants), so a word whose stem is among them is the term found exactly where termHit would hit it. Tokens whose roots overlap are one term ("merge" and "merging"), so no root belongs to two terms and a word in an item is found under one term at most.
func PromptTerms ¶ added in v0.16.0
func PromptTerms(prompt string) []PromptTerm
PromptTerms is the prompt index's query terms for the memory recall's ranking: each distinct word of the prompt, in the order the prompt first uses it, with its candidate roots. It reads the bytes TermMatcher reads, from the same index.
type Resolution ¶ added in v0.8.0
Resolution is ResolveRoot's answer together with the diagnostics the resolution produced. Notes is empty in the ordinary case; a non-empty entry is a refusal or a downgrade a front door MUST print out of band (stderr, never the injected context), because a resolution that silently declined to read a repository's own configuration is the exact shape the bound exists to prevent (.abcd/development/principles/loud-staging.md).
func Resolve ¶ added in v0.8.0
func Resolve(cwd string) Resolution
Resolve is ResolveRoot with its diagnostics kept. ResolveRoot is the shorthand for the callers that have nowhere to print them.
type ResolvedDomain ¶
ResolvedDomain pairs a domain with its name for ordered rendering and dedup, and with its Source so every consumer can say whose words these are (GHSA-22f8-qf5r-gjgq): the renderer marks a repo-sourced heading, the hook diagnostic labels the name, and `rules --json` carries the field.
func (ResolvedDomain) MarshalJSON ¶ added in v0.17.0
func (d ResolvedDomain) MarshalJSON() ([]byte, error)
MarshalJSON is the machine reader's view of a domain: both lists apart, and the size of each, so the review of the rule set can be run again as rules change. rules_bytes is what the hook sends for the domain in full, its heading included; checked_bytes is what the second list adds to the listing.
type RuleSet ¶
type RuleSet struct {
SchemaVersion int `json:"schema_version"`
Disabled bool `json:"disabled"`
Domains map[string]Domain `json:"domains"`
// contains filtered or unexported fields
}
RuleSet is the merged, validated rule model: the bundled defaults overlaid with the per-repo override.
func Defaults ¶
func Defaults() RuleSet
Defaults returns a deep copy of the binary-bundled default rule set, safe for the caller to mutate.
func LoadAt ¶ added in v0.16.2
LoadAt is LoadWith with the repository's rules and guard registry as they stood at commit base, for an agent whose working tree is not what it is judged by: what it wrote there since, committed or not, is not read. GRILL stays the bundled domain, at abcd's default question limits.
func LoadWith ¶ added in v0.17.0
LoadWith returns the bundled defaults merged with the user scope's ~/.abcd.noindex/rules.json and then with <repoRoot>/.abcd/rules.json — bundled, then user, then repo, each layer overriding per field (itd-117, spc-23). An absent file contributes nothing, so a machine with neither file gets the defaults unchanged; a present file that cannot be read, parsed or validated is a fail-closed error naming that file, and no partial set is returned with it.
The GRILL domain states the question limits l, the limits in force for repoRoot as the front door resolved them, and n, where they came from (spc-2610301950037469, approach 8); a caller with no repository's limits passes question.Default and no note, which is the bundled domain. The domain is regenerated on the bundled base before any rules.json layer lands, so a repository that overrides GRILL's rules still wins, and its Source stays bundled: setting a figure is not replacing the rules. A refusal in n is also one line of the notes, so every front door surfaces it out of band.
func Merge ¶
Merge overlays over onto base. Domain fields are per-field: a field set on the override wins; an absent field inherits the base (so {"state":"dormant"} on a default domain silences it while keeping its recall and rules). New domain keys are added. The kill switch is sticky (either side can enable it). Every domain the override names is recorded as SourceRepo — the one moment the origin is still known, so the renderer and the diagnostics can say so later.
func (RuleSet) Active ¶
func (rs RuleSet) Active() []ResolvedDomain
Active returns every injectable domain (state != dormant) in name-sorted order — the full set the diagnostic `abcd rules` render shows. The top-level kill switch yields nothing.
func (RuleSet) KillSwitchSources ¶ added in v0.11.0
KillSwitchSources returns the layers whose file set the kill switch, in layer order (SourceUser before SourceRepo); empty when the set is not disabled. The switch is sticky, so every layer named here has to clear it before anything injects again.
func (RuleSet) Lookup ¶
func (rs RuleSet) Lookup(name string) (ResolvedDomain, bool)
Lookup returns one domain by name regardless of its state (a dormant domain is still inspectable); ok is false when the name is absent.
func (RuleSet) Match ¶
func (rs RuleSet) Match(prompt string) []ResolvedDomain
Match returns the domains to inject for prompt, in deterministic (name-sorted) order. The top-level kill switch suppresses everything. Otherwise a domain is injected if a star-command names it (overriding dormant) or — when active — its recall keywords or aliases hit the prompt.
type SessionState ¶
type SessionState struct {
Count int `json:"count"`
Ledger map[string]string `json:"ledger"` // domain name -> last-injected signature
Recalled map[string]string `json:"recalled,omitempty"` // memory item key -> content signature
// FillUnknownSaid records that the hook has said, once this session, that
// how full the session is is unknown (UnknownFillNotice). The resets
// clear it with the ledgers, since they remove the file; the fixed
// backstop does not, so it is said once a session and not once a cycle.
FillUnknownSaid bool `json:"fill_unknown_said,omitempty"`
}
SessionState is the per-session dedup ledger plus the prompt counter that drives the fixed-N refresh backstop.
Recalled is the memory recall's own ledger (internal/core/recall, spc-2610111627213138): item key to a signature of the item's content. It is a second map because InjectWithin prunes every Ledger name that is not an active domain, which would forget every recalled item each turn; InjectWithin carries it through untouched, and the same resets clear both — ResetState removes the file, and the backstop prompt clears the two together.
func LoadState ¶
func LoadState(session string) SessionState
LoadState reads the ledger for a session. A missing, oversized, or malformed file yields the zero state (a fresh session), never an error — dedup is a best-effort optimisation, not a correctness gate. So does a file this account does not own, one others can write, one reached through a link, and one in a folder another account owns or can write: none is this account's word, and a fresh session only re-injects.