@dsh-ray/assistant-association 0.0.0-stage → 0.2.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.
Files changed (120) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +133 -2
  3. package/cordis.patch.yml +26 -0
  4. package/lib/aho-corasick.d.ts +41 -0
  5. package/lib/aho-corasick.d.ts.map +1 -0
  6. package/lib/aho-corasick.js +352 -0
  7. package/lib/aho-corasick.js.map +1 -0
  8. package/lib/bm25.d.ts +17 -0
  9. package/lib/bm25.d.ts.map +1 -0
  10. package/lib/bm25.js +73 -0
  11. package/lib/bm25.js.map +1 -0
  12. package/lib/clustering.d.ts +161 -0
  13. package/lib/clustering.d.ts.map +1 -0
  14. package/lib/clustering.js +1043 -0
  15. package/lib/clustering.js.map +1 -0
  16. package/lib/config.d.ts +67 -0
  17. package/lib/config.d.ts.map +1 -0
  18. package/lib/config.js +834 -0
  19. package/lib/config.js.map +1 -0
  20. package/lib/cues.d.ts +134 -0
  21. package/lib/cues.d.ts.map +1 -0
  22. package/lib/cues.js +793 -0
  23. package/lib/cues.js.map +1 -0
  24. package/lib/dreaming.d.ts +211 -0
  25. package/lib/dreaming.d.ts.map +1 -0
  26. package/lib/dreaming.js +1418 -0
  27. package/lib/dreaming.js.map +1 -0
  28. package/lib/entities.d.ts +18 -0
  29. package/lib/entities.d.ts.map +1 -0
  30. package/lib/entities.js +111 -0
  31. package/lib/entities.js.map +1 -0
  32. package/lib/eval-pool.d.ts +111 -0
  33. package/lib/eval-pool.d.ts.map +1 -0
  34. package/lib/eval-pool.js +392 -0
  35. package/lib/eval-pool.js.map +1 -0
  36. package/lib/hebbian.d.ts +54 -0
  37. package/lib/hebbian.d.ts.map +1 -0
  38. package/lib/hebbian.js +226 -0
  39. package/lib/hebbian.js.map +1 -0
  40. package/lib/holdout.d.ts +18 -0
  41. package/lib/holdout.d.ts.map +1 -0
  42. package/lib/holdout.js +97 -0
  43. package/lib/holdout.js.map +1 -0
  44. package/lib/hot-path.d.ts +8 -0
  45. package/lib/hot-path.d.ts.map +1 -0
  46. package/lib/hot-path.js +503 -0
  47. package/lib/hot-path.js.map +1 -0
  48. package/lib/hysteresis.d.ts +39 -0
  49. package/lib/hysteresis.d.ts.map +1 -0
  50. package/lib/hysteresis.js +297 -0
  51. package/lib/hysteresis.js.map +1 -0
  52. package/lib/index-memory.d.ts +112 -0
  53. package/lib/index-memory.d.ts.map +1 -0
  54. package/lib/index-memory.js +391 -0
  55. package/lib/index-memory.js.map +1 -0
  56. package/lib/index.d.ts +37 -0
  57. package/lib/index.d.ts.map +1 -0
  58. package/lib/index.js +37 -0
  59. package/lib/index.js.map +1 -0
  60. package/lib/intake-signal.d.ts +158 -0
  61. package/lib/intake-signal.d.ts.map +1 -0
  62. package/lib/intake-signal.js +366 -0
  63. package/lib/intake-signal.js.map +1 -0
  64. package/lib/param-tuning.d.ts +302 -0
  65. package/lib/param-tuning.d.ts.map +1 -0
  66. package/lib/param-tuning.js +1743 -0
  67. package/lib/param-tuning.js.map +1 -0
  68. package/lib/service.d.ts +164 -0
  69. package/lib/service.d.ts.map +1 -0
  70. package/lib/service.js +2071 -0
  71. package/lib/service.js.map +1 -0
  72. package/lib/sources.d.ts +42 -0
  73. package/lib/sources.d.ts.map +1 -0
  74. package/lib/sources.js +2024 -0
  75. package/lib/sources.js.map +1 -0
  76. package/lib/sqlite.d.ts +88 -0
  77. package/lib/sqlite.d.ts.map +1 -0
  78. package/lib/sqlite.js +1815 -0
  79. package/lib/sqlite.js.map +1 -0
  80. package/lib/tokenize.d.ts +4 -0
  81. package/lib/tokenize.d.ts.map +1 -0
  82. package/lib/tokenize.js +35 -0
  83. package/lib/tokenize.js.map +1 -0
  84. package/lib/tools.d.ts +27 -0
  85. package/lib/tools.d.ts.map +1 -0
  86. package/lib/tools.js +126 -0
  87. package/lib/tools.js.map +1 -0
  88. package/lib/types.d.ts +551 -0
  89. package/lib/types.d.ts.map +1 -0
  90. package/lib/types.js +163 -0
  91. package/lib/types.js.map +1 -0
  92. package/lib/version.d.ts +2 -0
  93. package/lib/version.d.ts.map +1 -0
  94. package/lib/version.js +2 -0
  95. package/lib/version.js.map +1 -0
  96. package/lib/web-fetch.d.ts +95 -0
  97. package/lib/web-fetch.d.ts.map +1 -0
  98. package/lib/web-fetch.js +833 -0
  99. package/lib/web-fetch.js.map +1 -0
  100. package/lib/web-learning-interests.d.ts +42 -0
  101. package/lib/web-learning-interests.d.ts.map +1 -0
  102. package/lib/web-learning-interests.js +4344 -0
  103. package/lib/web-learning-interests.js.map +1 -0
  104. package/lib/web-learning-runner.d.ts +43 -0
  105. package/lib/web-learning-runner.d.ts.map +1 -0
  106. package/lib/web-learning-runner.js +322 -0
  107. package/lib/web-learning-runner.js.map +1 -0
  108. package/lib/web-learning-worker.d.ts +75 -0
  109. package/lib/web-learning-worker.d.ts.map +1 -0
  110. package/lib/web-learning-worker.js +367 -0
  111. package/lib/web-learning-worker.js.map +1 -0
  112. package/lib/web-learning.d.ts +161 -0
  113. package/lib/web-learning.d.ts.map +1 -0
  114. package/lib/web-learning.js +912 -0
  115. package/lib/web-learning.js.map +1 -0
  116. package/lib/write-queue.d.ts +42 -0
  117. package/lib/write-queue.d.ts.map +1 -0
  118. package/lib/write-queue.js +439 -0
  119. package/lib/write-queue.js.map +1 -0
  120. package/package.json +156 -3
