"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.createWorkCreateCommand = createWorkCreateCommand;
exports.createWorkCreationOutcomeError = createWorkCreationOutcomeError;
const node_fs_1 = __importDefault(require("node:fs"));
const node_path_1 = __importDefault(require("node:path"));
const promises_1 = require("node:readline/promises");
const errors_1 = require("../../../lib/errors");
const output_1 = require("../../../lib/output");
const basic_workflow_1 = require("../../../lib/planning/basic-workflow");
const ordered_root_identity_1 = require("../../../lib/planning/ordered-root-identity");
const spec_readiness_1 = require("../../../lib/spec-readiness");
const work_creation_1 = require("../../../lib/work-creation");
const runtime_contract_1 = require("../../../lib/runtime/runtime-contract");
const global_format_1 = require("../global-format");
async function createWorkCreateCommand() {
    const { Command } = await import('commander');
    const command = new Command('create');
    command
        .description('Preview or create one canonical Basic task pair, Structured work overview, or Governed numbered slice root.')
        .option('--spec <path>', 'Canonical registered specification path; repeat for multiple sources.', collectValue, [])
        .option('--level <level>', 'Workflow level: basic, structured, or governed.')
        .option('--work-id <id>', 'Explicit lowercase kebab-case Structured work identity; optional for one source specification and required for multiple sources.')
        .option('--implementation-order <order|next>', 'Basic or Structured positive root order (at least two digits), or next available order.')
        .option('--slice-id <id>', 'Optional explicit ordered Governed slice identity with a prefix of at least two digits.')
        .option('--initiative-id <id>', 'Optional non-hierarchical Governed initiative identity.')
        .option('--task <json>', 'Complete Basic task contract as one JSON object.')
        .option('--task-id <id>', 'Basic task identity for direct flag or interactive input.')
        .option('--title <title>', 'Optional Basic task title.')
        .option('--objective <text>', 'Basic task objective.')
        .option('--target-path <path>', 'Basic task target path; repeat as needed.', collectValue, [])
        .option('--current-behavior <text>', 'Observed behavior before the Basic task.')
        .option('--desired-behavior <text>', 'Required behavior after the Basic task.')
        .option('--acceptance-criterion <text>', 'Basic acceptance criterion; repeat as needed.', collectValue, [])
        .option('--validation-command <command>', 'Basic validation command; repeat as needed.', collectValue, [])
        .option('--rollback-recovery <text>', 'Basic rollback or recovery guidance.')
        .option('--dependency <path>', 'Resolved Basic dependency artifact; repeat as needed.', collectValue, [])
        .option('--constraint <text>', 'Basic task constraint; repeat as needed.', collectValue, [])
        .option('--input-file <path>', 'Read one complete Basic task contract from a JSON file.')
        .option('--stdin', 'Read one complete Basic task contract as JSON from standard input.')
        .option('--interactive', 'Prompt on an attached TTY for one bounded Basic task contract.')
        .option('--agent-mode <mode>', 'Task or default child-task agent mode: autonomous, guided, or interactive.')
        .option('--evidence-profile <profile>', 'Task or default child-task evidence profile: runtime, contract, or hybrid.')
        .option('--confirm-independent', 'Explicitly assert that a second Basic task is independent.')
        .option('--dry-run', 'Preview canonical paths, policy, and write preconditions without writing.')
        .action(async (_, commandInstance) => {
        const format = (0, output_1.resolveOutputFormat)((0, global_format_1.getGlobalFormat)(commandInstance));
        if (format === null)
            throw (0, errors_1.createUsageError)('Output format must be one of: text, json.');
        const repository = (0, runtime_contract_1.createRepositoryContext)((0, runtime_contract_1.detectRepositoryRoot)(), false);
        const options = commandInstance.opts();
        let result;
        let basicBoundary = null;
        try {
            if (options.level === 'basic') {
                if (options.spec.length > 0 ||
                    options.workId !== undefined ||
                    options.sliceId !== undefined ||
                    options.initiativeId !== undefined) {
                    throw new work_creation_1.StructuredWorkCreationError('unsupported-level', 'Specification, work, slice, and initiative evidence cannot be used to create Basic work.');
                }
                const task = await normalizeBasicTaskInput(repository.root, options, format);
                basicBoundary = (0, basic_workflow_1.evaluateBasicCreationBoundary)({
                    requestedTaskId: task.taskId,
                    existingTaskIds: discoverExistingBasicTaskIds(repository.root),
                    confirmIndependent: options.confirmIndependent === true,
                });
                if (!basicBoundary.allowed) {
                    throw createSecondBasicTaskBoundaryError(basicBoundary);
                }
                const preview = (0, work_creation_1.previewBasicTaskPairCreationSync)({
                    repositoryRoot: repository.root,
                    implementationOrder: options.implementationOrder,
                    task: {
                        ...task,
                        agentMode: options.agentMode ?? task.agentMode,
                        evidenceProfile: options.evidenceProfile ?? task.evidenceProfile,
                    },
                });
                result = options.dryRun === true ? preview : (0, work_creation_1.applyBasicTaskPairCreationSync)(preview);
            }
            else {
                rejectBasicOptionsForWorkOverview(options);
                if (options.level === 'governed') {
                    if (options.workId !== undefined || options.implementationOrder !== undefined) {
                        throw new work_creation_1.StructuredWorkCreationError('invalid-request', 'Governed creation accepts --slice-id and rejects --work-id or --implementation-order.');
                    }
                    const preview = (0, work_creation_1.previewGovernedWorkCreationSync)({
                        repositoryRoot: repository.root,
                        specificationPaths: options.spec,
                        level: options.level,
                        sliceId: options.sliceId,
                        initiativeId: options.initiativeId,
                        authorizeRegistryRouting: true,
                        agentMode: options.agentMode,
                        evidenceProfile: options.evidenceProfile,
                    });
                    result = options.dryRun === true ? preview : (0, work_creation_1.applyGovernedWorkCreationSync)(preview);
                }
                else {
                    if (options.sliceId !== undefined || options.initiativeId !== undefined) {
                        throw new work_creation_1.StructuredWorkCreationError('invalid-request', 'Structured creation accepts --work-id and rejects Governed --slice-id or --initiative-id.');
                    }
                    const preview = (0, work_creation_1.previewStructuredWorkCreationSync)({
                        repositoryRoot: repository.root,
                        specificationPaths: options.spec,
                        level: options.level,
                        workId: options.workId,
                        implementationOrder: options.implementationOrder,
                        agentMode: options.agentMode,
                        evidenceProfile: options.evidenceProfile,
                    });
                    result = options.dryRun === true ? preview : (0, work_creation_1.applyStructuredWorkCreationSync)(preview);
                }
            }
        }
        catch (error) {
            throw normalizeWorkCreateError(error, repository.root, options);
        }
        if (result.writeOutcome !== 'previewed' &&
            result.writeOutcome !== 'committed' &&
            !(result.workflowLevel === 'governed' && result.writeOutcome === 'no-write')) {
            throw createWorkCreationOutcomeError(result);
        }
        (0, output_1.emitSuccess)({
            command: 'work create',
            format,
            text: result.workflowLevel === 'basic'
                ? renderBasicSuccessText(result, basicBoundary)
                : renderWorkOverviewSuccessText(result),
            data: result.workflowLevel === 'basic'
                ? { ...publicResult(result), basicWorkflow: basicBoundary }
                : publicResult(result),
        });
    });
    return command;
}
function collectValue(value, previous) {
    return [...previous, value];
}
async function normalizeBasicTaskInput(repositoryRoot, options, format) {
    const selectedModes = [options.task, options.inputFile, options.stdin === true, options.interactive === true].filter(Boolean).length;
    const hasDirectFlags = options.taskId !== undefined ||
        options.title !== undefined ||
        options.objective !== undefined ||
        options.targetPath.length > 0 ||
        options.currentBehavior !== undefined ||
        options.desiredBehavior !== undefined ||
        options.acceptanceCriterion.length > 0 ||
        options.validationCommand.length > 0 ||
        options.rollbackRecovery !== undefined ||
        options.dependency.length > 0 ||
        options.constraint.length > 0;
    if (selectedModes > 1 || (selectedModes > 0 && hasDirectFlags)) {
        throw (0, errors_1.createUsageError)('Choose exactly one Basic input mode: --task, --input-file, --stdin, --interactive, or direct task flags.', ['Input modes cannot be combined.']);
    }
    if (options.interactive === true) {
        if (format === 'json') {
            throw (0, errors_1.createUsageError)('Interactive Basic creation is unavailable with JSON output.');
        }
        if (process.stdin.isTTY !== true || process.stdout.isTTY !== true) {
            throw (0, errors_1.createUsageError)('Interactive Basic creation requires an attached TTY.', [
                'Use --task, --input-file, --stdin, or direct task flags for automation.',
            ]);
        }
        return promptForBasicTask();
    }
    if (options.task !== undefined)
        return parseBasicTaskJson(options.task, '--task');
    if (options.inputFile !== undefined) {
        const absolute = node_path_1.default.isAbsolute(options.inputFile)
            ? options.inputFile
            : node_path_1.default.resolve(repositoryRoot, options.inputFile);
        let text;
        try {
            text = node_fs_1.default.readFileSync(absolute, 'utf8');
        }
        catch (error) {
            throw (0, errors_1.createUsageError)(`Basic input file '${options.inputFile}' is not readable.`, [
                error instanceof Error ? error.message : 'Could not read the selected file.',
            ]);
        }
        return parseBasicTaskJson(text, options.inputFile);
    }
    if (options.stdin === true)
        return parseBasicTaskJson(node_fs_1.default.readFileSync(0, 'utf8'), 'stdin');
    return {
        taskId: options.taskId ?? '',
        ...(options.title === undefined ? {} : { title: options.title }),
        objective: options.objective ?? '',
        targetPaths: options.targetPath,
        ...(options.currentBehavior === undefined ? {} : { currentBehavior: options.currentBehavior }),
        desiredBehavior: options.desiredBehavior ?? '',
        acceptanceCriteria: options.acceptanceCriterion,
        validationCommands: options.validationCommand,
        rollbackRecovery: options.rollbackRecovery ?? '',
        dependencies: options.dependency,
        constraints: options.constraint,
    };
}
function parseBasicTaskJson(text, source) {
    let value;
    try {
        value = JSON.parse(text);
    }
    catch {
        throw (0, errors_1.createUsageError)(`Basic task input from '${source}' must be valid JSON.`);
    }
    if (value === null || typeof value !== 'object' || Array.isArray(value)) {
        throw (0, errors_1.createUsageError)(`Basic task input from '${source}' must be one JSON object.`);
    }
    return value;
}
async function promptForBasicTask() {
    const prompt = (0, promises_1.createInterface)({ input: process.stdin, output: process.stdout });
    try {
        const taskId = (await prompt.question('Task id: ')).trim();
        const title = (await prompt.question('Title (optional): ')).trim();
        const objective = (await prompt.question('Objective: ')).trim();
        const targetPaths = splitPromptList(await prompt.question('Target paths (comma-separated): '), ',');
        const currentBehavior = (await prompt.question('Current behavior (optional): ')).trim();
        const desiredBehavior = (await prompt.question('Desired behavior: ')).trim();
        const acceptanceCriteria = splitPromptList(await prompt.question('Acceptance criteria (semicolon-separated): '), ';');
        const validationCommands = splitPromptList(await prompt.question('Validation commands (semicolon-separated): '), ';');
        const rollbackRecovery = (await prompt.question('Rollback / recovery: ')).trim();
        return {
            taskId,
            ...(title === '' ? {} : { title }),
            objective,
            targetPaths,
            ...(currentBehavior === '' ? {} : { currentBehavior }),
            desiredBehavior,
            acceptanceCriteria,
            validationCommands,
            rollbackRecovery,
        };
    }
    finally {
        prompt.close();
    }
}
function splitPromptList(value, separator) {
    return value
        .split(separator)
        .map((entry) => entry.trim())
        .filter((entry) => entry !== '');
}
function rejectBasicOptionsForWorkOverview(options) {
    const basicOptionsPresent = options.task !== undefined ||
        options.taskId !== undefined ||
        options.title !== undefined ||
        options.objective !== undefined ||
        options.targetPath.length > 0 ||
        options.currentBehavior !== undefined ||
        options.desiredBehavior !== undefined ||
        options.acceptanceCriterion.length > 0 ||
        options.validationCommand.length > 0 ||
        options.rollbackRecovery !== undefined ||
        options.dependency.length > 0 ||
        options.constraint.length > 0 ||
        options.inputFile !== undefined ||
        options.stdin === true ||
        options.interactive === true ||
        options.confirmIndependent === true;
    if (basicOptionsPresent) {
        throw (0, errors_1.createUsageError)('Basic task input options require explicit --level basic.', [
            'Structured and Governed creation accept specification evidence and optional work defaults only.',
        ]);
    }
}
function normalizeWorkCreateError(error, repositoryRoot, options) {
    if (error instanceof errors_1.RuntimeError)
        return error;
    const readiness = normalizeMissingSpecReadiness(error, repositoryRoot, options);
    if (readiness !== null)
        return readiness;
    if (error instanceof work_creation_1.StructuredWorkCreationError || error instanceof work_creation_1.BasicTaskCreationError) {
        const conflict = error.code === 'destination-conflict' || error.code === 'stale-preview';
        return new errors_1.RuntimeError({
            message: error.message,
            code: `WORK_CREATE_${error.code.toUpperCase().replace(/-/g, '_')}`,
            exitCode: conflict ? errors_1.RuntimeExitCode.CONCURRENCY_CONFLICT : errors_1.RuntimeExitCode.USAGE,
            details: [
                conflict
                    ? 'Refresh the work creation preview after inspecting current canonical planning evidence.'
                    : 'Correct the selected Basic task contract or Structured/Governed specification evidence before retrying.',
            ],
        });
    }
    if (error instanceof Error) {
        return (0, errors_1.createUsageError)(error.message, ['No Basic, Structured, or Governed planning write was accepted.']);
    }
    return (0, errors_1.createUsageError)('Invalid work creation input.');
}
function normalizeMissingSpecReadiness(error, repositoryRoot, options) {
    if (options.level === 'basic' || options.spec.length === 0)
        return null;
    for (const selectedSpecPath of options.spec) {
        let resolution;
        try {
            resolution = (0, spec_readiness_1.resolveSpecificationPlanningReadinessSync)(repositoryRoot, selectedSpecPath);
        }
        catch {
            continue;
        }
        if (resolution.status !== 'missing')
            continue;
        const reviewArgv = [
            'day-shift',
            'spec',
            'review',
            '--spec',
            resolution.specPath,
            '--format',
            'json',
        ];
        const dispositionHandoff = [
            'Run the callable read-only spec review action and persist its complete JSON result at a selected repository-local path.',
            'If that current review recommends ready with no unresolved findings, preview spec disposition with --planning-readiness ready, --review-result <review-result.json>, explicit --recorded-by and --recorded-at, and --dry-run.',
            'Inspect the exact disposition preview before applying it without --dry-run; only then retry work create with the original selected specification set.',
        ];
        return new errors_1.RuntimeError({
            message: 'Work creation is blocked because a selected specification has no planning-readiness disposition.',
            code: 'WORK_CREATE_SPEC_READINESS_MISSING',
            exitCode: errors_1.RuntimeExitCode.INVALID_CONFIG,
            writeOutcome: 'no-writes',
            details: [
                `specId: ${resolution.specId}`,
                `specPath: ${resolution.specPath}`,
                `specRevision: ${resolution.currentSpecRevision}`,
                `dispositionPath: ${resolution.dispositionPath}`,
                `readinessStatus: ${resolution.status}`,
                ...dispositionHandoff,
                `Underlying routing failure: ${error instanceof Error ? error.message : String(error)}`,
                'No Basic, Structured, Governed, registry, review, or disposition file was written.',
            ],
            findings: [
                {
                    code: 'WORK_CREATE_SPEC_READINESS_MISSING',
                    severity: 'error',
                    message: `Specification '${resolution.specId}' requires an explicit review and disposition before planning.`,
                    path: resolution.specPath,
                    reason: 'missing-planning-readiness-disposition',
                    recommendedCommand: reviewArgv.join(' '),
                    recovery: dispositionHandoff,
                    noWriteBoundary: 'Missing specification readiness blocks work creation before any planning write.',
                },
            ],
            recoveryActions: [
                (0, errors_1.createDescriptorBackedRecoveryAction)({
                    command: 'spec review',
                    argv: reviewArgv,
                    explanation: 'Produce the current read-only review required by the explicit planning-readiness disposition handoff.',
                    selectedArtifactPath: resolution.specPath,
                }),
            ],
        });
    }
    return null;
}
function createWorkCreationOutcomeError(result) {
    const basic = result.workflowLevel === 'basic';
    const levelLabel = basic ? 'Basic' : result.workflowLevel === 'governed' ? 'Governed' : 'Structured';
    const details = [
        `workflowLevel: ${result.workflowLevel}`,
        ...(basic
            ? [`taskId: ${result.taskId}`, `taskDefinitionPath: ${result.taskDefinitionPath}`]
            : result.workflowLevel === 'governed'
                ? [`sliceId: ${result.sliceId}`, `sliceOverviewPath: ${result.sliceOverviewPath}`]
                : [`workId: ${result.workId}`, `overviewPath: ${result.overviewPath}`]),
        `writeOutcome: ${result.writeOutcome}`,
        `nextAction: ${result.nextAction}`,
        ...(result.recoveryPath === null ? [] : [`recoveryPath: ${result.recoveryPath}`]),
    ];
    if (result.writeOutcome === 'conflict') {
        return new errors_1.RuntimeError({
            message: basic ? 'Basic task-pair creation preview is stale.' : `${levelLabel} work creation preview is stale.`,
            code: 'WORK_CREATE_CONFLICT',
            exitCode: errors_1.RuntimeExitCode.CONCURRENCY_CONFLICT,
            details,
        });
    }
    if (result.writeOutcome === 'incomplete') {
        return new errors_1.RuntimeError({
            message: basic
                ? 'Basic task-pair creation stopped after a partial repository mutation.'
                : `${levelLabel} work creation stopped after a partial repository mutation.`,
            code: 'WORK_CREATE_INCOMPLETE',
            exitCode: errors_1.RuntimeExitCode.PARTIAL_MUTATION,
            writeOutcome: 'partial',
            details,
            recoveryActions: [
                (0, errors_1.createNonCallableRecoveryAction)({
                    id: 'recovery.inspect-work-create-transaction',
                    explanation: `Inspect retained transaction evidence before retrying ${levelLabel} work creation.`,
                    reason: result.recoveryPath ?? 'The retained transaction path was unavailable.',
                }),
            ],
        });
    }
    return new errors_1.RuntimeError({
        message: basic
            ? 'Basic task-pair creation did not write its intended pair.'
            : `${levelLabel} work creation did not write its intended overview.`,
        code: 'WORK_CREATE_NO_WRITE',
        exitCode: errors_1.RuntimeExitCode.ERROR,
        details,
    });
}
function publicResult(result) {
    if (result.workflowLevel === 'basic')
        return { ...result };
    if (result.workflowLevel === 'governed') {
        return {
            workflowLevel: result.workflowLevel,
            workflowLevelSource: result.workflowLevelSource,
            sliceId: result.sliceId,
            sliceIdGenerated: result.sliceIdGenerated,
            implementationOrder: result.implementationOrder,
            sliceSlug: result.sliceSlug,
            initiativeId: result.initiativeId,
            sliceOverviewPath: result.sliceOverviewPath,
            specifications: result.specifications,
            defaultAgentMode: result.defaultAgentMode,
            defaultAgentModeSource: result.defaultAgentModeSource,
            defaultEvidenceProfile: result.defaultEvidenceProfile,
            defaultEvidenceProfileSource: result.defaultEvidenceProfileSource,
            expected: result.expected,
            intendedPaths: result.intendedPaths,
            changedPaths: result.changedPaths,
            writeOutcome: result.writeOutcome,
            transactionId: result.transactionId,
            conflicts: result.conflicts,
            recoveryPath: result.recoveryPath,
            failure: result.failure,
            nextAction: result.nextAction,
        };
    }
    return {
        workflowLevel: result.workflowLevel,
        workflowLevelSource: result.workflowLevelSource,
        workId: result.workId,
        workIdGenerated: result.workIdGenerated,
        workIdCollisionOrdinal: result.workIdCollisionOrdinal,
        implementationOrder: result.implementationOrder,
        implementationOrderSource: result.implementationOrderSource,
        orderedRootName: result.orderedRootName,
        rootInventoryFingerprint: result.rootInventoryFingerprint,
        overviewPath: result.overviewPath,
        specifications: result.specifications,
        defaultAgentMode: result.defaultAgentMode,
        defaultAgentModeSource: result.defaultAgentModeSource,
        defaultEvidenceProfile: result.defaultEvidenceProfile,
        defaultEvidenceProfileSource: result.defaultEvidenceProfileSource,
        expected: result.expected,
        intendedPaths: result.intendedPaths,
        changedPaths: result.changedPaths,
        writeOutcome: result.writeOutcome,
        transactionId: result.transactionId,
        conflicts: result.conflicts,
        recoveryPath: result.recoveryPath,
        failure: result.failure,
        nextAction: result.nextAction,
    };
}
function renderWorkOverviewSuccessText(result) {
    if (result.workflowLevel === 'governed') {
        return [
            result.writeOutcome === 'previewed'
                ? 'Previewed Governed slice-root creation.'
                : result.writeOutcome === 'no-write'
                    ? 'Governed numbered slice root is already current.'
                    : 'Created Governed numbered slice root.',
            'Workflow level: governed',
            `Workflow level source: ${result.workflowLevelSource}`,
            `Slice id: ${result.sliceId}`,
            `Slice id generated: ${result.sliceIdGenerated}`,
            `Implementation order: ${result.implementationOrder}`,
            `Slice slug: ${result.sliceSlug}`,
            `Initiative id: ${result.initiativeId ?? 'none'}`,
            `Slice overview path: ${result.sliceOverviewPath}`,
            `Specifications: ${result.specifications.map((entry) => `${entry.specId}@${entry.revision}`).join(', ')}`,
            `Default agent mode: ${result.defaultAgentMode} (${result.defaultAgentModeSource})`,
            `Default evidence profile: ${result.defaultEvidenceProfile} (${result.defaultEvidenceProfileSource})`,
            `Expected conditions: ${result.expected.map((entry) => `${entry.path}:${entry.kind}:${entry.expectedState}`).join(', ')}`,
            `Intended paths: ${result.intendedPaths.join(', ')}`,
            `Changed paths: ${result.changedPaths.join(', ') || 'none'}`,
            `Write outcome: ${result.writeOutcome}`,
            `Transaction id: ${result.transactionId ?? 'none'}`,
            `Recovery path: ${result.recoveryPath ?? 'none'}`,
            `Next action: ${result.nextAction}`,
        ].join('\n');
    }
    const levelLabel = 'Structured';
    return [
        result.writeOutcome === 'previewed'
            ? `Previewed ${levelLabel} work creation.`
            : `Created ${levelLabel} work overview.`,
        `Workflow level: ${result.workflowLevel}`,
        `Workflow level source: ${result.workflowLevelSource}`,
        `Work id: ${result.workId}`,
        `Work id generated: ${result.workIdGenerated}`,
        `Implementation order: ${result.implementationOrder}`,
        `Implementation order source: ${result.implementationOrderSource}`,
        `Ordered root name: ${result.orderedRootName}`,
        `Overview path: ${result.overviewPath}`,
        `Specifications: ${result.specifications.map((entry) => `${entry.specId}@${entry.revision}`).join(', ')}`,
        `Default agent mode: ${result.defaultAgentMode} (${result.defaultAgentModeSource})`,
        `Default evidence profile: ${result.defaultEvidenceProfile} (${result.defaultEvidenceProfileSource})`,
        `Expected conditions: ${result.expected.map((entry) => `${entry.path}:${entry.kind}:${entry.expectedState}`).join(', ')}`,
        `Intended paths: ${result.intendedPaths.join(', ')}`,
        `Changed paths: ${result.changedPaths.join(', ') || 'none'}`,
        `Write outcome: ${result.writeOutcome}`,
        `Transaction id: ${result.transactionId ?? 'none'}`,
        `Recovery path: ${result.recoveryPath ?? 'none'}`,
        `Next action: ${result.nextAction}`,
    ].join('\n');
}
function renderBasicSuccessText(result, boundary) {
    return [
        result.writeOutcome === 'previewed' ? 'Previewed Basic task-pair creation.' : 'Created Basic task pair.',
        `Workflow level: ${result.workflowLevel}`,
        `Task id: ${result.taskId}`,
        `Implementation order: ${result.implementationOrder}`,
        `Implementation order source: ${result.implementationOrderSource}`,
        `Ordered root name: ${result.orderedRootName}`,
        `Task definition: ${result.taskDefinitionPath}`,
        `Implementation summary: ${result.implementationSummaryPath}`,
        `Agent mode: ${result.agentMode} (${result.agentModeSource})`,
        `Evidence profile: ${result.evidenceProfile} (${result.evidenceProfileSource})`,
        `Expected conditions: ${result.expected.map((entry) => `${entry.path}:${entry.kind}:${entry.expectedState}`).join(', ')}`,
        `Intended paths: ${result.intendedPaths.join(', ')}`,
        `Changed paths: ${result.changedPaths.join(', ') || 'none'}`,
        `Write outcome: ${result.writeOutcome}`,
        `Transaction id: ${result.transactionId ?? 'none'}`,
        `Recovery path: ${result.recoveryPath ?? 'none'}`,
        `Basic boundary reason: ${boundary.reasonCode}`,
        `Independent confirmation: ${boundary.confirmationSatisfied ? 'confirmed' : 'not required'}`,
        `Promotion advice: ${boundary.promotion.recommended ? boundary.promotion.command : 'not recommended'}`,
        `Next action: ${result.nextAction}`,
    ].join('\n');
}
function discoverExistingBasicTaskIds(repositoryRoot) {
    return [
        ...(0, ordered_root_identity_1.inspectOrderedRootCollectionSync)({
            repositoryRoot,
            collectionPath: '.day-shift/planning/basic/tasks',
            context: 'basic-root',
        }).stableIds,
    ].sort((left, right) => left.localeCompare(right));
}
function createSecondBasicTaskBoundaryError(boundary) {
    const [existingTaskId] = boundary.existingTaskIds;
    return new errors_1.RuntimeError({
        code: 'BASIC_SECOND_TASK_CONFIRMATION_REQUIRED',
        exitCode: errors_1.RuntimeExitCode.USAGE,
        message: 'A Basic task pair already exists; second-task creation requires explicit independent confirmation.',
        details: [
            `reasonCode: ${boundary.reasonCode}`,
            `existingTaskIds: ${boundary.existingTaskIds.join(', ')}`,
            'No Basic pair, parent artifact, index, or promotion artifact was written.',
            'Rerun with --confirm-independent only when the new task is genuinely independent, or select promotion separately.',
        ],
        recoveryActions: [
            (0, errors_1.createDescriptorBackedRecoveryAction)({
                command: 'task promote',
                argv: [
                    'day-shift',
                    'task',
                    'promote',
                    '--task-definition',
                    `.day-shift/planning/basic/tasks/${existingTaskId}/task-definition.md`,
                    '--to',
                    'structured',
                    '--work-id',
                    '<work-id>',
                    '--spec',
                    '<canonical-spec-path>',
                ],
                explanation: `Build a no-write Structured promotion plan for '${existingTaskId}' after selecting a canonical planning-ready specification and destination work id.`,
            }),
        ],
    });
}
