@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.
@@ -0,0 +1,2660 @@
1
+ import { SENSITIVITY_ORDER, applyDelta, resolveAuditActorType } from '../chunk-H4A2NIMQ.js';
2
+ import { beforeEach, describe, it, expect } from 'vitest';
3
+ import { randomUUID } from 'crypto';
4
+
5
+ /* @mnemo-ai/types — see https://github.com/lucasmailland/mnemosyne */
6
+
7
+ // src/testing/InMemoryStorageAdapter.ts
8
+ function uuid() {
9
+ return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, (c) => {
10
+ const r = Math.random() * 16 | 0;
11
+ return (c === "x" ? r : r & 3 | 8).toString(16);
12
+ });
13
+ }
14
+ async function factStatementHash(statement, subject) {
15
+ const canonical = `${statement.trim().toLowerCase()}|${subject}|fact`;
16
+ const digest = await globalThis.crypto.subtle.digest(
17
+ "SHA-256",
18
+ new TextEncoder().encode(canonical)
19
+ );
20
+ return Array.from(new Uint8Array(digest), (byte) => byte.toString(16).padStart(2, "0")).join("");
21
+ }
22
+ function cosineSimilarity(a, b) {
23
+ if (a.length !== b.length) return 0;
24
+ let dot = 0;
25
+ let normA = 0;
26
+ let normB = 0;
27
+ for (let i = 0; i < a.length; i++) {
28
+ const ai = a[i] ?? 0;
29
+ const bi = b[i] ?? 0;
30
+ dot += ai * bi;
31
+ normA += ai * ai;
32
+ normB += bi * bi;
33
+ }
34
+ const denom = Math.sqrt(normA) * Math.sqrt(normB);
35
+ return denom === 0 ? 0 : dot / denom;
36
+ }
37
+ function paginate(items, offset = 0, limit = 20) {
38
+ const sliced = items.slice(offset, offset + limit);
39
+ return {
40
+ items: sliced,
41
+ total: items.length,
42
+ offset,
43
+ limit,
44
+ hasMore: offset + sliced.length < items.length
45
+ };
46
+ }
47
+ var PENDING_KEY = "__mnemoConsolidationPending";
48
+ function worthSnapshot(fact) {
49
+ return {
50
+ alpha: fact.worthAlpha,
51
+ beta: fact.worthBeta,
52
+ success: fact.worthSuccess,
53
+ failure: fact.worthFailure
54
+ };
55
+ }
56
+ function worthEquals(fact, worth) {
57
+ return fact.worthAlpha === worth.alpha && fact.worthBeta === worth.beta && fact.worthSuccess === worth.success && fact.worthFailure === worth.failure;
58
+ }
59
+ function markerFor(fact) {
60
+ const marker = fact.metadata?.[PENDING_KEY];
61
+ return marker && typeof marker === "object" ? marker : void 0;
62
+ }
63
+ function withoutPendingMarker(metadata) {
64
+ const { [PENDING_KEY]: _pending, ...rest } = metadata;
65
+ return rest;
66
+ }
67
+ function hasPendingMarker(metadata) {
68
+ return Object.prototype.hasOwnProperty.call(metadata ?? {}, PENDING_KEY);
69
+ }
70
+ var InMemoryStorageAdapter = class {
71
+ capabilities = {
72
+ vectorSearch: false,
73
+ ftsSearch: false,
74
+ bitemporal: false,
75
+ graphExpansion: false,
76
+ transactions: true,
77
+ rls: false
78
+ };
79
+ // Data stores
80
+ sessions = /* @__PURE__ */ new Map();
81
+ turns = [];
82
+ facts = /* @__PURE__ */ new Map();
83
+ decisions = /* @__PURE__ */ new Map();
84
+ episodes = /* @__PURE__ */ new Map();
85
+ entities = /* @__PURE__ */ new Map();
86
+ strategies = /* @__PURE__ */ new Map();
87
+ workflows = /* @__PURE__ */ new Map();
88
+ skills = /* @__PURE__ */ new Map();
89
+ tasks = /* @__PURE__ */ new Map();
90
+ events = /* @__PURE__ */ new Map();
91
+ reasonings = /* @__PURE__ */ new Map();
92
+ hyperedges = /* @__PURE__ */ new Map();
93
+ compositionRules = /* @__PURE__ */ new Map();
94
+ inferences = [];
95
+ factHashes = /* @__PURE__ */ new Map();
96
+ factLsh = /* @__PURE__ */ new Map();
97
+ // key: `${ws}:${factId}`
98
+ embeddings = /* @__PURE__ */ new Map();
99
+ relations = /* @__PURE__ */ new Map();
100
+ agentProfiles = /* @__PURE__ */ new Map();
101
+ // key: `${ws}:${agentId}`
102
+ workspaceModes = /* @__PURE__ */ new Map();
103
+ // §9 L3 — query cache and embedding LRU stores
104
+ queryCache = [];
105
+ embeddingCache = /* @__PURE__ */ new Map();
106
+ // key: `${ws}:${textHash}`
107
+ // Append-only logs — tests can inspect these
108
+ outbox = [];
109
+ auditLog = [];
110
+ recallLog = [];
111
+ consolidationReviews = [];
112
+ // ── Session ──────────────────────────────────────────────────────────────────
113
+ async createSession(input) {
114
+ const session = {
115
+ id: uuid(),
116
+ workspaceId: input.workspaceId,
117
+ agentId: input.agentId,
118
+ status: "open",
119
+ turnCount: 0,
120
+ tokenCount: 0,
121
+ createdAt: /* @__PURE__ */ new Date(),
122
+ updatedAt: /* @__PURE__ */ new Date(),
123
+ metadata: input.metadata ?? {}
124
+ };
125
+ this.sessions.set(session.id, session);
126
+ return session;
127
+ }
128
+ async appendTurn(sessionId, turn) {
129
+ const session = this.sessions.get(sessionId);
130
+ if (!session || session.workspaceId !== turn.workspaceId) {
131
+ const error = new Error(`Session ${sessionId} not found.`);
132
+ error.code = "NOT_FOUND";
133
+ throw error;
134
+ }
135
+ this.turns.push({ id: uuid(), createdAt: /* @__PURE__ */ new Date(), ...turn, sessionId });
136
+ }
137
+ async listTurns(sessionId, workspaceId) {
138
+ return this.turns.filter((t) => t.sessionId === sessionId && t.workspaceId === workspaceId);
139
+ }
140
+ async closeSession(id, workspaceId) {
141
+ const s = this.sessions.get(id);
142
+ if (s && s.workspaceId === workspaceId) {
143
+ s.status = "collapsed";
144
+ }
145
+ }
146
+ async archiveSession(id, workspaceId) {
147
+ const s = this.sessions.get(id);
148
+ if (s && s.workspaceId === workspaceId) {
149
+ s.status = "archived";
150
+ }
151
+ }
152
+ async getSession(id, workspaceId) {
153
+ const s = this.sessions.get(id);
154
+ if (!s || s.workspaceId !== workspaceId) return null;
155
+ const turnCount = this.turns.filter((t) => t.sessionId === id).length;
156
+ return { ...s, turnCount };
157
+ }
158
+ async listSessions(workspaceId) {
159
+ return Array.from(this.sessions.values()).filter((s) => s.workspaceId === workspaceId);
160
+ }
161
+ async pinSessionTurn(sessionId, turnId, workspaceId, pinned) {
162
+ const turn = this.turns.find((t) => t.id === turnId && t.sessionId === sessionId && t.workspaceId === workspaceId);
163
+ if (turn) turn.pinned = pinned;
164
+ }
165
+ // ── Facts ────────────────────────────────────────────────────────────────────
166
+ async createFact(input) {
167
+ const now = /* @__PURE__ */ new Date();
168
+ const fact = {
169
+ id: uuid(),
170
+ workspaceId: input.workspaceId,
171
+ agentId: input.agentId,
172
+ actorId: input.actorId,
173
+ scope: input.scope,
174
+ scopeRef: input.scopeRef,
175
+ scopeOwner: input.scopeOwner ?? `workspace:${input.workspaceId}`,
176
+ statement: input.statement,
177
+ subject: input.subject,
178
+ kind: input.kind,
179
+ confidence: input.confidence ?? 0.8,
180
+ relevance: input.relevance ?? 0.8,
181
+ hitCount: 0,
182
+ worthSuccess: 0,
183
+ worthFailure: 0,
184
+ worthAlpha: 2,
185
+ worthBeta: 2,
186
+ worth: 0.5,
187
+ memoryType: "semantic",
188
+ memoryStrength: 1,
189
+ memoryStability: 1,
190
+ attribution: input.attribution ?? "inferred",
191
+ sourceMessageIds: input.sourceMessageIds ?? [],
192
+ sessionId: input.sessionId,
193
+ extractionSource: input.extractionSource,
194
+ topicKey: input.topicKey,
195
+ revisionCount: 1,
196
+ protocolVersion: "3.0",
197
+ entityId: input.entityId,
198
+ episodeId: input.episodeId,
199
+ status: "active",
200
+ pinned: false,
201
+ canonical: false,
202
+ sensitivity: input.sensitivity ?? "internal",
203
+ validFrom: input.validFrom ?? now,
204
+ validTo: input.validTo,
205
+ embeddingStale: true,
206
+ createdAt: now,
207
+ updatedAt: now,
208
+ // Generic creators may never forge a pending-consolidation marker — only
209
+ // applyConsolidationMerge is allowed to attach it. Strip any supplied key.
210
+ metadata: withoutPendingMarker(input.metadata ?? {})
211
+ };
212
+ this.facts.set(fact.id, fact);
213
+ this.outbox.push({
214
+ id: uuid(),
215
+ workspaceId: fact.workspaceId,
216
+ eventType: "vector_upsert",
217
+ payload: input.embedding && input.embedding.length > 0 ? { id: fact.id, kind: "fact", vector: input.embedding } : { id: fact.id, kind: "fact" },
218
+ createdAt: /* @__PURE__ */ new Date(),
219
+ attempts: 0
220
+ });
221
+ return fact;
222
+ }
223
+ async getFact(id, workspaceId) {
224
+ const f = this.facts.get(id);
225
+ return f && f.workspaceId === workspaceId ? f : null;
226
+ }
227
+ async updateFact(id, workspaceId, input) {
228
+ const f = this.facts.get(id);
229
+ if (!f || f.workspaceId !== workspaceId) return null;
230
+ const pending = hasPendingMarker(f.metadata);
231
+ if (pending && input.pinned !== void 0) return null;
232
+ if (input.statement !== void 0 && (f.status !== "active" || f.validTo !== void 0)) return null;
233
+ const updated = { ...f, ...input, revisionCount: f.revisionCount + 1, updatedAt: /* @__PURE__ */ new Date() };
234
+ if (input.metadata !== void 0) {
235
+ const stripped = withoutPendingMarker(input.metadata);
236
+ updated.metadata = pending ? { ...stripped, [PENDING_KEY]: f.metadata[PENDING_KEY] } : stripped;
237
+ }
238
+ this.facts.set(id, updated);
239
+ return updated;
240
+ }
241
+ async mergeFactByTopicKey(input) {
242
+ const fact = [...this.facts.values()].find(
243
+ (candidate) => candidate.workspaceId === input.workspaceId && candidate.topicKey === input.topicKey && candidate.status === "active" && candidate.validTo == null
244
+ );
245
+ if (!fact) return null;
246
+ if (hasPendingMarker(fact.metadata)) return null;
247
+ const existingTags = Array.isArray(fact.metadata.tags) ? fact.metadata.tags.filter((tag) => typeof tag === "string") : [];
248
+ const metadataTags = Array.isArray(input.metadata?.tags) ? input.metadata.tags.filter((tag) => typeof tag === "string") : [];
249
+ const tags = [.../* @__PURE__ */ new Set([...existingTags, ...metadataTags, ...input.tags ?? []])];
250
+ const metadata = { ...fact.metadata, ...input.metadata ?? {}, ...tags.length ? { tags } : {} };
251
+ const updated = {
252
+ ...fact,
253
+ statement: input.statement,
254
+ metadata,
255
+ revisionCount: fact.revisionCount + 1,
256
+ embeddingModel: void 0,
257
+ embeddingStale: true,
258
+ updatedAt: /* @__PURE__ */ new Date()
259
+ };
260
+ this.facts.set(fact.id, updated);
261
+ this.embeddings.delete(fact.id);
262
+ this.factLsh.delete(`${input.workspaceId}:${fact.id}`);
263
+ return updated;
264
+ }
265
+ async replaceFact(input) {
266
+ const sourceBeforeHash = this.facts.get(input.id);
267
+ const hash = await factStatementHash(input.statement, sourceBeforeHash?.subject ?? "");
268
+ const source = this.facts.get(input.id);
269
+ const now = /* @__PURE__ */ new Date();
270
+ if (!source || source.workspaceId !== input.workspaceId || source.status !== "active" || source.validTo != null || source.validFrom.getTime() > now.getTime() || hasPendingMarker(source.metadata) || input.actorIsolationId != null && source.actorId != null && source.actorId !== input.actorIsolationId) {
271
+ return null;
272
+ }
273
+ const previous = {
274
+ ...source,
275
+ status: "forgotten",
276
+ validTo: now,
277
+ updatedAt: now
278
+ };
279
+ const replacement = {
280
+ ...source,
281
+ id: uuid(),
282
+ agentId: input.agentId ?? source.agentId,
283
+ statement: input.statement,
284
+ revisionCount: source.revisionCount + 1,
285
+ status: "active",
286
+ validFrom: now,
287
+ validTo: void 0,
288
+ embedding: void 0,
289
+ embeddingModel: void 0,
290
+ embeddingStale: true,
291
+ createdAt: now,
292
+ updatedAt: now,
293
+ // A replacement is a brand-new fact — it must never inherit the source's
294
+ // pending-consolidation marker, or a rollback would resurrect a stranger.
295
+ metadata: withoutPendingMarker(source.metadata)
296
+ };
297
+ this.facts.set(source.id, previous);
298
+ this.facts.set(replacement.id, replacement);
299
+ this.factLsh.delete(`${input.workspaceId}:${source.id}`);
300
+ this.queryCache = this.queryCache.filter((entry) => entry.workspaceId !== input.workspaceId);
301
+ this.outbox.push(
302
+ {
303
+ id: uuid(),
304
+ workspaceId: input.workspaceId,
305
+ eventType: "vector_delete",
306
+ payload: { id: source.id, kind: "fact" },
307
+ createdAt: now,
308
+ attempts: 0
309
+ },
310
+ {
311
+ id: uuid(),
312
+ workspaceId: input.workspaceId,
313
+ eventType: "cache_bust",
314
+ payload: { pattern: `mnemo:${input.workspaceId}:*` },
315
+ createdAt: now,
316
+ attempts: 0
317
+ }
318
+ );
319
+ if (SENSITIVITY_ORDER[source.sensitivity] < SENSITIVITY_ORDER.confidential) {
320
+ this.outbox.push({
321
+ id: uuid(),
322
+ workspaceId: input.workspaceId,
323
+ eventType: "vector_upsert",
324
+ payload: { id: replacement.id, kind: "fact", text: input.statement },
325
+ createdAt: now,
326
+ attempts: 0
327
+ });
328
+ }
329
+ const relation = {
330
+ id: uuid(),
331
+ workspaceId: input.workspaceId,
332
+ sourceId: replacement.id,
333
+ sourceType: "fact",
334
+ targetId: source.id,
335
+ targetType: "fact",
336
+ verb: "supersedes",
337
+ weight: 1,
338
+ createdAt: now,
339
+ updatedAt: now,
340
+ metadata: {}
341
+ };
342
+ this.relations.set(relation.id, relation);
343
+ const hashKey = `${input.workspaceId}|${hash}`;
344
+ const existingHash = this.factHashes.get(hashKey);
345
+ this.factHashes.set(hashKey, existingHash ? { ...existingHash, factId: replacement.id, lastSeenAt: now, seenCount: existingHash.seenCount + 1 } : {
346
+ workspaceId: input.workspaceId,
347
+ statementHash: hash,
348
+ factId: replacement.id,
349
+ firstSeenAt: now,
350
+ lastSeenAt: now,
351
+ seenCount: 1
352
+ });
353
+ return { previous, replacement };
354
+ }
355
+ async archiveFact(id, workspaceId) {
356
+ const f = this.facts.get(id);
357
+ if (f && f.workspaceId === workspaceId && !hasPendingMarker(f.metadata)) {
358
+ this.facts.set(id, { ...f, status: "forgotten", validTo: /* @__PURE__ */ new Date() });
359
+ }
360
+ }
361
+ async queryFacts(filter) {
362
+ let items = [...this.facts.values()].filter((f) => f.workspaceId === filter.workspaceId);
363
+ if (filter.status) items = items.filter((f) => f.status === filter.status);
364
+ if (filter.kind) items = items.filter((f) => f.kind === filter.kind);
365
+ if (filter.sessionId) items = items.filter((f) => f.sessionId === filter.sessionId);
366
+ if (filter.entityId) items = items.filter((f) => f.entityId === filter.entityId);
367
+ if (filter.topicKey) items = items.filter((f) => f.topicKey === filter.topicKey);
368
+ if (filter.minConfidence !== void 0)
369
+ items = items.filter((f) => f.confidence >= filter.minConfidence);
370
+ return paginate(items, filter.offset, filter.limit);
371
+ }
372
+ async applyConsolidationMerge(input) {
373
+ const participantIds = [input.survivorId, ...input.absorbedFactIds].sort();
374
+ const rows = participantIds.flatMap((id) => {
375
+ const row = this.facts.get(id);
376
+ return row ? [row] : [];
377
+ });
378
+ const eligible = input.absorbedFactIds.length > 0 && new Set(participantIds).size === participantIds.length && rows.length === participantIds.length && rows.every(
379
+ (row) => row.workspaceId === input.workspaceId && row.status === "active" && row.validTo == null && !Object.prototype.hasOwnProperty.call(row.metadata ?? {}, PENDING_KEY)
380
+ );
381
+ const survivor = rows.filter((row) => row.id === input.survivorId);
382
+ const absorbed = input.absorbedFactIds.map((id) => rows.find((row) => row.id === id));
383
+ if (!eligible || survivor.length !== 1 || absorbed.some((row) => !row)) return null;
384
+ const previousWorth = worthSnapshot(survivor[0]);
385
+ const expectedMergedWorth = {
386
+ ...previousWorth,
387
+ alpha: previousWorth.alpha + 1,
388
+ success: previousWorth.success + 1
389
+ };
390
+ const snapshot = {
391
+ operationId: input.operationId,
392
+ workspaceId: input.workspaceId,
393
+ survivorId: input.survivorId,
394
+ absorbedFactIds: [...input.absorbedFactIds],
395
+ previousWorth,
396
+ expectedMergedWorth
397
+ };
398
+ const marker = { ...snapshot, leaseExpiresAt: input.leaseExpiresAt.toISOString() };
399
+ const closedAt = /* @__PURE__ */ new Date();
400
+ for (const row of rows) {
401
+ const isSurvivor = row.id === input.survivorId;
402
+ const updated = {
403
+ ...row,
404
+ metadata: { ...row.metadata, [PENDING_KEY]: marker },
405
+ updatedAt: closedAt,
406
+ ...isSurvivor ? {
407
+ worthAlpha: expectedMergedWorth.alpha,
408
+ worthBeta: expectedMergedWorth.beta,
409
+ worthSuccess: expectedMergedWorth.success,
410
+ worthFailure: expectedMergedWorth.failure,
411
+ worth: expectedMergedWorth.alpha / (expectedMergedWorth.alpha + expectedMergedWorth.beta)
412
+ } : { status: "merged", validTo: closedAt, mergedIntoId: input.survivorId }
413
+ };
414
+ this.facts.set(row.id, updated);
415
+ }
416
+ return snapshot;
417
+ }
418
+ consolidationRows(snapshot) {
419
+ const ids = [snapshot.survivorId, ...snapshot.absorbedFactIds];
420
+ const rows = ids.flatMap((id) => {
421
+ const row = this.facts.get(id);
422
+ return row ? [row] : [];
423
+ });
424
+ return rows.length === ids.length && rows.every((row) => row.workspaceId === snapshot.workspaceId) ? rows : null;
425
+ }
426
+ pendingConsolidationRows(snapshot) {
427
+ const rows = this.consolidationRows(snapshot);
428
+ if (!rows || !rows.every((row) => markerFor(row)?.operationId === snapshot.operationId)) return null;
429
+ const survivor = rows.find((row) => row.id === snapshot.survivorId);
430
+ const absorbed = rows.filter((row) => row.id !== snapshot.survivorId);
431
+ return survivor.status === "active" && survivor.validTo == null && worthEquals(survivor, snapshot.expectedMergedWorth) && absorbed.every((row) => row.status === "merged" && row.validTo != null && row.mergedIntoId === snapshot.survivorId) ? rows : null;
432
+ }
433
+ compensateConsolidationMerge(snapshot, review) {
434
+ const rows = this.pendingConsolidationRows(snapshot);
435
+ if (!rows) return false;
436
+ const now = /* @__PURE__ */ new Date();
437
+ for (const row of rows) {
438
+ const isSurvivor = row.id === snapshot.survivorId;
439
+ const updated = {
440
+ ...row,
441
+ status: "active",
442
+ validTo: void 0,
443
+ mergedIntoId: void 0,
444
+ metadata: withoutPendingMarker(row.metadata),
445
+ updatedAt: now,
446
+ ...isSurvivor ? {
447
+ worthAlpha: snapshot.previousWorth.alpha,
448
+ worthBeta: snapshot.previousWorth.beta,
449
+ worthSuccess: snapshot.previousWorth.success,
450
+ worthFailure: snapshot.previousWorth.failure,
451
+ worth: snapshot.previousWorth.alpha / (snapshot.previousWorth.alpha + snapshot.previousWorth.beta)
452
+ } : {}
453
+ };
454
+ this.facts.set(row.id, updated);
455
+ }
456
+ this.consolidationReviews.push({
457
+ id: `mrev_${uuid()}`,
458
+ workspaceId: snapshot.workspaceId,
459
+ factId: snapshot.survivorId,
460
+ reason: "manual",
461
+ review
462
+ });
463
+ return true;
464
+ }
465
+ async rollbackConsolidationMerge(input) {
466
+ return this.compensateConsolidationMerge(input.snapshot, input.review) ? "rolled_back" : "conflict";
467
+ }
468
+ async finalizeConsolidationMerge(input) {
469
+ const rows = this.pendingConsolidationRows(input.snapshot);
470
+ if (!rows) return "conflict";
471
+ const now = /* @__PURE__ */ new Date();
472
+ for (const row of rows) {
473
+ const isSurvivor = row.id === input.snapshot.survivorId;
474
+ const boost = isSurvivor && input.applyReplayBoost ? 1 : 0;
475
+ const updated = {
476
+ ...row,
477
+ metadata: withoutPendingMarker(row.metadata),
478
+ updatedAt: now,
479
+ ...isSurvivor && boost ? {
480
+ worthAlpha: row.worthAlpha + boost,
481
+ worthSuccess: row.worthSuccess + boost,
482
+ worth: (row.worthAlpha + boost) / (row.worthAlpha + boost + row.worthBeta)
483
+ } : {}
484
+ };
485
+ this.facts.set(row.id, updated);
486
+ }
487
+ return "finalized";
488
+ }
489
+ async refreshConsolidationMergeLease(input) {
490
+ const rows = this.pendingConsolidationRows(input.snapshot);
491
+ if (!rows) return "conflict";
492
+ for (const row of rows) {
493
+ const marker = markerFor(row);
494
+ this.facts.set(row.id, {
495
+ ...row,
496
+ metadata: { ...row.metadata, [PENDING_KEY]: { ...marker, leaseExpiresAt: input.leaseExpiresAt.toISOString() } }
497
+ });
498
+ }
499
+ return "refreshed";
500
+ }
501
+ async inspectConsolidationMergeState(snapshot) {
502
+ const rows = this.consolidationRows(snapshot);
503
+ if (!rows) return "divergent";
504
+ const survivor = rows.find((row) => row.id === snapshot.survivorId);
505
+ const absorbed = rows.filter((row) => row.id !== snapshot.survivorId);
506
+ const markers = rows.map(markerFor);
507
+ const noMarkers = markers.every((marker) => marker === void 0);
508
+ if (this.pendingConsolidationRows(snapshot)) return "pending";
509
+ if (noMarkers && survivor.status === "active" && survivor.validTo == null && worthEquals(survivor, snapshot.previousWorth) && absorbed.every((row) => row.status === "active" && row.validTo == null)) return "restored";
510
+ const boostedWorth = { ...snapshot.expectedMergedWorth, alpha: snapshot.expectedMergedWorth.alpha + 1, success: snapshot.expectedMergedWorth.success + 1 };
511
+ if (noMarkers && survivor.status === "active" && survivor.validTo == null && (worthEquals(survivor, snapshot.expectedMergedWorth) || worthEquals(survivor, boostedWorth)) && absorbed.every((row) => row.status === "merged" && row.validTo != null && row.mergedIntoId === snapshot.survivorId)) return "retained";
512
+ return "divergent";
513
+ }
514
+ async recoverExpiredConsolidationMerges(input) {
515
+ const operations = /* @__PURE__ */ new Map();
516
+ for (const fact of this.facts.values()) {
517
+ const marker = markerFor(fact);
518
+ if (fact.workspaceId === input.workspaceId && marker && new Date(marker.leaseExpiresAt).getTime() <= input.expiredBefore.getTime()) {
519
+ operations.set(marker.operationId, marker);
520
+ }
521
+ }
522
+ let recovered = 0;
523
+ for (const marker of operations.values()) {
524
+ const rows = this.pendingConsolidationRows(marker);
525
+ if (!rows || !rows.every((row) => {
526
+ const refreshed = markerFor(row);
527
+ return refreshed?.operationId === marker.operationId && new Date(refreshed.leaseExpiresAt).getTime() <= input.expiredBefore.getTime();
528
+ })) continue;
529
+ if (this.compensateConsolidationMerge(marker, {
530
+ reason: "replay_execution_failed",
531
+ passCount: 0,
532
+ failCount: 0,
533
+ queriesUsed: []
534
+ })) recovered += 1;
535
+ }
536
+ return recovered;
537
+ }
538
+ async findContradictingFacts(workspaceId, input) {
539
+ const limit = input.limit ?? 5;
540
+ const incomingTokens = new Set(
541
+ input.statement.toLowerCase().split(/\W+/).filter((t) => t.length > 2)
542
+ );
543
+ const scored = [...this.facts.values()].filter(
544
+ (f) => f.workspaceId === workspaceId && f.status === "active" && f.id !== input.excludeId
545
+ ).map((f) => {
546
+ const subjectMatch = f.subject === input.subject;
547
+ const factTokens = f.statement.toLowerCase().split(/\W+/).filter((t) => t.length > 2);
548
+ const overlap = factTokens.filter((t) => incomingTokens.has(t)).length;
549
+ return { f, subjectMatch, overlap };
550
+ }).filter((s) => s.subjectMatch || s.overlap > 0).sort(
551
+ (a, b) => a.subjectMatch === b.subjectMatch ? b.overlap - a.overlap : a.subjectMatch ? -1 : 1
552
+ ).slice(0, limit);
553
+ return scored.map(({ f }) => ({
554
+ id: f.id,
555
+ subject: f.subject,
556
+ statement: f.statement,
557
+ confidence: f.confidence,
558
+ attribution: f.attribution,
559
+ worth: f.worth,
560
+ validFrom: f.validFrom
561
+ }));
562
+ }
563
+ // ── SOC2 CF3 — Retention purge ────────────────────────────────────────────────
564
+ async purgeFacts(filter) {
565
+ const { workspaceId, sensitivity, olderThanDays, dryRun = false, limit = 500 } = filter;
566
+ if (SENSITIVITY_ORDER[sensitivity] <= SENSITIVITY_ORDER.public) {
567
+ return { softClosed: 0, eraseCandidateActorIds: [] };
568
+ }
569
+ const cutoff = new Date(Date.now() - olderThanDays * 24 * 60 * 60 * 1e3);
570
+ const candidates = [...this.facts.values()].filter(
571
+ (f) => f.workspaceId === workspaceId && f.sensitivity === sensitivity && f.createdAt < cutoff && f.validTo == null && f.status !== "hard_deleted" && // Retention purge must never soft-close a fact mid-consolidation.
572
+ !hasPendingMarker(f.metadata)
573
+ ).slice(0, limit);
574
+ if (dryRun) {
575
+ return { softClosed: candidates.length, eraseCandidateActorIds: [] };
576
+ }
577
+ const now = /* @__PURE__ */ new Date();
578
+ const affectedActorIds = /* @__PURE__ */ new Set();
579
+ for (const f of candidates) {
580
+ this.facts.set(f.id, { ...f, status: "forgotten", validTo: now, updatedAt: now });
581
+ if (f.actorId) affectedActorIds.add(f.actorId);
582
+ }
583
+ if (SENSITIVITY_ORDER[sensitivity] <= SENSITIVITY_ORDER.internal || affectedActorIds.size === 0) {
584
+ return { softClosed: candidates.length, eraseCandidateActorIds: [] };
585
+ }
586
+ const eraseCandidateActorIds = [];
587
+ for (const actorId of affectedActorIds) {
588
+ const remaining = [...this.facts.values()].filter(
589
+ (f) => f.workspaceId === workspaceId && f.actorId === actorId && SENSITIVITY_ORDER[f.sensitivity] >= SENSITIVITY_ORDER.confidential && f.validTo == null
590
+ );
591
+ if (remaining.length === 0) {
592
+ eraseCandidateActorIds.push(actorId);
593
+ }
594
+ }
595
+ return { softClosed: candidates.length, eraseCandidateActorIds };
596
+ }
597
+ // ── Decisions ────────────────────────────────────────────────────────────────
598
+ async createDecision(input) {
599
+ const now = /* @__PURE__ */ new Date();
600
+ const decision = {
601
+ id: uuid(),
602
+ workspaceId: input.workspaceId,
603
+ agentId: input.agentId,
604
+ conversationId: input.conversationId,
605
+ scopeRef: input.scopeRef,
606
+ kind: input.kind,
607
+ title: input.title,
608
+ body: input.body,
609
+ topicKey: input.topicKey,
610
+ revisionCount: 0,
611
+ normalizedHash: "",
612
+ status: "active",
613
+ sensitivity: input.sensitivity ?? "internal",
614
+ validFrom: input.validFrom ?? now,
615
+ createdAt: now,
616
+ updatedAt: now,
617
+ metadata: input.metadata ?? {}
618
+ };
619
+ this.decisions.set(decision.id, decision);
620
+ return decision;
621
+ }
622
+ async getDecision(id, workspaceId) {
623
+ const d = this.decisions.get(id);
624
+ return d && d.workspaceId === workspaceId ? d : null;
625
+ }
626
+ async updateDecision(id, input) {
627
+ const d = this.decisions.get(id);
628
+ if (!d) throw new Error(`Decision ${id} not found`);
629
+ const updated = { ...d, ...input, updatedAt: /* @__PURE__ */ new Date() };
630
+ this.decisions.set(id, updated);
631
+ return updated;
632
+ }
633
+ async archiveDecision(id, workspaceId) {
634
+ const d = this.decisions.get(id);
635
+ if (d && d.workspaceId === workspaceId) {
636
+ this.decisions.set(id, { ...d, status: "withdrawn" });
637
+ }
638
+ }
639
+ async queryDecisions(filter) {
640
+ let items = [...this.decisions.values()].filter((d) => d.workspaceId === filter.workspaceId);
641
+ if (filter.status) items = items.filter((d) => d.status === filter.status);
642
+ if (filter.kind) items = items.filter((d) => d.kind === filter.kind);
643
+ if (filter.scopeRef) items = items.filter((d) => d.scopeRef === filter.scopeRef || !d.scopeRef);
644
+ return paginate(items, filter.offset, filter.limit);
645
+ }
646
+ // ── Episodes ─────────────────────────────────────────────────────────────────
647
+ async createEpisode(input) {
648
+ const now = /* @__PURE__ */ new Date();
649
+ const episode = {
650
+ id: uuid(),
651
+ workspaceId: input.workspaceId,
652
+ agentId: input.agentId,
653
+ title: input.title,
654
+ narrative: input.narrative,
655
+ occurredAt: input.occurredAt,
656
+ durationMinutes: input.durationMinutes,
657
+ participants: input.participants ?? [],
658
+ topics: input.topics ?? [],
659
+ linkedFactIds: input.linkedFactIds ?? [],
660
+ parentEpisodeId: input.parentEpisodeId,
661
+ deltaContent: input.deltaContent,
662
+ isSynthetic: input.isSynthetic ?? false,
663
+ isRoot: !input.parentEpisodeId,
664
+ depth: (() => {
665
+ if (!input.parentEpisodeId) return 0;
666
+ const parent = this.episodes.get(input.parentEpisodeId);
667
+ if (!parent || parent.workspaceId !== input.workspaceId) {
668
+ throw new Error(`Parent episode ${input.parentEpisodeId} not found in workspace ${input.workspaceId}`);
669
+ }
670
+ return parent.depth + 1;
671
+ })(),
672
+ sourceConversationId: input.sourceConversationId,
673
+ sensitivity: input.sensitivity ?? "internal",
674
+ // P18: initialize bitemporal columns
675
+ validFrom: now,
676
+ validTo: void 0,
677
+ createdAt: now,
678
+ updatedAt: now,
679
+ metadata: input.metadata ?? {}
680
+ };
681
+ this.episodes.set(episode.id, episode);
682
+ return episode;
683
+ }
684
+ async getEpisode(id, workspaceId) {
685
+ const e = this.episodes.get(id);
686
+ return e && e.workspaceId === workspaceId ? e : null;
687
+ }
688
+ async updateEpisode(id, input) {
689
+ const e = this.episodes.get(id);
690
+ if (!e) throw new Error(`Episode ${id} not found`);
691
+ const updated = { ...e, ...input, updatedAt: /* @__PURE__ */ new Date() };
692
+ this.episodes.set(id, updated);
693
+ return updated;
694
+ }
695
+ async archiveEpisode(id, workspaceId) {
696
+ const e = this.episodes.get(id);
697
+ if (e && e.workspaceId === workspaceId) {
698
+ this.episodes.set(id, { ...e, validTo: /* @__PURE__ */ new Date(), updatedAt: /* @__PURE__ */ new Date() });
699
+ }
700
+ }
701
+ async queryEpisodes(filter) {
702
+ const items = [...this.episodes.values()].filter((e) => {
703
+ if (e.workspaceId !== filter.workspaceId) return false;
704
+ if (filter.parentEpisodeId !== void 0 && e.parentEpisodeId !== filter.parentEpisodeId) return false;
705
+ if (filter.validAt) {
706
+ if (e.validFrom > filter.validAt) return false;
707
+ if (e.validTo != null && e.validTo <= filter.validAt) return false;
708
+ }
709
+ return true;
710
+ });
711
+ return paginate(items, filter.offset, filter.limit);
712
+ }
713
+ async getEpisodeTreeNeighbors(episodeId, workspaceId, limit = 10) {
714
+ const target = this.episodes.get(episodeId);
715
+ if (!target || target.workspaceId !== workspaceId) return [];
716
+ const all = [...this.episodes.values()].filter((e) => e.workspaceId === workspaceId && e.id !== episodeId);
717
+ const neighbors = [];
718
+ if (target.parentEpisodeId) {
719
+ const parent = this.episodes.get(target.parentEpisodeId);
720
+ if (parent && parent.workspaceId === workspaceId) {
721
+ neighbors.push(parent);
722
+ }
723
+ }
724
+ const addedIds = new Set(neighbors.map((e) => e.id));
725
+ for (const ep of all) {
726
+ if (addedIds.has(ep.id)) continue;
727
+ if (target.parentEpisodeId && ep.parentEpisodeId === target.parentEpisodeId) {
728
+ neighbors.push(ep);
729
+ addedIds.add(ep.id);
730
+ }
731
+ }
732
+ for (const ep of all) {
733
+ if (addedIds.has(ep.id)) continue;
734
+ if (ep.parentEpisodeId === episodeId) {
735
+ neighbors.push(ep);
736
+ addedIds.add(ep.id);
737
+ }
738
+ }
739
+ return neighbors.slice(0, limit);
740
+ }
741
+ async persistCompression(input) {
742
+ const ep = this.episodes.get(input.rootEpisodeId);
743
+ if (!ep || ep.workspaceId !== input.workspaceId) return;
744
+ ep.narrative = input.compressedNarrative;
745
+ ep.metadata = { ...ep.metadata, compressed: true, retainedDeltas: input.retainedDeltas };
746
+ ep.updatedAt = /* @__PURE__ */ new Date();
747
+ }
748
+ async getKnowledgeDistribution(workspaceId) {
749
+ const inWs = (m) => [...m.values()].filter((v) => v.workspaceId === workspaceId).length;
750
+ return {
751
+ fact: inWs(this.facts),
752
+ decision: inWs(this.decisions),
753
+ strategy: inWs(this.strategies),
754
+ episode: inWs(this.episodes),
755
+ entity: inWs(this.entities),
756
+ task: inWs(this.tasks),
757
+ event: inWs(this.events),
758
+ skill: inWs(this.skills),
759
+ workflow: inWs(this.workflows),
760
+ reasoning: inWs(this.reasonings),
761
+ hyperedge: inWs(this.hyperedges)
762
+ };
763
+ }
764
+ async reconstructEpisode(id, workspaceId) {
765
+ const chain = [];
766
+ let cursor = id;
767
+ const seen = /* @__PURE__ */ new Set();
768
+ while (cursor && !seen.has(cursor)) {
769
+ seen.add(cursor);
770
+ const ep = this.episodes.get(cursor);
771
+ if (!ep || ep.workspaceId !== workspaceId) break;
772
+ chain.push(ep);
773
+ cursor = ep.parentEpisodeId ?? null;
774
+ }
775
+ if (chain.length === 0) throw new Error(`episode ${id} not found`);
776
+ const rootFirst = [...chain].reverse();
777
+ const root = rootFirst[0];
778
+ let reconstructed = root.narrative;
779
+ for (const ep of rootFirst.slice(1)) {
780
+ reconstructed = applyDelta(reconstructed, ep.deltaContent ?? "");
781
+ }
782
+ return { ...chain[0], narrative: reconstructed };
783
+ }
784
+ // DELTAMEM §16 — cosine search over stored episode embeddings (set via
785
+ // setEmbedding(episodeId, vec)). Returns workspace-scoped episodes with
786
+ // cosine ≥ minSim, most-similar first. Episodes without a stored embedding
787
+ // are excluded (mirrors the SQL `embedding IS NOT NULL` predicate).
788
+ async findSimilarEpisodes(workspaceId, embedding, limit, minSim) {
789
+ const hits = [];
790
+ for (const ep of this.episodes.values()) {
791
+ if (ep.workspaceId !== workspaceId) continue;
792
+ const vec = this.embeddings.get(ep.id);
793
+ if (!vec) continue;
794
+ const cosine = cosineSimilarity(embedding, vec);
795
+ if (cosine >= minSim) hits.push({ id: ep.id, cosine, depth: ep.depth });
796
+ }
797
+ hits.sort((a, b) => b.cosine - a.cosine);
798
+ return hits.slice(0, limit);
799
+ }
800
+ // ── Entities ─────────────────────────────────────────────────────────────────
801
+ async createEntity(input) {
802
+ const now = /* @__PURE__ */ new Date();
803
+ const entity = {
804
+ id: uuid(),
805
+ workspaceId: input.workspaceId,
806
+ kind: input.kind,
807
+ name: input.name,
808
+ description: input.description,
809
+ aliases: input.aliases ?? [],
810
+ canonicalId: input.canonicalId,
811
+ sensitivity: input.sensitivity ?? "internal",
812
+ firstSeenAt: now,
813
+ lastSeenAt: now,
814
+ mentionCount: 0,
815
+ // P18: initialize bitemporal columns
816
+ validFrom: now,
817
+ validTo: void 0,
818
+ createdAt: now,
819
+ updatedAt: now,
820
+ metadata: input.metadata ?? {}
821
+ };
822
+ this.entities.set(entity.id, entity);
823
+ return entity;
824
+ }
825
+ async getEntity(id, workspaceId) {
826
+ const e = this.entities.get(id);
827
+ return e && e.workspaceId === workspaceId ? e : null;
828
+ }
829
+ async updateEntity(id, input) {
830
+ const e = this.entities.get(id);
831
+ if (!e) throw new Error(`Entity ${id} not found`);
832
+ const updated = { ...e, ...input, updatedAt: /* @__PURE__ */ new Date() };
833
+ this.entities.set(id, updated);
834
+ return updated;
835
+ }
836
+ async archiveEntity(id, workspaceId) {
837
+ const e = this.entities.get(id);
838
+ if (e && e.workspaceId === workspaceId) {
839
+ this.entities.set(id, { ...e, validTo: /* @__PURE__ */ new Date(), updatedAt: /* @__PURE__ */ new Date() });
840
+ }
841
+ }
842
+ async queryEntities(filter) {
843
+ const items = [...this.entities.values()].filter((e) => {
844
+ if (e.workspaceId !== filter.workspaceId) return false;
845
+ if (filter.validAt) {
846
+ if (e.validFrom > filter.validAt) return false;
847
+ if (e.validTo != null && e.validTo <= filter.validAt) return false;
848
+ }
849
+ return true;
850
+ });
851
+ return paginate(items, filter.offset, filter.limit);
852
+ }
853
+ // P16 — stub: InMemoryStorageAdapter has no vector index for entities.
854
+ async findSimilarEntities(_workspaceId, _embedding, _limit, _minSim) {
855
+ return Promise.resolve([]);
856
+ }
857
+ // ── Strategies ────────────────────────────────────────────────────────────────
858
+ async createStrategy(input) {
859
+ const now = /* @__PURE__ */ new Date();
860
+ const strategy = {
861
+ id: uuid(),
862
+ workspaceId: input.workspaceId,
863
+ agentId: input.agentId,
864
+ trigger: input.trigger,
865
+ action: input.action,
866
+ context: input.context,
867
+ scopeRef: input.scopeRef,
868
+ sensitivity: input.sensitivity ?? "internal",
869
+ status: "active",
870
+ hitCount: 0,
871
+ worth: 0.5,
872
+ createdAt: now,
873
+ updatedAt: now,
874
+ metadata: input.metadata ?? {}
875
+ };
876
+ this.strategies.set(strategy.id, strategy);
877
+ return strategy;
878
+ }
879
+ async getStrategy(id, workspaceId) {
880
+ const s = this.strategies.get(id);
881
+ return s && s.workspaceId === workspaceId ? s : null;
882
+ }
883
+ async updateStrategy(id, input) {
884
+ const s = this.strategies.get(id);
885
+ if (!s) throw new Error(`Strategy ${id} not found`);
886
+ const updated = { ...s, ...input, updatedAt: /* @__PURE__ */ new Date() };
887
+ this.strategies.set(id, updated);
888
+ return updated;
889
+ }
890
+ async archiveStrategy(id, workspaceId) {
891
+ const s = this.strategies.get(id);
892
+ if (s && s.workspaceId === workspaceId) {
893
+ this.strategies.set(id, { ...s, status: "archived" });
894
+ }
895
+ }
896
+ async queryStrategies(filter) {
897
+ let items = [...this.strategies.values()].filter((s) => s.workspaceId === filter.workspaceId);
898
+ if (filter.scopeRef) items = items.filter((s) => s.scopeRef === filter.scopeRef || !s.scopeRef);
899
+ return paginate(items, filter.offset, filter.limit);
900
+ }
901
+ // ── Workflows ─────────────────────────────────────────────────────────────────
902
+ async createWorkflow(input) {
903
+ const now = /* @__PURE__ */ new Date();
904
+ const workflow = {
905
+ id: uuid(),
906
+ workspaceId: input.workspaceId,
907
+ name: input.name,
908
+ description: input.description,
909
+ steps: input.steps ?? [],
910
+ scopeRef: input.scopeRef,
911
+ sensitivity: input.sensitivity ?? "internal",
912
+ avgDurationMs: 0,
913
+ successRate: 0,
914
+ worth: 0.5,
915
+ executionCount: 0,
916
+ version: 1,
917
+ // P18: initialize bitemporal columns
918
+ validFrom: now,
919
+ validTo: void 0,
920
+ status: "active",
921
+ createdAt: now,
922
+ updatedAt: now,
923
+ metadata: input.metadata ?? {}
924
+ };
925
+ this.workflows.set(workflow.id, workflow);
926
+ return workflow;
927
+ }
928
+ async getWorkflow(id, workspaceId) {
929
+ const w = this.workflows.get(id);
930
+ return w && w.workspaceId === workspaceId ? w : null;
931
+ }
932
+ async updateWorkflow(id, input) {
933
+ const w = this.workflows.get(id);
934
+ if (!w) throw new Error(`Workflow ${id} not found`);
935
+ const updated = { ...w, ...input, updatedAt: /* @__PURE__ */ new Date() };
936
+ this.workflows.set(id, updated);
937
+ return updated;
938
+ }
939
+ async archiveWorkflow(id, workspaceId) {
940
+ const w = this.workflows.get(id);
941
+ if (w && w.workspaceId === workspaceId) {
942
+ this.workflows.set(id, { ...w, status: "deprecated", validTo: /* @__PURE__ */ new Date(), updatedAt: /* @__PURE__ */ new Date() });
943
+ }
944
+ }
945
+ async queryWorkflows(filter) {
946
+ let items = [...this.workflows.values()].filter((w) => {
947
+ if (w.workspaceId !== filter.workspaceId) return false;
948
+ if (filter.validAt) {
949
+ if (w.validFrom > filter.validAt) return false;
950
+ if (w.validTo != null && w.validTo <= filter.validAt) return false;
951
+ }
952
+ return true;
953
+ });
954
+ if (filter.scopeRef) items = items.filter((w) => w.scopeRef === filter.scopeRef || !w.scopeRef);
955
+ return paginate(items, filter.offset, filter.limit);
956
+ }
957
+ // ── Skills ────────────────────────────────────────────────────────────────────
958
+ async createSkill(input) {
959
+ const now = /* @__PURE__ */ new Date();
960
+ const skill = {
961
+ id: uuid(),
962
+ workspaceId: input.workspaceId,
963
+ name: input.name,
964
+ promptTemplate: input.promptTemplate,
965
+ variables: input.variables ?? [],
966
+ requiredContext: input.requiredContext ?? [],
967
+ sensitivity: input.sensitivity ?? "internal",
968
+ qualityScore: 0,
969
+ worth: 0.5,
970
+ usageCount: 0,
971
+ embeddingStale: true,
972
+ // P18: initialize bitemporal columns
973
+ validFrom: now,
974
+ validTo: void 0,
975
+ createdAt: now,
976
+ updatedAt: now,
977
+ metadata: input.metadata ?? {}
978
+ };
979
+ this.skills.set(skill.id, skill);
980
+ return skill;
981
+ }
982
+ async getSkill(id, workspaceId) {
983
+ const s = this.skills.get(id);
984
+ return s && s.workspaceId === workspaceId ? s : null;
985
+ }
986
+ async updateSkill(id, input) {
987
+ const s = this.skills.get(id);
988
+ if (!s) throw new Error(`Skill ${id} not found`);
989
+ const updated = { ...s, ...input, updatedAt: /* @__PURE__ */ new Date() };
990
+ this.skills.set(id, updated);
991
+ return updated;
992
+ }
993
+ async archiveSkill(id, workspaceId) {
994
+ const s = this.skills.get(id);
995
+ if (s && s.workspaceId === workspaceId) {
996
+ this.skills.set(id, { ...s, validTo: /* @__PURE__ */ new Date(), updatedAt: /* @__PURE__ */ new Date() });
997
+ }
998
+ }
999
+ async querySkills(filter) {
1000
+ const items = [...this.skills.values()].filter((s) => {
1001
+ if (s.workspaceId !== filter.workspaceId) return false;
1002
+ if (filter.validAt) {
1003
+ if (s.validFrom > filter.validAt) return false;
1004
+ if (s.validTo != null && s.validTo <= filter.validAt) return false;
1005
+ }
1006
+ return true;
1007
+ });
1008
+ return paginate(items, filter.offset, filter.limit);
1009
+ }
1010
+ // ── Tasks ─────────────────────────────────────────────────────────────────────
1011
+ async createTask(input) {
1012
+ const now = /* @__PURE__ */ new Date();
1013
+ const task = {
1014
+ id: uuid(),
1015
+ workspaceId: input.workspaceId,
1016
+ title: input.title,
1017
+ description: input.description,
1018
+ priority: input.priority ?? "medium",
1019
+ assignedTo: input.assignedTo,
1020
+ sessionId: input.sessionId,
1021
+ parentTaskId: input.parentTaskId,
1022
+ dueAt: input.dueAt,
1023
+ status: "pending",
1024
+ delegatedBy: input.delegatedBy,
1025
+ relatedFacts: input.relatedFacts ?? [],
1026
+ relatedEntities: input.relatedEntities ?? [],
1027
+ sensitivity: input.sensitivity ?? "internal",
1028
+ blockedBy: [],
1029
+ subtaskIds: [],
1030
+ // P18: initialize bitemporal columns
1031
+ validFrom: now,
1032
+ validTo: void 0,
1033
+ createdAt: now,
1034
+ updatedAt: now,
1035
+ metadata: input.metadata ?? {}
1036
+ };
1037
+ this.tasks.set(task.id, task);
1038
+ return task;
1039
+ }
1040
+ async getTask(id, workspaceId) {
1041
+ const t = this.tasks.get(id);
1042
+ return t && t.workspaceId === workspaceId ? t : null;
1043
+ }
1044
+ async updateTask(id, input) {
1045
+ const t = this.tasks.get(id);
1046
+ if (!t) throw new Error(`Task ${id} not found`);
1047
+ const updated = { ...t, ...input, updatedAt: /* @__PURE__ */ new Date() };
1048
+ this.tasks.set(id, updated);
1049
+ return updated;
1050
+ }
1051
+ async archiveTask(id, workspaceId) {
1052
+ const t = this.tasks.get(id);
1053
+ if (t && t.workspaceId === workspaceId) {
1054
+ this.tasks.set(id, { ...t, status: "cancelled", validTo: /* @__PURE__ */ new Date(), updatedAt: /* @__PURE__ */ new Date() });
1055
+ }
1056
+ }
1057
+ async listTasksForSession(workspaceId, sessionId) {
1058
+ return [...this.tasks.values()].filter((t) => t.workspaceId === workspaceId && t.sessionId === sessionId).map((t) => ({ id: t.id, status: t.status }));
1059
+ }
1060
+ async listStaleTasks(workspaceId, staleSinceMs, limit) {
1061
+ const cutoff = new Date(Date.now() - staleSinceMs);
1062
+ const excluded = /* @__PURE__ */ new Set(["done", "cancelled", "archived"]);
1063
+ return [...this.tasks.values()].filter(
1064
+ (t) => t.workspaceId === workspaceId && !excluded.has(t.status) && t.updatedAt < cutoff
1065
+ ).sort((a, b) => a.updatedAt.getTime() - b.updatedAt.getTime()).slice(0, limit).map((t) => ({ id: t.id, title: t.title, status: t.status, updatedAt: t.updatedAt }));
1066
+ }
1067
+ // ── §3.5 snapshot count methods ───────────────────────────────────────────────
1068
+ async countFactsByTypeStatus() {
1069
+ const counts = /* @__PURE__ */ new Map();
1070
+ for (const f of this.facts.values()) {
1071
+ if (f.status !== "forgotten") {
1072
+ const key = `${f.kind}::${f.status}`;
1073
+ counts.set(key, (counts.get(key) ?? 0) + 1);
1074
+ }
1075
+ }
1076
+ return Array.from(counts.entries()).map(([k, count]) => {
1077
+ const sep = k.indexOf("::");
1078
+ const type = k.slice(0, sep);
1079
+ const status = k.slice(sep + 2);
1080
+ return { type, status, count };
1081
+ });
1082
+ }
1083
+ async worthHistogram() {
1084
+ const buckets = {
1085
+ "0.0-0.2": 0,
1086
+ "0.2-0.4": 0,
1087
+ "0.4-0.6": 0,
1088
+ "0.6-0.8": 0,
1089
+ "0.8-1.0": 0
1090
+ };
1091
+ for (const f of this.facts.values()) {
1092
+ if (f.status !== "forgotten" && typeof f.worth === "number") {
1093
+ const w = f.worth;
1094
+ if (w < 0.2) buckets["0.0-0.2"]++;
1095
+ else if (w < 0.4) buckets["0.2-0.4"]++;
1096
+ else if (w < 0.6) buckets["0.4-0.6"]++;
1097
+ else if (w < 0.8) buckets["0.6-0.8"]++;
1098
+ else buckets["0.8-1.0"]++;
1099
+ }
1100
+ }
1101
+ return Object.entries(buckets).map(([bucket, count]) => ({ bucket, count }));
1102
+ }
1103
+ async countActiveSessions() {
1104
+ let n = 0;
1105
+ for (const s of this.sessions.values()) {
1106
+ if (s.status === "active") n++;
1107
+ }
1108
+ return n;
1109
+ }
1110
+ async countTasksByStatus() {
1111
+ const counts = /* @__PURE__ */ new Map();
1112
+ for (const t of this.tasks.values()) {
1113
+ counts.set(t.status, (counts.get(t.status) ?? 0) + 1);
1114
+ }
1115
+ return Array.from(counts.entries()).map(([status, count]) => ({ status, count }));
1116
+ }
1117
+ async countStaleTasks() {
1118
+ const staleSinceMs = 7 * 24 * 60 * 60 * 1e3;
1119
+ const excluded = /* @__PURE__ */ new Set(["done", "cancelled", "archived"]);
1120
+ const cutoff = new Date(Date.now() - staleSinceMs);
1121
+ let n = 0;
1122
+ for (const t of this.tasks.values()) {
1123
+ if (!excluded.has(t.status) && t.updatedAt < cutoff) n++;
1124
+ }
1125
+ return n;
1126
+ }
1127
+ async listScoredTrajectories(workspaceId, agentId, limit) {
1128
+ const ratingToScore = (r) => {
1129
+ if (r === "success") return 1;
1130
+ if (r === "failure") return 0;
1131
+ if (r === "neutral") return 0.5;
1132
+ return null;
1133
+ };
1134
+ const results = [];
1135
+ for (const s of this.sessions.values()) {
1136
+ if (s.workspaceId !== workspaceId) continue;
1137
+ if (agentId !== "*" && s.agentId !== agentId) continue;
1138
+ const rating = s.metadata?.outcomeRating;
1139
+ const score = ratingToScore(rating);
1140
+ if (score === null) continue;
1141
+ results.push({
1142
+ sessionId: s.id,
1143
+ score,
1144
+ promptVersionId: s.activePromptVersionId ?? null,
1145
+ createdAt: s.openedAt
1146
+ });
1147
+ }
1148
+ return results.sort((a, b) => b.createdAt.getTime() - a.createdAt.getTime()).slice(0, limit);
1149
+ }
1150
+ async computeCandidateAbScore(workspaceId, agentId, promptVersionId) {
1151
+ const ratingToScore = (r) => {
1152
+ if (r === "success") return 1;
1153
+ if (r === "failure") return 0;
1154
+ if (r === "neutral") return 0.5;
1155
+ return null;
1156
+ };
1157
+ const scores = [];
1158
+ for (const s of this.sessions.values()) {
1159
+ if (s.workspaceId !== workspaceId) continue;
1160
+ if (agentId !== "*" && s.agentId !== agentId) continue;
1161
+ if ((s.activePromptVersionId ?? null) !== promptVersionId) continue;
1162
+ const rating = s.metadata?.outcomeRating;
1163
+ const score = ratingToScore(rating);
1164
+ if (score === null) continue;
1165
+ scores.push(score);
1166
+ }
1167
+ if (scores.length === 0) return null;
1168
+ return scores.reduce((a, b) => a + b, 0) / scores.length;
1169
+ }
1170
+ async delegateTask(id, workspaceId, input) {
1171
+ const task = [...this.tasks.values()].find(
1172
+ (t) => t.id === id && t.workspaceId === workspaceId
1173
+ );
1174
+ if (!task) throw new Error(`Task not found: ${id}`);
1175
+ const updated = {
1176
+ ...task,
1177
+ status: "delegated",
1178
+ assignedTo: input.assignedTo,
1179
+ delegatedBy: input.delegatedBy,
1180
+ delegatedAt: /* @__PURE__ */ new Date(),
1181
+ updatedAt: /* @__PURE__ */ new Date()
1182
+ };
1183
+ this.tasks.set(id, updated);
1184
+ return updated;
1185
+ }
1186
+ async queryTasks(filter) {
1187
+ const items = [...this.tasks.values()].filter((t) => {
1188
+ if (t.workspaceId !== filter.workspaceId) return false;
1189
+ if (filter.validAt) {
1190
+ if (t.validFrom > filter.validAt) return false;
1191
+ if (t.validTo != null && t.validTo <= filter.validAt) return false;
1192
+ }
1193
+ return true;
1194
+ });
1195
+ return paginate(items, filter.offset, filter.limit);
1196
+ }
1197
+ // ── Events ────────────────────────────────────────────────────────────────────
1198
+ async createEvent(input) {
1199
+ const now = /* @__PURE__ */ new Date();
1200
+ const event = {
1201
+ id: uuid(),
1202
+ workspaceId: input.workspaceId,
1203
+ type: input.type,
1204
+ name: input.name,
1205
+ description: input.description,
1206
+ occurredAt: input.occurredAt,
1207
+ durationS: input.durationS,
1208
+ source: input.source,
1209
+ relatedEntities: input.relatedEntities ?? [],
1210
+ annotations: input.annotations ?? [],
1211
+ sensitivity: input.sensitivity ?? "internal",
1212
+ createdAt: now,
1213
+ metadata: input.metadata ?? {}
1214
+ };
1215
+ this.events.set(event.id, event);
1216
+ return event;
1217
+ }
1218
+ async getEvent(id, workspaceId) {
1219
+ const e = this.events.get(id);
1220
+ return e && e.workspaceId === workspaceId ? e : null;
1221
+ }
1222
+ async archiveEvent(id, workspaceId) {
1223
+ const e = this.events.get(id);
1224
+ if (e && e.workspaceId === workspaceId) {
1225
+ this.events.delete(id);
1226
+ }
1227
+ }
1228
+ async appendEventAnnotation(id, workspaceId, annotation) {
1229
+ const event = [...this.events.values()].find(
1230
+ (e) => e.id === id && e.workspaceId === workspaceId
1231
+ );
1232
+ if (!event) throw new Error(`Event not found: ${id}`);
1233
+ const updated = {
1234
+ ...event,
1235
+ annotations: [...event.annotations ?? [], annotation]
1236
+ };
1237
+ this.events.set(id, updated);
1238
+ return updated;
1239
+ }
1240
+ async queryEvents(filter) {
1241
+ const items = [...this.events.values()].filter((e) => e.workspaceId === filter.workspaceId);
1242
+ return paginate(items, filter.offset, filter.limit);
1243
+ }
1244
+ async updateEventSensitivity(id, workspaceId, sensitivity) {
1245
+ const event = this.events.get(id);
1246
+ if (event && event.workspaceId === workspaceId) {
1247
+ this.events.set(id, { ...event, sensitivity });
1248
+ }
1249
+ }
1250
+ // ── Reasoning ─────────────────────────────────────────────────────────────────
1251
+ async createReasoning(input) {
1252
+ const now = /* @__PURE__ */ new Date();
1253
+ const reasoning = {
1254
+ id: uuid(),
1255
+ workspaceId: input.workspaceId,
1256
+ agentId: input.agentId,
1257
+ question: input.question,
1258
+ chain: input.chain,
1259
+ conclusion: input.conclusion,
1260
+ topicKey: input.topicKey,
1261
+ sensitivity: input.sensitivity ?? "internal",
1262
+ successCount: 0,
1263
+ failureCount: 0,
1264
+ worth: 0.5,
1265
+ usageCount: 0,
1266
+ embeddingStale: true,
1267
+ status: "active",
1268
+ createdAt: now,
1269
+ updatedAt: now,
1270
+ metadata: input.metadata ?? {}
1271
+ };
1272
+ this.reasonings.set(reasoning.id, reasoning);
1273
+ return reasoning;
1274
+ }
1275
+ async getReasoning(id, workspaceId) {
1276
+ const r = this.reasonings.get(id);
1277
+ return r && r.workspaceId === workspaceId ? r : null;
1278
+ }
1279
+ async updateReasoning(id, input) {
1280
+ const r = this.reasonings.get(id);
1281
+ if (!r) throw new Error(`Reasoning ${id} not found`);
1282
+ const updated = { ...r, ...input, updatedAt: /* @__PURE__ */ new Date() };
1283
+ this.reasonings.set(id, updated);
1284
+ return updated;
1285
+ }
1286
+ async archiveReasoning(id, workspaceId) {
1287
+ const r = this.reasonings.get(id);
1288
+ if (r && r.workspaceId === workspaceId) {
1289
+ this.reasonings.set(id, { ...r, status: "archived" });
1290
+ }
1291
+ }
1292
+ async queryReasoning(filter) {
1293
+ let items = [...this.reasonings.values()].filter((r) => r.workspaceId === filter.workspaceId);
1294
+ if (filter.status) items = items.filter((r) => r.status === filter.status);
1295
+ if (filter.topicKey) items = items.filter((r) => r.topicKey === filter.topicKey);
1296
+ return paginate(items, filter.offset, filter.limit);
1297
+ }
1298
+ // Wave M1 — CoT cache adapter methods (spec §8)
1299
+ async searchReasoning(input) {
1300
+ const servable = /* @__PURE__ */ new Set(["active", "golden"]);
1301
+ const rows = [...this.reasonings.values()].filter((r) => r.workspaceId === input.workspaceId).filter((r) => input.includeAllStatuses || servable.has(r.status));
1302
+ return rows.slice(0, input.limit).map((r) => ({
1303
+ id: r.id,
1304
+ cosine: 1,
1305
+ worth: r.worth,
1306
+ successCount: r.successCount,
1307
+ failureCount: r.failureCount,
1308
+ status: r.status
1309
+ }));
1310
+ }
1311
+ async recordReasoningUse(id, workspaceId) {
1312
+ const r = this.reasonings.get(id);
1313
+ if (!r || r.workspaceId !== workspaceId) return;
1314
+ this.reasonings.set(id, {
1315
+ ...r,
1316
+ usageCount: r.usageCount + 1,
1317
+ lastUsedAt: /* @__PURE__ */ new Date(),
1318
+ updatedAt: /* @__PURE__ */ new Date()
1319
+ });
1320
+ }
1321
+ async setReasoningStatus(id, workspaceId, status) {
1322
+ const r = this.reasonings.get(id);
1323
+ if (!r || r.workspaceId !== workspaceId) return;
1324
+ this.reasonings.set(id, { ...r, status, updatedAt: /* @__PURE__ */ new Date() });
1325
+ }
1326
+ // ── Agent profile (Wave M2 — spec §13 self-editing memory) ───────────────────
1327
+ async getAgentProfile(workspaceId, agentId) {
1328
+ return this.agentProfiles.get(`${workspaceId}:${agentId}`) ?? null;
1329
+ }
1330
+ async upsertAgentProfile(input) {
1331
+ const key = `${input.workspaceId}:${input.agentId}`;
1332
+ const existing = this.agentProfiles.get(key);
1333
+ const now = /* @__PURE__ */ new Date();
1334
+ const updated = {
1335
+ workspaceId: input.workspaceId,
1336
+ agentId: input.agentId,
1337
+ summary: input.summary ?? existing?.summary ?? "",
1338
+ metadata: input.metadata ?? existing?.metadata ?? {},
1339
+ createdAt: existing?.createdAt ?? now,
1340
+ updatedAt: now
1341
+ };
1342
+ this.agentProfiles.set(key, updated);
1343
+ return updated;
1344
+ }
1345
+ async incrementSessionsSinceReflection(workspaceId, agentId) {
1346
+ const key = `${workspaceId}:${agentId}`;
1347
+ const existing = this.agentProfiles.get(key);
1348
+ const prev = existing?.metadata?.sessionsSinceReflection ?? 0;
1349
+ const next = prev + 1;
1350
+ const now = /* @__PURE__ */ new Date();
1351
+ const updated = {
1352
+ workspaceId,
1353
+ agentId,
1354
+ summary: existing?.summary ?? "",
1355
+ metadata: { ...existing?.metadata ?? {}, sessionsSinceReflection: next },
1356
+ createdAt: existing?.createdAt ?? now,
1357
+ updatedAt: now
1358
+ };
1359
+ this.agentProfiles.set(key, updated);
1360
+ return next;
1361
+ }
1362
+ // ── Hyperedges (Wave D) ───────────────────────────────────────────────────────
1363
+ async createHyperedge(input) {
1364
+ if (input.memberIds.length < 3) {
1365
+ throw new Error("createHyperedge requires at least 3 memberIds");
1366
+ }
1367
+ const now = /* @__PURE__ */ new Date();
1368
+ const h = {
1369
+ id: uuid(),
1370
+ workspaceId: input.workspaceId,
1371
+ memberIds: input.memberIds,
1372
+ activationCount: 0,
1373
+ worth: 0.5,
1374
+ validFrom: now,
1375
+ createdAt: now
1376
+ };
1377
+ if (input.label !== void 0) h.label = input.label;
1378
+ if (input.description !== void 0) h.description = input.description;
1379
+ if (input.contextQuery !== void 0) h.contextQuery = input.contextQuery;
1380
+ if (input.contextEmbedding !== void 0) h.contextEmbedding = input.contextEmbedding;
1381
+ this.hyperedges.set(h.id, h);
1382
+ return h;
1383
+ }
1384
+ async getHyperedge(id, workspaceId) {
1385
+ const h = this.hyperedges.get(id);
1386
+ if (!h || h.workspaceId !== workspaceId) return null;
1387
+ return h;
1388
+ }
1389
+ async updateHyperedge(id, input) {
1390
+ const h = this.hyperedges.get(id);
1391
+ if (!h) throw new Error(`Hyperedge not found: ${id}`);
1392
+ if (input.label !== void 0) h.label = input.label;
1393
+ if (input.description !== void 0) h.description = input.description;
1394
+ if (input.contextQuery !== void 0) h.contextQuery = input.contextQuery;
1395
+ return h;
1396
+ }
1397
+ async archiveHyperedge(id, workspaceId) {
1398
+ const h = this.hyperedges.get(id);
1399
+ if (h && h.workspaceId === workspaceId) {
1400
+ h.validTo = /* @__PURE__ */ new Date();
1401
+ }
1402
+ }
1403
+ async queryHyperedges(filter) {
1404
+ let items = [...this.hyperedges.values()].filter((h) => h.workspaceId === filter.workspaceId);
1405
+ if (filter.memberId) {
1406
+ items = items.filter((h) => h.memberIds.includes(filter.memberId));
1407
+ }
1408
+ if (filter.label) {
1409
+ items = items.filter((h) => h.label === filter.label);
1410
+ }
1411
+ items.sort((a, b) => b.activationCount - a.activationCount);
1412
+ return paginate(items, filter.offset, filter.limit);
1413
+ }
1414
+ async bumpHyperedgeActivation(id, workspaceId) {
1415
+ const h = this.hyperedges.get(id);
1416
+ if (h && h.workspaceId === workspaceId) {
1417
+ h.activationCount += 1;
1418
+ }
1419
+ }
1420
+ // ── Composition rules (Wave E) ────────────────────────────────────────────────
1421
+ async createCompositionRule(input) {
1422
+ const id = uuid();
1423
+ const rule = {
1424
+ id,
1425
+ workspaceId: input.workspaceId,
1426
+ name: input.name,
1427
+ description: input.description,
1428
+ conditionDsl: input.conditionDsl,
1429
+ actionDsl: input.actionDsl,
1430
+ priority: input.priority ?? 100,
1431
+ isActive: input.isActive ?? true,
1432
+ executionCount: 0,
1433
+ createdBy: input.createdBy,
1434
+ source: input.source ?? "manual",
1435
+ metadata: input.metadata ?? {},
1436
+ createdAt: /* @__PURE__ */ new Date(),
1437
+ updatedAt: /* @__PURE__ */ new Date()
1438
+ };
1439
+ this.compositionRules.set(id, rule);
1440
+ return rule;
1441
+ }
1442
+ async getCompositionRule(id, workspaceId) {
1443
+ const rule = this.compositionRules.get(id);
1444
+ return rule && rule.workspaceId === workspaceId ? rule : null;
1445
+ }
1446
+ async updateCompositionRule(id, workspaceId, input) {
1447
+ const rule = this.compositionRules.get(id);
1448
+ if (!rule || rule.workspaceId !== workspaceId) throw new Error(`CompositionRule ${id} not found`);
1449
+ const updated = { ...rule, ...input, updatedAt: /* @__PURE__ */ new Date() };
1450
+ this.compositionRules.set(id, updated);
1451
+ return updated;
1452
+ }
1453
+ async queryCompositionRules(filter) {
1454
+ let items = Array.from(this.compositionRules.values()).filter((r) => r.workspaceId === filter.workspaceId);
1455
+ if (filter.isActive !== void 0) items = items.filter((r) => r.isActive === filter.isActive);
1456
+ if (filter.source) items = items.filter((r) => r.source === filter.source);
1457
+ items.sort((a, b) => b.priority - a.priority);
1458
+ return paginate(items, filter.offset, filter.limit);
1459
+ }
1460
+ async bumpCompositionExecution(id, workspaceId) {
1461
+ const rule = this.compositionRules.get(id);
1462
+ if (!rule || rule.workspaceId !== workspaceId) return;
1463
+ this.compositionRules.set(id, { ...rule, executionCount: rule.executionCount + 1, updatedAt: /* @__PURE__ */ new Date() });
1464
+ }
1465
+ async ensureBuiltinCompositionRules(_workspaceId) {
1466
+ }
1467
+ async appendInference(input) {
1468
+ const entry = {
1469
+ id: uuid(),
1470
+ workspaceId: input.workspaceId,
1471
+ ruleId: input.ruleId,
1472
+ inputFactIds: input.inputFactIds,
1473
+ derivedKind: input.derivedKind,
1474
+ derivedId: input.derivedId,
1475
+ confidence: input.confidence,
1476
+ rationale: input.rationale,
1477
+ triggeredByQuery: input.triggeredByQuery,
1478
+ conversationId: input.conversationId,
1479
+ createdAt: /* @__PURE__ */ new Date()
1480
+ };
1481
+ this.inferences.push(entry);
1482
+ return entry;
1483
+ }
1484
+ async materialiseInference(input) {
1485
+ const now = /* @__PURE__ */ new Date();
1486
+ const factId = uuid();
1487
+ const fact = {
1488
+ id: factId,
1489
+ workspaceId: input.workspaceId,
1490
+ agentId: void 0,
1491
+ actorId: void 0,
1492
+ scope: input.fact.scope,
1493
+ scopeRef: void 0,
1494
+ scopeOwner: `workspace:${input.workspaceId}`,
1495
+ statement: input.fact.statement,
1496
+ subject: input.fact.subject,
1497
+ kind: input.fact.kind,
1498
+ confidence: 0.7,
1499
+ relevance: 0.8,
1500
+ hitCount: 0,
1501
+ worthSuccess: 0,
1502
+ worthFailure: 0,
1503
+ worthAlpha: 2,
1504
+ worthBeta: 2,
1505
+ worth: 0.5,
1506
+ memoryType: "semantic",
1507
+ memoryStrength: 1,
1508
+ memoryStability: 1,
1509
+ attribution: input.fact.attribution,
1510
+ sourceMessageIds: [],
1511
+ revisionCount: 1,
1512
+ protocolVersion: "3.0",
1513
+ status: "active",
1514
+ pinned: false,
1515
+ canonical: false,
1516
+ sensitivity: input.fact.sensitivity,
1517
+ validFrom: now,
1518
+ embeddingStale: true,
1519
+ createdAt: now,
1520
+ updatedAt: now,
1521
+ // A derived fact must never carry a forged pending-consolidation marker.
1522
+ metadata: withoutPendingMarker(input.fact.metadata ?? {})
1523
+ };
1524
+ this.facts.set(fact.id, fact);
1525
+ this.outbox.push({
1526
+ id: uuid(),
1527
+ workspaceId: input.workspaceId,
1528
+ eventType: "vector_upsert",
1529
+ payload: { id: factId, kind: "fact", statement: input.fact.statement },
1530
+ createdAt: now,
1531
+ attempts: 0
1532
+ });
1533
+ this.inferences.push({
1534
+ id: uuid(),
1535
+ workspaceId: input.workspaceId,
1536
+ ruleId: input.ruleId,
1537
+ inputFactIds: input.inferenceLog.inputFactIds,
1538
+ derivedKind: input.inferenceLog.derivedKind,
1539
+ derivedId: factId,
1540
+ confidence: input.inferenceLog.confidence,
1541
+ rationale: input.inferenceLog.rationale,
1542
+ triggeredByQuery: input.inferenceLog.triggeredByQuery,
1543
+ conversationId: input.inferenceLog.conversationId,
1544
+ createdAt: now
1545
+ });
1546
+ const rule = this.compositionRules.get(input.ruleId);
1547
+ if (rule && rule.workspaceId === input.workspaceId) {
1548
+ this.compositionRules.set(input.ruleId, {
1549
+ ...rule,
1550
+ executionCount: rule.executionCount + 1,
1551
+ updatedAt: now
1552
+ });
1553
+ }
1554
+ return { id: factId };
1555
+ }
1556
+ async queryInferences(filter) {
1557
+ let items = this.inferences.filter((e) => e.workspaceId === filter.workspaceId);
1558
+ if (filter.ruleId) items = items.filter((e) => e.ruleId === filter.ruleId);
1559
+ if (filter.derivedId) items = items.filter((e) => e.derivedId === filter.derivedId);
1560
+ if (filter.since) items = items.filter((e) => e.createdAt > filter.since);
1561
+ items = [...items].reverse();
1562
+ return paginate(items, filter.offset, filter.limit);
1563
+ }
1564
+ async lookupFactHash(workspaceId, statementHash) {
1565
+ return this.factHashes.get(`${workspaceId}|${statementHash}`) ?? null;
1566
+ }
1567
+ async upsertFactHash(input) {
1568
+ const key = `${input.workspaceId}|${input.statementHash}`;
1569
+ const existing = this.factHashes.get(key);
1570
+ if (existing) {
1571
+ const updated = { ...existing, seenCount: existing.seenCount + 1, lastSeenAt: /* @__PURE__ */ new Date() };
1572
+ this.factHashes.set(key, updated);
1573
+ return updated;
1574
+ }
1575
+ const entry = {
1576
+ workspaceId: input.workspaceId,
1577
+ statementHash: input.statementHash,
1578
+ factId: input.factId,
1579
+ firstSeenAt: /* @__PURE__ */ new Date(),
1580
+ lastSeenAt: /* @__PURE__ */ new Date(),
1581
+ seenCount: 1
1582
+ };
1583
+ this.factHashes.set(key, entry);
1584
+ return entry;
1585
+ }
1586
+ // ── LSH bands — Tier 2 pointer recall (Wave P) ──────────────────────────────
1587
+ candidateFactMatches(fact, query) {
1588
+ if (fact.workspaceId !== query.workspaceId) return false;
1589
+ const active = fact.status === "active" && fact.validTo == null;
1590
+ const archived = query.includeArchived === true && fact.status === "forgotten" && fact.validTo != null;
1591
+ if (!active && !archived) return false;
1592
+ if (query.includeLowWorth === false) {
1593
+ const n = fact.worthAlpha + fact.worthBeta;
1594
+ const p = n > 0 ? fact.worthAlpha / n : 0;
1595
+ const z2 = 1.96 ** 2;
1596
+ const lower = n > 0 ? (p + z2 / (2 * n) - 1.96 * Math.sqrt(p * (1 - p) / n + z2 / (4 * n * n))) / (1 + z2 / n) : 0;
1597
+ if (fact.worth <= 0.5 || lower < 0.3) return false;
1598
+ }
1599
+ const filter = query.filter;
1600
+ if (!filter) return true;
1601
+ const tags = Array.isArray(fact.metadata.tags) ? fact.metadata.tags.filter((tag) => typeof tag === "string") : [];
1602
+ if (filter.kinds && !filter.kinds.includes("fact")) return false;
1603
+ if (filter.tags && !filter.tags.every((tag) => tags.includes(tag))) return false;
1604
+ if (filter.validAfter && fact.validFrom < filter.validAfter) return false;
1605
+ if (filter.validBefore && fact.validFrom > filter.validBefore) return false;
1606
+ if (filter.minWorth !== void 0 && fact.worth < filter.minWorth) return false;
1607
+ if (filter.minConfidence !== void 0 && fact.confidence < filter.minConfidence) return false;
1608
+ if (filter.sensitivity && !filter.sensitivity.includes(fact.sensitivity)) return false;
1609
+ if (filter.provenance && !filter.provenance.includes(fact.attribution)) return false;
1610
+ if (filter.entityId && fact.entityId !== filter.entityId) return false;
1611
+ if (filter.sessionId && fact.sessionId !== filter.sessionId) return false;
1612
+ if (filter.scope && fact.scope !== filter.scope) return false;
1613
+ if (filter.scopeRef && fact.scopeRef !== filter.scopeRef) return false;
1614
+ if (filter.actorId && fact.actorId !== filter.actorId) return false;
1615
+ return true;
1616
+ }
1617
+ pointerCandidate(fact, embedding) {
1618
+ return {
1619
+ factId: fact.id,
1620
+ statement: fact.statement,
1621
+ embedding,
1622
+ sensitivity: fact.sensitivity,
1623
+ worth: fact.worth,
1624
+ worthAlpha: fact.worthAlpha,
1625
+ worthBeta: fact.worthBeta,
1626
+ attribution: fact.attribution,
1627
+ createdAt: fact.createdAt,
1628
+ validFrom: fact.validFrom,
1629
+ status: fact.status,
1630
+ validTo: fact.validTo ?? null,
1631
+ confidence: fact.confidence,
1632
+ tags: Array.isArray(fact.metadata.tags) ? fact.metadata.tags.filter((tag) => typeof tag === "string") : [],
1633
+ scope: fact.scope,
1634
+ scopeRef: fact.scopeRef,
1635
+ actorId: fact.actorId ?? null,
1636
+ entityId: fact.entityId,
1637
+ sessionId: fact.sessionId
1638
+ };
1639
+ }
1640
+ /** Test-only helper: store a pre-computed embedding to be returned by pointerCandidates. */
1641
+ setEmbedding(id, vec) {
1642
+ this.embeddings.set(id, vec);
1643
+ }
1644
+ async upsertFactLsh(input) {
1645
+ const fact = this.facts.get(input.factId);
1646
+ if (!fact || fact.workspaceId !== input.workspaceId || fact.revisionCount !== input.revision) return;
1647
+ this.factLsh.set(`${input.workspaceId}:${input.factId}`, input.bands);
1648
+ }
1649
+ async getRecallPrimitives(workspaceId, refs) {
1650
+ const stores = {
1651
+ fact: this.facts,
1652
+ decision: this.decisions,
1653
+ episode: this.episodes,
1654
+ entity: this.entities,
1655
+ strategy: this.strategies,
1656
+ workflow: this.workflows,
1657
+ skill: this.skills,
1658
+ task: this.tasks,
1659
+ event: this.events,
1660
+ reasoning: this.reasonings
1661
+ };
1662
+ const records = [];
1663
+ for (const ref of refs) {
1664
+ const value = ref.kind === "episode" ? await this.reconstructEpisode(ref.id, workspaceId).catch(() => null) : stores[ref.kind].get(ref.id);
1665
+ if (value?.workspaceId === workspaceId) {
1666
+ records.push({ ...ref, value });
1667
+ }
1668
+ }
1669
+ return records;
1670
+ }
1671
+ async getRecallStructures(workspaceId, sourceIds, hyperedgeLimitPerMember) {
1672
+ const ids = new Set(sourceIds);
1673
+ const relations = [...this.relations.values()].filter(
1674
+ (relation) => relation.workspaceId === workspaceId && ids.has(relation.sourceId)
1675
+ );
1676
+ const counts = /* @__PURE__ */ new Map();
1677
+ const hyperedges = [];
1678
+ for (const hyperedge of this.hyperedges.values()) {
1679
+ if (hyperedge.workspaceId !== workspaceId || hyperedge.validTo != null) continue;
1680
+ for (const memberId of hyperedge.memberIds) {
1681
+ if (!ids.has(memberId)) continue;
1682
+ const count = counts.get(memberId) ?? 0;
1683
+ if (count >= hyperedgeLimitPerMember) continue;
1684
+ hyperedges.push({ memberId, hyperedge });
1685
+ counts.set(memberId, count + 1);
1686
+ }
1687
+ }
1688
+ return { relations, hyperedges };
1689
+ }
1690
+ async pointerCandidates(query) {
1691
+ const signals = /* @__PURE__ */ new Map();
1692
+ const sig = new Set(query.bands.map((b) => `${b.bandIdx}:${b.bandHash}`));
1693
+ for (const [key, bands] of this.factLsh) {
1694
+ const colonIdx = key.indexOf(":");
1695
+ const ws = key.slice(0, colonIdx);
1696
+ const factId = key.slice(colonIdx + 1);
1697
+ if (ws !== query.workspaceId) continue;
1698
+ const collisions = bands.filter((b) => sig.has(`${b.bandIdx}:${b.bandHash}`)).length;
1699
+ if (collisions > 0) signals.set(factId, { collisions, ftsRank: 0 });
1700
+ }
1701
+ const terms = query.terms.map((t) => t.toLowerCase());
1702
+ for (const f of this.facts.values()) {
1703
+ if (!this.candidateFactMatches(f, query)) continue;
1704
+ const hay = f.statement.toLowerCase();
1705
+ const ftsRank = terms.reduce((score, term) => score + (hay.includes(term) ? 1 : 0), 0);
1706
+ if (ftsRank > 0) {
1707
+ const current = signals.get(f.id) ?? { collisions: 0, ftsRank: 0 };
1708
+ signals.set(f.id, { ...current, ftsRank });
1709
+ }
1710
+ }
1711
+ const out = [];
1712
+ const ordered = [...signals.entries()].sort(
1713
+ (a, b) => b[1].ftsRank - a[1].ftsRank || b[1].collisions - a[1].collisions || a[0].localeCompare(b[0])
1714
+ );
1715
+ for (const [id] of ordered) {
1716
+ const f = this.facts.get(id);
1717
+ if (!f || !this.candidateFactMatches(f, query)) continue;
1718
+ out.push(this.pointerCandidate(f, this.embeddings.get(id) ?? null));
1719
+ if (out.length >= query.limit) break;
1720
+ }
1721
+ return out;
1722
+ }
1723
+ /** FTS arm of hybrid Tier-3 recall: lexical substring match over statement. */
1724
+ async ftsCandidates(query) {
1725
+ if (query.terms.length === 0) return [];
1726
+ const terms = query.terms.map((t) => t.toLowerCase());
1727
+ const out = [];
1728
+ for (const f of this.facts.values()) {
1729
+ if (!this.candidateFactMatches(f, query)) continue;
1730
+ const hay = f.statement.toLowerCase();
1731
+ if (!terms.some((t) => hay.includes(t))) continue;
1732
+ out.push({ ...this.pointerCandidate(f, this.embeddings.get(f.id) ?? null), rank: 1 });
1733
+ if (out.length >= query.limit) break;
1734
+ }
1735
+ return out;
1736
+ }
1737
+ // ── Meta-cognition (Wave F) ───────────────────────────────────────────────────
1738
+ async getConfidenceMap(workspaceId, opts) {
1739
+ const limit = opts?.limit ?? 500;
1740
+ const out = [];
1741
+ for (const e of this.entities.values()) {
1742
+ if (e.workspaceId !== workspaceId) continue;
1743
+ const facts = [...this.facts.values()].filter(
1744
+ (f) => f.workspaceId === workspaceId && f.entityId === e.id && f.status === "active" && f.validTo == null
1745
+ );
1746
+ const factCount = facts.length;
1747
+ const avgWorth = factCount ? facts.reduce((a, f) => a + (f.worth ?? 0.5), 0) / factCount : 0;
1748
+ const avgConfidence = factCount ? facts.reduce((a, f) => a + (f.confidence ?? 0.7), 0) / factCount : 0;
1749
+ const newest = facts.reduce((m, f) => {
1750
+ const d = f.createdAt ?? null;
1751
+ return d && (!m || d > m) ? d : m;
1752
+ }, null);
1753
+ const evidenceVolume = facts.reduce(
1754
+ (a, f) => a + ((f.worthSuccess ?? 1) + (f.worthFailure ?? 1)),
1755
+ 0
1756
+ );
1757
+ const coverageLevel = factCount >= 10 && avgWorth > 0.7 ? "expert" : factCount >= 5 && avgWorth > 0.5 ? "familiar" : factCount >= 2 ? "aware" : factCount >= 1 ? "minimal" : "blind";
1758
+ const ageMs = newest ? Date.now() - newest.getTime() : Infinity;
1759
+ const day = 864e5;
1760
+ const freshness = ageMs < 7 * day ? "current" : ageMs < 30 * day ? "recent" : ageMs < 90 * day ? "aging" : "stale";
1761
+ out.push({
1762
+ workspaceId,
1763
+ entityId: e.id,
1764
+ canonicalName: e.name,
1765
+ kind: e.kind ?? "concept",
1766
+ factCount,
1767
+ avgConfidence,
1768
+ coverageLevel,
1769
+ freshness,
1770
+ topicKey: e.name,
1771
+ memoryCount: factCount,
1772
+ avgWorth,
1773
+ evidenceVolume,
1774
+ distinctAttributions: 0,
1775
+ pinnedCount: 0,
1776
+ lowStrengthCount: 0,
1777
+ lastUpdatedAt: /* @__PURE__ */ new Date()
1778
+ });
1779
+ }
1780
+ return out.slice(0, limit);
1781
+ }
1782
+ async getKnowledgeGaps(_workspaceId, _opts) {
1783
+ return [];
1784
+ }
1785
+ async getMetacognitionTrends(_workspaceId) {
1786
+ const z = { current: 0, previous: 0, delta: 0 };
1787
+ return { recallHitRate: z, avgRecallLatency: z, sessionCollapseQuality: z, strategySuccessRate: z };
1788
+ }
1789
+ async refreshMetacognitionViews() {
1790
+ }
1791
+ // ── Anticipation (Wave G) ─────────────────────────────────────────────────────
1792
+ async getSequentialPatterns(_args) {
1793
+ return [];
1794
+ }
1795
+ async getPeriodicPatterns(_args) {
1796
+ return [];
1797
+ }
1798
+ async refreshAnticipationViews() {
1799
+ }
1800
+ async getConditionalPatterns() {
1801
+ return [];
1802
+ }
1803
+ async getCoOccurrencePatterns() {
1804
+ return [];
1805
+ }
1806
+ // ── Relations ─────────────────────────────────────────────────────────────────
1807
+ async createRelation(input) {
1808
+ const now = /* @__PURE__ */ new Date();
1809
+ const relation = {
1810
+ id: uuid(),
1811
+ workspaceId: input.workspaceId,
1812
+ sourceId: input.sourceId,
1813
+ sourceType: input.sourceType,
1814
+ targetId: input.targetId,
1815
+ targetType: input.targetType,
1816
+ verb: input.verb,
1817
+ weight: input.weight ?? 1,
1818
+ createdAt: now,
1819
+ updatedAt: now,
1820
+ metadata: input.metadata ?? {}
1821
+ };
1822
+ this.relations.set(relation.id, relation);
1823
+ return relation;
1824
+ }
1825
+ async getRelations(filter) {
1826
+ let items = [...this.relations.values()].filter((r) => r.workspaceId === filter.workspaceId);
1827
+ if (filter.sourceId) items = items.filter((r) => r.sourceId === filter.sourceId);
1828
+ if (filter.targetId) items = items.filter((r) => r.targetId === filter.targetId);
1829
+ if (filter.verb) items = items.filter((r) => r.verb === filter.verb);
1830
+ return items;
1831
+ }
1832
+ async updateRelationStrength(id, delta) {
1833
+ const r = this.relations.get(id);
1834
+ if (r) this.relations.set(id, { ...r, weight: (r.weight ?? 1) + delta });
1835
+ }
1836
+ async deleteRelation(id, workspaceId) {
1837
+ const r = this.relations.get(id);
1838
+ if (r && r.workspaceId === workspaceId) this.relations.delete(id);
1839
+ }
1840
+ // ── Worth governance ──────────────────────────────────────────────────────────
1841
+ async updateWorth(id, workspaceId, primitiveKind, delta) {
1842
+ switch (primitiveKind) {
1843
+ case "fact": {
1844
+ const f = this.facts.get(id);
1845
+ if (!f || f.workspaceId !== workspaceId) return;
1846
+ if (hasPendingMarker(f.metadata)) return;
1847
+ const sDelta = delta.success * delta.creditWeight;
1848
+ const fDelta = delta.failure * delta.creditWeight;
1849
+ f.worthAlpha = (f.worthAlpha ?? 2) + sDelta;
1850
+ f.worthBeta = (f.worthBeta ?? 2) + fDelta;
1851
+ f.worthSuccess = (f.worthSuccess ?? 0) + sDelta;
1852
+ f.worthFailure = (f.worthFailure ?? 0) + fDelta;
1853
+ const denom = f.worthAlpha + f.worthBeta;
1854
+ f.worth = denom > 0 ? f.worthAlpha / denom : 0;
1855
+ f.updatedAt = /* @__PURE__ */ new Date();
1856
+ break;
1857
+ }
1858
+ case "hyperedge": {
1859
+ const h = this.hyperedges.get(id);
1860
+ if (!h || h.workspaceId !== workspaceId) return;
1861
+ const netDelta = (delta.success - delta.failure) * delta.creditWeight * 0.1;
1862
+ h.worth = Math.min(1, Math.max(0, h.worth + netDelta));
1863
+ break;
1864
+ }
1865
+ case "reasoning": {
1866
+ const r = this.reasonings.get(id);
1867
+ if (!r || r.workspaceId !== workspaceId) return;
1868
+ const newSuccess = (r.successCount ?? 0) + Math.round((delta.success ?? 0) * (delta.creditWeight ?? 1));
1869
+ const newFailure = (r.failureCount ?? 0) + Math.round((delta.failure ?? 0) * (delta.creditWeight ?? 1));
1870
+ const total = newSuccess + newFailure;
1871
+ this.reasonings.set(id, {
1872
+ ...r,
1873
+ successCount: newSuccess,
1874
+ failureCount: newFailure,
1875
+ worth: total === 0 ? 0.5 : newSuccess / total,
1876
+ updatedAt: /* @__PURE__ */ new Date()
1877
+ });
1878
+ break;
1879
+ }
1880
+ }
1881
+ }
1882
+ async recordRecall(entry) {
1883
+ this.recallLog.push(entry);
1884
+ const f = this.facts.get(entry.factId);
1885
+ if (f) this.facts.set(f.id, { ...f, hitCount: f.hitCount + 1, lastRecalledAt: /* @__PURE__ */ new Date() });
1886
+ }
1887
+ async getTdPredecessors(_workspaceId, _sessionId, _excludeFactId) {
1888
+ return [];
1889
+ }
1890
+ // ─── §11 Governance ─────────────────────────────────────────────────────────
1891
+ async setCanonical(id, workspaceId, canonical) {
1892
+ const fact = [...this.facts.values()].find((f) => f.id === id && f.workspaceId === workspaceId);
1893
+ if (fact && !hasPendingMarker(fact.metadata)) this.facts.set(id, { ...fact, canonical });
1894
+ }
1895
+ async getRecalledFactIds(workspaceId, sessionId) {
1896
+ const seen = /* @__PURE__ */ new Set();
1897
+ for (const entry of this.recallLog) {
1898
+ if (entry.workspaceId === workspaceId && entry.sessionId === sessionId) {
1899
+ seen.add(entry.factId);
1900
+ }
1901
+ }
1902
+ return [...seen];
1903
+ }
1904
+ async getProvenanceCredit(workspaceId, terminalIds, lambda, maxHops) {
1905
+ const cap = Math.min(maxHops, 5);
1906
+ const best = /* @__PURE__ */ new Map();
1907
+ for (const start of terminalIds) {
1908
+ const queue = [
1909
+ { id: start, credit: 1, depth: 0, path: /* @__PURE__ */ new Set([start]) }
1910
+ ];
1911
+ while (queue.length) {
1912
+ const { id, credit, depth, path } = queue.shift();
1913
+ if (depth >= cap) continue;
1914
+ const preds = [...this.relations.values()].filter(
1915
+ (r) => r.workspaceId === workspaceId && r.sourceId === id && (r.verb === "derived_from" || r.verb === "part_of")
1916
+ );
1917
+ for (const r of preds) {
1918
+ if (path.has(r.targetId)) continue;
1919
+ const c = credit * lambda;
1920
+ if ((best.get(r.targetId) ?? -1) < c) best.set(r.targetId, c);
1921
+ queue.push({ id: r.targetId, credit: c, depth: depth + 1, path: /* @__PURE__ */ new Set([...path, r.targetId]) });
1922
+ }
1923
+ }
1924
+ }
1925
+ return [...best.entries()].map(([factId, credit]) => ({ factId, credit }));
1926
+ }
1927
+ // ── Audit ─────────────────────────────────────────────────────────────────────
1928
+ async appendAuditEntry(entry) {
1929
+ this.auditLog.push({
1930
+ id: uuid(),
1931
+ createdAt: /* @__PURE__ */ new Date(),
1932
+ ...entry,
1933
+ actorType: resolveAuditActorType(entry)
1934
+ });
1935
+ }
1936
+ async listAuditLog(workspaceId, limit) {
1937
+ const all = this.auditLog.filter((e) => e.workspaceId === workspaceId);
1938
+ return all.slice(-limit);
1939
+ }
1940
+ // ── Outbox ────────────────────────────────────────────────────────────────────
1941
+ async appendOutbox(entry) {
1942
+ this.outbox.push({
1943
+ id: uuid(),
1944
+ createdAt: /* @__PURE__ */ new Date(),
1945
+ attempts: 0,
1946
+ ...entry
1947
+ });
1948
+ }
1949
+ async claimOutbox(limit) {
1950
+ return this.outbox.filter((e) => e.processed !== true).slice(0, limit);
1951
+ }
1952
+ async markOutboxProcessed(ids) {
1953
+ for (const e of this.outbox) {
1954
+ if (ids.includes(e.id)) e.processed = true;
1955
+ }
1956
+ }
1957
+ async markOutboxFailed(id, error) {
1958
+ for (const e of this.outbox) {
1959
+ if (e.id === id) e.lastError = error;
1960
+ }
1961
+ }
1962
+ async reapDeadLetters(maxAttempts) {
1963
+ let count = 0;
1964
+ for (const e of this.outbox) {
1965
+ const entry = e;
1966
+ if (!entry.processed && e.attempts >= maxAttempts) {
1967
+ entry.processed = true;
1968
+ count++;
1969
+ }
1970
+ }
1971
+ return count;
1972
+ }
1973
+ async purgeOutbox(olderThanMs) {
1974
+ const cutoff = new Date(Date.now() - olderThanMs);
1975
+ const before = this.outbox.length;
1976
+ this.outbox = this.outbox.filter((e) => {
1977
+ const entry = e;
1978
+ if (!entry.processed) return true;
1979
+ const processedAt = entry.processedAt ?? /* @__PURE__ */ new Date(0);
1980
+ return processedAt >= cutoff;
1981
+ });
1982
+ return before - this.outbox.length;
1983
+ }
1984
+ async countPendingOutbox() {
1985
+ return this.outbox.filter((e) => e.processed !== true).length;
1986
+ }
1987
+ // ── Webhooks ──────────────────────────────────────────────────────────────────
1988
+ webhookEndpoints = [];
1989
+ webhookDeliveries = [];
1990
+ async createWebhookEndpoint(input) {
1991
+ const now = /* @__PURE__ */ new Date();
1992
+ const endpoint = {
1993
+ id: input.id,
1994
+ workspaceId: input.workspaceId,
1995
+ url: input.url,
1996
+ events: input.events,
1997
+ secretHash: input.secretHash,
1998
+ isActive: true,
1999
+ description: input.description ?? null,
2000
+ failureCount: 0,
2001
+ disabledAt: null,
2002
+ createdAt: now,
2003
+ updatedAt: now
2004
+ };
2005
+ this.webhookEndpoints.push(endpoint);
2006
+ return endpoint;
2007
+ }
2008
+ async getWebhookEndpoint(id, workspaceId) {
2009
+ return this.webhookEndpoints.find((e) => e.id === id && e.workspaceId === workspaceId) ?? null;
2010
+ }
2011
+ async listWebhookEndpoints(workspaceId) {
2012
+ return this.webhookEndpoints.filter((e) => e.workspaceId === workspaceId);
2013
+ }
2014
+ async updateWebhookEndpoint(id, input) {
2015
+ const idx = this.webhookEndpoints.findIndex((e) => e.id === id);
2016
+ if (idx === -1) throw new Error(`Webhook ${id} not found`);
2017
+ const existing = this.webhookEndpoints[idx];
2018
+ const updated = {
2019
+ ...existing,
2020
+ url: input.url ?? existing.url,
2021
+ events: input.events ?? existing.events,
2022
+ isActive: input.isActive ?? existing.isActive,
2023
+ description: input.description !== void 0 ? input.description : existing.description,
2024
+ failureCount: input.failureCount ?? existing.failureCount,
2025
+ disabledAt: input.disabledAt !== void 0 ? input.disabledAt : existing.disabledAt,
2026
+ updatedAt: /* @__PURE__ */ new Date()
2027
+ };
2028
+ this.webhookEndpoints[idx] = updated;
2029
+ return updated;
2030
+ }
2031
+ async deleteWebhookEndpoint(id, workspaceId) {
2032
+ this.webhookEndpoints = this.webhookEndpoints.filter(
2033
+ (e) => !(e.id === id && e.workspaceId === workspaceId)
2034
+ );
2035
+ }
2036
+ async listActiveWebhookEndpoints(workspaceId, eventType) {
2037
+ return this.webhookEndpoints.filter(
2038
+ (e) => e.workspaceId === workspaceId && e.isActive && e.events.includes(eventType)
2039
+ );
2040
+ }
2041
+ async recordWebhookDelivery(entry) {
2042
+ this.webhookDeliveries.push({
2043
+ id: entry.id,
2044
+ webhookId: entry.webhookId,
2045
+ workspaceId: entry.workspaceId,
2046
+ eventType: entry.eventType,
2047
+ payload: entry.payload,
2048
+ status: entry.status,
2049
+ responseStatus: entry.responseStatus ?? null,
2050
+ responseBody: entry.responseBody ?? null,
2051
+ attempt: entry.attempt ?? 1,
2052
+ deliveredAt: entry.deliveredAt ?? null,
2053
+ nextAttemptAt: null,
2054
+ createdAt: /* @__PURE__ */ new Date()
2055
+ });
2056
+ }
2057
+ async listWebhookDeliveries(webhookId, workspaceId, limit = 50) {
2058
+ return this.webhookDeliveries.filter((d) => d.webhookId === webhookId && d.workspaceId === workspaceId).slice(-limit).reverse();
2059
+ }
2060
+ async listPendingWebhookDeliveries(limit) {
2061
+ const now = /* @__PURE__ */ new Date();
2062
+ return this.webhookDeliveries.filter(
2063
+ (d) => d.status === "pending" && (d.nextAttemptAt === null || d.nextAttemptAt <= now)
2064
+ ).slice(0, limit);
2065
+ }
2066
+ async updateWebhookDelivery(id, workspaceId, update) {
2067
+ const idx = this.webhookDeliveries.findIndex(
2068
+ (d) => d.id === id && d.workspaceId === workspaceId
2069
+ );
2070
+ if (idx === -1) return;
2071
+ const existing = this.webhookDeliveries[idx];
2072
+ this.webhookDeliveries[idx] = {
2073
+ ...existing,
2074
+ status: update.status ?? existing.status,
2075
+ responseStatus: update.responseStatus ?? existing.responseStatus,
2076
+ responseBody: update.responseBody ?? existing.responseBody,
2077
+ attempt: update.attempt ?? existing.attempt,
2078
+ deliveredAt: update.deliveredAt !== void 0 ? update.deliveredAt : existing.deliveredAt,
2079
+ nextAttemptAt: update.nextAttemptAt !== void 0 ? update.nextAttemptAt : existing.nextAttemptAt
2080
+ };
2081
+ }
2082
+ // ── Reminders (prospective memory) ────────────────────────────────────────────
2083
+ reminders = [];
2084
+ async createReminder(input) {
2085
+ const now = /* @__PURE__ */ new Date();
2086
+ const reminder = {
2087
+ id: input.id,
2088
+ workspaceId: input.workspaceId,
2089
+ content: input.content,
2090
+ condition: input.condition,
2091
+ triggerAt: input.triggerAt ?? null,
2092
+ status: "pending",
2093
+ conditionEmbedding: input.conditionEmbedding ?? null,
2094
+ triggeredAt: null,
2095
+ dismissedAt: null,
2096
+ createdByAgentId: input.createdByAgentId ?? null,
2097
+ createdAt: now,
2098
+ updatedAt: now
2099
+ };
2100
+ this.reminders.push(reminder);
2101
+ return reminder;
2102
+ }
2103
+ async getReminder(id, workspaceId) {
2104
+ return this.reminders.find((r) => r.id === id && r.workspaceId === workspaceId) ?? null;
2105
+ }
2106
+ async listPendingReminders(workspaceId, asOf) {
2107
+ return this.reminders.filter(
2108
+ (r) => r.workspaceId === workspaceId && r.status === "pending" && (r.triggerAt === null || r.triggerAt <= asOf)
2109
+ );
2110
+ }
2111
+ async dismissReminder(id, workspaceId, newStatus) {
2112
+ const reminder = this.reminders.find((r) => r.id === id && r.workspaceId === workspaceId);
2113
+ if (!reminder) return;
2114
+ const now = /* @__PURE__ */ new Date();
2115
+ reminder.status = newStatus;
2116
+ reminder.updatedAt = now;
2117
+ if (newStatus === "triggered") reminder.triggeredAt = now;
2118
+ if (newStatus === "dismissed") reminder.dismissedAt = now;
2119
+ }
2120
+ async listReminders(workspaceId, status, limit) {
2121
+ return this.reminders.filter(
2122
+ (r) => r.workspaceId === workspaceId && (status === "all" || r.status === status)
2123
+ ).slice(-limit).reverse();
2124
+ }
2125
+ // ── Recall log (ACT-R activation — TASK-4001) ────────────────────────────────
2126
+ mnemoRecallLog = [];
2127
+ async logRecall(workspaceId, memoryId, score) {
2128
+ this.mnemoRecallLog.push({
2129
+ id: uuid(),
2130
+ workspaceId,
2131
+ memoryId,
2132
+ recalledAt: (/* @__PURE__ */ new Date()).toISOString(),
2133
+ recallScore: score
2134
+ });
2135
+ }
2136
+ async getRecallLog(workspaceId, memoryId, limit) {
2137
+ return this.mnemoRecallLog.filter((e) => e.workspaceId === workspaceId && e.memoryId === memoryId).slice(-limit).reverse().map(({ id, recalledAt, recallScore }) => ({ id, recalledAt, recallScore }));
2138
+ }
2139
+ async getRecallLogs(workspaceId, memoryIds, limitPerMemory) {
2140
+ const ids = new Set(memoryIds);
2141
+ const counts = /* @__PURE__ */ new Map();
2142
+ const out = [];
2143
+ for (let index = this.mnemoRecallLog.length - 1; index >= 0; index--) {
2144
+ const entry = this.mnemoRecallLog[index];
2145
+ if (entry.workspaceId !== workspaceId || !ids.has(entry.memoryId)) continue;
2146
+ const count = counts.get(entry.memoryId) ?? 0;
2147
+ if (count >= limitPerMemory) continue;
2148
+ out.push({
2149
+ memoryId: entry.memoryId,
2150
+ id: entry.id,
2151
+ recalledAt: entry.recalledAt,
2152
+ recallScore: entry.recallScore
2153
+ });
2154
+ counts.set(entry.memoryId, count + 1);
2155
+ }
2156
+ return out;
2157
+ }
2158
+ async getRecentQueriesForFacts(workspaceId, factIds, limit) {
2159
+ if (factIds.length === 0) return [];
2160
+ const factIdSet = new Set(factIds);
2161
+ const matching = this.recallLog.filter(
2162
+ (e) => e.workspaceId === workspaceId && factIdSet.has(e.factId) && typeof e.queryText === "string" && e.queryText.trim() !== ""
2163
+ );
2164
+ const seen = /* @__PURE__ */ new Set();
2165
+ const result = [];
2166
+ for (let i = matching.length - 1; i >= 0 && result.length < limit; i--) {
2167
+ const entry = matching[i];
2168
+ const q = entry?.queryText;
2169
+ if (q != null && !seen.has(q)) {
2170
+ seen.add(q);
2171
+ result.push(q);
2172
+ }
2173
+ }
2174
+ return result;
2175
+ }
2176
+ // ── §9 L3 — Query cache (cosine >= threshold) ─────────────────────────────────
2177
+ async lookupQueryCache(workspaceId, embedding, threshold) {
2178
+ const now = Date.now();
2179
+ for (const entry of this.queryCache) {
2180
+ if (entry.workspaceId !== workspaceId) continue;
2181
+ if (entry.expiresAt <= now) continue;
2182
+ const cosine = cosineSimilarity(embedding, entry.embedding);
2183
+ if (cosine >= threshold) {
2184
+ return { resultIds: entry.resultIds, resultKinds: entry.resultKinds };
2185
+ }
2186
+ }
2187
+ return null;
2188
+ }
2189
+ async upsertQueryCache(input) {
2190
+ const now = Date.now();
2191
+ const expiresAt = now + input.ttlMs;
2192
+ const existingIdx = this.queryCache.findIndex(
2193
+ (e) => e.workspaceId === input.workspaceId && cosineSimilarity(e.embedding, input.embedding) >= 0.9999
2194
+ );
2195
+ const entry = {
2196
+ workspaceId: input.workspaceId,
2197
+ embedding: input.embedding,
2198
+ resultIds: input.resultIds,
2199
+ resultKinds: input.resultKinds,
2200
+ expiresAt
2201
+ };
2202
+ if (existingIdx >= 0) {
2203
+ this.queryCache[existingIdx] = entry;
2204
+ } else {
2205
+ this.queryCache.push(entry);
2206
+ }
2207
+ }
2208
+ // ── §9 L3 — Embedding LRU (exact text-hash) ───────────────────────────────────
2209
+ async getCachedEmbedding(workspaceId, textHash) {
2210
+ return this.embeddingCache.get(`${workspaceId}:${textHash}`) ?? null;
2211
+ }
2212
+ async putCachedEmbedding(input) {
2213
+ this.embeddingCache.set(`${input.workspaceId}:${input.textHash}`, input.embedding);
2214
+ }
2215
+ // ── Lifecycle ─────────────────────────────────────────────────────────────────
2216
+ async healthCheck() {
2217
+ return { status: "ok", latencyMs: 0 };
2218
+ }
2219
+ async close() {
2220
+ }
2221
+ async listWorkspaceIds() {
2222
+ const ids = /* @__PURE__ */ new Set();
2223
+ for (const f of this.facts.values()) {
2224
+ if (f.status === "active") ids.add(f.workspaceId);
2225
+ }
2226
+ return [...ids];
2227
+ }
2228
+ // ── RDD-5: Workspace operational mode (in-memory test double) ────────────────
2229
+ async getWorkspaceMode(workspaceId) {
2230
+ const r = this.workspaceModes.get(workspaceId);
2231
+ return r ? { ...r } : null;
2232
+ }
2233
+ async setWorkspaceMode(workspaceId, patch) {
2234
+ const prev = this.workspaceModes.get(workspaceId) ?? {
2235
+ mode: "learning",
2236
+ sessionCount: 0,
2237
+ promoteAt: null,
2238
+ startedAt: /* @__PURE__ */ new Date(),
2239
+ factCount: 0,
2240
+ entityCount: 0
2241
+ };
2242
+ this.workspaceModes.set(workspaceId, {
2243
+ ...prev,
2244
+ ...patch.mode !== void 0 ? { mode: patch.mode } : {},
2245
+ ...patch.sessionCount !== void 0 ? { sessionCount: patch.sessionCount } : {},
2246
+ ...patch.promoteAt !== void 0 ? { promoteAt: patch.promoteAt } : {},
2247
+ ...patch.factCount !== void 0 ? { factCount: patch.factCount } : {},
2248
+ ...patch.entityCount !== void 0 ? { entityCount: patch.entityCount } : {}
2249
+ });
2250
+ }
2251
+ async incrementWorkspaceModeCounters(workspaceId, delta) {
2252
+ const prev = this.workspaceModes.get(workspaceId) ?? {
2253
+ mode: "learning",
2254
+ sessionCount: 0,
2255
+ promoteAt: null,
2256
+ startedAt: /* @__PURE__ */ new Date(),
2257
+ factCount: 0,
2258
+ entityCount: 0
2259
+ };
2260
+ this.workspaceModes.set(workspaceId, {
2261
+ ...prev,
2262
+ sessionCount: prev.sessionCount + (delta.sessionCount ?? 0),
2263
+ factCount: (prev.factCount ?? 0) + (delta.factCount ?? 0),
2264
+ entityCount: (prev.entityCount ?? 0) + (delta.entityCount ?? 0)
2265
+ });
2266
+ }
2267
+ // ── Neuro-dynamics stubs (Wave Y, §25.2/§25.3) ───────────────────────────────
2268
+ async decayKind(_workspaceId, _decayClass, _halfLifeDays) {
2269
+ return 0;
2270
+ }
2271
+ async recordCoRecallStdp(_workspaceId, _relationId, _coRecalledAt) {
2272
+ }
2273
+ async normalizeHebbianWeights(_workspaceId) {
2274
+ return 0;
2275
+ }
2276
+ // ── Wave Y §25.1 — review queue + drift detection stubs ──────────────────────
2277
+ async enqueueReviewItem(_input) {
2278
+ }
2279
+ async queryDriftCandidates(_workspaceId) {
2280
+ return [];
2281
+ }
2282
+ // §36 Embedding-model migration stubs (in-memory always has no stale rows)
2283
+ async listStaleEmbeddings(_table, _workspaceId, _currentModel, _limit) {
2284
+ return [];
2285
+ }
2286
+ async markEmbeddingsStale(_table, _workspaceId, _currentModel) {
2287
+ return 0;
2288
+ }
2289
+ async updateEmbeddingVector(_table, _id, _workspaceId, _vector, _model) {
2290
+ }
2291
+ // §37 Hot-tier snapshot stubs
2292
+ async upsertHotTierSnapshot(_rows) {
2293
+ }
2294
+ async loadHotTierSnapshots(_workspaceId) {
2295
+ return [];
2296
+ }
2297
+ // ── RDD-4: Hybrid dedup gate ──────────────────────────────────────────────────
2298
+ /**
2299
+ * Return distinct topic_keys for facts in a session that were tagged with the
2300
+ * given extraction_source. Used by the hybrid collapse dedup gate.
2301
+ */
2302
+ async listSessionTopicKeysBySource(workspaceId, sessionId, source) {
2303
+ const keys = /* @__PURE__ */ new Set();
2304
+ for (const f of this.facts.values()) {
2305
+ if (f.workspaceId === workspaceId && f.sessionId === sessionId && f.extractionSource === source && f.topicKey) {
2306
+ keys.add(f.topicKey);
2307
+ }
2308
+ }
2309
+ return [...keys];
2310
+ }
2311
+ // ── Test helpers ──────────────────────────────────────────────────────────────
2312
+ /** Clear all data — call between test cases. */
2313
+ reset() {
2314
+ this.sessions.clear();
2315
+ this.turns = [];
2316
+ this.facts.clear();
2317
+ this.decisions.clear();
2318
+ this.episodes.clear();
2319
+ this.entities.clear();
2320
+ this.strategies.clear();
2321
+ this.workflows.clear();
2322
+ this.skills.clear();
2323
+ this.tasks.clear();
2324
+ this.events.clear();
2325
+ this.reasonings.clear();
2326
+ this.relations.clear();
2327
+ this.workspaceModes.clear();
2328
+ this.outbox = [];
2329
+ this.auditLog = [];
2330
+ this.recallLog = [];
2331
+ this.mnemoRecallLog = [];
2332
+ }
2333
+ };
2334
+ function runStorageAdapterContractTests(makeAdapter) {
2335
+ let adapter;
2336
+ beforeEach(async () => {
2337
+ adapter = await makeAdapter();
2338
+ });
2339
+ describe("StorageAdapter contract", () => {
2340
+ it("creates a fact and retrieves it by ID", async () => {
2341
+ const fact = await adapter.createFact({
2342
+ workspaceId: "11111111-1111-1111-1111-111111111111",
2343
+ scope: "global",
2344
+ statement: "Paris is the capital of France",
2345
+ subject: "Paris",
2346
+ kind: "other",
2347
+ confidence: 0.95
2348
+ });
2349
+ expect(fact.id).toBeTruthy();
2350
+ expect(fact.statement).toBe("Paris is the capital of France");
2351
+ expect(fact.confidence).toBe(0.95);
2352
+ const retrieved = await adapter.getFact(fact.id, "11111111-1111-1111-1111-111111111111");
2353
+ expect(retrieved).not.toBeNull();
2354
+ expect(retrieved?.id).toBe(fact.id);
2355
+ });
2356
+ it("returns null when getting a fact that does not exist", async () => {
2357
+ const result = await adapter.getFact("nonexistent-id", "11111111-1111-1111-1111-111111111111");
2358
+ expect(result).toBeNull();
2359
+ });
2360
+ it("updates a fact and reflects the change on retrieval", async () => {
2361
+ const fact = await adapter.createFact({
2362
+ workspaceId: "11111111-1111-1111-1111-111111111111",
2363
+ scope: "global",
2364
+ statement: "Original statement",
2365
+ subject: "test",
2366
+ kind: "other"
2367
+ });
2368
+ const updated = await adapter.updateFact(
2369
+ fact.id,
2370
+ "11111111-1111-1111-1111-111111111111",
2371
+ { confidence: 0.42 }
2372
+ );
2373
+ expect(updated?.confidence).toBe(0.42);
2374
+ const retrieved = await adapter.getFact(fact.id, "11111111-1111-1111-1111-111111111111");
2375
+ expect(retrieved?.confidence).toBe(0.42);
2376
+ });
2377
+ it("returns null and leaves the fact unchanged for a foreign workspace update", async () => {
2378
+ const fact = await adapter.createFact({
2379
+ workspaceId: "bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb",
2380
+ scope: "global",
2381
+ statement: "workspace B statement",
2382
+ subject: "test",
2383
+ kind: "other",
2384
+ confidence: 0.8
2385
+ });
2386
+ const updated = await adapter.updateFact(
2387
+ fact.id,
2388
+ "aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa",
2389
+ { confidence: 0.1 }
2390
+ );
2391
+ expect(updated).toBeNull();
2392
+ const retrieved = await adapter.getFact(fact.id, fact.workspaceId);
2393
+ expect(retrieved?.confidence).toBe(0.8);
2394
+ });
2395
+ it("queryFacts filters by workspaceId", async () => {
2396
+ await adapter.createFact({
2397
+ workspaceId: "aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa",
2398
+ scope: "global",
2399
+ statement: "fact in workspace A",
2400
+ subject: "A",
2401
+ kind: "other"
2402
+ });
2403
+ await adapter.createFact({
2404
+ workspaceId: "bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb",
2405
+ scope: "global",
2406
+ statement: "fact in workspace B",
2407
+ subject: "B",
2408
+ kind: "other"
2409
+ });
2410
+ const { items } = await adapter.queryFacts({ workspaceId: "aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa" });
2411
+ expect(items.every((f) => f.workspaceId === "aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa")).toBe(true);
2412
+ expect(items.some((f) => f.workspaceId === "bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb")).toBe(false);
2413
+ });
2414
+ it("RLS: workspace A cannot read workspace B facts", async () => {
2415
+ const factB = await adapter.createFact({
2416
+ workspaceId: "bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb",
2417
+ scope: "global",
2418
+ statement: "secret fact",
2419
+ subject: "secret",
2420
+ kind: "other"
2421
+ });
2422
+ const cross = await adapter.getFact(factB.id, "aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa");
2423
+ expect(cross).toBeNull();
2424
+ const { items } = await adapter.queryFacts({ workspaceId: "aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa" });
2425
+ expect(items.find((f) => f.id === factB.id)).toBeUndefined();
2426
+ });
2427
+ it("createFact: defaults sensitivity to 'internal' and respects explicit value", async () => {
2428
+ const defaulted = await adapter.createFact({
2429
+ workspaceId: "11111111-1111-1111-1111-111111111111",
2430
+ scope: "global",
2431
+ statement: "sensitivity default check",
2432
+ subject: "test",
2433
+ kind: "other"
2434
+ });
2435
+ expect(defaulted.sensitivity).toBe("internal");
2436
+ const explicit = await adapter.createFact({
2437
+ workspaceId: "11111111-1111-1111-1111-111111111111",
2438
+ scope: "global",
2439
+ statement: "sensitivity explicit check",
2440
+ subject: "test",
2441
+ kind: "other",
2442
+ sensitivity: "public"
2443
+ });
2444
+ expect(explicit.sensitivity).toBe("public");
2445
+ const fetched = await adapter.getFact(explicit.id, explicit.workspaceId);
2446
+ expect(fetched?.sensitivity).toBe("public");
2447
+ });
2448
+ it("worth is a decimal (no integer truncation)", async () => {
2449
+ const fact = await adapter.createFact({
2450
+ workspaceId: "11111111-1111-1111-1111-111111111111",
2451
+ scope: "global",
2452
+ statement: "decimal confidence test",
2453
+ subject: "test",
2454
+ kind: "other",
2455
+ confidence: 0.333
2456
+ });
2457
+ expect(fact.confidence).toBeCloseTo(0.333, 3);
2458
+ });
2459
+ it("outbox entries are observable after fact creation", async () => {
2460
+ const adapterWithOutbox = adapter;
2461
+ if (!Array.isArray(adapterWithOutbox.outbox)) return;
2462
+ const before = adapterWithOutbox.outbox.length;
2463
+ await adapter.createFact({
2464
+ workspaceId: "11111111-1111-1111-1111-111111111111",
2465
+ scope: "global",
2466
+ statement: "outbox test",
2467
+ subject: "test",
2468
+ kind: "other"
2469
+ });
2470
+ expect(adapterWithOutbox.outbox.length).toBeGreaterThan(before);
2471
+ });
2472
+ it("creates and retrieves a decision", async () => {
2473
+ const d = await adapter.createDecision({
2474
+ workspaceId: "11111111-1111-1111-1111-111111111111",
2475
+ kind: "decision",
2476
+ title: "Use Postgres",
2477
+ body: "We chose Postgres because of RLS support."
2478
+ });
2479
+ expect(d.id).toBeTruthy();
2480
+ const retrieved = await adapter.getDecision(d.id, "11111111-1111-1111-1111-111111111111");
2481
+ expect(retrieved?.title).toBe("Use Postgres");
2482
+ });
2483
+ it("creates and retrieves an episode", async () => {
2484
+ const ep = await adapter.createEpisode({
2485
+ workspaceId: "11111111-1111-1111-1111-111111111111",
2486
+ title: "Planning session",
2487
+ narrative: "Discussed the roadmap for Q3.",
2488
+ occurredAt: /* @__PURE__ */ new Date("2026-01-01")
2489
+ });
2490
+ expect(ep.id).toBeTruthy();
2491
+ const retrieved = await adapter.getEpisode(ep.id, "11111111-1111-1111-1111-111111111111");
2492
+ expect(retrieved?.title).toBe("Planning session");
2493
+ });
2494
+ it("creates and retrieves an entity", async () => {
2495
+ const entity = await adapter.createEntity({
2496
+ workspaceId: "11111111-1111-1111-1111-111111111111",
2497
+ name: "Anthropic",
2498
+ kind: "organization"
2499
+ });
2500
+ expect(entity.id).toBeTruthy();
2501
+ const retrieved = await adapter.getEntity(entity.id, "11111111-1111-1111-1111-111111111111");
2502
+ expect(retrieved?.name).toBe("Anthropic");
2503
+ });
2504
+ it("creates a relation and retrieves it by sourceId", async () => {
2505
+ const fact1 = await adapter.createFact({
2506
+ workspaceId: "11111111-1111-1111-1111-111111111111",
2507
+ scope: "global",
2508
+ statement: "A",
2509
+ subject: "A",
2510
+ kind: "other"
2511
+ });
2512
+ const fact2 = await adapter.createFact({
2513
+ workspaceId: "11111111-1111-1111-1111-111111111111",
2514
+ scope: "global",
2515
+ statement: "B",
2516
+ subject: "B",
2517
+ kind: "other"
2518
+ });
2519
+ await adapter.createRelation({
2520
+ workspaceId: "11111111-1111-1111-1111-111111111111",
2521
+ sourceId: fact1.id,
2522
+ sourceType: "fact",
2523
+ targetId: fact2.id,
2524
+ targetType: "fact",
2525
+ verb: "related",
2526
+ weight: 0.7
2527
+ });
2528
+ const relations = await adapter.getRelations({
2529
+ workspaceId: "11111111-1111-1111-1111-111111111111",
2530
+ sourceId: fact1.id
2531
+ });
2532
+ expect(relations.length).toBeGreaterThanOrEqual(1);
2533
+ expect(relations[0]?.verb).toBe("related");
2534
+ });
2535
+ it("records a recall event without throwing", async () => {
2536
+ const fact = await adapter.createFact({
2537
+ workspaceId: "11111111-1111-1111-1111-111111111111",
2538
+ scope: "global",
2539
+ statement: "recalled fact",
2540
+ subject: "test",
2541
+ kind: "other"
2542
+ });
2543
+ await expect(
2544
+ adapter.recordRecall({
2545
+ workspaceId: "11111111-1111-1111-1111-111111111111",
2546
+ factId: fact.id,
2547
+ queryText: "recalled fact",
2548
+ hitRank: 1,
2549
+ tdCredit: 0.1
2550
+ })
2551
+ ).resolves.not.toThrow();
2552
+ });
2553
+ it("paginates queryFacts results", async () => {
2554
+ for (let i = 0; i < 5; i++) {
2555
+ await adapter.createFact({
2556
+ workspaceId: "01010101-0101-0101-0101-010101010101",
2557
+ scope: "global",
2558
+ statement: `fact ${i}`,
2559
+ subject: "pg-test",
2560
+ kind: "other"
2561
+ });
2562
+ }
2563
+ const page1 = await adapter.queryFacts({ workspaceId: "01010101-0101-0101-0101-010101010101", offset: 0, limit: 2 });
2564
+ const page2 = await adapter.queryFacts({ workspaceId: "01010101-0101-0101-0101-010101010101", offset: 2, limit: 2 });
2565
+ expect(page1.items.length).toBe(2);
2566
+ expect(page2.items.length).toBe(2);
2567
+ expect(page1.items[0]?.id).not.toBe(page2.items[0]?.id);
2568
+ });
2569
+ it("healthCheck returns ok or degraded status", async () => {
2570
+ const h = await adapter.healthCheck();
2571
+ expect(["ok", "degraded", "down"]).toContain(h.status);
2572
+ expect(typeof h.latencyMs).toBe("number");
2573
+ });
2574
+ });
2575
+ }
2576
+
2577
+ // src/testing/InMemoryAccessPolicyStore.ts
2578
+ var InMemoryAccessPolicyStore = class {
2579
+ byKey = /* @__PURE__ */ new Map();
2580
+ key(ws, agent) {
2581
+ return `${ws}::${agent}`;
2582
+ }
2583
+ async getPolicy(workspaceId, agentId) {
2584
+ return this.byKey.get(this.key(workspaceId, agentId)) ?? null;
2585
+ }
2586
+ async putPolicy(policy) {
2587
+ this.byKey.set(this.key(policy.workspaceId, policy.agentId), policy);
2588
+ }
2589
+ };
2590
+ var InMemoryApprovalStore = class {
2591
+ byId = /* @__PURE__ */ new Map();
2592
+ async create(input) {
2593
+ const ar = {
2594
+ ...input,
2595
+ id: randomUUID(),
2596
+ status: "pending",
2597
+ createdAt: /* @__PURE__ */ new Date()
2598
+ };
2599
+ this.byId.set(ar.id, ar);
2600
+ return ar;
2601
+ }
2602
+ async get(workspaceId, id) {
2603
+ const ar = this.byId.get(id);
2604
+ return ar && ar.workspaceId === workspaceId ? ar : null;
2605
+ }
2606
+ async resolve(workspaceId, id, status, resolvedBy) {
2607
+ const ar = this.byId.get(id);
2608
+ if (!ar || ar.workspaceId !== workspaceId) throw new Error(`approval ${id} not found`);
2609
+ ar.status = status;
2610
+ ar.resolvedBy = resolvedBy;
2611
+ ar.resolvedAt = /* @__PURE__ */ new Date();
2612
+ }
2613
+ };
2614
+ var InMemoryBreakGlassStore = class {
2615
+ byId = /* @__PURE__ */ new Map();
2616
+ async request(input) {
2617
+ const r = {
2618
+ ...input,
2619
+ id: randomUUID(),
2620
+ status: "pending",
2621
+ createdAt: /* @__PURE__ */ new Date()
2622
+ };
2623
+ this.byId.set(r.id, r);
2624
+ return r;
2625
+ }
2626
+ async approve(workspaceId, id, approverId) {
2627
+ const r = this.byId.get(id);
2628
+ if (!r || r.workspaceId !== workspaceId) throw new Error(`break-glass request ${id} not found`);
2629
+ if (r.requestedBy === approverId) {
2630
+ throw new Error("requester cannot self-approve break-glass request");
2631
+ }
2632
+ if (r.status !== "pending") throw new Error(`break-glass request ${id} is not pending`);
2633
+ r.status = "approved";
2634
+ r.approvedBy = approverId;
2635
+ r.approvedAt = /* @__PURE__ */ new Date();
2636
+ }
2637
+ async get(workspaceId, id) {
2638
+ const r = this.byId.get(id);
2639
+ return r && r.workspaceId === workspaceId ? r : null;
2640
+ }
2641
+ async getActiveApproved(workspaceId, requestedBy) {
2642
+ const now = Date.now();
2643
+ for (const r of this.byId.values()) {
2644
+ if (r.workspaceId === workspaceId && r.requestedBy === requestedBy && r.status === "approved" && r.expiresAt.getTime() > now) {
2645
+ return r;
2646
+ }
2647
+ }
2648
+ return null;
2649
+ }
2650
+ async markUsed(workspaceId, id) {
2651
+ const r = this.byId.get(id);
2652
+ if (!r || r.workspaceId !== workspaceId) throw new Error(`break-glass request ${id} not found`);
2653
+ r.status = "used";
2654
+ r.usedAt = /* @__PURE__ */ new Date();
2655
+ }
2656
+ };
2657
+
2658
+ export { InMemoryAccessPolicyStore, InMemoryApprovalStore, InMemoryBreakGlassStore, InMemoryStorageAdapter, runStorageAdapterContractTests };
2659
+ //# sourceMappingURL=index.js.map
2660
+ //# sourceMappingURL=index.js.map