@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.
- package/LICENSE +21 -0
- package/README.md +133 -2
- package/cordis.patch.yml +26 -0
- package/lib/aho-corasick.d.ts +41 -0
- package/lib/aho-corasick.d.ts.map +1 -0
- package/lib/aho-corasick.js +352 -0
- package/lib/aho-corasick.js.map +1 -0
- package/lib/bm25.d.ts +17 -0
- package/lib/bm25.d.ts.map +1 -0
- package/lib/bm25.js +73 -0
- package/lib/bm25.js.map +1 -0
- package/lib/clustering.d.ts +161 -0
- package/lib/clustering.d.ts.map +1 -0
- package/lib/clustering.js +1043 -0
- package/lib/clustering.js.map +1 -0
- package/lib/config.d.ts +67 -0
- package/lib/config.d.ts.map +1 -0
- package/lib/config.js +834 -0
- package/lib/config.js.map +1 -0
- package/lib/cues.d.ts +134 -0
- package/lib/cues.d.ts.map +1 -0
- package/lib/cues.js +793 -0
- package/lib/cues.js.map +1 -0
- package/lib/dreaming.d.ts +211 -0
- package/lib/dreaming.d.ts.map +1 -0
- package/lib/dreaming.js +1418 -0
- package/lib/dreaming.js.map +1 -0
- package/lib/entities.d.ts +18 -0
- package/lib/entities.d.ts.map +1 -0
- package/lib/entities.js +111 -0
- package/lib/entities.js.map +1 -0
- package/lib/eval-pool.d.ts +111 -0
- package/lib/eval-pool.d.ts.map +1 -0
- package/lib/eval-pool.js +392 -0
- package/lib/eval-pool.js.map +1 -0
- package/lib/hebbian.d.ts +54 -0
- package/lib/hebbian.d.ts.map +1 -0
- package/lib/hebbian.js +226 -0
- package/lib/hebbian.js.map +1 -0
- package/lib/holdout.d.ts +18 -0
- package/lib/holdout.d.ts.map +1 -0
- package/lib/holdout.js +97 -0
- package/lib/holdout.js.map +1 -0
- package/lib/hot-path.d.ts +8 -0
- package/lib/hot-path.d.ts.map +1 -0
- package/lib/hot-path.js +503 -0
- package/lib/hot-path.js.map +1 -0
- package/lib/hysteresis.d.ts +39 -0
- package/lib/hysteresis.d.ts.map +1 -0
- package/lib/hysteresis.js +297 -0
- package/lib/hysteresis.js.map +1 -0
- package/lib/index-memory.d.ts +112 -0
- package/lib/index-memory.d.ts.map +1 -0
- package/lib/index-memory.js +391 -0
- package/lib/index-memory.js.map +1 -0
- package/lib/index.d.ts +37 -0
- package/lib/index.d.ts.map +1 -0
- package/lib/index.js +37 -0
- package/lib/index.js.map +1 -0
- package/lib/intake-signal.d.ts +158 -0
- package/lib/intake-signal.d.ts.map +1 -0
- package/lib/intake-signal.js +366 -0
- package/lib/intake-signal.js.map +1 -0
- package/lib/param-tuning.d.ts +302 -0
- package/lib/param-tuning.d.ts.map +1 -0
- package/lib/param-tuning.js +1743 -0
- package/lib/param-tuning.js.map +1 -0
- package/lib/service.d.ts +164 -0
- package/lib/service.d.ts.map +1 -0
- package/lib/service.js +2071 -0
- package/lib/service.js.map +1 -0
- package/lib/sources.d.ts +42 -0
- package/lib/sources.d.ts.map +1 -0
- package/lib/sources.js +2024 -0
- package/lib/sources.js.map +1 -0
- package/lib/sqlite.d.ts +88 -0
- package/lib/sqlite.d.ts.map +1 -0
- package/lib/sqlite.js +1815 -0
- package/lib/sqlite.js.map +1 -0
- package/lib/tokenize.d.ts +4 -0
- package/lib/tokenize.d.ts.map +1 -0
- package/lib/tokenize.js +35 -0
- package/lib/tokenize.js.map +1 -0
- package/lib/tools.d.ts +27 -0
- package/lib/tools.d.ts.map +1 -0
- package/lib/tools.js +126 -0
- package/lib/tools.js.map +1 -0
- package/lib/types.d.ts +551 -0
- package/lib/types.d.ts.map +1 -0
- package/lib/types.js +163 -0
- package/lib/types.js.map +1 -0
- package/lib/version.d.ts +2 -0
- package/lib/version.d.ts.map +1 -0
- package/lib/version.js +2 -0
- package/lib/version.js.map +1 -0
- package/lib/web-fetch.d.ts +95 -0
- package/lib/web-fetch.d.ts.map +1 -0
- package/lib/web-fetch.js +833 -0
- package/lib/web-fetch.js.map +1 -0
- package/lib/web-learning-interests.d.ts +42 -0
- package/lib/web-learning-interests.d.ts.map +1 -0
- package/lib/web-learning-interests.js +4344 -0
- package/lib/web-learning-interests.js.map +1 -0
- package/lib/web-learning-runner.d.ts +43 -0
- package/lib/web-learning-runner.d.ts.map +1 -0
- package/lib/web-learning-runner.js +322 -0
- package/lib/web-learning-runner.js.map +1 -0
- package/lib/web-learning-worker.d.ts +75 -0
- package/lib/web-learning-worker.d.ts.map +1 -0
- package/lib/web-learning-worker.js +367 -0
- package/lib/web-learning-worker.js.map +1 -0
- package/lib/web-learning.d.ts +161 -0
- package/lib/web-learning.d.ts.map +1 -0
- package/lib/web-learning.js +912 -0
- package/lib/web-learning.js.map +1 -0
- package/lib/write-queue.d.ts +42 -0
- package/lib/write-queue.d.ts.map +1 -0
- package/lib/write-queue.js +439 -0
- package/lib/write-queue.js.map +1 -0
- package/package.json +156 -3
package/lib/service.js
ADDED
|
@@ -0,0 +1,2071 @@
|
|
|
1
|
+
import { Service } from '@deepseek-ai/cordis';
|
|
2
|
+
import { clusterEpisodes, detectImplicitSignals, listImplicitSignals as queryImplicitSignals, listSkillCandidates as querySkillCandidates, reportImplicitSignalsToEvaluation, } from './clustering.js';
|
|
3
|
+
import { normalizeConfig, Config } from './config.js';
|
|
4
|
+
import { listDreamRuns as queryDreamRuns, runDreamingPass, sweepExpiredDreamingNodes, } from './dreaming.js';
|
|
5
|
+
import { listEvalPool as queryEvalPool, } from './eval-pool.js';
|
|
6
|
+
import { emitAssociationIntakeSignal, listIntakeSignals as queryIntakeSignals, } from './intake-signal.js';
|
|
7
|
+
import { assembleStepCues, consumeSessionTurnToolNames, evictNodesFromAgentState, foldStepSessionActivation, getOrCreateAgentAssocState, handleAgentStatus, handleInboxClaimed, handleInboxDiscarded, handleSessionEvent, recordTaskExposures, recordTurnTaskId, resolveOwnerScope, resolveTaskId, wipeStateOnOwnerRotation, } from './cues.js';
|
|
8
|
+
import { detectWeakUseNodes, selectHop0CoActivationTargets, } from './hebbian.js';
|
|
9
|
+
import { resolveHoldoutSeedKey, evaluateHoldout } from './holdout.js';
|
|
10
|
+
import { runHotPathQuery } from './hot-path.js';
|
|
11
|
+
import { applyHysteresisAndFormat } from './hysteresis.js';
|
|
12
|
+
import { buildMemoryIndex, rebuildMemoryIndexEdges, } from './index-memory.js';
|
|
13
|
+
import { AssociationParamTuningLedger, toHotPathProfile, } from './param-tuning.js';
|
|
14
|
+
import { AssociationSourceManager } from './sources.js';
|
|
15
|
+
import { AssociationStore, openAssociationDatabase, } from './sqlite.js';
|
|
16
|
+
import { AssistantAssociationError, registerAssociationTools, } from './tools.js';
|
|
17
|
+
import { WEB_LEARNING_SOURCE_PLUGIN, } from './types.js';
|
|
18
|
+
import { canonicalizeWebSourceUrl, computeWebSourceRef, getWebLearningBudgetUsage as queryWebLearningBudgetUsage, listWebLearningFetches as queryWebLearningFetches, listWebLearningRuns as queryWebLearningRuns, runWebLearningPass, withdrawWebSourceByUrl, } from './web-learning.js';
|
|
19
|
+
import {} from './web-learning-runner.js';
|
|
20
|
+
import { AssociationWriteQueue, loadGraphSnapshotChunked } from './write-queue.js';
|
|
21
|
+
const COLD_START_SYNC_THRESHOLD = 2_000;
|
|
22
|
+
export class AssistantAssociationService extends Service {
|
|
23
|
+
static inject = ['assistantPolicy'];
|
|
24
|
+
static Config = Config;
|
|
25
|
+
assocConfig;
|
|
26
|
+
policy;
|
|
27
|
+
assocStore;
|
|
28
|
+
writeQueue;
|
|
29
|
+
sourceManager;
|
|
30
|
+
paramLedger;
|
|
31
|
+
holdoutSeedKey;
|
|
32
|
+
agentStates = new WeakMap();
|
|
33
|
+
activeAgents = new Set();
|
|
34
|
+
headlessPrincipals = new WeakMap();
|
|
35
|
+
toolNamesBySessionTurn = new Map();
|
|
36
|
+
lastActivityByScope = new Map();
|
|
37
|
+
pendingTasks = new Set();
|
|
38
|
+
inFlightWebLearningScopes = new Set();
|
|
39
|
+
activeIndex = null;
|
|
40
|
+
ready = false;
|
|
41
|
+
indexBuildEpoch = 0;
|
|
42
|
+
invalidationGeneration = 0;
|
|
43
|
+
rebuildInFlight = null;
|
|
44
|
+
rebuildQueued = false;
|
|
45
|
+
active = true;
|
|
46
|
+
effectAbortController = new AbortController();
|
|
47
|
+
hotPathClock;
|
|
48
|
+
nowClock = () => Date.now();
|
|
49
|
+
constructor(ctx, input = {}) {
|
|
50
|
+
super(ctx, 'assistantAssociation');
|
|
51
|
+
const normalized = normalizeConfig(input);
|
|
52
|
+
this.assocConfig = normalized;
|
|
53
|
+
const policy = ctx.get('assistantPolicy');
|
|
54
|
+
if (policy === undefined) {
|
|
55
|
+
throw new Error('assistant-association: assistantPolicy service is required');
|
|
56
|
+
}
|
|
57
|
+
this.policy = policy;
|
|
58
|
+
if (!normalized.enabled) {
|
|
59
|
+
this.assocStore = null;
|
|
60
|
+
this.writeQueue = null;
|
|
61
|
+
this.sourceManager = null;
|
|
62
|
+
this.paramLedger = null;
|
|
63
|
+
this.holdoutSeedKey = null;
|
|
64
|
+
ctx.effect(() => () => {
|
|
65
|
+
this.active = false;
|
|
66
|
+
this.effectAbortController.abort();
|
|
67
|
+
}, 'assistant-association.disabled');
|
|
68
|
+
return;
|
|
69
|
+
}
|
|
70
|
+
const db = openAssociationDatabase(normalized.databasePath);
|
|
71
|
+
const store = new AssociationStore(db);
|
|
72
|
+
this.assocStore = store;
|
|
73
|
+
try {
|
|
74
|
+
this.holdoutSeedKey = resolveHoldoutSeedKey({
|
|
75
|
+
databasePath: normalized.databasePath,
|
|
76
|
+
holdoutSeed: normalized.holdoutSeed,
|
|
77
|
+
holdoutSeedPath: normalized.holdoutSeedPath,
|
|
78
|
+
});
|
|
79
|
+
}
|
|
80
|
+
catch (error) {
|
|
81
|
+
store.close();
|
|
82
|
+
throw error;
|
|
83
|
+
}
|
|
84
|
+
const pt = normalized.paramTuning;
|
|
85
|
+
this.paramLedger = new AssociationParamTuningLedger(store.database, {
|
|
86
|
+
baseConfig: {
|
|
87
|
+
decayHalfLifeMs: normalized.decayHalfLifeMs,
|
|
88
|
+
maxHops: normalized.maxHops,
|
|
89
|
+
maxItems: normalized.maxItems,
|
|
90
|
+
minItems: normalized.minItems,
|
|
91
|
+
hysteresisDelta: normalized.hysteresisDelta,
|
|
92
|
+
sourceWeights: normalized.sourceWeights,
|
|
93
|
+
hopTopN: normalized.hopTopN,
|
|
94
|
+
maxFanoutPerNode: normalized.maxFanoutPerNode,
|
|
95
|
+
hotPathBudgetMs: normalized.hotPathBudgetMs,
|
|
96
|
+
},
|
|
97
|
+
policy: {
|
|
98
|
+
minSample: pt.minSample,
|
|
99
|
+
minStepSample: pt.minStepSample,
|
|
100
|
+
minSourceSample: pt.minSourceSample,
|
|
101
|
+
minHoldoutSamples: pt.minHoldoutSamples,
|
|
102
|
+
maxTimeoutRatePpm: pt.maxTimeoutRatePpm,
|
|
103
|
+
lowUsageRatePpm: pt.lowUsageRatePpm,
|
|
104
|
+
healthyUsageRatePpm: pt.healthyUsageRatePpm,
|
|
105
|
+
highCorrectionRatePpm: pt.highCorrectionRatePpm,
|
|
106
|
+
noisySourceRatePpm: pt.noisySourceRatePpm,
|
|
107
|
+
regressionMarginPpm: pt.regressionMarginPpm,
|
|
108
|
+
timeoutMarginPpm: pt.timeoutMarginPpm,
|
|
109
|
+
maxTimeoutMarginPpm: pt.maxTimeoutMarginPpm,
|
|
110
|
+
usageDropMarginPpm: pt.usageDropMarginPpm,
|
|
111
|
+
observationMs: pt.observationMs,
|
|
112
|
+
evaluationWindowMs: pt.evaluationWindowMs,
|
|
113
|
+
relaxReplayWindowMs: pt.relaxationReplayWindowMs,
|
|
114
|
+
rollbackCooldownMs: pt.rollbackCooldownMs,
|
|
115
|
+
hotPathBudgetMs: normalized.hotPathBudgetMs,
|
|
116
|
+
minItems: normalized.minItems,
|
|
117
|
+
autoTightenEnabled: pt.enabled,
|
|
118
|
+
relaxationReplayEnabled: pt.relaxationReplayEnabled,
|
|
119
|
+
},
|
|
120
|
+
now: () => this.nowClock(),
|
|
121
|
+
hotPathClock: () => (this.hotPathClock !== undefined ? this.hotPathClock() : performance.now()),
|
|
122
|
+
});
|
|
123
|
+
const writeQueue = new AssociationWriteQueue(store, {
|
|
124
|
+
onGraphMutated: (info) => {
|
|
125
|
+
const evicted = new Set();
|
|
126
|
+
for (const w of info.withdrawals) {
|
|
127
|
+
for (const id of w.deletedNodeIds)
|
|
128
|
+
evicted.add(id);
|
|
129
|
+
for (const id of w.suppressedNodeIds)
|
|
130
|
+
evicted.add(id);
|
|
131
|
+
}
|
|
132
|
+
if (evicted.size > 0) {
|
|
133
|
+
this.evictNodesAcrossActiveAgents(evicted);
|
|
134
|
+
}
|
|
135
|
+
if (info.hasStructuralGraphChanges || info.hasUpserts || info.withdrawals.length > 0) {
|
|
136
|
+
void this.rebuildIndex();
|
|
137
|
+
}
|
|
138
|
+
else if (info.hasEdgeWeightUpdates &&
|
|
139
|
+
this.activeIndex !== null &&
|
|
140
|
+
!this.writeQueue?.hasPendingWithdrawals) {
|
|
141
|
+
this.rebuildEdgesOnly();
|
|
142
|
+
}
|
|
143
|
+
},
|
|
144
|
+
onError: (error) => {
|
|
145
|
+
this.ctx.logger.warn?.('assistant-association write queue error', { error: String(error) });
|
|
146
|
+
},
|
|
147
|
+
});
|
|
148
|
+
this.writeQueue = writeQueue;
|
|
149
|
+
const sourceManager = new AssociationSourceManager(ctx, store, writeQueue, {
|
|
150
|
+
onImmediateWithdraw: ({ ownerScopeKey, sourcePlugin, sourceRef, nodeIds }) => {
|
|
151
|
+
const evicted = new Set(nodeIds);
|
|
152
|
+
if (this.activeIndex !== null) {
|
|
153
|
+
this.activeIndex.tombstoneSourceRef(ownerScopeKey, sourcePlugin, sourceRef);
|
|
154
|
+
for (const id of nodeIds) {
|
|
155
|
+
this.activeIndex.tombstoneNodeId(id);
|
|
156
|
+
}
|
|
157
|
+
const slots = this.activeIndex.sourceRefToSlots.get(`${ownerScopeKey}\0${sourcePlugin}\0${sourceRef}`);
|
|
158
|
+
if (slots !== undefined) {
|
|
159
|
+
for (const slot of slots) {
|
|
160
|
+
const nid = this.activeIndex.nodeIds[slot];
|
|
161
|
+
if (nid !== undefined)
|
|
162
|
+
evicted.add(nid);
|
|
163
|
+
}
|
|
164
|
+
}
|
|
165
|
+
}
|
|
166
|
+
this.evictNodesAcrossActiveAgents(evicted);
|
|
167
|
+
},
|
|
168
|
+
onConflictSuppressed: ({ nodeIds }) => {
|
|
169
|
+
const evicted = new Set(nodeIds);
|
|
170
|
+
if (this.activeIndex !== null) {
|
|
171
|
+
for (const id of nodeIds) {
|
|
172
|
+
this.activeIndex.tombstoneNodeId(id);
|
|
173
|
+
}
|
|
174
|
+
}
|
|
175
|
+
this.evictNodesAcrossActiveAgents(evicted);
|
|
176
|
+
void this.rebuildIndex();
|
|
177
|
+
},
|
|
178
|
+
onTaskCorrected: ({ ownerScopeKey, taskId, nodeIds, nowMs }) => {
|
|
179
|
+
if (!this.active || this.writeQueue === null || nodeIds.length === 0)
|
|
180
|
+
return;
|
|
181
|
+
if (this.isTaskInHoldout(taskId).inHoldout)
|
|
182
|
+
return;
|
|
183
|
+
this.writeQueue.enqueue({
|
|
184
|
+
kind: 'upsert-replay-episode',
|
|
185
|
+
episode: {
|
|
186
|
+
taskId,
|
|
187
|
+
ownerScopeKey,
|
|
188
|
+
inHoldout: false,
|
|
189
|
+
cues: [],
|
|
190
|
+
correctedNodeIds: nodeIds,
|
|
191
|
+
occurredAt: nowMs,
|
|
192
|
+
},
|
|
193
|
+
});
|
|
194
|
+
},
|
|
195
|
+
hebbianConfig: normalized.hebbian,
|
|
196
|
+
dreamingConfig: normalized.dreaming,
|
|
197
|
+
holdoutSeedKey: this.holdoutSeedKey,
|
|
198
|
+
holdoutRateBps: normalized.holdoutRateBps,
|
|
199
|
+
consumeSessionToolNames: (sessionId) => consumeSessionTurnToolNames(this.toolNamesBySessionTurn, sessionId),
|
|
200
|
+
onEpisodesSynced: (scope) => {
|
|
201
|
+
this.scheduleClusteringForScope(scope);
|
|
202
|
+
},
|
|
203
|
+
onError: (error) => {
|
|
204
|
+
this.ctx.logger.warn?.('assistant-association source sync error', { error: String(error) });
|
|
205
|
+
},
|
|
206
|
+
now: () => this.nowClock(),
|
|
207
|
+
});
|
|
208
|
+
this.sourceManager = sourceManager;
|
|
209
|
+
// Initialize in-memory double-buffered index
|
|
210
|
+
if (store.countActiveNodes() <= COLD_START_SYNC_THRESHOLD) {
|
|
211
|
+
this.rebuildIndexSync();
|
|
212
|
+
}
|
|
213
|
+
else {
|
|
214
|
+
void this.rebuildIndex();
|
|
215
|
+
}
|
|
216
|
+
// Subscribe to runtime agent/session/goal events
|
|
217
|
+
ctx.on('agent/created', ({ agent }) => {
|
|
218
|
+
if (!this.active)
|
|
219
|
+
return;
|
|
220
|
+
this.activeAgents.add(agent);
|
|
221
|
+
const scope = this.resolveAgentScope(agent);
|
|
222
|
+
if (scope !== undefined && sourceManager.registerScope(scope)) {
|
|
223
|
+
sourceManager.scheduleSync(0);
|
|
224
|
+
}
|
|
225
|
+
});
|
|
226
|
+
ctx.on('agent/inbox/claimed', ({ agent, message, turn }) => {
|
|
227
|
+
if (!this.active)
|
|
228
|
+
return;
|
|
229
|
+
this.activeAgents.add(agent);
|
|
230
|
+
const state = getOrCreateAgentAssocState(this.agentStates, agent);
|
|
231
|
+
handleInboxClaimed(state, message, turn, this.activeIndex);
|
|
232
|
+
});
|
|
233
|
+
ctx.on('agent/inbox/discarded', ({ agent, message }) => {
|
|
234
|
+
if (!this.active)
|
|
235
|
+
return;
|
|
236
|
+
const state = getOrCreateAgentAssocState(this.agentStates, agent);
|
|
237
|
+
handleInboxDiscarded(state, message);
|
|
238
|
+
});
|
|
239
|
+
ctx.on('agent/status', ({ agent, status }) => {
|
|
240
|
+
if (!this.active)
|
|
241
|
+
return;
|
|
242
|
+
const state = getOrCreateAgentAssocState(this.agentStates, agent);
|
|
243
|
+
handleAgentStatus(state, status);
|
|
244
|
+
});
|
|
245
|
+
ctx.on('agent/disposed', ({ agent }) => {
|
|
246
|
+
this.activeAgents.delete(agent);
|
|
247
|
+
this.agentStates.delete(agent);
|
|
248
|
+
});
|
|
249
|
+
ctx.on('session/event', (session, event) => {
|
|
250
|
+
if (!this.active)
|
|
251
|
+
return;
|
|
252
|
+
const agents = this.ctx.get('agents', false);
|
|
253
|
+
const agent = agents?.get(session.id);
|
|
254
|
+
if (agent === undefined || agent.session !== session)
|
|
255
|
+
return;
|
|
256
|
+
this.activeAgents.add(agent);
|
|
257
|
+
const state = getOrCreateAgentAssocState(this.agentStates, agent);
|
|
258
|
+
const outcome = handleSessionEvent(state, session, event, this.activeIndex, this.toolNamesBySessionTurn);
|
|
259
|
+
if (outcome.telemetry !== undefined || outcome.assistantText !== undefined) {
|
|
260
|
+
const ownerScope = this.resolveAgentScope(agent);
|
|
261
|
+
if (ownerScope !== undefined) {
|
|
262
|
+
const turnNum = outcome.telemetry?.turn ?? outcome.assistantTurn ?? -1;
|
|
263
|
+
let taskId = state.turnTaskIds.get(turnNum);
|
|
264
|
+
if (taskId === undefined) {
|
|
265
|
+
taskId = resolveTaskId(this.ctx, agent, state, ownerScope).taskId;
|
|
266
|
+
if (turnNum >= 0) {
|
|
267
|
+
recordTurnTaskId(state, turnNum, taskId);
|
|
268
|
+
}
|
|
269
|
+
}
|
|
270
|
+
const holdout = this.isTaskInHoldout(taskId);
|
|
271
|
+
const nowMs = this.nowClock();
|
|
272
|
+
if (outcome.telemetry !== undefined && this.writeQueue !== null) {
|
|
273
|
+
this.writeQueue.enqueue({
|
|
274
|
+
kind: 'upsert-task-telemetry',
|
|
275
|
+
telemetry: {
|
|
276
|
+
taskId,
|
|
277
|
+
ownerScopeKey: ownerScope.ownerScopeKey,
|
|
278
|
+
inHoldout: holdout.inHoldout,
|
|
279
|
+
turnsDelta: outcome.telemetry.turnsDelta,
|
|
280
|
+
stepsDelta: outcome.telemetry.stepsDelta,
|
|
281
|
+
inputTokensDelta: outcome.telemetry.inputTokensDelta,
|
|
282
|
+
outputTokensDelta: outcome.telemetry.outputTokensDelta,
|
|
283
|
+
costUsdMicrosDelta: outcome.telemetry.costUsdMicrosDelta,
|
|
284
|
+
updatedAt: nowMs,
|
|
285
|
+
},
|
|
286
|
+
});
|
|
287
|
+
}
|
|
288
|
+
if (outcome.assistantText !== undefined &&
|
|
289
|
+
outcome.assistantText.length > 0 &&
|
|
290
|
+
!holdout.inHoldout &&
|
|
291
|
+
this.assocConfig.hebbian.enabled &&
|
|
292
|
+
this.activeIndex !== null &&
|
|
293
|
+
this.writeQueue !== null) {
|
|
294
|
+
this.processWeakUseFromAssistantText(agent, state, ownerScope, taskId, outcome.assistantText, nowMs);
|
|
295
|
+
}
|
|
296
|
+
}
|
|
297
|
+
}
|
|
298
|
+
});
|
|
299
|
+
ctx.on('goal/changed', ({ agent }) => {
|
|
300
|
+
if (!this.active || agent === undefined)
|
|
301
|
+
return;
|
|
302
|
+
const state = getOrCreateAgentAssocState(this.agentStates, agent);
|
|
303
|
+
state.inputNonce += 1;
|
|
304
|
+
});
|
|
305
|
+
// Register synchronous systemPrompt.context hook (order: 239, before personal-memory:task-context at 240; interpolate: false)
|
|
306
|
+
ctx.inject(['systemPrompt'], (promptCtx) => promptCtx.systemPrompt.context({
|
|
307
|
+
name: 'assistant-association:context',
|
|
308
|
+
order: 239,
|
|
309
|
+
interpolate: false,
|
|
310
|
+
text: ({ agent }) => this.contextSnapshot(agent),
|
|
311
|
+
}));
|
|
312
|
+
// Register assoc_read tool
|
|
313
|
+
const unregisterTools = registerAssociationTools(ctx, {
|
|
314
|
+
readById: (exec, id) => this.readById(exec, id),
|
|
315
|
+
});
|
|
316
|
+
// Start source ingestion & periodic reconcile
|
|
317
|
+
sourceManager.start();
|
|
318
|
+
const syncTimer = setInterval(() => {
|
|
319
|
+
if (this.active) {
|
|
320
|
+
sourceManager.scheduleSync(0);
|
|
321
|
+
if (this.assocConfig.paramTuning.enabled) {
|
|
322
|
+
try {
|
|
323
|
+
this.reconcileParamTuning();
|
|
324
|
+
}
|
|
325
|
+
catch (error) {
|
|
326
|
+
this.ctx.logger.warn?.('assistant-association param tuning error', {
|
|
327
|
+
error: String(error),
|
|
328
|
+
});
|
|
329
|
+
}
|
|
330
|
+
}
|
|
331
|
+
this.trackBackgroundTask(this.runPeriodicS3Maintenance().catch((error) => {
|
|
332
|
+
this.ctx.logger.warn?.('assistant-association s3 maintenance error', {
|
|
333
|
+
error: String(error),
|
|
334
|
+
});
|
|
335
|
+
}));
|
|
336
|
+
if (this.active &&
|
|
337
|
+
this.assocConfig.enabled &&
|
|
338
|
+
this.assocConfig.webLearning.enabled &&
|
|
339
|
+
this.assocConfig.webLearning.allowedDomains.length > 0 &&
|
|
340
|
+
!this.writeQueue?.hasPendingWithdrawals) {
|
|
341
|
+
this.trackBackgroundTask(this.runPeriodicS4WebLearning().catch((error) => {
|
|
342
|
+
this.ctx.logger.warn?.('assistant-association web learning error', {
|
|
343
|
+
error: String(error),
|
|
344
|
+
});
|
|
345
|
+
}));
|
|
346
|
+
}
|
|
347
|
+
}
|
|
348
|
+
}, normalized.syncIntervalMs);
|
|
349
|
+
syncTimer.unref?.();
|
|
350
|
+
const decayTimer = normalized.hebbian.enabled
|
|
351
|
+
? setInterval(() => {
|
|
352
|
+
if (this.active) {
|
|
353
|
+
this.enqueueHebbianDecayPass();
|
|
354
|
+
}
|
|
355
|
+
}, normalized.hebbian.decayIntervalMs)
|
|
356
|
+
: null;
|
|
357
|
+
decayTimer?.unref?.();
|
|
358
|
+
ctx.effect(() => async () => {
|
|
359
|
+
this.active = false;
|
|
360
|
+
this.effectAbortController.abort();
|
|
361
|
+
clearInterval(syncTimer);
|
|
362
|
+
if (decayTimer !== null) {
|
|
363
|
+
clearInterval(decayTimer);
|
|
364
|
+
}
|
|
365
|
+
unregisterTools();
|
|
366
|
+
sourceManager.dispose();
|
|
367
|
+
await writeQueue.dispose();
|
|
368
|
+
if (this.pendingTasks.size > 0) {
|
|
369
|
+
await Promise.allSettled(this.pendingTasks);
|
|
370
|
+
}
|
|
371
|
+
this.activeAgents.clear();
|
|
372
|
+
try {
|
|
373
|
+
store.close();
|
|
374
|
+
}
|
|
375
|
+
catch {
|
|
376
|
+
// Ignore already closed
|
|
377
|
+
}
|
|
378
|
+
}, 'assistant-association.lifecycle');
|
|
379
|
+
}
|
|
380
|
+
get enabled() {
|
|
381
|
+
return this.assocConfig.enabled;
|
|
382
|
+
}
|
|
383
|
+
get indexReady() {
|
|
384
|
+
return this.ready;
|
|
385
|
+
}
|
|
386
|
+
get store() {
|
|
387
|
+
return this.assocStore;
|
|
388
|
+
}
|
|
389
|
+
bindHeadlessPrincipal(agent, principalId) {
|
|
390
|
+
this.headlessPrincipals.set(agent, principalId);
|
|
391
|
+
this.activeAgents.add(agent);
|
|
392
|
+
}
|
|
393
|
+
setHotPathClock(clock) {
|
|
394
|
+
this.hotPathClock = clock;
|
|
395
|
+
}
|
|
396
|
+
setNowClock(now) {
|
|
397
|
+
this.nowClock = now ?? (() => Date.now());
|
|
398
|
+
}
|
|
399
|
+
isTaskInHoldout(taskId) {
|
|
400
|
+
if (this.holdoutSeedKey === null) {
|
|
401
|
+
throw new AssistantAssociationError('disabled', 'assistant-association is disabled');
|
|
402
|
+
}
|
|
403
|
+
return evaluateHoldout(this.holdoutSeedKey, taskId, this.assocConfig.holdoutRateBps);
|
|
404
|
+
}
|
|
405
|
+
shouldSuppressMemoryKeywordHits(agent) {
|
|
406
|
+
if (!this.active || !this.assocConfig.enabled || !this.ready)
|
|
407
|
+
return false;
|
|
408
|
+
if (agent === undefined)
|
|
409
|
+
return false;
|
|
410
|
+
const scope = this.resolveAgentScope(agent);
|
|
411
|
+
if (scope === undefined)
|
|
412
|
+
return false;
|
|
413
|
+
try {
|
|
414
|
+
const decision = this.policy.authorizeAgent(agent, 'snapshot', {
|
|
415
|
+
kind: 'tool',
|
|
416
|
+
id: 'assistant-association:context',
|
|
417
|
+
});
|
|
418
|
+
if (decision.effect !== 'allow')
|
|
419
|
+
return false;
|
|
420
|
+
}
|
|
421
|
+
catch {
|
|
422
|
+
return false;
|
|
423
|
+
}
|
|
424
|
+
const state = getOrCreateAgentAssocState(this.agentStates, agent);
|
|
425
|
+
const { taskId } = resolveTaskId(this.ctx, agent, state, scope);
|
|
426
|
+
if (this.isTaskInHoldout(taskId).inHoldout) {
|
|
427
|
+
return false;
|
|
428
|
+
}
|
|
429
|
+
if (state.lastStepOutcome !== undefined &&
|
|
430
|
+
state.lastStepOutcome.nonce === state.inputNonce &&
|
|
431
|
+
state.lastStepOutcome.taskId === taskId &&
|
|
432
|
+
state.lastStepOutcome.outcome !== 'injected') {
|
|
433
|
+
return false;
|
|
434
|
+
}
|
|
435
|
+
return true;
|
|
436
|
+
}
|
|
437
|
+
contextSnapshot(agent) {
|
|
438
|
+
if (!this.active || !this.assocConfig.enabled || !this.ready || agent === undefined) {
|
|
439
|
+
return '';
|
|
440
|
+
}
|
|
441
|
+
const activeIndex = this.activeIndex;
|
|
442
|
+
if (activeIndex === null)
|
|
443
|
+
return '';
|
|
444
|
+
const ownerScope = this.resolveAgentScope(agent);
|
|
445
|
+
if (ownerScope === undefined)
|
|
446
|
+
return '';
|
|
447
|
+
try {
|
|
448
|
+
const decision = this.policy.authorizeAgent(agent, 'snapshot', {
|
|
449
|
+
kind: 'tool',
|
|
450
|
+
id: 'assistant-association:context',
|
|
451
|
+
});
|
|
452
|
+
if (decision.effect !== 'allow')
|
|
453
|
+
return '';
|
|
454
|
+
}
|
|
455
|
+
catch {
|
|
456
|
+
return '';
|
|
457
|
+
}
|
|
458
|
+
this.activeAgents.add(agent);
|
|
459
|
+
const state = getOrCreateAgentAssocState(this.agentStates, agent);
|
|
460
|
+
if (wipeStateOnOwnerRotation(state, ownerScope.ownerScopeKey)) {
|
|
461
|
+
this.sourceManager?.registerScope(ownerScope);
|
|
462
|
+
}
|
|
463
|
+
const { taskId, taskKind, turnNumber, goalContext } = resolveTaskId(this.ctx, agent, state, ownerScope);
|
|
464
|
+
recordTurnTaskId(state, turnNumber, taskId);
|
|
465
|
+
const holdout = this.isTaskInHoldout(taskId);
|
|
466
|
+
const nowMs = this.nowClock();
|
|
467
|
+
const prevActivity = this.lastActivityByScope.get(ownerScope.ownerScopeKey) ?? 0;
|
|
468
|
+
if (nowMs > prevActivity) {
|
|
469
|
+
this.lastActivityByScope.set(ownerScope.ownerScopeKey, nowMs);
|
|
470
|
+
}
|
|
471
|
+
this.recordHoldoutOnce(state, taskId, ownerScope.ownerScopeKey, taskKind, agent, turnNumber, holdout, nowMs);
|
|
472
|
+
if (holdout.inHoldout) {
|
|
473
|
+
state.lastStepOutcome = { nonce: state.inputNonce, taskId, outcome: 'holdout' };
|
|
474
|
+
return '';
|
|
475
|
+
}
|
|
476
|
+
const activeProfile = this.paramLedger?.current(ownerScope.ownerScopeKey);
|
|
477
|
+
const profileVersion = activeProfile?.version ?? 0;
|
|
478
|
+
const useProfileParams = activeProfile !== undefined &&
|
|
479
|
+
(this.assocConfig.paramTuning.enabled || activeProfile.version > 0);
|
|
480
|
+
const resolvedHotPath = useProfileParams
|
|
481
|
+
? toHotPathProfile(activeProfile.parameters, {
|
|
482
|
+
hopTopN: this.assocConfig.hopTopN,
|
|
483
|
+
maxFanoutPerNode: this.assocConfig.maxFanoutPerNode,
|
|
484
|
+
hotPathBudgetMs: this.assocConfig.hotPathBudgetMs,
|
|
485
|
+
})
|
|
486
|
+
: undefined;
|
|
487
|
+
const effectiveMaxItems = resolvedHotPath?.maxItems ?? this.assocConfig.maxItems;
|
|
488
|
+
const effectiveMinItems = Math.min(this.assocConfig.minItems, effectiveMaxItems);
|
|
489
|
+
const effectiveHysteresisDelta = resolvedHotPath?.hysteresisDelta ?? this.assocConfig.hysteresisDelta;
|
|
490
|
+
const profile = resolvedHotPath ?? {
|
|
491
|
+
maxHops: this.assocConfig.maxHops,
|
|
492
|
+
hopTopN: this.assocConfig.hopTopN,
|
|
493
|
+
maxFanoutPerNode: this.assocConfig.maxFanoutPerNode,
|
|
494
|
+
maxItems: this.assocConfig.maxItems,
|
|
495
|
+
decayHalfLifeMs: this.assocConfig.decayHalfLifeMs,
|
|
496
|
+
budgetMs: this.assocConfig.hotPathBudgetMs,
|
|
497
|
+
sourceWeights: this.assocConfig.sourceWeights,
|
|
498
|
+
};
|
|
499
|
+
const goalKey = goalContext === undefined
|
|
500
|
+
? 'none'
|
|
501
|
+
: `${goalContext.goal.id}:${goalContext.goal.definition.version}:${goalContext.goal.native.revision}:${goalContext.checkpoint.nextStep.slice(0, 64)}`;
|
|
502
|
+
const epochKey = `${state.inputNonce}:${state.invalidationNonce}:${ownerScope.ownerScopeKey}:${taskId}:${goalKey}:${activeIndex.buildEpoch}:${this.invalidationGeneration}:${profileVersion}`;
|
|
503
|
+
if (state.memo !== undefined && state.memo.epochKey === epochKey) {
|
|
504
|
+
return state.memo.renderedBlock;
|
|
505
|
+
}
|
|
506
|
+
const shouldDecaySession = state.lastEvaluatedNonce !== state.inputNonce;
|
|
507
|
+
state.lastEvaluatedNonce = state.inputNonce;
|
|
508
|
+
const { cues, sessionActivations } = assembleStepCues({
|
|
509
|
+
agent,
|
|
510
|
+
state,
|
|
511
|
+
goalContext,
|
|
512
|
+
turnNumber,
|
|
513
|
+
nowMs,
|
|
514
|
+
shouldDecaySession,
|
|
515
|
+
activeIndex,
|
|
516
|
+
});
|
|
517
|
+
if (cues.length === 0 && sessionActivations.length === 0 && state.retainedItems.size === 0) {
|
|
518
|
+
state.lastStepOutcome = { nonce: state.inputNonce, taskId, outcome: 'injected' };
|
|
519
|
+
state.memo = { epochKey, renderedBlock: '' };
|
|
520
|
+
return '';
|
|
521
|
+
}
|
|
522
|
+
const result = runHotPathQuery(activeIndex, cues, {
|
|
523
|
+
ownerScopeKey: ownerScope.ownerScopeKey,
|
|
524
|
+
workspace: ownerScope.workspace,
|
|
525
|
+
agentPreset: ownerScope.agentPreset,
|
|
526
|
+
allowLowTrust: this.assocConfig.allowLowTrust,
|
|
527
|
+
allowSensitive: this.assocConfig.allowSensitive,
|
|
528
|
+
nowMs,
|
|
529
|
+
}, profile, {
|
|
530
|
+
sessionActivations,
|
|
531
|
+
...(this.hotPathClock === undefined ? {} : { clock: this.hotPathClock }),
|
|
532
|
+
});
|
|
533
|
+
if (result.timedOut) {
|
|
534
|
+
state.lastStepOutcome = { nonce: state.inputNonce, taskId, outcome: 'timeout' };
|
|
535
|
+
this.ctx.logger.warn?.('assoc-timeout', {
|
|
536
|
+
taskId,
|
|
537
|
+
ownerScopeKey: ownerScope.ownerScopeKey,
|
|
538
|
+
elapsedMs: result.elapsedMs,
|
|
539
|
+
candidateCount: result.candidateCount,
|
|
540
|
+
});
|
|
541
|
+
if (state.lastMetricNonce !== state.inputNonce) {
|
|
542
|
+
state.lastMetricNonce = state.inputNonce;
|
|
543
|
+
this.enqueueStepMetrics(taskId, ownerScope.ownerScopeKey, false, result.elapsedMs, true, 'timeout', [], result.candidateCount, nowMs, profileVersion, String(agent.session.id));
|
|
544
|
+
}
|
|
545
|
+
state.memo = { epochKey, renderedBlock: '' };
|
|
546
|
+
return '';
|
|
547
|
+
}
|
|
548
|
+
const formatted = applyHysteresisAndFormat({
|
|
549
|
+
state,
|
|
550
|
+
index: activeIndex,
|
|
551
|
+
ownerScope,
|
|
552
|
+
candidates: result.items,
|
|
553
|
+
maxItems: effectiveMaxItems,
|
|
554
|
+
minItems: effectiveMinItems,
|
|
555
|
+
maxContextTokens: this.assocConfig.maxContextTokens,
|
|
556
|
+
hysteresisDelta: effectiveHysteresisDelta,
|
|
557
|
+
allowLowTrust: this.assocConfig.allowLowTrust,
|
|
558
|
+
allowSensitive: this.assocConfig.allowSensitive,
|
|
559
|
+
nowMs,
|
|
560
|
+
});
|
|
561
|
+
state.lastStepOutcome = { nonce: state.inputNonce, taskId, outcome: 'injected' };
|
|
562
|
+
if (state.lastMetricNonce !== state.inputNonce) {
|
|
563
|
+
state.lastMetricNonce = state.inputNonce;
|
|
564
|
+
foldStepSessionActivation(state, formatted.injectedItems, nowMs);
|
|
565
|
+
recordTaskExposures(state, taskId, formatted.injectedItems);
|
|
566
|
+
this.enqueueStepMetrics(taskId, ownerScope.ownerScopeKey, false, result.elapsedMs, false, 'none', formatted.injectedItems.map((i) => ({
|
|
567
|
+
id: i.id,
|
|
568
|
+
sourcePlugin: i.sourcePlugin,
|
|
569
|
+
kind: i.kind,
|
|
570
|
+
hop: i.hop,
|
|
571
|
+
score: i.score,
|
|
572
|
+
reason: i.reason,
|
|
573
|
+
...(i.provenanceEdges !== undefined ? { provenanceEdges: i.provenanceEdges } : {}),
|
|
574
|
+
})), result.candidateCount, nowMs, profileVersion, String(agent.session.id));
|
|
575
|
+
if (cues.length > 0) {
|
|
576
|
+
this.writeQueue?.enqueue({
|
|
577
|
+
kind: 'upsert-replay-episode',
|
|
578
|
+
episode: {
|
|
579
|
+
taskId,
|
|
580
|
+
ownerScopeKey: ownerScope.ownerScopeKey,
|
|
581
|
+
inHoldout: false,
|
|
582
|
+
cues,
|
|
583
|
+
profileVersion,
|
|
584
|
+
occurredAt: nowMs,
|
|
585
|
+
},
|
|
586
|
+
});
|
|
587
|
+
}
|
|
588
|
+
if (this.assocConfig.intakeSignal.enabled && result.items.length > 0) {
|
|
589
|
+
const candidate = this.findIntakeSignalCandidate(ownerScope, result.items, goalContext?.goal.id, nowMs);
|
|
590
|
+
if (candidate !== null) {
|
|
591
|
+
this.scheduleIntakeSignal(ownerScope, candidate, nowMs);
|
|
592
|
+
}
|
|
593
|
+
}
|
|
594
|
+
}
|
|
595
|
+
state.memo = { epochKey, renderedBlock: formatted.block };
|
|
596
|
+
return formatted.block;
|
|
597
|
+
}
|
|
598
|
+
async readById(exec, rawId) {
|
|
599
|
+
if (!this.active) {
|
|
600
|
+
throw new AssistantAssociationError('disposed', 'assistant-association service is disposed');
|
|
601
|
+
}
|
|
602
|
+
if (!this.assocConfig.enabled || this.assocStore === null || this.writeQueue === null) {
|
|
603
|
+
throw new AssistantAssociationError('disabled', 'assistant-association is disabled');
|
|
604
|
+
}
|
|
605
|
+
const trimmedRaw = rawId.trim();
|
|
606
|
+
const nowMs = this.nowClock();
|
|
607
|
+
if (exec.signal.aborted) {
|
|
608
|
+
const earlyScope = this.resolveReadEventScopeSafe(exec.agent);
|
|
609
|
+
if (earlyScope !== undefined) {
|
|
610
|
+
const earlyTaskId = resolveTaskId(this.ctx, exec.agent, getOrCreateAgentAssocState(this.agentStates, exec.agent), earlyScope).taskId;
|
|
611
|
+
this.recordReadEvent(earlyScope.ownerScopeKey, earlyTaskId, trimmedRaw, false, 'policy-denied', nowMs);
|
|
612
|
+
}
|
|
613
|
+
throw new AssistantAssociationError('policy-denied', 'association read was cancelled');
|
|
614
|
+
}
|
|
615
|
+
const id = trimmedRaw;
|
|
616
|
+
if (id.length === 0 || Buffer.byteLength(id, 'utf8') > 256) {
|
|
617
|
+
const earlyScope = this.resolveReadEventScopeSafe(exec.agent);
|
|
618
|
+
if (earlyScope !== undefined) {
|
|
619
|
+
const earlyTaskId = resolveTaskId(this.ctx, exec.agent, getOrCreateAgentAssocState(this.agentStates, exec.agent), earlyScope).taskId;
|
|
620
|
+
this.recordReadEvent(earlyScope.ownerScopeKey, earlyTaskId, id, false, 'invalid-input', nowMs);
|
|
621
|
+
}
|
|
622
|
+
throw new AssistantAssociationError('invalid-input', 'association id is invalid');
|
|
623
|
+
}
|
|
624
|
+
const agent = exec.agent;
|
|
625
|
+
if (agent === undefined) {
|
|
626
|
+
throw new AssistantAssociationError('missing-identity', 'assoc_read requires a live agent');
|
|
627
|
+
}
|
|
628
|
+
const agents = this.ctx.get('agents', false);
|
|
629
|
+
if (agents !== undefined && agents.get(agent.id) !== agent) {
|
|
630
|
+
throw new AssistantAssociationError('missing-identity', 'assoc_read requires a registered agent');
|
|
631
|
+
}
|
|
632
|
+
const sessions = this.ctx.get('sessions', false);
|
|
633
|
+
if (sessions !== undefined && sessions.get(agent.session.id) !== agent.session) {
|
|
634
|
+
throw new AssistantAssociationError('missing-identity', 'assoc_read requires a live session');
|
|
635
|
+
}
|
|
636
|
+
const ownerScope = this.resolveAgentScope(agent);
|
|
637
|
+
if (ownerScope === undefined) {
|
|
638
|
+
throw new AssistantAssociationError('missing-identity', 'assoc_read requires an owner scope');
|
|
639
|
+
}
|
|
640
|
+
const state = getOrCreateAgentAssocState(this.agentStates, agent);
|
|
641
|
+
const taskInfo = resolveTaskId(this.ctx, agent, state, ownerScope);
|
|
642
|
+
const { taskId } = taskInfo;
|
|
643
|
+
const toolDecision = this.policy.authorizeAgent(agent, 'read', { kind: 'tool', id: 'assoc_read' }, { idempotencyKey: `assoc-read:${String(exec.rootCallId)}:${String(exec.callId)}` });
|
|
644
|
+
if (toolDecision.effect !== 'allow') {
|
|
645
|
+
this.recordReadEvent(ownerScope.ownerScopeKey, taskId, id, false, 'policy-denied', nowMs);
|
|
646
|
+
throw new AssistantAssociationError('policy-denied', 'assoc_read denied by policy');
|
|
647
|
+
}
|
|
648
|
+
if (this.writeQueue.isNodeTombstoned(id)) {
|
|
649
|
+
this.recordReadEvent(ownerScope.ownerScopeKey, taskId, id, false, 'not-found', nowMs);
|
|
650
|
+
throw new AssistantAssociationError('not-found', 'association item is unavailable');
|
|
651
|
+
}
|
|
652
|
+
const row = this.assocStore.getNodeById(id);
|
|
653
|
+
if (row === null ||
|
|
654
|
+
row.status !== 'active' ||
|
|
655
|
+
(row.expiresAt !== null && row.expiresAt <= nowMs) ||
|
|
656
|
+
this.writeQueue.isSourceTombstoned(row.ownerScopeKey, row.sourcePlugin, row.sourceRef) ||
|
|
657
|
+
this.assocStore.isSourceWithdrawn(row.ownerScopeKey, row.sourcePlugin, row.sourceRef)) {
|
|
658
|
+
this.recordReadEvent(ownerScope.ownerScopeKey, taskId, id, false, 'not-found', nowMs);
|
|
659
|
+
throw new AssistantAssociationError('not-found', 'association item is unavailable');
|
|
660
|
+
}
|
|
661
|
+
// Fail-closed sensitivity, trust & owner lineage check (zero cross-owner / ABA oracle)
|
|
662
|
+
if (row.sensitivity !== 'private') {
|
|
663
|
+
this.recordReadEvent(ownerScope.ownerScopeKey, taskId, id, false, 'not-found', nowMs);
|
|
664
|
+
throw new AssistantAssociationError('not-found', 'association item is unavailable');
|
|
665
|
+
}
|
|
666
|
+
if (!this.assocConfig.allowLowTrust && row.trust === 'low') {
|
|
667
|
+
this.recordReadEvent(ownerScope.ownerScopeKey, taskId, id, false, 'not-found', nowMs);
|
|
668
|
+
throw new AssistantAssociationError('not-found', 'association item is unavailable');
|
|
669
|
+
}
|
|
670
|
+
if (row.ownerScopeKey !== ownerScope.ownerScopeKey ||
|
|
671
|
+
row.ownerMode !== ownerScope.mode ||
|
|
672
|
+
row.principalDigest !== ownerScope.principalDigest) {
|
|
673
|
+
this.recordReadEvent(ownerScope.ownerScopeKey, taskId, id, false, 'not-found', nowMs);
|
|
674
|
+
throw new AssistantAssociationError('not-found', 'association item is unavailable');
|
|
675
|
+
}
|
|
676
|
+
if (ownerScope.mode === 'delivery' &&
|
|
677
|
+
(row.principalRecordId !== ownerScope.principalRecordId ||
|
|
678
|
+
row.principalVersion !== ownerScope.principalVersion)) {
|
|
679
|
+
this.recordReadEvent(ownerScope.ownerScopeKey, taskId, id, false, 'not-found', nowMs);
|
|
680
|
+
throw new AssistantAssociationError('not-found', 'association item is unavailable');
|
|
681
|
+
}
|
|
682
|
+
if (row.scopeMode === 'workspace' &&
|
|
683
|
+
(row.workspace !== ownerScope.workspace || row.agentPreset !== ownerScope.agentPreset)) {
|
|
684
|
+
this.recordReadEvent(ownerScope.ownerScopeKey, taskId, id, false, 'not-found', nowMs);
|
|
685
|
+
throw new AssistantAssociationError('not-found', 'association item is unavailable');
|
|
686
|
+
}
|
|
687
|
+
// Source-specific policy check
|
|
688
|
+
const sourceResource = this.sourcePolicyResource(row.kind, row.sourceRef);
|
|
689
|
+
if (sourceResource !== undefined) {
|
|
690
|
+
const srcDecision = this.policy.authorizeAgent(agent, 'read', sourceResource, {
|
|
691
|
+
idempotencyKey: `assoc-read-src:${String(exec.rootCallId)}:${String(exec.callId)}`,
|
|
692
|
+
});
|
|
693
|
+
if (srcDecision.effect !== 'allow') {
|
|
694
|
+
this.recordReadEvent(ownerScope.ownerScopeKey, taskId, id, false, 'policy-denied', nowMs);
|
|
695
|
+
throw new AssistantAssociationError('policy-denied', 'association source read denied by policy');
|
|
696
|
+
}
|
|
697
|
+
}
|
|
698
|
+
// Live source validity re-check
|
|
699
|
+
if (row.sourcePlugin === 'personal-memory') {
|
|
700
|
+
const pm = this.ctx.get('personalMemory', false);
|
|
701
|
+
if (pm !== undefined && typeof pm.read === 'function') {
|
|
702
|
+
const memoryId = row.sourceRef.replace(/^memory:/u, '');
|
|
703
|
+
let records;
|
|
704
|
+
try {
|
|
705
|
+
records = pm.read(agent, { ids: [memoryId] });
|
|
706
|
+
}
|
|
707
|
+
catch (error) {
|
|
708
|
+
if (error !== null &&
|
|
709
|
+
typeof error === 'object' &&
|
|
710
|
+
'code' in error &&
|
|
711
|
+
error.code === 'policy-denied') {
|
|
712
|
+
this.recordReadEvent(ownerScope.ownerScopeKey, taskId, id, false, 'policy-denied', nowMs);
|
|
713
|
+
throw new AssistantAssociationError('policy-denied', 'memory source read denied');
|
|
714
|
+
}
|
|
715
|
+
this.triggerInvalidation(row.ownerScopeKey, row.sourcePlugin, row.sourceRef, row.id);
|
|
716
|
+
this.recordReadEvent(ownerScope.ownerScopeKey, taskId, id, false, 'not-found', nowMs);
|
|
717
|
+
throw new AssistantAssociationError('not-found', 'association item is unavailable');
|
|
718
|
+
}
|
|
719
|
+
const liveRec = records[0];
|
|
720
|
+
if (liveRec === undefined ||
|
|
721
|
+
liveRec.status !== 'active' ||
|
|
722
|
+
liveRec.sensitivity !== 'private' ||
|
|
723
|
+
(liveRec.expiresAt !== undefined && liveRec.expiresAt <= nowMs)) {
|
|
724
|
+
this.triggerInvalidation(row.ownerScopeKey, row.sourcePlugin, row.sourceRef, row.id);
|
|
725
|
+
this.recordReadEvent(ownerScope.ownerScopeKey, taskId, id, false, 'not-found', nowMs);
|
|
726
|
+
throw new AssistantAssociationError('not-found', 'association item is unavailable');
|
|
727
|
+
}
|
|
728
|
+
}
|
|
729
|
+
}
|
|
730
|
+
if (row.kind === 'episode') {
|
|
731
|
+
if (row.metadata.conflicted === true) {
|
|
732
|
+
this.recordReadEvent(ownerScope.ownerScopeKey, taskId, id, false, 'not-found', nowMs);
|
|
733
|
+
throw new AssistantAssociationError('not-found', 'association item is unavailable');
|
|
734
|
+
}
|
|
735
|
+
const outcomeId = row.metadata.extra?.outcomeId;
|
|
736
|
+
const evaluation = this.ctx.get('assistantEvaluation', false);
|
|
737
|
+
if (typeof outcomeId === 'string' &&
|
|
738
|
+
ownerScope.mode === 'delivery' &&
|
|
739
|
+
ownerScope.principalRecordId !== null &&
|
|
740
|
+
ownerScope.principalVersion !== null &&
|
|
741
|
+
evaluation !== undefined &&
|
|
742
|
+
typeof evaluation.createHostScope === 'function' &&
|
|
743
|
+
typeof evaluation.inspectTrustedTaskOwnerRevision === 'function') {
|
|
744
|
+
try {
|
|
745
|
+
const rev = evaluation.inspectTrustedTaskOwnerRevision({
|
|
746
|
+
scope: evaluation.createHostScope({
|
|
747
|
+
workspace: ownerScope.workspace,
|
|
748
|
+
preset: ownerScope.agentPreset,
|
|
749
|
+
}),
|
|
750
|
+
outcomeId,
|
|
751
|
+
principalRecordId: ownerScope.principalRecordId,
|
|
752
|
+
principalVersion: ownerScope.principalVersion,
|
|
753
|
+
});
|
|
754
|
+
if (rev?.action === 'withdraw') {
|
|
755
|
+
this.triggerInvalidation(row.ownerScopeKey, row.sourcePlugin, row.sourceRef, row.id);
|
|
756
|
+
this.recordReadEvent(ownerScope.ownerScopeKey, taskId, id, false, 'not-found', nowMs);
|
|
757
|
+
throw new AssistantAssociationError('not-found', 'association item is unavailable');
|
|
758
|
+
}
|
|
759
|
+
}
|
|
760
|
+
catch (error) {
|
|
761
|
+
if (error instanceof AssistantAssociationError)
|
|
762
|
+
throw error;
|
|
763
|
+
this.recordReadEvent(ownerScope.ownerScopeKey, taskId, id, false, 'not-found', nowMs);
|
|
764
|
+
throw new AssistantAssociationError('not-found', 'association item is unavailable');
|
|
765
|
+
}
|
|
766
|
+
}
|
|
767
|
+
}
|
|
768
|
+
if (row.kind === 'wiki' || row.sourcePlugin === 'personal-wiki') {
|
|
769
|
+
const wiki = this.ctx.get('personalWiki', false);
|
|
770
|
+
if (wiki !== undefined && typeof wiki.inspectHostPages === 'function') {
|
|
771
|
+
const pageId = row.sourceRef.replace(/^wiki:/u, '');
|
|
772
|
+
let pages;
|
|
773
|
+
try {
|
|
774
|
+
pages = wiki.inspectHostPages({ includeArchived: false });
|
|
775
|
+
}
|
|
776
|
+
catch {
|
|
777
|
+
this.triggerInvalidation(row.ownerScopeKey, row.sourcePlugin, row.sourceRef, row.id);
|
|
778
|
+
this.recordReadEvent(ownerScope.ownerScopeKey, taskId, id, false, 'not-found', nowMs);
|
|
779
|
+
throw new AssistantAssociationError('not-found', 'association item is unavailable');
|
|
780
|
+
}
|
|
781
|
+
const livePage = pages.find((p) => p.metadata.id === pageId);
|
|
782
|
+
if (livePage === undefined || livePage.metadata.status === 'archived') {
|
|
783
|
+
this.triggerInvalidation(row.ownerScopeKey, row.sourcePlugin, row.sourceRef, row.id);
|
|
784
|
+
this.recordReadEvent(ownerScope.ownerScopeKey, taskId, id, false, 'not-found', nowMs);
|
|
785
|
+
throw new AssistantAssociationError('not-found', 'association item is unavailable');
|
|
786
|
+
}
|
|
787
|
+
}
|
|
788
|
+
}
|
|
789
|
+
if (row.kind === 'skill' || row.sourcePlugin === 'assistant-skills') {
|
|
790
|
+
const skills = this.ctx.get('assistantSkills', false);
|
|
791
|
+
if (skills !== undefined && typeof skills.inspectOwnerActiveSkills === 'function') {
|
|
792
|
+
if (ownerScope.mode !== 'delivery' ||
|
|
793
|
+
ownerScope.principalRecordId === null ||
|
|
794
|
+
ownerScope.principalVersion === null) {
|
|
795
|
+
this.recordReadEvent(ownerScope.ownerScopeKey, taskId, id, false, 'not-found', nowMs);
|
|
796
|
+
throw new AssistantAssociationError('not-found', 'association item is unavailable');
|
|
797
|
+
}
|
|
798
|
+
const skillName = row.sourceRef.replace(/^skill:/u, '');
|
|
799
|
+
let activeSkills;
|
|
800
|
+
try {
|
|
801
|
+
activeSkills = skills.inspectOwnerActiveSkills({
|
|
802
|
+
principalId: ownerScope.principalId,
|
|
803
|
+
principalRecordId: ownerScope.principalRecordId,
|
|
804
|
+
principalVersion: ownerScope.principalVersion,
|
|
805
|
+
workspace: ownerScope.workspace,
|
|
806
|
+
preset: ownerScope.agentPreset,
|
|
807
|
+
});
|
|
808
|
+
}
|
|
809
|
+
catch {
|
|
810
|
+
this.triggerInvalidation(row.ownerScopeKey, row.sourcePlugin, row.sourceRef, row.id);
|
|
811
|
+
this.recordReadEvent(ownerScope.ownerScopeKey, taskId, id, false, 'not-found', nowMs);
|
|
812
|
+
throw new AssistantAssociationError('not-found', 'association item is unavailable');
|
|
813
|
+
}
|
|
814
|
+
const liveSkill = activeSkills.find((s) => s.name === skillName && s.retired !== true);
|
|
815
|
+
if (liveSkill === undefined) {
|
|
816
|
+
this.triggerInvalidation(row.ownerScopeKey, row.sourcePlugin, row.sourceRef, row.id);
|
|
817
|
+
this.recordReadEvent(ownerScope.ownerScopeKey, taskId, id, false, 'not-found', nowMs);
|
|
818
|
+
throw new AssistantAssociationError('not-found', 'association item is unavailable');
|
|
819
|
+
}
|
|
820
|
+
}
|
|
821
|
+
}
|
|
822
|
+
if (row.kind === 'event' || row.sourcePlugin === 'event-triggers') {
|
|
823
|
+
const triggers = this.ctx.get('eventTriggers', false);
|
|
824
|
+
const triggerId = row.metadata.extra?.triggerId;
|
|
825
|
+
if (triggers !== undefined &&
|
|
826
|
+
typeof triggers.inspectOwnerSources === 'function' &&
|
|
827
|
+
typeof triggerId === 'string' &&
|
|
828
|
+
triggerId.length > 0 &&
|
|
829
|
+
ownerScope.mode === 'delivery' &&
|
|
830
|
+
ownerScope.principalRecordId !== null &&
|
|
831
|
+
ownerScope.principalVersion !== null) {
|
|
832
|
+
let activeSources;
|
|
833
|
+
try {
|
|
834
|
+
activeSources = triggers.inspectOwnerSources({
|
|
835
|
+
principalId: ownerScope.principalId,
|
|
836
|
+
principalRecordId: ownerScope.principalRecordId,
|
|
837
|
+
principalVersion: ownerScope.principalVersion,
|
|
838
|
+
workspace: ownerScope.workspace,
|
|
839
|
+
preset: ownerScope.agentPreset,
|
|
840
|
+
});
|
|
841
|
+
}
|
|
842
|
+
catch {
|
|
843
|
+
this.triggerInvalidation(row.ownerScopeKey, row.sourcePlugin, row.sourceRef, row.id);
|
|
844
|
+
this.recordReadEvent(ownerScope.ownerScopeKey, taskId, id, false, 'not-found', nowMs);
|
|
845
|
+
throw new AssistantAssociationError('not-found', 'association item is unavailable');
|
|
846
|
+
}
|
|
847
|
+
const liveSource = activeSources.find((s) => s.triggerId === triggerId);
|
|
848
|
+
if (liveSource === undefined ||
|
|
849
|
+
(liveSource.expiresAt !== undefined && liveSource.expiresAt <= nowMs)) {
|
|
850
|
+
this.triggerInvalidation(row.ownerScopeKey, row.sourcePlugin, row.sourceRef, row.id);
|
|
851
|
+
this.recordReadEvent(ownerScope.ownerScopeKey, taskId, id, false, 'not-found', nowMs);
|
|
852
|
+
throw new AssistantAssociationError('not-found', 'association item is unavailable');
|
|
853
|
+
}
|
|
854
|
+
}
|
|
855
|
+
}
|
|
856
|
+
if (row.kind === 'dream' || row.kind === 'abstraction') {
|
|
857
|
+
if (row.sourcePlugin === 'assistant-dreaming' && row.sourceRef.startsWith('dream-idea:')) {
|
|
858
|
+
const dreaming = this.ctx.get('assistantDreaming', false);
|
|
859
|
+
if (dreaming !== undefined && typeof dreaming.inspectIdeas === 'function') {
|
|
860
|
+
const ideaId = row.sourceRef.slice('dream-idea:'.length);
|
|
861
|
+
try {
|
|
862
|
+
const ideas = dreaming.inspectIdeas(500);
|
|
863
|
+
const matched = ideas.find((idea) => idea.id === ideaId);
|
|
864
|
+
if (matched !== undefined &&
|
|
865
|
+
(matched.state === 'rejected' || matched.state === 'withdrawn')) {
|
|
866
|
+
this.triggerInvalidation(row.ownerScopeKey, row.sourcePlugin, row.sourceRef, row.id);
|
|
867
|
+
this.recordReadEvent(ownerScope.ownerScopeKey, taskId, id, false, 'not-found', nowMs);
|
|
868
|
+
throw new AssistantAssociationError('not-found', 'association item is unavailable');
|
|
869
|
+
}
|
|
870
|
+
}
|
|
871
|
+
catch (error) {
|
|
872
|
+
if (error instanceof AssistantAssociationError)
|
|
873
|
+
throw error;
|
|
874
|
+
}
|
|
875
|
+
}
|
|
876
|
+
}
|
|
877
|
+
const derivedParents = this.assocStore.database
|
|
878
|
+
.prepare("SELECT source_node_id FROM assoc_derived_from WHERE target_kind = 'node' AND target_id = ?")
|
|
879
|
+
.all(row.id);
|
|
880
|
+
for (const parentRef of derivedParents) {
|
|
881
|
+
const parentNode = this.assocStore.getNodeById(parentRef.source_node_id);
|
|
882
|
+
if (parentNode === null ||
|
|
883
|
+
parentNode.status !== 'active' ||
|
|
884
|
+
(parentNode.expiresAt !== null && parentNode.expiresAt <= nowMs) ||
|
|
885
|
+
this.writeQueue.isNodeTombstoned(parentNode.id)) {
|
|
886
|
+
this.triggerInvalidation(row.ownerScopeKey, row.sourcePlugin, row.sourceRef, row.id);
|
|
887
|
+
this.recordReadEvent(ownerScope.ownerScopeKey, taskId, id, false, 'not-found', nowMs);
|
|
888
|
+
throw new AssistantAssociationError('not-found', 'association item is unavailable');
|
|
889
|
+
}
|
|
890
|
+
}
|
|
891
|
+
}
|
|
892
|
+
// Record read hit & S2 Hebbian strong use (+α) ONLY for active exposed non-holdout items
|
|
893
|
+
this.recordReadEvent(ownerScope.ownerScopeKey, taskId, row.id, true, 'ok', nowMs);
|
|
894
|
+
const inHoldout = this.isTaskInHoldout(taskId).inHoldout;
|
|
895
|
+
const taskExpMap = state.taskExposures.get(taskId);
|
|
896
|
+
const expEntry = taskExpMap?.get(row.id);
|
|
897
|
+
const inRetained = state.lastStepOutcome?.taskId === taskId &&
|
|
898
|
+
state.lastStepOutcome.outcome === 'injected' &&
|
|
899
|
+
state.retainedItems.has(row.id);
|
|
900
|
+
const isExposed = !inHoldout &&
|
|
901
|
+
(expEntry !== undefined || inRetained || this.assocStore.hasExposedRow(taskId, row.id));
|
|
902
|
+
if (isExposed && this.assocConfig.hebbian.enabled) {
|
|
903
|
+
if (expEntry !== undefined) {
|
|
904
|
+
expEntry.strongUsed = true;
|
|
905
|
+
}
|
|
906
|
+
const provenanceEdges = expEntry?.provenanceEdges ?? [];
|
|
907
|
+
const coActivatedNodeIds = provenanceEdges.length === 0 && (expEntry?.hop ?? 0) === 0
|
|
908
|
+
? selectHop0CoActivationTargets({
|
|
909
|
+
nodeId: row.id,
|
|
910
|
+
coExposedNodeIds: taskExpMap !== undefined ? [...taskExpMap.keys()] : [],
|
|
911
|
+
goalNodeId: taskInfo.goalContext !== undefined
|
|
912
|
+
? `a:g-${taskInfo.goalContext.goal.id}`
|
|
913
|
+
: null,
|
|
914
|
+
sessionNodeIds: [...state.sessionActivation.keys()],
|
|
915
|
+
episodeNodeId: taskInfo.taskKind === 'foreground-turn'
|
|
916
|
+
? `a:e-fg-${taskId.slice('foreground-turn:'.length)}`
|
|
917
|
+
: null,
|
|
918
|
+
})
|
|
919
|
+
: [];
|
|
920
|
+
this.writeQueue.enqueue({
|
|
921
|
+
kind: 'apply-hebbian-use',
|
|
922
|
+
useKind: 'strong',
|
|
923
|
+
taskId,
|
|
924
|
+
ownerScopeKey: row.ownerScopeKey,
|
|
925
|
+
nodeId: row.id,
|
|
926
|
+
sessionId: String(agent.session.id),
|
|
927
|
+
...(provenanceEdges.length > 0 ? { provenanceEdges } : {}),
|
|
928
|
+
...(coActivatedNodeIds.length > 0 ? { coActivatedNodeIds } : {}),
|
|
929
|
+
nowMs,
|
|
930
|
+
hebbianConfig: this.assocConfig.hebbian,
|
|
931
|
+
});
|
|
932
|
+
this.writeQueue.enqueue({
|
|
933
|
+
kind: 'upsert-replay-episode',
|
|
934
|
+
episode: {
|
|
935
|
+
taskId,
|
|
936
|
+
ownerScopeKey: row.ownerScopeKey,
|
|
937
|
+
inHoldout: false,
|
|
938
|
+
cues: [],
|
|
939
|
+
usedNodeIds: [row.id],
|
|
940
|
+
occurredAt: nowMs,
|
|
941
|
+
},
|
|
942
|
+
});
|
|
943
|
+
}
|
|
944
|
+
else {
|
|
945
|
+
this.writeQueue.enqueue({
|
|
946
|
+
kind: 'record-metrics',
|
|
947
|
+
metrics: [],
|
|
948
|
+
exposures: [
|
|
949
|
+
{
|
|
950
|
+
taskId,
|
|
951
|
+
nodeId: row.id,
|
|
952
|
+
ownerScopeKey: row.ownerScopeKey,
|
|
953
|
+
sourcePlugin: row.sourcePlugin,
|
|
954
|
+
exposedAt: nowMs,
|
|
955
|
+
wasExposed: isExposed,
|
|
956
|
+
strongUsed: isExposed,
|
|
957
|
+
sessionId: String(agent.session.id),
|
|
958
|
+
assocReadCount: 1,
|
|
959
|
+
},
|
|
960
|
+
],
|
|
961
|
+
});
|
|
962
|
+
}
|
|
963
|
+
return Object.freeze({
|
|
964
|
+
id: row.id,
|
|
965
|
+
kind: row.kind,
|
|
966
|
+
trust: row.trust,
|
|
967
|
+
sensitivity: 'private',
|
|
968
|
+
sourceRef: row.sourceRef,
|
|
969
|
+
sourceVersion: `v${row.sourceVersion}`,
|
|
970
|
+
title: row.title,
|
|
971
|
+
content: row.body,
|
|
972
|
+
entities: [...row.entities],
|
|
973
|
+
updatedAt: row.updatedAt,
|
|
974
|
+
...(row.metadata.sourceUrl !== undefined ? { sourceUrl: row.metadata.sourceUrl } : {}),
|
|
975
|
+
...(row.metadata.fetchedAt !== undefined ? { fetchedAt: row.metadata.fetchedAt } : {}),
|
|
976
|
+
});
|
|
977
|
+
}
|
|
978
|
+
currentParamProfile(scopeKey) {
|
|
979
|
+
if (!this.active) {
|
|
980
|
+
throw new AssistantAssociationError('disposed', 'assistant-association service is disposed');
|
|
981
|
+
}
|
|
982
|
+
if (!this.assocConfig.enabled || this.paramLedger === null) {
|
|
983
|
+
throw new AssistantAssociationError('disabled', 'assistant-association is disabled');
|
|
984
|
+
}
|
|
985
|
+
return this.paramLedger.current(scopeKey);
|
|
986
|
+
}
|
|
987
|
+
paramTuningStatus(scopeKey, eventLimit = 50) {
|
|
988
|
+
if (!this.active) {
|
|
989
|
+
throw new AssistantAssociationError('disposed', 'assistant-association service is disposed');
|
|
990
|
+
}
|
|
991
|
+
if (!this.assocConfig.enabled || this.paramLedger === null) {
|
|
992
|
+
throw new AssistantAssociationError('disabled', 'assistant-association is disabled');
|
|
993
|
+
}
|
|
994
|
+
return this.paramLedger.status(scopeKey, eventLimit);
|
|
995
|
+
}
|
|
996
|
+
requestParamTuning(input) {
|
|
997
|
+
if (!this.active) {
|
|
998
|
+
throw new AssistantAssociationError('disposed', 'assistant-association service is disposed');
|
|
999
|
+
}
|
|
1000
|
+
if (!this.assocConfig.enabled || this.paramLedger === null) {
|
|
1001
|
+
throw new AssistantAssociationError('disabled', 'assistant-association is disabled');
|
|
1002
|
+
}
|
|
1003
|
+
return this.paramLedger.requestChange(input);
|
|
1004
|
+
}
|
|
1005
|
+
reconcileParamTuning(scopeKey, nowMs) {
|
|
1006
|
+
if (!this.active) {
|
|
1007
|
+
throw new AssistantAssociationError('disposed', 'assistant-association service is disposed');
|
|
1008
|
+
}
|
|
1009
|
+
if (!this.assocConfig.enabled || this.paramLedger === null) {
|
|
1010
|
+
throw new AssistantAssociationError('disabled', 'assistant-association is disabled');
|
|
1011
|
+
}
|
|
1012
|
+
const filterTemplate = {
|
|
1013
|
+
allowLowTrust: this.assocConfig.allowLowTrust,
|
|
1014
|
+
allowSensitive: this.assocConfig.allowSensitive,
|
|
1015
|
+
};
|
|
1016
|
+
if (scopeKey !== undefined) {
|
|
1017
|
+
return this.paramLedger.tick({
|
|
1018
|
+
scopeKey,
|
|
1019
|
+
...(nowMs === undefined ? {} : { nowMs }),
|
|
1020
|
+
...(this.activeIndex === null ? {} : { index: this.activeIndex }),
|
|
1021
|
+
filterTemplate,
|
|
1022
|
+
});
|
|
1023
|
+
}
|
|
1024
|
+
const allScopes = new Set(this.paramLedger.listScopeKeys());
|
|
1025
|
+
if (this.sourceManager !== null) {
|
|
1026
|
+
for (const scope of this.sourceManager.listScopes()) {
|
|
1027
|
+
allScopes.add(scope.ownerScopeKey);
|
|
1028
|
+
}
|
|
1029
|
+
}
|
|
1030
|
+
const results = {};
|
|
1031
|
+
for (const key of allScopes) {
|
|
1032
|
+
results[key] = this.paramLedger.tick({
|
|
1033
|
+
scopeKey: key,
|
|
1034
|
+
...(nowMs === undefined ? {} : { nowMs }),
|
|
1035
|
+
...(this.activeIndex === null ? {} : { index: this.activeIndex }),
|
|
1036
|
+
filterTemplate,
|
|
1037
|
+
});
|
|
1038
|
+
}
|
|
1039
|
+
return Object.freeze(results);
|
|
1040
|
+
}
|
|
1041
|
+
async runHebbianDecayPass(nowMs) {
|
|
1042
|
+
if (!this.active) {
|
|
1043
|
+
throw new AssistantAssociationError('disposed', 'assistant-association service is disposed');
|
|
1044
|
+
}
|
|
1045
|
+
if (!this.assocConfig.enabled || this.writeQueue === null) {
|
|
1046
|
+
throw new AssistantAssociationError('disabled', 'assistant-association is disabled');
|
|
1047
|
+
}
|
|
1048
|
+
if (!this.assocConfig.hebbian.enabled)
|
|
1049
|
+
return;
|
|
1050
|
+
this.enqueueHebbianDecayPass(nowMs);
|
|
1051
|
+
await this.flush();
|
|
1052
|
+
}
|
|
1053
|
+
async syncAll() {
|
|
1054
|
+
if (this.sourceManager !== null) {
|
|
1055
|
+
await this.sourceManager.syncAll();
|
|
1056
|
+
}
|
|
1057
|
+
await this.flush();
|
|
1058
|
+
}
|
|
1059
|
+
async syncScope(scope) {
|
|
1060
|
+
if (this.sourceManager !== null) {
|
|
1061
|
+
this.sourceManager.registerScope(scope);
|
|
1062
|
+
await this.sourceManager.syncScope(scope);
|
|
1063
|
+
}
|
|
1064
|
+
await this.flush();
|
|
1065
|
+
}
|
|
1066
|
+
async flush() {
|
|
1067
|
+
if (this.pendingTasks.size > 0) {
|
|
1068
|
+
await Promise.allSettled(this.pendingTasks);
|
|
1069
|
+
}
|
|
1070
|
+
if (this.writeQueue !== null) {
|
|
1071
|
+
await this.writeQueue.flush();
|
|
1072
|
+
}
|
|
1073
|
+
if (this.pendingTasks.size > 0) {
|
|
1074
|
+
await Promise.allSettled(this.pendingTasks);
|
|
1075
|
+
}
|
|
1076
|
+
if (this.rebuildInFlight !== null) {
|
|
1077
|
+
await this.rebuildInFlight;
|
|
1078
|
+
}
|
|
1079
|
+
}
|
|
1080
|
+
async refreshIndex() {
|
|
1081
|
+
await this.flush();
|
|
1082
|
+
await this.rebuildIndex();
|
|
1083
|
+
}
|
|
1084
|
+
async runDreamingNow(scope, options) {
|
|
1085
|
+
if (!this.active) {
|
|
1086
|
+
throw new AssistantAssociationError('disposed', 'assistant-association service is disposed');
|
|
1087
|
+
}
|
|
1088
|
+
if (!this.assocConfig.enabled || this.assocStore === null || this.writeQueue === null) {
|
|
1089
|
+
throw new AssistantAssociationError('disabled', 'assistant-association is disabled');
|
|
1090
|
+
}
|
|
1091
|
+
await this.writeQueue.flush();
|
|
1092
|
+
if (!this.active) {
|
|
1093
|
+
throw new AssistantAssociationError('disposed', 'assistant-association service is disposed');
|
|
1094
|
+
}
|
|
1095
|
+
const nowMs = options?.nowMs ?? this.nowClock();
|
|
1096
|
+
const delivery = this.ctx.get('assistantDelivery', false);
|
|
1097
|
+
const dreaming = this.ctx.get('assistantDreaming', false);
|
|
1098
|
+
let ideas;
|
|
1099
|
+
if (dreaming !== undefined && typeof dreaming.inspectIdeas === 'function') {
|
|
1100
|
+
try {
|
|
1101
|
+
ideas = dreaming.inspectIdeas(200).map((idea) => ({
|
|
1102
|
+
id: idea.id,
|
|
1103
|
+
lane: idea.lane,
|
|
1104
|
+
runId: idea.runId,
|
|
1105
|
+
createdAt: idea.createdAt,
|
|
1106
|
+
dayKey: idea.dayKey,
|
|
1107
|
+
state: idea.state,
|
|
1108
|
+
summary: idea.summary,
|
|
1109
|
+
detail: idea.detail,
|
|
1110
|
+
evidenceRefs: [...idea.evidenceRefs],
|
|
1111
|
+
}));
|
|
1112
|
+
}
|
|
1113
|
+
catch {
|
|
1114
|
+
ideas = undefined;
|
|
1115
|
+
}
|
|
1116
|
+
}
|
|
1117
|
+
const evictedNodeIds = new Set();
|
|
1118
|
+
const resolvedLastActivity = options?.lastActivityAt !== undefined
|
|
1119
|
+
? options.lastActivityAt
|
|
1120
|
+
: this.lastActivityByScope.get(scope.ownerScopeKey);
|
|
1121
|
+
const hasRunningAgent = options?.hasRunningAgent ?? this.hasRunningAgentForScope(scope.ownerScopeKey);
|
|
1122
|
+
const result = runDreamingPass({
|
|
1123
|
+
db: this.assocStore.database,
|
|
1124
|
+
scope,
|
|
1125
|
+
config: this.assocConfig.dreaming,
|
|
1126
|
+
policy: this.policy,
|
|
1127
|
+
...(delivery === undefined ? {} : { delivery }),
|
|
1128
|
+
hasRunningAgent,
|
|
1129
|
+
...(resolvedLastActivity !== undefined ? { lastActivityAt: resolvedLastActivity } : {}),
|
|
1130
|
+
nowMs,
|
|
1131
|
+
...(ideas === undefined ? {} : { ideas }),
|
|
1132
|
+
weightMin: options?.weightMin ?? this.assocConfig.hebbian.weightMin,
|
|
1133
|
+
weightMax: options?.weightMax ?? this.assocConfig.hebbian.weightMax,
|
|
1134
|
+
...(options?.nodeLimit !== undefined ? { nodeLimit: options.nodeLimit } : {}),
|
|
1135
|
+
writer: {
|
|
1136
|
+
upsertBatch: (batch) => {
|
|
1137
|
+
const res = this.assocStore.upsertBatch(batch);
|
|
1138
|
+
for (const id of res.deletedNodeIds)
|
|
1139
|
+
evictedNodeIds.add(id);
|
|
1140
|
+
for (const id of res.suppressedNodeIds)
|
|
1141
|
+
evictedNodeIds.add(id);
|
|
1142
|
+
return res;
|
|
1143
|
+
},
|
|
1144
|
+
withdrawSource: (w) => {
|
|
1145
|
+
const res = this.assocStore.withdrawSource({ ...w, hardDelete: true });
|
|
1146
|
+
for (const id of res.deletedNodeIds)
|
|
1147
|
+
evictedNodeIds.add(id);
|
|
1148
|
+
for (const id of res.suppressedNodeIds)
|
|
1149
|
+
evictedNodeIds.add(id);
|
|
1150
|
+
return res;
|
|
1151
|
+
},
|
|
1152
|
+
},
|
|
1153
|
+
});
|
|
1154
|
+
if (evictedNodeIds.size > 0) {
|
|
1155
|
+
if (this.activeIndex !== null) {
|
|
1156
|
+
for (const id of evictedNodeIds) {
|
|
1157
|
+
this.activeIndex.tombstoneNodeId(id);
|
|
1158
|
+
}
|
|
1159
|
+
}
|
|
1160
|
+
this.evictNodesAcrossActiveAgents(evictedNodeIds);
|
|
1161
|
+
}
|
|
1162
|
+
if (result.ran &&
|
|
1163
|
+
(result.edgesCreated > 0 ||
|
|
1164
|
+
result.abstractionsCreated > 0 ||
|
|
1165
|
+
result.synonymsCreated > 0 ||
|
|
1166
|
+
result.expiredSwept > 0 ||
|
|
1167
|
+
result.ideasProjected > 0 ||
|
|
1168
|
+
result.ideasWithdrawn > 0)) {
|
|
1169
|
+
await this.rebuildIndex();
|
|
1170
|
+
}
|
|
1171
|
+
return result;
|
|
1172
|
+
}
|
|
1173
|
+
listDreamRuns(ownerScopeKey, limit = 20) {
|
|
1174
|
+
if (!this.active) {
|
|
1175
|
+
throw new AssistantAssociationError('disposed', 'assistant-association service is disposed');
|
|
1176
|
+
}
|
|
1177
|
+
if (!this.assocConfig.enabled || this.assocStore === null) {
|
|
1178
|
+
throw new AssistantAssociationError('disabled', 'assistant-association is disabled');
|
|
1179
|
+
}
|
|
1180
|
+
return queryDreamRuns(this.assocStore.database, ownerScopeKey, limit);
|
|
1181
|
+
}
|
|
1182
|
+
async sweepExpiredNodesNow(nowMs) {
|
|
1183
|
+
if (!this.active) {
|
|
1184
|
+
throw new AssistantAssociationError('disposed', 'assistant-association service is disposed');
|
|
1185
|
+
}
|
|
1186
|
+
if (!this.assocConfig.enabled || this.assocStore === null || this.writeQueue === null) {
|
|
1187
|
+
throw new AssistantAssociationError('disabled', 'assistant-association is disabled');
|
|
1188
|
+
}
|
|
1189
|
+
await this.writeQueue.flush();
|
|
1190
|
+
if (!this.active) {
|
|
1191
|
+
throw new AssistantAssociationError('disposed', 'assistant-association service is disposed');
|
|
1192
|
+
}
|
|
1193
|
+
const effectiveNow = nowMs ?? this.nowClock();
|
|
1194
|
+
const evicted = new Set();
|
|
1195
|
+
const swept = sweepExpiredDreamingNodes(this.assocStore.database, {
|
|
1196
|
+
nowMs: effectiveNow,
|
|
1197
|
+
withdrawSource: (w) => {
|
|
1198
|
+
const res = this.assocStore.withdrawSource({ ...w, hardDelete: true });
|
|
1199
|
+
for (const id of res.deletedNodeIds)
|
|
1200
|
+
evicted.add(id);
|
|
1201
|
+
for (const id of res.suppressedNodeIds)
|
|
1202
|
+
evicted.add(id);
|
|
1203
|
+
return res;
|
|
1204
|
+
},
|
|
1205
|
+
});
|
|
1206
|
+
for (const target of swept) {
|
|
1207
|
+
evicted.add(target.id);
|
|
1208
|
+
}
|
|
1209
|
+
if (evicted.size > 0) {
|
|
1210
|
+
if (this.activeIndex !== null) {
|
|
1211
|
+
for (const id of evicted) {
|
|
1212
|
+
this.activeIndex.tombstoneNodeId(id);
|
|
1213
|
+
}
|
|
1214
|
+
}
|
|
1215
|
+
this.evictNodesAcrossActiveAgents(evicted);
|
|
1216
|
+
await this.rebuildIndex();
|
|
1217
|
+
}
|
|
1218
|
+
return swept;
|
|
1219
|
+
}
|
|
1220
|
+
emitIntakeSignalNow(input) {
|
|
1221
|
+
if (!this.active) {
|
|
1222
|
+
throw new AssistantAssociationError('disposed', 'assistant-association service is disposed');
|
|
1223
|
+
}
|
|
1224
|
+
if (!this.assocConfig.enabled || this.assocStore === null) {
|
|
1225
|
+
throw new AssistantAssociationError('disabled', 'assistant-association is disabled');
|
|
1226
|
+
}
|
|
1227
|
+
const assistantWorkItems = this.ctx.get('assistantWorkItems', false);
|
|
1228
|
+
return emitAssociationIntakeSignal({
|
|
1229
|
+
db: this.assocStore.database,
|
|
1230
|
+
scope: input.scope,
|
|
1231
|
+
config: this.assocConfig.intakeSignal,
|
|
1232
|
+
goalNode: input.goalNode,
|
|
1233
|
+
targetNode: input.targetNode,
|
|
1234
|
+
score: input.score,
|
|
1235
|
+
...(input.reason !== undefined ? { reason: input.reason } : {}),
|
|
1236
|
+
inHoldout: input.inHoldout,
|
|
1237
|
+
policy: this.policy,
|
|
1238
|
+
...(assistantWorkItems === undefined ? {} : { assistantWorkItems }),
|
|
1239
|
+
nowMs: input.nowMs ?? this.nowClock(),
|
|
1240
|
+
});
|
|
1241
|
+
}
|
|
1242
|
+
listIntakeSignals(ownerScopeKey, limit = 50) {
|
|
1243
|
+
if (!this.active) {
|
|
1244
|
+
throw new AssistantAssociationError('disposed', 'assistant-association service is disposed');
|
|
1245
|
+
}
|
|
1246
|
+
if (!this.assocConfig.enabled || this.assocStore === null) {
|
|
1247
|
+
throw new AssistantAssociationError('disabled', 'assistant-association is disabled');
|
|
1248
|
+
}
|
|
1249
|
+
return queryIntakeSignals(this.assocStore.database, ownerScopeKey, limit);
|
|
1250
|
+
}
|
|
1251
|
+
async runClusteringNow(scope, options) {
|
|
1252
|
+
if (!this.active) {
|
|
1253
|
+
throw new AssistantAssociationError('disposed', 'assistant-association service is disposed');
|
|
1254
|
+
}
|
|
1255
|
+
if (!this.assocConfig.enabled || this.assocStore === null) {
|
|
1256
|
+
throw new AssistantAssociationError('disabled', 'assistant-association is disabled');
|
|
1257
|
+
}
|
|
1258
|
+
await this.writeQueue?.flush();
|
|
1259
|
+
if (!this.active) {
|
|
1260
|
+
throw new AssistantAssociationError('disposed', 'assistant-association service is disposed');
|
|
1261
|
+
}
|
|
1262
|
+
const ownerScopeKey = typeof scope === 'string' ? scope : scope.ownerScopeKey;
|
|
1263
|
+
const nowMs = options?.nowMs ?? this.nowClock();
|
|
1264
|
+
const cfg = options?.config ?? this.assocConfig.clustering;
|
|
1265
|
+
const persist = options?.persist ?? true;
|
|
1266
|
+
const clustering = await clusterEpisodes(this.assocStore.database, {
|
|
1267
|
+
ownerScopeKey,
|
|
1268
|
+
holdoutSeedKey: this.holdoutSeedKey,
|
|
1269
|
+
holdoutRateBps: this.assocConfig.holdoutRateBps,
|
|
1270
|
+
config: cfg,
|
|
1271
|
+
...(options?.episodes !== undefined ? { episodes: options.episodes } : {}),
|
|
1272
|
+
...(options?.benchmarkPlan !== undefined ? { benchmarkPlan: options.benchmarkPlan } : {}),
|
|
1273
|
+
nowMs,
|
|
1274
|
+
persist,
|
|
1275
|
+
});
|
|
1276
|
+
const implicitSignals = detectImplicitSignals(this.assocStore.database, {
|
|
1277
|
+
ownerScopeKey,
|
|
1278
|
+
holdoutSeedKey: this.holdoutSeedKey,
|
|
1279
|
+
holdoutRateBps: this.assocConfig.holdoutRateBps,
|
|
1280
|
+
config: cfg,
|
|
1281
|
+
...(options?.episodes !== undefined ? { episodes: options.episodes } : {}),
|
|
1282
|
+
nowMs,
|
|
1283
|
+
persist,
|
|
1284
|
+
});
|
|
1285
|
+
let reportedImplicitSignals = {
|
|
1286
|
+
reported: 0,
|
|
1287
|
+
skipped: 0,
|
|
1288
|
+
};
|
|
1289
|
+
if (options?.reportImplicitSignals !== false &&
|
|
1290
|
+
implicitSignals.signals.length > 0 &&
|
|
1291
|
+
this.active) {
|
|
1292
|
+
const resolvedScope = typeof scope === 'string'
|
|
1293
|
+
? this.sourceManager?.listScopes().find((s) => s.ownerScopeKey === ownerScopeKey)
|
|
1294
|
+
: scope;
|
|
1295
|
+
if (resolvedScope !== undefined) {
|
|
1296
|
+
const evalPeer = this.ctx.get('assistantEvaluation', false);
|
|
1297
|
+
reportedImplicitSignals = reportImplicitSignalsToEvaluation(evalPeer, implicitSignals.signals, { workspace: resolvedScope.workspace, preset: resolvedScope.agentPreset });
|
|
1298
|
+
}
|
|
1299
|
+
}
|
|
1300
|
+
return Object.freeze({
|
|
1301
|
+
clustering,
|
|
1302
|
+
implicitSignals,
|
|
1303
|
+
reportedImplicitSignals,
|
|
1304
|
+
});
|
|
1305
|
+
}
|
|
1306
|
+
listSkillCandidates(ownerScopeKey, options) {
|
|
1307
|
+
if (!this.active) {
|
|
1308
|
+
throw new AssistantAssociationError('disposed', 'assistant-association service is disposed');
|
|
1309
|
+
}
|
|
1310
|
+
if (!this.assocConfig.enabled || this.assocStore === null) {
|
|
1311
|
+
throw new AssistantAssociationError('disabled', 'assistant-association is disabled');
|
|
1312
|
+
}
|
|
1313
|
+
return querySkillCandidates(this.assocStore.database, ownerScopeKey, options);
|
|
1314
|
+
}
|
|
1315
|
+
listImplicitSignals(ownerScopeKey, options) {
|
|
1316
|
+
if (!this.active) {
|
|
1317
|
+
throw new AssistantAssociationError('disposed', 'assistant-association service is disposed');
|
|
1318
|
+
}
|
|
1319
|
+
if (!this.assocConfig.enabled || this.assocStore === null) {
|
|
1320
|
+
throw new AssistantAssociationError('disabled', 'assistant-association is disabled');
|
|
1321
|
+
}
|
|
1322
|
+
return queryImplicitSignals(this.assocStore.database, ownerScopeKey, options);
|
|
1323
|
+
}
|
|
1324
|
+
listEvalPool(ownerScopeKey, options) {
|
|
1325
|
+
if (!this.active) {
|
|
1326
|
+
throw new AssistantAssociationError('disposed', 'assistant-association service is disposed');
|
|
1327
|
+
}
|
|
1328
|
+
if (!this.assocConfig.enabled || this.assocStore === null) {
|
|
1329
|
+
throw new AssistantAssociationError('disabled', 'assistant-association is disabled');
|
|
1330
|
+
}
|
|
1331
|
+
return queryEvalPool(this.assocStore.database, ownerScopeKey, options);
|
|
1332
|
+
}
|
|
1333
|
+
async runWebLearningNow(scope, options) {
|
|
1334
|
+
if (!this.active) {
|
|
1335
|
+
throw new AssistantAssociationError('disposed', 'assistant-association service is disposed');
|
|
1336
|
+
}
|
|
1337
|
+
if (!this.assocConfig.enabled || this.assocStore === null || this.writeQueue === null) {
|
|
1338
|
+
throw new AssistantAssociationError('disabled', 'assistant-association is disabled');
|
|
1339
|
+
}
|
|
1340
|
+
const nowMs = options?.nowMs ?? options?.now ?? this.nowClock();
|
|
1341
|
+
if (this.inFlightWebLearningScopes.has(scope.ownerScopeKey)) {
|
|
1342
|
+
return {
|
|
1343
|
+
ran: false,
|
|
1344
|
+
runId: null,
|
|
1345
|
+
status: 'skipped',
|
|
1346
|
+
reason: 'run-in-progress',
|
|
1347
|
+
topicsConsidered: 0,
|
|
1348
|
+
requestsUsed: 0,
|
|
1349
|
+
pagesFetched: 0,
|
|
1350
|
+
bytesFetched: 0,
|
|
1351
|
+
nodesWritten: 0,
|
|
1352
|
+
edgesWritten: 0,
|
|
1353
|
+
writtenNodeIds: [],
|
|
1354
|
+
interests: [],
|
|
1355
|
+
fetches: [],
|
|
1356
|
+
dailyUsage: queryWebLearningBudgetUsage(this.assocStore.database, scope.ownerScopeKey, nowMs),
|
|
1357
|
+
};
|
|
1358
|
+
}
|
|
1359
|
+
const store = this.assocStore;
|
|
1360
|
+
const writeQueue = this.writeQueue;
|
|
1361
|
+
this.inFlightWebLearningScopes.add(scope.ownerScopeKey);
|
|
1362
|
+
const execution = (async () => {
|
|
1363
|
+
await writeQueue.flush();
|
|
1364
|
+
if (!this.active) {
|
|
1365
|
+
throw new AssistantAssociationError('disposed', 'assistant-association service is disposed');
|
|
1366
|
+
}
|
|
1367
|
+
if (writeQueue.hasPendingWithdrawals) {
|
|
1368
|
+
await writeQueue.flush();
|
|
1369
|
+
}
|
|
1370
|
+
if (!this.active) {
|
|
1371
|
+
throw new AssistantAssociationError('disposed', 'assistant-association service is disposed');
|
|
1372
|
+
}
|
|
1373
|
+
const delivery = this.ctx.get('assistantDelivery', false);
|
|
1374
|
+
const resolvedLastActivity = options?.lastActivityAt !== undefined
|
|
1375
|
+
? options.lastActivityAt
|
|
1376
|
+
: this.lastActivityByScope.get(scope.ownerScopeKey);
|
|
1377
|
+
const hasRunningAgent = options?.hasRunningAgent ?? this.hasRunningAgentForScope(scope.ownerScopeKey);
|
|
1378
|
+
const effectiveSignal = options?.signal !== undefined
|
|
1379
|
+
? AbortSignal.any([this.effectAbortController.signal, options.signal])
|
|
1380
|
+
: this.effectAbortController.signal;
|
|
1381
|
+
const result = await runWebLearningPass({
|
|
1382
|
+
store,
|
|
1383
|
+
scope,
|
|
1384
|
+
rootEnabled: this.assocConfig.enabled,
|
|
1385
|
+
config: this.assocConfig.webLearning,
|
|
1386
|
+
policy: this.policy,
|
|
1387
|
+
...(delivery === undefined ? {} : { delivery }),
|
|
1388
|
+
hasRunningAgent,
|
|
1389
|
+
...(resolvedLastActivity !== undefined ? { lastActivityAt: resolvedLastActivity } : {}),
|
|
1390
|
+
...(options?.ignoreIdle !== undefined ? { ignoreIdle: options.ignoreIdle } : {}),
|
|
1391
|
+
nowMs,
|
|
1392
|
+
...(options?.runner !== undefined ? { runner: options.runner } : {}),
|
|
1393
|
+
...(options?.workerDeps !== undefined ? { workerDeps: options.workerDeps } : {}),
|
|
1394
|
+
...(options?.subprocessOptions !== undefined
|
|
1395
|
+
? { subprocessOptions: options.subprocessOptions }
|
|
1396
|
+
: {}),
|
|
1397
|
+
signal: effectiveSignal,
|
|
1398
|
+
enqueueUpsertNodes: async (batch) => {
|
|
1399
|
+
if (!this.active || this.writeQueue === null || effectiveSignal.aborted)
|
|
1400
|
+
return;
|
|
1401
|
+
this.writeQueue.enqueue({
|
|
1402
|
+
kind: 'upsert-nodes',
|
|
1403
|
+
nodes: batch.nodes,
|
|
1404
|
+
edges: batch.edges,
|
|
1405
|
+
derivedRefs: batch.derivedRefs,
|
|
1406
|
+
});
|
|
1407
|
+
await this.writeQueue.flush();
|
|
1408
|
+
},
|
|
1409
|
+
});
|
|
1410
|
+
if (this.active && (result.nodesWritten > 0 || result.edgesWritten > 0)) {
|
|
1411
|
+
await this.rebuildIndex();
|
|
1412
|
+
}
|
|
1413
|
+
return result;
|
|
1414
|
+
})().finally(() => {
|
|
1415
|
+
this.inFlightWebLearningScopes.delete(scope.ownerScopeKey);
|
|
1416
|
+
});
|
|
1417
|
+
this.trackBackgroundTask(execution.then(() => { }, () => { }));
|
|
1418
|
+
return await execution;
|
|
1419
|
+
}
|
|
1420
|
+
listWebLearningRuns(ownerScopeKey, limit = 20) {
|
|
1421
|
+
if (!this.active) {
|
|
1422
|
+
throw new AssistantAssociationError('disposed', 'assistant-association service is disposed');
|
|
1423
|
+
}
|
|
1424
|
+
if (!this.assocConfig.enabled || this.assocStore === null) {
|
|
1425
|
+
throw new AssistantAssociationError('disabled', 'assistant-association is disabled');
|
|
1426
|
+
}
|
|
1427
|
+
return queryWebLearningRuns(this.assocStore.database, ownerScopeKey, limit);
|
|
1428
|
+
}
|
|
1429
|
+
listWebLearningFetches(ownerScopeKey, limit = 50) {
|
|
1430
|
+
if (!this.active) {
|
|
1431
|
+
throw new AssistantAssociationError('disposed', 'assistant-association service is disposed');
|
|
1432
|
+
}
|
|
1433
|
+
if (!this.assocConfig.enabled || this.assocStore === null) {
|
|
1434
|
+
throw new AssistantAssociationError('disabled', 'assistant-association is disabled');
|
|
1435
|
+
}
|
|
1436
|
+
return queryWebLearningFetches(this.assocStore.database, ownerScopeKey, limit);
|
|
1437
|
+
}
|
|
1438
|
+
getWebLearningBudgetUsage(ownerScopeKey, utcDay) {
|
|
1439
|
+
if (!this.active) {
|
|
1440
|
+
throw new AssistantAssociationError('disposed', 'assistant-association service is disposed');
|
|
1441
|
+
}
|
|
1442
|
+
if (!this.assocConfig.enabled || this.assocStore === null) {
|
|
1443
|
+
throw new AssistantAssociationError('disabled', 'assistant-association is disabled');
|
|
1444
|
+
}
|
|
1445
|
+
let effectiveNowMs;
|
|
1446
|
+
if (typeof utcDay === 'string') {
|
|
1447
|
+
if (!/^\d{4}-\d{2}-\d{2}$/u.test(utcDay)) {
|
|
1448
|
+
throw new AssistantAssociationError('invalid-input', 'utcDay must be formatted as YYYY-MM-DD');
|
|
1449
|
+
}
|
|
1450
|
+
const parsed = Date.parse(`${utcDay}T00:00:00.000Z`);
|
|
1451
|
+
if (!Number.isFinite(parsed)) {
|
|
1452
|
+
throw new AssistantAssociationError('invalid-input', 'utcDay is not a valid UTC date');
|
|
1453
|
+
}
|
|
1454
|
+
effectiveNowMs = parsed;
|
|
1455
|
+
}
|
|
1456
|
+
else {
|
|
1457
|
+
effectiveNowMs = utcDay ?? this.nowClock();
|
|
1458
|
+
}
|
|
1459
|
+
return queryWebLearningBudgetUsage(this.assocStore.database, ownerScopeKey, effectiveNowMs);
|
|
1460
|
+
}
|
|
1461
|
+
async withdrawWebSource(scope, sourceUrl, nowMs) {
|
|
1462
|
+
if (!this.active) {
|
|
1463
|
+
throw new AssistantAssociationError('disposed', 'assistant-association service is disposed');
|
|
1464
|
+
}
|
|
1465
|
+
if (!this.assocConfig.enabled || this.assocStore === null || this.writeQueue === null) {
|
|
1466
|
+
throw new AssistantAssociationError('disabled', 'assistant-association is disabled');
|
|
1467
|
+
}
|
|
1468
|
+
await this.writeQueue.flush();
|
|
1469
|
+
if (!this.active) {
|
|
1470
|
+
throw new AssistantAssociationError('disposed', 'assistant-association service is disposed');
|
|
1471
|
+
}
|
|
1472
|
+
const canonicalUrl = canonicalizeWebSourceUrl(sourceUrl);
|
|
1473
|
+
const sourceRef = computeWebSourceRef(canonicalUrl);
|
|
1474
|
+
this.writeQueue.markTombstoneSync({
|
|
1475
|
+
ownerScopeKey: scope.ownerScopeKey,
|
|
1476
|
+
sourcePlugin: WEB_LEARNING_SOURCE_PLUGIN,
|
|
1477
|
+
sourceRef,
|
|
1478
|
+
});
|
|
1479
|
+
this.activeIndex?.tombstoneSourceRef(scope.ownerScopeKey, WEB_LEARNING_SOURCE_PLUGIN, sourceRef);
|
|
1480
|
+
const result = withdrawWebSourceByUrl(this.assocStore, scope, sourceUrl, nowMs ?? this.nowClock());
|
|
1481
|
+
const evicted = new Set([...result.deletedNodeIds, ...result.suppressedNodeIds]);
|
|
1482
|
+
if (evicted.size > 0) {
|
|
1483
|
+
if (this.activeIndex !== null) {
|
|
1484
|
+
for (const id of evicted) {
|
|
1485
|
+
this.activeIndex.tombstoneNodeId(id);
|
|
1486
|
+
}
|
|
1487
|
+
}
|
|
1488
|
+
this.evictNodesAcrossActiveAgents(evicted);
|
|
1489
|
+
}
|
|
1490
|
+
await this.rebuildIndex();
|
|
1491
|
+
return result;
|
|
1492
|
+
}
|
|
1493
|
+
resolveAgentScope(agent) {
|
|
1494
|
+
return resolveOwnerScope(this.ctx, agent, {
|
|
1495
|
+
allowHeadlessScope: this.assocConfig.allowHeadlessScope,
|
|
1496
|
+
headlessPrincipals: this.headlessPrincipals,
|
|
1497
|
+
});
|
|
1498
|
+
}
|
|
1499
|
+
resolveReadEventScopeSafe(agent) {
|
|
1500
|
+
if (agent === undefined)
|
|
1501
|
+
return undefined;
|
|
1502
|
+
const agents = this.ctx.get('agents', false);
|
|
1503
|
+
if (agents !== undefined && agents.get(agent.id) !== agent)
|
|
1504
|
+
return undefined;
|
|
1505
|
+
const sessions = this.ctx.get('sessions', false);
|
|
1506
|
+
if (sessions !== undefined && sessions.get(agent.session.id) !== agent.session)
|
|
1507
|
+
return undefined;
|
|
1508
|
+
return this.resolveAgentScope(agent);
|
|
1509
|
+
}
|
|
1510
|
+
recordReadEvent(ownerScopeKey, taskId, nodeId, hit, reason, occurredAt) {
|
|
1511
|
+
if (this.writeQueue === null)
|
|
1512
|
+
return;
|
|
1513
|
+
this.writeQueue.enqueue({
|
|
1514
|
+
kind: 'record-read-event',
|
|
1515
|
+
event: {
|
|
1516
|
+
taskId,
|
|
1517
|
+
nodeId: nodeId.length > 0 ? nodeId.slice(0, 256) : '<invalid>',
|
|
1518
|
+
ownerScopeKey,
|
|
1519
|
+
hit,
|
|
1520
|
+
reason,
|
|
1521
|
+
occurredAt,
|
|
1522
|
+
},
|
|
1523
|
+
});
|
|
1524
|
+
}
|
|
1525
|
+
processWeakUseFromAssistantText(agent, state, ownerScope, taskId, assistantText, nowMs) {
|
|
1526
|
+
const activeIndex = this.activeIndex;
|
|
1527
|
+
if (activeIndex === null || this.writeQueue === null)
|
|
1528
|
+
return;
|
|
1529
|
+
const taskExpMap = state.taskExposures.get(taskId);
|
|
1530
|
+
if (taskExpMap === undefined || taskExpMap.size === 0)
|
|
1531
|
+
return;
|
|
1532
|
+
const exposedNodes = [];
|
|
1533
|
+
let hasUnusedExposed = false;
|
|
1534
|
+
for (const entry of taskExpMap.values()) {
|
|
1535
|
+
const slot = activeIndex.nodeIdToSlot.get(entry.nodeId);
|
|
1536
|
+
if (slot === undefined || activeIndex.nodeTombstoned[slot] !== 0)
|
|
1537
|
+
continue;
|
|
1538
|
+
if (!entry.strongUsed && !entry.weakUsed) {
|
|
1539
|
+
hasUnusedExposed = true;
|
|
1540
|
+
}
|
|
1541
|
+
exposedNodes.push({
|
|
1542
|
+
nodeId: entry.nodeId,
|
|
1543
|
+
entities: activeIndex.nodeEntities[slot] ?? [],
|
|
1544
|
+
});
|
|
1545
|
+
}
|
|
1546
|
+
if (!hasUnusedExposed || exposedNodes.length === 0)
|
|
1547
|
+
return;
|
|
1548
|
+
const matchedIds = detectWeakUseNodes({
|
|
1549
|
+
assistantText,
|
|
1550
|
+
exposedNodes,
|
|
1551
|
+
turnPromptEntities: state.turnPromptEntities,
|
|
1552
|
+
entityAutomaton: activeIndex.ac,
|
|
1553
|
+
ownerScopeKey: ownerScope.ownerScopeKey,
|
|
1554
|
+
allowLowTrust: this.assocConfig.allowLowTrust,
|
|
1555
|
+
});
|
|
1556
|
+
if (matchedIds.length === 0)
|
|
1557
|
+
return;
|
|
1558
|
+
const goalContext = resolveTaskId(this.ctx, agent, state, ownerScope).goalContext;
|
|
1559
|
+
const goalNodeId = goalContext !== undefined ? `a:g-${goalContext.goal.id}` : null;
|
|
1560
|
+
const episodeNodeId = taskId.startsWith('foreground-turn:')
|
|
1561
|
+
? `a:e-fg-${taskId.slice('foreground-turn:'.length)}`
|
|
1562
|
+
: null;
|
|
1563
|
+
const usedNodeIds = [];
|
|
1564
|
+
for (const nodeId of matchedIds) {
|
|
1565
|
+
const expEntry = taskExpMap.get(nodeId);
|
|
1566
|
+
if (expEntry === undefined || expEntry.strongUsed || expEntry.weakUsed)
|
|
1567
|
+
continue;
|
|
1568
|
+
expEntry.weakUsed = true;
|
|
1569
|
+
usedNodeIds.push(nodeId);
|
|
1570
|
+
const provenanceEdges = expEntry.provenanceEdges;
|
|
1571
|
+
const coActivatedNodeIds = provenanceEdges.length === 0 && expEntry.hop === 0
|
|
1572
|
+
? selectHop0CoActivationTargets({
|
|
1573
|
+
nodeId,
|
|
1574
|
+
coExposedNodeIds: [...taskExpMap.keys()],
|
|
1575
|
+
goalNodeId,
|
|
1576
|
+
sessionNodeIds: [...state.sessionActivation.keys()],
|
|
1577
|
+
episodeNodeId,
|
|
1578
|
+
})
|
|
1579
|
+
: [];
|
|
1580
|
+
this.writeQueue.enqueue({
|
|
1581
|
+
kind: 'apply-hebbian-use',
|
|
1582
|
+
useKind: 'weak',
|
|
1583
|
+
taskId,
|
|
1584
|
+
ownerScopeKey: ownerScope.ownerScopeKey,
|
|
1585
|
+
nodeId,
|
|
1586
|
+
sessionId: String(agent.session.id),
|
|
1587
|
+
...(provenanceEdges.length > 0 ? { provenanceEdges } : {}),
|
|
1588
|
+
...(coActivatedNodeIds.length > 0 ? { coActivatedNodeIds } : {}),
|
|
1589
|
+
nowMs,
|
|
1590
|
+
hebbianConfig: this.assocConfig.hebbian,
|
|
1591
|
+
});
|
|
1592
|
+
}
|
|
1593
|
+
if (usedNodeIds.length > 0) {
|
|
1594
|
+
this.writeQueue.enqueue({
|
|
1595
|
+
kind: 'upsert-replay-episode',
|
|
1596
|
+
episode: {
|
|
1597
|
+
taskId,
|
|
1598
|
+
ownerScopeKey: ownerScope.ownerScopeKey,
|
|
1599
|
+
inHoldout: false,
|
|
1600
|
+
cues: [],
|
|
1601
|
+
usedNodeIds,
|
|
1602
|
+
occurredAt: nowMs,
|
|
1603
|
+
},
|
|
1604
|
+
});
|
|
1605
|
+
}
|
|
1606
|
+
}
|
|
1607
|
+
enqueueHebbianDecayPass(nowMs) {
|
|
1608
|
+
if (!this.active || !this.assocConfig.hebbian.enabled || this.writeQueue === null)
|
|
1609
|
+
return;
|
|
1610
|
+
const heb = this.assocConfig.hebbian;
|
|
1611
|
+
this.writeQueue.enqueue({
|
|
1612
|
+
kind: 'apply-hebbian-decay',
|
|
1613
|
+
nowMs: nowMs ?? this.nowClock(),
|
|
1614
|
+
decayHalfLifeMs: heb.decayHalfLifeMs,
|
|
1615
|
+
nonUseGraceMs: heb.nonUseGraceMs,
|
|
1616
|
+
weightMin: heb.weightMin,
|
|
1617
|
+
weightMax: heb.weightMax,
|
|
1618
|
+
limit: 200,
|
|
1619
|
+
});
|
|
1620
|
+
}
|
|
1621
|
+
rebuildEdgesOnly() {
|
|
1622
|
+
if (!this.active || this.assocStore === null || this.activeIndex === null)
|
|
1623
|
+
return;
|
|
1624
|
+
if (this.writeQueue?.hasPendingWithdrawals)
|
|
1625
|
+
return;
|
|
1626
|
+
if (this.rebuildInFlight !== null) {
|
|
1627
|
+
this.rebuildQueued = true;
|
|
1628
|
+
return;
|
|
1629
|
+
}
|
|
1630
|
+
const baseIndex = this.activeIndex;
|
|
1631
|
+
const nowMs = this.nowClock();
|
|
1632
|
+
const edges = [];
|
|
1633
|
+
let offset = 0;
|
|
1634
|
+
const pageSize = 10_000;
|
|
1635
|
+
while (true) {
|
|
1636
|
+
const page = this.assocStore.loadActiveEdgesPage(pageSize, offset);
|
|
1637
|
+
if (page.length === 0)
|
|
1638
|
+
break;
|
|
1639
|
+
edges.push(...page);
|
|
1640
|
+
if (page.length < pageSize)
|
|
1641
|
+
break;
|
|
1642
|
+
offset += pageSize;
|
|
1643
|
+
}
|
|
1644
|
+
const indexEdges = [];
|
|
1645
|
+
for (const e of edges) {
|
|
1646
|
+
if (!baseIndex.nodeIdToSlot.has(e.aId) || !baseIndex.nodeIdToSlot.has(e.bId))
|
|
1647
|
+
continue;
|
|
1648
|
+
indexEdges.push({
|
|
1649
|
+
edgeId: e.edgeId,
|
|
1650
|
+
aId: e.aId,
|
|
1651
|
+
bId: e.bId,
|
|
1652
|
+
edgeType: e.edgeType,
|
|
1653
|
+
weight: e.weight,
|
|
1654
|
+
trust: e.trust,
|
|
1655
|
+
reason: e.reason,
|
|
1656
|
+
});
|
|
1657
|
+
}
|
|
1658
|
+
this.indexBuildEpoch += 1;
|
|
1659
|
+
this.activeIndex = rebuildMemoryIndexEdges(baseIndex, indexEdges, {
|
|
1660
|
+
buildEpoch: this.indexBuildEpoch,
|
|
1661
|
+
builtAt: nowMs,
|
|
1662
|
+
maxFanoutPerNode: this.assocConfig.maxFanoutPerNode,
|
|
1663
|
+
});
|
|
1664
|
+
}
|
|
1665
|
+
sourcePolicyResource(kind, sourceRef) {
|
|
1666
|
+
if (kind === 'memory')
|
|
1667
|
+
return { kind: 'memory', id: 'selected' };
|
|
1668
|
+
if (kind === 'goal')
|
|
1669
|
+
return { kind: 'goal', id: 'business-context' };
|
|
1670
|
+
if (kind === 'automation') {
|
|
1671
|
+
return { kind: 'automation', id: sourceRef.replace(/^automation:/u, '') || 'catalog' };
|
|
1672
|
+
}
|
|
1673
|
+
if (kind === 'wiki') {
|
|
1674
|
+
return { kind: 'wiki', id: sourceRef.replace(/^wiki:/u, '') || 'visible' };
|
|
1675
|
+
}
|
|
1676
|
+
return undefined;
|
|
1677
|
+
}
|
|
1678
|
+
triggerInvalidation(ownerScopeKey, sourcePlugin, sourceRef, nodeId) {
|
|
1679
|
+
this.writeQueue?.markTombstoneSync({
|
|
1680
|
+
nodeIds: [nodeId],
|
|
1681
|
+
ownerScopeKey,
|
|
1682
|
+
sourcePlugin,
|
|
1683
|
+
sourceRef,
|
|
1684
|
+
});
|
|
1685
|
+
this.activeIndex?.tombstoneNodeId(nodeId);
|
|
1686
|
+
this.evictNodesAcrossActiveAgents(new Set([nodeId]));
|
|
1687
|
+
this.writeQueue?.enqueue({
|
|
1688
|
+
kind: 'withdraw-source',
|
|
1689
|
+
ownerScopeKey,
|
|
1690
|
+
sourcePlugin,
|
|
1691
|
+
sourceRef,
|
|
1692
|
+
hardDelete: true,
|
|
1693
|
+
});
|
|
1694
|
+
}
|
|
1695
|
+
evictNodesAcrossActiveAgents(nodeIds) {
|
|
1696
|
+
if (nodeIds.size === 0)
|
|
1697
|
+
return;
|
|
1698
|
+
this.invalidationGeneration += 1;
|
|
1699
|
+
for (const agent of this.activeAgents) {
|
|
1700
|
+
const state = this.agentStates.get(agent);
|
|
1701
|
+
if (state !== undefined) {
|
|
1702
|
+
evictNodesFromAgentState(state, nodeIds);
|
|
1703
|
+
}
|
|
1704
|
+
}
|
|
1705
|
+
}
|
|
1706
|
+
recordHoldoutOnce(state, taskId, ownerScopeKey, taskKind, agent, turnNumber, holdout, nowMs) {
|
|
1707
|
+
if (this.writeQueue === null)
|
|
1708
|
+
return;
|
|
1709
|
+
if (state.recordedTaskIds.has(taskId))
|
|
1710
|
+
return;
|
|
1711
|
+
state.recordedTaskIds.add(taskId);
|
|
1712
|
+
while (state.recordedTaskIds.size > 256) {
|
|
1713
|
+
const oldest = state.recordedTaskIds.values().next().value;
|
|
1714
|
+
if (oldest === undefined)
|
|
1715
|
+
break;
|
|
1716
|
+
state.recordedTaskIds.delete(oldest);
|
|
1717
|
+
}
|
|
1718
|
+
this.writeQueue.enqueue({
|
|
1719
|
+
kind: 'record-holdout',
|
|
1720
|
+
row: {
|
|
1721
|
+
taskId,
|
|
1722
|
+
ownerScopeKey,
|
|
1723
|
+
taskKind,
|
|
1724
|
+
sessionId: String(agent.session.id),
|
|
1725
|
+
turnNumber,
|
|
1726
|
+
inHoldout: holdout.inHoldout,
|
|
1727
|
+
bucketBps: holdout.bucketBps,
|
|
1728
|
+
rateBps: holdout.rateBps,
|
|
1729
|
+
hmacDigest: holdout.hmacDigest,
|
|
1730
|
+
assignedAt: nowMs,
|
|
1731
|
+
},
|
|
1732
|
+
});
|
|
1733
|
+
if (holdout.inHoldout) {
|
|
1734
|
+
const profileVersion = this.paramLedger?.current(ownerScopeKey).version ?? 0;
|
|
1735
|
+
this.writeQueue.enqueue({
|
|
1736
|
+
kind: 'record-metrics',
|
|
1737
|
+
metrics: [
|
|
1738
|
+
{
|
|
1739
|
+
taskId,
|
|
1740
|
+
ownerScopeKey,
|
|
1741
|
+
inHoldout: true,
|
|
1742
|
+
latencyUs: 0,
|
|
1743
|
+
timedOut: false,
|
|
1744
|
+
fallbackMode: 'holdout',
|
|
1745
|
+
injectedCount: 0,
|
|
1746
|
+
candidateCount: 0,
|
|
1747
|
+
sourceCounts: {},
|
|
1748
|
+
profileVersion,
|
|
1749
|
+
occurredAt: nowMs,
|
|
1750
|
+
},
|
|
1751
|
+
],
|
|
1752
|
+
exposures: [],
|
|
1753
|
+
});
|
|
1754
|
+
}
|
|
1755
|
+
}
|
|
1756
|
+
enqueueStepMetrics(taskId, ownerScopeKey, inHoldout, elapsedMs, timedOut, fallbackMode, injected, candidateCount, nowMs, profileVersion = 0, sessionId) {
|
|
1757
|
+
if (this.writeQueue === null)
|
|
1758
|
+
return;
|
|
1759
|
+
const sourceCounts = {};
|
|
1760
|
+
for (const item of injected) {
|
|
1761
|
+
sourceCounts[item.kind] = (sourceCounts[item.kind] ?? 0) + 1;
|
|
1762
|
+
}
|
|
1763
|
+
this.writeQueue.enqueue({
|
|
1764
|
+
kind: 'record-metrics',
|
|
1765
|
+
metrics: [
|
|
1766
|
+
{
|
|
1767
|
+
taskId,
|
|
1768
|
+
ownerScopeKey,
|
|
1769
|
+
inHoldout,
|
|
1770
|
+
latencyUs: Math.max(0, Math.round(elapsedMs * 1_000)),
|
|
1771
|
+
timedOut,
|
|
1772
|
+
fallbackMode,
|
|
1773
|
+
injectedCount: injected.length,
|
|
1774
|
+
candidateCount,
|
|
1775
|
+
sourceCounts,
|
|
1776
|
+
profileVersion,
|
|
1777
|
+
occurredAt: nowMs,
|
|
1778
|
+
},
|
|
1779
|
+
],
|
|
1780
|
+
exposures: injected.map((item) => ({
|
|
1781
|
+
taskId,
|
|
1782
|
+
nodeId: item.id,
|
|
1783
|
+
ownerScopeKey,
|
|
1784
|
+
sourcePlugin: item.sourcePlugin,
|
|
1785
|
+
exposedAt: nowMs,
|
|
1786
|
+
wasExposed: true,
|
|
1787
|
+
hop: item.hop,
|
|
1788
|
+
score: item.score,
|
|
1789
|
+
reason: item.reason,
|
|
1790
|
+
provenanceEdges: item.provenanceEdges ?? [],
|
|
1791
|
+
sessionId: sessionId ?? null,
|
|
1792
|
+
})),
|
|
1793
|
+
});
|
|
1794
|
+
}
|
|
1795
|
+
rebuildIndexSync() {
|
|
1796
|
+
if (this.assocStore === null)
|
|
1797
|
+
return;
|
|
1798
|
+
const snapshotWithdrawalEpoch = this.writeQueue?.withdrawalEpoch ?? 0;
|
|
1799
|
+
const nowMs = this.nowClock();
|
|
1800
|
+
const total = this.assocStore.countActiveNodes();
|
|
1801
|
+
const nodes = total === 0 ? [] : this.assocStore.loadActiveNodesPage(Math.max(1, total), 0);
|
|
1802
|
+
const edges = total === 0 ? [] : this.assocStore.loadActiveEdgesPage(1_000_000, 0);
|
|
1803
|
+
const synonyms = total === 0 ? [] : this.assocStore.loadActiveSynonymsPage(100_000, 0);
|
|
1804
|
+
this.commitRebuiltIndex(nodes, edges, synonyms, nowMs, snapshotWithdrawalEpoch);
|
|
1805
|
+
}
|
|
1806
|
+
async rebuildIndex() {
|
|
1807
|
+
if (!this.active || this.assocStore === null)
|
|
1808
|
+
return;
|
|
1809
|
+
if (this.rebuildInFlight !== null) {
|
|
1810
|
+
this.rebuildQueued = true;
|
|
1811
|
+
await this.rebuildInFlight;
|
|
1812
|
+
return;
|
|
1813
|
+
}
|
|
1814
|
+
const run = async () => {
|
|
1815
|
+
do {
|
|
1816
|
+
this.rebuildQueued = false;
|
|
1817
|
+
if (!this.active || this.assocStore === null)
|
|
1818
|
+
return;
|
|
1819
|
+
const snapshotWithdrawalEpoch = this.writeQueue?.withdrawalEpoch ?? 0;
|
|
1820
|
+
const snap = await loadGraphSnapshotChunked(this.assocStore, {
|
|
1821
|
+
chunkSize: 2_000,
|
|
1822
|
+
isCancelled: () => !this.active,
|
|
1823
|
+
});
|
|
1824
|
+
if (snap === null || !this.active)
|
|
1825
|
+
return;
|
|
1826
|
+
this.commitRebuiltIndex(snap.nodes, snap.edges, snap.synonyms, this.nowClock(), snapshotWithdrawalEpoch);
|
|
1827
|
+
} while (this.rebuildQueued && this.active);
|
|
1828
|
+
};
|
|
1829
|
+
this.rebuildInFlight = run().finally(() => {
|
|
1830
|
+
this.rebuildInFlight = null;
|
|
1831
|
+
});
|
|
1832
|
+
await this.rebuildInFlight;
|
|
1833
|
+
}
|
|
1834
|
+
commitRebuiltIndex(nodes, edges, synonyms, nowMs, snapshotWithdrawalEpoch) {
|
|
1835
|
+
const activeIds = new Set();
|
|
1836
|
+
const indexNodes = [];
|
|
1837
|
+
for (const n of nodes) {
|
|
1838
|
+
if (n.status !== 'active')
|
|
1839
|
+
continue;
|
|
1840
|
+
if (this.writeQueue?.isNodeTombstoned(n.id))
|
|
1841
|
+
continue;
|
|
1842
|
+
if (this.writeQueue?.isSourceTombstoned(n.ownerScopeKey, n.sourcePlugin, n.sourceRef))
|
|
1843
|
+
continue;
|
|
1844
|
+
activeIds.add(n.id);
|
|
1845
|
+
indexNodes.push({
|
|
1846
|
+
id: n.id,
|
|
1847
|
+
kind: n.kind,
|
|
1848
|
+
sourcePlugin: n.sourcePlugin,
|
|
1849
|
+
sourceRef: n.sourceRef,
|
|
1850
|
+
ownerScopeKey: n.ownerScopeKey,
|
|
1851
|
+
ownerMode: n.ownerMode,
|
|
1852
|
+
scopeMode: n.scopeMode,
|
|
1853
|
+
workspace: n.workspace,
|
|
1854
|
+
agentPreset: n.agentPreset,
|
|
1855
|
+
trust: n.trust,
|
|
1856
|
+
sensitivity: n.sensitivity,
|
|
1857
|
+
title: n.title,
|
|
1858
|
+
entities: n.entities,
|
|
1859
|
+
tokens: n.tokens,
|
|
1860
|
+
expiresAt: n.expiresAt,
|
|
1861
|
+
updatedAt: n.updatedAt,
|
|
1862
|
+
});
|
|
1863
|
+
}
|
|
1864
|
+
const indexEdges = [];
|
|
1865
|
+
for (const e of edges) {
|
|
1866
|
+
if (!activeIds.has(e.aId) || !activeIds.has(e.bId))
|
|
1867
|
+
continue;
|
|
1868
|
+
indexEdges.push({
|
|
1869
|
+
edgeId: e.edgeId,
|
|
1870
|
+
aId: e.aId,
|
|
1871
|
+
bId: e.bId,
|
|
1872
|
+
edgeType: e.edgeType,
|
|
1873
|
+
weight: e.weight,
|
|
1874
|
+
trust: e.trust,
|
|
1875
|
+
reason: e.reason,
|
|
1876
|
+
});
|
|
1877
|
+
}
|
|
1878
|
+
this.indexBuildEpoch += 1;
|
|
1879
|
+
const nextIndex = buildMemoryIndex({
|
|
1880
|
+
nodes: indexNodes,
|
|
1881
|
+
edges: indexEdges,
|
|
1882
|
+
synonyms: synonyms
|
|
1883
|
+
.filter((s) => s.sourceNodeId === null || activeIds.has(s.sourceNodeId))
|
|
1884
|
+
.map((s) => ({
|
|
1885
|
+
surface: s.surface,
|
|
1886
|
+
canonicalEntity: s.canonicalEntity,
|
|
1887
|
+
ownerScopeKey: s.ownerScopeKey,
|
|
1888
|
+
trust: s.trust,
|
|
1889
|
+
})),
|
|
1890
|
+
}, {
|
|
1891
|
+
buildEpoch: this.indexBuildEpoch,
|
|
1892
|
+
builtAt: nowMs,
|
|
1893
|
+
maxFanoutPerNode: this.assocConfig.maxFanoutPerNode,
|
|
1894
|
+
});
|
|
1895
|
+
this.activeIndex = nextIndex;
|
|
1896
|
+
this.ready = true;
|
|
1897
|
+
this.writeQueue?.clearTombstonesForRebuiltGraph(activeIds, snapshotWithdrawalEpoch);
|
|
1898
|
+
}
|
|
1899
|
+
trackBackgroundTask(promise) {
|
|
1900
|
+
this.pendingTasks.add(promise);
|
|
1901
|
+
void promise.finally(() => {
|
|
1902
|
+
this.pendingTasks.delete(promise);
|
|
1903
|
+
});
|
|
1904
|
+
}
|
|
1905
|
+
hasRunningAgentForScope(ownerScopeKey) {
|
|
1906
|
+
for (const agent of this.activeAgents) {
|
|
1907
|
+
if (agent.status !== 'running')
|
|
1908
|
+
continue;
|
|
1909
|
+
const scope = this.resolveAgentScope(agent);
|
|
1910
|
+
if (scope?.ownerScopeKey === ownerScopeKey) {
|
|
1911
|
+
return true;
|
|
1912
|
+
}
|
|
1913
|
+
}
|
|
1914
|
+
return false;
|
|
1915
|
+
}
|
|
1916
|
+
scheduleClusteringForScope(scope) {
|
|
1917
|
+
if (!this.active || !this.assocConfig.enabled || this.holdoutSeedKey === null)
|
|
1918
|
+
return;
|
|
1919
|
+
this.trackBackgroundTask(this.runClusteringNow(scope).then(() => { }, (error) => {
|
|
1920
|
+
this.ctx.logger.warn?.('assistant-association clustering error', {
|
|
1921
|
+
error: String(error),
|
|
1922
|
+
});
|
|
1923
|
+
}));
|
|
1924
|
+
}
|
|
1925
|
+
async runPeriodicS3Maintenance() {
|
|
1926
|
+
if (!this.active || !this.assocConfig.enabled)
|
|
1927
|
+
return;
|
|
1928
|
+
if (!this.writeQueue?.hasPendingWithdrawals) {
|
|
1929
|
+
await this.sweepExpiredNodesNow();
|
|
1930
|
+
}
|
|
1931
|
+
if (!this.active || !this.assocConfig.dreaming.enabled || this.sourceManager === null)
|
|
1932
|
+
return;
|
|
1933
|
+
for (const scope of this.sourceManager.listScopes()) {
|
|
1934
|
+
if (!this.active)
|
|
1935
|
+
return;
|
|
1936
|
+
await this.runDreamingNow(scope);
|
|
1937
|
+
}
|
|
1938
|
+
}
|
|
1939
|
+
async runPeriodicS4WebLearning() {
|
|
1940
|
+
if (!this.active ||
|
|
1941
|
+
!this.assocConfig.enabled ||
|
|
1942
|
+
!this.assocConfig.webLearning.enabled ||
|
|
1943
|
+
this.sourceManager === null ||
|
|
1944
|
+
this.writeQueue?.hasPendingWithdrawals) {
|
|
1945
|
+
return;
|
|
1946
|
+
}
|
|
1947
|
+
for (const scope of this.sourceManager.listScopes()) {
|
|
1948
|
+
if (!this.active || this.writeQueue?.hasPendingWithdrawals)
|
|
1949
|
+
return;
|
|
1950
|
+
if (this.inFlightWebLearningScopes.has(scope.ownerScopeKey))
|
|
1951
|
+
continue;
|
|
1952
|
+
try {
|
|
1953
|
+
await this.runWebLearningNow(scope);
|
|
1954
|
+
}
|
|
1955
|
+
catch (error) {
|
|
1956
|
+
if (error instanceof AssistantAssociationError && error.code === 'disposed') {
|
|
1957
|
+
return;
|
|
1958
|
+
}
|
|
1959
|
+
throw error;
|
|
1960
|
+
}
|
|
1961
|
+
}
|
|
1962
|
+
}
|
|
1963
|
+
findIntakeSignalCandidate(ownerScope, items, activeGoalId, nowMs) {
|
|
1964
|
+
if (this.assocStore === null)
|
|
1965
|
+
return null;
|
|
1966
|
+
const minScore = this.assocConfig.intakeSignal.minScore;
|
|
1967
|
+
const isEligibleStored = (node) => node !== null &&
|
|
1968
|
+
node.status === 'active' &&
|
|
1969
|
+
node.sensitivity === 'private' &&
|
|
1970
|
+
node.ownerScopeKey === ownerScope.ownerScopeKey &&
|
|
1971
|
+
(node.expiresAt === null || node.expiresAt > nowMs);
|
|
1972
|
+
for (const item of items) {
|
|
1973
|
+
if (item.kind !== 'goal' || item.score < minScore)
|
|
1974
|
+
continue;
|
|
1975
|
+
const goalNode = this.assocStore.getNodeById(item.id);
|
|
1976
|
+
if (!isEligibleStored(goalNode) || goalNode.kind !== 'goal')
|
|
1977
|
+
continue;
|
|
1978
|
+
let targetNode = null;
|
|
1979
|
+
if (item.provenanceEdges !== undefined) {
|
|
1980
|
+
for (const edge of item.provenanceEdges) {
|
|
1981
|
+
const otherId = edge.aId === goalNode.id ? edge.bId : edge.aId;
|
|
1982
|
+
if (otherId === goalNode.id)
|
|
1983
|
+
continue;
|
|
1984
|
+
const cand = this.assocStore.getNodeById(otherId);
|
|
1985
|
+
if (isEligibleStored(cand)) {
|
|
1986
|
+
targetNode = cand;
|
|
1987
|
+
break;
|
|
1988
|
+
}
|
|
1989
|
+
}
|
|
1990
|
+
}
|
|
1991
|
+
if (targetNode === null) {
|
|
1992
|
+
for (const other of items) {
|
|
1993
|
+
if (other.id === goalNode.id || other.kind === 'goal')
|
|
1994
|
+
continue;
|
|
1995
|
+
const cand = this.assocStore.getNodeById(other.id);
|
|
1996
|
+
if (isEligibleStored(cand)) {
|
|
1997
|
+
targetNode = cand;
|
|
1998
|
+
break;
|
|
1999
|
+
}
|
|
2000
|
+
}
|
|
2001
|
+
}
|
|
2002
|
+
if (targetNode === null) {
|
|
2003
|
+
for (const other of items) {
|
|
2004
|
+
if (other.id === goalNode.id)
|
|
2005
|
+
continue;
|
|
2006
|
+
const cand = this.assocStore.getNodeById(other.id);
|
|
2007
|
+
if (isEligibleStored(cand)) {
|
|
2008
|
+
targetNode = cand;
|
|
2009
|
+
break;
|
|
2010
|
+
}
|
|
2011
|
+
}
|
|
2012
|
+
}
|
|
2013
|
+
if (targetNode !== null) {
|
|
2014
|
+
return {
|
|
2015
|
+
goalNode,
|
|
2016
|
+
targetNode,
|
|
2017
|
+
score: item.score,
|
|
2018
|
+
reason: item.reason,
|
|
2019
|
+
};
|
|
2020
|
+
}
|
|
2021
|
+
}
|
|
2022
|
+
if (activeGoalId !== undefined) {
|
|
2023
|
+
const goalNode = this.assocStore.getNodeById(`a:g-${activeGoalId}`);
|
|
2024
|
+
if (isEligibleStored(goalNode) && goalNode.kind === 'goal') {
|
|
2025
|
+
for (const other of items) {
|
|
2026
|
+
if (other.id === goalNode.id || other.score < minScore)
|
|
2027
|
+
continue;
|
|
2028
|
+
const targetNode = this.assocStore.getNodeById(other.id);
|
|
2029
|
+
if (isEligibleStored(targetNode)) {
|
|
2030
|
+
return {
|
|
2031
|
+
goalNode,
|
|
2032
|
+
targetNode,
|
|
2033
|
+
score: other.score,
|
|
2034
|
+
reason: other.reason,
|
|
2035
|
+
};
|
|
2036
|
+
}
|
|
2037
|
+
}
|
|
2038
|
+
}
|
|
2039
|
+
}
|
|
2040
|
+
return null;
|
|
2041
|
+
}
|
|
2042
|
+
scheduleIntakeSignal(ownerScope, candidate, nowMs) {
|
|
2043
|
+
const task = new Promise((resolve) => {
|
|
2044
|
+
queueMicrotask(() => {
|
|
2045
|
+
try {
|
|
2046
|
+
if (this.active && this.assocConfig.enabled && this.assocStore !== null) {
|
|
2047
|
+
this.emitIntakeSignalNow({
|
|
2048
|
+
scope: ownerScope,
|
|
2049
|
+
goalNode: candidate.goalNode,
|
|
2050
|
+
targetNode: candidate.targetNode,
|
|
2051
|
+
score: candidate.score,
|
|
2052
|
+
reason: candidate.reason,
|
|
2053
|
+
inHoldout: false,
|
|
2054
|
+
nowMs,
|
|
2055
|
+
});
|
|
2056
|
+
}
|
|
2057
|
+
}
|
|
2058
|
+
catch (error) {
|
|
2059
|
+
this.ctx.logger.warn?.('assistant-association intake signal error', {
|
|
2060
|
+
error: String(error),
|
|
2061
|
+
});
|
|
2062
|
+
}
|
|
2063
|
+
finally {
|
|
2064
|
+
resolve();
|
|
2065
|
+
}
|
|
2066
|
+
});
|
|
2067
|
+
});
|
|
2068
|
+
this.trackBackgroundTask(task);
|
|
2069
|
+
}
|
|
2070
|
+
}
|
|
2071
|
+
//# sourceMappingURL=service.js.map
|