@wildo-ai/saas-minions-lib 1.1.10 → 1.1.12

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 (29) hide show
  1. package/dist/esm/base-classes/services/services/minion-scoped-services-registry-handler.backend.service.js.map +1 -1
  2. package/dist/esm/index.js.map +1 -1
  3. package/dist/esm/inject/models/container.js.map +1 -1
  4. package/dist/esm/inject/models/service-types.js.map +1 -1
  5. package/dist/esm/runtime/queue/minion-tick-consumer.backend.service.d.ts +11 -2
  6. package/dist/esm/runtime/queue/minion-tick-consumer.backend.service.d.ts.map +1 -1
  7. package/dist/esm/runtime/queue/minion-tick-consumer.backend.service.js +13 -2
  8. package/dist/esm/runtime/queue/minion-tick-consumer.backend.service.js.map +1 -1
  9. package/dist/esm/runtime/services/define-minion-init.d.ts +8 -5
  10. package/dist/esm/runtime/services/define-minion-init.d.ts.map +1 -1
  11. package/dist/esm/runtime/services/define-minion-init.js.map +1 -1
  12. package/dist/esm/runtime/services/minion-liveness-heartbeat.d.ts +57 -0
  13. package/dist/esm/runtime/services/minion-liveness-heartbeat.d.ts.map +1 -0
  14. package/dist/esm/runtime/services/minion-liveness-heartbeat.js +125 -0
  15. package/dist/esm/runtime/services/minion-liveness-heartbeat.js.map +1 -0
  16. package/dist/esm/runtime/services/own-schedule-reader.backend.service.js.map +1 -1
  17. package/dist/esm/runtime/services/start-minion-application.backend.service.d.ts +14 -0
  18. package/dist/esm/runtime/services/start-minion-application.backend.service.d.ts.map +1 -1
  19. package/dist/esm/runtime/services/start-minion-application.backend.service.js +58 -8
  20. package/dist/esm/runtime/services/start-minion-application.backend.service.js.map +1 -1
  21. package/dist/tsconfig.build.tsbuildinfo +1 -1
  22. package/package.json +6 -6
  23. package/src/runtime/queue/__tests__/minion-tick-consumer.backend.service.test.ts +37 -1
  24. package/src/runtime/queue/minion-tick-consumer.backend.service.ts +14 -2
  25. package/src/runtime/services/__tests__/minion-liveness-heartbeat.test.ts +116 -0
  26. package/src/runtime/services/__tests__/start-minion-application.backend.service.test.ts +149 -2
  27. package/src/runtime/services/define-minion-init.ts +8 -5
  28. package/src/runtime/services/minion-liveness-heartbeat.ts +126 -0
  29. package/src/runtime/services/start-minion-application.backend.service.ts +63 -8
