mirror of
https://github.com/garrytan/gstack.git
synced 2026-11-05 08:23:59 +01:00
* security: isolate every gstack Bun entry point from the audited checkout's .env and bunfig.toml Bun auto-loads .env, .env.local and .env.<NODE_ENV> from its cwd and runs a cwd bunfig.toml preload before the program starts. gstack runs inside the repo it audits, so a committed .env could steer state roots, the claude binary or spend caps, and a bunfig preload ran arbitrary code in every bin and hook. Every bun shebang, shell and skill caller, TypeScript spawn and compiled build now disables both (--no-env-file --config=/dev/null, bunIsolationArgs(), --no-compile-autoload-dotenv/bunfig), with a ratchet and hostile-fixture regressions. Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com> * test: name the directly executed scripts in the isolation ratchet Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com> * test: follow the isolation flags in touchfiles, copy lists, recipe assertions and the harness pin Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com> * fix: keep browse/src/bun-child-config.ts unchanged so the native cookie qualification still binds Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com> * fix(windows): the empty bunfig outlives its process so the timeline hook's detached repair child can read it Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com> * v1.91.159.0 security: gstack's Bun entry points ignore the audited repo's .env and bunfig.toml (S1) Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com> * test: plan-mode render pattern accepts the isolation flags Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com> --------- Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>
216 lines
9.0 KiB
TypeScript
Executable File
216 lines
9.0 KiB
TypeScript
Executable File
#!/usr/bin/env -S bun --no-env-file --config=/dev/null
|
|
/**
|
|
* 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 { runBin } from './spawn-bin';
|
|
import { SPAWNED_CONSENT_RULE, SPAWNED_ESCAPE_SENTENCE } from './spawned-directive';
|
|
import { logHookError as sharedLogHookError } from './hook-log';
|
|
|
|
interface HookStdin {
|
|
tool_name?: string;
|
|
tool_response?: unknown;
|
|
cwd?: string;
|
|
}
|
|
|
|
function logHookError(msg: string): void {
|
|
sharedLogHookError('auq-error-fallback-hook', msg);
|
|
}
|
|
|
|
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 type SessionKind = 'spawned' | 'headless' | 'interactive' | 'unattended';
|
|
|
|
export function sessionKind(cwd?: string): SessionKind {
|
|
try {
|
|
const res = runBin('gstack-session-kind', [], {
|
|
encoding: 'utf-8',
|
|
timeout: 3000,
|
|
cwd: cwd && fs.existsSync(cwd) ? cwd : undefined,
|
|
});
|
|
const out = String(res.stdout || '').trim();
|
|
if (out === 'spawned' || out === 'headless' || out === 'interactive' || out === 'unattended') 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: SessionKind): 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':
|
|
// Self-contained carve-out (#2733 review): the "Spawned session block"
|
|
// exists in context only when a gstack preamble ran; an AUQ error
|
|
// outside a skill must still carry the destructive exception here.
|
|
return (
|
|
lead +
|
|
'SESSION_KIND=spawned — auto-choose the recommended option per the Spawned session block. ' +
|
|
'Do not emit prose, do not BLOCK. Exception: never auto-choose a destructive or ' +
|
|
'irreversible option — take the conservative non-destructive choice (skip/defer), ' +
|
|
'record it, and continue.' + SPAWNED_CONSENT_RULE
|
|
);
|
|
case 'unattended':
|
|
// Plan B1 (decision D6): a parent agent reads this run's artifacts and
|
|
// nobody answers mid-run. Recommended options are taken and logged;
|
|
// anything without a recommendation, a consent, a destructive option or
|
|
// an approval gate is a pending gate item, never an approval.
|
|
return (
|
|
lead +
|
|
'SESSION_KIND=unattended — auto-choose the `(recommended)` option and append it to decisions.jsonl ' +
|
|
'with kind "auto"; do not emit prose, do not BLOCK. A question with no recommendation, a consent, ' +
|
|
'a destructive or irreversible option, or an approval gate is appended with kind "approval" and status ' +
|
|
'"pending" — never chosen, never approved — and the skill ends at its next gate with ' +
|
|
'GSTACK_RESULT status=gate_pending (Unattended session block).'
|
|
);
|
|
case 'headless':
|
|
// #2733 review (multi-specialist): a spawned-marked subagent under a
|
|
// HEADLESS-classified parent env (CI/eval-hosted /ship) hits this branch
|
|
// — the shell-out sees the harness env, never the per-command marker.
|
|
// The self-gating escape sentence keeps the JSON contract alive there;
|
|
// plain headless sessions read its condition as false and still BLOCK.
|
|
return (
|
|
lead +
|
|
'SESSION_KIND=headless — report `BLOCKED — AskUserQuestion unavailable` and stop; no human can answer. ' +
|
|
SPAWNED_ESCAPE_SENTENCE
|
|
);
|
|
case 'interactive':
|
|
default:
|
|
// #2733: the shell-out above runs in the HARNESS env, so a subagent
|
|
// marked spawned via a per-command env prefix still classifies as
|
|
// interactive here — the escape sentence is the only lever for that
|
|
// topology (see spawned-directive.ts).
|
|
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.) ' +
|
|
SPAWNED_ESCAPE_SENTENCE
|
|
);
|
|
}
|
|
}
|
|
|
|
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();
|
|
});
|
|
}
|