"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.inspectMaterializedPhaseScaffoldProjection = inspectMaterializedPhaseScaffoldProjection;
exports.projectExpectedMaterializedPhaseScaffolds = projectExpectedMaterializedPhaseScaffolds;
exports.recordMaterializedProjectionDrift = recordMaterializedProjectionDrift;
exports.assertMilestoneProjectionRefreshAllowed = assertMilestoneProjectionRefreshAllowed;
exports.hasMaterializedTaskEvidence = hasMaterializedTaskEvidence;
exports.inspectMilestoneFullSetMaterialization = inspectMilestoneFullSetMaterialization;
exports.assertCurrentPhaseAuthoringReviewResult = assertCurrentPhaseAuthoringReviewResult;
const node_fs_1 = __importDefault(require("node:fs"));
const node_path_1 = __importDefault(require("node:path"));
const node_util_1 = require("node:util");
const errors_1 = require("../../errors");
const output_1 = require("../../output");
const paths_1 = require("../../paths");
const authoring_policy_1 = require("../authoring-policy");
const front_matter_utils_1 = require("../front-matter-utils");
const runtime_acceptance_1 = require("../runtime-acceptance");
const scaffold_application_1 = require("../scaffold-application");
const scaffold_target_path_policy_1 = require("../scaffold-target-path-policy");
const authoring_readiness_1 = require("./authoring-readiness");
const overview_rendering_1 = require("./overview-rendering");
const phase_parsing_1 = require("./phase-parsing");
const task_evidence_1 = require("./task-evidence");
function inspectMaterializedPhaseScaffoldProjection(options) {
    const runtimeEvidencePathPolicy = (0, scaffold_target_path_policy_1.readPlanningScaffoldTargetPathPolicy)(options.repositoryRoot);
    const milestoneDirectory = (0, front_matter_utils_1.toRepositoryLikePath)(node_path_1.default.join(node_path_1.default.dirname(options.phaseOverviewPath), "milestones", options.milestoneEvidence.milestoneSlug));
    const milestoneOverviewPath = (0, paths_1.composeCanonicalPlanningOverviewPath)("milestone", milestoneDirectory);
    if (!(0, task_evidence_1.isRegularRepositoryFile)(options.repositoryRoot, milestoneOverviewPath))
        return;
    const taskCandidateSlugs = options.authoredMilestoneScaffold.tasks.map((task) => task.slug);
    const runtimeAcceptance = options.parsedPhaseOverview.runtimeAcceptance === null
        ? null
        : {
            ...(0, runtime_acceptance_1.childRuntimeAcceptanceMetadata)(options.parsedPhaseOverview.runtimeAcceptance, {
                breakoutTask: options.parsedPhaseOverview.runtimeAcceptance.required
                    ? taskCandidateSlugs[0]
                    : null
            }),
            criterionIds: options.parsedPhaseOverview.runtimeAcceptance.required
                ? [...options.authoredMilestoneScaffold.criterionIds]
                : []
        };
    const expectedText = (0, authoring_policy_1.stampPlanningScaffoldProjectionRevision)((0, overview_rendering_1.renderMilestoneOverviewMarkdown)({
        milestoneTitle: (0, phase_parsing_1.resolveMilestoneTitle)(options.milestoneEvidence.milestoneSlug, undefined),
        milestoneDescription: options.milestoneDescription,
        slice: options.parsedPhaseOverview.slice,
        phase: options.parsedPhaseOverview.phase,
        milestoneSlug: options.milestoneEvidence.milestoneSlug,
        planningDepth: options.parsedPhaseOverview.planningDepth,
        sliceOverviewPath: options.parsedPhaseOverview.sliceOverviewPath,
        phaseOverviewPath: options.phaseOverviewPath,
        upstreamSpecs: options.parsedPhaseOverview.upstreamSpecs,
        governedPolicy: options.parsedPhaseOverview.governedPolicy,
        phasePurpose: options.parsedPhaseOverview.purpose,
        milestoneAcceptanceCriteria: options.authoredMilestoneScaffold.acceptanceCriteria,
        phaseRisks: options.parsedPhaseOverview.risks,
        scaffoldEvidence: options.milestoneEvidence.scaffoldEvidence,
        authoredMilestoneScaffold: options.authoredMilestoneScaffold,
        runtimeAcceptance,
        workflowCliCommand: `day-shift milestone new --phase-overview ${options.phaseOverviewPath} --full-set`
    }), "milestone");
    const observedText = node_fs_1.default.readFileSync(node_path_1.default.join(options.repositoryRoot, milestoneOverviewPath), "utf8");
    const expectedMilestoneProjection = (0, authoring_policy_1.projectPlanningScaffoldContract)(expectedText, "milestone");
    const observedMilestoneProjection = (0, authoring_policy_1.projectPlanningScaffoldContract)(observedText, "milestone");
    const milestoneComparison = compareMaterializedScaffoldProjections(expectedMilestoneProjection, observedMilestoneProjection, observedText);
    options.materializedScaffoldPaths.push(milestoneOverviewPath);
    options.materializedScaffoldRevisions.push({
        path: milestoneOverviewPath,
        parentProjectionRevision: (0, authoring_policy_1.planningScaffoldProjectionRevision)(expectedMilestoneProjection),
        childProjectionRevision: (0, authoring_policy_1.planningScaffoldProjectionRevision)(observedMilestoneProjection)
    });
    recordMaterializedProjectionDrift({
        parentPath: options.phaseOverviewPath,
        childPath: milestoneOverviewPath,
        comparison: milestoneComparison,
        scaffoldProjectionDrift: options.scaffoldProjectionDrift,
        findings: options.findings
    });
    for (const task of options.milestoneEvidence.taskIdentities) {
        const taskDefinitionPath = (0, front_matter_utils_1.toRepositoryLikePath)(node_path_1.default.join(milestoneDirectory, "tasks", task.taskSlug, "task-definition.md"));
        if (!(0, task_evidence_1.isRegularRepositoryFile)(options.repositoryRoot, taskDefinitionPath))
            continue;
        const observedText = node_fs_1.default.readFileSync(node_path_1.default.join(options.repositoryRoot, taskDefinitionPath), "utf8");
        const observedProjection = (0, authoring_policy_1.projectPlanningScaffoldContract)(observedText, "task");
        const expectedRawScaffold = (0, authoring_policy_1.inspectChildScaffoldEvidence)({
            markdownText: expectedText,
            childKind: "task",
            childSlug: task.taskSlug,
            declaredChildSlugs: options.milestoneEvidence.taskIdentities.map((entry) => entry.taskSlug),
            runtimeEvidencePathPolicy
        });
        const expectedAcceptanceScaffold = (0, scaffold_application_1.inspectAcceptanceScopedTaskScaffold)({
            milestoneMarkdownText: expectedText,
            childSlug: task.taskSlug,
            taskDescription: task.description,
            parentAcceptanceCriteria: expectedMilestoneProjection.acceptanceCriteria,
            assignedCriterionIds: task.criterionIds,
            scaffoldEvidence: expectedRawScaffold
        });
        const expectedProjection = {
            artifactKind: "task",
            childSlug: task.taskSlug,
            criterionIds: [...task.criterionIds],
            acceptanceCriteria: [...expectedAcceptanceScaffold.acceptanceCriteria],
            ownership: [],
            dependencies: (0, task_evidence_1.uniqueStrings)([
                milestoneOverviewPath,
                ...expectedAcceptanceScaffold.dependencies,
                ...expectedRawScaffold.dependencies
            ]),
            targetPaths: (0, task_evidence_1.uniqueStrings)([
                ...expectedAcceptanceScaffold.targetPaths,
                ...expectedRawScaffold.adapterPaths
            ]),
            adapterPaths: [...task.adapterPaths],
            validationCommands: [...expectedAcceptanceScaffold.validationCommands],
            rollback: expectedAcceptanceScaffold.rollback.length === 0
                ? []
                : [expectedAcceptanceScaffold.rollback.join(" ")],
            currentBehavior: expectedAcceptanceScaffold.currentBehavior,
            desiredBehavior: expectedAcceptanceScaffold.desiredBehavior,
            declaredChildCount: null,
            declaredChildSlugs: [],
            nestedEvidence: []
        };
        const comparableObserved = {
            ...observedProjection,
            ownership: [],
            declaredChildCount: null,
            declaredChildSlugs: [],
            nestedEvidence: []
        };
        const taskComparison = compareMaterializedScaffoldProjections(expectedProjection, comparableObserved, observedText);
        options.materializedScaffoldPaths.push(taskDefinitionPath);
        options.materializedScaffoldRevisions.push({
            path: taskDefinitionPath,
            parentProjectionRevision: (0, authoring_policy_1.planningScaffoldProjectionRevision)(expectedProjection),
            childProjectionRevision: (0, authoring_policy_1.planningScaffoldProjectionRevision)(comparableObserved)
        });
        recordMaterializedProjectionDrift({
            parentPath: options.phaseOverviewPath,
            childPath: taskDefinitionPath,
            comparison: taskComparison,
            scaffoldProjectionDrift: options.scaffoldProjectionDrift,
            findings: options.findings
        });
    }
}
/**
 * Projects the exact child contracts produced from one phase milestone block.
 * The legacy mode exists only so migration can prove an existing stamp against
 * the pre-scoped-evidence reader before adopting the current contract.
 */
