SLOPSHOPPER

actual-cli

Feature-complete companion for the actual CLI — runs and troubleshoots sync, status, auth, config, runners, and models across all 5 runners and 3 output…

panebandguardcommandtoastprocess
★ 5v1.6.0Apache-2.0updated 2026-10-23actual-software/actual-skill
A shopper browsing a rack in a slop shop
Preview · a replayed session in a sandbox
claude · ~/work/app · actual-cli
│ ┃ Rule briefing ✕ › fix the failing auth test and add an audit log call │ ┃ Rule briefing this session │ ┃ ⏺ Read(src/auth.ts) │ ┃ No reads yet in this session. ⎿ Read 6 lines │ ⏺ Update(src/auth.ts) │ ⎿ Added 2 lines, removed 1 line │ ⏺ Bash(bun test) │ ⎿ 3 pass, 1 fail │ │ ● Done. refresh now rejects expired claims and logs an audit event. │ │ ✻ Worked for 42s · done 4:20 PM │ │ › /rules-brief │ │ ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── › ? for shortcuts

Draws

Pane · Rule briefing
Rule briefing this session No reads yet in this session.
README

<h1 align="center">Actual.ai CLI Skill</h1>

<a href="https://app.actual.ai"> <img src="assets/logo.png" alt="Actual.ai" width="160"> </a>

<a href="https://github.com/actual-software/actual-skill/blob/main/LICENSE"><img src="https://img.shields.io/github/license/actual-software/actual-skill" alt="License"></a> <a href="https://github.com/actual-software/actual-skill/stargazers"><img src="https://img.shields.io/github/stars/actual-software/actual-skill?style=flat" alt="Stars"></a> <a href="https://github.com/actual-software/actual-skill/issues"><img src="https://img.shields.io/github/issues/actual-software/actual-skill" alt="Issues"></a>

Quickstart

Install Actual.ai Skill — Claude Code CLI

Run each step as its own copy/paste.

Step 1 — add this repo as a marketplace:

/plugin marketplace add actual-software/actual-skill

Step 2 — install the plugin:

/plugin install actual-cli@actual-cli-skills

Step 3 — reload plugins so Claude Code CLI loads the newly installed plugin:

/reload-plugins

Step 4 — run the skill in your coding agent:

/actual

The first time you run it, the skill asks for your permission to install the Actual.ai CLI for you. For example:

/actual

The `actual` CLI is not installed. Should I install it with:

    npm install -g @actualai/actual

Then I'll verify it with `actual --version`.
$skill-installer install the actual skill from actual-software/actual-skill

On first use, the actual skill will offer to install the actual CLI if it is not already on your PATH. For example:

$actual

The `actual` CLI is still not installed. Should I install it with:

    npm install -g @actualai/actual

Then I'll verify it with `actual --version`.

Clone and symlink to your global skills directory:

git clone https://github.com/actual-software/actual-skill.git ~/.local/share/actual-skill

# For OpenCode
ln -s ~/.local/share/actual-skill/skills/actual ~/.config/opencode/skills/actual

# For Cursor
ln -s ~/.local/share/actual-skill/skills/actual ~/.cursor/skills/actual

# For Claude Code (alternative to marketplace)
ln -s ~/.local/share/actual-skill/skills/actual ~/.claude/skills/actual

# For Codex (alternative to $skill-installer)
ln -s ~/.local/share/actual-skill/skills/actual ~/.agents/skills/actual

Keep Actual.ai Skill up to date — Claude Code CLI

Claude Code updates the plugin for you once auto-update is on for the actual-cli-skills marketplace. It's off by default for a third-party marketplace like this one, so turn it on once: run /plugin, open the Marketplaces tab, select actual-cli-skills, and choose Enable auto-update.

The same switch in a settings file is "autoUpdate": true on the marketplace's extraKnownMarketplaces entry. In ~/.claude/settings.json, add that line to the actual-cli-skills entry if one is already there, or add the whole entry:

{
  "extraKnownMarketplaces": {
    "actual-cli-skills": {
      "source": { "source": "github", "repo": "actual-software/actual-skill" },
      "autoUpdate": true
    }
  }
}

Re-adding the marketplace with claude plugin marketplace add rewrites this entry without the autoUpdate line, so add the line back if you do.

An organization can put the same entry in its managed settings to turn auto-update on for everyone, and setting autoUpdate there locks the toggle in /plugin.

With auto-update on, Claude Code checks for a new version in the background, up to ten minutes after the first message of each interactive session. The new version loads in your next session, or straight away if you run /reload-plugins when Claude Code tells you the plugin was updated. Setting DISABLE_AUTOUPDATER, DISABLE_UPDATES or CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC turns these background updates off unless FORCE_AUTOUPDATE_PLUGINS=1 is set as well.

To update by hand, refresh the marketplace, then update the plugin:

claude plugin marketplace update actual-cli-skills
claude plugin update actual-cli@actual-cli-skills

Then restart Claude Code, or run /reload-plugins in a session that's already open. If claude plugin update reports that the plugin is already at the latest version, there's no newer release yet.

Use Actual.ai Skill

Once installed, ask your agent in plain language. For example:

  • "Set up Actual for this repository."
  • "Preview the ADR guidance Actual would add here."
  • "Ask the Actual advisor how we should handle database access in a new service."
  • "Sign me in to Actual AI."
  • "Diagnose why Actual is failing."

In Codex, you can also call the skill directly by starting the prompt with $actual.

What is the Actual.ai Skill?

The Actual.ai Skill gives your AI coding agents architectural guardrails, keeping every plan and change grounded in the ADRs your team has already written.

Why do I need the Actual.ai Skill?

Coding agents don't know the architecture decisions your team has already made, so they write code that ignores them. The skill gives your agent your team's ADRs as context, so its code follows your architecture from the start.

Who is the Actual.ai Skill for?

AI-native software teams: developers who build with coding agents and want those agents to follow the architecture decisions their team has already made.

Where does the Actual.ai Skill work?

Inside the coding agent your team already uses: Claude Code, Codex, ChatGPT, Cursor, or OpenCode. It works in any repository with architecture rules committed in .actual/rules/, and stays silent in repositories without them.

When does the Actual.ai Skill run?

Whenever an architecture question comes up. Before your agent writes code, it asks your ADRs how your team builds things and gets an answer that cites its sources. In Claude Code, the skill also checks the plan before implementation starts and the changes at the end of every turn.

How does the Actual.ai Skill work?

ADR-backed context

The skill runs actual adr-bot, which reads your repository, fetches your team's ADRs from Actual AI, and writes guidance tailored to your codebase into the file your agent reads: CLAUDE.md, AGENTS.md, or Cursor rules. Your agent starts every session already knowing how your team builds things.

Architecture answers

When your agent hits an architecture question, the skill asks the Actual advisor. The advisor answers from your organization's ADRs and cites its sources, so you can trace every recommendation back to a decision your team made.

Governance

In Claude Code, the skill checks your agent's work against the architecture rules committed in .actual/rules/. When your agent leaves plan mode, its plan is checked before you see the approval dialog. At the end of every turn, its changes are checked too. A conflict goes back to the agent with the reason, and the turn continues until it's fixed.

A rule file in .actual/rules/ may open with a YAML header (adr_id, a scope with root and paths, and so on). The header says which part of the repository an ADR governs, and the CLI reads it. The skill never parses it: it counts the files, hands them to the CLI, and relays what the CLI returns. A file with no header is still read in the original format. Reading headers needs actual 0.9.0 or later. On an older CLI, in a repository whose rules carry them, the checks and briefing stand down rather than act on the wrong scope, and the session start tells you to upgrade; no hook blocks, but the agent is asked to pause and offer the upgrade. Overrides are unchanged: <doc-slug>::<rule-id>.

Your agent is also briefed as it reads. When it opens a file covered by a rule, the rules governing that file are surfaced before it makes its first edit. A file it writes without reading first — usually a new one — is briefed when it writes it instead; that brief arrives with the result, after the write, so it is a reminder that can prompt a revision. Editing a file already briefed by its read adds nothing. Briefing is advisory: it never blocks anything.

Reads through the shell count too, and they are most of them. Measured across 212 local sessions, four in five file reads went through cat, head, sed -n or grep rather than the Read tool, and a hook never sees those. A Claude Code mod covers them, and where it loads it takes over the Read tool too, so both kinds of read go through one path with one context budget, one record of what has already been said, and one way of reporting it. Reading a file twice does not brief it twice, whichever way you read it. The mod needs Claude Code 2.1.287 or later; on 2.1.285 and 2.1.286 set CLAUDE_CODE_ENABLE_FUNCTION_HOOKS=1 to load it. Without it the Read path still works on its own, without the cap or the report below.

Where the mod loads, briefing is capped so it cannot crowd out your agent's context: 48,000 characters per session by default, which is roughly two and a half times what a 40-file session was measured to use against a 425-rule repository. When the cap is reached your agent is told once, rather than briefing going quietly dead.

You can see briefing happen. Each read of a governed file reports one line to the transcript, the same shape every time — a state in caps at a fixed column, then what arrived, then the files:

