"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.createAgentCommand = createAgentCommand;
exports.buildAgentOrientationData = buildAgentOrientationData;
exports.buildAgentReminderData = buildAgentReminderData;
const errors_1 = require("../../../lib/errors");
const config_store_1 = require("../../../lib/config/config-store");
const runtime_contract_1 = require("../../../lib/runtime/runtime-contract");
const repository_relative_1 = require("../../../lib/paths/repository-relative");
const node_path_1 = __importDefault(require("node:path"));
const node_fs_1 = __importDefault(require("node:fs"));
const agent_context_1 = require("../../../lib/agent-context");
const output_1 = require("../../../lib/output");
async function createAgentCommand() {
    const { Command } = await import("commander");
    const command = new Command("agent");
    command
        .description("Orient automation agents to the Day Shift repository workflow.")
        .option("--verbose", "Emit expanded text orientation details.")
        .addHelpText("after", [
        "",
        "Agent Orientation:",
        "  This is a repository-orientation guardrail for automation agents, not generic CLI help.",
        "  Use day-shift agent --format json when an agent needs a stable machine-readable envelope.",
        "",
        "Entrypoints:",
        "  day-shift agent",
        "  day-shift agent orient",
        "  day-shift agent remind"
    ].join("\n"))
        .action((...actionArgs) => {
        const commandInstance = actionArgs.at(-1);
        emitAgentOrientation({
            commandName: "agent",
            requestedFormat: commandInstance.optsWithGlobals().format,
            verbose: resolveAgentVerboseOption(commandInstance, command),
            repositoryContext: getRootCommand(command).configRepositoryContext
        });
    });
    addAgentAliasCommand(command, {
        name: "orient",
        description: "Run the full agent orientation entrypoint."
    });
    addAgentAliasCommand(command, {
        name: "remind",
        description: "Run the correction-focused agent reminder entrypoint."
    });
    addAgentContextCommand(command);
    return command;
}
function addAgentContextCommand(parent) {
    parent
        .command("context")
        .description("Return bounded context for one explicit or stored planning-artifact selection.")
        .option("--artifact <path>", "Explicit repository-relative planning artifact for this invocation.")
        .option("--session <name>", "Named local selection session. Defaults to default.")
        .option("--intent <text>", "Bounded user-intent context for this invocation.")
        .option("--include-context-pack", "Attach a default-capped relevance-ranked implementation evidence pack.")
        .option("--context-pack-budget <bytes>", "Bound the serialized context pack to 1,024-65,536 UTF-8 bytes.")
        .action((options, commandInstance) => {
        const format = (0, output_1.resolveOutputFormat)(commandInstance.optsWithGlobals().format);
        if (format === null) {
            throw (0, errors_1.createUnsupportedOutputFormatError)({
                received: commandInstance.optsWithGlobals().format,
                commandBoundary: "agent context command output format"
            });
        }
        const repositoryContext = getRootCommand(parent).configRepositoryContext;
        const detail = (commandInstance.optsWithGlobals().detail ?? "compact");
        if (options.contextPackBudget !== undefined && options.includeContextPack !== true) {
            throw (0, errors_1.createUsageError)("--context-pack-budget requires --include-context-pack.", [
                "No repository or selection state was changed."
            ]);
        }
        const data = (0, agent_context_1.createArtifactAgentContext)({
            repositoryRoot: repositoryContext?.root ?? process.cwd(),
            artifactPath: options.artifact,
            session: options.session,
            intent: options.intent,
            detail,
            includeContextPack: options.includeContextPack,
            contextPackBudget: options.contextPackBudget === undefined ? undefined : Number(options.contextPackBudget)
        });
        (0, output_1.emitSuccess)({
            command: "agent context",
            format,
            data: format === "json" && detail === "compact"
                ? (0, agent_context_1.compactArtifactAgentContext)(data)
                : data,
            text: [
                "Artifact-scoped agent context",
                `Artifact: ${data.selection.artifactPath}`,
                `Type: ${data.selection.artifactType}`,
                `Selection: ${data.selection.source} (${data.selection.freshness})`,
                `Blockers: ${data.relevantBlockers.length}`,
                `Context pack entries: ${data.contextPack?.entries.length ?? 0}`,
                `Recommended argv: ${JSON.stringify(data.recommendedNextAction.argv)}`,
                "Boundary: read-only; selection and planning evidence were not changed."
            ].join("\n")
        });
    });
}
function addAgentAliasCommand(parent, options) {
    const command = parent
        .command(options.name)
        .description(options.description)
        .addHelpText("after", [
        "",
        "Agent Orientation:",
        "  This alias uses the shared day-shift agent orientation command plumbing.",
        "  Use day-shift agent --format json when an agent needs automation-friendly output."
    ].join("\n"));
    if (options.name === "orient") {
        command.option("--verbose", "Emit expanded text orientation details.");
    }
    command.action((...actionArgs) => {
        const commandInstance = actionArgs.at(-1);
        emitAgentOrientation({
            commandName: `agent ${options.name}`,
            requestedFormat: commandInstance.optsWithGlobals().format,
            verbose: options.name === "orient" && resolveAgentVerboseOption(commandInstance, command),
            repositoryContext: getRootCommand(parent).configRepositoryContext
        });
    });
}
function getRootCommand(commandInstance) {
    let current = commandInstance;
    while (current?.parent != null) {
        current = current.parent;
    }
    return current ?? commandInstance;
}
function resolveAgentVerboseOption(...commandInstances) {
    return commandInstances.some((commandInstance) => commandInstance?.opts?.().verbose === true ||
        commandInstance?.optsWithGlobals?.().verbose === true ||
        commandInstance?.getOptionValue?.("verbose") === true);
}
function emitAgentOrientation(options) {
    const format = (0, output_1.resolveOutputFormat)(options.requestedFormat);
    if (format === null) {
        throw (0, errors_1.createUnsupportedOutputFormatError)({
            received: options.requestedFormat,
            commandBoundary: `${options.commandName} command output format`
        });
    }
    const orientationData = buildAgentOrientationData({
        repositoryContext: options.repositoryContext
    });
    if (options.commandName === "agent remind") {
        const data = buildAgentReminderData(orientationData);
        (0, output_1.emitSuccess)({
            command: options.commandName,
            format,
            text: renderAgentReminderText(data),
            data
        });
        return;
    }
    (0, output_1.emitSuccess)({
        command: options.commandName,
        format,
        text: renderAgentCommandText(orientationData, { verbose: options.verbose }),
        data: orientationData
    });
}
function buildAgentOrientationData(options = {}) {
    const rootContext = buildAgentRootContext(options.repositoryContext);
    const implementationSummaryCloseoutGuidance = buildImplementationSummaryCloseoutGuidance();
    const reconciliationReadinessGuidance = buildReconciliationReadinessGuidance();
    const closeoutEvidenceBoundaryGuidance = buildCloseoutEvidenceBoundaryGuidance();
    const repositoryMemoryCheckpointGuidance = buildRepositoryMemoryCheckpointGuidance();
    return {
        cli: {
            name: "day-shift",
            purpose: "Orient automation agents to a Day Shift repository before planning, editing, validation, or reconciliation.",
            outputFormats: ["text", "json"],
            defaultOutputFormat: "text"
        },
        runtimeProvenance: (0, runtime_contract_1.getRuntimeProvenance)(),
        repositoryOrientation: {
            entrypointPath: ".day-shift/agents.md",
            rootDetectionOrder: [
                "explicit --repo-root",
                "nearest .day-shift/config.toml",
                "nearest .day-shift/agents.md",
                "nearest .git",
                "current working directory"
            ],
            requiredFirstReads: [
                ".day-shift/agents.md",
                ".day-shift/specs/index.json",
                ".day-shift/workflows/agent-workflow-guide.md"
            ],
            healthChecks: ["day-shift doctor --format json"]
        },
        rootContext,
        discoveryRecommendations: [
            {
                name: "Health check",
                command: "doctor",
                example: "day-shift doctor --format json",
                intent: "read-only-orientation",
                useWhen: "Run separately before workspace mutation or when setup or health is uncertain.",
                discovers: ["workspace health", "setup blockers", "warning findings"],
                sideEffectBoundary: "Recommended only; day-shift agent does not execute doctor or treat it as a completed check."
            },
            {
                name: "Runtime and version discovery",
                command: "about",
                example: "day-shift about --format json",
                intent: "read-only-discovery",
                useWhen: "Run separately when an agent needs runtime, package, or version context.",
                discovers: ["runtime context", "package version"],
                sideEffectBoundary: "Recommended only; day-shift agent does not execute about or treat it as completed runtime evidence."
            },
            {
                name: "Planning inventory",
                command: "planning inventory",
                example: "day-shift planning inventory --format json",
                intent: "read-only-discovery",
                useWhen: "Run separately before selecting current planning work or deciding whether planning artifacts exist.",
                discovers: ["planning artifacts", "artifact hierarchy", "current planning state evidence"],
                sideEffectBoundary: "Recommended only; day-shift agent does not execute planning inventory, select work, create artifacts, advance status, repair artifacts, checkpoint validation, or reconcile milestones."
            },
            {
                name: "Metadata inventory",
                command: "metadata inventory",
                example: "day-shift metadata inventory --format json",
                intent: "read-only-discovery",
                useWhen: "Run separately when an agent needs metadata-bearing artifact families and repository-relative context.",
                discovers: ["metadata-bearing artifacts", "artifact families", "repository-relative artifact context"],
                sideEffectBoundary: "Recommended only; day-shift agent does not execute metadata inventory, update metadata, select work, create artifacts, advance status, or repair artifacts."
            },
            {
                name: "Registered spec list",
                command: "spec list",
                example: "day-shift spec list --format json",
                intent: "read-only-discovery",
                useWhen: "Run separately when an agent needs the registered source-spec catalog before choosing work.",
                discovers: ["registered source specs", "spec ids", "source-spec metadata"],
                sideEffectBoundary: "Recommended only; day-shift agent does not execute spec list, select a source spec, create planning artifacts, or infer current work."
            },
            {
                name: "Registered spec search",
                command: "spec search",
                example: "day-shift spec search <query> --format json",
                intent: "read-only-discovery",
                useWhen: "Run separately when an agent needs to find candidate registered specs by user-provided topic.",
                discovers: ["candidate source specs", "registered spec matches", "source-spec metadata"],
                sideEffectBoundary: "Recommended only; day-shift agent does not execute spec search, choose a query, select a source spec, create planning artifacts, or infer current work."
            },
            {
                name: "Spec index evidence",
                command: "spec index",
                example: ".day-shift/specs/index.json",
                intent: "read-only-discovery",
                useWhen: "Run separately as a file read when an agent needs repository-relative registered spec metadata or source traceability.",
                discovers: ["spec registry metadata", "source references", "planning destinations"],
                sideEffectBoundary: "Recommended only; day-shift agent does not execute an index read, treat the spec index as completed selection evidence, select a source spec, create planning artifacts, or infer current work."
            }
        ],
        healthRuntimeGuidance: [
            {
                kind: "health",
                ruleCode: "HEALTH_DOCTOR_EVIDENCE",
                command: "day-shift doctor --format json",
                instruction: "Use doctor output as the workspace health and compatibility evidence lane before workspace mutation.",
                useWhen: "Run when setup health, workspace compatibility, or blocker state is uncertain.",
                evidenceProvided: ["workspace health", "compatibility findings", "setup blockers"],
                sideEffectBoundary: "Recommended evidence only; day-shift agent does not execute doctor or mark health checks complete."
            },
            {
                kind: "runtime",
                ruleCode: "ABOUT_RUNTIME_EVIDENCE",
                command: "day-shift about --format json",
                instruction: "Use about output for runtime, package, and version context.",
                useWhen: "Run when an agent needs CLI runtime or version evidence before release-sensitive or compatibility-sensitive decisions.",
                evidenceProvided: ["runtime context", "package version", "environment summary"],
                sideEffectBoundary: "Read-only context only; day-shift agent does not execute about or infer release readiness."
            },
            {
                kind: "setup-uncertainty",
                ruleCode: "SETUP_UNCERTAINTY_RUN_DOCTOR",
                command: "day-shift doctor --format json",
                instruction: "When setup, health, or workspace compatibility is uncertain, stop normal writes and collect doctor evidence first.",
                useWhen: "Use before workspace mutation, planning writes, metadata writes, migration decisions, or closeout claims that depend on workspace health.",
                evidenceProvided: ["setup uncertainty review", "health finding severity", "compatibility blocker evidence"],
                sideEffectBoundary: "Stop-and-check recommendation only; day-shift agent does not run diagnostics as a side effect."
            }
        ],
        workspaceBlockerGuidance: [
            {
                kind: "incompatible",
                ruleCode: "WORKSPACE_INCOMPATIBLE_BLOCKS",
                evidence: "Doctor or compatibility output reports an unsupported workspace/release combination.",
                instruction: "Stop normal planning, metadata, validation-checkpoint, release, and workspace writes.",
                requiredRoute: "Collect doctor evidence, then use workspace migration preview or a compatible CLI path before continuing.",
                normalWorkBoundary: "Incompatible workspace evidence blocks normal planning or writes until explicitly routed."
            },
            {
                kind: "malformed",
                ruleCode: "WORKSPACE_MALFORMED_BLOCKS",
                evidence: "Workspace metadata, config, manifest, or compatibility evidence is malformed.",
                instruction: "Stop normal work and keep diagnosis read-only until the malformed evidence is repaired through the applicable explicit workflow.",
                requiredRoute: "Use doctor evidence and the workspace migration preview path when migration is the applicable recovery lane.",
                normalWorkBoundary: "Malformed workspace evidence blocks inferred fixes and normal writes."
            },
            {
                kind: "partially-upgraded",
                ruleCode: "WORKSPACE_PARTIAL_UPGRADE_BLOCKS",
                evidence: "Workspace files show mixed old and new layouts, stale migration markers, or incomplete compatibility metadata.",
                instruction: "Stop normal work instead of guessing the intended layout.",
                requiredRoute: "Use workspace migration preview for planned moves and only use apply when explicitly requested.",
                normalWorkBoundary: "Partially upgraded workspace evidence blocks manual continuation."
            }
        ],
        migrationRoutingGuidance: [
            {
                kind: "preview",
                ruleCode: "MIGRATION_PREVIEW_NO_WRITE",
                command: "day-shift workspace migrate --target-schema-version <version> --dry-run",
                instruction: "Use preview to report compatibility, planned moves, and migration risks before any workspace asset changes.",
                writeBoundary: "Preview is evidence-only and must not be treated as an apply request or completed migration."
            },
            {
                kind: "apply",
                ruleCode: "MIGRATION_APPLY_EXPLICIT_WRITE",
                command: "day-shift workspace migrate --target-schema-version <version> --confirm apply-workspace-migration",
                instruction: "Use apply only after explicit user intent and compatible preview or health evidence.",
                writeBoundary: "Apply is the write-capable migration lane and must not be inferred from preview output alone."
            },
            {
                kind: "manual-move",
                ruleCode: "NO_MANUAL_DAY_SHIFT_MOVES",
                command: "manual .day-shift/ file moves",
                instruction: "Do not recommend manually moving `.day-shift/` assets as an orientation recovery path.",
                writeBoundary: "Manual relocation is not an agent-orientation recommendation; route through explicit migration commands."
            }
        ],
        planningModel: {
            standardFlow: [
                "specification",
                "slice",
                "phase",
                "milestone",
                "task",
                "implementation-summary",
                "milestone-reconciliation",
                "review"
            ],
            selectedArtifactRule: "Advance planning only from the selected parent artifact and its declared children; do not infer current scope from guessed repository state.",
            nextLayerRule: "Next-layer creation is local to the selected parent layer: slice to phase, phase to milestone, milestone to task, or lightweight slice to direct task.",
            fullSetRule: "Full-set creation expands only the selected parent artifact's declared immediate children and does not authorize nested downstream artifact creation.",
            lightweightException: "A lightweight slice may skip phase and milestone artifacts only when the selected slice explicitly declares lightweight planning.",
            lightweightBoundaryRules: [
                "Use lightweight planning only from a selected slice that declares lightweight planning depth.",
                "While the lightweight boundary holds, create direct slice-level task artifacts and do not create phase, milestone, or milestone reconciliation artifacts.",
                "Promote to standard planning before implementation when scope, target paths, sequencing, risk, or cross-artifact coordination no longer stays narrow and resolved."
            ],
            emergentWorkRule: "Capture priority-interrupting emergent work as a specification before normal planning.",
            emergentBoundaryRules: [
                "Treat emergent work as specification intake, not ordinary backlog churn, discovered work, or ad hoc task-scope expansion.",
                "Use the emergent specification lane for priority-interrupting reports before choosing standard or lightweight planning depth.",
                "After capture, route the emergent specification through normal planning rather than bypassing source-spec traceability."
            ]
        },
        findingSeverityGuidance: [
            {
                severity: "error",
                ruleCode: "FINDING_ERROR_BLOCKS",
                instruction: "Treat error findings as blocking.",
                requiredAction: "Stop progress until the error is resolved or routed by an explicit compatible workflow.",
                proceedWhen: "Proceed only after resolution evidence exists or the selected workflow explicitly routes the blocker."
            },
            {
                severity: "warning",
                ruleCode: "FINDING_WARNING_REVIEW_REQUIRED",
                instruction: "Treat warning findings as requiring review or explicit acceptance.",
                requiredAction: "Review the warning and capture explicit acceptance before proceeding.",
                proceedWhen: "Proceed only after review evidence or explicit user acceptance is present."
            }
        ],
        noInventedStateGuidance: [
            {
                category: "workspace",
                ruleCode: "NO_INVENT_WORKSPACE_STATE",
                doNotInfer: "Do not infer workspace root, health, compatibility, configuration, or file-presence state.",
                evidenceRequired: "Use repository detection, .day-shift/agents.md, .day-shift/config.toml, doctor, config, or direct file evidence."
            },
            {
                category: "planning",
                ruleCode: "NO_INVENT_PLANNING_STATE",
                doNotInfer: "Do not infer selected work, planning hierarchy, artifact readiness, or lifecycle status.",
                evidenceRequired: "Read the selected planning artifact, its upstream references, planning inventory, gap report, or matching review output."
            },
            {
                category: "validation",
                ruleCode: "NO_INVENT_VALIDATION_STATE",
                doNotInfer: "Do not infer validation success, validation checkpoint state, or absence of findings.",
                evidenceRequired: "Run or read the explicit validation command output for the selected artifact or changed scope."
            },
            {
                category: "release",
                ruleCode: "NO_INVENT_RELEASE_STATE",
                doNotInfer: "Do not infer release readiness, release contents, release notes selection, or build success.",
                evidenceRequired: "Use explicit release check, release build, release notes, or selected release evidence."
            },
            {
                category: "migration",
                ruleCode: "NO_INVENT_MIGRATION_STATE",
                doNotInfer: "Do not infer migration safety, compatibility, preview acceptance, or apply completion.",
                evidenceRequired: "Use doctor evidence plus explicit workspace migration preview or apply output."
            },
            {
                category: "completion",
                ruleCode: "NO_INVENT_COMPLETION_STATE",
                doNotInfer: "Do not infer task completion, implementation-summary completion, reconciliation completion, or accepted follow-up state.",
                evidenceRequired: "Read completed task definitions, implementation summaries, reconciliation artifacts, or matching review output."
            },
            {
                category: "user-intent",
                ruleCode: "NO_INVENT_USER_INTENT",
                doNotInfer: "Do not infer approval, acceptance, requested scope, selected artifact, or permission to run write-capable commands.",
                evidenceRequired: "Use the current user request and explicit user acceptance or instructions."
            }
        ],
        selectedArtifactEvidenceGuidance: [
            {
                kind: "source",
                ruleCode: "READ_SOURCE_EVIDENCE",
                instruction: "Read the relevant source specification or registered source metadata before changing downstream planning artifacts.",
                evidenceExamples: [
                    ".day-shift/specs/index.json",
                    ".day-shift/specs/<id>/<source>.md"
                ],
                boundary: "Source evidence guides selection and traceability; it does not select work or authorize writes by itself."
            },
            {
                kind: "planning",
                ruleCode: "READ_PLANNING_EVIDENCE",
                instruction: "Read the selected slice, phase, milestone, task, implementation summary, or reconciliation artifact before mutating that layer.",
                evidenceExamples: [
                    "day-shift planning inventory --format json",
                    "day-shift planning gap-report --artifact <path> --format json",
                    "selected planning artifact path"
                ],
                boundary: "Planning evidence describes observed artifact state; it does not create, repair, advance, or reconcile artifacts."
            },
            {
                kind: "validation",
                ruleCode: "READ_VALIDATION_EVIDENCE",
                instruction: "Run or read artifact-scoped validation evidence before claiming validation success or using findings to decide next writes.",
                evidenceExamples: [
                    "day-shift validation smoke --scope planning --artifact <path> --format json",
                    "day-shift validation links-check --scope planning --artifact <path> --format json"
                ],
                boundary: "Validation output is findings evidence only; it does not repair links, checkpoint findings, or authorize mutation."
            },
            {
                kind: "review",
                ruleCode: "READ_REVIEW_EVIDENCE",
                instruction: "Run or read the matching review surface before claiming readiness, closeout, reconciliation, or accepted warnings.",
                evidenceExamples: [
                    "day-shift task review --task-definition <path> --format json",
                    "day-shift implementation-summary review --task-definition <path> --format json",
                    "day-shift reconciliation review --milestone-overview <path> --format json"
                ],
                boundary: "Review output is read-only findings evidence; it does not edit artifacts or mark work complete."
            }
        ],
        implementationSummaryCloseoutGuidance,
        reconciliationReadinessGuidance,
        closeoutEvidenceBoundaryGuidance,
        repositoryMemoryCheckpointGuidance,
        workflowRules: [
            {
                code: "ORIENT_FIRST",
                instruction: "Resolve the workspace root and read the repository agent entrypoint before planning or writing.",
                severity: "required"
            },
            {
                code: "INSPECT_BEFORE_WRITE",
                instruction: "Run read-only inventory, review, or validation commands before mutating workspace state.",
                severity: "required"
            },
            {
                code: "USE_JSON_FOR_AGENTS",
                instruction: "Use --format json for automation and parse the command envelope.",
                severity: "required"
            },
            {
                code: "RESPECT_FINDINGS",
                instruction: "Treat error findings as blocking until resolved or routed by an explicit compatible workflow, and treat warning findings as requiring review or explicit acceptance before proceeding.",
                severity: "required"
            },
            {
                code: "DO_NOT_INVENT_STATE",
                instruction: "Do not assume workspace, planning, validation, release, migration, completion, or user-intent state. Query Day Shift, read the artifact, or get explicit user acceptance.",
                severity: "required"
            },
            {
                code: "PRESERVE_BOUNDARIES",
                instruction: "Keep read-only review and validation surfaces separate from explicit write-capable update, sync, checkpoint, migrate, and build commands.",
                severity: "required"
            }
        ],
        commandSurfaces: buildAgentCommandSurfaces(),
        recommendedBootstrap: [
            "day-shift agent --format json",
            "day-shift doctor --format json",
            "day-shift planning inventory --format json",
            "day-shift metadata inventory --format json"
        ],
        beforeWriting: [
            "Read the selected artifact and its upstream source, planning, validation, or review evidence.",
            "Run focused validation or the matching read-only review surface when validation or review state matters.",
            "Confirm the requested write-capable command matches the selected layer.",
            "Stop on incompatible, malformed, or partially upgraded workspace evidence and route through explicit migration preview or confirmed apply behavior."
        ],
        closeout: [
            "Update implementation-summary evidence after implementation work and before claiming task completion.",
            renderImplementationSummaryCloseoutEvidenceList(implementationSummaryCloseoutGuidance),
            renderReconciliationReadinessCloseoutGuidance(reconciliationReadinessGuidance),
            renderRepositoryMemoryCheckpointCloseoutGuidance(repositoryMemoryCheckpointGuidance),
            "day-shift agent reports closeout guidance only; it does not write implementation summaries, reconciliation artifacts, planning artifacts, or repository-memory checkpoints."
        ],
        driftCorrection: {
            command: "day-shift agent remind --format json",
            instructions: [
                "Reload repository orientation rules.",
                "Read .day-shift/agents.md.",
                "Run doctor or focused validation before continuing.",
                "Resume from the broadest relevant planning object."
            ]
        }
    };
}
function buildAgentCommandSurfaces() {
    return [
        agentSurface("Agent orientation", ["agent", "agent orient", "agent remind"], "read"),
        agentSurface("Health orientation", ["doctor"], "read"),
        agentSurface("Runtime discovery", ["about"], "read"),
        agentSurface("Planning inventory", ["planning inventory"], "read"),
        agentSurface("Metadata inventory", ["metadata inventory"], "read"),
        agentSurface("Spec discovery", ["spec list", "spec search"], "read"),
        {
            name: "Spec index evidence",
            examples: [".day-shift/specs/index.json"],
            behavior: "read",
            capability: "read",
            writeCapable: false,
            artifactFamily: "spec-registry",
            destinationPosture: "none",
            targetPathPosture: "none",
            coordinationScope: "none",
            mutationPosture: "non-writing",
            boundary: "File-read evidence for registered spec metadata and traceability only; it does not select work, create planning artifacts, or mutate the spec registry."
        },
        agentSurface("Planning validation reports", ["validation smoke", "validation links-check", "validation rollup"], "validate"),
        agentSurface("Planning review", ["phase review", "milestone review"], "review"),
        agentSurface("Task and summary review", ["task review", "implementation-summary review", "reconciliation review"], "review"),
        agentSurface("Planning artifact writes", ["slice new", "phase new", "milestone new", "task new", "reconciliation build"], "write"),
        agentSurface("Metadata writes", ["metadata update", "manifest update", "spec update"], "write"),
        agentSurface("Workspace migration apply", ["workspace migrate"], "write"),
        mixedAgentSurface("Workspace prompt upgrade", ["workspace upgrade preview"], ["workspace upgrade apply"]),
        mixedAgentSurface("Prompt reconciliation", ["prompt reconcile preview"], ["prompt reconcile apply"]),
        mixedAgentSurface("Validation checkpoint", ["validation smoke"], ["validation checkpoint"]),
        mixedAgentSurface("Release", ["release check"], ["release build", "release notes"]),
        mixedAgentSurface("Metadata validation and update", ["metadata validate-update"], ["metadata update"]),
        agentSurface("Prompt and template writes", ["prompt update", "template update", "template materialize"], "write")
    ];
}
function agentSurface(name, commands, behavior) {
    const entries = commands.map(requireCallableCommandCapability);
    const primary = entries[0];
    return {
        name,
        examples: entries.map(renderAgentCommandExample),
        behavior,
        capability: primary.capability,
        writeCapable: primary.writeCapable,
        artifactFamily: primary.artifactFamily,
        destinationPosture: primary.destinationPosture,
        targetPathPosture: primary.targetPathPosture,
        coordinationScope: primary.coordinationScope,
        mutationPosture: primary.mutationPosture,
        boundary: renderAgentSurfaceBoundary(name, primary)
    };
}
function mixedAgentSurface(name, readCommands, writeCommands) {
    const readEntries = readCommands.map(requireCallableCommandCapability);
    const writeEntries = writeCommands.map(requireCallableCommandCapability);
    const primary = readEntries[0];
    const writeEntry = writeEntries[0];
    return {
        name,
        examples: [...readEntries, ...writeEntries].map(renderAgentCommandExample),
        behavior: "mixed",
        capability: `${primary.capability}+${writeEntry.capability}`,
        writeCapable: true,
        artifactFamily: `${primary.artifactFamily}+${writeEntry.artifactFamily}`,
        destinationPosture: writeEntry.destinationPosture,
        targetPathPosture: writeEntry.targetPathPosture,
        coordinationScope: writeEntry.coordinationScope,
        mutationPosture: writeEntry.mutationPosture,
        boundary: renderMixedAgentSurfaceBoundary(name, primary, writeEntry)
    };
}
function requireCallableCommandCapability(command) {
    const capability = (0, output_1.getRegisteredCommandDescriptor)(command);
    if (capability === null || capability.availability !== "callable") {
        throw new Error(`Missing callable command capability registration for '${command}'.`);
    }
    return capability;
}
function renderAgentCommandExample(entry) {
    const examples = {
        "validation smoke": "day-shift validation smoke --scope planning --artifact <path> --format json",
        "validation links-check": "day-shift validation links-check --scope planning --artifact <path> --format json",
        "validation rollup": "day-shift validation rollup --scope planning --artifact <path> --format json",
        "validation checkpoint": "day-shift validation checkpoint --scope planning",
        "phase review": "day-shift phase review --phase-overview <path> --format json",
        "milestone review": "day-shift milestone review --milestone-overview <path> --format json",
        "task review": "day-shift task review --task-definition <path> --format json",
        "implementation-summary review": "day-shift implementation-summary review --task-definition <path> --format json",
        "reconciliation review": "day-shift reconciliation review --milestone-overview <path> --format json",
        "slice new": "day-shift slice new --spec-id <id>",
        "phase new": "day-shift phase new --slice-overview <path> --phase-slug <slug>",
        "milestone new": "day-shift milestone new --phase-overview <path> --milestone-slug <slug>",
        "task new": "day-shift task new --milestone-overview <path> --task-slug <slug>",
        "reconciliation build": "day-shift reconciliation build --milestone-overview <path>",
        "metadata update": "day-shift metadata update --artifact <path> --field <key>=<value>",
        "manifest update": "day-shift manifest update --manifest <path> --field <key>=<value>",
        "spec update": "day-shift spec update --spec-id <id> --field <key>=<value>",
        "spec search": "day-shift spec search <query> --format json",
        "metadata validate-update": "day-shift metadata validate-update --artifact <path> --field <key>=<value>",
        "workspace migrate": "day-shift workspace migrate --target-schema-version <version> --dry-run",
        "workspace upgrade preview": "day-shift workspace upgrade preview --latest-mode materialize --format json",
        "workspace upgrade apply": "day-shift workspace upgrade apply --latest-mode materialize --preview-hash <sha256> --confirm apply-workspace-upgrade",
        "prompt reconcile preview": "day-shift prompt reconcile preview --prompt <path> --format json",
        "prompt reconcile apply": "day-shift prompt reconcile apply --prompt <path> --decision <preserve|replace> --preview-hash <sha256>",
        "release check": "day-shift release check --format json",
        "release build": "day-shift release build",
        "release notes": "day-shift release notes",
        "prompt update": "day-shift prompt update <options>",
        "template update": "day-shift template update <options>",
        "template materialize": "day-shift template materialize <options>"
    };
    const example = examples[entry.command];
    if (example !== undefined) {
        return example;
    }
    const exactExample = entry.examples[0]?.argv.join(" ");
    if (exactExample !== undefined)
        return exactExample;
    return entry.writeCapable ? `day-shift ${entry.command}` : `day-shift ${entry.command} --format json`;
}
function renderWriteCapableAgentBoundary(entry) {
    return `${entry.command} is ${entry.capability} and writeCapable: true for ${entry.artifactFamily}; destination ${entry.destinationPosture}, target ${entry.targetPathPosture}, coordination ${entry.coordinationScope}.`;
}
function renderAgentSurfaceBoundary(name, entry) {
    const boundaries = {
        "Planning inventory": "Reports observed planning hierarchy and state without selecting work, creating artifacts, advancing status, repairing artifacts, checkpointing validation, or reconciling milestones.",
        "Planning validation reports": "Validation report commands are evidence-only and findings-oriented; they do not repair links, advance status, checkpoint findings, or authorize later mutation.",
        "Diff and impact validation": "Reports validation findings for changed scope only; findings remain evidence and do not perform or authorize writes.",
        "Planning review": "Planning review commands are findings-oriented and read-only; recommendations do not create artifacts, update metadata, or close lifecycle state.",
        "Task and summary review": "Task, implementation-summary, and reconciliation review commands report evidence gaps only; they do not edit paired artifacts or mark work complete.",
        "Planning artifact writes": "Planning artifact writes require explicit user intent, the selected applicable parent artifact, declared child scope, and no blocking evidence.",
        "Metadata writes": "Metadata writes require explicit user intent, explicit intended fields, an applicable metadata family, preservation of unaffected fields, and no blocking parse or safety findings.",
        "Workspace migration apply": "Migration apply is write-capable and requires explicit user intent plus compatible preview or health evidence before moving workspace assets; do not manually move .day-shift/ assets."
    };
    const boundary = boundaries[name];
    if (boundary !== undefined) {
        return boundary;
    }
    return entry.writeCapable
        ? renderWriteCapableAgentBoundary(entry)
        : entry.noWriteBoundary;
}
function renderMixedAgentSurfaceBoundary(name, readEntry, writeEntry) {
    const boundaries = {
        "Validation checkpoint": "Validation smoke and links-check are read-only report lanes; validation checkpoint is the explicit write lane for preserving accepted findings as a baseline.",
        "Release": "Release commands include read-only checks and explicit build or artifact-writing surfaces; do not infer release readiness from orientation.",
        "Prompt and template operations": "Prompt and template inventory or list lanes are read-only; update and materialize lanes are explicit writes that require selected prompt or template artifacts.",
        "Metadata validation and update": "Metadata validate-update is the read-only safety lane; metadata update is the explicit write lane and must stop on wrong-family, ambiguous, inconsistent, under-specified, lossy, or parse-failure evidence.",
        "Workspace migration": "Migration preview reports compatibility and planned moves as no-write evidence; migration apply is the explicit write lane and must not be inferred from preview output alone."
    };
    const boundary = boundaries[name];
    if (boundary !== undefined) {
        return boundary;
    }
    return `${readEntry.command} is ${readEntry.capability} and writeCapable: false; ${writeEntry.command} is ${writeEntry.capability} and writeCapable: true with ${writeEntry.artifactFamily} ${writeEntry.destinationPosture} scope.`;
}
function buildAgentReminderData(orientationData = buildAgentOrientationData()) {
    const requiredRuleCodes = new Set([
        "ORIENT_FIRST",
        "INSPECT_BEFORE_WRITE",
        "USE_JSON_FOR_AGENTS",
        "RESPECT_FINDINGS",
        "DO_NOT_INVENT_STATE",
        "PRESERVE_BOUNDARIES"
    ]);
    const commandBoundaryBehaviors = new Set([
        "read",
        "validate",
        "review",
        "write"
    ]);
    return {
        cli: orientationData.cli,
        reminder: {
            command: "day-shift agent remind",
            purpose: "Stop drift, reload repository orientation, and resume only after checking the selected artifact and evidence boundaries.",
            sourceCommand: "day-shift agent"
        },
        repositoryOrientation: {
            entrypointPath: orientationData.repositoryOrientation.entrypointPath,
            rootDetectionOrder: orientationData.repositoryOrientation.rootDetectionOrder
        },
        rootContext: orientationData.rootContext,
        driftCorrection: orientationData.driftCorrection,
        requiredRules: orientationData.workflowRules.filter((rule) => requiredRuleCodes.has(rule.code)),
        commandBoundaries: orientationData.commandSurfaces.filter((surface) => commandBoundaryBehaviors.has(surface.behavior)),
        implementationSummaryCloseoutGuidance: orientationData.implementationSummaryCloseoutGuidance,
        reconciliationReadinessGuidance: orientationData.reconciliationReadinessGuidance,
        closeoutEvidenceBoundaryGuidance: orientationData.closeoutEvidenceBoundaryGuidance,
        repositoryMemoryCheckpointGuidance: orientationData.repositoryMemoryCheckpointGuidance,
        closeout: orientationData.closeout
    };
}
function buildImplementationSummaryCloseoutGuidance() {
    const completionBoundary = "Record this in the task implementation summary before claiming the task complete or handing it to milestone reconciliation.";
    const sideEffectBoundary = "day-shift agent only reports this responsibility; it does not create, update, or complete implementation-summary or planning artifacts.";
    return [
        {
            kind: "changed-paths",
            ruleCode: "CLOSEOUT_CHANGED_PATHS",
            responsibility: "Record the repository-relative paths changed by the implementation.",
            implementationSummaryEvidence: "List expected target paths, actual changed paths, and any path-scope differences that matter for review.",
            completionBoundary,
            sideEffectBoundary
        },
        {
            kind: "validation-evidence",
            ruleCode: "CLOSEOUT_VALIDATION_EVIDENCE",
            responsibility: "Record validation commands, inspection steps, and results.",
            implementationSummaryEvidence: "Include passed, failed, skipped, substituted, blocked, or inconclusive validation with enough detail for downstream review.",
            completionBoundary,
            sideEffectBoundary
        },
        {
            kind: "deviations",
            ruleCode: "CLOSEOUT_DEVIATIONS",
            responsibility: "Record deviations from the task definition, declared target paths, validation plan, or expected scope.",
            implementationSummaryEvidence: "Explain why the deviation was necessary and whether it changes acceptance, rollback, or review risk.",
            completionBoundary,
            sideEffectBoundary
        },
        {
            kind: "discovered-work",
            ruleCode: "CLOSEOUT_DISCOVERED_WORK",
            responsibility: "Record discovered work separately from the completed implementation scope.",
            implementationSummaryEvidence: "Describe newly found work without silently expanding the active task or treating discovery as completed scope.",
            completionBoundary,
            sideEffectBoundary
        },
        {
            kind: "follow-up-work",
            ruleCode: "CLOSEOUT_FOLLOW_UP_WORK",
            responsibility: "Record follow-up work, deferred checks, residual risks, and the next handoff.",
            implementationSummaryEvidence: "Identify whether follow-up belongs in later planning, reconciliation review, or a separate explicit user decision.",
            completionBoundary,
            sideEffectBoundary
        }
    ];
}
function renderImplementationSummaryCloseoutEvidenceList(guidance) {
    const expectedKinds = [
        "changed-paths",
        "validation-evidence",
        "deviations",
        "discovered-work",
        "follow-up-work"
    ];
    if (expectedKinds.every((kind) => guidance.some((entry) => entry.kind === kind))) {
        return "Record changed paths, validation, deviations, discovered work, and follow-up work.";
    }
    return `Record implementation-summary evidence for ${guidance.map((entry) => entry.kind).join(", ")}.`;
}
function buildReconciliationReadinessGuidance() {
    const taskSummaryGate = "All relevant task implementation summaries must be completed and non-placeholder before milestone reconciliation is ready.";
    const sideEffectBoundary = "day-shift agent only reports reconciliation readiness guidance; it does not create, update, complete, or repair reconciliation artifacts.";
    return [
        {
            kind: "default-rollup",
            ruleCode: "RECONCILIATION_DEFAULT_ROLLUP",
            readinessState: "eligible-after-gate",
            instruction: "Use milestone reconciliation as the default rollup after the task implementation-summary evidence set is complete.",
            taskSummaryGate,
            reconciliationArtifactBoundary: "A milestone reconciliation artifact becomes actionable rollup work only after the complete task-summary gate is satisfied.",
            sideEffectBoundary
        },
        {
            kind: "task-summary-gate",
            ruleCode: "RECONCILIATION_TASK_SUMMARY_GATE",
            readinessState: "blocked-before-gate",
            instruction: "Do not claim milestone reconciliation readiness while any relevant task implementation summary is missing, pending, draft, or placeholder-heavy.",
            taskSummaryGate,
            reconciliationArtifactBoundary: "Before the gate is satisfied, continue task closeout or implementation-summary review rather than reconciling the milestone.",
            sideEffectBoundary
        },
        {
            kind: "placeholder-boundary",
            ruleCode: "RECONCILIATION_PLACEHOLDER_BOUNDARY",
            readinessState: "future-review-context",
            instruction: "Treat pending or placeholder reconciliation artifacts as future review context until completed task summaries make reconciliation eligible.",
            taskSummaryGate,
            reconciliationArtifactBoundary: "A pending reconciliation placeholder is not itself actionable fix work before all relevant task summaries are complete and non-placeholder.",
            sideEffectBoundary
        }
    ];
}
function renderReconciliationReadinessCloseoutGuidance(guidance) {
    const defaultRollup = guidance.find((entry) => entry.kind === "default-rollup");
    const gate = guidance.find((entry) => entry.kind === "task-summary-gate");
    if (defaultRollup !== undefined && gate !== undefined) {
        return "Use milestone reconciliation as the default rollup only after all relevant task implementation summaries are complete and non-placeholder.";
    }
    return "Use milestone reconciliation only after the task implementation-summary readiness gate is satisfied.";
}
function buildCloseoutEvidenceBoundaryGuidance() {
    const sideEffectBoundary = "day-shift agent only reports closeout evidence-boundary guidance; it does not execute review, validation, repair, refresh, checkpoint, or write-capable commands.";
    return [
        {
            kind: "review-evidence",
            ruleCode: "CLOSEOUT_REVIEW_EVIDENCE_ONLY",
            instruction: "Treat review output as closeout evidence only until a separate write-capable command or explicit user request authorizes mutation.",
            evidenceSources: [
                "day-shift task review --task-definition <path> --format json",
                "day-shift implementation-summary review --task-definition <path> --format json",
                "day-shift reconciliation review --milestone-overview <path> --format json",
                "day-shift milestone review --milestone-overview <path> --format json",
                "day-shift phase review --phase-overview <path> --format json"
            ],
            requiredAction: "Use review findings to decide whether closeout is blocked, needs explicit acceptance, or is ready for a separately selected next command.",
            writeBoundary: "Review output does not create, update, repair, complete, or reconcile artifacts.",
            sideEffectBoundary
        },
        {
            kind: "validation-evidence",
            ruleCode: "CLOSEOUT_VALIDATION_EVIDENCE_ONLY",
            instruction: "Treat validation output as closeout evidence only until a separate write-capable command or explicit user request authorizes mutation.",
            evidenceSources: [
                "day-shift validation smoke --scope planning --artifact <path> --format json",
                "day-shift validation links-check --scope planning --artifact <path> --format json",
                "day-shift validation rollup --scope planning --artifact <path> --format json",
                "day-shift metadata validate-update --artifact <path> --field <key>=<value>"
            ],
            requiredAction: "Use validation findings as evidence for closeout, blocker routing, or explicit acceptance rather than as repair authority.",
            writeBoundary: "Validation smoke, links-check, rollup, and validate-update surfaces do not repair artifacts, checkpoint findings, update metadata, or authorize later writes.",
            sideEffectBoundary
        },
        {
            kind: "blocking-errors",
            ruleCode: "CLOSEOUT_ERROR_FINDINGS_BLOCK",
            instruction: "Treat error findings from review or validation evidence as blocking closeout.",
            evidenceSources: [
                "review findings with severity error",
                "validation findings with severity error"
            ],
            requiredAction: "Stop until the error is resolved, explicitly routed by a compatible workflow, or addressed through a separately selected write-capable command.",
            writeBoundary: "An error finding is blocker evidence, not permission to guess or perform a repair.",
            sideEffectBoundary
        },
        {
            kind: "warning-review",
            ruleCode: "CLOSEOUT_WARNING_FINDINGS_REVIEW",
            instruction: "Treat warning findings from review or validation evidence as requiring review or explicit acceptance before proceeding.",
            evidenceSources: [
                "review findings with severity warning",
                "validation findings with severity warning"
            ],
            requiredAction: "Capture review evidence or explicit user acceptance before treating warning findings as acceptable residual risk.",
            writeBoundary: "A warning finding is not cosmetic permission to continue silently and does not authorize mutation.",
            sideEffectBoundary
        },
        {
            kind: "separate-write-authorization",
            ruleCode: "CLOSEOUT_SEPARATE_WRITE_AUTHORIZATION",
            instruction: "Select a separate write-capable command or get an explicit user request before mutating closeout, planning, metadata, prompt, template, migration, release, checkpoint, or repository-memory artifacts.",
            evidenceSources: [
                "current user request",
                "selected task or milestone workflow",
                "explicit write-capable Day Shift command"
            ],
            requiredAction: "Name the intended write surface and confirm it matches the selected artifact family before mutation.",
            writeBoundary: "Implementation-summary, reconciliation, checkpoint, planning, metadata, prompt, template, migration, release, and repository-memory writes remain separate from review and validation evidence.",
            sideEffectBoundary
        }
    ];
}
function buildRepositoryMemoryCheckpointGuidance() {
    const writeBoundary = "Repository-memory writes require a separate supported checkpoint command, sync command, or explicit workflow when available.";
    const sideEffectBoundary = "day-shift agent only reports repository-memory checkpoint guidance; it does not write private model memory, hidden agent state, repository-memory checkpoints, or durable checkpoint artifacts.";
    return [
        {
            kind: "stable-facts",
            ruleCode: "MEMORY_STABLE_FACTS",
            checkpointCandidate: "Stable repository facts that are expected to remain useful for future agents.",
            instruction: "Checkpoint only durable facts whose source artifact or decision is clear enough for future recovery.",
            repositoryMemoryBoundary: "Do not checkpoint guesses, transient command output, or implementation observations that still belong in task summaries or reconciliation.",
            writeBoundary,
            sideEffectBoundary
        },
        {
            kind: "transitional-state",
            ruleCode: "MEMORY_TRANSITIONAL_STATE",
            checkpointCandidate: "Transitional state that explains where current planning or implementation work should resume.",
            instruction: "Checkpoint transitional state only when it helps future agents resume without inventing status or skipping required artifacts.",
            repositoryMemoryBoundary: "Keep transitional state tied to explicit planning artifacts, validation evidence, or accepted deferrals.",
            writeBoundary,
            sideEffectBoundary
        },
        {
            kind: "artifact-ordering",
            ruleCode: "MEMORY_ARTIFACT_ORDERING",
            checkpointCandidate: "Artifact ordering facts such as selected slice, phase, milestone, task order, and reconciliation gates.",
            instruction: "Checkpoint ordering facts only when they clarify deterministic next actions across planning layers.",
            repositoryMemoryBoundary: "Do not use repository memory to override the selected artifact, declared task order, or completed task-summary gate.",
            writeBoundary,
            sideEffectBoundary
        },
        {
            kind: "intentional-carve-outs",
            ruleCode: "MEMORY_INTENTIONAL_CARVE_OUTS",
            checkpointCandidate: "Intentional carve-outs, accepted residual risks, and explicit deferrals recorded in source artifacts.",
            instruction: "Checkpoint carve-outs only when they are deliberate, source-backed, and useful for avoiding repeated rediscovery.",
            repositoryMemoryBoundary: "Do not turn unreviewed discovered work into durable repository-memory state.",
            writeBoundary,
            sideEffectBoundary
        },
        {
            kind: "separate-checkpoint-command",
            ruleCode: "MEMORY_SEPARATE_CHECKPOINT_COMMAND",
            checkpointCandidate: "A checkpoint action selected outside the orientation command.",
            instruction: "Use a separate supported checkpoint command, sync command, or explicit workflow for repository-memory writes when available.",
            repositoryMemoryBoundary: "Orientation output is candidate guidance only; it is not a checkpoint artifact and does not prove persistence.",
            writeBoundary,
            sideEffectBoundary
        },
        {
            kind: "private-memory-exclusion",
            ruleCode: "MEMORY_PRIVATE_STATE_EXCLUSION",
            checkpointCandidate: "Excluded memory surfaces: private model memory, hidden agent memory, and automatic durable repository state.",
            instruction: "Do not treat orientation output as private model memory mutation, hidden agent-state mutation, or automatic repository-memory persistence.",
            repositoryMemoryBoundary: "Durable state claims require explicit repository artifacts or supported write commands, not orientation text.",
            writeBoundary,
            sideEffectBoundary
        }
    ];
}
function buildAgentRootContext(repositoryContext) {
    const effectiveContext = repositoryContext ?? {
        root: process.cwd(),
        detectionSource: "cwd",
        warnedAboutFallback: true
    };
    const defaultPaths = {
        planningRootPath: ".day-shift/planning",
        specRootPath: "specs",
        specIndexPath: ".day-shift/specs/index.json",
        promptRootPath: ".day-shift/prompts",
        promptUserRootPath: ".day-shift/prompts/user"
    };
    const agentEntrypoint = buildAgentEntrypointStatus(effectiveContext.root);
    const baseContext = {
        effectiveRoot: effectiveContext.root,
        detectionSource: effectiveContext.detectionSource,
        detectionSourceLabel: formatDetectionSource(effectiveContext.detectionSource),
        markerPath: resolveDetectionMarkerPath(effectiveContext),
        dayShiftDirectoryPath: ".day-shift",
        configPath: ".day-shift/config.toml",
        agentEntrypointPath: ".day-shift/agents.md",
        agentEntrypoint
    };
    try {
        const resolvedConfig = (0, config_store_1.readResolvedConfig)(effectiveContext).resolved;
        return {
            ...baseContext,
            paths: {
                planningRootPath: (0, repository_relative_1.toRepositoryRelativePath)(effectiveContext.root, resolvedConfig.derived.planningRootPath),
                specRootPath: (0, repository_relative_1.toRepositoryRelativePath)(effectiveContext.root, resolvedConfig.derived.specRootPath),
                specIndexPath: (0, repository_relative_1.toRepositoryRelativePath)(effectiveContext.root, resolvedConfig.derived.specIndexPath),
                promptRootPath: (0, repository_relative_1.toRepositoryRelativePath)(effectiveContext.root, resolvedConfig.derived.promptRootPath),
                promptUserRootPath: (0, repository_relative_1.toRepositoryRelativePath)(effectiveContext.root, resolvedConfig.derived.promptUserRootPath)
            },
            config: {
                status: "resolved",
                source: "existing config loading",
                message: "Workspace paths resolved through shared config loading."
            }
        };
    }
    catch (error) {
        return {
            ...baseContext,
            paths: defaultPaths,
            config: {
                status: "unavailable",
                source: "existing config loading",
                message: getRootContextConfigErrorMessage(error)
            }
        };
    }
}
function buildAgentEntrypointStatus(repositoryRoot) {
    const absolutePath = node_path_1.default.join(repositoryRoot, runtime_contract_1.DAY_SHIFT_DIRECTORY_NAME, runtime_contract_1.AGENT_ENTRYPOINT_FILE_NAME);
    const present = node_fs_1.default.existsSync(absolutePath);
    if (present) {
        return {
            path: ".day-shift/agents.md",
            absolutePath,
            presence: "present",
            evidence: ".day-shift/agents.md exists at the resolved root.",
            firstReadGuidance: "Read .day-shift/agents.md before planning or writing."
        };
    }
    return {
        path: ".day-shift/agents.md",
        absolutePath,
        presence: "missing",
        evidence: ".day-shift/agents.md is absent at the resolved root.",
        firstReadGuidance: "Treat missing .day-shift/agents.md as evidence only; do not initialize, repair, scaffold, or materialize it."
    };
}
function resolveDetectionMarkerPath(repositoryContext) {
    if (repositoryContext.detectionSource === "config-toml") {
        return (0, repository_relative_1.toRepositoryRelativePath)(repositoryContext.root, repositoryContext.configPath ?? node_path_1.default.join(repositoryContext.root, runtime_contract_1.DAY_SHIFT_DIRECTORY_NAME, runtime_contract_1.CONFIG_FILE_NAME));
    }
    if (repositoryContext.detectionSource === "agents-md") {
        return (0, repository_relative_1.toRepositoryRelativePath)(repositoryContext.root, repositoryContext.agentEntrypointPath ?? node_path_1.default.join(repositoryContext.root, runtime_contract_1.DAY_SHIFT_DIRECTORY_NAME, runtime_contract_1.AGENT_ENTRYPOINT_FILE_NAME));
    }
    if (repositoryContext.detectionSource === "git") {
        return node_fs_1.default.existsSync(node_path_1.default.join(repositoryContext.root, ".git")) ? ".git" : null;
    }
    return null;
}
function formatDetectionSource(detectionSource) {
    switch (detectionSource) {
        case "explicit":
            return "explicit --repo-root";
        case "config-toml":
            return "nearest .day-shift/config.toml";
        case "agents-md":
            return "nearest .day-shift/agents.md";
        case "git":
            return "nearest .git";
        case "cwd":
            return "current working directory fallback";
    }
}
function getRootContextConfigErrorMessage(error) {
    if (error instanceof Error && error.message.trim().length > 0) {
        return `Workspace config could not be resolved: ${error.message}`;
    }
    return "Workspace config could not be resolved.";
}
function renderAgentCommandText(data, _options) {
    if (_options.verbose) {
        return renderAgentVerboseCommandText(data);
    }
    const validationSurface = data.commandSurfaces.find((surface) => surface.behavior === "validate");
    const validationExample = validationSurface?.examples[0];
    const commandSurfaceSummary = renderCompactCommandSurfaceSummary(data.commandSurfaces);
    const selectedEvidenceSummary = renderCompactSelectedArtifactEvidenceSummary(data.selectedArtifactEvidenceGuidance);
    const closeoutSummary = renderCompactImplementationSummaryCloseoutSummary(data.implementationSummaryCloseoutGuidance);
    const reconciliationReadinessSummary = renderCompactReconciliationReadinessSummary(data.reconciliationReadinessGuidance);
    const evidenceBoundarySummary = renderCompactCloseoutEvidenceBoundarySummary(data.closeoutEvidenceBoundaryGuidance);
    const repositoryMemorySummary = renderCompactRepositoryMemoryCheckpointSummary(data.repositoryMemoryCheckpointGuidance);
    const healthRuntimeSummary = renderCompactHealthRuntimeSummary(data.healthRuntimeGuidance);
    const migrationBlockerSummary = renderCompactMigrationBlockerSummary(data.workspaceBlockerGuidance, data.migrationRoutingGuidance);
    return [
        "Day Shift Agent Orientation",
        "Purpose:",
        `  ${data.cli.purpose}`,
        "Start here:",
        `  1. Resolve the effective workspace root (${data.rootContext.detectionSourceLabel}).`,
        `  2. ${data.rootContext.agentEntrypoint.firstReadGuidance}`,
        `  3. Run ${data.repositoryOrientation.healthChecks[0]} when setup or health is uncertain.`,
        "  4. Use read-only inventory, review, and validation commands before write-capable commands.",
        "Root context:",
        `  Effective root: ${data.rootContext.effectiveRoot}; Detection source: ${data.rootContext.detectionSourceLabel}; marker: ${data.rootContext.markerPath ?? "(none; fallback or explicit root)"}`,
        `  Agent entrypoint: ${data.rootContext.agentEntrypoint.path} (${data.rootContext.agentEntrypoint.presence})`,
        "Discovery recommendations:",
        ...data.discoveryRecommendations.map((recommendation) => `  - ${recommendation.example}: ${recommendation.useWhen} ${recommendation.sideEffectBoundary}`),
        ...(healthRuntimeSummary
            ? [
                `Health and runtime blockers: ${healthRuntimeSummary}`
            ]
            : []),
        ...(migrationBlockerSummary
            ? [`  - ${migrationBlockerSummary}`]
            : []),
        "Planning model:",
        `  ${data.planningModel.standardFlow.join(" -> ")}`,
        `  ${data.planningModel.selectedArtifactRule} ${data.planningModel.fullSetRule}`,
        `  ${data.planningModel.lightweightException} ${data.planningModel.lightweightBoundaryRules[1]} ${data.planningModel.emergentWorkRule} ${data.planningModel.emergentBoundaryRules[0]}`,
        "Repository rules:",
        ...data.workflowRules.map((rule) => `  - ${rule.instruction}`),
        "  - Preserve repository-relative paths.",
        "Command surfaces:",
        ...commandSurfaceSummary,
        "Recommended bootstrap:",
        `  ${data.recommendedBootstrap.join("; ")}`,
        "Before writing:",
        ...(validationExample
            ? [`  - Recommended check: ${validationExample}`]
            : []),
        ...(selectedEvidenceSummary
            ? [`  - ${selectedEvidenceSummary}`]
            : []),
        ...data.beforeWriting.slice(1).map((instruction) => `  - ${instruction}`),
        `Closeout: ${data.closeout[0]} ${closeoutSummary} ${reconciliationReadinessSummary} ${evidenceBoundarySummary} ${repositoryMemorySummary} ${data.closeout[4]}`
    ].join("\n");
}
function renderCompactMigrationBlockerSummary(blockers, routing) {
    const blockerKinds = blockers.map((blocker) => blocker.kind).join(", ");
    const preview = routing.find((entry) => entry.kind === "preview");
    const apply = routing.find((entry) => entry.kind === "apply");
    const manualMove = routing.find((entry) => entry.kind === "manual-move");
    if (blockerKinds.length === 0 || preview === undefined || apply === undefined || manualMove === undefined) {
        return null;
    }
    return `Stop on ${blockerKinds} workspace evidence; use ${preview.command} for no-write evidence and ${apply.command} only with explicit intent. ${manualMove.instruction}`;
}
function renderCompactHealthRuntimeSummary(guidance) {
    const setupGuidance = guidance.find((entry) => entry.kind === "setup-uncertainty");
    const configGuidance = guidance.find((entry) => entry.kind === "configuration");
    const runtimeGuidance = guidance.find((entry) => entry.kind === "runtime");
    if (setupGuidance === undefined) {
        return null;
    }
    const contextCommands = [configGuidance?.command, runtimeGuidance?.command]
        .filter((command) => command !== undefined)
        .join(" and ");
    return `${setupGuidance.instruction} Use ${setupGuidance.command} for evidence${contextCommands.length > 0 ? `, with ${contextCommands} for context` : ""}. ${setupGuidance.sideEffectBoundary}`;
}
function renderCompactCommandSurfaceSummary(surfaces) {
    const behaviorOrder = ["read", "validate", "review", "write", "mixed"];
    return behaviorOrder.flatMap((behavior) => {
        const surface = surfaces.find((candidate) => candidate.behavior === behavior);
        if (surface === undefined) {
            return [];
        }
        return [`  - ${behavior}: ${surface.examples[0]} (${surface.name}; capability: ${surface.capability}; writeCapable: ${surface.writeCapable})`];
    });
}
function renderCompactSelectedArtifactEvidenceSummary(guidance) {
    if (guidance.length === 0) {
        return null;
    }
    return `Read selected ${guidance.map((entry) => entry.kind).join(", ")} evidence before writes; guidance is read-only and does not select, validate, or complete work.`;
}
function renderCompactImplementationSummaryCloseoutSummary(guidance) {
    if (guidance.length === 0) {
        return "Record changed paths, validation, deviations, discovered work, and follow-up work.";
    }
    return renderImplementationSummaryCloseoutEvidenceList(guidance);
}
function renderCompactReconciliationReadinessSummary(guidance) {
    const gate = guidance.find((entry) => entry.kind === "task-summary-gate");
    const placeholder = guidance.find((entry) => entry.kind === "placeholder-boundary");
    const sideEffectBoundary = guidance[0]?.sideEffectBoundary;
    if (gate === undefined) {
        return "Use milestone reconciliation only after the task implementation-summary readiness gate is satisfied.";
    }
    return [
        renderReconciliationReadinessCloseoutGuidance(guidance),
        gate.reconciliationArtifactBoundary,
        placeholder?.reconciliationArtifactBoundary,
        sideEffectBoundary
    ]
        .filter((part) => part !== undefined)
        .join(" ");
}
function renderCompactCloseoutEvidenceBoundarySummary(guidance) {
    const review = guidance.find((entry) => entry.kind === "review-evidence");
    const validation = guidance.find((entry) => entry.kind === "validation-evidence");
    const error = guidance.find((entry) => entry.kind === "blocking-errors");
    const warning = guidance.find((entry) => entry.kind === "warning-review");
    const write = guidance.find((entry) => entry.kind === "separate-write-authorization");
    if (review === undefined ||
        validation === undefined ||
        error === undefined ||
        warning === undefined ||
        write === undefined) {
        return "Treat review and validation closeout outputs as evidence only; use separate write-capable commands for mutation.";
    }
    return [
        "Treat review and validation outputs as evidence only unless a separate write-capable command is selected.",
        "Validation smoke, links-check, review, and validate-update surfaces do not repair artifacts.",
        error.instruction,
        warning.instruction,
        write.writeBoundary
    ].join(" ");
}
function renderRepositoryMemoryCheckpointCloseoutGuidance(guidance) {
    const expectedKinds = [
        "stable-facts",
        "transitional-state",
        "artifact-ordering",
        "intentional-carve-outs",
        "separate-checkpoint-command",
        "private-memory-exclusion"
    ];
    if (expectedKinds.every((kind) => guidance.some((entry) => entry.kind === kind))) {
        return "Capture repository-memory checkpoint candidates only for stable facts, transitional state, artifact ordering, and intentional carve-outs; writes require a separate supported checkpoint command, sync command, or explicit workflow.";
    }
    return `Capture repository-memory checkpoint candidates only for ${guidance.map((entry) => entry.kind).join(", ")}.`;
}
function renderCompactRepositoryMemoryCheckpointSummary(guidance) {
    const separateCommand = guidance.find((entry) => entry.kind === "separate-checkpoint-command");
    const privateExclusion = guidance.find((entry) => entry.kind === "private-memory-exclusion");
    const sideEffectBoundary = guidance[0]?.sideEffectBoundary;
    if (separateCommand === undefined || privateExclusion === undefined) {
        return "Repository-memory checkpoint guidance is candidate-only and requires a separate supported write surface.";
    }
    return [
        renderRepositoryMemoryCheckpointCloseoutGuidance(guidance),
        separateCommand.repositoryMemoryBoundary,
        privateExclusion.instruction,
        sideEffectBoundary
    ]
        .filter((part) => part !== undefined)
        .join(" ");
}
function renderAgentVerboseCommandText(data) {
    return [
        "Day Shift Agent Orientation (Verbose)",
        "",
        "Purpose:",
        `  ${data.cli.purpose}`,
        "",
        "Root context:",
        `  Effective root: ${data.rootContext.effectiveRoot}`,
        `  Detection source: ${data.rootContext.detectionSourceLabel}`,
        `  Detection marker: ${data.rootContext.markerPath ?? "(none; fallback or explicit root)"}`,
        `  Day Shift directory: ${data.rootContext.dayShiftDirectoryPath}`,
        `  Config path: ${data.rootContext.configPath}`,
        `  Agent entrypoint: ${data.rootContext.agentEntrypoint.path}`,
        `  Agent entrypoint absolute path: ${data.rootContext.agentEntrypoint.absolutePath}`,
        `  Agent entrypoint presence: ${data.rootContext.agentEntrypoint.presence}`,
        `  Agent entrypoint evidence: ${data.rootContext.agentEntrypoint.evidence}`,
        `  Agent entrypoint guidance: ${data.rootContext.agentEntrypoint.firstReadGuidance}`,
        `  Config status: ${data.rootContext.config.status}`,
        `  Config source: ${data.rootContext.config.source}`,
        `  Config message: ${data.rootContext.config.message}`,
        `  Planning root: ${data.rootContext.paths.planningRootPath}`,
        `  Spec root: ${data.rootContext.paths.specRootPath}`,
        `  Spec index: ${data.rootContext.paths.specIndexPath}`,
        `  Prompt root: ${data.rootContext.paths.promptRootPath}`,
        `  User prompt root: ${data.rootContext.paths.promptUserRootPath}`,
        "",
        "Start here:",
        ...data.repositoryOrientation.rootDetectionOrder.map((source, index) => `  ${index + 1}. Root detection option: ${source}`),
        ...data.repositoryOrientation.requiredFirstReads.map((pathToRead) => `  - First read: ${pathToRead}`),
        ...data.repositoryOrientation.healthChecks.map((command) => `  - Health recommendation: ${command}`),
        "",
        "Discovery recommendations:",
        ...data.discoveryRecommendations.flatMap((recommendation) => [
            `  - ${recommendation.name}`,
            `    Command: ${recommendation.example}`,
            `    Intent: ${recommendation.intent}`,
            `    Use when: ${recommendation.useWhen}`,
            `    Discovers: ${recommendation.discovers.join(", ")}`,
            `    Boundary: ${recommendation.sideEffectBoundary}`
        ]),
        "",
        "Health and runtime guidance:",
        ...data.healthRuntimeGuidance.flatMap((guidance) => [
            `  - ${guidance.kind} (${guidance.ruleCode})`,
            `    Command: ${guidance.command}`,
            `    Instruction: ${guidance.instruction}`,
            `    Use when: ${guidance.useWhen}`,
            `    Evidence: ${guidance.evidenceProvided.join(", ")}`,
            `    Boundary: ${guidance.sideEffectBoundary}`
        ]),
        "",
        "Workspace blocker guidance:",
        ...data.workspaceBlockerGuidance.flatMap((guidance) => [
            `  - ${guidance.kind} (${guidance.ruleCode})`,
            `    Evidence: ${guidance.evidence}`,
            `    Instruction: ${guidance.instruction}`,
            `    Route: ${guidance.requiredRoute}`,
            `    Boundary: ${guidance.normalWorkBoundary}`
        ]),
        "",
        "Migration routing guidance:",
        ...data.migrationRoutingGuidance.flatMap((guidance) => [
            `  - ${guidance.kind} (${guidance.ruleCode})`,
            `    Command: ${guidance.command}`,
            `    Instruction: ${guidance.instruction}`,
            `    Boundary: ${guidance.writeBoundary}`
        ]),
        "",
        "Planning model:",
        `  Standard flow: ${data.planningModel.standardFlow.join(" -> ")}`,
        `  Selected artifact: ${data.planningModel.selectedArtifactRule}`,
        `  Next layer: ${data.planningModel.nextLayerRule}`,
        `  Full set: ${data.planningModel.fullSetRule}`,
        `  Lightweight exception: ${data.planningModel.lightweightException}`,
        ...data.planningModel.lightweightBoundaryRules.map((rule) => `  - Lightweight boundary: ${rule}`),
        `  Emergent work: ${data.planningModel.emergentWorkRule}`,
        ...data.planningModel.emergentBoundaryRules.map((rule) => `  - Emergent boundary: ${rule}`),
        "",
        "Repository rules:",
        ...data.workflowRules.map((rule) => `  - [${rule.severity}] ${rule.code}: ${rule.instruction}`),
        "",
        "Finding severity:",
        ...data.findingSeverityGuidance.map((guidance) => `  - ${guidance.severity} (${guidance.ruleCode}): ${guidance.instruction} ${guidance.requiredAction} ${guidance.proceedWhen}`),
        "",
        "No-invented-state guardrails:",
        ...data.noInventedStateGuidance.map((guidance) => `  - ${guidance.category} (${guidance.ruleCode}): ${guidance.doNotInfer} Evidence: ${guidance.evidenceRequired}`),
        "",
        "Selected-artifact evidence:",
        ...data.selectedArtifactEvidenceGuidance.map((guidance) => `  - ${guidance.kind} (${guidance.ruleCode}): ${guidance.instruction} Boundary: ${guidance.boundary}`),
        "",
        "Implementation-summary closeout evidence:",
        ...data.implementationSummaryCloseoutGuidance.flatMap((guidance) => [
            `  - ${guidance.kind} (${guidance.ruleCode})`,
            `    Responsibility: ${guidance.responsibility}`,
            `    Evidence: ${guidance.implementationSummaryEvidence}`,
            `    Completion boundary: ${guidance.completionBoundary}`,
            `    Side-effect boundary: ${guidance.sideEffectBoundary}`
        ]),
        "",
        "Reconciliation readiness:",
        ...data.reconciliationReadinessGuidance.flatMap((guidance) => [
            `  - ${guidance.kind} (${guidance.ruleCode})`,
            `    Readiness state: ${guidance.readinessState}`,
            `    Instruction: ${guidance.instruction}`,
            `    Task summary gate: ${guidance.taskSummaryGate}`,
            `    Artifact boundary: ${guidance.reconciliationArtifactBoundary}`,
            `    Side-effect boundary: ${guidance.sideEffectBoundary}`
        ]),
        "",
        "Closeout evidence boundaries:",
        ...data.closeoutEvidenceBoundaryGuidance.flatMap((guidance) => [
            `  - ${guidance.kind} (${guidance.ruleCode})`,
            `    Instruction: ${guidance.instruction}`,
            `    Evidence sources: ${guidance.evidenceSources.join("; ")}`,
            `    Required action: ${guidance.requiredAction}`,
            `    Write boundary: ${guidance.writeBoundary}`,
            `    Side-effect boundary: ${guidance.sideEffectBoundary}`
        ]),
        "",
        "Repository-memory checkpoint boundaries:",
        ...data.repositoryMemoryCheckpointGuidance.flatMap((guidance) => [
            `  - ${guidance.kind} (${guidance.ruleCode})`,
            `    Checkpoint candidate: ${guidance.checkpointCandidate}`,
            `    Instruction: ${guidance.instruction}`,
            `    Repository-memory boundary: ${guidance.repositoryMemoryBoundary}`,
            `    Write boundary: ${guidance.writeBoundary}`,
            `    Side-effect boundary: ${guidance.sideEffectBoundary}`
        ]),
        "",
        "Command surfaces:",
        ...data.commandSurfaces.flatMap((surface) => [
            `  - ${surface.name}`,
            `    Behavior: ${surface.behavior}`,
            `    Capability: ${surface.capability}`,
            `    Write capable: ${surface.writeCapable}`,
            `    Artifact family: ${surface.artifactFamily}`,
            `    Destination posture: ${surface.destinationPosture}`,
            `    Target path posture: ${surface.targetPathPosture}`,
            `    Coordination scope: ${surface.coordinationScope}`,
            `    Mutation posture: ${surface.mutationPosture}`,
            `    Examples: ${surface.examples.join("; ")}`,
            `    Boundary: ${surface.boundary}`
        ]),
        "",
        "Recommended bootstrap:",
        ...data.recommendedBootstrap.map((command) => `  - ${command}`),
        "",
        "Before writing:",
        ...data.beforeWriting.map((instruction) => `  - ${instruction}`),
        "",
        "Closeout:",
        ...data.closeout.map((instruction) => `  - ${instruction}`),
        "",
        "No-write caveat:",
        "  This orientation output is guidance only. It does not execute discovery, validation, migration, checkpoint, metadata update, planning creation, reconciliation, release, or repair commands."
    ].join("\n");
}
function renderAgentReminderText(data) {
    const rootHint = data.rootContext.detectionSourceLabel;
    const readBoundary = data.commandBoundaries.find((surface) => surface.behavior === "read");
    const validationBoundary = data.commandBoundaries.find((surface) => surface.behavior === "validate");
    const reviewBoundary = data.commandBoundaries.find((surface) => surface.behavior === "review");
    const writeBoundary = data.commandBoundaries.find((surface) => surface.behavior === "write");
    const closeoutSummary = renderCompactImplementationSummaryCloseoutSummary(data.implementationSummaryCloseoutGuidance);
    const reconciliationReadinessSummary = renderCompactReconciliationReadinessSummary(data.reconciliationReadinessGuidance);
    const evidenceBoundarySummary = renderCompactCloseoutEvidenceBoundarySummary(data.closeoutEvidenceBoundaryGuidance);
    const repositoryMemorySummary = renderCompactRepositoryMemoryCheckpointSummary(data.repositoryMemoryCheckpointGuidance);
    const closeoutBoundary = data.implementationSummaryCloseoutGuidance[0]?.completionBoundary;
    const closeoutSideEffectBoundary = data.implementationSummaryCloseoutGuidance[0]?.sideEffectBoundary;
    const ruleInstruction = (code) => data.requiredRules.find((rule) => rule.code === code)?.instruction;
    return [
        "Day Shift Agent Reminder",
        "",
        "Stop and reorient:",
        `  1. Resolve the effective workspace root${rootHint ? ` (${rootHint})` : ""}.`,
        `  2. ${data.rootContext.agentEntrypoint.firstReadGuidance}`,
        "  3. Use day-shift agent remind --format json for automation; parse the command envelope.",
        "  4. Inspect the selected artifact and upstream references before any write.",
        "",
        "Correct drift:",
        `  - ${ruleInstruction("PRESERVE_BOUNDARIES")}`,
        `  - ${ruleInstruction("RESPECT_FINDINGS")}`,
        `  - ${ruleInstruction("DO_NOT_INVENT_STATE")}`,
        `  - ${validationBoundary?.boundary}`,
        `  - ${reviewBoundary?.boundary}`,
        `  - ${readBoundary?.boundary}`,
        `  - ${writeBoundary?.boundary}`,
        "",
        "Closeout:",
        `  - ${data.closeout[0]}`,
        `  - ${closeoutSummary}`,
        ...(closeoutBoundary === undefined ? [] : [`  - ${closeoutBoundary}`]),
        ...(closeoutSideEffectBoundary === undefined ? [] : [`  - ${closeoutSideEffectBoundary}`]),
        `  - ${reconciliationReadinessSummary}`,
        `  - ${evidenceBoundarySummary} ${repositoryMemorySummary}`
    ]
        .filter((line) => line !== "  - undefined")
        .join("\n");
}
