Repository navigation
Expand file tree
/
Copy pathhooks_tool_failure.ts
More file actions
410 lines (352 loc) · 25.4 KB
/
Copy pathhooks_tool_failure.ts
File metadata and controls
410 lines (352 loc) · 25.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
/** `post_tool_use_failure` handler -- the repeat-failure brake. Two harnesses route a *failed* tool result here instead of to their ordinary post-tool event. Claude Code sends `PostToolUseFailure` with `error`, `is_interrupt` and `duration_ms` (captured on 2.1.281: a missing-file Read and a non-zero Bash exit both arrive here, never on PostToolUse), and its `additionalContext` reached the model in the same capture. Copilot CLI routes one to its own `postToolUseFailure` hook instead of `postToolUse`, and that hook accepts only `additionalContext`: `modifiedResult` is documented as not honored there and the bundle agrees, so a failed tool result cannot be fenced, compressed or shrunk on Copilot the way a successful one can. What the event *can* do is confirmed rather than assumed -- Copilot CLI 1.0.80, app.js offset 2043380 either folds `additionalContext` into `textResultForLlm` or pushes `{content, source:'system'}` onto `toolResult.newMessages`, so the text does reach the model. That makes this the one handler in token-goat whose channel *adds* tokens instead of removing them, and it is written accordingly: it is silent unless staying silent is more expensive than speaking. The only case that clears that bar is a repeat -- the same tool failing with the same error a second time, which is the model about to spend another whole tool call re-learning what it already knows. One short line costs ~25 tokens; the retry it prevents costs the call plus its failure text. So the first failure of any signature returns `pass` and writes nothing to the model, the second returns the line, and every later one returns `pass` again -- a signature is advised at most once per session, because a model that ignored the note will ignore it twice. Every failure is classified first (tool_error_class.ts) and recorded as one `tool_failure` stat, and a reason in {@link REPEAT_NOTICE_EXEMPT} never gets the line. State is a per-session sidecar, the same mechanism `pending_context.ts` uses, and every read and write is fail-soft: a hook that cannot persist its ledger must still return a valid response. */
import { createHash } from 'node:crypto'
import { existsSync, readFileSync, statSync, writeFileSync } from 'node:fs'
import { dirname, relative } from 'node:path'
import { callStreakAfterFailure } from './call_streak.js'
import { registerHook, type HookEvent } from './hook_registry.js'
import type * as EditNearMiss from './edit_near_miss.js'
import { buildLineIndex, offsetToLine } from './languages/common.js'
import { enqueueNonHeadMovingRewrites, extractCommand, resolveBashCall, unwrapCompressCommand, writeScopeFor } from './hooks_bash_commands.js'
import { noteFailedVerificationHandler } from './hooks_verification.js'
import { applyHintTracking, uncorrelatedHint } from './hint_stats.js'
import { contextOutput, getCwd, getFilePath, getToolInput, getToolName, passOutput, resolveEventPath } from './hooks_common.js'
import { displaySafeText, hostPathOfIndexKey, normalizePath } from './paths.js'
import { redactSecrets } from './secret_redact.js'
import { ensureDirSync } from './util.js'
import { sessionSidecarPath } from './session_store.js'
import { takeBashStartCwd } from './session.js'
import { diagnoseSqlFailure } from './session_store_schema.js'
import { recordStat } from './stats.js'
import { classifyToolError } from './tool_error_class.js'
import type { HookOutput } from './types.js'
const FAILURE_SUFFIX = '.tool-failures'
/** Signatures tracked per session before the oldest is dropped. A ledger is only ever consulted for membership, so the cap bounds the file rather than the usefulness: a session that has produced 64 distinct tool failures is not one where remembering the 65th changes an outcome. */
export const MAX_TRACKED_FAILURES = 64
/** Truncation point for the error text inside a signature. */
const SIGNATURE_ERROR_CHARS = 200
/** Bumped when the stored shape changes meaning. A file without this number, or with another, is an older writer's and is dropped unread: the first version stored the failure text itself, not its digest, so reading one back would keep text that may hold a secret. */
const LEDGER_VERSION = 2
interface FailureLedger {
/** Signature -> whether the advisory has already been emitted for it. */
seen: Record<string, boolean>
/** Insertion order, oldest first, so the cap can evict deterministically. */
order: string[]
}
/** Collapse a failed call to a signature that is stable across a retry but distinct across a genuinely different failure. Whitespace is squeezed and the text truncated because the same underlying error frequently arrives with a different wrapping, and a signature that changes on every occurrence would never match itself. */
export function failureSignature(toolName: string | undefined, errorText: string): string {
const tool = toolName === undefined || toolName === '' ? 'unknown' : toolName
const normalized = errorText.replace(/\s+/g, ' ').trim().slice(0, SIGNATURE_ERROR_CHARS)
return `${tool} :: ${normalized}`
}
/** Pull the failure text out of the raw event. Copilot's `PostToolUseFailureHookInput` carries a stringified error rather than the tool result, and the field name is not stable across the shapes token-goat's own bridges emit, so several are accepted. Returns '' when none is present, which the caller treats as "nothing to key on". */
export function extractFailureText(raw: Record<string, unknown>): string {
for (const key of ['error', 'errorMessage', 'tool_error', 'toolError', 'message', 'reason']) {
const value = raw[key]
if (typeof value === 'string' && value.trim() !== '') return value
}
const response = raw['tool_response'] ?? raw['toolResponse']
if (typeof response === 'string' && response.trim() !== '') return response
if (response !== null && typeof response === 'object') {
const nested = (response as Record<string, unknown>)['error']
if (typeof nested === 'string' && nested.trim() !== '') return nested
}
return ''
}
function ledgerPath(sessionId: string): string | null {
return sessionSidecarPath(sessionId, FAILURE_SUFFIX)
}
function readLedger(target: string): FailureLedger {
try {
const parsed: unknown = JSON.parse(readFileSync(target, 'utf8'))
if (parsed !== null && typeof parsed === 'object') {
if ((parsed as { version?: unknown }).version !== LEDGER_VERSION) return { seen: {}, order: [] }
const seen = (parsed as FailureLedger).seen
const order = (parsed as FailureLedger).order
if (seen !== null && typeof seen === 'object' && Array.isArray(order)) {
return { seen: seen as Record<string, boolean>, order: order.filter((k) => typeof k === 'string') }
}
}
} catch {
// Missing, unreadable or corrupt: start a fresh ledger rather than fail the hook.
}
return { seen: {}, order: [] }
}
function writeLedger(target: string, ledger: FailureLedger): void {
try {
ensureDirSync(dirname(target))
writeFileSync(target, JSON.stringify({ version: LEDGER_VERSION, ...ledger }), 'utf8')
} catch {
// Best-effort: a ledger that cannot be stored degrades to "every failure looks like the first", which is the silent direction, never a spurious advisory.
}
}
/** Failure reasons ({@link classifyToolError}) the repeat notice is withheld for, because it would be wrong for them. Two grounds, each from the 2026-09-24 transcript census behind tool_error_class.ts (row and repeat counts taken over the census copy of each result, clipped to 400 characters, so a row count can differ by a few from the report), with "repeats" meaning a later failure in the same transcript carrying the same {@link failureSignature}: either the failure is a refusal or a stop whose own text is what the model should act on, or its wording is generic enough that a repeated signature almost never came from a re-sent call, so "retrying it unchanged" was false every time it would have fired. */
export const REPEAT_NOTICE_EXEMPT: ReadonlySet<string> = new Set([
// Refusals and stops. Claude Code never delivers a refused call to this event (a PreToolUse deny fired no PostToolUseFailure in a 2.1.281 capture), so these guard the other harnesses that route failures here.
'interrupted', // the payload's is_interrupt flag; the census has 0 rows because an interrupt never surfaces as an is_error result
'tg_deny', // 2,762 rows, 283 repeats, 13 with the same input: the deny names the command to run instead
'tg_content_delivered', // a deny whose text is the content (a Skill's compact slice or heading tree, a served Read sidecar): the call did its job, so there is nothing to retry
'hook_deny', // 5 rows: another hook's refusal, with its own instruction
'user_rejected', // 73 rows, 21 repeats, 1 with the same input
'auto_mode_blocked', // 1 row
// Generic wording: a repeat was a different call that failed the same way.
'search_no_match', // 99 repeats, 0 with the same input: every empty grep prints the same bare `Exit code 1`
'command_timeout', // 41 repeats, 0 with the same input
'subagent_limit', // 27 repeats, 1 with the same input; the harness's own text already says not to retry
'input_validation', // 23 repeats, 0 with the same input
])
/** The advisory itself. Deliberately one line: it rides alongside a failure the model must read anyway. */
export function repeatFailureNotice(toolName: string | undefined): string {
// A tool name is not our text: an MCP server chooses the names it advertises, and this notice is delivered in token-goat's own voice, so a server naming a tool after our own marker would otherwise speak through us.
const tool = toolName === undefined || toolName === '' ? 'This tool' : displaySafeText(toolName)
return `[token-goat] ${tool} just failed with the same error as an earlier call this session. Retrying it unchanged will fail the same way -- change the arguments, the tool, or the approach.`
}
/** The near-miss finder (edit_near_miss.ts, with the secret-name list under it), loaded by {@link postToolUseFailureWithExtras} only for a failed edit tool call so the hook entry does not parse it on every tool call. Until it is loaded {@link diagnoseEditFailure} skips the near-miss rung and gives the older advice, so a caller that wants the near-miss answer awaits {@link loadNearMiss} first. */
let nearMissLib: typeof EditNearMiss | undefined
/** Load the near-miss module for {@link diagnoseEditFailure}. A load failure leaves it unloaded, which is the older-advice path rather than an error. */
export async function loadNearMiss(): Promise<void> {
try {
nearMissLib ??= await import('./edit_near_miss.js')
} catch {
// The near-miss rung is an extra; the older edit advice still answers.
}
}
/** Maximum file size (10 MB) to inspect on an edit failure to avoid memory stalls. */
const MAX_EDIT_DIAGNOSE_BYTES = 10 * 1024 * 1024
/** Every `old_string` an edit tool call carried: the single key under any host's spelling (Claude Code `old_string`, Copilot CLI `old_str`, a bare `target`, Antigravity `TargetContent`), then each `edits[]` entry of a MultiEdit. Empty strings are dropped, since they match everywhere. */
function editOldStrings(event: HookEvent): string[] {
const input = event.toolInput
const out: string[] = []
for (const key of ['old_string', 'old_str', 'target', 'TargetContent']) {
const value = input[key]
if (typeof value === 'string' && value !== '') {
out.push(value)
break
}
}
const edits = input['edits']
if (Array.isArray(edits)) {
for (const entry of edits) {
const value = entry !== null && typeof entry === 'object' ? (entry as Record<string, unknown>)['old_string'] : undefined
if (typeof value === 'string' && value !== '') out.push(value)
}
}
return out
}
/** Inspect an Edit tool failure and generate actionable, surgical guidance. When an agent fails an edit because `old_string` matches multiple locations or zero locations, the raw harness error ("Multiple matches found") provides no line numbers or context, causing blind retry loops. This helper inspects the file on disk to report the exact match counts and line numbers so the agent can disambiguate immediately. */
export function diagnoseEditFailure(event: HookEvent, errorText: string): string | null {
const toolName = getToolName(event)
if (!toolName || !/^(edit|multiedit|str_replace_editor)$/i.test(toolName)) {
return null
}
const isMultiple =
/multiple matches|not unique|found \d+ matches|matches \d+ times|more than one match/i.test(errorText)
const isNotFound =
/no match|not found|could not find|zero matches|string to replace.*not found/i.test(errorText)
if (!isMultiple && !isNotFound) {
return null
}
const fallbackPath = ['path', 'TargetFile'].map((key) => event.toolInput[key]).find((value): value is string => typeof value === 'string' && value !== '')
const filePath = getFilePath(event) ?? (fallbackPath === undefined ? undefined : resolveEventPath(event, fallbackPath))
if (!filePath) return null
const oldStrings = editOldStrings(event)
if (oldStrings.length === 0) return null
const absPath = hostPathOfIndexKey(normalizePath(filePath))
if (!existsSync(absPath)) return null
try {
const stat = statSync(absPath)
if (stat.size > MAX_EDIT_DIAGNOSE_BYTES) return null
const fileContent = readFileSync(absPath, 'utf8')
// A MultiEdit names several old strings and the error text may not say which one failed, so take the first one the file cannot explain: absent for a not-found, repeated for a multiple-match.
const oldString = oldStrings.length === 1 ? oldStrings[0] : oldStrings.find((candidate) => (isNotFound ? !fileContent.includes(candidate) : fileContent.indexOf(candidate) !== fileContent.lastIndexOf(candidate)))
if (oldString === undefined) return null
const relDisplay = displaySafeText(relative(process.cwd(), absPath).replace(/\\/g, '/') || absPath)
if (isMultiple) {
const matchLines: number[] = []
// One index over the file, reused by every match. Placing a match by slicing from character 0 and counting newlines costs the whole file per match, which is quadratic in the number of matches: a one-character `old_string` occurring 100,000 times in a 2 MB file took 1.7 s, and the cap above admits 10 MB. This runs inside a hook, so that time is paid by the harness before it can report a failed edit.
const lineIndex = buildLineIndex(fileContent)
let pos = 0
while (pos < fileContent.length) {
const idx = fileContent.indexOf(oldString, pos)
if (idx === -1) break
matchLines.push(offsetToLine(lineIndex, idx))
pos = idx + Math.max(1, oldString.length)
}
if (matchLines.length > 1) {
const lineList = matchLines.slice(0, 5).join(', ')
const overflow = matchLines.length > 5 ? ` (+${matchLines.length - 5} more)` : ''
return `[token-goat] Edit failed: string matched ${matchLines.length} times in ${relDisplay} on lines ${lineList}${overflow}. Include 2-3 lines of surrounding context to make old_str unique.`
}
}
if (isNotFound) {
const normOld = oldString.replace(/\r\n/g, '\n')
const normFile = fileContent.replace(/\r\n/g, '\n')
if (normFile.includes(normOld)) {
return `[token-goat] Edit failed: string not found in ${relDisplay}, but matches with normalized line endings. Check CRLF vs LF line endings or whitespace.`
}
const nearMiss = nearMissLib?.findNearMiss(fileContent, oldString) ?? null
const nearAdvice = nearMiss === null ? null : nearMissLib?.describeNearMiss(fileContent, relDisplay, nearMiss) ?? null
if (nearAdvice !== null) return nearAdvice
const firstLine = oldString.split(/\r?\n/)[0]?.trim() ?? ''
if (firstLine.length >= 10) {
const fileLines = fileContent.split('\n')
const similarLines: number[] = []
for (let i = 0; i < fileLines.length; i++) {
const lineText = fileLines[i]
if (lineText !== undefined && lineText.includes(firstLine)) {
similarLines.push(i + 1)
if (similarLines.length >= 3) break
}
}
if (similarLines.length > 0) {
return `[token-goat] Edit failed: string not found in ${relDisplay}. A similar line was found on line ${similarLines.join(', ')} — view that range to copy exact text.`
}
}
return `[token-goat] Edit failed: string not found in ${relDisplay}. View the target lines to copy the exact current content and indentation.`
}
} catch {
// Non-fatal if file reading or parsing fails
}
return null
}
/** The context answer for an edit diagnostic. Only a near-miss diagnostic (edit_near_miss.ts) is logged as a hint: the older advice carries no new information the hint ledger could judge. */
function editAdviceOutput(event: HookEvent, text: string): HookOutput {
const out = contextOutput(text)
return nearMissLib?.isNearMissAdvice(text) === true ? applyHintTracking(event, out, uncorrelatedHint('edit_near_miss')) : out
}
/** Reasons a failed Bash command opens no recovery pair, beyond {@link REPEAT_NOTICE_EXEMPT}: a syntax error or a blocked sleep is fixed by rewriting the command, so the fix is a different C rather than something run in between. */
const RECOVERY_SKIPPED: ReadonlySet<string> = new Set(['shell_syntax_error', 'sleep_blocked'])
/** What a failed call needs from the modules {@link postToolUseFailureWithExtras} loads on demand. */
interface ExtrasRequest {
readonly toolName: string | undefined
readonly errorText: string
}
interface AdviceSlot {
lines: string[]
recovery: (ExtrasRequest & { command: string }) | null
pathMiss: ExtrasRequest | null
}
function newSlot(): AdviceSlot {
return { lines: [], recovery: null, pathMiss: null }
}
function withExtraLines(base: HookOutput, lines: readonly string[]): HookOutput {
if (lines.length === 0) return base
const extra = lines.join('\n')
if (base.hookType === 'context') return contextOutput([base.context, extra].join('\n'), base.correlators)
return base.hookType === 'pass' ? contextOutput(extra) : base
}
/** The failure handler's answer without the two lines that need a module of their own: the failed-command recovery line (recovery_pairs.ts) and the missing-path suggestion (path_miss.ts). {@link postToolUseFailureWithExtras}, the registered handler, adds both. */
export function postToolUseFailureHandler(event: HookEvent): HookOutput {
return adviseOnFailure(event, newSlot())
}
/** {@link postToolUseFailureHandler} plus the recovery line and the missing-path suggestion, each appended to whatever it says. {@link adviseOnFailure}, which knows the classification, records what each needs in `slot`; the modules are imported here only when asked for, because recovery_pairs.ts and path_miss.ts (with the index reader under it) would otherwise be parsed by the hook entry on every tool call. */
export async function postToolUseFailureWithExtras(event: HookEvent): Promise<HookOutput> {
const slot = newSlot()
const toolName = getToolName(event)
if (toolName !== undefined && /^(edit|multiedit|str_replace_editor)$/i.test(toolName)) await loadNearMiss()
const base = adviseOnFailure(event, slot)
try {
if (slot.recovery !== null) {
const { recoveryAfterFailure } = await import('./recovery_pairs.js')
const recovery = recoveryAfterFailure(event, { command: slot.recovery.command, errorText: slot.recovery.errorText })
if (recovery !== null) slot.lines.push(recovery)
}
if (slot.pathMiss !== null) {
const { pathMissAfterFailure } = await import('./path_miss.js')
const pathMiss = pathMissAfterFailure(event, slot.pathMiss)
if (pathMiss !== null) slot.lines.push(pathMiss)
}
} catch {
// The two lines are extras; a failure to produce one leaves the advice already computed.
}
return withExtraLines(base, slot.lines)
}
function adviseOnFailure(event: HookEvent, slot: AdviceSlot): HookOutput {
try {
const errorText = extractFailureText(event.raw)
if (errorText === '') return passOutput()
const toolName = getToolName(event)
const executed = getToolInput(event)['command']
// A command the pre-hook rewrote into a `token-goat compress` wrapper arrives here as that wrapper, so classify the command inside it: otherwise every wrapped grep that found nothing reads as an unknown failure.
const command = typeof executed === 'string' ? (unwrapCompressCommand(executed) ?? executed) : executed
const verdict = classifyToolError(toolName, errorText, { isInterrupt: event.raw['is_interrupt'] === true, ...(typeof command === 'string' ? { command } : {}) })
recordStat('tool_failure', 0, 0, undefined, `tool=${(toolName ?? 'unknown').replace(/\s+/g, '_')} class=${verdict.kind} reason=${verdict.reason}`)
// Only a `search_no_match` can produce a line here, and that reason is exempt below, so the brake never competes with the repeat notice.
const streakLine = callStreakAfterFailure(event, verdict.reason)
if (toolName === 'Bash' && typeof command === 'string' && event.raw['is_interrupt'] !== true && !REPEAT_NOTICE_EXEMPT.has(verdict.reason) && !RECOVERY_SKIPPED.has(verdict.reason)) {
slot.recovery = { toolName, errorText, command }
}
if (verdict.reason === 'path_not_found' && event.raw['is_interrupt'] !== true) {
slot.pathMiss = { toolName, errorText }
}
if (REPEAT_NOTICE_EXEMPT.has(verdict.reason)) return streakLine ?? passOutput()
if (!event.sessionId) return passOutput()
const target = ledgerPath(event.sessionId)
if (target === null) return passOutput()
// Redact before the signature is derived, not after: this signature is the object the ledger persists to disk (writeLedger below), and a tool failure's error text is externally sourced (shell stderr, an MCP tool's own error, a fetch failure) and can carry a credential the failing call happened to echo back. Then kept only as a digest: redaction knows credential shapes, not an argument the shell printed back, so the text itself never reaches the ledger.
const signature = createHash('sha256').update(failureSignature(toolName, redactSecrets(errorText).text)).digest('hex')
const ledger = readLedger(target)
const priorState = ledger.seen[signature]
const editDiagnostic = diagnoseEditFailure(event, errorText)
const sqlDiagnostic = diagnoseSqlFailure(event, errorText)
if (priorState === undefined) {
// First time this exact failure has been seen: record it.
ledger.seen[signature] = false
ledger.order.push(signature)
while (ledger.order.length > MAX_TRACKED_FAILURES) {
const evicted = ledger.order.shift()
if (evicted !== undefined) delete ledger.seen[evicted]
}
writeLedger(target, ledger)
// If this is an actionable edit failure (e.g. multiple matches or not found), advise immediately on the first occurrence so the agent does not enter a blind retry loop.
if (editDiagnostic !== null) {
ledger.seen[signature] = true
writeLedger(target, ledger)
return editAdviceOutput(event, editDiagnostic)
}
// If this is an actionable SQL column/table error, advise immediately with valid schema.
if (sqlDiagnostic !== null) {
ledger.seen[signature] = true
writeLedger(target, ledger)
return contextOutput(sqlDiagnostic)
}
return passOutput()
}
if (priorState) return passOutput() // Already advised once; repeating it just costs tokens.
ledger.seen[signature] = true
writeLedger(target, ledger)
if (editDiagnostic !== null) {
return editAdviceOutput(event, editDiagnostic)
}
if (sqlDiagnostic !== null) {
return contextOutput(sqlDiagnostic)
}
return contextOutput(repeatFailureNotice(toolName))
} catch {
return passOutput()
}
}
/** The status line Claude Code puts first in a failed shell call's `error` (https://code.claude.com/docs/en/hooks.md, PostToolUseFailure input), or 1 when there is none, since a call that reached this event did not succeed and a script can write before it fails. */
function failedShellExitCode(raw: Record<string, unknown>): number {
const match = /^Exit code (-?\d+)/.exec(extractFailureText(raw))
const code = match === null ? 1 : Number(match[1])
return code === 0 ? 1 : code
}
/** A failed Bash or PowerShell call goes through the same shell-write pass a successful one does (postBashHandler), since a script that wrote files and then exited non-zero reaches only this event on Claude Code. Always passes: it only queues. */
export async function shellWriteAfterFailureHandler(event: HookEvent): Promise<HookOutput> {
try {
const reported = extractCommand(event)
if (reported === undefined) return passOutput()
const toolUseId = event.raw['tool_use_id']
const startCwd = (typeof toolUseId === 'string' && toolUseId !== '' ? takeBashStartCwd(toolUseId) : null) ?? getCwd(event) ?? null
const { rawCmd, cmd, runDir } = resolveBashCall(reported, startCwd)
await enqueueNonHeadMovingRewrites(cmd, writeScopeFor(rawCmd, runDir ?? process.cwd(), startCwd ?? process.cwd()), failedShellExitCode(event.raw))
} catch {
// A queueing failure must never turn a tool failure into a hook failure.
}
return passOutput()
}
// Registered ahead of the other failure handlers: one that answers with advice ends the run before a later handler is reached.
registerHook('post_tool_use_failure', shellWriteAfterFailureHandler, { toolName: 'Bash', advisory: true })
registerHook('post_tool_use_failure', shellWriteAfterFailureHandler, { toolName: 'PowerShell', advisory: true })
registerHook('post_tool_use_failure', noteFailedVerificationHandler, { advisory: true })
registerHook('post_tool_use_failure', postToolUseFailureWithExtras)