#!/usr/bin/env node
// PostToolUse hook — auto-record a spawned dead-advisor subagent's agentId.
//
// Problem: persisting the agentId was a manual `resolve.sh save` step the main LLM had to
// run after spawning. LLMs drop trailing steps, so the record never landed and the next
// /dead-advisor call saw no agent and respawned a duplicate.
//
// Fix: take it off the LLM. On every Agent spawn of subagent_type dead-advisor, extract the
// agentId from the tool response and persist it via resolve.sh (single source of truth for
// the sidecar layout). Deterministic — the main thread no longer has to remember.
//
// Fail-safe: any unexpected shape/error → exit 0, record nothing.

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);
const input = p.tool_input || {};
if (String(input.subagent_type) !== 'dead-advisor') process.exit(0);

const session = String(p.session_id || '');
if (!session) process.exit(0);

// agentId lives in the tool response; tolerate object-or-string shapes.
let blob = '';
try { blob = typeof p.tool_response === 'string' ? p.tool_response : JSON.stringify(p.tool_response); } catch { process.exit(0); }
const m = blob && blob.match(/agentId["']?\s*[:=]\s*["']?([A-Za-z0-9_-]+)/);
if (!m) process.exit(0);
const agentId = m[1];

const resolve = join(homedir(), '.claude', 'skills', 'dead-advisor', 'resolve.sh');
try {
  execFileSync('bash', [resolve, 'save', session, agentId], { stdio: 'ignore', timeout: 4000 });
} catch { /* fail-safe: never break the spawn flow */ }
process.exit(0);
