"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.taskRuntimeAttributionRequired = taskRuntimeAttributionRequired;
exports.createTaskWorkspace = createTaskWorkspace;
exports.createLightweightTaskWorkspace = createLightweightTaskWorkspace;
const node_fs_1 = __importDefault(require("node:fs"));
const node_path_1 = __importDefault(require("node:path"));
const errors_1 = require("../errors");
const authoring_policy_1 = require("./authoring-policy");
const command_write_summary_1 = require("../license/command-write-summary");
const paths_1 = require("../paths");
const front_matter_utils_1 = require("./front-matter-utils");
const upstream_specs_1 = require("./upstream-specs");
const path_resolution_1 = require("../templates/path-resolution");
const workflow_provenance_1 = require("./workflow-provenance");
const planning_document_utils_1 = require("./planning-document-utils");
const runtime_acceptance_1 = require("./runtime-acceptance");
function taskRuntimeAttributionRequired(executionMode, runtimeAcceptance) {
    return runtimeAcceptance?.required === true && executionMode !== "contract";
}
function createTaskWorkspace(repositoryRoot, options) {
    const milestoneOverviewPath = resolveMilestoneOverviewPath(repositoryRoot, options.milestoneOverviewPath);
    if (!node_fs_1.default.existsSync(milestoneOverviewPath.absolute)) {
        throw (0, errors_1.createUsageError)(`Parent milestone overview not found at '${milestoneOverviewPath.relative}'.`, ["Run day-shift milestone new first or pass the correct --milestone-overview path."]);
    }
    const parsedMilestoneOverview = parseMilestoneOverview(milestoneOverviewPath.absolute);
    const milestoneOverviewText = node_fs_1.default.readFileSync(milestoneOverviewPath.absolute, "utf8");
    const declaredTaskSlugsForDecomposition = [...parsedMilestoneOverview.tasks.keys()];
    const decompositionIssues = (0, authoring_policy_1.auditParentDecomposition)({
        artifactPath: milestoneOverviewPath.relative,
        markdownText: milestoneOverviewText,
        childKind: "task",
        declaredChildSlugs: declaredTaskSlugsForDecomposition
    });
    if (decompositionIssues.length > 0) {
        throw (0, errors_1.createUsageError)(`Planning decomposition contract rejected '${milestoneOverviewPath.relative}' before task writes.`, (0, authoring_policy_1.formatParentDecompositionIssues)(decompositionIssues));
    }
    const upstreamSpecs = (0, upstream_specs_1.normalizeUpstreamSpecsToLocalSpecPaths)(repositoryRoot, parsedMilestoneOverview.upstreamSpecs);
    const taskSlug = resolveTaskSlug(options.taskSlug);
    if (!declaredTaskSlugsForDecomposition.includes(taskSlug)) {
        throw (0, errors_1.createUsageError)(`Task '${taskSlug}' is not declared by '${milestoneOverviewPath.relative}'.`, ["Declare the task and update the authored target count and decomposition rationale before scaffolding."]);
    }
    const taskTitle = resolveTaskTitle(taskSlug, options.taskTitle);
    const milestoneDirectoryPath = node_path_1.default.dirname(milestoneOverviewPath.absolute);
    const tasksDirectoryPath = node_path_1.default.join(milestoneDirectoryPath, "tasks");
    // Promotion reuses this same standard destination shape: tasks/<task-slug>/.
    const taskDirectoryPath = node_path_1.default.join(tasksDirectoryPath, taskSlug);
    const taskDefinitionPath = node_path_1.default.join(taskDirectoryPath, "task-definition.md");
    const implementationSummaryPath = node_path_1.default.join(taskDirectoryPath, "implementation-summary.md");
    const declaredTaskSlugs = [...parsedMilestoneOverview.tasks.keys()];
    const breakoutIssues = (0, runtime_acceptance_1.validateMilestoneRuntimeBreakout)(parsedMilestoneOverview.runtimeAcceptance, declaredTaskSlugs);
    if (breakoutIssues.length > 0) {
        throw (0, errors_1.createUsageError)(`Runtime acceptance contract rejected '${milestoneOverviewPath.relative}'.`, [...breakoutIssues]);
    }
    const executionMode = (0, runtime_acceptance_1.taskExecutionModeForRuntimeAcceptance)(parsedMilestoneOverview.runtimeAcceptance, taskSlug, declaredTaskSlugs);
    const childRuntimeAcceptance = parsedMilestoneOverview.runtimeAcceptance === null
        ? null
        : (0, runtime_acceptance_1.childRuntimeAcceptanceMetadata)(parsedMilestoneOverview.runtimeAcceptance);
    const taskDefinitionExistsBeforeWrite = node_fs_1.default.existsSync(taskDefinitionPath);
    const implementationSummaryExistsBeforeWrite = node_fs_1.default.existsSync(implementationSummaryPath);
    if (taskDefinitionExistsBeforeWrite && parsedMilestoneOverview.runtimeAcceptance !== null) {
        const existingText = node_fs_1.default.readFileSync(taskDefinitionPath, "utf8");
        const existingFrontMatter = extractFrontMatter(taskDefinitionPath, existingText);
        const existingInspection = (0, runtime_acceptance_1.inspectRuntimeAcceptance)({
            artifactPath: taskDefinitionPath,
            artifactKind: "task",
            frontMatterLines: existingFrontMatter.lines,
            markdownText: existingText,
            requireExplicitForExecutableEvidence: false
        });
        const existingExecutionMode = readTopLevelField(existingFrontMatter.lines, "execution_mode")?.trim() ?? null;
        const existingIssues = [
            ...existingInspection.issues,
            ...(0, runtime_acceptance_1.validateTaskRuntimeAcceptance)({
                parent: parsedMilestoneOverview.runtimeAcceptance,
                child: existingInspection.metadata,
                executionMode: existingExecutionMode,
                taskMarkdown: existingText
            })
        ];
        if (existingIssues.length > 0) {
            throw (0, errors_1.createUsageError)(`Runtime acceptance contract rejected '${(0, front_matter_utils_1.toRepositoryLikePath)(taskDefinitionPath)}'.`, existingIssues);
        }
    }
    const renderedTaskDefinition = taskDefinitionExistsBeforeWrite
        ? null
        : renderTaskDefinitionMarkdown({
            repositoryRoot,
            taskTitle,
            taskSlug,
            taskDescription: resolveTaskDescription(taskSlug, options.taskDescription, parsedMilestoneOverview.tasks),
            slice: parsedMilestoneOverview.slice,
            phase: parsedMilestoneOverview.phase,
            milestone: parsedMilestoneOverview.milestone,
            planningDepth: parsedMilestoneOverview.planningDepth,
            sliceOverviewPath: parsedMilestoneOverview.sliceOverviewPath,
            phaseOverviewPath: parsedMilestoneOverview.phaseOverviewPath,
            milestoneOverviewPath: milestoneOverviewPath.relative,
            upstreamSpecs,
            milestonePurpose: parsedMilestoneOverview.purpose,
            milestoneScope: parsedMilestoneOverview.scope,
            milestoneAcceptanceCriteria: parsedMilestoneOverview.acceptanceCriteria,
            milestoneDependencies: parsedMilestoneOverview.dependencies,
            milestoneRisks: parsedMilestoneOverview.risks,
            milestoneValidationFocus: parsedMilestoneOverview.validationFocus,
            executionMode,
            runtimeAcceptance: childRuntimeAcceptance,
            workflowCliCommand: options.workflowCliCommand
        });
    const renderedImplementationSummary = implementationSummaryExistsBeforeWrite
        ? null
        : renderImplementationSummaryMarkdown({
            repositoryRoot,
            taskTitle,
            taskSlug,
            slice: parsedMilestoneOverview.slice,
            phase: parsedMilestoneOverview.phase,
            milestone: parsedMilestoneOverview.milestone,
            planningDepth: parsedMilestoneOverview.planningDepth,
            sliceOverviewPath: parsedMilestoneOverview.sliceOverviewPath,
            phaseOverviewPath: parsedMilestoneOverview.phaseOverviewPath,
            milestoneOverviewPath: milestoneOverviewPath.relative,
            taskDefinitionPath: (0, front_matter_utils_1.toRepositoryLikePath)(node_path_1.default.relative(repositoryRoot, taskDefinitionPath)),
            upstreamSpecs,
            executionMode,
            runtimeAcceptance: childRuntimeAcceptance,
            workflowCliCommand: options.workflowCliCommand
        });
    const taskDefinitionExists = node_fs_1.default.existsSync(taskDefinitionPath);
    const implementationSummaryExists = node_fs_1.default.existsSync(implementationSummaryPath);
    const tasksDirectoryAction = node_fs_1.default.existsSync(tasksDirectoryPath) ? "kept" : "created";
    if (options.validateOnly !== true) {
        ensureDirectory(tasksDirectoryPath);
        node_fs_1.default.mkdirSync(taskDirectoryPath, { recursive: true });
        if (!taskDefinitionExists && renderedTaskDefinition !== null) {
            node_fs_1.default.writeFileSync(taskDefinitionPath, renderedTaskDefinition, "utf8");
        }
        if (!implementationSummaryExists && renderedImplementationSummary !== null) {
            node_fs_1.default.writeFileSync(implementationSummaryPath, renderedImplementationSummary, "utf8");
        }
    }
    const taskDefinitionRelativePath = (0, front_matter_utils_1.toRepositoryLikePath)(node_path_1.default.relative(repositoryRoot, taskDefinitionPath));
    const implementationSummaryRelativePath = (0, front_matter_utils_1.toRepositoryLikePath)(node_path_1.default.relative(repositoryRoot, implementationSummaryPath));
    return {
        repositoryRoot,
        slice: parsedMilestoneOverview.slice,
        phase: parsedMilestoneOverview.phase,
        milestone: parsedMilestoneOverview.milestone,
        planningDepth: parsedMilestoneOverview.planningDepth,
        milestoneOverviewPath: milestoneOverviewPath.relative,
        tasksDirectoryPath,
        taskDirectoryPath,
        taskDefinitionPath,
        implementationSummaryPath,
        taskSlug,
        taskTitle,
        tasksDirectoryAction,
        taskDefinitionAction: taskDefinitionExists ? "kept" : "created",
        implementationSummaryAction: implementationSummaryExists ? "kept" : "created",
        contributingSpecIds: upstreamSpecs.map((entry) => entry.id),
        commandWriteSummary: (0, command_write_summary_1.normalizeCommandWriteSummary)({
            commandFamily: "task_generation",
            primaryOutputArtifacts: [taskDefinitionRelativePath, implementationSummaryRelativePath],
            updatedArtifacts: [
                {
                    path: taskDefinitionRelativePath,
                    action: taskDefinitionExists ? "kept" : "created",
                    reason: taskDefinitionExists ? "no_write" : "accepted_create"
                },
                {
                    path: implementationSummaryRelativePath,
                    action: implementationSummaryExists ? "kept" : "created",
                    reason: implementationSummaryExists ? "no_write" : "accepted_create"
                }
            ]
        })
    };
}
function createLightweightTaskWorkspace(repositoryRoot, options) {
    const sliceOverviewPath = resolveOverviewPath(repositoryRoot, options.sliceOverviewPath, "--slice-overview");
    if (!node_fs_1.default.existsSync(sliceOverviewPath.absolute)) {
        throw (0, errors_1.createUsageError)(`Parent slice overview not found at '${sliceOverviewPath.relative}'.`, ["Run day-shift slice new first or pass the correct --slice-overview path."]);
    }
    const parsedSliceOverview = parseSliceOverview(sliceOverviewPath.absolute);
    const upstreamSpecs = (0, upstream_specs_1.normalizeUpstreamSpecsToLocalSpecPaths)(repositoryRoot, parsedSliceOverview.upstreamSpecs);
    if (parsedSliceOverview.planningDepth !== "lightweight") {
        throw (0, errors_1.createUsageError)(`Parent slice overview '${sliceOverviewPath.relative}' must use planning_depth: lightweight for --lightweight task creation.`);
    }
    const taskSlug = resolveTaskSlug(options.taskSlug);
    const taskTitle = resolveTaskTitle(taskSlug, options.taskTitle);
    const sliceDirectoryPath = node_path_1.default.dirname(sliceOverviewPath.absolute);
    const tasksDirectoryPath = node_path_1.default.join(sliceDirectoryPath, "tasks");
    const taskDirectoryPath = node_path_1.default.join(tasksDirectoryPath, taskSlug);
    const taskDefinitionPath = node_path_1.default.join(taskDirectoryPath, "task-definition.md");
    const implementationSummaryPath = node_path_1.default.join(taskDirectoryPath, "implementation-summary.md");
    const tasksDirectoryAction = ensureDirectory(tasksDirectoryPath);
    node_fs_1.default.mkdirSync(taskDirectoryPath, { recursive: true });
    const taskDefinitionExists = node_fs_1.default.existsSync(taskDefinitionPath);
    if (!taskDefinitionExists) {
        node_fs_1.default.writeFileSync(taskDefinitionPath, renderLightweightTaskDefinitionMarkdown({
            repositoryRoot,
            taskTitle,
            taskSlug,
            slice: parsedSliceOverview.slice,
            planningDepth: parsedSliceOverview.planningDepth,
            sliceOverviewPath: sliceOverviewPath.relative,
            upstreamSpecs
        }), "utf8");
    }
    const implementationSummaryExists = node_fs_1.default.existsSync(implementationSummaryPath);
    if (!implementationSummaryExists) {
        node_fs_1.default.writeFileSync(implementationSummaryPath, renderLightweightImplementationSummaryMarkdown({
            repositoryRoot,
            taskTitle,
            taskSlug,
            slice: parsedSliceOverview.slice,
            planningDepth: parsedSliceOverview.planningDepth,
            sliceOverviewPath: sliceOverviewPath.relative,
            taskDefinitionPath: (0, front_matter_utils_1.toRepositoryLikePath)(node_path_1.default.relative(repositoryRoot, taskDefinitionPath)),
            upstreamSpecs
        }), "utf8");
    }
    const taskDefinitionRelativePath = (0, front_matter_utils_1.toRepositoryLikePath)(node_path_1.default.relative(repositoryRoot, taskDefinitionPath));
    const implementationSummaryRelativePath = (0, front_matter_utils_1.toRepositoryLikePath)(node_path_1.default.relative(repositoryRoot, implementationSummaryPath));
    return {
        repositoryRoot,
        slice: parsedSliceOverview.slice,
        planningDepth: parsedSliceOverview.planningDepth,
        sliceOverviewPath: sliceOverviewPath.relative,
        tasksDirectoryPath,
        taskDirectoryPath,
        taskDefinitionPath,
        implementationSummaryPath,
        taskSlug,
        taskTitle,
        tasksDirectoryAction,
        taskDefinitionAction: taskDefinitionExists ? "kept" : "created",
        implementationSummaryAction: implementationSummaryExists ? "kept" : "created",
        contributingSpecIds: upstreamSpecs.map((entry) => entry.id),
        commandWriteSummary: (0, command_write_summary_1.normalizeCommandWriteSummary)({
            commandFamily: "task_generation",
            primaryOutputArtifacts: [taskDefinitionRelativePath, implementationSummaryRelativePath],
            updatedArtifacts: [
                {
                    path: taskDefinitionRelativePath,
                    action: taskDefinitionExists ? "kept" : "created",
                    reason: taskDefinitionExists ? "no_write" : "accepted_create"
                },
                {
                    path: implementationSummaryRelativePath,
                    action: implementationSummaryExists ? "kept" : "created",
                    reason: implementationSummaryExists ? "no_write" : "accepted_create"
                }
            ]
        })
    };
}
function resolveMilestoneOverviewPath(repositoryRoot, inputPath) {
    return resolveOverviewPath(repositoryRoot, inputPath, "--milestone-overview");
}
function resolveOverviewPath(repositoryRoot, inputPath, optionName) {
    try {
        if (optionName === "--milestone-overview") {
            return (0, paths_1.resolvePlanningOverviewInputPath)(repositoryRoot, {
                layer: "milestone",
                inputPath
            });
        }
        if (optionName === "--slice-overview") {
            return (0, paths_1.resolvePlanningOverviewInputPath)(repositoryRoot, {
                layer: "slice",
                inputPath
            });
        }
        const parsed = (0, paths_1.parseRepositoryRelativePath)(inputPath);
        return {
            relative: parsed.normalizedPath,
            absolute: node_path_1.default.join(repositoryRoot, parsed.normalizedPath)
        };
    }
    catch (error) {
        throw (0, errors_1.createUsageError)(`Invalid ${optionName} path '${inputPath}'.`, [error instanceof Error ? error.message : String(error)]);
    }
}
function resolveTaskSlug(rawTaskSlug) {
    if ((0, paths_1.isCanonicalSlug)(rawTaskSlug)) {
        return rawTaskSlug;
    }
    const normalized = (0, paths_1.normalizeCanonicalSlug)(rawTaskSlug);
    if (normalized.kind === "canonical-slug") {
        return normalized.normalizedSlug;
    }
    throw (0, errors_1.createUsageError)(`Invalid task slug '${rawTaskSlug}'.`, [normalized.reason.message]);
}
function resolveTaskTitle(taskSlug, requestedTitle) {
    const trimmed = requestedTitle?.trim();
    if (trimmed !== undefined && trimmed !== "") {
        return trimmed;
    }
    return (0, front_matter_utils_1.toTitleCase)(taskSlug);
}
function ensureDirectory(directoryPath) {
    if (node_fs_1.default.existsSync(directoryPath)) {
        return "kept";
    }
    node_fs_1.default.mkdirSync(directoryPath, { recursive: true });
    return "created";
}
function parseMilestoneOverview(milestoneOverviewPath) {
    const fileText = node_fs_1.default.readFileSync(milestoneOverviewPath, "utf8");
    const sections = extractMarkdownSections(fileText);
    const frontMatter = extractFrontMatter(milestoneOverviewPath, fileText);
    const artifactType = readTopLevelField(frontMatter.lines, "artifact_type");
    if (artifactType !== "milestone_overview") {
        throw (0, errors_1.createUsageError)(`Parent overview '${(0, front_matter_utils_1.toRepositoryLikePath)(milestoneOverviewPath)}' must use artifact_type: milestone_overview.`);
    }
    const slice = readTopLevelField(frontMatter.lines, "slice");
    const phase = readTopLevelField(frontMatter.lines, "phase");
    const milestone = readTopLevelField(frontMatter.lines, "milestone");
    if (slice === undefined || slice.trim() === "") {
        throw (0, errors_1.createUsageError)(`Parent overview '${(0, front_matter_utils_1.toRepositoryLikePath)(milestoneOverviewPath)}' is missing required top-level field 'slice'.`);
    }
    if (phase === undefined || phase.trim() === "") {
        throw (0, errors_1.createUsageError)(`Parent overview '${(0, front_matter_utils_1.toRepositoryLikePath)(milestoneOverviewPath)}' is missing required top-level field 'phase'.`);
    }
    if (milestone === undefined || milestone.trim() === "") {
        throw (0, errors_1.createUsageError)(`Parent overview '${(0, front_matter_utils_1.toRepositoryLikePath)(milestoneOverviewPath)}' is missing required top-level field 'milestone'.`);
    }
    const planningDepth = readTopLevelField(frontMatter.lines, "planning_depth")?.trim() || "standard";
    const sliceOverviewPath = readUpstreamField(frontMatter.lines, "slice_overview");
    const phaseOverviewPath = readUpstreamField(frontMatter.lines, "phase_overview");
    if (sliceOverviewPath === undefined || sliceOverviewPath.trim() === "") {
        throw (0, errors_1.createUsageError)(`Parent overview '${(0, front_matter_utils_1.toRepositoryLikePath)(milestoneOverviewPath)}' is missing required upstream field 'slice_overview'.`);
    }
    if (phaseOverviewPath === undefined || phaseOverviewPath.trim() === "") {
        throw (0, errors_1.createUsageError)(`Parent overview '${(0, front_matter_utils_1.toRepositoryLikePath)(milestoneOverviewPath)}' is missing required upstream field 'phase_overview'.`);
    }
    const upstreamSpecs = parseUpstreamSpecs(frontMatter.lines, milestoneOverviewPath);
    const runtimeAcceptance = (0, runtime_acceptance_1.assertRuntimeAcceptanceInspection)((0, runtime_acceptance_1.inspectRuntimeAcceptance)({
        artifactPath: milestoneOverviewPath,
        artifactKind: "milestone",
        frontMatterLines: frontMatter.lines,
        markdownText: fileText
    }));
    if (upstreamSpecs.length === 0) {
        throw (0, errors_1.createUsageError)(`Parent overview '${(0, front_matter_utils_1.toRepositoryLikePath)(milestoneOverviewPath)}' must include at least one upstream spec entry under upstream.specs.`);
    }
    return {
        slice: slice.trim(),
        phase: phase.trim(),
        milestone: milestone.trim(),
        planningDepth,
        sliceOverviewPath: sliceOverviewPath.trim(),
        phaseOverviewPath: phaseOverviewPath.trim(),
        upstreamSpecs,
        purpose: normalizeSectionText(sections.get("Purpose")),
        scope: sectionBullets(sections.get("Scope")),
        tasks: parseDeclaredTaskDescriptions(sections.get("Tasks") ?? []),
        acceptanceCriteria: sectionBullets(sections.get("Acceptance Criteria")),
        dependencies: sectionBullets(sections.get("Dependencies")),
        risks: sectionBullets(sections.get("Risks")),
        validationFocus: sectionBullets(sections.get("Validation Focus")),
        runtimeAcceptance
    };
}
function parseSliceOverview(sliceOverviewPath) {
    const fileText = node_fs_1.default.readFileSync(sliceOverviewPath, "utf8");
    const frontMatter = extractFrontMatter(sliceOverviewPath, fileText);
    const artifactType = readTopLevelField(frontMatter.lines, "artifact_type");
    if (artifactType !== "slice_overview") {
        throw (0, errors_1.createUsageError)(`Parent overview '${(0, front_matter_utils_1.toRepositoryLikePath)(sliceOverviewPath)}' must use artifact_type: slice_overview.`);
    }
    const slice = readTopLevelField(frontMatter.lines, "slice");
    if (slice === undefined || slice.trim() === "") {
        throw (0, errors_1.createUsageError)(`Parent overview '${(0, front_matter_utils_1.toRepositoryLikePath)(sliceOverviewPath)}' is missing required top-level field 'slice'.`);
    }
    const planningDepth = readTopLevelField(frontMatter.lines, "planning_depth")?.trim() || "standard";
    const upstreamSpecs = parseUpstreamSpecs(frontMatter.lines, sliceOverviewPath);
    if (upstreamSpecs.length === 0) {
        throw (0, errors_1.createUsageError)(`Parent overview '${(0, front_matter_utils_1.toRepositoryLikePath)(sliceOverviewPath)}' must include at least one upstream spec entry under upstream.specs.`);
    }
    return {
        slice: slice.trim(),
        planningDepth,
        upstreamSpecs
    };
}
function extractFrontMatter(filePath, text) {
    const lines = text.split(/\r?\n/);
    if (lines[0] !== "---") {
        throw (0, errors_1.createUsageError)(`Parent overview '${(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)(`Parent overview '${(0, front_matter_utils_1.toRepositoryLikePath)(filePath)}' has malformed YAML front matter.`);
    }
    return {
        lines: lines.slice(1, closingIndex)
    };
}
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 readUpstreamField(lines, key) {
    let inUpstream = false;
    for (const line of lines) {
        if (!inUpstream) {
            if (line.trim() === "upstream:") {
                inUpstream = true;
            }
            continue;
        }
        if (!/^\s/.test(line)) {
            break;
        }
        const match = line.match(/^\s{2}([A-Za-z0-9_]+):\s*(.*)$/);
        if (match !== null && match[1] === key) {
            return (0, front_matter_utils_1.parseScalar)(match[2]);
        }
    }
    return undefined;
}
function parseUpstreamSpecs(lines, filePath) {
    const entries = [];
    for (let index = 0; index < lines.length; index += 1) {
        const idMatch = lines[index].match(/^\s*-\s+id:\s*(.+)$/);
        if (idMatch === null) {
            continue;
        }
        const depthLine = lines[index + 1];
        const refLine = lines[index + 2];
        const sourceTypeLine = lines[index + 3];
        const depthMatch = depthLine?.match(/^\s+depth:\s*(.+)$/);
        const refMatch = refLine?.match(/^\s+ref:\s*(.+)$/);
        const sourceTypeMatch = sourceTypeLine?.match(/^\s+source_type:\s*(.+)$/);
        if (depthMatch === null || refMatch === null || sourceTypeMatch === null) {
            throw (0, errors_1.createUsageError)(`Parent overview '${(0, front_matter_utils_1.toRepositoryLikePath)(filePath)}' has malformed upstream.specs metadata near '${lines[index].trim()}'.`);
        }
        entries.push({
            id: (0, front_matter_utils_1.parseScalar)(idMatch[1]),
            depth: (0, front_matter_utils_1.parseScalar)(depthMatch[1]),
            ref: (0, front_matter_utils_1.parseScalar)(refMatch[1]),
            sourceType: (0, front_matter_utils_1.parseScalar)(sourceTypeMatch[1])
        });
        index += 3;
    }
    return entries;
}
function extractMarkdownSections(text) {
    const lines = text.split(/\r?\n/);
    const sections = new Map();
    let currentSection;
    for (const line of lines) {
        const headingMatch = line.match(/^##\s+(.+?)\s*$/);
        if (headingMatch !== null) {
            currentSection = headingMatch[1];
            sections.set(currentSection, []);
            continue;
        }
        if (line.startsWith("# ")) {
            currentSection = undefined;
            continue;
        }
        if (currentSection !== undefined) {
            sections.get(currentSection)?.push(line);
        }
    }
    return sections;
}
function normalizeSectionText(lines) {
    return (lines ?? [])
        .map((line) => line.trim())
        .filter((line) => line !== "")
        .join(" ");
}
function sectionBullets(lines) {
    return (lines ?? [])
        .map((line) => line.trim())
        .filter((line) => line.startsWith("- "))
        .map((line) => line.slice(2).trim())
        .filter((line) => line !== "");
}
function parseDeclaredTaskDescriptions(lines) {
    const descriptions = new Map();
    for (const line of lines) {
        const declaration = (0, planning_document_utils_1.parseDeclaredChildSlugBullet)(line);
        if (declaration !== null) {
            descriptions.set(declaration.slug, declaration.description);
        }
    }
    return descriptions;
}
function resolveTaskDescription(taskSlug, requestedDescription, taskDescriptions) {
    const trimmed = requestedDescription?.trim();
    if (trimmed !== undefined && trimmed !== "") {
        return trimmed;
    }
    return taskDescriptions.get(taskSlug) ?? "";
}
function renderTaskDefinitionMarkdown(options) {
    const templatePath = (0, path_resolution_1.resolveWorkspaceTemplateAbsolutePath)({
        repositoryRoot: options.repositoryRoot,
        templatePath: ".day-shift/templates/task-definition.md"
    });
    if (!node_fs_1.default.existsSync(templatePath)) {
        throw (0, errors_1.createUsageError)("Task definition template is missing.", ["Expected template at .day-shift/templates/task-definition.md"]);
    }
    const templateText = node_fs_1.default.readFileSync(templatePath, "utf8");
    return renderFromTemplate(templateText, {
        titleSuffix: "",
        taskTitle: options.taskTitle,
        taskSlug: options.taskSlug,
        slice: options.slice,
        phase: options.phase,
        milestone: options.milestone,
        planningDepth: options.planningDepth,
        sliceOverviewPath: options.sliceOverviewPath,
        phaseOverviewPath: options.phaseOverviewPath,
        milestoneOverviewPath: options.milestoneOverviewPath,
        taskDefinitionPath: "",
        upstreamSpecs: options.upstreamSpecs,
        executionMode: options.executionMode,
        runtimeAcceptance: options.runtimeAcceptance,
        workflowCliCommand: options.workflowCliCommand,
        replacements: buildStandardTaskReplacements(options)
    });
}
function renderImplementationSummaryMarkdown(options) {
    const templatePath = (0, path_resolution_1.resolveWorkspaceTemplateAbsolutePath)({
        repositoryRoot: options.repositoryRoot,
        templatePath: ".day-shift/templates/implementation-summary.md"
    });
    if (!node_fs_1.default.existsSync(templatePath)) {
        throw (0, errors_1.createUsageError)("Implementation summary template is missing.", ["Expected template at .day-shift/templates/implementation-summary.md"]);
    }
    const templateText = node_fs_1.default.readFileSync(templatePath, "utf8");
    return renderFromTemplate(templateText, {
        titleSuffix: " Implementation Summary",
        taskTitle: options.taskTitle,
        taskSlug: options.taskSlug,
        slice: options.slice,
        phase: options.phase,
        milestone: options.milestone,
        planningDepth: options.planningDepth,
        sliceOverviewPath: options.sliceOverviewPath,
        phaseOverviewPath: options.phaseOverviewPath,
        milestoneOverviewPath: options.milestoneOverviewPath,
        taskDefinitionPath: options.taskDefinitionPath,
        upstreamSpecs: options.upstreamSpecs,
        executionMode: options.executionMode,
        runtimeAcceptance: options.runtimeAcceptance,
        workflowCliCommand: options.workflowCliCommand
    });
}
function renderLightweightTaskDefinitionMarkdown(options) {
    const templatePath = (0, path_resolution_1.resolveWorkspaceTemplateAbsolutePath)({
        repositoryRoot: options.repositoryRoot,
        templatePath: ".day-shift/templates/lightweight-task-definition.md"
    });
    if (!node_fs_1.default.existsSync(templatePath)) {
        throw (0, errors_1.createUsageError)("Lightweight task definition template is missing.", ["Expected template at .day-shift/templates/lightweight-task-definition.md"]);
    }
    const templateText = node_fs_1.default.readFileSync(templatePath, "utf8");
    return renderFromTemplate(templateText, {
        titleSuffix: "",
        taskTitle: options.taskTitle,
        taskSlug: options.taskSlug,
        slice: options.slice,
        planningDepth: options.planningDepth,
        sliceOverviewPath: options.sliceOverviewPath,
        taskDefinitionPath: "",
        upstreamSpecs: options.upstreamSpecs,
        workflowCliCommand: `day-shift task new --lightweight --slice-overview ${options.sliceOverviewPath} --task-slug ${options.taskSlug}`
    });
}
function renderLightweightImplementationSummaryMarkdown(options) {
    const templatePath = (0, path_resolution_1.resolveWorkspaceTemplateAbsolutePath)({
        repositoryRoot: options.repositoryRoot,
        templatePath: ".day-shift/templates/lightweight-implementation-summary.md"
    });
    if (!node_fs_1.default.existsSync(templatePath)) {
        throw (0, errors_1.createUsageError)("Lightweight implementation summary template is missing.", ["Expected template at .day-shift/templates/lightweight-implementation-summary.md"]);
    }
    const templateText = node_fs_1.default.readFileSync(templatePath, "utf8");
    return renderFromTemplate(templateText, {
        titleSuffix: " Implementation Summary",
        taskTitle: options.taskTitle,
        taskSlug: options.taskSlug,
        slice: options.slice,
        planningDepth: options.planningDepth,
        sliceOverviewPath: options.sliceOverviewPath,
        taskDefinitionPath: options.taskDefinitionPath,
        upstreamSpecs: options.upstreamSpecs,
        workflowCliCommand: `day-shift task new --lightweight --slice-overview ${options.sliceOverviewPath} --task-slug ${options.taskSlug}`
    });
}
function renderFromTemplate(templateText, options) {
    try {
        return renderFromTemplateUnsafe(templateText, options);
    }
    catch (error) {
        if (error instanceof TypeError) {
            throw (0, errors_1.createInvalidConfigError)("Task artifact template metadata updates were rejected.", [error.message], [{
                    code: "TASK_METADATA_UPDATE_BLOCKED",
                    message: error.message,
                    severity: "error"
                }]);
        }
        throw error;
    }
}
function renderFromTemplateUnsafe(templateText, options) {
    const workflowProvenance = (0, workflow_provenance_1.buildCliWorkflowProvenance)(options.workflowCliCommand ?? `day-shift task new --milestone-overview ${options.milestoneOverviewPath} --task-slug ${options.taskSlug}`);
    const upstreamSpecsBlock = options.upstreamSpecs
        .map((entry) => {
        return [
            `    - id: ${entry.id}`,
            `      depth: ${entry.depth}`,
            `      ref: ${JSON.stringify(entry.ref)}`,
            `      source_type: ${JSON.stringify(entry.sourceType)}`
        ].join("\n");
    })
        .join("\n");
    let text = templateText;
    text = text.replace([
        "  specs:",
        "    - id: \"{{spec_id}}\"",
        "      depth: \"{{spec_depth}}\"",
        "      ref: \"{{spec_ref}}\"",
        "      source_type: \"{{source_type}}\""
    ].join("\n"), ["  specs:", upstreamSpecsBlock].join("\n"));
    const replacementMap = {
        "{{task_title}}": options.taskTitle,
        "{{execution_mode}}": options.executionMode ?? "runtime",
        "{{objective}}": "Pending. Document the specific implementation objective before starting work.",
        "{{upstream_context}}": "- Pending. Add upstream context references before implementation.",
        "{{target_paths}}": "- Pending. Add implementation target paths before implementation.",
        "{{current_behavior}}": "Pending. Describe current behavior before implementation.",
        "{{desired_behavior}}": "Pending. Describe desired behavior before implementation.",
        "{{runtime_delta}}": "Pending. Because execution_mode defaults to `runtime`, replace this section before implementation with runtime target files, expected behavior change, verification commands with expected evidence, and rollback path. Switch execution_mode to `contract` only for contract-only evidence work, or to `hybrid` when the task must carry both runtime implementation evidence and contract evidence to complete the milestone.",
        "{{acceptance_criteria}}": "- Pending. Add acceptance criteria before implementation.",
        "{{validation_commands}}": "```sh\n# Pending\n```",
        "{{rollback_recovery}}": "Pending. Describe rollback or recovery approach before implementation.",
        "{{risks}}": "- Pending. Capture implementation risks before execution.",
        "{{dependencies}}": "- Pending. Add repository-relative artifact dependency paths before implementation.",
        "{{constraints}}": "- Pending. Add scope constraints before implementation.",
        "{{assumptions}}": "- None currently. Add reviewable planning assumptions when they are needed.",
        "{{lifecycle_closure_expectations}}": "Pending. Specify closure evidence before implementation.",
        "{{open_questions}}": "- None currently.",
        "{{summary}}": "Pending. This implementation summary is initialized as the stable execution artifact for the task.",
        "{{changed_paths}}": "None yet. Populate this section when implementation begins and verify the intended task-scoped code changes landed.",
        "{{acceptance_criteria_results}}": "Pending review after implementation.",
        "{{validation_performed}}": "None yet. Record validation plus any changed-file inspection used to confirm the intended edits landed without obvious errors, missing edits, or unintended drift.",
        "{{scope_classification}}": "Not started. Expected scope is limited to this task's declared implementation seams.",
        "{{deviations}}": "None yet.",
        "{{risks_and_follow_ups}}": "Residual risk remains until executable behavior, changed-file verification, and validation evidence are recorded."
    };
    for (const [token, replacement] of Object.entries({
        ...replacementMap,
        ...(options.replacements ?? {})
    })) {
        text = text.split(token).join(replacement);
    }
    text = (0, front_matter_utils_1.applyNonArtifactFrontMatterFieldUpdates)(text, {
        workflow_provenance: workflowProvenance.workflowProvenance,
        workflow_cli_command: workflowProvenance.workflowCliCommand,
        workflow_manual_exception: ""
    }, {
        family: "template",
        allowedKeys: ["workflow_provenance", "workflow_cli_command", "workflow_manual_exception"],
        requiredKeys: ["workflow_provenance", "workflow_cli_command", "workflow_manual_exception"]
    });
    const transitionUpdates = {
        slice: options.slice,
        task: options.taskSlug,
        planning_depth: options.planningDepth,
        status: "draft"
    };
    if (options.phase !== undefined) {
        transitionUpdates.phase = options.phase;
    }
    if (options.milestone !== undefined) {
        transitionUpdates.milestone = options.milestone;
    }
    if (options.taskDefinitionPath === "") {
        transitionUpdates.readiness = "needs more evidence";
    }
    else {
        transitionUpdates.implementation_status = "pending";
    }
    text = (0, front_matter_utils_1.applyStatusAndPlanningFieldTransition)(text, transitionUpdates);
    const upstreamUpdates = {
        "upstream.slice_overview": options.sliceOverviewPath
    };
    const repositoryRelativePathKeys = [
        "upstream.slice_overview"
    ];
    if (options.phaseOverviewPath !== undefined) {
        upstreamUpdates["upstream.phase_overview"] = options.phaseOverviewPath;
        repositoryRelativePathKeys.push("upstream.phase_overview");
    }
    if (options.milestoneOverviewPath !== undefined) {
        upstreamUpdates["upstream.milestone_overview"] = options.milestoneOverviewPath;
        repositoryRelativePathKeys.push("upstream.milestone_overview");
    }
    if (options.taskDefinitionPath !== "") {
        upstreamUpdates["upstream.task_definition"] = options.taskDefinitionPath;
        repositoryRelativePathKeys.push("upstream.task_definition");
    }
    text = (0, front_matter_utils_1.applyPlanningFrontMatterFieldUpdates)(text, upstreamUpdates, {
        repositoryRelativePathKeys
    });
    text = (0, runtime_acceptance_1.injectRuntimeAcceptanceFrontMatter)(text, options.runtimeAcceptance ?? null);
    const executionMode = options.executionMode ?? "runtime";
    const runtimeAttributionRequired = taskRuntimeAttributionRequired(executionMode, options.runtimeAcceptance ?? null);
    text = injectRuntimeAttributionRequiredFrontMatter(text, runtimeAttributionRequired);
    assertPlanningAuthoringCompliance(options.taskDefinitionPath === "" ? "task_definition" : "implementation_summary", text);
    return text.replace("# " + options.taskTitle + options.titleSuffix + options.titleSuffix, "# " + options.taskTitle + options.titleSuffix);
}
function buildStandardTaskReplacements(options) {
    if (!hasConcreteTaskEvidence(options)) {
        return {};
    }
    const validationCommands = concreteValidationCommands(options.milestoneValidationFocus);
    return {
        "{{objective}}": options.taskDescription === ""
            ? `Implement the \`${options.taskSlug}\` task within the parent milestone contract.`
            : sentenceCase(options.taskDescription),
        "{{upstream_context}}": list([
            options.milestoneOverviewPath,
            options.phaseOverviewPath,
            options.sliceOverviewPath,
            ...options.upstreamSpecs.map((entry) => entry.ref),
            options.milestonePurpose === "" ? undefined : `Parent milestone purpose: ${options.milestonePurpose}`
        ]),
        "{{target_paths}}": list(inferTargetPathGuidance(options)),
        "{{current_behavior}}": "Generated task definitions currently require manual completion before implementation can begin when scaffolded from placeholder-heavy templates.",
        "{{desired_behavior}}": options.taskDescription === ""
            ? "Generated task definitions should carry enough parent-derived evidence to support readiness review when the parent milestone contract is concrete."
            : `Generated task definitions should support this declared task behavior: ${options.taskDescription}`,
        ...(options.executionMode === "contract"
            ? {
                "{{runtime_delta}}": "Not applicable. This contract prerequisite carries inherited acceptance IDs and frozen contract evidence only."
            }
            : {}),
        "{{acceptance_criteria}}": listOrPending([
            options.taskDescription === "" ? undefined : `The task satisfies the declared outcome: ${options.taskDescription}`,
            ...options.milestoneAcceptanceCriteria.slice(0, 5).map((criterion) => `Parent milestone criterion addressed where in scope: ${criterion}`)
        ]),
        "{{validation_commands}}": validationCommands.length === 0
            ? "```sh\n# Pending: parent milestone did not declare concrete validation commands\n```"
            : ["```sh", ...validationCommands, "```"].join("\n"),
        "{{rollback_recovery}}": "Revert changes in the task target paths and rerun the task validation commands.",
        "{{risks}}": listOrPending(options.milestoneRisks.slice(0, 4).map((risk) => `Parent milestone risk to manage: ${risk}`)),
        "{{dependencies}}": listOrPending([
            options.milestoneOverviewPath,
            ...options.milestoneDependencies.slice(0, 5)
        ]),
        "{{constraints}}": listOrPending([
            ...options.milestoneScope.slice(0, 4).map((scopeItem) => `Stay within parent milestone scope: ${scopeItem}`),
            "Keep implementation changes inside declared task target paths unless a justified deviation is recorded."
        ]),
        "{{lifecycle_closure_expectations}}": "Complete the paired implementation summary with changed paths, validation evidence, acceptance results, deviations, and follow-up work before milestone reconciliation.",
        "{{open_questions}}": "- None currently."
    };
}
function hasConcreteTaskEvidence(options) {
    return options.taskDescription !== "" ||
        options.milestoneAcceptanceCriteria.length > 0 ||
        options.milestoneValidationFocus.length > 0 ||
        options.milestoneDependencies.length > 0 ||
        options.milestoneScope.length > 0;
}
function inferTargetPathGuidance(options) {
    const lowerEvidence = `${options.taskSlug} ${options.taskDescription}`.toLowerCase();
    const paths = [];
    if (lowerEvidence.includes("task") || lowerEvidence.includes("scaffold")) {
        paths.push("src/lib/planning/task-generation.ts");
    }
    if (lowerEvidence.includes("full-set") || lowerEvidence.includes("declared")) {
        paths.push("src/lib/planning/full-set-expansion.ts");
    }
    if (lowerEvidence.includes("test") || lowerEvidence.includes("cover") || lowerEvidence.includes("regression")) {
        paths.push("tests_v2/cli/planning/creation.test.js");
    }
    if (paths.length === 0) {
        paths.push("Implementation target paths should be confirmed from the parent milestone evidence before execution.");
    }
    return paths;
}
function concreteValidationCommands(validationFocus) {
    return validationFocus
        .map((item) => item.replace(/^`|`$/g, "").trim())
        .filter((item) => item !== "" && !item.startsWith("Use parent "))
        .filter((item) => /^(pnpm|node|npm|npx|yarn|bun|cargo|go|python|pytest|tsc)\b/.test(item));
}
function sentenceCase(value) {
    if (value === "") {
        return value;
    }
    return `${value[0].toUpperCase()}${value.slice(1)}`;
}
function list(items) {
    return listOrPending(items, ["Evidence is intentionally incomplete; refine this task before implementation."]);
}
function listOrPending(items, fallback = ["Pending. Add concrete evidence before implementation."]) {
    const normalized = items
        .map((item) => item?.trim() ?? "")
        .filter((item, index, allItems) => item !== "" && allItems.indexOf(item) === index);
    return (normalized.length === 0 ? fallback : normalized).map((item) => `- ${item}`).join("\n");
}
function assertPlanningAuthoringCompliance(artifactType, markdownText) {
    const issues = (0, authoring_policy_1.auditPlanningArtifactAuthoring)({
        artifactPath: `generated ${artifactType}`,
        artifactType,
        markdownText
    });
    if (issues.length > 0) {
        throw (0, errors_1.createUsageError)(`Planning authoring policy rejected generated ${artifactType} scaffold text.`, (0, authoring_policy_1.formatPlanningAuthoringIssues)(issues));
    }
}
function injectRuntimeAttributionRequiredFrontMatter(markdownText, required) {
    const lines = markdownText.split(/\r?\n/);
    const closingIndex = lines.findIndex((line, index) => index > 0 && line === "---");
    if (lines[0] !== "---" || closingIndex === -1) {
        throw new TypeError("Task artifact is missing valid YAML front matter.");
    }
    const existingIndex = lines.findIndex((line, index) => {
        return index > 0 && index < closingIndex && line.startsWith("runtime_attribution_required:");
    });
    if (existingIndex !== -1) {
        lines[existingIndex] = `runtime_attribution_required: ${required ? "true" : "false"}`;
        return lines.join("\n");
    }
    const executionModeIndex = lines.findIndex((line, index) => {
        return index > 0 && index < closingIndex && line.startsWith("execution_mode:");
    });
    const insertionIndex = executionModeIndex === -1 ? closingIndex : executionModeIndex + 1;
    lines.splice(insertionIndex, 0, `runtime_attribution_required: ${required ? "true" : "false"}`);
    return lines.join("\n");
}
