CAROL — Cognitive Amplifier Role Orchestration with LLM agents. Opinionated ritualistic framework that enforces discipline when working with multiple agents.

████████ ████ ██████████ ████████ ████
████░░░░░░ ████████ ████░░░░████ ████░░░░████ ████
████░░ ████░░░░████ ████ ████ ████ ████ ████
████ ████ ████ ██████████░░ ████ ████ ████
████ ████████████ ████░░████ ████ ████ ████
░░████ ████░░░░████ ████ ░░████ ████ ████ ████
░░████████ ████ ████ ████ ████ ░░████████░░ ████████████
░░░░░░░░ ░░░░ ░░░░ ░░░░ ░░░░ ░░░░░░░░ ░░░░░░░░░░░░
Cognitive Amplifier Role Orchestration for LLM agents
This document contains the "why" behind CAROL's protocol principles. The enforcement contract is in CAROL.md. Read this to understand intent; enforce from CAROL.md.
This document follows ASD-STE100 — see CAROL.md Writing Standard.
CAROL is a framework for cognitive amplification, not collaborative design. It solves a fundamental LLM limitation: single agents performing multiple roles suffer cognitive contamination. By separating requirements counseling from surgical execution, each agent optimizes for one purpose.
User = ARCHITECT — supreme decision maker, architect of systems, holder of invisible rationale. Agents = Amplifiers — execute vision at scale, transform specifications into code, amplify cognitive bandwidth.
A single agent asked to research, plan, and implement simultaneously contaminates each phase with the others. Research becomes biased toward implementation convenience. Planning becomes biased toward the first idea. Implementation becomes sloppy because the agent already "knows" the answer.
Separation enforces cognitive hygiene: each agent enters its phase clean, without the contamination of previous phases. ORACLE researches without implementation pressure. COUNSELOR plans without code bias. Engineer implements without design second-guessing.
Never mix. Never switch mid-task. Mixing collapses the boundary that makes each role useful.
ARCHITECT's decisions carry invisible rationale that does not exist in training data:
When something seems wrong to an agent, it is almost always correct to the system. The agent sees a pattern; ARCHITECT sees the full context. The correct response is always: ASK, never infer, never substitute.
Training data is dominated by:
What "usually" works in training data may be exactly wrong here. ARCHITECT's domain expertise, SPEC.md, PLAN.md, and the compiler are the only valid sources. Everything else is a training prior — a statistical guess dressed as knowledge.
Small pattern-preserving deviations from ARCHITECT's direction seem harmless individually. Over time they create an architecture that half-follows the DCF and half-follows training defaults. This drift is harder to fix than the original problem. Each deviation makes the next one more likely. The zero-tolerance rule exists because there is no safe deviation size.
ARCHITECT's role:
Agent's role:
NOT agent's role:
The last four are protocol violations, not just bad behavior. They degrade the architecture by substituting training priors for ARCHITECT's domain knowledge.
Constructive challenge is a one-shot fact-check, not a second opinion. Its purpose is to surface factual contradictions before they cause expensive mistakes — not to litigate direction. Once ARCHITECT has heard the challenge and responded, the information has been received. Re-raising is noise, not signal. It wastes ARCHITECT's time and reveals the agent is optimizing for its own confidence rather than ARCHITECT's decision.
"You are not a second opinion. You are a one-shot fact-checker protecting the objective."
Reframing is the most common way agents try to get around a failure. "Let me try a different approach" sounds like problem-solving but is often the agent repeating itself with different words. The session counter prevents this by treating any second failure as a signal that the agent's model of the problem is wrong — not just its approach. At that point, only ARCHITECT can reframe correctly.
Training bias says "be helpful, keep trying." CAROL says stop and discuss. CAROL wins because training bias is the failure mode.
/stop halts execution. /ode halts the problem frame. When every answer moves further from resolution, the issue is not the answer — it is the question being asked. ODE forces articulation of what is actually observed (O), where it breaks from expectation (D), and what expectation was held (E). This surfaces the actual gap instead of iterating on the wrong problem.
The O/D/E format is borrowed from the ODE protocol because it is the correct articulation structure for any reproducible mismatch. Stating E last is intentional — recency carries the highest weight, and E is what the agent needs most.
Claude 5-family models validate instructions as specifications: contradictory or redundant rule pairs measurably degrade output, and defensive rules written against older models now cost quality instead of adding it (Opus 5 system card). CAROL 0.0.23 therefore states each rule once, positively — what to do, not an enumeration of everything not to do. Terseness governs chat; losslessness governs deliverable documents. Two scopes, one rule each — not a contradiction.
Each role's model is pinned in its agent frontmatter model: line, the only source. The seat follows documented behavior for the job: delegation-heavy, long-retention primaries (COUNSELOR, ORACLE); literal executors fed exact specs (Engineer, MACHINIST); bounded deep-analysis invocations with coverage-not-filtering steering (Auditor); protocol-carrying discovery and research (Pathfinder, Librarian). The COUNSELOR seat has a budget ladder — carol counselor [opus55|opus5]. Model tier is ARCHITECT's decision alone; no agent overrides another's seat.
Per-step audit invocations multiply token cost and stall the Step Gate. Under 0.0.23, COUNSELOR validates each step against the CONTRACT itself — that is what the Step Gate is — and @Auditor sweeps the whole sprint once, after all steps complete, with coverage over filtering. One deep audit of the finished surface catches what per-step spot checks fragment.
Doxygen XML is not documentation — it is a navigation map. Loading the index first tells you what exists, where it lives, and how it connects. Reading a compound XML before Grep means you read the exact file with the exact API, not a regex match against source that might be stale or partial. Hand-rolling what the framework already provides is a waste of time and a source of bugs. Doxygen-first eliminates both.
Previously, technical debt was tracked in a "Technical Debt / Follow-up" subsection of SPRINT-LOG.md. This made it invisible between sessions — buried inside a log entry, not actionable. DEBT.md extracts debt into a first-class ledger: visible, captured with O/D/E structure, formally drained on payment. The format is identical to the ODE protocol because both are articulations of reproducible mismatches. They share format only, not lifecycle.
Output Discipline enforces terseness for conversational responses. Deliverable documents (RFC.md, PLAN.md, handoff artifacts) are different: they are the medium through which one agent communicates to another. If COUNSELOR compresses an RFC point because it seemed minor, ENGINEER never sees it. Information omitted from a handoff artifact is permanently lost in the workflow. Terseness in a deliverable is information loss, not efficiency.
@CAROL.md ORACLE: Rock 'n Roll
@CAROL.md COUNSELOR: Rock 'n Roll
@CAROL.md MACHINIST: Rock 'n Roll
carol oracle
carol machinist
@oracle analyze this architecture decision
@engineer scaffold this module per spec
@auditor verify this implementation
@librarian research JUCE PopupMenu API
@Pathfinder discover patterns in ~/Documents/Poems/dev/end/
Subagents invoke via Agent tool. Return BRIEF format to primary.
RFC.md — ORACLE produces it. One RFC per pre-flight session. COUNSELOR reads it and writes PLAN.md. RFC is never edited by COUNSELOR — it is a carrier document, not a living document.
SPEC.md — Written once per project. Updated only when project scope changes. If it exists, do not rewrite it. It defines what to build.
PLAN.md — Written per sprint. Ephemeral — abandoned plans are normal. May be held in COUNSELOR's context without being written to disk. Defines how to build what SPEC defines.
ARCHITECTURE.md — Written when system structure needs to be externalized. Not required for every project.
carol/SPRINT-LOG.md — Written only on "log sprint." Latest first. Keep last 5 entries. Not a project deliverable — protocol context only.
DEBT.md — Created lazily. Survives carol reset. Drained per sprint via carol debt clear. Never survives payment.
Rationale document for CAROL v0.0.28. Enforcement contract: ~/.carol/CAROL.md
hooks/register.js 164 lines1import { atom, read, update } from 'claude-code'
2
3const NUDGE_INTERVAL = 5
4const DEFAULT_ROLE = 'COUNSELOR'
5const MACHINIST_ROLE = 'MACHINIST'
6const READ_ONLY_GIT_AGENT = 'pathfinder'
7const ROLE_FILE = '/.carol-role'
8const AGENTS_DIRECTORY = '/agents/'
9const SPRINT_LOG = 'carol/SPRINT-LOG.md'
10
11const NO_GATE_PATTERN = /no[ -]?gate/i
12const GIT_INSTRUCTION_PATTERN = /\b(git|commit|push)\b/i
13
14const COMMAND_START = '(?:^|(?<=[;&|\\n(`]|\\$\\(|-exec(?:dir)?))\\s*'
15const COMMAND_PREFIX = '(?:(?:\\w+=\\S*|sudo|exec|time|nohup|command|env|xargs(?:\\s+-\\S+)*)\\s+)*'
16const COMMAND_HEAD = COMMAND_START + COMMAND_PREFIX + '(?:\\S*/)?'
17const GIT_OPTIONS = '(?:\\s+(?:-C\\s+\\S+|-c\\s+\\S+|--[a-z-]+(?:=\\S+)?))*\\s+'
18const GIT_SUFFIX = '(?:[\\s;&|)]|$)'
19const GIT_COMMAND_PATTERN = new RegExp(COMMAND_HEAD + 'git(?:\\s|$)', 'g')
20const GIT_READ_ONLY_PATTERN = new RegExp(COMMAND_HEAD + 'git' + GIT_OPTIONS + '(?:status|log|diff|show)' + GIT_SUFFIX, 'g')
21const GIT_SYNC_PATTERN = new RegExp(COMMAND_HEAD + 'git' + GIT_OPTIONS + '(?:push|pull)' + GIT_SUFFIX, 'g')
22const IN_PLACE_PATTERN = new RegExp(COMMAND_HEAD + '(?:(?:sed|perl)\\s+(?:[^|;&]*\\s)?(?:-[A-Za-z]*i[A-Za-z.]*|--in-place)(?:[\\s=]|$)|awk\\s+-i\\s+inplace)')
23
24const GIT_GATE = "This git command needs ARCHITECT's instruction, and ARCHITECT's last prompt names no git command (CAROL.md Git). Read-only git is allowed in the main session and in Pathfinder, never in another subagent, and the MACHINIST main session also runs push and pull. Do not retry. Read the working tree with the Read tool, or report what you need."
25const IN_PLACE_GATE = "An in-place edit with sed, perl or awk is not allowed (CAROL.md Destructive-Edit Discipline). Run: carol apply --expect N 'sed-expression' file... It backs up each file, prints the preview, checks that the changed-line count equals N, applies, verifies, and restores on a mismatch."
26const BACKGROUND_GATE = 'A subagent runs no background command (CAROL.md Subagent Return Format: the report is the final output). Run this command in the foreground, wait for it to finish, and put its result in your report.'
27const STEP_GATE = 'No gate until /log: this run ends at the sprint log. A text-only end of turn is a report, not the endpoint. Per CAROL.md Step Gate, a stop before the log is evidence that CONTRACT was not read at that point. Read ~/.carol/MANIFESTO.md, ~/.carol/CODING.md and ~/.carol/NAMES.md again with the Read tool, then read the implicated code at file:line. Correct course with the CONTRACT clause that covers it, and do the next step. Stop only for the closed stop set in CAROL.md Step Gate. If a subagent is still running, end the turn and wait for it.'
28const READ_DIRECTIVE = "If your reasoning still leaves an open end to fill in, read again thoroughly with the Read tool. Find the answer as a citable fact from the codebase, checked against ~/.carol/MANIFESTO.md, ~/.carol/CODING.md and ~/.carol/NAMES.md, and from the agreed rulings in the RFC and the PLAN. Above all, use ARCHITECT's explicit discussion recorded in the chat history. Never fill in a gap. Never leave an open end that reading can answer. Respond only with a citable fact."
29const OPEN_END_PATTERN = /\b(?:not read yet|(?:still )?needs? to (?:be )?verif(?:y|ied)|not yet verified|(?:have|has|had)(?: not|n't) (?:read|seen|checked|verified)|unread|do not know)\b/i
30const USER_ORIGIN_KINDS = ['composer', 'bridge']
31const NUDGE_MACHINIST ='CAROL NUDGE — MACHINIST executes directly with its own hands; @Pathfinder grounds unfamiliar surface; cross-platform consistency holds for ~/.config/ edits. Discuss before executing changes; cite file:line.'
32const NUDGE_DEFAULT = "CAROL NUDGE — Stay in role: plan and delegate (@Engineer code, @Pathfinder discovery, @Auditor once at sprint completion). Answer by reading; every claim cites file:line. Before the plan locks, hold answers until ARCHITECT's go. After the lock, execute to the endpoint per CAROL.md Step Gate."
33
34const promptCount = atom({ plugin: 'carol', key: 'promptCount' }, 0)
35const armedAtMs = atom({ plugin: 'carol', key: 'armedAtMs' }, 0)
36const isNoGateArmed = atom({ plugin: 'carol', key: 'isNoGateArmed' }, false)
37const isGitInstructed = atom({ plugin: 'carol', key: 'isGitInstructed' }, false)
38const sessionAgentType = atom({ plugin: 'carol', key: 'sessionAgentType' }, '')
39
40function countMatches(pattern, text) {
41 return (text.match(pattern) ?? []).length
42}
43
44async function getRole($) {
45 const role = await $.env.get('CAROL_ROLE')
46 if (role) return role
47 const roleFile = (await $.env.get('CAROL_ROOT')) + ROLE_FILE
48 const fileRole = (await $.fs.exists(roleFile)) ? (await $.fs.read(roleFile)).trim() : ''
49 return fileRole || DEFAULT_ROLE
50}
51
52async function armNoGate($) {
53 const armedAt = await $.clock.now()
54 await update($, isNoGateArmed, () => true)
55 await update($, armedAtMs, () => armedAt)
56}
57
58function getFeedbackText(outcome) {
59 if (outcome.isError === true) return outcome.text ?? ''
60 const { answers = {}, response = '' } = outcome.result ?? {}
61 return [response, ...Object.values(answers)].join('\n')
62}
63
64async function isNoGateRun($) {
65 return (await read($, isNoGateArmed)) && (await getRole($)) === DEFAULT_ROLE
66}
67
68async function getExpectedModel($, agentType) {
69 const definition = (await $.env.get('CAROL_ROOT')) + AGENTS_DIRECTORY + agentType + '.md'
70 if (!(await $.fs.exists(definition))) return undefined
71 const line = (await $.fs.read(definition)).split('\n').find((candidate) => candidate.startsWith('model:'))
72 return line.replace(/^model:\s*/, '')
73}
74
75async function isSprintLogNewer($, sprintLog) {
76 return (await $.fs.exists(sprintLog)) && (await $.fs.stat(sprintLog)).mtimeMs > (await read($, armedAtMs))
77}
78
79async function getSubagentType($, agentId) {
80 const agents = await $.agent.list()
81 return (agents.find((agent) => agent.id === agentId)?.type ?? '').toLowerCase()
82}
83
84async function getPermittedInvocations($, command, agentId) {
85 const isMainSession = agentId === undefined
86 const isReadOnlyPermitted = isMainSession || (await getSubagentType($, agentId)) === READ_ONLY_GIT_AGENT
87 const isSyncPermitted = isMainSession && (await read($, sessionAgentType)) === MACHINIST_ROLE
88 const readOnly = isReadOnlyPermitted ? countMatches(GIT_READ_ONLY_PATTERN, command) : 0
89 return isSyncPermitted ? readOnly + countMatches(GIT_SYNC_PATTERN, command) : readOnly
90}
91
92async function getBashVerdict($, command, agentId, isBackground) {
93 if (agentId !== undefined && isBackground) return { deny: BACKGROUND_GATE }
94 if (IN_PLACE_PATTERN.test(command)) return { deny: IN_PLACE_GATE }
95 const invocations = countMatches(GIT_COMMAND_PATTERN, command)
96 if (invocations === 0 || (await read($, isGitInstructed))) return undefined
97 return invocations === (await getPermittedInvocations($, command, agentId)) ? undefined : { deny: GIT_GATE }
98}
99
100async function failClosed($, e, next) {
101 if (next.called) return next(e)
102 return { deny: 'CAROL gate failed (' + next.error.kind + '), so this call was not run.' }
103}
104
105export function register(on) {
106 on('classic.UserPromptSubmit', async ($, e, next) => {
107 await update($, sessionAgentType, () => e.agent_type ?? '')
108 return next(e)
109 })
110
111 on('prompt.submit', async ($, e, next) => {
112 if (USER_ORIGIN_KINDS.includes(e.origin.kind)) {
113 if (NO_GATE_PATTERN.test(e.text)) await armNoGate($)
114 await update($, isGitInstructed, () => GIT_INSTRUCTION_PATTERN.test(e.text))
115 }
116 await update($, promptCount, (count) => count + 1)
117 const context = [...(e.context ?? []), READ_DIRECTIVE]
118 if ((await read($, promptCount)) % NUDGE_INTERVAL === 0) {
119 context.push((await getRole($)) === MACHINIST_ROLE ? NUDGE_MACHINIST : NUDGE_DEFAULT)
120 }
121 return next({ ...e, context })
122 })
123
124 on('classic.Stop', async ($, e, next) => {
125 if (await isNoGateRun($)) {
126 if (await isSprintLogNewer($, e.cwd + '/' + SPRINT_LOG)) {
127 await update($, isNoGateArmed, () => false)
128 } else if (e.stop_hook_active !== true) {
129 return { block: STEP_GATE }
130 }
131 }
132 if (OPEN_END_PATTERN.test(e.last_assistant_message ?? '') && e.stop_hook_active !== true) {
133 return { block: READ_DIRECTIVE }
134 }
135 return next(e)
136 })
137
138 on('tool.call', { tool: ['AskUserQuestion', 'EnterPlanMode', 'ExitPlanMode'] }, async ($, e, next) => {
139 if (await isNoGateRun($)) return { deny: STEP_GATE }
140 const outcome = await next(e)
141 if (NO_GATE_PATTERN.test(getFeedbackText(outcome))) await armNoGate($)
142 return outcome
143 }).catch(failClosed)
144
145 on('tool.call', { tool: ['Agent', 'Task'] }, async ($, e, next) => {
146 const agentType = String(e.subagent_type ?? '').toLowerCase()
147 const expected = await getExpectedModel($, agentType)
148 const passed = e.model ?? ''
149 if (expected !== undefined && passed !== expected) {
150 return { deny: 'Agent call needs model "' + expected + '", the model: value in ' + agentType + ".md. Pass model \"" + expected + "\" on every Agent call. Per CAROL.md Subagent Model, a tier change is ARCHITECT's edit to the definition." }
151 }
152 return next(e)
153 }).catch(failClosed)
154
155 on('tool.call', { tool: 'Bash' }, async ($, e, next) => {
156 const verdict = await getBashVerdict($, e.command, e.agentId, e.run_in_background === true)
157 return verdict === undefined ? next(e) : verdict
158 }).catch(failClosed)
159
160 on('tool.call', { tool: 'Monitor' }, async ($, e, next) => {
161 return e.agentId === undefined ? next(e) : { deny: BACKGROUND_GATE }
162 }).catch(failClosed)
163}
164hooks/types/index.d.ts 12 lines1declare module 'claude-code' {
2 interface PluginState {
3 carol: {
4 promptCount: number
5 armedAtMs: number
6 isNoGateArmed: boolean
7 isGitInstructed: boolean
8 sessionAgentType: string
9 }
10 }
11}
12