"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.suggestPlanningNextAction = suggestPlanningNextAction;
exports.projectGovernedTerminalWorkEvidence = projectGovernedTerminalWorkEvidence;
exports.routeTaskNextAction = routeTaskNextAction;
const node_path_1 = __importDefault(require("node:path"));
const cli_constants_1 = require("../../config/cli-constants");
const config_contract_1 = require("../../config/config-contract");
const cli_invocation_1 = require("../../runtime/cli-invocation");
const work_review_1 = require("../../work-review");
const artifact_policy_projection_1 = require("../artifact-policy-projection");
const next_action_resolver_1 = require("../next-action-resolver");
const task_contract_revision_adoption_1 = require("../task-contract-revision-adoption");
const task_contract_revision_recovery_1 = require("../task-contract-revision-recovery");
const work_discovery_1 = require("../work-discovery");
const artifact_discovery_1 = require("./artifact-discovery");
const document_support_1 = require("./document-support");
const gap_analysis_1 = require("./gap-analysis");
function suggestPlanningNextAction(options) {
    const scope = (0, artifact_discovery_1.resolveScope)(options.repositoryRoot, options.artifactPath, false);
    const record = (0, artifact_discovery_1.readArtifactRecord)(options.repositoryRoot, scope.path);
    const resolvedConfig = (0, config_contract_1.resolveDayShiftConfig)({
        repositoryContext: { root: options.repositoryRoot, detectionSource: "explicit", warnedAboutFallback: false }
    });
    switch (record.artifactType) {
        case "work_overview":
            return {
                artifactPath: record.path,
                artifactType: record.artifactType,
                recommendation: "Inspect declared canonical children.",
                reason: "Canonical work overviews are non-actionable parent records and cannot be selected as implementation work.",
                command: cliCommand(`planning inventory --root ${node_path_1.default.posix.dirname(record.path)}`),
                workflowPath: cli_constants_1.CLI_SOURCE_SPEC_PLANNING_WORKFLOW,
                promptPath: null,
                promptResolution: null
            };
        case "task_definition": {
            const workEvidence = (0, work_discovery_1.projectCanonicalWorkCandidate)({
                repositoryRoot: options.repositoryRoot,
                artifactPath: record.path
            });
            const nextAction = workEvidence?.nextAction ?? null;
            const topologyEvidence = (0, artifact_discovery_1.projectPlanningTopologyEvidence)(record);
            const route = routeTaskNextAction(options.repositoryRoot, record.path, nextAction, topologyEvidence, workEvidence);
            const promptResolution = (0, artifact_discovery_1.resolveRequiredPromptReference)(options.repositoryRoot, resolvedConfig.values, route.promptPath);
            return {
                artifactPath: record.path,
                artifactType: record.artifactType,
                recommendation: route.recommendation,
                reason: route.reason,
                command: route.command,
                workflowPath: route.workflowPath,
                promptPath: promptResolution.resolvedPromptPath,
                promptResolution,
                workEvidence,
                nextAction,
                optionalReviewCommand: route.optionalReviewCommand,
                topologyEvidence
            };
        }
        case "milestone_overview": {
            const reconciliationPath = (0, document_support_1.pairedReconciliationPath)(record.path);
            const reconciliationRecord = (0, artifact_discovery_1.readArtifactIfExists)(options.repositoryRoot, reconciliationPath);
            const allTaskSummariesComplete = (0, gap_analysis_1.areAllTaskImplementationSummariesComplete)(options.repositoryRoot, record.path);
            if (!allTaskSummariesComplete) {
                const declaredTasks = (0, document_support_1.readDeclaredChildSlugsFromDocument)(record.document, "Tasks");
                const firstTaskSlug = declaredTasks[0] ?? null;
                const promptResolution = (0, artifact_discovery_1.resolveRequiredPromptReference)(options.repositoryRoot, resolvedConfig.values, ".day-shift/prompts/user/task.next.md");
                return {
                    artifactPath: record.path,
                    artifactType: record.artifactType,
                    recommendation: "Advance the next task beneath this milestone.",
                    reason: "Milestone reconciliation is premature until all task implementation summaries are complete.",
                    command: firstTaskSlug === null
                        ? null
                        : cliCommand(`planning gap-report --scope ${record.path}`),
                    workflowPath: ".day-shift/workflows/03-implement-from-task.md",
                    promptPath: promptResolution.resolvedPromptPath,
                    promptResolution
                };
            }
            if (reconciliationRecord === null) {
                const promptResolution = (0, artifact_discovery_1.resolveRequiredPromptReference)(options.repositoryRoot, resolvedConfig.values, ".day-shift/prompts/user/reconciliation.build.md");
                return {
                    artifactPath: record.path,
                    artifactType: record.artifactType,
                    recommendation: "Build the paired milestone reconciliation.",
                    reason: "All task execution summaries are complete, but the default milestone reconciliation artifact is still missing.",
                    command: cliCommand(`reconciliation build --milestone-overview ${record.path}`),
                    workflowPath: ".day-shift/workflows/04-summarize-and-reconcile.md",
                    promptPath: promptResolution.resolvedPromptPath,
                    promptResolution
                };
            }
            if (!(0, document_support_1.isCompletedReconciliation)(reconciliationRecord)) {
                const promptResolution = (0, artifact_discovery_1.resolveRequiredPromptReference)(options.repositoryRoot, resolvedConfig.values, ".day-shift/prompts/user/reconciliation.build.md");
                return {
                    artifactPath: record.path,
                    artifactType: record.artifactType,
                    recommendation: "Refresh and complete milestone reconciliation evidence.",
                    reason: "The paired milestone reconciliation exists but still carries placeholder or incomplete review state.",
                    command: cliCommand(`reconciliation build --milestone-overview ${record.path}`),
                    workflowPath: ".day-shift/workflows/04-summarize-and-reconcile.md",
                    promptPath: promptResolution.resolvedPromptPath,
                    promptResolution
                };
            }
            const promptResolution = (0, artifact_discovery_1.resolveRequiredPromptReference)(options.repositoryRoot, resolvedConfig.values, ".day-shift/prompts/user/milestone.review.md");
            return {
                artifactPath: record.path,
                artifactType: record.artifactType,
                recommendation: "Review milestone closure evidence.",
                reason: "The milestone already has reconciliation evidence, so the next safe step is a read-only milestone review.",
                command: cliCommand(`milestone review --milestone-overview ${record.path}`),
                workflowPath: ".day-shift/workflows/04-summarize-and-reconcile.md",
                promptPath: promptResolution.resolvedPromptPath,
                promptResolution
            };
        }
        case "implementation_summary": {
            const topologyEvidence = (0, artifact_discovery_1.projectPlanningTopologyEvidence)(record);
            const taskTarget = (0, artifact_discovery_1.inspectTaskCommandArtifactTarget)(options.repositoryRoot, record.upstreamTaskDefinitionPath);
            const promptResolution = (0, artifact_discovery_1.resolveRequiredPromptReference)(options.repositoryRoot, resolvedConfig.values, (0, document_support_1.isCompletedImplementationSummary)(record)
                ? ".day-shift/prompts/user/implementation.review.md"
                : ".day-shift/prompts/user/implementation.build.md");
            if (topologyEvidence.workflowTopology === null) {
                return {
                    artifactPath: record.path,
                    artifactType: record.artifactType,
                    recommendation: "Repair invalid workflow topology before selecting a closeout route.",
                    reason: "Typed topology findings block review-boundary and reconciliation inference.",
                    command: taskTarget.callable
                        ? cliCommand(`implementation-summary review --task-definition ${taskTarget.normalizedPath}`)
                        : null,
                    workflowPath: ".day-shift/workflows/04-summarize-and-reconcile.md",
                    promptPath: promptResolution.resolvedPromptPath,
                    promptResolution,
                    optionalReviewCommand: null,
                    topologyEvidence
                };
            }
            const requiresReconciliation = topologyEvidence.reconciliationRequired === true;
            return {
                artifactPath: record.path,
                artifactType: record.artifactType,
                recommendation: (0, document_support_1.isCompletedImplementationSummary)(record)
                    ? requiresReconciliation
                        ? "Review implementation evidence before milestone rollup."
                        : "Review implementation evidence at the direct summary boundary."
                    : "Complete the task execution summary.",
                reason: (0, document_support_1.isCompletedImplementationSummary)(record)
                    ? requiresReconciliation
                        ? "The paired execution artifact is complete enough for read-only review and downstream reconciliation."
                        : `The paired execution artifact is complete at the ${topologyEvidence.taskSummaryReviewBoundary} boundary; no reconciliation artifact applies.`
                    : "The summary still lacks completed execution evidence, so milestone-level review would be premature.",
                command: taskTarget.callable
                    ? cliCommand(`implementation-summary review --task-definition ${taskTarget.normalizedPath}`)
                    : null,
                workflowPath: ".day-shift/workflows/04-summarize-and-reconcile.md",
                promptPath: promptResolution.resolvedPromptPath,
                promptResolution,
                optionalReviewCommand: null,
                topologyEvidence
            };
        }
        case "reconciliation": {
            const promptResolution = (0, artifact_discovery_1.resolveRequiredPromptReference)(options.repositoryRoot, resolvedConfig.values, (0, document_support_1.isCompletedReconciliation)(record)
                ? ".day-shift/prompts/user/reconciliation.review.md"
                : ".day-shift/prompts/user/reconciliation.build.md");
            return {
                artifactPath: record.path,
                artifactType: record.artifactType,
                recommendation: (0, document_support_1.isCompletedReconciliation)(record)
                    ? "Review reconciliation closure evidence."
                    : "Complete the milestone reconciliation.",
                reason: (0, document_support_1.isCompletedReconciliation)(record)
                    ? "The artifact is already in completed review state, so the next safe step is read-only closure validation."
                    : "The review artifact still carries incomplete state and should be finished before closure metadata is advanced.",
                command: record.upstreamMilestoneOverviewPath === null
                    ? null
                    : cliCommand(`reconciliation review --milestone-overview ${record.upstreamMilestoneOverviewPath}`),
                workflowPath: ".day-shift/workflows/04-summarize-and-reconcile.md",
                promptPath: promptResolution.resolvedPromptPath,
                promptResolution
            };
        }
        case "phase_overview": {
            const scaffoldRefinementFindings = (0, document_support_1.phaseScaffoldRefinementFindings)(options.repositoryRoot, record);
            if (scaffoldRefinementFindings.length > 0) {
                const promptResolution = (0, artifact_discovery_1.resolveRequiredPromptReference)(options.repositoryRoot, resolvedConfig.values, ".day-shift/prompts/user/phase.next.md");
                return {
                    artifactPath: record.path,
                    artifactType: record.artifactType,
                    recommendation: "Refine the selected phase contract before milestone creation.",
                    reason: `The phase has ${scaffoldRefinementFindings.length} blocking child-scaffold evidence finding${scaffoldRefinementFindings.length === 1 ? "" : "s"} across its declared milestones.`,
                    command: null,
                    workflowPath: cli_constants_1.CLI_SOURCE_SPEC_PLANNING_WORKFLOW,
                    promptPath: promptResolution.resolvedPromptPath,
                    promptResolution,
                    scaffoldRefinementFindings
                };
            }
            const phaseReadyForReview = (0, gap_analysis_1.areAllDeclaredMilestonesReconciled)(options.repositoryRoot, record);
            const promptResolution = (0, artifact_discovery_1.resolveRequiredPromptReference)(options.repositoryRoot, resolvedConfig.values, phaseReadyForReview
                ? ".day-shift/prompts/user/phase.review.md"
                : ".day-shift/prompts/user/phase.next.md");
            return {
                artifactPath: record.path,
                artifactType: record.artifactType,
                recommendation: phaseReadyForReview
                    ? "Review phase closure evidence."
                    : "Inspect milestone coverage beneath this phase.",
                reason: phaseReadyForReview
                    ? "Every declared milestone has completed reconciliation evidence; downstream evidence takes precedence over stale phase status for selecting the read-only review boundary."
                    : "The phase still has declared milestone work without completed reconciliation evidence.",
                command: phaseReadyForReview
                    ? cliCommand(`phase review --phase-overview ${record.path}`)
                    : cliCommand(`planning inventory --root ${node_path_1.default.posix.dirname(record.path)}`),
                workflowPath: phaseReadyForReview
                    ? ".day-shift/workflows/04-summarize-and-reconcile.md"
                    : cli_constants_1.CLI_SOURCE_SPEC_PLANNING_WORKFLOW,
                promptPath: promptResolution.resolvedPromptPath,
                promptResolution
            };
        }
        case "slice_overview": {
            const workEvidence = projectGovernedTerminalWorkEvidence(options.repositoryRoot, record);
            if (workEvidence !== null) {
                return {
                    artifactPath: record.path,
                    artifactType: record.artifactType,
                    recommendation: "No required Governed work action remains.",
                    reason: "The completed Governed slice has current accepted project-review evidence and clean terminal descendants.",
                    command: null,
                    workflowPath: null,
                    promptPath: null,
                    promptResolution: null,
                    workEvidence,
                    nextAction: workEvidence.nextAction,
                    optionalReviewCommand: null
                };
            }
            const promptResolution = (0, artifact_discovery_1.resolveRequiredPromptReference)(options.repositoryRoot, resolvedConfig.values, ".day-shift/prompts/user/slice.next.md");
            return {
                artifactPath: record.path,
                artifactType: record.artifactType,
                recommendation: "Inspect phase coverage beneath this slice.",
                reason: "Slice overviews stay on the planning boundary until a downstream phase, milestone, and task are selected.",
                command: cliCommand(`planning inventory --root ${node_path_1.default.posix.dirname(record.path)}`),
                workflowPath: cli_constants_1.CLI_SOURCE_SPEC_PLANNING_WORKFLOW,
                promptPath: promptResolution.resolvedPromptPath,
                promptResolution
            };
        }
        default:
            return (0, document_support_1.assertNever)(record.artifactType);
    }
}
function projectGovernedTerminalWorkEvidence(repositoryRoot, record) {
    if (record.artifactType !== "slice_overview" || record.status !== "completed") {
        return null;
    }
    try {
        const review = (0, work_review_1.inspectProjectTerminalStateSync)({
            repositoryRoot,
            overviewPath: record.path
        });
        if (!review.terminal || review.disposition !== "accepted")
            return null;
        const policy = (0, artifact_policy_projection_1.projectArtifactPolicy)(record.document.rawText);
        return {
            artifactPath: record.path,
            workflowLevel: "governed",
            effectiveAgentMode: policy.effectiveAgentMode,
            evidenceProfile: policy.evidenceProfile ?? "runtime",
            evidenceState: "completed",
            status: "completed",
            blockers: [],
            nextAction: (0, next_action_resolver_1.resolveNextAction)({ taskStatus: "completed" }),
            projectReviewPath: review.projectReviewPath,
            projectReviewDisposition: "accepted"
        };
    }
    catch {
        return null;
    }
}
function routeTaskNextAction(repositoryRoot, taskPath, result, topologyEvidence, workEvidence) {
    const implementationRoute = {
        workflowPath: ".day-shift/workflows/03-implement-from-task.md",
        promptPath: ".day-shift/prompts/user/task.next.md"
    };
    const closeoutRoute = {
        workflowPath: ".day-shift/workflows/04-summarize-and-reconcile.md",
        promptPath: ".day-shift/prompts/user/implementation.review.md"
    };
    if (topologyEvidence.workflowTopology === null) {
        return {
            ...closeoutRoute,
            recommendation: "Repair invalid workflow topology before selecting a next action.",
            reason: "Typed topology findings block review-boundary and reconciliation inference.",
            command: cliCommand(`task review --task-definition ${taskPath}`),
            optionalReviewCommand: null
        };
    }
    if (result === null) {
        return {
            ...implementationRoute,
            recommendation: "Resolve paired lifecycle evidence before implementation.",
            reason: "Canonical next-action evidence is unavailable.",
            command: cliCommand(`task readiness-review --task-definition ${taskPath}`),
            optionalReviewCommand: null
        };
    }
    const reason = `Canonical resolver selected '${result.nextAction}' (${result.reasonCode}).`;
    switch (result.nextAction) {
        case "recover_contract_revision": {
            const attemptId = workEvidence?.lifecycle.currentAttemptId ?? null;
            const taskRevision = workEvidence?.lifecycle.taskRevision ?? null;
            const candidates = (0, task_contract_revision_recovery_1.discoverTaskContractRevisionRecoverySync)(repositoryRoot, taskPath);
            const candidate = candidates.length === 1 ? candidates[0] : null;
            const adoptionCandidates = candidate === null
                ? (0, task_contract_revision_adoption_1.discoverTaskContractRevisionAdoptionSync)(repositoryRoot, taskPath)
                : [];
            const adoption = adoptionCandidates.length === 1 ? adoptionCandidates[0] : null;
            const recordedAt = new Date().toISOString();
            const command = attemptId === null || taskRevision === null
                ? null
                : candidate !== null
                    ? [
                        cliCommand("task attempt-contract-revise"),
                        `--revision-run-directory ${candidate.runDirectory}`,
                        `--task-definition ${taskPath}`,
                        `--attempt-id ${attemptId}`,
                        `--task-revision ${taskRevision}`,
                        `--checkpoint-id ${candidate.checkpointId}`,
                        "--recorded-by day-shift-navigation",
                        `--recorded-at ${recordedAt}`,
                        "--reason \"Preserve evidence after the accepted task contract revision.\"",
                        "--dry-run",
                    ].join(" ")
                    : adoption === null
                        ? null
                        : [
                            cliCommand("resume run revise-contract"),
                            `--run-directory ${adoption.runDirectory}`,
                            `--review-result ${adoption.sourceEvidencePath}`,
                            `--active-artifact ${taskPath}`,
                            "--recorded-by day-shift-navigation",
                            `--recorded-at ${recordedAt}`,
                            "--reason \"Adopt verified predecessor readiness evidence into the replacement strict run.\"",
                            "--rollback-gate task-readiness",
                            "--dry-run",
                        ].join(" ");
            return {
                ...implementationRoute,
                recommendation: candidate !== null
                    ? "Preserve the evidence-bearing predecessor through the accepted contract-revision checkpoint before refreshing readiness."
                    : adoption !== null
                        ? "Adopt the verified predecessor readiness lineage into the replacement strict run before preserving the evidence-bearing attempt."
                        : "A contract-revision checkpoint or verified replacement-run adoption is required before preserving the evidence-bearing attempt.",
                reason,
                command,
                optionalReviewCommand: null,
            };
        }
        case "supersede_attempt": {
            const attemptId = workEvidence?.lifecycle.currentAttemptId ?? null;
            const taskRevision = workEvidence?.lifecycle.taskRevision ?? null;
            const recordedAt = new Date().toISOString();
            const command = attemptId === null || taskRevision === null
                ? null
                : [
                    cliCommand("task attempt-supersede"),
                    `--task-definition ${taskPath}`,
                    `--attempt-id ${attemptId}`,
                    `--task-revision ${taskRevision}`,
                    "--recorded-by day-shift-navigation",
                    `--recorded-at ${recordedAt}`,
                    "--reason \"Authorized planning-contract revision after a pre-write runtime baseline.\"",
                    "--dry-run"
                ].join(" ");
            return {
                ...implementationRoute,
                recommendation: "Supersede the baseline-only predecessor before refreshing readiness authorization.",
                reason,
                command,
                optionalReviewCommand: null
            };
        }
        case "implement":
            return {
                ...implementationRoute,
                recommendation: "Implement the task using the task handoff workflow.",
                reason,
                command: null,
                optionalReviewCommand: null
            };
        case "revise":
            return {
                ...implementationRoute,
                recommendation: "Revise the current task implementation attempt.",
                reason,
                command: null,
                optionalReviewCommand: null
            };
        case "review":
            return {
                ...closeoutRoute,
                recommendation: "Review task closeout evidence.",
                reason,
                command: cliCommand(`task review --task-definition ${taskPath}`),
                optionalReviewCommand: null
            };
        case "close":
            return {
                ...closeoutRoute,
                recommendation: "Close the accepted task explicitly.",
                reason,
                command: cliCommand(`task close --task-definition ${taskPath}`),
                optionalReviewCommand: null
            };
        case "none":
            return {
                ...closeoutRoute,
                recommendation: result.reasonCode === "terminal_state"
                    ? "No required task lifecycle action remains."
                    : "No evidence-backed task action is currently available.",
                reason,
                command: null,
                optionalReviewCommand: result.reasonCode === "terminal_state"
                    ? cliCommand(`task review --task-definition ${taskPath}`)
                    : null
            };
        case "address_validation":
            return {
                ...closeoutRoute,
                recommendation: "Address current-attempt validation evidence before review or closeout.",
                reason,
                command: cliCommand(`task review --task-definition ${taskPath}`),
                optionalReviewCommand: null
            };
        case "reconcile":
            return {
                ...closeoutRoute,
                recommendation: "Review task evidence before milestone reconciliation.",
                reason,
                command: topologyEvidence.reconciliationRequired
                    ? cliCommand(`task review --task-definition ${taskPath}`)
                    : cliCommand(`implementation-summary review --task-definition ${taskPath}`),
                optionalReviewCommand: null
            };
        case "repair_state":
        case "recertify_plan":
        case "resolve_blocker":
        case "refine_task":
            return {
                ...implementationRoute,
                recommendation: "Resolve paired lifecycle evidence before implementation.",
                reason,
                command: cliCommand(`task readiness-review --task-definition ${taskPath}`),
                optionalReviewCommand: null
            };
    }
}
function cliCommand(args) {
    return (0, cli_invocation_1.renderDayShiftCliCommand)(args);
}
