@dsh-ray/assistant-memory-learning 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.
package/lib/runtime.js ADDED
@@ -0,0 +1,682 @@
1
+ import { ScannerOwnerGuard, ScannerOwnerUnavailable } from './scanner-owner-runtime.js';
2
+ import { hasWorkItemLearningFeedbackText, growthObjectDigest, memoryLearningRequestDigest, validateMemoryLearningReviewRequest } from '@dsh-ray/assistant-growth-contract';
3
+ import { validateLearningConfig, validateLearningModel } from './config.js';
4
+ import { LearningStore } from './store.js';
5
+ const OWNER = 'assistant-memory-learning';
6
+ const EXECUTOR = 'assistant-memory-learning-v1';
7
+ const CATALOG = growthObjectDigest({ executor: EXECUTOR, contract: 1 });
8
+ const EVENT_DEBOUNCE_MS = 50;
9
+ const EVENT_DEBOUNCE_MAX_WAIT_MS = 250;
10
+ const FALLBACK_CRON_EXPRESSION = '0 * * * *';
11
+ class SourcePending extends Error {
12
+ }
13
+ class SourceObsolete extends Error {
14
+ }
15
+ const presentationFlags = (task) => ({
16
+ brief: { truncated: task.presentation.brief.truncated, redacted: task.presentation.brief.redacted },
17
+ report: { truncated: task.presentation.report.truncated, redacted: task.presentation.report.redacted },
18
+ feedback: { truncated: task.presentation.feedback.truncated, redacted: task.presentation.feedback.redacted },
19
+ });
20
+ const same = (a, b) => growthObjectDigest(a) === growthObjectDigest(b);
21
+ const reasonText = (value) => Array.from(String(value).normalize('NFC').replaceAll('\0', '').trim())
22
+ .slice(0, 120).join('') || 'learning-incomplete';
23
+ /** Three durable source cursors (work items require explicit opt-in). Native Automations owns every timer and dispatch. */
24
+ export class MemoryLearningRuntime {
25
+ ports;
26
+ config;
27
+ store;
28
+ configDigest;
29
+ lane;
30
+ scanId;
31
+ abort = new AbortController();
32
+ flights = new Set();
33
+ unregister;
34
+ ownerGuard;
35
+ unsubscribeWake;
36
+ eventUnsubscribes = [];
37
+ scanDebounceTimer;
38
+ scanDebounceDeadline = null;
39
+ scanRescanPending = false;
40
+ initialized = false;
41
+ active = false;
42
+ scanning = false;
43
+ lastError = null;
44
+ lastScanAt = null;
45
+ closing;
46
+ constructor(config, ports) {
47
+ this.ports = ports;
48
+ this.config = validateLearningConfig(config);
49
+ this.configDigest = growthObjectDigest(this.config);
50
+ this.lane = growthObjectDigest([this.config.authorityId, this.config.owner]);
51
+ this.scanId = `memory-scan-${this.lane}`;
52
+ this.ownerGuard = new ScannerOwnerGuard(OWNER, this.scanId, this.scope(), ports.delivery, ports.automations, this.config.owner);
53
+ for (const [port, methods] of [
54
+ [ports.delivery, ['inspectOwnerRouteState', 'validateOwnerRoute', 'listOwnerForegroundTaskSources', 'inspectOwnerForegroundTaskSource', 'withOwnerForegroundTaskSourcesFence', 'inspectOwnerForegroundLearningTask']],
55
+ [ports.evaluation, ['canonicalHostScope', 'listTrustedTaskLearningProjections', 'withTrustedCanonicalScopeWriterFence', 'getTrustedForegroundLearningProjection', 'inspectTrustedTaskOwnerRevision']],
56
+ [ports.automations, ['inspectSystemOwnedRetirement', 'retireSystemOwned', 'onSchedulerWake', 'registerHostExecutor', 'reconcileSystem', 'inspectSystemOwnedActivation', 'inspectSystemOwned']],
57
+ [ports.memory, ['listLearningTargets', 'inspectLearningAdoptionAvailability', 'lookupLearningAdoption', 'adoptReviewedLearning']],
58
+ [ports.verifier, ['inspectMemoryLearningReviewAvailability', 'reviewMemoryLearning', 'lookupMemoryLearningReview']],
59
+ [ports.policy, ['evaluate', 'authorize']],
60
+ ])
61
+ for (const method of methods)
62
+ if (typeof port[method] !== 'function')
63
+ throw new Error(`memory learning requires compatible Host API: ${method}`);
64
+ this.store = new LearningStore(this.config.databasePath, { authorityId: this.config.authorityId,
65
+ configDigest: this.configDigest, maxExtractions: this.config.maxExtractions });
66
+ }
67
+ health = () => ({ enabled: true, connected: this.active && !this.ownerGuard.retired, lastScanAt: this.lastScanAt,
68
+ lastError: this.lastError, counts: this.store.counts(this.lane), ...this.store.availability() });
69
+ start() {
70
+ if (this.active || this.closing)
71
+ throw new Error('memory learning runtime cannot be started twice');
72
+ let recoverNativeScanner = false;
73
+ try {
74
+ this.ownerGuard.check();
75
+ }
76
+ catch (error) {
77
+ this.lastError = String(error).slice(0, 200);
78
+ if (this.ownerGuard.retired)
79
+ return;
80
+ recoverNativeScanner = this.ownerGuard.canReconcileScanner;
81
+ }
82
+ try {
83
+ this.unregister = this.ports.automations.registerHostExecutor({
84
+ descriptor: { executorId: EXECUTOR, contractVersion: 1, catalogDigest: CATALOG },
85
+ accepts: spec => spec.executorId === EXECUTOR && spec.executorContractVersion === 1 && spec.catalogDigest === CATALOG
86
+ && spec.runbookVersion === 1 && ['scan', 'learn'].includes(spec.runbookId),
87
+ execute: input => {
88
+ const flight = this.execute(input);
89
+ this.flights.add(flight);
90
+ void flight.finally(() => this.flights.delete(flight)).catch(() => { });
91
+ return flight;
92
+ },
93
+ });
94
+ this.active = true;
95
+ this.unsubscribeWake = this.ports.automations.onSchedulerWake(() => {
96
+ if (!this.active || this.initialized || this.ownerGuard.retired)
97
+ return;
98
+ try {
99
+ this.initializeScanner();
100
+ }
101
+ catch (error) {
102
+ this.lastError = String(error).slice(0, 200);
103
+ }
104
+ });
105
+ if (typeof this.ports.delivery.onForegroundTaskCompletion === 'function') {
106
+ this.eventUnsubscribes.push(this.ports.delivery.onForegroundTaskCompletion(() => { this.scheduleEventScan(); }));
107
+ }
108
+ if (typeof this.ports.evaluation.onTrustedTaskChange === 'function') {
109
+ this.eventUnsubscribes.push(this.ports.evaluation.onTrustedTaskChange(() => { this.scheduleEventScan(); }));
110
+ }
111
+ // One bounded activation reconciliation; subsequent scans are driven by completion events or hourly fallback cron.
112
+ if (recoverNativeScanner) {
113
+ try {
114
+ this.ports.automations.reconcileSystem({ owner: OWNER, automationId: this.scanId,
115
+ idempotencyKey: `${this.scanId}:${this.configDigest}`, desiredStatus: 'active', definition: this.definition() });
116
+ }
117
+ catch (error) {
118
+ this.lastError = String(error).slice(0, 200);
119
+ }
120
+ }
121
+ this.scan();
122
+ }
123
+ catch (error) {
124
+ this.active = false;
125
+ this.cleanupSubscriptions();
126
+ this.abort.abort(error);
127
+ this.store.close();
128
+ throw error;
129
+ }
130
+ }
131
+ clearEventDebounce() {
132
+ if (this.scanDebounceTimer !== undefined) {
133
+ clearTimeout(this.scanDebounceTimer);
134
+ this.scanDebounceTimer = undefined;
135
+ }
136
+ this.scanDebounceDeadline = null;
137
+ this.scanRescanPending = false;
138
+ }
139
+ cleanupSubscriptions() {
140
+ this.clearEventDebounce();
141
+ this.unsubscribeWake?.();
142
+ this.unsubscribeWake = undefined;
143
+ for (const unsubscribe of this.eventUnsubscribes.splice(0)) {
144
+ try {
145
+ unsubscribe();
146
+ }
147
+ catch { /* Best-effort cleanup during shutdown. */ }
148
+ }
149
+ this.unregister?.();
150
+ this.unregister = undefined;
151
+ }
152
+ scheduleEventScan() {
153
+ if (!this.active || this.closing || this.ownerGuard.retired)
154
+ return;
155
+ if (this.scanning) {
156
+ this.scanRescanPending = true;
157
+ return;
158
+ }
159
+ const now = Date.now();
160
+ const deadline = this.scanDebounceDeadline ??= now + EVENT_DEBOUNCE_MAX_WAIT_MS;
161
+ const delay = Math.min(EVENT_DEBOUNCE_MS, Math.max(0, deadline - now));
162
+ if (this.scanDebounceTimer !== undefined)
163
+ clearTimeout(this.scanDebounceTimer);
164
+ this.scanDebounceTimer = setTimeout(() => {
165
+ this.scanDebounceTimer = undefined;
166
+ this.scanDebounceDeadline = null;
167
+ if (!this.active || this.closing || this.ownerGuard.retired)
168
+ return;
169
+ this.scan();
170
+ }, delay);
171
+ this.scanDebounceTimer.unref?.();
172
+ }
173
+ initializeScanner() {
174
+ const owner = this.owner();
175
+ if (!this.initialized) {
176
+ this.store.interrupt(this.lane);
177
+ this.ports.automations.reconcileSystem({ owner: OWNER, automationId: this.scanId,
178
+ idempotencyKey: `${this.scanId}:${this.configDigest}`, desiredStatus: 'active', definition: this.definition() });
179
+ this.initialized = true;
180
+ }
181
+ return owner;
182
+ }
183
+ close() {
184
+ return this.closing ??= (async () => {
185
+ this.active = false;
186
+ this.cleanupSubscriptions();
187
+ this.abort.abort(new Error('memory learning provider disposed'));
188
+ if (!this.ownerGuard.retired && this.initialized)
189
+ this.store.interrupt(this.lane);
190
+ const deadline = AbortSignal.timeout(5000);
191
+ let release;
192
+ const expired = new Promise(resolve => {
193
+ const timeout = () => resolve(false);
194
+ deadline.addEventListener('abort', timeout, { once: true });
195
+ release = () => deadline.removeEventListener('abort', timeout);
196
+ });
197
+ try {
198
+ const drained = await Promise.race([Promise.allSettled(this.flights).then(() => true), expired]);
199
+ if (!drained)
200
+ throw new Error('memory learning shutdown timed out; pending dispatches remain unknown');
201
+ }
202
+ finally {
203
+ release();
204
+ this.store.close();
205
+ }
206
+ })();
207
+ }
208
+ scope() {
209
+ const owner = this.config.owner;
210
+ return { authorityId: owner.authorityId, principalId: owner.principalId, workspace: owner.workspace,
211
+ agentPreset: owner.agentPreset, expectedOwner: { authorityHash: owner.authorityHash,
212
+ principalRecordId: owner.principalRecordId, principalVersion: owner.principalVersion } };
213
+ }
214
+ owner() {
215
+ if (!this.active)
216
+ throw new Error('memory learning unavailable');
217
+ this.ownerGuard.check();
218
+ const current = this.ports.delivery.validateOwnerRoute(this.scope());
219
+ for (const key of Object.keys(this.config.owner)) {
220
+ if (current[key] !== this.config.owner[key])
221
+ throw new Error('memory learning owner authority changed');
222
+ }
223
+ }
224
+ policy(consume = false, idempotencyKey) {
225
+ const owner = this.config.owner;
226
+ const input = { subject: { kind: 'background', id: OWNER, workspace: owner.workspace, principal: owner.principalId },
227
+ action: 'extract', resource: { kind: 'memory', id: `learning:${this.config.authorityId}` }, context: { initiator: 'background' } };
228
+ const decision = consume ? this.ports.policy.authorize(input, idempotencyKey === undefined ? {} : { idempotencyKey }) : this.ports.policy.evaluate(input);
229
+ if (decision.effect !== 'allow')
230
+ throw new Error('memory learning extraction policy denied');
231
+ }
232
+ available(workItem = false, claimed = false) {
233
+ this.owner();
234
+ this.policy();
235
+ const review = this.ports.verifier.inspectMemoryLearningReviewAvailability({ owner: this.config.owner });
236
+ const memory = this.ports.memory.inspectLearningAdoptionAvailability({ owner: this.config.owner });
237
+ return Date.now() < this.config.expiresAt && (claimed || this.store.availability().available) && review?.available === true
238
+ && review.authorityId === this.config.reviewAuthorityId && review.authorityDigest === this.config.reviewAuthorityDigest
239
+ && (!workItem || review.workItemExperiences === true && memory.workItemExperiences === true)
240
+ && memory.available && memory.authorityId === this.config.adoptionAuthorityId && memory.grantDigest === this.config.adoptionGrantDigest;
241
+ }
242
+ evaluationFence(callback) {
243
+ const owner = this.config.owner;
244
+ const scope = this.ports.evaluation.canonicalHostScope({ workspace: owner.workspace, preset: owner.agentPreset });
245
+ const { scopeWatermark } = this.ports.evaluation.listTrustedTaskLearningProjections({ scope, limit: 1 });
246
+ const result = this.ports.evaluation.withTrustedCanonicalScopeWriterFence({ scope, scopeWatermark }, callback);
247
+ if (!result.matched)
248
+ throw new SourcePending('canonical scope changed during read');
249
+ return result.value;
250
+ }
251
+ withWorkItemSource(job, callback) {
252
+ this.abort.signal.throwIfAborted();
253
+ this.owner();
254
+ this.policy();
255
+ const intent = job.intent;
256
+ if (intent.sourceKind !== 'work-item' || !this.config.workItemExperiences
257
+ || intent.configDigest !== this.configDigest || !same(intent.owner, this.config.owner)
258
+ || Date.now() >= Math.min(intent.expiresAt, this.config.expiresAt))
259
+ throw new SourceObsolete('work-item learning authority expired');
260
+ const owner = this.config.owner;
261
+ const scope = this.ports.evaluation.canonicalHostScope({ workspace: owner.workspace, preset: owner.agentPreset });
262
+ const current = this.ports.evaluation.getTrustedWorkItemLearningProjection({ scope, itemId: intent.itemId });
263
+ const expected = intent.canonical;
264
+ if (!current || current.projection.disposition !== 'upsert' || current.objective?.outcomeId !== expected.outcomeId
265
+ || current.projection.version !== expected.version || current.projection.digest !== expected.digest
266
+ || current.objective.status !== expected.objectiveStatus)
267
+ throw new SourceObsolete('work-item canonical result changed');
268
+ const task = this.ports.delivery.inspectOwnerWorkItemLearningTask?.({ ...this.scope(), outcomeId: expected.outcomeId });
269
+ if (!task || !this.ports.delivery.withOwnerWorkItemLearningTaskFence)
270
+ throw new SourcePending('work-item reader temporarily unavailable');
271
+ const check = (value) => {
272
+ if (value.proofIdentity.itemId !== intent.itemId || value.canonical.objective?.outcomeId !== expected.outcomeId
273
+ || value.canonical.projection.version !== expected.version || value.canonical.projection.digest !== expected.digest
274
+ || value.canonical.objective.status !== expected.objectiveStatus
275
+ || value.owner.authorityHash !== owner.authorityHash || value.owner.principalRecordId !== owner.principalRecordId
276
+ || value.owner.principalVersion !== owner.principalVersion)
277
+ throw new SourceObsolete('work-item source changed');
278
+ if (Object.values(value.presentation).some(part => part.truncated))
279
+ throw new SourceObsolete('work-item presentation exceeds text boundary');
280
+ if (!hasWorkItemLearningFeedbackText(value.presentation.feedback.text))
281
+ throw new SourceObsolete('work-item owner feedback has no visible text');
282
+ if (job.snapshot && (job.snapshot.sourceKind !== 'work-item'
283
+ || value.sourceDigest !== job.snapshot.source.sourceDigest || value.presentationDigest !== job.snapshot.source.contentDigest
284
+ || value.presentation.brief.text !== job.snapshot.taskBrief || value.presentation.report.text !== job.snapshot.workerReport
285
+ || value.presentation.feedback.text !== job.snapshot.ownerFeedback
286
+ || !same(presentationFlags(value), job.snapshot.presentationFlags)
287
+ || !same(this.config.model ?? value.proofIdentity.supplier, job.snapshot.model)))
288
+ throw new SourceObsolete('frozen work-item source changed');
289
+ return callback(value);
290
+ };
291
+ return this.ports.delivery.withOwnerWorkItemLearningTaskFence({ ...this.scope(), itemId: intent.itemId,
292
+ outcomeId: expected.outcomeId, expectedSourceDigest: task.sourceDigest, expectedContentDigest: task.presentationDigest,
293
+ canonical: { version: expected.version, digest: expected.digest, objectiveStatus: expected.objectiveStatus } }, check);
294
+ }
295
+ withCurrentSource(job, callback) {
296
+ return job.intent.sourceKind === 'work-item' ? this.withWorkItemSource(job, callback) : this.withSource(job, callback);
297
+ }
298
+ withSource(job, callback) {
299
+ if (job.intent.sourceKind === 'work-item')
300
+ throw new Error('foreground source required');
301
+ this.abort.signal.throwIfAborted();
302
+ this.owner();
303
+ this.policy();
304
+ if (job.intent.configDigest !== this.configDigest || !same(job.intent.owner, this.config.owner)
305
+ || Date.now() >= Math.min(job.intent.expiresAt, this.config.expiresAt))
306
+ throw new SourceObsolete('learning authority or source window expired');
307
+ const metadata = this.ports.delivery.inspectOwnerForegroundTaskSource({ ...this.scope(), inboxId: job.intent.inboxId });
308
+ if (!metadata)
309
+ throw new SourcePending('completed source unavailable');
310
+ if (job.intent.expectedSourceDigest && metadata.sourceDigest !== job.intent.expectedSourceDigest
311
+ || job.snapshot && metadata.sourceDigest !== job.snapshot.source.sourceDigest
312
+ || metadata.execution.status !== 'succeeded' || !metadata.execution.quiescent
313
+ || metadata.execution.modelSelectionState !== 'frozen' || !metadata.execution.modelSelection)
314
+ throw new SourceObsolete('source completion or model changed');
315
+ return this.ports.delivery.withOwnerForegroundTaskSourcesFence({ ...this.scope(),
316
+ sources: [{ inboxId: metadata.inboxId, expectedSourceDigest: metadata.sourceDigest }] }, contents => this.evaluationFence(() => {
317
+ const owner = this.config.owner;
318
+ const scope = this.ports.evaluation.canonicalHostScope({ workspace: owner.workspace, preset: owner.agentPreset });
319
+ const canonical = this.ports.evaluation.getTrustedForegroundLearningProjection({ scope, inboxId: job.intent.inboxId });
320
+ const revision = canonical && this.ports.evaluation.inspectTrustedTaskOwnerRevision({ scope, outcomeId: canonical.triggerOutcomeId,
321
+ principalRecordId: owner.principalRecordId, principalVersion: owner.principalVersion });
322
+ if (revision?.action === 'withdraw')
323
+ throw new SourceObsolete('owner withdrew learning source');
324
+ const content = contents[0];
325
+ if (!content)
326
+ throw new SourcePending('original reply not yet readable');
327
+ if (content.input.truncated || content.reply.truncated)
328
+ throw new SourceObsolete('learning source exceeds text boundary');
329
+ let feedback;
330
+ if (job.intent.canonical) {
331
+ const expected = job.intent.canonical;
332
+ if (!canonical || canonical.projection.disposition !== 'upsert' || canonical.projection.version !== expected.version
333
+ || canonical.projection.digest !== expected.digest || canonical.objective?.status !== expected.objectiveStatus)
334
+ throw new SourceObsolete('canonical result changed');
335
+ const task = this.ports.delivery.inspectOwnerForegroundLearningTask({ authorityId: owner.authorityId, principalId: owner.principalId,
336
+ workspace: owner.workspace, agentPreset: owner.agentPreset, outcomeId: expected.outcomeId });
337
+ if (!task || task.judgement === 'unresolved' || !task.source.quiescent || task.source.truncated || task.feedback?.truncated)
338
+ throw new SourcePending('canonical owner source not yet readable');
339
+ if (task.source.inboxId !== job.intent.inboxId || task.ownerRevision?.action === 'withdraw'
340
+ || task.canonical.projection.version !== expected.version || task.canonical.projection.digest !== expected.digest
341
+ || task.canonical.objective?.status !== expected.objectiveStatus
342
+ || task.owner.authorityHash !== owner.authorityHash || task.owner.principalRecordId !== owner.principalRecordId
343
+ || task.owner.principalVersion !== owner.principalVersion)
344
+ throw new SourceObsolete('canonical source owner changed');
345
+ feedback = task.feedback?.text;
346
+ }
347
+ if (job.snapshot && (content.contentDigest !== job.snapshot.source.contentDigest
348
+ || content.input.text !== job.snapshot.ownerStatement || content.reply.text !== job.snapshot.assistantReply
349
+ || feedback !== job.snapshot.ownerFeedback
350
+ || !same(this.config.model ?? content.source.execution.modelSelection, job.snapshot.model)))
351
+ throw new SourceObsolete('frozen learning inputs changed');
352
+ return callback(content, feedback);
353
+ }));
354
+ }
355
+ scan = () => {
356
+ if (!this.active || this.scanning)
357
+ return;
358
+ this.scanning = true;
359
+ try {
360
+ this.lastError = null;
361
+ this.initializeScanner();
362
+ // Lost acknowledgements reconcile before admitting more paid work.
363
+ for (const job of this.store.pending(this.lane))
364
+ if (job.state === 'unknown') {
365
+ if (job.request)
366
+ this.reconcile(job);
367
+ // A durable request is always saved before any review/adoption call.
368
+ // No request proves that no memory mutation was dispatched. The paid
369
+ // extraction attempt remains consumed and is never retried.
370
+ else
371
+ this.store.settle(job.id, 'failed', 'interrupted-extraction-no-mutation-dispatched');
372
+ }
373
+ if (!this.available()) {
374
+ this.lastError = 'learning-authority-or-budget-unavailable';
375
+ return;
376
+ }
377
+ const owner = this.config.owner;
378
+ let stopped = false;
379
+ for (let pageNumber = 0; pageNumber < 10 && !stopped; pageNumber++) {
380
+ const after = this.store.cursor(this.lane, 'delivery');
381
+ const page = this.ports.delivery.listOwnerForegroundTaskSources({ ...this.scope(), ...(after ? { after } : {}), limit: 100 });
382
+ for (const source of page.items) {
383
+ const now = Date.now(), at = source.execution.completedAt ?? 0;
384
+ const eligible = source.execution.status === 'succeeded' && source.execution.quiescent && at <= now
385
+ && now - at <= this.config.lookbackMs && source.execution.modelSelectionState === 'frozen';
386
+ const intent = eligible ? { configDigest: this.configDigest, owner, kind: 'fact', subject: source.inboxId,
387
+ inboxId: source.inboxId, expectedSourceDigest: source.sourceDigest, createdAt: now,
388
+ expiresAt: Math.min(this.config.expiresAt, now + this.config.lookbackMs) } : undefined;
389
+ if (!this.store.stage({ lane: this.lane, feed: 'delivery', cursor: { ...page.nextCursor, sequence: source.completionSequence },
390
+ sequence: source.completionSequence, subject: source.inboxId, ...(intent ? { intent } : {}), maxPending: this.config.maxPending })) {
391
+ stopped = true;
392
+ break;
393
+ }
394
+ }
395
+ if (!stopped)
396
+ this.store.stage({ lane: this.lane, feed: 'delivery', cursor: page.nextCursor, sequence: page.nextCursor.sequence,
397
+ subject: 'cursor:delivery', maxPending: this.config.maxPending });
398
+ if (!page.hasMore)
399
+ break;
400
+ }
401
+ const scope = this.ports.evaluation.canonicalHostScope({ workspace: owner.workspace, preset: owner.agentPreset });
402
+ stopped = false;
403
+ for (let pageNumber = 0; pageNumber < 10 && !stopped; pageNumber++) {
404
+ const after = this.store.cursor(this.lane, 'evaluation');
405
+ const page = this.ports.evaluation.listTrustedTaskLearningProjections({ scope, ...(after ? { after } : {}), limit: 100 });
406
+ for (const item of page.items) {
407
+ const canonical = item.receipt, now = Date.now(), at = canonical.objective?.occurredAt ?? 0;
408
+ const foreground = canonical.projection.subjectKind === 'foreground-turn';
409
+ const status = canonical.objective?.status;
410
+ const eligible = foreground && canonical.projection.disposition === 'upsert' && (status === 'achieved' || status === 'not-achieved')
411
+ && at <= now && now - at <= this.config.lookbackMs;
412
+ const intent = eligible ? { configDigest: this.configDigest, owner, kind: 'experience',
413
+ subject: canonical.projection.subjectRef, inboxId: canonical.projection.subjectRef,
414
+ canonical: { outcomeId: canonical.triggerOutcomeId, version: canonical.projection.version,
415
+ digest: canonical.projection.digest, objectiveStatus: status }, createdAt: now,
416
+ expiresAt: Math.min(this.config.expiresAt, now + this.config.lookbackMs) } : undefined;
417
+ // No Delivery or Memory calls under this Evaluation lock.
418
+ const result = this.ports.evaluation.withTrustedCanonicalScopeWriterFence({ scope, scopeWatermark: page.scopeWatermark }, () => this.store.stage({ lane: this.lane, feed: 'evaluation', cursor: { scopeKey: page.nextCursor.scopeKey, watermark: item.watermark },
419
+ sequence: item.watermark, subject: canonical.projection.subjectRef, ...(intent ? { intent } : {}),
420
+ maxPending: this.config.maxPending, supersede: foreground }));
421
+ if (!result.matched || !result.value) {
422
+ stopped = true;
423
+ break;
424
+ }
425
+ }
426
+ if (!page.hasMore)
427
+ break;
428
+ }
429
+ if (this.config.workItemExperiences) {
430
+ stopped = false;
431
+ for (let pageNumber = 0; pageNumber < 10 && !stopped; pageNumber++) {
432
+ const after = this.store.cursor(this.lane, 'evaluation-work-items');
433
+ const page = this.ports.evaluation.listTrustedTaskLearningProjections({ scope, ...(after ? { after } : {}), limit: 100 });
434
+ for (const item of page.items) {
435
+ const canonical = item.receipt, now = Date.now(), at = canonical.objective?.occurredAt ?? 0;
436
+ const workItem = canonical.projection.subjectKind === 'work-item';
437
+ const status = canonical.objective?.status;
438
+ const eligible = workItem && canonical.projection.disposition === 'upsert' && (status === 'achieved' || status === 'not-achieved')
439
+ && at <= now && now - at <= this.config.lookbackMs;
440
+ const subject = workItem ? `work-item:${canonical.projection.subjectRef}` : 'cursor:work-items';
441
+ const intent = eligible ? { configDigest: this.configDigest, owner, kind: 'experience',
442
+ sourceKind: 'work-item', itemId: canonical.projection.subjectRef, subject,
443
+ canonical: { outcomeId: canonical.objective.outcomeId, version: canonical.projection.version,
444
+ digest: canonical.projection.digest, objectiveStatus: status }, createdAt: now,
445
+ expiresAt: Math.min(this.config.expiresAt, now + this.config.lookbackMs) } : undefined;
446
+ const result = this.ports.evaluation.withTrustedCanonicalScopeWriterFence({ scope, scopeWatermark: page.scopeWatermark }, () => this.store.stage({ lane: this.lane, feed: 'evaluation-work-items', cursor: { scopeKey: page.nextCursor.scopeKey, watermark: item.watermark },
447
+ sequence: item.watermark, subject, ...(intent ? { intent } : {}), maxPending: this.config.maxPending, supersede: workItem }));
448
+ if (!result.matched || !result.value) {
449
+ stopped = true;
450
+ break;
451
+ }
452
+ }
453
+ if (!page.hasMore)
454
+ break;
455
+ }
456
+ }
457
+ for (const pending of this.store.pending(this.lane)) {
458
+ if (pending.state !== 'pending' && pending.state !== 'queued')
459
+ continue;
460
+ try {
461
+ let job = pending;
462
+ if (job.state === 'pending') {
463
+ // Each API owns its own producer locks; do not nest target discovery.
464
+ const targets = this.ports.memory.listLearningTargets({ owner, limit: 20 });
465
+ if (job.intent.sourceKind === 'work-item') {
466
+ if (!this.available(true))
467
+ continue;
468
+ job = this.withWorkItemSource(job, task => this.store.freeze(job.id, {
469
+ sourceKind: 'work-item', presentationFlags: presentationFlags(task), model: validateLearningModel(this.config.model ?? task.proofIdentity.supplier),
470
+ source: { protocol: 'memory-learning-source/work-item/v1', itemId: task.proofIdentity.itemId,
471
+ sourceDigest: task.sourceDigest, contentDigest: task.presentationDigest, canonical: job.intent.canonical },
472
+ taskBrief: task.presentation.brief.text, workerReport: task.presentation.report.text,
473
+ ownerFeedback: task.presentation.feedback.text, targets: targets.filter(target => target.kind === 'experience'),
474
+ }));
475
+ }
476
+ else
477
+ job = this.withSource(job, (content, feedback) => this.store.freeze(job.id, {
478
+ model: validateLearningModel(this.config.model ?? content.source.execution.modelSelection),
479
+ source: { inboxId: content.source.inboxId, sourceDigest: content.sourceDigest, contentDigest: content.contentDigest,
480
+ ...(job.intent.canonical ? { canonical: job.intent.canonical } : {}) },
481
+ ownerStatement: content.input.text, assistantReply: content.reply.text,
482
+ ...(feedback === undefined ? {} : { ownerFeedback: feedback }), targets,
483
+ }));
484
+ }
485
+ if (job.intent.sourceKind === 'work-item') {
486
+ this.withCurrentSource(job, () => undefined);
487
+ this.schedule(job);
488
+ }
489
+ else
490
+ this.withCurrentSource(job, () => this.schedule(job));
491
+ }
492
+ catch (error) {
493
+ if (error instanceof ScannerOwnerUnavailable)
494
+ throw error;
495
+ if (error instanceof SourceObsolete)
496
+ this.store.settle(pending.id, 'superseded', reasonText(error.message));
497
+ // Missing source/provider/scheduling readiness keeps the same durable intent.
498
+ else if (!(error instanceof SourcePending))
499
+ this.lastError = String(error).slice(0, 200);
500
+ }
501
+ }
502
+ this.lastScanAt = Date.now();
503
+ if (this.lastError === 'learning-authority-or-budget-unavailable')
504
+ this.lastError = null;
505
+ }
506
+ catch (error) {
507
+ this.lastError = String(error).slice(0, 200);
508
+ }
509
+ finally {
510
+ this.scanning = false;
511
+ if (this.scanRescanPending && this.active && !this.closing && !this.ownerGuard.retired) {
512
+ this.scanRescanPending = false;
513
+ this.scheduleEventScan();
514
+ }
515
+ }
516
+ };
517
+ definition(job) {
518
+ const owner = this.config.owner;
519
+ return { name: job ? 'Learn from an ordinary owner task' : 'Discover ordinary owner learning',
520
+ schedule: job ? { kind: 'at', at: new Date(job.intent.createdAt + 1000).toISOString() }
521
+ : { kind: 'cron', expression: FALLBACK_CRON_EXPRESSION, timezone: 'UTC' }, workspace: owner.workspace, agentPreset: owner.agentPreset,
522
+ timeoutMs: job ? this.config.timeoutMs + 310_000 : 30_000, misfire: { kind: 'latest' }, overlap: 'skip',
523
+ retrySafety: 'never', maxRetries: 0, principal: owner.principalId,
524
+ budgetId: job ? this.config.budgetId : this.config.scanBudgetId,
525
+ budgetAmount: job ? this.config.budgetAmount : this.config.scanBudgetAmount,
526
+ execution: { kind: 'host', executorId: EXECUTOR, executorContractVersion: 1, runbookId: job ? 'learn' : 'scan',
527
+ runbookVersion: 1, catalogDigest: CATALOG, targetScope: { workspace: owner.workspace, preset: owner.agentPreset },
528
+ scopeDigest: growthObjectDigest([owner.workspace, owner.agentPreset]), ownerRouteId: owner.authorityId,
529
+ activationNonce: job?.digest ?? this.configDigest } };
530
+ }
531
+ schedule(input) {
532
+ let job = input;
533
+ const definition = this.definition(job);
534
+ if (job.definitionHash === null) {
535
+ this.ports.automations.reconcileSystem({ owner: OWNER, automationId: job.id,
536
+ idempotencyKey: `${job.id}:prepare`, desiredStatus: 'paused', definition });
537
+ const receipt = this.ports.automations.inspectSystemOwnedActivation({ owner: OWNER, automationId: job.id });
538
+ if (!receipt || receipt.activationNonce !== job.digest || receipt.ownerRouteId !== this.config.owner.authorityId)
539
+ throw new Error('learning registration mismatch');
540
+ job = this.store.bind(job.id, receipt.definitionHash);
541
+ }
542
+ const receipt = this.ports.automations.inspectSystemOwnedActivation({ owner: OWNER, automationId: job.id });
543
+ if (!receipt || receipt.definitionHash !== job.definitionHash || receipt.activationNonce !== job.digest)
544
+ throw new Error('learning definition changed');
545
+ const terminal = this.ports.automations.inspectSystemOwned({ owner: OWNER, automationId: job.id }).latestTerminalRuns.production;
546
+ if (terminal && terminal.immutableContext.state === 'verified' && terminal.immutableContext.definitionHash === job.definitionHash) {
547
+ this.store.settle(job.id, 'failed', 'native-run-ended-before-claim');
548
+ return;
549
+ }
550
+ this.ports.automations.reconcileSystem({ owner: OWNER, automationId: job.id,
551
+ idempotencyKey: `${job.id}:activate`, desiredStatus: 'active', definition });
552
+ }
553
+ reviewMatches(job, receipt) {
554
+ return receipt.operationId === job.request.operationId && receipt.requestDigest === memoryLearningRequestDigest(job.request)
555
+ && receipt.authorityId === this.config.reviewAuthorityId && receipt.authorityDigest === this.config.reviewAuthorityDigest
556
+ && receipt.sessionId !== job.request.extractionSessionId;
557
+ }
558
+ reconcile(job) {
559
+ try {
560
+ this.owner();
561
+ const prior = this.ports.memory.lookupLearningAdoption({ request: job.request });
562
+ if (prior) {
563
+ this.store.settle(job.id, 'adopted', 'reconciled-original-adoption', prior.receiptDigest);
564
+ return;
565
+ }
566
+ const review = this.ports.verifier.lookupMemoryLearningReview(job.request);
567
+ if (!review || !this.reviewMatches(job, review) || review.status === 'unknown')
568
+ return;
569
+ if (review.status === 'rejected')
570
+ this.store.settle(job.id, 'rejected', reasonText(review.reason), review.receiptDigest);
571
+ else {
572
+ // Lookup completed outside producer locks. Memory owns its adoption locks.
573
+ this.withCurrentSource(job, () => undefined);
574
+ const adopted = this.ports.memory.adoptReviewedLearning({ request: job.request });
575
+ this.store.settle(job.id, 'adopted', 'reconciled-approved-adoption', adopted.receiptDigest);
576
+ }
577
+ }
578
+ catch {
579
+ // A canonical change cannot prove that the original operation did not
580
+ // commit. Keep every saved unknown request queryable until an original
581
+ // receipt or explicit terminal review settles it; never replay paid calls.
582
+ }
583
+ }
584
+ async execute(input) {
585
+ const result = (outcome) => ({ outcome,
586
+ failureClass: outcome === 'succeeded' ? 'none' : outcome === 'unknown' ? 'unknown' : 'configuration',
587
+ failurePhase: outcome === 'succeeded' ? 'none' : 'host-execution', failureCode: outcome === 'succeeded' ? 'none' : 'memory-learning-incomplete',
588
+ sideEffectState: outcome === 'succeeded' ? 'possible' : outcome === 'unknown' ? 'unknown' : 'none',
589
+ retryability: outcome === 'failed' ? 'after-intervention' : 'unsafe' });
590
+ let claimed;
591
+ try {
592
+ this.owner();
593
+ this.abort.signal.throwIfAborted();
594
+ input.signal.throwIfAborted();
595
+ const owner = this.config.owner;
596
+ if (input.executionMode !== 'production' || input.catalogDigest !== CATALOG || input.ownerRouteId !== owner.authorityId
597
+ || input.principal !== owner.principalId || input.targetScope.workspace !== owner.workspace
598
+ || input.targetScope.preset !== owner.agentPreset)
599
+ throw new Error('learning dispatch scope mismatch');
600
+ const activation = this.ports.automations.inspectSystemOwnedActivation({ owner: OWNER, automationId: input.automationId });
601
+ if (!activation || activation.definitionHash !== input.definitionHash || activation.activationNonce !== input.activationNonce)
602
+ throw new Error('learning activation changed');
603
+ if (input.automationId === this.scanId) {
604
+ if (input.activationNonce !== this.configDigest)
605
+ throw new Error('learning scanner configuration changed');
606
+ this.scan();
607
+ return result(this.lastError === null ? 'succeeded' : 'failed');
608
+ }
609
+ const queued = this.store.get(input.automationId);
610
+ if (!queued || queued.state !== 'queued' || !queued.snapshot || queued.digest !== input.activationNonce
611
+ || queued.definitionHash !== input.definitionHash || !this.available(queued.intent.sourceKind === 'work-item'))
612
+ throw new Error('learning job is not admissible');
613
+ this.withCurrentSource(queued, () => { claimed = this.store.claim(queued.id, input.definitionHash, input.occurrenceId); });
614
+ const job = claimed;
615
+ const signal = AbortSignal.any([input.signal, this.abort.signal, AbortSignal.timeout(Math.max(1, Math.min(this.config.timeoutMs + 310_000, job.intent.expiresAt - Date.now(), this.config.expiresAt - Date.now())))]);
616
+ const assertCurrent = () => {
617
+ signal.throwIfAborted();
618
+ const current = this.store.get(job.id);
619
+ if (!current || current.state !== 'running' || current.occurrenceId !== input.occurrenceId)
620
+ throw new Error('learning claim superseded');
621
+ this.withCurrentSource(job, () => undefined);
622
+ };
623
+ assertCurrent();
624
+ this.policy(true, `memory-extract:${this.config.authorityId}:${job.id}`);
625
+ const extractionSignal = AbortSignal.any([signal, AbortSignal.timeout(this.config.timeoutMs)]);
626
+ if (job.intent.sourceKind === 'work-item' && !this.available(true, true))
627
+ throw new Error('work-item learning capabilities unavailable before extraction');
628
+ const extraction = await this.ports.extract({ config: this.config, job, signal: extractionSignal, assertCurrent });
629
+ assertCurrent();
630
+ if (!extraction.proposal) {
631
+ this.store.settle(job.id, 'noop', reasonText(extraction.reason), extraction.outputDigest, input.occurrenceId);
632
+ return result('succeeded');
633
+ }
634
+ const proposal = extraction.proposal;
635
+ const quoteSources = job.snapshot.sourceKind === 'work-item' ? [job.snapshot.ownerFeedback]
636
+ : [job.snapshot.ownerStatement, job.snapshot.ownerFeedback ?? ''];
637
+ if (job.snapshot.sourceKind === 'work-item' && !hasWorkItemLearningFeedbackText(proposal.evidenceQuote))
638
+ throw new Error('work-item quotation has no visible text');
639
+ if (!quoteSources.some(text => text.includes(proposal.evidenceQuote)))
640
+ throw new Error('learning quotation is not an owner source');
641
+ if (proposal.mutation.op !== 'remove' && proposal.mutation.entry.kind !== job.intent.kind)
642
+ throw new Error('learning kind changed');
643
+ const mutation = proposal.mutation;
644
+ if (mutation.op !== 'add' && !job.snapshot.targets.some(target => target.id === mutation.id && target.version === mutation.expectedVersion && target.kind === job.intent.kind))
645
+ throw new Error('learning target not in frozen managed set');
646
+ const request = validateMemoryLearningReviewRequest({ protocol: job.intent.sourceKind === 'work-item' ? 'memory-learning-review/v2' : 'memory-learning-review/v1',
647
+ operationId: job.id, extractionSessionId: extraction.sessionId,
648
+ owner, source: job.snapshot.source, ...proposal });
649
+ const saved = this.store.saveRequest(job.id, input.occurrenceId, request);
650
+ const review = await this.ports.verifier.reviewMemoryLearning(request, signal);
651
+ assertCurrent();
652
+ if (!this.reviewMatches(saved, review) || review.status === 'unknown') {
653
+ this.store.settle(job.id, 'unknown', 'independent-review-unresolved', undefined, input.occurrenceId);
654
+ return result('unknown');
655
+ }
656
+ if (review.status === 'rejected') {
657
+ this.store.settle(job.id, 'rejected', reasonText(review.reason), review.receiptDigest, input.occurrenceId);
658
+ return result('succeeded');
659
+ }
660
+ assertCurrent();
661
+ const adopted = this.ports.memory.adoptReviewedLearning({ request });
662
+ this.store.settle(job.id, 'adopted', 'independently-reviewed-and-adopted', adopted.receiptDigest, input.occurrenceId);
663
+ return result('succeeded');
664
+ }
665
+ catch (error) {
666
+ if (!this.active || this.abort.signal.aborted)
667
+ return result(claimed ? 'unknown' : 'failed');
668
+ if (claimed) {
669
+ const current = this.store.get(claimed.id);
670
+ if (current?.state === 'running' && current.occurrenceId === input.occurrenceId) {
671
+ this.store.settle(claimed.id, current.request ? 'unknown' : 'failed', reasonText(error), undefined, input.occurrenceId);
672
+ }
673
+ }
674
+ return result(claimed ? 'unknown' : 'failed');
675
+ }
676
+ finally {
677
+ if (this.active)
678
+ this.scan();
679
+ }
680
+ }
681
+ }
682
+ //# sourceMappingURL=runtime.js.map