@mnemo-ai/types 3.6.0-alpha.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.
- package/LICENSE +19 -0
- package/README.md +159 -0
- package/dist/chunk-H4A2NIMQ.js +124 -0
- package/dist/chunk-H4A2NIMQ.js.map +1 -0
- package/dist/index.cjs +342 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +371 -0
- package/dist/index.d.ts +371 -0
- package/dist/index.js +192 -0
- package/dist/index.js.map +1 -0
- package/dist/ports-PqoQMXjO.d.cts +3233 -0
- package/dist/ports-PqoQMXjO.d.ts +3233 -0
- package/dist/testing/index.cjs +2716 -0
- package/dist/testing/index.cjs.map +1 -0
- package/dist/testing/index.d.cts +420 -0
- package/dist/testing/index.d.ts +420 -0
- package/dist/testing/index.js +2660 -0
- package/dist/testing/index.js.map +1 -0
- package/package.json +69 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/branded.ts","../src/ports.ts","../src/compositionality.ts","../src/observability.ts","../src/embedding.ts"],"names":[],"mappings":"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","file":"index.js","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","// 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 { MnemoRelation, RelationVerb } from \"./relations.js\";\nimport type { MnemoSession, SessionTurn } 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 { Provenance, RecallFilter, RememberKind } from \"./recall.js\";\n\n// ─── Input/Filter types ───────────────────────────────────────────────────────\n\nexport interface CreateSessionInput {\n workspaceId: string;\n agentId?: string;\n actorId?: string;\n metadata?: Record<string, unknown>;\n}\n\nexport interface CreateFactInput {\n workspaceId: string;\n agentId?: string;\n actorId?: string;\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 * 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\nexport interface UpdateFactInput {\n statement?: string;\n confidence?: number;\n relevance?: number;\n status?: MnemoFact[\"status\"];\n pinned?: boolean;\n validTo?: Date;\n metadata?: Record<string, unknown>;\n}\n\nexport interface MergeFactByTopicKeyInput {\n workspaceId: string;\n topicKey: string;\n statement: string;\n metadata?: Record<string, unknown>;\n tags?: 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\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\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 */\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\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\nexport interface CreateDecisionInput {\n workspaceId: string;\n agentId?: string;\n actorId?: string;\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\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 validAt?: Date;\n offset?: number;\n limit?: number;\n}\n\nexport interface CreateEpisodeInput {\n workspaceId: string;\n agentId?: string;\n actorId?: string;\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 /** 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<MnemoEntity, \"name\" | \"aliases\" | \"description\" | \"canonicalId\" | \"metadata\">\n>;\n\nexport interface EntityFilter {\n workspaceId: string;\n kind?: MnemoEntity[\"kind\"];\n name?: string;\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 CreateStrategyInput {\n workspaceId: string;\n agentId?: string;\n actorId?: 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 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<MnemoStrategy, \"trigger\" | \"action\" | \"context\" | \"status\" | \"validTo\" | \"metadata\" | \"successCount\" | \"failureCount\" | \"worth\" | \"relatedFacts\" | \"attribution\">\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 validAt?: Date;\n offset?: number;\n limit?: number;\n}\n\nexport interface CreateWorkflowInput {\n workspaceId: string;\n actorId?: string;\n agentId?: 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 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 /** 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 CreateSkillInput {\n workspaceId: string;\n actorId?: string;\n agentId?: string;\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 offset?: number;\n limit?: number;\n}\n\nexport interface CreateTaskInput {\n workspaceId: string;\n actorId?: string;\n agentId?: string;\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 offset?: number;\n limit?: number;\n}\n\nexport interface CreateEventInput {\n workspaceId: string;\n agentId?: string;\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 /** 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 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}\n\nexport type UpdateHyperedgeInput = Partial<\n Pick<MnemoHyperedge, \"label\" | \"description\" | \"contextQuery\">\n>;\n\nexport interface HyperedgeFilter {\n workspaceId: string;\n memberId?: string;\n label?: string;\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<MnemoCompositionRule,\n | \"name\" | \"description\" | \"conditionDsl\" | \"actionDsl\"\n | \"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: string;\n targetId: string;\n targetType: string;\n verb: RelationVerb;\n weight?: number;\n metadata?: Record<string, unknown>;\n}\n\nexport interface RelationFilter {\n workspaceId: string;\n sourceId?: string;\n targetId?: string;\n verb?: RelationVerb;\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// ─── 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 condition: string;\n triggerAt: Date | null;\n status: \"pending\" | \"triggered\" | \"dismissed\";\n conditionEmbedding: number[] | null;\n triggeredAt: Date | null;\n dismissedAt: Date | null;\n createdByAgentId: string | null;\n createdAt: Date;\n updatedAt: Date;\n}\n\nexport interface CreateReminderInput {\n id: string;\n workspaceId: string;\n content: string;\n condition: string;\n triggerAt?: Date;\n conditionEmbedding?: number[];\n createdByAgentId?: string;\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}\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 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 entityId?: string;\n sessionId?: string;\n}\n\nexport interface FtsCandidate extends PointerCandidate {\n rank: 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\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\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 interface StorageAdapter {\n readonly capabilities: StorageCapabilities;\n\n // Session\n createSession(input: CreateSessionInput): Promise<MnemoSession>;\n appendTurn(sessionId: string, turn: Omit<SessionTurn, \"id\" | \"createdAt\">): Promise<void>;\n listTurns(sessionId: string, workspaceId: string): Promise<SessionTurn[]>;\n closeSession(id: string, workspaceId: string): Promise<void>;\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 archiveSession?(id: string, workspaceId: string): Promise<void>;\n getSession(id: string, workspaceId: string): Promise<MnemoSession | null>;\n listSessions?(workspaceId: string, limit?: number, offset?: number): Promise<MnemoSession[]>;\n updateSessionSummary?(args: {\n sessionId: string; workspaceId: string;\n summary: Record<string, unknown>; factCount: number;\n }): Promise<void>;\n pinSessionTurn(sessionId: string, turnId: string, workspaceId: string, pinned: boolean): Promise<void>;\n\n // Facts\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 archiveFact(id: string, workspaceId: string): Promise<void>;\n queryFacts(filter: FactFilter): Promise<PaginatedResult<MnemoFact>>;\n applyConsolidationMerge(input: ApplyConsolidationMergeInput): Promise<ConsolidationMergeSnapshot | null>;\n rollbackConsolidationMerge(input: { snapshot: ConsolidationMergeSnapshot; review: ReplayFailureReview }): Promise<\"rolled_back\" | \"conflict\">;\n finalizeConsolidationMerge(input: { snapshot: ConsolidationMergeSnapshot; applyReplayBoost: boolean }): Promise<\"finalized\" | \"conflict\">;\n refreshConsolidationMergeLease(input: { snapshot: ConsolidationMergeSnapshot; leaseExpiresAt: Date }): Promise<\"refreshed\" | \"conflict\">;\n inspectConsolidationMergeState(snapshot: ConsolidationMergeSnapshot): Promise<\"pending\" | \"restored\" | \"retained\" | \"divergent\">;\n recoverExpiredConsolidationMerges(input: { workspaceId: string; expiredBefore: Date }): Promise<number>;\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 /**\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 hardDeleteFact?(id: string, workspaceId: string): Promise<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 }): 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 * §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 */\n enqueueReview?(input: {\n workspaceId: string;\n primitiveKind: string;\n primitiveId: string;\n reason: string;\n priority?: number;\n }): Promise<void>;\n\n /** §11 governance: set/clear the canonical exemption flag. */\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 /**\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 * §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 // ── §9 L3 — Semantic query cache (cosine>=0.95 shortcut) ───────────────────\n /**\n * §9 L3 — cosine>=threshold lookup against mnemo_query_cache; null on miss.\n * Uses an HNSW index on the embedding column for fast ANN search.\n */\n lookupQueryCache?(\n workspaceId: string,\n embedding: Float32Array,\n threshold: number,\n scope?: string,\n ): Promise<{ resultIds: string[]; resultKinds: string[] } | null>;\n\n /** §9 L3 — store a recall result set for 24h reuse. */\n upsertQueryCache?(input: {\n workspaceId: string;\n queryText: string;\n embedding: Float32Array;\n resultIds: string[];\n resultKinds: string[];\n ttlMs: number;\n }): Promise<void>;\n\n // ── §9 L3 — Embedding LRU (avoid re-embedding identical text) ─────────────\n /** §9 L3 embedding LRU — exact text-hash lookup; null on miss. */\n getCachedEmbedding?(workspaceId: string, textHash: string): Promise<Float32Array | null>;\n\n /** §9 L3 embedding LRU — insert or refresh an embedding record. */\n putCachedEmbedding?(input: {\n workspaceId: string;\n textHash: string;\n embedding: Float32Array;\n model: string;\n }): Promise<void>;\n\n // Decisions\n createDecision(input: CreateDecisionInput): Promise<MnemoDecision>;\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 queryDecisions(filter: DecisionFilter): Promise<PaginatedResult<MnemoDecision>>;\n\n // Episodes\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?(episodeId: string, workspaceId: string, limit?: number): 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 * 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 * 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 * 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 // Entities\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 queryEntities(filter: EntityFilter): Promise<PaginatedResult<MnemoEntity>>;\n\n // Strategies\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 // Workflows\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 // Skills\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 // Tasks\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 // Events\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(id: string, workspaceId: string, annotation: EventAnnotation): 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 // Reasoning\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<Array<{\n id: string;\n cosine: number;\n worth: number;\n successCount: number;\n failureCount: number;\n status: MnemoReasoning[\"status\"];\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 // Agent profile (Wave M2 — self-editing memory, spec §13)\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 // Hyperedges\n createHyperedge(input: CreateHyperedgeInput): Promise<MnemoHyperedge>;\n getHyperedge(id: string, workspaceId: string): 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 // Composition rules (Wave E)\n createCompositionRule(input: CreateCompositionRuleInput): Promise<MnemoCompositionRule>;\n getCompositionRule(id: string, workspaceId: string): Promise<MnemoCompositionRule | null>;\n updateCompositionRule(id: string, workspaceId: string, input: UpdateCompositionRuleInput): Promise<MnemoCompositionRule>;\n queryCompositionRules(filter: CompositionRuleFilter): 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 // 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 // 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 getRecallStructures(\n workspaceId: string,\n sourceIds: string[],\n hyperedgeLimitPerMember: number,\n ): Promise<RecallStructures>;\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 // Meta-cognition (Wave F)\n getConfidenceMap(workspaceId: string, opts?: { limit?: number }): Promise<ConfidenceMapRow[]>;\n getKnowledgeGaps(workspaceId: string, opts?: { limit?: number; minScore?: number }): Promise<KnowledgeGapRow[]>;\n getMetacognitionTrends(workspaceId: string): Promise<MetacognitionTrends>;\n refreshMetacognitionViews(): Promise<void>;\n\n // Anticipation (Wave G)\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 // Relations\n createRelation(input: CreateRelationInput): Promise<MnemoRelation>;\n getRelations(filter: RelationFilter): Promise<MnemoRelation[]>;\n updateRelationStrength(id: string, delta: number): Promise<void>;\n deleteRelation(id: string, workspaceId: string): Promise<void>;\n\n // Worth governance (TD(λ))\n updateWorth(id: string, workspaceId: string, primitiveKind: PrimitiveKind, delta: WorthDelta): Promise<void>;\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 // Audit (append-only)\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 // Outbox (transactional side effects)\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 // Webhooks\n createWebhookEndpoint(input: CreateWebhookEndpointInput): Promise<MnemoWebhookEndpoint>;\n getWebhookEndpoint(id: string, workspaceId: string): Promise<MnemoWebhookEndpoint | null>;\n listWebhookEndpoints(workspaceId: string): Promise<MnemoWebhookEndpoint[]>;\n updateWebhookEndpoint(id: string, input: UpdateWebhookEndpointInput): Promise<MnemoWebhookEndpoint>;\n deleteWebhookEndpoint(id: string, workspaceId: string): Promise<void>;\n listActiveWebhookEndpoints(workspaceId: string, eventType: string): Promise<MnemoWebhookEndpoint[]>;\n recordWebhookDelivery(entry: CreateWebhookDeliveryInput): Promise<void>;\n listWebhookDeliveries(webhookId: string, workspaceId: string, limit?: number): 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(id: string, workspaceId: string, update: {\n status?: \"pending\" | \"delivered\" | \"failed\";\n responseStatus?: number;\n responseBody?: string;\n attempt?: number;\n deliveredAt?: Date;\n nextAttemptAt?: Date | null;\n }): Promise<void>;\n\n // Prospective memory (reminders)\n createReminder(input: CreateReminderInput): Promise<MnemoReminder>;\n getReminder(id: string, workspaceId: string): Promise<MnemoReminder | null>;\n listPendingReminders(workspaceId: string, asOf: Date): Promise<MnemoReminder[]>;\n dismissReminder(id: string, workspaceId: string, newStatus: \"triggered\" | \"dismissed\"): Promise<void>;\n listReminders(workspaceId: string, status: \"pending\" | \"triggered\" | \"dismissed\" | \"all\", limit: number): Promise<MnemoReminder[]>;\n\n // Recall log (ACT-R activation — TASK-4001)\n /** Append a recall event for a memory. Used by Stage 4 Petrov activation. */\n logRecall(workspaceId: string, memoryId: string, score: number): Promise<void>;\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 // ─── Engram neuro-dynamics (Wave Y, §25.2/§25.3) ───────────────────────────\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 // ─── Wave Y §25.1 — review queue + drift detection ──────────────────────────\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<Array<{\n id: string;\n statement: string;\n metadata: Record<string, unknown>;\n }>>;\n\n // Lifecycle\n healthCheck(): Promise<HealthStatus>;\n close(): Promise<void>;\n\n listWorkspaceIds(): Promise<string[]>;\n\n // ── §36 Embedding-model migration (Wave AA) ────────────────────────────────\n\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 ): Promise<Array<{ id: string; text: string }>>;\n\n /** Check if workspace has an ongoing embedding migration (stale embeddings exist). */\n hasActiveEmbeddingMigration?(workspaceId: 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 // ── §37 Hot-tier ZSet persistence (Wave AA) ────────────────────────────────\n\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 // ── Wave T4 — OutcomeSignal + stale-task cron ──────────────────────────────\n\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 * 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?(workspaceId: string, patch: {\n mode?: \"learning\" | \"production\";\n sessionCount?: number;\n promoteAt?: number | null;\n factCount?: number;\n entityCount?: number;\n }): Promise<void>;\n\n // ── RDD-4 — Hybrid per-turn/collapse dedup gate ───────────────────────────\n\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 listSessionTopicKeysBySource?(\n workspaceId: string,\n sessionId: string,\n source: string,\n ): Promise<string[]>;\n\n // ── RDD-5 — Workspace mode: graduation counters ────────────────────────────\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?(workspaceId: string, delta: {\n factCount?: number;\n entityCount?: number;\n sessionCount?: number;\n }): Promise<void>;\n\n // ── §21 Plugin state persistence (Wave U) ─────────────────────────────────\n\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?(workspaceId: string, pluginId: string, state: Record<string, unknown>): 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 // ── §14 Procedural memory (Wave U) ────────────────────────────────────────\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<Array<{ sessionId: string; score: number; promptVersionId: string | null; createdAt: Date }>>;\n\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 /v1/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 /v1/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 /v1/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 /v1/cost).\n * OPTIONAL — callers guard with `?.`.\n */\n getWorkspaceEmbeddingTokenUsage?(workspaceId: string, since: Date): Promise<number>;\n\n // ── §14 Prompt version CRUD (Wave U, U2.3) ───────────────────────────────\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/** The primitive tables that carry embedding / embedding_model / embedding_stale columns. */\nexport type EmbeddableTable = \"fact\" | \"decision\" | \"skill\" | \"strategy\" | \"reasoning\" | \"episode\" | \"entity\";\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 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 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\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}\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 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}\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 status: \"pending\" | \"approved\" | \"denied\" | \"expired\";\n resolvedBy?: string;\n resolvedAt?: Date;\n createdAt: Date;\n}\n\nexport interface ApprovalStore {\n create(input: ApprovalRequestInput): Promise<ApprovalRequest>;\n get(workspaceId: string, id: string): Promise<ApprovalRequest | null>;\n resolve(workspaceId: string, id: string, status: \"approved\" | \"denied\", resolvedBy: string): Promise<void>;\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(workspaceId: string, requestedBy: string): 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(input: Omit<SessionTokenRecord, \"id\" | \"usedAt\" | \"familyRevokedAt\" | \"createdAt\">): 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(workspaceId: string, key: string, responseCode: number, responseBody: string): 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","// 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 — aggregate recall-value / LLM-cost ratio for\n * the billing period (dimensionless multiplier).\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 /** Recall value / LLM cost ratio. >1 = profitable. null if cost = 0. */\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","/**\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"]}
|