import { BUILTIN_RUN_COMMAND_MANIFEST } from "../../../contracts/builtin-run-command-manifest.js";
import { caeRegistryTablesReady, countCaeAckRows, countCaeRegistryMutationAuditRows, countCaeTraceRows, getActiveCaeRegistryVersionId, getCaeRegistryVersionMeta, insertCaeAckSatisfaction, insertCaeRegistryCheckpoint, insertCaeRegistryMutationAudit, listCaeAckSatisfactions, listCaeRegistryActivationsForVersion, listCaeRegistryArtifactsForVersion, listCaeRegistryMutationAuditRows, listCaeRegistryVersionsWithCounts, listCaeTraceSnapshotSummaries, loadCaeTraceSnapshot, openKitSqliteReadWrite, persistCaeTraceIfEnabled } from "../../../core/cae/cae-kit-sqlite.js";
import { tryHandleCaeRegistryAdminCommand } from "../../../core/cae/cae-registry-admin-cli.js";
import { evaluateActivationBundle } from "../../../core/cae/cae-evaluate.js";
import { loadCaeRegistryForKit } from "../../../core/cae/cae-registry-effective.js";
import { digestCaeRegistryContent, loadCaeRegistry } from "../../../core/cae/cae-registry-load.js";
import { replaceActiveCaeRegistryFromLoaded } from "../../../core/cae/cae-registry-sqlite.js";
import { getAtPath } from "../../../core/workspace-kit-config.js";
import { getCaeSession, getLastCaeEvalIso, storeCaeSession } from "../trace-store.js";
import { buildGuidanceRulesCatalogEnvelope, deriveGuidanceRegistryMutationCapability } from "../guidance-rules-catalog.js";
import { buildGuidanceDraftImpactMatrix, buildPreviewEvaluationContext, coerceDraftGuidanceRuleInput, synthesizeDraftArtifactAndOverlay } from "../../../core/cae/guidance-draft-impact-preview.js";
import { computeGuidanceEnforcementReadiness } from "../../../core/cae/guidance-enforcement-readiness.js";
import { buildCaeAuthoringClassificationSnapshot } from "../../../core/cae/cae-authoring-source-classification.js";
import { listWorkspaceArtifactTemplatesV1 } from "../../../core/cae/workspace-artifact-templates.js";
import { prependMaintainerDeliveryLoopGuidanceCard, prependMaintainerDeliveryPolicyGuidanceCard } from "../maintainer-delivery-guidance.js";
import { prependTaskIntakePolicyGuidanceCard } from "../task-intake-guidance.js";
import { paginateIds, requireSchemaV1 } from "../pagination.js";
function resolveStoredCaeSession(workspacePath, effective, traceId) {
    const mem = getCaeSession(traceId);
    if (mem) {
        return { record: mem, storage: "memory" };
    }
    if (getAtPath(effective, "kit.cae.persistence") !== true) {
        return null;
    }
    const db = openKitSqliteReadWrite(workspacePath, effective);
    if (!db) {
        return null;
    }
    try {
        const snap = loadCaeTraceSnapshot(db, traceId);
        if (!snap) {
            return null;
        }
        return { record: { bundle: snap.bundle, trace: snap.trace }, storage: "sqlite" };
    }
    finally {
        db.close();
    }
}
function loadRegistryForCae(workspacePath, effective) {
    const res = loadCaeRegistryForKit(workspacePath, effective);
    if (!res.ok) {
        const store = getAtPath(effective, "kit.cae.registryStore");
        return {
            ok: false,
            code: res.code,
            message: res.message,
            remediation: {
                instructionPath: store === "json"
                    ? "src/modules/context-activation/instructions/cae-list-artifacts.md"
                    : "src/modules/context-activation/instructions/cae-import-json-registry.md"
            }
        };
    }
    return { ok: true, reg: res.value };
}
const CAE_SHADOW_FEEDBACK_STATE_ID = "context-activation.cae-shadow-feedback";
function loadShadowFeedbackRows(db) {
    const row = db
        .prepare(`SELECT state_json FROM workspace_module_state WHERE module_id = ?`)
        .get(CAE_SHADOW_FEEDBACK_STATE_ID);
    if (!row)
        return [];
    try {
        const parsed = JSON.parse(row.state_json);
        if (!Array.isArray(parsed.rows))
            return [];
        return parsed.rows.filter((item) => {
            if (!item || typeof item !== "object" || Array.isArray(item))
                return false;
            const r = item;
            return (typeof r.traceId === "string" &&
                typeof r.activationId === "string" &&
                typeof r.commandName === "string" &&
                (r.signal === "useful" || r.signal === "noisy") &&
                typeof r.actor === "string" &&
                typeof r.recordedAt === "string");
        });
    }
    catch {
        return [];
    }
}
function saveShadowFeedbackRows(db, rows) {
    const now = new Date().toISOString();
    const stateJson = JSON.stringify({ schemaVersion: 1, rows: rows.slice(-1000) });
    db.prepare(`INSERT INTO workspace_module_state (module_id, state_schema_version, state_json, updated_at)
     VALUES (?, 1, ?, ?)
     ON CONFLICT(module_id) DO UPDATE SET
       state_schema_version = excluded.state_schema_version,
       state_json = excluded.state_json,
       updated_at = excluded.updated_at`).run(CAE_SHADOW_FEEDBACK_STATE_ID, stateJson, now);
}
function summarizeShadowFeedback(rows) {
    const byActivation = new Map();
    for (const row of rows) {
        const cur = byActivation.get(row.activationId) ?? {
            activationId: row.activationId,
            useful: 0,
            noisy: 0,
            total: 0
        };
        cur[row.signal] += 1;
        cur.total += 1;
        byActivation.set(row.activationId, cur);
    }
    return {
        total: rows.length,
        useful: rows.filter((r) => r.signal === "useful").length,
        noisy: rows.filter((r) => r.signal === "noisy").length,
        byActivation: [...byActivation.values()].sort((a, b) => b.total - a.total || a.activationId.localeCompare(b.activationId))
    };
}
function buildCaeExplainResponse(traceId, bundle, trace, level) {
    const fam = bundle.families;
    const summaryText = `CAE trace ${traceId}: matched policy=${fam?.policy?.length ?? 0}, think=${fam?.think?.length ?? 0}, do=${fam?.do?.length ?? 0}, review=${fam?.review?.length ?? 0}.`;
    const base = {
        schemaVersion: 1,
        traceId,
        level,
        summaryText,
        textStability: "best_effort_v1"
    };
    if (level === "verbose" && Array.isArray(trace.events)) {
        base.verboseEvents = trace.events.map((e) => ({
            seq: e.seq,
            eventType: e.eventType,
            payloadSummary: typeof e.payload === "object" && e.payload !== null
                ? JSON.stringify(e.payload).slice(0, 1024)
                : ""
        }));
    }
    return base;
}
const GUIDANCE_PRODUCT_LABELS = {
    productName: "Guidance",
    technicalName: "Context Activation Engine (CAE)",
    terms: {
        cae: "Guidance system",
        activation: "Guidance item",
        artifact: "Source rule or playbook",
        bundle: "Guidance result",
        trace: "Why this appeared",
        shadowMode: "Preview mode",
        liveMode: "Applies now",
        enforcement: "Hard stop",
        acknowledgement: "I read this guidance",
        policyApproval: "Permission for a sensitive command"
    },
    families: {
        policy: "Rules to follow",
        think: "Things to consider",
        do: "Suggested steps",
        review: "Review checks"
    }
};
const GUIDANCE_WORKFLOW_INTENT_LABELS = {
    "get-next-actions": "Find the next task",
    "list-tasks": "Review the task queue",
    "dashboard-summary": "Refresh dashboard context",
    "queue-health": "Check queue health",
    "run-transition": "Change task status",
    "cae-dashboard-summary": "Reload Guidance status",
    "cae-guidance-preview": "Preview Guidance",
    "cae-recent-traces": "Review recent checks",
    "cae-explain": "Explain a Guidance check",
    "generate-document": "Generate one document",
    "document-project": "Regenerate project docs"
};
const GUIDANCE_CURATED_WORKFLOW_NAMES = Object.keys(GUIDANCE_WORKFLOW_INTENT_LABELS);
function asRecord(value) {
    return value && typeof value === "object" && !Array.isArray(value)
        ? value
        : null;
}
function familyCountsFromBundle(bundle) {
    const families = asRecord(bundle.families);
    const count = (family) => {
        const rows = families?.[family];
        return Array.isArray(rows) ? rows.length : 0;
    };
    return {
        policy: count("policy"),
        think: count("think"),
        do: count("do"),
        review: count("review")
    };
}
function optionalString(value) {
    return typeof value === "string" && value.trim().length > 0 ? value.trim() : undefined;
}
function buildTraceSummary(traceId, bundle, evaluationContext) {
    const counts = familyCountsFromBundle(bundle);
    const pendingAcknowledgements = Array.isArray(bundle.pendingAcknowledgements)
        ? bundle.pendingAcknowledgements
        : [];
    const conflicts = asRecord(bundle.conflictShadowSummary);
    const conflictEntries = Array.isArray(conflicts?.entries) ? conflicts.entries : [];
    const ec = asRecord(evaluationContext);
    const task = asRecord(ec?.task);
    const command = asRecord(ec?.command);
    const summary = {
        traceId,
        storage: "sqlite",
        evalMode: bundle.evaluationPipelineMode === "shadow" ? "shadow" : "live",
        familyCounts: counts,
        totalGuidanceCount: counts.policy + counts.think + counts.do + counts.review,
        pendingAcknowledgementCount: pendingAcknowledgements.length,
        conflictCount: conflictEntries.length,
        bundleId: typeof bundle.bundleId === "string" ? bundle.bundleId : null
    };
    const taskId = optionalString(task?.taskId);
    const taskTitle = optionalString(task?.title);
    const commandName = optionalString(command?.name);
    if (taskId)
        summary.taskId = taskId;
    if (taskTitle)
        summary.taskTitle = taskTitle;
    if (commandName)
        summary.commandName = commandName;
    return summary;
}
function commandModuleId(commandName) {
    return BUILTIN_RUN_COMMAND_MANIFEST.find((row) => row.name === commandName)?.moduleId;
}
function summarizeGuidanceCards(bundle, reg) {
    const families = asRecord(bundle.families);
    const labelByFamily = GUIDANCE_PRODUCT_LABELS.families;
    const out = {
        policy: [],
        think: [],
        do: [],
        review: []
    };
    for (const family of ["policy", "think", "do", "review"]) {
        const rows = Array.isArray(families?.[family]) ? families[family] : [];
        out[family] = rows.map((row) => {
            const artifactIds = Array.isArray(row.artifactIds)
                ? row.artifactIds.filter((id) => typeof id === "string")
                : [];
            const sourceTitles = artifactIds
                .map((artifactId) => {
                const artifact = reg.artifactById.get(artifactId);
                return typeof artifact?.title === "string" && artifact.title.length > 0
                    ? artifact.title
                    : artifactId;
            })
                .slice(0, 5);
            return {
                activationId: String(row.activationId ?? ""),
                family,
                familyLabel: labelByFamily[family],
                title: sourceTitles[0] ?? String(row.activationId ?? "Guidance item"),
                attention: family === "policy"
                    ? "required"
                    : family === "review"
                        ? "check"
                        : "advisory",
                artifactIds,
                sourceTitles,
                priority: Number(row.priority ?? 0),
                aggregateTightness: Number(row.aggregateTightness ?? 0)
            };
        });
    }
    return out;
}
function summarizeTraceSnapshot(row) {
    return {
        ...buildTraceSummary(row.traceId, row.bundle),
        ...(row.summary ?? {}),
        traceId: row.traceId,
        createdAt: row.createdAt,
        storage: "sqlite"
    };
}
function buildCaeHealthData(workspacePath, effective, includeDetails) {
    const caeEnabled = getAtPath(effective, "kit.cae.enabled") === true;
    const persistenceEnabled = getAtPath(effective, "kit.cae.persistence") === true;
    const load = loadRegistryForCae(workspacePath, effective);
    const registryStatus = load.ok ? "ok" : "invalid";
    const issues = load.ok ? [] : [{ code: load.code, detail: load.message ?? "" }];
    const registryStore = getAtPath(effective, "kit.cae.registryStore");
    const data = {
        schemaVersion: 1,
        caeEnabled,
        persistenceEnabled,
        lastEvalAt: getLastCaeEvalIso(),
        registryStatus,
        issues,
        registryStore: typeof registryStore === "string" ? registryStore : "sqlite"
    };
    if (load.ok) {
        data.registryContentHash = load.reg.registryDigest;
        data.artifactCount = load.reg.artifactById.size;
        data.activationCount = load.reg.activationById.size;
        const db = openKitSqliteReadWrite(workspacePath, effective);
        if (db) {
            try {
                if (caeRegistryTablesReady(db)) {
                    const vid = getActiveCaeRegistryVersionId(db);
                    if (vid)
                        data.activeRegistryVersionId = vid;
                }
            }
            finally {
                db.close();
            }
        }
    }
    if (includeDetails && persistenceEnabled) {
        const db = openKitSqliteReadWrite(workspacePath, effective);
        if (db) {
            try {
                const traceRowCount = countCaeTraceRows(db);
                data.traceRowCount = traceRowCount;
                data.ackRowCount = countCaeAckRows(db);
                if (traceRowCount > 0 && data.lastEvalAt === null) {
                    data.lastEvalAtNote =
                        "lastEvalAt is process-local; persisted traces exist even when this process has not evaluated CAE yet.";
                }
            }
            finally {
                db.close();
            }
        }
        else {
            data.traceRowCount = 0;
            data.ackRowCount = 0;
        }
    }
    return data;
}
function buildGuidanceProductModel(workspacePath, effective, health, loaded) {
    const adminMutations = getAtPath(effective, "kit.cae.adminMutations") === true;
    const workflowChoices = GUIDANCE_CURATED_WORKFLOW_NAMES.map((name) => {
        const manifest = BUILTIN_RUN_COMMAND_MANIFEST.find((row) => row.name === name);
        return {
            name,
            moduleId: manifest?.moduleId ?? "",
            description: manifest?.description ?? "Common workflow",
            curated: true,
            label: GUIDANCE_WORKFLOW_INTENT_LABELS[name] ?? name
        };
    });
    const library = loaded.ok
        ? {
            artifacts: {
                artifactIds: [...loaded.reg.artifactById.keys()].sort((a, b) => a.localeCompare(b))
            },
            activations: {
                activationIds: [...loaded.reg.activationById.keys()].sort((a, b) => a.localeCompare(b))
            }
        }
        : { artifacts: { artifactIds: [] }, activations: { activationIds: [] } };
    const versions = { versions: [], source: "unavailable" };
    const db = openKitSqliteReadWrite(workspacePath, effective);
    if (db) {
        try {
            versions.versions = listCaeRegistryVersionsWithCounts(db).map((row) => ({
                versionId: row.version_id,
                createdAt: row.created_at,
                createdBy: row.created_by,
                isActive: row.is_active === 1,
                note: row.note,
                artifactCount: row.artifact_count,
                activationCount: row.activation_count
            }));
            versions.source = "sqlite";
        }
        finally {
            db.close();
        }
    }
    const registryStoreRaw = health.registryStore ?? getAtPath(effective, "kit.cae.registryStore");
    const registryStoreNormalized = typeof registryStoreRaw === "string" ? registryStoreRaw : "sqlite";
    const mutationGates = deriveGuidanceRegistryMutationCapability({
        registryStore: registryStoreNormalized,
        adminMutations
    });
    const rulesCatalog = buildGuidanceRulesCatalogEnvelope({
        loadedOk: loaded.ok,
        loaded: loaded.ok ? loaded.reg : null,
        health,
        registryStoreRaw,
        adminMutations,
        familyLabels: GUIDANCE_PRODUCT_LABELS.families,
        loadFail: loaded.ok ? undefined : { code: loaded.code, message: loaded.message }
    });
    return {
        schemaVersion: 1,
        labels: GUIDANCE_PRODUCT_LABELS,
        rulesCatalog,
        intents: {
            defaultWorkflowName: "get-next-actions",
            workflows: workflowChoices
        },
        registry: {
            status: health.registryStatus ?? "unknown",
            activeVersionId: health.activeRegistryVersionId ?? null,
            artifactCount: loaded.ok ? loaded.reg.artifactById.size : 0,
            activationCount: loaded.ok ? loaded.reg.activationById.size : 0,
            store: health.registryStore ?? "sqlite"
        },
        library,
        versions,
        mutationCapability: {
            adminMutations,
            registryStore: registryStoreNormalized,
            canMutate: mutationGates.canMutate,
            denialReason: mutationGates.denialReason,
            approvalModel: {
                caeMutationApprovalRequired: true,
                policyApprovalSeparate: true
            }
        }
    };
}
function listRecentTraceSummariesForDashboard(workspacePath, effective, limit) {
    if (getAtPath(effective, "kit.cae.persistence") !== true) {
        return {
            available: false,
            rows: [],
            count: 0,
            code: "cae-persistence-disabled",
            message: "Enable kit.cae.persistence to list durable Guidance checks."
        };
    }
    const db = openKitSqliteReadWrite(workspacePath, effective);
    if (!db) {
        return {
            available: false,
            rows: [],
            count: 0,
            code: "cae-kit-sqlite-unavailable",
            message: "Planning SQLite database not found or not openable"
        };
    }
    try {
        const rows = listCaeTraceSnapshotSummaries(db, { limit }).map(summarizeTraceSnapshot);
        return { available: true, rows, count: rows.length };
    }
    finally {
        db.close();
    }
}
function buildDashboardSummaryData(workspacePath, effective) {
    const health = buildCaeHealthData(workspacePath, effective, true);
    const loaded = loadRegistryForCae(workspacePath, effective);
    const validation = loaded.ok
        ? {
            ok: true,
            code: "cae-registry-validate-ok",
            registryContentHash: loaded.reg.registryDigest,
            artifactCount: loaded.reg.artifactById.size,
            activationCount: loaded.reg.activationById.size
        }
        : { ok: false, code: loaded.code, message: loaded.message };
    const recentTraces = listRecentTraceSummariesForDashboard(workspacePath, effective, 10);
    const acknowledgements = { available: false, count: 0, rows: [] };
    const feedback = { available: false, summary: summarizeShadowFeedback([]), rows: [] };
    const db = openKitSqliteReadWrite(workspacePath, effective);
    if (db) {
        try {
            const ackRows = listCaeAckSatisfactions(db, { limit: 10 });
            acknowledgements.available = true;
            acknowledgements.count = countCaeAckRows(db);
            acknowledgements.rows = ackRows;
            const feedbackRows = loadShadowFeedbackRows(db);
            feedback.available = true;
            feedback.summary = summarizeShadowFeedback(feedbackRows);
            feedback.rows = feedbackRows
                .slice()
                .sort((a, b) => b.recordedAt.localeCompare(a.recordedAt))
                .slice(0, 10);
        }
        finally {
            db.close();
        }
    }
    return {
        schemaVersion: 1,
        product: GUIDANCE_PRODUCT_LABELS,
        guidanceProduct: buildGuidanceProductModel(workspacePath, effective, health, loaded),
        health,
        validation,
        recentTraces,
        acknowledgements,
        feedback
    };
}
function buildCaeAuthoringCounts(snapshot) {
    const artifactSource = { default: 0, workspace: 0, override: 0 };
    const artifactStatus = {
        active: 0,
        hidden: 0,
        retired: 0,
        "missing-file": 0,
        "external-allowed": 0
    };
    const artifactType = {};
    const activationFamily = { policy: 0, think: 0, do: 0, review: 0 };
    const activationStatus = {
        active: 0,
        draft: 0,
        disabled: 0,
        hidden: 0,
        retired: 0
    };
    for (const artifact of snapshot.artifacts) {
        artifactSource[artifact.source] = (artifactSource[artifact.source] ?? 0) + 1;
        artifactStatus[artifact.status] = (artifactStatus[artifact.status] ?? 0) + 1;
        artifactType[artifact.artifactType] = (artifactType[artifact.artifactType] ?? 0) + 1;
    }
    for (const activation of snapshot.activations) {
        activationFamily[activation.family] = (activationFamily[activation.family] ?? 0) + 1;
        activationStatus[activation.status] = (activationStatus[activation.status] ?? 0) + 1;
    }
    return {
        schemaVersion: 1,
        artifactSources: artifactSource,
        artifactStatuses: artifactStatus,
        artifactTypes: artifactType,
        activationFamilies: activationFamily,
        activationStatuses: activationStatus
    };
}
function buildAuthoringSummaryData(workspacePath, effective) {
    const health = buildCaeHealthData(workspacePath, effective, true);
    const loaded = loadRegistryForCae(workspacePath, effective);
    const validation = loaded.ok
        ? {
            ok: true,
            code: "cae-registry-validate-ok",
            registryContentHash: loaded.reg.registryDigest,
            artifactCount: loaded.reg.artifactById.size,
            activationCount: loaded.reg.activationById.size
        }
        : { ok: false, code: loaded.code, message: loaded.message };
    let activeVersion = {
        schemaVersion: 1,
        versionId: typeof health.activeRegistryVersionId === "string" ? health.activeRegistryVersionId : null,
        createdAt: null,
        createdBy: null,
        note: null,
        registryDigest: loaded.ok ? loaded.reg.registryDigest : null,
        artifactCount: loaded.ok ? loaded.reg.artifactById.size : 0,
        activationCount: loaded.ok ? loaded.reg.activationById.size : 0,
        isActive: typeof health.activeRegistryVersionId === "string"
    };
    let artifactRows = [];
    let activationRows = [];
    let recentMutations = {
        available: false,
        count: 0,
        rows: [],
        code: "cae-kit-sqlite-unavailable"
    };
    const db = openKitSqliteReadWrite(workspacePath, effective);
    if (db) {
        try {
            const activeVersionId = getActiveCaeRegistryVersionId(db);
            if (activeVersionId) {
                const meta = getCaeRegistryVersionMeta(db, activeVersionId);
                artifactRows = listCaeRegistryArtifactsForVersion(db, activeVersionId);
                activationRows = listCaeRegistryActivationsForVersion(db, activeVersionId);
                activeVersion = {
                    schemaVersion: 1,
                    versionId: activeVersionId,
                    createdAt: meta?.created_at ?? null,
                    createdBy: meta?.created_by ?? null,
                    note: meta?.note ?? null,
                    registryDigest: loaded.ok ? loaded.reg.registryDigest : null,
                    artifactCount: artifactRows.length,
                    activationCount: activationRows.length,
                    isActive: true
                };
                recentMutations = {
                    available: true,
                    count: countCaeRegistryMutationAuditRows(db),
                    rows: listCaeRegistryMutationAuditRows(db, { limit: 10, versionId: activeVersionId }).map((row) => ({
                        id: row.id,
                        recordedAt: row.recorded_at,
                        actor: row.actor,
                        commandName: row.command_name,
                        versionId: row.version_id,
                        note: row.note
                    }))
                };
            }
        }
        finally {
            db.close();
        }
    }
    if (artifactRows.length === 0 && activationRows.length === 0 && loaded.ok) {
        const versionId = typeof health.activeRegistryVersionId === "string" ? health.activeRegistryVersionId : "json-registry";
        artifactRows = loaded.reg.artifacts.map((row) => {
            const record = row;
            const ref = record.ref ?? {};
            return {
                version_id: versionId,
                artifact_id: String(record.artifactId ?? ""),
                artifact_type: String(record.artifactType ?? ""),
                path: String(ref.path ?? ""),
                title: typeof record.title === "string" ? record.title : null,
                description: null,
                metadata_json: JSON.stringify({ tags: record.tags ?? [] }),
                retired_at: null
            };
        });
        activationRows = loaded.reg.activations.map((row) => {
            const record = row;
            return {
                version_id: versionId,
                activation_id: String(record.activationId ?? ""),
                family: String(record.family ?? ""),
                priority: Number(record.priority ?? 0),
                lifecycle_state: typeof record.lifecycleState === "string" ? record.lifecycleState : "active",
                scope_json: JSON.stringify(record.scope ?? {}),
                artifact_refs_json: JSON.stringify(record.artifactRefs ?? []),
                acknowledgement_json: record.acknowledgement ? JSON.stringify(record.acknowledgement) : null,
                metadata_json: JSON.stringify({ flags: record.flags ?? undefined }),
                retired_at: null
            };
        });
    }
    const registryDigest = loaded.ok ? loaded.reg.registryDigest : "unavailable";
    const snapshot = buildCaeAuthoringClassificationSnapshot({
        workspaceRoot: workspacePath,
        activeVersionId: typeof activeVersion.versionId === "string" && activeVersion.versionId.length > 0
            ? activeVersion.versionId
            : null,
        registryDigest,
        artifactRows,
        activationRows
    });
    const mutationCapability = deriveGuidanceRegistryMutationCapability({
        registryStore: typeof health.registryStore === "string" ? health.registryStore : "sqlite",
        adminMutations: getAtPath(effective, "kit.cae.adminMutations") === true
    });
    const issues = Array.isArray(health.issues) ? health.issues : [];
    return {
        schemaVersion: 1,
        product: GUIDANCE_PRODUCT_LABELS,
        activeVersion,
        artifacts: {
            count: snapshot.artifacts.length,
            rows: snapshot.artifacts
        },
        activations: {
            count: snapshot.activations.length,
            rows: snapshot.activations
        },
        counts: {
            ...buildCaeAuthoringCounts(snapshot),
            recentMutationCount: Number(recentMutations.count ?? 0)
        },
        validation,
        validationWarnings: issues,
        recentMutations,
        readiness: {
            schemaVersion: 1,
            status: validation.ok ? (mutationCapability.canMutate ? "ready" : "read-only") : "degraded",
            canRender: true,
            canMutate: mutationCapability.canMutate,
            denialReason: mutationCapability.denialReason,
            issues
        },
        workspaceArtifactMarkdownTemplates: listWorkspaceArtifactTemplatesV1().map((t) => ({
            id: t.id,
            artifactType: t.artifactType,
            title: t.title,
            contentMarkdown: t.contentMarkdown
        })),
        health
    };
}
export async function runContextActivationOnCommand(command, ctx) {
    const args = command.args ?? {};
    const name = command.name;
    const ws = ctx.workspacePath;
    const effective = ctx.effectiveConfig ?? {};
    const adminRes = tryHandleCaeRegistryAdminCommand(name, args, ws, effective);
    if (adminRes !== undefined) {
        return adminRes;
    }
    if (name === "cae-dashboard-summary") {
        const bad = requireSchemaV1(args);
        if (bad)
            return bad;
        return {
            ok: true,
            code: "cae-dashboard-summary-ok",
            data: buildDashboardSummaryData(ws, effective)
        };
    }
    if (name === "cae-authoring-summary") {
        const bad = requireSchemaV1(args);
        if (bad)
            return bad;
        return {
            ok: true,
            code: "cae-authoring-summary-ok",
            data: buildAuthoringSummaryData(ws, effective)
        };
    }
    if (name === "cae-recent-traces") {
        const bad = requireSchemaV1(args);
        if (bad)
            return bad;
        const limit = typeof args.limit === "number" ? Math.floor(args.limit) : 25;
        const recent = listRecentTraceSummariesForDashboard(ws, effective, limit);
        if (!recent.available) {
            return {
                ok: false,
                code: recent.code ?? "cae-traces-unavailable",
                message: recent.message ?? "Recent CAE traces are unavailable"
            };
        }
        return {
            ok: true,
            code: "cae-recent-traces-ok",
            data: {
                schemaVersion: 1,
                rows: recent.rows,
                count: recent.count,
                storage: "sqlite",
                retention: {
                    maxRows: 2000,
                    note: "Durable CAE trace snapshots are pruned oldest-first after 2000 rows."
                }
            }
        };
    }
    if (name === "cae-guidance-preview") {
        const bad = requireSchemaV1(args);
        if (bad)
            return bad;
        const commandName = typeof args.commandName === "string" && args.commandName.trim().length > 0
            ? args.commandName.trim()
            : "";
        if (!commandName) {
            return { ok: false, code: "invalid-args", message: "commandName is required" };
        }
        const taskId = typeof args.taskId === "string" && args.taskId.trim().length > 0
            ? args.taskId.trim()
            : undefined;
        const moduleId = typeof args.moduleId === "string" && args.moduleId.trim().length > 0
            ? args.moduleId.trim()
            : commandModuleId(commandName);
        const commandArgs = asRecord(args.commandArgs) ?? {};
        const argvSummary = typeof args.argvSummary === "string" && args.argvSummary.trim().length > 0
            ? args.argvSummary.trim()
            : undefined;
        const phase = String(args.currentKitPhase ?? getAtPath(effective, "kit.currentPhaseNumber") ?? "0");
        const evalMode = args.evalMode === "live" ? "live" : "shadow";
        const loaded = loadRegistryForCae(ws, effective);
        if (!loaded.ok)
            return loaded;
        const draftRuleRaw = args["draftRule"] ?? args["draftGuidanceRule"];
        const govEarly = args["enforcementGovernanceEvidence"];
        if (govEarly !== undefined && govEarly !== null && (draftRuleRaw === undefined || draftRuleRaw === null)) {
            return {
                ok: false,
                code: "invalid-args",
                message: "enforcementGovernanceEvidence requires draftRule on cae-guidance-preview."
            };
        }
        const knownWorkflowNames = [
            ...GUIDANCE_CURATED_WORKFLOW_NAMES,
            ...BUILTIN_RUN_COMMAND_MANIFEST.map((entry) => entry.name)
        ];
        const uniqueKnownWorkflows = [...new Set(knownWorkflowNames)];
        let overlayRegistry = loaded.reg;
        let draftImpactBlock;
        let draftFamilyForEnforcement;
        let governanceForPreview;
        if (draftRuleRaw !== undefined && draftRuleRaw !== null) {
            const parsed = coerceDraftGuidanceRuleInput(draftRuleRaw);
            if (!parsed.ok) {
                return { ok: false, code: parsed.code, message: parsed.message };
            }
            const synthesized = synthesizeDraftArtifactAndOverlay({
                workspacePath: ws,
                baseRegistry: loaded.reg,
                draft: parsed.value,
                knownWorkflowNames: uniqueKnownWorkflows
            });
            if (!synthesized.ok) {
                return { ok: false, code: synthesized.code, message: synthesized.message };
            }
            overlayRegistry = synthesized.overlay;
            draftImpactBlock = buildGuidanceDraftImpactMatrix({
                workspacePath: ws,
                effective,
                baseRegistry: loaded.reg,
                overlayRegistry: synthesized.overlay,
                scopeBuild: synthesized.scopeBuild,
                draftFamily: parsed.value.family,
                primary: {
                    label: "Primary dashboard/workflow preview",
                    commandName,
                    moduleId: moduleId?.length ? moduleId : undefined,
                    taskId,
                    commandArgs,
                    argvSummary
                },
                currentKitPhase: phase,
                evalMode
            });
            draftFamilyForEnforcement = parsed.value.family;
            const govRaw = args["enforcementGovernanceEvidence"];
            if (govRaw !== undefined && govRaw !== null) {
                if (typeof govRaw !== "object" || Array.isArray(govRaw)) {
                    return {
                        ok: false,
                        code: "invalid-args",
                        message: "enforcementGovernanceEvidence must be a JSON object."
                    };
                }
                const g = govRaw;
                if (g.schemaVersion !== 1) {
                    return {
                        ok: false,
                        code: "invalid-args",
                        message: "enforcementGovernanceEvidence.schemaVersion must be 1."
                    };
                }
                governanceForPreview = {
                    schemaVersion: 1,
                    registryMutationAuditId: typeof g.registryMutationAuditId === "string" ? g.registryMutationAuditId : undefined,
                    rollbackTargetVersionId: typeof g.rollbackTargetVersionId === "string" ? g.rollbackTargetVersionId : undefined,
                    actor: typeof g.actor === "string" ? g.actor : undefined,
                    rationale: typeof g.rationale === "string" ? g.rationale : undefined
                };
            }
        }
        const evaluationContext = buildPreviewEvaluationContext({
            workspacePath: ws,
            effective,
            commandName,
            moduleId: moduleId?.length ? moduleId : undefined,
            taskId,
            commandArgs,
            argvSummary,
            currentKitPhase: phase
        });
        const { bundle, trace, traceId } = evaluateActivationBundle(evaluationContext, overlayRegistry, {
            evalMode
        });
        const persist = getAtPath(effective, "kit.cae.persistence") === true;
        const skipPersistenceBecauseDraftImpact = !!draftImpactBlock;
        if (!skipPersistenceBecauseDraftImpact) {
            storeCaeSession(traceId, { bundle, trace });
            persistCaeTraceIfEnabled(ws, effective, persist, traceId, trace, bundle, buildTraceSummary(traceId, bundle, evaluationContext));
        }
        const cards = summarizeGuidanceCards(bundle, overlayRegistry);
        await prependMaintainerDeliveryPolicyGuidanceCard(ws, effective, taskId, cards);
        await prependTaskIntakePolicyGuidanceCard(ws, effective, taskId, commandName, commandArgs, cards);
        await prependMaintainerDeliveryLoopGuidanceCard(ws, effective, taskId, cards);
        const counts = {
            policy: cards.policy.length,
            think: cards.think.length,
            do: cards.do.length,
            review: cards.review.length
        };
        const totalGuidanceCount = counts.policy + counts.think + counts.do + counts.review;
        return {
            ok: true,
            code: "cae-guidance-preview-ok",
            data: {
                schemaVersion: 1,
                product: GUIDANCE_PRODUCT_LABELS,
                evalMode,
                modeLabel: evalMode === "shadow" ? "Preview mode" : "Applies now",
                registryContentHash: loaded.reg.registryDigest,
                traceId,
                ephemeral: skipPersistenceBecauseDraftImpact ? true : !persist,
                evaluationContext,
                bundle,
                trace,
                guidanceCards: cards,
                familyCounts: counts,
                totalGuidanceCount,
                pendingAcknowledgements: bundle.pendingAcknowledgements,
                conflictShadowSummary: bundle.conflictShadowSummary,
                ...(draftImpactBlock && draftFamilyForEnforcement
                    ? {
                        draftImpact: draftImpactBlock,
                        enforcementReadiness: computeGuidanceEnforcementReadiness(draftImpactBlock, draftFamilyForEnforcement, new Date().toISOString(), governanceForPreview)
                    }
                    : {})
            }
        };
    }
    if (name === "cae-list-artifacts") {
        const bad = requireSchemaV1(args);
        if (bad)
            return bad;
        const loaded = loadRegistryForCae(ws, effective);
        if (!loaded.ok)
            return loaded;
        const { reg } = loaded;
        let ids = [...reg.artifactById.keys()].sort((a, b) => a.localeCompare(b));
        const typeFilter = typeof args.artifactType === "string" ? args.artifactType.trim() : "";
        if (typeFilter) {
            ids = ids.filter((id) => {
                const row = reg.artifactById.get(id);
                return row && row.artifactType === typeFilter;
            });
        }
        const { page, nextCursor } = paginateIds(ids, args.limit, args.cursor);
        return {
            ok: true,
            code: "cae-list-artifacts-ok",
            data: {
                schemaVersion: 1,
                artifactIds: page,
                nextCursor
            }
        };
    }
    if (name === "cae-get-artifact") {
        const bad = requireSchemaV1(args);
        if (bad)
            return bad;
        const artifactId = typeof args.artifactId === "string" ? args.artifactId.trim() : "";
        if (!artifactId) {
            return { ok: false, code: "invalid-args", message: "artifactId is required" };
        }
        const loaded = loadRegistryForCae(ws, effective);
        if (!loaded.ok)
            return loaded;
        const row = loaded.reg.artifactById.get(artifactId);
        if (!row) {
            return {
                ok: false,
                code: "cae-artifact-not-found",
                message: `Unknown artifactId '${artifactId}'`
            };
        }
        return {
            ok: true,
            code: "cae-get-artifact-ok",
            data: {
                schemaVersion: 1,
                artifact: row
            }
        };
    }
    if (name === "cae-list-activations") {
        const bad = requireSchemaV1(args);
        if (bad)
            return bad;
        const loaded = loadRegistryForCae(ws, effective);
        if (!loaded.ok)
            return loaded;
        const { reg } = loaded;
        let ids = [...reg.activationById.keys()].sort((a, b) => a.localeCompare(b));
        const fam = typeof args.family === "string" ? args.family.trim() : "";
        if (fam) {
            ids = ids.filter((id) => {
                const row = reg.activationById.get(id);
                return row && row.family === fam;
            });
        }
        const life = typeof args.lifecycleState === "string" ? args.lifecycleState.trim() : "";
        if (life) {
            ids = ids.filter((id) => {
                const row = reg.activationById.get(id);
                return row && row.lifecycleState === life;
            });
        }
        const { page, nextCursor } = paginateIds(ids, args.limit, args.cursor);
        return {
            ok: true,
            code: "cae-list-activations-ok",
            data: {
                schemaVersion: 1,
                activationIds: page,
                nextCursor
            }
        };
    }
    if (name === "cae-get-activation") {
        const bad = requireSchemaV1(args);
        if (bad)
            return bad;
        const activationId = typeof args.activationId === "string" ? args.activationId.trim() : "";
        if (!activationId) {
            return { ok: false, code: "invalid-args", message: "activationId is required" };
        }
        const loaded = loadRegistryForCae(ws, effective);
        if (!loaded.ok)
            return loaded;
        const row = loaded.reg.activationById.get(activationId);
        if (!row) {
            return {
                ok: false,
                code: "cae-activation-not-found",
                message: `Unknown activationId '${activationId}'`
            };
        }
        return {
            ok: true,
            code: "cae-get-activation-ok",
            data: {
                schemaVersion: 1,
                activation: row
            }
        };
    }
    if (name === "cae-evaluate") {
        const bad = requireSchemaV1(args);
        if (bad)
            return bad;
        const ec = args.evaluationContext;
        if (!ec || typeof ec !== "object" || Array.isArray(ec)) {
            return { ok: false, code: "invalid-args", message: "evaluationContext object is required" };
        }
        const loaded = loadRegistryForCae(ws, effective);
        if (!loaded.ok)
            return loaded;
        const evalMode = args.evalMode === "shadow" ? "shadow" : "live";
        const { bundle, trace, traceId } = evaluateActivationBundle(ec, loaded.reg, { evalMode });
        storeCaeSession(traceId, { bundle, trace });
        const persist = getAtPath(effective, "kit.cae.persistence") === true;
        persistCaeTraceIfEnabled(ws, effective, persist, traceId, trace, bundle, buildTraceSummary(traceId, bundle, ec));
        return {
            ok: true,
            code: "cae-evaluate-ok",
            data: {
                schemaVersion: 1,
                bundle,
                trace,
                traceId,
                ephemeral: !persist
            }
        };
    }
    if (name === "cae-explain") {
        const bad = requireSchemaV1(args);
        if (bad)
            return bad;
        const level = args.level === "verbose" ? "verbose" : "summary";
        const traceIdArg = typeof args.traceId === "string" ? args.traceId.trim() : "";
        if (traceIdArg) {
            const resolved = resolveStoredCaeSession(ws, effective, traceIdArg);
            if (!resolved) {
                return {
                    ok: false,
                    code: "cae-trace-not-found",
                    message: `No trace for traceId '${traceIdArg}' (memory or persisted store)`
                };
            }
            const { record, storage } = resolved;
            const explanation = buildCaeExplainResponse(traceIdArg, record.bundle, record.trace, level);
            return {
                ok: true,
                code: "cae-explain-ok",
                data: {
                    schemaVersion: 1,
                    explanation,
                    trace: record.trace,
                    storage,
                    ephemeral: storage === "memory"
                }
            };
        }
        const ec = args.evaluationContext;
        if (!ec || typeof ec !== "object" || Array.isArray(ec)) {
            return {
                ok: false,
                code: "invalid-args",
                message: "Provide traceId or evaluationContext for cae-explain"
            };
        }
        const loaded = loadRegistryForCae(ws, effective);
        if (!loaded.ok)
            return loaded;
        const evalMode = args.evalMode === "shadow" ? "shadow" : "live";
        const { bundle, trace, traceId } = evaluateActivationBundle(ec, loaded.reg, { evalMode });
        const explanation = buildCaeExplainResponse(traceId, bundle, trace, level);
        return {
            ok: true,
            code: "cae-explain-ok",
            data: {
                schemaVersion: 1,
                explanation,
                trace
            }
        };
    }
    if (name === "cae-registry-validate" || name === "cae-validate-registry") {
        const bad = requireSchemaV1(args);
        if (bad)
            return bad;
        const loaded = loadRegistryForCae(ws, effective);
        if (!loaded.ok) {
            return {
                ok: false,
                code: loaded.code,
                message: loaded.message,
                remediation: loaded.remediation
            };
        }
        return {
            ok: true,
            code: "cae-registry-validate-ok",
            data: {
                schemaVersion: 1,
                registryContentHash: loaded.reg.registryDigest,
                artifactCount: loaded.reg.artifactById.size,
                activationCount: loaded.reg.activationById.size
            }
        };
    }
    if (name === "cae-import-json-registry") {
        const bad = requireSchemaV1(args);
        if (bad)
            return bad;
        const artRel = typeof args.artifactsRelativePath === "string" && args.artifactsRelativePath.trim().length > 0
            ? args.artifactsRelativePath.trim()
            : undefined;
        const actRel = typeof args.activationsRelativePath === "string" && args.activationsRelativePath.trim().length > 0
            ? args.activationsRelativePath.trim()
            : undefined;
        const loadedSeed = loadCaeRegistry(ws, {
            artifactsRelativePath: artRel,
            activationsRelativePath: actRel,
            /** Import must not persist rows pointing at missing or escaped paths (CAE_PLAN C2 / T892). */
            verifyArtifactPaths: true
        });
        if (!loadedSeed.ok) {
            return {
                ok: false,
                code: loadedSeed.code,
                message: loadedSeed.message ?? "",
                remediation: { instructionPath: "src/modules/context-activation/instructions/cae-registry-validate.md" }
            };
        }
        const versionIdRaw = typeof args.versionId === "string" ? args.versionId.trim() : "";
        const versionId = versionIdRaw.length > 0 ? versionIdRaw : `cae.reg.import.${Date.now()}`;
        const actor = typeof args.actor === "string" && args.actor.trim().length > 0 ? args.actor.trim() : "import";
        const note = typeof args.note === "string" ? args.note : null;
        let checkpointId;
        const db = openKitSqliteReadWrite(ws, effective);
        if (!db) {
            return {
                ok: false,
                code: "cae-kit-sqlite-unavailable",
                message: "Planning SQLite database not found or not openable"
            };
        }
        try {
            if (!caeRegistryTablesReady(db)) {
                return {
                    ok: false,
                    code: "cae-registry-sqlite-not-ready",
                    message: "Kit SQLite schema does not include CAE registry tables (upgrade workspace-kit)"
                };
            }
            replaceActiveCaeRegistryFromLoaded(db, {
                versionId,
                createdBy: actor,
                note,
                registry: loadedSeed.value
            });
            const mutationAuditId = insertCaeRegistryMutationAudit(db, {
                actor,
                commandName: "cae-import-json-registry",
                versionId,
                note,
                payload: {
                    artifactCount: loadedSeed.value.artifactById.size,
                    activationCount: loadedSeed.value.activationById.size
                }
            });
            const checkpointLabel = typeof args.checkpointLabel === "string" ? args.checkpointLabel.trim() : "";
            if (checkpointLabel.length > 0) {
                const arts = [...loadedSeed.value.artifactById.values()];
                const acts = [...loadedSeed.value.activationById.values()];
                const registryDigest = digestCaeRegistryContent(versionId, arts, acts);
                const checkpointNote = typeof args.checkpointNote === "string" && args.checkpointNote.trim().length > 0
                    ? args.checkpointNote.trim()
                    : null;
                checkpointId = insertCaeRegistryCheckpoint(db, {
                    label: checkpointLabel,
                    actor,
                    note: checkpointNote,
                    versionId,
                    registryDigest,
                    mutationIds: mutationAuditId !== undefined ? [mutationAuditId] : []
                });
            }
        }
        finally {
            db.close();
        }
        const checkpointLabelOut = typeof args.checkpointLabel === "string" ? args.checkpointLabel.trim() : "";
        return {
            ok: true,
            code: "cae-import-json-registry-ok",
            data: {
                schemaVersion: 1,
                versionId,
                artifactCount: loadedSeed.value.artifactById.size,
                activationCount: loadedSeed.value.activationById.size,
                ...(checkpointLabelOut.length > 0
                    ? {
                        checkpointLabel: checkpointLabelOut,
                        checkpointId: typeof checkpointId === "number" && Number.isFinite(checkpointId) ? checkpointId : null
                    }
                    : {})
            }
        };
    }
    if (name === "cae-health") {
        const bad = requireSchemaV1(args);
        if (bad)
            return bad;
        const includeDetails = args.includeDetails === true;
        const data = buildCaeHealthData(ws, effective, includeDetails);
        return { ok: true, code: "cae-health-ok", data };
    }
    if (name === "cae-list-acks") {
        const bad = requireSchemaV1(args);
        if (bad)
            return bad;
        const db = openKitSqliteReadWrite(ws, effective);
        if (!db) {
            return {
                ok: false,
                code: "cae-kit-sqlite-unavailable",
                message: "Planning SQLite database not found or not openable"
            };
        }
        try {
            const traceId = typeof args.traceId === "string" ? args.traceId.trim() : undefined;
            const activationId = typeof args.activationId === "string" ? args.activationId.trim() : undefined;
            const limit = typeof args.limit === "number" ? args.limit : undefined;
            const rows = listCaeAckSatisfactions(db, { traceId, activationId, limit });
            return {
                ok: true,
                code: "cae-list-acks-ok",
                data: {
                    schemaVersion: 1,
                    rows,
                    count: rows.length,
                    filters: {
                        traceId: traceId ?? null,
                        activationId: activationId ?? null
                    }
                }
            };
        }
        finally {
            db.close();
        }
    }
    if (name === "cae-record-shadow-feedback") {
        const bad = requireSchemaV1(args);
        if (bad)
            return bad;
        const traceId = typeof args.traceId === "string" ? args.traceId.trim() : "";
        const activationId = typeof args.activationId === "string" ? args.activationId.trim() : "";
        const commandName = typeof args.commandName === "string" ? args.commandName.trim() : "";
        const actor = typeof args.actor === "string" ? args.actor.trim() : "";
        const signal = args.signal === "useful" || args.signal === "noisy" ? args.signal : "";
        const note = typeof args.note === "string" && args.note.trim().length > 0 ? args.note.trim() : undefined;
        if (!traceId || !activationId || !commandName || !actor || !signal) {
            return {
                ok: false,
                code: "invalid-args",
                message: "traceId, activationId, commandName, actor, and signal ('useful'|'noisy') are required"
            };
        }
        const db = openKitSqliteReadWrite(ws, effective);
        if (!db) {
            return {
                ok: false,
                code: "cae-kit-sqlite-unavailable",
                message: "Planning SQLite database not found or not openable"
            };
        }
        try {
            const feedback = {
                traceId,
                activationId,
                commandName,
                signal,
                actor,
                recordedAt: new Date().toISOString(),
                note
            };
            const rows = [...loadShadowFeedbackRows(db), feedback];
            saveShadowFeedbackRows(db, rows);
            return {
                ok: true,
                code: "cae-record-shadow-feedback-ok",
                data: {
                    schemaVersion: 1,
                    feedback,
                    summary: summarizeShadowFeedback(rows)
                }
            };
        }
        finally {
            db.close();
        }
    }
    if (name === "cae-shadow-feedback-report") {
        const bad = requireSchemaV1(args);
        if (bad)
            return bad;
        const db = openKitSqliteReadWrite(ws, effective);
        if (!db) {
            return {
                ok: false,
                code: "cae-kit-sqlite-unavailable",
                message: "Planning SQLite database not found or not openable"
            };
        }
        try {
            const activationId = typeof args.activationId === "string" ? args.activationId.trim() : "";
            const commandName = typeof args.commandName === "string" ? args.commandName.trim() : "";
            const signal = args.signal === "useful" || args.signal === "noisy" ? args.signal : "";
            const limit = Math.min(200, Math.max(1, typeof args.limit === "number" ? Math.floor(args.limit) : 50));
            let rows = loadShadowFeedbackRows(db);
            if (activationId)
                rows = rows.filter((r) => r.activationId === activationId);
            if (commandName)
                rows = rows.filter((r) => r.commandName === commandName);
            if (signal)
                rows = rows.filter((r) => r.signal === signal);
            const sortedRows = rows
                .slice()
                .sort((a, b) => b.recordedAt.localeCompare(a.recordedAt))
                .slice(0, limit);
            return {
                ok: true,
                code: "cae-shadow-feedback-report-ok",
                data: {
                    schemaVersion: 1,
                    summary: summarizeShadowFeedback(rows),
                    rows: sortedRows,
                    filters: {
                        activationId: activationId || null,
                        commandName: commandName || null,
                        signal: signal || null
                    }
                }
            };
        }
        finally {
            db.close();
        }
    }
    if (name === "cae-conflicts") {
        const bad = requireSchemaV1(args);
        if (bad)
            return bad;
        const ec = args.evaluationContext;
        if (!ec || typeof ec !== "object" || Array.isArray(ec)) {
            return { ok: false, code: "invalid-args", message: "evaluationContext object is required" };
        }
        const loaded = loadRegistryForCae(ws, effective);
        if (!loaded.ok)
            return loaded;
        const evalMode = args.evalMode === "shadow" ? "shadow" : "live";
        const { bundle, trace, traceId } = evaluateActivationBundle(ec, loaded.reg, { evalMode });
        storeCaeSession(traceId, { bundle, trace });
        const persist = getAtPath(effective, "kit.cae.persistence") === true;
        persistCaeTraceIfEnabled(ws, effective, persist, traceId, trace, bundle);
        return {
            ok: true,
            code: "cae-conflicts-ok",
            data: {
                schemaVersion: 1,
                traceId,
                conflictShadowSummary: bundle.conflictShadowSummary,
                ephemeral: !persist
            }
        };
    }
    if (name === "cae-get-trace") {
        const bad = requireSchemaV1(args);
        if (bad)
            return bad;
        const traceId = typeof args.traceId === "string" ? args.traceId.trim() : "";
        if (!traceId) {
            return { ok: false, code: "invalid-args", message: "traceId is required" };
        }
        const resolved = resolveStoredCaeSession(ws, effective, traceId);
        if (!resolved) {
            return {
                ok: false,
                code: "cae-trace-not-found",
                message: `No trace for traceId '${traceId}' (memory or persisted store)`
            };
        }
        const { record, storage } = resolved;
        return {
            ok: true,
            code: "cae-get-trace-ok",
            data: {
                schemaVersion: 1,
                trace: record.trace,
                storage,
                ephemeral: storage === "memory"
            }
        };
    }
    if (name === "cae-satisfy-ack") {
        const bad = requireSchemaV1(args);
        if (bad)
            return bad;
        if (getAtPath(effective, "kit.cae.persistence") !== true) {
            return {
                ok: false,
                code: "cae-persistence-disabled",
                message: "Set kit.cae.persistence to true to record acknowledgement satisfaction"
            };
        }
        const traceId = typeof args.traceId === "string" ? args.traceId.trim() : "";
        const ackToken = typeof args.ackToken === "string" ? args.ackToken.trim() : "";
        const activationId = typeof args.activationId === "string" ? args.activationId.trim() : "";
        const actor = typeof args.actor === "string" ? args.actor.trim() : "";
        if (!traceId || !ackToken || !activationId || !actor) {
            return {
                ok: false,
                code: "invalid-args",
                message: "traceId, ackToken, activationId, and actor are required strings"
            };
        }
        const loadedReg = loadRegistryForCae(ws, effective);
        if (!loadedReg.ok) {
            return {
                ok: false,
                code: loadedReg.code,
                message: loadedReg.message ?? "",
                remediation: { instructionPath: "src/modules/context-activation/instructions/cae-registry-validate.md" }
            };
        }
        const actRow = loadedReg.reg.activationById.get(activationId);
        if (!actRow) {
            return {
                ok: false,
                code: "cae-activation-not-found",
                message: `Unknown activationId '${activationId}'`
            };
        }
        const ackDef = actRow.acknowledgement;
        const expectedToken = ackDef && typeof ackDef.token === "string" ? ackDef.token.trim() : "";
        if (!expectedToken) {
            return {
                ok: false,
                code: "cae-ack-not-applicable",
                message: `Activation '${activationId}' has no acknowledgement.token; registry edits stay git+PR per .ai/cae/mutation-governance.md`
            };
        }
        if (ackToken !== expectedToken) {
            return {
                ok: false,
                code: "cae-ack-token-mismatch",
                message: "ackToken does not match registry acknowledgement.token for this activation"
            };
        }
        const db = openKitSqliteReadWrite(ws, effective);
        if (!db) {
            return {
                ok: false,
                code: "cae-kit-sqlite-unavailable",
                message: "Planning SQLite database not found or not openable"
            };
        }
        try {
            const snap = loadCaeTraceSnapshot(db, traceId);
            if (!snap) {
                return {
                    ok: false,
                    code: "cae-trace-not-found",
                    message: `No persisted trace for traceId '${traceId}' — persist traces first (kit.cae.persistence + preflight or cae-evaluate).`
                };
            }
            insertCaeAckSatisfaction(db, { traceId, ackToken, activationId, actor });
        }
        finally {
            db.close();
        }
        return {
            ok: true,
            code: "cae-satisfy-ack-ok",
            data: {
                schemaVersion: 1,
                traceId,
                activationId,
                ackToken,
                actor
            }
        };
    }
    return { ok: false, code: "unknown-command", message: `Unhandled command '${name}'` };
}
