@pattern-stack/codegen 0.14.0 → 0.14.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (30) hide show
  1. package/dist/runtime/subsystems/bridge/bridge-delivery.memory-backend.d.ts +1 -1
  2. package/dist/runtime/subsystems/bridge/bridge-delivery.memory-backend.js +2 -2
  3. package/dist/runtime/subsystems/bridge/bridge-delivery.memory-backend.js.map +1 -1
  4. package/dist/runtime/subsystems/bridge/bridge.module.js +172 -159
  5. package/dist/runtime/subsystems/bridge/bridge.module.js.map +1 -1
  6. package/dist/runtime/subsystems/bridge/index.js +154 -141
  7. package/dist/runtime/subsystems/bridge/index.js.map +1 -1
  8. package/dist/runtime/subsystems/index.js +161 -148
  9. package/dist/runtime/subsystems/index.js.map +1 -1
  10. package/dist/runtime/subsystems/jobs/index.js +128 -115
  11. package/dist/runtime/subsystems/jobs/index.js.map +1 -1
  12. package/dist/runtime/subsystems/jobs/job-orchestrator.memory-backend.js +128 -6
  13. package/dist/runtime/subsystems/jobs/job-orchestrator.memory-backend.js.map +1 -1
  14. package/dist/runtime/subsystems/jobs/job-run-service.memory-backend.js +17 -0
  15. package/dist/runtime/subsystems/jobs/job-run-service.memory-backend.js.map +1 -1
  16. package/dist/runtime/subsystems/jobs/job-step-service.memory-backend.js +25 -2
  17. package/dist/runtime/subsystems/jobs/job-step-service.memory-backend.js.map +1 -1
  18. package/dist/runtime/subsystems/jobs/job-worker.module.d.ts +26 -1
  19. package/dist/runtime/subsystems/jobs/job-worker.module.js +150 -137
  20. package/dist/runtime/subsystems/jobs/job-worker.module.js.map +1 -1
  21. package/dist/runtime/subsystems/jobs/jobs-domain.module.js +133 -124
  22. package/dist/runtime/subsystems/jobs/jobs-domain.module.js.map +1 -1
  23. package/dist/src/cli/index.js +804 -454
  24. package/dist/src/cli/index.js.map +1 -1
  25. package/package.json +1 -1
  26. package/runtime/subsystems/bridge/bridge-delivery.memory-backend.ts +8 -1
  27. package/runtime/subsystems/jobs/job-orchestrator.memory-backend.ts +8 -3
  28. package/runtime/subsystems/jobs/job-run-service.memory-backend.ts +4 -1
  29. package/runtime/subsystems/jobs/job-step-service.memory-backend.ts +7 -2
  30. package/runtime/subsystems/jobs/job-worker.module.ts +13 -1
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../runtime/subsystems/token-key.ts","../../../runtime/subsystems/events/events.tokens.ts","../../../runtime/subsystems/events/generated/bus.ts","../../../runtime/subsystems/events/events-errors.ts","../../../runtime/subsystems/events/generated/schemas.ts","../../../runtime/subsystems/events/generated/registry.ts","../../../runtime/subsystems/events/events.module.ts","../../../runtime/constants/tokens.ts","../../../runtime/subsystems/events/event-bus.drizzle-backend.ts","../../../runtime/subsystems/events/event-keyset-cursor.ts","../../../runtime/subsystems/events/domain-events.schema.ts","../../../runtime/subsystems/bridge/bridge.tokens.ts","../../../runtime/subsystems/events/event-bus.memory-backend.ts","../../../runtime/subsystems/jobs/job-orchestration.schema.ts","../../../runtime/subsystems/jobs/jobs-domain.tokens.ts","../../../runtime/subsystems/jobs/job-handler.base.ts","../../../runtime/subsystems/jobs/job-orchestrator.drizzle-backend.ts","../../../runtime/subsystems/jobs/jobs-errors.ts","../../../runtime/subsystems/jobs/job-run-service.drizzle-backend.ts","../../../runtime/subsystems/jobs/job-run-keyset-cursor.ts","../../../runtime/subsystems/jobs/job-step-service.drizzle-backend.ts","../../../runtime/subsystems/jobs/pool-config.loader.ts","../../../runtime/subsystems/jobs/bullmq.config.ts","../../../runtime/subsystems/jobs/job-worker.ts","../../../runtime/subsystems/jobs/memory-job-store.ts","../../../runtime/subsystems/jobs/job-orchestrator.memory-backend.ts","../../../runtime/subsystems/jobs/job-run-service.memory-backend.ts","../../../runtime/subsystems/jobs/job-step-service.memory-backend.ts","../../../runtime/subsystems/jobs/jobs-domain.module.ts","../../../runtime/subsystems/jobs/job-worker.module.ts","../../../runtime/subsystems/cache/cache.tokens.ts","../../../runtime/subsystems/cache/cache.module.ts","../../../runtime/subsystems/cache/cache.drizzle-backend.ts","../../../runtime/subsystems/cache/cache.schema.ts","../../../runtime/subsystems/cache/cache.memory-backend.ts","../../../runtime/subsystems/storage/storage.local-backend.ts","../../../runtime/subsystems/storage/storage.utils.ts","../../../runtime/subsystems/storage/storage.memory-backend.ts","../../../runtime/subsystems/storage/storage.module.ts","../../../runtime/subsystems/storage/storage.tokens.ts","../../../runtime/subsystems/observability/observability.tokens.ts","../../../runtime/subsystems/observability/observability.module.ts","../../../runtime/subsystems/observability/observability.service.ts","../../../runtime/subsystems/integration/integration.tokens.ts","../../../runtime/subsystems/observability/reporters/bridge-metrics.reporter.ts","../../../runtime/subsystems/observability/observability-errors.ts","../../../runtime/subsystems/integration/integration-field-diff.protocol.ts","../../../runtime/subsystems/integration/entity-change-source-registry.protocol.ts","../../../runtime/subsystems/integration/entity-change-source-registry.memory.ts","../../../runtime/subsystems/integration/detection-config.schema.ts","../../../runtime/subsystems/integration/incremental-read.ts","../../../runtime/subsystems/integration/integration-errors.ts","../../../runtime/subsystems/integration/integration-audit.schema.ts","../../../runtime/subsystems/integration/integration-cursor-store.memory-backend.ts","../../../runtime/subsystems/integration/integration-run-recorder.memory-backend.ts","../../../runtime/subsystems/integration/deep-equal.differ.ts","../../../runtime/subsystems/integration/execute-integration.use-case.ts","../../../runtime/subsystems/integration/integration-cursor-store.drizzle-backend.ts","../../../runtime/subsystems/integration/integration-run-recorder.drizzle-backend.ts","../../../runtime/subsystems/integration/integration.module.ts","../../../runtime/subsystems/auth/protocols/oauth-state-store.ts","../../../runtime/subsystems/auth/auth.tokens.ts","../../../runtime/subsystems/auth/runtime/connection-broken.error.ts","../../../runtime/subsystems/auth/runtime/oauth2-refresh.strategy.ts","../../../runtime/subsystems/auth/runtime/session-expired.error.ts","../../../runtime/subsystems/auth/runtime/with-auth-retry.ts","../../../runtime/subsystems/auth/auth-oauth-state.schema.ts","../../../runtime/subsystems/auth/backends/encryption-key/env.ts","../../../runtime/subsystems/auth/backends/state-store.memory-backend.ts","../../../runtime/subsystems/auth/backends/state-store.drizzle-backend.ts","../../../runtime/subsystems/auth/controllers/auth.controller.ts","../../../runtime/base-classes/tenant-context.ts","../../../runtime/subsystems/auth/auth.module.ts"],"sourcesContent":["/** Canonical package namespace for cross-boundary DI token keys. MUST be a hardcoded\n * constant (NOT derived from package.json) so a vendored copy — which lives inside the\n * CONSUMER's package — produces the identical key and the two copies share the symbol. */\nexport const PKG = '@pattern-stack/codegen';\n// TODO(token-version): if/when a runtime contract version is adopted, inject it HERE only\n// (e.g. `${PKG}#${ABI}.${area}.${name}`) — this helper is the single chokepoint.\nexport const tokenKey = (area: string, name: string): string => `${PKG}.${area}.${name}`;\n","/**\n * Injection token for the event bus.\n *\n * String constant (not Symbol) so it matches by value across import boundaries.\n * Matches the token in runtime/constants/tokens.ts — both are 'EVENT_BUS'.\n *\n * Usage in use cases:\n * ```typescript\n * constructor(@Inject(EVENT_BUS) private readonly eventBus: IEventBus) {}\n * ```\n */\nimport { tokenKey } from '../token-key';\n\nexport const EVENT_BUS = 'EVENT_BUS' as const;\n\n/**\n * Injection token for the read-side `IEventReadPort` over `domain_events`\n * (OBS-LIST-1).\n *\n * Bound by `EventsModule.forRoot` to the same backend instance as\n * `EVENT_BUS` for the `drizzle` and `memory` backends (both implement\n * `IEventReadPort`). The `redis` backend retains no history and therefore\n * does NOT provide this token — consumers composing it (e.g. the\n * observability combiner) inject it `@Optional()` and degrade to empty\n * results.\n *\n * String constant (not Symbol) so it matches by value across import\n * boundaries — same convention as `EVENT_BUS`.\n */\nexport const EVENT_READ_PORT = 'EVENT_READ_PORT' as const;\n\n/**\n * Injection token for the generated `TypedEventBus` facade.\n *\n * `TypedEventBus` lives in `runtime/subsystems/events/generated/bus.ts` and\n * wraps `IEventBus` with project-specific `AppDomainEvent`-typed `publish<T>()`\n * and `subscribe<T>()`. Use cases inject this token in preference to\n * `EVENT_BUS` when they want compile-time type safety on event shapes.\n *\n * String constant (not Symbol) so it matches by value across import\n * boundaries — same convention as `EVENT_BUS`.\n *\n * Provider registration lands in EVT-6 (EventsModule wiring); the token is\n * declared here so generated code can import it without depending on the\n * still-being-formalised module.\n */\nexport const TYPED_EVENT_BUS = 'TYPED_EVENT_BUS' as const;\n\n/**\n * Injection token for the resolved multi-tenancy flag.\n *\n * Provided by `EventsModule.forRoot(...)` as `options.multiTenant ?? false`.\n * Consumed by `TypedEventBus` to enforce the tenantId-is-required rule at\n * publish time.\n *\n * String constant (not Symbol) so it matches by value across import\n * boundaries — same convention as the other events tokens. (The jobs\n * subsystem uses Symbols for the analogous token; events chose strings\n * from the start and we keep the file internally consistent.)\n */\nexport const EVENTS_MULTI_TENANT = 'EVENTS_MULTI_TENANT' as const;\n\n/**\n * Injection token for the Redis connection URL used by RedisEventBus.\n * Provided automatically by EventsModule.forRoot({ backend: 'redis' }).\n *\n * ADR-037: namespaced `Symbol.for(...)` (via `tokenKey()`) so it matches by value\n * across runtime copies (the sibling string tokens above are already value-stable).\n * Note the jobs subsystem defines its own `REDIS_URL`-equivalent; this is the\n * events one.\n */\nexport const REDIS_URL = Symbol.for(tokenKey('events', 'redis-url'));\n\n/**\n * Injection token for the resolved `EventsModuleOptions` object.\n *\n * Provided automatically by `EventsModule.forRoot(...)` /\n * `EventsModule.forRootAsync(...)`. Backends that need to observe module\n * configuration (e.g. `DrizzleEventBus` reading `opts.pools` for\n * pool-filtered drain) inject via this token.\n *\n * String-valued (not `Symbol`) so it matches by value across import\n * boundaries — same convention as `EVENT_BUS`.\n */\nexport const EVENTS_MODULE_OPTIONS = 'EVENTS_MODULE_OPTIONS' as const;\n","// AUTO-GENERATED by @pattern-stack/codegen. Do not edit.\n// Run `codegen entity new --all` to refresh.\n\nimport { Injectable, Inject } from '@nestjs/common';\nimport { randomUUID } from 'crypto';\nimport { EVENT_BUS, EVENTS_MULTI_TENANT } from '../events.tokens';\nimport { MissingTenantIdError } from '../events-errors';\nimport type { IEventBus, DrizzleTransaction } from '../event-bus.protocol';\nimport { eventPayloadSchemas } from './schemas';\nimport { getEventMetadata } from './registry';\nimport type { EventTypeName, EventOfType, PayloadOfType } from './types';\n\n/**\n * Typed facade over IEventBus.\n *\n * Stamps `pool`, `direction`, `tier`, and `version` into `event.metadata`\n * from the generated `eventRegistry` before delegating to\n * `IEventBus.publish()`. Downstream backends (DrizzleEventBus) read those\n * values to populate the explicit `domain_events` columns.\n *\n * Tier stamping (AUDIT-3): every event carries `metadata.tier`, sourced\n * from the registry. For `tier: 'audit'` events, the bus FORCES\n * `metadata.pool = null` and `metadata.direction = null` regardless of\n * any caller-supplied values in `opts.metadata` — audit routing is\n * bus-stamped, not caller-controlled. Caller overrides are silently\n * dropped with a debug-level log (callers should not be specifying these\n * for audit events; see ai-docs/specs/issue-242/plan.md §AUDIT-3).\n *\n * Validation gating (EVT-Q5): `CODEGEN_EVENT_VALIDATE` env flag, default on.\n * Uses `safeParse` + `console.warn` — never throws, so a bad publish does\n * not crash a hot path.\n *\n * Multi-tenancy (EVT-6): when the EventsModule is configured with\n * `multiTenant: true`, every publish must supply `opts.metadata.tenantId`\n * — otherwise `publish()` throws `MissingTenantIdError`. When `multiTenant`\n * is `false` (default), no tenantId is required. If a tenantId IS supplied,\n * it is preserved on `event.metadata` and the Drizzle backend writes it to\n * `domain_events.tenant_id` (EVT-4).\n */\n@Injectable()\nexport class TypedEventBus {\n\tconstructor(\n\t\t@Inject(EVENT_BUS) private readonly bus: IEventBus,\n\t\t@Inject(EVENTS_MULTI_TENANT) private readonly multiTenant: boolean,\n\t) {}\n\n\tasync publish<T extends EventTypeName>(\n\t\ttype: T,\n\t\taggregateId: string,\n\t\tpayload: PayloadOfType<T>,\n\t\topts?: { tx?: DrizzleTransaction; metadata?: Record<string, unknown> },\n\t): Promise<void> {\n\t\tconst meta = getEventMetadata(type);\n\n\t\tconst flag = process.env['CODEGEN_EVENT_VALIDATE'];\n\t\tconst shouldValidate =\n\t\t\tflag === undefined ? true : flag !== 'false' && flag !== '0';\n\t\tif (shouldValidate) {\n\t\t\t// `eventPayloadSchemas` is typed as `Record<EventTypeName, z.ZodType>`,\n\t\t\t// so under `noUncheckedIndexedAccess` the indexed lookup widens\n\t\t\t// to `z.ZodType | undefined`. When no events are registered at\n\t\t\t// codegen time `EventTypeName` degrades to `string` and the\n\t\t\t// schemas object is literally `{}` — the guard below is the\n\t\t\t// honest handling of that empty-registry case (skip validation;\n\t\t\t// it's a warn-only best-effort check per the class docblock).\n\t\t\tconst schema = eventPayloadSchemas[type];\n\t\t\tif (schema) {\n\t\t\t\tconst check = schema.safeParse(payload);\n\t\t\t\tif (!check.success) {\n\t\t\t\t\tconsole.warn(\n\t\t\t\t\t\t`[TypedEventBus] payload validation failed for ${String(type)}:`,\n\t\t\t\t\t\tcheck.error.issues,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tconst tenantId = opts?.metadata?.['tenantId'];\n\t\tif (this.multiTenant && (tenantId === undefined || tenantId === null)) {\n\t\t\tthrow new MissingTenantIdError(type as string);\n\t\t}\n\n\t\tconst aggregateType =\n\t\t\tmeta.aggregate ?? meta.source ?? meta.destination ?? (type as string);\n\n\t\t// AUDIT-3: build metadata with tier-aware routing stamping. For\n\t\t// `tier: 'audit'` events the bus FORCES pool/direction to null,\n\t\t// even if the caller supplied them in opts.metadata. Audit routing\n\t\t// is bus-stamped, not caller-controlled (see plan §AUDIT-3).\n\t\tconst baseMetadata: Record<string, unknown> = { ...(opts?.metadata ?? {}) };\n\t\tif (meta.tier === 'audit') {\n\t\t\tif (\n\t\t\t\tbaseMetadata['pool'] !== undefined ||\n\t\t\t\tbaseMetadata['direction'] !== undefined\n\t\t\t) {\n\t\t\t\tconsole.debug(\n\t\t\t\t\t`[TypedEventBus] tier:audit event '${String(type)}' had pool/direction in opts.metadata; overriding to null.`,\n\t\t\t\t);\n\t\t\t}\n\t\t\tbaseMetadata['pool'] = null;\n\t\t\tbaseMetadata['direction'] = null;\n\t\t\tbaseMetadata['tier'] = 'audit';\n\t\t} else {\n\t\t\tbaseMetadata['pool'] = meta.pool;\n\t\t\tbaseMetadata['direction'] = meta.direction;\n\t\t\tbaseMetadata['tier'] = 'domain';\n\t\t}\n\t\tbaseMetadata['version'] = meta.version;\n\n\t\tawait this.bus.publish(\n\t\t\t{\n\t\t\t\tid: randomUUID(),\n\t\t\t\ttype,\n\t\t\t\taggregateId,\n\t\t\t\taggregateType,\n\t\t\t\tpayload: payload as Record<string, unknown>,\n\t\t\t\toccurredAt: new Date(),\n\t\t\t\tmetadata: baseMetadata,\n\t\t\t},\n\t\t\topts?.tx,\n\t\t);\n\t}\n\n\tsubscribe<T extends EventTypeName>(\n\t\ttype: T,\n\t\thandler: (event: EventOfType<T>) => Promise<void>,\n\t): () => void {\n\t\treturn this.bus.subscribe<EventOfType<T>>(type, handler as never);\n\t}\n}\n","/**\n * Typed errors for the events subsystem (ADR-024, EVT-6).\n *\n * All thrown from the publish path of `TypedEventBus`. They exist as\n * classes so consumers can `instanceof` them in catch blocks and\n * exception filters can map them to HTTP codes.\n */\n\n/**\n * Thrown by `TypedEventBus.publish()` when the EventsModule is configured\n * with `multiTenant: true` and the caller did not supply\n * `opts.metadata.tenantId`. Multi-tenant mode requires every outbox row to\n * be attributable to a tenant — the `domain_events.tenant_id` column is\n * populated from this value and the drain loop uses it for future\n * tenant-scoped filtering (deferred — see ADR-024 §Multi-tenancy).\n *\n * Disable multi-tenancy at the module level (`multiTenant: false`, the\n * default) to opt out of the requirement entirely.\n */\nexport class MissingTenantIdError extends Error {\n override readonly name = 'MissingTenantIdError';\n constructor(public readonly eventType: string) {\n super(\n `Missing tenantId for event '${eventType}'. EventsModule is configured ` +\n `with multiTenant: true — every publish must include ` +\n `opts.metadata.tenantId. Either pass the tenantId or disable ` +\n `multi-tenancy on the module.`,\n );\n }\n}\n","// AUTO-GENERATED by @pattern-stack/codegen. Do not edit.\n// Run `codegen entity new --all` to refresh.\n\n\nimport { z } from 'zod';\nimport type { EventTypeName } from './types';\n\nexport const contactCreatedPayloadSchema = z.object({\n\taccountId: z.string().uuid().nullable(),\n\tcontactId: z.string().uuid(),\n\tcreatedBy: z.string().uuid(),\n}).strict();\n\nexport const contactMarkedChampionPayloadSchema = z.object({\n\tcontactId: z.string().uuid(),\n\topportunityId: z.string().uuid(),\n}).strict();\n\nexport const contactMergedPayloadSchema = z.object({\n\tmergedBy: z.string().uuid(),\n\tsourceId: z.string().uuid(),\n\ttargetId: z.string().uuid(),\n}).strict();\n\nexport const crmSyncStartedPayloadSchema = z.object({\n\trunId: z.string().uuid(),\n\tsource: z.string(),\n}).strict();\n\nexport const dealCreatedPayloadSchema = z.object({\n\taccountId: z.string().uuid(),\n\tdealId: z.string().uuid(),\n\townerId: z.string().uuid(),\n}).strict();\n\nexport const dealStageChangedPayloadSchema = z.object({\n\tdealId: z.string().uuid(),\n\tnewStage: z.string(),\n\toldStage: z.string(),\n}).strict();\n\nexport const stripePaymentReceivedPayloadSchema = z.object({\n\tamountCents: z.number(),\n\tcurrency: z.string(),\n\tcustomerId: z.string(),\n\teventId: z.string(),\n\treceivedAt: z.coerce.date(),\n}).strict();\n\nexport const webhookOutboundContactSyncPayloadSchema = z.object({\n\tcontactId: z.string().uuid(),\n\toccurredAt: z.coerce.date(),\n\toperation: z.string(),\n}).strict();\n\nexport const eventPayloadSchemas = {\n\t'contact_created': contactCreatedPayloadSchema,\n\t'contact_marked_champion': contactMarkedChampionPayloadSchema,\n\t'contact_merged': contactMergedPayloadSchema,\n\t'crm_sync_started': crmSyncStartedPayloadSchema,\n\t'deal_created': dealCreatedPayloadSchema,\n\t'deal_stage_changed': dealStageChangedPayloadSchema,\n\t'stripe_payment_received': stripePaymentReceivedPayloadSchema,\n\t'webhook_outbound_contact_sync': webhookOutboundContactSyncPayloadSchema,\n} as const satisfies Record<EventTypeName, z.ZodType>;\n","// AUTO-GENERATED by @pattern-stack/codegen. Do not edit.\n// Run `codegen entity new --all` to refresh.\n\n\nimport type { EventTypeName } from './types';\n\nexport interface EventMetadata {\n\ttype: EventTypeName;\n\ttier: 'domain' | 'audit';\n\tdirection: 'inbound' | 'change' | 'outbound' | null;\n\tpool: 'events_inbound' | 'events_change' | 'events_outbound' | null;\n\taggregate?: string;\n\tsource?: string;\n\tdestination?: string;\n\tversion: number;\n\tretry: { attempts: number; backoff: 'linear' | 'exponential' };\n}\n\nexport const eventRegistry = {\n\t'contact_created': {\n\t\ttype: 'contact_created',\n\t\ttier: 'domain',\n\t\tdirection: 'change',\n\t\tpool: 'events_change',\n\t\taggregate: 'contact',\n\t\tversion: 1,\n\t\tretry: { attempts: 3, backoff: 'exponential' },\n\t},\n\t'contact_marked_champion': {\n\t\ttype: 'contact_marked_champion',\n\t\ttier: 'domain',\n\t\tdirection: 'change',\n\t\tpool: 'events_change',\n\t\taggregate: 'contact',\n\t\tversion: 1,\n\t\tretry: { attempts: 3, backoff: 'exponential' },\n\t},\n\t'contact_merged': {\n\t\ttype: 'contact_merged',\n\t\ttier: 'domain',\n\t\tdirection: 'change',\n\t\tpool: 'events_change',\n\t\taggregate: 'contact',\n\t\tversion: 1,\n\t\tretry: { attempts: 3, backoff: 'exponential' },\n\t},\n\t'crm_sync_started': {\n\t\ttype: 'crm_sync_started',\n\t\ttier: 'audit',\n\t\tdirection: null,\n\t\tpool: null,\n\t\tversion: 1,\n\t\tretry: { attempts: 3, backoff: 'exponential' },\n\t},\n\t'deal_created': {\n\t\ttype: 'deal_created',\n\t\ttier: 'domain',\n\t\tdirection: 'change',\n\t\tpool: 'events_change',\n\t\taggregate: 'deal',\n\t\tversion: 1,\n\t\tretry: { attempts: 3, backoff: 'exponential' },\n\t},\n\t'deal_stage_changed': {\n\t\ttype: 'deal_stage_changed',\n\t\ttier: 'domain',\n\t\tdirection: 'change',\n\t\tpool: 'events_change',\n\t\taggregate: 'deal',\n\t\tversion: 1,\n\t\tretry: { attempts: 3, backoff: 'exponential' },\n\t},\n\t'stripe_payment_received': {\n\t\ttype: 'stripe_payment_received',\n\t\ttier: 'domain',\n\t\tdirection: 'inbound',\n\t\tpool: 'events_inbound',\n\t\tsource: 'stripe',\n\t\tversion: 1,\n\t\tretry: { attempts: 5, backoff: 'exponential' },\n\t},\n\t'webhook_outbound_contact_sync': {\n\t\ttype: 'webhook_outbound_contact_sync',\n\t\ttier: 'domain',\n\t\tdirection: 'outbound',\n\t\tpool: 'events_outbound',\n\t\taggregate: 'contact',\n\t\tdestination: 'crm',\n\t\tversion: 1,\n\t\tretry: { attempts: 3, backoff: 'exponential' },\n\t},\n} as const satisfies Record<EventTypeName, EventMetadata>;\n\nexport function getEventMetadata<T extends EventTypeName>(type: T): EventMetadata {\n\tconst meta = eventRegistry[type];\n\tif (!meta) {\n\t\tthrow new Error(`No registry entry for event type '${String(type)}' — declare events under events/*.yaml and re-run \\`codegen entity new --all\\`.`);\n\t}\n\treturn meta;\n}\n","/**\n * EventsModule — DynamicModule factory for the event bus subsystem.\n *\n * Register once in AppModule:\n * ```typescript\n * @Module({\n * imports: [\n * EventsModule.forRoot({ backend: 'drizzle' }),\n * ],\n * })\n * export class AppModule {}\n * ```\n *\n * Tests swap to the memory backend without touching application code:\n * ```typescript\n * Test.createTestingModule({\n * imports: [EventsModule.forRoot({ backend: 'memory' })],\n * });\n * ```\n *\n * Per-pool drain isolation (EVT-4):\n * ```typescript\n * EventsModule.forRoot({ backend: 'drizzle', pools: ['events_change'] });\n * ```\n * Each process restricts its drain loop to the pools listed here. `pools`\n * is undefined by default → drain all pending rows (backwards-compatible).\n *\n * Typed facade + multi-tenancy (EVT-6):\n * - `TYPED_EVENT_BUS` resolves to the generated `TypedEventBus` wrapping\n * whichever backend is selected.\n * - `multiTenant: true` makes `TypedEventBus.publish` throw\n * `MissingTenantIdError` when the caller forgets `metadata.tenantId`.\n *\n * `global: true` means entity modules do not need to import EventsModule\n * individually — the EVENT_BUS and TYPED_EVENT_BUS tokens are available\n * project-wide.\n *\n * Async configuration (`forRootAsync`):\n * The async factory returns `EventsModuleOptions`; the EVENT_BUS provider\n * then receives its backend dependencies — DRIZZLE for the drizzle\n * backend, REDIS_URL for the redis backend, the resolved options for the\n * memory backend — through a proper `useFactory` so Nest DI wires them\n * correctly. Earlier revisions hand-constructed backends with\n * `new Class()` which silently left `db` / `redisUrl` undefined\n * (issue #108).\n */\nimport { Module, type DynamicModule, type Provider } from '@nestjs/common';\nimport {\n EVENT_BUS,\n EVENT_READ_PORT,\n EVENTS_MODULE_OPTIONS,\n EVENTS_MULTI_TENANT,\n REDIS_URL,\n TYPED_EVENT_BUS,\n} from './events.tokens';\nimport { DRIZZLE } from '../../constants/tokens';\nimport type { DrizzleClient } from '../../types/drizzle';\nimport { DrizzleEventBus } from './event-bus.drizzle-backend';\nimport { MemoryEventBus } from './event-bus.memory-backend';\n// #6 — `RedisEventBus` is lazy-loaded only when `backend: 'redis'` is selected.\n// The file is filtered out of the vendor set for non-redis installs (see\n// `backendFileFilter` in src/cli/commands/subsystem.ts); the dynamic-string\n// import below makes TS treat the specifier as `any` so the consumer's tsc\n// never tries to resolve the absent file.\nimport { TypedEventBus } from './generated/bus';\n\n/**\n * Lazy-load the Redis backend. Routed through a non-literal specifier so\n * the consumer's `tsc` doesn't resolve `./event-bus.redis-backend` at type\n * check time — important because that file is filtered out of drizzle/\n * memory installs (#6).\n */\nasync function loadRedisEventBus(): Promise<new (url: string) => object> {\n // Non-literal specifier — TS gives this an `any` module type, sidestepping\n // resolution of a file that may not be vendored.\n const specifier = './event-bus.redis-backend';\n const mod = (await import(specifier)) as { RedisEventBus: new (url: string) => object };\n return mod.RedisEventBus;\n}\n\nexport interface EventsModuleOptions {\n backend: 'drizzle' | 'memory' | 'redis';\n /**\n * Redis connection URL used when `backend` is `'redis'`.\n * Falls back to the REDIS_URL environment variable, then\n * `redis://localhost:6379` if neither is set.\n */\n redisUrl?: string;\n /**\n * Restrict the drain loop to these pools. Each pool name matches the\n * `domain_events.pool` column (populated from `event.metadata.pool` at\n * publish time). Leave undefined to drain all pending rows.\n *\n * Typical lane split: one process per `events_inbound` /\n * `events_change` / `events_outbound` so a slow outbound handler\n * cannot stall change-event propagation (see ADR-022).\n */\n pools?: string[];\n /**\n * Multi-tenancy opt-in (EVT-6).\n *\n * When `true`, every `TypedEventBus.publish()` call must supply\n * `opts.metadata.tenantId` — otherwise it throws `MissingTenantIdError`.\n * The tenantId is preserved on `event.metadata` and, for the Drizzle\n * backend, written to `domain_events.tenant_id` (EVT-4).\n *\n * Drain-side tenant filtering is deferred — the tenant-context model\n * (per-process vs. per-request vs. async-local-storage) is still\n * unsettled; see ADR-024 §Multi-tenancy. Only the publish-side\n * requirement ships here.\n *\n * Defaults to `false`.\n */\n multiTenant?: boolean;\n}\n\nexport interface EventsModuleAsyncOptions {\n useFactory: (...args: unknown[]) => Promise<EventsModuleOptions> | EventsModuleOptions;\n inject?: unknown[];\n imports?: unknown[];\n}\n\n/**\n * Shared provider set: `TypedEventBus` itself, the `TYPED_EVENT_BUS` token\n * binding, and the resolved `EVENTS_MULTI_TENANT` flag. Returned from one\n * place so every `forRoot` branch and `forRootAsync` agree.\n */\nfunction buildTypedBusProviders(multiTenant: boolean): Provider[] {\n return [\n TypedEventBus,\n { provide: TYPED_EVENT_BUS, useExisting: TypedEventBus },\n { provide: EVENTS_MULTI_TENANT, useValue: multiTenant },\n ];\n}\n\n/**\n * Construct the backend instance for the async path, routing constructor\n * arguments through Nest-resolved dependencies.\n *\n * DRIZZLE is declared optional at inject time so that memory-backend\n * consumers aren't required to also import `DatabaseModule`. If the\n * drizzle backend is selected but no DRIZZLE provider is registered, we\n * throw a clear error instead of silently constructing a broken bus.\n */\nasync function buildEventBusAsync(\n options: EventsModuleOptions,\n db: DrizzleClient | null,\n redisUrl: string,\n): Promise<unknown> {\n if (options.backend === 'drizzle') {\n if (!db) {\n throw new Error(\n \"EventsModule.forRootAsync: backend: 'drizzle' selected but DRIZZLE provider is not available. \" +\n 'Ensure DatabaseModule (or another provider exposing DRIZZLE) is imported before EventsModule.forRootAsync.',\n );\n }\n return new DrizzleEventBus(db, options);\n }\n if (options.backend === 'redis') {\n // #6: lazy import — the redis backend ships only with `--backend redis`\n // installs; drizzle/memory consumers never touch the file.\n const RedisEventBus = await loadRedisEventBus();\n return new RedisEventBus(redisUrl);\n }\n return new MemoryEventBus(options);\n}\n\n@Module({})\nexport class EventsModule {\n static forRootAsync(asyncOptions: EventsModuleAsyncOptions): DynamicModule {\n return {\n module: EventsModule,\n global: true,\n imports: (asyncOptions.imports ?? []) as Parameters<typeof Module>[0]['imports'],\n providers: [\n {\n provide: EVENTS_MODULE_OPTIONS,\n useFactory: asyncOptions.useFactory,\n inject: (asyncOptions.inject ?? []) as (string | symbol | Function)[],\n },\n {\n provide: EVENTS_MULTI_TENANT,\n useFactory: (options: EventsModuleOptions) => options.multiTenant ?? false,\n inject: [EVENTS_MODULE_OPTIONS],\n },\n {\n provide: REDIS_URL,\n useFactory: (options: EventsModuleOptions) =>\n options.redisUrl ?? process.env['REDIS_URL'] ?? 'redis://localhost:6379',\n inject: [EVENTS_MODULE_OPTIONS],\n },\n {\n provide: EVENT_BUS,\n useFactory: (\n options: EventsModuleOptions,\n db: DrizzleClient | null,\n redisUrl: string,\n ) => buildEventBusAsync(options, db, redisUrl),\n inject: [\n EVENTS_MODULE_OPTIONS,\n { token: DRIZZLE, optional: true },\n REDIS_URL,\n ],\n },\n {\n // Read port (OBS-LIST-1). Drizzle + memory backends implement\n // IEventReadPort on the EVENT_BUS instance; the redis backend\n // retains no history, so EVENT_READ_PORT resolves to `null` and\n // optional consumers (the observability combiner) degrade to\n // empty results.\n provide: EVENT_READ_PORT,\n useFactory: (options: EventsModuleOptions, bus: unknown) =>\n options.backend === 'redis' ? null : bus,\n inject: [EVENTS_MODULE_OPTIONS, EVENT_BUS],\n },\n TypedEventBus,\n { provide: TYPED_EVENT_BUS, useExisting: TypedEventBus },\n ],\n exports: [EVENT_BUS, EVENT_READ_PORT, TYPED_EVENT_BUS, EVENTS_MULTI_TENANT],\n };\n }\n\n static forRoot(\n options: EventsModuleOptions = { backend: 'drizzle' },\n ): DynamicModule {\n const multiTenant = options.multiTenant ?? false;\n\n if (options.backend === 'redis') {\n const resolvedUrl =\n options.redisUrl ?? process.env['REDIS_URL'] ?? 'redis://localhost:6379';\n\n return {\n module: EventsModule,\n global: true,\n providers: [\n { provide: EVENTS_MODULE_OPTIONS, useValue: options },\n { provide: REDIS_URL, useValue: resolvedUrl },\n {\n // #6: useFactory + dynamic import so the consumer's tsc never\n // needs to resolve `event-bus.redis-backend.ts` for drizzle/\n // memory installs (the file is filtered out by\n // `backendFileFilter`). Nest awaits async factories + manages\n // lifecycle on the returned instance, so we drop the old bare\n // `RedisEventBus` provider entry.\n provide: EVENT_BUS,\n useFactory: async (url: string): Promise<object> => {\n const RedisEventBus = await loadRedisEventBus();\n return new RedisEventBus(url);\n },\n inject: [REDIS_URL],\n },\n ...buildTypedBusProviders(multiTenant),\n ],\n exports: [EVENT_BUS, TYPED_EVENT_BUS, EVENTS_MULTI_TENANT],\n };\n }\n\n const provider =\n options.backend === 'drizzle'\n ? { provide: EVENT_BUS, useClass: DrizzleEventBus }\n : { provide: EVENT_BUS, useClass: MemoryEventBus };\n\n return {\n module: EventsModule,\n global: true,\n providers: [\n { provide: EVENTS_MODULE_OPTIONS, useValue: options },\n provider,\n // Read port (OBS-LIST-1): drizzle + memory backends implement\n // IEventReadPort on the same instance as EVENT_BUS. The redis\n // backend retains no history and does not provide this token.\n { provide: EVENT_READ_PORT, useExisting: EVENT_BUS },\n ...buildTypedBusProviders(multiTenant),\n ],\n exports: [EVENT_BUS, EVENT_READ_PORT, TYPED_EVENT_BUS, EVENTS_MULTI_TENANT],\n };\n }\n}\n","/**\n * NestJS injection tokens\n *\n * Used with @Inject() decorator in concrete repository constructors.\n */\n\n/**\n * Injection token for the Drizzle ORM database client.\n *\n * Usage in concrete repositories:\n * ```typescript\n * constructor(@Inject(DRIZZLE) db: DrizzleClient) { super(db); }\n * ```\n */\nexport const DRIZZLE = 'DRIZZLE' as const;\n\n/**\n * Injection token for the event bus (IEventBus).\n *\n * Optional — only resolved when EventsModule.forRoot() is registered.\n * BaseService uses this with @Optional() to emit lifecycle events\n * without requiring the events subsystem to be installed.\n *\n * Usage in services/use cases:\n * ```typescript\n * @Optional() @Inject(EVENT_BUS) eventBus?: IEventBus\n * ```\n */\nexport const EVENT_BUS = 'EVENT_BUS' as const;\n","/**\n * DrizzleEventBus — Postgres-backed event bus using the transactional outbox pattern.\n *\n * Events are inserted into the `domain_events` table within the caller's\n * Drizzle transaction. A background polling loop (started on module init)\n * reads unprocessed events and dispatches them to registered subscribers.\n *\n * When the transaction rolls back, the event is never persisted — no\n * phantom events.\n *\n * Pool awareness (EVT-4):\n * - On `publish`/`publishMany` the backend writes `metadata.pool`,\n * `metadata.direction`, and `metadata.tenantId` into the first-class\n * `pool` / `direction` / `tenant_id` columns (metadata JSON is still\n * written unchanged for protocol stability).\n * - The drain loop filters by `opts.pools` when provided, so separate\n * processes (e.g. one per `events_inbound` / `events_change` /\n * `events_outbound`) can claim only their own lane. `pools: undefined`\n * drains all pending rows (backwards-compatible behaviour).\n *\n * EVT-Q7: No stale-event sweeper. `FOR UPDATE SKIP LOCKED` is\n * self-healing — the row is only locked for the duration of the\n * enclosing polling transaction; the `status='processed'` update happens\n * within that same transaction. There is no `claimed_at` semantic (unlike\n * jobs), so no stale rows can exist.\n *\n * This backend is suitable until you need real-time fan-out or very high\n * throughput. At that point, swap the backend for Redis Streams or similar\n * via EventsModule.forRoot({ backend: '...' }) without touching use cases.\n */\nimport { Injectable, OnModuleDestroy, OnModuleInit, Inject, Logger, Optional } from '@nestjs/common';\nimport { eq, and, inArray, asc, desc, gte, lt, or, sql, type SQL } from 'drizzle-orm';\nimport type { DomainEvent, DrizzleTransaction, IEventBus } from './event-bus.protocol';\nimport type {\n EventPage,\n IEventReadPort,\n ListEventsQuery,\n} from './event-read.protocol';\nimport {\n clampEventLimit,\n decodeEventCursor,\n encodeEventCursor,\n} from './event-keyset-cursor';\nimport type { DrizzleClient } from '../../types/drizzle';\nimport { domainEvents, type DomainEventRecord } from './domain-events.schema';\nimport { DRIZZLE } from '../../constants/tokens';\nimport { EVENTS_MODULE_OPTIONS } from './events.tokens';\nimport type { EventsModuleOptions } from './events.module';\nimport { BRIDGE_OUTBOX_DRAIN_HOOK } from '../bridge/bridge.tokens';\nimport type { IBridgeOutboxDrainHook } from '../bridge/bridge.protocol';\n\n/** How long to wait between polling cycles (ms). */\nconst POLL_INTERVAL_MS = 1_000;\n/** Max events claimed per polling cycle to bound memory usage. */\nconst POLL_BATCH_SIZE = 50;\n\n/**\n * Row shape built from `metadata` for writing into `domain_events`. Keeps\n * the per-event extraction logic in one place so publish/publishMany stay\n * in sync.\n */\nfunction toInsertValues(event: DomainEvent, multiTenant: boolean) {\n const metadata = event.metadata ?? undefined;\n const pool = (metadata?.['pool'] as string | undefined) ?? null;\n const direction = (metadata?.['direction'] as string | undefined) ?? null;\n // AUDIT-1: tier defaults to 'domain' when absent. The DB CHECK\n // constraint (`domain_events_tier_routing_check`) enforces the\n // tier ⇔ routing-fields invariant at the storage boundary; no\n // JS-side assertion is needed here.\n const tier = (metadata?.['tier'] as string | undefined) ?? 'domain';\n const base = {\n id: event.id,\n type: event.type,\n aggregateId: event.aggregateId,\n aggregateType: event.aggregateType,\n payload: event.payload,\n occurredAt: event.occurredAt,\n processedAt: null,\n status: 'pending' as const,\n metadata: event.metadata,\n pool,\n direction,\n tier,\n };\n // EVT-8: `tenant_id` is a scaffold-time conditional column, emitted only\n // when `events.multi_tenant: true`. Only write it when multi-tenancy is\n // on — under single-tenant scaffolds the column does not exist, so the\n // key must be omitted from the insert.\n if (!multiTenant) return base;\n const tenantId = (metadata?.['tenantId'] as string | undefined) ?? null;\n return { ...base, tenantId };\n}\n\n/**\n * Project a raw `domain_events` row into the narrow `EventSummary` shape.\n * Shared with the memory backend via this helper kept module-local to each\n * backend (the events subsystem has no cross-backend projection file yet;\n * the two are byte-identical and small).\n */\nfunction toEventSummary(r: DomainEventRecord) {\n const metadata = (r.metadata ?? undefined) as\n | Record<string, unknown>\n | undefined;\n const rootRunId = metadata?.['rootRunId'];\n return {\n id: r.id,\n type: r.type,\n aggregateId: r.aggregateId,\n aggregateType: r.aggregateType,\n status: r.status,\n pool: r.pool,\n direction: r.direction,\n tier: r.tier,\n rootRunId: typeof rootRunId === 'string' ? rootRunId : null,\n // EVT-8: `tenant_id` is a scaffold-time conditional column. Read it\n // structurally so this projection typechecks against both the\n // multi-tenant schema (column present) and the single-tenant schema\n // (column absent → undefined → null).\n tenantId: (r as { tenantId?: string | null }).tenantId ?? null,\n occurredAt:\n r.occurredAt instanceof Date\n ? r.occurredAt\n : new Date(r.occurredAt as unknown as string),\n processedAt:\n r.processedAt == null\n ? null\n : r.processedAt instanceof Date\n ? r.processedAt\n : new Date(r.processedAt as unknown as string),\n };\n}\n\n@Injectable()\nexport class DrizzleEventBus implements IEventBus, IEventReadPort, OnModuleInit, OnModuleDestroy {\n private readonly logger = new Logger(DrizzleEventBus.name);\n private polling = false;\n private pollTimer: ReturnType<typeof setTimeout> | null = null;\n private readonly handlers = new Map<string, Set<(event: DomainEvent) => Promise<void>>>();\n private readonly opts: EventsModuleOptions;\n\n constructor(\n @Inject(DRIZZLE) private readonly db: DrizzleClient,\n @Optional() @Inject(EVENTS_MODULE_OPTIONS) opts?: EventsModuleOptions,\n /**\n * Bridge subsystem hook (BRIDGE-4). Optional — when the bridge\n * subsystem is not installed in the consuming app, this token is\n * undefined and the drain skips the bridge block entirely (preserves\n * EVT-4 baseline behaviour).\n *\n * When provided, `processEvent` is invoked once per drained event\n * INSIDE the per-event tx, before `processed_at` is stamped. The\n * hook owns all knowledge of `bridge_delivery + wrapper job_run`\n * shapes; the events subsystem stays unaware of bridge schemas.\n */\n @Optional()\n @Inject(BRIDGE_OUTBOX_DRAIN_HOOK)\n private readonly bridgeHook: IBridgeOutboxDrainHook | null = null,\n ) {\n // Default so direct construction (e.g. integration tests not going\n // through Nest DI) keeps working without an explicit options object.\n this.opts = opts ?? { backend: 'drizzle' };\n }\n\n // ============================================================================\n // Lifecycle\n // ============================================================================\n\n async onModuleInit(): Promise<void> {\n this.polling = true;\n this.schedulePoll();\n }\n\n async onModuleDestroy(): Promise<void> {\n this.polling = false;\n if (this.pollTimer) {\n clearTimeout(this.pollTimer);\n this.pollTimer = null;\n }\n }\n\n // ============================================================================\n // IEventBus\n // ============================================================================\n\n async publish(event: DomainEvent, tx?: DrizzleTransaction): Promise<void> {\n const client = (tx ?? this.db) as DrizzleClient;\n const multiTenant = this.opts.multiTenant ?? false;\n await client.insert(domainEvents).values(toInsertValues(event, multiTenant));\n }\n\n async publishMany(events: DomainEvent[], tx?: DrizzleTransaction): Promise<void> {\n if (events.length === 0) return;\n const client = (tx ?? this.db) as DrizzleClient;\n const multiTenant = this.opts.multiTenant ?? false;\n await client\n .insert(domainEvents)\n .values(events.map((e) => toInsertValues(e, multiTenant)));\n }\n\n async findById(eventId: string): Promise<DomainEvent | null> {\n const rows = await this.db\n .select()\n .from(domainEvents)\n .where(eq(domainEvents.id, eventId))\n .limit(1);\n const row = rows[0];\n if (!row) return null;\n return {\n id: row.id,\n type: row.type,\n aggregateId: row.aggregateId,\n aggregateType: row.aggregateType,\n payload: row.payload as Record<string, unknown>,\n occurredAt:\n row.occurredAt instanceof Date\n ? row.occurredAt\n : new Date(row.occurredAt as unknown as string),\n metadata: (row.metadata ?? undefined) as\n | Record<string, unknown>\n | undefined,\n };\n }\n\n subscribe<T extends DomainEvent = DomainEvent>(\n eventType: string,\n handler: (event: T) => Promise<void>,\n ): () => void {\n if (!this.handlers.has(eventType)) {\n this.handlers.set(eventType, new Set());\n }\n const set = this.handlers.get(eventType)!;\n const h = handler as (event: DomainEvent) => Promise<void>;\n set.add(h);\n return () => {\n set.delete(h);\n };\n }\n\n // ============================================================================\n // IEventReadPort (OBS-LIST-1)\n // ============================================================================\n\n async listEvents(query: ListEventsQuery = {}): Promise<EventPage> {\n const limit = clampEventLimit(query.limit);\n const conditions: SQL<unknown>[] = [];\n\n if (query.poolId) conditions.push(eq(domainEvents.pool, query.poolId));\n if (query.direction)\n conditions.push(eq(domainEvents.direction, query.direction));\n if (query.since) conditions.push(gte(domainEvents.occurredAt, query.since));\n if (query.rootRunId) {\n // Filter on the JSON correlation id: metadata->>'rootRunId'.\n conditions.push(\n sql`${domainEvents.metadata}->>'rootRunId' = ${query.rootRunId}`,\n );\n }\n // EVT-8: `tenant_id` is a scaffold-time conditional column (emitted only\n // under `events.multi_tenant: true`). Guard the filter behind the same\n // `multiTenant` flag, and read the column structurally so this backend\n // typechecks against both the multi-tenant schema (column present) and\n // the single-tenant schema (column absent). When multi-tenancy is off\n // there is no `tenant_id` column to filter on.\n if (this.opts.multiTenant && query.tenantId !== undefined) {\n const tenantIdColumn = (\n domainEvents as unknown as { tenantId: typeof domainEvents.pool }\n ).tenantId;\n conditions.push(\n query.tenantId === null\n ? (sql`${tenantIdColumn} is null` as SQL<unknown>)\n : eq(tenantIdColumn, query.tenantId),\n );\n }\n\n // Keyset seek: WHERE (occurred_at, id) < (cursorOccurredAt, cursorId).\n if (query.cursor) {\n const keyset = decodeEventCursor(query.cursor);\n if (keyset) {\n conditions.push(\n or(\n lt(domainEvents.occurredAt, keyset.occurredAt),\n and(\n eq(domainEvents.occurredAt, keyset.occurredAt),\n lt(domainEvents.id, keyset.id),\n ),\n )!,\n );\n }\n }\n\n const rows = (await this.db\n .select()\n .from(domainEvents)\n .where(conditions.length > 0 ? and(...conditions) : undefined)\n .orderBy(desc(domainEvents.occurredAt), desc(domainEvents.id))\n .limit(limit + 1)) as DomainEventRecord[];\n\n const hasMore = rows.length > limit;\n const page = hasMore ? rows.slice(0, limit) : rows;\n const items = page.map(toEventSummary);\n const last = page[page.length - 1];\n const nextCursor =\n hasMore && last\n ? encodeEventCursor({ occurredAt: last.occurredAt, id: last.id })\n : null;\n\n return { items, nextCursor };\n }\n\n // ============================================================================\n // Polling\n // ============================================================================\n\n /**\n * Test-only hook. Runs exactly one drain cycle and returns. Production\n * code goes through `onModuleInit` → `schedulePoll`, which calls the\n * same `processBatch` under a timer.\n */\n async drainOnce(): Promise<void> {\n await this.processBatch();\n }\n\n private schedulePoll(): void {\n if (!this.polling) return;\n this.pollTimer = setTimeout(async () => {\n try {\n await this.processBatch();\n } catch (err) {\n this.logger.error(`Poll cycle error: ${err}`);\n } finally {\n this.schedulePoll();\n }\n }, POLL_INTERVAL_MS);\n }\n\n /**\n * Drain one batch (BRIDGE-4 restructure of EVT-4).\n *\n * Two-phase per drained event:\n *\n * 1. **Per-event transaction** — bridge fanout (`bridgeHook.processEvent`)\n * + `processed_at` stamp. Both write through the same `tx`. A throw\n * inside the tx (only infra-level failures should reach here, since\n * the hook tolerates null direction and registry misses inline)\n * rolls back the bridge inserts AND the `processed_at` stamp; the\n * event re-claims on the next drain cycle. Bridge `UNIQUE\n * (event_id, trigger_id)` makes the retry idempotent.\n *\n * 2. **After commit** — dispatch in-process subscribers (`IEventBus.subscribe`\n * handlers). This deliberately runs OUTSIDE the per-event tx (lead\n * decision 2026-04-22): subscribers are best-effort and must not\n * gate forward progress or roll back bridge fanout. Subscriber\n * errors are caught + logged; `processed_at` is already committed.\n * The old `MAX_RETRIES=3` in-process retry loop and the\n * `failed`-stamping path were removed in BRIDGE-4 along with their\n * coupling.\n *\n * The `processed_at` UPDATE carries `AND status='pending'` (BRIDGE-4\n * tightening — without it, a hypothetical double-claim could double-stamp\n * the timestamp). The per-event tx + `FOR UPDATE SKIP LOCKED` claim\n * make this defensive belt-and-suspenders.\n */\n private async processBatch(): Promise<void> {\n const pools = this.opts.pools;\n\n // Build WHERE: status='pending' [AND pool IN (...)]\n const whereClause: SQL<unknown> = pools && pools.length > 0\n ? (and(eq(domainEvents.status, 'pending'), inArray(domainEvents.pool, pools)) as SQL<unknown>)\n : eq(domainEvents.status, 'pending');\n\n // Claim a batch with FOR UPDATE SKIP LOCKED so multiple pollers don't\n // double-dispatch. The lock is released when the outer transaction\n // commits — which is fine because the immediately-following per-event\n // tx flips status='processed' under its own `AND status='pending'`\n // guard, so a re-claim of the same row in a subsequent batch is a\n // no-op UPDATE.\n const rows = await this.db.transaction(async (tx) => {\n return tx\n .select()\n .from(domainEvents)\n .where(whereClause)\n .orderBy(asc(domainEvents.occurredAt))\n .limit(POLL_BATCH_SIZE)\n .for('update', { skipLocked: true });\n }) as Array<typeof domainEvents.$inferSelect>;\n\n for (const row of rows) {\n const event: DomainEvent = {\n id: row.id,\n type: row.type,\n aggregateId: row.aggregateId,\n aggregateType: row.aggregateType,\n payload: row.payload as Record<string, unknown>,\n occurredAt: row.occurredAt instanceof Date ? row.occurredAt : new Date(row.occurredAt as unknown as string),\n metadata: (row.metadata ?? undefined) as Record<string, unknown> | undefined,\n };\n\n // Phase 1 — per-event tx: bridge fanout + processed_at stamp.\n try {\n await this.db.transaction(async (tx) => {\n if (this.bridgeHook) {\n await this.bridgeHook.processEvent(event, tx);\n }\n await tx\n .update(domainEvents)\n .set({ status: 'processed', processedAt: new Date() })\n .where(\n and(\n eq(domainEvents.id, event.id),\n eq(domainEvents.status, 'pending'),\n ),\n );\n });\n } catch (err) {\n // Infra-level failure inside the per-event tx — bridge inserts\n // and processed_at both rolled back. Log and move on; the next\n // drain cycle re-claims the row. UNIQUE on bridge_delivery makes\n // the retry idempotent.\n this.logger.error(\n `Per-event tx failed for event id=${event.id} type=${event.type}: ${err}`,\n );\n continue;\n }\n\n // Phase 2 — best-effort subscriber dispatch. Errors are logged\n // and discarded; processed_at is already committed. Subscribers\n // are observability + cache-busts + small ancillary work; they\n // must not gate forward progress.\n try {\n await this.dispatch(event);\n } catch (err) {\n this.logger.error(\n `Subscriber dispatch failed for event id=${event.id} type=${event.type} ` +\n `(processed_at already committed; failure does not retry): ${err}`,\n );\n }\n }\n }\n\n private async dispatch(event: DomainEvent): Promise<void> {\n const set = this.handlers.get(event.type);\n if (!set) return;\n\n let firstError: unknown;\n for (const handler of set) {\n try {\n await handler(event);\n } catch (err) {\n this.logger.error(\n `Handler error for event type \"${event.type}\" (id: ${event.id}): ${err}`,\n );\n if (firstError === undefined) {\n firstError = err;\n }\n }\n }\n\n if (firstError !== undefined) {\n throw firstError;\n }\n }\n}\n","/**\n * Keyset (seek) cursor codec for `IEventReadPort.listEvents` (OBS-LIST-1).\n *\n * The list is ordered `occurred_at DESC, id DESC`. The cursor encodes the\n * `(occurredAt, id)` of the last row on the previous page so the next page\n * seeks with `WHERE (occurred_at, id) < (cursorOccurredAt, cursorId)`.\n *\n * The cursor is opaque to consumers: a base64url-encoded JSON tuple. Shape\n * is an implementation detail — never parse it outside this module.\n *\n * Mirrors the jobs keyset codec; kept separate because the events subsystem\n * must not depend on `runtime/subsystems/jobs/`.\n */\n\nexport interface EventKeyset {\n occurredAt: Date;\n id: string;\n}\n\n/** Default page size when `limit` is omitted. */\nexport const DEFAULT_EVENT_LIST_LIMIT = 50;\n/** Hard upper bound on page size. */\nexport const MAX_EVENT_LIST_LIMIT = 200;\n\n/** Clamp a caller-supplied `limit` into `[1, MAX_EVENT_LIST_LIMIT]`. */\nexport function clampEventLimit(limit: number | undefined): number {\n if (typeof limit !== 'number' || !Number.isFinite(limit)) {\n return DEFAULT_EVENT_LIST_LIMIT;\n }\n const floored = Math.floor(limit);\n if (floored < 1) return 1;\n if (floored > MAX_EVENT_LIST_LIMIT) return MAX_EVENT_LIST_LIMIT;\n return floored;\n}\n\nexport function encodeEventCursor(keyset: EventKeyset): string {\n const tuple = [keyset.occurredAt.toISOString(), keyset.id];\n return Buffer.from(JSON.stringify(tuple), 'utf8').toString('base64url');\n}\n\n/**\n * Decode an opaque cursor back into its `(occurredAt, id)` keyset. Returns\n * `null` for malformed input so user-supplied garbage is treated as \"start\n * from the beginning\" rather than throwing.\n */\nexport function decodeEventCursor(cursor: string): EventKeyset | null {\n try {\n const json = Buffer.from(cursor, 'base64url').toString('utf8');\n const parsed = JSON.parse(json) as unknown;\n if (!Array.isArray(parsed) || parsed.length !== 2) return null;\n const [iso, id] = parsed;\n if (typeof iso !== 'string' || typeof id !== 'string') return null;\n const occurredAt = new Date(iso);\n if (Number.isNaN(occurredAt.getTime())) return null;\n return { occurredAt, id };\n } catch {\n return null;\n }\n}\n","/**\n * Drizzle schema for the domain_events outbox table.\n *\n * This table backs the DrizzleEventBus. Events are inserted within the\n * same database transaction as the domain write (outbox pattern). A\n * polling process reads unprocessed rows and dispatches to subscribers.\n *\n * First-class routing columns (EVT-1):\n * - `pool` — populated by DrizzleEventBus.publish() (EVT-4); enables\n * pool-filtered drain queries without unpacking metadata JSON.\n * NULL when `tier='audit'` (audit events are not routed).\n * - `direction` — `inbound` | `change` | `outbound`; mirrors the routing\n * dimension used by jobs' reserved `events_inbound` /\n * `events_change` / `events_outbound` pools.\n * NULL when `tier='audit'`.\n * - `tenant_id` — conditional: emitted only when `events.multi_tenant: true`\n * in `codegen.config.yaml`. The runtime source declares it\n * unconditionally; EVT-8's scaffold template handles the\n * config-driven include/exclude.\n *\n * Audit-tier column (AUDIT-1):\n * - `tier` — `'domain'` | `'audit'`. Defaults to `'domain'`. Audit-tier\n * rows are observability-only (subscribers may observe but\n * the bridge MUST NOT spawn jobs from them); they have null\n * `pool` and `direction` by construction. The CHECK\n * constraint `domain_events_tier_routing_check` enforces\n * `tier='audit' ⇔ (pool IS NULL AND direction IS NULL)`.\n *\n * The `metadata` JSON column continues to carry these values for protocol\n * stability; the first-class columns are an optimization for drain filtering.\n *\n * Indexes (declared below in the index callback):\n * - (status, occurred_at) — polling drain filter\n * - (aggregate_id, aggregate_type) — event replay per aggregate\n * - (pool, status, occurred_at) — per-pool drain filter (EVT-1)\n * - (tier, status, occurred_at) — per-tier filter for the observability\n * viewer's tier toggle (AUDIT-1).\n */\nimport {\n check,\n index,\n jsonb,\n pgTable,\n text,\n timestamp,\n uuid,\n} from 'drizzle-orm/pg-core';\nimport { sql } from 'drizzle-orm';\nimport type { InferSelectModel } from 'drizzle-orm';\n\nexport const domainEvents = pgTable(\n 'domain_events',\n {\n id: uuid('id').primaryKey(),\n type: text('type').notNull(),\n aggregateId: text('aggregate_id').notNull(),\n aggregateType: text('aggregate_type').notNull(),\n payload: jsonb('payload').notNull().$type<Record<string, unknown>>(),\n occurredAt: timestamp('occurred_at', { withTimezone: true }).notNull(),\n processedAt: timestamp('processed_at', { withTimezone: true }),\n /** Lifecycle status: pending | processed | failed */\n status: text('status').notNull().default('pending'),\n /** Error message from the last failed dispatch attempt. */\n error: text('error'),\n metadata: jsonb('metadata').$type<Record<string, unknown>>(),\n /** Routing pool (e.g. `events_inbound`, `events_change`, `events_outbound`). Populated by DrizzleEventBus.publish() in EVT-4. NULL when `tier='audit'`. */\n pool: text('pool'),\n /** Routing direction: `inbound` | `change` | `outbound`. Populated by DrizzleEventBus.publish() in EVT-4. NULL when `tier='audit'`. */\n direction: text('direction'),\n /**\n * Event tier: `'domain'` (default) or `'audit'`. Audit-tier rows are\n * observability-only and have null `pool`/`direction` by construction —\n * enforced by the `domain_events_tier_routing_check` CHECK constraint\n * declared below. (AUDIT-1)\n */\n tier: text('tier').notNull().default('domain'),\n // conditional: emitted only when events.multi_tenant: true\n tenantId: text('tenant_id'),\n },\n (t) => ({\n /** Polling drain filter (existing — promoted from comment to declaration in EVT-1). */\n idxDomainEventsStatusOccurredAt: index('idx_domain_events_status_occurred_at').on(\n t.status,\n t.occurredAt,\n ),\n /** Event replay per aggregate (existing — promoted from comment to declaration in EVT-1). */\n idxDomainEventsAggregate: index('idx_domain_events_aggregate').on(\n t.aggregateId,\n t.aggregateType,\n ),\n /** Per-pool drain filter (EVT-1). Enables DrizzleEventBus to drain a single pool without scanning all events. */\n idxDomainEventsPoolStatusOccurredAt: index(\n 'idx_domain_events_pool_status_occurred_at',\n ).on(t.pool, t.status, t.occurredAt),\n /** Per-tier filter (AUDIT-1). Backs the observability viewer's tier toggle. */\n idxDomainEventsTierStatusOccurredAt: index(\n 'idx_domain_events_tier_status_occurred_at',\n ).on(t.tier, t.status, t.occurredAt),\n /**\n * Tier ↔ routing-fields invariant (AUDIT-1):\n * - `tier` is one of `'domain' | 'audit'`.\n * - `tier='audit'` ⇔ `pool IS NULL AND direction IS NULL`.\n * - `tier='domain'` ⇒ `pool` and `direction` are populated (the\n * DrizzleEventBus inserts always supply them; the bus stamps them\n * in AUDIT-3).\n */\n tierRoutingCheck: check(\n 'domain_events_tier_routing_check',\n sql`${t.tier} in ('domain','audit') AND ((${t.tier} = 'audit') = (${t.pool} is null and ${t.direction} is null))`,\n ),\n }),\n);\n\nexport type DomainEventRecord = InferSelectModel<typeof domainEvents>;\n","/**\n * Injection tokens for the bridge subsystem (ADR-023 Phase 2, BRIDGE-2).\n *\n * String constants (not Symbols) so they match by value across import\n * boundaries — same convention as `EVENT_BUS` / `EVENTS_MULTI_TENANT` in the\n * events subsystem (per EVT-6 §Implementation Notes). The jobs subsystem\n * uses Symbols for its analogous tokens; we keep the bridge file internally\n * consistent with the events convention because the bridge is conceptually\n * downstream of (and imports from) the events module.\n */\n\n/**\n * Token for the `IJobBridge` repo backend (memory in BRIDGE-3, Drizzle in\n * BRIDGE-4). Consumed by `BridgeDeliveryHandler` (BRIDGE-5), the outbox\n * drain (BRIDGE-4 modification), and `EventFlowService` (BRIDGE-7).\n */\nexport const BRIDGE_DELIVERY_REPO = 'BRIDGE_DELIVERY_REPO' as const;\n\n/**\n * Token for the `IEventFlow` facade implementation (BRIDGE-7). Use cases\n * inject this in preference to `EVENT_BUS` / `TYPED_EVENT_BUS` — calling\n * `eventFlow.publish(...)` / `eventFlow.publishAndStart(...)` is the\n * sanctioned authoring surface (ADR-023 §Decision 7).\n */\nexport const EVENT_FLOW = 'EVENT_FLOW' as const;\n\n/**\n * Token for the resolved multi-tenancy flag, provided by\n * `BridgeModule.forRoot({ multiTenant })` in BRIDGE-8. Consumed by\n * `EventFlowService.publishAndStart` (entry), `BridgeDeliveryHandler.handle`\n * (entry), and `DrizzleBridgeDeliveryRepo.insertDelivery` (pre-write) — the\n * three enforcement sites called out in ADR-023 §Multi-tenancy.\n */\nexport const BRIDGE_MULTI_TENANT = 'BRIDGE_MULTI_TENANT' as const;\n\n/**\n * Token for the resolved `BridgeModuleOptions` object. Provided by\n * `BridgeModule.forRoot(...)` / `forRootAsync(...)` in BRIDGE-8.\n * Mirrors `EVENTS_MODULE_OPTIONS` and `JOBS_DOMAIN_OPTIONS` shape — backends\n * inject this when they need to observe additional module configuration\n * (e.g. pool overrides) without each adding a dedicated token.\n */\nexport const BRIDGE_MODULE_OPTIONS = 'BRIDGE_MODULE_OPTIONS' as const;\n\n/**\n * Token for the codegen-emitted `bridgeRegistry` — the\n * `Record<EventTypeName, BridgeTriggerEntry[]>` map that drives\n * outbox-drain trigger lookup (BRIDGE-4) and `EventFlowService` Case B\n * dedup (BRIDGE-7). Provider registration lands in BRIDGE-8; the token is\n * declared here so generated code (BRIDGE-6) can import it without\n * depending on the still-being-formalised module.\n */\nexport const BRIDGE_REGISTRY = 'BRIDGE_REGISTRY' as const;\n\n\n/**\n * Token for the `IBridgeOutboxDrainHook` implementation (BRIDGE-4).\n * Injected `@Optional()` into `DrizzleEventBus` — when the bridge\n * subsystem is not installed the token is undefined and the events\n * outbox drain skips the bridge block entirely (preserves EVT-4\n * baseline behaviour).\n *\n * Resolution order: `BridgeModule.forRoot()` provides this token in\n * BRIDGE-8 alongside the rest of the bridge subsystem. `EventsModule`\n * itself never provides it; the events subsystem stays unaware of the\n * bridge unless the consumer wires it.\n */\nexport const BRIDGE_OUTBOX_DRAIN_HOOK = 'BRIDGE_OUTBOX_DRAIN_HOOK' as const;\n","/**\n * MemoryEventBus — in-memory backend for the event bus.\n *\n * Dispatches events synchronously to registered subscribers. The `tx`\n * parameter is ignored — all events are dispatched immediately.\n *\n * Use this backend in tests to assert event publication without a database.\n * Swap via EventsModule.forRoot({ backend: 'memory' }).\n *\n * Pool awareness (EVT-5):\n * - Mirrors the `DrizzleEventBus` per-process restriction (EVT-4). When\n * `opts.pools` is set, `publish`/`publishMany` still push the event into\n * `publishedEvents` (so test code can assert the full set of emitted\n * events regardless of pool filter), but handlers are NOT invoked for\n * events whose `metadata.pool` is outside the configured pools.\n * - `publishedEventsForPool(pool)` and `publishedEventsForDirection(dir)`\n * helpers are provided for targeted assertions.\n * - Shares the `EventsModuleOptions` shape (same token as Drizzle) rather\n * than introducing a memory-only options type — the surface is the same\n * and keeping them unified avoids drift between backends.\n */\nimport { Inject, Injectable, Logger, Optional } from '@nestjs/common';\nimport type { DomainEvent, IEventBus } from './event-bus.protocol';\nimport type {\n EventPage,\n EventSummary,\n IEventReadPort,\n ListEventsQuery,\n} from './event-read.protocol';\nimport {\n clampEventLimit,\n decodeEventCursor,\n encodeEventCursor,\n} from './event-keyset-cursor';\nimport { EVENTS_MODULE_OPTIONS } from './events.tokens';\nimport type { EventsModuleOptions } from './events.module';\n\n/**\n * Project an in-memory `DomainEvent` into the narrow `EventSummary` shape.\n * The memory backend has no first-class columns, so `pool` / `direction` /\n * `tier` / `tenantId` / `rootRunId` are read from `metadata` (mirroring how\n * the Drizzle backend stamps them onto columns at publish time). `status`\n * is reported as `'processed'` — the memory bus dispatches synchronously,\n * so once an event is in `publishedEvents` it has been handled.\n */\nfunction toEventSummary(event: DomainEvent): EventSummary {\n const metadata = event.metadata;\n const str = (key: string): string | null => {\n const v = metadata?.[key];\n return typeof v === 'string' ? v : null;\n };\n return {\n id: event.id,\n type: event.type,\n aggregateId: event.aggregateId,\n aggregateType: event.aggregateType,\n status: 'processed',\n pool: str('pool'),\n direction: str('direction'),\n tier: str('tier') ?? 'domain',\n rootRunId: str('rootRunId'),\n tenantId: str('tenantId'),\n occurredAt: event.occurredAt,\n processedAt: event.occurredAt,\n };\n}\n\n@Injectable()\nexport class MemoryEventBus implements IEventBus, IEventReadPort {\n private readonly logger = new Logger(MemoryEventBus.name);\n\n /** All events published since construction (or last clear). */\n readonly publishedEvents: DomainEvent[] = [];\n\n private readonly handlers = new Map<string, Set<(event: DomainEvent) => Promise<void>>>();\n private readonly opts: EventsModuleOptions;\n\n constructor(\n @Optional() @Inject(EVENTS_MODULE_OPTIONS) opts?: EventsModuleOptions,\n ) {\n // Default so direct construction (e.g. `new MemoryEventBus()` from a\n // unit test outside NestJS DI) keeps working without an explicit\n // options object.\n this.opts = opts ?? { backend: 'memory' };\n }\n\n async publish(event: DomainEvent): Promise<void> {\n // Mirror the `domain_events_tier_routing_check` DB constraint at the\n // memory backend boundary so misuse fails the same way regardless of\n // backend (AUDIT-1).\n this.assertTierRouting(event);\n\n // Always record the event — even if this process is configured with a\n // pool filter that excludes it. Test code relies on `publishedEvents`\n // being a complete log of what was published, not a filtered view.\n this.publishedEvents.push(event);\n\n if (this.shouldDispatch(event)) {\n await this.dispatch(event);\n }\n }\n\n async publishMany(events: DomainEvent[]): Promise<void> {\n for (const event of events) {\n await this.publish(event);\n }\n }\n\n async findById(eventId: string): Promise<DomainEvent | null> {\n return this.publishedEvents.find((e) => e.id === eventId) ?? null;\n }\n\n subscribe<T extends DomainEvent = DomainEvent>(\n eventType: string,\n handler: (event: T) => Promise<void>,\n ): () => void {\n if (!this.handlers.has(eventType)) {\n this.handlers.set(eventType, new Set());\n }\n // Cast is safe — callers pass a typed handler; we store as the base type\n const set = this.handlers.get(eventType)!;\n const h = handler as (event: DomainEvent) => Promise<void>;\n set.add(h);\n\n return () => {\n set.delete(h);\n };\n }\n\n // ============================================================================\n // IEventReadPort (OBS-LIST-1)\n // ============================================================================\n\n async listEvents(query: ListEventsQuery = {}): Promise<EventPage> {\n const limit = clampEventLimit(query.limit);\n const keyset = query.cursor ? decodeEventCursor(query.cursor) : null;\n\n const str = (e: DomainEvent, key: string): string | null => {\n const v = e.metadata?.[key];\n return typeof v === 'string' ? v : null;\n };\n\n const matched = this.publishedEvents.filter((e) => {\n if (query.poolId && str(e, 'pool') !== query.poolId) return false;\n if (query.direction && str(e, 'direction') !== query.direction)\n return false;\n if (query.rootRunId && str(e, 'rootRunId') !== query.rootRunId)\n return false;\n if (query.since && e.occurredAt.getTime() < query.since.getTime())\n return false;\n if (query.tenantId !== undefined) {\n const t = str(e, 'tenantId');\n if (query.tenantId === null) {\n if (t !== null) return false;\n } else if (t !== query.tenantId) {\n return false;\n }\n }\n return true;\n });\n\n // Order occurred_at DESC, id DESC to match the Drizzle backend keyset.\n matched.sort((a, b) => {\n const dt = b.occurredAt.getTime() - a.occurredAt.getTime();\n if (dt !== 0) return dt;\n return a.id < b.id ? 1 : a.id > b.id ? -1 : 0;\n });\n\n const seeked = keyset\n ? matched.filter((e) => {\n const ct = e.occurredAt.getTime();\n const kt = keyset.occurredAt.getTime();\n if (ct < kt) return true;\n if (ct > kt) return false;\n return e.id < keyset.id;\n })\n : matched;\n\n const hasMore = seeked.length > limit;\n const page = hasMore ? seeked.slice(0, limit) : seeked;\n const items = page.map(toEventSummary);\n const last = page[page.length - 1];\n const nextCursor =\n hasMore && last\n ? encodeEventCursor({ occurredAt: last.occurredAt, id: last.id })\n : null;\n\n return { items, nextCursor };\n }\n\n /** Remove all published events and subscriptions. Useful in beforeEach. */\n clear(): void {\n this.publishedEvents.length = 0;\n this.handlers.clear();\n }\n\n /** Filter published events by `metadata.pool`. */\n publishedEventsForPool(pool: string): DomainEvent[] {\n return this.publishedEvents.filter((e) => e.metadata?.['pool'] === pool);\n }\n\n /** Filter published events by `metadata.direction`. */\n publishedEventsForDirection(direction: string): DomainEvent[] {\n return this.publishedEvents.filter((e) => e.metadata?.['direction'] === direction);\n }\n\n /**\n * Decide whether `event` should be dispatched to handlers given the\n * current pool filter.\n *\n * Semantics (mirroring `DrizzleEventBus.processBatch`):\n * - `opts.pools` undefined → dispatch everything (no filter).\n * - `opts.pools` empty array → treated as \"no filter\" to match the\n * Drizzle backend, where `pools && pools.length > 0` is the gate on\n * the `inArray` WHERE clause. Empty arrays dispatch everything.\n * - `opts.pools` non-empty → dispatch only when `event.metadata.pool`\n * is in the list. Events without `metadata.pool` do NOT match — they\n * are out of all configured pools by definition.\n */\n private shouldDispatch(event: DomainEvent): boolean {\n const pools = this.opts.pools;\n if (!pools || pools.length === 0) return true;\n const eventPool = event.metadata?.['pool'];\n return typeof eventPool === 'string' && pools.includes(eventPool);\n }\n\n /**\n * Mirror the `domain_events_tier_routing_check` DB CHECK at the memory\n * backend (AUDIT-1). Audit-tier events MUST have null/undefined\n * `pool` and `direction` in metadata; the bridge dispatcher relies on\n * this invariant.\n */\n private assertTierRouting(event: DomainEvent): void {\n const tier = event.metadata?.['tier'];\n if (tier !== 'audit') return;\n const pool = event.metadata?.['pool'];\n const direction = event.metadata?.['direction'];\n const poolIsNull = pool === null || pool === undefined;\n const directionIsNull = direction === null || direction === undefined;\n if (!poolIsNull || !directionIsNull) {\n throw new Error(\n `MemoryEventBus: tier='audit' events must have null pool and direction ` +\n `(got pool=${String(pool)}, direction=${String(direction)}). ` +\n `This mirrors the domain_events CHECK constraint.`,\n );\n }\n }\n\n private async dispatch(event: DomainEvent): Promise<void> {\n const set = this.handlers.get(event.type);\n if (!set) return;\n\n let firstError: unknown;\n for (const handler of set) {\n try {\n await handler(event);\n } catch (err) {\n this.logger.error(\n `Handler error for event type \"${event.type}\" (id: ${event.id}): ${err}`,\n );\n if (firstError === undefined) {\n firstError = err;\n }\n }\n }\n\n if (firstError !== undefined) {\n throw firstError;\n }\n }\n}\n","/**\n * Drizzle schema for the job orchestration domain (ADR-022).\n *\n * Three tables model the lifecycle of a durable job:\n * - `job` — definitions keyed by handler type (e.g. 'onboarding').\n * - `job_run` — one row per attempt to execute a job; worker claims\n * rows directly via SELECT ... FOR UPDATE SKIP LOCKED.\n * - `job_step` — individual steps within a run; memoises output for replay.\n *\n * Phase 1 ships only this layer. There is no `job_queue` table, no executor\n * port — see ADR-022 and `.claude/skills/jobs/SKILL.md` for the rationale.\n */\nimport {\n pgEnum,\n pgTable,\n uuid,\n text,\n jsonb,\n integer,\n timestamp,\n index,\n uniqueIndex,\n} from 'drizzle-orm/pg-core';\nimport { sql } from 'drizzle-orm';\nimport type { InferSelectModel } from 'drizzle-orm';\n\n// ─── Internal $type<> helpers ───────────────────────────────────────────────\n// Annotation types for jsonb columns only. JOB-2 defines the public protocol\n// types; these remain private to this file.\n\ntype RetryPolicy = {\n attempts: number;\n backoff: 'fixed' | 'exponential';\n baseMs: number;\n nonRetryableErrors?: string[];\n};\n\ntype JobRunError = {\n message: string;\n stack?: string;\n retryable: boolean;\n attempt: number;\n};\n\n// ─── Enums ──────────────────────────────────────────────────────────────────\n\nexport const jobRunStatusEnum = pgEnum('job_run_status', [\n 'pending',\n 'running',\n 'waiting',\n 'completed',\n 'failed',\n 'timed_out',\n 'canceled',\n]);\n\n// extended in ADR-027: tool_call | llm_call | wait | checkpoint | message\nexport const jobStepKindEnum = pgEnum('job_step_kind', ['task']);\n\nexport const jobStepStatusEnum = pgEnum('job_step_status', [\n 'pending',\n 'running',\n 'completed',\n 'failed',\n 'skipped',\n]);\n\nexport const collisionModeEnum = pgEnum('job_collision_mode', [\n 'queue',\n 'reject',\n 'replace',\n]);\n\nexport const replayFromEnum = pgEnum('job_replay_from', [\n 'scratch',\n 'last_step',\n 'last_checkpoint',\n]);\n\nexport const parentClosePolicyEnum = pgEnum('job_parent_close_policy', [\n 'terminate',\n 'cancel',\n 'abandon',\n]);\n\n// Phase 3 placeholder — see ADR-025\nexport const waitKindEnum = pgEnum('job_wait_kind', ['signal']);\n\n// Phase 2 may add more sources; requires Atlas migration\nexport const triggerSourceEnum = pgEnum('job_trigger_source', [\n 'manual',\n 'schedule',\n 'event',\n 'parent',\n]);\n\n// ─── job ────────────────────────────────────────────────────────────────────\n\nexport const jobs = pgTable('job', {\n type: text('type').primaryKey(),\n version: integer('version').notNull().default(1),\n pool: text('pool').notNull(),\n scopeEntityType: text('scope_entity_type'),\n retryPolicy: jsonb('retry_policy').notNull().$type<RetryPolicy>(),\n timeoutMs: integer('timeout_ms'),\n concurrencyKeyTemplate: text('concurrency_key_template'),\n collisionMode: collisionModeEnum('collision_mode').notNull().default('queue'),\n dedupeKeyTemplate: text('dedupe_key_template'),\n dedupeWindowMs: integer('dedupe_window_ms'),\n priorityDefault: integer('priority_default').notNull().default(0),\n replayFrom: replayFromEnum('replay_from').notNull().default('last_checkpoint'),\n createdAt: timestamp('created_at', { withTimezone: true }).notNull().defaultNow(),\n updatedAt: timestamp('updated_at', { withTimezone: true }).notNull().defaultNow(),\n});\n\nexport type JobDefinitionRow = InferSelectModel<typeof jobs>;\n\n// ─── job_run ────────────────────────────────────────────────────────────────\n\nexport const jobRuns = pgTable(\n 'job_run',\n {\n id: uuid('id').primaryKey().defaultRandom(),\n jobType: text('job_type').notNull().references(() => jobs.type),\n jobVersion: integer('job_version').notNull(),\n parentRunId: uuid('parent_run_id').references((): any => jobRuns.id),\n /**\n * Service generates `id` client-side via randomUUID() and sets\n * root_run_id = id for root runs (single INSERT, no self-FK race).\n */\n rootRunId: uuid('root_run_id').notNull(),\n parentClosePolicy: parentClosePolicyEnum('parent_close_policy')\n .notNull()\n .default('terminate'),\n scopeEntityType: text('scope_entity_type'),\n scopeEntityId: text('scope_entity_id'),\n tenantId: text('tenant_id'),\n tags: jsonb('tags').notNull().default({}).$type<Record<string, string>>(),\n pool: text('pool').notNull(),\n priority: integer('priority').notNull().default(0),\n concurrencyKey: text('concurrency_key'),\n dedupeKey: text('dedupe_key'),\n status: jobRunStatusEnum('status').notNull().default('pending'),\n input: jsonb('input').notNull().$type<Record<string, unknown>>(),\n output: jsonb('output').$type<Record<string, unknown>>(),\n error: jsonb('error').$type<JobRunError>(),\n triggerSource: triggerSourceEnum('trigger_source').notNull(),\n triggerRef: text('trigger_ref'),\n runAt: timestamp('run_at', { withTimezone: true }).notNull().defaultNow(),\n startedAt: timestamp('started_at', { withTimezone: true }),\n finishedAt: timestamp('finished_at', { withTimezone: true }),\n claimedAt: timestamp('claimed_at', { withTimezone: true }),\n attempts: integer('attempts').notNull().default(0),\n // Phase 3 placeholder — see ADR-025\n waitKind: waitKindEnum('wait_kind'),\n // Phase 3 placeholder — see ADR-025\n resumeToken: text('resume_token'),\n // Phase 3 placeholder — see ADR-025\n waitDeadline: timestamp('wait_deadline', { withTimezone: true }),\n createdAt: timestamp('created_at', { withTimezone: true }).notNull().defaultNow(),\n updatedAt: timestamp('updated_at', { withTimezone: true }).notNull().defaultNow(),\n },\n (t) => ({\n /** Claim query: ORDER BY priority DESC, run_at ASC. */\n idxJobRunClaim: index('idx_job_run_claim').on(t.status, t.pool, t.runAt),\n /** Tree traversal / cascade cancel. */\n idxJobRunRoot: index('idx_job_run_root').on(t.rootRunId),\n /** listForScope query. */\n idxJobRunScope: index('idx_job_run_scope').on(t.scopeEntityType, t.scopeEntityId),\n /** Idempotency collapse — partial index. */\n idxJobRunDedupe: index('idx_job_run_dedupe')\n .on(t.jobType, t.dedupeKey)\n .where(sql`${t.dedupeKey} IS NOT NULL`),\n /** Collision check — partial index. */\n idxJobRunConcurrency: index('idx_job_run_concurrency')\n .on(t.concurrencyKey)\n .where(\n sql`${t.concurrencyKey} IS NOT NULL AND ${t.status} IN ('pending','running')`,\n ),\n }),\n);\n\nexport type JobRunRow = InferSelectModel<typeof jobRuns>;\n\n// ─── job_step ───────────────────────────────────────────────────────────────\n\nexport const jobSteps = pgTable(\n 'job_step',\n {\n id: uuid('id').primaryKey().defaultRandom(),\n jobRunId: uuid('job_run_id').notNull().references(() => jobRuns.id),\n stepId: text('step_id').notNull(),\n kind: jobStepKindEnum('kind').notNull().default('task'),\n /**\n * Monotonic within run. integer (max ~2B per run) is sufficient —\n * downgraded from ADR-022's bigint; revisit only if a single run\n * ever exceeds 2 billion steps.\n */\n seq: integer('seq').notNull(),\n status: jobStepStatusEnum('status').notNull().default('pending'),\n input: jsonb('input').$type<Record<string, unknown>>(),\n /** Memoised on success for replay. */\n output: jsonb('output').$type<Record<string, unknown>>(),\n error: jsonb('error').$type<JobRunError>(),\n attempts: integer('attempts').notNull().default(0),\n startedAt: timestamp('started_at', { withTimezone: true }),\n finishedAt: timestamp('finished_at', { withTimezone: true }),\n },\n (t) => ({\n /** No duplicate step IDs per run. */\n idxJobStepRunStep: uniqueIndex('idx_job_step_run_step').on(t.jobRunId, t.stepId),\n /** Ordered timeline reads. */\n idxJobStepTimeline: index('idx_job_step_timeline').on(t.jobRunId, t.seq),\n }),\n);\n\nexport type JobStepRow = InferSelectModel<typeof jobSteps>;\n","/**\n * Injection tokens for the job orchestration domain layer (ADR-022, JOB-2).\n *\n * Consumer code injects these symbols via `@Inject(JOB_ORCHESTRATOR)` etc.;\n * concrete backends (JOB-3 Drizzle, JOB-4 Memory) provide the implementations\n * through `JobsDomainModule.forRoot({ backend })` in JOB-5.\n *\n * Each token is a namespaced `Symbol.for(...)` (ADR-037, via `tokenKey()`) —\n * distinct per key, so Nest's DI lookup is unambiguous, AND matching by VALUE\n * across import boundaries so the package and a (legacy) vendored runtime copy\n * resolve to the same symbol.\n */\nimport { tokenKey } from '../token-key';\n\nexport const JOB_ORCHESTRATOR = Symbol.for(tokenKey('jobs', 'orchestrator'));\nexport const JOB_RUN_SERVICE = Symbol.for(tokenKey('jobs', 'run-service'));\nexport const JOB_STEP_SERVICE = Symbol.for(tokenKey('jobs', 'step-service'));\n\n/**\n * Multi-tenancy opt-in flag (JOB-8). Bound to the boolean passed in via\n * `JobsDomainModule.forRoot({ multiTenant })`, defaulting to `false`.\n *\n * When `true`, the four service-layer backends (Drizzle + Memory orchestrator\n * and run-service) enforce `tenantId` on every mutating / targeted-read call:\n * `start`, `cancel`, `listForScope`, `cancelForScope`, `rescheduleForScope`.\n * Missing (`undefined`) `tenantId` throws `MissingTenantIdError`; explicit\n * `null` opts into cross-tenant background work and passes through.\n *\n * The JobWorker claim loop is **cross-tenant by design** — the worker has no\n * tenant context; `tenantId` is populated at write time and enforced on\n * targeted reads. See docs/specs/JOB-8.md.\n */\nexport const JOBS_MULTI_TENANT = Symbol.for(tokenKey('jobs', 'multi-tenant'));\n","/**\n * Handler base class, JobContext, @JobHandler decorator, and policy types\n * for the job orchestration domain (ADR-022, JOB-2).\n *\n * User-authored jobs subclass `JobHandlerBase<TInput, TOutput>` and decorate\n * the class with `@JobHandler<TInput>('job_type', meta)`. The decorator\n * 1. stores metadata via `Reflect.defineMetadata` so Nest's reflector can\n * pick it up at module boot, and\n * 2. populates `JOB_HANDLER_REGISTRY` — a module-singleton map consumed by\n * `JobWorkerModule` (JOB-5) to materialise `job` rows and resolve\n * handler classes during claim/execute.\n *\n * No runtime orchestration lives here; this file is a pure type + decorator\n * surface so downstream PRs (JOB-3..JOB-5) can implement against a stable\n * shape.\n */\n// TODO(logging-subsystem): swap to ILogger once ADR-028 lands\nimport type { Logger } from '@nestjs/common';\nimport { tokenKey } from '../token-key';\nimport type { EventOfType, EventTypeName } from '../events/generated/types';\nimport type { JobRun } from './job-orchestrator.protocol';\n\n// ─── ParentClosePolicy ──────────────────────────────────────────────────────\n\n/**\n * What happens to running child runs when a parent enters a terminal state.\n * Stored on the child at spawn; changes to the parent after spawn do NOT\n * retroactively rewrite children.\n */\nexport enum ParentClosePolicy {\n Terminate = 'terminate',\n Cancel = 'cancel',\n Abandon = 'abandon',\n}\n\n// ─── Policy types ───────────────────────────────────────────────────────────\n\nexport interface RetryPolicy {\n attempts: number;\n backoff: 'fixed' | 'exponential';\n baseMs: number;\n nonRetryableErrors?: string[];\n}\n\nexport interface ConcurrencyPolicy<TInput> {\n key: (input: TInput) => string;\n collisionMode: 'queue' | 'reject' | 'replace';\n}\n\nexport interface DedupePolicy<TInput> {\n key: (input: TInput) => string;\n windowMs: number;\n}\n\n/**\n * Declarative scope reference. `TScope` is parameterised so JOB-7 can narrow\n * `entity` to the generated `ScopeEntityType` union at the call site without\n * modifying this file (OQ-1 resolution, 2026-04-20).\n */\nexport interface ScopeRef<TInput, TScope extends string = string> {\n entity: TScope;\n from: (input: TInput) => string;\n}\n\n/**\n * Bridge trigger authoring shape (BRIDGE-6 follow-up — BRIDGE-6 shipped the\n * generator + runtime for `@JobHandler({ triggers })` but never added the\n * authoring field to this type; the generator's tests scan source as strings,\n * so a real decorator was never compiled and the gap went uncaught).\n *\n * Declared on `@JobHandler({ triggers })`; the codegen bridge-registry\n * generator (`src/cli/shared/bridge-registry-generator.ts`) scans these from\n * source and emits `bridge/generated/registry.ts`, validating each `event`\n * against the generated `eventRegistry` at `gen-all`. The distributed union\n * narrows `map`/`when` per `event`, so callbacks are typed against the event\n * payload (ADR-023, \"typed against PayloadOfType<T>\").\n *\n * Typed against events' generated types — the same `import type` coupling the\n * bridge already has (erased at runtime). `jobs` must NOT import `bridge`, so\n * the post-gen `BridgeTriggerEntry` is deliberately not referenced here;\n * `triggerId`/`jobType` are computed by the generator, not authored.\n */\nexport type JobTrigger<TInput> = {\n [T in EventTypeName]: {\n /** Event type that fires this trigger. Validated against `eventRegistry`. */\n event: T;\n /** Maps the event to the job input. Inlined verbatim into the registry. */\n map: (event: EventOfType<T>) => TInput;\n /** Optional guard; `false` → wrapper records `status='skipped'`. */\n when?: (event: EventOfType<T>) => boolean;\n };\n}[EventTypeName];\n\nexport interface JobHandlerMeta<TInput> {\n pool?: string;\n scope?: ScopeRef<TInput>;\n retry?: RetryPolicy;\n concurrency?: ConcurrencyPolicy<TInput>;\n dedupe?: DedupePolicy<TInput>;\n timeoutMs?: number;\n replayFrom?: 'scratch' | 'last_step' | 'last_checkpoint';\n /**\n * Bridge triggers (ADR-023 Tier 3). Codegen scans these into `bridgeRegistry`;\n * the framework `BridgeDeliveryHandler` starts this job per matched event.\n * Absent for jobs started directly or via `IEventFlow.publishAndStart`.\n */\n triggers?: readonly JobTrigger<TInput>[];\n}\n\n// ─── Runtime option shapes ──────────────────────────────────────────────────\n\nexport interface StepOptions {\n retry?: RetryPolicy;\n timeoutMs?: number;\n}\n\nexport interface SpawnChildOptions {\n closePolicy?: ParentClosePolicy;\n runAt?: Date;\n priority?: number;\n tags?: Record<string, string>;\n}\n\n// ─── JobContext ─────────────────────────────────────────────────────────────\n\nexport interface JobContext<TInput> {\n readonly input: TInput;\n readonly run: JobRun;\n step<TOutput>(\n stepId: string,\n fn: () => Promise<TOutput>,\n opts?: StepOptions,\n ): Promise<TOutput>;\n spawnChild(type: string, input: unknown, opts?: SpawnChildOptions): Promise<JobRun>;\n readonly logger: Logger;\n // NOT in Phase 1 — deferred to ADR-025:\n // waitFor(kind, token, opts)\n // signal(token, payload)\n // sleep(ms)\n}\n\n// ─── JobHandlerBase ─────────────────────────────────────────────────────────\n\nexport abstract class JobHandlerBase<TInput, TOutput = unknown> {\n abstract run(ctx: JobContext<TInput>): Promise<TOutput>;\n}\n\n// ─── Registry + decorator ───────────────────────────────────────────────────\n\n/**\n * Module-singleton map keyed by job type. Populated by the `@JobHandler`\n * decorator at class definition time; consumed by `JobWorkerModule` (JOB-5)\n * to upsert `job` rows and resolve handler classes during claim/execute.\n */\nexport const JOB_HANDLER_REGISTRY = new Map<\n string,\n {\n type: string;\n meta: JobHandlerMeta<unknown>;\n handlerClass: new (...args: unknown[]) => JobHandlerBase<unknown>;\n }\n>();\n\n// ADR-037: namespaced `Symbol.for(...)` (via `tokenKey()`) so the reflection-metadata\n// key matches by value across import boundaries (the @JobHandler decorator and the\n// reader may resolve different runtime copies). Distinct from the DI tokens but\n// subject to the same dual-package identity hazard.\nexport const JOB_HANDLER_METADATA_KEY = Symbol.for(tokenKey('jobs', 'handler-metadata'));\n\n/**\n * Class decorator that registers a handler with the job type, the full\n * metadata shape, and the target class constructor.\n *\n * Duplicate-type behaviour (OQ-3, resolved 2026-04-18):\n * - `NODE_ENV === 'production'` → throw; silent overwrite in prod is a\n * correctness bug.\n * - `NODE_ENV === 'test'` → silent overwrite (tests intentionally\n * re-register handlers).\n * - otherwise (dev) → `console.warn` + overwrite. `console`\n * is used intentionally instead of the Nest `Logger` — decorators run\n * at module-load time before any Nest container exists.\n */\nexport function JobHandler<TInput>(\n type: string,\n meta: JobHandlerMeta<TInput>,\n): ClassDecorator {\n return (target) => {\n if (JOB_HANDLER_REGISTRY.has(type)) {\n const env = process.env.NODE_ENV;\n if (env === 'production') {\n throw new Error(\n `[JobHandler] Duplicate registration for job type '${type}'. ` +\n `Each @JobHandler must declare a unique type.`,\n );\n }\n if (env !== 'test') {\n // eslint-disable-next-line no-console\n console.warn(\n `[JobHandler] Duplicate registration for job type '${type}'. ` +\n `Overwriting previous handler — this is almost certainly a bug.`,\n );\n }\n }\n\n Reflect.defineMetadata(JOB_HANDLER_METADATA_KEY, { type, meta }, target);\n JOB_HANDLER_REGISTRY.set(type, {\n type,\n meta: meta as JobHandlerMeta<unknown>,\n handlerClass: target as unknown as new (\n ...args: unknown[]\n ) => JobHandlerBase<unknown>,\n });\n };\n}\n\n// ─── HandlerRegistry — read helpers consumed by JobWorkerModule (JOB-5) ─────\n\n/**\n * Single entry shape returned by `HandlerRegistry.getAll()` / `.get()` and\n * exposed to `JobWorkerModule.onModuleInit` for boot-time upserts.\n *\n * Structurally compatible with `IJobOrchestrator.upsertJobRows`'s\n * `JobUpsertEntry` so the worker module can pass entries through verbatim\n * without re-mapping.\n */\nexport interface HandlerRegistryEntry {\n type: string;\n meta: JobHandlerMeta<unknown>;\n handlerClass: new (...args: unknown[]) => JobHandlerBase<unknown>;\n}\n\n/**\n * Read facade over `JOB_HANDLER_REGISTRY`. The decorator's write path is\n * unchanged; this namespace exists so consumers (the worker module, tests)\n * don't import the raw `Map` and accidentally mutate it.\n */\nexport namespace HandlerRegistry {\n /** All registered entries in insertion order. */\n export function getAll(): HandlerRegistryEntry[] {\n return Array.from(JOB_HANDLER_REGISTRY.values());\n }\n\n /** Lookup by job type, or `undefined` if no `@JobHandler` is registered. */\n export function get(type: string): HandlerRegistryEntry | undefined {\n return JOB_HANDLER_REGISTRY.get(type);\n }\n}\n","/**\n * DrizzleJobOrchestrator — Postgres-backed implementation of\n * `IJobOrchestrator` (ADR-022, JOB-3).\n *\n * Single-layer architecture: `start` writes a single `job_run` row; the\n * `JobWorker` polling loop claims it directly via `FOR UPDATE SKIP LOCKED`.\n * No `job_queue` table, no executor port. See `docs/specs/JOB-3.md`.\n */\nimport { randomUUID } from 'node:crypto';\nimport { Inject, Injectable, Logger } from '@nestjs/common';\nimport { and, desc, eq, gt, inArray, isNotNull, ne, notInArray, sql } from 'drizzle-orm';\nimport type { DrizzleClient } from '../../types/drizzle';\nimport type { DrizzleTransaction } from '../events/event-bus.protocol';\nimport { DRIZZLE } from '../../constants/tokens';\nimport {\n jobRuns,\n jobs,\n type JobDefinitionRow,\n type JobRunRow,\n} from './job-orchestration.schema';\nimport type {\n CancelOptions,\n IJobOrchestrator,\n JobPoolDef,\n JobRun,\n JobUpsertEntry,\n StartOptions,\n} from './job-orchestrator.protocol';\nimport {\n JobCollisionError,\n JobNotReplayableError,\n JobTemplateFieldMissingError,\n JobTypeNotFoundError,\n MissingTenantIdError,\n} from './jobs-errors';\nimport { jobSteps } from './job-orchestration.schema';\nimport { JOBS_MULTI_TENANT } from './jobs-domain.tokens';\n\n/**\n * Terminal statuses — transitions into these are final. Used by `cancel`\n * (to short-circuit idempotently) and by `replay` (as the guard gate).\n */\nexport const TERMINAL_STATUSES = [\n 'completed',\n 'failed',\n 'timed_out',\n 'canceled',\n] as const;\ntype TerminalStatus = (typeof TERMINAL_STATUSES)[number];\ntype JobRunStatus = JobRunRow['status'];\n\n/** Statuses excluded from dedupe window matches per ADR-022. */\nconst DEDUPE_EXCLUDED_STATUSES: JobRunStatus[] = ['canceled', 'failed'];\n/** Statuses that count as in-flight for concurrency collision checks. */\nconst IN_FLIGHT_STATUSES: JobRunStatus[] = ['pending', 'running'];\n\n/**\n * Substitute `{{field}}` placeholders against the input payload.\n *\n * Implementation decision (JOB-3, 2026-04-19): simple `{{field}}` single-key\n * substitution, no dotted paths, no Mustache/Handlebars dependency. A missing\n * field throws `JobTemplateFieldMissingError` synchronously — cheaper than\n * discovering the misconfiguration at claim time.\n */\nexport function evaluateKeyTemplate(\n template: string,\n input: Record<string, unknown>,\n): string {\n return template.replace(/\\{\\{\\s*([a-zA-Z0-9_]+)\\s*\\}\\}/g, (_match, field: string) => {\n const value = input[field];\n if (value === undefined || value === null) {\n throw new JobTemplateFieldMissingError(template, field);\n }\n return String(value);\n });\n}\n\n@Injectable()\nexport class DrizzleJobOrchestrator implements IJobOrchestrator {\n // TODO(logging-subsystem): swap to ILogger once ADR-028 lands\n private readonly logger = new Logger(DrizzleJobOrchestrator.name);\n\n constructor(\n @Inject(DRIZZLE) private readonly db: DrizzleClient,\n @Inject(JOBS_MULTI_TENANT) private readonly multiTenant: boolean,\n ) {}\n\n /**\n * JOB-8 — resolve `tenantId` for a mutating / targeted-read call.\n * Returns the tenant value that should be written to the row (or compared\n * against in a WHERE clause). When `multiTenant` is off, the column is\n * forced to `null` regardless of what callers pass. When on, `undefined`\n * throws; `null` and strings pass through untouched.\n */\n private resolveTenantId(\n method: string,\n tenantId: string | null | undefined,\n ): string | null {\n if (!this.multiTenant) return null;\n if (tenantId === undefined) throw new MissingTenantIdError(method);\n return tenantId;\n }\n\n // ==========================================================================\n // start\n // ==========================================================================\n\n async start(\n type: string,\n input: unknown,\n opts: StartOptions = {},\n tx?: DrizzleTransaction,\n ): Promise<JobRun> {\n const payload = (input ?? {}) as Record<string, unknown>;\n\n // JOB-8 — resolve tenant gate up front so `multi_tenant=true` +\n // undefined surfaces before any row is touched.\n const tenantId = this.resolveTenantId('start', opts.tenantId);\n\n // BRIDGE-7: thread the optional caller tx through every read/write\n // in this method so EventFlowService.publishAndStart can bundle the\n // outbox insert, the eager job_run insert, and (for Case B) the\n // bridge_delivery pre-write into a single transaction.\n const client = (tx ?? this.db) as DrizzleClient;\n\n // 1a. Load job definition.\n const [def] = await client\n .select()\n .from(jobs)\n .where(eq(jobs.type, type))\n .limit(1);\n if (!def) throw new JobTypeNotFoundError(type);\n const definition = def as JobDefinitionRow;\n\n // 1b. Dedupe check.\n if (definition.dedupeKeyTemplate && definition.dedupeWindowMs) {\n const dedupeKey = evaluateKeyTemplate(definition.dedupeKeyTemplate, payload);\n const windowStart = new Date(Date.now() - definition.dedupeWindowMs);\n const existing = await client\n .select()\n .from(jobRuns)\n .where(\n and(\n eq(jobRuns.jobType, type),\n eq(jobRuns.dedupeKey, dedupeKey),\n gt(jobRuns.createdAt, windowStart),\n // status NOT IN ('canceled', 'failed')\n notInStatus(DEDUPE_EXCLUDED_STATUSES),\n ),\n )\n .orderBy(desc(jobRuns.createdAt))\n .limit(1);\n if (existing.length > 0) {\n return existing[0] as JobRun;\n }\n }\n\n // 1c. Concurrency collision check.\n let concurrencyKey: string | null = null;\n if (definition.concurrencyKeyTemplate) {\n concurrencyKey = evaluateKeyTemplate(\n definition.concurrencyKeyTemplate,\n payload,\n );\n const inFlight = await client\n .select()\n .from(jobRuns)\n .where(\n and(\n eq(jobRuns.concurrencyKey, concurrencyKey),\n inArray(jobRuns.status, IN_FLIGHT_STATUSES),\n ),\n )\n .limit(1);\n if (inFlight.length > 0) {\n const incumbent = inFlight[0] as JobRun;\n switch (definition.collisionMode) {\n case 'reject':\n throw new JobCollisionError(type, concurrencyKey, incumbent);\n case 'replace':\n // JOB-8 — thread the incumbent's own tenantId through the\n // internal cascade. Without this, every `replace`-collision\n // start() under multiTenant=true throws MissingTenantIdError\n // from the inner cancel() call instead of cancelling the\n // incumbent. Mirrors the memory backend's `cancelLocked(\n // incumbent.id, ..., incumbent.tenantId)` pattern.\n await this.cancel(incumbent.id, {\n cascade: true,\n reason: 'replaced',\n tenantId: incumbent.tenantId,\n });\n break;\n case 'queue':\n // Fall through — row is inserted; claim query gates it until\n // the incumbent transitions (see JobWorker.processRun queue gate).\n break;\n }\n }\n }\n\n // 1d. Resolve id + rootRunId, INSERT.\n const newId = randomUUID();\n let rootRunId: string = newId;\n if (opts.parentRunId) {\n const [parent] = await client\n .select({ rootRunId: jobRuns.rootRunId })\n .from(jobRuns)\n .where(eq(jobRuns.id, opts.parentRunId))\n .limit(1);\n if (!parent) {\n throw new Error(\n `parentRunId ${opts.parentRunId} does not reference an existing job_run`,\n );\n }\n rootRunId = parent.rootRunId;\n }\n\n const dedupeKey =\n definition.dedupeKeyTemplate\n ? evaluateKeyTemplate(definition.dedupeKeyTemplate, payload)\n : null;\n\n const [inserted] = await client\n .insert(jobRuns)\n .values({\n id: newId,\n jobType: type,\n jobVersion: definition.version,\n parentRunId: opts.parentRunId ?? null,\n rootRunId,\n parentClosePolicy: opts.parentClosePolicy ?? 'terminate',\n scopeEntityType: opts.scope?.entityType ?? null,\n scopeEntityId: opts.scope?.entityId ?? null,\n tenantId,\n tags: opts.tags ?? {},\n pool: opts.pool ?? definition.pool,\n priority: opts.priority ?? definition.priorityDefault,\n concurrencyKey,\n dedupeKey,\n status: 'pending',\n input: payload,\n output: null,\n error: null,\n triggerSource: opts.triggerSource ?? 'manual',\n triggerRef: opts.triggerRef ?? null,\n runAt: opts.runAt ?? new Date(),\n startedAt: null,\n finishedAt: null,\n claimedAt: null,\n attempts: 0,\n })\n .returning();\n\n return inserted as JobRun;\n }\n\n // ==========================================================================\n // cancel\n // ==========================================================================\n\n async cancel(runId: string, opts: CancelOptions = {}): Promise<void> {\n // JOB-8 — resolve tenant gate up front (strict undefined-throws).\n const tenantId = this.resolveTenantId('cancel', opts.tenantId);\n\n // Load target.\n const [target] = await this.db\n .select()\n .from(jobRuns)\n .where(eq(jobRuns.id, runId))\n .limit(1);\n if (!target) return;\n // JOB-8 — cross-tenant cancel is a silent no-op (no existence leak).\n if (this.multiTenant && target.tenantId !== tenantId) return;\n if (TERMINAL_STATUSES.includes(target.status as TerminalStatus)) {\n return; // idempotent\n }\n\n // Atomic transition, guarded against concurrent terminal moves.\n const [cancelled] = await this.db\n .update(jobRuns)\n .set({\n status: 'canceled',\n finishedAt: new Date(),\n updatedAt: new Date(),\n })\n .where(\n and(eq(jobRuns.id, runId), notInStatus([...TERMINAL_STATUSES])),\n )\n .returning();\n\n if (!cancelled) return; // lost the race; already terminal\n\n if (opts.cascade === false) return;\n\n // Fetch descendants and branch on parent_close_policy.\n const descendants = await this.db\n .select()\n .from(jobRuns)\n .where(\n and(\n eq(jobRuns.rootRunId, target.rootRunId),\n ne(jobRuns.id, runId),\n notInStatus([...TERMINAL_STATUSES]),\n ),\n );\n\n for (const child of descendants) {\n const policy = (child as JobRunRow).parentClosePolicy;\n if (policy === 'abandon') continue;\n // 'terminate' | 'cancel' — both transition the child to canceled.\n await this.db\n .update(jobRuns)\n .set({\n status: 'canceled',\n finishedAt: new Date(),\n updatedAt: new Date(),\n })\n .where(\n and(\n eq(jobRuns.id, (child as JobRunRow).id),\n notInStatus([...TERMINAL_STATUSES]),\n ),\n );\n }\n\n void opts.reason; // reserved for future audit logging\n }\n\n // ==========================================================================\n // replay\n // ==========================================================================\n\n async replay(runId: string): Promise<JobRun> {\n // Load target + its job definition (we need replay_from).\n const [target] = await this.db\n .select()\n .from(jobRuns)\n .where(eq(jobRuns.id, runId))\n .limit(1);\n if (!target) {\n throw new Error(`replay: run ${runId} not found`);\n }\n const run = target as JobRunRow;\n if (!TERMINAL_STATUSES.includes(run.status as TerminalStatus)) {\n throw new JobNotReplayableError(runId, run.status);\n }\n\n const [def] = await this.db\n .select()\n .from(jobs)\n .where(eq(jobs.type, run.jobType))\n .limit(1);\n if (!def) throw new JobTypeNotFoundError(run.jobType);\n const mode = (def as JobDefinitionRow).replayFrom;\n\n // Atomic: step reset + run reset must commit together.\n const result = await this.db.transaction(async (tx) => {\n if (mode === 'scratch') {\n await tx.delete(jobSteps).where(eq(jobSteps.jobRunId, runId));\n } else if (mode === 'last_step') {\n // Delete only non-completed step rows — completed steps stay memoised.\n await tx\n .delete(jobSteps)\n .where(\n and(eq(jobSteps.jobRunId, runId), ne(jobSteps.status, 'completed')),\n );\n } else {\n // 'last_checkpoint' — Phase 1 has no explicit checkpoint markers, so\n // behaviour collapses to `last_step`. See docs/specs/JOB-3.md\n // \"Implementation Decisions\" — planned divergence in a later phase.\n await tx\n .delete(jobSteps)\n .where(\n and(eq(jobSteps.jobRunId, runId), ne(jobSteps.status, 'completed')),\n );\n }\n\n const [updated] = await tx\n .update(jobRuns)\n .set({\n status: 'pending',\n attempts: 0,\n runAt: new Date(),\n startedAt: null,\n finishedAt: null,\n claimedAt: null,\n error: null,\n output: null,\n updatedAt: new Date(),\n })\n .where(eq(jobRuns.id, runId))\n .returning();\n return updated as JobRunRow;\n });\n\n return result as JobRun;\n }\n\n // ==========================================================================\n // upsertJobRows — boot-time materialisation of `job` definitions\n // ==========================================================================\n\n /**\n * Hash-gated `INSERT … ON CONFLICT (type) DO UPDATE … WHERE` per Q3\n * resolution (2026-04-19): the `UPDATE` branch executes only when one\n * of the persisted metadata fields differs from the incoming payload;\n * `version` bumps only on real change; concurrent boots with identical\n * content are idempotent no-ops.\n *\n * Why this shape (not `DO NOTHING`, not advisory locks):\n * - `DO NOTHING` would let an old-version instance leave a stale row\n * that a new-version instance can't overwrite during a rolling deploy.\n * - Advisory locks add latency and leak risk under crashes.\n * - The `WHERE … IS DISTINCT FROM …` clause makes the conditional\n * atomic — no read-modify-write race on `version` between concurrent\n * boots.\n *\n * Orphan detection: a single `SELECT type FROM job WHERE type NOT IN (...)`\n * returns the types present in DB but absent from `entries`. Caller (boot\n * validator) decides whether to throw `BootValidationError`.\n */\n async upsertJobRows(\n entries: JobUpsertEntry[],\n poolConfig: ReadonlyMap<string, JobPoolDef>,\n ): Promise<{ orphaned: string[] }> {\n void poolConfig; // pool validation is the module's responsibility; orchestrator just persists\n\n for (const entry of entries) {\n const meta = entry.meta;\n const pool = meta.pool ?? 'batch';\n const retryPolicy = meta.retry ?? {\n attempts: 1,\n backoff: 'fixed' as const,\n baseMs: 0,\n };\n const concurrencyKeyTemplate =\n (meta.concurrency as { key?: unknown } | undefined)?.key;\n const concurrencyKeyTemplateStr =\n typeof concurrencyKeyTemplate === 'string' ? concurrencyKeyTemplate : null;\n const collisionMode =\n (meta.concurrency?.collisionMode as JobDefinitionRow['collisionMode']) ??\n 'queue';\n const dedupeKeyTemplate =\n (meta.dedupe as { key?: unknown } | undefined)?.key;\n const dedupeKeyTemplateStr =\n typeof dedupeKeyTemplate === 'string' ? dedupeKeyTemplate : null;\n const dedupeWindowMs = meta.dedupe?.windowMs ?? null;\n const timeoutMs = meta.timeoutMs ?? null;\n const replayFrom = meta.replayFrom ?? 'last_checkpoint';\n const scopeEntityType = meta.scope?.entity ?? null;\n // Q3 resolution: priority_default and replay_from are part of the\n // hashed metadata even though they aren't currently set via decorator\n // metadata above (priority_default has no `@JobHandler` field yet).\n // Default to 0 to keep UPDATE branch quiet across deploys.\n const priorityDefault = 0;\n\n // Hash-gated upsert: every metadata column appears in the WHERE clause\n // so the UPDATE branch only fires on a real change. `version` bumps\n // exactly when the WHERE matches.\n await this.db\n .insert(jobs)\n .values({\n type: entry.type,\n version: 1,\n pool,\n scopeEntityType,\n retryPolicy,\n timeoutMs,\n concurrencyKeyTemplate: concurrencyKeyTemplateStr,\n collisionMode,\n dedupeKeyTemplate: dedupeKeyTemplateStr,\n dedupeWindowMs,\n priorityDefault,\n replayFrom,\n })\n .onConflictDoUpdate({\n target: jobs.type,\n set: {\n pool: sql`EXCLUDED.pool`,\n scopeEntityType: sql`EXCLUDED.scope_entity_type`,\n retryPolicy: sql`EXCLUDED.retry_policy`,\n timeoutMs: sql`EXCLUDED.timeout_ms`,\n concurrencyKeyTemplate: sql`EXCLUDED.concurrency_key_template`,\n collisionMode: sql`EXCLUDED.collision_mode`,\n dedupeKeyTemplate: sql`EXCLUDED.dedupe_key_template`,\n dedupeWindowMs: sql`EXCLUDED.dedupe_window_ms`,\n priorityDefault: sql`EXCLUDED.priority_default`,\n replayFrom: sql`EXCLUDED.replay_from`,\n version: sql`${jobs.version} + 1`,\n updatedAt: sql`now()`,\n },\n // The hash gate: every field listed in the Q3 resolution appears\n // here. `IS DISTINCT FROM` is the null-safe inequality operator;\n // jsonb cast to text gives stable comparison without invoking a\n // dedicated hash column (avoids a JOB-1 schema migration).\n setWhere: sql`\n ${jobs.pool} IS DISTINCT FROM EXCLUDED.pool OR\n ${jobs.retryPolicy}::text IS DISTINCT FROM EXCLUDED.retry_policy::text OR\n ${jobs.timeoutMs} IS DISTINCT FROM EXCLUDED.timeout_ms OR\n ${jobs.concurrencyKeyTemplate} IS DISTINCT FROM EXCLUDED.concurrency_key_template OR\n ${jobs.collisionMode} IS DISTINCT FROM EXCLUDED.collision_mode OR\n ${jobs.dedupeKeyTemplate} IS DISTINCT FROM EXCLUDED.dedupe_key_template OR\n ${jobs.dedupeWindowMs} IS DISTINCT FROM EXCLUDED.dedupe_window_ms OR\n ${jobs.priorityDefault} IS DISTINCT FROM EXCLUDED.priority_default OR\n ${jobs.replayFrom} IS DISTINCT FROM EXCLUDED.replay_from OR\n ${jobs.scopeEntityType} IS DISTINCT FROM EXCLUDED.scope_entity_type\n `,\n });\n }\n\n // Orphan detection: any `job` row whose type is not in the registry.\n const types = entries.map((e) => e.type);\n const orphans =\n types.length === 0\n ? await this.db.select({ type: jobs.type }).from(jobs)\n : await this.db\n .select({ type: jobs.type })\n .from(jobs)\n .where(notInArray(jobs.type, types));\n\n return { orphaned: orphans.map((o) => o.type) };\n }\n}\n\n// ─── Helpers ────────────────────────────────────────────────────────────────\n\nfunction notInStatus(statuses: JobRunStatus[]) {\n // Drizzle's inArray composes with `not` via negation helper; use raw sql\n // to stay readable. `inArray` + `.not()` isn't idiomatic in 0.45.\n const negated = statuses.map((s) => ne(jobRuns.status, s));\n return and(...negated);\n}\n\n// `isNotNull` + `gt` imports are retained for potential future use; silence\n// unused-import lint by re-exporting via `void`.\nvoid isNotNull;\n","/**\n * Typed errors for the job orchestration domain (ADR-022, JOB-3).\n *\n * All thrown by the Drizzle orchestrator (and mirrored by the Memory\n * backend in JOB-4). They exist as classes so consumers can `instanceof`\n * them in catch blocks and exception filters can map them to HTTP codes.\n */\nimport type { JobRun } from './job-orchestrator.protocol';\n\n/**\n * `start(type, …)` was called for a job type that has no row in the `job`\n * table. At runtime this usually means the handler was not decorated or the\n * boot validator (JOB-5) has not registered it yet.\n */\nexport class JobTypeNotFoundError extends Error {\n override readonly name = 'JobTypeNotFoundError';\n constructor(public readonly jobType: string) {\n super(`No job definition registered for type '${jobType}'.`);\n }\n}\n\n/**\n * Thrown by `start` when `collision_mode === 'reject'` and a non-terminal\n * run with the same `concurrency_key` already exists. Carries the incumbent\n * so callers can surface its id or subscribe to its completion event.\n */\nexport class JobCollisionError extends Error {\n override readonly name = 'JobCollisionError';\n constructor(\n public readonly jobType: string,\n public readonly concurrencyKey: string,\n public readonly incumbent: JobRun,\n ) {\n super(\n `Job type '${jobType}' has an in-flight run with concurrency_key ` +\n `'${concurrencyKey}' (incumbent ${incumbent.id}); collision_mode=reject.`,\n );\n }\n}\n\n/**\n * `replay` was called on a run that is not in a replayable terminal state\n * (i.e. still `pending` / `running` / `waiting`). Replay always spawns\n * fresh execution and therefore requires the source run to be settled.\n */\nexport class JobNotReplayableError extends Error {\n override readonly name = 'JobNotReplayableError';\n constructor(\n public readonly runId: string,\n public readonly currentStatus: string,\n ) {\n super(\n `Run ${runId} is not replayable from status '${currentStatus}'. ` +\n `Only 'completed', 'failed', 'timed_out', and 'canceled' are eligible.`,\n );\n }\n}\n\n/**\n * A `concurrency_key_template` or `dedupe_key_template` referenced a field\n * that is not present on the input payload. Caught at `start` time so the\n * caller sees the misconfiguration synchronously rather than at claim time.\n */\nexport class JobTemplateFieldMissingError extends Error {\n override readonly name = 'JobTemplateFieldMissingError';\n constructor(\n public readonly template: string,\n public readonly field: string,\n ) {\n super(\n `Template '${template}' references input field '${field}' which is ` +\n `missing or undefined on the payload.`,\n );\n }\n}\n\n/**\n * Thrown by the four multi-tenant-aware service-layer backends (JOB-8)\n * when `JobsDomainModule` was configured with `multiTenant: true` but the\n * caller did not pass a `tenantId` in the relevant options object.\n *\n * **Strict enforcement rationale (resolved 2026-04-18).** Cross-tenant data\n * leakage is the worst class of bug a multi-tenant system can ship; surfacing\n * the misuse loudly at the call site (rather than silently defaulting to\n * `null` or to the \"last tenant seen\") prevents both accidental global\n * writes and sneaky reads that return a union of tenants.\n *\n * - `undefined` `tenantId` → throw this error.\n * - Explicit `null` `tenantId` → passes; opts the call into cross-tenant\n * background work (e.g. a nightly housekeeping job that must scan all\n * tenants). The row is persisted with `tenant_id = NULL`.\n */\nexport class MissingTenantIdError extends Error {\n override readonly name = 'MissingTenantIdError';\n constructor(public readonly method: string) {\n super(\n `MissingTenantIdError: JobsDomainModule was configured with ` +\n `multiTenant=true but ${method} was called without tenantId ` +\n `(undefined). Pass an explicit tenantId, or pass null for ` +\n `cross-tenant work.`,\n );\n }\n}\n\n/**\n * Thrown by `JobWorkerModule.onModuleInit` (Drizzle backend only) when the\n * `job` table contains type rows for which no `@JobHandler` is registered\n * in the running process. Surfaces every orphaned type at once so a single\n * boot tells the operator everything to clean up.\n *\n * Skipped entirely in memory mode (Q4 resolution 2026-04-19) — the memory\n * backend has no DB rows to validate; `MemoryJobOrchestrator.start()`\n * throws `JobTypeNotFoundError` synchronously for unknown types instead.\n */\nexport class BootValidationError extends Error {\n override readonly name = 'BootValidationError';\n constructor(public readonly missingHandlers: string[]) {\n super(\n `BootValidationError: ${missingHandlers.length} orphaned job type(s) ` +\n `in 'job' table with no matching @JobHandler in the running process: ` +\n `[${missingHandlers.join(', ')}]. Either register the handler(s) or ` +\n `remove the rows.`,\n );\n }\n}\n\n/**\n * Thrown by `JobWorkerModule.onModuleInit` when one or more `@JobHandler`\n * classes target a `reserved: true` pool from the resolved pool config\n * (the three `events_*` pools are reserved for the events subsystem\n * outbox drain). Listing every offender on a single boot avoids the\n * fix-one-restart-fix-next loop.\n */\nexport class ReservedPoolViolationError extends Error {\n override readonly name = 'ReservedPoolViolationError';\n constructor(\n public readonly offenders: ReadonlyArray<{\n handlerClass: string;\n pool: string;\n }>,\n ) {\n super(\n `ReservedPoolViolationError: ${offenders.length} @JobHandler(s) target ` +\n `reserved pools — reserved pools are framework-only:\\n` +\n offenders\n .map((o) => ` - ${o.handlerClass} → pool='${o.pool}'`)\n .join('\\n'),\n );\n }\n}\n","/**\n * DrizzleJobRunService — scope-oriented reads and bulk operations against\n * `job_run` (ADR-022, JOB-3).\n *\n * Separate from the orchestrator because the access pattern differs: this\n * service scans by `(scope_entity_type, scope_entity_id)` via\n * `idx_job_run_scope`, whereas orchestrator mutates individual runs by id.\n */\nimport { Inject, Injectable } from '@nestjs/common';\nimport { and, asc, desc, eq, gte, inArray, isNull, lt, or, sql } from 'drizzle-orm';\nimport type { DrizzleClient } from '../../types/drizzle';\nimport { DRIZZLE } from '../../constants/tokens';\nimport { jobRuns, type JobRunRow } from './job-orchestration.schema';\nimport type { JobRun } from './job-orchestrator.protocol';\nimport type {\n IJobRunService,\n ListForScopeOptions,\n CancelForScopeOptions,\n RescheduleForScopeOptions,\n PoolStatusCount,\n JobRunFailure,\n ListJobRunsQuery,\n JobRunPage,\n JobRunSummary,\n} from './job-run-service.protocol';\nimport {\n clampLimit,\n decodeKeysetCursor,\n encodeKeysetCursor,\n toJobRunSummary,\n} from './job-run-keyset-cursor';\nimport type { IJobOrchestrator } from './job-orchestrator.protocol';\nimport { JOB_ORCHESTRATOR, JOBS_MULTI_TENANT } from './jobs-domain.tokens';\nimport { MissingTenantIdError } from './jobs-errors';\n\nconst NON_TERMINAL_STATUSES: JobRunRow['status'][] = [\n 'pending',\n 'running',\n 'waiting',\n];\n\n@Injectable()\nexport class DrizzleJobRunService implements IJobRunService {\n constructor(\n @Inject(DRIZZLE) private readonly db: DrizzleClient,\n @Inject(JOB_ORCHESTRATOR) private readonly orchestrator: IJobOrchestrator,\n @Inject(JOBS_MULTI_TENANT) private readonly multiTenant: boolean,\n ) {}\n\n /**\n * JOB-8 — produce the tenant WHERE fragment (or `null` to opt out).\n * Returns `null` when multi-tenancy is off (caller skips the predicate).\n * Throws `MissingTenantIdError` when on + `undefined`.\n * When on + explicit `null`, filters `tenant_id IS NULL`.\n */\n private tenantCondition(\n method: string,\n tenantId: string | null | undefined,\n ) {\n if (!this.multiTenant) return null;\n if (tenantId === undefined) throw new MissingTenantIdError(method);\n return tenantId === null\n ? isNull(jobRuns.tenantId)\n : eq(jobRuns.tenantId, tenantId);\n }\n\n async listForScope(\n entityType: string,\n entityId: string,\n opts: ListForScopeOptions = {},\n ): Promise<JobRun[]> {\n const conditions = [\n eq(jobRuns.scopeEntityType, entityType),\n eq(jobRuns.scopeEntityId, entityId),\n ];\n const tenantCond = this.tenantCondition('listForScope', opts.tenantId);\n if (tenantCond) conditions.push(tenantCond);\n if (opts.status) {\n if (Array.isArray(opts.status)) {\n conditions.push(inArray(jobRuns.status, opts.status));\n } else {\n conditions.push(eq(jobRuns.status, opts.status));\n }\n }\n if (opts.jobType) {\n conditions.push(eq(jobRuns.jobType, opts.jobType));\n }\n\n const orderCol = (() => {\n switch (opts.orderBy) {\n case 'created_at asc':\n return asc(jobRuns.createdAt);\n case 'run_at desc':\n return desc(jobRuns.runAt);\n case 'run_at asc':\n return asc(jobRuns.runAt);\n case 'created_at desc':\n default:\n return desc(jobRuns.createdAt);\n }\n })();\n\n let q = this.db\n .select()\n .from(jobRuns)\n .where(and(...conditions))\n .orderBy(orderCol)\n .$dynamic();\n\n if (typeof opts.limit === 'number') {\n q = q.limit(opts.limit);\n }\n if (typeof opts.offset === 'number') {\n q = q.offset(opts.offset);\n }\n\n const rows = await q;\n return rows as JobRun[];\n }\n\n async cancelForScope(\n entityType: string,\n entityId: string,\n opts: CancelForScopeOptions = {},\n ): Promise<void> {\n const tenantCond = this.tenantCondition('cancelForScope', opts.tenantId);\n const conditions = [\n eq(jobRuns.scopeEntityType, entityType),\n eq(jobRuns.scopeEntityId, entityId),\n inArray(jobRuns.status, NON_TERMINAL_STATUSES),\n ];\n if (tenantCond) conditions.push(tenantCond);\n\n const rows = await this.db\n .select({ id: jobRuns.id })\n .from(jobRuns)\n .where(and(...conditions));\n\n for (const { id } of rows) {\n // Propagate the tenant gate into cascade-cancel. The scope query has\n // already narrowed to this tenant; passing `tenantId` through keeps\n // the orchestrator's per-row guard consistent under multi-tenant mode.\n await this.orchestrator.cancel(id, {\n cascade: true,\n tenantId: opts.tenantId,\n });\n }\n }\n\n async rescheduleForScope(\n entityType: string,\n entityId: string,\n newRunAt: Date,\n opts: RescheduleForScopeOptions = {},\n ): Promise<void> {\n const tenantCond = this.tenantCondition('rescheduleForScope', opts.tenantId);\n const conditions = [\n eq(jobRuns.scopeEntityType, entityType),\n eq(jobRuns.scopeEntityId, entityId),\n eq(jobRuns.status, 'pending'),\n ];\n if (tenantCond) conditions.push(tenantCond);\n\n await this.db\n .update(jobRuns)\n .set({ runAt: newRunAt, updatedAt: new Date() })\n .where(and(...conditions));\n }\n\n async countByPoolAndStatus(\n tenantId?: string | null,\n ): Promise<PoolStatusCount[]> {\n const tenantCond = this.tenantCondition('countByPoolAndStatus', tenantId);\n const rows = await this.db\n .select({\n pool: jobRuns.pool,\n status: jobRuns.status,\n count: sql<number>`count(*)::int`.as('count'),\n })\n .from(jobRuns)\n .where(tenantCond ?? undefined)\n .groupBy(jobRuns.pool, jobRuns.status);\n\n return rows.map((r) => ({\n pool: r.pool,\n status: r.status,\n count: Number(r.count),\n }));\n }\n\n async listRecentFailed(\n limit: number,\n tenantId?: string | null,\n ): Promise<JobRunFailure[]> {\n const conditions = [eq(jobRuns.status, 'failed' as const)];\n const tenantCond = this.tenantCondition('listRecentFailed', tenantId);\n if (tenantCond) conditions.push(tenantCond);\n\n const rows = await this.db\n .select()\n .from(jobRuns)\n .where(and(...conditions))\n .orderBy(desc(jobRuns.finishedAt), desc(jobRuns.updatedAt))\n .limit(limit);\n\n return rows.map((r) => ({\n runId: r.id,\n jobType: r.jobType,\n pool: r.pool,\n scopeEntityType: r.scopeEntityType,\n scopeEntityId: r.scopeEntityId,\n tenantId: r.tenantId,\n attempts: r.attempts,\n errorMessage: r.error?.message ?? null,\n failedAt: r.finishedAt ?? r.updatedAt,\n createdAt: r.createdAt,\n }));\n }\n\n async listJobRuns(query: ListJobRunsQuery = {}): Promise<JobRunPage> {\n const limit = clampLimit(query.limit);\n const conditions = [];\n\n const tenantCond = this.tenantCondition('listJobRuns', query.tenantId);\n if (tenantCond) conditions.push(tenantCond);\n if (query.poolId) conditions.push(eq(jobRuns.pool, query.poolId));\n if (query.rootRunId) conditions.push(eq(jobRuns.rootRunId, query.rootRunId));\n if (query.status) conditions.push(eq(jobRuns.status, query.status));\n if (query.since) conditions.push(gte(jobRuns.createdAt, query.since));\n\n // Keyset seek: WHERE (created_at, id) < (cursorCreatedAt, cursorId),\n // expanded into a SARGable OR so the same `created_at` index is used.\n if (query.cursor) {\n const keyset = decodeKeysetCursor(query.cursor);\n if (keyset) {\n conditions.push(\n or(\n lt(jobRuns.createdAt, keyset.createdAt),\n and(\n eq(jobRuns.createdAt, keyset.createdAt),\n lt(jobRuns.id, keyset.id),\n ),\n )!,\n );\n }\n }\n\n // Fetch one extra row to determine whether a next page exists without a\n // separate COUNT.\n const rows = await this.db\n .select()\n .from(jobRuns)\n .where(conditions.length > 0 ? and(...conditions) : undefined)\n .orderBy(desc(jobRuns.createdAt), desc(jobRuns.id))\n .limit(limit + 1);\n\n const hasMore = rows.length > limit;\n const page = hasMore ? rows.slice(0, limit) : rows;\n const items = page.map(toJobRunSummary);\n const last = page[page.length - 1];\n const nextCursor =\n hasMore && last\n ? encodeKeysetCursor({ createdAt: last.createdAt, id: last.id })\n : null;\n\n return { items, nextCursor };\n }\n\n /**\n * Internal helper used by cascade paths (not on the public protocol).\n * Exposed as a public method on the concrete class so infrastructure\n * code (cascade tests, debug tools) can call it without a cast.\n */\n async findByRootRunId(rootRunId: string): Promise<JobRun[]> {\n const rows = await this.db\n .select()\n .from(jobRuns)\n .where(eq(jobRuns.rootRunId, rootRunId));\n return rows as JobRun[];\n }\n}\n","/**\n * Keyset (seek) cursor codec for `IJobRunService.listJobRuns` (OBS-LIST-1).\n *\n * The list is ordered `created_at DESC, id DESC`. The cursor encodes the\n * `(createdAt, id)` of the last row on the previous page so the next page\n * can seek with `WHERE (created_at, id) < (cursorCreatedAt, cursorId)`\n * rather than an `OFFSET`. Keyset pagination stays O(log n) on deep pages\n * and is stable as new rows arrive at the head.\n *\n * The cursor is opaque to consumers: a base64url-encoded JSON tuple. Shape\n * is an implementation detail — never parse it outside this module.\n *\n * Also hosts `toJobRunSummary`, the single `JobRunRow → JobRunSummary`\n * projection shared by both backends so the narrow shape stays in sync.\n */\nimport type { JobRunRow } from './job-orchestration.schema';\nimport type { JobRunSummary } from './job-run-service.protocol';\n\nexport interface JobRunKeyset {\n /** `created_at` of the last row on the previous page. */\n createdAt: Date;\n /** `id` (UUID) tie-break of the last row on the previous page. */\n id: string;\n}\n\n/** Default page size when `limit` is omitted. */\nexport const DEFAULT_LIST_LIMIT = 50;\n/** Hard upper bound on page size to keep a single read bounded. */\nexport const MAX_LIST_LIMIT = 200;\n\n/** Clamp a caller-supplied `limit` into `[1, MAX_LIST_LIMIT]`. */\nexport function clampLimit(limit: number | undefined): number {\n if (typeof limit !== 'number' || !Number.isFinite(limit)) {\n return DEFAULT_LIST_LIMIT;\n }\n const floored = Math.floor(limit);\n if (floored < 1) return 1;\n if (floored > MAX_LIST_LIMIT) return MAX_LIST_LIMIT;\n return floored;\n}\n\nexport function encodeKeysetCursor(keyset: JobRunKeyset): string {\n const tuple = [keyset.createdAt.toISOString(), keyset.id];\n return Buffer.from(JSON.stringify(tuple), 'utf8').toString('base64url');\n}\n\n/**\n * Decode an opaque cursor back into its `(createdAt, id)` keyset. Returns\n * `null` for a malformed cursor so callers can treat garbage input as\n * \"start from the beginning\" rather than throwing on user-supplied data.\n */\nexport function decodeKeysetCursor(cursor: string): JobRunKeyset | null {\n try {\n const json = Buffer.from(cursor, 'base64url').toString('utf8');\n const parsed = JSON.parse(json) as unknown;\n if (!Array.isArray(parsed) || parsed.length !== 2) return null;\n const [iso, id] = parsed;\n if (typeof iso !== 'string' || typeof id !== 'string') return null;\n const createdAt = new Date(iso);\n if (Number.isNaN(createdAt.getTime())) return null;\n return { createdAt, id };\n } catch {\n return null;\n }\n}\n\n/**\n * Project a raw `job_run` row into the narrow `JobRunSummary` shape exposed\n * by `listJobRuns`. `errorMessage` is pulled from the jsonb `error.message`.\n */\nexport function toJobRunSummary(r: JobRunRow): JobRunSummary {\n return {\n runId: r.id,\n rootRunId: r.rootRunId,\n parentRunId: r.parentRunId,\n triggerSource: r.triggerSource,\n triggerRef: r.triggerRef,\n jobType: r.jobType,\n pool: r.pool,\n status: r.status,\n scopeEntityType: r.scopeEntityType,\n scopeEntityId: r.scopeEntityId,\n tenantId: r.tenantId,\n attempts: r.attempts,\n errorMessage: r.error?.message ?? null,\n runAt: r.runAt,\n startedAt: r.startedAt,\n finishedAt: r.finishedAt,\n createdAt: r.createdAt,\n };\n}\n","/**\n * DrizzleJobStepService — upsert + lookup on `job_step` for replay-safe\n * memoization (ADR-022, JOB-3).\n *\n * `recordStep` upserts on the `(job_run_id, step_id)` unique index — each\n * step row is written as `running` first, then transitioned to a terminal\n * state (`completed` / `failed` / `skipped`). `findStep` is the hot path\n * that `ctx.step()` consults on every invocation; null on miss.\n */\nimport { Inject, Injectable } from '@nestjs/common';\nimport { and, eq } from 'drizzle-orm';\nimport type { DrizzleClient } from '../../types/drizzle';\nimport { DRIZZLE } from '../../constants/tokens';\nimport { jobSteps, type JobStepRow } from './job-orchestration.schema';\nimport type {\n IJobStepService,\n JobStep,\n RecordStepInput,\n} from './job-step-service.protocol';\n\n@Injectable()\nexport class DrizzleJobStepService implements IJobStepService {\n constructor(@Inject(DRIZZLE) private readonly db: DrizzleClient) {}\n\n async recordStep(input: RecordStepInput): Promise<JobStep> {\n const values = {\n jobRunId: input.jobRunId,\n stepId: input.stepId,\n kind: input.kind,\n seq: input.seq,\n status: input.status,\n input: (input.input ?? null) as Record<string, unknown> | null,\n output: (input.output ?? null) as Record<string, unknown> | null,\n error: input.error ?? null,\n attempts: input.attempts ?? 0,\n startedAt: input.startedAt ?? null,\n finishedAt: input.finishedAt ?? null,\n };\n\n const [row] = await this.db\n .insert(jobSteps)\n .values(values)\n .onConflictDoUpdate({\n target: [jobSteps.jobRunId, jobSteps.stepId],\n set: {\n status: values.status,\n output: values.output,\n error: values.error,\n finishedAt: values.finishedAt,\n attempts: values.attempts,\n },\n })\n .returning();\n\n return row as JobStep;\n }\n\n async findStep(runId: string, stepId: string): Promise<JobStep | null> {\n const [row] = await this.db\n .select()\n .from(jobSteps)\n .where(and(eq(jobSteps.jobRunId, runId), eq(jobSteps.stepId, stepId)))\n .limit(1);\n return ((row as JobStepRow | undefined) ?? null) as JobStep | null;\n }\n}\n","/**\n * Pool config loader for the job orchestration domain (ADR-022, JOB-5).\n *\n * Reads `codegen.config.yaml: jobs.pools` from `process.cwd()` (or an\n * explicit `configPath` for tests), merges user-defined pools onto the five\n * framework defaults, and returns the resolved `Map<string, PoolDefinition>`\n * consumed by `JobWorkerModule.onModuleInit` and `JobsDomainModule`'s\n * config-validator surface.\n *\n * Invariants:\n * - User cannot flip `reserved: true` on a framework pool — silently\n * preserved. The three `events_*` pools are reserved infrastructure\n * for the events outbox drain.\n * - User-defined pools cannot set `reserved: true` — `reserved` is\n * framework-only metadata.\n * - Missing `codegen.config.yaml` is not an error; loader returns the\n * framework defaults verbatim.\n *\n * Result is cached at module scope after first call so repeated reads (e.g.\n * a worker module + a one-off scaffold validator in the same process) hit\n * the same parse. Tests that pass `configPath` skip the cache and isolate.\n */\nimport { existsSync, readFileSync } from 'node:fs';\nimport { resolve } from 'node:path';\nimport { parse as parseYaml } from 'yaml';\n\nexport interface PoolDefinition {\n /** Routing identifier — reused as the per-pool worker queue name. */\n queue: string;\n /** Max parallel in-flight `processRun` calls for this pool's worker. */\n concurrency: number;\n /** `true` ⇒ user `@JobHandler` may not target it. Framework-only. */\n reserved: boolean;\n /** Free-text annotation surfaced in admin UIs / logs. */\n description?: string;\n}\n\nexport type PoolConfig = Map<string, PoolDefinition>;\n\n/**\n * Five framework defaults. Three reserved `events_*` pools drain the\n * `IEventBus` outbox (one per `DomainEvent.direction`); `interactive` and\n * `batch` are user-default pools (`batch` is the `@JobHandler` default\n * when no `pool` is specified).\n */\nexport const FRAMEWORK_POOLS: Readonly<Record<string, PoolDefinition>> = Object.freeze({\n events_inbound: Object.freeze({\n queue: 'jobs-events-inbound',\n concurrency: 20,\n reserved: true,\n description: 'Inbound events drain (events subsystem outbox).',\n }),\n events_change: Object.freeze({\n queue: 'jobs-events-change',\n concurrency: 30,\n reserved: true,\n description: 'Change events drain (events subsystem outbox).',\n }),\n events_outbound: Object.freeze({\n queue: 'jobs-events-outbound',\n concurrency: 10,\n reserved: true,\n description: 'Outbound events drain (events subsystem outbox).',\n }),\n interactive: Object.freeze({\n queue: 'jobs-interactive',\n concurrency: 20,\n reserved: false,\n description: 'User-facing latency-sensitive jobs.',\n }),\n batch: Object.freeze({\n queue: 'jobs-batch',\n concurrency: 5,\n reserved: false,\n description: 'Default pool for background jobs.',\n }),\n});\n\n/** Names of the framework reserved pools. Cheap inline lookup for the worker. */\nexport const RESERVED_POOL_NAMES: ReadonlySet<string> = new Set(\n Object.entries(FRAMEWORK_POOLS)\n .filter(([, def]) => def.reserved)\n .map(([name]) => name),\n);\n\n/**\n * Cache by absolute config path. The `cwd` default is normalised before\n * lookup so two callers passing the same path share the cache; explicit\n * test-only paths cache separately.\n */\nconst cache = new Map<string, PoolConfig>();\n\n/**\n * Reset the loader cache. Test-only — not exported from the package\n * `index.ts`. Useful for tests that mutate `process.cwd()` between cases.\n */\nexport function _resetPoolConfigCacheForTests(): void {\n cache.clear();\n}\n\n/**\n * Resolve the merged pool config.\n *\n * @param configPath optional absolute or cwd-relative path; defaults to\n * `${process.cwd()}/codegen.config.yaml`.\n */\nexport function loadPoolConfig(configPath?: string): PoolConfig {\n const resolved = resolve(configPath ?? `${process.cwd()}/codegen.config.yaml`);\n const cached = cache.get(resolved);\n if (cached) return cached;\n\n const merged = new Map<string, PoolDefinition>();\n // Seed with framework defaults first — they always take precedence on\n // `reserved` and provide defaults for `queue` / `concurrency` if user\n // overrides only some fields.\n for (const [name, def] of Object.entries(FRAMEWORK_POOLS)) {\n merged.set(name, { ...def });\n }\n\n if (!existsSync(resolved)) {\n cache.set(resolved, merged);\n return merged;\n }\n\n let raw: unknown;\n try {\n raw = parseYaml(readFileSync(resolved, 'utf8'));\n } catch (err) {\n throw new Error(\n `pool-config.loader: failed to parse YAML at ${resolved}: ${(err as Error).message}`,\n );\n }\n\n const userPools = extractUserPools(raw);\n for (const [name, userDef] of Object.entries(userPools)) {\n const existing = merged.get(name);\n if (existing) {\n // Framework pool — user may tweak concurrency + description but\n // cannot flip `reserved`. `queue` is frozen too (reserved framework\n // pools' queue identifiers are part of the cross-subsystem contract\n // with the events outbox drain).\n const next: PoolDefinition = {\n queue: existing.queue,\n concurrency:\n typeof userDef.concurrency === 'number'\n ? userDef.concurrency\n : existing.concurrency,\n reserved: existing.reserved,\n description: userDef.description ?? existing.description,\n };\n merged.set(name, next);\n continue;\n }\n // User-defined pool. Validate required fields; reject reserved.\n if (typeof userDef.queue !== 'string' || userDef.queue.length === 0) {\n throw new Error(\n `pool-config.loader: pool '${name}' must declare a non-empty 'queue'.`,\n );\n }\n if (typeof userDef.concurrency !== 'number' || userDef.concurrency <= 0) {\n throw new Error(\n `pool-config.loader: pool '${name}' must declare a positive 'concurrency'.`,\n );\n }\n if (userDef.reserved === true) {\n throw new Error(\n `pool-config.loader: user-defined pool '${name}' cannot set ` +\n `'reserved: true' — reserved is framework-only.`,\n );\n }\n merged.set(name, {\n queue: userDef.queue,\n concurrency: userDef.concurrency,\n reserved: false,\n description: userDef.description,\n });\n }\n\n cache.set(resolved, merged);\n return merged;\n}\n\n/**\n * Names of every non-reserved pool in the resolved config. The default\n * worker activation set when `JobWorkerModuleOptions.pools` is omitted —\n * the worker process never claims the reserved `events_*` pools by\n * default; those are bound by the events subsystem's outbox bridge.\n */\nexport function allNonReservedPoolNames(config: PoolConfig): string[] {\n const out: string[] = [];\n for (const [name, def] of config) {\n if (!def.reserved) out.push(name);\n }\n return out;\n}\n\n/**\n * Names of **every** pool in the resolved config, reserved `events_*` lanes\n * included. The activation set for a standalone worker booted with\n * `JobWorkerModule.forRoot({ allPools: true })` (BULLMQ-1 Phase 1) — the\n * single worker process drains both user pools and the bridge's reserved\n * pools so wrapper `job_run` rows are never stranded.\n */\nexport function allPoolNames(config: PoolConfig): string[] {\n return [...config.keys()];\n}\n\n// ─── internals ──────────────────────────────────────────────────────────────\n\ninterface UserPoolShape {\n queue?: string;\n concurrency?: number;\n reserved?: boolean;\n description?: string;\n}\n\nfunction extractUserPools(raw: unknown): Record<string, UserPoolShape> {\n if (!raw || typeof raw !== 'object') return {};\n const jobs = (raw as { jobs?: unknown }).jobs;\n if (!jobs || typeof jobs !== 'object') return {};\n const pools = (jobs as { pools?: unknown }).pools;\n if (!pools || typeof pools !== 'object') return {};\n const out: Record<string, UserPoolShape> = {};\n for (const [name, def] of Object.entries(pools as Record<string, unknown>)) {\n if (!def || typeof def !== 'object') continue;\n out[name] = def as UserPoolShape;\n }\n return out;\n}\n","/**\n * BullMQ backend configuration surface (BULLMQ-1, ADR-022 extension slot).\n *\n * The core `IJobOrchestrator` contract is backend-agnostic; everything in\n * this file is BullMQ-specific and lives behind the\n * `jobs.extensions.bullmq.*` config namespace (CLAUDE.md core/extension\n * protocol). The Drizzle backend never reads any of it.\n */\nimport { tokenKey } from '../token-key';\nimport { loadPoolConfig, type PoolConfig } from './pool-config.loader';\n\n/**\n * #6 — Structural mirror of BullMQ's `ConnectionOptions`. Declared locally\n * so this config file (which ships into EVERY jobs install, drizzle or\n * bullmq) does NOT need the `bullmq` peer dep resolved by the consumer's\n * tsc. The bullmq backend internally casts to the real `ConnectionOptions`\n * — that file is only vendored when `--backend bullmq` is selected\n * (see `backendFileFilter`).\n *\n * Accepts the `{ url }` shape this resolver emits, plus the host/port/\n * password/db form BullMQ also accepts, with an open index for any extra\n * ioredis options consumers may flow through.\n */\nexport type BullMqConnectionOptions = {\n url?: string;\n host?: string;\n port?: number;\n password?: string;\n db?: number;\n [key: string]: unknown;\n};\n\n/**\n * Typed shape of `codegen.config.yaml: jobs.extensions.bullmq`. Snake_case\n * because it mirrors the YAML the consumer authors.\n *\n * ```yaml\n * jobs:\n * backend: bullmq\n * extensions:\n * bullmq:\n * redis_url: redis://localhost:6379 # or env REDIS_URL\n * queue_prefix: myapp # optional namespace (ADR-022 OQ)\n * bull_board:\n * enabled: true\n * mount_path: /api/admin/queues\n * ```\n */\nexport interface BullMqExtensionsConfig {\n /**\n * Redis/Valkey connection URL. When omitted, the runtime resolves\n * `process.env.REDIS_URL`, then falls back to `redis://localhost:6379`.\n */\n redis_url?: string;\n /**\n * Optional queue-name prefix to avoid collisions when several codegen apps\n * share one Redis (ADR-022 §\"BullMQ queue naming collisions\"). Applied to\n * every pool queue alias.\n */\n queue_prefix?: string;\n /**\n * Bull Board dashboard — opt-in extension (not core). Mounting is the\n * consumer's responsibility (it needs the consumer's Express/Nest adapter +\n * admin auth); we only carry the config. See README + spec §Extensions.\n */\n bull_board?: {\n enabled: boolean;\n mount_path?: string;\n };\n}\n\n/**\n * The runtime form after `redis_url`/env resolution. This is what the\n * orchestrator + worker actually consume.\n */\nexport interface BullMqResolvedConfig {\n connection: BullMqConnectionOptions;\n queuePrefix?: string;\n bullBoard?: { enabled: boolean; mountPath: string };\n}\n\n// ADR-037: namespaced `Symbol.for(...)` (via `tokenKey()`) — matches by value\n// across runtime copies.\n/** DI token for the resolved BullMQ `ConnectionOptions` (ioredis-compatible). */\nexport const BULLMQ_CONNECTION = Symbol.for(tokenKey('jobs', 'bullmq-connection'));\n\n/** DI token for the full resolved BullMQ config (prefix + bull board). */\nexport const BULLMQ_RESOLVED_CONFIG = Symbol.for(tokenKey('jobs', 'bullmq-resolved-config'));\n\nconst DEFAULT_REDIS_URL = 'redis://localhost:6379';\nconst DEFAULT_BULL_BOARD_MOUNT = '/admin/queues';\n\n/**\n * Resolve the BullMQ runtime config from the extension block.\n *\n * Precedence for the connection URL:\n * 1. explicit `extensions.bullmq.redis_url`\n * 2. `process.env.REDIS_URL`\n * 3. `redis://localhost:6379`\n *\n * Returns a `{ url }` connection shape — BullMQ/ioredis accept a URL string\n * via the `{ url }` ConnectionOptions form.\n */\nexport function resolveBullMqConfig(\n ext: BullMqExtensionsConfig | undefined,\n): BullMqResolvedConfig {\n const url =\n ext?.redis_url ?? process.env.REDIS_URL ?? DEFAULT_REDIS_URL;\n\n const resolved: BullMqResolvedConfig = {\n connection: { url },\n queuePrefix: ext?.queue_prefix,\n };\n if (ext?.bull_board?.enabled) {\n resolved.bullBoard = {\n enabled: true,\n mountPath: ext.bull_board.mount_path ?? DEFAULT_BULL_BOARD_MOUNT,\n };\n }\n return resolved;\n}\n\n/**\n * Resolve the BullMQ queue name for a *logical pool name*. The orchestrator\n * and worker MUST agree on this mapping or jobs are enqueued onto a queue\n * nobody consumes. Both derive it identically:\n *\n * 1. Look up the pool's `queue` alias (e.g. `jobs-batch`) in the resolved\n * pool config — the same alias `JobWorkerModule.onModuleInit` logs and\n * that the BullMQ `Worker` binds to.\n * 2. Fall back to the logical pool name when the pool is unknown (defensive;\n * still a stable, colon-free identifier).\n * 3. Apply the optional `queue_prefix` namespace for multi-app Redis\n * sharing — `:` is fine in the *queue name* (it is only forbidden in the\n * `jobId`, hence the sha1 there).\n *\n * `poolConfig` defaults to the cached `loadPoolConfig()` so callers that only\n * hold the logical pool name (the orchestrator) don't need to thread the map.\n */\nexport function resolvePoolQueueName(\n pool: string,\n config: BullMqResolvedConfig | null | undefined,\n poolConfig: PoolConfig = loadPoolConfig(),\n): string {\n const alias = poolConfig.get(pool)?.queue ?? pool;\n const prefix = config?.queuePrefix;\n return prefix ? `${prefix}:${alias}` : alias;\n}\n","/**\n * JobWorker — backend-agnostic tick loop for the job orchestration domain\n * (ADR-022, JOB-3).\n *\n * One worker instance per active pool. On `onModuleInit` it starts two\n * intervals: the poll loop (claim → process → repeat) and the stale-claim\n * sweeper. On `onModuleDestroy` / SIGTERM it drains in-flight work and\n * releases still-`running` rows back to `pending` so a replacement worker\n * can resume with step memoization intact.\n *\n * The claim query is the beating heart: `SELECT … FOR UPDATE SKIP LOCKED`\n * inside a single transaction. Multiple worker processes share the table\n * without serialising on row locks.\n */\n// TODO(logging-subsystem): swap to ILogger once ADR-028 lands\nimport { Inject, Injectable, Logger, type OnModuleDestroy, type OnModuleInit } from '@nestjs/common';\nimport { ModuleRef } from '@nestjs/core';\nimport { and, asc, desc, eq, inArray, lt, lte, sql } from 'drizzle-orm';\nimport type { DrizzleClient } from '../../types/drizzle';\nimport { tokenKey } from '../token-key';\nimport { DRIZZLE } from '../../constants/tokens';\nimport { jobRuns, type JobRunRow } from './job-orchestration.schema';\nimport type { IJobOrchestrator, JobRun } from './job-orchestrator.protocol';\nimport type { IJobRunService } from './job-run-service.protocol';\nimport type { IJobStepService } from './job-step-service.protocol';\nimport {\n JOB_ORCHESTRATOR,\n JOB_RUN_SERVICE,\n JOB_STEP_SERVICE,\n} from './jobs-domain.tokens';\nimport {\n JOB_HANDLER_REGISTRY,\n JobHandlerBase,\n type JobContext,\n type JobHandlerMeta,\n type RetryPolicy,\n type SpawnChildOptions,\n type StepOptions,\n} from './job-handler.base';\n\n/**\n * Options accepted by `JobWorker`. JOB-5 threads these through module\n * `.forRoot()` config; supplied here as a plain DI-constructor argument\n * so the worker compiles standalone.\n */\nexport interface JobWorkerOptions {\n /** Pool name this worker claims from. Matches `job.pool`. */\n pool: string;\n /** Max concurrent in-flight `processRun` calls. */\n concurrency: number;\n /** Poll interval in ms. Default 1000. */\n pollIntervalMs?: number;\n /** Stale sweep interval in ms. Default 60_000. */\n staleSweeperIntervalMs?: number;\n /**\n * Threshold beyond which a `running` row is presumed stranded by a\n * crashed worker. Default 5 min. Must be >= 2× max handler duration.\n */\n staleThresholdMs?: number;\n /** Max ms to wait for in-flight drain on SIGTERM. Default 30_000. */\n shutdownTimeoutMs?: number;\n}\n\n// ADR-037: namespaced `Symbol.for(...)` (via `tokenKey()`) — matches by value\n// across runtime copies.\nexport const JOB_WORKER_OPTIONS = Symbol.for(tokenKey('jobs', 'worker-options'));\n\nconst DEFAULT_POLL_INTERVAL_MS = 1_000;\nconst DEFAULT_STALE_SWEEPER_INTERVAL_MS = 60_000;\nconst DEFAULT_STALE_THRESHOLD_MS = 5 * 60_000;\nconst DEFAULT_SHUTDOWN_TIMEOUT_MS = 30_000;\n\nconst TERMINAL_STATUSES: JobRunRow['status'][] = [\n 'completed',\n 'failed',\n 'timed_out',\n 'canceled',\n];\n\n// ─── Pure helpers (exported for unit tests) ────────────────────────────────\n\n/**\n * Backoff delay in ms for the Nth attempt (1-indexed). Supports both\n * policy modes. Exponential is capped at `Number.MAX_SAFE_INTEGER` so\n * pathological attempt counts don't overflow.\n */\nexport function computeBackoff(policy: RetryPolicy, attempts: number): number {\n const base = Math.max(policy.baseMs, 0);\n if (policy.backoff === 'fixed') {\n return base;\n }\n // exponential: baseMs * 2^(attempts-1)\n const exponent = Math.max(attempts - 1, 0);\n if (exponent >= 53) return Number.MAX_SAFE_INTEGER; // 2^53 overflow guard\n const raw = base * Math.pow(2, exponent);\n if (!Number.isFinite(raw) || raw >= Number.MAX_SAFE_INTEGER) {\n return Number.MAX_SAFE_INTEGER;\n }\n return raw;\n}\n\n/**\n * Decide whether an error should be retried under the given policy.\n * Matches `nonRetryableErrors` by `.name` OR `.code`. Returns\n * - `'retry'` if attempts remain and the error isn't blacklisted,\n * - `'fail'` otherwise (terminal failure).\n */\nexport function classifyError(\n err: unknown,\n policy: RetryPolicy | undefined,\n currentAttempts: number,\n): 'retry' | 'fail' {\n if (!policy) return 'fail';\n const errObj = err as { name?: string; code?: string } | undefined;\n const name = errObj?.name;\n const code = errObj?.code;\n const nonRetryable = policy.nonRetryableErrors ?? [];\n if (nonRetryable.some((n) => n === name || n === code)) return 'fail';\n if (currentAttempts + 1 >= policy.attempts) return 'fail';\n return 'retry';\n}\n\n/**\n * Build the raw claim-candidate select. Exported so tests can inspect\n * `.toSQL()` without spinning up the full worker. Matches JOB-3 §4 and\n * ADR-022 \"Claim query (Drizzle backend)\".\n */\nexport function buildClaimQuery(db: DrizzleClient, pool: string) {\n return db\n .select({ id: jobRuns.id })\n .from(jobRuns)\n .where(\n and(\n eq(jobRuns.status, 'pending'),\n eq(jobRuns.pool, pool),\n lte(jobRuns.runAt, new Date()),\n ),\n )\n .orderBy(desc(jobRuns.priority), asc(jobRuns.runAt))\n .limit(1)\n .for('update', { skipLocked: true });\n}\n\n/**\n * Build the stale-claim sweep candidate select. `FOR UPDATE SKIP LOCKED`\n * per OQ-2 resolution (2026-04-19): per-worker sweeper, safe without\n * leader election because the update is self-gating.\n */\nexport function buildStaleSweepQuery(\n db: DrizzleClient,\n staleThresholdMs: number,\n) {\n const threshold = new Date(Date.now() - staleThresholdMs);\n return db\n .select({ id: jobRuns.id })\n .from(jobRuns)\n .where(\n and(\n eq(jobRuns.status, 'running'),\n lt(jobRuns.claimedAt, threshold),\n ),\n )\n .for('update', { skipLocked: true });\n}\n\n// ─── Error serialisation ───────────────────────────────────────────────────\n\nfunction serialiseError(err: unknown, attempt: number, retryable: boolean) {\n const e = err as { message?: string; stack?: string; code?: string } | undefined;\n return {\n message: (e?.message ?? String(err)) as string,\n stack: e?.stack,\n retryable,\n attempt,\n };\n}\n\n// ─── JobWorker ─────────────────────────────────────────────────────────────\n\n@Injectable()\nexport class JobWorker implements OnModuleInit, OnModuleDestroy {\n private readonly logger = new Logger(JobWorker.name);\n private shuttingDown = false;\n private readonly inFlight = new Set<Promise<void>>();\n private pollTimer: ReturnType<typeof setInterval> | null = null;\n private sweeperTimer: ReturnType<typeof setInterval> | null = null;\n private sigtermHandled = false;\n private readonly sigtermHandler: () => void;\n\n private readonly pollIntervalMs: number;\n private readonly staleSweeperIntervalMs: number;\n private readonly staleThresholdMs: number;\n private readonly shutdownTimeoutMs: number;\n\n constructor(\n @Inject(DRIZZLE) private readonly db: DrizzleClient,\n @Inject(JOB_ORCHESTRATOR) private readonly orchestrator: IJobOrchestrator,\n @Inject(JOB_RUN_SERVICE) private readonly runService: IJobRunService,\n @Inject(JOB_STEP_SERVICE) private readonly stepService: IJobStepService,\n @Inject(JOB_WORKER_OPTIONS) private readonly options: JobWorkerOptions,\n private readonly moduleRef: ModuleRef,\n ) {\n this.pollIntervalMs = options.pollIntervalMs ?? DEFAULT_POLL_INTERVAL_MS;\n this.staleSweeperIntervalMs =\n options.staleSweeperIntervalMs ?? DEFAULT_STALE_SWEEPER_INTERVAL_MS;\n this.staleThresholdMs = options.staleThresholdMs ?? DEFAULT_STALE_THRESHOLD_MS;\n this.shutdownTimeoutMs =\n options.shutdownTimeoutMs ?? DEFAULT_SHUTDOWN_TIMEOUT_MS;\n\n this.sigtermHandler = () => {\n if (this.sigtermHandled) return;\n this.sigtermHandled = true;\n void this.onModuleDestroy();\n };\n void this.runService; // reserved for future scope-aware cancellation paths\n }\n\n // ============================================================================\n // Lifecycle\n // ============================================================================\n\n onModuleInit(): void {\n this.pollTimer = setInterval(() => {\n void this.pollAndProcess();\n }, this.pollIntervalMs);\n this.sweeperTimer = setInterval(() => {\n void this.sweepStaleClaims();\n }, this.staleSweeperIntervalMs);\n process.on('SIGTERM', this.sigtermHandler);\n }\n\n async onModuleDestroy(): Promise<void> {\n if (this.shuttingDown) {\n // Still drain, but don't tear intervals down twice.\n await this.drainInFlight();\n return;\n }\n this.shuttingDown = true;\n if (this.pollTimer) {\n clearInterval(this.pollTimer);\n this.pollTimer = null;\n }\n if (this.sweeperTimer) {\n clearInterval(this.sweeperTimer);\n this.sweeperTimer = null;\n }\n process.removeListener('SIGTERM', this.sigtermHandler);\n\n await this.drainInFlight();\n\n // Any rows still `running` past timeout → release back to pending.\n try {\n await this.db\n .update(jobRuns)\n .set({ status: 'pending', claimedAt: null, startedAt: null })\n .where(\n and(eq(jobRuns.status, 'running'), eq(jobRuns.pool, this.options.pool)),\n );\n } catch (err) {\n this.logger.error(`shutdown reset failed: ${(err as Error).message}`);\n }\n }\n\n private async drainInFlight(): Promise<void> {\n if (this.inFlight.size === 0) return;\n const timeout = new Promise<void>((resolve) =>\n setTimeout(resolve, this.shutdownTimeoutMs),\n );\n await Promise.race([\n Promise.allSettled([...this.inFlight]).then(() => undefined),\n timeout,\n ]);\n }\n\n // ============================================================================\n // Poll loop\n // ============================================================================\n\n async pollAndProcess(): Promise<void> {\n if (this.shuttingDown) return;\n if (this.inFlight.size >= this.options.concurrency) return;\n\n let claimed: JobRunRow | null;\n try {\n claimed = await this.claimNext(this.options.pool);\n } catch (err) {\n this.logger.error(`claimNext failed: ${(err as Error).message}`);\n return;\n }\n if (!claimed) return;\n\n const run = claimed;\n const promise = this.processRun(run).catch((err) => {\n this.logger.error(\n `processRun(${run.id}) unhandled: ${(err as Error).message}`,\n );\n });\n this.inFlight.add(promise);\n promise.finally(() => {\n this.inFlight.delete(promise);\n });\n }\n\n /**\n * Claim the next runnable row from the pool. Transaction ensures the\n * select-candidate + update-to-running pair is atomic; FOR UPDATE SKIP\n * LOCKED lets multiple workers share the table without serialising.\n */\n async claimNext(pool: string): Promise<JobRunRow | null> {\n return this.db.transaction(async (tx) => {\n const candidates = await tx\n .select({ id: jobRuns.id })\n .from(jobRuns)\n .where(\n and(\n eq(jobRuns.status, 'pending'),\n eq(jobRuns.pool, pool),\n lte(jobRuns.runAt, new Date()),\n ),\n )\n .orderBy(desc(jobRuns.priority), asc(jobRuns.runAt))\n .limit(1)\n .for('update', { skipLocked: true });\n const candidate = candidates[0];\n if (!candidate) return null;\n\n const [claimed] = await tx\n .update(jobRuns)\n .set({\n status: 'running',\n claimedAt: new Date(),\n startedAt: new Date(),\n updatedAt: new Date(),\n })\n .where(eq(jobRuns.id, candidate.id))\n .returning();\n return (claimed ?? null) as JobRunRow | null;\n });\n }\n\n // ============================================================================\n // Stale claim sweeper\n // ============================================================================\n\n /**\n * Release rows whose `claimed_at` is older than the threshold. Safe to\n * run concurrently across workers — the two-phase tx (select-for-update\n * then update) guarantees each stranded row is only reset once.\n */\n async sweepStaleClaims(): Promise<void> {\n if (this.shuttingDown) return;\n try {\n await this.db.transaction(async (tx) => {\n const threshold = new Date(Date.now() - this.staleThresholdMs);\n const stale = await tx\n .select({ id: jobRuns.id })\n .from(jobRuns)\n .where(\n and(eq(jobRuns.status, 'running'), lt(jobRuns.claimedAt, threshold)),\n )\n .for('update', { skipLocked: true });\n if (stale.length === 0) return;\n const ids = stale.map((r) => r.id);\n await tx\n .update(jobRuns)\n .set({ status: 'pending', claimedAt: null, startedAt: null })\n .where(inArray(jobRuns.id, ids));\n for (const id of ids) {\n this.logger.warn(`Recovered stale claim on run ${id}`);\n }\n });\n } catch (err) {\n this.logger.error(`sweepStaleClaims failed: ${(err as Error).message}`);\n }\n }\n\n // ============================================================================\n // processRun\n // ============================================================================\n\n private async processRun(claimed: JobRunRow): Promise<void> {\n const registryEntry = JOB_HANDLER_REGISTRY.get(claimed.jobType);\n\n // (a) Missing handler — defensive; JOB-5 boot validator should have caught.\n if (!registryEntry) {\n this.logger.error(\n `No handler registered for jobType='${claimed.jobType}' (run ${claimed.id})`,\n );\n await this.markFailed(\n claimed,\n new Error(`No handler registered for jobType='${claimed.jobType}'`),\n /*finalAttempts*/ (claimed.attempts ?? 0) + 1,\n );\n return;\n }\n\n // (b) Concurrency-queue release gate — defer if another run with the\n // same key is already `running`.\n if (claimed.concurrencyKey) {\n const inflight = await this.db\n .select({ id: jobRuns.id })\n .from(jobRuns)\n .where(\n and(\n eq(jobRuns.concurrencyKey, claimed.concurrencyKey),\n eq(jobRuns.status, 'running'),\n ),\n );\n const other = inflight.find((r) => r.id !== claimed.id);\n if (other) {\n await this.db\n .update(jobRuns)\n .set({\n status: 'pending',\n claimedAt: null,\n startedAt: null,\n updatedAt: new Date(),\n })\n .where(eq(jobRuns.id, claimed.id));\n return;\n }\n }\n\n const meta = registryEntry.meta as JobHandlerMeta<unknown>;\n const HandlerClass = registryEntry.handlerClass;\n\n // (c) Build JobContext. Resolve the handler instance from Nest's DI\n // graph so its `@Inject` constructor params (which may come from\n // any module in the app graph) are satisfied. `moduleRef.create()`\n // would otherwise instantiate a fresh class within JobWorkerModule's\n // scope only — which blows up with \"not a provider of the current\n // module\" for any handler that consumes a service from a peer\n // module (e.g. CrmSyncJob injecting CrmSyncFactory from CrmModule).\n // Consequence: handlers MUST be registered as providers in their\n // owning module (@Injectable + `providers: [HandlerClass]`). The\n // @JobHandler decorator handles registry registration only, not DI.\n // See the jobs skill's handler-authoring.md for the registration\n // rule.\n const handler = this.moduleRef.get(\n HandlerClass as unknown as new (...args: unknown[]) => unknown,\n { strict: false },\n ) as JobHandlerBase<unknown>;\n const ctx: JobContext<unknown> = {\n input: claimed.input,\n run: claimed as JobRun,\n step: this.makeStepFn(claimed),\n spawnChild: this.makeSpawnFn(claimed),\n logger: new Logger(`JobRun:${claimed.id}`),\n };\n\n const attemptsBefore = claimed.attempts ?? 0;\n try {\n // (d) Run the handler.\n const output = (await handler.run(ctx)) as Record<string, unknown> | undefined;\n // (e) Success.\n await this.db\n .update(jobRuns)\n .set({\n status: 'completed',\n output: (output ?? {}) as Record<string, unknown>,\n finishedAt: new Date(),\n updatedAt: new Date(),\n attempts: attemptsBefore + 1,\n })\n .where(eq(jobRuns.id, claimed.id));\n } catch (err) {\n // (f) Error classification + retry/fail.\n const policy = meta.retry;\n const decision = classifyError(err, policy, attemptsBefore);\n const nextAttempts = attemptsBefore + 1;\n if (decision === 'retry' && policy) {\n const delay = computeBackoff(policy, nextAttempts);\n await this.db\n .update(jobRuns)\n .set({\n status: 'pending',\n attempts: nextAttempts,\n runAt: new Date(Date.now() + delay),\n startedAt: null,\n claimedAt: null,\n error: serialiseError(err, nextAttempts, true),\n updatedAt: new Date(),\n })\n .where(eq(jobRuns.id, claimed.id));\n } else {\n await this.markFailed(claimed, err, nextAttempts);\n }\n }\n }\n\n private async markFailed(\n claimed: JobRunRow,\n err: unknown,\n finalAttempts: number,\n ): Promise<void> {\n await this.db\n .update(jobRuns)\n .set({\n status: 'failed',\n attempts: finalAttempts,\n finishedAt: new Date(),\n error: serialiseError(err, finalAttempts, false),\n updatedAt: new Date(),\n })\n .where(eq(jobRuns.id, claimed.id));\n\n // Parent-close-policy cascade: if this run has children under the same\n // root_run_id and this run's own parentClosePolicy is 'terminate', cascade.\n if (claimed.parentClosePolicy === 'terminate') {\n try {\n // JOB-8 — thread the run's own tenantId so the orchestrator's\n // multi-tenant gate passes. Without this, every terminate-policy\n // cascade throws MissingTenantIdError under multiTenant=true and\n // the outer catch silently swallows it — children never cancel.\n await this.orchestrator.cancel(claimed.id, {\n cascade: true,\n reason: 'parent-failed',\n tenantId: claimed.tenantId,\n });\n } catch (cascadeErr) {\n // cancel is idempotent; failure here is unusual but not fatal.\n this.logger.warn(\n `cascade on failed run ${claimed.id}: ${(cascadeErr as Error).message}`,\n );\n }\n }\n }\n\n // ============================================================================\n // ctx.step / ctx.spawnChild builders\n // ============================================================================\n\n private makeStepFn(run: JobRunRow) {\n return async <TOutput>(\n stepId: string,\n fn: () => Promise<TOutput>,\n _opts?: StepOptions,\n ): Promise<TOutput> => {\n void _opts;\n const existing = await this.stepService.findStep(run.id, stepId);\n if (existing?.status === 'completed') {\n return existing.output as TOutput;\n }\n\n const seq = await this.nextStepSeq(run.id);\n const startedAt = new Date();\n const nextAttempts = (existing?.attempts ?? 0) + 1;\n await this.stepService.recordStep({\n jobRunId: run.id,\n stepId,\n kind: 'task',\n seq,\n status: 'running',\n startedAt,\n attempts: nextAttempts,\n });\n try {\n const output = await fn();\n await this.stepService.recordStep({\n jobRunId: run.id,\n stepId,\n kind: 'task',\n seq,\n status: 'completed',\n output: output as Record<string, unknown> | undefined,\n finishedAt: new Date(),\n attempts: nextAttempts,\n });\n return output;\n } catch (err) {\n await this.stepService.recordStep({\n jobRunId: run.id,\n stepId,\n kind: 'task',\n seq,\n status: 'failed',\n error: serialiseError(err, nextAttempts, false),\n finishedAt: new Date(),\n attempts: nextAttempts,\n });\n throw err;\n }\n };\n }\n\n private makeSpawnFn(run: JobRunRow) {\n return async (\n type: string,\n input: unknown,\n opts?: SpawnChildOptions,\n ): Promise<JobRun> => {\n return this.orchestrator.start(type, input, {\n parentRunId: run.id,\n parentClosePolicy: opts?.closePolicy,\n runAt: opts?.runAt,\n priority: opts?.priority,\n tags: opts?.tags,\n triggerSource: 'parent',\n triggerRef: run.id,\n });\n };\n }\n\n /**\n * Allocate the next `seq` for a given run. SELECT-max approach — runs\n * typically have <100 steps so the scan is cheap, and correctness across\n * retries is more important than the microseconds saved by an in-memory\n * counter (which would drift if the worker crashes mid-run and another\n * worker resumes via stale-claim sweep).\n */\n private async nextStepSeq(runId: string): Promise<number> {\n const [row] = await this.db.execute(\n sql`SELECT COALESCE(MAX(seq), 0) + 1 AS next FROM job_step WHERE job_run_id = ${runId}`,\n ) as unknown as Array<{ next: number }>;\n // pg driver returns { rows: [...] } for raw execute; tolerate both shapes.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const maybeRows = (row as any)?.rows;\n if (Array.isArray(maybeRows) && maybeRows.length > 0) {\n return Number(maybeRows[0].next ?? 1);\n }\n if (row && typeof (row as { next?: unknown }).next !== 'undefined') {\n return Number((row as { next: unknown }).next);\n }\n return 1;\n }\n\n // ============================================================================\n // (suppress unused-import noise)\n // ============================================================================\n}\n\n// Terminal statuses re-exported for JOB-4 parity imports.\nexport { TERMINAL_STATUSES };\n","/**\n * MemoryJobStore — the shared in-memory backing for the three memory-backend\n * services (ADR-022, JOB-4).\n *\n * Plain class, not `@Injectable()`. Wired as a `useValue` provider in\n * JOB-5's `JobsDomainModule.forRoot({ backend: 'memory' })` so unit tests\n * can keep a direct reference for `beforeEach` resets.\n *\n * All three memory services receive the same `MemoryJobStore` instance via\n * constructor injection; the store owns mutable state, the services are\n * stateless mutators.\n */\nimport type {\n JobDefinitionRow,\n JobRunRow,\n JobStepRow,\n} from './job-orchestration.schema';\n\nexport class MemoryJobStore {\n /** Runs keyed by `id` (single source of truth for status/scope/lineage). */\n readonly runs: Map<string, JobRunRow> = new Map();\n\n /** Steps keyed by `job_run_id`; array order matches insertion order. */\n readonly steps: Map<string, JobStepRow[]> = new Map();\n\n /** Job definitions keyed by `type` — memory mirror of the `job` table. */\n readonly jobs: Map<string, JobDefinitionRow> = new Map();\n\n /** Reset everything. Tests call this in `beforeEach`. */\n clear(): void {\n this.runs.clear();\n this.steps.clear();\n this.jobs.clear();\n }\n}\n","/**\n * MemoryJobOrchestrator — in-process implementation of `IJobOrchestrator`\n * (ADR-022, JOB-4).\n *\n * Exists solely for the unit test suite: reproduces the Drizzle backend's\n * observable behaviour (claim ordering, collision modes, dedupe collapse,\n * memoization cache, replay row-clearing, cascade cancel) without a\n * database. Not production — the single-process mutex is a substitute for\n * Postgres' `FOR UPDATE SKIP LOCKED`; acceptable non-parity is listed in\n * `docs/specs/JOB-4.md` (fsync, query perf, multi-process claim).\n *\n * The `MemoryJobStore` is shared with `MemoryJobRunService` /\n * `MemoryJobStepService` — all three services mutate the same Maps under\n * the orchestrator's mutex.\n */\nimport { randomUUID } from 'node:crypto';\nimport { Inject, Injectable, Logger, Optional } from '@nestjs/common';\nimport { ModuleRef } from '@nestjs/core';\nimport type {\n JobDefinitionRow,\n JobRunRow,\n} from './job-orchestration.schema';\nimport type {\n CancelOptions,\n IJobOrchestrator,\n JobPoolDef,\n JobRun,\n JobUpsertEntry,\n StartOptions,\n} from './job-orchestrator.protocol';\nimport type {\n JobContext,\n JobHandlerBase,\n JobHandlerMeta,\n RetryPolicy,\n SpawnChildOptions,\n StepOptions,\n} from './job-handler.base';\nimport { ParentClosePolicy } from './job-handler.base';\nimport {\n JobCollisionError,\n JobNotReplayableError,\n JobTemplateFieldMissingError,\n JobTypeNotFoundError,\n MissingTenantIdError,\n} from './jobs-errors';\nimport { MemoryJobStore } from './memory-job-store';\nimport { MemoryJobStepService } from './job-step-service.memory-backend';\nimport { JOBS_MULTI_TENANT } from './jobs-domain.tokens';\n\n/**\n * Sentinel `run_at` for runs that lost the `queue` collision — they stay\n * unclaimable until the incumbent transitions terminal and the orchestrator\n * advances their `run_at` back to `now()`. Mirrors the Drizzle backend's\n * `claim-time gate` behaviour without requiring a separate claim query.\n */\nconst QUEUED_RUN_AT = new Date(8_640_000_000_000_000); // \"distant future\"\nconst TERMINAL_STATUSES: JobRunRow['status'][] = [\n 'completed',\n 'failed',\n 'timed_out',\n 'canceled',\n];\nconst DEDUPE_EXCLUDED_STATUSES: JobRunRow['status'][] = ['canceled', 'failed'];\nconst IN_FLIGHT_STATUSES: JobRunRow['status'][] = ['pending', 'running'];\n\nfunction isTerminal(status: JobRunRow['status']): boolean {\n return TERMINAL_STATUSES.includes(status);\n}\n\n/**\n * Mirror of `evaluateKeyTemplate` in the Drizzle backend. Kept private here\n * rather than exported so the memory backend has no dependency on the\n * Drizzle module.\n */\nfunction evaluateKeyTemplate(\n template: string,\n input: Record<string, unknown>,\n): string {\n return template.replace(\n /\\{\\{\\s*([a-zA-Z0-9_]+)\\s*\\}\\}/g,\n (_m, field: string) => {\n const value = input[field];\n if (value === undefined || value === null) {\n throw new JobTemplateFieldMissingError(template, field);\n }\n return String(value);\n },\n );\n}\n\n/**\n * Single-promise-chain mutex. Every mutating op on the store goes through\n * `run(...)` so two concurrent `start` calls observe the same sequential\n * consistency Postgres gives us via `FOR UPDATE SKIP LOCKED`. Error\n * swallowing on the chain pointer prevents one failed call from poisoning\n * the queue for subsequent callers.\n *\n * Kept private to this file on purpose — the spec explicitly forbids\n * exporting this; it exists only for the memory backend's internal\n * serialisation.\n */\nclass PromiseMutex {\n private queue: Promise<void> = Promise.resolve();\n\n async run<T>(fn: () => Promise<T>): Promise<T> {\n const next = this.queue.then(() => fn());\n // Swallow errors on the chain pointer so a throwing `fn` doesn't\n // permanently reject every future caller.\n this.queue = next.then(\n () => undefined,\n () => undefined,\n );\n return next;\n }\n}\n\n/** Handler registry entry — class + frozen metadata. */\ninterface HandlerRegistration {\n type: string;\n meta: JobHandlerMeta<unknown>;\n handlerClass: new (...args: unknown[]) => JobHandlerBase<unknown>;\n}\n\n@Injectable()\nexport class MemoryJobOrchestrator implements IJobOrchestrator {\n private readonly logger = new Logger(MemoryJobOrchestrator.name);\n private readonly mutex = new PromiseMutex();\n private readonly handlerRegistry = new Map<string, HandlerRegistration>();\n\n /**\n * `runId → dependent runId[]` — when a run with `concurrencyKey = K`\n * blocks on an incumbent, its id is added here under the incumbent's id.\n * On incumbent terminal transition we advance every dependent's `runAt`\n * back to `now()` so it becomes claimable.\n */\n private readonly queueBlockers = new Map<string, string[]>();\n\n constructor(\n private readonly store: MemoryJobStore,\n private readonly stepService: MemoryJobStepService,\n @Inject(JOBS_MULTI_TENANT) private readonly multiTenant: boolean,\n @Optional() private readonly moduleRef?: ModuleRef,\n ) {}\n\n /**\n * JOB-8 — mirror of the Drizzle backend's `resolveTenantId`. Returns the\n * value to stamp on `tenant_id` / compare against in memory predicates.\n * Off → always `null`. On + `undefined` → throw. On + `null`/string → pass.\n */\n private resolveTenantId(\n method: string,\n tenantId: string | null | undefined,\n ): string | null {\n if (!this.multiTenant) return null;\n if (tenantId === undefined) throw new MissingTenantIdError(method);\n return tenantId;\n }\n\n // ==========================================================================\n // registerHandler — replaces Drizzle's `job` table upsert\n // ==========================================================================\n\n /**\n * Populate the in-memory job definition row plus handler class lookup.\n * Called by `JobWorkerModule.onModuleInit` in memory mode, or directly by\n * unit tests that want to seed the registry without NestJS.\n */\n registerHandler<TInput>(\n type: string,\n meta: JobHandlerMeta<TInput>,\n handlerClass: new (...args: unknown[]) => JobHandlerBase<TInput>,\n ): void {\n const concurrencyKeyTemplate =\n (meta.concurrency as { key?: string } | undefined)?.key ?? null;\n const dedupeKeyTemplate =\n (meta.dedupe as { key?: string } | undefined)?.key ?? null;\n const dedupeWindowMs = meta.dedupe?.windowMs ?? null;\n const now = new Date();\n\n const def: JobDefinitionRow = {\n type,\n version: 1,\n pool: meta.pool ?? 'batch',\n scopeEntityType: meta.scope?.entity ?? null,\n retryPolicy: meta.retry ?? {\n attempts: 1,\n backoff: 'fixed',\n baseMs: 0,\n },\n timeoutMs: meta.timeoutMs ?? null,\n concurrencyKeyTemplate:\n typeof concurrencyKeyTemplate === 'string' ? concurrencyKeyTemplate : null,\n collisionMode:\n (meta.concurrency?.collisionMode as JobDefinitionRow['collisionMode']) ??\n 'queue',\n dedupeKeyTemplate:\n typeof dedupeKeyTemplate === 'string' ? dedupeKeyTemplate : null,\n dedupeWindowMs,\n priorityDefault: 0,\n replayFrom: meta.replayFrom ?? 'last_checkpoint',\n createdAt: now,\n updatedAt: now,\n };\n\n this.store.jobs.set(type, def);\n this.handlerRegistry.set(type, {\n type,\n meta: meta as JobHandlerMeta<unknown>,\n handlerClass: handlerClass as unknown as new (\n ...args: unknown[]\n ) => JobHandlerBase<unknown>,\n });\n }\n\n /** Test helper — look up a registered handler without exposing the map. */\n getHandlerRegistration(type: string): HandlerRegistration | undefined {\n return this.handlerRegistry.get(type);\n }\n\n /**\n * Boot-time upsert per `IJobOrchestrator.upsertJobRows`. Memory backend\n * just funnels each entry through `registerHandler`. The validator is\n * skipped entirely in memory mode (Q4 resolution 2026-04-19), so the\n * orphaned list is always empty — there are no DB rows to compare against.\n */\n async upsertJobRows(\n entries: JobUpsertEntry[],\n poolConfig: ReadonlyMap<string, JobPoolDef>,\n ): Promise<{ orphaned: string[] }> {\n void poolConfig; // pool validation is the module's responsibility\n for (const entry of entries) {\n this.registerHandler(\n entry.type,\n entry.meta as JobHandlerMeta<unknown>,\n entry.handlerClass as new (...args: unknown[]) => JobHandlerBase<unknown>,\n );\n }\n return { orphaned: [] };\n }\n\n // ==========================================================================\n // start\n // ==========================================================================\n\n async start(\n type: string,\n input: unknown,\n opts: StartOptions = {},\n // BRIDGE-7: signature parity with Drizzle backend. The memory backend\n // has no real transactions (its \"atomic\" boundary is a process-wide\n // mutex acquired by the body below), so the parameter is intentionally\n // ignored. Accepting it lets EventFlowService unit tests exercise the\n // same code path without two stub orchestrators.\n _tx?: unknown,\n ): Promise<JobRun> {\n // JOB-8 — resolve tenant gate outside the mutex so the error throws\n // synchronously-ish from the caller's stack rather than via the mutex's\n // deferred chain (matches Drizzle backend's pre-transaction guard).\n const tenantId = this.resolveTenantId('start', opts.tenantId);\n\n return this.mutex.run(async () => {\n const payload = (input ?? {}) as Record<string, unknown>;\n const definition = this.store.jobs.get(type);\n if (!definition) throw new JobTypeNotFoundError(type);\n\n // 1. Dedupe — return existing non-excluded run within the window.\n if (definition.dedupeKeyTemplate && definition.dedupeWindowMs) {\n const dedupeKey = evaluateKeyTemplate(\n definition.dedupeKeyTemplate,\n payload,\n );\n const windowStart = Date.now() - definition.dedupeWindowMs;\n const existing = this.findDedupeCandidate(type, dedupeKey, windowStart);\n if (existing) return existing;\n }\n\n // 2. Concurrency collision check.\n let concurrencyKey: string | null = null;\n let queueBlockedBy: string | null = null;\n if (definition.concurrencyKeyTemplate) {\n concurrencyKey = evaluateKeyTemplate(\n definition.concurrencyKeyTemplate,\n payload,\n );\n const incumbent = this.findInFlightByConcurrencyKey(concurrencyKey);\n if (incumbent) {\n switch (definition.collisionMode) {\n case 'reject':\n throw new JobCollisionError(type, concurrencyKey, incumbent);\n case 'replace':\n // Cancel incumbent (cascading children). Must happen inside\n // the mutex — call the internal helper, not public `cancel()`\n // (public `cancel` would re-enter the mutex and deadlock).\n // Internal replace path sidesteps the tenant gate — it uses\n // the incumbent's own tenant (same concurrency key implies\n // same tenant in practice, but the gate is bypassed via\n // `incumbent.tenantId` to avoid accidental cross-tenant\n // MissingTenantIdError bubbling from the user's `start` call).\n this.cancelLocked(\n incumbent.id,\n { cascade: true, reason: 'replaced' },\n incumbent.tenantId,\n );\n break;\n case 'queue':\n queueBlockedBy = incumbent.id;\n break;\n }\n }\n }\n\n // 3. Resolve lineage.\n const newId = randomUUID();\n let rootRunId: string = newId;\n if (opts.parentRunId) {\n const parent = this.store.runs.get(opts.parentRunId);\n if (!parent) {\n throw new Error(\n `parentRunId ${opts.parentRunId} does not reference an existing job_run`,\n );\n }\n rootRunId = parent.rootRunId;\n }\n\n // 4. Compute dedupe key for the persisted row (separate from dedupe\n // short-circuit above — we store it even when no prior run matched\n // so future dedupe checks see it).\n const dedupeKey = definition.dedupeKeyTemplate\n ? evaluateKeyTemplate(definition.dedupeKeyTemplate, payload)\n : null;\n\n const now = new Date();\n const runAt = queueBlockedBy\n ? QUEUED_RUN_AT\n : (opts.runAt ?? now);\n\n const row: JobRunRow = {\n id: newId,\n jobType: type,\n jobVersion: definition.version,\n parentRunId: opts.parentRunId ?? null,\n rootRunId,\n parentClosePolicy: opts.parentClosePolicy ?? 'terminate',\n scopeEntityType: opts.scope?.entityType ?? null,\n scopeEntityId: opts.scope?.entityId ?? null,\n tenantId,\n tags: opts.tags ?? {},\n pool: opts.pool ?? definition.pool,\n priority: opts.priority ?? definition.priorityDefault,\n concurrencyKey,\n dedupeKey,\n status: 'pending',\n input: payload,\n output: null,\n error: null,\n triggerSource: opts.triggerSource ?? 'manual',\n triggerRef: opts.triggerRef ?? null,\n runAt,\n startedAt: null,\n finishedAt: null,\n claimedAt: null,\n attempts: 0,\n waitKind: null,\n resumeToken: null,\n waitDeadline: null,\n createdAt: now,\n updatedAt: now,\n };\n\n this.store.runs.set(newId, row);\n if (queueBlockedBy) {\n const list = this.queueBlockers.get(queueBlockedBy) ?? [];\n list.push(newId);\n this.queueBlockers.set(queueBlockedBy, list);\n }\n return row;\n });\n }\n\n // ==========================================================================\n // cancel\n // ==========================================================================\n\n async cancel(runId: string, opts: CancelOptions = {}): Promise<void> {\n // JOB-8 — strict tenant gate outside the mutex (matches Drizzle path).\n const tenantId = this.resolveTenantId('cancel', opts.tenantId);\n await this.mutex.run(async () => {\n this.cancelLocked(runId, opts, tenantId);\n });\n }\n\n /**\n * Internal cancel that assumes the caller already holds the mutex.\n * Synchronous because all store ops are in-memory. Idempotent.\n *\n * `tenantForGate` is the already-validated tenant id (or `null`). When\n * non-null it gates the initial cancellation to that tenant's run; the\n * cascade step then sweeps descendants on the same `rootRunId` without\n * re-checking — children of a tenant-gated parent always share the\n * tenant (enforced at `start` time).\n */\n private cancelLocked(\n runId: string,\n opts: CancelOptions,\n tenantForGate: string | null,\n ): void {\n const run = this.store.runs.get(runId);\n if (!run) return;\n // JOB-8 — cross-tenant cancel is silent no-op.\n if (this.multiTenant && run.tenantId !== tenantForGate) return;\n if (isTerminal(run.status)) return;\n\n const now = new Date();\n\n // Collect descendants up front so Cancel-policy parents can wait on\n // children (their `finished_at` is set after children transition).\n const descendants =\n opts.cascade === false\n ? []\n : Array.from(this.store.runs.values()).filter(\n (r) =>\n r.rootRunId === run.rootRunId &&\n r.id !== runId &&\n !isTerminal(r.status),\n );\n\n // Group by policy stored on the child.\n const terminateChildren = descendants.filter(\n (d) => d.parentClosePolicy === ParentClosePolicy.Terminate,\n );\n const cancelChildren = descendants.filter(\n (d) => d.parentClosePolicy === ParentClosePolicy.Cancel,\n );\n // 'abandon' → do nothing.\n\n // Terminate policy: cancel children, then parent.\n for (const child of terminateChildren) {\n this.transitionToCanceled(child.id, now);\n }\n\n // Cancel policy: cancel children first, then parent (so parent's\n // finished_at is set only after children transitioned).\n for (const child of cancelChildren) {\n this.transitionToCanceled(child.id, now);\n }\n\n this.transitionToCanceled(runId, now);\n\n void opts.reason; // reserved for future audit logging\n }\n\n private transitionToCanceled(runId: string, at: Date): void {\n const run = this.store.runs.get(runId);\n if (!run) return;\n if (isTerminal(run.status)) return;\n const next: JobRunRow = {\n ...run,\n status: 'canceled',\n finishedAt: at,\n updatedAt: at,\n };\n this.store.runs.set(runId, next);\n this.unblockQueuedDependents(runId);\n }\n\n /**\n * When `runId` transitions to a terminal state, advance every dependent\n * `queue`-blocked run's `run_at` back to `now()` so `claimNext` picks\n * them up.\n */\n private unblockQueuedDependents(runId: string): void {\n const dependents = this.queueBlockers.get(runId);\n if (!dependents || dependents.length === 0) return;\n const now = new Date();\n for (const dep of dependents) {\n const depRun = this.store.runs.get(dep);\n if (!depRun) continue;\n if (depRun.status !== 'pending') continue;\n this.store.runs.set(dep, { ...depRun, runAt: now, updatedAt: now });\n }\n this.queueBlockers.delete(runId);\n }\n\n // ==========================================================================\n // claimNext — consumed by JobWorker in memory mode (tests exercise directly)\n // ==========================================================================\n\n async claimNext(pool: string): Promise<JobRunRow | null> {\n return this.mutex.run(async () => {\n const now = Date.now();\n const candidates = Array.from(this.store.runs.values()).filter(\n (r) =>\n r.status === 'pending' &&\n r.pool === pool &&\n r.runAt.getTime() <= now,\n );\n if (candidates.length === 0) return null;\n\n // ORDER BY priority DESC, run_at ASC (Drizzle parity).\n candidates.sort((a, b) => {\n if (a.priority !== b.priority) return b.priority - a.priority;\n return a.runAt.getTime() - b.runAt.getTime();\n });\n\n const winner = candidates[0]!;\n const claimedAt = new Date();\n const next: JobRunRow = {\n ...winner,\n status: 'running',\n claimedAt,\n startedAt: claimedAt,\n updatedAt: claimedAt,\n };\n this.store.runs.set(winner.id, next);\n return next;\n });\n }\n\n // ==========================================================================\n // replay\n // ==========================================================================\n\n async replay(runId: string): Promise<JobRun> {\n return this.mutex.run(async () => {\n const run = this.store.runs.get(runId);\n if (!run) throw new Error(`replay: run ${runId} not found`);\n if (!isTerminal(run.status)) {\n throw new JobNotReplayableError(runId, run.status);\n }\n const def = this.store.jobs.get(run.jobType);\n if (!def) throw new JobTypeNotFoundError(run.jobType);\n\n const mode = def.replayFrom;\n if (mode === 'scratch') {\n this.stepService.clearStepsForRun(runId);\n } else {\n // `last_step` and `last_checkpoint` collapse to the same semantic\n // in Phase 1 — delete non-completed rows, preserve memoized ones.\n // Matches the Drizzle backend exactly (see JOB-3 notes).\n this.stepService.clearIncompleteSteps(runId);\n }\n\n const now = new Date();\n const next: JobRunRow = {\n ...run,\n status: 'pending',\n attempts: 0,\n runAt: now,\n startedAt: null,\n finishedAt: null,\n claimedAt: null,\n error: null,\n output: null,\n updatedAt: now,\n };\n this.store.runs.set(runId, next);\n return next;\n });\n }\n\n // ==========================================================================\n // tick — used by unit tests + memory-mode JobWorker\n // ==========================================================================\n\n /**\n * Execute a single claimed run to completion, retry, or failure. Not on\n * `IJobOrchestrator` — it's the memory equivalent of the Drizzle\n * `JobWorker.processRun` code path. The unit tests drive it directly so\n * they can assert memoization across ticks without spinning up a worker.\n */\n async tick(runId: string): Promise<void> {\n // We load state outside the mutex because handler execution cannot\n // hold the serialisation lock — `fn()` inside `ctx.step` can call back\n // into `start` / `spawnChild` which would deadlock. Mutation points\n // (recordStep, status transition) go through the services or the\n // orchestrator entry points and re-enter the mutex there.\n const run = this.store.runs.get(runId);\n if (!run) throw new Error(`tick: run ${runId} not found`);\n if (run.status !== 'running') {\n throw new Error(\n `tick: run ${runId} must be 'running' (got '${run.status}')`,\n );\n }\n\n const registration = this.handlerRegistry.get(run.jobType);\n if (!registration) {\n await this.markFailed(run, new Error(\n `No handler registered for jobType='${run.jobType}'`,\n ), (run.attempts ?? 0) + 1);\n return;\n }\n const meta = registration.meta;\n const HandlerClass = registration.handlerClass;\n // Match the Drizzle backend: resolve the handler through Nest's\n // ModuleRef so `@Inject` constructor params work. ModuleRef is\n // @Optional() — zero-dep test stubs that construct this orchestrator\n // manually still hit the legacy `new HandlerClass()` path.\n // `get({ strict: false })` (not `create()`) — the handler must be a\n // provider in its owning module so cross-module @Inject dependencies\n // resolve. See job-worker.ts for the full rationale.\n const handler = this.moduleRef\n ? (this.moduleRef.get(\n HandlerClass as unknown as new (...args: unknown[]) => unknown,\n { strict: false },\n ) as JobHandlerBase<unknown>)\n : new HandlerClass();\n\n const ctx: JobContext<unknown> = {\n input: run.input,\n run: run as JobRun,\n step: this.makeStepFn(run),\n spawnChild: this.makeSpawnFn(run),\n logger: new Logger(`JobRun:${run.id}`),\n };\n\n const attemptsBefore = run.attempts ?? 0;\n try {\n const output = (await handler.run(ctx)) as Record<string, unknown> | undefined;\n await this.markCompleted(run, output ?? {}, attemptsBefore + 1);\n } catch (err) {\n const policy = meta.retry;\n const decision = classifyError(err, policy, attemptsBefore);\n const nextAttempts = attemptsBefore + 1;\n if (decision === 'retry' && policy) {\n const delay = computeBackoff(policy, nextAttempts);\n await this.rescheduleForRetry(run, err, nextAttempts, delay);\n } else {\n await this.markFailed(run, err, nextAttempts);\n }\n }\n }\n\n private makeStepFn(run: JobRunRow) {\n return async <TOutput>(\n stepId: string,\n fn: () => Promise<TOutput>,\n _opts?: StepOptions,\n ): Promise<TOutput> => {\n void _opts;\n const existing = await this.stepService.findStep(run.id, stepId);\n if (existing?.status === 'completed') {\n return existing.output as TOutput;\n }\n const seq = this.nextStepSeq(run.id);\n const startedAt = new Date();\n const nextAttempts = (existing?.attempts ?? 0) + 1;\n await this.stepService.recordStep({\n jobRunId: run.id,\n stepId,\n kind: 'task',\n seq,\n status: 'running',\n startedAt,\n attempts: nextAttempts,\n });\n try {\n const output = await fn();\n await this.stepService.recordStep({\n jobRunId: run.id,\n stepId,\n kind: 'task',\n seq,\n status: 'completed',\n output: output as Record<string, unknown> | undefined,\n finishedAt: new Date(),\n attempts: nextAttempts,\n });\n return output;\n } catch (err) {\n await this.stepService.recordStep({\n jobRunId: run.id,\n stepId,\n kind: 'task',\n seq,\n status: 'failed',\n error: serialiseError(err, nextAttempts, false),\n finishedAt: new Date(),\n attempts: nextAttempts,\n });\n throw err;\n }\n };\n }\n\n private makeSpawnFn(run: JobRunRow) {\n return async (\n type: string,\n input: unknown,\n opts?: SpawnChildOptions,\n ): Promise<JobRun> => {\n return this.start(type, input, {\n parentRunId: run.id,\n parentClosePolicy: opts?.closePolicy,\n runAt: opts?.runAt,\n priority: opts?.priority,\n tags: opts?.tags,\n triggerSource: 'parent',\n triggerRef: run.id,\n });\n };\n }\n\n private nextStepSeq(runId: string): number {\n const rows = this.store.steps.get(runId);\n if (!rows || rows.length === 0) return 1;\n let max = 0;\n for (const r of rows) if (r.seq > max) max = r.seq;\n return max + 1;\n }\n\n private async markCompleted(\n run: JobRunRow,\n output: Record<string, unknown>,\n attempts: number,\n ): Promise<void> {\n await this.mutex.run(async () => {\n const current = this.store.runs.get(run.id);\n if (!current || isTerminal(current.status)) return;\n const now = new Date();\n this.store.runs.set(run.id, {\n ...current,\n status: 'completed',\n output,\n finishedAt: now,\n updatedAt: now,\n attempts,\n });\n this.unblockQueuedDependents(run.id);\n });\n }\n\n private async markFailed(\n run: JobRunRow,\n err: unknown,\n attempts: number,\n ): Promise<void> {\n await this.mutex.run(async () => {\n const current = this.store.runs.get(run.id);\n if (!current || isTerminal(current.status)) return;\n const now = new Date();\n this.store.runs.set(run.id, {\n ...current,\n status: 'failed',\n finishedAt: now,\n updatedAt: now,\n attempts,\n error: serialiseError(err, attempts, false),\n });\n this.unblockQueuedDependents(run.id);\n });\n\n // parent_close_policy = 'terminate' cascade mirrors the Drizzle worker\n // (cancel runs outside its own terminal transition). We pass the run's\n // own `tenantId` so the cancel passes the multi-tenant gate — this is\n // system-internal cascade, not a user-initiated call.\n if (run.parentClosePolicy === 'terminate') {\n try {\n await this.cancel(run.id, {\n cascade: true,\n reason: 'parent-failed',\n tenantId: run.tenantId,\n });\n } catch (cascadeErr) {\n this.logger.warn(\n `cascade on failed run ${run.id}: ${(cascadeErr as Error).message}`,\n );\n }\n }\n }\n\n private async rescheduleForRetry(\n run: JobRunRow,\n err: unknown,\n attempts: number,\n delayMs: number,\n ): Promise<void> {\n await this.mutex.run(async () => {\n const current = this.store.runs.get(run.id);\n if (!current || isTerminal(current.status)) return;\n const now = new Date();\n this.store.runs.set(run.id, {\n ...current,\n status: 'pending',\n attempts,\n runAt: new Date(Date.now() + delayMs),\n startedAt: null,\n claimedAt: null,\n updatedAt: now,\n error: serialiseError(err, attempts, true),\n });\n });\n }\n\n // ==========================================================================\n // Internal queries — used by start / cancel\n // ==========================================================================\n\n private findDedupeCandidate(\n jobType: string,\n dedupeKey: string,\n windowStartMs: number,\n ): JobRunRow | null {\n let best: JobRunRow | null = null;\n for (const r of this.store.runs.values()) {\n if (r.jobType !== jobType) continue;\n if (r.dedupeKey !== dedupeKey) continue;\n if (DEDUPE_EXCLUDED_STATUSES.includes(r.status)) continue;\n if (r.createdAt.getTime() <= windowStartMs) continue;\n if (!best || r.createdAt.getTime() > best.createdAt.getTime()) {\n best = r;\n }\n }\n return best;\n }\n\n private findInFlightByConcurrencyKey(key: string): JobRunRow | null {\n for (const r of this.store.runs.values()) {\n if (r.concurrencyKey !== key) continue;\n if (!IN_FLIGHT_STATUSES.includes(r.status)) continue;\n return r;\n }\n return null;\n }\n}\n\n// ─── Pure helpers (mirrored from JobWorker so memory mode is standalone) ────\n\nfunction classifyError(\n err: unknown,\n policy: RetryPolicy | undefined,\n currentAttempts: number,\n): 'retry' | 'fail' {\n if (!policy) return 'fail';\n const errObj = err as { name?: string; code?: string } | undefined;\n const name = errObj?.name;\n const code = errObj?.code;\n const nonRetryable = policy.nonRetryableErrors ?? [];\n if (nonRetryable.some((n) => n === name || n === code)) return 'fail';\n if (currentAttempts + 1 >= policy.attempts) return 'fail';\n return 'retry';\n}\n\nfunction computeBackoff(policy: RetryPolicy, attempts: number): number {\n const base = Math.max(policy.baseMs, 0);\n if (policy.backoff === 'fixed') return base;\n const exponent = Math.max(attempts - 1, 0);\n if (exponent >= 53) return Number.MAX_SAFE_INTEGER;\n const raw = base * Math.pow(2, exponent);\n if (!Number.isFinite(raw) || raw >= Number.MAX_SAFE_INTEGER) {\n return Number.MAX_SAFE_INTEGER;\n }\n return raw;\n}\n\nfunction serialiseError(err: unknown, attempt: number, retryable: boolean) {\n const e = err as { message?: string; stack?: string } | undefined;\n return {\n message: (e?.message ?? String(err)) as string,\n stack: e?.stack,\n retryable,\n attempt,\n };\n}\n","/**\n * MemoryJobRunService — scope-oriented queries and bulk ops over the\n * in-memory run store (ADR-022, JOB-4).\n *\n * Mirrors `DrizzleJobRunService` but scans `MemoryJobStore.runs.values()`.\n * Cancel delegates back to the orchestrator so cascade semantics stay in\n * one place.\n */\nimport { Inject, Injectable } from '@nestjs/common';\nimport type { JobRunRow } from './job-orchestration.schema';\nimport type { JobRun } from './job-orchestrator.protocol';\nimport type {\n IJobRunService,\n ListForScopeOptions,\n CancelForScopeOptions,\n RescheduleForScopeOptions,\n PoolStatusCount,\n JobRunFailure,\n ListJobRunsQuery,\n JobRunPage,\n} from './job-run-service.protocol';\nimport {\n clampLimit,\n decodeKeysetCursor,\n encodeKeysetCursor,\n toJobRunSummary,\n} from './job-run-keyset-cursor';\nimport type { IJobOrchestrator } from './job-orchestrator.protocol';\nimport { JOB_ORCHESTRATOR, JOBS_MULTI_TENANT } from './jobs-domain.tokens';\nimport { MissingTenantIdError } from './jobs-errors';\nimport { MemoryJobStore } from './memory-job-store';\n\nconst NON_TERMINAL_STATUSES: JobRunRow['status'][] = [\n 'pending',\n 'running',\n 'waiting',\n];\n\n@Injectable()\nexport class MemoryJobRunService implements IJobRunService {\n constructor(\n private readonly store: MemoryJobStore,\n @Inject(JOB_ORCHESTRATOR) private readonly orchestrator: IJobOrchestrator,\n @Inject(JOBS_MULTI_TENANT) private readonly multiTenant: boolean,\n ) {}\n\n /**\n * JOB-8 — produce a per-row predicate for the tenant gate.\n * Returns `null` when multi-tenancy is off (caller doesn't check).\n * Throws when on + `undefined`; matches `tenant_id IS NULL` on explicit\n * `null` to support cross-tenant background work.\n */\n private tenantPredicate(\n method: string,\n tenantId: string | null | undefined,\n ): ((r: JobRunRow) => boolean) | null {\n if (!this.multiTenant) return null;\n if (tenantId === undefined) throw new MissingTenantIdError(method);\n return (r) => r.tenantId === tenantId;\n }\n\n async listForScope(\n entityType: string,\n entityId: string,\n opts: ListForScopeOptions = {},\n ): Promise<JobRun[]> {\n const statusFilter = opts.status\n ? Array.isArray(opts.status)\n ? new Set(opts.status)\n : new Set([opts.status])\n : null;\n const tenantCheck = this.tenantPredicate('listForScope', opts.tenantId);\n\n const rows: JobRunRow[] = [];\n for (const r of this.store.runs.values()) {\n if (r.scopeEntityType !== entityType) continue;\n if (r.scopeEntityId !== entityId) continue;\n if (statusFilter && !statusFilter.has(r.status)) continue;\n if (opts.jobType && r.jobType !== opts.jobType) continue;\n if (tenantCheck && !tenantCheck(r)) continue;\n rows.push(r);\n }\n\n const orderBy = opts.orderBy ?? 'created_at desc';\n rows.sort((a, b) => compareBy(a, b, orderBy));\n\n const offset = opts.offset ?? 0;\n const limit = opts.limit;\n const sliced =\n typeof limit === 'number' ? rows.slice(offset, offset + limit) : rows.slice(offset);\n return sliced as JobRun[];\n }\n\n async cancelForScope(\n entityType: string,\n entityId: string,\n opts: CancelForScopeOptions = {},\n ): Promise<void> {\n const tenantCheck = this.tenantPredicate('cancelForScope', opts.tenantId);\n\n const ids: string[] = [];\n for (const r of this.store.runs.values()) {\n if (r.scopeEntityType !== entityType) continue;\n if (r.scopeEntityId !== entityId) continue;\n if (!NON_TERMINAL_STATUSES.includes(r.status)) continue;\n if (tenantCheck && !tenantCheck(r)) continue;\n ids.push(r.id);\n }\n for (const id of ids) {\n // Propagate the tenant gate through the orchestrator's cancel so the\n // internal per-row guard passes (no surprise MissingTenantIdError\n // once the scope query has already narrowed to this tenant).\n await this.orchestrator.cancel(id, {\n cascade: true,\n tenantId: opts.tenantId,\n });\n }\n }\n\n async rescheduleForScope(\n entityType: string,\n entityId: string,\n newRunAt: Date,\n opts: RescheduleForScopeOptions = {},\n ): Promise<void> {\n const tenantCheck = this.tenantPredicate('rescheduleForScope', opts.tenantId);\n for (const r of this.store.runs.values()) {\n if (r.scopeEntityType !== entityType) continue;\n if (r.scopeEntityId !== entityId) continue;\n if (r.status !== 'pending') continue;\n if (tenantCheck && !tenantCheck(r)) continue;\n this.store.runs.set(r.id, {\n ...r,\n runAt: newRunAt,\n updatedAt: new Date(),\n });\n }\n }\n\n async countByPoolAndStatus(\n tenantId?: string | null,\n ): Promise<PoolStatusCount[]> {\n const tenantCheck = this.tenantPredicate('countByPoolAndStatus', tenantId);\n const map = new Map<string, PoolStatusCount>();\n for (const r of this.store.runs.values()) {\n if (tenantCheck && !tenantCheck(r)) continue;\n const key = `${r.pool}\\0${r.status}`;\n const cur = map.get(key);\n if (cur) {\n cur.count += 1;\n } else {\n map.set(key, { pool: r.pool, status: r.status, count: 1 });\n }\n }\n return Array.from(map.values());\n }\n\n async listRecentFailed(\n limit: number,\n tenantId?: string | null,\n ): Promise<JobRunFailure[]> {\n const tenantCheck = this.tenantPredicate('listRecentFailed', tenantId);\n const failed: JobRunRow[] = [];\n for (const r of this.store.runs.values()) {\n if (r.status !== 'failed') continue;\n if (tenantCheck && !tenantCheck(r)) continue;\n failed.push(r);\n }\n failed.sort((a, b) => {\n const at = (a.finishedAt ?? a.updatedAt).getTime();\n const bt = (b.finishedAt ?? b.updatedAt).getTime();\n return bt - at;\n });\n return failed.slice(0, limit).map((r) => ({\n runId: r.id,\n jobType: r.jobType,\n pool: r.pool,\n scopeEntityType: r.scopeEntityType,\n scopeEntityId: r.scopeEntityId,\n tenantId: r.tenantId,\n attempts: r.attempts,\n errorMessage: r.error?.message ?? null,\n failedAt: r.finishedAt ?? r.updatedAt,\n createdAt: r.createdAt,\n }));\n }\n\n async listJobRuns(query: ListJobRunsQuery = {}): Promise<JobRunPage> {\n const limit = clampLimit(query.limit);\n const tenantCheck = this.tenantPredicate('listJobRuns', query.tenantId);\n const keyset = query.cursor ? decodeKeysetCursor(query.cursor) : null;\n\n const matched: JobRunRow[] = [];\n for (const r of this.store.runs.values()) {\n if (tenantCheck && !tenantCheck(r)) continue;\n if (query.poolId && r.pool !== query.poolId) continue;\n if (query.rootRunId && r.rootRunId !== query.rootRunId) continue;\n if (query.status && r.status !== query.status) continue;\n if (query.since && r.createdAt.getTime() < query.since.getTime()) continue;\n matched.push(r);\n }\n\n // Order created_at DESC, id DESC to match the Drizzle backend's keyset.\n matched.sort((a, b) => {\n const dt = b.createdAt.getTime() - a.createdAt.getTime();\n if (dt !== 0) return dt;\n return a.id < b.id ? 1 : a.id > b.id ? -1 : 0;\n });\n\n // Keyset seek: drop everything at/after the cursor's (created_at, id).\n const seeked = keyset\n ? matched.filter((r) => {\n const ct = r.createdAt.getTime();\n const kt = keyset.createdAt.getTime();\n if (ct < kt) return true;\n if (ct > kt) return false;\n return r.id < keyset.id;\n })\n : matched;\n\n const hasMore = seeked.length > limit;\n const page = hasMore ? seeked.slice(0, limit) : seeked;\n const items = page.map(toJobRunSummary);\n const last = page[page.length - 1];\n const nextCursor =\n hasMore && last\n ? encodeKeysetCursor({ createdAt: last.createdAt, id: last.id })\n : null;\n\n return { items, nextCursor };\n }\n\n /**\n * Direct lookup. Not on the protocol — concrete-class convenience for\n * tests. Matches `DrizzleJobRunService.findByRootRunId` in spirit; both\n * are debug / test helpers that sidestep the orchestrator.\n */\n findById(runId: string): JobRun | null {\n return (this.store.runs.get(runId) ?? null) as JobRun | null;\n }\n\n /** Public counterpart to the Drizzle backend's `findByRootRunId` helper. */\n findByRootRunId(rootRunId: string): JobRun[] {\n const out: JobRunRow[] = [];\n for (const r of this.store.runs.values()) {\n if (r.rootRunId === rootRunId) out.push(r);\n }\n return out as JobRun[];\n }\n}\n\nfunction compareBy(\n a: JobRunRow,\n b: JobRunRow,\n order: Exclude<ListForScopeOptions['orderBy'], undefined>,\n): number {\n switch (order) {\n case 'created_at asc':\n return a.createdAt.getTime() - b.createdAt.getTime();\n case 'run_at desc':\n return b.runAt.getTime() - a.runAt.getTime();\n case 'run_at asc':\n return a.runAt.getTime() - b.runAt.getTime();\n case 'created_at desc':\n default:\n return b.createdAt.getTime() - a.createdAt.getTime();\n }\n}\n","/**\n * MemoryJobStepService — in-memory implementation of `IJobStepService`\n * (ADR-022, JOB-4).\n *\n * Mirrors `DrizzleJobStepService` but against plain Maps. `findStep` only\n * returns `completed` rows (memoization cache hit); anything non-completed\n * is invisible so the ctx.step fn re-runs on replay / retry exactly like\n * the Drizzle backend (which deletes non-completed rows on replay).\n */\nimport { randomUUID } from 'node:crypto';\nimport { Injectable } from '@nestjs/common';\nimport type { JobStepRow } from './job-orchestration.schema';\nimport type {\n IJobStepService,\n JobStep,\n RecordStepInput,\n} from './job-step-service.protocol';\nimport { MemoryJobStore } from './memory-job-store';\n\n@Injectable()\nexport class MemoryJobStepService implements IJobStepService {\n constructor(private readonly store: MemoryJobStore) {}\n\n async findStep(runId: string, stepId: string): Promise<JobStep | null> {\n const rows = this.store.steps.get(runId);\n if (!rows) return null;\n const match = rows.find(\n (r) => r.stepId === stepId && r.status === 'completed',\n );\n return (match ?? null) as JobStep | null;\n }\n\n async recordStep(input: RecordStepInput): Promise<JobStep> {\n const rows = this.getOrCreateRows(input.jobRunId);\n const existingIdx = rows.findIndex((r) => r.stepId === input.stepId);\n\n const normalisedInput =\n (input.input ?? null) as Record<string, unknown> | null;\n const normalisedOutput =\n (input.output ?? null) as Record<string, unknown> | null;\n\n if (existingIdx >= 0) {\n const prev = rows[existingIdx]!;\n const next: JobStepRow = {\n ...prev,\n status: input.status,\n input: normalisedInput ?? prev.input,\n output: normalisedOutput ?? prev.output,\n error: input.error ?? prev.error,\n attempts: input.attempts ?? prev.attempts,\n startedAt: input.startedAt ?? prev.startedAt,\n finishedAt: input.finishedAt ?? prev.finishedAt,\n };\n rows[existingIdx] = next;\n return next as JobStep;\n }\n\n const seq = input.seq ?? this.nextSeq(rows);\n const row: JobStepRow = {\n id: randomUUID(),\n jobRunId: input.jobRunId,\n stepId: input.stepId,\n kind: input.kind,\n seq,\n status: input.status,\n input: normalisedInput,\n output: normalisedOutput,\n error: input.error ?? null,\n attempts: input.attempts ?? 0,\n startedAt: input.startedAt ?? null,\n finishedAt: input.finishedAt ?? null,\n };\n rows.push(row);\n return row as JobStep;\n }\n\n /**\n * Replay helper — wipe every step row for a run. Mirrors the `scratch`\n * replay mode of the Drizzle backend (`DELETE FROM job_step WHERE job_run_id = …`).\n */\n clearStepsForRun(runId: string): void {\n this.store.steps.delete(runId);\n }\n\n /**\n * Remove every non-`completed` row for the run. Memoized (`completed`)\n * rows are preserved — this is the `last_checkpoint` / `last_step`\n * semantics the Drizzle backend implements via\n * `DELETE … WHERE status != 'completed'`. Both replay modes route here\n * (Phase 1 collapses `last_step` onto this behaviour; see JOB-3 notes).\n */\n clearIncompleteSteps(runId: string): void {\n const rows = this.store.steps.get(runId);\n if (!rows) return;\n const kept = rows.filter((r) => r.status === 'completed');\n if (kept.length === 0) {\n this.store.steps.delete(runId);\n } else {\n this.store.steps.set(runId, kept);\n }\n }\n\n private getOrCreateRows(runId: string): JobStepRow[] {\n let rows = this.store.steps.get(runId);\n if (!rows) {\n rows = [];\n this.store.steps.set(runId, rows);\n }\n return rows;\n }\n\n private nextSeq(rows: JobStepRow[]): number {\n let max = 0;\n for (const r of rows) {\n if (r.seq > max) max = r.seq;\n }\n return max + 1;\n }\n}\n","/**\n * JobsDomainModule — `DynamicModule.forRoot({ backend })` factory wiring\n * the three jobs-domain protocol tokens to a backend implementation\n * (ADR-022, JOB-5).\n *\n * Mirrors `EventsModule.forRoot()` exactly:\n * - `global: true` so consumer entity modules don't have to import this\n * individually — `JOB_ORCHESTRATOR` / `JOB_RUN_SERVICE` /\n * `JOB_STEP_SERVICE` are available project-wide.\n * - One backend at a time (Drizzle for production, Memory for tests).\n *\n * Backend swappability follows the core/extension protocol from CLAUDE.md:\n * the three tokens are the **core contract**; backend-specific tunables\n * live under `extensions.<backend>` so opting into a feature is explicit\n * and the type system reserves the slot.\n */\nimport { Module, type DynamicModule, type Provider } from '@nestjs/common';\nimport { DRIZZLE } from '../../constants/tokens';\nimport {\n JOB_ORCHESTRATOR,\n JOB_RUN_SERVICE,\n JOB_STEP_SERVICE,\n JOBS_MULTI_TENANT,\n} from './jobs-domain.tokens';\nimport { DrizzleJobOrchestrator } from './job-orchestrator.drizzle-backend';\nimport { DrizzleJobRunService } from './job-run-service.drizzle-backend';\nimport { DrizzleJobStepService } from './job-step-service.drizzle-backend';\n// #6 — `BullMQJobOrchestrator` is lazy-loaded only when `backend: 'bullmq'`\n// is selected. The backend file is filtered out of drizzle/memory installs\n// (see `backendFileFilter`); a non-literal dynamic import below sidesteps\n// consumer-side tsc resolution of an absent file.\nimport { MemoryJobOrchestrator } from './job-orchestrator.memory-backend';\nimport { MemoryJobRunService } from './job-run-service.memory-backend';\nimport { MemoryJobStepService } from './job-step-service.memory-backend';\nimport { MemoryJobStore } from './memory-job-store';\nimport {\n BULLMQ_CONNECTION,\n BULLMQ_RESOLVED_CONFIG,\n resolveBullMqConfig,\n type BullMqExtensionsConfig,\n} from './bullmq.config';\n\n/**\n * Drizzle backend extensions surface. None are wired into the Drizzle\n * orchestrator yet — this is the **typed reservation** for the LISTEN/NOTIFY\n * + tunable poll-interval extensions called out in ADR-022. App code\n * passing these today is parsed but not yet dispatched; when the\n * Drizzle orchestrator grows the consumer hooks, opt-in code paths will\n * read directly from these fields.\n */\nexport interface DrizzleBackendExtensions {\n /** Use Postgres LISTEN/NOTIFY to wake the polling loop. Default false. */\n listenNotify?: boolean;\n /** Polling interval when LISTEN/NOTIFY is off (ms). Default 1000. */\n pollIntervalMs?: number;\n}\n\nexport interface JobsDomainModuleOptions {\n backend: 'drizzle' | 'memory' | 'bullmq';\n /**\n * Backend-specific extensions. Only the matching backend's extensions\n * are read at boot; non-matching keys are ignored. This is the\n * core/extension protocol surface — see CLAUDE.md.\n */\n extensions?: {\n drizzle?: DrizzleBackendExtensions;\n /**\n * BullMQ backend extensions (BULLMQ-1). Snake_case mirrors the YAML\n * under `jobs.extensions.bullmq`. `redis_url` falls back to\n * `process.env.REDIS_URL` then `redis://localhost:6379`.\n */\n bullmq?: BullMqExtensionsConfig;\n };\n /** Multi-tenancy opt-in. Wired by JOB-8; module signature stays stable. */\n multiTenant?: boolean;\n}\n\n@Module({})\nexport class JobsDomainModule {\n static forRoot(opts: JobsDomainModuleOptions): DynamicModule {\n const multiTenant = opts.multiTenant ?? false;\n\n const providers: Provider[] = [\n // JOB-8 — boolean provider consumed by the four service-layer backends.\n // Always provided (even when `multiTenant === false`) so `@Inject`\n // always resolves; backends short-circuit the enforcement path when\n // the value is `false`. See `jobs-domain.tokens.ts` for the claim-loop\n // cross-tenant-by-design decision.\n { provide: JOBS_MULTI_TENANT, useValue: multiTenant },\n ];\n\n if (opts.backend === 'memory') {\n // The store is a plain class — wired as a singleton `useValue` so\n // unit tests can pull it out via `.get(MemoryJobStore)` for direct\n // assertions (matches the access pattern in JOB-4 specs).\n const store = new MemoryJobStore();\n providers.push({ provide: MemoryJobStore, useValue: store });\n providers.push(MemoryJobStepService);\n providers.push({ provide: JOB_STEP_SERVICE, useExisting: MemoryJobStepService });\n providers.push(MemoryJobOrchestrator);\n providers.push({ provide: JOB_ORCHESTRATOR, useExisting: MemoryJobOrchestrator });\n providers.push(MemoryJobRunService);\n providers.push({ provide: JOB_RUN_SERVICE, useExisting: MemoryJobRunService });\n } else if (opts.backend === 'bullmq') {\n // BULLMQ-1 — BullMQ orchestrator over a Postgres source of truth. The\n // run/step services stay Drizzle (domain reads + `listForScope` are\n // Postgres queries, unchanged per spec). Only the orchestrator's\n // claim/dispatch half swaps to BullMQ.\n //\n // #6 — the bullmq backend module is filtered out of drizzle/memory\n // installs (no `bullmq` peer dep, no consumer-side tsc compile of an\n // unused file). The factory below dynamic-imports it via a non-literal\n // specifier so TS treats the module type as `any` and never tries to\n // resolve the absent file on a drizzle/memory consumer.\n const resolved = resolveBullMqConfig(opts.extensions?.bullmq);\n providers.push({ provide: BULLMQ_CONNECTION, useValue: resolved.connection });\n providers.push({ provide: BULLMQ_RESOLVED_CONFIG, useValue: resolved });\n providers.push({\n provide: JOB_ORCHESTRATOR,\n useFactory: async (...args: unknown[]): Promise<object> => {\n const specifier = './job-orchestrator.bullmq-backend';\n const mod = (await import(specifier)) as {\n BullMQJobOrchestrator: new (...args: unknown[]) => object;\n };\n return new mod.BullMQJobOrchestrator(...args);\n },\n // The bullmq orchestrator constructor mirrors DrizzleJobOrchestrator's\n // injection list: DRIZZLE + JOBS_MULTI_TENANT + the resolved BullMQ\n // tokens. Importing token references would force a static dep on the\n // tokens file in this module's import graph; using the existing\n // symbols already in scope is sufficient.\n inject: [DRIZZLE, JOBS_MULTI_TENANT, BULLMQ_CONNECTION, BULLMQ_RESOLVED_CONFIG],\n });\n providers.push({ provide: JOB_RUN_SERVICE, useClass: DrizzleJobRunService });\n providers.push({ provide: JOB_STEP_SERVICE, useClass: DrizzleJobStepService });\n } else {\n providers.push({ provide: JOB_ORCHESTRATOR, useClass: DrizzleJobOrchestrator });\n providers.push({ provide: JOB_RUN_SERVICE, useClass: DrizzleJobRunService });\n providers.push({ provide: JOB_STEP_SERVICE, useClass: DrizzleJobStepService });\n }\n\n const exports = [\n JOB_ORCHESTRATOR,\n JOB_RUN_SERVICE,\n JOB_STEP_SERVICE,\n JOBS_MULTI_TENANT,\n ];\n // BULLMQ-1 — only export the BullMQ tokens when they were actually\n // provided. Nest throws \"exported but not provided\" otherwise. Exported so\n // JobWorkerModule (which imports this module) can read the resolved\n // connection/config to spawn BullMQ workers.\n if (opts.backend === 'bullmq') {\n exports.push(BULLMQ_CONNECTION, BULLMQ_RESOLVED_CONFIG);\n }\n\n return {\n module: JobsDomainModule,\n global: true,\n providers,\n exports,\n };\n }\n}\n","/**\n * JobWorkerModule — `DynamicModule.forRoot({ mode, pools? })` factory that\n * boots one `JobWorker` per active pool and runs the boot-time validator\n * (Drizzle only) (ADR-022, JOB-5).\n *\n * Imports `JobsDomainModule` internally so call sites only need to add\n * `JobWorkerModule.forRoot(...)` to `AppModule.imports` — the protocol\n * tokens become available transitively via `global: true`.\n *\n * Lifecycle (`onModuleInit`, **order-critical** per JOB-5 spec):\n * 1. `loadPoolConfig()` → resolved `PoolConfig`\n * 2. `HandlerRegistry.getAll()` → registered entries\n * 3. Reserved-pool validation → throws `ReservedPoolViolationError`\n * 4. `orchestrator.upsertJobRows(entries, …)` → persist `job` definitions\n * 5. Boot validator (Drizzle only) → throws `BootValidationError`\n * (skipped entirely in memory mode — Q4 resolution 2026-04-19)\n * 6. Spawn one `JobWorker` per active pool → start polling loops\n *\n * `onModuleDestroy` calls `gracefulStop` on each worker (drains in-flight,\n * resets `running` rows, removes SIGTERM handler).\n */\nimport {\n Inject,\n Injectable,\n Logger,\n Module,\n Optional,\n type DynamicModule,\n type OnModuleDestroy,\n type OnModuleInit,\n} from '@nestjs/common';\nimport { ModuleRef } from '@nestjs/core';\nimport { tokenKey } from '../token-key';\nimport { DRIZZLE } from '../../constants/tokens';\nimport type { DrizzleClient } from '../../types/drizzle';\nimport { HandlerRegistry, type HandlerRegistryEntry } from './job-handler.base';\nimport {\n JobsDomainModule,\n type JobsDomainModuleOptions,\n} from './jobs-domain.module';\nimport {\n JOB_ORCHESTRATOR,\n JOB_RUN_SERVICE,\n JOB_STEP_SERVICE,\n} from './jobs-domain.tokens';\nimport type { IJobOrchestrator } from './job-orchestrator.protocol';\nimport type { IJobRunService } from './job-run-service.protocol';\nimport type { IJobStepService } from './job-step-service.protocol';\nimport {\n allNonReservedPoolNames,\n allPoolNames,\n loadPoolConfig,\n type PoolConfig,\n} from './pool-config.loader';\nimport { JobWorker, type JobWorkerOptions } from './job-worker';\n// #6 — `BullMQJobWorker` is lazy-loaded only when `backend: 'bullmq'` is\n// selected (`spawnBullMQWorker` below). The file is filtered out of drizzle/\n// memory installs (see `backendFileFilter`). The `ConnectionOptions` type\n// previously imported from `'bullmq'` is replaced by `BullMqConnectionOptions`\n// from `./bullmq.config` (a self-contained structural mirror that does NOT\n// require the `bullmq` peer dep to type-check).\nimport {\n BULLMQ_CONNECTION,\n BULLMQ_RESOLVED_CONFIG,\n resolvePoolQueueName,\n type BullMqConnectionOptions,\n type BullMqResolvedConfig,\n} from './bullmq.config';\nimport {\n BootValidationError,\n ReservedPoolViolationError,\n} from './jobs-errors';\n\nconst DEFAULT_SHUTDOWN_TIMEOUT_MS = 30_000;\n\nexport interface JobWorkerModuleOptions {\n mode: 'embedded' | 'standalone';\n /**\n * Threads into the internal `JobsDomainModule.forRoot({ backend })`\n * import. Default `'drizzle'`. The boot-time validator runs for both\n * `'drizzle'` and `'bullmq'` (both persist `job` rows to Postgres);\n * `'memory'` skips it.\n */\n backend?: 'drizzle' | 'memory' | 'bullmq';\n /**\n * Active pool names. Defaults to every non-reserved pool in the resolved\n * config (i.e. `interactive`, `batch`, plus any user-defined pools).\n * Operators reduce this to one or two pools per worker process to scale\n * horizontally.\n */\n pools?: string[];\n /**\n * BULLMQ-1 Phase 1 — when `true`, `onModuleInit` activates **every** pool\n * in the resolved config, including the reserved `events_*` lanes. This is\n * how the standalone worker (`worker.ts`) drains bridge wrappers without\n * the consumer hand-listing `...BRIDGE_RESERVED_POOLS`. Mutually exclusive\n * with an explicit `pools` list — when both are set, `pools` wins (explicit\n * beats blanket) and `allPools` is ignored.\n *\n * `BridgeModule`'s reserved-pool guard short-circuits to \"pass\" when this\n * is `true`, since every reserved pool is provably being polled.\n */\n allPools?: boolean;\n /** SIGTERM drain budget. Default 30_000 ms. */\n shutdownTimeoutMs?: number;\n /**\n * Test-only — point the pool config loader at a specific YAML file.\n * Production code reads `${process.cwd()}/codegen.config.yaml`.\n */\n configPath?: string;\n /**\n * Forwarded into the inner `JobsDomainModule.forRoot()` call so the\n * worker module's caller can configure backend extensions in one place.\n */\n domainModuleExtensions?: JobsDomainModuleOptions['extensions'];\n /** Forwarded into `JobsDomainModule.forRoot()`. JOB-8 wires this. */\n multiTenant?: boolean;\n /**\n * Test-only escape hatch — when set, the module uses this factory\n * instead of `new JobWorker(...)` so unit tests can stub the worker\n * without spinning up the polling loop.\n */\n workerFactory?: (options: JobWorkerOptions) => Pick<JobWorker, 'onModuleInit' | 'onModuleDestroy'>;\n}\n\n/**\n * DI token for the resolved `JobWorkerModuleOptions`. Exported so other\n * subsystems can inject it `@Optional()` and inspect the active\n * configuration — e.g. `BridgeModule.onModuleInit` checks\n * `options.pools` against `BRIDGE_RESERVED_POOLS` to fail fast when a\n * reserved pool isn't being polled (BRIDGE-8).\n *\n * ADR-037: namespaced `Symbol.for(...)` (via `tokenKey()`) — matches by value\n * across runtime copies.\n */\nexport const JOB_WORKER_MODULE_OPTIONS = Symbol.for(tokenKey('jobs', 'worker-module-options'));\n\n/**\n * The lifecycle holder. Named `JobWorkerOrchestrator` in the spec to avoid\n * collision with `JobWorker` and `IJobOrchestrator`. Registered as a\n * provider on `JobWorkerModule`; Nest invokes `onModuleInit` /\n * `onModuleDestroy` automatically.\n */\n@Injectable()\nexport class JobWorkerOrchestrator implements OnModuleInit, OnModuleDestroy {\n private readonly logger = new Logger(JobWorkerOrchestrator.name);\n private readonly workers: Array<Pick<JobWorker, 'onModuleInit' | 'onModuleDestroy'>> = [];\n\n constructor(\n @Inject(JOB_ORCHESTRATOR) private readonly orchestrator: IJobOrchestrator,\n @Inject(JOB_RUN_SERVICE) private readonly runService: IJobRunService,\n @Inject(JOB_STEP_SERVICE) private readonly stepService: IJobStepService,\n @Inject(JOB_WORKER_MODULE_OPTIONS)\n private readonly options: JobWorkerModuleOptions,\n /**\n * Drizzle client is only required when `backend === 'drizzle'`. Made\n * `@Optional()` so memory-mode boots in `Test.createTestingModule`\n * without supplying a `DRIZZLE` provider.\n */\n @Optional() @Inject(DRIZZLE) private readonly db: DrizzleClient | null = null,\n private readonly moduleRef?: ModuleRef,\n /**\n * BULLMQ-1 — resolved BullMQ connection + config, only bound when the\n * inner `JobsDomainModule` was booted with `backend: 'bullmq'`. `@Optional()`\n * so drizzle/memory boots see `null`.\n */\n @Optional()\n @Inject(BULLMQ_CONNECTION)\n private readonly bullConnection: BullMqConnectionOptions | null = null,\n @Optional()\n @Inject(BULLMQ_RESOLVED_CONFIG)\n private readonly bullConfig: BullMqResolvedConfig | null = null,\n ) {}\n\n // ============================================================================\n // Lifecycle\n // ============================================================================\n\n async onModuleInit(): Promise<void> {\n const backend = this.options.backend ?? 'drizzle';\n\n // (1) Pool config first — every later step needs the resolved map.\n const poolConfig = loadPoolConfig(this.options.configPath);\n\n // (2) Snapshot the registry. Decorators run at class-load time so the\n // map is fully populated before any module init fires.\n const entries = HandlerRegistry.getAll();\n\n // (3) Reserved-pool validation BEFORE the upsert. Persisting a\n // reserved-pool handler row would leave the DB in a bad state for\n // the next boot to clean up.\n this.assertNoReservedPoolHandlers(entries, poolConfig);\n\n // (4) Upsert `job` definitions. Drizzle: hash-gated `ON CONFLICT DO\n // UPDATE`. Memory: populates `MemoryJobStore.jobs` + handler-class\n // registry.\n const { orphaned } = await this.orchestrator.upsertJobRows(\n entries,\n poolConfig,\n );\n\n // (5) Boot validator — Drizzle only. Memory mode never has DB rows\n // to validate (Q4 resolution 2026-04-19); the equivalent\n // protection is `MemoryJobOrchestrator.start()` throwing\n // `JobTypeNotFoundError` synchronously for unknown types.\n if (backend !== 'memory' && orphaned.length > 0) {\n throw new BootValidationError(orphaned);\n }\n\n // (6) Resolve active pool list and spawn one worker per pool.\n // Precedence: explicit `pools` > `allPools` (incl. reserved) >\n // non-reserved default. BULLMQ-1 Phase 1 adds the `allPools` rung so\n // the standalone worker drains the reserved `events_*` bridge lanes.\n const activePools = this.options.pools\n ? this.options.pools\n : this.options.allPools\n ? allPoolNames(poolConfig)\n : allNonReservedPoolNames(poolConfig);\n\n for (const poolName of activePools) {\n const def = poolConfig.get(poolName);\n if (!def) {\n throw new Error(\n `JobWorkerModule: active pool '${poolName}' is not defined in ` +\n `the resolved pool config. Configured pools: [${[...poolConfig.keys()].join(', ')}].`,\n );\n }\n // `pool` here is the logical pool name (e.g. 'crm_sync') — the same\n // value the orchestrator persists into `job_run.pool` from\n // `@JobHandler.meta.pool`, and therefore the value the worker's\n // claim query filters on. `def.queue` is a display/routing alias\n // (e.g. 'jobs-crm-sync') used by BullMQ-style backends for queue\n // naming; it MUST NOT be passed as the claim-filter pool, or the\n // worker will never match any row and the pool silently never\n // drains. See v0.4.4 fix notes.\n const workerOptions: JobWorkerOptions = {\n pool: poolName,\n concurrency: def.concurrency,\n shutdownTimeoutMs:\n this.options.shutdownTimeoutMs ?? DEFAULT_SHUTDOWN_TIMEOUT_MS,\n };\n const worker = this.options.workerFactory\n ? this.options.workerFactory(workerOptions)\n : backend === 'bullmq'\n ? await this.spawnBullMQWorker(poolName, def.queue, def.concurrency, poolConfig)\n : this.spawnWorker(workerOptions);\n // `JobWorker` extends Nest's lifecycle hooks but the worker isn't\n // a Nest provider here (we manage the array ourselves). Call\n // `onModuleInit` to start the loop. The Drizzle/stub workers return\n // void; `BullMQJobWorker.onModuleInit` is async (it lazily loads the\n // optional `bullmq` package), so we `await` — awaiting a `void` is a\n // harmless no-op for the synchronous workers.\n await worker.onModuleInit();\n this.workers.push(worker);\n this.logger.log(\n `JobWorker started: pool='${poolName}' (queue='${def.queue}') ` +\n `concurrency=${def.concurrency} backend='${backend}'`,\n );\n }\n }\n\n async onModuleDestroy(): Promise<void> {\n // Tear down in reverse order so the most recently started worker\n // drains first — keeps the SIGTERM handler graph predictable.\n for (let i = this.workers.length - 1; i >= 0; i--) {\n const worker = this.workers[i];\n if (!worker) continue;\n try {\n await worker.onModuleDestroy();\n } catch (err) {\n this.logger.error(\n `JobWorker shutdown failed: ${(err as Error).message}`,\n );\n }\n }\n this.workers.length = 0;\n\n // BULLMQ-1 — close the orchestrator's producer-side Queue/FlowProducer\n // connections so the process can exit cleanly. The orchestrator is the\n // BullMQ producer; workers are the consumers (closed above).\n const orch = this.orchestrator as { closeConnections?: () => Promise<void> };\n if (typeof orch.closeConnections === 'function') {\n try {\n await orch.closeConnections();\n } catch (err) {\n this.logger.error(\n `BullMQ orchestrator connection close failed: ${(err as Error).message}`,\n );\n }\n }\n }\n\n // ============================================================================\n // Internals\n // ============================================================================\n\n /**\n * Walk every registered handler; collect any whose declared `pool`\n * targets a reserved pool from the resolved config. If non-empty,\n * throw `ReservedPoolViolationError` with the offender list so the\n * operator sees every violating class on a single boot.\n */\n private assertNoReservedPoolHandlers(\n entries: HandlerRegistryEntry[],\n poolConfig: PoolConfig,\n ): void {\n const offenders: Array<{ handlerClass: string; pool: string }> = [];\n for (const entry of entries) {\n // Framework-owned handlers (`@framework/*` job types) are allowed in\n // reserved pools — that is in fact the entire point of the reserved\n // `events_*` pools (ADR-022 + ADR-023). The reserved-pool guard\n // exists to keep USER handlers out, not the framework's own\n // bridge-delivery handler. BRIDGE-5 introduced this exemption.\n if (entry.type.startsWith('@framework/')) continue;\n const declaredPool = entry.meta.pool ?? 'batch';\n const def = poolConfig.get(declaredPool);\n if (def?.reserved) {\n offenders.push({\n handlerClass: entry.handlerClass.name,\n pool: declaredPool,\n });\n }\n }\n if (offenders.length > 0) {\n throw new ReservedPoolViolationError(offenders);\n }\n }\n\n /**\n * Production worker spawn. `JobWorker` requires `DRIZZLE` so this only\n * succeeds when the module was booted with `backend: 'drizzle'`. Memory\n * mode tests must supply `workerFactory` — the memory backend has no\n * polling loop equivalent (`MemoryJobOrchestrator` is direct-invocation\n * only).\n *\n * We instantiate outside the Nest container because the module spawns\n * N workers from a single options shape, which doesn't fit Nest's\n * \"one provider per token\" model. The dependencies are passed\n * positionally; the constructor's `@Inject` decorators are unused on\n * this path (Nest still uses them when `JobWorker` is a provider — e.g.\n * in JOB-6's standalone `worker.ts` entrypoint).\n */\n private spawnWorker(workerOptions: JobWorkerOptions): JobWorker {\n if (!this.db) {\n throw new Error(\n `JobWorkerModule: in-process worker spawning requires the Drizzle ` +\n `backend (no DRIZZLE provider available). Memory-mode tests must ` +\n `pass 'workerFactory' to inject a stub.`,\n );\n }\n if (!this.moduleRef) {\n throw new Error(\n `JobWorkerModule: ModuleRef not available — cannot construct JobWorker ` +\n `with handler DI support. Ensure the orchestrator is resolved through ` +\n `the Nest container (not instantiated manually in tests).`,\n );\n }\n return new JobWorker(\n this.db,\n this.orchestrator,\n this.runService,\n this.stepService,\n workerOptions,\n this.moduleRef,\n );\n }\n\n /**\n * BULLMQ-1 — spawn a per-pool `BullMQJobWorker`. Requires the Drizzle\n * client (the worker drives `job_run` as the source of truth) AND the\n * resolved BullMQ connection (bound by `JobsDomainModule` when\n * `backend: 'bullmq'`). The queue name is derived identically to the\n * orchestrator's `dispatch` via `resolvePoolQueueName(pool, …)` so producer\n * and consumer agree.\n */\n /**\n * #6 — async + dynamic-import. The `job-worker.bullmq-backend.ts` file is\n * filtered out of the vendor set for drizzle/memory installs (no `bullmq`\n * peer dep needed). The non-literal import specifier makes TS treat the\n * module as `any` so the consumer's tsc never tries to resolve an absent\n * file. This method is only entered when `backend === 'bullmq'` — at which\n * point the file IS vendored.\n */\n private async spawnBullMQWorker(\n pool: string,\n _queueAlias: string,\n concurrency: number,\n poolConfig: PoolConfig,\n ): Promise<Pick<JobWorker, 'onModuleInit' | 'onModuleDestroy'>> {\n if (!this.db) {\n throw new Error(\n `JobWorkerModule: BullMQ worker spawning requires the Drizzle client ` +\n `(no DRIZZLE provider available) — job_run remains the source of truth.`,\n );\n }\n if (!this.bullConnection) {\n throw new Error(\n `JobWorkerModule: BullMQ worker spawning requires a resolved ` +\n `BULLMQ_CONNECTION. Ensure JobsDomainModule was booted with ` +\n `backend: 'bullmq'.`,\n );\n }\n if (!this.moduleRef) {\n throw new Error(\n `JobWorkerModule: ModuleRef not available — cannot construct ` +\n `BullMQJobWorker with handler DI support.`,\n );\n }\n const queueName = resolvePoolQueueName(pool, this.bullConfig, poolConfig);\n const specifier = './job-worker.bullmq-backend';\n const mod = (await import(specifier)) as {\n BullMQJobWorker: new (...args: unknown[]) => Pick<\n JobWorker,\n 'onModuleInit' | 'onModuleDestroy'\n >;\n };\n return new mod.BullMQJobWorker(\n this.db,\n this.orchestrator,\n this.stepService,\n {\n pool,\n queueName,\n concurrency,\n connection: this.bullConnection,\n },\n this.moduleRef,\n );\n }\n}\n\n@Module({})\nexport class JobWorkerModule {\n static forRoot(opts: JobWorkerModuleOptions): DynamicModule {\n return {\n module: JobWorkerModule,\n imports: [\n JobsDomainModule.forRoot({\n backend: opts.backend ?? 'drizzle',\n extensions: opts.domainModuleExtensions,\n multiTenant: opts.multiTenant,\n }),\n ],\n providers: [\n { provide: JOB_WORKER_MODULE_OPTIONS, useValue: opts },\n JobWorkerOrchestrator,\n ],\n // BULLMQ-1 Phase 1 — export the options token so `BridgeModule`'s\n // reserved-pool guard (`onModuleInit`) can actually inject it.\n // Previously `exports: []` left the `@Optional()` inject resolving to\n // `undefined` and the guard silently no-opped (a dead check). With the\n // token exported the guard fires for real; consumers that omit the\n // reserved pools (and don't set `allPools`) now fail fast with\n // `BridgeReservedPoolsNotPolledError` — which is correct.\n exports: [JOB_WORKER_MODULE_OPTIONS],\n };\n }\n}\n","/**\n * Injection token for the cache service.\n *\n * Usage in use cases:\n * ```typescript\n * constructor(@Inject(CACHE) private readonly cache: ICacheService) {}\n * ```\n *\n * Services may also inject CACHE for reads (get, has) per ADR-003.\n *\n * ADR-037: namespaced `Symbol.for(...)` key (via `tokenKey()`) so the token matches\n * by value across import boundaries (package vs vendored runtime copy).\n */\nimport { tokenKey } from '../token-key';\n\nexport const CACHE = Symbol.for(tokenKey('cache', 'cache'));\n\n/**\n * Injection token for the default TTL (in seconds) passed from CacheModule.forRoot().\n * Optional — omit for no-expiry behavior.\n */\nexport const CACHE_DEFAULT_TTL = Symbol.for(tokenKey('cache', 'default-ttl'));\n","/**\n * CacheModule — DynamicModule factory for the cache subsystem.\n *\n * Usage in AppModule:\n * ```typescript\n * CacheModule.forRoot({ backend: 'drizzle', defaultTtl: 300 })\n * ```\n *\n * Usage in tests:\n * ```typescript\n * CacheModule.forRoot({ backend: 'memory' })\n * ```\n *\n * `global: true` means any module that needs ICacheService can inject CACHE\n * directly without importing CacheModule. Register once in AppModule.\n *\n * The drizzle backend requires DRIZZLE to be provided globally (e.g., via DatabaseModule).\n *\n * Async configuration (`forRootAsync`):\n * The async factory returns `CacheModuleOptions`; the CACHE provider then\n * receives DRIZZLE (for the drizzle backend) through Nest DI rather than\n * hand-constructing with `null` — see issue #108 which flagged the same\n * shape in `EventsModule.forRootAsync`. DRIZZLE is injected as optional\n * so memory-backend consumers are not required to wire DatabaseModule.\n */\nimport { Module, type DynamicModule } from '@nestjs/common';\nimport { CACHE, CACHE_DEFAULT_TTL } from './cache.tokens';\nimport { DRIZZLE } from '../../constants/tokens';\nimport type { DrizzleClient } from '../../types/drizzle';\nimport { DrizzleCacheService } from './cache.drizzle-backend';\nimport { MemoryCacheService } from './cache.memory-backend';\n\nexport interface CacheModuleOptions {\n backend: 'drizzle' | 'memory';\n /** Default TTL in seconds for entries that don't specify their own TTL. Null = no expiry. */\n defaultTtl?: number;\n}\n\nexport interface CacheModuleAsyncOptions {\n useFactory: (...args: unknown[]) => Promise<CacheModuleOptions> | CacheModuleOptions;\n inject?: unknown[];\n imports?: unknown[];\n}\n\n/** String token for the resolved CacheModuleOptions in the async path. */\nconst CACHE_MODULE_OPTIONS = 'CACHE_MODULE_OPTIONS' as const;\n\nfunction buildCacheAsync(\n options: CacheModuleOptions,\n db: DrizzleClient | null,\n): DrizzleCacheService | MemoryCacheService {\n const defaultTtl = options.defaultTtl ?? null;\n if (options.backend === 'drizzle') {\n if (!db) {\n throw new Error(\n \"CacheModule.forRootAsync: backend: 'drizzle' selected but DRIZZLE provider is not available. \" +\n 'Ensure DatabaseModule (or another provider exposing DRIZZLE) is imported before CacheModule.forRootAsync.',\n );\n }\n return new DrizzleCacheService(db, defaultTtl);\n }\n return new MemoryCacheService(defaultTtl);\n}\n\n@Module({})\nexport class CacheModule {\n static forRootAsync(asyncOptions: CacheModuleAsyncOptions): DynamicModule {\n return {\n module: CacheModule,\n global: true,\n imports: (asyncOptions.imports ?? []) as Parameters<typeof Module>[0]['imports'],\n providers: [\n {\n provide: CACHE_MODULE_OPTIONS,\n useFactory: asyncOptions.useFactory,\n inject: (asyncOptions.inject ?? []) as (string | symbol | Function)[],\n },\n {\n provide: CACHE,\n useFactory: (options: CacheModuleOptions, db: DrizzleClient | null) =>\n buildCacheAsync(options, db),\n inject: [CACHE_MODULE_OPTIONS, { token: DRIZZLE, optional: true }],\n },\n // Alias the concrete classes to CACHE for typed injection.\n { provide: DrizzleCacheService, useExisting: CACHE },\n { provide: MemoryCacheService, useExisting: CACHE },\n ],\n exports: [CACHE],\n };\n }\n\n static forRoot(options: CacheModuleOptions = { backend: 'drizzle' }): DynamicModule {\n const ConcreteClass = options.backend === 'drizzle' ? DrizzleCacheService : MemoryCacheService;\n\n const providers = options.defaultTtl !== undefined\n ? [\n // Register the concrete class as the canonical instance\n ConcreteClass,\n { provide: CACHE_DEFAULT_TTL, useValue: options.defaultTtl },\n // CACHE token points to the same instance — no duplicate\n { provide: CACHE, useExisting: ConcreteClass },\n ]\n : [\n ConcreteClass,\n { provide: CACHE, useExisting: ConcreteClass },\n ];\n\n return {\n module: CacheModule,\n global: true,\n providers,\n exports: [CACHE],\n };\n }\n}\n","/**\n * DrizzleCacheService — Postgres-backed ICacheService via Drizzle ORM.\n *\n * Storage: `cache_entries` table with key (text pk), value (jsonb), expiresAt (timestamp).\n * TTL enforcement: reads filter by `expiresAt > now() OR expiresAt IS NULL`.\n * Prefix invalidation: `DELETE WHERE key LIKE 'escaped_prefix%'`.\n *\n * Lifecycle:\n * - OnModuleInit: starts periodic cleanup of expired entries.\n * Uses the Jobs subsystem if available (optional injection); falls back to setInterval.\n * - OnModuleDestroy: clears the setInterval timer if used.\n *\n * Error behavior per ADR-008:\n * - get() / has() return null/false on any error (never throw for reads).\n * - set() / delete() / invalidateByPrefix() throw on failure.\n */\nimport { Injectable, Inject, Optional, type OnModuleInit, type OnModuleDestroy } from '@nestjs/common';\nimport { gt, or, like, sql, eq } from 'drizzle-orm';\nimport type { DrizzleClient } from '../../types/drizzle';\nimport type { ICacheService } from './cache.protocol';\nimport { cacheEntries } from './cache.schema';\nimport { DRIZZLE } from '../../constants/tokens';\nimport { CACHE_DEFAULT_TTL } from './cache.tokens';\n\n// Re-export for backward compatibility\nexport { CACHE_DEFAULT_TTL } from './cache.tokens';\n\n/** Cleanup interval in milliseconds when jobs subsystem is unavailable. */\nconst CLEANUP_INTERVAL_MS = 5 * 60 * 1000; // 5 minutes\n\n@Injectable()\nexport class DrizzleCacheService implements ICacheService, OnModuleInit, OnModuleDestroy {\n private cleanupTimer: ReturnType<typeof setInterval> | null = null;\n /** In-flight getOrSet promises — keyed by cache key to deduplicate stampedes. */\n private readonly inflight = new Map<string, Promise<unknown>>();\n\n constructor(\n @Inject(DRIZZLE) private readonly db: DrizzleClient,\n @Optional() @Inject(CACHE_DEFAULT_TTL) private readonly defaultTtl: number | null = null,\n ) {}\n\n async onModuleInit(): Promise<void> {\n this.cleanupTimer = setInterval(() => {\n void this.deleteExpired();\n }, CLEANUP_INTERVAL_MS);\n }\n\n async onModuleDestroy(): Promise<void> {\n if (this.cleanupTimer !== null) {\n clearInterval(this.cleanupTimer);\n this.cleanupTimer = null;\n }\n }\n\n async get<T = unknown>(key: string): Promise<T | null> {\n try {\n const rows = await this.db\n .select()\n .from(cacheEntries)\n .where(\n sql`${cacheEntries.key} = ${key} AND (${cacheEntries.expiresAt} IS NULL OR ${cacheEntries.expiresAt} > now())`,\n )\n .limit(1);\n\n if (rows.length === 0) return null;\n return rows[0]!.value as T;\n } catch {\n return null;\n }\n }\n\n async set<T = unknown>(key: string, value: T, ttlSeconds?: number): Promise<void> {\n const effectiveTtl = ttlSeconds ?? this.defaultTtl ?? null;\n const expiresAt =\n effectiveTtl !== null\n ? new Date(Date.now() + effectiveTtl * 1000)\n : null;\n\n const jsonValue = value as Parameters<typeof cacheEntries.value.mapFromDriverValue>[0];\n await this.db\n .insert(cacheEntries)\n .values({ key, value: jsonValue, expiresAt })\n .onConflictDoUpdate({\n target: cacheEntries.key,\n set: { value: jsonValue, expiresAt },\n });\n }\n\n async delete(key: string): Promise<void> {\n await this.db.delete(cacheEntries).where(eq(cacheEntries.key, key));\n }\n\n async invalidateByPrefix(prefix: string): Promise<number> {\n // Escape LIKE wildcards to prevent prefix characters from matching unintended entries\n const escaped = prefix.replace(/%/g, '\\\\%').replace(/_/g, '\\\\_');\n const result = await this.db\n .delete(cacheEntries)\n .where(like(cacheEntries.key, `${escaped}%`))\n .returning({ key: cacheEntries.key });\n return result.length;\n }\n\n async has(key: string): Promise<boolean> {\n try {\n const result = await this.get(key);\n return result !== null;\n } catch {\n return false;\n }\n }\n\n async getOrSet<T = unknown>(\n key: string,\n factory: () => Promise<T>,\n ttlSeconds?: number,\n ): Promise<T> {\n // Fast path: cache hit\n const cached = await this.get<T>(key);\n if (cached !== null) return cached;\n\n // Stampede protection: if another call is already computing this key, reuse its promise\n const existing = this.inflight.get(key) as Promise<T> | undefined;\n if (existing !== undefined) return existing;\n\n const promise = factory().then(async (value) => {\n await this.set(key, value, ttlSeconds);\n return value;\n }).finally(() => {\n this.inflight.delete(key);\n });\n\n this.inflight.set(key, promise as Promise<unknown>);\n return promise;\n }\n\n /** Remove all expired entries. Called by the cleanup timer. */\n private async deleteExpired(): Promise<void> {\n try {\n await this.db\n .delete(cacheEntries)\n .where(\n or(\n gt(sql`now()`, cacheEntries.expiresAt),\n ),\n );\n } catch {\n // Cleanup failures are non-fatal — stale rows are filtered at read time\n }\n }\n}\n","/**\n * Drizzle schema for the cache_entries table.\n *\n * This table backs the DrizzleCacheService. TTL is enforced by filtering\n * on expiresAt at read time; a periodic cleanup job removes stale rows.\n *\n * Indexes:\n * - PRIMARY KEY on key (point-lookup)\n * - (expiresAt) for the cleanup query\n */\nimport { pgTable, text, jsonb, timestamp } from 'drizzle-orm/pg-core';\nimport type { InferSelectModel } from 'drizzle-orm';\n\nexport const cacheEntries = pgTable(\n 'cache_entries',\n {\n /** Cache key — primary key, text (not uuid) to support arbitrary key namespacing. */\n key: text('key').primaryKey(),\n /** Cached value serialised as JSONB. */\n value: jsonb('value').notNull(),\n /** NULL means the entry never expires. */\n expiresAt: timestamp('expires_at', { withTimezone: true }),\n },\n // Index: add (expires_at) via migration for cleanup queries\n);\n\nexport type CacheEntry = InferSelectModel<typeof cacheEntries>;\n","/**\n * MemoryCacheService — Map-backed ICacheService for tests and development.\n *\n * TTL is enforced via setTimeout — expired entries are deleted from the Map\n * when the timer fires. get() / has() also check the expiry time defensively\n * in case the timer fires late.\n *\n * No lifecycle hooks required — all state is in-process.\n *\n * Error behavior:\n * - get() / has() never throw; they return null/false.\n * - set() / delete() / invalidateByPrefix() throw on failure (consistent with protocol).\n */\nimport { Injectable, Inject, Optional } from '@nestjs/common';\nimport type { ICacheService } from './cache.protocol';\nimport { CACHE_DEFAULT_TTL } from './cache.tokens';\n\ninterface CacheRecord {\n value: unknown;\n expiresAt: number | null; // epoch ms, or null for no expiry\n}\n\n@Injectable()\nexport class MemoryCacheService implements ICacheService {\n private readonly store = new Map<string, CacheRecord>();\n private readonly timers = new Map<string, ReturnType<typeof setTimeout>>();\n /** In-flight getOrSet promises — keyed by cache key to deduplicate stampedes. */\n private readonly inflight = new Map<string, Promise<unknown>>();\n\n constructor(\n @Optional() @Inject(CACHE_DEFAULT_TTL) private readonly defaultTtl: number | null = null,\n ) {}\n\n async get<T = unknown>(key: string): Promise<T | null> {\n const record = this.store.get(key);\n if (!record) return null;\n if (record.expiresAt !== null && record.expiresAt <= Date.now()) {\n this.evict(key);\n return null;\n }\n return record.value as T;\n }\n\n async set<T = unknown>(key: string, value: T, ttlSeconds?: number): Promise<void> {\n const effectiveTtl = ttlSeconds ?? this.defaultTtl ?? null;\n\n // Clear any existing timer for this key\n this.clearTimer(key);\n\n const expiresAt = effectiveTtl !== null ? Date.now() + effectiveTtl * 1000 : null;\n this.store.set(key, { value, expiresAt });\n\n if (effectiveTtl !== null) {\n const timer = setTimeout(() => this.evict(key), effectiveTtl * 1000);\n this.timers.set(key, timer);\n }\n }\n\n async delete(key: string): Promise<void> {\n this.evict(key);\n }\n\n async invalidateByPrefix(prefix: string): Promise<number> {\n let count = 0;\n for (const key of this.store.keys()) {\n if (key.startsWith(prefix)) {\n this.evict(key);\n count++;\n }\n }\n return count;\n }\n\n async has(key: string): Promise<boolean> {\n const value = await this.get(key);\n return value !== null;\n }\n\n async getOrSet<T = unknown>(\n key: string,\n factory: () => Promise<T>,\n ttlSeconds?: number,\n ): Promise<T> {\n // Fast path: cache hit\n const cached = await this.get<T>(key);\n if (cached !== null) return cached;\n\n // Stampede protection: if another call is already computing this key, reuse its promise\n const existing = this.inflight.get(key) as Promise<T> | undefined;\n if (existing !== undefined) return existing;\n\n const promise = factory().then(async (value) => {\n await this.set(key, value, ttlSeconds);\n return value;\n }).finally(() => {\n this.inflight.delete(key);\n });\n\n this.inflight.set(key, promise as Promise<unknown>);\n return promise;\n }\n\n /** Remove a key from store and cancel its expiry timer. */\n private evict(key: string): void {\n this.store.delete(key);\n this.clearTimer(key);\n }\n\n private clearTimer(key: string): void {\n const timer = this.timers.get(key);\n if (timer !== undefined) {\n clearTimeout(timer);\n this.timers.delete(key);\n }\n }\n}\n","/**\n * Storage subsystem — local filesystem backend\n *\n * Writes files to `{basePath}/{key}` on the local filesystem.\n * Suitable for development only — use an S3/GCS backend in production.\n *\n * - Creates intermediate directories automatically (mkdirSync recursive)\n * - getUrl returns a `file://` URI pointing to the absolute path\n * - All methods throw on failure\n * - resolvePath validates against path traversal attacks\n */\nimport {\n createReadStream,\n existsSync,\n mkdirSync,\n readdirSync,\n readFileSync,\n statSync,\n unlinkSync,\n writeFileSync,\n} from 'fs';\nimport { dirname, join, relative, resolve, sep } from 'path';\nimport { Readable } from 'stream';\nimport type { IStorageService } from './storage.protocol';\nimport { toBuffer } from './storage.utils';\n\nexport class LocalStorageBackend implements IStorageService {\n private readonly basePath: string;\n\n constructor(basePath: string = './storage') {\n this.basePath = resolve(basePath);\n }\n\n async upload(key: string, data: Buffer | ReadableStream, contentType?: string): Promise<string> {\n const filePath = this.resolvePath(key);\n mkdirSync(dirname(filePath), { recursive: true });\n\n const buffer = await toBuffer(data);\n writeFileSync(filePath, buffer);\n return key;\n }\n\n async download(key: string): Promise<Buffer> {\n const filePath = this.resolvePath(key);\n if (!existsSync(filePath)) {\n throw new Error(`Storage: file not found: ${key}`);\n }\n return readFileSync(filePath);\n }\n\n async delete(key: string): Promise<void> {\n const filePath = this.resolvePath(key);\n if (!existsSync(filePath)) {\n throw new Error(`Storage: file not found: ${key}`);\n }\n unlinkSync(filePath);\n }\n\n async getUrl(key: string, _expiresInSeconds?: number): Promise<string> {\n const filePath = this.resolvePath(key);\n if (!existsSync(filePath)) {\n throw new Error(`Storage: file not found: ${key}`);\n }\n return `file://${filePath}`;\n }\n\n async exists(key: string): Promise<boolean> {\n try {\n return existsSync(this.resolvePath(key));\n } catch {\n // resolvePath throws on traversal attempt — treat as non-existent\n return false;\n }\n }\n\n async list(prefix?: string): Promise<string[]> {\n const keys = this.listRecursive(this.basePath);\n if (prefix === undefined) return keys;\n return keys.filter((k) => k.startsWith(prefix));\n }\n\n async downloadStream(key: string): Promise<ReadableStream> {\n const filePath = this.resolvePath(key);\n if (!existsSync(filePath)) {\n throw new Error(`Storage: file not found: ${key}`);\n }\n const nodeStream = createReadStream(filePath);\n return Readable.toWeb(nodeStream) as ReadableStream;\n }\n\n private resolvePath(key: string): string {\n const resolved = resolve(this.basePath, key);\n if (!resolved.startsWith(this.basePath + sep)) {\n throw new Error(`Invalid storage key (path traversal attempt): ${key}`);\n }\n return resolved;\n }\n\n /** Recursively list all files under dir, returning keys relative to basePath. */\n private listRecursive(dir: string): string[] {\n if (!existsSync(dir)) return [];\n const keys: string[] = [];\n for (const entry of readdirSync(dir, { withFileTypes: true })) {\n const full = join(dir, entry.name);\n if (entry.isDirectory()) {\n keys.push(...this.listRecursive(full));\n } else {\n keys.push(relative(this.basePath, full));\n }\n }\n return keys;\n }\n}\n","/**\n * Storage subsystem — shared utilities\n */\n\n/**\n * Convert a Buffer or Web ReadableStream to a Node.js Buffer.\n */\nexport async function toBuffer(data: Buffer | ReadableStream): Promise<Buffer> {\n if (Buffer.isBuffer(data)) {\n return data;\n }\n const reader = (data as ReadableStream<Uint8Array>).getReader();\n const chunks: Uint8Array[] = [];\n while (true) {\n const { done, value } = await reader.read();\n if (done) break;\n if (value) chunks.push(value);\n }\n return Buffer.concat(chunks);\n}\n","/**\n * Storage subsystem — in-memory backend\n *\n * Stores files as Buffers in a Map. Intended for unit tests only.\n * All state is lost when the process exits.\n *\n * - getUrl returns `memory://{key}` (not a real URL, useful for assertions)\n * - All methods throw on failure (missing keys, etc.)\n */\nimport type { IStorageService } from './storage.protocol';\nimport { toBuffer } from './storage.utils';\n\ninterface MemoryEntry {\n data: Buffer;\n contentType?: string;\n}\n\nexport class MemoryStorageBackend implements IStorageService {\n private readonly store = new Map<string, MemoryEntry>();\n\n async upload(key: string, data: Buffer | ReadableStream, contentType?: string): Promise<string> {\n const buffer = await toBuffer(data);\n this.store.set(key, { data: buffer, contentType });\n return key;\n }\n\n async download(key: string): Promise<Buffer> {\n const entry = this.store.get(key);\n if (!entry) {\n throw new Error(`Storage: file not found: ${key}`);\n }\n return entry.data;\n }\n\n async delete(key: string): Promise<void> {\n if (!this.store.has(key)) {\n throw new Error(`Storage: file not found: ${key}`);\n }\n this.store.delete(key);\n }\n\n async getUrl(key: string, _expiresInSeconds?: number): Promise<string> {\n if (!this.store.has(key)) {\n throw new Error(`Storage: file not found: ${key}`);\n }\n return `memory://${key}`;\n }\n\n async exists(key: string): Promise<boolean> {\n return this.store.has(key);\n }\n\n async list(prefix?: string): Promise<string[]> {\n const keys = Array.from(this.store.keys());\n if (prefix === undefined) return keys;\n return keys.filter((k) => k.startsWith(prefix));\n }\n\n async downloadStream(key: string): Promise<ReadableStream> {\n const buffer = await this.download(key);\n return new ReadableStream<Uint8Array>({\n start(controller) {\n controller.enqueue(new Uint8Array(buffer));\n controller.close();\n },\n });\n }\n\n /** Clear all stored files. Useful for test teardown. */\n clear(): void {\n this.store.clear();\n }\n\n /** Return number of stored files. Useful for test assertions. */\n size(): number {\n return this.store.size;\n }\n}\n","/**\n * Storage subsystem — NestJS module factory\n *\n * Register once in AppModule (global: true means all other modules can inject\n * STORAGE without importing StorageModule themselves):\n *\n * ```typescript\n * // app.module.ts\n * @Module({\n * imports: [\n * StorageModule.forRoot({ backend: 'local', basePath: './uploads' }),\n * ],\n * })\n * export class AppModule {}\n * ```\n *\n * Swap to memory backend in tests:\n * ```typescript\n * Test.createTestingModule({\n * imports: [StorageModule.forRoot({ backend: 'memory' })],\n * });\n * ```\n */\nimport { type DynamicModule, Module } from '@nestjs/common';\nimport { LocalStorageBackend } from './storage.local-backend';\nimport { MemoryStorageBackend } from './storage.memory-backend';\nimport { STORAGE } from './storage.tokens';\n\nexport interface StorageModuleOptions {\n /** Which backend to activate. */\n backend: 'local' | 'memory';\n /**\n * Base path for the local backend (resolved to an absolute path).\n * Ignored when backend is 'memory'. Defaults to `./storage`.\n */\n basePath?: string;\n}\n\n@Module({})\nexport class StorageModule {\n static forRoot(options: StorageModuleOptions = { backend: 'local' }): DynamicModule {\n const provider =\n options.backend === 'local'\n ? {\n provide: STORAGE,\n useFactory: () => new LocalStorageBackend(options.basePath ?? './storage'),\n }\n : {\n provide: STORAGE,\n useClass: MemoryStorageBackend,\n };\n\n return {\n module: StorageModule,\n global: true,\n providers: [provider],\n exports: [STORAGE],\n };\n }\n}\n","/**\n * Injection token for the storage service.\n *\n * Usage in use cases:\n * ```typescript\n * constructor(@Inject(STORAGE) private readonly storage: IStorageService) {}\n * ```\n *\n * ADR-037: namespaced `Symbol.for(...)` key (via `tokenKey()`) so the token matches\n * by value across import boundaries (package vs vendored runtime copy).\n */\nimport { tokenKey } from '../token-key';\n\nexport const STORAGE = Symbol.for(tokenKey('storage', 'storage'));\n","/**\n * Observability combiner subsystem — DI tokens (ADR-025, OBS-5).\n *\n * String constants (not Symbols), matching the events / bridge / integration\n * convention. The jobs subsystem uses Symbols for its analogous tokens;\n * observability stays internally consistent with its sibling combiner\n * (bridge) because the two are structurally paired (ADR-025).\n *\n * Usage in consumers:\n * ```ts\n * constructor(@Inject(OBSERVABILITY) private readonly obs: IObservability) {}\n * ```\n */\n\n/**\n * Token for the `IObservability` composer facade (OBS-5). Resolves to the\n * single `ObservabilityService` instance registered by\n * `ObservabilityModule.forRoot(...)`.\n */\nexport const OBSERVABILITY = 'OBSERVABILITY' as const;\n\n/**\n * Token for the resolved `ObservabilityModuleOptions` object. Provided by\n * `ObservabilityModule.forRoot(...)`. Reserved for phase 2 — the current\n * options shape is empty; OBS-6 will extend it with a `reporters` field.\n */\nexport const OBSERVABILITY_MODULE_OPTIONS = 'OBSERVABILITY_MODULE_OPTIONS' as const;\n","/**\n * ObservabilityModule — combiner subsystem (ADR-025, OBS-5, OBS-6).\n *\n * Composes the jobs, bridge, and integration read ports into a single\n * `IObservability` facade. Owned by no sibling subsystem; it consumes\n * their tokens via DI, which the consumer app wires by registering the\n * sibling modules in the right order (like BridgeModule — the named\n * precedent in ADR-025).\n *\n * Consumer wiring (register AFTER the composed sibling modules):\n * ```ts\n * @Module({\n * imports: [\n * EventsModule.forRoot({ backend: 'drizzle' }),\n * JobsDomainModule.forRoot({ backend: 'drizzle' }),\n * BridgeModule.forRoot({ backend: 'drizzle' }),\n * IntegrationModule.forRoot({ backend: 'drizzle' }),\n * ObservabilityModule.forRoot({\n * reporters: {\n * bridgeMetrics: {\n * enabled: true,\n * intervalMs: 60_000,\n * windowHours: 1,\n * },\n * },\n * }),\n * ],\n * })\n * class AppModule {}\n * ```\n *\n * # No `backend` option — intentional\n *\n * Unlike ADR-008 infrastructure subsystems (events / jobs / cache /\n * storage), observability is a combiner per ADR-025 and owns no durable\n * state. The \"backend\" is whichever backends the composed subsystems are\n * running — portability is inherited, not declared. See ADR-025 §4 (when\n * to pick combiner vs. infrastructure) and\n * `.claude/skills/observability/SKILL.md` §1.\n *\n * # Graceful sibling absence\n *\n * The consumed sibling tokens are `@Optional()` inside\n * `ObservabilityService`. An app that only installed a subset of the\n * composed subsystems can still register `ObservabilityModule`; the\n * methods whose sibling is missing return empty shapes.\n *\n * # Reporters (OBS-6)\n *\n * Internal consumers of the `OBSERVABILITY` facade — auto-registered\n * when the matching `reporters.*` key is present and enabled. Reporters\n * are NOT added to `exports`; they are a module-internal concern.\n * Consumers configure them via options; they never import the reporter\n * classes directly.\n */\nimport { Module, type DynamicModule, type Provider } from '@nestjs/common';\n\nimport {\n OBSERVABILITY,\n OBSERVABILITY_MODULE_OPTIONS,\n} from './observability.tokens';\nimport { ObservabilityService } from './observability.service';\nimport { BridgeMetricsReporter } from './reporters/bridge-metrics.reporter';\n\n/**\n * Config for the bridge-delivery sampler (OBS-6). All fields are required\n * when `enabled: true` — the config is declarative and explicit; there\n * are no hidden defaults. Lives on the module (not the reporter file) so\n * the module's options type stays the single authoritative schema for\n * everything `forRoot` accepts.\n */\nexport interface BridgeMetricsReporterConfig {\n /** Master switch. Reporter is only registered as a provider when this\n * is `true` (see `forRoot`). */\n enabled: boolean;\n /** Sampling period in ms. Must be `> 0` when `enabled: true`. */\n intervalMs: number;\n /** Trailing window (hours) passed to `getBridgeDeliveryHistogram`.\n * Must be `> 0` when `enabled: true`. */\n windowHours: number;\n /** Forwarded verbatim to `IObservability.getBridgeDeliveryHistogram`.\n * - `undefined` — sibling default semantics\n * - `null` — explicit cross-tenant match\n * - `string` — filter to that single tenant */\n tenantId?: string | null;\n}\n\n/**\n * Named-map of reporter configs. Named, not array, so consumers can toggle\n * individual reporters by key without juggling order and so future reporters\n * can be added without breaking existing configs.\n */\nexport interface ObservabilityReportersOptions {\n bridgeMetrics?: BridgeMetricsReporterConfig;\n}\n\n/**\n * Options for `ObservabilityModule.forRoot()`. Currently only `reporters`;\n * room to grow (sampling, exporters) without changing the module signature.\n */\nexport interface ObservabilityModuleOptions {\n reporters?: ObservabilityReportersOptions;\n}\n\n@Module({})\nexport class ObservabilityModule {\n static forRoot(options: ObservabilityModuleOptions = {}): DynamicModule {\n const providers: Provider[] = [\n // Expose the resolved options so internal reporters can read their\n // own config via `OBSERVABILITY_MODULE_OPTIONS`.\n { provide: OBSERVABILITY_MODULE_OPTIONS, useValue: options },\n // Register the concrete class as the canonical instance.\n ObservabilityService,\n // OBSERVABILITY token points at the same instance — consumers inject\n // the token, not the class, per ADR-025 §Shape (index.ts does NOT\n // export `ObservabilityService`).\n { provide: OBSERVABILITY, useExisting: ObservabilityService },\n ];\n\n // Reporters: auto-registered when enabled, not added to `exports`.\n // They are internal consumers of OBSERVABILITY; consumers configure\n // them via options rather than importing the classes.\n if (options.reporters?.bridgeMetrics?.enabled === true) {\n providers.push(BridgeMetricsReporter);\n }\n\n return {\n module: ObservabilityModule,\n global: true,\n providers,\n exports: [OBSERVABILITY, OBSERVABILITY_MODULE_OPTIONS],\n };\n }\n}\n","/**\n * ObservabilityService — `IObservability` combiner implementation\n * (ADR-025, OBS-5).\n *\n * Composes read methods across the jobs, bridge, and integration subsystems via\n * DI. Owns no state, no schema, no SQL. Every method is a one-line\n * delegation to the sibling port that already encodes the semantics.\n *\n * # Missing-port degradation\n *\n * Every sibling is injected with `@Optional()`. When the consumer's app\n * has not wired a given subsystem, the corresponding field is `undefined`\n * and the delegating method returns an empty shape:\n * - array methods return `[]`\n * - `getBridgeDeliveryHistogram` returns `{ pending: 0, delivered: 0,\n * skipped: 0, failed: 0 }` (matches the bridge protocol's fixed-keys\n * contract so consumers can render a 4-row chart unconditionally).\n *\n * Graceful absence is the whole point of the combiner pattern (ADR-025\n * §Shape, constraint 3) — a consumer that only installed the jobs\n * subsystem can still inject `OBSERVABILITY` and get useful job reads\n * without wiring the rest.\n *\n * # Multi-tenancy\n *\n * `tenantId` passes VERBATIM from the public method to the owning port.\n * `ObservabilityService` never re-implements tenant filtering. See\n * `.claude/skills/observability/SKILL.md` §3 and ADR-025.\n */\nimport { Inject, Injectable, Optional } from '@nestjs/common';\n\nimport { JOB_RUN_SERVICE } from '../jobs/jobs-domain.tokens';\nimport type {\n IJobRunService,\n JobRunFailure,\n JobRunPage,\n JobRunSummary,\n ListJobRunsQuery,\n PoolStatusCount,\n} from '../jobs/job-run-service.protocol';\n\nimport { EVENT_READ_PORT } from '../events/events.tokens';\nimport type {\n EventPage,\n EventSummary,\n IEventReadPort,\n ListEventsQuery,\n} from '../events/event-read.protocol';\n\nimport { BRIDGE_DELIVERY_REPO } from '../bridge/bridge.tokens';\nimport type { IJobBridge, StatusHistogram } from '../bridge/bridge.protocol';\n\nimport { INTEGRATION_CURSOR_STORE, INTEGRATION_RUN_RECORDER } from '../integration/integration.tokens';\nimport type {\n IIntegrationRunRecorder,\n IntegrationRunSummary,\n} from '../integration/integration-run-recorder.protocol';\nimport type {\n CursorSnapshot,\n ICursorStore,\n} from '../integration/integration-cursor-store.protocol';\n\nimport type {\n CorrelationTimeline,\n CorrelationTimelineEntry,\n IObservability,\n} from './observability.protocol';\n\n/**\n * Safety bound on how many pages the correlation timeline will walk when\n * draining a sibling port. A single run tree producing more than\n * 50 pages × default page size of correlated rows is pathological; cap to\n * keep the stitch bounded rather than unbounded-loop on bad data.\n */\nconst MAX_TIMELINE_PAGES = 50;\n\n@Injectable()\nexport class ObservabilityService implements IObservability {\n /**\n * All-zero histogram used when the bridge subsystem is absent. Matches\n * the bridge protocol's \"fixed keys, zero-filled\" contract so consumers\n * never branch on presence.\n */\n private static readonly EMPTY_HISTOGRAM: StatusHistogram = {\n pending: 0,\n delivered: 0,\n skipped: 0,\n failed: 0,\n };\n\n /** Empty page used when a sibling read port is absent. */\n private static readonly EMPTY_JOB_RUN_PAGE: JobRunPage = {\n items: [],\n nextCursor: null,\n };\n private static readonly EMPTY_EVENT_PAGE: EventPage = {\n items: [],\n nextCursor: null,\n };\n\n constructor(\n @Optional()\n @Inject(JOB_RUN_SERVICE)\n private readonly jobRuns?: IJobRunService,\n @Optional()\n @Inject(BRIDGE_DELIVERY_REPO)\n private readonly bridge?: IJobBridge,\n @Optional()\n @Inject(INTEGRATION_RUN_RECORDER)\n private readonly integrationRuns?: IIntegrationRunRecorder,\n @Optional()\n @Inject(INTEGRATION_CURSOR_STORE)\n private readonly cursors?: ICursorStore,\n @Optional()\n @Inject(EVENT_READ_PORT)\n private readonly events?: IEventReadPort | null,\n ) {}\n\n async getPoolDepths(tenantId?: string | null): Promise<PoolStatusCount[]> {\n if (!this.jobRuns) return [];\n return this.jobRuns.countByPoolAndStatus(tenantId);\n }\n\n async getRecentFailedJobs(\n limit: number,\n tenantId?: string | null,\n ): Promise<JobRunFailure[]> {\n if (!this.jobRuns) return [];\n return this.jobRuns.listRecentFailed(limit, tenantId);\n }\n\n async getBridgeDeliveryHistogram(\n windowHours: number,\n tenantId?: string | null,\n ): Promise<StatusHistogram> {\n if (!this.bridge) return { ...ObservabilityService.EMPTY_HISTOGRAM };\n return this.bridge.getStatusHistogram(windowHours, tenantId);\n }\n\n async getRecentIntegrationRuns(\n limit: number,\n subscriptionId?: string,\n tenantId?: string | null,\n ): Promise<IntegrationRunSummary[]> {\n if (!this.integrationRuns) return [];\n return this.integrationRuns.listRecent(limit, subscriptionId, tenantId);\n }\n\n async getCursors(tenantId?: string | null): Promise<CursorSnapshot[]> {\n if (!this.cursors) return [];\n return this.cursors.listAll(tenantId);\n }\n\n async listJobRuns(query?: ListJobRunsQuery): Promise<JobRunPage> {\n if (!this.jobRuns) {\n return { ...ObservabilityService.EMPTY_JOB_RUN_PAGE };\n }\n return this.jobRuns.listJobRuns(query);\n }\n\n async listEvents(query?: ListEventsQuery): Promise<EventPage> {\n if (!this.events) {\n return { ...ObservabilityService.EMPTY_EVENT_PAGE };\n }\n return this.events.listEvents(query);\n }\n\n async getCorrelationTimeline(\n rootRunId: string,\n tenantId?: string | null,\n ): Promise<CorrelationTimeline> {\n const runs = await this.collectRuns(rootRunId, tenantId);\n const events = await this.collectEvents(rootRunId, tenantId);\n\n const entries: CorrelationTimelineEntry[] = [\n ...runs.map(\n (run): CorrelationTimelineEntry => ({\n kind: 'job_run',\n at: run.createdAt,\n run,\n }),\n ),\n ...events.map(\n (event): CorrelationTimelineEntry => ({\n kind: 'event',\n at: event.occurredAt,\n event,\n }),\n ),\n ];\n\n // Ascending chronological order. Stable tie-break: job runs before\n // events at the same instant (the run that emits an event precedes it).\n entries.sort((a, b) => {\n const dt = a.at.getTime() - b.at.getTime();\n if (dt !== 0) return dt;\n if (a.kind === b.kind) return 0;\n return a.kind === 'job_run' ? -1 : 1;\n });\n\n const startedAt = entries.length > 0 ? entries[0]!.at : null;\n const lastActivityAt =\n entries.length > 0 ? entries[entries.length - 1]!.at : null;\n\n return {\n rootRunId,\n entries,\n summary: {\n runCount: runs.length,\n eventCount: events.length,\n startedAt,\n lastActivityAt,\n },\n };\n }\n\n /**\n * Drain every `job_run` sharing `rootRunId` by walking the keyset cursor.\n * Empty when the jobs subsystem is absent.\n */\n private async collectRuns(\n rootRunId: string,\n tenantId?: string | null,\n ): Promise<JobRunSummary[]> {\n if (!this.jobRuns) return [];\n const out: JobRunSummary[] = [];\n let cursor: string | undefined;\n for (let page = 0; page < MAX_TIMELINE_PAGES; page += 1) {\n const result = await this.jobRuns.listJobRuns({\n rootRunId,\n tenantId,\n cursor,\n });\n out.push(...result.items);\n if (!result.nextCursor) break;\n cursor = result.nextCursor;\n }\n return out;\n }\n\n /**\n * Drain every `domain_event` whose `metadata.rootRunId` matches by walking\n * the keyset cursor. Empty when the events read port is absent.\n */\n private async collectEvents(\n rootRunId: string,\n tenantId?: string | null,\n ): Promise<EventSummary[]> {\n if (!this.events) return [];\n const out: EventSummary[] = [];\n let cursor: string | undefined;\n for (let page = 0; page < MAX_TIMELINE_PAGES; page += 1) {\n const result = await this.events.listEvents({\n rootRunId,\n tenantId,\n cursor,\n });\n out.push(...result.items);\n if (!result.nextCursor) break;\n cursor = result.nextCursor;\n }\n return out;\n }\n}\n","/**\n * Integration subsystem — DI tokens\n *\n * String constants (not Symbols) so they match by value across import\n * boundaries — same convention as the events subsystem (`EVENT_BUS`). The\n * jobs subsystem uses Symbols for its analogous tokens; events and integration\n * stay internally consistent with strings.\n *\n * Usage in use cases:\n * ```ts\n * constructor(\n * @Inject(INTEGRATION_CHANGE_SOURCE) private readonly source: IChangeSource<CanonicalOpportunity>,\n * @Inject(INTEGRATION_CURSOR_STORE) private readonly cursors: ICursorStore,\n * @Inject(INTEGRATION_FIELD_DIFFER) private readonly differ: IFieldDiffer<CanonicalOpportunity>,\n * @Inject(INTEGRATION_SINK) private readonly sink: IIntegrationSink<CanonicalOpportunity>,\n * @Inject(INTEGRATION_RUN_RECORDER) private readonly recorder: IIntegrationRunRecorder,\n * ) {}\n * ```\n *\n * Concrete bindings are registered by `IntegrationModule.forRoot(...)` (SYNC-6).\n */\n\nexport const INTEGRATION_CHANGE_SOURCE = 'INTEGRATION_CHANGE_SOURCE' as const;\nexport const INTEGRATION_CURSOR_STORE = 'INTEGRATION_CURSOR_STORE' as const;\nexport const INTEGRATION_FIELD_DIFFER = 'INTEGRATION_FIELD_DIFFER' as const;\nexport const INTEGRATION_SINK = 'INTEGRATION_SINK' as const;\n\n/**\n * Run-recorder token (SYNC-5). Backed by `IIntegrationRunRecorder`. Drizzle impl\n * lands in SYNC-4; tests provide inline fakes.\n */\nexport const INTEGRATION_RUN_RECORDER = 'INTEGRATION_RUN_RECORDER' as const;\n\n/**\n * Injection token for the resolved `IntegrationModuleOptions` object (SYNC-6).\n *\n * Backends that need to observe module configuration (e.g. `multiTenant`\n * flag, pool filters) inject via this token. Provided automatically by\n * `IntegrationModule.forRoot(...)` / `IntegrationModule.forRootAsync(...)`.\n */\nexport const INTEGRATION_MODULE_OPTIONS = 'INTEGRATION_MODULE_OPTIONS' as const;\n\n/**\n * Injection token for the resolved multi-tenancy flag (SYNC-6).\n *\n * Provided by `IntegrationModule.forRoot(...)` as `options.multiTenant ?? false`.\n * Consumed by `ExecuteIntegrationUseCase` to enforce the tenantId-is-required rule.\n */\nexport const INTEGRATION_MULTI_TENANT = 'INTEGRATION_MULTI_TENANT' as const;\n\n/**\n * Injection token for the entity-keyed `IEntityChangeSourceRegistry` (C7,\n * #336). Bound to the codegen-emitted aggregator that folds per-provider\n * adapter contributions into one registry (RFC-0001 §3, emitted by Track D\n * D3/D4).\n *\n * A string constant, not `Symbol.for(...)`, to match this subsystem's token\n * convention (see file header). The originating issue's code block proposed a\n * `Symbol.for('@pattern-stack/codegen.entity-change-source-registry')` key,\n * predating the sync→integration consolidation onto string tokens; kept as a\n * string here for internal consistency with the other INTEGRATION_* tokens.\n */\nexport const ENTITY_CHANGE_SOURCE_REGISTRY = 'ENTITY_CHANGE_SOURCE_REGISTRY' as const;\n","/**\n * BridgeMetricsReporter — internal consumer of `IObservability`\n * (ADR-025, OBS-6).\n *\n * Periodically samples `getBridgeDeliveryHistogram` from the observability\n * facade and emits one log line per tick. Auto-registered by\n * `ObservabilityModule.forRoot()` when\n * `options.reporters.bridgeMetrics.enabled === true`. Consumers configure\n * via options; they never import this class. Not exported from the\n * module's `exports` array — internal.\n *\n * # Invariants (enforced by skill + ADR-025)\n *\n * - Injects ONLY `OBSERVABILITY` + `OBSERVABILITY_MODULE_OPTIONS`. Never\n * `BRIDGE_DELIVERY_REPO` or any other sibling token. Reporters are\n * consumers of the composed facade, not parallel composers.\n * - Never reaches into sibling tables or extends `IObservability`.\n * - Errors isolated per-tick (logged, never rethrown) so a transient\n * sibling failure does not kill the interval.\n * - `tenantId` passes VERBATIM to the facade — observability owns tenant\n * semantics, reporters don't re-implement them.\n *\n * # Lifecycle\n *\n * - `onModuleInit` — eager first-tick, then `setInterval`. Handle is\n * `.unref()`-ed when supported so the loop never blocks node shutdown.\n * - `onModuleDestroy` — `clearInterval` + null the handle. Idempotent.\n *\n * No `@nestjs/schedule` dependency — raw `setInterval` keeps the runtime\n * footprint minimal and avoids pulling a decorator framework in for a\n * single loop.\n */\nimport {\n Inject,\n Injectable,\n Logger,\n type OnModuleDestroy,\n type OnModuleInit,\n} from '@nestjs/common';\n\nimport type { IObservability } from '../observability.protocol';\nimport {\n OBSERVABILITY,\n OBSERVABILITY_MODULE_OPTIONS,\n} from '../observability.tokens';\n// Type-only imports — the module imports this file as a value for DI\n// registration, and this file imports config types back. Keeping the\n// back-edge type-only prevents a runtime circular-import.\nimport type {\n BridgeMetricsReporterConfig,\n ObservabilityModuleOptions,\n} from '../observability.module';\n\n@Injectable()\nexport class BridgeMetricsReporter implements OnModuleInit, OnModuleDestroy {\n private readonly logger = new Logger(BridgeMetricsReporter.name);\n private handle: ReturnType<typeof setInterval> | null = null;\n private readonly config: BridgeMetricsReporterConfig | undefined;\n\n constructor(\n @Inject(OBSERVABILITY) private readonly observability: IObservability,\n @Inject(OBSERVABILITY_MODULE_OPTIONS) options: ObservabilityModuleOptions,\n ) {\n this.config = options.reporters?.bridgeMetrics;\n }\n\n onModuleInit(): void {\n if (!this.config || !this.config.enabled) {\n this.logger.log('BridgeMetricsReporter disabled');\n return;\n }\n if (this.config.intervalMs <= 0 || this.config.windowHours <= 0) {\n this.logger.warn(\n `invalid config; not starting: intervalMs=${this.config.intervalMs} windowHours=${this.config.windowHours}`,\n );\n return;\n }\n // Eager first-tick so consumers see data immediately on boot, without\n // waiting `intervalMs` for the first sample.\n void this.runOnce();\n this.handle = setInterval(() => {\n void this.runOnce();\n }, this.config.intervalMs);\n // `.unref()` lets the node process exit even if the interval is still\n // scheduled — important in short-lived CLI/test contexts. Guarded\n // because browser-shimmed timers may not expose it.\n if (typeof this.handle.unref === 'function') this.handle.unref();\n }\n\n onModuleDestroy(): void {\n if (this.handle !== null) {\n clearInterval(this.handle);\n this.handle = null;\n }\n }\n\n /**\n * Single sample. Public so tests and future ops tooling can trigger a\n * sample on demand without waiting for the interval. Errors are caught\n * and logged here — never rethrown — so a transient sibling failure\n * does not kill subsequent ticks.\n */\n async runOnce(): Promise<void> {\n if (!this.config || !this.config.enabled) return;\n try {\n const h = await this.observability.getBridgeDeliveryHistogram(\n this.config.windowHours,\n this.config.tenantId,\n );\n this.logger.log(\n `bridge-delivery window=${this.config.windowHours}h tenant=${this.config.tenantId ?? 'default'} pending=${h.pending} delivered=${h.delivered} skipped=${h.skipped} failed=${h.failed}`,\n );\n } catch (err) {\n this.logger.error(\n 'BridgeMetricsReporter runOnce failed',\n err instanceof Error ? err.stack : String(err),\n );\n }\n }\n}\n","/**\n * Base class for observability-specific errors.\n *\n * Phase-1 `IObservability` methods do not throw — missing sibling ports\n * degrade to empty shapes (see `ObservabilityService`). This class exists\n * so future extensions (OBS-6 reporter misconfiguration, phase-2 Drizzle\n * extensions for `pg_stat_*` sampling, etc.) have a named base without\n * churning the barrel when they land.\n */\nexport class ObservabilityError extends Error {\n constructor(\n message: string,\n override readonly cause?: unknown,\n ) {\n super(message);\n this.name = 'ObservabilityError';\n }\n}\n","/**\n * Integration subsystem — field-diff protocol (port)\n *\n * `IFieldDiffer<T>` is the pluggable differ seam. The default implementation\n * (`DeepEqualDiffer`, ships in SYNC-5) walks every field except an ignore\n * list; CDC-aware differs can skip comparison for fields the provider didn't\n * flag as changed.\n *\n * `FieldDiffSchema` is the structural enforcement of the `changed_fields`\n * column per ADR-0003 — enforced at write time by the recorder service so\n * consumers can rely on the shape in downstream queries.\n */\nimport { z } from 'zod';\n\n// ============================================================================\n// FieldDiff shape — the ADR-0003 contract\n// ============================================================================\n\n/**\n * Structured per-field change. Enforced shape for `integration_run_items.changed_fields`.\n *\n * `created` items set `from: null, to: <value>` for every non-null field.\n * `deleted` items set `from: <value>, to: null`.\n * `noop` items carry `{}`.\n */\nexport const FieldDiffValueSchema = z.object({\n from: z.unknown(),\n to: z.unknown(),\n});\n\nexport const FieldDiffSchema = z.record(z.string(), FieldDiffValueSchema);\n\nexport type FieldDiffValue = z.infer<typeof FieldDiffValueSchema>;\nexport type FieldDiff = z.infer<typeof FieldDiffSchema>;\n\n/** Result of comparing a new record against its existing local state. */\nexport type DiffResult = FieldDiff | 'noop';\n\n// ============================================================================\n// IFieldDiffer\n// ============================================================================\n\n/**\n * Pluggable differ. Default ships in SYNC-5 as `DeepEqualDiffer<T>` —\n * deep-equal over every field except an ignore list (`updated_at` and other\n * row metadata). CDC-aware differs restrict comparison to\n * `providerChangedFields` when supplied.\n */\nexport interface IFieldDiffer<T> {\n /**\n * @param existing — current local state, or `null` when the record is new\n * @param incoming — the canonical record coming from the adapter\n * @param providerChangedFields — optional hint from CDC-capable sources;\n * when present, differ may restrict the comparison to these fields\n */\n diff(\n existing: T | null,\n incoming: T,\n providerChangedFields?: string[],\n ): DiffResult;\n}\n","/**\n * Integration subsystem — entity-keyed change-source registry (port)\n *\n * `IEntityChangeSourceRegistry` resolves an `IChangeSource<T>` by entity name.\n * It generalizes today's per-entity DI tokens (`ACCOUNT_POLL_FETCH_REGISTRY`,\n * `CONTACT_POLL_FETCH_REGISTRY`, …) into one entity-keyed registry, so the L3\n * composing port (`<Surface>Port`, Track C C6) can be entity-agnostic at the\n * type level instead of enumerating entities (epic #328 locked decision #5).\n *\n * This lives in L1 (the integration subsystem) rather than in a per-surface\n * package because the same shape applies across surfaces — CRM (`account`,\n * `contact`, `deal`), Mail (`email`, `thread`, `label`), Transcript\n * (`transcript`, `speaker`, `utterance`), Meeting (`meeting`, `attendee`).\n * Cross-surface plumbing belongs at L1 (epic #328 locked decision #6).\n *\n * Scope (Track C · C7): this is purely the L1 type + memory impl. Codegen does\n * NOT yet emit this registry, and the existing per-entity tokens keep emitting\n * unchanged — the retarget (and the per-entity-token deprecation) is Track D\n * D3/D4 (RFC-0001 §3/§8).\n *\n * See #336 (this issue), #328 (parent epic), RFC-0001 §3 (the registry\n * contract Track D emits the wiring for).\n */\n\nimport type { IChangeSource } from './integration-change-source.protocol';\n\n/**\n * Entity-keyed resolver for change sources. The orchestrator (and the L3\n * surface port) consume this, agnostic to whether a source came from a\n * hand-written adapter or a configured `PollChangeSource<T>`.\n */\nexport interface IEntityChangeSourceRegistry {\n /**\n * Resolve a change source for a given entity name.\n * Throws {@link UnknownEntityError} if the entity isn't registered.\n */\n get<T = unknown>(entityName: string): IChangeSource<T>;\n\n /** True if the entity is registered. */\n has(entityName: string): boolean;\n\n /** List all entity names this registry serves. */\n entities(): readonly string[];\n}\n\n/**\n * Thrown by {@link IEntityChangeSourceRegistry.get} when no source is\n * registered for the requested entity. The message enumerates the available\n * entities so a misconfiguration (typo'd entity name, missing adapter\n * contribution) is diagnosable from the error alone.\n */\nexport class UnknownEntityError extends Error {\n constructor(entity: string, available: readonly string[]) {\n super(\n `No change source registered for entity '${entity}'. Available: ${available.join(', ')}`,\n );\n this.name = 'UnknownEntityError';\n }\n}\n","/**\n * Integration subsystem — in-memory entity-change-source registry\n *\n * Default `IEntityChangeSourceRegistry` backed by a `Map<entityName, source>`.\n * Track D's codegen-emitted aggregator folds per-provider adapter\n * contributions into one of these and binds it under\n * `ENTITY_CHANGE_SOURCE_REGISTRY` (RFC-0001 §3); tests and simple consumers\n * construct it directly.\n *\n * See {@link ./entity-change-source-registry.protocol} for the contract and\n * #336 for scope.\n */\n\nimport type { IChangeSource } from './integration-change-source.protocol';\nimport {\n type IEntityChangeSourceRegistry,\n UnknownEntityError,\n} from './entity-change-source-registry.protocol';\n\nexport class MemoryEntityChangeSourceRegistry\n implements IEntityChangeSourceRegistry\n{\n constructor(private readonly sources: Map<string, IChangeSource<unknown>>) {}\n\n get<T = unknown>(name: string): IChangeSource<T> {\n const source = this.sources.get(name);\n if (!source) {\n throw new UnknownEntityError(name, [...this.sources.keys()]);\n }\n return source as IChangeSource<T>;\n }\n\n has(name: string): boolean {\n return this.sources.has(name);\n }\n\n entities(): readonly string[] {\n return [...this.sources.keys()];\n }\n}\n","/**\n * Integration subsystem — DetectionConfig schema (#226-1)\n *\n * Canonical Zod schema for per-entity integration detection config. The schema is\n * the single source of truth for filter/mapping shape and is consumed by:\n *\n * 1. Runtime primitives — `PollChangeSource<T>`, `WebhookChangeSource<T>`\n * (#226-3, #226-4) accept a parsed `DetectionConfig` at construction.\n * 2. Codegen — `src/schema/entity-definition.schema.ts` (#226-6) imports\n * this schema so per-entity YAML `detection:` blocks validate against\n * the same shape the runtime enforces.\n *\n * Locked decisions (see ADR-033 + decision memo Q1–Q6):\n * - Filter vocabulary is flat AND of `{ field, op, value }` triples; richer\n * boolean expressions (OR / NOT / nested) are deferred per epic open Q3.\n * - Cursor strategy is a tagged union over the four shapes the three modes\n * need (`systemModstamp`, `replayId`, `timestamp`, `eventId`). Each\n * strategy types its cursor internally; the orchestrator persists what\n * the iterator last yielded (integration skill rule 2).\n * - `mode: 'poll'` may opt into `provenance: 'cdc'` so Stripe-style event\n * endpoints (mechanically a poll, semantically CDC) reuse the poll\n * primitive while emitting `Change<T>.source = 'cdc'`. Long-lived\n * streaming CDC (SFDC Pub-Sub, Debezium) is a separate primitive\n * deferred to #226-8.\n * - `webhook` mode requires `eventIdField` so `WebhookChangeSource<T>`\n * can populate `Change<T>.dedupKey` from the inbound staging row.\n */\nimport { z } from 'zod';\n\n// ============================================================================\n// Field mapping — provider field → canonical target\n// ============================================================================\n\n/**\n * Maps a single provider field onto the canonical record. `transform` is an\n * opt-in tag the adapter callback may inspect (`date-iso`, `decimal-string`,\n * etc.); the schema does not enumerate transforms — adapters interpret them.\n */\nexport const FieldMappingSchema = z.object({\n source: z.string().min(1),\n target: z.string().min(1),\n transform: z.string().min(1).optional(),\n});\n\nexport type FieldMapping = z.infer<typeof FieldMappingSchema>;\n\n// ============================================================================\n// Resolved filter — flat-AND triple\n// ============================================================================\n\n/**\n * A single resolved filter clause applied at fetch time. `value` is `unknown`\n * to admit primitives, arrays (for `in` / `nin`), and dates as ISO strings —\n * adapters interpret per provider.\n */\nexport const ResolvedFilterSchema = z.object({\n field: z.string().min(1),\n op: z.enum(['eq', 'neq', 'in', 'nin', 'gt', 'gte', 'lt', 'lte']),\n value: z.unknown(),\n});\n\nexport type ResolvedFilter = z.infer<typeof ResolvedFilterSchema>;\n\n// ============================================================================\n// Cursor strategy — tagged union over the four shapes the modes need\n// ============================================================================\n\nconst SystemModstampCursorSchema = z.object({\n kind: z.literal('systemModstamp'),\n field: z.string().min(1),\n});\n\nconst ReplayIdCursorSchema = z.object({\n kind: z.literal('replayId'),\n field: z.string().min(1),\n});\n\nconst TimestampCursorSchema = z.object({\n kind: z.literal('timestamp'),\n field: z.string().min(1),\n});\n\nconst EventIdCursorSchema = z.object({\n kind: z.literal('eventId'),\n field: z.string().min(1),\n});\n\n/**\n * Gmail `historyId` (RFC-0003 §3) — an opaque, atomic vendor token. The next\n * watermark only exists at end-of-walk; there is no resumable mid-walk value.\n * `field` is metadata for codegen/adapters (the response key the token lives on).\n */\nconst HistoryIdCursorSchema = z.object({\n kind: z.literal('historyId'),\n field: z.string().min(1),\n});\n\n/**\n * Google Calendar `syncToken` (RFC-0003 §3) — an opaque, atomic sync token,\n * same divisibility profile as `historyId`.\n */\nconst SyncTokenCursorSchema = z.object({\n kind: z.literal('syncToken'),\n field: z.string().min(1),\n});\n\nexport const CursorStrategySchema = z.discriminatedUnion('kind', [\n SystemModstampCursorSchema,\n ReplayIdCursorSchema,\n TimestampCursorSchema,\n EventIdCursorSchema,\n HistoryIdCursorSchema,\n SyncTokenCursorSchema,\n]);\n\nexport type CursorStrategy = z.infer<typeof CursorStrategySchema>;\n\n// ============================================================================\n// Cursor divisibility (RFC-0003 §3)\n// ============================================================================\n\n/**\n * Whether a cursor strategy is *divisible* — a property of the strategy, not\n * the read primitive. Divisible cursors are sortable/monotonic watermarks whose\n * value is meaningful AS OF any single record (HubSpot `systemModstamp`, a\n * `timestamp` field, a Salesforce CDC `replayId`); the read primitive may\n * checkpoint per-ref mid-walk, so a crash resumes from the last delivered ref.\n *\n * Atomic cursors are opaque vendor tokens (Gmail `historyId`, Calendar\n * `syncToken`, a generic `eventId`) whose next value only exists at end-of-walk.\n * The primitive must withhold per-ref cursors and emit the token only at a safe\n * boundary, so an interrupted run never persists an unresumable mid-walk token\n * (it resumes all-or-nothing from the prior token — see `IncrementalReadBase`).\n *\n * `eventId` is classified atomic conservatively: a generic opaque id is treated\n * all-or-nothing unless a concrete strategy proves it monotonically resumable.\n */\nexport const CURSOR_DIVISIBILITY: Readonly<Record<CursorStrategy['kind'], boolean>> = {\n systemModstamp: true,\n timestamp: true,\n replayId: true,\n eventId: false,\n historyId: false,\n syncToken: false,\n};\n\n/** Predicate form of {@link CURSOR_DIVISIBILITY}. */\nexport function isDivisibleCursor(kind: CursorStrategy['kind']): boolean {\n return CURSOR_DIVISIBILITY[kind];\n}\n\n// ============================================================================\n// Mode-specific blocks\n// ============================================================================\n\n/**\n * Poll-mode block. `provenance: 'cdc'` opts the poll primitive into stamping\n * `Change<T>.source = 'cdc'` and populating `dedupKey` from the cursor's\n * `field` — used for Stripe-style event endpoints. Defaults to `'poll'`.\n */\nexport const PollDetectionSchema = z.object({\n cursor: CursorStrategySchema,\n provenance: z.enum(['poll', 'cdc']).optional(),\n});\n\nexport type PollDetection = z.infer<typeof PollDetectionSchema>;\n\n/**\n * Webhook-mode block. `eventIdField` names the column in the consumer-owned\n * inbound staging row that `WebhookChangeSource<T>` reads to set\n * `Change<T>.dedupKey`.\n */\nexport const WebhookDetectionSchema = z.object({\n eventIdField: z.string().min(1),\n});\n\nexport type WebhookDetection = z.infer<typeof WebhookDetectionSchema>;\n\n// ============================================================================\n// DetectionConfig — top-level discriminated union over `mode`\n// ============================================================================\n\nconst PollModeSchema = z.object({\n mode: z.literal('poll'),\n poll: PollDetectionSchema,\n mapping: z.array(FieldMappingSchema).min(1),\n filters: z.array(ResolvedFilterSchema).default([]),\n});\n\nconst WebhookModeSchema = z.object({\n mode: z.literal('webhook'),\n webhook: WebhookDetectionSchema,\n mapping: z.array(FieldMappingSchema).min(1),\n filters: z.array(ResolvedFilterSchema).default([]),\n});\n\n/**\n * Top-level detection config. Discriminated on `mode` so the relevant\n * mode-block (poll/webhook) is structurally required for that mode. CDC as a\n * long-lived streaming primitive is deferred (#226-8); CDC-as-provenance\n * (Stripe-style event endpoints) is expressed via `mode: 'poll'` with\n * `poll.provenance: 'cdc'`.\n */\nexport const DetectionConfigSchema = z.discriminatedUnion('mode', [\n PollModeSchema,\n WebhookModeSchema,\n]);\n\nexport type DetectionConfig = z.infer<typeof DetectionConfigSchema>;\n","/**\n * Integration subsystem — `IncrementalRead<T, F>` + `RandomRead<T>` capability\n * and the providing `IncrementalReadBase<T, F, M>` (RFC-0003 R1).\n *\n * The universal read primitive. Where `IChangeSource.listChanges` is the\n * *transport* contract (stream `Change<T>`, orchestrator owns cursor lifecycle),\n * this base owns *how the body that produces those changes is written* — the\n * level the bare `changeSources = {}` author-seam left unstructured.\n *\n * The read decomposes into two composable verbs the adapter supplies:\n *\n * - `enumerate(mode, filter) → AsyncIterable<Ref<M>[]>` — the cheap delta /\n * backfill walk; streams pages of lightweight refs (id + per-ref cursor +\n * filterable metadata). LAZY: pull-driven so hydrate backpressures it.\n * - `hydrate(ids) → Map<id, raw>` — the expensive fetch-by-id, batched; where\n * bounded concurrency / a vendor `/batch` endpoint lives. Keyed and\n * miss-tolerant (a mid-run 404 cannot shift alignment).\n * - `toCanonical(raw) → T | null` — provider payload → canonical record.\n *\n * The base PROVIDES the orchestration: drain enumerate, **filter before\n * hydrate** (structural — an adapter physically cannot hydrate-then-discard),\n * keyed pairing, per-ref cursor emission, and the `IChangeSource.listChanges`\n * adaptation. It also provides `RandomRead.get()` for free as\n * `toCanonical ∘ hydrate([id])` — so every incremental adapter is a\n * single-record reader (the \"list cheaply, fill on click\" query-surface need)\n * without extra code.\n *\n * The shape generalizes dealbrain's proven HubSpot `listSince` (streams, pushes\n * the filter server-side, carries a per-record cursor) to vendors whose list\n * returns id-stubs (Gmail) or nested resources (Meet). Calendar-style\n * full-object lists override `hydrate` as a passthrough.\n *\n * See RFC-0003 (Track D round-3), ADR-033 (`detection:` config), and\n * `poll-change-source.ts` (the sibling primitive this composes beside).\n */\n\nimport type {\n Change,\n ChangeSource,\n IChangeSource,\n IntegrationSubscriptionView,\n} from './integration-change-source.protocol';\n\n// ============================================================================\n// Capability shapes\n// ============================================================================\n\n/**\n * How a read walks the upstream. Modes are values, not verbs (swe-brain\n * ADR-0003: mode ≠ capability) — one `read()` verb dispatches on these.\n *\n * - `delta` — incremental walk from a persisted cursor.\n * - `full` — cursorless backfill (optionally bounded by `since`).\n * - `reconcile` — gap-repair: re-fetch a known id set the cursor skipped\n * (the repair pass for the silent-tail-skip + #414-style\n * multi-provider divergence).\n */\nexport type ReadMode =\n | { readonly kind: 'delta'; readonly cursor: unknown }\n | { readonly kind: 'full'; readonly since?: Date }\n | { readonly kind: 'reconcile'; readonly knownIds: readonly string[] };\n\n/**\n * A cheap ref from the enumerate pass: identity + per-ref cursor + metadata to\n * filter or display on. `cursor` is the position AS OF this ref — see\n * `IncrementalReadBase.cursorDivisible` (R2) for when it may be checkpointed\n * mid-walk versus withheld until a safe boundary.\n */\nexport interface Ref<M = Record<string, unknown>> {\n readonly externalId: string;\n readonly cursor: unknown;\n readonly meta: M;\n}\n\n/** A read request: the mode, an optional adapter-typed filter, and page size. */\nexport interface ReadRequest<F = unknown> {\n readonly mode: ReadMode;\n readonly filter?: F;\n readonly pageSize?: number;\n}\n\n/**\n * Per-run context threaded from `listChanges` into the vendor read body (R5).\n *\n * Carries the `subscription` framing the run so `enumerate`/`hydrate` can resolve\n * **per-connection credentials** (and raw-landing keys) from\n * `subscription.externalRef` — the gap a multi-account consumer surfaced: a\n * singleton change source cannot hold connection-scoped auth, and before R5 the\n * base forwarded the subscription only into `filterFor`, never into the fetch.\n *\n * Optional throughout (the core contract): a direct `read()` / `get()` call — the\n * query surface's \"fill one record on click\" — may omit it. An adapter that needs\n * per-connection auth reads `ctx?.subscription?.externalRef` and asserts its\n * presence; a provider-level-auth adapter ignores it.\n */\nexport interface ReadContext {\n /** The subscription framing this run; `externalRef` is the upstream scope /\n * connection id the adapter resolves credentials + raw-landing keys from. */\n readonly subscription?: IntegrationSubscriptionView;\n}\n\n/**\n * The `read()`-side envelope: canonical record + the raw vendor payload it came\n * from + the originating external id + the per-ref cursor.\n *\n * Distinct from the runtime's transport envelope `Change<T>`\n * (operation/externalId/cursor/source). The relationship is one-directional:\n * `listChanges()` adapts `read()` → `Change<T>` (dropping `raw`, stamping\n * `operation`). `read()` keeps `raw` and `externalId` so a query surface can\n * re-project without a second fetch.\n */\nexport interface SourcedRecord<T> {\n readonly externalId: string;\n readonly record: T;\n readonly raw: unknown;\n readonly cursor: unknown;\n}\n\n/**\n * The universal read capability — one public verb that streams. Filtering,\n * hydration, and cursor emission are the providing base's concern.\n */\nexport interface IncrementalRead<T, F = unknown> {\n read(req: ReadRequest<F>, ctx?: ReadContext): AsyncIterable<SourcedRecord<T>>;\n}\n\n/**\n * Single-record read by external id — the \"fill on click\" atom. Provided for\n * free by `IncrementalReadBase` (composes `hydrate` + `toCanonical`); declared\n * as its own capability so consumers can depend on it without the streaming\n * surface.\n */\nexport interface RandomRead<T> {\n get(id: string, ctx?: ReadContext): Promise<T | null>;\n}\n\n// ============================================================================\n// Bounded-parallel map helper\n// ============================================================================\n\n/**\n * Map `ids` through `fn` with at most `limit` concurrent in-flight calls,\n * collecting results keyed by id. The workhorse for writing a batched\n * `hydrate` over a single-id fetch without serial N+1 latency.\n */\nexport async function mapConcurrent<R>(\n ids: readonly string[],\n fn: (id: string) => Promise<R>,\n limit: number,\n): Promise<Map<string, R>> {\n const out = new Map<string, R>();\n if (ids.length === 0) return out;\n const width = Math.max(1, Math.min(limit, ids.length));\n let next = 0;\n const worker = async (): Promise<void> => {\n while (next < ids.length) {\n const idx = next++;\n const id = ids[idx]!;\n out.set(id, await fn(id));\n }\n };\n await Promise.all(Array.from({ length: width }, worker));\n return out;\n}\n\n// ============================================================================\n// IncrementalReadBase\n// ============================================================================\n\n/**\n * Providing base for the read capability. A subclass fills exactly three vendor\n * methods — `enumerate`, `hydrate`, `toCanonical` — and gets a streaming,\n * filter-before-hydrate, miss-tolerant `IncrementalRead<T, F>` +\n * `IChangeSource<T>` + `RandomRead<T>`.\n *\n * Type params: `T` canonical record, `F` adapter-typed filter, `M` per-ref\n * metadata (defaults to an untyped bag — surface packages supply a domain `M`).\n */\nexport abstract class IncrementalReadBase<T, F = unknown, M = Record<string, unknown>>\n implements IncrementalRead<T, F>, IChangeSource<T>, RandomRead<T>\n{\n /** Human label for run logs — e.g. `'google-mail-email'`. */\n abstract readonly label: string;\n\n /**\n * Whether the vendor takes the request predicate server-side. Declared, not\n * enforced here — surfaced into the emission manifest (R3) so the falsifier\n * suite (R4) can record which adapters filter post-hydrate. `false` is the\n * honest floor (e.g. Gmail without `q=`), handled via `matchesRecord`.\n */\n protected readonly filterPushdown: boolean = false;\n\n /** Max concurrent in-flight calls for a `mapConcurrent`-built `hydrate`. */\n protected readonly hydrateConcurrency: number = 10;\n\n /** `Change<T>.source` provenance stamped by `listChanges`. */\n protected readonly changeSource: ChangeSource = 'poll';\n\n /**\n * Whether this source's cursor strategy is divisible (RFC-0003 §3). When\n * `true` (default — sortable watermarks like `systemModstamp`/`timestamp`/\n * `replayId`), `listChanges` emits each record's per-ref cursor, so the\n * orchestrator may checkpoint mid-walk and a crash resumes from the last\n * delivered ref.\n *\n * When `false` (atomic opaque tokens — Gmail `historyId`, Calendar\n * `syncToken`), `listChanges` WITHHOLDS per-ref cursors and emits the\n * end-of-walk token only on the final record, so the orchestrator's\n * persist-last-yielded lifecycle can never persist an unresumable mid-walk\n * token. The cost is blast-radius: an interrupted atomic run resumes\n * all-or-nothing from the prior persisted token. For atomic *backfills* that\n * radius is the whole enumerate walk — bound it with `ReadRequest.pageSize`\n * (smaller pages ⇒ shorter walks per run). Per-page atomic checkpointing is a\n * future refinement; R2 gates at end-of-walk.\n *\n * Codegen (R3) sets this from the strategy kind via `isDivisibleCursor`.\n */\n protected readonly cursorDivisible: boolean = true;\n\n // ---- SUPPLIED by the adapter (the irreducible vendor seam) ----\n\n /**\n * The cheap walk. Streams pages of refs; LAZY so `hydrate` backpressures it\n * (one page hydrated before the next is pulled). Mode-dispatch lives here:\n * `delta` resumes from `mode.cursor`, `full` walks from the top, `reconcile`\n * re-fetches `mode.knownIds`.\n *\n * `pageSize` (from `ReadRequest`) is the adapter's requested vendor page size\n * — also the atomic-cursor backfill blast-radius bound (§ `cursorDivisible`).\n * Honor it as a hint; vendors that cap page size clamp it.\n *\n * `ctx?.subscription` (R5) carries the run's subscription, so a per-connection\n * adapter resolves credentials / upstream scope from `externalRef` here; absent\n * on a direct `read()` with no run subscription.\n */\n protected abstract enumerate(\n mode: ReadMode,\n filter?: F,\n pageSize?: number,\n ctx?: ReadContext,\n ): AsyncIterable<Ref<M>[]>;\n\n /**\n * Fetch raw payloads for `ids`, keyed by id. MUST be miss-tolerant: omit (or\n * map to `null`) any id that 404s mid-run rather than throwing or shifting\n * alignment. Write it over `mapConcurrent(ids, (id) => this.fetchOne(id),\n * this.hydrateConcurrency)`; override with a real `/batch` call or a\n * passthrough (full-object list) where the vendor allows.\n *\n * `ctx?.subscription` (R5) carries the run's subscription for per-connection\n * credential resolution (the fetch is where the vendor call happens) and is the\n * natural place to land raw payloads keyed by `subscription.id`.\n */\n protected abstract hydrate(ids: string[], ctx?: ReadContext): Promise<Map<string, unknown>>;\n\n /** Provider payload → canonical record. Return `null` to drop a record. */\n protected abstract toCanonical(raw: unknown): T | null;\n\n // ---- Optional filter hooks — exactly one is live per `filterPushdown` ----\n\n /** Pre-hydrate predicate over the cheap ref (preferred — avoids hydration). */\n protected matchesRef(_ref: Ref<M>, _filter?: F): boolean {\n return true;\n }\n\n /** Post-hydrate predicate over the canonical record (the no-pushdown floor). */\n protected matchesRecord(_record: T, _filter?: F): boolean {\n return true;\n }\n\n /**\n * Resolve the filter for a subscription when adapting to `listChanges`\n * (which has no filter argument). Defaults to none; codegen wiring (R3)\n * overrides this to thread `DetectionConfig.filters`.\n */\n protected filterFor(_subscription: IntegrationSubscriptionView): F | undefined {\n return undefined;\n }\n\n // ---- PROVIDED by the base ----\n\n /**\n * Stream canonical records for a request. Filter is applied BEFORE hydrate\n * (structural: a kept ref is hydrated, a rejected one never is), so an\n * adapter cannot hydrate-then-discard. A hydrate miss (deleted mid-run) is\n * skipped, never fabricated.\n */\n async *read(req: ReadRequest<F>, ctx?: ReadContext): AsyncIterable<SourcedRecord<T>> {\n for await (const refPage of this.enumerate(req.mode, req.filter, req.pageSize, ctx)) {\n const kept = refPage.filter((ref) => this.matchesRef(ref, req.filter));\n if (kept.length === 0) continue;\n const raws = await this.hydrate(\n kept.map((ref) => ref.externalId),\n ctx,\n );\n for (const ref of kept) {\n const raw = raws.get(ref.externalId);\n if (raw === undefined || raw === null) continue; // deleted mid-run → skip\n const record = this.toCanonical(raw);\n if (record !== null && this.matchesRecord(record, req.filter)) {\n yield { externalId: ref.externalId, record, raw, cursor: ref.cursor };\n }\n }\n }\n }\n\n /**\n * `RandomRead<T>` — single-record read, provided for free as\n * `toCanonical ∘ hydrate([id])`. Reuses the adapter's batched fetch + miss\n * tolerance; returns `null` for a missing or undecodable record.\n */\n async get(id: string, ctx?: ReadContext): Promise<T | null> {\n const raws = await this.hydrate([id], ctx);\n const raw = raws.get(id);\n if (raw === undefined || raw === null) return null;\n return this.toCanonical(raw);\n }\n\n /**\n * `IChangeSource<T>` adaptation. Maps the orchestrator's by-value cursor to a\n * `ReadMode` (`null` → `full` backfill, else `delta`), streams `read()`, and\n * stamps each `SourcedRecord` into a `Change<T>`. All records surface as\n * `'updated'`; the orchestrator's diff stage classifies create-vs-update and\n * deletes arrive as tombstone refs (`toCanonical` may flag them).\n *\n * Cursor emission honors `cursorDivisible` (RFC-0003 §3). Divisible: each\n * record carries its own per-ref cursor. Atomic: per-ref cursors are withheld\n * (`undefined`, which the orchestrator skips persisting) and the end-of-walk\n * token rides only on the final record — so a mid-walk crash never persists\n * an unresumable token. If an atomic run yields no surviving records, no\n * cursor is persisted and the next run re-reads the same (empty) delta — a\n * bounded inefficiency, never data loss.\n */\n async *listChanges(\n subscription: IntegrationSubscriptionView,\n cursor: unknown | null,\n ): AsyncIterable<Change<T>> {\n const mode: ReadMode =\n cursor === null || cursor === undefined\n ? { kind: 'full' }\n : { kind: 'delta', cursor };\n const filter = this.filterFor(subscription);\n // R5: thread the run's subscription into the read body so `enumerate`/`hydrate`\n // can resolve per-connection credentials (and raw-landing keys) from it.\n const stream = this.read({ mode, filter }, { subscription });\n\n if (this.cursorDivisible) {\n for await (const sourced of stream) {\n yield this.toChange(sourced, sourced.cursor);\n }\n return;\n }\n\n // Atomic: one-record lookahead. Emit every record but the last with a\n // withheld (`undefined`) cursor; the last record carries the end-of-walk\n // token. Contract: an atomic adapter stamps the (single, shared) end-of-walk\n // token onto its refs' `cursor` — so whichever record survives last carries\n // it. The base emits a real cursor exactly once, on that final record, so the\n // orchestrator can never persist a mid-walk value. If zero records survive,\n // nothing is persisted (next run re-reads the delta — bounded, never lossy).\n let prev: SourcedRecord<T> | null = null;\n for await (const sourced of stream) {\n if (prev !== null) yield this.toChange(prev, undefined);\n prev = sourced;\n }\n if (prev !== null) yield this.toChange(prev, prev.cursor);\n }\n\n /** Stamp a `SourcedRecord` into a `Change<T>` with an explicit emitted cursor. */\n private toChange(sourced: SourcedRecord<T>, cursor: unknown): Change<T> {\n return {\n externalId: sourced.externalId,\n operation: 'updated',\n record: sourced.record,\n cursor,\n source: this.changeSource,\n };\n }\n}\n","/**\n * Typed errors + shared boundary helpers for the integration subsystem.\n *\n * Classes (not bare Error) so consumers can `instanceof` them in catch\n * blocks and exception filters can map them to HTTP codes.\n *\n * Mirrors the shape of `events-errors.ts` and `jobs-errors.ts`.\n */\n\n/**\n * Thrown by the Drizzle cursor-store / run-recorder backends AND by the\n * orchestrator entry point when `INTEGRATION_MULTI_TENANT` is enabled but the\n * caller did not supply a non-null `tenantId`. Strict enforcement at the\n * boundary — explicit `null` still throws.\n *\n * Disable multi-tenancy on the module (`multiTenant: false`, the default)\n * to opt out of the requirement entirely.\n *\n * `operation` identifies the call site (e.g. `'cursor.put'`,\n * `'startRun'`, `'execute'`) so the stack-trace message points at the\n * specific boundary that rejected the input.\n */\nexport class MissingTenantIdError extends Error {\n override readonly name = 'MissingTenantIdError';\n constructor(operation: string) {\n super(\n `Missing tenantId for integration operation '${operation}'. IntegrationModule is ` +\n `configured with multiTenant: true — every call must include a ` +\n `non-null tenantId. Either pass the tenantId or disable multi-` +\n `tenancy on the module.`,\n );\n }\n}\n\n/**\n * Shared boundary guard — used at the orchestrator entry AND inside the\n * Drizzle backends. Keeping the check in one function guarantees every\n * `MissingTenantIdError` carries the same message shape regardless of the\n * site that raised it, which makes it easier for consumers to pattern-\n * match on the error in logs/metrics.\n *\n * When `multiTenant` is false, the function is a no-op — `tenantId` may\n * be anything (including `undefined`). When true, `undefined` or `null`\n * throws.\n */\nexport function assertTenantId(\n tenantId: string | null | undefined,\n options: { multiTenant: boolean; operation: string },\n): asserts tenantId is string {\n if (!options.multiTenant) return;\n if (tenantId === undefined || tenantId === null) {\n throw new MissingTenantIdError(options.operation);\n }\n}\n","/**\n * Drizzle schema for the integration subsystem audit/observability tables (SYNC-1).\n *\n * Three tables model end-to-end integration observability, keyed by the single port\n * every integration adapter implements (`IChangeSource<T>` from SYNC-2):\n *\n * - `integration_subscriptions` — owns the cursor per\n * `(connection_id, adapter, domain, external_ref)` tuple. Addressed\n * by id by `ICursorStore` (SYNC-3/SYNC-4).\n * - `integration_runs` — per-run audit log: start/complete, status,\n * cursor before/after, counts, direction (inbound|outbound),\n * action (poll|cdc|webhook|manual|writeback).\n * - `integration_run_items` — per-record change log with structured\n * `changed_fields` jsonb enforced by the Zod `FieldDiffSchema`\n * contract (ADR-0003; protocol lives in SYNC-2's\n * integration-field-diff.protocol.ts).\n *\n * Design calls (vs. issue #126 open questions):\n *\n * - `integration_subscriptions` ships in the subsystem (not consumer-owned).\n * Rationale: SYNC-4's `PostgresCursorStore` needs to read/write this\n * table directly; making it consumer-owned would require consumers to\n * hand-wire a shape the backend already knows. The row is addressable\n * by id and scoped by the uniqueness tuple; consumers can still\n * query/list it freely. Same stance as `job_run` being subsystem-\n * owned while remaining consumer-queryable.\n *\n * - `tenant_id` is always emitted on the three tables as nullable text.\n * The `INTEGRATION_MULTI_TENANT` DI flag (SYNC-6) is what enforces the\n * non-null + cross-tenant-isolation contract at the service/orchestrator\n * boundary. This mirrors JOB-1/JOB-8's final shape — runtime guard, not\n * a scaffold-time conditional column. Keeps the schema file uniform\n * across single-tenant and multi-tenant deployments.\n *\n * - `changed_fields` on `integration_run_items` is typed via the Zod-inferred\n * `FieldDiff` shape from SYNC-2 (`{ [fieldName]: { from, to } }`). The\n * recorder service (SYNC-5) validates every write against\n * `FieldDiffSchema.parse` so consumers can rely on the shape.\n */\nimport {\n pgEnum,\n pgTable,\n uuid,\n text,\n jsonb,\n integer,\n boolean,\n timestamp,\n index,\n uniqueIndex,\n} from 'drizzle-orm/pg-core';\nimport type { InferSelectModel } from 'drizzle-orm';\n\nimport type { FieldDiff } from './integration-field-diff.protocol';\n\n// ─── Enums ──────────────────────────────────────────────────────────────────\n\n/**\n * Direction of a integration run relative to local state.\n *\n * - `inbound` — external → local (the common case: SFDC poll → local DB).\n * - `outbound` — local → external (writeback; deferred per epic but the\n * column shape is reserved so future writeback runs share the audit log).\n */\nexport const integrationRunDirectionEnum = pgEnum('integration_run_direction', [\n 'inbound',\n 'outbound',\n]);\n\n/**\n * How the run detected upstream changes. Maps 1:1 to the `Change.source`\n * provenance on inbound runs; `manual` captures operator-triggered re-integrations\n * and `writeback` captures outbound runs.\n */\nexport const integrationRunActionEnum = pgEnum('integration_run_action', [\n 'poll',\n 'cdc',\n 'webhook',\n 'manual',\n 'writeback',\n]);\n\n/**\n * Lifecycle status of a integration run.\n *\n * - `running` — in-flight; recorder has started but not completed.\n * - `success` — completed with at least one change processed.\n * - `no_changes` — completed cleanly, no upstream changes found.\n * - `failed` — errored before completion; `error` column carries the\n * message. `records_processed` may be non-zero (partial progress).\n */\nexport const integrationRunStatusEnum = pgEnum('integration_run_status', [\n 'running',\n 'success',\n 'no_changes',\n 'failed',\n]);\n\n/**\n * Operation applied per record. Mirrors `Change<T>.operation` from SYNC-2,\n * plus the recorder's own `'noop'` for changes that matched existing state.\n */\nexport const integrationRunItemOperationEnum = pgEnum('integration_run_item_operation', [\n 'created',\n 'updated',\n 'deleted',\n 'noop',\n]);\n\n/**\n * Per-record status within a run. `skipped` captures loopback-detected echoes\n * of the local system's own writes (see `ILoopbackFingerprintStore` in the\n * epic), which record the external_id but intentionally do not touch local\n * state.\n */\nexport const integrationRunItemStatusEnum = pgEnum('integration_run_item_status', [\n 'success',\n 'failed',\n 'skipped',\n]);\n\n// ─── integration_subscriptions ─────────────────────────────────────────────────────\n\n/**\n * One cursor owner per (integration, adapter, domain, external_ref).\n *\n * - `connection_id` — opaque id of the connected account/instance. E.g.\n * the SFDC org id for polling strategies, the GitHub installation id\n * for webhook strategies.\n * - `adapter` — short adapter label, e.g. `'salesforce'`, `'hubspot'`.\n * - `domain` — canonical entity domain this subscription tracks,\n * e.g. `'opportunity'`, `'contact'`.\n * - `external_ref` — optional upstream scope (e.g. a filter id, a\n * webhook subscription id). NULL when the subscription covers the\n * entire domain.\n *\n * The cursor shape is opaque jsonb — strategies type it internally (poll:\n * `{ systemModstamp }`, cdc: `{ replayId }`, webhook: `{ ts }`). Overwritten\n * by `ICursorStore.put(id, cursor)`.\n */\nexport const integrationSubscriptions = pgTable(\n 'integration_subscriptions',\n {\n id: uuid('id').primaryKey().defaultRandom(),\n connectionId: text('connection_id').notNull(),\n adapter: text('adapter').notNull(),\n domain: text('domain').notNull(),\n externalRef: text('external_ref'),\n enabled: boolean('enabled').notNull().default(true),\n /**\n * Per-subscription configuration bag. Strategies type it internally;\n * e.g. polling strategies stash `{ batchSize, highWatermark }` here.\n */\n config: jsonb('config').notNull().default({}).$type<Record<string, unknown>>(),\n /**\n * Opaque cursor persisted by `ICursorStore.put()`. NULL until the first\n * successful run advances it.\n */\n cursor: jsonb('cursor').$type<unknown>(),\n lastIntegrationAt: timestamp('last_integration_at', { withTimezone: true }),\n /** Runtime-enforced when `INTEGRATION_MULTI_TENANT` is true; see SYNC-6. */\n tenantId: text('tenant_id'),\n createdAt: timestamp('created_at', { withTimezone: true }).notNull().defaultNow(),\n updatedAt: timestamp('updated_at', { withTimezone: true }).notNull().defaultNow(),\n },\n (t) => ({\n /**\n * Composite uniqueness per the epic shape. `external_ref` is nullable;\n * Postgres treats NULLs as distinct in a UNIQUE constraint, which means\n * two rows with the same `(connection_id, adapter, domain)` and NULL\n * external_ref are allowed. That's intentional — a subscription with\n * NULL external_ref covers the full domain, and duplicates there would\n * be a consumer-layer modeling issue, not a schema concern.\n */\n uqIntegrationSubscriptionTuple: uniqueIndex('uq_integration_subscriptions_tuple').on(\n t.connectionId,\n t.adapter,\n t.domain,\n t.externalRef,\n ),\n /** Scheduling query: list enabled subscriptions ordered by staleness. */\n idxIntegrationSubscriptionsEnabledLastIntegration: index(\n 'idx_integration_subscriptions_enabled_last_integration',\n ).on(t.enabled, t.lastIntegrationAt),\n }),\n);\n\nexport type IntegrationSubscriptionRow = InferSelectModel<typeof integrationSubscriptions>;\n\n// ─── integration_runs ──────────────────────────────────────────────────────────────\n\n/**\n * One row per invocation of `ExecuteIntegrationUseCase`. `started_at` is set when\n * the recorder opens the run; `completed_at`, `status`, `records_*`,\n * `cursor_after`, and `duration_ms` are filled on completion.\n *\n * `cursor_before` / `cursor_after` carry the opaque cursor snapshots so the\n * run log is fully self-describing — given a run id, an operator can reason\n * about exactly what window was scanned without cross-referencing another\n * table.\n */\nexport const integrationRuns = pgTable(\n 'integration_runs',\n {\n id: uuid('id').primaryKey().defaultRandom(),\n subscriptionId: uuid('subscription_id')\n .notNull()\n .references(() => integrationSubscriptions.id, { onDelete: 'cascade' }),\n direction: integrationRunDirectionEnum('direction').notNull(),\n action: integrationRunActionEnum('action').notNull(),\n status: integrationRunStatusEnum('status').notNull().default('running'),\n recordsFound: integer('records_found').notNull().default(0),\n recordsProcessed: integer('records_processed').notNull().default(0),\n cursorBefore: jsonb('cursor_before').$type<unknown>(),\n cursorAfter: jsonb('cursor_after').$type<unknown>(),\n durationMs: integer('duration_ms'),\n error: text('error'),\n startedAt: timestamp('started_at', { withTimezone: true })\n .notNull()\n .defaultNow(),\n completedAt: timestamp('completed_at', { withTimezone: true }),\n /** Runtime-enforced when `INTEGRATION_MULTI_TENANT` is true; see SYNC-6. */\n tenantId: text('tenant_id'),\n },\n (t) => ({\n /** Timeline read: \"most recent runs for this subscription\". */\n idxIntegrationRunsSubscriptionStartedAt: index(\n 'idx_integration_runs_subscription_started_at',\n ).on(t.subscriptionId, t.startedAt),\n /** Stale-run sweeper: \"runs that started > N minutes ago and are still running\". */\n idxIntegrationRunsStatusStartedAt: index('idx_integration_runs_status_started_at').on(\n t.status,\n t.startedAt,\n ),\n }),\n);\n\nexport type IntegrationRunRow = InferSelectModel<typeof integrationRuns>;\n\n// ─── integration_run_items ─────────────────────────────────────────────────────────\n\n/**\n * One row per upstream change processed within a run. Captures the canonical\n * decision the orchestrator made (`operation` + `status`), the structured\n * per-field diff (`changed_fields`, ADR-0003), and the local row id\n * (`local_id`) for drill-down joins.\n *\n * `changed_fields` is validated at the recorder layer via `FieldDiffSchema`\n * (SYNC-2) — the $type<FieldDiff> annotation here only documents the shape\n * for Drizzle consumers. The runtime enforcement is non-negotiable: downstream\n * drift-detection queries rely on the `{from, to}` shape per field.\n *\n * `title` is an optional human-readable label captured at write time (e.g.\n * `\"Pinnacle opportunity\"`) so run-log UIs don't need to re-hydrate the\n * canonical record.\n */\nexport const integrationRunItems = pgTable(\n 'integration_run_items',\n {\n id: uuid('id').primaryKey().defaultRandom(),\n integrationRunId: uuid('integration_run_id')\n .notNull()\n .references(() => integrationRuns.id, { onDelete: 'cascade' }),\n entityType: text('entity_type').notNull(),\n externalId: text('external_id').notNull(),\n localId: text('local_id'),\n operation: integrationRunItemOperationEnum('operation').notNull(),\n status: integrationRunItemStatusEnum('status').notNull(),\n /**\n * Structured per-field diff — ADR-0003 shape enforced by\n * `FieldDiffSchema.parse` at the recorder service layer.\n *\n * Shape: `{ [fieldName]: { from: unknown, to: unknown } }`.\n * Empty `{}` for `noop` items; `{ [field]: { from: null, to: <value> } }`\n * for created items; `{ [field]: { from: <value>, to: null } }` for\n * deleted items.\n */\n changedFields: jsonb('changed_fields').notNull().default({}).$type<FieldDiff>(),\n title: text('title'),\n error: text('error'),\n createdAt: timestamp('created_at', { withTimezone: true })\n .notNull()\n .defaultNow(),\n /** Runtime-enforced when `INTEGRATION_MULTI_TENANT` is true; see SYNC-6. */\n tenantId: text('tenant_id'),\n },\n (t) => ({\n /** Ordered timeline within a run. */\n idxIntegrationRunItemsRunCreatedAt: index('idx_integration_run_items_run_created_at').on(\n t.integrationRunId,\n t.createdAt,\n ),\n /** Per-record history: \"every integration that touched opportunity/$extId\". */\n idxIntegrationRunItemsEntityExternal: index(\n 'idx_integration_run_items_entity_external',\n ).on(t.entityType, t.externalId),\n }),\n);\n\nexport type IntegrationRunItemRow = InferSelectModel<typeof integrationRunItems>;\n","/**\n * MemoryCursorStore — in-memory backend for `ICursorStore` (SYNC-3).\n *\n * Test double that lets consumers exercise `ExecuteIntegrationUseCase` (SYNC-5) and\n * other cursor-consuming code paths without Postgres. Mirrors the role of\n * `MemoryEventBus` and `MemoryJobStore`: plain keyed state, tests take a\n * direct reference for `beforeEach` resets.\n *\n * Cursor values are stored by reference — the port's `get`/`put` contract\n * treats them as opaque `unknown`. Callers that want durable value-equality\n * semantics should snapshot via JSON before `put` and reparse after `get`;\n * this is what the Drizzle backend (SYNC-4) does implicitly via jsonb\n * round-trip. The memory backend intentionally does not simulate the\n * serialize/deserialize cycle — consumers who care should test against\n * Postgres.\n *\n * ## Multi-tenancy\n *\n * `tenantId` is accepted but ignored. The memory backend's state is\n * process-local — there's no durable storage where a cross-tenant leak\n * could occur. Tests that want to assert per-tenant isolation should\n * target the Drizzle backend.\n *\n * Not shipped in the upstream consumer; this is a subsystem-first addition for the\n * test surface. Consumed by:\n * - SYNC-5 unit tests (`ExecuteIntegrationUseCase` against synthetic sources)\n * - SYNC-6 module tests (`IntegrationModule.forRoot({ backend: 'memory' })`)\n */\nimport { Injectable } from '@nestjs/common';\nimport type {\n CursorSnapshot,\n ICursorStore,\n} from './integration-cursor-store.protocol';\nimport type { MemoryIntegrationSubscription } from './integration-run-recorder.memory-backend';\n\n@Injectable()\nexport class MemoryCursorStore implements ICursorStore {\n /**\n * Subscription-id → last persisted cursor. Public so tests can inspect\n * or pre-seed state; production callers MUST go through `get`/`put`.\n */\n readonly cursors: Map<string, unknown> = new Map();\n\n /**\n * Seedable subscription metadata for `listAll` — the memory backend\n * stores only `subscriptionId → cursor` in its write path, so the\n * snapshot shape (`connectionId`, `adapter`, `domain`, `externalRef`,\n * timestamps) has no natural source without test seeding. Tests populate\n * this map; unseeded entries get empty-string metadata and `new Date(0)`\n * timestamps so the shape stays stable. Production paths go through the\n * Drizzle backend.\n */\n readonly subscriptions: Map<string, MemoryIntegrationSubscription> = new Map();\n\n async get(\n subscriptionId: string,\n _tenantId?: string | null,\n ): Promise<unknown | null> {\n // `Map.get` returns `undefined` for missing keys; the port contract\n // returns `null`. Normalize here so callers can `=== null`-check.\n const value = this.cursors.get(subscriptionId);\n return value === undefined ? null : value;\n }\n\n async put(\n subscriptionId: string,\n cursor: unknown,\n _tenantId?: string | null,\n ): Promise<void> {\n // Overwrite semantics — matches the port contract and the Drizzle\n // backend's `ON CONFLICT DO UPDATE` behavior.\n this.cursors.set(subscriptionId, cursor);\n }\n\n async listAll(_tenantId?: string | null): Promise<CursorSnapshot[]> {\n // Accepts tenantId for contract symmetry but does not filter on it —\n // the memory backend never enforces tenancy (see class-level comment).\n const snapshots: CursorSnapshot[] = [];\n for (const [subscriptionId, cursor] of this.cursors.entries()) {\n const meta = this.subscriptions.get(subscriptionId);\n snapshots.push({\n subscriptionId,\n connectionId: meta?.connectionId ?? '',\n adapter: meta?.adapter ?? '',\n domain: meta?.domain ?? '',\n externalRef: meta?.externalRef ?? null,\n cursor: cursor ?? null,\n lastIntegrationAt: meta?.lastIntegrationAt ?? null,\n updatedAt: meta?.updatedAt ?? new Date(0),\n tenantId: null,\n });\n }\n return snapshots.sort(\n (a, b) => b.updatedAt.getTime() - a.updatedAt.getTime(),\n );\n }\n\n /** Reset state. Tests call this in `beforeEach`. */\n clear(): void {\n this.cursors.clear();\n this.subscriptions.clear();\n }\n}\n","/**\n * MemoryRunRecorder — in-memory backend for `IIntegrationRunRecorder` (SYNC-6).\n *\n * Test double so `IntegrationModule.forRoot({ backend: 'memory' })` is genuinely\n * end-to-end runnable without Postgres. Mirrors the role of\n * `MemoryCursorStore`: plain keyed state, `clear()` helper for\n * `beforeEach` resets, public inspection surface so tests can assert on\n * the recorded run + item timeline without scraping logs.\n *\n * Validates `changedFields` through `FieldDiffSchema.parse` on every\n * `recordItem` call — same ADR-0003 contract as the Drizzle backend. An\n * in-memory recorder that skipped the validation would be a silently\n * weaker contract than production.\n *\n * `startRun` generates a uuid via `crypto.randomUUID()` (Node 19+ / Bun).\n * We don't import `uuid` because the subsystem has no other use for it.\n *\n * ## Multi-tenancy\n *\n * `tenantId` is accepted (and recorded on the in-memory row so tests can\n * assert it) but enforcement lives at the module boundary. The memory\n * backend intentionally does not throw on missing `tenantId` — that's\n * the orchestrator's job when `multiTenant=true` (SYNC-6). A permissive\n * memory recorder lets tests exercise error paths where the orchestrator\n * short-circuits before ever reaching the recorder.\n */\nimport { Injectable } from '@nestjs/common';\nimport type {\n CompleteRunInput,\n IIntegrationRunRecorder,\n RecordItemInput,\n StartRunInput,\n IntegrationRunSummary,\n} from './integration-run-recorder.protocol';\nimport { FieldDiffSchema } from './integration-field-diff.protocol';\n\n/**\n * Optional per-subscription metadata a test can seed on the memory backend\n * so `listRecent` can surface `connectionId`. The memory recorder's write\n * path never persists subscription rows (it only stores runs + items), so\n * `listRecent` has no way to derive `connectionId` on its own. Tests that\n * care about the field should populate `subscriptions` before calling\n * `listRecent`; calls that don't seed get an empty string and a stable\n * shape (see `listRecent` below).\n */\nexport interface MemoryIntegrationSubscription {\n connectionId: string;\n adapter: string;\n domain: string;\n externalRef: string | null;\n lastIntegrationAt?: Date | null;\n updatedAt: Date;\n}\n\n/**\n * Concrete run row as held in memory. Shape mirrors the interesting\n * columns on `integration_runs` so assertions read like DB queries.\n */\nexport interface MemoryRunRecord {\n id: string;\n subscriptionId: string;\n direction: 'inbound' | 'outbound';\n action: 'poll' | 'cdc' | 'webhook' | 'manual' | 'writeback';\n status: 'running' | 'success' | 'no_changes' | 'failed';\n cursorBefore: unknown | null;\n cursorAfter: unknown | null;\n recordsFound: number;\n recordsProcessed: number;\n durationMs: number | null;\n error: string | null;\n tenantId: string | null;\n startedAt: Date;\n completedAt: Date | null;\n}\n\n@Injectable()\nexport class MemoryRunRecorder implements IIntegrationRunRecorder {\n /**\n * All started runs keyed by id. Public so tests can inspect lifecycle\n * transitions without poking through recording methods.\n */\n readonly runs: Map<string, MemoryRunRecord> = new Map();\n\n /**\n * Items keyed by `integration_run_id`, array order matches insertion order —\n * mirrors the timeline the `(integration_run_id, created_at)` index produces\n * in Postgres.\n */\n readonly items: Map<string, RecordItemInput[]> = new Map();\n\n /**\n * Seedable subscription metadata — tests populate this to make\n * `listRecent` return meaningful `connectionId` values. The memory\n * backend doesn't track subscriptions on its own (only runs + items), so\n * this map is the intentional extension point: tests write entries for\n * the subscription ids they use, production code never touches it.\n */\n readonly subscriptions: Map<string, MemoryIntegrationSubscription> = new Map();\n\n async startRun(input: StartRunInput): Promise<{ id: string }> {\n const id = crypto.randomUUID();\n this.runs.set(id, {\n id,\n subscriptionId: input.subscriptionId,\n direction: input.direction,\n action: input.action,\n status: 'running',\n cursorBefore: input.cursorBefore ?? null,\n cursorAfter: null,\n recordsFound: 0,\n recordsProcessed: 0,\n durationMs: null,\n error: null,\n tenantId: input.tenantId ?? null,\n startedAt: new Date(),\n completedAt: null,\n });\n this.items.set(id, []);\n return { id };\n }\n\n async recordItem(input: RecordItemInput): Promise<void> {\n // Same ADR-0003 contract as the Drizzle backend.\n FieldDiffSchema.parse(input.changedFields);\n\n const bucket = this.items.get(input.integrationRunId);\n if (!bucket) {\n throw new Error(\n `MemoryRunRecorder.recordItem: no run started for id '${input.integrationRunId}'. ` +\n `Call startRun(...) first.`,\n );\n }\n bucket.push(input);\n }\n\n async completeRun(runId: string, input: CompleteRunInput): Promise<void> {\n const run = this.runs.get(runId);\n if (!run) {\n throw new Error(\n `MemoryRunRecorder.completeRun: no run started for id '${runId}'.`,\n );\n }\n run.status = input.status;\n run.recordsFound = input.recordsFound;\n run.recordsProcessed = input.recordsProcessed;\n run.cursorAfter = input.cursorAfter ?? null;\n run.durationMs = input.durationMs;\n run.error = input.error ?? null;\n run.completedAt = new Date();\n }\n\n async listRecent(\n limit: number,\n subscriptionId?: string,\n _tenantId?: string | null,\n ): Promise<IntegrationRunSummary[]> {\n // Memory backend accepts tenantId for contract symmetry but does not\n // filter on it — state is process-local and cross-tenant isolation is\n // not meaningful here (matches MemoryCursorStore behavior).\n const all = Array.from(this.runs.values());\n const filtered =\n subscriptionId === undefined\n ? all\n : all.filter((r) => r.subscriptionId === subscriptionId);\n return filtered\n .sort((a, b) => b.startedAt.getTime() - a.startedAt.getTime())\n .slice(0, limit)\n .map((r) => ({\n id: r.id,\n subscriptionId: r.subscriptionId,\n // connectionId is only knowable if the test seeded subscriptions\n // metadata; empty string otherwise. The Drizzle backend resolves\n // it via JOIN, which is the production path.\n connectionId:\n this.subscriptions.get(r.subscriptionId)?.connectionId ?? '',\n status: r.status,\n startedAt: r.startedAt,\n completedAt: r.completedAt,\n recordsProcessed: r.recordsProcessed,\n tenantId: r.tenantId,\n }));\n }\n\n /** Reset state. Tests call this in `beforeEach`. */\n clear(): void {\n this.runs.clear();\n this.items.clear();\n this.subscriptions.clear();\n }\n\n // ─── test ergonomics ─────────────────────────────────────────────────\n\n /** All runs for a subscription, newest first. Timeline reads. */\n getRunsForSubscription(subscriptionId: string): MemoryRunRecord[] {\n return Array.from(this.runs.values())\n .filter((r) => r.subscriptionId === subscriptionId)\n .sort((a, b) => b.startedAt.getTime() - a.startedAt.getTime());\n }\n\n /** All item rows for a run, insertion-ordered. */\n getItemsForRun(runId: string): RecordItemInput[] {\n return this.items.get(runId) ?? [];\n }\n}\n","/**\n * DeepEqualDiffer — default `IFieldDiffer<T>` for the integration subsystem (SYNC-5).\n *\n * Walks every field of `incoming` against `existing`, emitting a structured\n * per-field diff (`{ from, to }`) for every field whose value changed.\n * Returns `'noop'` when the record is unchanged.\n *\n * Design decisions (extracted from the upstream consumer + HS-9 findings):\n *\n * 1. **Ignore list** — row metadata that sinks/services stamp unconditionally\n * so upstream cannot reasonably disagree:\n * `id`, `createdAt`, `updatedAt`, `deletedAt`, `type`,\n * `lastModifiedAt`, `fields`, `providerMetadata`\n * (`fields` is the EAV bag — it's diffed by the sink's EAV dual-write\n * path, not at the canonical-record layer.)\n *\n * 2. **`providerChangedFields` hint (CDC)** — when present, restricts the\n * comparison to the hinted field set. The hint is advisory; fields in\n * the ignore list are still filtered out even when hinted. Provider\n * hints are field-NAME-level; they don't override the ignore rules.\n *\n * 3. **Date → ISO string** — `Date` instances are normalized to\n * `toISOString()` before comparison. Sinks return `Date` from the DB\n * driver; adapters typically deliver strings. Direct `===` would\n * always say \"changed.\"\n *\n * 4. **Decimal-string vs number** — Postgres `numeric` columns return as\n * strings through Drizzle; adapters deliver numbers. When one side is a\n * number and the other is a numeric string that parses to the same\n * number, they're equal. The normalizer does NOT coerce non-numeric\n * strings, and it preserves zero-vs-null distinction.\n *\n * 5. **null-existing path** — `diff(null, incoming)` produces a full\n * created-shape diff (`{from: null, to: <value>}` for every non-ignored\n * field). Orchestrator sees this and records `operation: 'created'`.\n */\nimport { Injectable } from '@nestjs/common';\nimport type {\n DiffResult,\n FieldDiff,\n IFieldDiffer,\n} from './integration-field-diff.protocol';\n\n/**\n * Default ignore list. Keep in integration with consumer canonical-record shapes —\n * adding a row-metadata field here means no integration will ever mark it changed.\n *\n * Includes the columns contributed by the `external_id_tracking` behavior\n * (`external_id`/`externalId`, `provider`, `provider_metadata`/`providerMetadata`).\n * These are integration-tracking metadata, not domain attributes: they ride on the\n * canonical record but must never register as a field change (the external id\n * is the record's identity, not a mutable value). Listed in both snake_case\n * and camelCase so the differ ignores them regardless of the consumer's\n * canonical projection casing.\n */\nconst DEFAULT_IGNORE_FIELDS: ReadonlySet<string> = new Set([\n 'id',\n 'createdAt',\n 'updatedAt',\n 'deletedAt',\n 'type',\n 'lastModifiedAt',\n 'fields',\n 'external_id',\n 'externalId',\n 'provider',\n 'provider_metadata',\n 'providerMetadata',\n]);\n\nexport interface DeepEqualDifferOptions {\n /**\n * Extra field names to ignore in addition to the defaults. Consumers can\n * pass `['integration_version']` etc. to augment the base list; values here are\n * merged (not replaced) with `DEFAULT_IGNORE_FIELDS`.\n */\n readonly ignore?: readonly string[];\n}\n\n@Injectable()\nexport class DeepEqualDiffer<T extends Record<string, unknown>>\n implements IFieldDiffer<T>\n{\n private readonly ignore: ReadonlySet<string>;\n\n constructor(opts: DeepEqualDifferOptions = {}) {\n if (opts.ignore && opts.ignore.length > 0) {\n this.ignore = new Set([...DEFAULT_IGNORE_FIELDS, ...opts.ignore]);\n } else {\n this.ignore = DEFAULT_IGNORE_FIELDS;\n }\n }\n\n diff(\n existing: T | null,\n incoming: T,\n providerChangedFields?: string[],\n ): DiffResult {\n // Created-shape: every non-ignored field becomes `{from: null, to}`.\n if (existing === null) {\n const out: FieldDiff = {};\n for (const key of Object.keys(incoming)) {\n if (this.ignore.has(key)) continue;\n const value = (incoming as Record<string, unknown>)[key];\n // Skip fields that are themselves null/undefined — a created record\n // doesn't need to declare \"this field is null now\" for every\n // untouched column.\n if (value === null || value === undefined) continue;\n out[key] = { from: null, to: value };\n }\n return Object.keys(out).length === 0 ? 'noop' : out;\n }\n\n // Field set to compare. `providerChangedFields` narrows to a hint set;\n // ignored fields are filtered out regardless of hint.\n const candidates = new Set<string>();\n if (providerChangedFields && providerChangedFields.length > 0) {\n for (const key of providerChangedFields) {\n if (!this.ignore.has(key)) candidates.add(key);\n }\n } else {\n for (const key of Object.keys(incoming)) {\n if (!this.ignore.has(key)) candidates.add(key);\n }\n // Also include keys that exist on existing but not on incoming —\n // e.g. a field that was cleared. This would otherwise be missed when\n // incoming carries an undefined column we drop from the iteration.\n for (const key of Object.keys(existing)) {\n if (this.ignore.has(key)) continue;\n if (!(key in (incoming as Record<string, unknown>))) continue;\n candidates.add(key);\n }\n }\n\n const out: FieldDiff = {};\n for (const key of candidates) {\n const before = (existing as Record<string, unknown>)[key];\n const after = (incoming as Record<string, unknown>)[key];\n if (!isEqual(before, after)) {\n out[key] = { from: before ?? null, to: after ?? null };\n }\n }\n\n return Object.keys(out).length === 0 ? 'noop' : out;\n }\n}\n\n// ─── equality helpers ───────────────────────────────────────────────────────\n\n/**\n * Field-level equality with the canonical-integration normalizations:\n * - Date → toISOString (adapters deliver strings)\n * - numeric-string vs number → numeric equality when both parse\n * - deep equality for plain objects/arrays (single-level is enough for\n * canonical records; nested records travel as jsonb columns where the\n * sink already owns the comparison)\n */\nfunction isEqual(a: unknown, b: unknown): boolean {\n if (a === b) return true;\n\n const na = normalize(a);\n const nb = normalize(b);\n if (na === nb) return true;\n\n // After normalization: both may still be non-primitive objects.\n if (\n typeof na === 'object' &&\n typeof nb === 'object' &&\n na !== null &&\n nb !== null\n ) {\n return deepEqualObject(na as Record<string, unknown>, nb as Record<string, unknown>);\n }\n\n // Numeric string ↔ number: when one side is a number and the other is a\n // string that parses to the same finite number.\n const numericEqual = maybeNumericEqual(na, nb) || maybeNumericEqual(nb, na);\n return numericEqual;\n}\n\nfunction normalize(value: unknown): unknown {\n if (value instanceof Date) return value.toISOString();\n return value;\n}\n\nfunction maybeNumericEqual(a: unknown, b: unknown): boolean {\n // a is string-shape, b is number — parse a and compare. Only when the\n // string looks numeric AND the parse round-trips (no silent NaN pass-\n // through on non-numeric strings).\n if (typeof a !== 'string' || typeof b !== 'number') return false;\n if (a.trim() === '') return false;\n const parsed = Number(a);\n if (!Number.isFinite(parsed)) return false;\n return parsed === b;\n}\n\nfunction deepEqualObject(\n a: Record<string, unknown>,\n b: Record<string, unknown>,\n): boolean {\n if (Array.isArray(a) !== Array.isArray(b)) return false;\n const aKeys = Object.keys(a);\n const bKeys = Object.keys(b);\n if (aKeys.length !== bKeys.length) return false;\n for (const key of aKeys) {\n if (!(key in b)) return false;\n if (!isEqual(a[key], b[key])) return false;\n }\n return true;\n}\n","/**\n * ExecuteIntegrationUseCase — the generic integration orchestrator (SYNC-5).\n *\n * One class. Reused across every `(provider, detection-mode, canonical-entity)`\n * tuple. Parameterized over `T` so canonical records stay typed end-to-end.\n *\n * Flow per run:\n *\n * 1. `recorder.startRun(...)` — opens a `integration_runs` row in 'running'.\n * 2. for each change yielded by `source.listChanges(subscription, cursorBefore)`:\n * a. differ.diff(existing, incoming) → 'noop' short-circuits to\n * a noop audit row (no sink write).\n * b. sink.upsertByExternalId / softDeleteByExternalId → records\n * the local id on the audit row.\n * c. per-item try/catch — a failed item increments the failed\n * counter and records `status: 'failed'` with `error`, but\n * does NOT abort the run.\n * d. advance `latestCursor = change.cursor` as the iterator moves.\n * 3. `cursors.put(subscription.id, latestCursor)` when the loop completes\n * AND at least one cursor advance happened. On exceptions from the\n * source iterator (auth expiry, network error), we persist the\n * last-good cursor so the next run resumes from the last known\n * successful position.\n * 4. `finally { recorder.completeRun(...) }` — always terminates the run.\n *\n * Loopback suppression — when a consumer's writes echo back on the next\n * inbound poll/CDC/webhook — is composed into the source's middleware\n * chain via `createLoopbackMiddleware(store)` (#226-5 / ADR-033). The\n * orchestrator no longer special-cases echoes: middleware drops them\n * before they reach this loop. Consumers that don't have outbound\n * writeback paths simply omit the middleware.\n *\n * ## Generics\n *\n * - `T` = canonical record shape from the adapter side. Same `T` flows\n * through `IChangeSource<T>`, `IFieldDiffer<T>`, `IIntegrationSink<T>`.\n *\n * ## No CRM bleed\n *\n * Per the SYNC-5 issue's extraction notes (HS-9 finding), this orchestrator\n * is strictly provider-agnostic:\n * - `entityType` is `string` throughout; no `'opportunity' | 'account' | ...`\n * narrowing leaks into the use case\n * - the upstream consumer's `IntegrationRunRecorderService` class injection replaced with the\n * `IIntegrationRunRecorder` protocol (backend lands in SYNC-4)\n */\nimport { Inject, Injectable, Logger, Optional } from '@nestjs/common';\nimport type { IChangeSource, Change } from './integration-change-source.protocol';\nimport type { ICursorStore } from './integration-cursor-store.protocol';\nimport type { IFieldDiffer, FieldDiff } from './integration-field-diff.protocol';\nimport type { IIntegrationSink } from './integration-sink.protocol';\nimport type { IIntegrationRunRecorder } from './integration-run-recorder.protocol';\nimport { assertTenantId } from './integration-errors';\nimport {\n INTEGRATION_CHANGE_SOURCE,\n INTEGRATION_CURSOR_STORE,\n INTEGRATION_FIELD_DIFFER,\n INTEGRATION_MULTI_TENANT,\n INTEGRATION_RUN_RECORDER,\n INTEGRATION_SINK,\n} from './integration.tokens';\n\n// ============================================================================\n// Inputs + result\n// ============================================================================\n\nexport interface ExecuteIntegrationInput<T> {\n /** The subscription whose cursor/identity frames this run. */\n readonly subscription: {\n readonly id: string;\n readonly domain: string; // entityType — used on audit rows\n readonly externalRef?: string | null;\n };\n /** Per-run user context; threaded through sink writes. */\n readonly userId: string;\n /** Provider label persisted on saved rows, e.g. `'salesforce-crm'`. */\n readonly provider: string;\n /** Run direction — almost always `'inbound'`. Reserved for writeback. */\n readonly direction: 'inbound' | 'outbound';\n /** Detection mode — maps 1:1 to `integration_runs.action`. */\n readonly action: 'poll' | 'cdc' | 'webhook' | 'manual' | 'writeback';\n /** Multi-tenant deployments pass the tenant id through. */\n readonly tenantId?: string | null;\n /**\n * Optional override — inject a specific change source for this run when\n * the DI-bound source is not the one to use (e.g. manual backfill with\n * a custom cursor). Defaults to the DI-resolved `INTEGRATION_CHANGE_SOURCE`.\n */\n readonly sourceOverride?: IChangeSource<T>;\n}\n\nexport interface ExecuteIntegrationResult {\n readonly runId: string;\n readonly status: 'success' | 'no_changes' | 'failed';\n readonly recordsFound: number;\n readonly recordsProcessed: number;\n readonly recordsFailed: number;\n readonly cursorBefore: unknown | null;\n readonly cursorAfter: unknown | null;\n readonly durationMs: number;\n readonly error?: string | null;\n}\n\n// ============================================================================\n// ExecuteIntegrationUseCase\n// ============================================================================\n\n@Injectable()\nexport class ExecuteIntegrationUseCase<T extends Record<string, unknown>> {\n private readonly logger = new Logger(ExecuteIntegrationUseCase.name);\n\n constructor(\n @Inject(INTEGRATION_CHANGE_SOURCE) private readonly source: IChangeSource<T>,\n @Inject(INTEGRATION_CURSOR_STORE) private readonly cursors: ICursorStore,\n @Inject(INTEGRATION_FIELD_DIFFER) private readonly differ: IFieldDiffer<T>,\n @Inject(INTEGRATION_SINK) private readonly sink: IIntegrationSink<T>,\n @Inject(INTEGRATION_RUN_RECORDER) private readonly recorder: IIntegrationRunRecorder,\n @Optional()\n @Inject(INTEGRATION_MULTI_TENANT)\n private readonly multiTenant: boolean = false,\n ) {}\n\n async execute(input: ExecuteIntegrationInput<T>): Promise<ExecuteIntegrationResult> {\n // Defense-in-depth tenancy guard — fire BEFORE startRun so a rejected\n // input never leaves a dangling `status=running` row. Backends also\n // enforce (SYNC-4), but failing fast at the orchestrator boundary is\n // cheaper for observability, metrics, and manual cleanup.\n assertTenantId(input.tenantId, {\n multiTenant: this.multiTenant,\n operation: 'execute',\n });\n\n const source = input.sourceOverride ?? this.source;\n const startedAt = Date.now();\n const cursorBefore = await this.cursors.get(input.subscription.id, input.tenantId);\n\n const { id: runId } = await this.recorder.startRun({\n subscriptionId: input.subscription.id,\n direction: input.direction,\n action: input.action,\n cursorBefore,\n tenantId: input.tenantId,\n });\n\n let recordsFound = 0;\n let recordsProcessed = 0;\n let recordsFailed = 0;\n let latestCursor: unknown | null = cursorBefore;\n let cursorAdvanced = false;\n let runError: string | null = null;\n let status: 'success' | 'no_changes' | 'failed' = 'no_changes';\n\n try {\n for await (const change of source.listChanges(input.subscription, cursorBefore)) {\n recordsFound++;\n latestCursor = change.cursor;\n cursorAdvanced = true;\n\n try {\n await this.processChange(runId, input, change);\n recordsProcessed++;\n } catch (err) {\n recordsFailed++;\n const message = err instanceof Error ? err.message : String(err);\n this.logger.warn(\n `integration item failed: subscription=${input.subscription.id} externalId=${change.externalId}: ${message}`,\n );\n await this.recorder.recordItem({\n integrationRunId: runId,\n entityType: input.subscription.domain,\n externalId: change.externalId,\n operation: change.operation === 'deleted' ? 'deleted' : 'updated',\n status: 'failed',\n changedFields: {},\n error: message,\n tenantId: input.tenantId,\n });\n }\n }\n\n if (recordsFailed > 0 && recordsProcessed === 0 && recordsFound > 0) {\n // Every record we saw failed — call the run a failure, not a\n // success. Partial success (some processed, some failed) still\n // counts as 'success' so the cursor advances.\n status = 'failed';\n runError = `all ${recordsFailed} records failed`;\n } else if (recordsFound === 0) {\n status = 'no_changes';\n } else {\n status = 'success';\n }\n } catch (err) {\n // Source iterator itself threw — cursor DOES NOT advance past the\n // last-successful cursor. `latestCursor` still holds the last\n // `change.cursor` we observed, which is the furthest we know to\n // have delivered. Persist it (below) so next run resumes there.\n status = 'failed';\n runError = err instanceof Error ? err.message : String(err);\n this.logger.error(\n `integration source failed: subscription=${input.subscription.id}: ${runError}`,\n );\n }\n\n // Persist cursor advance only when something actually moved. Never\n // overwrite a valid cursor with `null` on a no-change run.\n if (cursorAdvanced && latestCursor !== null && latestCursor !== undefined) {\n try {\n await this.cursors.put(input.subscription.id, latestCursor, input.tenantId);\n } catch (err) {\n const message = err instanceof Error ? err.message : String(err);\n this.logger.error(\n `cursor put failed: subscription=${input.subscription.id}: ${message}`,\n );\n if (status !== 'failed') {\n status = 'failed';\n runError = `cursor put failed: ${message}`;\n }\n }\n }\n\n const durationMs = Date.now() - startedAt;\n\n await this.recorder.completeRun(runId, {\n status,\n recordsFound,\n recordsProcessed,\n cursorAfter: cursorAdvanced ? latestCursor : cursorBefore,\n durationMs,\n error: runError,\n });\n\n return {\n runId,\n status,\n recordsFound,\n recordsProcessed,\n recordsFailed,\n cursorBefore,\n cursorAfter: cursorAdvanced ? latestCursor : cursorBefore,\n durationMs,\n error: runError,\n };\n }\n\n private async processChange(\n runId: string,\n input: ExecuteIntegrationInput<T>,\n change: Change<T>,\n ): Promise<void> {\n // Deletion branch — no diff, no upsert; soft-delete via sink.\n if (change.operation === 'deleted') {\n const result = await this.sink.softDeleteByExternalId(\n input.userId,\n change.externalId,\n );\n await this.recorder.recordItem({\n integrationRunId: runId,\n entityType: input.subscription.domain,\n externalId: change.externalId,\n localId: result?.id ?? null,\n operation: result ? 'deleted' : 'noop',\n status: 'success',\n changedFields: {},\n tenantId: input.tenantId,\n });\n return;\n }\n\n // Create/update path — diff against local state, short-circuit on noop.\n const existing = await this.sink.findByExternalId(\n input.userId,\n change.externalId,\n );\n const diff = this.differ.diff(\n existing,\n change.record,\n change.providerChangedFields,\n );\n\n if (diff === 'noop') {\n // Sinks that declare `reprojectsOnNoop` reproject side data the differ\n // can't see (e.g. EAV field_values) — so fall through to the idempotent\n // upsert instead of short-circuiting. The canonical state is unchanged,\n // so the audit `operation` stays `'noop'`, but we capture the local id\n // returned by the upsert. Sinks without the flag keep today's behavior.\n if (!this.sink.reprojectsOnNoop) {\n await this.recorder.recordItem({\n integrationRunId: runId,\n entityType: input.subscription.domain,\n externalId: change.externalId,\n localId: null,\n operation: 'noop',\n status: 'success',\n changedFields: {},\n tenantId: input.tenantId,\n });\n return;\n }\n\n const { id: noopLocalId } = await this.sink.upsertByExternalId(\n input.userId,\n change.record,\n input.provider,\n );\n await this.recorder.recordItem({\n integrationRunId: runId,\n entityType: input.subscription.domain,\n externalId: change.externalId,\n localId: noopLocalId,\n operation: 'noop',\n status: 'success',\n changedFields: {},\n tenantId: input.tenantId,\n });\n return;\n }\n\n const { id: localId } = await this.sink.upsertByExternalId(\n input.userId,\n change.record,\n input.provider,\n );\n\n await this.recorder.recordItem({\n integrationRunId: runId,\n entityType: input.subscription.domain,\n externalId: change.externalId,\n localId,\n operation: existing === null ? 'created' : 'updated',\n status: 'success',\n changedFields: diff as FieldDiff,\n tenantId: input.tenantId,\n });\n }\n}\n","/**\n * PostgresCursorStore — Drizzle-backed `ICursorStore` (SYNC-4).\n *\n * Reads/writes `integration_subscriptions.cursor` directly — no service\n * composition. Consumers that want a service layer around subscriptions\n * wire it themselves; the port's contract is just cursor persistence.\n *\n * ## What `put` stamps\n *\n * `put` writes three columns in one statement: `cursor`, `last_integration_at`,\n * and `updated_at`. Rationale: SYNC-1's scheduling index\n * `(enabled, last_integration_at)` is useless if `last_integration_at` doesn't advance\n * with every cursor put. Every real consumer needs this stamped, so\n * bundling it here avoids every consumer wrapping the port in a service\n * layer just to stamp a timestamp.\n *\n * ## Multi-tenancy\n *\n * When `INTEGRATION_MULTI_TENANT` is true (SYNC-6):\n * - every read/write is scoped by `AND tenant_id = $tenantId`\n * - a null/missing `tenantId` throws `MissingTenantIdError` via the\n * shared `assertTenantId` helper (one message shape across the\n * orchestrator + both backends, SYNC-6)\n * - explicit `null` also throws — matches JOB-8 / EVT-6 strict-enforcement\n *\n * When the flag is off, `tenantId` is ignored. Cross-tenant isolation is\n * the caller's problem in single-tenant deployments.\n */\nimport { Inject, Injectable, Optional } from '@nestjs/common';\nimport { and, desc, eq, type SQL } from 'drizzle-orm';\nimport type { DrizzleClient } from '../../types/drizzle';\nimport { DRIZZLE } from '../../constants/tokens';\nimport type {\n CursorSnapshot,\n ICursorStore,\n} from './integration-cursor-store.protocol';\nimport { integrationSubscriptions } from './integration-audit.schema';\nimport { INTEGRATION_MULTI_TENANT } from './integration.tokens';\nimport { assertTenantId } from './integration-errors';\n\n@Injectable()\nexport class PostgresCursorStore implements ICursorStore {\n private readonly multiTenant: boolean;\n\n constructor(\n @Inject(DRIZZLE) private readonly db: DrizzleClient,\n @Optional() @Inject(INTEGRATION_MULTI_TENANT) multiTenant?: boolean,\n ) {\n this.multiTenant = multiTenant ?? false;\n }\n\n async get(\n subscriptionId: string,\n tenantId?: string | null,\n ): Promise<unknown | null> {\n const where = this.buildWhere(subscriptionId, tenantId, 'cursor.get');\n\n const rows = await this.db\n .select({ cursor: integrationSubscriptions.cursor })\n .from(integrationSubscriptions)\n .where(where)\n .limit(1);\n\n if (rows.length === 0) return null;\n return rows[0]?.cursor ?? null;\n }\n\n async put(\n subscriptionId: string,\n cursor: unknown,\n tenantId?: string | null,\n ): Promise<void> {\n const where = this.buildWhere(subscriptionId, tenantId, 'cursor.put');\n\n await this.db\n .update(integrationSubscriptions)\n .set({\n cursor,\n lastIntegrationAt: new Date(),\n updatedAt: new Date(),\n })\n .where(where);\n }\n\n async listAll(tenantId?: string | null): Promise<CursorSnapshot[]> {\n assertTenantId(tenantId, {\n multiTenant: this.multiTenant,\n operation: 'cursor.listAll',\n });\n\n const where = this.multiTenant\n ? eq(integrationSubscriptions.tenantId, tenantId as string)\n : undefined;\n\n const rows = await this.db\n .select({\n id: integrationSubscriptions.id,\n connectionId: integrationSubscriptions.connectionId,\n adapter: integrationSubscriptions.adapter,\n domain: integrationSubscriptions.domain,\n externalRef: integrationSubscriptions.externalRef,\n cursor: integrationSubscriptions.cursor,\n lastIntegrationAt: integrationSubscriptions.lastIntegrationAt,\n updatedAt: integrationSubscriptions.updatedAt,\n tenantId: integrationSubscriptions.tenantId,\n })\n .from(integrationSubscriptions)\n .where(where)\n .orderBy(desc(integrationSubscriptions.updatedAt));\n\n return rows.map((row) => ({\n subscriptionId: row.id,\n connectionId: row.connectionId,\n adapter: row.adapter,\n domain: row.domain,\n externalRef: row.externalRef,\n cursor: row.cursor ?? null,\n lastIntegrationAt: row.lastIntegrationAt,\n updatedAt: row.updatedAt,\n tenantId: row.tenantId,\n }));\n }\n\n /**\n * Centralized WHERE clause — `get` and `put` share identical semantics.\n * Drift here would let a caller read under one tenancy rule and write\n * under another.\n */\n private buildWhere(\n subscriptionId: string,\n tenantId: string | null | undefined,\n operation: string,\n ): SQL | undefined {\n assertTenantId(tenantId, {\n multiTenant: this.multiTenant,\n operation,\n });\n if (this.multiTenant) {\n return and(\n eq(integrationSubscriptions.id, subscriptionId),\n eq(integrationSubscriptions.tenantId, tenantId as string),\n );\n }\n return eq(integrationSubscriptions.id, subscriptionId);\n }\n}\n","/**\n * DrizzleIntegrationRunRecorder — Drizzle-backed `IIntegrationRunRecorder` (SYNC-4).\n *\n * Generic write path only — extracted from the source app's\n * `IntegrationRunRecorderService`, minus CRM-specific convenience methods. Those\n * stay consumer-owned; the subsystem ships the substrate.\n *\n * ## Responsibilities\n *\n * - `startRun` — INSERT integration_runs row in status='running', returns id.\n * - `recordItem` — validates `changedFields` via `FieldDiffSchema.parse`\n * BEFORE the INSERT; a malformed shape throws before\n * any DB call fires. Enforces the ADR-0003 contract at\n * the write boundary.\n * - `completeRun` — UPDATE integration_runs with terminal status, counts,\n * cursor_after, duration_ms, completed_at.\n *\n * ## Multi-tenancy\n *\n * When `INTEGRATION_MULTI_TENANT` is true (SYNC-6):\n * - `startRun` and `recordItem` require non-null `tenantId` on input.\n * Enforcement goes through the shared `assertTenantId` helper so the\n * error message shape matches the orchestrator entry point + the\n * cursor-store backends.\n * - `completeRun` does NOT re-check tenancy — the run id was returned\n * by `startRun` which already enforced it, and run ids are uuids that\n * aren't guessable cross-tenant. Matches JOB-3's pattern of trusting\n * the run-id for downstream mutations.\n */\nimport { Inject, Injectable, Optional } from '@nestjs/common';\nimport { and, desc, eq, type SQL } from 'drizzle-orm';\nimport type { DrizzleClient } from '../../types/drizzle';\nimport { DRIZZLE } from '../../constants/tokens';\nimport type {\n CompleteRunInput,\n IIntegrationRunRecorder,\n RecordItemInput,\n StartRunInput,\n IntegrationRunSummary,\n} from './integration-run-recorder.protocol';\nimport { integrationRuns, integrationRunItems, integrationSubscriptions } from './integration-audit.schema';\nimport { FieldDiffSchema } from './integration-field-diff.protocol';\nimport { INTEGRATION_MULTI_TENANT } from './integration.tokens';\nimport { assertTenantId } from './integration-errors';\n\n@Injectable()\nexport class DrizzleIntegrationRunRecorder implements IIntegrationRunRecorder {\n private readonly multiTenant: boolean;\n\n constructor(\n @Inject(DRIZZLE) private readonly db: DrizzleClient,\n @Optional() @Inject(INTEGRATION_MULTI_TENANT) multiTenant?: boolean,\n ) {\n this.multiTenant = multiTenant ?? false;\n }\n\n async startRun(input: StartRunInput): Promise<{ id: string }> {\n assertTenantId(input.tenantId, {\n multiTenant: this.multiTenant,\n operation: 'startRun',\n });\n\n const rows = await this.db\n .insert(integrationRuns)\n .values({\n subscriptionId: input.subscriptionId,\n direction: input.direction,\n action: input.action,\n status: 'running',\n cursorBefore: input.cursorBefore ?? null,\n tenantId: input.tenantId ?? null,\n })\n .returning({ id: integrationRuns.id });\n\n const id = rows[0]?.id;\n if (!id) {\n // Drizzle's insert().returning() contract: at least one row is\n // returned for every successful INSERT. A missing id would indicate\n // a driver misbehavior; throw loudly rather than return bogus data.\n throw new Error('DrizzleIntegrationRunRecorder: INSERT RETURNING produced no id');\n }\n return { id };\n }\n\n async recordItem(input: RecordItemInput): Promise<void> {\n assertTenantId(input.tenantId, {\n multiTenant: this.multiTenant,\n operation: 'recordItem',\n });\n\n // ADR-0003 contract enforcement — reject malformed changedFields\n // before the DB call fires. `parse` throws a ZodError; callers see\n // the validation failure, not a DB constraint error.\n FieldDiffSchema.parse(input.changedFields);\n\n await this.db.insert(integrationRunItems).values({\n integrationRunId: input.integrationRunId,\n entityType: input.entityType,\n externalId: input.externalId,\n localId: input.localId ?? null,\n operation: input.operation,\n status: input.status,\n changedFields: input.changedFields,\n title: input.title ?? null,\n error: input.error ?? null,\n tenantId: input.tenantId ?? null,\n });\n }\n\n async listRecent(\n limit: number,\n subscriptionId?: string,\n tenantId?: string | null,\n ): Promise<IntegrationRunSummary[]> {\n assertTenantId(tenantId, {\n multiTenant: this.multiTenant,\n operation: 'listRecent',\n });\n\n // JOIN against integration_subscriptions to resolve `connection_id` per run.\n // `integration_runs.subscription_id` is a non-null FK so INNER JOIN is correct;\n // there should be no orphaned runs.\n const conditions: SQL[] = [];\n if (subscriptionId !== undefined) {\n conditions.push(eq(integrationRuns.subscriptionId, subscriptionId));\n }\n if (this.multiTenant) {\n conditions.push(eq(integrationRuns.tenantId, tenantId as string));\n }\n const where =\n conditions.length === 0\n ? undefined\n : conditions.length === 1\n ? conditions[0]\n : and(...conditions);\n\n const rows = await this.db\n .select({\n id: integrationRuns.id,\n subscriptionId: integrationRuns.subscriptionId,\n connectionId: integrationSubscriptions.connectionId,\n status: integrationRuns.status,\n startedAt: integrationRuns.startedAt,\n completedAt: integrationRuns.completedAt,\n recordsProcessed: integrationRuns.recordsProcessed,\n tenantId: integrationRuns.tenantId,\n })\n .from(integrationRuns)\n .innerJoin(\n integrationSubscriptions,\n eq(integrationRuns.subscriptionId, integrationSubscriptions.id),\n )\n .where(where)\n .orderBy(desc(integrationRuns.startedAt))\n .limit(limit);\n\n return rows.map((row) => ({\n id: row.id,\n subscriptionId: row.subscriptionId,\n connectionId: row.connectionId,\n status: row.status,\n startedAt: row.startedAt,\n completedAt: row.completedAt,\n recordsProcessed: row.recordsProcessed,\n tenantId: row.tenantId,\n }));\n }\n\n async completeRun(runId: string, input: CompleteRunInput): Promise<void> {\n await this.db\n .update(integrationRuns)\n .set({\n status: input.status,\n recordsFound: input.recordsFound,\n recordsProcessed: input.recordsProcessed,\n cursorAfter: input.cursorAfter ?? null,\n durationMs: input.durationMs,\n error: input.error ?? null,\n completedAt: new Date(),\n })\n .where(eq(integrationRuns.id, runId));\n }\n}\n","/**\n * IntegrationModule — `DynamicModule.forRoot({ backend, multiTenant? })` factory\n * wiring the integration subsystem's substrate (SYNC-6, ADR-008 subsystem pattern).\n *\n * ## What this module provides\n *\n * - `INTEGRATION_CURSOR_STORE` — Drizzle or Memory cursor store\n * - `INTEGRATION_RUN_RECORDER` — Drizzle or Memory run recorder\n * - `INTEGRATION_FIELD_DIFFER` — default `DeepEqualDiffer`\n * - `INTEGRATION_MULTI_TENANT` — resolved boolean flag (defaults to false)\n * - `INTEGRATION_MODULE_OPTIONS` — the options object itself, for backends\n * that need to inspect config at construction time\n *\n * ## What this module does NOT provide\n *\n * - `INTEGRATION_CHANGE_SOURCE` — per-provider per-entity; consumer binds in\n * their feature module (e.g. `OpportunityIntegrationModule` provides a\n * `SalesforceOpportunityChangeSource`). Loopback suppression — when\n * needed — is composed into the primitive's middleware chain via\n * `createLoopbackMiddleware(store)` (#226-5 / ADR-033); the\n * orchestrator no longer accepts a fingerprint store directly.\n * - `INTEGRATION_SINK` — per canonical entity; consumer binds in their feature\n * module.\n * - `ExecuteIntegrationUseCase` — registered by the feature module alongside\n * its source + sink bindings. Providing the orchestrator here would\n * force Nest to resolve INTEGRATION_CHANGE_SOURCE + INTEGRATION_SINK at module\n * compile time, which fails when the feature module hasn't been\n * imported yet. Consumers register `ExecuteIntegrationUseCase` in the same\n * `providers` array as their source + sink so resolution is local\n * to where all three are bound.\n *\n * Same shape as `EventsModule.forRoot` — the module wires the bus; you\n * bring your own handlers. Here: the module wires the substrate; you\n * bring your own source + sink.\n *\n * ## Usage\n *\n * ```ts\n * // AppModule — single source of truth for backend + multi-tenancy.\n * @Module({\n * imports: [IntegrationModule.forRoot({ backend: 'drizzle' })],\n * })\n * export class AppModule {}\n *\n * // Per-entity feature module — binds source + sink, gets the\n * // orchestrator for free.\n * @Module({\n * providers: [\n * { provide: INTEGRATION_CHANGE_SOURCE, useClass: SalesforceOpportunitySource },\n * { provide: INTEGRATION_SINK, useClass: OpportunityIntegrationSink },\n * ExecuteIntegrationUseCase,\n * ],\n * })\n * export class OpportunityIntegrationModule {\n * constructor(\n * private readonly execute: ExecuteIntegrationUseCase<CanonicalOpportunity>,\n * ) {}\n * }\n * ```\n *\n * `global: true` means feature modules do not need to re-import\n * `IntegrationModule` — the substrate tokens are available project-wide.\n */\nimport { Module, type DynamicModule, type Provider } from '@nestjs/common';\nimport {\n INTEGRATION_CURSOR_STORE,\n INTEGRATION_FIELD_DIFFER,\n INTEGRATION_MODULE_OPTIONS,\n INTEGRATION_MULTI_TENANT,\n INTEGRATION_RUN_RECORDER,\n} from './integration.tokens';\nimport { MemoryCursorStore } from './integration-cursor-store.memory-backend';\nimport { MemoryRunRecorder } from './integration-run-recorder.memory-backend';\nimport { PostgresCursorStore } from './integration-cursor-store.drizzle-backend';\nimport { DrizzleIntegrationRunRecorder } from './integration-run-recorder.drizzle-backend';\nimport { DeepEqualDiffer } from './deep-equal.differ';\n\nexport interface IntegrationModuleOptions {\n /**\n * Backend selection. `drizzle` wires the Postgres cursor store +\n * run-log recorder; `memory` wires in-memory doubles suitable for\n * tests + local dev.\n */\n backend: 'drizzle' | 'memory';\n\n /**\n * Multi-tenancy opt-in (SYNC-6).\n *\n * When `true`, every call to the orchestrator + both Drizzle backends\n * must supply a non-null `tenantId`; missing values throw\n * `MissingTenantIdError`. Defense-in-depth: the orchestrator rejects\n * at entry (no dangling `status=running` rows) AND the Drizzle\n * backends reject at their write boundary (belt-and-braces for any\n * path that bypasses the orchestrator). Both sites use the shared\n * `assertTenantId` helper so error messages match.\n *\n * Memory backends accept `tenantId` unconditionally — their state is\n * process-local; cross-tenant isolation there is not meaningful.\n *\n * Defaults to `false`.\n */\n multiTenant?: boolean;\n}\n\n@Module({})\nexport class IntegrationModule {\n static forRoot(options: IntegrationModuleOptions): DynamicModule {\n const multiTenant = options.multiTenant ?? false;\n\n const sharedProviders: Provider[] = [\n { provide: INTEGRATION_MODULE_OPTIONS, useValue: options },\n { provide: INTEGRATION_MULTI_TENANT, useValue: multiTenant },\n // Default differ — consumers can override by binding a different\n // `IFieldDiffer<T>` to `INTEGRATION_FIELD_DIFFER` in their feature module.\n { provide: INTEGRATION_FIELD_DIFFER, useValue: new DeepEqualDiffer() },\n ];\n\n const backendProviders: Provider[] =\n options.backend === 'memory'\n ? [\n // Wired as singletons via `useValue` so tests can pull\n // them out via `moduleRef.get(MemoryCursorStore)` for\n // direct assertions. Matches JOB-4 / MemoryJobStore shape.\n { provide: MemoryCursorStore, useValue: new MemoryCursorStore() },\n {\n provide: INTEGRATION_CURSOR_STORE,\n useExisting: MemoryCursorStore,\n },\n { provide: MemoryRunRecorder, useValue: new MemoryRunRecorder() },\n {\n provide: INTEGRATION_RUN_RECORDER,\n useExisting: MemoryRunRecorder,\n },\n ]\n : [\n // Drizzle backends — injected with DRIZZLE (provided by the\n // consumer's DrizzleModule) + the INTEGRATION_MULTI_TENANT flag\n // we bound above.\n { provide: INTEGRATION_CURSOR_STORE, useClass: PostgresCursorStore },\n { provide: INTEGRATION_RUN_RECORDER, useClass: DrizzleIntegrationRunRecorder },\n ];\n\n return {\n module: IntegrationModule,\n global: true,\n providers: [...sharedProviders, ...backendProviders],\n exports: [\n INTEGRATION_MODULE_OPTIONS,\n INTEGRATION_MULTI_TENANT,\n INTEGRATION_FIELD_DIFFER,\n INTEGRATION_CURSOR_STORE,\n INTEGRATION_RUN_RECORDER,\n ],\n };\n }\n}\n","/**\n * Auth subsystem — `IOAuthStateStore` port.\n *\n * CSRF protection for the OAuth2 authorize-code callback. Generic across\n * providers. The store mints opaque state tokens at /connect time and\n * single-use consumes them at /callback time, returning the original\n * record (userId + optional post-callback redirect path).\n *\n * Concrete backends live under `../backends/`:\n * - `state-store.memory-backend.ts` — in-process Map (tests/dev).\n * - `state-store.drizzle-backend.ts` — Postgres (prod).\n *\n * Semantics:\n * - `generate(record)` → returns an opaque state token; record is stored\n * under that token until consumed or until TTL expires.\n * - `consume(state)` → atomically deletes the entry and returns the\n * record. Throws on missing, expired, or replayed state. Never returns\n * null — a missing/expired state is a CSRF signal.\n */\nexport interface OAuthStateRecord {\n userId: string;\n /** Optional post-callback redirect path (relative URL). */\n redirect?: string;\n}\n\nexport interface IOAuthStateStore {\n /** Mint an opaque state token bound to `record`. Single-use. */\n generate(record: OAuthStateRecord): Promise<string>;\n /**\n * Atomically consume `state`, returning the bound record. Throws on\n * missing / expired / replayed state.\n */\n consume(state: string): Promise<OAuthStateRecord>;\n}\n\n/**\n * Thrown by `IOAuthStateStore.consume` when the state token is unknown,\n * expired, or has already been consumed (replay attempt).\n */\nexport class OAuthStateError extends Error {\n constructor(\n message: string,\n public readonly reason: 'missing' | 'expired',\n ) {\n super(message);\n this.name = 'OAuthStateError';\n }\n}\n","/**\n * Auth subsystem — injection tokens.\n *\n * Following ADR-008 guidance: `Symbol()` tokens for type safety and collision\n * avoidance. Consumers inject these via `@Inject(...)` against the matching\n * protocol interface.\n *\n * Usage:\n * ```typescript\n * constructor(\n * @Inject(ENCRYPTION_KEY) private readonly key: IEncryptionKey,\n * @Inject(OAUTH_STATE_STORE) private readonly states: IOAuthStateStore,\n * @Inject(AUTH_CONNECTION_READER) private readonly reader: IConnectionReader,\n * @Inject(AUTH_CONNECTION_TOKEN_WRITER) private readonly writer: IConnectionTokenWriter,\n * @Inject(AUTH_CONNECTION_GRANT_SINK) private readonly grants: IConnectionGrantSink,\n * @Inject(AUTH_USER_CONTEXT) private readonly userCtx: IUserContext,\n * @Inject(STRATEGY_REGISTRY) private readonly registry: ProviderStrategyRegistry,\n * ) {}\n * ```\n *\n * `IAuthStrategy` implementations are provider-specific and registered under\n * provider-specific tokens (e.g. `SALESFORCE_AUTH_STRATEGY`,\n * `HUBSPOT_AUTH_STRATEGY`) by each connection module — this subsystem does\n * not mandate a single `AUTH_STRATEGY` token because an app typically has\n * many concurrent strategies, one per provider. They are dispatched through\n * `STRATEGY_REGISTRY` (a `ReadonlyMap<slug, IProviderStrategy>`), populated\n * by per-provider modules via a `useFactory` provider.\n */\nimport { tokenKey } from '../token-key';\n\n// ADR-037: namespaced `Symbol.for(...)` keys so a token matches by VALUE across\n// import boundaries — the package copy and a (legacy) vendored copy resolve to\n// the SAME symbol, eliminating the dual-package DI-token identity hazard that\n// crashed boot once the emitter began emitting `STRATEGY_REGISTRY` as a runtime\n// value (RFC-0003 R5). Matches the convention surface packages already use.\nexport const ENCRYPTION_KEY = Symbol.for(tokenKey('auth', 'encryption-key'));\nexport const OAUTH_STATE_STORE = Symbol.for(tokenKey('auth', 'oauth-state-store'));\nexport const AUTH_CONNECTION_READER = Symbol.for(tokenKey('auth', 'connection-reader'));\nexport const AUTH_CONNECTION_TOKEN_WRITER = Symbol.for(tokenKey('auth', 'connection-token-writer'));\nexport const AUTH_CONNECTION_GRANT_SINK = Symbol.for(tokenKey('auth', 'connection-grant-sink'));\nexport const AUTH_USER_CONTEXT = Symbol.for(tokenKey('auth', 'user-context'));\nexport const STRATEGY_REGISTRY = Symbol.for(tokenKey('auth', 'strategy-registry'));\n/**\n * Holds the resolved `AuthModuleOptions` (used by `AuthController` to read\n * `redirectUriBase` for building per-provider callback URIs).\n */\nexport const AUTH_OPTIONS = Symbol.for(tokenKey('auth', 'options'));\n","/**\n * Thrown when an OAuth2 provider returns `400 invalid_grant`/`invalid_token`\n * on refresh — the refresh token itself is dead (user revoked, org\n * deactivated, token expired beyond the provider's rotation window). The\n * connection should be marked broken so background sync stops picking it\n * up; the user re-initiates OAuth.\n *\n * Shared across every OAuth2 strategy.\n */\nexport class ConnectionBrokenError extends Error {\n constructor(\n readonly connectionId: string,\n readonly errorCode: string,\n readonly errorDescription: string,\n ) {\n super(\n `Connection ${connectionId} broken: ${errorCode} - ${errorDescription}`,\n );\n this.name = 'ConnectionBrokenError';\n }\n}\n","/**\n * Abstract base class for OAuth2 refresh-token strategies.\n *\n * Template-method pattern: `resolve()` is concrete; four small hooks inject\n * provider specifics. Validated across two providers (Salesforce, HubSpot)\n * in the extraction-source app before being extracted here — see\n * `docs/gate-1-auth-extraction-findings.md` for the \"build first, extract\n * later\" evidence.\n *\n * Subclass contract:\n * - `provider` — slug matched against `connections.provider`\n * - `defaultExpiresInSec` — fallback when refresh response omits `expires_in`\n * - `tokenEndpoint()` — URL to POST the refresh grant\n * - `refreshBodyExtras()` — provider-specific body params\n * - `parseRefreshResponse()` — raw JSON → ParsedRefreshResponse\n * - `buildCredentials()` — stored or freshly-refreshed access token +\n * connection + optional raw refresh response\n * → provider credentials\n *\n * Base handles: expiry check w/ 5-min safety window, `forceRefresh` escape\n * hatch, POST form-urlencoded body, OAuth2 error mapping to\n * `ConnectionBrokenError`, refresh-token rotation persistence, fetch +\n * clock injection for tests.\n */\nimport type {\n AuthCredentials,\n AuthResolveOptions,\n IAuthStrategy,\n} from '../protocols/auth-strategy';\nimport type {\n DecryptedConnection,\n IConnectionReader,\n IConnectionTokenWriter,\n} from '../protocols/connection-store';\nimport { ConnectionBrokenError } from './connection-broken.error';\n\nexport type FetchLike = (\n input: string | URL | Request,\n init?: RequestInit,\n) => Promise<Response>;\n\n/** Safety window before expiry that triggers a refresh. */\nconst REFRESH_SAFETY_MS = 5 * 60 * 1000;\n\nexport interface OAuth2RefreshStrategyOptions {\n connectionReader: IConnectionReader;\n tokenWriter: IConnectionTokenWriter;\n /** Injectable fetch for tests. Defaults to the global `fetch`. */\n fetch?: FetchLike;\n /** Injectable clock for tests. Defaults to `Date.now`. */\n now?: () => number;\n}\n\nexport interface ParsedRefreshResponse {\n accessToken: string;\n /**\n * New refresh token if the provider rotated it (HubSpot: always, Salesforce:\n * sometimes). Omit when the provider reused the old refresh token.\n */\n refreshToken?: string;\n /** Seconds from now. If omitted, subclass `defaultExpiresInSec` applies. */\n expiresInSec?: number;\n}\n\nexport abstract class OAuth2RefreshStrategy implements IAuthStrategy {\n protected abstract readonly provider: string;\n protected abstract readonly defaultExpiresInSec: number;\n\n protected readonly connectionReader: IConnectionReader;\n protected readonly tokenWriter: IConnectionTokenWriter;\n protected readonly fetchImpl: FetchLike;\n protected readonly now: () => number;\n\n constructor(opts: OAuth2RefreshStrategyOptions) {\n this.connectionReader = opts.connectionReader;\n this.tokenWriter = opts.tokenWriter;\n this.fetchImpl = opts.fetch ?? fetch;\n this.now = opts.now ?? Date.now;\n }\n\n async resolve(\n connectionId: string,\n opts: AuthResolveOptions = {},\n ): Promise<AuthCredentials> {\n const connection =\n await this.connectionReader.findByIdDecrypted(connectionId);\n if (!connection) {\n throw new Error(`Connection ${connectionId} not found`);\n }\n if (connection.provider !== this.provider) {\n throw new Error(\n `${this.constructor.name} called for non-${this.provider} connection ${connectionId} (provider=${connection.provider})`,\n );\n }\n\n const needsRefresh =\n opts.forceRefresh ||\n this.isExpiring(connection.expiresAt) ||\n !connection.accessToken;\n\n if (!needsRefresh) {\n return this.buildCredentials(connection.accessToken, connection);\n }\n\n if (!connection.refreshToken) {\n throw new ConnectionBrokenError(\n connectionId,\n 'no_refresh_token',\n 'Connection has no refresh token; user must reconnect',\n );\n }\n\n const { parsed, raw } = await this.executeRefresh(\n connectionId,\n connection.refreshToken,\n );\n const newExpiresAt = new Date(\n this.now() + (parsed.expiresInSec ?? this.defaultExpiresInSec) * 1000,\n );\n await this.tokenWriter.persistRefresh({\n connectionId,\n accessToken: parsed.accessToken,\n refreshToken: parsed.refreshToken ?? undefined,\n expiresAt: newExpiresAt,\n });\n\n return this.buildCredentials(parsed.accessToken, connection, raw);\n }\n\n protected abstract tokenEndpoint(): string;\n protected abstract refreshBodyExtras(): Record<string, string>;\n protected abstract parseRefreshResponse(raw: unknown): ParsedRefreshResponse;\n protected abstract buildCredentials(\n accessToken: string,\n connection: DecryptedConnection,\n refreshRaw?: unknown,\n ): AuthCredentials;\n\n private async executeRefresh(\n connectionId: string,\n refreshToken: string,\n ): Promise<{ parsed: ParsedRefreshResponse; raw: unknown }> {\n const body = new URLSearchParams({\n grant_type: 'refresh_token',\n refresh_token: refreshToken,\n ...this.refreshBodyExtras(),\n });\n const response = await this.fetchImpl(this.tokenEndpoint(), {\n method: 'POST',\n headers: { 'Content-Type': 'application/x-www-form-urlencoded' },\n body: body.toString(),\n });\n if (!response.ok) {\n const err = (await safeJson(response)) as Partial<{\n error: string;\n error_description: string;\n message: string;\n }>;\n if (\n response.status === 400 &&\n (err.error === 'invalid_grant' || err.error === 'invalid_token')\n ) {\n throw new ConnectionBrokenError(\n connectionId,\n err.error ?? 'invalid_grant',\n err.error_description ?? err.message ?? 'refresh token rejected',\n );\n }\n throw new Error(\n `${this.provider} token refresh failed: ${response.status} ${err.error ?? ''} ${err.error_description ?? err.message ?? ''}`.trim(),\n );\n }\n const raw = await response.json();\n return { parsed: this.parseRefreshResponse(raw), raw };\n }\n\n private isExpiring(expiresAt: Date | null): boolean {\n if (!expiresAt) return true;\n return expiresAt.getTime() - this.now() < REFRESH_SAFETY_MS;\n }\n}\n\nasync function safeJson(response: Response): Promise<unknown> {\n try {\n return await response.clone().json();\n } catch {\n return {};\n }\n}\n","/**\n * Provider-agnostic marker for \"the access token was rejected; a forced\n * refresh may recover.\"\n *\n * Concrete provider error classes (e.g. SalesforceSessionExpiredError,\n * HubSpotUnauthorizedError) either extend `SessionExpiredError` directly or\n * set `isSessionExpired === true` on their instances. `withAuthRetry` uses\n * the `isSessionExpiredError` predicate to decide whether to force-refresh\n * and retry once.\n *\n * This discriminator replaces the SFDC-only `instanceof` check from the\n * extraction-source app's original `withAuthRetry`. See\n * `docs/gate-1-auth-extraction-findings.md` (recommendation 4).\n */\nexport class SessionExpiredError extends Error {\n /** Duck-type marker — works across package boundaries where `instanceof` fails. */\n readonly isSessionExpired = true as const;\n\n constructor(message = 'Access token rejected by provider') {\n super(message);\n this.name = 'SessionExpiredError';\n }\n}\n\n/**\n * Predicate used by `withAuthRetry` by default.\n *\n * Matches any error that either `instanceof SessionExpiredError` or carries\n * the `isSessionExpired === true` marker property. Provider adapters that\n * want their existing error classes to participate can simply add the\n * marker property without touching the class hierarchy.\n */\nexport function isSessionExpiredError(err: unknown): boolean {\n if (err instanceof SessionExpiredError) return true;\n if (err !== null && typeof err === 'object' && 'isSessionExpired' in err) {\n return (err as { isSessionExpired?: unknown }).isSessionExpired === true;\n }\n return false;\n}\n","/**\n * Run `op` with auth-aware retry-once on session-expired errors.\n *\n * Pattern: resolve creds → run op → if `isSessionExpired(e)` → resolve with\n * `forceRefresh: true` → retry → propagate. A second session-expired error\n * on the refreshed token propagates rather than looping, so transient\n * adapter bugs can't hang the caller.\n *\n * Generalisation over the extraction source's SFDC-specific original: the\n * session-expired classifier is injected. Providers mark their session-\n * expired errors (via `instanceof` of a marker class, or by setting a known\n * property) and pass a classifier matching that shape.\n *\n * Default classifier recognises the marker interface `SessionExpiredError`\n * shipped in `session-expired.error.ts` — concrete provider errors that\n * extend it (or set `isSessionExpired === true`) get retried without any\n * further wiring.\n */\nimport type {\n AuthCredentials,\n IAuthStrategy,\n} from '../protocols/auth-strategy';\nimport { isSessionExpiredError } from './session-expired.error';\n\nexport interface WithAuthRetryOptions {\n /**\n * Classifier that decides whether a thrown error is a session-expired\n * signal worth retrying once with a fresh token. Defaults to the marker-\n * interface check in `session-expired.error.ts`.\n */\n isSessionExpired?: (err: unknown) => boolean;\n}\n\nexport async function withAuthRetry<T>(\n authStrategy: IAuthStrategy,\n connectionId: string,\n op: (credentials: AuthCredentials) => Promise<T>,\n options: WithAuthRetryOptions = {},\n): Promise<T> {\n const classify = options.isSessionExpired ?? isSessionExpiredError;\n\n let creds = await authStrategy.resolve(connectionId);\n try {\n return await op(creds);\n } catch (e) {\n if (!classify(e)) throw e;\n creds = await authStrategy.resolve(connectionId, { forceRefresh: true });\n return op(creds);\n }\n}\n","/**\n * Drizzle schema for the `auth_oauth_state` table — backs the\n * `DrizzleOAuthStateStore` (`state-store.drizzle-backend.ts`).\n *\n * One row per outstanding /connect → /callback dance. Single-use; rows are\n * deleted on consume. A periodic sweep (or a `WHERE expires_at < now()`\n * filter on read) clears abandoned rows.\n *\n * Columns:\n * - `state` — opaque random token, primary key.\n * - `user_id` — text (matches the consumer-defined user-id shape;\n * the auth subsystem doesn't constrain this to UUID\n * because some apps key users by external id).\n * - `redirect` — optional post-callback redirect path.\n * - `expires_at` — TTL boundary; entries past this are treated as absent.\n *\n * Convention: schema files live at the root of the subsystem dir\n * (mirrors `cache.schema.ts`, `integration-audit.schema.ts`, `domain-events.schema.ts`).\n */\nimport { pgTable, text, timestamp } from 'drizzle-orm/pg-core';\nimport type { InferSelectModel } from 'drizzle-orm';\n\nexport const authOAuthState = pgTable('auth_oauth_state', {\n state: text('state').primaryKey(),\n userId: text('user_id').notNull(),\n redirect: text('redirect'),\n expiresAt: timestamp('expires_at', { withTimezone: true }).notNull(),\n});\n\nexport type AuthOAuthState = InferSelectModel<typeof authOAuthState>;\n","/**\n * Env-backed AES-256-GCM encryption.\n *\n * Framing: `base64( nonce(12B) || ciphertext || authTag(16B) )`. Random nonce\n * per call means two encryptions of the same plaintext produce different\n * ciphertexts — prevents replay-style inference. Auth tag enforces integrity;\n * any tampering throws on decrypt.\n *\n * Key source: `INTEGRATION_TOKEN_ENCRYPTION_KEY` env var, 32 bytes base64-encoded.\n * Generate via `openssl rand -base64 32`.\n *\n * Future backend: `kms.ts` (AWS/GCP KMS) for production deployments that\n * need key rotation + audit trails.\n */\nimport { createCipheriv, createDecipheriv, randomBytes } from 'node:crypto';\nimport type { IEncryptionKey } from '../../protocols/encryption-key';\n\nexport interface EnvEncryptionKeyOptions {\n /** Defaults to `process.env`. Tests inject a fixture. */\n env?: NodeJS.ProcessEnv;\n /** Defaults to `'INTEGRATION_TOKEN_ENCRYPTION_KEY'`. */\n envVar?: string;\n}\n\nconst ALGO = 'aes-256-gcm';\nconst NONCE_BYTES = 12;\nconst TAG_BYTES = 16;\nconst KEY_BYTES = 32;\n\nexport class EnvEncryptionKey implements IEncryptionKey {\n private readonly key: Buffer;\n\n constructor(opts: EnvEncryptionKeyOptions = {}) {\n const env = opts.env ?? process.env;\n const envVar = opts.envVar ?? 'INTEGRATION_TOKEN_ENCRYPTION_KEY';\n const raw = env[envVar];\n if (!raw) {\n throw new Error(\n `EnvEncryptionKey: ${envVar} is not set. Generate with: openssl rand -base64 32`,\n );\n }\n const decoded = Buffer.from(raw, 'base64');\n if (decoded.length !== KEY_BYTES) {\n throw new Error(\n `EnvEncryptionKey: ${envVar} must decode to ${KEY_BYTES} bytes (got ${decoded.length}). Use: openssl rand -base64 32`,\n );\n }\n this.key = decoded;\n }\n\n async encrypt(plaintext: string): Promise<string> {\n const nonce = randomBytes(NONCE_BYTES);\n const cipher = createCipheriv(ALGO, this.key, nonce);\n const ciphertext = Buffer.concat([\n cipher.update(plaintext, 'utf8'),\n cipher.final(),\n ]);\n const authTag = cipher.getAuthTag();\n return Buffer.concat([nonce, ciphertext, authTag]).toString('base64');\n }\n\n async decrypt(ciphertext: string): Promise<string> {\n const buf = Buffer.from(ciphertext, 'base64');\n if (buf.length < NONCE_BYTES + TAG_BYTES) {\n throw new Error('EnvEncryptionKey: ciphertext too short');\n }\n const nonce = buf.subarray(0, NONCE_BYTES);\n const authTag = buf.subarray(buf.length - TAG_BYTES);\n const body = buf.subarray(NONCE_BYTES, buf.length - TAG_BYTES);\n\n const decipher = createDecipheriv(ALGO, this.key, nonce);\n decipher.setAuthTag(authTag);\n const plain = Buffer.concat([decipher.update(body), decipher.final()]);\n return plain.toString('utf8');\n }\n}\n","/**\n * In-memory `IOAuthStateStore` backend.\n *\n * Single-process store — Map<state, { record, expiresAt }>. Suitable for\n * tests and single-worker dev. Production deployments select the drizzle\n * backend so state survives restarts and is shared across workers.\n *\n * Single-use semantics:\n * - `generate(record)` mints a 256-bit random token (base64url, opaque).\n * - `consume(state)` deletes the entry on read. A second call with the\n * same state throws `OAuthStateError('replay')`.\n * - Expired entries also throw (`'expired'`); the entry is deleted as a\n * side effect so a later replay still surfaces correctly.\n *\n * TTL defaults to 10 minutes — long enough for a user to complete the\n * provider's consent screen, short enough that abandoned states age out.\n */\nimport { randomBytes } from 'node:crypto';\nimport {\n type IOAuthStateStore,\n type OAuthStateRecord,\n OAuthStateError,\n} from '../protocols/oauth-state-store';\n\nexport interface MemoryOAuthStateStoreOptions {\n /** TTL in ms. Default 10 minutes. */\n ttlMs?: number;\n /** Injectable clock for tests. Default `Date.now`. */\n now?: () => number;\n /** Injectable token generator for tests. Default 32-byte base64url. */\n generateToken?: () => string;\n}\n\ninterface Slot {\n record: OAuthStateRecord;\n expiresAt: number;\n}\n\nexport class MemoryOAuthStateStore implements IOAuthStateStore {\n private readonly store = new Map<string, Slot>();\n private readonly ttlMs: number;\n private readonly now: () => number;\n private readonly generateToken: () => string;\n\n constructor(opts: MemoryOAuthStateStoreOptions = {}) {\n this.ttlMs = opts.ttlMs ?? 10 * 60 * 1000;\n this.now = opts.now ?? (() => Date.now());\n this.generateToken =\n opts.generateToken ?? (() => randomBytes(32).toString('base64url'));\n }\n\n async generate(record: OAuthStateRecord): Promise<string> {\n const state = this.generateToken();\n this.store.set(state, {\n record: { ...record },\n expiresAt: this.now() + this.ttlMs,\n });\n return state;\n }\n\n async consume(state: string): Promise<OAuthStateRecord> {\n const slot = this.store.get(state);\n if (!slot) {\n throw new OAuthStateError(\n `OAuth state token unknown or already consumed`,\n 'missing',\n );\n }\n // Delete first so a concurrent consume can't replay.\n this.store.delete(state);\n if (slot.expiresAt <= this.now()) {\n throw new OAuthStateError(`OAuth state token expired`, 'expired');\n }\n return slot.record;\n }\n}\n","/**\n * Drizzle-backed `IOAuthStateStore`.\n *\n * Uses the `auth_oauth_state` table (see `auth-oauth-state.schema.ts`).\n * Single-use semantics enforced via `DELETE ... RETURNING`: the consume\n * path atomically deletes and returns the row, so a concurrent /callback\n * with the same state cannot replay.\n *\n * Behaviour:\n * - `generate(record)` mints a 256-bit base64url token, INSERTs the row\n * with `expires_at = now() + ttlMs`.\n * - `consume(state)` runs `DELETE ... WHERE state = $1 RETURNING ...`\n * once. Throws `OAuthStateError('missing')` if no row was deleted\n * (unknown or already consumed) and `OAuthStateError('expired')` if\n * the deleted row was past its `expires_at`.\n */\nimport { randomBytes } from 'node:crypto';\nimport { eq } from 'drizzle-orm';\nimport type { DrizzleClient } from '../../../types/drizzle';\nimport { authOAuthState } from '../auth-oauth-state.schema';\nimport {\n type IOAuthStateStore,\n type OAuthStateRecord,\n OAuthStateError,\n} from '../protocols/oauth-state-store';\n\nexport interface DrizzleOAuthStateStoreOptions {\n /** TTL in ms. Default 10 minutes. */\n ttlMs?: number;\n /** Injectable clock for tests. Default `Date.now`. */\n now?: () => number;\n /** Injectable token generator for tests. Default 32-byte base64url. */\n generateToken?: () => string;\n}\n\nexport class DrizzleOAuthStateStore implements IOAuthStateStore {\n private readonly ttlMs: number;\n private readonly now: () => number;\n private readonly generateToken: () => string;\n\n constructor(\n private readonly db: DrizzleClient,\n opts: DrizzleOAuthStateStoreOptions = {},\n ) {\n this.ttlMs = opts.ttlMs ?? 10 * 60 * 1000;\n this.now = opts.now ?? (() => Date.now());\n this.generateToken =\n opts.generateToken ?? (() => randomBytes(32).toString('base64url'));\n }\n\n async generate(record: OAuthStateRecord): Promise<string> {\n const state = this.generateToken();\n const expiresAt = new Date(this.now() + this.ttlMs);\n await this.db.insert(authOAuthState).values({\n state,\n userId: record.userId,\n redirect: record.redirect ?? null,\n expiresAt,\n });\n return state;\n }\n\n async consume(state: string): Promise<OAuthStateRecord> {\n const rows = await this.db\n .delete(authOAuthState)\n .where(eq(authOAuthState.state, state))\n .returning();\n const row = rows[0];\n if (!row) {\n throw new OAuthStateError(\n `OAuth state token unknown or already consumed`,\n 'missing',\n );\n }\n if (row.expiresAt.getTime() <= this.now()) {\n throw new OAuthStateError(`OAuth state token expired`, 'expired');\n }\n return {\n userId: row.userId,\n redirect: row.redirect ?? undefined,\n };\n }\n}\n","/**\n * AuthController — provider-agnostic OAuth2 connect/callback dance.\n *\n * Mounts two routes:\n * - `GET /auth/:provider/connect?redirect=...` — generates state, builds\n * the provider's authorize-url, 302-redirects the browser there.\n * - `GET /auth/:provider/callback?code=...&state=...` — consumes state,\n * exchanges the code for tokens, hands them to the grant sink, then\n * 302-redirects to the post-connect path.\n *\n * Hexagonal seams:\n * - `STRATEGY_REGISTRY` (ReadonlyMap<slug, IProviderStrategy>) — dispatch.\n * Concrete per-provider strategies live consumer-side and contribute\n * entries via a `useFactory` in the consumer's app module.\n * - `AUTH_USER_CONTEXT` (IUserContext) — resolves \"who is this request\"\n * from the consumer's session/JWT/etc.\n * - `OAUTH_STATE_STORE` (IOAuthStateStore) — CSRF state minting/consume.\n * - `AUTH_CONNECTION_GRANT_SINK` (IConnectionGrantSink) — persists the\n * freshly-minted grant. Adapter lives consumer-side (e.g. the\n * auth-integrations starter from #285).\n *\n * The controller never imports `ConnectionsService` or any other concrete\n * consumer type — it goes through ports only.\n */\nimport {\n Controller,\n Get,\n Inject,\n Param,\n Query,\n Req,\n Res,\n HttpException,\n HttpStatus,\n} from '@nestjs/common';\nimport {\n AUTH_CONNECTION_GRANT_SINK,\n AUTH_OPTIONS,\n AUTH_USER_CONTEXT,\n OAUTH_STATE_STORE,\n STRATEGY_REGISTRY,\n} from '../auth.tokens';\nimport type { AuthModuleOptions } from '../auth.module';\nimport type { IOAuthStateStore } from '../protocols/oauth-state-store';\nimport type { IUserContext } from '../protocols/user-context';\nimport type {\n IProviderStrategy,\n ProviderStrategyRegistry,\n} from '../protocols/provider-strategy';\nimport type { IConnectionGrantSink } from '../protocols/connection-store';\n\n/**\n * Minimal response surface used by the controller — typed loosely so we\n * don't pull a hard dep on `express` or `fastify`. Both popular HTTP\n * adapters expose `redirect(status, url)`.\n */\ninterface RedirectingResponse {\n redirect(statusCode: number, url: string): unknown;\n}\n\n@Controller('auth')\nexport class AuthController {\n constructor(\n @Inject(STRATEGY_REGISTRY)\n private readonly registry: ProviderStrategyRegistry,\n @Inject(AUTH_USER_CONTEXT)\n private readonly userContext: IUserContext,\n @Inject(OAUTH_STATE_STORE)\n private readonly stateStore: IOAuthStateStore,\n @Inject(AUTH_CONNECTION_GRANT_SINK)\n private readonly grantSink: IConnectionGrantSink,\n @Inject(AUTH_OPTIONS)\n private readonly options: AuthModuleOptions,\n ) {}\n\n @Get(':provider/connect')\n async connect(\n @Param('provider') slug: string,\n @Query('redirect') redirect: string | undefined,\n @Req() req: unknown,\n @Res() res: RedirectingResponse,\n ): Promise<unknown> {\n const strategy = this.requireStrategy(slug);\n const userId = await this.userContext.getCurrentUserId(req);\n const state = await this.stateStore.generate({ userId, redirect });\n const url = strategy.buildAuthorizeUrl({\n state,\n redirectUri: this.redirectUriFor(slug),\n });\n return res.redirect(HttpStatus.FOUND, url);\n }\n\n @Get(':provider/callback')\n async callback(\n @Param('provider') slug: string,\n @Query('code') code: string | undefined,\n @Query('state') state: string | undefined,\n @Res() res: RedirectingResponse,\n ): Promise<unknown> {\n const strategy = this.requireStrategy(slug);\n if (!code) {\n throw new HttpException(\n `Missing 'code' query param`,\n HttpStatus.BAD_REQUEST,\n );\n }\n if (!state) {\n throw new HttpException(\n `Missing 'state' query param`,\n HttpStatus.BAD_REQUEST,\n );\n }\n const { userId, redirect } = await this.stateStore.consume(state);\n const tokens = await strategy.exchangeCodeForTokens({\n code,\n redirectUri: this.redirectUriFor(slug),\n });\n await this.grantSink.createOrUpdateFromOAuthGrant({\n userId,\n provider: slug,\n accessToken: tokens.accessToken,\n refreshToken: tokens.refreshToken,\n expiresAt: tokens.expiresAt,\n scope: tokens.scope,\n externalAccountId: tokens.externalAccountId,\n providerMetadata: tokens.providerMetadata,\n });\n return res.redirect(\n HttpStatus.FOUND,\n redirect ?? `/settings/connections?connected=${encodeURIComponent(slug)}`,\n );\n }\n\n private requireStrategy(slug: string): IProviderStrategy {\n const strategy = this.registry.get(slug);\n if (!strategy) {\n throw new HttpException(\n `Unknown provider '${slug}'`,\n HttpStatus.NOT_FOUND,\n );\n }\n return strategy;\n }\n\n private redirectUriFor(slug: string): string {\n const base = this.options.redirectUriBase;\n if (!base) {\n throw new Error(\n `AuthModule.forRoot: redirectUriBase is required when AuthController is enabled`,\n );\n }\n const trimmed = base.replace(/\\/+$/, '');\n return `${trimmed}/auth/${encodeURIComponent(slug)}/callback`;\n }\n}\n","/**\n * Ambient requester context — AsyncLocalStorage-backed tenant scope.\n *\n * The alternative to threading `userId`/`organizationId` through every\n * repository/service signature. Set ONCE at each boundary the generated app\n * owns, read implicitly inside `BaseRepository` (see `scopePredicate`).\n *\n * ## Where to set it (boundaries)\n *\n * - HTTP / tRPC handlers — from the authenticated `ctx.user`\n * - OAuth callback controllers — from the authenticated session\n * - Queue/worker `process()` — from the job's owning user after the\n * job's record is loaded\n *\n * Each boundary wraps the rest of the request in `withRequester({ userId,\n * organizationId }, () => ...)`. The context propagates through every `await`\n * to all downstream repo/service calls without being passed explicitly.\n *\n * ## Where to read it\n *\n * - `BaseRepository.scopePredicate()` reads it (via `tryGetRequester` in\n * lenient mode, `requireRequester` in strict mode) and filters every read\n * by the ambient scope when the repo declares `userTracking: true`.\n *\n * ## Why AsyncLocalStorage over an explicit parameter\n *\n * Threading `userId` (and later `organizationId`) through dozens of method\n * signatures is pure parameter pollution. Ambient context also lets a repo\n * make the \"I forgot to scope\" mistake impossible at runtime: in strict mode\n * `requireRequester()` throws when no context is active, surfacing a missing\n * boundary call loudly rather than silently leaking cross-tenant data.\n *\n * ## Not-found semantics\n *\n * When a row exists but belongs to a different requester, scoped reads return\n * `null`/`[]` — identical to \"truly doesn't exist\". No existence oracle;\n * callers throw NotFound uniformly. Standard security practice.\n *\n * ## Testing\n *\n * Tests that exercise scoped repos must wrap the call in `withRequester(...)`.\n * In strict mode an unwrapped call hitting `requireRequester()` throws — by\n * design. In lenient mode (the default) an unwrapped call is simply unscoped.\n */\nimport { AsyncLocalStorage } from 'node:async_hooks';\n\n/**\n * Data-visibility scope. The auth layer decides which scope a request is\n * allowed to claim; the repo trusts whatever the ambient context says.\n *\n * - `'user'`: filter every read by `user_id = ctx.userId`. Default.\n * - `'org'`: filter every read by membership in the requester's org, resolved\n * via `user_id IN (ctx.orgUserIds)` rather than via a per-entity\n * `organization_id` column. Works for every user-owned table and keeps repos\n * single-table — the org member list is pre-resolved at the boundary.\n * - `'superuser'`: no scope filter. Engineering / internal-tools only.\n *\n * AUTHORIZATION (who is allowed to claim each scope) lives in boundary\n * middleware, not in the repo. The repo trusts the ambient context — same\n * trust model as a threaded `userId`.\n */\nexport type RequesterScope = 'user' | 'org' | 'superuser';\n\nexport interface RequesterContext {\n /**\n * The user making the request. Always present — even in `'org'` and\n * `'superuser'` scopes it is the audit-trail \"who actually did this\".\n */\n readonly userId: string;\n /**\n * The organization the requester belongs to. Required when\n * `scope === 'org'`; may be null for `'user'` (users with no org) and for\n * `'superuser'` (cross-org reads).\n */\n readonly organizationId: string | null;\n /**\n * Data-visibility scope. Defaults to `'user'` when omitted.\n */\n readonly scope?: RequesterScope;\n /**\n * For `scope === 'org'`: the list of user IDs in the requester's org,\n * pre-resolved by the boundary middleware that established the `'org'`\n * scope (one `SELECT users.id WHERE organization_id = X` at the trust\n * boundary). Repos use this as a literal `IN (...)` filter — they never\n * JOIN to `users` themselves. Required when `scope === 'org'`.\n */\n readonly orgUserIds?: readonly string[];\n}\n\nconst als = new AsyncLocalStorage<RequesterContext>();\n\n/**\n * Set the ambient requester context for the duration of `fn`. The context\n * propagates through `await` boundaries to all downstream calls. Nesting is\n * fine — an inner `withRequester` overrides the outer for its callback.\n */\nexport function withRequester<T>(\n ctx: RequesterContext,\n fn: () => Promise<T>,\n): Promise<T> {\n return als.run(ctx, fn);\n}\n\n/**\n * Read the ambient requester context. Throws if no context is active — by\n * design. Used by repos in strict scope-enforcement mode; an unwrapped call\n * site is a missing boundary.\n */\nexport function requireRequester(): RequesterContext {\n const ctx = als.getStore();\n if (!ctx) {\n throw new Error(\n 'No requester context active. Wrap the entry point in ' +\n 'withRequester({ userId, organizationId }, fn). See tenant-context.ts.',\n );\n }\n return ctx;\n}\n\n/**\n * Read the ambient requester context without throwing. Returns `undefined`\n * when no context is active. Used by repos in lenient scope-enforcement mode\n * (the default) and by code paths that legitimately run outside a request.\n */\nexport function tryGetRequester(): RequesterContext | undefined {\n return als.getStore();\n}\n\n/**\n * Resolve the effective scope for the ambient context, defaulting to `'user'`.\n */\nexport function requireRequesterScope(): RequesterScope {\n return requireRequester().scope ?? 'user';\n}\n\n/**\n * Convenience helpers for setting scope explicitly. All three preserve\n * `userId` in the context (audit trail) regardless of scope.\n *\n * - `withUserScope`: regular end-user requests. Most call sites.\n * - `withOrgScope`: admin / org-shared resource access. The caller MUST verify\n * the requester's role permits `'org'` before calling — the helper does not\n * enforce authorization. `orgUserIds` is pre-resolved at the boundary.\n * - `withSuperuserScope`: engineering scripts / internal tools. `organizationId`\n * is null (cross-org is the point). Same authorization caveat applies.\n */\nexport function withUserScope<T>(\n userId: string,\n organizationId: string | null,\n fn: () => Promise<T>,\n): Promise<T> {\n return withRequester({ userId, organizationId, scope: 'user' }, fn);\n}\n\nexport function withOrgScope<T>(\n userId: string,\n organizationId: string,\n orgUserIds: readonly string[],\n fn: () => Promise<T>,\n): Promise<T> {\n return withRequester(\n { userId, organizationId, scope: 'org', orgUserIds },\n fn,\n );\n}\n\nexport function withSuperuserScope<T>(\n userId: string,\n fn: () => Promise<T>,\n): Promise<T> {\n return withRequester(\n { userId, organizationId: null, scope: 'superuser' },\n fn,\n );\n}\n","/**\n * AuthModule — DynamicModule factory for the auth subsystem.\n *\n * Wires the pluggable backends the subsystem ships with:\n * - `ENCRYPTION_KEY` → `EnvEncryptionKey` (AES-256-GCM from env)\n * - `OAUTH_STATE_STORE` → `MemoryOAuthStateStore` (dev/tests) or\n * `DrizzleOAuthStateStore` (prod, requires\n * DRIZZLE provider).\n * - `AUTH_OPTIONS` → resolved options bag (used by AuthController\n * for `redirectUriBase`).\n *\n * The connection-store ports (`AUTH_CONNECTION_READER`,\n * `AUTH_CONNECTION_TOKEN_WRITER`, `AUTH_CONNECTION_GRANT_SINK`),\n * `AUTH_USER_CONTEXT`, and `STRATEGY_REGISTRY` are deliberately **not**\n * wired here — they are always consumer-specific:\n * - connection-store ports adapt the consumer's `connections` storage;\n * - `IUserContext` adapts the app's session/JWT scheme;\n * - `STRATEGY_REGISTRY` is populated from the per-provider strategy\n * classes the consumer maintains.\n *\n * Consumers provide them in their app module (or by importing the\n * `auth-integrations` starter, which binds the three connection-store\n * ports off a single canonical entity).\n *\n * Usage in AppModule:\n * ```typescript\n * AuthModule.forRoot({\n * encryptionKey: 'env',\n * oauthStateStore: 'memory', // or 'drizzle'\n * enableController: true,\n * redirectUriBase: 'http://localhost:3000',\n * });\n * ```\n *\n * `global: true` means other modules don't need to re-import AuthModule to\n * inject the auth tokens.\n */\nimport { Module, type DynamicModule, type Provider } from '@nestjs/common';\nimport {\n AUTH_OPTIONS,\n ENCRYPTION_KEY,\n OAUTH_STATE_STORE,\n} from './auth.tokens';\nimport { EnvEncryptionKey } from './backends/encryption-key/env';\nimport { MemoryOAuthStateStore } from './backends/state-store.memory-backend';\nimport { DrizzleOAuthStateStore } from './backends/state-store.drizzle-backend';\nimport { AuthController } from './controllers/auth.controller';\nimport { DRIZZLE } from '../../constants/tokens';\nimport type { DrizzleClient } from '../../types/drizzle';\n\ntype EncryptionKeyChoice =\n | 'env'\n | Omit<Provider, 'provide'>;\n\ntype OAuthStateStoreChoice =\n | 'memory'\n | 'drizzle'\n | Omit<Provider, 'provide'>;\n\nexport interface AuthModuleOptions {\n /** `'env'` (default) or a full provider definition (e.g. `{ useClass: MyKmsEncryptionKey }`). */\n encryptionKey?: EncryptionKeyChoice;\n /**\n * `'memory'` (default — tests/dev) or `'drizzle'` (prod, requires DRIZZLE\n * provider) or a full provider definition for a custom impl.\n */\n oauthStateStore?: OAuthStateStoreChoice;\n /**\n * Mount `AuthController` (`/auth/:provider/connect` + `/callback`).\n * Default `false` — apps that hand-roll connect/callback (rare) or that\n * use the subsystem only for the refresh path can opt out.\n */\n enableController?: boolean;\n /**\n * Public base URL of the API server. Used to construct per-provider\n * callback URIs as `${redirectUriBase}/auth/:provider/callback`.\n * Required when `enableController: true`.\n */\n redirectUriBase?: string;\n}\n\nfunction resolveEncryptionKeyProvider(choice: EncryptionKeyChoice): Provider {\n if (choice === 'env') {\n return { provide: ENCRYPTION_KEY, useClass: EnvEncryptionKey };\n }\n return { provide: ENCRYPTION_KEY, ...choice } as Provider;\n}\n\nfunction resolveOAuthStateStoreProvider(\n choice: OAuthStateStoreChoice,\n): Provider {\n if (choice === 'memory') {\n return { provide: OAUTH_STATE_STORE, useClass: MemoryOAuthStateStore };\n }\n if (choice === 'drizzle') {\n return {\n provide: OAUTH_STATE_STORE,\n useFactory: (db: DrizzleClient | null) => {\n if (!db) {\n throw new Error(\n \"AuthModule.forRoot: oauthStateStore: 'drizzle' selected but DRIZZLE provider is not available. \" +\n 'Ensure DatabaseModule (or another provider exposing DRIZZLE) is imported before AuthModule.forRoot.',\n );\n }\n return new DrizzleOAuthStateStore(db);\n },\n inject: [{ token: DRIZZLE, optional: true }],\n };\n }\n return { provide: OAUTH_STATE_STORE, ...choice } as Provider;\n}\n\n@Module({})\nexport class AuthModule {\n static forRoot(options: AuthModuleOptions = {}): DynamicModule {\n const resolved: AuthModuleOptions = {\n encryptionKey: options.encryptionKey ?? 'env',\n oauthStateStore: options.oauthStateStore ?? 'memory',\n enableController: options.enableController ?? false,\n redirectUriBase: options.redirectUriBase,\n };\n\n if (resolved.enableController && !resolved.redirectUriBase) {\n throw new Error(\n 'AuthModule.forRoot: redirectUriBase is required when enableController: true',\n );\n }\n\n const encryptionKeyProvider = resolveEncryptionKeyProvider(\n resolved.encryptionKey!,\n );\n const oauthStateStoreProvider = resolveOAuthStateStoreProvider(\n resolved.oauthStateStore!,\n );\n const optionsProvider: Provider = {\n provide: AUTH_OPTIONS,\n useValue: resolved,\n };\n\n return {\n module: AuthModule,\n global: true,\n providers: [encryptionKeyProvider, oauthStateStoreProvider, optionsProvider],\n controllers: resolved.enableController ? [AuthController] : [],\n exports: [ENCRYPTION_KEY, OAUTH_STATE_STORE, AUTH_OPTIONS],\n };\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;AAGO,IAAM,MAAM;AAGZ,IAAM,WAAW,CAAC,MAAc,SAAyB,GAAG,GAAG,IAAI,IAAI,IA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;AAAA,EACF;AACF;AAlCa,aAAN;AAAA,EADNC,QAAO,CAAC,CAAC;AAAA,GACG;","names":["check","Injectable","Inject","sql","sql","Injectable","Inject","Inject","Injectable","Logger","Optional","toEventSummary","Logger","Injectable","Optional","Inject","pgTable","uuid","text","jsonb","timestamp","index","sql","HandlerRegistry","randomUUID","Inject","Injectable","Logger","and","desc","eq","inArray","sql","MissingTenantIdError","Logger","MissingTenantIdError","eq","dedupeKey","and","desc","inArray","randomUUID","sql","Injectable","Inject","Inject","Injectable","and","asc","desc","eq","gte","inArray","lt","or","sql","MissingTenantIdError","eq","inArray","asc","desc","and","sql","gte","or","lt","Injectable","Inject","Inject","Injectable","and","eq","and","eq","Injectable","Inject","jobs","Inject","Injectable","Logger","and","asc","desc","eq","inArray","lt","sql","Logger","and","eq","resolve","desc","asc","lt","inArray","sql","Injectable","Inject","randomUUID","Inject","Injectable","Logger","Optional","TERMINAL_STATUSES","DEDUPE_EXCLUDED_STATUSES","IN_FLIGHT_STATUSES","evaluateKeyTemplate","Logger","MissingTenantIdError","dedupeKey","randomUUID","classifyError","computeBackoff","serialiseError","Injectable","Inject","Optional","Inject","Injectable","NON_TERMINAL_STATUSES","MissingTenantIdError","Injectable","Inject","randomUUID","Injectable","randomUUID","Injectable","Module","Module","Inject","Injectable","Logger","Module","Optional","DEFAULT_SHUTDOWN_TIMEOUT_MS","Logger","Injectable","Inject","Optional","Module","Module","Injectable","Inject","Optional","gt","or","sql","eq","pgTable","text","jsonb","timestamp","sql","eq","or","gt","Injectable","Inject","Optional","Injectable","Inject","Optional","Injectable","Optional","Inject","Module","existsSync","readFileSync","resolve","resolve","existsSync","readFileSync","Module","Module","Module","Inject","Injectable","Optional","jobRuns","integrationRuns","Injectable","Optional","Inject","Inject","Injectable","Logger","Logger","Injectable","Inject","Module","z","z","MissingTenantIdError","pgEnum","pgTable","uuid","text","jsonb","integer","timestamp","index","uniqueIndex","Injectable","Injectable","Injectable","Injectable","Injectable","out","Injectable","Inject","Injectable","Logger","Optional","Logger","Injectable","Inject","Optional","Inject","Injectable","Optional","and","desc","eq","eq","desc","and","Injectable","Inject","Optional","Inject","Injectable","Optional","and","desc","eq","eq","and","desc","Injectable","Inject","Optional","Module","Module","pgTable","text","timestamp","randomBytes","randomBytes","randomBytes","eq","randomBytes","eq","Inject","Inject","Module","Module"]}
1
+ {"version":3,"sources":["../../../runtime/subsystems/token-key.ts","../../../runtime/subsystems/events/events.tokens.ts","../../../runtime/subsystems/events/generated/bus.ts","../../../runtime/subsystems/events/events-errors.ts","../../../runtime/subsystems/events/generated/schemas.ts","../../../runtime/subsystems/events/generated/registry.ts","../../../runtime/subsystems/events/events.module.ts","../../../runtime/constants/tokens.ts","../../../runtime/subsystems/events/event-bus.drizzle-backend.ts","../../../runtime/subsystems/events/event-keyset-cursor.ts","../../../runtime/subsystems/events/domain-events.schema.ts","../../../runtime/subsystems/bridge/bridge.tokens.ts","../../../runtime/subsystems/events/event-bus.memory-backend.ts","../../../runtime/subsystems/jobs/job-orchestration.schema.ts","../../../runtime/subsystems/jobs/jobs-domain.tokens.ts","../../../runtime/subsystems/jobs/job-handler.base.ts","../../../runtime/subsystems/jobs/job-orchestrator.drizzle-backend.ts","../../../runtime/subsystems/jobs/jobs-errors.ts","../../../runtime/subsystems/jobs/job-run-service.drizzle-backend.ts","../../../runtime/subsystems/jobs/job-run-keyset-cursor.ts","../../../runtime/subsystems/jobs/job-step-service.drizzle-backend.ts","../../../runtime/subsystems/jobs/pool-config.loader.ts","../../../runtime/subsystems/jobs/bullmq.config.ts","../../../runtime/subsystems/jobs/job-worker.ts","../../../runtime/subsystems/jobs/memory-job-store.ts","../../../runtime/subsystems/jobs/job-orchestrator.memory-backend.ts","../../../runtime/subsystems/jobs/job-step-service.memory-backend.ts","../../../runtime/subsystems/jobs/job-run-service.memory-backend.ts","../../../runtime/subsystems/jobs/jobs-domain.module.ts","../../../runtime/subsystems/jobs/job-worker.module.ts","../../../runtime/subsystems/cache/cache.tokens.ts","../../../runtime/subsystems/cache/cache.module.ts","../../../runtime/subsystems/cache/cache.drizzle-backend.ts","../../../runtime/subsystems/cache/cache.schema.ts","../../../runtime/subsystems/cache/cache.memory-backend.ts","../../../runtime/subsystems/storage/storage.local-backend.ts","../../../runtime/subsystems/storage/storage.utils.ts","../../../runtime/subsystems/storage/storage.memory-backend.ts","../../../runtime/subsystems/storage/storage.module.ts","../../../runtime/subsystems/storage/storage.tokens.ts","../../../runtime/subsystems/observability/observability.tokens.ts","../../../runtime/subsystems/observability/observability.module.ts","../../../runtime/subsystems/observability/observability.service.ts","../../../runtime/subsystems/integration/integration.tokens.ts","../../../runtime/subsystems/observability/reporters/bridge-metrics.reporter.ts","../../../runtime/subsystems/observability/observability-errors.ts","../../../runtime/subsystems/integration/integration-field-diff.protocol.ts","../../../runtime/subsystems/integration/entity-change-source-registry.protocol.ts","../../../runtime/subsystems/integration/entity-change-source-registry.memory.ts","../../../runtime/subsystems/integration/detection-config.schema.ts","../../../runtime/subsystems/integration/incremental-read.ts","../../../runtime/subsystems/integration/integration-errors.ts","../../../runtime/subsystems/integration/integration-audit.schema.ts","../../../runtime/subsystems/integration/integration-cursor-store.memory-backend.ts","../../../runtime/subsystems/integration/integration-run-recorder.memory-backend.ts","../../../runtime/subsystems/integration/deep-equal.differ.ts","../../../runtime/subsystems/integration/execute-integration.use-case.ts","../../../runtime/subsystems/integration/integration-cursor-store.drizzle-backend.ts","../../../runtime/subsystems/integration/integration-run-recorder.drizzle-backend.ts","../../../runtime/subsystems/integration/integration.module.ts","../../../runtime/subsystems/auth/protocols/oauth-state-store.ts","../../../runtime/subsystems/auth/auth.tokens.ts","../../../runtime/subsystems/auth/runtime/connection-broken.error.ts","../../../runtime/subsystems/auth/runtime/oauth2-refresh.strategy.ts","../../../runtime/subsystems/auth/runtime/session-expired.error.ts","../../../runtime/subsystems/auth/runtime/with-auth-retry.ts","../../../runtime/subsystems/auth/auth-oauth-state.schema.ts","../../../runtime/subsystems/auth/backends/encryption-key/env.ts","../../../runtime/subsystems/auth/backends/state-store.memory-backend.ts","../../../runtime/subsystems/auth/backends/state-store.drizzle-backend.ts","../../../runtime/subsystems/auth/controllers/auth.controller.ts","../../../runtime/base-classes/tenant-context.ts","../../../runtime/subsystems/auth/auth.module.ts"],"sourcesContent":["/** Canonical package namespace for cross-boundary DI token keys. MUST be a hardcoded\n * constant (NOT derived from package.json) so a vendored copy — which lives inside the\n * CONSUMER's package — produces the identical key and the two copies share the symbol. */\nexport const PKG = '@pattern-stack/codegen';\n// TODO(token-version): if/when a runtime contract version is adopted, inject it HERE only\n// (e.g. `${PKG}#${ABI}.${area}.${name}`) — this helper is the single chokepoint.\nexport const tokenKey = (area: string, name: string): string => `${PKG}.${area}.${name}`;\n","/**\n * Injection token for the event bus.\n *\n * String constant (not Symbol) so it matches by value across import boundaries.\n * Matches the token in runtime/constants/tokens.ts — both are 'EVENT_BUS'.\n *\n * Usage in use cases:\n * ```typescript\n * constructor(@Inject(EVENT_BUS) private readonly eventBus: IEventBus) {}\n * ```\n */\nimport { tokenKey } from '../token-key';\n\nexport const EVENT_BUS = 'EVENT_BUS' as const;\n\n/**\n * Injection token for the read-side `IEventReadPort` over `domain_events`\n * (OBS-LIST-1).\n *\n * Bound by `EventsModule.forRoot` to the same backend instance as\n * `EVENT_BUS` for the `drizzle` and `memory` backends (both implement\n * `IEventReadPort`). The `redis` backend retains no history and therefore\n * does NOT provide this token — consumers composing it (e.g. the\n * observability combiner) inject it `@Optional()` and degrade to empty\n * results.\n *\n * String constant (not Symbol) so it matches by value across import\n * boundaries — same convention as `EVENT_BUS`.\n */\nexport const EVENT_READ_PORT = 'EVENT_READ_PORT' as const;\n\n/**\n * Injection token for the generated `TypedEventBus` facade.\n *\n * `TypedEventBus` lives in `runtime/subsystems/events/generated/bus.ts` and\n * wraps `IEventBus` with project-specific `AppDomainEvent`-typed `publish<T>()`\n * and `subscribe<T>()`. Use cases inject this token in preference to\n * `EVENT_BUS` when they want compile-time type safety on event shapes.\n *\n * String constant (not Symbol) so it matches by value across import\n * boundaries — same convention as `EVENT_BUS`.\n *\n * Provider registration lands in EVT-6 (EventsModule wiring); the token is\n * declared here so generated code can import it without depending on the\n * still-being-formalised module.\n */\nexport const TYPED_EVENT_BUS = 'TYPED_EVENT_BUS' as const;\n\n/**\n * Injection token for the resolved multi-tenancy flag.\n *\n * Provided by `EventsModule.forRoot(...)` as `options.multiTenant ?? false`.\n * Consumed by `TypedEventBus` to enforce the tenantId-is-required rule at\n * publish time.\n *\n * String constant (not Symbol) so it matches by value across import\n * boundaries — same convention as the other events tokens. (The jobs\n * subsystem uses Symbols for the analogous token; events chose strings\n * from the start and we keep the file internally consistent.)\n */\nexport const EVENTS_MULTI_TENANT = 'EVENTS_MULTI_TENANT' as const;\n\n/**\n * Injection token for the Redis connection URL used by RedisEventBus.\n * Provided automatically by EventsModule.forRoot({ backend: 'redis' }).\n *\n * ADR-037: namespaced `Symbol.for(...)` (via `tokenKey()`) so it matches by value\n * across runtime copies (the sibling string tokens above are already value-stable).\n * Note the jobs subsystem defines its own `REDIS_URL`-equivalent; this is the\n * events one.\n */\nexport const REDIS_URL = Symbol.for(tokenKey('events', 'redis-url'));\n\n/**\n * Injection token for the resolved `EventsModuleOptions` object.\n *\n * Provided automatically by `EventsModule.forRoot(...)` /\n * `EventsModule.forRootAsync(...)`. Backends that need to observe module\n * configuration (e.g. `DrizzleEventBus` reading `opts.pools` for\n * pool-filtered drain) inject via this token.\n *\n * String-valued (not `Symbol`) so it matches by value across import\n * boundaries — same convention as `EVENT_BUS`.\n */\nexport const EVENTS_MODULE_OPTIONS = 'EVENTS_MODULE_OPTIONS' as const;\n","// AUTO-GENERATED by @pattern-stack/codegen. Do not edit.\n// Run `codegen entity new --all` to refresh.\n\nimport { Injectable, Inject } from '@nestjs/common';\nimport { randomUUID } from 'crypto';\nimport { EVENT_BUS, EVENTS_MULTI_TENANT } from '../events.tokens';\nimport { MissingTenantIdError } from '../events-errors';\nimport type { IEventBus, DrizzleTransaction } from '../event-bus.protocol';\nimport { eventPayloadSchemas } from './schemas';\nimport { getEventMetadata } from './registry';\nimport type { EventTypeName, EventOfType, PayloadOfType } from './types';\n\n/**\n * Typed facade over IEventBus.\n *\n * Stamps `pool`, `direction`, `tier`, and `version` into `event.metadata`\n * from the generated `eventRegistry` before delegating to\n * `IEventBus.publish()`. Downstream backends (DrizzleEventBus) read those\n * values to populate the explicit `domain_events` columns.\n *\n * Tier stamping (AUDIT-3): every event carries `metadata.tier`, sourced\n * from the registry. For `tier: 'audit'` events, the bus FORCES\n * `metadata.pool = null` and `metadata.direction = null` regardless of\n * any caller-supplied values in `opts.metadata` — audit routing is\n * bus-stamped, not caller-controlled. Caller overrides are silently\n * dropped with a debug-level log (callers should not be specifying these\n * for audit events; see ai-docs/specs/issue-242/plan.md §AUDIT-3).\n *\n * Validation gating (EVT-Q5): `CODEGEN_EVENT_VALIDATE` env flag, default on.\n * Uses `safeParse` + `console.warn` — never throws, so a bad publish does\n * not crash a hot path.\n *\n * Multi-tenancy (EVT-6): when the EventsModule is configured with\n * `multiTenant: true`, every publish must supply `opts.metadata.tenantId`\n * — otherwise `publish()` throws `MissingTenantIdError`. When `multiTenant`\n * is `false` (default), no tenantId is required. If a tenantId IS supplied,\n * it is preserved on `event.metadata` and the Drizzle backend writes it to\n * `domain_events.tenant_id` (EVT-4).\n */\n@Injectable()\nexport class TypedEventBus {\n\tconstructor(\n\t\t@Inject(EVENT_BUS) private readonly bus: IEventBus,\n\t\t@Inject(EVENTS_MULTI_TENANT) private readonly multiTenant: boolean,\n\t) {}\n\n\tasync publish<T extends EventTypeName>(\n\t\ttype: T,\n\t\taggregateId: string,\n\t\tpayload: PayloadOfType<T>,\n\t\topts?: { tx?: DrizzleTransaction; metadata?: Record<string, unknown> },\n\t): Promise<void> {\n\t\tconst meta = getEventMetadata(type);\n\n\t\tconst flag = process.env['CODEGEN_EVENT_VALIDATE'];\n\t\tconst shouldValidate =\n\t\t\tflag === undefined ? true : flag !== 'false' && flag !== '0';\n\t\tif (shouldValidate) {\n\t\t\t// `eventPayloadSchemas` is typed as `Record<EventTypeName, z.ZodType>`,\n\t\t\t// so under `noUncheckedIndexedAccess` the indexed lookup widens\n\t\t\t// to `z.ZodType | undefined`. When no events are registered at\n\t\t\t// codegen time `EventTypeName` degrades to `string` and the\n\t\t\t// schemas object is literally `{}` — the guard below is the\n\t\t\t// honest handling of that empty-registry case (skip validation;\n\t\t\t// it's a warn-only best-effort check per the class docblock).\n\t\t\tconst schema = eventPayloadSchemas[type];\n\t\t\tif (schema) {\n\t\t\t\tconst check = schema.safeParse(payload);\n\t\t\t\tif (!check.success) {\n\t\t\t\t\tconsole.warn(\n\t\t\t\t\t\t`[TypedEventBus] payload validation failed for ${String(type)}:`,\n\t\t\t\t\t\tcheck.error.issues,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tconst tenantId = opts?.metadata?.['tenantId'];\n\t\tif (this.multiTenant && (tenantId === undefined || tenantId === null)) {\n\t\t\tthrow new MissingTenantIdError(type as string);\n\t\t}\n\n\t\tconst aggregateType =\n\t\t\tmeta.aggregate ?? meta.source ?? meta.destination ?? (type as string);\n\n\t\t// AUDIT-3: build metadata with tier-aware routing stamping. For\n\t\t// `tier: 'audit'` events the bus FORCES pool/direction to null,\n\t\t// even if the caller supplied them in opts.metadata. Audit routing\n\t\t// is bus-stamped, not caller-controlled (see plan §AUDIT-3).\n\t\tconst baseMetadata: Record<string, unknown> = { ...(opts?.metadata ?? {}) };\n\t\tif (meta.tier === 'audit') {\n\t\t\tif (\n\t\t\t\tbaseMetadata['pool'] !== undefined ||\n\t\t\t\tbaseMetadata['direction'] !== undefined\n\t\t\t) {\n\t\t\t\tconsole.debug(\n\t\t\t\t\t`[TypedEventBus] tier:audit event '${String(type)}' had pool/direction in opts.metadata; overriding to null.`,\n\t\t\t\t);\n\t\t\t}\n\t\t\tbaseMetadata['pool'] = null;\n\t\t\tbaseMetadata['direction'] = null;\n\t\t\tbaseMetadata['tier'] = 'audit';\n\t\t} else {\n\t\t\tbaseMetadata['pool'] = meta.pool;\n\t\t\tbaseMetadata['direction'] = meta.direction;\n\t\t\tbaseMetadata['tier'] = 'domain';\n\t\t}\n\t\tbaseMetadata['version'] = meta.version;\n\n\t\tawait this.bus.publish(\n\t\t\t{\n\t\t\t\tid: randomUUID(),\n\t\t\t\ttype,\n\t\t\t\taggregateId,\n\t\t\t\taggregateType,\n\t\t\t\tpayload: payload as Record<string, unknown>,\n\t\t\t\toccurredAt: new Date(),\n\t\t\t\tmetadata: baseMetadata,\n\t\t\t},\n\t\t\topts?.tx,\n\t\t);\n\t}\n\n\tsubscribe<T extends EventTypeName>(\n\t\ttype: T,\n\t\thandler: (event: EventOfType<T>) => Promise<void>,\n\t): () => void {\n\t\treturn this.bus.subscribe<EventOfType<T>>(type, handler as never);\n\t}\n}\n","/**\n * Typed errors for the events subsystem (ADR-024, EVT-6).\n *\n * All thrown from the publish path of `TypedEventBus`. They exist as\n * classes so consumers can `instanceof` them in catch blocks and\n * exception filters can map them to HTTP codes.\n */\n\n/**\n * Thrown by `TypedEventBus.publish()` when the EventsModule is configured\n * with `multiTenant: true` and the caller did not supply\n * `opts.metadata.tenantId`. Multi-tenant mode requires every outbox row to\n * be attributable to a tenant — the `domain_events.tenant_id` column is\n * populated from this value and the drain loop uses it for future\n * tenant-scoped filtering (deferred — see ADR-024 §Multi-tenancy).\n *\n * Disable multi-tenancy at the module level (`multiTenant: false`, the\n * default) to opt out of the requirement entirely.\n */\nexport class MissingTenantIdError extends Error {\n override readonly name = 'MissingTenantIdError';\n constructor(public readonly eventType: string) {\n super(\n `Missing tenantId for event '${eventType}'. EventsModule is configured ` +\n `with multiTenant: true — every publish must include ` +\n `opts.metadata.tenantId. Either pass the tenantId or disable ` +\n `multi-tenancy on the module.`,\n );\n }\n}\n","// AUTO-GENERATED by @pattern-stack/codegen. Do not edit.\n// Run `codegen entity new --all` to refresh.\n\n\nimport { z } from 'zod';\nimport type { EventTypeName } from './types';\n\nexport const contactCreatedPayloadSchema = z.object({\n\taccountId: z.string().uuid().nullable(),\n\tcontactId: z.string().uuid(),\n\tcreatedBy: z.string().uuid(),\n}).strict();\n\nexport const contactMarkedChampionPayloadSchema = z.object({\n\tcontactId: z.string().uuid(),\n\topportunityId: z.string().uuid(),\n}).strict();\n\nexport const contactMergedPayloadSchema = z.object({\n\tmergedBy: z.string().uuid(),\n\tsourceId: z.string().uuid(),\n\ttargetId: z.string().uuid(),\n}).strict();\n\nexport const crmSyncStartedPayloadSchema = z.object({\n\trunId: z.string().uuid(),\n\tsource: z.string(),\n}).strict();\n\nexport const dealCreatedPayloadSchema = z.object({\n\taccountId: z.string().uuid(),\n\tdealId: z.string().uuid(),\n\townerId: z.string().uuid(),\n}).strict();\n\nexport const dealStageChangedPayloadSchema = z.object({\n\tdealId: z.string().uuid(),\n\tnewStage: z.string(),\n\toldStage: z.string(),\n}).strict();\n\nexport const stripePaymentReceivedPayloadSchema = z.object({\n\tamountCents: z.number(),\n\tcurrency: z.string(),\n\tcustomerId: z.string(),\n\teventId: z.string(),\n\treceivedAt: z.coerce.date(),\n}).strict();\n\nexport const webhookOutboundContactSyncPayloadSchema = z.object({\n\tcontactId: z.string().uuid(),\n\toccurredAt: z.coerce.date(),\n\toperation: z.string(),\n}).strict();\n\nexport const eventPayloadSchemas = {\n\t'contact_created': contactCreatedPayloadSchema,\n\t'contact_marked_champion': contactMarkedChampionPayloadSchema,\n\t'contact_merged': contactMergedPayloadSchema,\n\t'crm_sync_started': crmSyncStartedPayloadSchema,\n\t'deal_created': dealCreatedPayloadSchema,\n\t'deal_stage_changed': dealStageChangedPayloadSchema,\n\t'stripe_payment_received': stripePaymentReceivedPayloadSchema,\n\t'webhook_outbound_contact_sync': webhookOutboundContactSyncPayloadSchema,\n} as const satisfies Record<EventTypeName, z.ZodType>;\n","// AUTO-GENERATED by @pattern-stack/codegen. Do not edit.\n// Run `codegen entity new --all` to refresh.\n\n\nimport type { EventTypeName } from './types';\n\nexport interface EventMetadata {\n\ttype: EventTypeName;\n\ttier: 'domain' | 'audit';\n\tdirection: 'inbound' | 'change' | 'outbound' | null;\n\tpool: 'events_inbound' | 'events_change' | 'events_outbound' | null;\n\taggregate?: string;\n\tsource?: string;\n\tdestination?: string;\n\tversion: number;\n\tretry: { attempts: number; backoff: 'linear' | 'exponential' };\n}\n\nexport const eventRegistry = {\n\t'contact_created': {\n\t\ttype: 'contact_created',\n\t\ttier: 'domain',\n\t\tdirection: 'change',\n\t\tpool: 'events_change',\n\t\taggregate: 'contact',\n\t\tversion: 1,\n\t\tretry: { attempts: 3, backoff: 'exponential' },\n\t},\n\t'contact_marked_champion': {\n\t\ttype: 'contact_marked_champion',\n\t\ttier: 'domain',\n\t\tdirection: 'change',\n\t\tpool: 'events_change',\n\t\taggregate: 'contact',\n\t\tversion: 1,\n\t\tretry: { attempts: 3, backoff: 'exponential' },\n\t},\n\t'contact_merged': {\n\t\ttype: 'contact_merged',\n\t\ttier: 'domain',\n\t\tdirection: 'change',\n\t\tpool: 'events_change',\n\t\taggregate: 'contact',\n\t\tversion: 1,\n\t\tretry: { attempts: 3, backoff: 'exponential' },\n\t},\n\t'crm_sync_started': {\n\t\ttype: 'crm_sync_started',\n\t\ttier: 'audit',\n\t\tdirection: null,\n\t\tpool: null,\n\t\tversion: 1,\n\t\tretry: { attempts: 3, backoff: 'exponential' },\n\t},\n\t'deal_created': {\n\t\ttype: 'deal_created',\n\t\ttier: 'domain',\n\t\tdirection: 'change',\n\t\tpool: 'events_change',\n\t\taggregate: 'deal',\n\t\tversion: 1,\n\t\tretry: { attempts: 3, backoff: 'exponential' },\n\t},\n\t'deal_stage_changed': {\n\t\ttype: 'deal_stage_changed',\n\t\ttier: 'domain',\n\t\tdirection: 'change',\n\t\tpool: 'events_change',\n\t\taggregate: 'deal',\n\t\tversion: 1,\n\t\tretry: { attempts: 3, backoff: 'exponential' },\n\t},\n\t'stripe_payment_received': {\n\t\ttype: 'stripe_payment_received',\n\t\ttier: 'domain',\n\t\tdirection: 'inbound',\n\t\tpool: 'events_inbound',\n\t\tsource: 'stripe',\n\t\tversion: 1,\n\t\tretry: { attempts: 5, backoff: 'exponential' },\n\t},\n\t'webhook_outbound_contact_sync': {\n\t\ttype: 'webhook_outbound_contact_sync',\n\t\ttier: 'domain',\n\t\tdirection: 'outbound',\n\t\tpool: 'events_outbound',\n\t\taggregate: 'contact',\n\t\tdestination: 'crm',\n\t\tversion: 1,\n\t\tretry: { attempts: 3, backoff: 'exponential' },\n\t},\n} as const satisfies Record<EventTypeName, EventMetadata>;\n\nexport function getEventMetadata<T extends EventTypeName>(type: T): EventMetadata {\n\tconst meta = eventRegistry[type];\n\tif (!meta) {\n\t\tthrow new Error(`No registry entry for event type '${String(type)}' — declare events under events/*.yaml and re-run \\`codegen entity new --all\\`.`);\n\t}\n\treturn meta;\n}\n","/**\n * EventsModule — DynamicModule factory for the event bus subsystem.\n *\n * Register once in AppModule:\n * ```typescript\n * @Module({\n * imports: [\n * EventsModule.forRoot({ backend: 'drizzle' }),\n * ],\n * })\n * export class AppModule {}\n * ```\n *\n * Tests swap to the memory backend without touching application code:\n * ```typescript\n * Test.createTestingModule({\n * imports: [EventsModule.forRoot({ backend: 'memory' })],\n * });\n * ```\n *\n * Per-pool drain isolation (EVT-4):\n * ```typescript\n * EventsModule.forRoot({ backend: 'drizzle', pools: ['events_change'] });\n * ```\n * Each process restricts its drain loop to the pools listed here. `pools`\n * is undefined by default → drain all pending rows (backwards-compatible).\n *\n * Typed facade + multi-tenancy (EVT-6):\n * - `TYPED_EVENT_BUS` resolves to the generated `TypedEventBus` wrapping\n * whichever backend is selected.\n * - `multiTenant: true` makes `TypedEventBus.publish` throw\n * `MissingTenantIdError` when the caller forgets `metadata.tenantId`.\n *\n * `global: true` means entity modules do not need to import EventsModule\n * individually — the EVENT_BUS and TYPED_EVENT_BUS tokens are available\n * project-wide.\n *\n * Async configuration (`forRootAsync`):\n * The async factory returns `EventsModuleOptions`; the EVENT_BUS provider\n * then receives its backend dependencies — DRIZZLE for the drizzle\n * backend, REDIS_URL for the redis backend, the resolved options for the\n * memory backend — through a proper `useFactory` so Nest DI wires them\n * correctly. Earlier revisions hand-constructed backends with\n * `new Class()` which silently left `db` / `redisUrl` undefined\n * (issue #108).\n */\nimport { Module, type DynamicModule, type Provider } from '@nestjs/common';\nimport {\n EVENT_BUS,\n EVENT_READ_PORT,\n EVENTS_MODULE_OPTIONS,\n EVENTS_MULTI_TENANT,\n REDIS_URL,\n TYPED_EVENT_BUS,\n} from './events.tokens';\nimport { DRIZZLE } from '../../constants/tokens';\nimport type { DrizzleClient } from '../../types/drizzle';\nimport { DrizzleEventBus } from './event-bus.drizzle-backend';\nimport { MemoryEventBus } from './event-bus.memory-backend';\n// #6 — `RedisEventBus` is lazy-loaded only when `backend: 'redis'` is selected.\n// The file is filtered out of the vendor set for non-redis installs (see\n// `backendFileFilter` in src/cli/commands/subsystem.ts); the dynamic-string\n// import below makes TS treat the specifier as `any` so the consumer's tsc\n// never tries to resolve the absent file.\nimport { TypedEventBus } from './generated/bus';\n\n/**\n * Lazy-load the Redis backend. Routed through a non-literal specifier so\n * the consumer's `tsc` doesn't resolve `./event-bus.redis-backend` at type\n * check time — important because that file is filtered out of drizzle/\n * memory installs (#6).\n */\nasync function loadRedisEventBus(): Promise<new (url: string) => object> {\n // Non-literal specifier — TS gives this an `any` module type, sidestepping\n // resolution of a file that may not be vendored.\n const specifier = './event-bus.redis-backend';\n const mod = (await import(specifier)) as { RedisEventBus: new (url: string) => object };\n return mod.RedisEventBus;\n}\n\nexport interface EventsModuleOptions {\n backend: 'drizzle' | 'memory' | 'redis';\n /**\n * Redis connection URL used when `backend` is `'redis'`.\n * Falls back to the REDIS_URL environment variable, then\n * `redis://localhost:6379` if neither is set.\n */\n redisUrl?: string;\n /**\n * Restrict the drain loop to these pools. Each pool name matches the\n * `domain_events.pool` column (populated from `event.metadata.pool` at\n * publish time). Leave undefined to drain all pending rows.\n *\n * Typical lane split: one process per `events_inbound` /\n * `events_change` / `events_outbound` so a slow outbound handler\n * cannot stall change-event propagation (see ADR-022).\n */\n pools?: string[];\n /**\n * Multi-tenancy opt-in (EVT-6).\n *\n * When `true`, every `TypedEventBus.publish()` call must supply\n * `opts.metadata.tenantId` — otherwise it throws `MissingTenantIdError`.\n * The tenantId is preserved on `event.metadata` and, for the Drizzle\n * backend, written to `domain_events.tenant_id` (EVT-4).\n *\n * Drain-side tenant filtering is deferred — the tenant-context model\n * (per-process vs. per-request vs. async-local-storage) is still\n * unsettled; see ADR-024 §Multi-tenancy. Only the publish-side\n * requirement ships here.\n *\n * Defaults to `false`.\n */\n multiTenant?: boolean;\n}\n\nexport interface EventsModuleAsyncOptions {\n useFactory: (...args: unknown[]) => Promise<EventsModuleOptions> | EventsModuleOptions;\n inject?: unknown[];\n imports?: unknown[];\n}\n\n/**\n * Shared provider set: `TypedEventBus` itself, the `TYPED_EVENT_BUS` token\n * binding, and the resolved `EVENTS_MULTI_TENANT` flag. Returned from one\n * place so every `forRoot` branch and `forRootAsync` agree.\n */\nfunction buildTypedBusProviders(multiTenant: boolean): Provider[] {\n return [\n TypedEventBus,\n { provide: TYPED_EVENT_BUS, useExisting: TypedEventBus },\n { provide: EVENTS_MULTI_TENANT, useValue: multiTenant },\n ];\n}\n\n/**\n * Construct the backend instance for the async path, routing constructor\n * arguments through Nest-resolved dependencies.\n *\n * DRIZZLE is declared optional at inject time so that memory-backend\n * consumers aren't required to also import `DatabaseModule`. If the\n * drizzle backend is selected but no DRIZZLE provider is registered, we\n * throw a clear error instead of silently constructing a broken bus.\n */\nasync function buildEventBusAsync(\n options: EventsModuleOptions,\n db: DrizzleClient | null,\n redisUrl: string,\n): Promise<unknown> {\n if (options.backend === 'drizzle') {\n if (!db) {\n throw new Error(\n \"EventsModule.forRootAsync: backend: 'drizzle' selected but DRIZZLE provider is not available. \" +\n 'Ensure DatabaseModule (or another provider exposing DRIZZLE) is imported before EventsModule.forRootAsync.',\n );\n }\n return new DrizzleEventBus(db, options);\n }\n if (options.backend === 'redis') {\n // #6: lazy import — the redis backend ships only with `--backend redis`\n // installs; drizzle/memory consumers never touch the file.\n const RedisEventBus = await loadRedisEventBus();\n return new RedisEventBus(redisUrl);\n }\n return new MemoryEventBus(options);\n}\n\n@Module({})\nexport class EventsModule {\n static forRootAsync(asyncOptions: EventsModuleAsyncOptions): DynamicModule {\n return {\n module: EventsModule,\n global: true,\n imports: (asyncOptions.imports ?? []) as Parameters<typeof Module>[0]['imports'],\n providers: [\n {\n provide: EVENTS_MODULE_OPTIONS,\n useFactory: asyncOptions.useFactory,\n inject: (asyncOptions.inject ?? []) as (string | symbol | Function)[],\n },\n {\n provide: EVENTS_MULTI_TENANT,\n useFactory: (options: EventsModuleOptions) => options.multiTenant ?? false,\n inject: [EVENTS_MODULE_OPTIONS],\n },\n {\n provide: REDIS_URL,\n useFactory: (options: EventsModuleOptions) =>\n options.redisUrl ?? process.env['REDIS_URL'] ?? 'redis://localhost:6379',\n inject: [EVENTS_MODULE_OPTIONS],\n },\n {\n provide: EVENT_BUS,\n useFactory: (\n options: EventsModuleOptions,\n db: DrizzleClient | null,\n redisUrl: string,\n ) => buildEventBusAsync(options, db, redisUrl),\n inject: [\n EVENTS_MODULE_OPTIONS,\n { token: DRIZZLE, optional: true },\n REDIS_URL,\n ],\n },\n {\n // Read port (OBS-LIST-1). Drizzle + memory backends implement\n // IEventReadPort on the EVENT_BUS instance; the redis backend\n // retains no history, so EVENT_READ_PORT resolves to `null` and\n // optional consumers (the observability combiner) degrade to\n // empty results.\n provide: EVENT_READ_PORT,\n useFactory: (options: EventsModuleOptions, bus: unknown) =>\n options.backend === 'redis' ? null : bus,\n inject: [EVENTS_MODULE_OPTIONS, EVENT_BUS],\n },\n TypedEventBus,\n { provide: TYPED_EVENT_BUS, useExisting: TypedEventBus },\n ],\n exports: [EVENT_BUS, EVENT_READ_PORT, TYPED_EVENT_BUS, EVENTS_MULTI_TENANT],\n };\n }\n\n static forRoot(\n options: EventsModuleOptions = { backend: 'drizzle' },\n ): DynamicModule {\n const multiTenant = options.multiTenant ?? false;\n\n if (options.backend === 'redis') {\n const resolvedUrl =\n options.redisUrl ?? process.env['REDIS_URL'] ?? 'redis://localhost:6379';\n\n return {\n module: EventsModule,\n global: true,\n providers: [\n { provide: EVENTS_MODULE_OPTIONS, useValue: options },\n { provide: REDIS_URL, useValue: resolvedUrl },\n {\n // #6: useFactory + dynamic import so the consumer's tsc never\n // needs to resolve `event-bus.redis-backend.ts` for drizzle/\n // memory installs (the file is filtered out by\n // `backendFileFilter`). Nest awaits async factories + manages\n // lifecycle on the returned instance, so we drop the old bare\n // `RedisEventBus` provider entry.\n provide: EVENT_BUS,\n useFactory: async (url: string): Promise<object> => {\n const RedisEventBus = await loadRedisEventBus();\n return new RedisEventBus(url);\n },\n inject: [REDIS_URL],\n },\n ...buildTypedBusProviders(multiTenant),\n ],\n exports: [EVENT_BUS, TYPED_EVENT_BUS, EVENTS_MULTI_TENANT],\n };\n }\n\n const provider =\n options.backend === 'drizzle'\n ? { provide: EVENT_BUS, useClass: DrizzleEventBus }\n : { provide: EVENT_BUS, useClass: MemoryEventBus };\n\n return {\n module: EventsModule,\n global: true,\n providers: [\n { provide: EVENTS_MODULE_OPTIONS, useValue: options },\n provider,\n // Read port (OBS-LIST-1): drizzle + memory backends implement\n // IEventReadPort on the same instance as EVENT_BUS. The redis\n // backend retains no history and does not provide this token.\n { provide: EVENT_READ_PORT, useExisting: EVENT_BUS },\n ...buildTypedBusProviders(multiTenant),\n ],\n exports: [EVENT_BUS, EVENT_READ_PORT, TYPED_EVENT_BUS, EVENTS_MULTI_TENANT],\n };\n }\n}\n","/**\n * NestJS injection tokens\n *\n * Used with @Inject() decorator in concrete repository constructors.\n */\n\n/**\n * Injection token for the Drizzle ORM database client.\n *\n * Usage in concrete repositories:\n * ```typescript\n * constructor(@Inject(DRIZZLE) db: DrizzleClient) { super(db); }\n * ```\n */\nexport const DRIZZLE = 'DRIZZLE' as const;\n\n/**\n * Injection token for the event bus (IEventBus).\n *\n * Optional — only resolved when EventsModule.forRoot() is registered.\n * BaseService uses this with @Optional() to emit lifecycle events\n * without requiring the events subsystem to be installed.\n *\n * Usage in services/use cases:\n * ```typescript\n * @Optional() @Inject(EVENT_BUS) eventBus?: IEventBus\n * ```\n */\nexport const EVENT_BUS = 'EVENT_BUS' as const;\n","/**\n * DrizzleEventBus — Postgres-backed event bus using the transactional outbox pattern.\n *\n * Events are inserted into the `domain_events` table within the caller's\n * Drizzle transaction. A background polling loop (started on module init)\n * reads unprocessed events and dispatches them to registered subscribers.\n *\n * When the transaction rolls back, the event is never persisted — no\n * phantom events.\n *\n * Pool awareness (EVT-4):\n * - On `publish`/`publishMany` the backend writes `metadata.pool`,\n * `metadata.direction`, and `metadata.tenantId` into the first-class\n * `pool` / `direction` / `tenant_id` columns (metadata JSON is still\n * written unchanged for protocol stability).\n * - The drain loop filters by `opts.pools` when provided, so separate\n * processes (e.g. one per `events_inbound` / `events_change` /\n * `events_outbound`) can claim only their own lane. `pools: undefined`\n * drains all pending rows (backwards-compatible behaviour).\n *\n * EVT-Q7: No stale-event sweeper. `FOR UPDATE SKIP LOCKED` is\n * self-healing — the row is only locked for the duration of the\n * enclosing polling transaction; the `status='processed'` update happens\n * within that same transaction. There is no `claimed_at` semantic (unlike\n * jobs), so no stale rows can exist.\n *\n * This backend is suitable until you need real-time fan-out or very high\n * throughput. At that point, swap the backend for Redis Streams or similar\n * via EventsModule.forRoot({ backend: '...' }) without touching use cases.\n */\nimport { Injectable, OnModuleDestroy, OnModuleInit, Inject, Logger, Optional } from '@nestjs/common';\nimport { eq, and, inArray, asc, desc, gte, lt, or, sql, type SQL } from 'drizzle-orm';\nimport type { DomainEvent, DrizzleTransaction, IEventBus } from './event-bus.protocol';\nimport type {\n EventPage,\n IEventReadPort,\n ListEventsQuery,\n} from './event-read.protocol';\nimport {\n clampEventLimit,\n decodeEventCursor,\n encodeEventCursor,\n} from './event-keyset-cursor';\nimport type { DrizzleClient } from '../../types/drizzle';\nimport { domainEvents, type DomainEventRecord } from './domain-events.schema';\nimport { DRIZZLE } from '../../constants/tokens';\nimport { EVENTS_MODULE_OPTIONS } from './events.tokens';\nimport type { EventsModuleOptions } from './events.module';\nimport { BRIDGE_OUTBOX_DRAIN_HOOK } from '../bridge/bridge.tokens';\nimport type { IBridgeOutboxDrainHook } from '../bridge/bridge.protocol';\n\n/** How long to wait between polling cycles (ms). */\nconst POLL_INTERVAL_MS = 1_000;\n/** Max events claimed per polling cycle to bound memory usage. */\nconst POLL_BATCH_SIZE = 50;\n\n/**\n * Row shape built from `metadata` for writing into `domain_events`. Keeps\n * the per-event extraction logic in one place so publish/publishMany stay\n * in sync.\n */\nfunction toInsertValues(event: DomainEvent, multiTenant: boolean) {\n const metadata = event.metadata ?? undefined;\n const pool = (metadata?.['pool'] as string | undefined) ?? null;\n const direction = (metadata?.['direction'] as string | undefined) ?? null;\n // AUDIT-1: tier defaults to 'domain' when absent. The DB CHECK\n // constraint (`domain_events_tier_routing_check`) enforces the\n // tier ⇔ routing-fields invariant at the storage boundary; no\n // JS-side assertion is needed here.\n const tier = (metadata?.['tier'] as string | undefined) ?? 'domain';\n const base = {\n id: event.id,\n type: event.type,\n aggregateId: event.aggregateId,\n aggregateType: event.aggregateType,\n payload: event.payload,\n occurredAt: event.occurredAt,\n processedAt: null,\n status: 'pending' as const,\n metadata: event.metadata,\n pool,\n direction,\n tier,\n };\n // EVT-8: `tenant_id` is a scaffold-time conditional column, emitted only\n // when `events.multi_tenant: true`. Only write it when multi-tenancy is\n // on — under single-tenant scaffolds the column does not exist, so the\n // key must be omitted from the insert.\n if (!multiTenant) return base;\n const tenantId = (metadata?.['tenantId'] as string | undefined) ?? null;\n return { ...base, tenantId };\n}\n\n/**\n * Project a raw `domain_events` row into the narrow `EventSummary` shape.\n * Shared with the memory backend via this helper kept module-local to each\n * backend (the events subsystem has no cross-backend projection file yet;\n * the two are byte-identical and small).\n */\nfunction toEventSummary(r: DomainEventRecord) {\n const metadata = (r.metadata ?? undefined) as\n | Record<string, unknown>\n | undefined;\n const rootRunId = metadata?.['rootRunId'];\n return {\n id: r.id,\n type: r.type,\n aggregateId: r.aggregateId,\n aggregateType: r.aggregateType,\n status: r.status,\n pool: r.pool,\n direction: r.direction,\n tier: r.tier,\n rootRunId: typeof rootRunId === 'string' ? rootRunId : null,\n // EVT-8: `tenant_id` is a scaffold-time conditional column. Read it\n // structurally so this projection typechecks against both the\n // multi-tenant schema (column present) and the single-tenant schema\n // (column absent → undefined → null).\n tenantId: (r as { tenantId?: string | null }).tenantId ?? null,\n occurredAt:\n r.occurredAt instanceof Date\n ? r.occurredAt\n : new Date(r.occurredAt as unknown as string),\n processedAt:\n r.processedAt == null\n ? null\n : r.processedAt instanceof Date\n ? r.processedAt\n : new Date(r.processedAt as unknown as string),\n };\n}\n\n@Injectable()\nexport class DrizzleEventBus implements IEventBus, IEventReadPort, OnModuleInit, OnModuleDestroy {\n private readonly logger = new Logger(DrizzleEventBus.name);\n private polling = false;\n private pollTimer: ReturnType<typeof setTimeout> | null = null;\n private readonly handlers = new Map<string, Set<(event: DomainEvent) => Promise<void>>>();\n private readonly opts: EventsModuleOptions;\n\n constructor(\n @Inject(DRIZZLE) private readonly db: DrizzleClient,\n @Optional() @Inject(EVENTS_MODULE_OPTIONS) opts?: EventsModuleOptions,\n /**\n * Bridge subsystem hook (BRIDGE-4). Optional — when the bridge\n * subsystem is not installed in the consuming app, this token is\n * undefined and the drain skips the bridge block entirely (preserves\n * EVT-4 baseline behaviour).\n *\n * When provided, `processEvent` is invoked once per drained event\n * INSIDE the per-event tx, before `processed_at` is stamped. The\n * hook owns all knowledge of `bridge_delivery + wrapper job_run`\n * shapes; the events subsystem stays unaware of bridge schemas.\n */\n @Optional()\n @Inject(BRIDGE_OUTBOX_DRAIN_HOOK)\n private readonly bridgeHook: IBridgeOutboxDrainHook | null = null,\n ) {\n // Default so direct construction (e.g. integration tests not going\n // through Nest DI) keeps working without an explicit options object.\n this.opts = opts ?? { backend: 'drizzle' };\n }\n\n // ============================================================================\n // Lifecycle\n // ============================================================================\n\n async onModuleInit(): Promise<void> {\n this.polling = true;\n this.schedulePoll();\n }\n\n async onModuleDestroy(): Promise<void> {\n this.polling = false;\n if (this.pollTimer) {\n clearTimeout(this.pollTimer);\n this.pollTimer = null;\n }\n }\n\n // ============================================================================\n // IEventBus\n // ============================================================================\n\n async publish(event: DomainEvent, tx?: DrizzleTransaction): Promise<void> {\n const client = (tx ?? this.db) as DrizzleClient;\n const multiTenant = this.opts.multiTenant ?? false;\n await client.insert(domainEvents).values(toInsertValues(event, multiTenant));\n }\n\n async publishMany(events: DomainEvent[], tx?: DrizzleTransaction): Promise<void> {\n if (events.length === 0) return;\n const client = (tx ?? this.db) as DrizzleClient;\n const multiTenant = this.opts.multiTenant ?? false;\n await client\n .insert(domainEvents)\n .values(events.map((e) => toInsertValues(e, multiTenant)));\n }\n\n async findById(eventId: string): Promise<DomainEvent | null> {\n const rows = await this.db\n .select()\n .from(domainEvents)\n .where(eq(domainEvents.id, eventId))\n .limit(1);\n const row = rows[0];\n if (!row) return null;\n return {\n id: row.id,\n type: row.type,\n aggregateId: row.aggregateId,\n aggregateType: row.aggregateType,\n payload: row.payload as Record<string, unknown>,\n occurredAt:\n row.occurredAt instanceof Date\n ? row.occurredAt\n : new Date(row.occurredAt as unknown as string),\n metadata: (row.metadata ?? undefined) as\n | Record<string, unknown>\n | undefined,\n };\n }\n\n subscribe<T extends DomainEvent = DomainEvent>(\n eventType: string,\n handler: (event: T) => Promise<void>,\n ): () => void {\n if (!this.handlers.has(eventType)) {\n this.handlers.set(eventType, new Set());\n }\n const set = this.handlers.get(eventType)!;\n const h = handler as (event: DomainEvent) => Promise<void>;\n set.add(h);\n return () => {\n set.delete(h);\n };\n }\n\n // ============================================================================\n // IEventReadPort (OBS-LIST-1)\n // ============================================================================\n\n async listEvents(query: ListEventsQuery = {}): Promise<EventPage> {\n const limit = clampEventLimit(query.limit);\n const conditions: SQL<unknown>[] = [];\n\n if (query.poolId) conditions.push(eq(domainEvents.pool, query.poolId));\n if (query.direction)\n conditions.push(eq(domainEvents.direction, query.direction));\n if (query.since) conditions.push(gte(domainEvents.occurredAt, query.since));\n if (query.rootRunId) {\n // Filter on the JSON correlation id: metadata->>'rootRunId'.\n conditions.push(\n sql`${domainEvents.metadata}->>'rootRunId' = ${query.rootRunId}`,\n );\n }\n // EVT-8: `tenant_id` is a scaffold-time conditional column (emitted only\n // under `events.multi_tenant: true`). Guard the filter behind the same\n // `multiTenant` flag, and read the column structurally so this backend\n // typechecks against both the multi-tenant schema (column present) and\n // the single-tenant schema (column absent). When multi-tenancy is off\n // there is no `tenant_id` column to filter on.\n if (this.opts.multiTenant && query.tenantId !== undefined) {\n const tenantIdColumn = (\n domainEvents as unknown as { tenantId: typeof domainEvents.pool }\n ).tenantId;\n conditions.push(\n query.tenantId === null\n ? (sql`${tenantIdColumn} is null` as SQL<unknown>)\n : eq(tenantIdColumn, query.tenantId),\n );\n }\n\n // Keyset seek: WHERE (occurred_at, id) < (cursorOccurredAt, cursorId).\n if (query.cursor) {\n const keyset = decodeEventCursor(query.cursor);\n if (keyset) {\n conditions.push(\n or(\n lt(domainEvents.occurredAt, keyset.occurredAt),\n and(\n eq(domainEvents.occurredAt, keyset.occurredAt),\n lt(domainEvents.id, keyset.id),\n ),\n )!,\n );\n }\n }\n\n const rows = (await this.db\n .select()\n .from(domainEvents)\n .where(conditions.length > 0 ? and(...conditions) : undefined)\n .orderBy(desc(domainEvents.occurredAt), desc(domainEvents.id))\n .limit(limit + 1)) as DomainEventRecord[];\n\n const hasMore = rows.length > limit;\n const page = hasMore ? rows.slice(0, limit) : rows;\n const items = page.map(toEventSummary);\n const last = page[page.length - 1];\n const nextCursor =\n hasMore && last\n ? encodeEventCursor({ occurredAt: last.occurredAt, id: last.id })\n : null;\n\n return { items, nextCursor };\n }\n\n // ============================================================================\n // Polling\n // ============================================================================\n\n /**\n * Test-only hook. Runs exactly one drain cycle and returns. Production\n * code goes through `onModuleInit` → `schedulePoll`, which calls the\n * same `processBatch` under a timer.\n */\n async drainOnce(): Promise<void> {\n await this.processBatch();\n }\n\n private schedulePoll(): void {\n if (!this.polling) return;\n this.pollTimer = setTimeout(async () => {\n try {\n await this.processBatch();\n } catch (err) {\n this.logger.error(`Poll cycle error: ${err}`);\n } finally {\n this.schedulePoll();\n }\n }, POLL_INTERVAL_MS);\n }\n\n /**\n * Drain one batch (BRIDGE-4 restructure of EVT-4).\n *\n * Two-phase per drained event:\n *\n * 1. **Per-event transaction** — bridge fanout (`bridgeHook.processEvent`)\n * + `processed_at` stamp. Both write through the same `tx`. A throw\n * inside the tx (only infra-level failures should reach here, since\n * the hook tolerates null direction and registry misses inline)\n * rolls back the bridge inserts AND the `processed_at` stamp; the\n * event re-claims on the next drain cycle. Bridge `UNIQUE\n * (event_id, trigger_id)` makes the retry idempotent.\n *\n * 2. **After commit** — dispatch in-process subscribers (`IEventBus.subscribe`\n * handlers). This deliberately runs OUTSIDE the per-event tx (lead\n * decision 2026-04-22): subscribers are best-effort and must not\n * gate forward progress or roll back bridge fanout. Subscriber\n * errors are caught + logged; `processed_at` is already committed.\n * The old `MAX_RETRIES=3` in-process retry loop and the\n * `failed`-stamping path were removed in BRIDGE-4 along with their\n * coupling.\n *\n * The `processed_at` UPDATE carries `AND status='pending'` (BRIDGE-4\n * tightening — without it, a hypothetical double-claim could double-stamp\n * the timestamp). The per-event tx + `FOR UPDATE SKIP LOCKED` claim\n * make this defensive belt-and-suspenders.\n */\n private async processBatch(): Promise<void> {\n const pools = this.opts.pools;\n\n // Build WHERE: status='pending' [AND pool IN (...)]\n const whereClause: SQL<unknown> = pools && pools.length > 0\n ? (and(eq(domainEvents.status, 'pending'), inArray(domainEvents.pool, pools)) as SQL<unknown>)\n : eq(domainEvents.status, 'pending');\n\n // Claim a batch with FOR UPDATE SKIP LOCKED so multiple pollers don't\n // double-dispatch. The lock is released when the outer transaction\n // commits — which is fine because the immediately-following per-event\n // tx flips status='processed' under its own `AND status='pending'`\n // guard, so a re-claim of the same row in a subsequent batch is a\n // no-op UPDATE.\n const rows = await this.db.transaction(async (tx) => {\n return tx\n .select()\n .from(domainEvents)\n .where(whereClause)\n .orderBy(asc(domainEvents.occurredAt))\n .limit(POLL_BATCH_SIZE)\n .for('update', { skipLocked: true });\n }) as Array<typeof domainEvents.$inferSelect>;\n\n for (const row of rows) {\n const event: DomainEvent = {\n id: row.id,\n type: row.type,\n aggregateId: row.aggregateId,\n aggregateType: row.aggregateType,\n payload: row.payload as Record<string, unknown>,\n occurredAt: row.occurredAt instanceof Date ? row.occurredAt : new Date(row.occurredAt as unknown as string),\n metadata: (row.metadata ?? undefined) as Record<string, unknown> | undefined,\n };\n\n // Phase 1 — per-event tx: bridge fanout + processed_at stamp.\n try {\n await this.db.transaction(async (tx) => {\n if (this.bridgeHook) {\n await this.bridgeHook.processEvent(event, tx);\n }\n await tx\n .update(domainEvents)\n .set({ status: 'processed', processedAt: new Date() })\n .where(\n and(\n eq(domainEvents.id, event.id),\n eq(domainEvents.status, 'pending'),\n ),\n );\n });\n } catch (err) {\n // Infra-level failure inside the per-event tx — bridge inserts\n // and processed_at both rolled back. Log and move on; the next\n // drain cycle re-claims the row. UNIQUE on bridge_delivery makes\n // the retry idempotent.\n this.logger.error(\n `Per-event tx failed for event id=${event.id} type=${event.type}: ${err}`,\n );\n continue;\n }\n\n // Phase 2 — best-effort subscriber dispatch. Errors are logged\n // and discarded; processed_at is already committed. Subscribers\n // are observability + cache-busts + small ancillary work; they\n // must not gate forward progress.\n try {\n await this.dispatch(event);\n } catch (err) {\n this.logger.error(\n `Subscriber dispatch failed for event id=${event.id} type=${event.type} ` +\n `(processed_at already committed; failure does not retry): ${err}`,\n );\n }\n }\n }\n\n private async dispatch(event: DomainEvent): Promise<void> {\n const set = this.handlers.get(event.type);\n if (!set) return;\n\n let firstError: unknown;\n for (const handler of set) {\n try {\n await handler(event);\n } catch (err) {\n this.logger.error(\n `Handler error for event type \"${event.type}\" (id: ${event.id}): ${err}`,\n );\n if (firstError === undefined) {\n firstError = err;\n }\n }\n }\n\n if (firstError !== undefined) {\n throw firstError;\n }\n }\n}\n","/**\n * Keyset (seek) cursor codec for `IEventReadPort.listEvents` (OBS-LIST-1).\n *\n * The list is ordered `occurred_at DESC, id DESC`. The cursor encodes the\n * `(occurredAt, id)` of the last row on the previous page so the next page\n * seeks with `WHERE (occurred_at, id) < (cursorOccurredAt, cursorId)`.\n *\n * The cursor is opaque to consumers: a base64url-encoded JSON tuple. Shape\n * is an implementation detail — never parse it outside this module.\n *\n * Mirrors the jobs keyset codec; kept separate because the events subsystem\n * must not depend on `runtime/subsystems/jobs/`.\n */\n\nexport interface EventKeyset {\n occurredAt: Date;\n id: string;\n}\n\n/** Default page size when `limit` is omitted. */\nexport const DEFAULT_EVENT_LIST_LIMIT = 50;\n/** Hard upper bound on page size. */\nexport const MAX_EVENT_LIST_LIMIT = 200;\n\n/** Clamp a caller-supplied `limit` into `[1, MAX_EVENT_LIST_LIMIT]`. */\nexport function clampEventLimit(limit: number | undefined): number {\n if (typeof limit !== 'number' || !Number.isFinite(limit)) {\n return DEFAULT_EVENT_LIST_LIMIT;\n }\n const floored = Math.floor(limit);\n if (floored < 1) return 1;\n if (floored > MAX_EVENT_LIST_LIMIT) return MAX_EVENT_LIST_LIMIT;\n return floored;\n}\n\nexport function encodeEventCursor(keyset: EventKeyset): string {\n const tuple = [keyset.occurredAt.toISOString(), keyset.id];\n return Buffer.from(JSON.stringify(tuple), 'utf8').toString('base64url');\n}\n\n/**\n * Decode an opaque cursor back into its `(occurredAt, id)` keyset. Returns\n * `null` for malformed input so user-supplied garbage is treated as \"start\n * from the beginning\" rather than throwing.\n */\nexport function decodeEventCursor(cursor: string): EventKeyset | null {\n try {\n const json = Buffer.from(cursor, 'base64url').toString('utf8');\n const parsed = JSON.parse(json) as unknown;\n if (!Array.isArray(parsed) || parsed.length !== 2) return null;\n const [iso, id] = parsed;\n if (typeof iso !== 'string' || typeof id !== 'string') return null;\n const occurredAt = new Date(iso);\n if (Number.isNaN(occurredAt.getTime())) return null;\n return { occurredAt, id };\n } catch {\n return null;\n }\n}\n","/**\n * Drizzle schema for the domain_events outbox table.\n *\n * This table backs the DrizzleEventBus. Events are inserted within the\n * same database transaction as the domain write (outbox pattern). A\n * polling process reads unprocessed rows and dispatches to subscribers.\n *\n * First-class routing columns (EVT-1):\n * - `pool` — populated by DrizzleEventBus.publish() (EVT-4); enables\n * pool-filtered drain queries without unpacking metadata JSON.\n * NULL when `tier='audit'` (audit events are not routed).\n * - `direction` — `inbound` | `change` | `outbound`; mirrors the routing\n * dimension used by jobs' reserved `events_inbound` /\n * `events_change` / `events_outbound` pools.\n * NULL when `tier='audit'`.\n * - `tenant_id` — conditional: emitted only when `events.multi_tenant: true`\n * in `codegen.config.yaml`. The runtime source declares it\n * unconditionally; EVT-8's scaffold template handles the\n * config-driven include/exclude.\n *\n * Audit-tier column (AUDIT-1):\n * - `tier` — `'domain'` | `'audit'`. Defaults to `'domain'`. Audit-tier\n * rows are observability-only (subscribers may observe but\n * the bridge MUST NOT spawn jobs from them); they have null\n * `pool` and `direction` by construction. The CHECK\n * constraint `domain_events_tier_routing_check` enforces\n * `tier='audit' ⇔ (pool IS NULL AND direction IS NULL)`.\n *\n * The `metadata` JSON column continues to carry these values for protocol\n * stability; the first-class columns are an optimization for drain filtering.\n *\n * Indexes (declared below in the index callback):\n * - (status, occurred_at) — polling drain filter\n * - (aggregate_id, aggregate_type) — event replay per aggregate\n * - (pool, status, occurred_at) — per-pool drain filter (EVT-1)\n * - (tier, status, occurred_at) — per-tier filter for the observability\n * viewer's tier toggle (AUDIT-1).\n */\nimport {\n check,\n index,\n jsonb,\n pgTable,\n text,\n timestamp,\n uuid,\n} from 'drizzle-orm/pg-core';\nimport { sql } from 'drizzle-orm';\nimport type { InferSelectModel } from 'drizzle-orm';\n\nexport const domainEvents = pgTable(\n 'domain_events',\n {\n id: uuid('id').primaryKey(),\n type: text('type').notNull(),\n aggregateId: text('aggregate_id').notNull(),\n aggregateType: text('aggregate_type').notNull(),\n payload: jsonb('payload').notNull().$type<Record<string, unknown>>(),\n occurredAt: timestamp('occurred_at', { withTimezone: true }).notNull(),\n processedAt: timestamp('processed_at', { withTimezone: true }),\n /** Lifecycle status: pending | processed | failed */\n status: text('status').notNull().default('pending'),\n /** Error message from the last failed dispatch attempt. */\n error: text('error'),\n metadata: jsonb('metadata').$type<Record<string, unknown>>(),\n /** Routing pool (e.g. `events_inbound`, `events_change`, `events_outbound`). Populated by DrizzleEventBus.publish() in EVT-4. NULL when `tier='audit'`. */\n pool: text('pool'),\n /** Routing direction: `inbound` | `change` | `outbound`. Populated by DrizzleEventBus.publish() in EVT-4. NULL when `tier='audit'`. */\n direction: text('direction'),\n /**\n * Event tier: `'domain'` (default) or `'audit'`. Audit-tier rows are\n * observability-only and have null `pool`/`direction` by construction —\n * enforced by the `domain_events_tier_routing_check` CHECK constraint\n * declared below. (AUDIT-1)\n */\n tier: text('tier').notNull().default('domain'),\n // conditional: emitted only when events.multi_tenant: true\n tenantId: text('tenant_id'),\n },\n (t) => ({\n /** Polling drain filter (existing — promoted from comment to declaration in EVT-1). */\n idxDomainEventsStatusOccurredAt: index('idx_domain_events_status_occurred_at').on(\n t.status,\n t.occurredAt,\n ),\n /** Event replay per aggregate (existing — promoted from comment to declaration in EVT-1). */\n idxDomainEventsAggregate: index('idx_domain_events_aggregate').on(\n t.aggregateId,\n t.aggregateType,\n ),\n /** Per-pool drain filter (EVT-1). Enables DrizzleEventBus to drain a single pool without scanning all events. */\n idxDomainEventsPoolStatusOccurredAt: index(\n 'idx_domain_events_pool_status_occurred_at',\n ).on(t.pool, t.status, t.occurredAt),\n /** Per-tier filter (AUDIT-1). Backs the observability viewer's tier toggle. */\n idxDomainEventsTierStatusOccurredAt: index(\n 'idx_domain_events_tier_status_occurred_at',\n ).on(t.tier, t.status, t.occurredAt),\n /**\n * Tier ↔ routing-fields invariant (AUDIT-1):\n * - `tier` is one of `'domain' | 'audit'`.\n * - `tier='audit'` ⇔ `pool IS NULL AND direction IS NULL`.\n * - `tier='domain'` ⇒ `pool` and `direction` are populated (the\n * DrizzleEventBus inserts always supply them; the bus stamps them\n * in AUDIT-3).\n */\n tierRoutingCheck: check(\n 'domain_events_tier_routing_check',\n sql`${t.tier} in ('domain','audit') AND ((${t.tier} = 'audit') = (${t.pool} is null and ${t.direction} is null))`,\n ),\n }),\n);\n\nexport type DomainEventRecord = InferSelectModel<typeof domainEvents>;\n","/**\n * Injection tokens for the bridge subsystem (ADR-023 Phase 2, BRIDGE-2).\n *\n * String constants (not Symbols) so they match by value across import\n * boundaries — same convention as `EVENT_BUS` / `EVENTS_MULTI_TENANT` in the\n * events subsystem (per EVT-6 §Implementation Notes). The jobs subsystem\n * uses Symbols for its analogous tokens; we keep the bridge file internally\n * consistent with the events convention because the bridge is conceptually\n * downstream of (and imports from) the events module.\n */\n\n/**\n * Token for the `IJobBridge` repo backend (memory in BRIDGE-3, Drizzle in\n * BRIDGE-4). Consumed by `BridgeDeliveryHandler` (BRIDGE-5), the outbox\n * drain (BRIDGE-4 modification), and `EventFlowService` (BRIDGE-7).\n */\nexport const BRIDGE_DELIVERY_REPO = 'BRIDGE_DELIVERY_REPO' as const;\n\n/**\n * Token for the `IEventFlow` facade implementation (BRIDGE-7). Use cases\n * inject this in preference to `EVENT_BUS` / `TYPED_EVENT_BUS` — calling\n * `eventFlow.publish(...)` / `eventFlow.publishAndStart(...)` is the\n * sanctioned authoring surface (ADR-023 §Decision 7).\n */\nexport const EVENT_FLOW = 'EVENT_FLOW' as const;\n\n/**\n * Token for the resolved multi-tenancy flag, provided by\n * `BridgeModule.forRoot({ multiTenant })` in BRIDGE-8. Consumed by\n * `EventFlowService.publishAndStart` (entry), `BridgeDeliveryHandler.handle`\n * (entry), and `DrizzleBridgeDeliveryRepo.insertDelivery` (pre-write) — the\n * three enforcement sites called out in ADR-023 §Multi-tenancy.\n */\nexport const BRIDGE_MULTI_TENANT = 'BRIDGE_MULTI_TENANT' as const;\n\n/**\n * Token for the resolved `BridgeModuleOptions` object. Provided by\n * `BridgeModule.forRoot(...)` / `forRootAsync(...)` in BRIDGE-8.\n * Mirrors `EVENTS_MODULE_OPTIONS` and `JOBS_DOMAIN_OPTIONS` shape — backends\n * inject this when they need to observe additional module configuration\n * (e.g. pool overrides) without each adding a dedicated token.\n */\nexport const BRIDGE_MODULE_OPTIONS = 'BRIDGE_MODULE_OPTIONS' as const;\n\n/**\n * Token for the codegen-emitted `bridgeRegistry` — the\n * `Record<EventTypeName, BridgeTriggerEntry[]>` map that drives\n * outbox-drain trigger lookup (BRIDGE-4) and `EventFlowService` Case B\n * dedup (BRIDGE-7). Provider registration lands in BRIDGE-8; the token is\n * declared here so generated code (BRIDGE-6) can import it without\n * depending on the still-being-formalised module.\n */\nexport const BRIDGE_REGISTRY = 'BRIDGE_REGISTRY' as const;\n\n\n/**\n * Token for the `IBridgeOutboxDrainHook` implementation (BRIDGE-4).\n * Injected `@Optional()` into `DrizzleEventBus` — when the bridge\n * subsystem is not installed the token is undefined and the events\n * outbox drain skips the bridge block entirely (preserves EVT-4\n * baseline behaviour).\n *\n * Resolution order: `BridgeModule.forRoot()` provides this token in\n * BRIDGE-8 alongside the rest of the bridge subsystem. `EventsModule`\n * itself never provides it; the events subsystem stays unaware of the\n * bridge unless the consumer wires it.\n */\nexport const BRIDGE_OUTBOX_DRAIN_HOOK = 'BRIDGE_OUTBOX_DRAIN_HOOK' as const;\n","/**\n * MemoryEventBus — in-memory backend for the event bus.\n *\n * Dispatches events synchronously to registered subscribers. The `tx`\n * parameter is ignored — all events are dispatched immediately.\n *\n * Use this backend in tests to assert event publication without a database.\n * Swap via EventsModule.forRoot({ backend: 'memory' }).\n *\n * Pool awareness (EVT-5):\n * - Mirrors the `DrizzleEventBus` per-process restriction (EVT-4). When\n * `opts.pools` is set, `publish`/`publishMany` still push the event into\n * `publishedEvents` (so test code can assert the full set of emitted\n * events regardless of pool filter), but handlers are NOT invoked for\n * events whose `metadata.pool` is outside the configured pools.\n * - `publishedEventsForPool(pool)` and `publishedEventsForDirection(dir)`\n * helpers are provided for targeted assertions.\n * - Shares the `EventsModuleOptions` shape (same token as Drizzle) rather\n * than introducing a memory-only options type — the surface is the same\n * and keeping them unified avoids drift between backends.\n */\nimport { Inject, Injectable, Logger, Optional } from '@nestjs/common';\nimport type { DomainEvent, IEventBus } from './event-bus.protocol';\nimport type {\n EventPage,\n EventSummary,\n IEventReadPort,\n ListEventsQuery,\n} from './event-read.protocol';\nimport {\n clampEventLimit,\n decodeEventCursor,\n encodeEventCursor,\n} from './event-keyset-cursor';\nimport { EVENTS_MODULE_OPTIONS } from './events.tokens';\nimport type { EventsModuleOptions } from './events.module';\n\n/**\n * Project an in-memory `DomainEvent` into the narrow `EventSummary` shape.\n * The memory backend has no first-class columns, so `pool` / `direction` /\n * `tier` / `tenantId` / `rootRunId` are read from `metadata` (mirroring how\n * the Drizzle backend stamps them onto columns at publish time). `status`\n * is reported as `'processed'` — the memory bus dispatches synchronously,\n * so once an event is in `publishedEvents` it has been handled.\n */\nfunction toEventSummary(event: DomainEvent): EventSummary {\n const metadata = event.metadata;\n const str = (key: string): string | null => {\n const v = metadata?.[key];\n return typeof v === 'string' ? v : null;\n };\n return {\n id: event.id,\n type: event.type,\n aggregateId: event.aggregateId,\n aggregateType: event.aggregateType,\n status: 'processed',\n pool: str('pool'),\n direction: str('direction'),\n tier: str('tier') ?? 'domain',\n rootRunId: str('rootRunId'),\n tenantId: str('tenantId'),\n occurredAt: event.occurredAt,\n processedAt: event.occurredAt,\n };\n}\n\n@Injectable()\nexport class MemoryEventBus implements IEventBus, IEventReadPort {\n private readonly logger = new Logger(MemoryEventBus.name);\n\n /** All events published since construction (or last clear). */\n readonly publishedEvents: DomainEvent[] = [];\n\n private readonly handlers = new Map<string, Set<(event: DomainEvent) => Promise<void>>>();\n private readonly opts: EventsModuleOptions;\n\n constructor(\n @Optional() @Inject(EVENTS_MODULE_OPTIONS) opts?: EventsModuleOptions,\n ) {\n // Default so direct construction (e.g. `new MemoryEventBus()` from a\n // unit test outside NestJS DI) keeps working without an explicit\n // options object.\n this.opts = opts ?? { backend: 'memory' };\n }\n\n async publish(event: DomainEvent): Promise<void> {\n // Mirror the `domain_events_tier_routing_check` DB constraint at the\n // memory backend boundary so misuse fails the same way regardless of\n // backend (AUDIT-1).\n this.assertTierRouting(event);\n\n // Always record the event — even if this process is configured with a\n // pool filter that excludes it. Test code relies on `publishedEvents`\n // being a complete log of what was published, not a filtered view.\n this.publishedEvents.push(event);\n\n if (this.shouldDispatch(event)) {\n await this.dispatch(event);\n }\n }\n\n async publishMany(events: DomainEvent[]): Promise<void> {\n for (const event of events) {\n await this.publish(event);\n }\n }\n\n async findById(eventId: string): Promise<DomainEvent | null> {\n return this.publishedEvents.find((e) => e.id === eventId) ?? null;\n }\n\n subscribe<T extends DomainEvent = DomainEvent>(\n eventType: string,\n handler: (event: T) => Promise<void>,\n ): () => void {\n if (!this.handlers.has(eventType)) {\n this.handlers.set(eventType, new Set());\n }\n // Cast is safe — callers pass a typed handler; we store as the base type\n const set = this.handlers.get(eventType)!;\n const h = handler as (event: DomainEvent) => Promise<void>;\n set.add(h);\n\n return () => {\n set.delete(h);\n };\n }\n\n // ============================================================================\n // IEventReadPort (OBS-LIST-1)\n // ============================================================================\n\n async listEvents(query: ListEventsQuery = {}): Promise<EventPage> {\n const limit = clampEventLimit(query.limit);\n const keyset = query.cursor ? decodeEventCursor(query.cursor) : null;\n\n const str = (e: DomainEvent, key: string): string | null => {\n const v = e.metadata?.[key];\n return typeof v === 'string' ? v : null;\n };\n\n const matched = this.publishedEvents.filter((e) => {\n if (query.poolId && str(e, 'pool') !== query.poolId) return false;\n if (query.direction && str(e, 'direction') !== query.direction)\n return false;\n if (query.rootRunId && str(e, 'rootRunId') !== query.rootRunId)\n return false;\n if (query.since && e.occurredAt.getTime() < query.since.getTime())\n return false;\n if (query.tenantId !== undefined) {\n const t = str(e, 'tenantId');\n if (query.tenantId === null) {\n if (t !== null) return false;\n } else if (t !== query.tenantId) {\n return false;\n }\n }\n return true;\n });\n\n // Order occurred_at DESC, id DESC to match the Drizzle backend keyset.\n matched.sort((a, b) => {\n const dt = b.occurredAt.getTime() - a.occurredAt.getTime();\n if (dt !== 0) return dt;\n return a.id < b.id ? 1 : a.id > b.id ? -1 : 0;\n });\n\n const seeked = keyset\n ? matched.filter((e) => {\n const ct = e.occurredAt.getTime();\n const kt = keyset.occurredAt.getTime();\n if (ct < kt) return true;\n if (ct > kt) return false;\n return e.id < keyset.id;\n })\n : matched;\n\n const hasMore = seeked.length > limit;\n const page = hasMore ? seeked.slice(0, limit) : seeked;\n const items = page.map(toEventSummary);\n const last = page[page.length - 1];\n const nextCursor =\n hasMore && last\n ? encodeEventCursor({ occurredAt: last.occurredAt, id: last.id })\n : null;\n\n return { items, nextCursor };\n }\n\n /** Remove all published events and subscriptions. Useful in beforeEach. */\n clear(): void {\n this.publishedEvents.length = 0;\n this.handlers.clear();\n }\n\n /** Filter published events by `metadata.pool`. */\n publishedEventsForPool(pool: string): DomainEvent[] {\n return this.publishedEvents.filter((e) => e.metadata?.['pool'] === pool);\n }\n\n /** Filter published events by `metadata.direction`. */\n publishedEventsForDirection(direction: string): DomainEvent[] {\n return this.publishedEvents.filter((e) => e.metadata?.['direction'] === direction);\n }\n\n /**\n * Decide whether `event` should be dispatched to handlers given the\n * current pool filter.\n *\n * Semantics (mirroring `DrizzleEventBus.processBatch`):\n * - `opts.pools` undefined → dispatch everything (no filter).\n * - `opts.pools` empty array → treated as \"no filter\" to match the\n * Drizzle backend, where `pools && pools.length > 0` is the gate on\n * the `inArray` WHERE clause. Empty arrays dispatch everything.\n * - `opts.pools` non-empty → dispatch only when `event.metadata.pool`\n * is in the list. Events without `metadata.pool` do NOT match — they\n * are out of all configured pools by definition.\n */\n private shouldDispatch(event: DomainEvent): boolean {\n const pools = this.opts.pools;\n if (!pools || pools.length === 0) return true;\n const eventPool = event.metadata?.['pool'];\n return typeof eventPool === 'string' && pools.includes(eventPool);\n }\n\n /**\n * Mirror the `domain_events_tier_routing_check` DB CHECK at the memory\n * backend (AUDIT-1). Audit-tier events MUST have null/undefined\n * `pool` and `direction` in metadata; the bridge dispatcher relies on\n * this invariant.\n */\n private assertTierRouting(event: DomainEvent): void {\n const tier = event.metadata?.['tier'];\n if (tier !== 'audit') return;\n const pool = event.metadata?.['pool'];\n const direction = event.metadata?.['direction'];\n const poolIsNull = pool === null || pool === undefined;\n const directionIsNull = direction === null || direction === undefined;\n if (!poolIsNull || !directionIsNull) {\n throw new Error(\n `MemoryEventBus: tier='audit' events must have null pool and direction ` +\n `(got pool=${String(pool)}, direction=${String(direction)}). ` +\n `This mirrors the domain_events CHECK constraint.`,\n );\n }\n }\n\n private async dispatch(event: DomainEvent): Promise<void> {\n const set = this.handlers.get(event.type);\n if (!set) return;\n\n let firstError: unknown;\n for (const handler of set) {\n try {\n await handler(event);\n } catch (err) {\n this.logger.error(\n `Handler error for event type \"${event.type}\" (id: ${event.id}): ${err}`,\n );\n if (firstError === undefined) {\n firstError = err;\n }\n }\n }\n\n if (firstError !== undefined) {\n throw firstError;\n }\n }\n}\n","/**\n * Drizzle schema for the job orchestration domain (ADR-022).\n *\n * Three tables model the lifecycle of a durable job:\n * - `job` — definitions keyed by handler type (e.g. 'onboarding').\n * - `job_run` — one row per attempt to execute a job; worker claims\n * rows directly via SELECT ... FOR UPDATE SKIP LOCKED.\n * - `job_step` — individual steps within a run; memoises output for replay.\n *\n * Phase 1 ships only this layer. There is no `job_queue` table, no executor\n * port — see ADR-022 and `.claude/skills/jobs/SKILL.md` for the rationale.\n */\nimport {\n pgEnum,\n pgTable,\n uuid,\n text,\n jsonb,\n integer,\n timestamp,\n index,\n uniqueIndex,\n} from 'drizzle-orm/pg-core';\nimport { sql } from 'drizzle-orm';\nimport type { InferSelectModel } from 'drizzle-orm';\n\n// ─── Internal $type<> helpers ───────────────────────────────────────────────\n// Annotation types for jsonb columns only. JOB-2 defines the public protocol\n// types; these remain private to this file.\n\ntype RetryPolicy = {\n attempts: number;\n backoff: 'fixed' | 'exponential';\n baseMs: number;\n nonRetryableErrors?: string[];\n};\n\ntype JobRunError = {\n message: string;\n stack?: string;\n retryable: boolean;\n attempt: number;\n};\n\n// ─── Enums ──────────────────────────────────────────────────────────────────\n\nexport const jobRunStatusEnum = pgEnum('job_run_status', [\n 'pending',\n 'running',\n 'waiting',\n 'completed',\n 'failed',\n 'timed_out',\n 'canceled',\n]);\n\n// extended in ADR-027: tool_call | llm_call | wait | checkpoint | message\nexport const jobStepKindEnum = pgEnum('job_step_kind', ['task']);\n\nexport const jobStepStatusEnum = pgEnum('job_step_status', [\n 'pending',\n 'running',\n 'completed',\n 'failed',\n 'skipped',\n]);\n\nexport const collisionModeEnum = pgEnum('job_collision_mode', [\n 'queue',\n 'reject',\n 'replace',\n]);\n\nexport const replayFromEnum = pgEnum('job_replay_from', [\n 'scratch',\n 'last_step',\n 'last_checkpoint',\n]);\n\nexport const parentClosePolicyEnum = pgEnum('job_parent_close_policy', [\n 'terminate',\n 'cancel',\n 'abandon',\n]);\n\n// Phase 3 placeholder — see ADR-025\nexport const waitKindEnum = pgEnum('job_wait_kind', ['signal']);\n\n// Phase 2 may add more sources; requires Atlas migration\nexport const triggerSourceEnum = pgEnum('job_trigger_source', [\n 'manual',\n 'schedule',\n 'event',\n 'parent',\n]);\n\n// ─── job ────────────────────────────────────────────────────────────────────\n\nexport const jobs = pgTable('job', {\n type: text('type').primaryKey(),\n version: integer('version').notNull().default(1),\n pool: text('pool').notNull(),\n scopeEntityType: text('scope_entity_type'),\n retryPolicy: jsonb('retry_policy').notNull().$type<RetryPolicy>(),\n timeoutMs: integer('timeout_ms'),\n concurrencyKeyTemplate: text('concurrency_key_template'),\n collisionMode: collisionModeEnum('collision_mode').notNull().default('queue'),\n dedupeKeyTemplate: text('dedupe_key_template'),\n dedupeWindowMs: integer('dedupe_window_ms'),\n priorityDefault: integer('priority_default').notNull().default(0),\n replayFrom: replayFromEnum('replay_from').notNull().default('last_checkpoint'),\n createdAt: timestamp('created_at', { withTimezone: true }).notNull().defaultNow(),\n updatedAt: timestamp('updated_at', { withTimezone: true }).notNull().defaultNow(),\n});\n\nexport type JobDefinitionRow = InferSelectModel<typeof jobs>;\n\n// ─── job_run ────────────────────────────────────────────────────────────────\n\nexport const jobRuns = pgTable(\n 'job_run',\n {\n id: uuid('id').primaryKey().defaultRandom(),\n jobType: text('job_type').notNull().references(() => jobs.type),\n jobVersion: integer('job_version').notNull(),\n parentRunId: uuid('parent_run_id').references((): any => jobRuns.id),\n /**\n * Service generates `id` client-side via randomUUID() and sets\n * root_run_id = id for root runs (single INSERT, no self-FK race).\n */\n rootRunId: uuid('root_run_id').notNull(),\n parentClosePolicy: parentClosePolicyEnum('parent_close_policy')\n .notNull()\n .default('terminate'),\n scopeEntityType: text('scope_entity_type'),\n scopeEntityId: text('scope_entity_id'),\n tenantId: text('tenant_id'),\n tags: jsonb('tags').notNull().default({}).$type<Record<string, string>>(),\n pool: text('pool').notNull(),\n priority: integer('priority').notNull().default(0),\n concurrencyKey: text('concurrency_key'),\n dedupeKey: text('dedupe_key'),\n status: jobRunStatusEnum('status').notNull().default('pending'),\n input: jsonb('input').notNull().$type<Record<string, unknown>>(),\n output: jsonb('output').$type<Record<string, unknown>>(),\n error: jsonb('error').$type<JobRunError>(),\n triggerSource: triggerSourceEnum('trigger_source').notNull(),\n triggerRef: text('trigger_ref'),\n runAt: timestamp('run_at', { withTimezone: true }).notNull().defaultNow(),\n startedAt: timestamp('started_at', { withTimezone: true }),\n finishedAt: timestamp('finished_at', { withTimezone: true }),\n claimedAt: timestamp('claimed_at', { withTimezone: true }),\n attempts: integer('attempts').notNull().default(0),\n // Phase 3 placeholder — see ADR-025\n waitKind: waitKindEnum('wait_kind'),\n // Phase 3 placeholder — see ADR-025\n resumeToken: text('resume_token'),\n // Phase 3 placeholder — see ADR-025\n waitDeadline: timestamp('wait_deadline', { withTimezone: true }),\n createdAt: timestamp('created_at', { withTimezone: true }).notNull().defaultNow(),\n updatedAt: timestamp('updated_at', { withTimezone: true }).notNull().defaultNow(),\n },\n (t) => ({\n /** Claim query: ORDER BY priority DESC, run_at ASC. */\n idxJobRunClaim: index('idx_job_run_claim').on(t.status, t.pool, t.runAt),\n /** Tree traversal / cascade cancel. */\n idxJobRunRoot: index('idx_job_run_root').on(t.rootRunId),\n /** listForScope query. */\n idxJobRunScope: index('idx_job_run_scope').on(t.scopeEntityType, t.scopeEntityId),\n /** Idempotency collapse — partial index. */\n idxJobRunDedupe: index('idx_job_run_dedupe')\n .on(t.jobType, t.dedupeKey)\n .where(sql`${t.dedupeKey} IS NOT NULL`),\n /** Collision check — partial index. */\n idxJobRunConcurrency: index('idx_job_run_concurrency')\n .on(t.concurrencyKey)\n .where(\n sql`${t.concurrencyKey} IS NOT NULL AND ${t.status} IN ('pending','running')`,\n ),\n }),\n);\n\nexport type JobRunRow = InferSelectModel<typeof jobRuns>;\n\n// ─── job_step ───────────────────────────────────────────────────────────────\n\nexport const jobSteps = pgTable(\n 'job_step',\n {\n id: uuid('id').primaryKey().defaultRandom(),\n jobRunId: uuid('job_run_id').notNull().references(() => jobRuns.id),\n stepId: text('step_id').notNull(),\n kind: jobStepKindEnum('kind').notNull().default('task'),\n /**\n * Monotonic within run. integer (max ~2B per run) is sufficient —\n * downgraded from ADR-022's bigint; revisit only if a single run\n * ever exceeds 2 billion steps.\n */\n seq: integer('seq').notNull(),\n status: jobStepStatusEnum('status').notNull().default('pending'),\n input: jsonb('input').$type<Record<string, unknown>>(),\n /** Memoised on success for replay. */\n output: jsonb('output').$type<Record<string, unknown>>(),\n error: jsonb('error').$type<JobRunError>(),\n attempts: integer('attempts').notNull().default(0),\n startedAt: timestamp('started_at', { withTimezone: true }),\n finishedAt: timestamp('finished_at', { withTimezone: true }),\n },\n (t) => ({\n /** No duplicate step IDs per run. */\n idxJobStepRunStep: uniqueIndex('idx_job_step_run_step').on(t.jobRunId, t.stepId),\n /** Ordered timeline reads. */\n idxJobStepTimeline: index('idx_job_step_timeline').on(t.jobRunId, t.seq),\n }),\n);\n\nexport type JobStepRow = InferSelectModel<typeof jobSteps>;\n","/**\n * Injection tokens for the job orchestration domain layer (ADR-022, JOB-2).\n *\n * Consumer code injects these symbols via `@Inject(JOB_ORCHESTRATOR)` etc.;\n * concrete backends (JOB-3 Drizzle, JOB-4 Memory) provide the implementations\n * through `JobsDomainModule.forRoot({ backend })` in JOB-5.\n *\n * Each token is a namespaced `Symbol.for(...)` (ADR-037, via `tokenKey()`) —\n * distinct per key, so Nest's DI lookup is unambiguous, AND matching by VALUE\n * across import boundaries so the package and a (legacy) vendored runtime copy\n * resolve to the same symbol.\n */\nimport { tokenKey } from '../token-key';\n\nexport const JOB_ORCHESTRATOR = Symbol.for(tokenKey('jobs', 'orchestrator'));\nexport const JOB_RUN_SERVICE = Symbol.for(tokenKey('jobs', 'run-service'));\nexport const JOB_STEP_SERVICE = Symbol.for(tokenKey('jobs', 'step-service'));\n\n/**\n * Multi-tenancy opt-in flag (JOB-8). Bound to the boolean passed in via\n * `JobsDomainModule.forRoot({ multiTenant })`, defaulting to `false`.\n *\n * When `true`, the four service-layer backends (Drizzle + Memory orchestrator\n * and run-service) enforce `tenantId` on every mutating / targeted-read call:\n * `start`, `cancel`, `listForScope`, `cancelForScope`, `rescheduleForScope`.\n * Missing (`undefined`) `tenantId` throws `MissingTenantIdError`; explicit\n * `null` opts into cross-tenant background work and passes through.\n *\n * The JobWorker claim loop is **cross-tenant by design** — the worker has no\n * tenant context; `tenantId` is populated at write time and enforced on\n * targeted reads. See docs/specs/JOB-8.md.\n */\nexport const JOBS_MULTI_TENANT = Symbol.for(tokenKey('jobs', 'multi-tenant'));\n","/**\n * Handler base class, JobContext, @JobHandler decorator, and policy types\n * for the job orchestration domain (ADR-022, JOB-2).\n *\n * User-authored jobs subclass `JobHandlerBase<TInput, TOutput>` and decorate\n * the class with `@JobHandler<TInput>('job_type', meta)`. The decorator\n * 1. stores metadata via `Reflect.defineMetadata` so Nest's reflector can\n * pick it up at module boot, and\n * 2. populates `JOB_HANDLER_REGISTRY` — a module-singleton map consumed by\n * `JobWorkerModule` (JOB-5) to materialise `job` rows and resolve\n * handler classes during claim/execute.\n *\n * No runtime orchestration lives here; this file is a pure type + decorator\n * surface so downstream PRs (JOB-3..JOB-5) can implement against a stable\n * shape.\n */\n// TODO(logging-subsystem): swap to ILogger once ADR-028 lands\nimport type { Logger } from '@nestjs/common';\nimport { tokenKey } from '../token-key';\nimport type { EventOfType, EventTypeName } from '../events/generated/types';\nimport type { JobRun } from './job-orchestrator.protocol';\n\n// ─── ParentClosePolicy ──────────────────────────────────────────────────────\n\n/**\n * What happens to running child runs when a parent enters a terminal state.\n * Stored on the child at spawn; changes to the parent after spawn do NOT\n * retroactively rewrite children.\n */\nexport enum ParentClosePolicy {\n Terminate = 'terminate',\n Cancel = 'cancel',\n Abandon = 'abandon',\n}\n\n// ─── Policy types ───────────────────────────────────────────────────────────\n\nexport interface RetryPolicy {\n attempts: number;\n backoff: 'fixed' | 'exponential';\n baseMs: number;\n nonRetryableErrors?: string[];\n}\n\nexport interface ConcurrencyPolicy<TInput> {\n key: (input: TInput) => string;\n collisionMode: 'queue' | 'reject' | 'replace';\n}\n\nexport interface DedupePolicy<TInput> {\n key: (input: TInput) => string;\n windowMs: number;\n}\n\n/**\n * Declarative scope reference. `TScope` is parameterised so JOB-7 can narrow\n * `entity` to the generated `ScopeEntityType` union at the call site without\n * modifying this file (OQ-1 resolution, 2026-04-20).\n */\nexport interface ScopeRef<TInput, TScope extends string = string> {\n entity: TScope;\n from: (input: TInput) => string;\n}\n\n/**\n * Bridge trigger authoring shape (BRIDGE-6 follow-up — BRIDGE-6 shipped the\n * generator + runtime for `@JobHandler({ triggers })` but never added the\n * authoring field to this type; the generator's tests scan source as strings,\n * so a real decorator was never compiled and the gap went uncaught).\n *\n * Declared on `@JobHandler({ triggers })`; the codegen bridge-registry\n * generator (`src/cli/shared/bridge-registry-generator.ts`) scans these from\n * source and emits `bridge/generated/registry.ts`, validating each `event`\n * against the generated `eventRegistry` at `gen-all`. The distributed union\n * narrows `map`/`when` per `event`, so callbacks are typed against the event\n * payload (ADR-023, \"typed against PayloadOfType<T>\").\n *\n * Typed against events' generated types — the same `import type` coupling the\n * bridge already has (erased at runtime). `jobs` must NOT import `bridge`, so\n * the post-gen `BridgeTriggerEntry` is deliberately not referenced here;\n * `triggerId`/`jobType` are computed by the generator, not authored.\n */\nexport type JobTrigger<TInput> = {\n [T in EventTypeName]: {\n /** Event type that fires this trigger. Validated against `eventRegistry`. */\n event: T;\n /** Maps the event to the job input. Inlined verbatim into the registry. */\n map: (event: EventOfType<T>) => TInput;\n /** Optional guard; `false` → wrapper records `status='skipped'`. */\n when?: (event: EventOfType<T>) => boolean;\n };\n}[EventTypeName];\n\nexport interface JobHandlerMeta<TInput> {\n pool?: string;\n scope?: ScopeRef<TInput>;\n retry?: RetryPolicy;\n concurrency?: ConcurrencyPolicy<TInput>;\n dedupe?: DedupePolicy<TInput>;\n timeoutMs?: number;\n replayFrom?: 'scratch' | 'last_step' | 'last_checkpoint';\n /**\n * Bridge triggers (ADR-023 Tier 3). Codegen scans these into `bridgeRegistry`;\n * the framework `BridgeDeliveryHandler` starts this job per matched event.\n * Absent for jobs started directly or via `IEventFlow.publishAndStart`.\n */\n triggers?: readonly JobTrigger<TInput>[];\n}\n\n// ─── Runtime option shapes ──────────────────────────────────────────────────\n\nexport interface StepOptions {\n retry?: RetryPolicy;\n timeoutMs?: number;\n}\n\nexport interface SpawnChildOptions {\n closePolicy?: ParentClosePolicy;\n runAt?: Date;\n priority?: number;\n tags?: Record<string, string>;\n}\n\n// ─── JobContext ─────────────────────────────────────────────────────────────\n\nexport interface JobContext<TInput> {\n readonly input: TInput;\n readonly run: JobRun;\n step<TOutput>(\n stepId: string,\n fn: () => Promise<TOutput>,\n opts?: StepOptions,\n ): Promise<TOutput>;\n spawnChild(type: string, input: unknown, opts?: SpawnChildOptions): Promise<JobRun>;\n readonly logger: Logger;\n // NOT in Phase 1 — deferred to ADR-025:\n // waitFor(kind, token, opts)\n // signal(token, payload)\n // sleep(ms)\n}\n\n// ─── JobHandlerBase ─────────────────────────────────────────────────────────\n\nexport abstract class JobHandlerBase<TInput, TOutput = unknown> {\n abstract run(ctx: JobContext<TInput>): Promise<TOutput>;\n}\n\n// ─── Registry + decorator ───────────────────────────────────────────────────\n\n/**\n * Module-singleton map keyed by job type. Populated by the `@JobHandler`\n * decorator at class definition time; consumed by `JobWorkerModule` (JOB-5)\n * to upsert `job` rows and resolve handler classes during claim/execute.\n */\nexport const JOB_HANDLER_REGISTRY = new Map<\n string,\n {\n type: string;\n meta: JobHandlerMeta<unknown>;\n handlerClass: new (...args: unknown[]) => JobHandlerBase<unknown>;\n }\n>();\n\n// ADR-037: namespaced `Symbol.for(...)` (via `tokenKey()`) so the reflection-metadata\n// key matches by value across import boundaries (the @JobHandler decorator and the\n// reader may resolve different runtime copies). Distinct from the DI tokens but\n// subject to the same dual-package identity hazard.\nexport const JOB_HANDLER_METADATA_KEY = Symbol.for(tokenKey('jobs', 'handler-metadata'));\n\n/**\n * Class decorator that registers a handler with the job type, the full\n * metadata shape, and the target class constructor.\n *\n * Duplicate-type behaviour (OQ-3, resolved 2026-04-18):\n * - `NODE_ENV === 'production'` → throw; silent overwrite in prod is a\n * correctness bug.\n * - `NODE_ENV === 'test'` → silent overwrite (tests intentionally\n * re-register handlers).\n * - otherwise (dev) → `console.warn` + overwrite. `console`\n * is used intentionally instead of the Nest `Logger` — decorators run\n * at module-load time before any Nest container exists.\n */\nexport function JobHandler<TInput>(\n type: string,\n meta: JobHandlerMeta<TInput>,\n): ClassDecorator {\n return (target) => {\n if (JOB_HANDLER_REGISTRY.has(type)) {\n const env = process.env.NODE_ENV;\n if (env === 'production') {\n throw new Error(\n `[JobHandler] Duplicate registration for job type '${type}'. ` +\n `Each @JobHandler must declare a unique type.`,\n );\n }\n if (env !== 'test') {\n // eslint-disable-next-line no-console\n console.warn(\n `[JobHandler] Duplicate registration for job type '${type}'. ` +\n `Overwriting previous handler — this is almost certainly a bug.`,\n );\n }\n }\n\n Reflect.defineMetadata(JOB_HANDLER_METADATA_KEY, { type, meta }, target);\n JOB_HANDLER_REGISTRY.set(type, {\n type,\n meta: meta as JobHandlerMeta<unknown>,\n handlerClass: target as unknown as new (\n ...args: unknown[]\n ) => JobHandlerBase<unknown>,\n });\n };\n}\n\n// ─── HandlerRegistry — read helpers consumed by JobWorkerModule (JOB-5) ─────\n\n/**\n * Single entry shape returned by `HandlerRegistry.getAll()` / `.get()` and\n * exposed to `JobWorkerModule.onModuleInit` for boot-time upserts.\n *\n * Structurally compatible with `IJobOrchestrator.upsertJobRows`'s\n * `JobUpsertEntry` so the worker module can pass entries through verbatim\n * without re-mapping.\n */\nexport interface HandlerRegistryEntry {\n type: string;\n meta: JobHandlerMeta<unknown>;\n handlerClass: new (...args: unknown[]) => JobHandlerBase<unknown>;\n}\n\n/**\n * Read facade over `JOB_HANDLER_REGISTRY`. The decorator's write path is\n * unchanged; this namespace exists so consumers (the worker module, tests)\n * don't import the raw `Map` and accidentally mutate it.\n */\nexport namespace HandlerRegistry {\n /** All registered entries in insertion order. */\n export function getAll(): HandlerRegistryEntry[] {\n return Array.from(JOB_HANDLER_REGISTRY.values());\n }\n\n /** Lookup by job type, or `undefined` if no `@JobHandler` is registered. */\n export function get(type: string): HandlerRegistryEntry | undefined {\n return JOB_HANDLER_REGISTRY.get(type);\n }\n}\n","/**\n * DrizzleJobOrchestrator — Postgres-backed implementation of\n * `IJobOrchestrator` (ADR-022, JOB-3).\n *\n * Single-layer architecture: `start` writes a single `job_run` row; the\n * `JobWorker` polling loop claims it directly via `FOR UPDATE SKIP LOCKED`.\n * No `job_queue` table, no executor port. See `docs/specs/JOB-3.md`.\n */\nimport { randomUUID } from 'node:crypto';\nimport { Inject, Injectable, Logger } from '@nestjs/common';\nimport { and, desc, eq, gt, inArray, isNotNull, ne, notInArray, sql } from 'drizzle-orm';\nimport type { DrizzleClient } from '../../types/drizzle';\nimport type { DrizzleTransaction } from '../events/event-bus.protocol';\nimport { DRIZZLE } from '../../constants/tokens';\nimport {\n jobRuns,\n jobs,\n type JobDefinitionRow,\n type JobRunRow,\n} from './job-orchestration.schema';\nimport type {\n CancelOptions,\n IJobOrchestrator,\n JobPoolDef,\n JobRun,\n JobUpsertEntry,\n StartOptions,\n} from './job-orchestrator.protocol';\nimport {\n JobCollisionError,\n JobNotReplayableError,\n JobTemplateFieldMissingError,\n JobTypeNotFoundError,\n MissingTenantIdError,\n} from './jobs-errors';\nimport { jobSteps } from './job-orchestration.schema';\nimport { JOBS_MULTI_TENANT } from './jobs-domain.tokens';\n\n/**\n * Terminal statuses — transitions into these are final. Used by `cancel`\n * (to short-circuit idempotently) and by `replay` (as the guard gate).\n */\nexport const TERMINAL_STATUSES = [\n 'completed',\n 'failed',\n 'timed_out',\n 'canceled',\n] as const;\ntype TerminalStatus = (typeof TERMINAL_STATUSES)[number];\ntype JobRunStatus = JobRunRow['status'];\n\n/** Statuses excluded from dedupe window matches per ADR-022. */\nconst DEDUPE_EXCLUDED_STATUSES: JobRunStatus[] = ['canceled', 'failed'];\n/** Statuses that count as in-flight for concurrency collision checks. */\nconst IN_FLIGHT_STATUSES: JobRunStatus[] = ['pending', 'running'];\n\n/**\n * Substitute `{{field}}` placeholders against the input payload.\n *\n * Implementation decision (JOB-3, 2026-04-19): simple `{{field}}` single-key\n * substitution, no dotted paths, no Mustache/Handlebars dependency. A missing\n * field throws `JobTemplateFieldMissingError` synchronously — cheaper than\n * discovering the misconfiguration at claim time.\n */\nexport function evaluateKeyTemplate(\n template: string,\n input: Record<string, unknown>,\n): string {\n return template.replace(/\\{\\{\\s*([a-zA-Z0-9_]+)\\s*\\}\\}/g, (_match, field: string) => {\n const value = input[field];\n if (value === undefined || value === null) {\n throw new JobTemplateFieldMissingError(template, field);\n }\n return String(value);\n });\n}\n\n@Injectable()\nexport class DrizzleJobOrchestrator implements IJobOrchestrator {\n // TODO(logging-subsystem): swap to ILogger once ADR-028 lands\n private readonly logger = new Logger(DrizzleJobOrchestrator.name);\n\n constructor(\n @Inject(DRIZZLE) private readonly db: DrizzleClient,\n @Inject(JOBS_MULTI_TENANT) private readonly multiTenant: boolean,\n ) {}\n\n /**\n * JOB-8 — resolve `tenantId` for a mutating / targeted-read call.\n * Returns the tenant value that should be written to the row (or compared\n * against in a WHERE clause). When `multiTenant` is off, the column is\n * forced to `null` regardless of what callers pass. When on, `undefined`\n * throws; `null` and strings pass through untouched.\n */\n private resolveTenantId(\n method: string,\n tenantId: string | null | undefined,\n ): string | null {\n if (!this.multiTenant) return null;\n if (tenantId === undefined) throw new MissingTenantIdError(method);\n return tenantId;\n }\n\n // ==========================================================================\n // start\n // ==========================================================================\n\n async start(\n type: string,\n input: unknown,\n opts: StartOptions = {},\n tx?: DrizzleTransaction,\n ): Promise<JobRun> {\n const payload = (input ?? {}) as Record<string, unknown>;\n\n // JOB-8 — resolve tenant gate up front so `multi_tenant=true` +\n // undefined surfaces before any row is touched.\n const tenantId = this.resolveTenantId('start', opts.tenantId);\n\n // BRIDGE-7: thread the optional caller tx through every read/write\n // in this method so EventFlowService.publishAndStart can bundle the\n // outbox insert, the eager job_run insert, and (for Case B) the\n // bridge_delivery pre-write into a single transaction.\n const client = (tx ?? this.db) as DrizzleClient;\n\n // 1a. Load job definition.\n const [def] = await client\n .select()\n .from(jobs)\n .where(eq(jobs.type, type))\n .limit(1);\n if (!def) throw new JobTypeNotFoundError(type);\n const definition = def as JobDefinitionRow;\n\n // 1b. Dedupe check.\n if (definition.dedupeKeyTemplate && definition.dedupeWindowMs) {\n const dedupeKey = evaluateKeyTemplate(definition.dedupeKeyTemplate, payload);\n const windowStart = new Date(Date.now() - definition.dedupeWindowMs);\n const existing = await client\n .select()\n .from(jobRuns)\n .where(\n and(\n eq(jobRuns.jobType, type),\n eq(jobRuns.dedupeKey, dedupeKey),\n gt(jobRuns.createdAt, windowStart),\n // status NOT IN ('canceled', 'failed')\n notInStatus(DEDUPE_EXCLUDED_STATUSES),\n ),\n )\n .orderBy(desc(jobRuns.createdAt))\n .limit(1);\n if (existing.length > 0) {\n return existing[0] as JobRun;\n }\n }\n\n // 1c. Concurrency collision check.\n let concurrencyKey: string | null = null;\n if (definition.concurrencyKeyTemplate) {\n concurrencyKey = evaluateKeyTemplate(\n definition.concurrencyKeyTemplate,\n payload,\n );\n const inFlight = await client\n .select()\n .from(jobRuns)\n .where(\n and(\n eq(jobRuns.concurrencyKey, concurrencyKey),\n inArray(jobRuns.status, IN_FLIGHT_STATUSES),\n ),\n )\n .limit(1);\n if (inFlight.length > 0) {\n const incumbent = inFlight[0] as JobRun;\n switch (definition.collisionMode) {\n case 'reject':\n throw new JobCollisionError(type, concurrencyKey, incumbent);\n case 'replace':\n // JOB-8 — thread the incumbent's own tenantId through the\n // internal cascade. Without this, every `replace`-collision\n // start() under multiTenant=true throws MissingTenantIdError\n // from the inner cancel() call instead of cancelling the\n // incumbent. Mirrors the memory backend's `cancelLocked(\n // incumbent.id, ..., incumbent.tenantId)` pattern.\n await this.cancel(incumbent.id, {\n cascade: true,\n reason: 'replaced',\n tenantId: incumbent.tenantId,\n });\n break;\n case 'queue':\n // Fall through — row is inserted; claim query gates it until\n // the incumbent transitions (see JobWorker.processRun queue gate).\n break;\n }\n }\n }\n\n // 1d. Resolve id + rootRunId, INSERT.\n const newId = randomUUID();\n let rootRunId: string = newId;\n if (opts.parentRunId) {\n const [parent] = await client\n .select({ rootRunId: jobRuns.rootRunId })\n .from(jobRuns)\n .where(eq(jobRuns.id, opts.parentRunId))\n .limit(1);\n if (!parent) {\n throw new Error(\n `parentRunId ${opts.parentRunId} does not reference an existing job_run`,\n );\n }\n rootRunId = parent.rootRunId;\n }\n\n const dedupeKey =\n definition.dedupeKeyTemplate\n ? evaluateKeyTemplate(definition.dedupeKeyTemplate, payload)\n : null;\n\n const [inserted] = await client\n .insert(jobRuns)\n .values({\n id: newId,\n jobType: type,\n jobVersion: definition.version,\n parentRunId: opts.parentRunId ?? null,\n rootRunId,\n parentClosePolicy: opts.parentClosePolicy ?? 'terminate',\n scopeEntityType: opts.scope?.entityType ?? null,\n scopeEntityId: opts.scope?.entityId ?? null,\n tenantId,\n tags: opts.tags ?? {},\n pool: opts.pool ?? definition.pool,\n priority: opts.priority ?? definition.priorityDefault,\n concurrencyKey,\n dedupeKey,\n status: 'pending',\n input: payload,\n output: null,\n error: null,\n triggerSource: opts.triggerSource ?? 'manual',\n triggerRef: opts.triggerRef ?? null,\n runAt: opts.runAt ?? new Date(),\n startedAt: null,\n finishedAt: null,\n claimedAt: null,\n attempts: 0,\n })\n .returning();\n\n return inserted as JobRun;\n }\n\n // ==========================================================================\n // cancel\n // ==========================================================================\n\n async cancel(runId: string, opts: CancelOptions = {}): Promise<void> {\n // JOB-8 — resolve tenant gate up front (strict undefined-throws).\n const tenantId = this.resolveTenantId('cancel', opts.tenantId);\n\n // Load target.\n const [target] = await this.db\n .select()\n .from(jobRuns)\n .where(eq(jobRuns.id, runId))\n .limit(1);\n if (!target) return;\n // JOB-8 — cross-tenant cancel is a silent no-op (no existence leak).\n if (this.multiTenant && target.tenantId !== tenantId) return;\n if (TERMINAL_STATUSES.includes(target.status as TerminalStatus)) {\n return; // idempotent\n }\n\n // Atomic transition, guarded against concurrent terminal moves.\n const [cancelled] = await this.db\n .update(jobRuns)\n .set({\n status: 'canceled',\n finishedAt: new Date(),\n updatedAt: new Date(),\n })\n .where(\n and(eq(jobRuns.id, runId), notInStatus([...TERMINAL_STATUSES])),\n )\n .returning();\n\n if (!cancelled) return; // lost the race; already terminal\n\n if (opts.cascade === false) return;\n\n // Fetch descendants and branch on parent_close_policy.\n const descendants = await this.db\n .select()\n .from(jobRuns)\n .where(\n and(\n eq(jobRuns.rootRunId, target.rootRunId),\n ne(jobRuns.id, runId),\n notInStatus([...TERMINAL_STATUSES]),\n ),\n );\n\n for (const child of descendants) {\n const policy = (child as JobRunRow).parentClosePolicy;\n if (policy === 'abandon') continue;\n // 'terminate' | 'cancel' — both transition the child to canceled.\n await this.db\n .update(jobRuns)\n .set({\n status: 'canceled',\n finishedAt: new Date(),\n updatedAt: new Date(),\n })\n .where(\n and(\n eq(jobRuns.id, (child as JobRunRow).id),\n notInStatus([...TERMINAL_STATUSES]),\n ),\n );\n }\n\n void opts.reason; // reserved for future audit logging\n }\n\n // ==========================================================================\n // replay\n // ==========================================================================\n\n async replay(runId: string): Promise<JobRun> {\n // Load target + its job definition (we need replay_from).\n const [target] = await this.db\n .select()\n .from(jobRuns)\n .where(eq(jobRuns.id, runId))\n .limit(1);\n if (!target) {\n throw new Error(`replay: run ${runId} not found`);\n }\n const run = target as JobRunRow;\n if (!TERMINAL_STATUSES.includes(run.status as TerminalStatus)) {\n throw new JobNotReplayableError(runId, run.status);\n }\n\n const [def] = await this.db\n .select()\n .from(jobs)\n .where(eq(jobs.type, run.jobType))\n .limit(1);\n if (!def) throw new JobTypeNotFoundError(run.jobType);\n const mode = (def as JobDefinitionRow).replayFrom;\n\n // Atomic: step reset + run reset must commit together.\n const result = await this.db.transaction(async (tx) => {\n if (mode === 'scratch') {\n await tx.delete(jobSteps).where(eq(jobSteps.jobRunId, runId));\n } else if (mode === 'last_step') {\n // Delete only non-completed step rows — completed steps stay memoised.\n await tx\n .delete(jobSteps)\n .where(\n and(eq(jobSteps.jobRunId, runId), ne(jobSteps.status, 'completed')),\n );\n } else {\n // 'last_checkpoint' — Phase 1 has no explicit checkpoint markers, so\n // behaviour collapses to `last_step`. See docs/specs/JOB-3.md\n // \"Implementation Decisions\" — planned divergence in a later phase.\n await tx\n .delete(jobSteps)\n .where(\n and(eq(jobSteps.jobRunId, runId), ne(jobSteps.status, 'completed')),\n );\n }\n\n const [updated] = await tx\n .update(jobRuns)\n .set({\n status: 'pending',\n attempts: 0,\n runAt: new Date(),\n startedAt: null,\n finishedAt: null,\n claimedAt: null,\n error: null,\n output: null,\n updatedAt: new Date(),\n })\n .where(eq(jobRuns.id, runId))\n .returning();\n return updated as JobRunRow;\n });\n\n return result as JobRun;\n }\n\n // ==========================================================================\n // upsertJobRows — boot-time materialisation of `job` definitions\n // ==========================================================================\n\n /**\n * Hash-gated `INSERT … ON CONFLICT (type) DO UPDATE … WHERE` per Q3\n * resolution (2026-04-19): the `UPDATE` branch executes only when one\n * of the persisted metadata fields differs from the incoming payload;\n * `version` bumps only on real change; concurrent boots with identical\n * content are idempotent no-ops.\n *\n * Why this shape (not `DO NOTHING`, not advisory locks):\n * - `DO NOTHING` would let an old-version instance leave a stale row\n * that a new-version instance can't overwrite during a rolling deploy.\n * - Advisory locks add latency and leak risk under crashes.\n * - The `WHERE … IS DISTINCT FROM …` clause makes the conditional\n * atomic — no read-modify-write race on `version` between concurrent\n * boots.\n *\n * Orphan detection: a single `SELECT type FROM job WHERE type NOT IN (...)`\n * returns the types present in DB but absent from `entries`. Caller (boot\n * validator) decides whether to throw `BootValidationError`.\n */\n async upsertJobRows(\n entries: JobUpsertEntry[],\n poolConfig: ReadonlyMap<string, JobPoolDef>,\n ): Promise<{ orphaned: string[] }> {\n void poolConfig; // pool validation is the module's responsibility; orchestrator just persists\n\n for (const entry of entries) {\n const meta = entry.meta;\n const pool = meta.pool ?? 'batch';\n const retryPolicy = meta.retry ?? {\n attempts: 1,\n backoff: 'fixed' as const,\n baseMs: 0,\n };\n const concurrencyKeyTemplate =\n (meta.concurrency as { key?: unknown } | undefined)?.key;\n const concurrencyKeyTemplateStr =\n typeof concurrencyKeyTemplate === 'string' ? concurrencyKeyTemplate : null;\n const collisionMode =\n (meta.concurrency?.collisionMode as JobDefinitionRow['collisionMode']) ??\n 'queue';\n const dedupeKeyTemplate =\n (meta.dedupe as { key?: unknown } | undefined)?.key;\n const dedupeKeyTemplateStr =\n typeof dedupeKeyTemplate === 'string' ? dedupeKeyTemplate : null;\n const dedupeWindowMs = meta.dedupe?.windowMs ?? null;\n const timeoutMs = meta.timeoutMs ?? null;\n const replayFrom = meta.replayFrom ?? 'last_checkpoint';\n const scopeEntityType = meta.scope?.entity ?? null;\n // Q3 resolution: priority_default and replay_from are part of the\n // hashed metadata even though they aren't currently set via decorator\n // metadata above (priority_default has no `@JobHandler` field yet).\n // Default to 0 to keep UPDATE branch quiet across deploys.\n const priorityDefault = 0;\n\n // Hash-gated upsert: every metadata column appears in the WHERE clause\n // so the UPDATE branch only fires on a real change. `version` bumps\n // exactly when the WHERE matches.\n await this.db\n .insert(jobs)\n .values({\n type: entry.type,\n version: 1,\n pool,\n scopeEntityType,\n retryPolicy,\n timeoutMs,\n concurrencyKeyTemplate: concurrencyKeyTemplateStr,\n collisionMode,\n dedupeKeyTemplate: dedupeKeyTemplateStr,\n dedupeWindowMs,\n priorityDefault,\n replayFrom,\n })\n .onConflictDoUpdate({\n target: jobs.type,\n set: {\n pool: sql`EXCLUDED.pool`,\n scopeEntityType: sql`EXCLUDED.scope_entity_type`,\n retryPolicy: sql`EXCLUDED.retry_policy`,\n timeoutMs: sql`EXCLUDED.timeout_ms`,\n concurrencyKeyTemplate: sql`EXCLUDED.concurrency_key_template`,\n collisionMode: sql`EXCLUDED.collision_mode`,\n dedupeKeyTemplate: sql`EXCLUDED.dedupe_key_template`,\n dedupeWindowMs: sql`EXCLUDED.dedupe_window_ms`,\n priorityDefault: sql`EXCLUDED.priority_default`,\n replayFrom: sql`EXCLUDED.replay_from`,\n version: sql`${jobs.version} + 1`,\n updatedAt: sql`now()`,\n },\n // The hash gate: every field listed in the Q3 resolution appears\n // here. `IS DISTINCT FROM` is the null-safe inequality operator;\n // jsonb cast to text gives stable comparison without invoking a\n // dedicated hash column (avoids a JOB-1 schema migration).\n setWhere: sql`\n ${jobs.pool} IS DISTINCT FROM EXCLUDED.pool OR\n ${jobs.retryPolicy}::text IS DISTINCT FROM EXCLUDED.retry_policy::text OR\n ${jobs.timeoutMs} IS DISTINCT FROM EXCLUDED.timeout_ms OR\n ${jobs.concurrencyKeyTemplate} IS DISTINCT FROM EXCLUDED.concurrency_key_template OR\n ${jobs.collisionMode} IS DISTINCT FROM EXCLUDED.collision_mode OR\n ${jobs.dedupeKeyTemplate} IS DISTINCT FROM EXCLUDED.dedupe_key_template OR\n ${jobs.dedupeWindowMs} IS DISTINCT FROM EXCLUDED.dedupe_window_ms OR\n ${jobs.priorityDefault} IS DISTINCT FROM EXCLUDED.priority_default OR\n ${jobs.replayFrom} IS DISTINCT FROM EXCLUDED.replay_from OR\n ${jobs.scopeEntityType} IS DISTINCT FROM EXCLUDED.scope_entity_type\n `,\n });\n }\n\n // Orphan detection: any `job` row whose type is not in the registry.\n const types = entries.map((e) => e.type);\n const orphans =\n types.length === 0\n ? await this.db.select({ type: jobs.type }).from(jobs)\n : await this.db\n .select({ type: jobs.type })\n .from(jobs)\n .where(notInArray(jobs.type, types));\n\n return { orphaned: orphans.map((o) => o.type) };\n }\n}\n\n// ─── Helpers ────────────────────────────────────────────────────────────────\n\nfunction notInStatus(statuses: JobRunStatus[]) {\n // Drizzle's inArray composes with `not` via negation helper; use raw sql\n // to stay readable. `inArray` + `.not()` isn't idiomatic in 0.45.\n const negated = statuses.map((s) => ne(jobRuns.status, s));\n return and(...negated);\n}\n\n// `isNotNull` + `gt` imports are retained for potential future use; silence\n// unused-import lint by re-exporting via `void`.\nvoid isNotNull;\n","/**\n * Typed errors for the job orchestration domain (ADR-022, JOB-3).\n *\n * All thrown by the Drizzle orchestrator (and mirrored by the Memory\n * backend in JOB-4). They exist as classes so consumers can `instanceof`\n * them in catch blocks and exception filters can map them to HTTP codes.\n */\nimport type { JobRun } from './job-orchestrator.protocol';\n\n/**\n * `start(type, …)` was called for a job type that has no row in the `job`\n * table. At runtime this usually means the handler was not decorated or the\n * boot validator (JOB-5) has not registered it yet.\n */\nexport class JobTypeNotFoundError extends Error {\n override readonly name = 'JobTypeNotFoundError';\n constructor(public readonly jobType: string) {\n super(`No job definition registered for type '${jobType}'.`);\n }\n}\n\n/**\n * Thrown by `start` when `collision_mode === 'reject'` and a non-terminal\n * run with the same `concurrency_key` already exists. Carries the incumbent\n * so callers can surface its id or subscribe to its completion event.\n */\nexport class JobCollisionError extends Error {\n override readonly name = 'JobCollisionError';\n constructor(\n public readonly jobType: string,\n public readonly concurrencyKey: string,\n public readonly incumbent: JobRun,\n ) {\n super(\n `Job type '${jobType}' has an in-flight run with concurrency_key ` +\n `'${concurrencyKey}' (incumbent ${incumbent.id}); collision_mode=reject.`,\n );\n }\n}\n\n/**\n * `replay` was called on a run that is not in a replayable terminal state\n * (i.e. still `pending` / `running` / `waiting`). Replay always spawns\n * fresh execution and therefore requires the source run to be settled.\n */\nexport class JobNotReplayableError extends Error {\n override readonly name = 'JobNotReplayableError';\n constructor(\n public readonly runId: string,\n public readonly currentStatus: string,\n ) {\n super(\n `Run ${runId} is not replayable from status '${currentStatus}'. ` +\n `Only 'completed', 'failed', 'timed_out', and 'canceled' are eligible.`,\n );\n }\n}\n\n/**\n * A `concurrency_key_template` or `dedupe_key_template` referenced a field\n * that is not present on the input payload. Caught at `start` time so the\n * caller sees the misconfiguration synchronously rather than at claim time.\n */\nexport class JobTemplateFieldMissingError extends Error {\n override readonly name = 'JobTemplateFieldMissingError';\n constructor(\n public readonly template: string,\n public readonly field: string,\n ) {\n super(\n `Template '${template}' references input field '${field}' which is ` +\n `missing or undefined on the payload.`,\n );\n }\n}\n\n/**\n * Thrown by the four multi-tenant-aware service-layer backends (JOB-8)\n * when `JobsDomainModule` was configured with `multiTenant: true` but the\n * caller did not pass a `tenantId` in the relevant options object.\n *\n * **Strict enforcement rationale (resolved 2026-04-18).** Cross-tenant data\n * leakage is the worst class of bug a multi-tenant system can ship; surfacing\n * the misuse loudly at the call site (rather than silently defaulting to\n * `null` or to the \"last tenant seen\") prevents both accidental global\n * writes and sneaky reads that return a union of tenants.\n *\n * - `undefined` `tenantId` → throw this error.\n * - Explicit `null` `tenantId` → passes; opts the call into cross-tenant\n * background work (e.g. a nightly housekeeping job that must scan all\n * tenants). The row is persisted with `tenant_id = NULL`.\n */\nexport class MissingTenantIdError extends Error {\n override readonly name = 'MissingTenantIdError';\n constructor(public readonly method: string) {\n super(\n `MissingTenantIdError: JobsDomainModule was configured with ` +\n `multiTenant=true but ${method} was called without tenantId ` +\n `(undefined). Pass an explicit tenantId, or pass null for ` +\n `cross-tenant work.`,\n );\n }\n}\n\n/**\n * Thrown by `JobWorkerModule.onModuleInit` (Drizzle backend only) when the\n * `job` table contains type rows for which no `@JobHandler` is registered\n * in the running process. Surfaces every orphaned type at once so a single\n * boot tells the operator everything to clean up.\n *\n * Skipped entirely in memory mode (Q4 resolution 2026-04-19) — the memory\n * backend has no DB rows to validate; `MemoryJobOrchestrator.start()`\n * throws `JobTypeNotFoundError` synchronously for unknown types instead.\n */\nexport class BootValidationError extends Error {\n override readonly name = 'BootValidationError';\n constructor(public readonly missingHandlers: string[]) {\n super(\n `BootValidationError: ${missingHandlers.length} orphaned job type(s) ` +\n `in 'job' table with no matching @JobHandler in the running process: ` +\n `[${missingHandlers.join(', ')}]. Either register the handler(s) or ` +\n `remove the rows.`,\n );\n }\n}\n\n/**\n * Thrown by `JobWorkerModule.onModuleInit` when one or more `@JobHandler`\n * classes target a `reserved: true` pool from the resolved pool config\n * (the three `events_*` pools are reserved for the events subsystem\n * outbox drain). Listing every offender on a single boot avoids the\n * fix-one-restart-fix-next loop.\n */\nexport class ReservedPoolViolationError extends Error {\n override readonly name = 'ReservedPoolViolationError';\n constructor(\n public readonly offenders: ReadonlyArray<{\n handlerClass: string;\n pool: string;\n }>,\n ) {\n super(\n `ReservedPoolViolationError: ${offenders.length} @JobHandler(s) target ` +\n `reserved pools — reserved pools are framework-only:\\n` +\n offenders\n .map((o) => ` - ${o.handlerClass} → pool='${o.pool}'`)\n .join('\\n'),\n );\n }\n}\n","/**\n * DrizzleJobRunService — scope-oriented reads and bulk operations against\n * `job_run` (ADR-022, JOB-3).\n *\n * Separate from the orchestrator because the access pattern differs: this\n * service scans by `(scope_entity_type, scope_entity_id)` via\n * `idx_job_run_scope`, whereas orchestrator mutates individual runs by id.\n */\nimport { Inject, Injectable } from '@nestjs/common';\nimport { and, asc, desc, eq, gte, inArray, isNull, lt, or, sql } from 'drizzle-orm';\nimport type { DrizzleClient } from '../../types/drizzle';\nimport { DRIZZLE } from '../../constants/tokens';\nimport { jobRuns, type JobRunRow } from './job-orchestration.schema';\nimport type { JobRun } from './job-orchestrator.protocol';\nimport type {\n IJobRunService,\n ListForScopeOptions,\n CancelForScopeOptions,\n RescheduleForScopeOptions,\n PoolStatusCount,\n JobRunFailure,\n ListJobRunsQuery,\n JobRunPage,\n JobRunSummary,\n} from './job-run-service.protocol';\nimport {\n clampLimit,\n decodeKeysetCursor,\n encodeKeysetCursor,\n toJobRunSummary,\n} from './job-run-keyset-cursor';\nimport type { IJobOrchestrator } from './job-orchestrator.protocol';\nimport { JOB_ORCHESTRATOR, JOBS_MULTI_TENANT } from './jobs-domain.tokens';\nimport { MissingTenantIdError } from './jobs-errors';\n\nconst NON_TERMINAL_STATUSES: JobRunRow['status'][] = [\n 'pending',\n 'running',\n 'waiting',\n];\n\n@Injectable()\nexport class DrizzleJobRunService implements IJobRunService {\n constructor(\n @Inject(DRIZZLE) private readonly db: DrizzleClient,\n @Inject(JOB_ORCHESTRATOR) private readonly orchestrator: IJobOrchestrator,\n @Inject(JOBS_MULTI_TENANT) private readonly multiTenant: boolean,\n ) {}\n\n /**\n * JOB-8 — produce the tenant WHERE fragment (or `null` to opt out).\n * Returns `null` when multi-tenancy is off (caller skips the predicate).\n * Throws `MissingTenantIdError` when on + `undefined`.\n * When on + explicit `null`, filters `tenant_id IS NULL`.\n */\n private tenantCondition(\n method: string,\n tenantId: string | null | undefined,\n ) {\n if (!this.multiTenant) return null;\n if (tenantId === undefined) throw new MissingTenantIdError(method);\n return tenantId === null\n ? isNull(jobRuns.tenantId)\n : eq(jobRuns.tenantId, tenantId);\n }\n\n async listForScope(\n entityType: string,\n entityId: string,\n opts: ListForScopeOptions = {},\n ): Promise<JobRun[]> {\n const conditions = [\n eq(jobRuns.scopeEntityType, entityType),\n eq(jobRuns.scopeEntityId, entityId),\n ];\n const tenantCond = this.tenantCondition('listForScope', opts.tenantId);\n if (tenantCond) conditions.push(tenantCond);\n if (opts.status) {\n if (Array.isArray(opts.status)) {\n conditions.push(inArray(jobRuns.status, opts.status));\n } else {\n conditions.push(eq(jobRuns.status, opts.status));\n }\n }\n if (opts.jobType) {\n conditions.push(eq(jobRuns.jobType, opts.jobType));\n }\n\n const orderCol = (() => {\n switch (opts.orderBy) {\n case 'created_at asc':\n return asc(jobRuns.createdAt);\n case 'run_at desc':\n return desc(jobRuns.runAt);\n case 'run_at asc':\n return asc(jobRuns.runAt);\n case 'created_at desc':\n default:\n return desc(jobRuns.createdAt);\n }\n })();\n\n let q = this.db\n .select()\n .from(jobRuns)\n .where(and(...conditions))\n .orderBy(orderCol)\n .$dynamic();\n\n if (typeof opts.limit === 'number') {\n q = q.limit(opts.limit);\n }\n if (typeof opts.offset === 'number') {\n q = q.offset(opts.offset);\n }\n\n const rows = await q;\n return rows as JobRun[];\n }\n\n async cancelForScope(\n entityType: string,\n entityId: string,\n opts: CancelForScopeOptions = {},\n ): Promise<void> {\n const tenantCond = this.tenantCondition('cancelForScope', opts.tenantId);\n const conditions = [\n eq(jobRuns.scopeEntityType, entityType),\n eq(jobRuns.scopeEntityId, entityId),\n inArray(jobRuns.status, NON_TERMINAL_STATUSES),\n ];\n if (tenantCond) conditions.push(tenantCond);\n\n const rows = await this.db\n .select({ id: jobRuns.id })\n .from(jobRuns)\n .where(and(...conditions));\n\n for (const { id } of rows) {\n // Propagate the tenant gate into cascade-cancel. The scope query has\n // already narrowed to this tenant; passing `tenantId` through keeps\n // the orchestrator's per-row guard consistent under multi-tenant mode.\n await this.orchestrator.cancel(id, {\n cascade: true,\n tenantId: opts.tenantId,\n });\n }\n }\n\n async rescheduleForScope(\n entityType: string,\n entityId: string,\n newRunAt: Date,\n opts: RescheduleForScopeOptions = {},\n ): Promise<void> {\n const tenantCond = this.tenantCondition('rescheduleForScope', opts.tenantId);\n const conditions = [\n eq(jobRuns.scopeEntityType, entityType),\n eq(jobRuns.scopeEntityId, entityId),\n eq(jobRuns.status, 'pending'),\n ];\n if (tenantCond) conditions.push(tenantCond);\n\n await this.db\n .update(jobRuns)\n .set({ runAt: newRunAt, updatedAt: new Date() })\n .where(and(...conditions));\n }\n\n async countByPoolAndStatus(\n tenantId?: string | null,\n ): Promise<PoolStatusCount[]> {\n const tenantCond = this.tenantCondition('countByPoolAndStatus', tenantId);\n const rows = await this.db\n .select({\n pool: jobRuns.pool,\n status: jobRuns.status,\n count: sql<number>`count(*)::int`.as('count'),\n })\n .from(jobRuns)\n .where(tenantCond ?? undefined)\n .groupBy(jobRuns.pool, jobRuns.status);\n\n return rows.map((r) => ({\n pool: r.pool,\n status: r.status,\n count: Number(r.count),\n }));\n }\n\n async listRecentFailed(\n limit: number,\n tenantId?: string | null,\n ): Promise<JobRunFailure[]> {\n const conditions = [eq(jobRuns.status, 'failed' as const)];\n const tenantCond = this.tenantCondition('listRecentFailed', tenantId);\n if (tenantCond) conditions.push(tenantCond);\n\n const rows = await this.db\n .select()\n .from(jobRuns)\n .where(and(...conditions))\n .orderBy(desc(jobRuns.finishedAt), desc(jobRuns.updatedAt))\n .limit(limit);\n\n return rows.map((r) => ({\n runId: r.id,\n jobType: r.jobType,\n pool: r.pool,\n scopeEntityType: r.scopeEntityType,\n scopeEntityId: r.scopeEntityId,\n tenantId: r.tenantId,\n attempts: r.attempts,\n errorMessage: r.error?.message ?? null,\n failedAt: r.finishedAt ?? r.updatedAt,\n createdAt: r.createdAt,\n }));\n }\n\n async listJobRuns(query: ListJobRunsQuery = {}): Promise<JobRunPage> {\n const limit = clampLimit(query.limit);\n const conditions = [];\n\n const tenantCond = this.tenantCondition('listJobRuns', query.tenantId);\n if (tenantCond) conditions.push(tenantCond);\n if (query.poolId) conditions.push(eq(jobRuns.pool, query.poolId));\n if (query.rootRunId) conditions.push(eq(jobRuns.rootRunId, query.rootRunId));\n if (query.status) conditions.push(eq(jobRuns.status, query.status));\n if (query.since) conditions.push(gte(jobRuns.createdAt, query.since));\n\n // Keyset seek: WHERE (created_at, id) < (cursorCreatedAt, cursorId),\n // expanded into a SARGable OR so the same `created_at` index is used.\n if (query.cursor) {\n const keyset = decodeKeysetCursor(query.cursor);\n if (keyset) {\n conditions.push(\n or(\n lt(jobRuns.createdAt, keyset.createdAt),\n and(\n eq(jobRuns.createdAt, keyset.createdAt),\n lt(jobRuns.id, keyset.id),\n ),\n )!,\n );\n }\n }\n\n // Fetch one extra row to determine whether a next page exists without a\n // separate COUNT.\n const rows = await this.db\n .select()\n .from(jobRuns)\n .where(conditions.length > 0 ? and(...conditions) : undefined)\n .orderBy(desc(jobRuns.createdAt), desc(jobRuns.id))\n .limit(limit + 1);\n\n const hasMore = rows.length > limit;\n const page = hasMore ? rows.slice(0, limit) : rows;\n const items = page.map(toJobRunSummary);\n const last = page[page.length - 1];\n const nextCursor =\n hasMore && last\n ? encodeKeysetCursor({ createdAt: last.createdAt, id: last.id })\n : null;\n\n return { items, nextCursor };\n }\n\n /**\n * Internal helper used by cascade paths (not on the public protocol).\n * Exposed as a public method on the concrete class so infrastructure\n * code (cascade tests, debug tools) can call it without a cast.\n */\n async findByRootRunId(rootRunId: string): Promise<JobRun[]> {\n const rows = await this.db\n .select()\n .from(jobRuns)\n .where(eq(jobRuns.rootRunId, rootRunId));\n return rows as JobRun[];\n }\n}\n","/**\n * Keyset (seek) cursor codec for `IJobRunService.listJobRuns` (OBS-LIST-1).\n *\n * The list is ordered `created_at DESC, id DESC`. The cursor encodes the\n * `(createdAt, id)` of the last row on the previous page so the next page\n * can seek with `WHERE (created_at, id) < (cursorCreatedAt, cursorId)`\n * rather than an `OFFSET`. Keyset pagination stays O(log n) on deep pages\n * and is stable as new rows arrive at the head.\n *\n * The cursor is opaque to consumers: a base64url-encoded JSON tuple. Shape\n * is an implementation detail — never parse it outside this module.\n *\n * Also hosts `toJobRunSummary`, the single `JobRunRow → JobRunSummary`\n * projection shared by both backends so the narrow shape stays in sync.\n */\nimport type { JobRunRow } from './job-orchestration.schema';\nimport type { JobRunSummary } from './job-run-service.protocol';\n\nexport interface JobRunKeyset {\n /** `created_at` of the last row on the previous page. */\n createdAt: Date;\n /** `id` (UUID) tie-break of the last row on the previous page. */\n id: string;\n}\n\n/** Default page size when `limit` is omitted. */\nexport const DEFAULT_LIST_LIMIT = 50;\n/** Hard upper bound on page size to keep a single read bounded. */\nexport const MAX_LIST_LIMIT = 200;\n\n/** Clamp a caller-supplied `limit` into `[1, MAX_LIST_LIMIT]`. */\nexport function clampLimit(limit: number | undefined): number {\n if (typeof limit !== 'number' || !Number.isFinite(limit)) {\n return DEFAULT_LIST_LIMIT;\n }\n const floored = Math.floor(limit);\n if (floored < 1) return 1;\n if (floored > MAX_LIST_LIMIT) return MAX_LIST_LIMIT;\n return floored;\n}\n\nexport function encodeKeysetCursor(keyset: JobRunKeyset): string {\n const tuple = [keyset.createdAt.toISOString(), keyset.id];\n return Buffer.from(JSON.stringify(tuple), 'utf8').toString('base64url');\n}\n\n/**\n * Decode an opaque cursor back into its `(createdAt, id)` keyset. Returns\n * `null` for a malformed cursor so callers can treat garbage input as\n * \"start from the beginning\" rather than throwing on user-supplied data.\n */\nexport function decodeKeysetCursor(cursor: string): JobRunKeyset | null {\n try {\n const json = Buffer.from(cursor, 'base64url').toString('utf8');\n const parsed = JSON.parse(json) as unknown;\n if (!Array.isArray(parsed) || parsed.length !== 2) return null;\n const [iso, id] = parsed;\n if (typeof iso !== 'string' || typeof id !== 'string') return null;\n const createdAt = new Date(iso);\n if (Number.isNaN(createdAt.getTime())) return null;\n return { createdAt, id };\n } catch {\n return null;\n }\n}\n\n/**\n * Project a raw `job_run` row into the narrow `JobRunSummary` shape exposed\n * by `listJobRuns`. `errorMessage` is pulled from the jsonb `error.message`.\n */\nexport function toJobRunSummary(r: JobRunRow): JobRunSummary {\n return {\n runId: r.id,\n rootRunId: r.rootRunId,\n parentRunId: r.parentRunId,\n triggerSource: r.triggerSource,\n triggerRef: r.triggerRef,\n jobType: r.jobType,\n pool: r.pool,\n status: r.status,\n scopeEntityType: r.scopeEntityType,\n scopeEntityId: r.scopeEntityId,\n tenantId: r.tenantId,\n attempts: r.attempts,\n errorMessage: r.error?.message ?? null,\n runAt: r.runAt,\n startedAt: r.startedAt,\n finishedAt: r.finishedAt,\n createdAt: r.createdAt,\n };\n}\n","/**\n * DrizzleJobStepService — upsert + lookup on `job_step` for replay-safe\n * memoization (ADR-022, JOB-3).\n *\n * `recordStep` upserts on the `(job_run_id, step_id)` unique index — each\n * step row is written as `running` first, then transitioned to a terminal\n * state (`completed` / `failed` / `skipped`). `findStep` is the hot path\n * that `ctx.step()` consults on every invocation; null on miss.\n */\nimport { Inject, Injectable } from '@nestjs/common';\nimport { and, eq } from 'drizzle-orm';\nimport type { DrizzleClient } from '../../types/drizzle';\nimport { DRIZZLE } from '../../constants/tokens';\nimport { jobSteps, type JobStepRow } from './job-orchestration.schema';\nimport type {\n IJobStepService,\n JobStep,\n RecordStepInput,\n} from './job-step-service.protocol';\n\n@Injectable()\nexport class DrizzleJobStepService implements IJobStepService {\n constructor(@Inject(DRIZZLE) private readonly db: DrizzleClient) {}\n\n async recordStep(input: RecordStepInput): Promise<JobStep> {\n const values = {\n jobRunId: input.jobRunId,\n stepId: input.stepId,\n kind: input.kind,\n seq: input.seq,\n status: input.status,\n input: (input.input ?? null) as Record<string, unknown> | null,\n output: (input.output ?? null) as Record<string, unknown> | null,\n error: input.error ?? null,\n attempts: input.attempts ?? 0,\n startedAt: input.startedAt ?? null,\n finishedAt: input.finishedAt ?? null,\n };\n\n const [row] = await this.db\n .insert(jobSteps)\n .values(values)\n .onConflictDoUpdate({\n target: [jobSteps.jobRunId, jobSteps.stepId],\n set: {\n status: values.status,\n output: values.output,\n error: values.error,\n finishedAt: values.finishedAt,\n attempts: values.attempts,\n },\n })\n .returning();\n\n return row as JobStep;\n }\n\n async findStep(runId: string, stepId: string): Promise<JobStep | null> {\n const [row] = await this.db\n .select()\n .from(jobSteps)\n .where(and(eq(jobSteps.jobRunId, runId), eq(jobSteps.stepId, stepId)))\n .limit(1);\n return ((row as JobStepRow | undefined) ?? null) as JobStep | null;\n }\n}\n","/**\n * Pool config loader for the job orchestration domain (ADR-022, JOB-5).\n *\n * Reads `codegen.config.yaml: jobs.pools` from `process.cwd()` (or an\n * explicit `configPath` for tests), merges user-defined pools onto the five\n * framework defaults, and returns the resolved `Map<string, PoolDefinition>`\n * consumed by `JobWorkerModule.onModuleInit` and `JobsDomainModule`'s\n * config-validator surface.\n *\n * Invariants:\n * - User cannot flip `reserved: true` on a framework pool — silently\n * preserved. The three `events_*` pools are reserved infrastructure\n * for the events outbox drain.\n * - User-defined pools cannot set `reserved: true` — `reserved` is\n * framework-only metadata.\n * - Missing `codegen.config.yaml` is not an error; loader returns the\n * framework defaults verbatim.\n *\n * Result is cached at module scope after first call so repeated reads (e.g.\n * a worker module + a one-off scaffold validator in the same process) hit\n * the same parse. Tests that pass `configPath` skip the cache and isolate.\n */\nimport { existsSync, readFileSync } from 'node:fs';\nimport { resolve } from 'node:path';\nimport { parse as parseYaml } from 'yaml';\n\nexport interface PoolDefinition {\n /** Routing identifier — reused as the per-pool worker queue name. */\n queue: string;\n /** Max parallel in-flight `processRun` calls for this pool's worker. */\n concurrency: number;\n /** `true` ⇒ user `@JobHandler` may not target it. Framework-only. */\n reserved: boolean;\n /** Free-text annotation surfaced in admin UIs / logs. */\n description?: string;\n}\n\nexport type PoolConfig = Map<string, PoolDefinition>;\n\n/**\n * Five framework defaults. Three reserved `events_*` pools drain the\n * `IEventBus` outbox (one per `DomainEvent.direction`); `interactive` and\n * `batch` are user-default pools (`batch` is the `@JobHandler` default\n * when no `pool` is specified).\n */\nexport const FRAMEWORK_POOLS: Readonly<Record<string, PoolDefinition>> = Object.freeze({\n events_inbound: Object.freeze({\n queue: 'jobs-events-inbound',\n concurrency: 20,\n reserved: true,\n description: 'Inbound events drain (events subsystem outbox).',\n }),\n events_change: Object.freeze({\n queue: 'jobs-events-change',\n concurrency: 30,\n reserved: true,\n description: 'Change events drain (events subsystem outbox).',\n }),\n events_outbound: Object.freeze({\n queue: 'jobs-events-outbound',\n concurrency: 10,\n reserved: true,\n description: 'Outbound events drain (events subsystem outbox).',\n }),\n interactive: Object.freeze({\n queue: 'jobs-interactive',\n concurrency: 20,\n reserved: false,\n description: 'User-facing latency-sensitive jobs.',\n }),\n batch: Object.freeze({\n queue: 'jobs-batch',\n concurrency: 5,\n reserved: false,\n description: 'Default pool for background jobs.',\n }),\n});\n\n/** Names of the framework reserved pools. Cheap inline lookup for the worker. */\nexport const RESERVED_POOL_NAMES: ReadonlySet<string> = new Set(\n Object.entries(FRAMEWORK_POOLS)\n .filter(([, def]) => def.reserved)\n .map(([name]) => name),\n);\n\n/**\n * Cache by absolute config path. The `cwd` default is normalised before\n * lookup so two callers passing the same path share the cache; explicit\n * test-only paths cache separately.\n */\nconst cache = new Map<string, PoolConfig>();\n\n/**\n * Reset the loader cache. Test-only — not exported from the package\n * `index.ts`. Useful for tests that mutate `process.cwd()` between cases.\n */\nexport function _resetPoolConfigCacheForTests(): void {\n cache.clear();\n}\n\n/**\n * Resolve the merged pool config.\n *\n * @param configPath optional absolute or cwd-relative path; defaults to\n * `${process.cwd()}/codegen.config.yaml`.\n */\nexport function loadPoolConfig(configPath?: string): PoolConfig {\n const resolved = resolve(configPath ?? `${process.cwd()}/codegen.config.yaml`);\n const cached = cache.get(resolved);\n if (cached) return cached;\n\n const merged = new Map<string, PoolDefinition>();\n // Seed with framework defaults first — they always take precedence on\n // `reserved` and provide defaults for `queue` / `concurrency` if user\n // overrides only some fields.\n for (const [name, def] of Object.entries(FRAMEWORK_POOLS)) {\n merged.set(name, { ...def });\n }\n\n if (!existsSync(resolved)) {\n cache.set(resolved, merged);\n return merged;\n }\n\n let raw: unknown;\n try {\n raw = parseYaml(readFileSync(resolved, 'utf8'));\n } catch (err) {\n throw new Error(\n `pool-config.loader: failed to parse YAML at ${resolved}: ${(err as Error).message}`,\n );\n }\n\n const userPools = extractUserPools(raw);\n for (const [name, userDef] of Object.entries(userPools)) {\n const existing = merged.get(name);\n if (existing) {\n // Framework pool — user may tweak concurrency + description but\n // cannot flip `reserved`. `queue` is frozen too (reserved framework\n // pools' queue identifiers are part of the cross-subsystem contract\n // with the events outbox drain).\n const next: PoolDefinition = {\n queue: existing.queue,\n concurrency:\n typeof userDef.concurrency === 'number'\n ? userDef.concurrency\n : existing.concurrency,\n reserved: existing.reserved,\n description: userDef.description ?? existing.description,\n };\n merged.set(name, next);\n continue;\n }\n // User-defined pool. Validate required fields; reject reserved.\n if (typeof userDef.queue !== 'string' || userDef.queue.length === 0) {\n throw new Error(\n `pool-config.loader: pool '${name}' must declare a non-empty 'queue'.`,\n );\n }\n if (typeof userDef.concurrency !== 'number' || userDef.concurrency <= 0) {\n throw new Error(\n `pool-config.loader: pool '${name}' must declare a positive 'concurrency'.`,\n );\n }\n if (userDef.reserved === true) {\n throw new Error(\n `pool-config.loader: user-defined pool '${name}' cannot set ` +\n `'reserved: true' — reserved is framework-only.`,\n );\n }\n merged.set(name, {\n queue: userDef.queue,\n concurrency: userDef.concurrency,\n reserved: false,\n description: userDef.description,\n });\n }\n\n cache.set(resolved, merged);\n return merged;\n}\n\n/**\n * Names of every non-reserved pool in the resolved config. The default\n * worker activation set when `JobWorkerModuleOptions.pools` is omitted —\n * the worker process never claims the reserved `events_*` pools by\n * default; those are bound by the events subsystem's outbox bridge.\n */\nexport function allNonReservedPoolNames(config: PoolConfig): string[] {\n const out: string[] = [];\n for (const [name, def] of config) {\n if (!def.reserved) out.push(name);\n }\n return out;\n}\n\n/**\n * Names of **every** pool in the resolved config, reserved `events_*` lanes\n * included. The activation set for a standalone worker booted with\n * `JobWorkerModule.forRoot({ allPools: true })` (BULLMQ-1 Phase 1) — the\n * single worker process drains both user pools and the bridge's reserved\n * pools so wrapper `job_run` rows are never stranded.\n */\nexport function allPoolNames(config: PoolConfig): string[] {\n return [...config.keys()];\n}\n\n// ─── internals ──────────────────────────────────────────────────────────────\n\ninterface UserPoolShape {\n queue?: string;\n concurrency?: number;\n reserved?: boolean;\n description?: string;\n}\n\nfunction extractUserPools(raw: unknown): Record<string, UserPoolShape> {\n if (!raw || typeof raw !== 'object') return {};\n const jobs = (raw as { jobs?: unknown }).jobs;\n if (!jobs || typeof jobs !== 'object') return {};\n const pools = (jobs as { pools?: unknown }).pools;\n if (!pools || typeof pools !== 'object') return {};\n const out: Record<string, UserPoolShape> = {};\n for (const [name, def] of Object.entries(pools as Record<string, unknown>)) {\n if (!def || typeof def !== 'object') continue;\n out[name] = def as UserPoolShape;\n }\n return out;\n}\n","/**\n * BullMQ backend configuration surface (BULLMQ-1, ADR-022 extension slot).\n *\n * The core `IJobOrchestrator` contract is backend-agnostic; everything in\n * this file is BullMQ-specific and lives behind the\n * `jobs.extensions.bullmq.*` config namespace (CLAUDE.md core/extension\n * protocol). The Drizzle backend never reads any of it.\n */\nimport { tokenKey } from '../token-key';\nimport { loadPoolConfig, type PoolConfig } from './pool-config.loader';\n\n/**\n * #6 — Structural mirror of BullMQ's `ConnectionOptions`. Declared locally\n * so this config file (which ships into EVERY jobs install, drizzle or\n * bullmq) does NOT need the `bullmq` peer dep resolved by the consumer's\n * tsc. The bullmq backend internally casts to the real `ConnectionOptions`\n * — that file is only vendored when `--backend bullmq` is selected\n * (see `backendFileFilter`).\n *\n * Accepts the `{ url }` shape this resolver emits, plus the host/port/\n * password/db form BullMQ also accepts, with an open index for any extra\n * ioredis options consumers may flow through.\n */\nexport type BullMqConnectionOptions = {\n url?: string;\n host?: string;\n port?: number;\n password?: string;\n db?: number;\n [key: string]: unknown;\n};\n\n/**\n * Typed shape of `codegen.config.yaml: jobs.extensions.bullmq`. Snake_case\n * because it mirrors the YAML the consumer authors.\n *\n * ```yaml\n * jobs:\n * backend: bullmq\n * extensions:\n * bullmq:\n * redis_url: redis://localhost:6379 # or env REDIS_URL\n * queue_prefix: myapp # optional namespace (ADR-022 OQ)\n * bull_board:\n * enabled: true\n * mount_path: /api/admin/queues\n * ```\n */\nexport interface BullMqExtensionsConfig {\n /**\n * Redis/Valkey connection URL. When omitted, the runtime resolves\n * `process.env.REDIS_URL`, then falls back to `redis://localhost:6379`.\n */\n redis_url?: string;\n /**\n * Optional queue-name prefix to avoid collisions when several codegen apps\n * share one Redis (ADR-022 §\"BullMQ queue naming collisions\"). Applied to\n * every pool queue alias.\n */\n queue_prefix?: string;\n /**\n * Bull Board dashboard — opt-in extension (not core). Mounting is the\n * consumer's responsibility (it needs the consumer's Express/Nest adapter +\n * admin auth); we only carry the config. See README + spec §Extensions.\n */\n bull_board?: {\n enabled: boolean;\n mount_path?: string;\n };\n}\n\n/**\n * The runtime form after `redis_url`/env resolution. This is what the\n * orchestrator + worker actually consume.\n */\nexport interface BullMqResolvedConfig {\n connection: BullMqConnectionOptions;\n queuePrefix?: string;\n bullBoard?: { enabled: boolean; mountPath: string };\n}\n\n// ADR-037: namespaced `Symbol.for(...)` (via `tokenKey()`) — matches by value\n// across runtime copies.\n/** DI token for the resolved BullMQ `ConnectionOptions` (ioredis-compatible). */\nexport const BULLMQ_CONNECTION = Symbol.for(tokenKey('jobs', 'bullmq-connection'));\n\n/** DI token for the full resolved BullMQ config (prefix + bull board). */\nexport const BULLMQ_RESOLVED_CONFIG = Symbol.for(tokenKey('jobs', 'bullmq-resolved-config'));\n\nconst DEFAULT_REDIS_URL = 'redis://localhost:6379';\nconst DEFAULT_BULL_BOARD_MOUNT = '/admin/queues';\n\n/**\n * Resolve the BullMQ runtime config from the extension block.\n *\n * Precedence for the connection URL:\n * 1. explicit `extensions.bullmq.redis_url`\n * 2. `process.env.REDIS_URL`\n * 3. `redis://localhost:6379`\n *\n * Returns a `{ url }` connection shape — BullMQ/ioredis accept a URL string\n * via the `{ url }` ConnectionOptions form.\n */\nexport function resolveBullMqConfig(\n ext: BullMqExtensionsConfig | undefined,\n): BullMqResolvedConfig {\n const url =\n ext?.redis_url ?? process.env.REDIS_URL ?? DEFAULT_REDIS_URL;\n\n const resolved: BullMqResolvedConfig = {\n connection: { url },\n queuePrefix: ext?.queue_prefix,\n };\n if (ext?.bull_board?.enabled) {\n resolved.bullBoard = {\n enabled: true,\n mountPath: ext.bull_board.mount_path ?? DEFAULT_BULL_BOARD_MOUNT,\n };\n }\n return resolved;\n}\n\n/**\n * Resolve the BullMQ queue name for a *logical pool name*. The orchestrator\n * and worker MUST agree on this mapping or jobs are enqueued onto a queue\n * nobody consumes. Both derive it identically:\n *\n * 1. Look up the pool's `queue` alias (e.g. `jobs-batch`) in the resolved\n * pool config — the same alias `JobWorkerModule.onModuleInit` logs and\n * that the BullMQ `Worker` binds to.\n * 2. Fall back to the logical pool name when the pool is unknown (defensive;\n * still a stable, colon-free identifier).\n * 3. Apply the optional `queue_prefix` namespace for multi-app Redis\n * sharing — `:` is fine in the *queue name* (it is only forbidden in the\n * `jobId`, hence the sha1 there).\n *\n * `poolConfig` defaults to the cached `loadPoolConfig()` so callers that only\n * hold the logical pool name (the orchestrator) don't need to thread the map.\n */\nexport function resolvePoolQueueName(\n pool: string,\n config: BullMqResolvedConfig | null | undefined,\n poolConfig: PoolConfig = loadPoolConfig(),\n): string {\n const alias = poolConfig.get(pool)?.queue ?? pool;\n const prefix = config?.queuePrefix;\n return prefix ? `${prefix}:${alias}` : alias;\n}\n","/**\n * JobWorker — backend-agnostic tick loop for the job orchestration domain\n * (ADR-022, JOB-3).\n *\n * One worker instance per active pool. On `onModuleInit` it starts two\n * intervals: the poll loop (claim → process → repeat) and the stale-claim\n * sweeper. On `onModuleDestroy` / SIGTERM it drains in-flight work and\n * releases still-`running` rows back to `pending` so a replacement worker\n * can resume with step memoization intact.\n *\n * The claim query is the beating heart: `SELECT … FOR UPDATE SKIP LOCKED`\n * inside a single transaction. Multiple worker processes share the table\n * without serialising on row locks.\n */\n// TODO(logging-subsystem): swap to ILogger once ADR-028 lands\nimport { Inject, Injectable, Logger, type OnModuleDestroy, type OnModuleInit } from '@nestjs/common';\nimport { ModuleRef } from '@nestjs/core';\nimport { and, asc, desc, eq, inArray, lt, lte, sql } from 'drizzle-orm';\nimport type { DrizzleClient } from '../../types/drizzle';\nimport { tokenKey } from '../token-key';\nimport { DRIZZLE } from '../../constants/tokens';\nimport { jobRuns, type JobRunRow } from './job-orchestration.schema';\nimport type { IJobOrchestrator, JobRun } from './job-orchestrator.protocol';\nimport type { IJobRunService } from './job-run-service.protocol';\nimport type { IJobStepService } from './job-step-service.protocol';\nimport {\n JOB_ORCHESTRATOR,\n JOB_RUN_SERVICE,\n JOB_STEP_SERVICE,\n} from './jobs-domain.tokens';\nimport {\n JOB_HANDLER_REGISTRY,\n JobHandlerBase,\n type JobContext,\n type JobHandlerMeta,\n type RetryPolicy,\n type SpawnChildOptions,\n type StepOptions,\n} from './job-handler.base';\n\n/**\n * Options accepted by `JobWorker`. JOB-5 threads these through module\n * `.forRoot()` config; supplied here as a plain DI-constructor argument\n * so the worker compiles standalone.\n */\nexport interface JobWorkerOptions {\n /** Pool name this worker claims from. Matches `job.pool`. */\n pool: string;\n /** Max concurrent in-flight `processRun` calls. */\n concurrency: number;\n /** Poll interval in ms. Default 1000. */\n pollIntervalMs?: number;\n /** Stale sweep interval in ms. Default 60_000. */\n staleSweeperIntervalMs?: number;\n /**\n * Threshold beyond which a `running` row is presumed stranded by a\n * crashed worker. Default 5 min. Must be >= 2× max handler duration.\n */\n staleThresholdMs?: number;\n /** Max ms to wait for in-flight drain on SIGTERM. Default 30_000. */\n shutdownTimeoutMs?: number;\n}\n\n// ADR-037: namespaced `Symbol.for(...)` (via `tokenKey()`) — matches by value\n// across runtime copies.\nexport const JOB_WORKER_OPTIONS = Symbol.for(tokenKey('jobs', 'worker-options'));\n\nconst DEFAULT_POLL_INTERVAL_MS = 1_000;\nconst DEFAULT_STALE_SWEEPER_INTERVAL_MS = 60_000;\nconst DEFAULT_STALE_THRESHOLD_MS = 5 * 60_000;\nconst DEFAULT_SHUTDOWN_TIMEOUT_MS = 30_000;\n\nconst TERMINAL_STATUSES: JobRunRow['status'][] = [\n 'completed',\n 'failed',\n 'timed_out',\n 'canceled',\n];\n\n// ─── Pure helpers (exported for unit tests) ────────────────────────────────\n\n/**\n * Backoff delay in ms for the Nth attempt (1-indexed). Supports both\n * policy modes. Exponential is capped at `Number.MAX_SAFE_INTEGER` so\n * pathological attempt counts don't overflow.\n */\nexport function computeBackoff(policy: RetryPolicy, attempts: number): number {\n const base = Math.max(policy.baseMs, 0);\n if (policy.backoff === 'fixed') {\n return base;\n }\n // exponential: baseMs * 2^(attempts-1)\n const exponent = Math.max(attempts - 1, 0);\n if (exponent >= 53) return Number.MAX_SAFE_INTEGER; // 2^53 overflow guard\n const raw = base * Math.pow(2, exponent);\n if (!Number.isFinite(raw) || raw >= Number.MAX_SAFE_INTEGER) {\n return Number.MAX_SAFE_INTEGER;\n }\n return raw;\n}\n\n/**\n * Decide whether an error should be retried under the given policy.\n * Matches `nonRetryableErrors` by `.name` OR `.code`. Returns\n * - `'retry'` if attempts remain and the error isn't blacklisted,\n * - `'fail'` otherwise (terminal failure).\n */\nexport function classifyError(\n err: unknown,\n policy: RetryPolicy | undefined,\n currentAttempts: number,\n): 'retry' | 'fail' {\n if (!policy) return 'fail';\n const errObj = err as { name?: string; code?: string } | undefined;\n const name = errObj?.name;\n const code = errObj?.code;\n const nonRetryable = policy.nonRetryableErrors ?? [];\n if (nonRetryable.some((n) => n === name || n === code)) return 'fail';\n if (currentAttempts + 1 >= policy.attempts) return 'fail';\n return 'retry';\n}\n\n/**\n * Build the raw claim-candidate select. Exported so tests can inspect\n * `.toSQL()` without spinning up the full worker. Matches JOB-3 §4 and\n * ADR-022 \"Claim query (Drizzle backend)\".\n */\nexport function buildClaimQuery(db: DrizzleClient, pool: string) {\n return db\n .select({ id: jobRuns.id })\n .from(jobRuns)\n .where(\n and(\n eq(jobRuns.status, 'pending'),\n eq(jobRuns.pool, pool),\n lte(jobRuns.runAt, new Date()),\n ),\n )\n .orderBy(desc(jobRuns.priority), asc(jobRuns.runAt))\n .limit(1)\n .for('update', { skipLocked: true });\n}\n\n/**\n * Build the stale-claim sweep candidate select. `FOR UPDATE SKIP LOCKED`\n * per OQ-2 resolution (2026-04-19): per-worker sweeper, safe without\n * leader election because the update is self-gating.\n */\nexport function buildStaleSweepQuery(\n db: DrizzleClient,\n staleThresholdMs: number,\n) {\n const threshold = new Date(Date.now() - staleThresholdMs);\n return db\n .select({ id: jobRuns.id })\n .from(jobRuns)\n .where(\n and(\n eq(jobRuns.status, 'running'),\n lt(jobRuns.claimedAt, threshold),\n ),\n )\n .for('update', { skipLocked: true });\n}\n\n// ─── Error serialisation ───────────────────────────────────────────────────\n\nfunction serialiseError(err: unknown, attempt: number, retryable: boolean) {\n const e = err as { message?: string; stack?: string; code?: string } | undefined;\n return {\n message: (e?.message ?? String(err)) as string,\n stack: e?.stack,\n retryable,\n attempt,\n };\n}\n\n// ─── JobWorker ─────────────────────────────────────────────────────────────\n\n@Injectable()\nexport class JobWorker implements OnModuleInit, OnModuleDestroy {\n private readonly logger = new Logger(JobWorker.name);\n private shuttingDown = false;\n private readonly inFlight = new Set<Promise<void>>();\n private pollTimer: ReturnType<typeof setInterval> | null = null;\n private sweeperTimer: ReturnType<typeof setInterval> | null = null;\n private sigtermHandled = false;\n private readonly sigtermHandler: () => void;\n\n private readonly pollIntervalMs: number;\n private readonly staleSweeperIntervalMs: number;\n private readonly staleThresholdMs: number;\n private readonly shutdownTimeoutMs: number;\n\n constructor(\n @Inject(DRIZZLE) private readonly db: DrizzleClient,\n @Inject(JOB_ORCHESTRATOR) private readonly orchestrator: IJobOrchestrator,\n @Inject(JOB_RUN_SERVICE) private readonly runService: IJobRunService,\n @Inject(JOB_STEP_SERVICE) private readonly stepService: IJobStepService,\n @Inject(JOB_WORKER_OPTIONS) private readonly options: JobWorkerOptions,\n private readonly moduleRef: ModuleRef,\n ) {\n this.pollIntervalMs = options.pollIntervalMs ?? DEFAULT_POLL_INTERVAL_MS;\n this.staleSweeperIntervalMs =\n options.staleSweeperIntervalMs ?? DEFAULT_STALE_SWEEPER_INTERVAL_MS;\n this.staleThresholdMs = options.staleThresholdMs ?? DEFAULT_STALE_THRESHOLD_MS;\n this.shutdownTimeoutMs =\n options.shutdownTimeoutMs ?? DEFAULT_SHUTDOWN_TIMEOUT_MS;\n\n this.sigtermHandler = () => {\n if (this.sigtermHandled) return;\n this.sigtermHandled = true;\n void this.onModuleDestroy();\n };\n void this.runService; // reserved for future scope-aware cancellation paths\n }\n\n // ============================================================================\n // Lifecycle\n // ============================================================================\n\n onModuleInit(): void {\n this.pollTimer = setInterval(() => {\n void this.pollAndProcess();\n }, this.pollIntervalMs);\n this.sweeperTimer = setInterval(() => {\n void this.sweepStaleClaims();\n }, this.staleSweeperIntervalMs);\n process.on('SIGTERM', this.sigtermHandler);\n }\n\n async onModuleDestroy(): Promise<void> {\n if (this.shuttingDown) {\n // Still drain, but don't tear intervals down twice.\n await this.drainInFlight();\n return;\n }\n this.shuttingDown = true;\n if (this.pollTimer) {\n clearInterval(this.pollTimer);\n this.pollTimer = null;\n }\n if (this.sweeperTimer) {\n clearInterval(this.sweeperTimer);\n this.sweeperTimer = null;\n }\n process.removeListener('SIGTERM', this.sigtermHandler);\n\n await this.drainInFlight();\n\n // Any rows still `running` past timeout → release back to pending.\n try {\n await this.db\n .update(jobRuns)\n .set({ status: 'pending', claimedAt: null, startedAt: null })\n .where(\n and(eq(jobRuns.status, 'running'), eq(jobRuns.pool, this.options.pool)),\n );\n } catch (err) {\n this.logger.error(`shutdown reset failed: ${(err as Error).message}`);\n }\n }\n\n private async drainInFlight(): Promise<void> {\n if (this.inFlight.size === 0) return;\n const timeout = new Promise<void>((resolve) =>\n setTimeout(resolve, this.shutdownTimeoutMs),\n );\n await Promise.race([\n Promise.allSettled([...this.inFlight]).then(() => undefined),\n timeout,\n ]);\n }\n\n // ============================================================================\n // Poll loop\n // ============================================================================\n\n async pollAndProcess(): Promise<void> {\n if (this.shuttingDown) return;\n if (this.inFlight.size >= this.options.concurrency) return;\n\n let claimed: JobRunRow | null;\n try {\n claimed = await this.claimNext(this.options.pool);\n } catch (err) {\n this.logger.error(`claimNext failed: ${(err as Error).message}`);\n return;\n }\n if (!claimed) return;\n\n const run = claimed;\n const promise = this.processRun(run).catch((err) => {\n this.logger.error(\n `processRun(${run.id}) unhandled: ${(err as Error).message}`,\n );\n });\n this.inFlight.add(promise);\n promise.finally(() => {\n this.inFlight.delete(promise);\n });\n }\n\n /**\n * Claim the next runnable row from the pool. Transaction ensures the\n * select-candidate + update-to-running pair is atomic; FOR UPDATE SKIP\n * LOCKED lets multiple workers share the table without serialising.\n */\n async claimNext(pool: string): Promise<JobRunRow | null> {\n return this.db.transaction(async (tx) => {\n const candidates = await tx\n .select({ id: jobRuns.id })\n .from(jobRuns)\n .where(\n and(\n eq(jobRuns.status, 'pending'),\n eq(jobRuns.pool, pool),\n lte(jobRuns.runAt, new Date()),\n ),\n )\n .orderBy(desc(jobRuns.priority), asc(jobRuns.runAt))\n .limit(1)\n .for('update', { skipLocked: true });\n const candidate = candidates[0];\n if (!candidate) return null;\n\n const [claimed] = await tx\n .update(jobRuns)\n .set({\n status: 'running',\n claimedAt: new Date(),\n startedAt: new Date(),\n updatedAt: new Date(),\n })\n .where(eq(jobRuns.id, candidate.id))\n .returning();\n return (claimed ?? null) as JobRunRow | null;\n });\n }\n\n // ============================================================================\n // Stale claim sweeper\n // ============================================================================\n\n /**\n * Release rows whose `claimed_at` is older than the threshold. Safe to\n * run concurrently across workers — the two-phase tx (select-for-update\n * then update) guarantees each stranded row is only reset once.\n */\n async sweepStaleClaims(): Promise<void> {\n if (this.shuttingDown) return;\n try {\n await this.db.transaction(async (tx) => {\n const threshold = new Date(Date.now() - this.staleThresholdMs);\n const stale = await tx\n .select({ id: jobRuns.id })\n .from(jobRuns)\n .where(\n and(eq(jobRuns.status, 'running'), lt(jobRuns.claimedAt, threshold)),\n )\n .for('update', { skipLocked: true });\n if (stale.length === 0) return;\n const ids = stale.map((r) => r.id);\n await tx\n .update(jobRuns)\n .set({ status: 'pending', claimedAt: null, startedAt: null })\n .where(inArray(jobRuns.id, ids));\n for (const id of ids) {\n this.logger.warn(`Recovered stale claim on run ${id}`);\n }\n });\n } catch (err) {\n this.logger.error(`sweepStaleClaims failed: ${(err as Error).message}`);\n }\n }\n\n // ============================================================================\n // processRun\n // ============================================================================\n\n private async processRun(claimed: JobRunRow): Promise<void> {\n const registryEntry = JOB_HANDLER_REGISTRY.get(claimed.jobType);\n\n // (a) Missing handler — defensive; JOB-5 boot validator should have caught.\n if (!registryEntry) {\n this.logger.error(\n `No handler registered for jobType='${claimed.jobType}' (run ${claimed.id})`,\n );\n await this.markFailed(\n claimed,\n new Error(`No handler registered for jobType='${claimed.jobType}'`),\n /*finalAttempts*/ (claimed.attempts ?? 0) + 1,\n );\n return;\n }\n\n // (b) Concurrency-queue release gate — defer if another run with the\n // same key is already `running`.\n if (claimed.concurrencyKey) {\n const inflight = await this.db\n .select({ id: jobRuns.id })\n .from(jobRuns)\n .where(\n and(\n eq(jobRuns.concurrencyKey, claimed.concurrencyKey),\n eq(jobRuns.status, 'running'),\n ),\n );\n const other = inflight.find((r) => r.id !== claimed.id);\n if (other) {\n await this.db\n .update(jobRuns)\n .set({\n status: 'pending',\n claimedAt: null,\n startedAt: null,\n updatedAt: new Date(),\n })\n .where(eq(jobRuns.id, claimed.id));\n return;\n }\n }\n\n const meta = registryEntry.meta as JobHandlerMeta<unknown>;\n const HandlerClass = registryEntry.handlerClass;\n\n // (c) Build JobContext. Resolve the handler instance from Nest's DI\n // graph so its `@Inject` constructor params (which may come from\n // any module in the app graph) are satisfied. `moduleRef.create()`\n // would otherwise instantiate a fresh class within JobWorkerModule's\n // scope only — which blows up with \"not a provider of the current\n // module\" for any handler that consumes a service from a peer\n // module (e.g. CrmSyncJob injecting CrmSyncFactory from CrmModule).\n // Consequence: handlers MUST be registered as providers in their\n // owning module (@Injectable + `providers: [HandlerClass]`). The\n // @JobHandler decorator handles registry registration only, not DI.\n // See the jobs skill's handler-authoring.md for the registration\n // rule.\n const handler = this.moduleRef.get(\n HandlerClass as unknown as new (...args: unknown[]) => unknown,\n { strict: false },\n ) as JobHandlerBase<unknown>;\n const ctx: JobContext<unknown> = {\n input: claimed.input,\n run: claimed as JobRun,\n step: this.makeStepFn(claimed),\n spawnChild: this.makeSpawnFn(claimed),\n logger: new Logger(`JobRun:${claimed.id}`),\n };\n\n const attemptsBefore = claimed.attempts ?? 0;\n try {\n // (d) Run the handler.\n const output = (await handler.run(ctx)) as Record<string, unknown> | undefined;\n // (e) Success.\n await this.db\n .update(jobRuns)\n .set({\n status: 'completed',\n output: (output ?? {}) as Record<string, unknown>,\n finishedAt: new Date(),\n updatedAt: new Date(),\n attempts: attemptsBefore + 1,\n })\n .where(eq(jobRuns.id, claimed.id));\n } catch (err) {\n // (f) Error classification + retry/fail.\n const policy = meta.retry;\n const decision = classifyError(err, policy, attemptsBefore);\n const nextAttempts = attemptsBefore + 1;\n if (decision === 'retry' && policy) {\n const delay = computeBackoff(policy, nextAttempts);\n await this.db\n .update(jobRuns)\n .set({\n status: 'pending',\n attempts: nextAttempts,\n runAt: new Date(Date.now() + delay),\n startedAt: null,\n claimedAt: null,\n error: serialiseError(err, nextAttempts, true),\n updatedAt: new Date(),\n })\n .where(eq(jobRuns.id, claimed.id));\n } else {\n await this.markFailed(claimed, err, nextAttempts);\n }\n }\n }\n\n private async markFailed(\n claimed: JobRunRow,\n err: unknown,\n finalAttempts: number,\n ): Promise<void> {\n await this.db\n .update(jobRuns)\n .set({\n status: 'failed',\n attempts: finalAttempts,\n finishedAt: new Date(),\n error: serialiseError(err, finalAttempts, false),\n updatedAt: new Date(),\n })\n .where(eq(jobRuns.id, claimed.id));\n\n // Parent-close-policy cascade: if this run has children under the same\n // root_run_id and this run's own parentClosePolicy is 'terminate', cascade.\n if (claimed.parentClosePolicy === 'terminate') {\n try {\n // JOB-8 — thread the run's own tenantId so the orchestrator's\n // multi-tenant gate passes. Without this, every terminate-policy\n // cascade throws MissingTenantIdError under multiTenant=true and\n // the outer catch silently swallows it — children never cancel.\n await this.orchestrator.cancel(claimed.id, {\n cascade: true,\n reason: 'parent-failed',\n tenantId: claimed.tenantId,\n });\n } catch (cascadeErr) {\n // cancel is idempotent; failure here is unusual but not fatal.\n this.logger.warn(\n `cascade on failed run ${claimed.id}: ${(cascadeErr as Error).message}`,\n );\n }\n }\n }\n\n // ============================================================================\n // ctx.step / ctx.spawnChild builders\n // ============================================================================\n\n private makeStepFn(run: JobRunRow) {\n return async <TOutput>(\n stepId: string,\n fn: () => Promise<TOutput>,\n _opts?: StepOptions,\n ): Promise<TOutput> => {\n void _opts;\n const existing = await this.stepService.findStep(run.id, stepId);\n if (existing?.status === 'completed') {\n return existing.output as TOutput;\n }\n\n const seq = await this.nextStepSeq(run.id);\n const startedAt = new Date();\n const nextAttempts = (existing?.attempts ?? 0) + 1;\n await this.stepService.recordStep({\n jobRunId: run.id,\n stepId,\n kind: 'task',\n seq,\n status: 'running',\n startedAt,\n attempts: nextAttempts,\n });\n try {\n const output = await fn();\n await this.stepService.recordStep({\n jobRunId: run.id,\n stepId,\n kind: 'task',\n seq,\n status: 'completed',\n output: output as Record<string, unknown> | undefined,\n finishedAt: new Date(),\n attempts: nextAttempts,\n });\n return output;\n } catch (err) {\n await this.stepService.recordStep({\n jobRunId: run.id,\n stepId,\n kind: 'task',\n seq,\n status: 'failed',\n error: serialiseError(err, nextAttempts, false),\n finishedAt: new Date(),\n attempts: nextAttempts,\n });\n throw err;\n }\n };\n }\n\n private makeSpawnFn(run: JobRunRow) {\n return async (\n type: string,\n input: unknown,\n opts?: SpawnChildOptions,\n ): Promise<JobRun> => {\n return this.orchestrator.start(type, input, {\n parentRunId: run.id,\n parentClosePolicy: opts?.closePolicy,\n runAt: opts?.runAt,\n priority: opts?.priority,\n tags: opts?.tags,\n triggerSource: 'parent',\n triggerRef: run.id,\n });\n };\n }\n\n /**\n * Allocate the next `seq` for a given run. SELECT-max approach — runs\n * typically have <100 steps so the scan is cheap, and correctness across\n * retries is more important than the microseconds saved by an in-memory\n * counter (which would drift if the worker crashes mid-run and another\n * worker resumes via stale-claim sweep).\n */\n private async nextStepSeq(runId: string): Promise<number> {\n const [row] = await this.db.execute(\n sql`SELECT COALESCE(MAX(seq), 0) + 1 AS next FROM job_step WHERE job_run_id = ${runId}`,\n ) as unknown as Array<{ next: number }>;\n // pg driver returns { rows: [...] } for raw execute; tolerate both shapes.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const maybeRows = (row as any)?.rows;\n if (Array.isArray(maybeRows) && maybeRows.length > 0) {\n return Number(maybeRows[0].next ?? 1);\n }\n if (row && typeof (row as { next?: unknown }).next !== 'undefined') {\n return Number((row as { next: unknown }).next);\n }\n return 1;\n }\n\n // ============================================================================\n // (suppress unused-import noise)\n // ============================================================================\n}\n\n// Terminal statuses re-exported for JOB-4 parity imports.\nexport { TERMINAL_STATUSES };\n","/**\n * MemoryJobStore — the shared in-memory backing for the three memory-backend\n * services (ADR-022, JOB-4).\n *\n * Plain class, not `@Injectable()`. Wired as a `useValue` provider in\n * JOB-5's `JobsDomainModule.forRoot({ backend: 'memory' })` so unit tests\n * can keep a direct reference for `beforeEach` resets.\n *\n * All three memory services receive the same `MemoryJobStore` instance via\n * constructor injection; the store owns mutable state, the services are\n * stateless mutators.\n */\nimport type {\n JobDefinitionRow,\n JobRunRow,\n JobStepRow,\n} from './job-orchestration.schema';\n\nexport class MemoryJobStore {\n /** Runs keyed by `id` (single source of truth for status/scope/lineage). */\n readonly runs: Map<string, JobRunRow> = new Map();\n\n /** Steps keyed by `job_run_id`; array order matches insertion order. */\n readonly steps: Map<string, JobStepRow[]> = new Map();\n\n /** Job definitions keyed by `type` — memory mirror of the `job` table. */\n readonly jobs: Map<string, JobDefinitionRow> = new Map();\n\n /** Reset everything. Tests call this in `beforeEach`. */\n clear(): void {\n this.runs.clear();\n this.steps.clear();\n this.jobs.clear();\n }\n}\n","/**\n * MemoryJobOrchestrator — in-process implementation of `IJobOrchestrator`\n * (ADR-022, JOB-4).\n *\n * Exists solely for the unit test suite: reproduces the Drizzle backend's\n * observable behaviour (claim ordering, collision modes, dedupe collapse,\n * memoization cache, replay row-clearing, cascade cancel) without a\n * database. Not production — the single-process mutex is a substitute for\n * Postgres' `FOR UPDATE SKIP LOCKED`; acceptable non-parity is listed in\n * `docs/specs/JOB-4.md` (fsync, query perf, multi-process claim).\n *\n * The `MemoryJobStore` is shared with `MemoryJobRunService` /\n * `MemoryJobStepService` — all three services mutate the same Maps under\n * the orchestrator's mutex.\n */\nimport { randomUUID } from 'node:crypto';\nimport { Inject, Injectable, Logger, Optional } from '@nestjs/common';\nimport { ModuleRef } from '@nestjs/core';\nimport type {\n JobDefinitionRow,\n JobRunRow,\n} from './job-orchestration.schema';\nimport type {\n CancelOptions,\n IJobOrchestrator,\n JobPoolDef,\n JobRun,\n JobUpsertEntry,\n StartOptions,\n} from './job-orchestrator.protocol';\nimport type {\n JobContext,\n JobHandlerBase,\n JobHandlerMeta,\n RetryPolicy,\n SpawnChildOptions,\n StepOptions,\n} from './job-handler.base';\nimport { ParentClosePolicy } from './job-handler.base';\nimport {\n JobCollisionError,\n JobNotReplayableError,\n JobTemplateFieldMissingError,\n JobTypeNotFoundError,\n MissingTenantIdError,\n} from './jobs-errors';\nimport { MemoryJobStore } from './memory-job-store';\nimport { MemoryJobStepService } from './job-step-service.memory-backend';\nimport { JOBS_MULTI_TENANT } from './jobs-domain.tokens';\n\n/**\n * Sentinel `run_at` for runs that lost the `queue` collision — they stay\n * unclaimable until the incumbent transitions terminal and the orchestrator\n * advances their `run_at` back to `now()`. Mirrors the Drizzle backend's\n * `claim-time gate` behaviour without requiring a separate claim query.\n */\nconst QUEUED_RUN_AT = new Date(8_640_000_000_000_000); // \"distant future\"\nconst TERMINAL_STATUSES: JobRunRow['status'][] = [\n 'completed',\n 'failed',\n 'timed_out',\n 'canceled',\n];\nconst DEDUPE_EXCLUDED_STATUSES: JobRunRow['status'][] = ['canceled', 'failed'];\nconst IN_FLIGHT_STATUSES: JobRunRow['status'][] = ['pending', 'running'];\n\nfunction isTerminal(status: JobRunRow['status']): boolean {\n return TERMINAL_STATUSES.includes(status);\n}\n\n/**\n * Mirror of `evaluateKeyTemplate` in the Drizzle backend. Kept private here\n * rather than exported so the memory backend has no dependency on the\n * Drizzle module.\n */\nfunction evaluateKeyTemplate(\n template: string,\n input: Record<string, unknown>,\n): string {\n return template.replace(\n /\\{\\{\\s*([a-zA-Z0-9_]+)\\s*\\}\\}/g,\n (_m, field: string) => {\n const value = input[field];\n if (value === undefined || value === null) {\n throw new JobTemplateFieldMissingError(template, field);\n }\n return String(value);\n },\n );\n}\n\n/**\n * Single-promise-chain mutex. Every mutating op on the store goes through\n * `run(...)` so two concurrent `start` calls observe the same sequential\n * consistency Postgres gives us via `FOR UPDATE SKIP LOCKED`. Error\n * swallowing on the chain pointer prevents one failed call from poisoning\n * the queue for subsequent callers.\n *\n * Kept private to this file on purpose — the spec explicitly forbids\n * exporting this; it exists only for the memory backend's internal\n * serialisation.\n */\nclass PromiseMutex {\n private queue: Promise<void> = Promise.resolve();\n\n async run<T>(fn: () => Promise<T>): Promise<T> {\n const next = this.queue.then(() => fn());\n // Swallow errors on the chain pointer so a throwing `fn` doesn't\n // permanently reject every future caller.\n this.queue = next.then(\n () => undefined,\n () => undefined,\n );\n return next;\n }\n}\n\n/** Handler registry entry — class + frozen metadata. */\ninterface HandlerRegistration {\n type: string;\n meta: JobHandlerMeta<unknown>;\n handlerClass: new (...args: unknown[]) => JobHandlerBase<unknown>;\n}\n\n@Injectable()\nexport class MemoryJobOrchestrator implements IJobOrchestrator {\n private readonly logger = new Logger(MemoryJobOrchestrator.name);\n private readonly mutex = new PromiseMutex();\n private readonly handlerRegistry = new Map<string, HandlerRegistration>();\n\n /**\n * `runId → dependent runId[]` — when a run with `concurrencyKey = K`\n * blocks on an incumbent, its id is added here under the incumbent's id.\n * On incumbent terminal transition we advance every dependent's `runAt`\n * back to `now()` so it becomes claimable.\n */\n private readonly queueBlockers = new Map<string, string[]>();\n\n constructor(\n // ADR-037 (package-mode DI): explicit `@Inject` tokens on every param —\n // the published bundle has no `design:paramtypes` metadata (built without\n // `emitDecoratorMetadata`), so by-type injection would resolve to\n // `undefined` in package mode. Class tokens (`MemoryJobStore`,\n // `MemoryJobStepService`, `ModuleRef`) are passed to `@Inject` explicitly.\n @Inject(MemoryJobStore) private readonly store: MemoryJobStore,\n @Inject(MemoryJobStepService) private readonly stepService: MemoryJobStepService,\n @Inject(JOBS_MULTI_TENANT) private readonly multiTenant: boolean,\n @Optional() @Inject(ModuleRef) private readonly moduleRef?: ModuleRef,\n ) {}\n\n /**\n * JOB-8 — mirror of the Drizzle backend's `resolveTenantId`. Returns the\n * value to stamp on `tenant_id` / compare against in memory predicates.\n * Off → always `null`. On + `undefined` → throw. On + `null`/string → pass.\n */\n private resolveTenantId(\n method: string,\n tenantId: string | null | undefined,\n ): string | null {\n if (!this.multiTenant) return null;\n if (tenantId === undefined) throw new MissingTenantIdError(method);\n return tenantId;\n }\n\n // ==========================================================================\n // registerHandler — replaces Drizzle's `job` table upsert\n // ==========================================================================\n\n /**\n * Populate the in-memory job definition row plus handler class lookup.\n * Called by `JobWorkerModule.onModuleInit` in memory mode, or directly by\n * unit tests that want to seed the registry without NestJS.\n */\n registerHandler<TInput>(\n type: string,\n meta: JobHandlerMeta<TInput>,\n handlerClass: new (...args: unknown[]) => JobHandlerBase<TInput>,\n ): void {\n const concurrencyKeyTemplate =\n (meta.concurrency as { key?: string } | undefined)?.key ?? null;\n const dedupeKeyTemplate =\n (meta.dedupe as { key?: string } | undefined)?.key ?? null;\n const dedupeWindowMs = meta.dedupe?.windowMs ?? null;\n const now = new Date();\n\n const def: JobDefinitionRow = {\n type,\n version: 1,\n pool: meta.pool ?? 'batch',\n scopeEntityType: meta.scope?.entity ?? null,\n retryPolicy: meta.retry ?? {\n attempts: 1,\n backoff: 'fixed',\n baseMs: 0,\n },\n timeoutMs: meta.timeoutMs ?? null,\n concurrencyKeyTemplate:\n typeof concurrencyKeyTemplate === 'string' ? concurrencyKeyTemplate : null,\n collisionMode:\n (meta.concurrency?.collisionMode as JobDefinitionRow['collisionMode']) ??\n 'queue',\n dedupeKeyTemplate:\n typeof dedupeKeyTemplate === 'string' ? dedupeKeyTemplate : null,\n dedupeWindowMs,\n priorityDefault: 0,\n replayFrom: meta.replayFrom ?? 'last_checkpoint',\n createdAt: now,\n updatedAt: now,\n };\n\n this.store.jobs.set(type, def);\n this.handlerRegistry.set(type, {\n type,\n meta: meta as JobHandlerMeta<unknown>,\n handlerClass: handlerClass as unknown as new (\n ...args: unknown[]\n ) => JobHandlerBase<unknown>,\n });\n }\n\n /** Test helper — look up a registered handler without exposing the map. */\n getHandlerRegistration(type: string): HandlerRegistration | undefined {\n return this.handlerRegistry.get(type);\n }\n\n /**\n * Boot-time upsert per `IJobOrchestrator.upsertJobRows`. Memory backend\n * just funnels each entry through `registerHandler`. The validator is\n * skipped entirely in memory mode (Q4 resolution 2026-04-19), so the\n * orphaned list is always empty — there are no DB rows to compare against.\n */\n async upsertJobRows(\n entries: JobUpsertEntry[],\n poolConfig: ReadonlyMap<string, JobPoolDef>,\n ): Promise<{ orphaned: string[] }> {\n void poolConfig; // pool validation is the module's responsibility\n for (const entry of entries) {\n this.registerHandler(\n entry.type,\n entry.meta as JobHandlerMeta<unknown>,\n entry.handlerClass as new (...args: unknown[]) => JobHandlerBase<unknown>,\n );\n }\n return { orphaned: [] };\n }\n\n // ==========================================================================\n // start\n // ==========================================================================\n\n async start(\n type: string,\n input: unknown,\n opts: StartOptions = {},\n // BRIDGE-7: signature parity with Drizzle backend. The memory backend\n // has no real transactions (its \"atomic\" boundary is a process-wide\n // mutex acquired by the body below), so the parameter is intentionally\n // ignored. Accepting it lets EventFlowService unit tests exercise the\n // same code path without two stub orchestrators.\n _tx?: unknown,\n ): Promise<JobRun> {\n // JOB-8 — resolve tenant gate outside the mutex so the error throws\n // synchronously-ish from the caller's stack rather than via the mutex's\n // deferred chain (matches Drizzle backend's pre-transaction guard).\n const tenantId = this.resolveTenantId('start', opts.tenantId);\n\n return this.mutex.run(async () => {\n const payload = (input ?? {}) as Record<string, unknown>;\n const definition = this.store.jobs.get(type);\n if (!definition) throw new JobTypeNotFoundError(type);\n\n // 1. Dedupe — return existing non-excluded run within the window.\n if (definition.dedupeKeyTemplate && definition.dedupeWindowMs) {\n const dedupeKey = evaluateKeyTemplate(\n definition.dedupeKeyTemplate,\n payload,\n );\n const windowStart = Date.now() - definition.dedupeWindowMs;\n const existing = this.findDedupeCandidate(type, dedupeKey, windowStart);\n if (existing) return existing;\n }\n\n // 2. Concurrency collision check.\n let concurrencyKey: string | null = null;\n let queueBlockedBy: string | null = null;\n if (definition.concurrencyKeyTemplate) {\n concurrencyKey = evaluateKeyTemplate(\n definition.concurrencyKeyTemplate,\n payload,\n );\n const incumbent = this.findInFlightByConcurrencyKey(concurrencyKey);\n if (incumbent) {\n switch (definition.collisionMode) {\n case 'reject':\n throw new JobCollisionError(type, concurrencyKey, incumbent);\n case 'replace':\n // Cancel incumbent (cascading children). Must happen inside\n // the mutex — call the internal helper, not public `cancel()`\n // (public `cancel` would re-enter the mutex and deadlock).\n // Internal replace path sidesteps the tenant gate — it uses\n // the incumbent's own tenant (same concurrency key implies\n // same tenant in practice, but the gate is bypassed via\n // `incumbent.tenantId` to avoid accidental cross-tenant\n // MissingTenantIdError bubbling from the user's `start` call).\n this.cancelLocked(\n incumbent.id,\n { cascade: true, reason: 'replaced' },\n incumbent.tenantId,\n );\n break;\n case 'queue':\n queueBlockedBy = incumbent.id;\n break;\n }\n }\n }\n\n // 3. Resolve lineage.\n const newId = randomUUID();\n let rootRunId: string = newId;\n if (opts.parentRunId) {\n const parent = this.store.runs.get(opts.parentRunId);\n if (!parent) {\n throw new Error(\n `parentRunId ${opts.parentRunId} does not reference an existing job_run`,\n );\n }\n rootRunId = parent.rootRunId;\n }\n\n // 4. Compute dedupe key for the persisted row (separate from dedupe\n // short-circuit above — we store it even when no prior run matched\n // so future dedupe checks see it).\n const dedupeKey = definition.dedupeKeyTemplate\n ? evaluateKeyTemplate(definition.dedupeKeyTemplate, payload)\n : null;\n\n const now = new Date();\n const runAt = queueBlockedBy\n ? QUEUED_RUN_AT\n : (opts.runAt ?? now);\n\n const row: JobRunRow = {\n id: newId,\n jobType: type,\n jobVersion: definition.version,\n parentRunId: opts.parentRunId ?? null,\n rootRunId,\n parentClosePolicy: opts.parentClosePolicy ?? 'terminate',\n scopeEntityType: opts.scope?.entityType ?? null,\n scopeEntityId: opts.scope?.entityId ?? null,\n tenantId,\n tags: opts.tags ?? {},\n pool: opts.pool ?? definition.pool,\n priority: opts.priority ?? definition.priorityDefault,\n concurrencyKey,\n dedupeKey,\n status: 'pending',\n input: payload,\n output: null,\n error: null,\n triggerSource: opts.triggerSource ?? 'manual',\n triggerRef: opts.triggerRef ?? null,\n runAt,\n startedAt: null,\n finishedAt: null,\n claimedAt: null,\n attempts: 0,\n waitKind: null,\n resumeToken: null,\n waitDeadline: null,\n createdAt: now,\n updatedAt: now,\n };\n\n this.store.runs.set(newId, row);\n if (queueBlockedBy) {\n const list = this.queueBlockers.get(queueBlockedBy) ?? [];\n list.push(newId);\n this.queueBlockers.set(queueBlockedBy, list);\n }\n return row;\n });\n }\n\n // ==========================================================================\n // cancel\n // ==========================================================================\n\n async cancel(runId: string, opts: CancelOptions = {}): Promise<void> {\n // JOB-8 — strict tenant gate outside the mutex (matches Drizzle path).\n const tenantId = this.resolveTenantId('cancel', opts.tenantId);\n await this.mutex.run(async () => {\n this.cancelLocked(runId, opts, tenantId);\n });\n }\n\n /**\n * Internal cancel that assumes the caller already holds the mutex.\n * Synchronous because all store ops are in-memory. Idempotent.\n *\n * `tenantForGate` is the already-validated tenant id (or `null`). When\n * non-null it gates the initial cancellation to that tenant's run; the\n * cascade step then sweeps descendants on the same `rootRunId` without\n * re-checking — children of a tenant-gated parent always share the\n * tenant (enforced at `start` time).\n */\n private cancelLocked(\n runId: string,\n opts: CancelOptions,\n tenantForGate: string | null,\n ): void {\n const run = this.store.runs.get(runId);\n if (!run) return;\n // JOB-8 — cross-tenant cancel is silent no-op.\n if (this.multiTenant && run.tenantId !== tenantForGate) return;\n if (isTerminal(run.status)) return;\n\n const now = new Date();\n\n // Collect descendants up front so Cancel-policy parents can wait on\n // children (their `finished_at` is set after children transition).\n const descendants =\n opts.cascade === false\n ? []\n : Array.from(this.store.runs.values()).filter(\n (r) =>\n r.rootRunId === run.rootRunId &&\n r.id !== runId &&\n !isTerminal(r.status),\n );\n\n // Group by policy stored on the child.\n const terminateChildren = descendants.filter(\n (d) => d.parentClosePolicy === ParentClosePolicy.Terminate,\n );\n const cancelChildren = descendants.filter(\n (d) => d.parentClosePolicy === ParentClosePolicy.Cancel,\n );\n // 'abandon' → do nothing.\n\n // Terminate policy: cancel children, then parent.\n for (const child of terminateChildren) {\n this.transitionToCanceled(child.id, now);\n }\n\n // Cancel policy: cancel children first, then parent (so parent's\n // finished_at is set only after children transitioned).\n for (const child of cancelChildren) {\n this.transitionToCanceled(child.id, now);\n }\n\n this.transitionToCanceled(runId, now);\n\n void opts.reason; // reserved for future audit logging\n }\n\n private transitionToCanceled(runId: string, at: Date): void {\n const run = this.store.runs.get(runId);\n if (!run) return;\n if (isTerminal(run.status)) return;\n const next: JobRunRow = {\n ...run,\n status: 'canceled',\n finishedAt: at,\n updatedAt: at,\n };\n this.store.runs.set(runId, next);\n this.unblockQueuedDependents(runId);\n }\n\n /**\n * When `runId` transitions to a terminal state, advance every dependent\n * `queue`-blocked run's `run_at` back to `now()` so `claimNext` picks\n * them up.\n */\n private unblockQueuedDependents(runId: string): void {\n const dependents = this.queueBlockers.get(runId);\n if (!dependents || dependents.length === 0) return;\n const now = new Date();\n for (const dep of dependents) {\n const depRun = this.store.runs.get(dep);\n if (!depRun) continue;\n if (depRun.status !== 'pending') continue;\n this.store.runs.set(dep, { ...depRun, runAt: now, updatedAt: now });\n }\n this.queueBlockers.delete(runId);\n }\n\n // ==========================================================================\n // claimNext — consumed by JobWorker in memory mode (tests exercise directly)\n // ==========================================================================\n\n async claimNext(pool: string): Promise<JobRunRow | null> {\n return this.mutex.run(async () => {\n const now = Date.now();\n const candidates = Array.from(this.store.runs.values()).filter(\n (r) =>\n r.status === 'pending' &&\n r.pool === pool &&\n r.runAt.getTime() <= now,\n );\n if (candidates.length === 0) return null;\n\n // ORDER BY priority DESC, run_at ASC (Drizzle parity).\n candidates.sort((a, b) => {\n if (a.priority !== b.priority) return b.priority - a.priority;\n return a.runAt.getTime() - b.runAt.getTime();\n });\n\n const winner = candidates[0]!;\n const claimedAt = new Date();\n const next: JobRunRow = {\n ...winner,\n status: 'running',\n claimedAt,\n startedAt: claimedAt,\n updatedAt: claimedAt,\n };\n this.store.runs.set(winner.id, next);\n return next;\n });\n }\n\n // ==========================================================================\n // replay\n // ==========================================================================\n\n async replay(runId: string): Promise<JobRun> {\n return this.mutex.run(async () => {\n const run = this.store.runs.get(runId);\n if (!run) throw new Error(`replay: run ${runId} not found`);\n if (!isTerminal(run.status)) {\n throw new JobNotReplayableError(runId, run.status);\n }\n const def = this.store.jobs.get(run.jobType);\n if (!def) throw new JobTypeNotFoundError(run.jobType);\n\n const mode = def.replayFrom;\n if (mode === 'scratch') {\n this.stepService.clearStepsForRun(runId);\n } else {\n // `last_step` and `last_checkpoint` collapse to the same semantic\n // in Phase 1 — delete non-completed rows, preserve memoized ones.\n // Matches the Drizzle backend exactly (see JOB-3 notes).\n this.stepService.clearIncompleteSteps(runId);\n }\n\n const now = new Date();\n const next: JobRunRow = {\n ...run,\n status: 'pending',\n attempts: 0,\n runAt: now,\n startedAt: null,\n finishedAt: null,\n claimedAt: null,\n error: null,\n output: null,\n updatedAt: now,\n };\n this.store.runs.set(runId, next);\n return next;\n });\n }\n\n // ==========================================================================\n // tick — used by unit tests + memory-mode JobWorker\n // ==========================================================================\n\n /**\n * Execute a single claimed run to completion, retry, or failure. Not on\n * `IJobOrchestrator` — it's the memory equivalent of the Drizzle\n * `JobWorker.processRun` code path. The unit tests drive it directly so\n * they can assert memoization across ticks without spinning up a worker.\n */\n async tick(runId: string): Promise<void> {\n // We load state outside the mutex because handler execution cannot\n // hold the serialisation lock — `fn()` inside `ctx.step` can call back\n // into `start` / `spawnChild` which would deadlock. Mutation points\n // (recordStep, status transition) go through the services or the\n // orchestrator entry points and re-enter the mutex there.\n const run = this.store.runs.get(runId);\n if (!run) throw new Error(`tick: run ${runId} not found`);\n if (run.status !== 'running') {\n throw new Error(\n `tick: run ${runId} must be 'running' (got '${run.status}')`,\n );\n }\n\n const registration = this.handlerRegistry.get(run.jobType);\n if (!registration) {\n await this.markFailed(run, new Error(\n `No handler registered for jobType='${run.jobType}'`,\n ), (run.attempts ?? 0) + 1);\n return;\n }\n const meta = registration.meta;\n const HandlerClass = registration.handlerClass;\n // Match the Drizzle backend: resolve the handler through Nest's\n // ModuleRef so `@Inject` constructor params work. ModuleRef is\n // @Optional() — zero-dep test stubs that construct this orchestrator\n // manually still hit the legacy `new HandlerClass()` path.\n // `get({ strict: false })` (not `create()`) — the handler must be a\n // provider in its owning module so cross-module @Inject dependencies\n // resolve. See job-worker.ts for the full rationale.\n const handler = this.moduleRef\n ? (this.moduleRef.get(\n HandlerClass as unknown as new (...args: unknown[]) => unknown,\n { strict: false },\n ) as JobHandlerBase<unknown>)\n : new HandlerClass();\n\n const ctx: JobContext<unknown> = {\n input: run.input,\n run: run as JobRun,\n step: this.makeStepFn(run),\n spawnChild: this.makeSpawnFn(run),\n logger: new Logger(`JobRun:${run.id}`),\n };\n\n const attemptsBefore = run.attempts ?? 0;\n try {\n const output = (await handler.run(ctx)) as Record<string, unknown> | undefined;\n await this.markCompleted(run, output ?? {}, attemptsBefore + 1);\n } catch (err) {\n const policy = meta.retry;\n const decision = classifyError(err, policy, attemptsBefore);\n const nextAttempts = attemptsBefore + 1;\n if (decision === 'retry' && policy) {\n const delay = computeBackoff(policy, nextAttempts);\n await this.rescheduleForRetry(run, err, nextAttempts, delay);\n } else {\n await this.markFailed(run, err, nextAttempts);\n }\n }\n }\n\n private makeStepFn(run: JobRunRow) {\n return async <TOutput>(\n stepId: string,\n fn: () => Promise<TOutput>,\n _opts?: StepOptions,\n ): Promise<TOutput> => {\n void _opts;\n const existing = await this.stepService.findStep(run.id, stepId);\n if (existing?.status === 'completed') {\n return existing.output as TOutput;\n }\n const seq = this.nextStepSeq(run.id);\n const startedAt = new Date();\n const nextAttempts = (existing?.attempts ?? 0) + 1;\n await this.stepService.recordStep({\n jobRunId: run.id,\n stepId,\n kind: 'task',\n seq,\n status: 'running',\n startedAt,\n attempts: nextAttempts,\n });\n try {\n const output = await fn();\n await this.stepService.recordStep({\n jobRunId: run.id,\n stepId,\n kind: 'task',\n seq,\n status: 'completed',\n output: output as Record<string, unknown> | undefined,\n finishedAt: new Date(),\n attempts: nextAttempts,\n });\n return output;\n } catch (err) {\n await this.stepService.recordStep({\n jobRunId: run.id,\n stepId,\n kind: 'task',\n seq,\n status: 'failed',\n error: serialiseError(err, nextAttempts, false),\n finishedAt: new Date(),\n attempts: nextAttempts,\n });\n throw err;\n }\n };\n }\n\n private makeSpawnFn(run: JobRunRow) {\n return async (\n type: string,\n input: unknown,\n opts?: SpawnChildOptions,\n ): Promise<JobRun> => {\n return this.start(type, input, {\n parentRunId: run.id,\n parentClosePolicy: opts?.closePolicy,\n runAt: opts?.runAt,\n priority: opts?.priority,\n tags: opts?.tags,\n triggerSource: 'parent',\n triggerRef: run.id,\n });\n };\n }\n\n private nextStepSeq(runId: string): number {\n const rows = this.store.steps.get(runId);\n if (!rows || rows.length === 0) return 1;\n let max = 0;\n for (const r of rows) if (r.seq > max) max = r.seq;\n return max + 1;\n }\n\n private async markCompleted(\n run: JobRunRow,\n output: Record<string, unknown>,\n attempts: number,\n ): Promise<void> {\n await this.mutex.run(async () => {\n const current = this.store.runs.get(run.id);\n if (!current || isTerminal(current.status)) return;\n const now = new Date();\n this.store.runs.set(run.id, {\n ...current,\n status: 'completed',\n output,\n finishedAt: now,\n updatedAt: now,\n attempts,\n });\n this.unblockQueuedDependents(run.id);\n });\n }\n\n private async markFailed(\n run: JobRunRow,\n err: unknown,\n attempts: number,\n ): Promise<void> {\n await this.mutex.run(async () => {\n const current = this.store.runs.get(run.id);\n if (!current || isTerminal(current.status)) return;\n const now = new Date();\n this.store.runs.set(run.id, {\n ...current,\n status: 'failed',\n finishedAt: now,\n updatedAt: now,\n attempts,\n error: serialiseError(err, attempts, false),\n });\n this.unblockQueuedDependents(run.id);\n });\n\n // parent_close_policy = 'terminate' cascade mirrors the Drizzle worker\n // (cancel runs outside its own terminal transition). We pass the run's\n // own `tenantId` so the cancel passes the multi-tenant gate — this is\n // system-internal cascade, not a user-initiated call.\n if (run.parentClosePolicy === 'terminate') {\n try {\n await this.cancel(run.id, {\n cascade: true,\n reason: 'parent-failed',\n tenantId: run.tenantId,\n });\n } catch (cascadeErr) {\n this.logger.warn(\n `cascade on failed run ${run.id}: ${(cascadeErr as Error).message}`,\n );\n }\n }\n }\n\n private async rescheduleForRetry(\n run: JobRunRow,\n err: unknown,\n attempts: number,\n delayMs: number,\n ): Promise<void> {\n await this.mutex.run(async () => {\n const current = this.store.runs.get(run.id);\n if (!current || isTerminal(current.status)) return;\n const now = new Date();\n this.store.runs.set(run.id, {\n ...current,\n status: 'pending',\n attempts,\n runAt: new Date(Date.now() + delayMs),\n startedAt: null,\n claimedAt: null,\n updatedAt: now,\n error: serialiseError(err, attempts, true),\n });\n });\n }\n\n // ==========================================================================\n // Internal queries — used by start / cancel\n // ==========================================================================\n\n private findDedupeCandidate(\n jobType: string,\n dedupeKey: string,\n windowStartMs: number,\n ): JobRunRow | null {\n let best: JobRunRow | null = null;\n for (const r of this.store.runs.values()) {\n if (r.jobType !== jobType) continue;\n if (r.dedupeKey !== dedupeKey) continue;\n if (DEDUPE_EXCLUDED_STATUSES.includes(r.status)) continue;\n if (r.createdAt.getTime() <= windowStartMs) continue;\n if (!best || r.createdAt.getTime() > best.createdAt.getTime()) {\n best = r;\n }\n }\n return best;\n }\n\n private findInFlightByConcurrencyKey(key: string): JobRunRow | null {\n for (const r of this.store.runs.values()) {\n if (r.concurrencyKey !== key) continue;\n if (!IN_FLIGHT_STATUSES.includes(r.status)) continue;\n return r;\n }\n return null;\n }\n}\n\n// ─── Pure helpers (mirrored from JobWorker so memory mode is standalone) ────\n\nfunction classifyError(\n err: unknown,\n policy: RetryPolicy | undefined,\n currentAttempts: number,\n): 'retry' | 'fail' {\n if (!policy) return 'fail';\n const errObj = err as { name?: string; code?: string } | undefined;\n const name = errObj?.name;\n const code = errObj?.code;\n const nonRetryable = policy.nonRetryableErrors ?? [];\n if (nonRetryable.some((n) => n === name || n === code)) return 'fail';\n if (currentAttempts + 1 >= policy.attempts) return 'fail';\n return 'retry';\n}\n\nfunction computeBackoff(policy: RetryPolicy, attempts: number): number {\n const base = Math.max(policy.baseMs, 0);\n if (policy.backoff === 'fixed') return base;\n const exponent = Math.max(attempts - 1, 0);\n if (exponent >= 53) return Number.MAX_SAFE_INTEGER;\n const raw = base * Math.pow(2, exponent);\n if (!Number.isFinite(raw) || raw >= Number.MAX_SAFE_INTEGER) {\n return Number.MAX_SAFE_INTEGER;\n }\n return raw;\n}\n\nfunction serialiseError(err: unknown, attempt: number, retryable: boolean) {\n const e = err as { message?: string; stack?: string } | undefined;\n return {\n message: (e?.message ?? String(err)) as string,\n stack: e?.stack,\n retryable,\n attempt,\n };\n}\n","/**\n * MemoryJobStepService — in-memory implementation of `IJobStepService`\n * (ADR-022, JOB-4).\n *\n * Mirrors `DrizzleJobStepService` but against plain Maps. `findStep` only\n * returns `completed` rows (memoization cache hit); anything non-completed\n * is invisible so the ctx.step fn re-runs on replay / retry exactly like\n * the Drizzle backend (which deletes non-completed rows on replay).\n */\nimport { randomUUID } from 'node:crypto';\nimport { Inject, Injectable } from '@nestjs/common';\nimport type { JobStepRow } from './job-orchestration.schema';\nimport type {\n IJobStepService,\n JobStep,\n RecordStepInput,\n} from './job-step-service.protocol';\nimport { MemoryJobStore } from './memory-job-store';\n\n@Injectable()\nexport class MemoryJobStepService implements IJobStepService {\n // ADR-037 (package-mode DI): explicit `@Inject(MemoryJobStore)` — the\n // published bundle carries no `design:paramtypes`, so a by-type inject\n // would resolve to `undefined` in package mode.\n constructor(\n @Inject(MemoryJobStore) private readonly store: MemoryJobStore,\n ) {}\n\n async findStep(runId: string, stepId: string): Promise<JobStep | null> {\n const rows = this.store.steps.get(runId);\n if (!rows) return null;\n const match = rows.find(\n (r) => r.stepId === stepId && r.status === 'completed',\n );\n return (match ?? null) as JobStep | null;\n }\n\n async recordStep(input: RecordStepInput): Promise<JobStep> {\n const rows = this.getOrCreateRows(input.jobRunId);\n const existingIdx = rows.findIndex((r) => r.stepId === input.stepId);\n\n const normalisedInput =\n (input.input ?? null) as Record<string, unknown> | null;\n const normalisedOutput =\n (input.output ?? null) as Record<string, unknown> | null;\n\n if (existingIdx >= 0) {\n const prev = rows[existingIdx]!;\n const next: JobStepRow = {\n ...prev,\n status: input.status,\n input: normalisedInput ?? prev.input,\n output: normalisedOutput ?? prev.output,\n error: input.error ?? prev.error,\n attempts: input.attempts ?? prev.attempts,\n startedAt: input.startedAt ?? prev.startedAt,\n finishedAt: input.finishedAt ?? prev.finishedAt,\n };\n rows[existingIdx] = next;\n return next as JobStep;\n }\n\n const seq = input.seq ?? this.nextSeq(rows);\n const row: JobStepRow = {\n id: randomUUID(),\n jobRunId: input.jobRunId,\n stepId: input.stepId,\n kind: input.kind,\n seq,\n status: input.status,\n input: normalisedInput,\n output: normalisedOutput,\n error: input.error ?? null,\n attempts: input.attempts ?? 0,\n startedAt: input.startedAt ?? null,\n finishedAt: input.finishedAt ?? null,\n };\n rows.push(row);\n return row as JobStep;\n }\n\n /**\n * Replay helper — wipe every step row for a run. Mirrors the `scratch`\n * replay mode of the Drizzle backend (`DELETE FROM job_step WHERE job_run_id = …`).\n */\n clearStepsForRun(runId: string): void {\n this.store.steps.delete(runId);\n }\n\n /**\n * Remove every non-`completed` row for the run. Memoized (`completed`)\n * rows are preserved — this is the `last_checkpoint` / `last_step`\n * semantics the Drizzle backend implements via\n * `DELETE … WHERE status != 'completed'`. Both replay modes route here\n * (Phase 1 collapses `last_step` onto this behaviour; see JOB-3 notes).\n */\n clearIncompleteSteps(runId: string): void {\n const rows = this.store.steps.get(runId);\n if (!rows) return;\n const kept = rows.filter((r) => r.status === 'completed');\n if (kept.length === 0) {\n this.store.steps.delete(runId);\n } else {\n this.store.steps.set(runId, kept);\n }\n }\n\n private getOrCreateRows(runId: string): JobStepRow[] {\n let rows = this.store.steps.get(runId);\n if (!rows) {\n rows = [];\n this.store.steps.set(runId, rows);\n }\n return rows;\n }\n\n private nextSeq(rows: JobStepRow[]): number {\n let max = 0;\n for (const r of rows) {\n if (r.seq > max) max = r.seq;\n }\n return max + 1;\n }\n}\n","/**\n * MemoryJobRunService — scope-oriented queries and bulk ops over the\n * in-memory run store (ADR-022, JOB-4).\n *\n * Mirrors `DrizzleJobRunService` but scans `MemoryJobStore.runs.values()`.\n * Cancel delegates back to the orchestrator so cascade semantics stay in\n * one place.\n */\nimport { Inject, Injectable } from '@nestjs/common';\nimport type { JobRunRow } from './job-orchestration.schema';\nimport type { JobRun } from './job-orchestrator.protocol';\nimport type {\n IJobRunService,\n ListForScopeOptions,\n CancelForScopeOptions,\n RescheduleForScopeOptions,\n PoolStatusCount,\n JobRunFailure,\n ListJobRunsQuery,\n JobRunPage,\n} from './job-run-service.protocol';\nimport {\n clampLimit,\n decodeKeysetCursor,\n encodeKeysetCursor,\n toJobRunSummary,\n} from './job-run-keyset-cursor';\nimport type { IJobOrchestrator } from './job-orchestrator.protocol';\nimport { JOB_ORCHESTRATOR, JOBS_MULTI_TENANT } from './jobs-domain.tokens';\nimport { MissingTenantIdError } from './jobs-errors';\nimport { MemoryJobStore } from './memory-job-store';\n\nconst NON_TERMINAL_STATUSES: JobRunRow['status'][] = [\n 'pending',\n 'running',\n 'waiting',\n];\n\n@Injectable()\nexport class MemoryJobRunService implements IJobRunService {\n constructor(\n // ADR-037 (package-mode DI): explicit `@Inject(MemoryJobStore)` — the\n // published bundle carries no `design:paramtypes`, so a by-type inject\n // would resolve to `undefined` in package mode.\n @Inject(MemoryJobStore) private readonly store: MemoryJobStore,\n @Inject(JOB_ORCHESTRATOR) private readonly orchestrator: IJobOrchestrator,\n @Inject(JOBS_MULTI_TENANT) private readonly multiTenant: boolean,\n ) {}\n\n /**\n * JOB-8 — produce a per-row predicate for the tenant gate.\n * Returns `null` when multi-tenancy is off (caller doesn't check).\n * Throws when on + `undefined`; matches `tenant_id IS NULL` on explicit\n * `null` to support cross-tenant background work.\n */\n private tenantPredicate(\n method: string,\n tenantId: string | null | undefined,\n ): ((r: JobRunRow) => boolean) | null {\n if (!this.multiTenant) return null;\n if (tenantId === undefined) throw new MissingTenantIdError(method);\n return (r) => r.tenantId === tenantId;\n }\n\n async listForScope(\n entityType: string,\n entityId: string,\n opts: ListForScopeOptions = {},\n ): Promise<JobRun[]> {\n const statusFilter = opts.status\n ? Array.isArray(opts.status)\n ? new Set(opts.status)\n : new Set([opts.status])\n : null;\n const tenantCheck = this.tenantPredicate('listForScope', opts.tenantId);\n\n const rows: JobRunRow[] = [];\n for (const r of this.store.runs.values()) {\n if (r.scopeEntityType !== entityType) continue;\n if (r.scopeEntityId !== entityId) continue;\n if (statusFilter && !statusFilter.has(r.status)) continue;\n if (opts.jobType && r.jobType !== opts.jobType) continue;\n if (tenantCheck && !tenantCheck(r)) continue;\n rows.push(r);\n }\n\n const orderBy = opts.orderBy ?? 'created_at desc';\n rows.sort((a, b) => compareBy(a, b, orderBy));\n\n const offset = opts.offset ?? 0;\n const limit = opts.limit;\n const sliced =\n typeof limit === 'number' ? rows.slice(offset, offset + limit) : rows.slice(offset);\n return sliced as JobRun[];\n }\n\n async cancelForScope(\n entityType: string,\n entityId: string,\n opts: CancelForScopeOptions = {},\n ): Promise<void> {\n const tenantCheck = this.tenantPredicate('cancelForScope', opts.tenantId);\n\n const ids: string[] = [];\n for (const r of this.store.runs.values()) {\n if (r.scopeEntityType !== entityType) continue;\n if (r.scopeEntityId !== entityId) continue;\n if (!NON_TERMINAL_STATUSES.includes(r.status)) continue;\n if (tenantCheck && !tenantCheck(r)) continue;\n ids.push(r.id);\n }\n for (const id of ids) {\n // Propagate the tenant gate through the orchestrator's cancel so the\n // internal per-row guard passes (no surprise MissingTenantIdError\n // once the scope query has already narrowed to this tenant).\n await this.orchestrator.cancel(id, {\n cascade: true,\n tenantId: opts.tenantId,\n });\n }\n }\n\n async rescheduleForScope(\n entityType: string,\n entityId: string,\n newRunAt: Date,\n opts: RescheduleForScopeOptions = {},\n ): Promise<void> {\n const tenantCheck = this.tenantPredicate('rescheduleForScope', opts.tenantId);\n for (const r of this.store.runs.values()) {\n if (r.scopeEntityType !== entityType) continue;\n if (r.scopeEntityId !== entityId) continue;\n if (r.status !== 'pending') continue;\n if (tenantCheck && !tenantCheck(r)) continue;\n this.store.runs.set(r.id, {\n ...r,\n runAt: newRunAt,\n updatedAt: new Date(),\n });\n }\n }\n\n async countByPoolAndStatus(\n tenantId?: string | null,\n ): Promise<PoolStatusCount[]> {\n const tenantCheck = this.tenantPredicate('countByPoolAndStatus', tenantId);\n const map = new Map<string, PoolStatusCount>();\n for (const r of this.store.runs.values()) {\n if (tenantCheck && !tenantCheck(r)) continue;\n const key = `${r.pool}\\0${r.status}`;\n const cur = map.get(key);\n if (cur) {\n cur.count += 1;\n } else {\n map.set(key, { pool: r.pool, status: r.status, count: 1 });\n }\n }\n return Array.from(map.values());\n }\n\n async listRecentFailed(\n limit: number,\n tenantId?: string | null,\n ): Promise<JobRunFailure[]> {\n const tenantCheck = this.tenantPredicate('listRecentFailed', tenantId);\n const failed: JobRunRow[] = [];\n for (const r of this.store.runs.values()) {\n if (r.status !== 'failed') continue;\n if (tenantCheck && !tenantCheck(r)) continue;\n failed.push(r);\n }\n failed.sort((a, b) => {\n const at = (a.finishedAt ?? a.updatedAt).getTime();\n const bt = (b.finishedAt ?? b.updatedAt).getTime();\n return bt - at;\n });\n return failed.slice(0, limit).map((r) => ({\n runId: r.id,\n jobType: r.jobType,\n pool: r.pool,\n scopeEntityType: r.scopeEntityType,\n scopeEntityId: r.scopeEntityId,\n tenantId: r.tenantId,\n attempts: r.attempts,\n errorMessage: r.error?.message ?? null,\n failedAt: r.finishedAt ?? r.updatedAt,\n createdAt: r.createdAt,\n }));\n }\n\n async listJobRuns(query: ListJobRunsQuery = {}): Promise<JobRunPage> {\n const limit = clampLimit(query.limit);\n const tenantCheck = this.tenantPredicate('listJobRuns', query.tenantId);\n const keyset = query.cursor ? decodeKeysetCursor(query.cursor) : null;\n\n const matched: JobRunRow[] = [];\n for (const r of this.store.runs.values()) {\n if (tenantCheck && !tenantCheck(r)) continue;\n if (query.poolId && r.pool !== query.poolId) continue;\n if (query.rootRunId && r.rootRunId !== query.rootRunId) continue;\n if (query.status && r.status !== query.status) continue;\n if (query.since && r.createdAt.getTime() < query.since.getTime()) continue;\n matched.push(r);\n }\n\n // Order created_at DESC, id DESC to match the Drizzle backend's keyset.\n matched.sort((a, b) => {\n const dt = b.createdAt.getTime() - a.createdAt.getTime();\n if (dt !== 0) return dt;\n return a.id < b.id ? 1 : a.id > b.id ? -1 : 0;\n });\n\n // Keyset seek: drop everything at/after the cursor's (created_at, id).\n const seeked = keyset\n ? matched.filter((r) => {\n const ct = r.createdAt.getTime();\n const kt = keyset.createdAt.getTime();\n if (ct < kt) return true;\n if (ct > kt) return false;\n return r.id < keyset.id;\n })\n : matched;\n\n const hasMore = seeked.length > limit;\n const page = hasMore ? seeked.slice(0, limit) : seeked;\n const items = page.map(toJobRunSummary);\n const last = page[page.length - 1];\n const nextCursor =\n hasMore && last\n ? encodeKeysetCursor({ createdAt: last.createdAt, id: last.id })\n : null;\n\n return { items, nextCursor };\n }\n\n /**\n * Direct lookup. Not on the protocol — concrete-class convenience for\n * tests. Matches `DrizzleJobRunService.findByRootRunId` in spirit; both\n * are debug / test helpers that sidestep the orchestrator.\n */\n findById(runId: string): JobRun | null {\n return (this.store.runs.get(runId) ?? null) as JobRun | null;\n }\n\n /** Public counterpart to the Drizzle backend's `findByRootRunId` helper. */\n findByRootRunId(rootRunId: string): JobRun[] {\n const out: JobRunRow[] = [];\n for (const r of this.store.runs.values()) {\n if (r.rootRunId === rootRunId) out.push(r);\n }\n return out as JobRun[];\n }\n}\n\nfunction compareBy(\n a: JobRunRow,\n b: JobRunRow,\n order: Exclude<ListForScopeOptions['orderBy'], undefined>,\n): number {\n switch (order) {\n case 'created_at asc':\n return a.createdAt.getTime() - b.createdAt.getTime();\n case 'run_at desc':\n return b.runAt.getTime() - a.runAt.getTime();\n case 'run_at asc':\n return a.runAt.getTime() - b.runAt.getTime();\n case 'created_at desc':\n default:\n return b.createdAt.getTime() - a.createdAt.getTime();\n }\n}\n","/**\n * JobsDomainModule — `DynamicModule.forRoot({ backend })` factory wiring\n * the three jobs-domain protocol tokens to a backend implementation\n * (ADR-022, JOB-5).\n *\n * Mirrors `EventsModule.forRoot()` exactly:\n * - `global: true` so consumer entity modules don't have to import this\n * individually — `JOB_ORCHESTRATOR` / `JOB_RUN_SERVICE` /\n * `JOB_STEP_SERVICE` are available project-wide.\n * - One backend at a time (Drizzle for production, Memory for tests).\n *\n * Backend swappability follows the core/extension protocol from CLAUDE.md:\n * the three tokens are the **core contract**; backend-specific tunables\n * live under `extensions.<backend>` so opting into a feature is explicit\n * and the type system reserves the slot.\n */\nimport { Module, type DynamicModule, type Provider } from '@nestjs/common';\nimport { DRIZZLE } from '../../constants/tokens';\nimport {\n JOB_ORCHESTRATOR,\n JOB_RUN_SERVICE,\n JOB_STEP_SERVICE,\n JOBS_MULTI_TENANT,\n} from './jobs-domain.tokens';\nimport { DrizzleJobOrchestrator } from './job-orchestrator.drizzle-backend';\nimport { DrizzleJobRunService } from './job-run-service.drizzle-backend';\nimport { DrizzleJobStepService } from './job-step-service.drizzle-backend';\n// #6 — `BullMQJobOrchestrator` is lazy-loaded only when `backend: 'bullmq'`\n// is selected. The backend file is filtered out of drizzle/memory installs\n// (see `backendFileFilter`); a non-literal dynamic import below sidesteps\n// consumer-side tsc resolution of an absent file.\nimport { MemoryJobOrchestrator } from './job-orchestrator.memory-backend';\nimport { MemoryJobRunService } from './job-run-service.memory-backend';\nimport { MemoryJobStepService } from './job-step-service.memory-backend';\nimport { MemoryJobStore } from './memory-job-store';\nimport {\n BULLMQ_CONNECTION,\n BULLMQ_RESOLVED_CONFIG,\n resolveBullMqConfig,\n type BullMqExtensionsConfig,\n} from './bullmq.config';\n\n/**\n * Drizzle backend extensions surface. None are wired into the Drizzle\n * orchestrator yet — this is the **typed reservation** for the LISTEN/NOTIFY\n * + tunable poll-interval extensions called out in ADR-022. App code\n * passing these today is parsed but not yet dispatched; when the\n * Drizzle orchestrator grows the consumer hooks, opt-in code paths will\n * read directly from these fields.\n */\nexport interface DrizzleBackendExtensions {\n /** Use Postgres LISTEN/NOTIFY to wake the polling loop. Default false. */\n listenNotify?: boolean;\n /** Polling interval when LISTEN/NOTIFY is off (ms). Default 1000. */\n pollIntervalMs?: number;\n}\n\nexport interface JobsDomainModuleOptions {\n backend: 'drizzle' | 'memory' | 'bullmq';\n /**\n * Backend-specific extensions. Only the matching backend's extensions\n * are read at boot; non-matching keys are ignored. This is the\n * core/extension protocol surface — see CLAUDE.md.\n */\n extensions?: {\n drizzle?: DrizzleBackendExtensions;\n /**\n * BullMQ backend extensions (BULLMQ-1). Snake_case mirrors the YAML\n * under `jobs.extensions.bullmq`. `redis_url` falls back to\n * `process.env.REDIS_URL` then `redis://localhost:6379`.\n */\n bullmq?: BullMqExtensionsConfig;\n };\n /** Multi-tenancy opt-in. Wired by JOB-8; module signature stays stable. */\n multiTenant?: boolean;\n}\n\n@Module({})\nexport class JobsDomainModule {\n static forRoot(opts: JobsDomainModuleOptions): DynamicModule {\n const multiTenant = opts.multiTenant ?? false;\n\n const providers: Provider[] = [\n // JOB-8 — boolean provider consumed by the four service-layer backends.\n // Always provided (even when `multiTenant === false`) so `@Inject`\n // always resolves; backends short-circuit the enforcement path when\n // the value is `false`. See `jobs-domain.tokens.ts` for the claim-loop\n // cross-tenant-by-design decision.\n { provide: JOBS_MULTI_TENANT, useValue: multiTenant },\n ];\n\n if (opts.backend === 'memory') {\n // The store is a plain class — wired as a singleton `useValue` so\n // unit tests can pull it out via `.get(MemoryJobStore)` for direct\n // assertions (matches the access pattern in JOB-4 specs).\n const store = new MemoryJobStore();\n providers.push({ provide: MemoryJobStore, useValue: store });\n providers.push(MemoryJobStepService);\n providers.push({ provide: JOB_STEP_SERVICE, useExisting: MemoryJobStepService });\n providers.push(MemoryJobOrchestrator);\n providers.push({ provide: JOB_ORCHESTRATOR, useExisting: MemoryJobOrchestrator });\n providers.push(MemoryJobRunService);\n providers.push({ provide: JOB_RUN_SERVICE, useExisting: MemoryJobRunService });\n } else if (opts.backend === 'bullmq') {\n // BULLMQ-1 — BullMQ orchestrator over a Postgres source of truth. The\n // run/step services stay Drizzle (domain reads + `listForScope` are\n // Postgres queries, unchanged per spec). Only the orchestrator's\n // claim/dispatch half swaps to BullMQ.\n //\n // #6 — the bullmq backend module is filtered out of drizzle/memory\n // installs (no `bullmq` peer dep, no consumer-side tsc compile of an\n // unused file). The factory below dynamic-imports it via a non-literal\n // specifier so TS treats the module type as `any` and never tries to\n // resolve the absent file on a drizzle/memory consumer.\n const resolved = resolveBullMqConfig(opts.extensions?.bullmq);\n providers.push({ provide: BULLMQ_CONNECTION, useValue: resolved.connection });\n providers.push({ provide: BULLMQ_RESOLVED_CONFIG, useValue: resolved });\n providers.push({\n provide: JOB_ORCHESTRATOR,\n useFactory: async (...args: unknown[]): Promise<object> => {\n const specifier = './job-orchestrator.bullmq-backend';\n const mod = (await import(specifier)) as {\n BullMQJobOrchestrator: new (...args: unknown[]) => object;\n };\n return new mod.BullMQJobOrchestrator(...args);\n },\n // The bullmq orchestrator constructor mirrors DrizzleJobOrchestrator's\n // injection list: DRIZZLE + JOBS_MULTI_TENANT + the resolved BullMQ\n // tokens. Importing token references would force a static dep on the\n // tokens file in this module's import graph; using the existing\n // symbols already in scope is sufficient.\n inject: [DRIZZLE, JOBS_MULTI_TENANT, BULLMQ_CONNECTION, BULLMQ_RESOLVED_CONFIG],\n });\n providers.push({ provide: JOB_RUN_SERVICE, useClass: DrizzleJobRunService });\n providers.push({ provide: JOB_STEP_SERVICE, useClass: DrizzleJobStepService });\n } else {\n providers.push({ provide: JOB_ORCHESTRATOR, useClass: DrizzleJobOrchestrator });\n providers.push({ provide: JOB_RUN_SERVICE, useClass: DrizzleJobRunService });\n providers.push({ provide: JOB_STEP_SERVICE, useClass: DrizzleJobStepService });\n }\n\n const exports = [\n JOB_ORCHESTRATOR,\n JOB_RUN_SERVICE,\n JOB_STEP_SERVICE,\n JOBS_MULTI_TENANT,\n ];\n // BULLMQ-1 — only export the BullMQ tokens when they were actually\n // provided. Nest throws \"exported but not provided\" otherwise. Exported so\n // JobWorkerModule (which imports this module) can read the resolved\n // connection/config to spawn BullMQ workers.\n if (opts.backend === 'bullmq') {\n exports.push(BULLMQ_CONNECTION, BULLMQ_RESOLVED_CONFIG);\n }\n\n return {\n module: JobsDomainModule,\n global: true,\n providers,\n exports,\n };\n }\n}\n","/**\n * JobWorkerModule — `DynamicModule.forRoot({ mode, pools? })` factory that\n * boots one `JobWorker` per active pool and runs the boot-time validator\n * (Drizzle only) (ADR-022, JOB-5).\n *\n * Imports `JobsDomainModule` internally so call sites only need to add\n * `JobWorkerModule.forRoot(...)` to `AppModule.imports` — the protocol\n * tokens become available transitively via `global: true`.\n *\n * Lifecycle (`onModuleInit`, **order-critical** per JOB-5 spec):\n * 1. `loadPoolConfig()` → resolved `PoolConfig`\n * 2. `HandlerRegistry.getAll()` → registered entries\n * 3. Reserved-pool validation → throws `ReservedPoolViolationError`\n * 4. `orchestrator.upsertJobRows(entries, …)` → persist `job` definitions\n * 5. Boot validator (Drizzle only) → throws `BootValidationError`\n * (skipped entirely in memory mode — Q4 resolution 2026-04-19)\n * 6. Spawn one `JobWorker` per active pool → start polling loops\n *\n * `onModuleDestroy` calls `gracefulStop` on each worker (drains in-flight,\n * resets `running` rows, removes SIGTERM handler).\n */\nimport {\n Inject,\n Injectable,\n Logger,\n Module,\n Optional,\n type DynamicModule,\n type OnModuleDestroy,\n type OnModuleInit,\n} from '@nestjs/common';\nimport { ModuleRef } from '@nestjs/core';\nimport { tokenKey } from '../token-key';\nimport { DRIZZLE } from '../../constants/tokens';\nimport type { DrizzleClient } from '../../types/drizzle';\nimport { HandlerRegistry, type HandlerRegistryEntry } from './job-handler.base';\nimport {\n JobsDomainModule,\n type JobsDomainModuleOptions,\n} from './jobs-domain.module';\nimport {\n JOB_ORCHESTRATOR,\n JOB_RUN_SERVICE,\n JOB_STEP_SERVICE,\n} from './jobs-domain.tokens';\nimport type { IJobOrchestrator } from './job-orchestrator.protocol';\nimport type { IJobRunService } from './job-run-service.protocol';\nimport type { IJobStepService } from './job-step-service.protocol';\nimport {\n allNonReservedPoolNames,\n allPoolNames,\n loadPoolConfig,\n type PoolConfig,\n} from './pool-config.loader';\nimport { JobWorker, type JobWorkerOptions } from './job-worker';\n// #6 — `BullMQJobWorker` is lazy-loaded only when `backend: 'bullmq'` is\n// selected (`spawnBullMQWorker` below). The file is filtered out of drizzle/\n// memory installs (see `backendFileFilter`). The `ConnectionOptions` type\n// previously imported from `'bullmq'` is replaced by `BullMqConnectionOptions`\n// from `./bullmq.config` (a self-contained structural mirror that does NOT\n// require the `bullmq` peer dep to type-check).\nimport {\n BULLMQ_CONNECTION,\n BULLMQ_RESOLVED_CONFIG,\n resolvePoolQueueName,\n type BullMqConnectionOptions,\n type BullMqResolvedConfig,\n} from './bullmq.config';\nimport {\n BootValidationError,\n ReservedPoolViolationError,\n} from './jobs-errors';\n\nconst DEFAULT_SHUTDOWN_TIMEOUT_MS = 30_000;\n\nexport interface JobWorkerModuleOptions {\n mode: 'embedded' | 'standalone';\n /**\n * Threads into the internal `JobsDomainModule.forRoot({ backend })`\n * import. Default `'drizzle'`. The boot-time validator runs for both\n * `'drizzle'` and `'bullmq'` (both persist `job` rows to Postgres);\n * `'memory'` skips it.\n */\n backend?: 'drizzle' | 'memory' | 'bullmq';\n /**\n * Active pool names. Defaults to every non-reserved pool in the resolved\n * config (i.e. `interactive`, `batch`, plus any user-defined pools).\n * Operators reduce this to one or two pools per worker process to scale\n * horizontally.\n */\n pools?: string[];\n /**\n * BULLMQ-1 Phase 1 — when `true`, `onModuleInit` activates **every** pool\n * in the resolved config, including the reserved `events_*` lanes. This is\n * how the standalone worker (`worker.ts`) drains bridge wrappers without\n * the consumer hand-listing `...BRIDGE_RESERVED_POOLS`. Mutually exclusive\n * with an explicit `pools` list — when both are set, `pools` wins (explicit\n * beats blanket) and `allPools` is ignored.\n *\n * `BridgeModule`'s reserved-pool guard short-circuits to \"pass\" when this\n * is `true`, since every reserved pool is provably being polled.\n */\n allPools?: boolean;\n /** SIGTERM drain budget. Default 30_000 ms. */\n shutdownTimeoutMs?: number;\n /**\n * Test-only — point the pool config loader at a specific YAML file.\n * Production code reads `${process.cwd()}/codegen.config.yaml`.\n */\n configPath?: string;\n /**\n * Forwarded into the inner `JobsDomainModule.forRoot()` call so the\n * worker module's caller can configure backend extensions in one place.\n */\n domainModuleExtensions?: JobsDomainModuleOptions['extensions'];\n /** Forwarded into `JobsDomainModule.forRoot()`. JOB-8 wires this. */\n multiTenant?: boolean;\n /**\n * Test-only escape hatch — when set, the module uses this factory\n * instead of `new JobWorker(...)` so unit tests can stub the worker\n * without spinning up the polling loop.\n */\n workerFactory?: (options: JobWorkerOptions) => Pick<JobWorker, 'onModuleInit' | 'onModuleDestroy'>;\n}\n\n/**\n * DI token for the resolved `JobWorkerModuleOptions`. Exported so other\n * subsystems can inject it `@Optional()` and inspect the active\n * configuration — e.g. `BridgeModule.onModuleInit` checks\n * `options.pools` against `BRIDGE_RESERVED_POOLS` to fail fast when a\n * reserved pool isn't being polled (BRIDGE-8).\n *\n * ADR-037: namespaced `Symbol.for(...)` (via `tokenKey()`) — matches by value\n * across runtime copies.\n */\nexport const JOB_WORKER_MODULE_OPTIONS = Symbol.for(tokenKey('jobs', 'worker-module-options'));\n\n/**\n * The lifecycle holder. Named `JobWorkerOrchestrator` in the spec to avoid\n * collision with `JobWorker` and `IJobOrchestrator`. Registered as a\n * provider on `JobWorkerModule`; Nest invokes `onModuleInit` /\n * `onModuleDestroy` automatically.\n */\n@Injectable()\nexport class JobWorkerOrchestrator implements OnModuleInit, OnModuleDestroy {\n private readonly logger = new Logger(JobWorkerOrchestrator.name);\n private readonly workers: Array<Pick<JobWorker, 'onModuleInit' | 'onModuleDestroy'>> = [];\n\n constructor(\n @Inject(JOB_ORCHESTRATOR) private readonly orchestrator: IJobOrchestrator,\n @Inject(JOB_RUN_SERVICE) private readonly runService: IJobRunService,\n @Inject(JOB_STEP_SERVICE) private readonly stepService: IJobStepService,\n @Inject(JOB_WORKER_MODULE_OPTIONS)\n private readonly options: JobWorkerModuleOptions,\n /**\n * Drizzle client is only required when `backend === 'drizzle'`. Made\n * `@Optional()` so memory-mode boots in `Test.createTestingModule`\n * without supplying a `DRIZZLE` provider.\n */\n @Optional() @Inject(DRIZZLE) private readonly db: DrizzleClient | null = null,\n /**\n * ADR-037 (package-mode DI): inject `ModuleRef` EXPLICITLY via `@Inject`\n * rather than relying on `design:paramtypes` reflection. The published\n * package bundle is built without `emitDecoratorMetadata` (tsup/esbuild\n * default), so a by-type injection here would resolve to `undefined` at\n * boot in package mode — breaking the worker entirely (the\n * `ModuleRef not available` throw). Vendored mode happened to work only\n * because the consumer's own `tsc` (emitDecoratorMetadata: true)\n * recompiled the source and emitted the metadata. The explicit token is\n * mode-agnostic. `ModuleRef` is always provided by `@nestjs/core`, so no\n * `@Optional()` is needed (it's a hard dependency of the worker path).\n */\n @Inject(ModuleRef) private readonly moduleRef?: ModuleRef,\n /**\n * BULLMQ-1 — resolved BullMQ connection + config, only bound when the\n * inner `JobsDomainModule` was booted with `backend: 'bullmq'`. `@Optional()`\n * so drizzle/memory boots see `null`.\n */\n @Optional()\n @Inject(BULLMQ_CONNECTION)\n private readonly bullConnection: BullMqConnectionOptions | null = null,\n @Optional()\n @Inject(BULLMQ_RESOLVED_CONFIG)\n private readonly bullConfig: BullMqResolvedConfig | null = null,\n ) {}\n\n // ============================================================================\n // Lifecycle\n // ============================================================================\n\n async onModuleInit(): Promise<void> {\n const backend = this.options.backend ?? 'drizzle';\n\n // (1) Pool config first — every later step needs the resolved map.\n const poolConfig = loadPoolConfig(this.options.configPath);\n\n // (2) Snapshot the registry. Decorators run at class-load time so the\n // map is fully populated before any module init fires.\n const entries = HandlerRegistry.getAll();\n\n // (3) Reserved-pool validation BEFORE the upsert. Persisting a\n // reserved-pool handler row would leave the DB in a bad state for\n // the next boot to clean up.\n this.assertNoReservedPoolHandlers(entries, poolConfig);\n\n // (4) Upsert `job` definitions. Drizzle: hash-gated `ON CONFLICT DO\n // UPDATE`. Memory: populates `MemoryJobStore.jobs` + handler-class\n // registry.\n const { orphaned } = await this.orchestrator.upsertJobRows(\n entries,\n poolConfig,\n );\n\n // (5) Boot validator — Drizzle only. Memory mode never has DB rows\n // to validate (Q4 resolution 2026-04-19); the equivalent\n // protection is `MemoryJobOrchestrator.start()` throwing\n // `JobTypeNotFoundError` synchronously for unknown types.\n if (backend !== 'memory' && orphaned.length > 0) {\n throw new BootValidationError(orphaned);\n }\n\n // (6) Resolve active pool list and spawn one worker per pool.\n // Precedence: explicit `pools` > `allPools` (incl. reserved) >\n // non-reserved default. BULLMQ-1 Phase 1 adds the `allPools` rung so\n // the standalone worker drains the reserved `events_*` bridge lanes.\n const activePools = this.options.pools\n ? this.options.pools\n : this.options.allPools\n ? allPoolNames(poolConfig)\n : allNonReservedPoolNames(poolConfig);\n\n for (const poolName of activePools) {\n const def = poolConfig.get(poolName);\n if (!def) {\n throw new Error(\n `JobWorkerModule: active pool '${poolName}' is not defined in ` +\n `the resolved pool config. Configured pools: [${[...poolConfig.keys()].join(', ')}].`,\n );\n }\n // `pool` here is the logical pool name (e.g. 'crm_sync') — the same\n // value the orchestrator persists into `job_run.pool` from\n // `@JobHandler.meta.pool`, and therefore the value the worker's\n // claim query filters on. `def.queue` is a display/routing alias\n // (e.g. 'jobs-crm-sync') used by BullMQ-style backends for queue\n // naming; it MUST NOT be passed as the claim-filter pool, or the\n // worker will never match any row and the pool silently never\n // drains. See v0.4.4 fix notes.\n const workerOptions: JobWorkerOptions = {\n pool: poolName,\n concurrency: def.concurrency,\n shutdownTimeoutMs:\n this.options.shutdownTimeoutMs ?? DEFAULT_SHUTDOWN_TIMEOUT_MS,\n };\n const worker = this.options.workerFactory\n ? this.options.workerFactory(workerOptions)\n : backend === 'bullmq'\n ? await this.spawnBullMQWorker(poolName, def.queue, def.concurrency, poolConfig)\n : this.spawnWorker(workerOptions);\n // `JobWorker` extends Nest's lifecycle hooks but the worker isn't\n // a Nest provider here (we manage the array ourselves). Call\n // `onModuleInit` to start the loop. The Drizzle/stub workers return\n // void; `BullMQJobWorker.onModuleInit` is async (it lazily loads the\n // optional `bullmq` package), so we `await` — awaiting a `void` is a\n // harmless no-op for the synchronous workers.\n await worker.onModuleInit();\n this.workers.push(worker);\n this.logger.log(\n `JobWorker started: pool='${poolName}' (queue='${def.queue}') ` +\n `concurrency=${def.concurrency} backend='${backend}'`,\n );\n }\n }\n\n async onModuleDestroy(): Promise<void> {\n // Tear down in reverse order so the most recently started worker\n // drains first — keeps the SIGTERM handler graph predictable.\n for (let i = this.workers.length - 1; i >= 0; i--) {\n const worker = this.workers[i];\n if (!worker) continue;\n try {\n await worker.onModuleDestroy();\n } catch (err) {\n this.logger.error(\n `JobWorker shutdown failed: ${(err as Error).message}`,\n );\n }\n }\n this.workers.length = 0;\n\n // BULLMQ-1 — close the orchestrator's producer-side Queue/FlowProducer\n // connections so the process can exit cleanly. The orchestrator is the\n // BullMQ producer; workers are the consumers (closed above).\n const orch = this.orchestrator as { closeConnections?: () => Promise<void> };\n if (typeof orch.closeConnections === 'function') {\n try {\n await orch.closeConnections();\n } catch (err) {\n this.logger.error(\n `BullMQ orchestrator connection close failed: ${(err as Error).message}`,\n );\n }\n }\n }\n\n // ============================================================================\n // Internals\n // ============================================================================\n\n /**\n * Walk every registered handler; collect any whose declared `pool`\n * targets a reserved pool from the resolved config. If non-empty,\n * throw `ReservedPoolViolationError` with the offender list so the\n * operator sees every violating class on a single boot.\n */\n private assertNoReservedPoolHandlers(\n entries: HandlerRegistryEntry[],\n poolConfig: PoolConfig,\n ): void {\n const offenders: Array<{ handlerClass: string; pool: string }> = [];\n for (const entry of entries) {\n // Framework-owned handlers (`@framework/*` job types) are allowed in\n // reserved pools — that is in fact the entire point of the reserved\n // `events_*` pools (ADR-022 + ADR-023). The reserved-pool guard\n // exists to keep USER handlers out, not the framework's own\n // bridge-delivery handler. BRIDGE-5 introduced this exemption.\n if (entry.type.startsWith('@framework/')) continue;\n const declaredPool = entry.meta.pool ?? 'batch';\n const def = poolConfig.get(declaredPool);\n if (def?.reserved) {\n offenders.push({\n handlerClass: entry.handlerClass.name,\n pool: declaredPool,\n });\n }\n }\n if (offenders.length > 0) {\n throw new ReservedPoolViolationError(offenders);\n }\n }\n\n /**\n * Production worker spawn. `JobWorker` requires `DRIZZLE` so this only\n * succeeds when the module was booted with `backend: 'drizzle'`. Memory\n * mode tests must supply `workerFactory` — the memory backend has no\n * polling loop equivalent (`MemoryJobOrchestrator` is direct-invocation\n * only).\n *\n * We instantiate outside the Nest container because the module spawns\n * N workers from a single options shape, which doesn't fit Nest's\n * \"one provider per token\" model. The dependencies are passed\n * positionally; the constructor's `@Inject` decorators are unused on\n * this path (Nest still uses them when `JobWorker` is a provider — e.g.\n * in JOB-6's standalone `worker.ts` entrypoint).\n */\n private spawnWorker(workerOptions: JobWorkerOptions): JobWorker {\n if (!this.db) {\n throw new Error(\n `JobWorkerModule: in-process worker spawning requires the Drizzle ` +\n `backend (no DRIZZLE provider available). Memory-mode tests must ` +\n `pass 'workerFactory' to inject a stub.`,\n );\n }\n if (!this.moduleRef) {\n throw new Error(\n `JobWorkerModule: ModuleRef not available — cannot construct JobWorker ` +\n `with handler DI support. Ensure the orchestrator is resolved through ` +\n `the Nest container (not instantiated manually in tests).`,\n );\n }\n return new JobWorker(\n this.db,\n this.orchestrator,\n this.runService,\n this.stepService,\n workerOptions,\n this.moduleRef,\n );\n }\n\n /**\n * BULLMQ-1 — spawn a per-pool `BullMQJobWorker`. Requires the Drizzle\n * client (the worker drives `job_run` as the source of truth) AND the\n * resolved BullMQ connection (bound by `JobsDomainModule` when\n * `backend: 'bullmq'`). The queue name is derived identically to the\n * orchestrator's `dispatch` via `resolvePoolQueueName(pool, …)` so producer\n * and consumer agree.\n */\n /**\n * #6 — async + dynamic-import. The `job-worker.bullmq-backend.ts` file is\n * filtered out of the vendor set for drizzle/memory installs (no `bullmq`\n * peer dep needed). The non-literal import specifier makes TS treat the\n * module as `any` so the consumer's tsc never tries to resolve an absent\n * file. This method is only entered when `backend === 'bullmq'` — at which\n * point the file IS vendored.\n */\n private async spawnBullMQWorker(\n pool: string,\n _queueAlias: string,\n concurrency: number,\n poolConfig: PoolConfig,\n ): Promise<Pick<JobWorker, 'onModuleInit' | 'onModuleDestroy'>> {\n if (!this.db) {\n throw new Error(\n `JobWorkerModule: BullMQ worker spawning requires the Drizzle client ` +\n `(no DRIZZLE provider available) — job_run remains the source of truth.`,\n );\n }\n if (!this.bullConnection) {\n throw new Error(\n `JobWorkerModule: BullMQ worker spawning requires a resolved ` +\n `BULLMQ_CONNECTION. Ensure JobsDomainModule was booted with ` +\n `backend: 'bullmq'.`,\n );\n }\n if (!this.moduleRef) {\n throw new Error(\n `JobWorkerModule: ModuleRef not available — cannot construct ` +\n `BullMQJobWorker with handler DI support.`,\n );\n }\n const queueName = resolvePoolQueueName(pool, this.bullConfig, poolConfig);\n const specifier = './job-worker.bullmq-backend';\n const mod = (await import(specifier)) as {\n BullMQJobWorker: new (...args: unknown[]) => Pick<\n JobWorker,\n 'onModuleInit' | 'onModuleDestroy'\n >;\n };\n return new mod.BullMQJobWorker(\n this.db,\n this.orchestrator,\n this.stepService,\n {\n pool,\n queueName,\n concurrency,\n connection: this.bullConnection,\n },\n this.moduleRef,\n );\n }\n}\n\n@Module({})\nexport class JobWorkerModule {\n static forRoot(opts: JobWorkerModuleOptions): DynamicModule {\n return {\n module: JobWorkerModule,\n imports: [\n JobsDomainModule.forRoot({\n backend: opts.backend ?? 'drizzle',\n extensions: opts.domainModuleExtensions,\n multiTenant: opts.multiTenant,\n }),\n ],\n providers: [\n { provide: JOB_WORKER_MODULE_OPTIONS, useValue: opts },\n JobWorkerOrchestrator,\n ],\n // BULLMQ-1 Phase 1 — export the options token so `BridgeModule`'s\n // reserved-pool guard (`onModuleInit`) can actually inject it.\n // Previously `exports: []` left the `@Optional()` inject resolving to\n // `undefined` and the guard silently no-opped (a dead check). With the\n // token exported the guard fires for real; consumers that omit the\n // reserved pools (and don't set `allPools`) now fail fast with\n // `BridgeReservedPoolsNotPolledError` — which is correct.\n exports: [JOB_WORKER_MODULE_OPTIONS],\n };\n }\n}\n","/**\n * Injection token for the cache service.\n *\n * Usage in use cases:\n * ```typescript\n * constructor(@Inject(CACHE) private readonly cache: ICacheService) {}\n * ```\n *\n * Services may also inject CACHE for reads (get, has) per ADR-003.\n *\n * ADR-037: namespaced `Symbol.for(...)` key (via `tokenKey()`) so the token matches\n * by value across import boundaries (package vs vendored runtime copy).\n */\nimport { tokenKey } from '../token-key';\n\nexport const CACHE = Symbol.for(tokenKey('cache', 'cache'));\n\n/**\n * Injection token for the default TTL (in seconds) passed from CacheModule.forRoot().\n * Optional — omit for no-expiry behavior.\n */\nexport const CACHE_DEFAULT_TTL = Symbol.for(tokenKey('cache', 'default-ttl'));\n","/**\n * CacheModule — DynamicModule factory for the cache subsystem.\n *\n * Usage in AppModule:\n * ```typescript\n * CacheModule.forRoot({ backend: 'drizzle', defaultTtl: 300 })\n * ```\n *\n * Usage in tests:\n * ```typescript\n * CacheModule.forRoot({ backend: 'memory' })\n * ```\n *\n * `global: true` means any module that needs ICacheService can inject CACHE\n * directly without importing CacheModule. Register once in AppModule.\n *\n * The drizzle backend requires DRIZZLE to be provided globally (e.g., via DatabaseModule).\n *\n * Async configuration (`forRootAsync`):\n * The async factory returns `CacheModuleOptions`; the CACHE provider then\n * receives DRIZZLE (for the drizzle backend) through Nest DI rather than\n * hand-constructing with `null` — see issue #108 which flagged the same\n * shape in `EventsModule.forRootAsync`. DRIZZLE is injected as optional\n * so memory-backend consumers are not required to wire DatabaseModule.\n */\nimport { Module, type DynamicModule } from '@nestjs/common';\nimport { CACHE, CACHE_DEFAULT_TTL } from './cache.tokens';\nimport { DRIZZLE } from '../../constants/tokens';\nimport type { DrizzleClient } from '../../types/drizzle';\nimport { DrizzleCacheService } from './cache.drizzle-backend';\nimport { MemoryCacheService } from './cache.memory-backend';\n\nexport interface CacheModuleOptions {\n backend: 'drizzle' | 'memory';\n /** Default TTL in seconds for entries that don't specify their own TTL. Null = no expiry. */\n defaultTtl?: number;\n}\n\nexport interface CacheModuleAsyncOptions {\n useFactory: (...args: unknown[]) => Promise<CacheModuleOptions> | CacheModuleOptions;\n inject?: unknown[];\n imports?: unknown[];\n}\n\n/** String token for the resolved CacheModuleOptions in the async path. */\nconst CACHE_MODULE_OPTIONS = 'CACHE_MODULE_OPTIONS' as const;\n\nfunction buildCacheAsync(\n options: CacheModuleOptions,\n db: DrizzleClient | null,\n): DrizzleCacheService | MemoryCacheService {\n const defaultTtl = options.defaultTtl ?? null;\n if (options.backend === 'drizzle') {\n if (!db) {\n throw new Error(\n \"CacheModule.forRootAsync: backend: 'drizzle' selected but DRIZZLE provider is not available. \" +\n 'Ensure DatabaseModule (or another provider exposing DRIZZLE) is imported before CacheModule.forRootAsync.',\n );\n }\n return new DrizzleCacheService(db, defaultTtl);\n }\n return new MemoryCacheService(defaultTtl);\n}\n\n@Module({})\nexport class CacheModule {\n static forRootAsync(asyncOptions: CacheModuleAsyncOptions): DynamicModule {\n return {\n module: CacheModule,\n global: true,\n imports: (asyncOptions.imports ?? []) as Parameters<typeof Module>[0]['imports'],\n providers: [\n {\n provide: CACHE_MODULE_OPTIONS,\n useFactory: asyncOptions.useFactory,\n inject: (asyncOptions.inject ?? []) as (string | symbol | Function)[],\n },\n {\n provide: CACHE,\n useFactory: (options: CacheModuleOptions, db: DrizzleClient | null) =>\n buildCacheAsync(options, db),\n inject: [CACHE_MODULE_OPTIONS, { token: DRIZZLE, optional: true }],\n },\n // Alias the concrete classes to CACHE for typed injection.\n { provide: DrizzleCacheService, useExisting: CACHE },\n { provide: MemoryCacheService, useExisting: CACHE },\n ],\n exports: [CACHE],\n };\n }\n\n static forRoot(options: CacheModuleOptions = { backend: 'drizzle' }): DynamicModule {\n const ConcreteClass = options.backend === 'drizzle' ? DrizzleCacheService : MemoryCacheService;\n\n const providers = options.defaultTtl !== undefined\n ? [\n // Register the concrete class as the canonical instance\n ConcreteClass,\n { provide: CACHE_DEFAULT_TTL, useValue: options.defaultTtl },\n // CACHE token points to the same instance — no duplicate\n { provide: CACHE, useExisting: ConcreteClass },\n ]\n : [\n ConcreteClass,\n { provide: CACHE, useExisting: ConcreteClass },\n ];\n\n return {\n module: CacheModule,\n global: true,\n providers,\n exports: [CACHE],\n };\n }\n}\n","/**\n * DrizzleCacheService — Postgres-backed ICacheService via Drizzle ORM.\n *\n * Storage: `cache_entries` table with key (text pk), value (jsonb), expiresAt (timestamp).\n * TTL enforcement: reads filter by `expiresAt > now() OR expiresAt IS NULL`.\n * Prefix invalidation: `DELETE WHERE key LIKE 'escaped_prefix%'`.\n *\n * Lifecycle:\n * - OnModuleInit: starts periodic cleanup of expired entries.\n * Uses the Jobs subsystem if available (optional injection); falls back to setInterval.\n * - OnModuleDestroy: clears the setInterval timer if used.\n *\n * Error behavior per ADR-008:\n * - get() / has() return null/false on any error (never throw for reads).\n * - set() / delete() / invalidateByPrefix() throw on failure.\n */\nimport { Injectable, Inject, Optional, type OnModuleInit, type OnModuleDestroy } from '@nestjs/common';\nimport { gt, or, like, sql, eq } from 'drizzle-orm';\nimport type { DrizzleClient } from '../../types/drizzle';\nimport type { ICacheService } from './cache.protocol';\nimport { cacheEntries } from './cache.schema';\nimport { DRIZZLE } from '../../constants/tokens';\nimport { CACHE_DEFAULT_TTL } from './cache.tokens';\n\n// Re-export for backward compatibility\nexport { CACHE_DEFAULT_TTL } from './cache.tokens';\n\n/** Cleanup interval in milliseconds when jobs subsystem is unavailable. */\nconst CLEANUP_INTERVAL_MS = 5 * 60 * 1000; // 5 minutes\n\n@Injectable()\nexport class DrizzleCacheService implements ICacheService, OnModuleInit, OnModuleDestroy {\n private cleanupTimer: ReturnType<typeof setInterval> | null = null;\n /** In-flight getOrSet promises — keyed by cache key to deduplicate stampedes. */\n private readonly inflight = new Map<string, Promise<unknown>>();\n\n constructor(\n @Inject(DRIZZLE) private readonly db: DrizzleClient,\n @Optional() @Inject(CACHE_DEFAULT_TTL) private readonly defaultTtl: number | null = null,\n ) {}\n\n async onModuleInit(): Promise<void> {\n this.cleanupTimer = setInterval(() => {\n void this.deleteExpired();\n }, CLEANUP_INTERVAL_MS);\n }\n\n async onModuleDestroy(): Promise<void> {\n if (this.cleanupTimer !== null) {\n clearInterval(this.cleanupTimer);\n this.cleanupTimer = null;\n }\n }\n\n async get<T = unknown>(key: string): Promise<T | null> {\n try {\n const rows = await this.db\n .select()\n .from(cacheEntries)\n .where(\n sql`${cacheEntries.key} = ${key} AND (${cacheEntries.expiresAt} IS NULL OR ${cacheEntries.expiresAt} > now())`,\n )\n .limit(1);\n\n if (rows.length === 0) return null;\n return rows[0]!.value as T;\n } catch {\n return null;\n }\n }\n\n async set<T = unknown>(key: string, value: T, ttlSeconds?: number): Promise<void> {\n const effectiveTtl = ttlSeconds ?? this.defaultTtl ?? null;\n const expiresAt =\n effectiveTtl !== null\n ? new Date(Date.now() + effectiveTtl * 1000)\n : null;\n\n const jsonValue = value as Parameters<typeof cacheEntries.value.mapFromDriverValue>[0];\n await this.db\n .insert(cacheEntries)\n .values({ key, value: jsonValue, expiresAt })\n .onConflictDoUpdate({\n target: cacheEntries.key,\n set: { value: jsonValue, expiresAt },\n });\n }\n\n async delete(key: string): Promise<void> {\n await this.db.delete(cacheEntries).where(eq(cacheEntries.key, key));\n }\n\n async invalidateByPrefix(prefix: string): Promise<number> {\n // Escape LIKE wildcards to prevent prefix characters from matching unintended entries\n const escaped = prefix.replace(/%/g, '\\\\%').replace(/_/g, '\\\\_');\n const result = await this.db\n .delete(cacheEntries)\n .where(like(cacheEntries.key, `${escaped}%`))\n .returning({ key: cacheEntries.key });\n return result.length;\n }\n\n async has(key: string): Promise<boolean> {\n try {\n const result = await this.get(key);\n return result !== null;\n } catch {\n return false;\n }\n }\n\n async getOrSet<T = unknown>(\n key: string,\n factory: () => Promise<T>,\n ttlSeconds?: number,\n ): Promise<T> {\n // Fast path: cache hit\n const cached = await this.get<T>(key);\n if (cached !== null) return cached;\n\n // Stampede protection: if another call is already computing this key, reuse its promise\n const existing = this.inflight.get(key) as Promise<T> | undefined;\n if (existing !== undefined) return existing;\n\n const promise = factory().then(async (value) => {\n await this.set(key, value, ttlSeconds);\n return value;\n }).finally(() => {\n this.inflight.delete(key);\n });\n\n this.inflight.set(key, promise as Promise<unknown>);\n return promise;\n }\n\n /** Remove all expired entries. Called by the cleanup timer. */\n private async deleteExpired(): Promise<void> {\n try {\n await this.db\n .delete(cacheEntries)\n .where(\n or(\n gt(sql`now()`, cacheEntries.expiresAt),\n ),\n );\n } catch {\n // Cleanup failures are non-fatal — stale rows are filtered at read time\n }\n }\n}\n","/**\n * Drizzle schema for the cache_entries table.\n *\n * This table backs the DrizzleCacheService. TTL is enforced by filtering\n * on expiresAt at read time; a periodic cleanup job removes stale rows.\n *\n * Indexes:\n * - PRIMARY KEY on key (point-lookup)\n * - (expiresAt) for the cleanup query\n */\nimport { pgTable, text, jsonb, timestamp } from 'drizzle-orm/pg-core';\nimport type { InferSelectModel } from 'drizzle-orm';\n\nexport const cacheEntries = pgTable(\n 'cache_entries',\n {\n /** Cache key — primary key, text (not uuid) to support arbitrary key namespacing. */\n key: text('key').primaryKey(),\n /** Cached value serialised as JSONB. */\n value: jsonb('value').notNull(),\n /** NULL means the entry never expires. */\n expiresAt: timestamp('expires_at', { withTimezone: true }),\n },\n // Index: add (expires_at) via migration for cleanup queries\n);\n\nexport type CacheEntry = InferSelectModel<typeof cacheEntries>;\n","/**\n * MemoryCacheService — Map-backed ICacheService for tests and development.\n *\n * TTL is enforced via setTimeout — expired entries are deleted from the Map\n * when the timer fires. get() / has() also check the expiry time defensively\n * in case the timer fires late.\n *\n * No lifecycle hooks required — all state is in-process.\n *\n * Error behavior:\n * - get() / has() never throw; they return null/false.\n * - set() / delete() / invalidateByPrefix() throw on failure (consistent with protocol).\n */\nimport { Injectable, Inject, Optional } from '@nestjs/common';\nimport type { ICacheService } from './cache.protocol';\nimport { CACHE_DEFAULT_TTL } from './cache.tokens';\n\ninterface CacheRecord {\n value: unknown;\n expiresAt: number | null; // epoch ms, or null for no expiry\n}\n\n@Injectable()\nexport class MemoryCacheService implements ICacheService {\n private readonly store = new Map<string, CacheRecord>();\n private readonly timers = new Map<string, ReturnType<typeof setTimeout>>();\n /** In-flight getOrSet promises — keyed by cache key to deduplicate stampedes. */\n private readonly inflight = new Map<string, Promise<unknown>>();\n\n constructor(\n @Optional() @Inject(CACHE_DEFAULT_TTL) private readonly defaultTtl: number | null = null,\n ) {}\n\n async get<T = unknown>(key: string): Promise<T | null> {\n const record = this.store.get(key);\n if (!record) return null;\n if (record.expiresAt !== null && record.expiresAt <= Date.now()) {\n this.evict(key);\n return null;\n }\n return record.value as T;\n }\n\n async set<T = unknown>(key: string, value: T, ttlSeconds?: number): Promise<void> {\n const effectiveTtl = ttlSeconds ?? this.defaultTtl ?? null;\n\n // Clear any existing timer for this key\n this.clearTimer(key);\n\n const expiresAt = effectiveTtl !== null ? Date.now() + effectiveTtl * 1000 : null;\n this.store.set(key, { value, expiresAt });\n\n if (effectiveTtl !== null) {\n const timer = setTimeout(() => this.evict(key), effectiveTtl * 1000);\n this.timers.set(key, timer);\n }\n }\n\n async delete(key: string): Promise<void> {\n this.evict(key);\n }\n\n async invalidateByPrefix(prefix: string): Promise<number> {\n let count = 0;\n for (const key of this.store.keys()) {\n if (key.startsWith(prefix)) {\n this.evict(key);\n count++;\n }\n }\n return count;\n }\n\n async has(key: string): Promise<boolean> {\n const value = await this.get(key);\n return value !== null;\n }\n\n async getOrSet<T = unknown>(\n key: string,\n factory: () => Promise<T>,\n ttlSeconds?: number,\n ): Promise<T> {\n // Fast path: cache hit\n const cached = await this.get<T>(key);\n if (cached !== null) return cached;\n\n // Stampede protection: if another call is already computing this key, reuse its promise\n const existing = this.inflight.get(key) as Promise<T> | undefined;\n if (existing !== undefined) return existing;\n\n const promise = factory().then(async (value) => {\n await this.set(key, value, ttlSeconds);\n return value;\n }).finally(() => {\n this.inflight.delete(key);\n });\n\n this.inflight.set(key, promise as Promise<unknown>);\n return promise;\n }\n\n /** Remove a key from store and cancel its expiry timer. */\n private evict(key: string): void {\n this.store.delete(key);\n this.clearTimer(key);\n }\n\n private clearTimer(key: string): void {\n const timer = this.timers.get(key);\n if (timer !== undefined) {\n clearTimeout(timer);\n this.timers.delete(key);\n }\n }\n}\n","/**\n * Storage subsystem — local filesystem backend\n *\n * Writes files to `{basePath}/{key}` on the local filesystem.\n * Suitable for development only — use an S3/GCS backend in production.\n *\n * - Creates intermediate directories automatically (mkdirSync recursive)\n * - getUrl returns a `file://` URI pointing to the absolute path\n * - All methods throw on failure\n * - resolvePath validates against path traversal attacks\n */\nimport {\n createReadStream,\n existsSync,\n mkdirSync,\n readdirSync,\n readFileSync,\n statSync,\n unlinkSync,\n writeFileSync,\n} from 'fs';\nimport { dirname, join, relative, resolve, sep } from 'path';\nimport { Readable } from 'stream';\nimport type { IStorageService } from './storage.protocol';\nimport { toBuffer } from './storage.utils';\n\nexport class LocalStorageBackend implements IStorageService {\n private readonly basePath: string;\n\n constructor(basePath: string = './storage') {\n this.basePath = resolve(basePath);\n }\n\n async upload(key: string, data: Buffer | ReadableStream, contentType?: string): Promise<string> {\n const filePath = this.resolvePath(key);\n mkdirSync(dirname(filePath), { recursive: true });\n\n const buffer = await toBuffer(data);\n writeFileSync(filePath, buffer);\n return key;\n }\n\n async download(key: string): Promise<Buffer> {\n const filePath = this.resolvePath(key);\n if (!existsSync(filePath)) {\n throw new Error(`Storage: file not found: ${key}`);\n }\n return readFileSync(filePath);\n }\n\n async delete(key: string): Promise<void> {\n const filePath = this.resolvePath(key);\n if (!existsSync(filePath)) {\n throw new Error(`Storage: file not found: ${key}`);\n }\n unlinkSync(filePath);\n }\n\n async getUrl(key: string, _expiresInSeconds?: number): Promise<string> {\n const filePath = this.resolvePath(key);\n if (!existsSync(filePath)) {\n throw new Error(`Storage: file not found: ${key}`);\n }\n return `file://${filePath}`;\n }\n\n async exists(key: string): Promise<boolean> {\n try {\n return existsSync(this.resolvePath(key));\n } catch {\n // resolvePath throws on traversal attempt — treat as non-existent\n return false;\n }\n }\n\n async list(prefix?: string): Promise<string[]> {\n const keys = this.listRecursive(this.basePath);\n if (prefix === undefined) return keys;\n return keys.filter((k) => k.startsWith(prefix));\n }\n\n async downloadStream(key: string): Promise<ReadableStream> {\n const filePath = this.resolvePath(key);\n if (!existsSync(filePath)) {\n throw new Error(`Storage: file not found: ${key}`);\n }\n const nodeStream = createReadStream(filePath);\n return Readable.toWeb(nodeStream) as ReadableStream;\n }\n\n private resolvePath(key: string): string {\n const resolved = resolve(this.basePath, key);\n if (!resolved.startsWith(this.basePath + sep)) {\n throw new Error(`Invalid storage key (path traversal attempt): ${key}`);\n }\n return resolved;\n }\n\n /** Recursively list all files under dir, returning keys relative to basePath. */\n private listRecursive(dir: string): string[] {\n if (!existsSync(dir)) return [];\n const keys: string[] = [];\n for (const entry of readdirSync(dir, { withFileTypes: true })) {\n const full = join(dir, entry.name);\n if (entry.isDirectory()) {\n keys.push(...this.listRecursive(full));\n } else {\n keys.push(relative(this.basePath, full));\n }\n }\n return keys;\n }\n}\n","/**\n * Storage subsystem — shared utilities\n */\n\n/**\n * Convert a Buffer or Web ReadableStream to a Node.js Buffer.\n */\nexport async function toBuffer(data: Buffer | ReadableStream): Promise<Buffer> {\n if (Buffer.isBuffer(data)) {\n return data;\n }\n const reader = (data as ReadableStream<Uint8Array>).getReader();\n const chunks: Uint8Array[] = [];\n while (true) {\n const { done, value } = await reader.read();\n if (done) break;\n if (value) chunks.push(value);\n }\n return Buffer.concat(chunks);\n}\n","/**\n * Storage subsystem — in-memory backend\n *\n * Stores files as Buffers in a Map. Intended for unit tests only.\n * All state is lost when the process exits.\n *\n * - getUrl returns `memory://{key}` (not a real URL, useful for assertions)\n * - All methods throw on failure (missing keys, etc.)\n */\nimport type { IStorageService } from './storage.protocol';\nimport { toBuffer } from './storage.utils';\n\ninterface MemoryEntry {\n data: Buffer;\n contentType?: string;\n}\n\nexport class MemoryStorageBackend implements IStorageService {\n private readonly store = new Map<string, MemoryEntry>();\n\n async upload(key: string, data: Buffer | ReadableStream, contentType?: string): Promise<string> {\n const buffer = await toBuffer(data);\n this.store.set(key, { data: buffer, contentType });\n return key;\n }\n\n async download(key: string): Promise<Buffer> {\n const entry = this.store.get(key);\n if (!entry) {\n throw new Error(`Storage: file not found: ${key}`);\n }\n return entry.data;\n }\n\n async delete(key: string): Promise<void> {\n if (!this.store.has(key)) {\n throw new Error(`Storage: file not found: ${key}`);\n }\n this.store.delete(key);\n }\n\n async getUrl(key: string, _expiresInSeconds?: number): Promise<string> {\n if (!this.store.has(key)) {\n throw new Error(`Storage: file not found: ${key}`);\n }\n return `memory://${key}`;\n }\n\n async exists(key: string): Promise<boolean> {\n return this.store.has(key);\n }\n\n async list(prefix?: string): Promise<string[]> {\n const keys = Array.from(this.store.keys());\n if (prefix === undefined) return keys;\n return keys.filter((k) => k.startsWith(prefix));\n }\n\n async downloadStream(key: string): Promise<ReadableStream> {\n const buffer = await this.download(key);\n return new ReadableStream<Uint8Array>({\n start(controller) {\n controller.enqueue(new Uint8Array(buffer));\n controller.close();\n },\n });\n }\n\n /** Clear all stored files. Useful for test teardown. */\n clear(): void {\n this.store.clear();\n }\n\n /** Return number of stored files. Useful for test assertions. */\n size(): number {\n return this.store.size;\n }\n}\n","/**\n * Storage subsystem — NestJS module factory\n *\n * Register once in AppModule (global: true means all other modules can inject\n * STORAGE without importing StorageModule themselves):\n *\n * ```typescript\n * // app.module.ts\n * @Module({\n * imports: [\n * StorageModule.forRoot({ backend: 'local', basePath: './uploads' }),\n * ],\n * })\n * export class AppModule {}\n * ```\n *\n * Swap to memory backend in tests:\n * ```typescript\n * Test.createTestingModule({\n * imports: [StorageModule.forRoot({ backend: 'memory' })],\n * });\n * ```\n */\nimport { type DynamicModule, Module } from '@nestjs/common';\nimport { LocalStorageBackend } from './storage.local-backend';\nimport { MemoryStorageBackend } from './storage.memory-backend';\nimport { STORAGE } from './storage.tokens';\n\nexport interface StorageModuleOptions {\n /** Which backend to activate. */\n backend: 'local' | 'memory';\n /**\n * Base path for the local backend (resolved to an absolute path).\n * Ignored when backend is 'memory'. Defaults to `./storage`.\n */\n basePath?: string;\n}\n\n@Module({})\nexport class StorageModule {\n static forRoot(options: StorageModuleOptions = { backend: 'local' }): DynamicModule {\n const provider =\n options.backend === 'local'\n ? {\n provide: STORAGE,\n useFactory: () => new LocalStorageBackend(options.basePath ?? './storage'),\n }\n : {\n provide: STORAGE,\n useClass: MemoryStorageBackend,\n };\n\n return {\n module: StorageModule,\n global: true,\n providers: [provider],\n exports: [STORAGE],\n };\n }\n}\n","/**\n * Injection token for the storage service.\n *\n * Usage in use cases:\n * ```typescript\n * constructor(@Inject(STORAGE) private readonly storage: IStorageService) {}\n * ```\n *\n * ADR-037: namespaced `Symbol.for(...)` key (via `tokenKey()`) so the token matches\n * by value across import boundaries (package vs vendored runtime copy).\n */\nimport { tokenKey } from '../token-key';\n\nexport const STORAGE = Symbol.for(tokenKey('storage', 'storage'));\n","/**\n * Observability combiner subsystem — DI tokens (ADR-025, OBS-5).\n *\n * String constants (not Symbols), matching the events / bridge / integration\n * convention. The jobs subsystem uses Symbols for its analogous tokens;\n * observability stays internally consistent with its sibling combiner\n * (bridge) because the two are structurally paired (ADR-025).\n *\n * Usage in consumers:\n * ```ts\n * constructor(@Inject(OBSERVABILITY) private readonly obs: IObservability) {}\n * ```\n */\n\n/**\n * Token for the `IObservability` composer facade (OBS-5). Resolves to the\n * single `ObservabilityService` instance registered by\n * `ObservabilityModule.forRoot(...)`.\n */\nexport const OBSERVABILITY = 'OBSERVABILITY' as const;\n\n/**\n * Token for the resolved `ObservabilityModuleOptions` object. Provided by\n * `ObservabilityModule.forRoot(...)`. Reserved for phase 2 — the current\n * options shape is empty; OBS-6 will extend it with a `reporters` field.\n */\nexport const OBSERVABILITY_MODULE_OPTIONS = 'OBSERVABILITY_MODULE_OPTIONS' as const;\n","/**\n * ObservabilityModule — combiner subsystem (ADR-025, OBS-5, OBS-6).\n *\n * Composes the jobs, bridge, and integration read ports into a single\n * `IObservability` facade. Owned by no sibling subsystem; it consumes\n * their tokens via DI, which the consumer app wires by registering the\n * sibling modules in the right order (like BridgeModule — the named\n * precedent in ADR-025).\n *\n * Consumer wiring (register AFTER the composed sibling modules):\n * ```ts\n * @Module({\n * imports: [\n * EventsModule.forRoot({ backend: 'drizzle' }),\n * JobsDomainModule.forRoot({ backend: 'drizzle' }),\n * BridgeModule.forRoot({ backend: 'drizzle' }),\n * IntegrationModule.forRoot({ backend: 'drizzle' }),\n * ObservabilityModule.forRoot({\n * reporters: {\n * bridgeMetrics: {\n * enabled: true,\n * intervalMs: 60_000,\n * windowHours: 1,\n * },\n * },\n * }),\n * ],\n * })\n * class AppModule {}\n * ```\n *\n * # No `backend` option — intentional\n *\n * Unlike ADR-008 infrastructure subsystems (events / jobs / cache /\n * storage), observability is a combiner per ADR-025 and owns no durable\n * state. The \"backend\" is whichever backends the composed subsystems are\n * running — portability is inherited, not declared. See ADR-025 §4 (when\n * to pick combiner vs. infrastructure) and\n * `.claude/skills/observability/SKILL.md` §1.\n *\n * # Graceful sibling absence\n *\n * The consumed sibling tokens are `@Optional()` inside\n * `ObservabilityService`. An app that only installed a subset of the\n * composed subsystems can still register `ObservabilityModule`; the\n * methods whose sibling is missing return empty shapes.\n *\n * # Reporters (OBS-6)\n *\n * Internal consumers of the `OBSERVABILITY` facade — auto-registered\n * when the matching `reporters.*` key is present and enabled. Reporters\n * are NOT added to `exports`; they are a module-internal concern.\n * Consumers configure them via options; they never import the reporter\n * classes directly.\n */\nimport { Module, type DynamicModule, type Provider } from '@nestjs/common';\n\nimport {\n OBSERVABILITY,\n OBSERVABILITY_MODULE_OPTIONS,\n} from './observability.tokens';\nimport { ObservabilityService } from './observability.service';\nimport { BridgeMetricsReporter } from './reporters/bridge-metrics.reporter';\n\n/**\n * Config for the bridge-delivery sampler (OBS-6). All fields are required\n * when `enabled: true` — the config is declarative and explicit; there\n * are no hidden defaults. Lives on the module (not the reporter file) so\n * the module's options type stays the single authoritative schema for\n * everything `forRoot` accepts.\n */\nexport interface BridgeMetricsReporterConfig {\n /** Master switch. Reporter is only registered as a provider when this\n * is `true` (see `forRoot`). */\n enabled: boolean;\n /** Sampling period in ms. Must be `> 0` when `enabled: true`. */\n intervalMs: number;\n /** Trailing window (hours) passed to `getBridgeDeliveryHistogram`.\n * Must be `> 0` when `enabled: true`. */\n windowHours: number;\n /** Forwarded verbatim to `IObservability.getBridgeDeliveryHistogram`.\n * - `undefined` — sibling default semantics\n * - `null` — explicit cross-tenant match\n * - `string` — filter to that single tenant */\n tenantId?: string | null;\n}\n\n/**\n * Named-map of reporter configs. Named, not array, so consumers can toggle\n * individual reporters by key without juggling order and so future reporters\n * can be added without breaking existing configs.\n */\nexport interface ObservabilityReportersOptions {\n bridgeMetrics?: BridgeMetricsReporterConfig;\n}\n\n/**\n * Options for `ObservabilityModule.forRoot()`. Currently only `reporters`;\n * room to grow (sampling, exporters) without changing the module signature.\n */\nexport interface ObservabilityModuleOptions {\n reporters?: ObservabilityReportersOptions;\n}\n\n@Module({})\nexport class ObservabilityModule {\n static forRoot(options: ObservabilityModuleOptions = {}): DynamicModule {\n const providers: Provider[] = [\n // Expose the resolved options so internal reporters can read their\n // own config via `OBSERVABILITY_MODULE_OPTIONS`.\n { provide: OBSERVABILITY_MODULE_OPTIONS, useValue: options },\n // Register the concrete class as the canonical instance.\n ObservabilityService,\n // OBSERVABILITY token points at the same instance — consumers inject\n // the token, not the class, per ADR-025 §Shape (index.ts does NOT\n // export `ObservabilityService`).\n { provide: OBSERVABILITY, useExisting: ObservabilityService },\n ];\n\n // Reporters: auto-registered when enabled, not added to `exports`.\n // They are internal consumers of OBSERVABILITY; consumers configure\n // them via options rather than importing the classes.\n if (options.reporters?.bridgeMetrics?.enabled === true) {\n providers.push(BridgeMetricsReporter);\n }\n\n return {\n module: ObservabilityModule,\n global: true,\n providers,\n exports: [OBSERVABILITY, OBSERVABILITY_MODULE_OPTIONS],\n };\n }\n}\n","/**\n * ObservabilityService — `IObservability` combiner implementation\n * (ADR-025, OBS-5).\n *\n * Composes read methods across the jobs, bridge, and integration subsystems via\n * DI. Owns no state, no schema, no SQL. Every method is a one-line\n * delegation to the sibling port that already encodes the semantics.\n *\n * # Missing-port degradation\n *\n * Every sibling is injected with `@Optional()`. When the consumer's app\n * has not wired a given subsystem, the corresponding field is `undefined`\n * and the delegating method returns an empty shape:\n * - array methods return `[]`\n * - `getBridgeDeliveryHistogram` returns `{ pending: 0, delivered: 0,\n * skipped: 0, failed: 0 }` (matches the bridge protocol's fixed-keys\n * contract so consumers can render a 4-row chart unconditionally).\n *\n * Graceful absence is the whole point of the combiner pattern (ADR-025\n * §Shape, constraint 3) — a consumer that only installed the jobs\n * subsystem can still inject `OBSERVABILITY` and get useful job reads\n * without wiring the rest.\n *\n * # Multi-tenancy\n *\n * `tenantId` passes VERBATIM from the public method to the owning port.\n * `ObservabilityService` never re-implements tenant filtering. See\n * `.claude/skills/observability/SKILL.md` §3 and ADR-025.\n */\nimport { Inject, Injectable, Optional } from '@nestjs/common';\n\nimport { JOB_RUN_SERVICE } from '../jobs/jobs-domain.tokens';\nimport type {\n IJobRunService,\n JobRunFailure,\n JobRunPage,\n JobRunSummary,\n ListJobRunsQuery,\n PoolStatusCount,\n} from '../jobs/job-run-service.protocol';\n\nimport { EVENT_READ_PORT } from '../events/events.tokens';\nimport type {\n EventPage,\n EventSummary,\n IEventReadPort,\n ListEventsQuery,\n} from '../events/event-read.protocol';\n\nimport { BRIDGE_DELIVERY_REPO } from '../bridge/bridge.tokens';\nimport type { IJobBridge, StatusHistogram } from '../bridge/bridge.protocol';\n\nimport { INTEGRATION_CURSOR_STORE, INTEGRATION_RUN_RECORDER } from '../integration/integration.tokens';\nimport type {\n IIntegrationRunRecorder,\n IntegrationRunSummary,\n} from '../integration/integration-run-recorder.protocol';\nimport type {\n CursorSnapshot,\n ICursorStore,\n} from '../integration/integration-cursor-store.protocol';\n\nimport type {\n CorrelationTimeline,\n CorrelationTimelineEntry,\n IObservability,\n} from './observability.protocol';\n\n/**\n * Safety bound on how many pages the correlation timeline will walk when\n * draining a sibling port. A single run tree producing more than\n * 50 pages × default page size of correlated rows is pathological; cap to\n * keep the stitch bounded rather than unbounded-loop on bad data.\n */\nconst MAX_TIMELINE_PAGES = 50;\n\n@Injectable()\nexport class ObservabilityService implements IObservability {\n /**\n * All-zero histogram used when the bridge subsystem is absent. Matches\n * the bridge protocol's \"fixed keys, zero-filled\" contract so consumers\n * never branch on presence.\n */\n private static readonly EMPTY_HISTOGRAM: StatusHistogram = {\n pending: 0,\n delivered: 0,\n skipped: 0,\n failed: 0,\n };\n\n /** Empty page used when a sibling read port is absent. */\n private static readonly EMPTY_JOB_RUN_PAGE: JobRunPage = {\n items: [],\n nextCursor: null,\n };\n private static readonly EMPTY_EVENT_PAGE: EventPage = {\n items: [],\n nextCursor: null,\n };\n\n constructor(\n @Optional()\n @Inject(JOB_RUN_SERVICE)\n private readonly jobRuns?: IJobRunService,\n @Optional()\n @Inject(BRIDGE_DELIVERY_REPO)\n private readonly bridge?: IJobBridge,\n @Optional()\n @Inject(INTEGRATION_RUN_RECORDER)\n private readonly integrationRuns?: IIntegrationRunRecorder,\n @Optional()\n @Inject(INTEGRATION_CURSOR_STORE)\n private readonly cursors?: ICursorStore,\n @Optional()\n @Inject(EVENT_READ_PORT)\n private readonly events?: IEventReadPort | null,\n ) {}\n\n async getPoolDepths(tenantId?: string | null): Promise<PoolStatusCount[]> {\n if (!this.jobRuns) return [];\n return this.jobRuns.countByPoolAndStatus(tenantId);\n }\n\n async getRecentFailedJobs(\n limit: number,\n tenantId?: string | null,\n ): Promise<JobRunFailure[]> {\n if (!this.jobRuns) return [];\n return this.jobRuns.listRecentFailed(limit, tenantId);\n }\n\n async getBridgeDeliveryHistogram(\n windowHours: number,\n tenantId?: string | null,\n ): Promise<StatusHistogram> {\n if (!this.bridge) return { ...ObservabilityService.EMPTY_HISTOGRAM };\n return this.bridge.getStatusHistogram(windowHours, tenantId);\n }\n\n async getRecentIntegrationRuns(\n limit: number,\n subscriptionId?: string,\n tenantId?: string | null,\n ): Promise<IntegrationRunSummary[]> {\n if (!this.integrationRuns) return [];\n return this.integrationRuns.listRecent(limit, subscriptionId, tenantId);\n }\n\n async getCursors(tenantId?: string | null): Promise<CursorSnapshot[]> {\n if (!this.cursors) return [];\n return this.cursors.listAll(tenantId);\n }\n\n async listJobRuns(query?: ListJobRunsQuery): Promise<JobRunPage> {\n if (!this.jobRuns) {\n return { ...ObservabilityService.EMPTY_JOB_RUN_PAGE };\n }\n return this.jobRuns.listJobRuns(query);\n }\n\n async listEvents(query?: ListEventsQuery): Promise<EventPage> {\n if (!this.events) {\n return { ...ObservabilityService.EMPTY_EVENT_PAGE };\n }\n return this.events.listEvents(query);\n }\n\n async getCorrelationTimeline(\n rootRunId: string,\n tenantId?: string | null,\n ): Promise<CorrelationTimeline> {\n const runs = await this.collectRuns(rootRunId, tenantId);\n const events = await this.collectEvents(rootRunId, tenantId);\n\n const entries: CorrelationTimelineEntry[] = [\n ...runs.map(\n (run): CorrelationTimelineEntry => ({\n kind: 'job_run',\n at: run.createdAt,\n run,\n }),\n ),\n ...events.map(\n (event): CorrelationTimelineEntry => ({\n kind: 'event',\n at: event.occurredAt,\n event,\n }),\n ),\n ];\n\n // Ascending chronological order. Stable tie-break: job runs before\n // events at the same instant (the run that emits an event precedes it).\n entries.sort((a, b) => {\n const dt = a.at.getTime() - b.at.getTime();\n if (dt !== 0) return dt;\n if (a.kind === b.kind) return 0;\n return a.kind === 'job_run' ? -1 : 1;\n });\n\n const startedAt = entries.length > 0 ? entries[0]!.at : null;\n const lastActivityAt =\n entries.length > 0 ? entries[entries.length - 1]!.at : null;\n\n return {\n rootRunId,\n entries,\n summary: {\n runCount: runs.length,\n eventCount: events.length,\n startedAt,\n lastActivityAt,\n },\n };\n }\n\n /**\n * Drain every `job_run` sharing `rootRunId` by walking the keyset cursor.\n * Empty when the jobs subsystem is absent.\n */\n private async collectRuns(\n rootRunId: string,\n tenantId?: string | null,\n ): Promise<JobRunSummary[]> {\n if (!this.jobRuns) return [];\n const out: JobRunSummary[] = [];\n let cursor: string | undefined;\n for (let page = 0; page < MAX_TIMELINE_PAGES; page += 1) {\n const result = await this.jobRuns.listJobRuns({\n rootRunId,\n tenantId,\n cursor,\n });\n out.push(...result.items);\n if (!result.nextCursor) break;\n cursor = result.nextCursor;\n }\n return out;\n }\n\n /**\n * Drain every `domain_event` whose `metadata.rootRunId` matches by walking\n * the keyset cursor. Empty when the events read port is absent.\n */\n private async collectEvents(\n rootRunId: string,\n tenantId?: string | null,\n ): Promise<EventSummary[]> {\n if (!this.events) return [];\n const out: EventSummary[] = [];\n let cursor: string | undefined;\n for (let page = 0; page < MAX_TIMELINE_PAGES; page += 1) {\n const result = await this.events.listEvents({\n rootRunId,\n tenantId,\n cursor,\n });\n out.push(...result.items);\n if (!result.nextCursor) break;\n cursor = result.nextCursor;\n }\n return out;\n }\n}\n","/**\n * Integration subsystem — DI tokens\n *\n * String constants (not Symbols) so they match by value across import\n * boundaries — same convention as the events subsystem (`EVENT_BUS`). The\n * jobs subsystem uses Symbols for its analogous tokens; events and integration\n * stay internally consistent with strings.\n *\n * Usage in use cases:\n * ```ts\n * constructor(\n * @Inject(INTEGRATION_CHANGE_SOURCE) private readonly source: IChangeSource<CanonicalOpportunity>,\n * @Inject(INTEGRATION_CURSOR_STORE) private readonly cursors: ICursorStore,\n * @Inject(INTEGRATION_FIELD_DIFFER) private readonly differ: IFieldDiffer<CanonicalOpportunity>,\n * @Inject(INTEGRATION_SINK) private readonly sink: IIntegrationSink<CanonicalOpportunity>,\n * @Inject(INTEGRATION_RUN_RECORDER) private readonly recorder: IIntegrationRunRecorder,\n * ) {}\n * ```\n *\n * Concrete bindings are registered by `IntegrationModule.forRoot(...)` (SYNC-6).\n */\n\nexport const INTEGRATION_CHANGE_SOURCE = 'INTEGRATION_CHANGE_SOURCE' as const;\nexport const INTEGRATION_CURSOR_STORE = 'INTEGRATION_CURSOR_STORE' as const;\nexport const INTEGRATION_FIELD_DIFFER = 'INTEGRATION_FIELD_DIFFER' as const;\nexport const INTEGRATION_SINK = 'INTEGRATION_SINK' as const;\n\n/**\n * Run-recorder token (SYNC-5). Backed by `IIntegrationRunRecorder`. Drizzle impl\n * lands in SYNC-4; tests provide inline fakes.\n */\nexport const INTEGRATION_RUN_RECORDER = 'INTEGRATION_RUN_RECORDER' as const;\n\n/**\n * Injection token for the resolved `IntegrationModuleOptions` object (SYNC-6).\n *\n * Backends that need to observe module configuration (e.g. `multiTenant`\n * flag, pool filters) inject via this token. Provided automatically by\n * `IntegrationModule.forRoot(...)` / `IntegrationModule.forRootAsync(...)`.\n */\nexport const INTEGRATION_MODULE_OPTIONS = 'INTEGRATION_MODULE_OPTIONS' as const;\n\n/**\n * Injection token for the resolved multi-tenancy flag (SYNC-6).\n *\n * Provided by `IntegrationModule.forRoot(...)` as `options.multiTenant ?? false`.\n * Consumed by `ExecuteIntegrationUseCase` to enforce the tenantId-is-required rule.\n */\nexport const INTEGRATION_MULTI_TENANT = 'INTEGRATION_MULTI_TENANT' as const;\n\n/**\n * Injection token for the entity-keyed `IEntityChangeSourceRegistry` (C7,\n * #336). Bound to the codegen-emitted aggregator that folds per-provider\n * adapter contributions into one registry (RFC-0001 §3, emitted by Track D\n * D3/D4).\n *\n * A string constant, not `Symbol.for(...)`, to match this subsystem's token\n * convention (see file header). The originating issue's code block proposed a\n * `Symbol.for('@pattern-stack/codegen.entity-change-source-registry')` key,\n * predating the sync→integration consolidation onto string tokens; kept as a\n * string here for internal consistency with the other INTEGRATION_* tokens.\n */\nexport const ENTITY_CHANGE_SOURCE_REGISTRY = 'ENTITY_CHANGE_SOURCE_REGISTRY' as const;\n","/**\n * BridgeMetricsReporter — internal consumer of `IObservability`\n * (ADR-025, OBS-6).\n *\n * Periodically samples `getBridgeDeliveryHistogram` from the observability\n * facade and emits one log line per tick. Auto-registered by\n * `ObservabilityModule.forRoot()` when\n * `options.reporters.bridgeMetrics.enabled === true`. Consumers configure\n * via options; they never import this class. Not exported from the\n * module's `exports` array — internal.\n *\n * # Invariants (enforced by skill + ADR-025)\n *\n * - Injects ONLY `OBSERVABILITY` + `OBSERVABILITY_MODULE_OPTIONS`. Never\n * `BRIDGE_DELIVERY_REPO` or any other sibling token. Reporters are\n * consumers of the composed facade, not parallel composers.\n * - Never reaches into sibling tables or extends `IObservability`.\n * - Errors isolated per-tick (logged, never rethrown) so a transient\n * sibling failure does not kill the interval.\n * - `tenantId` passes VERBATIM to the facade — observability owns tenant\n * semantics, reporters don't re-implement them.\n *\n * # Lifecycle\n *\n * - `onModuleInit` — eager first-tick, then `setInterval`. Handle is\n * `.unref()`-ed when supported so the loop never blocks node shutdown.\n * - `onModuleDestroy` — `clearInterval` + null the handle. Idempotent.\n *\n * No `@nestjs/schedule` dependency — raw `setInterval` keeps the runtime\n * footprint minimal and avoids pulling a decorator framework in for a\n * single loop.\n */\nimport {\n Inject,\n Injectable,\n Logger,\n type OnModuleDestroy,\n type OnModuleInit,\n} from '@nestjs/common';\n\nimport type { IObservability } from '../observability.protocol';\nimport {\n OBSERVABILITY,\n OBSERVABILITY_MODULE_OPTIONS,\n} from '../observability.tokens';\n// Type-only imports — the module imports this file as a value for DI\n// registration, and this file imports config types back. Keeping the\n// back-edge type-only prevents a runtime circular-import.\nimport type {\n BridgeMetricsReporterConfig,\n ObservabilityModuleOptions,\n} from '../observability.module';\n\n@Injectable()\nexport class BridgeMetricsReporter implements OnModuleInit, OnModuleDestroy {\n private readonly logger = new Logger(BridgeMetricsReporter.name);\n private handle: ReturnType<typeof setInterval> | null = null;\n private readonly config: BridgeMetricsReporterConfig | undefined;\n\n constructor(\n @Inject(OBSERVABILITY) private readonly observability: IObservability,\n @Inject(OBSERVABILITY_MODULE_OPTIONS) options: ObservabilityModuleOptions,\n ) {\n this.config = options.reporters?.bridgeMetrics;\n }\n\n onModuleInit(): void {\n if (!this.config || !this.config.enabled) {\n this.logger.log('BridgeMetricsReporter disabled');\n return;\n }\n if (this.config.intervalMs <= 0 || this.config.windowHours <= 0) {\n this.logger.warn(\n `invalid config; not starting: intervalMs=${this.config.intervalMs} windowHours=${this.config.windowHours}`,\n );\n return;\n }\n // Eager first-tick so consumers see data immediately on boot, without\n // waiting `intervalMs` for the first sample.\n void this.runOnce();\n this.handle = setInterval(() => {\n void this.runOnce();\n }, this.config.intervalMs);\n // `.unref()` lets the node process exit even if the interval is still\n // scheduled — important in short-lived CLI/test contexts. Guarded\n // because browser-shimmed timers may not expose it.\n if (typeof this.handle.unref === 'function') this.handle.unref();\n }\n\n onModuleDestroy(): void {\n if (this.handle !== null) {\n clearInterval(this.handle);\n this.handle = null;\n }\n }\n\n /**\n * Single sample. Public so tests and future ops tooling can trigger a\n * sample on demand without waiting for the interval. Errors are caught\n * and logged here — never rethrown — so a transient sibling failure\n * does not kill subsequent ticks.\n */\n async runOnce(): Promise<void> {\n if (!this.config || !this.config.enabled) return;\n try {\n const h = await this.observability.getBridgeDeliveryHistogram(\n this.config.windowHours,\n this.config.tenantId,\n );\n this.logger.log(\n `bridge-delivery window=${this.config.windowHours}h tenant=${this.config.tenantId ?? 'default'} pending=${h.pending} delivered=${h.delivered} skipped=${h.skipped} failed=${h.failed}`,\n );\n } catch (err) {\n this.logger.error(\n 'BridgeMetricsReporter runOnce failed',\n err instanceof Error ? err.stack : String(err),\n );\n }\n }\n}\n","/**\n * Base class for observability-specific errors.\n *\n * Phase-1 `IObservability` methods do not throw — missing sibling ports\n * degrade to empty shapes (see `ObservabilityService`). This class exists\n * so future extensions (OBS-6 reporter misconfiguration, phase-2 Drizzle\n * extensions for `pg_stat_*` sampling, etc.) have a named base without\n * churning the barrel when they land.\n */\nexport class ObservabilityError extends Error {\n constructor(\n message: string,\n override readonly cause?: unknown,\n ) {\n super(message);\n this.name = 'ObservabilityError';\n }\n}\n","/**\n * Integration subsystem — field-diff protocol (port)\n *\n * `IFieldDiffer<T>` is the pluggable differ seam. The default implementation\n * (`DeepEqualDiffer`, ships in SYNC-5) walks every field except an ignore\n * list; CDC-aware differs can skip comparison for fields the provider didn't\n * flag as changed.\n *\n * `FieldDiffSchema` is the structural enforcement of the `changed_fields`\n * column per ADR-0003 — enforced at write time by the recorder service so\n * consumers can rely on the shape in downstream queries.\n */\nimport { z } from 'zod';\n\n// ============================================================================\n// FieldDiff shape — the ADR-0003 contract\n// ============================================================================\n\n/**\n * Structured per-field change. Enforced shape for `integration_run_items.changed_fields`.\n *\n * `created` items set `from: null, to: <value>` for every non-null field.\n * `deleted` items set `from: <value>, to: null`.\n * `noop` items carry `{}`.\n */\nexport const FieldDiffValueSchema = z.object({\n from: z.unknown(),\n to: z.unknown(),\n});\n\nexport const FieldDiffSchema = z.record(z.string(), FieldDiffValueSchema);\n\nexport type FieldDiffValue = z.infer<typeof FieldDiffValueSchema>;\nexport type FieldDiff = z.infer<typeof FieldDiffSchema>;\n\n/** Result of comparing a new record against its existing local state. */\nexport type DiffResult = FieldDiff | 'noop';\n\n// ============================================================================\n// IFieldDiffer\n// ============================================================================\n\n/**\n * Pluggable differ. Default ships in SYNC-5 as `DeepEqualDiffer<T>` —\n * deep-equal over every field except an ignore list (`updated_at` and other\n * row metadata). CDC-aware differs restrict comparison to\n * `providerChangedFields` when supplied.\n */\nexport interface IFieldDiffer<T> {\n /**\n * @param existing — current local state, or `null` when the record is new\n * @param incoming — the canonical record coming from the adapter\n * @param providerChangedFields — optional hint from CDC-capable sources;\n * when present, differ may restrict the comparison to these fields\n */\n diff(\n existing: T | null,\n incoming: T,\n providerChangedFields?: string[],\n ): DiffResult;\n}\n","/**\n * Integration subsystem — entity-keyed change-source registry (port)\n *\n * `IEntityChangeSourceRegistry` resolves an `IChangeSource<T>` by entity name.\n * It generalizes today's per-entity DI tokens (`ACCOUNT_POLL_FETCH_REGISTRY`,\n * `CONTACT_POLL_FETCH_REGISTRY`, …) into one entity-keyed registry, so the L3\n * composing port (`<Surface>Port`, Track C C6) can be entity-agnostic at the\n * type level instead of enumerating entities (epic #328 locked decision #5).\n *\n * This lives in L1 (the integration subsystem) rather than in a per-surface\n * package because the same shape applies across surfaces — CRM (`account`,\n * `contact`, `deal`), Mail (`email`, `thread`, `label`), Transcript\n * (`transcript`, `speaker`, `utterance`), Meeting (`meeting`, `attendee`).\n * Cross-surface plumbing belongs at L1 (epic #328 locked decision #6).\n *\n * Scope (Track C · C7): this is purely the L1 type + memory impl. Codegen does\n * NOT yet emit this registry, and the existing per-entity tokens keep emitting\n * unchanged — the retarget (and the per-entity-token deprecation) is Track D\n * D3/D4 (RFC-0001 §3/§8).\n *\n * See #336 (this issue), #328 (parent epic), RFC-0001 §3 (the registry\n * contract Track D emits the wiring for).\n */\n\nimport type { IChangeSource } from './integration-change-source.protocol';\n\n/**\n * Entity-keyed resolver for change sources. The orchestrator (and the L3\n * surface port) consume this, agnostic to whether a source came from a\n * hand-written adapter or a configured `PollChangeSource<T>`.\n */\nexport interface IEntityChangeSourceRegistry {\n /**\n * Resolve a change source for a given entity name.\n * Throws {@link UnknownEntityError} if the entity isn't registered.\n */\n get<T = unknown>(entityName: string): IChangeSource<T>;\n\n /** True if the entity is registered. */\n has(entityName: string): boolean;\n\n /** List all entity names this registry serves. */\n entities(): readonly string[];\n}\n\n/**\n * Thrown by {@link IEntityChangeSourceRegistry.get} when no source is\n * registered for the requested entity. The message enumerates the available\n * entities so a misconfiguration (typo'd entity name, missing adapter\n * contribution) is diagnosable from the error alone.\n */\nexport class UnknownEntityError extends Error {\n constructor(entity: string, available: readonly string[]) {\n super(\n `No change source registered for entity '${entity}'. Available: ${available.join(', ')}`,\n );\n this.name = 'UnknownEntityError';\n }\n}\n","/**\n * Integration subsystem — in-memory entity-change-source registry\n *\n * Default `IEntityChangeSourceRegistry` backed by a `Map<entityName, source>`.\n * Track D's codegen-emitted aggregator folds per-provider adapter\n * contributions into one of these and binds it under\n * `ENTITY_CHANGE_SOURCE_REGISTRY` (RFC-0001 §3); tests and simple consumers\n * construct it directly.\n *\n * See {@link ./entity-change-source-registry.protocol} for the contract and\n * #336 for scope.\n */\n\nimport type { IChangeSource } from './integration-change-source.protocol';\nimport {\n type IEntityChangeSourceRegistry,\n UnknownEntityError,\n} from './entity-change-source-registry.protocol';\n\nexport class MemoryEntityChangeSourceRegistry\n implements IEntityChangeSourceRegistry\n{\n constructor(private readonly sources: Map<string, IChangeSource<unknown>>) {}\n\n get<T = unknown>(name: string): IChangeSource<T> {\n const source = this.sources.get(name);\n if (!source) {\n throw new UnknownEntityError(name, [...this.sources.keys()]);\n }\n return source as IChangeSource<T>;\n }\n\n has(name: string): boolean {\n return this.sources.has(name);\n }\n\n entities(): readonly string[] {\n return [...this.sources.keys()];\n }\n}\n","/**\n * Integration subsystem — DetectionConfig schema (#226-1)\n *\n * Canonical Zod schema for per-entity integration detection config. The schema is\n * the single source of truth for filter/mapping shape and is consumed by:\n *\n * 1. Runtime primitives — `PollChangeSource<T>`, `WebhookChangeSource<T>`\n * (#226-3, #226-4) accept a parsed `DetectionConfig` at construction.\n * 2. Codegen — `src/schema/entity-definition.schema.ts` (#226-6) imports\n * this schema so per-entity YAML `detection:` blocks validate against\n * the same shape the runtime enforces.\n *\n * Locked decisions (see ADR-033 + decision memo Q1–Q6):\n * - Filter vocabulary is flat AND of `{ field, op, value }` triples; richer\n * boolean expressions (OR / NOT / nested) are deferred per epic open Q3.\n * - Cursor strategy is a tagged union over the four shapes the three modes\n * need (`systemModstamp`, `replayId`, `timestamp`, `eventId`). Each\n * strategy types its cursor internally; the orchestrator persists what\n * the iterator last yielded (integration skill rule 2).\n * - `mode: 'poll'` may opt into `provenance: 'cdc'` so Stripe-style event\n * endpoints (mechanically a poll, semantically CDC) reuse the poll\n * primitive while emitting `Change<T>.source = 'cdc'`. Long-lived\n * streaming CDC (SFDC Pub-Sub, Debezium) is a separate primitive\n * deferred to #226-8.\n * - `webhook` mode requires `eventIdField` so `WebhookChangeSource<T>`\n * can populate `Change<T>.dedupKey` from the inbound staging row.\n */\nimport { z } from 'zod';\n\n// ============================================================================\n// Field mapping — provider field → canonical target\n// ============================================================================\n\n/**\n * Maps a single provider field onto the canonical record. `transform` is an\n * opt-in tag the adapter callback may inspect (`date-iso`, `decimal-string`,\n * etc.); the schema does not enumerate transforms — adapters interpret them.\n */\nexport const FieldMappingSchema = z.object({\n source: z.string().min(1),\n target: z.string().min(1),\n transform: z.string().min(1).optional(),\n});\n\nexport type FieldMapping = z.infer<typeof FieldMappingSchema>;\n\n// ============================================================================\n// Resolved filter — flat-AND triple\n// ============================================================================\n\n/**\n * A single resolved filter clause applied at fetch time. `value` is `unknown`\n * to admit primitives, arrays (for `in` / `nin`), and dates as ISO strings —\n * adapters interpret per provider.\n */\nexport const ResolvedFilterSchema = z.object({\n field: z.string().min(1),\n op: z.enum(['eq', 'neq', 'in', 'nin', 'gt', 'gte', 'lt', 'lte']),\n value: z.unknown(),\n});\n\nexport type ResolvedFilter = z.infer<typeof ResolvedFilterSchema>;\n\n// ============================================================================\n// Cursor strategy — tagged union over the four shapes the modes need\n// ============================================================================\n\nconst SystemModstampCursorSchema = z.object({\n kind: z.literal('systemModstamp'),\n field: z.string().min(1),\n});\n\nconst ReplayIdCursorSchema = z.object({\n kind: z.literal('replayId'),\n field: z.string().min(1),\n});\n\nconst TimestampCursorSchema = z.object({\n kind: z.literal('timestamp'),\n field: z.string().min(1),\n});\n\nconst EventIdCursorSchema = z.object({\n kind: z.literal('eventId'),\n field: z.string().min(1),\n});\n\n/**\n * Gmail `historyId` (RFC-0003 §3) — an opaque, atomic vendor token. The next\n * watermark only exists at end-of-walk; there is no resumable mid-walk value.\n * `field` is metadata for codegen/adapters (the response key the token lives on).\n */\nconst HistoryIdCursorSchema = z.object({\n kind: z.literal('historyId'),\n field: z.string().min(1),\n});\n\n/**\n * Google Calendar `syncToken` (RFC-0003 §3) — an opaque, atomic sync token,\n * same divisibility profile as `historyId`.\n */\nconst SyncTokenCursorSchema = z.object({\n kind: z.literal('syncToken'),\n field: z.string().min(1),\n});\n\nexport const CursorStrategySchema = z.discriminatedUnion('kind', [\n SystemModstampCursorSchema,\n ReplayIdCursorSchema,\n TimestampCursorSchema,\n EventIdCursorSchema,\n HistoryIdCursorSchema,\n SyncTokenCursorSchema,\n]);\n\nexport type CursorStrategy = z.infer<typeof CursorStrategySchema>;\n\n// ============================================================================\n// Cursor divisibility (RFC-0003 §3)\n// ============================================================================\n\n/**\n * Whether a cursor strategy is *divisible* — a property of the strategy, not\n * the read primitive. Divisible cursors are sortable/monotonic watermarks whose\n * value is meaningful AS OF any single record (HubSpot `systemModstamp`, a\n * `timestamp` field, a Salesforce CDC `replayId`); the read primitive may\n * checkpoint per-ref mid-walk, so a crash resumes from the last delivered ref.\n *\n * Atomic cursors are opaque vendor tokens (Gmail `historyId`, Calendar\n * `syncToken`, a generic `eventId`) whose next value only exists at end-of-walk.\n * The primitive must withhold per-ref cursors and emit the token only at a safe\n * boundary, so an interrupted run never persists an unresumable mid-walk token\n * (it resumes all-or-nothing from the prior token — see `IncrementalReadBase`).\n *\n * `eventId` is classified atomic conservatively: a generic opaque id is treated\n * all-or-nothing unless a concrete strategy proves it monotonically resumable.\n */\nexport const CURSOR_DIVISIBILITY: Readonly<Record<CursorStrategy['kind'], boolean>> = {\n systemModstamp: true,\n timestamp: true,\n replayId: true,\n eventId: false,\n historyId: false,\n syncToken: false,\n};\n\n/** Predicate form of {@link CURSOR_DIVISIBILITY}. */\nexport function isDivisibleCursor(kind: CursorStrategy['kind']): boolean {\n return CURSOR_DIVISIBILITY[kind];\n}\n\n// ============================================================================\n// Mode-specific blocks\n// ============================================================================\n\n/**\n * Poll-mode block. `provenance: 'cdc'` opts the poll primitive into stamping\n * `Change<T>.source = 'cdc'` and populating `dedupKey` from the cursor's\n * `field` — used for Stripe-style event endpoints. Defaults to `'poll'`.\n */\nexport const PollDetectionSchema = z.object({\n cursor: CursorStrategySchema,\n provenance: z.enum(['poll', 'cdc']).optional(),\n});\n\nexport type PollDetection = z.infer<typeof PollDetectionSchema>;\n\n/**\n * Webhook-mode block. `eventIdField` names the column in the consumer-owned\n * inbound staging row that `WebhookChangeSource<T>` reads to set\n * `Change<T>.dedupKey`.\n */\nexport const WebhookDetectionSchema = z.object({\n eventIdField: z.string().min(1),\n});\n\nexport type WebhookDetection = z.infer<typeof WebhookDetectionSchema>;\n\n// ============================================================================\n// DetectionConfig — top-level discriminated union over `mode`\n// ============================================================================\n\nconst PollModeSchema = z.object({\n mode: z.literal('poll'),\n poll: PollDetectionSchema,\n mapping: z.array(FieldMappingSchema).min(1),\n filters: z.array(ResolvedFilterSchema).default([]),\n});\n\nconst WebhookModeSchema = z.object({\n mode: z.literal('webhook'),\n webhook: WebhookDetectionSchema,\n mapping: z.array(FieldMappingSchema).min(1),\n filters: z.array(ResolvedFilterSchema).default([]),\n});\n\n/**\n * Top-level detection config. Discriminated on `mode` so the relevant\n * mode-block (poll/webhook) is structurally required for that mode. CDC as a\n * long-lived streaming primitive is deferred (#226-8); CDC-as-provenance\n * (Stripe-style event endpoints) is expressed via `mode: 'poll'` with\n * `poll.provenance: 'cdc'`.\n */\nexport const DetectionConfigSchema = z.discriminatedUnion('mode', [\n PollModeSchema,\n WebhookModeSchema,\n]);\n\nexport type DetectionConfig = z.infer<typeof DetectionConfigSchema>;\n","/**\n * Integration subsystem — `IncrementalRead<T, F>` + `RandomRead<T>` capability\n * and the providing `IncrementalReadBase<T, F, M>` (RFC-0003 R1).\n *\n * The universal read primitive. Where `IChangeSource.listChanges` is the\n * *transport* contract (stream `Change<T>`, orchestrator owns cursor lifecycle),\n * this base owns *how the body that produces those changes is written* — the\n * level the bare `changeSources = {}` author-seam left unstructured.\n *\n * The read decomposes into two composable verbs the adapter supplies:\n *\n * - `enumerate(mode, filter) → AsyncIterable<Ref<M>[]>` — the cheap delta /\n * backfill walk; streams pages of lightweight refs (id + per-ref cursor +\n * filterable metadata). LAZY: pull-driven so hydrate backpressures it.\n * - `hydrate(ids) → Map<id, raw>` — the expensive fetch-by-id, batched; where\n * bounded concurrency / a vendor `/batch` endpoint lives. Keyed and\n * miss-tolerant (a mid-run 404 cannot shift alignment).\n * - `toCanonical(raw) → T | null` — provider payload → canonical record.\n *\n * The base PROVIDES the orchestration: drain enumerate, **filter before\n * hydrate** (structural — an adapter physically cannot hydrate-then-discard),\n * keyed pairing, per-ref cursor emission, and the `IChangeSource.listChanges`\n * adaptation. It also provides `RandomRead.get()` for free as\n * `toCanonical ∘ hydrate([id])` — so every incremental adapter is a\n * single-record reader (the \"list cheaply, fill on click\" query-surface need)\n * without extra code.\n *\n * The shape generalizes dealbrain's proven HubSpot `listSince` (streams, pushes\n * the filter server-side, carries a per-record cursor) to vendors whose list\n * returns id-stubs (Gmail) or nested resources (Meet). Calendar-style\n * full-object lists override `hydrate` as a passthrough.\n *\n * See RFC-0003 (Track D round-3), ADR-033 (`detection:` config), and\n * `poll-change-source.ts` (the sibling primitive this composes beside).\n */\n\nimport type {\n Change,\n ChangeSource,\n IChangeSource,\n IntegrationSubscriptionView,\n} from './integration-change-source.protocol';\n\n// ============================================================================\n// Capability shapes\n// ============================================================================\n\n/**\n * How a read walks the upstream. Modes are values, not verbs (swe-brain\n * ADR-0003: mode ≠ capability) — one `read()` verb dispatches on these.\n *\n * - `delta` — incremental walk from a persisted cursor.\n * - `full` — cursorless backfill (optionally bounded by `since`).\n * - `reconcile` — gap-repair: re-fetch a known id set the cursor skipped\n * (the repair pass for the silent-tail-skip + #414-style\n * multi-provider divergence).\n */\nexport type ReadMode =\n | { readonly kind: 'delta'; readonly cursor: unknown }\n | { readonly kind: 'full'; readonly since?: Date }\n | { readonly kind: 'reconcile'; readonly knownIds: readonly string[] };\n\n/**\n * A cheap ref from the enumerate pass: identity + per-ref cursor + metadata to\n * filter or display on. `cursor` is the position AS OF this ref — see\n * `IncrementalReadBase.cursorDivisible` (R2) for when it may be checkpointed\n * mid-walk versus withheld until a safe boundary.\n */\nexport interface Ref<M = Record<string, unknown>> {\n readonly externalId: string;\n readonly cursor: unknown;\n readonly meta: M;\n}\n\n/** A read request: the mode, an optional adapter-typed filter, and page size. */\nexport interface ReadRequest<F = unknown> {\n readonly mode: ReadMode;\n readonly filter?: F;\n readonly pageSize?: number;\n}\n\n/**\n * Per-run context threaded from `listChanges` into the vendor read body (R5).\n *\n * Carries the `subscription` framing the run so `enumerate`/`hydrate` can resolve\n * **per-connection credentials** (and raw-landing keys) from\n * `subscription.externalRef` — the gap a multi-account consumer surfaced: a\n * singleton change source cannot hold connection-scoped auth, and before R5 the\n * base forwarded the subscription only into `filterFor`, never into the fetch.\n *\n * Optional throughout (the core contract): a direct `read()` / `get()` call — the\n * query surface's \"fill one record on click\" — may omit it. An adapter that needs\n * per-connection auth reads `ctx?.subscription?.externalRef` and asserts its\n * presence; a provider-level-auth adapter ignores it.\n */\nexport interface ReadContext {\n /** The subscription framing this run; `externalRef` is the upstream scope /\n * connection id the adapter resolves credentials + raw-landing keys from. */\n readonly subscription?: IntegrationSubscriptionView;\n}\n\n/**\n * The `read()`-side envelope: canonical record + the raw vendor payload it came\n * from + the originating external id + the per-ref cursor.\n *\n * Distinct from the runtime's transport envelope `Change<T>`\n * (operation/externalId/cursor/source). The relationship is one-directional:\n * `listChanges()` adapts `read()` → `Change<T>` (dropping `raw`, stamping\n * `operation`). `read()` keeps `raw` and `externalId` so a query surface can\n * re-project without a second fetch.\n */\nexport interface SourcedRecord<T> {\n readonly externalId: string;\n readonly record: T;\n readonly raw: unknown;\n readonly cursor: unknown;\n}\n\n/**\n * The universal read capability — one public verb that streams. Filtering,\n * hydration, and cursor emission are the providing base's concern.\n */\nexport interface IncrementalRead<T, F = unknown> {\n read(req: ReadRequest<F>, ctx?: ReadContext): AsyncIterable<SourcedRecord<T>>;\n}\n\n/**\n * Single-record read by external id — the \"fill on click\" atom. Provided for\n * free by `IncrementalReadBase` (composes `hydrate` + `toCanonical`); declared\n * as its own capability so consumers can depend on it without the streaming\n * surface.\n */\nexport interface RandomRead<T> {\n get(id: string, ctx?: ReadContext): Promise<T | null>;\n}\n\n// ============================================================================\n// Bounded-parallel map helper\n// ============================================================================\n\n/**\n * Map `ids` through `fn` with at most `limit` concurrent in-flight calls,\n * collecting results keyed by id. The workhorse for writing a batched\n * `hydrate` over a single-id fetch without serial N+1 latency.\n */\nexport async function mapConcurrent<R>(\n ids: readonly string[],\n fn: (id: string) => Promise<R>,\n limit: number,\n): Promise<Map<string, R>> {\n const out = new Map<string, R>();\n if (ids.length === 0) return out;\n const width = Math.max(1, Math.min(limit, ids.length));\n let next = 0;\n const worker = async (): Promise<void> => {\n while (next < ids.length) {\n const idx = next++;\n const id = ids[idx]!;\n out.set(id, await fn(id));\n }\n };\n await Promise.all(Array.from({ length: width }, worker));\n return out;\n}\n\n// ============================================================================\n// IncrementalReadBase\n// ============================================================================\n\n/**\n * Providing base for the read capability. A subclass fills exactly three vendor\n * methods — `enumerate`, `hydrate`, `toCanonical` — and gets a streaming,\n * filter-before-hydrate, miss-tolerant `IncrementalRead<T, F>` +\n * `IChangeSource<T>` + `RandomRead<T>`.\n *\n * Type params: `T` canonical record, `F` adapter-typed filter, `M` per-ref\n * metadata (defaults to an untyped bag — surface packages supply a domain `M`).\n */\nexport abstract class IncrementalReadBase<T, F = unknown, M = Record<string, unknown>>\n implements IncrementalRead<T, F>, IChangeSource<T>, RandomRead<T>\n{\n /** Human label for run logs — e.g. `'google-mail-email'`. */\n abstract readonly label: string;\n\n /**\n * Whether the vendor takes the request predicate server-side. Declared, not\n * enforced here — surfaced into the emission manifest (R3) so the falsifier\n * suite (R4) can record which adapters filter post-hydrate. `false` is the\n * honest floor (e.g. Gmail without `q=`), handled via `matchesRecord`.\n */\n protected readonly filterPushdown: boolean = false;\n\n /** Max concurrent in-flight calls for a `mapConcurrent`-built `hydrate`. */\n protected readonly hydrateConcurrency: number = 10;\n\n /** `Change<T>.source` provenance stamped by `listChanges`. */\n protected readonly changeSource: ChangeSource = 'poll';\n\n /**\n * Whether this source's cursor strategy is divisible (RFC-0003 §3). When\n * `true` (default — sortable watermarks like `systemModstamp`/`timestamp`/\n * `replayId`), `listChanges` emits each record's per-ref cursor, so the\n * orchestrator may checkpoint mid-walk and a crash resumes from the last\n * delivered ref.\n *\n * When `false` (atomic opaque tokens — Gmail `historyId`, Calendar\n * `syncToken`), `listChanges` WITHHOLDS per-ref cursors and emits the\n * end-of-walk token only on the final record, so the orchestrator's\n * persist-last-yielded lifecycle can never persist an unresumable mid-walk\n * token. The cost is blast-radius: an interrupted atomic run resumes\n * all-or-nothing from the prior persisted token. For atomic *backfills* that\n * radius is the whole enumerate walk — bound it with `ReadRequest.pageSize`\n * (smaller pages ⇒ shorter walks per run). Per-page atomic checkpointing is a\n * future refinement; R2 gates at end-of-walk.\n *\n * Codegen (R3) sets this from the strategy kind via `isDivisibleCursor`.\n */\n protected readonly cursorDivisible: boolean = true;\n\n // ---- SUPPLIED by the adapter (the irreducible vendor seam) ----\n\n /**\n * The cheap walk. Streams pages of refs; LAZY so `hydrate` backpressures it\n * (one page hydrated before the next is pulled). Mode-dispatch lives here:\n * `delta` resumes from `mode.cursor`, `full` walks from the top, `reconcile`\n * re-fetches `mode.knownIds`.\n *\n * `pageSize` (from `ReadRequest`) is the adapter's requested vendor page size\n * — also the atomic-cursor backfill blast-radius bound (§ `cursorDivisible`).\n * Honor it as a hint; vendors that cap page size clamp it.\n *\n * `ctx?.subscription` (R5) carries the run's subscription, so a per-connection\n * adapter resolves credentials / upstream scope from `externalRef` here; absent\n * on a direct `read()` with no run subscription.\n */\n protected abstract enumerate(\n mode: ReadMode,\n filter?: F,\n pageSize?: number,\n ctx?: ReadContext,\n ): AsyncIterable<Ref<M>[]>;\n\n /**\n * Fetch raw payloads for `ids`, keyed by id. MUST be miss-tolerant: omit (or\n * map to `null`) any id that 404s mid-run rather than throwing or shifting\n * alignment. Write it over `mapConcurrent(ids, (id) => this.fetchOne(id),\n * this.hydrateConcurrency)`; override with a real `/batch` call or a\n * passthrough (full-object list) where the vendor allows.\n *\n * `ctx?.subscription` (R5) carries the run's subscription for per-connection\n * credential resolution (the fetch is where the vendor call happens) and is the\n * natural place to land raw payloads keyed by `subscription.id`.\n */\n protected abstract hydrate(ids: string[], ctx?: ReadContext): Promise<Map<string, unknown>>;\n\n /** Provider payload → canonical record. Return `null` to drop a record. */\n protected abstract toCanonical(raw: unknown): T | null;\n\n // ---- Optional filter hooks — exactly one is live per `filterPushdown` ----\n\n /** Pre-hydrate predicate over the cheap ref (preferred — avoids hydration). */\n protected matchesRef(_ref: Ref<M>, _filter?: F): boolean {\n return true;\n }\n\n /** Post-hydrate predicate over the canonical record (the no-pushdown floor). */\n protected matchesRecord(_record: T, _filter?: F): boolean {\n return true;\n }\n\n /**\n * Resolve the filter for a subscription when adapting to `listChanges`\n * (which has no filter argument). Defaults to none; codegen wiring (R3)\n * overrides this to thread `DetectionConfig.filters`.\n */\n protected filterFor(_subscription: IntegrationSubscriptionView): F | undefined {\n return undefined;\n }\n\n // ---- PROVIDED by the base ----\n\n /**\n * Stream canonical records for a request. Filter is applied BEFORE hydrate\n * (structural: a kept ref is hydrated, a rejected one never is), so an\n * adapter cannot hydrate-then-discard. A hydrate miss (deleted mid-run) is\n * skipped, never fabricated.\n */\n async *read(req: ReadRequest<F>, ctx?: ReadContext): AsyncIterable<SourcedRecord<T>> {\n for await (const refPage of this.enumerate(req.mode, req.filter, req.pageSize, ctx)) {\n const kept = refPage.filter((ref) => this.matchesRef(ref, req.filter));\n if (kept.length === 0) continue;\n const raws = await this.hydrate(\n kept.map((ref) => ref.externalId),\n ctx,\n );\n for (const ref of kept) {\n const raw = raws.get(ref.externalId);\n if (raw === undefined || raw === null) continue; // deleted mid-run → skip\n const record = this.toCanonical(raw);\n if (record !== null && this.matchesRecord(record, req.filter)) {\n yield { externalId: ref.externalId, record, raw, cursor: ref.cursor };\n }\n }\n }\n }\n\n /**\n * `RandomRead<T>` — single-record read, provided for free as\n * `toCanonical ∘ hydrate([id])`. Reuses the adapter's batched fetch + miss\n * tolerance; returns `null` for a missing or undecodable record.\n */\n async get(id: string, ctx?: ReadContext): Promise<T | null> {\n const raws = await this.hydrate([id], ctx);\n const raw = raws.get(id);\n if (raw === undefined || raw === null) return null;\n return this.toCanonical(raw);\n }\n\n /**\n * `IChangeSource<T>` adaptation. Maps the orchestrator's by-value cursor to a\n * `ReadMode` (`null` → `full` backfill, else `delta`), streams `read()`, and\n * stamps each `SourcedRecord` into a `Change<T>`. All records surface as\n * `'updated'`; the orchestrator's diff stage classifies create-vs-update and\n * deletes arrive as tombstone refs (`toCanonical` may flag them).\n *\n * Cursor emission honors `cursorDivisible` (RFC-0003 §3). Divisible: each\n * record carries its own per-ref cursor. Atomic: per-ref cursors are withheld\n * (`undefined`, which the orchestrator skips persisting) and the end-of-walk\n * token rides only on the final record — so a mid-walk crash never persists\n * an unresumable token. If an atomic run yields no surviving records, no\n * cursor is persisted and the next run re-reads the same (empty) delta — a\n * bounded inefficiency, never data loss.\n */\n async *listChanges(\n subscription: IntegrationSubscriptionView,\n cursor: unknown | null,\n ): AsyncIterable<Change<T>> {\n const mode: ReadMode =\n cursor === null || cursor === undefined\n ? { kind: 'full' }\n : { kind: 'delta', cursor };\n const filter = this.filterFor(subscription);\n // R5: thread the run's subscription into the read body so `enumerate`/`hydrate`\n // can resolve per-connection credentials (and raw-landing keys) from it.\n const stream = this.read({ mode, filter }, { subscription });\n\n if (this.cursorDivisible) {\n for await (const sourced of stream) {\n yield this.toChange(sourced, sourced.cursor);\n }\n return;\n }\n\n // Atomic: one-record lookahead. Emit every record but the last with a\n // withheld (`undefined`) cursor; the last record carries the end-of-walk\n // token. Contract: an atomic adapter stamps the (single, shared) end-of-walk\n // token onto its refs' `cursor` — so whichever record survives last carries\n // it. The base emits a real cursor exactly once, on that final record, so the\n // orchestrator can never persist a mid-walk value. If zero records survive,\n // nothing is persisted (next run re-reads the delta — bounded, never lossy).\n let prev: SourcedRecord<T> | null = null;\n for await (const sourced of stream) {\n if (prev !== null) yield this.toChange(prev, undefined);\n prev = sourced;\n }\n if (prev !== null) yield this.toChange(prev, prev.cursor);\n }\n\n /** Stamp a `SourcedRecord` into a `Change<T>` with an explicit emitted cursor. */\n private toChange(sourced: SourcedRecord<T>, cursor: unknown): Change<T> {\n return {\n externalId: sourced.externalId,\n operation: 'updated',\n record: sourced.record,\n cursor,\n source: this.changeSource,\n };\n }\n}\n","/**\n * Typed errors + shared boundary helpers for the integration subsystem.\n *\n * Classes (not bare Error) so consumers can `instanceof` them in catch\n * blocks and exception filters can map them to HTTP codes.\n *\n * Mirrors the shape of `events-errors.ts` and `jobs-errors.ts`.\n */\n\n/**\n * Thrown by the Drizzle cursor-store / run-recorder backends AND by the\n * orchestrator entry point when `INTEGRATION_MULTI_TENANT` is enabled but the\n * caller did not supply a non-null `tenantId`. Strict enforcement at the\n * boundary — explicit `null` still throws.\n *\n * Disable multi-tenancy on the module (`multiTenant: false`, the default)\n * to opt out of the requirement entirely.\n *\n * `operation` identifies the call site (e.g. `'cursor.put'`,\n * `'startRun'`, `'execute'`) so the stack-trace message points at the\n * specific boundary that rejected the input.\n */\nexport class MissingTenantIdError extends Error {\n override readonly name = 'MissingTenantIdError';\n constructor(operation: string) {\n super(\n `Missing tenantId for integration operation '${operation}'. IntegrationModule is ` +\n `configured with multiTenant: true — every call must include a ` +\n `non-null tenantId. Either pass the tenantId or disable multi-` +\n `tenancy on the module.`,\n );\n }\n}\n\n/**\n * Shared boundary guard — used at the orchestrator entry AND inside the\n * Drizzle backends. Keeping the check in one function guarantees every\n * `MissingTenantIdError` carries the same message shape regardless of the\n * site that raised it, which makes it easier for consumers to pattern-\n * match on the error in logs/metrics.\n *\n * When `multiTenant` is false, the function is a no-op — `tenantId` may\n * be anything (including `undefined`). When true, `undefined` or `null`\n * throws.\n */\nexport function assertTenantId(\n tenantId: string | null | undefined,\n options: { multiTenant: boolean; operation: string },\n): asserts tenantId is string {\n if (!options.multiTenant) return;\n if (tenantId === undefined || tenantId === null) {\n throw new MissingTenantIdError(options.operation);\n }\n}\n","/**\n * Drizzle schema for the integration subsystem audit/observability tables (SYNC-1).\n *\n * Three tables model end-to-end integration observability, keyed by the single port\n * every integration adapter implements (`IChangeSource<T>` from SYNC-2):\n *\n * - `integration_subscriptions` — owns the cursor per\n * `(connection_id, adapter, domain, external_ref)` tuple. Addressed\n * by id by `ICursorStore` (SYNC-3/SYNC-4).\n * - `integration_runs` — per-run audit log: start/complete, status,\n * cursor before/after, counts, direction (inbound|outbound),\n * action (poll|cdc|webhook|manual|writeback).\n * - `integration_run_items` — per-record change log with structured\n * `changed_fields` jsonb enforced by the Zod `FieldDiffSchema`\n * contract (ADR-0003; protocol lives in SYNC-2's\n * integration-field-diff.protocol.ts).\n *\n * Design calls (vs. issue #126 open questions):\n *\n * - `integration_subscriptions` ships in the subsystem (not consumer-owned).\n * Rationale: SYNC-4's `PostgresCursorStore` needs to read/write this\n * table directly; making it consumer-owned would require consumers to\n * hand-wire a shape the backend already knows. The row is addressable\n * by id and scoped by the uniqueness tuple; consumers can still\n * query/list it freely. Same stance as `job_run` being subsystem-\n * owned while remaining consumer-queryable.\n *\n * - `tenant_id` is always emitted on the three tables as nullable text.\n * The `INTEGRATION_MULTI_TENANT` DI flag (SYNC-6) is what enforces the\n * non-null + cross-tenant-isolation contract at the service/orchestrator\n * boundary. This mirrors JOB-1/JOB-8's final shape — runtime guard, not\n * a scaffold-time conditional column. Keeps the schema file uniform\n * across single-tenant and multi-tenant deployments.\n *\n * - `changed_fields` on `integration_run_items` is typed via the Zod-inferred\n * `FieldDiff` shape from SYNC-2 (`{ [fieldName]: { from, to } }`). The\n * recorder service (SYNC-5) validates every write against\n * `FieldDiffSchema.parse` so consumers can rely on the shape.\n */\nimport {\n pgEnum,\n pgTable,\n uuid,\n text,\n jsonb,\n integer,\n boolean,\n timestamp,\n index,\n uniqueIndex,\n} from 'drizzle-orm/pg-core';\nimport type { InferSelectModel } from 'drizzle-orm';\n\nimport type { FieldDiff } from './integration-field-diff.protocol';\n\n// ─── Enums ──────────────────────────────────────────────────────────────────\n\n/**\n * Direction of a integration run relative to local state.\n *\n * - `inbound` — external → local (the common case: SFDC poll → local DB).\n * - `outbound` — local → external (writeback; deferred per epic but the\n * column shape is reserved so future writeback runs share the audit log).\n */\nexport const integrationRunDirectionEnum = pgEnum('integration_run_direction', [\n 'inbound',\n 'outbound',\n]);\n\n/**\n * How the run detected upstream changes. Maps 1:1 to the `Change.source`\n * provenance on inbound runs; `manual` captures operator-triggered re-integrations\n * and `writeback` captures outbound runs.\n */\nexport const integrationRunActionEnum = pgEnum('integration_run_action', [\n 'poll',\n 'cdc',\n 'webhook',\n 'manual',\n 'writeback',\n]);\n\n/**\n * Lifecycle status of a integration run.\n *\n * - `running` — in-flight; recorder has started but not completed.\n * - `success` — completed with at least one change processed.\n * - `no_changes` — completed cleanly, no upstream changes found.\n * - `failed` — errored before completion; `error` column carries the\n * message. `records_processed` may be non-zero (partial progress).\n */\nexport const integrationRunStatusEnum = pgEnum('integration_run_status', [\n 'running',\n 'success',\n 'no_changes',\n 'failed',\n]);\n\n/**\n * Operation applied per record. Mirrors `Change<T>.operation` from SYNC-2,\n * plus the recorder's own `'noop'` for changes that matched existing state.\n */\nexport const integrationRunItemOperationEnum = pgEnum('integration_run_item_operation', [\n 'created',\n 'updated',\n 'deleted',\n 'noop',\n]);\n\n/**\n * Per-record status within a run. `skipped` captures loopback-detected echoes\n * of the local system's own writes (see `ILoopbackFingerprintStore` in the\n * epic), which record the external_id but intentionally do not touch local\n * state.\n */\nexport const integrationRunItemStatusEnum = pgEnum('integration_run_item_status', [\n 'success',\n 'failed',\n 'skipped',\n]);\n\n// ─── integration_subscriptions ─────────────────────────────────────────────────────\n\n/**\n * One cursor owner per (integration, adapter, domain, external_ref).\n *\n * - `connection_id` — opaque id of the connected account/instance. E.g.\n * the SFDC org id for polling strategies, the GitHub installation id\n * for webhook strategies.\n * - `adapter` — short adapter label, e.g. `'salesforce'`, `'hubspot'`.\n * - `domain` — canonical entity domain this subscription tracks,\n * e.g. `'opportunity'`, `'contact'`.\n * - `external_ref` — optional upstream scope (e.g. a filter id, a\n * webhook subscription id). NULL when the subscription covers the\n * entire domain.\n *\n * The cursor shape is opaque jsonb — strategies type it internally (poll:\n * `{ systemModstamp }`, cdc: `{ replayId }`, webhook: `{ ts }`). Overwritten\n * by `ICursorStore.put(id, cursor)`.\n */\nexport const integrationSubscriptions = pgTable(\n 'integration_subscriptions',\n {\n id: uuid('id').primaryKey().defaultRandom(),\n connectionId: text('connection_id').notNull(),\n adapter: text('adapter').notNull(),\n domain: text('domain').notNull(),\n externalRef: text('external_ref'),\n enabled: boolean('enabled').notNull().default(true),\n /**\n * Per-subscription configuration bag. Strategies type it internally;\n * e.g. polling strategies stash `{ batchSize, highWatermark }` here.\n */\n config: jsonb('config').notNull().default({}).$type<Record<string, unknown>>(),\n /**\n * Opaque cursor persisted by `ICursorStore.put()`. NULL until the first\n * successful run advances it.\n */\n cursor: jsonb('cursor').$type<unknown>(),\n lastIntegrationAt: timestamp('last_integration_at', { withTimezone: true }),\n /** Runtime-enforced when `INTEGRATION_MULTI_TENANT` is true; see SYNC-6. */\n tenantId: text('tenant_id'),\n createdAt: timestamp('created_at', { withTimezone: true }).notNull().defaultNow(),\n updatedAt: timestamp('updated_at', { withTimezone: true }).notNull().defaultNow(),\n },\n (t) => ({\n /**\n * Composite uniqueness per the epic shape. `external_ref` is nullable;\n * Postgres treats NULLs as distinct in a UNIQUE constraint, which means\n * two rows with the same `(connection_id, adapter, domain)` and NULL\n * external_ref are allowed. That's intentional — a subscription with\n * NULL external_ref covers the full domain, and duplicates there would\n * be a consumer-layer modeling issue, not a schema concern.\n */\n uqIntegrationSubscriptionTuple: uniqueIndex('uq_integration_subscriptions_tuple').on(\n t.connectionId,\n t.adapter,\n t.domain,\n t.externalRef,\n ),\n /** Scheduling query: list enabled subscriptions ordered by staleness. */\n idxIntegrationSubscriptionsEnabledLastIntegration: index(\n 'idx_integration_subscriptions_enabled_last_integration',\n ).on(t.enabled, t.lastIntegrationAt),\n }),\n);\n\nexport type IntegrationSubscriptionRow = InferSelectModel<typeof integrationSubscriptions>;\n\n// ─── integration_runs ──────────────────────────────────────────────────────────────\n\n/**\n * One row per invocation of `ExecuteIntegrationUseCase`. `started_at` is set when\n * the recorder opens the run; `completed_at`, `status`, `records_*`,\n * `cursor_after`, and `duration_ms` are filled on completion.\n *\n * `cursor_before` / `cursor_after` carry the opaque cursor snapshots so the\n * run log is fully self-describing — given a run id, an operator can reason\n * about exactly what window was scanned without cross-referencing another\n * table.\n */\nexport const integrationRuns = pgTable(\n 'integration_runs',\n {\n id: uuid('id').primaryKey().defaultRandom(),\n subscriptionId: uuid('subscription_id')\n .notNull()\n .references(() => integrationSubscriptions.id, { onDelete: 'cascade' }),\n direction: integrationRunDirectionEnum('direction').notNull(),\n action: integrationRunActionEnum('action').notNull(),\n status: integrationRunStatusEnum('status').notNull().default('running'),\n recordsFound: integer('records_found').notNull().default(0),\n recordsProcessed: integer('records_processed').notNull().default(0),\n cursorBefore: jsonb('cursor_before').$type<unknown>(),\n cursorAfter: jsonb('cursor_after').$type<unknown>(),\n durationMs: integer('duration_ms'),\n error: text('error'),\n startedAt: timestamp('started_at', { withTimezone: true })\n .notNull()\n .defaultNow(),\n completedAt: timestamp('completed_at', { withTimezone: true }),\n /** Runtime-enforced when `INTEGRATION_MULTI_TENANT` is true; see SYNC-6. */\n tenantId: text('tenant_id'),\n },\n (t) => ({\n /** Timeline read: \"most recent runs for this subscription\". */\n idxIntegrationRunsSubscriptionStartedAt: index(\n 'idx_integration_runs_subscription_started_at',\n ).on(t.subscriptionId, t.startedAt),\n /** Stale-run sweeper: \"runs that started > N minutes ago and are still running\". */\n idxIntegrationRunsStatusStartedAt: index('idx_integration_runs_status_started_at').on(\n t.status,\n t.startedAt,\n ),\n }),\n);\n\nexport type IntegrationRunRow = InferSelectModel<typeof integrationRuns>;\n\n// ─── integration_run_items ─────────────────────────────────────────────────────────\n\n/**\n * One row per upstream change processed within a run. Captures the canonical\n * decision the orchestrator made (`operation` + `status`), the structured\n * per-field diff (`changed_fields`, ADR-0003), and the local row id\n * (`local_id`) for drill-down joins.\n *\n * `changed_fields` is validated at the recorder layer via `FieldDiffSchema`\n * (SYNC-2) — the $type<FieldDiff> annotation here only documents the shape\n * for Drizzle consumers. The runtime enforcement is non-negotiable: downstream\n * drift-detection queries rely on the `{from, to}` shape per field.\n *\n * `title` is an optional human-readable label captured at write time (e.g.\n * `\"Pinnacle opportunity\"`) so run-log UIs don't need to re-hydrate the\n * canonical record.\n */\nexport const integrationRunItems = pgTable(\n 'integration_run_items',\n {\n id: uuid('id').primaryKey().defaultRandom(),\n integrationRunId: uuid('integration_run_id')\n .notNull()\n .references(() => integrationRuns.id, { onDelete: 'cascade' }),\n entityType: text('entity_type').notNull(),\n externalId: text('external_id').notNull(),\n localId: text('local_id'),\n operation: integrationRunItemOperationEnum('operation').notNull(),\n status: integrationRunItemStatusEnum('status').notNull(),\n /**\n * Structured per-field diff — ADR-0003 shape enforced by\n * `FieldDiffSchema.parse` at the recorder service layer.\n *\n * Shape: `{ [fieldName]: { from: unknown, to: unknown } }`.\n * Empty `{}` for `noop` items; `{ [field]: { from: null, to: <value> } }`\n * for created items; `{ [field]: { from: <value>, to: null } }` for\n * deleted items.\n */\n changedFields: jsonb('changed_fields').notNull().default({}).$type<FieldDiff>(),\n title: text('title'),\n error: text('error'),\n createdAt: timestamp('created_at', { withTimezone: true })\n .notNull()\n .defaultNow(),\n /** Runtime-enforced when `INTEGRATION_MULTI_TENANT` is true; see SYNC-6. */\n tenantId: text('tenant_id'),\n },\n (t) => ({\n /** Ordered timeline within a run. */\n idxIntegrationRunItemsRunCreatedAt: index('idx_integration_run_items_run_created_at').on(\n t.integrationRunId,\n t.createdAt,\n ),\n /** Per-record history: \"every integration that touched opportunity/$extId\". */\n idxIntegrationRunItemsEntityExternal: index(\n 'idx_integration_run_items_entity_external',\n ).on(t.entityType, t.externalId),\n }),\n);\n\nexport type IntegrationRunItemRow = InferSelectModel<typeof integrationRunItems>;\n","/**\n * MemoryCursorStore — in-memory backend for `ICursorStore` (SYNC-3).\n *\n * Test double that lets consumers exercise `ExecuteIntegrationUseCase` (SYNC-5) and\n * other cursor-consuming code paths without Postgres. Mirrors the role of\n * `MemoryEventBus` and `MemoryJobStore`: plain keyed state, tests take a\n * direct reference for `beforeEach` resets.\n *\n * Cursor values are stored by reference — the port's `get`/`put` contract\n * treats them as opaque `unknown`. Callers that want durable value-equality\n * semantics should snapshot via JSON before `put` and reparse after `get`;\n * this is what the Drizzle backend (SYNC-4) does implicitly via jsonb\n * round-trip. The memory backend intentionally does not simulate the\n * serialize/deserialize cycle — consumers who care should test against\n * Postgres.\n *\n * ## Multi-tenancy\n *\n * `tenantId` is accepted but ignored. The memory backend's state is\n * process-local — there's no durable storage where a cross-tenant leak\n * could occur. Tests that want to assert per-tenant isolation should\n * target the Drizzle backend.\n *\n * Not shipped in the upstream consumer; this is a subsystem-first addition for the\n * test surface. Consumed by:\n * - SYNC-5 unit tests (`ExecuteIntegrationUseCase` against synthetic sources)\n * - SYNC-6 module tests (`IntegrationModule.forRoot({ backend: 'memory' })`)\n */\nimport { Injectable } from '@nestjs/common';\nimport type {\n CursorSnapshot,\n ICursorStore,\n} from './integration-cursor-store.protocol';\nimport type { MemoryIntegrationSubscription } from './integration-run-recorder.memory-backend';\n\n@Injectable()\nexport class MemoryCursorStore implements ICursorStore {\n /**\n * Subscription-id → last persisted cursor. Public so tests can inspect\n * or pre-seed state; production callers MUST go through `get`/`put`.\n */\n readonly cursors: Map<string, unknown> = new Map();\n\n /**\n * Seedable subscription metadata for `listAll` — the memory backend\n * stores only `subscriptionId → cursor` in its write path, so the\n * snapshot shape (`connectionId`, `adapter`, `domain`, `externalRef`,\n * timestamps) has no natural source without test seeding. Tests populate\n * this map; unseeded entries get empty-string metadata and `new Date(0)`\n * timestamps so the shape stays stable. Production paths go through the\n * Drizzle backend.\n */\n readonly subscriptions: Map<string, MemoryIntegrationSubscription> = new Map();\n\n async get(\n subscriptionId: string,\n _tenantId?: string | null,\n ): Promise<unknown | null> {\n // `Map.get` returns `undefined` for missing keys; the port contract\n // returns `null`. Normalize here so callers can `=== null`-check.\n const value = this.cursors.get(subscriptionId);\n return value === undefined ? null : value;\n }\n\n async put(\n subscriptionId: string,\n cursor: unknown,\n _tenantId?: string | null,\n ): Promise<void> {\n // Overwrite semantics — matches the port contract and the Drizzle\n // backend's `ON CONFLICT DO UPDATE` behavior.\n this.cursors.set(subscriptionId, cursor);\n }\n\n async listAll(_tenantId?: string | null): Promise<CursorSnapshot[]> {\n // Accepts tenantId for contract symmetry but does not filter on it —\n // the memory backend never enforces tenancy (see class-level comment).\n const snapshots: CursorSnapshot[] = [];\n for (const [subscriptionId, cursor] of this.cursors.entries()) {\n const meta = this.subscriptions.get(subscriptionId);\n snapshots.push({\n subscriptionId,\n connectionId: meta?.connectionId ?? '',\n adapter: meta?.adapter ?? '',\n domain: meta?.domain ?? '',\n externalRef: meta?.externalRef ?? null,\n cursor: cursor ?? null,\n lastIntegrationAt: meta?.lastIntegrationAt ?? null,\n updatedAt: meta?.updatedAt ?? new Date(0),\n tenantId: null,\n });\n }\n return snapshots.sort(\n (a, b) => b.updatedAt.getTime() - a.updatedAt.getTime(),\n );\n }\n\n /** Reset state. Tests call this in `beforeEach`. */\n clear(): void {\n this.cursors.clear();\n this.subscriptions.clear();\n }\n}\n","/**\n * MemoryRunRecorder — in-memory backend for `IIntegrationRunRecorder` (SYNC-6).\n *\n * Test double so `IntegrationModule.forRoot({ backend: 'memory' })` is genuinely\n * end-to-end runnable without Postgres. Mirrors the role of\n * `MemoryCursorStore`: plain keyed state, `clear()` helper for\n * `beforeEach` resets, public inspection surface so tests can assert on\n * the recorded run + item timeline without scraping logs.\n *\n * Validates `changedFields` through `FieldDiffSchema.parse` on every\n * `recordItem` call — same ADR-0003 contract as the Drizzle backend. An\n * in-memory recorder that skipped the validation would be a silently\n * weaker contract than production.\n *\n * `startRun` generates a uuid via `crypto.randomUUID()` (Node 19+ / Bun).\n * We don't import `uuid` because the subsystem has no other use for it.\n *\n * ## Multi-tenancy\n *\n * `tenantId` is accepted (and recorded on the in-memory row so tests can\n * assert it) but enforcement lives at the module boundary. The memory\n * backend intentionally does not throw on missing `tenantId` — that's\n * the orchestrator's job when `multiTenant=true` (SYNC-6). A permissive\n * memory recorder lets tests exercise error paths where the orchestrator\n * short-circuits before ever reaching the recorder.\n */\nimport { Injectable } from '@nestjs/common';\nimport type {\n CompleteRunInput,\n IIntegrationRunRecorder,\n RecordItemInput,\n StartRunInput,\n IntegrationRunSummary,\n} from './integration-run-recorder.protocol';\nimport { FieldDiffSchema } from './integration-field-diff.protocol';\n\n/**\n * Optional per-subscription metadata a test can seed on the memory backend\n * so `listRecent` can surface `connectionId`. The memory recorder's write\n * path never persists subscription rows (it only stores runs + items), so\n * `listRecent` has no way to derive `connectionId` on its own. Tests that\n * care about the field should populate `subscriptions` before calling\n * `listRecent`; calls that don't seed get an empty string and a stable\n * shape (see `listRecent` below).\n */\nexport interface MemoryIntegrationSubscription {\n connectionId: string;\n adapter: string;\n domain: string;\n externalRef: string | null;\n lastIntegrationAt?: Date | null;\n updatedAt: Date;\n}\n\n/**\n * Concrete run row as held in memory. Shape mirrors the interesting\n * columns on `integration_runs` so assertions read like DB queries.\n */\nexport interface MemoryRunRecord {\n id: string;\n subscriptionId: string;\n direction: 'inbound' | 'outbound';\n action: 'poll' | 'cdc' | 'webhook' | 'manual' | 'writeback';\n status: 'running' | 'success' | 'no_changes' | 'failed';\n cursorBefore: unknown | null;\n cursorAfter: unknown | null;\n recordsFound: number;\n recordsProcessed: number;\n durationMs: number | null;\n error: string | null;\n tenantId: string | null;\n startedAt: Date;\n completedAt: Date | null;\n}\n\n@Injectable()\nexport class MemoryRunRecorder implements IIntegrationRunRecorder {\n /**\n * All started runs keyed by id. Public so tests can inspect lifecycle\n * transitions without poking through recording methods.\n */\n readonly runs: Map<string, MemoryRunRecord> = new Map();\n\n /**\n * Items keyed by `integration_run_id`, array order matches insertion order —\n * mirrors the timeline the `(integration_run_id, created_at)` index produces\n * in Postgres.\n */\n readonly items: Map<string, RecordItemInput[]> = new Map();\n\n /**\n * Seedable subscription metadata — tests populate this to make\n * `listRecent` return meaningful `connectionId` values. The memory\n * backend doesn't track subscriptions on its own (only runs + items), so\n * this map is the intentional extension point: tests write entries for\n * the subscription ids they use, production code never touches it.\n */\n readonly subscriptions: Map<string, MemoryIntegrationSubscription> = new Map();\n\n async startRun(input: StartRunInput): Promise<{ id: string }> {\n const id = crypto.randomUUID();\n this.runs.set(id, {\n id,\n subscriptionId: input.subscriptionId,\n direction: input.direction,\n action: input.action,\n status: 'running',\n cursorBefore: input.cursorBefore ?? null,\n cursorAfter: null,\n recordsFound: 0,\n recordsProcessed: 0,\n durationMs: null,\n error: null,\n tenantId: input.tenantId ?? null,\n startedAt: new Date(),\n completedAt: null,\n });\n this.items.set(id, []);\n return { id };\n }\n\n async recordItem(input: RecordItemInput): Promise<void> {\n // Same ADR-0003 contract as the Drizzle backend.\n FieldDiffSchema.parse(input.changedFields);\n\n const bucket = this.items.get(input.integrationRunId);\n if (!bucket) {\n throw new Error(\n `MemoryRunRecorder.recordItem: no run started for id '${input.integrationRunId}'. ` +\n `Call startRun(...) first.`,\n );\n }\n bucket.push(input);\n }\n\n async completeRun(runId: string, input: CompleteRunInput): Promise<void> {\n const run = this.runs.get(runId);\n if (!run) {\n throw new Error(\n `MemoryRunRecorder.completeRun: no run started for id '${runId}'.`,\n );\n }\n run.status = input.status;\n run.recordsFound = input.recordsFound;\n run.recordsProcessed = input.recordsProcessed;\n run.cursorAfter = input.cursorAfter ?? null;\n run.durationMs = input.durationMs;\n run.error = input.error ?? null;\n run.completedAt = new Date();\n }\n\n async listRecent(\n limit: number,\n subscriptionId?: string,\n _tenantId?: string | null,\n ): Promise<IntegrationRunSummary[]> {\n // Memory backend accepts tenantId for contract symmetry but does not\n // filter on it — state is process-local and cross-tenant isolation is\n // not meaningful here (matches MemoryCursorStore behavior).\n const all = Array.from(this.runs.values());\n const filtered =\n subscriptionId === undefined\n ? all\n : all.filter((r) => r.subscriptionId === subscriptionId);\n return filtered\n .sort((a, b) => b.startedAt.getTime() - a.startedAt.getTime())\n .slice(0, limit)\n .map((r) => ({\n id: r.id,\n subscriptionId: r.subscriptionId,\n // connectionId is only knowable if the test seeded subscriptions\n // metadata; empty string otherwise. The Drizzle backend resolves\n // it via JOIN, which is the production path.\n connectionId:\n this.subscriptions.get(r.subscriptionId)?.connectionId ?? '',\n status: r.status,\n startedAt: r.startedAt,\n completedAt: r.completedAt,\n recordsProcessed: r.recordsProcessed,\n tenantId: r.tenantId,\n }));\n }\n\n /** Reset state. Tests call this in `beforeEach`. */\n clear(): void {\n this.runs.clear();\n this.items.clear();\n this.subscriptions.clear();\n }\n\n // ─── test ergonomics ─────────────────────────────────────────────────\n\n /** All runs for a subscription, newest first. Timeline reads. */\n getRunsForSubscription(subscriptionId: string): MemoryRunRecord[] {\n return Array.from(this.runs.values())\n .filter((r) => r.subscriptionId === subscriptionId)\n .sort((a, b) => b.startedAt.getTime() - a.startedAt.getTime());\n }\n\n /** All item rows for a run, insertion-ordered. */\n getItemsForRun(runId: string): RecordItemInput[] {\n return this.items.get(runId) ?? [];\n }\n}\n","/**\n * DeepEqualDiffer — default `IFieldDiffer<T>` for the integration subsystem (SYNC-5).\n *\n * Walks every field of `incoming` against `existing`, emitting a structured\n * per-field diff (`{ from, to }`) for every field whose value changed.\n * Returns `'noop'` when the record is unchanged.\n *\n * Design decisions (extracted from the upstream consumer + HS-9 findings):\n *\n * 1. **Ignore list** — row metadata that sinks/services stamp unconditionally\n * so upstream cannot reasonably disagree:\n * `id`, `createdAt`, `updatedAt`, `deletedAt`, `type`,\n * `lastModifiedAt`, `fields`, `providerMetadata`\n * (`fields` is the EAV bag — it's diffed by the sink's EAV dual-write\n * path, not at the canonical-record layer.)\n *\n * 2. **`providerChangedFields` hint (CDC)** — when present, restricts the\n * comparison to the hinted field set. The hint is advisory; fields in\n * the ignore list are still filtered out even when hinted. Provider\n * hints are field-NAME-level; they don't override the ignore rules.\n *\n * 3. **Date → ISO string** — `Date` instances are normalized to\n * `toISOString()` before comparison. Sinks return `Date` from the DB\n * driver; adapters typically deliver strings. Direct `===` would\n * always say \"changed.\"\n *\n * 4. **Decimal-string vs number** — Postgres `numeric` columns return as\n * strings through Drizzle; adapters deliver numbers. When one side is a\n * number and the other is a numeric string that parses to the same\n * number, they're equal. The normalizer does NOT coerce non-numeric\n * strings, and it preserves zero-vs-null distinction.\n *\n * 5. **null-existing path** — `diff(null, incoming)` produces a full\n * created-shape diff (`{from: null, to: <value>}` for every non-ignored\n * field). Orchestrator sees this and records `operation: 'created'`.\n */\nimport { Injectable } from '@nestjs/common';\nimport type {\n DiffResult,\n FieldDiff,\n IFieldDiffer,\n} from './integration-field-diff.protocol';\n\n/**\n * Default ignore list. Keep in integration with consumer canonical-record shapes —\n * adding a row-metadata field here means no integration will ever mark it changed.\n *\n * Includes the columns contributed by the `external_id_tracking` behavior\n * (`external_id`/`externalId`, `provider`, `provider_metadata`/`providerMetadata`).\n * These are integration-tracking metadata, not domain attributes: they ride on the\n * canonical record but must never register as a field change (the external id\n * is the record's identity, not a mutable value). Listed in both snake_case\n * and camelCase so the differ ignores them regardless of the consumer's\n * canonical projection casing.\n */\nconst DEFAULT_IGNORE_FIELDS: ReadonlySet<string> = new Set([\n 'id',\n 'createdAt',\n 'updatedAt',\n 'deletedAt',\n 'type',\n 'lastModifiedAt',\n 'fields',\n 'external_id',\n 'externalId',\n 'provider',\n 'provider_metadata',\n 'providerMetadata',\n]);\n\nexport interface DeepEqualDifferOptions {\n /**\n * Extra field names to ignore in addition to the defaults. Consumers can\n * pass `['integration_version']` etc. to augment the base list; values here are\n * merged (not replaced) with `DEFAULT_IGNORE_FIELDS`.\n */\n readonly ignore?: readonly string[];\n}\n\n@Injectable()\nexport class DeepEqualDiffer<T extends Record<string, unknown>>\n implements IFieldDiffer<T>\n{\n private readonly ignore: ReadonlySet<string>;\n\n constructor(opts: DeepEqualDifferOptions = {}) {\n if (opts.ignore && opts.ignore.length > 0) {\n this.ignore = new Set([...DEFAULT_IGNORE_FIELDS, ...opts.ignore]);\n } else {\n this.ignore = DEFAULT_IGNORE_FIELDS;\n }\n }\n\n diff(\n existing: T | null,\n incoming: T,\n providerChangedFields?: string[],\n ): DiffResult {\n // Created-shape: every non-ignored field becomes `{from: null, to}`.\n if (existing === null) {\n const out: FieldDiff = {};\n for (const key of Object.keys(incoming)) {\n if (this.ignore.has(key)) continue;\n const value = (incoming as Record<string, unknown>)[key];\n // Skip fields that are themselves null/undefined — a created record\n // doesn't need to declare \"this field is null now\" for every\n // untouched column.\n if (value === null || value === undefined) continue;\n out[key] = { from: null, to: value };\n }\n return Object.keys(out).length === 0 ? 'noop' : out;\n }\n\n // Field set to compare. `providerChangedFields` narrows to a hint set;\n // ignored fields are filtered out regardless of hint.\n const candidates = new Set<string>();\n if (providerChangedFields && providerChangedFields.length > 0) {\n for (const key of providerChangedFields) {\n if (!this.ignore.has(key)) candidates.add(key);\n }\n } else {\n for (const key of Object.keys(incoming)) {\n if (!this.ignore.has(key)) candidates.add(key);\n }\n // Also include keys that exist on existing but not on incoming —\n // e.g. a field that was cleared. This would otherwise be missed when\n // incoming carries an undefined column we drop from the iteration.\n for (const key of Object.keys(existing)) {\n if (this.ignore.has(key)) continue;\n if (!(key in (incoming as Record<string, unknown>))) continue;\n candidates.add(key);\n }\n }\n\n const out: FieldDiff = {};\n for (const key of candidates) {\n const before = (existing as Record<string, unknown>)[key];\n const after = (incoming as Record<string, unknown>)[key];\n if (!isEqual(before, after)) {\n out[key] = { from: before ?? null, to: after ?? null };\n }\n }\n\n return Object.keys(out).length === 0 ? 'noop' : out;\n }\n}\n\n// ─── equality helpers ───────────────────────────────────────────────────────\n\n/**\n * Field-level equality with the canonical-integration normalizations:\n * - Date → toISOString (adapters deliver strings)\n * - numeric-string vs number → numeric equality when both parse\n * - deep equality for plain objects/arrays (single-level is enough for\n * canonical records; nested records travel as jsonb columns where the\n * sink already owns the comparison)\n */\nfunction isEqual(a: unknown, b: unknown): boolean {\n if (a === b) return true;\n\n const na = normalize(a);\n const nb = normalize(b);\n if (na === nb) return true;\n\n // After normalization: both may still be non-primitive objects.\n if (\n typeof na === 'object' &&\n typeof nb === 'object' &&\n na !== null &&\n nb !== null\n ) {\n return deepEqualObject(na as Record<string, unknown>, nb as Record<string, unknown>);\n }\n\n // Numeric string ↔ number: when one side is a number and the other is a\n // string that parses to the same finite number.\n const numericEqual = maybeNumericEqual(na, nb) || maybeNumericEqual(nb, na);\n return numericEqual;\n}\n\nfunction normalize(value: unknown): unknown {\n if (value instanceof Date) return value.toISOString();\n return value;\n}\n\nfunction maybeNumericEqual(a: unknown, b: unknown): boolean {\n // a is string-shape, b is number — parse a and compare. Only when the\n // string looks numeric AND the parse round-trips (no silent NaN pass-\n // through on non-numeric strings).\n if (typeof a !== 'string' || typeof b !== 'number') return false;\n if (a.trim() === '') return false;\n const parsed = Number(a);\n if (!Number.isFinite(parsed)) return false;\n return parsed === b;\n}\n\nfunction deepEqualObject(\n a: Record<string, unknown>,\n b: Record<string, unknown>,\n): boolean {\n if (Array.isArray(a) !== Array.isArray(b)) return false;\n const aKeys = Object.keys(a);\n const bKeys = Object.keys(b);\n if (aKeys.length !== bKeys.length) return false;\n for (const key of aKeys) {\n if (!(key in b)) return false;\n if (!isEqual(a[key], b[key])) return false;\n }\n return true;\n}\n","/**\n * ExecuteIntegrationUseCase — the generic integration orchestrator (SYNC-5).\n *\n * One class. Reused across every `(provider, detection-mode, canonical-entity)`\n * tuple. Parameterized over `T` so canonical records stay typed end-to-end.\n *\n * Flow per run:\n *\n * 1. `recorder.startRun(...)` — opens a `integration_runs` row in 'running'.\n * 2. for each change yielded by `source.listChanges(subscription, cursorBefore)`:\n * a. differ.diff(existing, incoming) → 'noop' short-circuits to\n * a noop audit row (no sink write).\n * b. sink.upsertByExternalId / softDeleteByExternalId → records\n * the local id on the audit row.\n * c. per-item try/catch — a failed item increments the failed\n * counter and records `status: 'failed'` with `error`, but\n * does NOT abort the run.\n * d. advance `latestCursor = change.cursor` as the iterator moves.\n * 3. `cursors.put(subscription.id, latestCursor)` when the loop completes\n * AND at least one cursor advance happened. On exceptions from the\n * source iterator (auth expiry, network error), we persist the\n * last-good cursor so the next run resumes from the last known\n * successful position.\n * 4. `finally { recorder.completeRun(...) }` — always terminates the run.\n *\n * Loopback suppression — when a consumer's writes echo back on the next\n * inbound poll/CDC/webhook — is composed into the source's middleware\n * chain via `createLoopbackMiddleware(store)` (#226-5 / ADR-033). The\n * orchestrator no longer special-cases echoes: middleware drops them\n * before they reach this loop. Consumers that don't have outbound\n * writeback paths simply omit the middleware.\n *\n * ## Generics\n *\n * - `T` = canonical record shape from the adapter side. Same `T` flows\n * through `IChangeSource<T>`, `IFieldDiffer<T>`, `IIntegrationSink<T>`.\n *\n * ## No CRM bleed\n *\n * Per the SYNC-5 issue's extraction notes (HS-9 finding), this orchestrator\n * is strictly provider-agnostic:\n * - `entityType` is `string` throughout; no `'opportunity' | 'account' | ...`\n * narrowing leaks into the use case\n * - the upstream consumer's `IntegrationRunRecorderService` class injection replaced with the\n * `IIntegrationRunRecorder` protocol (backend lands in SYNC-4)\n */\nimport { Inject, Injectable, Logger, Optional } from '@nestjs/common';\nimport type { IChangeSource, Change } from './integration-change-source.protocol';\nimport type { ICursorStore } from './integration-cursor-store.protocol';\nimport type { IFieldDiffer, FieldDiff } from './integration-field-diff.protocol';\nimport type { IIntegrationSink } from './integration-sink.protocol';\nimport type { IIntegrationRunRecorder } from './integration-run-recorder.protocol';\nimport { assertTenantId } from './integration-errors';\nimport {\n INTEGRATION_CHANGE_SOURCE,\n INTEGRATION_CURSOR_STORE,\n INTEGRATION_FIELD_DIFFER,\n INTEGRATION_MULTI_TENANT,\n INTEGRATION_RUN_RECORDER,\n INTEGRATION_SINK,\n} from './integration.tokens';\n\n// ============================================================================\n// Inputs + result\n// ============================================================================\n\nexport interface ExecuteIntegrationInput<T> {\n /** The subscription whose cursor/identity frames this run. */\n readonly subscription: {\n readonly id: string;\n readonly domain: string; // entityType — used on audit rows\n readonly externalRef?: string | null;\n };\n /** Per-run user context; threaded through sink writes. */\n readonly userId: string;\n /** Provider label persisted on saved rows, e.g. `'salesforce-crm'`. */\n readonly provider: string;\n /** Run direction — almost always `'inbound'`. Reserved for writeback. */\n readonly direction: 'inbound' | 'outbound';\n /** Detection mode — maps 1:1 to `integration_runs.action`. */\n readonly action: 'poll' | 'cdc' | 'webhook' | 'manual' | 'writeback';\n /** Multi-tenant deployments pass the tenant id through. */\n readonly tenantId?: string | null;\n /**\n * Optional override — inject a specific change source for this run when\n * the DI-bound source is not the one to use (e.g. manual backfill with\n * a custom cursor). Defaults to the DI-resolved `INTEGRATION_CHANGE_SOURCE`.\n */\n readonly sourceOverride?: IChangeSource<T>;\n}\n\nexport interface ExecuteIntegrationResult {\n readonly runId: string;\n readonly status: 'success' | 'no_changes' | 'failed';\n readonly recordsFound: number;\n readonly recordsProcessed: number;\n readonly recordsFailed: number;\n readonly cursorBefore: unknown | null;\n readonly cursorAfter: unknown | null;\n readonly durationMs: number;\n readonly error?: string | null;\n}\n\n// ============================================================================\n// ExecuteIntegrationUseCase\n// ============================================================================\n\n@Injectable()\nexport class ExecuteIntegrationUseCase<T extends Record<string, unknown>> {\n private readonly logger = new Logger(ExecuteIntegrationUseCase.name);\n\n constructor(\n @Inject(INTEGRATION_CHANGE_SOURCE) private readonly source: IChangeSource<T>,\n @Inject(INTEGRATION_CURSOR_STORE) private readonly cursors: ICursorStore,\n @Inject(INTEGRATION_FIELD_DIFFER) private readonly differ: IFieldDiffer<T>,\n @Inject(INTEGRATION_SINK) private readonly sink: IIntegrationSink<T>,\n @Inject(INTEGRATION_RUN_RECORDER) private readonly recorder: IIntegrationRunRecorder,\n @Optional()\n @Inject(INTEGRATION_MULTI_TENANT)\n private readonly multiTenant: boolean = false,\n ) {}\n\n async execute(input: ExecuteIntegrationInput<T>): Promise<ExecuteIntegrationResult> {\n // Defense-in-depth tenancy guard — fire BEFORE startRun so a rejected\n // input never leaves a dangling `status=running` row. Backends also\n // enforce (SYNC-4), but failing fast at the orchestrator boundary is\n // cheaper for observability, metrics, and manual cleanup.\n assertTenantId(input.tenantId, {\n multiTenant: this.multiTenant,\n operation: 'execute',\n });\n\n const source = input.sourceOverride ?? this.source;\n const startedAt = Date.now();\n const cursorBefore = await this.cursors.get(input.subscription.id, input.tenantId);\n\n const { id: runId } = await this.recorder.startRun({\n subscriptionId: input.subscription.id,\n direction: input.direction,\n action: input.action,\n cursorBefore,\n tenantId: input.tenantId,\n });\n\n let recordsFound = 0;\n let recordsProcessed = 0;\n let recordsFailed = 0;\n let latestCursor: unknown | null = cursorBefore;\n let cursorAdvanced = false;\n let runError: string | null = null;\n let status: 'success' | 'no_changes' | 'failed' = 'no_changes';\n\n try {\n for await (const change of source.listChanges(input.subscription, cursorBefore)) {\n recordsFound++;\n latestCursor = change.cursor;\n cursorAdvanced = true;\n\n try {\n await this.processChange(runId, input, change);\n recordsProcessed++;\n } catch (err) {\n recordsFailed++;\n const message = err instanceof Error ? err.message : String(err);\n this.logger.warn(\n `integration item failed: subscription=${input.subscription.id} externalId=${change.externalId}: ${message}`,\n );\n await this.recorder.recordItem({\n integrationRunId: runId,\n entityType: input.subscription.domain,\n externalId: change.externalId,\n operation: change.operation === 'deleted' ? 'deleted' : 'updated',\n status: 'failed',\n changedFields: {},\n error: message,\n tenantId: input.tenantId,\n });\n }\n }\n\n if (recordsFailed > 0 && recordsProcessed === 0 && recordsFound > 0) {\n // Every record we saw failed — call the run a failure, not a\n // success. Partial success (some processed, some failed) still\n // counts as 'success' so the cursor advances.\n status = 'failed';\n runError = `all ${recordsFailed} records failed`;\n } else if (recordsFound === 0) {\n status = 'no_changes';\n } else {\n status = 'success';\n }\n } catch (err) {\n // Source iterator itself threw — cursor DOES NOT advance past the\n // last-successful cursor. `latestCursor` still holds the last\n // `change.cursor` we observed, which is the furthest we know to\n // have delivered. Persist it (below) so next run resumes there.\n status = 'failed';\n runError = err instanceof Error ? err.message : String(err);\n this.logger.error(\n `integration source failed: subscription=${input.subscription.id}: ${runError}`,\n );\n }\n\n // Persist cursor advance only when something actually moved. Never\n // overwrite a valid cursor with `null` on a no-change run.\n if (cursorAdvanced && latestCursor !== null && latestCursor !== undefined) {\n try {\n await this.cursors.put(input.subscription.id, latestCursor, input.tenantId);\n } catch (err) {\n const message = err instanceof Error ? err.message : String(err);\n this.logger.error(\n `cursor put failed: subscription=${input.subscription.id}: ${message}`,\n );\n if (status !== 'failed') {\n status = 'failed';\n runError = `cursor put failed: ${message}`;\n }\n }\n }\n\n const durationMs = Date.now() - startedAt;\n\n await this.recorder.completeRun(runId, {\n status,\n recordsFound,\n recordsProcessed,\n cursorAfter: cursorAdvanced ? latestCursor : cursorBefore,\n durationMs,\n error: runError,\n });\n\n return {\n runId,\n status,\n recordsFound,\n recordsProcessed,\n recordsFailed,\n cursorBefore,\n cursorAfter: cursorAdvanced ? latestCursor : cursorBefore,\n durationMs,\n error: runError,\n };\n }\n\n private async processChange(\n runId: string,\n input: ExecuteIntegrationInput<T>,\n change: Change<T>,\n ): Promise<void> {\n // Deletion branch — no diff, no upsert; soft-delete via sink.\n if (change.operation === 'deleted') {\n const result = await this.sink.softDeleteByExternalId(\n input.userId,\n change.externalId,\n );\n await this.recorder.recordItem({\n integrationRunId: runId,\n entityType: input.subscription.domain,\n externalId: change.externalId,\n localId: result?.id ?? null,\n operation: result ? 'deleted' : 'noop',\n status: 'success',\n changedFields: {},\n tenantId: input.tenantId,\n });\n return;\n }\n\n // Create/update path — diff against local state, short-circuit on noop.\n const existing = await this.sink.findByExternalId(\n input.userId,\n change.externalId,\n );\n const diff = this.differ.diff(\n existing,\n change.record,\n change.providerChangedFields,\n );\n\n if (diff === 'noop') {\n // Sinks that declare `reprojectsOnNoop` reproject side data the differ\n // can't see (e.g. EAV field_values) — so fall through to the idempotent\n // upsert instead of short-circuiting. The canonical state is unchanged,\n // so the audit `operation` stays `'noop'`, but we capture the local id\n // returned by the upsert. Sinks without the flag keep today's behavior.\n if (!this.sink.reprojectsOnNoop) {\n await this.recorder.recordItem({\n integrationRunId: runId,\n entityType: input.subscription.domain,\n externalId: change.externalId,\n localId: null,\n operation: 'noop',\n status: 'success',\n changedFields: {},\n tenantId: input.tenantId,\n });\n return;\n }\n\n const { id: noopLocalId } = await this.sink.upsertByExternalId(\n input.userId,\n change.record,\n input.provider,\n );\n await this.recorder.recordItem({\n integrationRunId: runId,\n entityType: input.subscription.domain,\n externalId: change.externalId,\n localId: noopLocalId,\n operation: 'noop',\n status: 'success',\n changedFields: {},\n tenantId: input.tenantId,\n });\n return;\n }\n\n const { id: localId } = await this.sink.upsertByExternalId(\n input.userId,\n change.record,\n input.provider,\n );\n\n await this.recorder.recordItem({\n integrationRunId: runId,\n entityType: input.subscription.domain,\n externalId: change.externalId,\n localId,\n operation: existing === null ? 'created' : 'updated',\n status: 'success',\n changedFields: diff as FieldDiff,\n tenantId: input.tenantId,\n });\n }\n}\n","/**\n * PostgresCursorStore — Drizzle-backed `ICursorStore` (SYNC-4).\n *\n * Reads/writes `integration_subscriptions.cursor` directly — no service\n * composition. Consumers that want a service layer around subscriptions\n * wire it themselves; the port's contract is just cursor persistence.\n *\n * ## What `put` stamps\n *\n * `put` writes three columns in one statement: `cursor`, `last_integration_at`,\n * and `updated_at`. Rationale: SYNC-1's scheduling index\n * `(enabled, last_integration_at)` is useless if `last_integration_at` doesn't advance\n * with every cursor put. Every real consumer needs this stamped, so\n * bundling it here avoids every consumer wrapping the port in a service\n * layer just to stamp a timestamp.\n *\n * ## Multi-tenancy\n *\n * When `INTEGRATION_MULTI_TENANT` is true (SYNC-6):\n * - every read/write is scoped by `AND tenant_id = $tenantId`\n * - a null/missing `tenantId` throws `MissingTenantIdError` via the\n * shared `assertTenantId` helper (one message shape across the\n * orchestrator + both backends, SYNC-6)\n * - explicit `null` also throws — matches JOB-8 / EVT-6 strict-enforcement\n *\n * When the flag is off, `tenantId` is ignored. Cross-tenant isolation is\n * the caller's problem in single-tenant deployments.\n */\nimport { Inject, Injectable, Optional } from '@nestjs/common';\nimport { and, desc, eq, type SQL } from 'drizzle-orm';\nimport type { DrizzleClient } from '../../types/drizzle';\nimport { DRIZZLE } from '../../constants/tokens';\nimport type {\n CursorSnapshot,\n ICursorStore,\n} from './integration-cursor-store.protocol';\nimport { integrationSubscriptions } from './integration-audit.schema';\nimport { INTEGRATION_MULTI_TENANT } from './integration.tokens';\nimport { assertTenantId } from './integration-errors';\n\n@Injectable()\nexport class PostgresCursorStore implements ICursorStore {\n private readonly multiTenant: boolean;\n\n constructor(\n @Inject(DRIZZLE) private readonly db: DrizzleClient,\n @Optional() @Inject(INTEGRATION_MULTI_TENANT) multiTenant?: boolean,\n ) {\n this.multiTenant = multiTenant ?? false;\n }\n\n async get(\n subscriptionId: string,\n tenantId?: string | null,\n ): Promise<unknown | null> {\n const where = this.buildWhere(subscriptionId, tenantId, 'cursor.get');\n\n const rows = await this.db\n .select({ cursor: integrationSubscriptions.cursor })\n .from(integrationSubscriptions)\n .where(where)\n .limit(1);\n\n if (rows.length === 0) return null;\n return rows[0]?.cursor ?? null;\n }\n\n async put(\n subscriptionId: string,\n cursor: unknown,\n tenantId?: string | null,\n ): Promise<void> {\n const where = this.buildWhere(subscriptionId, tenantId, 'cursor.put');\n\n await this.db\n .update(integrationSubscriptions)\n .set({\n cursor,\n lastIntegrationAt: new Date(),\n updatedAt: new Date(),\n })\n .where(where);\n }\n\n async listAll(tenantId?: string | null): Promise<CursorSnapshot[]> {\n assertTenantId(tenantId, {\n multiTenant: this.multiTenant,\n operation: 'cursor.listAll',\n });\n\n const where = this.multiTenant\n ? eq(integrationSubscriptions.tenantId, tenantId as string)\n : undefined;\n\n const rows = await this.db\n .select({\n id: integrationSubscriptions.id,\n connectionId: integrationSubscriptions.connectionId,\n adapter: integrationSubscriptions.adapter,\n domain: integrationSubscriptions.domain,\n externalRef: integrationSubscriptions.externalRef,\n cursor: integrationSubscriptions.cursor,\n lastIntegrationAt: integrationSubscriptions.lastIntegrationAt,\n updatedAt: integrationSubscriptions.updatedAt,\n tenantId: integrationSubscriptions.tenantId,\n })\n .from(integrationSubscriptions)\n .where(where)\n .orderBy(desc(integrationSubscriptions.updatedAt));\n\n return rows.map((row) => ({\n subscriptionId: row.id,\n connectionId: row.connectionId,\n adapter: row.adapter,\n domain: row.domain,\n externalRef: row.externalRef,\n cursor: row.cursor ?? null,\n lastIntegrationAt: row.lastIntegrationAt,\n updatedAt: row.updatedAt,\n tenantId: row.tenantId,\n }));\n }\n\n /**\n * Centralized WHERE clause — `get` and `put` share identical semantics.\n * Drift here would let a caller read under one tenancy rule and write\n * under another.\n */\n private buildWhere(\n subscriptionId: string,\n tenantId: string | null | undefined,\n operation: string,\n ): SQL | undefined {\n assertTenantId(tenantId, {\n multiTenant: this.multiTenant,\n operation,\n });\n if (this.multiTenant) {\n return and(\n eq(integrationSubscriptions.id, subscriptionId),\n eq(integrationSubscriptions.tenantId, tenantId as string),\n );\n }\n return eq(integrationSubscriptions.id, subscriptionId);\n }\n}\n","/**\n * DrizzleIntegrationRunRecorder — Drizzle-backed `IIntegrationRunRecorder` (SYNC-4).\n *\n * Generic write path only — extracted from the source app's\n * `IntegrationRunRecorderService`, minus CRM-specific convenience methods. Those\n * stay consumer-owned; the subsystem ships the substrate.\n *\n * ## Responsibilities\n *\n * - `startRun` — INSERT integration_runs row in status='running', returns id.\n * - `recordItem` — validates `changedFields` via `FieldDiffSchema.parse`\n * BEFORE the INSERT; a malformed shape throws before\n * any DB call fires. Enforces the ADR-0003 contract at\n * the write boundary.\n * - `completeRun` — UPDATE integration_runs with terminal status, counts,\n * cursor_after, duration_ms, completed_at.\n *\n * ## Multi-tenancy\n *\n * When `INTEGRATION_MULTI_TENANT` is true (SYNC-6):\n * - `startRun` and `recordItem` require non-null `tenantId` on input.\n * Enforcement goes through the shared `assertTenantId` helper so the\n * error message shape matches the orchestrator entry point + the\n * cursor-store backends.\n * - `completeRun` does NOT re-check tenancy — the run id was returned\n * by `startRun` which already enforced it, and run ids are uuids that\n * aren't guessable cross-tenant. Matches JOB-3's pattern of trusting\n * the run-id for downstream mutations.\n */\nimport { Inject, Injectable, Optional } from '@nestjs/common';\nimport { and, desc, eq, type SQL } from 'drizzle-orm';\nimport type { DrizzleClient } from '../../types/drizzle';\nimport { DRIZZLE } from '../../constants/tokens';\nimport type {\n CompleteRunInput,\n IIntegrationRunRecorder,\n RecordItemInput,\n StartRunInput,\n IntegrationRunSummary,\n} from './integration-run-recorder.protocol';\nimport { integrationRuns, integrationRunItems, integrationSubscriptions } from './integration-audit.schema';\nimport { FieldDiffSchema } from './integration-field-diff.protocol';\nimport { INTEGRATION_MULTI_TENANT } from './integration.tokens';\nimport { assertTenantId } from './integration-errors';\n\n@Injectable()\nexport class DrizzleIntegrationRunRecorder implements IIntegrationRunRecorder {\n private readonly multiTenant: boolean;\n\n constructor(\n @Inject(DRIZZLE) private readonly db: DrizzleClient,\n @Optional() @Inject(INTEGRATION_MULTI_TENANT) multiTenant?: boolean,\n ) {\n this.multiTenant = multiTenant ?? false;\n }\n\n async startRun(input: StartRunInput): Promise<{ id: string }> {\n assertTenantId(input.tenantId, {\n multiTenant: this.multiTenant,\n operation: 'startRun',\n });\n\n const rows = await this.db\n .insert(integrationRuns)\n .values({\n subscriptionId: input.subscriptionId,\n direction: input.direction,\n action: input.action,\n status: 'running',\n cursorBefore: input.cursorBefore ?? null,\n tenantId: input.tenantId ?? null,\n })\n .returning({ id: integrationRuns.id });\n\n const id = rows[0]?.id;\n if (!id) {\n // Drizzle's insert().returning() contract: at least one row is\n // returned for every successful INSERT. A missing id would indicate\n // a driver misbehavior; throw loudly rather than return bogus data.\n throw new Error('DrizzleIntegrationRunRecorder: INSERT RETURNING produced no id');\n }\n return { id };\n }\n\n async recordItem(input: RecordItemInput): Promise<void> {\n assertTenantId(input.tenantId, {\n multiTenant: this.multiTenant,\n operation: 'recordItem',\n });\n\n // ADR-0003 contract enforcement — reject malformed changedFields\n // before the DB call fires. `parse` throws a ZodError; callers see\n // the validation failure, not a DB constraint error.\n FieldDiffSchema.parse(input.changedFields);\n\n await this.db.insert(integrationRunItems).values({\n integrationRunId: input.integrationRunId,\n entityType: input.entityType,\n externalId: input.externalId,\n localId: input.localId ?? null,\n operation: input.operation,\n status: input.status,\n changedFields: input.changedFields,\n title: input.title ?? null,\n error: input.error ?? null,\n tenantId: input.tenantId ?? null,\n });\n }\n\n async listRecent(\n limit: number,\n subscriptionId?: string,\n tenantId?: string | null,\n ): Promise<IntegrationRunSummary[]> {\n assertTenantId(tenantId, {\n multiTenant: this.multiTenant,\n operation: 'listRecent',\n });\n\n // JOIN against integration_subscriptions to resolve `connection_id` per run.\n // `integration_runs.subscription_id` is a non-null FK so INNER JOIN is correct;\n // there should be no orphaned runs.\n const conditions: SQL[] = [];\n if (subscriptionId !== undefined) {\n conditions.push(eq(integrationRuns.subscriptionId, subscriptionId));\n }\n if (this.multiTenant) {\n conditions.push(eq(integrationRuns.tenantId, tenantId as string));\n }\n const where =\n conditions.length === 0\n ? undefined\n : conditions.length === 1\n ? conditions[0]\n : and(...conditions);\n\n const rows = await this.db\n .select({\n id: integrationRuns.id,\n subscriptionId: integrationRuns.subscriptionId,\n connectionId: integrationSubscriptions.connectionId,\n status: integrationRuns.status,\n startedAt: integrationRuns.startedAt,\n completedAt: integrationRuns.completedAt,\n recordsProcessed: integrationRuns.recordsProcessed,\n tenantId: integrationRuns.tenantId,\n })\n .from(integrationRuns)\n .innerJoin(\n integrationSubscriptions,\n eq(integrationRuns.subscriptionId, integrationSubscriptions.id),\n )\n .where(where)\n .orderBy(desc(integrationRuns.startedAt))\n .limit(limit);\n\n return rows.map((row) => ({\n id: row.id,\n subscriptionId: row.subscriptionId,\n connectionId: row.connectionId,\n status: row.status,\n startedAt: row.startedAt,\n completedAt: row.completedAt,\n recordsProcessed: row.recordsProcessed,\n tenantId: row.tenantId,\n }));\n }\n\n async completeRun(runId: string, input: CompleteRunInput): Promise<void> {\n await this.db\n .update(integrationRuns)\n .set({\n status: input.status,\n recordsFound: input.recordsFound,\n recordsProcessed: input.recordsProcessed,\n cursorAfter: input.cursorAfter ?? null,\n durationMs: input.durationMs,\n error: input.error ?? null,\n completedAt: new Date(),\n })\n .where(eq(integrationRuns.id, runId));\n }\n}\n","/**\n * IntegrationModule — `DynamicModule.forRoot({ backend, multiTenant? })` factory\n * wiring the integration subsystem's substrate (SYNC-6, ADR-008 subsystem pattern).\n *\n * ## What this module provides\n *\n * - `INTEGRATION_CURSOR_STORE` — Drizzle or Memory cursor store\n * - `INTEGRATION_RUN_RECORDER` — Drizzle or Memory run recorder\n * - `INTEGRATION_FIELD_DIFFER` — default `DeepEqualDiffer`\n * - `INTEGRATION_MULTI_TENANT` — resolved boolean flag (defaults to false)\n * - `INTEGRATION_MODULE_OPTIONS` — the options object itself, for backends\n * that need to inspect config at construction time\n *\n * ## What this module does NOT provide\n *\n * - `INTEGRATION_CHANGE_SOURCE` — per-provider per-entity; consumer binds in\n * their feature module (e.g. `OpportunityIntegrationModule` provides a\n * `SalesforceOpportunityChangeSource`). Loopback suppression — when\n * needed — is composed into the primitive's middleware chain via\n * `createLoopbackMiddleware(store)` (#226-5 / ADR-033); the\n * orchestrator no longer accepts a fingerprint store directly.\n * - `INTEGRATION_SINK` — per canonical entity; consumer binds in their feature\n * module.\n * - `ExecuteIntegrationUseCase` — registered by the feature module alongside\n * its source + sink bindings. Providing the orchestrator here would\n * force Nest to resolve INTEGRATION_CHANGE_SOURCE + INTEGRATION_SINK at module\n * compile time, which fails when the feature module hasn't been\n * imported yet. Consumers register `ExecuteIntegrationUseCase` in the same\n * `providers` array as their source + sink so resolution is local\n * to where all three are bound.\n *\n * Same shape as `EventsModule.forRoot` — the module wires the bus; you\n * bring your own handlers. Here: the module wires the substrate; you\n * bring your own source + sink.\n *\n * ## Usage\n *\n * ```ts\n * // AppModule — single source of truth for backend + multi-tenancy.\n * @Module({\n * imports: [IntegrationModule.forRoot({ backend: 'drizzle' })],\n * })\n * export class AppModule {}\n *\n * // Per-entity feature module — binds source + sink, gets the\n * // orchestrator for free.\n * @Module({\n * providers: [\n * { provide: INTEGRATION_CHANGE_SOURCE, useClass: SalesforceOpportunitySource },\n * { provide: INTEGRATION_SINK, useClass: OpportunityIntegrationSink },\n * ExecuteIntegrationUseCase,\n * ],\n * })\n * export class OpportunityIntegrationModule {\n * constructor(\n * private readonly execute: ExecuteIntegrationUseCase<CanonicalOpportunity>,\n * ) {}\n * }\n * ```\n *\n * `global: true` means feature modules do not need to re-import\n * `IntegrationModule` — the substrate tokens are available project-wide.\n */\nimport { Module, type DynamicModule, type Provider } from '@nestjs/common';\nimport {\n INTEGRATION_CURSOR_STORE,\n INTEGRATION_FIELD_DIFFER,\n INTEGRATION_MODULE_OPTIONS,\n INTEGRATION_MULTI_TENANT,\n INTEGRATION_RUN_RECORDER,\n} from './integration.tokens';\nimport { MemoryCursorStore } from './integration-cursor-store.memory-backend';\nimport { MemoryRunRecorder } from './integration-run-recorder.memory-backend';\nimport { PostgresCursorStore } from './integration-cursor-store.drizzle-backend';\nimport { DrizzleIntegrationRunRecorder } from './integration-run-recorder.drizzle-backend';\nimport { DeepEqualDiffer } from './deep-equal.differ';\n\nexport interface IntegrationModuleOptions {\n /**\n * Backend selection. `drizzle` wires the Postgres cursor store +\n * run-log recorder; `memory` wires in-memory doubles suitable for\n * tests + local dev.\n */\n backend: 'drizzle' | 'memory';\n\n /**\n * Multi-tenancy opt-in (SYNC-6).\n *\n * When `true`, every call to the orchestrator + both Drizzle backends\n * must supply a non-null `tenantId`; missing values throw\n * `MissingTenantIdError`. Defense-in-depth: the orchestrator rejects\n * at entry (no dangling `status=running` rows) AND the Drizzle\n * backends reject at their write boundary (belt-and-braces for any\n * path that bypasses the orchestrator). Both sites use the shared\n * `assertTenantId` helper so error messages match.\n *\n * Memory backends accept `tenantId` unconditionally — their state is\n * process-local; cross-tenant isolation there is not meaningful.\n *\n * Defaults to `false`.\n */\n multiTenant?: boolean;\n}\n\n@Module({})\nexport class IntegrationModule {\n static forRoot(options: IntegrationModuleOptions): DynamicModule {\n const multiTenant = options.multiTenant ?? false;\n\n const sharedProviders: Provider[] = [\n { provide: INTEGRATION_MODULE_OPTIONS, useValue: options },\n { provide: INTEGRATION_MULTI_TENANT, useValue: multiTenant },\n // Default differ — consumers can override by binding a different\n // `IFieldDiffer<T>` to `INTEGRATION_FIELD_DIFFER` in their feature module.\n { provide: INTEGRATION_FIELD_DIFFER, useValue: new DeepEqualDiffer() },\n ];\n\n const backendProviders: Provider[] =\n options.backend === 'memory'\n ? [\n // Wired as singletons via `useValue` so tests can pull\n // them out via `moduleRef.get(MemoryCursorStore)` for\n // direct assertions. Matches JOB-4 / MemoryJobStore shape.\n { provide: MemoryCursorStore, useValue: new MemoryCursorStore() },\n {\n provide: INTEGRATION_CURSOR_STORE,\n useExisting: MemoryCursorStore,\n },\n { provide: MemoryRunRecorder, useValue: new MemoryRunRecorder() },\n {\n provide: INTEGRATION_RUN_RECORDER,\n useExisting: MemoryRunRecorder,\n },\n ]\n : [\n // Drizzle backends — injected with DRIZZLE (provided by the\n // consumer's DrizzleModule) + the INTEGRATION_MULTI_TENANT flag\n // we bound above.\n { provide: INTEGRATION_CURSOR_STORE, useClass: PostgresCursorStore },\n { provide: INTEGRATION_RUN_RECORDER, useClass: DrizzleIntegrationRunRecorder },\n ];\n\n return {\n module: IntegrationModule,\n global: true,\n providers: [...sharedProviders, ...backendProviders],\n exports: [\n INTEGRATION_MODULE_OPTIONS,\n INTEGRATION_MULTI_TENANT,\n INTEGRATION_FIELD_DIFFER,\n INTEGRATION_CURSOR_STORE,\n INTEGRATION_RUN_RECORDER,\n ],\n };\n }\n}\n","/**\n * Auth subsystem — `IOAuthStateStore` port.\n *\n * CSRF protection for the OAuth2 authorize-code callback. Generic across\n * providers. The store mints opaque state tokens at /connect time and\n * single-use consumes them at /callback time, returning the original\n * record (userId + optional post-callback redirect path).\n *\n * Concrete backends live under `../backends/`:\n * - `state-store.memory-backend.ts` — in-process Map (tests/dev).\n * - `state-store.drizzle-backend.ts` — Postgres (prod).\n *\n * Semantics:\n * - `generate(record)` → returns an opaque state token; record is stored\n * under that token until consumed or until TTL expires.\n * - `consume(state)` → atomically deletes the entry and returns the\n * record. Throws on missing, expired, or replayed state. Never returns\n * null — a missing/expired state is a CSRF signal.\n */\nexport interface OAuthStateRecord {\n userId: string;\n /** Optional post-callback redirect path (relative URL). */\n redirect?: string;\n}\n\nexport interface IOAuthStateStore {\n /** Mint an opaque state token bound to `record`. Single-use. */\n generate(record: OAuthStateRecord): Promise<string>;\n /**\n * Atomically consume `state`, returning the bound record. Throws on\n * missing / expired / replayed state.\n */\n consume(state: string): Promise<OAuthStateRecord>;\n}\n\n/**\n * Thrown by `IOAuthStateStore.consume` when the state token is unknown,\n * expired, or has already been consumed (replay attempt).\n */\nexport class OAuthStateError extends Error {\n constructor(\n message: string,\n public readonly reason: 'missing' | 'expired',\n ) {\n super(message);\n this.name = 'OAuthStateError';\n }\n}\n","/**\n * Auth subsystem — injection tokens.\n *\n * Following ADR-008 guidance: `Symbol()` tokens for type safety and collision\n * avoidance. Consumers inject these via `@Inject(...)` against the matching\n * protocol interface.\n *\n * Usage:\n * ```typescript\n * constructor(\n * @Inject(ENCRYPTION_KEY) private readonly key: IEncryptionKey,\n * @Inject(OAUTH_STATE_STORE) private readonly states: IOAuthStateStore,\n * @Inject(AUTH_CONNECTION_READER) private readonly reader: IConnectionReader,\n * @Inject(AUTH_CONNECTION_TOKEN_WRITER) private readonly writer: IConnectionTokenWriter,\n * @Inject(AUTH_CONNECTION_GRANT_SINK) private readonly grants: IConnectionGrantSink,\n * @Inject(AUTH_USER_CONTEXT) private readonly userCtx: IUserContext,\n * @Inject(STRATEGY_REGISTRY) private readonly registry: ProviderStrategyRegistry,\n * ) {}\n * ```\n *\n * `IAuthStrategy` implementations are provider-specific and registered under\n * provider-specific tokens (e.g. `SALESFORCE_AUTH_STRATEGY`,\n * `HUBSPOT_AUTH_STRATEGY`) by each connection module — this subsystem does\n * not mandate a single `AUTH_STRATEGY` token because an app typically has\n * many concurrent strategies, one per provider. They are dispatched through\n * `STRATEGY_REGISTRY` (a `ReadonlyMap<slug, IProviderStrategy>`), populated\n * by per-provider modules via a `useFactory` provider.\n */\nimport { tokenKey } from '../token-key';\n\n// ADR-037: namespaced `Symbol.for(...)` keys so a token matches by VALUE across\n// import boundaries — the package copy and a (legacy) vendored copy resolve to\n// the SAME symbol, eliminating the dual-package DI-token identity hazard that\n// crashed boot once the emitter began emitting `STRATEGY_REGISTRY` as a runtime\n// value (RFC-0003 R5). Matches the convention surface packages already use.\nexport const ENCRYPTION_KEY = Symbol.for(tokenKey('auth', 'encryption-key'));\nexport const OAUTH_STATE_STORE = Symbol.for(tokenKey('auth', 'oauth-state-store'));\nexport const AUTH_CONNECTION_READER = Symbol.for(tokenKey('auth', 'connection-reader'));\nexport const AUTH_CONNECTION_TOKEN_WRITER = Symbol.for(tokenKey('auth', 'connection-token-writer'));\nexport const AUTH_CONNECTION_GRANT_SINK = Symbol.for(tokenKey('auth', 'connection-grant-sink'));\nexport const AUTH_USER_CONTEXT = Symbol.for(tokenKey('auth', 'user-context'));\nexport const STRATEGY_REGISTRY = Symbol.for(tokenKey('auth', 'strategy-registry'));\n/**\n * Holds the resolved `AuthModuleOptions` (used by `AuthController` to read\n * `redirectUriBase` for building per-provider callback URIs).\n */\nexport const AUTH_OPTIONS = Symbol.for(tokenKey('auth', 'options'));\n","/**\n * Thrown when an OAuth2 provider returns `400 invalid_grant`/`invalid_token`\n * on refresh — the refresh token itself is dead (user revoked, org\n * deactivated, token expired beyond the provider's rotation window). The\n * connection should be marked broken so background sync stops picking it\n * up; the user re-initiates OAuth.\n *\n * Shared across every OAuth2 strategy.\n */\nexport class ConnectionBrokenError extends Error {\n constructor(\n readonly connectionId: string,\n readonly errorCode: string,\n readonly errorDescription: string,\n ) {\n super(\n `Connection ${connectionId} broken: ${errorCode} - ${errorDescription}`,\n );\n this.name = 'ConnectionBrokenError';\n }\n}\n","/**\n * Abstract base class for OAuth2 refresh-token strategies.\n *\n * Template-method pattern: `resolve()` is concrete; four small hooks inject\n * provider specifics. Validated across two providers (Salesforce, HubSpot)\n * in the extraction-source app before being extracted here — see\n * `docs/gate-1-auth-extraction-findings.md` for the \"build first, extract\n * later\" evidence.\n *\n * Subclass contract:\n * - `provider` — slug matched against `connections.provider`\n * - `defaultExpiresInSec` — fallback when refresh response omits `expires_in`\n * - `tokenEndpoint()` — URL to POST the refresh grant\n * - `refreshBodyExtras()` — provider-specific body params\n * - `parseRefreshResponse()` — raw JSON → ParsedRefreshResponse\n * - `buildCredentials()` — stored or freshly-refreshed access token +\n * connection + optional raw refresh response\n * → provider credentials\n *\n * Base handles: expiry check w/ 5-min safety window, `forceRefresh` escape\n * hatch, POST form-urlencoded body, OAuth2 error mapping to\n * `ConnectionBrokenError`, refresh-token rotation persistence, fetch +\n * clock injection for tests.\n */\nimport type {\n AuthCredentials,\n AuthResolveOptions,\n IAuthStrategy,\n} from '../protocols/auth-strategy';\nimport type {\n DecryptedConnection,\n IConnectionReader,\n IConnectionTokenWriter,\n} from '../protocols/connection-store';\nimport { ConnectionBrokenError } from './connection-broken.error';\n\nexport type FetchLike = (\n input: string | URL | Request,\n init?: RequestInit,\n) => Promise<Response>;\n\n/** Safety window before expiry that triggers a refresh. */\nconst REFRESH_SAFETY_MS = 5 * 60 * 1000;\n\nexport interface OAuth2RefreshStrategyOptions {\n connectionReader: IConnectionReader;\n tokenWriter: IConnectionTokenWriter;\n /** Injectable fetch for tests. Defaults to the global `fetch`. */\n fetch?: FetchLike;\n /** Injectable clock for tests. Defaults to `Date.now`. */\n now?: () => number;\n}\n\nexport interface ParsedRefreshResponse {\n accessToken: string;\n /**\n * New refresh token if the provider rotated it (HubSpot: always, Salesforce:\n * sometimes). Omit when the provider reused the old refresh token.\n */\n refreshToken?: string;\n /** Seconds from now. If omitted, subclass `defaultExpiresInSec` applies. */\n expiresInSec?: number;\n}\n\nexport abstract class OAuth2RefreshStrategy implements IAuthStrategy {\n protected abstract readonly provider: string;\n protected abstract readonly defaultExpiresInSec: number;\n\n protected readonly connectionReader: IConnectionReader;\n protected readonly tokenWriter: IConnectionTokenWriter;\n protected readonly fetchImpl: FetchLike;\n protected readonly now: () => number;\n\n constructor(opts: OAuth2RefreshStrategyOptions) {\n this.connectionReader = opts.connectionReader;\n this.tokenWriter = opts.tokenWriter;\n this.fetchImpl = opts.fetch ?? fetch;\n this.now = opts.now ?? Date.now;\n }\n\n async resolve(\n connectionId: string,\n opts: AuthResolveOptions = {},\n ): Promise<AuthCredentials> {\n const connection =\n await this.connectionReader.findByIdDecrypted(connectionId);\n if (!connection) {\n throw new Error(`Connection ${connectionId} not found`);\n }\n if (connection.provider !== this.provider) {\n throw new Error(\n `${this.constructor.name} called for non-${this.provider} connection ${connectionId} (provider=${connection.provider})`,\n );\n }\n\n const needsRefresh =\n opts.forceRefresh ||\n this.isExpiring(connection.expiresAt) ||\n !connection.accessToken;\n\n if (!needsRefresh) {\n return this.buildCredentials(connection.accessToken, connection);\n }\n\n if (!connection.refreshToken) {\n throw new ConnectionBrokenError(\n connectionId,\n 'no_refresh_token',\n 'Connection has no refresh token; user must reconnect',\n );\n }\n\n const { parsed, raw } = await this.executeRefresh(\n connectionId,\n connection.refreshToken,\n );\n const newExpiresAt = new Date(\n this.now() + (parsed.expiresInSec ?? this.defaultExpiresInSec) * 1000,\n );\n await this.tokenWriter.persistRefresh({\n connectionId,\n accessToken: parsed.accessToken,\n refreshToken: parsed.refreshToken ?? undefined,\n expiresAt: newExpiresAt,\n });\n\n return this.buildCredentials(parsed.accessToken, connection, raw);\n }\n\n protected abstract tokenEndpoint(): string;\n protected abstract refreshBodyExtras(): Record<string, string>;\n protected abstract parseRefreshResponse(raw: unknown): ParsedRefreshResponse;\n protected abstract buildCredentials(\n accessToken: string,\n connection: DecryptedConnection,\n refreshRaw?: unknown,\n ): AuthCredentials;\n\n private async executeRefresh(\n connectionId: string,\n refreshToken: string,\n ): Promise<{ parsed: ParsedRefreshResponse; raw: unknown }> {\n const body = new URLSearchParams({\n grant_type: 'refresh_token',\n refresh_token: refreshToken,\n ...this.refreshBodyExtras(),\n });\n const response = await this.fetchImpl(this.tokenEndpoint(), {\n method: 'POST',\n headers: { 'Content-Type': 'application/x-www-form-urlencoded' },\n body: body.toString(),\n });\n if (!response.ok) {\n const err = (await safeJson(response)) as Partial<{\n error: string;\n error_description: string;\n message: string;\n }>;\n if (\n response.status === 400 &&\n (err.error === 'invalid_grant' || err.error === 'invalid_token')\n ) {\n throw new ConnectionBrokenError(\n connectionId,\n err.error ?? 'invalid_grant',\n err.error_description ?? err.message ?? 'refresh token rejected',\n );\n }\n throw new Error(\n `${this.provider} token refresh failed: ${response.status} ${err.error ?? ''} ${err.error_description ?? err.message ?? ''}`.trim(),\n );\n }\n const raw = await response.json();\n return { parsed: this.parseRefreshResponse(raw), raw };\n }\n\n private isExpiring(expiresAt: Date | null): boolean {\n if (!expiresAt) return true;\n return expiresAt.getTime() - this.now() < REFRESH_SAFETY_MS;\n }\n}\n\nasync function safeJson(response: Response): Promise<unknown> {\n try {\n return await response.clone().json();\n } catch {\n return {};\n }\n}\n","/**\n * Provider-agnostic marker for \"the access token was rejected; a forced\n * refresh may recover.\"\n *\n * Concrete provider error classes (e.g. SalesforceSessionExpiredError,\n * HubSpotUnauthorizedError) either extend `SessionExpiredError` directly or\n * set `isSessionExpired === true` on their instances. `withAuthRetry` uses\n * the `isSessionExpiredError` predicate to decide whether to force-refresh\n * and retry once.\n *\n * This discriminator replaces the SFDC-only `instanceof` check from the\n * extraction-source app's original `withAuthRetry`. See\n * `docs/gate-1-auth-extraction-findings.md` (recommendation 4).\n */\nexport class SessionExpiredError extends Error {\n /** Duck-type marker — works across package boundaries where `instanceof` fails. */\n readonly isSessionExpired = true as const;\n\n constructor(message = 'Access token rejected by provider') {\n super(message);\n this.name = 'SessionExpiredError';\n }\n}\n\n/**\n * Predicate used by `withAuthRetry` by default.\n *\n * Matches any error that either `instanceof SessionExpiredError` or carries\n * the `isSessionExpired === true` marker property. Provider adapters that\n * want their existing error classes to participate can simply add the\n * marker property without touching the class hierarchy.\n */\nexport function isSessionExpiredError(err: unknown): boolean {\n if (err instanceof SessionExpiredError) return true;\n if (err !== null && typeof err === 'object' && 'isSessionExpired' in err) {\n return (err as { isSessionExpired?: unknown }).isSessionExpired === true;\n }\n return false;\n}\n","/**\n * Run `op` with auth-aware retry-once on session-expired errors.\n *\n * Pattern: resolve creds → run op → if `isSessionExpired(e)` → resolve with\n * `forceRefresh: true` → retry → propagate. A second session-expired error\n * on the refreshed token propagates rather than looping, so transient\n * adapter bugs can't hang the caller.\n *\n * Generalisation over the extraction source's SFDC-specific original: the\n * session-expired classifier is injected. Providers mark their session-\n * expired errors (via `instanceof` of a marker class, or by setting a known\n * property) and pass a classifier matching that shape.\n *\n * Default classifier recognises the marker interface `SessionExpiredError`\n * shipped in `session-expired.error.ts` — concrete provider errors that\n * extend it (or set `isSessionExpired === true`) get retried without any\n * further wiring.\n */\nimport type {\n AuthCredentials,\n IAuthStrategy,\n} from '../protocols/auth-strategy';\nimport { isSessionExpiredError } from './session-expired.error';\n\nexport interface WithAuthRetryOptions {\n /**\n * Classifier that decides whether a thrown error is a session-expired\n * signal worth retrying once with a fresh token. Defaults to the marker-\n * interface check in `session-expired.error.ts`.\n */\n isSessionExpired?: (err: unknown) => boolean;\n}\n\nexport async function withAuthRetry<T>(\n authStrategy: IAuthStrategy,\n connectionId: string,\n op: (credentials: AuthCredentials) => Promise<T>,\n options: WithAuthRetryOptions = {},\n): Promise<T> {\n const classify = options.isSessionExpired ?? isSessionExpiredError;\n\n let creds = await authStrategy.resolve(connectionId);\n try {\n return await op(creds);\n } catch (e) {\n if (!classify(e)) throw e;\n creds = await authStrategy.resolve(connectionId, { forceRefresh: true });\n return op(creds);\n }\n}\n","/**\n * Drizzle schema for the `auth_oauth_state` table — backs the\n * `DrizzleOAuthStateStore` (`state-store.drizzle-backend.ts`).\n *\n * One row per outstanding /connect → /callback dance. Single-use; rows are\n * deleted on consume. A periodic sweep (or a `WHERE expires_at < now()`\n * filter on read) clears abandoned rows.\n *\n * Columns:\n * - `state` — opaque random token, primary key.\n * - `user_id` — text (matches the consumer-defined user-id shape;\n * the auth subsystem doesn't constrain this to UUID\n * because some apps key users by external id).\n * - `redirect` — optional post-callback redirect path.\n * - `expires_at` — TTL boundary; entries past this are treated as absent.\n *\n * Convention: schema files live at the root of the subsystem dir\n * (mirrors `cache.schema.ts`, `integration-audit.schema.ts`, `domain-events.schema.ts`).\n */\nimport { pgTable, text, timestamp } from 'drizzle-orm/pg-core';\nimport type { InferSelectModel } from 'drizzle-orm';\n\nexport const authOAuthState = pgTable('auth_oauth_state', {\n state: text('state').primaryKey(),\n userId: text('user_id').notNull(),\n redirect: text('redirect'),\n expiresAt: timestamp('expires_at', { withTimezone: true }).notNull(),\n});\n\nexport type AuthOAuthState = InferSelectModel<typeof authOAuthState>;\n","/**\n * Env-backed AES-256-GCM encryption.\n *\n * Framing: `base64( nonce(12B) || ciphertext || authTag(16B) )`. Random nonce\n * per call means two encryptions of the same plaintext produce different\n * ciphertexts — prevents replay-style inference. Auth tag enforces integrity;\n * any tampering throws on decrypt.\n *\n * Key source: `INTEGRATION_TOKEN_ENCRYPTION_KEY` env var, 32 bytes base64-encoded.\n * Generate via `openssl rand -base64 32`.\n *\n * Future backend: `kms.ts` (AWS/GCP KMS) for production deployments that\n * need key rotation + audit trails.\n */\nimport { createCipheriv, createDecipheriv, randomBytes } from 'node:crypto';\nimport type { IEncryptionKey } from '../../protocols/encryption-key';\n\nexport interface EnvEncryptionKeyOptions {\n /** Defaults to `process.env`. Tests inject a fixture. */\n env?: NodeJS.ProcessEnv;\n /** Defaults to `'INTEGRATION_TOKEN_ENCRYPTION_KEY'`. */\n envVar?: string;\n}\n\nconst ALGO = 'aes-256-gcm';\nconst NONCE_BYTES = 12;\nconst TAG_BYTES = 16;\nconst KEY_BYTES = 32;\n\nexport class EnvEncryptionKey implements IEncryptionKey {\n private readonly key: Buffer;\n\n constructor(opts: EnvEncryptionKeyOptions = {}) {\n const env = opts.env ?? process.env;\n const envVar = opts.envVar ?? 'INTEGRATION_TOKEN_ENCRYPTION_KEY';\n const raw = env[envVar];\n if (!raw) {\n throw new Error(\n `EnvEncryptionKey: ${envVar} is not set. Generate with: openssl rand -base64 32`,\n );\n }\n const decoded = Buffer.from(raw, 'base64');\n if (decoded.length !== KEY_BYTES) {\n throw new Error(\n `EnvEncryptionKey: ${envVar} must decode to ${KEY_BYTES} bytes (got ${decoded.length}). Use: openssl rand -base64 32`,\n );\n }\n this.key = decoded;\n }\n\n async encrypt(plaintext: string): Promise<string> {\n const nonce = randomBytes(NONCE_BYTES);\n const cipher = createCipheriv(ALGO, this.key, nonce);\n const ciphertext = Buffer.concat([\n cipher.update(plaintext, 'utf8'),\n cipher.final(),\n ]);\n const authTag = cipher.getAuthTag();\n return Buffer.concat([nonce, ciphertext, authTag]).toString('base64');\n }\n\n async decrypt(ciphertext: string): Promise<string> {\n const buf = Buffer.from(ciphertext, 'base64');\n if (buf.length < NONCE_BYTES + TAG_BYTES) {\n throw new Error('EnvEncryptionKey: ciphertext too short');\n }\n const nonce = buf.subarray(0, NONCE_BYTES);\n const authTag = buf.subarray(buf.length - TAG_BYTES);\n const body = buf.subarray(NONCE_BYTES, buf.length - TAG_BYTES);\n\n const decipher = createDecipheriv(ALGO, this.key, nonce);\n decipher.setAuthTag(authTag);\n const plain = Buffer.concat([decipher.update(body), decipher.final()]);\n return plain.toString('utf8');\n }\n}\n","/**\n * In-memory `IOAuthStateStore` backend.\n *\n * Single-process store — Map<state, { record, expiresAt }>. Suitable for\n * tests and single-worker dev. Production deployments select the drizzle\n * backend so state survives restarts and is shared across workers.\n *\n * Single-use semantics:\n * - `generate(record)` mints a 256-bit random token (base64url, opaque).\n * - `consume(state)` deletes the entry on read. A second call with the\n * same state throws `OAuthStateError('replay')`.\n * - Expired entries also throw (`'expired'`); the entry is deleted as a\n * side effect so a later replay still surfaces correctly.\n *\n * TTL defaults to 10 minutes — long enough for a user to complete the\n * provider's consent screen, short enough that abandoned states age out.\n */\nimport { randomBytes } from 'node:crypto';\nimport {\n type IOAuthStateStore,\n type OAuthStateRecord,\n OAuthStateError,\n} from '../protocols/oauth-state-store';\n\nexport interface MemoryOAuthStateStoreOptions {\n /** TTL in ms. Default 10 minutes. */\n ttlMs?: number;\n /** Injectable clock for tests. Default `Date.now`. */\n now?: () => number;\n /** Injectable token generator for tests. Default 32-byte base64url. */\n generateToken?: () => string;\n}\n\ninterface Slot {\n record: OAuthStateRecord;\n expiresAt: number;\n}\n\nexport class MemoryOAuthStateStore implements IOAuthStateStore {\n private readonly store = new Map<string, Slot>();\n private readonly ttlMs: number;\n private readonly now: () => number;\n private readonly generateToken: () => string;\n\n constructor(opts: MemoryOAuthStateStoreOptions = {}) {\n this.ttlMs = opts.ttlMs ?? 10 * 60 * 1000;\n this.now = opts.now ?? (() => Date.now());\n this.generateToken =\n opts.generateToken ?? (() => randomBytes(32).toString('base64url'));\n }\n\n async generate(record: OAuthStateRecord): Promise<string> {\n const state = this.generateToken();\n this.store.set(state, {\n record: { ...record },\n expiresAt: this.now() + this.ttlMs,\n });\n return state;\n }\n\n async consume(state: string): Promise<OAuthStateRecord> {\n const slot = this.store.get(state);\n if (!slot) {\n throw new OAuthStateError(\n `OAuth state token unknown or already consumed`,\n 'missing',\n );\n }\n // Delete first so a concurrent consume can't replay.\n this.store.delete(state);\n if (slot.expiresAt <= this.now()) {\n throw new OAuthStateError(`OAuth state token expired`, 'expired');\n }\n return slot.record;\n }\n}\n","/**\n * Drizzle-backed `IOAuthStateStore`.\n *\n * Uses the `auth_oauth_state` table (see `auth-oauth-state.schema.ts`).\n * Single-use semantics enforced via `DELETE ... RETURNING`: the consume\n * path atomically deletes and returns the row, so a concurrent /callback\n * with the same state cannot replay.\n *\n * Behaviour:\n * - `generate(record)` mints a 256-bit base64url token, INSERTs the row\n * with `expires_at = now() + ttlMs`.\n * - `consume(state)` runs `DELETE ... WHERE state = $1 RETURNING ...`\n * once. Throws `OAuthStateError('missing')` if no row was deleted\n * (unknown or already consumed) and `OAuthStateError('expired')` if\n * the deleted row was past its `expires_at`.\n */\nimport { randomBytes } from 'node:crypto';\nimport { eq } from 'drizzle-orm';\nimport type { DrizzleClient } from '../../../types/drizzle';\nimport { authOAuthState } from '../auth-oauth-state.schema';\nimport {\n type IOAuthStateStore,\n type OAuthStateRecord,\n OAuthStateError,\n} from '../protocols/oauth-state-store';\n\nexport interface DrizzleOAuthStateStoreOptions {\n /** TTL in ms. Default 10 minutes. */\n ttlMs?: number;\n /** Injectable clock for tests. Default `Date.now`. */\n now?: () => number;\n /** Injectable token generator for tests. Default 32-byte base64url. */\n generateToken?: () => string;\n}\n\nexport class DrizzleOAuthStateStore implements IOAuthStateStore {\n private readonly ttlMs: number;\n private readonly now: () => number;\n private readonly generateToken: () => string;\n\n constructor(\n private readonly db: DrizzleClient,\n opts: DrizzleOAuthStateStoreOptions = {},\n ) {\n this.ttlMs = opts.ttlMs ?? 10 * 60 * 1000;\n this.now = opts.now ?? (() => Date.now());\n this.generateToken =\n opts.generateToken ?? (() => randomBytes(32).toString('base64url'));\n }\n\n async generate(record: OAuthStateRecord): Promise<string> {\n const state = this.generateToken();\n const expiresAt = new Date(this.now() + this.ttlMs);\n await this.db.insert(authOAuthState).values({\n state,\n userId: record.userId,\n redirect: record.redirect ?? null,\n expiresAt,\n });\n return state;\n }\n\n async consume(state: string): Promise<OAuthStateRecord> {\n const rows = await this.db\n .delete(authOAuthState)\n .where(eq(authOAuthState.state, state))\n .returning();\n const row = rows[0];\n if (!row) {\n throw new OAuthStateError(\n `OAuth state token unknown or already consumed`,\n 'missing',\n );\n }\n if (row.expiresAt.getTime() <= this.now()) {\n throw new OAuthStateError(`OAuth state token expired`, 'expired');\n }\n return {\n userId: row.userId,\n redirect: row.redirect ?? undefined,\n };\n }\n}\n","/**\n * AuthController — provider-agnostic OAuth2 connect/callback dance.\n *\n * Mounts two routes:\n * - `GET /auth/:provider/connect?redirect=...` — generates state, builds\n * the provider's authorize-url, 302-redirects the browser there.\n * - `GET /auth/:provider/callback?code=...&state=...` — consumes state,\n * exchanges the code for tokens, hands them to the grant sink, then\n * 302-redirects to the post-connect path.\n *\n * Hexagonal seams:\n * - `STRATEGY_REGISTRY` (ReadonlyMap<slug, IProviderStrategy>) — dispatch.\n * Concrete per-provider strategies live consumer-side and contribute\n * entries via a `useFactory` in the consumer's app module.\n * - `AUTH_USER_CONTEXT` (IUserContext) — resolves \"who is this request\"\n * from the consumer's session/JWT/etc.\n * - `OAUTH_STATE_STORE` (IOAuthStateStore) — CSRF state minting/consume.\n * - `AUTH_CONNECTION_GRANT_SINK` (IConnectionGrantSink) — persists the\n * freshly-minted grant. Adapter lives consumer-side (e.g. the\n * auth-integrations starter from #285).\n *\n * The controller never imports `ConnectionsService` or any other concrete\n * consumer type — it goes through ports only.\n */\nimport {\n Controller,\n Get,\n Inject,\n Param,\n Query,\n Req,\n Res,\n HttpException,\n HttpStatus,\n} from '@nestjs/common';\nimport {\n AUTH_CONNECTION_GRANT_SINK,\n AUTH_OPTIONS,\n AUTH_USER_CONTEXT,\n OAUTH_STATE_STORE,\n STRATEGY_REGISTRY,\n} from '../auth.tokens';\nimport type { AuthModuleOptions } from '../auth.module';\nimport type { IOAuthStateStore } from '../protocols/oauth-state-store';\nimport type { IUserContext } from '../protocols/user-context';\nimport type {\n IProviderStrategy,\n ProviderStrategyRegistry,\n} from '../protocols/provider-strategy';\nimport type { IConnectionGrantSink } from '../protocols/connection-store';\n\n/**\n * Minimal response surface used by the controller — typed loosely so we\n * don't pull a hard dep on `express` or `fastify`. Both popular HTTP\n * adapters expose `redirect(status, url)`.\n */\ninterface RedirectingResponse {\n redirect(statusCode: number, url: string): unknown;\n}\n\n@Controller('auth')\nexport class AuthController {\n constructor(\n @Inject(STRATEGY_REGISTRY)\n private readonly registry: ProviderStrategyRegistry,\n @Inject(AUTH_USER_CONTEXT)\n private readonly userContext: IUserContext,\n @Inject(OAUTH_STATE_STORE)\n private readonly stateStore: IOAuthStateStore,\n @Inject(AUTH_CONNECTION_GRANT_SINK)\n private readonly grantSink: IConnectionGrantSink,\n @Inject(AUTH_OPTIONS)\n private readonly options: AuthModuleOptions,\n ) {}\n\n @Get(':provider/connect')\n async connect(\n @Param('provider') slug: string,\n @Query('redirect') redirect: string | undefined,\n @Req() req: unknown,\n @Res() res: RedirectingResponse,\n ): Promise<unknown> {\n const strategy = this.requireStrategy(slug);\n const userId = await this.userContext.getCurrentUserId(req);\n const state = await this.stateStore.generate({ userId, redirect });\n const url = strategy.buildAuthorizeUrl({\n state,\n redirectUri: this.redirectUriFor(slug),\n });\n return res.redirect(HttpStatus.FOUND, url);\n }\n\n @Get(':provider/callback')\n async callback(\n @Param('provider') slug: string,\n @Query('code') code: string | undefined,\n @Query('state') state: string | undefined,\n @Res() res: RedirectingResponse,\n ): Promise<unknown> {\n const strategy = this.requireStrategy(slug);\n if (!code) {\n throw new HttpException(\n `Missing 'code' query param`,\n HttpStatus.BAD_REQUEST,\n );\n }\n if (!state) {\n throw new HttpException(\n `Missing 'state' query param`,\n HttpStatus.BAD_REQUEST,\n );\n }\n const { userId, redirect } = await this.stateStore.consume(state);\n const tokens = await strategy.exchangeCodeForTokens({\n code,\n redirectUri: this.redirectUriFor(slug),\n });\n await this.grantSink.createOrUpdateFromOAuthGrant({\n userId,\n provider: slug,\n accessToken: tokens.accessToken,\n refreshToken: tokens.refreshToken,\n expiresAt: tokens.expiresAt,\n scope: tokens.scope,\n externalAccountId: tokens.externalAccountId,\n providerMetadata: tokens.providerMetadata,\n });\n return res.redirect(\n HttpStatus.FOUND,\n redirect ?? `/settings/connections?connected=${encodeURIComponent(slug)}`,\n );\n }\n\n private requireStrategy(slug: string): IProviderStrategy {\n const strategy = this.registry.get(slug);\n if (!strategy) {\n throw new HttpException(\n `Unknown provider '${slug}'`,\n HttpStatus.NOT_FOUND,\n );\n }\n return strategy;\n }\n\n private redirectUriFor(slug: string): string {\n const base = this.options.redirectUriBase;\n if (!base) {\n throw new Error(\n `AuthModule.forRoot: redirectUriBase is required when AuthController is enabled`,\n );\n }\n const trimmed = base.replace(/\\/+$/, '');\n return `${trimmed}/auth/${encodeURIComponent(slug)}/callback`;\n }\n}\n","/**\n * Ambient requester context — AsyncLocalStorage-backed tenant scope.\n *\n * The alternative to threading `userId`/`organizationId` through every\n * repository/service signature. Set ONCE at each boundary the generated app\n * owns, read implicitly inside `BaseRepository` (see `scopePredicate`).\n *\n * ## Where to set it (boundaries)\n *\n * - HTTP / tRPC handlers — from the authenticated `ctx.user`\n * - OAuth callback controllers — from the authenticated session\n * - Queue/worker `process()` — from the job's owning user after the\n * job's record is loaded\n *\n * Each boundary wraps the rest of the request in `withRequester({ userId,\n * organizationId }, () => ...)`. The context propagates through every `await`\n * to all downstream repo/service calls without being passed explicitly.\n *\n * ## Where to read it\n *\n * - `BaseRepository.scopePredicate()` reads it (via `tryGetRequester` in\n * lenient mode, `requireRequester` in strict mode) and filters every read\n * by the ambient scope when the repo declares `userTracking: true`.\n *\n * ## Why AsyncLocalStorage over an explicit parameter\n *\n * Threading `userId` (and later `organizationId`) through dozens of method\n * signatures is pure parameter pollution. Ambient context also lets a repo\n * make the \"I forgot to scope\" mistake impossible at runtime: in strict mode\n * `requireRequester()` throws when no context is active, surfacing a missing\n * boundary call loudly rather than silently leaking cross-tenant data.\n *\n * ## Not-found semantics\n *\n * When a row exists but belongs to a different requester, scoped reads return\n * `null`/`[]` — identical to \"truly doesn't exist\". No existence oracle;\n * callers throw NotFound uniformly. Standard security practice.\n *\n * ## Testing\n *\n * Tests that exercise scoped repos must wrap the call in `withRequester(...)`.\n * In strict mode an unwrapped call hitting `requireRequester()` throws — by\n * design. In lenient mode (the default) an unwrapped call is simply unscoped.\n */\nimport { AsyncLocalStorage } from 'node:async_hooks';\n\n/**\n * Data-visibility scope. The auth layer decides which scope a request is\n * allowed to claim; the repo trusts whatever the ambient context says.\n *\n * - `'user'`: filter every read by `user_id = ctx.userId`. Default.\n * - `'org'`: filter every read by membership in the requester's org, resolved\n * via `user_id IN (ctx.orgUserIds)` rather than via a per-entity\n * `organization_id` column. Works for every user-owned table and keeps repos\n * single-table — the org member list is pre-resolved at the boundary.\n * - `'superuser'`: no scope filter. Engineering / internal-tools only.\n *\n * AUTHORIZATION (who is allowed to claim each scope) lives in boundary\n * middleware, not in the repo. The repo trusts the ambient context — same\n * trust model as a threaded `userId`.\n */\nexport type RequesterScope = 'user' | 'org' | 'superuser';\n\nexport interface RequesterContext {\n /**\n * The user making the request. Always present — even in `'org'` and\n * `'superuser'` scopes it is the audit-trail \"who actually did this\".\n */\n readonly userId: string;\n /**\n * The organization the requester belongs to. Required when\n * `scope === 'org'`; may be null for `'user'` (users with no org) and for\n * `'superuser'` (cross-org reads).\n */\n readonly organizationId: string | null;\n /**\n * Data-visibility scope. Defaults to `'user'` when omitted.\n */\n readonly scope?: RequesterScope;\n /**\n * For `scope === 'org'`: the list of user IDs in the requester's org,\n * pre-resolved by the boundary middleware that established the `'org'`\n * scope (one `SELECT users.id WHERE organization_id = X` at the trust\n * boundary). Repos use this as a literal `IN (...)` filter — they never\n * JOIN to `users` themselves. Required when `scope === 'org'`.\n */\n readonly orgUserIds?: readonly string[];\n}\n\nconst als = new AsyncLocalStorage<RequesterContext>();\n\n/**\n * Set the ambient requester context for the duration of `fn`. The context\n * propagates through `await` boundaries to all downstream calls. Nesting is\n * fine — an inner `withRequester` overrides the outer for its callback.\n */\nexport function withRequester<T>(\n ctx: RequesterContext,\n fn: () => Promise<T>,\n): Promise<T> {\n return als.run(ctx, fn);\n}\n\n/**\n * Read the ambient requester context. Throws if no context is active — by\n * design. Used by repos in strict scope-enforcement mode; an unwrapped call\n * site is a missing boundary.\n */\nexport function requireRequester(): RequesterContext {\n const ctx = als.getStore();\n if (!ctx) {\n throw new Error(\n 'No requester context active. Wrap the entry point in ' +\n 'withRequester({ userId, organizationId }, fn). See tenant-context.ts.',\n );\n }\n return ctx;\n}\n\n/**\n * Read the ambient requester context without throwing. Returns `undefined`\n * when no context is active. Used by repos in lenient scope-enforcement mode\n * (the default) and by code paths that legitimately run outside a request.\n */\nexport function tryGetRequester(): RequesterContext | undefined {\n return als.getStore();\n}\n\n/**\n * Resolve the effective scope for the ambient context, defaulting to `'user'`.\n */\nexport function requireRequesterScope(): RequesterScope {\n return requireRequester().scope ?? 'user';\n}\n\n/**\n * Convenience helpers for setting scope explicitly. All three preserve\n * `userId` in the context (audit trail) regardless of scope.\n *\n * - `withUserScope`: regular end-user requests. Most call sites.\n * - `withOrgScope`: admin / org-shared resource access. The caller MUST verify\n * the requester's role permits `'org'` before calling — the helper does not\n * enforce authorization. `orgUserIds` is pre-resolved at the boundary.\n * - `withSuperuserScope`: engineering scripts / internal tools. `organizationId`\n * is null (cross-org is the point). Same authorization caveat applies.\n */\nexport function withUserScope<T>(\n userId: string,\n organizationId: string | null,\n fn: () => Promise<T>,\n): Promise<T> {\n return withRequester({ userId, organizationId, scope: 'user' }, fn);\n}\n\nexport function withOrgScope<T>(\n userId: string,\n organizationId: string,\n orgUserIds: readonly string[],\n fn: () => Promise<T>,\n): Promise<T> {\n return withRequester(\n { userId, organizationId, scope: 'org', orgUserIds },\n fn,\n );\n}\n\nexport function withSuperuserScope<T>(\n userId: string,\n fn: () => Promise<T>,\n): Promise<T> {\n return withRequester(\n { userId, organizationId: null, scope: 'superuser' },\n fn,\n );\n}\n","/**\n * AuthModule — DynamicModule factory for the auth subsystem.\n *\n * Wires the pluggable backends the subsystem ships with:\n * - `ENCRYPTION_KEY` → `EnvEncryptionKey` (AES-256-GCM from env)\n * - `OAUTH_STATE_STORE` → `MemoryOAuthStateStore` (dev/tests) or\n * `DrizzleOAuthStateStore` (prod, requires\n * DRIZZLE provider).\n * - `AUTH_OPTIONS` → resolved options bag (used by AuthController\n * for `redirectUriBase`).\n *\n * The connection-store ports (`AUTH_CONNECTION_READER`,\n * `AUTH_CONNECTION_TOKEN_WRITER`, `AUTH_CONNECTION_GRANT_SINK`),\n * `AUTH_USER_CONTEXT`, and `STRATEGY_REGISTRY` are deliberately **not**\n * wired here — they are always consumer-specific:\n * - connection-store ports adapt the consumer's `connections` storage;\n * - `IUserContext` adapts the app's session/JWT scheme;\n * - `STRATEGY_REGISTRY` is populated from the per-provider strategy\n * classes the consumer maintains.\n *\n * Consumers provide them in their app module (or by importing the\n * `auth-integrations` starter, which binds the three connection-store\n * ports off a single canonical entity).\n *\n * Usage in AppModule:\n * ```typescript\n * AuthModule.forRoot({\n * encryptionKey: 'env',\n * oauthStateStore: 'memory', // or 'drizzle'\n * enableController: true,\n * redirectUriBase: 'http://localhost:3000',\n * });\n * ```\n *\n * `global: true` means other modules don't need to re-import AuthModule to\n * inject the auth tokens.\n */\nimport { Module, type DynamicModule, type Provider } from '@nestjs/common';\nimport {\n AUTH_OPTIONS,\n ENCRYPTION_KEY,\n OAUTH_STATE_STORE,\n} from './auth.tokens';\nimport { EnvEncryptionKey } from './backends/encryption-key/env';\nimport { MemoryOAuthStateStore } from './backends/state-store.memory-backend';\nimport { DrizzleOAuthStateStore } from './backends/state-store.drizzle-backend';\nimport { AuthController } from './controllers/auth.controller';\nimport { DRIZZLE } from '../../constants/tokens';\nimport type { DrizzleClient } from '../../types/drizzle';\n\ntype EncryptionKeyChoice =\n | 'env'\n | Omit<Provider, 'provide'>;\n\ntype OAuthStateStoreChoice =\n | 'memory'\n | 'drizzle'\n | Omit<Provider, 'provide'>;\n\nexport interface AuthModuleOptions {\n /** `'env'` (default) or a full provider definition (e.g. `{ useClass: MyKmsEncryptionKey }`). */\n encryptionKey?: EncryptionKeyChoice;\n /**\n * `'memory'` (default — tests/dev) or `'drizzle'` (prod, requires DRIZZLE\n * provider) or a full provider definition for a custom impl.\n */\n oauthStateStore?: OAuthStateStoreChoice;\n /**\n * Mount `AuthController` (`/auth/:provider/connect` + `/callback`).\n * Default `false` — apps that hand-roll connect/callback (rare) or that\n * use the subsystem only for the refresh path can opt out.\n */\n enableController?: boolean;\n /**\n * Public base URL of the API server. Used to construct per-provider\n * callback URIs as `${redirectUriBase}/auth/:provider/callback`.\n * Required when `enableController: true`.\n */\n redirectUriBase?: string;\n}\n\nfunction resolveEncryptionKeyProvider(choice: EncryptionKeyChoice): Provider {\n if (choice === 'env') {\n return { provide: ENCRYPTION_KEY, useClass: EnvEncryptionKey };\n }\n return { provide: ENCRYPTION_KEY, ...choice } as Provider;\n}\n\nfunction resolveOAuthStateStoreProvider(\n choice: OAuthStateStoreChoice,\n): Provider {\n if (choice === 'memory') {\n return { provide: OAUTH_STATE_STORE, useClass: MemoryOAuthStateStore };\n }\n if (choice === 'drizzle') {\n return {\n provide: OAUTH_STATE_STORE,\n useFactory: (db: DrizzleClient | null) => {\n if (!db) {\n throw new Error(\n \"AuthModule.forRoot: oauthStateStore: 'drizzle' selected but DRIZZLE provider is not available. \" +\n 'Ensure DatabaseModule (or another provider exposing DRIZZLE) is imported before AuthModule.forRoot.',\n );\n }\n return new DrizzleOAuthStateStore(db);\n },\n inject: [{ token: DRIZZLE, optional: true }],\n };\n }\n return { provide: OAUTH_STATE_STORE, ...choice } as Provider;\n}\n\n@Module({})\nexport class AuthModule {\n static forRoot(options: AuthModuleOptions = {}): DynamicModule {\n const resolved: AuthModuleOptions = {\n encryptionKey: options.encryptionKey ?? 'env',\n oauthStateStore: options.oauthStateStore ?? 'memory',\n enableController: options.enableController ?? false,\n redirectUriBase: options.redirectUriBase,\n };\n\n if (resolved.enableController && !resolved.redirectUriBase) {\n throw new Error(\n 'AuthModule.forRoot: redirectUriBase is required when enableController: true',\n );\n }\n\n const encryptionKeyProvider = resolveEncryptionKeyProvider(\n resolved.encryptionKey!,\n );\n const oauthStateStoreProvider = resolveOAuthStateStoreProvider(\n resolved.oauthStateStore!,\n );\n const optionsProvider: Provider = {\n provide: AUTH_OPTIONS,\n useValue: resolved,\n };\n\n return {\n module: AuthModule,\n global: true,\n providers: [encryptionKeyProvider, oauthStateStoreProvider, optionsProvider],\n controllers: resolved.enableController ? [AuthController] : [],\n exports: [ENCRYPTION_KEY, OAUTH_STATE_STORE, AUTH_OPTIONS],\n };\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;AAGO,IAAM,MAAM;AAGZ,IAAM,WAAW,CAAC,MAAc,SAAyB,GAAG,GAAG,IAAI,IAAI,IAAI,IAAI;;;ACO/E,IAAM,YAAY;AAgBlB,IAAM,kBAAkB;AAiBxB,IAAM,kBAAkB;AAcxB,IAAM,sBAAsB;AAW5B,IAAM,YAAY,OAAO,IAAI,SAAS,UAAU,WAAW,CAAC;AAa5D,IAAM,wBAAwB;;;ACjFrC,SAAS,YAAY,cAAc;AACnC,SAAS,kBAAkB;;;ACepB,IAAM,uBAAN,cAAmC,MAAM;AAAA,EAE9C,YAA4B,WAAmB;AAC7C;AAAA,MACE,+BAA+B,SAAS;AAAA,IAI1C;AAN0B;AAAA,EAO5B;AAAA,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sql","Injectable","Inject","Inject","Injectable","Logger","Optional","toEventSummary","Logger","Injectable","Optional","Inject","pgTable","uuid","text","jsonb","timestamp","index","sql","HandlerRegistry","randomUUID","Inject","Injectable","Logger","and","desc","eq","inArray","sql","MissingTenantIdError","Logger","MissingTenantIdError","eq","dedupeKey","and","desc","inArray","randomUUID","sql","Injectable","Inject","Inject","Injectable","and","asc","desc","eq","gte","inArray","lt","or","sql","MissingTenantIdError","eq","inArray","asc","desc","and","sql","gte","or","lt","Injectable","Inject","Inject","Injectable","and","eq","and","eq","Injectable","Inject","jobs","Inject","Injectable","Logger","and","asc","desc","eq","inArray","lt","sql","Logger","and","eq","resolve","desc","asc","lt","inArray","sql","Injectable","Inject","randomUUID","Inject","Injectable","Logger","Optional","randomUUID","Inject","Injectable","randomUUID","Injectable","Inject","TERMINAL_STATUSES","DEDUPE_EXCLUDED_STATUSES","IN_FLIGHT_STATUSES","evaluateKeyTemplate","Logger","MissingTenantIdError","dedupeKey","randomUUID","classifyError","computeBackoff","serialiseError","Injectable","Inject","Optional","Inject","Injectable","NON_TERMINAL_STATUSES","MissingTenantIdError","Injectable","Inject","Module","Module","Inject","Injectable","Logger","Module","Optional","ModuleRef","DEFAULT_SHUTDOWN_TIMEOUT_MS","Logger","Injectable","Inject","Optional","ModuleRef","Module","Module","Injectable","Inject","Optional","gt","or","sql","eq","pgTable","text","jsonb","timestamp","sql","eq","or","gt","Injectable","Inject","Optional","Injectable","Inject","Optional","Injectable","Optional","Inject","Module","existsSync","readFileSync","resolve","resolve","existsSync","readFileSync","Module","Module","Module","Inject","Injectable","Optional","jobRuns","integrationRuns","Injectable","Optional","Inject","Inject","Injectable","Logger","Logger","Injectable","Inject","Module","z","z","MissingTenantIdError","pgEnum","pgTable","uuid","text","jsonb","integer","timestamp","index","uniqueIndex","Injectable","Injectable","Injectable","Injectable","Injectable","out","Injectable","Inject","Injectable","Logger","Optional","Logger","Injectable","Inject","Optional","Inject","Injectable","Optional","and","desc","eq","eq","desc","and","Injectable","Inject","Optional","Inject","Injectable","Optional","and","desc","eq","eq","and","desc","Injectable","Inject","Optional","Module","Module","pgTable","text","timestamp","randomBytes","randomBytes","randomBytes","eq","randomBytes","eq","Inject","Inject","Module","Module"]}