@dsh-ray/assistant-growth-driver 0.0.1-seed.0 → 0.2.1

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 (60) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +321 -1
  3. package/cordis.patch.yml +3 -0
  4. package/lib/association-intake.d.ts +55 -0
  5. package/lib/association-intake.d.ts.map +1 -0
  6. package/lib/association-intake.js +253 -0
  7. package/lib/association-intake.js.map +1 -0
  8. package/lib/config.d.ts +171 -0
  9. package/lib/config.d.ts.map +1 -0
  10. package/lib/config.js +401 -0
  11. package/lib/config.js.map +1 -0
  12. package/lib/deposit.d.ts +53 -0
  13. package/lib/deposit.d.ts.map +1 -0
  14. package/lib/deposit.js +56 -0
  15. package/lib/deposit.js.map +1 -0
  16. package/lib/dreaming-intake.d.ts +37 -0
  17. package/lib/dreaming-intake.d.ts.map +1 -0
  18. package/lib/dreaming-intake.js +180 -0
  19. package/lib/dreaming-intake.js.map +1 -0
  20. package/lib/growth-agent.d.ts +193 -0
  21. package/lib/growth-agent.d.ts.map +1 -0
  22. package/lib/growth-agent.js +1633 -0
  23. package/lib/growth-agent.js.map +1 -0
  24. package/lib/index.d.ts +79 -0
  25. package/lib/index.d.ts.map +1 -0
  26. package/lib/index.js +662 -0
  27. package/lib/index.js.map +1 -0
  28. package/lib/revision-target-matcher.d.ts +23 -0
  29. package/lib/revision-target-matcher.d.ts.map +1 -0
  30. package/lib/revision-target-matcher.js +51 -0
  31. package/lib/revision-target-matcher.js.map +1 -0
  32. package/lib/scanner-owner-runtime.d.ts +34 -0
  33. package/lib/scanner-owner-runtime.d.ts.map +1 -0
  34. package/lib/scanner-owner-runtime.js +99 -0
  35. package/lib/scanner-owner-runtime.js.map +1 -0
  36. package/lib/source-edits.d.ts +22 -0
  37. package/lib/source-edits.d.ts.map +1 -0
  38. package/lib/source-edits.js +77 -0
  39. package/lib/source-edits.js.map +1 -0
  40. package/lib/source-port.d.ts +223 -0
  41. package/lib/source-port.d.ts.map +1 -0
  42. package/lib/source-port.js +8 -0
  43. package/lib/source-port.js.map +1 -0
  44. package/lib/usage-runtime.d.ts +116 -0
  45. package/lib/usage-runtime.d.ts.map +1 -0
  46. package/lib/usage-runtime.js +853 -0
  47. package/lib/usage-runtime.js.map +1 -0
  48. package/lib/usage-store.d.ts +119 -0
  49. package/lib/usage-store.d.ts.map +1 -0
  50. package/lib/usage-store.js +343 -0
  51. package/lib/usage-store.js.map +1 -0
  52. package/lib/version.d.ts +2 -0
  53. package/lib/version.d.ts.map +1 -0
  54. package/lib/version.js +2 -0
  55. package/lib/version.js.map +1 -0
  56. package/lib/work-item-source.d.ts +63 -0
  57. package/lib/work-item-source.d.ts.map +1 -0
  58. package/lib/work-item-source.js +126 -0
  59. package/lib/work-item-source.js.map +1 -0
  60. package/package.json +146 -4
