#!/usr/bin/env node
// PreToolUse hook — block a DUPLICATE dead-advisor spawn; force reuse via SendMessage.
//
// Problem: even with auto-recording, the main LLM must still CHOOSE SendMessage over a fresh
// spawn. If it ignores the lookup and spawns anyway, a duplicate dead-advisor is born.
//
// Fix: when an Agent spawn of subagent_type dead-advisor is attempted AND a sidecar agentId
// already exists for this session, DENY the spawn and point to SendMessage. Reuse becomes
// enforced, not hoped-for — the LLM physically cannot create a duplicate.
//
// FAIL-OPEN: any error/parse problem → allow (exit 0). Must NEVER block a legit first spawn.
// ESCAPE: delete ~/.claude/dead-advisor-state/<session>.id to force a fresh subagent.

import { readFileSync } from 'node:fs';
import { execFileSync } from 'node:child_process';
import { homedir } from 'node:os';
import { join } from 'node:path';

function readStdin() { try { return readFileSync(0, 'utf8'); } catch { return ''; } }
let p = {};
try { p = JSON.parse(readStdin() || '{}'); } catch { process.exit(0); }

if (String(p.tool_name) !== 'Agent') process.exit(0);
if (String((p.tool_input || {}).subagent_type) !== 'dead-advisor') process.exit(0);
const session = String(p.session_id || '');
if (!session) process.exit(0);

const resolve = join(homedir(), '.claude', 'skills', 'dead-advisor', 'resolve.sh');
let existing = '';
try { existing = execFileSync('bash', [resolve, 'agent', session], { encoding: 'utf8', timeout: 4000 }).trim(); }
catch { process.exit(0); } // fail-open
if (!existing) process.exit(0); // no prior agent → allow first spawn

const reason =
  `A dead-advisor subagent already exists this session (agentId ${existing}). ` +
  `Do NOT spawn a duplicate — reuse it: SendMessage to ${existing} with your MODE: FOLLOW-UP prompt ` +
  `(TRANSCRIPT + READ RANGE + QUESTION). It keeps the accumulated context. ` +
  `To force a fresh subagent instead, delete ~/.claude/dead-advisor-state/${session}.id and retry.`;

process.stdout.write(JSON.stringify({
  hookSpecificOutput: { hookEventName: 'PreToolUse', permissionDecision: 'deny', permissionDecisionReason: reason },
}));
process.exit(0);
