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