/**
 * `olam flywheel session-start` — emit operator-state context for the
 * SessionStart hook (4th defense layer).
 *
 * Wire shape mirrors the standalone `scripts/hooks/session-start.mjs` so
 * both surfaces are valid invocation paths:
 *   - settings.json `hooks.SessionStart` calls `olam flywheel session-start`.
 *   - Dev / Hermes / smoke-tests can run `node scripts/hooks/session-start.mjs`
 *     directly without touching the CLI.
 *
 * Contract (matches MJS verbatim):
 *   - stdout: `{}` when no state; else
 *     `{ hookSpecificOutput: { hookEventName: "SessionStart", additionalContext: "<text>" } }`
 *   - stderr: human-readable warnings only.
 *   - exit: ALWAYS 0 (fail-soft — never block session start).
 *
 * Budget: <50 ms. Reads at most 3 small files under ~/.olam/state/. No network.
 *
 * ADR: docs/decisions/051-sessionstart-hook-4th-defense.md
 */
import { readFileSync, statSync } from 'node:fs';
import { homedir } from 'node:os';
import { join } from 'node:path';
export const SESSIONSTART_HOOK_SENTINEL = 'olam-sessionstart-context-hook-v1';
const MAX_WAKE_BRIEF_BYTES = 8 * 1024;
const MAX_ACTIVE_WORLD_BYTES = 4 * 1024;
const MAX_CONFIG_BYTES = 8 * 1024;
function tryReadCapped(path, maxBytes) {
    try {
        const stat = statSync(path);
        if (!stat.isFile() || stat.size === 0)
            return null;
        if (stat.size > maxBytes) {
            process.stderr.write(`[${SESSIONSTART_HOOK_SENTINEL}] skipping ${path}: ${stat.size} bytes > ${maxBytes} cap\n`);
            return null;
        }
        return readFileSync(path, 'utf-8');
    }
    catch (err) {
        const code = err?.code;
        if (code === 'ENOENT')
            return null;
        process.stderr.write(`[${SESSIONSTART_HOOK_SENTINEL}] read failed for ${path}: ${err?.message ?? err}\n`);
        return null;
    }
}
function tryParseJson(raw, label) {
    if (raw === null)
        return null;
    try {
        return JSON.parse(raw);
    }
    catch (err) {
        process.stderr.write(`[${SESSIONSTART_HOOK_SENTINEL}] ${label} JSON parse failed: ${err?.message ?? err}\n`);
        return null;
    }
}
export function buildContextBlock(olamHome) {
    const config = tryParseJson(tryReadCapped(join(olamHome, 'config.json'), MAX_CONFIG_BYTES), 'config.json');
    const activeWorld = tryParseJson(tryReadCapped(join(olamHome, 'state', 'active-world.json'), MAX_ACTIVE_WORLD_BYTES), 'active-world.json');
    const wakeBrief = tryReadCapped(join(olamHome, 'state', 'wake-brief.md'), MAX_WAKE_BRIEF_BYTES);
    const sections = [];
    if (config && typeof config.activeWorkspace === 'string') {
        sections.push(`Active workspace: ${config.activeWorkspace}`);
    }
    if (activeWorld && typeof activeWorld === 'object') {
        const parts = [];
        if (typeof activeWorld.worldId === 'string')
            parts.push(`worldId=${activeWorld.worldId}`);
        if (typeof activeWorld.branch === 'string')
            parts.push(`branch=${activeWorld.branch}`);
        if (typeof activeWorld.repo === 'string')
            parts.push(`repo=${activeWorld.repo}`);
        if (typeof activeWorld.tier === 'string')
            parts.push(`tier=${activeWorld.tier}`);
        if (typeof activeWorld.enteredAt === 'string')
            parts.push(`enteredAt=${activeWorld.enteredAt}`);
        if (parts.length > 0)
            sections.push(`Active world: ${parts.join(', ')}`);
    }
    if (wakeBrief && wakeBrief.trim().length > 0) {
        sections.push('Most recent wake brief:\n\n' + wakeBrief.trimEnd());
    }
    if (sections.length === 0)
        return null;
    const body = sections.join('\n\n');
    return `Olam SessionStart context (${Buffer.byteLength(body, 'utf-8')} bytes):\n\n${body}`;
}
export function emitSessionStartContext(olamHome) {
    try {
        const context = buildContextBlock(olamHome);
        if (context === null) {
            process.stdout.write('{}\n');
            return;
        }
        process.stdout.write(JSON.stringify({
            hookSpecificOutput: {
                hookEventName: 'SessionStart',
                additionalContext: context,
            },
        }) + '\n');
    }
    catch (err) {
        process.stderr.write(`[${SESSIONSTART_HOOK_SENTINEL}] unexpected error: ${err?.message ?? err}\n`);
        process.stdout.write('{}\n');
    }
}
export function registerFlywheelSessionStart(parent) {
    parent
        .command('session-start')
        .description('Emit operator-state context for the SessionStart hook (4th defense layer). Reads ~/.olam/state/* and writes the additionalContext JSON to stdout. Fail-soft: always exits 0.')
        .action(() => {
        const olamHome = process.env.OLAM_HOME ?? join(homedir(), '.olam');
        emitSessionStartContext(olamHome);
        // Always exit 0 — the hook must NEVER block session start.
        process.exit(0);
    });
}
//# sourceMappingURL=session-start.js.map