@@ -1 +1 @@
1
- {"version":3,"file":"minion-scoped-services-registry-handler.backend.service.js","sourceRoot":"","sources":["../../../../../../src/base-classes/services/services/minion-scoped-services-registry-handler.backend.service.ts"],"names":[],"mappings":"AAAA,OAAO,EAGL,4BAA4B,EAC5B,kBAAkB,GACnB,MAAM,uBAAuB,CAAC;AAW/B;;;;;;;;GAQG;AACH,MAAM,0BAA0B,GAAG,IAAI,GAAG,CAAS;IACjD,MAAM;IACN,MAAM;IACN,QAAQ;IACR,OAAO;IACP,uEAAuE;IACvE,uEAAuE;IACvE,QAAQ;CACT,CAAC,CAAC;AAEH,MAAM,oBAAoB,GAAG,IAAI,GAAG,CAAC;IACnC,MAAM;IACN,gFAAgF;IAChF,kFAAkF;IAClF,mFAAmF;IACnF,mEAAmE;IACnE,MAAM;IACN,QAAQ;IACR,OAAO;CACR,CAAC,CAAC;AAEH;;;;;;;;GAQG;AACH,MAAM,qBAAqB,GAAG,IAAI,GAAG,CAAC;IACpC,QAAQ;IACR,YAAY;IACZ,QAAQ;IACR,YAAY;IACZ,QAAQ;IACR,YAAY;IACZ,wBAAwB;IACxB,6BAA6B;CAC9B,CAAC,CAAC;AAEH;;;;;;;;;;;GAWG;AACH,MAAM,iCAAiC,GAAG,IAAI,GAAG,CAAS;IACxD,YAAY;IACZ,mBAAmB;IACnB,mBAAmB;IACnB,sBAAsB;IACtB,aAAa;IACb,MAAM,EAAE,oFAAoF;CAC7F,CAAC,CAAC;AAEH,MAAM,gCAAgC,GAAG,IAAI,GAAG,CAAS;IACvD,mBAAmB;IACnB,sBAAsB;IACtB,aAAa;IACb,MAAM;CACP,CAAC,CAAC;AAEH,MAAM,OAAO,iDAAiD;IAMzC;IACA;IANF,aAAa,C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,UAAU,EAAE,IAAI,CAAC,UAAU;oBAC3B,YAAY;oBACZ,UAAU,EAAE,kBAAkB,CAAC,KAAK;iBACrC,CAAC,CAAC;YACL,CAAC;SACF,CAAC,CAAC;QAEH,IAAI,CAAC,iBAAiB,CAAC,GAAG,CAAC,YAAY,EAAE,OAAO,CAAC,CAAC;QAClD,OAAO,OAAO,CAAC;IACjB,CAAC;IAEO,6BAA6B,CAAC,aAA4D;QAChG,IAAI,CAAC,aAAa,CAChB,aAAa,CAAC,kBAAkC,EAChD,IAAI,CAAC,iBAAiB,CACnB,aAAoD,CAAC,qBAAqB,EAC3E,aAAa,CAAC,mBAA6B,CAC5C,CACF,CAAC;IACJ,CAAC;IAEO,iBAAiB,CACvB,qBAAyC,EACzC,mBAA2B;QAE3B,MAAM,kBAAkB,GAAG,qBAAqB,IAAI,mBAAmB,CAAC;QACxE,OAAO,0BAA0B,CAAC,GAAG,CAAC,kBAAkB,CAAC;YACvD,CAAC,CAAC,kBAAkB,CAAC,IAAI;YACzB,CAAC,CAAC,kBAAkB,CAAC,KAAK,CAAC;IAC/B,CAAC;IAEO,aAAa,CAAC,YAA0B,EAAE,UAA8B;QAC9E,MAAM,SAAS,GAAG,UAAU,KAAK,kBAAkB,CAAC,IAAI;YACtD,CAAC,CAAC,IAAI,CAAC,aAAa;YACpB,CAAC,CAAC,IAAI,CAAC,cAAc,CAAC;QACxB,IAAI,SAAS,CAAC,GAAG,CAAC,GAAG,CAAC,IAAI,SAAS,CAAC,GAAG,CAAC,YAAY,CAAC,EAAE,CAAC;YACtD,OAAO;QACT,CAAC;QACD,MAAM,IAAI,4BAA4B,CAAC;YACrC,UAAU,EAAE,IAAI,CAAC,UAAU;YAC3B,YAAY;YACZ,UAAU;SACX,CAAC,CAAC;IACL,CAAC;CACF","sourcesContent":["import {\n ResourceConfiguration_OperationPath,\n ResourceType,\n ResourceAccessForbiddenError,\n ResourceAccessMode,\n} from '@wildo-ai/saas-models';\nimport type {\n AppConfiguration,\n ExecutionContext,\n ServicesRegistryHandlerBackendService,\n} from '@wildo-ai/saas-backend-lib';\n\ntype MinionResourceAccessConfig = NonNullable<\n NonNullable<AppConfiguration['minions']>[string]['resourceAccess']\n>;\n\n/**\n * Read-side operation identifiers. Anything in this set is classified\n * as a READ; anything else falls through to the path-aware classifiers\n * via `doByOperationPath` / `doByExecutionContext` rather than being\n * silently labelled WRITE (M4 fix). Custom operations and relationship\n * actions in particular cannot be classified by name — they MUST go\n * through `doByOperationPath` so the operation's own metadata drives\n * the access-mode decision.\n */\nconst READ_OPERATION_IDENTIFIERS = new Set<string>([\n 'READ',\n 'LIST',\n 'SEARCH',\n 'COUNT',\n // EXPORT serializes data outward; it's a read in v1. Listed explicitly\n // so a future EXPORT introduction does not silently classify as WRITE.\n 'EXPORT',\n]);\n\nconst READ_SERVICE_METHODS = new Set([\n 'read',\n // NOTE: `readAsSystem`/`listAsSystem` (ACL-bypassing system reads) deliberately\n // do NOT appear here — they were moved off the services registry handler onto the\n // dedicated `SystemAccessService` (Guard 3), which minion code is not granted. The\n // handler this proxy wraps no longer exposes a system-read at all.\n 'list',\n 'search',\n 'count',\n]);\n\n/**\n * Service methods classified as unconditional writes by name. The first\n * group are unambiguous CRUD writes; the polymorphic methods at the end\n * are listed conservatively as WRITE because their name alone does not\n * carry the operation's read/write intent. Worker code that needs read\n * semantics for a custom op or relationship action MUST go through\n * `doByOperationPath` so the operation's own metadata drives the\n * access-mode decision (see `resolveAccessMode`).\n */\nconst WRITE_SERVICE_METHODS = new Set([\n 'create',\n 'createMany',\n 'update',\n 'updateMany',\n 'delete',\n 'deleteMany',\n 'executeCustomOperation',\n 'applyRelationshipActionMany',\n]);\n\n/**\n * Per KD-11.A: the proxy is fail-CLOSED. A property name not in any of\n * the four sets above and not listed here is denied — minion code must\n * route through the chokepoints (`doByOperationPath`,\n * `doByExecutionContext`, `getService`, `getServiceOrThrow`) so the\n * resourceAccess whitelist applies.\n *\n * Symbol-keyed properties (e.g. `Symbol.toStringTag` for runtime\n * stringification) and a small number of harmless meta-properties are\n * allow-listed because denying them would break basic JS semantics\n * (`typeof`, `instanceof`, error formatting) without security value.\n */\nconst ALLOW_THROUGH_REGISTRY_PROPERTIES = new Set<string>([\n 'getService',\n 'getServiceOrThrow',\n 'doByOperationPath',\n 'doByExecutionContext',\n 'constructor',\n 'then', // present so Promise resolution doesn't trip when this proxy is awaited by accident\n]);\n\nconst ALLOW_THROUGH_SERVICE_PROPERTIES = new Set<string>([\n 'doByOperationPath',\n 'doByExecutionContext',\n 'constructor',\n 'then',\n]);\n\nexport class MinionScopedServicesRegistryHandlerBackendService {\n private readonly readAllowlist: Set<string>;\n private readonly writeAllowlist: Set<string>;\n private readonly serviceProxyCache = new Map<string, unknown>();\n\n constructor(\n private readonly baseRegistry: ServicesRegistryHandlerBackendService,\n private readonly minionName: string,\n resourceAccess: MinionResourceAccessConfig | undefined,\n ) {\n this.readAllowlist = new Set(resourceAccess?.read ?? []);\n this.writeAllowlist = new Set(resourceAccess?.write ?? []);\n }\n\n public asDecoratedRegistry(): ServicesRegistryHandlerBackendService {\n return new Proxy(this.baseRegistry, {\n get: (_target, property) => {\n if (property === 'getService') {\n return this.getService.bind(this);\n }\n if (property === 'getServiceOrThrow') {\n return this.getServiceOrThrow.bind(this);\n }\n if (property === 'doByOperationPath') {\n return this.doByOperationPath.bind(this);\n }\n if (property === 'doByExecutionContext') {\n return this.doByExecutionContext.bind(this);\n }\n if (typeof property === 'string' && READ_SERVICE_METHODS.has(property)) {\n return this.wrapRegistryMethod(property, ResourceAccessMode.READ);\n }\n if (typeof property === 'string' && WRITE_SERVICE_METHODS.has(property)) {\n return this.wrapRegistryMethod(property, ResourceAccessMode.WRITE);\n }\n\n // Symbol-keyed properties pass through (Symbol.toStringTag,\n // Symbol.toPrimitive, etc.) — they have no security relevance\n // and denying them breaks basic JS reflection.\n if (typeof property === 'symbol') {\n const value = (this.baseRegistry as unknown as Record<PropertyKey, unknown>)[property as unknown as string];\n return typeof value === 'function' ? value.bind(this.baseRegistry) : value;\n }\n\n // M3 fix — fail-CLOSED for unknown property names. Only the\n // explicit allow-list above and `ALLOW_THROUGH_REGISTRY_PROPERTIES`\n // expose the underlying registry; everything else throws so a\n // future method on `ServicesRegistryHandlerBackendService`\n // cannot silently bypass the resourceAccess whitelist.\n if (typeof property === 'string' && ALLOW_THROUGH_REGISTRY_PROPERTIES.has(property)) {\n const value = (this.baseRegistry as unknown as Record<PropertyKey, unknown>)[property];\n return typeof value === 'function' ? value.bind(this.baseRegistry) : value;\n }\n\n throw new ResourceAccessForbiddenError({\n minionName: this.minionName,\n resourceType: '<unscoped-registry-access>' as ResourceType,\n accessMode: ResourceAccessMode.WRITE,\n });\n },\n }) as ServicesRegistryHandlerBackendService;\n }\n\n private getService(resourceType: ResourceType): unknown {\n const service = this.baseRegistry.getService(resourceType);\n if (!service) {\n return undefined;\n }\n return this.wrapService(resourceType, service as unknown as Record<string, unknown>);\n }\n\n private getServiceOrThrow(resourceType: ResourceType): unknown {\n const service = this.baseRegistry.getServiceOrThrow(resourceType);\n return this.wrapService(resourceType, service as unknown as Record<string, unknown>);\n }\n\n private async doByOperationPath<T = unknown>(\n operationPath: ResourceConfiguration_OperationPath<any, any>,\n executionContext: ExecutionContext<any>,\n idOrIdsOrFilter?: unknown,\n data?: unknown,\n options?: unknown,\n ): Promise<T> {\n this.assertAllowedForOperationPath(operationPath);\n return this.baseRegistry.doByOperationPath(\n operationPath,\n executionContext,\n idOrIdsOrFilter,\n data,\n options,\n ) as Promise<T>;\n }\n\n private async doByExecutionContext<T = unknown>(\n executionContext: ExecutionContext<any>,\n data?: unknown,\n options?: unknown,\n ): Promise<T> {\n this.assertAllowed(\n executionContext.operation.resourceIdentifier as ResourceType,\n this.resolveAccessMode(\n executionContext.operation.resourceOperationLike as string | undefined,\n executionContext.operation.operationIdentifier as string,\n ),\n );\n return this.baseRegistry.doByExecutionContext(executionContext, data, options) as Promise<T>;\n }\n\n private wrapRegistryMethod(\n methodName: string,\n accessMode: ResourceAccessMode,\n ): (...args: unknown[]) => unknown {\n return async (...args: unknown[]) => {\n const [resourceType] = args;\n this.assertAllowed(resourceType as ResourceType, accessMode);\n return ((this.baseRegistry as unknown as Record<string, unknown>)[methodName] as (...callArgs: unknown[]) => unknown).apply(\n this.baseRegistry,\n args,\n );\n };\n }\n\n private wrapService(resourceType: ResourceType, service: Record<string, unknown>): unknown {\n if (this.serviceProxyCache.has(resourceType)) {\n return this.serviceProxyCache.get(resourceType);\n }\n\n const wrapped = new Proxy(service, {\n get: (_target, property) => {\n if (property === 'doByOperationPath') {\n return async (\n operationPath: ResourceConfiguration_OperationPath<any, any>,\n executionContext: ExecutionContext<any>,\n idOrIdsOrFilter?: unknown,\n data?: unknown,\n options?: unknown,\n ) => {\n this.assertAllowedForOperationPath(operationPath);\n return (service.doByOperationPath as (...args: unknown[]) => unknown).call(\n service,\n operationPath,\n executionContext,\n idOrIdsOrFilter,\n data,\n options,\n );\n };\n }\n if (property === 'doByExecutionContext') {\n return async (\n executionContext: ExecutionContext<any>,\n data?: unknown,\n options?: unknown,\n ) => {\n this.assertAllowed(\n resourceType,\n this.resolveAccessMode(\n executionContext.operation.resourceOperationLike as string | undefined,\n executionContext.operation.operationIdentifier as string,\n ),\n );\n return (service.doByExecutionContext as (...args: unknown[]) => unknown).call(\n service,\n executionContext,\n data,\n options,\n );\n };\n }\n if (typeof property === 'string' && READ_SERVICE_METHODS.has(property)) {\n return async (...args: unknown[]) => {\n this.assertAllowed(resourceType, ResourceAccessMode.READ);\n return (service[property] as (...callArgs: unknown[]) => unknown).apply(service, args);\n };\n }\n if (typeof property === 'string' && WRITE_SERVICE_METHODS.has(property)) {\n return async (...args: unknown[]) => {\n this.assertAllowed(resourceType, ResourceAccessMode.WRITE);\n return (service[property] as (...callArgs: unknown[]) => unknown).apply(service, args);\n };\n }\n\n // Symbol-keyed properties pass through (Symbol.toStringTag etc.).\n if (typeof property === 'symbol') {\n const value = service[property as unknown as keyof typeof service];\n return typeof value === 'function' ? value.bind(service) : value;\n }\n\n // M3 fix — fail-CLOSED. Only allow-listed property names + the\n // explicit method classifications above expose the underlying\n // service. Everything else throws so a future method on the\n // service cannot bypass the whitelist.\n if (typeof property === 'string' && ALLOW_THROUGH_SERVICE_PROPERTIES.has(property)) {\n const value = service[property as keyof typeof service];\n return typeof value === 'function' ? value.bind(service) : value;\n }\n\n throw new ResourceAccessForbiddenError({\n minionName: this.minionName,\n resourceType,\n accessMode: ResourceAccessMode.WRITE,\n });\n },\n });\n\n this.serviceProxyCache.set(resourceType, wrapped);\n return wrapped;\n }\n\n private assertAllowedForOperationPath(operationPath: ResourceConfiguration_OperationPath<any, any>): void {\n this.assertAllowed(\n operationPath.resourceIdentifier as ResourceType,\n this.resolveAccessMode(\n (operationPath as { resourceOperationLike?: string }).resourceOperationLike,\n operationPath.operationIdentifier as string,\n ),\n );\n }\n\n private resolveAccessMode(\n resourceOperationLike: string | undefined,\n operationIdentifier: string,\n ): ResourceAccessMode {\n const effectiveOperation = resourceOperationLike ?? operationIdentifier;\n return READ_OPERATION_IDENTIFIERS.has(effectiveOperation)\n ? ResourceAccessMode.READ\n : ResourceAccessMode.WRITE;\n }\n\n private assertAllowed(resourceType: ResourceType, accessMode: ResourceAccessMode): void {\n const allowlist = accessMode === ResourceAccessMode.READ\n ? this.readAllowlist\n : this.writeAllowlist;\n if (allowlist.has('*') || allowlist.has(resourceType)) {\n return;\n }\n throw new ResourceAccessForbiddenError({\n minionName: this.minionName,\n resourceType,\n accessMode,\n });\n }\n}\n"]}
1
+ {"version":3,"file":"minion-scoped-services-registry-handler.backend.service.js","sourceRoot":"","sources":["../../../../../src/base-classes/services/services/minion-scoped-services-registry-handler.backend.service.ts"],"names":[],"mappings":"AAAA,OAAO,EAGL,4BAA4B,EAC5B,kBAAkB,GACnB,MAAM,uBAAuB,CAAC;AAW/B;;;;;;;;GAQG;AACH,MAAM,0BAA0B,GAAG,IAAI,GAAG,CAAS;IACjD,MAAM;IACN,MAAM;IACN,QAAQ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BAA2B;QAE3B,MAAM,kBAAkB,GAAG,qBAAqB,IAAI,mBAAmB,CAAC;QACxE,OAAO,0BAA0B,CAAC,GAAG,CAAC,kBAAkB,CAAC;YACvD,CAAC,CAAC,kBAAkB,CAAC,IAAI;YACzB,CAAC,CAAC,kBAAkB,CAAC,KAAK,CAAC;IAC/B,CAAC;IAEO,aAAa,CAAC,YAA0B,EAAE,UAA8B;QAC9E,MAAM,SAAS,GAAG,UAAU,KAAK,kBAAkB,CAAC,IAAI;YACtD,CAAC,CAAC,IAAI,CAAC,aAAa;YACpB,CAAC,CAAC,IAAI,CAAC,cAAc,CAAC;QACxB,IAAI,SAAS,CAAC,GAAG,CAAC,GAAG,CAAC,IAAI,SAAS,CAAC,GAAG,CAAC,YAAY,CAAC,EAAE,CAAC;YACtD,OAAO;QACT,CAAC;QACD,MAAM,IAAI,4BAA4B,CAAC;YACrC,UAAU,EAAE,IAAI,CAAC,UAAU;YAC3B,YAAY;YACZ,UAAU;SACX,CAAC,CAAC;IACL,CAAC;CACF","sourcesContent":["import {\n ResourceConfiguration_OperationPath,\n ResourceType,\n ResourceAccessForbiddenError,\n ResourceAccessMode,\n} from '@wildo-ai/saas-models';\nimport type {\n AppConfiguration,\n ExecutionContext,\n ServicesRegistryHandlerBackendService,\n} from '@wildo-ai/saas-backend-lib';\n\ntype MinionResourceAccessConfig = NonNullable<\n NonNullable<AppConfiguration['minions']>[string]['resourceAccess']\n>;\n\n/**\n * Read-side operation identifiers. Anything in this set is classified\n * as a READ; anything else falls through to the path-aware classifiers\n * via `doByOperationPath` / `doByExecutionContext` rather than being\n * silently labelled WRITE (M4 fix). Custom operations and relationship\n * actions in particular cannot be classified by name — they MUST go\n * through `doByOperationPath` so the operation's own metadata drives\n * the access-mode decision.\n */\nconst READ_OPERATION_IDENTIFIERS = new Set<string>([\n 'READ',\n 'LIST',\n 'SEARCH',\n 'COUNT',\n // EXPORT serializes data outward; it's a read in v1. Listed explicitly\n // so a future EXPORT introduction does not silently classify as WRITE.\n 'EXPORT',\n]);\n\nconst READ_SERVICE_METHODS = new Set([\n 'read',\n // NOTE: `readAsSystem`/`listAsSystem` (ACL-bypassing system reads) deliberately\n // do NOT appear here — they were moved off the services registry handler onto the\n // dedicated `SystemAccessService` (Guard 3), which minion code is not granted. The\n // handler this proxy wraps no longer exposes a system-read at all.\n 'list',\n 'search',\n 'count',\n]);\n\n/**\n * Service methods classified as unconditional writes by name. The first\n * group are unambiguous CRUD writes; the polymorphic methods at the end\n * are listed conservatively as WRITE because their name alone does not\n * carry the operation's read/write intent. Worker code that needs read\n * semantics for a custom op or relationship action MUST go through\n * `doByOperationPath` so the operation's own metadata drives the\n * access-mode decision (see `resolveAccessMode`).\n */\nconst WRITE_SERVICE_METHODS = new Set([\n 'create',\n 'createMany',\n 'update',\n 'updateMany',\n 'delete',\n 'deleteMany',\n 'executeCustomOperation',\n 'applyRelationshipActionMany',\n]);\n\n/**\n * Per KD-11.A: the proxy is fail-CLOSED. A property name not in any of\n * the four sets above and not listed here is denied — minion code must\n * route through the chokepoints (`doByOperationPath`,\n * `doByExecutionContext`, `getService`, `getServiceOrThrow`) so the\n * resourceAccess whitelist applies.\n *\n * Symbol-keyed properties (e.g. `Symbol.toStringTag` for runtime\n * stringification) and a small number of harmless meta-properties are\n * allow-listed because denying them would break basic JS semantics\n * (`typeof`, `instanceof`, error formatting) without security value.\n */\nconst ALLOW_THROUGH_REGISTRY_PROPERTIES = new Set<string>([\n 'getService',\n 'getServiceOrThrow',\n 'doByOperationPath',\n 'doByExecutionContext',\n 'constructor',\n 'then', // present so Promise resolution doesn't trip when this proxy is awaited by accident\n]);\n\nconst ALLOW_THROUGH_SERVICE_PROPERTIES = new Set<string>([\n 'doByOperationPath',\n 'doByExecutionContext',\n 'constructor',\n 'then',\n]);\n\nexport class MinionScopedServicesRegistryHandlerBackendService {\n private readonly readAllowlist: Set<string>;\n private readonly writeAllowlist: Set<string>;\n private readonly serviceProxyCache = new Map<string, unknown>();\n\n constructor(\n private readonly baseRegistry: ServicesRegistryHandlerBackendService,\n private readonly minionName: string,\n resourceAccess: MinionResourceAccessConfig | undefined,\n ) {\n this.readAllowlist = new Set(resourceAccess?.read ?? []);\n this.writeAllowlist = new Set(resourceAccess?.write ?? []);\n }\n\n public asDecoratedRegistry(): ServicesRegistryHandlerBackendService {\n return new Proxy(this.baseRegistry, {\n get: (_target, property) => {\n if (property === 'getService') {\n return this.getService.bind(this);\n }\n if (property === 'getServiceOrThrow') {\n return this.getServiceOrThrow.bind(this);\n }\n if (property === 'doByOperationPath') {\n return this.doByOperationPath.bind(this);\n }\n if (property === 'doByExecutionContext') {\n return this.doByExecutionContext.bind(this);\n }\n if (typeof property === 'string' && READ_SERVICE_METHODS.has(property)) {\n return this.wrapRegistryMethod(property, ResourceAccessMode.READ);\n }\n if (typeof property === 'string' && WRITE_SERVICE_METHODS.has(property)) {\n return this.wrapRegistryMethod(property, ResourceAccessMode.WRITE);\n }\n\n // Symbol-keyed properties pass through (Symbol.toStringTag,\n // Symbol.toPrimitive, etc.) — they have no security relevance\n // and denying them breaks basic JS reflection.\n if (typeof property === 'symbol') {\n const value = (this.baseRegistry as unknown as Record<PropertyKey, unknown>)[property as unknown as string];\n return typeof value === 'function' ? value.bind(this.baseRegistry) : value;\n }\n\n // M3 fix — fail-CLOSED for unknown property names. Only the\n // explicit allow-list above and `ALLOW_THROUGH_REGISTRY_PROPERTIES`\n // expose the underlying registry; everything else throws so a\n // future method on `ServicesRegistryHandlerBackendService`\n // cannot silently bypass the resourceAccess whitelist.\n if (typeof property === 'string' && ALLOW_THROUGH_REGISTRY_PROPERTIES.has(property)) {\n const value = (this.baseRegistry as unknown as Record<PropertyKey, unknown>)[property];\n return typeof value === 'function' ? value.bind(this.baseRegistry) : value;\n }\n\n throw new ResourceAccessForbiddenError({\n minionName: this.minionName,\n resourceType: '<unscoped-registry-access>' as ResourceType,\n accessMode: ResourceAccessMode.WRITE,\n });\n },\n }) as ServicesRegistryHandlerBackendService;\n }\n\n private getService(resourceType: ResourceType): unknown {\n const service = this.baseRegistry.getService(resourceType);\n if (!service) {\n return undefined;\n }\n return this.wrapService(resourceType, service as unknown as Record<string, unknown>);\n }\n\n private getServiceOrThrow(resourceType: ResourceType): unknown {\n const service = this.baseRegistry.getServiceOrThrow(resourceType);\n return this.wrapService(resourceType, service as unknown as Record<string, unknown>);\n }\n\n private async doByOperationPath<T = unknown>(\n operationPath: ResourceConfiguration_OperationPath<any, any>,\n executionContext: ExecutionContext<any>,\n idOrIdsOrFilter?: unknown,\n data?: unknown,\n options?: unknown,\n ): Promise<T> {\n this.assertAllowedForOperationPath(operationPath);\n return this.baseRegistry.doByOperationPath(\n operationPath,\n executionContext,\n idOrIdsOrFilter,\n data,\n options,\n ) as Promise<T>;\n }\n\n private async doByExecutionContext<T = unknown>(\n executionContext: ExecutionContext<any>,\n data?: unknown,\n options?: unknown,\n ): Promise<T> {\n this.assertAllowed(\n executionContext.operation.resourceIdentifier as ResourceType,\n this.resolveAccessMode(\n executionContext.operation.resourceOperationLike as string | undefined,\n executionContext.operation.operationIdentifier as string,\n ),\n );\n return this.baseRegistry.doByExecutionContext(executionContext, data, options) as Promise<T>;\n }\n\n private wrapRegistryMethod(\n methodName: string,\n accessMode: ResourceAccessMode,\n ): (...args: unknown[]) => unknown {\n return async (...args: unknown[]) => {\n const [resourceType] = args;\n this.assertAllowed(resourceType as ResourceType, accessMode);\n return ((this.baseRegistry as unknown as Record<string, unknown>)[methodName] as (...callArgs: unknown[]) => unknown).apply(\n this.baseRegistry,\n args,\n );\n };\n }\n\n private wrapService(resourceType: ResourceType, service: Record<string, unknown>): unknown {\n if (this.serviceProxyCache.has(resourceType)) {\n return this.serviceProxyCache.get(resourceType);\n }\n\n const wrapped = new Proxy(service, {\n get: (_target, property) => {\n if (property === 'doByOperationPath') {\n return async (\n operationPath: ResourceConfiguration_OperationPath<any, any>,\n executionContext: ExecutionContext<any>,\n idOrIdsOrFilter?: unknown,\n data?: unknown,\n options?: unknown,\n ) => {\n this.assertAllowedForOperationPath(operationPath);\n return (service.doByOperationPath as (...args: unknown[]) => unknown).call(\n service,\n operationPath,\n executionContext,\n idOrIdsOrFilter,\n data,\n options,\n );\n };\n }\n if (property === 'doByExecutionContext') {\n return async (\n executionContext: ExecutionContext<any>,\n data?: unknown,\n options?: unknown,\n ) => {\n this.assertAllowed(\n resourceType,\n this.resolveAccessMode(\n executionContext.operation.resourceOperationLike as string | undefined,\n executionContext.operation.operationIdentifier as string,\n ),\n );\n return (service.doByExecutionContext as (...args: unknown[]) => unknown).call(\n service,\n executionContext,\n data,\n options,\n );\n };\n }\n if (typeof property === 'string' && READ_SERVICE_METHODS.has(property)) {\n return async (...args: unknown[]) => {\n this.assertAllowed(resourceType, ResourceAccessMode.READ);\n return (service[property] as (...callArgs: unknown[]) => unknown).apply(service, args);\n };\n }\n if (typeof property === 'string' && WRITE_SERVICE_METHODS.has(property)) {\n return async (...args: unknown[]) => {\n this.assertAllowed(resourceType, ResourceAccessMode.WRITE);\n return (service[property] as (...callArgs: unknown[]) => unknown).apply(service, args);\n };\n }\n\n // Symbol-keyed properties pass through (Symbol.toStringTag etc.).\n if (typeof property === 'symbol') {\n const value = service[property as unknown as keyof typeof service];\n return typeof value === 'function' ? value.bind(service) : value;\n }\n\n // M3 fix — fail-CLOSED. Only allow-listed property names + the\n // explicit method classifications above expose the underlying\n // service. Everything else throws so a future method on the\n // service cannot bypass the whitelist.\n if (typeof property === 'string' && ALLOW_THROUGH_SERVICE_PROPERTIES.has(property)) {\n const value = service[property as keyof typeof service];\n return typeof value === 'function' ? value.bind(service) : value;\n }\n\n throw new ResourceAccessForbiddenError({\n minionName: this.minionName,\n resourceType,\n accessMode: ResourceAccessMode.WRITE,\n });\n },\n });\n\n this.serviceProxyCache.set(resourceType, wrapped);\n return wrapped;\n }\n\n private assertAllowedForOperationPath(operationPath: ResourceConfiguration_OperationPath<any, any>): void {\n this.assertAllowed(\n operationPath.resourceIdentifier as ResourceType,\n this.resolveAccessMode(\n (operationPath as { resourceOperationLike?: string }).resourceOperationLike,\n operationPath.operationIdentifier as string,\n ),\n );\n }\n\n private resolveAccessMode(\n resourceOperationLike: string | undefined,\n operationIdentifier: string,\n ): ResourceAccessMode {\n const effectiveOperation = resourceOperationLike ?? operationIdentifier;\n return READ_OPERATION_IDENTIFIERS.has(effectiveOperation)\n ? ResourceAccessMode.READ\n : ResourceAccessMode.WRITE;\n }\n\n private assertAllowed(resourceType: ResourceType, accessMode: ResourceAccessMode): void {\n const allowlist = accessMode === ResourceAccessMode.READ\n ? this.readAllowlist\n : this.writeAllowlist;\n if (allowlist.has('*') || allowlist.has(resourceType)) {\n return;\n }\n throw new ResourceAccessForbiddenError({\n minionName: this.minionName,\n resourceType,\n accessMode,\n });\n }\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/index.ts"],"names":[],"mappings":"AAAA,cAAc,+BAA+B,CAAC;AAC9C,cAAc,2BAA2B,CAAC;AAC1C,cAAc,uCAAuC,CAAC;AACtD,cAAc,6DAA6D,CAAC;AAC5E,cAAc,sDAAsD,CAAC;AACrE,cAAc,0FAA0F,CAAC;AACzG,OAAO,EACL,8CAA8C,GAE/C,MAAM,4BAA4B,CAAC;AACpC,cAAc,wDAAwD,CAAC","sourcesContent":["export * from './inject/models/service-types';\nexport * from './inject/models/container';\nexport * from './runtime/services/define-minion-init';\nexport * from './runtime/services/start-minion-application.backend.service';\nexport * from './runtime/queue/minion-tick-consumer.backend.service';\nexport * from './base-classes/services/services/minion-scoped-services-registry-handler.backend.service';\nexport {\n projectApplicationInitializationConfigToMinion,\n type ProjectedMinionInitializationConfig,\n} from '@wildo-ai/saas-backend-lib';\nexport * from './runtime/services/own-schedule-reader.backend.service';\n"]}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAAA,cAAc,+BAA+B,CAAC;AAC9C,cAAc,2BAA2B,CAAC;AAC1C,cAAc,uCAAuC,CAAC;AACtD,cAAc,6DAA6D,CAAC;AAC5E,cAAc,sDAAsD,CAAC;AACrE,cAAc,0FAA0F,CAAC;AACzG,OAAO,EACL,8CAA8C,GAE/C,MAAM,4BAA4B,CAAC;AACpC,cAAc,wDAAwD,CAAC","sourcesContent":["export * from './inject/models/service-types';\nexport * from './inject/models/container';\nexport * from './runtime/services/define-minion-init';\nexport * from './runtime/services/start-minion-application.backend.service';\nexport * from './runtime/queue/minion-tick-consumer.backend.service';\nexport * from './base-classes/services/services/minion-scoped-services-registry-handler.backend.service';\nexport {\n projectApplicationInitializationConfigToMinion,\n type ProjectedMinionInitializationConfig,\n} from '@wildo-ai/saas-backend-lib';\nexport * from './runtime/services/own-schedule-reader.backend.service';\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"container.js","sourceRoot":"","sources":["../../../../../src/inject/models/container.ts"],"names":[],"mappings":"AAAA,OAAO,EAEL,oBAAoB,EACpB,kBAAkB,EAClB,yBAAyB,GAC1B,MAAM,4BAA4B,CAAC;AACpC,OAAO,EAAE,oCAAoC,EAAE,MAAM,iEAAiE,CAAC;AACvH,OAAO,EAAE,gCAAgC,EAAE,MAAM,0DAA0D,CAAC;AAC5G,OAAO,EAAE,+BAA+B,EAAE,MAAM,4DAA4D,CAAC;AAC7G,OAAO,EAAE,0BAA0B,EAAE,MAAM,iBAAiB,CAAC;AAI7D,IAAI,sBAA6C,CAAC;AAElD,MAAM,oBAAoB;IACK;IAA7B,YAA6B,SAAoB;QAApB,cAAS,GAAT,SAAS,CAAW;QAC/C,IAAI,CAAC,mBAAmB,EAAE,CAAC;IAC7B,CAAC;IAEM,YAAY;QACjB,OAAO,IAAI,CAAC,SAAS,CAAC;IACxB,CAAC;IAEO,mBAAmB;QACzB,IAAI,CAAC,IAAI,CAAC,SAAS,CAAC,OAAO,CAAC,0BAA0B,CAAC,6BAA6B,CAAC,EAAE,CAAC;YACtF,IAAI,CAAC,SAAS;iBACX,IAAI,CAAC,0BAA0B,CAAC,6BAA6B,CA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AC;AACzB,CAAC","sourcesContent":["import {\n type InversifyContainer,\n resetGlobalContainer,\n SAAS_SERVICE_TYPES,\n setupSaasBackendInjection,\n} from '@wildo-ai/saas-backend-lib';\nimport { StartMinionApplicationBackendService } from '../../runtime/services/start-minion-application.backend.service';\nimport { MinionTickConsumerBackendService } from '../../runtime/queue/minion-tick-consumer.backend.service';\nimport { OwnScheduleReaderBackendService } from '../../runtime/services/own-schedule-reader.backend.service';\nimport { SAAS_MINIONS_SERVICE_TYPES } from './service-types';\n\ntype Container = InversifyContainer;\n\nlet globalMinionsContainer: Container | undefined;\n\nclass SaasMinionsContainer {\n constructor(private readonly container: Container) {\n this.bindRuntimeServices();\n }\n\n public getContainer(): Container {\n return this.container;\n }\n\n private bindRuntimeServices(): void {\n if (!this.container.isBound(SAAS_MINIONS_SERVICE_TYPES.StartMinionApplicationService)) {\n this.container\n .bind(SAAS_MINIONS_SERVICE_TYPES.StartMinionApplicationService)\n .to(StartMinionApplicationBackendService)\n .inSingletonScope();\n }\n if (!this.container.isBound(SAAS_MINIONS_SERVICE_TYPES.MinionTickConsumerService)) {\n this.container\n .bind(SAAS_MINIONS_SERVICE_TYPES.MinionTickConsumerService)\n .to(MinionTickConsumerBackendService)\n .inSingletonScope();\n }\n if (!this.container.isBound(SAAS_MINIONS_SERVICE_TYPES.OwnScheduleReaderService)) {\n this.container\n .bind(SAAS_MINIONS_SERVICE_TYPES.OwnScheduleReaderService)\n .to(OwnScheduleReaderBackendService)\n .inSingletonScope();\n }\n }\n}\n\nexport function setupSaasMinionInjection(existing?: Container): Container {\n const container = existing ?? globalMinionsContainer ?? setupSaasBackendInjection();\n if (existing && !container.isBound(SAAS_SERVICE_TYPES.StartApplicationService)) {\n throw new Error(\n 'setupSaasMinionInjection(existing) requires a container that already includes saas-backend-lib bindings.',\n );\n }\n const minionsContainer = new SaasMinionsContainer(container);\n if (!existing) {\n globalMinionsContainer = minionsContainer.getContainer();\n }\n return minionsContainer.getContainer();\n}\n\nexport function getGlobalMinionsContainer(): Container {\n return globalMinionsContainer ?? setupSaasMinionInjection();\n}\n\nexport function resetGlobalMinionsContainer(): void {\n globalMinionsContainer = undefined;\n resetGlobalContainer();\n}\n"]}
1
+ {"version":3,"file":"container.js","sourceRoot":"","sources":["../../../../src/inject/models/container.ts"],"names":[],"mappings":"AAAA,OAAO,EAEL,oBAAoB,EACpB,kBAAkB,EAClB,yBAAyB,GAC1B,MAAM,4BAA4B,CAAC;AACpC,OAAO,EAAE,oCAAoC,EAAE,MAAM,iEAAiE,CAAC;AACvH,OAAO,EAAE,gCAAgC,EAAE,MAAM,0DAA0D,CAAC;AAC5G,OAAO,EAAE,+BAA+B,EAAE,MAAM,4DAA4D,CAAC;AAC7G,OAAO,EAAE,0BAA0B,EAAE,MAAM,iBAAiB,CAAC;AAI7D,IAAI,sBAA6C,CAAC;AAElD,MAAM,oBAAoB;IACK;IAA7B,YAA6B,SAAoB;QAApB,cAAS,GAAT,SAAS,CAAW;QAC/C,IAAI,CAAC,mBAAmB,EAAE,CAAC;IAC7B,CAAC;IAEM,YAAY;QACjB,OAAO,IAAI,CAAC,SAAS,CAAC;IACxB,CAAC;IAEO,mBAAmB;QACzB,IAAI,CAAC,IAAI,CAAC,SAAS,CAAC,OAAO,CAAC,0BAA0B,CAAC,6BAA6B,CAAC,EAAE,CAAC;YACtF,IAAI,CAAC,SAAS;iBACX,IAAI,CAAC,0BAA0B,CAAC,6BAA6B,CAAC;iBAC9D,EAAE,CAAC,oCAAoC,CAAC;iBACxC,gBAAgB,EAAE,CAAC;QACxB,CAAC;QACD,IAAI,CAAC,IAAI,CAAC,SAAS,CAAC,OAAO,CAAC,0BAA0B,CAAC,yBAAyB,CAAC,EAAE,CAAC;YAClF,IAAI,CAAC,SAAS;iBACX,IAAI,CAAC,0BAA0B,CAAC,yBAAyB,CAAC;iBAC1D,EAAE,CAAC,gCAAgC,CAAC;iBACpC,gBAAgB,EAAE,CAAC;QACxB,CAAC;QACD,IAAI,CAAC,IAAI,CAAC,SAAS,CAAC,OAAO,CAAC,0BAA0B,CAAC,wBAAwB,CAAC,EAAE,CAAC;YACjF,IAAI,CAAC,SAAS;iBACX,IAAI,CAAC,0BAA0B,CAAC,wBAAwB,CAAC;iBACzD,EAAE,CAAC,+BAA+B,CAAC;iBACnC,gBAAgB,EAAE,CAAC;QACxB,CAAC;IACH,CAAC;CACF;AAED,MAAM,UAAU,wBAAwB,CAAC,QAAoB;IAC3D,MAAM,SAAS,GAAG,QAAQ,IAAI,sBAAsB,IAAI,yBAAyB,EAAE,CAAC;IACpF,IAAI,QAAQ,IAAI,CAAC,SAAS,CAAC,OAAO,CAAC,kBAAkB,CAAC,uBAAuB,CAAC,EAAE,CAAC;QAC/E,MAAM,IAAI,KAAK,CACb,0GAA0G,CAC3G,CAAC;IACJ,CAAC;IACD,MAAM,gBAAgB,GAAG,IAAI,oBAAoB,CAAC,SAAS,CAAC,CAAC;IAC7D,IAAI,CAAC,QAAQ,EAAE,CAAC;QACd,sBAAsB,GAAG,gBAAgB,CAAC,YAAY,EAAE,CAAC;IAC3D,CAAC;IACD,OAAO,gBAAgB,CAAC,YAAY,EAAE,CAAC;AACzC,CAAC;AAED,MAAM,UAAU,yBAAyB;IACvC,OAAO,sBAAsB,IAAI,wBAAwB,EAAE,CAAC;AAC9D,CAAC;AAED,MAAM,UAAU,2BAA2B;IACzC,sBAAsB,GAAG,SAAS,CAAC;IACnC,oBAAoB,EAAE,CAAC;AACzB,CAAC","sourcesContent":["import {\n type InversifyContainer,\n resetGlobalContainer,\n SAAS_SERVICE_TYPES,\n setupSaasBackendInjection,\n} from '@wildo-ai/saas-backend-lib';\nimport { StartMinionApplicationBackendService } from '../../runtime/services/start-minion-application.backend.service';\nimport { MinionTickConsumerBackendService } from '../../runtime/queue/minion-tick-consumer.backend.service';\nimport { OwnScheduleReaderBackendService } from '../../runtime/services/own-schedule-reader.backend.service';\nimport { SAAS_MINIONS_SERVICE_TYPES } from './service-types';\n\ntype Container = InversifyContainer;\n\nlet globalMinionsContainer: Container | undefined;\n\nclass SaasMinionsContainer {\n constructor(private readonly container: Container) {\n this.bindRuntimeServices();\n }\n\n public getContainer(): Container {\n return this.container;\n }\n\n private bindRuntimeServices(): void {\n if (!this.container.isBound(SAAS_MINIONS_SERVICE_TYPES.StartMinionApplicationService)) {\n this.container\n .bind(SAAS_MINIONS_SERVICE_TYPES.StartMinionApplicationService)\n .to(StartMinionApplicationBackendService)\n .inSingletonScope();\n }\n if (!this.container.isBound(SAAS_MINIONS_SERVICE_TYPES.MinionTickConsumerService)) {\n this.container\n .bind(SAAS_MINIONS_SERVICE_TYPES.MinionTickConsumerService)\n .to(MinionTickConsumerBackendService)\n .inSingletonScope();\n }\n if (!this.container.isBound(SAAS_MINIONS_SERVICE_TYPES.OwnScheduleReaderService)) {\n this.container\n .bind(SAAS_MINIONS_SERVICE_TYPES.OwnScheduleReaderService)\n .to(OwnScheduleReaderBackendService)\n .inSingletonScope();\n }\n }\n}\n\nexport function setupSaasMinionInjection(existing?: Container): Container {\n const container = existing ?? globalMinionsContainer ?? setupSaasBackendInjection();\n if (existing && !container.isBound(SAAS_SERVICE_TYPES.StartApplicationService)) {\n throw new Error(\n 'setupSaasMinionInjection(existing) requires a container that already includes saas-backend-lib bindings.',\n );\n }\n const minionsContainer = new SaasMinionsContainer(container);\n if (!existing) {\n globalMinionsContainer = minionsContainer.getContainer();\n }\n return minionsContainer.getContainer();\n}\n\nexport function getGlobalMinionsContainer(): Container {\n return globalMinionsContainer ?? setupSaasMinionInjection();\n}\n\nexport function resetGlobalMinionsContainer(): void {\n globalMinionsContainer = undefined;\n resetGlobalContainer();\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"service-types.js","sourceRoot":"","sources":["../../../../../src/inject/models/service-types.ts"],"names":[],"mappings":"AAMA,MAAM,CAAC,MAAM,0BAA0B,GAA4B;IACjE,6BAA6B,EAAE,MAAM,CAAC,GAAG,CAAC,4CAA4C,CAAC;IACvF,yBAAyB,EAAE,MAAM,CAAC,GAAG,CAAC,wCAAwC,CAAC;IAC/E,wBAAwB,EAAE,MAAM,CAAC,GAAG,CAAC,uCAAuC,CAAC;CAC9E,CAAC","sourcesContent":["export interface SaasMinionsServiceTypes {\n readonly StartMinionApplicationService: symbol;\n readonly MinionTickConsumerService: symbol;\n readonly OwnScheduleReaderService: symbol;\n}\n\nexport const SAAS_MINIONS_SERVICE_TYPES: SaasMinionsServiceTypes = {\n StartMinionApplicationService: Symbol.for('SaaS.Minions.StartMinionApplicationService'),\n MinionTickConsumerService: Symbol.for('SaaS.Minions.MinionTickConsumerService'),\n OwnScheduleReaderService: Symbol.for('SaaS.Minions.OwnScheduleReaderService'),\n};\n"]}
1
+ {"version":3,"file":"service-types.js","sourceRoot":"","sources":["../../../../src/inject/models/service-types.ts"],"names":[],"mappings":"AAMA,MAAM,CAAC,MAAM,0BAA0B,GAA4B;IACjE,6BAA6B,EAAE,MAAM,CAAC,GAAG,CAAC,4CAA4C,CAAC;IACvF,yBAAyB,EAAE,MAAM,CAAC,GAAG,CAAC,wCAAwC,CAAC;IAC/E,wBAAwB,EAAE,MAAM,CAAC,GAAG,CAAC,uCAAuC,CAAC;CAC9E,CAAC","sourcesContent":["export interface SaasMinionsServiceTypes {\n readonly StartMinionApplicationService: symbol;\n readonly MinionTickConsumerService: symbol;\n readonly OwnScheduleReaderService: symbol;\n}\n\nexport const SAAS_MINIONS_SERVICE_TYPES: SaasMinionsServiceTypes = {\n StartMinionApplicationService: Symbol.for('SaaS.Minions.StartMinionApplicationService'),\n MinionTickConsumerService: Symbol.for('SaaS.Minions.MinionTickConsumerService'),\n OwnScheduleReaderService: Symbol.for('SaaS.Minions.OwnScheduleReaderService'),\n};\n"]}
@@ -14,7 +14,7 @@ export type MinionTickReconciler = (tick: MinionTickInvocation, attempt: Schedul
14
14
  * Minion-side consumer for the per-minion tick queue
15
15
  * (`wildo.queue.<appId>.minion-tick.<minionName>`, see `QueueNamingUtils.buildMinionTickQueueName`).
16
16
  *
17
- * Per KD-12 of `.claude/plans/minions-and-workers-implementation.md`:
17
+ * Contract:
18
18
  * - Subscribes only to the queue dedicated to THIS minion (no shared
19
19
  * `scheduled` queue subscription, so the backend-api and minion don't
20
20
  * compete on cron tick deliveries).
@@ -28,7 +28,7 @@ export type MinionTickReconciler = (tick: MinionTickInvocation, attempt: Schedul
28
28
  * tick that could not be recorded is NACKed.
29
29
  * - Dispatches `MINION_TICK` tokens that match this minion's identity to
30
30
  * the registered handler. The handler typically routes into the
31
- * locally-hosted `flowsActorsRegistry` per Q9 LOCKED.
31
+ * minion's own locally-hosted `flowsActorsRegistry`.
32
32
  *
33
33
  * Duplicate deliveries and recovery of one occurrence belong to the durable
34
34
  * coordinator. Overlap between DISTINCT occurrences remains the handler's
@@ -67,6 +67,15 @@ export declare class MinionTickConsumerBackendService {
67
67
  */
68
68
  resolveTickReview(input: Omit<Parameters<ScheduledExecutionRunner['resolveReview']>[0], 'queueName'>): Promise<void>;
69
69
  isRunning(): boolean;
70
+ /**
71
+ * Whether this consumer can still RECEIVE a tick: subscribed, and the broker connection is up.
72
+ *
73
+ * `isRunning()` alone is not enough. The RabbitMQ adapter does not reconnect, so after a broker restart the
74
+ * consumer stays "running" over a closed connection and no tick will ever arrive again. This is what the
75
+ * minion liveness heartbeat asks before each beat (#1859), so that state ends in a restart instead of a
76
+ * minion that is alive and deaf.
77
+ */
78
+ isReceiving(): boolean;
70
79
  private handleMessage;
71
80
  }
72
81
  //# sourceMappingURL=minion-tick-consumer.backend.service.d.ts.map
@@ -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,EAEtC,wBAAwB,EACxB,+BAA+B,EAC/B,+BAA+B,EAC/B,mCAAmC,EAEnC,KAAK,kBAAkB,EACxB,MAAM,4BAA4B,CAAC;AACpC,OAAO,E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AAE,+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;CAuD5B"}
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,EAEtC,wBAAwB,EACxB,+BAA+B,EAC/B,+BAA+B,EAC/B,mCAAmC,EAEnC,KAAK,kBAAkB,EACxB,MAAM,4BAA4B,CAAC;AACpC,OAAO,EAEc,KAAK,uBAAuB,EAAE,KAAK,uBAAuB,EAAE,KAAK,uBAAuB,EAAE,KAAK,6BAA6B,EAChJ,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,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B,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;IAI3B;;;;;;;OAOG;IACI,WAAW,IAAI,OAAO;YAIf,aAAa;CAuD5B"}
@@ -17,7 +17,7 @@ import { QueueNamingUtils, JobPayloadSchema, JobType, JobInitiator, JobStatus, }
17
17
  * Minion-side consumer for the per-minion tick queue
18
18
  * (`wildo.queue.<appId>.minion-tick.<minionName>`, see `QueueNamingUtils.buildMinionTickQueueName`).
19
19
  *
20
- * Per KD-12 of `.claude/plans/minions-and-workers-implementation.md`:
20
+ * Contract:
21
21
  * - Subscribes only to the queue dedicated to THIS minion (no shared
22
22
  * `scheduled` queue subscription, so the backend-api and minion don't
23
23
  * compete on cron tick deliveries).
@@ -31,7 +31,7 @@ import { QueueNamingUtils, JobPayloadSchema, JobType, JobInitiator, JobStatus, }
31
31
  * tick that could not be recorded is NACKed.
32
32
  * - Dispatches `MINION_TICK` tokens that match this minion's identity to
33
33
  * the registered handler. The handler typically routes into the
34
- * locally-hosted `flowsActorsRegistry` per Q9 LOCKED.
34
+ * minion's own locally-hosted `flowsActorsRegistry`.
35
35
  *
36
36
  * Duplicate deliveries and recovery of one occurrence belong to the durable
37
37
  * coordinator. Overlap between DISTINCT occurrences remains the handler's
@@ -153,6 +153,17 @@ let MinionTickConsumerBackendService = class MinionTickConsumerBackendService {
153
153
  isRunning() {
154
154
  return this.isConsuming;
155
155
  }
156
+ /**
157
+ * Whether this consumer can still RECEIVE a tick: subscribed, and the broker connection is up.
158
+ *
159
+ * `isRunning()` alone is not enough. The RabbitMQ adapter does not reconnect, so after a broker restart the
160
+ * consumer stays "running" over a closed connection and no tick will ever arrive again. This is what the
161
+ * minion liveness heartbeat asks before each beat (#1859), so that state ends in a restart instead of a
162
+ * minion that is alive and deaf.
163
+ */
164
+ isReceiving() {
165
+ return this.isConsuming && this.adapter.isConnected();
166
+ }
156
167
  async handleMessage(msg, channel, applicationId, expectedMinionName, queueName, resolver) {
157
168
  this.shutdownManager.jobStarted();
158
169
  let admitted;
@@ -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,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;;;;;;;;;;;;;;;;;;;;;;;GAuBG;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,CA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BAAmB,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;AA3MY,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,CA2M5C","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 ScheduledDeliveryVerdict,\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. An AUTHENTIC tick that\n * arrived after its admission window (usually because the minion was down;\n * see `ScheduledDeliveryLateness`) is recorded as\n * a missed occurrence and acknowledged, never run (#2212); only a late\n * tick that could not be recorded is NACKed.\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 delivery = await this.scheduledMessageVerifier.verifyAndExtractMinionTick(msg.content.toString(), expectedMinionName);\n const tick = delivery?.value;\n // Signature/target checks do not establish receiving-application ownership.\n // This comparison must precede every durable insert and handler resolution — a LATE tick's\n // included: a genuine token addressed elsewhere is foreign whether or not it is on time.\n if (!delivery || !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 if (delivery.verdict === ScheduledDeliveryVerdict.LATE) {\n // Genuine, past its admission deadline: the tick was missed — usually because this minion was\n // not consuming, though the scheduler can share the delay (see `ScheduledDeliveryLateness`).\n // Recorded and acknowledged, reported once per drain by the runner (#2212);\n // dead-lettered only if it could not be recorded.\n accepted = await this.runner.recordLateDelivery(job, queueName, resolver, delivery.lateness);\n } else {\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 }\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"]}
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,wBAAwB,EACxB,+BAA+B,EAC/B,+BAA+B,EAC/B,mCAAmC,GAGpC,MAAM,4BAA4B,CAAC;AACpC,OAAO,EACL,gBAAgB,EAAE,gBAAgB,EA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wB,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,CAuN5C","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 ScheduledDeliveryVerdict,\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 * Contract:\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. An AUTHENTIC tick that\n * arrived after its admission window (usually because the minion was down;\n * see `ScheduledDeliveryLateness`) is recorded as\n * a missed occurrence and acknowledged, never run (#2212); only a late\n * tick that could not be recorded is NACKed.\n * - Dispatches `MINION_TICK` tokens that match this minion's identity to\n * the registered handler. The handler typically routes into the\n * minion's own locally-hosted `flowsActorsRegistry`.\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 /**\n * Whether this consumer can still RECEIVE a tick: subscribed, and the broker connection is up.\n *\n * `isRunning()` alone is not enough. The RabbitMQ adapter does not reconnect, so after a broker restart the\n * consumer stays \"running\" over a closed connection and no tick will ever arrive again. This is what the\n * minion liveness heartbeat asks before each beat (#1859), so that state ends in a restart instead of a\n * minion that is alive and deaf.\n */\n public isReceiving(): boolean {\n return this.isConsuming && this.adapter.isConnected();\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 delivery = await this.scheduledMessageVerifier.verifyAndExtractMinionTick(msg.content.toString(), expectedMinionName);\n const tick = delivery?.value;\n // Signature/target checks do not establish receiving-application ownership.\n // This comparison must precede every durable insert and handler resolution — a LATE tick's\n // included: a genuine token addressed elsewhere is foreign whether or not it is on time.\n if (!delivery || !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 if (delivery.verdict === ScheduledDeliveryVerdict.LATE) {\n // Genuine, past its admission deadline: the tick was missed — usually because this minion was\n // not consuming, though the scheduler can share the delay (see `ScheduledDeliveryLateness`).\n // Recorded and acknowledged, reported once per drain by the runner (#2212);\n // dead-lettered only if it could not be recorded.\n accepted = await this.runner.recordLateDelivery(job, queueName, resolver, delivery.lateness);\n } else {\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 }\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"]}
@@ -20,6 +20,10 @@ export interface MinionProviderRuntimeArtifact {
20
20
  providerRuntimeImports?: ProviderRuntimeArtifact['providerRuntimeImports'];
21
21
  /** Mirrored for the same reason: the projection narrows and forwards it (#1672). */
22
22
  providerRuntimeAugmentations?: ProviderRuntimeArtifact['providerRuntimeAugmentations'];
23
+ /** Mirrored for the same reason: the projection narrows and forwards it (#3513). */
24
+ providerProcessingRegions?: ProviderRuntimeArtifact['providerProcessingRegions'];
25
+ /** Mirrored for the same reason: the projection narrows and forwards it (#2294), and the loader re-applies it. */
26
+ providerDataResidency?: ProviderRuntimeArtifact['providerDataResidency'];
23
27
  providerGraphDigest?: ProviderRuntimeArtifact['providerGraphDigest'];
24
28
  lockfileSectionDigest?: ProviderRuntimeArtifact['lockfileSectionDigest'];
25
29
  artifactKind: 'minions';
@@ -37,12 +41,11 @@ export interface MinionProviderRuntimeArtifact {
37
41
  * minion startup rebinds the services registry to the scoped decorator before any
38
42
  * tick is delivered.
39
43
  *
40
- * So a minion's effective authority is the INTERSECTION of two independent doors
41
- * (see `.claude/plans/minion-runtime-scope.md` D6):
44
+ * So a minion's effective authority is the INTERSECTION of two independent doors:
42
45
  *
43
46
  * - `resourceAccess` — operator-declared containment, enforced by the DI proxy;
44
47
  * - the system-access door — the sanctioned per-tenant-authorization bypass, which
45
- * for a minion is fail-closed on audit (D9 + OQ-5b): audited, or refused.
48
+ * for a minion is fail-closed on audit: audited, or refused.
46
49
  *
47
50
  * Neither subsumes the other. A resource the ACL forbids is refused even though the
48
51
  * system-access door would have allowed it, and a read the ACL permits is still
@@ -94,8 +97,8 @@ export type MinionInitializationConfig = Omit<ProjectedMinionInitializationConfi
94
97
  * the locally declared tickRecovery contract, never broker redelivery alone.
95
98
  *
96
99
  * Minion authors typically route the tick into the locally-hosted
97
- * `flowsActorsRegistry` (per Q9 LOCKED — per-minion-local actor
98
- * catalog). If omitted, the consumer still subscribes to the
100
+ * `flowsActorsRegistry` — each minion hosts its own local actor
101
+ * catalog rather than a shared one. If omitted, the consumer still subscribes to the
99
102
  * per-minion queue but refuses execution. A missing handler must never
100
103
  * be recorded as successful work.
101
104
  */
@@ -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,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,CA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,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;IACrB,YAAY,CAAC,EAAE,uBAAuB,CAAC,cAAc,CAAC,CAAC;IACvD;;;;;;OAMG;IACH,sBAAsB,CAAC,EAAE,uBAAuB,CAAC,wBAAwB,CAAC,CAAC;IAC3E,oFAAoF;IACpF,4BAA4B,CAAC,EAAE,uBAAuB,CAAC,8BAA8B,CAAC,CAAC;IACvF,oFAAoF;IACpF,yBAAyB,CAAC,EAAE,uBAAuB,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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":"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
+ {"version":3,"file":"define-minion-init.js","sourceRoot":"","sources":["../../../../src/runtime/services/define-minion-init.ts"],"names":[],"mappings":"AA+HA,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 /** Mirrored for the same reason: the projection narrows and forwards it (#3513). */\n providerProcessingRegions?: ProviderRuntimeArtifact['providerProcessingRegions'];\n /** Mirrored for the same reason: the projection narrows and forwards it (#2294), and the loader re-applies it. */\n providerDataResidency?: ProviderRuntimeArtifact['providerDataResidency'];\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 *\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: 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` — each minion hosts its own local actor\n * catalog rather than a shared one. 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"]}
@@ -0,0 +1,57 @@
1
+ import { type LoggerService } from '@wildo-ai/saas-backend-lib';
2
+ import { type MinionLivenessHeartbeatSettings } from '@wildo-ai/platform-config-lib';
3
+ /**
4
+ * The producer half of a minion's file liveness contract (#1859).
5
+ *
6
+ * The probe half — the `exec` command the k8s `livenessProbe`/`startupProbe` and the compose `healthcheck`
7
+ * run, and their cadence — is rendered from the same parsed `wildo.minion.config.ts > liveness` by
8
+ * `minion-liveness.contracts.ts` in `@wildo-ai/platform-config-lib`, which also renders the env this
9
+ * writer is configured from. Read that module's header for how `heartbeat.intervalSec`, `staleAfterSec`,
10
+ * `periodSeconds` and `failureThreshold` relate.
11
+ *
12
+ * ## What a heartbeat asserts
13
+ *
14
+ * Not that the process exists: a process whose broker connection has closed is alive and useless, because
15
+ * the RabbitMQ adapter does not reconnect and the minion will never receive another tick. So every beat asks
16
+ * `isWorkLoopAlive()` first — wired by minion startup to "the tick consumer is subscribed and the broker
17
+ * connection is up" — and writes nothing when the answer is no. The file then goes stale, the probe fails,
18
+ * and the kubelet restarts the minion into a fresh connection, which is the only recovery there is.
19
+ *
20
+ * A long-running tick does not stop the beats. Ticks run detached from receipt and the beat is a timer, so
21
+ * the heartbeat stays fresh for as long as the handler awaits I/O; only a handler that blocks the event loop
22
+ * for longer than the stale window is restarted.
23
+ *
24
+ * ## The write is atomic
25
+ *
26
+ * Each beat writes a sibling temporary file and renames it over the heartbeat, so the probe never reads a
27
+ * half-written number. A torn read would fail the probe's numeric check, and a few of those in a row would
28
+ * restart a healthy minion.
29
+ */
30
+ export declare class MinionLivenessHeartbeat {
31
+ private readonly settings;
32
+ private readonly isWorkLoopAlive;
33
+ private readonly logger;
34
+ private readonly now;
35
+ private timer;
36
+ private inFlight;
37
+ /** Logged on the transition only, so a stopped loop does not write one warning per interval. */
38
+ private reportedNotAlive;
39
+ constructor(settings: MinionLivenessHeartbeatSettings, isWorkLoopAlive: () => boolean, logger: Pick<LoggerService, 'info' | 'warn' | 'error'>, now?: () => number);
40
+ /**
41
+ * Remove a heartbeat left by an earlier process, so nothing can read as alive before this one has beaten.
42
+ * Missing is the normal case.
43
+ */
44
+ static clear(settings: MinionLivenessHeartbeatSettings, logger: Pick<LoggerService, 'warn'>): Promise<void>;
45
+ /** Writes the first beat now, then one every `intervalSec`. Idempotent. */
46
+ start(): Promise<void>;
47
+ /**
48
+ * Stops beating and removes the heartbeat, so a stopping minion reads as not alive at once rather than
49
+ * one stale window later.
50
+ */
51
+ stop(): Promise<void>;
52
+ isRunning(): boolean;
53
+ /** One beat. Exposed for tests; the timer calls it. Never overlaps itself. */
54
+ beat(): Promise<void>;
55
+ private writeIfAlive;
56
+ }
57
+ //# sourceMappingURL=minion-liveness-heartbeat.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"minion-liveness-heartbeat.d.ts","sourceRoot":"","sources":["../../../../src/runtime/services/minion-liveness-heartbeat.ts"],"names":[],"mappings":"AAEA,OAAO,EAAuB,KAAK,aAAa,EAAE,MAAM,4BAA4B,CAAC;AACrF,OAAO,EAAiC,KAAK,+BAA+B,EAAE,MAAM,+BAA+B,CAAC;AAEpH;;;;;;;;;;;;;;;;;;;;;;;;;;GA0BG;AACH,qBAAa,uBAAuB;IAOhC,OAAO,CAAC,QAAQ,CAAC,QAAQ;IACzB,OAAO,CAAC,QAAQ,CAAC,eAAe;IAChC,OAAO,CAAC,QAAQ,CAAC,MAAM;IACvB,OAAO,CAAC,QAAQ,CAAC,GAAG;IATtB,OAAO,CAAC,KAAK,CAA6C;IAC1D,OAAO,CAAC,QAAQ,CAA4B;IAC5C,gGAAgG;IAChG,OAAO,CAAC,gBAAgB,CAAS;gBAGd,QAAQ,EAAE,+BAA+B,EACzC,eAAe,EAAE,MAAM,OAAO,EAC9B,MAAM,EAAE,IAAI,CAAC,aAAa,EAAE,MAAM,GAAG,MAAM,GAAG,OAAO,CAAC,EACtD,GAAG,GAAE,MAAM,MAAiB;IAG/C;;;OAGG;WACiB,KAAK,CACvB,QAAQ,EAAE,+BAA+B,EACzC,MAAM,EAAE,IAAI,CAAC,aAAa,EAAE,MAAM,CAAC,GAClC,OAAO,CAAC,IAAI,CAAC;IAUhB,2EAA2E;IAC9D,KAAK,IAAI,OAAO,CAAC,IAAI,CAAC;IAenC;;;OAGG;IACU,IAAI,IAAI,OAAO,CAAC,IAAI,CAAC;IAO3B,SAAS,IAAI,OAAO;IAI3B,8EAA8E;IACjE,IAAI,IAAI,OAAO,CAAC,IAAI,CAAC;YAQpB,YAAY;CAuB3B"}
@@ -0,0 +1,125 @@
1
+ import { mkdir, rename, unlink, writeFile } from 'node:fs/promises';
2
+ import { dirname } from 'node:path';
3
+ import { describeCaughtError } from '@wildo-ai/saas-backend-lib';
4
+ import { encodeMinionLivenessHeartbeat } from '@wildo-ai/platform-config-lib';
5
+ /**
6
+ * The producer half of a minion's file liveness contract (#1859).
7
+ *
8
+ * The probe half — the `exec` command the k8s `livenessProbe`/`startupProbe` and the compose `healthcheck`
9
+ * run, and their cadence — is rendered from the same parsed `wildo.minion.config.ts > liveness` by
10
+ * `minion-liveness.contracts.ts` in `@wildo-ai/platform-config-lib`, which also renders the env this
11
+ * writer is configured from. Read that module's header for how `heartbeat.intervalSec`, `staleAfterSec`,
12
+ * `periodSeconds` and `failureThreshold` relate.
13
+ *
14
+ * ## What a heartbeat asserts
15
+ *
16
+ * Not that the process exists: a process whose broker connection has closed is alive and useless, because
17
+ * the RabbitMQ adapter does not reconnect and the minion will never receive another tick. So every beat asks
18
+ * `isWorkLoopAlive()` first — wired by minion startup to "the tick consumer is subscribed and the broker
19
+ * connection is up" — and writes nothing when the answer is no. The file then goes stale, the probe fails,
20
+ * and the kubelet restarts the minion into a fresh connection, which is the only recovery there is.
21
+ *
22
+ * A long-running tick does not stop the beats. Ticks run detached from receipt and the beat is a timer, so
23
+ * the heartbeat stays fresh for as long as the handler awaits I/O; only a handler that blocks the event loop
24
+ * for longer than the stale window is restarted.
25
+ *
26
+ * ## The write is atomic
27
+ *
28
+ * Each beat writes a sibling temporary file and renames it over the heartbeat, so the probe never reads a
29
+ * half-written number. A torn read would fail the probe's numeric check, and a few of those in a row would
30
+ * restart a healthy minion.
31
+ */
32
+ export class MinionLivenessHeartbeat {
33
+ settings;
34
+ isWorkLoopAlive;
35
+ logger;
36
+ now;
37
+ timer;
38
+ inFlight;
39
+ /** Logged on the transition only, so a stopped loop does not write one warning per interval. */
40
+ reportedNotAlive = false;
41
+ constructor(settings, isWorkLoopAlive, logger, now = Date.now) {
42
+ this.settings = settings;
43
+ this.isWorkLoopAlive = isWorkLoopAlive;
44
+ this.logger = logger;
45
+ this.now = now;
46
+ }
47
+ /**
48
+ * Remove a heartbeat left by an earlier process, so nothing can read as alive before this one has beaten.
49
+ * Missing is the normal case.
50
+ */
51
+ static async clear(settings, logger) {
52
+ try {
53
+ await unlink(settings.filePath);
54
+ }
55
+ catch (error) {
56
+ if (error.code !== 'ENOENT') {
57
+ logger.warn('Could not remove the minion liveness heartbeat', { filePath: settings.filePath, error: describeCaughtError(error) });
58
+ }
59
+ }
60
+ }
61
+ /** Writes the first beat now, then one every `intervalSec`. Idempotent. */
62
+ async start() {
63
+ if (this.timer)
64
+ return;
65
+ this.timer = setInterval(() => {
66
+ void this.beat();
67
+ }, this.settings.intervalSec * 1000);
68
+ // The heartbeat must never be what keeps a process up: a minion with nothing else holding its event loop
69
+ // open has stopped working, and exiting is the honest outcome.
70
+ this.timer.unref();
71
+ await this.beat();
72
+ this.logger.info('Minion liveness heartbeat started', {
73
+ filePath: this.settings.filePath,
74
+ intervalSec: this.settings.intervalSec,
75
+ });
76
+ }
77
+ /**
78
+ * Stops beating and removes the heartbeat, so a stopping minion reads as not alive at once rather than
79
+ * one stale window later.
80
+ */
81
+ async stop() {
82
+ if (this.timer)
83
+ clearInterval(this.timer);
84
+ this.timer = undefined;
85
+ await this.inFlight;
86
+ await MinionLivenessHeartbeat.clear(this.settings, this.logger);
87
+ }
88
+ isRunning() {
89
+ return this.timer !== undefined;
90
+ }
91
+ /** One beat. Exposed for tests; the timer calls it. Never overlaps itself. */
92
+ async beat() {
93
+ if (this.inFlight)
94
+ return this.inFlight;
95
+ this.inFlight = this.writeIfAlive().finally(() => {
96
+ this.inFlight = undefined;
97
+ });
98
+ return this.inFlight;
99
+ }
100
+ async writeIfAlive() {
101
+ if (!this.isWorkLoopAlive()) {
102
+ if (!this.reportedNotAlive) {
103
+ this.reportedNotAlive = true;
104
+ this.logger.warn('Minion work loop is not receiving ticks; the liveness heartbeat is withheld so the probe fails', {
105
+ filePath: this.settings.filePath,
106
+ });
107
+ }
108
+ return;
109
+ }
110
+ this.reportedNotAlive = false;
111
+ const temporaryPath = `${this.settings.filePath}.${process.pid}.tmp`;
112
+ try {
113
+ // The schema keeps the file inside a writable mount; a sub-directory of one may not exist yet.
114
+ await mkdir(dirname(this.settings.filePath), { recursive: true });
115
+ await writeFile(temporaryPath, encodeMinionLivenessHeartbeat(this.now()), 'utf8');
116
+ await rename(temporaryPath, this.settings.filePath);
117
+ }
118
+ catch (error) {
119
+ // Nothing to retry here: an unwritable heartbeat (a read-only rootfs without its `/tmp` mount) fails the
120
+ // probe, and the restart that follows is the correct outcome for a minion that cannot prove it is alive.
121
+ this.logger.error('Could not write the minion liveness heartbeat', { filePath: this.settings.filePath, error: describeCaughtError(error) });
122
+ }
123
+ }
124
+ }
125
+ //# sourceMappingURL=minion-liveness-heartbeat.js.map