Enforces the role-to-model map and synchronous review dispatch on agent.spawn in autonomous sessions, and logs every rewrite

A hooks-only mod on agent.spawn that applies the review tiers mechanically instead of by prose, and logs each decision.
| Rule | Condition | Rewrite |
|---|---|---|
| model | The spawn's subagentType has a configured model and the call's model is unset or does not carry it (sonnet is satisfied by claude-sonnet-5-5) | model set to the configured alias |
| sync | run_in_background is true on a main-loop spawn of quality-reviewer, quality-verifier or developer | background set to false |
Forks, teammates and Workflow-started agents are left alone: the engine ignores model on the first two and every change on the third. An unset model is never compliant, because the agent definition's own pin then decides, and developer.md pins opus.
enforce decides whether a rule rewrites or only logs: auto rewrites once the auto skill has expanded in the session or when the spawn's permission mode is auto, and logs a would rewrite line elsewhere; always and never do what they say.
userConfig: enforce, developer_model (sonnet), verifier_model (sonnet), reviewer_model (opus), sync_review_dispatch (true), ledger (true).
<session root>/tmp/spawn-policy-<sessionId>.jsonl, one row per spawn a rule fired on:
{"ts":"...","session":"...","type":"developer","description":"fix batch 2","modelIn":null,"modelOut":"sonnet","backgroundIn":true,"backgroundOut":false,"rules":["model:developer->sonnet","sync:developer"],"enforced":true,"parentAgentId":null,"resolvedModel":"claude-sonnet-5-5"}
Installed user-wide by update.sh and loaded in place from this folder; claude --plugin-dir ~/.claude/mods/spawn-policy loads it for one session on a machine without the install. The retro reads the ledger as a Spawn policy line and spawn_policy in fleet-metrics.py's JSON.
claude plugin validate mods/spawn-policy && claude plugin test mods/spawn-policy && mods/typecheck.sh mods/spawn-policyhooks/register.ts 59 lines1import type { Register } from 'claude-code'
2import { decide, dotGitOf, owningCheckout, readOptions } from './policy'
3
4let autonomous = false
5let sessionId = ''
6let ledgerPath = ''
7let rows: string[] = []
8
9export const register: Register = (on, options) => {
10 const opts = readOptions(options)
11
12 on('session.start', async ($, e, next) => {
13 sessionId = await $.session.id()
14 if (opts.ledger) {
15 const reported = await $.session.root()
16 ledgerPath = `${owningCheckout(reported, await dotGitOf((path) => $.fs.read(path), reported))}/tmp/spawn-policy-${sessionId}.jsonl`
17 if (await $.fs.exists(ledgerPath)) rows = (await $.fs.read(ledgerPath)).split('\n').filter((line) => line !== '')
18 }
19 return next(e)
20 })
21
22 on('skill.prompt', { skill: 'auto' }, async ($, e, next) => {
23 autonomous = true
24 return next(e)
25 })
26
27 on('agent.spawn', async ($, e, next) => {
28 const decision = decide(e, opts.policy)
29 if (decision.rules.length === 0) return next(e)
30 const enforced = opts.enforce === 'always' || (opts.enforce === 'auto' && (autonomous || e.permissionMode === 'auto'))
31 const modelOut = enforced && decision.model !== undefined ? decision.model : e.model
32 const backgroundOut = enforced && decision.background === false ? false : e.background
33 const verb = enforced ? 'rewrote' : 'would rewrite'
34 $.ui.log(`${verb} ${e.subagentType}: ${decision.rules.join(', ')}`)
35 const rewritten = { ...e, background: backgroundOut }
36 const result = await next(!enforced ? e : modelOut === undefined ? rewritten : { ...rewritten, model: modelOut })
37 if (opts.ledger) {
38 rows.push(
39 JSON.stringify({
40 ts: new Date().toISOString(),
41 session: sessionId,
42 type: e.subagentType,
43 description: e.description,
44 modelIn: e.model ?? null,
45 modelOut: modelOut ?? null,
46 backgroundIn: e.background,
47 backgroundOut,
48 rules: decision.rules,
49 enforced,
50 parentAgentId: e.parentAgentId ?? null,
51 resolvedModel: result.model,
52 }),
53 )
54 await $.fs.write(ledgerPath, rows.join('\n') + '\n')
55 }
56 return result
57 }).catch(($, e, next) => next(e))
58}
59hooks/policy.ts 103 lines1export type Spawn = {
2 readonly subagentType: string
3 readonly model?: string
4 readonly background: boolean
5 readonly fork: boolean
6 readonly isTeammate?: true
7 readonly workflow?: unknown
8 readonly parentAgentId?: string
9}
10
11// The checkout a ledger belongs to. A session resumed inside a /start wt worktree reports the worktree as its root — measured
12// 2026-10-10: three fleet sessions resumed at 14:22Z wrote their later rows under <worktree>/tmp, where /finish deletes them and
13// fleet-metrics.py never looked — so a linked worktree (its `.git` is a file naming the owning repo's worktrees dir) resolves to
14// the checkout that owns it. Anything else, a main checkout's `.git` directory included, keeps the root as reported.
15export function owningCheckout(root: string, dotGit: string | null): string {
16 const target = /^gitdir:\s*(.+?)\s*$/m.exec(dotGit ?? '')?.[1]
17 if (target === undefined) return root
18 const gitdir = (/^(?:\/|[A-Za-z]:[\\/])/.test(target) ? target : `${root}/${target}`).replace(/\\/g, '/')
19 const at = gitdir.indexOf('/.git/worktrees/')
20 if (at === -1) return root
21 const out: string[] = []
22 for (const seg of gitdir.slice(0, at).split('/')) {
23 if (seg === '..') out.pop()
24 else if (seg !== '.' && (seg !== '' || out.length === 0)) out.push(seg)
25 }
26 return out.join('/')
27}
28
29// A main checkout's `.git` is a directory, which the read rejects; a linked worktree's is a one-line file.
30export async function dotGitOf(read: (path: string) => Promise<string>, root: string): Promise<string | null> {
31 try {
32 return await read(`${root}/.git`)
33 } catch {
34 return null
35 }
36}
37
38export type Policy = {
39 readonly models: Readonly<Record<string, string>>
40 readonly syncTypes: ReadonlySet<string>
41 readonly syncReview: boolean
42}
43
44export type Decision = {
45 readonly model?: string
46 readonly background?: false
47 readonly rules: readonly string[]
48}
49
50// An alias (`sonnet`) is compliant with itself and with any id or bracketed form that carries it (`claude-sonnet-5-5`,
51// `opus[1m]`); an unset model is never compliant, because the agent definition's own pin then decides (developer.md pins opus).
52export function isCompliant(given: string | undefined, want: string): boolean {
53 return given !== undefined && (given === want || given.includes(want))
54}
55
56export function decide(e: Spawn, policy: Policy): Decision {
57 if (e.fork || e.isTeammate === true || e.workflow !== undefined) return { rules: [] }
58 const rules: string[] = []
59 let model: string | undefined
60 let background: false | undefined
61 const want = policy.models[e.subagentType]
62 if (want !== undefined && !isCompliant(e.model, want)) {
63 model = want
64 rules.push(`model:${e.subagentType}->${want}`)
65 }
66 if (policy.syncReview && e.background && e.parentAgentId === undefined && policy.syncTypes.has(e.subagentType)) {
67 background = false
68 rules.push(`sync:${e.subagentType}`)
69 }
70 return background === false ? { model, background, rules } : { model, rules }
71}
72
73export type Enforce = 'auto' | 'always' | 'never'
74
75export type Options = {
76 readonly enforce: Enforce
77 readonly policy: Policy
78 readonly ledger: boolean
79}
80
81const REVIEW_TYPES = ['quality-reviewer', 'quality-verifier', 'developer'] as const
82
83function str(value: unknown, fallback: string): string {
84 return typeof value === 'string' && value !== '' ? value : fallback
85}
86
87export function readOptions(raw: Readonly<Record<string, unknown>>): Options {
88 const enforce = raw.enforce
89 return {
90 enforce: enforce === 'always' || enforce === 'never' ? enforce : 'auto',
91 policy: {
92 models: {
93 developer: str(raw.developer_model, 'sonnet'),
94 'quality-verifier': str(raw.verifier_model, 'sonnet'),
95 'quality-reviewer': str(raw.reviewer_model, 'opus'),
96 },
97 syncTypes: new Set(REVIEW_TYPES),
98 syncReview: raw.sync_review_dispatch !== false,
99 },
100 ledger: raw.ledger !== false,
101 }
102}
103