function projectExpectedMaterializedPhaseScaffolds(options) {
    const runtimeEvidencePathPolicy = (0, scaffold_target_path_policy_1.readPlanningScaffoldTargetPathPolicy)(options.repositoryRoot);
    const milestoneDirectory = (0, front_matter_utils_1.toRepositoryLikePath)(node_path_1.default.join(node_path_1.default.dirname(options.phaseOverviewPath), "milestones", options.milestoneEvidence.milestoneSlug));
    const milestoneOverviewPath = (0, paths_1.composeCanonicalPlanningOverviewPath)("milestone", milestoneDirectory);
    const taskCandidateSlugs = options.authoredMilestoneScaffold.tasks.map((task) => task.slug);
    const runtimeAcceptance = options.parsedPhaseOverview.runtimeAcceptance === null
        ? null
        : {
            ...(0, runtime_acceptance_1.childRuntimeAcceptanceMetadata)(options.parsedPhaseOverview.runtimeAcceptance, {
                breakoutTask: options.parsedPhaseOverview.runtimeAcceptance.required
                    ? taskCandidateSlugs[0]
                    : null
            }),
            criterionIds: options.parsedPhaseOverview.runtimeAcceptance.required
                ? [...options.authoredMilestoneScaffold.criterionIds]
                : []
        };
    const expectedText = (0, authoring_policy_1.stampPlanningScaffoldProjectionRevision)((0, overview_rendering_1.renderMilestoneOverviewMarkdown)({
        milestoneTitle: (0, phase_parsing_1.resolveMilestoneTitle)(options.milestoneEvidence.milestoneSlug, undefined),
        milestoneDescription: options.milestoneDescription,
        slice: options.parsedPhaseOverview.slice,
        phase: options.parsedPhaseOverview.phase,
        milestoneSlug: options.milestoneEvidence.milestoneSlug,
        planningDepth: options.parsedPhaseOverview.planningDepth,
        sliceOverviewPath: options.parsedPhaseOverview.sliceOverviewPath,
        phaseOverviewPath: options.phaseOverviewPath,
        upstreamSpecs: options.parsedPhaseOverview.upstreamSpecs,
        governedPolicy: options.parsedPhaseOverview.governedPolicy,
        phasePurpose: options.parsedPhaseOverview.purpose,
        milestoneAcceptanceCriteria: options.authoredMilestoneScaffold.acceptanceCriteria,
        phaseRisks: options.parsedPhaseOverview.risks,
        scaffoldEvidence: options.milestoneEvidence.scaffoldEvidence,
        authoredMilestoneScaffold: options.authoredMilestoneScaffold,
        runtimeAcceptance,
        workflowCliCommand: `day-shift milestone new --phase-overview ${options.phaseOverviewPath} --full-set`
    }), "milestone");
    const expectedMilestoneProjection = (0, authoring_policy_1.projectPlanningScaffoldContract)(expectedText, "milestone", options.projectionReader);
    const projected = [{
            path: milestoneOverviewPath,
            artifactKind: "milestone",
            projection: expectedMilestoneProjection
        }];
    for (const task of options.milestoneEvidence.taskIdentities) {
        const taskDefinitionPath = (0, front_matter_utils_1.toRepositoryLikePath)(node_path_1.default.join(milestoneDirectory, "tasks", task.taskSlug, "task-definition.md"));
        const expectedRawScaffold = (0, authoring_policy_1.inspectChildScaffoldEvidence)({
            markdownText: expectedText,
            childKind: "task",
            childSlug: task.taskSlug,
            declaredChildSlugs: options.milestoneEvidence.taskIdentities.map((entry) => entry.taskSlug),
            runtimeEvidencePathPolicy,
            compatibilityMode: options.compatibilityMode
        });
        const expectedAcceptanceScaffold = (0, scaffold_application_1.inspectAcceptanceScopedTaskScaffold)({
            milestoneMarkdownText: expectedText,
            childSlug: task.taskSlug,
            taskDescription: task.description,
            parentAcceptanceCriteria: expectedMilestoneProjection.acceptanceCriteria,
            assignedCriterionIds: task.criterionIds,
            scaffoldEvidence: expectedRawScaffold
        });
        projected.push({
            path: taskDefinitionPath,
            artifactKind: "task",
            projection: {
                artifactKind: "task",
                childSlug: task.taskSlug,
                criterionIds: options.taskCriterionProjection === "parent-fallback"
                    ? [...options.milestoneEvidence.criterionIds]
                    : [...task.criterionIds],
                acceptanceCriteria: [...expectedAcceptanceScaffold.acceptanceCriteria],
                ownership: [],
                dependencies: (0, task_evidence_1.uniqueStrings)([
                    milestoneOverviewPath,
                    ...expectedAcceptanceScaffold.dependencies,
                    ...expectedRawScaffold.dependencies
                ]),
                targetPaths: (0, task_evidence_1.uniqueStrings)([
                    ...expectedAcceptanceScaffold.targetPaths,
                    ...expectedRawScaffold.adapterPaths
                ]),
                adapterPaths: [...task.adapterPaths],
                validationCommands: [...expectedAcceptanceScaffold.validationCommands],
                rollback: expectedAcceptanceScaffold.rollback.length === 0
                    ? []
                    : [expectedAcceptanceScaffold.rollback.join(" ")],
                currentBehavior: expectedAcceptanceScaffold.currentBehavior,
                desiredBehavior: expectedAcceptanceScaffold.desiredBehavior,
                declaredChildCount: null,
                declaredChildSlugs: [],
                nestedEvidence: []
            }
        });
    }
    return projected;
}
function compareMaterializedScaffoldProjections(expected, observed, observedText) {
    const comparison = (0, authoring_policy_1.comparePlanningScaffoldProjections)(expected, observed);
    if (comparison.current)
        return comparison;
    const recordedProjectionRevision = (0, authoring_policy_1.readPlanningScaffoldProjectionRevision)(observedText);
    if (recordedProjectionRevision === null
        || recordedProjectionRevision !== (0, authoring_policy_1.planningScaffoldProjectionRevision)(expected)) {
        return comparison;
    }
    const refinementFields = expected.artifactKind === "milestone"
        ? new Set([
            "ownership",
            "dependencies",
            "targetPaths",
            "adapterPaths",
            "validationCommands",
            "rollback"
        ])
        : new Set([
            "dependencies",
            "targetPaths",
            "adapterPaths",
            "validationCommands",
            "rollback",
            "currentBehavior",
            "desiredBehavior"
        ]);
    const drift = comparison.drift.filter((entry) => !refinementFields.has(entry.field));
    return {
        expected,
        observed,
        drift,
        current: drift.length === 0
    };
}
function recordMaterializedProjectionDrift(options) {
    if (options.comparison.current)
        return;
    options.scaffoldProjectionDrift.push({
        parentPath: options.parentPath,
        childPath: options.childPath,
        comparison: options.comparison
    });
    options.findings.push(...options.comparison.drift.map((entry) => (0, output_1.createBlockingValidationFinding)({
        code: "PLANNING_SCAFFOLD_PROJECTION_DRIFT",
        message: `Materialized child '${options.childPath}' has ${entry.kind} scaffold projection drift at '${entry.field}'.`,
        path: options.childPath,
        blockingReason: "invalid-command-input",
        recovery: `Review the current parent projection at '${options.parentPath}'. Use the explicit scaffold refresh path only while the child remains lifecycle-untouched.`,
        evidence: {
            category: "planning-review",
            details: {
                parentPath: options.parentPath,
                childPath: options.childPath,
                field: entry.field,
                driftKind: entry.kind,
                expectedParentProjection: entry.expected,
                observedChildProjection: entry.observed,
                requiresRefinement: true,
                noWriteRequired: true
            }
        }
    })));
}
function assertMilestoneProjectionRefreshAllowed(options) {
    const artifactPath = options.artifactPath;
    const findings = options.comparison.drift.map((entry) => (0, output_1.createBlockingValidationFinding)({
        code: "PLANNING_SCAFFOLD_PROJECTION_DRIFT",
        message: `Materialized milestone '${artifactPath}' has ${entry.kind} scaffold projection drift at '${entry.field}'.`,
        path: artifactPath,
        blockingReason: "invalid-command-input",
        recovery: `Rerun with --recover-scaffold only if the generated milestone pair is still lifecycle-untouched; otherwise preserve the child and revise the parent or record separate discovered work.`,
        evidence: {
            category: "planning-review",
            details: {
                field: entry.field,
                driftKind: entry.kind,
                expectedParentProjection: entry.expected,
                observedChildProjection: entry.observed,
                noWriteRequired: true
            }
        }
    }));
    if (!options.refreshRequested) {
        throw (0, errors_1.createInvalidConfigError)(`Current parent scaffold projection does not match '${artifactPath}'.`, [
            ...findings.map((finding) => finding.message),
            "No milestone artifact write was attempted. Use --recover-scaffold as a separate preservation-first refresh only before lifecycle evidence exists."
        ], findings);
    }
    const recordedRevision = (0, authoring_policy_1.readPlanningScaffoldProjectionRevision)(options.observedText);
    const observedRevision = (0, authoring_policy_1.planningScaffoldProjectionRevision)(options.comparison.observed);
    const frontMatter = (0, phase_parsing_1.extractFrontMatter)(options.overviewPath, options.observedText);
    const status = (0, phase_parsing_1.readTopLevelField)(frontMatter.lines, "status")?.trim() ?? null;
    const reconciliationText = node_fs_1.default.existsSync(options.reconciliationPath)
        ? node_fs_1.default.readFileSync(options.reconciliationPath, "utf8")
        : "";
    const reconciliationFrontMatter = reconciliationText === ""
        ? null
        : (0, phase_parsing_1.extractFrontMatter)(options.reconciliationPath, reconciliationText);
    const reconciliationStatus = reconciliationFrontMatter === null
        ? null
        : (0, phase_parsing_1.readTopLevelField)(reconciliationFrontMatter.lines, "reconciliation_status")?.trim() ?? null;
    const lifecycleUntouched = status === "draft"
        && (recordedRevision === observedRevision
            || recordedRevision === (0, authoring_policy_1.legacyPlanningScaffoldProjectionRevision)(options.comparison.observed))
        && !hasMaterializedTaskEvidence(options.tasksDirectoryPath)
        && reconciliationStatus === "pending"
        && /Pending\. This reconciliation artifact is initialized/u.test(reconciliationText);
    if (lifecycleUntouched)
        return;
    throw (0, errors_1.createInvalidConfigError)(`Scaffold refresh is unavailable for '${artifactPath}' because preservation-first lifecycle checks did not prove an untouched generated pair.`, [
        `Recorded projection: ${recordedRevision ?? "(missing)"}.`,
        `Observed projection: ${observedRevision}.`,
        `Milestone status: ${status ?? "(missing)"}.`,
        `Reconciliation status: ${reconciliationStatus ?? "(missing)"}.`,
        "No milestone artifact write was attempted; existing authored or lifecycle evidence was preserved."
    ], findings.map((finding) => ({
        ...finding,
        code: "PLANNING_SCAFFOLD_REFRESH_UNAVAILABLE"
    })));
}
function hasMaterializedTaskEvidence(tasksDirectoryPath) {
    if (!node_fs_1.default.existsSync(tasksDirectoryPath))
        return false;
    return node_fs_1.default.readdirSync(tasksDirectoryPath, { withFileTypes: true }).some((entry) => {
        if (!entry.isDirectory())
            return true;
        const directory = node_path_1.default.join(tasksDirectoryPath, entry.name);
        return node_fs_1.default.existsSync(node_path_1.default.join(directory, "task-definition.md"))
            || node_fs_1.default.existsSync(node_path_1.default.join(directory, "implementation-summary.md"));
    });
}
function inspectMilestoneFullSetMaterialization(repositoryRoot, options) {
    const phaseOverviewPath = (0, phase_parsing_1.resolvePhaseOverviewPath)(repositoryRoot, options.phaseOverviewPath);
    if (!node_fs_1.default.existsSync(phaseOverviewPath.absolute)) {
        throw (0, errors_1.createUsageError)(`Parent phase overview not found at '${phaseOverviewPath.relative}'.`);
    }
    const phaseOverviewText = node_fs_1.default.readFileSync(phaseOverviewPath.absolute, "utf8");
    const declaredMilestoneSlugs = (0, authoring_policy_1.declaredPlanningChildSlugs)(phaseOverviewText, "Milestones");
    const phaseDirectory = node_path_1.default.dirname(phaseOverviewPath.relative);
    const missingMilestoneSlugs = declaredMilestoneSlugs.filter((milestoneSlug) => {
        const milestoneDirectory = (0, front_matter_utils_1.toRepositoryLikePath)(node_path_1.default.join(phaseDirectory, "milestones", milestoneSlug));
        const overviewPath = (0, paths_1.composeCanonicalPlanningOverviewPath)("milestone", milestoneDirectory);
        const reconciliationPath = (0, front_matter_utils_1.toRepositoryLikePath)(node_path_1.default.join(milestoneDirectory, "reconciliation.md"));
        return !(0, task_evidence_1.isRegularRepositoryFile)(repositoryRoot, overviewPath)
            || !(0, task_evidence_1.isRegularRepositoryFile)(repositoryRoot, reconciliationPath);
    });
    return {
        phaseOverviewPath: phaseOverviewPath.relative,
        declaredMilestoneSlugs,
        missingMilestoneSlugs,
        fullyMaterialized: declaredMilestoneSlugs.length > 0
            && missingMilestoneSlugs.length === 0
    };
}
function assertCurrentPhaseAuthoringReviewResult(repositoryRoot, options) {
    const envelope = (0, task_evidence_1.asRecord)(options.phaseReviewResult);
    const data = (0, task_evidence_1.asRecord)(envelope?.data);
    const output = (0, task_evidence_1.asRecord)(envelope?.output);
    const receipt = (0, task_evidence_1.asRecord)(data?.phaseAuthoringReceipt);
    const authoringBlockingIssues = Array.isArray(data?.phaseAuthoringBlockingIssues)
        ? data.phaseAuthoringBlockingIssues
        : null;
    const envelopeFindings = Array.isArray(envelope?.findings)
        ? envelope.findings.flatMap((entry) => {
            const finding = (0, task_evidence_1.asRecord)(entry);
            return finding !== null && typeof finding.code === "string"
                ? [finding]
                : [];
        })
        : null;
    if (envelope === null
        || envelope.status !== "ok"
        || envelope.command !== "phase review"
        || data === null
        || data.readOnly !== true
        || data.writeCapable !== false
        || data.reviewMode !== "readiness"
        || output?.complete !== true
        || authoringBlockingIssues === null
        || envelopeFindings === null
        || receipt === null) {
        throw (0, task_evidence_1.phaseAuthoringReceiptError)("PLANNING_PHASE_AUTHORING_RECEIPT_MALFORMED", "--phase-review-result must contain one complete zero-blocker read-only phase readiness review result.");
    }
    const authoringFindings = envelopeFindings.filter((finding) => finding.code.startsWith("PLANNING_SCAFFOLD_")
        || finding.code.startsWith("PLANNING_MILESTONE_SCAFFOLD_")
        || finding.code.startsWith("PHASE_VALIDATION_"));
    const decompositionOnly = authoringBlockingIssues.length > 0
        && authoringFindings.length === 0;
    if (authoringFindings.length > 0
        || (authoringBlockingIssues.length !== 0 && !decompositionOnly)
        || (receipt.complete !== true && !decompositionOnly)
        || (receipt.handoffReady !== true && !decompositionOnly)) {
        throw (0, task_evidence_1.phaseAuthoringReceiptError)("PLANNING_PHASE_AUTHORING_RECEIPT_INCOMPLETE", "The phase authoring review still contains child scaffold blockers.", authoringFindings);
    }
    const current = (0, authoring_readiness_1.inspectPhaseMilestoneAuthoringReadiness)(repositoryRoot, {
        phaseOverviewPath: options.phaseOverviewPath
    });
    const currentDecompositionOnly = current.findings.length > 0
        && current.findings.every((finding) => finding.code.startsWith("PLANNING_DECOMPOSITION_"));
    if (!current.complete && !currentDecompositionOnly) {
        throw (0, task_evidence_1.phaseAuthoringReceiptError)("PLANNING_PHASE_AUTHORING_RECEIPT_STALE", "The selected phase no longer has a complete milestone authoring contract.", current.findings);
    }
    if (receipt.phaseOverviewPath !== current.phaseOverviewPath
        || receipt.phaseRevision !== current.phaseRevision) {
        throw (0, task_evidence_1.phaseAuthoringReceiptError)("PLANNING_PHASE_AUTHORING_RECEIPT_STALE", "The phase authoring receipt is not bound to the exact current phase path and revision.");
    }
    if (typeof receipt.reviewedAt !== "string") {
        throw (0, task_evidence_1.phaseAuthoringReceiptError)("PLANNING_PHASE_AUTHORING_RECEIPT_MALFORMED", "The phase authoring receipt is missing its review timestamp.");
    }
    const expected = (0, authoring_policy_1.createPhaseAuthoringReadinessReceipt)({
        phaseOverviewPath: current.phaseOverviewPath,
        phaseRevision: current.phaseRevision,
        reviewedAt: receipt.reviewedAt,
        blockerCount: typeof receipt.blockerCount === "number"
            ? receipt.blockerCount
            : current.findings.length,
        inspectionComplete: current.complete,
        declaredMilestoneSlugs: current.declaredMilestoneSlugs,
        normalizedScaffoldEvidence: current.normalizedScaffoldEvidence,
        contractImpactFingerprints: current.contractImpactCoverage.tasks.map((task) => ({
            milestoneSlug: task.milestoneSlug,
            taskSlug: task.taskSlug,
            fingerprint: task.fingerprint
        })),
        materializedScaffoldRevisions: current.materializedScaffoldRevisions
    });
    if (!(0, node_util_1.isDeepStrictEqual)(receipt, expected)) {
        throw (0, task_evidence_1.phaseAuthoringReceiptError)("PLANNING_PHASE_AUTHORING_RECEIPT_MISMATCH", "The phase authoring receipt does not match the current materialized child revisions, contract-impact fingerprints, declared order, criterion ownership, nested tasks, or normalized scaffold evidence.");
    }
    return expected;
}
