"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.buildImplementationSummaryArtifact = buildImplementationSummaryArtifact;
exports.reviewImplementationSummary = reviewImplementationSummary;
exports.buildReconciliationArtifact = buildReconciliationArtifact;
exports.reviewReconciliation = reviewReconciliation;
exports.renderImplementationSummaryBuildResult = renderImplementationSummaryBuildResult;
exports.renderImplementationSummaryReviewResult = renderImplementationSummaryReviewResult;
exports.renderReconciliationBuildResult = renderReconciliationBuildResult;
exports.renderReconciliationReviewResult = renderReconciliationReviewResult;
const node_fs_1 = __importDefault(require("node:fs"));
const node_path_1 = __importDefault(require("node:path"));
const node_child_process_1 = require("node:child_process");
const errors_1 = require("../errors");
const command_write_summary_1 = require("../license/command-write-summary");
const output_1 = require("../output");
const paths_1 = require("../paths");
const path_resolution_1 = require("../templates/path-resolution");
const declared_target_paths_1 = require("../validation/declared-target-paths");
const documentation_path_classifier_1 = require("../validation/documentation-path-classifier");
const review_output_contracts_1 = require("./review-output-contracts");
const task_scoped_change_report_1 = require("../validation/task-scoped-change-report");
const front_matter_utils_1 = require("./front-matter-utils");
const planning_document_utils_1 = require("./planning-document-utils");
const task_cycle_runtime_attribution_1 = require("./task-cycle-runtime-attribution");
const IMPLEMENTATION_SUMMARY_SECTIONS = [
    "Summary",
    "Changed Paths",
    "Acceptance Criteria Results",
    "Validation Performed",
    "Scope Classification",
    "Deviations",
    "Risks and Follow-Ups",
    "Open Questions"
];
const RECONCILIATION_SECTIONS = [
    "Review Status",
    "Milestone Intent",
    "Completed Task Summaries",
    "Acceptance Criteria Review",
    "Planned Work",
    "Discovered Work",
    "Backlog Work",
    "Accepted Residual Work",
    "Validation Review",
    "Follow-Up Tasks",
    "Review Concerns",
    "Final Notes"
];
const TASK_RECONCILIATION_SECTIONS = [
    "Review Status",
    "Original Intent",
    "Completed Work",
    "Acceptance Criteria Review",
    "Planned Work",
    "Discovered Work",
    "Backlog Work",
    "Accepted Residual Work",
    "Validation Review",
    "Follow-Up Tasks",
    "Review Concerns",
    "Final Notes"
];
const GENERATED_RECONCILIATION_SECTIONS = new Set([
    "Review Status",
    "Milestone Intent",
    "Completed Task Summaries",
    "Acceptance Criteria Review",
    "Planned Work",
    "Validation Review",
    "Review Concerns"
]);
const PLACEHOLDER_PATTERN = /(\bTBD\b|\bTODO\b|^PLACEHOLDER$|{{\s*[A-Za-z0-9_]+\s*}}|^pending\b)/im;
const TEMPLATE_SCAFFOLD_PATTERN = /^(Record newly discovered work that emerged during implementation or review\.|Move out-of-scope but relevant follow-up into backlog work here\.|Record reviewed residual work that does not block acceptance\.|List any concrete next tasks that remain after reconciliation\.)$/im;
const IMPLEMENTATION_SUMMARY_AUTHORING_GUIDANCE = Object.freeze({
    "Validation Exceptions": [
        "Authoring guidance:",
        "- Use this section only when planned validation could not run.",
        "- Runtime and hybrid validation exceptions must record the planned command, blocker, substitute evidence, residual risk, and follow-up validation path.",
        "- If there are no validation exceptions, use exactly `None.`"
    ].join("\n"),
    "Runtime Evidence Boundary": [
        "Authoring guidance:",
        "- Contract summaries must not claim runtime implementation unless runtime files changed and executable evidence is recorded.",
        "- Runtime and hybrid summaries must name non-documentation changed paths and executable validation evidence, or a structured validation exception for the validation gap only.",
        "- Validation exceptions cannot substitute for missing runtime code changes."
    ].join("\n")
});
const IMPLEMENTATION_SUMMARY_REFERENCE_PATTERN = /`?(\.day-shift\/[^\s`:)]+\/implementation-summary\.md)`?/g;
const MARKDOWN_IMPLEMENTATION_SUMMARY_LINK_PATTERN = /\[[^\]\n]+\]\(([^)\s]+\/implementation-summary\.md)\)/g;
const UNRESOLVED_ACCEPTANCE_REVIEW_PATTERN = /(pending review|completed task evidence:\s*none available|pending task evidence:.*remains incomplete|no milestone acceptance criteria were found|requires explicit human review)/im;
const WEAK_VALIDATION_REVIEW_PATTERN = /(no completed task validation evidence is available yet|validation section missing|no milestone validation focus was found|pending review|requires explicit human review)/im;
const CONTRADICTS_COMPLETED_STATUS_PATTERN = /(blocking|unresolved|must|required before closeout|incomplete evidence remains|remains incomplete|pending evidence)/im;
const PLACEHOLDER_EXACT_VALUES = new Set([
    "Pending.",
    "Pending. This implementation summary is initialized as the stable execution artifact for the task.",
    "None yet.",
    "None yet. Populate this section when implementation begins.",
    "None yet. Populate this section when implementation begins and verify the intended task-scoped code changes landed.",
    "Pending review after implementation.",
    "None yet. Record validation plus any changed-file inspection used to confirm the intended edits landed without obvious errors, missing edits, or unintended drift.",
    "Not started. Expected scope is limited to this task's declared implementation seams.",
    "Residual risk remains until executable behavior and validation evidence are recorded.",
    "Residual risk remains until executable behavior, changed-file verification, and validation evidence are recorded.",
    "Pending. This reconciliation artifact is initialized as the default milestone review rollup path for completed task summaries.",
    "- Pending. Add completed task implementation summaries as milestone execution work finishes.",
    "Pending review after task implementation summaries are available.",
    "Pending review. Evaluate each milestone criterion against the completed task summary evidence under these canonical headings.",
    "None yet. Record out-of-scope follow-up work here if implementation or review surfaces it.",
    "Pending. Summarize targeted CLI validation evidence once milestone tasks complete.",
    "Pending. Add concrete next tasks here only if reconciliation identifies remaining work after review.",
    "None accepted yet.",
    "Pending milestone review.",
    "Pending milestone review. No completed task implementation summaries are available yet.",
    "Pending milestone review. Evidence has been refreshed, but milestone acceptance still requires explicit human review."
]);
function buildImplementationSummaryArtifact(repositoryRoot, options) {
    const taskDefinitionPath = resolveRepositoryPath(repositoryRoot, options.taskDefinitionPath, "task-definition");
    if (!node_fs_1.default.existsSync(taskDefinitionPath.absolute)) {
        throw (0, errors_1.createUsageError)(`Task definition not found at '${taskDefinitionPath.relative}'.`, ["Pass an existing repository-relative --task-definition path."]);
    }
    const taskDocument = parseMarkdownDocument(taskDefinitionPath.relative, node_fs_1.default.readFileSync(taskDefinitionPath.absolute, "utf8"));
    assertArtifactType(taskDocument.frontMatterLines, taskDefinitionPath.relative, "task_definition");
    const context = parseTaskDefinitionContext(taskDefinitionPath.relative, taskDocument);
    const implementationSummaryPath = (0, front_matter_utils_1.toRepositoryLikePath)(node_path_1.default.join(node_path_1.default.dirname(taskDefinitionPath.relative), "implementation-summary.md"));
    const implementationSummaryAbsolute = node_path_1.default.join(repositoryRoot, implementationSummaryPath);
    const existingText = node_fs_1.default.existsSync(implementationSummaryAbsolute)
        ? node_fs_1.default.readFileSync(implementationSummaryAbsolute, "utf8")
        : null;
    const existingDocument = existingText === null
        ? null
        : parseMarkdownDocument(implementationSummaryPath, existingText);
    if (existingDocument !== null) {
        assertArtifactType(existingDocument.frontMatterLines, implementationSummaryPath, "implementation_summary");
    }
    const metadata = resolveSummaryMetadataState(existingDocument, taskDefinitionPath.relative);
    let rendered = renderImplementationSummaryDocument(repositoryRoot, context, {
        metadata,
        sections: resolveImplementationSummarySectionValues(existingDocument, metadata)
    });
    rendered = (0, task_cycle_runtime_attribution_1.injectRuntimeAttributionSummaryFrontMatter)(rendered, (0, task_cycle_runtime_attribution_1.deriveTaskCycleRuntimeAttribution)(repositoryRoot, {
        taskDefinitionPath: taskDefinitionPath.relative,
        taskMarkdownText: node_fs_1.default.readFileSync(taskDefinitionPath.absolute, "utf8"),
        summaryMarkdownText: rendered
    }));
    const declaredTargetPathEvidence = (0, declared_target_paths_1.readTaskDeclaredTargetPathEvidence)(taskDefinitionPath.relative, node_fs_1.default.readFileSync(taskDefinitionPath.absolute, "utf8"));
    const taskScopedChangeReport = (0, task_scoped_change_report_1.buildTaskScopedChangeReport)({
        statusLines: collectGitStatusPorcelainLines(repositoryRoot),
        declaredTargetEvidence: declaredTargetPathEvidence.evidence
    });
    const changed = existingText !== rendered;
    if (changed) {
        node_fs_1.default.mkdirSync(node_path_1.default.dirname(implementationSummaryAbsolute), { recursive: true });
        node_fs_1.default.writeFileSync(implementationSummaryAbsolute, rendered, "utf8");
    }
    return {
        repositoryRoot,
        taskDefinitionPath: taskDefinitionPath.relative,
        implementationSummaryPath,
        action: existingText === null ? "created" : "refreshed",
        changed,
        writeApplied: changed,
        commandWriteSummary: normalizeCanonicalBuildCommandWriteSummary({
            commandFamily: "implementation_summary",
            artifactPath: implementationSummaryPath,
            action: existingText === null ? "created" : "refreshed",
            changed,
            materialWhenChanged: true
        }),
        canonicalDestination: {
            sourcePath: taskDefinitionPath.relative,
            destinationPath: implementationSummaryPath,
            destinationKind: "task-implementation-summary",
            writeMode: "canonical-paired-artifact",
            writeApplied: changed,
            readOnly: false
        },
        reviewHandoff: {
            sourcePath: taskDefinitionPath.relative,
            destinationPath: implementationSummaryPath,
            handoffKind: "task-to-implementation-summary",
            defaultReviewRollup: "milestone-reconciliation",
            taskLevelReconciliation: "explicit-exception-only"
        },
        taskScopedChangeReport
    };
}
function reviewImplementationSummary(repositoryRoot, options) {
    const taskDefinitionPath = resolveRepositoryPath(repositoryRoot, options.taskDefinitionPath, "task-definition");
    if (!node_fs_1.default.existsSync(taskDefinitionPath.absolute)) {
        throw (0, errors_1.createUsageError)(`Task definition not found at '${taskDefinitionPath.relative}'.`, ["Pass an existing repository-relative --task-definition path."]);
    }
    const taskDefinitionText = node_fs_1.default.readFileSync(taskDefinitionPath.absolute, "utf8");
    const taskDocument = parseMarkdownDocument(taskDefinitionPath.relative, taskDefinitionText);
    assertArtifactType(taskDocument.frontMatterLines, taskDefinitionPath.relative, "task_definition");
    const context = parseTaskDefinitionContext(taskDefinitionPath.relative, taskDocument, {
        allowMissingExecutionMode: true
    });
    const declaredTargetPathEvidence = (0, declared_target_paths_1.readTaskDeclaredTargetPathEvidence)(taskDefinitionPath.relative, taskDefinitionText);
    const implementationSummaryPath = (0, front_matter_utils_1.toRepositoryLikePath)(node_path_1.default.join(node_path_1.default.dirname(taskDefinitionPath.relative), "implementation-summary.md"));
    const implementationSummaryAbsolute = node_path_1.default.join(repositoryRoot, implementationSummaryPath);
    if (!node_fs_1.default.existsSync(implementationSummaryAbsolute)) {
        throw (0, errors_1.createUsageError)(`Paired implementation summary not found at '${implementationSummaryPath}'.`, ["Run day-shift implementation-summary build first or restore the paired implementation-summary.md artifact."]);
    }
    const summaryDocument = parseMarkdownDocument(implementationSummaryPath, node_fs_1.default.readFileSync(implementationSummaryAbsolute, "utf8"));
    assertArtifactType(summaryDocument.frontMatterLines, implementationSummaryPath, "implementation_summary");
    const duplicateImplementationSummaryPaths = collectDuplicateImplementationSummaryPaths(repositoryRoot, taskDefinitionPath.relative, implementationSummaryPath);
    const missingEvidence = [];
    const placeholderResidue = [];
    const alignmentIssues = [];
    const reviewNotes = [];
    const implementationStatus = readTopLevelField(summaryDocument.frontMatterLines, "implementation_status")?.trim() ?? null;
    const artifactStatus = readTopLevelField(summaryDocument.frontMatterLines, "status")?.trim() ?? null;
    const taskStatus = readTopLevelField(taskDocument.frontMatterLines, "status")?.trim() ?? null;
    const taskReadiness = readTopLevelField(taskDocument.frontMatterLines, "readiness")?.trim() ?? null;
    const summaryExecutionMode = readTopLevelField(summaryDocument.frontMatterLines, "execution_mode")?.trim() ?? null;
    assertMatchingPlanningIdentity(context, summaryDocument.frontMatterLines, implementationSummaryPath, alignmentIssues, implementationSummaryIdentityKeys(context));
    const upstreamTaskDefinition = readUpstreamField(summaryDocument.frontMatterLines, "task_definition")?.trim() ?? null;
    if (upstreamTaskDefinition !== taskDefinitionPath.relative) {
        alignmentIssues.push(`Upstream task_definition should point to '${taskDefinitionPath.relative}', found '${upstreamTaskDefinition ?? "(missing)"}'.`);
    }
    if (context.executionMode === "") {
        alignmentIssues.push("Task definition execution_mode is missing.");
    }
    else if (!isAllowedExecutionMode(context.executionMode)) {
        alignmentIssues.push(`Task definition execution_mode uses unsupported value '${context.executionMode}'.`);
    }
    if (summaryExecutionMode === null || summaryExecutionMode === "") {
        alignmentIssues.push("Implementation summary execution_mode is missing.");
    }
    else if (!isAllowedExecutionMode(summaryExecutionMode)) {
        alignmentIssues.push(`Implementation summary execution_mode uses unsupported value '${summaryExecutionMode}'.`);
    }
    else if (summaryExecutionMode !== context.executionMode) {
        alignmentIssues.push(`Implementation summary execution_mode '${summaryExecutionMode}' does not match task definition execution_mode '${context.executionMode}'.`);
    }
    if (context.executionMode === "contract" && hasRuntimeImplementationClaim(summaryDocument.sections)) {
        alignmentIssues.push("Contract-mode implementation summary claims runtime implementation; use runtime or hybrid mode for runtime behavior changes, or reword the summary as contract evidence only.");
    }
    for (const duplicateImplementationSummaryPath of duplicateImplementationSummaryPaths) {
        alignmentIssues.push(`Duplicate or misplaced implementation-summary closeout artifact '${duplicateImplementationSummaryPath}' was found under the selected task directory; keep the canonical paired summary at '${implementationSummaryPath}' and correct the duplicate with an explicit follow-up command.`);
    }
    for (const sectionName of IMPLEMENTATION_SUMMARY_SECTIONS) {
        const sectionText = summaryDocument.sections.get(sectionName);
        if (sectionText === undefined) {
            missingEvidence.push(`Missing required section '${sectionName}'.`);
            continue;
        }
        if (isPlaceholderContent(sectionText)) {
            placeholderResidue.push(`Section '${sectionName}' still contains placeholder content.`);
        }
    }
    const changedPathsText = summaryDocument.sections.get("Changed Paths");
    if (changedPathsText === undefined || isPlaceholderContent(changedPathsText)) {
        missingEvidence.push("Changed Paths does not list implemented repository paths yet.");
    }
    else {
        const changedPathEvidence = extractSummaryChangedPathEvidence(changedPathsText);
        const concreteChangedPaths = changedPathEvidence
            .filter((entry) => entry.state === "path" && entry.path !== undefined)
            .map((entry) => entry.path);
        if (concreteChangedPaths.length === 0) {
            missingEvidence.push("Changed Paths does not list concrete repository-relative changed paths.");
        }
        if ((context.executionMode === "runtime" || context.executionMode === "hybrid") && concreteChangedPaths.length > 0) {
            const runtimeEligibleChangedPaths = concreteChangedPaths.filter((changedPath) => (0, documentation_path_classifier_1.classifyDocumentationPath)(changedPath).runtimeEligible);
            if (runtimeEligibleChangedPaths.length === 0) {
                missingEvidence.push("Runtime and hybrid implementation summaries must include at least one runtime-eligible changed path; current Changed Paths evidence is documentation-only.");
            }
            else {
                const explicitRuntimeTargetPaths = declaredTargetPathEvidence.explicitTargetPaths.filter((targetPath) => (0, documentation_path_classifier_1.classifyDocumentationPath)(targetPath).runtimeEligible);
                const deviationsText = summaryDocument.sections.get("Deviations");
                if (explicitRuntimeTargetPaths.length === 0) {
                    alignmentIssues.push("Task definition does not provide concrete runtime-eligible Runtime Delta target paths for runtime target-alignment review.");
                }
                else {
                    for (const changedPath of runtimeEligibleChangedPaths) {
                        if (pathOverlapsAnyTarget(changedPath, explicitRuntimeTargetPaths)) {
                            continue;
                        }
                        const matchingDeviationTarget = explicitRuntimeTargetPaths.find((targetPath) => hasRuntimeTargetReplacementDeviation(deviationsText, targetPath, changedPath));
                        if (matchingDeviationTarget !== undefined) {
                            reviewNotes.push(`Runtime changed path '${changedPath}' replaces declared Runtime Delta target '${matchingDeviationTarget}' with explicit deviation evidence.`);
                            continue;
                        }
                        alignmentIssues.push(`Runtime changed path '${changedPath}' does not overlap declared Runtime Delta target paths (${explicitRuntimeTargetPaths.join(", ")}) and requires explicit deviation evidence naming both the declared target and replacement changed path.`);
                    }
                }
            }
        }
        for (const entry of changedPathEvidence) {
            if (entry.state !== "path") {
                missingEvidence.push(entry.message);
            }
        }
        const explicitTargetPaths = declaredTargetPathEvidence.explicitTargetPaths;
        if (concreteChangedPaths.length > 0 && explicitTargetPaths.length === 0) {
            alignmentIssues.push("Task definition does not provide concrete Implementation Target Paths for changed-path overlap review.");
        }
        const deviationsText = summaryDocument.sections.get("Deviations");
        const hasDeviationJustification = hasConcreteDeviationJustification(deviationsText);
        for (const changedPath of concreteChangedPaths) {
            if (explicitTargetPaths.length === 0 || pathOverlapsAnyTarget(changedPath, explicitTargetPaths)) {
                continue;
            }
            if (hasDeviationJustification) {
                reviewNotes.push(`Changed path '${changedPath}' is outside declared task target paths but the Deviations section records justification.`);
                continue;
            }
            alignmentIssues.push(`Changed path '${changedPath}' is outside declared task target paths (${explicitTargetPaths.join(", ")}) and requires concrete deviation justification.`);
        }
    }
    const validationText = summaryDocument.sections.get("Validation Performed");
    if (validationText === undefined || isPlaceholderContent(validationText)) {
        missingEvidence.push("Validation Performed does not record any executed validation evidence.");
    }
    else if ((context.executionMode === "runtime" || context.executionMode === "hybrid")
        && hasValidationExceptionIntent(validationText)
        && !hasCompleteStructuredValidationException(validationText)) {
        missingEvidence.push("Runtime and hybrid validation exceptions must record planned command, blocker, substitute evidence, residual risk, and follow-up validation path.");
    }
    else if (!hasConcreteValidationEvidence(validationText)) {
        missingEvidence.push("Validation Performed only provides status-level validation claims; record commands, changed-file inspection, or an explicit validation exception.");
    }
    const acceptanceCriteriaResultsText = summaryDocument.sections.get("Acceptance Criteria Results");
    if (acceptanceCriteriaResultsText !== undefined
        && !isPlaceholderContent(acceptanceCriteriaResultsText)
        && !hasConcreteAcceptanceEvidence(acceptanceCriteriaResultsText)) {
        missingEvidence.push("Acceptance Criteria Results only assert completion; connect each result to changed paths, validation, commands, or concrete implementation evidence.");
    }
    missingEvidence.push(...(0, task_cycle_runtime_attribution_1.reviewTaskCycleRuntimeAttribution)(repositoryRoot, {
        taskDefinitionPath: taskDefinitionPath.relative,
        taskMarkdownText: taskDefinitionText,
        summaryMarkdownText: node_fs_1.default.readFileSync(implementationSummaryAbsolute, "utf8")
    }));
    if (implementationStatus !== "completed") {
        reviewNotes.push(`implementation_status is '${implementationStatus ?? "(missing)"}', so task closeout evidence is not complete yet.`);
    }
    if (implementationStatus === "completed" && artifactStatus !== "completed") {
        alignmentIssues.push(`implementation_status is 'completed' while shared status is '${artifactStatus ?? "(missing)"}'.`);
    }
    if (artifactStatus === "completed" && implementationStatus !== "completed") {
        alignmentIssues.push(`Shared status is 'completed' while implementation_status is '${implementationStatus ?? "(missing)"}'.`);
    }
    const closeoutEvidenceStatus = missingEvidence.length === 0
        && placeholderResidue.length === 0
        && alignmentIssues.length === 0
        && implementationStatus === "completed"
        && artifactStatus === "completed"
        ? "sufficient"
        : "insufficient";
    const blockingIssues = [
        ...missingEvidence,
        ...placeholderResidue,
        ...alignmentIssues
    ];
    const warnings = [...reviewNotes];
    const metadataHygieneFollowUps = [];
    if (closeoutEvidenceStatus === "sufficient"
        && (taskStatus !== "completed" || taskReadiness !== "completed")) {
        metadataHygieneFollowUps.push(`Paired task definition closeout metadata should be readiness=completed and status=completed; found readiness='${taskReadiness ?? "(missing)"}' and status='${taskStatus ?? "(missing)"}'. Recommended command: day-shift task update --task-definition ${taskDefinitionPath.relative} --active-artifact ${taskDefinitionPath.relative} --field readiness=completed --field status=completed.`);
    }
    const recoveryGuidance = buildEvidenceReviewRecoveryGuidance({
        artifactPath: implementationSummaryPath,
        reviewKind: "implementation-summary",
        blockingIssues,
        warnings,
        metadataHygieneFollowUps
    });
    const findings = buildEvidenceReviewFindings({
        artifactPath: implementationSummaryPath,
        reviewKind: "implementation-summary",
        blockingIssues,
        warnings,
        metadataHygieneFollowUps
    });
    return {
        taskDefinitionPath: taskDefinitionPath.relative,
        implementationSummaryPath,
        implementationStatus,
        artifactStatus,
        closeoutEvidenceStatus,
        missingEvidence,
        placeholderResidue,
        alignmentIssues,
        reviewNotes,
        blockingIssues,
        warnings,
        metadataHygieneFollowUps,
        recoveryGuidance,
        findings
    };
}
function buildReconciliationArtifact(repositoryRoot, options) {
    const selector = resolveReconciliationSelector(options);
    if (selector.kind === "task") {
        return buildTaskReconciliationArtifact(repositoryRoot, selector.taskDefinitionPath, selector.rationale);
    }
    return buildMilestoneReconciliationArtifact(repositoryRoot, selector.milestoneOverviewPath);
}
function normalizeCanonicalBuildCommandWriteSummary(options) {
    return (0, command_write_summary_1.normalizeCommandWriteSummary)({
        commandFamily: options.commandFamily,
        primaryOutputArtifacts: [options.artifactPath],
        updatedArtifacts: [
            {
                path: options.artifactPath,
                action: options.changed ? options.action : "kept",
                reason: options.materialWhenChanged && options.changed
                    ? undefined
                    : options.changed
                        ? options.action === "created"
                            ? "accepted_create"
                            : "accepted_refresh"
                        : "no_write",
                materialUpdate: options.materialWhenChanged && options.changed ? true : undefined
            }
        ]
    });
}
function buildMilestoneReconciliationArtifact(repositoryRoot, milestoneOverviewPathInput) {
    const milestoneOverviewPath = resolveRepositoryPath(repositoryRoot, milestoneOverviewPathInput, "milestone overview");
    if (!node_fs_1.default.existsSync(milestoneOverviewPath.absolute)) {
        throw (0, errors_1.createUsageError)(`Milestone overview not found at '${milestoneOverviewPath.relative}'.`, ["Pass an existing repository-relative --milestone-overview path."]);
    }
    const milestoneDocument = parseMarkdownDocument(milestoneOverviewPath.relative, node_fs_1.default.readFileSync(milestoneOverviewPath.absolute, "utf8"));
    assertArtifactType(milestoneDocument.frontMatterLines, milestoneOverviewPath.relative, "milestone_overview");
    const context = parseMilestoneOverviewContext(milestoneOverviewPath.relative, milestoneDocument);
    const reconciliationPath = (0, front_matter_utils_1.toRepositoryLikePath)(node_path_1.default.join(node_path_1.default.dirname(milestoneOverviewPath.relative), "reconciliation.md"));
    const reconciliationAbsolute = node_path_1.default.join(repositoryRoot, reconciliationPath);
    const existingText = node_fs_1.default.existsSync(reconciliationAbsolute)
        ? node_fs_1.default.readFileSync(reconciliationAbsolute, "utf8")
        : null;
    const existingDocument = existingText === null
        ? null
        : parseMarkdownDocument(reconciliationPath, existingText);
    if (existingDocument !== null) {
        assertArtifactType(existingDocument.frontMatterLines, reconciliationPath, "reconciliation");
    }
    const taskEvidence = collectMilestoneTaskEvidence(repositoryRoot, milestoneOverviewPath.relative);
    const metadata = resolveReconciliationMetadataState(existingDocument, milestoneOverviewPath.relative, taskEvidence);
    const rendered = renderReconciliationDocument(repositoryRoot, context, {
        metadata,
        sections: resolveReconciliationSectionValues(existingDocument, taskEvidence, context),
        milestoneOverviewPath: milestoneOverviewPath.relative
    });
    const changed = existingText !== rendered;
    if (changed) {
        node_fs_1.default.mkdirSync(node_path_1.default.dirname(reconciliationAbsolute), { recursive: true });
        node_fs_1.default.writeFileSync(reconciliationAbsolute, rendered, "utf8");
    }
    return {
        repositoryRoot,
        mode: "milestone",
        milestoneOverviewPath: milestoneOverviewPath.relative,
        taskDefinitionPath: null,
        reconciliationPath,
        action: existingText === null ? "created" : "refreshed",
        changed,
        writeApplied: changed,
        commandWriteSummary: normalizeCanonicalBuildCommandWriteSummary({
            commandFamily: "reconciliation",
            artifactPath: reconciliationPath,
            action: existingText === null ? "created" : "refreshed",
            changed,
            materialWhenChanged: false
        }),
        completedTaskSummaries: taskEvidence.completed.map((entry) => entry.relativePath),
        incompleteTaskSummaries: taskEvidence.incomplete.map((entry) => entry.relativePath),
        canonicalDestination: {
            sourcePath: milestoneOverviewPath.relative,
            destinationPath: reconciliationPath,
            destinationKind: "milestone-reconciliation",
            writeMode: "canonical-paired-artifact",
            writeApplied: changed,
            readOnly: false
        },
        reviewHandoff: {
            sourcePath: milestoneOverviewPath.relative,
            destinationPath: reconciliationPath,
            handoffKind: "implementation-summary-to-milestone-reconciliation",
            defaultReviewRollup: "milestone-reconciliation",
            taskLevelReconciliation: "explicit-exception-only"
        }
    };
}
function reviewReconciliation(repositoryRoot, options) {
    const selector = resolveReconciliationSelector(options);
    if (selector.kind === "task") {
        return reviewTaskReconciliation(repositoryRoot, selector.taskDefinitionPath);
    }
    return reviewMilestoneReconciliation(repositoryRoot, selector.milestoneOverviewPath);
}
function reviewMilestoneReconciliation(repositoryRoot, milestoneOverviewPathInput) {
    const milestoneOverviewPath = resolveRepositoryPath(repositoryRoot, milestoneOverviewPathInput, "milestone overview");
    if (!node_fs_1.default.existsSync(milestoneOverviewPath.absolute)) {
        throw (0, errors_1.createUsageError)(`Milestone overview not found at '${milestoneOverviewPath.relative}'.`, ["Pass an existing repository-relative --milestone-overview path."]);
    }
    const milestoneDocument = parseMarkdownDocument(milestoneOverviewPath.relative, node_fs_1.default.readFileSync(milestoneOverviewPath.absolute, "utf8"));
    assertArtifactType(milestoneDocument.frontMatterLines, milestoneOverviewPath.relative, "milestone_overview");
    const context = parseMilestoneOverviewContext(milestoneOverviewPath.relative, milestoneDocument);
    const reconciliationPath = (0, front_matter_utils_1.toRepositoryLikePath)(node_path_1.default.join(node_path_1.default.dirname(milestoneOverviewPath.relative), "reconciliation.md"));
    const reconciliationAbsolute = node_path_1.default.join(repositoryRoot, reconciliationPath);
    if (!node_fs_1.default.existsSync(reconciliationAbsolute)) {
        throw (0, errors_1.createUsageError)(`Paired reconciliation not found at '${reconciliationPath}'.`, ["Run day-shift reconciliation build first or restore the paired reconciliation.md artifact."]);
    }
    const reconciliationDocument = parseMarkdownDocument(reconciliationPath, node_fs_1.default.readFileSync(reconciliationAbsolute, "utf8"));
    assertArtifactType(reconciliationDocument.frontMatterLines, reconciliationPath, "reconciliation");
    const taskEvidence = collectMilestoneTaskEvidence(repositoryRoot, milestoneOverviewPath.relative);
    const evidenceGaps = [];
    const placeholderResidue = [];
    const alignmentIssues = [];
    const reviewConcerns = [];
    const findingIssues = [];
    const reconciliationArtifact = {
        family: "reconciliation",
        path: reconciliationPath,
        artifactType: "reconciliation"
    };
    const milestoneOverviewArtifact = {
        family: "milestone_overview",
        path: milestoneOverviewPath.relative,
        artifactType: "milestone_overview"
    };
    const reconciliationAffectedPath = {
        role: "finding-location",
        path: reconciliationPath,
        artifact: reconciliationArtifact
    };
    const milestoneOverviewAffectedPath = {
        role: "trace-link",
        path: milestoneOverviewPath.relative,
        artifact: milestoneOverviewArtifact,
        description: "review source milestone overview"
    };
    const recordEvidenceGap = (message, category, affectedPaths = [reconciliationAffectedPath]) => {
        evidenceGaps.push(message);
        findingIssues.push({
            message,
            severity: "error",
            category,
            path: reconciliationPath,
            artifacts: [reconciliationArtifact, milestoneOverviewArtifact],
            affectedPaths
        });
    };
    const recordPlaceholderResidue = (message, category) => {
        placeholderResidue.push(message);
        findingIssues.push({
            message,
            severity: "error",
            category,
            path: reconciliationPath,
            artifacts: [reconciliationArtifact, milestoneOverviewArtifact],
            affectedPaths: [reconciliationAffectedPath]
        });
    };
    const recordAlignmentIssue = (message, category, affectedPaths = [reconciliationAffectedPath]) => {
        alignmentIssues.push(message);
        findingIssues.push({
            message,
            severity: "error",
            category,
            path: reconciliationPath,
            artifacts: [reconciliationArtifact, milestoneOverviewArtifact],
            affectedPaths
        });
    };
    const recordReviewConcern = (message, category, affectedPaths = [reconciliationAffectedPath]) => {
        reviewConcerns.push(message);
        findingIssues.push({
            message,
            severity: "warning",
            category,
            path: reconciliationPath,
            artifacts: [reconciliationArtifact, milestoneOverviewArtifact],
            affectedPaths
        });
    };
    const reconciliationStatus = readTopLevelField(reconciliationDocument.frontMatterLines, "reconciliation_status")?.trim() ?? null;
    const artifactStatus = readTopLevelField(reconciliationDocument.frontMatterLines, "status")?.trim() ?? null;
    const declaredLaterWork = collectDeclaredLaterWorkEntries(repositoryRoot, context);
    const planningIdentityAlignmentIssues = [];
    assertMatchingPlanningIdentity(context, reconciliationDocument.frontMatterLines, reconciliationPath, planningIdentityAlignmentIssues, [
        "slice",
        "phase",
        "milestone",
        "planning_depth"
    ]);
    for (const planningIdentityAlignmentIssue of planningIdentityAlignmentIssues) {
        recordAlignmentIssue(planningIdentityAlignmentIssue, "metadata-alignment");
    }
    const upstreamMilestoneOverview = readUpstreamField(reconciliationDocument.frontMatterLines, "milestone_overview")?.trim() ?? null;
    if (upstreamMilestoneOverview !== milestoneOverviewPath.relative) {
        recordAlignmentIssue(`Upstream milestone_overview should point to '${milestoneOverviewPath.relative}', found '${upstreamMilestoneOverview ?? "(missing)"}'.`, "metadata-alignment", [reconciliationAffectedPath, milestoneOverviewAffectedPath]);
    }
    for (const sectionName of RECONCILIATION_SECTIONS) {
        const sectionText = reconciliationDocument.sections.get(sectionName);
        const findingCategory = reconciliationSectionFindingCategory(sectionName);
        if (sectionText === undefined) {
            recordEvidenceGap(`Missing required section '${sectionName}'.`, findingCategory);
            continue;
        }
        if (isPlaceholderContent(sectionText)) {
            recordPlaceholderResidue(`Section '${sectionName}' still contains placeholder review content.`, findingCategory);
        }
    }
    if (taskEvidence.completed.length === 0) {
        recordEvidenceGap("No completed task implementation summaries were found for this milestone.", "task-summary-reference-health");
    }
    for (const pendingSummary of taskEvidence.incomplete) {
        const pendingSummaryArtifact = {
            family: "implementation_summary",
            path: pendingSummary.relativePath,
            artifactType: "implementation_summary"
        };
        recordReviewConcern(`Task summary '${pendingSummary.relativePath}' is not complete yet (implementation_status: ${pendingSummary.implementationStatus || "(missing)"}).`, "task-summary-reference-health", [
            reconciliationAffectedPath,
            {
                role: "trace-link",
                path: pendingSummary.relativePath,
                artifact: pendingSummaryArtifact,
                description: "incomplete task implementation-summary evidence"
            }
        ]);
    }
    const completedTaskSummariesText = reconciliationDocument.sections.get("Completed Task Summaries");
    if (completedTaskSummariesText !== undefined && !isPlaceholderContent(completedTaskSummariesText)) {
        const referencedSummaryPaths = extractImplementationSummaryReferences(completedTaskSummariesText, reconciliationPath);
        const completedSummaryPaths = new Set(taskEvidence.completed.map((entry) => entry.relativePath));
        const incompleteSummaryPaths = new Set(taskEvidence.incomplete.map((entry) => entry.relativePath));
        const knownSummaryPaths = new Set([...completedSummaryPaths, ...incompleteSummaryPaths]);
        for (const completedSummary of taskEvidence.completed) {
            if (!referencedSummaryPaths.has(completedSummary.relativePath)) {
                const completedSummaryArtifact = {
                    family: "implementation_summary",
                    path: completedSummary.relativePath,
                    artifactType: "implementation_summary"
                };
                recordEvidenceGap(`Completed Task Summaries does not reference completed task summary '${completedSummary.relativePath}'.`, "task-summary-reference-health", [
                    reconciliationAffectedPath,
                    {
                        role: "trace-link",
                        path: completedSummary.relativePath,
                        artifact: completedSummaryArtifact,
                        description: "completed task implementation-summary evidence"
                    }
                ]);
            }
        }
        for (const referencedSummaryPath of referencedSummaryPaths) {
            const referencedSummaryArtifact = {
                family: "implementation_summary",
                path: referencedSummaryPath,
                artifactType: "implementation_summary"
            };
            if (!knownSummaryPaths.has(referencedSummaryPath)) {
                recordEvidenceGap(`Completed Task Summaries references stale or undiscovered task summary '${referencedSummaryPath}'.`, "task-summary-reference-health", [
                    reconciliationAffectedPath,
                    {
                        role: "trace-link",
                        path: referencedSummaryPath,
                        artifact: referencedSummaryArtifact,
                        description: "stale or undiscovered task implementation-summary reference"
                    }
                ]);
                continue;
            }
            if (incompleteSummaryPaths.has(referencedSummaryPath)) {
                recordReviewConcern(`Completed Task Summaries references incomplete task summary '${referencedSummaryPath}'.`, "task-summary-reference-health", [
                    reconciliationAffectedPath,
                    {
                        role: "trace-link",
                        path: referencedSummaryPath,
                        artifact: referencedSummaryArtifact,
                        description: "incomplete task implementation-summary reference"
                    }
                ]);
            }
        }
    }
    if (reconciliationStatus === "completed" && taskEvidence.incomplete.length > 0) {
        recordAlignmentIssue("reconciliation_status is 'completed' while one or more task implementation summaries remain incomplete.", "metadata-alignment");
    }
    if (reconciliationStatus === "completed" && artifactStatus !== "completed") {
        recordAlignmentIssue(`reconciliation_status is 'completed' while shared status is '${artifactStatus ?? "(missing)"}'.`, "metadata-alignment");
    }
    if (artifactStatus === "completed" && reconciliationStatus !== "completed") {
        recordAlignmentIssue(`Shared status is 'completed' while reconciliation_status is '${reconciliationStatus ?? "(missing)"}'.`, "metadata-alignment");
    }
    const acceptanceCriteriaReviewText = reconciliationDocument.sections.get("Acceptance Criteria Review");
    if (acceptanceCriteriaReviewText === undefined || isPlaceholderContent(acceptanceCriteriaReviewText)) {
        recordEvidenceGap("Acceptance Criteria Review does not resolve milestone acceptance criteria against completed task evidence yet.", "acceptance-criteria-coverage");
    }
    else if (UNRESOLVED_ACCEPTANCE_REVIEW_PATTERN.test(acceptanceCriteriaReviewText)) {
        recordEvidenceGap("Acceptance Criteria Review still describes unresolved or incomplete acceptance evidence.", "acceptance-criteria-coverage");
    }
    const validationReviewText = reconciliationDocument.sections.get("Validation Review");
    if (validationReviewText === undefined || isPlaceholderContent(validationReviewText)) {
        recordEvidenceGap("Validation Review does not summarize reviewable validation evidence yet.", "validation-coverage");
    }
    else if (WEAK_VALIDATION_REVIEW_PATTERN.test(validationReviewText)) {
        recordEvidenceGap("Validation Review still describes missing or weak validation evidence.", "validation-coverage");
    }
    for (const completedSummary of taskEvidence.completed) {
        if (completedSummary.validationText === null || isPlaceholderContent(completedSummary.validationText)) {
            const completedSummaryArtifact = {
                family: "implementation_summary",
                path: completedSummary.relativePath,
                artifactType: "implementation_summary"
            };
            recordEvidenceGap(`Completed task summary '${completedSummary.relativePath}' does not provide reviewable validation evidence.`, "validation-coverage", [
                reconciliationAffectedPath,
                {
                    role: "trace-link",
                    path: completedSummary.relativePath,
                    artifact: completedSummaryArtifact,
                    description: "completed task validation evidence source"
                }
            ]);
        }
        for (const runtimeEvidenceIssue of collectReconciliationRuntimeEvidenceIssues(completedSummary)) {
            const completedSummaryArtifact = {
                family: "implementation_summary",
                path: completedSummary.relativePath,
                artifactType: "implementation_summary"
            };
            recordEvidenceGap(runtimeEvidenceIssue, "validation-coverage", [
                reconciliationAffectedPath,
                {
                    role: "trace-link",
                    path: completedSummary.relativePath,
                    artifact: completedSummaryArtifact,
                    description: "runtime or hybrid task implementation-summary evidence source"
                }
            ]);
        }
    }
    const reviewConcernText = reconciliationDocument.sections.get("Review Concerns");
    if (hasActionableReviewText(reviewConcernText)) {
        recordReviewConcern("Review Concerns records authored review concerns that need human disposition.", "review-concern");
        if (reconciliationStatus === "completed" && CONTRADICTS_COMPLETED_STATUS_PATTERN.test(reviewConcernText ?? "")) {
            recordAlignmentIssue("reconciliation_status is 'completed' while Review Concerns still describes unresolved closeout concerns.", "metadata-alignment");
        }
    }
    for (const sectionName of ["Discovered Work", "Backlog Work", "Follow-Up Tasks"]) {
        const sectionText = reconciliationDocument.sections.get(sectionName);
        if (hasActionableReviewText(sectionText)) {
            const declaredLaterWorkMatch = matchDeclaredLaterWork(sectionText ?? "", declaredLaterWork);
            if (declaredLaterWorkMatch !== null) {
                const declarationArtifact = {
                    family: declaredLaterWorkMatch.kind === "milestone" ? "phase_overview" : "slice_overview",
                    path: declaredLaterWorkMatch.sourcePath,
                    artifactType: declaredLaterWorkMatch.kind === "milestone" ? "phase_overview" : "slice_overview"
                };
                recordReviewConcern(`${sectionName} records declared later ${declaredLaterWorkMatch.kind} work '${declaredLaterWorkMatch.slug}' from '${declaredLaterWorkMatch.sourcePath}' and is classified separately from unresolved residual concerns.`, "declared-later-work", [
                    reconciliationAffectedPath,
                    {
                        role: "trace-link",
                        path: declaredLaterWorkMatch.sourcePath,
                        artifact: declarationArtifact,
                        description: `parent ${declaredLaterWorkMatch.kind === "milestone" ? "phase" : "slice"} declaration for later ${declaredLaterWorkMatch.kind} '${declaredLaterWorkMatch.slug}'`
                    }
                ]);
                continue;
            }
            recordReviewConcern(`${sectionName} records remaining work as advisory reconciliation evidence.`, "review-concern");
            if (reconciliationStatus === "completed" && CONTRADICTS_COMPLETED_STATUS_PATTERN.test(sectionText ?? "")) {
                recordAlignmentIssue(`reconciliation_status is 'completed' while ${sectionName} still describes unresolved closeout work.`, "metadata-alignment");
            }
        }
    }
    const acceptedResidualWorkText = reconciliationDocument.sections.get("Accepted Residual Work");
    if (hasActionableReviewText(acceptedResidualWorkText)) {
        recordReviewConcern("Accepted Residual Work records accepted residual evidence for visibility.", "review-concern");
    }
    const closureEvidenceStatus = evidenceGaps.length === 0
        && placeholderResidue.length === 0
        && alignmentIssues.length === 0
        && taskEvidence.incomplete.length === 0
        && reconciliationStatus === "completed"
        && artifactStatus === "completed"
        ? "sufficient"
        : "insufficient";
    const blockingIssues = [
        ...evidenceGaps,
        ...placeholderResidue,
        ...alignmentIssues
    ];
    const warnings = [...reviewConcerns];
    const metadataHygieneFollowUps = [];
    const recoveryGuidance = buildEvidenceReviewRecoveryGuidance({
        artifactPath: reconciliationPath,
        reviewKind: "reconciliation",
        blockingIssues,
        warnings,
        metadataHygieneFollowUps
    });
    const findings = buildEvidenceReviewFindings({
        artifactPath: reconciliationPath,
        reviewKind: "reconciliation",
        blockingIssues,
        warnings,
        metadataHygieneFollowUps,
        issues: findingIssues
    });
    return {
        mode: "milestone",
        milestoneOverviewPath: milestoneOverviewPath.relative,
        taskDefinitionPath: null,
        reconciliationPath,
        reconciliationStatus,
        artifactStatus,
        closureEvidenceStatus,
        evidenceGaps,
        placeholderResidue,
        alignmentIssues,
        reviewConcerns,
        blockingIssues,
        warnings,
        metadataHygieneFollowUps,
        recoveryGuidance,
        findings
    };
}
function buildTaskReconciliationArtifact(repositoryRoot, taskDefinitionPathInput, rationale) {
    const taskDefinitionPath = resolveRepositoryPath(repositoryRoot, taskDefinitionPathInput, "task definition");
    const context = loadTaskDefinitionContext(repositoryRoot, taskDefinitionPath);
    const reconciliationPath = resolveTaskReconciliationPath(taskDefinitionPath.relative);
    const reconciliationAbsolute = node_path_1.default.join(repositoryRoot, reconciliationPath);
    const existingText = node_fs_1.default.existsSync(reconciliationAbsolute)
        ? node_fs_1.default.readFileSync(reconciliationAbsolute, "utf8")
        : null;
    const existingDocument = existingText === null
        ? null
        : parseMarkdownDocument(reconciliationPath, existingText);
    if (existingDocument !== null) {
        assertArtifactType(existingDocument.frontMatterLines, reconciliationPath, "reconciliation");
    }
    const implementationSummaryPath = resolveTaskImplementationSummaryPath(taskDefinitionPath.relative);
    const taskEvidence = collectTaskImplementationSummaryEvidence(repositoryRoot, implementationSummaryPath);
    const rendered = renderTaskReconciliationDocument(repositoryRoot, context, {
        metadata: resolveReconciliationMetadataState(existingDocument, taskDefinitionPath.relative),
        sections: resolveTaskReconciliationSectionValues(existingDocument, context, taskEvidence, rationale),
        taskDefinitionPath: taskDefinitionPath.relative,
        implementationSummaryPath
    });
    const changed = existingText !== rendered;
    if (changed) {
        node_fs_1.default.mkdirSync(node_path_1.default.dirname(reconciliationAbsolute), { recursive: true });
        node_fs_1.default.writeFileSync(reconciliationAbsolute, rendered, "utf8");
    }
    return {
        repositoryRoot,
        mode: "task",
        milestoneOverviewPath: context.milestoneOverviewPath,
        taskDefinitionPath: taskDefinitionPath.relative,
        reconciliationPath,
        action: existingText === null ? "created" : "refreshed",
        changed,
        writeApplied: changed,
        commandWriteSummary: normalizeCanonicalBuildCommandWriteSummary({
            commandFamily: "reconciliation",
            artifactPath: reconciliationPath,
            action: existingText === null ? "created" : "refreshed",
            changed,
            materialWhenChanged: false
        }),
        completedTaskSummaries: taskEvidence.implementationStatus === "completed" ? [implementationSummaryPath] : [],
        incompleteTaskSummaries: taskEvidence.implementationStatus === "completed" ? [] : [implementationSummaryPath],
        canonicalDestination: {
            sourcePath: taskDefinitionPath.relative,
            destinationPath: reconciliationPath,
            destinationKind: "task-reconciliation",
            writeMode: "canonical-paired-artifact",
            writeApplied: changed,
            readOnly: false
        },
        reviewHandoff: {
            sourcePath: taskDefinitionPath.relative,
            destinationPath: reconciliationPath,
            handoffKind: "task-definition-to-task-reconciliation",
            defaultReviewRollup: "milestone-reconciliation",
            taskLevelReconciliation: "explicit-exception-only"
        }
    };
}
function reviewTaskReconciliation(repositoryRoot, taskDefinitionPathInput) {
    const taskDefinitionPath = resolveRepositoryPath(repositoryRoot, taskDefinitionPathInput, "task definition");
    const context = loadTaskDefinitionContext(repositoryRoot, taskDefinitionPath);
    const reconciliationPath = resolveTaskReconciliationPath(taskDefinitionPath.relative);
    const reconciliationAbsolute = node_path_1.default.join(repositoryRoot, reconciliationPath);
    if (!node_fs_1.default.existsSync(reconciliationAbsolute)) {
        throw (0, errors_1.createUsageError)(`Task-level reconciliation not found at '${reconciliationPath}'.`, ["Run day-shift reconciliation build --task-definition <path> first or restore the explicit task-local reconciliation.md artifact."]);
    }
    const reconciliationDocument = parseMarkdownDocument(reconciliationPath, node_fs_1.default.readFileSync(reconciliationAbsolute, "utf8"));
    assertArtifactType(reconciliationDocument.frontMatterLines, reconciliationPath, "reconciliation");
    const evidenceGaps = [];
    const placeholderResidue = [];
    const alignmentIssues = [];
    const reviewConcerns = [];
    assertMatchingPlanningIdentity(context, reconciliationDocument.frontMatterLines, reconciliationPath, alignmentIssues, ["slice", "phase", "milestone", "task", "planning_depth"]);
    const expectedParentLinks = [
        ["slice_overview", context.sliceOverviewPath],
        ["phase_overview", context.phaseOverviewPath],
        ["milestone_overview", context.milestoneOverviewPath],
        ["task_definition", taskDefinitionPath.relative]
    ];
    for (const [key, expected] of expectedParentLinks) {
        const actual = readUpstreamField(reconciliationDocument.frontMatterLines, key)?.trim() ?? null;
        if (actual !== expected) {
            alignmentIssues.push(`Upstream ${key} should point to '${expected ?? "(missing)"}', found '${actual ?? "(missing)"}'.`);
        }
    }
    for (const sectionName of TASK_RECONCILIATION_SECTIONS) {
        const sectionText = reconciliationDocument.sections.get(sectionName);
        if (sectionText === undefined) {
            evidenceGaps.push(`Missing required section '${sectionName}'.`);
            continue;
        }
        if (isPlaceholderContent(sectionText)) {
            placeholderResidue.push(`Section '${sectionName}' still contains placeholder review content.`);
        }
    }
    const reconciliationStatus = readTopLevelField(reconciliationDocument.frontMatterLines, "reconciliation_status")?.trim() ?? null;
    const artifactStatus = readTopLevelField(reconciliationDocument.frontMatterLines, "status")?.trim() ?? null;
    if (reconciliationStatus !== "completed") {
        reviewConcerns.push(`reconciliation_status is '${reconciliationStatus ?? "(missing)"}', so task-level reconciliation closeout is not complete yet.`);
    }
    if (reconciliationStatus === "completed" && artifactStatus !== "completed") {
        alignmentIssues.push(`reconciliation_status is 'completed' while shared status is '${artifactStatus ?? "(missing)"}'.`);
    }
    if (artifactStatus === "completed" && reconciliationStatus !== "completed") {
        alignmentIssues.push(`Shared status is 'completed' while reconciliation_status is '${reconciliationStatus ?? "(missing)"}'.`);
    }
    const closureEvidenceStatus = evidenceGaps.length === 0
        && placeholderResidue.length === 0
        && alignmentIssues.length === 0
        && reconciliationStatus === "completed"
        && artifactStatus === "completed"
        ? "sufficient"
        : "insufficient";
    const blockingIssues = [
        ...evidenceGaps,
        ...placeholderResidue,
        ...alignmentIssues
    ];
    const warnings = [...reviewConcerns];
    const metadataHygieneFollowUps = [];
    const recoveryGuidance = buildEvidenceReviewRecoveryGuidance({
        artifactPath: reconciliationPath,
        reviewKind: "reconciliation",
        blockingIssues,
        warnings,
        metadataHygieneFollowUps
    });
    const findings = buildEvidenceReviewFindings({
        artifactPath: reconciliationPath,
        reviewKind: "reconciliation",
        blockingIssues,
        warnings,
        metadataHygieneFollowUps
    });
    return {
        mode: "task",
        milestoneOverviewPath: context.milestoneOverviewPath,
        taskDefinitionPath: taskDefinitionPath.relative,
        reconciliationPath,
        reconciliationStatus,
        artifactStatus,
        closureEvidenceStatus,
        evidenceGaps,
        placeholderResidue,
        alignmentIssues,
        reviewConcerns,
        blockingIssues,
        warnings,
        metadataHygieneFollowUps,
        recoveryGuidance,
        findings
    };
}
function collectGitStatusPorcelainLines(repositoryRoot) {
    const result = (0, node_child_process_1.spawnSync)("git", [
        "-C",
        repositoryRoot,
        "status",
        "--porcelain=v1",
        "--untracked-files=all"
    ], {
        encoding: "utf8"
    });
    if ((result.status !== 0 || result.error !== undefined) && result.stdout.trim() === "") {
        return [];
    }
    return result.stdout
        .split(/\r?\n/)
        .map((line) => line.trimEnd())
        .filter((line) => line.length > 0);
}
function renderImplementationSummaryBuildResult(result) {
    return [
        (0, output_1.renderTerminalHeading)("Implementation summary build", "title").trimEnd(),
        "",
        (0, output_1.renderTerminalSection)({
            heading: "Summary",
            fields: [
                { label: "Task definition", value: result.taskDefinitionPath },
                { label: "Implementation summary", value: result.implementationSummaryPath },
                { label: "Source path", value: result.canonicalDestination.sourcePath },
                { label: "Destination path", value: result.canonicalDestination.destinationPath },
                { label: "Review handoff", value: result.reviewHandoff.handoffKind },
                { label: "Default review rollup", value: result.reviewHandoff.defaultReviewRollup },
                { label: "Task-level reconciliation", value: result.reviewHandoff.taskLevelReconciliation },
                { label: "Action", value: result.action },
                { label: "Changed", value: result.changed ? "yes" : "no" }
            ],
            lines: [
                (0, output_1.renderTerminalBoundary)(result.writeApplied
                    ? {
                        kind: "write-applied",
                        target: result.canonicalDestination.destinationPath,
                        targetLabel: "Destination path",
                        stateSurface: "implementation summary artifact"
                    }
                    : {
                        kind: "mutating-no-op",
                        target: result.canonicalDestination.destinationPath,
                        targetLabel: "Destination path",
                        stateSurface: "implementation summary artifact",
                        reason: result.changed ? "Build reported changed content without applying a write." : "Summary already matched the intended paired artifact state."
                    })
            ]
        }),
        "",
        (0, output_1.renderTerminalSection)({
            heading: "Task-Scoped Change Evidence",
            fields: [
                { label: "Status paths", value: String(result.taskScopedChangeReport.statusPathEvidence.length) },
                { label: "Scoped changed paths", value: String(result.taskScopedChangeReport.scopedChangedPaths.length) },
                { label: "Unrelated changed paths", value: String(result.taskScopedChangeReport.unrelatedChangedPaths.length) },
                { label: "Invalid changed-path evidence", value: String(result.taskScopedChangeReport.comparison.invalidChangedPathEvidence.length) }
            ],
            lines: result.taskScopedChangeReport.scopedChangedPaths.length === 0
                ? ["- Scoped changed paths: none detected."]
                : result.taskScopedChangeReport.scopedChangedPaths.map((changedPath) => `- Scoped changed path: ${changedPath}`)
        })
    ].join("\n");
}
function renderImplementationSummaryReviewResult(result) {
    const lines = [
        (0, output_1.renderTerminalHeading)("Implementation summary review", "title").trimEnd(),
        "",
        (0, output_1.renderTerminalSection)({
            heading: "Summary",
            fields: [
                { label: "Task definition", value: result.taskDefinitionPath },
                { label: "Implementation summary", value: result.implementationSummaryPath },
                { label: "Implementation status", value: result.implementationStatus ?? "(missing)" },
                { label: "Artifact status", value: result.artifactStatus ?? "(missing)" },
                { label: "Closeout evidence", value: result.closeoutEvidenceStatus }
            ],
            lines: [(0, output_1.renderTerminalBoundary)({ kind: "read-only" })]
        }),
        "",
        (0, output_1.renderTerminalSection)({
            heading: "Review Output Contract",
            lines: (0, review_output_contracts_1.renderReviewOutputContractLines)()
        }),
        "",
        "Blocking Issues:"
    ];
    appendIssueLines(lines, result.blockingIssues);
    lines.push("", "Warnings:");
    appendIssueLines(lines, result.warnings);
    lines.push("", "Metadata-Hygiene Follow-Ups:");
    appendIssueLines(lines, result.metadataHygieneFollowUps);
    lines.push("", "Recovery Guidance:");
    appendIssueLines(lines, result.recoveryGuidance);
    if (result.findings.length > 0) {
        lines.push("", (0, output_1.renderValidationFindingsText)(result.findings, "Structured Findings"));
    }
    return lines.join("\n");
}
function renderReconciliationBuildResult(result) {
    const lines = [
        (0, output_1.renderTerminalHeading)("Reconciliation build", "title").trimEnd(),
        "",
        (0, output_1.renderTerminalSection)({
            heading: "Summary",
            fields: [
                { label: "Reconciliation mode", value: result.mode },
                { label: "Milestone overview", value: result.milestoneOverviewPath ?? "(not selected)" },
                { label: "Task definition", value: result.taskDefinitionPath ?? "(not selected)" },
                { label: "Reconciliation", value: result.reconciliationPath },
                { label: "Source path", value: result.canonicalDestination.sourcePath },
                { label: "Destination path", value: result.canonicalDestination.destinationPath },
                { label: "Review handoff", value: result.reviewHandoff.handoffKind },
                { label: "Default review rollup", value: result.reviewHandoff.defaultReviewRollup },
                { label: "Task-level reconciliation", value: result.reviewHandoff.taskLevelReconciliation },
                { label: "Action", value: result.action },
                { label: "Changed", value: result.changed ? "yes" : "no" }
            ],
            lines: [
                (0, output_1.renderTerminalBoundary)(result.writeApplied
                    ? {
                        kind: "write-applied",
                        target: result.canonicalDestination.destinationPath,
                        targetLabel: "Destination path",
                        stateSurface: "reconciliation artifact"
                    }
                    : {
                        kind: "mutating-no-op",
                        target: result.canonicalDestination.destinationPath,
                        targetLabel: "Destination path",
                        stateSurface: "reconciliation artifact",
                        reason: result.changed ? "Build reported changed content without applying a write." : "Reconciliation already matched the intended artifact state."
                    })
            ]
        }),
        "",
        "Completed Task Summaries:"
    ];
    appendIssueLines(lines, result.completedTaskSummaries);
    lines.push("", "Incomplete Task Summaries:");
    appendIssueLines(lines, result.incompleteTaskSummaries);
    return lines.join("\n");
}
function renderReconciliationReviewResult(result) {
    const lines = [
        (0, output_1.renderTerminalHeading)("Reconciliation review", "title").trimEnd(),
        "",
        (0, output_1.renderTerminalSection)({
            heading: "Summary",
            fields: [
                { label: "Reconciliation mode", value: result.mode },
                { label: "Milestone overview", value: result.milestoneOverviewPath ?? "(not selected)" },
                { label: "Task definition", value: result.taskDefinitionPath ?? "(not selected)" },
                { label: "Reconciliation", value: result.reconciliationPath },
                { label: "Reconciliation status", value: result.reconciliationStatus ?? "(missing)" },
                { label: "Artifact status", value: result.artifactStatus ?? "(missing)" },
                { label: "Closure evidence", value: result.closureEvidenceStatus }
            ],
            lines: [(0, output_1.renderTerminalBoundary)({ kind: "read-only" })]
        }),
        "",
        (0, output_1.renderTerminalSection)({
            heading: "Review Output Contract",
            lines: (0, review_output_contracts_1.renderReviewOutputContractLines)()
        }),
        "",
        "Blocking Issues:"
    ];
    appendIssueLines(lines, result.blockingIssues);
    lines.push("", "Warnings:");
    appendIssueLines(lines, result.warnings);
    lines.push("", "Metadata-Hygiene Follow-Ups:");
    appendIssueLines(lines, result.metadataHygieneFollowUps);
    lines.push("", "Recovery Guidance:");
    appendIssueLines(lines, result.recoveryGuidance);
    if (result.findings.length > 0) {
        lines.push("", (0, output_1.renderValidationFindingsText)(result.findings, "Structured Findings"));
    }
    return lines.join("\n");
}
function buildEvidenceReviewRecoveryGuidance(options) {
    const guidance = [];
    if (options.blockingIssues.length > 0) {
        guidance.push(`This ${options.reviewKind} review is read-only and applied no writes; repair the cited blocking findings in '${options.artifactPath}' through an explicit build, update, or metadata command before treating the review as closeout evidence.`);
    }
    if (options.warnings.length > 0) {
        guidance.push("Carry warnings forward as advisory evidence only; they do not authorize implicit status transitions or other writes.");
    }
    if (options.metadataHygieneFollowUps.length > 0) {
        guidance.push(`Apply metadata follow-ups only through an explicit update or sync command for '${options.artifactPath}' after the evidence is complete.`);
    }
    return guidance;
}
function buildEvidenceReviewFindings(options) {
    const reviewPrefix = options.reviewKind === "implementation-summary"
        ? "IMPLEMENTATION_SUMMARY_REVIEW"
        : "RECONCILIATION_REVIEW";
    if (options.issues !== undefined) {
        return [
            ...options.issues.map((issue) => {
                const code = `${reviewPrefix}_${formatFindingCategoryCode(issue.category)}`;
                const evidence = {
                    category: "planning-review",
                    details: {
                        category: issue.category,
                        blocking: issue.severity === "error",
                        reviewKind: options.reviewKind,
                        artifactPath: options.artifactPath
                    }
                };
                if (issue.severity === "error") {
                    return (0, output_1.createBlockingValidationFinding)({
                        code,
                        message: issue.message,
                        path: issue.path,
                        artifacts: issue.artifacts,
                        affectedPaths: issue.affectedPaths,
                        blockingReason: issue.category === "metadata-alignment"
                            ? "unsafe-scope-mismatch"
                            : "broken-traceability",
                        recovery: `This ${options.reviewKind} review is read-only and applied no writes; repair the ${issue.category} evidence in '${options.artifactPath}' through an explicit build, update, or metadata command before treating the review as closeout evidence.`,
                        evidence
                    });
                }
                return (0, output_1.createAdvisoryValidationFinding)({
                    code,
                    message: issue.message,
                    path: issue.path,
                    artifacts: issue.artifacts,
                    affectedPaths: issue.affectedPaths,
                    advisoryReason: issue.category === "review-concern"
                        ? "possible-discovered-work"
                        : "weak-evidence",
                    recovery: "Carry this reconciliation review finding forward as advisory evidence only; it does not authorize implicit status transitions or writes.",
                    evidence
                });
            }),
            ...options.metadataHygieneFollowUps.map((message) => createValidationFindingForMetadataFollowUp(reviewPrefix, options.artifactPath, message))
        ];
    }
    return [
        ...options.blockingIssues.map((message) => ({
            code: `${reviewPrefix}_BLOCKING`,
            message,
            severity: "error",
            path: options.artifactPath
        })),
        ...options.warnings.map((message) => ({
            code: `${reviewPrefix}_WARNING`,
            message,
            severity: "warning",
            path: options.artifactPath
        })),
        ...options.metadataHygieneFollowUps.map((message) => ({
            code: `${reviewPrefix}_METADATA_FOLLOW_UP`,
            message,
            severity: "informational",
            path: options.artifactPath
        }))
    ];
}
function createValidationFindingForMetadataFollowUp(reviewPrefix, artifactPath, message) {
    return (0, output_1.createAdvisoryValidationFinding)({
        code: `${reviewPrefix}_METADATA_FOLLOW_UP`,
        message,
        severity: "informational",
        level: "informational",
        path: artifactPath,
        advisoryReason: "weak-evidence",
        recovery: `Apply metadata follow-ups only through an explicit update or sync command for '${artifactPath}' after the evidence is complete.`,
        evidence: {
            category: "planning-review",
            details: {
                category: "metadata-alignment",
                blocking: false,
                artifactPath
            }
        }
    });
}
function formatFindingCategoryCode(category) {
    return category.replace(/-/g, "_").toUpperCase();
}
function reconciliationSectionFindingCategory(sectionName) {
    switch (sectionName) {
        case "Completed Task Summaries":
            return "task-summary-reference-health";
        case "Acceptance Criteria Review":
            return "acceptance-criteria-coverage";
        case "Validation Review":
            return "validation-coverage";
        case "Review Concerns":
        case "Discovered Work":
        case "Backlog Work":
        case "Accepted Residual Work":
        case "Follow-Up Tasks":
            return "review-concern";
        default:
            return "reconciliation-completeness";
    }
}
function extractImplementationSummaryReferences(text, sourceArtifactPath) {
    const references = new Set();
    for (const match of text.matchAll(IMPLEMENTATION_SUMMARY_REFERENCE_PATTERN)) {
        references.add(match[1]);
    }
    for (const match of text.matchAll(MARKDOWN_IMPLEMENTATION_SUMMARY_LINK_PATTERN)) {
        const linkedPath = decodeMarkdownLinkDestination(match[1]);
        if (linkedPath === null) {
            continue;
        }
        references.add(resolveImplementationSummaryReference(linkedPath, sourceArtifactPath));
    }
    return references;
}
function decodeMarkdownLinkDestination(destination) {
    try {
        return decodeURI(destination);
    }
    catch {
        return null;
    }
}
function resolveImplementationSummaryReference(referencePath, sourceArtifactPath) {
    if (referencePath.startsWith(".day-shift/")) {
        return (0, front_matter_utils_1.toRepositoryLikePath)(referencePath);
    }
    return (0, front_matter_utils_1.toRepositoryLikePath)(node_path_1.default.posix.normalize(node_path_1.default.posix.join(node_path_1.default.posix.dirname(sourceArtifactPath), referencePath)));
}
function hasActionableReviewText(text) {
    if (text === undefined || isPlaceholderContent(text)) {
        return false;
    }
    const normalized = text.trim().replace(/^[-*]\s+/gm, "").trim();
    if (normalized === "") {
        return false;
    }
    if (/^(none|none\.|no concerns\.?|no follow-up tasks\.?|none identified by build refresh\.?)$/i.test(normalized)) {
        return false;
    }
    if (/^no immediate evidence-gap concerns were detected during build refresh/i.test(normalized)) {
        return false;
    }
    if (/review is now complete/i.test(normalized)) {
        return false;
    }
    return true;
}
function collectDeclaredLaterWorkEntries(repositoryRoot, context) {
    return [
        ...collectLaterDeclaredChildren({
            repositoryRoot,
            sourcePath: context.phaseOverviewPath,
            sectionName: "Milestones",
            currentSlug: context.milestone,
            kind: "milestone"
        }),
        ...collectLaterDeclaredChildren({
            repositoryRoot,
            sourcePath: context.sliceOverviewPath,
            sectionName: "Phases",
            currentSlug: context.phase,
            kind: "phase"
        })
    ];
}
function collectLaterDeclaredChildren(options) {
    const sourceAbsolutePath = node_path_1.default.join(options.repositoryRoot, options.sourcePath);
    if (!node_fs_1.default.existsSync(sourceAbsolutePath)) {
        return [];
    }
    const document = parseMarkdownDocument(options.sourcePath, node_fs_1.default.readFileSync(sourceAbsolutePath, "utf8"));
    const declaredSlugs = parseDeclaredSlugBullets(document.sections.get(options.sectionName));
    const currentIndex = declaredSlugs.indexOf(options.currentSlug);
    if (currentIndex === -1) {
        return [];
    }
    return declaredSlugs.slice(currentIndex + 1).map((slug) => ({
        kind: options.kind,
        slug,
        sourcePath: options.sourcePath
    }));
}
function parseDeclaredSlugBullets(sectionText) {
    if (sectionText === undefined || isPlaceholderContent(sectionText)) {
        return [];
    }
    return [...sectionText.matchAll(/^\s*-\s+`([^`]+)`/gm)].map((match) => match[1].trim());
}
function matchDeclaredLaterWork(text, declaredLaterWork) {
    for (const entry of declaredLaterWork) {
        const expression = new RegExp(`(^|[^a-z0-9-])${escapeRegExp(entry.slug)}([^a-z0-9-]|$)`, "iu");
        if (expression.test(text)) {
            return entry;
        }
    }
    return null;
}
function escapeRegExp(value) {
    return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
}
function resolveRepositoryPath(repositoryRoot, inputPath, label) {
    try {
        const parsed = (0, paths_1.parseRepositoryRelativePath)(inputPath);
        return {
            relative: parsed.normalizedPath,
            absolute: node_path_1.default.join(repositoryRoot, parsed.normalizedPath)
        };
    }
    catch (error) {
        throw (0, errors_1.createUsageError)(`Invalid --${label.replace(/ /g, "-")} path '${inputPath}'.`, [error instanceof Error ? error.message : String(error)]);
    }
}
function parseMarkdownDocument(filePath, text) {
    const lines = text.split(/\r?\n/);
    if (lines[0] !== "---") {
        throw (0, errors_1.createUsageError)(`Artifact '${filePath}' is missing YAML front matter.`);
    }
    let closingIndex = -1;
    for (let index = 1; index < lines.length; index += 1) {
        if (lines[index] === "---") {
            closingIndex = index;
            break;
        }
    }
    if (closingIndex === -1) {
        throw (0, errors_1.createUsageError)(`Artifact '${filePath}' has malformed YAML front matter.`);
    }
    const frontMatterLines = lines.slice(1, closingIndex);
    const bodyLines = lines.slice(closingIndex + 1);
    const sections = new Map();
    let currentSection = null;
    let currentSectionLines = [];
    let title = null;
    for (const line of bodyLines) {
        const h1Match = line.match(/^#\s+(.+)$/);
        if (h1Match !== null && title === null) {
            title = h1Match[1].trim();
            continue;
        }
        const h2Match = line.match(/^##\s+(.+)$/);
        if (h2Match !== null) {
            if (currentSection !== null) {
                sections.set(currentSection, trimSectionContent(currentSectionLines));
            }
            currentSection = h2Match[1].trim();
            currentSectionLines = [];
            continue;
        }
        if (currentSection !== null) {
            currentSectionLines.push(line);
        }
    }
    if (currentSection !== null) {
        sections.set(currentSection, trimSectionContent(currentSectionLines));
    }
    return {
        frontMatterLines,
        sections,
        title
    };
}
function collectDuplicateImplementationSummaryPaths(repositoryRoot, taskDefinitionPath, canonicalImplementationSummaryPath) {
    const taskDirectory = node_path_1.default.dirname(taskDefinitionPath);
    const absoluteTaskDirectory = node_path_1.default.join(repositoryRoot, taskDirectory);
    const duplicatePaths = [];
    if (!node_fs_1.default.existsSync(absoluteTaskDirectory)) {
        return duplicatePaths;
    }
    const visit = (absoluteDirectory) => {
        const entries = node_fs_1.default.readdirSync(absoluteDirectory, { withFileTypes: true });
        for (const entry of entries) {
            const absoluteEntryPath = node_path_1.default.join(absoluteDirectory, entry.name);
            if (entry.isDirectory()) {
                visit(absoluteEntryPath);
                continue;
            }
            if (!entry.isFile() || !entry.name.endsWith(".md")) {
                continue;
            }
            const relativeEntryPath = (0, front_matter_utils_1.toRepositoryLikePath)(node_path_1.default.relative(repositoryRoot, absoluteEntryPath));
            if (relativeEntryPath === canonicalImplementationSummaryPath) {
                continue;
            }
            let entryText;
            try {
                entryText = node_fs_1.default.readFileSync(absoluteEntryPath, "utf8");
            }
            catch {
                continue;
            }
            let entryDocument;
            try {
                entryDocument = parseMarkdownDocument(relativeEntryPath, entryText);
            }
            catch {
                continue;
            }
            const artifactType = readTopLevelField(entryDocument.frontMatterLines, "artifact_type")?.trim();
            if (artifactType === "implementation_summary") {
                duplicatePaths.push(relativeEntryPath);
            }
        }
    };
    visit(absoluteTaskDirectory);
    return duplicatePaths.sort((a, b) => a.localeCompare(b, "en"));
}
function extractSummaryChangedPathEvidence(sectionText) {
    const bulletLines = sectionText
        .split(/\r?\n/)
        .map((line) => line.trim())
        .filter((line) => line.startsWith("- "));
    if (bulletLines.length === 0) {
        return [
            {
                state: "prose",
                rawText: sectionText.trim(),
                message: "Changed Paths contains prose-only evidence instead of repository-relative path bullets."
            }
        ];
    }
    const evidence = [];
    const seenPaths = new Set();
    for (const bulletLine of bulletLines) {
        const rawItem = bulletLine.slice(2).trim();
        const pathCandidate = extractPathCandidate(rawItem);
        if (isPlaceholderChangedPath(pathCandidate)) {
            evidence.push({
                state: "placeholder",
                rawText: rawItem,
                message: `Changed Paths entry '${rawItem}' is placeholder evidence.`
            });
            continue;
        }
        if (pathCandidate === null || /[\s;]/.test(pathCandidate)) {
            evidence.push({
                state: "prose",
                rawText: rawItem,
                message: `Changed Paths entry '${rawItem}' is not a concrete repository-relative path.`
            });
            continue;
        }
        try {
            const normalizedPath = (0, paths_1.parseRepositoryRelativePath)(pathCandidate).normalizedPath;
            if (seenPaths.has(normalizedPath)) {
                continue;
            }
            seenPaths.add(normalizedPath);
            evidence.push({
                state: "path",
                rawText: rawItem,
                path: normalizedPath,
                message: `Changed path '${normalizedPath}' is concrete summary evidence.`
            });
        }
        catch (error) {
            evidence.push({
                state: "invalid",
                rawText: rawItem,
                message: `Changed Paths entry '${rawItem}' is invalid: ${error instanceof Error ? error.message : String(error)}`
            });
        }
    }
    return evidence;
}
function extractPathCandidate(rawItem) {
    const codeSpanMatch = rawItem.match(/`([^`]+)`/);
    if (codeSpanMatch !== null) {
        return codeSpanMatch[1].trim();
    }
    const trimmed = rawItem.trim();
    return trimmed === "" ? null : trimmed;
}
function isPlaceholderChangedPath(value) {
    if (value === null) {
        return true;
    }
    return value.trim() === ""
        || /^none(?: currently)?\.?$/i.test(value)
        || /^none yet\b/i.test(value)
        || /^pending\b/i.test(value)
        || /^tbd\.?$/i.test(value)
        || /^todo\b/i.test(value)
        || /^placeholder$/i.test(value);
}
function pathOverlapsAnyTarget(changedPath, targetPaths) {
    return targetPaths.some((targetPath) => pathsOverlap(changedPath, targetPath));
}
function pathsOverlap(leftPath, rightPath) {
    return leftPath === rightPath
        || leftPath.startsWith(`${rightPath}/`)
        || rightPath.startsWith(`${leftPath}/`);
}
function hasConcreteDeviationJustification(sectionText) {
    if (sectionText === undefined || isPlaceholderContent(sectionText)) {
        return false;
    }
    const normalized = sectionText.trim().replace(/^[-*]\s+/gm, "").trim();
    return normalized !== ""
        && !/^(none|none\.|no deviations\.?|no deviation\.?|not applicable\.?|n\/a\.?)$/i.test(normalized);
}
function hasRuntimeTargetReplacementDeviation(sectionText, declaredTargetPath, changedPath) {
    if (!hasConcreteDeviationJustification(sectionText)) {
        return false;
    }
    const normalizedSectionText = normalizePathEvidenceText(sectionText ?? "");
    return normalizedSectionText.includes(declaredTargetPath)
        && normalizedSectionText.includes(changedPath);
}
function normalizePathEvidenceText(text) {
    return text
        .replace(/\\/g, "/")
        .replace(/`/g, "")
        .trim();
}
function hasConcreteValidationEvidence(sectionText) {
    const normalized = normalizeEvidenceText(sectionText);
    if (normalized === "") {
        return false;
    }
    return /`[^`]+`/.test(sectionText)
        || /\b(?:pnpm|npm|node|tsc|cargo|go test|pytest|vitest|jest)\b/i.test(normalized)
        || /\b(?:diff|numstat|stat|wc -l)\b/i.test(normalized)
        || /\b(?:inspect(?:ed|ion)?|review(?:ed)? changed|no-write review|skipped|substituted|blocked|inconclusive)\b/i.test(normalized)
        || /(?:^|\s)(?:\.day-shift|src|tests|dist|docs)\//.test(normalized);
}
function hasValidationExceptionIntent(sectionText) {
    const normalized = normalizeEvidenceText(sectionText);
    return /\b(?:skipped|could not run|unable to run|blocked|validation exception|substituted|substitute evidence)\b/i.test(normalized);
}
function hasCompleteStructuredValidationException(sectionText) {
    return [
        /\bplanned command\b/i,
        /\b(?:blocker|environment blocker|dependency blocker)\b/i,
        /\bsubstitute evidence\b/i,
        /\bresidual risk\b/i,
        /\bfollow-up (?:validation )?(?:command|path)\b/i
    ].every((pattern) => pattern.test(sectionText));
}
function hasConcreteAcceptanceEvidence(sectionText) {
    const normalized = normalizeEvidenceText(sectionText);
    if (normalized === "") {
        return false;
    }
    if (/^(?:passed|complete|completed|done|satisfied|accepted|implemented|met)[\s.:-]*$/i.test(normalized)) {
        return false;
    }
    return /`[^`]+`/.test(sectionText)
        || /\b(?:changed paths?|validation|command|test|diff|inspection|evidence|read-only|no-write|implemented|reports?|flags?|accepts?|rejects?|classifies|metadata|summary|review)\b/i.test(normalized)
        || /(?:^|\s)(?:\.day-shift|src|tests|dist|docs)\//.test(normalized);
}
function normalizeEvidenceText(sectionText) {
    return sectionText
        .split(/\r?\n/)
        .map((line) => line.trim().replace(/^[-*]\s+/, ""))
        .filter((line) => line !== "")
        .join(" ")
        .trim();
}
function trimSectionContent(lines) {
    const joined = lines.join("\n");
    return joined.replace(/^\n+/, "").replace(/\n+$/, "").trim();
}
function assertArtifactType(frontMatterLines, filePath, expectedType) {
    const artifactType = readTopLevelField(frontMatterLines, "artifact_type")?.trim();
    if (artifactType !== expectedType) {
        const guidance = expectedType === "milestone_overview"
            ? [
                "Pass an existing repository-relative --milestone-overview path to a milestone overview artifact.",
                "Do not pass a reconciliation.md path or another planning artifact as the build source."
            ]
            : [];
        throw (0, errors_1.createUsageError)(`Artifact '${filePath}' must use artifact_type: ${expectedType}.`, [
            `Found: ${artifactType ?? "(missing)"}`,
            ...guidance
        ]);
    }
}
function parseTaskDefinitionContext(filePath, document, options = {}) {
    const planningDepth = readRequiredTopLevelField(document.frontMatterLines, filePath, "planning_depth");
    const isLightweight = planningDepth === "lightweight";
    if (isLightweight) {
        assertLightweightTaskPath(filePath, document.frontMatterLines);
    }
    return {
        taskDefinitionPath: filePath,
        title: document.title ?? inferTaskTitleFromPath(filePath),
        slice: readRequiredTopLevelField(document.frontMatterLines, filePath, "slice"),
        phase: isLightweight ? null : readRequiredTopLevelField(document.frontMatterLines, filePath, "phase"),
        milestone: isLightweight ? null : readRequiredTopLevelField(document.frontMatterLines, filePath, "milestone"),
        task: readRequiredTopLevelField(document.frontMatterLines, filePath, "task"),
        planningDepth,
        sliceOverviewPath: readRequiredUpstreamField(document.frontMatterLines, filePath, "slice_overview"),
        phaseOverviewPath: isLightweight ? null : readRequiredUpstreamField(document.frontMatterLines, filePath, "phase_overview"),
        milestoneOverviewPath: isLightweight ? null : readRequiredUpstreamField(document.frontMatterLines, filePath, "milestone_overview"),
        upstreamSpecs: parseUpstreamSpecs(document.frontMatterLines, filePath),
        objectiveText: document.sections.get("Objective") ?? null,
        acceptanceCriteriaText: document.sections.get("Acceptance Criteria") ?? null,
        validationCommandsText: document.sections.get("Validation Commands") ?? null,
        executionMode: options.allowMissingExecutionMode
            ? readTopLevelField(document.frontMatterLines, "execution_mode")?.trim() ?? ""
            : readRequiredTopLevelField(document.frontMatterLines, filePath, "execution_mode")
    };
}
function parseMilestoneOverviewContext(filePath, document) {
    return {
        milestoneOverviewPath: filePath,
        title: document.title ?? inferTaskTitleFromPath(filePath),
        slice: readRequiredTopLevelField(document.frontMatterLines, filePath, "slice"),
        phase: readRequiredTopLevelField(document.frontMatterLines, filePath, "phase"),
        milestone: readRequiredTopLevelField(document.frontMatterLines, filePath, "milestone"),
        planningDepth: readRequiredTopLevelField(document.frontMatterLines, filePath, "planning_depth"),
        sliceOverviewPath: readRequiredUpstreamField(document.frontMatterLines, filePath, "slice_overview"),
        phaseOverviewPath: readRequiredUpstreamField(document.frontMatterLines, filePath, "phase_overview"),
        upstreamSpecs: parseUpstreamSpecs(document.frontMatterLines, filePath),
        purposeText: document.sections.get("Purpose") ?? null,
        acceptanceCriteriaText: document.sections.get("Acceptance Criteria") ?? null,
        validationFocusText: document.sections.get("Validation Focus") ?? null
    };
}
function resolveSummaryMetadataState(document, taskDefinitionPath) {
    return {
        workflowProvenance: readTopLevelField(document?.frontMatterLines ?? [], "workflow_provenance")?.trim() || "cli",
        workflowCliCommand: readTopLevelField(document?.frontMatterLines ?? [], "workflow_cli_command")?.trim()
            || `day-shift implementation-summary build --task-definition ${taskDefinitionPath}`,
        workflowManualException: readTopLevelField(document?.frontMatterLines ?? [], "workflow_manual_exception")?.trim() || "",
        implementationStatus: readTopLevelField(document?.frontMatterLines ?? [], "implementation_status")?.trim() || "pending",
        status: readTopLevelField(document?.frontMatterLines ?? [], "status")?.trim() || "draft"
    };
}
function resolveReconciliationMetadataState(document, milestoneOverviewPath, taskEvidence) {
    const allDeclaredTasksComplete = taskEvidence !== undefined
        && taskEvidence.completed.length > 0
        && taskEvidence.incomplete.length === 0;
    return {
        workflowProvenance: readTopLevelField(document?.frontMatterLines ?? [], "workflow_provenance")?.trim() || "cli",
        workflowCliCommand: readTopLevelField(document?.frontMatterLines ?? [], "workflow_cli_command")?.trim()
            || `day-shift reconciliation build --milestone-overview ${milestoneOverviewPath}`,
        workflowManualException: readTopLevelField(document?.frontMatterLines ?? [], "workflow_manual_exception")?.trim() || "",
        reconciliationStatus: allDeclaredTasksComplete
            ? "completed"
            : readTopLevelField(document?.frontMatterLines ?? [], "reconciliation_status")?.trim() || "pending",
        status: allDeclaredTasksComplete
            ? "completed"
            : readTopLevelField(document?.frontMatterLines ?? [], "status")?.trim() || "draft"
    };
}
function resolveImplementationSummarySectionValues(document, metadata) {
    const defaults = getDefaultImplementationSummarySections();
    for (const [sectionName, defaultValue] of Object.entries(defaults)) {
        const existing = document?.sections.get(sectionName);
        const authoredContent = existing === undefined
            ? ""
            : stripImplementationSummaryAuthoringGuidance(sectionName, existing);
        defaults[sectionName] = authoredContent !== "" ? authoredContent : defaultValue;
    }
    if (metadata.implementationStatus === "completed" && metadata.status === "completed") {
        normalizeCompletedImplementationSummaryNoneStates(defaults);
    }
    return defaults;
}
function stripImplementationSummaryAuthoringGuidance(sectionName, value) {
    const guidance = IMPLEMENTATION_SUMMARY_AUTHORING_GUIDANCE[sectionName];
    if (guidance === undefined) {
        return value;
    }
    let next = value;
    while (next.includes(guidance)) {
        next = next.replace(guidance, "");
    }
    return next.replace(/\n{3,}/g, "\n\n").trim();
}
function normalizeCompletedImplementationSummaryNoneStates(sections) {
    if (isPlaceholderContent(sections.Deviations)) {
        sections.Deviations = "None.";
    }
    if (isPlaceholderContent(sections["Risks and Follow-Ups"])) {
        sections["Risks and Follow-Ups"] = "None.";
    }
    if (isPlaceholderContent(sections["Open Questions"])) {
        sections["Open Questions"] = "- None currently.";
    }
}
function resolveReconciliationSectionValues(document, taskEvidence, context) {
    const defaults = getDefaultReconciliationSections(taskEvidence, context);
    for (const [sectionName, generatedValue] of Object.entries(defaults)) {
        if (GENERATED_RECONCILIATION_SECTIONS.has(sectionName)) {
            defaults[sectionName] = generatedValue;
            continue;
        }
        const existing = document?.sections.get(sectionName);
        if (existing === undefined || existing.trim() === "") {
            defaults[sectionName] = generatedValue;
            continue;
        }
        const preservedExisting = removeTemplateScaffoldContent(existing);
        if (isPlaceholderContent(preservedExisting)) {
            defaults[sectionName] = generatedValue;
            continue;
        }
        defaults[sectionName] = sectionContradictsTaskEvidence(sectionName, preservedExisting, taskEvidence)
            ? generatedValue
            : preservedExisting;
    }
    return defaults;
}
function resolveTaskReconciliationSectionValues(document, context, taskEvidence, rationale) {
    const defaults = getDefaultTaskReconciliationSections(context, taskEvidence, rationale);
    for (const [sectionName, defaultValue] of Object.entries(defaults)) {
        const existing = document?.sections.get(sectionName);
        if (existing === undefined || existing.trim() === "") {
            defaults[sectionName] = defaultValue;
            continue;
        }
        const preservedExisting = removeTemplateScaffoldContent(existing);
        defaults[sectionName] = isPlaceholderContent(preservedExisting) ? defaultValue : preservedExisting;
    }
    return defaults;
}
function renderImplementationSummaryDocument(repositoryRoot, context, options) {
    const templatePath = (0, path_resolution_1.resolveWorkspaceTemplateAbsolutePath)({
        repositoryRoot,
        templatePath: `.day-shift/templates/${context.planningDepth === "lightweight"
            ? "lightweight-implementation-summary.md"
            : "implementation-summary.md"}`
    });
    if (!node_fs_1.default.existsSync(templatePath)) {
        throw (0, errors_1.createUsageError)("Implementation summary template is missing.", [`Expected template at ${(0, front_matter_utils_1.toRepositoryLikePath)(node_path_1.default.relative(repositoryRoot, templatePath))}`]);
    }
    let text = node_fs_1.default.readFileSync(templatePath, "utf8");
    text = replaceSpecPlaceholders(text, context.upstreamSpecs);
    const replacements = {
        "{{slice}}": context.slice,
        "{{phase}}": context.phase ?? "",
        "{{milestone}}": context.milestone ?? "",
        "{{task}}": context.task,
        "{{planning_depth}}": context.planningDepth,
        "{{workflow_provenance}}": options.metadata.workflowProvenance,
        "{{workflow_cli_command}}": options.metadata.workflowCliCommand,
        "{{workflow_manual_exception}}": options.metadata.workflowManualException,
        "{{execution_mode}}": context.executionMode,
        "{{task_title}}": context.title,
        "{{slice_overview}}": context.sliceOverviewPath,
        "{{phase_overview}}": context.phaseOverviewPath ?? "",
        "{{milestone_overview}}": context.milestoneOverviewPath ?? "",
        "{{task_definition}}": context.taskDefinitionPath,
        "implementation_status: pending": `implementation_status: ${options.metadata.implementationStatus}`,
        "status: draft": `status: ${options.metadata.status}`,
        "{{summary}}": options.sections["Summary"],
        "{{changed_paths}}": options.sections["Changed Paths"],
        "{{acceptance_criteria_results}}": options.sections["Acceptance Criteria Results"],
        "{{validation_performed}}": options.sections["Validation Performed"],
        "{{validation_exceptions}}": options.sections["Validation Exceptions"] ?? "None.",
        "{{scope_classification}}": options.sections["Scope Classification"],
        "{{runtime_evidence_boundary}}": options.sections["Runtime Evidence Boundary"] ?? "Not evaluated yet.",
        "{{deviations}}": options.sections["Deviations"],
        "{{risks_and_follow_ups}}": options.sections["Risks and Follow-Ups"],
        "{{open_questions}}": options.sections["Open Questions"]
    };
    return replaceAll(text, replacements);
}
function assertLightweightTaskPath(filePath, frontMatterLines) {
    const taskSlug = readRequiredTopLevelField(frontMatterLines, filePath, "task");
    const expectedSuffix = `/tasks/${taskSlug}/task-definition.md`;
    if (!filePath.endsWith(expectedSuffix)) {
        throw (0, errors_1.createUsageError)(`Lightweight task definition '${filePath}' must live under a direct slice tasks/<task-slug>/ directory.`, [`Expected path suffix: ${expectedSuffix}`]);
    }
}
function implementationSummaryIdentityKeys(context) {
    if (context.planningDepth === "lightweight") {
        return ["slice", "task", "planning_depth"];
    }
    return ["slice", "phase", "milestone", "task", "planning_depth"];
}
function renderReconciliationDocument(repositoryRoot, context, options) {
    const templatePath = (0, path_resolution_1.resolveWorkspaceTemplateAbsolutePath)({
        repositoryRoot,
        templatePath: ".day-shift/templates/milestone-reconciliation.md"
    });
    if (!node_fs_1.default.existsSync(templatePath)) {
        throw (0, errors_1.createUsageError)("Milestone reconciliation template is missing.", ["Expected template at .day-shift/templates/milestone-reconciliation.md"]);
    }
    let text = node_fs_1.default.readFileSync(templatePath, "utf8");
    text = replaceSpecPlaceholders(text, context.upstreamSpecs);
    const replacements = {
        "{{slice}}": context.slice,
        "{{phase}}": context.phase,
        "{{milestone}}": context.milestone,
        "{{planning_depth}}": context.planningDepth,
        "{{workflow_provenance}}": options.metadata.workflowProvenance,
        "{{workflow_cli_command}}": options.metadata.workflowCliCommand,
        "{{workflow_manual_exception}}": options.metadata.workflowManualException,
        "{{slice_overview}}": context.sliceOverviewPath,
        "{{phase_overview}}": context.phaseOverviewPath,
        "{{milestone_overview}}": options.milestoneOverviewPath,
        "{{milestone_title}}": context.title,
        "reconciliation_status: pending": `reconciliation_status: ${options.metadata.reconciliationStatus}`,
        "status: draft": `status: ${options.metadata.status}`,
        "{{review_status}}": options.sections["Review Status"],
        "{{milestone_intent}}": options.sections["Milestone Intent"],
        "{{completed_task_summaries}}": options.sections["Completed Task Summaries"],
        "{{acceptance_criteria_review}}": options.sections["Acceptance Criteria Review"],
        "{{planned_work}}": options.sections["Planned Work"],
        "{{discovered_work}}": options.sections["Discovered Work"],
        "{{backlog_work}}": options.sections["Backlog Work"],
        "{{accepted_residual_work}}": options.sections["Accepted Residual Work"],
        "{{validation_review}}": options.sections["Validation Review"],
        "{{follow_up_tasks}}": options.sections["Follow-Up Tasks"],
        "{{review_concerns}}": options.sections["Review Concerns"],
        "{{final_notes}}": options.sections["Final Notes"]
    };
    return replaceAll(text, replacements).replace(/^None accepted yet\.$/m, options.sections["Accepted Residual Work"]);
}
function renderTaskReconciliationDocument(repositoryRoot, context, options) {
    const templatePath = (0, path_resolution_1.resolveWorkspaceTemplateAbsolutePath)({
        repositoryRoot,
        templatePath: ".day-shift/templates/reconciliation.md"
    });
    if (!node_fs_1.default.existsSync(templatePath)) {
        throw (0, errors_1.createUsageError)("Task-level reconciliation template is missing.", ["Expected template at .day-shift/templates/reconciliation.md"]);
    }
    let text = node_fs_1.default.readFileSync(templatePath, "utf8");
    text = replaceSpecPlaceholders(text, context.upstreamSpecs);
    const replacements = {
        "{{slice}}": context.slice,
        "{{phase}}": context.phase ?? "",
        "{{milestone}}": context.milestone ?? "",
        "{{task}}": context.task,
        "{{planning_depth}}": context.planningDepth,
        "{{workflow_provenance}}": options.metadata.workflowProvenance,
        "{{workflow_cli_command}}": options.metadata.workflowCliCommand,
        "{{workflow_manual_exception}}": options.metadata.workflowManualException,
        "{{slice_overview}}": context.sliceOverviewPath,
        "{{phase_overview}}": context.phaseOverviewPath ?? "",
        "{{milestone_overview}}": context.milestoneOverviewPath ?? "",
        "{{task_definition}}": options.taskDefinitionPath,
        "{{implementation_summary}}": options.implementationSummaryPath,
        "{{task_title}}": context.title,
        "reconciliation_status: pending": `reconciliation_status: ${options.metadata.reconciliationStatus}`,
        "status: draft": `status: ${options.metadata.status}`,
        "{{review_status}}": options.sections["Review Status"],
        "{{original_intent}}": options.sections["Original Intent"],
        "{{completed_work}}": options.sections["Completed Work"],
        "{{acceptance_criteria_review}}": options.sections["Acceptance Criteria Review"],
        "{{planned_work}}": options.sections["Planned Work"],
        "{{discovered_work}}": options.sections["Discovered Work"],
        "{{backlog_work}}": options.sections["Backlog Work"],
        "{{accepted_residual_work}}": options.sections["Accepted Residual Work"],
        "{{validation_review}}": options.sections["Validation Review"],
        "{{follow_up_tasks}}": options.sections["Follow-Up Tasks"],
        "{{review_concerns}}": options.sections["Review Concerns"],
        "{{final_notes}}": options.sections["Final Notes"]
    };
    return replaceAll(text, replacements);
}
function replaceSpecPlaceholders(templateText, upstreamSpecs) {
    const upstreamSpecsBlock = upstreamSpecs
        .map((entry) => {
        return [
            `    - id: ${entry.id}`,
            `      depth: ${entry.depth}`,
            `      ref: ${JSON.stringify(entry.ref)}`,
            `      source_type: ${JSON.stringify(entry.sourceType)}`
        ].join("\n");
    })
        .join("\n");
    return templateText.replace([
        "  specs:",
        "    - id: \"{{spec_id}}\"",
        "      depth: \"{{spec_depth}}\"",
        "      ref: \"{{spec_ref}}\"",
        "      source_type: \"{{source_type}}\""
    ].join("\n"), ["  specs:", upstreamSpecsBlock].join("\n"));
}
function replaceAll(text, replacements) {
    let next = text;
    for (const [token, value] of Object.entries(replacements)) {
        next = next.split(token).join(value);
    }
    return next;
}
function getDefaultImplementationSummarySections() {
    return {
        Summary: "Pending. This implementation summary is initialized as the stable execution artifact for the task.",
        "Changed Paths": "None yet. Populate this section when implementation begins and verify the intended task-scoped code changes landed.",
        "Acceptance Criteria Results": "Pending review after implementation.",
        "Validation Performed": "None yet. Record validation plus any changed-file inspection used to confirm the intended edits landed without obvious errors, missing edits, or unintended drift.",
        "Validation Exceptions": "None.",
        "Scope Classification": "Not started. Expected scope is limited to this task's declared implementation seams.",
        "Runtime Evidence Boundary": "Not evaluated yet. Runtime and hybrid summaries must not claim runtime implementation without runtime changed paths and executable validation evidence.",
        Deviations: "None yet.",
        "Risks and Follow-Ups": "Residual risk remains until executable behavior, changed-file verification, and validation evidence are recorded.",
        "Open Questions": "- None currently."
    };
}
function getDefaultReconciliationSections(taskEvidence, context) {
    return {
        "Review Status": buildReviewStatusText(taskEvidence),
        "Milestone Intent": buildMilestoneIntentText(context),
        "Completed Task Summaries": buildCompletedTaskSummariesText(taskEvidence.completed),
        "Acceptance Criteria Review": buildAcceptanceCriteriaReviewText(taskEvidence, context),
        "Planned Work": buildPlannedWorkText(taskEvidence),
        "Discovered Work": "None.",
        "Backlog Work": "None.",
        "Accepted Residual Work": "None.",
        "Validation Review": buildValidationReviewText(taskEvidence.completed, context),
        "Follow-Up Tasks": "None.",
        "Review Concerns": buildReviewConcernsText(taskEvidence),
        "Final Notes": taskEvidence.completed.length === 0
            ? "Milestone evidence has been refreshed; no completed task implementation summaries are available yet."
            : "Milestone evidence has been refreshed from task summaries; explicit human review still owns milestone acceptance."
    };
}
function getDefaultTaskReconciliationSections(context, taskEvidence, rationale) {
    const hasCompletedSummary = taskEvidence.implementationStatus === "completed";
    return {
        "Review Status": [
            "Task-level reconciliation exception selected explicitly from the source task definition.",
            `Source task definition: ${context.taskDefinitionPath}.`,
            `Parent milestone overview: ${context.milestoneOverviewPath ?? "(missing)"}.`,
            `Exception rationale: ${rationale}.`,
            "Default review rollup remains milestone-reconciliation unless this explicit task-level selector is used."
        ].join("\n"),
        "Original Intent": context.objectiveText === null || isPlaceholderContent(context.objectiveText)
            ? "Review this task against its task-definition objective and acceptance criteria."
            : context.objectiveText,
        "Completed Work": taskEvidence.summaryText ?? "No paired implementation summary evidence is available yet.",
        "Acceptance Criteria Review": taskEvidence.acceptanceCriteriaText ?? buildTaskAcceptanceFallbackText(context),
        "Planned Work": hasCompletedSummary
            ? "No remaining planned work was inferred by task-level reconciliation build."
            : `Paired implementation summary remains incomplete (implementation_status: ${taskEvidence.implementationStatus || "(missing)"}).`,
        "Discovered Work": "None identified by build refresh.",
        "Backlog Work": "None identified by build refresh.",
        "Accepted Residual Work": "None identified by build refresh.",
        "Validation Review": taskEvidence.validationText ?? buildTaskValidationFallbackText(context),
        "Follow-Up Tasks": "None identified by build refresh.",
        "Review Concerns": hasCompletedSummary
            ? "Task-level reconciliation remains an explicit exception; milestone-level reconciliation is still the default rollup."
            : "Task-level reconciliation was created before paired implementation-summary closeout evidence was complete.",
        "Final Notes": "Task-level reconciliation path resolution completed from an explicit task-definition selector; this artifact is not the default milestone rollup."
    };
}
function buildTaskAcceptanceFallbackText(context) {
    if (context.acceptanceCriteriaText === null || isPlaceholderContent(context.acceptanceCriteriaText)) {
        return "No paired implementation-summary acceptance evidence is available yet.";
    }
    return [
        "Task acceptance criteria from the task definition:",
        ...normalizeReviewLines(context.acceptanceCriteriaText),
        "",
        "No paired implementation-summary acceptance evidence is available yet."
    ].join("\n");
}
function buildTaskValidationFallbackText(context) {
    if (context.validationCommandsText === null || isPlaceholderContent(context.validationCommandsText)) {
        return "No paired implementation-summary validation evidence is available yet.";
    }
    return [
        "Task validation commands from the task definition:",
        ...normalizeReviewLines(context.validationCommandsText),
        "",
        "No paired implementation-summary validation evidence is available yet."
    ].join("\n");
}
function buildReviewStatusText(taskEvidence) {
    if (taskEvidence.completed.length === 0) {
        return "Not reviewed. No completed task implementation summaries were found for this milestone.";
    }
    if (taskEvidence.incomplete.length > 0) {
        return `Partial. ${taskEvidence.completed.length} completed task implementation summar${taskEvidence.completed.length === 1 ? "y" : "ies"} ${taskEvidence.completed.length === 1 ? "was" : "were"} found, but ${taskEvidence.incomplete.length} remain incomplete or pending further implementation evidence.`;
    }
    return "Completed. Every declared task has a completed, non-placeholder implementation summary and the milestone evidence is ready for reconciliation review.";
}
function buildAcceptanceCriteriaReviewText(taskEvidence, context) {
    const criteriaLines = context.acceptanceCriteriaText === null || isPlaceholderContent(context.acceptanceCriteriaText)
        ? ["- No milestone acceptance criteria were found in the milestone overview."]
        : normalizeReviewLines(context.acceptanceCriteriaText);
    const evidenceLines = taskEvidence.completed.length === 0
        ? ["- Completed task evidence: none available."]
        : taskEvidence.completed.map((entry) => `- Completed task evidence: ${entry.relativePath}.`);
    const pendingLines = taskEvidence.incomplete.length === 0
        ? ["- Pending task evidence: none detected by build refresh."]
        : taskEvidence.incomplete.map((entry) => {
            const suffix = formatSummaryEvidenceIssueSuffix(entry);
            return `- Pending task evidence: ${entry.relativePath} remains incomplete (implementation_status: ${entry.implementationStatus || "(missing)"}${suffix}).`;
        });
    return [
        "Milestone acceptance criteria from the overview:",
        ...criteriaLines,
        "",
        "Evidence available for review:",
        ...evidenceLines,
        ...pendingLines
    ].join("\n");
}
function buildMilestoneIntentText(context) {
    if (context.purposeText !== null && !isPlaceholderContent(context.purposeText)) {
        return context.purposeText;
    }
    return "Review whether milestone outcomes and completed task summary evidence satisfy the milestone's intended review boundary without introducing new closure claims automatically.";
}
function buildCompletedTaskSummariesText(completedEvidence) {
    if (completedEvidence.length === 0) {
        return "- No completed task implementation summaries were found for this milestone.";
    }
    return completedEvidence
        .map((entry) => {
        const summaryExcerpt = entry.summaryText === null ? "summary section missing" : firstContentLine(entry.summaryText);
        return `- ${entry.relativePath}: ${summaryExcerpt}`;
    })
        .join("\n");
}
function buildPlannedWorkText(taskEvidence) {
    if (taskEvidence.incomplete.length === 0) {
        return "Completed. No planned work remains inside this milestone.";
    }
    return taskEvidence.incomplete
        .map((entry) => {
        const suffix = formatSummaryEvidenceIssueSuffix(entry);
        return `- ${entry.relativePath} remains incomplete (implementation_status: ${entry.implementationStatus || "(missing)"}${suffix}).`;
    })
        .join("\n");
}
function buildValidationReviewText(completedEvidence, context) {
    const focusLines = context.validationFocusText === null || isPlaceholderContent(context.validationFocusText)
        ? ["- No milestone validation focus was found in the milestone overview."]
        : normalizeReviewLines(context.validationFocusText);
    const evidenceLines = completedEvidence.length === 0
        ? ["- No completed task validation evidence is available yet."]
        : completedEvidence
            .map((entry) => {
            if (entry.validationText === null) {
                return `- ${entry.relativePath}: validation section missing`;
            }
            return [
                `- ${entry.relativePath}:`,
                ...normalizeReviewLines(entry.validationText)
            ].join("\n");
        });
    return [
        "Milestone validation focus from the overview:",
        ...focusLines,
        "",
        "Completed task validation evidence:",
        ...evidenceLines
    ].join("\n");
}
function buildReviewConcernsText(taskEvidence) {
    if (taskEvidence.incomplete.length === 0) {
        return "None.";
    }
    return taskEvidence.incomplete
        .map((entry) => {
        const evidenceIssues = entry.evidenceIssues !== undefined && entry.evidenceIssues.length > 0
            ? ` ${entry.evidenceIssues.join(" ")}`
            : "";
        return `- Incomplete task evidence remains at ${entry.relativePath}.${evidenceIssues}`;
    })
        .join("\n");
}
function collectMilestoneTaskEvidence(repositoryRoot, milestoneOverviewPath) {
    const milestoneOverviewAbsolute = node_path_1.default.join(repositoryRoot, milestoneOverviewPath);
    const milestoneDirectory = node_path_1.default.dirname(milestoneOverviewAbsolute);
    const declaredTaskSlugs = node_fs_1.default.existsSync(milestoneOverviewAbsolute)
        ? parseDeclaredTaskSlugs(parseMarkdownDocument(milestoneOverviewPath, node_fs_1.default.readFileSync(milestoneOverviewAbsolute, "utf8")))
        : [];
    const completed = [];
    const incomplete = [];
    for (const taskSlug of declaredTaskSlugs) {
        const summaryAbsolute = node_path_1.default.join(milestoneDirectory, "tasks", taskSlug, "implementation-summary.md");
        const relativePath = (0, front_matter_utils_1.toRepositoryLikePath)(node_path_1.default.relative(repositoryRoot, summaryAbsolute));
        if (!node_fs_1.default.existsSync(summaryAbsolute)) {
            incomplete.push({
                relativePath,
                implementationStatus: "missing",
                artifactStatus: "missing",
                summaryText: null,
                validationText: null,
                evidenceIssues: ["Paired implementation summary is missing for the declared task."]
            });
            continue;
        }
        const document = parseMarkdownDocument(relativePath, node_fs_1.default.readFileSync(summaryAbsolute, "utf8"));
        assertArtifactType(document.frontMatterLines, relativePath, "implementation_summary");
        const evidence = {
            relativePath,
            implementationStatus: readTopLevelField(document.frontMatterLines, "implementation_status")?.trim() || "",
            artifactStatus: readTopLevelField(document.frontMatterLines, "status")?.trim() || "",
            executionMode: readTopLevelField(document.frontMatterLines, "execution_mode")?.trim() ?? null,
            summaryText: document.sections.get("Summary") ?? null,
            changedPathsText: document.sections.get("Changed Paths") ?? null,
            acceptanceCriteriaText: document.sections.get("Acceptance Criteria Results") ?? null,
            risksAndFollowUpsText: document.sections.get("Risks and Follow-Ups") ?? null,
            validationText: document.sections.get("Validation Performed") ?? null
        };
        const taskDefinitionPath = (0, front_matter_utils_1.toRepositoryLikePath)(node_path_1.default.join(node_path_1.default.dirname(relativePath), "task-definition.md"));
        const taskDefinitionAbsolute = node_path_1.default.join(repositoryRoot, taskDefinitionPath);
        const evidenceIssues = [
            ...collectImplementationSummaryEvidenceIssues(document),
            ...(node_fs_1.default.existsSync(taskDefinitionAbsolute)
                ? (0, task_cycle_runtime_attribution_1.reviewTaskCycleRuntimeAttribution)(repositoryRoot, {
                    taskDefinitionPath,
                    taskMarkdownText: node_fs_1.default.readFileSync(taskDefinitionAbsolute, "utf8"),
                    summaryMarkdownText: node_fs_1.default.readFileSync(summaryAbsolute, "utf8")
                })
                : [])
        ];
        if (evidence.implementationStatus === "completed" && evidence.artifactStatus === "completed" && evidenceIssues.length === 0) {
            completed.push(evidence);
        }
        else {
            incomplete.push({ ...evidence, evidenceIssues });
        }
    }
    completed.sort((left, right) => left.relativePath.localeCompare(right.relativePath));
    incomplete.sort((left, right) => left.relativePath.localeCompare(right.relativePath));
    return { completed, incomplete };
}
function parseDeclaredTaskSlugs(document) {
    const tasksText = document.sections.get("Tasks");
    if (tasksText === undefined || isPlaceholderContent(tasksText)) {
        return [];
    }
    const taskSlugs = [];
    const seen = new Set();
    for (const line of tasksText.split(/\r?\n/)) {
        const declaration = (0, planning_document_utils_1.parseDeclaredChildSlugBullet)(line);
        if (declaration === null) {
            continue;
        }
        const taskSlug = declaration.slug.trim();
        if (seen.has(taskSlug)) {
            continue;
        }
        seen.add(taskSlug);
        taskSlugs.push(taskSlug);
    }
    return taskSlugs;
}
function collectTaskImplementationSummaryEvidence(repositoryRoot, implementationSummaryPath) {
    const summaryAbsolute = node_path_1.default.join(repositoryRoot, implementationSummaryPath);
    if (!node_fs_1.default.existsSync(summaryAbsolute)) {
        return {
            relativePath: implementationSummaryPath,
            implementationStatus: "missing",
            artifactStatus: "missing",
            summaryText: null,
            acceptanceCriteriaText: null,
            risksAndFollowUpsText: null,
            validationText: null
        };
    }
    const document = parseMarkdownDocument(implementationSummaryPath, node_fs_1.default.readFileSync(summaryAbsolute, "utf8"));
    assertArtifactType(document.frontMatterLines, implementationSummaryPath, "implementation_summary");
    return {
        relativePath: implementationSummaryPath,
        implementationStatus: readTopLevelField(document.frontMatterLines, "implementation_status")?.trim() || "",
        artifactStatus: readTopLevelField(document.frontMatterLines, "status")?.trim() || "",
        executionMode: readTopLevelField(document.frontMatterLines, "execution_mode")?.trim() ?? null,
        summaryText: document.sections.get("Summary") ?? null,
        changedPathsText: document.sections.get("Changed Paths") ?? null,
        acceptanceCriteriaText: document.sections.get("Acceptance Criteria Results") ?? null,
        risksAndFollowUpsText: document.sections.get("Risks and Follow-Ups") ?? null,
        validationText: document.sections.get("Validation Performed") ?? null
    };
}
function loadTaskDefinitionContext(repositoryRoot, taskDefinitionPath) {
    if (!node_fs_1.default.existsSync(taskDefinitionPath.absolute)) {
        throw (0, errors_1.createUsageError)(`Task definition not found at '${taskDefinitionPath.relative}'.`, ["Pass an existing repository-relative --task-definition path for the explicit task-level reconciliation exception."]);
    }
    if (node_path_1.default.basename(taskDefinitionPath.relative) !== "task-definition.md") {
        throw (0, errors_1.createUsageError)(`Task-level reconciliation requires a task-definition.md selector, received '${taskDefinitionPath.relative}'.`, ["Do not infer task-level reconciliation from a task directory, implementation-summary.md, or reconciliation.md path."]);
    }
    const taskDocument = parseMarkdownDocument(taskDefinitionPath.relative, node_fs_1.default.readFileSync(taskDefinitionPath.absolute, "utf8"));
    assertArtifactType(taskDocument.frontMatterLines, taskDefinitionPath.relative, "task_definition");
    const context = parseTaskDefinitionContext(taskDefinitionPath.relative, taskDocument);
    if (context.planningDepth !== "standard" || context.phase === null || context.milestone === null || context.phaseOverviewPath === null || context.milestoneOverviewPath === null) {
        throw (0, errors_1.createUsageError)(`Task-level reconciliation requires a standard task with complete phase and milestone parent links at '${taskDefinitionPath.relative}'.`, ["Lightweight tasks do not have milestone-level reconciliation rollup context."]);
    }
    return context;
}
function resolveTaskReconciliationPath(taskDefinitionPath) {
    return (0, front_matter_utils_1.toRepositoryLikePath)(node_path_1.default.join(node_path_1.default.dirname(taskDefinitionPath), "reconciliation.md"));
}
function resolveTaskImplementationSummaryPath(taskDefinitionPath) {
    return (0, front_matter_utils_1.toRepositoryLikePath)(node_path_1.default.join(node_path_1.default.dirname(taskDefinitionPath), "implementation-summary.md"));
}
function resolveReconciliationSelector(options) {
    const hasMilestoneOverview = typeof options.milestoneOverviewPath === "string" && options.milestoneOverviewPath.trim() !== "";
    const hasTaskDefinition = typeof options.taskDefinitionPath === "string" && options.taskDefinitionPath.trim() !== "";
    const rationale = typeof options.taskReconciliationRationale === "string"
        ? options.taskReconciliationRationale.trim()
        : "";
    if (hasMilestoneOverview && hasTaskDefinition) {
        throw (0, errors_1.createUsageError)("Choose exactly one reconciliation source selector.", [
            "Use --milestone-overview for the default milestone reconciliation rollup.",
            "Use --task-definition only for an explicit task-level reconciliation exception."
        ]);
    }
    if (hasTaskDefinition) {
        if (rationale === "") {
            throw (0, errors_1.createUsageError)("Task-level reconciliation requires an explicit exception rationale.", [
                "Pass --rationale <text> with --task-definition to record why milestone-level reconciliation is not the selected rollup path.",
                "Use --milestone-overview for the default milestone reconciliation rollup."
            ]);
        }
        return { kind: "task", taskDefinitionPath: options.taskDefinitionPath, rationale };
    }
    if (hasMilestoneOverview) {
        return { kind: "milestone", milestoneOverviewPath: options.milestoneOverviewPath };
    }
    throw (0, errors_1.createUsageError)("Missing reconciliation source selector.", [
        "Use --milestone-overview for the default milestone reconciliation rollup.",
        "Use --task-definition only for an explicit task-level reconciliation exception."
    ]);
}
function collectImplementationSummaryEvidenceIssues(document) {
    const issues = [];
    for (const sectionName of IMPLEMENTATION_SUMMARY_SECTIONS) {
        const sectionText = document.sections.get(sectionName);
        if (sectionText === undefined) {
            issues.push(`Missing required section '${sectionName}'.`);
            continue;
        }
        if (isPlaceholderContent(sectionText)) {
            issues.push(`Section '${sectionName}' still contains placeholder content.`);
        }
    }
    const changedPathsText = document.sections.get("Changed Paths");
    if (changedPathsText !== undefined && !isPlaceholderContent(changedPathsText)) {
        const changedPathEvidence = extractSummaryChangedPathEvidence(changedPathsText);
        const concreteChangedPaths = changedPathEvidence.filter((entry) => entry.state === "path");
        if (concreteChangedPaths.length === 0) {
            issues.push("Changed Paths does not list concrete repository-relative changed paths.");
        }
        for (const entry of changedPathEvidence) {
            if (entry.state !== "path") {
                issues.push(entry.message);
            }
        }
    }
    const acceptanceCriteriaText = document.sections.get("Acceptance Criteria Results");
    if (acceptanceCriteriaText !== undefined
        && !isPlaceholderContent(acceptanceCriteriaText)
        && !hasConcreteAcceptanceEvidence(acceptanceCriteriaText)) {
        issues.push("Acceptance Criteria Results lacks concrete evidence tied to implementation or validation.");
    }
    const validationText = document.sections.get("Validation Performed");
    if (validationText !== undefined
        && !isPlaceholderContent(validationText)
        && !hasConcreteValidationEvidence(validationText)) {
        issues.push("Validation Performed lacks concrete command, inspection, or explicit validation-exception evidence.");
    }
    const deviationsText = document.sections.get("Deviations");
    if (deviationsText === undefined || isPlaceholderContent(deviationsText)) {
        issues.push("Deviations does not record either concrete deviations or an explicit none-state.");
    }
    const risksAndFollowUpsText = document.sections.get("Risks and Follow-Ups");
    if (risksAndFollowUpsText === undefined || isPlaceholderContent(risksAndFollowUpsText)) {
        issues.push("Risks and Follow-Ups does not record either concrete follow-up evidence or an explicit none-state.");
    }
    return [...new Set(issues)];
}
function collectReconciliationRuntimeEvidenceIssues(summary) {
    const executionMode = summary.executionMode?.trim() ?? "";
    if (executionMode !== "runtime" && executionMode !== "hybrid") {
        return [];
    }
    const issues = [];
    const changedPathsText = summary.changedPathsText;
    if (changedPathsText === undefined || changedPathsText === null || isPlaceholderContent(changedPathsText)) {
        issues.push(`Runtime or hybrid task summary '${summary.relativePath}' does not provide Changed Paths evidence for reconciliation runtime review.`);
        return issues;
    }
    const changedPathEvidence = extractSummaryChangedPathEvidence(changedPathsText);
    const concreteChangedPaths = changedPathEvidence
        .filter((entry) => entry.state === "path" && entry.path !== undefined)
        .map((entry) => entry.path);
    const runtimeEligibleChangedPaths = concreteChangedPaths.filter((changedPath) => (0, documentation_path_classifier_1.classifyDocumentationPath)(changedPath).runtimeEligible);
    if (concreteChangedPaths.length === 0) {
        issues.push(`Runtime or hybrid task summary '${summary.relativePath}' does not list concrete repository-relative Changed Paths evidence for reconciliation runtime review.`);
    }
    else if (runtimeEligibleChangedPaths.length === 0) {
        issues.push(`Runtime or hybrid task summary '${summary.relativePath}' only lists documentation-only Changed Paths evidence; reconciliation requires runtime-eligible changed-path evidence.`);
    }
    if (summary.validationText === null || isPlaceholderContent(summary.validationText) || !hasConcreteValidationEvidence(summary.validationText)) {
        issues.push(`Runtime or hybrid task summary '${summary.relativePath}' does not provide concrete executable validation evidence for reconciliation runtime review.`);
    }
    return issues;
}
function formatSummaryEvidenceIssueSuffix(entry) {
    if (entry.evidenceIssues === undefined || entry.evidenceIssues.length === 0) {
        return "";
    }
    return `; evidence gaps: ${entry.evidenceIssues.join(" ")}`;
}
function assertMatchingPlanningIdentity(context, frontMatterLines, artifactPath, issues, keys) {
    for (const key of keys) {
        const expectedValue = resolveExpectedPlanningValue(context, key);
        const actualValue = readTopLevelField(frontMatterLines, key)?.trim() ?? null;
        if (actualValue !== expectedValue) {
            issues.push(`Metadata field '${key}' on '${artifactPath}' should be '${expectedValue}', found '${actualValue ?? "(missing)"}'.`);
        }
    }
}
function resolveExpectedPlanningValue(context, key) {
    switch (key) {
        case "slice":
            return context.slice;
        case "phase":
            return context.phase ?? "";
        case "milestone":
            return context.milestone ?? "";
        case "task":
            return "task" in context ? context.task : "";
        case "planning_depth":
            return context.planningDepth;
        default:
            return "";
    }
}
function readRequiredTopLevelField(lines, filePath, key) {
    const value = readTopLevelField(lines, key)?.trim();
    if (!value) {
        throw (0, errors_1.createUsageError)(`Artifact '${filePath}' is missing required top-level field '${key}'.`);
    }
    return value;
}
function isAllowedExecutionMode(value) {
    return value === "runtime" || value === "contract" || value === "hybrid";
}
function hasRuntimeImplementationClaim(sections) {
    const claimText = [
        sections.get("Summary") ?? "",
        sections.get("Acceptance Criteria Results") ?? "",
        sections.get("Scope Classification") ?? ""
    ].join("\n");
    return /\b(?:implemented runtime|runtime implementation (?:landed|completed|done|shipped)|runtime behavior (?:changed|implemented|shipped)|changed runtime behavior|wired runtime|shipped runtime)\b/i.test(claimText);
}
function readRequiredUpstreamField(lines, filePath, key) {
    const value = readUpstreamField(lines, key)?.trim();
    if (!value) {
        throw (0, errors_1.createUsageError)(`Artifact '${filePath}' is missing required upstream field '${key}'.`);
    }
    return value;
}
function readTopLevelField(lines, key) {
    for (const line of lines) {
        if (/^\s/.test(line)) {
            continue;
        }
        const match = line.match(/^([A-Za-z0-9_]+):\s*(.*)$/);
        if (match !== null && match[1] === key) {
            return (0, front_matter_utils_1.parseScalar)(match[2]);
        }
    }
    return undefined;
}
function readUpstreamField(lines, key) {
    let inUpstream = false;
    for (const line of lines) {
        if (!inUpstream) {
            if (line.trim() === "upstream:") {
                inUpstream = true;
            }
            continue;
        }
        if (!/^\s/.test(line)) {
            break;
        }
        const match = line.match(/^\s{2}([A-Za-z0-9_]+):\s*(.*)$/);
        if (match !== null && match[1] === key) {
            return (0, front_matter_utils_1.parseScalar)(match[2]);
        }
    }
    return undefined;
}
function parseUpstreamSpecs(lines, filePath) {
    const entries = [];
    for (let index = 0; index < lines.length; index += 1) {
        const idMatch = lines[index].match(/^\s*-\s+id:\s*(.+)$/);
        if (idMatch === null) {
            continue;
        }
        const depthMatch = lines[index + 1]?.match(/^\s+depth:\s*(.+)$/);
        const refMatch = lines[index + 2]?.match(/^\s+ref:\s*(.+)$/);
        const sourceTypeMatch = lines[index + 3]?.match(/^\s+source_type:\s*(.+)$/);
        if (depthMatch === null || refMatch === null || sourceTypeMatch === null) {
            throw (0, errors_1.createUsageError)(`Artifact '${filePath}' has malformed upstream.specs metadata near '${lines[index].trim()}'.`);
        }
        entries.push({
            id: (0, front_matter_utils_1.parseScalar)(idMatch[1]),
            depth: (0, front_matter_utils_1.parseScalar)(depthMatch[1]),
            ref: (0, front_matter_utils_1.parseScalar)(refMatch[1]),
            sourceType: (0, front_matter_utils_1.parseScalar)(sourceTypeMatch[1])
        });
        index += 3;
    }
    return entries;
}
function inferTaskTitleFromPath(filePath) {
    return node_path_1.default.basename(node_path_1.default.dirname(filePath));
}
function isPlaceholderContent(value) {
    const trimmed = value.trim();
    if (trimmed === "") {
        return true;
    }
    if (PLACEHOLDER_PATTERN.test(trimmed)) {
        return true;
    }
    return PLACEHOLDER_EXACT_VALUES.has(trimmed);
}
function removeTemplateScaffoldContent(value) {
    return value
        .split(/\r?\n/)
        .filter((line) => !TEMPLATE_SCAFFOLD_PATTERN.test(line.trim()))
        .join("\n")
        .replace(/\n{3,}/g, "\n\n")
        .trim();
}
function firstContentLine(value) {
    for (const line of value.split(/\r?\n/)) {
        const trimmed = line.trim();
        if (trimmed !== "") {
            return trimmed;
        }
    }
    return "(empty)";
}
function normalizeReviewLines(value) {
    const lines = value
        .split(/\r?\n/)
        .map((line) => line.trim())
        .filter((line) => line !== "");
    if (lines.length === 0) {
        return ["- (none)"];
    }
    return lines.map((line) => line.startsWith("- ") ? line : `- ${line}`);
}
function sectionContradictsTaskEvidence(sectionName, value, taskEvidence) {
    if (sectionName !== "Final Notes") {
        return false;
    }
    const normalized = value.toLowerCase();
    const claimsClosure = /\b(complete|completed|closed|accepted|sufficient|no blocking|ready for downstream)\b/.test(normalized);
    return claimsClosure && (taskEvidence.completed.length === 0 || taskEvidence.incomplete.length > 0);
}
function appendIssueLines(lines, issues) {
    if (issues.length === 0) {
        lines.push("- (none)");
        return;
    }
    for (const issue of issues) {
        lines.push(`- ${issue}`);
    }
}
