@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
package/lib/index.js ADDED
@@ -0,0 +1,662 @@
1
+ import { randomUUID } from 'node:crypto';
2
+ import { Context, Service } from '@deepseek-ai/cordis';
3
+ import { credentialRef } from '@deepseek-ai/dsh-credentials';
4
+ import { ReasoningEffortId } from '@deepseek-ai/dsh-llm';
5
+ import { SourceGrowthRunUnavailableError } from '@dsh-ray/assistant-growth-contract';
6
+ import { Config, normalizeConfig } from './config.js';
7
+ import { mintGrowthAuthority } from './deposit.js';
8
+ import { readAssociationCandidates, } from './association-intake.js';
9
+ import { readValidatedDreamIdeas, } from './dreaming-intake.js';
10
+ import { runGrowthAgent } from './growth-agent.js';
11
+ import { version } from './version.js';
12
+ import { UsageLearningRuntime } from './usage-runtime.js';
13
+ export const name = 'dsh-ray-assistant-growth-driver';
14
+ export { version, Config, normalizeConfig };
15
+ /**
16
+ * cordis 4.0.2 hands cross-plugin service consumers a traceable Proxy whose
17
+ * shadow-method trap rebinds `this` to a second Proxy; ES #private brand
18
+ * checks then throw ("Cannot read private member … from an object whose class
19
+ * did not declare it"). The library exposes the raw instance through
20
+ * Symbol.for('cordis.original') on every traceable Proxy; plain-object mocks
21
+ * have no such marker and pass through unchanged.
22
+ */
23
+ const CORDIS_ORIGINAL = Symbol.for('cordis.original');
24
+ function unwrapService(service) {
25
+ return service?.[CORDIS_ORIGINAL] ?? service;
26
+ }
27
+ /**
28
+ * Opt-in, fail-closed periodic growth driver. Every wake:
29
+ * 1. re-anchors the frozen configured owner scope against Delivery;
30
+ * 2. freezes the conversation's model (or explicit fixed override), applying
31
+ * supplier-specific credential/contract checks only to that supplier;
32
+ * 3. optionally reserves an owner-configured background budget;
33
+ * 4. runs ONE bounded background agent that may only read history and
34
+ * propose a paused skill candidate through Host re-verification.
35
+ * Any failed precondition skips the wake with a health reason: the driver
36
+ * never changes route, never falls back to another model and never self-enables.
37
+ */
38
+ export class AssistantGrowthDriverService extends Service {
39
+ static Config = Config;
40
+ static inject = ['assistantGoals', 'assistantSkills', 'assistantPolicy', 'assistantDelivery', 'agents', 'sessions', 'tools', 'llm'];
41
+ #config;
42
+ #flight;
43
+ #active = true;
44
+ #abort = new AbortController();
45
+ #sourceBinding;
46
+ #health = { lastWakeAt: null, outcome: 'never-run', reason: null, run: null };
47
+ #usage;
48
+ constructor(ctx, input = {}) {
49
+ super(ctx, 'assistantGrowthDriver');
50
+ this.#config = normalizeConfig(input);
51
+ ctx.effect(() => {
52
+ const timer = this.#config.enabled && this.#config.scope !== null && this.#config.intervalMs > 0
53
+ ? setInterval(() => { void this.wake().catch(() => undefined); }, this.#config.intervalMs) : undefined;
54
+ timer?.unref?.();
55
+ return async () => {
56
+ this.#active = false;
57
+ if (timer !== undefined)
58
+ clearInterval(timer);
59
+ this.#abort.abort(new Error('assistant-growth-driver: disposed'));
60
+ await this.#flight;
61
+ };
62
+ }, 'assistant-growth-driver.runtime');
63
+ const usagePrerequisitesReady = this.#config.usageLearning.enabled
64
+ && this.#config.scope !== null
65
+ && this.#config.budgetId !== null
66
+ && this.#config.budgetAmount !== null
67
+ && this.#config.intervalMs === 0
68
+ && this.#config.usageLearning.databasePath !== null
69
+ && this.#config.usageLearning.scanBudgetId !== null
70
+ && this.#config.usageLearning.scanBudgetAmount !== null;
71
+ if (usagePrerequisitesReady) {
72
+ ctx.inject(['assistantEvaluation', 'assistantAutomations'], usageCtx => {
73
+ const usage = new UsageLearningRuntime(this.#config, {
74
+ evaluation: usageCtx.assistantEvaluation, automations: usageCtx.assistantAutomations,
75
+ delivery: usageCtx.assistantDelivery, review: input => this.#reviewUsage(input), reviewWorkItem: input => this.#reviewUsage(input),
76
+ inspectWorkItemToolPreauthorization: () => {
77
+ try {
78
+ const policy = unwrapService(usageCtx.get('assistantPolicy'));
79
+ return this.ctx.fiber.name === 'dsh-ray-assistant-growth-driver'
80
+ && policy?.workItemGrowthToolPreauthorizationVersion?.() === 1 && typeof policy.registerPreauthorizedTool === 'function';
81
+ }
82
+ catch {
83
+ return false;
84
+ }
85
+ },
86
+ inspectWorkItemCreationReadiness: ({ owner }) => {
87
+ const binding = this.#sourceBinding;
88
+ return binding?.available() && binding.workItemCreationReady() ? binding.port.inspectWorkItemCreationReadiness?.({ owner }) : undefined;
89
+ },
90
+ inspectWorkItemRevisionReadiness: ({ owner }) => {
91
+ const binding = this.#sourceBinding;
92
+ return binding?.available() && binding.workItemRevisionReady?.() ? binding.port.inspectWorkItemRevisionReadiness?.({ owner }) : undefined;
93
+ },
94
+ inspectWorkItemRevisionTargets: () => {
95
+ const binding = this.#sourceBinding;
96
+ return binding?.available() && binding.workItemRevisionReady?.()
97
+ ? binding.port.inspectCreatedCapabilityRevisionTargets?.() ?? [] : [];
98
+ },
99
+ inspectCreationAcceptanceAuthority: () => this.#sourceBinding?.port.inspectSourceCreationAcceptanceAuthority?.(),
100
+ inspectRevisionAcceptanceAuthority: () => this.#sourceBinding?.port.inspectSourceRevisionAcceptanceAuthority?.(),
101
+ inspectRevisionRegressionAcceptanceAuthority: () => this.#sourceBinding?.port.inspectSourceRevisionRegressionAcceptanceAuthority?.(),
102
+ });
103
+ usageCtx.effect(() => async () => {
104
+ if (this.#usage === usage)
105
+ this.#usage = undefined;
106
+ await usage.close();
107
+ }, 'assistant-growth-driver.usage-learning');
108
+ this.#usage = usage;
109
+ usage.start();
110
+ this.#sourceBinding?.nudge();
111
+ });
112
+ }
113
+ if (this.#config.pluginSourceProposals.enabled
114
+ && this.#config.scope !== null
115
+ && this.#config.pluginSourceProposals.repository !== null) {
116
+ // Optional provider lives in a nested injection. Its generation owns the
117
+ // source capability and cancellation; the outer driver remains usable
118
+ // when the control plane is absent or is being replaced.
119
+ ctx.inject(['pluginControlPlane'], sourceCtx => {
120
+ const abort = new AbortController();
121
+ const current = () => {
122
+ abort.signal.throwIfAborted();
123
+ return sourceCtx.get('pluginControlPlane');
124
+ };
125
+ const provider = current();
126
+ const durable = this.#config.pluginSourceProposals.preparationMode === 'durable';
127
+ // Bind API seams, not this generation's availability. Automations can
128
+ // appear after the control plane: canEnqueueSource then changes from
129
+ // false to true without a control-plane reload.
130
+ const seamsPresent = durable
131
+ ? typeof provider.canEnqueueSource === 'function' && typeof provider.enqueueSourceJob === 'function' && typeof provider.inspectSourceJob === 'function'
132
+ : typeof provider.canPrepareSource === 'function' && typeof provider.prepareModifySourcePlan === 'function';
133
+ if (!seamsPresent || typeof provider.inspectSource !== 'function')
134
+ return;
135
+ const producerAvailable = this.#config.usageLearning.enabled
136
+ && typeof provider.registerSourceGrowthRunProducer === 'function';
137
+ const revisionSeamsPresent = durable && this.#config.pluginSourceProposals.allowRevision && producerAvailable
138
+ && typeof provider.getSourceRevisionNamespace === 'function'
139
+ && typeof provider.inspectSourceRevisionAcceptanceAuthority === 'function'
140
+ && typeof provider.inspectCreatedCapabilityRevisionTargets === 'function'
141
+ && typeof provider.inspectRevisionSource === 'function';
142
+ if (producerAvailable)
143
+ sourceCtx.effect(() => provider.registerSourceGrowthRunProducer(this.#config.usageLearning.workItemFailures ? {
144
+ protocol: 'assistant-growth-source-run-producer/v2',
145
+ inspect: request => {
146
+ if (!this.#usage)
147
+ throw new SourceGrowthRunUnavailableError('usage runtime is temporarily unavailable');
148
+ return this.#usage.inspectAnySourceGrowthRun(request);
149
+ },
150
+ withWorkItemRunFence: (request, callback) => {
151
+ if (!this.#usage)
152
+ throw new SourceGrowthRunUnavailableError('usage runtime is temporarily unavailable');
153
+ return this.#usage.withWorkItemRunFence(request, callback);
154
+ },
155
+ } : {
156
+ protocol: 'assistant-growth-source-run-producer/v1',
157
+ inspect: request => {
158
+ if (!this.#usage)
159
+ throw new SourceGrowthRunUnavailableError('usage runtime is temporarily unavailable');
160
+ return this.#usage.inspectSourceGrowthRun(request);
161
+ },
162
+ }), 'assistant-growth-driver.source-run-producer');
163
+ const binding = {
164
+ signal: abort.signal,
165
+ recordWorkItemFailure: (source) => {
166
+ const live = current();
167
+ if (typeof live.recordOwnerWorkItemFailureGap !== 'function')
168
+ throw new Error('control plane work item gap API unavailable');
169
+ return live.recordOwnerWorkItemFailureGap(source);
170
+ },
171
+ recordTaskFailure: (source) => {
172
+ const live = current();
173
+ if (typeof live.recordOwnerTaskFailureGap !== 'function')
174
+ throw new Error('control plane owner task gap API unavailable');
175
+ return live.recordOwnerTaskFailureGap(source);
176
+ },
177
+ available: () => {
178
+ try {
179
+ const live = current();
180
+ return durable ? live.canEnqueueSource?.() === true : live.canPrepareSource?.() === true;
181
+ }
182
+ catch {
183
+ return false;
184
+ }
185
+ },
186
+ taskCreationReady: () => producerAvailable && this.#usage !== undefined,
187
+ workItemCreationReady: () => {
188
+ try {
189
+ const live = current();
190
+ return producerAvailable && this.#usage !== undefined && typeof live.inspectWorkItemCreationReadiness === 'function'
191
+ && typeof live.recordOwnerWorkItemFailureGap === 'function' && typeof live.inspectCreateSource === 'function'
192
+ && typeof live.getSourceCreationNamespace === 'function' && typeof live.inspectSourceCreationAcceptanceAuthority === 'function';
193
+ }
194
+ catch {
195
+ return false;
196
+ }
197
+ },
198
+ workItemRevisionReady: () => {
199
+ try {
200
+ const live = current();
201
+ return producerAvailable && this.#usage !== undefined && typeof live.inspectWorkItemRevisionReadiness === 'function'
202
+ && typeof live.getSourceRevisionNamespace === 'function' && typeof live.inspectSourceRevisionAcceptanceAuthority === 'function';
203
+ }
204
+ catch {
205
+ return false;
206
+ }
207
+ },
208
+ taskRevisionReady: () => revisionSeamsPresent && this.#usage !== undefined,
209
+ nudge: () => { if (producerAvailable)
210
+ current().reconcileSourceGrowthRuns?.(); },
211
+ port: {
212
+ listOpenGaps: () => current().gaps(50),
213
+ inspectWorkItemCreationReadiness: input => current().inspectWorkItemCreationReadiness?.(input),
214
+ inspectWorkItemRevisionReadiness: input => current().inspectWorkItemRevisionReadiness?.(input),
215
+ ...(typeof provider.inspectSourceTargets === 'function'
216
+ ? { inspectSourceTargets: async (input) => {
217
+ const signal = AbortSignal.any([input.signal, abort.signal, this.#abort.signal]);
218
+ const live = current();
219
+ if (typeof live.inspectSourceTargets !== 'function')
220
+ throw new Error('control plane source targets API unavailable');
221
+ return live.inspectSourceTargets({ ...input, signal,
222
+ assertCurrent: () => { signal.throwIfAborted(); current(); input.assertCurrent(); },
223
+ });
224
+ } }
225
+ : {}),
226
+ inspectSource: async (input) => {
227
+ const signal = AbortSignal.any([input.signal, abort.signal, this.#abort.signal]);
228
+ return current().inspectSource({ ...input, signal,
229
+ assertCurrent: () => { signal.throwIfAborted(); current(); input.assertCurrent(); },
230
+ });
231
+ },
232
+ ...(durable && this.#config.pluginSourceProposals.allowCreation
233
+ && typeof provider.inspectCreateSource === 'function' && typeof provider.getSourceCreationNamespace === 'function'
234
+ ? { inspectCreateSource: async (input) => {
235
+ const signal = AbortSignal.any([input.signal, abort.signal, this.#abort.signal]);
236
+ const live = current();
237
+ if (typeof live.inspectCreateSource !== 'function')
238
+ throw new Error('control plane creation source API unavailable');
239
+ return live.inspectCreateSource({ ...input, signal,
240
+ assertCurrent: () => { signal.throwIfAborted(); current(); input.assertCurrent(); },
241
+ });
242
+ },
243
+ getSourceCreationNamespace: () => {
244
+ const namespace = current().getSourceCreationNamespace?.();
245
+ return namespace === undefined ? undefined : { namePrefix: namespace.namePrefix };
246
+ },
247
+ inspectSourceCreationAcceptanceAuthority: () => current().inspectSourceCreationAcceptanceAuthority?.() }
248
+ : {}),
249
+ ...(revisionSeamsPresent ? {
250
+ getSourceRevisionNamespace: () => {
251
+ const namespace = current().getSourceRevisionNamespace?.();
252
+ return namespace === undefined ? undefined : { namePrefix: namespace.namePrefix };
253
+ },
254
+ inspectSourceRevisionAcceptanceAuthority: () => current().inspectSourceRevisionAcceptanceAuthority?.(),
255
+ inspectSourceRevisionRegressionAcceptanceAuthority: () => current().inspectSourceRevisionRegressionAcceptanceAuthority?.(),
256
+ inspectCreatedCapabilityRevisionTargets: () => {
257
+ const live = current();
258
+ if (typeof live.inspectCreatedCapabilityRevisionTargets !== 'function')
259
+ throw new Error('control plane revision targets unavailable');
260
+ return live.inspectCreatedCapabilityRevisionTargets();
261
+ },
262
+ inspectRevisionSource: async (request) => {
263
+ const signal = AbortSignal.any([request.signal, abort.signal, this.#abort.signal]);
264
+ const live = current();
265
+ if (typeof live.inspectRevisionSource !== 'function')
266
+ throw new Error('control plane revision source unavailable');
267
+ return live.inspectRevisionSource({ ...request, signal,
268
+ assertCurrent: () => { signal.throwIfAborted(); current(); request.assertCurrent(); },
269
+ });
270
+ },
271
+ } : {}),
272
+ prepareModifySourcePlan: async (input) => {
273
+ const signal = AbortSignal.any([input.signal, abort.signal, this.#abort.signal]);
274
+ return current().prepareModifySourcePlan({ ...input, signal,
275
+ assertCurrent: () => { signal.throwIfAborted(); current(); input.assertCurrent(); },
276
+ });
277
+ },
278
+ enqueueSourceJob: async (input) => {
279
+ const signal = AbortSignal.any([input.signal, abort.signal, this.#abort.signal]);
280
+ // Do not add route/configuration/timeout fields here. The
281
+ // control-plane durable authority owns those independently.
282
+ return current().enqueueSourceJob({ ...input, signal,
283
+ assertCurrent: () => { signal.throwIfAborted(); current(); input.assertCurrent(); },
284
+ });
285
+ },
286
+ inspectSourceJob: (input) => current().inspectSourceJob(input),
287
+ },
288
+ };
289
+ this.#sourceBinding = binding;
290
+ sourceCtx.effect(() => () => {
291
+ abort.abort(new Error('assistant-growth-driver: source provider changed'));
292
+ if (this.#sourceBinding === binding)
293
+ this.#sourceBinding = undefined;
294
+ }, 'assistant-growth-driver.source-provider');
295
+ binding.nudge();
296
+ if (this.#config.usageLearning.workItemFailures)
297
+ this.#usage?.scan();
298
+ });
299
+ }
300
+ }
301
+ // Cordis traces public service calls through a proxy. Bind these entry points
302
+ // to the owning instance so private state and the wake's Fiber stay intact.
303
+ health = () => this.#health;
304
+ usageHealth = () => this.#usage?.health() ?? { enabled: this.#config.usageLearning.enabled, connected: false };
305
+ async #reviewUsage(input) {
306
+ // Unlike timer nudges, a durable job must run its own frozen source, never
307
+ // coalesce onto an unrelated manual wake and report that wake as its result.
308
+ while (this.#flight !== undefined) {
309
+ await this.#flight;
310
+ input.assertCurrent();
311
+ }
312
+ input.assertCurrent();
313
+ let outcome = 'unknown';
314
+ const flight = this.#runWake({ usage: input }).then(() => {
315
+ outcome = this.#health.outcome === 'ran' && this.#health.run?.outcome === 'succeeded' ? 'reviewed' : 'unknown';
316
+ }).finally(() => { if (this.#flight === flight)
317
+ this.#flight = undefined; });
318
+ this.#flight = flight;
319
+ await flight;
320
+ return outcome;
321
+ }
322
+ /** Run one wake immediately (also used by tests / an explicit Host trigger). */
323
+ wake = (input = {}) => {
324
+ if (!this.#active || !this.#config.enabled)
325
+ return Promise.resolve();
326
+ // Coalesce explicit and timer wakes onto the same bounded run. Queueing
327
+ // timer ticks would build an unbounded backlog when a build is slow.
328
+ if (this.#flight !== undefined)
329
+ return this.#flight;
330
+ const flight = this.#runWake(input).finally(() => { if (this.#flight === flight)
331
+ this.#flight = undefined; });
332
+ this.#flight = flight;
333
+ return flight;
334
+ };
335
+ async #resolveCredential() {
336
+ // Without an explicit credential reference the adapter/provider owns its
337
+ // own credential, so the driver has nothing to resolve.
338
+ const env = this.#config.apiKeyEnv;
339
+ if (env === null)
340
+ return true;
341
+ const credentials = this.ctx.get('credentials', false);
342
+ const resolved = credentials === undefined ? undefined : (await credentials.resolve(credentialRef(env)))?.value;
343
+ const key = resolved ?? process.env[env];
344
+ return typeof key === 'string' && key.length > 0;
345
+ }
346
+ async #runWake(input) {
347
+ const wakeId = input.usage?.id ?? `growth-wake-${Date.now()}-${randomUUID()}`;
348
+ const startedAt = Date.now();
349
+ const workItemUsage = input.usage !== undefined && 'sourceKind' in input.usage && input.usage.sourceKind === 'work-item' ? input.usage : undefined;
350
+ // The revision corridor is enabled per wake only for jobs frozen as
351
+ // revise-created; creation wakes keep the historical revision-forced-off
352
+ // configuration exactly.
353
+ const config = workItemUsage
354
+ ? { ...this.#config, pluginSourceProposals: { ...this.#config.pluginSourceProposals,
355
+ allowModification: false, allowRevision: workItemUsage.corridor === 'revise-created' } }
356
+ : this.#config;
357
+ if (!config.scope) {
358
+ this.#health = { lastWakeAt: startedAt, outcome: 'skipped', reason: 'missing-scope', run: null };
359
+ return;
360
+ }
361
+ const delivery = unwrapService(this.ctx.get('assistantDelivery'));
362
+ const policy = unwrapService(this.ctx.get('assistantPolicy', false));
363
+ const goals = unwrapService(this.ctx.get('assistantGoals'));
364
+ const skills = unwrapService(this.ctx.get('assistantSkills'));
365
+ // ---- preflight (no network, no agent) ----
366
+ let authority;
367
+ try {
368
+ authority = mintGrowthAuthority(delivery, config.scope, startedAt + config.maxDurationMs, input.usage !== undefined);
369
+ if (input.usage) {
370
+ const base = authority, usage = input.usage;
371
+ authority = Object.freeze({ ...base, assertCurrent() { base.assertCurrent(); usage.assertCurrent(); } });
372
+ authority.assertCurrent();
373
+ }
374
+ }
375
+ catch (error) {
376
+ this.#health = { lastWakeAt: startedAt, outcome: 'skipped', reason: `missing-binding:${errorMessage(error)}`, run: null };
377
+ return;
378
+ }
379
+ let model;
380
+ let modelFailure;
381
+ try {
382
+ const selected = input.usage?.model ?? (config.provider !== null && config.model !== null
383
+ ? { provider: config.provider, model: config.model,
384
+ ...(config.reasoningEffort === null ? {} : { reasoningEffort: config.reasoningEffort }) }
385
+ : delivery.inspectOwnerModelSelection({ authorityId: config.scope.ownerRouteId,
386
+ principalId: config.scope.principalId, workspace: config.scope.workspace,
387
+ agentPreset: config.scope.preset,
388
+ ...(input.sourceAgent === undefined ? {} : { sourceAgent: input.sourceAgent }) }));
389
+ if (!selected.provider || !selected.model)
390
+ throw new Error('owner model selection is unavailable');
391
+ model = Object.freeze({ provider: selected.provider, model: selected.model,
392
+ ...(selected.reasoningEffort === undefined ? {} : { reasoningEffort: ReasoningEffortId(selected.reasoningEffort) }) });
393
+ authority.assertCurrent();
394
+ }
395
+ catch (error) {
396
+ modelFailure = errorMessage(error);
397
+ }
398
+ // Owner-anchored workflow learning is a separate, purely Host-local track.
399
+ // It needs only the anchored owner authority and performs no model/network
400
+ // call, so it runs before the credential/budget gates. Failure here never
401
+ // blocks the model-driven skill track below.
402
+ let ownerAnchored;
403
+ if (config.workflowOwnerAnchored.enabled && workItemUsage === undefined) {
404
+ ownerAnchored = await this.#runOwnerAnchoredTrack({
405
+ startedAt, authority, goals, delivery: delivery,
406
+ });
407
+ }
408
+ let dreamingIntake = config.dreamingIdeas.enabled && input.usage === undefined
409
+ ? Object.freeze({ enabled: false, considered: 0, ingested: 0, rejectedUnvalidated: 0, ideaIds: Object.freeze([]) })
410
+ : undefined;
411
+ const spreadDreamingHealth = dreamingIntake === undefined ? {} : { dreamingIntake };
412
+ let associationIntake = config.associationCandidates.enabled && input.usage === undefined
413
+ ? Object.freeze({ enabled: false, considered: 0, ingested: 0, rejectedUnverified: 0, candidateIds: Object.freeze([]) })
414
+ : undefined;
415
+ const spreadAssociationHealth = associationIntake === undefined ? {} : { associationIntake };
416
+ if (model === undefined || modelFailure !== undefined) {
417
+ this.#health = { lastWakeAt: startedAt, outcome: 'skipped', reason: `missing-model:${modelFailure ?? 'unavailable'}`, run: null, ownerAnchored, ...spreadDreamingHealth, ...spreadAssociationHealth };
418
+ return;
419
+ }
420
+ if (!await this.#resolveCredential()) {
421
+ this.#health = { lastWakeAt: startedAt, outcome: 'skipped', reason: 'missing-credential', run: null, ownerAnchored, ...spreadDreamingHealth, ...spreadAssociationHealth };
422
+ return;
423
+ }
424
+ if (policy === undefined) {
425
+ this.#health = { lastWakeAt: startedAt, outcome: 'skipped', reason: 'missing-policy', run: null, ownerAnchored, ...spreadDreamingHealth, ...spreadAssociationHealth };
426
+ return;
427
+ }
428
+ let reservationId;
429
+ let reservationSettled = false;
430
+ let agentSubmitted = false;
431
+ if (input.usage === undefined && config.budgetId !== null && config.budgetAmount !== null) {
432
+ try {
433
+ const reservation = policy.reserve({
434
+ budgetId: config.budgetId,
435
+ subject: { kind: 'background', id: wakeId, workspace: config.scope.workspace, principal: config.scope.principalId },
436
+ amount: config.budgetAmount,
437
+ idempotencyKey: `growth-budget:${wakeId}`,
438
+ });
439
+ if (reservation.status !== 'reserved') {
440
+ this.#health = { lastWakeAt: startedAt, outcome: 'skipped', reason: `budget:${reservation.status}`, run: null, ownerAnchored, ...spreadDreamingHealth, ...spreadAssociationHealth };
441
+ return;
442
+ }
443
+ reservationId = reservation.reservationId;
444
+ }
445
+ catch (error) {
446
+ this.#health = { lastWakeAt: startedAt, outcome: 'skipped', reason: `budget:${errorMessage(error)}`, run: null, ownerAnchored, ...spreadDreamingHealth, ...spreadAssociationHealth };
447
+ return;
448
+ }
449
+ }
450
+ try {
451
+ let validatedDreamIdeas = [];
452
+ if (config.dreamingIdeas.enabled && input.usage === undefined) {
453
+ try {
454
+ const intake = readValidatedDreamIdeas(this.ctx, authority, config.dreamingIdeas.maxIdeasPerWake);
455
+ validatedDreamIdeas = intake.ideas;
456
+ dreamingIntake = intake.summary;
457
+ }
458
+ catch (error) {
459
+ authority.assertCurrent();
460
+ this.ctx.logger.warn(`assistant-growth-driver: dreamingIdeas intake fallback: ${errorMessage(error)}`);
461
+ }
462
+ }
463
+ const nextDreamingHealth = dreamingIntake === undefined ? {} : { dreamingIntake };
464
+ let associationCandidates = [];
465
+ if (config.associationCandidates.enabled && input.usage === undefined) {
466
+ try {
467
+ const intake = readAssociationCandidates(this.ctx, authority, config.associationCandidates.maxCandidatesPerWake);
468
+ associationCandidates = intake.candidates;
469
+ associationIntake = intake.summary;
470
+ }
471
+ catch (error) {
472
+ authority.assertCurrent();
473
+ this.ctx.logger.warn(`assistant-growth-driver: associationCandidates intake fallback: ${errorMessage(error)}`);
474
+ }
475
+ }
476
+ const nextAssociationHealth = associationIntake === undefined ? {} : { associationIntake };
477
+ agentSubmitted = true;
478
+ const bound = this.#sourceBinding;
479
+ const source = bound !== undefined && bound.available() ? bound : undefined;
480
+ if (workItemUsage && !source)
481
+ throw new Error('work item growth requires its current source plane');
482
+ let sourcePort = source?.port;
483
+ if (source && input.usage) {
484
+ const usage = input.usage;
485
+ const ownGaps = () => {
486
+ usage.assertCurrent();
487
+ return usage.source.protocol === 'assistant-delivery/work-item-engineering-context/v1'
488
+ ? [source.recordWorkItemFailure({ task: usage.source.task, manifest: usage.source.manifest, objective: usage.source.objective })]
489
+ : usage.source.canonical.objective?.status === 'not-achieved' ? [source.recordTaskFailure(usage.source)] : [];
490
+ };
491
+ // Persist the exact failure before submitting the model; neither a
492
+ // model assertion nor an operator's global gap is a prerequisite.
493
+ ownGaps();
494
+ const assertGap = (gapId) => {
495
+ if (!ownGaps().some(gap => gap.id === gapId && gap.status === 'open' && gap.candidateId === undefined)) {
496
+ throw new Error('source gap is not the current task failure');
497
+ }
498
+ };
499
+ const taskPort = { ...source.port, listOpenGaps: ownGaps,
500
+ prepareModifySourcePlan: request => { if (workItemUsage)
501
+ throw new Error('work item growth only permits creation or revision'); assertGap(request.gapId); return source.port.prepareModifySourcePlan(request); },
502
+ enqueueSourceJob: request => {
503
+ assertGap(request.gapId);
504
+ const growthRun = this.#usage?.inspectAnySourceGrowthRun({ runId: usage.id, intentDigest: usage.intentDigest });
505
+ if (workItemUsage?.corridor === 'revise-created') {
506
+ // The corridor was frozen as revise-created: only that mode may
507
+ // cross this gate, under a current v3 binding and revision pins.
508
+ if (request.mode !== 'revise-created' || source.workItemRevisionReady?.() !== true
509
+ || growthRun?.protocol !== 'assistant-growth/source-run/v3' || growthRun.revisionAcceptance === undefined) {
510
+ throw new Error('assistant-growth-driver: work item revision lacks its current native source run');
511
+ }
512
+ return source.port.enqueueSourceJob({ ...request, growthRun });
513
+ }
514
+ if (request.mode === 'create' && (!source.taskCreationReady() || growthRun === undefined)) {
515
+ throw new Error('assistant-growth-driver: task-bound creation lacks a current native source run');
516
+ }
517
+ if (workItemUsage && request.mode !== 'create')
518
+ throw new Error('work item growth only permits creation');
519
+ if (request.mode === 'revise-created' && (!source.taskRevisionReady() || growthRun?.protocol !== 'assistant-growth/source-run/v1' || growthRun.revisionAcceptance === undefined)) {
520
+ throw new Error('assistant-growth-driver: task-bound revision lacks a current native source run');
521
+ }
522
+ return source.port.enqueueSourceJob((request.mode === 'create' || request.mode === 'revise-created') && growthRun !== undefined
523
+ ? { ...request, growthRun } : request);
524
+ },
525
+ };
526
+ // A revise-created corridor never exposes the creation lane: its v3
527
+ // binding cannot authorize creates, so the tool must not appear either.
528
+ const creationSeamsReady = source.taskCreationReady() && workItemUsage?.corridor !== 'revise-created';
529
+ if (!creationSeamsReady) {
530
+ delete taskPort.inspectCreateSource;
531
+ delete taskPort.getSourceCreationNamespace;
532
+ }
533
+ const revisionSeamsReady = workItemUsage === undefined
534
+ ? source.taskRevisionReady() : workItemUsage.corridor === 'revise-created' && source.workItemRevisionReady?.() === true;
535
+ if (!revisionSeamsReady) {
536
+ delete taskPort.getSourceRevisionNamespace;
537
+ delete taskPort.inspectSourceRevisionAcceptanceAuthority;
538
+ delete taskPort.inspectSourceRevisionRegressionAcceptanceAuthority;
539
+ delete taskPort.inspectCreatedCapabilityRevisionTargets;
540
+ delete taskPort.inspectRevisionSource;
541
+ }
542
+ sourcePort = taskPort;
543
+ }
544
+ const run = await runGrowthAgent(this.ctx, { wakeId, authority, config, model, goals, skills,
545
+ ...(sourcePort === undefined ? {} : { sourcePlane: sourcePort }),
546
+ ...(validatedDreamIdeas.length === 0 ? {} : { validatedDreamIdeas }),
547
+ ...(associationCandidates.length === 0 ? {} : { associationCandidates }),
548
+ ...(input.usage === undefined ? {} : { feedback: input.usage.source,
549
+ ...(workItemUsage ? { assertFirstModelAdmission: workItemUsage.assertFirstModelAdmission, workItemAuthorization: { runId: workItemUsage.id, intentDigest: workItemUsage.intentDigest, definitionHash: workItemUsage.definitionHash, occurrenceId: workItemUsage.occurrenceId, assertCurrent: workItemUsage.assertCurrent } } : {}),
550
+ generationDeadlineAt: input.usage.expiresAt,
551
+ ...(config.maxToolCalls === 0 ? {} : { onSourceExecution: (actual) => {
552
+ return input.usage.bindSourceRun(actual);
553
+ } }) }),
554
+ signal: AbortSignal.any([this.#abort.signal, ...(source === undefined ? [] : [source.signal]),
555
+ ...(input.usage === undefined ? [] : [input.usage.signal])]), });
556
+ if (reservationId !== undefined) {
557
+ policy.finalize(reservationId, config.budgetAmount);
558
+ reservationSettled = true;
559
+ }
560
+ this.#health = { lastWakeAt: startedAt, outcome: 'ran', reason: run.outcome, run, ownerAnchored, ...nextDreamingHealth, ...nextAssociationHealth };
561
+ }
562
+ catch (error) {
563
+ if (reservationId !== undefined && !reservationSettled) {
564
+ // The agent factory may already have submitted a request: charge the
565
+ // reservation conservatively rather than release potentially-spent budget.
566
+ try {
567
+ if (agentSubmitted)
568
+ policy.finalize(reservationId, config.budgetAmount);
569
+ else
570
+ policy.release(reservationId);
571
+ }
572
+ catch { /* leave the reservation ledger state visible for the owner */ }
573
+ }
574
+ this.#health = { lastWakeAt: startedAt, outcome: 'failed', reason: errorMessage(error), run: null, ownerAnchored, ...(dreamingIntake === undefined ? {} : { dreamingIntake }), ...(associationIntake === undefined ? {} : { associationIntake }) };
575
+ this.ctx.logger.warn(`assistant-growth-driver: wake ${wakeId} failed: ${errorMessage(error)}`);
576
+ }
577
+ }
578
+ /**
579
+ * The owner-anchored workflow track. It only enumerates recently completed
580
+ * owner goals and asks Delivery to independently re-verify and (if the goal
581
+ * honestly reduces to one no-tool agent turn) record a paused candidate. The
582
+ * driver passes ONLY a locator plus the bounded authority — never a prompt,
583
+ * steps or an acceptance verdict — and it never approves, activates or
584
+ * installs anything. A goal that fails the owner-root/achieved evidence bar
585
+ * is skipped; an infrastructure, policy, authority or live-route mismatch
586
+ * fails closed and halts the track for this wake.
587
+ */
588
+ async #runOwnerAnchoredTrack(input) {
589
+ const trackConfig = this.#config.workflowOwnerAnchored;
590
+ const summary = {
591
+ considered: 0, attempted: 0, recorded: 0, replayed: 0, abstained: 0, stopped: null,
592
+ };
593
+ let records;
594
+ try {
595
+ records = input.goals.inspectOwnerGoals(input.authority.scope, 50);
596
+ }
597
+ catch (error) {
598
+ return { ...summary, stopped: `inspect:${errorMessage(error)}` };
599
+ }
600
+ const cutoff = input.startedAt - trackConfig.lookbackMs;
601
+ // Coarse discovery filter only; the whole-goal succeeded/quiescent/achieved
602
+ // and owner-root checks are Delivery's single source of truth at commit.
603
+ const candidates = records.filter(record => record.native.phase === 'complete' && record.updatedAt >= cutoff);
604
+ const mutable = { ...summary };
605
+ mutable.considered = candidates.length;
606
+ for (const record of candidates) {
607
+ if (mutable.attempted >= trackConfig.maxCommitsPerWake)
608
+ break;
609
+ try {
610
+ // Re-anchor before every commit: a revoked/rebound owner route or a
611
+ // principal generation change aborts the rest of the track.
612
+ input.authority.assertCurrent();
613
+ }
614
+ catch (error) {
615
+ mutable.stopped = `authority:${errorMessage(error)}`;
616
+ break;
617
+ }
618
+ // Every locator field comes from the anchored authority (never from the
619
+ // enumerated record or a caller-supplied prompt); only the per-goal
620
+ // sessionId/goalId identify which owner success to re-verify.
621
+ const { principalId, workspace, preset } = input.authority.scope;
622
+ const locator = {
623
+ ownerRouteId: input.authority.ownerRouteId,
624
+ principalId,
625
+ workspace,
626
+ preset,
627
+ sessionId: record.native.sessionId,
628
+ goalId: record.id,
629
+ };
630
+ mutable.attempted += 1;
631
+ try {
632
+ const result = await input.delivery.commitOwnerAnchoredWorkflowTrace({ locator, authority: input.authority });
633
+ if (result.outcome === 'abstained')
634
+ mutable.abstained += 1;
635
+ else if (result.replayed)
636
+ mutable.replayed += 1;
637
+ else
638
+ mutable.recorded += 1;
639
+ }
640
+ catch (error) {
641
+ const code = error?.code;
642
+ const message = errorMessage(error);
643
+ if (code === 'runtime-unavailable' || code === 'policy-denied' || code === 'runtime-conflict'
644
+ || /live owner route|owner route changed|authority expired/u.test(message)) {
645
+ mutable.stopped = `${typeof code === 'string' ? code : 'error'}:${message}`;
646
+ break;
647
+ }
648
+ // Otherwise this completed goal is merely not learnable right now
649
+ // (no current achieved receipt, not owner-root, etc.); keep scanning.
650
+ }
651
+ }
652
+ return Object.freeze(mutable);
653
+ }
654
+ }
655
+ function errorMessage(error) {
656
+ return error instanceof Error ? error.message : String(error);
657
+ }
658
+ export function apply(ctx, input = {}) {
659
+ new AssistantGrowthDriverService(ctx, input);
660
+ }
661
+ export default { name, Config, inject: AssistantGrowthDriverService.inject, apply, version };
662
+ //# sourceMappingURL=index.js.map