@dsh-ray/assistant-association 0.0.1-seed.0 → 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 +132 -1
  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 +149 -4
package/lib/sources.js ADDED
@@ -0,0 +1,2024 @@
1
+ import { createHash } from 'node:crypto';
2
+ import { DEFAULT_ASSOCIATION_DREAMING_CONFIG, projectDreamIdeasToAssociation, } from './dreaming.js';
3
+ import { buildSharedEntityEdges, extractEntities } from './entities.js';
4
+ import { retractEvalPoolTask, upsertEvalPoolFromReceipt, withdrawEvalPoolTask, } from './eval-pool.js';
5
+ import { clampEdgeWeight, classifyEvaluationCorrection } from './hebbian.js';
6
+ import { normalizeEntityKey, tokenizeAssociationText } from './tokenize.js';
7
+ import { computeDeterministicEdgeId, computeDeterministicSynonymId, computeOwnerScopeKey, computePrincipalDigest, DEFAULT_HEBBIAN_CONFIG, normalizeSourceVersion, } from './types.js';
8
+ const MAX_ENTITY_PEERS_PER_UPSERT = 64;
9
+ const MAX_SHARED_EDGES_PER_NODE = 16;
10
+ const MAX_TITLE_CHARS = 160;
11
+ const MAX_BODY_CHARS = 8_192;
12
+ function sha256Hex(value) {
13
+ return createHash('sha256').update(value, 'utf8').digest('hex');
14
+ }
15
+ function sanitizeEventSummaryText(raw) {
16
+ return raw
17
+ .replace(/\b(?:sk|pk|tok|token|secret|bearer)[_-]?[A-Za-z0-9._-]{12,}\b/giu, '[redacted]')
18
+ .replace(/\bauthorization\s*:\s*\S+/giu, 'authorization:[redacted]');
19
+ }
20
+ function compactTitle(raw, maxChars = MAX_TITLE_CHARS) {
21
+ const collapsed = raw.normalize('NFKC').replace(/\s+/gu, ' ').trim();
22
+ if (collapsed.length <= maxChars)
23
+ return collapsed;
24
+ const chars = [...collapsed];
25
+ if (chars.length <= maxChars)
26
+ return collapsed;
27
+ return `${chars.slice(0, Math.max(0, maxChars - 1)).join('')}…`;
28
+ }
29
+ function makeMemoryNodeId(recordId, scope, existingPrimary) {
30
+ const base = `a:m-${recordId}`;
31
+ return existingPrimary ? base : `${base}~${scope.ownerScopeKey.slice(0, 8)}`;
32
+ }
33
+ export class AssociationSourceManager {
34
+ #ctx;
35
+ #store;
36
+ #writeQueue;
37
+ #callbacks;
38
+ #scopes = new Map();
39
+ #routeAuthorities = new Map();
40
+ #assignedGlobalMemoryOwners = new Map();
41
+ #disposers = [];
42
+ #syncTimer = null;
43
+ #syncInFlight = null;
44
+ #syncQueued = false;
45
+ #disposed = false;
46
+ constructor(ctx, store, writeQueue, callbacks) {
47
+ this.#ctx = ctx;
48
+ this.#store = store;
49
+ this.#writeQueue = writeQueue;
50
+ this.#callbacks = callbacks;
51
+ }
52
+ #now() {
53
+ return this.#callbacks.now?.() ?? Date.now();
54
+ }
55
+ start() {
56
+ // Load persisted scopes from SQLite
57
+ for (const scope of this.#store.listOwnerScopes()) {
58
+ this.#scopes.set(scope.ownerScopeKey, scope);
59
+ }
60
+ // Bind optional Delivery service
61
+ const fDelivery = this.#ctx.inject(['assistantDelivery'], (deliveryCtx) => {
62
+ const delivery = deliveryCtx.get('assistantDelivery', false);
63
+ if (delivery === undefined)
64
+ return;
65
+ this.#discoverDeliveryScopes(delivery);
66
+ const unsubFg = typeof delivery.onForegroundTaskCompletion === 'function'
67
+ ? delivery.onForegroundTaskCompletion(() => {
68
+ this.#discoverDeliveryScopes(delivery);
69
+ this.scheduleSync();
70
+ })
71
+ : undefined;
72
+ return () => {
73
+ unsubFg?.();
74
+ };
75
+ });
76
+ this.#disposers.push(() => {
77
+ void fDelivery.dispose();
78
+ });
79
+ // Bind optional PersonalMemory service
80
+ const fMemory = this.#ctx.inject(['personalMemory'], (pmCtx) => {
81
+ const pm = pmCtx.get('personalMemory', false);
82
+ if (pm === undefined)
83
+ return;
84
+ const unsub = typeof pm.onRecordChange === 'function'
85
+ ? pm.onRecordChange((event) => {
86
+ this.#handleMemoryRecordChange(event);
87
+ })
88
+ : undefined;
89
+ this.scheduleSync();
90
+ return () => {
91
+ unsub?.();
92
+ };
93
+ });
94
+ this.#disposers.push(() => {
95
+ void fMemory.dispose();
96
+ });
97
+ // Bind optional AssistantGoals service
98
+ const fGoals = this.#ctx.inject(['assistantGoals'], (goalsCtx) => {
99
+ const goals = goalsCtx.get('assistantGoals', false);
100
+ if (goals === undefined)
101
+ return;
102
+ const unsub = typeof goals.onGoalRecordChange === 'function'
103
+ ? goals.onGoalRecordChange((event) => {
104
+ this.#handleGoalRecordChange(event);
105
+ })
106
+ : undefined;
107
+ this.scheduleSync();
108
+ return () => {
109
+ unsub?.();
110
+ };
111
+ });
112
+ this.#disposers.push(() => {
113
+ void fGoals.dispose();
114
+ });
115
+ // Bind optional AssistantWorkItems service
116
+ const fWorkItems = this.#ctx.inject(['assistantWorkItems'], (wiCtx) => {
117
+ const workItems = wiCtx.get('assistantWorkItems', false);
118
+ if (workItems === undefined)
119
+ return;
120
+ const unsub = typeof workItems.onWorkItemChange === 'function'
121
+ ? workItems.onWorkItemChange((event) => {
122
+ this.#handleWorkItemChange(event);
123
+ })
124
+ : undefined;
125
+ this.scheduleSync();
126
+ return () => {
127
+ unsub?.();
128
+ };
129
+ });
130
+ this.#disposers.push(() => {
131
+ void fWorkItems.dispose();
132
+ });
133
+ // Bind optional AssistantAutomations service
134
+ const fAutomations = this.#ctx.inject(['assistantAutomations'], (autoCtx) => {
135
+ const automations = autoCtx.get('assistantAutomations', false);
136
+ if (automations === undefined)
137
+ return;
138
+ const unsub = typeof automations.onDefinitionChange === 'function'
139
+ ? automations.onDefinitionChange((event) => {
140
+ this.#handleAutomationChange(event);
141
+ })
142
+ : undefined;
143
+ this.scheduleSync();
144
+ return () => {
145
+ unsub?.();
146
+ };
147
+ });
148
+ this.#disposers.push(() => {
149
+ void fAutomations.dispose();
150
+ });
151
+ // Bind optional AssistantEvaluation service
152
+ const fEvaluation = this.#ctx.inject(['assistantEvaluation'], (evalCtx) => {
153
+ const evaluation = evalCtx.get('assistantEvaluation', false);
154
+ if (evaluation === undefined)
155
+ return;
156
+ const unsub = typeof evaluation.onTrustedTaskChange === 'function'
157
+ ? evaluation.onTrustedTaskChange(() => {
158
+ this.scheduleSync();
159
+ })
160
+ : undefined;
161
+ this.scheduleSync();
162
+ return () => {
163
+ unsub?.();
164
+ };
165
+ });
166
+ this.#disposers.push(() => {
167
+ void fEvaluation.dispose();
168
+ });
169
+ // Bind optional PersonalWiki service
170
+ const fWiki = this.#ctx.inject(['personalWiki'], (wikiCtx) => {
171
+ const wiki = wikiCtx.get('personalWiki', false);
172
+ if (wiki === undefined)
173
+ return;
174
+ const unsub = typeof wiki.onPageChange === 'function'
175
+ ? wiki.onPageChange((event) => {
176
+ this.#handleWikiPageChange(event);
177
+ })
178
+ : undefined;
179
+ this.scheduleSync();
180
+ return () => {
181
+ unsub?.();
182
+ };
183
+ });
184
+ this.#disposers.push(() => {
185
+ void fWiki.dispose();
186
+ });
187
+ // Bind optional AssistantSkills service
188
+ const fSkills = this.#ctx.inject(['assistantSkills'], (skillsCtx) => {
189
+ const skills = skillsCtx.get('assistantSkills', false);
190
+ if (skills === undefined)
191
+ return;
192
+ const unsub = typeof skills.onSkillChange === 'function'
193
+ ? skills.onSkillChange(() => {
194
+ this.scheduleSync();
195
+ })
196
+ : undefined;
197
+ this.scheduleSync();
198
+ return () => {
199
+ unsub?.();
200
+ };
201
+ });
202
+ this.#disposers.push(() => {
203
+ void fSkills.dispose();
204
+ });
205
+ // Bind optional EventTriggers service
206
+ const fTriggers = this.#ctx.inject(['eventTriggers'], (trigCtx) => {
207
+ const triggers = trigCtx.get('eventTriggers', false);
208
+ if (triggers === undefined)
209
+ return;
210
+ const unsubChanges = typeof triggers.subscribeSourceChanges === 'function'
211
+ ? triggers.subscribeSourceChanges(() => {
212
+ this.scheduleSync();
213
+ })
214
+ : undefined;
215
+ const unsubIntake = typeof triggers.registerIntakeObserver === 'function'
216
+ ? triggers.registerIntakeObserver({
217
+ protocol: 1,
218
+ observe: () => {
219
+ this.scheduleSync();
220
+ },
221
+ })
222
+ : undefined;
223
+ this.scheduleSync();
224
+ return () => {
225
+ unsubChanges?.();
226
+ unsubIntake?.();
227
+ };
228
+ });
229
+ this.#disposers.push(() => {
230
+ void fTriggers.dispose();
231
+ });
232
+ // Bind optional AssistantDreaming service
233
+ const fDreaming = this.#ctx.inject(['assistantDreaming'], (dreamCtx) => {
234
+ const dreaming = dreamCtx.get('assistantDreaming', false);
235
+ if (dreaming === undefined)
236
+ return;
237
+ const unsub = typeof dreaming.onIdeaChange === 'function'
238
+ ? dreaming.onIdeaChange(() => {
239
+ this.scheduleSync();
240
+ })
241
+ : undefined;
242
+ this.scheduleSync();
243
+ return () => {
244
+ unsub?.();
245
+ };
246
+ });
247
+ this.#disposers.push(() => {
248
+ void fDreaming.dispose();
249
+ });
250
+ }
251
+ dispose() {
252
+ this.#disposed = true;
253
+ if (this.#syncTimer !== null) {
254
+ clearTimeout(this.#syncTimer);
255
+ this.#syncTimer = null;
256
+ }
257
+ while (this.#disposers.length > 0) {
258
+ const dispose = this.#disposers.pop();
259
+ try {
260
+ dispose();
261
+ }
262
+ catch {
263
+ // Ignore disposer errors during teardown
264
+ }
265
+ }
266
+ }
267
+ registerScope(scope) {
268
+ if (this.#disposed)
269
+ return false;
270
+ const existing = this.#scopes.get(scope.ownerScopeKey);
271
+ if (existing !== undefined && existing.authorityId === scope.authorityId) {
272
+ return false;
273
+ }
274
+ this.#scopes.set(scope.ownerScopeKey, scope);
275
+ try {
276
+ this.#store.upsertOwnerScope(scope, this.#now());
277
+ }
278
+ catch (error) {
279
+ this.#callbacks.onError?.(error);
280
+ }
281
+ return existing === undefined;
282
+ }
283
+ listScopes() {
284
+ return [...this.#scopes.values()];
285
+ }
286
+ scheduleSync(delayMs = 15) {
287
+ if (this.#disposed)
288
+ return;
289
+ if (this.#syncInFlight !== null) {
290
+ this.#syncQueued = true;
291
+ return;
292
+ }
293
+ if (this.#syncTimer !== null)
294
+ return;
295
+ this.#syncTimer = setTimeout(() => {
296
+ this.#syncTimer = null;
297
+ void this.syncAll();
298
+ }, delayMs);
299
+ this.#syncTimer.unref?.();
300
+ }
301
+ async syncAll() {
302
+ if (this.#disposed)
303
+ return;
304
+ if (this.#syncInFlight !== null) {
305
+ this.#syncQueued = true;
306
+ await this.#syncInFlight;
307
+ return;
308
+ }
309
+ const run = async () => {
310
+ do {
311
+ this.#syncQueued = false;
312
+ if (this.#syncTimer !== null) {
313
+ clearTimeout(this.#syncTimer);
314
+ this.#syncTimer = null;
315
+ }
316
+ const delivery = this.#ctx.get('assistantDelivery', false);
317
+ if (delivery !== undefined) {
318
+ this.#discoverDeliveryScopes(delivery);
319
+ }
320
+ for (const scope of Array.from(this.#scopes.values())) {
321
+ if (this.#disposed)
322
+ return;
323
+ await this.syncScope(scope);
324
+ }
325
+ await this.#writeQueue.flush();
326
+ this.#assignedGlobalMemoryOwners.clear();
327
+ } while (this.#syncQueued && !this.#disposed);
328
+ };
329
+ this.#syncInFlight = run().finally(() => {
330
+ this.#syncInFlight = null;
331
+ });
332
+ await this.#syncInFlight;
333
+ }
334
+ async syncScope(scope) {
335
+ if (this.#disposed)
336
+ return;
337
+ try {
338
+ this.#syncPersonalMemoryScope(scope);
339
+ this.#syncGoalsScope(scope);
340
+ this.#syncWorkItemsScope(scope);
341
+ this.#syncAutomationsScope(scope);
342
+ this.#syncWikiScope(scope);
343
+ this.#syncSkillsScope(scope);
344
+ this.#syncEventTriggersScope(scope);
345
+ this.#syncDreamIdeasScope(scope);
346
+ const hadFg = this.#syncDeliveryEpisodesScope(scope);
347
+ await this.#writeQueue.flush();
348
+ if (this.#disposed)
349
+ return;
350
+ const hadEval = this.#syncEvaluationScope(scope);
351
+ await this.#writeQueue.flush();
352
+ if ((hadFg || hadEval) && !this.#disposed) {
353
+ this.#callbacks.onEpisodesSynced?.(scope);
354
+ }
355
+ }
356
+ catch (error) {
357
+ this.#callbacks.onError?.(error);
358
+ }
359
+ }
360
+ #discoverDeliveryScopes(delivery) {
361
+ if (typeof delivery.listActiveOwnerRouteScopes !== 'function')
362
+ return;
363
+ let routes;
364
+ try {
365
+ routes = delivery.listActiveOwnerRouteScopes();
366
+ }
367
+ catch {
368
+ return;
369
+ }
370
+ for (const route of routes) {
371
+ const principalDigest = computePrincipalDigest(route.principalId);
372
+ const ownerScopeKey = computeOwnerScopeKey({
373
+ mode: 'delivery',
374
+ principalDigest,
375
+ principalRecordId: route.principalRecordId,
376
+ principalVersion: route.principalVersion,
377
+ workspace: route.workspace,
378
+ agentPreset: route.agentPreset,
379
+ });
380
+ this.#routeAuthorities.set(ownerScopeKey, route);
381
+ this.registerScope({
382
+ mode: 'delivery',
383
+ ownerScopeKey,
384
+ principalId: route.principalId,
385
+ principalDigest,
386
+ principalRecordId: route.principalRecordId,
387
+ principalVersion: route.principalVersion,
388
+ workspace: route.workspace,
389
+ agentPreset: route.agentPreset,
390
+ authorityId: route.authorityId,
391
+ });
392
+ }
393
+ }
394
+ #enqueueUpsertWithEdges(scope, nodes, cursor, extra) {
395
+ const extraSynonyms = extra?.synonyms ?? [];
396
+ const extraDerivedRefs = extra?.extraDerivedRefs ?? [];
397
+ if (nodes.length === 0 &&
398
+ cursor === undefined &&
399
+ extraSynonyms.length === 0 &&
400
+ extraDerivedRefs.length === 0) {
401
+ return;
402
+ }
403
+ const existingPeers = nodes.length > 0
404
+ ? this.#store.loadEntityCandidateNodesForScope(scope.ownerScopeKey, MAX_ENTITY_PEERS_PER_UPSERT)
405
+ : [];
406
+ const combinedPeers = [
407
+ ...existingPeers,
408
+ ...nodes
409
+ .filter((n) => n.status !== 'withdrawn' && n.status !== 'suppressed' && n.sensitivity === 'private')
410
+ .map((n) => ({
411
+ id: n.id,
412
+ sourceVersion: n.sourceVersion,
413
+ ownerScopeKey: n.ownerScopeKey,
414
+ trust: n.trust,
415
+ entities: n.entities,
416
+ updatedAt: n.updatedAt,
417
+ })),
418
+ ];
419
+ const seenEdges = new Set();
420
+ const edges = [];
421
+ const derivedRefs = [];
422
+ const nowMs = this.#now();
423
+ for (const node of nodes) {
424
+ if (node.sensitivity !== 'private' || node.status === 'withdrawn' || node.status === 'suppressed') {
425
+ continue;
426
+ }
427
+ const built = buildSharedEntityEdges({
428
+ id: node.id,
429
+ sourceVersion: node.sourceVersion,
430
+ ownerScopeKey: node.ownerScopeKey,
431
+ trust: node.trust,
432
+ entities: node.entities,
433
+ updatedAt: node.updatedAt,
434
+ }, combinedPeers, { maxEdgesPerNode: MAX_SHARED_EDGES_PER_NODE, nowMs });
435
+ for (const edge of built.edges) {
436
+ if (seenEdges.has(edge.edgeId))
437
+ continue;
438
+ seenEdges.add(edge.edgeId);
439
+ edges.push(edge);
440
+ }
441
+ derivedRefs.push(...built.derivedRefs);
442
+ if (node.kind === 'episode' &&
443
+ node.sourcePlugin === 'assistant-delivery' &&
444
+ node.sourceRef.startsWith('foreground-turn:') &&
445
+ this.#callbacks.hebbianConfig?.enabled !== false) {
446
+ const hebbianCfg = this.#callbacks.hebbianConfig ?? DEFAULT_HEBBIAN_CONFIG;
447
+ const initWeight = clampEdgeWeight(hebbianCfg.initialHebbianWeight, hebbianCfg.weightMin, hebbianCfg.weightMax);
448
+ const taskExposures = this.#store.findExposuresByTaskOrSession(scope.ownerScopeKey, node.sourceRef);
449
+ for (const exp of taskExposures) {
450
+ if (exp.hop !== 0 ||
451
+ (!exp.strongUsed && !exp.weakUsed) ||
452
+ exp.corrected ||
453
+ exp.nodeId === node.id) {
454
+ continue;
455
+ }
456
+ const peerNode = this.#store.getNodeById(exp.nodeId);
457
+ if (peerNode === null ||
458
+ peerNode.status !== 'active' ||
459
+ peerNode.ownerScopeKey !== scope.ownerScopeKey ||
460
+ peerNode.sensitivity !== 'private') {
461
+ continue;
462
+ }
463
+ const [aId, bId] = node.id <= peerNode.id ? [node.id, peerNode.id] : [peerNode.id, node.id];
464
+ const edgeId = computeDeterministicEdgeId(aId, bId, 'hebbian');
465
+ if (!seenEdges.has(edgeId)) {
466
+ seenEdges.add(edgeId);
467
+ edges.push({
468
+ edgeId,
469
+ aId,
470
+ bId,
471
+ edgeType: 'hebbian',
472
+ weight: initWeight,
473
+ trust: node.trust === 'low' || peerNode.trust === 'low' ? 'low' : 'trusted',
474
+ reason: 'hebbian:episode-co-use',
475
+ useCount: 1,
476
+ lastUsedAt: nowMs,
477
+ createdAt: nowMs,
478
+ updatedAt: nowMs,
479
+ });
480
+ }
481
+ derivedRefs.push({
482
+ sourceNodeId: node.id,
483
+ sourceVersion: node.sourceVersion,
484
+ targetKind: 'edge',
485
+ targetId: edgeId,
486
+ }, {
487
+ sourceNodeId: peerNode.id,
488
+ sourceVersion: peerNode.sourceVersion,
489
+ targetKind: 'edge',
490
+ targetId: edgeId,
491
+ });
492
+ }
493
+ }
494
+ }
495
+ this.#writeQueue.enqueue({
496
+ kind: 'upsert-nodes',
497
+ nodes,
498
+ edges,
499
+ ...(extraSynonyms.length > 0 ? { synonyms: extraSynonyms } : {}),
500
+ derivedRefs: extraDerivedRefs.length > 0 ? [...derivedRefs, ...extraDerivedRefs] : derivedRefs,
501
+ ...(cursor === undefined ? {} : { cursor }),
502
+ });
503
+ }
504
+ #withdrawImmediate(input) {
505
+ const nodeIds = this.#store.listCascadeNodeIdsForSource(input.ownerScopeKey, input.sourcePlugin, input.sourceRef);
506
+ for (const nid of nodeIds) {
507
+ if (this.#assignedGlobalMemoryOwners.get(nid) === input.ownerScopeKey) {
508
+ this.#assignedGlobalMemoryOwners.delete(nid);
509
+ }
510
+ }
511
+ this.#writeQueue.markTombstoneSync({
512
+ nodeIds,
513
+ ownerScopeKey: input.ownerScopeKey,
514
+ sourcePlugin: input.sourcePlugin,
515
+ sourceRef: input.sourceRef,
516
+ });
517
+ this.#callbacks.onImmediateWithdraw({
518
+ ownerScopeKey: input.ownerScopeKey,
519
+ sourcePlugin: input.sourcePlugin,
520
+ sourceRef: input.sourceRef,
521
+ nodeIds,
522
+ });
523
+ this.#writeQueue.enqueue({
524
+ kind: 'withdraw-source',
525
+ ownerScopeKey: input.ownerScopeKey,
526
+ sourcePlugin: input.sourcePlugin,
527
+ sourceRef: input.sourceRef,
528
+ hardDelete: true,
529
+ recordWithdrawalTombstone: input.recordWithdrawalTombstone,
530
+ });
531
+ }
532
+ // ---------------------------------------------------------------------------
533
+ // Source (a): personal-memory
534
+ // ---------------------------------------------------------------------------
535
+ #toMemoryContext(scope) {
536
+ if (scope.mode === 'delivery' && scope.principalRecordId !== null && scope.principalVersion !== null) {
537
+ return {
538
+ workspace: scope.workspace,
539
+ agentPreset: scope.agentPreset,
540
+ namespace: {
541
+ mode: 'delivery',
542
+ principalDigest: scope.principalDigest,
543
+ principalRecordId: scope.principalRecordId,
544
+ principalVersion: scope.principalVersion,
545
+ },
546
+ };
547
+ }
548
+ return {
549
+ workspace: scope.workspace,
550
+ agentPreset: scope.agentPreset,
551
+ namespace: {
552
+ mode: 'headless',
553
+ principalDigest: scope.principalDigest,
554
+ lineageId: `headless:${scope.principalDigest}`,
555
+ lineageVersion: 1,
556
+ },
557
+ };
558
+ }
559
+ #memoryRecordMatchesScope(record, scope) {
560
+ if (record.namespace.mode === 'delivery') {
561
+ if (scope.mode !== 'delivery' ||
562
+ scope.principalDigest !== record.namespace.principalDigest ||
563
+ scope.principalRecordId !== record.namespace.principalRecordId ||
564
+ scope.principalVersion !== record.namespace.principalVersion) {
565
+ return false;
566
+ }
567
+ }
568
+ else if (record.namespace.mode === 'headless') {
569
+ if (scope.mode !== 'headless' ||
570
+ scope.principalDigest !== record.namespace.principalDigest) {
571
+ return false;
572
+ }
573
+ }
574
+ if (record.scope === 'workspace' && record.workspace !== scope.workspace)
575
+ return false;
576
+ if (record.owner === 'agent' && record.agentPreset !== scope.agentPreset)
577
+ return false;
578
+ return true;
579
+ }
580
+ #mapMemoryRecordToNode(record, scope) {
581
+ const baseId = `a:m-${record.id}`;
582
+ const pendingOwner = this.#assignedGlobalMemoryOwners.get(baseId);
583
+ const existingGlobal = pendingOwner === undefined ? this.#store.getNodeById(baseId) : null;
584
+ const claimedOwner = pendingOwner ?? existingGlobal?.ownerScopeKey;
585
+ const canUseBaseId = claimedOwner === undefined || claimedOwner === scope.ownerScopeKey;
586
+ if (canUseBaseId) {
587
+ this.#assignedGlobalMemoryOwners.set(baseId, scope.ownerScopeKey);
588
+ }
589
+ const nodeId = makeMemoryNodeId(record.id, scope, canUseBaseId);
590
+ const claimText = record.knowledge?.claim !== undefined
591
+ ? `${record.knowledge.claim.key}: ${record.knowledge.claim.value}`
592
+ : '';
593
+ const title = compactTitle(record.content);
594
+ const body = [record.content, claimText].filter((s) => s.length > 0).join('\n').slice(0, MAX_BODY_CHARS);
595
+ const combinedText = `${title}\n${body}`;
596
+ return {
597
+ id: nodeId,
598
+ kind: 'memory',
599
+ sourcePlugin: 'personal-memory',
600
+ sourceRef: `memory:${record.id}`,
601
+ sourceVersion: normalizeSourceVersion(record.version),
602
+ ownerScopeKey: scope.ownerScopeKey,
603
+ ownerMode: scope.mode,
604
+ principalDigest: scope.principalDigest,
605
+ principalRecordId: scope.mode === 'delivery' ? scope.principalRecordId : null,
606
+ principalVersion: scope.mode === 'delivery' ? scope.principalVersion : null,
607
+ scopeMode: record.scope,
608
+ workspace: scope.workspace,
609
+ agentPreset: scope.agentPreset,
610
+ trust: record.trust === 'external' ? 'low' : 'trusted',
611
+ sensitivity: record.sensitivity,
612
+ title,
613
+ body,
614
+ entities: extractEntities(combinedText),
615
+ tokens: tokenizeAssociationText(`${combinedText}\n${record.kind}`),
616
+ metadata: {
617
+ memoryOwner: record.owner,
618
+ memoryScope: record.scope,
619
+ },
620
+ expiresAt: record.expiresAt ?? null,
621
+ createdAt: record.createdAt,
622
+ updatedAt: record.updatedAt,
623
+ };
624
+ }
625
+ #syncPersonalMemoryScope(scope) {
626
+ const pm = this.#ctx.get('personalMemory', false);
627
+ if (pm === undefined || typeof pm.listActiveRecordsForAssociationSync !== 'function')
628
+ return;
629
+ const cursorRow = this.#store.getIngestCursor('personal-memory', scope.ownerScopeKey);
630
+ let afterUpdatedAt;
631
+ let afterId;
632
+ if (cursorRow !== null) {
633
+ try {
634
+ const parsed = JSON.parse(cursorRow.cursorJson);
635
+ if (typeof parsed.updatedAt === 'number')
636
+ afterUpdatedAt = parsed.updatedAt;
637
+ if (typeof parsed.id === 'string')
638
+ afterId = parsed.id;
639
+ }
640
+ catch {
641
+ // Ignore malformed cursor
642
+ }
643
+ }
644
+ const memCtx = this.#toMemoryContext(scope);
645
+ while (!this.#disposed) {
646
+ let records;
647
+ try {
648
+ records = pm.listActiveRecordsForAssociationSync(memCtx, {
649
+ ...(afterUpdatedAt === undefined ? {} : { afterUpdatedAt }),
650
+ ...(afterId === undefined ? {} : { afterId }),
651
+ limit: 100,
652
+ });
653
+ }
654
+ catch {
655
+ return;
656
+ }
657
+ if (records.length === 0)
658
+ break;
659
+ const upserts = [];
660
+ let lastUpdatedAt = afterUpdatedAt ?? 0;
661
+ let lastId = afterId ?? '';
662
+ for (const rec of records) {
663
+ lastUpdatedAt = rec.updatedAt;
664
+ lastId = rec.id;
665
+ if (rec.status !== 'active')
666
+ continue;
667
+ if (rec.expiresAt !== undefined && rec.expiresAt <= this.#now())
668
+ continue;
669
+ if (this.#store.isSourceWithdrawn(scope.ownerScopeKey, 'personal-memory', `memory:${rec.id}`)) {
670
+ continue;
671
+ }
672
+ upserts.push(this.#mapMemoryRecordToNode(rec, scope));
673
+ }
674
+ afterUpdatedAt = lastUpdatedAt;
675
+ afterId = lastId;
676
+ this.#enqueueUpsertWithEdges(scope, upserts, {
677
+ sourcePlugin: 'personal-memory',
678
+ scopeKey: scope.ownerScopeKey,
679
+ cursorJson: JSON.stringify({ updatedAt: lastUpdatedAt, id: lastId }),
680
+ });
681
+ if (records.length < 100)
682
+ break;
683
+ }
684
+ }
685
+ #handleMemoryRecordChange(event) {
686
+ if (this.#disposed)
687
+ return;
688
+ const rec = event.record;
689
+ const hebbianCfg = this.#callbacks.hebbianConfig;
690
+ for (const scope of this.#scopes.values()) {
691
+ if (!this.#memoryRecordMatchesScope(rec, scope))
692
+ continue;
693
+ if (event.op === 'remove' || rec.status === 'removed') {
694
+ this.#withdrawImmediate({
695
+ ownerScopeKey: scope.ownerScopeKey,
696
+ sourcePlugin: 'personal-memory',
697
+ sourceRef: `memory:${rec.id}`,
698
+ recordWithdrawalTombstone: event.reason === 'withdrawn',
699
+ });
700
+ }
701
+ else {
702
+ if (hebbianCfg?.enabled !== false &&
703
+ (event.op === 'replace' ||
704
+ (event.op === 'add' && typeof rec.supersedes === 'string' && rec.supersedes.length > 0))) {
705
+ const targetRecordIds = new Set();
706
+ if (event.op === 'replace') {
707
+ targetRecordIds.add(rec.id);
708
+ }
709
+ if (typeof rec.supersedes === 'string' && rec.supersedes.length > 0) {
710
+ targetRecordIds.add(rec.supersedes);
711
+ }
712
+ const nowMs = this.#now();
713
+ const lookbackMs = hebbianCfg?.correctionLookbackMs ?? DEFAULT_HEBBIAN_CONFIG.correctionLookbackMs;
714
+ const minExposedAt = Math.max(0, nowMs - lookbackMs);
715
+ for (const targetRecordId of targetRecordIds) {
716
+ const existingNode = this.#store.findNodeBySourceRef(scope.ownerScopeKey, 'personal-memory', `memory:${targetRecordId}`);
717
+ const targetNodeId = existingNode?.id ?? `a:m-${targetRecordId}`;
718
+ const latestExp = this.#store.findLatestUncorrectedMemoryExposure(scope.ownerScopeKey, targetNodeId, minExposedAt);
719
+ this.#writeQueue.enqueue({
720
+ kind: 'apply-hebbian-correction',
721
+ ownerScopeKey: scope.ownerScopeKey,
722
+ nodeId: targetNodeId,
723
+ minExposedAt,
724
+ nowMs,
725
+ ...(hebbianCfg === undefined ? {} : { hebbianConfig: hebbianCfg }),
726
+ });
727
+ if (latestExp !== null) {
728
+ this.#callbacks.onTaskCorrected?.({
729
+ ownerScopeKey: scope.ownerScopeKey,
730
+ taskId: latestExp.taskId,
731
+ nodeIds: [targetNodeId],
732
+ nowMs,
733
+ });
734
+ }
735
+ }
736
+ }
737
+ const node = this.#mapMemoryRecordToNode(rec, scope);
738
+ this.#enqueueUpsertWithEdges(scope, [node]);
739
+ }
740
+ }
741
+ }
742
+ // ---------------------------------------------------------------------------
743
+ // Source (b): assistant-goals
744
+ // ---------------------------------------------------------------------------
745
+ #mapGoalRecordToNode(record, scope) {
746
+ const title = compactTitle(`[${record.native.phase}] ${record.definition.objective}`);
747
+ const body = [
748
+ record.definition.objective,
749
+ record.checkpoint.nextStep,
750
+ ...record.checkpoint.blockers,
751
+ ]
752
+ .filter((s) => s.trim().length > 0)
753
+ .join('\n')
754
+ .slice(0, MAX_BODY_CHARS);
755
+ const combinedText = `${title}\n${body}`;
756
+ return {
757
+ id: `a:g-${record.id}`,
758
+ kind: 'goal',
759
+ sourcePlugin: 'assistant-goals',
760
+ sourceRef: `goal:${record.id}`,
761
+ sourceVersion: normalizeSourceVersion(`v${record.version}:def${record.definition.version}`),
762
+ ownerScopeKey: scope.ownerScopeKey,
763
+ ownerMode: scope.mode,
764
+ principalDigest: scope.principalDigest,
765
+ principalRecordId: scope.mode === 'delivery' ? scope.principalRecordId : null,
766
+ principalVersion: scope.mode === 'delivery' ? scope.principalVersion : null,
767
+ scopeMode: 'workspace',
768
+ workspace: scope.workspace,
769
+ agentPreset: scope.agentPreset,
770
+ trust: 'trusted',
771
+ sensitivity: 'private',
772
+ title,
773
+ body,
774
+ entities: extractEntities(combinedText),
775
+ tokens: tokenizeAssociationText(combinedText),
776
+ metadata: {
777
+ extra: {
778
+ goalId: record.id,
779
+ phase: record.native.phase,
780
+ },
781
+ },
782
+ createdAt: record.createdAt,
783
+ updatedAt: record.updatedAt,
784
+ };
785
+ }
786
+ #syncGoalsScope(scope) {
787
+ if (scope.mode !== 'delivery' ||
788
+ scope.principalRecordId === null ||
789
+ scope.principalVersion === null) {
790
+ return;
791
+ }
792
+ const goals = this.#ctx.get('assistantGoals', false);
793
+ if (goals === undefined || typeof goals.inspectOwnerGoals !== 'function')
794
+ return;
795
+ let records;
796
+ try {
797
+ records = goals.inspectOwnerGoals({
798
+ principalId: scope.principalId,
799
+ principalRecordId: scope.principalRecordId,
800
+ principalVersion: scope.principalVersion,
801
+ workspace: scope.workspace,
802
+ preset: scope.agentPreset,
803
+ }, 50);
804
+ }
805
+ catch {
806
+ return;
807
+ }
808
+ const upserts = [];
809
+ for (const rec of records) {
810
+ if (rec.native.phase === 'cleared')
811
+ continue;
812
+ if (this.#store.isSourceWithdrawn(scope.ownerScopeKey, 'assistant-goals', `goal:${rec.id}`)) {
813
+ continue;
814
+ }
815
+ upserts.push(this.#mapGoalRecordToNode(rec, scope));
816
+ }
817
+ this.#enqueueUpsertWithEdges(scope, upserts);
818
+ }
819
+ #handleGoalRecordChange(event) {
820
+ if (this.#disposed)
821
+ return;
822
+ const principalDigest = computePrincipalDigest(event.scope.principalId);
823
+ const ownerScopeKey = computeOwnerScopeKey({
824
+ mode: 'delivery',
825
+ principalDigest,
826
+ principalRecordId: event.scope.principalRecordId,
827
+ principalVersion: event.scope.principalVersion,
828
+ workspace: event.scope.workspace,
829
+ agentPreset: event.scope.preset,
830
+ });
831
+ const scope = this.#scopes.get(ownerScopeKey);
832
+ if (scope === undefined)
833
+ return;
834
+ if (event.clearedGoalId !== undefined || event.record?.native.phase === 'cleared') {
835
+ const goalId = event.clearedGoalId ?? event.record.id;
836
+ this.#withdrawImmediate({
837
+ ownerScopeKey,
838
+ sourcePlugin: 'assistant-goals',
839
+ sourceRef: `goal:${goalId}`,
840
+ recordWithdrawalTombstone: false,
841
+ });
842
+ return;
843
+ }
844
+ if (event.record !== undefined) {
845
+ this.#enqueueUpsertWithEdges(scope, [this.#mapGoalRecordToNode(event.record, scope)]);
846
+ }
847
+ }
848
+ // ---------------------------------------------------------------------------
849
+ // Source (c): assistant-work-items
850
+ // ---------------------------------------------------------------------------
851
+ #mapWorkItemToNode(item, scope) {
852
+ const title = compactTitle(`[${item.state}] ${item.title}`);
853
+ const body = [item.title, item.brief, item.lastReportSummary ?? '']
854
+ .filter((s) => s.trim().length > 0)
855
+ .join('\n')
856
+ .slice(0, MAX_BODY_CHARS);
857
+ const combinedText = `${title}\n${body}`;
858
+ return {
859
+ id: `a:w-${item.id}`,
860
+ kind: 'work-item',
861
+ sourcePlugin: 'assistant-work-items',
862
+ sourceRef: `work-item:${item.id}`,
863
+ sourceVersion: normalizeSourceVersion(`u${item.updatedAt}:r${item.revisionCount}:${item.state}`),
864
+ ownerScopeKey: scope.ownerScopeKey,
865
+ ownerMode: scope.mode,
866
+ principalDigest: scope.principalDigest,
867
+ principalRecordId: scope.mode === 'delivery' ? scope.principalRecordId : null,
868
+ principalVersion: scope.mode === 'delivery' ? scope.principalVersion : null,
869
+ scopeMode: 'workspace',
870
+ workspace: scope.workspace,
871
+ agentPreset: scope.agentPreset,
872
+ trust: item.observed ? 'low' : 'trusted',
873
+ sensitivity: 'private',
874
+ title,
875
+ body,
876
+ entities: extractEntities(combinedText),
877
+ tokens: tokenizeAssociationText(combinedText),
878
+ metadata: {
879
+ extra: {
880
+ workItemId: item.id,
881
+ state: item.state,
882
+ observed: item.observed,
883
+ },
884
+ },
885
+ createdAt: item.createdAt,
886
+ updatedAt: item.updatedAt,
887
+ };
888
+ }
889
+ #syncWorkItemsScope(scope) {
890
+ if (scope.mode !== 'delivery' ||
891
+ scope.principalRecordId === null ||
892
+ scope.principalVersion === null ||
893
+ scope.authorityId === undefined) {
894
+ return;
895
+ }
896
+ const workItems = this.#ctx.get('assistantWorkItems', false);
897
+ if (workItems === undefined || typeof workItems.inspectOwnerWorkItems !== 'function')
898
+ return;
899
+ let items;
900
+ try {
901
+ items = workItems.inspectOwnerWorkItems({
902
+ principalId: scope.principalId,
903
+ principalRecordId: scope.principalRecordId,
904
+ principalVersion: scope.principalVersion,
905
+ workspace: scope.workspace,
906
+ preset: scope.agentPreset,
907
+ ownerRouteId: scope.authorityId,
908
+ }, { limit: 100 });
909
+ }
910
+ catch {
911
+ return;
912
+ }
913
+ const upserts = [];
914
+ for (const item of items) {
915
+ if (item.state === 'dropped' && item.stateReason === 'signal-withdrawn') {
916
+ this.#withdrawImmediate({
917
+ ownerScopeKey: scope.ownerScopeKey,
918
+ sourcePlugin: 'assistant-work-items',
919
+ sourceRef: `work-item:${item.id}`,
920
+ recordWithdrawalTombstone: true,
921
+ });
922
+ continue;
923
+ }
924
+ if (this.#store.isSourceWithdrawn(scope.ownerScopeKey, 'assistant-work-items', `work-item:${item.id}`)) {
925
+ continue;
926
+ }
927
+ upserts.push(this.#mapWorkItemToNode(item, scope));
928
+ }
929
+ this.#enqueueUpsertWithEdges(scope, upserts);
930
+ }
931
+ #handleWorkItemChange(event) {
932
+ if (this.#disposed)
933
+ return;
934
+ const principalDigest = computePrincipalDigest(event.scope.principalId);
935
+ const ownerScopeKey = computeOwnerScopeKey({
936
+ mode: 'delivery',
937
+ principalDigest,
938
+ principalRecordId: event.scope.principalRecordId,
939
+ principalVersion: event.scope.principalVersion,
940
+ workspace: event.scope.workspace,
941
+ agentPreset: event.scope.preset,
942
+ });
943
+ const scope = this.#scopes.get(ownerScopeKey);
944
+ if (scope === undefined)
945
+ return;
946
+ if (event.op === 'withdraw') {
947
+ this.#withdrawImmediate({
948
+ ownerScopeKey,
949
+ sourcePlugin: 'assistant-work-items',
950
+ sourceRef: `work-item:${event.itemId}`,
951
+ recordWithdrawalTombstone: true,
952
+ });
953
+ return;
954
+ }
955
+ this.#syncWorkItemsScope(scope);
956
+ }
957
+ // ---------------------------------------------------------------------------
958
+ // Source (d): assistant-automations
959
+ // ---------------------------------------------------------------------------
960
+ #mapAutomationToNode(record, scope) {
961
+ const def = record.definition;
962
+ const scheduleDesc = JSON.stringify(def.schedule);
963
+ const execDesc = 'execution' in def && def.execution?.kind === 'host'
964
+ ? `runbook:${def.execution.runbookId}`
965
+ : def.prompt ?? '';
966
+ const title = compactTitle(`[${record.status}] ${def.name}`);
967
+ const body = `${def.name}\n${scheduleDesc}\n${execDesc}`.slice(0, MAX_BODY_CHARS);
968
+ const combinedText = `${title}\n${body}`;
969
+ return {
970
+ id: `a:au-${record.id}`,
971
+ kind: 'automation',
972
+ sourcePlugin: 'assistant-automations',
973
+ sourceRef: `automation:${record.id}`,
974
+ sourceVersion: normalizeSourceVersion(`v${record.version}:${record.status}`),
975
+ ownerScopeKey: scope.ownerScopeKey,
976
+ ownerMode: scope.mode,
977
+ principalDigest: scope.principalDigest,
978
+ principalRecordId: scope.mode === 'delivery' ? scope.principalRecordId : null,
979
+ principalVersion: scope.mode === 'delivery' ? scope.principalVersion : null,
980
+ scopeMode: 'workspace',
981
+ workspace: scope.workspace,
982
+ agentPreset: scope.agentPreset,
983
+ trust: 'trusted',
984
+ sensitivity: 'private',
985
+ title,
986
+ body,
987
+ entities: extractEntities(combinedText),
988
+ tokens: tokenizeAssociationText(combinedText),
989
+ metadata: {
990
+ extra: {
991
+ automationId: record.id,
992
+ status: record.status,
993
+ },
994
+ },
995
+ createdAt: record.createdAt,
996
+ updatedAt: record.updatedAt,
997
+ };
998
+ }
999
+ #syncAutomationsScope(scope) {
1000
+ const automations = this.#ctx.get('assistantAutomations', false);
1001
+ if (automations === undefined || typeof automations.inspectOwnerAutomations !== 'function') {
1002
+ return;
1003
+ }
1004
+ let records;
1005
+ try {
1006
+ records = automations.inspectOwnerAutomations({
1007
+ principalId: scope.principalId,
1008
+ workspace: scope.workspace,
1009
+ preset: scope.agentPreset,
1010
+ limit: 100,
1011
+ });
1012
+ }
1013
+ catch {
1014
+ return;
1015
+ }
1016
+ const upserts = [];
1017
+ for (const rec of records) {
1018
+ if (rec.status === 'deleted') {
1019
+ this.#withdrawImmediate({
1020
+ ownerScopeKey: scope.ownerScopeKey,
1021
+ sourcePlugin: 'assistant-automations',
1022
+ sourceRef: `automation:${rec.id}`,
1023
+ recordWithdrawalTombstone: true,
1024
+ });
1025
+ continue;
1026
+ }
1027
+ if (this.#store.isSourceWithdrawn(scope.ownerScopeKey, 'assistant-automations', `automation:${rec.id}`)) {
1028
+ continue;
1029
+ }
1030
+ upserts.push(this.#mapAutomationToNode(rec, scope));
1031
+ }
1032
+ this.#enqueueUpsertWithEdges(scope, upserts);
1033
+ }
1034
+ #handleAutomationChange(event) {
1035
+ if (this.#disposed)
1036
+ return;
1037
+ for (const scope of this.#scopes.values()) {
1038
+ if (scope.workspace !== event.workspace ||
1039
+ scope.agentPreset !== event.agentPreset ||
1040
+ scope.principalId !== event.principal) {
1041
+ continue;
1042
+ }
1043
+ if (event.status === 'deleted') {
1044
+ this.#withdrawImmediate({
1045
+ ownerScopeKey: scope.ownerScopeKey,
1046
+ sourcePlugin: 'assistant-automations',
1047
+ sourceRef: `automation:${event.automationId}`,
1048
+ recordWithdrawalTombstone: true,
1049
+ });
1050
+ }
1051
+ else {
1052
+ this.#syncAutomationsScope(scope);
1053
+ }
1054
+ }
1055
+ }
1056
+ // ---------------------------------------------------------------------------
1057
+ // Source (d.1): personal-wiki
1058
+ // ---------------------------------------------------------------------------
1059
+ #mapWikiPageToNode(page, scope) {
1060
+ const scope8 = scope.ownerScopeKey.slice(0, 8);
1061
+ const rawId = `a:wk-${scope8}-${page.metadata.id}`;
1062
+ const nodeId = rawId.length <= 128 ? rawId : `a:wk-${scope8}-${sha256Hex(page.metadata.id).slice(0, 24)}`;
1063
+ const title = compactTitle(page.metadata.title);
1064
+ const body = page.body.slice(0, MAX_BODY_CHARS);
1065
+ const combinedText = `${title}\n${body}\n${page.metadata.tags.join(' ')}\n${page.metadata.aliases.join(' ')}`;
1066
+ const extracted = extractEntities(combinedText);
1067
+ const entitySet = new Set(extracted);
1068
+ const normalizedTitle = normalizeEntityKey(page.metadata.title);
1069
+ if (normalizedTitle !== null)
1070
+ entitySet.add(normalizedTitle);
1071
+ for (const tag of page.metadata.tags) {
1072
+ const k = normalizeEntityKey(tag);
1073
+ if (k !== null)
1074
+ entitySet.add(k);
1075
+ }
1076
+ for (const alias of page.metadata.aliases) {
1077
+ const k = normalizeEntityKey(alias);
1078
+ if (k !== null)
1079
+ entitySet.add(k);
1080
+ }
1081
+ const entities = [...entitySet];
1082
+ const parsedCreated = Date.parse(page.metadata.created);
1083
+ const parsedUpdated = Date.parse(page.metadata.updated);
1084
+ const nowMs = this.#now();
1085
+ const createdAt = Number.isFinite(parsedCreated) && parsedCreated >= 0 ? parsedCreated : nowMs;
1086
+ const updatedAt = Number.isFinite(parsedUpdated) && parsedUpdated >= 0 ? parsedUpdated : nowMs;
1087
+ const sourceVersion = normalizeSourceVersion(page.revision);
1088
+ const synonyms = [];
1089
+ const derivedRefs = [];
1090
+ if (page.metadata.status !== 'draft' && page.metadata.aliases.length > 0) {
1091
+ const canonical = normalizedTitle ?? entities[0] ?? null;
1092
+ if (canonical !== null) {
1093
+ for (const alias of page.metadata.aliases) {
1094
+ const surface = normalizeEntityKey(alias);
1095
+ if (surface === null || surface === canonical)
1096
+ continue;
1097
+ const synId = computeDeterministicSynonymId(scope.ownerScopeKey, surface, canonical);
1098
+ synonyms.push({
1099
+ id: synId,
1100
+ ownerScopeKey: scope.ownerScopeKey,
1101
+ surface,
1102
+ canonicalEntity: canonical,
1103
+ sourceNodeId: nodeId,
1104
+ trust: 'trusted',
1105
+ createdAt: updatedAt,
1106
+ });
1107
+ derivedRefs.push({
1108
+ sourceNodeId: nodeId,
1109
+ sourceVersion,
1110
+ targetKind: 'synonym',
1111
+ targetId: synId,
1112
+ });
1113
+ }
1114
+ }
1115
+ }
1116
+ const node = {
1117
+ id: nodeId,
1118
+ kind: 'wiki',
1119
+ sourcePlugin: 'personal-wiki',
1120
+ sourceRef: `wiki:${page.metadata.id}`,
1121
+ sourceVersion,
1122
+ ownerScopeKey: scope.ownerScopeKey,
1123
+ ownerMode: scope.mode,
1124
+ principalDigest: scope.principalDigest,
1125
+ principalRecordId: scope.mode === 'delivery' ? scope.principalRecordId : null,
1126
+ principalVersion: scope.mode === 'delivery' ? scope.principalVersion : null,
1127
+ scopeMode: 'user-global',
1128
+ workspace: scope.workspace,
1129
+ agentPreset: scope.agentPreset,
1130
+ trust: page.metadata.status === 'draft' ? 'low' : 'trusted',
1131
+ sensitivity: 'private',
1132
+ title,
1133
+ body,
1134
+ entities,
1135
+ tokens: tokenizeAssociationText(combinedText),
1136
+ metadata: {
1137
+ extra: {
1138
+ pageId: page.metadata.id,
1139
+ relativePath: page.relativePath,
1140
+ status: page.metadata.status,
1141
+ authority: page.metadata.authority,
1142
+ type: page.metadata.type,
1143
+ aliases: [...page.metadata.aliases],
1144
+ },
1145
+ },
1146
+ createdAt,
1147
+ updatedAt,
1148
+ };
1149
+ return { node, synonyms, derivedRefs };
1150
+ }
1151
+ #syncWikiScope(scope) {
1152
+ const wiki = this.#ctx.get('personalWiki', false);
1153
+ if (wiki === undefined || typeof wiki.inspectHostPages !== 'function')
1154
+ return;
1155
+ let pages;
1156
+ try {
1157
+ pages = wiki.inspectHostPages({ includeArchived: false });
1158
+ }
1159
+ catch {
1160
+ return;
1161
+ }
1162
+ const activeRefs = new Set();
1163
+ const upserts = [];
1164
+ const synonyms = [];
1165
+ const extraDerivedRefs = [];
1166
+ for (const page of pages) {
1167
+ if (page.metadata.status === 'archived')
1168
+ continue;
1169
+ const sourceRef = `wiki:${page.metadata.id}`;
1170
+ activeRefs.add(sourceRef);
1171
+ if (this.#store.isSourceWithdrawn(scope.ownerScopeKey, 'personal-wiki', sourceRef)) {
1172
+ continue;
1173
+ }
1174
+ const mapped = this.#mapWikiPageToNode(page, scope);
1175
+ upserts.push(mapped.node);
1176
+ synonyms.push(...mapped.synonyms);
1177
+ extraDerivedRefs.push(...mapped.derivedRefs);
1178
+ }
1179
+ for (const existingRef of this.#store.listActiveSourceRefsForPlugin(scope.ownerScopeKey, 'personal-wiki')) {
1180
+ if (!activeRefs.has(existingRef)) {
1181
+ this.#withdrawImmediate({
1182
+ ownerScopeKey: scope.ownerScopeKey,
1183
+ sourcePlugin: 'personal-wiki',
1184
+ sourceRef: existingRef,
1185
+ recordWithdrawalTombstone: false,
1186
+ });
1187
+ }
1188
+ }
1189
+ this.#enqueueUpsertWithEdges(scope, upserts, undefined, {
1190
+ synonyms,
1191
+ extraDerivedRefs,
1192
+ });
1193
+ }
1194
+ #handleWikiPageChange(event) {
1195
+ if (this.#disposed)
1196
+ return;
1197
+ if (event.kind === 'archived' ||
1198
+ event.kind === 'deleted' ||
1199
+ event.page?.metadata.status === 'archived') {
1200
+ for (const scope of this.#scopes.values()) {
1201
+ this.#withdrawImmediate({
1202
+ ownerScopeKey: scope.ownerScopeKey,
1203
+ sourcePlugin: 'personal-wiki',
1204
+ sourceRef: `wiki:${event.pageId}`,
1205
+ recordWithdrawalTombstone: false,
1206
+ });
1207
+ }
1208
+ return;
1209
+ }
1210
+ this.scheduleSync();
1211
+ }
1212
+ // ---------------------------------------------------------------------------
1213
+ // Source (d.2): assistant-skills
1214
+ // ---------------------------------------------------------------------------
1215
+ #syncSkillsScope(scope) {
1216
+ if (scope.mode !== 'delivery' ||
1217
+ scope.principalRecordId === null ||
1218
+ scope.principalVersion === null) {
1219
+ return;
1220
+ }
1221
+ const skills = this.#ctx.get('assistantSkills', false);
1222
+ if (skills === undefined || typeof skills.inspectOwnerActiveSkills !== 'function')
1223
+ return;
1224
+ let activeSkills;
1225
+ try {
1226
+ activeSkills = skills.inspectOwnerActiveSkills({
1227
+ principalId: scope.principalId,
1228
+ principalRecordId: scope.principalRecordId,
1229
+ principalVersion: scope.principalVersion,
1230
+ workspace: scope.workspace,
1231
+ preset: scope.agentPreset,
1232
+ });
1233
+ }
1234
+ catch {
1235
+ return;
1236
+ }
1237
+ const activeRefs = new Set();
1238
+ const upserts = [];
1239
+ const nowMs = this.#now();
1240
+ for (const skill of activeSkills) {
1241
+ if (skill.retired === true)
1242
+ continue;
1243
+ const sourceRef = `skill:${skill.name}`;
1244
+ activeRefs.add(sourceRef);
1245
+ if (this.#store.isSourceWithdrawn(scope.ownerScopeKey, 'assistant-skills', sourceRef)) {
1246
+ continue;
1247
+ }
1248
+ const toolNames = [
1249
+ ...new Set(skill.steps.map((s) => s.toolName).filter((t) => t.trim().length > 0)),
1250
+ ];
1251
+ const title = compactTitle(`[skill] ${skill.name}: ${skill.description}`);
1252
+ const body = [
1253
+ skill.name,
1254
+ skill.description,
1255
+ skill.inputs.length > 0 ? `inputs: ${skill.inputs.map((i) => i.name).join(', ')}` : '',
1256
+ toolNames.length > 0 ? `tools: ${toolNames.join(' -> ')}` : '',
1257
+ ]
1258
+ .filter((s) => s.length > 0)
1259
+ .join('\n')
1260
+ .slice(0, MAX_BODY_CHARS);
1261
+ const combinedText = `${title}\n${body}`;
1262
+ const entitySet = new Set(extractEntities(combinedText));
1263
+ const normName = normalizeEntityKey(skill.name);
1264
+ if (normName !== null)
1265
+ entitySet.add(normName);
1266
+ for (const tool of toolNames) {
1267
+ const normTool = normalizeEntityKey(tool);
1268
+ if (normTool !== null)
1269
+ entitySet.add(normTool);
1270
+ }
1271
+ const skillVersionRaw = skill.version;
1272
+ const definitionDigest = skill.definitionDigest;
1273
+ const sourceVersion = typeof skillVersionRaw === 'number' && Number.isSafeInteger(skillVersionRaw)
1274
+ ? skillVersionRaw
1275
+ : normalizeSourceVersion(definitionDigest ?? 1);
1276
+ const createdAtRaw = skill.createdAt;
1277
+ const updatedAtRaw = skill.updatedAt;
1278
+ const createdAt = typeof createdAtRaw === 'number' ? createdAtRaw : nowMs;
1279
+ const updatedAt = typeof updatedAtRaw === 'number' ? updatedAtRaw : nowMs;
1280
+ upserts.push({
1281
+ id: `a:sk-${scope.ownerScopeKey.slice(0, 8)}-${sha256Hex(skill.name).slice(0, 24)}`,
1282
+ kind: 'skill',
1283
+ sourcePlugin: 'assistant-skills',
1284
+ sourceRef,
1285
+ sourceVersion,
1286
+ ownerScopeKey: scope.ownerScopeKey,
1287
+ ownerMode: scope.mode,
1288
+ principalDigest: scope.principalDigest,
1289
+ principalRecordId: scope.principalRecordId,
1290
+ principalVersion: scope.principalVersion,
1291
+ scopeMode: 'workspace',
1292
+ workspace: scope.workspace,
1293
+ agentPreset: scope.agentPreset,
1294
+ trust: 'trusted',
1295
+ sensitivity: 'private',
1296
+ title,
1297
+ body,
1298
+ entities: [...entitySet],
1299
+ tokens: tokenizeAssociationText(combinedText),
1300
+ metadata: {
1301
+ ...(toolNames.length > 0 ? { toolNames } : {}),
1302
+ extra: {
1303
+ skillName: skill.name,
1304
+ version: sourceVersion,
1305
+ },
1306
+ },
1307
+ createdAt,
1308
+ updatedAt,
1309
+ });
1310
+ }
1311
+ for (const existingRef of this.#store.listActiveSourceRefsForPlugin(scope.ownerScopeKey, 'assistant-skills')) {
1312
+ if (!activeRefs.has(existingRef)) {
1313
+ this.#withdrawImmediate({
1314
+ ownerScopeKey: scope.ownerScopeKey,
1315
+ sourcePlugin: 'assistant-skills',
1316
+ sourceRef: existingRef,
1317
+ recordWithdrawalTombstone: false,
1318
+ });
1319
+ }
1320
+ }
1321
+ this.#enqueueUpsertWithEdges(scope, upserts);
1322
+ }
1323
+ // ---------------------------------------------------------------------------
1324
+ // Source (d.3): event-triggers
1325
+ // ---------------------------------------------------------------------------
1326
+ #mapOutboxEventToNode(item, scope) {
1327
+ const rawKey = `${item.triggerId}\0${item.eventId}`;
1328
+ const scope8 = scope.ownerScopeKey.slice(0, 8);
1329
+ const nodeId = `a:ev-${scope8}-${sha256Hex(rawKey).slice(0, 24)}`;
1330
+ const candidateRef = `event:${item.triggerId}:${item.eventId}`;
1331
+ const sourceRef = candidateRef.length <= 512 ? candidateRef : `event:${sha256Hex(rawKey).slice(0, 32)}`;
1332
+ const sanitizedTitle = sanitizeEventSummaryText(item.title);
1333
+ const sanitizedSummary = sanitizeEventSummaryText(item.summary);
1334
+ const title = compactTitle(`[event:${item.triggerKind}] ${sanitizedTitle}`);
1335
+ const body = `${sanitizedTitle}\n${sanitizedSummary}`.slice(0, MAX_BODY_CHARS);
1336
+ const combinedText = `${title}\n${sanitizedSummary}\n${item.entities.join(' ')}`;
1337
+ const entitySet = new Set(extractEntities(combinedText));
1338
+ for (const ent of item.entities) {
1339
+ const k = normalizeEntityKey(sanitizeEventSummaryText(ent));
1340
+ if (k !== null)
1341
+ entitySet.add(k);
1342
+ }
1343
+ const ttlMs = item.ttlMs !== undefined && item.ttlMs > 0 ? item.ttlMs : null;
1344
+ const expiresAt = ttlMs !== null ? item.occurredAt + ttlMs : null;
1345
+ return {
1346
+ id: nodeId,
1347
+ kind: 'event',
1348
+ sourcePlugin: 'event-triggers',
1349
+ sourceRef,
1350
+ sourceVersion: Math.max(1, item.sequence),
1351
+ ownerScopeKey: scope.ownerScopeKey,
1352
+ ownerMode: scope.mode,
1353
+ principalDigest: scope.principalDigest,
1354
+ principalRecordId: scope.principalRecordId,
1355
+ principalVersion: scope.principalVersion,
1356
+ scopeMode: 'workspace',
1357
+ workspace: scope.workspace,
1358
+ agentPreset: scope.agentPreset,
1359
+ trust: 'low',
1360
+ sensitivity: 'private',
1361
+ title,
1362
+ body,
1363
+ entities: [...entitySet],
1364
+ tokens: tokenizeAssociationText(combinedText),
1365
+ metadata: {
1366
+ extra: {
1367
+ triggerId: item.triggerId,
1368
+ triggerKind: item.triggerKind,
1369
+ automationId: item.automationId,
1370
+ eventId: item.eventId,
1371
+ sequence: item.sequence,
1372
+ envelopeDigest: item.envelopeDigest,
1373
+ observationDigest: item.observationDigest,
1374
+ },
1375
+ },
1376
+ ttlMs,
1377
+ expiresAt,
1378
+ createdAt: item.occurredAt,
1379
+ updatedAt: item.occurredAt,
1380
+ };
1381
+ }
1382
+ #syncEventTriggersScope(scope) {
1383
+ if (scope.mode !== 'delivery' ||
1384
+ scope.principalRecordId === null ||
1385
+ scope.principalVersion === null) {
1386
+ return;
1387
+ }
1388
+ const triggers = this.#ctx.get('eventTriggers', false);
1389
+ if (triggers === undefined)
1390
+ return;
1391
+ const ownerScope = {
1392
+ principalId: scope.principalId,
1393
+ principalRecordId: scope.principalRecordId,
1394
+ principalVersion: scope.principalVersion,
1395
+ workspace: scope.workspace,
1396
+ preset: scope.agentPreset,
1397
+ };
1398
+ const nowMs = this.#now();
1399
+ if (typeof triggers.inspectOwnerSources === 'function') {
1400
+ let activeSources;
1401
+ try {
1402
+ activeSources = triggers.inspectOwnerSources(ownerScope);
1403
+ }
1404
+ catch {
1405
+ activeSources = [];
1406
+ }
1407
+ const activeTriggerIds = new Set(activeSources.map((s) => s.triggerId));
1408
+ for (const existingNode of this.#store.listActiveNodesBySourcePlugin(scope.ownerScopeKey, 'event-triggers')) {
1409
+ const triggerId = existingNode.metadata.extra?.triggerId;
1410
+ const isExpired = existingNode.expiresAt !== null && existingNode.expiresAt <= nowMs;
1411
+ if (isExpired ||
1412
+ (typeof triggerId === 'string' && !activeTriggerIds.has(triggerId))) {
1413
+ this.#withdrawImmediate({
1414
+ ownerScopeKey: scope.ownerScopeKey,
1415
+ sourcePlugin: 'event-triggers',
1416
+ sourceRef: existingNode.sourceRef,
1417
+ recordWithdrawalTombstone: false,
1418
+ });
1419
+ }
1420
+ }
1421
+ }
1422
+ if (typeof triggers.inspectOwnerOutboxEvents !== 'function')
1423
+ return;
1424
+ const cursorRow = this.#store.getIngestCursor('event-triggers', scope.ownerScopeKey);
1425
+ let afterSequence = 0;
1426
+ if (cursorRow !== null) {
1427
+ try {
1428
+ const parsed = JSON.parse(cursorRow.cursorJson);
1429
+ if (typeof parsed.afterSequence === 'number' &&
1430
+ Number.isSafeInteger(parsed.afterSequence) &&
1431
+ parsed.afterSequence >= 0) {
1432
+ afterSequence = parsed.afterSequence;
1433
+ }
1434
+ }
1435
+ catch {
1436
+ afterSequence = 0;
1437
+ }
1438
+ }
1439
+ while (!this.#disposed) {
1440
+ let page;
1441
+ try {
1442
+ page = triggers.inspectOwnerOutboxEvents({
1443
+ scope: ownerScope,
1444
+ afterSequence,
1445
+ limit: 100,
1446
+ });
1447
+ }
1448
+ catch {
1449
+ return;
1450
+ }
1451
+ if (page.items.length === 0)
1452
+ break;
1453
+ const upserts = [];
1454
+ for (const item of page.items) {
1455
+ const expiresAt = item.ttlMs !== undefined && item.ttlMs > 0 ? item.occurredAt + item.ttlMs : null;
1456
+ if (expiresAt !== null && expiresAt <= nowMs)
1457
+ continue;
1458
+ const mapped = this.#mapOutboxEventToNode(item, scope);
1459
+ if (this.#store.isSourceWithdrawn(scope.ownerScopeKey, 'event-triggers', mapped.sourceRef)) {
1460
+ continue;
1461
+ }
1462
+ upserts.push(mapped);
1463
+ }
1464
+ afterSequence = page.nextSequence;
1465
+ this.#enqueueUpsertWithEdges(scope, upserts, {
1466
+ sourcePlugin: 'event-triggers',
1467
+ scopeKey: scope.ownerScopeKey,
1468
+ cursorJson: JSON.stringify({ afterSequence: page.nextSequence }),
1469
+ });
1470
+ if (!page.hasMore)
1471
+ break;
1472
+ }
1473
+ }
1474
+ // ---------------------------------------------------------------------------
1475
+ // Source (d.4): assistant-dreaming ideas
1476
+ // ---------------------------------------------------------------------------
1477
+ #syncDreamIdeasScope(scope) {
1478
+ const dreaming = this.#ctx.get('assistantDreaming', false);
1479
+ if (dreaming === undefined || typeof dreaming.inspectIdeas !== 'function')
1480
+ return;
1481
+ let rawIdeas;
1482
+ try {
1483
+ rawIdeas = dreaming.inspectIdeas(200);
1484
+ }
1485
+ catch {
1486
+ return;
1487
+ }
1488
+ if (rawIdeas.length === 0)
1489
+ return;
1490
+ const ideas = rawIdeas.map((idea) => ({
1491
+ id: idea.id,
1492
+ lane: idea.lane,
1493
+ runId: idea.runId,
1494
+ createdAt: idea.createdAt,
1495
+ dayKey: idea.dayKey,
1496
+ state: idea.state,
1497
+ summary: idea.summary,
1498
+ detail: idea.detail,
1499
+ evidenceRefs: [...idea.evidenceRefs],
1500
+ }));
1501
+ const cfg = this.#callbacks.dreamingConfig ?? DEFAULT_ASSOCIATION_DREAMING_CONFIG;
1502
+ const projected = projectDreamIdeasToAssociation(ideas, scope, cfg, this.#now());
1503
+ for (const withdrawal of projected.withdrawals) {
1504
+ if (this.#store.findNodeBySourceRef(withdrawal.ownerScopeKey, withdrawal.sourcePlugin, withdrawal.sourceRef) !== null) {
1505
+ this.#withdrawImmediate({
1506
+ ownerScopeKey: withdrawal.ownerScopeKey,
1507
+ sourcePlugin: withdrawal.sourcePlugin,
1508
+ sourceRef: withdrawal.sourceRef,
1509
+ recordWithdrawalTombstone: true,
1510
+ });
1511
+ }
1512
+ }
1513
+ const upserts = projected.upserts.filter((node) => !this.#store.isSourceWithdrawn(scope.ownerScopeKey, node.sourcePlugin, node.sourceRef));
1514
+ if (upserts.length > 0) {
1515
+ this.#enqueueUpsertWithEdges(scope, upserts);
1516
+ }
1517
+ }
1518
+ // ---------------------------------------------------------------------------
1519
+ // Source (e): Episodes (Delivery foreground + Evaluation projections)
1520
+ // ---------------------------------------------------------------------------
1521
+ #mapDeliveryEpisodeToNode(content, scope) {
1522
+ const src = content.source;
1523
+ const toolNames = this.#callbacks.consumeSessionToolNames?.(src.binding.sessionId) ?? [];
1524
+ const inputFirstLine = content.input.text.split(/\r?\n/u).find((l) => l.trim().length > 0) ?? content.input.text;
1525
+ const title = compactTitle(`[turn] ${inputFirstLine}`);
1526
+ const toolSuffix = toolNames.length > 0 ? `\ntools: ${toolNames.join(', ')}` : '';
1527
+ const body = `${content.input.text}\n---\n${content.reply.text}${toolSuffix}`.slice(0, MAX_BODY_CHARS);
1528
+ const combinedText = `${title}\n${content.input.text}\n${content.reply.text}`;
1529
+ const completedAt = src.execution.completedAt ?? this.#now();
1530
+ const srcOutcomeId = src.outcomeId;
1531
+ return {
1532
+ id: `a:e-fg-${src.inboxId}`,
1533
+ kind: 'episode',
1534
+ sourcePlugin: 'assistant-delivery',
1535
+ sourceRef: `foreground-turn:${src.inboxId}`,
1536
+ sourceVersion: normalizeSourceVersion(content.sourceDigest.slice(0, 16)),
1537
+ ownerScopeKey: scope.ownerScopeKey,
1538
+ ownerMode: scope.mode,
1539
+ principalDigest: scope.principalDigest,
1540
+ principalRecordId: scope.mode === 'delivery' ? scope.principalRecordId : null,
1541
+ principalVersion: scope.mode === 'delivery' ? scope.principalVersion : null,
1542
+ scopeMode: 'workspace',
1543
+ workspace: scope.workspace,
1544
+ agentPreset: scope.agentPreset,
1545
+ trust: 'trusted',
1546
+ sensitivity: 'private',
1547
+ title,
1548
+ body,
1549
+ entities: extractEntities(combinedText),
1550
+ tokens: tokenizeAssociationText(combinedText),
1551
+ metadata: {
1552
+ ...(toolNames.length > 0 ? { toolNames: [...toolNames] } : {}),
1553
+ extra: {
1554
+ inboxId: src.inboxId,
1555
+ sessionId: src.binding.sessionId,
1556
+ ...(typeof srcOutcomeId === 'string' && srcOutcomeId.length > 0
1557
+ ? { outcomeId: srcOutcomeId }
1558
+ : {}),
1559
+ },
1560
+ },
1561
+ createdAt: completedAt,
1562
+ updatedAt: completedAt,
1563
+ };
1564
+ }
1565
+ #syncDeliveryEpisodesScope(scope) {
1566
+ if (scope.mode !== 'delivery' ||
1567
+ scope.principalRecordId === null ||
1568
+ scope.principalVersion === null ||
1569
+ scope.authorityId === undefined) {
1570
+ return false;
1571
+ }
1572
+ const route = this.#routeAuthorities.get(scope.ownerScopeKey);
1573
+ if (route === undefined)
1574
+ return false;
1575
+ const delivery = this.#ctx.get('assistantDelivery', false);
1576
+ if (delivery === undefined ||
1577
+ typeof delivery.listOwnerForegroundTaskSources !== 'function' ||
1578
+ typeof delivery.withOwnerForegroundTaskSourcesFence !== 'function') {
1579
+ return false;
1580
+ }
1581
+ const cursorRow = this.#store.getIngestCursor('delivery-foreground', scope.ownerScopeKey);
1582
+ let after;
1583
+ if (cursorRow !== null) {
1584
+ try {
1585
+ after = JSON.parse(cursorRow.cursorJson);
1586
+ }
1587
+ catch {
1588
+ after = undefined;
1589
+ }
1590
+ }
1591
+ const ownerScopeInput = {
1592
+ authorityId: route.authorityId,
1593
+ principalId: scope.principalId,
1594
+ workspace: scope.workspace,
1595
+ agentPreset: scope.agentPreset,
1596
+ expectedOwner: {
1597
+ authorityHash: route.authorityHash,
1598
+ principalRecordId: scope.principalRecordId,
1599
+ principalVersion: scope.principalVersion,
1600
+ },
1601
+ };
1602
+ let syncedAny = false;
1603
+ while (!this.#disposed) {
1604
+ let page;
1605
+ try {
1606
+ page = delivery.listOwnerForegroundTaskSources({
1607
+ ...ownerScopeInput,
1608
+ ...(after === undefined ? {} : { after }),
1609
+ limit: 50,
1610
+ });
1611
+ }
1612
+ catch {
1613
+ return syncedAny;
1614
+ }
1615
+ if (page.items.length === 0)
1616
+ break;
1617
+ const eligibleRefs = page.items
1618
+ .filter((src) => !this.#store.isSourceWithdrawn(scope.ownerScopeKey, 'assistant-delivery', `foreground-turn:${src.inboxId}`))
1619
+ .map((src) => ({
1620
+ inboxId: src.inboxId,
1621
+ expectedSourceDigest: src.sourceDigest,
1622
+ }));
1623
+ const upserts = [];
1624
+ if (eligibleRefs.length > 0) {
1625
+ try {
1626
+ delivery.withOwnerForegroundTaskSourcesFence({
1627
+ ...ownerScopeInput,
1628
+ sources: eligibleRefs,
1629
+ }, (contents) => {
1630
+ for (const item of contents) {
1631
+ if (item === undefined)
1632
+ continue;
1633
+ upserts.push(this.#mapDeliveryEpisodeToNode(item, scope));
1634
+ }
1635
+ });
1636
+ }
1637
+ catch {
1638
+ // If owner route rotated or fence failed, skip this batch cleanly
1639
+ return syncedAny;
1640
+ }
1641
+ }
1642
+ if (upserts.length > 0) {
1643
+ syncedAny = true;
1644
+ }
1645
+ after = page.nextCursor;
1646
+ this.#enqueueUpsertWithEdges(scope, upserts, {
1647
+ sourcePlugin: 'delivery-foreground',
1648
+ scopeKey: scope.ownerScopeKey,
1649
+ cursorJson: JSON.stringify(page.nextCursor),
1650
+ });
1651
+ if (!page.hasMore)
1652
+ break;
1653
+ }
1654
+ return syncedAny;
1655
+ }
1656
+ #syncEvaluationScope(scope) {
1657
+ if (scope.mode !== 'delivery' ||
1658
+ scope.principalRecordId === null ||
1659
+ scope.principalVersion === null) {
1660
+ return false;
1661
+ }
1662
+ const evaluation = this.#ctx.get('assistantEvaluation', false);
1663
+ if (evaluation === undefined ||
1664
+ typeof evaluation.createHostScope !== 'function' ||
1665
+ typeof evaluation.listTrustedTaskLearningProjections !== 'function') {
1666
+ return false;
1667
+ }
1668
+ const verifier = this.#ctx.get('assistantVerifier', false);
1669
+ const holdoutSeedKey = this.#callbacks.holdoutSeedKey ?? null;
1670
+ const holdoutRateBps = this.#callbacks.holdoutRateBps;
1671
+ const hostScope = evaluation.createHostScope({
1672
+ workspace: scope.workspace,
1673
+ preset: scope.agentPreset,
1674
+ });
1675
+ const cursorScopeKey = `${scope.ownerScopeKey}:eval`;
1676
+ const cursorRow = this.#store.getIngestCursor('evaluation-canonical', cursorScopeKey);
1677
+ let after;
1678
+ if (cursorRow !== null) {
1679
+ try {
1680
+ after = JSON.parse(cursorRow.cursorJson);
1681
+ }
1682
+ catch {
1683
+ after = undefined;
1684
+ }
1685
+ }
1686
+ let syncedAny = false;
1687
+ while (!this.#disposed) {
1688
+ let page;
1689
+ try {
1690
+ page = evaluation.listTrustedTaskLearningProjections({
1691
+ scope: hostScope,
1692
+ ...(after === undefined ? {} : { after }),
1693
+ limit: 100,
1694
+ });
1695
+ }
1696
+ catch {
1697
+ return syncedAny;
1698
+ }
1699
+ if (page.items.length === 0)
1700
+ break;
1701
+ const upserts = [];
1702
+ for (const entry of page.items) {
1703
+ const receipt = entry.receipt;
1704
+ const outcomeId = receipt.objective?.outcomeId ??
1705
+ receipt.projection.evidenceOutcomeId ??
1706
+ receipt.triggerOutcomeId;
1707
+ const revision = outcomeId !== undefined && typeof evaluation.inspectTrustedTaskOwnerRevision === 'function'
1708
+ ? evaluation.inspectTrustedTaskOwnerRevision({
1709
+ scope: hostScope,
1710
+ outcomeId,
1711
+ principalRecordId: scope.principalRecordId,
1712
+ principalVersion: scope.principalVersion,
1713
+ })
1714
+ : undefined;
1715
+ const { subjectKind, subjectRef, disposition } = receipt.projection;
1716
+ const evalTaskId = `${subjectKind}:${subjectRef}`;
1717
+ // Case 1: Explicit owner withdrawal (action === 'withdraw') -> correction -β then hard cascade delete + tombstone
1718
+ if (revision?.action === 'withdraw') {
1719
+ this.#triggerEvaluationCorrection(scope, receipt, revision);
1720
+ withdrawEvalPoolTask(this.#store.database, scope.ownerScopeKey, evalTaskId, {
1721
+ updatedAt: this.#now(),
1722
+ });
1723
+ if (subjectKind === 'foreground-turn') {
1724
+ this.#withdrawImmediate({
1725
+ ownerScopeKey: scope.ownerScopeKey,
1726
+ sourcePlugin: 'assistant-delivery',
1727
+ sourceRef: `foreground-turn:${subjectRef}`,
1728
+ recordWithdrawalTombstone: true,
1729
+ });
1730
+ }
1731
+ this.#withdrawImmediate({
1732
+ ownerScopeKey: scope.ownerScopeKey,
1733
+ sourcePlugin: 'assistant-evaluation',
1734
+ sourceRef: evalTaskId,
1735
+ recordWithdrawalTombstone: true,
1736
+ });
1737
+ syncedAny = true;
1738
+ continue;
1739
+ }
1740
+ // Case 2: Conflict retraction (disposition === 'retract' without 'withdraw')
1741
+ if (disposition === 'retract') {
1742
+ this.#triggerEvaluationCorrection(scope, receipt, revision);
1743
+ retractEvalPoolTask(this.#store.database, scope.ownerScopeKey, evalTaskId, {
1744
+ updatedAt: this.#now(),
1745
+ projectionVersion: receipt.projection.version,
1746
+ projectionDigest: receipt.projection.digest,
1747
+ });
1748
+ const objStatus = receipt.objective?.status ?? 'retracted';
1749
+ if (subjectKind === 'foreground-turn') {
1750
+ const fgNode = this.#store.findNodeBySourceRef(scope.ownerScopeKey, 'assistant-delivery', `foreground-turn:${subjectRef}`);
1751
+ if (fgNode !== null) {
1752
+ const res = this.#store.suppressNodeConflict({
1753
+ ownerScopeKey: scope.ownerScopeKey,
1754
+ sourcePlugin: 'assistant-delivery',
1755
+ sourceRef: `foreground-turn:${subjectRef}`,
1756
+ objectiveStatus: objStatus,
1757
+ nowMs: this.#now(),
1758
+ });
1759
+ this.#callbacks.onConflictSuppressed({
1760
+ nodeIds: [...res.deletedNodeIds, ...res.suppressedNodeIds],
1761
+ });
1762
+ }
1763
+ }
1764
+ else {
1765
+ const evalNode = this.#store.findNodeBySourceRef(scope.ownerScopeKey, 'assistant-evaluation', evalTaskId);
1766
+ if (evalNode !== null) {
1767
+ const res = this.#store.suppressNodeConflict({
1768
+ ownerScopeKey: scope.ownerScopeKey,
1769
+ sourcePlugin: 'assistant-evaluation',
1770
+ sourceRef: evalTaskId,
1771
+ objectiveStatus: objStatus,
1772
+ nowMs: this.#now(),
1773
+ });
1774
+ this.#callbacks.onConflictSuppressed({
1775
+ nodeIds: [...res.deletedNodeIds, ...res.suppressedNodeIds],
1776
+ });
1777
+ }
1778
+ }
1779
+ syncedAny = true;
1780
+ continue;
1781
+ }
1782
+ // Case 3: Upsert non-foreground or verified episode
1783
+ if (disposition === 'upsert') {
1784
+ const verified = this.#verifyEvaluationProjectionOwner(receipt, scope);
1785
+ if (!verified)
1786
+ continue;
1787
+ this.#triggerEvaluationCorrection(scope, receipt, revision);
1788
+ const existingFg = subjectKind === 'foreground-turn'
1789
+ ? this.#store.findNodeBySourceRef(scope.ownerScopeKey, 'assistant-delivery', `foreground-turn:${subjectRef}`)
1790
+ : null;
1791
+ const mappedEvalNode = existingFg !== null ||
1792
+ this.#store.isSourceWithdrawn(scope.ownerScopeKey, 'assistant-evaluation', evalTaskId)
1793
+ ? null
1794
+ : this.#mapEvaluationReceiptToNode(receipt, scope);
1795
+ const poolEntities = existingFg?.entities ?? mappedEvalNode?.entities ?? [];
1796
+ const poolToolNames = existingFg?.metadata.toolNames ?? mappedEvalNode?.metadata?.toolNames ?? [];
1797
+ if (holdoutSeedKey !== null) {
1798
+ upsertEvalPoolFromReceipt(this.#store.database, {
1799
+ ownerScopeKey: scope.ownerScopeKey,
1800
+ receipt,
1801
+ holdoutSeedKey,
1802
+ ...(holdoutRateBps === undefined ? {} : { holdoutRateBps }),
1803
+ taskId: evalTaskId,
1804
+ ...(poolEntities.length > 0 ? { entities: poolEntities } : {}),
1805
+ ...(poolToolNames.length > 0 ? { toolNames: poolToolNames } : {}),
1806
+ ...(verifier === undefined ? {} : { assistantVerifier: verifier }),
1807
+ nowMs: this.#now(),
1808
+ });
1809
+ }
1810
+ if (existingFg !== null) {
1811
+ if (typeof outcomeId === 'string' && outcomeId.length > 0) {
1812
+ this.#store.attachNodeOutcomeId(existingFg.id, outcomeId);
1813
+ }
1814
+ syncedAny = true;
1815
+ continue;
1816
+ }
1817
+ if (mappedEvalNode !== null) {
1818
+ upserts.push(mappedEvalNode);
1819
+ syncedAny = true;
1820
+ }
1821
+ }
1822
+ }
1823
+ after = page.nextCursor;
1824
+ this.#enqueueUpsertWithEdges(scope, upserts, {
1825
+ sourcePlugin: 'evaluation-canonical',
1826
+ scopeKey: cursorScopeKey,
1827
+ cursorJson: JSON.stringify(page.nextCursor),
1828
+ });
1829
+ if (!page.hasMore)
1830
+ break;
1831
+ }
1832
+ return syncedAny;
1833
+ }
1834
+ #resolveEvaluationSessionId(receipt, scope) {
1835
+ const { subjectKind, subjectRef } = receipt.projection;
1836
+ const evidenceLists = [receipt.objective?.evidence, receipt.execution?.evidence];
1837
+ for (const list of evidenceLists) {
1838
+ if (!Array.isArray(list))
1839
+ continue;
1840
+ for (const item of list) {
1841
+ if ((item.kind === 'session' || item.kind === 'session-id') && item.ref.length > 0) {
1842
+ return item.ref;
1843
+ }
1844
+ }
1845
+ }
1846
+ const existing = this.#store.findNodeBySourceRef(scope.ownerScopeKey, 'assistant-evaluation', `${subjectKind}:${subjectRef}`);
1847
+ const extraSession = existing?.metadata.extra?.sessionId;
1848
+ if (typeof extraSession === 'string' && extraSession.length > 0) {
1849
+ return extraSession;
1850
+ }
1851
+ return subjectRef.length > 0 ? subjectRef : null;
1852
+ }
1853
+ #triggerEvaluationCorrection(scope, receipt, revision) {
1854
+ const hebbianCfg = this.#callbacks.hebbianConfig;
1855
+ if (hebbianCfg?.enabled === false)
1856
+ return;
1857
+ if (!classifyEvaluationCorrection(receipt, revision))
1858
+ return;
1859
+ const { subjectKind, subjectRef } = receipt.projection;
1860
+ const taskId = `${subjectKind}:${subjectRef}`;
1861
+ const sessionId = subjectKind !== 'foreground-turn'
1862
+ ? this.#resolveEvaluationSessionId(receipt, scope)
1863
+ : null;
1864
+ const nowMs = this.#now();
1865
+ const matchedExposures = this.#store.findExposuresByTaskOrSession(scope.ownerScopeKey, taskId, sessionId);
1866
+ const uncorrectedNodeIds = matchedExposures
1867
+ .filter((e) => !e.corrected)
1868
+ .map((e) => e.nodeId);
1869
+ this.#writeQueue.enqueue({
1870
+ kind: 'apply-hebbian-correction',
1871
+ ownerScopeKey: scope.ownerScopeKey,
1872
+ taskId,
1873
+ ...(sessionId === null ? {} : { sessionId }),
1874
+ nowMs,
1875
+ ...(hebbianCfg === undefined ? {} : { hebbianConfig: hebbianCfg }),
1876
+ });
1877
+ if (uncorrectedNodeIds.length > 0) {
1878
+ const resolvedTaskId = matchedExposures[0]?.taskId ?? taskId;
1879
+ this.#callbacks.onTaskCorrected?.({
1880
+ ownerScopeKey: scope.ownerScopeKey,
1881
+ taskId: resolvedTaskId,
1882
+ nodeIds: uncorrectedNodeIds,
1883
+ nowMs,
1884
+ });
1885
+ }
1886
+ }
1887
+ #verifyEvaluationProjectionOwner(receipt, scope) {
1888
+ const { subjectKind, subjectRef } = receipt.projection;
1889
+ const delivery = this.#ctx.get('assistantDelivery', false);
1890
+ if (subjectKind === 'foreground-turn') {
1891
+ const route = this.#routeAuthorities.get(scope.ownerScopeKey);
1892
+ if (route === undefined ||
1893
+ scope.principalRecordId === null ||
1894
+ scope.principalVersion === null ||
1895
+ delivery === undefined ||
1896
+ typeof delivery.inspectOwnerForegroundTaskSource !== 'function') {
1897
+ return false;
1898
+ }
1899
+ try {
1900
+ const inspected = delivery.inspectOwnerForegroundTaskSource({
1901
+ authorityId: route.authorityId,
1902
+ principalId: scope.principalId,
1903
+ workspace: scope.workspace,
1904
+ agentPreset: scope.agentPreset,
1905
+ expectedOwner: {
1906
+ authorityHash: route.authorityHash,
1907
+ principalRecordId: scope.principalRecordId,
1908
+ principalVersion: scope.principalVersion,
1909
+ },
1910
+ inboxId: subjectRef,
1911
+ });
1912
+ return inspected !== undefined;
1913
+ }
1914
+ catch {
1915
+ return false;
1916
+ }
1917
+ }
1918
+ if (subjectKind === 'work-item') {
1919
+ const outcomeId = receipt.objective?.outcomeId ?? receipt.triggerOutcomeId;
1920
+ if (scope.authorityId === undefined ||
1921
+ delivery === undefined ||
1922
+ typeof delivery.inspectOwnerWorkItemLearningTask !== 'function') {
1923
+ return false;
1924
+ }
1925
+ try {
1926
+ const task = delivery.inspectOwnerWorkItemLearningTask({
1927
+ authorityId: scope.authorityId,
1928
+ principalId: scope.principalId,
1929
+ workspace: scope.workspace,
1930
+ agentPreset: scope.agentPreset,
1931
+ outcomeId,
1932
+ });
1933
+ return task !== undefined;
1934
+ }
1935
+ catch {
1936
+ return false;
1937
+ }
1938
+ }
1939
+ if (subjectKind === 'automation-run') {
1940
+ const automations = this.#ctx.get('assistantAutomations', false);
1941
+ if (automations === undefined || typeof automations.inspectOwnerAutomations !== 'function') {
1942
+ return false;
1943
+ }
1944
+ try {
1945
+ const list = automations.inspectOwnerAutomations({
1946
+ principalId: scope.principalId,
1947
+ workspace: scope.workspace,
1948
+ preset: scope.agentPreset,
1949
+ limit: 200,
1950
+ });
1951
+ // Require at least one owner automation (and match automationId if embedded in situation/ref)
1952
+ return list.some((a) => subjectRef.includes(a.id) || receipt.situation.includes(a.id));
1953
+ }
1954
+ catch {
1955
+ return false;
1956
+ }
1957
+ }
1958
+ if (subjectKind === 'goal-outcome' || subjectKind === 'goal-step') {
1959
+ if (scope.principalRecordId === null || scope.principalVersion === null)
1960
+ return false;
1961
+ const goals = this.#ctx.get('assistantGoals', false);
1962
+ if (goals === undefined || typeof goals.inspectOwnerGoals !== 'function')
1963
+ return false;
1964
+ try {
1965
+ const list = goals.inspectOwnerGoals({
1966
+ principalId: scope.principalId,
1967
+ principalRecordId: scope.principalRecordId,
1968
+ principalVersion: scope.principalVersion,
1969
+ workspace: scope.workspace,
1970
+ preset: scope.agentPreset,
1971
+ }, 50);
1972
+ return list.some((g) => subjectRef.includes(g.id) || receipt.situation.includes(g.id));
1973
+ }
1974
+ catch {
1975
+ return false;
1976
+ }
1977
+ }
1978
+ return false;
1979
+ }
1980
+ #mapEvaluationReceiptToNode(receipt, scope) {
1981
+ const { subjectKind, subjectRef, version, digest } = receipt.projection;
1982
+ const execStatus = receipt.execution?.status ?? 'unknown';
1983
+ const objStatus = receipt.objective?.status ?? 'unknown';
1984
+ const title = compactTitle(`[${subjectKind}] ${receipt.situation}`);
1985
+ const body = `${receipt.situation}\nexecution: ${execStatus}\nobjective: ${objStatus}`.slice(0, MAX_BODY_CHARS);
1986
+ const combinedText = `${title}\n${receipt.situation}`;
1987
+ const occurredAt = receipt.objective?.occurredAt ?? receipt.execution?.occurredAt ?? this.#now();
1988
+ const outcomeId = receipt.objective?.outcomeId ??
1989
+ receipt.projection.evidenceOutcomeId ??
1990
+ receipt.triggerOutcomeId;
1991
+ return {
1992
+ id: `a:e-${subjectKind}-${subjectRef}`,
1993
+ kind: 'episode',
1994
+ sourcePlugin: 'assistant-evaluation',
1995
+ sourceRef: `${subjectKind}:${subjectRef}`,
1996
+ sourceVersion: normalizeSourceVersion(`v${version}:${digest.slice(0, 12)}`),
1997
+ ownerScopeKey: scope.ownerScopeKey,
1998
+ ownerMode: scope.mode,
1999
+ principalDigest: scope.principalDigest,
2000
+ principalRecordId: scope.mode === 'delivery' ? scope.principalRecordId : null,
2001
+ principalVersion: scope.mode === 'delivery' ? scope.principalVersion : null,
2002
+ scopeMode: 'workspace',
2003
+ workspace: scope.workspace,
2004
+ agentPreset: scope.agentPreset,
2005
+ trust: 'trusted',
2006
+ sensitivity: 'private',
2007
+ title,
2008
+ body,
2009
+ entities: extractEntities(combinedText),
2010
+ tokens: tokenizeAssociationText(combinedText),
2011
+ metadata: {
2012
+ objectiveStatus: objStatus,
2013
+ extra: {
2014
+ subjectKind,
2015
+ subjectRef,
2016
+ ...(typeof outcomeId === 'string' && outcomeId.length > 0 ? { outcomeId } : {}),
2017
+ },
2018
+ },
2019
+ createdAt: occurredAt,
2020
+ updatedAt: occurredAt,
2021
+ };
2022
+ }
2023
+ }
2024
+ //# sourceMappingURL=sources.js.map