"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.buildAgentRootContext = buildAgentRootContext;
exports.buildAgentEntrypointStatus = buildAgentEntrypointStatus;
exports.resolveDetectionMarkerPath = resolveDetectionMarkerPath;
exports.formatDetectionSource = formatDetectionSource;
exports.getRootContextConfigErrorMessage = getRootContextConfigErrorMessage;
exports.renderAgentCommandText = renderAgentCommandText;
exports.renderCompactMigrationBlockerSummary = renderCompactMigrationBlockerSummary;
exports.renderCompactHealthRuntimeSummary = renderCompactHealthRuntimeSummary;
exports.renderCompactCommandSurfaceSummary = renderCompactCommandSurfaceSummary;
exports.renderCompactSelectedArtifactEvidenceSummary = renderCompactSelectedArtifactEvidenceSummary;
exports.renderCompactImplementationSummaryCloseoutSummary = renderCompactImplementationSummaryCloseoutSummary;
exports.renderCompactReconciliationReadinessSummary = renderCompactReconciliationReadinessSummary;
exports.renderCompactCloseoutEvidenceBoundarySummary = renderCompactCloseoutEvidenceBoundarySummary;
exports.renderRepositoryMemoryCheckpointCloseoutGuidance = renderRepositoryMemoryCheckpointCloseoutGuidance;
exports.renderCompactRepositoryMemoryCheckpointSummary = renderCompactRepositoryMemoryCheckpointSummary;
exports.renderAgentVerboseCommandText = renderAgentVerboseCommandText;
exports.renderAgentReminderText = renderAgentReminderText;
// Agent command registration, orientation evidence, guidance, and rendering.
const config_store_1 = require("../../../lib/config/config-store");
const cli_constants_1 = require("../../../lib/config/cli-constants");
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 orientation_guidance_1 = require("./orientation-guidance");
function buildAgentRootContext(repositoryContext) {
    const effectiveContext = repositoryContext ?? {
        root: process.cwd(),
        detectionSource: 'cwd',
        warnedAboutFallback: true,
    };
    const defaultPaths = {
        planningRootPath: '.day-shift/planning',
        specRootPath: 'specs',
        specIndexPath: cli_constants_1.CLI_SPEC_INDEX_PATH,
        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}`,
        'Collaboration:',
        `  Default mode: ${data.collaboration.defaultResolution.mode} (${data.collaboration.defaultResolution.source}); source precedence: ${data.collaboration.sourcePrecedence.join(' > ')}.`,
        `  ${data.collaboration.authorityBoundary}`,
        '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}`,
        `  Numbering: ${data.planningModel.orderingContract.identityBoundary} ${data.planningModel.orderingContract.compatibilityBoundary} ${data.planningModel.orderingContract.migrationBoundary}`,
        `  ${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 schemaPreview = routing.find((entry) => entry.kind === 'schema-preview');
    const schemaApply = routing.find((entry) => entry.kind === 'schema-apply');
    const structuralPlan = routing.find((entry) => entry.kind === 'structural-plan');
    const structuralApply = routing.find((entry) => entry.kind === 'structural-apply');
    const manualMove = routing.find((entry) => entry.kind === 'manual-move');
    if (blockerKinds.length === 0 ||
        schemaPreview === undefined ||
        schemaApply === undefined ||
        structuralPlan === undefined ||
        structuralApply === undefined ||
        manualMove === undefined) {
        return null;
    }
    return `Stop on ${blockerKinds} workspace evidence; use ${schemaPreview.command} for schema evidence or ${structuralPlan.command} for layout evidence, then use ${schemaApply.command} or ${structuralApply.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 (0, orientation_guidance_1.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 [
        (0, orientation_guidance_1.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}`,
        '',
        'Collaboration policy:',
        `  Default mode: ${data.collaboration.defaultResolution.mode} (${data.collaboration.defaultResolution.source})`,
        `  Source precedence: ${data.collaboration.sourcePrecedence.join(' > ')}`,
        ...data.collaboration.modes.map((policy) => `  ${policy.mode}: progress=${policy.progressEvents.join(',')}; checkpoints=${policy.requiredCheckpoints.join(',')}; safety=${policy.safetyStops.join(',')}`),
        `  ${data.collaboration.authorityBoundary}`,
        '',
        '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}`,
        `  Numbering: roots use ${data.planningModel.orderingContract.rootMetadata}; direct Structured tasks use ${data.planningModel.orderingContract.structuredTaskMetadata} at ${data.planningModel.orderingContract.structuredTaskPath}`,
        `  Identity and compatibility: ${data.planningModel.orderingContract.identityBoundary} ${data.planningModel.orderingContract.compatibilityBoundary} ${data.planningModel.orderingContract.migrationBoundary}`,
        `  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');
}
