#!/usr/bin/env node
// Copyright (c) 2026 Hellmai Ltd
// SPDX-License-Identifier: AGPL-3.0-only
import path from 'node:path';
import Table from 'cli-table3';
import { DelegationRegistryStore } from '@lumenflow/core';
import { createWUParser } from '@lumenflow/core/arg-parser';
import { EXIT_CODES } from '@lumenflow/core/wu-constants';
import { runCLI } from './cli-entry-point.js';
import { collectActiveSessionRecords, resolveSessionForDelegation } from './session-cross-link.js';
const LOG_PREFIX = '[mem:roster]';
const CLI_OPTIONS = {
    json: {
        name: 'json',
        flags: '--json',
        description: 'Output roster entries as JSON',
    },
    initiative: {
        name: 'initiative',
        flags: '--initiative <id>',
        description: 'Limit roster to sessions linked to an initiative',
    },
};
async function loadRoster(baseDir, initiativeId) {
    const sessions = collectActiveSessionRecords(baseDir).filter((session) => session.session_id);
    const store = new DelegationRegistryStore(path.join(baseDir, '.lumenflow', 'state'));
    let delegations = [];
    try {
        await store.load();
        delegations = store.getPendingDelegations();
    }
    catch {
        delegations = [];
    }
    const rows = sessions.map((session) => {
        const delegation = delegations.find((entry) => entry.id === session.delegation_id) ??
            delegations.find((entry) => resolveSessionForDelegation(entry, new Map([[session.wu_id, session]]))?.session_id ===
                session.session_id);
        return {
            session_id: session.session_id,
            display_name: session.display_name,
            lifecycle_role: session.lifecycle_role,
            specialty_profile: session.specialty_profile,
            current_wu: session.wu_id,
            lane: session.lane,
            last_heartbeat: session.last_heartbeat,
            delegation_id: session.delegation_id,
            initiative: delegation?.ownership_scope?.initiative_id,
        };
    });
    return initiativeId ? rows.filter((row) => row.initiative === initiativeId) : rows;
}
function printHuman(rows) {
    if (rows.length === 0) {
        console.log(`${LOG_PREFIX} No live sessions`);
        return;
    }
    const table = new Table({
        head: ['session_id', 'display_name', 'role', 'current_wu', 'lane', 'last_heartbeat'],
        wordWrap: true,
    });
    for (const row of rows) {
        table.push([
            row.session_id,
            row.display_name ?? '-',
            `${row.lifecycle_role ?? '-'}/${row.specialty_profile ?? '-'}`,
            row.current_wu,
            row.lane ?? '-',
            row.last_heartbeat ?? '-',
        ]);
    }
    console.log(table.toString());
}
export async function main() {
    const args = createWUParser({
        name: 'mem-roster',
        description: 'List live agent sessions and their role axes',
        options: [CLI_OPTIONS.json, CLI_OPTIONS.initiative],
        required: [],
    });
    const rows = await loadRoster(process.cwd(), args.initiative);
    if (args.json) {
        console.log(JSON.stringify({ entries: rows }, null, 2));
        return;
    }
    printHuman(rows);
}
if (import.meta.main) {
    void runCLI(main).catch((error) => {
        const message = error instanceof Error ? error.message : String(error);
        console.error(`${LOG_PREFIX} Error: ${message}`);
        process.exit(EXIT_CODES.ERROR);
    });
}
//# sourceMappingURL=mem-roster.js.map