@@ -0,0 +1,853 @@
1
+ import { ScannerOwnerGuard, ScannerOwnerUnavailable, drainScannerFlights } from './scanner-owner-runtime.js';
2
+ import { acceptanceDigest } from '@dsh-ray/task-acceptance-contract';
3
+ import { SourceGrowthRunUnavailableError, isSourceOwnerContinuation, sourceGrowthEvidenceDigest, sourceGrowthRunDigest, validateSourceGrowthRunBinding, validateAnySourceGrowthRunBinding, anySourceGrowthRunDigest } from '@dsh-ray/assistant-growth-contract';
4
+ import { UsageStore, isWorkItemUsageIntent } from './usage-store.js';
5
+ import { freezeWorkItemData, ownData, isWorkItemCreationReady, isWorkItemRevisionReady, workItemAuthorityDeadline, workItemRevisionAuthorityDeadline, workItemTextDigest, workItemRunSource, workItemStableOwner } from './work-item-source.js';
6
+ import { matchRevisionTarget } from './revision-target-matcher.js';
7
+ class WorkItemSourcePending extends Error {
8
+ }
9
+ class WorkItemSourceObsolete extends Error {
10
+ }
11
+ const OWNER = 'assistant-growth-usage';
12
+ const EXECUTOR = 'assistant-growth-usage-v1';
13
+ const CATALOG = acceptanceDigest({ executor: EXECUTOR, version: 1 });
14
+ const same = (a, b) => acceptanceDigest(a) === acceptanceDigest(b);
15
+ /** Durable task-driven reviews; only native Automations owns timers/claims. */
16
+ export class UsageLearningRuntime {
17
+ config;
18
+ ports;
19
+ store;
20
+ lane;
21
+ configDigest;
22
+ scanId;
23
+ abort = new AbortController();
24
+ flights = new Set();
25
+ unregister;
26
+ unsubscribe;
27
+ ownerGuard;
28
+ unsubscribeWake;
29
+ initialized = false;
30
+ active = false;
31
+ scanning = false;
32
+ lastError = null;
33
+ lastScanAt = null;
34
+ closing;
35
+ constructor(config, ports) {
36
+ this.config = config;
37
+ this.ports = ports;
38
+ if (!config.usageLearning.enabled || !config.scope || !config.usageLearning.databasePath || !config.budgetId)
39
+ throw new Error('usage learning configuration missing');
40
+ if (typeof ports.evaluation.listTrustedTaskLearningProjections !== 'function'
41
+ || typeof ports.evaluation.withTrustedCanonicalTaskWriterFence !== 'function'
42
+ || typeof ports.evaluation.onTrustedTaskChange !== 'function'
43
+ || typeof ports.delivery.inspectOwnerRouteState !== 'function'
44
+ || typeof ports.automations.inspectSystemOwnedRetirement !== 'function'
45
+ || typeof ports.automations.retireSystemOwned !== 'function'
46
+ || typeof ports.automations.onSchedulerWake !== 'function'
47
+ || typeof ports.delivery.inspectOwnerForegroundLearningTask !== 'function'
48
+ || typeof ports.automations.registerHostExecutor !== 'function'
49
+ || typeof ports.automations.inspectSystemOwnedActivation !== 'function') {
50
+ throw new Error('usage learning requires compatible Evaluation, Delivery and Automations Host APIs');
51
+ }
52
+ this.store = new UsageStore(config.usageLearning.databasePath);
53
+ this.lane = acceptanceDigest(config.scope);
54
+ // Historical defaults were revision=false and modification=true. Preserve
55
+ // both omissions for old runs; an explicitly restricted lane stays distinct.
56
+ const { allowRevision, allowModification, ...legacySourceConfig } = config.pluginSourceProposals;
57
+ this.configDigest = acceptanceDigest({ ...config, pluginSourceProposals: { ...legacySourceConfig,
58
+ ...(allowRevision ? { allowRevision: true } : {}),
59
+ ...(allowModification === false ? { allowModification: false } : {}) } });
60
+ this.scanId = `usage-scan-${this.lane}`;
61
+ this.ownerGuard = new ScannerOwnerGuard(OWNER, this.scanId, { authorityId: config.scope.ownerRouteId,
62
+ principalId: config.scope.principalId, workspace: config.scope.workspace, agentPreset: config.scope.preset }, ports.delivery, ports.automations);
63
+ }
64
+ health = () => ({ enabled: true, connected: this.active && !this.ownerGuard.retired, lastScanAt: this.lastScanAt,
65
+ lastError: this.lastError, counts: this.store.counts(this.lane) });
66
+ start() {
67
+ let recoverNativeScanner = false;
68
+ try {
69
+ this.ownerGuard.check();
70
+ }
71
+ catch (error) {
72
+ this.lastError = String(error).slice(0, 200);
73
+ if (this.ownerGuard.retired)
74
+ return;
75
+ recoverNativeScanner = this.ownerGuard.canReconcileScanner;
76
+ }
77
+ this.unregister = this.ports.automations.registerHostExecutor({
78
+ descriptor: { executorId: EXECUTOR, contractVersion: 1, catalogDigest: CATALOG },
79
+ accepts: spec => spec.executorId === EXECUTOR && spec.executorContractVersion === 1
80
+ && spec.catalogDigest === CATALOG && spec.runbookVersion === 1 && ['scan', 'review'].includes(spec.runbookId),
81
+ execute: input => {
82
+ const flight = this.execute(input);
83
+ this.flights.add(flight);
84
+ void flight.finally(() => this.flights.delete(flight)).catch(() => { });
85
+ return flight;
86
+ },
87
+ });
88
+ this.active = true;
89
+ this.unsubscribeWake = this.ports.automations.onSchedulerWake(() => {
90
+ if (!this.active || this.initialized || this.ownerGuard.retired)
91
+ return;
92
+ try {
93
+ this.initializeScanner();
94
+ }
95
+ catch (error) {
96
+ this.lastError = String(error).slice(0, 200);
97
+ }
98
+ });
99
+ this.unsubscribe = this.ports.evaluation.onTrustedTaskChange(() => this.scan());
100
+ // This persisted scan also discovers writes made by another Host process.
101
+ if (recoverNativeScanner) {
102
+ try {
103
+ this.ports.automations.reconcileSystem({ owner: OWNER, automationId: this.scanId,
104
+ idempotencyKey: `${this.scanId}:${this.configDigest}`, desiredStatus: 'active', definition: this.definition() });
105
+ }
106
+ catch (error) {
107
+ this.lastError = String(error).slice(0, 200);
108
+ }
109
+ }
110
+ this.scan();
111
+ }
112
+ initializeScanner() {
113
+ const owner = this.owner();
114
+ if (!this.initialized) {
115
+ this.store.interrupt(this.lane);
116
+ this.ports.automations.reconcileSystem({ owner: OWNER, automationId: this.scanId,
117
+ idempotencyKey: `${this.scanId}:${this.configDigest}`, desiredStatus: 'active', definition: this.definition() });
118
+ this.initialized = true;
119
+ }
120
+ return owner;
121
+ }
122
+ close() {
123
+ return this.closing ??= (async () => {
124
+ this.active = false;
125
+ this.unsubscribeWake?.();
126
+ this.unsubscribe?.();
127
+ this.unregister?.();
128
+ this.abort.abort(new Error('usage learning provider disposed'));
129
+ try {
130
+ await drainScannerFlights(this.flights);
131
+ }
132
+ finally {
133
+ this.store.close();
134
+ }
135
+ })();
136
+ }
137
+ owner() {
138
+ if (!this.active)
139
+ throw new Error('usage learning unavailable');
140
+ this.ownerGuard.check();
141
+ const scope = this.config.scope;
142
+ return this.ports.delivery.validateOwnerRoute({ authorityId: scope.ownerRouteId, principalId: scope.principalId,
143
+ workspace: scope.workspace, agentPreset: scope.preset });
144
+ }
145
+ source(job) {
146
+ this.abort.signal.throwIfAborted();
147
+ if (isWorkItemUsageIntent(job.intent))
148
+ throw new Error('foreground usage source required');
149
+ if (job.intent.configDigest !== this.configDigest || job.intent.expiresAt <= Date.now()
150
+ || !isSourceOwnerContinuation(this.owner(), job.intent.source.owner))
151
+ throw new Error('usage authority changed or expired');
152
+ const owner = job.intent.source.owner;
153
+ const source = this.ports.delivery.inspectOwnerForegroundLearningTask({ authorityId: owner.authorityId,
154
+ principalId: owner.principalId, workspace: owner.workspace, agentPreset: owner.agentPreset,
155
+ outcomeId: job.intent.source.canonical.triggerOutcomeId });
156
+ if (!source || !same(source.canonical.projection, job.intent.source.canonical.projection)
157
+ || !same(source.source, job.intent.source.source) || !same(source.owner, owner)
158
+ || !(source.ownerRevision === undefined && job.intent.source.ownerRevision === undefined
159
+ || source.ownerRevision !== undefined && job.intent.source.ownerRevision !== undefined
160
+ && same(source.ownerRevision, job.intent.source.ownerRevision))
161
+ || source.judgement !== job.intent.source.judgement)
162
+ throw new Error('usage source changed');
163
+ return source;
164
+ }
165
+ inspectSourceGrowthRun = (request) => {
166
+ if (!this.active)
167
+ throw new SourceGrowthRunUnavailableError('usage runtime is temporarily unavailable');
168
+ try {
169
+ const job = this.store.get(request.runId);
170
+ if (!job || isWorkItemUsageIntent(job.intent) || job.digest !== request.intentDigest || !['running', 'reviewed'].includes(job.state)
171
+ || !job.intent.modelOrigin || !job.intent.budget || !job.sourceRun
172
+ || job.definitionHash === null || job.occurrenceId === null)
173
+ return undefined;
174
+ const source = this.source(job);
175
+ const binding = job.sourceRun;
176
+ if (binding.protocol !== 'assistant-growth/source-run/v1')
177
+ return undefined;
178
+ validateSourceGrowthRunBinding(binding);
179
+ if (binding.creationAcceptance !== undefined) {
180
+ const current = this.ports.inspectCreationAcceptanceAuthority?.();
181
+ if (current === undefined || current.expiresAt <= Date.now() || !same(binding.creationAcceptance, current))
182
+ return undefined;
183
+ }
184
+ if (binding.revisionAcceptance !== undefined) {
185
+ const current = this.ports.inspectRevisionAcceptanceAuthority?.();
186
+ if (current === undefined || current.expiresAt <= Date.now() || !same(binding.revisionAcceptance, current))
187
+ return undefined;
188
+ }
189
+ if (binding.revisionRegressionAcceptance !== undefined) {
190
+ const current = this.ports.inspectRevisionRegressionAcceptanceAuthority?.();
191
+ if (current === undefined || current.expiresAt <= Date.now() || !same(binding.revisionRegressionAcceptance, current))
192
+ return undefined;
193
+ }
194
+ if (binding.runId !== job.id || binding.intentDigest !== job.digest || binding.configDigest !== this.configDigest
195
+ || binding.native.definitionHash !== job.definitionHash || binding.native.occurrenceId !== job.occurrenceId
196
+ || binding.source.outcomeId !== source.canonical.triggerOutcomeId
197
+ || !same(binding.source.projection, source.canonical.projection)
198
+ || binding.ownerDigest !== sourceGrowthEvidenceDigest(source.owner)
199
+ || binding.source.sourceDigest !== sourceGrowthEvidenceDigest({ protocol: source.protocol, source: source.source,
200
+ judgement: source.judgement, ownerRevision: source.ownerRevision })
201
+ || !same(binding.model, job.intent.model) || binding.modelOrigin !== job.intent.modelOrigin
202
+ || !same(binding.budget, job.intent.budget))
203
+ return undefined;
204
+ return structuredClone(binding);
205
+ }
206
+ catch (error) {
207
+ if (error instanceof ScannerOwnerUnavailable && !this.ownerGuard.retired)
208
+ throw new SourceGrowthRunUnavailableError(error.message);
209
+ const code = error instanceof Error ? error.code : undefined;
210
+ if (code === 'SQLITE_BUSY' || code === 'SQLITE_LOCKED'
211
+ || code === 'ERR_SQLITE_ERROR' && error instanceof Error && /database (?:is )?(?:busy|locked)/iu.test(error.message)) {
212
+ throw new SourceGrowthRunUnavailableError('usage store is temporarily busy');
213
+ }
214
+ return undefined;
215
+ }
216
+ };
217
+ workItemScope(owner) {
218
+ return { authorityId: owner.authorityId, principalId: owner.principalId, workspace: owner.workspace, agentPreset: owner.agentPreset,
219
+ expectedOwner: { authorityHash: owner.authorityHash, principalRecordId: owner.principalRecordId, principalVersion: owner.principalVersion } };
220
+ }
221
+ assertWorkItemReadiness(owner, admission = true) {
222
+ const pins = this.config.usageLearning.workItemAuthorities;
223
+ const currentOwner = this.owner();
224
+ if (!isSourceOwnerContinuation(currentOwner, owner))
225
+ throw new WorkItemSourceObsolete('work item source owner changed');
226
+ if (!this.config.usageLearning.workItemFailures || !pins || !this.ports.reviewWorkItem
227
+ || this.ports.inspectWorkItemToolPreauthorization?.() !== true
228
+ || !isWorkItemCreationReady(this.ports.inspectWorkItemCreationReadiness?.({ owner: currentOwner }), pins, Date.now(), admission)) {
229
+ throw new WorkItemSourcePending('work item engineering peers or authorizations unavailable');
230
+ }
231
+ }
232
+ assertWorkItemRevisionReadiness(owner, pins, admission) {
233
+ const currentOwner = this.owner();
234
+ if (!isSourceOwnerContinuation(currentOwner, owner))
235
+ throw new WorkItemSourceObsolete('work item source owner changed');
236
+ if (this.ports.inspectWorkItemToolPreauthorization?.() !== true
237
+ || !isWorkItemRevisionReady(this.ports.inspectWorkItemRevisionReadiness?.({ owner: currentOwner }), pins, Date.now(), admission)) {
238
+ throw new WorkItemSourcePending('work item revision peers or authorizations unavailable');
239
+ }
240
+ }
241
+ /**
242
+ * Freeze the corridor when the WorkItem leaves the pending queue. The
243
+ * revise-created corridor wins only when every revision peer is live AND the
244
+ * deterministic target matcher finds exactly one adopted capability named in
245
+ * the objective; otherwise the job keeps the fail-closed create-only corridor.
246
+ */
247
+ resolveWorkItemCorridor(source) {
248
+ const owner = this.owner();
249
+ if (!isSourceOwnerContinuation(owner, source.task.owner))
250
+ throw new WorkItemSourceObsolete('work item source owner changed');
251
+ if (this.ports.inspectWorkItemToolPreauthorization?.() !== true) {
252
+ throw new WorkItemSourcePending('work item tool preauthorization unavailable');
253
+ }
254
+ const revisionPins = this.config.usageLearning.workItemRevisionAuthorities;
255
+ if (revisionPins !== undefined
256
+ && isWorkItemRevisionReady(this.ports.inspectWorkItemRevisionReadiness?.({ owner }), revisionPins, Date.now(), true)) {
257
+ const targets = this.ports.inspectWorkItemRevisionTargets?.() ?? [];
258
+ const match = matchRevisionTarget(source.objective, targets);
259
+ if (match !== undefined) {
260
+ return { corridor: 'revise-created', authorities: structuredClone(revisionPins),
261
+ revisionTarget: { parentPlanId: match.parentPlanId, name: match.name } };
262
+ }
263
+ }
264
+ const creationPins = this.config.usageLearning.workItemAuthorities;
265
+ if (this.config.usageLearning.workItemFailures && creationPins !== undefined
266
+ && isWorkItemCreationReady(this.ports.inspectWorkItemCreationReadiness?.({ owner }), creationPins, Date.now(), true)) {
267
+ return { corridor: 'create', authorities: structuredClone(creationPins) };
268
+ }
269
+ throw new WorkItemSourcePending('work item engineering peers or authorizations unavailable');
270
+ }
271
+ currentWorkItem(locator) {
272
+ if (locator.configDigest !== this.configDigest || locator.expiresAt <= Date.now()
273
+ || !same(workItemStableOwner(this.owner()), locator.owner))
274
+ throw new WorkItemSourceObsolete('work item usage authority changed or expired');
275
+ const get = this.ports.evaluation.getTrustedWorkItemLearningProjection;
276
+ if (typeof get !== 'function')
277
+ throw new WorkItemSourcePending('work item canonical reader unavailable');
278
+ const scope = this.ports.evaluation.canonicalHostScope({ workspace: locator.owner.workspace, preset: locator.owner.agentPreset });
279
+ const current = get.call(this.ports.evaluation, { scope, itemId: locator.itemId });
280
+ if (!current || current.projection.disposition !== 'upsert' || current.objective?.status !== 'not-achieved'
281
+ || current.objective.outcomeId !== locator.canonical.outcomeId || current.projection.version !== locator.canonical.version
282
+ || current.projection.digest !== locator.canonical.digest)
283
+ throw new WorkItemSourceObsolete('work item canonical source changed');
284
+ }
285
+ expectation(source) {
286
+ const task = source.task, outcome = task.canonical.objective;
287
+ return { ...this.workItemScope(task.owner), itemId: task.proofIdentity.itemId, outcomeId: outcome.outcomeId,
288
+ expectedSourceDigest: task.sourceDigest, expectedContentDigest: task.presentationDigest,
289
+ canonical: { version: task.canonical.projection.version, digest: task.canonical.projection.digest, objectiveStatus: 'not-achieved' },
290
+ expectedManifestDigest: source.manifest.manifestDigest, expectedObjectiveDigest: source.manifest.objective.fullTextDigest };
291
+ }
292
+ locatorFor(intent) {
293
+ const source = workItemRunSource(intent.source), owner = intent.source.task.owner;
294
+ return { protocol: 'assistant-growth/work-item-usage-locator/v1', configDigest: intent.configDigest,
295
+ owner: { authorityId: owner.authorityId, authorityHash: owner.authorityHash, principalId: owner.principalId,
296
+ principalRecordId: owner.principalRecordId, principalVersion: owner.principalVersion, workspace: owner.workspace, agentPreset: owner.agentPreset },
297
+ itemId: source.itemId, canonical: { outcomeId: source.outcomeId, version: source.projection.version,
298
+ digest: source.projection.digest, objectiveStatus: 'not-achieved' }, createdAt: intent.createdAt, expiresAt: intent.expiresAt };
299
+ }
300
+ withWorkItemSource(intent, callback) {
301
+ this.abort.signal.throwIfAborted();
302
+ this.currentWorkItem(this.locatorFor(intent));
303
+ const expectedPins = intent.corridor === 'revise-created'
304
+ ? this.config.usageLearning.workItemRevisionAuthorities
305
+ : this.config.usageLearning.workItemAuthorities;
306
+ if (expectedPins === undefined || !same(intent.authorities, expectedPins))
307
+ throw new WorkItemSourceObsolete('work item authority pins changed');
308
+ const fence = this.ports.delivery.withOwnerWorkItemEngineeringContextFence;
309
+ if (!fence)
310
+ throw new WorkItemSourcePending('work item engineering fence unavailable');
311
+ return fence.call(this.ports.delivery, this.expectation(intent.source), source => {
312
+ this.abort.signal.throwIfAborted();
313
+ const authorityDeadline = intent.corridor === 'revise-created'
314
+ ? workItemRevisionAuthorityDeadline(intent.authorities) : workItemAuthorityDeadline(intent.authorities);
315
+ if (!this.active || intent.configDigest !== this.configDigest || Date.now() >= Math.min(intent.expiresAt, authorityDeadline))
316
+ throw new WorkItemSourceObsolete('work item usage lifecycle or authority expired');
317
+ if (!same(workItemRunSource({ ...intent.source, ...source }), workItemRunSource(intent.source))
318
+ || !isSourceOwnerContinuation(source.task.owner, intent.source.task.owner)
319
+ || !same({ ...source.task, owner: intent.source.task.owner, canonical: intent.source.task.canonical }, intent.source.task)
320
+ || !same(source.manifest, intent.source.manifest) || source.objective !== intent.source.objective)
321
+ throw new WorkItemSourceObsolete('frozen work item engineering source changed');
322
+ return callback(source);
323
+ });
324
+ }
325
+ readWorkItem(locator) {
326
+ this.currentWorkItem(locator);
327
+ const inspect = this.ports.delivery.inspectOwnerWorkItemEngineeringContext, read = this.ports.delivery.readOwnerWorkItemEngineeringContext;
328
+ if (!inspect || !read)
329
+ throw new WorkItemSourcePending('work item engineering context reader unavailable');
330
+ const context = inspect.call(this.ports.delivery, { ...this.workItemScope(locator.owner), itemId: locator.itemId, outcomeId: locator.canonical.outcomeId });
331
+ if (!context)
332
+ throw new WorkItemSourcePending('complete work item context temporarily unreadable');
333
+ let shell = { protocol: 'assistant-delivery/work-item-engineering-context/v1', ...context, objective: '', parentReports: [] };
334
+ const expectation = this.expectation(shell);
335
+ const readAll = (selector, fullTextDigest, fullBytes) => {
336
+ if (!Number.isSafeInteger(fullBytes) || fullBytes < 1 || fullBytes > (selector.kind === 'objective' ? 16_384 : 65_536))
337
+ throw new WorkItemSourceObsolete('work item context exceeds complete input bound');
338
+ let offset = 0, text = '';
339
+ for (let pageNumber = 0; pageNumber < 32; pageNumber++) {
340
+ const page = read.call(this.ports.delivery, { ...expectation, selector, offset, maxBytes: 8192 });
341
+ if (!page || page.manifestDigest !== context.manifest.manifestDigest || page.fullTextDigest !== fullTextDigest
342
+ || page.fullBytes !== fullBytes || page.offset !== offset || !page.text.isWellFormed()
343
+ || page.returnedBytes !== Buffer.byteLength(page.text) || page.returnedBytes < 1)
344
+ throw new WorkItemSourcePending('work item context pagination changed');
345
+ text += page.text;
346
+ offset += page.returnedBytes;
347
+ if (offset > fullBytes || page.nextOffset !== undefined && page.nextOffset !== offset)
348
+ throw new WorkItemSourceObsolete('invalid work item context pagination');
349
+ if (page.nextOffset === undefined) {
350
+ if (offset !== fullBytes || workItemTextDigest(text) !== fullTextDigest)
351
+ throw new WorkItemSourceObsolete('work item context was not fully read');
352
+ return text;
353
+ }
354
+ }
355
+ throw new WorkItemSourceObsolete('work item context pagination exceeds bound');
356
+ };
357
+ shell = { ...shell, objective: readAll({ kind: 'objective' }, context.manifest.objective.fullTextDigest, context.manifest.objective.fullBytes) };
358
+ let reportBytes = 0;
359
+ shell.parentReports = context.manifest.reports.map(report => {
360
+ reportBytes += report.fullBytes;
361
+ if (report.truncated || reportBytes > 262_144)
362
+ throw new WorkItemSourceObsolete('sealed background reports exceed bound');
363
+ return { itemId: report.itemId, revision: report.revision, fullTextDigest: report.fullTextDigest, fullBytes: report.fullBytes,
364
+ text: readAll({ kind: 'parent-report', itemId: report.itemId, revision: report.revision }, report.fullTextDigest, report.fullBytes) };
365
+ });
366
+ workItemRunSource(shell);
367
+ return freezeWorkItemData(shell);
368
+ }
369
+ scanWorkItems(owner, scope) {
370
+ for (let pageNumber = 0, stopped = false; pageNumber < 10 && !stopped; pageNumber++) {
371
+ const after = this.store.workItemCursor(this.lane);
372
+ const page = this.ports.evaluation.listTrustedTaskLearningProjections({ scope, ...(after ? { after } : {}), limit: 100 });
373
+ for (const item of page.items) {
374
+ const canonical = item.receipt, now = Date.now(), at = canonical.objective?.occurredAt ?? 0;
375
+ const workItem = canonical.projection.subjectKind === 'work-item';
376
+ const eligible = workItem && canonical.projection.disposition === 'upsert' && canonical.objective?.status === 'not-achieved'
377
+ && at <= now && now - at < this.config.usageLearning.lookbackMs;
378
+ const locator = eligible ? { protocol: 'assistant-growth/work-item-usage-locator/v1',
379
+ configDigest: this.configDigest, owner: { authorityId: owner.authorityId, authorityHash: owner.authorityHash,
380
+ principalId: owner.principalId, principalRecordId: owner.principalRecordId, principalVersion: owner.principalVersion,
381
+ workspace: owner.workspace, agentPreset: owner.agentPreset }, itemId: canonical.projection.subjectRef,
382
+ canonical: { outcomeId: canonical.objective.outcomeId, version: canonical.projection.version,
383
+ digest: canonical.projection.digest, objectiveStatus: 'not-achieved' }, createdAt: now, expiresAt: at + this.config.usageLearning.lookbackMs } : undefined;
384
+ const staged = this.ports.evaluation.withTrustedCanonicalTaskWriterFence({ scope, scopeWatermark: page.scopeWatermark,
385
+ evidence: [canonical.projection] }, () => this.store.consumeWorkItem({ lane: this.lane, scopeKey: page.nextCursor.scopeKey,
386
+ watermark: item.watermark, ...(workItem ? { itemId: canonical.projection.subjectRef } : {}),
387
+ ...(locator ? { locator } : {}), maxPending: this.config.usageLearning.maxPending }));
388
+ if (!staged.matched || !staged.value) {
389
+ stopped = true;
390
+ break;
391
+ }
392
+ }
393
+ if (!page.hasMore)
394
+ break;
395
+ }
396
+ for (const pending of this.store.pendingWorkItems(this.lane)) {
397
+ try {
398
+ this.currentWorkItem(pending.locator);
399
+ const source = this.readWorkItem(pending.locator);
400
+ const corridor = this.resolveWorkItemCorridor(source);
401
+ const fixed = this.config.provider !== null && this.config.model !== null;
402
+ const intent = { sourceKind: 'work-item', configDigest: this.configDigest, source,
403
+ model: fixed ? { provider: this.config.provider, model: this.config.model, ...(this.config.reasoningEffort === null ? {} : { reasoningEffort: this.config.reasoningEffort }) }
404
+ : structuredClone(source.task.proofIdentity.supplier), modelOrigin: fixed ? 'explicit-growth-override' : 'inherited-owner-task',
405
+ budget: { budgetId: this.config.budgetId, amount: this.config.budgetAmount, maxModelCalls: this.config.maxModelCalls,
406
+ maxToolCalls: this.config.maxToolCalls, maxOutputTokens: this.config.maxOutputTokens, maxDurationMs: this.config.maxDurationMs,
407
+ maxPlansPerWake: this.config.pluginSourceProposals.maxPlansPerWake },
408
+ ...corridor,
409
+ createdAt: pending.locator.createdAt, expiresAt: pending.locator.expiresAt };
410
+ this.withWorkItemSource(intent, () => this.store.freezeWorkItem(pending.id, intent));
411
+ }
412
+ catch (error) {
413
+ if (error instanceof ScannerOwnerUnavailable)
414
+ throw error;
415
+ if (error instanceof WorkItemSourceObsolete)
416
+ this.store.abandonWorkItem(pending.id);
417
+ else if (!(error instanceof WorkItemSourcePending))
418
+ this.lastError = String(error).slice(0, 200);
419
+ }
420
+ }
421
+ }
422
+ inspectAnySourceGrowthRun = (request) => {
423
+ if (!this.active)
424
+ throw new SourceGrowthRunUnavailableError('usage runtime temporarily unavailable');
425
+ const job = this.store.get(request.runId);
426
+ if (!job || !isWorkItemUsageIntent(job.intent))
427
+ return this.inspectSourceGrowthRun(request);
428
+ try {
429
+ const expectedProtocol = job.intent.corridor === 'revise-created'
430
+ ? 'assistant-growth/source-run/v3' : 'assistant-growth/source-run/v2';
431
+ if (job.digest !== request.intentDigest || !['running', 'reviewed'].includes(job.state) || !job.sourceRun
432
+ || job.sourceRun.protocol !== expectedProtocol)
433
+ return undefined;
434
+ if (job.intent.corridor === 'revise-created') {
435
+ this.assertWorkItemRevisionReadiness(job.intent.source.task.owner, job.intent.authorities, false);
436
+ }
437
+ else {
438
+ this.assertWorkItemReadiness(job.intent.source.task.owner, false);
439
+ }
440
+ return this.withWorkItemSource(job.intent, () => this.store.withWorkItemRunWriter(request, current => {
441
+ if (!current.sourceRun || current.sourceRun.protocol !== expectedProtocol)
442
+ throw new Error('work item run absent');
443
+ this.assertWorkItemBinding(current, current.sourceRun);
444
+ return freezeWorkItemData(current.sourceRun);
445
+ }));
446
+ }
447
+ catch (error) {
448
+ if (error instanceof WorkItemSourcePending || error instanceof ScannerOwnerUnavailable)
449
+ throw new SourceGrowthRunUnavailableError(error.message);
450
+ return undefined;
451
+ }
452
+ };
453
+ withWorkItemRunFence = (input, callback) => {
454
+ if (!this.active)
455
+ throw new SourceGrowthRunUnavailableError('usage runtime temporarily unavailable');
456
+ input = ownData(input);
457
+ if (Object.keys(input).sort().join(',') !== 'expectedGrowthRunDigest,intentDigest,runId' || typeof callback !== 'function'
458
+ || typeof input.runId !== 'string' || !input.runId || input.runId.length > 500
459
+ || typeof input.intentDigest !== 'string' || !/^[a-f0-9]{64}$/u.test(input.intentDigest)
460
+ || typeof input.expectedGrowthRunDigest !== 'string' || !/^[a-f0-9]{64}$/u.test(input.expectedGrowthRunDigest))
461
+ throw new Error('invalid work item run fence input');
462
+ const job = this.store.get(input.runId);
463
+ if (!job || job.digest !== input.intentDigest || !isWorkItemUsageIntent(job.intent))
464
+ throw new Error('work item run not found');
465
+ const intent = job.intent;
466
+ if (intent.corridor === 'revise-created') {
467
+ this.assertWorkItemRevisionReadiness(intent.source.task.owner, intent.authorities, false);
468
+ }
469
+ else {
470
+ this.assertWorkItemReadiness(intent.source.task.owner, false);
471
+ }
472
+ return this.withWorkItemSource(intent, () => this.store.withWorkItemRunWriter(input, current => {
473
+ const binding = current.sourceRun;
474
+ if (!binding || binding.protocol === 'assistant-growth/source-run/v1'
475
+ || (intent.corridor === 'revise-created'
476
+ ? binding.protocol !== 'assistant-growth/source-run/v3' : binding.protocol !== 'assistant-growth/source-run/v2')
477
+ || anySourceGrowthRunDigest(binding) !== input.expectedGrowthRunDigest
478
+ || binding.configDigest !== this.configDigest || !same(binding.authorities, intent.authorities)
479
+ || !same(binding.source, workItemRunSource(intent.source)))
480
+ throw new Error('work item run binding changed');
481
+ this.assertWorkItemBinding(current, binding);
482
+ return callback(freezeWorkItemData(binding));
483
+ }));
484
+ };
485
+ assertWorkItemBinding(job, binding) {
486
+ validateAnySourceGrowthRunBinding(binding);
487
+ if (!isWorkItemUsageIntent(job.intent)
488
+ || (binding.protocol === 'assistant-growth/source-run/v3') !== (job.intent.corridor === 'revise-created')
489
+ || binding.runId !== job.id || binding.intentDigest !== job.digest
490
+ || binding.configDigest !== this.configDigest || binding.ownerDigest !== sourceGrowthEvidenceDigest(job.intent.source.task.owner)
491
+ || binding.native.automationId !== job.id || binding.native.definitionHash !== job.definitionHash || binding.native.occurrenceId !== job.occurrenceId
492
+ || !same(binding.source, workItemRunSource(job.intent.source)) || !same(binding.model, job.intent.model)
493
+ || binding.modelOrigin !== job.intent.modelOrigin || !same(binding.budget, job.intent.budget)
494
+ || !same(binding.authorities, job.intent.authorities) || binding.expiresAt !== job.intent.expiresAt)
495
+ throw new Error('work item persisted run differs from frozen job');
496
+ }
497
+ async executeWorkItem(input, queued, result) {
498
+ if (!isWorkItemUsageIntent(queued.intent))
499
+ throw new Error('work item usage expected');
500
+ const intent = queued.intent;
501
+ const revision = intent.corridor === 'revise-created';
502
+ const authorityDeadline = revision
503
+ ? workItemRevisionAuthorityDeadline(intent.authorities)
504
+ : workItemAuthorityDeadline(intent.authorities);
505
+ const assertReady = (admission) => {
506
+ if (intent.corridor === 'revise-created')
507
+ this.assertWorkItemRevisionReadiness(intent.source.task.owner, intent.authorities, admission);
508
+ else
509
+ this.assertWorkItemReadiness(intent.source.task.owner, admission);
510
+ };
511
+ let claimed = false;
512
+ try {
513
+ assertReady(true);
514
+ this.withWorkItemSource(intent, () => { this.store.claim(queued.id, input.definitionHash, input.occurrenceId); claimed = true; });
515
+ const signal = AbortSignal.any([input.signal, this.abort.signal, AbortSignal.timeout(Math.max(1, Math.min(this.config.maxDurationMs, intent.expiresAt - Date.now(), authorityDeadline - Date.now())))]);
516
+ const assertCurrent = () => {
517
+ signal.throwIfAborted();
518
+ // Peer/owner probes can synchronously change source state. Run them
519
+ // before the final complete source frame; its callback is local only.
520
+ assertReady(false);
521
+ this.withWorkItemSource(intent, () => {
522
+ signal.throwIfAborted();
523
+ const current = this.store.get(queued.id);
524
+ if (current?.state !== 'running' || current.occurrenceId !== input.occurrenceId
525
+ || current.digest !== queued.digest)
526
+ throw new Error('work item usage no longer owns dispatch');
527
+ });
528
+ };
529
+ const bindSourceRun = actual => {
530
+ assertCurrent();
531
+ assertReady(true);
532
+ if (!same(actual.model, intent.model) || actual.generationDeadlineAt > authorityDeadline) {
533
+ throw new Error('work item run setup authority changed');
534
+ }
535
+ const binding = intent.corridor === 'revise-created'
536
+ ? this.bindWorkItemRevisionRun(actual, intent, queued, input)
537
+ : this.bindWorkItemCreationRun(actual, intent, queued, input);
538
+ return this.withWorkItemSource(intent, () => this.store.bindWorkItemSourceRun(queued.id, queued.digest, input.definitionHash, input.occurrenceId, binding));
539
+ };
540
+ assertReady(true);
541
+ assertCurrent();
542
+ const outcome = await this.ports.reviewWorkItem({ sourceKind: 'work-item', id: queued.id, intentDigest: queued.digest,
543
+ definitionHash: input.definitionHash, occurrenceId: input.occurrenceId, expiresAt: Math.min(intent.expiresAt, authorityDeadline),
544
+ corridor: intent.corridor, model: intent.model, source: intent.source, signal, assertCurrent,
545
+ assertFirstModelAdmission: () => { assertReady(true); assertCurrent(); }, bindSourceRun });
546
+ assertCurrent();
547
+ this.store.settle(queued.id, outcome, outcome === 'reviewed' ? 'review-complete-not-adopted' : 'review-incomplete', input.occurrenceId);
548
+ return result(outcome === 'reviewed' ? 'succeeded' : outcome);
549
+ }
550
+ catch {
551
+ if (claimed)
552
+ this.store.settle(queued.id, 'unknown', 'interrupted-after-dispatch', input.occurrenceId);
553
+ return result(claimed ? 'unknown' : 'failed');
554
+ }
555
+ }
556
+ bindWorkItemCreationRun(actual, intent, queued, input) {
557
+ if (!same(actual.creationAcceptance, intent.authorities.creationAcceptance)
558
+ || actual.revisionAcceptance !== undefined || actual.revisionRegressionAcceptance !== undefined) {
559
+ throw new Error('work item run setup authority changed');
560
+ }
561
+ return { protocol: 'assistant-growth/source-run/v2', mode: 'create',
562
+ runId: queued.id, intentDigest: queued.digest, configDigest: intent.configDigest, ownerDigest: sourceGrowthEvidenceDigest(intent.source.task.owner),
563
+ source: workItemRunSource(intent.source), model: actual.model, modelOrigin: intent.modelOrigin, budget: intent.budget,
564
+ creationAcceptance: structuredClone(intent.authorities.creationAcceptance), authorities: structuredClone(intent.authorities),
565
+ native: { owner: OWNER, automationId: queued.id, definitionHash: input.definitionHash, occurrenceId: input.occurrenceId },
566
+ sessionId: actual.sessionId, toolContractDigest: actual.toolContractDigest, executionContractDigest: actual.executionContractDigest,
567
+ createdAt: actual.createdAt, generationDeadlineAt: actual.generationDeadlineAt, expiresAt: intent.expiresAt };
568
+ }
569
+ bindWorkItemRevisionRun(actual, intent, queued, input) {
570
+ if (actual.creationAcceptance !== undefined || actual.revisionAcceptance === undefined
571
+ || !same(actual.revisionAcceptance, intent.authorities.revisionAcceptance)
572
+ || (actual.revisionRegressionAcceptance === undefined) !== (intent.authorities.revisionRegressionAcceptance === undefined)
573
+ || (actual.revisionRegressionAcceptance !== undefined && intent.authorities.revisionRegressionAcceptance !== undefined
574
+ && !same(actual.revisionRegressionAcceptance, intent.authorities.revisionRegressionAcceptance))) {
575
+ throw new Error('work item revision run setup authority changed');
576
+ }
577
+ return { protocol: 'assistant-growth/source-run/v3', mode: 'revise-created',
578
+ runId: queued.id, intentDigest: queued.digest, configDigest: intent.configDigest, ownerDigest: sourceGrowthEvidenceDigest(intent.source.task.owner),
579
+ source: workItemRunSource(intent.source), model: actual.model, modelOrigin: intent.modelOrigin, budget: intent.budget,
580
+ revisionAcceptance: structuredClone(intent.authorities.revisionAcceptance),
581
+ ...(intent.authorities.revisionRegressionAcceptance === undefined ? {} : {
582
+ revisionRegressionAcceptance: structuredClone(intent.authorities.revisionRegressionAcceptance)
583
+ }),
584
+ authorities: structuredClone(intent.authorities),
585
+ native: { owner: OWNER, automationId: queued.id, definitionHash: input.definitionHash, occurrenceId: input.occurrenceId },
586
+ sessionId: actual.sessionId, toolContractDigest: actual.toolContractDigest, executionContractDigest: actual.executionContractDigest,
587
+ createdAt: actual.createdAt, generationDeadlineAt: actual.generationDeadlineAt, expiresAt: intent.expiresAt };
588
+ }
589
+ /** Synchronous nudge, bounded to 1000 heads. Native scan resumes the cursor. */
590
+ scan = () => {
591
+ if (!this.active || this.scanning)
592
+ return;
593
+ this.scanning = true;
594
+ try {
595
+ const owner = this.initializeScanner();
596
+ for (const job of this.store.pending(this.lane))
597
+ if (job.state === 'queued') {
598
+ try {
599
+ if (isWorkItemUsageIntent(job.intent)) {
600
+ this.withWorkItemSource(job.intent, () => undefined);
601
+ this.schedule(job);
602
+ }
603
+ else {
604
+ this.source(job);
605
+ this.schedule(job);
606
+ }
607
+ }
608
+ catch (error) {
609
+ if (isWorkItemUsageIntent(job.intent)) {
610
+ if (error instanceof WorkItemSourceObsolete)
611
+ this.store.settle(job.id, 'superseded', error.message);
612
+ continue;
613
+ }
614
+ ;
615
+ if (error instanceof ScannerOwnerUnavailable)
616
+ throw error;
617
+ this.store.settle(job.id, 'failed', 'queued-source-or-schedule-unavailable');
618
+ }
619
+ }
620
+ const scope = this.ports.evaluation.canonicalHostScope({ workspace: owner.workspace, preset: owner.agentPreset });
621
+ let stop = false;
622
+ for (let pageNumber = 0; pageNumber < 10 && !stop; pageNumber += 1) {
623
+ const page = this.ports.evaluation.listTrustedTaskLearningProjections({ scope,
624
+ ...(this.store.cursor(this.lane) === undefined ? {} : { after: this.store.cursor(this.lane) }), limit: 100 });
625
+ for (const item of page.items) {
626
+ const canonical = item.receipt;
627
+ const source = canonical.projection.subjectKind === 'foreground-turn'
628
+ ? this.ports.delivery.inspectOwnerForegroundLearningTask({ authorityId: owner.authorityId,
629
+ principalId: owner.principalId, workspace: owner.workspace, agentPreset: owner.agentPreset,
630
+ outcomeId: canonical.triggerOutcomeId }) : undefined;
631
+ const fixedModel = this.config.provider !== null && this.config.model !== null;
632
+ const model = fixedModel
633
+ ? { provider: this.config.provider, model: this.config.model,
634
+ ...(this.config.reasoningEffort === null ? {} : { reasoningEffort: this.config.reasoningEffort }) }
635
+ : source?.source.modelSelection;
636
+ const now = Date.now();
637
+ const occurredAt = canonical.objective?.occurredAt ?? 0;
638
+ const eligible = source !== undefined && source.source.quiescent && !source.source.truncated
639
+ && canonical.projection.disposition === 'upsert' && source.judgement !== 'unresolved'
640
+ && occurredAt <= now && now - occurredAt <= this.config.usageLearning.lookbackMs && model !== undefined;
641
+ const intent = eligible ? { configDigest: this.configDigest, source: source, model: model,
642
+ modelOrigin: fixedModel ? 'explicit-growth-override' : 'inherited-owner-task',
643
+ budget: { budgetId: this.config.budgetId, amount: this.config.budgetAmount,
644
+ maxModelCalls: this.config.maxModelCalls, maxToolCalls: this.config.maxToolCalls,
645
+ maxOutputTokens: this.config.maxOutputTokens, maxDurationMs: this.config.maxDurationMs,
646
+ maxPlansPerWake: this.config.pluginSourceProposals.maxPlansPerWake },
647
+ createdAt: now, expiresAt: now + this.config.usageLearning.lookbackMs } : undefined;
648
+ const result = this.ports.evaluation.withTrustedCanonicalTaskWriterFence({ scope, scopeWatermark: page.scopeWatermark,
649
+ evidence: [canonical.projection] }, () => {
650
+ if (!same(owner, this.owner()))
651
+ throw new Error('usage owner changed during scan');
652
+ return this.store.consume({ lane: this.lane, scopeKey: page.nextCursor.scopeKey, watermark: item.watermark,
653
+ subject: `${canonical.projection.subjectKind}:${canonical.projection.subjectRef}`,
654
+ ...(intent === undefined ? {} : { intent }), maxPending: this.config.usageLearning.maxPending });
655
+ });
656
+ if (!result.matched || !result.value) {
657
+ stop = true;
658
+ break;
659
+ }
660
+ }
661
+ if (!page.hasMore)
662
+ break;
663
+ }
664
+ if (this.config.usageLearning.workItemFailures
665
+ && (this.config.usageLearning.workItemAuthorities !== undefined
666
+ || this.config.usageLearning.workItemRevisionAuthorities !== undefined))
667
+ this.scanWorkItems(owner, scope);
668
+ for (const job of this.store.pending(this.lane))
669
+ if (job.state === 'queued') {
670
+ if (isWorkItemUsageIntent(job.intent)) {
671
+ try {
672
+ this.schedule(job);
673
+ }
674
+ catch (error) {
675
+ if (error instanceof WorkItemSourceObsolete)
676
+ this.store.settle(job.id, 'superseded', error.message);
677
+ }
678
+ ;
679
+ continue;
680
+ }
681
+ try {
682
+ this.schedule(job);
683
+ }
684
+ catch (error) {
685
+ if (error instanceof ScannerOwnerUnavailable)
686
+ throw error;
687
+ this.store.settle(job.id, 'failed', 'schedule-rejected');
688
+ }
689
+ }
690
+ this.lastError = null;
691
+ this.lastScanAt = Date.now();
692
+ }
693
+ catch (error) {
694
+ this.lastError = error instanceof Error ? error.message.slice(0, 200) : 'usage-scan-failed';
695
+ }
696
+ finally {
697
+ this.scanning = false;
698
+ }
699
+ };
700
+ definition(job) {
701
+ const scope = this.config.scope;
702
+ return { name: job ? 'Review real task feedback' : 'Discover real task feedback',
703
+ schedule: job ? { kind: 'at', at: new Date(job.intent.createdAt + 1000).toISOString() }
704
+ : { kind: 'cron', expression: '* * * * *', timezone: 'UTC' },
705
+ workspace: scope.workspace, agentPreset: scope.preset, timeoutMs: job ? this.config.maxDurationMs + 5000 : 30_000,
706
+ misfire: { kind: 'latest' }, overlap: 'skip', retrySafety: 'never', maxRetries: 0, principal: scope.principalId,
707
+ ...(job ? { budgetId: this.config.budgetId, budgetAmount: this.config.budgetAmount }
708
+ : { budgetId: this.config.usageLearning.scanBudgetId, budgetAmount: this.config.usageLearning.scanBudgetAmount }),
709
+ execution: { kind: 'host', executorId: EXECUTOR, executorContractVersion: 1, runbookId: job ? 'review' : 'scan',
710
+ runbookVersion: 1, catalogDigest: CATALOG, targetScope: { workspace: scope.workspace, preset: scope.preset },
711
+ scopeDigest: acceptanceDigest([scope.workspace, scope.preset]), ownerRouteId: scope.ownerRouteId,
712
+ activationNonce: job?.digest ?? this.configDigest } };
713
+ }
714
+ schedule(input) {
715
+ let job = input;
716
+ if (isWorkItemUsageIntent(job.intent)) {
717
+ this.assertWorkItemReadiness(job.intent.source.task.owner);
718
+ this.withWorkItemSource(job.intent, () => undefined);
719
+ }
720
+ else
721
+ this.source(job);
722
+ const definition = this.definition(job);
723
+ if (job.definitionHash === null) {
724
+ this.ports.automations.reconcileSystem({ owner: OWNER, automationId: job.id,
725
+ idempotencyKey: `${job.id}:prepare`, desiredStatus: 'paused', definition });
726
+ const receipt = this.ports.automations.inspectSystemOwnedActivation({ owner: OWNER, automationId: job.id });
727
+ if (!receipt || receipt.activationNonce !== job.digest || receipt.ownerRouteId !== this.config.scope.ownerRouteId)
728
+ throw new Error('usage registration mismatch');
729
+ job = this.store.bind(job.id, receipt.definitionHash);
730
+ }
731
+ const current = this.ports.automations.inspectSystemOwnedActivation({ owner: OWNER, automationId: job.id });
732
+ if (!current || current.definitionHash !== job.definitionHash || current.activationNonce !== job.digest)
733
+ throw new Error('usage definition changed');
734
+ const terminal = this.ports.automations.inspectSystemOwned({ owner: OWNER, automationId: job.id }).latestTerminalRuns.production;
735
+ if (terminal && terminal.immutableContext.state === 'verified' && terminal.immutableContext.definitionHash === job.definitionHash) {
736
+ this.store.settle(job.id, 'failed', 'native-run-ended-before-claim');
737
+ return;
738
+ }
739
+ if (isWorkItemUsageIntent(job.intent)) {
740
+ this.assertWorkItemReadiness(job.intent.source.task.owner);
741
+ this.withWorkItemSource(job.intent, () => undefined);
742
+ }
743
+ this.ports.automations.reconcileSystem({ owner: OWNER, automationId: job.id,
744
+ idempotencyKey: `${job.id}:activate`, desiredStatus: 'active', definition });
745
+ }
746
+ async execute(input) {
747
+ const result = (outcome) => ({ outcome,
748
+ failureClass: outcome === 'succeeded' ? 'none' : outcome === 'unknown' ? 'unknown' : 'configuration',
749
+ failurePhase: outcome === 'succeeded' ? 'none' : 'host-execution', failureCode: outcome === 'succeeded' ? 'none' : 'usage-review-rejected',
750
+ sideEffectState: outcome === 'unknown' ? 'unknown' : outcome === 'succeeded' ? 'possible' : 'none',
751
+ retryability: outcome === 'succeeded' || outcome === 'unknown' ? 'unsafe' : 'after-intervention' });
752
+ let claimed;
753
+ try {
754
+ const owner = this.owner();
755
+ if (input.executionMode !== 'production' || input.catalogDigest !== CATALOG || input.ownerRouteId !== owner.authorityId
756
+ || input.principal !== owner.principalId || input.targetScope.workspace !== owner.workspace || input.targetScope.preset !== owner.agentPreset)
757
+ throw new Error('usage dispatch scope mismatch');
758
+ input.signal.throwIfAborted();
759
+ if (input.automationId === this.scanId) {
760
+ const current = this.ports.automations.inspectSystemOwnedActivation({ owner: OWNER, automationId: this.scanId });
761
+ if (input.activationNonce !== this.configDigest || current?.definitionHash !== input.definitionHash)
762
+ throw new Error('usage scanner changed');
763
+ this.scan();
764
+ return result(this.lastError === null ? 'succeeded' : 'failed');
765
+ }
766
+ const queued = this.store.get(input.automationId);
767
+ if (!queued || queued.state !== 'queued' || queued.digest !== input.activationNonce || queued.definitionHash !== input.definitionHash)
768
+ throw new Error('usage review is not queued');
769
+ if (isWorkItemUsageIntent(queued.intent))
770
+ return await this.executeWorkItem(input, queued, result);
771
+ this.source(queued);
772
+ claimed = this.store.claim(queued.id, input.definitionHash, input.occurrenceId);
773
+ const job = claimed;
774
+ if (isWorkItemUsageIntent(job.intent))
775
+ throw new Error('foreground usage claim required');
776
+ const signal = AbortSignal.any([input.signal, this.abort.signal,
777
+ AbortSignal.timeout(Math.max(1, Math.min(this.config.maxDurationMs, job.intent.expiresAt - Date.now())))]);
778
+ const assertCurrent = () => {
779
+ signal.throwIfAborted();
780
+ this.source(job);
781
+ const stored = this.store.get(job.id);
782
+ if (stored?.state !== 'running' || stored.occurrenceId !== input.occurrenceId)
783
+ throw new Error('usage dispatch no longer owned');
784
+ };
785
+ assertCurrent();
786
+ const bindSourceRun = actual => {
787
+ assertCurrent();
788
+ if (actual.creationAcceptance !== undefined) {
789
+ const current = this.ports.inspectCreationAcceptanceAuthority?.();
790
+ if (current === undefined || current.expiresAt <= Date.now() || !same(actual.creationAcceptance, current)) {
791
+ throw new Error('usage creation acceptance authority changed during Agent setup');
792
+ }
793
+ }
794
+ if (actual.revisionAcceptance !== undefined) {
795
+ const current = this.ports.inspectRevisionAcceptanceAuthority?.();
796
+ if (current === undefined || current.expiresAt <= Date.now() || !same(actual.revisionAcceptance, current)) {
797
+ throw new Error('usage revision acceptance authority changed during Agent setup');
798
+ }
799
+ }
800
+ if (actual.revisionRegressionAcceptance !== undefined) {
801
+ const current = this.ports.inspectRevisionRegressionAcceptanceAuthority?.();
802
+ if (current === undefined || current.expiresAt <= Date.now() || !same(actual.revisionRegressionAcceptance, current)) {
803
+ throw new Error('usage revision regression acceptance authority changed during Agent setup');
804
+ }
805
+ }
806
+ if (!job.intent.modelOrigin || !job.intent.budget || !same(actual.model, job.intent.model)) {
807
+ throw new Error('usage source run lacks a frozen model or budget');
808
+ }
809
+ const source = this.source(job);
810
+ const projection = source.canonical.projection;
811
+ if (projection.subjectKind !== 'foreground-turn' || projection.disposition !== 'upsert')
812
+ throw new Error('usage source projection is not current');
813
+ const binding = {
814
+ protocol: 'assistant-growth/source-run/v1', runId: job.id, intentDigest: job.digest,
815
+ configDigest: job.intent.configDigest, ownerDigest: sourceGrowthEvidenceDigest(source.owner),
816
+ source: { outcomeId: source.canonical.triggerOutcomeId,
817
+ projection: { subjectKind: 'foreground-turn', subjectRef: projection.subjectRef, version: projection.version,
818
+ digest: projection.digest, disposition: 'upsert',
819
+ ...(projection.evidenceOutcomeId === undefined ? {} : { evidenceOutcomeId: projection.evidenceOutcomeId }) },
820
+ sourceDigest: sourceGrowthEvidenceDigest({ protocol: source.protocol, source: source.source,
821
+ judgement: source.judgement, ownerRevision: source.ownerRevision }) },
822
+ model: actual.model, modelOrigin: job.intent.modelOrigin, budget: job.intent.budget,
823
+ ...(actual.creationAcceptance === undefined ? {} : { creationAcceptance: structuredClone(actual.creationAcceptance) }),
824
+ ...(actual.revisionAcceptance === undefined ? {} : { revisionAcceptance: structuredClone(actual.revisionAcceptance) }),
825
+ ...(actual.revisionRegressionAcceptance === undefined ? {} : { revisionRegressionAcceptance: structuredClone(actual.revisionRegressionAcceptance) }),
826
+ native: { owner: 'assistant-growth-usage', automationId: job.id,
827
+ definitionHash: input.definitionHash, occurrenceId: input.occurrenceId },
828
+ sessionId: actual.sessionId, toolContractDigest: actual.toolContractDigest,
829
+ executionContractDigest: actual.executionContractDigest, createdAt: actual.createdAt,
830
+ generationDeadlineAt: actual.generationDeadlineAt, expiresAt: job.intent.expiresAt,
831
+ };
832
+ sourceGrowthRunDigest(binding);
833
+ return this.store.bindSourceRun(job.id, job.digest, input.definitionHash, input.occurrenceId, binding);
834
+ };
835
+ const outcome = await this.ports.review({ id: job.id, intentDigest: job.digest,
836
+ definitionHash: input.definitionHash, occurrenceId: input.occurrenceId, expiresAt: job.intent.expiresAt,
837
+ model: job.intent.model, source: job.intent.source, signal, assertCurrent, bindSourceRun });
838
+ assertCurrent();
839
+ this.store.settle(job.id, outcome, outcome === 'reviewed' ? 'review-complete-not-adopted' : 'review-incomplete', input.occurrenceId);
840
+ return result(outcome === 'reviewed' ? 'succeeded' : outcome);
841
+ }
842
+ catch {
843
+ if (claimed)
844
+ this.store.settle(claimed.id, 'unknown', 'interrupted-after-dispatch', input.occurrenceId);
845
+ return result(claimed ? 'unknown' : 'failed');
846
+ }
847
+ finally {
848
+ if (this.active)
849
+ this.scan();
850
+ }
851
+ }
852
+ }
853
+ //# sourceMappingURL=usage-runtime.js.map