#!/usr/bin/env node
// Copyright (c) 2026 Hellmai Ltd
// SPDX-License-Identifier: AGPL-3.0-only
/**
 * Agent Session End CLI
 *
 * Ends the current agent session and returns summary.
 *
 * Usage:
 *   pnpm agent:session:end
 */
import { Command } from 'commander';
import { endSession, getCurrentSession } from '@lumenflow/agent';
import { buildAgentSessionEndedEvent, buildAgentSessionStalledEvent, } from './agent-runtime-enrollment-events.js';
import { EXIT_CODES } from '@lumenflow/core/wu-constants';
import { ProcessExitError } from '@lumenflow/core/error-handler';
import chalk from 'chalk';
import { runCLI } from './cli-entry-point.js';
import { resolveConductorEventSink } from './kernel-event-sync/lifecycle-emitters.js';
const program = new Command()
    .name('agent:session:end')
    .description('End the current agent session')
    .action(async () => {
    try {
        const session = await getCurrentSession();
        if (!session) {
            const message = 'No active session to end.';
            console.error(chalk.yellow(message));
            throw new ProcessExitError(message, EXIT_CODES.SUCCESS);
        }
        const conductorSink = await resolveConductorEventSink();
        const summary = await endSession();
        // WU-2642 (INIT-057 Phase 4): Stop the control-plane sync sidecar
        // spawned at session start so file watchers / interval timers don't
        // leak past session-end.
        try {
            const { stopControlPlaneSidecar } = await import('./sidecar-manager.js');
            const sidecarResult = await stopControlPlaneSidecar({
                workspaceRoot: process.cwd(),
                logger: {
                    warn: (message) => console.warn(chalk.yellow(`[agent:session:end] ${message}`)),
                },
            });
            if (sidecarResult.stopped) {
                console.log(chalk.dim(`  Stopped sidecar (pid=${sidecarResult.pid})`));
            }
        }
        catch (err) {
            const message = err instanceof Error ? err.message : String(err);
            console.warn(chalk.yellow(`Warning: could not stop control-plane sync sidecar: ${message}`));
            conductorSink(buildAgentSessionStalledEvent({
                session_id: session.session_id,
                wu_id: session.wu_id,
                lane: session.lane,
                stage: 'sidecar_stop',
                reason: message,
            }));
        }
        conductorSink(buildAgentSessionEndedEvent({
            session_id: summary.session_id,
            wu_id: summary.wu_id,
            lane: summary.lane,
            incidents_logged: summary.incidents_logged,
            incidents_major: summary.incidents_major,
        }));
        console.log(chalk.green(`✓ Session ended`));
        console.log(`  WU: ${chalk.cyan(summary.wu_id)}`);
        console.log(`  Lane: ${chalk.cyan(summary.lane)}`);
        console.log(`  Duration: ${chalk.cyan(summary.started)} → ${chalk.cyan(summary.completed)}`);
        console.log(`  Incidents: ${summary.incidents_logged} (${summary.incidents_major} major)`);
        // WU-2754 (ADR-014 extension 2): persist final role state so the operator
        // can see which lifecycle_role + specialty_profile the session ran as.
        if (summary.lifecycle_role) {
            console.log(`  Lifecycle role: ${chalk.cyan(summary.lifecycle_role)}`);
        }
        if (summary.specialty_profile) {
            console.log(`  Specialty profile: ${chalk.cyan(summary.specialty_profile)}`);
        }
        if (summary.delegation_id) {
            console.log(`  Delegation: ${chalk.cyan(summary.delegation_id)}`);
        }
    }
    catch (err) {
        if (err instanceof ProcessExitError) {
            throw err;
        }
        const message = err instanceof Error ? err.message : String(err);
        console.error(chalk.red(`Error: ${message}`));
        throw new ProcessExitError(message, EXIT_CODES.ERROR);
    }
});
export async function main() {
    await program.parseAsync(process.argv);
}
if (import.meta.main) {
    void runCLI(main);
}
//# sourceMappingURL=agent-session-end.js.map