@pattern-stack/codegen 0.11.0 → 0.12.0
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.
- package/CHANGELOG.md +60 -0
- package/dist/runtime/subsystems/index.d.ts +7 -3
- package/dist/runtime/subsystems/index.js +993 -19
- package/dist/runtime/subsystems/index.js.map +1 -1
- package/dist/runtime/subsystems/integration/entity-change-source-registry.memory.d.ts +25 -0
- package/dist/runtime/subsystems/integration/entity-change-source-registry.memory.js +34 -0
- package/dist/runtime/subsystems/integration/entity-change-source-registry.memory.js.map +1 -0
- package/dist/runtime/subsystems/integration/entity-change-source-registry.protocol.d.ts +53 -0
- package/dist/runtime/subsystems/integration/entity-change-source-registry.protocol.js +13 -0
- package/dist/runtime/subsystems/integration/entity-change-source-registry.protocol.js.map +1 -0
- package/dist/runtime/subsystems/integration/execute-integration.use-case.js.map +1 -1
- package/dist/runtime/subsystems/integration/index.d.ts +3 -1
- package/dist/runtime/subsystems/integration/index.js +35 -0
- package/dist/runtime/subsystems/integration/index.js.map +1 -1
- package/dist/runtime/subsystems/integration/integration-cursor-store.drizzle-backend.js.map +1 -1
- package/dist/runtime/subsystems/integration/integration-run-recorder.drizzle-backend.js.map +1 -1
- package/dist/runtime/subsystems/integration/integration.module.js.map +1 -1
- package/dist/runtime/subsystems/integration/integration.tokens.d.ts +14 -1
- package/dist/runtime/subsystems/integration/integration.tokens.js +2 -0
- package/dist/runtime/subsystems/integration/integration.tokens.js.map +1 -1
- package/dist/runtime/subsystems/observability/index.js.map +1 -1
- package/dist/runtime/subsystems/observability/observability.module.js.map +1 -1
- package/dist/runtime/subsystems/observability/observability.service.js.map +1 -1
- package/dist/src/cli/index.js +1074 -107
- package/dist/src/cli/index.js.map +1 -1
- package/dist/src/index.d.ts +48 -0
- package/dist/src/index.js +99 -3
- package/dist/src/index.js.map +1 -1
- package/package.json +9 -1
- package/runtime/subsystems/index.ts +15 -0
- package/runtime/subsystems/integration/entity-change-source-registry.memory.ts +40 -0
- package/runtime/subsystems/integration/entity-change-source-registry.protocol.ts +59 -0
- package/runtime/subsystems/integration/index.ts +9 -0
- package/runtime/subsystems/integration/integration.tokens.ts +14 -0
- package/templates/entity/new/clean-lite-ps/entity.ejs.t +12 -3
- package/templates/entity/new/clean-lite-ps/prompt-extension.js +212 -29
- package/templates/entity/new/backend/modules/core/integration-source.providers.ejs.t +0 -18
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../runtime/subsystems/integration/integration.module.ts","../../../../runtime/subsystems/integration/integration.tokens.ts","../../../../runtime/subsystems/integration/integration-cursor-store.memory-backend.ts","../../../../runtime/subsystems/integration/integration-run-recorder.memory-backend.ts","../../../../runtime/subsystems/integration/integration-field-diff.protocol.ts","../../../../runtime/subsystems/integration/integration-cursor-store.drizzle-backend.ts","../../../../runtime/constants/tokens.ts","../../../../runtime/subsystems/integration/integration-audit.schema.ts","../../../../runtime/subsystems/integration/integration-errors.ts","../../../../runtime/subsystems/integration/integration-run-recorder.drizzle-backend.ts","../../../../runtime/subsystems/integration/deep-equal.differ.ts"],"sourcesContent":["/**\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 * 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 * 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 * 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 * 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 * 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 * 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 * 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 * 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 * 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"],"mappings":";;;;;;;;;;;;;AA+DA,SAAS,cAAiD;;;ACxCnD,IAAM,2BAA2B;AACjC,IAAM,2BAA2B;AAOjC,IAAM,2BAA2B;AASjC,IAAM,6BAA6B;AAQnC,IAAM,2BAA2B;;;ACpBxC,SAAS,kBAAkB;AAQpB,IAAM,oBAAN,MAAgD;AAAA;AAAA;AAAA;AAAA;AAAA,EAK5C,UAAgC,oBAAI,IAAI;AAAA;AAAA;AAAA;AAAA;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AE,SAAS,0BAA0B,UAAU,8BAA8B;AAAA,IAC/E;AAEN,WAAO;AAAA,MACL,QAAQ;AAAA,MACR,QAAQ;AAAA,MACR,WAAW,CAAC,GAAG,iBAAiB,GAAG,gBAAgB;AAAA,MACnD,SAAS;AAAA,QACP;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,MACF;AAAA,IACF;AAAA,EACF;AACF;AAlDa,oBAAN;AAAA,EADN,OAAO,CAAC,CAAC;AAAA,GACG;","names":["Injectable","Injectable","Injectable","Injectable","Inject","Injectable","Optional","and","desc","eq","eq","and","desc","Injectable","Inject","Optional","Injectable","out","Injectable"]}
|
|
1
|
+
{"version":3,"sources":["../../../../runtime/subsystems/integration/integration.module.ts","../../../../runtime/subsystems/integration/integration.tokens.ts","../../../../runtime/subsystems/integration/integration-cursor-store.memory-backend.ts","../../../../runtime/subsystems/integration/integration-run-recorder.memory-backend.ts","../../../../runtime/subsystems/integration/integration-field-diff.protocol.ts","../../../../runtime/subsystems/integration/integration-cursor-store.drizzle-backend.ts","../../../../runtime/constants/tokens.ts","../../../../runtime/subsystems/integration/integration-audit.schema.ts","../../../../runtime/subsystems/integration/integration-errors.ts","../../../../runtime/subsystems/integration/integration-run-recorder.drizzle-backend.ts","../../../../runtime/subsystems/integration/deep-equal.differ.ts"],"sourcesContent":["/**\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 * 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 * 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 * 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 * 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 * 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 * 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 * 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 * 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 * 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"],"mappings":";;;;;;;;;;;;;AA+DA,SAAS,cAAiD;;;ACxCnD,IAAM,2BAA2B;AACjC,IAAM,2BAA2B;AAOjC,IAAM,2BAA2B;AASjC,IAAM,6BAA6B;AAQnC,IAAM,2BAA2B;;;ACpBxC,SAAS,kBAAkB;AAQpB,IAAM,oBAAN,MAAgD;AAAA;AAAA;AAAA;AAAA;AAAA,EAK5C,UAAgC,oBAAI,IAAI;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAWxC,gBAA4D,oBAAI,IAAI;AAAA,EAE7E,MAAM,IACJ,gBACA,WACyB;AAGzB,UAAM,QAAQ,KAAK,QAAQ,IAAI,cAAc;AAC7C,WAAO,UAAU,SAAY,OAAO;AAAA,EACtC;AAAA,EAEA,MAAM,IACJ,gBACA,QACA,WACe;AAGf,SAAK,QAAQ,IAAI,gBAAgB,MAAM;AAAA,EACzC;AAAA,EAEA,MAAM,QAAQ,WAAsD;AAGlE,UAAM,YAA8B,CAAC;AACrC,eAAW,CAAC,gBAAgB,MAAM,KAAK,KAAK,QAAQ,QAAQ,GAAG;AAC7D,YAAM,OAAO,KAAK,cAAc,IAAI,cAAc;AAClD,gBAAU,KAAK;AAAA,QACb;AAAA,QACA,cAAc,MAAM,gBAAgB;AAAA,QACpC,SAAS,MAAM,WAAW;AAAA,QAC1B,QAAQ,MAAM,UAAU;AAAA,QACxB,aAAa,MAAM,eAAe;AAAA,QAClC,QAAQ,UAAU;AAAA,QAClB,mBAAmB,MAAM,qBAAqB;AAAA,QAC9C,WAAW,MAAM,aAAa,oBAAI,KAAK,CAAC;AA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AQ;AAAA,MACzD,EAAE,SAAS,0BAA0B,UAAU,YAAY;AAAA;AAAA;AAAA,MAG3D,EAAE,SAAS,0BAA0B,UAAU,IAAI,gBAAgB,EAAE;AAAA,IACvE;AAEA,UAAM,mBACJ,QAAQ,YAAY,WAChB;AAAA;AAAA;AAAA;AAAA,MAIE,EAAE,SAAS,mBAAmB,UAAU,IAAI,kBAAkB,EAAE;AAAA,MAChE;AAAA,QACE,SAAS;AAAA,QACT,aAAa;AAAA,MACf;AAAA,MACA,EAAE,SAAS,mBAAmB,UAAU,IAAI,kBAAkB,EAAE;AAAA,MAChE;AAAA,QACE,SAAS;AAAA,QACT,aAAa;AAAA,MACf;AAAA,IACF,IACA;AAAA;AAAA;AAAA;AAAA,MAIE,EAAE,SAAS,0BAA0B,UAAU,oBAAoB;AAAA,MACnE,EAAE,SAAS,0BAA0B,UAAU,8BAA8B;AAAA,IAC/E;AAEN,WAAO;AAAA,MACL,QAAQ;AAAA,MACR,QAAQ;AAAA,MACR,WAAW,CAAC,GAAG,iBAAiB,GAAG,gBAAgB;AAAA,MACnD,SAAS;AAAA,QACP;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,MACF;AAAA,IACF;AAAA,EACF;AACF;AAlDa,oBAAN;AAAA,EADN,OAAO,CAAC,CAAC;AAAA,GACG;","names":["Injectable","Injectable","Injectable","Injectable","Inject","Injectable","Optional","and","desc","eq","eq","and","desc","Injectable","Inject","Optional","Injectable","out","Injectable"]}
|
|
@@ -43,5 +43,18 @@ declare const INTEGRATION_MODULE_OPTIONS: "INTEGRATION_MODULE_OPTIONS";
|
|
|
43
43
|
* Consumed by `ExecuteIntegrationUseCase` to enforce the tenantId-is-required rule.
|
|
44
44
|
*/
|
|
45
45
|
declare const INTEGRATION_MULTI_TENANT: "INTEGRATION_MULTI_TENANT";
|
|
46
|
+
/**
|
|
47
|
+
* Injection token for the entity-keyed `IEntityChangeSourceRegistry` (C7,
|
|
48
|
+
* #336). Bound to the codegen-emitted aggregator that folds per-provider
|
|
49
|
+
* adapter contributions into one registry (RFC-0001 §3, emitted by Track D
|
|
50
|
+
* D3/D4).
|
|
51
|
+
*
|
|
52
|
+
* A string constant, not `Symbol.for(...)`, to match this subsystem's token
|
|
53
|
+
* convention (see file header). The originating issue's code block proposed a
|
|
54
|
+
* `Symbol.for('@pattern-stack/codegen.entity-change-source-registry')` key,
|
|
55
|
+
* predating the sync→integration consolidation onto string tokens; kept as a
|
|
56
|
+
* string here for internal consistency with the other INTEGRATION_* tokens.
|
|
57
|
+
*/
|
|
58
|
+
declare const ENTITY_CHANGE_SOURCE_REGISTRY: "ENTITY_CHANGE_SOURCE_REGISTRY";
|
|
46
59
|
|
|
47
|
-
export { INTEGRATION_CHANGE_SOURCE, INTEGRATION_CURSOR_STORE, INTEGRATION_FIELD_DIFFER, INTEGRATION_MODULE_OPTIONS, INTEGRATION_MULTI_TENANT, INTEGRATION_RUN_RECORDER, INTEGRATION_SINK };
|
|
60
|
+
export { ENTITY_CHANGE_SOURCE_REGISTRY, INTEGRATION_CHANGE_SOURCE, INTEGRATION_CURSOR_STORE, INTEGRATION_FIELD_DIFFER, INTEGRATION_MODULE_OPTIONS, INTEGRATION_MULTI_TENANT, INTEGRATION_RUN_RECORDER, INTEGRATION_SINK };
|
|
@@ -6,7 +6,9 @@ var INTEGRATION_SINK = "INTEGRATION_SINK";
|
|
|
6
6
|
var INTEGRATION_RUN_RECORDER = "INTEGRATION_RUN_RECORDER";
|
|
7
7
|
var INTEGRATION_MODULE_OPTIONS = "INTEGRATION_MODULE_OPTIONS";
|
|
8
8
|
var INTEGRATION_MULTI_TENANT = "INTEGRATION_MULTI_TENANT";
|
|
9
|
+
var ENTITY_CHANGE_SOURCE_REGISTRY = "ENTITY_CHANGE_SOURCE_REGISTRY";
|
|
9
10
|
export {
|
|
11
|
+
ENTITY_CHANGE_SOURCE_REGISTRY,
|
|
10
12
|
INTEGRATION_CHANGE_SOURCE,
|
|
11
13
|
INTEGRATION_CURSOR_STORE,
|
|
12
14
|
INTEGRATION_FIELD_DIFFER,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../runtime/subsystems/integration/integration.tokens.ts"],"sourcesContent":["/**\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"],"mappings":";AAsBO,IAAM,4BAA4B;AAClC,IAAM,2BAA2B;AACjC,IAAM,2BAA2B;AACjC,IAAM,mBAAmB;AAMzB,IAAM,2BAA2B;AASjC,IAAM,6BAA6B;AAQnC,IAAM,2BAA2B;","names":[]}
|
|
1
|
+
{"version":3,"sources":["../../../../runtime/subsystems/integration/integration.tokens.ts"],"sourcesContent":["/**\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"],"mappings":";AAsBO,IAAM,4BAA4B;AAClC,IAAM,2BAA2B;AACjC,IAAM,2BAA2B;AACjC,IAAM,mBAAmB;AAMzB,IAAM,2BAA2B;AASjC,IAAM,6BAA6B;AAQnC,IAAM,2BAA2B;AAcjC,IAAM,gCAAgC;","names":[]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../runtime/subsystems/observability/observability.tokens.ts","../../../../runtime/subsystems/observability/observability.module.ts","../../../../runtime/subsystems/observability/observability.service.ts","../../../../runtime/subsystems/jobs/jobs-domain.tokens.ts","../../../../runtime/subsystems/events/events.tokens.ts","../../../../runtime/subsystems/bridge/bridge.tokens.ts","../../../../runtime/subsystems/integration/integration.tokens.ts","../../../../runtime/subsystems/observability/reporters/bridge-metrics.reporter.ts","../../../../runtime/subsystems/observability/observability-errors.ts"],"sourcesContent":["/**\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 * 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 unique `Symbol` — guaranteed distinct from every other\n * Symbol at runtime, which is exactly the uniqueness guarantee Nest's DI\n * container relies on for token-based lookup.\n */\nexport const JOB_ORCHESTRATOR = Symbol('JOB_ORCHESTRATOR');\nexport const JOB_RUN_SERVICE = Symbol('JOB_RUN_SERVICE');\nexport const JOB_STEP_SERVICE = Symbol('JOB_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('JOBS_MULTI_TENANT');\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 */\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 */\nexport const REDIS_URL = Symbol('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","/**\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 * 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 * 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"],"mappings":";;;;;;;;;;;;;;;AAmBO,IAAM,gBAAgB;AAOtB,IAAM,+BAA+B;;;AC6B5C,SAAS,cAAiD;;;AC1B1D,SAAS,QAAQ,YAAY,gBAAgB;;;ACjBtC,IAAM,kBAAkB,uBAAO,iBAAiB;;;ACehD,IAAM,kBAAkB;;;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A,QACV;AAAA,QACA,eAAe,QAAQ,IAAI,QAAQ,OAAO,GAAG;AAAA,MAC/C;AAAA,IACF;AAAA,EACF;AACF;AAjEa,wBAAN;AAAA,EADNC,YAAW;AAAA,EAOP,mBAAAC,QAAO,aAAa;AAAA,EACpB,mBAAAA,QAAO,4BAA4B;AAAA,GAP3B;;;ANmDN,IAAM,sBAAN,MAA0B;AAAA,EAC/B,OAAO,QAAQ,UAAsC,CAAC,GAAkB;AACtE,UAAM,YAAwB;AAAA;AAAA;AAAA,MAG5B,EAAE,SAAS,8BAA8B,UAAU,QAAQ;AAAA;AAAA,MAE3D;AAAA;AAAA;AAAA;AAAA,MAIA,EAAE,SAAS,eAAe,aAAa,qBAAqB;AAAA,IAC9D;AAKA,QAAI,QAAQ,WAAW,eAAe,YAAY,MAAM;AACtD,gBAAU,KAAK,qBAAqB;AAAA,IACtC;AAEA,WAAO;AAAA,MACL,QAAQ;AAAA,MACR,QAAQ;AAAA,MACR;AAAA,MACA,SAAS,CAAC,eAAe,4BAA4B;AAAA,IACvD;AAAA,EACF;AACF;AA5Ba,sBAAN;AAAA,EADN,OAAO,CAAC,CAAC;AAAA,GACG;;;AOhGN,IAAM,qBAAN,cAAiC,MAAM;AAAA,EAC5C,YACE,SACkB,OAClB;AACA,UAAM,OAAO;AAFK;AAGlB,SAAK,OAAO;AAAA,EACd;AAAA,EAJoB;AAKtB;","names":["Inject","Injectable","Injectable","Inject"]}
|
|
1
|
+
{"version":3,"sources":["../../../../runtime/subsystems/observability/observability.tokens.ts","../../../../runtime/subsystems/observability/observability.module.ts","../../../../runtime/subsystems/observability/observability.service.ts","../../../../runtime/subsystems/jobs/jobs-domain.tokens.ts","../../../../runtime/subsystems/events/events.tokens.ts","../../../../runtime/subsystems/bridge/bridge.tokens.ts","../../../../runtime/subsystems/integration/integration.tokens.ts","../../../../runtime/subsystems/observability/reporters/bridge-metrics.reporter.ts","../../../../runtime/subsystems/observability/observability-errors.ts"],"sourcesContent":["/**\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 * 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 unique `Symbol` — guaranteed distinct from every other\n * Symbol at runtime, which is exactly the uniqueness guarantee Nest's DI\n * container relies on for token-based lookup.\n */\nexport const JOB_ORCHESTRATOR = Symbol('JOB_ORCHESTRATOR');\nexport const JOB_RUN_SERVICE = Symbol('JOB_RUN_SERVICE');\nexport const JOB_STEP_SERVICE = Symbol('JOB_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('JOBS_MULTI_TENANT');\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 */\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 */\nexport const REDIS_URL = Symbol('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","/**\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 * 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"],"mappings":";;;;;;;;;;;;;;;AAmBO,IAAM,gBAAgB;AAOtB,IAAM,+BAA+B;;;AC6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