@wildo-ai/saas-minions-lib 1.1.5 → 1.1.6

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.
@@ -1 +1 @@
1
- {"version":3,"file":"minion-tick-consumer.backend.service.d.ts","sourceRoot":"","sources":["../../../../../src/runtime/queue/minion-tick-consumer.backend.service.ts"],"names":[],"mappings":"AAEA,OAAO,EAEL,aAAa,EACb,6BAA6B,EAE7B,sCAAsC,EACtC,wBAAwB,EACxB,+BAA+B,EAC/B,+BAA+B,EAC/B,mCAAmC,EAEnC,KAAK,kBAAkB,EACxB,MAAM,4BAA4B,CAAC;AACpC,OAAO,EAEL,KAAK,uBAAuB,EAAE,KAAK,uBAAuB,EAAE,KAAK,uBAAuB,EAAE,KAAK,6BAA6B,EAC7H,MAAM,uBAAuB,CAAC;AAE/B,+GAA+G;AAC/G,MAAM,MAAM,oBAAoB,GAAG,IAAI,CAAC,kBAAkB,EAAE,OAAO,GAAG,eAAe,GAAG,SAAS,GAAG,YAAY,GAAG,eAAe,CAAC,GAAG;IACpI,mFAAmF;IACnF,SAAS,EAAE,IAAI,CAAC;IAChB,qFAAqF;IACrF,WAAW,CAAC,EAAE,IAAI,CAAC;CACpB,CAAC;AAEF,qGAAqG;AACrG,MAAM,MAAM,iBAAiB,GAAG,CAAC,IAAI,EAAE,oBAAoB,EAAE,OAAO,EAAE,uBAAuB,KAAK,OAAO,CAAC,IAAI,CAAC,CAAC;AAChH,MAAM,MAAM,oBAAoB,GAAG,CAAC,IAAI,EAAE,oBAAoB,EAAE,OAAO,EAAE,uBAAuB,KAAK,OAAO,CAAC,6BAA6B,CAAC,CAAC;AAE5I;;;;;;;;;;;;;;;;;;;GAmBG;AACH,qBACa,gCAAgC;IAUzC,OAAO,CAAC,QAAQ,CAAC,OAAO;IAExB,OAAO,CAAC,QAAQ,CAAC,wBAAwB;IAEzC,OAAO,CAAC,QAAQ,CAAC,MAAM;IAMvB,OAAO,CAAC,QAAQ,CAAC,eAAe;IAnBlC,OAAO,CAAC,WAAW,CAAS;IAC5B,OAAO,CAAC,kBAAkB,CAAC,CAAS;IACpC,OAAO,CAAC,QAAQ,CAAC,MAAM,CAA2B;IAClD,OAAO,CAAC,WAAW,CAAC,CAA8D;IAElF,SAAS,CAAC,QAAQ,CAAC,QAAQ,EAAE,CAAC,OAAO,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,KAAK,IAAI,CAAC;gBAIvE,OAAO,EAAE,6BAA6B,EAEtC,wBAAwB,EAAE,sCAAsC,EAEhE,MAAM,EAAE,aAAa,EAEtC,OAAO,EAAE,+BAA+B,EAExC,cAAc,EAAE,+BAA+B,EAE9B,eAAe,EAAE,mCAAmC;IAY1D,KAAK,CAAC,KAAK,EAAE;QACxB;;;;;WAKG;QACH,aAAa,EAAE,MAAM,CAAC;QACtB,UAAU,EAAE,MAAM,CAAC;QACnB,OAAO,CAAC,EAAE,iBAAiB,CAAC;QAC5B,cAAc,CAAC,EAAE,OAAO,CAAC,uBAAuB,CAAC,CAAC;QAClD,cAAc,CAAC,EAAE,uBAAuB,CAAC;QACzC,SAAS,CAAC,EAAE,oBAAoB,CAAC;KAClC,GAAG,OAAO,CAAC,IAAI,CAAC;IA2EJ,IAAI,IAAI,OAAO,CAAC,IAAI,CAAC;IAWlC;;;;OAIG;IACU,iBAAiB,CAC5B,KAAK,EAAE,IAAI,CAAC,UAAU,CAAC,wBAAwB,CAAC,eAAe,CAAC,CAAC,CAAC,CAAC,CAAC,EAAE,WAAW,CAAC,GACjF,OAAO,CAAC,IAAI,CAAC;IAMT,SAAS,IAAI,OAAO;YAIb,aAAa;CAwC5B"}
1
+ {"version":3,"file":"minion-tick-consumer.backend.service.d.ts","sourceRoot":"","sources":["../../../../../src/runtime/queue/minion-tick-consumer.backend.service.ts"],"names":[],"mappings":"AAEA,OAAO,EAEL,aAAa,EACb,6BAA6B,EAE7B,sCAAsC,EACtC,wBA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I,CAAC;gBAIvE,OAAO,EAAE,6BAA6B,EAEtC,wBAAwB,EAAE,sCAAsC,EAEhE,MAAM,EAAE,aAAa,EAEtC,OAAO,EAAE,+BAA+B,EAExC,cAAc,EAAE,+BAA+B,EAE9B,eAAe,EAAE,mCAAmC;IAY1D,KAAK,CAAC,KAAK,EAAE;QACxB;;;;;WAKG;QACH,aAAa,EAAE,MAAM,CAAC;QACtB,UAAU,EAAE,MAAM,CAAC;QACnB,OAAO,CAAC,EAAE,iBAAiB,CAAC;QAC5B,cAAc,CAAC,EAAE,OAAO,CAAC,uBAAuB,CAAC,CAAC;QAClD,cAAc,CAAC,EAAE,uBAAuB,CAAC;QACzC,SAAS,CAAC,EAAE,oBAAoB,CAAC;KAClC,GAAG,OAAO,CAAC,IAAI,CAAC;IA2EJ,IAAI,IAAI,OAAO,CAAC,IAAI,CAAC;IAWlC;;;;OAIG;IACU,iBAAiB,CAC5B,KAAK,EAAE,IAAI,CAAC,UAAU,CAAC,wBAAwB,CAAC,eAAe,CAAC,CAAC,CAAC,CAAC,CAAC,EAAE,WAAW,CAAC,GACjF,OAAO,CAAC,IAAI,CAAC;IAMT,SAAS,IAAI,OAAO;YAIb,aAAa;CA6C5B"}
@@ -151,6 +151,7 @@ let MinionTickConsumerBackendService = class MinionTickConsumerBackendService {
151
151
  }
