Grades every request before its turn starts (task class → effort rung, in one low-effort completion) and routes it to the genius reasoning patterns and…

Claude Code mods and a separate Codex adapter for the ai-architect.tools harness. The Claude mods keep one concern per mod, state shared through dependencies:
| Mod | Owns | Depends on | |
|---|---|---|---|
cortex-guard | refusals: wiki pages only through wiki_write, worktrees inside <repo>/.claude/worktrees/ | nothing | |
cortex-wiki | /wiki <wiki/**.md> to PDF | nothing | |
zetetic-genius | state: the request grade (task class → effort), the genius patterns and skills it matches | nothing | |
zetetic-autopilot | context, policy, phases: effort ladder, model routing (a subagent's call, then its own definition, then its prompt's DESIGN block, never lowered by pressure), the dispatch table (hooks/dispatch-table.ts): an inheriting subagent nobody designed runs at the model and effort of its task's class, graded by one classifier completion (cls/review on each spawn record the table decided, absent before 0.11.0), an inheriting subagent's effort from the turn's grade when its call names a model but no effort (effort on each spawn record, absent before 0.10.0), the quota's cap on the main loop's parallel subagents, offloaded tool results; the phase each loop is in, on each run the steps a stuck escalation raised (escalated, absent before 0.8.0), and the advisor calls | zetetic-genius | |
zetetic-insights | insights: the turn ledger across sessions ($.store), joined with /insights session outcomes and .zetetic/goals; per-phase effort proposals, `/calibrate apply\ | reset`, the calibration file the autopilot reads | zetetic-autopilot, zetetic-genius |
mission-control | renderer; the /mission pane: the turn's lanes by phase (bar height = effort, advisor calls, failed calls), effort per phase, learning curves per phase. Pixels in kitty or Ghostty outside tmux, coloured cells elsewhere | zetetic-autopilot, zetetic-insights | |
harness-fleet | fleet: the owner's plugins, installed vs offered version, open PRs with CI, open issues (a defect is taken and fixed, a feature request goes to the owner); /fleet. Reads only (gh pr list, gh issue list, git remote): every outward action is a button the owner presses, which puts a prompt in front of the model | guard, genius, autopilot | |
superpowers | third-party skills library (obra/superpowers, MIT), pinned to v7.0.0 bb92a77: listed here so it installs with the mods; which skills we keep is decided after measurement | nothing |
Each output of a mod has one reader, and the engine fixes the reader by the API the output goes through (there is no per-call option): $.ui.toast, $.ui.log, $.ui.status, panes and rows are the user's, and the model never sees them; a tool.call result's context, a prompt.submit context and prompt.compose sections are Claude's, and the user never sees them; a deny is the model's tool error (the transcript draws it too). A text is written for its reader, and one string is never sent to both. The mods that send to both say which text is whose:
zetetic-autopilot: the user reads a toast when main implements (what main ran) and when a subagent spawn is refused (which spawn, how many run, the cap and the window: no instruction); Claude reads, in the context of main's first implementing tool result of a turn, the rule to delegate to a subagent, and, as the Agent tool's error, the cap refusal with the way out (wait for a running agent to finish, spawn again).cortex-guard: the user reads a toast for each refusal, for a worktree that was not registered, and for a guard that failed; Claude reads the refusal's rule and fix as the tool's error (the same error when the guard itself failed), and, in the context of the result of its git worktree add, that the worktree was not registered and its cleanup is not covered.harness-fleet: the user reads the /fleet pane and its toasts; Claude reads only what a button the user presses puts in front of it (review, take an issue, draft an issue), as "The harness-fleet plugin sent a message: ..." in the plugin's own voice: the owner is "the owner" in it, never "me" or "I".Each mod is validated, tested and type-checked on its own:
cd mods/<mod> && claude plugin validate . && claude plugin test && npx -y -p typescript tsc -p . --noEmit
tsc needs the engine to have loaded the mod once (it lays .claude-plugin/types/); keep --noEmit, since a plain tsc -p . writes .js files beside the sources. For hot reload in a session, link the mod into that session's ~/.claude/dev-mods/<session>/ folder; the engine watches the folder a link names.
A mod cannot import a file from another mod (the engine refuses it: "outside the plugin's folder"), so the few small pure files several mods need are copied into each of them: hooks/paths.ts (where ~/ lands: HOME, else USERPROFILE, CLAUDE_CONFIG_DIR for ~/.claude) in five mods, and hooks/design.ts (the one parser of a prompt's DESIGN block) in zetetic-insights and zetetic-autopilot, each with its test. After editing one, copy it over the others; this fails when a copy differs:
sh scripts/check-shared.sh
.claude-plugin/marketplace.json lists each mod as "source": "./mods/<mod>", so the repository is the marketplace. From another machine:
/plugin install <mod> --marketplace cdeust/claude-mods
y adds the marketplace, then the user scope. On this machine a folder marketplace reads the mods from the checkout, with no copy: claude plugin marketplace add <this folder>, then /plugin install <mod> and /reload-plugins after an edit.
claude plugin marketplace add and claude plugin install both write enabledPlugins and extraKnownMarketplaces into settings.json. Where that file cannot be changed, load the mods by directory instead: nothing is written, and each mod is registered for the session as <name>@inline.
MODS=/path/to/claude-mods/mods
# repeat --plugin-dir once per mod
claude \
--plugin-dir $MODS/cortex-guard \
--plugin-dir $MODS/cortex-wiki \
--plugin-dir $MODS/zetetic-genius \
--plugin-dir $MODS/zetetic-autopilot \
--plugin-dir $MODS/zetetic-insights \
--plugin-dir $MODS/mission-control \
--plugin-dir $MODS/harness-fleet
# or one variable, colon separated
CLAUDE_CODE_PLUGIN_DIRS=$MODS/cortex-guard:$MODS/cortex-wiki:$MODS/zetetic-genius:$MODS/zetetic-autopilot:$MODS/zetetic-insights:$MODS/mission-control:$MODS/harness-fleet claude
# an alias in the shell profile: it sets MODS itself, because the alias body is single-quoted and
# is expanded each time it runs, not when the profile is read
alias claude-mods='MODS=/path/to/claude-mods/mods; CLAUDE_CODE_PLUGIN_DIRS=$MODS/cortex-guard:$MODS/cortex-wiki:$MODS/zetetic-genius:$MODS/zetetic-autopilot:$MODS/zetetic-insights:$MODS/mission-control:$MODS/harness-fleet claude'
Which form to prefer: an interactive session may ask for a login when CLAUDE_CONFIG_DIR points at an empty directory (seen once in an isolated directory, where headless claude -p did not ask). On the machine's own configuration directory, which is already logged in, that does not apply; use the repeated --plugin-dir or the alias there, and keep an isolated CLAUDE_CONFIG_DIR for tests only.
claude plugin list shows them under "Session-only plugins" with Status: loaded.
What then must hold:
dependencies of a mod are resolved among the mods loaded in the same command, so load a mod together with what it names: zetetic-autopilot needs zetetic-genius; harness-fleet needs cortex-guard, zetetic-autopilot and zetetic-genius. A mod whose dependency is absent is listed disabled, with the error Dependency "<name>" is not installed.settings.json under pluginConfigs), so every default in a plugin.json has to be right on any machine:| Mod | Option | Default | Notes |
|---|---|---|---|
cortex-guard | hygiene_script | ~/Developments/disk-hygiene/disk_hygiene.py | ~/ is the home of the user running the session, read at runtime. When the file is not there, one toast per session says hygiene script not found at <path>; worktrees are not registered; an empty value disables the registration without a toast. A python3 that fails to start gets one toast naming the cause, and no further worktree is registered for the session (no retry) |
zetetic-genius | mode, classifier_model | observe, haiku | the grade is one low-effort completion on the haiku alias |
zetetic-autopilot | policy_mode, quota_pressure_percent, max_parallel_agents, offload_threshold_chars, offload_preview_chars | enforce, 80, 5, 30000, 2000 | the cap counts and refuses only the main loop's own spawns (a fork of main included): a subagent's nested spawn, a workflow script's agent() and a teammate are neither refused nor counted. A result past the threshold is written whole to a file in the session's tool-results directory (the engine's cleanupPeriodDays sweeps it, 30 days by default; the mod deletes nothing); the model reads the preview, the path and the size |
mission-control | renderer | auto | auto draws pixels in kitty or Ghostty outside tmux (TMUX, TERM, TERM_PROGRAM, KITTY_WINDOW_ID), cells elsewhere; cells or pixels forces one |
harness-fleet | github_owner, refresh_on_start | cdeust, true | reads gh pr list, gh issue list and git remote |
python3 (guard), gh and a route to api.github.com (fleet), the files under ~/.claude/plugins/ (fleet), pandoc and xelatex (wiki), and the model aliases (genius, autopilot).Measured, on one Mac (Claude Code 2.1.293, no company sandbox): with a pristine settings.json holding {} and an isolated CLAUDE_CONFIG_DIR, loading the mods by CLAUDE_CODE_PLUGIN_DIRS lists them as loaded and leaves settings.json at {}; zetetic-autopilot loaded alone is disabled with the dependency error above.
Not measured: the managed-settings lock itself (it could not be reproduced), whether a company policy accepts --plugin-dir, any refusal of a real sandbox (blocked network, denied exec, unreadable ~/.claude), the model aliases, and whether /config lists the options of directory-loaded mods in an interactive session.
hooks/register.tsx 233 lines1import { atom, read, update } from 'claude-code'
2import type { EngineInterface, Register } from 'claude-code'
3
4import type { Classified, GeniusDecision, GeniusState } from '../types'
5import { placePath } from './paths'
6import {
7 SHAPES_PATH,
8 SHAPE_SKILL_PREFIX,
9 type Shape,
10 classifierPrompt,
11 classifierSystem,
12 advisorContext,
13 isClassifiable,
14 parseClassification,
15 parseShapes,
16 sameRequest,
17 shapeContext,
18 toClassified,
19} from './classify'
20import {
21 GENIUS_DIR,
22 GENIUS_INDEX,
23 GENIUS_PLUGIN,
24 INSTALLED_PLUGINS_PATH,
25 type GeniusRow,
26 geniusContext,
27 installPathOf,
28 parseGeniusIndex,
29} from './genius'
30
31// source: platform.claude.com/docs/en/models/haiku-5-5/whats-new-haiku-5-5: adaptive thinking is on by
32// default and its tokens count toward max_tokens, so a small cap can end after the thinking block;
33// the JSON answer itself is under 60 tokens, unused room costs nothing.
34const CLASSIFIER_MAX_TOKENS = 1024
35const CLASSIFIER_TIMEOUT_MS = 4000 // source: own choice, a prompt must not wait longer on its classifier
36const DECISIONS_CAP = 50 // source: bounds $.state size; a viewer shows the last rows only
37
38const state = atom({ plugin: 'zetetic-genius', key: 'state' } as const, {
39 mode: 'observe',
40 classifierModel: 'haiku',
41 classified: null,
42 classifierError: null,
43 skillShapesLoaded: 0,
44 geniusShapesLoaded: 0,
45 geniusDir: null,
46 decisions: [],
47} as GeniusState)
48
49// The two option lists, read at start; module state a hot reload rebuilds through session.start.
50let skills: Shape[] = []
51let genius: GeniusRow[] = []
52let geniusDir: string | null = null
53
54// Where a `~/` path lands on this machine: HOME, else USERPROFILE, and CLAUDE_CONFIG_DIR for what lives
55// in the engine's config directory (paths.ts). No home to place it is an error with that reason.
56async function expandHome($: EngineInterface, path: string): Promise<string> {
57 if (!path.startsWith('~/')) return path
58 const placed = placePath(
59 { home: await $.env.get('HOME'), userProfile: await $.env.get('USERPROFILE'), configDir: await $.env.get('CLAUDE_CONFIG_DIR') },
60 path,
61 )
62 if ('reason' in placed) throw new Error(placed.reason)
63
64 return placed.path
65}
66
67const fail = async ($: EngineInterface, what: string, error: unknown): Promise<void> => {
68 await update($, state, (s) => ({ ...s, classifierError: `${what}: ${String(error).slice(0, 100)}` }))
69}
70
71// The skill shapes from the generated routing table; absent, the classifier grades effort alone.
72async function loadSkills($: EngineInterface): Promise<void> {
73 try {
74 skills = parseShapes(await $.fs.read(await expandHome($, SHAPES_PATH)))
75 await update($, state, (s) => ({ ...s, skillShapesLoaded: skills.length }))
76 } catch (error) {
77 skills = []
78 await fail($, SHAPES_PATH, error)
79 }
80}
81
82// The genius shapes from the installed plugin's INDEX.md, found through installed_plugins.json.
83async function loadGenius($: EngineInterface): Promise<void> {
84 try {
85 const installed = await $.fs.read(await expandHome($, INSTALLED_PLUGINS_PATH))
86 const root = installPathOf(installed, GENIUS_PLUGIN)
87 if (root === undefined) throw new Error(`${GENIUS_PLUGIN} is not installed`)
88 geniusDir = `${root}/${GENIUS_DIR}`
89 genius = parseGeniusIndex(await $.fs.read(`${geniusDir}/${GENIUS_INDEX}`))
90 await update($, state, (s) => ({ ...s, geniusDir, geniusShapesLoaded: genius.length }))
91 } catch (error) {
92 genius = []
93 geniusDir = null
94 await fail($, 'genius index', error)
95 }
96}
97
98// One low-effort completion grades the request; anything but a strict answer is no decision.
99async function classify($: EngineInterface, text: string): Promise<Classified | undefined> {
100 const s = await read($, state)
101 const started = await $.clock.now()
102 const r = await $.model.complete({
103 model: s.classifierModel,
104 effort: 'low',
105 system: [{ text: classifierSystem(skills, genius), cache: true }],
106 prompt: classifierPrompt(text),
107 maxTokens: CLASSIFIER_MAX_TOKENS,
108 timeoutMs: CLASSIFIER_TIMEOUT_MS,
109 })
110 const now = await $.clock.now()
111 if (!r.isAnswered) {
112 await fail($, 'classifier', r.reason)
113 return undefined
114 }
115 const c = parseClassification(r.text, skills, genius)
116 if (c === undefined) {
117 await fail($, 'classifier answered off-contract', r.text.slice(0, 80))
118 return undefined
119 }
120 const classified = toClassified(c, text, started, now)
121 await update($, state, (st) => ({ ...st, classified, classifierError: null }))
122 return classified
123}
124
125// The context blocks a graded prompt carries: each genius pattern's procedure, then the skills.
126async function contextFor($: EngineInterface, c: Classified): Promise<string[]> {
127 const blocks: string[] = []
128 for (const pick of c.geniuses) {
129 if (geniusDir === null) break
130 const path = `${geniusDir}/${pick.agent}.md`
131 try {
132 blocks.push(geniusContext(pick.agent, await $.fs.read(path), genius, path))
133 } catch (error) {
134 await fail($, path, error)
135 }
136 }
137 if (c.shapes.length > 0) blocks.push(shapeContext(c.shapes))
138 return blocks
139}
140
141const decide = (s: GeniusState, d: GeniusDecision): GeniusState => ({
142 ...s,
143 decisions: [...s.decisions, d].slice(-DECISIONS_CAP),
144})
145
146export const register: Register = (on, options) => {
147 const mode: GeniusState['mode'] = options.mode === 'enforce' ? 'enforce' : 'observe'
148 const classifierModel = String(options.classifier_model ?? 'haiku')
149 // A hot reload keeps $.state from the previous load: the configured fields are set afresh.
150 const configured = (s: GeniusState): GeniusState => ({ ...s, mode, classifierModel })
151
152 on('session.start', async ($, e, next) => {
153 await update($, state, configured)
154 await loadSkills($)
155 await loadGenius($)
156
157 return next(e)
158 })
159
160 // /clear, /resume and /branch reset $.state and never fire session.start again.
161 on('classic.SessionStart', { source: ['clear', 'resume', 'fork'] }, async ($, e, next) => {
162 await update($, state, configured)
163 await loadSkills($)
164 await loadGenius($)
165
166 return next(e)
167 })
168
169 // Observed, the prompt goes through untouched; enforced, the patterns ride beside it.
170 on('prompt.submit', async ($, e, next) => {
171 if (!isClassifiable(e.text, e.origin)) return next(e)
172 const c = await classify($, e.text)
173 const advice = c === undefined ? undefined : advisorContext(c.taskClass)
174 if (c === undefined || (c.geniuses.length === 0 && c.shapes.length === 0 && advice === undefined)) return next(e)
175 const applied = (await read($, state)).mode === 'enforce'
176 for (const g of c.geniuses)
177 await update($, state, (s) =>
178 decide(s, { at: c.at, kind: 'genius', subject: g.shape, to: `${g.agent} pattern`, applied }),
179 )
180 if (c.shapes.length > 0)
181 await update($, state, (s) =>
182 decide(s, {
183 at: c.at,
184 kind: 'shape',
185 subject: c.shapes.join(' + '),
186 to: c.shapes.map((id) => `${SHAPE_SKILL_PREFIX}${id}`).join(', '),
187 applied,
188 }),
189 )
190 if (advice !== undefined)
191 await update($, state, (s) => decide(s, { at: c.at, kind: 'advisor', subject: c.taskClass, to: 'advisor before the first edit and before done', applied }))
192 if (!applied) return next(e)
193 const blocks = [...(await contextFor($, c)), ...(advice === undefined ? [] : [advice])]
194 return blocks.length === 0 ? next(e) : next({ ...e, context: [...(e.context ?? []), ...blocks] })
195 })
196
197 // prompt.submit's turnId is the turn that was running, not the one the prompt starts: the
198 // grade binds to its turn here, by the prompt's opening. turn.start also fires for a subagent's
199 // turn, with no loop id (measured 2026-10-14): any other text leaves the grade as it is, bound
200 // to its own turn, which the autopilot matches by id.
201 on('turn.start', async ($, e, next) => {
202 const s = await read($, state)
203 const c = s.classified
204 const isOurs = c !== null && c.turnId === null && sameRequest(c.text, e.text)
205 const bound = isOurs && c !== null ? { ...c, turnId: e.turnId } : c
206 await update($, state, (st) => ({ ...st, classified: bound }))
207
208 return next(e)
209 })
210
211 on('ui.render', { component: 'AbovePrompt' }, async ($, e, next) => {
212 const s = await read($, state)
213 const c = s.classified
214 if (e.props.hasSurvey || (c === null && s.classifierError === null)) return next(e)
215 const { Box, Text } = $.ui.resolve(e)
216 const picks = [...(c?.geniuses.map((g) => `${g.agent} · ${g.shape}`) ?? []), ...(c?.shapes ?? [])]
217 const graded =
218 c === null
219 ? 'no request graded'
220 : `${c.taskClass} → effort ${c.effort} · ${picks.length === 0 ? 'no pattern' : picks.join(' · ')} · ${c.ms} ms`
221 const trouble = s.classifierError === null ? '' : ` · ${s.classifierError}`
222
223 return (
224 <Box>
225 <Text dimColor>
226 genius {s.mode} · {graded}
227 {trouble}
228 </Text>
229 </Box>
230 )
231 })
232}
233hooks/paths.ts 41 lines1// Where `~/` lands on the machine a mod runs on. Pure: the engine follows `$` only inside the module
2// that spells it, so each mod's register file reads the three variables and hands their values here.
3//
4// This file exists once per mod that expands `~/` (a mod cannot import a file from another mod: the
5// engine refuses it, "outside the plugin's folder"), and every copy is byte-identical;
6// scripts/check-shared.sh fails when one differs.
7
8export type PathVars = { home: string | undefined; userProfile: string | undefined; configDir: string | undefined }
9export type Placed = { path: string } | { reason: string }
10
11const isSet = (value: string | undefined): value is string => value !== undefined && value !== ''
12const trimmed = (dir: string): string => dir.replace(/[\\/]+$/, '')
13
14// source: HOME is the home on macOS and Linux, USERPROFILE on Windows (cmd and PowerShell set it,
15// not HOME); Node's os.homedir() reads them in that order on each platform. Unset in a sandbox: no
16// place, said as such, never `/`.
17export const homeOf = (vars: PathVars): Placed =>
18 isSet(vars.home) ? { path: trimmed(vars.home) } : isSet(vars.userProfile) ? { path: trimmed(vars.userProfile) } : { reason: 'neither HOME nor USERPROFILE is set' }
19
20// source: CLAUDE_CONFIG_DIR relocates the engine's `~/.claude` (plugins/, reference/, settings.json);
21// without it the config directory is `<home>/.claude`.
22export const configDirOf = (vars: PathVars): Placed => {
23 if (isSet(vars.configDir)) return { path: trimmed(vars.configDir) }
24 const home = homeOf(vars)
25
26 return 'path' in home ? { path: `${home.path}/.claude` } : home
27}
28
29const CONFIG_PREFIX = '~/.claude'
30
31// A path as the mods spell it: `~/.claude/...` is under the config directory, any other `~/...` under
32// the home, anything else is already a place.
33export const placePath = (vars: PathVars, path: string): Placed => {
34 if (!path.startsWith('~/')) return { path }
35 const isConfig = path === CONFIG_PREFIX || path.startsWith(`${CONFIG_PREFIX}/`)
36 const base = isConfig ? configDirOf(vars) : homeOf(vars)
37 if ('reason' in base) return { reason: `${path} has no place: ${base.reason}` }
38
39 return { path: `${base.path}/${path.slice(isConfig ? CONFIG_PREFIX.length + 1 : 2)}` }
40}
41hooks/classify.ts 145 lines1// Pure half of the request classifier: what the cheap model is asked, how its answer is read,
2// and what each answer means for effort. The two option lists come from files read at start.
3
4import type { Classified, Effort, GeniusPick, TaskClass } from '../types'
5import type { GeniusRow } from './genius'
6
7// source: ~/.claude/reference/skill-routing-table.md, generated from the problem-shaped skills'
8// `shapes:` frontmatter (zetetic-team-subagents); read at session start, never copied here.
9export const SHAPES_PATH = '~/.claude/reference/skill-routing-table.md'
10// source: the skills are installed under this plugin name (the Skill tool lists them so).
11export const SHAPE_SKILL_PREFIX = 'zetetic-team-subagents:'
12
13export type Shape = { id: string; description: string }
14
15// `| shape | skill | description |` rows; the header and the separator carry no shape.
16export const parseShapes = (table: string): Shape[] =>
17 table
18 .split('\n')
19 .map((line) => line.split('|').map((cell) => cell.trim()))
20 .filter((cells) => cells.length >= 4 && /^[a-z][a-z-]+$/.test(cells[1] ?? ''))
21 .map((cells) => ({ id: cells[1] ?? '', description: (cells[3] ?? '').replace(/\s+/g, ' ') }))
22
23// source: effort-calibration.md task table: reading and I/O low; a fully specified plan low; a
24// clear bug fix low–medium (medium here, the higher bound); architecture, PRD, research
25// synthesis medium; correctness-critical work high; "genuinely stuck" high is the autopilot's
26// stuck signal, not the classifier's.
27export const TASK_CLASSES: readonly TaskClass[] = ['routine', 'planned', 'bugfix', 'analysis', 'critical']
28const CLASS_EFFORT: Record<TaskClass, Effort> = {
29 routine: 'low',
30 planned: 'low',
31 bugfix: 'medium',
32 analysis: 'medium',
33 critical: 'high',
34}
35export const effortForClass = (cls: TaskClass): Effort => CLASS_EFFORT[cls]
36
37export type Classification = { taskClass: TaskClass; shapes: string[]; geniuses: GeniusPick[] }
38
39// source: own choice, under this length the text continues the previous task ("yes", "go on")
40// and carries no shape of its own.
41export const MIN_CLASSIFIABLE_CHARS = 20
42// source: own choice, the opening of a request names its task; the rest is pasted material.
43export const PROMPT_HEAD_CHARS = 4000
44export const MAX_PICKS = 2 // source: /genius:route recommends 1–3 agents; two patterns at most per prompt
45
46// A slash command runs through command.run; a plugin's own submit is not the person's request.
47export const isClassifiable = (text: string, origin: { kind: string }): boolean =>
48 origin.kind !== 'plugin' && !text.trimStart().startsWith('/') && text.trim().length >= MIN_CLASSIFIABLE_CHARS
49
50export const classifierSystem = (shapes: readonly Shape[], genius: readonly GeniusRow[]): string =>
51 [
52 'You classify one request addressed to a coding agent. Answer with one JSON object and nothing else:',
53 '{"task_class": <class>, "shapes": [<skill id>, ...], "geniuses": [{"agent": <agent>, "shape": <shape>}, ...]}',
54 '',
55 'task_class is exactly one of:',
56 '- routine: reading, listing, searching, formatting, a one-line change, a question answered from files.',
57 '- planned: implementing a plan or spec that is already written out in the request.',
58 '- bugfix: a bug whose cause is clear or quickly located.',
59 '- analysis: an architecture decision, a design, a research synthesis, a multi-file feature.',
60 '- critical: formal correctness, concurrency, security, billing, data loss; a wrong answer is worse than a slow one.',
61 '',
62 `shapes and geniuses together hold at most ${MAX_PICKS} picks whose trigger the request clearly matches; both [] when none does.`,
63 // source: agents/genius/INDEX.md, its rule, verbatim.
64 'Rule: if no shape below matches the problem, do not force a genius agent.',
65 'A pick fits only when the request has that structure, never because the topic is adjacent.',
66 'Prefer a genius shape (a precise reasoning procedure) over a skill when both would fit; never pick both for the same structure.',
67 '',
68 'Skills (problem-shaped methods):',
69 ...shapes.map((s) => `- ${s.id}: ${s.description}`),
70 '',
71 'Genius shapes (agent in parentheses, then the trigger):',
72 ...genius.map((g) => `- ${g.shape} (${g.agent}): ${g.trigger}`),
73 ].join('\n')
74
75export const classifierPrompt = (text: string): string => text.slice(0, PROMPT_HEAD_CHARS)
76
77const asPick = (v: unknown, known: readonly GeniusRow[]): GeniusPick | undefined => {
78 const o = v as { agent?: unknown; shape?: unknown } | null
79 if (o === null || typeof o !== 'object' || typeof o.agent !== 'string' || typeof o.shape !== 'string') return undefined
80 return known.some((g) => g.agent === o.agent && g.shape === o.shape) ? { agent: o.agent, shape: o.shape } : undefined
81}
82
83// Strict: a JSON object, fenced or bare; an unknown class, skill or genius pair voids the answer.
84export const parseClassification = (
85 answer: string,
86 shapes: readonly Shape[],
87 genius: readonly GeniusRow[],
88): Classification | undefined => {
89 const match = /\{[\s\S]*\}/.exec(answer)
90 if (match === null) return undefined
91 let raw: unknown
92 try {
93 raw = JSON.parse(match[0])
94 } catch {
95 return undefined
96 }
97 const obj = raw as { task_class?: unknown; shapes?: unknown; geniuses?: unknown }
98 const cls = obj.task_class
99 if (typeof cls !== 'string' || !(TASK_CLASSES as readonly string[]).includes(cls)) return undefined
100 const knownSkills = new Set(shapes.map((s) => s.id))
101 const skills = Array.isArray(obj.shapes) ? obj.shapes : []
102 if (!skills.every((s) => typeof s === 'string' && knownSkills.has(s))) return undefined
103 const picks = Array.isArray(obj.geniuses) ? obj.geniuses.map((g) => asPick(g, genius)) : []
104 if (picks.some((p) => p === undefined)) return undefined
105 const geniuses = (picks as GeniusPick[]).filter((p, i, all) => all.findIndex((q) => q.agent === p.agent) === i)
106 const uniqueSkills = [...new Set(skills as string[])]
107 const room = Math.max(0, MAX_PICKS - geniuses.slice(0, MAX_PICKS).length)
108 return { taskClass: cls as TaskClass, shapes: uniqueSkills.slice(0, room), geniuses: geniuses.slice(0, MAX_PICKS) }
109}
110
111export const toClassified = (c: Classification, text: string, startedAt: number, now: number): Classified => ({
112 turnId: null,
113 text,
114 taskClass: c.taskClass,
115 effort: effortForClass(c.taskClass),
116 shapes: c.shapes,
117 geniuses: c.geniuses,
118 ms: now - startedAt,
119 at: now,
120})
121
122// source: the Advisor tool's own instructions to the main model (call it before substantive work
123// and again before declaring done; on short reactive tasks it adds little after the first call).
124// The grades that are long enough to have a decision point and a completion worth checking:
125export const ADVISOR_CLASSES: readonly TaskClass[] = ['analysis', 'critical']
126
127// One line beside the prompt for those grades; the advisor is a server tool, nothing can gate it.
128export const advisorContext = (cls: TaskClass): string | undefined =>
129 ADVISOR_CLASSES.includes(cls)
130 ? `zetetic-genius: this request is graded ${cls}. Consult the advisor once after orientation and before the first edit, and once before declaring done; not between routine steps.`
131 : undefined
132
133// What the model reads beside the prompt when a skill fits: load it first.
134export const shapeContext = (ids: readonly string[]): string =>
135 [
136 'zetetic-genius: this request matches a reasoning shape. Before answering, invoke the Skill tool for',
137 ...ids.map((id) => ` ${SHAPE_SKILL_PREFIX}${id}`),
138 'and follow its method. Say in one line which shape you applied.',
139 ].join('\n')
140
141// source: own choice, the opening of a prompt identifies it at turn.start.
142export const BIND_HEAD_CHARS = 200
143export const sameRequest = (a: string, b: string): boolean =>
144 a.slice(0, BIND_HEAD_CHARS) === b.slice(0, BIND_HEAD_CHARS)
145hooks/genius.ts 78 lines1// Pure side of the genius patterns: where they are installed, how INDEX.md routes by shape, and
2// what part of a pattern file rides beside the prompt.
3
4// source: ~/.claude/plugins/installed_plugins.json, the engine's record of installed plugins;
5// `plugins["<name>@<marketplace>"][0].installPath` is the folder a session runs.
6export const INSTALLED_PLUGINS_PATH = '~/.claude/plugins/installed_plugins.json'
7export const GENIUS_PLUGIN = 'zetetic-team-subagents@zetetic-marketplace'
8// source: the plugin's layout, agents/genius/<name>.md and agents/genius/INDEX.md.
9export const GENIUS_DIR = 'agents/genius'
10export const GENIUS_INDEX = 'INDEX.md'
11
12export const installPathOf = (installedPluginsJson: string, plugin: string): string | undefined => {
13 let parsed: { plugins?: Record<string, { installPath?: unknown }[]> }
14 try {
15 parsed = JSON.parse(installedPluginsJson) as typeof parsed
16 } catch (error) {
17 // A record that is not JSON is not "plugin not installed": the caller is told which it is.
18 throw new Error(`installed_plugins.json is not valid JSON (${error instanceof Error ? error.message : String(error)})`.slice(0, 160))
19 }
20 const path = parsed.plugins?.[plugin]?.[0]?.installPath
21 return typeof path === 'string' && path !== '' ? path : undefined
22}
23
24// One INDEX.md row: `| **shape** | trigger | [agent](agent.md) | key move |`.
25export type GeniusRow = { shape: string; trigger: string; agent: string; keyMove: string }
26
27const ROW = /^\|\s*\*\*([a-z0-9-]+)\*\*\s*\|\s*(.*?)\s*\|\s*\[([a-z0-9-]+)\]\([^)]*\)\s*\|\s*(.*?)\s*\|\s*$/
28
29export const parseGeniusIndex = (md: string): GeniusRow[] =>
30 md
31 .split('\n')
32 .map((line) => ROW.exec(line))
33 .filter((m): m is RegExpExecArray => m !== null)
34 .map((m) => ({ shape: m[1] ?? '', trigger: m[2] ?? '', agent: m[3] ?? '', keyMove: m[4] ?? '' }))
35
36// The sections of a pattern file are XML-like tags; the procedure the model needs is the
37// identity's opening, the workflow and the output format (about 4–5 K characters), not the
38// canonical moves (11 K median), which stay one Read away.
39export const sectionOf = (file: string, tag: string): string | undefined => {
40 const m = new RegExp(`<${tag}>([\\s\\S]*?)</${tag}>`).exec(file)
41 return m === null ? undefined : (m[1] ?? '').trim()
42}
43
44export const identityOpening = (file: string): string => {
45 const identity = sectionOf(file, 'identity') ?? ''
46 return identity.split(/\n\s*\n/).find((p) => p.trim() !== '') ?? ''
47}
48
49// The pattern's own effort, from its frontmatter; the owner decides whether it floors a turn.
50export const patternEffort = (file: string): string | undefined => {
51 const m = /^effort:\s*([a-z]+)\s*$/m.exec(file.split(/^---\s*$/m)[1] ?? '')
52 return m === null ? undefined : m[1]
53}
54
55export const geniusContext = (
56 agent: string,
57 file: string,
58 rows: readonly GeniusRow[],
59 filePath: string,
60): string => {
61 const matched = rows.filter((r) => r.agent === agent)
62 return [
63 `zetetic-genius: apply the ${agent} reasoning pattern to this request, before anything else.`,
64 '',
65 identityOpening(file),
66 '',
67 ...matched.map((r) => `Shape ${r.shape}: ${r.trigger}. Key move: ${r.keyMove}`),
68 '',
69 'Workflow:',
70 sectionOf(file, 'workflow') ?? '(no workflow section)',
71 '',
72 'Output format:',
73 sectionOf(file, 'output-format') ?? '(no output-format section)',
74 '',
75 `The full pattern, with its canonical moves and blind spots, is ${filePath}; read it when a step needs more than the workflow says. Say in one line which pattern you applied.`,
76 ].join('\n')
77}
78types/index.d.ts 48 lines1// The request classifier's contract: what it decided about the current prompt.
2
3// source: ~/.claude/reference/agent-reference/effort-calibration.md § Effort levels (task table).
4export type TaskClass = 'routine' | 'planned' | 'bugfix' | 'analysis' | 'critical'
5export type Effort = 'low' | 'medium' | 'high' | 'xhigh' | 'max'
6
7// One genius reasoning pattern picked for the request, by the shape that matched.
8export type GeniusPick = { agent: string; shape: string }
9
10// What the classifier said about one prompt: pending (turnId null) until turn.start binds it.
11export type Classified = {
12 turnId: string | null
13 text: string
14 taskClass: TaskClass
15 effort: Effort
16 shapes: string[]
17 geniuses: GeniusPick[]
18 ms: number
19 at: number
20}
21
22export type GeniusDecision = {
23 at: number
24 kind: 'shape' | 'genius' | 'advisor'
25 subject: string
26 to: string
27 applied: boolean
28}
29
30export type GeniusState = {
31 mode: 'observe' | 'enforce'
32 classifierModel: string
33 classified: Classified | null
34 classifierError: string | null
35 skillShapesLoaded: number
36 geniusShapesLoaded: number
37 geniusDir: string | null
38 decisions: GeniusDecision[]
39}
40
41declare module 'claude-code' {
42 interface PluginState {
43 'zetetic-genius': {
44 state: GeniusState
45 }
46 }
47}
48