"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.createTaskWorkspace = createTaskWorkspace;
const node_fs_1 = __importDefault(require("node:fs"));
const node_path_1 = __importDefault(require("node:path"));
const errors_1 = require("../../errors");
const output_1 = require("../../output");
const command_write_summary_1 = require("../../license/command-write-summary");
const artifact_policy_projection_1 = require("../artifact-policy-projection");
const authoring_policy_1 = require("../authoring-policy");
const front_matter_utils_1 = require("../front-matter-utils");
const governed_hierarchy_context_1 = require("../governed-hierarchy-context");
const runtime_acceptance_1 = require("../runtime-acceptance");
const scaffold_application_1 = require("../scaffold-application");
const task_scaffold_recovery_1 = require("../task-scaffold-recovery");
const scaffold_target_path_policy_1 = require("../scaffold-target-path-policy");
const upstream_specs_1 = require("../upstream-specs");
const artifact_parsing_1 = require("./artifact-parsing");
const artifact_rendering_1 = require("./artifact-rendering");
const projection_1 = require("./projection");
const runtime_scaffold_1 = require("./runtime-scaffold");
function createTaskWorkspace(repositoryRoot, options) {
    const runtimeEvidencePathPolicy = (0, scaffold_target_path_policy_1.readPlanningScaffoldTargetPathPolicy)(repositoryRoot);
    const milestoneOverviewPath = (0, artifact_parsing_1.resolveMilestoneOverviewPath)(repositoryRoot, options.milestoneOverviewPath);
    if (!node_fs_1.default.existsSync(milestoneOverviewPath.absolute)) {
        throw (0, errors_1.createUsageError)(`Parent milestone overview not found at '${milestoneOverviewPath.relative}'.`, ["Run day-shift milestone new first or pass the correct --milestone-overview path."]);
    }
    const milestoneOverviewText = node_fs_1.default.readFileSync(milestoneOverviewPath.absolute, "utf8");
    const parentExpectedRevision = (0, scaffold_application_1.planningScaffoldContentRevision)(milestoneOverviewText);
    const parsedMilestoneOverview = (0, artifact_parsing_1.parseMilestoneOverview)(milestoneOverviewPath.absolute, milestoneOverviewText);
    (0, governed_hierarchy_context_1.assertCanonicalGovernedParentSync)(repositoryRoot, {
        layer: "milestone",
        parentPath: milestoneOverviewPath.relative,
        slice: parsedMilestoneOverview.slice,
        phase: parsedMilestoneOverview.phase,
        milestone: parsedMilestoneOverview.milestone,
        policy: parsedMilestoneOverview.governedPolicy
    });
    const declaredTaskSlugsForDecomposition = [...parsedMilestoneOverview.tasks.keys()];
    const decompositionIssues = (0, authoring_policy_1.auditParentDecomposition)({
        artifactPath: milestoneOverviewPath.relative,
        markdownText: milestoneOverviewText,
        childKind: "task",
        declaredChildSlugs: declaredTaskSlugsForDecomposition
    });
    if (decompositionIssues.length > 0) {
        throw (0, errors_1.createUsageError)(`Planning decomposition contract rejected '${milestoneOverviewPath.relative}' before task writes.`, (0, authoring_policy_1.formatParentDecompositionIssues)(decompositionIssues));
    }
    const upstreamSpecs = (0, upstream_specs_1.normalizeUpstreamSpecsToLocalSpecPaths)(repositoryRoot, parsedMilestoneOverview.upstreamSpecs);
    const taskSlug = (0, artifact_parsing_1.resolveTaskSlug)(options.taskSlug);
    if (!declaredTaskSlugsForDecomposition.includes(taskSlug)) {
        throw (0, errors_1.createUsageError)(`Task '${taskSlug}' is not declared by '${milestoneOverviewPath.relative}'.`, ["Declare the task and update the authored target count and decomposition rationale before scaffolding."]);
    }
    const rawScaffoldEvidence = (0, authoring_policy_1.inspectChildScaffoldEvidence)({
        markdownText: milestoneOverviewText,
        childKind: "task",
        childSlug: taskSlug,
        declaredChildSlugs: declaredTaskSlugsForDecomposition,
        runtimeEvidencePathPolicy
    });
    const dependencyIssues = (0, authoring_policy_1.inspectOrderedTaskScaffoldDependencies)({
        repositoryRoot,
        tasks: declaredTaskSlugsForDecomposition.map((declaredTaskSlug) => {
            const evidence = declaredTaskSlug === taskSlug
                ? rawScaffoldEvidence
                : (0, authoring_policy_1.inspectChildScaffoldEvidence)({
                    markdownText: milestoneOverviewText,
                    childKind: "task",
                    childSlug: declaredTaskSlug,
                    declaredChildSlugs: declaredTaskSlugsForDecomposition,
                    runtimeEvidencePathPolicy
                });
            return {
                taskSlug: declaredTaskSlug,
                dependencies: evidence.dependencies,
                targetPaths: evidence.targetPaths,
                adapterPaths: evidence.adapterPaths
            };
        })
    });
    if (dependencyIssues.length > 0) {
        throw (0, errors_1.createInvalidConfigError)(`Planning dependency ordering rejected '${milestoneOverviewPath.relative}' before task writes.`, [
            ...dependencyIssues.map((issue) => issue.message),
            "No task-definition or implementation-summary write was attempted."
        ], dependencyIssues.map((issue) => ({
            code: issue.code,
            message: issue.message,
            severity: "error",
            path: milestoneOverviewPath.relative,
            evidence: {
                category: "planning-review",
                details: {
                    childKind: "task",
                    childSlug: issue.consumerTask,
                    consumerTask: issue.consumerTask,
                    dependencyPath: issue.dependencyPath,
                    producerTask: issue.producerTasks.length === 1
                        ? issue.producerTasks[0]
                        : null,
                    producerTasks: issue.producerTasks,
                    consumerSequence: issue.consumerSequence,
                    producerSequence: issue.producerSequences.length === 1
                        ? issue.producerSequences[0]
                        : null,
                    producerSequences: issue.producerSequences,
                    requiresRefinement: true,
                    noWriteRequired: true
                }
            }
        })));
    }
    (0, runtime_scaffold_1.assertExecutableScaffoldEvidence)(milestoneOverviewPath.relative, rawScaffoldEvidence);
    const taskTitle = (0, artifact_parsing_1.resolveTaskTitle)(taskSlug, options.taskTitle);
    if (options.recoverScaffold === true
        && options.taskTitle !== undefined
        && options.taskTitle.trim() !== "") {
        throw (0, errors_1.createUsageError)("--task-title cannot be combined with --recover-scaffold.", [
            "Recovery preserves the canonical generated task identity and replaces only a byte-exact untouched scaffold.",
            "No task artifact write was attempted."
        ]);
    }
    const taskDescription = (0, artifact_parsing_1.resolveTaskDescription)(taskSlug, options.taskDescription, parsedMilestoneOverview.tasks);
    const milestoneDirectoryPath = node_path_1.default.dirname(milestoneOverviewPath.absolute);
    const tasksDirectoryPath = node_path_1.default.join(milestoneDirectoryPath, "tasks");
    // Promotion reuses this same standard destination shape: tasks/<task-slug>/.
    const taskDirectoryPath = node_path_1.default.join(tasksDirectoryPath, taskSlug);
    const taskDefinitionPath = node_path_1.default.join(taskDirectoryPath, "task-definition.md");
    const implementationSummaryPath = node_path_1.default.join(taskDirectoryPath, "implementation-summary.md");
    const declaredTaskSlugs = [...parsedMilestoneOverview.tasks.keys()];
    const breakoutIssues = (0, runtime_acceptance_1.validateMilestoneRuntimeBreakout)(parsedMilestoneOverview.runtimeAcceptance, declaredTaskSlugs);
    if (breakoutIssues.length > 0) {
        throw (0, errors_1.createUsageError)(`Runtime acceptance contract rejected '${milestoneOverviewPath.relative}'.`, [...breakoutIssues]);
    }
    (0, runtime_scaffold_1.assertMaterializedRuntimeBreakout)({
        repositoryRoot,
        milestoneOverviewPath: milestoneOverviewPath.relative,
        runtimeAcceptance: parsedMilestoneOverview.runtimeAcceptance,
        requestedTaskSlug: taskSlug,
        validateOnly: options.validateOnly === true
    });
    const runtimeCriterionOwnership = (0, scaffold_application_1.inspectRuntimeCriterionOwnership)({
        milestoneMarkdownText: milestoneOverviewText,
        declaredChildSlugs: declaredTaskSlugs,
        parentCriterionIds: parsedMilestoneOverview.runtimeAcceptance?.required === true
            ? parsedMilestoneOverview.runtimeAcceptance.criterionIds
            : []
    });
    if (!runtimeCriterionOwnership.complete) {
        throw (0, errors_1.createUsageError)(`Runtime criterion ownership rejected '${milestoneOverviewPath.relative}' before task writes.`, [...runtimeCriterionOwnership.issues]);
    }
    const parentAcceptanceCriterionIds = (0, artifact_parsing_1.acceptanceCriterionIds)(parsedMilestoneOverview.acceptanceCriteria);
    const acceptanceCriterionOwnership = (0, scaffold_application_1.inspectRuntimeCriterionOwnership)({
        milestoneMarkdownText: milestoneOverviewText,
        declaredChildSlugs: declaredTaskSlugs,
        parentCriterionIds: parentAcceptanceCriterionIds
    });
    if (!acceptanceCriterionOwnership.complete) {
        throw (0, errors_1.createUsageError)(`Acceptance criterion ownership rejected '${milestoneOverviewPath.relative}' before task writes.`, [...acceptanceCriterionOwnership.issues]);
    }
    const executionMode = (0, runtime_acceptance_1.taskExecutionModeForRuntimeAcceptance)(parsedMilestoneOverview.runtimeAcceptance, taskSlug, declaredTaskSlugs);
    const assignedRuntimeCriterionIds = runtimeCriterionOwnership.childOwnership
        .find((ownership) => ownership.childSlug === taskSlug)?.criterionIds;
    const assignedCriterionIds = acceptanceCriterionOwnership.childOwnership
        .find((ownership) => ownership.childSlug === taskSlug)?.criterionIds;
    const acceptanceScopedScaffoldInspection = (0, scaffold_application_1.inspectAcceptanceScopedTaskScaffold)({
        milestoneMarkdownText: milestoneOverviewText,
        childSlug: taskSlug,
        taskDescription,
        parentAcceptanceCriteria: parsedMilestoneOverview.acceptanceCriteria,
        assignedCriterionIds: assignedCriterionIds ?? [],
        scaffoldEvidence: rawScaffoldEvidence
    });
    const acceptanceScopedScaffold = {
        ...acceptanceScopedScaffoldInspection,
        targetPaths: [
            ...new Set([
                ...acceptanceScopedScaffoldInspection.targetPaths,
                ...rawScaffoldEvidence.adapterPaths
            ])
        ],
        dependencies: (0, runtime_scaffold_1.normalizeScaffoldDependencyPaths)({
            milestoneOverviewPath: milestoneOverviewPath.relative,
            dependencies: [
                ...acceptanceScopedScaffoldInspection.dependencies,
                ...rawScaffoldEvidence.dependencies
            ]
        })
    };
    (0, runtime_scaffold_1.assertAcceptanceScopedScaffold)(milestoneOverviewPath.relative, acceptanceScopedScaffold);
    const scaffoldEvidence = {
        ...rawScaffoldEvidence,
        dependencies: acceptanceScopedScaffold.dependencies,
        targetPaths: acceptanceScopedScaffold.targetPaths,
        validationCommands: acceptanceScopedScaffold.validationCommands,
        rollback: acceptanceScopedScaffold.rollback
    };
    const inheritedRuntimeAcceptance = parsedMilestoneOverview.runtimeAcceptance === null
        ? null
        : (0, runtime_acceptance_1.childRuntimeAcceptanceMetadata)(parsedMilestoneOverview.runtimeAcceptance);
    const inheritedChildRuntimeAcceptance = inheritedRuntimeAcceptance === null
        ? null
        : {
            ...inheritedRuntimeAcceptance,
            criterionIds: assignedRuntimeCriterionIds === undefined
                ? inheritedRuntimeAcceptance.criterionIds
                : [...assignedRuntimeCriterionIds]
        };
    const inferredLegacyChildRuntimeAcceptance = inheritedChildRuntimeAcceptance === null
        && acceptanceCriterionOwnership.mode === "decomposed"
        && (assignedCriterionIds?.length ?? 0) > 0
        && executionMode === "runtime"
        ? {
            required: true,
            criterionIds: [...assignedCriterionIds],
            maxContractStreak: 1,
            breakoutTask: null,
            exception: null
        }
        : null;
    const childRuntimeAcceptance = inheritedChildRuntimeAcceptance ?? inferredLegacyChildRuntimeAcceptance;
    const requiresRefinement = childRuntimeAcceptance === null
        && executionMode !== "contract";
    const refinementFindings = requiresRefinement
        ? [(0, output_1.createAdvisoryValidationFinding)({
                code: "PLANNING_TASK_RUNTIME_ACCEPTANCE_REFINEMENT_REQUIRED",
                message: `Task '${taskSlug}' has runtime evidence but its parent contract does not provide explicit or deterministically decomposed runtime acceptance.`,
                path: milestoneOverviewPath.relative,
                advisoryReason: "weak-evidence",
                recovery: "Declare recognizable acceptance-criterion labels and exact non-empty per-task Scaffold Evidence criterion_ids ownership, or add an explicit parent runtime_acceptance contract, then rerun the original command with --recover-scaffold while the generated task pair remains lifecycle-untouched.",
                evidence: {
                    category: "planning-review",
                    details: {
                        childKind: "task",
                        childSlug: taskSlug,
                        criterionOwnershipMode: acceptanceCriterionOwnership.mode,
                        parentAcceptanceCriterionIds,
                        assignedCriterionIds: assignedCriterionIds ?? [],
                        requiresRefinement: true,
                        noWriteRequired: false
                    }
                }
            })]
        : [];
    const taskDefinitionExistsBeforeWrite = node_fs_1.default.existsSync(taskDefinitionPath);
    const implementationSummaryExistsBeforeWrite = node_fs_1.default.existsSync(implementationSummaryPath);
    const taskDefinitionRelativePath = (0, front_matter_utils_1.toRepositoryLikePath)(node_path_1.default.relative(repositoryRoot, taskDefinitionPath));
    const implementationSummaryRelativePath = (0, front_matter_utils_1.toRepositoryLikePath)(node_path_1.default.relative(repositoryRoot, implementationSummaryPath));
    const existingTaskDefinitionText = taskDefinitionExistsBeforeWrite
        ? node_fs_1.default.readFileSync(taskDefinitionPath, "utf8")
        : null;
    const existingTaskFrontMatter = existingTaskDefinitionText === null
        ? null
        : (0, artifact_parsing_1.extractFrontMatter)(taskDefinitionPath, existingTaskDefinitionText);
    const recoveryGeneratedAt = existingTaskFrontMatter === null
        ? undefined
        : (0, artifact_parsing_1.readTopLevelField)(existingTaskFrontMatter.lines, "created_at");
    const recoveryWorkflowCliCommand = options.recoverScaffold === true
        && existingTaskFrontMatter !== null
        ? (0, artifact_parsing_1.readTopLevelField)(existingTaskFrontMatter.lines, "workflow_cli_command")
        : undefined;
    const generatedAt = recoveryGeneratedAt ?? new Date().toISOString();
    const artifactWorkflowCliCommand = recoveryWorkflowCliCommand ?? options.workflowCliCommand;
    if (taskDefinitionExistsBeforeWrite) {
        (0, governed_hierarchy_context_1.assertExistingGovernedArtifactSync)(taskDefinitionPath, {
            artifactType: "task_definition",
            slice: parsedMilestoneOverview.slice,
            phase: parsedMilestoneOverview.phase,
            milestone: parsedMilestoneOverview.milestone,
            task: taskSlug,
            planningDepth: parsedMilestoneOverview.planningDepth,
            upstream: {
                slice_overview: parsedMilestoneOverview.sliceOverviewPath,
                phase_overview: parsedMilestoneOverview.phaseOverviewPath,
                milestone_overview: milestoneOverviewPath.relative
            }
        });
    }
    if (implementationSummaryExistsBeforeWrite) {
        (0, governed_hierarchy_context_1.assertExistingGovernedArtifactSync)(implementationSummaryPath, {
            artifactType: "implementation_summary",
            slice: parsedMilestoneOverview.slice,
            phase: parsedMilestoneOverview.phase,
            milestone: parsedMilestoneOverview.milestone,
            task: taskSlug,
            planningDepth: parsedMilestoneOverview.planningDepth,
            upstream: {
                slice_overview: parsedMilestoneOverview.sliceOverviewPath,
                phase_overview: parsedMilestoneOverview.phaseOverviewPath,
                milestone_overview: milestoneOverviewPath.relative,
                task_definition: taskDefinitionRelativePath
            }
        });
    }
    if (taskDefinitionExistsBeforeWrite && parsedMilestoneOverview.runtimeAcceptance !== null) {
        const existingText = existingTaskDefinitionText;
        const existingFrontMatter = existingTaskFrontMatter;
        const existingInspection = (0, runtime_acceptance_1.inspectRuntimeAcceptance)({
            artifactPath: taskDefinitionPath,
            artifactKind: "task",
            frontMatterLines: existingFrontMatter.lines,
            markdownText: existingText,
            requireExplicitForExecutableEvidence: false
        });
        const existingExecutionMode = (0, artifact_policy_projection_1.projectArtifactPolicy)(existingText).evidenceProfile;
        const expectedRuntimeAcceptance = parsedMilestoneOverview.runtimeAcceptance === null
            ? null
            : {
                ...parsedMilestoneOverview.runtimeAcceptance,
                criterionIds: assignedRuntimeCriterionIds === undefined
                    ? parsedMilestoneOverview.runtimeAcceptance.criterionIds
                    : [...assignedRuntimeCriterionIds]
            };
        const existingIssues = [
            ...existingInspection.issues,
            ...(expectedRuntimeAcceptance === null ? [] : (0, runtime_acceptance_1.validateTaskRuntimeAcceptance)({
                parent: expectedRuntimeAcceptance,
                child: existingInspection.metadata,
                executionMode: existingExecutionMode,
                taskMarkdown: existingText
            }))
        ];
        if (existingIssues.length > 0) {
            throw (0, errors_1.createUsageError)(`Runtime acceptance contract rejected '${(0, front_matter_utils_1.toRepositoryLikePath)(taskDefinitionPath)}'.`, existingIssues);
        }
    }
    const expectedRenderedTaskDefinition = (0, authoring_policy_1.stampPlanningScaffoldProjectionRevision)((0, artifact_rendering_1.renderTaskDefinitionMarkdown)({
        repositoryRoot,
        taskTitle,
        taskSlug,
        taskDescription,
        slice: parsedMilestoneOverview.slice,
        phase: parsedMilestoneOverview.phase,
        milestone: parsedMilestoneOverview.milestone,
        planningDepth: parsedMilestoneOverview.planningDepth,
        sliceOverviewPath: parsedMilestoneOverview.sliceOverviewPath,
        phaseOverviewPath: parsedMilestoneOverview.phaseOverviewPath,
        milestoneOverviewPath: milestoneOverviewPath.relative,
        upstreamSpecs,
        milestonePurpose: parsedMilestoneOverview.purpose,
        milestoneScope: parsedMilestoneOverview.scope,
        milestoneAcceptanceCriteria: parsedMilestoneOverview.acceptanceCriteria,
        milestoneDependencies: parsedMilestoneOverview.dependencies,
        milestoneRisks: parsedMilestoneOverview.risks,
        milestoneValidationFocus: parsedMilestoneOverview.validationFocus,
        scaffoldEvidence,
        acceptanceScopedScaffold,
        executionMode,
        governedPolicy: parsedMilestoneOverview.governedPolicy,
        runtimeAcceptance: childRuntimeAcceptance,
        generatedAt,
        workflowCliCommand: artifactWorkflowCliCommand
    }), "task");
    const scaffoldProjection = taskDefinitionExistsBeforeWrite
        ? (0, authoring_policy_1.comparePlanningScaffoldProjections)((0, authoring_policy_1.projectPlanningScaffoldContract)(expectedRenderedTaskDefinition, "task"), (0, authoring_policy_1.projectPlanningScaffoldContract)(existingTaskDefinitionText, "task"))
        : null;
    const recordedProjectionRevision = existingTaskDefinitionText === null
        ? null
        : (0, authoring_policy_1.readPlanningScaffoldProjectionRevision)(existingTaskDefinitionText);
    const legacyRecoveryCandidate = options.recoverScaffold === true
        && recordedProjectionRevision === null;
    const projectionRefresh = scaffoldProjection !== null
        && !scaffoldProjection.current
        && options.recoverScaffold === true
        && !legacyRecoveryCandidate;
    if (scaffoldProjection !== null
        && !scaffoldProjection.current
        && !legacyRecoveryCandidate) {
        (0, projection_1.assertTaskProjectionRefreshAllowed)({
            taskDefinitionPath,
            taskDefinitionRelativePath,
            implementationSummaryPath,
            observedText: existingTaskDefinitionText,
            comparison: scaffoldProjection,
            refreshRequested: options.recoverScaffold === true
        });
    }
    const renderedTaskDefinition = taskDefinitionExistsBeforeWrite
        && options.recoverScaffold !== true
        ? null
        : expectedRenderedTaskDefinition;
    const renderedImplementationSummary = implementationSummaryExistsBeforeWrite
        && options.recoverScaffold !== true
        ? null
        : (0, artifact_rendering_1.renderImplementationSummaryMarkdown)({
            repositoryRoot,
            taskTitle,
            taskSlug,
            slice: parsedMilestoneOverview.slice,
            phase: parsedMilestoneOverview.phase,
            milestone: parsedMilestoneOverview.milestone,
            planningDepth: parsedMilestoneOverview.planningDepth,
            sliceOverviewPath: parsedMilestoneOverview.sliceOverviewPath,
            phaseOverviewPath: parsedMilestoneOverview.phaseOverviewPath,
            milestoneOverviewPath: milestoneOverviewPath.relative,
            taskDefinitionPath: (0, front_matter_utils_1.toRepositoryLikePath)(node_path_1.default.relative(repositoryRoot, taskDefinitionPath)),
            upstreamSpecs,
            executionMode,
            governedPolicy: parsedMilestoneOverview.governedPolicy,
            runtimeAcceptance: childRuntimeAcceptance,
            generatedAt,
            workflowCliCommand: artifactWorkflowCliCommand
        });
    const taskDefinitionExists = node_fs_1.default.existsSync(taskDefinitionPath);
    const implementationSummaryExists = node_fs_1.default.existsSync(implementationSummaryPath);
    const previousScaffoldEvidence = {
        ...scaffoldEvidence,
        targetPaths: acceptanceScopedScaffoldInspection.targetPaths
    };
    const renderedPreviousTaskDefinition = options.recoverScaffold !== true
        ? null
        : (0, artifact_rendering_1.renderTaskDefinitionMarkdown)({
            repositoryRoot,
            taskTitle,
            taskSlug,
            taskDescription,
            slice: parsedMilestoneOverview.slice,
            phase: parsedMilestoneOverview.phase,
            milestone: parsedMilestoneOverview.milestone,
            planningDepth: parsedMilestoneOverview.planningDepth,
            sliceOverviewPath: parsedMilestoneOverview.sliceOverviewPath,
            phaseOverviewPath: parsedMilestoneOverview.phaseOverviewPath,
            milestoneOverviewPath: milestoneOverviewPath.relative,
            upstreamSpecs,
            milestonePurpose: parsedMilestoneOverview.purpose,
            milestoneScope: parsedMilestoneOverview.scope,
            milestoneAcceptanceCriteria: parsedMilestoneOverview.acceptanceCriteria,
            milestoneDependencies: parsedMilestoneOverview.dependencies,
            milestoneRisks: parsedMilestoneOverview.risks,
            milestoneValidationFocus: parsedMilestoneOverview.validationFocus,
            scaffoldEvidence: previousScaffoldEvidence,
            acceptanceScopedScaffold: acceptanceScopedScaffoldInspection,
            executionMode,
            governedPolicy: parsedMilestoneOverview.governedPolicy,
            runtimeAcceptance: childRuntimeAcceptance,
            generatedAt,
            workflowCliCommand: artifactWorkflowCliCommand
        });
    const legacyAcceptanceScopedScaffoldInspection = options.recoverScaffold === true
        ? (0, scaffold_application_1.inspectAcceptanceScopedTaskScaffold)({
            milestoneMarkdownText: milestoneOverviewText,
            childSlug: taskSlug,
            taskDescription,
            parentAcceptanceCriteria: parsedMilestoneOverview.acceptanceCriteria,
            assignedCriterionIds: [],
            scaffoldEvidence: rawScaffoldEvidence
        })
        : null;
    const legacyAcceptanceScopedScaffold = legacyAcceptanceScopedScaffoldInspection === null
        ? null
        : {
            ...legacyAcceptanceScopedScaffoldInspection,
            dependencies: (0, runtime_scaffold_1.normalizeScaffoldDependencyPaths)({
                milestoneOverviewPath: milestoneOverviewPath.relative,
                dependencies: [
                    ...legacyAcceptanceScopedScaffoldInspection.dependencies,
                    ...rawScaffoldEvidence.dependencies
                ]
            })
        };
    const renderedLegacyTaskDefinition = legacyAcceptanceScopedScaffold === null
        ? null
        : (0, artifact_rendering_1.renderTaskDefinitionMarkdown)({
            repositoryRoot,
            taskTitle,
            taskSlug,
            taskDescription,
            slice: parsedMilestoneOverview.slice,
            phase: parsedMilestoneOverview.phase,
            milestone: parsedMilestoneOverview.milestone,
            planningDepth: parsedMilestoneOverview.planningDepth,
            sliceOverviewPath: parsedMilestoneOverview.sliceOverviewPath,
            phaseOverviewPath: parsedMilestoneOverview.phaseOverviewPath,
            milestoneOverviewPath: milestoneOverviewPath.relative,
            upstreamSpecs,
            milestonePurpose: parsedMilestoneOverview.purpose,
            milestoneScope: parsedMilestoneOverview.scope,
            milestoneAcceptanceCriteria: parsedMilestoneOverview.acceptanceCriteria,
            milestoneDependencies: parsedMilestoneOverview.dependencies,
            milestoneRisks: parsedMilestoneOverview.risks,
            milestoneValidationFocus: parsedMilestoneOverview.validationFocus,
            scaffoldEvidence,
            acceptanceScopedScaffold: legacyAcceptanceScopedScaffold,
            executionMode,
            governedPolicy: parsedMilestoneOverview.governedPolicy,
            runtimeAcceptance: inheritedChildRuntimeAcceptance,
            generatedAt,
            workflowCliCommand: artifactWorkflowCliCommand
        });
    const renderedAcceptanceRecoveredTaskDefinition = options.recoverScaffold !== true
        ? null
        : (0, artifact_rendering_1.renderTaskDefinitionMarkdown)({
            repositoryRoot,
            taskTitle,
            taskSlug,
            taskDescription,
            slice: parsedMilestoneOverview.slice,
            phase: parsedMilestoneOverview.phase,
            milestone: parsedMilestoneOverview.milestone,
            planningDepth: parsedMilestoneOverview.planningDepth,
            sliceOverviewPath: parsedMilestoneOverview.sliceOverviewPath,
            phaseOverviewPath: parsedMilestoneOverview.phaseOverviewPath,
            milestoneOverviewPath: milestoneOverviewPath.relative,
            upstreamSpecs,
            milestonePurpose: parsedMilestoneOverview.purpose,
            milestoneScope: parsedMilestoneOverview.scope,
            milestoneAcceptanceCriteria: parsedMilestoneOverview.acceptanceCriteria,
            milestoneDependencies: parsedMilestoneOverview.dependencies,
            milestoneRisks: parsedMilestoneOverview.risks,
            milestoneValidationFocus: parsedMilestoneOverview.validationFocus,
            scaffoldEvidence,
            acceptanceScopedScaffold,
            executionMode,
            governedPolicy: parsedMilestoneOverview.governedPolicy,
            runtimeAcceptance: inheritedChildRuntimeAcceptance,
            generatedAt,
            workflowCliCommand: artifactWorkflowCliCommand
        });
    const renderedLegacyImplementationSummary = options.recoverScaffold !== true
        ? null
        : (0, artifact_rendering_1.renderImplementationSummaryMarkdown)({
            repositoryRoot,
            taskTitle,
            taskSlug,
            slice: parsedMilestoneOverview.slice,
            phase: parsedMilestoneOverview.phase,
            milestone: parsedMilestoneOverview.milestone,
            planningDepth: parsedMilestoneOverview.planningDepth,
            sliceOverviewPath: parsedMilestoneOverview.sliceOverviewPath,
            phaseOverviewPath: parsedMilestoneOverview.phaseOverviewPath,
            milestoneOverviewPath: milestoneOverviewPath.relative,
            taskDefinitionPath: taskDefinitionRelativePath,
            upstreamSpecs,
            executionMode,
            governedPolicy: parsedMilestoneOverview.governedPolicy,
            runtimeAcceptance: inheritedChildRuntimeAcceptance,
            generatedAt,
            workflowCliCommand: artifactWorkflowCliCommand
        });
    const recoveryInspection = options.recoverScaffold === true && !projectionRefresh
        ? (0, task_scaffold_recovery_1.inspectTaskScaffoldRecoveryPairSync)({
            taskDefinitionPath,
            taskDefinitionRepositoryRelativePath: taskDefinitionRelativePath,
            implementationSummaryPath,
            expectedLegacyTaskDefinitionTexts: [
                renderedPreviousTaskDefinition ?? "",
                renderedLegacyTaskDefinition ?? "",
                renderedAcceptanceRecoveredTaskDefinition ?? ""
            ],
            expectedPendingImplementationSummaryTexts: [
                renderedImplementationSummary ?? "",
                renderedLegacyImplementationSummary ?? ""
            ],
            expectedRecoveredTaskDefinitionText: renderedTaskDefinition ?? undefined
        })
        : null;
    if (recoveryInspection !== null && !recoveryInspection.eligible) {
        throw (0, errors_1.createUsageError)(`Task scaffold recovery rejected '${taskDefinitionRelativePath}' before writes.`, [...recoveryInspection.issues, "No task artifact write was attempted."]);
    }
    const tasksDirectoryAction = node_fs_1.default.existsSync(tasksDirectoryPath) ? "kept" : "created";
    const plannedWrites = [
        ...(projectionRefresh && renderedTaskDefinition !== null
            ? [{
                    path: taskDefinitionRelativePath,
                    contents: renderedTaskDefinition,
                    mode: "replace",
                    expectedRevision: (0, scaffold_application_1.planningScaffoldContentRevision)(node_fs_1.default.readFileSync(taskDefinitionPath))
                }]
            : recoveryInspection?.action === "replace"
                && renderedTaskDefinition !== null
                && recoveryInspection.taskDefinitionText !== renderedTaskDefinition
                && recoveryInspection.taskDefinitionExpectedRevision !== null
                ? [{
                        path: taskDefinitionRelativePath,
                        contents: renderedTaskDefinition,
                        mode: "replace",
                        expectedRevision: recoveryInspection.taskDefinitionExpectedRevision
                    }]
                : !taskDefinitionExists && renderedTaskDefinition !== null
                    ? [{ path: taskDefinitionRelativePath, contents: renderedTaskDefinition }]
                    : []),
        ...(!implementationSummaryExists && renderedImplementationSummary !== null
            ? [{ path: implementationSummaryRelativePath, contents: renderedImplementationSummary }]
            : [])
    ];
    const taskDefinitionRefreshed = plannedWrites.some((write) => write.path === taskDefinitionRelativePath && write.mode === "replace");
    const implementationSummaryRefreshed = plannedWrites.some((write) => write.path === implementationSummaryRelativePath && write.mode === "replace");
    let application = {
        outcome: "no-write",
        intendedPaths: [],
        changedPaths: [],
        transactionId: null,
        conflicts: [],
        recoveryPath: null,
        failure: null
    };
    if (options.validateOnly !== true) {
        application = (0, scaffold_application_1.applyPlanningScaffoldSync)(repositoryRoot, plannedWrites, {
            parentPaths: [{
                    path: milestoneOverviewPath.relative,
                    expectedRevision: parentExpectedRevision
                }]
        });
        (0, scaffold_application_1.assertPlanningScaffoldApplied)(application);
    }
    return {
        repositoryRoot,
        slice: parsedMilestoneOverview.slice,
        phase: parsedMilestoneOverview.phase,
        milestone: parsedMilestoneOverview.milestone,
        planningDepth: parsedMilestoneOverview.planningDepth,
        milestoneOverviewPath: milestoneOverviewPath.relative,
        tasksDirectoryPath,
        taskDirectoryPath,
        taskDefinitionPath,
        implementationSummaryPath,
        taskSlug,
        taskTitle,
        parentExpectedRevision,
        tasksDirectoryAction,
        taskDefinitionAction: taskDefinitionRefreshed
            ? "refreshed"
            : taskDefinitionExists
                ? "kept"
                : "created",
        implementationSummaryAction: implementationSummaryRefreshed
            ? "refreshed"
            : implementationSummaryExists
                ? "kept"
                : "created",
        contributingSpecIds: upstreamSpecs.map((entry) => entry.id),
        plannedWrites,
        requiresRefinement,
        refinementFindings,
        scaffoldEvidence,
        runtimeCriterionOwnership,
        scaffoldProjection,
        application,
        commandWriteSummary: (0, command_write_summary_1.normalizeCommandWriteSummary)({
            commandFamily: "task_generation",
            primaryOutputArtifacts: [taskDefinitionRelativePath, implementationSummaryRelativePath],
            updatedArtifacts: [
                {
                    path: taskDefinitionRelativePath,
                    action: taskDefinitionRefreshed
                        ? "refreshed"
                        : taskDefinitionExists
                            ? "kept"
                            : "created",
                    reason: taskDefinitionRefreshed
                        ? "accepted_refresh"
                        : taskDefinitionExists
                            ? "no_write"
                            : "accepted_create"
                },
                {
                    path: implementationSummaryRelativePath,
                    action: implementationSummaryRefreshed
                        ? "refreshed"
                        : implementationSummaryExists
                            ? "kept"
                            : "created",
                    reason: implementationSummaryRefreshed
                        ? "accepted_refresh"
                        : implementationSummaryExists
                            ? "no_write"
                            : "accepted_create"
                }
            ]
        })
    };
}
