@dsh-ray/assistant-proactive 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 (48) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +121 -1
  3. package/cordis.patch.yml +3 -0
  4. package/lib/attention-tuning.d.ts +31 -0
  5. package/lib/attention-tuning.d.ts.map +1 -0
  6. package/lib/attention-tuning.js +45 -0
  7. package/lib/attention-tuning.js.map +1 -0
  8. package/lib/engine.d.ts +56 -0
  9. package/lib/engine.d.ts.map +1 -0
  10. package/lib/engine.js +753 -0
  11. package/lib/engine.js.map +1 -0
  12. package/lib/goal-lifecycle.d.ts +69 -0
  13. package/lib/goal-lifecycle.d.ts.map +1 -0
  14. package/lib/goal-lifecycle.js +27 -0
  15. package/lib/goal-lifecycle.js.map +1 -0
  16. package/lib/index.d.ts +109 -0
  17. package/lib/index.d.ts.map +1 -0
  18. package/lib/index.js +1062 -0
  19. package/lib/index.js.map +1 -0
  20. package/lib/intake-evaluation.d.ts +202 -0
  21. package/lib/intake-evaluation.d.ts.map +1 -0
  22. package/lib/intake-evaluation.js +693 -0
  23. package/lib/intake-evaluation.js.map +1 -0
  24. package/lib/intake-routing.d.ts +99 -0
  25. package/lib/intake-routing.d.ts.map +1 -0
  26. package/lib/intake-routing.js +190 -0
  27. package/lib/intake-routing.js.map +1 -0
  28. package/lib/preparation-store.d.ts +48 -0
  29. package/lib/preparation-store.d.ts.map +1 -0
  30. package/lib/preparation-store.js +120 -0
  31. package/lib/preparation-store.js.map +1 -0
  32. package/lib/preparation.d.ts +16 -0
  33. package/lib/preparation.d.ts.map +1 -0
  34. package/lib/preparation.js +127 -0
  35. package/lib/preparation.js.map +1 -0
  36. package/lib/reminder.d.ts +17 -0
  37. package/lib/reminder.d.ts.map +1 -0
  38. package/lib/reminder.js +46 -0
  39. package/lib/reminder.js.map +1 -0
  40. package/lib/types.d.ts +254 -0
  41. package/lib/types.d.ts.map +1 -0
  42. package/lib/types.js +2 -0
  43. package/lib/types.js.map +1 -0
  44. package/lib/version.d.ts +2 -0
  45. package/lib/version.d.ts.map +1 -0
  46. package/lib/version.js +2 -0
  47. package/lib/version.js.map +1 -0
  48. package/package.json +93 -4
