@mnemo-ai/types 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/branded.ts","../src/primitives.ts","../src/relations.ts","../src/session.ts","../src/audit.ts","../src/ports.ts","../src/security.ts","../src/compositionality.ts","../src/observability.ts","../src/delta-text.ts","../src/embedding.ts","../src/provenance.ts","../src/graph-assembly.ts","../src/dashboard-aggregates.ts","../src/indexing.ts","../src/datetime.ts","../src/harness-runtime.ts","../src/harness.ts","../src/storage-errors.ts","../src/scope-ref.ts","../src/fact-hash.ts","../src/managed-collapse.ts","../src/lsh.ts","../src/pg-session.ts","../src/pg-errors.ts","../src/i18n.ts"],"names":["z","createHash"],"mappings":";;;;;;;;AAmBO,IAAM,aAAA,GAAgB,CAAC,CAAA,KAA2B;AAClD,IAAM,QAAA,GAAgB,CAAC,CAAA,KAA2B;AAClD,IAAM,YAAA,GAAgB,CAAC,CAAA,KAA2B;AAClD,IAAM,WAAA,GAAgB,CAAC,CAAA,KAA2B;AAClD,IAAM,UAAA,GAAgB,CAAC,CAAA,KAA2B;AAClD,IAAM,YAAA,GAAgB,CAAC,CAAA,KAA2B;AAClD,IAAM,YAAA,GAAgB,CAAC,CAAA,KAA2B;AAClD,IAAM,SAAA,GAAgB,CAAC,CAAA,KAA2B;AAClD,IAAM,QAAA,GAAgB,CAAC,CAAA,KAA2B;AAClD,IAAM,SAAA,GAAgB,CAAC,CAAA,KAA2B;AAClD,IAAM,aAAA,GAAgB,CAAC,CAAA,KAA2B;AAClD,IAAM,WAAA,GAAgB,CAAC,CAAA,KAA2B;AAClD,IAAM,YAAA,GAAgB,CAAC,CAAA,KAA2B;AAGzD,IAAM,iBAAA,GACJ,iEAAA;AAGK,SAAS,cAAc,CAAA,EAAoB;AAChD,EAAA,OAAO,iBAAA,CAAkB,KAAK,CAAC,CAAA;AACjC;;;ACqyBO,IAAM,eAAA,GAA4C;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OAAA,CAAQ,KAAA,CAAM,KAAK,IAAI,CAAA;AAClD,QAAA,GAAA,GAAM,IAAA,IAAQ,KAAK,MAAA,IAAU,CAAA,CAAA;AAAA,MAC/B;AAAA,IACF;AACA,IAAA,IAAI,EAAA,EAAI,OAAO,EAAE,GAAA,EAAK,IAAA,EAAK;AAAA,EAC7B;AACA,EAAA,OAAO,MAAA;AACT","file":"index.cjs","sourcesContent":["// Branded ID types — prevent accidental ID mix-ups at compile time.\n// All IDs are cuid2 strings at runtime; the brand is erased post-compilation.\n\nexport type WorkspaceId = string & { readonly _brand: \"WorkspaceId\" };\nexport type FactId = string & { readonly _brand: \"FactId\" };\nexport type DecisionId = string & { readonly _brand: \"DecisionId\" };\nexport type EpisodeId = string & { readonly _brand: \"EpisodeId\" };\nexport type EntityId = string & { readonly _brand: \"EntityId\" };\nexport type StrategyId = string & { readonly _brand: \"StrategyId\" };\nexport type WorkflowId = string & { readonly _brand: \"WorkflowId\" };\nexport type SkillId = string & { readonly _brand: \"SkillId\" };\nexport type TaskId = string & { readonly _brand: \"TaskId\" };\nexport type EventId = string & { readonly _brand: \"EventId\" };\nexport type ReasoningId = string & { readonly _brand: \"ReasoningId\" };\nexport type SessionId = string & { readonly _brand: \"SessionId\" };\nexport type RelationId = string & { readonly _brand: \"RelationId\" };\nexport type HyperedgeId = string & { readonly _brand: \"HyperedgeId\" };\n\n// Type-safe cast helpers — use at trust boundaries (DB reads, API responses).\nexport const asWorkspaceId = (s: string): WorkspaceId => s as WorkspaceId;\nexport const asFactId = (s: string): FactId => s as FactId;\nexport const asDecisionId = (s: string): DecisionId => s as DecisionId;\nexport const asEpisodeId = (s: string): EpisodeId => s as EpisodeId;\nexport const asEntityId = (s: string): EntityId => s as EntityId;\nexport const asStrategyId = (s: string): StrategyId => s as StrategyId;\nexport const asWorkflowId = (s: string): WorkflowId => s as WorkflowId;\nexport const asSkillId = (s: string): SkillId => s as SkillId;\nexport const asTaskId = (s: string): TaskId => s as TaskId;\nexport const asEventId = (s: string): EventId => s as EventId;\nexport const asReasoningId = (s: string): ReasoningId => s as ReasoningId;\nexport const asSessionId = (s: string): SessionId => s as SessionId;\nexport const asRelationId = (s: string): RelationId => s as RelationId;\n\n// UUID guard — used to reject non-UUID workspace IDs before any DB cast.\nconst WORKSPACE_UUID_RE =\n /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;\n\n/** Returns true iff `s` is a well-formed UUID (any version, case-insensitive). */\nexport function isWorkspaceId(s: string): boolean {\n return WORKSPACE_UUID_RE.test(s);\n}\n","import type { ActorType } from \"./provenance.js\";\n\n/**\n * 10 Cognitive Primitive interfaces — DATA_MODEL.md §2.1–§2.10.\n *\n * Every primitive lives in a workspace (multi-tenant RLS), has bitemporal\n * time axes (validFrom/validTo = world truth; createdAt = system discovery),\n * and participates in the Hebbian relation graph via MnemoRelation.\n *\n * Decay classes (how `worth` decays over time without recall):\n * Semantic (slow) — fact, decision, strategy, workflow, skill, reasoning\n * Episodic (medium) — episode, entity\n * Working (fast) — task (high priority items degrade if not acted on)\n * Immutable — event (no decay, no updatedAt — append-only)\n *\n * SQL GENERATED columns (worth, memory_strength) are computed by Postgres\n * triggers and are read-only on the TypeScript side.\n *\n * Quick reference — kind enums:\n * MnemoFact.kind (13): \"preference\"|\"trait\"|\"event\"|\"relationship\"|\"skill\"|\"concern\"|\n * \"architecture\"|\"bugfix\"|\"config\"|\"discovery\"|\"policy\"|\"process\"|\"other\"\n * MnemoDecision.kind (8): \"decision\"|\"architecture\"|\"policy\"|\"process\"|\"bugfix\"|\"learning\"|\"discovery\"|\"config\"\n * MnemoEntity.kind (6): \"person\"|\"organization\"|\"project\"|\"concept\"|\"place\"|\"other\"\n */\n\n// ─── §2.1 mnemo_fact ──────────────────────────────────────────────────────────\n\n/**\n * A piece of durable behavioral knowledge about a user, agent, or domain.\n *\n * Use for: user preferences, beliefs, observed traits, relationship facts.\n * Do NOT use for: architectural decisions (→ MnemoDecision), sequential events\n * (→ MnemoEpisode), or named entities (→ MnemoEntity).\n *\n * Bitemporal: validFrom/validTo = when true in the world; createdAt = system discovery.\n * Forget by setting validTo = NOW() — rows are never deleted.\n * Sensitivity ceiling is enforced via SENSITIVITY_ORDER (never string comparison, MED-23).\n */\n/**\n * Why an encrypted fact's text is not in a read (SECURITY.md §7):\n * `erased` — its actor's key was destroyed by crypto-erasure;\n * `unreadable` — no key ring is configured, or the key does not open it.\n */\nexport type FactRedaction = \"erased\" | \"unreadable\";\n\nexport interface MnemoFact {\n id: string;\n workspaceId: string;\n agentId?: string;\n actorId?: string;\n /** The platform account (mnemo_user.id) behind this write, when one exists. */\n userId?: string | null;\n actorType?: ActorType;\n scope: \"global\" | \"conversation\";\n scopeRef?: string;\n /** Multi-tenant ownership: \"workspace:<id>\" | \"user:<id>\" | \"tenant:<id>\" */\n scopeOwner?: string;\n\n statement: string;\n subject: string;\n kind:\n | \"preference\"\n | \"trait\"\n | \"event\"\n | \"relationship\"\n | \"skill\"\n | \"concern\"\n | \"architecture\"\n | \"bugfix\"\n | \"config\"\n | \"discovery\"\n | \"policy\"\n | \"process\"\n | \"other\";\n\n confidence: number;\n relevance: number;\n hitCount: number;\n lastRecalledAt?: Date;\n\n worthSuccess: number;\n worthFailure: number;\n worthAlpha: number;\n worthBeta: number;\n worth: number; // GENERATED — read-only\n\n memoryType: \"semantic\" | \"episodic\" | \"procedural\" | \"working\";\n memoryStrength: number;\n memoryStability: number;\n lastStrengthUpdate?: Date;\n\n attribution: \"user_stated\" | \"user_belief\" | \"objective_fact\" | \"inferred\";\n attributedTo?: \"user\" | \"assistant\" | \"system\";\n sourceMessageIds: string[];\n /**\n * Other memory primitive ids (facts/decisions/episodes/entities) this fact\n * references. Physical `linked_memory_ids` column — `NOT NULL DEFAULT '{}'`\n * (flatten-legacy-dual-core PR9a / D6.2). Non-optional to match the DB\n * default and the `MemoryFactSchemaForList` wire contract that requires it.\n */\n linkedMemoryIds: string[];\n\n /**\n * Correlation id for the session that produced this fact. **Not authoritative\n * and deliberately un-FK'd**: it arrives from `POST /remember`'s body and\n * nothing validates it against `mnemo_session`, so an FK would turn a stale\n * or invented id into a constraint error and lose the write — the exact\n * failure class P74 removed. Use {@link MnemoFact.episodeId} to answer \"what\n * context did this come from\". See DATA_MODEL.md §4.9.\n */\n sessionId?: string;\n extractionSource?: string;\n topicKey?: string;\n revisionCount: number;\n protocolVersion: string;\n\n entityId?: string;\n /**\n * **The canonical fact→context link.** FK to `mnemo_episode` (ON DELETE SET\n * NULL), written by the collapse through `linkSessionFactsToEpisode`, and the\n * one field `preferSourceEpisode` (spec §17) reads on every cold recall.\n *\n * Of the four ways this schema can express \"this came from that session\",\n * this is the only one with referential integrity. See DATA_MODEL.md §4.9 for\n * the other three and why they cannot be tightened.\n */\n episodeId?: string;\n\n status: \"active\" | \"merged\" | \"forgotten\";\n pinned: boolean;\n /** §11 governance: worth>0.8 ∧ confLower>0.7 → exempt from consolidation merging (MEMORY_MODEL line 1045). */\n canonical: boolean;\n /** Per-fact sensitivity ceiling — compared via SENSITIVITY_ORDER, never string equality (MED-23). */\n sensitivity: \"public\" | \"internal\" | \"confidential\" | \"restricted\";\n /**\n * Set only when the row's encrypted `statement`/`subject` could not be\n * opened on read; both then hold a placeholder (`[erased]`, `[unreadable]`)\n * instead of ciphertext. See {@link FactRedaction}.\n */\n redacted?: FactRedaction;\n mergedIntoId?: string;\n\n validFrom: Date;\n validTo?: Date;\n\n embedding?: Float32Array;\n embeddingModel?: string;\n embeddingStale: boolean;\n\n createdAt: Date;\n updatedAt: Date;\n metadata: Record<string, unknown>;\n}\n\n// ─── §2.2 mnemo_decision ──────────────────────────────────────────────────────\n\n/**\n * A logged architectural or policy decision with full rationale.\n *\n * Use for: design choices, technical policies, process decisions, ADRs.\n * Do NOT use for: behavioral preferences (→ MnemoFact) or task tracking (→ MnemoTask).\n *\n * Decisions have a `status` lifecycle: active → superseded (when a newer decision\n * replaces it, supersededById links to the replacement).\n * Decay: slow semantic decay. Architectural decisions remain relevant long-term.\n */\nexport interface MnemoDecision {\n id: string;\n workspaceId: string;\n agentId?: string;\n actorId?: string;\n userId?: string | null;\n actorType?: ActorType;\n conversationId?: string;\n /** Multi-tenant ownership: \"workspace:<id>\" | \"user:<id>\" | \"tenant:<id>\" */\n scopeOwner?: string;\n /** Project/entity scope reference (e.g. 'project-x'). Mirrors mnemo_fact.scope_ref. */\n scopeRef?: string;\n\n kind:\n | \"decision\"\n | \"architecture\"\n | \"policy\"\n | \"process\"\n | \"bugfix\"\n | \"learning\"\n | \"discovery\"\n | \"config\";\n title: string;\n body: string;\n\n topicKey?: string;\n revisionCount: number;\n normalizedHash: string;\n\n status: \"active\" | \"superseded\" | \"withdrawn\";\n supersededById?: string;\n\n decidedByUserId?: string;\n confidence?: number;\n /** Per-decision sensitivity ceiling — compared via SENSITIVITY_ORDER, never string equality (MED-23). */\n sensitivity: \"public\" | \"internal\" | \"confidential\" | \"restricted\";\n\n embedding?: Float32Array;\n embeddingModel?: string;\n embeddingStale: boolean;\n\n validFrom: Date;\n validTo?: Date;\n createdAt: Date;\n updatedAt: Date;\n metadata: Record<string, unknown>;\n}\n\n// ─── §2.3 mnemo_episode ───────────────────────────────────────────────────────\n\n/**\n * An episodic memory — a bounded narrative record of a session or event.\n *\n * Use for: conversation summaries, meeting records, project milestones.\n * Do NOT use for: individual facts extracted from a session (→ MnemoFact).\n *\n * Episodes can be hierarchical (parentEpisodeId). Root episodes (isRoot=true, parentEpisodeId=null)\n * represent top-level events. Delta episodes store only what changed relative to parent.\n * Session collapse (collapseSession in core) creates episodes from conversation turns.\n */\nexport interface MnemoEpisode {\n id: string;\n workspaceId: string;\n agentId?: string;\n actorId?: string;\n userId?: string | null;\n actorType?: ActorType;\n /** Multi-tenant ownership: \"workspace:<id>\" | \"user:<id>\" | \"tenant:<id>\" */\n scopeOwner?: string;\n\n title: string;\n narrative: string;\n occurredAt: Date;\n durationMinutes?: number;\n participants: string[];\n topics: string[];\n linkedFactIds: string[];\n\n parentEpisodeId?: string; // NULL = root\n deltaContent?: string;\n isRoot: boolean;\n depth: number;\n\n isSynthetic: boolean;\n /**\n * Correlation id for the conversation/session this episode summarises. **Not\n * authoritative and deliberately un-FK'd**: besides the collapse,\n * `@mnemo-ai/cup` writes v2 `session_id` values here during the v2→v3\n * migration, and those have no row in `mnemo_session` — an FK would break the\n * migration. See DATA_MODEL.md §4.9.\n */\n sourceConversationId?: string;\n /** Per-episode sensitivity ceiling — compared via SENSITIVITY_ORDER, never string equality (MED-23). */\n sensitivity: \"public\" | \"internal\" | \"confidential\" | \"restricted\";\n\n // P18 — bitemporal validity interval. validFrom = when this episode became valid;\n // validTo = null means currently valid; archive sets validTo = now().\n validFrom: Date;\n validTo?: Date;\n\n createdAt: Date;\n updatedAt: Date;\n metadata: Record<string, unknown>;\n}\n\n// ─── §2.4 mnemo_entity ────────────────────────────────────────────────────────\n\n/**\n * A named real-world entity that facts and episodes can reference.\n *\n * Use for: persons, organizations, projects, concepts, places.\n * Do NOT use for: facts about the entity (→ MnemoFact with entityId pointer) or\n * the entity's decisions (→ MnemoDecision).\n *\n * Canonical deduplication: canonicalId = null means this row IS canonical.\n * Aliases grow automatically as different name forms are observed (mentionCount, lastSeenAt).\n */\nexport interface MnemoEntity {\n id: string;\n workspaceId: string;\n actorId?: string;\n agentId?: string;\n /** Who WROTE this row (provenance) — the platform account, when one exists. */\n userId?: string | null;\n actorType?: ActorType;\n /** Multi-tenant ownership: \"workspace:<id>\" | \"user:<id>\" | \"tenant:<id>\" */\n scopeOwner?: string;\n\n name: string;\n kind: \"person\" | \"organization\" | \"project\" | \"concept\" | \"place\" | \"other\";\n aliases: string[];\n canonicalId?: string; // NULL = this row is canonical\n description?: string;\n /**\n * Who this row is ABOUT (subject), not who wrote it — deliberately a\n * different field from `userId` above. Only ever set via the dedicated\n * POST /entities/:id/link-user route (admin-or-self, workspace-membership\n * checked); never accepted on create/update, so an LLM cannot claim an\n * identity by supplying this field. Only valid when kind === \"person\".\n */\n linkedUserId?: string | null;\n\n firstSeenAt: Date;\n lastSeenAt: Date;\n mentionCount: number;\n /** Per-entity sensitivity ceiling — compared via SENSITIVITY_ORDER, never string equality (MED-23). */\n sensitivity: \"public\" | \"internal\" | \"confidential\" | \"restricted\";\n\n // P18 — bitemporal validity interval. validFrom = when this entity became valid;\n // validTo = null means currently valid; archive sets validTo = now().\n validFrom: Date;\n validTo?: Date;\n\n createdAt: Date;\n updatedAt: Date;\n metadata: Record<string, unknown>;\n}\n\n// ─── §2.5 mnemo_strategy ──────────────────────────────────────────────────────\n\n/**\n * A trigger→action heuristic that the agent applies recurrently.\n *\n * Use for: \"when X happens, do Y\" patterns learned from experience or policy.\n * Do NOT use for: one-off decisions (→ MnemoDecision) or task instructions (→ MnemoTask).\n *\n * worth is GENERATED from successCount/failureCount (Beta distribution mean). Strategies with\n * high worth float to the top of recall results. Low-worth strategies decay toward archival.\n */\nexport interface MnemoStrategy {\n id: string;\n workspaceId: string;\n agentId?: string;\n actorId?: string;\n userId?: string | null;\n actorType?: ActorType;\n /** Multi-tenant ownership: \"workspace:<id>\" | \"user:<id>\" | \"tenant:<id>\" */\n scopeOwner?: string;\n /** Project/entity scope reference (e.g. 'project-x'). Mirrors mnemo_fact.scope_ref. */\n scopeRef?: string;\n\n trigger: string;\n action: string;\n context?: string;\n\n relatedFacts: string[];\n memoryType: \"procedural\";\n attribution: \"user_stated\" | \"user_belief\" | \"objective_fact\" | \"inferred\";\n\n successCount: number;\n failureCount: number;\n worth: number; // GENERATED — read-only\n\n supersedesId?: string;\n status: \"active\" | \"superseded\" | \"archived\";\n /** Per-strategy sensitivity ceiling — compared via SENSITIVITY_ORDER, never string equality (MED-23). */\n sensitivity: \"public\" | \"internal\" | \"confidential\" | \"restricted\";\n\n embedding?: Float32Array;\n embeddingModel?: string;\n embeddingStale: boolean;\n\n validFrom: Date;\n validTo?: Date;\n createdAt: Date;\n updatedAt: Date;\n metadata: Record<string, unknown>;\n}\n\n// ─── §2.6 mnemo_workflow ──────────────────────────────────────────────────────\n\n/**\n * A reusable multi-step process template with ordered steps, conditions, and timing.\n *\n * Use for: standard operating procedures, repeatable agent workflows, checklists.\n * Do NOT use for: one-off task plans (→ MnemoTask) or general heuristics (→ MnemoStrategy).\n *\n * Versioned: previousVersionId links to the superseded version. executionCount and\n * successRate track runtime performance to inform worth decay.\n */\n\nexport interface WorkflowStep {\n order: number;\n action: string;\n condition?: string;\n expectedDurationMs: number;\n tools?: string[];\n}\n\nexport interface MnemoWorkflow {\n id: string;\n workspaceId: string;\n actorId?: string;\n agentId?: string;\n userId?: string | null;\n actorType?: ActorType;\n /** Multi-tenant ownership: \"workspace:<id>\" | \"user:<id>\" | \"tenant:<id>\" */\n scopeOwner?: string;\n /** Project/entity scope reference (e.g. 'project-x'). Mirrors mnemo_fact.scope_ref. */\n scopeRef?: string;\n\n name: string;\n description?: string;\n steps: WorkflowStep[];\n\n avgDurationMs: number;\n successRate: number;\n worth: number;\n executionCount: number;\n lastExecutedAt?: Date;\n\n version: number;\n previousVersionId?: string;\n status: \"active\" | \"deprecated\" | \"draft\";\n /** Per-workflow sensitivity ceiling — compared via SENSITIVITY_ORDER, never string equality (MED-23). */\n sensitivity: \"public\" | \"internal\" | \"confidential\" | \"restricted\";\n\n // P18 — bitemporal validity interval. validFrom = when this workflow became valid;\n // validTo = null means currently valid; archive sets validTo = now().\n validFrom: Date;\n validTo?: Date;\n\n createdAt: Date;\n updatedAt: Date;\n metadata: Record<string, unknown>;\n}\n\n// ─── §2.7 mnemo_skill ─────────────────────────────────────────────────────────\n\n/**\n * A stored prompt template for a repeatable task.\n *\n * Use for: prompt engineering building blocks, reusable generation patterns.\n * Do NOT use for: process templates with conditional steps (→ MnemoWorkflow) or\n * trigger→action heuristics (→ MnemoStrategy).\n *\n * qualityScore tracks runtime effectiveness; usageCount drives worth.\n * Embeddings allow semantic retrieval (\"find a skill for writing SQL from natural language\").\n */\nexport interface MnemoSkill {\n id: string;\n workspaceId: string;\n actorId?: string;\n agentId?: string;\n userId?: string | null;\n actorType?: ActorType;\n /** Multi-tenant ownership: \"workspace:<id>\" | \"user:<id>\" | \"tenant:<id>\" */\n scopeOwner?: string;\n\n name: string;\n promptTemplate: string;\n variables: string[];\n requiredContext: string[];\n\n qualityScore: number;\n worth: number;\n usageCount: number;\n lastUsedAt?: Date;\n /** Per-skill sensitivity ceiling — compared via SENSITIVITY_ORDER, never string equality (MED-23). */\n sensitivity: \"public\" | \"internal\" | \"confidential\" | \"restricted\";\n\n embedding?: Float32Array;\n embeddingModel?: string;\n embeddingStale: boolean;\n\n // P18 — bitemporal validity interval. validFrom = when this skill became valid;\n // validTo = null means currently valid; archive sets validTo = now().\n validFrom: Date;\n validTo?: Date;\n\n createdAt: Date;\n updatedAt: Date;\n metadata: Record<string, unknown>;\n}\n\n// ─── §2.8 mnemo_task ──────────────────────────────────────────────────────────\n\n/**\n * A tracked action item with a full lifecycle and delegation chain.\n *\n * Use for: work items, reminders, delegated actions, subtasks with blocking chains.\n * Do NOT use for: general heuristics (→ MnemoStrategy) or process templates (→ MnemoWorkflow).\n *\n * blockedBy and subtaskIds form a DAG. parentTaskId enables hierarchical decomposition.\n * Decay: fast (working memory class) — high-priority tasks that are not acted on lose worth.\n */\nexport interface MnemoTask {\n id: string;\n workspaceId: string;\n actorId?: string;\n agentId?: string;\n userId?: string | null;\n actorType?: ActorType;\n /** Multi-tenant ownership: \"workspace:<id>\" | \"user:<id>\" | \"tenant:<id>\" */\n scopeOwner?: string;\n\n title: string;\n description?: string;\n status: \"pending\" | \"in_progress\" | \"blocked\" | \"delegated\" | \"completed\" | \"cancelled\";\n priority: \"critical\" | \"high\" | \"medium\" | \"low\";\n\n assignedTo: string;\n delegatedBy?: string;\n delegatedAt?: Date;\n\n blockedBy: string[];\n subtaskIds: string[];\n parentTaskId?: string;\n\n relatedFacts: string[];\n relatedEntities: string[];\n sessionId?: string;\n\n outcome?: string;\n lessonsLearned?: string;\n /** Per-task sensitivity ceiling — compared via SENSITIVITY_ORDER, never string equality (MED-23). */\n sensitivity: \"public\" | \"internal\" | \"confidential\" | \"restricted\";\n\n startedAt?: Date;\n completedAt?: Date;\n dueAt?: Date;\n\n // P18 — bitemporal validity interval. validFrom = when this task became valid;\n // validTo = null means currently valid; archiveTask always sets validTo=now(),\n // and sets status='cancelled' only when the task is not already terminal\n // (completed/cancelled) — see TERMINAL_TASK_STATUSES (ports.ts).\n validFrom: Date;\n validTo?: Date;\n\n createdAt: Date;\n updatedAt: Date;\n metadata: Record<string, unknown>;\n}\n\n// ─── §2.9 mnemo_event ─────────────────────────────────────────────────────────\n\n/**\n * An immutable record of something that happened. Events are append-only.\n *\n * Use for: system events, external webhooks, calendar events, audit trail entries.\n * Do NOT use for: mutable state (→ MnemoFact) or sequential narratives (→ MnemoEpisode).\n *\n * IMPORTANT: Events have no `updatedAt`. Once written, an event row never changes.\n * Annotations are appended via the annotations array (JSONB), not by editing the row.\n * Decay: IMMUTABLE — events do not decay. They accumulate forever (partitioned by occurredAt).\n */\n\nexport interface EventAnnotation {\n author: string;\n content: string;\n at: Date;\n}\n\nexport interface MnemoEvent {\n id: string;\n workspaceId: string;\n agentId?: string;\n actorId?: string;\n userId?: string | null;\n actorType?: ActorType;\n /** Multi-tenant ownership: \"workspace:<id>\" | \"user:<id>\" | \"tenant:<id>\" */\n scopeOwner?: string;\n\n type: \"system\" | \"external\" | \"user\" | \"agent\" | \"scheduled\";\n name: string;\n description: string;\n occurredAt: Date;\n durationS?: number;\n\n source: string;\n relatedEntities: string[];\n annotations: EventAnnotation[];\n /** Per-event sensitivity ceiling — compared via SENSITIVITY_ORDER, never string equality (MED-23).\n * Raise-only: once set, can only be elevated, never lowered (append-only principle). */\n sensitivity: \"public\" | \"internal\" | \"confidential\" | \"restricted\";\n\n // Events are immutable — no updatedAt\n createdAt: Date;\n metadata: Record<string, unknown>;\n}\n\n// ─── §2.10 mnemo_reasoning ────────────────────────────────────────────────────\n\n/**\n * A stored chain-of-thought — a question, its reasoning steps, and the conclusion reached.\n *\n * Use for: caching successful reasoning patterns, building a \"how I solved X\" library.\n * Do NOT use for: final answers/facts (→ MnemoFact) or process steps (→ MnemoWorkflow).\n *\n * worth is GENERATED and decays with disuse — the system prioritises reasoning that\n * has been recalled and applied multiple times. Embeddings are on the `question` field\n * to enable semantic retrieval of \"find how I reasoned about problems like this\".\n *\n * `status` remains the retrieval gate (searchReasoning filters on\n * `status IN ('active','golden')`) — `validTo` is the audit axis only, not a\n * read predicate. Do not swap the two.\n */\n\nexport interface ReasoningStep {\n step: number;\n reasoning: string;\n conclusion?: string;\n}\n\nexport interface MnemoReasoning {\n id: string;\n workspaceId: string;\n agentId?: string;\n actorId?: string;\n userId?: string | null;\n actorType?: ActorType;\n /** Multi-tenant ownership: \"workspace:<id>\" | \"user:<id>\" | \"tenant:<id>\" */\n scopeOwner?: string;\n\n question: string;\n chain: ReasoningStep[];\n conclusion: string;\n\n successCount: number;\n failureCount: number;\n worth: number; // GENERATED — read-only\n\n topicKey?: string;\n embedding?: Float32Array;\n embeddingModel?: string;\n embeddingStale: boolean;\n\n status: \"active\" | \"archived\" | \"pruned\" | \"quarantined\" | \"golden\";\n lastUsedAt?: Date;\n usageCount: number;\n /** Per-reasoning sensitivity ceiling — compared via SENSITIVITY_ORDER, never string equality (MED-23). */\n sensitivity: \"public\" | \"internal\" | \"confidential\" | \"restricted\";\n\n // P64 — bitemporal validity interval. validFrom = when this reasoning became valid;\n // validTo = null means currently valid; archiveReasoning sets validTo = now().\n validFrom: Date;\n validTo?: Date;\n\n createdAt: Date;\n updatedAt: Date;\n metadata: Record<string, unknown>;\n}\n\n// ─── §2.11 mnemo_hyperedge ──────────────────────────────────────────────────\n\n/**\n * An n-ary relation connecting 3 or more memory primitives.\n *\n * Use for: groups of memories that co-activate together under a shared context.\n * Do NOT use for: binary relations between two primitives (→ MnemoRelation via memory_relate).\n *\n * Hebbian: activationCount bumps each time any member is recalled together with the others\n * (bumpHyperedgeActivation, driven by hyperedge_bump events in the OutboxWorker) — it only\n * increments activation_count, never touches worth.\n * worth is a plain `real` column, default 0.5 at creation — NOT a Beta-Bernoulli posterior\n * (no alpha/beta or success/failure counters here). StorageAdapter.updateWorth() does have a\n * \"hyperedge\" case (±0.1 TD(λ)-style step, clamped to [0,1]) implemented identically in both\n * DrizzleStorageAdapter/RecallRepository and InMemoryStorageAdapter, but nothing in the\n * current call graph ever invokes updateWorth with kind \"hyperedge\": memory_self_edit's\n * strengthen/weaken only targets fact/strategy, and PATCH /hyperedges/:id only accepts\n * label/description/contextQuery, not worth. So in practice worth stays frozen at its\n * creation-time value unless a future caller wires up that update path.\n * Bitemporal: validFrom/validTo = membership window; createdAt = discovery time.\n * NOTE: No metadata column on the underlying table. No contextEmbeddingModel column.\n */\nexport interface MnemoHyperedge {\n id: string;\n workspaceId: string;\n memberIds: string[];\n label?: string;\n description?: string;\n contextQuery?: string;\n contextEmbedding?: Float32Array;\n activationCount: number;\n worth: number;\n validFrom: Date;\n validTo?: Date;\n createdAt: Date;\n actorId?: string;\n /** The platform account (mnemo_user.id) behind this write, when one exists. */\n userId?: string | null;\n actorType?: ActorType;\n}\n\n// ─── §32 Compositionality ──────────────────────────────────────────────────\n\nexport interface MnemoCompositionRule {\n id: string;\n workspaceId: string;\n name: string;\n description?: string;\n conditionDsl: unknown;\n actionDsl: unknown;\n priority: number;\n isActive: boolean;\n executionCount: number;\n createdBy?: string;\n source: \"manual\" | \"mined\" | \"imported\";\n metadata: Record<string, unknown>;\n createdAt: Date;\n updatedAt: Date;\n}\n\nexport interface MnemoInferenceLogEntry {\n id: string;\n workspaceId: string;\n ruleId: string;\n inputFactIds: string[];\n derivedKind?: string;\n derivedId?: string;\n confidence: number;\n rationale?: string;\n triggeredByQuery?: string;\n conversationId?: string;\n createdAt: Date;\n}\n\nexport interface MnemoFactHash {\n workspaceId: string;\n statementHash: string;\n factId: string;\n firstSeenAt: Date;\n lastSeenAt: Date;\n seenCount: number;\n}\n\n// ─── §31 Meta-cognition view rows ──────────────────────────────────────────\n\nexport interface ConfidenceMapRow {\n workspaceId: string;\n // Entity-keyed (spec §31, migration 0020).\n entityId: string;\n canonicalName: string;\n kind: string;\n factCount: number;\n avgConfidence: number;\n coverageLevel: \"expert\" | \"familiar\" | \"aware\" | \"minimal\" | \"blind\";\n freshness: \"current\" | \"recent\" | \"aging\" | \"stale\";\n // Back-compat / aggregate fields (topicKey aliases canonicalName).\n topicKey: string;\n memoryCount: number;\n avgWorth: number;\n evidenceVolume: number;\n distinctAttributions: number;\n pinnedCount: number;\n lowStrengthCount: number;\n lastUpdatedAt: Date;\n}\n\nexport interface KnowledgeGapRow {\n workspaceId: string;\n topicKey: string;\n avgWorth: number;\n evidenceVolume: number;\n memoryCount: number;\n recallHits30d: number;\n gapScore: number;\n}\n\nexport interface TrendPair {\n current: number;\n previous: number;\n delta: number;\n}\n\nexport interface MetacognitionTrends {\n recallHitRate: TrendPair;\n /** PROXY: AVG(activation_score) — mnemo_recall_log has no latency column. */\n avgRecallLatency: TrendPair;\n sessionCollapseQuality: TrendPair;\n strategySuccessRate: TrendPair;\n}\n\n// ─── Anticipation view rows (ALGORITHMS.md §8) ──────────────────────────────\n\nexport interface SequentialPatternRow {\n workspaceId: string;\n predecessorId: string;\n successorId: string;\n support: number;\n avgLagSeconds: number;\n confidence: number;\n}\n\nexport interface PeriodicPatternRow {\n workspaceId: string;\n memoryId: string; // alias for fact_id in the MV\n dayOfWeek: number;\n hourBucket: number;\n slotRecalls: number;\n distinctWeeks: number;\n slotShare: number;\n}\n\nexport interface ConditionalPatternRow {\n workspaceId: string;\n queryKey: string;\n factId: string;\n coReturns: number;\n queryTotal: number;\n confidence: number;\n}\n\nexport interface CoOccurrencePatternRow {\n workspaceId: string;\n sourceId: string;\n partnerId: string;\n coRecallCount: number;\n hebbianWeight: number;\n}\n\n// ─── Union: any cognitive primitive ───────────────────────────────────────────\n\nexport type CognitivePrimitive =\n | MnemoFact\n | MnemoDecision\n | MnemoEpisode\n | MnemoEntity\n | MnemoStrategy\n | MnemoWorkflow\n | MnemoSkill\n | MnemoTask\n | MnemoEvent\n | MnemoReasoning;\n\nexport type PrimitiveKind =\n | \"fact\"\n | \"decision\"\n | \"episode\"\n | \"entity\"\n | \"strategy\"\n | \"workflow\"\n | \"skill\"\n | \"task\"\n | \"event\"\n | \"reasoning\"\n | \"hyperedge\";\n\n/** Runtime companion to {@link PrimitiveKind} — validate untyped API input against this. */\nexport const PRIMITIVE_KINDS: readonly PrimitiveKind[] = [\n \"fact\",\n \"decision\",\n \"episode\",\n \"entity\",\n \"strategy\",\n \"workflow\",\n \"skill\",\n \"task\",\n \"event\",\n \"reasoning\",\n \"hyperedge\",\n];\n\n/**\n * Per-{@link PrimitiveKind} subtype enums (the `subtype` field on\n * RememberRequest). Only \"fact\", \"decision\", and \"entity\" have a real\n * subtype taxonomy today — the rest have no subtype concept and `subtype`\n * is ignored for them.\n */\nexport const PRIMITIVE_SUBTYPES = {\n // Q-3: architecture … process are the categories agents file facts under\n // (the decision vocabulary). Not \"decision\" itself: a fact whose kind names\n // another primitive is hydrated as that primitive by recall.\n fact: [\n \"preference\",\n \"trait\",\n \"event\",\n \"relationship\",\n \"skill\",\n \"concern\",\n \"architecture\",\n \"bugfix\",\n \"config\",\n \"discovery\",\n \"policy\",\n \"process\",\n \"other\",\n ],\n decision: [\n \"decision\",\n \"architecture\",\n \"policy\",\n \"process\",\n \"bugfix\",\n \"learning\",\n \"discovery\",\n \"config\",\n ],\n entity: [\"person\", \"organization\", \"project\", \"concept\", \"place\", \"other\"],\n} as const satisfies Partial<Record<PrimitiveKind, readonly string[]>>;\n\n// ─── §2.13 mnemo_agent_profile (Wave M2 — spec §13 self-editing memory) ─────\n\n/**\n * Per-agent self-model / profile store.\n * Populated and rewritten by the reflection cycle (runReflectionCycle).\n * One row per (workspace_id, agent_id) — upserted on every reflection pass.\n */\nexport interface MnemoAgentProfile {\n workspaceId: string;\n agentId: string;\n /** Free-text summary generated by the last reflection cycle. */\n summary: string;\n /**\n * Flexible metadata bag.\n * Reserved keys: sessionsSinceReflection (number), lastReflectionAt (ISO string).\n */\n metadata: Record<string, unknown>;\n createdAt: Date;\n updatedAt: Date;\n}\n","// Relationship infrastructure types — DATA_MODEL.md §3\n// mnemo_relation, mnemo_hyperedge, mnemo_citation\n\nimport type { ActorType } from \"./provenance.js\";\nimport type { MnemoEntity } from \"./primitives.js\";\nimport type { Sensitivity } from \"./common.js\";\n\n/**\n * The 9 locked relation verbs. This set is CLOSED — do not add values here\n * without a matching SQL migration that updates the CHECK constraint in\n * packages/adapter-postgres/migrations/v3/0001_baseline.sql.\n *\n * Semantics:\n * \"related\" — Generic symmetric link. Use when no more specific verb applies.\n * \"compatible\" — A and B are known to work together (e.g. two tools, two strategies).\n * \"scoped\" — A applies within the scope of B (A is narrower than B).\n * \"conflicts_with\" — A and B contradict each other; both cannot be true simultaneously.\n * \"supersedes\" — A replaces B (B is outdated). B should have status \"superseded\".\n * \"not_conflict\" — Explicit disambiguation: A and B look contradictory but are not.\n * \"derived_from\" — A was extracted, inferred, or synthesised from B.\n * \"part_of\" — A is a structural component of B.\n * \"member_of\" — A belongs to group or category B.\n *\n * Hebbian learning: `weight` on MnemoRelation strengthens when both endpoints\n * are co-recalled in the same query. This drives the activation cascade in stage 4\n * of the recall pipeline (recall-cold.ts).\n */\nexport type RelationVerb =\n | \"related\"\n | \"compatible\"\n | \"scoped\"\n | \"conflicts_with\"\n | \"supersedes\"\n | \"not_conflict\"\n | \"derived_from\"\n | \"part_of\"\n | \"member_of\";\n\n/**\n * Judgment-workflow status (flatten-legacy-dual-core D6.4). Matches the\n * physical `mnemo_relation.judgment_status` column and legacy\n * `core/src/graph/relation.ts`'s `JudgmentStatus`.\n */\nexport type JudgmentStatus = \"pending\" | \"judged\" | \"dismissed\";\n\n/** Who/what applied a judgment. Matches `mnemo_relation.marked_by_kind`. */\nexport type MarkerKind = \"user\" | \"agent\" | \"system\" | \"llm_judge\";\n\n/**\n * Primitive kinds that can be a `mnemo_relation` endpoint — enforced\n * physically by `mnemo_relation_source_kind_check`/`mnemo_relation_target_kind_check`\n * (migration 0045 widened them from the original fact/decision/entity/episode\n * to every non-hyperedge primitive, so strategies, workflows, skills, tasks,\n * events and reasoning can be related and lineage edges can point at them).\n * A hyperedge is itself an n-ary relation and is not a binary endpoint.\n */\nexport type RelationNodeKind =\n | \"fact\"\n | \"decision\"\n | \"entity\"\n | \"episode\"\n | \"strategy\"\n | \"workflow\"\n | \"skill\"\n | \"task\"\n | \"event\"\n | \"reasoning\";\n\n/** Runtime companion to {@link RelationNodeKind}. */\nexport const RELATION_NODE_KINDS: readonly RelationNodeKind[] = [\n \"fact\",\n \"decision\",\n \"entity\",\n \"episode\",\n \"strategy\",\n \"workflow\",\n \"skill\",\n \"task\",\n \"event\",\n \"reasoning\",\n];\n\n/**\n * `mnemo_relation` is ONE physical table carrying TWO overlays on the same\n * row (flatten-legacy-dual-core D6.4, verified against\n * `adapter-postgres/src/schema/relations.ts:6-40`):\n * - Hebbian co-recall learning (`weight`/`coRecallCount`/`directionality`/\n * `lastCoRecallAt`) — driven by the recall pipeline's STDP updates.\n * - Judgment workflow (`judgmentStatus`/`reason`/`evidence`/`confidence`/\n * `markedBy*`/`provenance`/`conversationId`/`supersededByRelationId`/\n * `validFrom`/`validTo`) — driven by conflict resolution / memory_judge.\n *\n * There is no separate free-form `metadata` field: the physical table has\n * no `metadata` column at all. The previous `MnemoRelation.metadata` was a\n * fiction that silently aliased onto the `evidence` column in\n * `GraphRepository.createRelation` — every relation write (even pure\n * Hebbian ones with no judgment intent) forced `evidence` to a non-null\n * `{}` instead of leaving the judgment overlay's natural unset (`null`)\n * state alone. `evidence` is now the real, correctly-named, nullable field.\n */\nexport interface MnemoRelation {\n id: string;\n workspaceId: string;\n\n sourceId: string;\n sourceType: RelationNodeKind;\n targetId: string;\n targetType: RelationNodeKind;\n\n verb: RelationVerb;\n weight: number; // Hebbian weight [0,1] — updated on co-recall\n\n /** Timestamp of the last co-recall event — used to compute STDP Δt (Wave Y, §25.3). */\n lastCoRecallAt?: Date;\n /** Number of times both endpoints have been co-recalled together (Hebbian overlay). */\n coRecallCount: number;\n /** Directional STDP bias in [-1, 1] (Hebbian overlay). */\n directionality: number;\n\n createdAt: Date;\n updatedAt: Date;\n\n actorId?: string;\n /** The platform account (mnemo_user.id) behind this write, when one exists. */\n userId?: string | null;\n actorType?: ActorType;\n\n /**\n * Bitemporal validity window. Both columns exist physically on\n * `mnemo_relation` (`valid_from NOT NULL DEFAULT now()`, `valid_to`\n * nullable) — always present, unlike the write-provenance triple above.\n */\n validFrom: Date;\n validTo: Date | null;\n\n /**\n * Judgment-workflow overlay (flatten-legacy-dual-core D6.4) — all fields\n * already exist physically on `mnemo_relation` and are already modeled by\n * the Drizzle `relationTable` object. Required (not optional) because the\n * physical columns are always present with real defaults on every row,\n * even for pure-Hebbian relations that were never judged\n * (`judgmentStatus: \"pending\"`, everything else `null`).\n */\n judgmentStatus: JudgmentStatus;\n reason: string | null;\n evidence: Record<string, unknown> | null;\n confidence: number | null;\n markedByUserId: string | null;\n markedByKind: MarkerKind;\n markedByModel: string | null;\n markedByPromptVersion: string | null;\n provenance: string | null;\n conversationId: string | null;\n supersededByRelationId: string | null;\n}\n\n/** Memory primitive a citation can attach to. */\nexport type CitationMemoryKind = \"fact\" | \"decision\" | \"entity\" | \"episode\";\n\n/** Where a citation's source span came from. */\nexport type CitationSourceKind =\n \"message\" | \"document\" | \"tool_call\" | \"llm_extraction\" | \"user_edit\" | \"agent_save\" | \"imported\";\n\n/**\n * flatten-legacy-dual-core PR9e (design.md D6.5): the previous declaration\n * (`sourceId`/`sourceType`/`derivedId`/`derivedType`/`citationType`/\n * `confidence`) never matched the physical `mnemosyne.mnemo_citation` table\n * at all — reconciled to the real columns (`memory_kind`/`memory_id`/\n * `source_kind`/`source_id`/`extractor_model`/`extractor_prompt_version`/\n * `judge_model`/`judge_relation_id`/`evidence_excerpt`/`created_at`), same\n * shape the legacy `core/src/citation/store.ts`'s `Citation` and\n * `core/src/db/schema/citation.ts` already carry, and the same wire shape\n * `server/src/routes/citations.ts`'s `CitationSchema` already validates.\n */\nexport interface MnemoCitation {\n id: string;\n workspaceId: string;\n\n memoryKind: CitationMemoryKind;\n memoryId: string;\n\n sourceKind: CitationSourceKind;\n sourceId: string | null;\n\n extractorModel: string | null;\n extractorPromptVersion: string | null;\n judgeModel: string | null;\n judgeRelationId: string | null;\n evidenceExcerpt: string | null;\n\n createdAt: Date;\n}\n\n/** Filter for {@link MnemoCitation} reads (`StorageAdapter.listCitations`). */\nexport interface CitationFilter {\n workspaceId: string;\n memoryKind?: CitationMemoryKind;\n memoryId?: string;\n limit?: number;\n /**\n * flatten-legacy-dual-core PR9h (design.md D6.5 \"Export\") — additive\n * offset-pagination field. `listCitations` clamps `limit` to 500/call\n * (`CitationRepository.ts`); the pure-core `exportWorkspace` projection\n * (packages/core/src/cognitive/export/) needs to walk past that per-call\n * cap up to its own 100k row cap, and `CitationFilter` had no way to page\n * beyond the first 500 rows before this field existed. `GET /citations`\n * (routes/citations.ts) never sets this — its own public `limit` query\n * param is already capped at 500, so the field defaults to `0` there.\n */\n offset?: number;\n}\n\n/**\n * flatten-legacy-dual-core PR9f (design.md D6.5 \"Graph — assembly-in-adapter,\n * traversal-in-core\"): the Memory Graph's node kinds. Mirrors legacy\n * `core/src/graph/types.ts`'s `GraphEntityKind`-adjacent `kind` discriminant.\n */\nexport type GraphNodeKind = \"entity\" | \"episode\" | \"decision\";\n\n/** Filter for {@link GraphSnapshot} assembly (`StorageAdapter.getGraphSnapshot`). */\nexport interface GraphSnapshotFilter {\n workspaceId: string;\n /** Restrict to this entity + its 1-hop neighbourhood. Omit for the full canonical view. */\n focusEntityId?: string;\n /** Overlay precomputed semantic-neighbor (kNN) edges onto the graph. */\n includeSemantic?: boolean;\n /**\n * Add an episode → entity edge (relation \"mentions\", provenance \"episode_facts\") for every\n * entity one of the episode's visible linked facts is about. Derived, never stored.\n */\n includeMentions?: boolean;\n /** Bitemporal point-in-time reconstruction — reproduces the graph as it stood at this instant. */\n asOf?: Date;\n /**\n * The caller's sensitivity ceiling. When set, entities, episodes, decisions\n * and facts above it are left out: no node, no edge or semantic edge drawn\n * from them, and no count in `factCount`. Omit for every tier.\n */\n maxSensitivity?: Sensitivity;\n}\n\n/** A node in the Memory Graph — an entity, episode, or active decision. */\nexport interface GraphNode {\n id: string;\n kind: GraphNodeKind;\n entityKind?: MnemoEntity[\"kind\"];\n label: string;\n description?: string | null;\n mentionCount: number;\n factCount: number;\n avgMemoryStrength: number;\n createdAt: Date;\n}\n\n/** An edge in the Memory Graph — a typed relation (or semantic-neighbor overlay) between two nodes. */\nexport interface GraphEdge {\n id: string;\n source: string;\n target: string;\n relation: string;\n confidence: number;\n provenance: string | null;\n}\n\n/** Adapter-assembled Memory Graph snapshot — mirrors legacy `buildGraphQuery` (`graph/query.ts`). */\nexport interface GraphSnapshot {\n nodes: GraphNode[];\n edges: GraphEdge[];\n meta: {\n entityCount: number;\n episodeCount: number;\n decisionCount: number;\n relationCount: number;\n };\n}\n","// Session types — DATA_MODEL.md §4 (mnemo_session + mnemo_session_turn)\n\nimport type { Sensitivity } from \"./common.js\";\nimport type { ActorType } from \"./provenance.js\";\n\nexport const TRAFFIC_ORIGINS = [\"organic\", \"installer_verify\", \"evaluation\", \"unknown\"] as const;\nexport type TrafficOrigin = (typeof TRAFFIC_ORIGINS)[number];\nexport const TURN_ORIGINS = [\n \"human\",\n \"agent_message\",\n \"task_notification\",\n \"pasted_content\",\n \"assistant\",\n \"unknown\",\n] as const;\nexport type TurnOrigin = (typeof TURN_ORIGINS)[number];\n\n/** Content origin is evidence about a message, never authentication of its author. */\nexport function classifyTurnOrigin(\n role: SessionTurn[\"role\"],\n content: string,\n native?: { turnOrigin?: TurnOrigin; turnOriginEvidence?: string }\n): { turnOrigin: TurnOrigin; turnOriginEvidence: string } {\n if (native?.turnOrigin && TURN_ORIGINS.includes(native.turnOrigin))\n return {\n turnOrigin: native.turnOrigin,\n turnOriginEvidence:\n typeof native.turnOriginEvidence === \"string\"\n ? native.turnOriginEvidence.slice(0, 256)\n : \"caller:typed_origin\",\n };\n if (role === \"assistant\")\n return { turnOrigin: \"assistant\", turnOriginEvidence: \"role:assistant\" };\n const text = content.trim();\n for (const [tag, origin] of [\n [\"agent-message\", \"agent_message\"],\n [\"task-notification\", \"task_notification\"],\n [\"pasted_content\", \"pasted_content\"],\n ] as const) {\n if (new RegExp(`^<${tag}(?:\\\\s[^>]*)?>[\\\\s\\\\S]*</${tag}>$`).test(text))\n return { turnOrigin: origin, turnOriginEvidence: `text:whole_wrapper:${tag}` };\n }\n return { turnOrigin: \"unknown\", turnOriginEvidence: \"unclassified\" };\n}\n\nexport type SessionStatus = \"active\" | \"collapse_pending\" | \"collapsed\" | \"archived\";\nexport type ManagedCloseKind = \"authoritative\" | \"provisional\";\nexport type ManagedArchiveReason =\n \"empty_session\" | \"incomplete_exchange\" | \"too_few_turns\" | \"low_recurrence_signal\" | \"no_pin\";\n\nexport const RECOVERABLE_MANAGED_ARCHIVE_REASONS = [\n \"too_few_turns\",\n \"low_recurrence_signal\",\n \"no_pin\",\n] as const satisfies readonly ManagedArchiveReason[];\n\nexport interface MnemoSession {\n id: string;\n workspaceId: string;\n agentId?: string;\n actorId?: string;\n\n trafficOrigin?: TrafficOrigin;\n continuityRootId?: string | null;\n status: SessionStatus;\n turnCount: number;\n tokenCount: number;\n\n /** kept as optional for backward-compat with any stored snapshots */\n collapseTriggeredAt?: Date;\n collapsedAt?: Date;\n\n openedAt: Date;\n scratch?: Record<string, unknown>;\n metadata: Record<string, unknown>;\n /** §14 A/B measurement — which prompt version was active when this session ran. */\n activePromptVersionId?: string | null;\n /**\n * Explicit user rating for the session, mirroring `mnemo_session.outcome_rating`\n * and its CHECK constraint. Read by `mnemo_metacognition_trends`\n * (`sessionCollapseQuality`), PluginRepository's §14 scored trajectories and\n * MeteringRepository; written by POST /session/:id/feedback.\n *\n * The column and all three readers predate this field — the domain type never\n * modelled it, which is precisely why no write path could set it.\n */\n outcomeRating?: \"success\" | \"failure\" | \"neutral\" | null;\n /** EPISODE-1: human-readable label, e.g. \"Reunión con cliente 2026-06-12\". */\n label?: string | null;\n sourceHost?: string | null;\n sourceSessionId?: string | null;\n sourceClientInstanceId?: string | null;\n sourceGeneration?: number | null;\n predecessorSessionId?: string | null;\n lastActivityAt?: Date | null;\n closeKind?: ManagedCloseKind | null;\n closeRequestedAt?: Date | null;\n closeGraceDeadline?: Date | null;\n terminalDigestVersion?: number | null;\n terminalMessageSetDigest?: string | null;\n terminalMaxEnqueueSequence?: number | null;\n sensitivity?: Sensitivity | null;\n originActorId?: string | null;\n originActorType?: ActorType | null;\n originUserId?: string | null;\n originSensitivityCeiling?: Sensitivity | null;\n collapseLeaseOwner?: string | null;\n collapseLeaseExpiresAt?: Date | null;\n collapseAttempts?: number;\n collapseNextAttemptAt?: Date | null;\n collapseOperationId?: string | null;\n captureIncomplete?: boolean;\n captureIncompleteReasons?: string[];\n archiveReason?: string | null;\n archivedAt?: Date | null;\n /** LIFECYCLE-14: `mnemo_session.fact_count`, written by a completed collapse. */\n factCount?: number | null;\n /** LIFECYCLE-14: the persisted collapse summary (`context_snapshot`); null before one. */\n collapseSummary?: Record<string, unknown> | null;\n}\n\nexport interface SessionTurn {\n id: string;\n workspaceId: string;\n sessionId: string;\n turnIndex: number;\n role: \"user\" | \"assistant\" | \"system\" | \"tool\";\n content: string;\n turnOrigin?: TurnOrigin;\n turnOriginEvidence?: string;\n tokenCount?: number;\n pinned?: boolean;\n hint?: string;\n sourceMessageId?: string;\n supersedesSourceMessageId?: string;\n contentHash?: string;\n retractedAt?: Date;\n retractionReason?: string;\n ingestionEventId?: string;\n createdAt: Date;\n}\n\nexport interface ManagedSessionClaim {\n session: MnemoSession;\n leaseOwner: string;\n leaseExpiresAt: Date;\n}\n\nexport interface ManagedCollapseRetry {\n attempts: number;\n nextAttemptAt: Date;\n}\n\nexport interface ManagedLifecycleQuiesceResult {\n pendingCount: number;\n liveLeaseCount: number;\n reactivatedCount: number;\n}\n","// Audit log types — DATA_MODEL.md §4.8 (SECURITY.md §6)\n// mnemo_audit_log is append-only: INSERT only for app role, enforced by trigger.\n\nimport type { ActorType } from \"./provenance.js\";\n\nexport type AuditAction =\n | \"recall\"\n | \"create\"\n | \"update\"\n | \"delete\"\n | \"hard_delete\"\n | \"export\"\n | \"self_edit\"\n | \"session_open\"\n | \"session_close\"\n | \"key_create\"\n | \"key_rotate\"\n | \"key_revoke\"\n | \"admin_access\"\n | \"federation_sync\"\n | \"erasure_initiated\"\n // Terminal entry of POST /admin/erasure (routes/admin-erasure.ts). Core\n // forget's hard mode still closes with \"hard_delete\" (it also deletes a fact).\n | \"erasure_complete\"\n // Wired in sdd/p56-federation-cert-pin-mismatch-audit: emitted by\n // gateFederationRequest() (routes/federation.ts) when a peer's\n // presented mTLS cert fails the constant-time pin comparison.\n | \"federation_cert_pin_mismatch\"\n | \"federation_cert_rotated\"\n // p50-audit-log-emitters: declared, deliberately NOT emitted by this\n // change — no runtime plugin lifecycle exists yet to emit these from.\n | \"plugin_installed\"\n | \"plugin_removed\"\n | \"workspace_created\"\n // p50-audit-log-emitters: declared, deliberately NOT emitted by this\n // change — no delete-workspace route exists to emit this from.\n | \"workspace_deleted\"\n // p50-audit-log-emitters: declared, deliberately NOT emitted by this\n // change — this is a migration-time-only concern, not a request-time event.\n | \"rls_policy_changed\"\n // p50-audit-log-emitters (D10): deferred, not silently dropped. Both live\n // in `ScopedApiKeyAdapter.authenticate()`, an auth hot path with no\n // `deps.storage` handle — wiring these needs its own design (see\n // sdd/p50-audit-log-emitters/tasks Phase 9, task 9.1 — tracked as blocked).\n // Wired in sdd/p52-mfa-ip-denied-audit via authenticateScoped()'s optional\n // storage handle.\n | \"mfa_verified\"\n | \"ip_denied\"\n // Migration 0050 (accounts stage A): account, invitation and instance actions.\n | \"login_success\"\n | \"login_failure\"\n | \"user_created\"\n | \"user_disabled\"\n | \"user_enabled\"\n | \"user_offboarded\"\n | \"superadmin_granted\"\n | \"superadmin_revoked\"\n | \"member_added\"\n | \"member_removed\"\n | \"member_role_changed\"\n | \"invitation_created\"\n | \"invitation_revoked\"\n | \"invitation_accepted\"\n | \"link_created\"\n | \"password_changed\"\n | \"password_reset\"\n | \"settings_changed\"\n | \"workspace_opened\";\n\n/**\n * Who performed the audited operation (SECURITY.md §6 \"Audit\n * Trail\"). The distinction is load-bearing for the threat model: insider-access\n * detection and federation-sync provenance both rely on being able to tell a\n * human `user`, an autonomous `agent`, an internal `system` job, and an inbound\n * `federation` peer apart.\n */\nexport type AuditActorType = ActorType;\n\nexport interface AuditLogEntry {\n id: string;\n workspaceId: string;\n /**\n * Origin of the operation. Threaded from the auth context. When omitted, the\n * storage adapter resolves it via {@link resolveAuditActorType} (back-compat:\n * `user` when an actorId is present, else `system`).\n */\n actorType?: AuditActorType;\n actorId?: string;\n action: AuditAction;\n resourceKind: string;\n resourceId?: string;\n ipAddress?: string;\n userAgent?: string;\n detail?: Record<string, unknown>;\n isTerminal: boolean; // true for GDPR erasure terminal records\n merkleHash?: Uint8Array; // hash chain integrity; NULL until terminal record\n /**\n * The stable entry uuid the Merkle chain commits to (the row's `id` is a\n * BIGINT assigned after hashing). Returned by listAuditLog so the chain can\n * be verified; a writer never sets it (the adapter generates it).\n */\n entryUid?: string;\n createdAt: Date;\n}\n\n/**\n * Resolve the `actor_type` to persist for an audit entry.\n *\n * - Prefer the explicit `actorType` threaded from the auth context (the correct\n * value for `agent` / `federation` / `system` / `user` origins).\n * - Back-compat fallback when callers don't yet pass one: `user` if an actorId\n * is present (matches the historical hardcoded value), otherwise `system`.\n *\n * Pure (no I/O) so it can be unit-tested and shared by every StorageAdapter\n * implementation without coupling `@mnemo-ai/types` to any infrastructure.\n */\nexport function resolveAuditActorType(\n entry: Pick<AuditLogEntry, \"actorType\" | \"actorId\">\n): AuditActorType {\n if (entry.actorType) return entry.actorType;\n return entry.actorId ? \"user\" : \"system\";\n}\n","// Port interfaces — PACKAGE_ARCHITECTURE.md §3 (updated by TASK-0006/0007)\n// These are the hexagonal-architecture \"ports\": the contracts @mnemo-ai/core\n// depends on. Zero infrastructure imports here; all adapters implement these.\n\nimport type {\n MnemoFact,\n MnemoDecision,\n MnemoEpisode,\n MnemoEntity,\n MnemoStrategy,\n MnemoWorkflow,\n MnemoSkill,\n MnemoTask,\n MnemoEvent,\n MnemoReasoning,\n MnemoHyperedge,\n MnemoCompositionRule,\n MnemoInferenceLogEntry,\n MnemoFactHash,\n MnemoAgentProfile,\n ConfidenceMapRow,\n KnowledgeGapRow,\n MetacognitionTrends,\n SequentialPatternRow,\n PeriodicPatternRow,\n ConditionalPatternRow,\n CoOccurrencePatternRow,\n WorkflowStep,\n EventAnnotation,\n} from \"./primitives.js\";\nimport type {\n MnemoRelation,\n RelationVerb,\n JudgmentStatus,\n MarkerKind,\n RelationNodeKind,\n MnemoCitation,\n CitationFilter,\n GraphSnapshotFilter,\n GraphSnapshot,\n} from \"./relations.js\";\nimport type {\n ManagedArchiveReason,\n ManagedCollapseRetry,\n ManagedLifecycleQuiesceResult,\n ManagedSessionClaim,\n MnemoSession,\n SessionTurn,\n} from \"./session.js\";\nimport type { OutboxEntry } from \"./outbox.js\";\nimport type { AuditLogEntry } from \"./audit.js\";\nimport type {\n PaginatedResult,\n WorthDelta,\n HealthStatus,\n Sensitivity,\n DecayClass,\n} from \"./common.js\";\nimport type { PrimitiveKind } from \"./primitives.js\";\nimport type {\n Provenance,\n RecallFilter,\n RecallHitObservation,\n RecallRequestObservation,\n RememberKind,\n} from \"./recall.js\";\nimport type { ActorType } from \"./provenance.js\";\nimport type { HarnessEvent, HarnessEventAck, ManagedSessionProvenance } from \"./harness.js\";\n\n// ─── Input/Filter types ───────────────────────────────────────────────────────\n\nexport interface CreateSessionInput {\n workspaceId: string;\n agentId?: string;\n /** The authenticating CREDENTIAL, namespaced ActorRef (\"key:<id>\").\n * Persisted to metadata — NEVER to mnemo_session.user_id. */\n actorId?: string;\n /** The real mnemo_user.id behind the request, or null. Persisted to\n * mnemo_session.user_id. */\n userId?: string | null;\n actorType?: ActorType;\n metadata?: Record<string, unknown>;\n label?: string;\n trafficOrigin?: import(\"./session.js\").TrafficOrigin;\n sourceSessionId?: string;\n sourceClientInstanceId?: string;\n sourceGeneration?: number;\n predecessorSessionId?: string;\n}\n\nexport interface CreateFactInput {\n workspaceId: string;\n agentId?: string;\n actorId?: string;\n userId?: string | null;\n actorType?: ActorType;\n scope: MnemoFact[\"scope\"];\n scopeRef?: string;\n statement: string;\n subject: string;\n kind: MnemoFact[\"kind\"];\n confidence?: number;\n relevance?: number;\n attribution?: MnemoFact[\"attribution\"];\n attributedTo?: MnemoFact[\"attribution\"];\n sourceMessageIds?: string[];\n sessionId?: string;\n extractionSource?: string;\n topicKey?: string;\n entityId?: string;\n episodeId?: string;\n validFrom?: Date;\n validTo?: Date;\n tags?: string[];\n metadata?: Record<string, unknown>;\n sensitivity?: MnemoFact[\"sensitivity\"];\n /**\n * PRIM-15 — restore paths (POST /import) only. A new fact starts `active` and\n * unpinned; a restored one keeps what the export said, so a forgotten fact\n * comes back closed and a pinned one stays pinned. Omitted → the column\n * defaults (`active`, `false`), exactly as before.\n */\n status?: MnemoFact[\"status\"];\n pinned?: boolean;\n /**\n * Ownership level: \"workspace:<id>\" | \"user:<id>\" | \"tenant:<id>\".\n * Defaults to \"workspace:<workspaceId>\" when omitted.\n * Used by multi-level recall to route facts to the right context pool.\n */\n scopeOwner?: string;\n /**\n * Precomputed embedding for the fact's statement. When supplied, createFact\n * enqueues an authoritative vector-form `vector_upsert` outbox entry (the\n * worker re-applies this exact vector) instead of the text-form entry it would\n * otherwise embed itself. This honours the \"server skips its own embed pass\n * when a vector is supplied\" contract and prevents a re-embed of the statement\n * from clobbering a host-supplied vector. Length must match the workspace\n * embedding dimensions.\n */\n embedding?: number[];\n /** The model stamp (e.g. 'text-embedding-3-small') used to generate the embedding. */\n embeddingModel?: string;\n /**\n * Extra fields to stamp on the `vector_upsert` outbox entry this call enqueues.\n *\n * `mnemo_outbox` grants `mnemo_app_role` SELECT and INSERT only (0001 baseline),\n * matching the append-only posture of the audit and deletion logs. A caller that\n * needs the job to say more than the defaults therefore has to supply it here,\n * to be written with the row — an UPDATE afterwards fails with 42501 under the\n * non-bypass role `withMnemoTx` installs.\n */\n vectorJob?: {\n /**\n * Ask the worker to also persist this fact's LSH band signatures, inside the\n * same job, before it acknowledges.\n *\n * `remember()` embeds synchronously and can enqueue its own `lsh_upsert` entry\n * with precomputed bands. A caller with no embedding at creation time (managed\n * collapse) cannot, so it rides the request on the vector job — which also\n * makes vector + LSH + acknowledgement one atomic retry unit rather than two\n * independently ackable entries. Fact-only: LSH bands serve near-duplicate\n * fact recall (spec §17).\n */\n indexLsh?: boolean;\n /** Managed-collapse operation that produced this fact, for provenance. */\n operationId?: string;\n /**\n * Revision the job should index at. Defaults to 1, which is right for a new\n * fact; a bitemporal successor must pass its predecessor's count plus one so\n * the LSH row is keyed to the revision the successor actually carries.\n */\n revision?: number;\n };\n}\n\nexport interface UpdateFactInput {\n statement?: string;\n confidence?: number;\n relevance?: number;\n status?: MnemoFact[\"status\"];\n pinned?: boolean;\n /**\n * P85.2 — `null` REOPENS the bitemporal interval; omitting the field leaves it\n * untouched. Implementations already distinguish the two (`if (input.validTo\n * !== undefined)`), but the type only allowed a Date, so there was no way to\n * express \"this fact is valid again\".\n *\n * That is what made `POST /facts/:id/restore` a lie: it set `status: \"active\"`\n * and nothing else, while every recall path filters on `validTo IS NULL`. The\n * fact came back 200, reported `status: \"active\"`, and stayed unrecallable.\n */\n validTo?: Date | null;\n metadata?: Record<string, unknown>;\n /**\n * flatten-legacy-dual-core PR15 (task 6c.2) — additive widening backing\n * `PATCH /facts/:id`'s subject/kind edit fields. Legacy `patchFact()`\n * (factory.ts) has always supported patching `subject`/`kind`; both\n * columns are physically present on `mnemo_fact` and already modeled by\n * `MnemoFact`, but this port-interface method never exposed them — same\n * class of narrow, additive widening as PR9c's `sourceIds`/PR9f's\n * `targetIds`, not new domain modeling.\n */\n subject?: string;\n kind?: MnemoFact[\"kind\"];\n /**\n * CHAOS-8 — optimistic precondition. When set, the update applies only if\n * the row is still at this `revisionCount`; otherwise the adapter throws\n * {@link FactRevisionConflictError} and changes nothing. Read-modify-write\n * callers (self-edit `append`, `PATCH /facts/:id` with `expectedRevision`)\n * use it so two writers cannot silently overwrite each other.\n */\n expectedRevision?: number;\n}\n\n/**\n * CHAOS-8 — thrown by `updateFact` when `expectedRevision` no longer matches\n * the row. Nothing was written; re-read and retry, or report a conflict.\n */\nexport class FactRevisionConflictError extends Error {\n readonly code = \"REVISION_CONFLICT\";\n\n constructor(\n readonly factId: string,\n readonly expectedRevision: number,\n readonly currentRevision: number\n ) {\n super(`fact ${factId} is at revision ${currentRevision}, not the expected ${expectedRevision}`);\n this.name = \"FactRevisionConflictError\";\n }\n}\n\n/** CHAOS-7 — the `uniq_mnemo_fact_dedup` key of a fact write. */\nexport interface FindLiveFactByStatementInput {\n workspaceId: string;\n scope: MnemoFact[\"scope\"];\n scopeRef?: string;\n subject: string;\n /** The statement as stored (post-redaction, plaintext tiers only). */\n statement: string;\n /**\n * APP-009 — the rest of a fact's identity. When given, only a row with this\n * owner (a row with none counts as the workspace's) and this tier matches:\n * the same sentence owned by another user, or kept at another tier, is a\n * different fact. Omitted, the lookup is by the first four fields alone.\n */\n scopeOwner?: string;\n sensitivity?: MnemoFact[\"sensitivity\"];\n}\n\nexport interface MergeFactByTopicKeyInput {\n workspaceId: string;\n topicKey: string;\n statement: string;\n metadata?: Record<string, unknown>;\n tags?: string[];\n /**\n * The session the new statement came from (WP-4 request). When given, the\n * successor carries it and starts with `episode_id = NULL`, so the collapse\n * of THAT session links it (`linkSessionFactsToEpisode`) instead of it\n * staying attached to the predecessor's episode. Omitted → both inherited.\n */\n sessionId?: string;\n /** Provenance of the new statement (e.g. \"collapse\"). Omitted → inherited. */\n extractionSource?: string;\n /**\n * The vector the caller already computed from the new statement's plaintext.\n * A confidential+ successor is never re-embedded from its column (that holds\n * ciphertext), so without this it would drop out of semantic recall.\n */\n embedding?: number[];\n embeddingModel?: string;\n}\n\nexport interface MergeDecisionByTopicKeyInput {\n workspaceId: string;\n topicKey: string;\n title: string;\n body: string;\n kind: MnemoDecision[\"kind\"];\n metadata?: Record<string, unknown>;\n /**\n * AGENTSIM-7 support: persisted on the revised row when given, so a decision\n * written through `remember` keeps its scope and session correlation on the\n * topic-key update path too (create already carries both). Left untouched\n * when omitted.\n */\n scopeRef?: string;\n conversationId?: string;\n}\n\nexport interface ReplaceFactInput {\n id: string;\n workspaceId: string;\n statement: string;\n requestedBy: string;\n agentId?: string;\n actorIsolationId?: string;\n /**\n * Real `mnemo_user.id`. Presence is the enable signal for the\n * user-isolation RLS backstop (`mnemo_fact_user_isolation_select`) — there\n * is no separate boolean toggle, so enforcement can never be turned on\n * without a concrete identity to scope it to.\n */\n userIsolationId?: string;\n}\n\nexport interface ReplaceFactResult {\n previous: MnemoFact;\n replacement: MnemoFact;\n}\n\nexport interface FactFilter {\n workspaceId: string;\n status?: MnemoFact[\"status\"];\n kind?: MnemoFact[\"kind\"];\n scope?: MnemoFact[\"scope\"];\n entityId?: string;\n sessionId?: string;\n minConfidence?: number;\n topicKey?: string;\n tags?: string[];\n validAt?: Date;\n offset?: number;\n limit?: number;\n /**\n * complete-mcp-tools B3 — transaction-time lower bound (created_at >= x).\n * Additive-only field: when set, `queryFacts` also orders results by\n * `created_at DESC` so callers surfacing genuine creation events (e.g.\n * `GET /timeline`) can rely on newest-first ordering. Does not replace or\n * rename any existing field.\n */\n createdSince?: Date;\n /** The caller's read ceiling: rows above it are left out of the page and of `total`. */\n maxSensitivity?: Sensitivity;\n}\n\n// ─── flatten-legacy-dual-core PR9b (D6.3 — T2) — keyset fact list + hard purge ──\n//\n// `queryFacts`/`FactFilter` above are left UNTOUCHED (its `PaginatedResult`\n// offset contract has many existing callers, incl. PR8's `linkedFactCount`).\n// `FactPageFilter`/`FactPage`/`queryFactsPage` are a SEPARATE, additive\n// keyset-pagination method living beside it — ports `GET /facts` (list),\n// which legacy `CoreLike.listFacts` (factory.ts) backed with cursor\n// pagination, FTS, sortBy/order, and a bitemporal `asOf` snapshot.\n\nexport interface FactPageFilter {\n workspaceId: string;\n kind?: MnemoFact[\"kind\"];\n scope?: MnemoFact[\"scope\"];\n scopeRef?: string;\n /**\n * P135: other spellings of the project `scopeRef` names (its canonical name\n * and aliases). A row matches when its scope_ref is `scopeRef` or any of\n * these. Filled by the core from the workspace's `project` entities, never\n * by callers; ignored without `scopeRef`.\n */\n scopeRefAliases?: string[];\n status?: MnemoFact[\"status\"] | \"all\";\n pinned?: boolean;\n sensitivity?: Sensitivity;\n /** Plain-text FTS over text_lemmatized — plainto_tsquery over the shared\n * `mnemosyne.mnemo_fts` config (P131 B1), same as findContradictingFacts. */\n q?: string;\n sortBy?: \"created_at\" | \"updated_at\" | \"relevance\" | \"hit_count\";\n order?: \"asc\" | \"desc\";\n /** Opaque base64 keyset cursor `{v, id}` — legacy wire format, preserved verbatim. */\n cursor?: string;\n asOf?: Date;\n /** Incremental pull: only facts modified after this instant (federation.ts's future use). */\n updatedSince?: Date;\n /** Only facts created at or after this instant (`created_at >= x`). */\n createdSince?: Date;\n /**\n * PRIM-8 — the caller's read ceiling. Rows above it are excluded in the\n * query itself, so both the page and `total` only ever describe what the\n * caller may read. Omitted → no ceiling (internal callers).\n */\n maxSensitivity?: Sensitivity;\n /**\n * PRIM-16 — only rows whose validity is still open (`valid_to IS NULL`).\n * `status: \"active\"` alone admits a row whose interval already ended.\n */\n currentOnly?: boolean;\n limit: number;\n}\n\nexport interface FactPage {\n items: MnemoFact[];\n nextCursor: string | null;\n total: number;\n /**\n * PRIM-19 — `itemCursors[i]` resumes strictly after `items[i]`, rendered with\n * the database's own precision (a JS Date would lose microseconds). Lets a\n * caller that merges this page with another stream stop at any item.\n */\n itemCursors?: string[];\n}\n\n// ─── flatten-legacy-dual-core Slice 3a pt.2 (PR6) — workspace vitals + audit feed ──\n//\n// Ported 1:1 from the legacy `CoreLike.vitals()`/`CoreLike.audit()` shapes\n// (packages/core/src/factory-types.ts's `CoreWorkspaceVitals`/`CoreAuditEntry`)\n// so `routes/health.ts` and `routes/audit.ts` can move off `deps.core` without\n// changing their observable HTTP contract (D3 Tier A parity pins the response\n// shape byte-for-byte before this port).\n\n/** Workspace-scoped fact vitals — GET /health's response body. */\nexport interface WorkspaceVitals {\n workspaceId: string;\n factsLive: number;\n factsClosed: number;\n pinnedCount: number;\n lastRecallAt: string | null;\n lastWriteAt: string | null;\n embeddings: { indexed: number; pending: number };\n /** Live fact counts grouped by scope_ref. Only non-null scope_ref values. */\n factsByScopeRef: Array<{ scopeRef: string; count: number }>;\n}\n\n/**\n * The undo-log feed (GET /audit) counted, not listed: exactly `days` UTC days ending\n * today, zero-filled, oldest first, each with the day's user forgets and system\n * archives; `totals` over the window.\n */\nexport interface AuditFeedStats {\n days: Array<{ day: string; user: number; system: number }>;\n totals: { user: number; system: number };\n}\n\n/** One entry in the inspector's \"Undo log\" — GET /audit's response items. */\nexport interface AuditFeedEntry {\n id: string;\n factId: string;\n factStatement: string;\n factSubject: string;\n factKind: string;\n action: \"forgotten\";\n actorKind: \"user\" | \"system\";\n actorName: string | null;\n timestamp: string;\n revertible: boolean;\n}\n\n/** Filter for {@link StorageAdapter.getAuditFeed} — mirrors GET /audit's query params. */\nexport interface AuditFeedFilter {\n workspaceId: string;\n limit: number;\n actorKind?: \"user\" | \"system\";\n from?: string;\n to?: string;\n q?: string;\n /** Only facts at or below this tier (the caller's read ceiling). Omitted: every tier. */\n maxSensitivity?: Sensitivity;\n}\n\n// ─── flatten-legacy-dual-core Phase 9 (task 9.1) — health snapshot ────────────\n//\n// Ported 1:1 from `packages/core/src/health/{index,compute}.ts`'s\n// `HealthSnapshot`/`GetHealthSnapshotInput` shapes (Requirement 4) so\n// `routes/admin.ts`, `routes/governance.ts`, and the `mnemo.health.snapshot`\n// cron can move off the direct `@mnemo-ai/core` import onto the v3\n// `StorageAdapter` port, matching the `getWorkspaceVitals`/`getAuditFeed`\n// precedent above (PR6). Same physical `mnemo_health`/`mnemo_extraction_job`\n// tables; same computed-metric definitions; response shape unchanged.\n\n/** One `mnemo_health` row — a per-workspace memory-drift snapshot. */\nexport interface HealthSnapshot {\n workspaceId: string;\n snapshotAt: Date;\n factCountActive: number;\n factCountArchived: number;\n factCountEmbedded: number;\n factCountUnembedded: number;\n decisionCountActive: number;\n relationCountConflicts: number;\n factsWithZeroHits: number;\n /** NULL when no telemetry exists yet (cold start). */\n recallHitRate30d: number | null;\n extractionJobsFailed7d: number;\n extractionJobsDeferred: number;\n computedInMs: number;\n}\n\n/**\n * One UTC day of the snapshot history: exactly `days` entries ending today, oldest\n * first; a day with no snapshot has every figure null. Shares, not row counts: a\n * snapshot covers every sensitivity tier, so absolute counts are left out.\n * `zeroHitShare` = facts never recalled / active facts; `embeddedShare` = embedded /\n * (embedded + unembedded); `recallHitRate30d` as stored; `failedJobs7d` as stored.\n */\nexport interface HealthSnapshotDay {\n day: string;\n recallHitRate30d: number | null;\n zeroHitShare: number | null;\n embeddedShare: number | null;\n failedJobs7d: number | null;\n}\n\n/** Input for {@link StorageAdapter.getHealthSnapshot}. */\nexport interface GetHealthSnapshotInput {\n workspaceId: string;\n /**\n * When true, recompute the snapshot now AND persist it. When false\n * (default), return the most recently persisted snapshot, or `null`\n * when none exist yet.\n */\n fresh?: boolean;\n}\n\n// ── flatten-legacy-dual-core Slice 3c pt.1 (PR10) — active-learning review\n// queue (`mnemo_review_queue`, Mnemosyne v1.3+). Backs `routes/review.ts`.\n// See {@link StorageAdapter.listActiveLearningReview} for the disambiguation\n// against the Wave Y §25.1 `enqueueReview`/`enqueueReviewItem` pair, which\n// target the unrelated `mnemo_review_item` table.\n\nexport type ActiveLearningReviewReason = \"low_confidence\" | \"contradiction\" | \"manual\";\nexport type ActiveLearningReviewResolution = \"kept\" | \"edited\" | \"forgotten\" | \"dismissed\";\n\nexport interface ActiveLearningReviewRow {\n id: string;\n workspaceId: string;\n /** Populated for fact-sourced rows; null for decision-sourced rows. */\n factId: string | null;\n /** Populated for decision-sourced rows; null for fact-sourced rows. */\n decisionId: string | null;\n reason: ActiveLearningReviewReason;\n createdAt: Date;\n resolvedAt: Date | null;\n resolvedBy: string | null;\n resolution: ActiveLearningReviewResolution | null;\n}\n\n/** Filter for {@link StorageAdapter.listActiveLearningReview} — mirrors GET /review's query params. */\nexport interface ActiveLearningReviewFilter {\n workspaceId: string;\n reason?: ActiveLearningReviewReason;\n /** When true, include resolved rows. Defaults to unresolved-only. */\n includeResolved?: boolean;\n limit?: number;\n}\n\nexport interface EnqueueActiveLearningReviewInput {\n workspaceId: string;\n /** Exactly one of `factId`/`decisionId` must be supplied. */\n factId?: string;\n decisionId?: string;\n reason: ActiveLearningReviewReason;\n}\n\nexport interface EnqueueActiveLearningReviewResult {\n /** id of the row queued, OR the pre-existing open row's id on a dedup hit. */\n id: string;\n /** True iff a fresh row was inserted; false on a dedup hit. */\n inserted: boolean;\n}\n\nexport interface ResolveActiveLearningReviewInput {\n workspaceId: string;\n reviewId: string;\n resolvedBy: string;\n resolution: ActiveLearningReviewResolution;\n}\n\nexport interface ResolveActiveLearningReviewResult {\n /** True when an open row was resolved; false when already resolved or missing. */\n resolved: boolean;\n factId: string | null;\n decisionId: string | null;\n /** True when `resolution: 'forgotten'` cascaded to the linked fact's status. */\n cascaded: boolean;\n}\n\n// ── §33 Distributed Consensus — contradiction detection on write ──────────────\n\n/**\n * Query for active facts that potentially contradict a candidate fact.\n * Mirrors the candidate-on-write matching in core conflict/fact-candidate.ts:\n * same `subject` (catches \"user prefers X\" → \"user prefers Y\") OR FTS overlap\n * on the statement. Scoped to ACTIVE facts in the workspace.\n */\n/**\n * P130 — default cosine floor for contradiction candidates.\n *\n * Measured against the real pairs, worst case on each side:\n *\n * worst TRUE contradiction that must pass 0.6861\n * (\"usamos Postgres\" / \"ya no usamos Postgres, migramos a MySQL\")\n * worst FALSE pair that must not 0.4356\n * (\"Verificacion de P117: soft delete\" / \"The team uses PostgreSQL…\")\n *\n * 0.55 sits between them with margin on both sides, and leans low on purpose:\n * this is a candidate GATE and the resolver still judges polarity downstream,\n * so admitting a near-miss costs one review item while rejecting a true\n * contradiction loses it silently. Asymmetric cost, asymmetric placement.\n *\n * Lives here rather than in an adapter so the production adapter and the\n * in-memory double cannot drift to different floors — a divergence that would\n * make every contradiction test meaningless without failing anything.\n */\nexport const DEFAULT_CONTRADICTION_MIN_SIMILARITY = 0.55;\n\n/**\n * PRIM-5 — the subject a fact gets when the caller sends none (remember,\n * collapse, import all default to it). It says nothing about what a fact is\n * about, so for a row without a usable vector, sharing it must never make a\n * contradiction candidate on its own: one such row (a restored fact with a NULL\n * embedding) turned every later default-subject write into a \"conflict\".\n */\nexport const GENERIC_FACT_SUBJECT = \"general\";\n\n/** True when `subject` names something — neither empty nor {@link GENERIC_FACT_SUBJECT}. */\nexport function isSpecificFactSubject(subject: string): boolean {\n const s = subject.trim().toLowerCase();\n return s !== \"\" && s !== GENERIC_FACT_SUBJECT;\n}\n\nexport interface FindContradictingFactsInput {\n /** Exact `subject` of the candidate fact (cheap same-subject match). */\n subject: string;\n /** The candidate statement, run through full-text search for overlap. */\n statement: string;\n /** When set, the just-inserted candidate is excluded from the results. */\n excludeId?: string;\n /** Max rows returned. Default 5 (adapter-defined). */\n limit?: number;\n /**\n * P130 — the incoming statement's embedding. When supplied, candidates are\n * generated by cosine similarity and `subject` stops generating them.\n *\n * The lexical predicate CANNOT find contradictions, by construction:\n * `plainto_tsquery` ANDs every term, so a candidate must contain every word\n * of the incoming statement — including the one that differs. A\n * contradiction differs by definition. Measured: \"el broker de mensajes es\n * RabbitMQ\" @@ plainto_tsquery(\"el broker de mensajes es Kafka\") is FALSE.\n *\n * So `subject = $1` was not a crutch, it was the only clause producing\n * candidates at all — which is why conflicts were reported between pairs as\n * unrelated as \"Verificacion de P117: soft delete\" and \"The team uses\n * PostgreSQL with pgvector\" (both `general`). Removing it without a\n * replacement was tried and reverted: it swapped 100% false positives for\n * 100% false negatives.\n *\n * Cosine is the replacement because it measures the thing the predicate was\n * always reaching for — \"talks about the same thing\" — leaving polarity to\n * the resolver. Measured separation on the real cases, worst positive vs\n * worst negative: +0.25 with bge-m3, +0.17 with mxbai-embed-large. Both\n * separate; the current model separates more.\n *\n * Optional so callers without an embedding keep the old behaviour rather\n * than silently getting no candidates.\n */\n embedding?: number[];\n /**\n * Cosine floor for the semantic arm. Adapter default sits between the\n * measured worst-positive and worst-negative above. Ignored when\n * `embedding` is absent.\n */\n minSimilarity?: number;\n /**\n * The caller's read ceiling: facts above it are not candidates. The\n * candidates' text reaches the caller (`/remember` conflicts, paraphrase\n * reuse), so a writer must not see what it could not read.\n */\n maxSensitivity?: Sensitivity;\n /**\n * The context of the write being screened. When set, only facts in that\n * same context are candidates — the scope, scope_ref and owner (NULL owner =\n * `workspace:<id>`) a recall filtered to it, and paraphrase reuse, match on.\n */\n writeContext?: {\n scope: MnemoFact[\"scope\"];\n scopeRef?: string;\n scopeOwner: string;\n };\n}\n\n/**\n * A fact surfaced as a potential contradiction. Carries exactly the fields the\n * pure §33 resolver (decideAutoResolution) consumes — attribution, worth,\n * validFrom — plus identity/context (id, statement, subject, confidence) the\n * caller needs to act on the verdict (supersede / review) and to log it.\n *\n * `worth` is the generated Beta-Bernoulli posterior (NUMERIC in Postgres);\n * adapters MUST coerce it to a JS number before returning.\n */\nexport interface ContradictingFact {\n id: string;\n subject: string;\n statement: string;\n confidence: number;\n attribution: MnemoFact[\"attribution\"];\n worth: number;\n validFrom: Date;\n /**\n * Cosine similarity to the incoming embedding, when the candidate was found\n * by its vector. Absent for a candidate found by the lexical predicate (no\n * usable vector, or no embedding supplied) — there is no cosine to report.\n */\n similarity?: number;\n}\n\nexport interface CreateDecisionInput {\n workspaceId: string;\n agentId?: string;\n actorId?: string;\n userId?: string | null;\n actorType?: ActorType;\n conversationId?: string;\n /** Ownership: \"workspace:<id>\" | \"user:<id>\" | \"tenant:<id>\". Defaults to \"workspace:<workspaceId>\". */\n scopeOwner?: string;\n /** Project/entity scope reference (e.g. 'project-x'). Mirrors mnemo_fact.scope_ref. */\n scopeRef?: string;\n kind: MnemoDecision[\"kind\"];\n title: string;\n body: string;\n topicKey?: string;\n decidedByUserId?: string;\n confidence?: number;\n validFrom?: Date;\n sensitivity?: Sensitivity;\n metadata?: Record<string, unknown>;\n}\n\nexport interface UpdateDecisionInput {\n workspaceId: string;\n title?: string;\n body?: string;\n status?: MnemoDecision[\"status\"];\n supersededById?: string;\n validTo?: Date;\n metadata?: Record<string, unknown>;\n}\n\n/**\n * WP-6 / PRIM-18 — atomic decision supersession. Locks both decisions, then in\n * one transaction closes the predecessor (`status='superseded'`,\n * `supersededById`, `validTo`), records the `supersedes` lineage relation\n * (successor -> predecessor) and drops the predecessor from the vector index.\n *\n * Throws `StorageValidationError` for a self-supersede, `StorageNotFoundError`\n * when either decision is missing in the workspace, and `StorageConflictError`\n * when the successor is not active (which also rules out cycles) or the\n * predecessor was already replaced by a DIFFERENT decision. Repeating the same\n * transition is idempotent: it returns the predecessor unchanged.\n */\nexport interface SupersedeDecisionInput {\n workspaceId: string;\n /** The decision being replaced. */\n id: string;\n /** The decision that replaces it. */\n supersededById: string;\n actorId?: string;\n userId?: string | null;\n actorType?: ActorType;\n}\n\nexport interface DecisionFilter {\n workspaceId: string;\n status?: MnemoDecision[\"status\"];\n kind?: MnemoDecision[\"kind\"];\n topicKey?: string;\n /** When set, return records with scope_ref = X OR scope_ref IS NULL. */\n scopeRef?: string;\n /**\n * P135: other spellings of the project `scopeRef` names (its canonical name\n * and aliases). A row matches when its scope_ref is `scopeRef` or any of\n * these. Filled by the core from the workspace's `project` entities, never\n * by callers; ignored without `scopeRef`.\n */\n scopeRefAliases?: string[];\n validAt?: Date;\n /** Only rows open now (`validTo IS NULL`): the clock-free \"current\" filter (see EntityFilter.openOnly). */\n openOnly?: boolean;\n /** Only decisions in one of these statuses (ANDed with `status`). */\n statuses?: MnemoDecision[\"status\"][];\n /** Read ceiling: decisions above it are excluded in the query. Omitted → no ceiling. */\n maxSensitivity?: Sensitivity;\n /** Only decisions created at or after this instant. */\n createdSince?: Date;\n /** Only decisions whose `validTo ?? updatedAt` (ms precision) is strictly after this instant. */\n closedSince?: Date;\n /**\n * Newest first by this instant at ms precision, ties broken by id in byte\n * order, descending. `closedAt` is `validTo ?? updatedAt`. Unset keeps the\n * storage order.\n */\n orderBy?: \"createdAt\" | \"closedAt\";\n /** Keyset: only rows that sort after this position (older, or same ms and a smaller id). Needs `orderBy`. */\n before?: { at: Date; id: string };\n /** No COUNT: `total` is then `offset + items.length` and `hasMore` means the page came back full. */\n skipTotal?: boolean;\n offset?: number;\n limit?: number;\n}\n\nexport interface CreateEpisodeInput {\n workspaceId: string;\n agentId?: string;\n actorId?: string;\n userId?: string | null;\n actorType?: ActorType;\n /** Ownership: \"workspace:<id>\" | \"user:<id>\" | \"tenant:<id>\". Defaults to \"workspace:<workspaceId>\". */\n scopeOwner?: string;\n title: string;\n narrative: string;\n occurredAt: Date;\n durationMinutes?: number;\n participants?: string[];\n topics?: string[];\n linkedFactIds?: string[];\n parentEpisodeId?: string;\n deltaContent?: string;\n isSynthetic?: boolean;\n sourceConversationId?: string;\n sensitivity?: Sensitivity;\n metadata?: Record<string, unknown>;\n}\n\nexport type UpdateEpisodeInput = { workspaceId: string } & Partial<\n Pick<MnemoEpisode, \"title\" | \"narrative\" | \"topics\" | \"linkedFactIds\" | \"metadata\">\n>;\n\nexport interface EpisodeFilter {\n workspaceId: string;\n topics?: string[];\n participantId?: string;\n isSynthetic?: boolean;\n parentEpisodeId?: string; // NEW — direct children of this episode (spec §16 trees)\n after?: Date;\n before?: Date;\n /** P18 — asOf filter: validFrom <= validAt AND (validTo IS NULL OR validTo > validAt) */\n validAt?: Date;\n offset?: number;\n limit?: number;\n}\n\nexport interface CreateEntityInput {\n workspaceId: string;\n actorId?: string;\n agentId?: string;\n userId?: string | null;\n actorType?: ActorType;\n /** Ownership: \"workspace:<id>\" | \"user:<id>\" | \"tenant:<id>\". Defaults to \"workspace:<workspaceId>\". */\n scopeOwner?: string;\n name: string;\n kind: MnemoEntity[\"kind\"];\n aliases?: string[];\n canonicalId?: string;\n description?: string;\n sensitivity?: Sensitivity;\n metadata?: Record<string, unknown>;\n}\n\nexport type UpdateEntityInput = { workspaceId: string } & Partial<\n Pick<\n MnemoEntity,\n \"name\" | \"kind\" | \"aliases\" | \"metadata\" | \"linkedUserId\" | \"validTo\" | \"sensitivity\"\n >\n> & {\n /**\n * `null` explicitly clears the field (canonicalId: null = \"this row is\n * canonical again\"; description: null = \"no description\"); `undefined`\n * (omitted key) leaves it untouched. Widened beyond MnemoEntity's\n * (undefined-only) read shape to match the mutation semantics legacy\n * `CoreLike.updateEntity` already modeled (`description?: string | null`,\n * `canonicalId?: string | null`) — flatten-legacy-dual-core PR9a, found\n * while porting `routes/entities.ts patchEntityRoute` off `deps.core`.\n */\n description?: string | null;\n canonicalId?: string | null;\n };\n\n/**\n * WP-6 / PRIM-2 — atomic bitemporal revision of ONE live entity: close it,\n * insert a successor carrying the same name/kind/aliases/description, record\n * the `supersedes` lineage relation (successor -> closed) and enqueue the\n * embedding upkeep, all in one transaction. Unlink and reassignment are this\n * operation with a different `linkedUserId`; doing them as separate calls lost\n * the entity whenever the second one failed.\n *\n * Throws `StorageNotFoundError` when the entity does not exist in the\n * workspace, and `StorageConflictError` when it is already closed or when the\n * successor would collide with a live row (name/kind, or the user's live link).\n * A conflict rolls everything back, including the close.\n */\nexport interface SupersedeEntityInput {\n workspaceId: string;\n /** The live entity to close. */\n id: string;\n successor: {\n /** `null` = the successor is not linked to any user (unlink). */\n linkedUserId: string | null;\n sensitivity?: Sensitivity;\n actorId?: string;\n userId?: string | null;\n actorType?: ActorType;\n };\n}\n\nexport interface EntityFilter {\n workspaceId: string;\n kind?: MnemoEntity[\"kind\"];\n /** Exact match on `name`. For substring search across name + aliases, use `q`. */\n name?: string;\n /**\n * Case-insensitive substring search across `name` AND `aliases`\n * (flatten-legacy-dual-core PR9a / D6.2) — mirrors legacy\n * `core/src/entity/query.ts`'s `listEntities` `q` filter. Distinct from\n * `name`, which stays exact-match.\n */\n q?: string;\n /** P18 — asOf filter: validFrom <= validAt AND (validTo IS NULL OR validTo > validAt) */\n validAt?: Date;\n /**\n * Only rows that are open now (`validTo IS NULL`), decided by the row alone.\n * This is the \"current list\" filter. `validAt: new Date()` is not: rows are\n * stamped by Postgres `now()`, so a server clock a few milliseconds behind\n * the database's hid a row created a moment earlier.\n */\n openOnly?: boolean;\n offset?: number;\n limit?: number;\n}\n\nexport interface CreateStrategyInput {\n workspaceId: string;\n agentId?: string;\n actorId?: string;\n userId?: string | null;\n actorType?: ActorType;\n /** Ownership: \"workspace:<id>\" | \"user:<id>\" | \"tenant:<id>\". Defaults to \"workspace:<workspaceId>\". */\n scopeOwner?: string;\n /** Project/entity scope reference (e.g. 'project-x'). Mirrors mnemo_fact.scope_ref. */\n scopeRef?: string;\n trigger: string;\n action: string;\n context?: string;\n relatedFacts?: string[];\n attribution?: MnemoStrategy[\"attribution\"];\n supersedesId?: string;\n validFrom?: Date;\n sensitivity?: Sensitivity;\n metadata?: Record<string, unknown>;\n}\n\nexport type UpdateStrategyInput = { workspaceId: string } & Partial<\n Pick<\n MnemoStrategy,\n | \"trigger\"\n | \"action\"\n | \"context\"\n | \"status\"\n | \"validTo\"\n | \"metadata\"\n | \"successCount\"\n | \"failureCount\"\n | \"worth\"\n | \"relatedFacts\"\n | \"attribution\"\n >\n>;\n\nexport interface StrategyFilter {\n workspaceId: string;\n status?: MnemoStrategy[\"status\"];\n /** When set, return records with scope_ref = X OR scope_ref IS NULL. */\n scopeRef?: string;\n /**\n * P135: other spellings of the project `scopeRef` names (its canonical name\n * and aliases). A row matches when its scope_ref is `scopeRef` or any of\n * these. Filled by the core from the workspace's `project` entities, never\n * by callers; ignored without `scopeRef`.\n */\n scopeRefAliases?: string[];\n validAt?: Date;\n /** Only rows open now (`validTo IS NULL`): the clock-free \"current\" filter (see EntityFilter.openOnly). */\n openOnly?: boolean;\n offset?: number;\n limit?: number;\n}\n\nexport interface CreateWorkflowInput {\n workspaceId: string;\n actorId?: string;\n agentId?: string;\n userId?: string | null;\n actorType?: ActorType;\n /** Ownership: \"workspace:<id>\" | \"user:<id>\" | \"tenant:<id>\". Defaults to \"workspace:<workspaceId>\". */\n scopeOwner?: string;\n /** Project/entity scope reference (e.g. 'project-x'). Mirrors mnemo_fact.scope_ref. */\n scopeRef?: string;\n name: string;\n description?: string;\n steps: WorkflowStep[];\n sensitivity?: Sensitivity;\n metadata?: Record<string, unknown>;\n}\n\nexport type UpdateWorkflowInput = { workspaceId: string } & Partial<\n Pick<MnemoWorkflow, \"name\" | \"description\" | \"steps\" | \"status\" | \"metadata\">\n>;\n\nexport interface WorkflowFilter {\n workspaceId: string;\n status?: MnemoWorkflow[\"status\"];\n /** When set, return records with scope_ref = X OR scope_ref IS NULL. */\n scopeRef?: string;\n /**\n * P135: other spellings of the project `scopeRef` names (its canonical name\n * and aliases). A row matches when its scope_ref is `scopeRef` or any of\n * these. Filled by the core from the workspace's `project` entities, never\n * by callers; ignored without `scopeRef`.\n */\n scopeRefAliases?: string[];\n /** P18 — asOf filter: validFrom <= validAt AND (validTo IS NULL OR validTo > validAt) */\n validAt?: Date;\n /** Only rows open now (`validTo IS NULL`): the clock-free \"current\" filter (see EntityFilter.openOnly). */\n openOnly?: boolean;\n offset?: number;\n limit?: number;\n}\n\nexport interface CreateSkillInput {\n workspaceId: string;\n actorId?: string;\n agentId?: string;\n userId?: string | null;\n actorType?: ActorType;\n /** Ownership: \"workspace:<id>\" | \"user:<id>\" | \"tenant:<id>\". Defaults to \"workspace:<workspaceId>\". */\n scopeOwner?: string;\n name: string;\n promptTemplate: string;\n variables?: string[];\n requiredContext?: string[];\n sensitivity?: Sensitivity;\n metadata?: Record<string, unknown>;\n}\n\nexport type UpdateSkillInput = { workspaceId: string } & Partial<\n Pick<MnemoSkill, \"name\" | \"promptTemplate\" | \"variables\" | \"requiredContext\" | \"metadata\">\n>;\n\nexport interface SkillFilter {\n workspaceId: string;\n /** P18 — asOf filter: validFrom <= validAt AND (validTo IS NULL OR validTo > validAt) */\n validAt?: Date;\n /** Only rows open now (`validTo IS NULL`): the clock-free \"current\" filter (see EntityFilter.openOnly). */\n openOnly?: boolean;\n offset?: number;\n limit?: number;\n}\n\nexport interface CreateTaskInput {\n workspaceId: string;\n actorId?: string;\n agentId?: string;\n userId?: string | null;\n actorType?: ActorType;\n /** Ownership: \"workspace:<id>\" | \"user:<id>\" | \"tenant:<id>\". Defaults to \"workspace:<workspaceId>\". */\n scopeOwner?: string;\n title: string;\n description?: string;\n priority?: MnemoTask[\"priority\"];\n assignedTo: string;\n sessionId?: string;\n parentTaskId?: string;\n dueAt?: Date;\n delegatedBy?: string;\n relatedFacts?: string[];\n relatedEntities?: string[];\n sensitivity?: Sensitivity;\n metadata?: Record<string, unknown>;\n}\n\nexport interface DelegateTaskInput {\n assignedTo: string;\n delegatedBy: string;\n}\n\nexport type UpdateTaskInput = { workspaceId: string } & Partial<\n Pick<\n MnemoTask,\n | \"title\"\n | \"description\"\n | \"status\"\n | \"priority\"\n | \"assignedTo\"\n | \"blockedBy\"\n | \"subtaskIds\"\n | \"outcome\"\n | \"lessonsLearned\"\n | \"startedAt\"\n | \"completedAt\"\n | \"dueAt\"\n | \"metadata\"\n >\n>;\n\nexport interface TaskFilter {\n workspaceId: string;\n status?: MnemoTask[\"status\"];\n assignedTo?: string;\n parentTaskId?: string;\n /** P18 — asOf filter: validFrom <= validAt AND (validTo IS NULL OR validTo > validAt) */\n validAt?: Date;\n /** Only rows open now (`validTo IS NULL`): the clock-free \"current\" filter (see EntityFilter.openOnly). */\n openOnly?: boolean;\n offset?: number;\n limit?: number;\n}\n\n/**\n * B7 — the task statuses with no outgoing transitions (mirrors\n * `TASK_TRANSITIONS` entries that are `[]` in `@mnemo-ai/core`'s\n * `cognitive/tasks.ts`). Lives here, not in `@mnemo-ai/core`, because\n * storage adapters (`@mnemo-ai/adapter-postgres`, the in-memory test\n * adapter) implement `archiveTask` and must stay terminal-aware without\n * importing core. `core/cognitive/__tests__/task-state-machine.test.ts`\n * asserts this set equals the derived terminal set — single source of\n * truth enforced by test, not by re-exporting from core.\n */\nexport const TERMINAL_TASK_STATUSES = [\"completed\", \"cancelled\"] as const;\n\nexport interface CreateEventInput {\n workspaceId: string;\n agentId?: string;\n actorId?: string;\n userId?: string | null;\n actorType?: ActorType;\n /** Ownership: \"workspace:<id>\" | \"user:<id>\" | \"tenant:<id>\". Defaults to \"workspace:<workspaceId>\". */\n scopeOwner?: string;\n type: MnemoEvent[\"type\"];\n name: string;\n description: string;\n occurredAt: Date;\n durationS?: number;\n source: string;\n relatedEntities?: string[];\n annotations?: EventAnnotation[];\n sensitivity?: Sensitivity;\n metadata?: Record<string, unknown>;\n}\n\nexport interface EventFilter {\n workspaceId: string;\n type?: MnemoEvent[\"type\"];\n source?: string;\n after?: Date;\n before?: Date;\n offset?: number;\n limit?: number;\n}\n\nexport interface CreateReasoningInput {\n workspaceId: string;\n agentId?: string;\n actorId?: string;\n userId?: string | null;\n actorType?: ActorType;\n /** Ownership: \"workspace:<id>\" | \"user:<id>\" | \"tenant:<id>\". Defaults to \"workspace:<workspaceId>\". */\n scopeOwner?: string;\n question: string;\n chain: MnemoReasoning[\"chain\"];\n conclusion: string;\n topicKey?: string;\n sensitivity?: Sensitivity;\n metadata?: Record<string, unknown>;\n}\n\nexport type UpdateReasoningInput = { workspaceId: string } & Partial<\n Pick<MnemoReasoning, \"status\" | \"chain\" | \"conclusion\" | \"metadata\">\n>;\n\nexport interface ReasoningFilter {\n workspaceId: string;\n status?: MnemoReasoning[\"status\"];\n topicKey?: string;\n /** PRIM-16 — validFrom <= validAt AND (validTo IS NULL OR validTo > validAt): current rows. */\n validAt?: Date;\n /** Only rows open now (`validTo IS NULL`): the clock-free \"current\" filter (see EntityFilter.openOnly). */\n openOnly?: boolean;\n offset?: number;\n limit?: number;\n}\n\n// ── Hyperedges ──────────────────────────────────────────────────────────────\n\nexport interface CreateHyperedgeInput {\n workspaceId: string;\n memberIds: string[];\n label?: string;\n description?: string;\n contextQuery?: string;\n contextEmbedding?: Float32Array;\n actorId?: string;\n userId?: string | null;\n actorType?: ActorType;\n /**\n * WP-6 / PRIM-13: also require every member id to exist in this workspace\n * (any primitive kind). Off by default so internal writers that already hold\n * real ids pay nothing; the HTTP route turns it on. Repeated members are\n * rejected either way (`StorageValidationError`).\n */\n verifyMembers?: boolean;\n /**\n * With `verifyMembers`: the caller's sensitivity ceiling. A member above it is\n * treated exactly like a nonexistent one (same error, no ids), so member\n * validation is not an existence oracle across sensitivity levels. Omitted =\n * no ceiling (trusted internal callers).\n */\n maxSensitivity?: Sensitivity;\n}\n\nexport type UpdateHyperedgeInput = Partial<\n Pick<MnemoHyperedge, \"label\" | \"description\" | \"contextQuery\">\n> & {\n /**\n * WP-6 / PRIM-12: the workspace the hyperedge belongs to. The update has to\n * set the RLS workspace GUC BEFORE reading the row; without it the lookup\n * ran as no workspace and every PATCH failed under the production role.\n * Optional only for backward compatibility with callers that predate it.\n */\n workspaceId?: string;\n};\n\nexport interface HyperedgeFilter {\n workspaceId: string;\n memberId?: string;\n label?: string;\n /** Include closed (deleted) hyperedges. Default false: only open ones. */\n includeClosed?: boolean;\n /**\n * The caller's ceiling: a hyperedge with any member above it is left out of\n * the page and of `total`. Member ids that resolve to no row don't hide it.\n */\n maxSensitivity?: Sensitivity;\n offset?: number;\n limit?: number;\n}\n\n// ── Composition rules ───────────────────────────────────────────────────────\n\nexport interface CreateCompositionRuleInput {\n workspaceId: string;\n name: string;\n description?: string;\n conditionDsl: unknown;\n actionDsl: unknown;\n priority?: number;\n isActive?: boolean;\n createdBy?: string;\n source?: MnemoCompositionRule[\"source\"];\n metadata?: Record<string, unknown>;\n}\n\nexport type UpdateCompositionRuleInput = Partial<\n Pick<\n MnemoCompositionRule,\n \"name\" | \"description\" | \"conditionDsl\" | \"actionDsl\" | \"priority\" | \"isActive\" | \"metadata\"\n >\n>;\n\nexport interface CompositionRuleFilter {\n workspaceId: string;\n isActive?: boolean;\n source?: MnemoCompositionRule[\"source\"];\n offset?: number;\n limit?: number;\n}\n\n// ── Inference log ───────────────────────────────────────────────────────────\n\nexport interface AppendInferenceInput {\n workspaceId: string;\n ruleId: string;\n inputFactIds: string[];\n derivedKind?: string;\n derivedId?: string;\n confidence: number;\n rationale?: string;\n triggeredByQuery?: string;\n conversationId?: string;\n}\n\nexport interface MaterialiseInferenceInput {\n ruleId: string;\n workspaceId: string;\n fact: {\n scope: string;\n kind: string;\n subject: string;\n statement: string;\n attribution: string;\n sensitivity: Sensitivity;\n metadata: Record<string, unknown>;\n };\n inferenceLog: {\n inputFactIds: string[];\n derivedKind: string;\n confidence: number;\n rationale: string;\n triggeredByQuery?: string;\n conversationId?: string;\n };\n}\n\nexport interface InferenceLogFilter {\n workspaceId: string;\n ruleId?: string;\n derivedId?: string;\n since?: Date;\n offset?: number;\n limit?: number;\n}\n\n// ── Fact hash ───────────────────────────────────────────────────────────────\n\nexport interface UpsertFactHashInput {\n workspaceId: string;\n statementHash: string;\n factId: string;\n}\n\nexport interface CreateRelationInput {\n workspaceId: string;\n sourceId: string;\n sourceType: RelationNodeKind;\n targetId: string;\n targetType: RelationNodeKind;\n verb: RelationVerb;\n weight?: number;\n actorId?: string;\n userId?: string | null;\n actorType?: ActorType;\n\n /**\n * flatten-legacy-dual-core D6.4 — the judgment-workflow overlay on the\n * SAME physical `mnemo_relation` row. All optional: DB defaults stay\n * authoritative when omitted (`judgmentStatus: 'pending'`,\n * `markedByKind: 'system'`, everything else `null`). `evidence` is the\n * real physical column — there is no separate `metadata` field.\n */\n judgmentStatus?: JudgmentStatus;\n reason?: string | null;\n evidence?: Record<string, unknown> | null;\n confidence?: number | null;\n markedByUserId?: string | null;\n markedByKind?: MarkerKind;\n markedByModel?: string | null;\n markedByPromptVersion?: string | null;\n provenance?: string | null;\n conversationId?: string | null;\n supersededByRelationId?: string | null;\n validFrom?: Date;\n validTo?: Date | null;\n}\n\nexport interface RelationFilter {\n workspaceId: string;\n sourceId?: string;\n targetId?: string;\n /** TRAVERSE-1 batched BFS layer — routes/relations.ts already needs this. */\n sourceIds?: string[];\n /**\n * flatten-legacy-dual-core PR9f (design.md D6.5) — the batched-BFS\n * counterpart of `sourceIds`, matching a frontier node against the\n * `targetId` column. `mnemo_relation` is a single directed row per pair;\n * legacy `traverseRelations`/`findShortestPath` treat it as UNDIRECTED\n * (`r.source_id = node OR r.target_id = node`). `sourceIds` alone would\n * silently miss every edge where the frontier node happens to be stored\n * in the `target_id` column — `traverseGraph`/`findGraphPath` query both\n * batched filters per hop to reproduce the exact undirected semantics.\n */\n targetIds?: string[];\n verb?: RelationVerb;\n verbs?: RelationVerb[];\n judgmentStatus?: JudgmentStatus;\n /** Bitemporal point-in-time filter: `validFrom <= validAt AND (validTo IS NULL OR validTo > validAt)`. */\n validAt?: Date;\n /**\n * Only relations that are open now (`validTo IS NULL`). Defaults to true\n * unless `validAt` is given: a relation closed by a delete or a hard delete\n * is not part of the current graph (PRIM-12, PRIM-13). Readers that need\n * the history (export, lineage, conflict bookkeeping) pass `false`.\n */\n openOnly?: boolean;\n /**\n * The caller's sensitivity ceiling. A relation whose source or target row is\n * above it is left out (before `limit`), so a capped walk never reaches, names\n * or counts a node it may not see. Ids that resolve to no row still pass.\n */\n maxSensitivity?: Sensitivity;\n limit?: number;\n}\n\n/**\n * flatten-legacy-dual-core D6.4 — apply a judgment decision to an existing\n * relation (PATCH /relations/:id equivalent, wired by PR 9d). Always sets\n * `judgmentStatus: \"judged\"` on the target row; every other field is set\n * only when provided. Returns `null` when the row does not exist in this\n * workspace (never throws for \"not found\").\n */\nexport interface ApplyRelationJudgmentInput {\n workspaceId: string;\n id: string;\n relation: RelationVerb;\n reason?: string;\n evidence?: Record<string, unknown>;\n confidence?: number;\n markedByKind: MarkerKind;\n markedByUserId?: string | null;\n markedByModel?: string;\n markedByPromptVersion?: string;\n /** The caller's ceiling: a relation with an endpoint above it reads as missing (`null`). */\n maxSensitivity?: Sensitivity;\n}\n\n/**\n * flatten-legacy-dual-core Slice 3c (B5, design.md's \"Coordination decision\").\n *\n * `routes/conflicts.ts`'s `POST /conflicts/:id/resolve` chains up to 6 separate\n * writes (close 1-2 facts, optionally create a merged fact, patch the judged\n * relation, create 1-2 `supersedes` relations). The legacy `CoreLike` chained\n * 6 independently-committed calls — non-atomic, the exact bug this closes.\n * `MnemoRelation`/`CreateRelationInput`'s judgment-workflow fields have no v3\n * port equivalent for `patchRelation` (no v3 method at all) and only a subset\n * for `createRelation` (see PR8's disclosed `relations.ts` finding in\n * design.md's Open Questions) — reusing those generic methods here would\n * still need 4-6 separate calls, reintroducing the same non-atomicity. This\n * ONE composite method performs the whole resolution inside a single DB\n * transaction instead, matching the `FactRepository.replaceFact` precedent\n * (close + insert + relation-insert, one `db.transaction`).\n */\nexport type ConflictResolutionAction = \"supersede_a\" | \"supersede_b\" | \"keep_both\" | \"merge\";\n\nexport interface ResolveConflictInput {\n workspaceId: string;\n /** The existing `conflicts_with` relation id being resolved. */\n relationId: string;\n sourceId: string;\n sourceKind: string;\n targetId: string;\n targetKind: string;\n action: ConflictResolutionAction;\n /** Required when action === \"merge\". */\n mergedStatement?: string;\n actorId?: string;\n userId?: string | null;\n actorType?: ActorType;\n}\n\nexport interface ResolveConflictResult {\n /** The newly created merged fact's id, only when action === \"merge\". */\n mergedFactId: string | null;\n}\n\nexport interface RecallLogEntry {\n workspaceId: string;\n factId: string;\n sessionId?: string;\n queryText?: string;\n hitRank?: number;\n tdCredit?: number;\n activationScore?: number;\n latencyMs?: number; // Wall-clock recall latency in ms; NULL for legacy rows\n}\n\n// ─── harden-hooks-and-measure-precision (Slice 4, A2-read) — precision-at-k ──\n//\n// Requirement 5/6: \"of the hits served at rank < k, what fraction went on to\n// receive TD(λ) credit ... in the same session.\" Derived ENTIRELY from\n// already-persisted `mnemo_recall_log` + `mnemo_session` columns — no new\n// write path, no port write method, no schema migration. See\n// openspec/harden-hooks-and-measure-precision/design.md for the full\n// data-mapping, the exact definition of \"credited\", and documented\n// limitations of this coarse proxy.\n\n/** One k value's precision figure, always paired with its sample size. */\nexport interface RecallPrecisionAtK {\n k: number;\n /** null when sampleSize is 0 — never a fabricated 0 or 1 (Requirement 5). */\n precision: number | null;\n /** Count of hits at hitRank < k whose session resolved (collapsed). */\n sampleSize: number;\n}\n\n/** Fixed caveat text returned on every {@link RecallPrecisionReport} — Requirement 6. */\nexport const RECALL_PRECISION_METHODOLOGY_NOTE =\n \"TD(λ) credit is a coarse session-level proxy, not per-hit attribution: a hit \" +\n 'counts as \"credited\" only when its session collapsed AND created at least one ' +\n \"fact, and the hit falls within the 20-most-recently-recalled window that \" +\n \"propagateTdCredit actually reads (mnemo_session.fact_count > 0, recency rank \" +\n \"≤ 20 within its session) — not because this specific hit was verified to \" +\n \"shape that fact. Hits whose session never collapsed are excluded from every \" +\n \"denominator, not counted as failures (design.md). Per-hit attribution requires \" +\n \"the D5 citation write path, which is out of scope for this report.\";\n\n/** Requirement 5/6 report shape — see {@link RecallPort.getRecallPrecision}. */\nexport interface RecallPrecisionReport {\n workspaceId: string;\n computedAt: Date;\n /** All mnemo_recall_log rows considered (hitRank IS NOT NULL, sessionId IS NOT NULL). */\n totalHits: number;\n /** Hits whose session never collapsed — excluded from every precisionAtK denominator. */\n pendingHits: number;\n /** Precision at k = 1, 3, 5 (Requirement 5's \"at least k ∈ {1, 3, 5}\"). */\n precisionAtK: RecallPrecisionAtK[];\n /** true when every k has sampleSize === 0 (Requirement 5's insufficient-data scenario). */\n insufficientData: boolean;\n /** Always present; equal to {@link RECALL_PRECISION_METHODOLOGY_NOTE}. */\n methodologyNote: string;\n}\n\n// ─── Webhook types ────────────────────────────────────────────────────────────\n\nexport interface MnemoWebhookEndpoint {\n id: string;\n workspaceId: string;\n url: string;\n events: string[];\n secretHash: string;\n isActive: boolean;\n description: string | null;\n failureCount: number;\n disabledAt: Date | null;\n createdAt: Date;\n updatedAt: Date;\n}\n\nexport interface CreateWebhookEndpointInput {\n id: string;\n workspaceId: string;\n url: string;\n events: string[];\n secretHash: string;\n description?: string;\n}\n\nexport interface UpdateWebhookEndpointInput {\n url?: string;\n events?: string[];\n isActive?: boolean;\n description?: string;\n /** Delivery-worker: increment failure count for 3-strike auto-disable. */\n failureCount?: number;\n /** Delivery-worker: set when endpoint is auto-disabled after 3 strikes. */\n disabledAt?: Date | null;\n}\n\nexport interface MnemoWebhookDelivery {\n id: string;\n webhookId: string;\n workspaceId: string;\n eventType: string;\n payload: Record<string, unknown>;\n status: \"pending\" | \"delivered\" | \"failed\";\n responseStatus: number | null;\n responseBody: string | null;\n attempt: number;\n deliveredAt: Date | null;\n nextAttemptAt: Date | null;\n createdAt: Date;\n}\n\nexport interface CreateWebhookDeliveryInput {\n id: string;\n webhookId: string;\n workspaceId: string;\n eventType: string;\n payload: Record<string, unknown>;\n status: \"pending\" | \"delivered\" | \"failed\";\n responseStatus?: number;\n responseBody?: string;\n attempt?: number;\n deliveredAt?: Date;\n}\n\n// ─── Prospective memory (reminders) ──────────────────────────────────────────\n\nexport interface MnemoReminder {\n id: string;\n workspaceId: string;\n content: string;\n /** REMIND-1: nullable — a reminder may be time-only (no semantic condition). */\n condition: string | null;\n triggerAt: Date | null;\n status: \"pending\" | \"triggered\" | \"dismissed\";\n conditionEmbedding: number[] | null;\n triggeredAt: Date | null;\n dismissedAt: Date | null;\n /**\n * LIFECYCLE-6: when a recall first returned this reminder to an agent. Null\n * on a triggered reminder means it fired (by the poller, or by a recall that\n * failed to answer) and no agent has seen it yet.\n */\n deliveredAt?: Date | null;\n createdByAgentId: string | null;\n actorId?: string;\n userId?: string | null;\n actorType?: ActorType;\n createdAt: Date;\n updatedAt: Date;\n}\n\nexport interface CreateReminderInput {\n id: string;\n workspaceId: string;\n content: string;\n /** REMIND-1: optional — a reminder needs at least one of condition/triggerAt. */\n condition?: string;\n triggerAt?: Date;\n conditionEmbedding?: number[];\n createdByAgentId?: string;\n /** The authenticating CREDENTIAL, namespaced ActorRef (e.g. \"key:<id>\"). */\n actorId?: string;\n /** The real mnemo_user.id behind the request, or null. */\n userId?: string | null;\n actorType?: ActorType;\n}\n\n// ─── Wave P: LSH Tier 2 types ────────────────────────────────────────────────\n\nexport interface LshBandValue {\n bandIdx: number;\n bandHash: bigint;\n}\n\nexport interface UpsertFactLshInput {\n workspaceId: string;\n factId: string;\n revision: number;\n bands: LshBandValue[];\n}\n\nexport type RecallPrimitiveValue =\n | MnemoFact\n | MnemoDecision\n | MnemoEpisode\n | MnemoEntity\n | MnemoStrategy\n | MnemoWorkflow\n | MnemoSkill\n | MnemoTask\n | MnemoEvent\n | MnemoReasoning;\n\nexport interface RecallPrimitiveRef {\n id: string;\n kind: Exclude<PrimitiveKind, \"hyperedge\">;\n}\n\nexport interface RecallPrimitiveRecord extends RecallPrimitiveRef {\n value: RecallPrimitiveValue;\n}\n\nexport interface RecallLogRecord {\n memoryId: string;\n id: string;\n recalledAt: string;\n recallScore: number;\n}\n\nexport interface RecallStructures {\n relations: MnemoRelation[];\n hyperedges: Array<{ memberId: string; hyperedge: MnemoHyperedge }>;\n}\n\nexport interface PointerCandidateQuery {\n workspaceId: string;\n terms: string[];\n bands: LshBandValue[];\n limit: number;\n filter?: RecallFilter;\n includeArchived?: boolean;\n includeLowWorth?: boolean;\n /** Recall-only: retry an empty strict FTS result with two content-term matches. */\n relaxedOnEmpty?: boolean;\n /**\n * Point-in-time recall: only rows whose validity interval contains this\n * instant (`validFrom <= asOf AND (validTo IS NULL OR validTo > asOf)`),\n * whatever their status now. Replaces the \"current rows\" gate and\n * `includeArchived`.\n */\n asOf?: Date;\n}\n\nexport interface PointerCandidate {\n factId: string;\n statement: string;\n embedding: number[] | null;\n sensitivity: Sensitivity;\n worth: number;\n worthAlpha?: number;\n worthBeta?: number;\n /** Judged observations; both 0 means untested (see isUntestedWorth). */\n worthSuccess?: number;\n worthFailure?: number;\n attribution: Provenance;\n createdAt: Date;\n validFrom?: Date;\n status: MnemoFact[\"status\"];\n validTo: Date | null;\n confidence?: number;\n tags?: string[];\n scope?: MnemoFact[\"scope\"];\n scopeRef?: string;\n actorId?: string | null;\n /**\n * Platform account behind the write, when one exists. NOTE: as of the\n * provenance-identity fix (migration 0023), the storage-adapter query that\n * populates PointerCandidate has not yet been updated to select user_id —\n * this field will read undefined via that path until it is. Present here\n * so the recall-cold.ts FTS hit mapper is ready to carry it through once\n * the adapter catches up.\n */\n userId?: string | null;\n actorType?: ActorType;\n entityId?: string;\n sessionId?: string;\n /** Ownership label (\"workspace:<id>\" | \"user:<id>\" | \"tenant:<id>\"); absent on legacy rows. */\n scopeOwner?: string;\n /** The fact's topicKey, when it has one — shown on recall hits so a writer can reuse it. */\n topicKey?: string;\n subject?: string;\n}\n\nexport interface FtsCandidate extends PointerCandidate {\n rank: number;\n}\n\n/**\n * make-primitives-recallable (design.md D4/Interfaces) — one candidate hit\n * from `StorageAdapter.recallableCandidates?()`. Deliberately NOT an\n * `FtsCandidate`/`PointerCandidate` extension: those two are irreducibly\n * fact-shaped (`factId`, `statement`, `worth`, `attribution`,\n * `status: MnemoFact[\"status\"]`); reshaping them to fit a decision would move\n * the fact ranking path this change must leave untouched. `score` is either a\n * cosine similarity in [0,1] (semantic arm) or a `ts_rank` value (lexical\n * arm) — the caller (recall-cold.ts, PR4) decides how the two are compared\n * and damped, this port method only reports which arm(s) produced a match.\n */\nexport interface PrimitiveCandidate {\n id: string;\n kind: PrimitiveKind;\n score: number;\n sensitivity: Sensitivity;\n /**\n * WP-3: the evidence behind `score`, kept per arm. `score` is the larger of\n * the two when both arms matched, which mixes a cosine with a `ts_rank`; a\n * caller that ranks across kinds needs them apart. Optional so an adapter\n * that predates them still works: recall-cold then reads `score` as the\n * cosine when it sent no `terms`.\n */\n similarity?: number;\n lexicalRank?: number;\n}\n\n/**\n * Query for `StorageAdapter.recallableCandidates?()`. `kinds` DRIVES which\n * table(s) are searched — it is not a post-filter — so `kinds: [\"decision\"]`\n * searches only `mnemo_decision`, never facts. Supply `embedding` for the\n * semantic (cosine) arm, `terms` for the lexical (`ts_rank`) arm, either or\n * both; supplying neither returns `[]` without issuing a query.\n */\nexport interface PrimitiveCandidateQuery {\n workspaceId: string;\n kinds: PrimitiveKind[];\n limit: number;\n embedding?: number[];\n minSimilarity?: number;\n terms?: string[];\n /**\n * RECALL-7: when the strict lexical match (every term) finds nothing for a\n * kind, retry with rows matching at least two distinct content terms — the\n * fallback the fact FTS arm already has. Recall sets it; default off.\n */\n relaxedOnEmpty?: boolean;\n /**\n * RECALL-6: exact ownership label, applied in both arms before `limit`, so a\n * personal-only recall is not starved by a window full of workspace rows.\n */\n scopeOwner?: string;\n /** Point-in-time recall: rows valid at this instant instead of the live ones. */\n asOf?: Date;\n}\n\n/** Query for `StorageAdapter.federatedRecallCandidates?()`. */\nexport interface FederatedRecallQuery {\n workspaceId: string;\n terms: string[];\n limit: number;\n /** The tiers the caller may read; a row at any other tier is never returned. */\n sensitivity: Sensitivity[];\n}\n\n/** One federated item that matched a recall, as the receiving server stored it. */\nexport interface FederatedRecallCandidate {\n /** The item's id on this server (`local_id`). */\n id: string;\n /** The peer it came from, as that peer named itself. */\n peerDomain: string;\n statement: string;\n /** The tier the peer gave it; anything but the four tiers reads as `restricted`. */\n sensitivity: Sensitivity;\n /** ISO timestamps as the peer sent them; the caller drops unparseable ones. */\n validFrom: string | null;\n validTo: string | null;\n /** `ts_rank` of the match. */\n lexicalRank: number;\n}\n\nexport interface ConsolidationWorthSnapshot {\n alpha: number;\n beta: number;\n success: number;\n failure: number;\n}\n\nexport interface ConsolidationMergeSnapshot {\n operationId: string;\n workspaceId: string;\n survivorId: string;\n absorbedFactIds: string[];\n previousWorth: ConsolidationWorthSnapshot;\n expectedMergedWorth: ConsolidationWorthSnapshot;\n}\n\nexport interface ApplyConsolidationMergeInput {\n operationId: string;\n workspaceId: string;\n survivorId: string;\n absorbedFactIds: string[];\n leaseExpiresAt: Date;\n}\n\nexport interface ReplayFailureReview {\n reason: \"replay_validation_failed\" | \"replay_execution_failed\";\n passCount: number;\n failCount: number;\n queriesUsed: string[];\n}\n\n// ── SOC2 CF3 — Retention purge ──────────────────────────────────────────────\n\n/**\n * Filter passed to StorageAdapter.purgeFacts?().\n * Caller MUST never pass sensitivity='public' (spec: public facts are never purged).\n */\nexport interface PurgeFactsFilter {\n workspaceId: string;\n /** The sensitivity tier to purge. Must not be 'public'. */\n sensitivity: Sensitivity;\n /** Soft-close facts with createdAt < now() - olderThanDays. */\n olderThanDays: number;\n /**\n * When true: count matching rows and compute erase candidates but do NOT\n * execute any UPDATE or append any deletion-log row.\n */\n dryRun?: boolean;\n /** Max rows updated per call (default 500). Bounds transaction length. */\n limit?: number;\n}\n\n/**\n * Result returned by StorageAdapter.purgeFacts?().\n */\nexport interface PurgeFactsResult {\n /** Number of fact rows whose status was set to 'forgotten' (0 in dry-run). */\n softClosed: number;\n /**\n * actorIds whose encrypted facts (confidential + restricted combined) all\n * have validTo IS NOT NULL after this purge — safe to call destroyActorDek.\n * Always empty when sensitivity='internal' (no DEK for plaintext tier).\n * Always empty in dry-run mode.\n */\n eraseCandidateActorIds: string[];\n /**\n * userIds (the platform account behind a write, when one exists) whose\n * encrypted facts — across EVERY actorId/key they've used — all have\n * validTo IS NOT NULL after this purge. Safe to call destroyUserDeks,\n * which destroys ALL of that person's DEKs in one call (a person with\n * multiple keys has multiple actor-keyed DEKs; this is what makes erasure\n * actually per-person instead of per-credential). Always empty when\n * sensitivity='internal' or in dry-run mode, same as eraseCandidateActorIds.\n */\n eraseCandidateUserIds: string[];\n}\n\n// ─── StorageAdapter ───────────────────────────────────────────────────────────\n\nexport interface StorageCapabilities {\n vectorSearch: boolean;\n ftsSearch: boolean;\n bitemporal: boolean;\n graphExpansion: boolean;\n transactions: boolean;\n rls: boolean;\n}\n\nexport interface HarnessIngestionPort {\n ingestHarnessEvent(input: {\n workspaceId: string;\n provenance: ManagedSessionProvenance;\n event: HarnessEvent;\n receivedAt: Date;\n }): Promise<HarnessEventAck>;\n}\n\nexport interface ManagedSessionLifecyclePort {\n claimManagedSessions(input: {\n workspaceId: string;\n leaseOwner: string;\n limit: number;\n inactivityMs: number;\n provisionalGraceMs: number;\n leaseMs: number;\n }): Promise<ManagedSessionClaim[]>;\n markManagedCollapseRetry(input: {\n workspaceId: string;\n sessionId: string;\n leaseOwner: string;\n error: string;\n baseRetryMs: number;\n maxRetryMs: number;\n }): Promise<ManagedCollapseRetry | null>;\n finalizeManagedArchive(input: {\n workspaceId: string;\n sessionId: string;\n leaseOwner: string;\n operationId: string;\n reason: ManagedArchiveReason;\n }): Promise<boolean>;\n releaseExpiredManagedLeases(input: { workspaceId: string }): Promise<number>;\n retryLegacyManagedArchive(input: { workspaceId: string; sessionId: string }): Promise<boolean>;\n quiesceManagedLifecycle(input: { workspaceId: string }): Promise<ManagedLifecycleQuiesceResult>;\n listManagedCollapseTurns(sessionId: string, workspaceId: string): Promise<SessionTurn[]>;\n purgeManagedTurns(input: {\n workspaceId: string;\n terminalBefore: Date;\n limit: number;\n }): Promise<number>;\n\n /**\n * Cross-workspace managed lifecycle aggregate for scrape-time gauges.\n *\n * Deliberately a storage read rather than in-process counters: a counter only\n * knows what this replica saw since it started, which after a restart or beside\n * a second replica is not the state of the system.\n *\n * Returns only bounded, non-identifying groupings — never a workspace or\n * session id, which would become an unbounded Prometheus label.\n */\n /**\n * Erase the managed transcript behind an episode, tombstoning and auditing it\n * exactly as retention would but attributed to the caller.\n *\n * Exists as a port rather than route SQL so the governance rule — forgetting\n * knowledge also forgets the words that produced it — lives in one place and\n * cannot be half-applied by a caller that forgets to do it.\n */\n forgetManagedTranscriptForEpisode?(input: {\n workspaceId: string;\n episodeId: string;\n actorId: string;\n }): Promise<{ sessionId: string | null; turnsRemoved: number }>;\n\n /** Managed session metadata for a workspace export. Never includes content. */\n exportManagedSessions?(input: { workspaceId: string; limit: number }): Promise<\n Array<{\n sessionId: string;\n sourceHost: string;\n status: string;\n turnCount: number;\n startedAt: string | null;\n collapsedAt: string | null;\n archivedAt: string | null;\n archiveReason: string | null;\n captureIncomplete: boolean;\n }>\n >;\n\n /** Raw managed transcripts still held — a turn retention erased is simply absent. */\n exportManagedTranscripts?(input: { workspaceId: string; limit: number }): Promise<\n Array<{\n sessionId: string;\n turnIndex: number;\n role: string;\n content: string;\n sourceMessageId: string | null;\n createdAt: string | null;\n }>\n >;\n\n managedLifecycleStats?(): Promise<{\n active: number;\n pending: number;\n collapsed: number;\n archivedByReason: Array<{ reason: string; count: number }>;\n retryBuckets: Array<{ bucket: string; count: number }>;\n oldestPendingAgeSeconds: number | null;\n messageCountBuckets: Array<{ bucket: string; count: number }>;\n extraction: Array<{ result: string; count: number }>;\n incompleteCapture: number;\n }>;\n}\n\n// ─── segregate-storage-ports — narrow domain sub-ports (PR1, Phase 1 group A) ──\n//\n// PR1 of a stacked chain (design.md/tasks.md `segregate-storage-ports`) additively\n// extracts Port Map rows 1-8 as named interfaces below. Every member's name,\n// signature, optionality, and doc comment is copied VERBATIM from its original home\n// in the flat `StorageAdapter` interface further down this file — nothing here is a\n// behavior change. The flat `StorageAdapter` interface is intentionally left\n// completely untouched in this PR (zero deletions); groups B-E (the remaining 30\n// domain ports) and the final `StorageAdapter` intersection alias land in later PRs\n// in this chain (tasks 1.4-1.11). See design.md D3/D4 for placement rationale and\n// the per-method override table.\n\n/** Session lifecycle: create, append turns, close, scratch pad, and dedup lookups. */\nexport interface SessionPort {\n createSession(input: CreateSessionInput): Promise<MnemoSession>;\n /**\n * Sessions started and episodes remembered in the last `days` UTC days. See\n * {@link SessionStats}. Episodes and their linked facts above `maxSensitivity`\n * are not counted; sessions carry no content and are all counted.\n */\n getSessionStats(input: {\n workspaceId: string;\n days: number;\n maxSensitivity?: Sensitivity;\n }): Promise<SessionStats>;\n appendTurn(sessionId: string, turn: Omit<SessionTurn, \"id\" | \"createdAt\">): Promise<number>;\n listTurns(sessionId: string, workspaceId: string): Promise<SessionTurn[]>;\n closeSession(id: string, workspaceId: string): Promise<void>;\n recordCollapseFailure?(id: string, workspaceId: string, error: string): Promise<void>;\n /**\n * LIFECYCLE-7/8 — atomic, single-winner persistence of an ORDINARY\n * (non-managed) session collapse.\n *\n * Opens ONE workspace-scoped transaction and locks the session row. When the\n * session is missing, managed (`source_host` set) or already `collapsed`, it\n * returns `{ committed: false, status }` WITHOUT calling `apply`. Otherwise it\n * runs `apply` with a StorageAdapter bound to that transaction, then marks the\n * session `collapsed` in the same transaction and returns\n * `{ committed: true, value }`. A throw from `apply` rolls back every write it\n * made and leaves the session as it was, so the collapse can be retried.\n *\n * `apply` must only write: no model calls while the transaction is open.\n * Optional — callers fall back to the non-atomic write sequence + closeSession.\n *\n * `terminalStatus: \"archived\"` (review round) is the SKIPPED collapse's\n * commit: same lock and refusal rules, but the session ends `archived`, with\n * `archiveReason` stamped as `metadata.archiveReason`. Default `collapsed`.\n *\n * `topicLocks` (review round): the fact and decision topic keys `apply` will\n * create or merge. The adapter takes their locks in ONE sorted order right\n * after the session lock, before `apply` runs, so two collapses touching the\n * same topics in different orders queue instead of deadlocking.\n */\n commitSessionCollapse?<T>(\n input: {\n workspaceId: string;\n sessionId: string;\n /** Abort a stale snapshot before writing any extracted knowledge. */\n expectedTurnCount?: number;\n terminalStatus?: \"collapsed\" | \"archived\";\n archiveReason?: string;\n topicLocks?: { facts: string[]; decisions: string[] };\n },\n apply: (storage: StorageAdapter) => Promise<T>\n ): Promise<{ committed: true; value: T } | { committed: false; status: string | null }>;\n /**\n * §7 discard — archive a session WITHOUT collapsing it into durable knowledge.\n * Sets status='archived' (distinct from closeSession's 'collapsed') and leaves\n * context_snapshot null. Optional for backward-compat; callers guard with `?.`.\n *\n * `reason` (LIFECYCLE-14) is stamped as `metadata.archiveReason`, e.g.\n * `collapse_failed` when the sweep gave up after its last attempt. It is not\n * the managed `archive_reason` column, whose CHECK lists managed reasons only.\n */\n archiveSession?(id: string, workspaceId: string, reason?: string): Promise<void>;\n getSession(id: string, workspaceId: string): Promise<MnemoSession | null>;\n listSessions?(workspaceId: string, limit?: number, offset?: number): Promise<MnemoSession[]>;\n\n /**\n * Persist the explicit outcome rating a user gave a session.\n *\n * `mnemo_session.outcome_rating` has existed since the baseline migration,\n * constrained to 'success' | 'failure' | 'neutral', and is read by three\n * consumers: the `mnemo_metacognition_trends` SQL function (it *is*\n * `sessionCollapseQuality`), PluginRepository's §14 scored-trajectory list,\n * and MeteringRepository. No code ever wrote it — POST /session/:id/feedback\n * mapped the thumbs to a worth delta on the recalled facts and dropped the\n * session-level signal on the floor, so all three consumers read a column\n * that was permanently NULL.\n *\n * @returns true when a session row was updated, false when the id matched\n * nothing in this workspace — the caller decides whether that is a\n * 404, rather than the write silently reporting success.\n */\n recordSessionOutcome(\n sessionId: string,\n workspaceId: string,\n rating: \"success\" | \"failure\" | \"neutral\"\n ): Promise<boolean>;\n updateSessionSummary?(args: {\n sessionId: string;\n workspaceId: string;\n summary: Record<string, unknown>;\n factCount: number;\n }): Promise<void>;\n /**\n * autonomous-memory Requirement 1/4 (session-correlation, compliance-backstop):\n * stamps `metadata.lastRecallAt` (ISO string) on the given session, merged\n * (not replaced) into whatever metadata already exists. Best-effort — the\n * caller (POST /recall) treats a failure here as non-fatal, matching the\n * existing anticipation-preinject pattern. Optional for backward-compat;\n * callers guard with `?.`. A no-op (never throws \"not found\") when the\n * session id doesn't exist in this workspace, since a stale/invalid\n * correlation id from a hook must never fail the recall it's attached to.\n */\n // NOTE (design D4): distinct from RecallPort.logRecall (ACT-R activation log)\n // and RecallPort.recordRecall (TD(λ) worth update) — both land in a later PR\n // in this chain (group C, task 1.5). This method stamps session metadata; it\n // never touches the recall log or worth-governance tables.\n recordSessionRecall?(sessionId: string, workspaceId: string): Promise<void>;\n /**\n * Pin or unpin one turn of a session, selected by id OR by ordinal index.\n *\n * Both selectors are first-class because `memory_session action:'pin_turn'`\n * has always advertised both, while nothing translated an index into an id —\n * the MCP tool did `args.turnId ?? String(args.turnIndex)`, so `turnIndex: 1`\n * reached SQL as the id `\"1\"` and blew up a uuid comparison with\n * `invalid input syntax for type uuid`. `mnemo_session_turn.turn_index` has\n * been populated all along; the index selector is one WHERE clause.\n *\n * Exactly one of `turnId` / `turnIndex` must be supplied. Note `turnIndex: 0`\n * is a legitimate selector (the first turn), so implementations must test it\n * with `!== undefined` rather than for truthiness.\n *\n * @returns whether a turn actually matched. Previously this returned void, so\n * a selector matching nothing was indistinguishable from success and the\n * route answered 204 for a turn that does not exist.\n */\n pinSessionTurn(input: {\n sessionId: string;\n workspaceId: string;\n turnId?: string;\n turnIndex?: number;\n pinned: boolean;\n }): Promise<boolean>;\n /**\n * flatten-legacy-dual-core Slice 3c pt.1 (PR10) — overwrite the session's\n * ephemeral scratch pad (`mnemo_session.scratch`, jsonb). Backs\n * `POST /session/:id/scratch` when no `SessionBuffer` is wired. Returns\n * false when the session doesn't exist in this workspace (route maps to 404).\n */\n replaceSessionScratch(input: {\n workspaceId: string;\n sessionId: string;\n scratch: Record<string, unknown>;\n }): Promise<boolean>;\n /**\n * flatten-legacy-dual-core Phase 7 — read-side twin of\n * {@link replaceSessionScratch}. Backs the session-sweep background job's\n * `SessionScratchStore` wiring (`@mnemo-ai/server`'s `index.ts`), which\n * previously read scratch through the legacy `CoreLike.getSessionScratch`.\n * Returns `null` when the session doesn't exist in this workspace.\n */\n getSessionScratch(input: {\n workspaceId: string;\n sessionId: string;\n }): Promise<Record<string, unknown> | null>;\n /**\n * §22 Dedup gate — return distinct topic_keys for facts in a session that were\n * tagged with a specific extraction_source (e.g. \"per_turn\").\n *\n * Used by the hybrid collapse dedup gate to skip collapse outputs whose topic_key\n * already exists in the per-turn extraction set for the same session — preventing\n * the same knowledge from being written twice (once per-turn, once at collapse).\n *\n * OPTIONAL — when absent the dedup gate is skipped (collapse proceeds normally).\n * Callers MUST guard with `?.`.\n *\n * @param workspaceId - scope the query to this workspace\n * @param sessionId - only facts from this session\n * @param source - extraction_source value (typically \"per_turn\")\n * @returns - array of distinct topic_key strings (nulls excluded)\n */\n // D4 override: assigned to SessionPort, NOT WorkspacePort, despite this\n // method's original \"RDD-4\" comment header — it is a session+source scoped\n // dedup gate; the workspace repository was an incidental implementation\n // detail, not the domain this method answers.\n listSessionTopicKeysBySource?(\n workspaceId: string,\n sessionId: string,\n source: string\n ): Promise<string[]>;\n}\n\n/**\n * Fact CRUD, keyset paging, hard-delete, contradiction detection, and §11\n * governance (canonical flag, recalled-fact ids, provenance credit).\n */\nexport interface FactPort {\n createFact(input: CreateFactInput): Promise<MnemoFact>;\n getFact(id: string, workspaceId: string): Promise<MnemoFact | null>;\n updateFact(id: string, workspaceId: string, input: UpdateFactInput): Promise<MnemoFact | null>;\n mergeFactByTopicKey(input: MergeFactByTopicKeyInput): Promise<MnemoFact | null>;\n replaceFact(input: ReplaceFactInput): Promise<ReplaceFactResult | null>;\n /**\n * Close a live fact (`status = 'forgotten'`, `valid_to = now`).\n *\n * PRIM-3 / CHAOS-8: resolves `true` when THIS call closed the fact and\n * `false` when there was nothing to close — missing, already closed (a\n * repeat or the loser of a concurrent archive), or mid-consolidation. A\n * `false` call writes nothing. `void` is what adapters predating the flag\n * return; callers treat it as \"closed\".\n */\n archiveFact(id: string, workspaceId: string): Promise<boolean | void>;\n queryFacts(filter: FactFilter): Promise<PaginatedResult<MnemoFact>>;\n /**\n * CHAOS-7 — the live fact holding exactly this statement under the same\n * dedup key `uniq_mnemo_fact_dedup` enforces (workspace, scope, scopeRef,\n * subject, statement), or null. `remember()` calls it after losing that\n * index's race: the winner committed the row but not yet its content hash,\n * so the hash lookup cannot find it. Optional: adapters without a unique\n * dedup index never raise the race.\n */\n findLiveFactByStatement?(input: FindLiveFactByStatementInput): Promise<MnemoFact | null>;\n\n /**\n * PRIM-15 — the fact a previous POST /import created from export row\n * `importedId` (stored as `metadata.importedId`), open or closed, or null.\n * Searches the whole workspace: the import route used to scan only the first\n * page of `queryFacts`, so every re-import past 20 facts duplicated the row.\n * Optional — the route falls back to that scan when an adapter lacks it.\n */\n findFactByImportedId?(workspaceId: string, importedId: string): Promise<MnemoFact | null>;\n\n /**\n * P109 — bind a session's facts to the episode that session collapsed into,\n * populating `mnemo_fact.episode_id`.\n *\n * That column, and its FK to `mnemo_episode`, have existed since the baseline\n * migration, and `preferSourceEpisode` (core/src/cognitive/recall-cold.ts,\n * spec §17 \"prefer source episode\") reads it on every cold recall to surface\n * the richer episode above the bare fact. Nothing ever wrote it: the episode\n * is created at collapse step 7.5, AFTER the facts, and only ever recorded the\n * link on its own side (`mnemo_episode.linked_fact_ids`). So the enrichment\n * ran, found `episodeId` null on every hit, and returned unchanged — dead\n * machinery that looked wired.\n *\n * Keyed on `session_id` (indexed as `idx_fact_session`) rather than on an id\n * list, because it must cover both populations: the facts collapse extracts\n * AND the facts an agent wrote mid-session via remember(). Both carry the\n * session id; only the former is known to the caller as an id list.\n *\n * Only ever fills a NULL `episode_id` — it never re-points a fact already\n * bound to an episode — so re-running a collapse is idempotent.\n *\n * @returns how many facts were newly linked.\n */\n linkSessionFactsToEpisode(\n workspaceId: string,\n sessionId: string,\n episodeId: string\n ): Promise<number>;\n\n /**\n * flatten-legacy-dual-core PR9b (D6.3) — keyset-paginated fact list\n * backing `GET /facts`. Additive, NOT a replacement for {@link queryFacts}\n * (see the comment on {@link FactPageFilter}). REQUIRED — every adapter\n * implements it; it backs a first-class route, not an optional degrade.\n */\n queryFactsPage(filter: FactPageFilter): Promise<FactPage>;\n\n /**\n * Facts deleted outright (`hard` and `gdpr_erasure` rows of\n * mnemo_deletion_log whose fact is gone), oldest deletion first, keyset\n * paginated in the `{v, id}` cursor format of {@link queryFactsPage} sorted by\n * `updated_at`: `v` is the deletion time. `GET /memory/federation/items`\n * merges them into its fact stream as tombstones. `createdAt` is null on rows\n * written before migration 0068. Optional: without it no hard delete reaches\n * a peer.\n */\n queryDeletedFactsPage?(filter: {\n workspaceId: string;\n cursor?: string;\n deletedSince?: Date;\n limit: number;\n }): Promise<{ id: string; deletedAt: Date; createdAt: Date | null; cursor: string }[]>;\n\n /**\n * The latest creation time among the facts `GET /memory/federation/items`\n * served `peerId` in this workspace (migration 0070), or null if it served it\n * none. Bounds the tombstones that peer gets, whatever `knownCursor` it sends.\n * Optional: without it no tombstone is served.\n */\n federationServeMark?(workspaceId: string, peerId: string): Promise<Date | null>;\n /** Raises that mark to `servedUntil`; never lowers it. */\n raiseFederationServeMark?(workspaceId: string, peerId: string, servedUntil: Date): Promise<void>;\n\n /**\n * flatten-legacy-dual-core PR9b (D6.3) — hard DELETE of every\n * `status = 'forgotten'` fact row in the workspace, mirroring legacy\n * `purgeClosedFacts` (factory.ts). NOT GDPR erasure (no deletion-log entry,\n * no actor DEK crypto-erasure) — see `routes/facts.ts`'s `DELETE\n * /facts/purge` doc comment. Skips rows carrying the\n * `__mnemoConsolidationPending` marker, same guard every other write method\n * in this codebase uses. Distinct from {@link purgeFacts}, which is a SOFT\n * close (`SET status='forgotten'`) by sensitivity tier — the opposite\n * operation. REQUIRED — backs a first-class route.\n *\n * @returns the number of rows physically deleted.\n */\n // NOTE (design D4): this is the HARD delete path, distinct from\n // RetentionPort.purgeFacts? which is a SOFT retention close (sets\n // status='forgotten' by sensitivity tier, does not remove the row).\n //\n // P114: `actorId` is REQUIRED, not optional, and that is the point. This path\n // physically removes many rows at once and used to append nothing to\n // mnemo_deletion_log while the two single-row paths both did. An audit entry\n // needs an actor, so the type refuses to let a caller purge anonymously.\n // Pass a namespaced ActorRef from resolveProvenance() — never a bare id.\n purgeForgottenFacts(workspaceId: string, actorId: string): Promise<number>;\n\n /**\n * P72 — move a fact to another workspace, bitemporally and in one call.\n *\n * There is no `UPDATE ... SET workspace_id`, and there should not be: it would\n * rewrite history and leave a hole in the audit trail. This is the honest\n * remediation the two-step manual dance already implied — close the interval\n * in the wrong workspace, create the successor in the right one, and link\n * them with `supersedes` — done atomically so it cannot half-happen.\n *\n * Atomic across the workspace boundary because `mnemo_set_workspace` uses\n * `set_config(..., true)`, which is transaction-local and re-settable: one\n * transaction can adopt each workspace's RLS context in turn.\n *\n * The `supersedes` relation lives in the DESTINATION workspace. It has to live\n * in exactly one — RLS scopes relation rows too — and the destination is where\n * someone later asks \"where did this come from?\".\n *\n * Returns null when no active fact with that id exists in `fromWorkspaceId`.\n */\n relocateFact?(input: {\n id: string;\n fromWorkspaceId: string;\n toWorkspaceId: string;\n actorId: string;\n reason?: string;\n }): Promise<{ previousId: string; newId: string } | null>;\n\n /**\n * §33 Distributed Consensus — surface active facts that potentially\n * contradict a candidate fact, using the SAME matching as core\n * conflict/fact-candidate.ts: exact same-`subject` OR full-text overlap on\n * the statement, scoped to active facts in the workspace. Returns only the\n * fields the pure resolver (decideAutoResolution) needs, plus identity.\n *\n * This is the port surface that lets the port-only fact-write path\n * (core/v3 remember) run deterministic contradiction resolution without\n * importing drizzle. REQUIRED — every adapter implements it (the InMemory\n * test adapter does a substring/subject match).\n */\n findContradictingFacts(\n workspaceId: string,\n input: FindContradictingFactsInput\n ): Promise<ContradictingFact[]>;\n\n /** §11 governance: set/clear the canonical exemption flag. */\n // D4 override: assigned to FactPort (not wherever the old \"§11 governance\"\n // comment header implied) — no standalone governance table exists; this is\n // fact-scoped, same as getRecalledFactIds and getProvenanceCredit below.\n setCanonical(id: string, workspaceId: string, canonical: boolean): Promise<void>;\n /** §11 governance.propagate: fact IDs recalled in a session (for DAG seeding). */\n getRecalledFactIds(workspaceId: string, sessionId: string): Promise<string[]>;\n /**\n * §11 TD(λ): walk the provenance DAG (derived_from/part_of edges) backward from\n * `terminalIds`, returning each predecessor's decayed credit = lambda^depth.\n * Bounded by maxHops (spec line 1037, default 5). Cyclic-safe.\n */\n getProvenanceCredit(\n workspaceId: string,\n terminalIds: string[],\n lambda: number,\n maxHops: number\n ): Promise<Array<{ factId: string; credit: number }>>;\n}\n\n/**\n * SOC2/GDPR retention: hard delete, deletion-log audit trail, sensitivity-tier\n * soft purge, and actor/user DEK crypto-erasure.\n */\nexport interface RetentionPort {\n /**\n * Wave X — GDPR hard-delete: permanently removes the row from mnemo_fact.\n * MUST be called only after scope check (\"memory:hard_delete\").\n * Optional — guards with `?.` at call sites.\n *\n * Every call also closes the fact's open relations in the same transaction\n * (PRIM-13): an edge to a row that no longer exists was returned by traverse\n * as a dangling node.\n *\n * SEC-4: with `audit`, the same transaction also appends the\n * mnemo_deletion_log row and enqueues vector_delete + cache_bust, so the\n * physical delete can never commit without its trace. Callers that write\n * their own deletion log (cognitive/forget.ts) omit it.\n *\n * Resolves `false` when nothing was deleted (the row is mid-consolidation),\n * otherwise the deleted row's `createdAt` (0068: the deletion log keeps it so\n * federation can serve the deletion as a tombstone); adapters that predate\n * that resolve `true` or `void`.\n */\n hardDeleteFact?(\n id: string,\n workspaceId: string,\n audit?: { actorId: string; reason?: string }\n ): Promise<{ createdAt: Date } | boolean | void>;\n\n /**\n * Wave X — GDPR erasure audit: appends a row to mnemo_deletion_log.\n * Log is INSERT-only for app role (enforced by migration 0001).\n * Optional — guards with `?.` at call sites.\n */\n appendDeletionLog?(input: {\n workspaceId: string;\n deletedItemId: string;\n deletedItemType: string;\n deletionType: \"soft\" | \"hard\" | \"gdpr_erasure\" | \"federation_tombstone\" | \"retention_purge\";\n actorId: string;\n reason?: string;\n /** 0068 — a deleted fact's creation time; federation serves it as a tombstone only with it. */\n itemCreatedAt?: Date;\n }): Promise<void>;\n\n /**\n * SOC2 CF3 — bulk soft-close facts past their retention window for a given\n * sensitivity tier. Runs inside a single db.transaction with the workspace\n * GUC set; paginated at `limit` rows per call (default 500) to bound\n * transaction length. On dryRun=true counts rows without mutating any.\n *\n * Returns `eraseCandidateActorIds`: actors whose remaining active\n * confidential+restricted facts count reaches zero after this purge — safe\n * to call destroyActorDek on. Always empty for the internal tier (no DEK).\n *\n * Optional — callers guard with `?.`.\n */\n purgeFacts?(filter: PurgeFactsFilter): Promise<PurgeFactsResult>;\n\n /**\n * GDPR crypto-erasure — returns the base64-encoded encrypted DEK for an\n * active actor, or null if the DEK has been destroyed or never provisioned.\n * Already implemented in DrizzleStorageAdapter since Wave P/P1.2.\n */\n getActorDek?(workspaceId: string, actorId: string): Promise<string | null>;\n\n /**\n * GDPR crypto-erasure — destroys an actor's DEK (marks it 'destroyed' and\n * nulls the key material). Returns true if a live DEK was found and destroyed.\n * Already implemented in DrizzleStorageAdapter since Wave P/P1.2.\n */\n destroyActorDek?(workspaceId: string, actorId: string): Promise<boolean>;\n\n /**\n * GDPR crypto-erasure, person-scoped — destroys EVERY DEK belonging to a\n * platform user (mnemo_user.id), across every actor_id/API key they've\n * used. Returns the number of DEKs destroyed (0, 1, or more — a person\n * with multiple keys has multiple actor-keyed DEKs). This is what makes\n * erasure actually per-person instead of per-credential; destroyActorDek\n * alone only ever touches one credential's DEK. Optional — guard with `?.`.\n */\n destroyUserDeks?(workspaceId: string, userId: string): Promise<number>;\n}\n\n/** Consolidation merge apply/rollback/finalize lifecycle (memory consolidation pipeline). */\nexport interface ConsolidationPort {\n applyConsolidationMerge(\n input: ApplyConsolidationMergeInput\n ): Promise<ConsolidationMergeSnapshot | null>;\n rollbackConsolidationMerge(input: {\n snapshot: ConsolidationMergeSnapshot;\n review: ReplayFailureReview;\n }): Promise<\"rolled_back\" | \"conflict\">;\n finalizeConsolidationMerge(input: {\n snapshot: ConsolidationMergeSnapshot;\n applyReplayBoost: boolean;\n }): Promise<\"finalized\" | \"conflict\">;\n refreshConsolidationMergeLease(input: {\n snapshot: ConsolidationMergeSnapshot;\n leaseExpiresAt: Date;\n }): Promise<\"refreshed\" | \"conflict\">;\n inspectConsolidationMergeState(\n snapshot: ConsolidationMergeSnapshot\n ): Promise<\"pending\" | \"restored\" | \"retained\" | \"divergent\">;\n recoverExpiredConsolidationMerges(input: {\n workspaceId: string;\n expiredBefore: Date;\n }): Promise<number>;\n}\n\n// ── flatten-legacy-dual-core Slice 3c pt.1 (PR10) — active-learning review\n// queue (Mnemosyne v1.3+, `mnemo_review_queue`). Distinct from the Wave Y\n// §25.1 `enqueueReview`/`enqueueReviewItem` pair (DriftReviewPort below), which\n// target a DIFFERENT physical table (`mnemo_review_item`, codebase-drift review).\n// This one backs `GET/POST /review*` (routes/review.ts): a fact or\n// decision queued for human triage, resolved with an optional atomic\n// cascade to `status='forgotten'` on the linked fact.\nexport interface ActiveLearningReviewPort {\n listActiveLearningReview(filter: ActiveLearningReviewFilter): Promise<ActiveLearningReviewRow[]>;\n /** Cheap COUNT(*) of unresolved rows for the workspace. */\n countUnresolvedActiveLearningReview(workspaceId: string): Promise<number>;\n /**\n * Idempotent insert: exactly one of `factId`/`decisionId` must be supplied.\n * Returns the existing open row's id (inserted:false) when one already\n * targets the same source, so the two producers (extraction pipeline +\n * manual flag) never duplicate a row.\n */\n enqueueActiveLearningReview(\n input: EnqueueActiveLearningReviewInput\n ): Promise<EnqueueActiveLearningReviewResult>;\n /**\n * Atomically resolves the row and, for `resolution: 'forgotten'` on a\n * fact-sourced row, flips the linked fact's status to `'forgotten'` in the\n * SAME transaction. Idempotent: resolving an already-resolved row returns\n * `resolved: false` (the caller maps that to 404/409).\n */\n resolveActiveLearningReview(\n input: ResolveActiveLearningReviewInput\n ): Promise<ResolveActiveLearningReviewResult>;\n}\n\n/**\n * Wave Y §25.1 — codebase/config/infrastructure drift review queue\n * (`mnemo_review_item`). Enqueue a primitive for review, and query facts\n * that are candidates for drift verification.\n */\nexport interface DriftReviewPort {\n /**\n * §11 governance (demote path): enqueue a fact as an archive candidate for\n * human/automated review. OPTIONAL — callers must guard with `?.`.\n * The `mnemo_review_queue` table exists in the baseline migration.\n * Idempotent: no new row while one with the same primitive and reason is\n * still pending, so a sweep that re-flags every run files one review.\n */\n // NOTE (design D4): despite the doc comment above (inherited verbatim from\n // its original location) naming `mnemo_review_queue`, the production\n // DrizzleStorageAdapter delegates this method to `recall.enqueueReviewItem`,\n // which writes `mnemo_review_item` — the SAME table as enqueueReviewItem/\n // queryDriftCandidates below, not the ActiveLearningReviewPort table. The\n // adapter's executable behavior wins over its own doc comment (design D4);\n // this method is grouped here, not in ActiveLearningReviewPort.\n enqueueReview?(input: {\n workspaceId: string;\n primitiveKind: string;\n primitiveId: string;\n reason: string;\n priority?: number;\n }): Promise<void>;\n\n /** Enqueue a primitive for human/auto review (e.g. codebase drift). */\n enqueueReviewItem(input: {\n workspaceId: string;\n primitiveId: string;\n primitiveKind?: string;\n reason: string;\n detail?: Record<string, unknown>;\n }): Promise<void>;\n\n /** Query facts that are codebase/config/infrastructure sourced (for drift verification). */\n queryDriftCandidates(workspaceId: string): Promise<\n Array<{\n id: string;\n statement: string;\n metadata: Record<string, unknown>;\n sensitivity: Sensitivity;\n }>\n >;\n}\n\n/**\n * §9 L3 — lookupQueryCache input. Matched exactly against `mnemo_query_cache`\n * (P59, design.md §3): the table has no HNSW index (dropped by migration\n * `0009`, deliberately not restored by `0010`), so a lookup is a bounded seq\n * scan over a freshness-windowed, `topK`-matched, workspace-shared candidate\n * set — see `FactRepository.lookupQueryCache` for the exact predicate set.\n */\nexport interface LookupQueryCacheInput {\n workspaceId: string;\n embedding: Float32Array;\n /** Minimum cosine similarity for a hit (core passes L3_COSINE = 0.95). */\n threshold: number;\n /** Requested result-set size; matched exactly against the stored entry. */\n topK: number;\n /** Entries older than this are not reusable (core passes L3_MAX_AGE_MS). */\n maxAgeMs: number;\n}\n\n/**\n * §9 L3 — insertQueryCache input (P59, design.md §3). Insert-only: the\n * physical table has no unique key, so there is no upsert semantics.\n */\nexport interface InsertQueryCacheInput {\n workspaceId: string;\n embedding: Float32Array;\n resultIds: string[];\n resultKinds: string[];\n topK: number;\n}\n\n/**\n * §9 L3 caching: semantic query-result cache (cosine>=0.95 shortcut) and\n * embedding LRU (avoid re-embedding identical text).\n */\nexport interface QueryCachePort {\n /**\n * §9 L3 — cosine>=threshold lookup against mnemo_query_cache; null on miss.\n * No ANN index exists on this column — see `LookupQueryCacheInput` above.\n */\n lookupQueryCache?(\n input: LookupQueryCacheInput\n ): Promise<{ resultIds: string[]; resultKinds: string[] } | null>;\n\n /**\n * §9 L3 — append one recall result set. Insert-only: the table has no\n * unique key to upsert against (P59, design.md D11).\n */\n insertQueryCache?(input: InsertQueryCacheInput): Promise<void>;\n\n /**\n * P68 — prune L3 rows older than `olderThanMs`, for one workspace.\n *\n * P59 chose Option A (insert-only, no eviction) deliberately: every eligible\n * recall appends a row and nothing removes it except replaceFact's whole-\n * workspace bust. Read cost stays bounded by the freshness window and the\n * 200-row cap on `idx_mnemo_qc_ws`, so the debt was storage, not latency —\n * and unbounded.\n *\n * Prunes on `created_at`, not `last_used_at`. Under today's insert-only\n * writes the two are identical, but P59 design.md D6 warns that a future\n * touch-on-hit would let a repeatedly-requested entry keep refreshing itself\n * and never expire. Anchoring the pruner to creation time means that change\n * cannot silently defeat eviction.\n *\n * Workspace-scoped rather than a global sweep so it runs inside the ordinary\n * RLS transaction, like every other maintenance pass (`perWorkspace` in the\n * cron registry).\n *\n * @returns how many rows were removed.\n */\n pruneQueryCache?(workspaceId: string, olderThanMs: number): Promise<number>;\n\n /**\n * §9 L3 embedding LRU — exact `(text-hash, model)` lookup; null on miss.\n *\n * `model` is part of the identity of a cache entry, not metadata about it.\n * The row is keyed `(workspace_id, text_hash)` — the same text hashes\n * identically no matter which model embedded it — so a lookup that ignores\n * `model` can hand back a vector from a different embedding space. Those\n * coordinates mean nothing in the current one, and because widths differ\n * across models (1024 Bedrock/bge-m3, 1536 OpenAI) the downstream cosine\n * query does not merely score badly, it raises `different halfvec\n * dimensions` and the recall fails. Same hazard `_embedding-width.ts`\n * documents for the search path.\n *\n * Optional for backward compatibility with adapters written before the\n * parameter existed; omitting it restores the old model-blind behaviour and\n * should be treated as a bug in the caller, not a supported mode.\n */\n getCachedEmbedding?(\n workspaceId: string,\n textHash: string,\n model?: string\n ): Promise<Float32Array | null>;\n\n /**\n * §9 L3 embedding LRU — insert or refresh an embedding record.\n *\n * A write for a `(workspace, text)` that is already cached under a DIFFERENT\n * model replaces the stored vector and model. It cannot be a no-op that only\n * bumps `hit_count`: the caller only reaches this path after a cache miss,\n * which under a model-aware read means the entry belongs to a model nobody\n * is using any more. Keeping the old vector would strand the entry forever —\n * permanently missed on read, never overwritten on write.\n */\n putCachedEmbedding?(input: {\n workspaceId: string;\n textHash: string;\n embedding: Float32Array;\n model: string;\n }): Promise<void>;\n}\n\n/** Decision CRUD and topic-key merge. */\nexport interface DecisionPort {\n /**\n * PRIM-18 — insert, unless an active, open decision with the same identity\n * (kind, title, body, owner, scopeRef, sensitivity — as the insert would\n * store them) exists; then return that one with `reused: true`. Lookup and\n * insert are atomic: identical concurrent calls yield one row. Optional: an\n * adapter without it keeps inserting.\n */\n createDecisionUnlessDuplicate?(\n input: CreateDecisionInput\n ): Promise<{ decision: MnemoDecision; reused: boolean }>;\n createDecision(input: CreateDecisionInput): Promise<MnemoDecision>;\n mergeDecisionByTopicKey(input: MergeDecisionByTopicKeyInput): Promise<MnemoDecision | null>;\n getDecision(id: string, workspaceId: string): Promise<MnemoDecision | null>;\n updateDecision(id: string, input: UpdateDecisionInput): Promise<MnemoDecision>;\n archiveDecision(id: string, workspaceId: string): Promise<void>;\n /** WP-6 / PRIM-18 — see {@link SupersedeDecisionInput}. */\n supersedeDecision(input: SupersedeDecisionInput): Promise<MnemoDecision>;\n queryDecisions(filter: DecisionFilter): Promise<PaginatedResult<MnemoDecision>>;\n}\n\n// ─── end segregate-storage-ports PR1 additions (Phase 1 group A, rows 1-8) ────\n\n// ─── segregate-storage-ports — narrow domain sub-ports (PR2, Phase 1 group B) ──\n//\n// PR2 of the same stacked chain additively extracts Port Map rows 9-16 as named\n// interfaces below. Every member's name, signature, optionality, and doc comment\n// is copied VERBATIM from its original home in the flat `StorageAdapter`\n// interface further down this file — nothing here is a behavior change. The\n// flat `StorageAdapter` interface remains completely untouched in this PR (zero\n// deletions); groups C-E (the remaining 22 domain ports) and the final\n// `StorageAdapter` intersection alias land in later PRs in this chain (tasks\n// 1.5-1.11). See design.md D3/D4 for placement rationale and the per-method\n// override table.\n\n/** Episodic memory: session/event narratives, tree reconstruction, similarity search, and compression. */\nexport interface EpisodePort {\n createEpisode(input: CreateEpisodeInput): Promise<MnemoEpisode>;\n getEpisode(id: string, workspaceId: string): Promise<MnemoEpisode | null>;\n updateEpisode(id: string, input: UpdateEpisodeInput): Promise<MnemoEpisode>;\n archiveEpisode(id: string, workspaceId: string): Promise<void>;\n queryEpisodes(filter: EpisodeFilter): Promise<PaginatedResult<MnemoEpisode>>;\n /**\n * Reconstruct an episode's full narrative by walking parentEpisodeId to the\n * root and folding deltaContent in depth order (root→leaf). Spec §16.\n */\n reconstructEpisode(id: string, workspaceId: string): Promise<MnemoEpisode>;\n /**\n * Spec §16 episode trees: return the matched episode's parent, siblings (same\n * parentEpisodeId) and direct children — the RELATED neighbourhood for recall\n * expansion. Workspace-scoped; excludes the episode itself. Capped at `limit`\n * (default 10). Optional for backward compatibility with adapters that don't\n * implement tree traversal.\n */\n getEpisodeTreeNeighbors?(\n episodeId: string,\n workspaceId: string,\n limit?: number\n ): Promise<MnemoEpisode[]>;\n /**\n * DELTAMEM §16 — HNSW cosine search over mnemo_episode.embedding, scoped to\n * `workspaceId`. Returns up to `limit` episodes whose embedding cosine\n * similarity to `embedding` is ≥ `minSim`, most-similar first. Rows with a\n * NULL embedding (not yet indexed) are excluded. Used at episode-creation time\n * to find the nearest existing episode to delta-encode against (parent link).\n *\n * `embedding` is a query vector of the embedder's dimension (1536). `minSim`\n * is a cosine similarity in [0,1]. Implementations without a vector index\n * (InMemory) may return an empty list.\n */\n findSimilarEpisodes(\n workspaceId: string,\n embedding: number[],\n limit: number,\n minSim: number\n ): Promise<SimilarEpisode[]>;\n /**\n * Persist an Experience-Compression result (spec §2): replace the root\n * episode's narrative with the compressed summary and stash retained leaf\n * deltas + provenance in metadata. Idempotent on re-run.\n */\n persistCompression(input: {\n workspaceId: string;\n rootEpisodeId: string;\n compressedNarrative: string;\n retainedDeltas: Array<{ episodeId: string; deltaContent: string }>;\n }): Promise<void>;\n}\n\n/**\n * Entity CRUD and similarity search (person/org/project/concept/place/other).\n *\n * D4 override: `findSimilarEntities` sits under the old \"Episodes\" comment\n * header in the flat interface below, but the `DrizzleStorageAdapter`\n * delegates it to `this.entities` — the adapter wins (explore.md's originally\n * flagged example of an imprecise comment-section boundary).\n */\nexport interface EntityPort {\n createEntity(input: CreateEntityInput): Promise<MnemoEntity>;\n getEntity(id: string, workspaceId: string): Promise<MnemoEntity | null>;\n updateEntity(id: string, input: UpdateEntityInput): Promise<MnemoEntity>;\n archiveEntity(id: string, workspaceId: string): Promise<void>;\n /** WP-6 / PRIM-2 — see {@link SupersedeEntityInput}. */\n supersedeEntity(input: SupersedeEntityInput): Promise<MnemoEntity>;\n queryEntities(filter: EntityFilter): Promise<PaginatedResult<MnemoEntity>>;\n /**\n * P16 — HNSW cosine search over mnemo_entity.embedding, scoped to\n * `workspaceId`. Returns up to `limit` entities whose embedding cosine\n * similarity to `embedding` is ≥ `minSim`, most-similar first. Rows with a\n * NULL embedding (not yet indexed) are excluded. Implementations without a\n * vector index (InMemory) may return an empty list.\n */\n findSimilarEntities(\n workspaceId: string,\n embedding: number[],\n limit: number,\n minSim: number\n ): Promise<SimilarEntity[]>;\n}\n\n/** Strategy CRUD (trigger→action heuristics). */\nexport interface StrategyPort {\n /**\n * PRIM-18 — see DecisionPort.createDecisionUnlessDuplicate (identity:\n * trigger, action, owner, scopeRef, sensitivity). Not for `supersedesId`.\n */\n createStrategyUnlessDuplicate?(\n input: CreateStrategyInput\n ): Promise<{ strategy: MnemoStrategy; reused: boolean }>;\n createStrategy(input: CreateStrategyInput): Promise<MnemoStrategy>;\n getStrategy(id: string, workspaceId: string): Promise<MnemoStrategy | null>;\n updateStrategy(id: string, input: UpdateStrategyInput): Promise<MnemoStrategy>;\n archiveStrategy(id: string, workspaceId: string): Promise<void>;\n queryStrategies(filter: StrategyFilter): Promise<PaginatedResult<MnemoStrategy>>;\n}\n\n/** Workflow CRUD (reusable multi-step process templates). */\nexport interface WorkflowPort {\n createWorkflow(input: CreateWorkflowInput): Promise<MnemoWorkflow>;\n getWorkflow(id: string, workspaceId: string): Promise<MnemoWorkflow | null>;\n updateWorkflow(id: string, input: UpdateWorkflowInput): Promise<MnemoWorkflow>;\n archiveWorkflow(id: string, workspaceId: string): Promise<void>;\n queryWorkflows(filter: WorkflowFilter): Promise<PaginatedResult<MnemoWorkflow>>;\n}\n\n/** Skill CRUD (prompt templates for repeatable tasks). */\nexport interface SkillPort {\n createSkill(input: CreateSkillInput): Promise<MnemoSkill>;\n getSkill(id: string, workspaceId: string): Promise<MnemoSkill | null>;\n updateSkill(id: string, input: UpdateSkillInput): Promise<MnemoSkill>;\n archiveSkill(id: string, workspaceId: string): Promise<void>;\n querySkills(filter: SkillFilter): Promise<PaginatedResult<MnemoSkill>>;\n}\n\n/**\n * Task CRUD, delegation, and lifecycle.\n *\n * D4 override: `listTasksForSession?` sits under the old \"§11 governance\"\n * comment header in the flat interface below, but it is a task read used by\n * the collapse pipeline's task-completion outcome signal (RDD-1) — the\n * adapter delegates it to `this.tasks`, so it belongs on `TaskPort`, not\n * wherever the old header implied.\n */\nexport interface TaskPort {\n createTask(input: CreateTaskInput): Promise<MnemoTask>;\n getTask(id: string, workspaceId: string): Promise<MnemoTask | null>;\n updateTask(id: string, input: UpdateTaskInput): Promise<MnemoTask>;\n archiveTask(id: string, workspaceId: string): Promise<void>;\n delegateTask(id: string, workspaceId: string, input: DelegateTaskInput): Promise<MnemoTask>;\n queryTasks(filter: TaskFilter): Promise<PaginatedResult<MnemoTask>>;\n /**\n * Return task id+status pairs linked to a session.\n * Used by the collapse pipeline to compute the task-completion outcome signal (RDD-1).\n * OPTIONAL — callers MUST guard with `?.`.\n */\n listTasksForSession?(\n workspaceId: string,\n sessionId: string\n ): Promise<Array<{ id: string; status: string }>>;\n}\n\n/** Immutable event log CRUD + sensitivity updates (no `updatedAt` by design). */\nexport interface EventPort {\n createEvent(input: CreateEventInput): Promise<MnemoEvent>;\n getEvent(id: string, workspaceId: string): Promise<MnemoEvent | null>;\n archiveEvent(id: string, workspaceId: string): Promise<void>;\n appendEventAnnotation(\n id: string,\n workspaceId: string,\n annotation: EventAnnotation\n ): Promise<MnemoEvent>;\n queryEvents(filter: EventFilter): Promise<PaginatedResult<MnemoEvent>>;\n /** P15: Raise the sensitivity of an event. Raise-only — calling code MUST verify\n * sensitivityAtLeast(newSensitivity, existing.sensitivity) before calling this. */\n updateEventSensitivity(id: string, workspaceId: string, sensitivity: Sensitivity): Promise<void>;\n}\n\n/** Reasoning-chain CRUD, CoT cache search, usage tracking, and lifecycle status. */\nexport interface ReasoningPort {\n createReasoning(input: CreateReasoningInput): Promise<MnemoReasoning>;\n getReasoning(id: string, workspaceId: string): Promise<MnemoReasoning | null>;\n updateReasoning(id: string, input: UpdateReasoningInput): Promise<MnemoReasoning>;\n archiveReasoning(id: string, workspaceId: string): Promise<void>;\n queryReasoning(filter: ReasoningFilter): Promise<PaginatedResult<MnemoReasoning>>;\n\n /** Wave M1 — CoT cache search. Returns candidates ranked by cosine similarity.\n * By default only servable rows (active + golden) are returned. */\n searchReasoning(input: {\n workspaceId: string;\n vector: number[];\n limit: number;\n includeAllStatuses?: boolean;\n }): Promise<\n Array<{\n id: string;\n cosine: number;\n worth: number;\n successCount: number;\n failureCount: number;\n status: MnemoReasoning[\"status\"];\n }>\n >;\n\n /** Wave M1 — bump usage_count and last_used_at for a reasoning cache hit. */\n recordReasoningUse(id: string, workspaceId: string): Promise<void>;\n\n /** Wave M1 — transition lifecycle status (quarantined / golden / active). */\n setReasoningStatus(\n id: string,\n workspaceId: string,\n status: MnemoReasoning[\"status\"]\n ): Promise<void>;\n}\n\n// ─── end segregate-storage-ports PR2 additions (Phase 1 group B, rows 9-16) ───\n\n// ─── segregate-storage-ports — narrow domain sub-ports (PR3, Phase 1 group C) ──\n//\n// PR3 of the same stacked chain additively extracts Port Map rows 17-24 as named\n// interfaces below. Every member's name, signature, optionality, and doc comment\n// is copied VERBATIM from its original home in the flat `StorageAdapter`\n// interface further down this file — nothing here is a behavior change. The\n// flat `StorageAdapter` interface remains completely untouched in this PR (zero\n// deletions); groups D-E (the remaining 14 domain ports) and the final\n// `StorageAdapter` intersection alias land in later PRs in this chain (tasks\n// 1.6-1.11). See design.md D3/D4 for placement rationale and the per-method\n// override table.\n\n/**\n * Agent self-model: profile CRUD, §14 procedural-memory trajectory scores, and\n * prompt-version lifecycle (Wave M2/Wave U).\n *\n * D4 override: `listScoredTrajectories?` sits under the old \"§14 Procedural\n * memory\" comment header in the flat interface below, but the\n * `DrizzleStorageAdapter` delegates it to `this.plugins` — grouped here with\n * the prompt-version methods per design D4's Port Map table (§14 agent\n * self-model), not split into its own port.\n */\nexport interface AgentPort {\n getAgentProfile(workspaceId: string, agentId: string): Promise<MnemoAgentProfile | null>;\n upsertAgentProfile(input: {\n workspaceId: string;\n agentId: string;\n summary?: string;\n metadata?: Record<string, unknown>;\n }): Promise<MnemoAgentProfile>;\n /**\n * Increment the sessionsSinceReflection counter in the agent profile's metadata.\n * Creates a profile row if one does not exist yet.\n * Returns the new counter value.\n */\n incrementSessionsSinceReflection(workspaceId: string, agentId: string): Promise<number>;\n\n /**\n * List the N most-recent scored trajectories for an agent.\n * Each trajectory is a session-level probe with a worth score (0–1).\n * OPTIONAL — callers guard with `?.`.\n */\n listScoredTrajectories?(\n workspaceId: string,\n agentId: string,\n limit: number\n ): Promise<\n Array<{ sessionId: string; score: number; promptVersionId: string | null; createdAt: Date }>\n >;\n\n /**\n * Insert a new prompt version row in status 'candidate'.\n * Returns the generated row id.\n * OPTIONAL — callers guard with `?.`.\n */\n createPromptVersion?(input: {\n workspaceId: string;\n agentId: string;\n promptText: string;\n diffFromPrevious: string;\n algorithm: string;\n trajectoriesUsed: number;\n avgScoreBefore: number | null;\n avgScoreAfter: number | null;\n status: \"candidate\";\n }): Promise<{ id: string }>;\n\n /**\n * Return the most-recently created candidate (or active) prompt version\n * for the given (workspace, agent) pair, or null if none exists.\n * OPTIONAL — callers guard with `?.`.\n */\n getActivePromptVersion?(\n workspaceId: string,\n agentId: string\n ): Promise<{\n id: string;\n status: \"candidate\" | \"testing\" | \"active\" | \"rolled_back\";\n trajectoriesUsed: number | null;\n avgScoreBefore: number | null;\n avgScoreAfter: number | null;\n } | null>;\n\n /**\n * Return the most-recently activated prompt version across ALL agents in a\n * workspace, or null if no activated versions exist. Used by the cognitive\n * health snapshot to compute proceduralEvolutionDelta without needing a\n * specific agentId.\n * OPTIONAL — callers guard with `?.`.\n */\n getLatestActivatedPromptVersion?(workspaceId: string): Promise<{\n avgScoreBefore: number | null;\n avgScoreAfter: number | null;\n } | null>;\n\n /**\n * List all prompt versions for (workspace, agent), newest first.\n * OPTIONAL — callers guard with `?.`.\n */\n listPromptVersions?(\n workspaceId: string,\n agentId: string\n ): Promise<\n Array<{\n id: string;\n promptText: string | null;\n diffFromPrevious: string | null;\n algorithm: string;\n status: string;\n trajectoriesUsed: number | null;\n avgScoreBefore: number | null;\n avgScoreAfter: number | null;\n activatedAt: Date | null;\n createdAt: Date;\n }>\n >;\n\n /**\n * Update the status of a prompt version to 'testing', 'active', or 'rolled_back'\n * and record the final avgScoreAfter.\n * OPTIONAL — callers guard with `?.`.\n */\n transitionPromptVersion?(\n workspaceId: string,\n promptVersionId: string,\n newStatus: \"testing\" | \"active\" | \"rolled_back\",\n avgScoreAfter: number\n ): Promise<void>;\n\n /**\n * §14 A/B scoring — returns the mean outcome score for all trajectories\n * associated with a specific prompt version within a workspace.\n * Returns null when there are no scored trajectories for the version.\n * OPTIONAL — callers guard with `?.`.\n */\n computeCandidateAbScore?(\n workspaceId: string,\n agentId: string,\n promptVersionId: string\n ): Promise<number | null>;\n}\n\n/** N-ary relations (hyperedges): CRUD, querying, and activation bumps. */\nexport interface HyperedgePort {\n createHyperedge(input: CreateHyperedgeInput): Promise<MnemoHyperedge>;\n /**\n * Closed (deleted) hyperedges read as `null` unless `opts.includeClosed`; so\n * does one with a member above `opts.maxSensitivity`.\n */\n getHyperedge(\n id: string,\n workspaceId: string,\n opts?: { includeClosed?: boolean; maxSensitivity?: Sensitivity }\n ): Promise<MnemoHyperedge | null>;\n updateHyperedge(id: string, input: UpdateHyperedgeInput): Promise<MnemoHyperedge>;\n archiveHyperedge(id: string, workspaceId: string): Promise<void>;\n queryHyperedges(filter: HyperedgeFilter): Promise<PaginatedResult<MnemoHyperedge>>;\n bumpHyperedgeActivation(id: string, workspaceId: string): Promise<void>;\n}\n\n/** Composition/inference rule engine: rule CRUD, built-in rule seeding, and the append-only inference log. */\nexport interface CompositionPort {\n createCompositionRule(input: CreateCompositionRuleInput): Promise<MnemoCompositionRule>;\n getCompositionRule(id: string, workspaceId: string): Promise<MnemoCompositionRule | null>;\n updateCompositionRule(\n id: string,\n workspaceId: string,\n input: UpdateCompositionRuleInput\n ): Promise<MnemoCompositionRule>;\n queryCompositionRules(\n filter: CompositionRuleFilter\n ): Promise<PaginatedResult<MnemoCompositionRule>>;\n bumpCompositionExecution(id: string, workspaceId: string): Promise<void>;\n /**\n * Idempotently seed the 7 built-in composition rule templates for a workspace.\n * Calls `mnemo_seed_builtin_rules(workspace_id)` which runs ON CONFLICT DO NOTHING\n * so repeated calls are safe. Called lazily on first write per workspace so every\n * fresh workspace gets the inference engine populated automatically.\n */\n ensureBuiltinCompositionRules(workspaceId: string): Promise<void>;\n\n // Inference log (Wave E — append-only)\n appendInference(input: AppendInferenceInput): Promise<MnemoInferenceLogEntry>;\n queryInferences(filter: InferenceLogFilter): Promise<PaginatedResult<MnemoInferenceLogEntry>>;\n\n // Materialise inference (Wave H — atomic: createFact + appendInference + bumpCompositionExecution)\n // Atomically: createFact + appendInference + bumpCompositionExecution + fact_hash upsert\n // in ONE transaction. Prevents orphaned facts (FINDING #4).\n materialiseInference(input: MaterialiseInferenceInput): Promise<{ id: string }>;\n}\n\n/** Binary relation CRUD, strength updates, atomic conflict resolution, and relation judgments. */\nexport interface RelationPort {\n createRelation(input: CreateRelationInput): Promise<MnemoRelation>;\n getRelations(filter: RelationFilter): Promise<MnemoRelation[]>;\n updateRelationStrength(id: string, delta: number): Promise<void>;\n /**\n * Physical `DELETE FROM mnemo_relation`. No bitemporal close, no audit entry,\n * no deletion-log row — the relation and its judgment provenance\n * (`markedByKind`, `reason`, `evidence`, `confidence`) are simply gone.\n *\n * Deliberately NOT the method behind `DELETE /relations/:id`. See\n * {@link closeRelation}: the exposed surface closes the interval, matching\n * `forget()`'s \"closes validity — does NOT delete rows\" contract that every\n * other primitive follows. Exposing this one would put an unauditable,\n * irreversible operation on the API for the only primitive that carries an\n * explicit human judgment.\n */\n deleteRelation(id: string, workspaceId: string): Promise<void>;\n\n /**\n * P111 — bitemporal close for a relation: sets `valid_to = now()` and leaves\n * the row, so the judgment trail survives and `validAt` queries still see it\n * as it was.\n *\n * `mnemo_relation` has carried `valid_to` since the baseline and\n * `getRelations` already filters on it (`validTo IS NULL OR validTo > validAt`);\n * nothing could ever set it, so a relation created by mistake — or by the\n * dangling-write path P74 describes — could not be retracted through any\n * surface at all.\n *\n * @returns true when a row was closed, false when the id matched nothing,\n * the interval was already closed, or an endpoint is above\n * `opts.maxSensitivity`, so the caller can 404 rather than report\n * success for a no-op.\n */\n closeRelation(\n id: string,\n workspaceId: string,\n opts?: { maxSensitivity?: Sensitivity }\n ): Promise<boolean>;\n /** Atomic conflict resolution (B5) — see `ResolveConflictInput`'s doc comment. */\n resolveConflict(input: ResolveConflictInput): Promise<ResolveConflictResult>;\n /** flatten-legacy-dual-core D6.4 — see `ApplyRelationJudgmentInput`'s doc comment. */\n applyRelationJudgment(input: ApplyRelationJudgmentInput): Promise<MnemoRelation | null>;\n}\n\n/** Citations attached to memory primitives (flatten-legacy-dual-core PR9e, design.md D6.5). */\nexport interface CitationPort {\n /** List citations attached to a memory primitive, newest first. */\n listCitations(filter: CitationFilter): Promise<MnemoCitation[]>;\n}\n\n/**\n * Graph snapshot assembly and semantic-neighbor backfill — adapter-side only;\n * traversal/pathfinding live in `@mnemo-ai/core` looping `RelationPort.getRelations`\n * (design.md D6.5 \"Graph — assembly-in-adapter, traversal-in-core\").\n */\nexport interface GraphPort {\n /**\n * flatten-legacy-dual-core PR9f (design.md D6.5 \"Graph — assembly-in-adapter,\n * traversal-in-core\"). Adapter-side snapshot assembly — mirrors legacy\n * `buildGraphQuery` (`core/src/graph/query.ts`). Traversal/pathfinding\n * (`traverseGraph`/`findGraphPath`) are pure `@mnemo-ai/core` functions\n * looping this interface's `getRelations`, not adapter methods.\n */\n getGraphSnapshot(filter: GraphSnapshotFilter): Promise<GraphSnapshot>;\n\n /**\n * Each entity's mentions, counted the way `getGraphSnapshot` derives an entity\n * node's `mentionCount`: its active facts plus the non-synthetic episodes\n * related to it by an open, non-dismissed entity↔episode relation, each only when at or below\n * `maxSensitivity`. One entry per requested id (0 when there are none). The\n * stored `mention_count` column is never maintained, so it is not used.\n */\n countEntityMentions(input: {\n workspaceId: string;\n entityIds: string[];\n maxSensitivity?: Sensitivity;\n }): Promise<Record<string, number>>;\n\n /**\n * The ids, among `ids`, that resolve to a row of this workspace above\n * `maxSensitivity`, in any primitive table (an id field such as a fact's\n * `linkedMemoryIds` may name any kind). An id that resolves to no row is not\n * hidden. Routes use it to drop pointers to rows the caller cannot read, so a\n * response never names an id its ceiling hides.\n */\n findHiddenIds(input: {\n workspaceId: string;\n ids: string[];\n maxSensitivity: Sensitivity;\n }): Promise<string[]>;\n\n /**\n * How many unresolved conflicts GET /conflicts can list: open\n * `conflicts_with` relations whose two facts exist in this workspace, are\n * current (`validTo` unset) and, with `maxSensitivity`, are both at or below\n * it. One COUNT, so a caller never reads every pair to learn the total.\n */\n countOpenConflicts(input: { workspaceId: string; maxSensitivity?: Sensitivity }): Promise<number>;\n\n /**\n * flatten-legacy-dual-core PR9g (design.md D6.5 \"Graph — assembly-in-adapter,\n * traversal-in-core\"). Adapter-side set-based kNN backfill over the HNSW\n * index on `mnemo_fact.embedding` — a set-based `INSERT ... JOIN LATERAL`,\n * not portable to core (design.md's D6.5 table: \"Snapshot assembly + kNN\n * backfill in core\" was rejected for exactly this reason). Recomputes the\n * workspace's semantic-neighbor edges from scratch (delete + fresh\n * top-k insert) — idempotent, safe to call repeatedly. Returns the number\n * of edges written.\n *\n * `public.mnemo_semantic_neighbor`'s schema-location verdict (design.md\n * D6.5/D6.6): the table is created by the legacy core migration stream\n * (`core/migrations/0073_mnemo_semantic_neighbor.sql`, unqualified —\n * lands in `public`, not `mnemosyne`), not by any adapter-postgres\n * baseline migration. Adapter-postgres's baseline (0001) only\n * conditionally GRANTs DML on it `IF EXISTS`, matching the same\n * defensive pattern already used for `mnemo_extraction_job` (0016). This\n * method queries the table at its current, unmoved physical location\n * (`public.mnemo_semantic_neighbor`) — same assumption PR9f's read-only\n * `loadSemanticEdges` already made for `getGraphSnapshot`'s\n * `includeSemantic` overlay. Production always runs core's migrations\n * before adapter-postgres's (`docker/Dockerfile.migrate`), proven by\n * `fresh-install-migrate.integration.test.ts`'s \"full prod migrate order\"\n * block, so the table is guaranteed present by the time this method can\n * be called. Moving the table under v3's own ownership is out of this\n * PR's scope — deferred to Phase 7 (Slice 4, legacy retirement), when\n * core's migration stream stops running at all.\n */\n backfillSemanticNeighbors(input: {\n workspaceId: string;\n k?: number;\n threshold?: number;\n modelVersion?: string;\n }): Promise<number>;\n}\n\n/**\n * Bounded recall hydration for the cold-recall pipeline, the ACT-R activation\n * log, TD(λ) worth governance, and the FTS candidate arm of Tier-3 recall.\n *\n * Assembled from three originally separate sections of the flat interface\n * (\"Bounded recall hydration\", \"Recall log (ACT-R activation — TASK-4001)\",\n * \"Worth governance (TD(λ))\") — declared here in design.md's Port Map row 23\n * order, not the flat interface's physical line order. See design D3.\n */\nexport interface RecallPort {\n /** Records one recall request and its final hits; optional for adapters. */\n recordRecallObservation?(\n request: RecallRequestObservation,\n hits: RecallHitObservation[]\n ): Promise<void>;\n // Bounded recall hydration. Implementations use one RLS transaction per batch,\n // never one transaction per overfetched candidate.\n getRecallPrimitives(\n workspaceId: string,\n refs: RecallPrimitiveRef[]\n ): Promise<RecallPrimitiveRecord[]>;\n getRecallLogs(\n workspaceId: string,\n memoryIds: string[],\n limitPerMemory: number\n ): Promise<RecallLogRecord[]>;\n /**\n * With `maxSensitivity`, a relation whose endpoint, or a hyperedge whose\n * member, sits above the ceiling is left out (the same rule as GET /relations\n * and GET /hyperedges), so a hit's relation count names nothing hidden.\n */\n getRecallStructures(\n workspaceId: string,\n sourceIds: string[],\n hyperedgeLimitPerMember: number,\n maxSensitivity?: Sensitivity\n ): Promise<RecallStructures>;\n /**\n * WP-3 (AGENTSIM-4): the ids, among `ids`, that sit on either end of an\n * unresolved `conflicts_with` relation (`valid_to IS NULL`, the same\n * definition GET /conflicts lists). Recall marks those hits `contested`.\n * Optional: without it every hit reports no dispute. With `maxSensitivity`, a\n * conflict whose other end sits above the ceiling does not count (GET\n * /conflicts hides it too), so `contested` reveals nothing hidden.\n */\n getUnresolvedConflictIds?(\n workspaceId: string,\n ids: string[],\n maxSensitivity?: Sensitivity\n ): Promise<string[]>;\n\n /** FTS arm of hybrid Tier-3 recall: full-text match over text_lemmatized (migration 0047),\n * workspace-scoped, returns up to `limit` PointerCandidate rows. Adapters without FTS return []. */\n ftsCandidates?(query: Omit<PointerCandidateQuery, \"bands\">): Promise<FtsCandidate[]>;\n\n /**\n * make-primitives-recallable (design.md D4/Interfaces, PR3 — Phase 5) —\n * non-fact recall candidates (currently `mnemo_decision` only, following\n * `RECALLABLE_KINDS`), workspace-scoped, driven by `query.kinds` (not a\n * post-filter). Runs the semantic (cosine, `minSimilarity`) arm when\n * `embedding` is supplied, the lexical (`ts_rank`,\n * `plainto_tsquery(mnemosyne.mnemo_fts)`) arm when `terms` is supplied, both when\n * both are supplied, neither (→ `[]`, no query issued) otherwise. Returns\n * up to `limit` candidates, highest score first. Optional — as of this PR\n * it is implemented but not yet called from `recall-cold.ts` (PR4 wires\n * it in); adapters that never implement it behave exactly like adapters\n * without `ftsCandidates?` today.\n */\n recallableCandidates?(query: PrimitiveCandidateQuery): Promise<PrimitiveCandidate[]>;\n /**\n * Items a federation sync brought into the workspace (`mnemo_federated_item`)\n * whose statement matches `terms` lexically: they carry no embedding. Only\n * live (not archived) rows of `workspaceId` at the tiers in `sensitivity`,\n * best match first. Adapters without federation storage omit it.\n */\n federatedRecallCandidates?(query: FederatedRecallQuery): Promise<FederatedRecallCandidate[]>;\n /** Fetch the most recent recall timestamps for a memory, newest first. */\n getRecallLog(\n workspaceId: string,\n memoryId: string,\n limit: number\n ): Promise<Array<{ id: string; recalledAt: string; recallScore: number }>>;\n /**\n * Return up to `limit` distinct query texts from mnemo_recall_log whose\n * fact_id matches any of `factIds`, ordered by recalled_at DESC.\n * Used by the §12 consolidation replay gate to prefer real historical\n * queries over LLM-generated synthetic ones. Returns [] when the log\n * is empty or no rows match.\n */\n getRecentQueriesForFacts(\n workspaceId: string,\n factIds: string[],\n limit: number\n ): Promise<string[]>;\n\n updateWorth(\n id: string,\n workspaceId: string,\n primitiveKind: PrimitiveKind,\n delta: WorthDelta\n ): Promise<void>;\n // NOTE (design D4): this is the TD(λ) worth update, distinct from\n // SessionPort.recordSessionRecall? (session metadata stamp, group A) and\n // from logRecall above (ACT-R activation log).\n recordRecall(entry: RecallLogEntry): Promise<void>;\n /**\n * Fetch predecessor recalls in the same session for TD(λ) backward propagation.\n * Returns facts recalled before `excludeFactId` in this session, most-recent first,\n * up to 20 entries. Each entry includes the stored tdCredit (λ^rank).\n */\n getTdPredecessors(\n workspaceId: string,\n sessionId: string,\n excludeFactId: string\n ): Promise<Array<{ factId: string; tdCredit: number; recalledAt: Date }>>;\n\n /**\n * recall-precision-report (harden-hooks-and-measure-precision, Requirement 5/6):\n * precision-at-k over data already persisted by `recordRecall` and collapse's\n * TD(λ) propagation (`propagateTdCredit`). Read-only — no write path, no\n * schema migration. See `RecallPrecisionReport` and design.md for the exact\n * derivation.\n */\n getRecallPrecision(workspaceId: string): Promise<RecallPrecisionReport>;\n\n /**\n * p50/p95 recall latency over `mnemo_recall_log` rows of the last `days` days\n * (one row per served memory; rows without `latency_ms` are excluded). Rounded\n * to integer ms; both null when there are no samples.\n */\n /**\n * APP-015 — the context economy of a workspace over `days`: how many recalls\n * recorded a served size, their average and p95 served characters, and the\n * size of every live plaintext fact (what injecting all of memory on every\n * turn would cost). Facts are sized only at or under `maxSensitivity`\n * (the caller's ceiling) and never above internal (encrypted tiers store\n * ciphertext). Optional: adapters without it report nothing.\n */\n getContextEconomy?(\n workspaceId: string,\n days: number,\n maxSensitivity: Sensitivity\n ): Promise<{\n recalls: number;\n servedCharsAvg: number | null;\n servedCharsP95: number | null;\n liveFacts: number;\n liveFactChars: number;\n }>;\n getRecallLatency(\n workspaceId: string,\n days: number\n ): Promise<{ p50Ms: number | null; p95Ms: number | null; samples: number }>;\n\n /**\n * Facts created per UTC day: exactly `days` entries ending today, zero-filled,\n * oldest first, `day` as YYYY-MM-DD. Lives here with the stats reads even\n * though it counts `mnemo_fact.created_at`.\n */\n getWritesPerDay(\n workspaceId: string,\n days: number\n ): Promise<Array<{ day: string; count: number }>>;\n\n /**\n * Recall calls per UTC day: exactly `days` entries ending today, zero-filled,\n * oldest first, plus the same figures over the whole window. See\n * {@link RecallMetricsWindow} for where each figure comes from.\n */\n getRecallMetrics(workspaceId: string, days: number): Promise<RecallMetrics>;\n\n /**\n * Counts of the live facts (`valid_to IS NULL`, `status = 'active'`) the caller\n * can read: rows above `maxSensitivity` are not counted. No ceiling counts all.\n */\n getFactStats(input: { workspaceId: string; maxSensitivity?: Sensitivity }): Promise<FactStats>;\n}\n\n/**\n * One window of recall activity.\n *\n * - `queries` counts recall calls: the `recall` entries of `mnemo_audit_log`,\n * one per call whatever it returned. `mnemo_recall_log` cannot count them:\n * it has one row per served fact and none at all for a call that served nothing.\n * - `zeroHitShare` is the share of those calls that returned nothing, over the\n * calls whose audit detail is readable (a crypto-wrapped detail hides its\n * `resultCount`); null when none is.\n * - `p50Ms` / `p95Ms` are percentiles of the recall log's `latency_ms` over its\n * `hit_rank = 0` rows, one per call that served a fact; null with no samples.\n */\nexport interface RecallMetricsWindow {\n queries: number;\n zeroHitShare: number | null;\n p50Ms: number | null;\n p95Ms: number | null;\n}\n\nexport interface RecallMetrics {\n /** `YYYY-MM-DD` UTC days, oldest first. */\n days: Array<RecallMetricsWindow & { day: string }>;\n totals: RecallMetricsWindow;\n}\n\n/**\n * Sessions and episodes over a window of UTC days ending today.\n *\n * - `days`: sessions started each day (`mnemo_session.started_at`), split by their\n * current status; exactly `days` entries, zero-filled, oldest first.\n * - `totals.collapsed`: sessions of the window that were collapsed into memory\n * (`collapsed_at` set); `avgTurns` is the mean `turn_count`, null with no session.\n * - `totals.episodes`: non-synthetic episodes that occurred in the window under the\n * ceiling; `factsPerEpisode` is the mean of their linked facts the caller can read.\n * - `topics`: the five topics most of those episodes carry, largest first.\n */\nexport interface SessionStats {\n days: Array<{ day: string; active: number; collapsed: number; archived: number }>;\n totals: {\n sessions: number;\n collapsed: number;\n avgTurns: number | null;\n episodes: number;\n factsPerEpisode: number | null;\n };\n topics: Array<{ topic: string; count: number }>;\n}\n\n/** Live facts under the caller's ceiling, counted four ways. Zero groups are omitted. */\nexport interface FactStats {\n live: number;\n pinned: number;\n /** `hit_count = 0`: never served by a recall. */\n neverRecalled: number;\n /** The latest `created_at` among these same facts (ISO); null when there are none. */\n lastWriteAt: string | null;\n byKind: Array<{ kind: string; count: number }>;\n bySensitivity: Array<{ sensitivity: Sensitivity; count: number }>;\n byMemoryType: Array<{ memoryType: string; count: number }>;\n}\n\n/** Fact-hash and LSH-band indexes backing Tier-2 pointer recall (Wave E/Wave P). */\nexport interface FactIndexPort {\n // Fact hash (Wave E)\n lookupFactHash(workspaceId: string, statementHash: string): Promise<MnemoFactHash | null>;\n upsertFactHash(input: UpsertFactHashInput): Promise<MnemoFactHash>;\n\n // Fact LSH bands — Tier 2 pointer recall (Wave P)\n upsertFactLsh(input: UpsertFactLshInput): Promise<void>;\n pointerCandidates(query: PointerCandidateQuery): Promise<PointerCandidate[]>;\n}\n\n// ─── end segregate-storage-ports PR3 additions (Phase 1 group C, rows 17-24) ──\n\n// ─── segregate-storage-ports — narrow domain sub-ports (PR4, Phase 1 group D) ──\n//\n// PR4 of the same stacked chain additively extracts Port Map rows 25-32 as named\n// interfaces below. Every member's name, signature, optionality, and doc comment\n// is copied VERBATIM from its original home in the flat `StorageAdapter`\n// interface further down this file — nothing here is a behavior change. The\n// flat `StorageAdapter` interface remains completely untouched in this PR (zero\n// deletions); group E (the remaining 7 domain ports) and the final\n// `StorageAdapter` intersection alias land in later PRs in this chain (tasks\n// 1.7-1.11). No D4 overrides land in this group — design.md states the comment\n// headers and adapter delegation already agree for every method here, so this\n// is a straight copy, no reassignment needed. See design.md D3 for placement\n// rationale.\n\n/**\n * Engram neuro-dynamics (Wave Y, §25.2/§25.3): STDP co-recall weighting,\n * Beta-evidence decay, and homeostatic normalisation of hebbian weights.\n */\nexport interface NeuroDynamicsPort {\n /**\n * Decay Beta evidence (worth_alpha/worth_beta) for all facts of a given\n * decay class using exponential half-life. Entity class is a no-op (returns 0).\n * Returns the number of rows updated.\n */\n decayKind(workspaceId: string, decayClass: DecayClass, halfLifeDays: number): Promise<number>;\n\n /**\n * Record a co-recall event between two facts: computes STDP Δw from\n * the inter-spike interval (now − lastCoRecallAt) and updates\n * hebbian_weight, directionality, co_recall_count, last_co_recall_at.\n */\n recordCoRecallStdp(workspaceId: string, relationId: string, coRecalledAt: Date): Promise<void>;\n\n /**\n * Homeostatic weekly rescale: renormalise hebbian_weight for a workspace\n * via PERCENT_RANK() OVER (ORDER BY hebbian_weight). Returns rows updated.\n */\n normalizeHebbianWeights(workspaceId: string): Promise<number>;\n}\n\n/** Meta-cognition (Wave F): confidence/knowledge-gap introspection views over the workspace's memory. */\nexport interface MetacognitionPort {\n getConfidenceMap(workspaceId: string, opts?: { limit?: number }): Promise<ConfidenceMapRow[]>;\n getKnowledgeGaps(\n workspaceId: string,\n opts?: { limit?: number; minScore?: number }\n ): Promise<KnowledgeGapRow[]>;\n getMetacognitionTrends(workspaceId: string): Promise<MetacognitionTrends>;\n refreshMetacognitionViews(): Promise<void>;\n}\n\n/**\n * Anticipation (Wave G): sequential/periodic/conditional/co-occurrence\n * pattern queries feeding the anticipation feed.\n */\nexport interface AnticipationPort {\n getSequentialPatterns(args: {\n workspaceId: string;\n predecessorId?: string;\n minConfidence?: number;\n limit?: number;\n }): Promise<SequentialPatternRow[]>;\n\n getPeriodicPatterns(args: {\n workspaceId: string;\n dayOfWeek?: number;\n hourBucket?: number;\n limit?: number;\n }): Promise<PeriodicPatternRow[]>;\n\n refreshAnticipationViews(): Promise<void>;\n\n getConditionalPatterns(args: {\n workspaceId: string;\n queryKey?: string;\n minConfidence?: number;\n limit?: number;\n }): Promise<ConditionalPatternRow[]>;\n\n getCoOccurrencePatterns(args: {\n workspaceId: string;\n sourceId: string;\n minCoRecall?: number;\n limit?: number;\n }): Promise<CoOccurrencePatternRow[]>;\n}\n\n/** Append-only audit log (workspace governance / mnemo.audit.merkle integrity verification). */\nexport interface AuditPort {\n appendAuditEntry(entry: Omit<AuditLogEntry, \"id\" | \"createdAt\">): Promise<void>;\n /**\n * Return the last `limit` audit log entries for a workspace, ordered by id ASC\n * (oldest first — required by verifyAuditChain() which expects forward order).\n * Used by the mnemo.audit.merkle cron job for integrity verification.\n */\n listAuditLog(workspaceId: string, limit: number): Promise<AuditLogEntry[]>;\n /**\n * What the given actors (audit actor ids, e.g. `user:<id>`) did in this workspace:\n * entries per UTC day and by action over the last `days` days, and each actor's\n * latest entry ever. See {@link AuditActivity}.\n */\n getAuditActivity(input: {\n workspaceId: string;\n days: number;\n actorIds: string[];\n }): Promise<AuditActivity>;\n}\n\n/**\n * Audit-log activity of a set of actors. `days`: exactly `days` UTC days ending\n * today, zero-filled, oldest first. `byAction`: the window's entries by action,\n * largest first. `lastAt`: each actor's latest entry ever (ISO), absent when none.\n */\nexport interface AuditActivity {\n days: Array<{ day: string; count: number }>;\n byAction: Array<{ action: string; count: number }>;\n lastAt: Record<string, string>;\n}\n\n/** Transactional outbox: durable side-effect queue drained by the outbox worker. */\nexport interface OutboxPort {\n appendOutbox(entry: Omit<OutboxEntry, \"id\" | \"createdAt\" | \"attempts\">): Promise<void>;\n claimOutbox(limit: number): Promise<OutboxEntry[]>;\n markOutboxProcessed(ids: string[]): Promise<void>;\n markOutboxFailed(id: string, error: string): Promise<void>;\n /** Move permanently exhausted outbox entries to a dead-letter state. Returns the count moved. */\n reapDeadLetters(maxAttempts: number): Promise<number>;\n /** Delete old processed outbox entries. Returns the count deleted. */\n purgeOutbox(olderThanMs: number): Promise<number>;\n /** Count outbox rows not yet delivered (processedAt IS NULL). For queue-depth telemetry. */\n countPendingOutbox(): Promise<number>;\n}\n\n/** Webhook endpoint registration and delivery tracking. */\nexport interface WebhookPort {\n createWebhookEndpoint(input: CreateWebhookEndpointInput): Promise<MnemoWebhookEndpoint>;\n getWebhookEndpoint(id: string, workspaceId: string): Promise<MnemoWebhookEndpoint | null>;\n listWebhookEndpoints(workspaceId: string): Promise<MnemoWebhookEndpoint[]>;\n updateWebhookEndpoint(\n id: string,\n workspaceId: string,\n input: UpdateWebhookEndpointInput\n ): Promise<MnemoWebhookEndpoint>;\n deleteWebhookEndpoint(id: string, workspaceId: string): Promise<void>;\n recordWebhookDelivery(entry: CreateWebhookDeliveryInput): Promise<void>;\n listWebhookDeliveries(\n webhookId: string,\n workspaceId: string,\n limit?: number\n ): Promise<MnemoWebhookDelivery[]>;\n /** Delivery-worker: returns pending deliveries due for their next attempt. */\n listPendingWebhookDeliveries(limit: number): Promise<MnemoWebhookDelivery[]>;\n /** Delivery-worker: update delivery row after an attempt. */\n updateWebhookDelivery(\n id: string,\n workspaceId: string,\n update: {\n status?: \"pending\" | \"delivered\" | \"failed\";\n responseStatus?: number;\n responseBody?: string;\n attempt?: number;\n deliveredAt?: Date;\n nextAttemptAt?: Date | null;\n }\n ): Promise<void>;\n}\n\n/** Prospective memory (reminders): time/semantic triggers surfaced back to the agent. */\nexport interface ReminderPort {\n createReminder(input: CreateReminderInput): Promise<MnemoReminder>;\n listDueReminderWorkspaceIds(): Promise<string[]>;\n getReminder(id: string, workspaceId: string): Promise<MnemoReminder | null>;\n listPendingReminders(workspaceId: string, asOf: Date): Promise<MnemoReminder[]>;\n dismissReminder(\n id: string,\n workspaceId: string,\n newStatus: \"triggered\" | \"dismissed\"\n ): Promise<void>;\n listReminders(\n workspaceId: string,\n status: \"pending\" | \"triggered\" | \"dismissed\" | \"all\",\n limit: number\n ): Promise<MnemoReminder[]>;\n /**\n * LIFECYCLE-6 — atomically CLAIM triggered reminders no recall has returned\n * yet, stamping `deliveredAt`, and return only the rows this call claimed:\n * the given `ids` (what this recall itself fired) plus up to `limit` of the\n * oldest other undelivered ones. Two concurrent recalls never claim the same\n * row, so a reminder is delivered once. The 30-second poller fires\n * time-only reminders with nobody to show them to; the next recall delivers\n * them through this. Optional: without it a poller-fired reminder reaches\n * agents only through events and webhooks.\n */\n claimUndeliveredReminders?(\n workspaceId: string,\n input: { ids: string[]; limit: number }\n ): Promise<MnemoReminder[]>;\n}\n\n/** §36 embedding-model migration (Wave AA): detect and re-embed stale rows after a model change. */\nexport interface EmbeddingMaintenancePort {\n /**\n * Return up to `limit` rows from `table` whose `embedding_stale = true`\n * or whose `embedding_model != currentModel`.\n * Table is one of: \"fact\" | \"decision\" | \"skill\" | \"strategy\" | \"reasoning\".\n */\n listStaleEmbeddings(\n table: EmbeddableTable,\n workspaceId: string,\n currentModel: string,\n limit: number,\n /**\n * `plaintextOnly`: only `public`/`internal` rows, for an embedder that may\n * not receive confidential+ text (MNEMO_SENSITIVE_TEXT_TO_PROVIDERS=none).\n */\n opts?: { plaintextOnly?: boolean }\n ): Promise<Array<{ id: string; text: string }>>;\n\n /**\n * The sensitivity tier of the row an embedding job would embed, or null when\n * the row or its table is unknown. The outbox worker reads it before\n * embedding text for an embedder that may not receive confidential+ text.\n */\n getEmbeddingSourceSensitivity?(\n table: EmbeddableTable,\n id: string,\n workspaceId: string\n ): Promise<string | null>;\n\n /**\n * Check if workspace has an ongoing embedding migration (stale embeddings exist).\n *\n * P111: takes `currentModel` because \"stale\" is only meaningful relative to the\n * model recall is about to embed with. Unlike {@link listStaleEmbeddings},\n * this requires an existing vector; an unembedded row needs backfill but\n * cannot make vector scores incomparable. The original one-argument signature\n * could only have consulted `embedding_stale`, a flag whose only writer\n * (`markEmbeddingsStale`) has never had a caller, so it would have answered\n * `false` forever even once implemented.\n *\n * Still optional on the port: `recall-cold` guards the call and degrades to\n * `false`. That guard is why an absent implementation went unnoticed for so\n * long, so it is required of the production adapter and stays optional only\n * for partial test doubles.\n */\n hasActiveEmbeddingMigration?(workspaceId: string, currentModel: string): Promise<boolean>;\n\n /**\n * Mark all rows in `table` for `workspaceId` as stale where\n * `embedding_model != currentModel`. Returns count of updated rows.\n */\n markEmbeddingsStale(\n table: EmbeddableTable,\n workspaceId: string,\n currentModel: string\n ): Promise<number>;\n\n /**\n * Write a freshly computed embedding + stamp `embedding_model = model`\n * and `embedding_stale = false` for the given row.\n */\n updateEmbeddingVector(\n table: EmbeddableTable,\n id: string,\n workspaceId: string,\n vector: number[],\n model: string\n ): Promise<void>;\n}\n\n// ─── end segregate-storage-ports PR4 additions (Phase 1 group D, rows 25-32) ──\n\n// ─── segregate-storage-ports — narrow domain sub-ports (PR5, Phase 1 group E) ──\n//\n// PR5 of the same stacked chain additively extracts Port Map rows 33-39 as named\n// interfaces below — the final group. Every member's name, signature, optionality,\n// and doc comment is copied VERBATIM from its original home in the flat\n// `StorageAdapter` interface further down this file — nothing here is a behavior\n// change. The flat `StorageAdapter` interface remains completely untouched in this\n// PR (zero deletions); replacing it with the intersection alias, plus\n// `ports-guard.ts`, land in a later PR in this chain (tasks 1.8-1.11). See\n// design.md D3/D4 for placement rationale and the per-method override table. This\n// PR completes all 39 named sub-ports.\n\n/** Hot-tier ZSet snapshot persistence (§37, Wave AA). */\nexport interface HotTierPort {\n /**\n * Upsert hot-tier snapshot rows into mnemo_hot_tier_snapshot.\n * Uses ON CONFLICT DO UPDATE to overwrite stale scores.\n */\n upsertHotTierSnapshot(rows: HotTierSnapshotRow[]): Promise<void>;\n\n /**\n * Load hot-tier snapshot rows. When workspaceId is provided, scoped to\n * that workspace; otherwise returns all rows (used at boot to reload all).\n */\n loadHotTierSnapshots(workspaceId?: string): Promise<HotTierSnapshotRow[]>;\n}\n\n/**\n * Prometheus scrape-path aggregates + stale-task cron reads.\n *\n * D4 override: `listStaleTasks?`, `countStaleTasks?`, and `countTasksByStatus?`\n * sit under the old \"Wave T4 — OutcomeSignal + stale-task cron\" comment header\n * in the flat interface below, but the `DrizzleStorageAdapter` delegates all\n * three to `this.metering` — the Prometheus scrape path, not task lifecycle —\n * so they belong on `MetricsPort`, not `TaskPort`.\n */\nexport interface MetricsPort {\n /**\n * Return tasks that have been in a non-terminal status for longer than\n * `staleSinceMs` milliseconds. Used by the stale-task cron to auto-archive\n * tasks that are abandoned without being explicitly closed.\n *\n * Terminal statuses (completed, archived) are excluded — only active tasks\n * are returned. Optional because the cron gracefully skips if absent.\n *\n * @param workspaceId - workspace to scan\n * @param staleSinceMs - how old the updatedAt must be (ms, default 7 days)\n * @param limit - max rows to return per cron tick (default 100)\n */\n listStaleTasks?(\n workspaceId: string,\n staleSinceMs: number,\n limit: number\n ): Promise<Array<{ id: string; title: string; status: string; updatedAt: Date }>>;\n\n /**\n * Returns a per-(type,status) fact count for the snapshot gauge.\n * Aggregate across all workspaces; only called on Prometheus scrape (every ~15s).\n * Optional — callers guard with `?.()`.\n */\n countFactsByTypeStatus?(): Promise<Array<{ type: string; status: string; count: number }>>;\n\n /**\n * Returns fact counts bucketed by worth score.\n * Buckets: '0.0-0.2', '0.2-0.4', '0.4-0.6', '0.6-0.8', '0.8-1.0'.\n */\n worthHistogram?(): Promise<Array<{ bucket: string; count: number }>>;\n\n /**\n * Returns the number of currently active sessions (status = 'active').\n */\n countActiveSessions?(): Promise<number>;\n\n /**\n * Returns task counts grouped by status.\n */\n countTasksByStatus?(): Promise<Array<{ status: string; count: number }>>;\n\n /**\n * Returns the count of stale tasks (reuses listStaleTasks logic).\n */\n countStaleTasks?(): Promise<number>;\n}\n\n/**\n * Workspace-level aggregates: vitals, audit feed, health snapshot, knowledge\n * distribution, and operational mode (learning/production graduation).\n *\n * D4 override: `getKnowledgeDistribution` sits under the old \"Episodes\" comment\n * header, and `getWorkspaceVitals`/`getAuditFeed` sit under the old \"Facts\"\n * comment header, in the flat interface below — but the `DrizzleStorageAdapter`\n * delegates all three to `this.episodes`/`this.facts` respectively only\n * incidentally; they are workspace-level aggregates (not per-primitive CRUD),\n * so design D4 assigns them to `WorkspacePort` instead.\n */\nexport interface WorkspacePort {\n /** Workspace vitals aggregate (fact counts, embedding backlog, scope breakdown). */\n getWorkspaceVitals(workspaceId: string): Promise<WorkspaceVitals>;\n /** Undo-log feed: UNION of forgotten facts + archived facts, newest first. */\n getAuditFeed(filter: AuditFeedFilter): Promise<AuditFeedEntry[]>;\n /**\n * The undo-log feed counted per UTC day over the last `days` days: user forgets\n * and system archives, each fact at or under `maxSensitivity`. See {@link AuditFeedStats}.\n */\n getAuditFeedStats(input: {\n workspaceId: string;\n days: number;\n maxSensitivity?: Sensitivity;\n }): Promise<AuditFeedStats>;\n /**\n * Memory-drift snapshot (`mnemo_health`). `fresh: false` (default) reads the\n * latest persisted row, or `null` if none exist. `fresh: true` recomputes\n * now (querying `mnemo_fact`/`mnemo_decision`/`mnemo_relation`/\n * `mnemo_extraction_job`) and persists a new row before returning it.\n * flatten-legacy-dual-core Phase 9 — ports `@mnemo-ai/core`'s\n * `getHealthSnapshot` (Requirement 4).\n */\n getHealthSnapshot(input: GetHealthSnapshotInput): Promise<HealthSnapshot | null>;\n /**\n * The persisted snapshots of the last `days` UTC days, one per day (the day's\n * latest), as shares and rates only: see {@link HealthSnapshotDay}.\n */\n getHealthSnapshots(input: { workspaceId: string; days: number }): Promise<HealthSnapshotDay[]>;\n /**\n * Count active primitives per knowledge type for the UCE scheduler (spec §10).\n * Keys are the 10 RememberKind values; missing types may be omitted (treated as 0).\n */\n getKnowledgeDistribution(workspaceId: string): Promise<Partial<Record<RememberKind, number>>>;\n /**\n * Get the operational mode for a workspace (learning or production).\n * Returns null if no mode row exists yet (caller should treat as learning mode).\n *\n * RDD-5: extended with startedAt, factCount, entityCount for multi-criteria graduation.\n */\n getWorkspaceMode?(workspaceId: string): Promise<{\n mode: \"learning\" | \"production\";\n sessionCount: number;\n promoteAt: number | null;\n /** When the workspace entered learning mode (for daysElapsed graduation criterion). */\n startedAt?: Date;\n /** Cumulative fact count (for factCount >= 50 graduation criterion). */\n factCount?: number;\n /** Cumulative entity count (for entityCount >= 5 graduation criterion). */\n entityCount?: number;\n } | null>;\n\n /**\n * Upsert the workspace mode row. Used to:\n * - promote a workspace from learning → production\n * - increment sessionCount after each collapse\n */\n setWorkspaceMode?(\n workspaceId: string,\n patch: {\n mode?: \"learning\" | \"production\";\n sessionCount?: number;\n promoteAt?: number | null;\n factCount?: number;\n entityCount?: number;\n }\n ): Promise<void>;\n\n /**\n * Atomically increment fact_count and entity_count in mnemo_workspace_mode.\n * Called after each successful collapse to keep graduation criteria up to date.\n *\n * OPTIONAL — when absent the counters are not updated. Callers MUST guard with `?.`.\n */\n incrementWorkspaceModeCounters?(\n workspaceId: string,\n delta: {\n factCount?: number;\n entityCount?: number;\n sessionCount?: number;\n }\n ): Promise<void>;\n}\n\n/** Plugin state persistence — per-workspace, per-plugin JSON blob (§21, Wave U). */\nexport interface PluginStatePort {\n /**\n * Return the full state JSON blob for a plugin in a workspace.\n * Returns null when no row exists yet (plugin has not persisted state).\n * OPTIONAL — callers guard with `?.`.\n */\n getPluginState?(workspaceId: string, pluginId: string): Promise<Record<string, unknown> | null>;\n\n /**\n * Upsert the full state blob for a plugin in a workspace.\n * Uses ON CONFLICT (workspace_id, plugin_id) DO UPDATE.\n * OPTIONAL — callers guard with `?.`.\n */\n upsertPluginState?(\n workspaceId: string,\n pluginId: string,\n state: Record<string, unknown>\n ): Promise<void>;\n\n /**\n * Remove a single key from the plugin's state JSON.\n * No-op when the row or key does not exist.\n * OPTIONAL — callers guard with `?.`.\n */\n deletePluginStateKey?(workspaceId: string, pluginId: string, key: string): Promise<void>;\n}\n\n/** Billing/metering read paths: spend, meter events, and per-metric token/recall usage. */\nexport interface BillingPort {\n /**\n * Get the total spend (USD) for a workspace in the current calendar month.\n * Returns 0.0 when no spend rows exist.\n * Implemented as SUM(cost_usd) over mnemo_meter_event WHERE occurred_at >=\n * date_trunc('month', now()). OPTIONAL — callers guard with `?.`.\n */\n getWorkspaceMonthlySpendUsd?(workspaceId: string): Promise<number>;\n\n /**\n * Durably append a single billing meter event (F15, spec §35 lines 4203-4217).\n *\n * Idempotent: `idempotencyKey` is UNIQUE in mnemo_meter_event, so a retried or\n * cross-replica duplicate write is silently dropped (ON CONFLICT DO NOTHING).\n * Fire-and-forget callers MUST NOT let a rejection bubble onto a request path.\n *\n * The shape is declared structurally (not imported from @mnemo-ai/core) so the\n * types package stays at the bottom of the dependency graph. `metric` is the\n * core MeterMetric string; `quantity` maps to the `units` column; `costUsd`\n * maps to the `cost_usd` column.\n *\n * OPTIONAL — callers guard with `?.`.\n */\n appendMeterEvent?(event: {\n workspaceId: string;\n metric: string;\n quantity: number;\n occurredAt: Date;\n costUsd: number;\n idempotencyKey: string;\n }): Promise<void>;\n\n /**\n * Month-to-date usage counts per metric for a workspace, summed from the\n * durable mnemo_meter_event table (units grouped by operation, occurred_at >=\n * date_trunc('month', now())). Keys are MeterMetric strings; missing metrics\n * are absent (caller defaults to 0). Used by aggregation + GET /usage so\n * usage survives restart. OPTIONAL — callers guard with `?.`.\n */\n getMonthToDateUsageFromDb?(workspaceId: string): Promise<Record<string, number>>;\n\n /**\n * Get the total number of recall operations for a workspace in the current\n * calendar month. Returns 0 when no recall rows exist.\n * Used by the cognitive health snapshot (GET /health/cognitive).\n * OPTIONAL — callers guard with `?.`.\n */\n getWorkspaceMonthlyRecallCount?(workspaceId: string): Promise<number>;\n\n /**\n * Get the total LLM tokens consumed by a workspace since `since`.\n * Returns 0 when no token-usage rows exist.\n * Used by the cost dashboard (GET /cost).\n * OPTIONAL — callers guard with `?.`.\n */\n getWorkspaceLLMTokenUsage?(workspaceId: string, since: Date): Promise<number>;\n\n /**\n * Get the total embedding tokens consumed by a workspace since `since`.\n * Returns 0 when no embedding-usage rows exist.\n * Used by the cost dashboard (GET /cost).\n * OPTIONAL — callers guard with `?.`.\n */\n getWorkspaceEmbeddingTokenUsage?(workspaceId: string, since: Date): Promise<number>;\n}\n\n/** Adapter lifecycle: health probe, graceful close, and workspace enumeration. */\nexport interface LifecyclePort {\n healthCheck(): Promise<HealthStatus>;\n close(): Promise<void>;\n listWorkspaceIds(): Promise<string[]>;\n}\n\n/** The set of optional capabilities an adapter implementation supports. */\nexport interface CapabilitiesPort {\n readonly capabilities: StorageCapabilities;\n}\n\n// ─── end segregate-storage-ports PR5 additions (Phase 1 group E, rows 33-39) ──\n// All 39 named sub-ports now exist. The intersection alias (task 1.8) and\n// `ports-guard.ts` (task 1.9) land in the next PR in this chain.\n\n/**\n * Primary persistence port — the single contract that core depends on for all durable storage.\n *\n * Implemented by: `@mnemo-ai/adapter-postgres` (DrizzleStorageAdapter) and\n * InMemoryStorageAdapter (test utility in `@mnemo-ai/types/src/testing/`).\n *\n * Contract invariants ALL implementations MUST uphold (enforced by StorageAdapterContract.ts):\n * - getFact(id, workspaceIdA) returns null when the fact belongs to workspaceIdB (RLS isolation)\n * - Sensitivity defaults to \"internal\" when not explicitly set\n * - Decimal confidence values must not be truncated (store as NUMERIC/REAL, not INTEGER)\n * - Outbox entries are observable immediately after createFact (transactional outbox)\n * - healthCheck() always returns a value (never throws)\n *\n * How to implement: extend InMemoryStorageAdapter or write from scratch, then run\n * `runStorageAdapterContractTests(makeAdapter)` from packages/types/src/testing/StorageAdapterContract.ts.\n */\nexport type StorageAdapter = SessionPort &\n Partial<HarnessIngestionPort> &\n Partial<ManagedSessionLifecyclePort> &\n Partial<ManagedCollapsePort> &\n Partial<ManagedSessionWorkerPort> &\n FactPort &\n RetentionPort &\n ConsolidationPort &\n ActiveLearningReviewPort &\n DriftReviewPort &\n QueryCachePort &\n DecisionPort &\n EpisodePort &\n EntityPort &\n StrategyPort &\n WorkflowPort &\n SkillPort &\n TaskPort &\n EventPort &\n ReasoningPort &\n AgentPort &\n HyperedgePort &\n CompositionPort &\n RelationPort &\n CitationPort &\n GraphPort &\n RecallPort &\n FactIndexPort &\n NeuroDynamicsPort &\n MetacognitionPort &\n AnticipationPort &\n AuditPort &\n OutboxPort &\n WebhookPort &\n ReminderPort &\n EmbeddingMaintenancePort &\n HotTierPort &\n MetricsPort &\n WorkspacePort &\n PluginStatePort &\n BillingPort &\n LifecyclePort &\n CapabilitiesPort;\n\n/** The primitive tables that carry embedding / embedding_model / embedding_stale columns. */\nexport type EmbeddableTable =\n | \"fact\"\n | \"decision\"\n | \"skill\"\n | \"strategy\"\n | \"reasoning\"\n | \"episode\"\n | \"entity\"\n // P65 / migration 0033 — workflow gained its embedding column. Until then it\n // was in the \"no embedding column, cannot be vector-indexed\" bucket, and the\n // OutboxWorker marked its vector_upsert entries processed after skipping them.\n | \"workflow\"\n // P65 / migration 0034 — same story for these two. `hyperedge` is now the\n // only primitive left without an embedding column.\n | \"task\"\n | \"event\";\n\n/** One hit from StorageAdapter.findSimilarEpisodes (DELTAMEM §16). */\nexport interface SimilarEpisode {\n id: string;\n /** Cosine similarity to the query vector, in [0,1]. Higher = more similar. */\n cosine: number;\n depth: number;\n}\n\n/** One hit from StorageAdapter.findSimilarEntities (P16). */\nexport interface SimilarEntity {\n id: string;\n /** Cosine similarity to the query vector, in [0,1]. Higher = more similar. */\n cosine: number;\n}\n\n/** One row in mnemo_hot_tier_snapshot (§37 Wave AA). */\nexport interface HotTierSnapshotRow {\n workspaceId: string;\n cacheKey: string;\n score: number;\n payload: Record<string, unknown>;\n}\n\n// ─── CacheAdapter ─────────────────────────────────────────────────────────────\n\nexport interface CacheSetOpts {\n ttlMs?: number;\n ifNotExists?: boolean;\n}\n\nexport interface CacheCapabilities {\n sortedSets: boolean;\n pubSub: boolean;\n patterns: boolean;\n atomic: boolean;\n /** Generic Hash field ops (hSet/hGet/hGetAll/hDel). Redis: true; in-process fallback: true. */\n hashes: boolean;\n}\n\n/**\n * Optional caching port — speeds up hot recall paths and holds ephemeral session state.\n *\n * Implemented by: `@mnemo-ai/adapter-redis` (RedisCacheAdapter) and\n * InMemoryCacheAdapter (test utility).\n *\n * Required methods (all implementations): get, set, delete, deletePattern, healthCheck, close.\n * Optional methods (Redis-only, gated by capabilities flags):\n * - sortedSets (zadd, zrangeByScore, zincrby): used by recall-hot.ts for score-ranked recall cache\n * - pubSub (publish, subscribe): used by federation fanout (stub — not yet wired)\n *\n * Core does NOT depend on CacheAdapter being present — the MnemoWorkspace context\n * marks it optional. Without a cache adapter, recall always cold-path fetches from storage.\n * With one, hot-path results are cached under `recall:{workspaceId}:{queryHash}`.\n *\n * TTL contract: callers specify ttlMs per set(); the adapter must honour it within ±1s.\n * Serialization: values are JSON-serialized by the adapter; callers may pass any JSON-safe value.\n */\nexport interface CacheAdapter {\n readonly id: string;\n readonly capabilities: CacheCapabilities;\n\n get<T>(key: string): Promise<T | null>;\n set<T>(key: string, value: T, opts?: CacheSetOpts): Promise<void>;\n delete(key: string): Promise<void>;\n /**\n * Idempotently promote a fact into the workspace hot tier on behalf of one\n * managed collapse effect, trimming the tier to `maxSize`.\n *\n * Optional: an adapter without it simply performs no promotion. `effectId`\n * is the dedup key, so a redelivered effect promotes exactly once.\n */\n applyManagedHotPromotion?(input: {\n workspaceId: string;\n factId: string;\n effectId: string;\n maxSize: number;\n }): Promise<void>;\n deletePattern(pattern: string): Promise<number>;\n\n // Sorted sets — optional (Redis only)\n zadd?(key: string, score: number, member: string): Promise<void>;\n zrangeByScore?(key: string, min: number, max: number, limit?: number): Promise<string[]>;\n zincrby?(key: string, increment: number, member: string): Promise<number>;\n /** Remove members from a sorted set — needed for correct LRU-by-activation eviction. */\n zrem?(key: string, ...members: string[]): Promise<number>;\n\n /**\n * Atomic counter: INCR the key then (re)set its TTL to ttlSeconds, returning\n * the new value. Used by L0 working memory for rate-limit counters and bloom\n * primitives. Optional — present on Redis; the in-process WorkingMemory fallback\n * implements an equivalent. TTL is mandatory (no PERSIST).\n */\n incrWithTtl?(key: string, ttlSeconds: number): Promise<number>;\n\n // Pub/Sub — optional (Redis only)\n publish?(channel: string, message: string): Promise<void>;\n subscribe?(channel: string, handler: (message: string) => void): Promise<void>;\n\n // Lists — optional (Redis only); §35 WS replay ring buffer.\n lpush?(key: string, value: string): Promise<number>;\n lrange?(key: string, start: number, stop: number): Promise<string[]>;\n ltrim?(key: string, start: number, stop: number): Promise<void>;\n lpushCapped?(key: string, value: string, max: number, ttlSeconds: number): Promise<void>;\n\n // Hashes — optional (gated by capabilities.hashes).\n /** Set a single field on a hash and (re)set the hash key's TTL to ttlSeconds. */\n hSetWithTtl?(key: string, field: string, value: string, ttlSeconds: number): Promise<void>;\n /** Read one field; null when the field or key is absent. */\n hGet?(key: string, field: string): Promise<string | null>;\n /** Read every field as a plain object; {} when the key is absent. */\n hGetAll?(key: string): Promise<Record<string, string>>;\n /** Delete one or more fields; returns the number of fields removed. */\n hDel?(key: string, ...fields: string[]): Promise<number>;\n\n healthCheck(): Promise<HealthStatus>;\n info?(): Promise<CacheInfo>;\n close(): Promise<void>;\n}\n\nexport interface CacheInfo {\n usedMemoryBytes: number | null;\n connectedClients: number | null;\n}\n\n// ─── VectorAdapter ────────────────────────────────────────────────────────────\n\nexport interface VectorSearchInput {\n workspaceId: string;\n vector: Float32Array;\n limit: number;\n minSimilarity?: number;\n filter?: Record<string, unknown>;\n}\n\nexport interface VectorSearchHit {\n id: string;\n score: number;\n primitiveKind?: string;\n metadata?: Record<string, unknown>;\n}\n\nexport interface VectorFilter {\n workspaceId?: string;\n primitiveKind?: string;\n ids?: string[];\n}\n\n/**\n * Approximate-nearest-neighbour search port for semantic recall (stage 2 of recall pipeline).\n *\n * Implemented by: `@mnemo-ai/adapter-vector` (pgvector via DrizzleStorageAdapter)\n * and InMemoryVectorAdapter (cosine brute-force for tests, not production).\n *\n * The `dimensions` property MUST match the embedding model in use (1536 for text-embedding-3-small,\n * 3072 for text-embedding-3-large). Mismatch causes a hard error at upsert time.\n *\n * HNSW index params (production only): m=16, ef_construction=64, halfvec(1536).\n * See packages/adapter-postgres/migrations/v3/0005_vector_indexes.sql.\n *\n * Workspace isolation is enforced by including workspaceId in VectorSearchInput.filter —\n * NEVER search without it. The adapter itself does not enforce RLS (unlike StorageAdapter).\n *\n * search() returns hits ordered by score descending. Callers filter by minSimilarity themselves\n * since the threshold is tunable per-query. Typical minimum: 0.7 for semantic recall.\n */\nexport interface VectorAdapter {\n readonly id: string;\n readonly dimensions: number;\n\n search(input: VectorSearchInput): Promise<VectorSearchHit[]>;\n upsert(id: string, vector: Float32Array, metadata?: Record<string, unknown>): Promise<void>;\n delete(id: string, workspaceId: string): Promise<void>;\n deleteByFilter(filter: VectorFilter): Promise<number>;\n\n healthCheck(): Promise<HealthStatus>;\n close(): Promise<void>;\n}\n\n// ─── EmbedAdapter ─────────────────────────────────────────────────────────────\n\n/**\n * Text embedding port — converts strings to dense vectors for semantic similarity.\n *\n * Implemented by: `@mnemo-ai/llm-providers` (OpenAIEmbedAdapter, CohereEmbedAdapter)\n * and InMemoryEmbedAdapter (deterministic mock that returns unit vectors by hash).\n *\n * embed(texts) batches multiple strings into a single API call where possible.\n * embedSingle is a convenience wrapper that calls embed([text])[0].\n *\n * The `model` property is the canonical model identifier (e.g. \"text-embedding-3-small\").\n * It is stored alongside each primitive's embedding so stale embeddings can be detected\n * and re-generated when the model changes (embeddingStale flag on primitives).\n *\n * Never pass empty strings — most providers return a zero vector or error.\n * Text should be pre-processed (stripped of markdown/HTML) before embedding.\n */\nexport interface EmbedAdapter {\n readonly id: string;\n readonly model: string;\n readonly dimensions: number;\n\n /**\n * Whether these vectors carry real semantic meaning.\n *\n * `false` marks a stand-in that returns well-formed, unit-length vectors with\n * no relationship to meaning — today that is the `MNEMO_EMBED_STUB=true`\n * hash embedder (SHA-256 expanded to 1536 floats). Absent/`true` means a real\n * provider.\n *\n * It exists because P115: the RecMem gate in session collapse compared stub\n * cosines against a 0.6 threshold and, when they fell short, DISCARDED the\n * collapse and closed the session. Two sessions on the same topic scored 0.58\n * and 0.50 — and the more repetitive one scored LOWER. A hash was deciding\n * whether a session became memory, and nothing in the type system connected\n * \"these vectors are fake\" to \"do not let a semantic gate act on them\".\n *\n * Contract for consumers: a component that makes an IRREVERSIBLE or\n * lossy decision from vector similarity MUST check this and stand down when\n * it is `false`. Ranking and ordering may still use the vectors — a bad\n * ordering is recoverable, a discarded session is not.\n */\n readonly semantic?: boolean;\n\n /**\n * The operator runs this embedder on its own machine or private network, so\n * confidential and restricted text sent to it does not leave the deployment.\n * Absent/`false` = external (SECURITY.md §7, MNEMO_SENSITIVE_TEXT_TO_PROVIDERS).\n */\n readonly local?: boolean;\n\n embed(texts: string[]): Promise<Float32Array[]>;\n embedSingle(text: string): Promise<Float32Array>;\n\n /** Optional input_type-aware embed for document indexing (e.g. Voyage/Cohere). */\n embedDocument?(texts: string[]): Promise<Float32Array[]>;\n /** Optional input_type-aware embed for search queries (e.g. Voyage/Cohere). */\n embedQuery?(text: string): Promise<Float32Array>;\n\n healthCheck(): Promise<HealthStatus>;\n}\n\n// ─── LLMAdapter ───────────────────────────────────────────────────────────────\n\nexport interface LLMMessage {\n role: \"user\" | \"assistant\";\n content: string;\n}\n\n/**\n * Which engine job a completion serves. A host that routes completions per task\n * (the server's MNEMO_LLM_<TASK>_* variables) picks the provider from it; a\n * single provider ignores it. Unset means \"default\".\n *\n * - judge: a verdict over given material (conflict classification, rerank, reminder conditions)\n * - summary: condensing a session or document into facts (collapse, capture, compression)\n * - prefilter: shaping a query before retrieval (HyDE, anticipation queries)\n * - default: everything else\n */\nexport type LLMTask = \"judge\" | \"summary\" | \"prefilter\" | \"default\";\n\nexport interface LLMInput {\n system?: string;\n messages: LLMMessage[];\n maxTokens?: number;\n temperature?: number;\n /** Hint to the LLM adapter to use this specific model (e.g. \"haiku\" for cheap tier). */\n model?: string;\n /** The job this completion serves, for per-task provider routing. */\n task?: LLMTask;\n}\n\nexport interface LLMOutput {\n content: string;\n tokensUsed: { input: number; output: number };\n model: string;\n finishReason: \"stop\" | \"length\" | \"tool_use\";\n /** Vendor identity (\"openai\", \"anthropic\", ...) when surfaced by the provider. */\n provider?: string;\n /** Vendor-estimated USD cost for this completion; undefined when the model is not priced. */\n costUSD?: number;\n}\n\n// Duck-typed schema (structurally matches zod, valibot, etc.)\nexport interface SchemaLike<T> {\n parse: (data: unknown) => T;\n}\n\n/**\n * LLM inference port — drives extraction, consolidation, and CUP migration.\n *\n * Implemented by: `@mnemo-ai/llm-providers` (ClaudeAdapter, OpenAIAdapter, GeminiAdapter).\n * Routing across providers is handled by LLMRouter (packages/core/src/v3/llm/router.ts)\n * which wraps multiple LLMAdapters with per-task provider selection + BudgetGuard.\n *\n * generate(): unstructured text generation. Used for CUP migration narration and\n * session collapse summarization.\n *\n * generateStructured<T>(input, schema): returns a validated T by asking the LLM to\n * produce a JSON object that matches the schema. The schema argument is duck-typed\n * (SchemaLike<T>) — works with zod, valibot, or any object with a `.parse()` method.\n * Used for extraction (fact/decision/entity parsing) and consolidation classification.\n *\n * Callers must handle token budget: maxTokens in LLMInput sets output ceiling.\n * The tokensUsed in LLMOutput is authoritative for cost tracking (BudgetGuard reads it).\n *\n * Implementation note: do NOT store LLMAdapter instances in workspace context directly —\n * always go through LLMRouter to enable provider switching and cost limits.\n */\nexport interface LLMAdapter {\n readonly id: string;\n readonly model: string;\n /**\n * The tasks this adapter answers from a provider the operator runs on its own\n * machine or private network: confidential and restricted text sent for them\n * does not leave the deployment. Absent = every task is external\n * (SECURITY.md §7, MNEMO_SENSITIVE_TEXT_TO_PROVIDERS).\n */\n readonly localTasks?: readonly LLMTask[];\n\n generate(input: LLMInput): Promise<LLMOutput>;\n generateStructured<T>(input: LLMInput, schema: SchemaLike<T>): Promise<T>;\n\n healthCheck(): Promise<HealthStatus>;\n}\n\n// ─── QueueAdapter ─────────────────────────────────────────────────────────────\n\nexport interface EnqueueOpts {\n priority?: number;\n retryLimit?: number;\n retryDelay?: number;\n startAfter?: Date;\n singletonKey?: string;\n}\n\nexport type JobHandler<T = unknown> = (data: T) => Promise<void>;\n\n/**\n * Background job port — schedules async work (embedding refresh, consolidation, webhook delivery).\n *\n * Implemented by: `@mnemo-ai/adapter-postgres` (PgBossQueueAdapter using pg-boss in\n * the same Postgres database as storage, so jobs are durable) and InMemoryQueueAdapter\n * (immediate synchronous execution for tests — no actual deferral).\n *\n * enqueue(): one-shot job. Returns jobId for status tracking.\n * - singletonKey: prevents duplicate jobs (used for workspace-scoped consolidation runs).\n * - startAfter: future-scheduled execution (used for TTL-expiry reminders).\n * - retryLimit + retryDelay: exponential backoff on handler errors.\n *\n * schedule(): recurring cron job. Idempotent — calling twice with same jobName+cron is a no-op.\n * Used to schedule nightly consolidation and embedding staleness scans.\n *\n * process(): registers the handler for a job type. Must be called at server startup before\n * jobs start processing. Handlers are async and must not throw — errors go to pg-boss\n * dead-letter queue and are retried per retryLimit.\n *\n * Shutdown: always call close() on graceful shutdown to let in-flight jobs complete.\n */\nexport interface QueueAdapter {\n readonly id: string;\n\n enqueue(jobName: string, data: unknown, opts?: EnqueueOpts): Promise<string>;\n schedule(jobName: string, cron: string, data?: unknown): Promise<void>;\n process<T = unknown>(jobName: string, handler: JobHandler<T>): Promise<void>;\n\n healthCheck(): Promise<HealthStatus>;\n close(): Promise<void>;\n}\n\n// ─── OutboxAdapter ────────────────────────────────────────────────────────────\n\nexport interface OutboxStats {\n pending: number;\n failed: number;\n oldestPendingMs: number;\n}\n\n/**\n * Transactional outbox port — guarantees at-least-once event delivery without 2-phase commit.\n *\n * Implemented by: `@mnemo-ai/adapter-postgres` (DrizzleOutboxAdapter writing to mnemo_outbox\n * in the same transaction as the fact/decision write). There is no InMemory implementation —\n * OutboxAdapter is always paired with a real database transaction.\n *\n * Pattern: within a storage write transaction, call append() so the outbox entry is committed\n * atomically with the fact. A background poller (OutboxRelay in packages/core) calls\n * claimBatch() → delivers events → markProcessed(). On failure, markFailed() increments\n * the attempt counter; the poller retries until MAX_ATTEMPTS (see outbox.ts).\n *\n * append(): must be called INSIDE the same DB transaction as the primary write.\n * Passing the entry outside a transaction breaks the atomicity guarantee.\n *\n * claimBatch(): claims and locks entries for processing (SELECT … FOR UPDATE SKIP LOCKED).\n * Returns at most `limit` entries. Only pending entries with attempts < MAX are returned.\n *\n * Security: the mnemo_app_role has INSERT-only on mnemo_outbox (UPDATE and DELETE revoked).\n * Processed/failed entries are marked by a privileged relay role, not the app role.\n */\nexport interface OutboxAdapter {\n append(entry: Omit<OutboxEntry, \"id\" | \"createdAt\" | \"attempts\">): Promise<void>;\n claimBatch(limit: number): Promise<OutboxEntry[]>;\n markProcessed(ids: string[]): Promise<void>;\n markFailed(id: string, error: string): Promise<void>;\n getStats(): Promise<OutboxStats>;\n}\n\n// ─── Logger ───────────────────────────────────────────────────────────────────\n\nexport interface LogContext {\n workspaceId?: string;\n agentId?: string;\n traceId?: string;\n spanId?: string;\n operation?: string;\n durationMs?: number;\n error?: { type: string; message: string; stack?: string; code?: string };\n cost?: { model: string; tokensIn: number; tokensOut: number; costUsd: number };\n [key: string]: unknown;\n}\n\nexport interface Logger {\n debug(msg: string, ctx?: LogContext): void;\n info(msg: string, ctx?: LogContext): void;\n warn(msg: string, ctx?: LogContext): void;\n error(msg: string, ctx?: LogContext): void;\n fatal(msg: string, ctx?: LogContext): void;\n child(bindings: Record<string, unknown>): Logger;\n}\n\n// ─── Telemetry ────────────────────────────────────────────────────────────────\n\nexport interface SpanOpts {\n parent?: Span;\n attributes?: Record<string, string | number | boolean>;\n}\n\nexport interface Span {\n setAttribute(key: string, value: string | number | boolean): void;\n setStatus(status: \"ok\" | \"error\", message?: string): void;\n end(): void;\n}\n\nexport interface Telemetry {\n startSpan(name: string, opts?: SpanOpts): Span;\n counter(name: string, value?: number, attrs?: Record<string, string>): void;\n histogram(name: string, value: number, attrs?: Record<string, string>): void;\n gauge(name: string, value: number, attrs?: Record<string, string>): void;\n shutdown(): Promise<void>;\n}\n\n// ─── RBAC policy stores (§19) ─────────────────────────────────────────────────\n\nimport type { AgentMemoryAccess, ApprovalTrigger, SpecScope } from \"./security.js\";\n\nexport type AccessPolicyRecord = AgentMemoryAccess & { namespaces?: string[] };\n\nexport interface AccessPolicyStore {\n getPolicy(workspaceId: string, agentId: string): Promise<AccessPolicyRecord | null>;\n putPolicy(policy: AccessPolicyRecord): Promise<void>;\n listPolicies(workspaceId: string): Promise<AccessPolicyRecord[]>;\n /** Returns false when the agent had no policy in this workspace. */\n deletePolicy(workspaceId: string, agentId: string): Promise<boolean>;\n}\n\nexport interface ApprovalRequestInput {\n workspaceId: string;\n requestedBy: string;\n trigger: ApprovalTrigger;\n resource: string;\n resourceId?: string;\n payload: Record<string, unknown>;\n expiresAt: Date;\n}\n\nexport interface ApprovalRequest extends ApprovalRequestInput {\n id: string;\n /** `consumed`: an approved request that has been carried out (APP-007). */\n status: \"pending\" | \"approved\" | \"denied\" | \"expired\" | \"consumed\";\n resolvedBy?: string;\n resolvedAt?: Date;\n createdAt: Date;\n}\n\n/**\n * How long a raised approval request waits for a human decision, and how long\n * an approval stays usable once granted (counted from the decision, not from\n * the request). Final review I6 of the 2026-11-22 audit.\n */\nexport const APPROVAL_PENDING_TTL_MS = 24 * 60 * 60_000;\nexport const APPROVAL_USE_TTL_MS = 60 * 60_000;\n\nexport interface ApprovalStore {\n create(input: ApprovalRequestInput): Promise<ApprovalRequest>;\n get(workspaceId: string, id: string): Promise<ApprovalRequest | null>;\n /**\n * Moves a pending, unexpired request to `status`. Resolves false when it was\n * no longer pending or had expired, so two resolvers cannot both win.\n */\n resolve(\n workspaceId: string,\n id: string,\n status: \"approved\" | \"denied\",\n resolvedBy: string\n ): Promise<boolean | void>;\n /**\n * APP-007 — spend an approved request on the request it was granted for:\n * atomically, only while approved and unexpired, only by the user who asked\n * for it, only for the same method and path. True when this call spent it.\n */\n consume(\n workspaceId: string,\n id: string,\n by: { requestedBy: string; method: string; path: string }\n ): Promise<boolean>;\n}\n\n// ─── WP8 (F10) — SOC2 break-glass two-person approval ─────────────────────────\n\nexport interface BreakGlassRequestInput {\n workspaceId: string;\n /** Admin A — the requester. */\n requestedBy: string;\n /** Free-text incident justification (audited). */\n reason: string;\n /** §6 scopes the grant covers (e.g. [\"memory:export\"]). */\n requestedScopes: SpecScope[];\n /** Grant validity ceiling (server-set; typically now + 15m). */\n expiresAt: Date;\n}\n\nexport interface BreakGlassRequestRecord extends BreakGlassRequestInput {\n id: string;\n status: \"pending\" | \"approved\" | \"denied\" | \"expired\" | \"used\";\n /** Admin B — the approver. Set on approve(); MUST differ from requestedBy. */\n approvedBy?: string;\n approvedAt?: Date;\n usedAt?: Date;\n createdAt: Date;\n}\n\nexport interface BreakGlassStore {\n /** Admin A files a pending request. */\n request(input: BreakGlassRequestInput): Promise<BreakGlassRequestRecord>;\n /**\n * Admin B approves. MUST throw if approverId === the request's requestedBy\n * (two-person / dual-control rule — a requester cannot self-approve).\n */\n approve(workspaceId: string, id: string, approverId: string): Promise<void>;\n /** Single fetch by id (audit + status checks). */\n get(workspaceId: string, id: string): Promise<BreakGlassRequestRecord | null>;\n /**\n * The active grant for a requester: status='approved', not expired, not yet\n * used. Returns null when none — the gate then 403s (or 202s on pending).\n */\n getActiveApproved(\n workspaceId: string,\n requestedBy: string\n ): Promise<BreakGlassRequestRecord | null>;\n /** Consume a grant (single-use): flips status→'used' and stamps usedAt. */\n markUsed(workspaceId: string, id: string): Promise<void>;\n}\n\n// ─── Wave X — Session token store (device binding + refresh-token rotation) ──\n\nexport interface SessionTokenRecord {\n id: string;\n workspaceId: string;\n actorId: string;\n /** SHA-256 hash of the plaintext refresh token. */\n tokenHash: string;\n /** SHA-256 of userAgent + acceptLanguage + ipNetwork. */\n deviceFingerprint: string;\n /** Set to the time of first use; null while still valid for first rotation. */\n usedAt: Date | null;\n /** Null = active family. Non-null = family revoked at this time. */\n familyRevokedAt: Date | null;\n expiresAt: Date;\n createdAt: Date;\n}\n\nexport interface SessionTokenStore {\n /** Store a new refresh token hash for a given actor. */\n create(\n input: Omit<SessionTokenRecord, \"id\" | \"usedAt\" | \"familyRevokedAt\" | \"createdAt\">\n ): Promise<SessionTokenRecord>;\n /** Look up a token by its SHA-256 hash (exact match, workspace-scoped). */\n findByHash(workspaceId: string, tokenHash: string): Promise<SessionTokenRecord | null>;\n /** Mark a token as used (sets usedAt = now). */\n markUsed(id: string, workspaceId: string): Promise<void>;\n /** Revoke the entire family rooted at the given token id. */\n revokeFamily(rootId: string, workspaceId: string): Promise<void>;\n /** Delete all expired tokens for housekeeping. */\n purgeExpired(workspaceId: string): Promise<number>;\n}\n\n// ─── Idempotency port ──────────────────────────────────────────────────────\n\nexport type BeginResult =\n | { state: \"new\" }\n | { state: \"replay\"; responseCode: number; responseBody: string }\n | { state: \"in_flight\" }\n | { state: \"mismatch\" };\n\n/**\n * Stripe-pattern recovery points for multi-phase mutating operations\n * (spec §Idempotency / RDD9, lines 3954-3964). A long op records its phase as\n * it advances so a crashed-then-retried request can skip completed phases.\n * started → key claimed, no work done yet (INSERT default)\n * session_locked → Phase 1 done: local bookkeeping committed (session marked collapsing)\n * llm_called → Phase 2 done: external LLM summarisation succeeded\n * facts_persisted → Phase 3 done: knowledge units written to PG\n * completed → Phase 4 done: response persisted; future calls replay\n */\nexport const RECOVERY_POINTS = [\n \"started\",\n \"session_locked\",\n \"llm_called\",\n \"facts_persisted\",\n \"completed\",\n] as const;\nexport type RecoveryPoint = (typeof RECOVERY_POINTS)[number];\n\nexport interface IdempotencyStore {\n /** Atomically claim the key. MUST run under SERIALIZABLE so concurrent dupes collide. */\n begin(workspaceId: string, key: string, requestHash: string): Promise<BeginResult>;\n /** Persist the final response for future replays. Sets recovery_point='completed'. */\n complete(\n workspaceId: string,\n key: string,\n responseCode: number,\n responseBody: string\n ): Promise<void>;\n /**\n * Advance the recovery point for an in-flight key (idempotent: re-recording the\n * same phase is a no-op). Used by multi-phase ops (session collapse) to mark\n * progress so a retry can skip completed phases. No-op if the key row is absent.\n */\n recordPhase(workspaceId: string, key: string, phase: RecoveryPoint): Promise<void>;\n /** Read the current recovery point, or null if the key is unknown. */\n getRecoveryPoint(workspaceId: string, key: string): Promise<RecoveryPoint | null>;\n}\n\n/** Atomic, lease-fenced managed extraction persistence. */\nexport interface ManagedCollapsePort {\n commitManagedCollapse(input: {\n operationId: string;\n workspaceId: string;\n sessionId: string;\n generation: number;\n leaseOwner: string;\n plan: import(\"./managed-collapse.js\").ManagedCollapsePlan;\n }): Promise<import(\"./harness.js\").ManagedCollapseCommitResult>;\n}\n\nexport interface ManagedSessionWorkerPort {\n isHarnessIngestionEnabled(input: { workspaceId: string }): Promise<boolean>;\n disableHarnessIngestion(input: {\n workspaceId: string;\n }): Promise<{ ingestionEnabled: false; fenceEpoch: number }>;\n heartbeatManagedCollapseLease(input: {\n workspaceId: string;\n sessionId: string;\n operationId: string;\n leaseOwner: string;\n leaseMs: number;\n }): Promise<boolean>;\n claimManagedCollapseEffects(input: {\n workspaceId: string;\n leaseOwner: string;\n limit: number;\n leaseMs: number;\n }): Promise<import(\"./managed-collapse.js\").ManagedEffectClaim[]>;\n completeManagedCollapseEffect(input: {\n workspaceId: string;\n id: string;\n leaseOwner: string;\n }): Promise<boolean>;\n retryManagedCollapseEffect(input: {\n workspaceId: string;\n id: string;\n leaseOwner: string;\n error: string;\n baseRetryMs: number;\n maxRetryMs: number;\n }): Promise<boolean>;\n runManagedCollapseEffect(\n input: { workspaceId: string; id: string; leaseOwner: string },\n apply: (ports: { storage: StorageAdapter; outbox: OutboxAdapter }) => Promise<void>\n ): Promise<boolean>;\n}\n","// Security, auth, RBAC, and sensitivity types — SECURITY.md §2, §3, §5\n// TASK-2003 deliverable.\n\nimport type { Sensitivity } from \"./common.js\";\nimport type { HealthStatus } from \"./common.js\";\nimport type { ActorType } from \"./provenance.js\";\nimport type { AuditAction } from \"./audit.js\";\nimport type { LLMTask } from \"./ports.js\";\n\n// ─── Sensitivity ordering (fixes MED-23: comparison was string equality) ──────\n//\n// Sensitivity tiers map to integers. ALWAYS compare using SENSITIVITY_ORDER or\n// sensitivityAtLeast() — NEVER with string equality or alphabetic comparison.\n//\n// MED-23 root cause: \"confidential\" > \"internal\" is alphabetically correct but\n// semantically wrong (internal=1 < confidential=2). String comparison produced\n// inverted access decisions.\n//\n// Enforcement rule:\n// - On ceiling violation: return 404 NOT 403 (anti-probing — do not confirm existence)\n// - Auth context carries maxSensitivity; fact carries sensitivity\n// - Access allowed when: SENSITIVITY_ORDER[fact.sensitivity] <= SENSITIVITY_ORDER[auth.maxSensitivity]\n\nexport const SENSITIVITY_ORDER: Record<Sensitivity, number> = {\n public: 0, // visible to anyone with workspace read access\n internal: 1, // workspace-internal, not for external sharing\n confidential: 2, // restricted distribution within workspace\n restricted: 3, // highest tier: need-to-know only\n};\n\n/**\n * Returns true if sensitivity `a` is at or above tier `b`.\n * Use this when checking if a fact's sensitivity is within the caller's ceiling.\n *\n * @example\n * // Allow access only if caller's ceiling >= fact's sensitivity\n * if (!sensitivityAtLeast(auth.maxSensitivity, fact.sensitivity)) {\n * return notFound(); // 404, never 403 (anti-probing rule)\n * }\n */\nexport function sensitivityAtLeast(a: Sensitivity, b: Sensitivity): boolean {\n return SENSITIVITY_ORDER[a] >= SENSITIVITY_ORDER[b];\n}\n\n/** The tiers a caller with `ceiling` may read, lowest first. */\nexport function tiersAtOrBelow(ceiling: Sensitivity): Sensitivity[] {\n return (Object.keys(SENSITIVITY_ORDER) as Sensitivity[]).filter(\n (tier) => SENSITIVITY_ORDER[tier] <= SENSITIVITY_ORDER[ceiling]\n );\n}\n\n// ─── Sensitive text to providers (SECURITY.md §7) ─────────────────────────────\n\n/**\n * MNEMO_SENSITIVE_TEXT_TO_PROVIDERS: which external providers may receive the\n * plaintext of confidential and restricted text.\n * none neither the embedder nor the completion provider\n * embed the embedder only (the default)\n * all both\n * A provider the operator runs locally is not egress and gets it under any value\n * (`EmbedAdapter.local`, `LLMAdapter.localTasks`).\n */\nexport type SensitiveTextPolicy = \"none\" | \"embed\" | \"all\";\n\n/** Confidential, restricted, or a tier that is missing or unknown: fail closed. */\nexport function isSensitiveTier(tier: Sensitivity | null | undefined): boolean {\n // Own properties only: `in` would accept \"toString\" or \"__proto__\".\n const rank =\n typeof tier === \"string\" && Object.prototype.hasOwnProperty.call(SENSITIVITY_ORDER, tier)\n ? SENSITIVITY_ORDER[tier]\n : undefined;\n return typeof rank !== \"number\" || rank >= SENSITIVITY_ORDER.confidential;\n}\n\n/** Whether confidential+ text may go to this embedder. */\nexport function sensitiveTextMayReachEmbedder(\n policy: SensitiveTextPolicy | undefined,\n embed: { readonly local?: boolean } | undefined\n): boolean {\n return (policy ?? \"embed\") !== \"none\" || embed?.local === true;\n}\n\n/**\n * Whether confidential+ text may go to this completion adapter for `task`. A\n * completion with no task is routed to whatever answers by default, so it never\n * counts as local: only `all` lets it through.\n */\nexport function sensitiveTextMayReachLlm(\n policy: SensitiveTextPolicy | undefined,\n llm: { readonly localTasks?: readonly LLMTask[] } | undefined,\n task: LLMTask | undefined\n): boolean {\n if (policy === \"all\") return true;\n return task !== undefined && Array.isArray(llm?.localTasks) && llm.localTasks.includes(task);\n}\n\n// ─── API Key types ─────────────────────────────────────────────────────────────\n\nexport type ApiKeyType = \"mk_live_\" | \"mk_test_\" | \"mk_sess_\" | \"mk_fed_\" | \"mk_admin_\";\n\n// ─── Scopes ────────────────────────────────────────────────────────────────────\n\nexport type KeyScope =\n | \"memory:read\"\n | \"memory:write\"\n | \"memory:delete\"\n | \"memory:admin\"\n | \"memory:hard_delete\"\n | \"memory:session\"\n | \"memory:task\"\n | \"memory:event\"\n | \"memory:self_edit\"\n | \"memory:procedural\"\n | \"memory:reasoning\"\n | \"memory:export\"\n | \"memory:governance\"\n | \"memory:subscribe\"\n | \"session:read\"\n | \"session:write\"\n | \"session:manage\"\n | \"entity:read\"\n | \"entity:write\"\n | \"entity:admin\"\n | \"federation:read\"\n | \"federation:write\"\n | \"federation:manage\"\n // Peer trust administration (approve/reject/revoke a federation peer) is a\n // separate, non-tenant-mintable authority tier from routine federation\n // data-plane sync — see WORKSPACE_ADMIN_SCOPES below and the SPEC_SCOPES\n // comment. Never add this to SPEC_SCOPES (same precedent as admin:workspace).\n | \"federation:admin\"\n | \"memory:federation\" // canonical name — XDC-06 fix\n | \"admin:keys\"\n | \"admin:workspace\"\n | \"admin:billing\"\n | \"admin:tenant\";\n\nexport const ALL_SCOPES: ReadonlyArray<KeyScope> = [\n \"memory:read\",\n \"memory:write\",\n \"memory:delete\",\n \"memory:admin\",\n \"memory:hard_delete\",\n \"memory:session\",\n \"memory:task\",\n \"memory:event\",\n \"memory:self_edit\",\n \"memory:procedural\",\n \"memory:reasoning\",\n \"memory:export\",\n \"memory:governance\",\n \"memory:subscribe\",\n \"session:read\",\n \"session:write\",\n \"session:manage\",\n \"entity:read\",\n \"entity:write\",\n \"entity:admin\",\n \"federation:read\",\n \"federation:write\",\n \"federation:manage\",\n \"federation:admin\",\n \"memory:federation\",\n \"admin:keys\",\n \"admin:workspace\",\n \"admin:billing\",\n \"admin:tenant\",\n] as const;\n\n// ─── Spec §6 — 15 canonical memory scopes ─────────────────────────────────────\n\n// NOTE: \"federation:admin\" is deliberately NOT listed here, mirroring the\n// existing \"admin:workspace\" precedent — SPEC_SCOPES is the set a\n// workspace-scoped dashboard/MCP flow can self-mint, and peer trust\n// administration must stay operator-provisioned only (out-of-band via\n// POST /admin/keys or the create-api-key.cjs bootstrap script).\nexport const SPEC_SCOPES = [\n \"memory:read\",\n \"memory:write\",\n \"memory:delete\",\n \"memory:hard_delete\",\n \"memory:session\",\n \"memory:task\",\n \"memory:event\",\n \"memory:self_edit\",\n \"memory:procedural\",\n \"memory:reasoning\",\n \"memory:export\",\n \"memory:admin\",\n \"memory:federation\",\n \"memory:governance\",\n \"memory:subscribe\",\n] as const;\n\nexport type SpecScope = (typeof SPEC_SCOPES)[number];\n\n// ─── Workspace membership roles → scope narrowing ─────────────────────────────\n//\n// mnemo_workspace_member.role is one of 4 values (owner/admin/write/read). It\n// governs what a user-token (uk_live_*) request may do IN A SPECIFIC WORKSPACE\n// — narrower than, and never wider than, the token's own static scopes. See\n// docs/architecture/MULTI_TENANCY.md for the full model and rationale.\n//\n// Tenant-plane scopes (admin:tenant, admin:billing) and the instance-global\n// admin:workspace scope are NEVER narrowed by a workspace role — they belong\n// to a different, orthogonal authority plane (see WORKSPACE_GOVERNED_SCOPES).\n\nexport type WorkspaceRole = \"read\" | \"write\" | \"admin\" | \"owner\";\n\nexport const WORKSPACE_ROLE_ORDER: Record<WorkspaceRole, number> = {\n read: 0,\n write: 1,\n admin: 2,\n owner: 3,\n};\n\n/** Returns true if workspace role `a` is at or above tier `b`. */\nexport function roleAtLeast(a: WorkspaceRole, b: WorkspaceRole): boolean {\n return WORKSPACE_ROLE_ORDER[a] >= WORKSPACE_ROLE_ORDER[b];\n}\n\n/** Scopes governed by workspace membership role — every scope except the 3 tenant/instance-plane ones. */\nexport const WORKSPACE_GOVERNED_SCOPES: ReadonlySet<KeyScope> = new Set(\n ALL_SCOPES.filter((s) => s !== \"admin:tenant\" && s !== \"admin:billing\" && s !== \"admin:workspace\")\n);\n\nconst WORKSPACE_READ_SCOPES: ReadonlyArray<KeyScope> = [\n \"memory:read\",\n \"memory:subscribe\",\n \"session:read\",\n \"entity:read\",\n \"federation:read\",\n];\n\nconst WORKSPACE_WRITE_SCOPES: ReadonlyArray<KeyScope> = [\n ...WORKSPACE_READ_SCOPES,\n \"memory:write\",\n \"memory:delete\",\n \"memory:session\",\n \"memory:task\",\n \"memory:event\",\n \"memory:reasoning\",\n \"memory:procedural\",\n \"memory:self_edit\",\n \"session:write\",\n \"entity:write\",\n];\n\nconst WORKSPACE_ADMIN_SCOPES: ReadonlyArray<KeyScope> = [\n ...WORKSPACE_WRITE_SCOPES,\n \"memory:admin\",\n \"memory:hard_delete\",\n \"memory:export\",\n \"memory:governance\",\n \"memory:federation\",\n \"admin:keys\",\n \"session:manage\",\n \"entity:admin\",\n \"federation:write\",\n \"federation:manage\",\n \"federation:admin\",\n];\n\n/**\n * Scopes a member with this workspace role may exercise IN THAT WORKSPACE.\n * `owner` and `admin` are deliberately scope-identical: the owner/admin\n * distinction is a membership-management privilege (transfer ownership,\n * remove the last owner, delete the workspace), not a difference in what\n * memory operations are allowed — see `requireWorkspaceAdmin` in\n * `packages/server/src/routes/tenants.ts`. Inventing an owner-only scope\n * with no route behind it would be speculative surface this codebase avoids.\n */\nexport const WORKSPACE_ROLE_SCOPES: Record<WorkspaceRole, ReadonlySet<KeyScope>> = {\n read: new Set(WORKSPACE_READ_SCOPES),\n write: new Set(WORKSPACE_WRITE_SCOPES),\n admin: new Set(WORKSPACE_ADMIN_SCOPES),\n owner: new Set(WORKSPACE_ADMIN_SCOPES),\n};\n\n/**\n * Narrow a key's own static scopes down to what its workspace membership\n * role allows IN THIS WORKSPACE. Tenant/instance-plane scopes (outside\n * `WORKSPACE_GOVERNED_SCOPES`) always pass through untouched — a different\n * authority plane. This can only ever REMOVE scopes from the input, never\n * add one: a workspace role can never grant more than the key already had.\n */\nexport function narrowScopesForWorkspaceRole(\n keyScopes: ReadonlyArray<KeyScope>,\n role: WorkspaceRole\n): ReadonlyArray<KeyScope> {\n const allowed = WORKSPACE_ROLE_SCOPES[role];\n return keyScopes.filter((s) => !WORKSPACE_GOVERNED_SCOPES.has(s) || allowed.has(s));\n}\n\n// ─── Auth context ──────────────────────────────────────────────────────────────\n\nexport interface KeyDeprecation {\n deprecated: true;\n /** ISO-8601 sunset instant = deprecatedAt + 7 days. */\n sunset: string;\n}\n\n/** One row of markUsed history, newest first (for anomaly detection). */\nexport interface KeyUsageEvent {\n ipAddress: string;\n at: Date;\n}\n\nexport interface RotateKeyResult {\n /** The full new key shown ONCE (SECURITY.md §2.2). */\n newKey: string;\n newKeyId: string;\n /** The old key's ISO sunset (deprecatedAt + 7 days). */\n sunset: string;\n}\n\nexport interface KeyEscrowEntry {\n keyId: string;\n prefix: ApiKeyType;\n workspaceId: string;\n scopes: KeyScope[];\n action: \"rotate\" | \"revoke\" | \"break_glass\";\n reason: string;\n escrowedAt: Date;\n}\n\nexport interface AuthContext {\n workspaceId: string;\n actorId: string;\n actorType: ActorType;\n /** The platform account (mnemo_user.id) behind this action, when one exists. */\n userId?: string | null;\n scopes: ReadonlyArray<KeyScope>;\n keyType?: ApiKeyType;\n federationPeer?: string;\n sessionId?: string;\n metadata?: Record<string, unknown>;\n /**\n * Set when the authenticating key is in its 7-day deprecation grace\n * (SECURITY.md §2.2). The middleware emits Deprecation/Sunset/\n * Mnemosyne-Key-Deprecated headers from this.\n */\n keyDeprecation?: KeyDeprecation;\n /**\n * Per-key recall sensitivity ceiling carried by the key grant (§5, MED-23).\n * When present it can only LOWER the effective recall ceiling below the\n * process-wide MNEMO_SENSITIVITY_CEILING — never raise it (the effective\n * ceiling is min(envCeiling, keyMax) via SENSITIVITY_ORDER). Undefined for\n * legacy/non-scoped keys → the process-wide ceiling applies unchanged.\n */\n maxSensitivity?: Sensitivity;\n}\n\nexport type AuthResult =\n | { ok: true; context: AuthContext }\n | {\n ok: false;\n code: \"UNAUTHORIZED\" | \"FORBIDDEN\" | \"TOKEN_EXPIRED\" | \"REVOKED\" | \"INVALID\";\n reason: string;\n /**\n * Audit-only. Optional for every `AuthAdapter` — only `ScopedApiKeyAdapter`\n * currently sets these so `authenticateScoped()` can emit `ip_denied` /\n * (future) failure audit entries before the rejection throws.\n */\n workspaceId?: string;\n keyId?: string;\n auditAction?: AuditAction;\n };\n\n// ─── Credentials ──────────────────────────────────────────────────────────────\n\nexport interface InheritedContext {\n workspaceId: string;\n actorId: string;\n actorType: \"agent\" | \"user\" | \"system\";\n scopes: KeyScope[];\n hostSignature?: string;\n}\n\nexport interface RawCredentials {\n bearer?: string;\n apiKey?: string;\n clientCert?: Uint8Array; // mTLS peer certificate (DER)\n inherited?: InheritedContext;\n /** SEC-03: client IP for allowlist enforcement in ScopedApiKeyAdapter */\n clientIp?: string;\n /** Break-glass: TOTP code for mk_admin_ keys (SECURITY.md §2.2). */\n mfaToken?: string;\n}\n\nexport interface AuthOperation {\n action: KeyScope;\n resource?: string;\n workspaceId?: string;\n}\n\n// ─── AuthAdapter port ─────────────────────────────────────────────────────────\n\nexport interface AuthAdapter {\n readonly id: string;\n\n authenticate(credentials: RawCredentials): Promise<AuthResult>;\n authorize(context: AuthContext, operation: AuthOperation): Promise<void>;\n healthCheck(): Promise<HealthStatus>;\n}\n\n// ─── API Key store interface (used by ScopedApiKeyAdapter) ───────────────────\n\nexport interface ApiKeyRecord {\n keyId: string;\n prefix: ApiKeyType;\n hashedSecret: string;\n workspaceId: string;\n scopes: KeyScope[];\n status: \"active\" | \"deprecated\" | \"revoked\";\n expiresAt: Date | null;\n rotatedFromId?: string;\n ipAllowlist?: string[];\n createdAt: Date;\n lastUsedAt?: Date;\n /** Set when status flips to \"deprecated\" during rotation (§3.3). */\n deprecatedAt?: Date | null;\n /** TOTP shared secret (base32) for mk_admin_ break-glass keys. */\n mfaSecret?: string | null;\n /** AB6.2: workspace.is_test flag — populated by store to enable test/prod key isolation. */\n isTest?: boolean;\n /**\n * The platform user who issued the key (mnemo_user.id), when a user-bound\n * caller issued it. Break-glass dual control keys on it, so an mk_admin_ key\n * always carries one.\n */\n userId?: string | null;\n /**\n * Per-key recall sensitivity ceiling grant (§5). When set, it lowers the\n * effective recall ceiling for requests made with this key below the\n * process-wide MNEMO_SENSITIVITY_CEILING (never raises it). Absent on legacy\n * keys → the process-wide ceiling applies unchanged.\n */\n maxSensitivity?: Sensitivity;\n}\n\nexport interface ApiKeyStore {\n lookup(prefix: ApiKeyType, keyId: string): Promise<ApiKeyRecord | null>;\n markUsed(keyId: string, ipAddress: string): Promise<void>;\n revoke(keyId: string, reason: string): Promise<void>;\n /** Newest-first usage history for anomaly detection. */\n recentUsage(keyId: string, limit: number): Promise<KeyUsageEvent[]>;\n /** Flip a key to deprecated with a grace window (rotation step 3). */\n deprecate(keyId: string, deprecatedAt: Date): Promise<void>;\n /** Persist a new key record (rotation step 1); returns nothing. */\n insert(record: ApiKeyRecord): Promise<void>;\n /** Append-only escrow of key METADATA (never the secret) for forensics. */\n escrow(entry: KeyEscrowEntry): Promise<void>;\n}\n\n// ─── Deployment tier ──────────────────────────────────────────────────────────\n\nexport type DeploymentTier = \"personal\" | \"team\" | \"cloud\" | \"embedded\";\n\n// ─── Agent memory access policy (spec §19) ────────────────────────────────────\n\nexport type ApprovalTrigger =\n | \"delete_fact\"\n | \"overwrite_decision\"\n | \"write_entity\"\n | \"cross_agent_read\"\n | \"bulk_export\"\n | \"federation_share\"\n | \"procedural_evolution\"\n | \"task_delegation\";\n\nexport interface SelfEditPolicy {\n enabled: boolean;\n maxWorthDelta?: number;\n}\n\nexport interface AgentMemoryAccess {\n agentId: string;\n workspaceId: string;\n readScopes: SpecScope[];\n writeScopes: SpecScope[];\n selfEdit: SelfEditPolicy;\n taskScopes: {\n canCreate: boolean;\n canDelegate: boolean;\n canDelegateTo: string[];\n };\n limits: {\n maxRecallsPerMinute: number;\n maxWritesPerMinute: number;\n maxSessionsConcurrent: number;\n maxSelfEditsPerSession: number;\n };\n requireApprovalFor: ApprovalTrigger[];\n federationAccess: \"none\" | \"read\" | \"read_write\";\n}\n\n// ─── Injection guard ──────────────────────────────────────────────────────────\n\nexport interface InjectionGuardResult {\n score: number; // 0–1; high = likely injection attempt\n flagged: boolean;\n reason?: string;\n}\n\n// ─── Wave X — Active Security Detection ──────────────────────────────────────\n\n/**\n * Noisy-OR injection score for recall-path text.\n * Aggregates all matched poisoning categories.\n */\nexport interface InjectionScore {\n /** Composite noisy-OR probability in [0, 1]; high = likely injection. */\n score: number;\n flagged: boolean;\n categories: string[];\n}\n\n// ─── Column-level encryption (SECURITY.md §7) ────────────────────────────────\n\n/**\n * Wire format for an AES-256-GCM encrypted field stored in the database.\n * Identified by the sentinel prefix \"enc:v1:\" when serialized to a column.\n */\nexport interface EncryptedField {\n /** AES-256-GCM ciphertext, base64-encoded. */\n ciphertext: string;\n /** GCM IV, base64-encoded (12 bytes). */\n iv: string;\n /** GCM authentication tag, base64-encoded (16 bytes). */\n tag: string;\n /** DEK identifier — used for rotation auditing. */\n dekId: string;\n algorithm: \"AES-256-GCM\";\n}\n\n/**\n * Write-time semantic anomaly score derived from neighbour cosine similarities.\n */\nexport interface AnomalyScore {\n /** Composite anomaly probability in [0, 1]; high = anomalous. */\n score: number;\n flagged: boolean;\n signals: {\n /** Isolation score: 1 − mean(neighbour cosine sims). High = isolated from existing knowledge. */\n distance: number;\n /** Estimated PII density derived from piiRiskScore. */\n piiDensity: number;\n /** Fraction of neighbours in contradiction zone [0.80, 0.97). */\n contradiction: number;\n };\n}\n","// packages/types/src/compositionality.ts\n// Composition rule DSL types and zod parsers.\nimport { z } from \"zod\";\n\n// ── Conditions ────────────────────────────────────────────────────────────────\n\nconst FactKindClause = z.object({\n op: z.literal(\"fact_kind\"),\n kind: z.string().min(1).max(64),\n bind: z.string().regex(/^\\$[a-z][a-z0-9_]*$/i).optional(),\n}).strict();\n\nconst TopicKeyInClause = z.object({\n op: z.literal(\"topic_key_in\"),\n topicKeys: z.array(z.string().min(1).max(200)).min(1).max(32),\n bind: z.string().regex(/^\\$[a-z][a-z0-9_]*$/i).optional(),\n}).strict();\n\nconst TextContainsClause = z.object({\n op: z.literal(\"text_contains\"),\n needle: z.string().min(1).max(500),\n bind: z.string().regex(/^\\$[a-z][a-z0-9_]*$/i).optional(),\n}).strict();\n\nconst RELATION_VERBS = [\n \"related\", \"compatible\", \"scoped\", \"conflicts_with\", \"supersedes\",\n \"not_conflict\", \"derived_from\", \"part_of\", \"member_of\",\n] as const;\n\nconst BIND_RE = /^\\$[a-z][a-z0-9_]*$/i;\n\nconst RelationClause = z.object({\n op: z.literal(\"relation\"),\n from: z.string().regex(BIND_RE),\n to: z.string().regex(BIND_RE),\n verb: z.enum(RELATION_VERBS),\n}).strict();\n\nconst NumberOrBind = z.union([z.number(), z.string().regex(BIND_RE)]);\n\nconst FactValueClause = z.object({\n op: z.literal(\"fact_value\"),\n subject: z.string().regex(BIND_RE),\n predicate: z.string().min(1).max(128),\n valueType: z.enum([\"duration\", \"number\"]),\n compare: z.object({\n lt: NumberOrBind.optional(),\n gt: NumberOrBind.optional(),\n lte: NumberOrBind.optional(),\n gte: NumberOrBind.optional(),\n }).strict().partial().optional(),\n bind: z.string().regex(BIND_RE).optional(),\n}).strict();\n\nconst ConditionClause = z.discriminatedUnion(\"op\", [\n FactKindClause, TopicKeyInClause, TextContainsClause,\n RelationClause, FactValueClause,\n]);\n\nexport const ConditionDslSchema = z.object({\n all: z.array(ConditionClause).min(1).max(8),\n}).strict();\n\nexport type ConditionDsl = z.infer<typeof ConditionDslSchema>;\n\n// ── Actions ───────────────────────────────────────────────────────────────────\n\nconst DeriveFactAction = z.object({\n op: z.literal(\"derive_fact\"),\n statementTemplate: z.string().min(1).max(2000),\n // DSL kind: NOT a valid MnemoFact.kind — stored in metadata.inference.derivedKind.\n // Engine writes kind='other' to mnemo_fact (valid kind) and attribution='inferred'.\n kind: z.string().min(1).max(64).default(\"inferred\"),\n topicKey: z.string().max(200).optional(),\n baseConfidence: z.number().min(0).max(1).default(0.7),\n sensitivity: z.enum([\"public\", \"internal\", \"confidential\", \"restricted\"]).default(\"internal\"),\n type: z.literal(\"fact\").default(\"fact\"),\n}).strict();\n\nconst DeriveWarningAction = z.object({\n op: z.literal(\"derive_warning\"),\n statementTemplate: z.string().min(1).max(2000),\n kind: z.string().min(1).max(64).default(\"inferred\"),\n topicKey: z.string().max(200).optional(),\n baseConfidence: z.number().min(0).max(1).default(0.7),\n sensitivity: z.enum([\"public\", \"internal\", \"confidential\", \"restricted\"]).default(\"internal\"),\n type: z.literal(\"warning\").default(\"warning\"),\n}).strict();\n\nexport const ActionDslSchema = z.discriminatedUnion(\"op\", [DeriveFactAction, DeriveWarningAction]);\nexport type ActionDsl = z.infer<typeof ActionDslSchema>;\n\n// ── Derived Inference (result shape) ─────────────────────────────────────────\n// Defined here (in @mnemo-ai/types) so recall.ts can import it without\n// a forbidden types→core dependency.\n\nexport interface DerivedInference {\n ruleId: string;\n ruleName: string;\n inputFactIds: string[];\n derivedKind: string;\n derivedStatement: string;\n confidence: number;\n type: \"fact\" | \"warning\";\n rationale: string;\n materialisedFactId?: string;\n}\n\n// ── Parsers ───────────────────────────────────────────────────────────────────\n\nexport function parseConditionDsl(raw: unknown): ConditionDsl {\n return ConditionDslSchema.parse(raw);\n}\nexport function parseActionDsl(raw: unknown): ActionDsl {\n return ActionDslSchema.parse(raw);\n}\n","/**\n * Observability types — Wave AC §AC2\n *\n * CognitiveHealthSnapshot gives a high-level view of a workspace's\n * memory health across four key dimensions from spec §28–§34:\n *\n * worthConvergenceRate — fraction of facts whose worth has stabilised\n * (α/(α+β) within ε of previous evaluation).\n * compositionUtilization — ratio of active composition rules that fired\n * at least once in the last 7 days.\n * knowledgeTypeBalance — Shannon entropy over primitive type distribution\n * (fact/decision/episode/entity/…), in bits.\n * proceduralEvolutionDelta — mean score-delta of the last activated prompt\n * version (avgScoreAfter − avgScoreBefore).\n * unitEconomics.roiMultiplier — always null: no measured value of a recall\n * exists (APP-015). Kept for wire compatibility.\n * unitEconomics.costUsdThisMonth — total LLM cost for the billing period.\n * unitEconomics.recallCount — number of recall operations this billing period.\n *\n * All numeric fields are in [0,∞) unless noted; null means the metric\n * could not be computed (e.g. no facts in the workspace yet).\n */\n\nexport interface CognitiveHealthUnitEconomics {\n /** Always null: nothing measures a recall in dollars (APP-015). */\n roiMultiplier: number | null;\n /** Total LLM spend in USD for the current calendar month. */\n costUsdThisMonth: number;\n /** Number of recall operations executed this calendar month. */\n recallCount: number;\n}\n\nexport interface CognitiveHealthSnapshot {\n /** Workspace this snapshot is scoped to. */\n workspaceId: string;\n /** ISO-8601 timestamp when the snapshot was computed. */\n computedAt: string;\n\n /**\n * Fraction [0,1] of active facts whose Beta-Bernoulli worth has\n * stabilised (|α/(α+β) − previous| < 0.01). null if no facts.\n */\n worthConvergenceRate: number | null;\n\n /**\n * Fraction [0,1] of active composition rules that fired at least\n * once in the last 7 days. 0 if no rules exist.\n */\n compositionUtilization: number | null;\n\n /**\n * Shannon entropy (bits) over the distribution of memory primitive\n * types in the workspace. Higher = more diverse memory portfolio.\n * null if workspace has no primitives.\n */\n knowledgeTypeBalance: number | null;\n\n /**\n * Score delta (avgScoreAfter − avgScoreBefore) of the most recently\n * activated prompt version for any agent in this workspace.\n * Positive = procedural improvement. null if no prompt versions exist.\n */\n proceduralEvolutionDelta: number | null;\n\n /** Unit economics for the current billing period. */\n unitEconomics: CognitiveHealthUnitEconomics;\n\n // ── B2.2: 7 additional fields (spec §AC2) ──────────────────────────────────\n\n /**\n * Fraction of sessions that were collapsed due to turn-limit/inactivity\n * (i.e. involuntary collapses / total sessions started).\n * null if no sessions have been started in-process.\n */\n sessionCollapseRate?: number | null;\n\n /**\n * Fraction of reasoning.resolve() calls served from the CoT distillation\n * cache (cache_hit / (cache_hit + execute)).\n * null if no reasoning.resolve calls recorded.\n */\n reasoningCacheHitRate?: number | null;\n\n /**\n * Mean Beta-Bernoulli worth (α/(α+β)) across active facts in the workspace.\n * null if the workspace has no active facts.\n */\n avgMemoryWorth?: number | null;\n\n /**\n * Fraction of recall operations served from the hot (Redis L1) tier\n * (hot / (hot + cold + unified + miss)).\n * null if no recall tier hits recorded.\n */\n hotTierHitRate?: number | null;\n\n /**\n * Per-workspace anticipation accuracy: fraction of pre-staged anticipated\n * memories subsequently recalled in the same session.\n * null if no session for this workspace has collapsed yet.\n */\n anticipationAccuracy?: number | null;\n\n /**\n * Fraction of consolidation jobs that were gated (skipped) rather than\n * merged (skipped / (merged + skipped + failed)).\n * null if no consolidation decisions recorded.\n */\n consolidationGateRate?: number | null;\n\n /**\n * Fraction of consolidation jobs that failed (failed / total).\n * Note: `failed` is a superset of `rolled_back` until the scheduler emits\n * a dedicated `rolled_back` outcome label.\n * null if no consolidation decisions recorded.\n * @remarks FIXME: failed is a superset of rolled_back\n */\n consolidationRollbackRate?: number | null;\n}\n\n// ── MNEMO_ERROR_CODES registry ──────────────────────────────────────────────\n// Canonical error codes for all Mnemosyne v3 error conditions.\n// Used by telemetry spans, structured logs, and error responses.\n\nexport const MNEMO_ERROR_CODES = {\n // Storage errors\n STORAGE_NOT_FOUND: \"mnemo.storage.not_found\",\n STORAGE_CONFLICT: \"mnemo.storage.conflict\",\n STORAGE_CONSTRAINT: \"mnemo.storage.constraint_violation\",\n STORAGE_TIMEOUT: \"mnemo.storage.timeout\",\n // Auth errors\n AUTH_MISSING_KEY: \"mnemo.auth.missing_key\",\n AUTH_EXPIRED_KEY: \"mnemo.auth.expired_key\",\n AUTH_INSUFFICIENT_SCOPE: \"mnemo.auth.insufficient_scope\",\n AUTH_WORKSPACE_MISMATCH: \"mnemo.auth.workspace_mismatch\",\n // Recall errors\n RECALL_BUDGET_EXCEEDED: \"mnemo.recall.budget_exceeded\",\n RECALL_VECTOR_MISSING: \"mnemo.recall.vector_missing\",\n RECALL_UPSTREAM_TIMEOUT: \"mnemo.recall.upstream_timeout\",\n // Composition errors\n COMPOSE_DSL_INVALID: \"mnemo.compose.dsl_invalid\",\n COMPOSE_MAX_FIRINGS: \"mnemo.compose.max_firings_reached\",\n COMPOSE_MATERIALISE_FAIL: \"mnemo.compose.materialise_failed\",\n // Self-edit errors\n SELF_EDIT_BUDGET: \"mnemo.self_edit.budget_exceeded\",\n SELF_EDIT_COOLDOWN: \"mnemo.self_edit.cooldown_active\",\n SELF_EDIT_SCOPE: \"mnemo.self_edit.scope_denied\",\n SELF_EDIT_ABUSE_FLAG: \"mnemo.self_edit.abuse_flagged\",\n SELF_EDIT_WORTH_FROZEN: \"mnemo.self_edit.worth_frozen\",\n // Federation errors\n FED_SIGNATURE_INVALID: \"mnemo.federation.signature_invalid\",\n FED_VERSION_SKEW: \"mnemo.federation.version_skew\",\n FED_QUORUM_UNREACHABLE: \"mnemo.federation.quorum_unreachable\",\n // Procedural errors\n PROC_BUDGET_BELOW_GATE: \"mnemo.procedural.budget_below_gate\",\n PROC_NO_TRAJECTORIES: \"mnemo.procedural.no_trajectories\",\n // General\n RATE_LIMIT: \"mnemo.rate_limit\",\n VALIDATION: \"mnemo.validation\",\n INTERNAL: \"mnemo.internal\",\n} as const;\n\nexport type MnemoErrorCode = typeof MNEMO_ERROR_CODES[keyof typeof MNEMO_ERROR_CODES];\n\n// ── MnemoSpanAttributes ───────────────────────────────────────────────────────\n// Standard attribute names for OpenTelemetry spans emitted by Mnemosyne.\n\nexport interface MnemoSpanAttributes {\n /** Workspace the operation is scoped to. */\n \"mnemo.workspace_id\"?: string;\n /** Agent (actor) the operation was performed on behalf of. */\n \"mnemo.agent_id\"?: string;\n /** Session the operation belongs to, when one is active. */\n \"mnemo.session_id\"?: string;\n /** W3C trace id, propagated across service boundaries. */\n \"mnemo.trace_id\"?: string;\n /** Primitive kind being operated on (fact/episode/entity/…). */\n \"mnemo.kind\"?: string;\n /** Operation being performed. */\n \"mnemo.operation\"?: string;\n /** Surprise/PE score for remember() calls. */\n \"mnemo.pe\"?: number;\n /** Whether the result was served from hot-tier cache. */\n \"mnemo.from_hot_tier\"?: boolean;\n /** Which tier served the result: \"hot\" | \"pointer\" | \"cold\" | \"l3_cache\" | \"none\". */\n \"mnemo.tier_hit\"?: string;\n /** True when the result was served from a cache layer (L3 query cache). */\n \"mnemo.cache_hit\"?: boolean;\n /** Number of hits returned by recall. */\n \"mnemo.hit_count\"?: number;\n /** Number of results returned (spec alias of hit_count for recall). */\n \"mnemo.result_count\"?: number;\n /** Mean worth (α/(α+β) or score fallback) across returned hits. */\n \"mnemo.worth_avg\"?: number;\n /** LLM tokens saved by serving this operation without a model call. */\n \"mnemo.tokens_saved\"?: number;\n /** LLM tokens consumed by this operation. */\n \"mnemo.llm_tokens_used\"?: number;\n /** LLM cost in USD attributed to this operation. */\n \"mnemo.llm_cost_usd\"?: number;\n /** Latency in milliseconds. */\n \"mnemo.latency_ms\"?: number;\n /** Error code from MNEMO_ERROR_CODES. */\n \"mnemo.error_code\"?: MnemoErrorCode;\n /** Rule ID that triggered a composition inference. */\n \"mnemo.rule_id\"?: string;\n /** Number of composition rule firings in a call. */\n \"mnemo.firings\"?: number;\n /** Self-edit action applied. */\n \"mnemo.self_edit.action\"?: string;\n /** Idempotency key for mutating operations. */\n \"mnemo.idempotency_key\"?: string;\n /** Reason the session was collapsed (e.g. \"turn_limit\", \"inactivity\", \"manual\"). */\n \"mnemo.collapse.reason\"?: string;\n /** Number of turns processed in the collapsed session. */\n \"mnemo.collapse.turns\"?: number;\n /** Outcome of a reasoning resolve operation. */\n \"mnemo.reasoning.result\"?: \"cache_hit\" | \"execute\";\n /** Federation peer ID for sync operations. */\n \"mnemo.federation.peer\"?: string;\n /** Plugin name/ID for spans that trace a single named plugin's execution. */\n \"mnemo.plugin.name\"?: string;\n /** Event hook name for spans that dispatch a hook to all active plugins. */\n \"mnemo.plugin.hook\"?: string;\n}\n\n/**\n * Canonical span names emitted by Mnemosyne.\n * Import and use these constants at span-creation sites so dashboards\n * can correlate spans by name without string-matching fragility.\n *\n * `write` is the spec's name (Observability §, line 1718) for the persist\n * span; it is an ALIAS of the live `mnemo.remember` span name (see WP13\n * RECONCILE note). Use MNEMO_SPAN_NAMES.write when referring to the spec\n * concept; the emitted span string remains \"mnemo.remember\".\n */\nexport const MNEMO_SPAN_NAMES = {\n recall: \"mnemo.recall\",\n remember: \"mnemo.remember\",\n /** Spec alias of `remember` (spec calls this span \"mnemo.write\"). */\n write: \"mnemo.remember\",\n sessionCollapse: \"mnemo.session.collapse\",\n reasoningResolve: \"mnemo.reasoning.resolve\",\n federationSync: \"mnemo.federation.sync\",\n /** Auth middleware span — wraps the bearer-token resolution path. */\n auth: \"mnemo.auth\",\n /** Embedding span — wraps embedSingle / embed batch calls. */\n embed: \"mnemo.embed\",\n /** Re-ranking span — wraps RecMem rerank on the cold path. */\n rerank: \"mnemo.rerank\",\n /** Composition span — wraps composeInferences on the cold path. */\n composition: \"mnemo.composition\",\n /** Render span — wraps renderFactsCompact at the call site. */\n render: \"mnemo.render\",\n plugin: (name: string) => `mnemo.plugin.${name}`,\n} as const;\n","// Deterministic, dependency-free text-delta codec for DELTAMEM §16 residual\n// episode trees (MEMORY_IMPROVEMENT.md:1296-1329).\n//\n// A child episode that overlaps its parent stores only the RESIDUAL between the\n// parent's reconstructed narrative and its own. Encoding is line-based: we strip\n// the longest common prefix and longest common suffix of lines, and persist only\n// the differing middle window plus the two anchor counts. Reconstruction splices\n// the residual middle back between the parent's prefix and suffix lines.\n//\n// This module is intentionally free of any runtime dependency so it can live in\n// @mnemo-ai/types — the lowest package depended on by core, adapter-postgres,\n// and the in-memory test adapter. It performs no I/O and is fully deterministic.\n\n/** Magic header marking a residual (prefix/suffix-anchored) payload. */\nexport const DELTA_MAGIC_V1 = \"MNEMO_DELTA_V1\";\n/** Magic header marking a full-text payload (used when a residual would not be smaller). */\nexport const FULL_MAGIC_V1 = \"MNEMO_FULL_V1\";\n\n// Split into lines WITHOUT discarding information: we keep \"\\n\" as the join glue\n// and operate on the array. join(\"\\n\") of split(\"\\n\") is the identity on any\n// string, so prefix/suffix splicing is exact (including blank and trailing lines).\nfunction toLines(s: string): string[] {\n return s.split(\"\\n\");\n}\n\n/**\n * Encode `child` as a residual against `parent`.\n *\n * Format (residual, all parts newline-joined into ONE string):\n * line 0: `MNEMO_DELTA_V1\\t<prefixCount>\\t<suffixCount>`\n * line 1..N: the differing MIDDLE lines of `child`\n *\n * If the residual would not be strictly smaller than a full payload, returns a\n * full payload instead:\n * line 0: `MNEMO_FULL_V1`\n * line 1..N: the full `child` text\n *\n * `applyDelta` inverts whichever form is produced.\n */\nexport function encodeDelta(parent: string, child: string): string {\n const p = toLines(parent);\n const c = toLines(child);\n\n // Longest common prefix of lines.\n let prefix = 0;\n const maxPrefix = Math.min(p.length, c.length);\n while (prefix < maxPrefix && p[prefix] === c[prefix]) prefix++;\n\n // Longest common suffix of lines, not overlapping the matched prefix.\n let suffix = 0;\n const maxSuffix = Math.min(p.length, c.length) - prefix;\n while (\n suffix < maxSuffix &&\n p[p.length - 1 - suffix] === c[c.length - 1 - suffix]\n ) {\n suffix++;\n }\n\n const middle = c.slice(prefix, c.length - suffix);\n const header = `${DELTA_MAGIC_V1}\\t${prefix}\\t${suffix}`;\n const residual = [header, ...middle].join(\"\\n\");\n const full = `${FULL_MAGIC_V1}\\n${child}`;\n\n // Prefer the residual only when it is strictly smaller; otherwise the full\n // payload guarantees correctness with no growth surprise for adversarial input.\n return residual.length < full.length ? residual : full;\n}\n\n/**\n * Reconstruct the child narrative from `parent` and an encoded `delta`.\n *\n * Back-compat: a `delta` that begins with neither magic header is treated as a\n * literal full narrative (legacy rows / raw fixtures written before WP5).\n */\nexport function applyDelta(parent: string, delta: string): string {\n if (delta.startsWith(`${FULL_MAGIC_V1}\\n`)) {\n return delta.slice(FULL_MAGIC_V1.length + 1);\n }\n if (delta === FULL_MAGIC_V1) {\n return \"\";\n }\n if (!delta.startsWith(`${DELTA_MAGIC_V1}\\t`)) {\n // Legacy: deltaContent already holds the full narrative.\n return delta;\n }\n\n const newlineIdx = delta.indexOf(\"\\n\");\n const headerLine = newlineIdx === -1 ? delta : delta.slice(0, newlineIdx);\n const body = newlineIdx === -1 ? \"\" : delta.slice(newlineIdx + 1);\n\n const parts = headerLine.split(\"\\t\");\n const prefix = Number(parts[1]);\n const suffix = Number(parts[2]);\n if (!Number.isInteger(prefix) || !Number.isInteger(suffix)) {\n throw new Error(`applyDelta: malformed ${DELTA_MAGIC_V1} header \"${headerLine}\"`);\n }\n\n const p = toLines(parent);\n // The header had no body line iff the middle window was empty (newlineIdx===-1).\n const middle = newlineIdx === -1 ? [] : toLines(body);\n\n const head = p.slice(0, prefix);\n const tail = suffix === 0 ? [] : p.slice(p.length - suffix);\n return [...head, ...middle, ...tail].join(\"\\n\");\n}\n","/**\n * Canonical EmbeddingSpace identity (§B4.1).\n *\n * Vectors can only be compared when they share the exact same EmbeddingSpace.\n */\nexport interface EmbeddingSpace {\n spaceId: string;\n provider: string;\n model: string;\n modelRevision?: string;\n dimensions: number;\n distanceMetric: \"cosine\" | \"ip\" | \"l2\";\n inputType?: \"document\" | \"query\" | \"symmetric\";\n normalization?: \"l2\" | \"none\";\n dtype?: \"float32\" | \"float16\" | \"int8\";\n preprocessingVersion?: string;\n}\n\nexport type EmbeddingSpaceStatus =\n | \"building\"\n | \"active\"\n | \"dormant\"\n | \"stale\"\n | \"superseded\"\n | \"failed\";\n\n/**\n * Generate a deterministic canonical spaceId string.\n */\nexport function generateSpaceId(space: Omit<EmbeddingSpace, \"spaceId\">): string {\n const parts = [\n space.provider,\n space.model,\n space.modelRevision ?? \"v1\",\n String(space.dimensions),\n space.distanceMetric ?? \"cosine\",\n space.dtype ?? \"float32\",\n ];\n return parts.join(\":\").toLowerCase();\n}\n","// Provenance identity — who/what acted, and on whose behalf.\n//\n// Root cause this fixes: `actorId` was specified as \"the end-user this\n// transaction speaks for\" (see @mnemo-ai/core tx.ts) but got populated with\n// the authenticating API key's own row id, with no way to tell the two\n// apart at read time. Every write path then invented its own coercion\n// between the two meanings (see CLAUDE.md \"Provenance identity\").\n//\n// The fix: three orthogonal fields, always computed together, never as a\n// fallback chain of `a ?? b ?? c`:\n// - actorType: WHAT kind of principal acted (always present)\n// - actorId: WHO acted — a namespaced ActorRef, never a bare id (always present)\n// - userId: the platform account behind the action, when one exists (nullable)\n//\n// actorType/actorId answer \"what credential acted\"; userId answers \"on whose\n// behalf\". They are not alternatives — one never falls back to the other.\n\n/** What kind of principal performed an action. */\nexport type ActorType = \"agent\" | \"user\" | \"system\" | \"federation\";\n\n/** The namespace prefix of an ActorRef — mirrors the `scopeOwner` convention (see primitives.ts). */\nexport type ActorNamespace = \"user\" | \"key\" | \"system\" | \"peer\";\n\n/**\n * A namespaced, parseable actor identifier: `<namespace>:<id>`.\n *\n * | actorType | form | source |\n * |---------------|-----------------------------------------|--------------------------------------|\n * | `user` | `user:<mnemo_user.id>` | key's bound user, or JWT-resolved account |\n * | `agent` | `key:<mnemo_api_keys.id>` | the authenticating key's own row id |\n * | `system` | `system:<component>` | hardcoded per call site (e.g. `system:collapse`) |\n * | `federation` | `peer:<instanceId>` | the remote peer's identity |\n *\n * A bare, un-namespaced string (a raw key id, or the shared `apiKeyPrefix`\n * constant like `\"mns_live_\"`) is NEVER a valid ActorRef — see\n * `parseActorRef`, which rejects both.\n */\nexport type ActorRef = `${ActorNamespace}:${string}`;\n\nexport function formatActorRef(namespace: ActorNamespace, id: string): ActorRef {\n return `${namespace}:${id}`;\n}\n\nconst ACTOR_NAMESPACES: ReadonlySet<string> = new Set<ActorNamespace>([\n \"user\",\n \"key\",\n \"system\",\n \"peer\",\n]);\n\n/**\n * Parse a namespaced ActorRef. Returns null for anything that isn't one —\n * including bare ids and known non-identity constants like an apiKeyPrefix\n * (`mns_live_`, `mk_admin_`, etc.), which must never be mistaken for an\n * ActorRef.\n */\nexport function parseActorRef(value: string): { namespace: ActorNamespace; id: string } | null {\n const idx = value.indexOf(\":\");\n if (idx <= 0) return null;\n const namespace = value.slice(0, idx);\n const id = value.slice(idx + 1);\n if (!id || !ACTOR_NAMESPACES.has(namespace)) return null;\n return { namespace: namespace as ActorNamespace, id };\n}\n\n/**\n * The identity triple every write path must produce, computed in one place\n * (server-side `resolveProvenance()`) — never assembled ad hoc per route via\n * a fallback chain.\n *\n * Not to be confused with `Provenance` in recall.ts, which is the\n * epistemological-origin enum (`\"user_stated\" | \"objective_fact\" | ...`,\n * the `attribution` column) — a different, pre-existing concept. This one is\n * about WHO/WHAT acted; that one is about HOW a memory came to be known.\n */\nexport interface ActorProvenance {\n /** WHAT kind of principal acted. Always present. */\n actorType: ActorType;\n /** WHO acted — namespaced, parseable, never a bare id. Always present. */\n actorId: ActorRef;\n /** The platform account behind the action, when one exists. null otherwise. */\n userId: string | null;\n}\n","// flatten-legacy-dual-core PR9f (design.md D6.5 \"Graph — assembly-in-adapter,\n// traversal-in-core\"). Pure snapshot assembly, zero I/O — mirrors legacy\n// `buildGraphData`'s focus-neighbourhood + meta-count tail exactly\n// (`packages/core/src/graph/query.ts:132-162`).\n//\n// Callers (`GraphRepository` in adapter-postgres, `InMemoryStorageAdapter`\n// here) map their own rows to `GraphNode[]`/`GraphEdge[]` first — including\n// pre-filtering edges to pairs whose both endpoints are in `nodes`, exactly\n// as legacy's `relations.filter(r => nodeIds.has(sourceId) && nodeIds.has(targetId))`\n// does — then share this one assembly step so the focus/meta logic can never\n// duplicate or drift between adapters.\n\nimport type { GraphNode, GraphEdge, GraphSnapshot } from \"./relations.js\";\n\nexport interface AssembleGraphSnapshotOptions {\n /** Restrict the returned snapshot to this node + its 1-hop neighbourhood. */\n focusEntityId?: string;\n}\n\nfunction countMeta(nodes: GraphNode[], edges: GraphEdge[]): GraphSnapshot[\"meta\"] {\n return {\n entityCount: nodes.filter((n) => n.kind === \"entity\").length,\n episodeCount: nodes.filter((n) => n.kind === \"episode\").length,\n decisionCount: nodes.filter((n) => n.kind === \"decision\").length,\n relationCount: edges.length,\n };\n}\n\n/**\n * An entity's mentions are the facts linked to it (its `factCount`) plus the\n * episodes related to it. Both come from rows the caller can already see, so\n * the count never reflects anything above the ceiling. The stored\n * `mention_count` column is never maintained, so it is not read.\n */\nfunction withMentionCounts(nodes: GraphNode[], edges: GraphEdge[]): GraphNode[] {\n const episodes = new Set(nodes.filter((n) => n.kind === \"episode\").map((n) => n.id));\n const episodesByNode = new Map<string, Set<string>>();\n const link = (nodeId: string, episodeId: string) => {\n const seen = episodesByNode.get(nodeId) ?? new Set<string>();\n seen.add(episodeId);\n episodesByNode.set(nodeId, seen);\n };\n for (const e of edges) {\n // A derived \"mentions\" edge restates the episode's facts, already in factCount; counting it\n // again would also part the graph from GET /entities (countEntityMentions).\n if (e.provenance === \"episode_facts\") continue;\n if (episodes.has(e.source)) link(e.target, e.source);\n if (episodes.has(e.target)) link(e.source, e.target);\n }\n return nodes.map((n) =>\n n.kind === \"entity\"\n ? { ...n, mentionCount: n.factCount + (episodesByNode.get(n.id)?.size ?? 0) }\n : n\n );\n}\n\nexport function assembleGraphSnapshot(\n allNodes: GraphNode[],\n edges: GraphEdge[],\n opts: AssembleGraphSnapshotOptions = {}\n): GraphSnapshot {\n // Counted over the whole graph, before a focus narrows what is returned.\n const nodes = withMentionCounts(allNodes, edges);\n if (opts.focusEntityId) {\n const focus = opts.focusEntityId;\n const neighborIds = new Set<string>([focus]);\n for (const e of edges) {\n if (e.source === focus) neighborIds.add(e.target);\n if (e.target === focus) neighborIds.add(e.source);\n }\n const focusNodes = nodes.filter((n) => neighborIds.has(n.id));\n const focusEdges = edges.filter((e) => neighborIds.has(e.source) && neighborIds.has(e.target));\n return { nodes: focusNodes, edges: focusEdges, meta: countMeta(focusNodes, focusEdges) };\n }\n\n return { nodes, edges, meta: countMeta(nodes, edges) };\n}\n","import type {\n AuditActivity,\n AuditFeedStats,\n HealthSnapshot,\n HealthSnapshotDay,\n SessionStats,\n} from \"./ports.js\";\n\n/** `days` UTC day keys (`YYYY-MM-DD`) ending today, oldest first. */\nexport function utcDayKeys(days: number, now = Date.now()): string[] {\n const today = Date.parse(new Date(now).toISOString().slice(0, 10));\n return Array.from({ length: days }, (_, i) =>\n new Date(today - (days - 1 - i) * 86_400_000).toISOString().slice(0, 10)\n );\n}\n\n/**\n * Shared by the Postgres repository and the in-memory twin, so the two never drift:\n * session rows grouped by (start day, status), and the window's episodes with their\n * readable linked-fact count, become {@link SessionStats}.\n */\nexport function tallySessionStats(\n days: number,\n sessions: Array<{ day: string; status: string; n: number; collapsed: number; turns: number }>,\n episodes: Array<{ topics: string[]; facts: number }>\n): SessionStats {\n const byDay = new Map(\n utcDayKeys(days).map((day) => [day, { day, active: 0, collapsed: 0, archived: 0 }])\n );\n let n = 0;\n let collapsed = 0;\n let turns = 0;\n for (const r of sessions) {\n n += r.n;\n collapsed += r.collapsed;\n turns += r.turns;\n const d = byDay.get(r.day);\n if (d && (r.status === \"active\" || r.status === \"collapsed\" || r.status === \"archived\"))\n d[r.status] += r.n;\n }\n const topics = new Map<string, number>();\n for (const e of episodes)\n for (const t of new Set(e.topics)) topics.set(t, (topics.get(t) ?? 0) + 1);\n const facts = episodes.reduce((sum, e) => sum + e.facts, 0);\n return {\n days: [...byDay.values()],\n totals: {\n sessions: n,\n collapsed,\n avgTurns: n > 0 ? turns / n : null,\n episodes: episodes.length,\n factsPerEpisode: episodes.length > 0 ? facts / episodes.length : null,\n },\n topics: [...topics]\n .sort((a, b) => b[1] - a[1] || (a[0] < b[0] ? -1 : 1))\n .slice(0, 5)\n .map(([topic, count]) => ({ topic, count })),\n };\n}\n\n/** Shared by the Postgres repository and the twin: (day, action) groups → {@link AuditActivity}. */\nexport function tallyAuditActivity(\n days: number,\n groups: Array<{ day: string; action: string; n: number }>,\n lastAt: Record<string, string>\n): AuditActivity {\n const perDay = new Map(utcDayKeys(days).map((day) => [day, 0]));\n const byAction = new Map<string, number>();\n for (const g of groups) {\n if (perDay.has(g.day)) perDay.set(g.day, perDay.get(g.day)! + g.n);\n byAction.set(g.action, (byAction.get(g.action) ?? 0) + g.n);\n }\n return {\n days: [...perDay].map(([day, count]) => ({ day, count })),\n byAction: [...byAction]\n .sort((a, b) => b[1] - a[1] || (a[0] < b[0] ? -1 : 1))\n .map(([action, count]) => ({ action, count })),\n lastAt,\n };\n}\n\n/** Shared by the repository and the twin: each day's latest snapshot → {@link HealthSnapshotDay}. */\nexport function tallyHealthSnapshots(\n days: number,\n latestByDay: Map<\n string,\n Pick<\n HealthSnapshot,\n | \"factCountActive\"\n | \"factCountEmbedded\"\n | \"factCountUnembedded\"\n | \"factsWithZeroHits\"\n | \"recallHitRate30d\"\n | \"extractionJobsFailed7d\"\n >\n >\n): HealthSnapshotDay[] {\n return utcDayKeys(days).map((day) => {\n const s = latestByDay.get(day);\n if (!s)\n return {\n day,\n recallHitRate30d: null,\n zeroHitShare: null,\n embeddedShare: null,\n failedJobs7d: null,\n };\n const indexable = s.factCountEmbedded + s.factCountUnembedded;\n return {\n day,\n recallHitRate30d: s.recallHitRate30d,\n zeroHitShare: s.factCountActive > 0 ? s.factsWithZeroHits / s.factCountActive : null,\n embeddedShare: indexable > 0 ? s.factCountEmbedded / indexable : null,\n failedJobs7d: s.extractionJobsFailed7d,\n };\n });\n}\n\n/** Shared by the repository and the twin: (day, actor kind) groups → {@link AuditFeedStats}. */\nexport function tallyAuditFeedStats(\n days: number,\n groups: Array<{ day: string; actorKind: \"user\" | \"system\"; n: number }>\n): AuditFeedStats {\n const byDay = new Map(utcDayKeys(days).map((day) => [day, { day, user: 0, system: 0 }]));\n const totals = { user: 0, system: 0 };\n for (const g of groups) {\n const d = byDay.get(g.day);\n if (!d) continue;\n d[g.actorKind] += g.n;\n totals[g.actorKind] += g.n;\n }\n return { days: [...byDay.values()], totals };\n}\n","// Recallable-kind registry — the single source of truth for which primitive\n// kinds are indexed on write (embedding + vector-index entry) and therefore\n// retrievable through memory_recall / memory_search, and exactly what text\n// is projected into that index for each kind.\n//\n// make-primitives-recallable (design.md D1), extended by P65: nine kinds are\n// recallable today — every primitive except `entity`, which has its own\n// cosine arm (findSimilarEntities) outside this registry. A default recall\n// reaches seven kinds (DEFAULT_RECALL_KINDS plus entities); `kinds` reaches\n// all ten. Adding a kind is a RECALLABLE_KINDS entry, a\n// PRIMITIVE_TEXT_PROJECTION entry, its embedding/text_lemmatized columns, a\n// DEFAULT_RECALL_KINDS decision and a backfill run.\n//\n// Zero infrastructure imports — enforced by `__tests__/purity.test.ts`.\n\nimport type { PrimitiveKind } from \"./primitives.js\";\n\n/**\n * Primitive kinds whose write path is guaranteed to produce a `vector_upsert`\n * outbox entry in the same transaction that persists the row (spec.md\n * Requirement 1). A kind NOT in this set is persisted but never indexed —\n * \"write-only memory\", the exact defect this change fixes for `decision`.\n */\nexport const RECALLABLE_KINDS = [\n \"fact\",\n \"decision\",\n \"strategy\",\n \"workflow\",\n \"skill\",\n \"episode\",\n \"task\",\n \"event\",\n \"reasoning\",\n] as const;\n\nexport type RecallableKind = (typeof RECALLABLE_KINDS)[number];\n\n/**\n * Kinds `recallCold` searches when a caller supplies no `RecallQuery.kinds`\n * filter (spec.md Requirement 4 / design.md D4 — conservatism lives in the\n * damping/gating parameters, not in an opt-out here). Defined as its own\n * export, distinct from RECALLABLE_KINDS, because the two lists are allowed\n * to diverge later: a kind can become recallable (indexed on write) before\n * it ships default-on in recall results.\n */\nexport const DEFAULT_RECALL_KINDS: readonly RecallableKind[] = [\n \"fact\",\n \"decision\",\n \"strategy\",\n \"workflow\",\n \"skill\",\n \"episode\",\n];\n\n/**\n * The three kinds that are INDEXED but not returned by default. Kept as its own\n * export so the split is stated once and readable, rather than inferred by\n * diffing two lists.\n *\n * `task` and `event` are operational records, not knowledge: a cancelled ticket\n * or a webhook delivery surfacing on an unrelated question is noise, and noise\n * in a recall budget costs a real answer its slot. `reasoning` is a stored\n * chain-of-thought — valuable when you ask for it (\"how did we conclude X?\"),\n * and misleading when it arrives unbidden, because a discarded line of\n * reasoning reads exactly like a conclusion.\n *\n * All three ARE reachable: `RecallQuery.kinds` overrides this entirely, so an\n * agent that wants them asks for them.\n */\nexport const NON_DEFAULT_RECALLABLE_KINDS: readonly RecallableKind[] = [\n \"task\",\n \"event\",\n \"reasoning\",\n];\n\n/**\n * P65 wave 1 — why `strategy` and `workflow` went first, and why they are\n * default-on rather than merely indexed.\n *\n * They are reusable heuristics and processes: \"when X, do Y\" and \"here is how\n * we do Z\". That is precisely the content an agent benefits from finding\n * WITHOUT having been told to look, which is what default-on means. A `task` or\n * an `event` surfacing on every unrelated recall is noise — those are next, and\n * the plan is to index them without defaulting them, which is the distinction\n * `RECALLABLE_KINDS` vs `DEFAULT_RECALL_KINDS` exists to express and which was\n * unused until now (the two lists were identical).\n *\n * What the backlog under-estimated: adding a kind is NOT only a registry entry.\n * Of the seven write-only kinds, only `episode`, `skill`, `strategy` and\n * `reasoning` had an `embedding` column at all, and NONE had `text_lemmatized`.\n * `workflow`, `task` and `event` had neither. Migration 0033 gave these two what\n * recall needs; the remaining five each still need theirs.\n */\n\n/** Narrows `kind` to `RecallableKind` when it is one of RECALLABLE_KINDS. */\nexport function isRecallableKind(kind: PrimitiveKind): kind is RecallableKind {\n return (RECALLABLE_KINDS as readonly string[]).includes(kind);\n}\n\n/**\n * Declares exactly which fields of a primitive's row are embedded/indexed\n * for a given recallable kind, and how they are joined into one text blob.\n * `separator` is inserted only between fields that are actually present\n * (non-empty strings) — a missing/empty field is skipped, never emitted as\n * the literal string `\"undefined\"`.\n */\nexport interface TextProjection {\n readonly fields: readonly string[];\n readonly separator: string;\n}\n\n/**\n * Per-kind text projection — the single source of truth for \"what exactly\n * gets embedded\" for each recallable kind. Replaces the three previously\n * hardcoded `title + \" \" + body` sites for decisions\n * (`DecisionRepository.ts:57`, `:121`, `EmbeddingRepository.ts:16`); all\n * three now derive from this constant instead of duplicating the join.\n */\nexport const PRIMITIVE_TEXT_PROJECTION: Record<RecallableKind, TextProjection> = {\n fact: { fields: [\"statement\"], separator: \" \" },\n decision: { fields: [\"title\", \"body\"], separator: \" \" },\n // The trigger→action pair IS the heuristic; either half alone is\n // unsearchable. \"when the build goes red\" means nothing without what to do\n // about it, and \"re-run with --no-cache\" means nothing without when.\n strategy: { fields: [\"trigger\", \"action\"], separator: \" \" },\n // `description` is optional on MnemoWorkflow, and projectPrimitiveText skips\n // empty fields rather than emitting the literal \"undefined\", so a\n // name-only workflow still projects cleanly.\n workflow: { fields: [\"name\", \"description\"], separator: \" \" },\n // The template IS the skill; the name alone is a label.\n skill: { fields: [\"name\", \"promptTemplate\"], separator: \" \" },\n // Matches the createEpisode producer's text-form outbox payload, so a §36\n // model migration re-embeds the same text the lexical column indexes.\n episode: { fields: [\"title\", \"narrative\"], separator: \" \" },\n task: { fields: [\"title\", \"description\"], separator: \" \" },\n event: { fields: [\"name\", \"description\"], separator: \" \" },\n reasoning: { fields: [\"question\", \"conclusion\"], separator: \" \" },\n};\n\n// ─── Embedding widths ─────────────────────────────────────────────────────────\n\n/**\n * The vector widths this schema physically supports — the single source of\n * truth, replacing \"whatever positive integer someone typed\".\n *\n * These four are not a preference, they are what the database has tables for:\n * `mnemo_fact_embeddings_1024 / _1536 / _2048 / _4096`\n * (`adapter-postgres/src/schema/vector_space.ts`), plus the dimension-scoped\n * HNSW indexes migration 0010 builds over them.\n *\n * P117 is why this constant exists. `MNEMO_EMBED_DIMENSIONS` accepted any\n * positive integer, and `mnemo_fact.embedding` is an unconstrained `halfvec`,\n * so a workspace configured at 768 wrote facts perfectly well — and could never\n * delete them, because `archiveFact()` copies the row into a table that WAS\n * pinned at 1536. Data you can create and cannot forget. The archive column is\n * unconstrained now (migration 0032), but the wider point stands: a width with\n * no index behind it is a silent performance cliff, and the place to refuse it\n * is the moment it is configured or written — not three operations later, in an\n * error message at the end of an 8 KB SQL dump.\n *\n * Adding a width means adding its table and index first. This list follows the\n * schema; it never leads it.\n */\nexport const SUPPORTED_EMBED_DIMENSIONS = [1024, 1536, 2048, 4096] as const;\n\nexport type SupportedEmbedDimension = (typeof SUPPORTED_EMBED_DIMENSIONS)[number];\n\n/** Narrows `n` to a width the schema has a table and an index for. */\nexport function isSupportedEmbedDimension(n: number): n is SupportedEmbedDimension {\n return (SUPPORTED_EMBED_DIMENSIONS as readonly number[]).includes(n);\n}\n\n/**\n * Throws unless `n` is a supported width. `context` names the caller so the\n * message says which knob to turn — the failure this replaces surfaced as\n * `expected 1536 dimensions, not 768` from deep inside a Drizzle insert, which\n * named neither the setting nor the fact.\n */\nexport function assertSupportedEmbedDimension(n: number, context: string): void {\n if (!isSupportedEmbedDimension(n)) {\n throw new Error(\n `${context}: unsupported embedding width ${n}. ` +\n `This schema has vector tables and indexes only for ` +\n `${SUPPORTED_EMBED_DIMENSIONS.join(\", \")}. ` +\n `Pick an embedding model with one of those widths (or add the table, ` +\n `index and migration for ${n} first).`\n );\n }\n}\n\n/**\n * Joins a recallable kind's declared fields out of `row` into the one text blob\n * that gets embedded and lexically indexed. Pure.\n *\n * A missing or non-string field is skipped rather than emitted as the literal\n * `\"undefined\"` — which matters for optional projected fields like\n * `workflow.description`: a name-only workflow must index as its name, not as\n * `\"deploy undefined\"`.\n *\n * P65 moved this here from `@mnemo-ai/core`. It is a pure function over\n * PRIMITIVE_TEXT_PROJECTION, and the in-memory adapter in `types/testing` needs\n * it to satisfy the same write contract the real adapters do — types cannot\n * import from core, so a helper living in core made the double structurally\n * unable to mirror the thing it doubles. Core re-exports it, so every existing\n * import keeps working.\n */\nexport function projectPrimitiveText(kind: RecallableKind, row: Record<string, unknown>): string {\n const projection = PRIMITIVE_TEXT_PROJECTION[kind];\n return projection.fields\n .map((field) => row[field])\n .filter((value): value is string => typeof value === \"string\" && value.length > 0)\n .join(projection.separator);\n}\n","import { z } from \"zod\";\n\n// zod's own date regex (calendar-aware, leap years), without the anchors.\nconst DATE = z.regexes.date.source.slice(1, -1);\nconst TIME = \"(?:[01]\\\\d|2[0-3]):[0-5]\\\\d(?::[0-5]\\\\d(?:\\\\.\\\\d+)?)?\";\nconst OFFSET = \"[+-](?:[01]\\\\d|2[0-3]):[0-5]\\\\d\";\n\nconst UTC_ONLY = new RegExp(`^${DATE}T(?:${TIME}(?:Z))$`);\nconst WITH_OFFSET = new RegExp(`^${DATE}T(?:${TIME}(?:Z|(${OFFSET})))$`);\n\n/**\n * ISO 8601 date-time for request inputs. Seconds and fractions are optional\n * (`2026-08-01T09:00Z`, `…T09:00:00Z`, `…T09:00:00.000Z`): the set\n * `z.string().datetime()` accepted before zod 4.5 made seconds mandatory.\n * Same issue (`invalid_format`, format `datetime`), same JSON Schema\n * (`format: date-time`). Responses keep zod's strict `datetime()`.\n */\nexport function isoDateTimeInput(opts: { offset?: boolean } = {}) {\n return z.stringFormat(\"datetime\", opts.offset ? WITH_OFFSET : UTC_ONLY);\n}\n","import { createHash } from \"node:crypto\";\n\nexport const HARNESS_PROTOCOL_VERSION = 1 as const;\nexport const HARNESS_CHUNK_VERSION = 1 as const;\nexport const HARNESS_MAX_BATCH_EVENTS = 100;\nexport const HARNESS_MAX_BATCH_BYTES = 1024 * 1024;\nexport const HARNESS_MAX_MESSAGE_BYTES = 64 * 1024;\nexport const HARNESS_MAX_CHUNKS_PER_MESSAGE = 256;\nexport const HARNESS_MAX_IDENTITY_BYTES = 512;\nexport const HARNESS_CLOSE_GRACE_MS = 5_000;\nexport const HARNESS_MAX_GENERATION = 2_147_483_647;\nexport const HARNESS_MAX_ENQUEUE_SEQUENCE = Number.MAX_SAFE_INTEGER;\n\nexport interface HarnessTurnAppendChunk {\n version: typeof HARNESS_CHUNK_VERSION;\n chunkIndex: number;\n chunkCount: number;\n messageContentHash: string;\n}\n\nexport interface HarnessTerminalMember {\n type: \"M\" | \"L\";\n hostMessageId: string;\n role: \"user\" | \"assistant\";\n contentHash: string;\n}\n\nexport function canonicalJson(value: unknown): string {\n if (value === null || typeof value === \"string\" || typeof value === \"boolean\") {\n return JSON.stringify(value);\n }\n if (typeof value === \"number\") {\n if (!Number.isFinite(value) || !Number.isSafeInteger(value)) {\n throw new TypeError(\"Canonical JSON supports only safe integer numbers\");\n }\n return JSON.stringify(value);\n }\n if (Array.isArray(value)) {\n return `[${value.map((item) => canonicalJson(item)).join(\",\")}]`;\n }\n if (typeof value === \"object\") {\n const object = value as Record<string, unknown>;\n return `{${Object.keys(object)\n .sort()\n .map((key) => `${JSON.stringify(key)}:${canonicalJson(object[key])}`)\n .join(\",\")}}`;\n }\n throw new TypeError(`Canonical JSON does not support ${typeof value}`);\n}\n\nexport function sha256Hex(value: string | Uint8Array): string {\n return createHash(\"sha256\").update(value).digest(\"hex\");\n}\n\nfunction encodeDigestField(value: string): Buffer {\n const bytes = Buffer.from(value, \"utf8\");\n const length = Buffer.allocUnsafe(4);\n length.writeUInt32BE(bytes.length);\n return Buffer.concat([length, bytes]);\n}\n\nexport function computeTerminalDigestV1(members: readonly HarnessTerminalMember[]): string {\n const identities = new Set<string>();\n const encoded = members.map((member) => {\n const identity = member.hostMessageId;\n if (Buffer.byteLength(identity, \"utf8\") > HARNESS_MAX_IDENTITY_BYTES) {\n throw new Error(`Terminal member identity exceeds ${HARNESS_MAX_IDENTITY_BYTES} UTF-8 bytes`);\n }\n if (identities.has(identity)) throw new Error(\"Duplicate terminal member\");\n identities.add(identity);\n\n return {\n type: Buffer.from(member.type, \"utf8\"),\n hostMessageId: encodeDigestField(member.hostMessageId),\n member: Buffer.concat([\n Buffer.from(member.type, \"utf8\"),\n encodeDigestField(member.hostMessageId),\n encodeDigestField(member.role),\n encodeDigestField(member.contentHash),\n ]),\n };\n });\n\n encoded.sort((left, right) => {\n const typeOrder = Buffer.compare(left.type, right.type);\n return typeOrder === 0 ? Buffer.compare(left.hostMessageId, right.hostMessageId) : typeOrder;\n });\n\n return sha256Hex(Buffer.concat(encoded.map(({ member }) => member)));\n}\n\nexport { classifyTurnOrigin, TURN_ORIGINS } from \"./session.js\";\nexport type { TurnOrigin } from \"./session.js\";\n","import { z } from \"zod\";\nimport type { Sensitivity } from \"./common.js\";\nimport { isoDateTimeInput } from \"./datetime.js\";\nimport {\n HARNESS_CHUNK_VERSION,\n HARNESS_MAX_BATCH_BYTES,\n HARNESS_MAX_BATCH_EVENTS,\n HARNESS_MAX_CHUNKS_PER_MESSAGE,\n HARNESS_MAX_ENQUEUE_SEQUENCE,\n HARNESS_MAX_GENERATION,\n HARNESS_MAX_IDENTITY_BYTES,\n HARNESS_MAX_MESSAGE_BYTES,\n HARNESS_PROTOCOL_VERSION,\n canonicalJson,\n sha256Hex,\n} from \"./harness-runtime.js\";\nimport type { ActorRef, ActorType } from \"./provenance.js\";\n\nexport * from \"./harness-runtime.js\";\n\nconst HASH_PATTERN = /^[0-9a-f]{64}$/;\nconst NON_EMPTY_STRING = z.string().min(1);\nconst IDENTITY_STRING = NON_EMPTY_STRING.refine(\n (value) => Buffer.byteLength(value, \"utf8\") <= HARNESS_MAX_IDENTITY_BYTES,\n `Identity exceeds ${HARNESS_MAX_IDENTITY_BYTES} UTF-8 bytes`\n);\nconst GENERATION = z.number().int().nonnegative().max(HARNESS_MAX_GENERATION);\nconst ENQUEUE_SEQUENCE = z.number().int().positive().max(HARNESS_MAX_ENQUEUE_SEQUENCE);\nconst occurredAtSchema = isoDateTimeInput({ offset: true });\n\nexport class HarnessPayloadLimitError extends Error {\n override readonly name = \"HarnessPayloadLimitError\";\n\n constructor(\n readonly limit: \"batch\" | \"message\",\n readonly maxBytes: number,\n readonly actualBytes: number\n ) {\n super(`Harness ${limit} exceeds ${maxBytes} bytes`);\n }\n}\n\nconst eventBase = {\n eventId: IDENTITY_STRING,\n host: z.enum([\"opencode\", \"claude-code\", \"codex\"]),\n hostSessionId: IDENTITY_STRING,\n clientInstanceId: IDENTITY_STRING,\n enqueueSequence: ENQUEUE_SEQUENCE,\n occurredAt: occurredAtSchema,\n payloadHash: z.string().regex(HASH_PATTERN),\n normalizationVersion: z.literal(1),\n};\n\nconst harnessTurnAppendChunkSchema = z\n .strictObject({\n version: z.literal(HARNESS_CHUNK_VERSION),\n chunkIndex: z.number().int().nonnegative().max(HARNESS_MAX_CHUNKS_PER_MESSAGE - 1),\n chunkCount: z.number().int().min(2).max(HARNESS_MAX_CHUNKS_PER_MESSAGE),\n messageContentHash: z.string().regex(HASH_PATTERN),\n })\n .refine((chunk) => chunk.chunkIndex < chunk.chunkCount, {\n message: \"chunkIndex must be less than chunkCount\",\n });\n\nconst harnessEventSchema = z.discriminatedUnion(\"type\", [\n z.strictObject({\n ...eventBase,\n type: z.literal(\"session.start\"),\n requestedGeneration: GENERATION.optional(),\n sensitivity: z.enum([\"public\", \"internal\"]).optional(),\n metadata: z.record(z.string(), z.string()).optional(),\n }),\n z.strictObject({\n ...eventBase,\n type: z.literal(\"turn.append\"),\n sourceGeneration: GENERATION,\n hostMessageId: IDENTITY_STRING,\n supersedesSourceMessageId: IDENTITY_STRING.optional(),\n role: z.enum([\"user\", \"assistant\"]),\n content: z.string(),\n contentHash: z.string().regex(HASH_PATTERN),\n turnOrigin: z\n .enum([\n \"human\",\n \"agent_message\",\n \"task_notification\",\n \"pasted_content\",\n \"assistant\",\n \"unknown\",\n ])\n .optional(),\n turnOriginEvidence: z.string().max(256).optional(),\n chunk: harnessTurnAppendChunkSchema.optional(),\n }),\n z.strictObject({\n ...eventBase,\n type: z.literal(\"turn.retract\"),\n sourceGeneration: GENERATION,\n hostMessageId: IDENTITY_STRING,\n reason: z.enum([\"superseded\", \"branch_removed\"]),\n }),\n z.strictObject({\n ...eventBase,\n type: z.literal(\"sequence.loss\"),\n sourceGeneration: GENERATION,\n reason: z.enum([\"capacity\", \"invalid_payload\", \"permanent_rejection\"]),\n lostEventType: z.enum([\"turn.append\", \"turn.retract\"]),\n lostHostMessageId: IDENTITY_STRING,\n lostRole: z.enum([\"user\", \"assistant\"]),\n lostContentHash: z.string().regex(HASH_PATTERN),\n }),\n z.strictObject({\n ...eventBase,\n type: z.literal(\"event.cancel\"),\n sourceGeneration: GENERATION,\n targetEventId: IDENTITY_STRING,\n reason: z.enum([\"generation_redirect\", \"terminal_rebuild\"]),\n }),\n z.strictObject({\n ...eventBase,\n type: z.literal(\"session.end\"),\n sourceGeneration: GENERATION,\n reason: z.enum([\"host_end\", \"host_delete\", \"inactivity\"]),\n finalMessageSetDigest: z.string().regex(HASH_PATTERN),\n maxEnqueueSequence: ENQUEUE_SEQUENCE,\n }),\n]);\n\nconst harnessBatchV1Schema = z.strictObject({\n protocolVersion: z.literal(HARNESS_PROTOCOL_VERSION),\n expectedWorkspaceId: IDENTITY_STRING,\n clientInstanceId: IDENTITY_STRING,\n events: z.array(harnessEventSchema).max(HARNESS_MAX_BATCH_EVENTS),\n});\n\nconst harnessProbeV1Schema = z.strictObject({\n protocolVersion: z.literal(HARNESS_PROTOCOL_VERSION),\n expectedWorkspaceId: IDENTITY_STRING,\n clientInstanceId: IDENTITY_STRING,\n});\n\nexport type HarnessEvent = z.infer<typeof harnessEventSchema>;\nexport type HarnessBatchV1 = z.infer<typeof harnessBatchV1Schema>;\nexport type HarnessProbeV1 = z.infer<typeof harnessProbeV1Schema>;\n\nexport interface HarnessEventAck {\n eventId: string;\n status: \"accepted\" | \"duplicate\" | \"rejected\";\n retryable: boolean;\n code?: string;\n sessionId?: string;\n effectiveGeneration?: number;\n}\n\nexport interface HarnessBatchAckV1 {\n protocolVersion: typeof HARNESS_PROTOCOL_VERSION;\n workspaceId: string;\n acknowledgements: HarnessEventAck[];\n}\n\nexport interface HarnessProbeAckV1 {\n protocolVersion: typeof HARNESS_PROTOCOL_VERSION;\n workspaceId: string;\n available: boolean;\n limits?: {\n maxBatchEvents: number;\n maxBatchBytes: number;\n maxMessageBytes: number;\n };\n code?: string;\n}\n\nexport interface ManagedSessionProvenance {\n trafficOrigin?: import(\"./session.js\").TrafficOrigin;\n actorId: ActorRef;\n actorType: ActorType;\n userId: string | null;\n sensitivityCeiling: Sensitivity;\n}\n\nexport type HarnessSemanticErrorCode =\n | \"payload_hash_mismatch\"\n | \"content_hash_mismatch\"\n | \"future_timestamp\"\n | \"terminal_sequence_mismatch\";\n\nexport function computeHarnessPayloadHash(event: HarnessEvent): string {\n const { payloadHash: _payloadHash, ...body } = event;\n return sha256Hex(canonicalJson(body));\n}\n\nexport function validateHarnessEventSemantics(\n event: HarnessEvent,\n receivedAt: Date\n): HarnessSemanticErrorCode | null {\n if (computeHarnessPayloadHash(event) !== event.payloadHash) return \"payload_hash_mismatch\";\n if (event.type === \"turn.append\" && sha256Hex(event.content) !== event.contentHash) {\n return \"content_hash_mismatch\";\n }\n if (event.type === \"session.end\" && event.enqueueSequence !== event.maxEnqueueSequence + 1) {\n return \"terminal_sequence_mismatch\";\n }\n if (Date.parse(event.occurredAt) > receivedAt.getTime() + 24 * 60 * 60 * 1000) {\n return \"future_timestamp\";\n }\n return null;\n}\n\nexport function parseHarnessBatchV1(input: unknown): HarnessBatchV1 {\n const serialized = typeof input === \"string\" ? input : JSON.stringify(input);\n if (serialized !== undefined) {\n const serializedBytes = Buffer.byteLength(serialized, \"utf8\");\n if (serializedBytes > HARNESS_MAX_BATCH_BYTES) {\n throw new HarnessPayloadLimitError(\"batch\", HARNESS_MAX_BATCH_BYTES, serializedBytes);\n }\n }\n\n const batch = harnessBatchV1Schema.parse(typeof input === \"string\" ? JSON.parse(input) : input);\n for (const event of batch.events) {\n if (event.clientInstanceId !== batch.clientInstanceId) {\n throw new Error(\"Event clientInstanceId must match the batch clientInstanceId\");\n }\n if (event.type === \"turn.append\") {\n const messageBytes = Buffer.byteLength(event.content, \"utf8\");\n if (messageBytes > HARNESS_MAX_MESSAGE_BYTES) {\n throw new HarnessPayloadLimitError(\"message\", HARNESS_MAX_MESSAGE_BYTES, messageBytes);\n }\n }\n }\n return batch;\n}\n\nexport function parseHarnessProbeV1(input: unknown): HarnessProbeV1 {\n return harnessProbeV1Schema.parse(input);\n}\nexport type ManagedCollapseCommitResult =\n | {\n status: \"collapsed\";\n operationId: string;\n sessionId: string;\n episodeId: string;\n factIds: string[];\n decisionIds: string[];\n strategyIds: string[];\n rejectedCount: number;\n }\n | {\n status: \"archived\";\n operationId: string;\n sessionId: string;\n reason: import(\"./session.js\").ManagedArchiveReason;\n };\n","/**\n * Typed storage failures that a caller is expected to turn into a 4xx instead\n * of a 500. Adapters throw these for conditions the CLIENT caused (a name that\n * is already taken, a lineage target that does not exist), so the HTTP layer\n * never has to parse driver error text.\n */\n\n/** A referenced row does not exist in this workspace (or is not visible to the caller). */\nexport class StorageNotFoundError extends Error {\n readonly code = \"not_found\" as const;\n constructor(message: string) {\n super(message);\n this.name = \"StorageNotFoundError\";\n }\n}\n\n/** The write conflicts with the current state: a live row already owns the key, or the row was already closed. */\nexport class StorageConflictError extends Error {\n readonly code = \"conflict\" as const;\n constructor(message: string) {\n super(message);\n this.name = \"StorageConflictError\";\n }\n}\n\n/** The input is structurally invalid for the graph (self-loop, repeated member, wrong kind). */\nexport class StorageValidationError extends Error {\n readonly code = \"invalid\" as const;\n constructor(message: string) {\n super(message);\n this.name = \"StorageValidationError\";\n }\n}\n","/**\n * P135: the scope_ref values a read filter accepts — `scopeRef` plus the other\n * spellings of the same project (`scopeRefAliases`), deduplicated. `undefined`\n * when the filter names no scopeRef, so callers keep their \"no condition\" path.\n */\nexport function scopeRefValues(filter: {\n scopeRef?: string | undefined;\n scopeRefAliases?: string[] | undefined;\n}): string[] | undefined {\n if (!filter.scopeRef) return undefined;\n return [...new Set([filter.scopeRef, ...(filter.scopeRefAliases ?? [])])];\n}\n\n/** True when `value` is one of the scope_ref values the filter accepts (or the filter names none). */\nexport function scopeRefMatches(\n value: string | null | undefined,\n filter: { scopeRef?: string | undefined; scopeRefAliases?: string[] | undefined }\n): boolean {\n const accepted = scopeRefValues(filter);\n return accepted === undefined || (value != null && accepted.includes(value));\n}\n","import { createHash } from \"node:crypto\";\n\n/**\n * The content fingerprint behind `mnemo_fact_hash`.\n *\n * P126 — this lived inline in five places: three in `cognitive/remember.ts`\n * (the dedupe lookup and two upserts), one in `FactRepository`'s supersede\n * path, and a sixth was about to be added by the fix for the in-place-edit\n * case. Five copies of a hash formula is not a style problem: the fingerprint\n * only works if the writer and the reader agree BYTE FOR BYTE, and a drifted\n * copy does not error — it silently stops matching, and the dedupe it backs\n * quietly turns into a duplicate factory.\n *\n * The normalisation is deliberately shallow: trim and lowercase only. It is not\n * trying to decide that two differently-worded statements mean the same thing —\n * that is `remember()`'s surprise gate and the conflict machinery, both of\n * which reason about embeddings. This answers the narrower question \"is this\n * the SAME TEXT, said again\".\n *\n * `subject` participates because the same sentence under a different subject is\n * a different assertion, and the trailing `fact` keeps the space from colliding\n * with a future primitive's fingerprints.\n */\nexport function factStatementHash(statement: string, subject: string): string {\n const normalised = `${statement.trim().toLowerCase()}|${subject}|fact`;\n return createHash(\"sha256\").update(normalised).digest(\"hex\");\n}\n","/** Validated, write-free managed extraction output. The commit fence revalidates topic matches. */\nimport type { Sensitivity, WorthDelta } from \"./common.js\";\nimport type { ManagedSessionProvenance } from \"./harness.js\";\nimport type { ManagedArchiveReason } from \"./session.js\";\nimport type {\n CreateFactInput,\n CreateDecisionInput,\n CreateStrategyInput,\n CreateEpisodeInput,\n} from \"./ports.js\";\n\nexport interface ManagedCandidateSupport {\n id: string;\n sourceMessageIds: string[];\n sensitivity: Sensitivity;\n topicKey?: string;\n /** Advisory snapshot only; commit resolves the active topic under a lock. */\n predecessorId?: string;\n}\nexport type ManagedCollapseCandidate = ManagedCandidateSupport &\n (\n | { kind: \"fact\"; input: CreateFactInput }\n | { kind: \"decision\"; input: CreateDecisionInput }\n | { kind: \"strategy\"; input: CreateStrategyInput }\n );\nexport interface ManagedRejectedCandidate {\n id: string;\n kind: \"fact\" | \"decision\" | \"strategy\";\n topicKey?: string;\n requestedSensitivity: Sensitivity;\n contentHash: string;\n reason: \"sensitivity_ceiling\";\n}\nexport type ManagedPostCommitEffectKind =\n | \"session_buffer_cleanup\"\n | \"hot_tier_promotion\"\n | \"bus_delivery\"\n | \"webhook_delivery\"\n | \"td_credit\"\n | \"governance\"\n | \"graduation\"\n | \"reflection\"\n | \"anticipation_telemetry\"\n | \"llm_usage_telemetry\";\nexport interface ManagedPostCommitEffect {\n effectKind: ManagedPostCommitEffectKind;\n targetKind: \"session\" | \"fact\" | \"workspace\" | \"agent\";\n targetId: string;\n payload: Record<string, unknown>;\n}\nexport interface ManagedCollapsePlanBase {\n operationId: string;\n workspaceId: string;\n sessionId: string;\n generation: number;\n sourceMessageIds: string[];\n sensitivity: Sensitivity;\n provenance: ManagedSessionProvenance;\n}\nexport interface ManagedPreparedCollapsePlan extends ManagedCollapsePlanBase {\n status: \"prepared\";\n candidates: ManagedCollapseCandidate[];\n rejectedCandidates: ManagedRejectedCandidate[];\n episode: {\n id: string;\n input: CreateEpisodeInput;\n sourceMessageIds: string[];\n sensitivity: Sensitivity;\n };\n /** Includes existing facts with this sessionId; commit must preserve stricter classification. */\n linkSessionFacts: true;\n predecessorSessionId?: string;\n relations: Array<{\n id: string;\n sourceId: string;\n targetId: string;\n sourceType: \"fact\";\n targetType: \"fact\";\n verb: \"related\";\n }>;\n hyperedges: Array<{ id: string; memberIds: string[]; label: string; description: string }>;\n worthUpdates: Array<{ factId: string; delta: WorthDelta }>;\n counters: { factCount: number; sessionCount: 1; reflectionAgentId?: string };\n summary: {\n goal?: string;\n outcome: string;\n discoveries: string[];\n nextSteps: string[];\n relevantEntities: string[];\n keyDecisions: string[];\n turnsProcessed: number;\n pinsUsed: number;\n llmTokensUsed: number;\n collapseReason: string;\n episodeId: string;\n };\n indexJobs: Array<{\n eventType: \"vector_upsert\";\n targetKind: \"fact\" | \"decision\";\n targetId: string;\n }>;\n /** Commit materializes provenance, topic closures/supersedes, correction review rows,\n * lifecycle rows and these durable effects atomically with all output above. */\n postCommitEffects: ManagedPostCommitEffect[];\n}\nexport type ManagedCollapsePlan =\n | ManagedPreparedCollapsePlan\n | (ManagedCollapsePlanBase & {\n status: \"archive\";\n reason: ManagedArchiveReason;\n postCommitEffects: ManagedPostCommitEffect[];\n })\n | (Omit<ManagedCollapsePlanBase, \"sensitivity\" | \"provenance\"> & {\n status: \"retryable\";\n reason:\n | \"invalid_session\"\n | \"invalid_provenance\"\n | \"llm_unavailable\"\n | \"invalid_extraction\"\n | \"preparation_unavailable\";\n });\n\n/** Stable identity is allocated before a session's first collapse commit. */\nexport function managedCollapseOperationId(session: {\n workspaceId: string;\n id: string;\n sourceGeneration?: number | null;\n collapseOperationId?: string | null;\n}): string {\n return (\n session.collapseOperationId ??\n `managed:${session.workspaceId}:${session.id}:${session.sourceGeneration ?? -1}`\n );\n}\n\nexport interface ManagedEffectClaim extends Omit<ManagedPostCommitEffect, \"effectKind\"> {\n id: string;\n workspaceId: string;\n operationId: string;\n leaseOwner: string;\n effectKind: ManagedPostCommitEffectKind | \"lifecycle_event\" | \"metrics\" | \"redis_cleanup\";\n}\n","export const LSH_DIMS = 64;\nexport const LSH_BANDS = 6;\nexport const LSH_PLANES_PER_BAND = 8;\nconst LSH_SEED = 0x9e3779b9;\n\n// Deterministic xorshift32 PRNG seeded with LSH_SEED\nfunction xorshift32(state: number): number {\n state ^= state << 13;\n state ^= state >>> 17;\n state ^= state << 5;\n return state >>> 0;\n}\n\n// Pre-generate sign random-projection hyperplanes: 6 bands × 8 planes × 64 dims.\n// All bands project the SAME 64-dim embedding prefix; bands differ only by their planes.\nconst PLANES: number[][][] = [];\n{\n let rng = LSH_SEED;\n for (let b = 0; b < LSH_BANDS; b++) {\n const band: number[][] = [];\n for (let p = 0; p < LSH_PLANES_PER_BAND; p++) {\n const plane: number[] = [];\n for (let d = 0; d < LSH_DIMS; d++) {\n rng = xorshift32(rng);\n plane.push(rng & 1 ? 1 : -1);\n }\n band.push(plane);\n }\n PLANES.push(band);\n }\n}\n\n// FNV-1a 64-bit band hash\nfunction fnv1a64(bandIdx: number, sketch: number, spaceId?: string): bigint {\n let h = 0xcbf29ce484222325n;\n const prime = 0x100000001b3n;\n const mask = 0xffffffffffffffffn;\n const str = spaceId ? `${spaceId}:${bandIdx}` : `${bandIdx}`;\n for (let i = 0; i < str.length; i++) {\n h = (h ^ BigInt(str.charCodeAt(i))) & mask;\n h = (h * prime) & mask;\n }\n h = (h ^ BigInt(sketch & 0xff)) & mask;\n h = (h * prime) & mask;\n return h;\n}\n\nexport interface LshBand {\n bandIdx: number;\n bandHash: bigint;\n}\n\nexport function lshBands(embedding: Float32Array | number[], spaceId?: string): LshBand[] {\n const out: LshBand[] = [];\n for (let b = 0; b < LSH_BANDS; b++) {\n let sketch = 0;\n for (let p = 0; p < LSH_PLANES_PER_BAND; p++) {\n const plane = PLANES[b]![p]!;\n let dot = 0;\n for (let d = 0; d < plane.length; d++) {\n dot += (embedding[d] ?? 0) * plane[d]!; // all bands use the same 64-dim prefix\n }\n if (dot >= 0) sketch |= 1 << p;\n }\n out.push({ bandIdx: b, bandHash: fnv1a64(b, sketch, spaceId) });\n }\n return out;\n}\n","/**\n * PG-TIMEOUTS: server-side time limits for every runtime Postgres pool.\n *\n * Without them a stuck connection stays stuck: on the chaos stack an\n * `idle in transaction` audit append held an advisory lock forever while nine\n * other connections waited on it (`SHOW statement_timeout` etc. all `0`), and\n * the instance never recovered (CHAOS-1). These limits are sent as startup\n * parameters on each connection, so they need no migration and no role change.\n *\n * - `statement_timeout` cancels one statement that runs too long.\n * - `lock_timeout` cancels a statement waiting too long for a lock (advisory\n * locks included). It must be shorter than `statement_timeout`, or it never\n * fires first.\n * - `idle_in_transaction_session_timeout` ends a session that holds a\n * transaction open while the application does nothing on it.\n *\n * Migrations open their own connections and never get these limits; long\n * maintenance statements raise them per transaction (see\n * {@link resolvePgMaintenanceTimeoutMs}).\n *\n * Pure: takes the environment as an argument (no `process` access here).\n */\n\n/** Each limit in ms. 0 means \"not set here\": the role or server default applies. */\nexport interface PgSessionTimeouts {\n /** `statement_timeout`, in ms. */\n statementTimeoutMs: number;\n /** `lock_timeout`, in ms. */\n lockTimeoutMs: number;\n /** `idle_in_transaction_session_timeout`, in ms. */\n idleInTransactionTimeoutMs: number;\n}\n\nexport const DEFAULT_PG_SESSION_TIMEOUTS: Readonly<PgSessionTimeouts> = Object.freeze({\n statementTimeoutMs: 60_000,\n lockTimeoutMs: 15_000,\n idleInTransactionTimeoutMs: 60_000,\n});\n\n/** Env var → field. Values are milliseconds; `0` leaves that limit to the role/server. */\nexport const PG_SESSION_TIMEOUT_ENV = Object.freeze({\n statementTimeoutMs: \"MNEMO_PG_STATEMENT_TIMEOUT_MS\",\n lockTimeoutMs: \"MNEMO_PG_LOCK_TIMEOUT_MS\",\n idleInTransactionTimeoutMs: \"MNEMO_PG_IDLE_IN_TRANSACTION_TIMEOUT_MS\",\n} as const);\n\n/** Statement budget for long maintenance work (matview refreshes). 0 = no limit. */\nexport const PG_MAINTENANCE_TIMEOUT_ENV = \"MNEMO_PG_MAINTENANCE_STATEMENT_TIMEOUT_MS\";\n\ntype Env = Readonly<Record<string, string | undefined>>;\n\nfunction readMs(env: Env, name: string, fallback: number): number {\n const raw = env[name];\n if (raw === undefined || raw.trim() === \"\") return fallback;\n const n = Number(raw);\n if (!Number.isSafeInteger(n) || n < 0) {\n throw new Error(`${name} must be a whole number of milliseconds >= 0, got \"${raw}\"`);\n }\n return n;\n}\n\n/**\n * Resolve the runtime pool limits from the environment. Throws on a value\n * that is not a non-negative integer, and when `lock_timeout` is not shorter\n * than `statement_timeout` (both set): a misconfiguration should stop the\n * boot, not surface as the next outage.\n */\nexport function resolvePgSessionTimeouts(env: Env): PgSessionTimeouts {\n const t: PgSessionTimeouts = {\n statementTimeoutMs: readMs(\n env,\n PG_SESSION_TIMEOUT_ENV.statementTimeoutMs,\n DEFAULT_PG_SESSION_TIMEOUTS.statementTimeoutMs\n ),\n lockTimeoutMs: readMs(\n env,\n PG_SESSION_TIMEOUT_ENV.lockTimeoutMs,\n DEFAULT_PG_SESSION_TIMEOUTS.lockTimeoutMs\n ),\n idleInTransactionTimeoutMs: readMs(\n env,\n PG_SESSION_TIMEOUT_ENV.idleInTransactionTimeoutMs,\n DEFAULT_PG_SESSION_TIMEOUTS.idleInTransactionTimeoutMs\n ),\n };\n if (t.statementTimeoutMs > 0 && t.lockTimeoutMs >= t.statementTimeoutMs) {\n throw new Error(\n `${PG_SESSION_TIMEOUT_ENV.lockTimeoutMs} (${t.lockTimeoutMs}) must be shorter than ` +\n `${PG_SESSION_TIMEOUT_ENV.statementTimeoutMs} (${t.statementTimeoutMs})`\n );\n }\n return t;\n}\n\n/**\n * The startup parameters for a postgres.js `connection` option. Postgres\n * applies them to the session as if set with `SET`; a transaction can still\n * override them with `SET LOCAL`. A limit of 0 is left out, so a role-level\n * setting (`ALTER ROLE … SET`) still applies and a pooler that rejects unknown\n * startup parameters can be served by setting all three to 0.\n */\nexport function pgSessionTimeoutParams(t: PgSessionTimeouts): Record<string, string> {\n const params: Record<string, string> = {};\n if (t.statementTimeoutMs > 0) params[\"statement_timeout\"] = String(t.statementTimeoutMs);\n if (t.lockTimeoutMs > 0) params[\"lock_timeout\"] = String(t.lockTimeoutMs);\n if (t.idleInTransactionTimeoutMs > 0) {\n params[\"idle_in_transaction_session_timeout\"] = String(t.idleInTransactionTimeoutMs);\n }\n return params;\n}\n\n/** Statement and lock budget for long maintenance statements, in ms (0 = no limit). */\nexport function resolvePgMaintenanceTimeoutMs(env: Env): number {\n return readMs(env, PG_MAINTENANCE_TIMEOUT_ENV, 0);\n}\n","/**\n * CHAOS-10: tell a database that is unavailable or too slow right now from a\n * request that can never succeed.\n *\n * With Postgres stopped, writes answered 500 `internal_error`, which tells a\n * client nothing about retrying. An error this function accepts means \"the\n * dependency failed, retry later\" (503 + Retry-After in the server's error\n * handler); anything else — constraint, privilege, syntax — is not fixed by\n * retrying. A timeout after the statement was sent does NOT prove that nothing\n * was written; callers that retry writes still need idempotency.\n *\n * Pure: reads only `err.code` (postgres.js / Node socket codes and SQLSTATEs),\n * so it lives here, next to the PG-TIMEOUTS limits whose errors it classifies.\n */\n\n/** postgres.js and Node socket errors (`err.code`) for a lost or refused connection. */\nconst TRANSIENT_DRIVER_CODES = new Set([\n \"ECONNREFUSED\",\n \"ECONNRESET\",\n \"ETIMEDOUT\",\n \"EPIPE\",\n \"EHOSTUNREACH\",\n \"ENETUNREACH\",\n \"ENOTFOUND\",\n \"EAI_AGAIN\",\n \"CONNECT_TIMEOUT\",\n \"CONNECTION_CLOSED\",\n \"CONNECTION_ENDED\",\n \"CONNECTION_DESTROYED\",\n]);\n\n/** SQLSTATEs for an unavailable server or a PG-TIMEOUTS limit that fired. */\nconst TRANSIENT_SQLSTATES = new Set([\n \"53300\", // too_many_connections\n \"57P01\", // admin_shutdown\n \"57P02\", // crash_shutdown\n \"57P03\", // cannot_connect_now (starting up / recovery)\n \"57014\", // query_canceled — statement_timeout\n \"55P03\", // lock_not_available — lock_timeout\n \"25P03\", // idle_in_transaction_session_timeout\n]);\n\nfunction codeOf(err: unknown): string | undefined {\n if (typeof err !== \"object\" || err === null) return undefined;\n const code = (err as { code?: unknown }).code;\n return typeof code === \"string\" ? code : undefined;\n}\n\n/**\n * opossum's own timeout: code `ETIMEDOUT` (the same string as a socket timeout)\n * and the message \"Timed out after Nms\". It says a breaker-wrapped call ran\n * long, whatever that call was (a recall that includes an LLM rerank, an\n * embed), so it is not evidence about the database.\n */\nexport function isBreakerTimeoutError(err: unknown): boolean {\n return (\n err instanceof Error &&\n codeOf(err) === \"ETIMEDOUT\" &&\n /^Timed out after \\d+ms$/.test(err.message)\n );\n}\n\n/** True when `err` (or an error in its `cause` chain) is a transient database failure. */\nexport function isTransientDbError(err: unknown): boolean {\n let current: unknown = err;\n for (let depth = 0; depth < 5 && current instanceof Error; depth++) {\n const code = isBreakerTimeoutError(current) ? undefined : codeOf(current);\n if (code !== undefined) {\n if (TRANSIENT_DRIVER_CODES.has(code) || TRANSIENT_SQLSTATES.has(code)) return true;\n // SQLSTATE class 08: connection exception.\n if (/^08[0-9A-Z]{3}$/.test(code)) return true;\n }\n current = (current as { cause?: unknown }).cause;\n }\n return false;\n}\n","/**\n * Tiny, dependency-free i18n core shared by the CLI, the MCP server and the\n * server's error messages. Dictionaries live in each package; this file only\n * resolves a locale, renders a key, and matches English templates.\n */\n\nexport type Locale = \"en-US\" | \"es-419\";\nexport const LOCALES: readonly Locale[] = [\"en-US\", \"es-419\"];\nexport const DEFAULT_LOCALE: Locale = \"en-US\";\n\nconst PRIMARY: Record<string, Locale> = { en: \"en-US\", es: \"es-419\" };\n\n/**\n * BCP 47 (`es`, `es-AR`) and POSIX (`es_MX.UTF-8`, `es_AR@euro`) tags to a\n * Locale. `C`, `POSIX`, empty and unknown languages give undefined.\n */\nexport function normalizeLocale(tag?: string): Locale | undefined {\n if (typeof tag !== \"string\" || !tag) return undefined; // JSON config can hand us a number\n const primary =\n tag\n .trim()\n .toLowerCase()\n .split(/[-_.@]/)[0] ?? \"\";\n // Own properties only: \"constructor\" or \"__proto__\" must not reach Object's.\n return Object.hasOwn(PRIMARY, primary) ? PRIMARY[primary] : undefined;\n}\n\n/** First candidate that normalizes wins, then q-sorted Accept-Language, then en-US. */\nexport function resolveLocale(\n candidates: Array<string | undefined>,\n acceptLanguage?: string\n): Locale {\n for (const c of candidates) {\n const locale = normalizeLocale(c);\n if (locale) return locale;\n }\n const ranked = (acceptLanguage ?? \"\")\n .split(\",\")\n .map((part, i) => {\n const [tag, ...params] = part.trim().split(\";\");\n const q = params.map((p) => p.trim()).find((p) => p.startsWith(\"q=\"));\n return { tag, q: q ? Number(q.slice(2)) : 1, i };\n })\n .filter((e) => e.tag && e.q > 0) // NaN (malformed q) fails this too\n .sort((a, b) => b.q - a.q || a.i - b.i);\n for (const { tag } of ranked) {\n const locale = normalizeLocale(tag);\n if (locale) return locale;\n }\n return DEFAULT_LOCALE;\n}\n\nexport type Plural = { one: string; other: string };\n/** A dictionary: nested objects whose leaves are strings or `{ one, other }` plurals. */\nexport type Dict<T = string> = { readonly [key: string]: T | Plural | Dict<T> };\nexport type Vars = Record<string, string | number>;\n\n/**\n * Renders `key` (dotted) from `dict`. `{name}` is replaced from `vars`; an\n * unknown `{name}` stays visible. A `{ one, other }` leaf picks its branch from\n * `vars.count` with Intl.PluralRules. A missing key returns the key.\n */\nexport function translate(\n dict: Dict,\n key: string,\n vars?: Vars,\n locale: Locale = DEFAULT_LOCALE\n): string {\n let node: unknown = dict;\n for (const part of key.split(\".\"))\n node =\n node && typeof node === \"object\" && Object.hasOwn(node, part)\n ? (node as Record<string, unknown>)[part]\n : undefined;\n if (node && typeof node === \"object\") {\n const p = node as Record<string, unknown>;\n const count = vars?.count;\n const branch = typeof count === \"number\" ? new Intl.PluralRules(locale).select(count) : \"other\";\n node = Object.hasOwn(p, branch) ? p[branch] : p.other;\n }\n if (typeof node !== \"string\") return key;\n return node.replace(/\\{(\\w+)\\}/g, (m, name: string) =>\n vars && Object.hasOwn(vars, name) ? String(vars[name]) : m\n );\n}\n\nexport interface CompiledTemplate {\n key: string;\n /** Literal pieces around the placeholders: `literals.length === names.length + 1`. */\n literals: string[];\n names: string[];\n /** Literal characters (placeholders excluded): more means more specific. */\n weight: number;\n}\n\n/** Messages longer than this are never matched (they stay untranslated). */\nexport const MAX_MATCH_LENGTH = 2048;\n\n/**\n * Compiles English `{name}` templates (key -> template), most specific (most\n * literal characters, then fewest placeholders) first. Throws on a duplicate\n * placeholder name or two adjacent placeholders (unmatchable without a separator).\n */\nexport function compileTemplates(table: Record<string, string>): CompiledTemplate[] {\n return Object.entries(table)\n .map(([key, template]) => {\n // split with a capture group alternates literal, name, literal, ...\n const pieces = template.split(/\\{(\\w+)\\}/);\n const literals = pieces.filter((_, i) => i % 2 === 0);\n const names = pieces.filter((_, i) => i % 2 === 1);\n if (new Set(names).size !== names.length)\n throw new Error(`duplicate placeholder in \"${key}\"`);\n if (literals.slice(1, -1).includes(\"\")) throw new Error(`adjacent placeholders in \"${key}\"`);\n return { key, literals, names, weight: literals.join(\"\").length };\n })\n .sort((a, b) => b.weight - a.weight || a.names.length - b.names.length); // stable\n}\n\n/**\n * The key and captured values of the first template matching `message`, else\n * undefined. Linear time, no RegExp: the message must start and end with the\n * template's outer literals and contain the middle ones in order. Each middle\n * literal is taken at its FIRST occurrence after the previous one, so it can\n * differ from a backtracking regex only when a separator also occurs inside a\n * captured value. Captures are non-empty.\n */\nexport function matchTemplate(\n compiled: readonly CompiledTemplate[],\n message: string\n): { key: string; vars: Record<string, string> } | undefined {\n if (message.length > MAX_MATCH_LENGTH) return undefined;\n for (const { key, literals, names } of compiled) {\n const first = literals[0] ?? \"\";\n if (names.length === 0) {\n if (message === first) return { key, vars: Object.create(null) };\n continue;\n }\n const last = literals[literals.length - 1] ?? \"\";\n if (!message.startsWith(first) || !message.endsWith(last)) continue;\n const end = message.length - last.length;\n if (end < first.length) continue; // prefix and suffix would overlap\n const vars: Record<string, string> = Object.create(null);\n let pos = first.length;\n let ok = true;\n for (let i = 0; i < names.length && ok; i++) {\n const sep = i < names.length - 1 ? (literals[i + 1] ?? \"\") : undefined;\n const stop = sep === undefined ? end : message.indexOf(sep, pos + 1);\n if (stop <= pos || (sep !== undefined && stop + sep.length > end)) ok = false;\n else {\n vars[names[i] as string] = message.slice(pos, stop);\n pos = stop + (sep?.length ?? 0);\n }\n }\n if (ok) return { key, vars };\n }\n return undefined;\n}\n"]}