@dsh-ray/assistant-association 0.0.1-seed.0 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (120) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +132 -1
  3. package/cordis.patch.yml +26 -0
  4. package/lib/aho-corasick.d.ts +41 -0
  5. package/lib/aho-corasick.d.ts.map +1 -0
  6. package/lib/aho-corasick.js +352 -0
  7. package/lib/aho-corasick.js.map +1 -0
  8. package/lib/bm25.d.ts +17 -0
  9. package/lib/bm25.d.ts.map +1 -0
  10. package/lib/bm25.js +73 -0
  11. package/lib/bm25.js.map +1 -0
  12. package/lib/clustering.d.ts +161 -0
  13. package/lib/clustering.d.ts.map +1 -0
  14. package/lib/clustering.js +1043 -0
  15. package/lib/clustering.js.map +1 -0
  16. package/lib/config.d.ts +67 -0
  17. package/lib/config.d.ts.map +1 -0
  18. package/lib/config.js +834 -0
  19. package/lib/config.js.map +1 -0
  20. package/lib/cues.d.ts +134 -0
  21. package/lib/cues.d.ts.map +1 -0
  22. package/lib/cues.js +793 -0
  23. package/lib/cues.js.map +1 -0
  24. package/lib/dreaming.d.ts +211 -0
  25. package/lib/dreaming.d.ts.map +1 -0
  26. package/lib/dreaming.js +1418 -0
  27. package/lib/dreaming.js.map +1 -0
  28. package/lib/entities.d.ts +18 -0
  29. package/lib/entities.d.ts.map +1 -0
  30. package/lib/entities.js +111 -0
  31. package/lib/entities.js.map +1 -0
  32. package/lib/eval-pool.d.ts +111 -0
  33. package/lib/eval-pool.d.ts.map +1 -0
  34. package/lib/eval-pool.js +392 -0
  35. package/lib/eval-pool.js.map +1 -0
  36. package/lib/hebbian.d.ts +54 -0
  37. package/lib/hebbian.d.ts.map +1 -0
  38. package/lib/hebbian.js +226 -0
  39. package/lib/hebbian.js.map +1 -0
  40. package/lib/holdout.d.ts +18 -0
  41. package/lib/holdout.d.ts.map +1 -0
  42. package/lib/holdout.js +97 -0
  43. package/lib/holdout.js.map +1 -0
  44. package/lib/hot-path.d.ts +8 -0
  45. package/lib/hot-path.d.ts.map +1 -0
  46. package/lib/hot-path.js +503 -0
  47. package/lib/hot-path.js.map +1 -0
  48. package/lib/hysteresis.d.ts +39 -0
  49. package/lib/hysteresis.d.ts.map +1 -0
  50. package/lib/hysteresis.js +297 -0
  51. package/lib/hysteresis.js.map +1 -0
  52. package/lib/index-memory.d.ts +112 -0
  53. package/lib/index-memory.d.ts.map +1 -0
  54. package/lib/index-memory.js +391 -0
  55. package/lib/index-memory.js.map +1 -0
  56. package/lib/index.d.ts +37 -0
  57. package/lib/index.d.ts.map +1 -0
  58. package/lib/index.js +37 -0
  59. package/lib/index.js.map +1 -0
  60. package/lib/intake-signal.d.ts +158 -0
  61. package/lib/intake-signal.d.ts.map +1 -0
  62. package/lib/intake-signal.js +366 -0
  63. package/lib/intake-signal.js.map +1 -0
  64. package/lib/param-tuning.d.ts +302 -0
  65. package/lib/param-tuning.d.ts.map +1 -0
  66. package/lib/param-tuning.js +1743 -0
  67. package/lib/param-tuning.js.map +1 -0
  68. package/lib/service.d.ts +164 -0
  69. package/lib/service.d.ts.map +1 -0
  70. package/lib/service.js +2071 -0
  71. package/lib/service.js.map +1 -0
  72. package/lib/sources.d.ts +42 -0
  73. package/lib/sources.d.ts.map +1 -0
  74. package/lib/sources.js +2024 -0
  75. package/lib/sources.js.map +1 -0
  76. package/lib/sqlite.d.ts +88 -0
  77. package/lib/sqlite.d.ts.map +1 -0
  78. package/lib/sqlite.js +1815 -0
  79. package/lib/sqlite.js.map +1 -0
  80. package/lib/tokenize.d.ts +4 -0
  81. package/lib/tokenize.d.ts.map +1 -0
  82. package/lib/tokenize.js +35 -0
  83. package/lib/tokenize.js.map +1 -0
  84. package/lib/tools.d.ts +27 -0
  85. package/lib/tools.d.ts.map +1 -0
  86. package/lib/tools.js +126 -0
  87. package/lib/tools.js.map +1 -0
  88. package/lib/types.d.ts +551 -0
  89. package/lib/types.d.ts.map +1 -0
  90. package/lib/types.js +163 -0
  91. package/lib/types.js.map +1 -0
  92. package/lib/version.d.ts +2 -0
  93. package/lib/version.d.ts.map +1 -0
  94. package/lib/version.js +2 -0
  95. package/lib/version.js.map +1 -0
  96. package/lib/web-fetch.d.ts +95 -0
  97. package/lib/web-fetch.d.ts.map +1 -0
  98. package/lib/web-fetch.js +833 -0
  99. package/lib/web-fetch.js.map +1 -0
  100. package/lib/web-learning-interests.d.ts +42 -0
  101. package/lib/web-learning-interests.d.ts.map +1 -0
  102. package/lib/web-learning-interests.js +4344 -0
  103. package/lib/web-learning-interests.js.map +1 -0
  104. package/lib/web-learning-runner.d.ts +43 -0
  105. package/lib/web-learning-runner.d.ts.map +1 -0
  106. package/lib/web-learning-runner.js +322 -0
  107. package/lib/web-learning-runner.js.map +1 -0
  108. package/lib/web-learning-worker.d.ts +75 -0
  109. package/lib/web-learning-worker.d.ts.map +1 -0
  110. package/lib/web-learning-worker.js +367 -0
  111. package/lib/web-learning-worker.js.map +1 -0
  112. package/lib/web-learning.d.ts +161 -0
  113. package/lib/web-learning.d.ts.map +1 -0
  114. package/lib/web-learning.js +912 -0
  115. package/lib/web-learning.js.map +1 -0
  116. package/lib/write-queue.d.ts +42 -0
  117. package/lib/write-queue.d.ts.map +1 -0
  118. package/lib/write-queue.js +439 -0
  119. package/lib/write-queue.js.map +1 -0
  120. package/package.json +149 -4