@@ -0,0 +1,1418 @@
1
+ import { createHash } from 'node:crypto';
2
+ import { extractEntities } from './entities.js';
3
+ import { normalizeEntityKey, tokenizeAssociationText } from './tokenize.js';
4
+ import { computeDeterministicEdgeId, } from './types.js';
5
+ export const DEFAULT_ASSOCIATION_DREAMING_CONFIG = Object.freeze({
6
+ enabled: true,
7
+ intervalMs: 3_600_000,
8
+ idleMinMs: 1_800_000,
9
+ maxPairsPerRun: 16,
10
+ maxAbstractionsPerRun: 4,
11
+ maxSynonymsPerRun: 16,
12
+ nodeTtlMs: 30 * 86_400_000,
13
+ allowModelSynthesis: false,
14
+ });
15
+ export function normalizeAssociationDreamingConfig(raw) {
16
+ const intervalMs = typeof raw?.intervalMs === 'number' && Number.isFinite(raw.intervalMs) && raw.intervalMs >= 0
17
+ ? Math.floor(raw.intervalMs)
18
+ : DEFAULT_ASSOCIATION_DREAMING_CONFIG.intervalMs;
19
+ const idleMinMs = typeof raw?.idleMinMs === 'number' && Number.isFinite(raw.idleMinMs) && raw.idleMinMs >= 0
20
+ ? Math.floor(raw.idleMinMs)
21
+ : DEFAULT_ASSOCIATION_DREAMING_CONFIG.idleMinMs;
22
+ const maxPairsPerRun = typeof raw?.maxPairsPerRun === 'number' &&
23
+ Number.isFinite(raw.maxPairsPerRun) &&
24
+ raw.maxPairsPerRun >= 0
25
+ ? Math.floor(raw.maxPairsPerRun)
26
+ : DEFAULT_ASSOCIATION_DREAMING_CONFIG.maxPairsPerRun;
27
+ const maxAbstractionsPerRun = typeof raw?.maxAbstractionsPerRun === 'number' &&
28
+ Number.isFinite(raw.maxAbstractionsPerRun) &&
29
+ raw.maxAbstractionsPerRun >= 0
30
+ ? Math.floor(raw.maxAbstractionsPerRun)
31
+ : DEFAULT_ASSOCIATION_DREAMING_CONFIG.maxAbstractionsPerRun;
32
+ const maxSynonymsPerRun = typeof raw?.maxSynonymsPerRun === 'number' &&
33
+ Number.isFinite(raw.maxSynonymsPerRun) &&
34
+ raw.maxSynonymsPerRun >= 0
35
+ ? Math.floor(raw.maxSynonymsPerRun)
36
+ : DEFAULT_ASSOCIATION_DREAMING_CONFIG.maxSynonymsPerRun;
37
+ const nodeTtlMs = typeof raw?.nodeTtlMs === 'number' && Number.isFinite(raw.nodeTtlMs) && raw.nodeTtlMs >= 0
38
+ ? Math.floor(raw.nodeTtlMs)
39
+ : DEFAULT_ASSOCIATION_DREAMING_CONFIG.nodeTtlMs;
40
+ const normalized = {
41
+ enabled: raw?.enabled ?? DEFAULT_ASSOCIATION_DREAMING_CONFIG.enabled,
42
+ intervalMs,
43
+ idleMinMs,
44
+ maxPairsPerRun,
45
+ maxAbstractionsPerRun,
46
+ maxSynonymsPerRun,
47
+ nodeTtlMs,
48
+ allowModelSynthesis: raw?.allowModelSynthesis === true,
49
+ ...(typeof raw?.budgetId === 'string' && raw.budgetId.length > 0
50
+ ? { budgetId: raw.budgetId }
51
+ : {}),
52
+ ...(typeof raw?.budgetAmount === 'number' &&
53
+ Number.isFinite(raw.budgetAmount) &&
54
+ raw.budgetAmount > 0
55
+ ? { budgetAmount: raw.budgetAmount }
56
+ : {}),
57
+ };
58
+ return Object.freeze(normalized);
59
+ }
60
+ const TOKEN_STOPWORDS = new Set([
61
+ 'the',
62
+ 'and',
63
+ 'for',
64
+ 'with',
65
+ 'that',
66
+ 'this',
67
+ 'from',
68
+ 'into',
69
+ 'your',
70
+ 'have',
71
+ 'will',
72
+ 'are',
73
+ 'was',
74
+ 'were',
75
+ 'not',
76
+ 'but',
77
+ 'can',
78
+ 'use',
79
+ 'used',
80
+ 'using',
81
+ 'when',
82
+ 'what',
83
+ 'which',
84
+ 'where',
85
+ 'how',
86
+ 'all',
87
+ 'any',
88
+ 'has',
89
+ 'had',
90
+ 'been',
91
+ 'true',
92
+ 'false',
93
+ 'null',
94
+ 'undefined',
95
+ 'about',
96
+ 'also',
97
+ 'than',
98
+ 'then',
99
+ 'them',
100
+ 'they',
101
+ 'their',
102
+ 'there',
103
+ 'here',
104
+ 'more',
105
+ 'some',
106
+ 'only',
107
+ 'other',
108
+ 'such',
109
+ 'each',
110
+ 'into',
111
+ 'over',
112
+ ]);
113
+ const CJK_CHAR_RE = /[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Hangul}]/u;
114
+ const PARENTHETICAL_ALIAS_RE = /([A-Za-z0-9\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Hangul}][A-Za-z0-9\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Hangul} _./:-]{1,64}?)\s*[((]\s*([A-Za-z0-9\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Hangul}][A-Za-z0-9\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Hangul} _./:-]{1,48}?)\s*[))]/gu;
115
+ const CAMEL_CASE_RE = /\b([A-Za-z][a-z0-9]+(?:[A-Z][A-Za-z0-9]*)+)\b/gu;
116
+ function sha256Hex(value) {
117
+ return createHash('sha256').update(value, 'utf8').digest('hex');
118
+ }
119
+ export function computeDreamSynonymId(ownerScopeKey, surface, canonicalEntity) {
120
+ return `syn-${sha256Hex(`${ownerScopeKey}\0${surface}\0${canonicalEntity}`).slice(0, 24)}`;
121
+ }
122
+ export function computeAbstractionNodeId(ownerScopeKey, memberNodeIds, sharedConcepts) {
123
+ const scope8 = ownerScopeKey.slice(0, 8);
124
+ const sortedMembers = [...memberNodeIds].sort();
125
+ const sortedConcepts = [...sharedConcepts].sort();
126
+ const digest = sha256Hex(`abstraction\0${ownerScopeKey}\0${sortedMembers.join('\0')}\0${sortedConcepts.join('\0')}`).slice(0, 20);
127
+ return `a:abs-${scope8}-${digest}`;
128
+ }
129
+ function clampWeight(value, weightMin, weightMax) {
130
+ const lo = Math.max(0.0, Math.min(10.0, weightMin));
131
+ const hi = Math.max(lo, Math.min(10.0, weightMax));
132
+ if (!Number.isFinite(value))
133
+ return lo;
134
+ return Math.min(hi, Math.max(lo, value));
135
+ }
136
+ function compactText(raw, maxChars) {
137
+ const collapsed = raw.normalize('NFKC').replace(/\s+/gu, ' ').trim();
138
+ if (collapsed.length <= maxChars)
139
+ return collapsed;
140
+ const chars = [...collapsed];
141
+ if (chars.length <= maxChars)
142
+ return collapsed;
143
+ return `${chars.slice(0, Math.max(0, maxChars - 1)).join('')}…`;
144
+ }
145
+ function hasTable(db, tableName) {
146
+ const row = db
147
+ .prepare("SELECT 1 AS ok FROM sqlite_master WHERE type = 'table' AND name = ?")
148
+ .get(tableName);
149
+ return row !== undefined;
150
+ }
151
+ export function ensureDreamingSchema(db) {
152
+ db.exec(`
153
+ CREATE TABLE IF NOT EXISTS assoc_dream_runs (
154
+ run_id TEXT PRIMARY KEY,
155
+ owner_scope_key TEXT NOT NULL,
156
+ status TEXT NOT NULL,
157
+ edges_created INTEGER NOT NULL DEFAULT 0,
158
+ abstractions_created INTEGER NOT NULL DEFAULT 0,
159
+ synonyms_created INTEGER NOT NULL DEFAULT 0,
160
+ ran_at INTEGER NOT NULL
161
+ ) STRICT;
162
+ CREATE INDEX IF NOT EXISTS assoc_dream_runs_scope_time
163
+ ON assoc_dream_runs(owner_scope_key, ran_at DESC);
164
+ `);
165
+ }
166
+ function buildDreamingPolicyRequest(scope) {
167
+ return {
168
+ subject: {
169
+ kind: 'background',
170
+ id: 'assistant-association:dreaming',
171
+ workspace: scope.workspace,
172
+ principal: scope.principalId,
173
+ },
174
+ action: 'dream.build',
175
+ resource: {
176
+ kind: 'evolution',
177
+ id: 'assistant-association:dreaming',
178
+ },
179
+ context: {
180
+ initiator: 'background',
181
+ },
182
+ };
183
+ }
184
+ function inferLastScopeActivityAt(db, ownerScopeKey) {
185
+ let latest = null;
186
+ if (hasTable(db, 'assoc_step_metrics')) {
187
+ const stepRow = db
188
+ .prepare('SELECT MAX(occurred_at) AS ts FROM assoc_step_metrics WHERE owner_scope_key = ?')
189
+ .get(ownerScopeKey);
190
+ if (typeof stepRow?.ts === 'number' && Number.isFinite(stepRow.ts)) {
191
+ latest = stepRow.ts;
192
+ }
193
+ }
194
+ if (hasTable(db, 'assoc_nodes')) {
195
+ const nodeRow = db
196
+ .prepare(`
197
+ SELECT MAX(updated_at) AS ts
198
+ FROM assoc_nodes
199
+ WHERE owner_scope_key = ?
200
+ AND status = 'active'
201
+ AND kind NOT IN ('dream', 'abstraction', 'web')
202
+ `)
203
+ .get(ownerScopeKey);
204
+ if (typeof nodeRow?.ts === 'number' && Number.isFinite(nodeRow.ts)) {
205
+ latest = latest === null ? nodeRow.ts : Math.max(latest, nodeRow.ts);
206
+ }
207
+ }
208
+ return latest;
209
+ }
210
+ function evaluateDreamingGate(input, mode, idempotencyKey) {
211
+ const nowMs = input.nowMs ?? Date.now();
212
+ if (!input.config.enabled) {
213
+ return { allowed: false, reason: 'disabled' };
214
+ }
215
+ if (input.policy?.getEmergencyStop?.()?.enabled === true) {
216
+ return { allowed: false, reason: 'emergency-stop' };
217
+ }
218
+ // Evaluate cheap, side-effect-free local readiness gates before calling
219
+ // side-effecting policy.authorize() or delivery route checks.
220
+ if (input.db !== undefined &&
221
+ input.config.intervalMs > 0 &&
222
+ hasTable(input.db, 'assoc_dream_runs')) {
223
+ const row = input.db
224
+ .prepare("SELECT MAX(ran_at) AS last_ran_at FROM assoc_dream_runs WHERE owner_scope_key = ? AND status = 'completed'")
225
+ .get(input.scope.ownerScopeKey);
226
+ if (typeof row?.last_ran_at === 'number' &&
227
+ Number.isFinite(row.last_ran_at) &&
228
+ nowMs - row.last_ran_at < input.config.intervalMs) {
229
+ return { allowed: false, reason: 'interval-not-elapsed' };
230
+ }
231
+ }
232
+ if (input.hasRunningAgent === true) {
233
+ return { allowed: false, reason: 'agent-active' };
234
+ }
235
+ const lastActivityAt = input.lastActivityAt !== undefined
236
+ ? input.lastActivityAt
237
+ : input.db !== undefined
238
+ ? inferLastScopeActivityAt(input.db, input.scope.ownerScopeKey)
239
+ : null;
240
+ if (lastActivityAt === null ||
241
+ !Number.isFinite(lastActivityAt) ||
242
+ nowMs - lastActivityAt < input.config.idleMinMs) {
243
+ return { allowed: false, reason: 'not-idle' };
244
+ }
245
+ const requirePolicy = input.requirePolicy ?? true;
246
+ if (requirePolicy && input.policy === undefined) {
247
+ return { allowed: false, reason: 'policy-unavailable' };
248
+ }
249
+ if (input.config.budgetId !== undefined) {
250
+ if (typeof input.policy?.getBudgetConfig !== 'function') {
251
+ return { allowed: false, reason: 'budget-unavailable' };
252
+ }
253
+ const budget = input.policy.getBudgetConfig(input.config.budgetId);
254
+ const requiredAmount = input.config.budgetAmount ?? 1;
255
+ if (budget === undefined || !Number.isFinite(budget.limit) || budget.limit < requiredAmount) {
256
+ return { allowed: false, reason: 'budget-unavailable' };
257
+ }
258
+ }
259
+ if (input.scope.mode === 'delivery' && input.delivery !== undefined) {
260
+ const authorityId = input.scope.authorityId;
261
+ if (typeof input.delivery.validateOwnerRoute === 'function') {
262
+ if (typeof authorityId !== 'string' || authorityId.length === 0) {
263
+ return { allowed: false, reason: 'route-invalid' };
264
+ }
265
+ try {
266
+ input.delivery.validateOwnerRoute({
267
+ authorityId,
268
+ principalId: input.scope.principalId,
269
+ workspace: input.scope.workspace,
270
+ agentPreset: input.scope.agentPreset,
271
+ });
272
+ }
273
+ catch {
274
+ return { allowed: false, reason: 'route-invalid' };
275
+ }
276
+ }
277
+ if (typeof input.delivery.inspectOwnerRouteState === 'function') {
278
+ if (typeof authorityId !== 'string' || authorityId.length === 0) {
279
+ return { allowed: false, reason: 'route-invalid' };
280
+ }
281
+ try {
282
+ const routeState = input.delivery.inspectOwnerRouteState({
283
+ authorityId,
284
+ principalId: input.scope.principalId,
285
+ workspace: input.scope.workspace,
286
+ agentPreset: input.scope.agentPreset,
287
+ });
288
+ const status = typeof routeState === 'string' ? routeState : routeState?.status;
289
+ if (status !== 'active') {
290
+ return { allowed: false, reason: 'route-inactive' };
291
+ }
292
+ }
293
+ catch {
294
+ return { allowed: false, reason: 'route-invalid' };
295
+ }
296
+ }
297
+ }
298
+ if (input.policy !== undefined) {
299
+ const request = buildDreamingPolicyRequest(input.scope);
300
+ let decision;
301
+ if (mode === 'execute') {
302
+ if (typeof input.policy.authorize === 'function') {
303
+ const resolvedIdempotencyKey = typeof idempotencyKey === 'function' ? idempotencyKey() : idempotencyKey;
304
+ decision = input.policy.authorize(request, resolvedIdempotencyKey === undefined
305
+ ? undefined
306
+ : { idempotencyKey: resolvedIdempotencyKey });
307
+ }
308
+ else if (typeof input.policy.evaluate === 'function') {
309
+ decision = input.policy.evaluate(request);
310
+ }
311
+ }
312
+ else {
313
+ if (typeof input.policy.evaluate === 'function') {
314
+ decision = input.policy.evaluate(request);
315
+ }
316
+ else if (typeof input.policy.authorize === 'function') {
317
+ decision = input.policy.authorize(request);
318
+ }
319
+ }
320
+ if (decision === undefined) {
321
+ if (requirePolicy) {
322
+ return { allowed: false, reason: 'policy-unavailable' };
323
+ }
324
+ }
325
+ else if (decision.effect !== 'allow') {
326
+ return {
327
+ allowed: false,
328
+ reason: 'policy-denied',
329
+ ...(decision.reasonCode !== undefined ? { policyReasonCode: decision.reasonCode } : {}),
330
+ };
331
+ }
332
+ }
333
+ return { allowed: true, reason: 'ok' };
334
+ }
335
+ export function canRunDreaming(input) {
336
+ return evaluateDreamingGate(input, 'dry-check');
337
+ }
338
+ function loadCandidateNodes(db, ownerScopeKey, nowMs, limit) {
339
+ const rows = db
340
+ .prepare(`
341
+ SELECT id, kind, source_plugin, source_ref, source_version,
342
+ owner_scope_key, owner_mode, principal_digest, principal_record_id, principal_version,
343
+ scope_mode, workspace, agent_preset, trust, sensitivity,
344
+ title, body, entities_json, tokens_json, metadata_json,
345
+ status, created_at, updated_at
346
+ FROM assoc_nodes
347
+ WHERE status = 'active'
348
+ AND owner_scope_key = ?
349
+ AND sensitivity = 'private'
350
+ AND kind NOT IN ('dream', 'abstraction', 'web')
351
+ AND (expires_at IS NULL OR expires_at > ?)
352
+ ORDER BY updated_at DESC, id ASC
353
+ LIMIT ?
354
+ `)
355
+ .all(ownerScopeKey, nowMs, limit);
356
+ return rows.map((row) => ({
357
+ id: row.id,
358
+ kind: row.kind,
359
+ sourcePlugin: row.source_plugin,
360
+ sourceRef: row.source_ref,
361
+ sourceVersion: row.source_version,
362
+ ownerScopeKey: row.owner_scope_key,
363
+ ownerMode: row.owner_mode,
364
+ principalDigest: row.principal_digest,
365
+ principalRecordId: row.principal_record_id,
366
+ principalVersion: row.principal_version,
367
+ scopeMode: row.scope_mode,
368
+ workspace: row.workspace,
369
+ agentPreset: row.agent_preset,
370
+ trust: row.trust,
371
+ sensitivity: row.sensitivity,
372
+ title: row.title,
373
+ body: row.body,
374
+ entities: JSON.parse(row.entities_json),
375
+ tokens: JSON.parse(row.tokens_json),
376
+ metadata: JSON.parse(row.metadata_json),
377
+ status: row.status,
378
+ createdAt: row.created_at,
379
+ updatedAt: row.updated_at,
380
+ }));
381
+ }
382
+ function isSignificantToken(token) {
383
+ if (TOKEN_STOPWORDS.has(token))
384
+ return false;
385
+ if (CJK_CHAR_RE.test(token)) {
386
+ return [...token].length >= 2;
387
+ }
388
+ return token.length >= 3;
389
+ }
390
+ function pairKey(aId, bId) {
391
+ return aId <= bId ? `${aId}\0${bId}` : `${bId}\0${aId}`;
392
+ }
393
+ function loadExistingGraphNeighborhood(db, nodeIds) {
394
+ const connectedPairs = new Set();
395
+ const neighborsByNode = new Map();
396
+ if (nodeIds.length === 0) {
397
+ return { connectedPairs, neighborsByNode };
398
+ }
399
+ const nodeSet = new Set(nodeIds);
400
+ const placeholders = nodeIds.map(() => '?').join(',');
401
+ const edges = db
402
+ .prepare(`
403
+ SELECT e.a_id, e.b_id
404
+ FROM assoc_edges e
405
+ JOIN assoc_nodes a ON a.id = e.a_id AND a.status = 'active'
406
+ JOIN assoc_nodes b ON b.id = e.b_id AND b.status = 'active'
407
+ WHERE e.a_id IN (${placeholders}) OR e.b_id IN (${placeholders})
408
+ `)
409
+ .all(...nodeIds, ...nodeIds);
410
+ for (const edge of edges) {
411
+ if (nodeSet.has(edge.a_id) && nodeSet.has(edge.b_id)) {
412
+ connectedPairs.add(pairKey(edge.a_id, edge.b_id));
413
+ }
414
+ let aNeighbors = neighborsByNode.get(edge.a_id);
415
+ if (aNeighbors === undefined) {
416
+ aNeighbors = new Set();
417
+ neighborsByNode.set(edge.a_id, aNeighbors);
418
+ }
419
+ aNeighbors.add(edge.b_id);
420
+ let bNeighbors = neighborsByNode.get(edge.b_id);
421
+ if (bNeighbors === undefined) {
422
+ bNeighbors = new Set();
423
+ neighborsByNode.set(edge.b_id, bNeighbors);
424
+ }
425
+ bNeighbors.add(edge.a_id);
426
+ }
427
+ return { connectedPairs, neighborsByNode };
428
+ }
429
+ function synthesizeLongRangeDreamEdges(nodes, connectedPairs, neighborsByNode, maxPairs, wMin, wMax, nowMs) {
430
+ if (maxPairs <= 0 || nodes.length < 2) {
431
+ return { edges: [], derivedRefs: [] };
432
+ }
433
+ const df = new Map();
434
+ const sigTokenSets = nodes.map((node) => {
435
+ const set = new Set();
436
+ for (const tok of node.tokens) {
437
+ if (isSignificantToken(tok))
438
+ set.add(tok);
439
+ }
440
+ for (const tok of set) {
441
+ df.set(tok, (df.get(tok) ?? 0) + 1);
442
+ }
443
+ return set;
444
+ });
445
+ const entitySets = nodes.map((node) => new Set(node.entities));
446
+ const idf = (tok) => Math.log((nodes.length + 1) / ((df.get(tok) ?? 0) + 1)) + 1;
447
+ const candidates = [];
448
+ for (let i = 0; i < nodes.length; i += 1) {
449
+ const a = nodes[i];
450
+ const aTokens = sigTokenSets[i];
451
+ const aEntities = entitySets[i];
452
+ const aNeighbors = neighborsByNode.get(a.id);
453
+ for (let j = i + 1; j < nodes.length; j += 1) {
454
+ const b = nodes[j];
455
+ if (connectedPairs.has(pairKey(a.id, b.id)))
456
+ continue;
457
+ const bTokens = sigTokenSets[j];
458
+ const bEntities = entitySets[j];
459
+ const bNeighbors = neighborsByNode.get(b.id);
460
+ const sharedTokens = [];
461
+ let sharedIdfSum = 0;
462
+ let unionIdfSum = 0;
463
+ for (const tok of aTokens) {
464
+ const w = idf(tok);
465
+ unionIdfSum += w;
466
+ if (bTokens.has(tok)) {
467
+ sharedTokens.push(tok);
468
+ sharedIdfSum += w;
469
+ }
470
+ }
471
+ for (const tok of bTokens) {
472
+ if (!aTokens.has(tok))
473
+ unionIdfSum += idf(tok);
474
+ }
475
+ const tokenSim = unionIdfSum > 0 ? sharedIdfSum / unionIdfSum : 0;
476
+ const sharedEntities = [];
477
+ for (const ent of aEntities) {
478
+ if (bEntities.has(ent))
479
+ sharedEntities.push(ent);
480
+ }
481
+ let sharedBridges = 0;
482
+ if (aNeighbors !== undefined && bNeighbors !== undefined) {
483
+ for (const neighbor of aNeighbors) {
484
+ if (neighbor !== a.id && neighbor !== b.id && bNeighbors.has(neighbor)) {
485
+ sharedBridges += 1;
486
+ }
487
+ }
488
+ }
489
+ const qualifies = (sharedTokens.length >= 2 && tokenSim >= 0.12) ||
490
+ (sharedEntities.length >= 1 && tokenSim >= 0.08) ||
491
+ (sharedBridges >= 1 && (sharedTokens.length >= 1 || sharedEntities.length >= 1));
492
+ if (!qualifies)
493
+ continue;
494
+ const bridgeBoost = 0.18 * Math.min(2, sharedBridges);
495
+ const entityBoost = 0.12 * Math.min(3, sharedEntities.length);
496
+ const rawScore = Math.min(1.0, tokenSim + bridgeBoost + entityBoost);
497
+ const mappedWeight = 0.30 + 0.35 * Math.min(1.0, rawScore);
498
+ const weight = clampWeight(mappedWeight, wMin, wMax);
499
+ const [left, right] = a.id <= b.id ? [a, b] : [b, a];
500
+ const edgeId = computeDeterministicEdgeId(left.id, right.id, 'dream');
501
+ const basisTokens = (sharedEntities.length > 0 ? sharedEntities : sharedTokens)
502
+ .slice(0, 3)
503
+ .join(',');
504
+ const basis = sharedBridges > 0
505
+ ? `bridge+${basisTokens || 'concept'}`
506
+ : basisTokens || 'concept';
507
+ candidates.push({
508
+ a: left,
509
+ b: right,
510
+ edgeId,
511
+ rawScore,
512
+ weight,
513
+ basis,
514
+ });
515
+ }
516
+ }
517
+ candidates.sort((x, y) => {
518
+ if (y.rawScore !== x.rawScore)
519
+ return y.rawScore - x.rawScore;
520
+ const xRecency = Math.max(x.a.updatedAt, x.b.updatedAt);
521
+ const yRecency = Math.max(y.a.updatedAt, y.b.updatedAt);
522
+ if (yRecency !== xRecency)
523
+ return yRecency - xRecency;
524
+ return x.edgeId.localeCompare(y.edgeId);
525
+ });
526
+ const edges = [];
527
+ const derivedRefs = [];
528
+ const limit = Math.min(maxPairs, candidates.length);
529
+ for (let i = 0; i < limit; i += 1) {
530
+ const item = candidates[i];
531
+ edges.push({
532
+ edgeId: item.edgeId,
533
+ aId: item.a.id,
534
+ bId: item.b.id,
535
+ edgeType: 'dream',
536
+ weight: item.weight,
537
+ trust: 'low',
538
+ reason: `dream:${item.basis}`.slice(0, 256),
539
+ createdAt: nowMs,
540
+ updatedAt: nowMs,
541
+ });
542
+ derivedRefs.push({
543
+ sourceNodeId: item.a.id,
544
+ sourceVersion: item.a.sourceVersion,
545
+ targetKind: 'edge',
546
+ targetId: item.edgeId,
547
+ }, {
548
+ sourceNodeId: item.b.id,
549
+ sourceVersion: item.b.sourceVersion,
550
+ targetKind: 'edge',
551
+ targetId: item.edgeId,
552
+ });
553
+ }
554
+ return { edges, derivedRefs };
555
+ }
556
+ function synthesizeAbstractionClusters(db, scope, nodes, maxAbstractions, nodeTtlMs, wMin, wMax, nowMs) {
557
+ if (maxAbstractions <= 0 || nodes.length < 2) {
558
+ return { nodes: [], edges: [], derivedRefs: [] };
559
+ }
560
+ const conceptSets = nodes.map((node) => {
561
+ const set = new Set();
562
+ for (const ent of node.entities) {
563
+ const normalized = normalizeEntityKey(ent);
564
+ if (normalized !== null && !TOKEN_STOPWORDS.has(normalized))
565
+ set.add(normalized);
566
+ }
567
+ for (const tok of node.tokens) {
568
+ if (isSignificantToken(tok))
569
+ set.add(tok);
570
+ }
571
+ return set;
572
+ });
573
+ const entitySets = nodes.map((node) => new Set(node.entities));
574
+ const seedClusters = [];
575
+ const seenSignatures = new Set();
576
+ for (let i = 0; i < nodes.length; i += 1) {
577
+ const a = nodes[i];
578
+ const aConcepts = conceptSets[i];
579
+ const aEntities = entitySets[i];
580
+ for (let j = i + 1; j < nodes.length; j += 1) {
581
+ const b = nodes[j];
582
+ const bConcepts = conceptSets[j];
583
+ const bEntities = entitySets[j];
584
+ const sharedEntities = [];
585
+ for (const ent of aEntities) {
586
+ if (bEntities.has(ent))
587
+ sharedEntities.push(ent);
588
+ }
589
+ const sharedConcepts = [];
590
+ for (const c of aConcepts) {
591
+ if (bConcepts.has(c))
592
+ sharedConcepts.push(c);
593
+ }
594
+ if (sharedConcepts.length < 2)
595
+ continue;
596
+ const members = [a, b];
597
+ const coreSet = new Set(sharedConcepts);
598
+ for (let k = 0; k < nodes.length && members.length < 6; k += 1) {
599
+ if (k === i || k === j)
600
+ continue;
601
+ const c = nodes[k];
602
+ const cConcepts = conceptSets[k];
603
+ let overlap = 0;
604
+ for (const sc of coreSet) {
605
+ if (cConcepts.has(sc))
606
+ overlap += 1;
607
+ }
608
+ if (overlap >= 2) {
609
+ members.push(c);
610
+ }
611
+ }
612
+ const finalShared = [...coreSet]
613
+ .filter((concept) => members.every((_, idx) => {
614
+ const nodeIdx = nodes.indexOf(members[idx]);
615
+ return nodeIdx >= 0 && conceptSets[nodeIdx].has(concept);
616
+ }))
617
+ .sort();
618
+ if (finalShared.length < 2)
619
+ continue;
620
+ const sortedMemberIds = members.map((m) => m.id).sort();
621
+ const signature = `${sortedMemberIds.join('\0')}|${finalShared.slice(0, 8).join('\0')}`;
622
+ if (seenSignatures.has(signature))
623
+ continue;
624
+ seenSignatures.add(signature);
625
+ const score = finalShared.length + sharedEntities.length * 1.5 + members.length * 0.5;
626
+ seedClusters.push({
627
+ members: [...members].sort((x, y) => x.id.localeCompare(y.id)),
628
+ sharedConcepts: finalShared.slice(0, 8),
629
+ score,
630
+ });
631
+ }
632
+ }
633
+ seedClusters.sort((x, y) => {
634
+ if (y.score !== x.score)
635
+ return y.score - x.score;
636
+ if (y.members.length !== x.members.length)
637
+ return y.members.length - x.members.length;
638
+ return x.members[0].id.localeCompare(y.members[0].id);
639
+ });
640
+ const checkExistingNode = db.prepare("SELECT 1 AS ok FROM assoc_nodes WHERE id = ? AND status = 'active'");
641
+ const absNodes = [];
642
+ const absEdges = [];
643
+ const derivedRefs = [];
644
+ const usedMemberPairs = new Set();
645
+ for (const cluster of seedClusters) {
646
+ if (absNodes.length >= maxAbstractions)
647
+ break;
648
+ const memberIds = cluster.members.map((m) => m.id);
649
+ const primaryPair = pairKey(memberIds[0], memberIds[1]);
650
+ if (usedMemberPairs.has(primaryPair))
651
+ continue;
652
+ const absId = computeAbstractionNodeId(scope.ownerScopeKey, memberIds, cluster.sharedConcepts);
653
+ if (checkExistingNode.get(absId) !== undefined)
654
+ continue;
655
+ usedMemberPairs.add(primaryPair);
656
+ const labelConcepts = cluster.sharedConcepts.slice(0, 4).join(', ');
657
+ const title = compactText(`Abstraction: ${labelConcepts}`, 160);
658
+ const body = compactText(`Bridging abstraction across ${cluster.members.length} sources (${cluster.members.map((m) => m.title).slice(0, 4).join('; ')}) sharing concepts: ${cluster.sharedConcepts.join(', ')}.`, 1024);
659
+ const tokens = tokenizeAssociationText(`${title} ${body}`);
660
+ const expiresAt = nodeTtlMs > 0 ? nowMs + nodeTtlMs : null;
661
+ const sourceRefSuffix = absId.slice(`a:abs-${scope.ownerScopeKey.slice(0, 8)}-`.length);
662
+ absNodes.push({
663
+ id: absId,
664
+ kind: 'abstraction',
665
+ sourcePlugin: 'assistant-association',
666
+ sourceRef: `abstraction:${sourceRefSuffix}`,
667
+ sourceVersion: 1,
668
+ ownerScopeKey: scope.ownerScopeKey,
669
+ ownerMode: scope.mode,
670
+ principalDigest: scope.principalDigest,
671
+ principalRecordId: scope.principalRecordId,
672
+ principalVersion: scope.principalVersion,
673
+ scopeMode: 'workspace',
674
+ workspace: scope.workspace,
675
+ agentPreset: scope.agentPreset,
676
+ trust: 'low',
677
+ sensitivity: 'private',
678
+ title,
679
+ body,
680
+ entities: cluster.sharedConcepts,
681
+ tokens,
682
+ metadata: {
683
+ extra: {
684
+ supportingNodeIds: memberIds,
685
+ sharedConcepts: cluster.sharedConcepts,
686
+ },
687
+ },
688
+ ttlMs: nodeTtlMs > 0 ? nodeTtlMs : null,
689
+ expiresAt,
690
+ status: 'active',
691
+ createdAt: nowMs,
692
+ updatedAt: nowMs,
693
+ });
694
+ const edgeWeight = clampWeight(0.45 + 0.05 * Math.min(4, cluster.sharedConcepts.length), wMin, wMax);
695
+ const reason = `abstraction:${cluster.sharedConcepts.slice(0, 3).join(',')}`.slice(0, 256);
696
+ for (const member of cluster.members) {
697
+ const [aId, bId] = member.id <= absId ? [member.id, absId] : [absId, member.id];
698
+ const edgeId = computeDeterministicEdgeId(aId, bId, 'abstraction');
699
+ absEdges.push({
700
+ edgeId,
701
+ aId,
702
+ bId,
703
+ edgeType: 'abstraction',
704
+ weight: edgeWeight,
705
+ trust: 'low',
706
+ reason,
707
+ createdAt: nowMs,
708
+ updatedAt: nowMs,
709
+ });
710
+ derivedRefs.push({
711
+ sourceNodeId: member.id,
712
+ sourceVersion: member.sourceVersion,
713
+ targetKind: 'node',
714
+ targetId: absId,
715
+ }, {
716
+ sourceNodeId: member.id,
717
+ sourceVersion: member.sourceVersion,
718
+ targetKind: 'edge',
719
+ targetId: edgeId,
720
+ }, {
721
+ sourceNodeId: absId,
722
+ sourceVersion: 1,
723
+ targetKind: 'edge',
724
+ targetId: edgeId,
725
+ });
726
+ }
727
+ }
728
+ return { nodes: absNodes, edges: absEdges, derivedRefs };
729
+ }
730
+ function splitCamelCase(identifier) {
731
+ const spaced = identifier.replace(/([a-z0-9])([A-Z])/gu, '$1 $2').toLowerCase().trim();
732
+ if (!spaced.includes(' '))
733
+ return null;
734
+ return normalizeEntityKey(spaced);
735
+ }
736
+ function extractAliasesFromMetadata(metadata) {
737
+ const out = [];
738
+ const rawRecord = metadata;
739
+ const extraAliases = metadata.extra?.aliases;
740
+ const topAliases = rawRecord['aliases'];
741
+ for (const candidateList of [extraAliases, topAliases]) {
742
+ if (!Array.isArray(candidateList))
743
+ continue;
744
+ for (const entry of candidateList) {
745
+ if (typeof entry !== 'string')
746
+ continue;
747
+ const normalized = normalizeEntityKey(entry);
748
+ if (normalized !== null)
749
+ out.push(normalized);
750
+ }
751
+ }
752
+ return out;
753
+ }
754
+ function synthesizeSynonyms(scope, nodes, abstractionNodes, maxSynonyms, nowMs) {
755
+ if (maxSynonyms <= 0 || nodes.length === 0) {
756
+ return { synonyms: [], derivedRefs: [] };
757
+ }
758
+ const canonicalGroundings = new Map();
759
+ for (const node of nodes) {
760
+ for (const ent of node.entities) {
761
+ const canonical = normalizeEntityKey(ent);
762
+ if (canonical === null || TOKEN_STOPWORDS.has(canonical))
763
+ continue;
764
+ let list = canonicalGroundings.get(canonical);
765
+ if (list === undefined) {
766
+ list = [];
767
+ canonicalGroundings.set(canonical, list);
768
+ }
769
+ if (!list.some((existing) => existing.id === node.id)) {
770
+ list.push(node);
771
+ }
772
+ }
773
+ }
774
+ const abstractionByConcept = new Map();
775
+ for (const absNode of abstractionNodes) {
776
+ for (const ent of absNode.entities) {
777
+ if (!abstractionByConcept.has(ent)) {
778
+ abstractionByConcept.set(ent, absNode);
779
+ }
780
+ }
781
+ }
782
+ const seenSurfaceCanonical = new Set();
783
+ const synonyms = [];
784
+ const derivedRefs = [];
785
+ const addSynonym = (rawSurface, canonicalEntity, groundingNodes) => {
786
+ if (synonyms.length >= maxSynonyms)
787
+ return;
788
+ const surface = normalizeEntityKey(rawSurface);
789
+ if (surface === null ||
790
+ surface === canonicalEntity ||
791
+ surface.length > 256 ||
792
+ canonicalEntity.length > 256 ||
793
+ TOKEN_STOPWORDS.has(surface) ||
794
+ groundingNodes.length === 0) {
795
+ return;
796
+ }
797
+ const dedupKey = `${surface}\0${canonicalEntity}`;
798
+ if (seenSurfaceCanonical.has(dedupKey))
799
+ return;
800
+ seenSurfaceCanonical.add(dedupKey);
801
+ const synId = computeDreamSynonymId(scope.ownerScopeKey, surface, canonicalEntity);
802
+ const primaryNode = groundingNodes[0];
803
+ synonyms.push({
804
+ id: synId,
805
+ ownerScopeKey: scope.ownerScopeKey,
806
+ surface,
807
+ canonicalEntity,
808
+ sourceNodeId: primaryNode.id,
809
+ trust: 'low',
810
+ createdAt: nowMs,
811
+ });
812
+ for (const grounding of groundingNodes) {
813
+ derivedRefs.push({
814
+ sourceNodeId: grounding.id,
815
+ sourceVersion: grounding.sourceVersion,
816
+ targetKind: 'synonym',
817
+ targetId: synId,
818
+ });
819
+ }
820
+ const bridge = abstractionByConcept.get(canonicalEntity);
821
+ if (bridge !== undefined) {
822
+ derivedRefs.push({
823
+ sourceNodeId: bridge.id,
824
+ sourceVersion: bridge.sourceVersion,
825
+ targetKind: 'synonym',
826
+ targetId: synId,
827
+ });
828
+ }
829
+ };
830
+ for (const node of nodes) {
831
+ if (synonyms.length >= maxSynonyms)
832
+ break;
833
+ const text = `${node.title}\n${node.body}`;
834
+ // 1. Metadata aliases (e.g., wiki/skill aliases)
835
+ const metaAliases = extractAliasesFromMetadata(node.metadata);
836
+ if (metaAliases.length > 0) {
837
+ const titleCanonical = normalizeEntityKey(node.title);
838
+ const fallbackCanonical = node.entities[0] ?? null;
839
+ const canonical = titleCanonical !== null && canonicalGroundings.has(titleCanonical)
840
+ ? titleCanonical
841
+ : fallbackCanonical !== null && canonicalGroundings.has(fallbackCanonical)
842
+ ? fallbackCanonical
843
+ : null;
844
+ if (canonical !== null) {
845
+ const groundings = canonicalGroundings.get(canonical) ?? [node];
846
+ const combinedGroundings = groundings.some((g) => g.id === node.id)
847
+ ? groundings
848
+ : [node, ...groundings];
849
+ for (const alias of metaAliases) {
850
+ addSynonym(alias, canonical, combinedGroundings);
851
+ }
852
+ }
853
+ }
854
+ // 2. Parenthetical aliases: `Canonical (Alias)` or `Alias (Canonical)`
855
+ PARENTHETICAL_ALIAS_RE.lastIndex = 0;
856
+ let parenMatch;
857
+ while ((parenMatch = PARENTHETICAL_ALIAS_RE.exec(text)) !== null) {
858
+ if (synonyms.length >= maxSynonyms)
859
+ break;
860
+ const left = normalizeEntityKey(parenMatch[1] ?? '');
861
+ const right = normalizeEntityKey(parenMatch[2] ?? '');
862
+ if (left === null || right === null || left === right)
863
+ continue;
864
+ const leftWords = left.split(/\s+/u);
865
+ const leftCandidates = [];
866
+ for (let start = 0; start < leftWords.length; start += 1) {
867
+ const phrase = leftWords.slice(start).join(' ');
868
+ if (phrase.length < 2)
869
+ continue;
870
+ leftCandidates.push(phrase, phrase.replace(/\s+/gu, '-'), phrase.replace(/\s+/gu, '_'));
871
+ }
872
+ const leftCanonical = leftCandidates.find((v) => canonicalGroundings.has(v));
873
+ const rightGroundings = canonicalGroundings.get(right);
874
+ if (leftCanonical !== undefined) {
875
+ const leftGroundings = canonicalGroundings.get(leftCanonical);
876
+ const groundings = leftGroundings.some((g) => g.id === node.id)
877
+ ? leftGroundings
878
+ : [node, ...leftGroundings];
879
+ addSynonym(right, leftCanonical, groundings);
880
+ }
881
+ else if (rightGroundings !== undefined) {
882
+ const groundings = rightGroundings.some((g) => g.id === node.id)
883
+ ? rightGroundings
884
+ : [node, ...rightGroundings];
885
+ addSynonym(left, right, groundings);
886
+ }
887
+ else if (node.entities.length > 0) {
888
+ // Check if left matches a multi-word form of a canonical entity in this node
889
+ for (const ent of node.entities) {
890
+ if (ent === left || ent === right) {
891
+ const groundings = canonicalGroundings.get(ent) ?? [node];
892
+ addSynonym(ent === left ? right : left, ent, groundings);
893
+ break;
894
+ }
895
+ }
896
+ }
897
+ }
898
+ // 3. CamelCase variants in raw text matching canonical entities
899
+ CAMEL_CASE_RE.lastIndex = 0;
900
+ let camelMatch;
901
+ while ((camelMatch = CAMEL_CASE_RE.exec(text)) !== null) {
902
+ if (synonyms.length >= maxSynonyms)
903
+ break;
904
+ const rawCamel = camelMatch[1];
905
+ if (rawCamel === undefined)
906
+ continue;
907
+ const normalizedCamel = normalizeEntityKey(rawCamel);
908
+ const spaced = splitCamelCase(rawCamel);
909
+ if (normalizedCamel === null || spaced === null)
910
+ continue;
911
+ const hyphenated = spaced.replace(/\s+/gu, '-');
912
+ const underscored = spaced.replace(/\s+/gu, '_');
913
+ for (const candidateCanonical of [normalizedCamel, hyphenated, underscored, spaced]) {
914
+ const groundings = canonicalGroundings.get(candidateCanonical);
915
+ if (groundings !== undefined) {
916
+ const combined = groundings.some((g) => g.id === node.id)
917
+ ? groundings
918
+ : [node, ...groundings];
919
+ if (spaced !== candidateCanonical)
920
+ addSynonym(spaced, candidateCanonical, combined);
921
+ if (normalizedCamel !== candidateCanonical) {
922
+ addSynonym(normalizedCamel, candidateCanonical, combined);
923
+ }
924
+ break;
925
+ }
926
+ }
927
+ }
928
+ }
929
+ // 4. Hyphen / underscore / space variants for canonical entities in scope
930
+ const sortedCanonicals = [...canonicalGroundings.keys()].sort();
931
+ for (const canonical of sortedCanonicals) {
932
+ if (synonyms.length >= maxSynonyms)
933
+ break;
934
+ const groundings = canonicalGroundings.get(canonical);
935
+ if (canonical.includes('-')) {
936
+ addSynonym(canonical.replace(/-/gu, ' '), canonical, groundings);
937
+ addSynonym(canonical.replace(/-/gu, '_'), canonical, groundings);
938
+ }
939
+ else if (canonical.includes('_')) {
940
+ addSynonym(canonical.replace(/_/gu, ' '), canonical, groundings);
941
+ addSynonym(canonical.replace(/_/gu, '-'), canonical, groundings);
942
+ }
943
+ }
944
+ return { synonyms, derivedRefs };
945
+ }
946
+ export function synthesizeDreamingArtifacts(db, scope, config, options) {
947
+ const nowMs = options?.nowMs ?? Date.now();
948
+ const wMin = options?.weightMin ?? 0.05;
949
+ const wMax = options?.weightMax ?? 3.0;
950
+ const nodeLimit = Math.max(2, Math.min(512, options?.nodeLimit ?? 128));
951
+ const nodes = loadCandidateNodes(db, scope.ownerScopeKey, nowMs, nodeLimit);
952
+ if (nodes.length === 0) {
953
+ return {
954
+ nodes: [],
955
+ edges: [],
956
+ synonyms: [],
957
+ derivedRefs: [],
958
+ pairsCreated: 0,
959
+ abstractionsCreated: 0,
960
+ synonymsCreated: 0,
961
+ };
962
+ }
963
+ const { connectedPairs, neighborsByNode } = loadExistingGraphNeighborhood(db, nodes.map((n) => n.id));
964
+ const edgeSynth = synthesizeLongRangeDreamEdges(nodes, connectedPairs, neighborsByNode, config.maxPairsPerRun, wMin, wMax, nowMs);
965
+ const absSynth = synthesizeAbstractionClusters(db, scope, nodes, config.maxAbstractionsPerRun, config.nodeTtlMs, wMin, wMax, nowMs);
966
+ const synSynth = synthesizeSynonyms(scope, nodes, absSynth.nodes, config.maxSynonymsPerRun, nowMs);
967
+ return {
968
+ nodes: absSynth.nodes,
969
+ edges: [...edgeSynth.edges, ...absSynth.edges],
970
+ synonyms: synSynth.synonyms,
971
+ derivedRefs: [
972
+ ...edgeSynth.derivedRefs,
973
+ ...absSynth.derivedRefs,
974
+ ...synSynth.derivedRefs,
975
+ ],
976
+ pairsCreated: edgeSynth.edges.length,
977
+ abstractionsCreated: absSynth.nodes.length,
978
+ synonymsCreated: synSynth.synonyms.length,
979
+ };
980
+ }
981
+ export function projectDreamIdeasToAssociation(ideas, scope, config, nowMs = Date.now()) {
982
+ const scope8 = scope.ownerScopeKey.slice(0, 8);
983
+ const upserts = [];
984
+ const withdrawals = [];
985
+ for (const idea of ideas) {
986
+ const sourceRef = `dream-idea:${idea.id}`;
987
+ const nodeId = `a:dr-${scope8}-${sha256Hex(idea.id).slice(0, 20)}`;
988
+ if (idea.state === 'rejected' || idea.state === 'withdrawn') {
989
+ withdrawals.push({
990
+ ownerScopeKey: scope.ownerScopeKey,
991
+ sourcePlugin: 'assistant-dreaming',
992
+ sourceRef,
993
+ nodeId,
994
+ });
995
+ continue;
996
+ }
997
+ const title = compactText(idea.summary, 160);
998
+ const body = compactText(idea.detail || idea.summary, 4_096);
999
+ const combined = `${title}\n${body}`;
1000
+ const entities = extractEntities(combined);
1001
+ const tokens = tokenizeAssociationText(combined);
1002
+ const expiresAt = config.nodeTtlMs > 0 ? nowMs + config.nodeTtlMs : null;
1003
+ upserts.push({
1004
+ id: nodeId,
1005
+ kind: 'dream',
1006
+ sourcePlugin: 'assistant-dreaming',
1007
+ sourceRef,
1008
+ sourceVersion: 1,
1009
+ ownerScopeKey: scope.ownerScopeKey,
1010
+ ownerMode: scope.mode,
1011
+ principalDigest: scope.principalDigest,
1012
+ principalRecordId: scope.principalRecordId,
1013
+ principalVersion: scope.principalVersion,
1014
+ scopeMode: 'workspace',
1015
+ workspace: scope.workspace,
1016
+ agentPreset: scope.agentPreset,
1017
+ trust: 'low',
1018
+ sensitivity: 'private',
1019
+ title,
1020
+ body,
1021
+ entities,
1022
+ tokens,
1023
+ metadata: {
1024
+ extra: {
1025
+ dreamRunId: idea.runId,
1026
+ dreamLane: idea.lane,
1027
+ dreamState: idea.state,
1028
+ dayKey: idea.dayKey,
1029
+ evidenceRefs: [...idea.evidenceRefs],
1030
+ },
1031
+ },
1032
+ ttlMs: config.nodeTtlMs > 0 ? config.nodeTtlMs : null,
1033
+ expiresAt,
1034
+ status: 'active',
1035
+ createdAt: idea.createdAt,
1036
+ updatedAt: nowMs,
1037
+ });
1038
+ }
1039
+ return { upserts, withdrawals };
1040
+ }
1041
+ export function findExpiredAssociationNodes(db, options) {
1042
+ const nowMs = options?.nowMs ?? Date.now();
1043
+ const limit = Math.max(1, Math.min(1_000, options?.limit ?? 200));
1044
+ const rows = (options?.ownerScopeKey !== undefined
1045
+ ? db
1046
+ .prepare(`
1047
+ SELECT id, owner_scope_key, source_plugin, source_ref, kind, expires_at
1048
+ FROM assoc_nodes
1049
+ WHERE owner_scope_key = ?
1050
+ AND expires_at IS NOT NULL
1051
+ AND expires_at <= ?
1052
+ ORDER BY expires_at ASC, id ASC
1053
+ LIMIT ?
1054
+ `)
1055
+ .all(options.ownerScopeKey, nowMs, limit)
1056
+ : db
1057
+ .prepare(`
1058
+ SELECT id, owner_scope_key, source_plugin, source_ref, kind, expires_at
1059
+ FROM assoc_nodes
1060
+ WHERE expires_at IS NOT NULL
1061
+ AND expires_at <= ?
1062
+ ORDER BY expires_at ASC, id ASC
1063
+ LIMIT ?
1064
+ `)
1065
+ .all(nowMs, limit));
1066
+ return rows.map((row) => ({
1067
+ id: row.id,
1068
+ ownerScopeKey: row.owner_scope_key,
1069
+ sourcePlugin: row.source_plugin,
1070
+ sourceRef: row.source_ref,
1071
+ kind: row.kind,
1072
+ expiresAt: row.expires_at,
1073
+ }));
1074
+ }
1075
+ function cascadeWithdrawNodeDirectly(db, ownerScopeKey, sourcePlugin, sourceRef) {
1076
+ db.exec('BEGIN IMMEDIATE');
1077
+ try {
1078
+ const matching = db
1079
+ .prepare('SELECT id FROM assoc_nodes WHERE owner_scope_key = ? AND source_plugin = ? AND source_ref = ?')
1080
+ .all(ownerScopeKey, sourcePlugin, sourceRef);
1081
+ if (matching.length === 0) {
1082
+ db.exec('COMMIT');
1083
+ return;
1084
+ }
1085
+ const selectDerived = db.prepare('SELECT target_kind, target_id FROM assoc_derived_from WHERE source_node_id = ?');
1086
+ const selectSynsByNode = db.prepare('SELECT id FROM assoc_synonyms WHERE source_node_id = ?');
1087
+ const deleteSyn = db.prepare('DELETE FROM assoc_synonyms WHERE id = ?');
1088
+ const deleteEdge = db.prepare('DELETE FROM assoc_edges WHERE edge_id = ?');
1089
+ const deleteIncidentEdges = db.prepare('DELETE FROM assoc_edges WHERE a_id = ? OR b_id = ?');
1090
+ const deleteNode = db.prepare('DELETE FROM assoc_nodes WHERE id = ?');
1091
+ const deleteDerivedBySource = db.prepare('DELETE FROM assoc_derived_from WHERE source_node_id = ?');
1092
+ const deleteDerivedByTarget = db.prepare('DELETE FROM assoc_derived_from WHERE target_kind = ? AND target_id = ?');
1093
+ const visitedNodes = new Set();
1094
+ const deletedNodes = new Set();
1095
+ const deletedEdges = new Set();
1096
+ const deletedSyns = new Set();
1097
+ const queue = matching.map((m) => m.id);
1098
+ for (const rootId of queue) {
1099
+ deletedNodes.add(rootId);
1100
+ }
1101
+ while (queue.length > 0) {
1102
+ const nodeId = queue.shift();
1103
+ if (visitedNodes.has(nodeId))
1104
+ continue;
1105
+ visitedNodes.add(nodeId);
1106
+ const derived = selectDerived.all(nodeId);
1107
+ for (const row of derived) {
1108
+ if (row.target_kind === 'edge') {
1109
+ deletedEdges.add(row.target_id);
1110
+ }
1111
+ else if (row.target_kind === 'synonym') {
1112
+ deletedSyns.add(row.target_id);
1113
+ }
1114
+ else if (row.target_kind === 'node' && !deletedNodes.has(row.target_id)) {
1115
+ deletedNodes.add(row.target_id);
1116
+ queue.push(row.target_id);
1117
+ }
1118
+ }
1119
+ const attachedSyns = selectSynsByNode.all(nodeId);
1120
+ for (const syn of attachedSyns) {
1121
+ deletedSyns.add(syn.id);
1122
+ }
1123
+ }
1124
+ for (const synId of deletedSyns) {
1125
+ deleteSyn.run(synId);
1126
+ deleteDerivedByTarget.run('synonym', synId);
1127
+ }
1128
+ for (const edgeId of deletedEdges) {
1129
+ deleteEdge.run(edgeId);
1130
+ deleteDerivedByTarget.run('edge', edgeId);
1131
+ }
1132
+ for (const nodeId of deletedNodes) {
1133
+ deleteIncidentEdges.run(nodeId, nodeId);
1134
+ deleteNode.run(nodeId);
1135
+ deleteDerivedByTarget.run('node', nodeId);
1136
+ deleteDerivedBySource.run(nodeId);
1137
+ }
1138
+ db.exec('COMMIT');
1139
+ }
1140
+ catch (error) {
1141
+ db.exec('ROLLBACK');
1142
+ throw error;
1143
+ }
1144
+ }
1145
+ export function sweepExpiredDreamingNodes(db, options) {
1146
+ const nowMs = options?.nowMs ?? Date.now();
1147
+ const targets = findExpiredAssociationNodes(db, {
1148
+ ...(options?.ownerScopeKey === undefined ? {} : { ownerScopeKey: options.ownerScopeKey }),
1149
+ nowMs,
1150
+ ...(options?.limit === undefined ? {} : { limit: options.limit }),
1151
+ });
1152
+ for (const target of targets) {
1153
+ if (options?.withdrawSource !== undefined) {
1154
+ options.withdrawSource({
1155
+ ownerScopeKey: target.ownerScopeKey,
1156
+ sourcePlugin: target.sourcePlugin,
1157
+ sourceRef: target.sourceRef,
1158
+ hardDelete: true,
1159
+ nowMs,
1160
+ });
1161
+ }
1162
+ else {
1163
+ cascadeWithdrawNodeDirectly(db, target.ownerScopeKey, target.sourcePlugin, target.sourceRef);
1164
+ }
1165
+ }
1166
+ return targets;
1167
+ }
1168
+ function applyArtifactsDirectly(db, input) {
1169
+ db.exec('BEGIN IMMEDIATE');
1170
+ try {
1171
+ const checkWithdrawn = db.prepare('SELECT 1 AS ok FROM assoc_withdrawn_sources WHERE owner_scope_key = ? AND source_plugin = ? AND source_ref = ?');
1172
+ const upsertNodeStmt = db.prepare(`
1173
+ INSERT INTO assoc_nodes (
1174
+ id, kind, source_plugin, source_ref, source_version,
1175
+ owner_scope_key, owner_mode, principal_digest, principal_record_id, principal_version,
1176
+ scope_mode, workspace, agent_preset, trust, sensitivity,
1177
+ title, body, entities_json, tokens_json, metadata_json,
1178
+ ttl_ms, expires_at, status, created_at, updated_at
1179
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
1180
+ ON CONFLICT(id) DO UPDATE SET
1181
+ kind = excluded.kind,
1182
+ source_plugin = excluded.source_plugin,
1183
+ source_ref = excluded.source_ref,
1184
+ source_version = excluded.source_version,
1185
+ owner_scope_key = excluded.owner_scope_key,
1186
+ owner_mode = excluded.owner_mode,
1187
+ principal_digest = excluded.principal_digest,
1188
+ principal_record_id = excluded.principal_record_id,
1189
+ principal_version = excluded.principal_version,
1190
+ scope_mode = excluded.scope_mode,
1191
+ workspace = excluded.workspace,
1192
+ agent_preset = excluded.agent_preset,
1193
+ trust = excluded.trust,
1194
+ sensitivity = excluded.sensitivity,
1195
+ title = excluded.title,
1196
+ body = excluded.body,
1197
+ entities_json = excluded.entities_json,
1198
+ tokens_json = excluded.tokens_json,
1199
+ metadata_json = excluded.metadata_json,
1200
+ ttl_ms = excluded.ttl_ms,
1201
+ expires_at = excluded.expires_at,
1202
+ status = excluded.status,
1203
+ updated_at = excluded.updated_at
1204
+ `);
1205
+ const skippedNodeIds = new Set();
1206
+ for (const node of input.nodes) {
1207
+ if (checkWithdrawn.get(node.ownerScopeKey, node.sourcePlugin, node.sourceRef) !== undefined) {
1208
+ skippedNodeIds.add(node.id);
1209
+ continue;
1210
+ }
1211
+ upsertNodeStmt.run(node.id, node.kind, node.sourcePlugin, node.sourceRef, node.sourceVersion, node.ownerScopeKey, node.ownerMode, node.principalDigest, node.principalRecordId, node.principalVersion, node.scopeMode, node.workspace, node.agentPreset, node.trust, node.sensitivity, node.title.slice(0, 512), node.body, JSON.stringify(node.entities), JSON.stringify(node.tokens), JSON.stringify(node.metadata ?? {}), node.ttlMs ?? null, node.expiresAt ?? null, node.status ?? 'active', node.createdAt, node.updatedAt);
1212
+ }
1213
+ if (input.edges.length > 0) {
1214
+ const checkNode = db.prepare('SELECT 1 AS ok FROM assoc_nodes WHERE id = ?');
1215
+ const upsertEdgeStmt = db.prepare(`
1216
+ INSERT INTO assoc_edges (
1217
+ edge_id, a_id, b_id, edge_type, weight, trust, reason,
1218
+ use_count, last_used_at, created_at, updated_at
1219
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
1220
+ ON CONFLICT(a_id, b_id, edge_type) DO UPDATE SET
1221
+ weight = excluded.weight,
1222
+ trust = excluded.trust,
1223
+ reason = excluded.reason,
1224
+ updated_at = excluded.updated_at
1225
+ `);
1226
+ for (const edge of input.edges) {
1227
+ if (edge.aId === edge.bId)
1228
+ continue;
1229
+ if (checkNode.get(edge.aId) === undefined || checkNode.get(edge.bId) === undefined) {
1230
+ continue;
1231
+ }
1232
+ upsertEdgeStmt.run(edge.edgeId, edge.aId, edge.bId, edge.edgeType, Math.min(10.0, Math.max(0.0, edge.weight)), edge.trust, edge.reason.slice(0, 256), edge.useCount ?? 0, edge.lastUsedAt ?? null, edge.createdAt, edge.updatedAt);
1233
+ }
1234
+ }
1235
+ if (input.synonyms && input.synonyms.length > 0) {
1236
+ const upsertSynStmt = db.prepare(`
1237
+ INSERT INTO assoc_synonyms (
1238
+ id, owner_scope_key, surface, canonical_entity, source_node_id, trust, created_at
1239
+ ) VALUES (?, ?, ?, ?, ?, ?, ?)
1240
+ ON CONFLICT(owner_scope_key, surface, canonical_entity) DO UPDATE SET
1241
+ source_node_id = excluded.source_node_id,
1242
+ trust = excluded.trust
1243
+ `);
1244
+ for (const syn of input.synonyms) {
1245
+ if (syn.sourceNodeId !== undefined && syn.sourceNodeId !== null && skippedNodeIds.has(syn.sourceNodeId)) {
1246
+ continue;
1247
+ }
1248
+ upsertSynStmt.run(syn.id, syn.ownerScopeKey, syn.surface, syn.canonicalEntity, syn.sourceNodeId ?? null, syn.trust, syn.createdAt);
1249
+ }
1250
+ }
1251
+ if (input.derivedRefs.length > 0) {
1252
+ const insertDerivedStmt = db.prepare(`
1253
+ INSERT OR IGNORE INTO assoc_derived_from (
1254
+ source_node_id, source_version, target_kind, target_id
1255
+ ) VALUES (?, ?, ?, ?)
1256
+ `);
1257
+ for (const ref of input.derivedRefs) {
1258
+ if (skippedNodeIds.has(ref.sourceNodeId) ||
1259
+ (ref.targetKind === 'node' && skippedNodeIds.has(ref.targetId))) {
1260
+ continue;
1261
+ }
1262
+ insertDerivedStmt.run(ref.sourceNodeId, ref.sourceVersion, ref.targetKind, ref.targetId);
1263
+ }
1264
+ }
1265
+ db.exec('COMMIT');
1266
+ }
1267
+ catch (error) {
1268
+ db.exec('ROLLBACK');
1269
+ throw error;
1270
+ }
1271
+ }
1272
+ export function runDreamingPass(input) {
1273
+ ensureDreamingSchema(input.db);
1274
+ const nowMs = input.nowMs ?? Date.now();
1275
+ let computedRunId = null;
1276
+ const getRunId = () => {
1277
+ if (computedRunId === null) {
1278
+ const runCountRow = input.db
1279
+ .prepare('SELECT COUNT(*) AS cnt FROM assoc_dream_runs WHERE owner_scope_key = ?')
1280
+ .get(input.scope.ownerScopeKey);
1281
+ const runOrdinal = runCountRow?.cnt ?? 0;
1282
+ computedRunId = `dream-${sha256Hex(`${input.scope.ownerScopeKey}\0${nowMs}\0${runOrdinal}`).slice(0, 24)}`;
1283
+ }
1284
+ return computedRunId;
1285
+ };
1286
+ const gate = evaluateDreamingGate(input, 'execute', getRunId);
1287
+ if (!gate.allowed) {
1288
+ return {
1289
+ ran: false,
1290
+ runId: null,
1291
+ status: 'skipped',
1292
+ reason: gate.reason,
1293
+ ...(gate.policyReasonCode !== undefined
1294
+ ? { policyReasonCode: gate.policyReasonCode }
1295
+ : {}),
1296
+ edgesCreated: 0,
1297
+ abstractionsCreated: 0,
1298
+ synonymsCreated: 0,
1299
+ expiredSwept: 0,
1300
+ ideasProjected: 0,
1301
+ ideasWithdrawn: 0,
1302
+ artifacts: {
1303
+ nodes: [],
1304
+ edges: [],
1305
+ synonyms: [],
1306
+ derivedRefs: [],
1307
+ pairsCreated: 0,
1308
+ abstractionsCreated: 0,
1309
+ synonymsCreated: 0,
1310
+ },
1311
+ };
1312
+ }
1313
+ const runId = getRunId();
1314
+ const expiredTargets = sweepExpiredDreamingNodes(input.db, {
1315
+ ownerScopeKey: input.scope.ownerScopeKey,
1316
+ nowMs,
1317
+ ...(input.writer?.withdrawSource !== undefined
1318
+ ? { withdrawSource: input.writer.withdrawSource }
1319
+ : {}),
1320
+ });
1321
+ let ideasProjected = 0;
1322
+ let ideasWithdrawn = 0;
1323
+ let ideaNodes = [];
1324
+ if (input.ideas !== undefined && input.ideas.length > 0) {
1325
+ const projected = projectDreamIdeasToAssociation(input.ideas, input.scope, input.config, nowMs);
1326
+ ideaNodes = projected.upserts;
1327
+ ideasProjected = projected.upserts.length;
1328
+ for (const w of projected.withdrawals) {
1329
+ if (input.writer?.withdrawSource !== undefined) {
1330
+ input.writer.withdrawSource({
1331
+ ownerScopeKey: w.ownerScopeKey,
1332
+ sourcePlugin: w.sourcePlugin,
1333
+ sourceRef: w.sourceRef,
1334
+ hardDelete: true,
1335
+ nowMs,
1336
+ });
1337
+ }
1338
+ else {
1339
+ cascadeWithdrawNodeDirectly(input.db, w.ownerScopeKey, w.sourcePlugin, w.sourceRef);
1340
+ }
1341
+ ideasWithdrawn += 1;
1342
+ }
1343
+ }
1344
+ const artifacts = synthesizeDreamingArtifacts(input.db, input.scope, input.config, {
1345
+ nowMs,
1346
+ ...(input.weightMin !== undefined ? { weightMin: input.weightMin } : {}),
1347
+ ...(input.weightMax !== undefined ? { weightMax: input.weightMax } : {}),
1348
+ ...(input.nodeLimit !== undefined ? { nodeLimit: input.nodeLimit } : {}),
1349
+ });
1350
+ const allNodes = [...ideaNodes, ...artifacts.nodes];
1351
+ if (allNodes.length > 0 ||
1352
+ artifacts.edges.length > 0 ||
1353
+ artifacts.synonyms.length > 0 ||
1354
+ artifacts.derivedRefs.length > 0) {
1355
+ const batch = {
1356
+ nodes: allNodes,
1357
+ edges: artifacts.edges,
1358
+ synonyms: artifacts.synonyms,
1359
+ derivedRefs: artifacts.derivedRefs,
1360
+ };
1361
+ if (input.writer !== undefined) {
1362
+ input.writer.upsertBatch(batch);
1363
+ }
1364
+ else {
1365
+ applyArtifactsDirectly(input.db, batch);
1366
+ }
1367
+ }
1368
+ input.db
1369
+ .prepare(`
1370
+ INSERT INTO assoc_dream_runs (
1371
+ run_id, owner_scope_key, status,
1372
+ edges_created, abstractions_created, synonyms_created, ran_at
1373
+ ) VALUES (?, ?, 'completed', ?, ?, ?, ?)
1374
+ ON CONFLICT(run_id) DO UPDATE SET
1375
+ status = excluded.status,
1376
+ edges_created = excluded.edges_created,
1377
+ abstractions_created = excluded.abstractions_created,
1378
+ synonyms_created = excluded.synonyms_created,
1379
+ ran_at = excluded.ran_at
1380
+ `)
1381
+ .run(runId, input.scope.ownerScopeKey, artifacts.edges.length, artifacts.abstractionsCreated, artifacts.synonymsCreated, nowMs);
1382
+ return {
1383
+ ran: true,
1384
+ runId,
1385
+ status: 'completed',
1386
+ reason: 'ok',
1387
+ edgesCreated: artifacts.edges.length,
1388
+ abstractionsCreated: artifacts.abstractionsCreated,
1389
+ synonymsCreated: artifacts.synonymsCreated,
1390
+ expiredSwept: expiredTargets.length,
1391
+ ideasProjected,
1392
+ ideasWithdrawn,
1393
+ artifacts,
1394
+ };
1395
+ }
1396
+ export function listDreamRuns(db, ownerScopeKey, limit = 20) {
1397
+ if (!hasTable(db, 'assoc_dream_runs'))
1398
+ return [];
1399
+ const rows = db
1400
+ .prepare(`
1401
+ SELECT run_id, owner_scope_key, status, edges_created, abstractions_created, synonyms_created, ran_at
1402
+ FROM assoc_dream_runs
1403
+ WHERE owner_scope_key = ?
1404
+ ORDER BY ran_at DESC, run_id ASC
1405
+ LIMIT ?
1406
+ `)
1407
+ .all(ownerScopeKey, Math.max(1, Math.min(200, limit)));
1408
+ return rows.map((row) => ({
1409
+ runId: row.run_id,
1410
+ ownerScopeKey: row.owner_scope_key,
1411
+ status: row.status,
1412
+ edgesCreated: row.edges_created,
1413
+ abstractionsCreated: row.abstractions_created,
1414
+ synonymsCreated: row.synonyms_created,
1415
+ ranAt: row.ran_at,
1416
+ }));
1417
+ }
1418
+ //# sourceMappingURL=dreaming.js.map