package/lib/engine.js ADDED
@@ -0,0 +1,753 @@
1
+ import { closeSync, constants, lstatSync, mkdirSync, openSync, chmodSync } from 'node:fs';
2
+ import { dirname, isAbsolute } from 'node:path';
3
+ import { randomUUID } from 'node:crypto';
4
+ import { DatabaseSync } from 'node:sqlite';
5
+ import { reminderContentDigest } from './reminder.js';
6
+ import { attentionOverlay, tuneProfile } from './attention-tuning.js';
7
+ export const RECENT_NOTIFICATION_WINDOW_MS = 3_600_000;
8
+ export const URGENCY_WINDOW_MS = 900_000;
9
+ export const ACTIVE_IDLE_THRESHOLD_MS = 60_000;
10
+ export const IDLE_DISCOUNT_START_MS = 600_000;
11
+ export const IDLE_DISCOUNT_FULL_MS = 3_600_000;
12
+ export const MAX_ACTIVITY_PENALTY = 15;
13
+ export const MAX_IDLE_DISCOUNT = 10;
14
+ export const PENALTY_PER_RECENT_NOTIFICATION = 5;
15
+ export const MAX_FREQUENCY_PENALTY = 40;
16
+ export const MAX_URGENCY_BONUS = 20;
17
+ export const MAX_ACCEPTANCE_BONUS = 15;
18
+ export const MAX_ACCEPTANCE_PENALTY = 20;
19
+ const DEFAULT_EXPLICIT_ACCEPTANCE_SAMPLES = 10;
20
+ const RUNTIME_CONTEXT_KEYS = [
21
+ 'userActive',
22
+ 'idleDurationMs',
23
+ 'recentNotificationCount',
24
+ 'urgencyPpm',
25
+ 'acceptanceRatePpm',
26
+ 'acceptanceSamples',
27
+ ];
28
+ const DYNAMIC_SIGNAL_KEYS = [
29
+ ...RUNTIME_CONTEXT_KEYS,
30
+ 'remainingTtlMs',
31
+ 'acceptedCount',
32
+ 'rejectedCount',
33
+ 'overlayInterruptionCostDelta',
34
+ ];
35
+ const max = 1_000_000_000;
36
+ const integer = (value, limit = max) => typeof value === 'number' && Number.isSafeInteger(value) && value >= 0 && value <= limit;
37
+ const text = (value, limit = 4096) => typeof value === 'string' && value.length > 0 && value.length <= limit && !/[\s\p{Cc}]/u.test(value);
38
+ const content = (value, limit = 65_536) => typeof value === 'string' && value.length > 0 && value.length <= limit && !/[\p{Cc}]/u.test(value.replace(/[\r\n]/gu, ''));
39
+ const freeze = (value) => Object.freeze(JSON.parse(JSON.stringify(value)));
40
+ function fail(message = 'assistant-proactive: invalid opportunity input') { throw new Error(message); }
41
+ export function privatePath(path) {
42
+ if (!isAbsolute(path))
43
+ fail('assistant-proactive: databasePath must be absolute');
44
+ mkdirSync(dirname(path), { recursive: true, mode: 0o700 });
45
+ const directory = lstatSync(dirname(path));
46
+ if (!directory.isDirectory() || directory.isSymbolicLink() || (directory.mode & 0o022) !== 0)
47
+ fail('assistant-proactive: unsafe database directory');
48
+ try {
49
+ lstatSync(path);
50
+ }
51
+ catch (error) {
52
+ if (!error || typeof error !== 'object' || !('code' in error) || error.code !== 'ENOENT')
53
+ throw error;
54
+ closeSync(openSync(path, constants.O_CREAT | constants.O_EXCL | constants.O_RDWR | constants.O_NOFOLLOW, 0o600));
55
+ chmodSync(path, 0o600);
56
+ }
57
+ for (const item of [path, `${path}-wal`, `${path}-shm`]) {
58
+ try {
59
+ const stat = lstatSync(item);
60
+ if (!stat.isFile() || stat.isSymbolicLink() || stat.nlink !== 1 || (stat.mode & 0o077) !== 0)
61
+ fail('assistant-proactive: unsafe database file');
62
+ }
63
+ catch (error) {
64
+ if (!error || typeof error !== 'object' || !('code' in error) || error.code !== 'ENOENT')
65
+ throw error;
66
+ }
67
+ }
68
+ }
69
+ export function validateProfile(input) {
70
+ if (!input || typeof input !== 'object' || Object.keys(input).some(key => !['preparation', 'id', 'mode', 'expectedBenefit', 'successPpm', 'executionCost', 'interruptionCost', 'possibleLoss', 'minimumUtility', 'mergeWindowMs', 'cooldownMs', 'rejectionCooldownMs', 'quietHours', 'maxDecisionsPerGoal', 'maxExecutionsPerGoal', 'maxRemindersPerGoal'].includes(key))
71
+ || !text(input.id) || !['prepare', 'remind', 'execute'].includes(input.mode) || input.successPpm > 1_000_000
72
+ || ![input.expectedBenefit, input.successPpm, input.executionCost, input.interruptionCost, input.possibleLoss, input.minimumUtility, input.mergeWindowMs, input.cooldownMs, input.rejectionCooldownMs, input.maxDecisionsPerGoal, input.maxExecutionsPerGoal, input.maxRemindersPerGoal].every(value => integer(value)))
73
+ fail('assistant-proactive: invalid profile');
74
+ if (input.quietHours !== undefined) {
75
+ const quiet = input.quietHours;
76
+ if (!quiet || typeof quiet !== 'object' || Object.keys(quiet).length !== 3 || typeof quiet.timezone !== 'string' || quiet.timezone.length > 128 || !integer(quiet.startMinute, 1439) || !integer(quiet.endMinute, 1439) || quiet.startMinute === quiet.endMinute)
77
+ fail('assistant-proactive: invalid quiet hours');
78
+ try {
79
+ Intl.DateTimeFormat('en-US', { timeZone: quiet.timezone }).format();
80
+ }
81
+ catch {
82
+ fail('assistant-proactive: invalid quiet hours');
83
+ }
84
+ }
85
+ if (input.preparation !== undefined) {
86
+ const p = input.preparation;
87
+ if (input.mode !== 'prepare' || !p || typeof p !== 'object' || Object.keys(p).length !== 5
88
+ || ![p.provider, p.model, p.budgetId].every(value => text(value, 512))
89
+ || !integer(p.maxOutputTokens, 32_768) || p.maxOutputTokens < 1
90
+ || !integer(p.timeoutMs, 300_000) || p.timeoutMs < 1_000)
91
+ fail('assistant-proactive: invalid preparation settings');
92
+ }
93
+ // BigInt makes the product exact before the bounded public number conversion.
94
+ const utility = BigInt(input.expectedBenefit) * BigInt(input.successPpm) / 1000000n - BigInt(input.executionCost) - BigInt(input.interruptionCost) - BigInt(input.possibleLoss);
95
+ if (utility < BigInt(-Number.MAX_SAFE_INTEGER) || utility > BigInt(Number.MAX_SAFE_INTEGER))
96
+ fail('assistant-proactive: unsafe utility');
97
+ return freeze({ ...input, ...(input.quietHours === undefined ? {} : { quietHours: { ...input.quietHours } }) });
98
+ }
99
+ function scopeKey(scope) {
100
+ if (!scope || typeof scope !== 'object' || Object.keys(scope).length !== 5 || ![scope.principalId, scope.principalRecordId, scope.preset].every(item => text(item, 4096)) || !content(scope.workspace, 4096) || !integer(scope.principalVersion) || scope.principalVersion < 1 || !scope.workspace.startsWith('/'))
101
+ fail();
102
+ return JSON.stringify({ principalId: scope.principalId, principalRecordId: scope.principalRecordId, principalVersion: scope.principalVersion, workspace: scope.workspace, preset: scope.preset });
103
+ }
104
+ function validateInput(input) {
105
+ if (!input || typeof input !== 'object' || ![input.waitId, input.profileId, input.goalId, input.sessionId, input.definitionDigest, input.nativeGoalId, input.ownerRouteId, input.sourceDigest, input.sourceId, input.event.id, input.event.digest].every(value => text(value)) || !content(input.objective)
106
+ || input.event.observationDigest !== undefined && (typeof input.event.observationDigest !== 'string' || !/^[a-f0-9]{64}$/u.test(input.event.observationDigest))
107
+ || !integer(input.nativeRevision) || !integer(input.event.sequence) || !integer(input.event.occurredAt, Number.MAX_SAFE_INTEGER) || !integer(input.expiresAt, Number.MAX_SAFE_INTEGER))
108
+ fail();
109
+ scopeKey(input.scope);
110
+ }
111
+ function reminderContent(input) {
112
+ return { goalId: input.goalId, objective: input.objective, definitionDigest: input.definitionDigest, nativeGoalId: input.nativeGoalId, nativeRevision: input.nativeRevision,
113
+ sourceId: input.sourceId, sourceDigest: input.sourceDigest, eventDigest: input.event.digest, eventObservationDigest: input.event.observationDigest };
114
+ }
115
+ function plainRecord(value, message) {
116
+ if (typeof value !== 'object' || value === null || Array.isArray(value))
117
+ fail(message);
118
+ const proto = Object.getPrototypeOf(value);
119
+ if (proto !== Object.prototype && proto !== null)
120
+ fail(message);
121
+ if (Object.getOwnPropertySymbols(value).length !== 0)
122
+ fail(message);
123
+ return value;
124
+ }
125
+ export function validateRuntimeContext(context) {
126
+ if (context === undefined)
127
+ return undefined;
128
+ const record = plainRecord(context, 'assistant-proactive: invalid runtime context');
129
+ for (const key of Object.keys(record)) {
130
+ if (!RUNTIME_CONTEXT_KEYS.includes(key))
131
+ fail('assistant-proactive: invalid runtime context');
132
+ }
133
+ const normalized = {};
134
+ if (record['userActive'] !== undefined) {
135
+ if (typeof record['userActive'] !== 'boolean')
136
+ fail('assistant-proactive: invalid runtime context');
137
+ normalized.userActive = record['userActive'];
138
+ }
139
+ if (record['idleDurationMs'] !== undefined) {
140
+ if (!integer(record['idleDurationMs'], Number.MAX_SAFE_INTEGER))
141
+ fail('assistant-proactive: invalid runtime context');
142
+ normalized.idleDurationMs = record['idleDurationMs'];
143
+ }
144
+ if (record['recentNotificationCount'] !== undefined) {
145
+ if (!integer(record['recentNotificationCount'], Number.MAX_SAFE_INTEGER))
146
+ fail('assistant-proactive: invalid runtime context');
147
+ normalized.recentNotificationCount = record['recentNotificationCount'];
148
+ }
149
+ if (record['urgencyPpm'] !== undefined) {
150
+ if (!integer(record['urgencyPpm'], 1_000_000))
151
+ fail('assistant-proactive: invalid runtime context');
152
+ normalized.urgencyPpm = record['urgencyPpm'];
153
+ }
154
+ if (record['acceptanceRatePpm'] !== undefined) {
155
+ if (!integer(record['acceptanceRatePpm'], 1_000_000))
156
+ fail('assistant-proactive: invalid runtime context');
157
+ normalized.acceptanceRatePpm = record['acceptanceRatePpm'];
158
+ }
159
+ if (record['acceptanceSamples'] !== undefined) {
160
+ if (!integer(record['acceptanceSamples'], Number.MAX_SAFE_INTEGER))
161
+ fail('assistant-proactive: invalid runtime context');
162
+ normalized.acceptanceSamples = record['acceptanceSamples'];
163
+ }
164
+ return Object.freeze(normalized);
165
+ }
166
+ function validateDynamicSignals(signals) {
167
+ if (signals === undefined)
168
+ return {};
169
+ const record = plainRecord(signals, 'assistant-proactive: invalid dynamic utility signals');
170
+ for (const key of Object.keys(record)) {
171
+ if (!DYNAMIC_SIGNAL_KEYS.includes(key))
172
+ fail('assistant-proactive: invalid dynamic utility signals');
173
+ }
174
+ const base = validateRuntimeContext({
175
+ ...(record['userActive'] === undefined ? {} : { userActive: record['userActive'] }),
176
+ ...(record['idleDurationMs'] === undefined ? {} : { idleDurationMs: record['idleDurationMs'] }),
177
+ ...(record['recentNotificationCount'] === undefined ? {} : { recentNotificationCount: record['recentNotificationCount'] }),
178
+ ...(record['urgencyPpm'] === undefined ? {} : { urgencyPpm: record['urgencyPpm'] }),
179
+ ...(record['acceptanceRatePpm'] === undefined ? {} : { acceptanceRatePpm: record['acceptanceRatePpm'] }),
180
+ ...(record['acceptanceSamples'] === undefined ? {} : { acceptanceSamples: record['acceptanceSamples'] }),
181
+ }) ?? {};
182
+ let remainingTtlMs;
183
+ if (record['remainingTtlMs'] !== undefined) {
184
+ const rawTtl = record['remainingTtlMs'];
185
+ if (typeof rawTtl !== 'number' || !Number.isSafeInteger(rawTtl))
186
+ fail('assistant-proactive: invalid dynamic utility signals');
187
+ remainingTtlMs = rawTtl;
188
+ }
189
+ let acceptedCount;
190
+ if (record['acceptedCount'] !== undefined) {
191
+ if (!integer(record['acceptedCount'], Number.MAX_SAFE_INTEGER))
192
+ fail('assistant-proactive: invalid dynamic utility signals');
193
+ acceptedCount = record['acceptedCount'];
194
+ }
195
+ let rejectedCount;
196
+ if (record['rejectedCount'] !== undefined) {
197
+ if (!integer(record['rejectedCount'], Number.MAX_SAFE_INTEGER))
198
+ fail('assistant-proactive: invalid dynamic utility signals');
199
+ rejectedCount = record['rejectedCount'];
200
+ }
201
+ let overlayInterruptionCostDelta;
202
+ if (record['overlayInterruptionCostDelta'] !== undefined) {
203
+ if (!integer(record['overlayInterruptionCostDelta'], max))
204
+ fail('assistant-proactive: invalid dynamic utility signals');
205
+ overlayInterruptionCostDelta = record['overlayInterruptionCostDelta'];
206
+ }
207
+ return {
208
+ ...base,
209
+ ...(remainingTtlMs === undefined ? {} : { remainingTtlMs }),
210
+ ...(acceptedCount === undefined ? {} : { acceptedCount }),
211
+ ...(rejectedCount === undefined ? {} : { rejectedCount }),
212
+ ...(overlayInterruptionCostDelta === undefined ? {} : { overlayInterruptionCostDelta }),
213
+ };
214
+ }
215
+ function clampSafeInteger(value) {
216
+ const minSafe = BigInt(-Number.MAX_SAFE_INTEGER);
217
+ const maxSafe = BigInt(Number.MAX_SAFE_INTEGER);
218
+ if (value < minSafe)
219
+ return -Number.MAX_SAFE_INTEGER;
220
+ if (value > maxSafe)
221
+ return Number.MAX_SAFE_INTEGER;
222
+ return Number(value);
223
+ }
224
+ /**
225
+ * Bounded, deterministic WP12 dynamic utility & interruption cost calculation.
226
+ * Neutral signals (no activity/idle signal, 0 recent notifications, unbounded/long TTL,
227
+ * empty feedback history) produce 0 adjustment so behavior matches the static formula.
228
+ */
229
+ export function computeDynamicUtility(profile, signals = {}) {
230
+ if (!profile || typeof profile !== 'object'
231
+ || !integer(profile.expectedBenefit, Number.MAX_SAFE_INTEGER)
232
+ || !integer(profile.successPpm, 1_000_000)
233
+ || !integer(profile.executionCost, Number.MAX_SAFE_INTEGER)
234
+ || !integer(profile.interruptionCost, Number.MAX_SAFE_INTEGER)
235
+ || !integer(profile.possibleLoss, Number.MAX_SAFE_INTEGER)) {
236
+ fail('assistant-proactive: invalid profile');
237
+ }
238
+ const checked = validateDynamicSignals(signals);
239
+ const overlayDelta = checked.overlayInterruptionCostDelta ?? 0;
240
+ const baseInterruptionCost = Math.max(0, profile.interruptionCost - overlayDelta);
241
+ // 1. User activity / idle duration (idle discount applies only to base profile interruptionCost, never overlay delta)
242
+ let activityAdjustment = 0;
243
+ if (checked.userActive === true || (checked.idleDurationMs !== undefined && checked.idleDurationMs < ACTIVE_IDLE_THRESHOLD_MS)) {
244
+ activityAdjustment = MAX_ACTIVITY_PENALTY;
245
+ }
246
+ else if (checked.idleDurationMs !== undefined && checked.idleDurationMs >= IDLE_DISCOUNT_START_MS) {
247
+ const span = IDLE_DISCOUNT_FULL_MS - IDLE_DISCOUNT_START_MS;
248
+ const elapsed = Math.min(checked.idleDurationMs - IDLE_DISCOUNT_START_MS, span);
249
+ const rawDiscount = Math.floor((MAX_IDLE_DISCOUNT * elapsed) / span);
250
+ const maxDiscount = Math.min(MAX_IDLE_DISCOUNT, baseInterruptionCost);
251
+ activityAdjustment = -Math.min(maxDiscount, rawDiscount);
252
+ }
253
+ // 2. Recent notification frequency / rate
254
+ const recentCount = Math.min(1_000_000, Math.max(0, checked.recentNotificationCount ?? 0));
255
+ const frequencyPenalty = Math.min(MAX_FREQUENCY_PENALTY, recentCount * PENALTY_PER_RECENT_NOTIFICATION);
256
+ const effectiveInterruptionCost = Math.max(0, profile.interruptionCost + activityAdjustment + frequencyPenalty);
257
+ const interruptionDelta = effectiveInterruptionCost - profile.interruptionCost;
258
+ // 3. Urgency / remaining TTL
259
+ let urgencyBonus = 0;
260
+ if (checked.urgencyPpm !== undefined) {
261
+ urgencyBonus = Math.floor((MAX_URGENCY_BONUS * checked.urgencyPpm) / 1_000_000);
262
+ }
263
+ else if (checked.remainingTtlMs !== undefined && checked.remainingTtlMs >= 0 && checked.remainingTtlMs < URGENCY_WINDOW_MS) {
264
+ urgencyBonus = Math.floor((MAX_URGENCY_BONUS * (URGENCY_WINDOW_MS - checked.remainingTtlMs)) / URGENCY_WINDOW_MS);
265
+ }
266
+ // 4. Historical acceptance rate (Laplace-smoothed, cold-start neutral)
267
+ let accepted = checked.acceptedCount ?? 0;
268
+ let rejected = checked.rejectedCount ?? 0;
269
+ if (checked.acceptanceRatePpm !== undefined) {
270
+ const extSamples = checked.acceptanceSamples ?? DEFAULT_EXPLICIT_ACCEPTANCE_SAMPLES;
271
+ if (extSamples > 0) {
272
+ const extAccepted = Math.round((checked.acceptanceRatePpm * extSamples) / 1_000_000);
273
+ const extRejected = extSamples - extAccepted;
274
+ accepted = Math.max(accepted, extAccepted);
275
+ rejected = Math.max(rejected, extRejected);
276
+ }
277
+ }
278
+ const totalFeedback = BigInt(accepted) + BigInt(rejected);
279
+ let acceptanceAdjustment = 0;
280
+ if (totalFeedback > 0n) {
281
+ const smoothedPpm = Number(((BigInt(accepted) + 1n) * 1000000n) / (totalFeedback + 2n));
282
+ const rawDelta = Math.trunc(((smoothedPpm - 500_000) * 40) / 500_000);
283
+ acceptanceAdjustment = Math.max(-MAX_ACCEPTANCE_PENALTY, Math.min(MAX_ACCEPTANCE_BONUS, rawDelta));
284
+ }
285
+ const baseUtilityBig = (BigInt(profile.expectedBenefit) * BigInt(profile.successPpm)) / 1000000n
286
+ - BigInt(profile.executionCost)
287
+ - BigInt(profile.interruptionCost)
288
+ - BigInt(profile.possibleLoss);
289
+ const effectiveUtilityBig = baseUtilityBig
290
+ - BigInt(interruptionDelta)
291
+ + BigInt(urgencyBonus)
292
+ + BigInt(acceptanceAdjustment);
293
+ return Object.freeze({
294
+ baseUtility: clampSafeInteger(baseUtilityBig),
295
+ baseInterruptionCost,
296
+ effectiveInterruptionCost,
297
+ activityAdjustment,
298
+ frequencyPenalty,
299
+ urgencyBonus,
300
+ acceptanceAdjustment,
301
+ effectiveUtility: clampSafeInteger(effectiveUtilityBig),
302
+ });
303
+ }
304
+ function minuteAt(now, timezone) {
305
+ const parts = new Intl.DateTimeFormat('en-US', { timeZone: timezone, hour: '2-digit', minute: '2-digit', hourCycle: 'h23' }).formatToParts(new Date(now));
306
+ const get = (name) => Number(parts.find(part => part.type === name)?.value);
307
+ return get('hour') * 60 + get('minute');
308
+ }
309
+ function quiet(now, profile) {
310
+ const value = profile.quietHours;
311
+ if (!value)
312
+ return false;
313
+ const minute = minuteAt(now, value.timezone);
314
+ return value.startMinute < value.endMinute ? minute >= value.startMinute && minute < value.endMinute : minute >= value.startMinute || minute < value.endMinute;
315
+ }
316
+ function quietEndsAt(now, profile) {
317
+ for (let offset = 60_000; offset <= 25 * 60 * 60_000; offset += 60_000)
318
+ if (!quiet(now + offset, profile))
319
+ return now + offset;
320
+ fail('assistant-proactive: quiet hours did not end');
321
+ }
322
+ /** Durable, owner-scoped opportunity accounting. Utility is an operator estimate, not a probability or a bill. */
323
+ export class OpportunityEngine {
324
+ #db;
325
+ #profiles = new Map();
326
+ #now;
327
+ #overlay;
328
+ constructor(path, profiles, options = {}) {
329
+ if (!Array.isArray(profiles))
330
+ fail('assistant-proactive: profiles must be an array');
331
+ for (const item of profiles) {
332
+ const profile = validateProfile(item);
333
+ if (this.#profiles.has(profile.id))
334
+ fail('assistant-proactive: duplicate profile');
335
+ this.#profiles.set(profile.id, profile);
336
+ }
337
+ this.#now = options.now ?? Date.now;
338
+ if (path !== ':memory:')
339
+ privatePath(path);
340
+ this.#db = new DatabaseSync(path);
341
+ this.#db.exec(`PRAGMA journal_mode = WAL; PRAGMA synchronous = FULL; PRAGMA busy_timeout = 250;
342
+ CREATE TABLE IF NOT EXISTS proactive_profiles(scope_json TEXT NOT NULL, goal_id TEXT NOT NULL, profile_id TEXT NOT NULL, profile_json TEXT NOT NULL, PRIMARY KEY(scope_json, goal_id, profile_id)) STRICT, WITHOUT ROWID;
343
+ CREATE TABLE IF NOT EXISTS proactive_decisions(id TEXT PRIMARY KEY, scope_json TEXT NOT NULL, goal_id TEXT NOT NULL, profile_id TEXT NOT NULL, payload_json TEXT NOT NULL) STRICT;
344
+ CREATE TABLE IF NOT EXISTS proactive_events(scope_json TEXT NOT NULL, goal_id TEXT NOT NULL, profile_id TEXT NOT NULL, source_id TEXT NOT NULL, event_sequence INTEGER NOT NULL, event_digest TEXT NOT NULL, decision_id TEXT NOT NULL REFERENCES proactive_decisions(id), PRIMARY KEY(scope_json, goal_id, profile_id, source_id, event_sequence, event_digest)) STRICT, WITHOUT ROWID;
345
+ CREATE INDEX IF NOT EXISTS proactive_decisions_goal ON proactive_decisions(scope_json, goal_id, profile_id);
346
+ CREATE TABLE IF NOT EXISTS proactive_reminders(scope_json TEXT NOT NULL, goal_id TEXT NOT NULL, source_id TEXT NOT NULL, content_digest TEXT NOT NULL, decision_id TEXT NOT NULL REFERENCES proactive_decisions(id), queued INTEGER NOT NULL DEFAULT 0 CHECK(queued IN (0, 1)), PRIMARY KEY(scope_json, goal_id, source_id)) STRICT, WITHOUT ROWID;`);
347
+ // Pre-release development databases may hold the table without `queued`; add it in place.
348
+ if (!this.#db.prepare('PRAGMA table_info(proactive_reminders)').all().some(column => column.name === 'queued'))
349
+ this.#db.exec('ALTER TABLE proactive_reminders ADD COLUMN queued INTEGER NOT NULL DEFAULT 0 CHECK(queued IN (0, 1))');
350
+ }
351
+ /**
352
+ * `overlay` is an optional verified tighten-only Evaluation attention version.
353
+ * It is applied to the frozen goal profile for this evaluation only and is
354
+ * never persisted into the profile snapshot.
355
+ */
356
+ evaluate(input, overlay, runtimeContext) {
357
+ this.#db.exec('BEGIN IMMEDIATE');
358
+ try {
359
+ this.#overlay = attentionOverlay(overlay);
360
+ const context = validateRuntimeContext(runtimeContext);
361
+ const value = this.#evaluate(input, context);
362
+ this.#db.exec('COMMIT');
363
+ return value;
364
+ }
365
+ catch (error) {
366
+ try {
367
+ this.#db.exec('ROLLBACK');
368
+ }
369
+ catch { }
370
+ throw error;
371
+ }
372
+ finally {
373
+ this.#overlay = undefined;
374
+ }
375
+ }
376
+ #evaluate(input, context) {
377
+ validateInput(input);
378
+ const now = this.#now();
379
+ if (!integer(now, Number.MAX_SAFE_INTEGER))
380
+ fail('assistant-proactive: invalid clock');
381
+ const scope = scopeKey(input.scope);
382
+ const profile = tuneProfile(this.#profile(scope, input.goalId, input.profileId), this.#overlay);
383
+ let cachedUtility;
384
+ const currentUtility = () => cachedUtility ?? (cachedUtility = this.#dynamicUtility(scope, input, profile, now, context));
385
+ const existing = this.#event(scope, input);
386
+ if (existing) {
387
+ if (!this.#sameIdentity(existing, input))
388
+ fail('assistant-proactive: event identity conflict');
389
+ if (now >= input.expiresAt)
390
+ return this.#terminal(existing, 'consume', 'suppress', 'expired', now);
391
+ const rejected = this.#latestRejected(scope, input.goalId, profile.id);
392
+ if (rejected && rejected.id !== existing.id && now < rejected.updatedAt + profile.rejectionCooldownMs)
393
+ return this.#terminal(existing, 'consume', 'suppress', 'rejected-cooldown', now);
394
+ if (existing.state === 'pending' && now >= existing.eligibleAt)
395
+ return this.#mature(scope, existing, input, profile, now, context);
396
+ return freeze({ disposition: existing.mode === 'execute' && existing.state === 'decided' ? 'execute' : existing.state === 'pending' ? 'defer' : 'consume', decision: existing });
397
+ }
398
+ if (this.#sequenceConflict(scope, input))
399
+ fail('assistant-proactive: event sequence conflict');
400
+ const latest = this.#latest(scope, input.goalId, profile.id, input.sourceId);
401
+ if (latest && input.event.sequence < latest.eventSequence)
402
+ return freeze({ disposition: 'consume', decision: latest });
403
+ if (now >= input.expiresAt)
404
+ return this.#save(scope, input, profile, 'consume', 'suppress', 'expired', now, now, currentUtility());
405
+ const rejected = this.#latestRejected(scope, input.goalId, profile.id);
406
+ if (rejected && now < rejected.updatedAt + profile.rejectionCooldownMs)
407
+ return this.#save(scope, input, profile, 'consume', 'suppress', 'rejected-cooldown', now, now, currentUtility());
408
+ if (latest?.state === 'pending' && this.#sameIdentity(latest, input) && now < latest.eligibleAt)
409
+ return this.#merge(scope, latest, input, now);
410
+ if (latest?.state === 'pending' && this.#sameIdentity(latest, input))
411
+ return this.#mature(scope, latest, input, profile, now, context);
412
+ const counts = this.#counts(scope, input.goalId);
413
+ if (counts.ledger >= profile.maxDecisionsPerGoal || profile.mode === 'execute' && counts.executions >= profile.maxExecutionsPerGoal || profile.mode === 'remind' && counts.reminders >= profile.maxRemindersPerGoal)
414
+ return this.#budgetProjection(input, profile, now, currentUtility());
415
+ if (this.#muted(profile))
416
+ return this.#save(scope, input, profile, 'consume', 'suppress', 'attention-muted', now, now, currentUtility());
417
+ if (quiet(now, profile))
418
+ return this.#save(scope, input, profile, 'defer', 'suppress', 'quiet-hours', now, quietEndsAt(now, profile), currentUtility());
419
+ if (currentUtility() < profile.minimumUtility)
420
+ return this.#save(scope, input, profile, 'consume', 'suppress', 'below-threshold', now, now, currentUtility());
421
+ if (latest && now < latest.updatedAt + profile.cooldownMs)
422
+ return this.#save(scope, input, profile, 'consume', 'suppress', 'cooldown', now, now, currentUtility());
423
+ if (profile.mergeWindowMs > 0)
424
+ return this.#save(scope, input, profile, 'defer', 'suppress', 'coalescing', now, now + profile.mergeWindowMs, currentUtility());
425
+ if (profile.mode === 'remind' && this.#unchangedReminder(scope, reminderContent(input)))
426
+ return this.#save(scope, input, profile, 'consume', 'suppress', 'unchanged', now, now, currentUtility());
427
+ return this.#save(scope, input, profile, profile.mode === 'execute' ? 'execute' : 'consume', profile.mode, profile.mode === 'execute' ? 'execution' : profile.mode === 'remind' ? 'reminder' : 'prepared', now, now, currentUtility());
428
+ }
429
+ feedback(id, scopeInput, feedback) {
430
+ this.#db.exec('BEGIN IMMEDIATE');
431
+ try {
432
+ if (!text(id) || !['accepted', 'rejected'].includes(feedback))
433
+ fail();
434
+ const scope = scopeKey(scopeInput);
435
+ const found = this.#decision(id);
436
+ if (!found || scopeKey(found.scope) !== scope || found.state !== 'decided')
437
+ fail('assistant-proactive: opportunity decision is unavailable');
438
+ const next = freeze({ ...found, state: 'closed', feedback, updatedAt: this.#now() });
439
+ this.#put(next);
440
+ this.#db.exec('COMMIT');
441
+ return next;
442
+ }
443
+ catch (error) {
444
+ try {
445
+ this.#db.exec('ROLLBACK');
446
+ }
447
+ catch { }
448
+ throw error;
449
+ }
450
+ }
451
+ get(id) {
452
+ if (!text(id))
453
+ fail();
454
+ return this.#decision(id);
455
+ }
456
+ list(scopeInput, goalId) {
457
+ const scope = scopeKey(scopeInput);
458
+ if (goalId !== undefined && !text(goalId))
459
+ fail();
460
+ const rows = this.#db.prepare(`SELECT payload_json FROM proactive_decisions WHERE scope_json = ? ${goalId === undefined ? '' : 'AND goal_id = ?'} ORDER BY json_extract(payload_json, '$.firstObservedAt'), id`).all(...(goalId === undefined ? [scope] : [scope, goalId]));
461
+ return freeze(rows.map(row => this.#parse(row.payload_json)));
462
+ }
463
+ listScopes() {
464
+ const rows = this.#db.prepare('SELECT DISTINCT scope_json FROM proactive_decisions').all();
465
+ return freeze(rows.map(row => JSON.parse(row.scope_json)));
466
+ }
467
+ listAll(filter = {}) {
468
+ const conditions = [];
469
+ const params = [];
470
+ if (filter.scope !== undefined) {
471
+ conditions.push('scope_json = ?');
472
+ params.push(scopeKey(filter.scope));
473
+ }
474
+ if (filter.workspace !== undefined) {
475
+ if (!content(filter.workspace, 4096) || !filter.workspace.startsWith('/'))
476
+ fail();
477
+ conditions.push("json_extract(scope_json, '$.workspace') = ?");
478
+ params.push(filter.workspace);
479
+ }
480
+ if (filter.preset !== undefined) {
481
+ if (!text(filter.preset, 4096))
482
+ fail();
483
+ conditions.push("json_extract(scope_json, '$.preset') = ?");
484
+ params.push(filter.preset);
485
+ }
486
+ if (filter.principalId !== undefined) {
487
+ if (!text(filter.principalId, 4096))
488
+ fail();
489
+ conditions.push("json_extract(scope_json, '$.principalId') = ?");
490
+ params.push(filter.principalId);
491
+ }
492
+ if (filter.goalId !== undefined) {
493
+ if (!text(filter.goalId))
494
+ fail();
495
+ conditions.push('goal_id = ?');
496
+ params.push(filter.goalId);
497
+ }
498
+ if (filter.state !== undefined) {
499
+ if (!['pending', 'decided', 'closed'].includes(filter.state))
500
+ fail();
501
+ conditions.push("json_extract(payload_json, '$.state') = ?");
502
+ params.push(filter.state);
503
+ }
504
+ if (filter.mode !== undefined) {
505
+ if (!['prepare', 'remind', 'execute', 'suppress'].includes(filter.mode))
506
+ fail();
507
+ conditions.push("json_extract(payload_json, '$.mode') = ?");
508
+ params.push(filter.mode);
509
+ }
510
+ const limit = typeof filter.limit === 'number' && Number.isSafeInteger(filter.limit) && filter.limit > 0
511
+ ? Math.min(filter.limit, 500) : 100;
512
+ const where = conditions.length > 0 ? `WHERE ${conditions.join(' AND ')}` : '';
513
+ const rows = this.#db.prepare(`SELECT payload_json FROM proactive_decisions ${where} ORDER BY json_extract(payload_json, '$.updatedAt') DESC, rowid DESC LIMIT ?`).all(...params, limit);
514
+ return freeze(rows.map(row => this.#parse(row.payload_json)));
515
+ }
516
+ profileSnapshot(scope, goalId, profileId) {
517
+ const row = this.#db.prepare('SELECT profile_json FROM proactive_profiles WHERE scope_json = ? AND goal_id = ? AND profile_id = ?').get(scopeKey(scope), goalId, profileId);
518
+ if (!row)
519
+ fail('assistant-proactive: frozen goal profile unavailable');
520
+ return validateProfile(JSON.parse(row.profile_json));
521
+ }
522
+ closeWait(waitId, scope, reason) {
523
+ if (!text(waitId) || !['expired', 'cancelled'].includes(reason))
524
+ fail();
525
+ this.#db.exec('BEGIN IMMEDIATE');
526
+ try {
527
+ for (const decision of this.list(scope))
528
+ if (decision.waitId === waitId && decision.state === 'pending')
529
+ this.#terminal(decision, 'consume', 'suppress', reason, this.#now());
530
+ this.#db.exec('COMMIT');
531
+ }
532
+ catch (error) {
533
+ this.#db.exec('ROLLBACK');
534
+ throw error;
535
+ }
536
+ }
537
+ sourcesForWait(waitId, scopeInput) {
538
+ if (!text(waitId))
539
+ fail();
540
+ return collectSourceLinks(this.list(scopeInput).filter(decision => decision.waitId === waitId));
541
+ }
542
+ sourcesForGoal(scopeInput, goalId) {
543
+ if (!text(goalId))
544
+ fail();
545
+ return collectSourceLinks(this.list(scopeInput, goalId));
546
+ }
547
+ listByNativeGoal(nativeGoalId, sessionId) {
548
+ if (!text(nativeGoalId))
549
+ fail();
550
+ if (sessionId !== undefined && !text(sessionId))
551
+ fail();
552
+ const sql = sessionId === undefined
553
+ ? "SELECT payload_json FROM proactive_decisions WHERE json_extract(payload_json, '$.nativeGoalId') = ? ORDER BY json_extract(payload_json, '$.updatedAt') DESC, rowid DESC LIMIT 64"
554
+ : "SELECT payload_json FROM proactive_decisions WHERE json_extract(payload_json, '$.nativeGoalId') = ? AND json_extract(payload_json, '$.sessionId') = ? ORDER BY json_extract(payload_json, '$.updatedAt') DESC, rowid DESC LIMIT 64";
555
+ const rows = (sessionId === undefined
556
+ ? this.#db.prepare(sql).all(nativeGoalId)
557
+ : this.#db.prepare(sql).all(nativeGoalId, sessionId));
558
+ return freeze(rows.map(row => this.#parse(row.payload_json)));
559
+ }
560
+ closeGoal(scopeInput, goalId, reason) {
561
+ if (!text(goalId) || !['completed', 'cancelled', 'expired', 'retired'].includes(reason))
562
+ fail();
563
+ const terminalReason = reason === 'expired' ? 'expired' : 'cancelled';
564
+ this.#db.exec('BEGIN IMMEDIATE');
565
+ try {
566
+ const closed = [];
567
+ for (const decision of this.list(scopeInput, goalId)) {
568
+ if (decision.state === 'pending') {
569
+ closed.push(this.#terminal(decision, 'consume', 'suppress', terminalReason, this.#now()).decision);
570
+ }
571
+ }
572
+ this.#db.exec('COMMIT');
573
+ return freeze(closed);
574
+ }
575
+ catch (error) {
576
+ this.#db.exec('ROLLBACK');
577
+ throw error;
578
+ }
579
+ }
580
+ /** Delivery accepted (queued) this decision's reminder; a later replay past its send window keeps the dedupe. */
581
+ confirmReminder(decision) {
582
+ this.#db.prepare('UPDATE proactive_reminders SET queued = 1 WHERE scope_json = ? AND goal_id = ? AND source_id = ? AND decision_id = ?').run(scopeKey(decision.scope), decision.goalId, decision.sourceId, decision.id);
583
+ }
584
+ /**
585
+ * This decision's reminder was never accepted by Delivery and its send window has closed, so it must not
586
+ * count as seen. Only the unconfirmed row this decision wrote is removed; a newer reminder is left alone.
587
+ */
588
+ releaseReminder(decision) {
589
+ this.#db.prepare('DELETE FROM proactive_reminders WHERE scope_json = ? AND goal_id = ? AND source_id = ? AND decision_id = ? AND queued = 0').run(scopeKey(decision.scope), decision.goalId, decision.sourceId, decision.id);
590
+ }
591
+ close() { this.#db.close(); }
592
+ #muted(profile) { return profile.mode === 'remind' && this.#overlay?.parameters.muted === true; }
593
+ /** Records which attention version shaped a decision; absent when no overlay applied. */
594
+ #attention(profile) {
595
+ return this.#overlay && profile.mode === 'remind' ? { attentionTuning: freeze({ version: this.#overlay.version, digest: this.#overlay.digest }) } : {};
596
+ }
597
+ #tag(existing, profile) {
598
+ const { attentionTuning: _previous, ...rest } = existing;
599
+ return { ...rest, ...this.#attention(profile) };
600
+ }
601
+ #profile(scope, goalId, profileId) {
602
+ const row = this.#db.prepare('SELECT profile_json FROM proactive_profiles WHERE scope_json = ? AND goal_id = ? AND profile_id = ?').get(scope, goalId, profileId);
603
+ if (row)
604
+ return validateProfile(JSON.parse(row.profile_json));
605
+ const configured = this.#profiles.get(profileId);
606
+ if (!configured)
607
+ fail('assistant-proactive: unknown profile');
608
+ const prior = this.#db.prepare('SELECT profile_json FROM proactive_profiles WHERE scope_json = ? AND goal_id = ?').all(scope, goalId);
609
+ const bounds = prior.map(item => validateProfile(JSON.parse(item.profile_json)));
610
+ const profile = { ...configured, maxDecisionsPerGoal: Math.min(configured.maxDecisionsPerGoal, ...bounds.map(item => item.maxDecisionsPerGoal)), maxExecutionsPerGoal: Math.min(configured.maxExecutionsPerGoal, ...bounds.map(item => item.maxExecutionsPerGoal)), maxRemindersPerGoal: Math.min(configured.maxRemindersPerGoal, ...bounds.map(item => item.maxRemindersPerGoal)) };
611
+ this.#db.prepare('INSERT INTO proactive_profiles VALUES (?, ?, ?, ?)').run(scope, goalId, profileId, JSON.stringify(profile));
612
+ return profile;
613
+ }
614
+ #parse(value) { try {
615
+ return freeze(JSON.parse(value));
616
+ }
617
+ catch {
618
+ fail('assistant-proactive: corrupt database');
619
+ } }
620
+ #decision(id) { const row = this.#db.prepare('SELECT payload_json FROM proactive_decisions WHERE id = ?').get(id); return row ? this.#parse(row.payload_json) : undefined; }
621
+ #event(scope, input) { const row = this.#db.prepare('SELECT decision_id FROM proactive_events WHERE scope_json = ? AND goal_id = ? AND profile_id = ? AND source_id = ? AND event_sequence = ? AND event_digest = ?').get(scope, input.goalId, input.profileId, input.sourceId, input.event.sequence, input.event.digest); return row ? this.#decision(row.decision_id) : undefined; }
622
+ #sequenceConflict(scope, input) { return this.#db.prepare('SELECT 1 AS found FROM proactive_events WHERE scope_json = ? AND goal_id = ? AND profile_id = ? AND source_id = ? AND event_sequence = ? LIMIT 1').get(scope, input.goalId, input.profileId, input.sourceId, input.event.sequence) !== undefined; }
623
+ #latest(scope, goalId, profileId, sourceId) { const row = this.#db.prepare("SELECT payload_json FROM proactive_decisions WHERE scope_json = ? AND goal_id = ? AND profile_id = ? AND json_extract(payload_json, '$.sourceId') = ? ORDER BY json_extract(payload_json, '$.eventSequence') DESC, json_extract(payload_json, '$.updatedAt') DESC LIMIT 1").get(scope, goalId, profileId, sourceId); return row ? this.#parse(row.payload_json) : undefined; }
624
+ #latestRejected(scope, goalId, profileId) { const row = this.#db.prepare("SELECT payload_json FROM proactive_decisions WHERE scope_json = ? AND goal_id = ? AND profile_id = ? AND json_extract(payload_json, '$.feedback') = 'rejected' ORDER BY json_extract(payload_json, '$.updatedAt') DESC LIMIT 1").get(scope, goalId, profileId); return row ? this.#parse(row.payload_json) : undefined; }
625
+ #counts(scope, goalId) {
626
+ const rows = this.list(JSON.parse(scope), goalId);
627
+ return { ledger: rows.length, executions: rows.filter(value => value.mode === 'execute').length, reminders: rows.filter(value => value.mode === 'remind').length };
628
+ }
629
+ #merge(scope, existing, input, now) {
630
+ const next = input.event.sequence > existing.eventSequence ? freeze({ ...existing, waitId: input.waitId, sessionId: input.sessionId, ownerRouteId: input.ownerRouteId, sourceId: input.sourceId, eventId: input.event.id, eventSequence: input.event.sequence, eventDigest: input.event.digest, eventObservationDigest: input.event.observationDigest, sourceDigest: input.sourceDigest, objective: input.objective, definitionDigest: input.definitionDigest, nativeGoalId: input.nativeGoalId, nativeRevision: input.nativeRevision, updatedAt: now, observations: existing.observations + 1 }) : freeze({ ...existing, updatedAt: now, observations: existing.observations + 1 });
631
+ this.#put(next);
632
+ this.#link(scope, input, next.id);
633
+ return freeze({ disposition: 'defer', decision: next });
634
+ }
635
+ #recentNotifications(scope, now) {
636
+ const windowStart = Math.max(0, now - RECENT_NOTIFICATION_WINDOW_MS);
637
+ const row = this.#db.prepare("SELECT count(*) AS count FROM proactive_decisions WHERE scope_json = ? AND json_extract(payload_json, '$.mode') IN ('remind', 'execute') AND json_extract(payload_json, '$.state') IN ('decided', 'closed') AND json_extract(payload_json, '$.updatedAt') >= ? AND json_extract(payload_json, '$.updatedAt') <= ?").get(scope, windowStart, now);
638
+ return row && Number.isSafeInteger(row.count) && row.count >= 0 ? row.count : 0;
639
+ }
640
+ #acceptanceHistory(scope) {
641
+ const row = this.#db.prepare("SELECT COALESCE(SUM(CASE WHEN json_extract(payload_json, '$.feedback') = 'accepted' THEN 1 ELSE 0 END), 0) AS accepted, COALESCE(SUM(CASE WHEN json_extract(payload_json, '$.feedback') = 'rejected' THEN 1 ELSE 0 END), 0) AS rejected FROM proactive_decisions WHERE scope_json = ? AND json_extract(payload_json, '$.feedback') IN ('accepted', 'rejected')").get(scope);
642
+ return {
643
+ accepted: row && Number.isSafeInteger(row.accepted) && row.accepted >= 0 ? row.accepted : 0,
644
+ rejected: row && Number.isSafeInteger(row.rejected) && row.rejected >= 0 ? row.rejected : 0,
645
+ };
646
+ }
647
+ #dynamicUtility(scope, input, profile, now, context) {
648
+ const ttlDiff = BigInt(input.expiresAt) - BigInt(now);
649
+ const remainingTtlMs = ttlDiff < 0n ? -1 : ttlDiff < BigInt(URGENCY_WINDOW_MS) ? Number(ttlDiff) : undefined;
650
+ const dbRecent = this.#recentNotifications(scope, now);
651
+ const recentNotificationCount = context?.recentNotificationCount !== undefined
652
+ ? Math.max(dbRecent, context.recentNotificationCount)
653
+ : dbRecent;
654
+ const history = this.#acceptanceHistory(scope);
655
+ const overlayInterruptionCostDelta = profile.mode === 'remind' ? (this.#overlay?.parameters.interruptionCostDelta ?? 0) : 0;
656
+ return computeDynamicUtility(profile, {
657
+ ...context,
658
+ recentNotificationCount,
659
+ ...(remainingTtlMs === undefined ? {} : { remainingTtlMs }),
660
+ acceptedCount: history.accepted,
661
+ rejectedCount: history.rejected,
662
+ overlayInterruptionCostDelta,
663
+ }).effectiveUtility;
664
+ }
665
+ #mature(scope, existing, input, profile, now, context) {
666
+ if (now >= input.expiresAt)
667
+ return this.#terminal(existing, 'consume', 'suppress', 'expired', now);
668
+ const rejected = this.#latestRejected(scope, input.goalId, profile.id);
669
+ if (rejected && rejected.id !== existing.id && now < rejected.updatedAt + profile.rejectionCooldownMs)
670
+ return this.#terminal(existing, 'consume', 'suppress', 'rejected-cooldown', now);
671
+ if (this.#muted(profile)) {
672
+ const muted = freeze({ ...this.#tag(existing, profile), state: 'decided', mode: 'suppress', reason: 'attention-muted', updatedAt: now });
673
+ this.#put(muted);
674
+ return freeze({ disposition: 'consume', decision: muted });
675
+ }
676
+ if (quiet(now, profile)) {
677
+ const delayed = freeze({ ...this.#tag(existing, profile), reason: 'quiet-hours', updatedAt: now, eligibleAt: quietEndsAt(now, profile) });
678
+ this.#put(delayed);
679
+ return freeze({ disposition: 'defer', decision: delayed });
680
+ }
681
+ const currentUtility = this.#dynamicUtility(scope, input, profile, now, context);
682
+ if (currentUtility < profile.minimumUtility) {
683
+ const suppressed = freeze({ ...this.#tag(existing, profile), state: 'decided', mode: 'suppress', reason: 'below-threshold', utility: currentUtility, updatedAt: now });
684
+ this.#put(suppressed);
685
+ return freeze({ disposition: 'consume', decision: suppressed });
686
+ }
687
+ const counts = this.#counts(scope, input.goalId);
688
+ const budget = counts.ledger > profile.maxDecisionsPerGoal || profile.mode === 'execute' && counts.executions >= profile.maxExecutionsPerGoal || profile.mode === 'remind' && counts.reminders >= profile.maxRemindersPerGoal;
689
+ // Compare the content of the latest coalesced observation, i.e. what this decision will actually report.
690
+ const observed = { ...this.#tag(existing, profile), ...(input.event.sequence > existing.eventSequence ? { eventId: input.event.id, eventSequence: input.event.sequence, eventDigest: input.event.digest, eventObservationDigest: input.event.observationDigest, observations: existing.observations + 1 } : {}) };
691
+ const unchanged = !budget && profile.mode === 'remind' && this.#unchangedReminder(scope, observed);
692
+ const mode = budget || unchanged ? 'suppress' : profile.mode;
693
+ const reason = budget ? 'budget' : unchanged ? 'unchanged' : profile.mode === 'execute' ? 'execution' : profile.mode === 'remind' ? 'reminder' : 'prepared';
694
+ const next = freeze({ ...observed, mode, state: 'decided', reason, utility: currentUtility, updatedAt: now });
695
+ this.#put(next);
696
+ this.#link(scope, input, next.id);
697
+ if (mode === 'remind')
698
+ this.#remember(scope, next);
699
+ return freeze({ disposition: mode === 'execute' ? 'execute' : 'consume', decision: next });
700
+ }
701
+ #save(scope, input, profile, disposition, mode, reason, now, eligibleAt, evaluatedUtility) {
702
+ if (this.#counts(scope, input.goalId).ledger >= profile.maxDecisionsPerGoal)
703
+ return this.#budgetProjection(input, profile, now, evaluatedUtility);
704
+ const decision = freeze({ id: `opportunity-${randomUUID()}`, waitId: input.waitId, profileId: profile.id, scope: input.scope, goalId: input.goalId, sessionId: input.sessionId, ownerRouteId: input.ownerRouteId, sourceId: input.sourceId, eventId: input.event.id, eventSequence: input.event.sequence, eventDigest: input.event.digest, eventObservationDigest: input.event.observationDigest, sourceDigest: input.sourceDigest, objective: input.objective, definitionDigest: input.definitionDigest, nativeGoalId: input.nativeGoalId, nativeRevision: input.nativeRevision, mode, state: eligibleAt > now ? 'pending' : 'decided', reason, utility: evaluatedUtility, firstObservedAt: now, updatedAt: now, eligibleAt, expiresAt: input.expiresAt, observations: 1, ...this.#attention(profile) });
705
+ this.#put(decision);
706
+ this.#link(scope, input, decision.id);
707
+ if (mode === 'remind')
708
+ this.#remember(scope, decision);
709
+ return freeze({ disposition, decision });
710
+ }
711
+ /**
712
+ * One reminder per goal source until what the owner would read changes or the owner answers it. Durable in
713
+ * the same transaction as the decision, so a restart neither forgets nor re-sends an unchanged reminder.
714
+ */
715
+ #unchangedReminder(scope, value) {
716
+ const row = this.#db.prepare('SELECT content_digest, decision_id FROM proactive_reminders WHERE scope_json = ? AND goal_id = ? AND source_id = ?').get(scope, value.goalId, value.sourceId);
717
+ if (!row || row.content_digest !== reminderContentDigest(value))
718
+ return false;
719
+ return this.#decision(row.decision_id)?.feedback === undefined;
720
+ }
721
+ #remember(scope, decision) {
722
+ this.#db.prepare('INSERT INTO proactive_reminders(scope_json, goal_id, source_id, content_digest, decision_id, queued) VALUES (?, ?, ?, ?, ?, 0) ON CONFLICT(scope_json, goal_id, source_id) DO UPDATE SET content_digest = excluded.content_digest, decision_id = excluded.decision_id, queued = 0').run(scope, decision.goalId, decision.sourceId, reminderContentDigest(decision), decision.id);
723
+ }
724
+ #put(decision) { this.#db.prepare('INSERT INTO proactive_decisions(id, scope_json, goal_id, profile_id, payload_json) VALUES (?, ?, ?, ?, ?) ON CONFLICT(id) DO UPDATE SET payload_json = excluded.payload_json').run(decision.id, scopeKey(decision.scope), decision.goalId, decision.profileId, JSON.stringify(decision)); }
725
+ #link(scope, input, id) { this.#db.prepare('INSERT OR IGNORE INTO proactive_events VALUES (?, ?, ?, ?, ?, ?, ?)').run(scope, input.goalId, input.profileId, input.sourceId, input.event.sequence, input.event.digest, id); }
726
+ #terminal(existing, disposition, mode, reason, now) { const next = freeze({ ...existing, mode, reason, state: 'decided', updatedAt: now }); if (existing.state === 'pending')
727
+ this.#put(next); return freeze({ disposition, decision: next }); }
728
+ #budgetProjection(input, profile, now, evaluatedUtility) { return freeze({ disposition: 'consume', decision: freeze({ id: `opportunity-budget-${input.event.digest}`, waitId: input.waitId, profileId: profile.id, scope: input.scope, goalId: input.goalId, sessionId: input.sessionId, ownerRouteId: input.ownerRouteId, sourceId: input.sourceId, eventId: input.event.id, eventSequence: input.event.sequence, eventDigest: input.event.digest, eventObservationDigest: input.event.observationDigest, sourceDigest: input.sourceDigest, objective: input.objective, definitionDigest: input.definitionDigest, nativeGoalId: input.nativeGoalId, nativeRevision: input.nativeRevision, mode: 'suppress', state: 'decided', reason: 'budget', utility: evaluatedUtility, firstObservedAt: now, updatedAt: now, eligibleAt: now, expiresAt: input.expiresAt, observations: 0 }) }); }
729
+ #sameIdentity(value, input) { return value.waitId === input.waitId && value.sessionId === input.sessionId && value.nativeGoalId === input.nativeGoalId && value.nativeRevision === input.nativeRevision && value.ownerRouteId === input.ownerRouteId && value.sourceId === input.sourceId && value.sourceDigest === input.sourceDigest && value.definitionDigest === input.definitionDigest && value.objective === input.objective && value.expiresAt === input.expiresAt && value.goalId === input.goalId && sameScope(value.scope, input.scope); }
730
+ }
731
+ function sameScope(left, right) { return scopeKey(left) === scopeKey(right); }
732
+ function collectSourceLinks(decisions) {
733
+ const links = [];
734
+ const seen = new Set();
735
+ for (const decision of decisions) {
736
+ const key = `${decision.goalId}\0${decision.sourceId}\0${decision.sourceDigest}\0${decision.definitionDigest}`;
737
+ if (seen.has(key))
738
+ continue;
739
+ seen.add(key);
740
+ links.push({
741
+ scope: decision.scope,
742
+ goalId: decision.goalId,
743
+ waitId: decision.waitId,
744
+ sourceId: decision.sourceId,
745
+ sourceDigest: decision.sourceDigest,
746
+ definitionDigest: decision.definitionDigest,
747
+ nativeGoalId: decision.nativeGoalId,
748
+ nativeRevision: decision.nativeRevision,
749
+ });
750
+ }
751
+ return freeze(links);
752
+ }
753
+ //# sourceMappingURL=engine.js.map