actual-cli: ▌ BRIEFED    2 ADRs · 8 of 35 rules    tokens.ts
actual-cli: ▌ NO CHANGE  briefed earlier  tokens.ts
  • A governed file that briefs nothing says why, rather than leaving you to guess: nothing new for it, the budget spent, or the CLI could not answer.
  • A read of files nothing governs reports nothing, once the CLI says so. Most files in a repository are ungoverned, and a line on each would bury the reads that matter. Until that ships in the CLI (actual-cli#867), such a read logs a "briefed earlier, or ungoverned" row instead.
  • /rules-brief lists the session, in the order it happened, those quiet reads included, with the reason beside each one: the last 40 of at most 200 records.

None of this governs: it never touches the Stop verdict, which is the implementation gate's. None of it costs your agent context either, because the model never reads these lines — they are not counted against the cap above. It does need a terminal or the desktop app: nothing is reported in claude -p, the SDK, the VS Code chat panel or a cloud session, though briefing itself still runs there.

Governance never gets in the way of unrelated work. Outside a repository with .actual/rules/, the checks do nothing. If the CLI is missing, outdated, or crashes, you get a message instead of a block. A rule that stays unresolved stops blocking after three denied rounds per session. To clear a denied rule for the rest of the session, run actual check-override --session <id> --rule <doc-slug>::<rule-id> --reason "..." from a terminal.

Set ACTUAL_PLAN_GATE=off to turn governance off, ACTUAL_RULES_BRIEF=off to turn off briefing alone while the checks keep running, or ACTUAL_RULES_DIR to use a different rules directory. The briefing limits have their own variables — ACTUAL_RULES_BRIEF_MAX_SESSION_CHARS for the per-session cap and ACTUAL_RULES_BRIEF_LIMIT, _RULES_PER_DECISION, _MAX_CHARS and _MIN_SCORE for actual rules brief's own limits — and the same settings appear as labelled rows under /plugin. _MIN_SCORE is worth knowing about if briefing feels noisy: a rule's score reflects how narrowly its verify path is written, so the useful floor differs per repository and there is no good default.

The hooks also stay silent inside the claude subprocesses actual itself spawns (marked with ACTUAL_CLI_SUBPROCESS=1), so the judge's own Stop hook can't rerun impl-check and recurse. Failures are silent by design, so if you need to see why briefing isn't appearing, set ACTUAL_HOOK_DEBUG=1 and run claude --debug; it reports the rules directory, the CLI's exit status, why a reply was dropped, and how much context briefing has used. Run bash hooks/tests/run.sh to test the hooks locally, and CLAUDE_CODE_ENABLE_FUNCTION_HOOKS=1 claude plugin test . to test the mod; neither needs the network or a CLI install. Governance relies on Claude Code hooks, so it isn't available in Codex, ChatGPT, Cursor, or OpenCode.

Session summary

In Claude Code, a row above the prompt shows what Actual AI has done for your agent this session: how many of your repository's ADRs it added to the agent's context, and how many folders the agent worked in that no ADR covers. It reads Actual AI: 3 of 12 ADRs added to context · 2 areas with no ADR, or Actual AI: no ADR covers the 3 areas you worked in while no ADR has been added. The CLI writes the row and the plugin shows it as given, and actual session summary --json names the folders. It reads 0 of 12 from the start of the session and updates after each of your agent's replies, in the background, so no reply waits on it. After /clear it counts the new session. Claude Code's own surveys and other plugins share that band: the row steps aside while a survey is showing, and the [-] at its right collapses the band.

It counts against the same rules directory as briefing, ACTUAL_RULES_DIR included, and shows nothing outside a repository with .actual/rules/, when the rules hold no decision, or when the CLI is missing or too old to write the row. ACTUAL_PLAN_GATE=off leaves it on. The same mod that briefs shell reads draws it, so it needs the same Claude Code: 2.1.287 or later, or 2.1.285 and 2.1.286 with CLAUDE_CODE_ENABLE_FUNCTION_HOOKS=1. The band appears in the terminal and the desktop app, and not in VS Code or claude -p. Its tests run with the mod's: CLAUDE_CODE_ENABLE_FUNCTION_HOOKS=1 claude plugin test ..

Once briefing reaches its per-session cap, the count can include the ADRs of the one brief that didn't fit: the CLI records each brief before the mod checks it against the cap, and the mod holds that one back.

Troubleshooting

When something fails, the skill diagnoses it for you. It knows every error the CLI can return, all five runners (claude-cli, anthropic-api, openai-api, codex-cli, cursor-cli), and all three output formats, so it can find the cause and retry without you reading logs.

Documentation

See the Actual CLI docs for getting started and the full command reference. Point your agent at docs.md for the same docs in Markdown.

Requirements

  • A supported coding agent: Claude Code, Codex, ChatGPT, Cursor, or OpenCode.
  • Your repository onboarded at app.actual.ai, so Actual can generate its ADRs.
  • The actual CLI 0.8.0 or later (actual-software/actual-cli). The skill offers to install it on first use, or you can install it yourself with npm install -g @actualai/actual or brew install actual-software/actual/actual. In Claude Code, each session start in a repository with rules compares the installed version with the one the skill needs and offers to upgrade an older CLI, with the command for however you installed it when the CLI can name it, or both commands when it's too old to. A declined offer doesn't come back as an interruption after a compaction or a resume.
  • Rule files with a YAML header need actual 0.9.0 or later. Upgrade with npm install -g @actualai/actual@latest or brew upgrade actual-software/actual/actual. Check with actual rules brief --help, which names adr-header-v2 on a CLI that reads them.

License

Apache-2.0

Source 1 files
hooks/register.js 1587 lines
1// register.js - Claude mod: brief the agent on the rules governing a file it
2// read, through the Read tool or through Bash.
3//
4// Why this exists beside hooks/rules-brief.sh rather than replacing it.
5// PostToolUse:Read is the delivery point rules-brief.sh uses, and it is the
6// right one -- except that across 212 sampled local sessions, 80% of file
7// reads never went through the Read tool at all. They went through `cat`,
8// `head`, `sed -n` and `grep` in Bash, which fires no Read hook. 35% of those
9// sessions used Bash more than five times and Read exactly zero times. One of
10// them (sprintreview session fb5061e2) implemented a whole feature in 35 Bash
11// calls, reached the Stop gate with three MUST conflicts, and was never
12// briefed once, because there was nothing for PostToolUse:Read to hook.
13//
14// A settings hook cannot close that gap well: it would need a second
15// PostToolUse registration on Bash, a shell-side parse of an arbitrary command
16// string, and a CLI spawn per Bash call inside a 2-second timeout. A mod gets
17// the command string as data, runs in-process, and spends its CLI time inside
18// $.process.run, which the hook time limit explicitly excludes.
19//
20// Division of labour with rules-brief.sh: this mod hooks both Read and Bash,
21// and where it loads it stands the hook down for Read (STAND_DOWN_FIELD, below)
22// so one brief is delivered once, by the path that has a budget and a record.
23// The hook remains for versions of Claude Code that cannot load a mod. The mod deliberately
24// synthesizes a PostToolUse:Read envelope and calls `actual rules brief
25// --claude-hook` rather than the simpler `--file` direct mode, because
26// --claude-hook is what consults brief memory. Both paths therefore share one
27// dedup store and a file read with `cat` after a Read tool call is not briefed
28// twice. Direct mode is stateless (verified: same file twice returns the full
29// brief both times), so using it here would have meant a second, parallel
30// dedup store in the mod.
31//
32// Advisory by construction, like the hook. It never denies, never rewrites a
33// command, and never changes a tool result: a brief goes beside the result, in
34// the call's `context`. Every failure path leaves the result exactly as the
35// tool produced it. There is
36// deliberately no .catch handler: a .catch makes a hook fail closed, which is
37// right for a gate and wrong for this.
38
39// Phase 1 scope: the plumbing, plus the two facts a real session established
40// that no amount of reasoning would have. Both were found by probing an actual
41// `claude -p` run, and both corrected a guess:
42//
43//  1. Where a brief goes. A tool.call result's `context` is what the model
44//     reads after the tool's result. Probed on 2.1.287 with a marker for both
45//     Read and Bash: the model received each as its own system reminder
46//     ("tool.call hook additional context"), and the transcript recorded it
47//     as a hook_additional_context attachment beside an untouched tool result
48//     -- the channel a PostToolUse hook's additionalContext uses. An earlier
49//     version appended the brief to result.stdout and result.file.content
50//     instead, which put rule text inside the file as the model read it and
51//     inside the tool result the transcript kept.
52//  2. Claude Code already classifies each Bash command: `isReadOnly` is true
53//     for `cat a.txt` and `sed -n 1p a.txt`, and absent for `echo written >
54//     b.txt`. That is the read-vs-write signal Phase 2 was going to build a
55//     regex for, supplied by the permission system itself.
56//
57// So classification is not ours to guess. We brief a Bash call only when
58// Claude Code says it was read-only, which is both broader than a command
59// allowlist (it covers `grep -n file`, pipes, and spellings nobody enumerated)
60// and safer: a command Claude Code cannot classify leaves isReadOnly absent,
61// and absent means no brief.
62//
63// Briefing only read-only commands also settles a design question with
64// evidence. A write-shaped command has already composed its replacement text
65// by the time it exists, so briefing it could only prompt a revision -- which
66// is impl-gate.sh's job. Only a read can be briefed before the edit is
67// written, which is the whole point of delivering at read time.
68//
69// What Phase 2 still owes: better *path* extraction -- heredoc bodies, more
70// than one path per command -- not classification.
71//
72// Edit and Write are the one exception to "only a read", and a narrow one
73// (AK-794). Claude Code makes the agent Read a file before editing or
74// overwriting it, so for an existing file the Read brief has already landed
75// and the CLI answers the edit with silence. What is left is a file written
76// without a Read -- mostly a new one from Write -- which no read-time brief
77// could ever reach. Its brief lands with the tool result, after the write ran,
78// so it is a reminder that can prompt a revision, not a briefing ahead of the
79// work. The Bash write path stays unbriefed: a shell write names its file
80// inside an arbitrary command string, and the Stop gate covers it.
81
82// --- Path extraction ---------------------------------------------------
83//
84// What this has to get right, measured against the 35 Bash calls of one real
85// session (sprintreview fb5061e2) and a live probe of isReadOnly:
86//
87//   cat a.ts                              one path
88//   cat a.ts b.ts                         read-only, TWO paths
89//   cat a.ts | head -3                    read-only, pipe
90//   cd /abs/dir && cat rel/a.ts           read-only, path relative to /abs/dir
91//   grep -n class a.ts                    read-only
92//   sed -n 1,2p a.ts                      read-only
93//
94// 11 of those 35 calls (31%) began with `cd <dir> &&`, every one of them with
95// an absolute target, and the targets were not all the repo root -- one was
96// apps/actual. A path in such a command resolves against the cd target, not
97// the session's cwd, so ignoring the prefix means either missing the file or,
98// worse, resolving to a different file that happens to exist at the same
99// relative path.
100
101// A token that could be a path with an extension. No `*`, so a glob such as
102// `src/*.ts` is not mistaken for a file. No quotes, so `sed -n '1,2p'` and a
103// quoted path with a space are both passed over -- the latter is a known and
104// accepted miss.
105//
106// The extension must begin with a letter. Running this over 35 real Bash
107// commands, the version string in `echo "=== jwt 9.0.3 API evidence ==="`
108// matched a digits-allowed pattern and became a candidate path; `.ts`, `.md`,
109// `.json`, `.cjs`, `.tf`, `.yaml` and `.d.ts` all still match.
110//
111// A leading `/` or `~/` is allowed. Without it every absolute path was
112// rejected, because the first character had to be a word character or a dot --
113// and Claude Code's Bash tool writes absolute paths freely. A reported session
114// ran `sed -n '1,20p' /Users/.../app/lib/query-keys.ts` and two `cat`s of
115// absolute paths, and all three briefed nothing while the same reads written
116// relatively briefed correctly, which made the whole feature look intermittent.
117const PATH_TOKEN = /^(\/|~\/)?[\w.][\w./-]*\.[A-Za-z][A-Za-z0-9]{0,5}$/;
118
119// How many files one command may brief. A command reading six files would
120// otherwise inject six briefs at once, which is the volume question Phase 3
121// still owes an answer to; until then, cap it low.
122const MAX_PATHS_PER_COMMAND = 2;
123
124// Peel any leading `cd <dir> &&` chain off the front and report the directory
125// the rest of the command actually runs in. Only a leading chain counts: a
126// `cd` later in the pipeline changes the base partway through, and guessing
127// which half a path belongs to is worse than declining, so that returns null.
128function resolveBase(command) {
129  let rest = command.trim();
130  let base = null;
131  for (;;) {
132    // `&&` or `;`, and a `cd` that ends the command has neither. A bare
133    // `cd apps/web` was previously not a base at all: the regex needed a
134    // separator, so the loop never matched, the `cd` was still in `rest`, and
135    // the ambiguity check below threw the whole command away. The shell kept
136    // the new directory and this mod did not, so every later relative path
137    // resolved against the wrong base.
138    const m = /^cd\s+("[^"]+"|'[^']+'|[^\s&|;]+)\s*(?:&&|;|$)\s*/.exec(rest);
139    if (!m) break;
140    const target = m[1].replace(/^["']|["']$/g, '');
141    // Successive `cd`s compose, as the shell composes them: `cd a && cd b`
142    // ends in `a/b`, not `b`. Overwriting made the second one win, which put
143    // the base one directory too shallow for the rest of the session.
144    base = base === null || target.startsWith('/') ? target : joinPath(base, target);
145    rest = rest.slice(m[0].length);
146  }
147  // A `cd` anywhere in what is left makes the base ambiguous.
148  if (/(^|[\s&|;])cd\s/.test(rest)) return null;
149  // Everything from a heredoc marker on is the body of a document, not argv.
150  // Scanning it finds property accessors -- `jwk.kid`, `claims.jti` -- that
151  // look exactly like dotted paths. Those commands are never briefed anyway,
152  // because Claude Code does not mark a heredoc read-only (probed live, even
153  // for one that only reads and prints), but the extractor should not be
154  // inventing candidates it would then have to filter.
155  const heredoc = rest.indexOf('<<');
156  if (heredoc !== -1) rest = rest.slice(0, heredoc);
157  return { base, rest };
158}
159
160// Join a possibly-relative token onto a base directory, without importing
161// path: a mod's whole dependency surface is the mods API, same hygiene rule
162// the shell hooks follow for jq and python.
163function joinPath(base, token) {
164  if (token.startsWith('/')) return token;
165  return `${base.replace(/\/+$/, '')}/${token}`;
166}
167
168// Collapse `.` and `..` segments so containment can be checked as a string
169// prefix. A token that climbs above its base is left with leading `..`, which
170// no absolute root prefixes, so it is rejected by the containment test rather
171// than needing its own branch.
172function normalizePath(p) {
173  const out = [];
174  for (const seg of p.split('/')) {
175    if (seg === '' || seg === '.') continue;
176    if (seg === '..') out.pop();
177    else out.push(seg);
178  }
179  return (p.startsWith('/') ? '/' : '') + out.join('/');
180}
181
182function isWithin(root, candidate) {
183  const r = normalizePath(root).replace(/\/+$/, '');
184  if (r === '' || r === '/') return true;
185  return candidate === r || candidate.startsWith(`${r}/`);
186}
187
188// Why a file a Read, Edit or Write names outright is not worth a spawn, or
189// null when it is: the Bash path's two filters, for the tools that skip its
190// parsing. Without them every scratchpad write -- Claude Code keeps one under
191// TMPDIR -- and every edit of a rule document spawned the CLI to hear "no".
192//
193// Outside only when outside the root, the session's directory and the
194// session's project root alike. The root can be git's physical path while
195// Claude names files by the logical one a symlinked checkout was opened
196// through; a test against the root alone would skip governed files there,
197// silently. The cwd covers that until the shell runs `cd apps/web`, after
198// which a file elsewhere in the checkout is under neither; the project root
199// ($.session.root()) is the logical path the session was opened at, or the
200// one `/cd` or a worktree move took it to, and a shell `cd` does not move it.
201// A file inside the rules directory is a rule document, which is not governed
202// by itself.
203function unbriefable(named, { repoRoot, cwd, sessionRoot, rulesDir }) {
204  if (![repoRoot, cwd, sessionRoot].filter(Boolean).some((base) => isWithin(base, named))) return 'outside-root';
205  if (rulesDir && isWithin(rulesDir, named)) return 'ungoverned';
206  return null;
207}
208
209// The Bash tool runs every command in ONE persistent shell, so a `cd` in any
210// call changes the directory every later call runs in. On Claude Code 2.1.296
211// `$.session.cwd()` follows that shell: after `cd apps/actual && ls lib/oauth`
212// the next call reads `<repo>/apps/actual`. That is why nothing is tracked
213// here -- the cwd read after a call is already where the shell ended up, and
214// the only arithmetic left is for the call that did the `cd`, whose relative
215// target must be joined onto the directory the call STARTED in (see the
216// tool.call handler). A copy of the shell's directory kept here drifted from
217// the real one on every failed `cd`, and doubled every relative one.
218//
219// Perfect shell emulation is not the goal and not achievable -- a `cd` buried
220// in a pipeline, a shell variable, a subshell -- so the resolver treats the
221// shell's directory as the first guess among several rather than the truth.
222
223// Candidate path tokens, plus the directory a leading `cd` chain moved to.
224// Resolution is left to the caller, which can check what exists; this stays a
225// pure function so the corpus of real commands can be replayed against it.
226function candidateTokens(command) {
227  if (typeof command !== 'string' || command.length === 0) return null;
228  const split = resolveBase(command);
229  if (!split) return null;
230
231  const tokens = [];
232  const seen = new Set();
233  // Skip argv[0] of each pipeline stage: `cat`, `head`, `grep` are not paths,
234  // and a tool name with a dot (`a.out`) would otherwise look like one.
235  for (const stage of split.rest.split(/\||&&|;/)) {
236    for (const token of stage.trim().split(/\s+/).slice(1)) {
237      if (token.startsWith('-')) continue;
238      if (!PATH_TOKEN.test(token)) continue;
239      if (seen.has(token)) continue;
240      seen.add(token);
241      tokens.push(token);
242    }
243  }
244  return { cdTarget: split.base, tokens };
245}
246
247// Under ACTUAL_HOOK_DEBUG, say what briefing decided -- including, and
248// especially, when it decided nothing. The first version of this reported only
249// from the point where a brief was already being appended, which left every
250// case worth debugging silent: a command that was not read-only, a token that
251// resolved to nothing, a spent budget, and a mod that never loaded all looked
252// identical from a transcript. Three sessions were spent unable to tell them
253// apart. The line rides out in the call's context, which the session
254// transcript records even under `claude -p`, where $.ui.log does not reach.
255// The model reads it too, so it is debug-gated.
256async function debugNote($, outcome, detail) {
257  const enabled = await $.env.get('ACTUAL_HOOK_DEBUG');
258  if (!enabled) return '';
259  return `actual rules brief [debug]: ${outcome}${detail ? ` -- ${detail}` : ''}`;
260}
261
262// Hand text to the model beside a tool's result, never inside it, so the
263// result is the same whatever the tool's shape. Entries already there are
264// kept: a hook beneath hands its context over whole. Returns the result
265// untouched when there is no text, so the quiet path allocates nothing.
266function withContext(result, text) {
267  if (!text) return result;
268  return { ...result, context: [...(result.context ?? []), text] };
269}
270
271// --- What the user sees ---------------------------------------------------
272//
273// The brief itself has to reach Claude, so it rides in the tool result and
274// costs context -- which is why there is a session budget at all. What a
275// *person* needs is different: whether a brief happened, what it covered, and
276// when one did not, why. A `$.ui.log` row or the pane costs nothing,
277// because they go to the terminal and the Desktop app and Claude never reads
278// them. So everything below is free, and none of it is in the budget.
279//
280// It is also not a substitute for the brief: nothing shows in `claude -p`, the
281// SDK, the VS Code chat panel or a cloud session (hooks still run there). The
282// report is for the person watching, and there is no person watching those.
283
284// One record per Bash tool call, keyed by its tool_use_id, so a call's
285// report and the pane's row are the same record. Bounded: a long session makes
286// thousands of tool calls and this is a convenience, not a log.
287const MAX_OUTCOMES = 200;
288// A quiet read's own outcome name, when every file was quiet for one reason.
289// `already-briefed` is left out on purpose: that is the `deduped` row, whose
290// line can also speak for a mixed call.
291const QUIET_OUTCOMES = {
292  ungoverned: 'ungoverned',
293  'nothing-to-show': 'no-text',
294  'outside-root': 'outside-root',
295  'no-rules': 'no-rule-set',
296};
297
298// Reasons the mod has a wording for. A token outside this set is one a newer
299// CLI named, such as a rule document whose status excludes it: shown as the
300// CLI said it rather than as a reason it did not give.
301const KNOWN_REASONS = new Set(['already-briefed', 'unknown', ...Object.keys(QUIET_OUTCOMES)]);
302const isUnrecognised = (reason) => !KNOWN_REASONS.has(reason);
303
304// Per session, not per process. `spent` and `repoRoots` are both
305// keyed by session and this was not, so a pane headed "this session" listed
306// reads from before a `/clear` -- and from any other session sharing the
307// process -- as though they were this one's.
308// Sessions that have already been told the budget is spent.
309const budgetAnnounced = new Set();
310const v2Announced = new Set();
311
312const outcomes = new Map();
313
314function outcomesFor(sessionId) {
315  let own = outcomes.get(sessionId);
316  if (!own) {
317    own = new Map();
318    outcomes.set(sessionId, own);
319  }
320  return own;
321}
322
323function recordOutcome(sessionId, toolUseId, record) {
324  if (!toolUseId) return;
325  const own = outcomesFor(sessionId);
326  own.set(toolUseId, { at: Date.now(), ...record });
327  while (own.size > MAX_OUTCOMES) {
328    own.delete(own.keys().next().value);
329  }
330}
331
332// Read the shape back out of a brief for the one-line summary. Best effort by
333// construction: this parses the CLI's human-readable text, which is not a
334// contract, so every field is optional and a parse that finds nothing yields a
335// character count instead. A summary is cosmetic -- it must never be able to
336// affect whether the brief itself was delivered.
337function summarize(brief) {
338  const decisions = [];
339  let current = null;
340  for (const line of brief.split('\n')) {
341    if (line.startsWith('## ')) {
342      current = { title: line.slice(3).trim(), shown: 0, total: 0 };
343      decisions.push(current);
344    } else if (/^- \[/.test(line)) {
345      if (current) current.shown += 1;
346    } else {
347      // The CLI's own truncation note, which is per decision: the rules listed
348      // above it are `shown`, and `total` is how many that decision really has.
349      const more = /^- \((\d+) of (\d+) rules shown\)/.exec(line);
350      if (more && current) current.total = Number(more[2]);
351    }
352  }
353  // A decision with no note is shown in full, so its total is what it listed.
354  for (const d of decisions) if (!d.total) d.total = d.shown;
355  return {
356    decisions: decisions.map((d) => d.title),
357    shown: decisions.reduce((n, d) => n + d.shown, 0),
358    total: decisions.reduce((n, d) => n + d.total, 0),
359    chars: brief.length,
360  };
361}
362
363// `1 rule`, `2 rules`: the brief that names one rule says so.
364function counted(n, noun) {
365  return `${n} ${noun}${n === 1 ? '' : 's'}`;
366}
367
368// The transcript row for one call. Null for the calls worth saying nothing
369// about -- a command that read no governed file is the overwhelming majority,
370// and a line on every one of them would be noise rather than information.
371// The sentence for one call's outcome, without a prefix: $.ui.log adds the
372// plugin's name itself.
373//
374// Reported through $.ui.log alone. An earlier version also drew the line under
375// the tool call through `ui.render`, which looked better placed but could not
376// be relied on -- Claude Code collapses some calls into a summary row whose id
377// is not the call's, so the line vanished. Keeping both channels meant every
378// expanded call reported its brief twice, once in each, which a real session
379// showed six times over. One channel that always works beats two that
380// sometimes do.
381function names(files) {
382  return files.map((f) => f.split('/').pop()).join(', ');
383}
384
385// A row's three columns: a state in caps, what it amounted to, then the files.
386//
387// The host draws every one of these as `⏺ actual-cli: <text>` at one dim
388// weight -- $.ui.log carries text and nothing else, no colour and no bold -- so
389// the only way to make a row findable is its shape. A bar glyph gives a column
390// of rows a left edge, and a fixed-width state in caps puts the same word in
391// the same place every time, so a scan down the transcript lands on it without
392// reading the sentence.
393//
394// The state is padded to the longest of them, which is why the detail and the
395// files line up across rows of different kinds.
396const STATE_WIDTH = 9;
397
398function row(state, detail, files) {
399  const columns = [state.padEnd(STATE_WIDTH), detail];
400  if (files) columns.push(`  ${files}`);
401  return `\u258c ${columns.join('  ')}`;
402}
403
404function reportLine(record) {
405  if (!record) return null;
406  const files = names(record.files ?? []);
407  switch (record.outcome) {
408    case 'delivered': {
409      const s = record.summary ?? {};
410      const n = s.decisions?.length ?? 0;
411      // A brief whose text did not parse still reports its size: the count is
412      // the one thing always known, and "0 ADRs" reads as a failure.
413      if (n === 0) return row('BRIEFED', `${s.chars ?? 0} chars`, files);
414      const rules =
415        s.total && s.total > s.shown
416          ? `${s.shown} of ${counted(s.total, 'rule')}`
417          : counted(s.shown ?? 0, 'rule');
418      return row('BRIEFED', `${counted(n, 'ADR')} \u00b7 ${rules}`, files);
419    }
420    case 'deduped': {
421      // Only the files this row can speak for. `unknown` is a CLI too old to
422      // name a reason, which keeps both meanings rather than picking one.
423      const by = (want) =>
424        (record.files ?? []).filter((f) => ((record.reasons ?? {})[f] ?? 'unknown') === want);
425      const known = by('already-briefed');
426      const unsure = by('unknown');
427      const other = (record.files ?? []).filter((f) => isUnrecognised((record.reasons ?? {})[f] ?? 'unknown'));
428      const groups = [];
429      if (known.length) groups.push(`briefed earlier  ${names(known)}`);
430      if (unsure.length) groups.push(`briefed earlier, or ungoverned  ${names(unsure)}`);
431      if (other.length) {
432        const tokens = [...new Set(other.map((f) => record.reasons[f]))].join(', ');
433        groups.push(`no brief (${tokens})  ${names(other)}`);
434      }
435      if (groups.length === 0) return null;
436      return row('NO CHANGE', groups.join('  \u00b7  '));
437    }
438    case 'ungoverned':
439    case 'no-text':
440    case 'outside-root':
441    case 'no-rule-set':
442      // Quiet for a reason that is not about this read: see the pane, which
443      // names all four.
444      return null;
445    case 'budget':
446      // Reported once by deliverBrief when the budget runs out, not per read.
447      return null;
448    case 'cli-error':
449      return row('CLI ERROR', record.detail ?? 'CLI error', files);
450    default:
451      return null;
452  }
453}
454
455// --- Session budget -----------------------------------------------------
456//
457// Dedup (shared with the hook, via brief memory) stops the same decision being
458// briefed twice. What it cannot bound is accumulation: a session that touches
459// many governed files collects many distinct decisions. Measured over three
460// real rule sets -- 425, 183 and 219 documents -- a 40-file session accumulates
461// 12 to 18 distinct decisions, so roughly 20-30 KB of injected context, and
462// 87-100% of sampled files were governed by at least one rule.
463//
464// `--min-score` cannot substitute for a cap. Its scores form a fixed lattice
465// of 0.75 x {1, 1.5, 2, 3, 4} -- five rungs, identical in all three corpora --
466// and the score measures how narrowly a rule's `verify` glob was written
467// (`ai/**` scores 0.75, `ai/src/mastra/workflows/**/*.ts` scores 3.00), not how
468// relevant the rule is. So one threshold behaves differently everywhere: a
469// 1.50 floor cuts 70% in one repo, 23% in another and 0% in a third. It stays
470// a per-repo escape hatch (`config set --repo rules_min_score`), not a lever
471// this mod can set on anyone's behalf.
472//
473// Hence a hard per-session character cap. It stops rather than truncates: the
474// CLI's own --max-chars already drops whole rules from a single brief and says
475// how many it left out, and a brief cut mid-rule is worse than no brief -- a
476// half-printed MUST can read as permission.
477
478// Measured, not guessed. Against the 425-rule corpus with dedup active, 40
479// governed files injected 18,751 characters -- and only 8 of those 40 reads
480// produced a brief at all, the other 32 being decisions already delivered.
481// Accumulation over that run: 9,039 chars at 10 files, 10,841 at 20, 12,573 at
482// 30, 18,751 at 40.
483//
484// A first guess of 20,000 was wrong: it sits at 94% of the 40-file figure, so
485// it would have started dropping briefs in ordinary sessions rather than
486// catching runaway ones. This cap exists for pathology -- a session crossing
487// hundreds of governed files in many rule areas -- not for tuning relevance,
488// which is what dedup and the CLI's own limits are for. 48,000 is about 2.5x
489// the measured normal case: roughly 12,000 tokens, or 6% of a 200k context
490// window, which is a defensible ceiling for governance context and still stops
491// an unbounded climb.
492const DEFAULT_MAX_SESSION_CHARS = 48000;
493
494// Per-session totals, keyed by session id so a reload or a second session in
495// one process starts clean rather than inheriting a spent budget.
496const spent = new Map();
497
498function spendable(sessionId, cap) {
499  const used = spent.get(sessionId) ?? 0;
500  return Math.max(0, cap - used);
501}
502
503function spend(sessionId, chars) {
504  spent.set(sessionId, (spent.get(sessionId) ?? 0) + chars);
505}
506
507// Said once, on the call that exhausts the budget. Briefing that simply stops
508// is the silent-degradation failure this plugin already has one of too many:
509// a brief that never arrives is indistinguishable from a file no rule governs.
510// One short line makes the difference legible and tells the agent what to do.
511const EXHAUSTED_NOTICE =
512  'Actual rule briefing has reached its per-session context budget and will ' +
513  'stay quiet from here. Run `actual rules brief --file <path>` if you need ' +
514  'the rules for a specific file.';
515
516// The one allowlisted shape, as a parse rather than a byte match. The hook has
517// to do this with shell parameter expansion and needs five guards to pin the
518// shape (see rules-brief.sh); here it is a property read, and every other
519// field the CLI might emit -- a decision, continue, a permissionDecision --
520// is ignored because it is simply never looked at.
521function briefFrom(stdout) {
522  if (!stdout) return '';
523  let parsed;
524  try {
525    parsed = JSON.parse(stdout);
526  } catch {
527    return '';
528  }
529  const context = parsed?.hookSpecificOutput?.additionalContext;
530  return typeof context === 'string' ? context : '';
531}
532
533// hook_event_name is load-bearing: an envelope without it returns nothing at
534// all. session_id is load-bearing differently -- without it the CLI still
535// briefs, but silently stops consulting brief memory, so every read of a
536// governed file would brief again.
537//
538// agent_id is the third component of brief memory's key, and omitting it is
539// worse than a duplicate brief. A subagent runs with its own context, so a
540// decision briefed to the parent has not been shown to it -- which is exactly
541// why the CLI keys on it (see brief_memory.rs). Probed in a real subagent, the
542// Read hook's envelope carries `agent_id` and this mod's event carries the
543// same value as `e.agentId`. Leaving it out filed the subagent's reads under
544// the parent's slot, so the subagent would be denied a brief the parent had
545// already seen, and the parent would later miss one it never saw. All three
546// fields are asserted in the tests.
547//
548// The event and tool are what the call was: a Bash or Read call is a
549// PostToolUse:Read, an Edit or Write call is a PreToolUse on that tool -- the
550// two pairs the CLI answers, and the ones hooks/rules-brief.sh forwards. The
551// CLI keeps one brief memory across both, so a file briefed by either is not
552// briefed again by the other.
553function envelopeFor({ sessionId, agentId, cwd, filePath, tool = 'Read' }) {
554  const write = WRITE_TOOLS.includes(tool);
555  const envelope = {
556    session_id: sessionId,
557    cwd,
558    hook_event_name: write ? 'PreToolUse' : 'PostToolUse',
559    tool_name: write ? tool : 'Read',
560    tool_input: { file_path: filePath },
561  };
562  if (!write) envelope.tool_response = { type: 'text' };
563  // Omitted rather than sent empty for the main agent, matching the hook: the
564  // CLI treats an absent and an empty agent_id the same, but an envelope that
565  // mirrors the real one is easier to reason about.
566  if (agentId) envelope.agent_id = agentId;
567  return JSON.stringify(envelope);
568}
569
570// Every tunable is readable two ways: a `userConfig` field, which gives the
571// operator a labelled row in the plugin's settings, and an environment
572// variable, which an operator can set for one session without editing
573// settings. Env wins, the same precedence the three switches above use.
574//
575// Two reasons it is not userConfig alone. The plugin already established the
576// ACTUAL_* convention for exactly this, and `userConfig` values arrive in
577// register()'s `options` at load time, which no test harness in this build can
578// inject -- a tunable nothing can test is a tunable that quietly stops working.
579// Each env name is written as a literal at its call site, not composed from a
580// prefix, and the reads sit in one plain function rather than behind a table of
581// closures. Claude Code enforces both: `$.env.get` refuses a template with a
582// substitution, and `$` may only be passed to a function declared at the top of
583// the file. The point is that the variables a mod reads can be listed without
584// running it -- `claude plugin validate` prints them, which is the whole reason
585// that output is worth showing a security reviewer.
586async function readEnvSettings($) {
587  const [maxSessionChars, limit, rulesPerDecision, maxChars, minScore] = await Promise.all([
588    $.env.get('ACTUAL_RULES_BRIEF_MAX_SESSION_CHARS'),
589    $.env.get('ACTUAL_RULES_BRIEF_LIMIT'),
590    $.env.get('ACTUAL_RULES_BRIEF_RULES_PER_DECISION'),
591    $.env.get('ACTUAL_RULES_BRIEF_MAX_CHARS'),
592    $.env.get('ACTUAL_RULES_BRIEF_MIN_SCORE'),
593  ]);
594  return { maxSessionChars, limit, rulesPerDecision, maxChars, minScore };
595}
596
597// The rules directory to govern against. This has to agree with
598// bootstrap.sh's rules_dir() exactly, not approximately: brief memory is keyed
599// on session_id + agent_id + rules_dir, so any divergence means one read
600// briefs twice -- and in a monorepo the mod also governs against the wrong
601// rule set. Measured on a fixture whose root and subproject rule sets both
602// match one file, before this was forwarded at all: the hook briefed the
603// subproject's R-API-001 and the mod, same session, briefed the root's
604// R-ROOT-001.
605//
606// No single mods API call gives that agreement, which four probed layouts
607// settled:
608//
609//   layout                           hook        $.session.root()  repo().root
610//   worktree under the project root  worktree    worktree   OK     main repo  X
611//   worktree + CLAUDE_PROJECT_DIR    worktree    worktree   OK     main repo  X
612//   monorepo subproject as project   subproject  subproject OK     outer repo X
613//   launched in a subdirectory       that subdir that subdir OK     git root   X
614//
615// $.session.root() tracks the session's working directory, so it is right for
616// a worktree and right one directory down too: the hook resolves that
617// subdirectory as well, because CLAUDE_PROJECT_DIR names it. repo().root is
618// the main checkout, so it is wrong in every row.
619//
620// The last row was recorded the other way round here, on the assumption that
621// the hook picks the git root. It does not, and a test that asserted it kept
622// the error in place. Measured in a live session: with the subproject as the
623// project directory, a Read briefed the subproject's decision and a `cat` of
624// the same file briefed two of the root's, 3,296 characters, and the model
625// received both.
626//
627// So the mod asks git the same question the hook asks, and applies the same
628// rule: when CLAUDE_PROJECT_DIR and the git toplevel are nested, the deeper
629// path is the more specific context and wins; otherwise the active checkout
630// does. See resolve_repo_root in bootstrap.sh for why each case is that way.
631// One git spawn per session and project root, cached. `/cd` and a worktree
632// move change $.session.root() and a shell `cd` does not, so only a real move
633// asks again.
634
635const repoRoots = new Map();
636
637// Per process, unlike the maps around it: the first $.session.root() this load
638// of the module resolves, which the count's reading at session start makes
639// before anything can move the session. CLAUDE_PROJECT_DIR stays there for the
640// gates through `/cd`, a worktree move and `/clear`, and this stands in for it.
641let launchRoot;
642
643// Every spawn's timeout: the PostToolUse:Read hook's own budget in hooks.json.
644// $.process.run waits 30 seconds when given none, and the hook time limit does
645// not cover it, so a CLI that hangs would stall every read for that long. A
646// spawn that times out does not return: `$.process.run` rejects, as it does
647// when the command cannot start, so each caller catches it.
648const SPAWN_TIMEOUT_MS = 2000;
649
650function deeperOf(projectDir, gitRoot) {
651  if (!projectDir) return gitRoot;
652  if (!gitRoot) return projectDir;
653  const p = projectDir.replace(/\/+$/, '');
654  const g = gitRoot.replace(/\/+$/, '');
655  if (g === p) return g;
656  if (g.startsWith(`${p}/`)) return g; // worktree: nested under the project
657  if (p.startsWith(`${g}/`)) return p; // monorepo: subproject inside the repo
658  return g; // unrelated: the active checkout wins
659}
660
661// `~` expanded once per session. PATH_TOKEN accepts a `~/` token, and without
662// this `joinPath` made it `<base>/~/repos/...`, which exists nowhere -- so the
663// pattern offered a candidate that could never resolve. It matters because a
664// checkout usually does sit under the home directory, so `cat ~/repos/x/a.ts`
665// names a file this mod governs.
666const homeDirs = new Map();
667
668async function resolveHome($, sessionId) {
669  if (homeDirs.has(sessionId)) return homeDirs.get(sessionId);
670  let home = null;
671  try {
672    home = (await $.env.get('HOME')) || null;
673  } catch {
674    // No HOME: a `~` token simply stays unresolvable, as before.
675  }
676  homeDirs.set(sessionId, home);
677  return home;
678}
679
680// Whether the installed CLI has `rules brief` at all, asked once a session
681// with `actual rules brief --help`. actual-cli v0.6.2 and older answer
682// `unrecognized subcommand` with exit 2 -- and without this every read in a
683// governed repository logged a CLI ERROR row for a state the person cannot do
684// anything about mid-turn. Preflight already tells the agent once to upgrade.
685//
686// Only a definite answer is kept. A probe that times out says nothing about
687// the CLI, so the next read asks again.
688const briefAvailable = new Map();
689
690// What the same probe learned about ADR header v2 (AK-963): whether the CLI's
691// `rules brief --help` names the capability marker. Set beside briefAvailable,
692// so it is as definite as that answer is.
693const ADR_V2_MARKER = 'adr-header-v2';
694const briefReadsV2 = new Map();
695// Whether the rule files carry a v2 header, per session and rules directory, with
696// the listing signature the answer was made under.
697const rulesAreV2 = new Map();
698
699// The rule files governedRulesDir last saw in each directory, and a signature of
700// their names, sizes and mtimes, so the ADR header v2 check reads them without
701// listing the directory a second time and knows when its answer has gone stale.
702const ruleFileListing = new Map();
703
704async function rulesBriefAvailable($, sessionId, cwd) {
705  if (briefAvailable.has(sessionId)) return briefAvailable.get(sessionId);
706  let ok = false;
707  let definite = true;
708  try {
709    const run = await $.process.run(['actual', 'rules', 'brief', '--help'], {
710      cwd,
711      timeoutMs: SPAWN_TIMEOUT_MS,
712    });
713    ok = run.exitCode === 0;
714    // The same capability marker bootstrap.sh's have_adr_v2 reads: the help of
715    // a CLI that parses the ADR header v2 names it.
716    briefReadsV2.set(sessionId, ok && (run.stdout ?? '').includes(ADR_V2_MARKER));
717  } catch {
718    // Cannot start (no `actual` on PATH) or still running at the timeout. The
719    // first is as definite as an exit code; the second is not distinguishable
720    // from it here, so neither is cached against the session for good.
721    definite = false;
722  }
723  if (definite) briefAvailable.set(sessionId, ok);
724  return ok;
725}
726
727// A session's probe answer is kept while it is positive. A negative one (no
728// marker, no `rules brief`, or no answer) is dropped at the end of each turn, so
729// a CLI upgraded mid-session is noticed by the next governed read, as it is by
730// the shell hooks. Costs one `--help` spawn a turn while the CLI stays old.
731async function forgetNegativeProbe($) {
732  try {
733    const sessionId = await $.session.id();
734    if (!sessionId || briefReadsV2.get(sessionId) === true) return;
735    briefAvailable.delete(sessionId);
736    briefReadsV2.delete(sessionId);
737  } catch {
738    // Nothing to forget without a session; the next read probes as usual.
739  }
740}
741
742// True when `text` opens with an ADR header v2: the rule the CLI's own parser
743// applies (frontmatter_end in actual-cli's src/rules/parse.rs, which is the
744// source of truth and should be read before changing this). A leading UTF-8 BOM
745// is ignored; the first line is `---` once trailing whitespace is trimmed; a
746// closing `---` follows; and no line between them is an unindented ATX heading,
747// because a block with a heading in it is a markdown horizontal rule and the
748// parser reads the file as v1. Mirrors rules_file_has_v2_header in bootstrap.sh.
749function hasV2Header(text) {
750  const lines = text.replace(/^\uFEFF/, '').split('\n').map((l) => l.replace(/\r$/, ''));
751  if (lines[0].trimEnd() !== '---') return false;
752  let heading = false;
753  for (const line of lines.slice(1)) {
754    if (line.trimEnd() === '---') return !heading;
755    if (!/^\s/.test(line) && /^#{1,6} /.test(line.trimEnd())) heading = true;
756  }
757  return false;
758}
759
760// True when the rule files carry an ADR header v2 and the installed CLI cannot
761// read it, so a brief built from them would be wrong. Mirrors adr_v2_unsupported
762// in bootstrap.sh: the same header test, the same silent pass for v1
763// repositories and for a CLI that names the marker. Call after
764// rulesBriefAvailable, which is what learns the marker.
765//
766// The files are read in-process (no spawn), and only when the CLI lacks the
767// marker, so a current CLI and a v1 repository on a current CLI pay nothing.
768// The answer is cached against the directory listing governedRulesDir already
769// fetched on this call (names, sizes, mtimes), so it holds while the rule files
770// do and is asked again the moment one is added, removed or rewritten: a
771// repository converted to v2 mid-session is caught on the next read, as the
772// shell hooks catch it.
773async function adrV2Unsupported($, sessionId, rulesDir) {
774  if (briefReadsV2.get(sessionId)) return false;
775  const listing = ruleFileListing.get(rulesDir);
776  const key = `${sessionId}\n${rulesDir}`;
777  const cached = rulesAreV2.get(key);
778  if (cached && cached.signature === listing?.signature) return cached.v2;
779  let v2 = false;
780  let unreadable = false;
781  for (const name of listing?.names ?? []) {
782    let text;
783    try {
784      text = String(await $.fs.read(`${rulesDir}/${name}`));
785    } catch {
786      // Skip the file and go on, as the CLI does (it records an unreadable rule
787      // file and keeps discovering) and the shell loop does: one bad file must
788      // not hide a v2 header in the next one.
789      unreadable = true;
790      continue;
791    }
792    if (hasV2Header(text)) {
793      v2 = true;
794      break;
795    }
796  }
797  // An answer reached past a file it could not read is not cached, so the next
798  // read tries that file again.
799  if (!unreadable) rulesAreV2.set(key, { signature: listing?.signature, v2 });
800  return v2;
801}
802
803async function resolveRepoRoot($, sessionId, cwd) {
804  const sessionRoot = await $.session.root();
805  if (!launchRoot) launchRoot = sessionRoot;
806  const key = `${sessionId}\n${sessionRoot}`;
807  if (repoRoots.has(key)) return repoRoots.get(key);
808  let gitRoot = null;
809  try {
810    // Run in the root the answer is cached under, not the caller's cwd: the
811    // first call after a move can come from wherever the shell has gone.
812    const run = await $.process.run(['git', 'rev-parse', '--show-toplevel'], {
813      cwd: sessionRoot || cwd,
814      timeoutMs: SPAWN_TIMEOUT_MS,
815    });
816    if (run.exitCode === 0) gitRoot = (run.stdout ?? '').trim() || null;
817  } catch {
818    // Not a repository, or no git. Fall through to the project dir.
819  }
820  // CLAUDE_PROJECT_DIR is set for hook processes, not for a mod, so this read
821  // returns nothing in a live session and `deeperOf` fell back to the git root
822  // every time -- which is how the mod came to brief a monorepo subproject
823  // from the root's rule set while the hook briefed it from the subproject's.
824  // The launch root stands in for it. A moved root decides only the cache key
825  // and where git runs, which is the part of the gates' answer that follows
826  // their cwd.
827  const projectDir = (await $.env.get('CLAUDE_PROJECT_DIR')) || launchRoot;
828  const root = deeperOf(projectDir || null, gitRoot) ?? cwd;
829  repoRoots.set(key, root);
830  return root;
831}
832
833async function resolveRulesDir($, sessionId, cwd) {
834  const override = await $.env.get('ACTUAL_RULES_DIR');
835  if (override) return override;
836  const root = await resolveRepoRoot($, sessionId, cwd);
837  if (!root) return null;
838  return `${root.replace(/\/+$/, '')}/.actual/rules`;
839}
840
841// The rules directory, but only when it holds a rule file -- rules_present in
842// bootstrap.sh, counting the same way: top-level `*.md` entries. Null means
843// this repository has nothing to govern against, and every handler below must
844// then be a silent no-op: no CLI spawn, no record, no transcript line, no
845// pane. Installing the plugin must not be visible in unrelated repositories.
846//
847// Not cached: a session can commit its first rule file partway through, and
848// the hook re-checks on every Read for the same reason. A listing is in-process
849// and cheap; the repo root underneath it is already cached per session and
850// project root.
851async function governedRulesDir($, sessionId, cwd) {
852  const rulesDir = await resolveRulesDir($, sessionId, cwd);
853  if (!rulesDir) return null;
854  let entries;
855  try {
856    entries = await $.fs.list(rulesDir);
857  } catch {
858    return null;
859  }
860  const names = (entries ?? []).map((entry) => entry.name).filter((name) => name.endsWith('.md'));
861  const files = (entries ?? []).filter((entry) => entry.name.endsWith('.md'));
862  ruleFileListing.set(rulesDir, {
863    names,
864    signature: files.map((f) => `${f.name}:${f.size}:${f.mtimeMs}`).join('\n'),
865  });
866  return names.length ? rulesDir : null;
867}
868
869// Which keys exist, and the CLI flag each one forwards to. maxSessionChars has
870// no flag: it is this mod's own budget, enforced here, not something the CLI
871// knows about.
872const CLI_FLAGS = {
873  limit: '--limit',
874  rulesPerDecision: '--rules-per-decision',
875  maxChars: '--max-chars',
876  minScore: '--min-score',
877};
878
879// Env wins over userConfig, the same precedence the three switches above use:
880// a settings row is the durable preference, an environment variable is the
881// override for one session.
882function mergeSettings(fromEnv, options) {
883  const resolved = {};
884  for (const key of ['maxSessionChars', ...Object.keys(CLI_FLAGS)]) {
885    const raw = fromEnv[key];
886    const parsed = raw === undefined || raw === null || raw === '' ? NaN : Number(raw);
887    if (Number.isFinite(parsed)) resolved[key] = parsed;
888    else if (Number.isFinite(options[key])) resolved[key] = options[key];
889  }
890  return resolved;
891}
892
893// Pass a limit through to the CLI only when the operator set one, so the CLI's
894// own defaults (2 decisions, 8 rules each, 4000 chars, no score floor) stay in
895// one place rather than being restated here. --min-score especially: its
896// default is the repository's own `rules_min_score`, then the user-wide key,
897// and overriding that from here would silently ignore a repo's setting.
898function cliLimits(resolved) {
899  const argv = [];
900  for (const [key, flag] of Object.entries(CLI_FLAGS)) {
901    if (Number.isFinite(resolved[key])) argv.push(flag, String(resolved[key]));
902  }
903  return argv;
904}
905
906// What Phase 3 of the plan asked for: the numbers needed to choose a cap,
907// rather than a cap chosen from unease.
908//
909// Two channels, because one is not enough. $.ui.log writes a dim transcript
910// line the model does not read, which is the right thing in an interactive
911// session -- measuring must not itself change what the session sees. But it
912// does not reach `claude -p` stdout, and headless is exactly where a scripted
913// measurement over many files would run, so the first attempt at this produced
914// nothing at all. The second channel adds the same line to the brief, where it
915// rides out in the call's context and the session transcript records it, even
916// headless. That one does enter the model's context, so it is strictly
917// debug-only.
918//
919// Neither channel writes a file. A durable log would mean declaring $.fs.write
920// on a governance plugin whose audit surface is the thing that makes it
921// reviewable, and a debug counter is not worth that.
922async function budgetLine($, sessionId, cap) {
923  try {
924    const used = spent.get(sessionId) ?? 0;
925    const usage = await $.session.usage();
926    const ctx = usage?.context;
927    const where = ctx ? ` context ${ctx.tokens}/${ctx.window} (${ctx.percent}%)` : '';
928    const line = `actual rules brief: injected ${used}/${cap} chars this session;${where}`;
929    $.ui.log(line);
930    return line;
931  } catch {
932    // Instrumentation must never be the reason a brief fails.
933    return '';
934  }
935}
936
937// Same three switches the shell hooks honour, read through $.env so a test can
938// set them. ACTUAL_CLI_SUBPROCESS is not an opt-out but a recursion guard:
939// actual-cli runs its conformance judge as a nested `claude -p`, and a judge
940// must weigh the rules it was handed, not rules a hook injected into its prompt
941// mid-run.
942//
943// Every mods API call is async, including $.env.get. Reading these without
944// awaiting compares a Promise to a string -- never equal, so every opt-out
945// silently stops working -- and leaks an unhandled rejection per call. Awaited
946// together rather than in sequence: three env reads are independent.
947async function optedOut($) {
948  const [planGate, briefSwitch, subprocess] = await Promise.all([
949    $.env.get('ACTUAL_PLAN_GATE'),
950    $.env.get('ACTUAL_RULES_BRIEF'),
951    $.env.get('ACTUAL_CLI_SUBPROCESS'),
952  ]);
953  return planGate === 'off' || briefSwitch === 'off' || subprocess === '1';
954}
955
956// Everything that happens once a set of governed files is in hand: the
957// budget, the CLI call per file, the record, and the context handed to the
958// model. Shared by the shell path and the Read path so neither can drift
959// from the other -- the divergence that produced every key bug in this mod.
960async function deliverBrief($, e, result, paths, ctx) {
961  const { cwd, sessionId, rulesDir, repoRoot, options } = ctx;
962  const resolved = mergeSettings(await readEnvSettings($), options);
963  const cap = Number.isFinite(resolved.maxSessionChars)
964    ? resolved.maxSessionChars
965    : DEFAULT_MAX_SESSION_CHARS;
966
967  // A cap of 0 turns briefing off, which `maxSessionChars` documents. Off has
968  // to mean silent: this used to fall through to the budget row below, so the
969  // switch that disables the feature made it report on every single read.
970  if (cap <= 0) return result;
971
972  let remaining = spendable(sessionId, cap);
973  if (remaining <= 0) {
974    recordOutcome(sessionId, e.tool_use_id, { outcome: 'budget', files: paths });
975    // Said once a session, not once a read. The budget is spent for the rest
976    // of the session, so every later read of any file in the repository --
977    // including the ungoverned ones this promises to stay quiet about --
978    // repeated the same row. The pane still lists each one.
979    if (!budgetAnnounced.has(sessionId)) {
980      budgetAnnounced.add(sessionId);
981      $.ui.log(row('BUDGET', `${cap} chars spent; quiet for the rest of this session`));
982    }
983    return withContext(result, await debugNote($, 'not briefed', `session budget of ${cap} chars is spent`));
984  }
985
986  if (!(await rulesBriefAvailable($, sessionId, cwd))) {
987    recordOutcome(sessionId, e.tool_use_id, { outcome: 'no-cli', files: paths });
988    return withContext(result, await debugNote($, 'not briefed', '`actual rules brief` is not available in this CLI'));
989  }
990
991  if (await adrV2Unsupported($, sessionId, rulesDir)) {
992    recordOutcome(sessionId, e.tool_use_id, { outcome: 'v2-cli-old', files: paths });
993    // Once a session, as the budget row is: the state holds for every later read.
994    if (!v2Announced.has(sessionId)) {
995      v2Announced.add(sessionId);
996      // 0.9.0 is ADR_V2_MIN_CLI in lib/bootstrap.sh, which the shell messages share;
997      // a bash variable cannot reach this file, so change both together.
998      $.ui.log(row('OLD CLI', 'rules use ADR header v2; upgrade actual to 0.9.0+ for briefs'));
999    }
1000    return withContext(result, await debugNote($, 'not briefed', 'the rule files use ADR header v2, which this CLI cannot read'));
1001  }
1002
1003  let appended = '';
1004  let exhausted = false;
1005  let cliError = null;
1006  const summaries = [];
1007  // Which files actually contributed, as opposed to which resolved. A
1008  // command naming two governed files where only one has anything new to
1009  // say must not be reported as having briefed both: `package.json,
1010  // pnpm-lock.yaml` read as two sources when the lockfile contributed
1011  // nothing, which is exactly the kind of thing this line exists to make
1012  // visible and so must not itself misstate.
1013  const briefedFiles = [];
1014  // Why each quiet file was quiet, from the CLI's stderr. Hook-mode stdout
1015  // cannot say -- it carries the brief the model reads -- so the reason is
1016  // named on stderr as `no-brief=<token>`, which the model never sees.
1017  const reasons = new Map();
1018  for (const filePath of paths) {
1019    let run;
1020    try {
1021      run = await $.process.run(
1022        [
1023          'actual', 'rules', 'brief', '--claude-hook',
1024          // The root, stated rather than inferred. The CLI takes it from
1025          // `--repo` first and from the envelope's `cwd` otherwise, and that cwd
1026          // follows the agent's `cd`: measured on 2.1.296, after
1027          // `cd apps/actual && ls lib/oauth` the next call ran in
1028          // `<repo>/apps/actual`. The CLI then placed every file against that
1029          // subdirectory -- files inside it matched as `lib/...` against
1030          // repository-relative globs, files outside it refused as "not under"
1031          // -- so four governed reads in one session briefed nothing while this
1032          // mod had resolved all four correctly. 11 of the 35 Bash calls in the
1033          // reference session began with `cd <dir> &&`.
1034          '--repo', repoRoot,
1035          '--rules-dir', rulesDir,
1036          ...cliLimits(resolved),
1037        ],
1038        {
1039          stdin: envelopeFor({ sessionId, agentId: e.agentId, cwd, filePath, tool: e.tool }),
1040          cwd,
1041          timeoutMs: SPAWN_TIMEOUT_MS,
1042        }
1043      );
1044    } catch {
1045      // Past the timeout, or the CLI could not start. `$.process.run` rejects
1046      // for both rather than returning an exit code. Without this the
1047      // rejection left for the handler's outer catch, which returned the
1048      // untouched result: no row, and a brief already collected for an earlier
1049      // file thrown away after the CLI had recorded it as shown.
1050      cliError = 'timed out or did not start';
1051      continue;
1052    }
1053    if (run.exitCode !== 0) {
1054      cliError = `exit ${run.exitCode}`;
1055      continue;
1056    }
1057    const reason = /no-brief=([a-z-]+)/.exec(run.stderr ?? '')?.[1];
1058    if (reason) reasons.set(filePath, reason);
1059    const brief = briefFrom(run.stdout);
1060    if (!brief) continue;
1061
1062    // A brief that does not fit is dropped whole, and the budget is
1063    // declared spent. Taking the next, smaller brief instead would make
1064    // which rules an agent sees depend on the order it happened to read
1065    // files in.
1066    if (brief.length > remaining) {
1067      exhausted = true;
1068      break;
1069    }
1070    appended += (appended ? '\n\n' : '') + brief;
1071    remaining -= brief.length;
1072    summaries.push(summarize(brief));
1073    briefedFiles.push(filePath);
1074  }
1075
1076  if (exhausted) {
1077    // Spend the rest of the budget so the notice is emitted once, not on
1078    // every subsequent read.
1079    spend(sessionId, cap);
1080    // Claude is told as well as the user, deliberately. The drawn toast is
1081    // for the person watching; Claude still needs to know that briefing has
1082    // stopped, or it is back to not being able to tell silence from a file
1083    // no rule governs.
1084    appended += (appended ? '\n\n' : '') + EXHAUSTED_NOTICE;
1085    $.ui.toast('Actual rule briefing has reached its per-session context budget.');
1086  } else if (appended) {
1087    spend(sessionId, appended.length);
1088  }
1089
1090  if (appended) {
1091    // One record for the call, merging what each file contributed.
1092    recordOutcome(sessionId, e.tool_use_id, {
1093      outcome: exhausted ? 'budget' : 'delivered',
1094      files: briefedFiles,
1095      // Kept so the pane can still show what resolved but said nothing.
1096      resolved: paths,
1097      summary: {
1098        decisions: summaries.flatMap((x) => x.decisions),
1099        shown: summaries.reduce((n, x) => n + x.shown, 0),
1100        total: summaries.reduce((n, x) => n + x.total, 0),
1101        chars: appended.length,
1102      },
1103    });
1104  } else if (cliError) {
1105    recordOutcome(sessionId, e.tool_use_id, { outcome: 'cli-error', files: paths, detail: cliError });
1106  } else {
1107    // Resolved a governed file and the CLI said nothing: every applicable
1108    // decision has already been briefed this session. The single most
1109    // useful thing to be able to see, because it is the one case where
1110    // silence is correct.
1111    // One outcome name, two very different facts, which is why the CLI now
1112    // says which. A read whose files are all ungoverned is the common case
1113    // and reports nothing: in a repo of any size most files are not governed,
1114    // and a line on every one of them would bury the reads that matter.
1115    // When every file was quiet for the same reason, the row says which. A
1116    // mixed call stays `deduped`, whose line names each group.
1117    const kinds = new Set(paths.map((f) => reasons.get(f) ?? 'unknown'));
1118    const only = kinds.size === 1 ? [...kinds][0] : null;
1119    recordOutcome(sessionId, e.tool_use_id, {
1120      outcome: Object.hasOwn(QUIET_OUTCOMES, only) ? QUIET_OUTCOMES[only] : 'deduped',
1121      files: paths,
1122      reasons: Object.fromEntries(reasons),
1123    });
1124    // The reason the CLI gave, per file, rather than one guess for all of
1125    // them. This said "already briefed" whatever the token was, so a debug
1126    // session chasing an ungoverned or outside-root file was told the
1127    // opposite of what the CLI had reported.
1128    const why = paths
1129      .map((f) => `${f}: ${reasons.get(f) ?? 'no reason given'}`)
1130      .join('; ');
1131    const note = await debugNote($, 'not briefed', `nothing new for ${why}`);
1132    if (note) appended = note;
1133  }
1134
1135  if (options.debug || (await $.env.get('ACTUAL_HOOK_DEBUG'))) {
1136    const line = await budgetLine($, sessionId, cap);
1137    if (line) appended += (appended ? '\n\n' : '') + line;
1138  }
1139
1140  // Report through $.ui.log. An earlier version drew a line under the tool
1141  // result, which depends on the render site Claude Code uses and collapses
1142  // some calls into a summary row whose id is not any member call's
1143  // tool_use_id, so reports went missing. $.ui.log writes a dim transcript
1144  // line the model does not read and depends on no render site.
1145  //
1146  // This reverses an invariant added two commits earlier -- that the mod logs
1147  // nothing unless debugging. That rule was about leftover debug noise
1148  // reaching a user's transcript, which is still true of `EX=true`. One
1149  // deliberate line per brief is the report itself.
1150  // $.ui.log already prefixes the plugin's name, so the line carried its own
1151  // prefix twice: `actual-cli: actual: briefed 2 ADRs...`.
1152  //
1153  // An Edit or Write reports only what it delivered or what failed. Nearly
1154  // every edit is of a file already read, so its `NO CHANGE` row would be the
1155  // same line under every edit of a session; the pane still lists each one.
1156  const record = outcomesFor(sessionId).get(e.tool_use_id);
1157  const quietWrite =
1158    WRITE_TOOLS.includes(e.tool) && record?.outcome !== 'delivered' && record?.outcome !== 'cli-error';
1159  const report = quietWrite ? null : reportLine(record);
1160  if (report) $.ui.log(report);
1161
1162
1163  if (!appended) return result;
1164
1165  return withContext(result, appended);
1166}
1167
1168// One label per outcome, the one table the pane reads. Two
1169// copies of this drifted apart once already, which is how `no new` and
1170// `nothing new for` came to say the same thing two ways.
1171const OUTCOME_LABELS = {
1172  delivered: 'briefed  ',
1173  deduped: 'no new   ',
1174  ungoverned: 'no rules ',
1175  'no-text': 'no text  ',
1176  'outside-root': 'off-root ',
1177  'no-rule-set': 'no set   ',
1178  budget: 'budget   ',
1179  'cli-error': 'error    ',
1180  'no-cli': 'old CLI   ',
1181  'v2-cli-old': 'v2 unread',
1182  unresolved: 'no match ',
1183  'no-paths': 'no path  ',
1184  'not-read-only': 'writes   ',
1185};
1186
1187const PANE = 'rules-brief';
1188
1189// Set on a PostToolUse:Read event this mod is briefing, so hooks/rules-brief.sh
1190// stands down for it. Read only: PreToolUse uses ACTUAL_SKILL_MOD_SESSION
1191// instead. The hook matches the literal bytes, so a rename here must be made
1192// there too.
1193const STAND_DOWN_FIELD = 'actual_rules_brief_by_mod';
1194
1195// The tools briefed as a reminder when written, and the ones whose
1196// PreToolUse registration of rules-brief.sh this mod stands down. Exactly the
1197// CLI's own list: NotebookEdit names its file as notebook_path and the CLI
1198// does not answer it.
1199const WRITE_TOOLS = ['Edit', 'Write'];
1200