@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,3233 @@
|
|
|
1
|
+
import { z } from 'zod';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* 10 Cognitive Primitive interfaces — DATA_MODEL.md §2.1–§2.10.
|
|
5
|
+
*
|
|
6
|
+
* Every primitive lives in a workspace (multi-tenant RLS), has bitemporal
|
|
7
|
+
* time axes (validFrom/validTo = world truth; createdAt = system discovery),
|
|
8
|
+
* and participates in the Hebbian relation graph via MnemoRelation.
|
|
9
|
+
*
|
|
10
|
+
* Decay classes (how `worth` decays over time without recall):
|
|
11
|
+
* Semantic (slow) — fact, decision, strategy, workflow, skill, reasoning
|
|
12
|
+
* Episodic (medium) — episode, entity
|
|
13
|
+
* Working (fast) — task (high priority items degrade if not acted on)
|
|
14
|
+
* Immutable — event (no decay, no updatedAt — append-only)
|
|
15
|
+
*
|
|
16
|
+
* SQL GENERATED columns (worth, memory_strength) are computed by Postgres
|
|
17
|
+
* triggers and are read-only on the TypeScript side.
|
|
18
|
+
*
|
|
19
|
+
* Quick reference — kind enums:
|
|
20
|
+
* MnemoFact.kind (7): "preference"|"trait"|"event"|"relationship"|"skill"|"concern"|"other"
|
|
21
|
+
* MnemoDecision.kind (8): "decision"|"architecture"|"policy"|"process"|"bugfix"|"learning"|"discovery"|"config"
|
|
22
|
+
* MnemoEntity.kind (6): "person"|"organization"|"project"|"concept"|"place"|"other"
|
|
23
|
+
*/
|
|
24
|
+
/**
|
|
25
|
+
* A piece of durable behavioral knowledge about a user, agent, or domain.
|
|
26
|
+
*
|
|
27
|
+
* Use for: user preferences, beliefs, observed traits, relationship facts.
|
|
28
|
+
* Do NOT use for: architectural decisions (→ MnemoDecision), sequential events
|
|
29
|
+
* (→ MnemoEpisode), or named entities (→ MnemoEntity).
|
|
30
|
+
*
|
|
31
|
+
* Bitemporal: validFrom/validTo = when true in the world; createdAt = system discovery.
|
|
32
|
+
* Forget by setting validTo = NOW() — rows are never deleted.
|
|
33
|
+
* Sensitivity ceiling is enforced via SENSITIVITY_ORDER (never string comparison, MED-23).
|
|
34
|
+
*/
|
|
35
|
+
interface MnemoFact {
|
|
36
|
+
id: string;
|
|
37
|
+
workspaceId: string;
|
|
38
|
+
agentId?: string;
|
|
39
|
+
actorId?: string;
|
|
40
|
+
scope: "global" | "conversation";
|
|
41
|
+
scopeRef?: string;
|
|
42
|
+
/** Multi-tenant ownership: "workspace:<id>" | "user:<id>" | "tenant:<id>" */
|
|
43
|
+
scopeOwner?: string;
|
|
44
|
+
statement: string;
|
|
45
|
+
subject: string;
|
|
46
|
+
kind: "preference" | "trait" | "event" | "relationship" | "skill" | "concern" | "other";
|
|
47
|
+
confidence: number;
|
|
48
|
+
relevance: number;
|
|
49
|
+
hitCount: number;
|
|
50
|
+
lastRecalledAt?: Date;
|
|
51
|
+
worthSuccess: number;
|
|
52
|
+
worthFailure: number;
|
|
53
|
+
worthAlpha: number;
|
|
54
|
+
worthBeta: number;
|
|
55
|
+
worth: number;
|
|
56
|
+
memoryType: "semantic" | "episodic" | "procedural" | "working";
|
|
57
|
+
memoryStrength: number;
|
|
58
|
+
memoryStability: number;
|
|
59
|
+
lastStrengthUpdate?: Date;
|
|
60
|
+
attribution: "user_stated" | "user_belief" | "objective_fact" | "inferred";
|
|
61
|
+
attributedTo?: "user" | "assistant" | "system";
|
|
62
|
+
sourceMessageIds: string[];
|
|
63
|
+
sessionId?: string;
|
|
64
|
+
extractionSource?: string;
|
|
65
|
+
topicKey?: string;
|
|
66
|
+
revisionCount: number;
|
|
67
|
+
protocolVersion: string;
|
|
68
|
+
entityId?: string;
|
|
69
|
+
episodeId?: string;
|
|
70
|
+
status: "active" | "merged" | "forgotten";
|
|
71
|
+
pinned: boolean;
|
|
72
|
+
/** §11 governance: worth>0.8 ∧ confLower>0.7 → exempt from consolidation merging (MEMORY_MODEL line 1045). */
|
|
73
|
+
canonical: boolean;
|
|
74
|
+
/** Per-fact sensitivity ceiling — compared via SENSITIVITY_ORDER, never string equality (MED-23). */
|
|
75
|
+
sensitivity: "public" | "internal" | "confidential" | "restricted";
|
|
76
|
+
mergedIntoId?: string;
|
|
77
|
+
validFrom: Date;
|
|
78
|
+
validTo?: Date;
|
|
79
|
+
embedding?: Float32Array;
|
|
80
|
+
embeddingModel?: string;
|
|
81
|
+
embeddingStale: boolean;
|
|
82
|
+
createdAt: Date;
|
|
83
|
+
updatedAt: Date;
|
|
84
|
+
metadata: Record<string, unknown>;
|
|
85
|
+
}
|
|
86
|
+
/**
|
|
87
|
+
* A logged architectural or policy decision with full rationale.
|
|
88
|
+
*
|
|
89
|
+
* Use for: design choices, technical policies, process decisions, ADRs.
|
|
90
|
+
* Do NOT use for: behavioral preferences (→ MnemoFact) or task tracking (→ MnemoTask).
|
|
91
|
+
*
|
|
92
|
+
* Decisions have a `status` lifecycle: active → superseded (when a newer decision
|
|
93
|
+
* replaces it, supersededById links to the replacement).
|
|
94
|
+
* Decay: slow semantic decay. Architectural decisions remain relevant long-term.
|
|
95
|
+
*/
|
|
96
|
+
interface MnemoDecision {
|
|
97
|
+
id: string;
|
|
98
|
+
workspaceId: string;
|
|
99
|
+
agentId?: string;
|
|
100
|
+
actorId?: string;
|
|
101
|
+
conversationId?: string;
|
|
102
|
+
/** Multi-tenant ownership: "workspace:<id>" | "user:<id>" | "tenant:<id>" */
|
|
103
|
+
scopeOwner?: string;
|
|
104
|
+
/** Project/entity scope reference (e.g. 'project-x'). Mirrors mnemo_fact.scope_ref. */
|
|
105
|
+
scopeRef?: string;
|
|
106
|
+
kind: "decision" | "architecture" | "policy" | "process" | "bugfix" | "learning" | "discovery" | "config";
|
|
107
|
+
title: string;
|
|
108
|
+
body: string;
|
|
109
|
+
topicKey?: string;
|
|
110
|
+
revisionCount: number;
|
|
111
|
+
normalizedHash: string;
|
|
112
|
+
status: "active" | "superseded" | "withdrawn";
|
|
113
|
+
supersededById?: string;
|
|
114
|
+
decidedByUserId?: string;
|
|
115
|
+
confidence?: number;
|
|
116
|
+
/** Per-decision sensitivity ceiling — compared via SENSITIVITY_ORDER, never string equality (MED-23). */
|
|
117
|
+
sensitivity: "public" | "internal" | "confidential" | "restricted";
|
|
118
|
+
embedding?: Float32Array;
|
|
119
|
+
embeddingModel?: string;
|
|
120
|
+
embeddingStale: boolean;
|
|
121
|
+
validFrom: Date;
|
|
122
|
+
validTo?: Date;
|
|
123
|
+
createdAt: Date;
|
|
124
|
+
updatedAt: Date;
|
|
125
|
+
metadata: Record<string, unknown>;
|
|
126
|
+
}
|
|
127
|
+
/**
|
|
128
|
+
* An episodic memory — a bounded narrative record of a session or event.
|
|
129
|
+
*
|
|
130
|
+
* Use for: conversation summaries, meeting records, project milestones.
|
|
131
|
+
* Do NOT use for: individual facts extracted from a session (→ MnemoFact).
|
|
132
|
+
*
|
|
133
|
+
* Episodes can be hierarchical (parentEpisodeId). Root episodes (isRoot=true, parentEpisodeId=null)
|
|
134
|
+
* represent top-level events. Delta episodes store only what changed relative to parent.
|
|
135
|
+
* Session collapse (collapseSession in core) creates episodes from conversation turns.
|
|
136
|
+
*/
|
|
137
|
+
interface MnemoEpisode {
|
|
138
|
+
id: string;
|
|
139
|
+
workspaceId: string;
|
|
140
|
+
agentId?: string;
|
|
141
|
+
actorId?: string;
|
|
142
|
+
/** Multi-tenant ownership: "workspace:<id>" | "user:<id>" | "tenant:<id>" */
|
|
143
|
+
scopeOwner?: string;
|
|
144
|
+
title: string;
|
|
145
|
+
narrative: string;
|
|
146
|
+
occurredAt: Date;
|
|
147
|
+
durationMinutes?: number;
|
|
148
|
+
participants: string[];
|
|
149
|
+
topics: string[];
|
|
150
|
+
linkedFactIds: string[];
|
|
151
|
+
parentEpisodeId?: string;
|
|
152
|
+
deltaContent?: string;
|
|
153
|
+
isRoot: boolean;
|
|
154
|
+
depth: number;
|
|
155
|
+
isSynthetic: boolean;
|
|
156
|
+
sourceConversationId?: string;
|
|
157
|
+
/** Per-episode sensitivity ceiling — compared via SENSITIVITY_ORDER, never string equality (MED-23). */
|
|
158
|
+
sensitivity: "public" | "internal" | "confidential" | "restricted";
|
|
159
|
+
validFrom: Date;
|
|
160
|
+
validTo?: Date;
|
|
161
|
+
createdAt: Date;
|
|
162
|
+
updatedAt: Date;
|
|
163
|
+
metadata: Record<string, unknown>;
|
|
164
|
+
}
|
|
165
|
+
/**
|
|
166
|
+
* A named real-world entity that facts and episodes can reference.
|
|
167
|
+
*
|
|
168
|
+
* Use for: persons, organizations, projects, concepts, places.
|
|
169
|
+
* Do NOT use for: facts about the entity (→ MnemoFact with entityId pointer) or
|
|
170
|
+
* the entity's decisions (→ MnemoDecision).
|
|
171
|
+
*
|
|
172
|
+
* Canonical deduplication: canonicalId = null means this row IS canonical.
|
|
173
|
+
* Aliases grow automatically as different name forms are observed (mentionCount, lastSeenAt).
|
|
174
|
+
*/
|
|
175
|
+
interface MnemoEntity {
|
|
176
|
+
id: string;
|
|
177
|
+
workspaceId: string;
|
|
178
|
+
actorId?: string;
|
|
179
|
+
agentId?: string;
|
|
180
|
+
/** Multi-tenant ownership: "workspace:<id>" | "user:<id>" | "tenant:<id>" */
|
|
181
|
+
scopeOwner?: string;
|
|
182
|
+
name: string;
|
|
183
|
+
kind: "person" | "organization" | "project" | "concept" | "place" | "other";
|
|
184
|
+
aliases: string[];
|
|
185
|
+
canonicalId?: string;
|
|
186
|
+
description?: string;
|
|
187
|
+
firstSeenAt: Date;
|
|
188
|
+
lastSeenAt: Date;
|
|
189
|
+
mentionCount: number;
|
|
190
|
+
/** Per-entity sensitivity ceiling — compared via SENSITIVITY_ORDER, never string equality (MED-23). */
|
|
191
|
+
sensitivity: "public" | "internal" | "confidential" | "restricted";
|
|
192
|
+
validFrom: Date;
|
|
193
|
+
validTo?: Date;
|
|
194
|
+
createdAt: Date;
|
|
195
|
+
updatedAt: Date;
|
|
196
|
+
metadata: Record<string, unknown>;
|
|
197
|
+
}
|
|
198
|
+
/**
|
|
199
|
+
* A trigger→action heuristic that the agent applies recurrently.
|
|
200
|
+
*
|
|
201
|
+
* Use for: "when X happens, do Y" patterns learned from experience or policy.
|
|
202
|
+
* Do NOT use for: one-off decisions (→ MnemoDecision) or task instructions (→ MnemoTask).
|
|
203
|
+
*
|
|
204
|
+
* worth is GENERATED from successCount/failureCount (Beta distribution mean). Strategies with
|
|
205
|
+
* high worth float to the top of recall results. Low-worth strategies decay toward archival.
|
|
206
|
+
*/
|
|
207
|
+
interface MnemoStrategy {
|
|
208
|
+
id: string;
|
|
209
|
+
workspaceId: string;
|
|
210
|
+
agentId?: string;
|
|
211
|
+
actorId?: string;
|
|
212
|
+
/** Multi-tenant ownership: "workspace:<id>" | "user:<id>" | "tenant:<id>" */
|
|
213
|
+
scopeOwner?: string;
|
|
214
|
+
/** Project/entity scope reference (e.g. 'project-x'). Mirrors mnemo_fact.scope_ref. */
|
|
215
|
+
scopeRef?: string;
|
|
216
|
+
trigger: string;
|
|
217
|
+
action: string;
|
|
218
|
+
context?: string;
|
|
219
|
+
relatedFacts: string[];
|
|
220
|
+
memoryType: "procedural";
|
|
221
|
+
attribution: "user_stated" | "user_belief" | "objective_fact" | "inferred";
|
|
222
|
+
successCount: number;
|
|
223
|
+
failureCount: number;
|
|
224
|
+
worth: number;
|
|
225
|
+
supersedesId?: string;
|
|
226
|
+
status: "active" | "superseded" | "archived";
|
|
227
|
+
/** Per-strategy sensitivity ceiling — compared via SENSITIVITY_ORDER, never string equality (MED-23). */
|
|
228
|
+
sensitivity: "public" | "internal" | "confidential" | "restricted";
|
|
229
|
+
embedding?: Float32Array;
|
|
230
|
+
embeddingModel?: string;
|
|
231
|
+
embeddingStale: boolean;
|
|
232
|
+
validFrom: Date;
|
|
233
|
+
validTo?: Date;
|
|
234
|
+
createdAt: Date;
|
|
235
|
+
updatedAt: Date;
|
|
236
|
+
metadata: Record<string, unknown>;
|
|
237
|
+
}
|
|
238
|
+
/**
|
|
239
|
+
* A reusable multi-step process template with ordered steps, conditions, and timing.
|
|
240
|
+
*
|
|
241
|
+
* Use for: standard operating procedures, repeatable agent workflows, checklists.
|
|
242
|
+
* Do NOT use for: one-off task plans (→ MnemoTask) or general heuristics (→ MnemoStrategy).
|
|
243
|
+
*
|
|
244
|
+
* Versioned: previousVersionId links to the superseded version. executionCount and
|
|
245
|
+
* successRate track runtime performance to inform worth decay.
|
|
246
|
+
*/
|
|
247
|
+
interface WorkflowStep {
|
|
248
|
+
order: number;
|
|
249
|
+
action: string;
|
|
250
|
+
condition?: string;
|
|
251
|
+
expectedDurationMs: number;
|
|
252
|
+
tools?: string[];
|
|
253
|
+
}
|
|
254
|
+
interface MnemoWorkflow {
|
|
255
|
+
id: string;
|
|
256
|
+
workspaceId: string;
|
|
257
|
+
actorId?: string;
|
|
258
|
+
agentId?: string;
|
|
259
|
+
/** Multi-tenant ownership: "workspace:<id>" | "user:<id>" | "tenant:<id>" */
|
|
260
|
+
scopeOwner?: string;
|
|
261
|
+
/** Project/entity scope reference (e.g. 'project-x'). Mirrors mnemo_fact.scope_ref. */
|
|
262
|
+
scopeRef?: string;
|
|
263
|
+
name: string;
|
|
264
|
+
description?: string;
|
|
265
|
+
steps: WorkflowStep[];
|
|
266
|
+
avgDurationMs: number;
|
|
267
|
+
successRate: number;
|
|
268
|
+
worth: number;
|
|
269
|
+
executionCount: number;
|
|
270
|
+
lastExecutedAt?: Date;
|
|
271
|
+
version: number;
|
|
272
|
+
previousVersionId?: string;
|
|
273
|
+
status: "active" | "deprecated" | "draft";
|
|
274
|
+
/** Per-workflow sensitivity ceiling — compared via SENSITIVITY_ORDER, never string equality (MED-23). */
|
|
275
|
+
sensitivity: "public" | "internal" | "confidential" | "restricted";
|
|
276
|
+
validFrom: Date;
|
|
277
|
+
validTo?: Date;
|
|
278
|
+
createdAt: Date;
|
|
279
|
+
updatedAt: Date;
|
|
280
|
+
metadata: Record<string, unknown>;
|
|
281
|
+
}
|
|
282
|
+
/**
|
|
283
|
+
* A stored prompt template for a repeatable task.
|
|
284
|
+
*
|
|
285
|
+
* Use for: prompt engineering building blocks, reusable generation patterns.
|
|
286
|
+
* Do NOT use for: process templates with conditional steps (→ MnemoWorkflow) or
|
|
287
|
+
* trigger→action heuristics (→ MnemoStrategy).
|
|
288
|
+
*
|
|
289
|
+
* qualityScore tracks runtime effectiveness; usageCount drives worth.
|
|
290
|
+
* Embeddings allow semantic retrieval ("find a skill for writing SQL from natural language").
|
|
291
|
+
*/
|
|
292
|
+
interface MnemoSkill {
|
|
293
|
+
id: string;
|
|
294
|
+
workspaceId: string;
|
|
295
|
+
actorId?: string;
|
|
296
|
+
agentId?: string;
|
|
297
|
+
/** Multi-tenant ownership: "workspace:<id>" | "user:<id>" | "tenant:<id>" */
|
|
298
|
+
scopeOwner?: string;
|
|
299
|
+
name: string;
|
|
300
|
+
promptTemplate: string;
|
|
301
|
+
variables: string[];
|
|
302
|
+
requiredContext: string[];
|
|
303
|
+
qualityScore: number;
|
|
304
|
+
worth: number;
|
|
305
|
+
usageCount: number;
|
|
306
|
+
lastUsedAt?: Date;
|
|
307
|
+
/** Per-skill sensitivity ceiling — compared via SENSITIVITY_ORDER, never string equality (MED-23). */
|
|
308
|
+
sensitivity: "public" | "internal" | "confidential" | "restricted";
|
|
309
|
+
embedding?: Float32Array;
|
|
310
|
+
embeddingModel?: string;
|
|
311
|
+
embeddingStale: boolean;
|
|
312
|
+
validFrom: Date;
|
|
313
|
+
validTo?: Date;
|
|
314
|
+
createdAt: Date;
|
|
315
|
+
updatedAt: Date;
|
|
316
|
+
metadata: Record<string, unknown>;
|
|
317
|
+
}
|
|
318
|
+
/**
|
|
319
|
+
* A tracked action item with a full lifecycle and delegation chain.
|
|
320
|
+
*
|
|
321
|
+
* Use for: work items, reminders, delegated actions, subtasks with blocking chains.
|
|
322
|
+
* Do NOT use for: general heuristics (→ MnemoStrategy) or process templates (→ MnemoWorkflow).
|
|
323
|
+
*
|
|
324
|
+
* blockedBy and subtaskIds form a DAG. parentTaskId enables hierarchical decomposition.
|
|
325
|
+
* Decay: fast (working memory class) — high-priority tasks that are not acted on lose worth.
|
|
326
|
+
*/
|
|
327
|
+
interface MnemoTask {
|
|
328
|
+
id: string;
|
|
329
|
+
workspaceId: string;
|
|
330
|
+
actorId?: string;
|
|
331
|
+
agentId?: string;
|
|
332
|
+
/** Multi-tenant ownership: "workspace:<id>" | "user:<id>" | "tenant:<id>" */
|
|
333
|
+
scopeOwner?: string;
|
|
334
|
+
title: string;
|
|
335
|
+
description?: string;
|
|
336
|
+
status: "pending" | "in_progress" | "blocked" | "delegated" | "completed" | "cancelled";
|
|
337
|
+
priority: "critical" | "high" | "medium" | "low";
|
|
338
|
+
assignedTo: string;
|
|
339
|
+
delegatedBy?: string;
|
|
340
|
+
delegatedAt?: Date;
|
|
341
|
+
blockedBy: string[];
|
|
342
|
+
subtaskIds: string[];
|
|
343
|
+
parentTaskId?: string;
|
|
344
|
+
relatedFacts: string[];
|
|
345
|
+
relatedEntities: string[];
|
|
346
|
+
sessionId?: string;
|
|
347
|
+
outcome?: string;
|
|
348
|
+
lessonsLearned?: string;
|
|
349
|
+
/** Per-task sensitivity ceiling — compared via SENSITIVITY_ORDER, never string equality (MED-23). */
|
|
350
|
+
sensitivity: "public" | "internal" | "confidential" | "restricted";
|
|
351
|
+
startedAt?: Date;
|
|
352
|
+
completedAt?: Date;
|
|
353
|
+
dueAt?: Date;
|
|
354
|
+
validFrom: Date;
|
|
355
|
+
validTo?: Date;
|
|
356
|
+
createdAt: Date;
|
|
357
|
+
updatedAt: Date;
|
|
358
|
+
metadata: Record<string, unknown>;
|
|
359
|
+
}
|
|
360
|
+
/**
|
|
361
|
+
* An immutable record of something that happened. Events are append-only.
|
|
362
|
+
*
|
|
363
|
+
* Use for: system events, external webhooks, calendar events, audit trail entries.
|
|
364
|
+
* Do NOT use for: mutable state (→ MnemoFact) or sequential narratives (→ MnemoEpisode).
|
|
365
|
+
*
|
|
366
|
+
* IMPORTANT: Events have no `updatedAt`. Once written, an event row never changes.
|
|
367
|
+
* Annotations are appended via the annotations array (JSONB), not by editing the row.
|
|
368
|
+
* Decay: IMMUTABLE — events do not decay. They accumulate forever (partitioned by occurredAt).
|
|
369
|
+
*/
|
|
370
|
+
interface EventAnnotation {
|
|
371
|
+
author: string;
|
|
372
|
+
content: string;
|
|
373
|
+
at: Date;
|
|
374
|
+
}
|
|
375
|
+
interface MnemoEvent {
|
|
376
|
+
id: string;
|
|
377
|
+
workspaceId: string;
|
|
378
|
+
agentId?: string;
|
|
379
|
+
/** Multi-tenant ownership: "workspace:<id>" | "user:<id>" | "tenant:<id>" */
|
|
380
|
+
scopeOwner?: string;
|
|
381
|
+
type: "system" | "external" | "user" | "agent" | "scheduled";
|
|
382
|
+
name: string;
|
|
383
|
+
description: string;
|
|
384
|
+
occurredAt: Date;
|
|
385
|
+
durationS?: number;
|
|
386
|
+
source: string;
|
|
387
|
+
relatedEntities: string[];
|
|
388
|
+
annotations: EventAnnotation[];
|
|
389
|
+
/** Per-event sensitivity ceiling — compared via SENSITIVITY_ORDER, never string equality (MED-23).
|
|
390
|
+
* Raise-only: once set, can only be elevated, never lowered (append-only principle). */
|
|
391
|
+
sensitivity: "public" | "internal" | "confidential" | "restricted";
|
|
392
|
+
createdAt: Date;
|
|
393
|
+
metadata: Record<string, unknown>;
|
|
394
|
+
}
|
|
395
|
+
/**
|
|
396
|
+
* A stored chain-of-thought — a question, its reasoning steps, and the conclusion reached.
|
|
397
|
+
*
|
|
398
|
+
* Use for: caching successful reasoning patterns, building a "how I solved X" library.
|
|
399
|
+
* Do NOT use for: final answers/facts (→ MnemoFact) or process steps (→ MnemoWorkflow).
|
|
400
|
+
*
|
|
401
|
+
* worth is GENERATED and decays with disuse — the system prioritises reasoning that
|
|
402
|
+
* has been recalled and applied multiple times. Embeddings are on the `question` field
|
|
403
|
+
* to enable semantic retrieval of "find how I reasoned about problems like this".
|
|
404
|
+
*/
|
|
405
|
+
interface ReasoningStep {
|
|
406
|
+
step: number;
|
|
407
|
+
reasoning: string;
|
|
408
|
+
conclusion?: string;
|
|
409
|
+
}
|
|
410
|
+
interface MnemoReasoning {
|
|
411
|
+
id: string;
|
|
412
|
+
workspaceId: string;
|
|
413
|
+
agentId?: string;
|
|
414
|
+
/** Multi-tenant ownership: "workspace:<id>" | "user:<id>" | "tenant:<id>" */
|
|
415
|
+
scopeOwner?: string;
|
|
416
|
+
question: string;
|
|
417
|
+
chain: ReasoningStep[];
|
|
418
|
+
conclusion: string;
|
|
419
|
+
successCount: number;
|
|
420
|
+
failureCount: number;
|
|
421
|
+
worth: number;
|
|
422
|
+
topicKey?: string;
|
|
423
|
+
embedding?: Float32Array;
|
|
424
|
+
embeddingModel?: string;
|
|
425
|
+
embeddingStale: boolean;
|
|
426
|
+
status: "active" | "archived" | "pruned" | "quarantined" | "golden";
|
|
427
|
+
lastUsedAt?: Date;
|
|
428
|
+
usageCount: number;
|
|
429
|
+
/** Per-reasoning sensitivity ceiling — compared via SENSITIVITY_ORDER, never string equality (MED-23). */
|
|
430
|
+
sensitivity: "public" | "internal" | "confidential" | "restricted";
|
|
431
|
+
createdAt: Date;
|
|
432
|
+
updatedAt: Date;
|
|
433
|
+
metadata: Record<string, unknown>;
|
|
434
|
+
}
|
|
435
|
+
/**
|
|
436
|
+
* An n-ary relation connecting 3 or more memory primitives.
|
|
437
|
+
*
|
|
438
|
+
* Use for: groups of memories that co-activate together under a shared context.
|
|
439
|
+
* Do NOT use for: binary relations between two primitives (→ MnemoRelation via memory_relate).
|
|
440
|
+
*
|
|
441
|
+
* Hebbian: activationCount bumps each time any member is recalled together with the others.
|
|
442
|
+
* worth decays via TD(λ) 0.1-step updates (not Beta-Bernoulli — no success/failure counters).
|
|
443
|
+
* Bitemporal: validFrom/validTo = membership window; createdAt = discovery time.
|
|
444
|
+
* NOTE: No metadata column on the underlying table. No contextEmbeddingModel column.
|
|
445
|
+
*/
|
|
446
|
+
interface MnemoHyperedge {
|
|
447
|
+
id: string;
|
|
448
|
+
workspaceId: string;
|
|
449
|
+
memberIds: string[];
|
|
450
|
+
label?: string;
|
|
451
|
+
description?: string;
|
|
452
|
+
contextQuery?: string;
|
|
453
|
+
contextEmbedding?: Float32Array;
|
|
454
|
+
activationCount: number;
|
|
455
|
+
worth: number;
|
|
456
|
+
validFrom: Date;
|
|
457
|
+
validTo?: Date;
|
|
458
|
+
createdAt: Date;
|
|
459
|
+
}
|
|
460
|
+
interface MnemoCompositionRule {
|
|
461
|
+
id: string;
|
|
462
|
+
workspaceId: string;
|
|
463
|
+
name: string;
|
|
464
|
+
description?: string;
|
|
465
|
+
conditionDsl: unknown;
|
|
466
|
+
actionDsl: unknown;
|
|
467
|
+
priority: number;
|
|
468
|
+
isActive: boolean;
|
|
469
|
+
executionCount: number;
|
|
470
|
+
createdBy?: string;
|
|
471
|
+
source: "manual" | "mined" | "imported";
|
|
472
|
+
metadata: Record<string, unknown>;
|
|
473
|
+
createdAt: Date;
|
|
474
|
+
updatedAt: Date;
|
|
475
|
+
}
|
|
476
|
+
interface MnemoInferenceLogEntry {
|
|
477
|
+
id: string;
|
|
478
|
+
workspaceId: string;
|
|
479
|
+
ruleId: string;
|
|
480
|
+
inputFactIds: string[];
|
|
481
|
+
derivedKind?: string;
|
|
482
|
+
derivedId?: string;
|
|
483
|
+
confidence: number;
|
|
484
|
+
rationale?: string;
|
|
485
|
+
triggeredByQuery?: string;
|
|
486
|
+
conversationId?: string;
|
|
487
|
+
createdAt: Date;
|
|
488
|
+
}
|
|
489
|
+
interface MnemoFactHash {
|
|
490
|
+
workspaceId: string;
|
|
491
|
+
statementHash: string;
|
|
492
|
+
factId: string;
|
|
493
|
+
firstSeenAt: Date;
|
|
494
|
+
lastSeenAt: Date;
|
|
495
|
+
seenCount: number;
|
|
496
|
+
}
|
|
497
|
+
interface ConfidenceMapRow {
|
|
498
|
+
workspaceId: string;
|
|
499
|
+
entityId: string;
|
|
500
|
+
canonicalName: string;
|
|
501
|
+
kind: string;
|
|
502
|
+
factCount: number;
|
|
503
|
+
avgConfidence: number;
|
|
504
|
+
coverageLevel: "expert" | "familiar" | "aware" | "minimal" | "blind";
|
|
505
|
+
freshness: "current" | "recent" | "aging" | "stale";
|
|
506
|
+
topicKey: string;
|
|
507
|
+
memoryCount: number;
|
|
508
|
+
avgWorth: number;
|
|
509
|
+
evidenceVolume: number;
|
|
510
|
+
distinctAttributions: number;
|
|
511
|
+
pinnedCount: number;
|
|
512
|
+
lowStrengthCount: number;
|
|
513
|
+
lastUpdatedAt: Date;
|
|
514
|
+
}
|
|
515
|
+
interface KnowledgeGapRow {
|
|
516
|
+
workspaceId: string;
|
|
517
|
+
topicKey: string;
|
|
518
|
+
avgWorth: number;
|
|
519
|
+
evidenceVolume: number;
|
|
520
|
+
memoryCount: number;
|
|
521
|
+
recallHits30d: number;
|
|
522
|
+
gapScore: number;
|
|
523
|
+
}
|
|
524
|
+
interface TrendPair {
|
|
525
|
+
current: number;
|
|
526
|
+
previous: number;
|
|
527
|
+
delta: number;
|
|
528
|
+
}
|
|
529
|
+
interface MetacognitionTrends {
|
|
530
|
+
recallHitRate: TrendPair;
|
|
531
|
+
/** PROXY: AVG(activation_score) — mnemo_recall_log has no latency column. */
|
|
532
|
+
avgRecallLatency: TrendPair;
|
|
533
|
+
sessionCollapseQuality: TrendPair;
|
|
534
|
+
strategySuccessRate: TrendPair;
|
|
535
|
+
}
|
|
536
|
+
interface SequentialPatternRow {
|
|
537
|
+
workspaceId: string;
|
|
538
|
+
predecessorId: string;
|
|
539
|
+
successorId: string;
|
|
540
|
+
support: number;
|
|
541
|
+
avgLagSeconds: number;
|
|
542
|
+
confidence: number;
|
|
543
|
+
}
|
|
544
|
+
interface PeriodicPatternRow {
|
|
545
|
+
workspaceId: string;
|
|
546
|
+
memoryId: string;
|
|
547
|
+
dayOfWeek: number;
|
|
548
|
+
hourBucket: number;
|
|
549
|
+
slotRecalls: number;
|
|
550
|
+
distinctWeeks: number;
|
|
551
|
+
slotShare: number;
|
|
552
|
+
}
|
|
553
|
+
interface ConditionalPatternRow {
|
|
554
|
+
workspaceId: string;
|
|
555
|
+
queryKey: string;
|
|
556
|
+
factId: string;
|
|
557
|
+
coReturns: number;
|
|
558
|
+
queryTotal: number;
|
|
559
|
+
confidence: number;
|
|
560
|
+
}
|
|
561
|
+
interface CoOccurrencePatternRow {
|
|
562
|
+
workspaceId: string;
|
|
563
|
+
sourceId: string;
|
|
564
|
+
partnerId: string;
|
|
565
|
+
coRecallCount: number;
|
|
566
|
+
hebbianWeight: number;
|
|
567
|
+
}
|
|
568
|
+
type CognitivePrimitive = MnemoFact | MnemoDecision | MnemoEpisode | MnemoEntity | MnemoStrategy | MnemoWorkflow | MnemoSkill | MnemoTask | MnemoEvent | MnemoReasoning;
|
|
569
|
+
type PrimitiveKind = "fact" | "decision" | "episode" | "entity" | "strategy" | "workflow" | "skill" | "task" | "event" | "reasoning" | "hyperedge";
|
|
570
|
+
/**
|
|
571
|
+
* Per-agent self-model / profile store.
|
|
572
|
+
* Populated and rewritten by the reflection cycle (runReflectionCycle).
|
|
573
|
+
* One row per (workspace_id, agent_id) — upserted on every reflection pass.
|
|
574
|
+
*/
|
|
575
|
+
interface MnemoAgentProfile {
|
|
576
|
+
workspaceId: string;
|
|
577
|
+
agentId: string;
|
|
578
|
+
/** Free-text summary generated by the last reflection cycle. */
|
|
579
|
+
summary: string;
|
|
580
|
+
/**
|
|
581
|
+
* Flexible metadata bag.
|
|
582
|
+
* Reserved keys: sessionsSinceReflection (number), lastReflectionAt (ISO string).
|
|
583
|
+
*/
|
|
584
|
+
metadata: Record<string, unknown>;
|
|
585
|
+
createdAt: Date;
|
|
586
|
+
updatedAt: Date;
|
|
587
|
+
}
|
|
588
|
+
|
|
589
|
+
/**
|
|
590
|
+
* The 9 locked relation verbs. This set is CLOSED — do not add values here
|
|
591
|
+
* without a matching SQL migration that updates the CHECK constraint in
|
|
592
|
+
* packages/adapter-postgres/migrations/v3/0001_baseline.sql.
|
|
593
|
+
*
|
|
594
|
+
* Semantics:
|
|
595
|
+
* "related" — Generic symmetric link. Use when no more specific verb applies.
|
|
596
|
+
* "compatible" — A and B are known to work together (e.g. two tools, two strategies).
|
|
597
|
+
* "scoped" — A applies within the scope of B (A is narrower than B).
|
|
598
|
+
* "conflicts_with" — A and B contradict each other; both cannot be true simultaneously.
|
|
599
|
+
* "supersedes" — A replaces B (B is outdated). B should have status "superseded".
|
|
600
|
+
* "not_conflict" — Explicit disambiguation: A and B look contradictory but are not.
|
|
601
|
+
* "derived_from" — A was extracted, inferred, or synthesised from B.
|
|
602
|
+
* "part_of" — A is a structural component of B.
|
|
603
|
+
* "member_of" — A belongs to group or category B.
|
|
604
|
+
*
|
|
605
|
+
* Hebbian learning: `weight` on MnemoRelation strengthens when both endpoints
|
|
606
|
+
* are co-recalled in the same query. This drives the activation cascade in stage 4
|
|
607
|
+
* of the recall pipeline (recall-cold.ts).
|
|
608
|
+
*/
|
|
609
|
+
type RelationVerb = "related" | "compatible" | "scoped" | "conflicts_with" | "supersedes" | "not_conflict" | "derived_from" | "part_of" | "member_of";
|
|
610
|
+
interface MnemoRelation {
|
|
611
|
+
id: string;
|
|
612
|
+
workspaceId: string;
|
|
613
|
+
sourceId: string;
|
|
614
|
+
sourceType: string;
|
|
615
|
+
targetId: string;
|
|
616
|
+
targetType: string;
|
|
617
|
+
verb: RelationVerb;
|
|
618
|
+
weight: number;
|
|
619
|
+
/** Timestamp of the last co-recall event — used to compute STDP Δt (Wave Y, §25.3). */
|
|
620
|
+
lastCoRecallAt?: Date;
|
|
621
|
+
createdAt: Date;
|
|
622
|
+
updatedAt: Date;
|
|
623
|
+
metadata: Record<string, unknown>;
|
|
624
|
+
}
|
|
625
|
+
interface MnemoCitation {
|
|
626
|
+
id: string;
|
|
627
|
+
workspaceId: string;
|
|
628
|
+
sourceId: string;
|
|
629
|
+
sourceType: string;
|
|
630
|
+
derivedId: string;
|
|
631
|
+
derivedType: string;
|
|
632
|
+
citationType: "extraction" | "inference" | "consolidation" | "federation";
|
|
633
|
+
confidence: number;
|
|
634
|
+
createdAt: Date;
|
|
635
|
+
}
|
|
636
|
+
|
|
637
|
+
type SessionStatus = "active" | "collapsed" | "archived";
|
|
638
|
+
interface MnemoSession {
|
|
639
|
+
id: string;
|
|
640
|
+
workspaceId: string;
|
|
641
|
+
agentId?: string;
|
|
642
|
+
actorId?: string;
|
|
643
|
+
status: SessionStatus;
|
|
644
|
+
turnCount: number;
|
|
645
|
+
tokenCount: number;
|
|
646
|
+
/** kept as optional for backward-compat with any stored snapshots */
|
|
647
|
+
collapseTriggeredAt?: Date;
|
|
648
|
+
collapsedAt?: Date;
|
|
649
|
+
openedAt: Date;
|
|
650
|
+
scratch?: Record<string, unknown>;
|
|
651
|
+
metadata: Record<string, unknown>;
|
|
652
|
+
/** §14 A/B measurement — which prompt version was active when this session ran. */
|
|
653
|
+
activePromptVersionId?: string | null;
|
|
654
|
+
}
|
|
655
|
+
interface SessionTurn {
|
|
656
|
+
id: string;
|
|
657
|
+
workspaceId: string;
|
|
658
|
+
sessionId: string;
|
|
659
|
+
turnIndex: number;
|
|
660
|
+
role: "user" | "assistant" | "system" | "tool";
|
|
661
|
+
content: string;
|
|
662
|
+
tokenCount?: number;
|
|
663
|
+
pinned?: boolean;
|
|
664
|
+
hint?: string;
|
|
665
|
+
createdAt: Date;
|
|
666
|
+
}
|
|
667
|
+
|
|
668
|
+
type OutboxEventType = "vector_upsert" | "vector_delete" | "cache_bust" | "cache_set" | "queue_job" | "webhook_fire" | "hyperedge_bump" | "lsh_upsert";
|
|
669
|
+
interface OutboxEntry {
|
|
670
|
+
id: string;
|
|
671
|
+
workspaceId: string;
|
|
672
|
+
eventType: OutboxEventType;
|
|
673
|
+
payload: Record<string, unknown>;
|
|
674
|
+
createdAt: Date;
|
|
675
|
+
claimedAt?: Date;
|
|
676
|
+
processedAt?: Date;
|
|
677
|
+
attempts: number;
|
|
678
|
+
lastError?: string;
|
|
679
|
+
}
|
|
680
|
+
interface WebhookFirePayload {
|
|
681
|
+
webhookId: string;
|
|
682
|
+
workspaceId: string;
|
|
683
|
+
url: string;
|
|
684
|
+
eventType: string;
|
|
685
|
+
payload: Record<string, unknown>;
|
|
686
|
+
secret: string;
|
|
687
|
+
}
|
|
688
|
+
|
|
689
|
+
type AuditAction = "recall" | "create" | "update" | "delete" | "hard_delete" | "export" | "self_edit" | "session_open" | "session_close" | "key_create" | "key_rotate" | "key_revoke" | "admin_access" | "federation_sync" | "erasure_initiated" | "erasure_complete" | "federation_cert_pin_mismatch" | "federation_cert_rotated" | "plugin_installed" | "plugin_removed" | "workspace_created" | "workspace_deleted" | "rls_policy_changed" | "mfa_verified" | "ip_denied";
|
|
690
|
+
/**
|
|
691
|
+
* Who performed the audited operation (SECURITY_ARCHITECTURE.md §6 "Audit
|
|
692
|
+
* Trail"). The distinction is load-bearing for the threat model: insider-access
|
|
693
|
+
* detection and federation-sync provenance both rely on being able to tell a
|
|
694
|
+
* human `user`, an autonomous `agent`, an internal `system` job, and an inbound
|
|
695
|
+
* `federation` peer apart.
|
|
696
|
+
*/
|
|
697
|
+
type AuditActorType = "agent" | "user" | "system" | "federation";
|
|
698
|
+
interface AuditLogEntry {
|
|
699
|
+
id: string;
|
|
700
|
+
workspaceId: string;
|
|
701
|
+
/**
|
|
702
|
+
* Origin of the operation. Threaded from the auth context. When omitted, the
|
|
703
|
+
* storage adapter resolves it via {@link resolveAuditActorType} (back-compat:
|
|
704
|
+
* `user` when an actorId is present, else `system`).
|
|
705
|
+
*/
|
|
706
|
+
actorType?: AuditActorType;
|
|
707
|
+
actorId?: string;
|
|
708
|
+
action: AuditAction;
|
|
709
|
+
resourceKind: string;
|
|
710
|
+
resourceId?: string;
|
|
711
|
+
ipAddress?: string;
|
|
712
|
+
userAgent?: string;
|
|
713
|
+
detail?: Record<string, unknown>;
|
|
714
|
+
isTerminal: boolean;
|
|
715
|
+
merkleHash?: Uint8Array;
|
|
716
|
+
createdAt: Date;
|
|
717
|
+
}
|
|
718
|
+
/**
|
|
719
|
+
* Resolve the `actor_type` to persist for an audit entry.
|
|
720
|
+
*
|
|
721
|
+
* - Prefer the explicit `actorType` threaded from the auth context (the correct
|
|
722
|
+
* value for `agent` / `federation` / `system` / `user` origins).
|
|
723
|
+
* - Back-compat fallback when callers don't yet pass one: `user` if an actorId
|
|
724
|
+
* is present (matches the historical hardcoded value), otherwise `system`.
|
|
725
|
+
*
|
|
726
|
+
* Pure (no I/O) so it can be unit-tested and shared by every StorageAdapter
|
|
727
|
+
* implementation without coupling `@mnemo-ai/types` to any infrastructure.
|
|
728
|
+
*/
|
|
729
|
+
declare function resolveAuditActorType(entry: Pick<AuditLogEntry, "actorType" | "actorId">): AuditActorType;
|
|
730
|
+
|
|
731
|
+
type Sensitivity = "public" | "internal" | "confidential" | "restricted";
|
|
732
|
+
type Attribution = "user_stated" | "user_belief" | "objective_fact" | "inferred";
|
|
733
|
+
/**
|
|
734
|
+
* Five decay classes mapping PrimitiveKind to a half-life (spec §25.2).
|
|
735
|
+
* "entity" has half-life 0 (immortal — no decay ever applied).
|
|
736
|
+
*/
|
|
737
|
+
type DecayClass = "procedural" | "semantic" | "episodic" | "entity" | "reasoning";
|
|
738
|
+
interface PaginatedResult<T> {
|
|
739
|
+
items: T[];
|
|
740
|
+
total: number;
|
|
741
|
+
offset: number;
|
|
742
|
+
limit: number;
|
|
743
|
+
hasMore: boolean;
|
|
744
|
+
}
|
|
745
|
+
interface WorthDelta {
|
|
746
|
+
success: number;
|
|
747
|
+
failure: number;
|
|
748
|
+
creditWeight: number;
|
|
749
|
+
}
|
|
750
|
+
interface VectorEmbedding {
|
|
751
|
+
id: string;
|
|
752
|
+
workspaceId: string;
|
|
753
|
+
primitiveKind: string;
|
|
754
|
+
vector: Float32Array;
|
|
755
|
+
model: string;
|
|
756
|
+
}
|
|
757
|
+
interface VectorQuery {
|
|
758
|
+
workspaceId: string;
|
|
759
|
+
vector: Float32Array;
|
|
760
|
+
limit: number;
|
|
761
|
+
minSimilarity?: number;
|
|
762
|
+
filter?: Record<string, unknown>;
|
|
763
|
+
}
|
|
764
|
+
interface VectorSearchResult {
|
|
765
|
+
id: string;
|
|
766
|
+
score: number;
|
|
767
|
+
primitiveKind: string;
|
|
768
|
+
}
|
|
769
|
+
interface HealthStatus {
|
|
770
|
+
status: "ok" | "degraded" | "down";
|
|
771
|
+
latencyMs: number;
|
|
772
|
+
detail?: string;
|
|
773
|
+
}
|
|
774
|
+
|
|
775
|
+
declare const ConditionDslSchema: z.ZodObject<{
|
|
776
|
+
all: z.ZodArray<z.ZodDiscriminatedUnion<[z.ZodObject<{
|
|
777
|
+
op: z.ZodLiteral<"fact_kind">;
|
|
778
|
+
kind: z.ZodString;
|
|
779
|
+
bind: z.ZodOptional<z.ZodString>;
|
|
780
|
+
}, z.core.$strict>, z.ZodObject<{
|
|
781
|
+
op: z.ZodLiteral<"topic_key_in">;
|
|
782
|
+
topicKeys: z.ZodArray<z.ZodString>;
|
|
783
|
+
bind: z.ZodOptional<z.ZodString>;
|
|
784
|
+
}, z.core.$strict>, z.ZodObject<{
|
|
785
|
+
op: z.ZodLiteral<"text_contains">;
|
|
786
|
+
needle: z.ZodString;
|
|
787
|
+
bind: z.ZodOptional<z.ZodString>;
|
|
788
|
+
}, z.core.$strict>, z.ZodObject<{
|
|
789
|
+
op: z.ZodLiteral<"relation">;
|
|
790
|
+
from: z.ZodString;
|
|
791
|
+
to: z.ZodString;
|
|
792
|
+
verb: z.ZodEnum<{
|
|
793
|
+
related: "related";
|
|
794
|
+
compatible: "compatible";
|
|
795
|
+
scoped: "scoped";
|
|
796
|
+
conflicts_with: "conflicts_with";
|
|
797
|
+
supersedes: "supersedes";
|
|
798
|
+
not_conflict: "not_conflict";
|
|
799
|
+
derived_from: "derived_from";
|
|
800
|
+
part_of: "part_of";
|
|
801
|
+
member_of: "member_of";
|
|
802
|
+
}>;
|
|
803
|
+
}, z.core.$strict>, z.ZodObject<{
|
|
804
|
+
op: z.ZodLiteral<"fact_value">;
|
|
805
|
+
subject: z.ZodString;
|
|
806
|
+
predicate: z.ZodString;
|
|
807
|
+
valueType: z.ZodEnum<{
|
|
808
|
+
number: "number";
|
|
809
|
+
duration: "duration";
|
|
810
|
+
}>;
|
|
811
|
+
compare: z.ZodOptional<z.ZodObject<{
|
|
812
|
+
lt: z.ZodOptional<z.ZodOptional<z.ZodUnion<readonly [z.ZodNumber, z.ZodString]>>>;
|
|
813
|
+
gt: z.ZodOptional<z.ZodOptional<z.ZodUnion<readonly [z.ZodNumber, z.ZodString]>>>;
|
|
814
|
+
lte: z.ZodOptional<z.ZodOptional<z.ZodUnion<readonly [z.ZodNumber, z.ZodString]>>>;
|
|
815
|
+
gte: z.ZodOptional<z.ZodOptional<z.ZodUnion<readonly [z.ZodNumber, z.ZodString]>>>;
|
|
816
|
+
}, z.core.$strict>>;
|
|
817
|
+
bind: z.ZodOptional<z.ZodString>;
|
|
818
|
+
}, z.core.$strict>], "op">>;
|
|
819
|
+
}, z.core.$strict>;
|
|
820
|
+
type ConditionDsl = z.infer<typeof ConditionDslSchema>;
|
|
821
|
+
declare const ActionDslSchema: z.ZodDiscriminatedUnion<[z.ZodObject<{
|
|
822
|
+
op: z.ZodLiteral<"derive_fact">;
|
|
823
|
+
statementTemplate: z.ZodString;
|
|
824
|
+
kind: z.ZodDefault<z.ZodString>;
|
|
825
|
+
topicKey: z.ZodOptional<z.ZodString>;
|
|
826
|
+
baseConfidence: z.ZodDefault<z.ZodNumber>;
|
|
827
|
+
sensitivity: z.ZodDefault<z.ZodEnum<{
|
|
828
|
+
public: "public";
|
|
829
|
+
internal: "internal";
|
|
830
|
+
confidential: "confidential";
|
|
831
|
+
restricted: "restricted";
|
|
832
|
+
}>>;
|
|
833
|
+
type: z.ZodDefault<z.ZodLiteral<"fact">>;
|
|
834
|
+
}, z.core.$strict>, z.ZodObject<{
|
|
835
|
+
op: z.ZodLiteral<"derive_warning">;
|
|
836
|
+
statementTemplate: z.ZodString;
|
|
837
|
+
kind: z.ZodDefault<z.ZodString>;
|
|
838
|
+
topicKey: z.ZodOptional<z.ZodString>;
|
|
839
|
+
baseConfidence: z.ZodDefault<z.ZodNumber>;
|
|
840
|
+
sensitivity: z.ZodDefault<z.ZodEnum<{
|
|
841
|
+
public: "public";
|
|
842
|
+
internal: "internal";
|
|
843
|
+
confidential: "confidential";
|
|
844
|
+
restricted: "restricted";
|
|
845
|
+
}>>;
|
|
846
|
+
type: z.ZodDefault<z.ZodLiteral<"warning">>;
|
|
847
|
+
}, z.core.$strict>], "op">;
|
|
848
|
+
type ActionDsl = z.infer<typeof ActionDslSchema>;
|
|
849
|
+
interface DerivedInference {
|
|
850
|
+
ruleId: string;
|
|
851
|
+
ruleName: string;
|
|
852
|
+
inputFactIds: string[];
|
|
853
|
+
derivedKind: string;
|
|
854
|
+
derivedStatement: string;
|
|
855
|
+
confidence: number;
|
|
856
|
+
type: "fact" | "warning";
|
|
857
|
+
rationale: string;
|
|
858
|
+
materialisedFactId?: string;
|
|
859
|
+
}
|
|
860
|
+
declare function parseConditionDsl(raw: unknown): ConditionDsl;
|
|
861
|
+
declare function parseActionDsl(raw: unknown): ActionDsl;
|
|
862
|
+
|
|
863
|
+
type Provenance = "user_stated" | "user_belief" | "objective_fact" | "inferred" | "extracted" | "federation_received" | "consolidation";
|
|
864
|
+
interface RecallFilter {
|
|
865
|
+
kinds?: PrimitiveKind[];
|
|
866
|
+
tags?: string[];
|
|
867
|
+
validAfter?: Date;
|
|
868
|
+
validBefore?: Date;
|
|
869
|
+
minWorth?: number;
|
|
870
|
+
minConfidence?: number;
|
|
871
|
+
sensitivity?: Sensitivity[];
|
|
872
|
+
provenance?: Provenance[];
|
|
873
|
+
entityId?: string;
|
|
874
|
+
sessionId?: string;
|
|
875
|
+
scope?: "global" | "conversation";
|
|
876
|
+
/** Optional entity/project reference — filters to facts scoped to this entity id. */
|
|
877
|
+
scopeRef?: string;
|
|
878
|
+
/** P11 — when provided, restrict recall to facts attributed to this actor. */
|
|
879
|
+
actorId?: string;
|
|
880
|
+
}
|
|
881
|
+
interface RecallQuery {
|
|
882
|
+
workspaceId: string;
|
|
883
|
+
text: string;
|
|
884
|
+
embedding?: Float32Array;
|
|
885
|
+
filter?: RecallFilter;
|
|
886
|
+
limit?: number;
|
|
887
|
+
offset?: number;
|
|
888
|
+
includeArchived?: boolean;
|
|
889
|
+
materialiseInferences?: boolean;
|
|
890
|
+
conversationId?: string;
|
|
891
|
+
/** Bitemporal time-travel recall timestamp. */
|
|
892
|
+
asOf?: Date;
|
|
893
|
+
/** When true, bypasses the worth serving gate (spec §11). Default: gate is ON. */
|
|
894
|
+
includeLowWorth?: boolean;
|
|
895
|
+
/**
|
|
896
|
+
* Approximate remaining token budget (spec §17 CALMem ladder).
|
|
897
|
+
* Controls which recall tiers are attempted:
|
|
898
|
+
* <500 → skip (return empty)
|
|
899
|
+
* <2000 → Tier 1 (hot) only, cap 3 hits
|
|
900
|
+
* <8000 → Tier 1+2 (hot+pointer), cap 5 hits
|
|
901
|
+
* ≥8000 → full hot→pointer→cold pipeline
|
|
902
|
+
* absent → full pipeline (backward compatible)
|
|
903
|
+
*/
|
|
904
|
+
tokenBudget?: number;
|
|
905
|
+
/** Opt-in LLM rerank of cold-recall hits (RecMem-gated). Default: off. */
|
|
906
|
+
rerank?: boolean;
|
|
907
|
+
/** Min recurrence signal among candidates to spend an LLM rerank call (spec §1/§2). Default 0.6. */
|
|
908
|
+
recurrenceThreshold?: number;
|
|
909
|
+
/** HyDE pre-step (arXiv:2212.10496): LLM writes a hypothetical answer doc; its
|
|
910
|
+
* embedding is averaged with the query embedding before HNSW search. Default: off.
|
|
911
|
+
* Degrades gracefully when ctx.llm is absent. Zero diff when false.
|
|
912
|
+
*/
|
|
913
|
+
hyde?: boolean;
|
|
914
|
+
/** B5.1 Explicit search mode: "lexical" | "semantic" | "hybrid" | "auto" (default: "auto"). */
|
|
915
|
+
mode?: "lexical" | "semantic" | "hybrid" | "auto";
|
|
916
|
+
/** Hybrid vector weight [0, 1] (0 = FTS-only, 1 = vector-only, 0.5 = blend). Deprecated in favor of mode. */
|
|
917
|
+
vectorWeight?: number;
|
|
918
|
+
/**
|
|
919
|
+
* Hybrid FTS arm: after HNSW search, also query text_lemmatized (idx_fact_fts
|
|
920
|
+
* from migration 0047) and merge unique candidates at minSimilarity baseline.
|
|
921
|
+
* Default: off. Zero diff when false.
|
|
922
|
+
*/
|
|
923
|
+
hybridFts?: boolean;
|
|
924
|
+
/**
|
|
925
|
+
* §36 — true when the workspace's embeddings are mid-migration to a new model.
|
|
926
|
+
* When set, recall-cold leans on FTS (0.7) over vector (0.3). Derived at the
|
|
927
|
+
* orchestrator/transport layer from detectStale(...).total > 0. Default
|
|
928
|
+
* (undefined/false): normal weights (fts 0.4 / vector 0.6).
|
|
929
|
+
*/
|
|
930
|
+
embeddingMigrationActive?: boolean;
|
|
931
|
+
}
|
|
932
|
+
interface RelationSummary {
|
|
933
|
+
id: string;
|
|
934
|
+
targetId: string;
|
|
935
|
+
targetKind: PrimitiveKind;
|
|
936
|
+
verb: RelationVerb;
|
|
937
|
+
weight: number;
|
|
938
|
+
}
|
|
939
|
+
interface RecallHit {
|
|
940
|
+
id: string;
|
|
941
|
+
primitive: PrimitiveKind;
|
|
942
|
+
content: string;
|
|
943
|
+
score: number;
|
|
944
|
+
sensitivity: Sensitivity;
|
|
945
|
+
injectionScore: number;
|
|
946
|
+
provenance: Provenance;
|
|
947
|
+
origin: "local" | `federation:${string}` | `plugin:${string}`;
|
|
948
|
+
contested: boolean;
|
|
949
|
+
validFrom: Date;
|
|
950
|
+
validTo: Date | null;
|
|
951
|
+
tags: string[];
|
|
952
|
+
relations: RelationSummary[];
|
|
953
|
+
worth?: number;
|
|
954
|
+
worthLowerBound?: number;
|
|
955
|
+
factKind?: string;
|
|
956
|
+
/**
|
|
957
|
+
* Hyperedges this fact belongs to. During cold recall, members of a hyperedge
|
|
958
|
+
* with worth > 0.5 are expanded into scored hits (score = parentScore ×
|
|
959
|
+
* hyperedge.worth) by expandHyperedgeMembers. This field is the structural
|
|
960
|
+
* input that expansion consumes.
|
|
961
|
+
*/
|
|
962
|
+
hyperedges?: Array<{
|
|
963
|
+
id: string;
|
|
964
|
+
coMembers: string[];
|
|
965
|
+
label?: string;
|
|
966
|
+
worth?: number;
|
|
967
|
+
}>;
|
|
968
|
+
embedding?: number[];
|
|
969
|
+
scope?: "global" | "conversation";
|
|
970
|
+
scopeRef?: string;
|
|
971
|
+
/**
|
|
972
|
+
* Multi-tenant ownership label. Format: "workspace:<id>" | "user:<id>" | "tenant:<id>".
|
|
973
|
+
* Absent on legacy facts created before scope_owner was introduced.
|
|
974
|
+
* Used by multi-level recall to filter hits to their expected ownership tier.
|
|
975
|
+
*/
|
|
976
|
+
scopeOwner?: string;
|
|
977
|
+
/**
|
|
978
|
+
* P11 — the actor (userId or apiKeyPrefix) that created this memory.
|
|
979
|
+
* Null for rows created before P11 was deployed (pre-attribution era).
|
|
980
|
+
*/
|
|
981
|
+
actorId?: string | null;
|
|
982
|
+
/** B5.5 Lexical score (FTS rank signal). */
|
|
983
|
+
lexicalScore?: number;
|
|
984
|
+
/** B5.5 Vector score (HNSW cosine similarity signal). */
|
|
985
|
+
vectorScore?: number;
|
|
986
|
+
}
|
|
987
|
+
interface RecallResponse {
|
|
988
|
+
hits: RecallHit[];
|
|
989
|
+
total: number;
|
|
990
|
+
query: {
|
|
991
|
+
text: string;
|
|
992
|
+
limit: number;
|
|
993
|
+
offset: number;
|
|
994
|
+
};
|
|
995
|
+
latencyMs: number;
|
|
996
|
+
fromHotTier: boolean;
|
|
997
|
+
inferences?: DerivedInference[];
|
|
998
|
+
/**
|
|
999
|
+
* Search mode used to produce these hits.
|
|
1000
|
+
* "vector" — normal HNSW semantic search (embed adapter available).
|
|
1001
|
+
* "fts" — full-text search fallback via text_lemmatized (no embed adapter configured).
|
|
1002
|
+
* Results are ranked by ts_rank rather than cosine similarity.
|
|
1003
|
+
* Absent when the response came from the hot tier (fromHotTier: true).
|
|
1004
|
+
*/
|
|
1005
|
+
searchMode?: "vector" | "fts" | "lexical" | "semantic" | "hybrid" | "auto";
|
|
1006
|
+
/** B5.10 Debug metadata for search execution tracing. */
|
|
1007
|
+
debug?: {
|
|
1008
|
+
modeRequested: string;
|
|
1009
|
+
modeUsed: string;
|
|
1010
|
+
spaceId?: string;
|
|
1011
|
+
tiersConsulted: string[];
|
|
1012
|
+
cacheHit: boolean;
|
|
1013
|
+
fallback: boolean;
|
|
1014
|
+
};
|
|
1015
|
+
}
|
|
1016
|
+
type RememberKind = PrimitiveKind;
|
|
1017
|
+
interface RememberRequest {
|
|
1018
|
+
workspaceId: string;
|
|
1019
|
+
kind: RememberKind;
|
|
1020
|
+
content: string;
|
|
1021
|
+
subject?: string;
|
|
1022
|
+
confidence?: number;
|
|
1023
|
+
conversationId?: string;
|
|
1024
|
+
agentId?: string;
|
|
1025
|
+
topicKey?: string;
|
|
1026
|
+
sensitivity?: Sensitivity;
|
|
1027
|
+
provenance?: Provenance;
|
|
1028
|
+
tags?: string[];
|
|
1029
|
+
sessionId?: string;
|
|
1030
|
+
metadata?: Record<string, unknown>;
|
|
1031
|
+
/** Scope of the fact — default "global". Use "personal" (input-only shorthand) to store in the user's personal workspace. */
|
|
1032
|
+
scope?: "global" | "conversation" | "personal";
|
|
1033
|
+
/** Optional entity/project ref — pairs with scope to namespace facts (e.g. 'mnemosyne', 'project:abc'). */
|
|
1034
|
+
scopeRef?: string;
|
|
1035
|
+
/**
|
|
1036
|
+
* Ownership level for multi-tenant routing.
|
|
1037
|
+
* "workspace:<id>" | "user:<id>" | "tenant:<id>"
|
|
1038
|
+
* Default: "workspace:<workspaceId>".
|
|
1039
|
+
* Use "user:<userId>" for personal preferences, "tenant:<tenantId>" for company-wide facts.
|
|
1040
|
+
*/
|
|
1041
|
+
scopeOwner?: string;
|
|
1042
|
+
/**
|
|
1043
|
+
* Host-side pre-computed embedding. When supplied, the cognitive engine
|
|
1044
|
+
* skips its own embed pass and stores this vector directly — the server
|
|
1045
|
+
* never needs its own LLM credentials for the write path. Must be the
|
|
1046
|
+
* same model/dimensionality as the workspace's recall embedding
|
|
1047
|
+
* (default: OpenAI text-embedding-3-small, 1536 dims).
|
|
1048
|
+
*/
|
|
1049
|
+
precomputedEmbedding?: Float32Array;
|
|
1050
|
+
}
|
|
1051
|
+
interface RememberResponse {
|
|
1052
|
+
id: string;
|
|
1053
|
+
kind: RememberKind;
|
|
1054
|
+
staged: boolean;
|
|
1055
|
+
actorId?: string;
|
|
1056
|
+
}
|
|
1057
|
+
|
|
1058
|
+
declare const SENSITIVITY_ORDER: Record<Sensitivity, number>;
|
|
1059
|
+
/**
|
|
1060
|
+
* Returns true if sensitivity `a` is at or above tier `b`.
|
|
1061
|
+
* Use this when checking if a fact's sensitivity is within the caller's ceiling.
|
|
1062
|
+
*
|
|
1063
|
+
* @example
|
|
1064
|
+
* // Allow access only if caller's ceiling >= fact's sensitivity
|
|
1065
|
+
* if (!sensitivityAtLeast(auth.maxSensitivity, fact.sensitivity)) {
|
|
1066
|
+
* return notFound(); // 404, never 403 (anti-probing rule)
|
|
1067
|
+
* }
|
|
1068
|
+
*/
|
|
1069
|
+
declare function sensitivityAtLeast(a: Sensitivity, b: Sensitivity): boolean;
|
|
1070
|
+
type ApiKeyType = "mk_live_" | "mk_test_" | "mk_sess_" | "mk_fed_" | "mk_admin_";
|
|
1071
|
+
type KeyScope = "memory:read" | "memory:write" | "memory:delete" | "memory:admin" | "memory:hard_delete" | "memory:session" | "memory:task" | "memory:event" | "memory:self_edit" | "memory:procedural" | "memory:reasoning" | "memory:export" | "memory:governance" | "memory:subscribe" | "session:read" | "session:write" | "session:manage" | "entity:read" | "entity:write" | "entity:admin" | "federation:read" | "federation:write" | "federation:manage" | "memory:federation" | "admin:keys" | "admin:workspace" | "admin:billing" | "admin:tenant";
|
|
1072
|
+
declare const ALL_SCOPES: ReadonlyArray<KeyScope>;
|
|
1073
|
+
declare const SPEC_SCOPES: readonly ["memory:read", "memory:write", "memory:delete", "memory:hard_delete", "memory:session", "memory:task", "memory:event", "memory:self_edit", "memory:procedural", "memory:reasoning", "memory:export", "memory:admin", "memory:federation", "memory:governance", "memory:subscribe"];
|
|
1074
|
+
type SpecScope = (typeof SPEC_SCOPES)[number];
|
|
1075
|
+
interface KeyDeprecation {
|
|
1076
|
+
deprecated: true;
|
|
1077
|
+
/** ISO-8601 sunset instant = deprecatedAt + 7 days. */
|
|
1078
|
+
sunset: string;
|
|
1079
|
+
}
|
|
1080
|
+
/** One row of markUsed history, newest first (for anomaly detection). */
|
|
1081
|
+
interface KeyUsageEvent {
|
|
1082
|
+
ipAddress: string;
|
|
1083
|
+
at: Date;
|
|
1084
|
+
}
|
|
1085
|
+
interface RotateKeyResult {
|
|
1086
|
+
/** The full new key shown ONCE (SECURITY.md §3.4). */
|
|
1087
|
+
newKey: string;
|
|
1088
|
+
newKeyId: string;
|
|
1089
|
+
/** The old key's ISO sunset (deprecatedAt + 7 days). */
|
|
1090
|
+
sunset: string;
|
|
1091
|
+
}
|
|
1092
|
+
interface KeyEscrowEntry {
|
|
1093
|
+
keyId: string;
|
|
1094
|
+
prefix: ApiKeyType;
|
|
1095
|
+
workspaceId: string;
|
|
1096
|
+
scopes: KeyScope[];
|
|
1097
|
+
action: "rotate" | "revoke" | "break_glass";
|
|
1098
|
+
reason: string;
|
|
1099
|
+
escrowedAt: Date;
|
|
1100
|
+
}
|
|
1101
|
+
interface AuthContext {
|
|
1102
|
+
workspaceId: string;
|
|
1103
|
+
actorId: string;
|
|
1104
|
+
actorType: "agent" | "user" | "system" | "federation";
|
|
1105
|
+
scopes: ReadonlyArray<KeyScope>;
|
|
1106
|
+
keyType?: ApiKeyType;
|
|
1107
|
+
federationPeer?: string;
|
|
1108
|
+
sessionId?: string;
|
|
1109
|
+
metadata?: Record<string, unknown>;
|
|
1110
|
+
/**
|
|
1111
|
+
* Set when the authenticating key is in its 7-day deprecation grace
|
|
1112
|
+
* (SECURITY.md §3.3). The middleware emits Deprecation/Sunset/
|
|
1113
|
+
* Mnemosyne-Key-Deprecated headers from this.
|
|
1114
|
+
*/
|
|
1115
|
+
keyDeprecation?: KeyDeprecation;
|
|
1116
|
+
/**
|
|
1117
|
+
* Per-key recall sensitivity ceiling carried by the key grant (§5, MED-23).
|
|
1118
|
+
* When present it can only LOWER the effective recall ceiling below the
|
|
1119
|
+
* process-wide MNEMO_SENSITIVITY_CEILING — never raise it (the effective
|
|
1120
|
+
* ceiling is min(envCeiling, keyMax) via SENSITIVITY_ORDER). Undefined for
|
|
1121
|
+
* legacy/non-scoped keys → the process-wide ceiling applies unchanged.
|
|
1122
|
+
*/
|
|
1123
|
+
maxSensitivity?: Sensitivity;
|
|
1124
|
+
}
|
|
1125
|
+
type AuthResult = {
|
|
1126
|
+
ok: true;
|
|
1127
|
+
context: AuthContext;
|
|
1128
|
+
} | {
|
|
1129
|
+
ok: false;
|
|
1130
|
+
code: "UNAUTHORIZED" | "FORBIDDEN" | "TOKEN_EXPIRED" | "REVOKED" | "INVALID";
|
|
1131
|
+
reason: string;
|
|
1132
|
+
};
|
|
1133
|
+
interface InheritedContext {
|
|
1134
|
+
workspaceId: string;
|
|
1135
|
+
actorId: string;
|
|
1136
|
+
actorType: "agent" | "user" | "system";
|
|
1137
|
+
scopes: KeyScope[];
|
|
1138
|
+
hostSignature?: string;
|
|
1139
|
+
}
|
|
1140
|
+
interface RawCredentials {
|
|
1141
|
+
bearer?: string;
|
|
1142
|
+
apiKey?: string;
|
|
1143
|
+
clientCert?: Uint8Array;
|
|
1144
|
+
inherited?: InheritedContext;
|
|
1145
|
+
/** SEC-03: client IP for allowlist enforcement in ScopedApiKeyAdapter */
|
|
1146
|
+
clientIp?: string;
|
|
1147
|
+
/** Break-glass: TOTP code for mk_admin_ keys (SECURITY.md §3.1). */
|
|
1148
|
+
mfaToken?: string;
|
|
1149
|
+
}
|
|
1150
|
+
interface AuthOperation {
|
|
1151
|
+
action: KeyScope;
|
|
1152
|
+
resource?: string;
|
|
1153
|
+
workspaceId?: string;
|
|
1154
|
+
}
|
|
1155
|
+
interface AuthAdapter {
|
|
1156
|
+
readonly id: string;
|
|
1157
|
+
authenticate(credentials: RawCredentials): Promise<AuthResult>;
|
|
1158
|
+
authorize(context: AuthContext, operation: AuthOperation): Promise<void>;
|
|
1159
|
+
healthCheck(): Promise<HealthStatus>;
|
|
1160
|
+
}
|
|
1161
|
+
interface ApiKeyRecord {
|
|
1162
|
+
keyId: string;
|
|
1163
|
+
prefix: ApiKeyType;
|
|
1164
|
+
hashedSecret: string;
|
|
1165
|
+
workspaceId: string;
|
|
1166
|
+
scopes: KeyScope[];
|
|
1167
|
+
status: "active" | "deprecated" | "revoked";
|
|
1168
|
+
expiresAt: Date | null;
|
|
1169
|
+
rotatedFromId?: string;
|
|
1170
|
+
ipAllowlist?: string[];
|
|
1171
|
+
createdAt: Date;
|
|
1172
|
+
lastUsedAt?: Date;
|
|
1173
|
+
/** Set when status flips to "deprecated" during rotation (§3.3). */
|
|
1174
|
+
deprecatedAt?: Date | null;
|
|
1175
|
+
/** TOTP shared secret (base32) for mk_admin_ break-glass keys. */
|
|
1176
|
+
mfaSecret?: string | null;
|
|
1177
|
+
/** AB6.2: workspace.is_test flag — populated by store to enable test/prod key isolation. */
|
|
1178
|
+
isTest?: boolean;
|
|
1179
|
+
/**
|
|
1180
|
+
* Per-key recall sensitivity ceiling grant (§5). When set, it lowers the
|
|
1181
|
+
* effective recall ceiling for requests made with this key below the
|
|
1182
|
+
* process-wide MNEMO_SENSITIVITY_CEILING (never raises it). Absent on legacy
|
|
1183
|
+
* keys → the process-wide ceiling applies unchanged.
|
|
1184
|
+
*/
|
|
1185
|
+
maxSensitivity?: Sensitivity;
|
|
1186
|
+
}
|
|
1187
|
+
interface ApiKeyStore {
|
|
1188
|
+
lookup(prefix: ApiKeyType, keyId: string): Promise<ApiKeyRecord | null>;
|
|
1189
|
+
markUsed(keyId: string, ipAddress: string): Promise<void>;
|
|
1190
|
+
revoke(keyId: string, reason: string): Promise<void>;
|
|
1191
|
+
/** Newest-first usage history for anomaly detection. */
|
|
1192
|
+
recentUsage(keyId: string, limit: number): Promise<KeyUsageEvent[]>;
|
|
1193
|
+
/** Flip a key to deprecated with a grace window (rotation step 3). */
|
|
1194
|
+
deprecate(keyId: string, deprecatedAt: Date): Promise<void>;
|
|
1195
|
+
/** Persist a new key record (rotation step 1); returns nothing. */
|
|
1196
|
+
insert(record: ApiKeyRecord): Promise<void>;
|
|
1197
|
+
/** Append-only escrow of key METADATA (never the secret) for forensics. */
|
|
1198
|
+
escrow(entry: KeyEscrowEntry): Promise<void>;
|
|
1199
|
+
}
|
|
1200
|
+
type DeploymentTier = "personal" | "team" | "cloud" | "embedded";
|
|
1201
|
+
type ApprovalTrigger = "delete_fact" | "overwrite_decision" | "write_entity" | "cross_agent_read" | "bulk_export" | "federation_share" | "procedural_evolution" | "task_delegation";
|
|
1202
|
+
interface SelfEditPolicy {
|
|
1203
|
+
enabled: boolean;
|
|
1204
|
+
maxWorthDelta?: number;
|
|
1205
|
+
}
|
|
1206
|
+
interface AgentMemoryAccess {
|
|
1207
|
+
agentId: string;
|
|
1208
|
+
workspaceId: string;
|
|
1209
|
+
readScopes: SpecScope[];
|
|
1210
|
+
writeScopes: SpecScope[];
|
|
1211
|
+
selfEdit: SelfEditPolicy;
|
|
1212
|
+
taskScopes: {
|
|
1213
|
+
canCreate: boolean;
|
|
1214
|
+
canDelegate: boolean;
|
|
1215
|
+
canDelegateTo: string[];
|
|
1216
|
+
};
|
|
1217
|
+
limits: {
|
|
1218
|
+
maxRecallsPerMinute: number;
|
|
1219
|
+
maxWritesPerMinute: number;
|
|
1220
|
+
maxSessionsConcurrent: number;
|
|
1221
|
+
maxSelfEditsPerSession: number;
|
|
1222
|
+
};
|
|
1223
|
+
requireApprovalFor: ApprovalTrigger[];
|
|
1224
|
+
federationAccess: "none" | "read" | "read_write";
|
|
1225
|
+
}
|
|
1226
|
+
interface InjectionGuardResult {
|
|
1227
|
+
score: number;
|
|
1228
|
+
flagged: boolean;
|
|
1229
|
+
reason?: string;
|
|
1230
|
+
}
|
|
1231
|
+
/**
|
|
1232
|
+
* Noisy-OR injection score for recall-path text.
|
|
1233
|
+
* Aggregates all matched poisoning categories.
|
|
1234
|
+
*/
|
|
1235
|
+
interface InjectionScore {
|
|
1236
|
+
/** Composite noisy-OR probability in [0, 1]; high = likely injection. */
|
|
1237
|
+
score: number;
|
|
1238
|
+
flagged: boolean;
|
|
1239
|
+
categories: string[];
|
|
1240
|
+
}
|
|
1241
|
+
/**
|
|
1242
|
+
* Wire format for an AES-256-GCM encrypted field stored in the database.
|
|
1243
|
+
* Identified by the sentinel prefix "enc:v1:" when serialized to a column.
|
|
1244
|
+
*/
|
|
1245
|
+
interface EncryptedField {
|
|
1246
|
+
/** AES-256-GCM ciphertext, base64-encoded. */
|
|
1247
|
+
ciphertext: string;
|
|
1248
|
+
/** GCM IV, base64-encoded (12 bytes). */
|
|
1249
|
+
iv: string;
|
|
1250
|
+
/** GCM authentication tag, base64-encoded (16 bytes). */
|
|
1251
|
+
tag: string;
|
|
1252
|
+
/** DEK identifier — used for rotation auditing. */
|
|
1253
|
+
dekId: string;
|
|
1254
|
+
algorithm: "AES-256-GCM";
|
|
1255
|
+
}
|
|
1256
|
+
/**
|
|
1257
|
+
* Write-time semantic anomaly score derived from neighbour cosine similarities.
|
|
1258
|
+
*/
|
|
1259
|
+
interface AnomalyScore {
|
|
1260
|
+
/** Composite anomaly probability in [0, 1]; high = anomalous. */
|
|
1261
|
+
score: number;
|
|
1262
|
+
flagged: boolean;
|
|
1263
|
+
signals: {
|
|
1264
|
+
/** Isolation score: 1 − mean(neighbour cosine sims). High = isolated from existing knowledge. */
|
|
1265
|
+
distance: number;
|
|
1266
|
+
/** Estimated PII density derived from piiRiskScore. */
|
|
1267
|
+
piiDensity: number;
|
|
1268
|
+
/** Fraction of neighbours in contradiction zone [0.80, 0.97). */
|
|
1269
|
+
contradiction: number;
|
|
1270
|
+
};
|
|
1271
|
+
}
|
|
1272
|
+
|
|
1273
|
+
interface CreateSessionInput {
|
|
1274
|
+
workspaceId: string;
|
|
1275
|
+
agentId?: string;
|
|
1276
|
+
actorId?: string;
|
|
1277
|
+
metadata?: Record<string, unknown>;
|
|
1278
|
+
}
|
|
1279
|
+
interface CreateFactInput {
|
|
1280
|
+
workspaceId: string;
|
|
1281
|
+
agentId?: string;
|
|
1282
|
+
actorId?: string;
|
|
1283
|
+
scope: MnemoFact["scope"];
|
|
1284
|
+
scopeRef?: string;
|
|
1285
|
+
statement: string;
|
|
1286
|
+
subject: string;
|
|
1287
|
+
kind: MnemoFact["kind"];
|
|
1288
|
+
confidence?: number;
|
|
1289
|
+
relevance?: number;
|
|
1290
|
+
attribution?: MnemoFact["attribution"];
|
|
1291
|
+
attributedTo?: MnemoFact["attribution"];
|
|
1292
|
+
sourceMessageIds?: string[];
|
|
1293
|
+
sessionId?: string;
|
|
1294
|
+
extractionSource?: string;
|
|
1295
|
+
topicKey?: string;
|
|
1296
|
+
entityId?: string;
|
|
1297
|
+
episodeId?: string;
|
|
1298
|
+
validFrom?: Date;
|
|
1299
|
+
validTo?: Date;
|
|
1300
|
+
tags?: string[];
|
|
1301
|
+
metadata?: Record<string, unknown>;
|
|
1302
|
+
sensitivity?: MnemoFact["sensitivity"];
|
|
1303
|
+
/**
|
|
1304
|
+
* Ownership level: "workspace:<id>" | "user:<id>" | "tenant:<id>".
|
|
1305
|
+
* Defaults to "workspace:<workspaceId>" when omitted.
|
|
1306
|
+
* Used by multi-level recall to route facts to the right context pool.
|
|
1307
|
+
*/
|
|
1308
|
+
scopeOwner?: string;
|
|
1309
|
+
/**
|
|
1310
|
+
* Precomputed embedding for the fact's statement. When supplied, createFact
|
|
1311
|
+
* enqueues an authoritative vector-form `vector_upsert` outbox entry (the
|
|
1312
|
+
* worker re-applies this exact vector) instead of the text-form entry it would
|
|
1313
|
+
* otherwise embed itself. This honours the "server skips its own embed pass
|
|
1314
|
+
* when a vector is supplied" contract and prevents a re-embed of the statement
|
|
1315
|
+
* from clobbering a host-supplied vector. Length must match the workspace
|
|
1316
|
+
* embedding dimensions.
|
|
1317
|
+
*/
|
|
1318
|
+
embedding?: number[];
|
|
1319
|
+
/** The model stamp (e.g. 'text-embedding-3-small') used to generate the embedding. */
|
|
1320
|
+
embeddingModel?: string;
|
|
1321
|
+
}
|
|
1322
|
+
interface UpdateFactInput {
|
|
1323
|
+
statement?: string;
|
|
1324
|
+
confidence?: number;
|
|
1325
|
+
relevance?: number;
|
|
1326
|
+
status?: MnemoFact["status"];
|
|
1327
|
+
pinned?: boolean;
|
|
1328
|
+
validTo?: Date;
|
|
1329
|
+
metadata?: Record<string, unknown>;
|
|
1330
|
+
}
|
|
1331
|
+
interface MergeFactByTopicKeyInput {
|
|
1332
|
+
workspaceId: string;
|
|
1333
|
+
topicKey: string;
|
|
1334
|
+
statement: string;
|
|
1335
|
+
metadata?: Record<string, unknown>;
|
|
1336
|
+
tags?: string[];
|
|
1337
|
+
}
|
|
1338
|
+
interface ReplaceFactInput {
|
|
1339
|
+
id: string;
|
|
1340
|
+
workspaceId: string;
|
|
1341
|
+
statement: string;
|
|
1342
|
+
requestedBy: string;
|
|
1343
|
+
agentId?: string;
|
|
1344
|
+
actorIsolationId?: string;
|
|
1345
|
+
}
|
|
1346
|
+
interface ReplaceFactResult {
|
|
1347
|
+
previous: MnemoFact;
|
|
1348
|
+
replacement: MnemoFact;
|
|
1349
|
+
}
|
|
1350
|
+
interface FactFilter {
|
|
1351
|
+
workspaceId: string;
|
|
1352
|
+
status?: MnemoFact["status"];
|
|
1353
|
+
kind?: MnemoFact["kind"];
|
|
1354
|
+
scope?: MnemoFact["scope"];
|
|
1355
|
+
entityId?: string;
|
|
1356
|
+
sessionId?: string;
|
|
1357
|
+
minConfidence?: number;
|
|
1358
|
+
topicKey?: string;
|
|
1359
|
+
tags?: string[];
|
|
1360
|
+
validAt?: Date;
|
|
1361
|
+
offset?: number;
|
|
1362
|
+
limit?: number;
|
|
1363
|
+
}
|
|
1364
|
+
/**
|
|
1365
|
+
* Query for active facts that potentially contradict a candidate fact.
|
|
1366
|
+
* Mirrors the candidate-on-write matching in core conflict/fact-candidate.ts:
|
|
1367
|
+
* same `subject` (catches "user prefers X" → "user prefers Y") OR FTS overlap
|
|
1368
|
+
* on the statement. Scoped to ACTIVE facts in the workspace.
|
|
1369
|
+
*/
|
|
1370
|
+
interface FindContradictingFactsInput {
|
|
1371
|
+
/** Exact `subject` of the candidate fact (cheap same-subject match). */
|
|
1372
|
+
subject: string;
|
|
1373
|
+
/** The candidate statement, run through full-text search for overlap. */
|
|
1374
|
+
statement: string;
|
|
1375
|
+
/** When set, the just-inserted candidate is excluded from the results. */
|
|
1376
|
+
excludeId?: string;
|
|
1377
|
+
/** Max rows returned. Default 5 (adapter-defined). */
|
|
1378
|
+
limit?: number;
|
|
1379
|
+
}
|
|
1380
|
+
/**
|
|
1381
|
+
* A fact surfaced as a potential contradiction. Carries exactly the fields the
|
|
1382
|
+
* pure §33 resolver (decideAutoResolution) consumes — attribution, worth,
|
|
1383
|
+
* validFrom — plus identity/context (id, statement, subject, confidence) the
|
|
1384
|
+
* caller needs to act on the verdict (supersede / review) and to log it.
|
|
1385
|
+
*
|
|
1386
|
+
* `worth` is the generated Beta-Bernoulli posterior (NUMERIC in Postgres);
|
|
1387
|
+
* adapters MUST coerce it to a JS number before returning.
|
|
1388
|
+
*/
|
|
1389
|
+
interface ContradictingFact {
|
|
1390
|
+
id: string;
|
|
1391
|
+
subject: string;
|
|
1392
|
+
statement: string;
|
|
1393
|
+
confidence: number;
|
|
1394
|
+
attribution: MnemoFact["attribution"];
|
|
1395
|
+
worth: number;
|
|
1396
|
+
validFrom: Date;
|
|
1397
|
+
}
|
|
1398
|
+
interface CreateDecisionInput {
|
|
1399
|
+
workspaceId: string;
|
|
1400
|
+
agentId?: string;
|
|
1401
|
+
actorId?: string;
|
|
1402
|
+
conversationId?: string;
|
|
1403
|
+
/** Ownership: "workspace:<id>" | "user:<id>" | "tenant:<id>". Defaults to "workspace:<workspaceId>". */
|
|
1404
|
+
scopeOwner?: string;
|
|
1405
|
+
/** Project/entity scope reference (e.g. 'project-x'). Mirrors mnemo_fact.scope_ref. */
|
|
1406
|
+
scopeRef?: string;
|
|
1407
|
+
kind: MnemoDecision["kind"];
|
|
1408
|
+
title: string;
|
|
1409
|
+
body: string;
|
|
1410
|
+
topicKey?: string;
|
|
1411
|
+
decidedByUserId?: string;
|
|
1412
|
+
confidence?: number;
|
|
1413
|
+
validFrom?: Date;
|
|
1414
|
+
sensitivity?: Sensitivity;
|
|
1415
|
+
metadata?: Record<string, unknown>;
|
|
1416
|
+
}
|
|
1417
|
+
interface UpdateDecisionInput {
|
|
1418
|
+
workspaceId: string;
|
|
1419
|
+
title?: string;
|
|
1420
|
+
body?: string;
|
|
1421
|
+
status?: MnemoDecision["status"];
|
|
1422
|
+
supersededById?: string;
|
|
1423
|
+
validTo?: Date;
|
|
1424
|
+
metadata?: Record<string, unknown>;
|
|
1425
|
+
}
|
|
1426
|
+
interface DecisionFilter {
|
|
1427
|
+
workspaceId: string;
|
|
1428
|
+
status?: MnemoDecision["status"];
|
|
1429
|
+
kind?: MnemoDecision["kind"];
|
|
1430
|
+
topicKey?: string;
|
|
1431
|
+
/** When set, return records with scope_ref = X OR scope_ref IS NULL. */
|
|
1432
|
+
scopeRef?: string;
|
|
1433
|
+
validAt?: Date;
|
|
1434
|
+
offset?: number;
|
|
1435
|
+
limit?: number;
|
|
1436
|
+
}
|
|
1437
|
+
interface CreateEpisodeInput {
|
|
1438
|
+
workspaceId: string;
|
|
1439
|
+
agentId?: string;
|
|
1440
|
+
actorId?: string;
|
|
1441
|
+
/** Ownership: "workspace:<id>" | "user:<id>" | "tenant:<id>". Defaults to "workspace:<workspaceId>". */
|
|
1442
|
+
scopeOwner?: string;
|
|
1443
|
+
title: string;
|
|
1444
|
+
narrative: string;
|
|
1445
|
+
occurredAt: Date;
|
|
1446
|
+
durationMinutes?: number;
|
|
1447
|
+
participants?: string[];
|
|
1448
|
+
topics?: string[];
|
|
1449
|
+
linkedFactIds?: string[];
|
|
1450
|
+
parentEpisodeId?: string;
|
|
1451
|
+
deltaContent?: string;
|
|
1452
|
+
isSynthetic?: boolean;
|
|
1453
|
+
sourceConversationId?: string;
|
|
1454
|
+
sensitivity?: Sensitivity;
|
|
1455
|
+
metadata?: Record<string, unknown>;
|
|
1456
|
+
}
|
|
1457
|
+
type UpdateEpisodeInput = {
|
|
1458
|
+
workspaceId: string;
|
|
1459
|
+
} & Partial<Pick<MnemoEpisode, "title" | "narrative" | "topics" | "linkedFactIds" | "metadata">>;
|
|
1460
|
+
interface EpisodeFilter {
|
|
1461
|
+
workspaceId: string;
|
|
1462
|
+
topics?: string[];
|
|
1463
|
+
participantId?: string;
|
|
1464
|
+
isSynthetic?: boolean;
|
|
1465
|
+
parentEpisodeId?: string;
|
|
1466
|
+
after?: Date;
|
|
1467
|
+
before?: Date;
|
|
1468
|
+
/** P18 — asOf filter: validFrom <= validAt AND (validTo IS NULL OR validTo > validAt) */
|
|
1469
|
+
validAt?: Date;
|
|
1470
|
+
offset?: number;
|
|
1471
|
+
limit?: number;
|
|
1472
|
+
}
|
|
1473
|
+
interface CreateEntityInput {
|
|
1474
|
+
workspaceId: string;
|
|
1475
|
+
actorId?: string;
|
|
1476
|
+
agentId?: string;
|
|
1477
|
+
/** Ownership: "workspace:<id>" | "user:<id>" | "tenant:<id>". Defaults to "workspace:<workspaceId>". */
|
|
1478
|
+
scopeOwner?: string;
|
|
1479
|
+
name: string;
|
|
1480
|
+
kind: MnemoEntity["kind"];
|
|
1481
|
+
aliases?: string[];
|
|
1482
|
+
canonicalId?: string;
|
|
1483
|
+
description?: string;
|
|
1484
|
+
sensitivity?: Sensitivity;
|
|
1485
|
+
metadata?: Record<string, unknown>;
|
|
1486
|
+
}
|
|
1487
|
+
type UpdateEntityInput = {
|
|
1488
|
+
workspaceId: string;
|
|
1489
|
+
} & Partial<Pick<MnemoEntity, "name" | "aliases" | "description" | "canonicalId" | "metadata">>;
|
|
1490
|
+
interface EntityFilter {
|
|
1491
|
+
workspaceId: string;
|
|
1492
|
+
kind?: MnemoEntity["kind"];
|
|
1493
|
+
name?: string;
|
|
1494
|
+
/** P18 — asOf filter: validFrom <= validAt AND (validTo IS NULL OR validTo > validAt) */
|
|
1495
|
+
validAt?: Date;
|
|
1496
|
+
offset?: number;
|
|
1497
|
+
limit?: number;
|
|
1498
|
+
}
|
|
1499
|
+
interface CreateStrategyInput {
|
|
1500
|
+
workspaceId: string;
|
|
1501
|
+
agentId?: string;
|
|
1502
|
+
actorId?: string;
|
|
1503
|
+
/** Ownership: "workspace:<id>" | "user:<id>" | "tenant:<id>". Defaults to "workspace:<workspaceId>". */
|
|
1504
|
+
scopeOwner?: string;
|
|
1505
|
+
/** Project/entity scope reference (e.g. 'project-x'). Mirrors mnemo_fact.scope_ref. */
|
|
1506
|
+
scopeRef?: string;
|
|
1507
|
+
trigger: string;
|
|
1508
|
+
action: string;
|
|
1509
|
+
context?: string;
|
|
1510
|
+
relatedFacts?: string[];
|
|
1511
|
+
attribution?: MnemoStrategy["attribution"];
|
|
1512
|
+
supersedesId?: string;
|
|
1513
|
+
validFrom?: Date;
|
|
1514
|
+
sensitivity?: Sensitivity;
|
|
1515
|
+
metadata?: Record<string, unknown>;
|
|
1516
|
+
}
|
|
1517
|
+
type UpdateStrategyInput = {
|
|
1518
|
+
workspaceId: string;
|
|
1519
|
+
} & Partial<Pick<MnemoStrategy, "trigger" | "action" | "context" | "status" | "validTo" | "metadata" | "successCount" | "failureCount" | "worth" | "relatedFacts" | "attribution">>;
|
|
1520
|
+
interface StrategyFilter {
|
|
1521
|
+
workspaceId: string;
|
|
1522
|
+
status?: MnemoStrategy["status"];
|
|
1523
|
+
/** When set, return records with scope_ref = X OR scope_ref IS NULL. */
|
|
1524
|
+
scopeRef?: string;
|
|
1525
|
+
validAt?: Date;
|
|
1526
|
+
offset?: number;
|
|
1527
|
+
limit?: number;
|
|
1528
|
+
}
|
|
1529
|
+
interface CreateWorkflowInput {
|
|
1530
|
+
workspaceId: string;
|
|
1531
|
+
actorId?: string;
|
|
1532
|
+
agentId?: string;
|
|
1533
|
+
/** Ownership: "workspace:<id>" | "user:<id>" | "tenant:<id>". Defaults to "workspace:<workspaceId>". */
|
|
1534
|
+
scopeOwner?: string;
|
|
1535
|
+
/** Project/entity scope reference (e.g. 'project-x'). Mirrors mnemo_fact.scope_ref. */
|
|
1536
|
+
scopeRef?: string;
|
|
1537
|
+
name: string;
|
|
1538
|
+
description?: string;
|
|
1539
|
+
steps: WorkflowStep[];
|
|
1540
|
+
sensitivity?: Sensitivity;
|
|
1541
|
+
metadata?: Record<string, unknown>;
|
|
1542
|
+
}
|
|
1543
|
+
type UpdateWorkflowInput = {
|
|
1544
|
+
workspaceId: string;
|
|
1545
|
+
} & Partial<Pick<MnemoWorkflow, "name" | "description" | "steps" | "status" | "metadata">>;
|
|
1546
|
+
interface WorkflowFilter {
|
|
1547
|
+
workspaceId: string;
|
|
1548
|
+
status?: MnemoWorkflow["status"];
|
|
1549
|
+
/** When set, return records with scope_ref = X OR scope_ref IS NULL. */
|
|
1550
|
+
scopeRef?: string;
|
|
1551
|
+
/** P18 — asOf filter: validFrom <= validAt AND (validTo IS NULL OR validTo > validAt) */
|
|
1552
|
+
validAt?: Date;
|
|
1553
|
+
offset?: number;
|
|
1554
|
+
limit?: number;
|
|
1555
|
+
}
|
|
1556
|
+
interface CreateSkillInput {
|
|
1557
|
+
workspaceId: string;
|
|
1558
|
+
actorId?: string;
|
|
1559
|
+
agentId?: string;
|
|
1560
|
+
/** Ownership: "workspace:<id>" | "user:<id>" | "tenant:<id>". Defaults to "workspace:<workspaceId>". */
|
|
1561
|
+
scopeOwner?: string;
|
|
1562
|
+
name: string;
|
|
1563
|
+
promptTemplate: string;
|
|
1564
|
+
variables?: string[];
|
|
1565
|
+
requiredContext?: string[];
|
|
1566
|
+
sensitivity?: Sensitivity;
|
|
1567
|
+
metadata?: Record<string, unknown>;
|
|
1568
|
+
}
|
|
1569
|
+
type UpdateSkillInput = {
|
|
1570
|
+
workspaceId: string;
|
|
1571
|
+
} & Partial<Pick<MnemoSkill, "name" | "promptTemplate" | "variables" | "requiredContext" | "metadata">>;
|
|
1572
|
+
interface SkillFilter {
|
|
1573
|
+
workspaceId: string;
|
|
1574
|
+
/** P18 — asOf filter: validFrom <= validAt AND (validTo IS NULL OR validTo > validAt) */
|
|
1575
|
+
validAt?: Date;
|
|
1576
|
+
offset?: number;
|
|
1577
|
+
limit?: number;
|
|
1578
|
+
}
|
|
1579
|
+
interface CreateTaskInput {
|
|
1580
|
+
workspaceId: string;
|
|
1581
|
+
actorId?: string;
|
|
1582
|
+
agentId?: string;
|
|
1583
|
+
/** Ownership: "workspace:<id>" | "user:<id>" | "tenant:<id>". Defaults to "workspace:<workspaceId>". */
|
|
1584
|
+
scopeOwner?: string;
|
|
1585
|
+
title: string;
|
|
1586
|
+
description?: string;
|
|
1587
|
+
priority?: MnemoTask["priority"];
|
|
1588
|
+
assignedTo: string;
|
|
1589
|
+
sessionId?: string;
|
|
1590
|
+
parentTaskId?: string;
|
|
1591
|
+
dueAt?: Date;
|
|
1592
|
+
delegatedBy?: string;
|
|
1593
|
+
relatedFacts?: string[];
|
|
1594
|
+
relatedEntities?: string[];
|
|
1595
|
+
sensitivity?: Sensitivity;
|
|
1596
|
+
metadata?: Record<string, unknown>;
|
|
1597
|
+
}
|
|
1598
|
+
interface DelegateTaskInput {
|
|
1599
|
+
assignedTo: string;
|
|
1600
|
+
delegatedBy: string;
|
|
1601
|
+
}
|
|
1602
|
+
type UpdateTaskInput = {
|
|
1603
|
+
workspaceId: string;
|
|
1604
|
+
} & Partial<Pick<MnemoTask, "title" | "description" | "status" | "priority" | "assignedTo" | "blockedBy" | "subtaskIds" | "outcome" | "lessonsLearned" | "startedAt" | "completedAt" | "dueAt" | "metadata">>;
|
|
1605
|
+
interface TaskFilter {
|
|
1606
|
+
workspaceId: string;
|
|
1607
|
+
status?: MnemoTask["status"];
|
|
1608
|
+
assignedTo?: string;
|
|
1609
|
+
parentTaskId?: string;
|
|
1610
|
+
/** P18 — asOf filter: validFrom <= validAt AND (validTo IS NULL OR validTo > validAt) */
|
|
1611
|
+
validAt?: Date;
|
|
1612
|
+
offset?: number;
|
|
1613
|
+
limit?: number;
|
|
1614
|
+
}
|
|
1615
|
+
interface CreateEventInput {
|
|
1616
|
+
workspaceId: string;
|
|
1617
|
+
agentId?: string;
|
|
1618
|
+
/** Ownership: "workspace:<id>" | "user:<id>" | "tenant:<id>". Defaults to "workspace:<workspaceId>". */
|
|
1619
|
+
scopeOwner?: string;
|
|
1620
|
+
type: MnemoEvent["type"];
|
|
1621
|
+
name: string;
|
|
1622
|
+
description: string;
|
|
1623
|
+
occurredAt: Date;
|
|
1624
|
+
durationS?: number;
|
|
1625
|
+
source: string;
|
|
1626
|
+
relatedEntities?: string[];
|
|
1627
|
+
annotations?: EventAnnotation[];
|
|
1628
|
+
sensitivity?: Sensitivity;
|
|
1629
|
+
metadata?: Record<string, unknown>;
|
|
1630
|
+
}
|
|
1631
|
+
interface EventFilter {
|
|
1632
|
+
workspaceId: string;
|
|
1633
|
+
type?: MnemoEvent["type"];
|
|
1634
|
+
source?: string;
|
|
1635
|
+
after?: Date;
|
|
1636
|
+
before?: Date;
|
|
1637
|
+
offset?: number;
|
|
1638
|
+
limit?: number;
|
|
1639
|
+
}
|
|
1640
|
+
interface CreateReasoningInput {
|
|
1641
|
+
workspaceId: string;
|
|
1642
|
+
agentId?: string;
|
|
1643
|
+
/** Ownership: "workspace:<id>" | "user:<id>" | "tenant:<id>". Defaults to "workspace:<workspaceId>". */
|
|
1644
|
+
scopeOwner?: string;
|
|
1645
|
+
question: string;
|
|
1646
|
+
chain: MnemoReasoning["chain"];
|
|
1647
|
+
conclusion: string;
|
|
1648
|
+
topicKey?: string;
|
|
1649
|
+
sensitivity?: Sensitivity;
|
|
1650
|
+
metadata?: Record<string, unknown>;
|
|
1651
|
+
}
|
|
1652
|
+
type UpdateReasoningInput = {
|
|
1653
|
+
workspaceId: string;
|
|
1654
|
+
} & Partial<Pick<MnemoReasoning, "status" | "chain" | "conclusion" | "metadata">>;
|
|
1655
|
+
interface ReasoningFilter {
|
|
1656
|
+
workspaceId: string;
|
|
1657
|
+
status?: MnemoReasoning["status"];
|
|
1658
|
+
topicKey?: string;
|
|
1659
|
+
offset?: number;
|
|
1660
|
+
limit?: number;
|
|
1661
|
+
}
|
|
1662
|
+
interface CreateHyperedgeInput {
|
|
1663
|
+
workspaceId: string;
|
|
1664
|
+
memberIds: string[];
|
|
1665
|
+
label?: string;
|
|
1666
|
+
description?: string;
|
|
1667
|
+
contextQuery?: string;
|
|
1668
|
+
contextEmbedding?: Float32Array;
|
|
1669
|
+
}
|
|
1670
|
+
type UpdateHyperedgeInput = Partial<Pick<MnemoHyperedge, "label" | "description" | "contextQuery">>;
|
|
1671
|
+
interface HyperedgeFilter {
|
|
1672
|
+
workspaceId: string;
|
|
1673
|
+
memberId?: string;
|
|
1674
|
+
label?: string;
|
|
1675
|
+
offset?: number;
|
|
1676
|
+
limit?: number;
|
|
1677
|
+
}
|
|
1678
|
+
interface CreateCompositionRuleInput {
|
|
1679
|
+
workspaceId: string;
|
|
1680
|
+
name: string;
|
|
1681
|
+
description?: string;
|
|
1682
|
+
conditionDsl: unknown;
|
|
1683
|
+
actionDsl: unknown;
|
|
1684
|
+
priority?: number;
|
|
1685
|
+
isActive?: boolean;
|
|
1686
|
+
createdBy?: string;
|
|
1687
|
+
source?: MnemoCompositionRule["source"];
|
|
1688
|
+
metadata?: Record<string, unknown>;
|
|
1689
|
+
}
|
|
1690
|
+
type UpdateCompositionRuleInput = Partial<Pick<MnemoCompositionRule, "name" | "description" | "conditionDsl" | "actionDsl" | "priority" | "isActive" | "metadata">>;
|
|
1691
|
+
interface CompositionRuleFilter {
|
|
1692
|
+
workspaceId: string;
|
|
1693
|
+
isActive?: boolean;
|
|
1694
|
+
source?: MnemoCompositionRule["source"];
|
|
1695
|
+
offset?: number;
|
|
1696
|
+
limit?: number;
|
|
1697
|
+
}
|
|
1698
|
+
interface AppendInferenceInput {
|
|
1699
|
+
workspaceId: string;
|
|
1700
|
+
ruleId: string;
|
|
1701
|
+
inputFactIds: string[];
|
|
1702
|
+
derivedKind?: string;
|
|
1703
|
+
derivedId?: string;
|
|
1704
|
+
confidence: number;
|
|
1705
|
+
rationale?: string;
|
|
1706
|
+
triggeredByQuery?: string;
|
|
1707
|
+
conversationId?: string;
|
|
1708
|
+
}
|
|
1709
|
+
interface MaterialiseInferenceInput {
|
|
1710
|
+
ruleId: string;
|
|
1711
|
+
workspaceId: string;
|
|
1712
|
+
fact: {
|
|
1713
|
+
scope: string;
|
|
1714
|
+
kind: string;
|
|
1715
|
+
subject: string;
|
|
1716
|
+
statement: string;
|
|
1717
|
+
attribution: string;
|
|
1718
|
+
sensitivity: Sensitivity;
|
|
1719
|
+
metadata: Record<string, unknown>;
|
|
1720
|
+
};
|
|
1721
|
+
inferenceLog: {
|
|
1722
|
+
inputFactIds: string[];
|
|
1723
|
+
derivedKind: string;
|
|
1724
|
+
confidence: number;
|
|
1725
|
+
rationale: string;
|
|
1726
|
+
triggeredByQuery?: string;
|
|
1727
|
+
conversationId?: string;
|
|
1728
|
+
};
|
|
1729
|
+
}
|
|
1730
|
+
interface InferenceLogFilter {
|
|
1731
|
+
workspaceId: string;
|
|
1732
|
+
ruleId?: string;
|
|
1733
|
+
derivedId?: string;
|
|
1734
|
+
since?: Date;
|
|
1735
|
+
offset?: number;
|
|
1736
|
+
limit?: number;
|
|
1737
|
+
}
|
|
1738
|
+
interface UpsertFactHashInput {
|
|
1739
|
+
workspaceId: string;
|
|
1740
|
+
statementHash: string;
|
|
1741
|
+
factId: string;
|
|
1742
|
+
}
|
|
1743
|
+
interface CreateRelationInput {
|
|
1744
|
+
workspaceId: string;
|
|
1745
|
+
sourceId: string;
|
|
1746
|
+
sourceType: string;
|
|
1747
|
+
targetId: string;
|
|
1748
|
+
targetType: string;
|
|
1749
|
+
verb: RelationVerb;
|
|
1750
|
+
weight?: number;
|
|
1751
|
+
metadata?: Record<string, unknown>;
|
|
1752
|
+
}
|
|
1753
|
+
interface RelationFilter {
|
|
1754
|
+
workspaceId: string;
|
|
1755
|
+
sourceId?: string;
|
|
1756
|
+
targetId?: string;
|
|
1757
|
+
verb?: RelationVerb;
|
|
1758
|
+
}
|
|
1759
|
+
interface RecallLogEntry {
|
|
1760
|
+
workspaceId: string;
|
|
1761
|
+
factId: string;
|
|
1762
|
+
sessionId?: string;
|
|
1763
|
+
queryText?: string;
|
|
1764
|
+
hitRank?: number;
|
|
1765
|
+
tdCredit?: number;
|
|
1766
|
+
activationScore?: number;
|
|
1767
|
+
latencyMs?: number;
|
|
1768
|
+
}
|
|
1769
|
+
interface MnemoWebhookEndpoint {
|
|
1770
|
+
id: string;
|
|
1771
|
+
workspaceId: string;
|
|
1772
|
+
url: string;
|
|
1773
|
+
events: string[];
|
|
1774
|
+
secretHash: string;
|
|
1775
|
+
isActive: boolean;
|
|
1776
|
+
description: string | null;
|
|
1777
|
+
failureCount: number;
|
|
1778
|
+
disabledAt: Date | null;
|
|
1779
|
+
createdAt: Date;
|
|
1780
|
+
updatedAt: Date;
|
|
1781
|
+
}
|
|
1782
|
+
interface CreateWebhookEndpointInput {
|
|
1783
|
+
id: string;
|
|
1784
|
+
workspaceId: string;
|
|
1785
|
+
url: string;
|
|
1786
|
+
events: string[];
|
|
1787
|
+
secretHash: string;
|
|
1788
|
+
description?: string;
|
|
1789
|
+
}
|
|
1790
|
+
interface UpdateWebhookEndpointInput {
|
|
1791
|
+
url?: string;
|
|
1792
|
+
events?: string[];
|
|
1793
|
+
isActive?: boolean;
|
|
1794
|
+
description?: string;
|
|
1795
|
+
/** Delivery-worker: increment failure count for 3-strike auto-disable. */
|
|
1796
|
+
failureCount?: number;
|
|
1797
|
+
/** Delivery-worker: set when endpoint is auto-disabled after 3 strikes. */
|
|
1798
|
+
disabledAt?: Date | null;
|
|
1799
|
+
}
|
|
1800
|
+
interface MnemoWebhookDelivery {
|
|
1801
|
+
id: string;
|
|
1802
|
+
webhookId: string;
|
|
1803
|
+
workspaceId: string;
|
|
1804
|
+
eventType: string;
|
|
1805
|
+
payload: Record<string, unknown>;
|
|
1806
|
+
status: "pending" | "delivered" | "failed";
|
|
1807
|
+
responseStatus: number | null;
|
|
1808
|
+
responseBody: string | null;
|
|
1809
|
+
attempt: number;
|
|
1810
|
+
deliveredAt: Date | null;
|
|
1811
|
+
nextAttemptAt: Date | null;
|
|
1812
|
+
createdAt: Date;
|
|
1813
|
+
}
|
|
1814
|
+
interface CreateWebhookDeliveryInput {
|
|
1815
|
+
id: string;
|
|
1816
|
+
webhookId: string;
|
|
1817
|
+
workspaceId: string;
|
|
1818
|
+
eventType: string;
|
|
1819
|
+
payload: Record<string, unknown>;
|
|
1820
|
+
status: "pending" | "delivered" | "failed";
|
|
1821
|
+
responseStatus?: number;
|
|
1822
|
+
responseBody?: string;
|
|
1823
|
+
attempt?: number;
|
|
1824
|
+
deliveredAt?: Date;
|
|
1825
|
+
}
|
|
1826
|
+
interface MnemoReminder {
|
|
1827
|
+
id: string;
|
|
1828
|
+
workspaceId: string;
|
|
1829
|
+
content: string;
|
|
1830
|
+
condition: string;
|
|
1831
|
+
triggerAt: Date | null;
|
|
1832
|
+
status: "pending" | "triggered" | "dismissed";
|
|
1833
|
+
conditionEmbedding: number[] | null;
|
|
1834
|
+
triggeredAt: Date | null;
|
|
1835
|
+
dismissedAt: Date | null;
|
|
1836
|
+
createdByAgentId: string | null;
|
|
1837
|
+
createdAt: Date;
|
|
1838
|
+
updatedAt: Date;
|
|
1839
|
+
}
|
|
1840
|
+
interface CreateReminderInput {
|
|
1841
|
+
id: string;
|
|
1842
|
+
workspaceId: string;
|
|
1843
|
+
content: string;
|
|
1844
|
+
condition: string;
|
|
1845
|
+
triggerAt?: Date;
|
|
1846
|
+
conditionEmbedding?: number[];
|
|
1847
|
+
createdByAgentId?: string;
|
|
1848
|
+
}
|
|
1849
|
+
interface LshBandValue {
|
|
1850
|
+
bandIdx: number;
|
|
1851
|
+
bandHash: bigint;
|
|
1852
|
+
}
|
|
1853
|
+
interface UpsertFactLshInput {
|
|
1854
|
+
workspaceId: string;
|
|
1855
|
+
factId: string;
|
|
1856
|
+
revision: number;
|
|
1857
|
+
bands: LshBandValue[];
|
|
1858
|
+
}
|
|
1859
|
+
type RecallPrimitiveValue = MnemoFact | MnemoDecision | MnemoEpisode | MnemoEntity | MnemoStrategy | MnemoWorkflow | MnemoSkill | MnemoTask | MnemoEvent | MnemoReasoning;
|
|
1860
|
+
interface RecallPrimitiveRef {
|
|
1861
|
+
id: string;
|
|
1862
|
+
kind: Exclude<PrimitiveKind, "hyperedge">;
|
|
1863
|
+
}
|
|
1864
|
+
interface RecallPrimitiveRecord extends RecallPrimitiveRef {
|
|
1865
|
+
value: RecallPrimitiveValue;
|
|
1866
|
+
}
|
|
1867
|
+
interface RecallLogRecord {
|
|
1868
|
+
memoryId: string;
|
|
1869
|
+
id: string;
|
|
1870
|
+
recalledAt: string;
|
|
1871
|
+
recallScore: number;
|
|
1872
|
+
}
|
|
1873
|
+
interface RecallStructures {
|
|
1874
|
+
relations: MnemoRelation[];
|
|
1875
|
+
hyperedges: Array<{
|
|
1876
|
+
memberId: string;
|
|
1877
|
+
hyperedge: MnemoHyperedge;
|
|
1878
|
+
}>;
|
|
1879
|
+
}
|
|
1880
|
+
interface PointerCandidateQuery {
|
|
1881
|
+
workspaceId: string;
|
|
1882
|
+
terms: string[];
|
|
1883
|
+
bands: LshBandValue[];
|
|
1884
|
+
limit: number;
|
|
1885
|
+
filter?: RecallFilter;
|
|
1886
|
+
includeArchived?: boolean;
|
|
1887
|
+
includeLowWorth?: boolean;
|
|
1888
|
+
}
|
|
1889
|
+
interface PointerCandidate {
|
|
1890
|
+
factId: string;
|
|
1891
|
+
statement: string;
|
|
1892
|
+
embedding: number[] | null;
|
|
1893
|
+
sensitivity: Sensitivity;
|
|
1894
|
+
worth: number;
|
|
1895
|
+
worthAlpha?: number;
|
|
1896
|
+
worthBeta?: number;
|
|
1897
|
+
attribution: Provenance;
|
|
1898
|
+
createdAt: Date;
|
|
1899
|
+
validFrom?: Date;
|
|
1900
|
+
status: MnemoFact["status"];
|
|
1901
|
+
validTo: Date | null;
|
|
1902
|
+
confidence?: number;
|
|
1903
|
+
tags?: string[];
|
|
1904
|
+
scope?: MnemoFact["scope"];
|
|
1905
|
+
scopeRef?: string;
|
|
1906
|
+
actorId?: string | null;
|
|
1907
|
+
entityId?: string;
|
|
1908
|
+
sessionId?: string;
|
|
1909
|
+
}
|
|
1910
|
+
interface FtsCandidate extends PointerCandidate {
|
|
1911
|
+
rank: number;
|
|
1912
|
+
}
|
|
1913
|
+
interface ConsolidationWorthSnapshot {
|
|
1914
|
+
alpha: number;
|
|
1915
|
+
beta: number;
|
|
1916
|
+
success: number;
|
|
1917
|
+
failure: number;
|
|
1918
|
+
}
|
|
1919
|
+
interface ConsolidationMergeSnapshot {
|
|
1920
|
+
operationId: string;
|
|
1921
|
+
workspaceId: string;
|
|
1922
|
+
survivorId: string;
|
|
1923
|
+
absorbedFactIds: string[];
|
|
1924
|
+
previousWorth: ConsolidationWorthSnapshot;
|
|
1925
|
+
expectedMergedWorth: ConsolidationWorthSnapshot;
|
|
1926
|
+
}
|
|
1927
|
+
interface ApplyConsolidationMergeInput {
|
|
1928
|
+
operationId: string;
|
|
1929
|
+
workspaceId: string;
|
|
1930
|
+
survivorId: string;
|
|
1931
|
+
absorbedFactIds: string[];
|
|
1932
|
+
leaseExpiresAt: Date;
|
|
1933
|
+
}
|
|
1934
|
+
interface ReplayFailureReview {
|
|
1935
|
+
reason: "replay_validation_failed" | "replay_execution_failed";
|
|
1936
|
+
passCount: number;
|
|
1937
|
+
failCount: number;
|
|
1938
|
+
queriesUsed: string[];
|
|
1939
|
+
}
|
|
1940
|
+
/**
|
|
1941
|
+
* Filter passed to StorageAdapter.purgeFacts?().
|
|
1942
|
+
* Caller MUST never pass sensitivity='public' (spec: public facts are never purged).
|
|
1943
|
+
*/
|
|
1944
|
+
interface PurgeFactsFilter {
|
|
1945
|
+
workspaceId: string;
|
|
1946
|
+
/** The sensitivity tier to purge. Must not be 'public'. */
|
|
1947
|
+
sensitivity: Sensitivity;
|
|
1948
|
+
/** Soft-close facts with createdAt < now() - olderThanDays. */
|
|
1949
|
+
olderThanDays: number;
|
|
1950
|
+
/**
|
|
1951
|
+
* When true: count matching rows and compute erase candidates but do NOT
|
|
1952
|
+
* execute any UPDATE or append any deletion-log row.
|
|
1953
|
+
*/
|
|
1954
|
+
dryRun?: boolean;
|
|
1955
|
+
/** Max rows updated per call (default 500). Bounds transaction length. */
|
|
1956
|
+
limit?: number;
|
|
1957
|
+
}
|
|
1958
|
+
/**
|
|
1959
|
+
* Result returned by StorageAdapter.purgeFacts?().
|
|
1960
|
+
*/
|
|
1961
|
+
interface PurgeFactsResult {
|
|
1962
|
+
/** Number of fact rows whose status was set to 'forgotten' (0 in dry-run). */
|
|
1963
|
+
softClosed: number;
|
|
1964
|
+
/**
|
|
1965
|
+
* actorIds whose encrypted facts (confidential + restricted combined) all
|
|
1966
|
+
* have validTo IS NOT NULL after this purge — safe to call destroyActorDek.
|
|
1967
|
+
* Always empty when sensitivity='internal' (no DEK for plaintext tier).
|
|
1968
|
+
* Always empty in dry-run mode.
|
|
1969
|
+
*/
|
|
1970
|
+
eraseCandidateActorIds: string[];
|
|
1971
|
+
}
|
|
1972
|
+
interface StorageCapabilities {
|
|
1973
|
+
vectorSearch: boolean;
|
|
1974
|
+
ftsSearch: boolean;
|
|
1975
|
+
bitemporal: boolean;
|
|
1976
|
+
graphExpansion: boolean;
|
|
1977
|
+
transactions: boolean;
|
|
1978
|
+
rls: boolean;
|
|
1979
|
+
}
|
|
1980
|
+
/**
|
|
1981
|
+
* Primary persistence port — the single contract that core depends on for all durable storage.
|
|
1982
|
+
*
|
|
1983
|
+
* Implemented by: `@mnemo-ai/adapter-postgres` (DrizzleStorageAdapter) and
|
|
1984
|
+
* InMemoryStorageAdapter (test utility in `@mnemo-ai/types/src/testing/`).
|
|
1985
|
+
*
|
|
1986
|
+
* Contract invariants ALL implementations MUST uphold (enforced by StorageAdapterContract.ts):
|
|
1987
|
+
* - getFact(id, workspaceIdA) returns null when the fact belongs to workspaceIdB (RLS isolation)
|
|
1988
|
+
* - Sensitivity defaults to "internal" when not explicitly set
|
|
1989
|
+
* - Decimal confidence values must not be truncated (store as NUMERIC/REAL, not INTEGER)
|
|
1990
|
+
* - Outbox entries are observable immediately after createFact (transactional outbox)
|
|
1991
|
+
* - healthCheck() always returns a value (never throws)
|
|
1992
|
+
*
|
|
1993
|
+
* How to implement: extend InMemoryStorageAdapter or write from scratch, then run
|
|
1994
|
+
* `runStorageAdapterContractTests(makeAdapter)` from packages/types/src/testing/StorageAdapterContract.ts.
|
|
1995
|
+
*/
|
|
1996
|
+
interface StorageAdapter {
|
|
1997
|
+
readonly capabilities: StorageCapabilities;
|
|
1998
|
+
createSession(input: CreateSessionInput): Promise<MnemoSession>;
|
|
1999
|
+
appendTurn(sessionId: string, turn: Omit<SessionTurn, "id" | "createdAt">): Promise<void>;
|
|
2000
|
+
listTurns(sessionId: string, workspaceId: string): Promise<SessionTurn[]>;
|
|
2001
|
+
closeSession(id: string, workspaceId: string): Promise<void>;
|
|
2002
|
+
/**
|
|
2003
|
+
* §7 discard — archive a session WITHOUT collapsing it into durable knowledge.
|
|
2004
|
+
* Sets status='archived' (distinct from closeSession's 'collapsed') and leaves
|
|
2005
|
+
* context_snapshot null. Optional for backward-compat; callers guard with `?.`.
|
|
2006
|
+
*/
|
|
2007
|
+
archiveSession?(id: string, workspaceId: string): Promise<void>;
|
|
2008
|
+
getSession(id: string, workspaceId: string): Promise<MnemoSession | null>;
|
|
2009
|
+
listSessions?(workspaceId: string, limit?: number, offset?: number): Promise<MnemoSession[]>;
|
|
2010
|
+
updateSessionSummary?(args: {
|
|
2011
|
+
sessionId: string;
|
|
2012
|
+
workspaceId: string;
|
|
2013
|
+
summary: Record<string, unknown>;
|
|
2014
|
+
factCount: number;
|
|
2015
|
+
}): Promise<void>;
|
|
2016
|
+
pinSessionTurn(sessionId: string, turnId: string, workspaceId: string, pinned: boolean): Promise<void>;
|
|
2017
|
+
createFact(input: CreateFactInput): Promise<MnemoFact>;
|
|
2018
|
+
getFact(id: string, workspaceId: string): Promise<MnemoFact | null>;
|
|
2019
|
+
updateFact(id: string, workspaceId: string, input: UpdateFactInput): Promise<MnemoFact | null>;
|
|
2020
|
+
mergeFactByTopicKey(input: MergeFactByTopicKeyInput): Promise<MnemoFact | null>;
|
|
2021
|
+
replaceFact(input: ReplaceFactInput): Promise<ReplaceFactResult | null>;
|
|
2022
|
+
archiveFact(id: string, workspaceId: string): Promise<void>;
|
|
2023
|
+
queryFacts(filter: FactFilter): Promise<PaginatedResult<MnemoFact>>;
|
|
2024
|
+
applyConsolidationMerge(input: ApplyConsolidationMergeInput): Promise<ConsolidationMergeSnapshot | null>;
|
|
2025
|
+
rollbackConsolidationMerge(input: {
|
|
2026
|
+
snapshot: ConsolidationMergeSnapshot;
|
|
2027
|
+
review: ReplayFailureReview;
|
|
2028
|
+
}): Promise<"rolled_back" | "conflict">;
|
|
2029
|
+
finalizeConsolidationMerge(input: {
|
|
2030
|
+
snapshot: ConsolidationMergeSnapshot;
|
|
2031
|
+
applyReplayBoost: boolean;
|
|
2032
|
+
}): Promise<"finalized" | "conflict">;
|
|
2033
|
+
refreshConsolidationMergeLease(input: {
|
|
2034
|
+
snapshot: ConsolidationMergeSnapshot;
|
|
2035
|
+
leaseExpiresAt: Date;
|
|
2036
|
+
}): Promise<"refreshed" | "conflict">;
|
|
2037
|
+
inspectConsolidationMergeState(snapshot: ConsolidationMergeSnapshot): Promise<"pending" | "restored" | "retained" | "divergent">;
|
|
2038
|
+
recoverExpiredConsolidationMerges(input: {
|
|
2039
|
+
workspaceId: string;
|
|
2040
|
+
expiredBefore: Date;
|
|
2041
|
+
}): Promise<number>;
|
|
2042
|
+
/**
|
|
2043
|
+
* §33 Distributed Consensus — surface active facts that potentially
|
|
2044
|
+
* contradict a candidate fact, using the SAME matching as core
|
|
2045
|
+
* conflict/fact-candidate.ts: exact same-`subject` OR full-text overlap on
|
|
2046
|
+
* the statement, scoped to active facts in the workspace. Returns only the
|
|
2047
|
+
* fields the pure resolver (decideAutoResolution) needs, plus identity.
|
|
2048
|
+
*
|
|
2049
|
+
* This is the port surface that lets the port-only fact-write path
|
|
2050
|
+
* (core/v3 remember) run deterministic contradiction resolution without
|
|
2051
|
+
* importing drizzle. REQUIRED — every adapter implements it (the InMemory
|
|
2052
|
+
* test adapter does a substring/subject match).
|
|
2053
|
+
*/
|
|
2054
|
+
findContradictingFacts(workspaceId: string, input: FindContradictingFactsInput): Promise<ContradictingFact[]>;
|
|
2055
|
+
/**
|
|
2056
|
+
* Wave X — GDPR hard-delete: permanently removes the row from mnemo_fact.
|
|
2057
|
+
* MUST be called only after scope check ("memory:hard_delete").
|
|
2058
|
+
* Optional — guards with `?.` at call sites.
|
|
2059
|
+
*/
|
|
2060
|
+
hardDeleteFact?(id: string, workspaceId: string): Promise<void>;
|
|
2061
|
+
/**
|
|
2062
|
+
* Wave X — GDPR erasure audit: appends a row to mnemo_deletion_log.
|
|
2063
|
+
* Log is INSERT-only for app role (enforced by migration 0001).
|
|
2064
|
+
* Optional — guards with `?.` at call sites.
|
|
2065
|
+
*/
|
|
2066
|
+
appendDeletionLog?(input: {
|
|
2067
|
+
workspaceId: string;
|
|
2068
|
+
deletedItemId: string;
|
|
2069
|
+
deletedItemType: string;
|
|
2070
|
+
deletionType: "soft" | "hard" | "gdpr_erasure" | "federation_tombstone" | "retention_purge";
|
|
2071
|
+
actorId: string;
|
|
2072
|
+
reason?: string;
|
|
2073
|
+
}): Promise<void>;
|
|
2074
|
+
/**
|
|
2075
|
+
* SOC2 CF3 — bulk soft-close facts past their retention window for a given
|
|
2076
|
+
* sensitivity tier. Runs inside a single db.transaction with the workspace
|
|
2077
|
+
* GUC set; paginated at `limit` rows per call (default 500) to bound
|
|
2078
|
+
* transaction length. On dryRun=true counts rows without mutating any.
|
|
2079
|
+
*
|
|
2080
|
+
* Returns `eraseCandidateActorIds`: actors whose remaining active
|
|
2081
|
+
* confidential+restricted facts count reaches zero after this purge — safe
|
|
2082
|
+
* to call destroyActorDek on. Always empty for the internal tier (no DEK).
|
|
2083
|
+
*
|
|
2084
|
+
* Optional — callers guard with `?.`.
|
|
2085
|
+
*/
|
|
2086
|
+
purgeFacts?(filter: PurgeFactsFilter): Promise<PurgeFactsResult>;
|
|
2087
|
+
/**
|
|
2088
|
+
* GDPR crypto-erasure — returns the base64-encoded encrypted DEK for an
|
|
2089
|
+
* active actor, or null if the DEK has been destroyed or never provisioned.
|
|
2090
|
+
* Already implemented in DrizzleStorageAdapter since Wave P/P1.2.
|
|
2091
|
+
*/
|
|
2092
|
+
getActorDek?(workspaceId: string, actorId: string): Promise<string | null>;
|
|
2093
|
+
/**
|
|
2094
|
+
* GDPR crypto-erasure — destroys an actor's DEK (marks it 'destroyed' and
|
|
2095
|
+
* nulls the key material). Returns true if a live DEK was found and destroyed.
|
|
2096
|
+
* Already implemented in DrizzleStorageAdapter since Wave P/P1.2.
|
|
2097
|
+
*/
|
|
2098
|
+
destroyActorDek?(workspaceId: string, actorId: string): Promise<boolean>;
|
|
2099
|
+
/**
|
|
2100
|
+
* §11 governance (demote path): enqueue a fact as an archive candidate for
|
|
2101
|
+
* human/automated review. OPTIONAL — callers must guard with `?.`.
|
|
2102
|
+
* The `mnemo_review_queue` table exists in the baseline migration.
|
|
2103
|
+
*/
|
|
2104
|
+
enqueueReview?(input: {
|
|
2105
|
+
workspaceId: string;
|
|
2106
|
+
primitiveKind: string;
|
|
2107
|
+
primitiveId: string;
|
|
2108
|
+
reason: string;
|
|
2109
|
+
priority?: number;
|
|
2110
|
+
}): Promise<void>;
|
|
2111
|
+
/** §11 governance: set/clear the canonical exemption flag. */
|
|
2112
|
+
setCanonical(id: string, workspaceId: string, canonical: boolean): Promise<void>;
|
|
2113
|
+
/** §11 governance.propagate: fact IDs recalled in a session (for DAG seeding). */
|
|
2114
|
+
getRecalledFactIds(workspaceId: string, sessionId: string): Promise<string[]>;
|
|
2115
|
+
/**
|
|
2116
|
+
* Return task id+status pairs linked to a session.
|
|
2117
|
+
* Used by the collapse pipeline to compute the task-completion outcome signal (RDD-1).
|
|
2118
|
+
* OPTIONAL — callers MUST guard with `?.`.
|
|
2119
|
+
*/
|
|
2120
|
+
listTasksForSession?(workspaceId: string, sessionId: string): Promise<Array<{
|
|
2121
|
+
id: string;
|
|
2122
|
+
status: string;
|
|
2123
|
+
}>>;
|
|
2124
|
+
/**
|
|
2125
|
+
* §11 TD(λ): walk the provenance DAG (derived_from/part_of edges) backward from
|
|
2126
|
+
* `terminalIds`, returning each predecessor's decayed credit = lambda^depth.
|
|
2127
|
+
* Bounded by maxHops (spec line 1037, default 5). Cyclic-safe.
|
|
2128
|
+
*/
|
|
2129
|
+
getProvenanceCredit(workspaceId: string, terminalIds: string[], lambda: number, maxHops: number): Promise<Array<{
|
|
2130
|
+
factId: string;
|
|
2131
|
+
credit: number;
|
|
2132
|
+
}>>;
|
|
2133
|
+
/**
|
|
2134
|
+
* §9 L3 — cosine>=threshold lookup against mnemo_query_cache; null on miss.
|
|
2135
|
+
* Uses an HNSW index on the embedding column for fast ANN search.
|
|
2136
|
+
*/
|
|
2137
|
+
lookupQueryCache?(workspaceId: string, embedding: Float32Array, threshold: number, scope?: string): Promise<{
|
|
2138
|
+
resultIds: string[];
|
|
2139
|
+
resultKinds: string[];
|
|
2140
|
+
} | null>;
|
|
2141
|
+
/** §9 L3 — store a recall result set for 24h reuse. */
|
|
2142
|
+
upsertQueryCache?(input: {
|
|
2143
|
+
workspaceId: string;
|
|
2144
|
+
queryText: string;
|
|
2145
|
+
embedding: Float32Array;
|
|
2146
|
+
resultIds: string[];
|
|
2147
|
+
resultKinds: string[];
|
|
2148
|
+
ttlMs: number;
|
|
2149
|
+
}): Promise<void>;
|
|
2150
|
+
/** §9 L3 embedding LRU — exact text-hash lookup; null on miss. */
|
|
2151
|
+
getCachedEmbedding?(workspaceId: string, textHash: string): Promise<Float32Array | null>;
|
|
2152
|
+
/** §9 L3 embedding LRU — insert or refresh an embedding record. */
|
|
2153
|
+
putCachedEmbedding?(input: {
|
|
2154
|
+
workspaceId: string;
|
|
2155
|
+
textHash: string;
|
|
2156
|
+
embedding: Float32Array;
|
|
2157
|
+
model: string;
|
|
2158
|
+
}): Promise<void>;
|
|
2159
|
+
createDecision(input: CreateDecisionInput): Promise<MnemoDecision>;
|
|
2160
|
+
getDecision(id: string, workspaceId: string): Promise<MnemoDecision | null>;
|
|
2161
|
+
updateDecision(id: string, input: UpdateDecisionInput): Promise<MnemoDecision>;
|
|
2162
|
+
archiveDecision(id: string, workspaceId: string): Promise<void>;
|
|
2163
|
+
queryDecisions(filter: DecisionFilter): Promise<PaginatedResult<MnemoDecision>>;
|
|
2164
|
+
createEpisode(input: CreateEpisodeInput): Promise<MnemoEpisode>;
|
|
2165
|
+
getEpisode(id: string, workspaceId: string): Promise<MnemoEpisode | null>;
|
|
2166
|
+
updateEpisode(id: string, input: UpdateEpisodeInput): Promise<MnemoEpisode>;
|
|
2167
|
+
archiveEpisode(id: string, workspaceId: string): Promise<void>;
|
|
2168
|
+
queryEpisodes(filter: EpisodeFilter): Promise<PaginatedResult<MnemoEpisode>>;
|
|
2169
|
+
/**
|
|
2170
|
+
* Reconstruct an episode's full narrative by walking parentEpisodeId to the
|
|
2171
|
+
* root and folding deltaContent in depth order (root→leaf). Spec §16.
|
|
2172
|
+
*/
|
|
2173
|
+
reconstructEpisode(id: string, workspaceId: string): Promise<MnemoEpisode>;
|
|
2174
|
+
/**
|
|
2175
|
+
* Spec §16 episode trees: return the matched episode's parent, siblings (same
|
|
2176
|
+
* parentEpisodeId) and direct children — the RELATED neighbourhood for recall
|
|
2177
|
+
* expansion. Workspace-scoped; excludes the episode itself. Capped at `limit`
|
|
2178
|
+
* (default 10). Optional for backward compatibility with adapters that don't
|
|
2179
|
+
* implement tree traversal.
|
|
2180
|
+
*/
|
|
2181
|
+
getEpisodeTreeNeighbors?(episodeId: string, workspaceId: string, limit?: number): Promise<MnemoEpisode[]>;
|
|
2182
|
+
/**
|
|
2183
|
+
* DELTAMEM §16 — HNSW cosine search over mnemo_episode.embedding, scoped to
|
|
2184
|
+
* `workspaceId`. Returns up to `limit` episodes whose embedding cosine
|
|
2185
|
+
* similarity to `embedding` is ≥ `minSim`, most-similar first. Rows with a
|
|
2186
|
+
* NULL embedding (not yet indexed) are excluded. Used at episode-creation time
|
|
2187
|
+
* to find the nearest existing episode to delta-encode against (parent link).
|
|
2188
|
+
*
|
|
2189
|
+
* `embedding` is a query vector of the embedder's dimension (1536). `minSim`
|
|
2190
|
+
* is a cosine similarity in [0,1]. Implementations without a vector index
|
|
2191
|
+
* (InMemory) may return an empty list.
|
|
2192
|
+
*/
|
|
2193
|
+
findSimilarEpisodes(workspaceId: string, embedding: number[], limit: number, minSim: number): Promise<SimilarEpisode[]>;
|
|
2194
|
+
/**
|
|
2195
|
+
* P16 — HNSW cosine search over mnemo_entity.embedding, scoped to
|
|
2196
|
+
* `workspaceId`. Returns up to `limit` entities whose embedding cosine
|
|
2197
|
+
* similarity to `embedding` is ≥ `minSim`, most-similar first. Rows with a
|
|
2198
|
+
* NULL embedding (not yet indexed) are excluded. Implementations without a
|
|
2199
|
+
* vector index (InMemory) may return an empty list.
|
|
2200
|
+
*/
|
|
2201
|
+
findSimilarEntities(workspaceId: string, embedding: number[], limit: number, minSim: number): Promise<SimilarEntity[]>;
|
|
2202
|
+
/**
|
|
2203
|
+
* Count active primitives per knowledge type for the UCE scheduler (spec §10).
|
|
2204
|
+
* Keys are the 10 RememberKind values; missing types may be omitted (treated as 0).
|
|
2205
|
+
*/
|
|
2206
|
+
getKnowledgeDistribution(workspaceId: string): Promise<Partial<Record<RememberKind, number>>>;
|
|
2207
|
+
/**
|
|
2208
|
+
* Persist an Experience-Compression result (spec §2): replace the root
|
|
2209
|
+
* episode's narrative with the compressed summary and stash retained leaf
|
|
2210
|
+
* deltas + provenance in metadata. Idempotent on re-run.
|
|
2211
|
+
*/
|
|
2212
|
+
persistCompression(input: {
|
|
2213
|
+
workspaceId: string;
|
|
2214
|
+
rootEpisodeId: string;
|
|
2215
|
+
compressedNarrative: string;
|
|
2216
|
+
retainedDeltas: Array<{
|
|
2217
|
+
episodeId: string;
|
|
2218
|
+
deltaContent: string;
|
|
2219
|
+
}>;
|
|
2220
|
+
}): Promise<void>;
|
|
2221
|
+
createEntity(input: CreateEntityInput): Promise<MnemoEntity>;
|
|
2222
|
+
getEntity(id: string, workspaceId: string): Promise<MnemoEntity | null>;
|
|
2223
|
+
updateEntity(id: string, input: UpdateEntityInput): Promise<MnemoEntity>;
|
|
2224
|
+
archiveEntity(id: string, workspaceId: string): Promise<void>;
|
|
2225
|
+
queryEntities(filter: EntityFilter): Promise<PaginatedResult<MnemoEntity>>;
|
|
2226
|
+
createStrategy(input: CreateStrategyInput): Promise<MnemoStrategy>;
|
|
2227
|
+
getStrategy(id: string, workspaceId: string): Promise<MnemoStrategy | null>;
|
|
2228
|
+
updateStrategy(id: string, input: UpdateStrategyInput): Promise<MnemoStrategy>;
|
|
2229
|
+
archiveStrategy(id: string, workspaceId: string): Promise<void>;
|
|
2230
|
+
queryStrategies(filter: StrategyFilter): Promise<PaginatedResult<MnemoStrategy>>;
|
|
2231
|
+
createWorkflow(input: CreateWorkflowInput): Promise<MnemoWorkflow>;
|
|
2232
|
+
getWorkflow(id: string, workspaceId: string): Promise<MnemoWorkflow | null>;
|
|
2233
|
+
updateWorkflow(id: string, input: UpdateWorkflowInput): Promise<MnemoWorkflow>;
|
|
2234
|
+
archiveWorkflow(id: string, workspaceId: string): Promise<void>;
|
|
2235
|
+
queryWorkflows(filter: WorkflowFilter): Promise<PaginatedResult<MnemoWorkflow>>;
|
|
2236
|
+
createSkill(input: CreateSkillInput): Promise<MnemoSkill>;
|
|
2237
|
+
getSkill(id: string, workspaceId: string): Promise<MnemoSkill | null>;
|
|
2238
|
+
updateSkill(id: string, input: UpdateSkillInput): Promise<MnemoSkill>;
|
|
2239
|
+
archiveSkill(id: string, workspaceId: string): Promise<void>;
|
|
2240
|
+
querySkills(filter: SkillFilter): Promise<PaginatedResult<MnemoSkill>>;
|
|
2241
|
+
createTask(input: CreateTaskInput): Promise<MnemoTask>;
|
|
2242
|
+
getTask(id: string, workspaceId: string): Promise<MnemoTask | null>;
|
|
2243
|
+
updateTask(id: string, input: UpdateTaskInput): Promise<MnemoTask>;
|
|
2244
|
+
archiveTask(id: string, workspaceId: string): Promise<void>;
|
|
2245
|
+
delegateTask(id: string, workspaceId: string, input: DelegateTaskInput): Promise<MnemoTask>;
|
|
2246
|
+
queryTasks(filter: TaskFilter): Promise<PaginatedResult<MnemoTask>>;
|
|
2247
|
+
createEvent(input: CreateEventInput): Promise<MnemoEvent>;
|
|
2248
|
+
getEvent(id: string, workspaceId: string): Promise<MnemoEvent | null>;
|
|
2249
|
+
archiveEvent(id: string, workspaceId: string): Promise<void>;
|
|
2250
|
+
appendEventAnnotation(id: string, workspaceId: string, annotation: EventAnnotation): Promise<MnemoEvent>;
|
|
2251
|
+
queryEvents(filter: EventFilter): Promise<PaginatedResult<MnemoEvent>>;
|
|
2252
|
+
/** P15: Raise the sensitivity of an event. Raise-only — calling code MUST verify
|
|
2253
|
+
* sensitivityAtLeast(newSensitivity, existing.sensitivity) before calling this. */
|
|
2254
|
+
updateEventSensitivity(id: string, workspaceId: string, sensitivity: Sensitivity): Promise<void>;
|
|
2255
|
+
createReasoning(input: CreateReasoningInput): Promise<MnemoReasoning>;
|
|
2256
|
+
getReasoning(id: string, workspaceId: string): Promise<MnemoReasoning | null>;
|
|
2257
|
+
updateReasoning(id: string, input: UpdateReasoningInput): Promise<MnemoReasoning>;
|
|
2258
|
+
archiveReasoning(id: string, workspaceId: string): Promise<void>;
|
|
2259
|
+
queryReasoning(filter: ReasoningFilter): Promise<PaginatedResult<MnemoReasoning>>;
|
|
2260
|
+
/** Wave M1 — CoT cache search. Returns candidates ranked by cosine similarity.
|
|
2261
|
+
* By default only servable rows (active + golden) are returned. */
|
|
2262
|
+
searchReasoning(input: {
|
|
2263
|
+
workspaceId: string;
|
|
2264
|
+
vector: number[];
|
|
2265
|
+
limit: number;
|
|
2266
|
+
includeAllStatuses?: boolean;
|
|
2267
|
+
}): Promise<Array<{
|
|
2268
|
+
id: string;
|
|
2269
|
+
cosine: number;
|
|
2270
|
+
worth: number;
|
|
2271
|
+
successCount: number;
|
|
2272
|
+
failureCount: number;
|
|
2273
|
+
status: MnemoReasoning["status"];
|
|
2274
|
+
}>>;
|
|
2275
|
+
/** Wave M1 — bump usage_count and last_used_at for a reasoning cache hit. */
|
|
2276
|
+
recordReasoningUse(id: string, workspaceId: string): Promise<void>;
|
|
2277
|
+
/** Wave M1 — transition lifecycle status (quarantined / golden / active). */
|
|
2278
|
+
setReasoningStatus(id: string, workspaceId: string, status: MnemoReasoning["status"]): Promise<void>;
|
|
2279
|
+
getAgentProfile(workspaceId: string, agentId: string): Promise<MnemoAgentProfile | null>;
|
|
2280
|
+
upsertAgentProfile(input: {
|
|
2281
|
+
workspaceId: string;
|
|
2282
|
+
agentId: string;
|
|
2283
|
+
summary?: string;
|
|
2284
|
+
metadata?: Record<string, unknown>;
|
|
2285
|
+
}): Promise<MnemoAgentProfile>;
|
|
2286
|
+
/**
|
|
2287
|
+
* Increment the sessionsSinceReflection counter in the agent profile's metadata.
|
|
2288
|
+
* Creates a profile row if one does not exist yet.
|
|
2289
|
+
* Returns the new counter value.
|
|
2290
|
+
*/
|
|
2291
|
+
incrementSessionsSinceReflection(workspaceId: string, agentId: string): Promise<number>;
|
|
2292
|
+
createHyperedge(input: CreateHyperedgeInput): Promise<MnemoHyperedge>;
|
|
2293
|
+
getHyperedge(id: string, workspaceId: string): Promise<MnemoHyperedge | null>;
|
|
2294
|
+
updateHyperedge(id: string, input: UpdateHyperedgeInput): Promise<MnemoHyperedge>;
|
|
2295
|
+
archiveHyperedge(id: string, workspaceId: string): Promise<void>;
|
|
2296
|
+
queryHyperedges(filter: HyperedgeFilter): Promise<PaginatedResult<MnemoHyperedge>>;
|
|
2297
|
+
bumpHyperedgeActivation(id: string, workspaceId: string): Promise<void>;
|
|
2298
|
+
createCompositionRule(input: CreateCompositionRuleInput): Promise<MnemoCompositionRule>;
|
|
2299
|
+
getCompositionRule(id: string, workspaceId: string): Promise<MnemoCompositionRule | null>;
|
|
2300
|
+
updateCompositionRule(id: string, workspaceId: string, input: UpdateCompositionRuleInput): Promise<MnemoCompositionRule>;
|
|
2301
|
+
queryCompositionRules(filter: CompositionRuleFilter): Promise<PaginatedResult<MnemoCompositionRule>>;
|
|
2302
|
+
bumpCompositionExecution(id: string, workspaceId: string): Promise<void>;
|
|
2303
|
+
/**
|
|
2304
|
+
* Idempotently seed the 7 built-in composition rule templates for a workspace.
|
|
2305
|
+
* Calls `mnemo_seed_builtin_rules(workspace_id)` which runs ON CONFLICT DO NOTHING
|
|
2306
|
+
* so repeated calls are safe. Called lazily on first write per workspace so every
|
|
2307
|
+
* fresh workspace gets the inference engine populated automatically.
|
|
2308
|
+
*/
|
|
2309
|
+
ensureBuiltinCompositionRules(workspaceId: string): Promise<void>;
|
|
2310
|
+
appendInference(input: AppendInferenceInput): Promise<MnemoInferenceLogEntry>;
|
|
2311
|
+
queryInferences(filter: InferenceLogFilter): Promise<PaginatedResult<MnemoInferenceLogEntry>>;
|
|
2312
|
+
materialiseInference(input: MaterialiseInferenceInput): Promise<{
|
|
2313
|
+
id: string;
|
|
2314
|
+
}>;
|
|
2315
|
+
lookupFactHash(workspaceId: string, statementHash: string): Promise<MnemoFactHash | null>;
|
|
2316
|
+
upsertFactHash(input: UpsertFactHashInput): Promise<MnemoFactHash>;
|
|
2317
|
+
upsertFactLsh(input: UpsertFactLshInput): Promise<void>;
|
|
2318
|
+
pointerCandidates(query: PointerCandidateQuery): Promise<PointerCandidate[]>;
|
|
2319
|
+
getRecallPrimitives(workspaceId: string, refs: RecallPrimitiveRef[]): Promise<RecallPrimitiveRecord[]>;
|
|
2320
|
+
getRecallLogs(workspaceId: string, memoryIds: string[], limitPerMemory: number): Promise<RecallLogRecord[]>;
|
|
2321
|
+
getRecallStructures(workspaceId: string, sourceIds: string[], hyperedgeLimitPerMember: number): Promise<RecallStructures>;
|
|
2322
|
+
/** FTS arm of hybrid Tier-3 recall: full-text match over text_lemmatized (migration 0047),
|
|
2323
|
+
* workspace-scoped, returns up to `limit` PointerCandidate rows. Adapters without FTS return []. */
|
|
2324
|
+
ftsCandidates?(query: Omit<PointerCandidateQuery, "bands">): Promise<FtsCandidate[]>;
|
|
2325
|
+
getConfidenceMap(workspaceId: string, opts?: {
|
|
2326
|
+
limit?: number;
|
|
2327
|
+
}): Promise<ConfidenceMapRow[]>;
|
|
2328
|
+
getKnowledgeGaps(workspaceId: string, opts?: {
|
|
2329
|
+
limit?: number;
|
|
2330
|
+
minScore?: number;
|
|
2331
|
+
}): Promise<KnowledgeGapRow[]>;
|
|
2332
|
+
getMetacognitionTrends(workspaceId: string): Promise<MetacognitionTrends>;
|
|
2333
|
+
refreshMetacognitionViews(): Promise<void>;
|
|
2334
|
+
getSequentialPatterns(args: {
|
|
2335
|
+
workspaceId: string;
|
|
2336
|
+
predecessorId?: string;
|
|
2337
|
+
minConfidence?: number;
|
|
2338
|
+
limit?: number;
|
|
2339
|
+
}): Promise<SequentialPatternRow[]>;
|
|
2340
|
+
getPeriodicPatterns(args: {
|
|
2341
|
+
workspaceId: string;
|
|
2342
|
+
dayOfWeek?: number;
|
|
2343
|
+
hourBucket?: number;
|
|
2344
|
+
limit?: number;
|
|
2345
|
+
}): Promise<PeriodicPatternRow[]>;
|
|
2346
|
+
refreshAnticipationViews(): Promise<void>;
|
|
2347
|
+
getConditionalPatterns(args: {
|
|
2348
|
+
workspaceId: string;
|
|
2349
|
+
queryKey?: string;
|
|
2350
|
+
minConfidence?: number;
|
|
2351
|
+
limit?: number;
|
|
2352
|
+
}): Promise<ConditionalPatternRow[]>;
|
|
2353
|
+
getCoOccurrencePatterns(args: {
|
|
2354
|
+
workspaceId: string;
|
|
2355
|
+
sourceId: string;
|
|
2356
|
+
minCoRecall?: number;
|
|
2357
|
+
limit?: number;
|
|
2358
|
+
}): Promise<CoOccurrencePatternRow[]>;
|
|
2359
|
+
createRelation(input: CreateRelationInput): Promise<MnemoRelation>;
|
|
2360
|
+
getRelations(filter: RelationFilter): Promise<MnemoRelation[]>;
|
|
2361
|
+
updateRelationStrength(id: string, delta: number): Promise<void>;
|
|
2362
|
+
deleteRelation(id: string, workspaceId: string): Promise<void>;
|
|
2363
|
+
updateWorth(id: string, workspaceId: string, primitiveKind: PrimitiveKind, delta: WorthDelta): Promise<void>;
|
|
2364
|
+
recordRecall(entry: RecallLogEntry): Promise<void>;
|
|
2365
|
+
/**
|
|
2366
|
+
* Fetch predecessor recalls in the same session for TD(λ) backward propagation.
|
|
2367
|
+
* Returns facts recalled before `excludeFactId` in this session, most-recent first,
|
|
2368
|
+
* up to 20 entries. Each entry includes the stored tdCredit (λ^rank).
|
|
2369
|
+
*/
|
|
2370
|
+
getTdPredecessors(workspaceId: string, sessionId: string, excludeFactId: string): Promise<Array<{
|
|
2371
|
+
factId: string;
|
|
2372
|
+
tdCredit: number;
|
|
2373
|
+
recalledAt: Date;
|
|
2374
|
+
}>>;
|
|
2375
|
+
appendAuditEntry(entry: Omit<AuditLogEntry, "id" | "createdAt">): Promise<void>;
|
|
2376
|
+
/**
|
|
2377
|
+
* Return the last `limit` audit log entries for a workspace, ordered by id ASC
|
|
2378
|
+
* (oldest first — required by verifyAuditChain() which expects forward order).
|
|
2379
|
+
* Used by the mnemo.audit.merkle cron job for integrity verification.
|
|
2380
|
+
*/
|
|
2381
|
+
listAuditLog(workspaceId: string, limit: number): Promise<AuditLogEntry[]>;
|
|
2382
|
+
appendOutbox(entry: Omit<OutboxEntry, "id" | "createdAt" | "attempts">): Promise<void>;
|
|
2383
|
+
claimOutbox(limit: number): Promise<OutboxEntry[]>;
|
|
2384
|
+
markOutboxProcessed(ids: string[]): Promise<void>;
|
|
2385
|
+
markOutboxFailed(id: string, error: string): Promise<void>;
|
|
2386
|
+
/** Move permanently exhausted outbox entries to a dead-letter state. Returns the count moved. */
|
|
2387
|
+
reapDeadLetters(maxAttempts: number): Promise<number>;
|
|
2388
|
+
/** Delete old processed outbox entries. Returns the count deleted. */
|
|
2389
|
+
purgeOutbox(olderThanMs: number): Promise<number>;
|
|
2390
|
+
/** Count outbox rows not yet delivered (processedAt IS NULL). For queue-depth telemetry. */
|
|
2391
|
+
countPendingOutbox(): Promise<number>;
|
|
2392
|
+
createWebhookEndpoint(input: CreateWebhookEndpointInput): Promise<MnemoWebhookEndpoint>;
|
|
2393
|
+
getWebhookEndpoint(id: string, workspaceId: string): Promise<MnemoWebhookEndpoint | null>;
|
|
2394
|
+
listWebhookEndpoints(workspaceId: string): Promise<MnemoWebhookEndpoint[]>;
|
|
2395
|
+
updateWebhookEndpoint(id: string, input: UpdateWebhookEndpointInput): Promise<MnemoWebhookEndpoint>;
|
|
2396
|
+
deleteWebhookEndpoint(id: string, workspaceId: string): Promise<void>;
|
|
2397
|
+
listActiveWebhookEndpoints(workspaceId: string, eventType: string): Promise<MnemoWebhookEndpoint[]>;
|
|
2398
|
+
recordWebhookDelivery(entry: CreateWebhookDeliveryInput): Promise<void>;
|
|
2399
|
+
listWebhookDeliveries(webhookId: string, workspaceId: string, limit?: number): Promise<MnemoWebhookDelivery[]>;
|
|
2400
|
+
/** Delivery-worker: returns pending deliveries due for their next attempt. */
|
|
2401
|
+
listPendingWebhookDeliveries(limit: number): Promise<MnemoWebhookDelivery[]>;
|
|
2402
|
+
/** Delivery-worker: update delivery row after an attempt. */
|
|
2403
|
+
updateWebhookDelivery(id: string, workspaceId: string, update: {
|
|
2404
|
+
status?: "pending" | "delivered" | "failed";
|
|
2405
|
+
responseStatus?: number;
|
|
2406
|
+
responseBody?: string;
|
|
2407
|
+
attempt?: number;
|
|
2408
|
+
deliveredAt?: Date;
|
|
2409
|
+
nextAttemptAt?: Date | null;
|
|
2410
|
+
}): Promise<void>;
|
|
2411
|
+
createReminder(input: CreateReminderInput): Promise<MnemoReminder>;
|
|
2412
|
+
getReminder(id: string, workspaceId: string): Promise<MnemoReminder | null>;
|
|
2413
|
+
listPendingReminders(workspaceId: string, asOf: Date): Promise<MnemoReminder[]>;
|
|
2414
|
+
dismissReminder(id: string, workspaceId: string, newStatus: "triggered" | "dismissed"): Promise<void>;
|
|
2415
|
+
listReminders(workspaceId: string, status: "pending" | "triggered" | "dismissed" | "all", limit: number): Promise<MnemoReminder[]>;
|
|
2416
|
+
/** Append a recall event for a memory. Used by Stage 4 Petrov activation. */
|
|
2417
|
+
logRecall(workspaceId: string, memoryId: string, score: number): Promise<void>;
|
|
2418
|
+
/** Fetch the most recent recall timestamps for a memory, newest first. */
|
|
2419
|
+
getRecallLog(workspaceId: string, memoryId: string, limit: number): Promise<Array<{
|
|
2420
|
+
id: string;
|
|
2421
|
+
recalledAt: string;
|
|
2422
|
+
recallScore: number;
|
|
2423
|
+
}>>;
|
|
2424
|
+
/**
|
|
2425
|
+
* Return up to `limit` distinct query texts from mnemo_recall_log whose
|
|
2426
|
+
* fact_id matches any of `factIds`, ordered by recalled_at DESC.
|
|
2427
|
+
* Used by the §12 consolidation replay gate to prefer real historical
|
|
2428
|
+
* queries over LLM-generated synthetic ones. Returns [] when the log
|
|
2429
|
+
* is empty or no rows match.
|
|
2430
|
+
*/
|
|
2431
|
+
getRecentQueriesForFacts(workspaceId: string, factIds: string[], limit: number): Promise<string[]>;
|
|
2432
|
+
/**
|
|
2433
|
+
* Decay Beta evidence (worth_alpha/worth_beta) for all facts of a given
|
|
2434
|
+
* decay class using exponential half-life. Entity class is a no-op (returns 0).
|
|
2435
|
+
* Returns the number of rows updated.
|
|
2436
|
+
*/
|
|
2437
|
+
decayKind(workspaceId: string, decayClass: DecayClass, halfLifeDays: number): Promise<number>;
|
|
2438
|
+
/**
|
|
2439
|
+
* Record a co-recall event between two facts: computes STDP Δw from
|
|
2440
|
+
* the inter-spike interval (now − lastCoRecallAt) and updates
|
|
2441
|
+
* hebbian_weight, directionality, co_recall_count, last_co_recall_at.
|
|
2442
|
+
*/
|
|
2443
|
+
recordCoRecallStdp(workspaceId: string, relationId: string, coRecalledAt: Date): Promise<void>;
|
|
2444
|
+
/**
|
|
2445
|
+
* Homeostatic weekly rescale: renormalise hebbian_weight for a workspace
|
|
2446
|
+
* via PERCENT_RANK() OVER (ORDER BY hebbian_weight). Returns rows updated.
|
|
2447
|
+
*/
|
|
2448
|
+
normalizeHebbianWeights(workspaceId: string): Promise<number>;
|
|
2449
|
+
/** Enqueue a primitive for human/auto review (e.g. codebase drift). */
|
|
2450
|
+
enqueueReviewItem(input: {
|
|
2451
|
+
workspaceId: string;
|
|
2452
|
+
primitiveId: string;
|
|
2453
|
+
primitiveKind?: string;
|
|
2454
|
+
reason: string;
|
|
2455
|
+
detail?: Record<string, unknown>;
|
|
2456
|
+
}): Promise<void>;
|
|
2457
|
+
/** Query facts that are codebase/config/infrastructure sourced (for drift verification). */
|
|
2458
|
+
queryDriftCandidates(workspaceId: string): Promise<Array<{
|
|
2459
|
+
id: string;
|
|
2460
|
+
statement: string;
|
|
2461
|
+
metadata: Record<string, unknown>;
|
|
2462
|
+
}>>;
|
|
2463
|
+
healthCheck(): Promise<HealthStatus>;
|
|
2464
|
+
close(): Promise<void>;
|
|
2465
|
+
listWorkspaceIds(): Promise<string[]>;
|
|
2466
|
+
/**
|
|
2467
|
+
* Return up to `limit` rows from `table` whose `embedding_stale = true`
|
|
2468
|
+
* or whose `embedding_model != currentModel`.
|
|
2469
|
+
* Table is one of: "fact" | "decision" | "skill" | "strategy" | "reasoning".
|
|
2470
|
+
*/
|
|
2471
|
+
listStaleEmbeddings(table: EmbeddableTable, workspaceId: string, currentModel: string, limit: number): Promise<Array<{
|
|
2472
|
+
id: string;
|
|
2473
|
+
text: string;
|
|
2474
|
+
}>>;
|
|
2475
|
+
/** Check if workspace has an ongoing embedding migration (stale embeddings exist). */
|
|
2476
|
+
hasActiveEmbeddingMigration?(workspaceId: string): Promise<boolean>;
|
|
2477
|
+
/**
|
|
2478
|
+
* Mark all rows in `table` for `workspaceId` as stale where
|
|
2479
|
+
* `embedding_model != currentModel`. Returns count of updated rows.
|
|
2480
|
+
*/
|
|
2481
|
+
markEmbeddingsStale(table: EmbeddableTable, workspaceId: string, currentModel: string): Promise<number>;
|
|
2482
|
+
/**
|
|
2483
|
+
* Write a freshly computed embedding + stamp `embedding_model = model`
|
|
2484
|
+
* and `embedding_stale = false` for the given row.
|
|
2485
|
+
*/
|
|
2486
|
+
updateEmbeddingVector(table: EmbeddableTable, id: string, workspaceId: string, vector: number[], model: string): Promise<void>;
|
|
2487
|
+
/**
|
|
2488
|
+
* Upsert hot-tier snapshot rows into mnemo_hot_tier_snapshot.
|
|
2489
|
+
* Uses ON CONFLICT DO UPDATE to overwrite stale scores.
|
|
2490
|
+
*/
|
|
2491
|
+
upsertHotTierSnapshot(rows: HotTierSnapshotRow[]): Promise<void>;
|
|
2492
|
+
/**
|
|
2493
|
+
* Load hot-tier snapshot rows. When workspaceId is provided, scoped to
|
|
2494
|
+
* that workspace; otherwise returns all rows (used at boot to reload all).
|
|
2495
|
+
*/
|
|
2496
|
+
loadHotTierSnapshots(workspaceId?: string): Promise<HotTierSnapshotRow[]>;
|
|
2497
|
+
/**
|
|
2498
|
+
* Return tasks that have been in a non-terminal status for longer than
|
|
2499
|
+
* `staleSinceMs` milliseconds. Used by the stale-task cron to auto-archive
|
|
2500
|
+
* tasks that are abandoned without being explicitly closed.
|
|
2501
|
+
*
|
|
2502
|
+
* Terminal statuses (completed, archived) are excluded — only active tasks
|
|
2503
|
+
* are returned. Optional because the cron gracefully skips if absent.
|
|
2504
|
+
*
|
|
2505
|
+
* @param workspaceId - workspace to scan
|
|
2506
|
+
* @param staleSinceMs - how old the updatedAt must be (ms, default 7 days)
|
|
2507
|
+
* @param limit - max rows to return per cron tick (default 100)
|
|
2508
|
+
*/
|
|
2509
|
+
listStaleTasks?(workspaceId: string, staleSinceMs: number, limit: number): Promise<Array<{
|
|
2510
|
+
id: string;
|
|
2511
|
+
title: string;
|
|
2512
|
+
status: string;
|
|
2513
|
+
updatedAt: Date;
|
|
2514
|
+
}>>;
|
|
2515
|
+
/**
|
|
2516
|
+
* Returns a per-(type,status) fact count for the snapshot gauge.
|
|
2517
|
+
* Aggregate across all workspaces; only called on Prometheus scrape (every ~15s).
|
|
2518
|
+
* Optional — callers guard with `?.()`.
|
|
2519
|
+
*/
|
|
2520
|
+
countFactsByTypeStatus?(): Promise<Array<{
|
|
2521
|
+
type: string;
|
|
2522
|
+
status: string;
|
|
2523
|
+
count: number;
|
|
2524
|
+
}>>;
|
|
2525
|
+
/**
|
|
2526
|
+
* Returns fact counts bucketed by worth score.
|
|
2527
|
+
* Buckets: '0.0-0.2', '0.2-0.4', '0.4-0.6', '0.6-0.8', '0.8-1.0'.
|
|
2528
|
+
*/
|
|
2529
|
+
worthHistogram?(): Promise<Array<{
|
|
2530
|
+
bucket: string;
|
|
2531
|
+
count: number;
|
|
2532
|
+
}>>;
|
|
2533
|
+
/**
|
|
2534
|
+
* Returns the number of currently active sessions (status = 'active').
|
|
2535
|
+
*/
|
|
2536
|
+
countActiveSessions?(): Promise<number>;
|
|
2537
|
+
/**
|
|
2538
|
+
* Returns task counts grouped by status.
|
|
2539
|
+
*/
|
|
2540
|
+
countTasksByStatus?(): Promise<Array<{
|
|
2541
|
+
status: string;
|
|
2542
|
+
count: number;
|
|
2543
|
+
}>>;
|
|
2544
|
+
/**
|
|
2545
|
+
* Returns the count of stale tasks (reuses listStaleTasks logic).
|
|
2546
|
+
*/
|
|
2547
|
+
countStaleTasks?(): Promise<number>;
|
|
2548
|
+
/**
|
|
2549
|
+
* Get the operational mode for a workspace (learning or production).
|
|
2550
|
+
* Returns null if no mode row exists yet (caller should treat as learning mode).
|
|
2551
|
+
*
|
|
2552
|
+
* RDD-5: extended with startedAt, factCount, entityCount for multi-criteria graduation.
|
|
2553
|
+
*/
|
|
2554
|
+
getWorkspaceMode?(workspaceId: string): Promise<{
|
|
2555
|
+
mode: "learning" | "production";
|
|
2556
|
+
sessionCount: number;
|
|
2557
|
+
promoteAt: number | null;
|
|
2558
|
+
/** When the workspace entered learning mode (for daysElapsed graduation criterion). */
|
|
2559
|
+
startedAt?: Date;
|
|
2560
|
+
/** Cumulative fact count (for factCount >= 50 graduation criterion). */
|
|
2561
|
+
factCount?: number;
|
|
2562
|
+
/** Cumulative entity count (for entityCount >= 5 graduation criterion). */
|
|
2563
|
+
entityCount?: number;
|
|
2564
|
+
} | null>;
|
|
2565
|
+
/**
|
|
2566
|
+
* Upsert the workspace mode row. Used to:
|
|
2567
|
+
* - promote a workspace from learning → production
|
|
2568
|
+
* - increment sessionCount after each collapse
|
|
2569
|
+
*/
|
|
2570
|
+
setWorkspaceMode?(workspaceId: string, patch: {
|
|
2571
|
+
mode?: "learning" | "production";
|
|
2572
|
+
sessionCount?: number;
|
|
2573
|
+
promoteAt?: number | null;
|
|
2574
|
+
factCount?: number;
|
|
2575
|
+
entityCount?: number;
|
|
2576
|
+
}): Promise<void>;
|
|
2577
|
+
/**
|
|
2578
|
+
* §22 Dedup gate — return distinct topic_keys for facts in a session that were
|
|
2579
|
+
* tagged with a specific extraction_source (e.g. "per_turn").
|
|
2580
|
+
*
|
|
2581
|
+
* Used by the hybrid collapse dedup gate to skip collapse outputs whose topic_key
|
|
2582
|
+
* already exists in the per-turn extraction set for the same session — preventing
|
|
2583
|
+
* the same knowledge from being written twice (once per-turn, once at collapse).
|
|
2584
|
+
*
|
|
2585
|
+
* OPTIONAL — when absent the dedup gate is skipped (collapse proceeds normally).
|
|
2586
|
+
* Callers MUST guard with `?.`.
|
|
2587
|
+
*
|
|
2588
|
+
* @param workspaceId - scope the query to this workspace
|
|
2589
|
+
* @param sessionId - only facts from this session
|
|
2590
|
+
* @param source - extraction_source value (typically "per_turn")
|
|
2591
|
+
* @returns - array of distinct topic_key strings (nulls excluded)
|
|
2592
|
+
*/
|
|
2593
|
+
listSessionTopicKeysBySource?(workspaceId: string, sessionId: string, source: string): Promise<string[]>;
|
|
2594
|
+
/**
|
|
2595
|
+
* Atomically increment fact_count and entity_count in mnemo_workspace_mode.
|
|
2596
|
+
* Called after each successful collapse to keep graduation criteria up to date.
|
|
2597
|
+
*
|
|
2598
|
+
* OPTIONAL — when absent the counters are not updated. Callers MUST guard with `?.`.
|
|
2599
|
+
*/
|
|
2600
|
+
incrementWorkspaceModeCounters?(workspaceId: string, delta: {
|
|
2601
|
+
factCount?: number;
|
|
2602
|
+
entityCount?: number;
|
|
2603
|
+
sessionCount?: number;
|
|
2604
|
+
}): Promise<void>;
|
|
2605
|
+
/**
|
|
2606
|
+
* Return the full state JSON blob for a plugin in a workspace.
|
|
2607
|
+
* Returns null when no row exists yet (plugin has not persisted state).
|
|
2608
|
+
* OPTIONAL — callers guard with `?.`.
|
|
2609
|
+
*/
|
|
2610
|
+
getPluginState?(workspaceId: string, pluginId: string): Promise<Record<string, unknown> | null>;
|
|
2611
|
+
/**
|
|
2612
|
+
* Upsert the full state blob for a plugin in a workspace.
|
|
2613
|
+
* Uses ON CONFLICT (workspace_id, plugin_id) DO UPDATE.
|
|
2614
|
+
* OPTIONAL — callers guard with `?.`.
|
|
2615
|
+
*/
|
|
2616
|
+
upsertPluginState?(workspaceId: string, pluginId: string, state: Record<string, unknown>): Promise<void>;
|
|
2617
|
+
/**
|
|
2618
|
+
* Remove a single key from the plugin's state JSON.
|
|
2619
|
+
* No-op when the row or key does not exist.
|
|
2620
|
+
* OPTIONAL — callers guard with `?.`.
|
|
2621
|
+
*/
|
|
2622
|
+
deletePluginStateKey?(workspaceId: string, pluginId: string, key: string): Promise<void>;
|
|
2623
|
+
/**
|
|
2624
|
+
* List the N most-recent scored trajectories for an agent.
|
|
2625
|
+
* Each trajectory is a session-level probe with a worth score (0–1).
|
|
2626
|
+
* OPTIONAL — callers guard with `?.`.
|
|
2627
|
+
*/
|
|
2628
|
+
listScoredTrajectories?(workspaceId: string, agentId: string, limit: number): Promise<Array<{
|
|
2629
|
+
sessionId: string;
|
|
2630
|
+
score: number;
|
|
2631
|
+
promptVersionId: string | null;
|
|
2632
|
+
createdAt: Date;
|
|
2633
|
+
}>>;
|
|
2634
|
+
/**
|
|
2635
|
+
* Get the total spend (USD) for a workspace in the current calendar month.
|
|
2636
|
+
* Returns 0.0 when no spend rows exist.
|
|
2637
|
+
* Implemented as SUM(cost_usd) over mnemo_meter_event WHERE occurred_at >=
|
|
2638
|
+
* date_trunc('month', now()). OPTIONAL — callers guard with `?.`.
|
|
2639
|
+
*/
|
|
2640
|
+
getWorkspaceMonthlySpendUsd?(workspaceId: string): Promise<number>;
|
|
2641
|
+
/**
|
|
2642
|
+
* Durably append a single billing meter event (F15, spec §35 lines 4203-4217).
|
|
2643
|
+
*
|
|
2644
|
+
* Idempotent: `idempotencyKey` is UNIQUE in mnemo_meter_event, so a retried or
|
|
2645
|
+
* cross-replica duplicate write is silently dropped (ON CONFLICT DO NOTHING).
|
|
2646
|
+
* Fire-and-forget callers MUST NOT let a rejection bubble onto a request path.
|
|
2647
|
+
*
|
|
2648
|
+
* The shape is declared structurally (not imported from @mnemo-ai/core) so the
|
|
2649
|
+
* types package stays at the bottom of the dependency graph. `metric` is the
|
|
2650
|
+
* core MeterMetric string; `quantity` maps to the `units` column; `costUsd`
|
|
2651
|
+
* maps to the `cost_usd` column.
|
|
2652
|
+
*
|
|
2653
|
+
* OPTIONAL — callers guard with `?.`.
|
|
2654
|
+
*/
|
|
2655
|
+
appendMeterEvent?(event: {
|
|
2656
|
+
workspaceId: string;
|
|
2657
|
+
metric: string;
|
|
2658
|
+
quantity: number;
|
|
2659
|
+
occurredAt: Date;
|
|
2660
|
+
costUsd: number;
|
|
2661
|
+
idempotencyKey: string;
|
|
2662
|
+
}): Promise<void>;
|
|
2663
|
+
/**
|
|
2664
|
+
* Month-to-date usage counts per metric for a workspace, summed from the
|
|
2665
|
+
* durable mnemo_meter_event table (units grouped by operation, occurred_at >=
|
|
2666
|
+
* date_trunc('month', now())). Keys are MeterMetric strings; missing metrics
|
|
2667
|
+
* are absent (caller defaults to 0). Used by aggregation + GET /v1/usage so
|
|
2668
|
+
* usage survives restart. OPTIONAL — callers guard with `?.`.
|
|
2669
|
+
*/
|
|
2670
|
+
getMonthToDateUsageFromDb?(workspaceId: string): Promise<Record<string, number>>;
|
|
2671
|
+
/**
|
|
2672
|
+
* Get the total number of recall operations for a workspace in the current
|
|
2673
|
+
* calendar month. Returns 0 when no recall rows exist.
|
|
2674
|
+
* Used by the cognitive health snapshot (GET /v1/health/cognitive).
|
|
2675
|
+
* OPTIONAL — callers guard with `?.`.
|
|
2676
|
+
*/
|
|
2677
|
+
getWorkspaceMonthlyRecallCount?(workspaceId: string): Promise<number>;
|
|
2678
|
+
/**
|
|
2679
|
+
* Get the total LLM tokens consumed by a workspace since `since`.
|
|
2680
|
+
* Returns 0 when no token-usage rows exist.
|
|
2681
|
+
* Used by the cost dashboard (GET /v1/cost).
|
|
2682
|
+
* OPTIONAL — callers guard with `?.`.
|
|
2683
|
+
*/
|
|
2684
|
+
getWorkspaceLLMTokenUsage?(workspaceId: string, since: Date): Promise<number>;
|
|
2685
|
+
/**
|
|
2686
|
+
* Get the total embedding tokens consumed by a workspace since `since`.
|
|
2687
|
+
* Returns 0 when no embedding-usage rows exist.
|
|
2688
|
+
* Used by the cost dashboard (GET /v1/cost).
|
|
2689
|
+
* OPTIONAL — callers guard with `?.`.
|
|
2690
|
+
*/
|
|
2691
|
+
getWorkspaceEmbeddingTokenUsage?(workspaceId: string, since: Date): Promise<number>;
|
|
2692
|
+
/**
|
|
2693
|
+
* Insert a new prompt version row in status 'candidate'.
|
|
2694
|
+
* Returns the generated row id.
|
|
2695
|
+
* OPTIONAL — callers guard with `?.`.
|
|
2696
|
+
*/
|
|
2697
|
+
createPromptVersion?(input: {
|
|
2698
|
+
workspaceId: string;
|
|
2699
|
+
agentId: string;
|
|
2700
|
+
promptText: string;
|
|
2701
|
+
diffFromPrevious: string;
|
|
2702
|
+
algorithm: string;
|
|
2703
|
+
trajectoriesUsed: number;
|
|
2704
|
+
avgScoreBefore: number | null;
|
|
2705
|
+
avgScoreAfter: number | null;
|
|
2706
|
+
status: "candidate";
|
|
2707
|
+
}): Promise<{
|
|
2708
|
+
id: string;
|
|
2709
|
+
}>;
|
|
2710
|
+
/**
|
|
2711
|
+
* Return the most-recently created candidate (or active) prompt version
|
|
2712
|
+
* for the given (workspace, agent) pair, or null if none exists.
|
|
2713
|
+
* OPTIONAL — callers guard with `?.`.
|
|
2714
|
+
*/
|
|
2715
|
+
getActivePromptVersion?(workspaceId: string, agentId: string): Promise<{
|
|
2716
|
+
id: string;
|
|
2717
|
+
status: "candidate" | "testing" | "active" | "rolled_back";
|
|
2718
|
+
trajectoriesUsed: number | null;
|
|
2719
|
+
avgScoreBefore: number | null;
|
|
2720
|
+
avgScoreAfter: number | null;
|
|
2721
|
+
} | null>;
|
|
2722
|
+
/**
|
|
2723
|
+
* Return the most-recently activated prompt version across ALL agents in a
|
|
2724
|
+
* workspace, or null if no activated versions exist. Used by the cognitive
|
|
2725
|
+
* health snapshot to compute proceduralEvolutionDelta without needing a
|
|
2726
|
+
* specific agentId.
|
|
2727
|
+
* OPTIONAL — callers guard with `?.`.
|
|
2728
|
+
*/
|
|
2729
|
+
getLatestActivatedPromptVersion?(workspaceId: string): Promise<{
|
|
2730
|
+
avgScoreBefore: number | null;
|
|
2731
|
+
avgScoreAfter: number | null;
|
|
2732
|
+
} | null>;
|
|
2733
|
+
/**
|
|
2734
|
+
* List all prompt versions for (workspace, agent), newest first.
|
|
2735
|
+
* OPTIONAL — callers guard with `?.`.
|
|
2736
|
+
*/
|
|
2737
|
+
listPromptVersions?(workspaceId: string, agentId: string): Promise<Array<{
|
|
2738
|
+
id: string;
|
|
2739
|
+
promptText: string | null;
|
|
2740
|
+
diffFromPrevious: string | null;
|
|
2741
|
+
algorithm: string;
|
|
2742
|
+
status: string;
|
|
2743
|
+
trajectoriesUsed: number | null;
|
|
2744
|
+
avgScoreBefore: number | null;
|
|
2745
|
+
avgScoreAfter: number | null;
|
|
2746
|
+
activatedAt: Date | null;
|
|
2747
|
+
createdAt: Date;
|
|
2748
|
+
}>>;
|
|
2749
|
+
/**
|
|
2750
|
+
* Update the status of a prompt version to 'testing', 'active', or 'rolled_back'
|
|
2751
|
+
* and record the final avgScoreAfter.
|
|
2752
|
+
* OPTIONAL — callers guard with `?.`.
|
|
2753
|
+
*/
|
|
2754
|
+
transitionPromptVersion?(workspaceId: string, promptVersionId: string, newStatus: "testing" | "active" | "rolled_back", avgScoreAfter: number): Promise<void>;
|
|
2755
|
+
/**
|
|
2756
|
+
* §14 A/B scoring — returns the mean outcome score for all trajectories
|
|
2757
|
+
* associated with a specific prompt version within a workspace.
|
|
2758
|
+
* Returns null when there are no scored trajectories for the version.
|
|
2759
|
+
* OPTIONAL — callers guard with `?.`.
|
|
2760
|
+
*/
|
|
2761
|
+
computeCandidateAbScore?(workspaceId: string, agentId: string, promptVersionId: string): Promise<number | null>;
|
|
2762
|
+
}
|
|
2763
|
+
/** The primitive tables that carry embedding / embedding_model / embedding_stale columns. */
|
|
2764
|
+
type EmbeddableTable = "fact" | "decision" | "skill" | "strategy" | "reasoning" | "episode" | "entity";
|
|
2765
|
+
/** One hit from StorageAdapter.findSimilarEpisodes (DELTAMEM §16). */
|
|
2766
|
+
interface SimilarEpisode {
|
|
2767
|
+
id: string;
|
|
2768
|
+
/** Cosine similarity to the query vector, in [0,1]. Higher = more similar. */
|
|
2769
|
+
cosine: number;
|
|
2770
|
+
depth: number;
|
|
2771
|
+
}
|
|
2772
|
+
/** One hit from StorageAdapter.findSimilarEntities (P16). */
|
|
2773
|
+
interface SimilarEntity {
|
|
2774
|
+
id: string;
|
|
2775
|
+
/** Cosine similarity to the query vector, in [0,1]. Higher = more similar. */
|
|
2776
|
+
cosine: number;
|
|
2777
|
+
}
|
|
2778
|
+
/** One row in mnemo_hot_tier_snapshot (§37 Wave AA). */
|
|
2779
|
+
interface HotTierSnapshotRow {
|
|
2780
|
+
workspaceId: string;
|
|
2781
|
+
cacheKey: string;
|
|
2782
|
+
score: number;
|
|
2783
|
+
payload: Record<string, unknown>;
|
|
2784
|
+
}
|
|
2785
|
+
interface CacheSetOpts {
|
|
2786
|
+
ttlMs?: number;
|
|
2787
|
+
ifNotExists?: boolean;
|
|
2788
|
+
}
|
|
2789
|
+
interface CacheCapabilities {
|
|
2790
|
+
sortedSets: boolean;
|
|
2791
|
+
pubSub: boolean;
|
|
2792
|
+
patterns: boolean;
|
|
2793
|
+
atomic: boolean;
|
|
2794
|
+
/** Generic Hash field ops (hSet/hGet/hGetAll/hDel). Redis: true; in-process fallback: true. */
|
|
2795
|
+
hashes: boolean;
|
|
2796
|
+
}
|
|
2797
|
+
/**
|
|
2798
|
+
* Optional caching port — speeds up hot recall paths and holds ephemeral session state.
|
|
2799
|
+
*
|
|
2800
|
+
* Implemented by: `@mnemo-ai/adapter-redis` (RedisCacheAdapter) and
|
|
2801
|
+
* InMemoryCacheAdapter (test utility).
|
|
2802
|
+
*
|
|
2803
|
+
* Required methods (all implementations): get, set, delete, deletePattern, healthCheck, close.
|
|
2804
|
+
* Optional methods (Redis-only, gated by capabilities flags):
|
|
2805
|
+
* - sortedSets (zadd, zrangeByScore, zincrby): used by recall-hot.ts for score-ranked recall cache
|
|
2806
|
+
* - pubSub (publish, subscribe): used by federation fanout (stub — not yet wired)
|
|
2807
|
+
*
|
|
2808
|
+
* Core does NOT depend on CacheAdapter being present — the MnemoWorkspace context
|
|
2809
|
+
* marks it optional. Without a cache adapter, recall always cold-path fetches from storage.
|
|
2810
|
+
* With one, hot-path results are cached under `recall:{workspaceId}:{queryHash}`.
|
|
2811
|
+
*
|
|
2812
|
+
* TTL contract: callers specify ttlMs per set(); the adapter must honour it within ±1s.
|
|
2813
|
+
* Serialization: values are JSON-serialized by the adapter; callers may pass any JSON-safe value.
|
|
2814
|
+
*/
|
|
2815
|
+
interface CacheAdapter {
|
|
2816
|
+
readonly id: string;
|
|
2817
|
+
readonly capabilities: CacheCapabilities;
|
|
2818
|
+
get<T>(key: string): Promise<T | null>;
|
|
2819
|
+
set<T>(key: string, value: T, opts?: CacheSetOpts): Promise<void>;
|
|
2820
|
+
delete(key: string): Promise<void>;
|
|
2821
|
+
deletePattern(pattern: string): Promise<number>;
|
|
2822
|
+
zadd?(key: string, score: number, member: string): Promise<void>;
|
|
2823
|
+
zrangeByScore?(key: string, min: number, max: number, limit?: number): Promise<string[]>;
|
|
2824
|
+
zincrby?(key: string, increment: number, member: string): Promise<number>;
|
|
2825
|
+
/** Remove members from a sorted set — needed for correct LRU-by-activation eviction. */
|
|
2826
|
+
zrem?(key: string, ...members: string[]): Promise<number>;
|
|
2827
|
+
/**
|
|
2828
|
+
* Atomic counter: INCR the key then (re)set its TTL to ttlSeconds, returning
|
|
2829
|
+
* the new value. Used by L0 working memory for rate-limit counters and bloom
|
|
2830
|
+
* primitives. Optional — present on Redis; the in-process WorkingMemory fallback
|
|
2831
|
+
* implements an equivalent. TTL is mandatory (no PERSIST).
|
|
2832
|
+
*/
|
|
2833
|
+
incrWithTtl?(key: string, ttlSeconds: number): Promise<number>;
|
|
2834
|
+
publish?(channel: string, message: string): Promise<void>;
|
|
2835
|
+
subscribe?(channel: string, handler: (message: string) => void): Promise<void>;
|
|
2836
|
+
lpush?(key: string, value: string): Promise<number>;
|
|
2837
|
+
lrange?(key: string, start: number, stop: number): Promise<string[]>;
|
|
2838
|
+
ltrim?(key: string, start: number, stop: number): Promise<void>;
|
|
2839
|
+
lpushCapped?(key: string, value: string, max: number, ttlSeconds: number): Promise<void>;
|
|
2840
|
+
/** Set a single field on a hash and (re)set the hash key's TTL to ttlSeconds. */
|
|
2841
|
+
hSetWithTtl?(key: string, field: string, value: string, ttlSeconds: number): Promise<void>;
|
|
2842
|
+
/** Read one field; null when the field or key is absent. */
|
|
2843
|
+
hGet?(key: string, field: string): Promise<string | null>;
|
|
2844
|
+
/** Read every field as a plain object; {} when the key is absent. */
|
|
2845
|
+
hGetAll?(key: string): Promise<Record<string, string>>;
|
|
2846
|
+
/** Delete one or more fields; returns the number of fields removed. */
|
|
2847
|
+
hDel?(key: string, ...fields: string[]): Promise<number>;
|
|
2848
|
+
healthCheck(): Promise<HealthStatus>;
|
|
2849
|
+
info?(): Promise<CacheInfo>;
|
|
2850
|
+
close(): Promise<void>;
|
|
2851
|
+
}
|
|
2852
|
+
interface CacheInfo {
|
|
2853
|
+
usedMemoryBytes: number | null;
|
|
2854
|
+
connectedClients: number | null;
|
|
2855
|
+
}
|
|
2856
|
+
interface VectorSearchInput {
|
|
2857
|
+
workspaceId: string;
|
|
2858
|
+
vector: Float32Array;
|
|
2859
|
+
limit: number;
|
|
2860
|
+
minSimilarity?: number;
|
|
2861
|
+
filter?: Record<string, unknown>;
|
|
2862
|
+
}
|
|
2863
|
+
interface VectorSearchHit {
|
|
2864
|
+
id: string;
|
|
2865
|
+
score: number;
|
|
2866
|
+
primitiveKind?: string;
|
|
2867
|
+
metadata?: Record<string, unknown>;
|
|
2868
|
+
}
|
|
2869
|
+
interface VectorFilter {
|
|
2870
|
+
workspaceId?: string;
|
|
2871
|
+
primitiveKind?: string;
|
|
2872
|
+
ids?: string[];
|
|
2873
|
+
}
|
|
2874
|
+
/**
|
|
2875
|
+
* Approximate-nearest-neighbour search port for semantic recall (stage 2 of recall pipeline).
|
|
2876
|
+
*
|
|
2877
|
+
* Implemented by: `@mnemo-ai/adapter-vector` (pgvector via DrizzleStorageAdapter)
|
|
2878
|
+
* and InMemoryVectorAdapter (cosine brute-force for tests, not production).
|
|
2879
|
+
*
|
|
2880
|
+
* The `dimensions` property MUST match the embedding model in use (1536 for text-embedding-3-small,
|
|
2881
|
+
* 3072 for text-embedding-3-large). Mismatch causes a hard error at upsert time.
|
|
2882
|
+
*
|
|
2883
|
+
* HNSW index params (production only): m=16, ef_construction=64, halfvec(1536).
|
|
2884
|
+
* See packages/adapter-postgres/migrations/v3/0005_vector_indexes.sql.
|
|
2885
|
+
*
|
|
2886
|
+
* Workspace isolation is enforced by including workspaceId in VectorSearchInput.filter —
|
|
2887
|
+
* NEVER search without it. The adapter itself does not enforce RLS (unlike StorageAdapter).
|
|
2888
|
+
*
|
|
2889
|
+
* search() returns hits ordered by score descending. Callers filter by minSimilarity themselves
|
|
2890
|
+
* since the threshold is tunable per-query. Typical minimum: 0.7 for semantic recall.
|
|
2891
|
+
*/
|
|
2892
|
+
interface VectorAdapter {
|
|
2893
|
+
readonly id: string;
|
|
2894
|
+
readonly dimensions: number;
|
|
2895
|
+
search(input: VectorSearchInput): Promise<VectorSearchHit[]>;
|
|
2896
|
+
upsert(id: string, vector: Float32Array, metadata?: Record<string, unknown>): Promise<void>;
|
|
2897
|
+
delete(id: string, workspaceId: string): Promise<void>;
|
|
2898
|
+
deleteByFilter(filter: VectorFilter): Promise<number>;
|
|
2899
|
+
healthCheck(): Promise<HealthStatus>;
|
|
2900
|
+
close(): Promise<void>;
|
|
2901
|
+
}
|
|
2902
|
+
/**
|
|
2903
|
+
* Text embedding port — converts strings to dense vectors for semantic similarity.
|
|
2904
|
+
*
|
|
2905
|
+
* Implemented by: `@mnemo-ai/llm-providers` (OpenAIEmbedAdapter, CohereEmbedAdapter)
|
|
2906
|
+
* and InMemoryEmbedAdapter (deterministic mock that returns unit vectors by hash).
|
|
2907
|
+
*
|
|
2908
|
+
* embed(texts) batches multiple strings into a single API call where possible.
|
|
2909
|
+
* embedSingle is a convenience wrapper that calls embed([text])[0].
|
|
2910
|
+
*
|
|
2911
|
+
* The `model` property is the canonical model identifier (e.g. "text-embedding-3-small").
|
|
2912
|
+
* It is stored alongside each primitive's embedding so stale embeddings can be detected
|
|
2913
|
+
* and re-generated when the model changes (embeddingStale flag on primitives).
|
|
2914
|
+
*
|
|
2915
|
+
* Never pass empty strings — most providers return a zero vector or error.
|
|
2916
|
+
* Text should be pre-processed (stripped of markdown/HTML) before embedding.
|
|
2917
|
+
*/
|
|
2918
|
+
interface EmbedAdapter {
|
|
2919
|
+
readonly id: string;
|
|
2920
|
+
readonly model: string;
|
|
2921
|
+
readonly dimensions: number;
|
|
2922
|
+
embed(texts: string[]): Promise<Float32Array[]>;
|
|
2923
|
+
embedSingle(text: string): Promise<Float32Array>;
|
|
2924
|
+
/** Optional input_type-aware embed for document indexing (e.g. Voyage/Cohere). */
|
|
2925
|
+
embedDocument?(texts: string[]): Promise<Float32Array[]>;
|
|
2926
|
+
/** Optional input_type-aware embed for search queries (e.g. Voyage/Cohere). */
|
|
2927
|
+
embedQuery?(text: string): Promise<Float32Array>;
|
|
2928
|
+
healthCheck(): Promise<HealthStatus>;
|
|
2929
|
+
}
|
|
2930
|
+
interface LLMMessage {
|
|
2931
|
+
role: "user" | "assistant";
|
|
2932
|
+
content: string;
|
|
2933
|
+
}
|
|
2934
|
+
interface LLMInput {
|
|
2935
|
+
system?: string;
|
|
2936
|
+
messages: LLMMessage[];
|
|
2937
|
+
maxTokens?: number;
|
|
2938
|
+
temperature?: number;
|
|
2939
|
+
/** Hint to the LLM adapter to use this specific model (e.g. "haiku" for cheap tier). */
|
|
2940
|
+
model?: string;
|
|
2941
|
+
}
|
|
2942
|
+
interface LLMOutput {
|
|
2943
|
+
content: string;
|
|
2944
|
+
tokensUsed: {
|
|
2945
|
+
input: number;
|
|
2946
|
+
output: number;
|
|
2947
|
+
};
|
|
2948
|
+
model: string;
|
|
2949
|
+
finishReason: "stop" | "length" | "tool_use";
|
|
2950
|
+
/** Vendor identity ("openai", "anthropic", ...) when surfaced by the provider. */
|
|
2951
|
+
provider?: string;
|
|
2952
|
+
/** Vendor-estimated USD cost for this completion; undefined when the model is not priced. */
|
|
2953
|
+
costUSD?: number;
|
|
2954
|
+
}
|
|
2955
|
+
interface SchemaLike<T> {
|
|
2956
|
+
parse: (data: unknown) => T;
|
|
2957
|
+
}
|
|
2958
|
+
/**
|
|
2959
|
+
* LLM inference port — drives extraction, consolidation, and CUP migration.
|
|
2960
|
+
*
|
|
2961
|
+
* Implemented by: `@mnemo-ai/llm-providers` (ClaudeAdapter, OpenAIAdapter, GeminiAdapter).
|
|
2962
|
+
* Routing across providers is handled by LLMRouter (packages/core/src/v3/llm/router.ts)
|
|
2963
|
+
* which wraps multiple LLMAdapters with per-task provider selection + BudgetGuard.
|
|
2964
|
+
*
|
|
2965
|
+
* generate(): unstructured text generation. Used for CUP migration narration and
|
|
2966
|
+
* session collapse summarization.
|
|
2967
|
+
*
|
|
2968
|
+
* generateStructured<T>(input, schema): returns a validated T by asking the LLM to
|
|
2969
|
+
* produce a JSON object that matches the schema. The schema argument is duck-typed
|
|
2970
|
+
* (SchemaLike<T>) — works with zod, valibot, or any object with a `.parse()` method.
|
|
2971
|
+
* Used for extraction (fact/decision/entity parsing) and consolidation classification.
|
|
2972
|
+
*
|
|
2973
|
+
* Callers must handle token budget: maxTokens in LLMInput sets output ceiling.
|
|
2974
|
+
* The tokensUsed in LLMOutput is authoritative for cost tracking (BudgetGuard reads it).
|
|
2975
|
+
*
|
|
2976
|
+
* Implementation note: do NOT store LLMAdapter instances in workspace context directly —
|
|
2977
|
+
* always go through LLMRouter to enable provider switching and cost limits.
|
|
2978
|
+
*/
|
|
2979
|
+
interface LLMAdapter {
|
|
2980
|
+
readonly id: string;
|
|
2981
|
+
readonly model: string;
|
|
2982
|
+
generate(input: LLMInput): Promise<LLMOutput>;
|
|
2983
|
+
generateStructured<T>(input: LLMInput, schema: SchemaLike<T>): Promise<T>;
|
|
2984
|
+
healthCheck(): Promise<HealthStatus>;
|
|
2985
|
+
}
|
|
2986
|
+
interface EnqueueOpts {
|
|
2987
|
+
priority?: number;
|
|
2988
|
+
retryLimit?: number;
|
|
2989
|
+
retryDelay?: number;
|
|
2990
|
+
startAfter?: Date;
|
|
2991
|
+
singletonKey?: string;
|
|
2992
|
+
}
|
|
2993
|
+
type JobHandler<T = unknown> = (data: T) => Promise<void>;
|
|
2994
|
+
/**
|
|
2995
|
+
* Background job port — schedules async work (embedding refresh, consolidation, webhook delivery).
|
|
2996
|
+
*
|
|
2997
|
+
* Implemented by: `@mnemo-ai/adapter-postgres` (PgBossQueueAdapter using pg-boss in
|
|
2998
|
+
* the same Postgres database as storage, so jobs are durable) and InMemoryQueueAdapter
|
|
2999
|
+
* (immediate synchronous execution for tests — no actual deferral).
|
|
3000
|
+
*
|
|
3001
|
+
* enqueue(): one-shot job. Returns jobId for status tracking.
|
|
3002
|
+
* - singletonKey: prevents duplicate jobs (used for workspace-scoped consolidation runs).
|
|
3003
|
+
* - startAfter: future-scheduled execution (used for TTL-expiry reminders).
|
|
3004
|
+
* - retryLimit + retryDelay: exponential backoff on handler errors.
|
|
3005
|
+
*
|
|
3006
|
+
* schedule(): recurring cron job. Idempotent — calling twice with same jobName+cron is a no-op.
|
|
3007
|
+
* Used to schedule nightly consolidation and embedding staleness scans.
|
|
3008
|
+
*
|
|
3009
|
+
* process(): registers the handler for a job type. Must be called at server startup before
|
|
3010
|
+
* jobs start processing. Handlers are async and must not throw — errors go to pg-boss
|
|
3011
|
+
* dead-letter queue and are retried per retryLimit.
|
|
3012
|
+
*
|
|
3013
|
+
* Shutdown: always call close() on graceful shutdown to let in-flight jobs complete.
|
|
3014
|
+
*/
|
|
3015
|
+
interface QueueAdapter {
|
|
3016
|
+
readonly id: string;
|
|
3017
|
+
enqueue(jobName: string, data: unknown, opts?: EnqueueOpts): Promise<string>;
|
|
3018
|
+
schedule(jobName: string, cron: string, data?: unknown): Promise<void>;
|
|
3019
|
+
process<T = unknown>(jobName: string, handler: JobHandler<T>): Promise<void>;
|
|
3020
|
+
healthCheck(): Promise<HealthStatus>;
|
|
3021
|
+
close(): Promise<void>;
|
|
3022
|
+
}
|
|
3023
|
+
interface OutboxStats {
|
|
3024
|
+
pending: number;
|
|
3025
|
+
failed: number;
|
|
3026
|
+
oldestPendingMs: number;
|
|
3027
|
+
}
|
|
3028
|
+
/**
|
|
3029
|
+
* Transactional outbox port — guarantees at-least-once event delivery without 2-phase commit.
|
|
3030
|
+
*
|
|
3031
|
+
* Implemented by: `@mnemo-ai/adapter-postgres` (DrizzleOutboxAdapter writing to mnemo_outbox
|
|
3032
|
+
* in the same transaction as the fact/decision write). There is no InMemory implementation —
|
|
3033
|
+
* OutboxAdapter is always paired with a real database transaction.
|
|
3034
|
+
*
|
|
3035
|
+
* Pattern: within a storage write transaction, call append() so the outbox entry is committed
|
|
3036
|
+
* atomically with the fact. A background poller (OutboxRelay in packages/core) calls
|
|
3037
|
+
* claimBatch() → delivers events → markProcessed(). On failure, markFailed() increments
|
|
3038
|
+
* the attempt counter; the poller retries until MAX_ATTEMPTS (see outbox.ts).
|
|
3039
|
+
*
|
|
3040
|
+
* append(): must be called INSIDE the same DB transaction as the primary write.
|
|
3041
|
+
* Passing the entry outside a transaction breaks the atomicity guarantee.
|
|
3042
|
+
*
|
|
3043
|
+
* claimBatch(): claims and locks entries for processing (SELECT … FOR UPDATE SKIP LOCKED).
|
|
3044
|
+
* Returns at most `limit` entries. Only pending entries with attempts < MAX are returned.
|
|
3045
|
+
*
|
|
3046
|
+
* Security: the mnemo_app_role has INSERT-only on mnemo_outbox (UPDATE and DELETE revoked).
|
|
3047
|
+
* Processed/failed entries are marked by a privileged relay role, not the app role.
|
|
3048
|
+
*/
|
|
3049
|
+
interface OutboxAdapter {
|
|
3050
|
+
append(entry: Omit<OutboxEntry, "id" | "createdAt" | "attempts">): Promise<void>;
|
|
3051
|
+
claimBatch(limit: number): Promise<OutboxEntry[]>;
|
|
3052
|
+
markProcessed(ids: string[]): Promise<void>;
|
|
3053
|
+
markFailed(id: string, error: string): Promise<void>;
|
|
3054
|
+
getStats(): Promise<OutboxStats>;
|
|
3055
|
+
}
|
|
3056
|
+
interface LogContext {
|
|
3057
|
+
workspaceId?: string;
|
|
3058
|
+
agentId?: string;
|
|
3059
|
+
traceId?: string;
|
|
3060
|
+
spanId?: string;
|
|
3061
|
+
operation?: string;
|
|
3062
|
+
durationMs?: number;
|
|
3063
|
+
error?: {
|
|
3064
|
+
type: string;
|
|
3065
|
+
message: string;
|
|
3066
|
+
stack?: string;
|
|
3067
|
+
code?: string;
|
|
3068
|
+
};
|
|
3069
|
+
cost?: {
|
|
3070
|
+
model: string;
|
|
3071
|
+
tokensIn: number;
|
|
3072
|
+
tokensOut: number;
|
|
3073
|
+
costUsd: number;
|
|
3074
|
+
};
|
|
3075
|
+
[key: string]: unknown;
|
|
3076
|
+
}
|
|
3077
|
+
interface Logger {
|
|
3078
|
+
debug(msg: string, ctx?: LogContext): void;
|
|
3079
|
+
info(msg: string, ctx?: LogContext): void;
|
|
3080
|
+
warn(msg: string, ctx?: LogContext): void;
|
|
3081
|
+
error(msg: string, ctx?: LogContext): void;
|
|
3082
|
+
fatal(msg: string, ctx?: LogContext): void;
|
|
3083
|
+
child(bindings: Record<string, unknown>): Logger;
|
|
3084
|
+
}
|
|
3085
|
+
interface SpanOpts {
|
|
3086
|
+
parent?: Span;
|
|
3087
|
+
attributes?: Record<string, string | number | boolean>;
|
|
3088
|
+
}
|
|
3089
|
+
interface Span {
|
|
3090
|
+
setAttribute(key: string, value: string | number | boolean): void;
|
|
3091
|
+
setStatus(status: "ok" | "error", message?: string): void;
|
|
3092
|
+
end(): void;
|
|
3093
|
+
}
|
|
3094
|
+
interface Telemetry {
|
|
3095
|
+
startSpan(name: string, opts?: SpanOpts): Span;
|
|
3096
|
+
counter(name: string, value?: number, attrs?: Record<string, string>): void;
|
|
3097
|
+
histogram(name: string, value: number, attrs?: Record<string, string>): void;
|
|
3098
|
+
gauge(name: string, value: number, attrs?: Record<string, string>): void;
|
|
3099
|
+
shutdown(): Promise<void>;
|
|
3100
|
+
}
|
|
3101
|
+
|
|
3102
|
+
type AccessPolicyRecord = AgentMemoryAccess & {
|
|
3103
|
+
namespaces?: string[];
|
|
3104
|
+
};
|
|
3105
|
+
interface AccessPolicyStore {
|
|
3106
|
+
getPolicy(workspaceId: string, agentId: string): Promise<AccessPolicyRecord | null>;
|
|
3107
|
+
putPolicy(policy: AccessPolicyRecord): Promise<void>;
|
|
3108
|
+
}
|
|
3109
|
+
interface ApprovalRequestInput {
|
|
3110
|
+
workspaceId: string;
|
|
3111
|
+
requestedBy: string;
|
|
3112
|
+
trigger: ApprovalTrigger;
|
|
3113
|
+
resource: string;
|
|
3114
|
+
resourceId?: string;
|
|
3115
|
+
payload: Record<string, unknown>;
|
|
3116
|
+
expiresAt: Date;
|
|
3117
|
+
}
|
|
3118
|
+
interface ApprovalRequest extends ApprovalRequestInput {
|
|
3119
|
+
id: string;
|
|
3120
|
+
status: "pending" | "approved" | "denied" | "expired";
|
|
3121
|
+
resolvedBy?: string;
|
|
3122
|
+
resolvedAt?: Date;
|
|
3123
|
+
createdAt: Date;
|
|
3124
|
+
}
|
|
3125
|
+
interface ApprovalStore {
|
|
3126
|
+
create(input: ApprovalRequestInput): Promise<ApprovalRequest>;
|
|
3127
|
+
get(workspaceId: string, id: string): Promise<ApprovalRequest | null>;
|
|
3128
|
+
resolve(workspaceId: string, id: string, status: "approved" | "denied", resolvedBy: string): Promise<void>;
|
|
3129
|
+
}
|
|
3130
|
+
interface BreakGlassRequestInput {
|
|
3131
|
+
workspaceId: string;
|
|
3132
|
+
/** Admin A — the requester. */
|
|
3133
|
+
requestedBy: string;
|
|
3134
|
+
/** Free-text incident justification (audited). */
|
|
3135
|
+
reason: string;
|
|
3136
|
+
/** §6 scopes the grant covers (e.g. ["memory:export"]). */
|
|
3137
|
+
requestedScopes: SpecScope[];
|
|
3138
|
+
/** Grant validity ceiling (server-set; typically now + 15m). */
|
|
3139
|
+
expiresAt: Date;
|
|
3140
|
+
}
|
|
3141
|
+
interface BreakGlassRequestRecord extends BreakGlassRequestInput {
|
|
3142
|
+
id: string;
|
|
3143
|
+
status: "pending" | "approved" | "denied" | "expired" | "used";
|
|
3144
|
+
/** Admin B — the approver. Set on approve(); MUST differ from requestedBy. */
|
|
3145
|
+
approvedBy?: string;
|
|
3146
|
+
approvedAt?: Date;
|
|
3147
|
+
usedAt?: Date;
|
|
3148
|
+
createdAt: Date;
|
|
3149
|
+
}
|
|
3150
|
+
interface BreakGlassStore {
|
|
3151
|
+
/** Admin A files a pending request. */
|
|
3152
|
+
request(input: BreakGlassRequestInput): Promise<BreakGlassRequestRecord>;
|
|
3153
|
+
/**
|
|
3154
|
+
* Admin B approves. MUST throw if approverId === the request's requestedBy
|
|
3155
|
+
* (two-person / dual-control rule — a requester cannot self-approve).
|
|
3156
|
+
*/
|
|
3157
|
+
approve(workspaceId: string, id: string, approverId: string): Promise<void>;
|
|
3158
|
+
/** Single fetch by id (audit + status checks). */
|
|
3159
|
+
get(workspaceId: string, id: string): Promise<BreakGlassRequestRecord | null>;
|
|
3160
|
+
/**
|
|
3161
|
+
* The active grant for a requester: status='approved', not expired, not yet
|
|
3162
|
+
* used. Returns null when none — the gate then 403s (or 202s on pending).
|
|
3163
|
+
*/
|
|
3164
|
+
getActiveApproved(workspaceId: string, requestedBy: string): Promise<BreakGlassRequestRecord | null>;
|
|
3165
|
+
/** Consume a grant (single-use): flips status→'used' and stamps usedAt. */
|
|
3166
|
+
markUsed(workspaceId: string, id: string): Promise<void>;
|
|
3167
|
+
}
|
|
3168
|
+
interface SessionTokenRecord {
|
|
3169
|
+
id: string;
|
|
3170
|
+
workspaceId: string;
|
|
3171
|
+
actorId: string;
|
|
3172
|
+
/** SHA-256 hash of the plaintext refresh token. */
|
|
3173
|
+
tokenHash: string;
|
|
3174
|
+
/** SHA-256 of userAgent + acceptLanguage + ipNetwork. */
|
|
3175
|
+
deviceFingerprint: string;
|
|
3176
|
+
/** Set to the time of first use; null while still valid for first rotation. */
|
|
3177
|
+
usedAt: Date | null;
|
|
3178
|
+
/** Null = active family. Non-null = family revoked at this time. */
|
|
3179
|
+
familyRevokedAt: Date | null;
|
|
3180
|
+
expiresAt: Date;
|
|
3181
|
+
createdAt: Date;
|
|
3182
|
+
}
|
|
3183
|
+
interface SessionTokenStore {
|
|
3184
|
+
/** Store a new refresh token hash for a given actor. */
|
|
3185
|
+
create(input: Omit<SessionTokenRecord, "id" | "usedAt" | "familyRevokedAt" | "createdAt">): Promise<SessionTokenRecord>;
|
|
3186
|
+
/** Look up a token by its SHA-256 hash (exact match, workspace-scoped). */
|
|
3187
|
+
findByHash(workspaceId: string, tokenHash: string): Promise<SessionTokenRecord | null>;
|
|
3188
|
+
/** Mark a token as used (sets usedAt = now). */
|
|
3189
|
+
markUsed(id: string, workspaceId: string): Promise<void>;
|
|
3190
|
+
/** Revoke the entire family rooted at the given token id. */
|
|
3191
|
+
revokeFamily(rootId: string, workspaceId: string): Promise<void>;
|
|
3192
|
+
/** Delete all expired tokens for housekeeping. */
|
|
3193
|
+
purgeExpired(workspaceId: string): Promise<number>;
|
|
3194
|
+
}
|
|
3195
|
+
type BeginResult = {
|
|
3196
|
+
state: "new";
|
|
3197
|
+
} | {
|
|
3198
|
+
state: "replay";
|
|
3199
|
+
responseCode: number;
|
|
3200
|
+
responseBody: string;
|
|
3201
|
+
} | {
|
|
3202
|
+
state: "in_flight";
|
|
3203
|
+
} | {
|
|
3204
|
+
state: "mismatch";
|
|
3205
|
+
};
|
|
3206
|
+
/**
|
|
3207
|
+
* Stripe-pattern recovery points for multi-phase mutating operations
|
|
3208
|
+
* (spec §Idempotency / RDD9, lines 3954-3964). A long op records its phase as
|
|
3209
|
+
* it advances so a crashed-then-retried request can skip completed phases.
|
|
3210
|
+
* started → key claimed, no work done yet (INSERT default)
|
|
3211
|
+
* session_locked → Phase 1 done: local bookkeeping committed (session marked collapsing)
|
|
3212
|
+
* llm_called → Phase 2 done: external LLM summarisation succeeded
|
|
3213
|
+
* facts_persisted → Phase 3 done: knowledge units written to PG
|
|
3214
|
+
* completed → Phase 4 done: response persisted; future calls replay
|
|
3215
|
+
*/
|
|
3216
|
+
declare const RECOVERY_POINTS: readonly ["started", "session_locked", "llm_called", "facts_persisted", "completed"];
|
|
3217
|
+
type RecoveryPoint = (typeof RECOVERY_POINTS)[number];
|
|
3218
|
+
interface IdempotencyStore {
|
|
3219
|
+
/** Atomically claim the key. MUST run under SERIALIZABLE so concurrent dupes collide. */
|
|
3220
|
+
begin(workspaceId: string, key: string, requestHash: string): Promise<BeginResult>;
|
|
3221
|
+
/** Persist the final response for future replays. Sets recovery_point='completed'. */
|
|
3222
|
+
complete(workspaceId: string, key: string, responseCode: number, responseBody: string): Promise<void>;
|
|
3223
|
+
/**
|
|
3224
|
+
* Advance the recovery point for an in-flight key (idempotent: re-recording the
|
|
3225
|
+
* same phase is a no-op). Used by multi-phase ops (session collapse) to mark
|
|
3226
|
+
* progress so a retry can skip completed phases. No-op if the key row is absent.
|
|
3227
|
+
*/
|
|
3228
|
+
recordPhase(workspaceId: string, key: string, phase: RecoveryPoint): Promise<void>;
|
|
3229
|
+
/** Read the current recovery point, or null if the key is unknown. */
|
|
3230
|
+
getRecoveryPoint(workspaceId: string, key: string): Promise<RecoveryPoint | null>;
|
|
3231
|
+
}
|
|
3232
|
+
|
|
3233
|
+
export { type CreateSkillInput as $, ALL_SCOPES as A, type BeginResult as B, type CacheAdapter as C, type CacheCapabilities as D, type CacheInfo as E, type CacheSetOpts as F, type CoOccurrencePatternRow as G, type CognitivePrimitive as H, type CompositionRuleFilter as I, type ConditionDsl as J, ConditionDslSchema as K, type ConditionalPatternRow as L, type ConfidenceMapRow as M, type ConsolidationMergeSnapshot as N, type ConsolidationWorthSnapshot as O, type ContradictingFact as P, type CreateCompositionRuleInput as Q, type CreateDecisionInput as R, type CreateEntityInput as S, type CreateEpisodeInput as T, type CreateEventInput as U, type CreateFactInput as V, type CreateHyperedgeInput as W, type CreateReasoningInput as X, type CreateRelationInput as Y, type CreateReminderInput as Z, type CreateSessionInput as _, type AccessPolicyRecord as a, type MnemoWebhookDelivery as a$, type CreateStrategyInput as a0, type CreateTaskInput as a1, type CreateWebhookDeliveryInput as a2, type CreateWebhookEndpointInput as a3, type CreateWorkflowInput as a4, type DecayClass as a5, type DecisionFilter as a6, type DelegateTaskInput as a7, type DeploymentTier as a8, type DerivedInference as a9, type LLMInput as aA, type LLMMessage as aB, type LLMOutput as aC, type LogContext as aD, type Logger as aE, type LshBandValue as aF, type MaterialiseInferenceInput as aG, type MergeFactByTopicKeyInput as aH, type MetacognitionTrends as aI, type MnemoAgentProfile as aJ, type MnemoCitation as aK, type MnemoCompositionRule as aL, type MnemoDecision as aM, type MnemoEntity as aN, type MnemoEpisode as aO, type MnemoEvent as aP, type MnemoFact as aQ, type MnemoFactHash as aR, type MnemoHyperedge as aS, type MnemoInferenceLogEntry as aT, type MnemoReasoning as aU, type MnemoRelation as aV, type MnemoReminder as aW, type MnemoSession as aX, type MnemoSkill as aY, type MnemoStrategy as aZ, type MnemoTask as a_, type EmbedAdapter as aa, type EmbeddableTable as ab, type EncryptedField as ac, type EnqueueOpts as ad, type EntityFilter as ae, type EpisodeFilter as af, type EventAnnotation as ag, type EventFilter as ah, type FactFilter as ai, type FindContradictingFactsInput as aj, type FtsCandidate as ak, type HealthStatus as al, type HotTierSnapshotRow as am, type HyperedgeFilter as an, type IdempotencyStore as ao, type InferenceLogFilter as ap, type InheritedContext as aq, type InjectionGuardResult as ar, type InjectionScore as as, type JobHandler as at, type KeyDeprecation as au, type KeyEscrowEntry as av, type KeyScope as aw, type KeyUsageEvent as ax, type KnowledgeGapRow as ay, type LLMAdapter as az, type AccessPolicyStore as b, type UpdateDecisionInput as b$, type MnemoWebhookEndpoint as b0, type MnemoWorkflow as b1, type OutboxAdapter as b2, type OutboxEntry as b3, type OutboxEventType as b4, type OutboxStats as b5, type PaginatedResult as b6, type PeriodicPatternRow as b7, type PointerCandidate as b8, type PointerCandidateQuery as b9, type ReplaceFactInput as bA, type ReplaceFactResult as bB, type ReplayFailureReview as bC, type RotateKeyResult as bD, SENSITIVITY_ORDER as bE, SPEC_SCOPES as bF, type SchemaLike as bG, type SelfEditPolicy as bH, type Sensitivity as bI, type SequentialPatternRow as bJ, type SessionStatus as bK, type SessionTokenRecord as bL, type SessionTokenStore as bM, type SessionTurn as bN, type SimilarEntity as bO, type SimilarEpisode as bP, type SkillFilter as bQ, type Span as bR, type SpanOpts as bS, type SpecScope as bT, type StorageAdapter as bU, type StorageCapabilities as bV, type StrategyFilter as bW, type TaskFilter as bX, type Telemetry as bY, type TrendPair as bZ, type UpdateCompositionRuleInput as b_, type PrimitiveKind as ba, type Provenance as bb, type PurgeFactsFilter as bc, type PurgeFactsResult as bd, type QueueAdapter as be, RECOVERY_POINTS as bf, type RawCredentials as bg, type ReasoningFilter as bh, type ReasoningStep as bi, type RecallFilter as bj, type RecallHit as bk, type RecallLogEntry as bl, type RecallLogRecord as bm, type RecallPrimitiveRecord as bn, type RecallPrimitiveRef as bo, type RecallPrimitiveValue as bp, type RecallQuery as bq, type RecallResponse as br, type RecallStructures as bs, type RecoveryPoint as bt, type RelationFilter as bu, type RelationSummary as bv, type RelationVerb as bw, type RememberKind as bx, type RememberRequest as by, type RememberResponse as bz, type ActionDsl as c, type UpdateEntityInput as c0, type UpdateEpisodeInput as c1, type UpdateFactInput as c2, type UpdateHyperedgeInput as c3, type UpdateReasoningInput as c4, type UpdateSkillInput as c5, type UpdateStrategyInput as c6, type UpdateTaskInput as c7, type UpdateWebhookEndpointInput as c8, type UpdateWorkflowInput as c9, type UpsertFactHashInput as ca, type UpsertFactLshInput as cb, type VectorAdapter as cc, type VectorEmbedding as cd, type VectorFilter as ce, type VectorQuery as cf, type VectorSearchHit as cg, type VectorSearchInput as ch, type VectorSearchResult as ci, type WebhookFirePayload as cj, type WorkflowFilter as ck, type WorkflowStep as cl, type WorthDelta as cm, parseActionDsl as cn, parseConditionDsl as co, resolveAuditActorType as cp, sensitivityAtLeast as cq, ActionDslSchema as d, type AgentMemoryAccess as e, type AnomalyScore as f, type ApiKeyRecord as g, type ApiKeyStore as h, type ApiKeyType as i, type AppendInferenceInput as j, type ApplyConsolidationMergeInput as k, type ApprovalRequest as l, type ApprovalRequestInput as m, type ApprovalStore as n, type ApprovalTrigger as o, type Attribution as p, type AuditAction as q, type AuditActorType as r, type AuditLogEntry as s, type AuthAdapter as t, type AuthContext as u, type AuthOperation as v, type AuthResult as w, type BreakGlassRequestInput as x, type BreakGlassRequestRecord as y, type BreakGlassStore as z };
|