"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.readDirectTasks = readDirectTasks;
exports.readGovernedHierarchy = readGovernedHierarchy;
exports.readCanonicalChildDirectories = readCanonicalChildDirectories;
exports.validateGovernedHierarchyArtifact = validateGovernedHierarchyArtifact;
exports.readGovernedReconciliation = readGovernedReconciliation;
exports.readTask = readTask;
exports.parseOverview = parseOverview;
exports.parseOverviewSpecifications = parseOverviewSpecifications;
exports.aggregationPreconditions = aggregationPreconditions;
// Structured and governed project review aggregation, persistence, and closure orchestration.
const node_fs_1 = __importDefault(require("node:fs"));
const node_path_1 = __importDefault(require("node:path"));
const mutation_preconditions_1 = require("../filesystem/mutation-preconditions");
const artifact_policy_projection_1 = require("../planning/artifact-policy-projection");
const planning_artifact_document_1 = require("../planning/planning-artifact-document");
const task_lifecycle_1 = require("../planning/task-lifecycle");
const planning_document_utils_1 = require("../planning/planning-document-utils");
const canonical_write_target_1 = require("../paths/canonical-write-target");
const ordered_root_identity_1 = require("../planning/ordered-root-identity");
const contracts_and_aggregation_1 = require("./contracts-and-aggregation");
const rendering_and_storage_1 = require("./rendering-and-storage");
function readDirectTasks(repositoryRoot, workRoot, runtimeTasksRoot, findings) {
    if (!node_fs_1.default.existsSync(runtimeTasksRoot))
        return [];
    if (!node_fs_1.default.statSync(runtimeTasksRoot).isDirectory()) {
        findings.push((0, rendering_and_storage_1.finding)('STRUCTURED_TASK_ROOT_INVALID', 'error', node_path_1.default.posix.join(workRoot, 'tasks'), 'Structured tasks path is not a directory.'));
        return [];
    }
    try {
        return (0, ordered_root_identity_1.inspectStructuredTaskCollectionSync)({
            repositoryRoot,
            collectionPath: node_path_1.default.posix.join(workRoot, 'tasks'),
        })
            .entries.map((entry) => readTask(repositoryRoot, node_path_1.default.posix.dirname(entry.taskDefinitionPath), entry.taskId, 'structured'))
            .sort((left, right) => left.sequence === right.sequence
            ? left.taskId.localeCompare(right.taskId)
            : (left.sequence ?? Number.MAX_SAFE_INTEGER) - (right.sequence ?? Number.MAX_SAFE_INTEGER));
    }
    catch (error) {
        findings.push((0, rendering_and_storage_1.finding)('STRUCTURED_TASK_INVENTORY_INVALID', 'error', node_path_1.default.posix.join(workRoot, 'tasks'), error instanceof ordered_root_identity_1.OrderedRootIdentityError ? error.message : 'Structured task inventory could not be resolved.'));
        return [];
    }
}
function readGovernedHierarchy(repositoryRoot, sliceRoot, sliceId, findings) {
    const tasks = [];
    const reconciliations = [];
    const hierarchyArtifacts = [];
    const sliceOverviewPath = node_path_1.default.posix.join(sliceRoot, 'slice-overview.md');
    hierarchyArtifacts.push(validateGovernedHierarchyArtifact(repositoryRoot, {
        artifactPath: sliceOverviewPath,
        expectedArtifactType: 'slice_overview',
        expectedParents: {},
        sliceId,
        findingLabel: 'SLICE',
    }, findings));
    const phasesRoot = node_path_1.default.posix.join(sliceRoot, 'phases');
    const phaseIds = readCanonicalChildDirectories(repositoryRoot, phasesRoot, 'GOVERNED_PHASE_SET_EMPTY', `Governed slice '${sliceId}' requires at least one canonical phase.`, findings);
    for (const phaseId of phaseIds) {
        const phaseRoot = node_path_1.default.posix.join(phasesRoot, phaseId);
        const phaseOverviewPath = node_path_1.default.posix.join(phaseRoot, 'phase-overview.md');
        hierarchyArtifacts.push(validateGovernedHierarchyArtifact(repositoryRoot, {
            artifactPath: phaseOverviewPath,
            expectedArtifactType: 'phase_overview',
            expectedParents: { slice_overview: sliceOverviewPath },
            sliceId,
            findingLabel: 'PHASE',
        }, findings));
        const milestonesRoot = node_path_1.default.posix.join(phaseRoot, 'milestones');
        const milestoneIds = readCanonicalChildDirectories(repositoryRoot, milestonesRoot, 'GOVERNED_MILESTONE_SET_EMPTY', `Governed phase '${phaseId}' requires at least one canonical milestone.`, findings);
        for (const milestoneId of milestoneIds) {
            const milestoneRoot = node_path_1.default.posix.join(milestonesRoot, milestoneId);
            const milestoneOverviewPath = node_path_1.default.posix.join(milestoneRoot, 'milestone-overview.md');
            hierarchyArtifacts.push(validateGovernedHierarchyArtifact(repositoryRoot, {
                artifactPath: milestoneOverviewPath,
                expectedArtifactType: 'milestone_overview',
                expectedParents: {
                    slice_overview: sliceOverviewPath,
                    phase_overview: phaseOverviewPath,
                },
                sliceId,
                findingLabel: 'MILESTONE',
            }, findings));
            const tasksRoot = node_path_1.default.posix.join(milestoneRoot, 'tasks');
            const taskIds = readCanonicalChildDirectories(repositoryRoot, tasksRoot, 'GOVERNED_MILESTONE_TASK_SET_EMPTY', `Governed milestone '${milestoneId}' requires at least one canonical task pair.`, findings);
            for (const taskId of taskIds) {
                tasks.push(readTask(repositoryRoot, node_path_1.default.posix.join(tasksRoot, taskId), taskId, 'governed', {
                    sliceId,
                    expectedParents: {
                        slice_overview: sliceOverviewPath,
                        phase_overview: phaseOverviewPath,
                        milestone_overview: milestoneOverviewPath,
                    },
                }));
            }
            reconciliations.push(readGovernedReconciliation(repositoryRoot, {
                milestoneId,
                milestoneOverviewPath,
                reconciliationPath: node_path_1.default.posix.join(milestoneRoot, 'reconciliation.md'),
                sliceId,
                expectedParents: {
                    slice_overview: sliceOverviewPath,
                    phase_overview: phaseOverviewPath,
                    milestone_overview: milestoneOverviewPath,
                },
            }));
        }
    }
    return {
        tasks: tasks.sort((left, right) => left.taskDefinitionPath.localeCompare(right.taskDefinitionPath)),
        reconciliations: reconciliations.sort((left, right) => left.reconciliationPath.localeCompare(right.reconciliationPath)),
        hierarchyArtifacts: hierarchyArtifacts.sort((left, right) => left.artifactPath.localeCompare(right.artifactPath)),
    };
}
function readCanonicalChildDirectories(repositoryRoot, directoryPath, emptyCode, emptyMessage, findings) {
    const target = (0, canonical_write_target_1.resolveCanonicalWriteTargetSync)(repositoryRoot, directoryPath);
    if (!target.exists || !node_fs_1.default.statSync(target.runtimePath).isDirectory()) {
        findings.push((0, rendering_and_storage_1.finding)(emptyCode, 'error', directoryPath, emptyMessage));
        return [];
    }
    const children = node_fs_1.default
        .readdirSync(target.runtimePath, { withFileTypes: true })
        .filter((entry) => entry.isDirectory())
        .map((entry) => entry.name)
        .sort((left, right) => left.localeCompare(right));
    if (children.length === 0) {
        findings.push((0, rendering_and_storage_1.finding)(emptyCode, 'error', directoryPath, emptyMessage));
    }
    return children;
}
function validateGovernedHierarchyArtifact(repositoryRoot, options, findings) {
    const target = (0, canonical_write_target_1.resolveCanonicalWriteTargetSync)(repositoryRoot, options.artifactPath);
    if (!target.exists || !node_fs_1.default.statSync(target.runtimePath).isFile()) {
        findings.push((0, rendering_and_storage_1.finding)(`GOVERNED_${options.findingLabel}_OVERVIEW_MISSING`, 'error', options.artifactPath, `Governed hierarchy artifact '${options.artifactPath}' is missing.`));
        return {
            artifactType: options.expectedArtifactType,
            artifactPath: options.artifactPath,
            artifactRevision: null,
        };
    }
    const text = node_fs_1.default.readFileSync(target.runtimePath, 'utf8');
    const document = (0, planning_document_utils_1.parseMarkdownFrontMatter)(text);
    const artifactType = (0, planning_document_utils_1.readTopLevelField)(document.frontMatterLines, 'artifact_type');
    const workflowLevel = (0, planning_document_utils_1.readTopLevelField)(document.frontMatterLines, 'workflow_level');
    const sliceId = (0, planning_document_utils_1.readTopLevelField)(document.frontMatterLines, 'slice') ??
        (artifactType === 'slice_overview' ? (0, planning_document_utils_1.readTopLevelField)(document.frontMatterLines, 'id') : null);
    if (artifactType !== options.expectedArtifactType || workflowLevel !== 'governed' || sliceId !== options.sliceId) {
        findings.push((0, rendering_and_storage_1.finding)(`GOVERNED_${options.findingLabel}_IDENTITY_MISMATCH`, 'error', options.artifactPath, `Governed hierarchy artifact '${options.artifactPath}' must be ${options.expectedArtifactType} with workflow_level governed for slice '${options.sliceId}'.`));
    }
    if (options.expectedArtifactType === 'slice_overview' &&
        (0, rendering_and_storage_1.readNestedUpstream)(document.frontMatterLines, 'work_overview') !== null) {
        findings.push((0, rendering_and_storage_1.finding)('GOVERNED_SLICE_PARENT_MISMATCH', 'error', options.artifactPath, `Canonical Governed slice root '${options.artifactPath}' must not reference a work_overview parent.`));
    }
    for (const [parentKind, expectedPath] of Object.entries(options.expectedParents)) {
        const actualPath = (0, rendering_and_storage_1.readNestedUpstream)(document.frontMatterLines, parentKind);
        if (actualPath !== expectedPath) {
            findings.push((0, rendering_and_storage_1.finding)(`GOVERNED_${options.findingLabel}_PARENT_MISMATCH`, 'error', options.artifactPath, `Governed hierarchy artifact '${options.artifactPath}' must reference ${parentKind} '${expectedPath}', found '${actualPath ?? '(missing)'}'.`));
        }
    }
    return {
        artifactType: options.expectedArtifactType,
        artifactPath: options.artifactPath,
        artifactRevision: (0, rendering_and_storage_1.revision)(text),
    };
}
function readGovernedReconciliation(repositoryRoot, options) {
    const target = (0, canonical_write_target_1.resolveCanonicalWriteTargetSync)(repositoryRoot, options.reconciliationPath);
    const blockers = [];
    if (!target.exists || !node_fs_1.default.statSync(target.runtimePath).isFile()) {
        blockers.push((0, rendering_and_storage_1.finding)('GOVERNED_RECONCILIATION_MISSING', 'error', options.reconciliationPath, `Governed milestone '${options.milestoneId}' is missing reconciliation.md.`));
        return {
            milestoneId: options.milestoneId,
            milestoneOverviewPath: options.milestoneOverviewPath,
            reconciliationPath: options.reconciliationPath,
            reconciliationRevision: null,
            status: null,
            reconciliationStatus: null,
            placeholderFree: false,
            acceptedResidualWork: false,
            followUpWork: false,
            deferredWork: false,
            waiverEvidence: false,
            reviewConcerns: true,
            blockers,
        };
    }
    const text = node_fs_1.default.readFileSync(target.runtimePath, 'utf8');
    const frontMatter = (0, planning_document_utils_1.parseMarkdownFrontMatter)(text);
    const parsed = (0, planning_artifact_document_1.parsePlanningArtifactDocument)(text);
    const artifactType = (0, planning_document_utils_1.readTopLevelField)(frontMatter.frontMatterLines, 'artifact_type');
    const workflowLevel = (0, planning_document_utils_1.readTopLevelField)(frontMatter.frontMatterLines, 'workflow_level');
    const milestone = (0, planning_document_utils_1.readTopLevelField)(frontMatter.frontMatterLines, 'milestone');
    const sliceId = (0, planning_document_utils_1.readTopLevelField)(frontMatter.frontMatterLines, 'slice');
    const status = (0, planning_document_utils_1.readTopLevelField)(frontMatter.frontMatterLines, 'status') ?? null;
    const reconciliationStatus = (0, planning_document_utils_1.readTopLevelField)(frontMatter.frontMatterLines, 'reconciliation_status') ?? null;
    if (artifactType !== 'reconciliation' ||
        workflowLevel !== 'governed' ||
        sliceId !== options.sliceId ||
        milestone !== options.milestoneId) {
        blockers.push((0, rendering_and_storage_1.finding)('GOVERNED_RECONCILIATION_IDENTITY_MISMATCH', 'error', options.reconciliationPath, `Reconciliation '${options.reconciliationPath}' must identify Governed slice '${options.sliceId}' and milestone '${options.milestoneId}'.`));
    }
    for (const [parentKind, expectedPath] of Object.entries(options.expectedParents)) {
        const actualPath = (0, rendering_and_storage_1.readNestedUpstream)(frontMatter.frontMatterLines, parentKind);
        if (actualPath !== expectedPath) {
            blockers.push((0, rendering_and_storage_1.finding)('GOVERNED_RECONCILIATION_PARENT_MISMATCH', 'error', options.reconciliationPath, `Reconciliation '${options.reconciliationPath}' must reference ${parentKind} '${expectedPath}', found '${actualPath ?? '(missing)'}'.`));
        }
    }
    const requiredSections = [
        'Review Status',
        'Completed Task Summaries',
        'Acceptance Criteria Review',
        'Validation Review',
        'Final Notes',
    ];
    const sections = new Map(parsed.sections.map((section) => [section.heading, section.contentText.trim()]));
    const placeholderFree = requiredSections.every((heading) => {
        const value = sections.get(heading) ?? '';
        return value !== '' && !(0, rendering_and_storage_1.isPendingEvidence)(value);
    });
    if (status !== 'completed' || reconciliationStatus !== 'completed') {
        blockers.push((0, rendering_and_storage_1.finding)('GOVERNED_RECONCILIATION_INCOMPLETE', 'error', options.reconciliationPath, `Reconciliation '${options.reconciliationPath}' must have status and reconciliation_status completed.`));
    }
    if (!placeholderFree) {
        blockers.push((0, rendering_and_storage_1.finding)('GOVERNED_RECONCILIATION_PLACEHOLDER', 'error', options.reconciliationPath, `Reconciliation '${options.reconciliationPath}' retains missing or placeholder closeout evidence.`));
    }
    const acceptedResidualWork = (0, rendering_and_storage_1.sectionSignalsEvidence)(sections.get('Accepted Residual Work'));
    const followUpWork = (0, rendering_and_storage_1.sectionSignalsEvidence)(sections.get('Follow-Up Tasks'));
    const deferredWork = (0, rendering_and_storage_1.sectionSignalsEvidence)(sections.get('Backlog Work')) || (0, rendering_and_storage_1.sectionSignalsEvidence)(sections.get('Discovered Work'));
    const concernsText = sections.get('Review Concerns');
    const reviewConcerns = (0, rendering_and_storage_1.sectionSignalsEvidence)(concernsText);
    if (reviewConcerns) {
        blockers.push((0, rendering_and_storage_1.finding)('GOVERNED_RECONCILIATION_REVIEW_CONCERN', 'error', options.reconciliationPath, `Reconciliation '${options.reconciliationPath}' retains unresolved review concerns.`));
    }
    const waiverEvidence = [...sections.entries()].some(([heading, value]) => /waivers?/i.test(heading) && (0, rendering_and_storage_1.sectionSignalsEvidence)(value)) ||
        [sections.get('Accepted Residual Work'), sections.get('Review Status')].some((value) => value !== undefined &&
            /\bwaiver(?:s|ed)?\b/i.test(value) &&
            !/\b(?:no|none|without)\b[^.\n]*\bwaiver(?:s|ed)?\b/i.test(value));
    return {
        milestoneId: options.milestoneId,
        milestoneOverviewPath: options.milestoneOverviewPath,
        reconciliationPath: options.reconciliationPath,
        reconciliationRevision: (0, rendering_and_storage_1.revision)(text),
        status,
        reconciliationStatus,
        placeholderFree,
        acceptedResidualWork,
        followUpWork,
        deferredWork,
        waiverEvidence,
        reviewConcerns,
        blockers: (0, rendering_and_storage_1.sortFindings)(blockers),
    };
}
function readTask(repositoryRoot, taskRoot, directoryTaskId, workflowLevel, governedContext) {
    const taskDefinitionPath = node_path_1.default.posix.join(taskRoot, 'task-definition.md');
    const implementationSummaryPath = node_path_1.default.posix.join(taskRoot, 'implementation-summary.md');
    const taskTarget = (0, canonical_write_target_1.resolveCanonicalWriteTargetSync)(repositoryRoot, taskDefinitionPath);
    const summaryTarget = (0, canonical_write_target_1.resolveCanonicalWriteTargetSync)(repositoryRoot, implementationSummaryPath);
    const blockers = [];
    const findingPrefix = workflowLevel.toUpperCase();
    const levelTitle = (0, rendering_and_storage_1.titleLevel)(workflowLevel);
    if (!taskTarget.exists || !node_fs_1.default.statSync(taskTarget.runtimePath).isFile()) {
        blockers.push((0, rendering_and_storage_1.finding)(`${findingPrefix}_TASK_DEFINITION_MISSING`, 'error', taskDefinitionPath, `${levelTitle} task '${directoryTaskId}' is missing task-definition.md.`));
    }
    if (!summaryTarget.exists || !node_fs_1.default.statSync(summaryTarget.runtimePath).isFile()) {
        blockers.push((0, rendering_and_storage_1.finding)(`${findingPrefix}_IMPLEMENTATION_SUMMARY_MISSING`, 'error', implementationSummaryPath, `${levelTitle} task '${directoryTaskId}' is missing implementation-summary.md.`));
    }
    const taskText = taskTarget.exists && node_fs_1.default.statSync(taskTarget.runtimePath).isFile()
        ? node_fs_1.default.readFileSync(taskTarget.runtimePath, 'utf8')
        : '';
    const summaryText = summaryTarget.exists && node_fs_1.default.statSync(summaryTarget.runtimePath).isFile()
        ? node_fs_1.default.readFileSync(summaryTarget.runtimePath, 'utf8')
        : null;
    const taskPolicy = taskText === '' ? null : (0, artifact_policy_projection_1.projectArtifactPolicy)(taskText);
    const summaryPolicy = summaryText === null ? null : (0, artifact_policy_projection_1.projectArtifactPolicy)(summaryText);
    const lifecyclePair = taskText === '' || summaryText === null
        ? null
        : (0, task_lifecycle_1.projectTaskLifecyclePair)({ taskDefinition: taskText, implementationSummary: summaryText });
    if (taskPolicy !== null) {
        for (const issue of taskPolicy.blockingFindings) {
            blockers.push((0, rendering_and_storage_1.finding)(`${findingPrefix}_TASK_${issue.code.toUpperCase().replace(/-/g, '_')}`, 'error', taskDefinitionPath, issue.message));
        }
        if (taskPolicy.taskId !== directoryTaskId || taskPolicy.workflowLevel !== workflowLevel) {
            blockers.push((0, rendering_and_storage_1.finding)(`${findingPrefix}_TASK_IDENTITY_MISMATCH`, 'error', taskDefinitionPath, `Task directory '${directoryTaskId}' does not match a canonical ${levelTitle} task identity.`));
        }
        if (governedContext !== undefined) {
            const taskDocument = (0, planning_document_utils_1.parseMarkdownFrontMatter)(taskText);
            if ((0, planning_document_utils_1.readTopLevelField)(taskDocument.frontMatterLines, 'slice') !== governedContext.sliceId) {
                blockers.push((0, rendering_and_storage_1.finding)('GOVERNED_TASK_SLICE_MISMATCH', 'error', taskDefinitionPath, `Governed task '${directoryTaskId}' must belong to slice '${governedContext.sliceId}'.`));
            }
            for (const [parentKind, expectedPath] of Object.entries(governedContext.expectedParents)) {
                const actualPath = (0, rendering_and_storage_1.readNestedUpstream)(taskDocument.frontMatterLines, parentKind);
                if (actualPath !== expectedPath) {
                    blockers.push((0, rendering_and_storage_1.finding)('GOVERNED_TASK_PARENT_MISMATCH', 'error', taskDefinitionPath, `Governed task '${directoryTaskId}' must reference ${parentKind} '${expectedPath}', found '${actualPath ?? '(missing)'}'.`));
                }
            }
        }
    }
    if (summaryPolicy !== null) {
        for (const issue of summaryPolicy.blockingFindings) {
            blockers.push((0, rendering_and_storage_1.finding)(`${findingPrefix}_SUMMARY_${issue.code.toUpperCase().replace(/-/g, '_')}`, 'error', implementationSummaryPath, issue.message));
        }
        if (summaryPolicy.taskId !== directoryTaskId || summaryPolicy.workflowLevel !== workflowLevel) {
            blockers.push((0, rendering_and_storage_1.finding)(`${findingPrefix}_SUMMARY_IDENTITY_MISMATCH`, 'error', implementationSummaryPath, `Implementation summary identity does not match ${levelTitle} task '${directoryTaskId}'.`));
        }
        if (governedContext !== undefined && summaryText !== null) {
            const summaryDocument = (0, planning_document_utils_1.parseMarkdownFrontMatter)(summaryText);
            if ((0, planning_document_utils_1.readTopLevelField)(summaryDocument.frontMatterLines, 'slice') !== governedContext.sliceId) {
                blockers.push((0, rendering_and_storage_1.finding)('GOVERNED_SUMMARY_SLICE_MISMATCH', 'error', implementationSummaryPath, `Governed implementation summary '${directoryTaskId}' must belong to slice '${governedContext.sliceId}'.`));
            }
            for (const [parentKind, expectedPath] of Object.entries(governedContext.expectedParents)) {
                const actualPath = (0, rendering_and_storage_1.readNestedUpstream)(summaryDocument.frontMatterLines, parentKind);
                if (actualPath !== expectedPath) {
                    blockers.push((0, rendering_and_storage_1.finding)('GOVERNED_SUMMARY_PARENT_MISMATCH', 'error', implementationSummaryPath, `Governed implementation summary '${directoryTaskId}' must reference ${parentKind} '${expectedPath}', found '${actualPath ?? '(missing)'}'.`));
                }
            }
        }
    }
    if (lifecyclePair !== null) {
        for (const issue of lifecyclePair.blockingFindings) {
            blockers.push((0, rendering_and_storage_1.finding)(`${findingPrefix}_LIFECYCLE_${issue.code.toUpperCase().replace(/-/g, '_')}`, 'error', issue.artifact === 'implementation_summary' ? implementationSummaryPath : taskDefinitionPath, issue.message));
        }
    }
    const taskDocument = (0, planning_artifact_document_1.parsePlanningArtifactDocument)(taskText);
    const summaryDocument = summaryText === null ? null : (0, planning_artifact_document_1.parsePlanningArtifactDocument)(summaryText);
    const sequenceValue = taskDocument.frontMatterFields.sequence;
    const sequence = sequenceValue !== undefined && /^\d+$/.test(sequenceValue) ? Number.parseInt(sequenceValue, 10) : null;
    const dependencies = (0, rendering_and_storage_1.parseDependencies)(taskDocument.frontMatterLines);
    const validationEvidence = (0, rendering_and_storage_1.hasEvidence)(summaryDocument, 'Validation Performed');
    const acceptanceEvidence = (0, rendering_and_storage_1.hasEvidence)(summaryDocument, 'Acceptance Criteria Results');
    const status = lifecyclePair?.task.status ?? taskPolicy?.lifecycle.status ?? null;
    const readiness = lifecyclePair?.task.readiness ?? taskPolicy?.lifecycle.readiness ?? null;
    const implementationStatus = lifecyclePair?.implementationStatus ??
        lifecyclePair?.summary?.legacyImplementationStatus ??
        summaryPolicy?.lifecycle.implementationStatus ??
        null;
    const reviewDisposition = lifecyclePair?.reviewDisposition ??
        lifecyclePair?.summary?.legacyReviewDisposition ??
        summaryPolicy?.lifecycle.reviewDisposition ??
        null;
    return {
        taskId: taskPolicy?.taskId ?? directoryTaskId,
        sequence,
        taskDefinitionPath,
        implementationSummaryPath,
        taskDefinitionRevision: (0, rendering_and_storage_1.revision)(taskText),
        implementationSummaryRevision: summaryText === null ? null : (0, rendering_and_storage_1.revision)(summaryText),
        readiness,
        status,
        implementationStatus,
        reviewDisposition,
        evidenceProfile: taskPolicy?.evidenceProfile ?? null,
        agentMode: taskPolicy?.effectiveAgentMode ?? 'guided',
        dependencies,
        validationEvidence,
        acceptanceEvidence,
        blockers: (0, rendering_and_storage_1.sortFindings)(blockers),
        nextAction: blockers.length > 0
            ? 'repair_state'
            : (status === 'completed' || status === 'cancelled') &&
                implementationStatus === 'completed' &&
                (reviewDisposition === 'accepted' ||
                    reviewDisposition === 'accepted_with_follow_up' ||
                    reviewDisposition === 'cancelled')
                ? 'review_closeout'
                : readiness === 'ready_to_implement'
                    ? 'implement'
                    : 'refine_task',
    };
}
function parseOverview(text, overviewPath) {
    const document = (0, planning_document_utils_1.parseMarkdownFrontMatter)(text);
    const artifactType = (0, planning_document_utils_1.readTopLevelField)(document.frontMatterLines, 'artifact_type');
    const workflowLevel = (0, planning_document_utils_1.readTopLevelField)(document.frontMatterLines, 'workflow_level');
    const structured = artifactType === 'work_overview' && workflowLevel === 'structured';
    const governed = artifactType === 'slice_overview' && workflowLevel === 'governed';
    const ownerId = governed
        ? ((0, planning_document_utils_1.readTopLevelField)(document.frontMatterLines, 'slice') ?? (0, planning_document_utils_1.readTopLevelField)(document.frontMatterLines, 'id'))
        : (0, planning_document_utils_1.readTopLevelField)(document.frontMatterLines, 'id');
    const governedId = governed ? (0, planning_document_utils_1.readTopLevelField)(document.frontMatterLines, 'id') : null;
    if ((!structured && !governed) || !ownerId || (governed && governedId !== undefined && governedId !== ownerId)) {
        throw new contracts_and_aggregation_1.StructuredProjectReviewError('invalid-request', `Overview '${overviewPath}' must be a canonical Structured work_overview or Governed slice_overview with one stable owner id.`);
    }
    const specifications = parseOverviewSpecifications(document.frontMatterLines);
    if (specifications.length === 0) {
        throw new contracts_and_aggregation_1.StructuredProjectReviewError('invalid-request', `${(0, rendering_and_storage_1.titleLevel)(workflowLevel)} overview '${overviewPath}' has no canonical specification evidence.`);
    }
    return {
        ownerId,
        workflowLevel: workflowLevel,
        status: (0, planning_document_utils_1.readTopLevelField)(document.frontMatterLines, 'status') ?? null,
        specifications,
    };
}
function parseOverviewSpecifications(lines) {
    const entries = [];
    let current = null;
    for (const line of lines) {
        const id = line.match(/^\s{4}- id:\s*(.+)$/);
        if (id !== null) {
            if (current?.specId && current.specPath) {
                entries.push({
                    specId: current.specId,
                    specPath: current.specPath,
                    revision: current.revision ?? null,
                });
            }
            current = { specId: (0, rendering_and_storage_1.scalar)(id[1]) };
            continue;
        }
        const field = line.match(/^\s{6}(ref|revision):\s*(.+)$/);
        if (field !== null && current !== null) {
            if (field[1] === 'ref')
                current.specPath = (0, rendering_and_storage_1.scalar)(field[2]);
            else
                current.revision = (0, rendering_and_storage_1.scalar)(field[2]);
        }
    }
    if (current?.specId && current.specPath) {
        entries.push({
            specId: current.specId,
            specPath: current.specPath,
            revision: current.revision ?? null,
        });
    }
    return entries.sort((left, right) => left.specPath.localeCompare(right.specPath));
}
function aggregationPreconditions(repositoryRoot, aggregation, includeReviewDestination) {
    const paths = [
        (0, rendering_and_storage_1.aggregationOverviewPath)(aggregation),
        ...aggregation.specifications.map((entry) => entry.specPath),
        ...aggregation.hierarchyArtifacts.flatMap((entry) => (entry.artifactRevision === null ? [] : [entry.artifactPath])),
        ...aggregation.tasks.flatMap((entry) => [
            entry.taskDefinitionPath,
            ...(entry.implementationSummaryRevision === null ? [] : [entry.implementationSummaryPath]),
        ]),
        ...aggregation.reconciliations.flatMap((entry) => [
            ...(entry.reconciliationRevision === null ? [] : [entry.reconciliationPath]),
        ]),
    ];
    const preconditions = paths.map((entryPath) => (0, mutation_preconditions_1.captureContentRevisionPreconditionSync)((0, canonical_write_target_1.resolveCanonicalWriteTargetSync)(repositoryRoot, entryPath)));
    if (includeReviewDestination) {
        preconditions.push((0, mutation_preconditions_1.captureDestinationPresencePreconditionSync)((0, canonical_write_target_1.resolveCanonicalWriteTargetSync)(repositoryRoot, aggregation.projectReviewPath)));
    }
    return (0, rendering_and_storage_1.dedupePreconditions)(preconditions);
}
