Files
gstack/hosts/claude/hooks/auq-error-fallback-hook.ts
T
Garry Tan 4dfdb7cdc2 v1.57.2.0 feat: AskUserQuestion prose fallback when the tool fails at runtime (#1908)
* feat(auq): add gstack-session-kind + echo SESSION_KIND in preamble

Classifies the session as spawned | headless | interactive from env markers
(OPENCLAW_SESSION / GSTACK_HEADLESS / CONDUCTOR_* / CLAUDE_CODE_ENTRYPOINT / CI),
defaulting to interactive. Echoed once at skill start alongside BRANCH/REPO_MODE
so the AskUserQuestion-failure fallback can branch without a shell-out at failure
time. Degrade-safe: empty/error => interactive.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* feat(auq): prose fallback when AskUserQuestion fails (interactive sessions)

On a genuine AUQ failure (tool absent, or present-but-erroring like Conductor's
flaky MCP returning '[Tool result missing due to internal error]'): retry once,
then branch on SESSION_KIND — spawned auto-chooses, headless BLOCKs, interactive
renders a prose decision brief the user answers by typing a letter.

The prose fallback MUST surface the triad: a clear ELI10 of the issue, a
per-choice Completeness score, and a recommendation+why (one paragraph per
choice). Carves out the [plan-tune auto-decide] denial as NOT a failure, and
qualifies the former 'tool_use, not prose' assertions so the rule isn't
self-contradicting. Tests pin the triad, the SESSION_KIND branch, the OV2
collision guard, the always-loaded guarantee, and a cross-file invariant on the
auto-decide prefix.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* test(auq): default GSTACK_HEADLESS=1 in eval/E2E runners

Headless harness runs classify as headless (BLOCK on AUQ failure rather than
emit a prose question no one reads). SDK runner uses ambient mutation, not the
Options.env object, to avoid breaking the SDK auth pipeline. Interactive-path
suites opt out by overriding the env per-run.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* feat(auq): defensive PostToolUse error-fallback hook (OV3:B)

When an AskUserQuestion call returns an error/missing result, this hook injects
additionalContext reminding the model to run the prose fallback for the current
SESSION_KIND. It does not render prose itself — it guarantees the reminder fires
at the moment of failure instead of relying on the model recalling SESSION_KIND.

Inert on success and inert if the platform never invokes PostToolUse on tool
errors (unverified — could not force the Conductor MCP error in a harness; see
the spike doc). The prompt-level fallback covers the case regardless. Decision
logic is unit-tested deterministically; registered in setup beside the existing
AUQ hooks.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* chore(auq): regenerate SKILL.md for all hosts + refresh ship goldens

Regenerated from the resolver changes (gen:skill-docs --host all). Refreshes the
byte-exact ship golden fixtures (claude/codex/factory). Spec prose tightened so
the cross-cutting preamble addition stays under the 5% per-skill parity ceiling
(investigate 4.8%) — guard unchanged.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* fix(test): kebab testNames for section-loading E2Es to match TOUCHFILES keys

The two section-loading E2E tests used display-form testNames ('/ship
section-loading', '/plan-ceo-review section-loading') while every other E2E
testName and their E2E_TOUCHFILES keys are kebab. The completeness gate does an
exact `name in E2E_TOUCHFILES` check, so it failed (pre-existing on main); diff-
based selection also couldn't match them. Align to ship-section-loading /
plan-ceo-section-loading.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* fix(test): make external-host freshness checks deterministic

The parameterized host smoke + --host all freshness tests assumed an external
`gen:skill-docs --host all` had run first (it never does in `bun test`), so which
host reported STALE varied by sibling-test timing — flaky. Regenerate the
gitignored external host dirs in a beforeAll so the --dry-run check is
deterministic. It still catches non-deterministic generation (the real bug class
for regenerated outputs); the tracked-claude freshness test runs earlier and is
unaffected.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* test(parity): headroom for AUQ cross-cutting addition on carved document-release

Merging main brought the carve of document-release (smaller skeleton); the AUQ
prose-fallback adds ~2KB to every skill's always-loaded preamble, landing
document-release at ~5.9% over the pre-carve v1.53.0.0 baseline. Add a per-carve
maxSizeRatio override (CARVE_GUARDS single source of truth) and bump only this
skill to 1.08. All other skills keep the strict 1.05 ceiling.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* fix(auq): harden error-fallback hook + harness per adversarial review

Codex pre-landing review found three real issues:
- The PostToolUse fallback hook shared source 'plan-tune-cathedral' with the
  question-log hook (same event+matcher); gstack-settings-hook replaces the entry,
  so it would have clobbered plan-tune capture. Give it its own 'auq-error-fallback'
  source (separate entry, both run); ALREADY_INSTALLED now requires both sources.
- isErrorResponse triggered on any string containing 'internal error'/'is_error',
  so a real answer or a {"is_error": false} payload could fire the fallback after a
  successful question. Narrow it to the missing-result sentinel + boolean is_error.
- The SDK runner mutated process.env.GSTACK_HEADLESS process-wide (leaked headless
  into later tests). Removed; GSTACK_HEADLESS=1 now lives in the eval package.json
  scripts, scoped to the invocation and inherited by the SDK child.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* chore: bump version and changelog (v1.57.2.0)

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-07 21:38:21 -07:00

203 lines
7.3 KiB
TypeScript
Executable File

#!/usr/bin/env bun
/**
* PostToolUse hook for AskUserQuestion — runtime reliability layer for the
* AUQ-failure prose fallback (OV3:B).
*
* When an AskUserQuestion call comes back as an ERROR / missing result (the
* Conductor MCP bug returns `[Tool result missing due to internal error]`), this
* hook injects `additionalContext` reminding the model of the failure-fallback
* rule, tailored to the session kind. It does NOT render the prose itself — the
* model still emits it. The hook only guarantees the reminder fires at the moment
* of failure, instead of relying on the model noticing the error result and
* recalling the echoed SESSION_KIND.
*
* DEFENSIVE / INERT-IF-UNSUPPORTED: it is unverified whether Claude Code invokes
* PostToolUse hooks when an MCP tool returns a transport/missing-result error (we
* could not force that Conductor-internal failure in a harness — see
* docs/spikes/claude-code-hook-mutation.md §"PostToolUse on tool error"). If the
* platform does NOT fire the hook on that path, this is simply never invoked — no
* harm; the prompt-level fallback in generate-ask-user-format.ts still covers it.
* On a SUCCESSFUL AskUserQuestion (a real answer), the hook defers (no output).
*
* Triggered by ~/.claude/settings.json (registered by `setup` next to
* question-log-hook):
* PostToolUse matcher "(AskUserQuestion|mcp__.*__AskUserQuestion)"
*
* Invariants:
* - Always exits 0. A failing hook MUST NOT block the user's session.
* - Never triggers on a successful answer (would corrupt a normal AUQ).
* - Errors land in ~/.gstack/hook-errors.log.
*/
import * as fs from 'fs';
import * as path from 'path';
import * as os from 'os';
import { spawnSync } from 'child_process';
interface HookStdin {
tool_name?: string;
tool_response?: unknown;
cwd?: string;
}
function stateRoot(): string {
return (
process.env.GSTACK_STATE_ROOT ||
process.env.GSTACK_HOME ||
path.join(os.homedir(), '.gstack')
);
}
function logHookError(msg: string): void {
try {
const sr = stateRoot();
fs.mkdirSync(sr, { recursive: true });
fs.appendFileSync(
path.join(sr, 'hook-errors.log'),
`${new Date().toISOString()} auq-error-fallback-hook: ${msg}\n`,
);
} catch {
// last-resort swallow
}
}
function readStdin(): Promise<string> {
return new Promise((resolve) => {
let buf = '';
process.stdin.setEncoding('utf-8');
process.stdin.on('data', (chunk) => (buf += chunk));
process.stdin.on('end', () => resolve(buf));
process.stdin.on('error', () => resolve(buf));
setTimeout(() => resolve(buf), 2000);
});
}
/** No-op output — let the tool result stand untouched. */
function defer(): void {
process.stdout.write(
JSON.stringify({ hookSpecificOutput: { hookEventName: 'PostToolUse' } }),
);
process.exit(0);
}
function inject(additionalContext: string): void {
process.stdout.write(
JSON.stringify({
hookSpecificOutput: { hookEventName: 'PostToolUse', additionalContext },
}),
);
process.exit(0);
}
/**
* Decide whether the tool_response is an ERROR / missing result rather than a
* real answer. Conservative: only flag clear failure shapes, so a successful
* AskUserQuestion (which carries the user's choice) is never misread as failure.
*/
export function isErrorResponse(response: unknown): boolean {
if (response === null || response === undefined) return true;
if (typeof response === 'string') {
const s = response.trim();
if (s === '') return true;
// Match ONLY the specific missing-result sentinel phrase, not any string that
// merely contains "error" — a real answer like "Investigate the internal error"
// must NOT trigger the fallback. (Codex review finding.)
return /tool result missing/i.test(s);
}
if (typeof response === 'object') {
const rec = response as Record<string, unknown>;
// Structured flag must be the boolean true — not the substring "is_error" inside
// a serialized success payload like '{"is_error": false}'.
if (rec.is_error === true || rec.isError === true) return true;
if (typeof rec.error === 'string' && rec.error.trim() !== '') return true;
// Some hosts wrap the payload as { content: "..." } or { content: [{text}] }.
const content = rec.content;
if (typeof content === 'string') return /tool result missing/i.test(content);
if (Array.isArray(content)) {
const text = content
.map((c) => (typeof c === 'string' ? c : (c as Record<string, unknown>)?.text ?? ''))
.join(' ');
return /tool result missing/i.test(text);
}
}
return false;
}
/** Resolve SESSION_KIND via the shared helper (same classification the preamble
* echoes). Falls back to 'interactive' (degrade-safe) on any failure. */
export function sessionKind(cwd?: string): 'spawned' | 'headless' | 'interactive' {
try {
const here = path.dirname(new URL(import.meta.url).pathname);
const bin = path.resolve(here, '..', '..', '..', 'bin', 'gstack-session-kind');
const res = spawnSync(bin, [], {
encoding: 'utf-8',
timeout: 3000,
cwd: cwd && fs.existsSync(cwd) ? cwd : undefined,
});
const out = (res.stdout || '').trim();
if (out === 'spawned' || out === 'headless' || out === 'interactive') return out;
} catch (e) {
logHookError(`sessionKind failed: ${(e as Error).message}`);
}
return 'interactive';
}
/** The directive injected per session kind. Exported for unit testing. */
export function directiveFor(kind: 'spawned' | 'headless' | 'interactive'): string {
const lead =
'The AskUserQuestion call did not return a usable answer (error / missing result). ' +
'Per the AskUserQuestion failure-fallback rule: ';
switch (kind) {
case 'spawned':
return (
lead +
'SESSION_KIND=spawned — auto-choose the recommended option per the Spawned session block. ' +
'Do not emit prose, do not BLOCK.'
);
case 'headless':
return (
lead +
'SESSION_KIND=headless — report `BLOCKED — AskUserQuestion unavailable` and stop; no human can answer.'
);
case 'interactive':
default:
return (
lead +
'SESSION_KIND=interactive — render the decision as a PROSE message now: a clear ELI10 of the issue, ' +
'then a Recommendation line, then ONE paragraph per choice carrying its `(recommended)` marker, its ' +
'`Completeness: X/10`, and 2-4 sentences of reasoning. Tell the user to reply with a letter, then STOP. ' +
'(Retry the call once first only if no answer could have surfaced.)'
);
}
}
async function main(): Promise<void> {
const raw = await readStdin();
if (!raw.trim()) return defer();
let stdin: HookStdin;
try {
stdin = JSON.parse(raw);
} catch (e) {
logHookError(`stdin parse failed: ${(e as Error).message}`);
return defer();
}
const toolName = stdin.tool_name || '';
if (toolName !== 'AskUserQuestion' && !/^mcp__.+__AskUserQuestion$/.test(toolName)) {
return defer();
}
if (!isErrorResponse(stdin.tool_response)) return defer();
inject(directiveFor(sessionKind(stdin.cwd)));
}
// Only run the stdin→stdout pipeline when executed as a hook, not when imported
// by the unit test (which exercises the exported pure functions).
if (import.meta.main) {
main().catch((e) => {
logHookError(`main crash: ${(e as Error).message}`);
defer();
});
}