Skip to content

Commit 3913ac9

Browse files
committed
fix(hooks): read the spawn advisory roster from the event's project
The unrestricted-spawn advisory and the scoped-spawn deny scanned process.cwd()/.claude/agents. They now scan the cwd the hook payload names, falling back to process.cwd() as sibling hooks do, so three receipt test files no longer depend on the developer's own roster.
1 parent dfbc684 commit 3913ac9

5 files changed

Lines changed: 48 additions & 12 deletions

‎src/hooks_agent_spawn.ts‎

Lines changed: 9 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -221,7 +221,7 @@ export function preAgentHandler(event: HookEvent): HookOutput {
221221

222222
try {
223223
// Ahead of the outstanding-spawn registration: a denied call never runs, so registering it would flag its own retry as a near-duplicate.
224-
const scopedDeny = buildScopedSpawnDeny(toolInput)
224+
const scopedDeny = buildScopedSpawnDeny(toolInput, getCwd(event))
225225
if (scopedDeny) return scopedDeny
226226

227227
// Check for a near-duplicate BEFORE registering this prompt, so a spawn never flags itself.
@@ -420,10 +420,10 @@ export function parseAgentDefinition(text: string, fallbackName: string): { name
420420
return { name, restricted: false }
421421
}
422422

423-
/** Scan the machine-level agent roster (~/.claude/agents, recursively, following symlinked collection directories with a realpath cycle guard) and return the sorted names of every definition that carries a `tools:` allowlist. This is the advisory's existence gate: with no restricted definition on the machine there is nothing actionable to recommend, and an unclearable warning trains the user to ignore every warning the tool emits. Both the home roster and the project's own <cwd>/.claude/agents are scanned: the project roster holds exactly the definitions a spawn in that repo should be reaching for, and scanning it is what makes every name here potentially repository-authored rather than user-authored, which is why parseAgentDefinition constrains the name's shape before it can reach a model-facing advisory. */
424-
export function findRestrictedAgentNames(roots?: readonly string[]): string[] {
423+
/** Scan the machine-level agent roster (~/.claude/agents, recursively, following symlinked collection directories with a realpath cycle guard) and return the sorted names of every definition that carries a `tools:` allowlist. This is the advisory's existence gate: with no restricted definition on the machine there is nothing actionable to recommend, and an unclearable warning trains the user to ignore every warning the tool emits. Both the home roster and the project's own <projectDir>/.claude/agents are scanned (projectDir is the cwd the hook payload names, so a resident server's start directory or a payload from another project never picks the roster; process.cwd() only when the payload names none): the project roster holds exactly the definitions a spawn in that repo should be reaching for, and scanning it is what makes every name here potentially repository-authored rather than user-authored, which is why parseAgentDefinition constrains the name's shape before it can reach a model-facing advisory. */
424+
export function findRestrictedAgentNames(roots?: readonly string[], projectDir: string = process.cwd()): string[] {
425425
// The project roster is scanned alongside the home one because a repo's own .claude/agents holds exactly the definitions a spawn in that repo should be reaching for, and a home-only default made them invisible to the advisory: this repo carries three such definitions and the advisory named none of them. Duplicate roots are harmless, since the visited set below folds them.
426-
const projectAgentsRoot = path.join(process.cwd(), '.claude', 'agents')
426+
const projectAgentsRoot = path.join(projectDir, '.claude', 'agents')
427427
const scanRoots = roots ?? [path.join(claudeConfigDir(), 'agents'), projectAgentsRoot]
428428
const names = new Set<string>()
429429
const visited = new Set<string>()
@@ -499,7 +499,7 @@ export function findRestrictedAgentNames(roots?: readonly string[]): string[] {
499499
}
500500

501501
/** Build the once-per-session unrestricted-spawn advisory, or '' when it does not apply. Trigger: the finished spawn ran as general-purpose, either because `subagent_type` was absent (620 of 3,167 corpus spawn blocks) or because it named general-purpose explicitly; both are definitionally unrestricted with no definition file to resolve, which is the only restriction status observable at the hook without reading a roster file for the spawned type. Gate: at least one tools-restricted agent definition exists in ~/.claude/agents, so the advice is actionable and the hint clearable. Dedupe: once per session via the persisted hints-shown set. Accounting: recorded as a zero-credit `session_hint`. The advisory fires AFTER the spawn it observed and cannot save that spawn: the counterfactual it might improve (the user's next spawn, or their roster) is not a branch this code blocks, so crediting anything would repeat the advisory-credited-the-full-file defect class. The text says so explicitly for the same reason. */
502-
export function buildUnrestrictedSpawnAdvisory(toolInput: Record<string, unknown>): string {
502+
export function buildUnrestrictedSpawnAdvisory(toolInput: Record<string, unknown>, projectDir?: string): string {
503503
try {
504504
// Gated off entirely on Copilot CLI because the advisory's content is Claude Code's Task schema (subagent_type, ~/.claude/agents rosters). Copilot's own task tool carries agent_type, not subagent_type (captured toolArgs {description, prompt, agent_type, name}, tg-captures C4a), so the absent-field trigger would misclassify every Copilot task spawn as an untyped general-purpose spawn. The channel is not the reason: post_tool_use additionalContext does reach the model on Copilot 1.0.88 (tg-captures C1a). Other bridges are not gated here: their task-tool wire shapes are unverified (loop-ledger BE-06) and their bridges forward additionalContext, so suppressing them would rest on inference. VS Code is gated for the same schema reason, read off its own bundle: runSubagent takes {prompt, description, agentName, model} (RunSubagentTool.getToolData in VS Code 1.137.0's workbench.desktop.main.js), where agentName names a VS Code chat agent, so advice to pass a ~/.claude/agents name as subagent_type names a key the tool does not have.
505505
const harness = getHarnessName()
@@ -508,7 +508,7 @@ export function buildUnrestrictedSpawnAdvisory(toolInput: Record<string, unknown
508508
const spawnType = typeof rawType === 'string' ? rawType.trim() : ''
509509
if (spawnType !== '' && spawnType !== 'general-purpose') return ''
510510
if (wasHintShown(SPAWN_RESTRICT_HINT_KEY)) return ''
511-
const names = findRestrictedAgentNames()
511+
const names = findRestrictedAgentNames(undefined, projectDir)
512512
if (names.length === 0) return ''
513513
markHintShown(SPAWN_RESTRICT_HINT_KEY)
514514
recordStat('session_hint', 0, 0, undefined, 'agent-spawn-restrict')
@@ -525,14 +525,14 @@ export function buildUnrestrictedSpawnAdvisory(toolInput: Record<string, unknown
525525
const SCOPED_SPAWN_DENY_KEY = 'agent-scoped-spawn-deny'
526526

527527
/** The pre-tool counterpart of {@link buildUnrestrictedSpawnAdvisory}, behind `hints.agent_scoped_spawn_deny` (off by default). The advisory can only describe a spawn that has already paid for its unrestricted prefix; this refuses the first untyped spawn of a session before it runs and names the restricted definitions, so the retry can pick one. Narrower than the advisory on purpose: only an OMITTED subagent_type triggers it, since an explicit `general-purpose` is a choice the caller made, and a refusal that overrode a choice would just be re-issued. Once per session, so the promise the message makes -- re-issue unchanged and it runs -- is kept by construction. Harness-gated exactly as the advisory is, for the same schema reason. Returns null when it does not fire. */
528-
function buildScopedSpawnDeny(toolInput: Record<string, unknown>): HookOutput | null {
528+
function buildScopedSpawnDeny(toolInput: Record<string, unknown>, projectDir?: string): HookOutput | null {
529529
if (!loadConfig().hints.agent_scoped_spawn_deny) return null
530530
const harness = getHarnessName()
531531
if (harness === 'copilot_cli' || harness === 'vscode') return null
532532
const rawType = toolInput['subagent_type']
533533
if (typeof rawType === 'string' && rawType.trim() !== '') return null
534534
if (wasHintShown(SCOPED_SPAWN_DENY_KEY)) return null
535-
const names = findRestrictedAgentNames()
535+
const names = findRestrictedAgentNames(undefined, projectDir)
536536
if (names.length === 0) return null
537537
markHintShown(SCOPED_SPAWN_DENY_KEY)
538538
// The post-tool advisory would name the same definitions again after the retry runs; the deny has already said it.
@@ -631,7 +631,7 @@ export async function postAgentHandler(event: HookEvent): Promise<HookOutput> {
631631
// Built before the min_bytes early returns because the advisory is about the SPAWN, not the report: a lane that came back with a two-line answer paid the same unrestricted prefix. On the early-return paths it rides alone as the whole context output; past them it is folded into `notice` below, BEFORE the net-benefit gate prices that notice, so the gate-then-emit-extra accounting trap cannot reappear here.
632632
const receipt = (await loadAgentReceipt()).takeAgentReceipt(event.sessionId, resultText)
633633
if (receipt !== null) recordStat('agent_receipt', 0, 0, undefined, 'agent')
634-
const spawnAdvisory = [buildUnrestrictedSpawnAdvisory(event.toolInput), receipt ?? ''].filter((part) => part !== '').join('\n')
634+
const spawnAdvisory = [buildUnrestrictedSpawnAdvisory(event.toolInput, getCwd(event)), receipt ?? ''].filter((part) => part !== '').join('\n')
635635
if (!resultText || resultText.length < agentReportCfg.min_bytes) {
636636
return spawnAdvisory === '' ? passOutput() : contextOutput(spawnAdvisory)
637637
}

‎tests/agent_receipt.test.ts‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -258,7 +258,8 @@ describe('the receipt through the real hook registry', () => {
258258
last_assistant_message: message,
259259
...extra,
260260
})
261-
const agentResult = (sid: string, text: string) => runHook(buildEvent('post_tool_use', { tool_name: 'Agent', tool_input: { prompt: 'Look into it.' }, session_id: sid, tool_response: text }))
261+
// The event names the directory the roster is read from, so a developer's own .claude/agents under the process cwd never reaches these expectations.
262+
const agentResult = (sid: string, text: string) => runHook(buildEvent('post_tool_use', { tool_name: 'Agent', tool_input: { prompt: 'Look into it.' }, session_id: sid, tool_response: text, cwd: repo }))
262263

263264
it('a subagent whose last check failed gets a receipt on its report', async () => {
264265
const sid = newSession()

‎tests/agent_receipt_git_unfinished.test.ts‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -179,7 +179,8 @@ const stopPayload = (sid: string, cwd: string, message: string) => ({
179179
last_assistant_message: message,
180180
})
181181
const newSession = (): string => `s-unfinished-${process.pid}-${sessionCounter++}-${Math.random().toString(36).slice(2)}`
182-
const agentResult = (sid: string, text: string) => runHook(buildEvent('post_tool_use', { tool_name: 'Agent', tool_input: { prompt: 'Look into it.' }, session_id: sid, tool_response: text }))
182+
// The event names the directory the roster is read from, so a developer's own .claude/agents under the process cwd never reaches these expectations.
183+
const agentResult = (sid: string, text: string) => runHook(buildEvent('post_tool_use', { tool_name: 'Agent', tool_input: { prompt: 'Look into it.' }, session_id: sid, tool_response: text, cwd: repo.replaceAll(path.sep, '/') }))
183184

184185
/** Runs the stop hook over the repo held by `hold`'s filter, waits for the filter to have announced itself, then aborts git: the order is decided by those two events and no clock. Rejects when git ends before the filter started, which is a broken fixture and not a pass. */
185186
async function stopWhileHeld(sid: string, hold: Hold): Promise<Awaited<ReturnType<typeof runHook>>> {

‎tests/hooks_agent_spawn.test.ts‎

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -93,10 +93,12 @@ async function callAgentHook(
9393
toolInput: Record<string, unknown>,
9494
sid: string,
9595
toolResponse?: unknown,
96+
cwd?: string,
9697
) {
9798
resetSessionState()
9899
loadSessionState(sid)
99100
const payload: Record<string, unknown> = { tool_name: 'Agent', tool_input: toolInput, session_id: sid }
101+
if (cwd !== undefined) payload['cwd'] = cwd
100102
if (toolResponse !== undefined) payload['tool_response'] = toolResponse
101103
const result = await runHook(buildEvent(eventName, payload))
102104
saveSessionState(sid)
@@ -1181,6 +1183,37 @@ describe('unrestricted-spawn advisory (post_tool_use, gated on a restricted rost
11811183
expect(result.hookType).toBe('pass')
11821184
})
11831185

1186+
// HAND-DERIVED: two temp projects built here, one under the process cwd (this file chdirs into a sandbox) and one named only by the event's cwd; the expectations follow from which directory the event names, not from the matcher.
1187+
it('reads the roster of the project the event names, not the process cwd', async () => {
1188+
const eventProject = fs.realpathSync.native(fs.mkdtempSync(path.join(os.tmpdir(), 'tg-event-proj-')))
1189+
try {
1190+
fs.mkdirSync(path.join(process.cwd(), '.claude', 'agents'), { recursive: true })
1191+
fs.writeFileSync(path.join(process.cwd(), '.claude', 'agents', 'cwd-only.md'), '---\nname: process-cwd-agent\ntools: Read\n---\nb')
1192+
fs.mkdirSync(path.join(eventProject, '.claude', 'agents'), { recursive: true })
1193+
fs.writeFileSync(path.join(eventProject, '.claude', 'agents', 'event-only.md'), '---\nname: event-project-agent\ntools: Read\n---\nb')
1194+
const result = await callAgentHook('post_tool_use', { prompt: 'p', description: 'd' }, `${sessionId}-advisory-event-cwd`, 'short report', eventProject)
1195+
expect(result.hookType).toBe('context')
1196+
if (result.hookType === 'context') {
1197+
expect(result.context).toContain('event-project-agent')
1198+
expect(result.context).not.toContain('process-cwd-agent')
1199+
}
1200+
} finally {
1201+
fs.rmSync(eventProject, { recursive: true, force: true })
1202+
}
1203+
})
1204+
1205+
it('stays silent when the event names a project with no roster, even though the process cwd holds a restricted agent', async () => {
1206+
const emptyProject = fs.realpathSync.native(fs.mkdtempSync(path.join(os.tmpdir(), 'tg-event-empty-')))
1207+
try {
1208+
fs.mkdirSync(path.join(process.cwd(), '.claude', 'agents'), { recursive: true })
1209+
fs.writeFileSync(path.join(process.cwd(), '.claude', 'agents', 'cwd-only.md'), '---\nname: process-cwd-agent\ntools: Read\n---\nb')
1210+
const result = await callAgentHook('post_tool_use', { prompt: 'p', description: 'd' }, `${sessionId}-advisory-event-cwd-empty`, 'short report', emptyProject)
1211+
expect(result.hookType).toBe('pass')
1212+
} finally {
1213+
fs.rmSync(emptyProject, { recursive: true, force: true })
1214+
}
1215+
})
1216+
11841217
it('rides along with the report-cache notice on the large-prose path instead of being dropped by it', async () => {
11851218
writeRoster({ 'lean-coder.md': RESTRICTED_DEF })
11861219
const sid = `${sessionId}-advisory-large`

‎tests/subagent_stop_verdict_hosts.test.ts‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -121,7 +121,8 @@ const copilotStop = (sid: string, message: string) => ({
121121
last_assistant_message: message,
122122
})
123123

124-
const agentResult = (sid: string, text: string) => runHook(buildEvent('post_tool_use', { tool_name: 'Agent', tool_input: { prompt: 'Look into it.' }, session_id: sid, tool_response: text }))
124+
// The event names the directory the roster is read from, so a developer's own .claude/agents under the process cwd never reaches these expectations.
125+
const agentResult = (sid: string, text: string) => runHook(buildEvent('post_tool_use', { tool_name: 'Agent', tool_input: { prompt: 'Look into it.' }, session_id: sid, tool_response: text, cwd: cwdOf() }))
125126
const waitResult = (sid: string, report: string) =>
126127
runHook(buildEvent('post_tool_use', { tool_name: 'multi_agent_v1wait_agent', tool_input: { targets: ['thread-a'] }, session_id: sid, tool_response: JSON.stringify({ status: { 'thread-a': { completed: report } }, timed_out: false }) }))
127128

0 commit comments

Comments
 (0)