"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.createResumeRunCommand = createResumeRunCommand;
const errors_1 = require("../../../lib/errors");
const agent_context_1 = require("../../../lib/agent-context");
const lifecycle_run_context_1 = require("../../../lib/lifecycle-run-context");
const automation_protocol_1 = require("../../../lib/automation-protocol");
const lifecycle_run_analysis_1 = require("../../../lib/lifecycle-run-analysis");
const run_pack_1 = require("../../../lib/lifecycle-run-context/run-pack");
const output_1 = require("../../../lib/output");
const runtime_contract_1 = require("../../../lib/runtime/runtime-contract");
const config_store_1 = require("../../../lib/config/config-store");
const config_1 = require("../../../lib/config");
const sandbox_contract_1 = require("../../../lib/paths/sandbox-contract");
const task_contract_revision_adoption_1 = require("../../../lib/planning/task-contract-revision-adoption");
const registration_1 = require("../registration");
async function createResumeRunCommand() {
    const { Command } = await import('commander');
    const command = new Command('run').description('Manage one repository-local, evidence-only lifecycle run context.');
    (0, registration_1.registerCommand)(command, await createResumeRunOpenCommand());
    (0, registration_1.registerCommand)(command, await createResumeRunRecordCommand());
    (0, registration_1.registerCommand)(command, await createResumeRunReviseContractCommand());
    (0, registration_1.registerCommand)(command, await createResumeRunMigrateCommand());
    (0, registration_1.registerCommand)(command, await createResumeRunPackCommand());
    (0, registration_1.registerCommand)(command, await createResumeRunStatusCommand());
    (0, registration_1.registerCommand)(command, await createResumeRunResumeCommand());
    (0, registration_1.registerCommand)(command, await createResumeRunExplainCommand());
    (0, registration_1.registerCommand)(command, await createResumeRunFrictionReportCommand());
    (0, registration_1.registerCommand)(command, await createResumeRunCompareCommand());
    return command;
}
async function createResumeRunMigrateCommand() {
    const { Command } = await import('commander');
    return new Command('migrate')
        .description("Preview or atomically copy one legacy root 'sandbox/run-*' into '.day-shift/runs/'.")
        .requiredOption('--run-directory <path>', "Legacy repository-relative 'sandbox/run-<run-id>' source directory.")
        .option('--expected-source-snapshot <digest>', 'Exact source snapshot emitted by the current dry-run; required for apply.')
        .option('--dry-run', 'Verify and preview the canonical managed destination without writes.', false)
        .option('--apply', 'Atomically publish the preview-bound managed destination while preserving the legacy source.', false)
        .action((options, commandInstance) => {
        if (Number(Boolean(options.dryRun)) + Number(Boolean(options.apply)) !== 1) {
            throw (0, errors_1.createUsageError)('Run migration requires exactly one explicit mode: --dry-run or --apply.');
        }
        const root = repositoryRoot(commandInstance);
        const result = options.dryRun
            ? (0, lifecycle_run_context_1.previewLifecycleRunMigrationSync)({ repositoryRoot: root, runDirectory: options.runDirectory })
            : (0, lifecycle_run_context_1.applyLifecycleRunMigrationSync)({
                repositoryRoot: root,
                runDirectory: options.runDirectory,
                expectedSourceSnapshot: options.expectedSourceSnapshot ?? '',
            });
        emitRunResult('resume run migrate', commandInstance, projectLifecycleRunMigration(result), result.writeOutcome === 'committed', options.dryRun ? 'Lifecycle run migration preview' : 'Lifecycle run migrated');
    });
}
function projectLifecycleRunMigration(result) {
    const explicitDetail = process.argv.some((token) => token === '--detail' || token.startsWith('--detail='));
    const detail = (0, output_1.detectOutputProjectionOptions)(process.argv).detail ?? 'full';
    if (detail === 'full' && (explicitDetail || (0, automation_protocol_1.getSelectedAutomationProtocolVersion)() !== 2))
        return result;
    const { intendedPaths, expected, changedPaths, ...compact } = result;
    return {
        ...compact,
        intendedPathCount: intendedPaths.length,
        expectedPreconditionCount: expected.length,
        changedPathCount: changedPaths.length,
    };
}
async function createResumeRunPackCommand() {
    const { Command } = await import('commander');
    return new Command('pack')
        .description('Preview, atomically create, or verify one immutable content-addressed lifecycle run pack.')
        .option('--run-directory <path>', 'Canonical managed source run directory; legacy root runs remain readable.')
        .requiredOption('--destination <path>', 'Explicit new repository-local .day-shift/runs destination, or existing pack for verification.')
        .option('--expected-source-snapshot <digest>', 'Exact canonical source snapshot emitted by the current dry-run; required for apply.')
        .option('--dry-run', 'Verify the source and report exact deduplication and destination projections without writes.', false)
        .option('--apply', 'Publish the exact source-snapshot-bound pack destination atomically.', false)
        .option('--verify', 'Read and verify an existing pack manifest and every content-addressed object without writes.', false)
        .action((options, commandInstance) => {
        const selectedModes = [options.dryRun, options.apply, options.verify].filter(Boolean).length;
        if (selectedModes !== 1) {
            throw (0, errors_1.createUsageError)('Run pack requires exactly one explicit mode: --dry-run, --apply, or --verify.');
        }
        const root = repositoryRoot(commandInstance);
        const destination = requireSandboxRunDirectoryOption(options.destination, 'Lifecycle run pack destination');
        let result;
        if (options.verify) {
            if (options.runDirectory !== undefined || options.expectedSourceSnapshot !== undefined) {
                throw (0, errors_1.createUsageError)('Run pack verify accepts only the explicit pack --destination.');
            }
            result = (0, run_pack_1.inspectLifecycleRunPackSync)({
                repositoryRoot: root,
                destination,
            });
        }
        else {
            if (options.runDirectory === undefined) {
                throw (0, errors_1.createUsageError)('Run pack dry-run and apply require --run-directory.');
            }
            if (options.dryRun) {
                if (options.expectedSourceSnapshot !== undefined) {
                    throw (0, errors_1.createUsageError)('Run pack dry-run computes the source snapshot and does not accept one.');
                }
                result = (0, run_pack_1.previewLifecycleRunPackSync)({
                    repositoryRoot: root,
                    runDirectory: options.runDirectory,
                    destination,
                });
            }
            else {
                if (options.expectedSourceSnapshot === undefined) {
                    throw (0, errors_1.createUsageError)('Run pack apply requires --expected-source-snapshot from the current dry-run.');
                }
                result = (0, run_pack_1.createAndApplyLifecycleRunPackSync)({
                    repositoryRoot: root,
                    runDirectory: options.runDirectory,
                    destination,
                    expectedSourceSnapshot: options.expectedSourceSnapshot,
                });
            }
        }
        if (result.writeOutcome === 'conflict' || result.writeOutcome === 'no-write') {
            throw new errors_1.RuntimeError({
                code: result.writeOutcome === 'conflict' ? 'LIFECYCLE_RUN_PACK_CONFLICT' : 'LIFECYCLE_RUN_PACK_NO_WRITE_FAILURE',
                exitCode: result.writeOutcome === 'conflict' ? errors_1.RuntimeExitCode.CONCURRENCY_CONFLICT : errors_1.RuntimeExitCode.ERROR,
                message: 'Lifecycle run pack stopped before publishing its destination.',
                details: [
                    result.failure ?? 'Exact source or destination preconditions no longer match.',
                    'The canonical source run was left unchanged.',
                ],
                recoveryActions: [
                    (0, errors_1.createNonCallableRecoveryAction)({
                        id: 'recovery.lifecycle-run.pack.refresh-preview',
                        command: 'resume run pack',
                        explanation: 'Create a new dry-run against the current source and an absent explicit destination.',
                        reason: 'A changed snapshot or destination cannot be safely inferred or overwritten.',
                    }),
                ],
            });
        }
        emitRunResult('resume run pack', commandInstance, projectRunPack(result), result.writeOutcome === 'committed', result.operation === 'dry-run'
            ? 'Lifecycle run pack dry-run'
            : result.operation === 'apply'
                ? 'Lifecycle run pack published'
                : 'Lifecycle run pack verified');
    });
}
async function createResumeRunReviseContractCommand() {
    const { Command } = await import('commander');
    return new Command('revise-contract')
        .description('Preview or atomically checkpoint one explicitly authorized bounded phase/active planning or direct Basic/Structured task contract revision.')
        .requiredOption('--run-directory <path>', 'Canonical managed run directory; legacy root runs remain readable.')
        .requiredOption('--review-result <path>', 'Repository-relative current authoritative review, or the exact predecessor task attempt-open evidence emitted for replacement-run checkpoint adoption.')
        .requiredOption('--active-artifact <path>', 'Exact repository-relative active planning artifact bound by the run.')
        .requiredOption('--recorded-by <text>', 'Actor explicitly authorizing the bounded contract revision.')
        .requiredOption('--recorded-at <timestamp>', 'ISO-8601 authorization time with an explicit timezone.')
        .requiredOption('--reason <text>', 'Bounded reason for revising the run contract.')
        .requiredOption('--rollback-gate <identity>', 'Closed rollback gate: phase-authoring-review, milestone-scaffold, or task-readiness.')
        .option('--project <id>', 'Explicit monorepo project whose contract-revision impact budget applies.')
        .option('--max-invalidated-entries <count>', 'Explicit non-negative manifest-entry impact limit.')
        .option('--max-evidence-bytes <count>', 'Explicit non-negative indexed-evidence byte impact limit.')
        .option('--impact-acknowledgement <identity>', 'Exact acknowledgement identity emitted by an over-budget no-write preview.')
        .option('--dry-run', 'Preview exact preconditions and intended writes without changing repository state.', false)
        .action((options, commandInstance) => {
        try {
            const root = repositoryRoot(commandInstance);
            let adoptionCandidate = null;
            if (options.rollbackGate === 'task-readiness') {
                try {
                    adoptionCandidate = (0, task_contract_revision_adoption_1.discoverTaskContractRevisionAdoptionSync)(root, options.activeArtifact)
                        .find((candidate) => candidate.runDirectory === options.runDirectory &&
                        candidate.sourceEvidencePath === options.reviewResult) ?? null;
                }
                catch {
                    adoptionCandidate = null;
                }
            }
            if (adoptionCandidate !== null) {
                const preview = (0, task_contract_revision_adoption_1.previewTaskContractRevisionAdoptionSync)({
                    repositoryRoot: root,
                    runDirectory: adoptionCandidate.runDirectory,
                    sourceRunDirectory: adoptionCandidate.sourceRunDirectory,
                    taskDefinitionPath: options.activeArtifact,
                    attemptId: adoptionCandidate.attemptId,
                    taskRevision: adoptionCandidate.newTaskRevision,
                    recordedBy: options.recordedBy,
                    recordedAt: options.recordedAt,
                    reason: options.reason,
                });
                const result = options.dryRun ? preview : (0, task_contract_revision_adoption_1.applyTaskContractRevisionAdoptionSync)(preview);
                assertContractRevisionAdoptionApplied(result);
                emitRunResult('resume run revise-contract', commandInstance, {
                    ...result,
                    dryRun: Boolean(options.dryRun),
                    noWriteBoundary: options.dryRun
                        ? 'Dry-run verified the immutable source entry, stale task pair, evidence-bearing attempt, replacement binding, and exact repository preconditions without writing.'
                        : result.idempotent
                            ? 'Exact replay matched the adopted checkpoint and performed no writes.'
                            : 'Apply copied no source bytes, wrote one digest-bound adoption receipt, and updated only the replacement manifest.',
                    nextAction: {
                        reasonCode: 'contract_revision_requires_evidence_recovery',
                        command: 'task attempt-contract-revise',
                        argv: [
                            'day-shift', 'task', 'attempt-contract-revise',
                            '--revision-run-directory', result.runDirectory,
                            '--task-definition', result.taskDefinitionPath,
                            '--attempt-id', result.priorAttemptId,
                            '--task-revision', result.newTaskRevision,
                            '--checkpoint-id', result.checkpointId,
                            '--recorded-by', options.recordedBy,
                            '--recorded-at', options.recordedAt,
                            '--reason', 'Preserve evidence after the adopted task contract revision.',
                            '--dry-run',
                        ],
                        callable: true,
                        writeCapable: true,
                    },
                }, result.writeOutcome === 'committed', options.dryRun ? 'Lifecycle contract-revision adoption preview' : 'Lifecycle contract-revision checkpoint adopted');
                return;
            }
            const context = (0, runtime_contract_1.createRepositoryContext)({ root, detectionSource: 'explicit' }, false);
            const config = (0, config_store_1.readResolvedConfig)(context, {
                projectId: options.project,
                currentDirectory: process.cwd(),
            });
            const explicitBudget = {
                ...(options.maxInvalidatedEntries === undefined
                    ? {}
                    : {
                        max_invalidated_entries: parseNonNegativeSafeInteger(options.maxInvalidatedEntries, 'Maximum invalidated entries'),
                    }),
                ...(options.maxEvidenceBytes === undefined
                    ? {}
                    : { max_evidence_bytes: parseNonNegativeSafeInteger(options.maxEvidenceBytes, 'Maximum evidence bytes') }),
            };
            const impactBudget = (0, config_1.resolveContractRevisionImpactBudget)({
                repositoryConfig: config.repositoryConfig,
                projectContext: config.resolved.projectContext,
                repositoryConfigPath: config.resolved.derived.sharedConfigPath,
                explicit: explicitBudget,
            });
            const preview = (0, lifecycle_run_context_1.previewLifecycleRunContractRevisionSync)({
                repositoryRoot: root,
                runDirectory: options.runDirectory,
                reviewResultPath: options.reviewResult,
                activeArtifactPath: options.activeArtifact,
                recordedBy: options.recordedBy,
                recordedAt: options.recordedAt,
                reason: options.reason,
                rollbackGate: options.rollbackGate,
                impactBudget,
                impactAcknowledgement: options.impactAcknowledgement,
            });
            const result = options.dryRun ? preview : (0, lifecycle_run_context_1.applyLifecycleRunContractRevisionSync)(preview);
            assertContractRevisionApplied(result);
            const noWriteBoundary = !result.impactAuthorization.satisfied
                ? 'Impact exceeds the resolved contract-revision budget; the exact emitted acknowledgement identity is required before any write can be planned or applied.'
                : options.dryRun
                    ? 'Dry-run validated the current authoritative review, manifest completeness, canonical digests, impact budget, rollback gate, and exact repository preconditions without writing.'
                    : result.idempotent
                        ? 'Exact replay matched the current checkpoint and performed no writes.'
                        : 'Apply committed the indexed review and manifest checkpoint as one preconditioned repository transaction.';
            emitRunResult('resume run revise-contract', commandInstance, {
                ...projectContractRevisionResult(result),
                dryRun: Boolean(options.dryRun),
                noWriteBoundary,
            }, result.writeOutcome === 'committed', options.dryRun ? 'Lifecycle run contract revision preview' : 'Lifecycle run contract revision');
        }
        catch (error) {
            throw normalizeContractRevisionError(normalizeContractRevisionAdoptionError(error));
        }
    });
}
async function createResumeRunOpenCommand() {
    const { Command } = await import('commander');
    return new Command('open')
        .description("Create or open one bounded lifecycle run manifest below '.day-shift/runs/'.")
        .requiredOption('--run-directory <path>', "Canonical repository-relative '.day-shift/runs/run-<run-id>' directory; created when absent.")
        .requiredOption('--phase <path>', 'Repository-relative selected phase overview, or the selected task definition as a direct phase-less run anchor.')
        .requiredOption('--profile <value>', 'Lifecycle profile recorded for this run.')
        .requiredOption('--metadata-posture <value>', 'Metadata posture recorded as context, never write authority.')
        .requiredOption('--actor <text>', 'Actor opening the run.')
        .requiredOption('--active-artifact <path>', 'Repository-relative active lifecycle artifact.')
        .requiredOption('--active-gate <identity>', 'Current explicit lifecycle gate identity.')
        .option('--opened-at <timestamp>', 'ISO-8601 opening time; defaults to command time.')
        .action((options, commandInstance) => {
        const result = (0, lifecycle_run_context_1.openLifecycleRunContext)({
            repositoryRoot: repositoryRoot(commandInstance),
            runDirectory: options.runDirectory,
            phasePath: options.phase,
            lifecycleProfile: options.profile,
            metadataPosture: options.metadataPosture,
            actor: options.actor,
            activeArtifactPath: options.activeArtifact,
            activeGate: options.activeGate,
            openedAt: options.openedAt,
        });
        emitRunResult('resume run open', commandInstance, result, true, 'Lifecycle run context opened');
    });
}
async function createResumeRunRecordCommand() {
    const { Command } = await import('commander');
    return new Command('record')
        .description('Import one non-empty structured command result under a deterministic evidence name; ordinary gates use global run binding.')
        .requiredOption('--run-directory <path>', 'Canonical managed run directory; legacy root runs remain readable.')
        .requiredOption('--result <path>', 'Repository-relative non-empty structured success or error JSON result.')
        .option('--command <identity>', 'Exact command identity; must match the structured result when both are present.')
        .option('--artifact <path>', 'Repository-relative active artifact; defaults to the manifest active artifact.')
        .requiredOption('--gate <identity>', 'Lifecycle gate associated with this result.')
        .option('--write-outcome <value>', 'Explicit write outcome when the result does not carry one.')
        .option('--receipt-id <identity>', 'Explicit receipt identity. Repeat as needed.', collect, [])
        .option('--supersedes-entry-id <identity>', 'Prior manifest entry replaced by this result.')
        .option('--recorded-at <timestamp>', 'ISO-8601 record time; defaults to command time.')
        .action((options, commandInstance) => {
        const result = (0, lifecycle_run_context_1.recordLifecycleRunOutcome)({
            repositoryRoot: repositoryRoot(commandInstance),
            runDirectory: options.runDirectory,
            resultPath: options.result,
            commandIdentity: options.command,
            artifactPath: options.artifact,
            gate: options.gate,
            writeOutcome: options.writeOutcome,
            receiptIds: options.receiptId,
            supersedesEntryId: options.supersedesEntryId,
            recordedAt: options.recordedAt,
        });
        emitRunResult('resume run record', commandInstance, result, true, 'Lifecycle command outcome recorded');
    });
}
async function createResumeRunStatusCommand() {
    const { Command } = await import('commander');
    return new Command('status')
        .description('Revalidate one lifecycle run manifest, canonical evidence, and unindexed required JSON without writes.')
        .requiredOption('--run-directory <path>', 'Canonical managed run directory; legacy root runs remain readable.')
        .option('--artifact <path>', 'Explicit active artifact identity for conflict checking.')
        .action((options, commandInstance) => {
        const inspection = (0, lifecycle_run_context_1.inspectLifecycleRunContext)({
            repositoryRoot: repositoryRoot(commandInstance),
            runDirectory: options.runDirectory,
            selectedArtifactPath: options.artifact,
        });
        const projectionOptions = (0, output_1.detectOutputProjectionOptions)(process.argv);
        const statusProjection = (0, lifecycle_run_context_1.projectLifecycleRunStatus)(repositoryRoot(commandInstance), inspection, {
            pageLane: projectionOptions.pageLane,
        });
        const data = useCompactRunStatus() || projectionOptions.pageLane !== undefined
            ? statusProjection
            : { ...inspection, statusProjection };
        emitRunResult('resume run status', commandInstance, {
            ...data,
            noWriteBoundary: 'Status revalidates the manifest, canonical phase and active artifact, every evidence digest, and indexed/auxiliary/unindexed-required JSON classification without changing repository state.',
        }, false, 'Lifecycle run context status');
    });
}
async function createResumeRunResumeCommand() {
    const { Command } = await import('commander');
    return new Command('resume')
        .description('Revalidate one run and derive the current next action from canonical repository evidence.')
        .requiredOption('--run-directory <path>', 'Canonical managed run directory; legacy root runs remain readable.')
        .option('--artifact <path>', 'Explicit active artifact identity; conflicts fail closed.')
        .action((options, commandInstance) => {
        const root = repositoryRoot(commandInstance);
        const inspection = (0, lifecycle_run_context_1.inspectLifecycleRunContext)({
            repositoryRoot: root,
            runDirectory: options.runDirectory,
            selectedArtifactPath: options.artifact,
        });
        assertResumable(inspection);
        const statusProjection = (0, lifecycle_run_context_1.projectLifecycleRunStatus)(root, inspection);
        if (inspection.terminalState === 'review_complete_read_only' ||
            inspection.terminalState === 'task_close_complete') {
            const terminalContext = inspection.terminalState === 'task_close_complete'
                ? (0, agent_context_1.createTaskCloseCompletionContext)()
                : (0, agent_context_1.createReadOnlyReviewCompletionContext)();
            const terminalProjection = {
                ...statusProjection,
                nextAction: terminalContext.currentNextAction,
                resumeCapsule: {
                    ...statusProjection.resumeCapsule,
                    nextAction: terminalContext.currentNextAction,
                },
            };
            emitRunResult('resume run resume', commandInstance, {
                ...(useCompactRunStatus() ? terminalProjection : inspection),
                ...terminalContext,
                recordedGate: inspection.manifest.activeGate,
                historyAuthoritative: false,
                noWriteBoundary: inspection.terminalState === 'task_close_complete'
                    ? 'Resume verified the indexed task-close gate against the current canonical direct Basic task pair; no phase, reconciliation, project-review, or further lifecycle gate is permitted or executed.'
                    : 'Resume verified the recorded clean read-only phase review against current canonical revisions; no further lifecycle gate is permitted or executed.',
            }, false, 'Lifecycle run resume guidance');
            return;
        }
        const context = (0, agent_context_1.createArtifactAgentContext)({
            repositoryRoot: root,
            artifactPath: inspection.manifest.activeArtifactPath,
            detail: 'compact',
        });
        const currentNextAction = statusProjection.validationRecoveryAction ?? context.recommendedNextAction;
        const compactProjection = statusProjection.validationRecoveryAction === null
            ? {
                ...statusProjection,
                nextAction: currentNextAction,
                resumeCapsule: {
                    ...statusProjection.resumeCapsule,
                    nextAction: currentNextAction,
                },
            }
            : {
                state: statusProjection.state,
                runId: statusProjection.runId,
                runDirectory: statusProjection.runDirectory,
                manifestPath: statusProjection.manifestPath,
                manifestHash: statusProjection.manifestHash,
                currentGate: statusProjection.currentGate,
                activeArtifact: statusProjection.activeArtifact,
                terminalState: statusProjection.terminalState,
                readOnly: statusProjection.readOnly,
                entryCount: statusProjection.entryCount,
                commandEnvelopeOutcomes: statusProjection.commandEnvelopeOutcomes,
                validationOutcomes: statusProjection.validationOutcomes,
                blockerCount: statusProjection.blockerCount,
                nextAction: currentNextAction,
                recovery: statusProjection.recovery,
                authorityBoundary: statusProjection.authorityBoundary,
            };
        emitRunResult('resume run resume', commandInstance, {
            ...(useCompactRunStatus() ? compactProjection : inspection),
            currentNextAction,
            nextPermittedGate: currentNextAction.id,
            recordedGate: inspection.manifest.activeGate,
            ...(statusProjection.validationRecoveryAction === null
                ? {
                    currentNextActionResolution: context.workEvidence?.nextAction ?? null,
                    currentBlockers: context.relevantBlockers,
                }
                : {}),
            historyAuthoritative: false,
            noWriteBoundary: statusProjection.validationRecoveryAction === null
                ? 'Resume derives current action legality from canonical artifacts and never executes or authorizes a manifest-recorded command.'
                : 'Resume preserves the immutable unrecordable-execution recovery boundary and does not authorize or rerun the completed validation argv.',
        }, false, 'Lifecycle run resume guidance');
    });
}
async function createResumeRunExplainCommand() {
    const { Command } = await import('commander');
    return new Command('explain')
        .description('Explain one selected immutable run entry, gate, or finding code without executing recovery or mutating history.')
        .requiredOption('--run-directory <path>', 'Canonical managed run directory; legacy root runs remain readable.')
        .option('--artifact <path>', 'Optional explicit active artifact identity for typed conflict reporting.')
        .option('--entry <identity>', 'Exact immutable manifest entry identity.')
        .option('--gate <identity>', 'Exact manifest gate identity.')
        .option('--finding-code <identity>', 'Exact stable structured error or finding code.')
        .action((options, commandInstance) => {
        const root = repositoryRoot(commandInstance);
        const inspection = (0, lifecycle_run_context_1.inspectLifecycleRunContext)({
            repositoryRoot: root,
            runDirectory: options.runDirectory,
            selectedArtifactPath: options.artifact,
        });
        const selector = resolveRunSelector(commandInstance.optsWithGlobals?.() ?? options);
        const result = (0, lifecycle_run_analysis_1.explainLifecycleRun)({ repositoryRoot: root, inspection, selector });
        emitRunResult('resume run explain', commandInstance, projectRunAnalysis(result, 'causalEdges'), false, 'Lifecycle run explanation');
    });
}
async function createResumeRunFrictionReportCommand() {
    const { Command } = await import('commander');
    return new Command('friction-report')
        .description('Report bounded semantic lifecycle friction metrics from immutable indexed evidence without writes.')
        .requiredOption('--run-directory <path>', 'Canonical managed run directory; legacy root runs remain readable.')
        .option('--artifact <path>', 'Optional explicit active artifact identity for typed conflict reporting.')
        .action((options, commandInstance) => {
        const root = repositoryRoot(commandInstance);
        const inspection = (0, lifecycle_run_context_1.inspectLifecycleRunContext)({
            repositoryRoot: root,
            runDirectory: options.runDirectory,
            selectedArtifactPath: options.artifact,
        });
        const result = (0, lifecycle_run_analysis_1.reportLifecycleRunFriction)({ repositoryRoot: root, inspection });
        emitRunResult('resume run friction-report', commandInstance, projectRunAnalysis(result, 'metricDetails'), false, 'Lifecycle run friction report');
    });
}
async function createResumeRunCompareCommand() {
    const { Command } = await import('commander');
    return new Command('compare')
        .description('Compare two independently verified lifecycle runs and label non-comparable dimensions without writes.')
        .requiredOption('--left-run-directory <path>', 'Canonical managed left run directory; legacy root runs remain readable.')
        .requiredOption('--right-run-directory <path>', 'Canonical managed right run directory; legacy root runs remain readable.')
        .option('--left-artifact <path>', 'Optional explicit left active artifact identity for typed conflict reporting.')
        .option('--right-artifact <path>', 'Optional explicit right active artifact identity for typed conflict reporting.')
        .action((options, commandInstance) => {
        const root = repositoryRoot(commandInstance);
        const left = (0, lifecycle_run_context_1.inspectLifecycleRunContext)({
            repositoryRoot: root,
            runDirectory: options.leftRunDirectory,
            selectedArtifactPath: options.leftArtifact,
        });
        const right = (0, lifecycle_run_context_1.inspectLifecycleRunContext)({
            repositoryRoot: root,
            runDirectory: options.rightRunDirectory,
            selectedArtifactPath: options.rightArtifact,
        });
        const result = (0, lifecycle_run_analysis_1.compareLifecycleRuns)({ repositoryRoot: root, left, right });
        emitRunResult('resume run compare', commandInstance, projectRunAnalysis(result, 'comparisonDetails'), false, 'Lifecycle run comparison');
    });
}
function resolveRunSelector(options) {
    const selected = [
        options.entry === undefined ? null : { kind: 'entry', value: options.entry },
        options.gate === undefined ? null : { kind: 'gate', value: options.gate },
        options.findingCode === undefined ? null : { kind: 'finding-code', value: options.findingCode },
    ].filter((value) => value !== null);
    if (selected.length !== 1) {
        throw (0, errors_1.createUsageError)('Run explain requires exactly one selector: --entry, --gate, or --finding-code.');
    }
    const value = selected[0].value.trim();
    if (!/^[A-Za-z0-9][A-Za-z0-9._:-]{1,127}$/u.test(value)) {
        throw (0, errors_1.createUsageError)('Run explain selectors must be bounded machine-safe identities.');
    }
    return { ...selected[0], value };
}
function requireSandboxRunDirectoryOption(value, label) {
    try {
        return (0, sandbox_contract_1.assertSandboxRunDirectoryPath)(value);
    }
    catch (error) {
        throw (0, errors_1.createUsageError)(`${label} must be one canonical .day-shift/runs/run-<run-id> directory.`, [
            error instanceof Error ? error.message : String(error),
        ]);
    }
}
function projectRunAnalysis(data, pageLane) {
    if (!useCompactRunAnalysis())
        return data;
    const projection = (0, output_1.detectOutputProjectionOptions)(process.argv);
    const requestedLane = projection.pageLane;
    const common = {
        schemaVersion: data.schemaVersion,
        analysis: data.analysis,
        readOnly: data.readOnly,
        writeCapable: data.writeCapable,
        state: data.state,
        runId: data.runId,
        runDirectory: data.runDirectory,
        manifestPath: data.manifestPath,
        manifestHash: data.manifestHash,
        manifestComplete: data.manifestComplete,
        terminalState: data.terminalState,
        decisionTrace: data.decisionTrace,
        recovery: data.recovery,
        authorityBoundary: data.authorityBoundary,
        noWriteBoundary: data.noWriteBoundary,
    };
    const compact = data.analysis === 'explain'
        ? {
            ...common,
            selector: data.selector,
            selection: data.selection,
            firstSupportedDivergence: data.firstSupportedDivergence,
            violatedInvariant: data.violatedInvariant,
            priorSuccessfulPrerequisite: data.priorSuccessfulPrerequisite,
            invalidatedDownstreamEvidence: data.invalidatedDownstreamEvidence,
            smallestAuthoritativeRecovery: data.smallestAuthoritativeRecovery,
            validationHistory: data.validationHistory,
            causalEdgeCount: Array.isArray(data.causalEdges) ? data.causalEdges.length : 0,
            unsupportedCausalityPolicy: data.unsupportedCausalityPolicy,
            blockers: data.blockers,
            blockerCount: data.blockerCount,
        }
        : data.analysis === 'friction-report'
            ? {
                ...common,
                cliEnvelopeOutcomes: data.cliEnvelopeOutcomes,
                nestedValidationOutcomes: data.nestedValidationOutcomes,
                retryClusterCount: Array.isArray(data.retryClusters) ? data.retryClusters.length : 0,
                gateAttemptCount: Array.isArray(data.gateAttempts) ? data.gateAttempts.length : 0,
                revisionChurn: data.revisionChurn,
                supersession: data.supersession,
                recoveryPosture: data.recoveryPosture,
                evidenceStorage: data.evidenceStorage,
                outputBudgetPressure: data.outputBudgetPressure,
                blockerCount: data.blockerCount,
            }
            : {
                ...common,
                left: data.left,
                right: data.right,
                comparable: data.comparable,
                nonComparable: data.nonComparable,
                stableDeltas: data.stableDeltas,
                validationHistoryBoundary: data.validationHistoryBoundary,
            };
    return requestedLane === pageLane ? { ...compact, [pageLane]: data[pageLane] } : compact;
}
function useCompactRunAnalysis() {
    const explicitDetail = process.argv.some((token) => token === '--detail' || token.startsWith('--detail='));
    const detail = (0, output_1.detectOutputProjectionOptions)(process.argv).detail ?? 'full';
    return detail === 'compact' || (!explicitDetail && (0, automation_protocol_1.getSelectedAutomationProtocolVersion)() === 2);
}
function projectRunPack(result) {
    const explicitDetail = process.argv.some((token) => token === '--detail' || token.startsWith('--detail='));
    const detail = (0, output_1.detectOutputProjectionOptions)(process.argv).detail ?? 'full';
    const compact = detail === 'compact' || (!explicitDetail && (0, automation_protocol_1.getSelectedAutomationProtocolVersion)() === 2);
    if (!compact)
        return result;
    return {
        schemaVersion: result.schemaVersion,
        packManifestVersion: result.packManifestVersion,
        operation: result.operation,
        sourceRunDirectory: result.sourceRunDirectory,
        destination: result.destination,
        sourceSnapshot: result.sourceSnapshot,
        logicalPackDigest: result.logicalPackDigest,
        packId: result.packId,
        sourceBytes: result.sourceBytes,
        uniqueObjectBytes: result.uniqueObjectBytes,
        projectedBytes: result.projectedBytes,
        duplicateCount: result.duplicateCount,
        logicalEntryCount: result.logicalEntryCount,
        uniqueObjectCount: result.uniqueObjectCount,
        intendedPathCount: result.intendedPaths.length,
        changedPathCount: result.changedPaths.length,
        expectedCount: result.expected.length,
        writeOutcome: result.writeOutcome,
        transactionId: result.transactionId,
        conflictCount: result.conflicts.length,
        sourceUnchanged: result.sourceUnchanged,
        readOnly: result.readOnly,
        recovery: result.recovery,
        noWriteBoundary: result.noWriteBoundary,
        failure: result.failure,
    };
}
function assertResumable(value) {
    if (value.state === 'fresh' || value.state === 'incomplete')
        return;
    if (value.state === 'conflict') {
        throw new errors_1.RuntimeError({
            code: 'LIFECYCLE_RUN_SELECTION_CONFLICT',
            exitCode: errors_1.RuntimeExitCode.CONCURRENCY_CONFLICT,
            message: 'Lifecycle run context conflicts with the explicitly selected artifact.',
            details: [
                `Manifest active artifact: ${value.manifest.activeArtifactPath}`,
                `Selected artifact: ${value.conflict?.selectedArtifactPath}`,
                'No manifest or evidence state was changed.',
            ],
            recoveryActions: [
                (0, errors_1.createNonCallableRecoveryAction)({
                    id: 'recovery.lifecycle-run.select-current-artifact',
                    command: 'resume run resume',
                    explanation: 'Review the current active artifact and select the intended run explicitly.',
                    reason: 'The shared boundary cannot choose between conflicting artifact identities.',
                }),
            ],
        });
    }
    throw new errors_1.RuntimeError({
        code: 'LIFECYCLE_RUN_STALE',
        exitCode: errors_1.RuntimeExitCode.STALE_EVIDENCE,
        message: 'Lifecycle run context is stale and cannot authorize resume guidance.',
        details: [
            ...value.staleReasons.map((reason) => `Reason: ${reason}`),
            'Manifest history was preserved as evidence and no state was changed.',
        ],
        recoveryActions: [
            (0, errors_1.createNonCallableRecoveryAction)({
                id: 'recovery.lifecycle-run.revise-contract',
                command: 'resume run revise-contract',
                explanation: 'Use the narrow contract-revision transition only when the stale reasons are bounded to the selected phase or active planning artifact and a current clean phase review explicitly authorizes rollback.',
                reason: 'The current review path, actor, authorization time, bounded reason, and rollback gate cannot be inferred from stale manifest history.',
            }),
        ],
    });
}
function assertContractRevisionApplied(result) {
    if (result.writeOutcome === 'no-write' && !result.idempotent && result.failure !== null) {
        throw new errors_1.RuntimeError({
            code: 'LIFECYCLE_RUN_CONTRACT_REVISION_NO_WRITE_FAILURE',
            exitCode: errors_1.RuntimeExitCode.ERROR,
            message: 'Lifecycle run contract revision stopped before applying any repository write.',
            details: [result.failure, 'Refresh current status and preview before retrying.'],
            recoveryActions: [
                (0, errors_1.createNonCallableRecoveryAction)({
                    id: 'recovery.lifecycle-run.revise-contract.no-write-failure',
                    command: 'resume run status',
                    explanation: 'Confirm the manifest and indexed evidence remain current before creating a new preview.',
                    reason: 'The failed in-process transaction preview cannot be safely reused.',
                }),
            ],
        });
    }
    if (result.writeOutcome === 'conflict') {
        throw new errors_1.RuntimeError({
            code: 'LIFECYCLE_RUN_CONTRACT_REVISION_CONFLICT',
            exitCode: errors_1.RuntimeExitCode.CONCURRENCY_CONFLICT,
            message: 'Lifecycle run contract revision preconditions changed before apply.',
            details: [
                ...result.conflicts.map((conflict) => `${conflict.path}: expected ${conflict.expectedState}; observed ${conflict.observedState}`),
                'No contract revision writes were applied; refresh the preview from current repository state.',
            ],
            recoveryActions: [
                (0, errors_1.createNonCallableRecoveryAction)({
                    id: 'recovery.lifecycle-run.revise-contract.refresh-preview',
                    command: 'resume run revise-contract',
                    explanation: 'Revalidate the current review and all repository preconditions before retrying the same bounded transition.',
                    reason: 'The exact current command inputs must be supplied again and cannot be recovered from a stale preview.',
                }),
            ],
        });
    }
    if (result.writeOutcome === 'incomplete') {
        throw new errors_1.RuntimeError({
            code: 'LIFECYCLE_RUN_CONTRACT_REVISION_INCOMPLETE',
            exitCode: errors_1.RuntimeExitCode.PARTIAL_MUTATION,
            message: 'Lifecycle run contract revision could not prove a complete atomic outcome.',
            details: [
                `Transaction: ${result.transactionId ?? 'unknown'}`,
                `Recovery record: ${result.recoveryPath ?? 'unavailable'}`,
                result.failure ?? 'Inspect the durable transaction record before any retry.',
            ],
            writeOutcome: 'partial',
            recoveryActions: [
                (0, errors_1.createNonCallableRecoveryAction)({
                    id: 'recovery.lifecycle-run.revise-contract.inspect-transaction',
                    command: 'resume run status',
                    explanation: 'Inspect the lifecycle manifest and durable transaction state before deciding whether repair is safe.',
                    reason: 'Partial transaction state requires operator inspection and cannot be repaired automatically.',
                }),
            ],
        });
    }
}
function assertContractRevisionAdoptionApplied(result) {
    if (result.writeOutcome === 'conflict') {
        throw new errors_1.RuntimeError({
            code: 'LIFECYCLE_RUN_CONTRACT_REVISION_ADOPTION_CONFLICT',
            exitCode: errors_1.RuntimeExitCode.CONCURRENCY_CONFLICT,
            message: 'Contract-revision checkpoint adoption preconditions changed before apply.',
            details: [
                ...result.conflicts.map((conflict) => `${conflict.path}: expected ${conflict.expectedState}; observed ${conflict.observedState}`),
                'No source evidence was changed; refresh the exact source/replacement preview.',
            ],
            writeOutcome: 'no-writes',
        });
    }
    if (result.writeOutcome === 'incomplete') {
        throw new errors_1.RuntimeError({
            code: 'LIFECYCLE_RUN_CONTRACT_REVISION_ADOPTION_INCOMPLETE',
            exitCode: errors_1.RuntimeExitCode.PARTIAL_MUTATION,
            message: 'Contract-revision checkpoint adoption could not prove a complete atomic outcome.',
            details: [
                `Transaction: ${result.transactionId ?? 'unknown'}`,
                `Recovery record: ${result.recoveryPath ?? 'unavailable'}`,
                result.failure ?? 'Inspect the durable transaction record before retrying.',
                'The selected source run was not a write target.',
            ],
            writeOutcome: 'partial',
        });
    }
}
function normalizeContractRevisionAdoptionError(error) {
    if (!(error instanceof task_contract_revision_adoption_1.TaskContractRevisionAdoptionError))
        return error;
    const staleCodes = new Set(['stale-task-revision', 'stale-preview']);
    const concurrencyCodes = new Set(['checkpoint-conflict']);
    return new errors_1.RuntimeError({
        code: `LIFECYCLE_RUN_CONTRACT_REVISION_ADOPTION_${error.code.replace(/-/g, '_').toUpperCase()}`,
        exitCode: concurrencyCodes.has(error.code)
            ? errors_1.RuntimeExitCode.CONCURRENCY_CONFLICT
            : staleCodes.has(error.code)
                ? errors_1.RuntimeExitCode.STALE_EVIDENCE
                : error.code === 'invalid-input'
                    ? errors_1.RuntimeExitCode.USAGE
                    : errors_1.RuntimeExitCode.INVALID_CONFIG,
        message: 'Contract-revision checkpoint adoption was rejected.',
        details: [
            error.message,
            'No source run, source evidence, task definition, implementation summary, replacement manifest, or adoption receipt was changed.',
        ],
        writeOutcome: 'no-writes',
        recoveryActions: [(0, errors_1.createNonCallableRecoveryAction)({
                id: 'recovery.lifecycle-run.adopt-contract-revision.refresh-preview',
                command: 'resume run adopt-contract-revision',
                explanation: 'Refresh the exact source run, replacement run, task revision, and attempt lineage before retrying.',
                reason: 'Ambiguous or changed lineage cannot be selected by the failure boundary.',
            })],
    });
}
function normalizeContractRevisionError(error) {
    if (!(error instanceof lifecycle_run_context_1.LifecycleRunContractRevisionError))
        return error;
    const concurrencyCodes = new Set(['artifact-conflict', 'evidence-conflict', 'review-destination-conflict']);
    const staleCodes = new Set(['review-stale', 'stale-preview', 'unbounded-stale-state']);
    const exitCode = concurrencyCodes.has(error.code)
        ? errors_1.RuntimeExitCode.CONCURRENCY_CONFLICT
        : staleCodes.has(error.code)
            ? errors_1.RuntimeExitCode.STALE_EVIDENCE
            : errors_1.RuntimeExitCode.INVALID_CONFIG;
    return new errors_1.RuntimeError({
        code: `LIFECYCLE_RUN_CONTRACT_REVISION_${error.code.replace(/-/g, '_').toUpperCase()}`,
        exitCode,
        message: error.message,
        details: [
            `Contract revision reason: ${error.code}`,
            'The transition failed closed without changing the lifecycle manifest or indexed evidence.',
        ],
        recoveryActions: [
            (0, errors_1.createNonCallableRecoveryAction)({
                id: 'recovery.lifecycle-run.revise-contract.inspect-current-state',
                command: 'resume run status',
                explanation: 'Inspect current manifest completeness, digests, selected artifact identity, and stale reasons before retrying.',
                reason: 'Current run directory and selected artifact inputs are required and cannot be safely inferred.',
            }),
        ],
    });
}
function emitRunResult(command, commandInstance, data, write, heading) {
    const format = (0, output_1.resolveOutputFormat)(commandInstance.optsWithGlobals?.().format);
    if (format === null)
        throw (0, errors_1.createUsageError)('Output format must be one of: text, json.');
    (0, output_1.emitSuccess)({
        command,
        format,
        data,
        text: [
            heading,
            `Run: ${data.manifest?.runId ?? data.runId ?? 'unknown'}`,
            `State: ${data.state ?? data.writeOutcome ?? 'observed'}`,
            ...(data.statusProjection === undefined && data.commandEnvelopeOutcomes === undefined
                ? []
                : [
                    `Current gate: ${data.statusProjection?.currentGate ?? data.currentGate}`,
                    `Terminal state: ${data.statusProjection?.terminalState ?? data.terminalState ?? 'not terminal'}`,
                    `Evidence: ${data.statusProjection?.entryCount ?? data.entryCount} entries / ${data.statusProjection?.evidenceBytes ?? data.evidenceBytes} bytes`,
                    `Contract revisions: ${data.statusProjection?.contractRevisionCount ?? data.contractRevisionCount}`,
                    `Validation outcomes: passed ${data.statusProjection?.validationOutcomes?.passed ?? data.validationOutcomes?.passed ?? 0}, failed ${data.statusProjection?.validationOutcomes?.failed ?? data.validationOutcomes?.failed ?? 0}, previews ${data.statusProjection?.validationOutcomes?.previews ?? data.validationOutcomes?.previews ?? 0}, superseded ${data.statusProjection?.validationOutcomes?.superseded ?? data.validationOutcomes?.superseded ?? 0}`,
                    `Next action: ${data.statusProjection?.nextAction ?? data.nextAction}`,
                ]),
            (0, output_1.renderTerminalBoundary)(write
                ? { kind: 'write-applied', target: data.manifestPath, stateSurface: 'repository-local lifecycle run context' }
                : { kind: 'read-only' }),
        ].join('\n'),
    });
}
function useCompactRunStatus() {
    const explicitDetail = process.argv.some((token) => token === '--detail' || token.startsWith('--detail='));
    const detail = (0, output_1.detectOutputProjectionOptions)(process.argv).detail ?? 'full';
    return detail === 'compact' || (!explicitDetail && (0, automation_protocol_1.getSelectedAutomationProtocolVersion)() === 2);
}
function projectContractRevisionResult(result) {
    if (!useCompactContractRevision())
        return result;
    const { invalidatedEntryIds: _invalidatedEntryIds, ...checkpoint } = result.checkpoint;
    return {
        runId: result.runId,
        runDirectory: result.runDirectory,
        manifestPath: result.manifestPath,
        checkpoint: {
            ...checkpoint,
            invalidatedEntryCount: result.checkpoint.invalidatedEntryIds.length,
        },
        reviewEntry: result.reviewEntry,
        impact: {
            schemaVersion: result.impact.schemaVersion,
            impactDigest: result.impact.impactDigest,
            counts: result.impact.counts,
            evidenceBytes: result.impact.evidenceBytes,
            downstreamArtifacts: {
                contractPath: result.impact.downstreamArtifacts.contractPath,
                contractFingerprint: result.impact.downstreamArtifacts.contractFingerprint,
                contractState: result.impact.downstreamArtifacts.contractState,
                relationshipCount: result.impact.downstreamArtifacts.relationshipIds.length,
                pathCount: result.impact.downstreamArtifacts.paths.length,
                unknownProducerPathCount: result.impact.downstreamArtifacts.unknownProducerPaths.length,
                issues: result.impact.downstreamArtifacts.issues,
            },
        },
        impactBudget: result.impactBudget,
        impactAuthorization: result.impactAuthorization,
        manifestRevision: result.manifestRevision,
        nextManifestRevision: result.nextManifestRevision,
        idempotent: result.idempotent,
        intendedPaths: result.intendedPaths,
        changedPaths: result.changedPaths,
        expectedCount: result.expected.length,
        writeOutcome: result.writeOutcome,
        transactionId: result.transactionId,
        conflicts: result.conflicts,
        recoveryPath: result.recoveryPath,
        failure: result.failure,
    };
}
function useCompactContractRevision() {
    const explicitDetail = process.argv.some((token) => token === '--detail' || token.startsWith('--detail='));
    const detail = (0, output_1.detectOutputProjectionOptions)(process.argv).detail ?? 'full';
    return detail === 'compact' || (!explicitDetail && (0, automation_protocol_1.getSelectedAutomationProtocolVersion)() === 2);
}
function parseNonNegativeSafeInteger(value, label) {
    if (typeof value !== 'string' || !/^(0|[1-9][0-9]*)$/u.test(value)) {
        throw (0, errors_1.createUsageError)(`${label} must be a non-negative safe integer.`);
    }
    const parsed = Number(value);
    if (!Number.isSafeInteger(parsed)) {
        throw (0, errors_1.createUsageError)(`${label} must be a non-negative safe integer.`);
    }
    return parsed;
}
function collect(value, previous) {
    return [...previous, value];
}
function repositoryRoot(commandInstance) {
    const root = (commandInstance?.parent?.parent?.parent ?? commandInstance);
    return (root?.configRepositoryContext ?? (0, runtime_contract_1.createRepositoryContext)((0, runtime_contract_1.detectRepositoryRoot)(), false)).root;
}