@@ -0,0 +1,912 @@
1
+ import { createHash } from 'node:crypto';
2
+ import { buildSharedEntityEdges, extractEntities } from './entities.js';
3
+ import { ensureWebLearningSchema } from './sqlite.js';
4
+ import { tokenizeAssociationText } from './tokenize.js';
5
+ import { normalizeSourceVersion, WEB_LEARNING_SOURCE_PLUGIN, } from './types.js';
6
+ import { validateWhitelistedWebUrl } from './web-fetch.js';
7
+ import { extractWebLearningInterests, } from './web-learning-interests.js';
8
+ import { createInProcessWebLearningRunner, createSubprocessWebLearningRunner, } from './web-learning-runner.js';
9
+ const MAX_WEB_TITLE_CHARS = 160;
10
+ const MAX_WEB_BODY_CHARS = 8_192;
11
+ const MAX_SHARED_ENTITY_EDGES_PER_WEB_NODE = 16;
12
+ function sha256Hex(value) {
13
+ return createHash('sha256').update(value, 'utf8').digest('hex');
14
+ }
15
+ function asDatabase(storeOrDb) {
16
+ return 'database' in storeOrDb ? storeOrDb.database : storeOrDb;
17
+ }
18
+ function hasTable(db, tableName) {
19
+ const row = db
20
+ .prepare("SELECT 1 AS ok FROM sqlite_master WHERE type = 'table' AND name = ?")
21
+ .get(tableName);
22
+ return row !== undefined;
23
+ }
24
+ function compactText(raw, maxChars) {
25
+ const collapsed = raw.normalize('NFKC').replace(/\s+/gu, ' ').trim();
26
+ if (collapsed.length <= maxChars)
27
+ return collapsed;
28
+ const chars = [...collapsed];
29
+ if (chars.length <= maxChars)
30
+ return collapsed;
31
+ return `${chars.slice(0, Math.max(0, maxChars - 1)).join('')}…`;
32
+ }
33
+ export function formatUtcDayKey(nowMs) {
34
+ return new Date(nowMs).toISOString().slice(0, 10);
35
+ }
36
+ export function computeWebNodeId(ownerScopeKey, canonicalUrl) {
37
+ const scope8 = ownerScopeKey.slice(0, 8);
38
+ const digest = sha256Hex(`${ownerScopeKey}\0${canonicalUrl}`).slice(0, 20);
39
+ return `a:web-${scope8}-${digest}`;
40
+ }
41
+ export function computeWebSourceRef(canonicalUrl) {
42
+ return canonicalUrl.length <= 512 ? canonicalUrl : `web:${sha256Hex(canonicalUrl)}`;
43
+ }
44
+ export function canonicalizeWebSourceUrl(rawUrl) {
45
+ const trimmed = rawUrl.trim();
46
+ try {
47
+ const parsed = new URL(trimmed);
48
+ parsed.hash = '';
49
+ return parsed.toString();
50
+ }
51
+ catch {
52
+ return trimmed;
53
+ }
54
+ }
55
+ export function buildWebLearningPolicyRequest(scope) {
56
+ return {
57
+ subject: {
58
+ kind: 'background',
59
+ id: 'assistant-association:web-learning',
60
+ workspace: scope.workspace,
61
+ principal: scope.principalId,
62
+ },
63
+ action: 'web.learn',
64
+ resource: {
65
+ kind: 'network',
66
+ id: 'assistant-association:web-learning',
67
+ },
68
+ context: {
69
+ initiator: 'background',
70
+ },
71
+ };
72
+ }
73
+ function inferLastScopeActivityAt(db, ownerScopeKey) {
74
+ let latest = null;
75
+ if (hasTable(db, 'assoc_step_metrics')) {
76
+ const stepRow = db
77
+ .prepare('SELECT MAX(occurred_at) AS ts FROM assoc_step_metrics WHERE owner_scope_key = ?')
78
+ .get(ownerScopeKey);
79
+ if (typeof stepRow?.ts === 'number' && Number.isFinite(stepRow.ts)) {
80
+ latest = stepRow.ts;
81
+ }
82
+ }
83
+ if (hasTable(db, 'assoc_nodes')) {
84
+ const nodeRow = db
85
+ .prepare(`
86
+ SELECT MAX(updated_at) AS ts
87
+ FROM assoc_nodes
88
+ WHERE owner_scope_key = ?
89
+ AND status = 'active'
90
+ AND kind NOT IN ('dream', 'abstraction', 'web')
91
+ `)
92
+ .get(ownerScopeKey);
93
+ if (typeof nodeRow?.ts === 'number' && Number.isFinite(nodeRow.ts)) {
94
+ latest = latest === null ? nodeRow.ts : Math.max(latest, nodeRow.ts);
95
+ }
96
+ }
97
+ return latest;
98
+ }
99
+ export function getWebLearningBudgetUsage(storeOrDb, ownerScopeKey, nowMs = Date.now()) {
100
+ const db = asDatabase(storeOrDb);
101
+ const utcDay = formatUtcDayKey(nowMs);
102
+ if (!hasTable(db, 'assoc_web_learning_budget_usage')) {
103
+ return {
104
+ ownerScopeKey,
105
+ utcDay,
106
+ requestsUsed: 0,
107
+ pagesFetched: 0,
108
+ bytesFetched: 0,
109
+ updatedAt: 0,
110
+ };
111
+ }
112
+ const row = db
113
+ .prepare(`
114
+ SELECT owner_scope_key, utc_day, requests_used, pages_fetched, bytes_fetched, updated_at
115
+ FROM assoc_web_learning_budget_usage
116
+ WHERE owner_scope_key = ? AND utc_day = ?
117
+ `)
118
+ .get(ownerScopeKey, utcDay);
119
+ if (row === undefined) {
120
+ return {
121
+ ownerScopeKey,
122
+ utcDay,
123
+ requestsUsed: 0,
124
+ pagesFetched: 0,
125
+ bytesFetched: 0,
126
+ updatedAt: 0,
127
+ };
128
+ }
129
+ return {
130
+ ownerScopeKey: row.owner_scope_key,
131
+ utcDay: row.utc_day,
132
+ requestsUsed: row.requests_used,
133
+ pagesFetched: row.pages_fetched,
134
+ bytesFetched: row.bytes_fetched,
135
+ updatedAt: row.updated_at,
136
+ };
137
+ }
138
+ export function evaluateWebLearningGate(input, mode = 'dry-check', idempotencyKey) {
139
+ const db = input.db ?? input.store?.database;
140
+ const nowMs = input.nowMs ?? Date.now();
141
+ const utcDay = formatUtcDayKey(nowMs);
142
+ const dailyUsage = db !== undefined
143
+ ? getWebLearningBudgetUsage(db, input.scope.ownerScopeKey, nowMs)
144
+ : {
145
+ ownerScopeKey: input.scope.ownerScopeKey,
146
+ utcDay,
147
+ requestsUsed: 0,
148
+ pagesFetched: 0,
149
+ bytesFetched: 0,
150
+ updatedAt: 0,
151
+ };
152
+ const remainingDailyRequests = Math.max(0, input.config.maxRequestsPerDay - dailyUsage.requestsUsed);
153
+ const remainingDailyBytes = Math.max(0, input.config.maxBytesPerDay - dailyUsage.bytesFetched);
154
+ const deny = (reason, policyReasonCode) => ({
155
+ allowed: false,
156
+ reason,
157
+ ...(policyReasonCode !== undefined ? { policyReasonCode } : {}),
158
+ utcDay,
159
+ dailyUsage,
160
+ remainingDailyRequests,
161
+ remainingDailyBytes,
162
+ });
163
+ // 1. Enabled gate
164
+ if (!(input.rootEnabled ?? true) || !input.config.enabled) {
165
+ return deny('disabled');
166
+ }
167
+ // 2. Non-empty domain whitelist (fail-closed)
168
+ if (input.config.allowedDomains.length === 0) {
169
+ return deny('empty-whitelist');
170
+ }
171
+ // 3. Emergency stop
172
+ if (input.policy?.getEmergencyStop?.()?.enabled === true) {
173
+ return deny('emergency-stop');
174
+ }
175
+ // 4. Interval gate
176
+ if (db !== undefined &&
177
+ input.config.intervalMs > 0 &&
178
+ hasTable(db, 'assoc_web_learning_runs')) {
179
+ const row = db
180
+ .prepare(`
181
+ SELECT MAX(finished_at) AS last_finished_at
182
+ FROM assoc_web_learning_runs
183
+ WHERE owner_scope_key = ? AND status IN ('completed', 'budget-exhausted')
184
+ `)
185
+ .get(input.scope.ownerScopeKey);
186
+ if (typeof row?.last_finished_at === 'number' &&
187
+ Number.isFinite(row.last_finished_at) &&
188
+ nowMs - row.last_finished_at < input.config.intervalMs) {
189
+ return deny('interval-not-elapsed');
190
+ }
191
+ }
192
+ // 5. Idle gate
193
+ if (!input.ignoreIdle && input.config.idleMinMs > 0) {
194
+ if (input.hasRunningAgent === true) {
195
+ return deny('agent-active');
196
+ }
197
+ const lastActivityAt = input.lastActivityAt !== undefined
198
+ ? input.lastActivityAt
199
+ : db !== undefined
200
+ ? inferLastScopeActivityAt(db, input.scope.ownerScopeKey)
201
+ : null;
202
+ if (lastActivityAt === null ||
203
+ !Number.isFinite(lastActivityAt) ||
204
+ nowMs - lastActivityAt < input.config.idleMinMs) {
205
+ return deny('not-idle');
206
+ }
207
+ }
208
+ // 6. Persisted daily budget gate
209
+ if (dailyUsage.requestsUsed >= input.config.maxRequestsPerDay ||
210
+ dailyUsage.bytesFetched >= input.config.maxBytesPerDay) {
211
+ return deny('daily-budget-exhausted');
212
+ }
213
+ // 7. Delivery owner route check
214
+ if (input.scope.mode === 'delivery' && input.delivery !== undefined) {
215
+ const authorityId = input.scope.authorityId;
216
+ if (typeof input.delivery.validateOwnerRoute === 'function') {
217
+ if (typeof authorityId !== 'string' || authorityId.length === 0) {
218
+ return deny('route-invalid');
219
+ }
220
+ try {
221
+ input.delivery.validateOwnerRoute({
222
+ authorityId,
223
+ principalId: input.scope.principalId,
224
+ workspace: input.scope.workspace,
225
+ agentPreset: input.scope.agentPreset,
226
+ });
227
+ }
228
+ catch {
229
+ return deny('route-invalid');
230
+ }
231
+ }
232
+ if (typeof input.delivery.inspectOwnerRouteState === 'function') {
233
+ if (typeof authorityId !== 'string' || authorityId.length === 0) {
234
+ return deny('route-invalid');
235
+ }
236
+ try {
237
+ const routeState = input.delivery.inspectOwnerRouteState({
238
+ authorityId,
239
+ principalId: input.scope.principalId,
240
+ workspace: input.scope.workspace,
241
+ agentPreset: input.scope.agentPreset,
242
+ });
243
+ const status = typeof routeState === 'string' ? routeState : routeState?.status;
244
+ if (status !== 'active') {
245
+ return deny('route-inactive');
246
+ }
247
+ }
248
+ catch {
249
+ return deny('route-invalid');
250
+ }
251
+ }
252
+ }
253
+ // 8. Policy availability, Policy budget check, and Policy authorization (last!)
254
+ const requirePolicy = input.requirePolicy ?? true;
255
+ if (requirePolicy && input.policy === undefined) {
256
+ return deny('policy-unavailable');
257
+ }
258
+ if (input.config.budgetId !== undefined) {
259
+ if (typeof input.policy?.getBudgetConfig !== 'function') {
260
+ return deny('budget-unavailable');
261
+ }
262
+ const budget = input.policy.getBudgetConfig(input.config.budgetId);
263
+ const requiredAmount = input.config.budgetAmount ?? 1;
264
+ if (budget === undefined || !Number.isFinite(budget.limit) || budget.limit <= 0) {
265
+ return deny('budget-unavailable');
266
+ }
267
+ if (budget.limit < requiredAmount) {
268
+ return deny('budget-exhausted');
269
+ }
270
+ }
271
+ if (input.policy !== undefined) {
272
+ const request = buildWebLearningPolicyRequest(input.scope);
273
+ let decision;
274
+ if (mode === 'execute') {
275
+ if (typeof input.policy.authorize === 'function') {
276
+ const resolvedKey = typeof idempotencyKey === 'function' ? idempotencyKey() : idempotencyKey;
277
+ const nonEmptyKey = resolvedKey !== undefined && resolvedKey.trim().length > 0
278
+ ? resolvedKey
279
+ : `web-learn:${input.scope.ownerScopeKey.slice(0, 12)}:${nowMs}`;
280
+ decision = input.policy.authorize(request, { idempotencyKey: nonEmptyKey });
281
+ }
282
+ else if (typeof input.policy.evaluate === 'function') {
283
+ decision = input.policy.evaluate(request);
284
+ }
285
+ }
286
+ else {
287
+ if (typeof input.policy.evaluate === 'function') {
288
+ decision = input.policy.evaluate(request);
289
+ }
290
+ else if (typeof input.policy.authorize === 'function') {
291
+ // Defer side-effectful authorize() until execute mode once targets are confirmed.
292
+ decision = { effect: 'allow' };
293
+ }
294
+ }
295
+ if (decision === undefined) {
296
+ if (requirePolicy) {
297
+ return deny('policy-unavailable');
298
+ }
299
+ }
300
+ else if (decision.effect !== 'allow') {
301
+ if (decision.reasonCode === 'budget-exhausted') {
302
+ return deny('budget-exhausted', decision.reasonCode);
303
+ }
304
+ return deny('policy-denied', decision.reasonCode);
305
+ }
306
+ }
307
+ return {
308
+ allowed: true,
309
+ reason: 'ok',
310
+ utcDay,
311
+ dailyUsage,
312
+ remainingDailyRequests,
313
+ remainingDailyBytes,
314
+ };
315
+ }
316
+ function recordRunRow(db, row) {
317
+ db.prepare(`
318
+ INSERT INTO assoc_web_learning_runs (
319
+ run_id, owner_scope_key, started_at, finished_at, status, reason,
320
+ topics_considered, requests_used, pages_fetched, bytes_fetched,
321
+ nodes_written, details_json
322
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
323
+ ON CONFLICT(run_id) DO UPDATE SET
324
+ finished_at = excluded.finished_at,
325
+ status = excluded.status,
326
+ reason = excluded.reason,
327
+ topics_considered = excluded.topics_considered,
328
+ requests_used = excluded.requests_used,
329
+ pages_fetched = excluded.pages_fetched,
330
+ bytes_fetched = excluded.bytes_fetched,
331
+ nodes_written = excluded.nodes_written,
332
+ details_json = excluded.details_json
333
+ `).run(row.runId, row.ownerScopeKey, row.startedAt, row.finishedAt, row.status, row.reason, row.topicsConsidered, row.requestsUsed, row.pagesFetched, row.bytesFetched, row.nodesWritten, row.details === undefined ? null : JSON.stringify(row.details));
334
+ }
335
+ function extractDomainSafe(rawUrl) {
336
+ try {
337
+ return new URL(rawUrl).hostname.toLowerCase();
338
+ }
339
+ catch {
340
+ return '';
341
+ }
342
+ }
343
+ function buildFetchAttemptRows(runId, ownerScopeKey, attempts, writtenNodeByUrl, overrideTimestamp) {
344
+ return attempts.map((attempt, index) => {
345
+ const canonical = canonicalizeWebSourceUrl(attempt.finalUrl ?? attempt.url);
346
+ const written = writtenNodeByUrl.get(canonical);
347
+ const fetchedAt = overrideTimestamp ?? attempt.fetchedAt;
348
+ return {
349
+ fetchId: `fetch-${sha256Hex(`${runId}\0${index}\0${attempt.url}`).slice(0, 24)}`,
350
+ ownerScopeKey,
351
+ runId,
352
+ canonicalUrl: canonical,
353
+ domain: extractDomainSafe(canonical),
354
+ interestKey: attempt.interestKey,
355
+ status: attempt.ok ? 'ok' : (attempt.rejectionCode ?? 'error'),
356
+ bytesFetched: attempt.bytesFetched,
357
+ nodeId: written?.nodeId ?? null,
358
+ fetchedAt,
359
+ expiresAt: written?.expiresAt ?? null,
360
+ };
361
+ });
362
+ }
363
+ function mapWorkerStatusToRunStatus(workerStatus) {
364
+ if (workerStatus === 'completed')
365
+ return 'completed';
366
+ if (workerStatus === 'budget-exhausted')
367
+ return 'budget-exhausted';
368
+ if (workerStatus === 'rejected')
369
+ return 'skipped';
370
+ return 'failed';
371
+ }
372
+ export async function runWebLearningPass(input) {
373
+ const db = input.store.database;
374
+ ensureWebLearningSchema(db);
375
+ const nowMs = input.nowMs ?? Date.now();
376
+ let computedRunId = null;
377
+ const getRunId = () => {
378
+ if (computedRunId === null) {
379
+ const countRow = db
380
+ .prepare('SELECT COUNT(*) AS cnt FROM assoc_web_learning_runs WHERE owner_scope_key = ?')
381
+ .get(input.scope.ownerScopeKey);
382
+ const ordinal = countRow?.cnt ?? 0;
383
+ computedRunId = `web-${sha256Hex(`${input.scope.ownerScopeKey}\0${nowMs}\0${ordinal}`).slice(0, 24)}`;
384
+ }
385
+ return computedRunId;
386
+ };
387
+ const dryGate = evaluateWebLearningGate(input, 'dry-check');
388
+ if (!dryGate.allowed) {
389
+ const gateStatus = dryGate.reason === 'daily-budget-exhausted' || dryGate.reason === 'budget-exhausted'
390
+ ? 'budget-exhausted'
391
+ : 'skipped';
392
+ return {
393
+ ran: false,
394
+ runId: null,
395
+ status: gateStatus,
396
+ reason: dryGate.reason,
397
+ ...(dryGate.policyReasonCode !== undefined
398
+ ? { policyReasonCode: dryGate.policyReasonCode }
399
+ : {}),
400
+ topicsConsidered: 0,
401
+ requestsUsed: 0,
402
+ pagesFetched: 0,
403
+ bytesFetched: 0,
404
+ nodesWritten: 0,
405
+ edgesWritten: 0,
406
+ writtenNodeIds: [],
407
+ interests: [],
408
+ fetches: [],
409
+ dailyUsage: dryGate.dailyUsage,
410
+ };
411
+ }
412
+ if (input.signal?.aborted) {
413
+ return {
414
+ ran: false,
415
+ runId: null,
416
+ status: 'failed',
417
+ reason: 'aborted',
418
+ topicsConsidered: 0,
419
+ requestsUsed: 0,
420
+ pagesFetched: 0,
421
+ bytesFetched: 0,
422
+ nodesWritten: 0,
423
+ edgesWritten: 0,
424
+ writtenNodeIds: [],
425
+ interests: [],
426
+ fetches: [],
427
+ dailyUsage: dryGate.dailyUsage,
428
+ };
429
+ }
430
+ const extracted = extractWebLearningInterests(input.store, input.scope, {
431
+ config: input.config,
432
+ nowMs,
433
+ });
434
+ if (extracted.targets.length === 0) {
435
+ let suppressDuplicateNoTargetsRow = false;
436
+ if (input.config.intervalMs > 0) {
437
+ const lastRun = db
438
+ .prepare(`
439
+ SELECT status, reason, finished_at
440
+ FROM assoc_web_learning_runs
441
+ WHERE owner_scope_key = ?
442
+ ORDER BY finished_at DESC, started_at DESC, rowid DESC
443
+ LIMIT 1
444
+ `)
445
+ .get(input.scope.ownerScopeKey);
446
+ if (lastRun !== undefined &&
447
+ lastRun.status === 'skipped' &&
448
+ lastRun.reason === 'no-targets' &&
449
+ nowMs - lastRun.finished_at < input.config.intervalMs) {
450
+ suppressDuplicateNoTargetsRow = true;
451
+ }
452
+ }
453
+ let persistedRunId = null;
454
+ if (!suppressDuplicateNoTargetsRow) {
455
+ persistedRunId = getRunId();
456
+ recordRunRow(db, {
457
+ runId: persistedRunId,
458
+ ownerScopeKey: input.scope.ownerScopeKey,
459
+ startedAt: nowMs,
460
+ finishedAt: nowMs,
461
+ status: 'skipped',
462
+ reason: 'no-targets',
463
+ topicsConsidered: extracted.interests.length,
464
+ requestsUsed: 0,
465
+ pagesFetched: 0,
466
+ bytesFetched: 0,
467
+ nodesWritten: 0,
468
+ details: {
469
+ skippedCooldownCount: extracted.skippedCooldownCount,
470
+ rejectedSeedUrls: extracted.rejectedSeedUrls,
471
+ },
472
+ });
473
+ }
474
+ return {
475
+ ran: false,
476
+ runId: persistedRunId,
477
+ status: 'skipped',
478
+ reason: 'no-targets',
479
+ topicsConsidered: extracted.interests.length,
480
+ requestsUsed: 0,
481
+ pagesFetched: 0,
482
+ bytesFetched: 0,
483
+ nodesWritten: 0,
484
+ edgesWritten: 0,
485
+ writtenNodeIds: [],
486
+ interests: extracted.interests,
487
+ fetches: [],
488
+ dailyUsage: dryGate.dailyUsage,
489
+ };
490
+ }
491
+ const runId = getRunId();
492
+ const gate = evaluateWebLearningGate(input, 'execute', () => `web-learn:${runId}`);
493
+ if (!gate.allowed) {
494
+ const gateStatus = gate.reason === 'daily-budget-exhausted' || gate.reason === 'budget-exhausted'
495
+ ? 'budget-exhausted'
496
+ : 'skipped';
497
+ return {
498
+ ran: false,
499
+ runId: null,
500
+ status: gateStatus,
501
+ reason: gate.reason,
502
+ ...(gate.policyReasonCode !== undefined ? { policyReasonCode: gate.policyReasonCode } : {}),
503
+ topicsConsidered: extracted.interests.length,
504
+ requestsUsed: 0,
505
+ pagesFetched: 0,
506
+ bytesFetched: 0,
507
+ nodesWritten: 0,
508
+ edgesWritten: 0,
509
+ writtenNodeIds: [],
510
+ interests: extracted.interests,
511
+ fetches: [],
512
+ dailyUsage: gate.dailyUsage,
513
+ };
514
+ }
515
+ if (input.signal?.aborted) {
516
+ return {
517
+ ran: false,
518
+ runId,
519
+ status: 'failed',
520
+ reason: 'aborted',
521
+ topicsConsidered: extracted.interests.length,
522
+ requestsUsed: 0,
523
+ pagesFetched: 0,
524
+ bytesFetched: 0,
525
+ nodesWritten: 0,
526
+ edgesWritten: 0,
527
+ writtenNodeIds: [],
528
+ interests: extracted.interests,
529
+ fetches: [],
530
+ dailyUsage: gate.dailyUsage,
531
+ };
532
+ }
533
+ const effectiveMaxRequests = Math.min(input.config.maxRequestsPerRun, gate.remainingDailyRequests);
534
+ const effectiveMaxTotalBytes = Math.min(input.config.maxTotalBytesPerRun, gate.remainingDailyBytes);
535
+ const plan = {
536
+ runId,
537
+ allowedDomains: input.config.allowedDomains,
538
+ allowSubdomains: input.config.allowSubdomains,
539
+ allowIpv6: input.config.allowIpv6,
540
+ targets: extracted.targets,
541
+ budget: {
542
+ maxRequests: effectiveMaxRequests,
543
+ maxPages: input.config.maxPagesPerRun,
544
+ maxBytesPerRequest: input.config.maxBytesPerRequest,
545
+ maxTotalBytes: effectiveMaxTotalBytes,
546
+ maxDurationMs: input.config.maxDurationMs,
547
+ requestTimeoutMs: input.config.requestTimeoutMs,
548
+ maxRedirects: input.config.maxRedirects,
549
+ },
550
+ };
551
+ const runner = input.runner !== undefined
552
+ ? input.runner
553
+ : input.config.isolationMode === 'in-process'
554
+ ? createInProcessWebLearningRunner({
555
+ ...input.workerDeps,
556
+ ...(input.nowMs !== undefined && input.workerDeps?.now === undefined
557
+ ? { now: () => nowMs }
558
+ : {}),
559
+ })
560
+ : createSubprocessWebLearningRunner(input.subprocessOptions);
561
+ let output;
562
+ try {
563
+ output = await runner.run(plan, input.signal);
564
+ }
565
+ catch (error) {
566
+ const message = error instanceof Error ? error.message : String(error);
567
+ const reason = input.signal?.aborted ? 'aborted' : 'runner-error';
568
+ recordRunRow(db, {
569
+ runId,
570
+ ownerScopeKey: input.scope.ownerScopeKey,
571
+ startedAt: nowMs,
572
+ finishedAt: Math.max(nowMs, Date.now()),
573
+ status: 'failed',
574
+ reason,
575
+ topicsConsidered: extracted.interests.length,
576
+ requestsUsed: 0,
577
+ pagesFetched: 0,
578
+ bytesFetched: 0,
579
+ nodesWritten: 0,
580
+ details: { error: message },
581
+ });
582
+ return {
583
+ ran: false,
584
+ runId,
585
+ status: 'failed',
586
+ reason,
587
+ topicsConsidered: extracted.interests.length,
588
+ requestsUsed: 0,
589
+ pagesFetched: 0,
590
+ bytesFetched: 0,
591
+ nodesWritten: 0,
592
+ edgesWritten: 0,
593
+ writtenNodeIds: [],
594
+ interests: extracted.interests,
595
+ fetches: [],
596
+ dailyUsage: gate.dailyUsage,
597
+ };
598
+ }
599
+ if (input.signal?.aborted || output.status === 'aborted') {
600
+ const abortedFinishedAt = input.nowMs !== undefined ? nowMs : Math.max(nowMs, output.finishedAt);
601
+ input.store.runInTransaction(() => {
602
+ if (output.requestsUsed > 0 || output.bytesFetched > 0) {
603
+ db.prepare(`
604
+ INSERT INTO assoc_web_learning_budget_usage (
605
+ owner_scope_key, utc_day, requests_used, pages_fetched, bytes_fetched, updated_at
606
+ ) VALUES (?, ?, ?, ?, ?, ?)
607
+ ON CONFLICT(owner_scope_key, utc_day) DO UPDATE SET
608
+ requests_used = assoc_web_learning_budget_usage.requests_used + excluded.requests_used,
609
+ pages_fetched = assoc_web_learning_budget_usage.pages_fetched + excluded.pages_fetched,
610
+ bytes_fetched = assoc_web_learning_budget_usage.bytes_fetched + excluded.bytes_fetched,
611
+ updated_at = excluded.updated_at
612
+ `).run(input.scope.ownerScopeKey, gate.utcDay, output.requestsUsed, output.pagesFetched, output.bytesFetched, abortedFinishedAt);
613
+ }
614
+ recordRunRow(db, {
615
+ runId,
616
+ ownerScopeKey: input.scope.ownerScopeKey,
617
+ startedAt: nowMs,
618
+ finishedAt: abortedFinishedAt,
619
+ status: 'failed',
620
+ reason: 'aborted',
621
+ topicsConsidered: extracted.interests.length,
622
+ requestsUsed: output.requestsUsed,
623
+ pagesFetched: output.pagesFetched,
624
+ bytesFetched: output.bytesFetched,
625
+ nodesWritten: 0,
626
+ details: { reason: output.reason },
627
+ });
628
+ });
629
+ return {
630
+ ran: false,
631
+ runId,
632
+ status: 'failed',
633
+ reason: 'aborted',
634
+ topicsConsidered: extracted.interests.length,
635
+ requestsUsed: output.requestsUsed,
636
+ pagesFetched: output.pagesFetched,
637
+ bytesFetched: output.bytesFetched,
638
+ nodesWritten: 0,
639
+ edgesWritten: 0,
640
+ writtenNodeIds: [],
641
+ interests: extracted.interests,
642
+ fetches: [],
643
+ dailyUsage: getWebLearningBudgetUsage(db, input.scope.ownerScopeKey, nowMs),
644
+ };
645
+ }
646
+ // Build trust:'low' 'web' nodes + entity edges with bidirectional assoc_derived_from
647
+ const overrideFetchedAt = input.nowMs !== undefined && input.workerDeps?.now === undefined ? nowMs : undefined;
648
+ const scopePeers = input.store.loadEntityCandidateNodesForScope(input.scope.ownerScopeKey, 256);
649
+ const workingPeers = [...scopePeers];
650
+ const nodesToWrite = [];
651
+ const edgesToWrite = [];
652
+ const derivedRefsToWrite = [];
653
+ const seenEdgeIds = new Set();
654
+ const writtenNodeByUrl = new Map();
655
+ for (const page of output.pages) {
656
+ let canonicalUrl;
657
+ try {
658
+ canonicalUrl = validateWhitelistedWebUrl(page.finalUrl || page.sourceUrl, {
659
+ allowedDomains: input.config.allowedDomains,
660
+ allowSubdomains: input.config.allowSubdomains,
661
+ }).canonicalUrl;
662
+ }
663
+ catch {
664
+ continue;
665
+ }
666
+ const sourceRef = computeWebSourceRef(canonicalUrl);
667
+ if (input.store.isSourceWithdrawn(input.scope.ownerScopeKey, WEB_LEARNING_SOURCE_PLUGIN, sourceRef)) {
668
+ continue;
669
+ }
670
+ const fetchedAt = overrideFetchedAt ?? page.fetchedAt;
671
+ const ttlMs = input.config.nodeTtlMs > 0 ? input.config.nodeTtlMs : null;
672
+ const expiresAt = ttlMs !== null ? fetchedAt + ttlMs : null;
673
+ const nodeId = computeWebNodeId(input.scope.ownerScopeKey, canonicalUrl);
674
+ const title = compactText(page.title || canonicalUrl, MAX_WEB_TITLE_CHARS);
675
+ const body = compactText(page.text || title, MAX_WEB_BODY_CHARS);
676
+ const combined = `${title}\n${body}`;
677
+ const entities = extractEntities(combined);
678
+ const tokens = tokenizeAssociationText(combined);
679
+ const sourceVersion = normalizeSourceVersion(page.contentDigest.slice(0, 16) || fetchedAt);
680
+ const node = {
681
+ id: nodeId,
682
+ kind: 'web',
683
+ sourcePlugin: WEB_LEARNING_SOURCE_PLUGIN,
684
+ sourceRef,
685
+ sourceVersion,
686
+ ownerScopeKey: input.scope.ownerScopeKey,
687
+ ownerMode: input.scope.mode,
688
+ principalDigest: input.scope.principalDigest,
689
+ principalRecordId: input.scope.mode === 'delivery' ? input.scope.principalRecordId : null,
690
+ principalVersion: input.scope.mode === 'delivery' ? input.scope.principalVersion : null,
691
+ scopeMode: 'workspace',
692
+ workspace: input.scope.workspace,
693
+ agentPreset: input.scope.agentPreset,
694
+ trust: 'low',
695
+ sensitivity: 'private',
696
+ title,
697
+ body,
698
+ entities,
699
+ tokens,
700
+ metadata: {
701
+ sourceUrl: canonicalUrl,
702
+ fetchedAt,
703
+ extra: {
704
+ fetchedAtIso: new Date(fetchedAt).toISOString(),
705
+ contentDigest: page.contentDigest,
706
+ contentType: page.contentType,
707
+ interestKey: page.interestKey,
708
+ runId,
709
+ originNodeIds: [...page.originNodeIds],
710
+ },
711
+ },
712
+ ttlMs,
713
+ expiresAt,
714
+ status: 'active',
715
+ createdAt: fetchedAt,
716
+ updatedAt: fetchedAt,
717
+ };
718
+ nodesToWrite.push(node);
719
+ writtenNodeByUrl.set(canonicalUrl, { nodeId, expiresAt });
720
+ const edgeResult = buildSharedEntityEdges({
721
+ id: node.id,
722
+ sourceVersion: node.sourceVersion,
723
+ ownerScopeKey: node.ownerScopeKey,
724
+ trust: 'low',
725
+ entities: node.entities,
726
+ updatedAt: fetchedAt,
727
+ }, workingPeers, {
728
+ maxEdgesPerNode: MAX_SHARED_ENTITY_EDGES_PER_WEB_NODE,
729
+ nowMs: fetchedAt,
730
+ });
731
+ for (const edge of edgeResult.edges) {
732
+ if (!seenEdgeIds.has(edge.edgeId)) {
733
+ seenEdgeIds.add(edge.edgeId);
734
+ edgesToWrite.push(edge);
735
+ }
736
+ }
737
+ derivedRefsToWrite.push(...edgeResult.derivedRefs);
738
+ workingPeers.push({
739
+ id: node.id,
740
+ sourceVersion: node.sourceVersion,
741
+ ownerScopeKey: node.ownerScopeKey,
742
+ trust: 'low',
743
+ entities: node.entities,
744
+ updatedAt: fetchedAt,
745
+ });
746
+ }
747
+ if (nodesToWrite.length > 0 || edgesToWrite.length > 0 || derivedRefsToWrite.length > 0) {
748
+ const batch = {
749
+ nodes: nodesToWrite,
750
+ edges: edgesToWrite,
751
+ derivedRefs: derivedRefsToWrite,
752
+ };
753
+ if (input.enqueueUpsertNodes !== undefined) {
754
+ await input.enqueueUpsertNodes(batch);
755
+ }
756
+ else {
757
+ input.store.upsertBatch(batch);
758
+ }
759
+ }
760
+ const fetchRows = buildFetchAttemptRows(runId, input.scope.ownerScopeKey, output.attempts, writtenNodeByUrl, overrideFetchedAt);
761
+ const finishedAt = input.nowMs !== undefined ? nowMs : Math.max(nowMs, output.finishedAt);
762
+ const runStatus = mapWorkerStatusToRunStatus(output.status);
763
+ input.store.runInTransaction(() => {
764
+ if (fetchRows.length > 0) {
765
+ const insertFetchStmt = db.prepare(`
766
+ INSERT INTO assoc_web_learning_fetches (
767
+ fetch_id, owner_scope_key, run_id, canonical_url, domain,
768
+ interest_key, status, bytes_fetched, node_id, fetched_at, expires_at
769
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
770
+ ON CONFLICT(fetch_id) DO UPDATE SET
771
+ status = excluded.status,
772
+ bytes_fetched = excluded.bytes_fetched,
773
+ node_id = excluded.node_id,
774
+ fetched_at = excluded.fetched_at,
775
+ expires_at = excluded.expires_at
776
+ `);
777
+ for (const f of fetchRows) {
778
+ insertFetchStmt.run(f.fetchId, f.ownerScopeKey, f.runId, f.canonicalUrl, f.domain, f.interestKey, f.status, f.bytesFetched, f.nodeId, f.fetchedAt, f.expiresAt);
779
+ }
780
+ }
781
+ db.prepare(`
782
+ INSERT INTO assoc_web_learning_budget_usage (
783
+ owner_scope_key, utc_day, requests_used, pages_fetched, bytes_fetched, updated_at
784
+ ) VALUES (?, ?, ?, ?, ?, ?)
785
+ ON CONFLICT(owner_scope_key, utc_day) DO UPDATE SET
786
+ requests_used = assoc_web_learning_budget_usage.requests_used + excluded.requests_used,
787
+ pages_fetched = assoc_web_learning_budget_usage.pages_fetched + excluded.pages_fetched,
788
+ bytes_fetched = assoc_web_learning_budget_usage.bytes_fetched + excluded.bytes_fetched,
789
+ updated_at = excluded.updated_at
790
+ `).run(input.scope.ownerScopeKey, gate.utcDay, output.requestsUsed, output.pagesFetched, output.bytesFetched, finishedAt);
791
+ recordRunRow(db, {
792
+ runId,
793
+ ownerScopeKey: input.scope.ownerScopeKey,
794
+ startedAt: nowMs,
795
+ finishedAt,
796
+ status: runStatus,
797
+ reason: output.reason,
798
+ topicsConsidered: extracted.interests.length,
799
+ requestsUsed: output.requestsUsed,
800
+ pagesFetched: output.pagesFetched,
801
+ bytesFetched: output.bytesFetched,
802
+ nodesWritten: nodesToWrite.length,
803
+ details: {
804
+ workerStatus: output.status,
805
+ interestKeys: extracted.interests.map((item) => item.interestKey),
806
+ rejectedSeedUrls: extracted.rejectedSeedUrls,
807
+ },
808
+ });
809
+ });
810
+ const updatedUsage = getWebLearningBudgetUsage(db, input.scope.ownerScopeKey, nowMs);
811
+ return {
812
+ ran: true,
813
+ runId,
814
+ status: runStatus,
815
+ reason: output.reason,
816
+ topicsConsidered: extracted.interests.length,
817
+ requestsUsed: output.requestsUsed,
818
+ pagesFetched: output.pagesFetched,
819
+ bytesFetched: output.bytesFetched,
820
+ nodesWritten: nodesToWrite.length,
821
+ edgesWritten: edgesToWrite.length,
822
+ writtenNodeIds: nodesToWrite.map((node) => node.id),
823
+ interests: extracted.interests,
824
+ fetches: fetchRows,
825
+ dailyUsage: updatedUsage,
826
+ };
827
+ }
828
+ export function listWebLearningRuns(storeOrDb, ownerScopeKey, limit = 20) {
829
+ const db = asDatabase(storeOrDb);
830
+ if (!hasTable(db, 'assoc_web_learning_runs'))
831
+ return [];
832
+ const rows = db
833
+ .prepare(`
834
+ SELECT run_id, owner_scope_key, started_at, finished_at, status, reason,
835
+ topics_considered, requests_used, pages_fetched, bytes_fetched,
836
+ nodes_written, details_json
837
+ FROM assoc_web_learning_runs
838
+ WHERE owner_scope_key = ?
839
+ ORDER BY started_at DESC, run_id ASC
840
+ LIMIT ?
841
+ `)
842
+ .all(ownerScopeKey, Math.max(1, Math.min(200, Math.floor(limit))));
843
+ return rows.map((row) => {
844
+ let details = null;
845
+ if (row.details_json !== null) {
846
+ try {
847
+ const parsed = JSON.parse(row.details_json);
848
+ if (parsed !== null && typeof parsed === 'object' && !Array.isArray(parsed)) {
849
+ details = parsed;
850
+ }
851
+ }
852
+ catch {
853
+ details = null;
854
+ }
855
+ }
856
+ return {
857
+ runId: row.run_id,
858
+ ownerScopeKey: row.owner_scope_key,
859
+ startedAt: row.started_at,
860
+ finishedAt: row.finished_at,
861
+ status: row.status,
862
+ reason: row.reason,
863
+ topicsConsidered: row.topics_considered,
864
+ requestsUsed: row.requests_used,
865
+ pagesFetched: row.pages_fetched,
866
+ bytesFetched: row.bytes_fetched,
867
+ nodesWritten: row.nodes_written,
868
+ details,
869
+ };
870
+ });
871
+ }
872
+ export function listWebLearningFetches(storeOrDb, ownerScopeKey, limit = 50) {
873
+ const db = asDatabase(storeOrDb);
874
+ if (!hasTable(db, 'assoc_web_learning_fetches'))
875
+ return [];
876
+ const rows = db
877
+ .prepare(`
878
+ SELECT fetch_id, owner_scope_key, run_id, canonical_url, domain,
879
+ interest_key, status, bytes_fetched, node_id, fetched_at, expires_at
880
+ FROM assoc_web_learning_fetches
881
+ WHERE owner_scope_key = ?
882
+ ORDER BY fetched_at DESC, fetch_id ASC
883
+ LIMIT ?
884
+ `)
885
+ .all(ownerScopeKey, Math.max(1, Math.min(500, Math.floor(limit))));
886
+ return rows.map((row) => ({
887
+ fetchId: row.fetch_id,
888
+ ownerScopeKey: row.owner_scope_key,
889
+ runId: row.run_id,
890
+ canonicalUrl: row.canonical_url,
891
+ domain: row.domain,
892
+ interestKey: row.interest_key,
893
+ status: row.status,
894
+ bytesFetched: row.bytes_fetched,
895
+ nodeId: row.node_id,
896
+ fetchedAt: row.fetched_at,
897
+ expiresAt: row.expires_at,
898
+ }));
899
+ }
900
+ export function withdrawWebSourceByUrl(store, scope, sourceUrl, nowMs = Date.now()) {
901
+ const canonicalUrl = canonicalizeWebSourceUrl(sourceUrl);
902
+ const sourceRef = computeWebSourceRef(canonicalUrl);
903
+ return store.withdrawSource({
904
+ ownerScopeKey: scope.ownerScopeKey,
905
+ sourcePlugin: WEB_LEARNING_SOURCE_PLUGIN,
906
+ sourceRef,
907
+ hardDelete: true,
908
+ recordWithdrawalTombstone: true,
909
+ nowMs,
910
+ });
911
+ }
912
+ //# sourceMappingURL=web-learning.js.map