"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.createAgentCommand = createAgentCommand;
exports.addAgentContextCommand = addAgentContextCommand;
exports.addAgentAliasCommand = addAgentAliasCommand;
exports.getRootCommand = getRootCommand;
exports.resolveAgentVerboseOption = resolveAgentVerboseOption;
exports.emitAgentOrientation = emitAgentOrientation;
exports.buildAgentOrientationData = buildAgentOrientationData;
// Agent command registration, orientation evidence, guidance, and rendering.
const errors_1 = require("../../../lib/errors");
const runtime_contract_1 = require("../../../lib/runtime/runtime-contract");
const agent_context_1 = require("../../../lib/agent-context");
const policy_resolution_1 = require("../../../lib/planning/policy-resolution");
const cli_constants_1 = require("../../../lib/config/cli-constants");
const output_1 = require("../../../lib/output");
const orientation_guidance_1 = require("./orientation-guidance");
const orientation_rendering_1 = require("./orientation-rendering");
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((_, commandInstance) => {
        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 specification/planning artifact or stored planning selection.')
        .option('--artifact <path>', 'Explicit repository-relative specification or 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((_, commandInstance) => {
        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 = (0, orientation_guidance_1.buildAgentReminderData)(orientationData);
        (0, output_1.emitSuccess)({
            command: options.commandName,
            format,
            text: (0, orientation_rendering_1.renderAgentReminderText)(data),
            data,
        });
        return;
    }
    (0, output_1.emitSuccess)({
        command: options.commandName,
        format,
        text: (0, orientation_rendering_1.renderAgentCommandText)(orientationData, { verbose: options.verbose }),
        data: orientationData,
    });
}
function buildAgentOrientationData(options = {}) {
    const rootContext = (0, orientation_rendering_1.buildAgentRootContext)(options.repositoryContext);
    const implementationSummaryCloseoutGuidance = (0, orientation_guidance_1.buildImplementationSummaryCloseoutGuidance)();
    const reconciliationReadinessGuidance = (0, orientation_guidance_1.buildReconciliationReadinessGuidance)();
    const closeoutEvidenceBoundaryGuidance = (0, orientation_guidance_1.buildCloseoutEvidenceBoundaryGuidance)();
    const repositoryMemoryCheckpointGuidance = (0, orientation_guidance_1.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',
        },
        collaboration: {
            defaultResolution: (0, policy_resolution_1.resolveCollaborationPolicy)({}),
            modes: [
                (0, policy_resolution_1.projectCollaborationPolicy)('autonomous'),
                (0, policy_resolution_1.projectCollaborationPolicy)('guided'),
                (0, policy_resolution_1.projectCollaborationPolicy)('interactive'),
            ],
            sourcePrecedence: policy_resolution_1.AGENT_MODE_SOURCE_PRECEDENCE,
            authorityBoundary: 'Agent mode changes collaboration cadence and checkpoints only; it never selects work or grants readiness, validation, approval, destructive-action, external-system, disposition, or closeout authority.',
        },
        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', cli_constants_1.CLI_SPEC_INDEX_PATH, '.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: cli_constants_1.CLI_SPEC_INDEX_PATH,
                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: 'schema-preview',
                ruleCode: 'SCHEMA_MIGRATION_PREVIEW_NO_WRITE',
                command: 'day-shift workspace migrate --target-schema-version <version> --dry-run',
                instruction: 'Use schema preview to report managed workspace-content changes before any workspace asset changes.',
                writeBoundary: 'Schema preview is evidence-only and must not be treated as structural planning, an apply request, or a completed migration.',
            },
            {
                kind: 'schema-apply',
                ruleCode: 'SCHEMA_MIGRATION_APPLY_EXPLICIT_WRITE',
                command: 'day-shift workspace migrate --target-schema-version <version> --confirm apply-workspace-migration',
                instruction: 'Use schema apply only after explicit user intent and compatible preview or health evidence.',
                writeBoundary: 'Schema apply is write-capable and must not be inferred from preview output alone.',
            },
            {
                kind: 'structural-check',
                ruleCode: 'STRUCTURAL_MIGRATION_CHECK_NO_WRITE',
                command: 'day-shift workspace migrate --check --mapping <work-unit-id=level>',
                instruction: 'Use structural check to classify legacy numbered planning units and surface unresolved level mappings without moving artifacts.',
                writeBoundary: 'Structural check is read-only evidence and does not authorize planning-layout mutation.',
            },
            {
                kind: 'structural-plan',
                ruleCode: 'STRUCTURAL_MIGRATION_PLAN_NO_WRITE',
                command: 'day-shift workspace migrate --plan --mapping <work-unit-id=level>',
                instruction: 'Use structural plan to produce the exact canonical destination mapping, preconditions, collisions, and plan digest.',
                writeBoundary: 'Structural plan is read-only evidence; recommendations and mappings do not apply themselves.',
            },
            {
                kind: 'structural-apply',
                ruleCode: 'STRUCTURAL_MIGRATION_APPLY_EXPLICIT_WRITE',
                command: 'day-shift workspace migrate --apply --expected-plan-digest <digest> --confirm apply-workspace-migration',
                instruction: 'Apply a structural migration only from the exact reviewed plan digest and explicit confirmation.',
                writeBoundary: 'Structural apply is transactional and write-capable; refresh the plan after any precondition conflict and use recorded recovery evidence after interruption.',
            },
            {
                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: {
            canonicalRoots: {
                basic: '.day-shift/planning/basic/tasks/<NN>-<task-id>/',
                structured: '.day-shift/planning/structured/<NN>-<work-id>/',
                governed: '.day-shift/planning/governed/<NN>-<slice-slug>/',
            },
            orderingContract: {
                rootMetadata: 'implementation_order',
                structuredTaskMetadata: 'sequence',
                structuredTaskPath: 'tasks/<NN>-<task-id>/',
                identityBoundary: 'Numeric prefixes are path ordering only; work ids, task ids, dependencies, attempts, reviews, validations, receipts, and closeout identities stay unprefixed.',
                compatibilityBoundary: 'Unnumbered Basic and Structured roots and direct Structured task directories remain readable compatibility inputs, never canonical new-write destinations.',
                migrationBoundary: 'Discovery and normal planning never migrate paths implicitly; structural migration requires an exact read-only plan digest and explicit apply.',
            },
            levels: [
                {
                    level: 'basic',
                    useWhen: 'Use for the fastest independent one-task path with narrow, resolved scope.',
                    structure: 'A direct task-definition and implementation-summary pair.',
                    creationCommand: 'day-shift work create --level basic',
                },
                {
                    level: 'structured',
                    useWhen: 'Use as the normal planned-feature default when multiple direct tasks need shared context.',
                    structure: 'A work overview with direct task-definition and implementation-summary pairs.',
                    creationCommand: 'day-shift work create --level structured',
                },
                {
                    level: 'governed',
                    useWhen: 'Use for staged work that needs formal review, hierarchy, and reconciliation.',
                    structure: 'An ordered slice overview with direct phase, milestone, task, review, and reconciliation descendants; optional initiative identity is non-hierarchical.',
                    creationCommand: 'day-shift work create --level governed',
                },
            ],
            standardFlow: [
                'specification',
                'workflow selection',
                'Basic | Structured | Governed',
                'implementation',
                'review and closeout',
            ],
            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 workflow: Basic uses one implementation_order-numbered direct task pair, Structured uses an implementation_order-numbered overview with parent-local sequence-numbered direct tasks, and Governed uses slice, phase, milestone, and task children.',
            fullSetRule: "Full-set creation expands only the selected parent artifact's declared immediate children and does not authorize nested downstream artifact creation.",
            lightweightException: 'Legacy lightweight planning remains a read-compatible alias for direct-task organization; new work should choose Basic or Structured explicitly.',
            lightweightBoundaryRules: [
                'Do not present lightweight and standard as the current workflow-selection model.',
                'Preserve labeled legacy lightweight artifacts as compatibility input without treating older top-level numbered roots as canonical.',
                'Promotion is an explicit user-authorized write from Basic to Structured or Governed, or from Structured to Governed; a recommendation never promotes work automatically.',
            ],
            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: [cli_constants_1.CLI_SPEC_INDEX_PATH, '.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: (0, orientation_guidance_1.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.',
            (0, orientation_guidance_1.renderImplementationSummaryCloseoutEvidenceList)(implementationSummaryCloseoutGuidance),
            (0, orientation_guidance_1.renderReconciliationReadinessCloseoutGuidance)(reconciliationReadinessGuidance),
            (0, orientation_rendering_1.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.',
            ],
        },
    };
}
