A council of specialist reviewers that gates risky tool calls before they run. Rules decide the tier; model members give a second opinion; anything uncertain…

A Claude Code mod that gates risky tool calls before they run. Rules sort every call into a tier. Calls that need a second opinion go to a model reviewer, and anything uncertain comes to you.
The rules tier is the safety boundary. The model reviewers are a second opinion: they can catch what a pattern misses, but they never widen what the rules allow. This is not a sandbox or a security product (see What it does not protect against).
Status: all six stages done, with the final deliverables (SPEC §21–22), after the 0.5.0 hardening. Available now: the rules; three model reviewers (destructive operations, diffs, and git and databases) with routing between them; the full council with your project's own checks for big operations; the secrets scan, read-only previews, review rounds and lockout, the approve cache, escalation to you, allow rules offered after "allow once", /council and /council report, shadow mode and bypass, fail-closed handling and the audit log, the theme (with a plain mode), and the debate pane, the council check band, the wipe counter, the threat meter and the epic drop. The 0.5.0 release closed the rules-tier and pipeline findings of the Stage 5 review (docs/REVIEW-2026-10.md). Headless live checks ran on Claude Code 2.1.294; the interactive screens (the dialogs, the pane, the band, the mode label) still await a check in a terminal. See ROADMAP.md for what's left, SPEC.md for the original spec and DESIGN.md for how it works.
Turn on shadow mode while you tune the rules: /council shadow on for one session, or "Shadow mode" in /config. Reviewers still run and log their verdicts to the audit log, but they never refuse. The block tier, the ask tier, protected paths and the secrets scan still enforce. The label council: shadow shows by the prompt while it is on. Until the audit log has a line, a one-time toast at session start suggests it.
Requires Claude Code 2.1.287 or later (mods are on by default).
claude --plugin-dir ./mods/council-of-elrondclaude plugin marketplace add Deluha/council-of-elrond, then claude plugin install council-of-elrond@council-of-elrond. Other ways, updating and removing: docs/INSTALL.md.CLAUDE_CODE_PLUGIN_DIRS to the folder's absolute path in the environment or in ~/.claude/settings.json under env.Check it loaded: /plugin shows the mods line, and claude plugin validate ./mods/council-of-elrond lists its hooks.
| Tier | What happens | | :- | :- | | allow | Passes untouched, with no model call. Anything no rule matches is allowed. | | review | A model reviewer gives a verdict: approve runs it, revise or block refuses it. | | ask | Comes straight to you. | | block | Refused, with the rule's reason. No model call, no question. |
Compound commands (&&, ;, |, $(...), backticks, subshells, sh -c '...', eval, and heredocs fed to a shell) are split, and the strictest part decides.
Shipped defaults:
/, your home directory, the project root, or anything outside the project;sudo, doas, su;.env*, Jenkinsfile, migrations folders, and the entries below. The entries written with a leading **/ hold in every repository below the session root, at any depth, the rules file included (app/.claude/council-of-elrond/rules.json), and so does the directory itself (rm -rf app/.git asks). A path outside the session root is matched by its absolute form, so another repository's .git/ or your user ~/.claude/settings.json (which holds hooks and permissions) asks too:/.github/workflows/, /.gitlab-ci.yml, /.circleci/, /.buildkite/**;/db/migrate/;/.git/;/.claude/council-of-elrond/, /.claude/settings.json, /.claude/settings.local.json.Approve never pre-approves. An approved call still goes through Claude Code's normal permission check and prompt. The mod never takes part in the permission decision.
Subagents are gated too. A subagent's tool calls go through the same pipeline as the main conversation's, and their audit lines carry the subagent's agentId (checked live on Claude Code 2.1.294, with the subagent in the background and in the foreground).
A review-tier call goes to exactly one model reviewer, the one its rule names (member and profile in a rule), unless it is a big operation (see The full council). Each reviewer has a short checklist of its own and sees only what that checklist needs.
| Reviewer | Takes | Sees | Checks | | :- | :- | :- | :- | | Destructive operations (Gandalf, gandalf) | deletes, moves, overwrites, scripts, infrastructure, anything no rule names | the call, the preview, scripts Claude wrote this session | reversibility, width, reach, backups, intent | | Diffs (Legolas, legolas) | Write, Edit, NotebookEdit | a diff built from the call against the file as it stands (cut to the diff line limit), the file's git status | matches the request, scope creep, weakened tests, disabled checks, dependency/CI/config changes, obvious breakage. No style review. | | Git (Aragorn, aragorn, profile git) | push, merge, rebase, reset, tag, amend and other history changes | the command, the branch, remote and commits it would send or bring in, recent history with remote branches marked, your protected branches | protected target, force, rewriting pushed history, unrelated commits | | Database (Aragorn, aragorn, profile database) | SQL clients, migrations, .sql files | the command, SQL from -c/-e/heredocs, .sql files it names inside the project, or a SQL file's diff; which production patterns match | rollback path, destructive DDL, UPDATE/DELETE without WHERE, production-looking target, transactions, long locks |
Gandalf is the fallback. A call goes to Gandalf when its rule names nobody, when the named reviewer is switched off, when a compound command's parts name different reviewers (one specialist would judge only its own part), or when a rule names the diff reviewer for something with no file. If Gandalf is off too, the call comes to you. /council test "<command>" shows who would review and why.
Big operations go to every enabled reviewer at once instead of one. By default they are a git push, a merge into a protected branch (git merge while a protected branch is checked out, or gh pr merge) and a database migration.
git push && psql … gets both.git diff. When the remote does not have the branch yet, the diff is against the remote's default branch (<remote>/HEAD), the changes since the branch point.opus by default), not its own./config). By default they run in parallel. "Full council one at a time" asks them in turn instead, each getting what is left of the deadline, and stops at the first block.Project checks (Gimli, gimli) run alongside: your tests, lint and typecheck, from gimli.commands in rules.json:
{
"schemaVersion": 1,
"gimli": {
"commands": [
{ "name": "tests", "argv": ["npm", "test"], "timeoutMs": 300000 },
{ "name": "lint", "argv": ["npx", "eslint", "."] }
]
},
"bigOperations": ["publish", "/^kubectl\\s+apply(\\s|$)/"]
}
rules.json is a protected path, so Claude can't add a command without asking you.timeoutMs says otherwise, at most 600 s. It runs outside the reviewers' deadline, so a council can take as long as the longer of the two.["env", "CI=1", "npm", "test"].Changing what counts as big: bigOperations in rules.json adds rule ids, /regex/flags matched against each shell part, or merge-to-protected; it only adds to the shipped list. Only calls the rules already send to review can be big operations: a blocked call stays refused, and an ask-tier call still comes to you. To send big operations to one reviewer like any other call, turn off "Full council for big operations" in /config. /council test "<command>" shows when a call would go to the full council, who would sit and which checks would run.
Put project overrides in .claude/council-of-elrond/rules.json:
{
"schemaVersion": 1,
"rules": [
{
"id": "allow-clean-build",
"tier": "allow",
"tools": ["Bash"],
"command": "^rm -rf (build|dist)$",
"reason": "Build output is disposable here."
},
{
"id": "no-terraform-destroy",
"tier": "block",
"tools": ["Bash"],
"command": "^terraform destroy",
"reason": "Infrastructure is torn down by CI only."
},
{
"id": "review-mcp-db",
"tier": "review",
"tools": ["mcp__db__*"],
"reason": "Database MCP calls."
}
],
"disableRules": ["shell-move"],
"protectedPaths": ["secrets/**"],
"protectedBranches": ["staging"],
"productionPatterns": ["\\bprd-"],
"models": { "gandalf": "opus" }
}
Rule fields:
tools: exact names, globs (mcp__*) or /regex/flags.command: a regex matched against each shell part, with quotes removed and wrappers such as sudo, env and nice stripped.path: a regex matched against the file path relative to the project root.input: a regex matched against the call's JSON.member and profile: who reviews (gandalf, legolas, aragorn with git or database).How overrides combine with the shipped rules:
A broken file is ignored whole. The shipped rules stay in force, and the errors are listed by field in the transcript.
The overrides file is itself a protected path, so Claude can't edit it without asking you.
Where the file lives. At the top of the project: .claude/council-of-elrond/rules.json under the session root. When the session root is the parent of several repositories, each repository directly below it has its own, at its own top (see the next section). No other depth counts: a file in an arbitrary subfolder is never read, so a planted file cannot set rules for the calls beneath it.
Some environments (a cloud environment with two repositories, a workspace folder) start the session in a folder that holds several repositories rather than in one of them. If that folder has no rules.json of its own and is not itself a repository (no .git), the mod looks up the rules per call:
.git. Its rules are its own .claude/council-of-elrond/rules.json, or the shipped defaults when it has none. A rules file in a folder with no .git, or deeper than a repository's top, is ignored.cd earlier in the command) and every path the part names; for a file edit, the file. cd app && make from the root touches the root and app; cat ../app/x run in lib touches lib and app; cmd > /dev/null names a path in no repository and adds nothing. A directory the call works in that is in no repository (the root, a plain folder, /, an unknown cd $X) brings in the root's own rules, which are the shipped defaults.rm -rf ../lib run in app is blocked, since lib is outside the repository the rule measures against (deleting a repository is like rm -rf .).protectedPaths: ["config/secret/"] in app's file is app/config/secret/. A council call runs the checks of every repository it touches, each in its own directory, eight in all (the repositories' lists joined in the order they were touched). Git (the preview, a push's range, the current branch for a merge) runs in the deciding repository (or in the folder a cd in the command leads to, when it is inside the project)..gitignore is written beside each. /council log, report, rules and models read the repository of the session's working directory (the root's when it is in none).Each repository's file is read once and kept; /council reload reads them all again, and the mod's own write to a repository's file reloads that one. A repository created after the session started is seen after /council reload. A session root that has a rules.json, or is itself a repository, keeps the single set of rules it always had. The lookup is on for any root with neither, even one that holds no repository: a plain folder is then offered no allow rule or allowlist entry for calls outside a repository, so give it a rules.json (even {"schemaVersion": 1}) to get them back. The cloud guide has the setup: Cloud sessions.
| Reviewer | Built-in default | | :- | :- | | Destructive operations (Gandalf) | sonnet | | Diffs (Legolas) | sonnet | | Git and database (Aragorn, both profiles) | opus | | Full council (every member, for big operations) | opus |
Aliases resolve to the newest model of that family your Claude Code build knows. A reviewer's model comes from the first of these that sets one:
/council model gandalf opus). Each switch is checked with one tiny request first./config ("Gandalf model", "Legolas model", "Aragorn model", "Full council model": default, sonnet, opus, fable or haiku).models in the project rules file, which also takes full model IDs.The token cap, effort and deadline follow the model automatically. "Review deadline" in /config overrides the deadline.
/config)| Option | Default | | :- | :- | | Gandalf enabled | on (off: calls only it would review come to you) | | Gandalf model | default | | Legolas enabled | on (off: its reviews go to Gandalf) | | Legolas model | default | | Aragorn enabled | on (off: its reviews go to Gandalf) | | Aragorn model | default | | Full council for big operations | on (off: big operations go to one reviewer) | | Full council model | default | | Full council one at a time | off (members in parallel) | | Project checks enabled | on (runs gimli.commands for big operations) | | Review deadline (seconds) | 0 (from the model) | | Session token budget | 1,500,000 (spent: reviews come to you) | | Audit log path | .claude/council-of-elrond/audit/audit.jsonl | | Audit log size before rotation (KB) | 1024, three files kept | | Shadow mode | off | | Plain mode | off (themed). On: no theme text anywhere | | Secrets scan enabled | on | | Read-only preview enabled | on | | Preview line limit | 80 | | Diff line limit | 200 | | Tool errors count as failed attempts | on |
| Mode | What it does | How to set it | | :- | :- | :- | | Enforcing (the default) | Every tier applies. A reviewer's revise or block refuses the call; a reviewer that fails, or none being on, brings it to you. | Nothing to set. | | Shadow | Reviewers and the full council (its project checks included) log their verdicts and never refuse; a failed review passes, logged. The block tier, the ask tier, protected paths, the secrets scan and lockouts still enforce. | /council shadow on for the session, or "Shadow mode" in /config. Label: council: shadow. | | Bypass (themed: Leeroy mode) | Every gated call passes unreviewed, block-tier calls and the secrets scan included, and each is logged. | /council off, for this session only and never saved; /council on ends it. Label: council: bypass (council: Leeroy mode themed). | | Plain | Every string in its plain variant, with no theme text anywhere; behaviour is identical. It combines with any mode above. | "Plain mode" in /config. |
By default the council speaks in its theme. The "Plain mode" option in /config switches every theme word off; behaviour is identical in both modes.
What is themed, for you only:
/council, the dialog and the report say Gandalf, Legolas, Aragorn (git or databases), Gimli, Gollum, Galadriel, Elrond and the Council of Elrond where plain mode says the role ("the destructive-operations reviewer", "the full council").council: Leeroy mode by the prompt, and in /council)./council counts wipes where plain mode says "refused or failed attempts".What is never themed: what Claude reads. Refusals, the full council's reasons and the rule reason written to your rules file are plain in both modes, and name the role, not the character. Member ids you type (/council model gandalf opus) are config keys and stay as written. The dialogs that confirm exact data you agree to write (the allowlist entry, an allow rule) keep their plain text.
Each theme term and its plain name are in the Glossary.
"Council" stays in plain mode: it is the product's name.
Everything /council prints is for you: it draws in a pane where a surface draws one, else as dim transcript lines. Claude does not read it, with one exception: where nothing draws at all (the cloud web client, claude -p, the SDK), /council status, report, rules and test also go to Claude to show you, because Claude is then the only way to reach you; see Where nothing draws. That applies only to a person's command. In claude -p and the SDK a command is not a person's, so it gets no relay. In a plain claude -p "/council" run nothing prints; use --output-format stream-json, where the lines arrive as ui_log messages.
| Command | What it does | | :- | :- | | /council | Status: mode, each member with its state, model and verdict counts, the full council and the project checks, failed attempts since your last prompt, tokens spent, median review time. | | /council off, /council on | Bypass for this session: gated calls pass unreviewed and are logged. Never persisted. The label council: bypass (council: Leeroy mode when themed) shows by the prompt. | | /council shadow on, /council shadow off | Shadow mode for this session, over the /config setting. | | /council log [n] | The last n gated calls (default 10) from the audit log. | | /council rules | Every effective rule with its source (shipped or project), and the lists. | | /council test "<command>" | Which tier, rule, reviewer (and profile, and why it fell back to Gandalf if it did) and operation key a shell command would get. For a big operation it shows the full council's seats, model and checks. Runs nothing, so a merge is assumed to land on a protected branch. | | /council model [<member> <model> [--save]] | Lists each slot's model and where it came from, or switches one for this session (default clears the switch). --save also writes the /config row when the model is one of its picker values. | | /council reload | Reads rules.json again (every repository's, when the session root holds several). | | /council report | A summary of the audit log, rotated files included (see below). | | /council debate | Opens the debate pane at any width (where nothing draws, prints its rows as transcript lines). |
off, shadow on and model only run when a person types them. They loosen the gate (bypass, reviewers that never refuse, a d
hooks/register.ts 2027 lines1import { atom, read, update } from 'claude-code'
2import type { EngineInterface, PluginOptions, ProcessRunResult, ProcessSpawnResult, Register, RenderElement, ToolCallResult } from 'claude-code'
3
4import type { CouncilPanel } from '../types'
5import { appendPlan, AUDIT_GITIGNORE, auditLine, fingerprintOf, isRotation, ROTATED_FILES } from './audit.js'
6import type { AuditRecord, Decision } from './audit.js'
7import { OVERRIDES_PATH } from './config/defaults.js'
8import { loadConfig, MODEL_ID } from './config/schema.js'
9import type { LoadedConfig } from './config/schema.js'
10import { MODEL_SLOTS } from './config/types.js'
11import type { GimliCommand, MemberName, ModelSlot } from './config/types.js'
12import { withAllowlistEntry, withRule } from './config/write.js'
13import type { FileEdit } from './config/write.js'
14import { isCouncilCommand, isSlot, logOutput, modelsOutput, needsPerson, parseCouncil, rulesOutput, statusOutput, testOutput } from './elrond/commands.js'
15import { callKeyOf, codeOf, isOfferable, parseChatLines } from './elrond/chat.js'
16import { combine, hasRealBlock } from './elrond/combine.js'
17import type { Voice } from './elrond/combine.js'
18import { bigOperationOf, councilSeats, needsCurrentBranch, rangeOf } from './elrond/council.js'
19import type { Big, CouncilSeat } from './elrond/council.js'
20import type { CouncilCommand, Output, StatusInput } from './elrond/commands.js'
21import { interpretAnswer, optionsOf, questionText } from './elrond/escalation.js'
22import type { Answer, MemberOpinion, Unanswered } from './elrond/escalation.js'
23import { deadlineFor, profileOf, resolveModel } from './elrond/models.js'
24import type { ModelChoice } from './elrond/models.js'
25import {
26 cacheApprove,
27 isOutOfRounds,
28 isWipeOutcome,
29 lockoutOf,
30 noteRound,
31 noteWipe,
32 operationOf,
33 outcomeOf,
34 resetOperation,
35 resetRounds,
36 roundsLeft,
37} from './elrond/operations.js'
38import type { WipePolicy } from './elrond/operations.js'
39import { refusalText } from './elrond/refusal.js'
40import { isRelayed, noticeText, nobodyToAsk, relayContext } from './elrond/relay.js'
41import { reportOutput } from './elrond/report.js'
42import { bandRows, debateRows, voiceNote } from './elrond/view.js'
43import type { Row } from './elrond/view.js'
44import { ruleJson, suggestRule } from './elrond/suggest.js'
45import type { Refusal } from './elrond/refusal.js'
46import { route } from './elrond/routing.js'
47import type { Enabled, Seat } from './elrond/routing.js'
48import { ARAGORN_LIMITS, productionHits, sqlOf } from './members/aragorn.js'
49import type { SqlPiece } from './members/aragorn.js'
50import { requestOf, whoOf } from './members/brief.js'
51import type { Brief } from './members/brief.js'
52import { formatPreview, INSPECTION_TIMEOUT_MS, MAX_LISTED, mergePlace, planPreview, rangeDiffInspection } from './members/galadriel.js'
53import type { Inspection, InspectionResult } from './members/galadriel.js'
54import { GANDALF_LIMITS } from './members/gandalf.js'
55import { isGimliBlock, keepTail, problemOf, statusOf, tailOf } from './members/gimli.js'
56import type { GimliRun } from './members/gimli.js'
57import { patternsWith, scanCall, warnsPasswordFingerprint } from './members/gollum.js'
58import { callDiff, LEGOLAS_LIMITS } from './members/legolas.js'
59import type { CallDiff, Current } from './members/legolas.js'
60import type { GollumFinding } from './members/gollum.js'
61import { newNonce, parseVerdict, truncate } from './members/shared.js'
62import type { Verdict } from './members/shared.js'
63import { redact } from './redact.js'
64import type { SecretPattern } from './redact.js'
65import { classify, FILE_PATH_FIELDS, SHELL_TOOLS, targetsOf } from './rules/classify.js'
66import type { Call, Classification, ClassifyContext, Target } from './rules/classify.js'
67import { isInside, relativeTo, resolve } from './rules/paths.js'
68import { auditDirsOf, candidateChildren, checksOf, combineClassifications, intersection, scopesTouched, scopeTagOf, unionById, writeDirOf } from './rules/scopes.js'
69import {
70 addReviewTime,
71 addTokens,
72 answerChat,
73 clearCache,
74 clearEpic,
75 closeDebate,
76 count,
77 declineRule,
78 forOtherPrompt,
79 grantChat,
80 holdsChat,
81 INITIAL_SESSION,
82 isReadable,
83 isShadow,
84 markDebateOpened,
85 noteCheck,
86 noteOffer,
87 noteVoice,
88 noteWritten,
89 openDebate,
90 resetForPrompt,
91 sessionOf,
92 tidyCall,
93 tidyReason,
94 useChat,
95 withBypass,
96 withEpic,
97 withSessionModel,
98 withShadow,
99} from './state.js'
100import type { ChatUse } from './state.js'
101import type { CouncilDebate, CouncilSession } from '../types'
102import { currentMode, setMode, text, withMode } from './strings.js'
103import type { Mode, StringKey } from './strings.js'
104
105/**
106 * Elrond, the chair: the one `tool.call` hook every call passes through.
107 * Rules classify it; allow passes untouched; block refuses; a locked-out
108 * operation refuses; the secrets scan refuses or asks; ask goes to the user;
109 * review gets a read-only preview and goes to a model member. Every failure
110 * refuses or asks: the hook never lets a gated call through on an error.
111 *
112 * Also `/council`, and the mode label by the prompt. The only file that
113 * touches `$`; everything it decides with is a pure function in a sibling.
114 */
115
116const session = atom({ plugin: 'council-of-elrond', key: 'session' } as const, INITIAL_SESSION)
117
118const panel = atom({ plugin: 'council-of-elrond', key: 'panel' } as const, { title: '', lines: [] } as CouncilPanel)
119
120/** Margin kept on the hook's own 10 s budget before any pass-through. */
121const BUDGET_GUARD_MS = 1_000
122
123/**
124 * Prompt origins that are a person's own: they reset the per-prompt state, and
125 * only they may run the `/council` subcommands that loosen the gate. `sdk` is the
126 * host's own turn (`claude -p`, the Agent SDK), not typed at a terminal; the cloud
127 * web client arrives as `composer` (DESIGN §14.3).
128 */
129const HUMAN_ORIGINS: ReadonlySet<string> = new Set(['composer', 'bridge'])
130
131const MAX_SCRIPTS = 3
132
133const COMMAND = 'council'
134const PANE_ID = 'council'
135
136/** The debate pane: its own id, so it sits beside the `/council` output as a tab. */
137const DEBATE_PANE_ID = 'council-debate'
138
139/** Rows the debate pane asks for where it is placed inline. */
140const DEBATE_PANE_ROWS = 12
141
142/** How long the epic drop row and toast last. */
143const EPIC_MS = 8_000
144
145/** The `/config` row a `--save` writes, per slot that has one. */
146const CONFIG_ROWS: Readonly<Partial<Record<ModelSlot, string>>> = {
147 gandalf: 'council-of-elrond.gandalfModel',
148 legolas: 'council-of-elrond.legolasModel',
149 aragorn: 'council-of-elrond.aragornModel',
150 council: 'council-of-elrond.councilModel',
151}
152
153/** What the `/config` model picker offers; anything else is session-only. */
154const PICKER_OPTIONS: readonly string[] = ['default', 'sonnet', 'opus', 'fable', 'haiku']
155
156/**
157 * Git for previews: no locks taken, no prompts, plain output, and no program
158 * started from the repository's config: `core.fsmonitor` and `log.showSignature`
159 * (which runs the configured gpg program) are forced off.
160 */
161const GIT_ENV: Record<string, string> = {
162 GIT_OPTIONAL_LOCKS: '0',
163 GIT_TERMINAL_PROMPT: '0',
164 GIT_PAGER: 'cat',
165 LC_ALL: 'C',
166 GIT_CONFIG_COUNT: '2',
167 GIT_CONFIG_KEY_0: 'core.fsmonitor',
168 GIT_CONFIG_VALUE_0: 'false',
169 GIT_CONFIG_KEY_1: 'log.showSignature',
170 GIT_CONFIG_VALUE_1: 'false',
171}
172
173const PROBE_TIMEOUT_MS = 20_000
174
175type Settings = {
176 gandalfEnabled: boolean
177 gandalfModel: string
178 legolasEnabled: boolean
179 legolasModel: string
180 aragornEnabled: boolean
181 aragornModel: string
182 councilEnabled: boolean
183 councilModel: string
184 councilSequential: boolean
185 gimliEnabled: boolean
186 diffLines: number
187 reviewDeadlineSeconds: number
188 tokenBudget: number
189 auditLogPath: string
190 auditMaxKb: number
191 shadowMode: boolean
192 toolErrorsAreWipes: boolean
193 previewLines: number
194 gollumEnabled: boolean
195 galadrielEnabled: boolean
196 plainMode: boolean
197}
198
199const modelSetting = (value: unknown): string => (typeof value === 'string' ? value : 'default')
200
201const settingsOf = (options: PluginOptions): Settings => ({
202 gandalfEnabled: options.gandalfEnabled !== false,
203 gandalfModel: modelSetting(options.gandalfModel),
204 legolasEnabled: options.legolasEnabled !== false,
205 legolasModel: modelSetting(options.legolasModel),
206 aragornEnabled: options.aragornEnabled !== false,
207 aragornModel: modelSetting(options.aragornModel),
208 councilEnabled: options.councilEnabled !== false,
209 councilModel: modelSetting(options.councilModel),
210 councilSequential: options.councilSequential === true,
211 gimliEnabled: options.gimliEnabled !== false,
212 diffLines: typeof options.diffLines === 'number' ? options.diffLines : 200,
213 reviewDeadlineSeconds: typeof options.reviewDeadlineSeconds === 'number' ? options.reviewDeadlineSeconds : 0,
214 tokenBudget: typeof options.tokenBudget === 'number' ? options.tokenBudget : 1_500_000,
215 auditLogPath:
216 typeof options.auditLogPath === 'string' && options.auditLogPath !== ''
217 ? options.auditLogPath
218 : '.claude/council-of-elrond/audit/audit.jsonl',
219 auditMaxKb: typeof options.auditMaxKb === 'number' ? options.auditMaxKb : 1024,
220 shadowMode: options.shadowMode === true,
221 toolErrorsAreWipes: options.toolErrorsAreWipes !== false,
222 previewLines: typeof options.previewLines === 'number' ? options.previewLines : 80,
223 gollumEnabled: options.gollumEnabled !== false,
224 galadrielEnabled: options.galadrielEnabled !== false,
225 plainMode: options.plainMode === true,
226})
227
228type Context = {
229 loaded: LoadedConfig
230 root: string
231 /** The root with symbolic links resolved, to map resolved paths back under `root`. */
232 realRoot: string
233 home?: string
234 /** Shipped and configured secret patterns: the scan's, and every redaction's. */
235 patterns: readonly SecretPattern[]
236 /** C5: the root holds no rules file and no `.git`, so each call looks up the repositories below it. */
237 isMulti: boolean
238}
239
240/** A rules scope: the session root, or a repository directly below it (C5). */
241type Scope = { dir: string; loaded: LoadedConfig; patterns: readonly SecretPattern[] }
242
243/**
244 * The context one call is decided in: `root` stays the session root, `loaded` is
245 * the deciding scope's, and the rest is what the touched scopes share.
246 */
247type CallContext = Context & {
248 scopes: readonly Scope[]
249 /** Where git runs: the deciding scope's directory. */
250 gitDir: string
251 /** Secrets allowed in every touched scope. */
252 allowlist: readonly string[]
253 /** Where a rules entry may be written for this call; none when it touched more than one scope or the root alone in a multi-repository root. */
254 writeDir: string | undefined
255}
256
257type Review =
258 | { ok: true; verdict: Verdict; model: string; tokens: number }
259 | { ok: false; problem: string; model: string; tokens: number }
260
261// Module state: starts over on every load, as the module does.
262let settings: Settings = settingsOf({})
263let context: Promise<Context> | undefined
264/** C5: one entry per child of the root, a repository's scope or undefined for a plain folder. */
265const children = new Map<string, Promise<Scope | undefined>>()
266let auditQueue: Promise<void> = Promise.resolve()
267/** The folders whose audit `.gitignore` was looked at since the module loaded. */
268const gitignoreChecked = new Set<string>()
269const warned = new Set<string>()
270
271const wipePolicy = (): WipePolicy => ({ toolErrors: settings.toolErrorsAreWipes })
272
273const enabledMembers = (): Enabled => ({
274 gandalf: settings.gandalfEnabled,
275 legolas: settings.legolasEnabled,
276 aragorn: settings.aragornEnabled,
277})
278
279/** The /config row's model for a slot. */
280const settingsModel = (slot: ModelSlot): string => {
281 switch (slot) {
282 case 'gandalf':
283 return settings.gandalfModel
284 case 'legolas':
285 return settings.legolasModel
286 case 'aragorn':
287 return settings.aragornModel
288 case 'council':
289 return settings.councilModel
290 }
291}
292
293function warnOnce($: EngineInterface, key: string, line: string, toast?: string): void {
294 if (warned.has(key)) return
295 warned.add(key)
296 $.ui.log(line)
297 if (toast !== undefined) $.ui.toast(toast, { timeoutMs: 8_000 })
298}
299
300/** Reads and validates the rules file of one directory; a broken one warns once under `key`. */
301async function loadRules($: EngineInterface, dir: string, key: string): Promise<{ loaded: LoadedConfig; hasFile: boolean }> {
302 const path = `${dir}/${OVERRIDES_PATH}`
303 let fileText: string | undefined
304 let readProblem: string | undefined
305 const hasFile = await $.fs.exists(path)
306 if (hasFile) {
307 fileText = await $.fs.read(path).catch((error: unknown) => {
308 readProblem = `(file): could not be read: ${error instanceof Error ? error.message : String(error)}`
309 return undefined
310 })
311 }
312 const loaded = readProblem !== undefined ? { ...loadConfig(undefined), errors: [readProblem] } : loadConfig(fileText)
313 if (loaded.errors.length > 0) {
314 warnOnce(
315 $,
316 key,
317 text('notice.configBroken', { path: OVERRIDES_PATH, errors: loaded.errors.join('; ') }),
318 text('notice.configBrokenShort'),
319 )
320 }
321 return { loaded, hasFile }
322}
323
324async function loadContext($: EngineInterface): Promise<Context> {
325 const root = await $.session.root()
326 const realRoot = (await $.fs.stat(root, { resolve: true }).catch(() => undefined))?.realPath ?? root
327 const home = await $.env.get('HOME')
328 const { loaded, hasFile } = await loadRules($, root, 'config')
329 // C5: a rules file at the root, or a root that is itself a repository, keeps today's single scope.
330 const isMulti = !hasFile && !(await $.fs.exists(`${root}/.git`))
331 const patterns = patternsWith(loaded.compiled.config.gollum.patterns)
332 return { loaded, root, realRoot, patterns, isMulti, ...(home !== undefined && { home }) }
333}
334
335async function contextOf($: EngineInterface): Promise<Context> {
336 if (context === undefined) {
337 context = loadContext($).catch((error: unknown) => {
338 context = undefined
339 throw error
340 })
341 }
342 return context
343}
344
345/** A direct child of the root as a scope: a real directory holding `.git` is a repository, anything else is not. */
346async function loadChild($: EngineInterface, dir: string): Promise<Scope | undefined> {
347 const stat = await $.fs.stat(dir).catch(() => undefined)
348 if (stat === undefined || stat.isLink || stat.kind !== 'dir') return undefined
349 if (!(await $.fs.exists(`${dir}/.git`))) return undefined
350 const { loaded } = await loadRules($, dir, `config:${dir}`)
351 return { dir, loaded, patterns: patternsWith(loaded.compiled.config.gollum.patterns) }
352}
353
354/** The scope of a child directory of the root, or undefined when it is not a repository. Cached, negatives too; a failed load is not. */
355function childScope($: EngineInterface, dir: string): Promise<Scope | undefined> {
356 let entry = children.get(dir)
357 if (entry === undefined) {
358 const loading: Promise<Scope | undefined> = loadChild($, dir).catch((error: unknown) => {
359 if (children.get(dir) === loading) children.delete(dir)
360 throw error
361 })
362 entry = loading
363 children.set(dir, entry)
364 }
365 return entry
366}
367
368const rootScopeOf = (ctx: Context): Scope => ({ dir: ctx.root, loaded: ctx.loaded, patterns: ctx.patterns })
369
370/** The scopes a call touches, in order (DESIGN §14.5); the root scope alone when the lookup is off. */
371async function scopesOf($: EngineInterface, ctx: Context, targets: readonly Target[]): Promise<Scope[]> {
372 const rootScope = rootScopeOf(ctx)
373 if (!ctx.isMulti) return [rootScope]
374 const candidates = candidateChildren(targets, ctx.root)
375 const found = await Promise.all(candidates.map(dir => childScope($, dir)))
376 const repositories = new Map<string, Scope>()
377 candidates.forEach((dir, index) => {
378 const scope = found[index]
379 if (scope !== undefined) repositories.set(dir, scope)
380 })
381 return scopesTouched(targets, ctx.root, new Set(repositories.keys())).map(dir => repositories.get(dir) ?? rootScope)
382}
383
384/** The context for the scopes a call touched; `index` is the deciding one. */
385function callContextOf(ctx: Context, scopes: readonly Scope[], index: number): CallContext {
386 const deciding = scopes[index] ?? rootScopeOf(ctx)
387 const dirs = scopes.map(scope => scope.dir)
388 return {
389 ...ctx,
390 loaded: deciding.loaded,
391 patterns: scopeTagOf(dirs, ctx.root) === '' ? ctx.patterns : unionById([ctx.patterns, ...scopes.map(scope => scope.patterns)]),
392 scopes,
393 gitDir: deciding.dir,
394 allowlist: intersection(scopes.map(scope => scope.loaded.compiled.config.gollum.allowlist)),
395 writeDir: writeDirOf(dirs, ctx.root, ctx.isMulti),
396 }
397}
398
399/** The classification of a call across the scopes it touches: the strictest wins (DESIGN §14.5). */
400async function classifyIn(
401 $: EngineInterface,
402 ctx: Context,
403 call: Call,
404 where: ClassifyContext,
405): Promise<{ classification: Classification; ctx: CallContext }> {
406 const scopes = await scopesOf($, ctx, targetsOf(call, where))
407 const { classification, index } = combineClassifications(scopes.map(scope => classify(call, scope.loaded.compiled, { ...where, root: scope.dir })))
408 return { classification, ctx: callContextOf(ctx, scopes, index) }
409}
410
411/** The scope of the session's working directory: its repository, else the root's. For `/council` and the start suggestion. */
412async function cwdScopeOf($: EngineInterface, ctx: Context): Promise<Scope> {
413 const [scope] = await scopesOf($, ctx, [{ path: await $.session.cwd(), isWorkingDir: true }])
414 return scope ?? rootScopeOf(ctx)
415}
416
417/** The root's context seen through one scope's config, for the `/council` subcommands. */
418const inScope = (ctx: Context, scope: Scope): Context =>
419 scope.dir === ctx.root ? ctx : { ...ctx, loaded: scope.loaded, patterns: unionById([ctx.patterns, scope.patterns]) }
420
421/** Reads the rules again (decision 9: after the mod's own writes, and on `/council reload`): the root's and every repository's. */
422async function reloadContext($: EngineInterface): Promise<Context> {
423 context = undefined
424 children.clear()
425 for (const key of [...warned]) if (key === 'config' || key.startsWith('config:')) warned.delete(key)
426 const fresh = await contextOf($)
427 await update($, session, value => clearCache(sessionOf(value)))
428 return fresh
429}
430
431/** The context seen through the session's working directory's scope, for the `/council` subcommands. */
432async function cwdContextOf($: EngineInterface): Promise<Context> {
433 const ctx = await contextOf($)
434 return inScope(ctx, await cwdScopeOf($, ctx))
435}
436
437/** After the mod wrote a rules file in `dir`: the root's context, or that repository's entry alone. */
438async function reloadAt($: EngineInterface, ctx: Context, dir: string): Promise<void> {
439 if (dir === ctx.root) await reloadContext($)
440 else await reloadScope($, dir)
441}
442
443/** After the mod wrote a repository's rules file: that entry alone is read again. */
444async function reloadScope($: EngineInterface, dir: string): Promise<void> {
445 children.delete(dir)
446 warned.delete(`config:${dir}`)
447 await childScope($, dir)
448 await update($, session, value => clearCache(sessionOf(value)))
449}
450
451/** Where a file tool's path really lands, symbolic links resolved, mapped under the root. */
452async function realPathOf($: EngineInterface, call: Call, cwd: string, ctx: Context): Promise<string | undefined> {
453 const field = FILE_PATH_FIELDS[call.tool]
454 const given = field === undefined ? undefined : call.input[field]
455 if (typeof given !== 'string') return undefined
456 const absolute = resolve(given, cwd, ctx.home)
457 const cut = absolute.lastIndexOf('/')
458 const own = await $.fs.stat(absolute, { resolve: true }).catch(() => undefined)
459 let real = own?.realPath
460 if (real === undefined) {
461 const folder = await $.fs.stat(absolute.slice(0, cut) || '/', { resolve: true }).catch(() => undefined)
462 if (folder?.realPath !== undefined) real = `${folder.realPath.replace(/\/$/, '')}/${absolute.slice(cut + 1)}`
463 }
464 if (real === undefined) return undefined
465 return ctx.realRoot !== ctx.root && (real === ctx.realRoot || isInside(real, ctx.realRoot))
466 ? `${ctx.root}${real.slice(ctx.realRoot.length)}`
467 : real
468}
469
470/** Content of scripts the call runs that Claude wrote this session, redacted. */
471async function scriptsOf(
472 $: EngineInterface,
473 classification: Classification,
474 cwd: string,
475 written: readonly string[],
476 ctx: Context,
477): Promise<{ path: string; content: string }[]> {
478 const scripts: { path: string; content: string }[] = []
479 for (const word of classification.scriptPaths) {
480 if (scripts.length >= MAX_SCRIPTS) break
481 const path = resolve(word, cwd, ctx.home)
482 if (!written.includes(path)) continue
483 const content = await $.fs.read(path).catch(() => undefined)
484 if (typeof content === 'string') {
485 scripts.push({ path, content: redact(truncate(content, GANDALF_LIMITS.scriptLines, GANDALF_LIMITS.scriptChars), ctx.patterns) })
486 }
487 }
488 return scripts
489}
490
491/**
492 * The folder git runs in: the deciding scope's, or, for a call that `cd`s
493 * inside the root, that folder with its links resolved. Undefined when it
494 * cannot be resolved or really lies outside the root (a link may lead out).
495 */
496async function gitDirOf($: EngineInterface, cwd: string | undefined, ctx: CallContext): Promise<string | undefined> {
497 if (cwd === undefined) return ctx.gitDir
498 const real = (await $.fs.stat(cwd, { resolve: true }).catch(() => undefined))?.realPath
499 return real !== undefined && (real === ctx.realRoot || isInside(real, ctx.realRoot)) ? real : undefined
500}
501
502/**
503 * Runs one git inspection from the table: its argv, then, only if that exits
504 * non-zero or throws and the table gives one, its fixed `orElse` argv, once.
505 * The fallback's result (and label) stands only if it succeeds; otherwise the
506 * first attempt's outcome is kept, as if there were no fallback. A step with
507 * a folder of its own runs there if that really lies inside the root, and
508 * does not run (it throws, as any failure) if not.
509 */
510async function runGitInspection(
511 $: EngineInterface,
512 step: { label: string; argv: readonly string[]; orElse?: { label: string; argv: readonly string[] }; cwd?: string },
513 ctx: CallContext,
514): Promise<{ label: string; run: ProcessRunResult }> {
515 const dir = await gitDirOf($, step.cwd, ctx)
516 if (dir === undefined) throw new Error('git would run outside the project')
517 const attempt = (argv: readonly string[]): Promise<ProcessRunResult> => $.process.run(argv, { cwd: dir, env: GIT_ENV, timeoutMs: INSPECTION_TIMEOUT_MS })
518 let first: ProcessRunResult | undefined
519 let failure: unknown
520 try {
521 first = await attempt(step.argv)
522 if (first.exitCode === 0 || step.orElse === undefined) return { label: step.label, run: first }
523 } catch (error) {
524 if (step.orElse === undefined) throw error
525 failure = error
526 }
527 try {
528 const second = await attempt(step.orElse.argv)
529 if (second.exitCode === 0) return { label: step.orElse.label, run: second }
530 } catch {
531 // The fallback failing leaves the first attempt's outcome.
532 }
533 if (first === undefined) throw failure
534 return { label: step.label, run: first }
535}
536
537/**
538 * Runs Galadriel's inspections: only what the table planned, read-only, each
539 * on its own timeout. A failure is no preview, never a decision.
540 */
541async function previewOf($: EngineInterface, plan: readonly Inspection[], ctx: CallContext): Promise<string | undefined> {
542 const results: InspectionResult[] = []
543 for (const step of plan) {
544 try {
545 if (step.kind === 'path') {
546 const stat = await $.fs.stat(step.path).catch(() => undefined)
547 if (stat === undefined) {
548 results.push({ kind: 'path', label: step.label, state: 'missing' })
549 } else if (stat.kind === 'dir') {
550 const entries = await $.fs.list(step.path)
551 const names = entries.slice(0, MAX_LISTED).map(entry => (entry.kind === 'dir' ? `${entry.name}/` : entry.name))
552 results.push({ kind: 'path', label: step.label, state: 'dir', entries: names, total: entries.length })
553 } else {
554 results.push({ kind: 'path', label: step.label, state: 'file', size: stat.size })
555 }
556 } else {
557 const { label, run } = await runGitInspection($, step, ctx)
558 results.push({ kind: 'git', label, exitCode: run.exitCode, stdout: run.stdout.slice(0, 50_000) })
559 }
560 } catch {
561 results.push({ kind: 'failed', label: step.label })
562 }
563 }
564 const preview = formatPreview(results, settings.previewLines)
565 return preview === undefined ? undefined : redact(preview, ctx.patterns)
566}
567
568/**
569 * What a file tool would change, as a diff against the file as it stands,
570 * redacted. Reading the file is the only I/O; nothing runs.
571 */
572async function fileDiffOf($: EngineInterface, call: Call, cwd: string, realPath: string | undefined, ctx: Context): Promise<{ path: string; diff: CallDiff } | undefined> {
573 const field = FILE_PATH_FIELDS[call.tool]
574 const given = field === undefined ? undefined : call.input[field]
575 if (field === undefined) return undefined
576 if (typeof given !== 'string') return { path: '(no path)', diff: callDiff(call, '(no path)', { state: 'unreadable' }, settings.diffLines) }
577 const absolute = realPath ?? resolve(given, cwd, ctx.home)
578 const path = relativeTo(absolute, ctx.root) || absolute
579 let current: Current
580 if (!(await $.fs.exists(absolute).catch(() => true))) {
581 current = { state: 'missing' }
582 } else {
583 const content = await $.fs.read(absolute).catch(() => undefined)
584 current = typeof content === 'string' ? { state: 'text', text: content } : { state: 'unreadable' }
585 }
586 const diff = callDiff(call, path, current, settings.diffLines)
587 return { path, diff: { ...diff, diff: redact(diff.diff, ctx.patterns) } }
588}
589
590/** The `.sql` files a database call names, read when they sit inside the project, redacted and cut. */
591async function sqlFilesOf($: EngineInterface, files: readonly { word: string; cwd?: string }[], cwd: string, ctx: Context): Promise<SqlPiece[]> {
592 const pieces: SqlPiece[] = []
593 for (const file of files) {
594 const path = resolve(file.word.replace(/^['"]|['"]$/g, ''), file.cwd ?? cwd, ctx.home)
595 if (!isInside(path, ctx.root)) continue
596 // Inside by name is not enough: a link may land outside the project.
597 const real = (await $.fs.stat(path, { resolve: true }).catch(() => undefined))?.realPath
598 if (real === undefined || !isInside(real, ctx.realRoot)) continue
599 const content = await $.fs.read(real).catch(() => undefined)
600 if (typeof content === 'string') {
601 pieces.push({ label: relativeTo(path, ctx.root) ?? path, text: redact(truncate(content, ARAGORN_LIMITS.sqlLines, ARAGORN_LIMITS.sqlChars), ctx.patterns) })
602 }
603 }
604 return pieces
605}
606
607/** What the seated member is given: the context its profile asks for, and nothing else. */
608async function briefOf(
609 $: EngineInterface,
610 seat: Seat,
611 call: Call,
612 classification: Classification,
613 cwd: string,
614 realPath: string | undefined,
615 state: CouncilSession,
616 preview: string | undefined,
617 ctx: Context,
618): Promise<Brief> {
619 const ruleReasons = [...new Set(classification.findings.map(finding => finding.reason))]
620 const shown = callText(call, ctx.patterns)
621 const latestPrompt = state.latestPrompt
622 const withPreview = preview !== undefined ? { preview } : {}
623 // Routing seats the diff reviewer on file tools only, which always have a diff.
624 const file = seat.member === 'gandalf' || seat.profile === 'git' ? undefined : await fileDiffOf($, call, cwd, realPath, ctx)
625 if (seat.member === 'legolas' && file !== undefined) {
626 return { member: 'legolas', context: { tool: call.tool, path: file.path, diff: file.diff, ruleReasons, latestPrompt, ...withPreview } }
627 }
628 if (seat.member === 'aragorn' && seat.profile === 'git') {
629 return {
630 member: 'aragorn',
631 profile: 'git',
632 context: { tool: call.tool, call: shown, ruleReasons, latestPrompt, protectedBranches: ctx.loaded.compiled.config.protectedBranches, ...withPreview },
633 }
634 }
635 if (seat.member === 'aragorn') {
636 const found = sqlOf(classification)
637 const inline = found.inline.map(piece => ({ label: piece.label, text: redact(piece.text, ctx.patterns) }))
638 const sql = [...inline, ...(await sqlFilesOf($, found.files, cwd, ctx))]
639 const production = productionHits([shown, ...sql.map(piece => piece.text)].join('\n'), ctx.loaded.compiled.production)
640 return {
641 member: 'aragorn',
642 profile: 'database',
643 context: { tool: call.tool, call: shown, ruleReasons, latestPrompt, sql, production, ...(file !== undefined && { diff: file.diff }) },
644 }
645 }
646 const scripts = await scriptsOf($, classification, cwd, state.written, ctx)
647 return { member: 'gandalf', context: { tool: call.tool, call: shown, ruleReasons, latestPrompt, scripts, ...withPreview } }
648}
649
650/**
651 * One model review, for any member: its own system prompt and prompt, the
652 * model's request settings, a deadline passed as the call's own timeout,
653 * and the strict verdict parse. Every failure is a review without a verdict.
654 */
655async function review($: EngineInterface, brief: Brief, model: string, deadlineMs: number, signal: AbortSignal): Promise<Review> {
656 const nonce = newNonce()
657 const request = requestOf(brief, nonce)
658 const limits = profileOf(model)
659 const who = text(whoOf(brief.member, brief.profile))
660 try {
661 const reply = await $.model.complete(
662 {
663 model,
664 system: request.system,
665 prompt: request.prompt,
666 maxTokens: limits.maxTokens,
667 ...(limits.effort !== undefined && { effort: limits.effort }),
668 timeoutMs: deadlineMs,
669 },
670 { signal },
671 )
672 const usage = reply.usage
673 const tokens =
674 usage.input_tokens + usage.output_tokens + usage.cache_creation_input_tokens + usage.cache_read_input_tokens
675 if (!reply.isAnswered) {
676 const problem =
677 reply.reason === 'aborted'
678 ? 'it ran out of time or was interrupted'
679 : reply.reason === 'api-error'
680 ? `the API answered with an error (${reply.error})`
681 : 'it gave an empty reply'
682 if (reply.reason === 'api-error' && ['model_not_found', 'invalid_request', 'authentication_failed'].includes(reply.error)) {
683 warnOnce($, `model:${model}`, text('notice.modelFailed', { who, model, problem }))
684 }
685 return { ok: false, problem, model, tokens }
686 }
687 const parsed = parseVerdict(reply.text)
688 return parsed.ok
689 ? { ok: true, verdict: parsed.verdict, model, tokens }
690 : { ok: false, problem: `malformed verdict: ${parsed.problem}`, model, tokens }
691 } catch (error) {
692 const problem = `the request was refused: ${error instanceof Error ? error.message : String(error)}`
693 warnOnce($, `model:${model}`, text('notice.modelFailed', { who, model, problem }))
694 return { ok: false, problem, model, tokens: 0 }
695 }
696}
697
698/** The checked-out branch, for whether a merge lands on a protected one; unknown on any failure. */
699async function currentBranchOf($: EngineInterface, dir: string): Promise<string | undefined> {
700 try {
701 const run = await $.process.run(['git', 'rev-parse', '--abbrev-ref', 'HEAD'], { cwd: dir, env: GIT_ENV, timeoutMs: INSPECTION_TIMEOUT_MS })
702 const branch = run.stdout.trim()
703 return run.exitCode === 0 && branch !== '' ? branch : undefined
704 } catch {
705 return undefined
706 }
707}
708
709/**
710 * What a push would send or a merge bring in, for the diff reviewer: one
711 * read-only `git diff` from Galadriel's table, cut to the diff limit and
712 * redacted, with the range that was read (the table's fallback range when the
713 * first can't be read). Undefined when git can't say.
714 */
715async function rangeDiffOf($: EngineInterface, step: Extract<Inspection, { kind: 'git' }>, ctx: CallContext): Promise<{ label: string; diff: string } | undefined> {
716 try {
717 const { label, run } = await runGitInspection($, step, ctx)
718 if (run.exitCode !== 0) return undefined
719 const diff = run.stdout.slice(0, LEGOLAS_LIMITS.diffChars * 4).trimEnd()
720 return { label, diff: redact(truncate(diff === '' ? '(no changes)' : diff, settings.diffLines, LEGOLAS_LIMITS.diffChars), ctx.patterns) }
721 } catch {
722 return undefined
723 }
724}
725
726/**
727 * Runs one of the project's checks from a rules file, by argument vector,
728 * in the directory of the scope that lists it. Its own timeout ends it (a clock timer, which costs
729 * the hook no budget while the child's output is awaited); so does `stop`
730 * once the council has blocked, and Esc, through the dispatch's signal.
731 */
732async function runCheck($: EngineInterface, command: GimliCommand, dir: string, stop: AbortSignal): Promise<GimliRun> {
733 const started = await $.clock.now()
734 let ended: 'timeout' | 'stopped' | undefined
735 let exit: ProcessSpawnResult | undefined
736 let output = ''
737 let rejection: string | undefined
738 let isEnded: () => void = () => undefined
739 const endedEarly = new Promise<void>(resolve => {
740 isEnded = resolve
741 })
742 const stream = $.process.spawn({ argv: command.argv, cwd: dir })
743 const end = (why: 'timeout' | 'stopped'): void => {
744 if (ended !== undefined || exit !== undefined) return
745 ended = why
746 isEnded()
747 // Ending the loop is what kills the child.
748 void stream.return(undefined as never).catch(() => undefined)
749 }
750 const timer = $.clock.after(command.timeoutMs, () => end('timeout'))
751 const onStop = (): void => end('stopped')
752 stop.addEventListener('abort', onStop)
753 if (stop.aborted) onStop()
754 const reading = (async () => {
755 for await (const chunk of stream) output = keepTail(output, chunk.text)
756 if (ended === undefined) exit = await stream.result
757 })().catch((error: unknown) => {
758 // It could not start, or its stream broke: no exit code, so it does not pass. Keep the engine's message to tell Claude why.
759 rejection = error instanceof Error ? error.message : String(error)
760 })
761 try {
762 // Ended early, the run is over even if the stream is slow to close.
763 await Promise.race([reading, endedEarly])
764 } finally {
765 timer.cancel()
766 stop.removeEventListener('abort', onStop)
767 }
768 const ms = (await $.clock.now()) - started
769 const status = statusOf(ended, exit)
770 return {
771 name: command.name,
772 status,
773 ...(ended === undefined && exit !== undefined && { code: exit.code, signal: exit.signal }),
774 tail: tailOf(output),
775 // Only when it broke by itself: a run the council or the clock ended says nothing of the sort.
776 ...(status === 'error' && rejection !== undefined && { problem: rejection }),
777 ms,
778 }
779}
780
781/** One seat at the full council: who, and the brief it reviews (none: it sits out, saying why). */
782type Sitting = { seat: CouncilSeat; who: StringKey; brief?: Brief; skip?: string }
783
784type Held = { voices: Voice[]; tokens: number[]; runs: GimliRun[] }
785
786/** What `convene` reports as it goes, for the debate record: a voice resolved, or a check ended. */
787type Progress = { kind: 'voice'; index: number; voice: Voice } | { kind: 'check'; run: GimliRun }
788
789/**
790 * The full council. The project's checks start first and run on their own
791 * timeouts (decision 3); the model members run in parallel, or one at a time
792 * stopping at the first block, under one shared deadline passed to each
793 * request as the time remaining. Each member sees only its own brief.
794 */
795async function convene(
796 $: EngineInterface,
797 sittings: readonly Sitting[],
798 model: string,
799 deadlineMs: number,
800 isSequential: boolean,
801 checks: readonly { command: GimliCommand; dir: string }[],
802 signal: AbortSignal,
803 progress: (event: Progress) => Promise<void>,
804): Promise<Held> {
805 const started = await $.clock.now()
806 const stop = new AbortController()
807 // Esc ends the checks through the engine killing their children; chaining the signal makes that ours too.
808 const onAbort = (): void => stop.abort()
809 signal.addEventListener('abort', onAbort)
810 if (signal.aborted) onAbort()
811 try {
812 let isCheckFailed = false
813 // The debate record is only watching: a note that fails or lags changes nothing here.
814 const noted: Promise<void>[] = []
815 const note = (event: Progress): void => {
816 noted.push(Promise.resolve().then(() => progress(event)).catch(() => undefined))
817 }
818 const checking = Promise.all(
819 checks.map(check =>
820 runCheck($, check.command, check.dir, stop.signal).then(run => {
821 if (isGimliBlock(run)) {
822 isCheckFailed = true
823 stop.abort()
824 }
825 note({ kind: 'check', run })
826 return run
827 }),
828 ),
829 )
830 const tokens: number[] = sittings.map(() => 0)
831 const baseOf = (sitting: Sitting) => ({ who: sitting.who, member: sitting.seat.member, ...(sitting.seat.member === 'aragorn' && { profile: sitting.seat.profile }) })
832 const ask = async (sitting: Sitting, index: number): Promise<Voice> => {
833 const base = baseOf(sitting)
834 if (sitting.brief === undefined) return { kind: 'skipped', ...base, why: sitting.skip ?? '' }
835 const remaining = Math.floor(deadlineMs - ((await $.clock.now()) - started))
836 if (remaining < 1) return { kind: 'failed', ...base, problem: text('council.deadline') }
837 const result = await review($, sitting.brief, model, remaining, signal)
838 tokens[index] = result.tokens
839 return result.ok ? { kind: 'verdict', ...base, verdict: result.verdict } : { kind: 'failed', ...base, problem: result.problem }
840 }
841 const resolved = (index: number, voice: Voice): Voice => {
842 note({ kind: 'voice', index, voice })
843 return voice
844 }
845 let voices: Voice[]
846 if (isSequential) {
847 voices = []
848 for (const [index, sitting] of sittings.entries()) {
849 const isBlocked = isCheckFailed || voices.some(voice => voice.kind === 'failed' || (voice.kind === 'verdict' && voice.verdict.verdict === 'block'))
850 voices.push(
851 resolved(index, isBlocked ? { kind: 'skipped', ...baseOf(sitting), why: text('council.stopped') } : await ask(sitting, index)),
852 )
853 }
854 } else {
855 voices = await Promise.all(sittings.map(async (sitting, index) => resolved(index, await ask(sitting, index))))
856 }
857 // A check can only add a block: once a member has blocked, one still running cannot matter.
858 if (hasRealBlock(voices)) stop.abort()
859 const runs = await checking
860 await Promise.all(noted)
861 return { voices, tokens, runs }
862 } finally {
863 // A throw above would otherwise leave a check running to its own timeout (up to 600 s).
864 stop.abort()
865 signal.removeEventListener('abort', onAbort)
866 }
867}
868
869/** Puts the call to the user; where nobody can be asked, says so. */
870async function escalate($: EngineInterface, question: string, withAllowlist: boolean): Promise<Answer | Unanswered> {
871 const surfaces = await $.session.surfaces()
872 if (surfaces.length === 0) return 'unavailable'
873 try {
874 // One mode for the labels offered and the labels compared: they must match exactly.
875 const mode = currentMode()
876 const answer = await $.ui.ask(question, { options: optionsOf(mode, withAllowlist), header: text('ask.rollHeader', {}, mode) })
877 return interpretAnswer(answer, mode, withAllowlist)
878 } catch {
879 // The engine's "Chat about this" rejects exactly like a dismissal and cannot be told apart (DESIGN §12.4).
880 return 'dismissed'
881 }
882}
883
884/** The second confirm before an allowlist entry is written: only "Add it" adds. */
885async function confirmAllowlist($: EngineInterface, finding: GollumFinding): Promise<boolean> {
886 const base = text('ask.confirmAllowlist', { label: finding.label, entry: finding.fingerprint, path: OVERRIDES_PATH, field: 'gollum.allowlist' })
887 const question = warnsPasswordFingerprint(finding) ? `${base}\n${text('ask.confirmAllowlistPassword')}` : base
888 try {
889 const answer = await $.ui.ask(question, { options: [text('ask.confirmAdd'), text('ask.confirmCancel')], header: text('ask.header') })
890 return answer === text('ask.confirmAdd')
891 } catch {
892 return false
893 }
894}
895
896/**
897 * Rewrites the project rules file with one confirmed change, read fresh: a
898 * broken file is left alone, and a result that doesn't validate isn't written.
899 */
900async function writeOverrides($: EngineInterface, root: string, change: (current: string | undefined) => FileEdit): Promise<FileEdit> {
901 const path = `${root}/${OVERRIDES_PATH}`
902 try {
903 const current = (await $.fs.exists(path)) ? await $.fs.read(path) : undefined
904 const edit = change(current)
905 if (edit.ok) await $.fs.write(path, edit.text)
906 return edit
907 } catch (error) {
908 return { ok: false, problem: error instanceof Error ? error.message : String(error) }
909 }
910}
911
912/**
913 * After "allow once" and a call that ran: offers the allow rule for it, showing
914 * the exact JSON, and writes it only on "Add the rule" (then reloads, decision
915 * 9). Any other answer, or dismissing, declines it for the session. Returns the
916 * id of the rule written. `where` is the single scope's (its root is `dir`), and
917 * the rule goes to the rules file in `dir`.
918 */
919async function offerRule(
920 $: EngineInterface,
921 call: Call,
922 classification: Classification,
923 where: ClassifyContext,
924 ctx: Context,
925 hadSecret: boolean,
926 dir: string,
927): Promise<string | undefined> {
928 const state = sessionOf(await read($, session))
929 const suggested = suggestRule(call, classification, ctx.loaded.compiled, where, { hadSecret, declined: state.declinedRules })
930 if (suggested.kind === 'none') return undefined
931 const { rule, key } = suggested.suggestion
932 if ((await $.session.surfaces()).length === 0) return undefined
933 const question = text('ask.suggestRule', { path: OVERRIDES_PATH, json: ruleJson(rule) })
934 const answer = await $.ui
935 .ask(question, { options: [text('ask.suggestAdd'), text('ask.suggestDecline')], header: text('ask.header') })
936 .catch(() => undefined)
937 if (answer !== text('ask.suggestAdd')) {
938 await update($, session, value => declineRule(sessionOf(value), key))
939 return undefined
940 }
941 const written = await writeOverrides($, dir, current => withRule(current, rule))
942 if (!written.ok) {
943 $.ui.log(text('notice.ruleFailed', { problem: written.problem }))
944 return undefined
945 }
946 await reloadAt($, ctx, dir)
947 $.ui.log(text('notice.ruleWritten', { id: rule.id, path: OVERRIDES_PATH }))
948 return rule.id
949}
950
951async function appendAudit($: EngineInterface, record: AuditRecord, root: string): Promise<void> {
952 const path = resolve(settings.auditLogPath, root)
953 const folder = path.slice(0, path.lastIndexOf('/'))
954 if (!gitignoreChecked.has(folder)) {
955 gitignoreChecked.add(folder)
956 const ignore = `${folder}/.gitignore`
957 if (isInside(path, root) && !(await $.fs.exists(ignore))) await $.fs.write(ignore, AUDIT_GITIGNORE)
958 }
959 const line = auditLine(record)
960 const current = (await $.fs.exists(path)) ? await $.fs.read(path) : ''
961 const maxBytes = settings.auditMaxKb * 1024
962 const older: (string | undefined)[] = []
963 if (isRotation(current, line, maxBytes)) {
964 for (let n = 1; n < ROTATED_FILES - 1; n++) {
965 const rotated = `${path}.${n}`
966 older.push((await $.fs.exists(rotated)) ? await $.fs.read(rotated) : undefined)
967 }
968 }
969 for (const write of appendPlan(path, current, line, maxBytes, older)) await $.fs.write(write.path, write.text)
970}
971
972/**
973 * Queues one audit line for each of `dirs` (the call's repositories, else the
974 * root: DESIGN §14.5). Writes run in order, but nobody waits for them: a
975 * failed write is logged and a hanging one holds back only the lines queued
976 * after it, never a decision or the call that follows.
977 */
978function audit($: EngineInterface, record: AuditRecord, dirs: readonly string[]): void {
979 for (const dir of dirs) {
980 auditQueue = auditQueue
981 .then(() => appendAudit($, record, dir))
982 .catch((error: unknown) => {
983 $.ui.log(text('notice.auditFailed', { problem: error instanceof Error ? error.message : String(error) }), { to: 'debug' })
984 })
985 }
986}
987
988/** Notes a file Claude wrote, once the write has run. */
989async function noteWrite($: EngineInterface, call: Call, cwd: string, home: string | undefined, result: ToolCallResult): Promise<void> {
990 const field = FILE_PATH_FIELDS[call.tool]
991 const given = field === undefined ? undefined : call.input[field]
992 const isWritten = typeof given === 'string' && result.deny === undefined && result.isError !== true
993 if (isWritten) await update($, session, value => noteWritten(sessionOf(value), resolve(given, cwd, home)))
994}
995
996/**
997 * The label by the prompt where SessionMode is not drawn (other surfaces): the
998 * status line. Cleared when no such surface is left, so a line set for a phone
999 * does not outlive it.
1000 */
1001async function syncIndicator($: EngineInterface): Promise<void> {
1002 const state = sessionOf(await read($, session))
1003 const label = state.bypass ? text('mode.bypass') : isShadow(state, settings.shadowMode) ? text('mode.shadow') : undefined
1004 const surfaces = await $.session.surfaces()
1005 $.ui.status(surfaces.some(surface => surface !== 'terminal' && surface !== 'desktop') ? label : undefined)
1006}
1007
1008/**
1009 * Where nothing draws, the start notice goes in as a row the model reads (the
1010 * only channel to the person). A refusal or a failure is logged, never raised:
1011 * session start goes on.
1012 */
1013async function announce($: EngineInterface): Promise<void> {
1014 try {
1015 if ((await $.session.surfaces()).length > 0) return
1016 const result = await $.session.append({ message: { type: 'user', content: [{ type: 'text', text: noticeText() }] } })
1017 if (result.deny !== undefined) $.ui.log(text('notice.appendFailed', { problem: result.deny }), { to: 'debug' })
1018 } catch (error) {
1019 $.ui.log(text('notice.appendFailed', { problem: error instanceof Error ? error.message : String(error) }), { to: 'debug' })
1020 }
1021}
1022
1023/**
1024 * `/council` output as the command's `context`, for a person's command where
1025 * nothing draws; else undefined. It is built again, in plain (nothing Claude
1026 * reads is themed) and, for rules, without the allowlist's characters; every
1027 * line is then redacted (relay.ts).
1028 */
1029async function relayOf($: EngineInterface, command: CouncilCommand, origin: string): Promise<readonly string[] | undefined> {
1030 if (!isRelayed(command) || !HUMAN_ORIGINS.has(origin)) return undefined
1031 if ((await $.session.surfaces()).length > 0) return undefined
1032 const ctx = await contextOf($)
1033 return [relayContext(command, await councilOutput($, command, 'plain'), ctx.patterns, newNonce())]
1034}
1035
1036/** Shows `/council` output to the user: in its pane where one draws, else as transcript lines. */
1037async function show($: EngineInterface, output: Output): Promise<void> {
1038 const surfaces = await $.session.surfaces()
1039 if (surfaces.length > 0) {
1040 await update($, panel, () => output)
1041 const opened = await $.ui.open({ id: PANE_ID, title: output.title }).catch(() => undefined)
1042 if (opened?.isPlaced === true) return
1043 }
1044 $.ui.log(output.title)
1045 for (const line of output.lines) $.ui.log(line)
1046}
1047
1048/** Rows as a column of Text: a theme key for colour, never a raw colour, so a theme change reaches them. */
1049function drawRows(Box: Parameters<typeof h>[0], Text: Parameters<typeof h>[0], rows: readonly Row[], wrap: 'wrap' | 'truncate'): RenderElement {
1050 const lines = rows.map(row =>
1051 h(Text, { wrap, ...(row.color !== undefined && { color: row.color }), ...(row.bold === true && { bold: true }), ...(row.dim === true && { dimColor: true }) }, row.text),
1052 )
1053 return h(Box, { flexDirection: 'column' }, ...lines) as RenderElement
1054}
1055
1056/**
1057 * Opens the debate pane unasked, once per session: the engine itself keeps an
1058 * unasked open undrawn below 144 columns, so the mod never measures the terminal.
1059 * A refused open is ignored; it is never retried.
1060 */
1061async function openDebatePane($: EngineInterface): Promise<void> {
1062 if (sessionOf(await read($, session)).debateOpened) return
1063 // Claimed before the open, so a parallel call does not open it too.
1064 await update($, session, value => markDebateOpened(sessionOf(value)))
1065 if ((await $.session.surfaces()).length === 0) return
1066 await $.ui.open({ id: DEBATE_PANE_ID, title: text('debate.title'), rows: DEBATE_PANE_ROWS }).catch(() => undefined)
1067}
1068
1069/** `/council debate`: the pane at any width (it answers the person's command), else the same rows as transcript lines. */
1070async function showDebate($: EngineInterface): Promise<void> {
1071 const surfaces = await $.session.surfaces()
1072 if (surfaces.length > 0) {
1073 const opened = await $.ui.open({ id: DEBATE_PANE_ID, title: text('debate.title'), rows: DEBATE_PANE_ROWS }).catch(() => undefined)
1074 if (opened?.isPlaced === true) return
1075 }
1076 $.ui.log(text('debate.title'))
1077 for (const row of debateRows(sessionOf(await read($, session)), undefined, currentMode())) $.ui.log(row.text)
1078}
1079
1080/**
1081 * The epic drop (themed mode, a pushed or merged call the full council
1082 * approved): the row hides itself once `epicUntil` passes, whatever happens to
1083 * the timer, which is only a redraw trigger (a hot reload cancels it).
1084 */
1085async function epicDrop($: EngineInterface): Promise<void> {
1086 const until = (await $.clock.now()) + EPIC_MS
1087 await update($, session, value => withEpic(sessionOf(value), until))
1088 $.ui.toast(text('epic.toast'), { timeoutMs: EPIC_MS })
1089 $.clock.after(EPIC_MS + 100, () => {
1090 void (async () => {
1091 try {
1092 const now = await $.clock.now()
1093 await update($, session, value => clearEpic(sessionOf(value), now))
1094 } catch {
1095 // The row hides itself at its time anyway.
1096 }
1097 })()
1098 })
1099}
1100
1101/** `/council report`: the rotated files (oldest first), then the current one; an unreadable file is named and left out. */
1102async function reportFrom($: EngineInterface, path: string, mode?: Mode): Promise<Output> {
1103 const files: string[] = []
1104 const unreadable: string[] = []
1105 for (const file of [...Array.from({ length: ROTATED_FILES - 1 }, (_, i) => `${path}.${ROTATED_FILES - 1 - i}`), path]) {
1106 try {
1107 if (await $.fs.exists(file)) files.push(await $.fs.read(file))
1108 } catch (error) {
1109 unreadable.push(`${file}: ${error instanceof Error ? error.message : String(error)}`)
1110 }
1111 }
1112 return mode === undefined ? reportOutput(files, unreadable) : withMode(mode, () => reportOutput(files, unreadable))
1113}
1114
1115/** A one-request check that a model answers: an API error is a no, a timeout unsure. */
1116async function probeModel($: EngineInterface, model: string): Promise<{ ok: true } | { ok: false; isCertain: boolean; problem: string }> {
1117 try {
1118 const reply = await $.model.complete({ model, prompt: 'Reply with the single word OK.', maxTokens: 16, timeoutMs: PROBE_TIMEOUT_MS })
1119 const usage = reply.usage
1120 await update($, session, value => addTokens(sessionOf(value), usage.input_tokens + usage.output_tokens))
1121 if (reply.isAnswered || reply.reason === 'empty-reply') return { ok: true }
1122 if (reply.reason === 'api-error') return { ok: false, isCertain: true, problem: reply.error }
1123 return { ok: false, isCertain: false, problem: 'no answer in time' }
1124 } catch (error) {
1125 return { ok: false, isCertain: true, problem: error instanceof Error ? error.message : String(error) }
1126 }
1127}
1128
1129function modelChoice(slot: ModelSlot, ctx: Context, sessionModels: Readonly<Partial<Record<ModelSlot, string>>>): ModelChoice {
1130 const project = ctx.loaded.compiled.config.models[slot]
1131 const sessionModel = sessionModels[slot]
1132 return resolveModel(slot, {
1133 settings: settingsModel(slot),
1134 ...(project !== undefined && { project }),
1135 ...(sessionModel !== undefined && { session: sessionModel }),
1136 })
1137}
1138
1139/** The project checks a call would run: every touched scope's, each in its own directory (empty when Gimli is off). */
1140const checksIn = (ctx: CallContext): { command: GimliCommand; dir: string }[] =>
1141 settings.gimliEnabled ? checksOf(ctx.scopes.map(scope => ({ dir: scope.dir, commands: scope.loaded.compiled.config.gimli.commands }))) : []
1142
1143async function councilModel($: EngineInterface, command: Extract<CouncilCommand, { kind: 'model' }>): Promise<Output> {
1144 const title = text('cmd.title')
1145 if (!isSlot(command.slot)) return { title, lines: [text('cmd.modelBadSlot', { slot: command.slot, slots: MODEL_SLOTS.join(', ') })] }
1146 const slot = command.slot
1147 const ctx = await contextOf($)
1148 const before = sessionOf(await read($, session))
1149 if (command.model === 'default') {
1150 const after = await update($, session, value => withSessionModel(sessionOf(value), slot, undefined))
1151 const now = modelChoice(slot, ctx, after.models)
1152 return { title, lines: [text('cmd.modelCleared', { id: slot, model: now.model, source: now.source })] }
1153 }
1154 if (!MODEL_ID.test(command.model)) return { title, lines: [text('cmd.modelBadId', { model: command.model })] }
1155
1156 const lines: string[] = []
1157 const probe = await probeModel($, command.model)
1158 if (!probe.ok && probe.isCertain) {
1159 const previous = modelChoice(slot, ctx, before.models)
1160 return { title, lines: [text('cmd.modelProbeFailed', { model: command.model, problem: probe.problem, id: slot, previous: previous.model })] }
1161 }
1162 await update($, session, value => withSessionModel(sessionOf(value), slot, command.model))
1163 lines.push(text('cmd.modelSet', { id: slot, model: command.model }))
1164 if (!probe.ok) lines.push(text('cmd.modelProbeUnsure', { model: command.model, problem: probe.problem }))
1165 if (command.save) {
1166 const row = CONFIG_ROWS[slot]
1167 if (row === undefined) {
1168 lines.push(text('cmd.modelNotSaved', { problem: text('cmd.modelNoRow', { id: slot }) }))
1169 } else if (!PICKER_OPTIONS.includes(command.model)) {
1170 lines.push(text('cmd.modelNotSaved', { problem: text('cmd.modelNotOption', { options: PICKER_OPTIONS.join(', ') }) }))
1171 } else {
1172 const saved = await $.config.set({ key: row, value: command.model }).catch((error: unknown) => ({
1173 deny: error instanceof Error ? error.message : String(error),
1174 }))
1175 lines.push(saved.deny === undefined ? text('cmd.modelSaved') : text('cmd.modelNotSaved', { problem: saved.deny }))
1176 }
1177 }
1178 return { title, lines }
1179}
1180
1181/**
1182 * The output of one subcommand. The `$` reads come first; the pure builders then
1183 * run in `mode` when one is given (the copy Claude reads is built in plain). A
1184 * mode is given only for that copy, so it also hides the allowlist entries.
1185 */
1186async function councilOutput($: EngineInterface, command: Exclude<CouncilCommand, { kind: 'debate' }>, mode?: Mode): Promise<Output> {
1187 const title = text('cmd.title')
1188 // Synchronous builders only: nothing that reads `$` goes inside.
1189 const inMode = (build: () => Output): Output => (mode === undefined ? build() : withMode(mode, build))
1190 switch (command.kind) {
1191 case 'status': {
1192 const ctx = await contextOf($)
1193 const state = sessionOf(await read($, session))
1194 const runMode = state.bypass ? 'bypass' : isShadow(state, settings.shadowMode) ? 'shadow' : 'enforcing'
1195 const input: StatusInput = {
1196 session: state,
1197 mode: runMode,
1198 members: {
1199 gandalf: { enabled: settings.gandalfEnabled, choice: modelChoice('gandalf', ctx, state.models) },
1200 legolas: { enabled: settings.legolasEnabled, choice: modelChoice('legolas', ctx, state.models) },hooks/audit.ts 151 lines1import { redact } from './redact.js'
2
3/**
4 * The audit log: one JSONL line per gated call. It holds no file contents,
5 * diffs or secrets: the call itself appears only as its fingerprint, and the
6 * reasons are redacted and cut.
7 */
8
9/** `chat` is "Talk first"; `chat-allow`, `chat-session` and `chat-deny` are a person's typed council allow / deny (ROADMAP C4). */
10export type Decision =
11 | 'allow-once'
12 | 'allowlist'
13 | 'keep-blocked'
14 | 'instruction'
15 | 'dismissed'
16 | 'chat'
17 | 'unavailable'
18 | 'chat-allow'
19 | 'chat-session'
20 | 'chat-deny'
21
22export type AuditRecord = {
23 ts: string
24 tool: string
25 /** SHA-256 of the tool and its whitespace-collapsed arguments, cut to 16 hex digits. */
26 fingerprint: string
27 /** The operation key: what the call attempts, so rephrased retries share it. */
28 opKey: string | null
29 tier: string
30 ruleId: string | null
31 member: string | null
32 profile: string | null
33 model: string | null
34 verdict: string | null
35 reason: string | null
36 shadow: boolean
37 bypass: boolean
38 /** The user's answer, when the call was escalated. */
39 decision: Decision | null
40 /**
41 * What happened to the call: it ran, ran and errored, was refused by the
42 * council, was refused by the person at Claude Code's own permission
43 * prompt, or was denied by that check with nobody asked.
44 */
45 outcome: 'ran' | 'error' | 'refused' | 'refused-by-user' | 'denied-by-permission'
46 /** An identical call was approved earlier this prompt, so no reviewer ran. */
47 cached?: true
48 /**
49 * A big operation's full council: the entry that made it big, each member's
50 * own verdict (or `failed`, `skipped`) and tokens, each check's result. No output.
51 */
52 council?: {
53 entry: string
54 voices: readonly { member: string; profile: string | null; verdict: string; tokens: number }[]
55 checks: readonly { name: string; status: string; ms: number }[]
56 }
57 /** The whole call, from the hook's start to the result: tool run and the user's answers included. */
58 latencyMs: number
59 /** The model review alone (one member, or the full council), when one ran. */
60 reviewMs?: number
61 /** The id of the allow rule the user added for this call after allowing it once. */
62 ruleAdded?: string
63 tokens: number
64 /** Present for a subagent's call. */
65 agentId?: string
66}
67
68const MAX_REASON_CHARS = 300
69
70/** The one line written for a record, newline included. */
71export function auditLine(record: AuditRecord): string {
72 const reason =
73 record.reason === null
74 ? null
75 : (() => {
76 const clean = redact(record.reason).replace(/\s+/g, ' ').trim()
77 return clean.length > MAX_REASON_CHARS ? `${clean.slice(0, MAX_REASON_CHARS - 1)}…` : clean
78 })()
79 return `${JSON.stringify({ ...record, reason })}\n`
80}
81
82// Fields whose whitespace carries no meaning, so a reformatted value is the
83// same call. A shell command is one; a file's content is NOT (indentation is
84// significant in YAML, Python, Makefiles), so it is hashed exactly, or a
85// re-indented write would reuse an earlier approve without review.
86const INSIGNIFICANT_WHITESPACE = new Set(['command'])
87
88/** Sorts keys; collapses whitespace only in fields where it has no meaning. */
89function canonical(value: unknown, collapseWhitespace = false): unknown {
90 if (typeof value === 'string') return collapseWhitespace ? value.replace(/\s+/g, ' ').trim() : value
91 if (Array.isArray(value)) return value.map(item => canonical(item, collapseWhitespace))
92 if (typeof value === 'object' && value !== null) {
93 return Object.fromEntries(
94 Object.keys(value)
95 .sort()
96 .map(key => [key, canonical((value as Record<string, unknown>)[key], INSIGNIFICANT_WHITESPACE.has(key))]),
97 )
98 }
99 return value
100}
101
102/**
103 * The text a fingerprint hashes: tool name plus arguments, canonicalised. A
104 * `scope` (the repositories a call touches, C5) is mixed in when given, so one
105 * call in two repositories has two keys; none leaves the text as it always was.
106 */
107export const fingerprintText = (tool: string, input: unknown, scope = ''): string =>
108 `${tool}\u0000${JSON.stringify(canonical(input))}${scope === '' ? '' : `\u0000scope\u0000${scope}`}`
109
110export async function fingerprintOf(tool: string, input: unknown, scope = ''): Promise<string> {
111 const bytes = new TextEncoder().encode(fingerprintText(tool, input, scope))
112 const digest = new Uint8Array(await crypto.subtle.digest('SHA-256', bytes))
113 return Array.from(digest.slice(0, 8), byte => byte.toString(16).padStart(2, '0')).join('')
114}
115
116export const ROTATED_FILES = 3
117
118const encoder = new TextEncoder()
119
120/** The UTF-8 size of a text: the unit the log's limit is in, which `.length` is not. */
121export const byteLength = (value: string): number => encoder.encode(value).length
122
123/** Whether appending `line` to `current` takes the file past `maxBytes`: the older files are read, and the log rotates, only then. */
124export const isRotation = (current: string, line: string, maxBytes: number): boolean =>
125 current !== '' && byteLength(current) + byteLength(line) > maxBytes
126
127/**
128 * The writes that append `line` to a log holding `current`: the new current
129 * file, plus the rotated files when the line would take it past `maxBytes`.
130 * `older` holds `<path>.1` .. `<path>.N-1` as read (undefined when absent).
131 */
132export function appendPlan(
133 path: string,
134 current: string,
135 line: string,
136 maxBytes: number,
137 older: readonly (string | undefined)[],
138): { path: string; text: string }[] {
139 if (!isRotation(current, line, maxBytes)) return [{ path, text: current + line }]
140 const writes: { path: string; text: string }[] = []
141 for (let n = ROTATED_FILES - 1; n >= 1; n--) {
142 const source = n === 1 ? current : older[n - 2]
143 if (source !== undefined) writes.push({ path: `${path}.${n}`, text: source })
144 }
145 writes.push({ path, text: line })
146 return writes
147}
148
149/** The `.gitignore` written beside the log, so it is never committed. */
150export const AUDIT_GITIGNORE = '# Written by the council mod: the audit log stays local.\n*\n'
151hooks/config/defaults.ts 321 lines1import type { Config, Rule } from './types.js'
2
3/**
4 * The shipped rules. Shell `command` patterns match one part of a compound
5 * command at a time, after quotes are removed and wrappers (`sudo`, `env`,
6 * `nice`, `timeout`, ...) and leading `NAME=value` assignments are stripped,
7 * with git's global options (`-C dir`, `-c k=v`) dropped. They are anchored
8 * at the program name.
9 *
10 * The rules are the safety boundary; the model members are a second opinion.
11 */
12
13const SHELL = ['Bash', 'Monitor'] as const
14const FILES = ['Write', 'Edit', 'NotebookEdit'] as const
15
16const BLOCK: readonly Rule[] = [
17 {
18 id: 'rm-recursive-outside-repo',
19 tier: 'block',
20 tools: SHELL,
21 check: 'rm-outside-repo',
22 reason:
23 'Recursive delete of the filesystem root, the home directory or a path outside the project.',
24 },
25 {
26 id: 'force-push-protected-branch',
27 tier: 'block',
28 tools: SHELL,
29 check: 'force-push-protected',
30 reason: 'Force push (or delete) of a protected branch.',
31 },
32 {
33 id: 'destructive-sql-production',
34 tier: 'block',
35 tools: SHELL,
36 check: 'destructive-sql-production',
37 reason: 'DROP or TRUNCATE against a target that looks like production.',
38 },
39 {
40 id: 'raw-disk-write',
41 tier: 'block',
42 tools: SHELL,
43 check: 'raw-disk-write',
44 reason: 'Writes directly to a disk device.',
45 },
46]
47
48const ASK: readonly Rule[] = [
49 {
50 id: 'privileged',
51 tier: 'ask',
52 tools: SHELL,
53 check: 'privileged',
54 reason: 'Runs with elevated privileges (sudo, doas, su).',
55 },
56]
57
58const REVIEW: readonly Rule[] = [
59 {
60 id: 'sql-file-write',
61 tier: 'review',
62 tools: FILES,
63 path: String.raw`\.sql$`,
64 member: 'aragorn',
65 profile: 'database',
66 reason: 'Writes or edits SQL.',
67 },
68 {
69 id: 'file-write',
70 tier: 'review',
71 tools: FILES,
72 member: 'legolas',
73 reason: 'Writes or edits a file.',
74 },
75 {
76 id: 'shell-delete',
77 tier: 'review',
78 tools: SHELL,
79 command: String.raw`^(rm|rmdir|unlink|shred|srm|trash|trash-put|rimraf|del-cli|trash-cli)(\s|$)`,
80 reason: 'Deletes files.',
81 },
82 {
83 id: 'shell-find-delete',
84 tier: 'review',
85 tools: SHELL,
86 command: String.raw`^find\s.*\s(-delete|-exec(dir)?\s|-ok(dir)?\s)`,
87 reason: 'Finds files and deletes or runs a command on each.',
88 },
89 {
90 id: 'shell-move',
91 tier: 'review',
92 tools: SHELL,
93 command: String.raw`^mv(\s|$)`,
94 reason: 'Moves or renames files, which can overwrite.',
95 },
96 {
97 id: 'shell-overwrite-tools',
98 tier: 'review',
99 tools: SHELL,
100 command: String.raw`^(dd|mkfs(\.\w+)?|truncate|wipefs|fdisk|parted|sfdisk)(\s|$)`,
101 reason: 'Overwrites or truncates data in place.',
102 },
103 {
104 id: 'shell-recursive-permissions',
105 tier: 'review',
106 tools: SHELL,
107 command: String.raw`^(chmod|chown|chgrp)\s(.*\s)?(-[a-zA-Z]*R[a-zA-Z]*|--recursive)(\s|$)`,
108 reason: 'Changes permissions or ownership recursively.',
109 },
110 {
111 id: 'shell-in-place-edit',
112 tier: 'review',
113 tools: SHELL,
114 command: String.raw`^(sed|perl|ruby)\s(.*\s)?(-[a-zA-Z]*i[a-zA-Z]*|--in-place)(\S*)(\s|$)`,
115 reason: 'Edits files in place.',
116 },
117 {
118 id: 'shell-redirect-write',
119 tier: 'review',
120 tools: SHELL,
121 check: 'redirect-write',
122 reason: 'Writes or overwrites a file through a shell redirect.',
123 },
124 {
125 id: 'shell-tee',
126 tier: 'review',
127 tools: SHELL,
128 command: String.raw`^tee(\s|$)`,
129 reason: 'Writes a file with tee.',
130 },
131 {
132 id: 'git-remote-or-history',
133 tier: 'review',
134 tools: SHELL,
135 command: String.raw`^git\s(push|merge|rebase|reset|tag|filter-branch|filter-repo|cherry-pick|revert|update-ref|replace)(\s|$)|^git\scommit\s(.*\s)?--amend(\s|$)`,
136 member: 'aragorn',
137 profile: 'git',
138 reason: 'Changes a remote or rewrites git history.',
139 },
140 {
141 id: 'git-config-write',
142 tier: 'review',
143 tools: SHELL,
144 check: 'git-config-write',
145 member: 'aragorn',
146 profile: 'git',
147 reason: 'Writes git configuration (.git/config), which can set hooks, a pager or an SSH command that runs code.',
148 },
149 {
150 id: 'git-config-injection',
151 tier: 'review',
152 tools: SHELL,
153 check: 'git-config-injection',
154 member: 'aragorn',
155 profile: 'git',
156 reason: 'Passes git a configuration key, exec-path or bisect command that can run arbitrary code.',
157 },
158 {
159 id: 'dangerous-env-assignment',
160 tier: 'review',
161 tools: SHELL,
162 check: 'dangerous-env-assignment',
163 reason: 'Sets an environment variable that changes what a later program loads or runs.',
164 },
165 {
166 id: 'git-discard',
167 tier: 'review',
168 tools: SHELL,
169 command: String.raw`^git\s(clean|restore|worktree\sremove)(\s|$)|^git\sstash\s(drop|clear)(\s|$)|^git\sbranch\s(.*\s)?-[a-zA-Z]*D[a-zA-Z]*(\s|$)|^git\sbranch\s(.*\s)?(--delete|-d)\s(.*\s)?(--force|-f)(\s|$)|^git\scheckout\s(.*\s)?(--|-f|--force|\.)(\s|$)|^git\sgc\s(.*\s)?--prune|^git\sreflog\s(expire|delete)(\s|$)`,
170 reason: 'Discards git work that may not be recoverable.',
171 },
172 {
173 id: 'database-client',
174 tier: 'review',
175 tools: SHELL,
176 command: String.raw`^(psql|pg_restore|dropdb|createdb|mysql|mariadb|mysqladmin|sqlite3|mongo|mongosh|mongorestore|redis-cli|cqlsh|sqlcmd|clickhouse(-client)?)(\s|$)`,
177 member: 'aragorn',
178 profile: 'database',
179 reason: 'Runs a database client.',
180 },
181 {
182 id: 'database-migration',
183 tier: 'review',
184 tools: SHELL,
185 command: String.raw`^((npx|bunx|pnpm(\sexec|\sdlx)?|yarn)\s)?(prisma\s(migrate|db\spush|db\sexecute)|knex\smigrate|sequelize(-cli)?\sdb:|typeorm\smigration|drizzle-kit\s(push|migrate|drop)|alembic\s(upgrade|downgrade|stamp)|flyway|liquibase|goose|dbmate|atlas\s(migrate|schema\sapply)|migrate\s)|^(python\d*(\.\d+)?\s)?(\S*/)?manage\.py\s(migrate|flush|sqlflush|reset_db)|^((bundle\sexec|bin/)\s?)?(rails|rake)\sdb:`,
186 member: 'aragorn',
187 profile: 'database',
188 reason: 'Runs a database migration.',
189 },
190 {
191 id: 'infrastructure',
192 tier: 'review',
193 tools: SHELL,
194 command: String.raw`^(terraform|tofu)\s(apply|destroy|import|taint|state\s(rm|mv|push))|^kubectl\s(delete|apply|replace|patch|scale|drain|cordon|rollout\sundo|set)|^helm\s(install|upgrade|uninstall|delete|rollback)|^docker\s((container|image|volume|network|system|builder)\s)?(rm|rmi|prune)|^docker[\s-]compose\s(.*\s)?down|^(aws|gcloud|az)\s.*\s(delete|remove|rm|destroy|terminate)`,
195 reason: 'Changes or deletes infrastructure.',
196 },
197 {
198 id: 'network-write',
199 tier: 'review',
200 tools: SHELL,
201 command: String.raw`^curl\s(.*\s)?(-X\s?(POST|PUT|PATCH|DELETE)|--request\s(POST|PUT|PATCH|DELETE)|-d|--data(-\w+)?|-F|--form|-T|--upload-file)(\s|$|=)|^wget\s(.*\s)?--(post|method|body)`,
202 reason: 'Sends data to a remote service.',
203 },
204 {
205 id: 'remote-copy',
206 tier: 'review',
207 tools: SHELL,
208 command: String.raw`^(scp|sftp)(\s|$)|^rsync\s(.*\s)?--(delete\S*|remove-source-files)(\s|$)`,
209 reason: 'Copies to another machine, or syncs with deletion.',
210 },
211 {
212 id: 'publish',
213 tier: 'review',
214 tools: SHELL,
215 command: String.raw`^(npm|pnpm|yarn)\s(.*\s)?publish(\s|$)|^cargo\spublish|^twine\supload|^gem\spush|^gh\s(release\s(create|delete|upload)|repo\s(delete|archive|edit)|pr\smerge|api\s.*-X\s?(POST|PUT|PATCH|DELETE))`,
216 reason: 'Publishes or changes something outside this machine.',
217 },
218 {
219 id: 'script-shell',
220 tier: 'review',
221 tools: SHELL,
222 command: String.raw`^(bash|sh|zsh|dash|ksh|fish|csh|tcsh)(\s|$)`,
223 reason: 'Runs a shell script, inline shell code or code piped into a shell.',
224 },
225 {
226 id: 'script-inline',
227 tier: 'review',
228 tools: SHELL,
229 command: String.raw`^(python\d*(\.\d+)?|node|nodejs|deno|bun|ruby|perl|php|lua|Rscript|osascript|pwsh|powershell)\s(.*\s)?(-c|-e|--eval|-p|--print|-r|-|-Command)(\s|$)`,
230 reason: 'Runs inline code.',
231 },
232 {
233 id: 'script-file',
234 tier: 'review',
235 tools: SHELL,
236 command: String.raw`^(python\d*(\.\d+)?|node|nodejs|deno(\srun)?|bun(\srun)?|ruby|perl|php|lua|Rscript|ts-node|tsx)\s(-\S+\s)*[^-\s]\S*\.(py|js|mjs|cjs|ts|mts|cts|rb|pl|php|lua|R)(\s|$)`,
237 reason: 'Runs a script file.',
238 },
239 {
240 id: 'script-path',
241 tier: 'review',
242 tools: SHELL,
243 command: String.raw`^[^\s/]*/\S*(\s|$)`,
244 reason: 'Runs a program or script by its path.',
245 },
246 {
247 id: 'script-eval',
248 tier: 'review',
249 tools: SHELL,
250 command: String.raw`^(eval|source|\.|xargs|parallel)(\s|$)|^psql\s(.*\s)?(-f|--file)(\s|=|$)`,
251 reason: 'Evaluates code built at run time or from a file (eval, source, xargs, parallel).',
252 },
253 {
254 id: 'remote-exec',
255 tier: 'review',
256 tools: SHELL,
257 command: String.raw`^(ssh|nc|ncat|netcat|telnet)(\s|$)|^rsync\s(.*\s)?(-e|--rsync-path)(\s|=)|^docker\s(.*\s)?(exec|run)(\s|$)|^docker[\s-]compose\s(.*\s)?(exec|run)(\s|$)|^(podman|nerdctl)\s(.*\s)?(exec|run)(\s|$)|^kubectl\s(.*\s)?exec(\s|$)|^(heroku|fly|flyctl)\s(.*\s)?(run|ssh)(\s|$)|^gcloud\s(.*\s)?ssh(\s|$)|^aws\s(.*\s)?(ssm\s(start-session|send-command))`,
258 reason: 'Runs a command on another machine or inside a container.',
259 },
260 {
261 id: 'sandbox-disabled',
262 tier: 'review',
263 tools: ['Bash'],
264 input: String.raw`"dangerouslyDisableSandbox":true`,
265 reason: 'Runs a command with the sandbox disabled.',
266 },
267 {
268 id: 'mcp-mutating',
269 tier: 'review',
270 tools: [String.raw`/^mcp__.+__.*(delete|remove|drop|merge|push|write|update|create|send|execute|exec|run|deploy|publish|destroy|purge|truncate|move|rename|upload|post|insert|modify|set)/i`],
271 reason: 'Calls an MCP tool whose name says it changes something.',
272 },
273]
274
275export const SHIPPED: Config = {
276 schemaVersion: 1,
277 rules: [...BLOCK, ...ASK, ...REVIEW],
278 disableRules: [],
279 protectedPaths: [
280 '**/.env',
281 '**/.env.*',
282 '**/.github/workflows/**',
283 '**/.gitlab-ci.yml',
284 '**/.circleci/**',
285 '**/.buildkite/**',
286 '**/Jenkinsfile',
287 '**/migrations/**',
288 '**/db/migrate/**',
289 '**/.git/**',
290 '**/.claude/council-of-elrond/**',
291 '**/.claude/settings.json',
292 '**/.claude/settings.local.json',
293 ],
294 protectedBranches: ['main', 'master', 'production', 'prod', 'release/*', 'trunk'],
295 productionPatterns: [
296 String.raw`(^|[^a-z0-9])prod(uction)?([^a-z0-9]|$)`,
297 String.raw`(^|[^a-z0-9])live([^a-z0-9]|$)`,
298 String.raw`(^|[^a-z0-9])primary([^a-z0-9]|$)`,
299 ],
300 models: {},
301 gollum: { patterns: [], allowlist: [] },
302 // A push, a merge into a protected branch, a migration: the full council.
303 bigOperations: [String.raw`/^git\s+push(\s|$)/`, 'merge-to-protected', 'database-migration'],
304 gimli: { commands: [] },
305}
306
307/**
308 * The built-in model per slot: the latest Sonnet as the floor, the latest
309 * Opus where the stakes are higher. Aliases resolve to the newest model of
310 * that family the running Claude Code knows.
311 */
312export const BUILT_IN_MODELS = {
313 gandalf: 'sonnet',
314 legolas: 'sonnet',
315 aragorn: 'opus',
316 council: 'opus',
317} as const
318
319/** The project overrides file, relative to the project root. */
320export const OVERRIDES_PATH = '.claude/council-of-elrond/rules.json'
321hooks/config/schema.ts 529 lines1import { globToRegExp, protectedMatcher, slashRegex, toolMatcher } from '../rules/globs.js'
2import type { ProtectedMatcher } from '../rules/globs.js'
3import { SHIPPED } from './defaults.js'
4import {
5 BIG_CHECKS,
6 CHECKS,
7 MEMBERS,
8 MODEL_SLOTS,
9 PROFILES,
10 SECRET_KINDS,
11 SECRET_LEVELS,
12 TIERS,
13} from './types.js'
14import type {
15 BigCheck,
16 CheckName,
17 Config,
18 GimliCommand,
19 GollumPattern,
20 MemberName,
21 ModelSlot,
22 Overrides,
23 Profile,
24 Rule,
25 RuleSource,
26 Tier,
27} from './types.js'
28
29export const SCHEMA_VERSION = 1
30
31export type CompiledRule = Rule & {
32 source: RuleSource
33 matchesTool: (tool: string) => boolean
34 commandRe?: RegExp
35 pathRe?: RegExp
36 inputRe?: RegExp
37}
38
39/** A big-operation entry, compiled: which rule, which command pattern, or which check. */
40export type BigOperation =
41 | { kind: 'rule'; entry: string; ruleId: string }
42 | { kind: 'command'; entry: string; re: RegExp }
43 | { kind: 'check'; entry: string; check: BigCheck }
44
45export type CompiledConfig = {
46 config: Config
47 /** Project rules first, in file order, then the enabled shipped rules. */
48 rules: readonly CompiledRule[]
49 protectedPaths: readonly ProtectedMatcher[]
50 protectedBranches: readonly RegExp[]
51 production: readonly RegExp[]
52 bigOperations: readonly BigOperation[]
53}
54
55export type LoadedConfig = {
56 compiled: CompiledConfig
57 /** Where the effective config came from. */
58 origin: 'shipped' | 'shipped+project'
59 /** Problems with the overrides file, by field; non-empty means it was ignored. */
60 errors: readonly string[]
61}
62
63const TOP_KEYS = [
64 'schemaVersion',
65 'rules',
66 'disableRules',
67 'protectedPaths',
68 'protectedBranches',
69 'productionPatterns',
70 'models',
71 'gollum',
72 'bigOperations',
73 'gimli',
74] as const
75
76const GIMLI_KEYS = ['commands'] as const
77const GIMLI_COMMAND_KEYS = ['name', 'argv', 'timeoutMs'] as const
78
79/** A check command's timeout: 120 s unless set, between 1 s and 10 minutes (the most a process may run). */
80export const GIMLI_TIMEOUT = { default: 120_000, min: 1_000, max: 600_000 } as const
81
82/** At most this many project checks, in one rules file or across the repositories a call touches. */
83export const MAX_GIMLI_COMMANDS = 8
84
85const GOLLUM_KEYS = ['patterns', 'allowlist'] as const
86const GOLLUM_PATTERN_KEYS = ['id', 'level', 'regex', 'label', 'kind'] as const
87
88/** A fingerprint as the dialog shows it; anything else in the allowlist is an exact string. */
89export const SECRET_FINGERPRINT = /^sha256:[0-9a-f]{16}$/
90
91const MAX_ALLOWLIST_ENTRY = 500
92
93const RULE_KEYS = [
94 'id',
95 'tier',
96 'tools',
97 'command',
98 'path',
99 'input',
100 'check',
101 'member',
102 'profile',
103 'reason',
104] as const
105
106export const MODEL_ID = /^[A-Za-z0-9][A-Za-z0-9._\-[\]@:/]{0,99}$/
107
108const isObject = (value: unknown): value is Record<string, unknown> =>
109 typeof value === 'object' && value !== null && !Array.isArray(value)
110
111const includes = <T extends string>(list: readonly T[], value: unknown): value is T =>
112 typeof value === 'string' && (list as readonly string[]).includes(value)
113
114function regexError(source: unknown, flags = ''): string | undefined {
115 if (typeof source !== 'string' || source === '') return 'must be a non-empty regex string'
116 try {
117 new RegExp(source, flags)
118 return undefined
119 } catch (error) {
120 return `invalid regex: ${error instanceof Error ? error.message : String(error)}`
121 }
122}
123
124function stringList(value: unknown, field: string, errors: string[]): string[] {
125 if (!Array.isArray(value)) {
126 errors.push(`${field}: must be a list of strings`)
127 return []
128 }
129 value.forEach((item, index) => {
130 if (typeof item !== 'string' || item === '') {
131 errors.push(`${field}[${index}]: must be a non-empty string`)
132 }
133 })
134 return value.filter((item): item is string => typeof item === 'string' && item !== '')
135}
136
137function validateRule(raw: unknown, field: string, errors: string[]): Rule | undefined {
138 if (!isObject(raw)) {
139 errors.push(`${field}: must be an object`)
140 return undefined
141 }
142 const before = errors.length
143 for (const key of Object.keys(raw)) {
144 if (!includes(RULE_KEYS, key)) errors.push(`${field}.${key}: unknown field`)
145 }
146 if (typeof raw.id !== 'string' || raw.id === '') errors.push(`${field}.id: required string`)
147 if (!includes(TIERS, raw.tier)) errors.push(`${field}.tier: one of ${TIERS.join(', ')}`)
148 const tools = stringList(raw.tools, `${field}.tools`, errors)
149 if (Array.isArray(raw.tools) && raw.tools.length === 0) {
150 errors.push(`${field}.tools: name at least one tool`)
151 }
152 tools.forEach((pattern, index) => {
153 try {
154 toolMatcher(pattern)
155 } catch (error) {
156 errors.push(`${field}.tools[${index}]: ${error instanceof Error ? error.message : String(error)}`)
157 }
158 })
159 for (const key of ['command', 'path', 'input'] as const) {
160 if (raw[key] !== undefined) {
161 const problem = regexError(raw[key])
162 if (problem !== undefined) errors.push(`${field}.${key}: ${problem}`)
163 }
164 }
165 if (raw.check !== undefined && !includes(CHECKS, raw.check)) {
166 errors.push(`${field}.check: one of ${CHECKS.join(', ')}`)
167 }
168 if (raw.member !== undefined && !includes(MEMBERS, raw.member)) {
169 errors.push(`${field}.member: one of ${MEMBERS.join(', ')}`)
170 }
171 if (raw.profile !== undefined) {
172 if (!includes(PROFILES, raw.profile)) {
173 errors.push(`${field}.profile: one of ${PROFILES.join(', ')}`)
174 } else if (raw.member !== 'aragorn') {
175 errors.push(`${field}.profile: only Aragorn (member "aragorn") has profiles`)
176 }
177 }
178 if (typeof raw.reason !== 'string' || raw.reason.trim() === '') {
179 errors.push(`${field}.reason: required string`)
180 }
181 if (errors.length > before) return undefined
182 return {
183 id: raw.id as string,
184 tier: raw.tier as Tier,
185 tools,
186 ...(raw.command !== undefined && { command: raw.command as string }),
187 ...(raw.path !== undefined && { path: raw.path as string }),
188 ...(raw.input !== undefined && { input: raw.input as string }),
189 ...(raw.check !== undefined && { check: raw.check as CheckName }),
190 ...(raw.member !== undefined && { member: raw.member as MemberName }),
191 ...(raw.profile !== undefined && { profile: raw.profile as Profile }),
192 reason: (raw.reason as string).trim(),
193 }
194}
195
196function validateGollum(raw: unknown, errors: string[]): Overrides['gollum'] {
197 if (!isObject(raw)) {
198 errors.push('gollum: must be an object')
199 return undefined
200 }
201 for (const key of Object.keys(raw)) {
202 if (!includes(GOLLUM_KEYS, key)) errors.push(`gollum.${key}: unknown field`)
203 }
204 const out: { patterns?: GollumPattern[]; allowlist?: string[] } = {}
205 if (raw.patterns !== undefined) {
206 if (!Array.isArray(raw.patterns)) {
207 errors.push('gollum.patterns: must be a list')
208 } else {
209 const seen = new Set<string>()
210 out.patterns = []
211 raw.patterns.forEach((item, index) => {
212 const field = `gollum.patterns[${index}]`
213 if (!isObject(item)) {
214 errors.push(`${field}: must be an object`)
215 return
216 }
217 const before = errors.length
218 for (const key of Object.keys(item)) {
219 if (!includes(GOLLUM_PATTERN_KEYS, key)) errors.push(`${field}.${key}: unknown field`)
220 }
221 if (typeof item.id !== 'string' || item.id === '') errors.push(`${field}.id: required string`)
222 else if (seen.has(item.id)) errors.push(`${field}.id: "${item.id}" is used twice`)
223 if (!includes(SECRET_LEVELS, item.level)) errors.push(`${field}.level: one of ${SECRET_LEVELS.join(', ')}`)
224 const problem = regexError(item.regex, 'g')
225 if (problem !== undefined) errors.push(`${field}.regex: ${problem}`)
226 else if (new RegExp(item.regex as string).test('')) errors.push(`${field}.regex: must not match empty text`)
227 if (typeof item.label !== 'string' || item.label.trim() === '') errors.push(`${field}.label: required string`)
228 if (item.kind !== undefined && !includes(SECRET_KINDS, item.kind)) errors.push(`${field}.kind: one of ${SECRET_KINDS.join(', ')}`)
229 if (errors.length > before) return
230 seen.add(item.id as string)
231 out.patterns?.push({
232 id: item.id as string,
233 level: item.level as GollumPattern['level'],
234 regex: item.regex as string,
235 label: (item.label as string).trim(),
236 ...(item.kind === undefined ? {} : { kind: item.kind as GollumPattern['kind'] }),
237 })
238 })
239 }
240 }
241 if (raw.allowlist !== undefined) {
242 const entries = stringList(raw.allowlist, 'gollum.allowlist', errors)
243 entries.forEach((entry, index) => {
244 if (entry.length > MAX_ALLOWLIST_ENTRY) errors.push(`gollum.allowlist[${index}]: longer than ${MAX_ALLOWLIST_ENTRY} characters`)
245 else if (!SECRET_FINGERPRINT.test(entry) && entry.length < 6) {
246 errors.push(`gollum.allowlist[${index}]: an exact secret of at least 6 characters, or a sha256: fingerprint`)
247 }
248 })
249 out.allowlist = entries
250 }
251 return out
252}
253
254function validateGimli(raw: unknown, errors: string[]): Overrides['gimli'] {
255 if (!isObject(raw)) {
256 errors.push('gimli: must be an object')
257 return undefined
258 }
259 for (const key of Object.keys(raw)) {
260 if (!includes(GIMLI_KEYS, key)) errors.push(`gimli.${key}: unknown field`)
261 }
262 if (raw.commands === undefined) return {}
263 if (!Array.isArray(raw.commands)) {
264 errors.push('gimli.commands: must be a list')
265 return undefined
266 }
267 if (raw.commands.length > MAX_GIMLI_COMMANDS) errors.push(`gimli.commands: at most ${MAX_GIMLI_COMMANDS} commands`)
268 const seen = new Set<string>()
269 const commands: GimliCommand[] = []
270 raw.commands.forEach((item, index) => {
271 const field = `gimli.commands[${index}]`
272 if (!isObject(item)) {
273 errors.push(`${field}: must be an object`)
274 return
275 }
276 const before = errors.length
277 for (const key of Object.keys(item)) {
278 if (!includes(GIMLI_COMMAND_KEYS, key)) errors.push(`${field}.${key}: unknown field`)
279 }
280 if (typeof item.name !== 'string' || item.name.trim() === '') errors.push(`${field}.name: required string`)
281 else if (seen.has(item.name.trim())) errors.push(`${field}.name: "${item.name.trim()}" is used twice`)
282 if (!Array.isArray(item.argv) || item.argv.length === 0) {
283 errors.push(`${field}.argv: a non-empty list of strings (the command and its arguments; no shell)`)
284 } else {
285 item.argv.forEach((word, i) => {
286 if (typeof word !== 'string' || (i === 0 && word.trim() === '')) errors.push(`${field}.argv[${i}]: must be a${i === 0 ? ' non-empty' : ''} string`)
287 })
288 }
289 const timeout = item.timeoutMs
290 if (timeout !== undefined && (typeof timeout !== 'number' || !Number.isInteger(timeout) || timeout < GIMLI_TIMEOUT.min || timeout > GIMLI_TIMEOUT.max)) {
291 errors.push(`${field}.timeoutMs: a whole number of milliseconds from ${GIMLI_TIMEOUT.min} to ${GIMLI_TIMEOUT.max}`)
292 }
293 if (errors.length > before) return
294 const name = (item.name as string).trim()
295 seen.add(name)
296 commands.push({ name, argv: [...(item.argv as string[])], timeoutMs: (timeout as number | undefined) ?? GIMLI_TIMEOUT.default })
297 })
298 return { commands }
299}
300
301/**
302 * A big-operation entry: `/regex/flags`, a named check, or a rule id the
303 * merged config holds (shipped, or the file's own).
304 */
305function validateBigOperations(raw: unknown, ruleIds: ReadonlySet<string>, errors: string[]): string[] {
306 const entries = stringList(raw, 'bigOperations', errors)
307 entries.forEach((entry, index) => {
308 const field = `bigOperations[${index}]`
309 if (entry.startsWith('/')) {
310 try {
311 if (slashRegex(entry) === undefined) errors.push(`${field}: a regex is written /source/flags`)
312 } catch (error) {
313 errors.push(`${field}: invalid regex: ${error instanceof Error ? error.message : String(error)}`)
314 }
315 } else if (!includes(BIG_CHECKS, entry) && !ruleIds.has(entry)) {
316 errors.push(`${field}: "${entry}" is not a rule id, a /regex/ or one of ${BIG_CHECKS.join(', ')}`)
317 }
318 })
319 return entries
320}
321
322/**
323 * Validates the parsed overrides file against this build's schema, reporting
324 * every problem by field. Any problem means the whole file is ignored.
325 */
326export function validateOverrides(
327 raw: unknown,
328 shipped: Config = SHIPPED,
329): { overrides: Overrides; errors: [] } | { overrides: undefined; errors: string[] } {
330 const errors: string[] = []
331 if (!isObject(raw)) {
332 return { overrides: undefined, errors: ['(file): must be a JSON object'] }
333 }
334 if (raw.schemaVersion !== SCHEMA_VERSION) {
335 return {
336 overrides: undefined,
337 errors: [
338 `schemaVersion: ${JSON.stringify(raw.schemaVersion)} is not a version this build reads (${SCHEMA_VERSION})`,
339 ],
340 }
341 }
342 for (const key of Object.keys(raw)) {
343 if (!includes(TOP_KEYS, key)) errors.push(`${key}: unknown field`)
344 }
345
346 const shippedIds = new Map(shipped.rules.map(rule => [rule.id, rule]))
347 const overrides: Overrides = { schemaVersion: 1 }
348
349 if (raw.rules !== undefined) {
350 if (!Array.isArray(raw.rules)) {
351 errors.push('rules: must be a list')
352 } else {
353 const seen = new Set<string>()
354 const rules: Rule[] = []
355 raw.rules.forEach((item, index) => {
356 const rule = validateRule(item, `rules[${index}]`, errors)
357 if (rule === undefined) return
358 if (seen.has(rule.id)) errors.push(`rules[${index}].id: "${rule.id}" is used twice`)
359 if (includes(BIG_CHECKS, rule.id)) errors.push(`rules[${index}].id: "${rule.id}" is the name of a big-operation check`)
360 if (shippedIds.has(rule.id)) {
361 errors.push(
362 `rules[${index}].id: "${rule.id}" is a shipped rule's id; disable it with disableRules and give yours another id`,
363 )
364 }
365 seen.add(rule.id)
366 rules.push(rule)
367 })
368 overrides.rules = rules
369 }
370 }
371
372 if (raw.disableRules !== undefined) {
373 const ids = stringList(raw.disableRules, 'disableRules', errors)
374 ids.forEach((id, index) => {
375 const rule = shippedIds.get(id)
376 if (rule === undefined) {
377 errors.push(`disableRules[${index}]: "${id}" is not a shipped rule`)
378 } else if (rule.tier === 'block') {
379 errors.push(`disableRules[${index}]: "${id}" is a block rule; block rules cannot be disabled`)
380 }
381 })
382 overrides.disableRules = ids
383 }
384
385 if (raw.protectedPaths !== undefined) {
386 overrides.protectedPaths = stringList(raw.protectedPaths, 'protectedPaths', errors)
387 }
388 if (raw.protectedBranches !== undefined) {
389 overrides.protectedBranches = stringList(raw.protectedBranches, 'protectedBranches', errors)
390 }
391 if (raw.productionPatterns !== undefined) {
392 const patterns = stringList(raw.productionPatterns, 'productionPatterns', errors)
393 patterns.forEach((pattern, index) => {
394 const problem = regexError(pattern, 'i')
395 if (problem !== undefined) errors.push(`productionPatterns[${index}]: ${problem}`)
396 })
397 overrides.productionPatterns = patterns
398 }
399
400 if (raw.models !== undefined) {
401 if (!isObject(raw.models)) {
402 errors.push('models: must be an object')
403 } else {
404 const models: Partial<Record<ModelSlot, string>> = {}
405 for (const [slot, model] of Object.entries(raw.models)) {
406 if (!includes(MODEL_SLOTS, slot)) {
407 errors.push(`models.${slot}: unknown slot (one of ${MODEL_SLOTS.join(', ')})`)
408 } else if (typeof model !== 'string' || !MODEL_ID.test(model)) {
409 errors.push(`models.${slot}: must be a model alias or id`)
410 } else {
411 models[slot] = model
412 }
413 }
414 overrides.models = models
415 }
416 }
417
418 if (raw.gollum !== undefined) {
419 const gollum = validateGollum(raw.gollum, errors)
420 if (gollum !== undefined) overrides.gollum = gollum
421 }
422
423 if (raw.bigOperations !== undefined) {
424 const ruleIds = new Set([...shippedIds.keys(), ...(overrides.rules ?? []).map(rule => rule.id)])
425 overrides.bigOperations = validateBigOperations(raw.bigOperations, ruleIds, errors)
426 }
427
428 if (raw.gimli !== undefined) {
429 const gimli = validateGimli(raw.gimli, errors)
430 if (gimli !== undefined) overrides.gimli = gimli
431 }
432
433 return errors.length > 0
434 ? { overrides: undefined, errors }
435 : { overrides, errors: [] }
436}
437
438const union = (a: readonly string[], b: readonly string[] = []): string[] => [
439 ...new Set([...a, ...b]),
440]
441
442/**
443 * Overrides win: project rules are tried before shipped ones, and project
444 * models stand. Lists only add to the shipped ones, so a project can widen
445 * the protection but never narrow it; block rules cannot be disabled.
446 */
447export function mergeConfig(shipped: Config, overrides: Overrides): Config {
448 const disabled = new Set(overrides.disableRules ?? [])
449 return {
450 schemaVersion: 1,
451 rules: [
452 ...(overrides.rules ?? []),
453 ...shipped.rules.filter(rule => rule.tier === 'block' || !disabled.has(rule.id)),
454 ],
455 disableRules: [...disabled],
456 protectedPaths: union(shipped.protectedPaths, overrides.protectedPaths),
457 protectedBranches: union(shipped.protectedBranches, overrides.protectedBranches),
458 productionPatterns: union(shipped.productionPatterns, overrides.productionPatterns),
459 models: { ...shipped.models, ...overrides.models },
460 gollum: {
461 patterns: [...shipped.gollum.patterns, ...(overrides.gollum?.patterns ?? [])],
462 allowlist: union(shipped.gollum.allowlist, overrides.gollum?.allowlist),
463 },
464 bigOperations: union(shipped.bigOperations, overrides.bigOperations),
465 gimli: { commands: [...shipped.gimli.commands, ...(overrides.gimli?.commands ?? [])] },
466 }
467}
468
469function compileBigOperation(entry: string): BigOperation {
470 const re = slashRegex(entry)
471 if (re !== undefined) return { kind: 'command', entry, re }
472 return includes(BIG_CHECKS, entry) ? { kind: 'check', entry, check: entry } : { kind: 'rule', entry, ruleId: entry }
473}
474
475const branchToRegExp = (branch: string): RegExp => globToRegExp(branch)
476
477export function compileConfig(config: Config, projectRuleIds: ReadonlySet<string>): CompiledConfig {
478 const rules = config.rules.map((rule): CompiledRule => {
479 const matchers = rule.tools.map(toolMatcher)
480 return {
481 ...rule,
482 source: projectRuleIds.has(rule.id) ? 'project' : 'shipped',
483 matchesTool: tool => matchers.some(matches => matches(tool)),
484 ...(rule.command !== undefined && { commandRe: new RegExp(rule.command) }),
485 ...(rule.path !== undefined && { pathRe: new RegExp(rule.path) }),
486 ...(rule.input !== undefined && { inputRe: new RegExp(rule.input) }),
487 }
488 })
489 return {
490 config,
491 rules,
492 protectedPaths: config.protectedPaths.map(protectedMatcher),
493 protectedBranches: config.protectedBranches.map(branchToRegExp),
494 production: config.productionPatterns.map(pattern => new RegExp(pattern, 'i')),
495 bigOperations: config.bigOperations.map(compileBigOperation),
496 }
497}
498
499/**
500 * The effective config from the overrides file's text (undefined: no file).
501 * A file that does not parse or validate is ignored whole, and the shipped
502 * defaults stand, with the errors reported. It never turns the gate off.
503 */
504export function loadConfig(fileText: string | undefined, shipped: Config = SHIPPED): LoadedConfig {
505 const shippedOnly = (errors: readonly string[]): LoadedConfig => ({
506 compiled: compileConfig(shipped, new Set()),
507 origin: 'shipped',
508 errors,
509 })
510 if (fileText === undefined) return shippedOnly([])
511
512 let raw: unknown
513 try {
514 raw = JSON.parse(fileText)
515 } catch (error) {
516 return shippedOnly([`(file): not valid JSON: ${error instanceof Error ? error.message : String(error)}`])
517 }
518 const result = validateOverrides(raw, shipped)
519 if (result.overrides === undefined) return shippedOnly(result.errors)
520
521 const merged = mergeConfig(shipped, result.overrides)
522 const projectIds = new Set((result.overrides.rules ?? []).map(rule => rule.id))
523 try {
524 return { compiled: compileConfig(merged, projectIds), origin: 'shipped+project', errors: [] }
525 } catch (error) {
526 return shippedOnly([`(file): ${error instanceof Error ? error.message : String(error)}`])
527 }
528}
529hooks/config/types.ts 137 lines1/**
2 * The council's configuration: the shipped defaults (defaults.ts) merged with
3 * the project overrides file (.claude/council-of-elrond/rules.json).
4 */
5
6/** Tiers, least strict first: the strictest across a call's parts wins. */
7export const TIERS = ['allow', 'review', 'ask', 'block'] as const
8export type Tier = (typeof TIERS)[number]
9
10export const MEMBERS = ['gandalf', 'legolas', 'aragorn'] as const
11export type MemberName = (typeof MEMBERS)[number]
12
13export const PROFILES = ['git', 'database'] as const
14export type Profile = (typeof PROFILES)[number]
15
16/** Model slots: one per model member, plus the full council's. */
17export const MODEL_SLOTS = ['gandalf', 'legolas', 'aragorn', 'council'] as const
18export type ModelSlot = (typeof MODEL_SLOTS)[number]
19
20/**
21 * Checks written in code, for what a pattern cannot say safely: they read the
22 * parsed words of a shell part rather than its text.
23 */
24export const CHECKS = [
25 'rm-outside-repo',
26 'force-push-protected',
27 'destructive-sql-production',
28 'privileged',
29 'redirect-write',
30 'git-config-write',
31 'git-config-injection',
32 'dangerous-env-assignment',
33 'raw-disk-write',
34] as const
35export type CheckName = (typeof CHECKS)[number]
36
37export type Rule = {
38 /** Unique id, shown in /council rules and the audit log. */
39 id: string
40 tier: Tier
41 /**
42 * The tools the rule covers: an exact name (`Bash`), a glob (`mcp__*`), or a
43 * regex written `/source/flags`.
44 */
45 tools: readonly string[]
46 /** Regex matched against each part of a shell command (Bash, Monitor). */
47 command?: string
48 /** Regex matched against the call's file path, relative to the project root. */
49 path?: string
50 /** Regex matched against the call's input as JSON. */
51 input?: string
52 /** A check in code (CHECKS) that must also hold. */
53 check?: CheckName
54 /** Who reviews a `review` match; Gandalf when absent. */
55 member?: MemberName
56 profile?: Profile
57 /** Plain-English reason, given to Claude and to you. Never the pattern. */
58 reason: string
59}
60
61export type Config = {
62 schemaVersion: 1
63 rules: readonly Rule[]
64 /** Ids of shipped non-block rules to switch off. */
65 disableRules: readonly string[]
66 /** Globs, relative to the project root: always the ask tier. */
67 protectedPaths: readonly string[]
68 /** Branch names or globs: force pushes to them are blocked. */
69 protectedBranches: readonly string[]
70 /** Regexes (case-insensitive) that make a target look like production. */
71 productionPatterns: readonly string[]
72 /** Per-slot model: an alias (`sonnet`, `opus`, `fable`) or a full id. */
73 models: Readonly<Partial<Record<ModelSlot, string>>>
74 /** The secrets scan's extra patterns and its allowlist. */
75 gollum: GollumConfig
76 /**
77 * What goes to the full council instead of one member: a rule id, a command
78 * regex written `/source/flags` (matched against each shell part), or a
79 * named check (BIG_CHECKS).
80 */
81 bigOperations: readonly string[]
82 /** The project's own checks the full council runs (tests, lint, typecheck). */
83 gimli: GimliConfig
84}
85
86/** Big-operation entries decided in code: a merge whose target is a protected branch. */
87export const BIG_CHECKS = ['merge-to-protected'] as const
88export type BigCheck = (typeof BIG_CHECKS)[number]
89
90export type GimliCommand = {
91 /** Shown to the user and to Claude (`tests`, `lint`). */
92 name: string
93 /** The command by its argument vector: no shell. */
94 argv: readonly string[]
95 /** How long it may run, in milliseconds (default 120 s, at most 600 s). */
96 timeoutMs: number
97}
98
99export type GimliConfig = {
100 commands: readonly GimliCommand[]
101}
102
103export const SECRET_LEVELS = ['high', 'low'] as const
104
105export const SECRET_KINDS = ['password', 'token'] as const
106
107export type GollumPattern = {
108 id: string
109 level: (typeof SECRET_LEVELS)[number]
110 /** Regex source, matched globally against what the call would write or run. */
111 regex: string
112 /** What the finding is called in the dialog and refusal (`deploy key`). */
113 label: string
114 /** `password` adds the allowlist warning that a short value's fingerprint is guessable. Absent means `token`. */
115 kind?: (typeof SECRET_KINDS)[number]
116}
117
118export type GollumConfig = {
119 patterns: readonly GollumPattern[]
120 /** Exact secret strings, or `sha256:` fingerprints the dialog shows. Never regexes. */
121 allowlist: readonly string[]
122}
123
124/** What the project overrides file may hold: every field optional. */
125export type Overrides = Partial<Omit<Config, 'schemaVersion' | 'gollum' | 'gimli'>> & {
126 schemaVersion: 1
127 gollum?: Partial<GollumConfig>
128 gimli?: Partial<GimliConfig>
129}
130
131export type RuleSource = 'shipped' | 'project'
132
133export const strictness = (tier: Tier): number => TIERS.indexOf(tier)
134
135export const stricter = (a: Tier, b: Tier): Tier =>
136 strictness(a) >= strictness(b) ? a : b
137hooks/config/write.ts 59 lines1import { validateOverrides } from './schema.js'
2import type { Rule } from './types.js'
3
4/**
5 * Edits to the project overrides file the mod makes itself, only after the
6 * user confirmed the exact entry. Pure: the file's text in, the new text out.
7 * A file that does not read as a valid overrides file is never rewritten, and
8 * an edit whose result does not validate is not made.
9 */
10
11export type FileEdit = { ok: true; text: string } | { ok: false; problem: string }
12
13type Raw = Record<string, unknown>
14
15const isObject = (value: unknown): value is Raw => typeof value === 'object' && value !== null && !Array.isArray(value)
16
17/**
18 * Reads the file (none, or blank: a new one), applies `change` to the parsed
19 * object, validates the result and writes it back pretty-printed. Spreading
20 * the parsed object keeps the user's key order; new keys go last.
21 */
22export function editOverrides(fileText: string | undefined, change: (raw: Raw) => Raw): FileEdit {
23 let raw: Raw
24 if (fileText === undefined || fileText.trim() === '') {
25 raw = { schemaVersion: 1 }
26 } else {
27 let parsed: unknown
28 try {
29 parsed = JSON.parse(fileText)
30 } catch {
31 return { ok: false, problem: 'the rules file is not valid JSON' }
32 }
33 if (!isObject(parsed)) return { ok: false, problem: 'the rules file is not a JSON object' }
34 raw = parsed
35 }
36 const before = validateOverrides(raw)
37 if (before.overrides === undefined) return { ok: false, problem: `the rules file has errors (${before.errors.join('; ')})` }
38 const next = change(raw)
39 const after = validateOverrides(next)
40 if (after.overrides === undefined) return { ok: false, problem: `the entry does not validate (${after.errors.join('; ')})` }
41 return { ok: true, text: `${JSON.stringify(next, null, 2)}\n` }
42}
43
44/** Adds one entry to `gollum.allowlist`, keeping the rest of the file and its key order. */
45export const withAllowlistEntry = (fileText: string | undefined, entry: string): FileEdit =>
46 editOverrides(fileText, raw => {
47 const gollum = isObject(raw.gollum) ? raw.gollum : {}
48 const allowlist = Array.isArray(gollum.allowlist) ? (gollum.allowlist as unknown[]) : []
49 return { ...raw, gollum: { ...gollum, allowlist: allowlist.includes(entry) ? allowlist : [...allowlist, entry] } }
50 })
51
52/**
53 * Adds one rule after the file's own rules: rules the user wrote decide
54 * first. An id already taken (the file changed since the rule was offered)
55 * fails validation, and nothing is written.
56 */
57export const withRule = (fileText: string | undefined, rule: Rule): FileEdit =>
58 editOverrides(fileText, raw => ({ ...raw, rules: [...(Array.isArray(raw.rules) ? (raw.rules as unknown[]) : []), rule] }))
59hooks/elrond/commands.ts 316 lines1import type { CouncilSession } from '../../types'
2import type { CompiledConfig } from '../config/schema.js'
3import { MEMBERS, MODEL_SLOTS, TIERS } from '../config/types.js'
4import type { MemberName, ModelSlot } from '../config/types.js'
5import { whoOf } from '../members/brief.js'
6import type { Classification } from '../rules/classify.js'
7import type { Big, CouncilSeat } from './council.js'
8import { councilSeatId } from './council.js'
9import { median } from '../state.js'
10import { text } from '../strings.js'
11import type { StringKey } from '../strings.js'
12import type { ModelChoice } from './models.js'
13import type { Operation } from './operations.js'
14import { attemptsOf } from './operations.js'
15import type { Route, Seat } from './routing.js'
16
17/**
18 * `/council`: one command, its subcommands parsed from the raw argument
19 * string, and its output built as lines. The output is for the user: register.ts
20 * draws it in a pane or logs it. Where nothing draws, four subcommands also reach
21 * Claude, redacted (relay.ts, ROADMAP C2).
22 */
23
24export type CouncilCommand =
25 | { kind: 'status' }
26 | { kind: 'bypass'; on: boolean }
27 | { kind: 'shadow'; on: boolean }
28 | { kind: 'log'; count: number }
29 | { kind: 'rules' }
30 | { kind: 'test'; command: string }
31 | { kind: 'models' }
32 | { kind: 'model'; slot: string; model: string; save: boolean }
33 | { kind: 'reload' }
34 | { kind: 'report' }
35 | { kind: 'debate' }
36 | { kind: 'usage'; key: StringKey; params?: Record<string, string> }
37
38export type Output = { title: string; lines: string[] }
39
40const DEFAULT_LOG = 10
41const MAX_LOG = 50
42
43/** Splits on spaces, keeping single- or double-quoted runs whole. */
44export function words(args: string): string[] {
45 const out: string[] = []
46 const re = /"((?:[^"\\]|\\.)*)"|'([^']*)'|(\S+)/g
47 for (const match of args.matchAll(re)) out.push(match[1] !== undefined ? match[1].replace(/\\(.)/g, '$1') : (match[2] ?? match[3] ?? ''))
48 return out
49}
50
51export function parseCouncil(args: string): CouncilCommand {
52 const trimmed = args.trim()
53 const [sub = '', ...rest] = words(trimmed)
54 switch (sub.toLowerCase()) {
55 case '':
56 case 'status':
57 return { kind: 'status' }
58 case 'on':
59 return { kind: 'bypass', on: false }
60 case 'off':
61 return { kind: 'bypass', on: true }
62 case 'shadow': {
63 const value = (rest[0] ?? '').toLowerCase()
64 return value === 'on' || value === 'off' ? { kind: 'shadow', on: value === 'on' } : { kind: 'usage', key: 'cmd.shadowUsage' }
65 }
66 case 'log': {
67 const n = Number(rest[0] ?? DEFAULT_LOG)
68 return { kind: 'log', count: Number.isInteger(n) && n > 0 ? Math.min(n, MAX_LOG) : DEFAULT_LOG }
69 }
70 case 'rules':
71 return { kind: 'rules' }
72 case 'test': {
73 // Everything after `test`, one layer of quotes removed: the command as typed.
74 const raw = trimmed.slice(trimmed.indexOf(sub) + sub.length).trim()
75 const command = /^(["'])([\s\S]*)\1$/.exec(raw)?.[2] ?? raw
76 return command === '' ? { kind: 'usage', key: 'cmd.testUsage' } : { kind: 'test', command }
77 }
78 case 'model':
79 case 'models': {
80 if (rest.length === 0) return { kind: 'models' }
81 const save = rest.includes('--save')
82 const [slot, model] = rest.filter(word => word !== '--save')
83 if (slot === undefined || model === undefined) return { kind: 'usage', key: 'cmd.modelUsage', params: { slots: MODEL_SLOTS.join(', ') } }
84 return { kind: 'model', slot: slot.toLowerCase(), model, save }
85 }
86 case 'reload':
87 return { kind: 'reload' }
88 case 'report':
89 return { kind: 'report' }
90 case 'debate':
91 return { kind: 'debate' }
92 default:
93 return { kind: 'usage', key: 'cmd.unknown', params: { sub } }
94 }
95}
96
97/**
98 * Whether a subcommand loosens the gate (bypass on, shadow on, a model switch),
99 * so only a person typing it may run it. `models` (the listing), `on`,
100 * `shadow off` and the rest change nothing that lets more through.
101 */
102export const needsPerson = (command: CouncilCommand): boolean =>
103 (command.kind === 'bypass' && command.on) || (command.kind === 'shadow' && command.on) || command.kind === 'model'
104
105/**
106 * Whether a prompt submission runs the `/council` command (`name`): it never asks
107 * the model, so unlike a skill or prompt command it does not start a new task.
108 */
109export const isCouncilCommand = (command: { name: string } | undefined, name: string): boolean => command?.name === name
110
111export const isSlot = (value: string): value is ModelSlot => (MODEL_SLOTS as readonly string[]).includes(value)
112
113export const WHO_OF_SLOT: Readonly<Record<ModelSlot, StringKey>> = {
114 gandalf: 'who.gandalf',
115 legolas: 'who.legolas',
116 aragorn: 'who.aragorn',
117 council: 'who.council',
118}
119
120export type StatusInput = {
121 session: CouncilSession
122 mode: 'enforcing' | 'shadow' | 'bypass'
123 members: Readonly<Record<MemberName, { enabled: boolean; choice: ModelChoice }>>
124 council: { enabled: boolean; choice: ModelChoice; sequential: boolean }
125 gimli: { enabled: boolean; commands: number }
126 gollumEnabled: boolean
127 galadrielEnabled: boolean
128 tokenBudget: number
129}
130
131const ZERO_COUNTS = { approved: 0, revised: 0, blocked: 0, failed: 0 }
132
133export function statusOutput(input: StatusInput): Output {
134 const { session } = input
135 const attempts = attemptsOf(session)
136 const typical = median(session.reviewMs)
137 const onOff = (on: boolean): string => text(on ? 'cmd.on' : 'cmd.off')
138 return {
139 title: text('cmd.title'),
140 lines: [
141 text('cmd.mode', { mode: text(`cmd.mode.${input.mode}`) }),
142 text('cmd.members'),
143 ...MEMBERS.map(member =>
144 text('cmd.member', {
145 who: text(whoOf(member)),
146 id: member,
147 state: onOff(input.members[member].enabled),
148 model: input.members[member].choice.model,
149 source: input.members[member].choice.source,
150 ...(session.counts[member] ?? ZERO_COUNTS),
151 }),
152 ),
153 text('cmd.council', {
154 who: text('who.fullCouncil'),
155 state: onOff(input.council.enabled),
156 model: input.council.choice.model,
157 source: input.council.choice.source,
158 order: text(input.council.sequential ? 'cmd.council.sequential' : 'cmd.council.parallel'),
159 ...(session.counts.council ?? ZERO_COUNTS),
160 }),
161 text('cmd.gimli', {
162 who: text('who.gimli'),
163 state: onOff(input.gimli.enabled),
164 count: input.gimli.commands,
165 ...(session.counts.gimli ?? ZERO_COUNTS),
166 }),
167 text('cmd.memberCode', { who: text('who.gollum'), state: onOff(input.gollumEnabled) }),
168 text('cmd.memberCode', { who: text('who.galadriel'), state: onOff(input.galadrielEnabled) }),
169 text('cmd.attempts', attempts),
170 text('cmd.tokens', { spent: session.tokensSpent, budget: input.tokenBudget }),
171 typical === undefined
172 ? text('cmd.noReviews')
173 : text('cmd.median', { time: `${(typical / 1000).toFixed(1)} s`, reviews: session.reviewMs.length }),
174 ],
175 }
176}
177
178/** The last `count` audit lines, newest last. Unparseable lines are skipped. */
179export function logOutput(logText: string, count: number): Output {
180 const records = logText
181 .split('\n')
182 .filter(line => line.trim() !== '')
183 .flatMap(line => {
184 try {
185 return [JSON.parse(line) as Record<string, unknown>]
186 } catch {
187 return []
188 }
189 })
190 .slice(-count)
191 if (records.length === 0) return { title: text('cmd.title'), lines: [text('cmd.logEmpty')] }
192 const str = (value: unknown, fallback = '-'): string => (typeof value === 'string' && value !== '' ? value : fallback)
193 return {
194 title: text('cmd.logTitle', { n: records.length }),
195 lines: records.map(record =>
196 text('cmd.logLine', {
197 ts: str(record.ts).replace('T', ' ').slice(0, 19),
198 tool: str(record.tool),
199 tier: str(record.tier),
200 who: str(record.member, record.tier === 'block' ? 'rules' : '-'),
201 verdict: str(record.verdict, '-') + (record.shadow === true ? ' (shadow)' : '') + (record.cached === true ? ' (cached)' : ''),
202 decision: typeof record.decision === 'string' ? `, you: ${record.decision}` : '',
203 outcome: str(record.outcome),
204 reason: str(record.reason, ''),
205 }),
206 ),
207 }
208}
209
210/**
211 * `forModel`: the copy relayed through Claude (relay.ts). An exact-string allowlist
212 * entry shows no character at all, where the person's own copy shows its first three.
213 */
214export function rulesOutput(compiled: CompiledConfig, origin: string, errors: readonly string[], forModel = false): Output {
215 const rules = [...compiled.rules].sort((a, b) => TIERS.indexOf(b.tier) - TIERS.indexOf(a.tier))
216 const list = (key: StringKey, items: readonly string[]): string[] =>
217 items.length === 0 ? [] : [text('cmd.listLine', { name: text(key), items: items.join(', ') })]
218 return {
219 title: text('cmd.rulesTitle', { origin }),
220 lines: [
221 ...(errors.length > 0 ? [text('cmd.configErrors', { errors: errors.join('; ') })] : []),
222 ...rules.map(rule => text('cmd.ruleLine', { tier: rule.tier.padEnd(6), id: rule.id, source: rule.source, reason: rule.reason })),
223 ...list('cmd.list.protectedPaths', compiled.config.protectedPaths),
224 ...list('cmd.list.protectedBranches', compiled.config.protectedBranches),
225 ...list('cmd.list.production', compiled.config.productionPatterns),
226 ...list('cmd.list.secretPatterns', compiled.config.gollum.patterns.map(pattern => `${pattern.id} (${pattern.level})`)),
227 ...list(
228 'cmd.list.allowlist',
229 compiled.config.gollum.allowlist.map(entry => (entry.startsWith('sha256:') ? entry : forModel ? text('cmd.allowlistHidden') : `${entry.slice(0, 3)}…`)),
230 ),
231 ],
232 }
233}
234
235/** A seat as typed in config: `aragorn/git`, `gandalf`. */
236const seatId = (seat: Seat): string => (seat.profile !== undefined ? `${seat.member}/${seat.profile}` : seat.member)
237
238/** Who would review, for `/council test`: the route, and the model of the member it seats. */
239export type Reviewer = { route: Route; choice?: ModelChoice }
240
241/** A big operation, for `/council test`: who would sit, on which model, and the checks that would run. */
242export type CouncilPreview = {
243 big: Big
244 enabled: boolean
245 seats: readonly CouncilSeat[]
246 choice: ModelChoice
247 checks: readonly string[]
248 /** A merge counted as big without the current branch being checked. */
249 isBranchAssumed: boolean
250}
251
252const seatLine = (seat: CouncilSeat): string =>
253 seat.member === 'legolas' && seat.range !== undefined
254 ? text('cmd.seatRange', { who: text(whoOf(seat.member)), id: seat.member, kind: seat.range })
255 : text('cmd.seat', { who: text(whoOf(seat.member, seat.member === 'aragorn' ? seat.profile : undefined)), id: councilSeatId(seat) })
256
257function councilLines(council: CouncilPreview): string[] {
258 const who = text('who.fullCouncil')
259 if (council.seats.length === 0) return [text('cmd.testCouncilNobody', { entry: council.big.entry, who })]
260 return [
261 text('cmd.testCouncil', { who, entry: council.big.entry, model: council.choice.model, source: council.choice.source, seats: council.seats.map(seatLine).join('; ') }),
262 council.checks.length > 0
263 ? text('cmd.testCouncilChecks', { who: text('who.gimli'), names: council.checks.map(name => `"${name}"`).join(', ') })
264 : text('cmd.testCouncilNoChecks'),
265 ...(council.isBranchAssumed ? [text('cmd.testCouncilBranch', { who })] : []),
266 ]
267}
268
269export function testOutput(
270 command: string,
271 classification: Classification,
272 operation: Operation | undefined,
273 reviewer: Reviewer | undefined,
274 council?: CouncilPreview,
275): Output {
276 const decided = classification.decided
277 const lines = [text('cmd.testTier', { tier: classification.tier })]
278 if (decided === undefined) {
279 lines.push(text('cmd.testAllow'))
280 } else {
281 for (const finding of classification.findings) {
282 lines.push(text('cmd.testFinding', { subject: finding.subject, tier: finding.tier, rule: finding.ruleId, source: finding.source, reason: finding.reason }))
283 }
284 if (council?.enabled === true) {
285 lines.push(...councilLines(council))
286 } else if (classification.tier === 'review' && reviewer !== undefined) {
287 const { route } = reviewer
288 const wanted = route.wanted !== undefined ? `${text(whoOf(route.wanted.member, route.wanted.profile))} [${seatId(route.wanted)}]` : ''
289 if (route.kind === 'none') {
290 lines.push(text('cmd.testNoReviewer', { wanted }))
291 } else {
292 lines.push(
293 text('cmd.testReviewer', {
294 who: text(whoOf(route.member, route.profile)),
295 id: route.member,
296 profile: route.profile !== undefined ? `/${route.profile}` : '',
297 model: reviewer.choice?.model ?? '-',
298 source: reviewer.choice?.source ?? '-',
299 }),
300 )
301 if (route.fallback !== undefined) lines.push(text('cmd.testFallback', { wanted, why: text(`route.${route.fallback}`) }))
302 }
303 if (council !== undefined) lines.push(text('cmd.testCouncilOff', { entry: council.big.entry, who: text('who.fullCouncil') }))
304 }
305 if (operation !== undefined) lines.push(text('cmd.testOperation', { key: operation.key }))
306 }
307 return { title: text('cmd.testTitle', { command: command.length > 60 ? `${command.slice(0, 59)}…` : command }), lines }
308}
309
310export function modelsOutput(choices: Readonly<Record<ModelSlot, ModelChoice>>): Output {
311 return {
312 title: text('cmd.modelTitle'),
313 lines: MODEL_SLOTS.map(slot => text('cmd.modelLine', { id: slot, model: choices[slot].model, source: choices[slot].source })),
314 }
315}
316hooks/elrond/chat.ts 75 lines1import { fingerprintOf } from '../audit.js'
2import { SHELL_TOOLS } from '../rules/classify.js'
3import type { Call, Classification } from '../rules/classify.js'
4
5/**
6 * The chat approval route (ROADMAP C4, DESIGN §14.4): where nothing draws, a
7 * person approves or refuses a refused call by typing a line in their next
8 * message. Everything here is pure; register.ts reads the origin and wires it,
9 * and state.ts holds the offers, allowances and denials.
10 */
11
12export type ChatCommand = { kind: 'allow' | 'deny'; code: string; scope: 'once' | 'session' } | { kind: 'malformed' }
13
14/** More chat lines than this in one message are removed and answered as malformed, not acted on. */
15export const MAX_CHAT_LINES = 10
16
17/** The characters of a call's key that the person types. */
18export const CODE_LENGTH = 6
19
20const CHAT_LINE = /^council\s+(?:allow|deny)\b/i
21
22const VALID_LINE = /^council\s+(allow|deny)\s+(?:council:)?([0-9a-f]{6})(?:\s+(session))?$/i
23
24function commandOf(line: string): ChatCommand {
25 const match = VALID_LINE.exec(line)
26 const kind = match?.[1]?.toLowerCase()
27 const code = match?.[2]
28 if (match === null || code === undefined || (kind !== 'allow' && kind !== 'deny')) return { kind: 'malformed' }
29 const isSession = match[3] !== undefined
30 // A refusal is never "for the session".
31 if (kind === 'deny' && isSession) return { kind: 'malformed' }
32 return { kind, code: code.toLowerCase(), scope: isSession ? 'session' : 'once' }
33}
34
35/**
36 * The chat lines of a person's message, in order, and the message without them.
37 * A chat line is a whole line that begins `council allow` or `council deny`;
38 * only the three exact forms are valid, anything else on such a line is malformed.
39 */
40export function parseChatLines(message: string): { commands: ChatCommand[]; rest: string } {
41 const commands: ChatCommand[] = []
42 const kept: string[] = []
43 for (const line of message.split('\n')) {
44 if (!CHAT_LINE.test(line.trim())) {
45 kept.push(line)
46 continue
47 }
48 commands.push(commands.length < MAX_CHAT_LINES ? commandOf(line.trim()) : { kind: 'malformed' })
49 }
50 return { commands, rest: kept.join('\n').replace(/[\r\n]+$/, '') }
51}
52
53/**
54 * The key of a call: its fingerprint without a shell tool's `description`,
55 * which only labels the call, so a retry with new wording keeps its key. Every
56 * other field stays (`dangerouslyDisableSandbox`, `timeout`, `run_in_background`).
57 * A `scope` tag (C5) keeps a repository's allowance out of another one.
58 */
59export function callKeyOf(call: Call, scope = ''): Promise<string> {
60 if (!SHELL_TOOLS.has(call.tool)) return fingerprintOf(call.tool, call.input, scope)
61 const { description: _label, ...input } = call.input
62 return fingerprintOf(call.tool, input, scope)
63}
64
65/** What the person types: the first characters of the key. */
66export const codeOf = (callKey: string): string => callKey.slice(0, CODE_LENGTH)
67
68/**
69 * Whether a refused call may be approved in chat: never a protected path or a
70 * block rule, the same opening as `suggestRule`. (A high-confidence secret is
71 * refused before any of this.)
72 */
73export const isOfferable = (classification: Classification): boolean =>
74 !classification.isProtected && classification.tier !== 'block' && !classification.findings.some(finding => finding.tier === 'block')
75hooks/elrond/combine.ts 132 lines1import type { MemberName, Profile } from '../config/types.js'
2import { isGimliBlock } from '../members/gimli.js'
3import type { GimliRun } from '../members/gimli.js'
4import { VERDICTS } from '../members/shared.js'
5import type { Verdict, VerdictValue } from '../members/shared.js'
6import { text } from '../strings.js'
7import type { StringKey } from '../strings.js'
8import type { MemberOpinion } from './escalation.js'
9
10/**
11 * Combining the full council: the strictest verdict wins (block, then revise,
12 * then approve). A member that errored, timed out or answered malformed
13 * counts as a block from that member; a check that failed, timed out or
14 * could not start is a block too. Each reason is labelled with who gave it.
15 * Members never see each other's verdicts: this runs after all of them.
16 * Claude reads the reason and alternative, so every string here is asked for
17 * in plain mode, whatever the session's mode.
18 */
19
20/** One model member's part in the council. */
21export type Voice =
22 | { kind: 'verdict'; who: StringKey; member: MemberName; profile?: Profile; verdict: Verdict }
23 /** No verdict: an error, a timeout, a malformed reply. Counts as a block. */
24 | { kind: 'failed'; who: StringKey; member: MemberName; profile?: Profile; problem: string }
25 /** Never asked: the sequential council stopped at an earlier block, or there was nothing to review. */
26 | { kind: 'skipped'; who: StringKey; member: MemberName; profile?: Profile; why: string }
27
28export type Combined = {
29 verdict: VerdictValue
30 /** Every voice that didn't approve, labelled, one per line: the reason Claude and the user read. */
31 reason: string
32 /** The same without any check's output: what the audit log keeps. */
33 summary: string
34 /** The safer alternatives of those voices, labelled. */
35 alternative: string
36 /** Blocked only because members gave no verdict: no member blocked or asked to revise, and every check passed. */
37 isFailureOnly: boolean
38 /** How many model members gave a verdict or failed; zero means nobody reviewed. */
39 reviewed: number
40 /** Each voice and check, for the question put to the user. */
41 opinions: MemberOpinion[]
42}
43
44const rank = (verdict: VerdictValue): number => VERDICTS.indexOf(verdict)
45
46const valueOf = (voice: Voice): VerdictValue | undefined =>
47 voice.kind === 'verdict' ? voice.verdict.verdict : voice.kind === 'failed' ? 'block' : undefined
48
49/** What a check run says, in a line. */
50export function runLine(run: GimliRun): string {
51 switch (run.status) {
52 case 'passed':
53 return text('gimli.passed', { name: run.name }, 'plain')
54 case 'failed':
55 return run.code === null || run.code === undefined
56 ? text('gimli.killed', { name: run.name, signal: run.signal ?? 'a signal' }, 'plain')
57 : text('gimli.failed', { name: run.name, code: run.code }, 'plain')
58 case 'timed-out':
59 return text('gimli.timedOut', { name: run.name, seconds: Math.round(run.ms / 1000) }, 'plain')
60 case 'error':
61 return text('gimli.error', { name: run.name }, 'plain')
62 case 'stopped':
63 return text('gimli.stopped', { name: run.name }, 'plain')
64 }
65}
66
67/** The detailed line, for Claude only: the engine's error (a check that could not start) and the last lines. */
68const withTail = (run: GimliRun): string =>
69 [
70 runLine(run),
71 ...(run.problem !== undefined && run.problem !== '' ? [text('gimli.problem', { problem: run.problem }, 'plain')] : []),
72 ...(run.tail === '' ? [] : [text('gimli.tail', { tail: run.tail }, 'plain')]),
73 ].join(' ')
74
75export function combine(voices: readonly Voice[], runs: readonly GimliRun[]): Combined {
76 let verdict: VerdictValue = 'approve'
77 const reasons: string[] = []
78 const summaries: string[] = []
79 const alternatives: string[] = []
80 let isRealBlock = false
81 for (const voice of voices) {
82 const value = valueOf(voice)
83 if (value === undefined || value === 'approve') continue
84 if (rank(value) > rank(verdict)) verdict = value
85 const who = text(voice.who, {}, 'plain')
86 if (voice.kind === 'verdict') {
87 isRealBlock = true
88 reasons.push(text('council.voice', { who, verdict: value, reason: voice.verdict.reason }, 'plain'))
89 summaries.push(reasons.at(-1) as string)
90 alternatives.push(text('council.voice', { who, verdict: value, reason: voice.verdict.safer_alternative }, 'plain'))
91 } else if (voice.kind === 'failed') {
92 reasons.push(text('council.noVerdict', { who, problem: voice.problem }, 'plain'))
93 summaries.push(reasons.at(-1) as string)
94 }
95 }
96 const failedRuns = runs.filter(isGimliBlock)
97 if (failedRuns.length > 0) {
98 verdict = 'block'
99 isRealBlock = true
100 for (const run of failedRuns) {
101 reasons.push(text('council.voice', { who: text('who.gimli', {}, 'plain'), verdict: 'block', reason: withTail(run) }, 'plain'))
102 summaries.push(text('council.voice', { who: text('who.gimli', {}, 'plain'), verdict: 'block', reason: runLine(run) }, 'plain'))
103 }
104 alternatives.push(text('alternative.gimli', { names: failedRuns.map(run => `"${run.name}"`).join(', ') }, 'plain'))
105 }
106 if (verdict !== 'approve' && alternatives.length === 0) alternatives.push(text('alternative.ask', {}, 'plain'))
107
108 const opinions: MemberOpinion[] = [
109 ...voices.flatMap((voice): MemberOpinion[] =>
110 voice.kind === 'verdict'
111 ? [{ who: voice.who, verdict: voice.verdict.verdict, reason: voice.verdict.reason }]
112 : voice.kind === 'failed'
113 ? [{ who: voice.who, problem: voice.problem }]
114 : [],
115 ),
116 ...runs.map((run): MemberOpinion => ({ who: 'who.gimli', verdict: isGimliBlock(run) ? 'block' : 'approve', reason: runLine(run) })),
117 ]
118 return {
119 verdict,
120 reason: reasons.map(line => `\n- ${line}`).join(''),
121 summary: summaries.join(' '),
122 alternative: alternatives.length === 1 ? (alternatives[0] as string) : alternatives.map(line => `\n- ${line}`).join(''),
123 isFailureOnly: verdict === 'block' && !isRealBlock,
124 reviewed: voices.filter(voice => voice.kind !== 'skipped').length,
125 opinions,
126 }
127}
128
129/** Whether the council has already blocked for real, so a check still running can no longer matter. */
130export const hasRealBlock = (voices: readonly Voice[]): boolean =>
131 voices.some(voice => voice.kind === 'verdict' && voice.verdict.verdict === 'block')
132hooks/elrond/council.ts 115 lines1import type { BigOperation, CompiledConfig } from '../config/schema.js'
2import type { Profile } from '../config/types.js'
3import { FILE_PATH_FIELDS } from '../rules/classify.js'
4import type { Call, Classification, Finding } from '../rules/classify.js'
5import type { ShellPart } from '../rules/shell.js'
6import type { Enabled } from './routing.js'
7import { seatOf } from './routing.js'
8
9/**
10 * The full council: which review-tier calls are big operations, and who sits
11 * for one. Pure: the current branch, the one fact a rule cannot see, comes in
12 * from register.ts.
13 */
14
15/** Why a call is a big operation: the config entry that matched, and the part it matched. */
16export type Big = { entry: string; subject: string }
17
18/** What decides a big operation besides the call: the current branch, when a merge needs it. */
19export type BigContext = {
20 /** The checked-out branch; undefined when unknown (a merge into it then counts as big). */
21 currentBranch?: string
22}
23
24const isGit = (part: ShellPart, sub: string): boolean => part.coreWords[0] === 'git' && part.coreWords[1] === sub
25
26/** A merge lands on the checked-out branch; a pull request merge on a base the command doesn't name. */
27const isMerge = (part: ShellPart): boolean =>
28 (isGit(part, 'merge') && !part.coreWords.slice(2).some(word => ['--abort', '--quit', '--continue'].includes(word))) ||
29 (part.coreWords[0] === 'gh' && part.coreWords[1] === 'pr' && part.coreWords[2] === 'merge')
30
31/** Whether working out a big operation needs the current branch: only a `git merge` does. */
32export const needsCurrentBranch = (classification: Classification, compiled: CompiledConfig): boolean =>
33 compiled.bigOperations.some(big => big.kind === 'check') &&
34 classification.findings.some(finding => finding.part !== undefined && isGit(finding.part, 'merge'))
35
36function matches(big: BigOperation, finding: Finding, compiled: CompiledConfig, context: BigContext): boolean {
37 if (big.kind === 'rule') return finding.ruleId === big.ruleId
38 const part = finding.part
39 if (part === undefined) return false
40 if (big.kind === 'command') return big.re.test(part.core)
41 // merge-to-protected: an unknown current branch counts, since the merge may land on a protected one.
42 if (!isMerge(part)) return false
43 if (part.coreWords[0] === 'gh') return true
44 const branch = context.currentBranch
45 return branch === undefined || branch === 'HEAD' || compiled.protectedBranches.some(re => re.test(branch))
46}
47
48/**
49 * The big operation a review-tier call is, if any: the first configured entry
50 * one of its review parts matches. Other tiers never reach the council.
51 */
52export function bigOperationOf(classification: Classification, compiled: CompiledConfig, context: BigContext = {}): Big | undefined {
53 if (classification.tier !== 'review') return undefined
54 for (const finding of classification.findings) {
55 if (finding.tier !== 'review') continue
56 const big = compiled.bigOperations.find(entry => matches(entry, finding, compiled, context))
57 if (big !== undefined) return { entry: big.entry, subject: finding.subject }
58 }
59 return undefined
60}
61
62/**
63 * One seat at the full council. The diff reviewer reviews a file tool's own
64 * diff, or the changes a push or merge would send or bring in (`range`).
65 */
66export type CouncilSeat =
67 | { member: 'gandalf' }
68 | { member: 'legolas'; range?: 'push' | 'merge' }
69 | { member: 'aragorn'; profile: Profile }
70
71/** The push or merge a diff reviewer could read the changes of, if the call has one. */
72export function rangeOf(classification: Classification): { kind: 'push' | 'merge'; part: ShellPart } | undefined {
73 for (const finding of classification.findings) {
74 const part = finding.part
75 if (part === undefined || finding.tier !== 'review') continue
76 if (isGit(part, 'push')) return { kind: 'push', part }
77 if (isGit(part, 'merge') && isMerge(part)) return { kind: 'merge', part }
78 }
79 return undefined
80}
81
82/**
83 * Who sits for a big operation: every enabled model member with something of
84 * this call to review. The general reviewer always; the git and database
85 * reviewer once per profile the call's parts ask for; the diff reviewer for a
86 * file change, or for a push or merge (the changes it would send or bring in,
87 * read by a fixed `git diff`, so only while the read-only preview is on).
88 * Each gets its own brief; none sees another's verdict.
89 */
90export function councilSeats(call: Call, classification: Classification, enabled: Enabled, options: { ranges: boolean }): CouncilSeat[] {
91 const seats: CouncilSeat[] = []
92 if (enabled.gandalf) seats.push({ member: 'gandalf' })
93 if (enabled.legolas) {
94 if (FILE_PATH_FIELDS[call.tool] !== undefined) seats.push({ member: 'legolas' })
95 else if (options.ranges) {
96 const range = rangeOf(classification)
97 if (range !== undefined) seats.push({ member: 'legolas', range: range.kind })
98 }
99 }
100 if (enabled.aragorn) {
101 const profiles = new Set<Profile>()
102 for (const finding of classification.findings) {
103 if (finding.tier !== 'review') continue
104 const seat = seatOf(finding)
105 if (seat.member === 'aragorn' && seat.profile !== undefined) profiles.add(seat.profile)
106 }
107 for (const profile of ['git', 'database'] as const) if (profiles.has(profile)) seats.push({ member: 'aragorn', profile })
108 }
109 return seats
110}
111
112/** A seat as typed in config and shown by `/council test`: `aragorn/git`, `gandalf`. */
113export const councilSeatId = (seat: CouncilSeat): string =>
114 seat.member === 'aragorn' ? `${seat.member}/${seat.profile}` : seat.member
115hooks/elrond/escalation.ts 82 lines1import { truncate } from '../members/shared.js'
2import { redact } from '../redact.js'
3import { text } from '../strings.js'
4import type { Mode, StringKey } from '../strings.js'
5
6/**
7 * The escalation: the question put to the user, and what their answer means.
8 * The dialog is the engine's AskUserQuestion: the mod's labelled options plus a
9 * free-text "Other", which reaches Claude as an instruction. The engine's own
10 * "Chat about this" reads as a dismissal (DESIGN §12.4).
11 */
12
13export type MemberOpinion =
14 | { who: StringKey; verdict: string; reason: string }
15 | { who: StringKey; problem: string }
16
17export type Question = {
18 call: string
19 ruleReason: string
20 why: StringKey
21 opinions: readonly MemberOpinion[]
22 /** The read-only preview, when there is one. */
23 preview?: string
24 /** Possible secrets the scan found, already redacted. */
25 secrets?: readonly { label: string; snippet: string }[]
26 /** The dialog offers the allowlist (one finding exactly). */
27 canAllowlist?: boolean
28}
29
30export type Answer =
31 | { kind: 'allow-once' }
32 | { kind: 'keep-blocked' }
33 | { kind: 'allowlist' }
34 | { kind: 'talk-first' }
35 | { kind: 'instruction'; text: string }
36
37export type Unanswered = 'dismissed' | 'unavailable'
38
39const MAX_QUESTION_CHARS = 2_500
40
41const PREVIEW_LINES = 15
42
43/** The dialog's labels; a secrets question adds the allowlist. */
44export const optionsOf = (mode: Mode = 'plain', withAllowlist = false): string[] => [
45 text('ask.allowOnce', {}, mode),
46 ...(withAllowlist ? [text('ask.allowlist', {}, mode)] : []),
47 text('ask.keepBlocked', {}, mode),
48 text('ask.talkFirst', {}, mode),
49]
50
51export function questionText(question: Question, mode: Mode = 'plain'): string {
52 const lines = [
53 text('ask.title', {}, mode),
54 text(question.why, {}, mode),
55 text('ask.call', { call: truncate(redact(question.call), 12, 600) }, mode),
56 ...(question.ruleReason !== '' ? [text('ask.rule', { reason: question.ruleReason }, mode)] : []),
57 ...(question.secrets ?? []).map(secret =>
58 text('ask.secret', { label: secret.label, snippet: redact(secret.snippet) }, mode),
59 ),
60 ...question.opinions.map(opinion =>
61 'problem' in opinion
62 ? text('ask.failed', { who: text(opinion.who, {}, mode), problem: opinion.problem }, mode)
63 : text('ask.verdict', { who: text(opinion.who, {}, mode), verdict: opinion.verdict, reason: redact(opinion.reason) }, mode),
64 ),
65 ...(question.preview !== undefined
66 ? [text('ask.preview', { preview: truncate(redact(question.preview), PREVIEW_LINES, 900) }, mode)]
67 : []),
68 text(question.canAllowlist === true ? 'ask.closeSecret' : 'ask.close', {}, mode),
69 ]
70 const joined = lines.join('\n')
71 return joined.length > MAX_QUESTION_CHARS ? `${joined.slice(0, MAX_QUESTION_CHARS - 1)}…` : joined
72}
73
74/** Labels compare exactly; anything else the user typed is an instruction. */
75export function interpretAnswer(answer: string, mode: Mode = 'plain', withAllowlist = false): Answer {
76 if (answer === text('ask.allowOnce', {}, mode)) return { kind: 'allow-once' }
77 if (answer === text('ask.keepBlocked', {}, mode)) return { kind: 'keep-blocked' }
78 if (answer === text('ask.talkFirst', {}, mode)) return { kind: 'talk-first' }
79 if (withAllowlist && answer === text('ask.allowlist', {}, mode)) return { kind: 'allowlist' }
80 return { kind: 'instruction', text: answer.trim() }
81}
82hooks/elrond/models.ts 53 lines1import { BUILT_IN_MODELS } from '../config/defaults.js'
2import type { ModelSlot } from '../config/types.js'
3
4/**
5 * Which model a slot runs on, from the first layer that sets one: a session
6 * switch, the user's /config row, the project rules file, the built-in.
7 */
8
9export type ModelSource = 'session' | 'settings' | 'project' | 'built-in'
10
11export type ModelChoice = { model: string; source: ModelSource }
12
13export type ModelLayers = {
14 session?: string
15 /** The /config row's value; `default` means unset. */
16 settings?: string
17 project?: string
18}
19
20const isSet = (value: string | undefined): value is string =>
21 value !== undefined && value.trim() !== '' && value !== 'default'
22
23export function resolveModel(slot: ModelSlot, layers: ModelLayers): ModelChoice {
24 if (isSet(layers.session)) return { model: layers.session, source: 'session' }
25 if (isSet(layers.settings)) return { model: layers.settings, source: 'settings' }
26 if (isSet(layers.project)) return { model: layers.project, source: 'project' }
27 return { model: BUILT_IN_MODELS[slot], source: 'built-in' }
28}
29
30/**
31 * The request settings that follow from a model, so choosing a model is the
32 * only decision. Thinking models spend output tokens thinking, so their cap
33 * leaves room; an unknown id is treated as a thinking model.
34 */
35export type ModelProfile = {
36 maxTokens: number
37 effort?: 'low'
38 deadlineMs: number
39}
40
41export function profileOf(model: string): ModelProfile {
42 const name = model.toLowerCase()
43 if (name.includes('haiku')) return { maxTokens: 400, deadlineMs: 20_000 }
44 if (name.includes('sonnet')) return { maxTokens: 2_000, effort: 'low', deadlineMs: 30_000 }
45 if (name.includes('fable') || name.includes('mythos')) return { maxTokens: 4_000, effort: 'low', deadlineMs: 90_000 }
46 if (name.includes('opus')) return { maxTokens: 2_000, effort: 'low', deadlineMs: 45_000 }
47 return { maxTokens: 2_000, effort: 'low', deadlineMs: 45_000 }
48}
49
50/** The deadline for one review: the user's override in seconds (0: from the model). */
51export const deadlineFor = (model: string, overrideSeconds: number): number =>
52 overrideSeconds > 0 ? overrideSeconds * 1000 : profileOf(model).deadlineMs
53