152
152
  async handleMessage(msg, channel, applicationId, expectedMinionName, queueName, resolver) {
153
153
  this.shutdownManager.jobStarted();
154
+ let admitted;
154
155
  try {
155
156
  let accepted = false;
156
157
  try {
@@ -166,7 +167,9 @@ let MinionTickConsumerBackendService = class MinionTickConsumerBackendService {
166
167
  initiatedBy: JobInitiator.CRONTAB, createdAt: new Date(tick.iat * 1000), maxRetries: 0,
167
168
  scheduledAt: tick.scheduledAt === undefined ? undefined : new Date(tick.scheduledAt),
168
169
  });
169
- await this.runner.receive(job, queueName, resolver);
170
+ // Durable receipt, then acknowledge, THEN run — a long tick must not hold later deliveries
171
+ // unreceived past their five-minute token (`ScheduledExecutionRunner.admit`).
172
+ admitted = await this.runner.admit(job, queueName, resolver);
170
173
  accepted = true;
171
174
  }
172
175
  catch (error) {
@@ -187,6 +190,9 @@ let MinionTickConsumerBackendService = class MinionTickConsumerBackendService {
187
190
  finally {
188
191
  this.shutdownManager.jobCompleted();
189
192
  }
193
+ // Started only after the delivery is settled; the runner tracks the run's own activity.
194
+ if (admitted)
195
+ this.runner.launch(admitted, resolver);
190
196
  }
191
197
  };
192
198
  MinionTickConsumerBackendService = __decorate([
@@ -1 +1 @@
1
- {"version":3,"file":"minion-tick-consumer.backend.service.js","sourceRoot":"","sources":["../../../../../src/runtime/queue/minion-tick-consumer.backend.service.ts"],"names":[],"mappings":";;;;;;;;;;;;AAAA,OAAO,EAAE,MAAM,EAAE,UAAU,EAAE,MAAM,WAAW,CAAC;AAE/C,OAAO,EACL,mBAAmB,EACnB,aAAa,EACb,6BAA6B,EAC7B,kBAAkB,EAClB,sCAAsC,EACtC,wBAAwB,EACxB,+BAA+B,EAC/B,+BAA+B,EAC/B,mCAAmC,GAGpC,MAAM,4BAA4B,CAAC;AACpC,OAAO,EACL,gBAAgB,EAAE,gBAAgB,EAAE,OAAO,EAAE,YAAY,EAAE,SAAS,GAErE,MAAM,uBAAuB,CAAC;AAc/B;;;;;;;;;;;;;;;;;;;GAmBG;AAEI,IAAM,gCAAgC,GAAtC,MAAM,gCAAgC;IAUxB;IAEA;IAEA;IAMA;IAnBX,WAAW,GAAG,KAAK,CAAC;IACpB,kBAAkB,CAAU;IACnB,MAAM,CAA2B;IAC1C,WAAW,CAA+D;IAE/D,QAAQ,CAA+D;IAE1F,YAEmB,OAAsC,EAEtC,wBAAgE,EAEhE,MAAqB,EAEtC,OAAwC,EAExC,cAA+C,EAE9B,eAAoD;QAVpD,YAAO,GAAP,OAAO,CAA+B;QAEtC,6BAAwB,GAAxB,wBAAwB,CAAwC;QAEhE,WAAM,GAAN,MAAM,CAAe;QAMrB,oBAAe,GAAf,eAAe,CAAqC;QAErE,IAAI,C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AC,wBAAwB,CAAC,CAAA;IAEnD,WAAA,MAAM,CAAC,kBAAkB,CAAC,4BAA4B,CAAC,CAAA;qCAT9B,6BAA6B;QAEZ,sCAAsC;QAExD,aAAa;QAE7B,+BAA+B;QAExB,+BAA+B;QAEb,mCAAmC;GApB5D,gCAAgC,CA4L5C","sourcesContent":["import { inject, injectable } from 'inversify';\nimport type { Channel, ConsumeMessage } from 'amqplib';\nimport {\n describeCaughtError,\n LoggerService,\n RabbitMQAdapterBackendService,\n SAAS_SERVICE_TYPES,\n ScheduledMessageVerifierBackendService,\n ScheduledExecutionRunner,\n JobStatusTrackingBackendService,\n JobPayloadStorageBackendService,\n WorkerShutdownManagerBackendService,\n type ScheduledExecutionResolver,\n type MinionTickJobToken,\n} from '@wildo-ai/saas-backend-lib';\nimport {\n QueueNamingUtils, JobPayloadSchema, JobType, JobInitiator, JobStatus,\n type ScheduledAttemptContext, type ScheduledEvidencePolicy, type ScheduledRecoveryPolicy, type ScheduledReconciliationResult,\n} from '@wildo-ai/saas-models';\n\n/** Application payload after authentication; transport credentials are never replayed to recovery handlers. */\nexport type MinionTickInvocation = Pick<MinionTickJobToken, 'jobId' | 'applicationId' | 'jobType' | 'minionName' | 'inputDataJson'> & {\n /** Original authenticated publication time, preserved across recovery attempts. */\n createdAt: Date;\n /** Authenticated cron occurrence time; absent for independent manual invocations. */\n scheduledAt?: Date;\n};\n\n/** Stable occurrence plus a fresh attempt identity; retries are owned by the durable coordinator. */\nexport type MinionTickHandler = (tick: MinionTickInvocation, attempt: ScheduledAttemptContext) => Promise<void>;\nexport type MinionTickReconciler = (tick: MinionTickInvocation, attempt: ScheduledAttemptContext) => Promise<ScheduledReconciliationResult>;\n\n/**\n * Minion-side consumer for the per-minion tick queue\n * (`wildo.queue.<appId>.minion-tick.<minionName>`, see `QueueNamingUtils.buildMinionTickQueueName`).\n *\n * Per KD-12 of `.claude/plans/minions-and-workers-implementation.md`:\n * - Subscribes only to the queue dedicated to THIS minion (no shared\n * `scheduled` queue subscription, so the backend-api and minion don't\n * compete on cron tick deliveries).\n * - Verifies every inbound JWT through\n * `ScheduledMessageVerifierBackendService.verifyAndExtractMinionTick(token, expectedMinionName)`\n * — invalid signature, malformed payload, wrong issuer/audience, or\n * wrong target minion all NACK without requeue.\n * - Dispatches `MINION_TICK` tokens that match this minion's identity to\n * the registered handler. The handler typically routes into the\n * locally-hosted `flowsActorsRegistry` per Q9 LOCKED.\n *\n * Duplicate deliveries and recovery of one occurrence belong to the durable\n * coordinator. Overlap between DISTINCT occurrences remains the handler's\n * responsibility; these are separate guarantees.\n */\n@injectable()\nexport class MinionTickConsumerBackendService {\n private isConsuming = false;\n private consumingQueueName?: string;\n private readonly runner: ScheduledExecutionRunner;\n private reviewScope?: { queueName: string; resolver: ScheduledExecutionResolver };\n\n protected readonly logDebug: (message: string, context?: Record<string, unknown>) => void;\n\n constructor(\n @inject(SAAS_SERVICE_TYPES.RabbitMQAdapterService)\n private readonly adapter: RabbitMQAdapterBackendService,\n @inject(SAAS_SERVICE_TYPES.ScheduledMessageVerifierService)\n private readonly scheduledMessageVerifier: ScheduledMessageVerifierBackendService,\n @inject(SAAS_SERVICE_TYPES.Logger)\n private readonly logger: LoggerService,\n @inject(SAAS_SERVICE_TYPES.JobStatusTrackingService)\n tracker: JobStatusTrackingBackendService,\n @inject(SAAS_SERVICE_TYPES.JobPayloadStorageService)\n payloadStorage: JobPayloadStorageBackendService,\n @inject(SAAS_SERVICE_TYPES.WorkerShutdownManagerService)\n private readonly shutdownManager: WorkerShutdownManagerBackendService,\n ) {\n this.runner = new ScheduledExecutionRunner(tracker, logger, payloadStorage, {\n started: () => shutdownManager.jobStarted(),\n completed: () => shutdownManager.jobCompleted(),\n });\n // Stop broker receipts and recovery admissions before the shared signal coordinator drains work.\n shutdownManager.registerStopHandler(() => this.stop());\n this.logDebug = this.logger.debugByType('MinionTickConsumerBackendService');\n this.logger.setDebugTypeLogging('MinionTickConsumerBackendService', false);\n }\n\n public async start(input: {\n /**\n * The PLATFORM's id for the application this minion serves — the id its tick queue is named\n * from and the id the crontabs-manager signs into every tick. It is addressing, never a row\n * identity: the tick rows and stored payloads are anchored by the tracker and the payload\n * storage to the application RECORD id, which they resolve themselves.\n */\n applicationId: string;\n minionName: string;\n handler?: MinionTickHandler;\n recoveryPolicy?: Partial<ScheduledRecoveryPolicy>;\n evidencePolicy?: ScheduledEvidencePolicy;\n reconcile?: MinionTickReconciler;\n }): Promise<void> {\n if (this.isConsuming) {\n throw new Error('MinionTickConsumerBackendService.start called while already consuming.');\n }\n\n const { applicationId, minionName, handler, recoveryPolicy, evidencePolicy, reconcile } = input;\n // The scanner resolves only this runtime's locally authored handler. Durable input\n // is trusted after first receipt; it is never turned back into a signed JWT.\n const resolver: ScheduledExecutionResolver = async (job) => {\n if (job.applicationId !== applicationId || job.jobType !== JobType.MINION_TICK || job.minionName !== minionName || !handler) return undefined;\n const tick: MinionTickInvocation = {\n jobId: job.jobId, applicationId, jobType: JobType.MINION_TICK, minionName,\n inputDataJson: job.inputDataJson, createdAt: job.createdAt, scheduledAt: job.scheduledAt,\n };\n return {\n policy: recoveryPolicy,\n evidencePolicy,\n execute: async (attempt) => {\n const startedAt = Date.now();\n await handler(tick, attempt);\n return { jobId: job.jobId, status: JobStatus.COMPLETED, startedAt: new Date(startedAt), durationMs: Date.now() - startedAt, completedAt: new Date() };\n },\n reconcile: reconcile ? (attempt) => reconcile(tick, attempt) : undefined,\n };\n };\n const queueName = QueueNamingUtils.buildMinionTickQueueName(applicationId, minionName);\n\n // M5 — adapter readiness guard. The minion entrypoint calls this\n // method AFTER `StartApplicationBackendService.initialize`, which\n // typically connects the RabbitMQ adapter. Throw a descriptive\n // error if the adapter is not connected so a misconfigured\n // bootstrap surfaces here rather than at the first cron tick.\n if (!this.adapter.isConnected()) {\n throw new Error(\n 'MinionTickConsumerBackendService.start called before the RabbitMQ adapter connected. ' +\n 'Ensure the minion bootstrap completes before subscribing to the tick queue.',\n );\n }\n\n // H2 — the minion runtime OWNS and declares this per-minion tick queue.\n // The crontabs-batches-manager publisher is a producer only and passively\n // verifies the queue (`checkQueue`) rather than declaring it, so there is no\n // publisher-side declaration whose args this must match — the minion is the\n // sole topology owner here. `durable: true` + `x-queue-type: 'quorum'` is\n // the minion's own chosen shape (durable so ticks survive a broker restart).\n //\n // Declared on the adapter's dedicated topology channel (not the primary\n // publish/consume channel): a `406` arg-mismatch against a pre-existing\n // incompatible queue closes only that channel, so it can't tear down the\n // primary channel and crash-loop the minion bootstrap. The\n // `x-queue-type: 'quorum'` argument is not modelled by `QueueAssertOptions`,\n // so we declare directly on the channel rather than via `adapter.assertQueue`.\n const channel = await this.adapter.getTopologyChannel();\n await channel.assertQueue(queueName, {\n durable: true,\n arguments: {\n 'x-queue-type': 'quorum',\n },\n });\n\n await this.adapter.consume(queueName, async (msg: ConsumeMessage, channel: Channel) => {\n await this.handleMessage(msg, channel, applicationId, minionName, queueName, resolver);\n });\n\n this.consumingQueueName = queueName;\n this.isConsuming = true;\n this.runner.start(queueName, resolver);\n this.reviewScope = { queueName, resolver };\n this.logger.info('Minion tick consumer started', {\n queueName,\n applicationId,\n minionName,\n });\n }\n\n public async stop(): Promise<void> {\n this.runner.stop();\n this.reviewScope = undefined;\n if (!this.isConsuming || !this.consumingQueueName) {\n return;\n }\n await this.adapter.cancelConsumer(this.consumingQueueName);\n this.isConsuming = false;\n this.consumingQueueName = undefined;\n }\n\n /**\n * Invoke from an application-owned operator operation AFTER authorization.\n * Runtime app/queue ownership is derived here, never supplied by the caller;\n * actor, reason and expected revision are persisted atomically with the decision.\n */\n public async resolveTickReview(\n input: Omit<Parameters<ScheduledExecutionRunner['resolveReview']>[0], 'queueName'>,\n ): Promise<void> {\n const scope = this.reviewScope;\n if (!scope) throw new Error('Minion tick review requires an initialized consumer');\n await this.runner.resolveReview({ ...input, queueName: scope.queueName }, scope.resolver);\n }\n\n public isRunning(): boolean {\n return this.isConsuming;\n }\n\n private async handleMessage(\n msg: ConsumeMessage,\n channel: Channel,\n applicationId: string,\n expectedMinionName: string,\n queueName: string,\n resolver: ScheduledExecutionResolver,\n ): Promise<void> {\n this.shutdownManager.jobStarted();\n try {\n let accepted = false;\n try {\n const tick = await this.scheduledMessageVerifier.verifyAndExtractMinionTick(msg.content.toString(), expectedMinionName);\n // Signature/target checks do not establish receiving-application ownership.\n // This comparison must precede every durable insert and handler resolution.\n if (!tick || tick.applicationId !== applicationId || tick.minionName !== expectedMinionName) {\n throw new Error('Scheduled minion token does not match the receiving application and minion');\n }\n const job = JobPayloadSchema.parse({\n jobId: tick.jobId, jobType: JobType.MINION_TICK, applicationId: tick.applicationId,\n minionName: tick.minionName, inputDataJson: tick.inputDataJson,\n initiatedBy: JobInitiator.CRONTAB, createdAt: new Date(tick.iat * 1000), maxRetries: 0,\n scheduledAt: tick.scheduledAt === undefined ? undefined : new Date(tick.scheduledAt),\n });\n await this.runner.receive(job, queueName, resolver);\n accepted = true;\n } catch (error) {\n this.logger.error('Minion tick admission failed', { expectedMinionName, error: describeCaughtError(error) });\n }\n\n // Settlement failure is a broker problem, not a new business failure. Never\n // NACK after an ACK throws or run the handler again from this catch boundary.\n try {\n if (accepted) channel.ack(msg);\n else channel.nack(msg, false, false);\n } catch (error) {\n this.logger.error('Minion tick settlement failed', { expectedMinionName, error: describeCaughtError(error) });\n }\n } finally { this.shutdownManager.jobCompleted(); }\n }\n}\n"]}
1
+ {"version":3,"file":"minion-tick-consumer.backend.service.js","sourceRoot":"","sources":["../../../../../src/runtime/queue/minion-tick-consumer.backend.service.ts"],"names":[],"mappings":";;;;;;;;;;;;AAAA,OAAO,EAAE,MAAM,EAAE,UAAU,EAAE,MAAM,WAAW,CAAC;AAE/C,OAAO,EACL,mBAAmB,EACnB,aAAa,EACb,6BAA6B,EAC7B,kBAAkB,EAClB,sCAAsC,EACtC,wBAAwB,EACxB,+BAA+B,EAC/B,+BAA+B,EAC/B,mCAAmC,GAGpC,MAAM,4BAA4B,CAAC;AACpC,OAAO,EACL,gBAAgB,E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CAAC;YACvC,CAAC;YAAC,OAAO,KAAK,EAAE,CAAC;gBACf,IAAI,CAAC,MAAM,CAAC,KAAK,CAAC,+BAA+B,EAAE,EAAE,kBAAkB,EAAE,KAAK,EAAE,mBAAmB,CAAC,KAAK,CAAC,EAAE,CAAC,CAAC;YAChH,CAAC;QACH,CAAC;gBAAS,CAAC;YAAC,IAAI,CAAC,eAAe,CAAC,YAAY,EAAE,CAAC;QAAC,CAAC;QAClD,wFAAwF;QACxF,IAAI,QAAQ;YAAE,IAAI,CAAC,MAAM,CAAC,MAAM,CAAC,QAAQ,EAAE,QAAQ,CAAC,CAAC;IACvD,CAAC;CACF,CAAA;AAjMY,gCAAgC;IAD5C,UAAU,EAAE;IAUR,WAAA,MAAM,CAAC,kBAAkB,CAAC,sBAAsB,CAAC,CAAA;IAEjD,WAAA,MAAM,CAAC,kBAAkB,CAAC,+BAA+B,CAAC,CAAA;IAE1D,WAAA,MAAM,CAAC,kBAAkB,CAAC,MAAM,CAAC,CAAA;IAEjC,WAAA,MAAM,CAAC,kBAAkB,CAAC,wBAAwB,CAAC,CAAA;IAEnD,WAAA,MAAM,CAAC,kBAAkB,CAAC,wBAAwB,CAAC,CAAA;IAEnD,WAAA,MAAM,CAAC,kBAAkB,CAAC,4BAA4B,CAAC,CAAA;qCAT9B,6BAA6B;QAEZ,sCAAsC;QAExD,aAAa;QAE7B,+BAA+B;QAExB,+BAA+B;QAEb,mCAAmC;GApB5D,gCAAgC,CAiM5C","sourcesContent":["import { inject, injectable } from 'inversify';\nimport type { Channel, ConsumeMessage } from 'amqplib';\nimport {\n describeCaughtError,\n LoggerService,\n RabbitMQAdapterBackendService,\n SAAS_SERVICE_TYPES,\n ScheduledMessageVerifierBackendService,\n ScheduledExecutionRunner,\n JobStatusTrackingBackendService,\n JobPayloadStorageBackendService,\n WorkerShutdownManagerBackendService,\n type ScheduledExecutionResolver,\n type MinionTickJobToken,\n} from '@wildo-ai/saas-backend-lib';\nimport {\n QueueNamingUtils, JobPayloadSchema, JobType, JobInitiator, JobStatus,\n type JobExecution, type ScheduledAttemptContext, type ScheduledEvidencePolicy, type ScheduledRecoveryPolicy, type ScheduledReconciliationResult,\n} from '@wildo-ai/saas-models';\n\n/** Application payload after authentication; transport credentials are never replayed to recovery handlers. */\nexport type MinionTickInvocation = Pick<MinionTickJobToken, 'jobId' | 'applicationId' | 'jobType' | 'minionName' | 'inputDataJson'> & {\n /** Original authenticated publication time, preserved across recovery attempts. */\n createdAt: Date;\n /** Authenticated cron occurrence time; absent for independent manual invocations. */\n scheduledAt?: Date;\n};\n\n/** Stable occurrence plus a fresh attempt identity; retries are owned by the durable coordinator. */\nexport type MinionTickHandler = (tick: MinionTickInvocation, attempt: ScheduledAttemptContext) => Promise<void>;\nexport type MinionTickReconciler = (tick: MinionTickInvocation, attempt: ScheduledAttemptContext) => Promise<ScheduledReconciliationResult>;\n\n/**\n * Minion-side consumer for the per-minion tick queue\n * (`wildo.queue.<appId>.minion-tick.<minionName>`, see `QueueNamingUtils.buildMinionTickQueueName`).\n *\n * Per KD-12 of `.claude/plans/minions-and-workers-implementation.md`:\n * - Subscribes only to the queue dedicated to THIS minion (no shared\n * `scheduled` queue subscription, so the backend-api and minion don't\n * compete on cron tick deliveries).\n * - Verifies every inbound JWT through\n * `ScheduledMessageVerifierBackendService.verifyAndExtractMinionTick(token, expectedMinionName)`\n * — invalid signature, malformed payload, wrong issuer/audience, or\n * wrong target minion all NACK without requeue.\n * - Dispatches `MINION_TICK` tokens that match this minion's identity to\n * the registered handler. The handler typically routes into the\n * locally-hosted `flowsActorsRegistry` per Q9 LOCKED.\n *\n * Duplicate deliveries and recovery of one occurrence belong to the durable\n * coordinator. Overlap between DISTINCT occurrences remains the handler's\n * responsibility; these are separate guarantees.\n */\n@injectable()\nexport class MinionTickConsumerBackendService {\n private isConsuming = false;\n private consumingQueueName?: string;\n private readonly runner: ScheduledExecutionRunner;\n private reviewScope?: { queueName: string; resolver: ScheduledExecutionResolver };\n\n protected readonly logDebug: (message: string, context?: Record<string, unknown>) => void;\n\n constructor(\n @inject(SAAS_SERVICE_TYPES.RabbitMQAdapterService)\n private readonly adapter: RabbitMQAdapterBackendService,\n @inject(SAAS_SERVICE_TYPES.ScheduledMessageVerifierService)\n private readonly scheduledMessageVerifier: ScheduledMessageVerifierBackendService,\n @inject(SAAS_SERVICE_TYPES.Logger)\n private readonly logger: LoggerService,\n @inject(SAAS_SERVICE_TYPES.JobStatusTrackingService)\n tracker: JobStatusTrackingBackendService,\n @inject(SAAS_SERVICE_TYPES.JobPayloadStorageService)\n payloadStorage: JobPayloadStorageBackendService,\n @inject(SAAS_SERVICE_TYPES.WorkerShutdownManagerService)\n private readonly shutdownManager: WorkerShutdownManagerBackendService,\n ) {\n this.runner = new ScheduledExecutionRunner(tracker, logger, payloadStorage, {\n started: () => shutdownManager.jobStarted(),\n completed: () => shutdownManager.jobCompleted(),\n });\n // Stop broker receipts and recovery admissions before the shared signal coordinator drains work.\n shutdownManager.registerStopHandler(() => this.stop());\n this.logDebug = this.logger.debugByType('MinionTickConsumerBackendService');\n this.logger.setDebugTypeLogging('MinionTickConsumerBackendService', false);\n }\n\n public async start(input: {\n /**\n * The PLATFORM's id for the application this minion serves — the id its tick queue is named\n * from and the id the crontabs-manager signs into every tick. It is addressing, never a row\n * identity: the tick rows and stored payloads are anchored by the tracker and the payload\n * storage to the application RECORD id, which they resolve themselves.\n */\n applicationId: string;\n minionName: string;\n handler?: MinionTickHandler;\n recoveryPolicy?: Partial<ScheduledRecoveryPolicy>;\n evidencePolicy?: ScheduledEvidencePolicy;\n reconcile?: MinionTickReconciler;\n }): Promise<void> {\n if (this.isConsuming) {\n throw new Error('MinionTickConsumerBackendService.start called while already consuming.');\n }\n\n const { applicationId, minionName, handler, recoveryPolicy, evidencePolicy, reconcile } = input;\n // The scanner resolves only this runtime's locally authored handler. Durable input\n // is trusted after first receipt; it is never turned back into a signed JWT.\n const resolver: ScheduledExecutionResolver = async (job) => {\n if (job.applicationId !== applicationId || job.jobType !== JobType.MINION_TICK || job.minionName !== minionName || !handler) return undefined;\n const tick: MinionTickInvocation = {\n jobId: job.jobId, applicationId, jobType: JobType.MINION_TICK, minionName,\n inputDataJson: job.inputDataJson, createdAt: job.createdAt, scheduledAt: job.scheduledAt,\n };\n return {\n policy: recoveryPolicy,\n evidencePolicy,\n execute: async (attempt) => {\n const startedAt = Date.now();\n await handler(tick, attempt);\n return { jobId: job.jobId, status: JobStatus.COMPLETED, startedAt: new Date(startedAt), durationMs: Date.now() - startedAt, completedAt: new Date() };\n },\n reconcile: reconcile ? (attempt) => reconcile(tick, attempt) : undefined,\n };\n };\n const queueName = QueueNamingUtils.buildMinionTickQueueName(applicationId, minionName);\n\n // M5 — adapter readiness guard. The minion entrypoint calls this\n // method AFTER `StartApplicationBackendService.initialize`, which\n // typically connects the RabbitMQ adapter. Throw a descriptive\n // error if the adapter is not connected so a misconfigured\n // bootstrap surfaces here rather than at the first cron tick.\n if (!this.adapter.isConnected()) {\n throw new Error(\n 'MinionTickConsumerBackendService.start called before the RabbitMQ adapter connected. ' +\n 'Ensure the minion bootstrap completes before subscribing to the tick queue.',\n );\n }\n\n // H2 — the minion runtime OWNS and declares this per-minion tick queue.\n // The crontabs-batches-manager publisher is a producer only and passively\n // verifies the queue (`checkQueue`) rather than declaring it, so there is no\n // publisher-side declaration whose args this must match — the minion is the\n // sole topology owner here. `durable: true` + `x-queue-type: 'quorum'` is\n // the minion's own chosen shape (durable so ticks survive a broker restart).\n //\n // Declared on the adapter's dedicated topology channel (not the primary\n // publish/consume channel): a `406` arg-mismatch against a pre-existing\n // incompatible queue closes only that channel, so it can't tear down the\n // primary channel and crash-loop the minion bootstrap. The\n // `x-queue-type: 'quorum'` argument is not modelled by `QueueAssertOptions`,\n // so we declare directly on the channel rather than via `adapter.assertQueue`.\n const channel = await this.adapter.getTopologyChannel();\n await channel.assertQueue(queueName, {\n durable: true,\n arguments: {\n 'x-queue-type': 'quorum',\n },\n });\n\n await this.adapter.consume(queueName, async (msg: ConsumeMessage, channel: Channel) => {\n await this.handleMessage(msg, channel, applicationId, minionName, queueName, resolver);\n });\n\n this.consumingQueueName = queueName;\n this.isConsuming = true;\n this.runner.start(queueName, resolver);\n this.reviewScope = { queueName, resolver };\n this.logger.info('Minion tick consumer started', {\n queueName,\n applicationId,\n minionName,\n });\n }\n\n public async stop(): Promise<void> {\n this.runner.stop();\n this.reviewScope = undefined;\n if (!this.isConsuming || !this.consumingQueueName) {\n return;\n }\n await this.adapter.cancelConsumer(this.consumingQueueName);\n this.isConsuming = false;\n this.consumingQueueName = undefined;\n }\n\n /**\n * Invoke from an application-owned operator operation AFTER authorization.\n * Runtime app/queue ownership is derived here, never supplied by the caller;\n * actor, reason and expected revision are persisted atomically with the decision.\n */\n public async resolveTickReview(\n input: Omit<Parameters<ScheduledExecutionRunner['resolveReview']>[0], 'queueName'>,\n ): Promise<void> {\n const scope = this.reviewScope;\n if (!scope) throw new Error('Minion tick review requires an initialized consumer');\n await this.runner.resolveReview({ ...input, queueName: scope.queueName }, scope.resolver);\n }\n\n public isRunning(): boolean {\n return this.isConsuming;\n }\n\n private async handleMessage(\n msg: ConsumeMessage,\n channel: Channel,\n applicationId: string,\n expectedMinionName: string,\n queueName: string,\n resolver: ScheduledExecutionResolver,\n ): Promise<void> {\n this.shutdownManager.jobStarted();\n let admitted: JobExecution | undefined;\n try {\n let accepted = false;\n try {\n const tick = await this.scheduledMessageVerifier.verifyAndExtractMinionTick(msg.content.toString(), expectedMinionName);\n // Signature/target checks do not establish receiving-application ownership.\n // This comparison must precede every durable insert and handler resolution.\n if (!tick || tick.applicationId !== applicationId || tick.minionName !== expectedMinionName) {\n throw new Error('Scheduled minion token does not match the receiving application and minion');\n }\n const job = JobPayloadSchema.parse({\n jobId: tick.jobId, jobType: JobType.MINION_TICK, applicationId: tick.applicationId,\n minionName: tick.minionName, inputDataJson: tick.inputDataJson,\n initiatedBy: JobInitiator.CRONTAB, createdAt: new Date(tick.iat * 1000), maxRetries: 0,\n scheduledAt: tick.scheduledAt === undefined ? undefined : new Date(tick.scheduledAt),\n });\n // Durable receipt, then acknowledge, THEN run — a long tick must not hold later deliveries\n // unreceived past their five-minute token (`ScheduledExecutionRunner.admit`).\n admitted = await this.runner.admit(job, queueName, resolver);\n accepted = true;\n } catch (error) {\n this.logger.error('Minion tick admission failed', { expectedMinionName, error: describeCaughtError(error) });\n }\n\n // Settlement failure is a broker problem, not a new business failure. Never\n // NACK after an ACK throws or run the handler again from this catch boundary.\n try {\n if (accepted) channel.ack(msg);\n else channel.nack(msg, false, false);\n } catch (error) {\n this.logger.error('Minion tick settlement failed', { expectedMinionName, error: describeCaughtError(error) });\n }\n } finally { this.shutdownManager.jobCompleted(); }\n // Started only after the delivery is settled; the runner tracks the run's own activity.\n if (admitted) this.runner.launch(admitted, resolver);\n }\n}\n"]}
@@ -18,6 +18,8 @@ export interface MinionProviderRuntimeArtifact {
18
18
  * which would assert, across a package boundary, the very thing nobody checked.
19
19
  */
20
20
  providerRuntimeImports?: ProviderRuntimeArtifact['providerRuntimeImports'];
21
+ /** Mirrored for the same reason: the projection narrows and forwards it (#1672). */
22
+ providerRuntimeAugmentations?: ProviderRuntimeArtifact['providerRuntimeAugmentations'];
21
23
  providerGraphDigest?: ProviderRuntimeArtifact['providerGraphDigest'];
22
24
  lockfileSectionDigest?: ProviderRuntimeArtifact['lockfileSectionDigest'];
23
25
  artifactKind: 'minions';
@@ -1 +1 @@
1
- {"version":3,"file":"define-minion-init.d.ts","sourceRoot":"","sources":["../../../../../src/runtime/services/define-minion-init.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACV,mCAAmC,EACnC,uBAAuB,EACvB,0BAA0B,EAC3B,MAAM,4BAA4B,CAAC;AACpC,OAAO,KAAK,EAAE,uBAAuB,EAAE,uBAAuB,EAAE,6BAA6B,EAAE,MAAM,uBAAuB,CAAC;AAC7H,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,+CAA+C,CAAC;AACvF,OAAO,KAAK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,CAC5C,KAAK,EAAE,UAAU,CAAC,iBAAiB,CAAC,CAAC,CAAC,CAAC,EACvC,OAAO,EAAE,iBAAiB,KACvB,OAAO,CAAC,6BAA6B,CAAC,CAAC;AAE5C,MAAM,MAAM,0BAA0B,GAAG,IAAI,CAAC,mCAAmC,EAAE,iBAAiB,CAAC,GAAG;IACtG,eAAe,CAAC,EAAE,uBAAuB,GAAG,6BAA6B,CAAC;IAC1E;;;;;;;;;;OAUG;IACH,MAAM,CAAC,EAAE,uBAAuB,CAAC;IACjC,+GAA+G;IAC/G,YAAY,CAAC,EAAE,OAAO,CAAC,uBAAuB,CAAC,CAAC;IAChD,yGAAyG;IACzG,aAAa,CAAC,EAAE,+BAA+B,CAAC;CACjD,CAAC;AAEF,wBAAgB,gBAAgB,CAC9B,MAAM,EAAE,0BAA0B,GACjC,0BAA0B,CAE5B;;AACD,mDAAmD"}
1
+ {"version":3,"file":"define-minion-init.d.ts","sourceRoot":"","sources":["../../../../../src/runtime/services/define-minion-init.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACV,mCAAmC,EACnC,uBAAuB,EACvB,0BAA0B,EAC3B,MAAM,4BAA4B,CAAC;AACpC,OAAO,KAAK,EAAE,uBAAuB,EAAE,uBAAuB,EAAE,6BAA6B,EAAE,MAAM,uBAAuB,CAAC;AAC7H,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,+CAA+C,CAAC;AACvF,OAAO,KAAK,EAAE,+BAA+B,EAAE,MAAM,uCAAuC,CAAC;AAE7F,KAAK,oBAAoB,GAAG,uBAAuB,CAAC,OAAO,CAAC,CAAC;AAC7D,KAAK,sBAAsB,GAAG,uBAAuB,CAAC,SAAS,CAAC,CAAC;AAEjE,MAAM,WAAW,6BAA6B;IAC5C,iBAAiB,EAAE,MAAM,CAAC;IAC1B,WAAW,EAAE,uBAAuB,CAAC,aAAa,CAAC,CAAC;IACpD,WAAW,EAAE,MAAM,CAAC;IACpB,YAAY,EAAE,MAAM,CAAC;IACr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IAC1E;;;;;;;;;;OAUG;IACH,MAAM,CAAC,EAAE,uBAAuB,CAAC;IACjC,+GAA+G;IAC/G,YAAY,CAAC,EAAE,OAAO,CAAC,uBAAuB,CAAC,CAAC;IAChD,yGAAyG;IACzG,aAAa,CAAC,EAAE,+BAA+B,CAAC;CACjD,CAAC;AAEF,wBAAgB,gBAAgB,CAC9B,MAAM,EAAE,0BAA0B,GACjC,0BAA0B,CAE5B;;AACD,mDAAmD"}
@@ -1 +1 @@
1
- {"version":3,"file":"define-minion-init.js","sourceRoot":"","sources":["../../../../../src/runtime/services/define-minion-init.ts"],"names":[],"mappings":"AA0HA,MAAM,UAAU,gBAAgB,CAC9B,MAAkC;IAElC,OAAO,MAAM,CAAC;AAChB,CAAC;AACD,mDAAmD","sourcesContent":["import type {\n ProjectedMinionInitializationConfig,\n ProviderRuntimeArtifact,\n SystemAccessBackendService,\n} from '@wildo-ai/saas-backend-lib';\nimport type { ScheduledAttemptContext, ScheduledRecoveryPolicy, ScheduledReconciliationResult } from '@wildo-ai/saas-models';\nimport type { MinionTickHandler } from '../queue/minion-tick-consumer.backend.service';\nimport type { OwnScheduleReaderBackendService } from './own-schedule-reader.backend.service';\n\ntype ProviderRuntimeScope = ProviderRuntimeArtifact['scope'];\ntype ProviderRuntimeModules = ProviderRuntimeArtifact['modules'];\n\nexport interface MinionProviderRuntimeArtifact {\n __AUTOGENERATED__: string;\n generatedBy: ProviderRuntimeArtifact['generatedBy'];\n generatedAt: string;\n sourceDigest: string;\n providerRefs?: ProviderRuntimeArtifact['providerRefs'];\n /**\n * Mirrored from the engine artifact so the per-host projection can FORWARD it (#330).\n *\n * This interface is a hand-written mirror of the CLI's multi-scope artifact, so a field the\n * CLI emits and this shape omits is a field the projection can only reach through a cast —\n * which would assert, across a package boundary, the very thing nobody checked.\n */\n providerRuntimeImports?: ProviderRuntimeArtifact['providerRuntimeImports'];\n providerGraphDigest?: ProviderRuntimeArtifact['providerGraphDigest'];\n lockfileSectionDigest?: ProviderRuntimeArtifact['lockfileSectionDigest'];\n artifactKind: 'minions';\n modules: ProviderRuntimeModules;\n scopes: Record<string, ProviderRuntimeScope>;\n}\n\n/**\n * The surface a minion's tick handler is given to do its work with.\n *\n * Handed to the handler rather than left for each author to resolve from the\n * container, for the same reason the runtime identity is established in\n * framework-owned startup: a boundary an author has to find is a boundary an author\n * can get wrong. What arrives here is already the CONTAINED surface —\n * `systemAccess` routes through the minion's `resourceAccess` ACL proxy, because\n * minion startup rebinds the services registry to the scoped decorator before any\n * tick is delivered.\n *\n * So a minion's effective authority is the INTERSECTION of two independent doors\n * (see `.claude/plans/minion-runtime-scope.md` D6):\n *\n * - `resourceAccess` — operator-declared containment, enforced by the DI proxy;\n * - the system-access door — the sanctioned per-tenant-authorization bypass, which\n * for a minion is fail-closed on audit (D9 + OQ-5b): audited, or refused.\n *\n * Neither subsumes the other. A resource the ACL forbids is refused even though the\n * system-access door would have allowed it, and a read the ACL permits is still\n * refused if it cannot be recorded.\n */\n/** @wildo_source:part:start minions.tick-contract facet:layer:backend facet:family:minion facet:audience:app-developer */\nexport interface MinionTickContext {\n /** Stable occurrence and fresh attempt identities for effect idempotency and reconciliation. */\n scheduledAttempt: ScheduledAttemptContext;\n /**\n * The sanctioned privileged-access door, already contained by this minion's\n * `resourceAccess` whitelist.\n *\n * Use this — never a repository directly (the `no-direct-repo-from-minion` ESLint\n * rule enforces that) — so every access stays inside both doors and leaves an\n * attributable audit record naming this minion.\n */\n systemAccess: SystemAccessBackendService;\n /** This minion's name, as declared in `wildo.saas.config.ts > minions`. */\n minionName: string;\n /**\n * Read this minion's OWN cron schedule and recent runs (R4).\n *\n * Present only when the application declared the `own_cron_records` scope in\n * this minion's `platformAccess`; otherwise the platform refuses and `read()`\n * rejects. It is deliberately NOT absent from the type in that case — the\n * authority decision belongs to the platform, and a client-side `undefined`\n * would be this process guessing at it, which drifts the moment the\n * declaration changes under a running minion.\n *\n * `read()` takes no arguments, and that is the contract rather than a\n * convenience: the subject is derived from this runtime's attested identity,\n * so another minion's schedule is not something this call could be asked for.\n */\n ownSchedule: OwnScheduleReaderBackendService;\n}\n\n/**\n * Tick handler invoked for each admitted execution attempt of an authenticated\n * occurrence addressed to this minion. Duplicate deliveries do not create new attempts.\n */\nexport type MinionTickAuthorHandler = (\n token: Parameters<MinionTickHandler>[0],\n context: MinionTickContext,\n) => Promise<void>;\n\n/** Reconcile durable/provider evidence of an earlier attempt; uncertainty must remain inconclusive. */\nexport type MinionTickReconciliationHandler = (\n token: Parameters<MinionTickHandler>[0],\n context: MinionTickContext,\n) => Promise<ScheduledReconciliationResult>;\n\nexport type MinionInitializationConfig = Omit<ProjectedMinionInitializationConfig, 'providerRuntime'> & {\n providerRuntime?: ProviderRuntimeArtifact | MinionProviderRuntimeArtifact;\n /**\n * Tick handler for admitted execution attempts addressed to this minion,\n * receiving the framework-supplied {@link MinionTickContext}. Recovery follows\n * the locally declared tickRecovery contract, never broker redelivery alone.\n *\n * Minion authors typically route the tick into the locally-hosted\n * `flowsActorsRegistry` (per Q9 LOCKED — per-minion-local actor\n * catalog). If omitted, the consumer still subscribes to the\n * per-minion queue but refuses execution. A missing handler must never\n * be recorded as successful work.\n */\n onTick?: MinionTickAuthorHandler;\n /** Locally authored effect-safety contract. Undeclared handlers default to manual review after uncertainty. */\n tickRecovery?: Partial<ScheduledRecoveryPolicy>;\n /** Required for reconciliation-based recovery; runs with the same contained access surface as onTick. */\n reconcileTick?: MinionTickReconciliationHandler;\n};\n\nexport function defineMinionInit(\n config: MinionInitializationConfig,\n): MinionInitializationConfig {\n return config;\n}\n/** @wildo_source:part:end minions.tick-contract */\n"]}
1
+ {"version":3,"file":"define-minion-init.js","sourceRoot":"","sources":["../../../../../src/runtime/services/define-minion-init.ts"],"names":[],"mappings":"AA4HA,MAAM,UAAU,gBAAgB,CAC9B,MAAkC;IAElC,OAAO,MAAM,CAAC;AAChB,CAAC;AACD,mDAAmD","sourcesContent":["import type {\n ProjectedMinionInitializationConfig,\n ProviderRuntimeArtifact,\n SystemAccessBackendService,\n} from '@wildo-ai/saas-backend-lib';\nimport type { ScheduledAttemptContext, ScheduledRecoveryPolicy, ScheduledReconciliationResult } from '@wildo-ai/saas-models';\nimport type { MinionTickHandler } from '../queue/minion-tick-consumer.backend.service';\nimport type { OwnScheduleReaderBackendService } from './own-schedule-reader.backend.service';\n\ntype ProviderRuntimeScope = ProviderRuntimeArtifact['scope'];\ntype ProviderRuntimeModules = ProviderRuntimeArtifact['modules'];\n\nexport interface MinionProviderRuntimeArtifact {\n __AUTOGENERATED__: string;\n generatedBy: ProviderRuntimeArtifact['generatedBy'];\n generatedAt: string;\n sourceDigest: string;\n providerRefs?: ProviderRuntimeArtifact['providerRefs'];\n /**\n * Mirrored from the engine artifact so the per-host projection can FORWARD it (#330).\n *\n * This interface is a hand-written mirror of the CLI's multi-scope artifact, so a field the\n * CLI emits and this shape omits is a field the projection can only reach through a cast —\n * which would assert, across a package boundary, the very thing nobody checked.\n */\n providerRuntimeImports?: ProviderRuntimeArtifact['providerRuntimeImports'];\n /** Mirrored for the same reason: the projection narrows and forwards it (#1672). */\n providerRuntimeAugmentations?: ProviderRuntimeArtifact['providerRuntimeAugmentations'];\n providerGraphDigest?: ProviderRuntimeArtifact['providerGraphDigest'];\n lockfileSectionDigest?: ProviderRuntimeArtifact['lockfileSectionDigest'];\n artifactKind: 'minions';\n modules: ProviderRuntimeModules;\n scopes: Record<string, ProviderRuntimeScope>;\n}\n\n/**\n * The surface a minion's tick handler is given to do its work with.\n *\n * Handed to the handler rather than left for each author to resolve from the\n * container, for the same reason the runtime identity is established in\n * framework-owned startup: a boundary an author has to find is a boundary an author\n * can get wrong. What arrives here is already the CONTAINED surface —\n * `systemAccess` routes through the minion's `resourceAccess` ACL proxy, because\n * minion startup rebinds the services registry to the scoped decorator before any\n * tick is delivered.\n *\n * So a minion's effective authority is the INTERSECTION of two independent doors\n * (see `.claude/plans/minion-runtime-scope.md` D6):\n *\n * - `resourceAccess` — operator-declared containment, enforced by the DI proxy;\n * - the system-access door — the sanctioned per-tenant-authorization bypass, which\n * for a minion is fail-closed on audit (D9 + OQ-5b): audited, or refused.\n *\n * Neither subsumes the other. A resource the ACL forbids is refused even though the\n * system-access door would have allowed it, and a read the ACL permits is still\n * refused if it cannot be recorded.\n */\n/** @wildo_source:part:start minions.tick-contract facet:layer:backend facet:family:minion facet:audience:app-developer */\nexport interface MinionTickContext {\n /** Stable occurrence and fresh attempt identities for effect idempotency and reconciliation. */\n scheduledAttempt: ScheduledAttemptContext;\n /**\n * The sanctioned privileged-access door, already contained by this minion's\n * `resourceAccess` whitelist.\n *\n * Use this — never a repository directly (the `no-direct-repo-from-minion` ESLint\n * rule enforces that) — so every access stays inside both doors and leaves an\n * attributable audit record naming this minion.\n */\n systemAccess: SystemAccessBackendService;\n /** This minion's name, as declared in `wildo.saas.config.ts > minions`. */\n minionName: string;\n /**\n * Read this minion's OWN cron schedule and recent runs (R4).\n *\n * Present only when the application declared the `own_cron_records` scope in\n * this minion's `platformAccess`; otherwise the platform refuses and `read()`\n * rejects. It is deliberately NOT absent from the type in that case — the\n * authority decision belongs to the platform, and a client-side `undefined`\n * would be this process guessing at it, which drifts the moment the\n * declaration changes under a running minion.\n *\n * `read()` takes no arguments, and that is the contract rather than a\n * convenience: the subject is derived from this runtime's attested identity,\n * so another minion's schedule is not something this call could be asked for.\n */\n ownSchedule: OwnScheduleReaderBackendService;\n}\n\n/**\n * Tick handler invoked for each admitted execution attempt of an authenticated\n * occurrence addressed to this minion. Duplicate deliveries do not create new attempts.\n */\nexport type MinionTickAuthorHandler = (\n token: Parameters<MinionTickHandler>[0],\n context: MinionTickContext,\n) => Promise<void>;\n\n/** Reconcile durable/provider evidence of an earlier attempt; uncertainty must remain inconclusive. */\nexport type MinionTickReconciliationHandler = (\n token: Parameters<MinionTickHandler>[0],\n context: MinionTickContext,\n) => Promise<ScheduledReconciliationResult>;\n\nexport type MinionInitializationConfig = Omit<ProjectedMinionInitializationConfig, 'providerRuntime'> & {\n providerRuntime?: ProviderRuntimeArtifact | MinionProviderRuntimeArtifact;\n /**\n * Tick handler for admitted execution attempts addressed to this minion,\n * receiving the framework-supplied {@link MinionTickContext}. Recovery follows\n * the locally declared tickRecovery contract, never broker redelivery alone.\n *\n * Minion authors typically route the tick into the locally-hosted\n * `flowsActorsRegistry` (per Q9 LOCKED — per-minion-local actor\n * catalog). If omitted, the consumer still subscribes to the\n * per-minion queue but refuses execution. A missing handler must never\n * be recorded as successful work.\n */\n onTick?: MinionTickAuthorHandler;\n /** Locally authored effect-safety contract. Undeclared handlers default to manual review after uncertainty. */\n tickRecovery?: Partial<ScheduledRecoveryPolicy>;\n /** Required for reconciliation-based recovery; runs with the same contained access surface as onTick. */\n reconcileTick?: MinionTickReconciliationHandler;\n};\n\nexport function defineMinionInit(\n config: MinionInitializationConfig,\n): MinionInitializationConfig {\n return config;\n}\n/** @wildo_source:part:end minions.tick-contract */\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"start-minion-application.backend.service.d.ts","sourceRoot":"","sources":["../../../../../src/runtime/services/start-minion-application.backend.service.ts"],"names":[],"mappings":"AAAA,OAAO,EAEL,KAAK,uBAAuB,EAI5B,KAAK,aAAa,EAElB,KAAK,8BAA8B,EACnC,KAAK,0BAA0B,EAE/B,KAAK,8BAA8B,EAAuB,MAAM,4BAA4B,CAAC;AAK/F,OAAO,KAAK,EAAE,+BAA+B,EAAE,MAAM,uCAAuC,CAAC;AAC7F,OAAO,EACL,gCAAgC,EAEjC,MAAM,+CAA+C,CAAC;AACvD,OAAO,KAAK,EACV,0BAA0B,EAK3B,MAAM,sBAAsB,CAAC;AAQ9B,qBACa,oCAAoC;IAK7C,OAAO,CAAC,QAAQ,CAAC,uBAAuB;IAExC,OAAO,CAAC,QAAQ,CAAC,gBAAgB;IAEjC,OAAO,CAAC,QAAQ,CAAC,YAAY;IAE7B,OAAO,CAAC,QAAQ,CAAC,MAAM;IAEvB,OAAO,CAAC,QAAQ,CAAC,gBAAgB;IAEjC,OAAO,CAAC,QAAQ,CAAC,YAAY;IAE7B,OAAO,CAAC,QAAQ,CAAC,iBAAiB;IAhBpC,OAAO,CAAC,mBAAmB,CAAS;gBAIjB,uBAAuB,EAAE,8BAA8B,EAEvD,gBAAgB,EAAE,uBAAuB,EAEzC,YAAY,EAAE,gCAAgC,EAE9C,MAAM,EAAE,aAAa,EAErB,gBAAgB,EAAE,8BAA8B,EAEhD,YAAY,EAAE,0BAA0B,EAExC,iBAAiB,EAAE,+BAA+B;IAGxD,UAAU,CAAC,MAAM,EAAE,0BAA0B,GAAG,OAAO,CAAC,IAAI,CAAC;IAqI7D,QAAQ,IAAI,OAAO,CAAC,IAAI,CAAC;IAe/B,wBAAwB,IAAI,OAAO;YAI5B,iBAAiB;IAgD/B,OAAO,CAAC,sBAAsB;IAkC9B;;;;;;;;;;;;;;;;;;;;;;;;OAwBG;IACH,OAAO,CAAC,wBAAwB;IAoBhC,OAAO,CAAC,gCAAgC;CAoEzC"}
1
+ {"version":3,"file":"start-minion-application.backend.service.d.ts","sourceRoot":"","sources":["../../../../../src/runtime/services/start-minion-application.backend.service.ts"],"names":[],"mappings":"AAAA,OAAO,EAEL,KAAK,uBAAuB,EAI5B,KAAK,aAAa,EAElB,KAAK,8BAA8B,EACnC,KAAK,0BAA0B,EAE/B,KAAK,8BAA8B,EAAuB,MAAM,4BAA4B,CAAC;AAK/F,OAAO,KAAK,EAAE,+BAA+B,EAAE,MAAM,uCAAuC,CAAC;AAC7F,OAAO,EACL,gCAAgC,EAEjC,MAAM,+CAA+C,CAAC;AACvD,OAAO,KAAK,EACV,0BAA0B,EAK3B,MAAM,sBAAsB,CAAC;AAQ9B,qBACa,oCAAoC;IAK7C,OAAO,CAAC,QAAQ,CAAC,uBAAuB;IAExC,OAAO,CAAC,QAAQ,CAAC,gBAAgB;IAEjC,OAAO,CAAC,QAAQ,CAAC,YAAY;IAE7B,OAAO,CAAC,QAAQ,CAAC,MAAM;IAEvB,OAAO,CAAC,QAAQ,CAAC,gBAAgB;IAEjC,OAAO,CAAC,QAAQ,CAAC,YAAY;IAE7B,OAAO,CAAC,QAAQ,CAAC,iBAAiB;IAhBpC,OAAO,CAAC,mBAAmB,CAAS;gBAIjB,uBAAuB,EAAE,8BAA8B,EAEvD,gBAAgB,EAAE,uBAAuB,EAEzC,YAAY,EAAE,gCAAgC,EAE9C,MAAM,EAAE,aAAa,EAErB,gBAAgB,EAAE,8BAA8B,EAEhD,YAAY,EAAE,0BAA0B,EAExC,iBAAiB,EAAE,+BAA+B;IAGxD,UAAU,CAAC,MAAM,EAAE,0BAA0B,GAAG,OAAO,CAAC,IAAI,CAAC;IAqI7D,QAAQ,IAAI,OAAO,CAAC,IAAI,CAAC;IAe/B,wBAAwB,IAAI,OAAO;YAI5B,iBAAiB;IAgD/B,OAAO,CAAC,sBAAsB;IAkC9B;;;;;;;;;;;;;;;;;;;;;;;;OAwBG;IACH,OAAO,CAAC,wBAAwB;IAoBhC,OAAO,CAAC,gCAAgC;CAyEzC"}
@@ -279,6 +279,10 @@ let StartMinionApplicationBackendService = class StartMinionApplicationBackendSe
279
279
  // is the union across every host, and handing this host a sibling's package specifiers would
280
280
  // tell it that it may load something it never declared.
281
281
  const projectedProviderRuntimeImports = Object.fromEntries(Object.entries(providerRuntime.providerRuntimeImports ?? {}).filter(([providerRef]) => projectedProviderRefs.includes(providerRef)));
282
+ // Narrowed with the refs as well (#1672): a host applies augmentations only to providers it declares, and a
283
+ // sibling's opt-in must not load a package into this process.
284
+ const projectedAugmentations = Object.entries(providerRuntime.providerRuntimeAugmentations ?? {})
285
+ .filter(([providerRef]) => projectedProviderRefs.includes(providerRef));
282
286
  return {
283
287
  __AUTOGENERATED__: providerRuntime.__AUTOGENERATED__,
284
288
  generatedBy: providerRuntime.generatedBy,
@@ -286,6 +290,7 @@ let StartMinionApplicationBackendService = class StartMinionApplicationBackendSe
286
290
  sourceDigest: providerRuntime.sourceDigest,
287
291
  providerRefs: projectedProviderRefs,
288
292
  providerRuntimeImports: projectedProviderRuntimeImports,
293
+ ...(projectedAugmentations.length === 0 ? {} : { providerRuntimeAugmentations: Object.fromEntries(projectedAugmentations) }),
289
294
  providerGraphDigest: providerRuntime.providerGraphDigest,
290
295
  lockfileSectionDigest: providerRuntime.lockfileSectionDigest,
291
296
  artifactKind: 'backend',
@@ -1 +1 @@
1
- {"version":3,"file":"start-minion-application.backend.service.js","sourceRoot":"","sources":["../../../../../src/runtime/services/start-minion-application.backend.service.ts"],"names":[],"mappings":";;;;;;;;;;;;AAAA,OAAO,EAGL,yBAAyB,EACzB,MAAM,EACN,UAAU,EAKV,kBAAkB,EACmB,mBAAmB,EAAE,MAAM,4BAA4B,CAAC;AAC/F,OAAO,EAAE,2BAA2B,EAAE,SAAS,EAAgC,MAAM,uBAAuB,CAAC;AAC7G,OAAO,EAAE,8BAA8B,EAAE,MAAM,+BAA+B,CAAC;AAC/E,OAAO,EAAE,iDAAiD,EAAE,MAAM,8FAA8F,CAAC;AACjK,OAAO,EAAE,0BAA0B,EAAE,MAAM,mCAAmC,CAAC;AAE/E,OAAO,EACL,gCAAgC,GAEjC,MAAM,+CAA+C,CAAC;AAgBhD,IAAM,oCAAoC,GAA1C,MAAM,oCAAoC;IAK5B;IAEA;IAEA;IAEA;IAEA;IAEA;IAEA;IAhBX,mBAAmB,GAAG,KAAK,CAAC;IAEpC,YAEmB,uBAAuD,EAEvD,gBAAyC,EAEzC,YAA8C,EAE9C,MAAqB,EAErB,gBAAgD,EAEhD,YAAwC,EAExC,iBAAkD;QAZlD,4BAAuB,GAAvB,uBAAuB,CAAgC;QAEvD,qBAAgB,GAAhB,gBAAgB,CAAyB;QAEzC,iBAAY,GAAZ,YAAY,CAAkC;QAE9C,WAAM,GAAN,MAAM,CAAe;QAErB,qBAAgB,GAAhB,gBAAgB,CAAgC;QAEhD,iBAAY,GAAZ,YAAY,CAA4B;QAExC,sBAAiB,GAAjB,iBAAiB,CAAiC;IAClE,CAAC;IAEG,KAAK,CAAC,UAAU,CAAC,MAAk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AAC,WAAW,CAAC,CAAC,CACzE,CAAC;QAEF,OAAO;YACL,iBAAiB,EAAE,eAAe,CAAC,iBAAiB;YACpD,WAAW,EAAE,eAAe,CAAC,WAAW;YACxC,WAAW,EAAE,eAAe,CAAC,WAAW;YACxC,YAAY,EAAE,eAAe,CAAC,YAAY;YAC1C,YAAY,EAAE,qBAAqB;YACnC,sBAAsB,EAAE,+BAA+B;YACvD,mBAAmB,EAAE,eAAe,CAAC,mBAAmB;YACxD,qBAAqB,EAAE,eAAe,CAAC,qBAAqB;YAC5D,YAAY,EAAE,SAAS;YACvB,OAAO,EAAE,eAAe,CAAC,OAAO;YAChC,KAAK;SACN,CAAC;IACJ,CAAC;CACF,CAAA;AA/WY,oCAAoC;IADhD,UAAU,EAAE;IAKR,WAAA,MAAM,CAAC,kBAAkB,CAAC,uBAAuB,CAAC,CAAA;IAElD,WAAA,MAAM,CAAC,kBAAkB,CAAC,gBAAgB,CAAC,CAAA;IAE3C,WAAA,MAAM,CAAC,0BAA0B,CAAC,yBAAyB,CAAC,CAAA;IAE5D,WAAA,MAAM,CAAC,kBAAkB,CAAC,MAAM,CAAC,CAAA;IAEjC,WAAA,MAAM,CAAC,kBAAkB,CAAC,uBAAuB,CAAC,CAAA;IAElD,WAAA,MAAM,CAAC,kBAAkB,CAAC,mBAAmB,CAAC,CAAA;IAE9C,WAAA,MAAM,CAAC,0BAA0B,CAAC,wBAAwB,CAAC,CAAA;yDAP7B,gCAAgC;GATtD,oCAAoC,CA+WhD","sourcesContent":["import {\n type AppConfiguration,\n type AppConfigurationService,\n ApplicationRuntimeProfile,\n inject,\n injectable,\n type LoggerService,\n type ProviderRuntimeArtifact,\n type RuntimePrincipalBackendService,\n type SystemAccessBackendService,\n SAAS_SERVICE_TYPES,\n type StartApplicationBackendService, describeCaughtError } from '@wildo-ai/saas-backend-lib';\nimport { ErrorCustomMessageReference, ErrorType, type ScheduledRecoveryPolicy } from '@wildo-ai/saas-models';\nimport { assertProviderRuntimeEnvInSync } from '@wildo-ai/platform-config-lib';\nimport { MinionScopedServicesRegistryHandlerBackendService } from '../../base-classes/services/services/minion-scoped-services-registry-handler.backend.service';\nimport { SAAS_MINIONS_SERVICE_TYPES } from '../../inject/models/service-types';\nimport type { OwnScheduleReaderBackendService } from './own-schedule-reader.backend.service';\nimport {\n MinionTickConsumerBackendService,\n type MinionTickHandler,\n} from '../queue/minion-tick-consumer.backend.service';\nimport type {\n MinionInitializationConfig,\n MinionProviderRuntimeArtifact,\n MinionTickAuthorHandler,\n MinionTickContext,\n MinionTickReconciliationHandler,\n} from './define-minion-init';\n\ntype MinionAwareAppConfiguration = AppConfiguration & {\n minions?: Record<string, MinionRuntimeConfig>;\n};\n\ntype MinionRuntimeConfig = NonNullable<NonNullable<AppConfiguration['minions']>[string]>;\n\n@injectable()\nexport class StartMinionApplicationBackendService {\n private tickConsumerStarted = false;\n\n constructor(\n @inject(SAAS_SERVICE_TYPES.StartApplicationService)\n private readonly startApplicationService: StartApplicationBackendService,\n @inject(SAAS_SERVICE_TYPES.AppConfigService)\n private readonly appConfigService: AppConfigurationService,\n @inject(SAAS_MINIONS_SERVICE_TYPES.MinionTickConsumerService)\n private readonly tickConsumer: MinionTickConsumerBackendService,\n @inject(SAAS_SERVICE_TYPES.Logger)\n private readonly logger: LoggerService,\n @inject(SAAS_SERVICE_TYPES.RuntimePrincipalService)\n private readonly runtimePrincipal: RuntimePrincipalBackendService,\n @inject(SAAS_SERVICE_TYPES.SystemAccessService)\n private readonly systemAccess: SystemAccessBackendService,\n @inject(SAAS_MINIONS_SERVICE_TYPES.OwnScheduleReaderService)\n private readonly ownScheduleReader: OwnScheduleReaderBackendService,\n ) {}\n\n public async initialize(config: MinionInitializationConfig): Promise<void> {\n const {\n minionName,\n serviceIdentifier,\n onTick,\n tickRecovery,\n reconcileTick,\n ...startupConfig\n } = config;\n // Declare WHO this process is before anything can perform a privileged access.\n //\n // Established here, in framework-owned minion startup, rather than left to each\n // minion author — attribution that an author can forget is attribution that will\n // be missing exactly when an auditor needs it. Every minion therefore carries its\n // identity structurally, by virtue of being a minion.\n //\n // Attribution only: this grants nothing. A minion's operations are governed by its\n // role and its `resourceAccess` whitelist; its cross-tenant reach comes from the\n // system-access door. See `.claude/plans/minion-runtime-scope.md` (D9).\n //\n // assurance-control: WILDO.AUDIT.SECURITY_EVENT — privileged access by a non-human\n // background runtime is attributable to that runtime.\n this.runtimePrincipal.initialize({\n runtimeProfile: ApplicationRuntimeProfile.MINION,\n runtimeKey: minionName,\n serviceIdentifier: serviceIdentifier ?? `minions.${minionName}`,\n });\n\n const normalizedProviderRuntime = this.normalizeProviderRuntime(\n startupConfig.providerRuntime,\n minionName,\n );\n\n // Boot-time fail-closed reconciliation between the typed\n // `wildo-provider-runtime.generated.ts` artifact and the\n // `.wildo-providers.env` file mounted into this process. Catches\n // stale-sync drift (operator regenerated one surface but not the\n // other) BEFORE the registry filter would silently boot with\n // mismatched topology.\n //\n // Skipped when:\n // - the artifact is absent (host authored zero providers AND no\n // scope block in `wildo.saas.config.ts`); or\n // - the artifact has zero `providerRefs` (host authored an\n // explicit empty scope `providers: {}`). The CLI emitter\n // deliberately does NOT write `.wildo-providers.env` in that\n // case, so the env-vars are absent — running the assertion\n // would raise a false-positive fail-closed.\n // Defensive `?? []` — the schema marks `providerRefs` optional, so\n // a hand-crafted artifact (test fixture / future format drift)\n // could omit it. Without the fallback `.length` would TypeError\n // before fail-closed produced its actionable message. Production\n // CLI emit always defaults to `[]`, so this is hardening only.\n const projectedProviderRefs = normalizedProviderRuntime?.providerRefs ?? [];\n if (normalizedProviderRuntime && projectedProviderRefs.length > 0) {\n assertProviderRuntimeEnvInSync({\n artifactProviderRefs: projectedProviderRefs,\n artifactSourceDigest: normalizedProviderRuntime.sourceDigest,\n hostKind: 'minion',\n hostKey: minionName,\n });\n }\n\n await this.startApplicationService.initialize({\n ...startupConfig,\n providerRuntime: normalizedProviderRuntime,\n headlessMode: true,\n skipCronSync: true,\n // A minion reuses the full backend startup lifecycle but is NOT a job\n // worker for the shared application queues — it consumes ONLY its own\n // `minion-tick.<name>` queue (subscribed below via `startTickConsumer`).\n // Skipping the shared job consumers keeps RabbitMQ from round-robining\n // scheduled-cron ticks onto this process (which would dead-letter every\n // tick it can't interpret). The broker connection itself is still made,\n // because the tick consumer depends on it.\n skipJobConsumers: true,\n serviceIdentifier: serviceIdentifier ?? `minions.${minionName}`,\n afterResourcesRegistryInitialized: async ({\n appConfig,\n resourcesRegistryService,\n errorBuilder,\n }) => {\n const minionConfig = this.getMinionRuntimeConfig(\n appConfig as MinionAwareAppConfiguration,\n minionName,\n errorBuilder,\n );\n const resourceAccess = minionConfig.resourceAccess;\n const knownResourceTypes = new Set(resourcesRegistryService.getResourceTypes());\n const unknownResourceTypes = [\n ...(resourceAccess?.read ?? []),\n ...(resourceAccess?.write ?? []),\n ].filter((resourceType, index, all) => (\n resourceType !== '*'\n && !knownResourceTypes.has(resourceType)\n && all.indexOf(resourceType) === index\n ));\n\n if (unknownResourceTypes.length > 0) {\n throw errorBuilder.buildError(ErrorType.CONFIGURATION, undefined, {\n customMessageReference: ErrorCustomMessageReference.CONFIGURATION,\n context: {\n message:\n `Minion '${minionName}' references unknown resources in resourceAccess: `\n + `[${unknownResourceTypes.join(', ')}].`,\n minionName,\n unknownResourceTypes,\n },\n });\n }\n },\n servicesRegistryDecoratorFactory: (registry, { appConfig, errorBuilder }) => (\n new MinionScopedServicesRegistryHandlerBackendService(\n registry as any,\n minionName,\n this.getMinionRuntimeConfig(\n appConfig as MinionAwareAppConfiguration,\n minionName,\n errorBuilder,\n ).resourceAccess,\n ).asDecoratedRegistry()\n ),\n });\n\n // KD-12 auto-wiring: every minion subscribes to its dedicated tick\n // queue (`wildo.queue.<appId>.minion-tick.<minionName>`). Cron-mode\n // minions receive ticks from `platform-crontabs-batches-manager`;\n // always-up minions receive nothing on this queue under normal\n // operation but the subscription is harmless (no message ⇒ no\n // dispatch) and keeps the runtime contract symmetric across modes.\n await this.startTickConsumer(minionName, onTick, tickRecovery, reconcileTick);\n }\n\n public async shutdown(): Promise<void> {\n if (this.tickConsumerStarted) {\n try {\n await this.tickConsumer.stop();\n } catch (error) {\n this.logger.warn('Failed to stop minion tick consumer cleanly', {\n error: describeCaughtError(error),\n });\n } finally {\n this.tickConsumerStarted = false;\n }\n }\n await this.startApplicationService.shutdown();\n }\n\n public isApplicationInitialized(): boolean {\n return this.startApplicationService.isApplicationInitialized();\n }\n\n private async startTickConsumer(\n minionName: string,\n onTick: MinionTickAuthorHandler | undefined,\n tickRecovery: Partial<ScheduledRecoveryPolicy> | undefined,\n reconcileTick: MinionTickReconciliationHandler | undefined,\n ): Promise<void> {\n // The surface the handler is ALLOWED to work with, assembled once at the tick\n // boundary. Handed to the author rather than left for them to resolve from the\n // container: `systemAccess` here is already contained by this minion's\n // `resourceAccess` ACL, because startup rebinds the services registry to the\n // scoped decorator before any tick can be delivered. An author who resolved the\n // door themselves could bypass that; an author handed this one cannot.\n const context: Omit<MinionTickContext, 'scheduledAttempt'> = {\n systemAccess: this.systemAccess,\n minionName,\n // Same reasoning as `systemAccess`: handed to the author rather than left\n // to be resolved from the container. A reader an author constructs is a\n // reader an author could construct with a different identity; this one is\n // bound to the process's own attested principal and cannot be pointed\n // elsewhere.\n ownSchedule: this.ownScheduleReader,\n };\n\n // Missing handlers stay absent: the durable coordinator records REVIEW instead of\n // treating an unimplemented tick as successful work.\n const handler: MinionTickHandler | undefined = onTick\n ? async (token, scheduledAttempt) => onTick(token, { ...context, scheduledAttempt })\n : undefined;\n\n const evidencePolicies = this.appConfigService.config?.scheduledEvidence?.minions;\n for (const configuredName of Object.keys(evidencePolicies ?? {})) {\n if (!Object.hasOwn(this.appConfigService.config.minions ?? {}, configuredName)) {\n this.logger.warn('Scheduled evidence policy names an undeclared minion; no evidence will be collected for this key', { minionName: configuredName });\n }\n }\n await this.tickConsumer.start({\n applicationId: this.appConfigService.applicationId,\n minionName,\n handler,\n recoveryPolicy: tickRecovery,\n evidencePolicy: evidencePolicies && Object.hasOwn(evidencePolicies, minionName) ? evidencePolicies[minionName] : undefined,\n reconcile: reconcileTick\n ? async (token, scheduledAttempt) => reconcileTick(token, { ...context, scheduledAttempt })\n : undefined,\n });\n this.tickConsumerStarted = true;\n }\n\n private getMinionRuntimeConfig(\n appConfig: MinionAwareAppConfiguration,\n minionName: string,\n errorBuilder?: {\n buildError: (\n errorType: ErrorType,\n executionContext: undefined,\n options: {\n customMessageReference?: ErrorCustomMessageReference;\n context?: Record<string, unknown>;\n },\n ) => unknown;\n },\n ): MinionRuntimeConfig {\n const minionConfig = appConfig.minions?.[minionName];\n if (minionConfig) {\n return minionConfig;\n }\n\n if (!errorBuilder) {\n throw new Error(`Minion '${minionName}' is missing from appConfig.minions.`);\n }\n\n throw errorBuilder.buildError(ErrorType.CONFIGURATION, undefined, {\n customMessageReference: ErrorCustomMessageReference.CONFIGURATION,\n context: {\n message:\n `Minion '${minionName}' is not declared in the managed runtime config. `\n + 'Re-sync the application bootstrap material before starting the minion.',\n minionName,\n },\n });\n }\n\n /**\n * Bridge the per-minion materialized provider runtime artifact into the\n * `ProviderRuntimeArtifact` shape consumed by `StartApplicationBackendService`\n * (and ultimately filtered by `BackendProviderRegistryBackendService`).\n *\n * Three accepted input shapes:\n *\n * 1. `{ artifactKind: 'backend', scope: ... }` — already projected to a\n * backend-shaped single-scope artifact (e.g. produced by an\n * embedding host that pre-selected the scope).\n * 2. `{ artifactKind: 'minions', scope: ..., scopes: undefined }` —\n * what `wildo config sync` writes to each minion's\n * `src/generated/wildo-provider-runtime.generated.ts`. The CLI calls\n * `selectScopedProviderRuntimeArtifact(artifacts.minions, minionKey)`\n * so the file already carries only this minion's scope. We unwrap\n * it here to the canonical backend-shaped artifact.\n * 3. `{ artifactKind: 'minions', scopes: { [name]: ... } }` —\n * multi-scope minion artifact (legacy / non-CLI-driven hosts that\n * pass the unscoped artifact). We resolve `scopes[minionName]`.\n *\n * Anything else fails fast with a clear locator. Each minion process\n * must only see its own scope — there is no fallback to other scopes,\n * no merging across minions, and no silent recovery from a missing\n * scope.\n */\n private normalizeProviderRuntime(\n providerRuntime: MinionInitializationConfig['providerRuntime'],\n minionName: string,\n ): ProviderRuntimeArtifact | undefined {\n if (!providerRuntime) {\n return undefined;\n }\n if (providerRuntime.artifactKind === 'backend') {\n return providerRuntime;\n }\n const artifactKind = providerRuntime.artifactKind;\n if (artifactKind !== 'minions') {\n throw new Error(\n `Unsupported provider runtime artifactKind '${artifactKind}' for minion '${minionName}'.`,\n );\n }\n\n return this.selectMinionProviderRuntimeScope(providerRuntime, minionName);\n }\n\n private selectMinionProviderRuntimeScope(\n providerRuntime: MinionProviderRuntimeArtifact,\n minionName: string,\n ): ProviderRuntimeArtifact {\n const preScopedScope = (providerRuntime as MinionProviderRuntimeArtifact & {\n scope?: ProviderRuntimeArtifact['scope'];\n }).scope;\n const scopes = providerRuntime.scopes as\n | Record<string, ProviderRuntimeArtifact['scope']>\n | undefined;\n\n let scope: ProviderRuntimeArtifact['scope'] | undefined;\n\n if (preScopedScope && (!scopes || Object.keys(scopes).length === 0)) {\n // Shape 2 — the CLI-emitted per-minion module.\n scope = preScopedScope;\n } else if (scopes) {\n // Shape 3 — unscoped multi-scope artifact.\n scope = scopes[minionName];\n if (!scope) {\n throw new Error(\n `Provider runtime artifact does not contain a scope for minion '${minionName}'. `\n + `Re-run \\`wildo config sync\\` and verify the minion is declared in `\n + `wildo.saas.config.ts \\`providers.scopes.minions\\`.`,\n );\n }\n }\n\n if (!scope) {\n throw new Error(\n `Provider runtime artifact for minion '${minionName}' is missing both a `\n + `pre-scoped \\`scope\\` and a multi-scope \\`scopes\\` map. The artifact is malformed.`,\n );\n }\n\n // Recompute `providerRefs` from the projected per-host scope, NOT\n // from the multi-scope union the parent artifact carries. The\n // `buildMultiScopeArtifactMetadata` upstream computes\n // `providerRefs` as the union across all hosts; preserving that\n // here would make the boot-time `assertProviderRuntimeEnvInSync`\n // guard treat sibling-scope refs as \"this host has providers\" and\n // mistakenly run reconciliation on hosts whose own scope is empty.\n // Mirrors `selectScopedProviderRuntimeArtifact` in\n // `provider-runtime-artifacts.ts`.\n const projectedProviderRefs = Object.keys(scope.providers ?? {}).sort();\n // Narrowed with the refs, for the same reason (#330): the import map on a multi-scope artifact\n // is the union across every host, and handing this host a sibling's package specifiers would\n // tell it that it may load something it never declared.\n const projectedProviderRuntimeImports = Object.fromEntries(\n Object.entries(\n providerRuntime.providerRuntimeImports ?? {},\n ).filter(([providerRef]) => projectedProviderRefs.includes(providerRef)),\n );\n\n return {\n __AUTOGENERATED__: providerRuntime.__AUTOGENERATED__,\n generatedBy: providerRuntime.generatedBy,\n generatedAt: providerRuntime.generatedAt,\n sourceDigest: providerRuntime.sourceDigest,\n providerRefs: projectedProviderRefs,\n providerRuntimeImports: projectedProviderRuntimeImports,\n providerGraphDigest: providerRuntime.providerGraphDigest,\n lockfileSectionDigest: providerRuntime.lockfileSectionDigest,\n artifactKind: 'backend',\n modules: providerRuntime.modules,\n scope,\n };\n }\n}\n"]}
1
+ {"version":3,"file":"start-minion-application.backend.service.js","sourceRoot":"","sources":["../../../../../src/runtime/services/start-minion-application.backend.service.ts"],"names":[],"mappings":";;;;;;;;;;;;AAAA,OAAO,EAGL,yBAAyB,EACzB,MAAM,EACN,UAAU,EAKV,kBAAkB,EACmB,mBAAmB,EAAE,MAAM,4BAA4B,CAAC;AAC/F,OAAO,EAAE,2BAA2B,EAAE,SAAS,EAAgC,MAAM,uBAAuB,CAAC;AAC7G,OAAO,EAAE,8BAA8B,EAAE,MAAM,+BAA+B,CAAC;AAC/E,OAAO,EAAE,iDAAiD,EAAE,MAAM,8FAA8F,CAAC;AACjK,OAAO,EAAE,0BAA0B,EAAE,MAAM,mCAAmC,CAAC;AAE/E,OAAO,EACL,gCAAgC,GAEjC,MAAM,+CAA+C,CAAC;AAgBhD,IAAM,oCAAoC,GAA1C,MAAM,oCAAoC;IAK5B;IAEA;IAEA;IAEA;IAEA;IAEA;IAEA;IAhBX,mBAAmB,GAA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N,CAAC;IACJ,CAAC;CACF,CAAA;AApXY,oCAAoC;IADhD,UAAU,EAAE;IAKR,WAAA,MAAM,CAAC,kBAAkB,CAAC,uBAAuB,CAAC,CAAA;IAElD,WAAA,MAAM,CAAC,kBAAkB,CAAC,gBAAgB,CAAC,CAAA;IAE3C,WAAA,MAAM,CAAC,0BAA0B,CAAC,yBAAyB,CAAC,CAAA;IAE5D,WAAA,MAAM,CAAC,kBAAkB,CAAC,MAAM,CAAC,CAAA;IAEjC,WAAA,MAAM,CAAC,kBAAkB,CAAC,uBAAuB,CAAC,CAAA;IAElD,WAAA,MAAM,CAAC,kBAAkB,CAAC,mBAAmB,CAAC,CAAA;IAE9C,WAAA,MAAM,CAAC,0BAA0B,CAAC,wBAAwB,CAAC,CAAA;yDAP7B,gCAAgC;GATtD,oCAAoC,CAoXhD","sourcesContent":["import {\n type AppConfiguration,\n type AppConfigurationService,\n ApplicationRuntimeProfile,\n inject,\n injectable,\n type LoggerService,\n type ProviderRuntimeArtifact,\n type RuntimePrincipalBackendService,\n type SystemAccessBackendService,\n SAAS_SERVICE_TYPES,\n type StartApplicationBackendService, describeCaughtError } from '@wildo-ai/saas-backend-lib';\nimport { ErrorCustomMessageReference, ErrorType, type ScheduledRecoveryPolicy } from '@wildo-ai/saas-models';\nimport { assertProviderRuntimeEnvInSync } from '@wildo-ai/platform-config-lib';\nimport { MinionScopedServicesRegistryHandlerBackendService } from '../../base-classes/services/services/minion-scoped-services-registry-handler.backend.service';\nimport { SAAS_MINIONS_SERVICE_TYPES } from '../../inject/models/service-types';\nimport type { OwnScheduleReaderBackendService } from './own-schedule-reader.backend.service';\nimport {\n MinionTickConsumerBackendService,\n type MinionTickHandler,\n} from '../queue/minion-tick-consumer.backend.service';\nimport type {\n MinionInitializationConfig,\n MinionProviderRuntimeArtifact,\n MinionTickAuthorHandler,\n MinionTickContext,\n MinionTickReconciliationHandler,\n} from './define-minion-init';\n\ntype MinionAwareAppConfiguration = AppConfiguration & {\n minions?: Record<string, MinionRuntimeConfig>;\n};\n\ntype MinionRuntimeConfig = NonNullable<NonNullable<AppConfiguration['minions']>[string]>;\n\n@injectable()\nexport class StartMinionApplicationBackendService {\n private tickConsumerStarted = false;\n\n constructor(\n @inject(SAAS_SERVICE_TYPES.StartApplicationService)\n private readonly startApplicationService: StartApplicationBackendService,\n @inject(SAAS_SERVICE_TYPES.AppConfigService)\n private readonly appConfigService: AppConfigurationService,\n @inject(SAAS_MINIONS_SERVICE_TYPES.MinionTickConsumerService)\n private readonly tickConsumer: MinionTickConsumerBackendService,\n @inject(SAAS_SERVICE_TYPES.Logger)\n private readonly logger: LoggerService,\n @inject(SAAS_SERVICE_TYPES.RuntimePrincipalService)\n private readonly runtimePrincipal: RuntimePrincipalBackendService,\n @inject(SAAS_SERVICE_TYPES.SystemAccessService)\n private readonly systemAccess: SystemAccessBackendService,\n @inject(SAAS_MINIONS_SERVICE_TYPES.OwnScheduleReaderService)\n private readonly ownScheduleReader: OwnScheduleReaderBackendService,\n ) {}\n\n public async initialize(config: MinionInitializationConfig): Promise<void> {\n const {\n minionName,\n serviceIdentifier,\n onTick,\n tickRecovery,\n reconcileTick,\n ...startupConfig\n } = config;\n // Declare WHO this process is before anything can perform a privileged access.\n //\n // Established here, in framework-owned minion startup, rather than left to each\n // minion author — attribution that an author can forget is attribution that will\n // be missing exactly when an auditor needs it. Every minion therefore carries its\n // identity structurally, by virtue of being a minion.\n //\n // Attribution only: this grants nothing. A minion's operations are governed by its\n // role and its `resourceAccess` whitelist; its cross-tenant reach comes from the\n // system-access door. See `.claude/plans/minion-runtime-scope.md` (D9).\n //\n // assurance-control: WILDO.AUDIT.SECURITY_EVENT — privileged access by a non-human\n // background runtime is attributable to that runtime.\n this.runtimePrincipal.initialize({\n runtimeProfile: ApplicationRuntimeProfile.MINION,\n runtimeKey: minionName,\n serviceIdentifier: serviceIdentifier ?? `minions.${minionName}`,\n });\n\n const normalizedProviderRuntime = this.normalizeProviderRuntime(\n startupConfig.providerRuntime,\n minionName,\n );\n\n // Boot-time fail-closed reconciliation between the typed\n // `wildo-provider-runtime.generated.ts` artifact and the\n // `.wildo-providers.env` file mounted into this process. Catches\n // stale-sync drift (operator regenerated one surface but not the\n // other) BEFORE the registry filter would silently boot with\n // mismatched topology.\n //\n // Skipped when:\n // - the artifact is absent (host authored zero providers AND no\n // scope block in `wildo.saas.config.ts`); or\n // - the artifact has zero `providerRefs` (host authored an\n // explicit empty scope `providers: {}`). The CLI emitter\n // deliberately does NOT write `.wildo-providers.env` in that\n // case, so the env-vars are absent — running the assertion\n // would raise a false-positive fail-closed.\n // Defensive `?? []` — the schema marks `providerRefs` optional, so\n // a hand-crafted artifact (test fixture / future format drift)\n // could omit it. Without the fallback `.length` would TypeError\n // before fail-closed produced its actionable message. Production\n // CLI emit always defaults to `[]`, so this is hardening only.\n const projectedProviderRefs = normalizedProviderRuntime?.providerRefs ?? [];\n if (normalizedProviderRuntime && projectedProviderRefs.length > 0) {\n assertProviderRuntimeEnvInSync({\n artifactProviderRefs: projectedProviderRefs,\n artifactSourceDigest: normalizedProviderRuntime.sourceDigest,\n hostKind: 'minion',\n hostKey: minionName,\n });\n }\n\n await this.startApplicationService.initialize({\n ...startupConfig,\n providerRuntime: normalizedProviderRuntime,\n headlessMode: true,\n skipCronSync: true,\n // A minion reuses the full backend startup lifecycle but is NOT a job\n // worker for the shared application queues — it consumes ONLY its own\n // `minion-tick.<name>` queue (subscribed below via `startTickConsumer`).\n // Skipping the shared job consumers keeps RabbitMQ from round-robining\n // scheduled-cron ticks onto this process (which would dead-letter every\n // tick it can't interpret). The broker connection itself is still made,\n // because the tick consumer depends on it.\n skipJobConsumers: true,\n serviceIdentifier: serviceIdentifier ?? `minions.${minionName}`,\n afterResourcesRegistryInitialized: async ({\n appConfig,\n resourcesRegistryService,\n errorBuilder,\n }) => {\n const minionConfig = this.getMinionRuntimeConfig(\n appConfig as MinionAwareAppConfiguration,\n minionName,\n errorBuilder,\n );\n const resourceAccess = minionConfig.resourceAccess;\n const knownResourceTypes = new Set(resourcesRegistryService.getResourceTypes());\n const unknownResourceTypes = [\n ...(resourceAccess?.read ?? []),\n ...(resourceAccess?.write ?? []),\n ].filter((resourceType, index, all) => (\n resourceType !== '*'\n && !knownResourceTypes.has(resourceType)\n && all.indexOf(resourceType) === index\n ));\n\n if (unknownResourceTypes.length > 0) {\n throw errorBuilder.buildError(ErrorType.CONFIGURATION, undefined, {\n customMessageReference: ErrorCustomMessageReference.CONFIGURATION,\n context: {\n message:\n `Minion '${minionName}' references unknown resources in resourceAccess: `\n + `[${unknownResourceTypes.join(', ')}].`,\n minionName,\n unknownResourceTypes,\n },\n });\n }\n },\n servicesRegistryDecoratorFactory: (registry, { appConfig, errorBuilder }) => (\n new MinionScopedServicesRegistryHandlerBackendService(\n registry as any,\n minionName,\n this.getMinionRuntimeConfig(\n appConfig as MinionAwareAppConfiguration,\n minionName,\n errorBuilder,\n ).resourceAccess,\n ).asDecoratedRegistry()\n ),\n });\n\n // KD-12 auto-wiring: every minion subscribes to its dedicated tick\n // queue (`wildo.queue.<appId>.minion-tick.<minionName>`). Cron-mode\n // minions receive ticks from `platform-crontabs-batches-manager`;\n // always-up minions receive nothing on this queue under normal\n // operation but the subscription is harmless (no message ⇒ no\n // dispatch) and keeps the runtime contract symmetric across modes.\n await this.startTickConsumer(minionName, onTick, tickRecovery, reconcileTick);\n }\n\n public async shutdown(): Promise<void> {\n if (this.tickConsumerStarted) {\n try {\n await this.tickConsumer.stop();\n } catch (error) {\n this.logger.warn('Failed to stop minion tick consumer cleanly', {\n error: describeCaughtError(error),\n });\n } finally {\n this.tickConsumerStarted = false;\n }\n }\n await this.startApplicationService.shutdown();\n }\n\n public isApplicationInitialized(): boolean {\n return this.startApplicationService.isApplicationInitialized();\n }\n\n private async startTickConsumer(\n minionName: string,\n onTick: MinionTickAuthorHandler | undefined,\n tickRecovery: Partial<ScheduledRecoveryPolicy> | undefined,\n reconcileTick: MinionTickReconciliationHandler | undefined,\n ): Promise<void> {\n // The surface the handler is ALLOWED to work with, assembled once at the tick\n // boundary. Handed to the author rather than left for them to resolve from the\n // container: `systemAccess` here is already contained by this minion's\n // `resourceAccess` ACL, because startup rebinds the services registry to the\n // scoped decorator before any tick can be delivered. An author who resolved the\n // door themselves could bypass that; an author handed this one cannot.\n const context: Omit<MinionTickContext, 'scheduledAttempt'> = {\n systemAccess: this.systemAccess,\n minionName,\n // Same reasoning as `systemAccess`: handed to the author rather than left\n // to be resolved from the container. A reader an author constructs is a\n // reader an author could construct with a different identity; this one is\n // bound to the process's own attested principal and cannot be pointed\n // elsewhere.\n ownSchedule: this.ownScheduleReader,\n };\n\n // Missing handlers stay absent: the durable coordinator records REVIEW instead of\n // treating an unimplemented tick as successful work.\n const handler: MinionTickHandler | undefined = onTick\n ? async (token, scheduledAttempt) => onTick(token, { ...context, scheduledAttempt })\n : undefined;\n\n const evidencePolicies = this.appConfigService.config?.scheduledEvidence?.minions;\n for (const configuredName of Object.keys(evidencePolicies ?? {})) {\n if (!Object.hasOwn(this.appConfigService.config.minions ?? {}, configuredName)) {\n this.logger.warn('Scheduled evidence policy names an undeclared minion; no evidence will be collected for this key', { minionName: configuredName });\n }\n }\n await this.tickConsumer.start({\n applicationId: this.appConfigService.applicationId,\n minionName,\n handler,\n recoveryPolicy: tickRecovery,\n evidencePolicy: evidencePolicies && Object.hasOwn(evidencePolicies, minionName) ? evidencePolicies[minionName] : undefined,\n reconcile: reconcileTick\n ? async (token, scheduledAttempt) => reconcileTick(token, { ...context, scheduledAttempt })\n : undefined,\n });\n this.tickConsumerStarted = true;\n }\n\n private getMinionRuntimeConfig(\n appConfig: MinionAwareAppConfiguration,\n minionName: string,\n errorBuilder?: {\n buildError: (\n errorType: ErrorType,\n executionContext: undefined,\n options: {\n customMessageReference?: ErrorCustomMessageReference;\n context?: Record<string, unknown>;\n },\n ) => unknown;\n },\n ): MinionRuntimeConfig {\n const minionConfig = appConfig.minions?.[minionName];\n if (minionConfig) {\n return minionConfig;\n }\n\n if (!errorBuilder) {\n throw new Error(`Minion '${minionName}' is missing from appConfig.minions.`);\n }\n\n throw errorBuilder.buildError(ErrorType.CONFIGURATION, undefined, {\n customMessageReference: ErrorCustomMessageReference.CONFIGURATION,\n context: {\n message:\n `Minion '${minionName}' is not declared in the managed runtime config. `\n + 'Re-sync the application bootstrap material before starting the minion.',\n minionName,\n },\n });\n }\n\n /**\n * Bridge the per-minion materialized provider runtime artifact into the\n * `ProviderRuntimeArtifact` shape consumed by `StartApplicationBackendService`\n * (and ultimately filtered by `BackendProviderRegistryBackendService`).\n *\n * Three accepted input shapes:\n *\n * 1. `{ artifactKind: 'backend', scope: ... }` — already projected to a\n * backend-shaped single-scope artifact (e.g. produced by an\n * embedding host that pre-selected the scope).\n * 2. `{ artifactKind: 'minions', scope: ..., scopes: undefined }` —\n * what `wildo config sync` writes to each minion's\n * `src/generated/wildo-provider-runtime.generated.ts`. The CLI calls\n * `selectScopedProviderRuntimeArtifact(artifacts.minions, minionKey)`\n * so the file already carries only this minion's scope. We unwrap\n * it here to the canonical backend-shaped artifact.\n * 3. `{ artifactKind: 'minions', scopes: { [name]: ... } }` —\n * multi-scope minion artifact (legacy / non-CLI-driven hosts that\n * pass the unscoped artifact). We resolve `scopes[minionName]`.\n *\n * Anything else fails fast with a clear locator. Each minion process\n * must only see its own scope — there is no fallback to other scopes,\n * no merging across minions, and no silent recovery from a missing\n * scope.\n */\n private normalizeProviderRuntime(\n providerRuntime: MinionInitializationConfig['providerRuntime'],\n minionName: string,\n ): ProviderRuntimeArtifact | undefined {\n if (!providerRuntime) {\n return undefined;\n }\n if (providerRuntime.artifactKind === 'backend') {\n return providerRuntime;\n }\n const artifactKind = providerRuntime.artifactKind;\n if (artifactKind !== 'minions') {\n throw new Error(\n `Unsupported provider runtime artifactKind '${artifactKind}' for minion '${minionName}'.`,\n );\n }\n\n return this.selectMinionProviderRuntimeScope(providerRuntime, minionName);\n }\n\n private selectMinionProviderRuntimeScope(\n providerRuntime: MinionProviderRuntimeArtifact,\n minionName: string,\n ): ProviderRuntimeArtifact {\n const preScopedScope = (providerRuntime as MinionProviderRuntimeArtifact & {\n scope?: ProviderRuntimeArtifact['scope'];\n }).scope;\n const scopes = providerRuntime.scopes as\n | Record<string, ProviderRuntimeArtifact['scope']>\n | undefined;\n\n let scope: ProviderRuntimeArtifact['scope'] | undefined;\n\n if (preScopedScope && (!scopes || Object.keys(scopes).length === 0)) {\n // Shape 2 — the CLI-emitted per-minion module.\n scope = preScopedScope;\n } else if (scopes) {\n // Shape 3 — unscoped multi-scope artifact.\n scope = scopes[minionName];\n if (!scope) {\n throw new Error(\n `Provider runtime artifact does not contain a scope for minion '${minionName}'. `\n + `Re-run \\`wildo config sync\\` and verify the minion is declared in `\n + `wildo.saas.config.ts \\`providers.scopes.minions\\`.`,\n );\n }\n }\n\n if (!scope) {\n throw new Error(\n `Provider runtime artifact for minion '${minionName}' is missing both a `\n + `pre-scoped \\`scope\\` and a multi-scope \\`scopes\\` map. The artifact is malformed.`,\n );\n }\n\n // Recompute `providerRefs` from the projected per-host scope, NOT\n // from the multi-scope union the parent artifact carries. The\n // `buildMultiScopeArtifactMetadata` upstream computes\n // `providerRefs` as the union across all hosts; preserving that\n // here would make the boot-time `assertProviderRuntimeEnvInSync`\n // guard treat sibling-scope refs as \"this host has providers\" and\n // mistakenly run reconciliation on hosts whose own scope is empty.\n // Mirrors `selectScopedProviderRuntimeArtifact` in\n // `provider-runtime-artifacts.ts`.\n const projectedProviderRefs = Object.keys(scope.providers ?? {}).sort();\n // Narrowed with the refs, for the same reason (#330): the import map on a multi-scope artifact\n // is the union across every host, and handing this host a sibling's package specifiers would\n // tell it that it may load something it never declared.\n const projectedProviderRuntimeImports = Object.fromEntries(\n Object.entries(\n providerRuntime.providerRuntimeImports ?? {},\n ).filter(([providerRef]) => projectedProviderRefs.includes(providerRef)),\n );\n // Narrowed with the refs as well (#1672): a host applies augmentations only to providers it declares, and a\n // sibling's opt-in must not load a package into this process.\n const projectedAugmentations = Object.entries(providerRuntime.providerRuntimeAugmentations ?? {})\n .filter(([providerRef]) => projectedProviderRefs.includes(providerRef));\n\n return {\n __AUTOGENERATED__: providerRuntime.__AUTOGENERATED__,\n generatedBy: providerRuntime.generatedBy,\n generatedAt: providerRuntime.generatedAt,\n sourceDigest: providerRuntime.sourceDigest,\n providerRefs: projectedProviderRefs,\n providerRuntimeImports: projectedProviderRuntimeImports,\n ...(projectedAugmentations.length === 0 ? {} : { providerRuntimeAugmentations: Object.fromEntries(projectedAugmentations) }),\n providerGraphDigest: providerRuntime.providerGraphDigest,\n lockfileSectionDigest: providerRuntime.lockfileSectionDigest,\n artifactKind: 'backend',\n modules: providerRuntime.modules,\n scope,\n };\n }\n}\n"]}