"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.syncTaskDefinitionStatusFromReview = syncTaskDefinitionStatusFromReview;
exports.syncMilestoneOverviewStatusFromReview = syncMilestoneOverviewStatusFromReview;
exports.syncPhaseOverviewStatusFromReview = syncPhaseOverviewStatusFromReview;
exports.inventoryMetadataState = inventoryMetadataState;
exports.renderMetadataSyncResult = renderMetadataSyncResult;
exports.renderMetadataInventoryResult = renderMetadataInventoryResult;
const node_fs_1 = __importDefault(require("node:fs"));
const node_path_1 = __importDefault(require("node:path"));
const errors_1 = require("../errors");
const paths_1 = require("../paths");
const front_matter_utils_1 = require("./front-matter-utils");
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 PLACEHOLDER_PATTERNS = [
    /\{\{\s*[A-Za-z0-9_.-]+\s*\}\}/,
    /\bTBD\b/i,
    /\bTODO\b/i,
    /^PLACEHOLDER$/i,
    /^pending$/i,
    /^pending\./i
];
const INSTRUCTION_PHRASES = [
    "Template notes:",
    "This implementation summary is initialized as the stable execution artifact for the task.",
    "This reconciliation artifact is initialized as a milestone-generation placeholder",
    "Reference the completed task summaries that make up the milestone evidence.",
    "State whether the milestone is reviewed, pending, partial, or blocked.",
    "Restate the milestone goal in review terms, not implementation steps.",
    "Review each milestone criterion against the task summaries.",
    "Note any planned work that remains after the task summaries are reviewed.",
    "Record newly discovered work that emerged during implementation or review.",
    "Move out-of-scope but relevant follow-up into backlog work here.",
    "Summarize the validation evidence and whether it is sufficient.",
    "List any concrete next tasks that remain after reconciliation.",
    "Call out any remaining ambiguity, drift, or review risk.",
    "Close with the overall milestone verdict and any handoff notes."
];
const HELPER_COVERAGE = [
    { surface: "metadata update", status: "helper-backed write" },
    { surface: "metadata validate-update", status: "helper-backed read-only validation" },
    { surface: "metadata sync-status-from-review", status: "deterministic review-driven write" },
    { surface: "metadata inventory", status: "read-only inspection" },
    { surface: "task promote", status: "helper-backed planning mutation" },
    { surface: "task update", status: "helper-backed planning mutation" },
    { surface: "implementation-summary update", status: "helper-backed planning mutation" },
    { surface: "reconciliation update", status: "helper-backed planning mutation" },
    { surface: "prompt update", status: "helper-backed non-artifact mutation" },
    { surface: "template update", status: "helper-backed non-artifact mutation" },
    { surface: "manifest update", status: "helper-backed manifest mutation" },
    { surface: "spec update", status: "helper-backed spec-registry mutation" }
];
function syncTaskDefinitionStatusFromReview(options) {
    const taskDefinitionPath = resolveTaskDefinitionInput(options.rootPath);
    assertActiveArtifactMatch(taskDefinitionPath, options.activeArtifactPath);
    const taskAbsolutePath = (0, paths_1.resolveRepositoryRelativePath)(options.repositoryRoot, (0, paths_1.parseRepositoryRelativePath)(taskDefinitionPath));
    if (!node_fs_1.default.existsSync(taskAbsolutePath)) {
        throw (0, errors_1.createUsageError)(`Task definition path '${taskDefinitionPath}' does not exist.`, ["Pass an existing repository-relative --task-definition path."]);
    }
    const taskContent = node_fs_1.default.readFileSync(taskAbsolutePath, "utf8");
    const taskDocument = parseMarkdownDocument(taskDefinitionPath, taskContent);
    assertArtifactType(taskDocument.frontMatterLines, taskDefinitionPath, "task_definition");
    const taskDirectoryPath = node_path_1.default.dirname(taskDefinitionPath);
    const pairedImplementationSummaryPath = (0, front_matter_utils_1.toRepositoryLikePath)(node_path_1.default.join(taskDirectoryPath, "implementation-summary.md"));
    const milestoneReconciliationPath = resolveMilestoneReconciliationPath(taskDefinitionPath);
    const implementationSummaryAssessment = assessImplementationSummary(options.repositoryRoot, pairedImplementationSummaryPath, taskDefinitionPath);
    const reconciliationAssessment = assessMilestoneReconciliation(options.repositoryRoot, milestoneReconciliationPath, taskDefinitionPath);
    const milestoneSummaryAssessment = assessMilestoneTaskSummaries(options.repositoryRoot, taskDefinitionPath);
    if (implementationSummaryAssessment.eligible) {
        const nextContent = (0, front_matter_utils_1.applyStatusAndPlanningFieldTransition)(taskContent, {
            readiness: "completed",
            status: "completed"
        });
        const changed = nextContent !== taskContent;
        if (changed) {
            node_fs_1.default.writeFileSync(taskAbsolutePath, nextContent, "utf8");
        }
        return {
            artifactPath: taskDefinitionPath,
            artifactType: "task_definition",
            taskDefinitionPath,
            pairedImplementationSummaryPath,
            milestoneReconciliationPath,
            source: "implementation-summary",
            changed,
            writeApplied: changed
        };
    }
    if (reconciliationAssessment.eligible && milestoneSummaryAssessment.eligible) {
        const nextContent = (0, front_matter_utils_1.applyStatusAndPlanningFieldTransition)(taskContent, {
            status: "completed"
        });
        const changed = nextContent !== taskContent;
        if (changed) {
            node_fs_1.default.writeFileSync(taskAbsolutePath, nextContent, "utf8");
        }
        return {
            artifactPath: taskDefinitionPath,
            artifactType: "task_definition",
            taskDefinitionPath,
            pairedImplementationSummaryPath,
            milestoneReconciliationPath,
            source: "reconciliation",
            changed,
            writeApplied: changed
        };
    }
    const findings = [];
    const details = [
        `Task definition: ${taskDefinitionPath}`,
        ...implementationSummaryAssessment.reasons.map((reason) => `Implementation summary: ${reason}`),
        ...reconciliationAssessment.reasons.map((reason) => `Milestone reconciliation: ${reason}`),
        ...milestoneSummaryAssessment.reasons.map((reason) => `Milestone task summaries: ${reason}`)
    ];
    for (const reason of implementationSummaryAssessment.reasons) {
        findings.push({
            code: "METADATA_SYNC_BLOCKED",
            message: reason,
            severity: "error",
            path: pairedImplementationSummaryPath
        });
    }
    for (const reason of reconciliationAssessment.reasons) {
        findings.push({
            code: "METADATA_SYNC_BLOCKED",
            message: reason,
            severity: "error",
            path: milestoneReconciliationPath
        });
    }
    for (const reason of milestoneSummaryAssessment.reasons) {
        findings.push({
            code: "METADATA_SYNC_BLOCKED",
            message: reason,
            severity: "error",
            path: milestoneReconciliationPath
        });
    }
    throw (0, errors_1.createInvalidConfigError)("Metadata sync from review was rejected.", details, findings);
}
function syncMilestoneOverviewStatusFromReview(options) {
    const milestoneOverviewPath = resolveArtifactInput(options.rootPath, "milestone-overview", "milestone-overview.md");
    assertActiveArtifactMatch(milestoneOverviewPath, options.activeArtifactPath);
    const milestoneOverviewAbsolutePath = (0, paths_1.resolveRepositoryRelativePath)(options.repositoryRoot, (0, paths_1.parseRepositoryRelativePath)(milestoneOverviewPath));
    if (!node_fs_1.default.existsSync(milestoneOverviewAbsolutePath)) {
        throw (0, errors_1.createUsageError)(`Milestone overview path '${milestoneOverviewPath}' does not exist.`, ["Pass an existing repository-relative --milestone-overview path."]);
    }
    const milestoneOverviewContent = node_fs_1.default.readFileSync(milestoneOverviewAbsolutePath, "utf8");
    const milestoneOverviewDocument = parseMarkdownDocument(milestoneOverviewPath, milestoneOverviewContent);
    assertArtifactType(milestoneOverviewDocument.frontMatterLines, milestoneOverviewPath, "milestone_overview");
    const reconciliationPath = (0, front_matter_utils_1.toRepositoryLikePath)(node_path_1.default.join(node_path_1.default.dirname(milestoneOverviewPath), "reconciliation.md"));
    const reconciliationAssessment = assessMilestoneOverviewReconciliation(options.repositoryRoot, reconciliationPath);
    if (!reconciliationAssessment.eligible) {
        throwMetadataSyncRejected(milestoneOverviewPath, reconciliationPath, reconciliationAssessment.reasons);
    }
    const nextContent = (0, front_matter_utils_1.applyStatusAndPlanningFieldTransition)(milestoneOverviewContent, { status: "completed" });
    const changed = nextContent !== milestoneOverviewContent;
    if (changed) {
        node_fs_1.default.writeFileSync(milestoneOverviewAbsolutePath, nextContent, "utf8");
    }
    return {
        artifactPath: milestoneOverviewPath,
        artifactType: "milestone_overview",
        taskDefinitionPath: null,
        pairedImplementationSummaryPath: null,
        milestoneReconciliationPath: reconciliationPath,
        source: "reconciliation",
        changed,
        writeApplied: changed
    };
}
function syncPhaseOverviewStatusFromReview(options) {
    const phaseOverviewPath = resolveArtifactInput(options.rootPath, "phase-overview", "phase-overview.md");
    assertActiveArtifactMatch(phaseOverviewPath, options.activeArtifactPath);
    const phaseOverviewAbsolutePath = (0, paths_1.resolveRepositoryRelativePath)(options.repositoryRoot, (0, paths_1.parseRepositoryRelativePath)(phaseOverviewPath));
    if (!node_fs_1.default.existsSync(phaseOverviewAbsolutePath)) {
        throw (0, errors_1.createUsageError)(`Phase overview path '${phaseOverviewPath}' does not exist.`, ["Pass an existing repository-relative --phase-overview path."]);
    }
    const phaseOverviewContent = node_fs_1.default.readFileSync(phaseOverviewAbsolutePath, "utf8");
    const phaseOverviewDocument = parseMarkdownDocument(phaseOverviewPath, phaseOverviewContent);
    assertArtifactType(phaseOverviewDocument.frontMatterLines, phaseOverviewPath, "phase_overview");
    const reasons = [];
    for (const milestoneSlug of parseDeclaredSlugBullets(phaseOverviewDocument.sections.get("Milestones"))) {
        const reconciliationPath = (0, front_matter_utils_1.toRepositoryLikePath)(node_path_1.default.join(node_path_1.default.dirname(phaseOverviewPath), "milestones", milestoneSlug, "reconciliation.md"));
        const assessment = assessMilestoneOverviewReconciliation(options.repositoryRoot, reconciliationPath);
        reasons.push(...assessment.reasons);
    }
    if (reasons.length > 0) {
        throwMetadataSyncRejected(phaseOverviewPath, phaseOverviewPath, reasons);
    }
    const nextContent = (0, front_matter_utils_1.applyStatusAndPlanningFieldTransition)(phaseOverviewContent, { status: "completed" });
    const changed = nextContent !== phaseOverviewContent;
    if (changed) {
        node_fs_1.default.writeFileSync(phaseOverviewAbsolutePath, nextContent, "utf8");
    }
    return {
        artifactPath: phaseOverviewPath,
        artifactType: "phase_overview",
        taskDefinitionPath: null,
        pairedImplementationSummaryPath: null,
        milestoneReconciliationPath: null,
        source: "phase-reconciliation",
        changed,
        writeApplied: changed
    };
}
function inventoryMetadataState(options) {
    const inventoryRootInput = options.rootPath ?? ".day-shift/planning";
    const inventoryRootPath = (0, paths_1.resolveRepositoryRelativePath)(options.repositoryRoot, (0, paths_1.parseRepositoryRelativePath)(inventoryRootInput));
    if (!node_fs_1.default.existsSync(inventoryRootPath)) {
        throw (0, errors_1.createUsageError)(`Inventory root path '${inventoryRootInput}' does not exist.`, ["Pass an existing repository-relative --root path."]);
    }
    const taskDefinitionPaths = collectFilesWithName(inventoryRootPath, "task-definition.md");
    const opportunities = [];
    let implementationSummariesCompleted = 0;
    let reconciliationsCompleted = 0;
    for (const absoluteTaskDefinitionPath of taskDefinitionPaths) {
        const taskDefinitionPath = (0, front_matter_utils_1.toRepositoryLikePath)(node_path_1.default.relative(options.repositoryRoot, absoluteTaskDefinitionPath));
        const taskDirectoryPath = node_path_1.default.dirname(taskDefinitionPath);
        const implementationSummaryPath = (0, front_matter_utils_1.toRepositoryLikePath)(node_path_1.default.join(taskDirectoryPath, "implementation-summary.md"));
        const milestoneReconciliationPath = resolveMilestoneReconciliationPath(taskDefinitionPath);
        const taskContent = node_fs_1.default.readFileSync(absoluteTaskDefinitionPath, "utf8");
        const taskDocument = parseMarkdownDocument(taskDefinitionPath, taskContent);
        const taskStatus = readTopLevelField(taskDocument.frontMatterLines, "status")?.trim() ?? null;
        const taskReadiness = readTopLevelField(taskDocument.frontMatterLines, "readiness")?.trim() ?? null;
        const summaryAssessment = assessImplementationSummary(options.repositoryRoot, implementationSummaryPath, taskDefinitionPath);
        if (summaryAssessment.eligible) {
            implementationSummariesCompleted += 1;
        }
        const reconciliationAssessment = assessMilestoneReconciliation(options.repositoryRoot, milestoneReconciliationPath, taskDefinitionPath);
        const milestoneSummaryAssessment = assessMilestoneTaskSummaries(options.repositoryRoot, taskDefinitionPath);
        if (reconciliationAssessment.eligible) {
            reconciliationsCompleted += 1;
        }
        if (summaryAssessment.eligible && (taskStatus !== "completed" || taskReadiness !== "completed")) {
            opportunities.push({
                taskDefinitionPath,
                implementationSummaryPath,
                milestoneReconciliationPath,
                source: "implementation-summary",
                reason: "Completed implementation summary evidence is present, but the task definition lifecycle fields are still stale."
            });
        }
        if (reconciliationAssessment.eligible
            && milestoneSummaryAssessment.eligible
            && taskStatus !== "completed") {
            opportunities.push({
                taskDefinitionPath,
                implementationSummaryPath,
                milestoneReconciliationPath,
                source: "reconciliation",
                reason: "Completed milestone reconciliation evidence is present, but the task definition status is still stale."
            });
        }
    }
    return {
        repositoryRoot: options.repositoryRoot,
        inventoryRoot: (0, front_matter_utils_1.toRepositoryLikePath)(node_path_1.default.relative(options.repositoryRoot, inventoryRootPath) || "."),
        taskDefinitionsScanned: taskDefinitionPaths.length,
        implementationSummariesCompleted,
        reconciliationsCompleted,
        helperCoverage: HELPER_COVERAGE,
        updateOpportunities: opportunities
    };
}
function renderMetadataSyncResult(result) {
    return [
        "Metadata sync from review applied.",
        `Artifact: ${result.artifactPath}`,
        `Artifact type: ${result.artifactType}`,
        `Task definition: ${result.taskDefinitionPath ?? "(not selected)"}`,
        `Paired implementation summary: ${result.pairedImplementationSummaryPath ?? "(not selected)"}`,
        `Milestone reconciliation: ${result.milestoneReconciliationPath ?? "(not selected)"}`,
        `Source: ${result.source}`,
        `Changed: ${result.changed ? "yes" : "no"}`,
        `Write applied: ${result.writeApplied ? "yes" : "no"}`
    ].join("\n");
}
function renderMetadataInventoryResult(result) {
    const lines = [
        "Metadata inventory",
        `Inventory root: ${result.inventoryRoot}`,
        `Task definitions scanned: ${result.taskDefinitionsScanned}`,
        `Completed implementation summaries: ${result.implementationSummariesCompleted}`,
        `Completed reconciliations: ${result.reconciliationsCompleted}`,
        "",
        "Helper coverage:"
    ];
    for (const entry of result.helperCoverage) {
        lines.push(`- ${entry.surface}: ${entry.status}`);
    }
    lines.push("", "Update opportunities:");
    if (result.updateOpportunities.length === 0) {
        lines.push("- No actionable metadata state detected.");
    }
    else {
        for (const opportunity of result.updateOpportunities) {
            lines.push(`- ${opportunity.taskDefinitionPath}`);
            lines.push(`  source: ${opportunity.source}`);
            lines.push(`  implementation summary: ${opportunity.implementationSummaryPath}`);
            lines.push(`  milestone reconciliation: ${opportunity.milestoneReconciliationPath}`);
            lines.push(`  reason: ${opportunity.reason}`);
        }
    }
    return lines.join("\n");
}
function resolveTaskDefinitionInput(rootPath) {
    const inputPath = rootPath ?? ".day-shift/planning";
    const parsed = (0, paths_1.parseRepositoryRelativePath)(inputPath);
    if (parsed.segments[parsed.segments.length - 1] !== "task-definition.md") {
        throw (0, errors_1.createUsageError)(`Invalid task definition path '${inputPath}'.`, ["Expected a repository-relative path ending in task-definition.md."]);
    }
    return parsed.normalizedPath;
}
function resolveArtifactInput(rootPath, label, fileName) {
    const inputPath = rootPath ?? ".day-shift/planning";
    const parsed = (0, paths_1.parseRepositoryRelativePath)(inputPath);
    if (parsed.segments[parsed.segments.length - 1] !== fileName) {
        throw (0, errors_1.createUsageError)(`Invalid ${label} path '${inputPath}'.`, [`Expected a repository-relative path ending in ${fileName}.`]);
    }
    return parsed.normalizedPath;
}
function assertActiveArtifactMatch(artifactPath, activeArtifactPath) {
    if (activeArtifactPath === undefined || activeArtifactPath.trim() === "") {
        return;
    }
    const activeArtifact = (0, paths_1.parseRepositoryRelativePath)(activeArtifactPath).normalizedPath;
    if (activeArtifact === artifactPath) {
        return;
    }
    throw (0, errors_1.createInvalidConfigError)("Metadata sync from review was rejected.", [
        "Active artifact conflict.",
        `Field '--active-artifact' is '${activeArtifact}'; expected '${artifactPath}'.`,
        "No partial write was applied."
    ], [{
            code: "METADATA_SYNC_BLOCKED",
            message: "Active artifact mismatch for metadata sync-status-from-review.",
            severity: "error",
            path: artifactPath
        }]);
}
function parseMarkdownDocument(filePath, fileText) {
    const lines = fileText.split(/\r?\n/);
    if (lines[0] !== "---") {
        throw (0, errors_1.createUsageError)(`Artifact '${(0, front_matter_utils_1.toRepositoryLikePath)(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 '${(0, front_matter_utils_1.toRepositoryLikePath)(filePath)}' has malformed YAML front matter.`);
    }
    const contentLines = lines.slice(closingIndex + 1);
    return {
        frontMatterLines: lines.slice(1, closingIndex),
        contentLines,
        sections: parseSections(contentLines)
    };
}
function parseSections(contentLines) {
    const sections = new Map();
    let currentHeading = null;
    let sectionBuffer = [];
    for (const line of contentLines) {
        const headingMatch = line.match(/^##\s+(.+)$/);
        if (headingMatch !== null) {
            if (currentHeading !== null) {
                sections.set(currentHeading, sectionBuffer.join("\n").trim());
            }
            currentHeading = headingMatch[1].trim();
            sectionBuffer = [];
            continue;
        }
        if (currentHeading !== null) {
            sectionBuffer.push(line);
        }
    }
    if (currentHeading !== null) {
        sections.set(currentHeading, sectionBuffer.join("\n").trim());
    }
    return sections;
}
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) {
            continue;
        }
        if (match[1] === key) {
            return (0, front_matter_utils_1.parseScalar)(match[2]);
        }
    }
    return undefined;
}
function assertArtifactType(frontMatterLines, filePath, expectedArtifactType) {
    const artifactType = readTopLevelField(frontMatterLines, "artifact_type")?.trim();
    if (artifactType !== expectedArtifactType) {
        throw (0, errors_1.createUsageError)(`Artifact '${filePath}' is not a ${expectedArtifactType} artifact.`, [`Expected artifact_type '${expectedArtifactType}', found '${artifactType ?? "(missing)"}'.`]);
    }
}
function assessImplementationSummary(repositoryRoot, summaryPath, taskDefinitionPath) {
    const absolutePath = node_path_1.default.join(repositoryRoot, summaryPath);
    if (!node_fs_1.default.existsSync(absolutePath)) {
        return {
            eligible: false,
            reasons: [`Paired implementation summary '${summaryPath}' is missing.`]
        };
    }
    const document = parseMarkdownDocument(summaryPath, node_fs_1.default.readFileSync(absolutePath, "utf8"));
    const reasons = [];
    assertArtifactType(document.frontMatterLines, summaryPath, "implementation_summary");
    const implementationStatus = readTopLevelField(document.frontMatterLines, "implementation_status")?.trim();
    if (implementationStatus !== "completed") {
        reasons.push(`Paired implementation summary '${summaryPath}' does not carry implementation_status: completed.`);
    }
    const status = readTopLevelField(document.frontMatterLines, "status")?.trim();
    if (status !== "completed") {
        reasons.push(`Paired implementation summary '${summaryPath}' does not carry status: completed.`);
    }
    for (const sectionName of IMPLEMENTATION_SUMMARY_SECTIONS) {
        const sectionText = document.sections.get(sectionName);
        if (sectionText === undefined) {
            reasons.push(`Paired implementation summary '${summaryPath}' is missing section '${sectionName}'.`);
            continue;
        }
        if (isPlaceholderContent(sectionText)) {
            reasons.push(`Section '${sectionName}' in '${summaryPath}' still contains placeholder content.`);
        }
    }
    if (reasons.length === 0) {
        return {
            eligible: true,
            reasons: []
        };
    }
    return {
        eligible: false,
        reasons
    };
}
function assessMilestoneReconciliation(repositoryRoot, reconciliationPath, taskDefinitionPath) {
    const absolutePath = node_path_1.default.join(repositoryRoot, reconciliationPath);
    if (!node_fs_1.default.existsSync(absolutePath)) {
        return {
            eligible: false,
            reasons: [`Milestone reconciliation '${reconciliationPath}' is missing.`]
        };
    }
    const document = parseMarkdownDocument(reconciliationPath, node_fs_1.default.readFileSync(absolutePath, "utf8"));
    const reasons = [];
    const fileText = [
        ...document.frontMatterLines,
        ...document.contentLines
    ].join("\n");
    assertArtifactType(document.frontMatterLines, reconciliationPath, "reconciliation");
    const reconciliationStatus = readTopLevelField(document.frontMatterLines, "reconciliation_status")?.trim();
    if (reconciliationStatus !== "completed") {
        reasons.push(`Milestone reconciliation '${reconciliationPath}' does not carry reconciliation_status: completed.`);
    }
    const status = readTopLevelField(document.frontMatterLines, "status")?.trim();
    if (status !== "completed") {
        reasons.push(`Milestone reconciliation '${reconciliationPath}' does not carry status: completed.`);
    }
    for (const sectionName of RECONCILIATION_SECTIONS) {
        const sectionText = document.sections.get(sectionName);
        if (sectionText === undefined) {
            reasons.push(`Milestone reconciliation '${reconciliationPath}' is missing section '${sectionName}'.`);
            continue;
        }
        if (isPlaceholderContent(sectionText)) {
            reasons.push(`Section '${sectionName}' in '${reconciliationPath}' still contains placeholder content.`);
        }
    }
    const taskToken = escapeRegExp(taskDefinitionPath);
    const taskSlug = taskDefinitionPath.split("/").slice(-2, -1)[0] ?? "";
    const acceptedPattern = /\baccepted\b/i;
    const taskReferencePattern = new RegExp(`${taskToken}|\\b${escapeRegExp(taskSlug)}\\b`, "i");
    if (!acceptedPattern.test(fileText) || !taskReferencePattern.test(fileText)) {
        reasons.push(`Milestone reconciliation '${reconciliationPath}' does not explicitly name task '${taskDefinitionPath}' as accepted.`);
    }
    if (reasons.length === 0) {
        return {
            eligible: true,
            reasons: []
        };
    }
    return {
        eligible: false,
        reasons
    };
}
function assessMilestoneOverviewReconciliation(repositoryRoot, reconciliationPath) {
    const absolutePath = node_path_1.default.join(repositoryRoot, reconciliationPath);
    if (!node_fs_1.default.existsSync(absolutePath)) {
        return {
            eligible: false,
            reasons: [`Milestone reconciliation '${reconciliationPath}' is missing.`]
        };
    }
    const document = parseMarkdownDocument(reconciliationPath, node_fs_1.default.readFileSync(absolutePath, "utf8"));
    const reasons = [];
    assertArtifactType(document.frontMatterLines, reconciliationPath, "reconciliation");
    if (readTopLevelField(document.frontMatterLines, "reconciliation_status")?.trim() !== "completed") {
        reasons.push(`Milestone reconciliation '${reconciliationPath}' does not carry reconciliation_status: completed.`);
    }
    if (readTopLevelField(document.frontMatterLines, "status")?.trim() !== "completed") {
        reasons.push(`Milestone reconciliation '${reconciliationPath}' does not carry status: completed.`);
    }
    for (const sectionName of RECONCILIATION_SECTIONS) {
        const sectionText = document.sections.get(sectionName);
        if (sectionText === undefined) {
            reasons.push(`Milestone reconciliation '${reconciliationPath}' is missing section '${sectionName}'.`);
            continue;
        }
        if (isPlaceholderContent(sectionText)) {
            reasons.push(`Section '${sectionName}' in '${reconciliationPath}' still contains placeholder content.`);
        }
    }
    return reasons.length === 0 ? { eligible: true, reasons: [] } : { eligible: false, reasons };
}
function parseDeclaredSlugBullets(sectionText) {
    return [...(sectionText ?? "").matchAll(/^\s*-\s+`([^`]+)`/gm)].map((match) => match[1].trim());
}
function throwMetadataSyncRejected(artifactPath, evidencePath, reasons) {
    throw (0, errors_1.createInvalidConfigError)("Metadata sync from review was rejected.", [`Artifact: ${artifactPath}`, ...reasons], reasons.map((reason) => ({
        code: "METADATA_SYNC_BLOCKED",
        message: reason,
        severity: "error",
        path: evidencePath
    })));
}
function assessMilestoneTaskSummaries(repositoryRoot, taskDefinitionPath) {
    const milestoneTasksDirectoryPath = resolveMilestoneTasksDirectoryPath(taskDefinitionPath);
    const absoluteTasksDirectory = node_path_1.default.join(repositoryRoot, milestoneTasksDirectoryPath);
    if (!node_fs_1.default.existsSync(absoluteTasksDirectory)) {
        return {
            eligible: false,
            reasons: [`Milestone tasks directory '${milestoneTasksDirectoryPath}' is missing.`]
        };
    }
    const taskDefinitionPaths = collectFilesWithName(absoluteTasksDirectory, "task-definition.md")
        .map((absoluteTaskDefinitionPath) => (0, front_matter_utils_1.toRepositoryLikePath)(node_path_1.default.relative(repositoryRoot, absoluteTaskDefinitionPath)))
        .sort((left, right) => left.localeCompare(right));
    if (taskDefinitionPaths.length === 0) {
        return {
            eligible: false,
            reasons: [`Milestone tasks directory '${milestoneTasksDirectoryPath}' has no task definitions.`]
        };
    }
    const reasons = [];
    for (const currentTaskDefinitionPath of taskDefinitionPaths) {
        const summaryPath = (0, front_matter_utils_1.toRepositoryLikePath)(node_path_1.default.join(node_path_1.default.dirname(currentTaskDefinitionPath), "implementation-summary.md"));
        const summaryAssessment = assessImplementationSummary(repositoryRoot, summaryPath, currentTaskDefinitionPath);
        if (!summaryAssessment.eligible) {
            reasons.push(...summaryAssessment.reasons.map((reason) => `Task '${currentTaskDefinitionPath}' is not complete: ${reason}`));
        }
    }
    if (reasons.length === 0) {
        return {
            eligible: true,
            reasons: []
        };
    }
    return {
        eligible: false,
        reasons
    };
}
function isPlaceholderContent(text) {
    const normalized = text.trim();
    if (normalized.length === 0) {
        return true;
    }
    if (PLACEHOLDER_PATTERNS.some((pattern) => pattern.test(normalized))) {
        return true;
    }
    return INSTRUCTION_PHRASES.some((phrase) => normalized.toLowerCase().includes(phrase.toLowerCase()));
}
function collectFilesWithName(rootPath, fileName) {
    const results = [];
    const entries = node_fs_1.default.readdirSync(rootPath, { withFileTypes: true });
    for (const entry of entries) {
        const absolutePath = node_path_1.default.join(rootPath, entry.name);
        if (entry.isDirectory()) {
            results.push(...collectFilesWithName(absolutePath, fileName));
            continue;
        }
        if (entry.isFile() && entry.name === fileName) {
            results.push(absolutePath);
        }
    }
    return results;
}
function resolveMilestoneReconciliationPath(taskDefinitionPath) {
    const normalizedPath = (0, front_matter_utils_1.toRepositoryLikePath)(taskDefinitionPath);
    const marker = "/tasks/";
    const markerIndex = normalizedPath.lastIndexOf(marker);
    if (markerIndex === -1) {
        return ".day-shift/planning/reconciliation.md";
    }
    return `${normalizedPath.slice(0, markerIndex)}/reconciliation.md`;
}
function resolveMilestoneTasksDirectoryPath(taskDefinitionPath) {
    const normalizedPath = (0, front_matter_utils_1.toRepositoryLikePath)(taskDefinitionPath);
    const marker = "/tasks/";
    const markerIndex = normalizedPath.lastIndexOf(marker);
    if (markerIndex === -1) {
        throw (0, errors_1.createUsageError)(`Task definition '${taskDefinitionPath}' is not under a milestone tasks directory.`, ["Expected a path containing '/tasks/<task-slug>/task-definition.md'."]);
    }
    return `${normalizedPath.slice(0, markerIndex)}/tasks`;
}
function escapeRegExp(value) {
    return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
}
