import path from 'node:path';
import { runProcess, writeJsonAtomic } from '../fsx.js';
import { scanAgentTextForRecursion } from './agent-recursion-guard.js';
import { validateAgentWorkerResult } from './agent-worker-pipeline.js';
import { buildFixturePatchEnvelopes } from './agent-runner-fake.js';
import { fastModeEnv, resolveFastModePolicy } from './fast-mode-policy.js';
export async function runProcessAgent(agent, slice, opts = {}) {
    const fastPolicy = resolveFastModePolicy({ fastMode: opts.fastMode ?? agent.fast_mode, serviceTier: opts.serviceTier ?? agent.service_tier });
    const planned = opts.command ? scanCommandForRecursion(opts.command) : { ok: true, violations: [] };
    if (!planned.ok) {
        return validateAgentWorkerResult({
            mission_id: opts.missionId || opts.mission_id || '',
            agent_id: agent.id,
            session_id: agent.session_id,
            persona_id: agent.persona_id || agent.id,
            task_slice_id: slice?.id || '',
            status: 'blocked',
            backend: 'process',
            summary: 'Process backend command blocked by agent recursion guard.',
            artifacts: [],
            blockers: planned.violations.map((entry) => 'recursion:' + entry),
            unverified: [],
            writes: [],
            source_intelligence_refs: agent.source_intelligence_refs || null,
            goal_mode_ref: agent.goal_mode_ref || null
        });
    }
    if (!opts.command) {
        const patchEnvelopes = buildFixturePatchEnvelopes(agent, slice, opts);
        return validateAgentWorkerResult({
            mission_id: opts.missionId || opts.mission_id || '',
            agent_id: agent.id,
            session_id: agent.session_id,
            persona_id: agent.persona_id || agent.id,
            task_slice_id: slice?.id || '',
            status: 'done',
            backend: 'process',
            summary: 'Process backend dry run for ' + (slice?.id || agent.id) + '.',
            artifacts: [],
            blockers: [],
            unverified: ['no process command supplied'],
            writes: [],
            ...(patchEnvelopes.length ? { patch_envelopes: patchEnvelopes } : {}),
            source_intelligence_refs: agent.source_intelligence_refs || null,
            goal_mode_ref: agent.goal_mode_ref || null,
            ...(opts.emitFollowUpWorkItems ? { follow_up_work_items: [buildFixtureFollowUp(agent, slice)] } : {})
        });
    }
    const result = await runProcess(opts.command[0], opts.command.slice(1), { cwd: opts.cwd || process.cwd(), env: { ...(opts.env || {}), ...fastModeEnv(fastPolicy) }, timeoutMs: opts.timeoutMs || 30000, maxOutputBytes: 128 * 1024 });
    const report = await writeAgentProcessReport(opts.agentRoot || opts.cwd || process.cwd(), agent, 'process', {
        command: opts.command,
        service_tier: fastPolicy.service_tier,
        fast_mode: fastPolicy.fast_mode,
        env: fastModeEnv(fastPolicy),
        pid: result.pid || null,
        exit_code: result.code,
        stdout_tail: result.stdout,
        stderr_tail: result.stderr,
        stdout_bytes: result.stdoutBytes,
        stderr_bytes: result.stderrBytes,
        truncated: result.truncated,
        timed_out: result.timedOut
    });
    return validateAgentWorkerResult({
        mission_id: opts.missionId || opts.mission_id || '',
        agent_id: agent.id,
        session_id: agent.session_id,
        persona_id: agent.persona_id || agent.id,
        task_slice_id: slice?.id || '',
        status: result.code === 0 ? 'done' : 'failed',
        backend: 'process',
        summary: result.stdout.slice(-1000) || result.stderr.slice(-1000),
        artifacts: [report],
        blockers: result.code === 0 ? [] : ['process_exit_' + result.code],
        unverified: [],
        writes: [],
        source_intelligence_refs: agent.source_intelligence_refs || null,
        goal_mode_ref: agent.goal_mode_ref || null
    });
}
function buildFixtureFollowUp(agent, slice) {
    return {
        id: `${String(slice?.id || agent.id)}-process-follow-up-001`,
        title: 'Process fixture follow-up work item',
        description: 'Schema-valid follow-up generated by the process backend dry-run fixture.',
        required_persona_category: 'verifier',
        priority: 100,
        dependencies: [],
        lease_requirements: [],
        max_attempts: 1,
        reason: 'exercise process backend follow_up_work_items fixture path',
        source_agent_session_id: agent.session_id
    };
}
async function writeAgentProcessReport(root, agent, backend, report) {
    const rel = path.join(agent.session_artifact_dir || path.join('sessions', agent.id), 'agent-process-report.json');
    await writeJsonAtomic(path.join(root, rel), { schema: 'sks.agent-process-report.v1', backend, agent_id: agent.id, session_id: agent.session_id, service_tier: report.service_tier || agent.service_tier || 'fast', fast_mode: report.fast_mode !== false, ...report });
    return rel;
}
function scanCommandForRecursion(command) {
    const joined = command.map((part) => String(part)).join(' ');
    return scanAgentTextForRecursion(joined);
}
//# sourceMappingURL=agent-runner-process.js.map