"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.buildReviewStatusText = buildReviewStatusText;
exports.buildAcceptanceCriteriaReviewText = buildAcceptanceCriteriaReviewText;
exports.buildMilestoneIntentText = buildMilestoneIntentText;
exports.buildCompletedTaskSummariesText = buildCompletedTaskSummariesText;
exports.buildPlannedWorkText = buildPlannedWorkText;
exports.buildValidationReviewText = buildValidationReviewText;
exports.buildReviewConcernsText = buildReviewConcernsText;
exports.collectMilestoneTaskEvidence = collectMilestoneTaskEvidence;
exports.parseDeclaredTaskSlugs = parseDeclaredTaskSlugs;
exports.inspectTaskRuntimeAcceptanceForReconciliation = inspectTaskRuntimeAcceptanceForReconciliation;
exports.collectTaskImplementationSummaryEvidence = collectTaskImplementationSummaryEvidence;
exports.resolveSummaryEvidenceLifecycle = resolveSummaryEvidenceLifecycle;
exports.reviewWaiverApplies = reviewWaiverApplies;
exports.isReconciliationCompletedSummaryEvidence = isReconciliationCompletedSummaryEvidence;
exports.formatCompletionEvidenceLabel = formatCompletionEvidenceLabel;
exports.loadTaskDefinitionContext = loadTaskDefinitionContext;
exports.resolveTaskReconciliationPath = resolveTaskReconciliationPath;
exports.resolveTaskImplementationSummaryPath = resolveTaskImplementationSummaryPath;
// Responsibility-focused implementation extracted from the public compatibility facade.
const node_fs_1 = __importDefault(require("node:fs"));
const node_path_1 = __importDefault(require("node:path"));
const errors_1 = require("../../errors");
const declared_target_paths_1 = require("../../validation/declared-target-paths");
const artifact_policy_projection_1 = require("../artifact-policy-projection");
const front_matter_utils_1 = require("../front-matter-utils");
const context_1 = require("../implementation-summary/context");
const contracts_1 = require("../implementation-summary/contracts");
const document_paths_1 = require("../implementation-summary/document-paths");
const planning_document_utils_1 = require("../planning-document-utils");
const runtime_acceptance_1 = require("../runtime-acceptance");
const semantic_placeholder_1 = require("../semantic-placeholder");
const task_cycle_runtime_attribution_1 = require("../task-cycle-runtime-attribution");
const task_lifecycle_1 = require("../task-lifecycle");
const task_waivers_1 = require("../task-waivers");
const selector_evidence_1 = require("./selector-evidence");
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 contracts_1.MILESTONE_REVIEW_READY_MARKER;
}
function buildAcceptanceCriteriaReviewText(taskEvidence, context) {
    const criteriaLines = context.acceptanceCriteriaText === null || (0, semantic_placeholder_1.hasSemanticPlaceholderContent)(context.acceptanceCriteriaText)
        ? ["- No milestone acceptance criteria were found in the milestone overview."]
        : (0, selector_evidence_1.normalizeReviewLines)(context.acceptanceCriteriaText);
    const evidenceLines = taskEvidence.completed.length === 0
        ? ["- Completed task evidence: none available."]
        : taskEvidence.completed.map((entry) => `- Completed task evidence: ${entry.relativePath}.${formatCompletionEvidenceLabel(entry)}`);
    const pendingLines = taskEvidence.incomplete.length === 0
        ? ["- Pending task evidence: none detected by build refresh."]
        : taskEvidence.incomplete.map((entry) => {
            const suffix = (0, selector_evidence_1.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 && !(0, semantic_placeholder_1.hasSemanticPlaceholderContent)(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" : (0, selector_evidence_1.firstContentLine)(entry.summaryText);
        return `- ${entry.relativePath}: ${summaryExcerpt}${formatCompletionEvidenceLabel(entry)}`;
    })
        .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 = (0, selector_evidence_1.formatSummaryEvidenceIssueSuffix)(entry);
        return `- ${entry.relativePath} remains incomplete (implementation_status: ${entry.implementationStatus || "(missing)"}${suffix}).`;
    })
        .join("\n");
}
function buildValidationReviewText(completedEvidence, context) {
    const focusLines = context.validationFocusText === null || (0, semantic_placeholder_1.hasSemanticPlaceholderContent)(context.validationFocusText)
        ? ["- No milestone validation focus was found in the milestone overview."]
        : (0, selector_evidence_1.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}:`,
                ...(0, selector_evidence_1.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 milestoneDocument = node_fs_1.default.existsSync(milestoneOverviewAbsolute)
        ? (0, document_paths_1.parseMarkdownDocument)(milestoneOverviewPath, node_fs_1.default.readFileSync(milestoneOverviewAbsolute, "utf8"))
        : null;
    const declaredTaskSlugs = milestoneDocument === null ? [] : parseDeclaredTaskSlugs(milestoneDocument);
    const parentRuntimeAcceptance = milestoneDocument === null
        ? null
        : (0, runtime_acceptance_1.inspectRuntimeAcceptance)({
            artifactPath: milestoneOverviewPath,
            artifactKind: "milestone",
            frontMatterLines: milestoneDocument.frontMatterLines,
            markdownText: milestoneDocument.rawText
        }).metadata;
    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 summaryText = node_fs_1.default.readFileSync(summaryAbsolute, "utf8");
        const document = (0, document_paths_1.parseMarkdownDocument)(relativePath, summaryText);
        (0, context_1.assertArtifactType)(document.frontMatterLines, relativePath, "implementation_summary");
        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 taskDefinitionText = node_fs_1.default.existsSync(taskDefinitionAbsolute)
            ? node_fs_1.default.readFileSync(taskDefinitionAbsolute, "utf8")
            : null;
        const runtimeAcceptance = taskDefinitionText === null
            ? { issues: [], legacyCompatibility: false }
            : inspectTaskRuntimeAcceptanceForReconciliation({
                taskDefinitionPath,
                taskDefinitionText,
                taskSlug,
                parent: parentRuntimeAcceptance
            });
        const lifecycle = resolveSummaryEvidenceLifecycle(summaryText, taskDefinitionText !== null && reviewWaiverApplies(relativePath, summaryText, taskDefinitionText));
        const evidence = {
            relativePath,
            implementationStatus: lifecycle.implementationStatus,
            reviewDisposition: lifecycle.reviewDisposition,
            completionEvidenceKind: lifecycle.completionEvidenceKind,
            artifactStatus: lifecycle.completionEvidenceKind === undefined ? "draft" : "completed",
            executionMode: (0, artifact_policy_projection_1.projectArtifactPolicy)(summaryText).evidenceProfile,
            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,
            declaredTargetEvidence: taskDefinitionText === null
                ? []
                : (0, declared_target_paths_1.readTaskDeclaredTargetPathEvidence)(taskDefinitionPath, taskDefinitionText).evidence,
            legacyRuntimeAcceptanceCompatibility: runtimeAcceptance.legacyCompatibility
        };
        const evidenceIssues = [
            ...(0, selector_evidence_1.collectImplementationSummaryEvidenceIssues)(document),
            ...runtimeAcceptance.issues,
            ...(node_fs_1.default.existsSync(taskDefinitionAbsolute)
                ? (0, task_cycle_runtime_attribution_1.reviewTaskCycleRuntimeAttribution)(repositoryRoot, {
                    taskDefinitionPath,
                    taskMarkdownText: taskDefinitionText,
                    summaryMarkdownText: node_fs_1.default.readFileSync(summaryAbsolute, "utf8")
                })
                : [])
        ];
        if (isReconciliationCompletedSummaryEvidence(evidence) && 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 || (0, semantic_placeholder_1.hasSemanticPlaceholderContent)(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 inspectTaskRuntimeAcceptanceForReconciliation(options) {
    if (options.parent === null)
        return { issues: [], legacyCompatibility: false };
    const document = (0, document_paths_1.parseMarkdownDocument)(options.taskDefinitionPath, options.taskDefinitionText);
    const child = (0, runtime_acceptance_1.inspectRuntimeAcceptance)({
        artifactPath: options.taskDefinitionPath,
        artifactKind: "task",
        frontMatterLines: document.frontMatterLines,
        markdownText: options.taskDefinitionText,
        requireExplicitForExecutableEvidence: true
    });
    const status = (0, selector_evidence_1.readTopLevelField)(document.frontMatterLines, "status")?.trim() ?? null;
    const attributionRequired = (0, selector_evidence_1.readTopLevelField)(document.frontMatterLines, "runtime_attribution_required")?.trim() ?? null;
    const legacyCompatibility = child.metadata === null
        && options.parent.required
        && options.parent.breakoutTask === options.taskSlug
        && status === "completed"
        && attributionRequired === "false";
    if (legacyCompatibility) {
        // A closed bootstrap breakout remains readable, but contributes no inferred
        // criterion IDs and cannot authorize a new mutation. Current consumers must
        // carry the authoritative parent IDs explicitly.
        return { issues: [], legacyCompatibility: true };
    }
    return {
        issues: [...child.issues, ...(0, runtime_acceptance_1.validateInheritedRuntimeAcceptance)(options.parent, child.metadata)],
        legacyCompatibility: false
    };
}
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 summaryText = node_fs_1.default.readFileSync(summaryAbsolute, "utf8");
    const document = (0, document_paths_1.parseMarkdownDocument)(implementationSummaryPath, summaryText);
    (0, context_1.assertArtifactType)(document.frontMatterLines, implementationSummaryPath, "implementation_summary");
    const taskDefinitionPath = implementationSummaryPath.replace(/implementation-summary\.md$/, "task-definition.md");
    const taskDefinitionAbsolute = node_path_1.default.join(repositoryRoot, taskDefinitionPath);
    const taskDefinitionText = node_fs_1.default.existsSync(taskDefinitionAbsolute) ? node_fs_1.default.readFileSync(taskDefinitionAbsolute, "utf8") : null;
    const lifecycle = resolveSummaryEvidenceLifecycle(summaryText, taskDefinitionText !== null && reviewWaiverApplies(implementationSummaryPath, summaryText, taskDefinitionText));
    return {
        relativePath: implementationSummaryPath,
        implementationStatus: lifecycle.implementationStatus,
        reviewDisposition: lifecycle.reviewDisposition,
        completionEvidenceKind: lifecycle.completionEvidenceKind,
        artifactStatus: lifecycle.completionEvidenceKind === undefined ? "draft" : "completed",
        executionMode: (0, artifact_policy_projection_1.projectArtifactPolicy)(summaryText).evidenceProfile,
        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,
        declaredTargetEvidence: taskDefinitionText === null
            ? []
            : (0, declared_target_paths_1.readTaskDeclaredTargetPathEvidence)(taskDefinitionPath, taskDefinitionText).evidence
    };
}
function resolveSummaryEvidenceLifecycle(summaryText, reviewWaiverApplicable = false) {
    const projection = (0, task_lifecycle_1.projectImplementationSummaryLifecycle)(summaryText);
    const lifecycle = projection.value;
    const implementationStatus = lifecycle.currentAttempt?.implementationStatus
        ?? lifecycle.legacyImplementationStatus
        ?? "";
    const reviewDisposition = lifecycle.currentAttempt?.reviewDisposition
        ?? lifecycle.legacyReviewDisposition
        ?? "";
    const currentAcceptedCompleted = lifecycle.currentAttempt?.implementationStatus === "completed"
        && (lifecycle.currentAttempt.reviewDisposition === "accepted"
            || lifecycle.currentAttempt.reviewDisposition === "accepted_with_follow_up");
    const currentWaivedCompleted = lifecycle.currentAttempt?.implementationStatus === "completed"
        && lifecycle.currentAttempt.reviewDisposition === "waived"
        && reviewWaiverApplicable;
    const legacyArtifactStatus = (0, selector_evidence_1.readTopLevelField)((0, document_paths_1.parseMarkdownDocument)("implementation-summary.md", summaryText).frontMatterLines, "status")?.trim() ?? null;
    const legacyTerminalCompleted = lifecycle.currentAttempt === null
        && lifecycle.attempts.length === 0
        && lifecycle.legacyImplementationStatus === "completed"
        && legacyArtifactStatus === "completed"
        && projection.blockingFindings.length === 0;
    return {
        implementationStatus,
        reviewDisposition,
        completionEvidenceKind: currentAcceptedCompleted
            ? "accepted_current_attempt"
            : currentWaivedCompleted
                ? "waived_current_attempt"
                : legacyTerminalCompleted
                    ? "legacy_terminal_projection"
                    : undefined
    };
}
function reviewWaiverApplies(summaryPath, summaryText, taskDefinitionText) {
    const lifecycle = (0, task_lifecycle_1.projectImplementationSummaryLifecycle)(summaryText).value;
    const current = lifecycle.currentAttempt;
    if (current?.reviewDisposition !== "waived" || current.reviewWaiverId === null)
        return false;
    const taskLines = (0, document_paths_1.parseMarkdownDocument)("task-definition.md", taskDefinitionText).frontMatterLines;
    const subjectId = (0, front_matter_utils_1.parseScalar)((0, selector_evidence_1.readTopLevelField)(taskLines, "task") ?? (0, selector_evidence_1.readTopLevelField)(taskLines, "id") ?? "") ?? "";
    return subjectId !== "" && (0, task_waivers_1.findApplicableTaskWaiver)(summaryPath, summaryText, {
        waiverType: "review",
        subjectId,
        attemptId: current.attemptId,
        evaluatedAt: new Date().toISOString(),
        authorityRequired: true,
        waiverId: current.reviewWaiverId
    })?.applicable === true;
}
function isReconciliationCompletedSummaryEvidence(evidence) {
    return evidence.implementationStatus === "completed"
        && evidence.completionEvidenceKind !== undefined;
}
function formatCompletionEvidenceLabel(evidence) {
    const lifecycleLabel = evidence.completionEvidenceKind === "legacy_terminal_projection"
        ? " Compatibility: legacy top-level terminal completion is used for read-only reconciliation aggregation; accepted review disposition is not inferred."
        : evidence.completionEvidenceKind === "waived_current_attempt"
            ? " Completion uses an applicable explicit review waiver; accepted review disposition is not inferred."
            : "";
    const runtimeLabel = evidence.legacyRuntimeAcceptanceCompatibility === true
        ? " Legacy bootstrap breakout is read-only compatibility evidence; runtime criterion IDs are not inferred and cannot authorize mutation."
        : "";
    return `${lifecycleLabel}${runtimeLabel}`;
}
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 = (0, document_paths_1.parseMarkdownDocument)(taskDefinitionPath.relative, node_fs_1.default.readFileSync(taskDefinitionPath.absolute, "utf8"));
    (0, context_1.assertArtifactType)(taskDocument.frontMatterLines, taskDefinitionPath.relative, "task_definition");
    const context = (0, context_1.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"));
}
