/**
 * olam memory start — bring up the agent-memory service.
 *
 * Phase B substrate: delegates to `MemoryServiceContainerController` so the
 * service runs as a Docker container managed by the same lifecycle as
 * kg-service / auth-service / mcp-auth-service. The legacy Phase A host-process
 * model (spawning the `agentmemory` npm bin + writing `~/.olam/memory.pid`)
 * is retired; legacy on-disk state is migrated away on first new-substrate
 * invocation via `migrateFromHostProcess()`.
 *
 * Operator-facing surface unchanged:
 *   - `olam memory start` still produces a running service on :3111.
 *   - `bootstrap.ts:429` `runOlam(['memory', 'start'])` call site untouched.
 *   - `--skip-memory` / `OLAM_BOOTSTRAP_SKIP_MEMORY=1` still skip.
 *
 * Phase C deletes the host-process helpers from `_paths.ts` + drops the
 * `@agentmemory/agentmemory` PUBLISH_DEPS entry. Until then, the host-process
 * code paths are unreachable but present (clean-revert insurance).
 *
 * Plan reference: docs/plans/memory-service-as-docker-peripheral/phase-b-tasks.md B1
 */
import { printError, printSuccess, printInfo, printHeader, printWarning } from '../../output.js';
import { MEMORY_SERVICE_PORT, MemoryServiceContainerController, } from '../memory-service-container.js';
import { migrateFromHostProcess } from '../../lib/memory-host-process-migration.js';
export async function runMemoryStart() {
    printHeader('olam memory start');
    // 1. Migrate away from any Phase A host-process state on disk. Idempotent
    //    no-op on hosts that never ran the legacy substrate. PID-reuse defence
    //    is in the helper — we never SIGTERM a process whose comm name isn't
    //    `node`.
    const migration = migrateFromHostProcess();
    if (migration.cleaned) {
        printInfo('migration', migration.summary);
    }
    // 2. Substrate handoff to MemoryServiceContainerController (Phase A A1).
    const controller = new MemoryServiceContainerController();
    const current = controller.status();
    if (current.state === 'running') {
        const ready = await controller.waitForReady(5_000);
        if (ready) {
            printSuccess(`olam-memory-service already running on :${current.port}; /agentmemory/livez ok`);
            return 0;
        }
        printWarning(`olam-memory-service container is running but /agentmemory/livez did not respond. ` +
            `Run 'olam memory stop' then retry, or 'olam memory logs' to diagnose.`);
        return 1;
    }
    if (controller.imageMissingEverywhere()) {
        printError('olam-memory-service image not found locally. ' +
            'Run `olam bootstrap` to pull the published image, or ' +
            '`node packages/cli/scripts/build-memory-service-image.mjs` to build from source.');
        return 1;
    }
    try {
        controller.start();
    }
    catch (err) {
        const errMsg = err instanceof Error ? err.message : String(err);
        const stderr = err instanceof Error && 'stderr' in err
            ? String(err.stderr ?? '').trim()
            : '';
        printError(`olam-memory-service failed to start: ${errMsg}${stderr ? `\n  stderr: ${stderr}` : ''}`);
        return 1;
    }
    const ready = await controller.waitForReady();
    if (!ready) {
        printError(`olam-memory-service started but /agentmemory/livez did not respond within 60s. ` +
            `Inspect logs with 'olam memory logs'.`);
        return 1;
    }
    printSuccess(`olam-memory-service started on :${MEMORY_SERVICE_PORT}; /agentmemory/livez ok`);
    return 0;
}
export function registerMemoryStart(cmd) {
    cmd
        .command('start')
        .description('Start the agent-memory Docker container (Phase B substrate).')
        .action(async () => {
        const exitCode = await runMemoryStart();
        process.exit(exitCode);
    });
}
//# sourceMappingURL=start.js.map