"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.reviewTaskReadiness = reviewTaskReadiness;
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 validation_1 = require("../validation");
const front_matter_utils_1 = require("./front-matter-utils");
const planning_heuristics_1 = require("./planning-heuristics");
const authoring_policy_1 = require("./authoring-policy");
const planning_artifact_document_1 = require("./planning-artifact-document");
const execution_profiles_1 = require("./execution-profiles");
const runtime_acceptance_1 = require("./runtime-acceptance");
const REQUIRED_SECTIONS = [
    "Objective",
    "Upstream Context",
    "Implementation Target Paths",
    "Current Behavior",
    "Desired Behavior",
    "Acceptance Criteria",
    "Validation Commands",
    "Rollback / Recovery",
    "Risks",
    "Dependencies",
    "Constraints",
    "Assumptions",
    "Open Questions"
];
const RUNTIME_DELTA_REQUIRED_EVIDENCE = [
    { label: "runtime target files", pattern: /\b(runtime\s+)?target files?\b/i },
    { label: "expected behavior change", pattern: /\bexpected behavior change\b/i },
    { label: "verification commands with expected evidence", pattern: /\bverification commands?\b/i },
    { label: "rollback path", pattern: /\brollback (path|command|scope)\b/i }
];
const PLACEHOLDER_PATTERN = /(\bTBD\b|\bTODO\b|^PLACEHOLDER$|{{\s*[A-Za-z0-9_]+\s*}}|^pending$)/im;
const LEAKED_TEMPLATE_PHRASES = [
    "Template notes:",
    "Use this section to",
    "List only",
    "Keep only",
    "If there are none, use exactly"
];
const UNRESOLVED_PLACEHOLDER_PATTERN = /{{\s*[A-Za-z0-9_]+\s*}}/g;
const FENCED_CODE_BLOCK_PATTERN = /(^|\n)(```|~~~)[^\n]*\n[\s\S]*?\n\2(?=\n|$)/g;
const INLINE_CODE_SPAN_PATTERN = /`+[^`\n]+`+/g;
function reviewTaskReadiness(repositoryRoot, options) {
    const taskDefinitionPath = resolveTaskDefinitionPath(repositoryRoot, options.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."]);
    }
    const fileText = node_fs_1.default.readFileSync(taskDefinitionPath.absolute, "utf8");
    const parsedTaskDocument = parseTaskDocument(taskDefinitionPath.relative, fileText);
    const missingEvidence = [];
    const dependencyBlockers = [];
    const sequencingIssues = [];
    const handoffBlockers = [];
    const reviewBoundaryWarnings = [];
    const authoringIssues = (0, authoring_policy_1.auditPlanningArtifactAuthoring)({
        artifactPath: taskDefinitionPath.relative,
        artifactType: "task_definition",
        markdownText: fileText,
        allowLegacyManualAlias: true,
        allowMissingProvenance: true
    });
    missingEvidence.push(...(0, authoring_policy_1.formatPlanningAuthoringIssues)(authoringIssues));
    const readiness = readTopLevelField(parsedTaskDocument.frontMatter.lines, "readiness");
    const executionMode = readTopLevelField(parsedTaskDocument.frontMatter.lines, "execution_mode")?.trim() ?? null;
    const planningDepth = readTopLevelField(parsedTaskDocument.frontMatter.lines, "planning_depth")?.trim() ?? null;
    const executionProfile = readTopLevelField(parsedTaskDocument.frontMatter.lines, "execution_profile")?.trim() ?? null;
    const isLightweightTask = planningDepth === "lightweight";
    if (readiness === undefined || readiness.trim() === "") {
        missingEvidence.push("Front matter field 'readiness' is missing.");
    }
    else if (!isAllowedReadiness(readiness.trim())) {
        missingEvidence.push(`Front matter field 'readiness' uses unsupported value '${readiness.trim()}'.`);
    }
    if (executionMode === null || executionMode === "") {
        missingEvidence.push("Front matter field 'execution_mode' is missing.");
    }
    else if (!isAllowedExecutionMode(executionMode)) {
        missingEvidence.push(`Front matter field 'execution_mode' uses unsupported value '${executionMode}'.`);
    }
    let executionProfileReadiness = null;
    if (executionProfile !== null) {
        if (!(0, execution_profiles_1.isExecutionProfileId)(executionProfile)) {
            missingEvidence.push(`Front matter field 'execution_profile' uses unsupported value '${executionProfile}'.`);
        }
        else {
            const targetPathEvidence = (0, validation_1.readTaskDeclaredTargetPathEvidence)(taskDefinitionPath.relative, fileText);
            executionProfileReadiness = (0, execution_profiles_1.evaluateExecutionProfileReadiness)(executionProfile, {
                sections: parsedTaskDocument.sections,
                targetPaths: targetPathEvidence.explicitTargetPaths
            });
            missingEvidence.push(...executionProfileReadiness.blockers.map((blocker) => `Execution profile blocker: ${blocker}`));
        }
    }
    for (const sectionName of REQUIRED_SECTIONS) {
        const sectionText = parsedTaskDocument.sections.get(sectionName);
        if (sectionText === undefined) {
            missingEvidence.push(`Missing required section '${sectionName}'.`);
            continue;
        }
        if (isIncompleteSection(sectionText)) {
            missingEvidence.push(`Section '${sectionName}' is incomplete.`);
        }
    }
    if (executionMode === "runtime" || executionMode === "hybrid") {
        const runtimeDeltaText = parsedTaskDocument.sections.get("Runtime Delta");
        if (runtimeDeltaText === undefined) {
            missingEvidence.push("Runtime Delta section is required for runtime and hybrid tasks.");
        }
        else if (isIncompleteSection(runtimeDeltaText)) {
            missingEvidence.push("Runtime Delta section is incomplete for runtime or hybrid execution mode.");
        }
        else {
            const missingRuntimeDeltaEvidence = RUNTIME_DELTA_REQUIRED_EVIDENCE
                .filter((requirement) => !requirement.pattern.test(runtimeDeltaText))
                .map((requirement) => requirement.label);
            if (missingRuntimeDeltaEvidence.length > 0) {
                missingEvidence.push(`Runtime Delta section is missing required evidence: ${missingRuntimeDeltaEvidence.join(", ")}.`);
            }
        }
    }
    if (!isLightweightTask) {
        const milestoneOverviewPath = resolveMilestoneOverviewPath(taskDefinitionPath.relative, repositoryRoot);
        if (milestoneOverviewPath !== null) {
            const parentText = node_fs_1.default.readFileSync(milestoneOverviewPath.absolute, "utf8");
            const parentFrontMatter = parseFrontMatter(milestoneOverviewPath.relative, parentText);
            const parentInspection = (0, runtime_acceptance_1.inspectRuntimeAcceptance)({
                artifactPath: milestoneOverviewPath.relative,
                artifactKind: "milestone",
                frontMatterLines: parentFrontMatter.lines,
                markdownText: parentText
            });
            missingEvidence.push(...parentInspection.issues.map((issue) => `Parent runtime acceptance: ${issue}`));
            const childInspection = (0, runtime_acceptance_1.inspectRuntimeAcceptance)({
                artifactPath: taskDefinitionPath.relative,
                artifactKind: "task",
                frontMatterLines: parsedTaskDocument.frontMatter.lines,
                markdownText: fileText,
                requireExplicitForExecutableEvidence: false
            });
            missingEvidence.push(...childInspection.issues.map((issue) => `Task runtime acceptance: ${issue}`));
            if (parentInspection.metadata !== null) {
                missingEvidence.push(...(0, runtime_acceptance_1.validateTaskRuntimeAcceptance)({
                    parent: parentInspection.metadata,
                    child: childInspection.metadata,
                    executionMode,
                    taskMarkdown: fileText
                }));
            }
            else if (childInspection.metadata !== null) {
                missingEvidence.push("Task runtime_acceptance metadata cannot classify acceptance when the parent milestone has no authoritative runtime_acceptance metadata.");
            }
        }
    }
    const openQuestionsText = parsedTaskDocument.sections.get("Open Questions");
    if (openQuestionsText !== undefined && !isOpenQuestionsResolved(openQuestionsText)) {
        missingEvidence.push("Open questions are unresolved.");
    }
    const implementationTargetPathsText = parsedTaskDocument.sections.get("Implementation Target Paths");
    const constraintsText = parsedTaskDocument.sections.get("Constraints");
    if (implementationTargetPathsText !== undefined
        && constraintsText !== undefined
        && forbidsSharedImplementationOverlap(constraintsText)) {
        const overlappingSiblingPaths = detectLaterImplementationTargetOverlap(repositoryRoot, taskDefinitionPath.relative, implementationTargetPathsText);
        if (overlappingSiblingPaths.length > 0) {
            missingEvidence.push(`Implementation Target Paths overlap with later implementation-owned sibling task surfaces despite the declared no-shared-implementation constraint: ${overlappingSiblingPaths.join(", ")}.`);
        }
    }
    const leakedTemplatePhrases = detectLeakedTemplatePhrases(fileText);
    for (const leakedPhrase of leakedTemplatePhrases) {
        missingEvidence.push(`Leaked template scaffolding detected: '${leakedPhrase}'.`);
    }
    const unresolvedPlaceholders = detectUnresolvedPlaceholders(fileText);
    if (unresolvedPlaceholders.length > 0) {
        missingEvidence.push(`Unresolved template placeholders remain: ${unresolvedPlaceholders.join(", ")}.`);
    }
    const dependenciesText = parsedTaskDocument.sections.get("Dependencies");
    if (dependenciesText !== undefined) {
        const dependencyPaths = extractDependencyPaths(dependenciesText);
        const sequencingContext = resolveSequencingContext(taskDefinitionPath.relative, readTopLevelField(parsedTaskDocument.frontMatter.lines, "task"));
        for (const dependencyPath of dependencyPaths) {
            let parsedDependencyPath;
            try {
                parsedDependencyPath = (0, paths_1.parseRepositoryRelativePath)(dependencyPath);
            }
            catch {
                dependencyBlockers.push(`Dependency path '${dependencyPath}' is not a valid repository-relative path.`);
                continue;
            }
            if (!isArtifactPathLike(parsedDependencyPath.normalizedPath)) {
                dependencyBlockers.push(`Dependency entry '${dependencyPath}' is prose, not a repository-relative artifact path. Move behavioral dependency prose to Upstream Context, Current Behavior, or Assumptions, or replace it with concrete artifact paths.`);
                continue;
            }
            const dependencyAbsolutePath = node_path_1.default.join(repositoryRoot, parsedDependencyPath.normalizedPath);
            if (!node_fs_1.default.existsSync(dependencyAbsolutePath)) {
                dependencyBlockers.push(`Dependency artifact '${parsedDependencyPath.normalizedPath}' does not exist.`);
                continue;
            }
            const sequencedIssue = detectLaterSiblingDependency(sequencingContext, parsedDependencyPath.normalizedPath);
            if (sequencedIssue !== null) {
                sequencingIssues.push(sequencedIssue);
            }
        }
    }
    const readinessStatus = missingEvidence.length === 0
        && dependencyBlockers.length === 0
        && sequencingIssues.length === 0
        ? "ready to implement"
        : "blocked";
    const pairedImplementationSummaryPath = (0, front_matter_utils_1.toRepositoryLikePath)(node_path_1.default.join(node_path_1.default.dirname(taskDefinitionPath.relative), "implementation-summary.md"));
    const milestoneReconciliationPath = isLightweightTask
        ? null
        : resolveMilestoneReconciliationPath(taskDefinitionPath.relative);
    const implementationSummaryAbsolutePath = node_path_1.default.join(repositoryRoot, pairedImplementationSummaryPath);
    if (!node_fs_1.default.existsSync(implementationSummaryAbsolutePath)) {
        handoffBlockers.push(`Paired implementation summary '${pairedImplementationSummaryPath}' does not exist.`);
    }
    else {
        const summaryText = node_fs_1.default.readFileSync(implementationSummaryAbsolutePath, "utf8");
        const summaryFrontMatter = parseFrontMatter(pairedImplementationSummaryPath, summaryText);
        const artifactType = readTopLevelField(summaryFrontMatter.lines, "artifact_type")?.trim();
        if (artifactType !== "implementation_summary") {
            handoffBlockers.push(`Paired implementation summary '${pairedImplementationSummaryPath}' has unsupported artifact_type '${artifactType ?? "(missing)"}'.`);
        }
        const implementationStatus = readTopLevelField(summaryFrontMatter.lines, "implementation_status")?.trim();
        if (implementationStatus !== "pending" && implementationStatus !== "completed") {
            handoffBlockers.push(`Paired implementation summary '${pairedImplementationSummaryPath}' uses unsupported implementation_status '${implementationStatus ?? "(missing)"}'.`);
        }
        const taskLifecycleStatus = readTopLevelField(parsedTaskDocument.frontMatter.lines, "status")?.trim();
        if (implementationStatus === "completed" && taskLifecycleStatus !== "completed") {
            handoffBlockers.push(`Unsupported state transition: '${pairedImplementationSummaryPath}' is implementation_status 'completed' while task-definition status is '${taskLifecycleStatus ?? "(missing)"}'.`);
        }
    }
    const reconciliationAbsolutePath = milestoneReconciliationPath === null
        ? null
        : node_path_1.default.join(repositoryRoot, milestoneReconciliationPath);
    if (reconciliationAbsolutePath !== null && !node_fs_1.default.existsSync(reconciliationAbsolutePath)) {
        reviewBoundaryWarnings.push(`Milestone reconciliation artifact '${milestoneReconciliationPath}' is missing; milestone-level reconciliation is the default review rollup path.`);
    }
    const handoffStatus = readinessStatus === "ready to implement" && handoffBlockers.length === 0
        ? "ready for implementation handoff"
        : "blocked";
    const currentLifecycleEvidence = handoffStatus === "ready for implementation handoff"
        ? [
            `task readiness review found '${taskDefinitionPath.relative}' ready for implementation handoff`,
            `paired implementation summary exists at '${pairedImplementationSummaryPath}'`
        ]
        : [];
    const heuristicFindings = (0, planning_heuristics_1.collectPlanningHeuristicFindings)({
        artifactPath: taskDefinitionPath.relative,
        artifactFamily: "task_definition",
        frontMatterLines: parsedTaskDocument.frontMatter.lines,
        sections: parsedTaskDocument.sections,
        enabledRuleFamilies: ["planning-language", "decomposition", "target-path-hygiene", "dependency-hygiene", "stale-spec-risk", "lightweight-promotion-pressure"],
        currentLifecycleEvidence
    });
    reviewBoundaryWarnings.push(...heuristicFindings.map((finding) => finding.message));
    const blockingIssues = [
        ...missingEvidence,
        ...dependencyBlockers,
        ...sequencingIssues
    ];
    const warnings = [
        ...handoffBlockers,
        ...reviewBoundaryWarnings
    ];
    const recoveryGuidance = buildTaskReadinessRecoveryGuidance({
        taskDefinitionPath: taskDefinitionPath.relative,
        missingEvidence,
        dependencyBlockers,
        sequencingIssues,
        handoffBlockers,
        reviewBoundaryWarnings
    });
    const findings = [
        ...buildReviewFindings("TASK_READINESS_MISSING_EVIDENCE", "error", missingEvidence, taskDefinitionPath.relative),
        ...buildReviewFindings("TASK_READINESS_DEPENDENCY_BLOCKER", "error", dependencyBlockers, taskDefinitionPath.relative),
        ...buildReviewFindings("TASK_READINESS_SEQUENCING_BLOCKER", "error", sequencingIssues, taskDefinitionPath.relative),
        ...buildReviewFindings("TASK_READINESS_HANDOFF_BLOCKER", "warning", handoffBlockers, pairedImplementationSummaryPath),
        ...buildReviewFindings("TASK_READINESS_REVIEW_BOUNDARY_WARNING", "warning", reviewBoundaryWarnings, milestoneReconciliationPath ?? pairedImplementationSummaryPath),
        ...heuristicFindings
    ];
    return {
        repositoryRoot,
        taskDefinitionPath: taskDefinitionPath.relative,
        reviewedReadiness: readiness?.trim() || null,
        readinessStatus,
        handoffStatus,
        pairedImplementationSummaryPath,
        milestoneReconciliationPath,
        reviewBoundaryKind: isLightweightTask ? "lightweight-task-summary" : "milestone-reconciliation",
        missingEvidence,
        dependencyBlockers,
        sequencingIssues,
        handoffBlockers,
        reviewBoundaryWarnings,
        blockingIssues,
        warnings,
        recoveryGuidance,
        findings,
        executionProfileReadiness
    };
}
function buildTaskReadinessRecoveryGuidance(options) {
    const guidance = [];
    if (options.missingEvidence.length > 0) {
        guidance.push(`Update '${options.taskDefinitionPath}' to supply the missing readiness evidence before implementation starts.`);
    }
    if (options.dependencyBlockers.length > 0) {
        if (options.dependencyBlockers.some((message) => message.includes("is prose, not a repository-relative artifact path"))) {
            guidance.push("Move prose dependency bullets out of '## Dependencies' into Upstream Context, Current Behavior, or Assumptions, or replace them with concrete repository-relative artifact paths.");
        }
        guidance.push("Create, restore, or relink the cited dependency artifacts before implementation.");
    }
    if (options.sequencingIssues.length > 0) {
        guidance.push("Correct later-sibling dependencies or reorder the task sequence before implementation.");
    }
    if (options.handoffBlockers.length > 0) {
        guidance.push(`Restore the paired implementation-summary surface before handoff, for example with 'node dist/cli/index.js implementation-summary build --task-definition ${options.taskDefinitionPath}'.`);
    }
    if (options.reviewBoundaryWarnings.length > 0) {
        guidance.push("Carry review-boundary warnings forward as milestone-handoff evidence only; do not treat them as permission to write during readiness review.");
    }
    return guidance;
}
function buildReviewFindings(code, severity, messages, artifactPath) {
    return messages.map((message) => ({
        code,
        message,
        severity,
        path: artifactPath
    }));
}
function resolveTaskDefinitionPath(repositoryRoot, inputPath) {
    try {
        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 {
            relative: parsed.normalizedPath,
            absolute: node_path_1.default.join(repositoryRoot, parsed.normalizedPath)
        };
    }
    catch (error) {
        if (error instanceof Error && error.name === "RuntimeError") {
            throw error;
        }
        throw (0, errors_1.createUsageError)(`Invalid --task-definition path '${inputPath}'.`, [error instanceof Error ? error.message : String(error)]);
    }
}
function parseTaskDocument(filePath, fileText) {
    const parsed = (0, planning_artifact_document_1.parsePlanningArtifactDocument)(fileText);
    if (!parsed.hasFrontMatter) {
        if (parsed.diagnostics.some((diagnostic) => diagnostic.code === "unterminated-front-matter")) {
            throw (0, errors_1.createUsageError)(`Artifact '${(0, front_matter_utils_1.toRepositoryLikePath)(filePath)}' has malformed YAML front matter.`);
        }
        throw (0, errors_1.createUsageError)(`Artifact '${(0, front_matter_utils_1.toRepositoryLikePath)(filePath)}' is missing YAML front matter.`);
    }
    const sections = new Map();
    for (const section of parsed.sections)
        sections.set(section.heading, section.contentText.trim());
    return {
        frontMatter: {
            lines: parsed.frontMatterLines,
            contentLines: parsed.bodyText.split(/\r?\n/)
        },
        sections
    };
}
function parseFrontMatter(filePath, fileText) {
    const parsed = (0, planning_artifact_document_1.parsePlanningArtifactDocument)(fileText);
    if (!parsed.hasFrontMatter) {
        if (parsed.diagnostics.some((diagnostic) => diagnostic.code === "unterminated-front-matter")) {
            throw (0, errors_1.createUsageError)(`Artifact '${(0, front_matter_utils_1.toRepositoryLikePath)(filePath)}' has malformed YAML front matter.`);
        }
        throw (0, errors_1.createUsageError)(`Artifact '${(0, front_matter_utils_1.toRepositoryLikePath)(filePath)}' is missing YAML front matter.`);
    }
    return { lines: parsed.frontMatterLines, contentLines: parsed.bodyText.split(/\r?\n/) };
}
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 isAllowedReadiness(value) {
    return value === "needs more evidence"
        || value === "ready"
        || value === "ready to implement"
        || value === "blocked"
        || value === "completed";
}
function isAllowedExecutionMode(value) {
    return value === "runtime" || value === "contract" || value === "hybrid";
}
function isIncompleteSection(value) {
    const trimmed = value.trim();
    if (trimmed.length === 0) {
        return true;
    }
    return PLACEHOLDER_PATTERN.test(stripMarkdownCode(trimmed));
}
function isOpenQuestionsResolved(sectionText) {
    const normalized = sectionText
        .split(/\r?\n/)
        .map((line) => line.trim())
        .filter((line) => line.length > 0);
    return normalized.length === 1 && normalized[0] === "- None currently.";
}
function detectLeakedTemplatePhrases(fileText) {
    const matches = new Set();
    for (const phrase of LEAKED_TEMPLATE_PHRASES) {
        const expression = new RegExp(escapeRegExp(phrase), "i");
        if (expression.test(fileText)) {
            matches.add(phrase);
        }
    }
    return [...matches];
}
function detectUnresolvedPlaceholders(fileText) {
    const matches = stripMarkdownCode(fileText).match(UNRESOLVED_PLACEHOLDER_PATTERN) ?? [];
    const unique = new Set(matches.map((match) => match.replace(/\s+/g, "")));
    return [...unique].sort();
}
function stripMarkdownCode(value) {
    return value
        .replace(FENCED_CODE_BLOCK_PATTERN, "\n")
        .replace(INLINE_CODE_SPAN_PATTERN, "");
}
function escapeRegExp(value) {
    return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
}
function extractDependencyPaths(sectionText) {
    return extractBulletedPaths(sectionText);
}
function isArtifactPathLike(dependencyPath) {
    if (/[,\s;]/.test(dependencyPath)) {
        return false;
    }
    return dependencyPath.startsWith(".")
        || dependencyPath.includes("/")
        || /^[A-Za-z0-9_.-]+\.[A-Za-z0-9]+$/.test(dependencyPath);
}
function extractBulletedPaths(sectionText) {
    const dependencies = [];
    for (const line of sectionText.split(/\r?\n/)) {
        const trimmed = line.trim();
        if (!trimmed.startsWith("- ")) {
            continue;
        }
        const item = trimmed.slice(2).trim();
        if (/^none(?: currently)?\.?$/i.test(item) || /^pending\b/i.test(item)) {
            continue;
        }
        const backtickMatch = item.match(/^`([^`]+)`$/);
        dependencies.push(backtickMatch === null ? item : backtickMatch[1]);
    }
    return dependencies;
}
function forbidsSharedImplementationOverlap(sectionText) {
    return /not [^.]*shared runtime implementation/i.test(sectionText)
        || /keep executable [^.]* out of this task/i.test(sectionText)
        || /later helper, CLI, and shared coverage work belongs to/i.test(sectionText);
}
function detectLaterImplementationTargetOverlap(repositoryRoot, taskDefinitionPath, implementationTargetPathsText) {
    const currentContext = resolveSequencingContext(taskDefinitionPath, taskDefinitionPath.match(/\/tasks\/([^/]+)\/task-definition\.md$/)?.[1]);
    if (currentContext.taskSlug === null || currentContext.milestoneTasksPrefix === null) {
        return [];
    }
    const currentTargetEvidence = (0, validation_1.readTaskDeclaredTargetPathEvidence)(taskDefinitionPath, `## Implementation Target Paths\n\n${implementationTargetPathsText}`);
    const currentTargets = new Set(currentTargetEvidence.explicitTargetPaths);
    if (currentTargets.size === 0) {
        return [];
    }
    const tasksDirectoryPath = node_path_1.default.join(repositoryRoot, `${currentContext.milestoneTasksPrefix}`);
    if (!node_fs_1.default.existsSync(tasksDirectoryPath)) {
        return [];
    }
    const overlappingPaths = new Set();
    for (const entry of node_fs_1.default.readdirSync(tasksDirectoryPath, { withFileTypes: true })) {
        if (!entry.isDirectory()) {
            continue;
        }
        const siblingSlug = entry.name;
        if (siblingSlug === currentContext.taskSlug) {
            continue;
        }
        const siblingOrder = parseOrderedPrefix(siblingSlug);
        const currentOrder = parseOrderedPrefix(currentContext.taskSlug);
        if (siblingOrder === null || currentOrder === null || siblingOrder <= currentOrder) {
            continue;
        }
        if (!/-implement-/i.test(siblingSlug)) {
            continue;
        }
        const siblingTaskDefinitionPath = node_path_1.default.join(tasksDirectoryPath, siblingSlug, "task-definition.md");
        if (!node_fs_1.default.existsSync(siblingTaskDefinitionPath)) {
            continue;
        }
        const siblingDocument = parseTaskDocument((0, front_matter_utils_1.toRepositoryLikePath)(node_path_1.default.relative(repositoryRoot, siblingTaskDefinitionPath)), node_fs_1.default.readFileSync(siblingTaskDefinitionPath, "utf8"));
        const siblingTargetsText = siblingDocument.sections.get("Implementation Target Paths");
        if (siblingTargetsText === undefined) {
            continue;
        }
        const siblingTargetEvidence = (0, validation_1.readTaskDeclaredTargetPathEvidence)((0, front_matter_utils_1.toRepositoryLikePath)(node_path_1.default.relative(repositoryRoot, siblingTaskDefinitionPath)), `## Implementation Target Paths\n\n${siblingTargetsText}`);
        for (const siblingTarget of siblingTargetEvidence.explicitTargetPaths) {
            if (currentTargets.has(siblingTarget)) {
                overlappingPaths.add(siblingTarget);
            }
        }
    }
    return [...overlappingPaths].sort();
}
function resolveSequencingContext(taskDefinitionPath, taskSlugRaw) {
    const taskSlug = taskSlugRaw?.trim() || null;
    if (taskSlug === null || !(0, paths_1.isCanonicalSlug)(taskSlug)) {
        return {
            taskSlug: null,
            milestoneTasksPrefix: null
        };
    }
    const token = `/tasks/${taskSlug}/task-definition.md`;
    const tokenIndex = taskDefinitionPath.lastIndexOf(token);
    if (tokenIndex === -1) {
        return {
            taskSlug,
            milestoneTasksPrefix: null
        };
    }
    return {
        taskSlug,
        milestoneTasksPrefix: taskDefinitionPath.slice(0, tokenIndex + 7)
    };
}
function detectLaterSiblingDependency(context, dependencyPath) {
    if (context.taskSlug === null || context.milestoneTasksPrefix === null) {
        return null;
    }
    if (!dependencyPath.startsWith(context.milestoneTasksPrefix)) {
        return null;
    }
    const dependencyMatch = dependencyPath.match(/\/tasks\/([^/]+)\/task-definition\.md$/);
    if (dependencyMatch === null) {
        return null;
    }
    const currentOrder = parseOrderedPrefix(context.taskSlug);
    const dependencyOrder = parseOrderedPrefix(dependencyMatch[1]);
    if (currentOrder === null || dependencyOrder === null) {
        return null;
    }
    if (dependencyOrder > currentOrder) {
        return `Dependency '${dependencyPath}' references later-numbered sibling task '${dependencyMatch[1]}'.`;
    }
    return null;
}
function parseOrderedPrefix(slug) {
    const match = slug.match(/^(\d+)-/);
    if (match === null) {
        return null;
    }
    return Number.parseInt(match[1], 10);
}
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 resolveMilestoneOverviewPath(taskDefinitionPath, repositoryRoot) {
    const normalizedPath = (0, front_matter_utils_1.toRepositoryLikePath)(taskDefinitionPath);
    const marker = "/tasks/";
    const markerIndex = normalizedPath.lastIndexOf(marker);
    if (markerIndex === -1) {
        return null;
    }
    const milestoneDirectory = normalizedPath.slice(0, markerIndex);
    for (const fileName of ["milestone-overview.md", "overview.md"]) {
        const relative = `${milestoneDirectory}/${fileName}`;
        const absolute = node_path_1.default.join(repositoryRoot, relative);
        if (node_fs_1.default.existsSync(absolute)) {
            return { relative, absolute };
        }
    }
    return null;
}
