#!/usr/bin/env node
import { constants, realpathSync } from "node:fs";
import fs from "node:fs/promises";
import path from "node:path";
import { fileURLToPath } from "node:url";
import { AGENT_CLI_MAP_HUMAN_DOC, POLICY_APPROVAL_HUMAN_DOC, POLICY_APPROVAL_TWO_LANES_DOC, appendPolicyTrace, parsePolicyApprovalFromEnv, resolveActorWithFallback } from "./core/policy.js";
import { buildAgentInstructionSurface } from "./core/agent-instruction-surface.js";
import { runWorkspaceConfigCli } from "./core/config-cli.js";
import { handleRunCommand } from "./cli/run-command.js";
import { collectPluginDoctorSummaryLines, collectPolicyLaneEnvDoctorSummaryLines, collectTaskPersistenceDoctorSummaryLines } from "./cli/doctor-planning-issues.js";
import { collectCaeDoctorSummaryLines } from "./cli/doctor-cae.js";
import { collectDoctorContractIssues, collectDoctorRuntimeContractStatus } from "./cli/doctor-contract-validation.js";
import { collectMaintainerDeliveryLoopIssues, formatMaintainerDeliveryLoopAdvisoryLines } from "./cli/doctor-delivery-loop.js";
import { ModuleRegistryError } from "./core/module-registry.js";
import { loadWorkspaceDotenv } from "./core/load-workspace-dotenv.js";
import { resolveRegistryAndConfig } from "./core/module-registry-resolve.js";
import { defaultRegistryModules } from "./modules/index.js";
import { CANONICAL_KIT_NAME, defaultWorkspaceKitPaths } from "./cli/default-workspace-kit-paths.js";
import { currentOwnedPaths, pointerRuleContent, profileSchemaContent } from "./cli/profile-baseline-content.js";
import { createDriftExpectedAssets, driftContentMatches, generateProfileDrivenArtifacts, parseJsonFile, readCliBundledPackageVersion, readOwnedPathsDocument, resolvePackageVersion, toJsonWithTrailingNewline, validateProfile, writeFileWithBackupIfChanged } from "./cli/profile-support.js";
import { runWorkspaceKitInitCommand } from "./cli/init-command.js";
import { runRefreshContextCommand } from "./cli/refresh-context-command.js";
import { runWorkspaceKitStartCommand } from "./cli/start-command.js";
import { WORKSPACE_KIT_RUNTIME_LAUNCHER_RELATIVE_PATH, WORKSPACE_KIT_RUNTIME_STAMP_RELATIVE_PATH, generateWorkspaceKitLauncherContent, readRuntimeStamp, verifyRuntimeStamp } from "./core/runtime-contract.js";
export { defaultWorkspaceKitPaths } from "./cli/default-workspace-kit-paths.js";
export { parseJsonFile } from "./cli/profile-support.js";
const EXIT_SUCCESS = 0;
const EXIT_VALIDATION_FAILURE = 1;
const EXIT_USAGE_ERROR = 2;
const EXIT_INTERNAL_ERROR = 3;
async function requireCliPolicyApproval(cwd, operationId, commandLabel, writeError) {
    const approval = parsePolicyApprovalFromEnv(process.env);
    if (!approval) {
        writeError(`workspace-kit ${commandLabel} (${operationId}) requires WORKSPACE_KIT_POLICY_APPROVAL with JSON {"confirmed":true,"rationale":"..."} (env lane). Sensitive workspace-kit run commands use JSON policyApproval instead — see ${POLICY_APPROVAL_TWO_LANES_DOC}.`);
        await appendPolicyTrace(cwd, {
            timestamp: new Date().toISOString(),
            operationId,
            command: commandLabel,
            actor: await resolveActorWithFallback(cwd, {}, process.env),
            allowed: false,
            message: "missing WORKSPACE_KIT_POLICY_APPROVAL"
        });
        return null;
    }
    return { rationale: approval.rationale };
}
async function recordCliPolicySuccess(cwd, operationId, commandLabel, rationale, commandOk) {
    await appendPolicyTrace(cwd, {
        timestamp: new Date().toISOString(),
        operationId,
        command: commandLabel,
        actor: await resolveActorWithFallback(cwd, {}, process.env),
        allowed: true,
        rationale,
        commandOk
    });
}
function writeDoctorFailureRemediation(writeError, issues) {
    writeError("");
    writeError("Next steps:");
    const hasMissing = issues.some((issue) => issue.reason === "missing");
    const hasRuntimeIssue = issues.some((issue) => issue.reason.startsWith("runtime-"));
    const manifestMissing = issues.some((issue) => issue.reason === "missing" && issue.path === defaultWorkspaceKitPaths.manifest);
    if (manifestMissing) {
        writeError("  - Repository not attached yet: run `workspace-kit init` (preview with `workspace-kit init --dry-run`).");
    }
    else if (hasMissing) {
        writeError("  - Partial attach detected: run `workspace-kit init` to repair missing baseline files (preview with `workspace-kit init --dry-run`); use `workspace-kit upgrade` after package updates.");
    }
    if (hasRuntimeIssue) {
        writeError("  - Runtime contract drift: repair setup, then run `workspace-kit init --force` to regenerate the runtime stamp and launcher.");
    }
    writeError("  - workspace-kit --help — orientation and top-level commands");
    writeError("  - workspace-kit run — list module commands (after doctor passes)");
    const rowMissing = issues.some((issue) => issue.reason === "kit-workspace-status-row-missing");
    if (rowMissing) {
        writeError("  - kit_workspace_status row missing (SQLite v10+): repair planning DB or re-run kit migrations; see `.ai/runbooks/workspace-status-sqlite.md` and `docs/maintainers/runbooks/task-persistence-operator.md`.");
    }
    const planningSqlite = issues.some((issue) => issue.reason.includes("sqlite-") ||
        issue.path.includes("workspace-kit.db") ||
        issue.path === "better-sqlite3");
    if (planningSqlite) {
        writeError("  - Planning SQLite: run `pnpm exec wk run backup-planning-sqlite '{\"outputPath\":\".workspace-kit/backups/planning-pre-repair.db\"}'` then `pnpm exec wk run task-persistence-readiness '{}'` before manual DB repair — docs/maintainers/runbooks/task-persistence-operator.md");
    }
}
function doctorWantsMachineJson(doctorRest) {
    for (let i = 0; i < doctorRest.length; i++) {
        const t = doctorRest[i];
        if (t === "--json" || t === "-j")
            return true;
        if (t === "--format" && doctorRest[i + 1] === "json")
            return true;
        if (t.startsWith("--format=") && t.slice("--format=".length) === "json")
            return true;
    }
    return false;
}
async function isExecutable(filePath) {
    try {
        await fs.access(filePath, constants.X_OK);
        return true;
    }
    catch {
        return false;
    }
}
function runtimeStampDriftFindings(cwd) {
    const read = readRuntimeStamp(cwd);
    if (!read.ok) {
        return read.issues.map((issue) => `${WORKSPACE_KIT_RUNTIME_STAMP_RELATIVE_PATH}: ${issue.code}`);
    }
    const verification = verifyRuntimeStamp(read.stamp, {
        currentIdentity: read.stamp,
        checkNativeSqlite: false
    });
    return verification.issues.map((issue) => `${WORKSPACE_KIT_RUNTIME_STAMP_RELATIVE_PATH}: ${issue.code}`);
}
function parseDetachArgv(argv) {
    return {
        dryRun: argv.includes("--dry-run"),
        json: argv.includes("--json") || argv.includes("--format=json")
    };
}
async function runWorkspaceKitDetachCommand(cwd, argv, writeLine, writeError) {
    const flags = parseDetachArgv(argv);
    const ownedPathsDocument = await readOwnedPathsDocument(cwd);
    const ownedPaths = [...new Set(ownedPathsDocument.ownedPaths)].sort();
    const plan = {
        dryRun: flags.dryRun,
        deletionEnabled: false,
        ownedPaths,
        pathCount: ownedPaths.length,
        ownershipPolicyPath: defaultWorkspaceKitPaths.ownedPaths
    };
    if (!flags.dryRun) {
        if (flags.json) {
            writeLine(JSON.stringify({
                ok: false,
                code: "detach-preview-only",
                schemaVersion: 1,
                message: "workspace-kit detach is preview-only; no files changed.",
                data: plan
            }, null, 2));
        }
        else {
            writeError("workspace-kit detach is preview-only in this release. No files changed.");
            writeError("Re-run with `workspace-kit detach --dry-run` to inspect kit-owned paths.");
        }
        return EXIT_USAGE_ERROR;
    }
    if (flags.json) {
        writeLine(JSON.stringify({ ok: true, code: "detach-plan", schemaVersion: 1, data: plan }, null, 2));
        return EXIT_SUCCESS;
    }
    writeLine("workspace-kit detach (dry-run) — no files changed.");
    writeLine("Owned paths:");
    for (const ownedPath of ownedPaths) {
        writeLine(`- ${ownedPath}`);
    }
    return EXIT_SUCCESS;
}
async function printWorkspaceKitTopLevelHelp(writeLine) {
    const version = await readCliBundledPackageVersion();
    const versionSuffix = version ? ` v${version}` : "";
    writeLine(`Workflow Cannon — workspace-kit${versionSuffix} (${CANONICAL_KIT_NAME})`);
    writeLine("");
    writeLine("CLI for deterministic, policy-governed task workflows.");
    writeLine("Command discovery: run `workspace-kit run` with no subcommand (after `doctor` passes) to print every module command.");
    writeLine("Also installed as the short command `wk` (same binary as `workspace-kit`).");
    writeLine("");
    writeLine("Start here (attach Workflow Cannon to a repo)");
    writeLine("  1) workspace-kit init           ← first-run attach / baselines / SQLite");
    writeLine("  2) workspace-kit start           ← quick health summary + useful commands");
    writeLine("  3) workspace-kit run get-next-actions '{}'   ← safe read: suggested next work");
    writeLine("");
    writeLine("Top-level commands");
    writeLine("  doctor          Validate kit contract files, config, and persistence checks");
    writeLine("  doctor [--json | --format json]   Contract-check result as a single JSON envelope (distinct from --agent-instruction-surface)");
    writeLine("  doctor --agent-instruction-surface [--agent-instruction-surface-lean]   JSON instruction catalog (optional lean digest projection)");
    writeLine("  doctor [--delivery-loop] [--delivery-loop-strict]   optional maintainer delivery advisory / gate (dirty + protected branch + in_progress tasks)");
    writeLine("  run <cmd> [json]  Run a module command; omit <cmd> to list runnable commands");
    writeLine("  run [--json | --format json]   With no <cmd>: machine-readable command catalog (stable names + policy hints)");
    writeLine("  run <cmd> --schema-only   Pilot: print JSON Schema + sample args (run-transition, create-task, update-task, dashboard-summary)");
    writeLine("  config          Show or change kit config (mutations need env approval — see below)");
    writeLine("  check           Validate workspace-kit.profile.json");
    writeLine("  init            Attach Workflow Cannon (detect + baselines + SQLite + doctor)");
    writeLine("  init --dry-run [--json]   Preview planned writes (never modifies disk)");
    writeLine("  refresh-context Regenerate profile-driven artifacts from workspace-kit.profile.json (env approval)");
    writeLine("  start           Doctor-backed status summary after attach (--json)");
    writeLine("  upgrade         Refresh kit-managed baseline files (needs env approval)");
    writeLine("  drift-check     Fail if managed kit assets differ from expected content");
    writeLine("  detach --dry-run [--json]   Preview kit-owned paths; no deletion is performed");
    writeLine("");
    writeLine("Policy & docs (paths are relative to a clone of this repo; npm consumers: open the package or docs site)");
    writeLine(`  ${AGENT_CLI_MAP_HUMAN_DOC} — tier table, copy-paste JSON for agents`);
    writeLine(`  ${POLICY_APPROVAL_HUMAN_DOC} — when policyApproval JSON vs env approval applies`);
    writeLine("");
    writeLine("Global options");
    writeLine("  -h, --help      Show this message");
    writeLine("  -V, --version   Print CLI version");
    writeLine("  help            Same as --help");
}
export async function runCli(args, options = {}) {
    const cwd = options.cwd ?? process.cwd();
    loadWorkspaceDotenv(cwd);
    const writeLine = options.writeLine ?? console.log;
    const writeError = options.writeError ?? console.error;
    const readStdinLine = options.readStdinLine;
    const [command] = args;
    if (command === "--version" || command === "-V") {
        const v = await readCliBundledPackageVersion();
        writeLine(v ?? "workspace-kit (version unknown)");
        return EXIT_SUCCESS;
    }
    if (command === "--help" || command === "-h" || command === "help") {
        await printWorkspaceKitTopLevelHelp(writeLine);
        return EXIT_SUCCESS;
    }
    if (!command) {
        await printWorkspaceKitTopLevelHelp(writeLine);
        writeError("Missing command. Re-run with a top-level command, or pass --help for the same guide.");
        return EXIT_USAGE_ERROR;
    }
    if (command === "config") {
        return runWorkspaceConfigCli(cwd, args.slice(1), { writeLine, writeError });
    }
    if (command === "init") {
        return runWorkspaceKitInitCommand(cwd, args.slice(1), { writeLine, writeError, readStdinLine }, {
            success: EXIT_SUCCESS,
            validationFailure: EXIT_VALIDATION_FAILURE,
            usageError: EXIT_USAGE_ERROR,
            internalError: EXIT_INTERNAL_ERROR
        });
    }
    if (command === "refresh-context") {
        return runRefreshContextCommand(cwd, writeLine, writeError);
    }
    if (command === "start") {
        return runWorkspaceKitStartCommand(cwd, args.slice(1), { writeLine, writeError, readStdinLine }, {
            success: EXIT_SUCCESS,
            validationFailure: EXIT_VALIDATION_FAILURE,
            usageError: EXIT_USAGE_ERROR,
            internalError: EXIT_INTERNAL_ERROR
        });
    }
    if (command === "detach") {
        return runWorkspaceKitDetachCommand(cwd, args.slice(1), writeLine, writeError);
    }
    if (command === "check") {
        const { errors } = await validateProfile(cwd);
        if (errors.length > 0) {
            writeError("workspace-kit check failed profile validation.");
            for (const error of errors) {
                writeError(`- ${error}`);
            }
            return EXIT_VALIDATION_FAILURE;
        }
        writeLine("workspace-kit check passed.");
        writeLine("Profile validation succeeded for required baseline fields.");
        return EXIT_SUCCESS;
    }
    if (command === "upgrade") {
        const approval = await requireCliPolicyApproval(cwd, "cli.upgrade", "upgrade", writeError);
        if (!approval) {
            return EXIT_VALIDATION_FAILURE;
        }
        const { errors, profile } = await validateProfile(cwd);
        if (errors.length > 0 || !profile) {
            await recordCliPolicySuccess(cwd, "cli.upgrade", "upgrade", approval.rationale, false);
            writeError("workspace-kit upgrade failed profile validation.");
            for (const error of errors) {
                writeError(`- ${error}`);
            }
            return EXIT_VALIDATION_FAILURE;
        }
        const ownedPathsDocument = await readOwnedPathsDocument(cwd);
        const backupRoot = path.join(cwd, ".workspace-kit", "backups", new Date().toISOString());
        const updatedPaths = [];
        const preservedPaths = [];
        const unsupportedPaths = [];
        const ownedPathSet = new Set(ownedPathsDocument.ownedPaths);
        for (const ownedPath of currentOwnedPaths) {
            ownedPathSet.add(ownedPath);
        }
        ownedPathSet.add(defaultWorkspaceKitPaths.profile);
        ownedPathSet.add(defaultWorkspaceKitPaths.profileSchema);
        ownedPathSet.add(defaultWorkspaceKitPaths.manifest);
        ownedPathSet.add(defaultWorkspaceKitPaths.ownedPaths);
        ownedPathSet.add(".cursor/rules/workspace-kit-profile-pointer.mdc");
        const existingManifestValue = await parseJsonFile(path.join(cwd, defaultWorkspaceKitPaths.manifest)).catch(() => ({}));
        const existingManifest = existingManifestValue &&
            typeof existingManifestValue === "object" &&
            !Array.isArray(existingManifestValue)
            ? existingManifestValue
            : {};
        const nowIso = new Date().toISOString();
        const resolvedKitVersion = (await resolvePackageVersion(cwd)) ?? (await readCliBundledPackageVersion()) ?? "0.0.0";
        const mergedManifest = {
            schemaVersion: 1,
            kit: {
                name: CANONICAL_KIT_NAME,
                version: resolvedKitVersion
            },
            installedAt: typeof existingManifest.installedAt === "string" && existingManifest.installedAt.length > 0
                ? existingManifest.installedAt
                : nowIso,
            lastUpgrade: nowIso,
            ownershipPolicyPath: defaultWorkspaceKitPaths.ownedPaths
        };
        const desiredAssets = new Map([
            [defaultWorkspaceKitPaths.profileSchema, toJsonWithTrailingNewline(profileSchemaContent)],
            [defaultWorkspaceKitPaths.manifest, toJsonWithTrailingNewline(mergedManifest)],
            [
                defaultWorkspaceKitPaths.ownedPaths,
                toJsonWithTrailingNewline({
                    schemaVersion: 1,
                    ownedPaths: currentOwnedPaths,
                    notes: "Phase 3 baseline: managed kit-owned paths are updated by workspace-kit upgrade with backup safety."
                })
            ],
            [WORKSPACE_KIT_RUNTIME_LAUNCHER_RELATIVE_PATH, generateWorkspaceKitLauncherContent()],
            [".cursor/rules/workspace-kit-profile-pointer.mdc", `${pointerRuleContent}`]
        ]);
        for (const ownedPath of ownedPathSet) {
            if (ownedPath === defaultWorkspaceKitPaths.profile) {
                preservedPaths.push(ownedPath);
                continue;
            }
            if (ownedPath === WORKSPACE_KIT_RUNTIME_STAMP_RELATIVE_PATH) {
                preservedPaths.push(ownedPath);
                continue;
            }
            const desiredContent = desiredAssets.get(ownedPath);
            if (!desiredContent) {
                if (ownedPath !== ".workspace-kit/generated/project-context.json" &&
                    ownedPath !== ".cursor/rules/workspace-kit-project-context.mdc") {
                    unsupportedPaths.push(ownedPath);
                }
                continue;
            }
            const changed = await writeFileWithBackupIfChanged(cwd, ownedPath, desiredContent, backupRoot);
            if (ownedPath === WORKSPACE_KIT_RUNTIME_LAUNCHER_RELATIVE_PATH) {
                const launcherPath = path.join(cwd, ownedPath);
                const executableBefore = await isExecutable(launcherPath);
                await fs.chmod(launcherPath, 0o755);
                if (!changed && !executableBefore) {
                    updatedPaths.push(ownedPath);
                    continue;
                }
            }
            if (changed) {
                updatedPaths.push(ownedPath);
            }
        }
        const generatedArtifacts = await generateProfileDrivenArtifacts(cwd, profile);
        updatedPaths.push(path.relative(cwd, generatedArtifacts.generatedJsonPath));
        updatedPaths.push(path.relative(cwd, generatedArtifacts.generatedRulePath));
        writeLine("workspace-kit upgrade completed.");
        if (updatedPaths.length > 0) {
            writeLine("Updated kit-owned paths:");
            for (const updatedPath of updatedPaths) {
                writeLine(`- ${updatedPath}`);
            }
        }
        if (preservedPaths.length > 0) {
            writeLine("Preserved merge-managed paths:");
            for (const preservedPath of preservedPaths) {
                writeLine(`- ${preservedPath}`);
            }
        }
        if (unsupportedPaths.length > 0) {
            writeLine("Ignored unsupported owned paths:");
            for (const unsupportedPath of unsupportedPaths) {
                writeLine(`- ${unsupportedPath}`);
            }
        }
        writeLine(`Backups written under: ${path.relative(cwd, backupRoot)}`);
        await recordCliPolicySuccess(cwd, "cli.upgrade", "upgrade", approval.rationale, true);
        return EXIT_SUCCESS;
    }
    if (command === "drift-check") {
        const { errors, profile } = await validateProfile(cwd);
        if (errors.length > 0 || !profile) {
            writeError("workspace-kit drift-check failed profile validation.");
            for (const error of errors) {
                writeError(`- ${error}`);
            }
            return EXIT_VALIDATION_FAILURE;
        }
        const driftFindings = [];
        const warnings = [];
        const expectedAssets = createDriftExpectedAssets(profile);
        expectedAssets.set(WORKSPACE_KIT_RUNTIME_LAUNCHER_RELATIVE_PATH, generateWorkspaceKitLauncherContent());
        const ownedPathsDocument = await readOwnedPathsDocument(cwd);
        const ownedPathSet = new Set(ownedPathsDocument.ownedPaths);
        for (const managedRuntimePath of [
            WORKSPACE_KIT_RUNTIME_STAMP_RELATIVE_PATH,
            WORKSPACE_KIT_RUNTIME_LAUNCHER_RELATIVE_PATH
        ]) {
            if (!ownedPathSet.has(managedRuntimePath)) {
                driftFindings.push(`${defaultWorkspaceKitPaths.ownedPaths}: missing managed runtime path ${managedRuntimePath}`);
                ownedPathSet.add(managedRuntimePath);
            }
        }
        for (const ownedPath of ownedPathSet) {
            if (ownedPath === WORKSPACE_KIT_RUNTIME_STAMP_RELATIVE_PATH) {
                driftFindings.push(...runtimeStampDriftFindings(cwd));
                continue;
            }
            const expectedContent = expectedAssets.get(ownedPath);
            if (!expectedContent) {
                warnings.push(`unsupported owned path skipped: ${ownedPath}`);
                continue;
            }
            const targetPath = path.join(cwd, ownedPath);
            let existingContent;
            try {
                existingContent = await fs.readFile(targetPath, "utf8");
            }
            catch {
                driftFindings.push(`${ownedPath}: missing`);
                continue;
            }
            if (!driftContentMatches(ownedPath, existingContent, expectedContent)) {
                driftFindings.push(`${ownedPath}: content drift detected`);
            }
            if (ownedPath === WORKSPACE_KIT_RUNTIME_LAUNCHER_RELATIVE_PATH &&
                !(await isExecutable(targetPath))) {
                driftFindings.push(`${ownedPath}: not executable`);
            }
        }
        const manifestPath = path.join(cwd, defaultWorkspaceKitPaths.manifest);
        let manifest;
        try {
            const parsedManifest = await parseJsonFile(manifestPath);
            if (parsedManifest && typeof parsedManifest === "object" && !Array.isArray(parsedManifest)) {
                manifest = parsedManifest;
            }
            else {
                driftFindings.push(`${defaultWorkspaceKitPaths.manifest}: invalid structure`);
            }
        }
        catch {
            driftFindings.push(`${defaultWorkspaceKitPaths.manifest}: missing or invalid JSON`);
        }
        if (manifest) {
            if (manifest.ownershipPolicyPath !== defaultWorkspaceKitPaths.ownedPaths) {
                driftFindings.push(`${defaultWorkspaceKitPaths.manifest}: ownershipPolicyPath must equal ${defaultWorkspaceKitPaths.ownedPaths}`);
            }
            const manifestKit = manifest.kit && typeof manifest.kit === "object" && !Array.isArray(manifest.kit)
                ? manifest.kit
                : undefined;
            const manifestKitName = manifestKit && typeof manifestKit.name === "string" ? manifestKit.name : undefined;
            const manifestKitVersion = manifestKit && typeof manifestKit.version === "string" ? manifestKit.version : undefined;
            const packageVersion = await resolvePackageVersion(cwd);
            if (!manifestKitName || !manifestKitVersion) {
                driftFindings.push(`${defaultWorkspaceKitPaths.manifest}: kit.name and kit.version are required`);
            }
            else if ((manifestKitName === CANONICAL_KIT_NAME || manifestKitName === "quicktask-workspace-kit") &&
                packageVersion) {
                if (manifestKitVersion !== packageVersion) {
                    driftFindings.push(`${defaultWorkspaceKitPaths.manifest}: kit.version (${manifestKitVersion}) does not match package version (${packageVersion})`);
                }
            }
            else if (manifestKitName !== CANONICAL_KIT_NAME &&
                manifestKitName !== "quicktask-workspace-kit") {
                warnings.push(`${defaultWorkspaceKitPaths.manifest}: kit.name is '${manifestKitName}', skipping package-version drift comparison`);
            }
        }
        if (driftFindings.length > 0) {
            writeError("workspace-kit drift-check detected drift.");
            for (const finding of driftFindings) {
                writeError(`- ${finding}`);
            }
            for (const warning of warnings) {
                writeError(`- warning: ${warning}`);
            }
            return EXIT_VALIDATION_FAILURE;
        }
        writeLine("workspace-kit drift-check passed.");
        writeLine("No managed asset drift detected for supported owned paths.");
        for (const warning of warnings) {
            writeLine(`- warning: ${warning}`);
        }
        return EXIT_SUCCESS;
    }
    if (command === "run") {
        return handleRunCommand(cwd, args, { writeLine, writeError, readStdinLine }, {
            success: EXIT_SUCCESS,
            validationFailure: EXIT_VALIDATION_FAILURE,
            usageError: EXIT_USAGE_ERROR,
            internalError: EXIT_INTERNAL_ERROR
        });
    }
    if (command !== "doctor") {
        writeError(`Unknown command '${command}'. Supported: init, refresh-context, start, doctor, check, upgrade, drift-check, detach, run, config. Run workspace-kit --help for a guided overview.`);
        return EXIT_USAGE_ERROR;
    }
    const doctorRest = args.slice(1);
    const wantDoctorJson = doctorWantsMachineJson(doctorRest);
    const wantLeanInstructionSurface = doctorRest.includes("--agent-instruction-surface-lean") ||
        doctorRest.includes("agent-instruction-surface-lean");
    const wantAgentInstructionSurface = doctorRest.includes("--agent-instruction-surface") ||
        doctorRest.includes("agent-instruction-surface") ||
        wantLeanInstructionSurface;
    const deliveryLoopStrict = doctorRest.includes("--delivery-loop-strict");
    const wantDeliveryLoop = deliveryLoopStrict || doctorRest.includes("--delivery-loop");
    const runtimeContract = await collectDoctorRuntimeContractStatus(cwd);
    const issues = await collectDoctorContractIssues(cwd);
    if (issues.length > 0) {
        if (wantDoctorJson) {
            writeLine(JSON.stringify({
                ok: false,
                code: "doctor-contract-failed",
                schemaVersion: 1,
                message: "workspace-kit doctor failed validation.",
                data: { issues, runtimeContract },
                remediation: {
                    humanHints: [
                        "workspace-kit --help",
                        "Fix missing or invalid paths reported in data.issues",
                        "For runtime contract drift, repair setup and run `workspace-kit init --force`."
                    ]
                }
            }, null, 2));
            return EXIT_VALIDATION_FAILURE;
        }
        writeError("workspace-kit doctor failed validation.");
        for (const issue of issues) {
            writeError(`- ${issue.path}: ${issue.reason}`);
        }
        writeDoctorFailureRemediation(writeError, issues);
        return EXIT_VALIDATION_FAILURE;
    }
    if (wantAgentInstructionSurface) {
        try {
            const { registry, effective } = await resolveRegistryAndConfig(cwd, defaultRegistryModules);
            const surface = buildAgentInstructionSurface(registry.getAllModules(), registry, {
                workspacePath: cwd,
                effectiveConfig: effective,
                projection: wantLeanInstructionSurface ? "lean" : "full"
            });
            writeLine(JSON.stringify({ ok: true, code: "agent-instruction-surface", data: surface }, null, 2));
        }
        catch (error) {
            const message = error instanceof Error ? error.message : String(error);
            writeError(`workspace-kit doctor: could not build agent instruction surface: ${message}`);
            writeError("  Hint: workspace-kit --help; fix config/module issues, then retry.");
            if (error instanceof ModuleRegistryError) {
                return EXIT_VALIDATION_FAILURE;
            }
            return EXIT_INTERNAL_ERROR;
        }
        return EXIT_SUCCESS;
    }
    let deliveryLoopIssues = [];
    if (wantDeliveryLoop) {
        try {
            const { effective } = await resolveRegistryAndConfig(cwd, defaultRegistryModules, {});
            deliveryLoopIssues = await collectMaintainerDeliveryLoopIssues(cwd, effective);
        }
        catch (error) {
            const message = error instanceof Error ? error.message : String(error);
            writeError(`workspace-kit doctor: maintainer delivery loop check failed: ${message}`);
            return EXIT_INTERNAL_ERROR;
        }
        if (deliveryLoopStrict && deliveryLoopIssues.length > 0) {
            writeError("workspace-kit doctor failed maintainer delivery loop gate (--delivery-loop-strict).");
            for (const issue of deliveryLoopIssues) {
                writeError(`- ${issue.path}: ${issue.reason}`);
            }
            writeError("  Hint: move work to a task branch from the phase integration branch — .ai/playbooks/task-to-phase-branch.md");
            return EXIT_VALIDATION_FAILURE;
        }
    }
    const lines = [];
    lines.push("workspace-kit doctor passed.");
    lines.push("All canonical workspace-kit contract files are present and parseable JSON.");
    lines.push(`Runtime contract healthy: ${runtimeContract.stampPath} and ${runtimeContract.launcherPath}.`);
    lines.push("Effective workspace config resolved; task planning persistence checks passed (including SQLite when configured).");
    for (const line of await collectTaskPersistenceDoctorSummaryLines(cwd)) {
        lines.push(line);
    }
    for (const line of collectPolicyLaneEnvDoctorSummaryLines()) {
        lines.push(line);
    }
    for (const line of await collectCaeDoctorSummaryLines(cwd)) {
        lines.push(line);
    }
    for (const line of await collectPluginDoctorSummaryLines(cwd)) {
        lines.push(line);
    }
    if (wantDeliveryLoop && !deliveryLoopStrict && deliveryLoopIssues.length > 0) {
        for (const line of formatMaintainerDeliveryLoopAdvisoryLines(deliveryLoopIssues)) {
            lines.push(line);
        }
    }
    lines.push(`Next: workspace-kit run — list module commands; see ${AGENT_CLI_MAP_HUMAN_DOC} for tier/policy copy-paste.`);
    if (wantDoctorJson) {
        writeLine(JSON.stringify({
            ok: true,
            code: "doctor-contract-ok",
            schemaVersion: 1,
            message: "workspace-kit doctor passed.",
            data: {
                summaryText: lines,
                runtimeContract,
                nextHint: `workspace-kit run --json lists commands; see ${AGENT_CLI_MAP_HUMAN_DOC}`
            }
        }, null, 2));
        return EXIT_SUCCESS;
    }
    for (const line of lines) {
        writeLine(line);
    }
    return EXIT_SUCCESS;
}
async function main() {
    try {
        const code = await runCli(process.argv.slice(2));
        process.exitCode = code;
    }
    catch (error) {
        const message = error instanceof Error ? error.message : String(error);
        console.error(`workspace-kit internal error: ${message}`);
        process.exitCode = EXIT_INTERNAL_ERROR;
    }
}
function isCliInvokedDirectly() {
    const argvScript = process.argv[1];
    if (typeof argvScript !== "string") {
        return false;
    }
    try {
        return realpathSync(argvScript) === realpathSync(fileURLToPath(import.meta.url));
    }
    catch {
        return false;
    }
}
if (isCliInvokedDirectly()) {
    void main();
}
