@happyvertical/smrt-jobs 0.61.2 → 0.61.4
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/AGENTS.md +3 -3
- package/dist/chunks/{runner-BUlKrA4Z.js → runner-BRwm00s-.js} +160 -25
- package/dist/chunks/runner-BRwm00s-.js.map +1 -0
- package/dist/index.js +13 -15
- package/dist/index.js.map +1 -1
- package/dist/manifest.json +797 -500
- package/dist/runner.d.ts.map +1 -1
- package/dist/runner.js +1 -1
- package/dist/schedule-runner.d.ts.map +1 -1
- package/dist/smrt-job-dedupe-slot.d.ts.map +1 -1
- package/dist/smrt-job-event.d.ts.map +1 -1
- package/dist/smrt-knowledge.json +138 -132
- package/dist/smrt-knowledge.okf.md +6 -2
- package/dist/terminal-outcome.d.ts.map +1 -1
- package/dist/worker-liveness-thread.js +11 -3
- package/dist/worker-liveness-thread.js.map +1 -1
- package/dist/worker-liveness-ticker.d.ts +23 -8
- package/dist/worker-liveness-ticker.d.ts.map +1 -1
- package/dist/worker-liveness.d.ts +37 -7
- package/dist/worker-liveness.d.ts.map +1 -1
- package/package.json +11 -11
- package/dist/chunks/runner-BUlKrA4Z.js.map +0 -1
- package/dist/chunks/worker-liveness-C1Gjnhax.js +0 -58
- package/dist/chunks/worker-liveness-C1Gjnhax.js.map +0 -1
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":["result"],"sources":["../src/durable-payload-integrity.ts","../src/forge-projection.ts","../src/job-handle.ts","../src/job-builder.ts","../src/object-extension.ts","../src/schedule-admission.ts","../src/schedule-runner.ts","../src/index.ts"],"sourcesContent":["import { createHmac, timingSafeEqual } from 'node:crypto';\n\nexport interface DurableJobPayloadIntegrity {\n version: 1;\n keyId: string;\n signature: string;\n}\n\nexport interface DurableJobPayloadSigner {\n readonly keyId: string;\n sign(payload: unknown): DurableJobPayloadIntegrity;\n verify(payload: unknown, integrity: DurableJobPayloadIntegrity): boolean;\n}\n\n/** Create a deterministic HMAC signer for JSON job payloads. The key is never persisted. */\nexport function createHmacDurableJobPayloadSigner(options: {\n keyId: string;\n key: string | Uint8Array;\n}): DurableJobPayloadSigner {\n if (!options.keyId || options.keyId.length > 256) {\n throw new Error(\n 'Durable job integrity keyId must contain 1-256 characters',\n );\n }\n const keyLength =\n typeof options.key === 'string'\n ? Buffer.byteLength(options.key)\n : options.key.byteLength;\n if (keyLength < 32) {\n throw new Error('Durable job integrity key must contain at least 32 bytes');\n }\n const signature = (payload: unknown) =>\n createHmac('sha256', options.key)\n .update(canonicalJson(payload))\n .digest('base64url');\n return Object.freeze({\n keyId: options.keyId,\n sign(payload: unknown): DurableJobPayloadIntegrity {\n return {\n version: 1,\n keyId: options.keyId,\n signature: signature(payload),\n };\n },\n verify(payload: unknown, integrity: DurableJobPayloadIntegrity): boolean {\n if (\n integrity?.version !== 1 ||\n integrity.keyId !== options.keyId ||\n typeof integrity.signature !== 'string'\n ) {\n return false;\n }\n const expected = Buffer.from(signature(payload));\n const actual = Buffer.from(integrity.signature);\n return (\n actual.length === expected.length && timingSafeEqual(actual, expected)\n );\n },\n });\n}\n\nfunction canonicalJson(value: unknown): string {\n // Jobs persist `args` as JSON. Normalize through that exact representation\n // before sorting keys so a value with JSON serialization (notably Date) is\n // signed identically before enqueue and after the worker reloads the row.\n let persisted: string | undefined;\n try {\n persisted = JSON.stringify(value);\n } catch {\n throw new Error('Durable job integrity payload must be acyclic JSON');\n }\n if (persisted === undefined) {\n throw new Error('Durable job integrity payload must be JSON-serializable');\n }\n\n const seen = new Set<object>();\n const canonicalize = (item: unknown, inArray = false): unknown => {\n if (\n item === null ||\n typeof item === 'string' ||\n typeof item === 'boolean'\n ) {\n return item;\n }\n if (typeof item === 'number') return Number.isFinite(item) ? item : null;\n if (\n item === undefined ||\n typeof item === 'function' ||\n typeof item === 'symbol'\n ) {\n return inArray ? null : undefined;\n }\n if (typeof item !== 'object' || seen.has(item)) {\n throw new Error('Durable job integrity payload must be acyclic JSON');\n }\n seen.add(item);\n if (Array.isArray(item)) {\n const result = item.map((entry) => canonicalize(entry, true));\n seen.delete(item);\n return result;\n }\n // JSON may contain an own `__proto__` property. A normal object would invoke\n // Object.prototype's legacy prototype setter here and omit that property\n // from the signed representation.\n const result: Record<string, unknown> = Object.create(null);\n for (const key of Object.keys(item as Record<string, unknown>).sort()) {\n const entry = canonicalize((item as Record<string, unknown>)[key]);\n if (entry !== undefined) result[key] = entry;\n }\n seen.delete(item);\n return result;\n };\n return JSON.stringify(canonicalize(JSON.parse(persisted)));\n}\n","// Self-register this package's manifest for consumers importing this module\n// directly. See __smrt-register__.ts (issue #1132).\nimport './__smrt-register__.js';\n\nimport { randomUUID } from 'node:crypto';\nimport {\n detectEngine,\n field,\n SmrtCollection,\n SmrtObject,\n smrt,\n} from '@happyvertical/smrt-core';\nimport {\n requireTenant,\n TenantScoped,\n tenantId,\n withTenant,\n} from '@happyvertical/smrt-tenancy';\nimport type { DatabaseInterface } from '@happyvertical/sql';\nimport { redactErrorForPersistence } from './error-redaction.js';\n\nconst MAX_OBSERVATION_VERSION = 2_147_483_647;\nconst MAX_FORGE_DURATION_MS = 2_147_483_647;\nconst MAX_DATE_TIMESTAMP_MS = 8_640_000_000_000_000;\n\ntype DatabaseWithConfig = DatabaseInterface & {\n config?: {\n type?: string;\n url?: string;\n };\n type?: string;\n};\n\nexport type ForgeDeliveryStatus =\n | 'pending'\n | 'leased'\n | 'retry'\n | 'completed'\n | 'dead_letter';\n\n/**\n * A provider-neutral observation emitted by a forge delivery adapter.\n *\n * `version` is a monotonically increasing provider/domain revision for one\n * `(projection, subjectKey)` pair. Projectors never infer issue semantics from\n * pull requests; applications choose both the projection and subject identity.\n */\nexport interface ForgeObservation<T = unknown> {\n projection: string;\n subjectKey: string;\n version: number;\n value: T;\n}\n\nexport interface ForgeProjectionContext {\n /** Transaction-scoped database. Projection writes must use this handle. */\n db: DatabaseInterface;\n tenantId: string;\n deliveryId: string;\n}\n\nexport interface ForgeProjector<T = unknown> {\n /**\n * Normalize a provider delivery into a tracker-independent observation.\n * Return null when the delivery is intentionally ignored.\n */\n observe(delivery: ForgeDelivery): Promise<ForgeObservation<T> | null>;\n /**\n * Apply the observation. The callback and checkpoint/delivery updates share\n * one database transaction.\n */\n project(\n observation: ForgeObservation<T>,\n context: ForgeProjectionContext,\n ): Promise<void>;\n}\n\nexport type ForgeProjectionAuditEvent =\n | {\n type: 'delivery.accepted' | 'delivery.duplicate';\n tenantId: string;\n deliveryId: string;\n provider: string;\n }\n | {\n type:\n | 'delivery.leased'\n | 'delivery.completed'\n | 'delivery.retry_scheduled'\n | 'delivery.dead_lettered'\n | 'delivery.replayed'\n | 'observation.stale';\n tenantId: string;\n deliveryId: string;\n attempt: number;\n };\n\nexport type ForgeProjectionAuditHook = (\n event: ForgeProjectionAuditEvent,\n) => void | Promise<void>;\n\n@smrt({\n tableName: '_smrt_forge_deliveries',\n conflictColumns: ['tenant_id', 'provider', 'delivery_id'],\n api: false,\n cli: false,\n mcp: false,\n // `claimReady()` scans two OR-branches every poll (#2364, epic #2382\n // finding A3): `status IN ('pending','retry') AND next_attempt_at <= ?`\n // (the common ready-to-run case) and `status = 'leased' AND\n // lease_expires_at < ?` (reclaiming an expired lease — also the predicate\n // of the lease-expiry-to-dead_letter sweep above it in the same method).\n // Neither branch is a prefix of the other, so both composites are\n // declared; PostgreSQL can combine them with a BitmapOr when planning the\n // OR. Roll this out with `smrt db:migrate --postgres-safe` (#2362), same\n // as `_smrt_jobs` above — deliveries are claimed continuously too.\n indexes: [\n {\n name: '_smrt_forge_deliveries_status_next_attempt_at_idx',\n columns: ['status', 'nextAttemptAt'],\n },\n {\n name: '_smrt_forge_deliveries_status_lease_expires_at_idx',\n columns: ['status', 'leaseExpiresAt'],\n },\n ],\n})\n@TenantScoped({ mode: 'required' })\nexport class ForgeDelivery extends SmrtObject { static __smrtPackage__ = \"@happyvertical/smrt-jobs\";\n @tenantId()\n tenantId: string = '';\n\n @field({ type: 'text', required: true })\n provider: string = '';\n\n @field({ type: 'text', required: true })\n deliveryId: string = '';\n\n @field({ type: 'text', nullable: true })\n installationKey: string | null = null;\n\n @field({ type: 'text', nullable: true })\n repositoryKey: string | null = null;\n\n @field({ type: 'text', required: true })\n eventName: string = '';\n\n @field({ type: 'json' })\n payload: Record<string, unknown> = {};\n\n @field({ type: 'text', required: true, default: 'pending' })\n status: ForgeDeliveryStatus = 'pending';\n\n @field({ type: 'integer', required: true, default: 0 })\n attempts: number = 0;\n\n @field({ type: 'integer', required: true, default: 5 })\n maxAttempts: number = 5;\n\n @field({ type: 'datetime', required: true })\n receivedAt: Date = new Date();\n\n @field({ type: 'datetime', required: true })\n nextAttemptAt: Date = new Date();\n\n @field({ type: 'text', nullable: true })\n leaseOwner: string | null = null;\n\n @field({ type: 'text', nullable: true })\n leaseToken: string | null = null;\n\n @field({ type: 'datetime', nullable: true })\n leaseExpiresAt: Date | null = null;\n\n @field({ type: 'text', nullable: true })\n lastError: string | null = null;\n\n @field({ type: 'datetime', nullable: true })\n completedAt: Date | null = null;\n\n @field({ type: 'integer', required: true, default: 0 })\n replayCount: number = 0;\n}\n\n@smrt({\n tableName: '_smrt_forge_projection_checkpoints',\n conflictColumns: ['tenant_id', 'projection', 'subject_key'],\n api: false,\n cli: false,\n mcp: false,\n})\n@TenantScoped({ mode: 'required' })\nexport class ForgeProjectionCheckpoint extends SmrtObject { static __smrtPackage__ = \"@happyvertical/smrt-jobs\";\n @tenantId()\n tenantId: string = '';\n\n @field({ type: 'text', required: true })\n projection: string = '';\n\n @field({ type: 'text', required: true })\n subjectKey: string = '';\n\n // The current portable field contract persists this as a signed 32-bit\n // integer. `assertObservation()` enforces the matching public range.\n @field({ type: 'integer', required: true })\n observationVersion: number = 0;\n\n @field({ type: 'text', required: true })\n deliveryId: string = '';\n\n @field({ type: 'datetime', required: true })\n observedAt: Date = new Date();\n}\n\nexport interface AcceptForgeDeliveryInput {\n provider: string;\n deliveryId: string;\n installationKey?: string | null;\n repositoryKey?: string | null;\n eventName: string;\n payload: Record<string, unknown>;\n maxAttempts?: number;\n receivedAt?: Date;\n}\n\nexport interface AcceptedForgeDelivery {\n delivery: ForgeDelivery;\n accepted: boolean;\n}\n\nexport interface ClaimForgeDeliveryOptions {\n workerId: string;\n leaseMs: number;\n now?: Date;\n /**\n * Claim only deliveries from these providers. Runtimes that share the inbox\n * with other projections must set it so each claims only its own\n * deliveries; omitted, every provider is claimable.\n */\n providers?: readonly string[];\n}\n\n/**\n * Durable provider delivery inbox.\n *\n * All tenant-facing operations require ambient tenant context. `claimReady`\n * is the sole cross-tenant worker scan and returns the captured tenant so the\n * runtime can restore it before normalization or projection.\n */\n@smrt({\n api: false,\n cli: false,\n mcp: false,\n})\nexport class ForgeDeliveryCollection extends SmrtCollection<ForgeDelivery> { static __smrtPackage__ = \"@happyvertical/smrt-jobs\";\n static readonly _itemClass = ForgeDelivery;\n\n async accept(\n input: AcceptForgeDeliveryInput,\n audit?: ForgeProjectionAuditHook,\n ): Promise<AcceptedForgeDelivery> {\n const tenant = requireTenant().tenantId;\n assertNonEmpty('provider', input.provider);\n assertNonEmpty('deliveryId', input.deliveryId);\n assertNonEmpty('eventName', input.eventName);\n\n const now = input.receivedAt ?? new Date();\n const id = randomUUID();\n const inserted = await this.db.query(\n `INSERT INTO _smrt_forge_deliveries (\n id, slug, context, tenant_id, provider, delivery_id, installation_key,\n repository_key, event_name, payload, status, attempts, max_attempts,\n received_at, next_attempt_at, replay_count, created_at, updated_at\n ) VALUES (?, ?, '', ?, ?, ?, ?, ?, ?, ?, 'pending', 0, ?, ?, ?, 0, ?, ?)\n ON CONFLICT (tenant_id, provider, delivery_id) DO NOTHING\n RETURNING id`,\n id,\n `${input.provider}-${input.deliveryId}`.slice(0, 255),\n tenant,\n input.provider,\n input.deliveryId,\n input.installationKey ?? null,\n input.repositoryKey ?? null,\n input.eventName,\n JSON.stringify(input.payload),\n clampMaxAttempts(input.maxAttempts ?? 5),\n now.toISOString(),\n now.toISOString(),\n now.toISOString(),\n now.toISOString(),\n );\n const accepted = inserted.rows.length === 1;\n // Read back through the tenant-scoped collection path, not raw SQL: the\n // tenancy interceptor applies the ambient tenant filter itself, so this\n // works under `rawQueryPolicy: 'throw'` without any bypass (#3100).\n const [delivery] = await this.list({\n where: {\n tenantId: tenant,\n provider: input.provider,\n deliveryId: input.deliveryId,\n },\n limit: 1,\n });\n if (!delivery) throw new Error('Forge delivery insert could not be read');\n await audit?.({\n type: accepted ? 'delivery.accepted' : 'delivery.duplicate',\n tenantId: tenant,\n deliveryId: delivery.deliveryId,\n provider: delivery.provider,\n });\n return { delivery, accepted };\n }\n\n async claimReady(\n options: ClaimForgeDeliveryOptions,\n audit?: ForgeProjectionAuditHook,\n ): Promise<ForgeDelivery | null> {\n assertFinitePositive('leaseMs', options.leaseMs);\n const now = options.now ?? new Date();\n const nowIso = now.toISOString();\n const leaseExpiresAt = tryAddDuration(now, options.leaseMs);\n if (!leaseExpiresAt) {\n throw new Error('leaseMs extends past the supported Date range');\n }\n const token = randomUUID();\n const isPostgres = getDatabaseEngine(this.db) === 'postgres';\n const lockClause = isPostgres ? ' FOR UPDATE SKIP LOCKED' : '';\n const providers = options.providers;\n if (providers !== undefined) {\n if (providers.length === 0) {\n throw new Error('providers must name at least one provider');\n }\n for (const provider of providers) assertNonEmpty('providers[]', provider);\n }\n const providerClause = providers\n ? ` AND provider IN (${providers.map(() => '?').join(', ')})`\n : '';\n const providerParams = providers ? [...providers] : [];\n\n // An expired final attempt cannot be safely re-run. Move it to the\n // operator-recoverable terminal state before selecting another candidate.\n await this.query(\n `UPDATE _smrt_forge_deliveries\n SET status = 'dead_letter',\n lease_owner = NULL,\n lease_token = NULL,\n lease_expires_at = NULL,\n last_error = 'worker lease expired',\n updated_at = ?\n WHERE status = 'leased'\n AND lease_expires_at < ?\n AND attempts >= max_attempts${providerClause}`,\n [nowIso, nowIso, ...providerParams],\n { allowRawOnTenantScoped: true },\n );\n\n const candidateSelect = `\n SELECT id AS claim_id\n FROM _smrt_forge_deliveries\n WHERE attempts < max_attempts${providerClause}\n AND (\n (status IN ('pending', 'retry') AND next_attempt_at <= ?)\n OR (status = 'leased' AND lease_expires_at < ?)\n )\n ORDER BY next_attempt_at ASC, received_at ASC, created_at ASC, id ASC\n LIMIT 1${lockClause}`;\n const candidateParams = [...providerParams, nowIso, nowIso];\n const setClause = `\n SET status = 'leased',\n attempts = attempts + 1,\n lease_owner = ?,\n lease_token = ?,\n lease_expires_at = ?,\n updated_at = ?`;\n const setParams = [options.workerId, token, leaseExpiresAt, nowIso];\n const stillClaimable = `(\n (status IN ('pending', 'retry') AND next_attempt_at <= ?)\n OR (status = 'leased' AND lease_expires_at < ?)\n )`;\n // PostgreSQL selects the candidate once in a MATERIALIZED CTE: an\n // `IN (SELECT … LIMIT 1 FOR UPDATE SKIP LOCKED)` subquery can be rescanned\n // per outer row by a nested-loop semi join, leasing several deliveries\n // under one token while only the first is returned (#3105, #3145).\n const claimed = isPostgres\n ? await this.query(\n `WITH claim_candidates AS MATERIALIZED (${candidateSelect})\n UPDATE _smrt_forge_deliveries${setClause}\n FROM claim_candidates\n WHERE _smrt_forge_deliveries.id = claim_candidates.claim_id\n AND ${stillClaimable}\n RETURNING _smrt_forge_deliveries.*`,\n [...candidateParams, ...setParams, nowIso, nowIso],\n { allowRawOnTenantScoped: true },\n )\n : await this.query(\n `UPDATE _smrt_forge_deliveries${setClause}\n WHERE id IN (${candidateSelect})\n AND ${stillClaimable}\n RETURNING *`,\n [...setParams, ...candidateParams, nowIso, nowIso],\n { allowRawOnTenantScoped: true },\n );\n const delivery = claimed[0] ?? null;\n if (delivery) {\n await withTenant({ tenantId: delivery.tenantId }, async () => {\n try {\n await audit?.({\n type: 'delivery.leased',\n tenantId: delivery.tenantId,\n deliveryId: delivery.deliveryId,\n attempt: delivery.attempts,\n });\n } catch {\n // The durable lease already committed. Observability failures must\n // not strand it or consume an attempt before its projector runs.\n }\n });\n }\n return delivery;\n }\n\n async replay(id: string, audit?: ForgeProjectionAuditHook): Promise<boolean> {\n const tenant = requireTenant().tenantId;\n const now = new Date().toISOString();\n const result = await this.db.query(\n `UPDATE _smrt_forge_deliveries\n SET status = 'pending',\n attempts = 0,\n next_attempt_at = ?,\n lease_owner = NULL,\n lease_token = NULL,\n lease_expires_at = NULL,\n last_error = NULL,\n completed_at = NULL,\n replay_count = replay_count + 1,\n updated_at = ?\n WHERE id = ?\n AND tenant_id = ?\n AND status = 'dead_letter'\n RETURNING delivery_id, replay_count`,\n now,\n now,\n id,\n tenant,\n );\n const replayed = result.rows.length === 1;\n if (replayed) {\n const row = result.rows[0] as {\n delivery_id: string;\n replay_count: number;\n };\n await audit?.({\n type: 'delivery.replayed',\n tenantId: tenant,\n deliveryId: row.delivery_id,\n attempt: Number(row.replay_count),\n });\n }\n return replayed;\n }\n}\n\nexport interface ForgeProjectionRuntimeOptions {\n db: DatabaseInterface;\n workerId: string;\n /** Claim only these providers' deliveries; see {@link ClaimForgeDeliveryOptions}. */\n providers?: readonly string[];\n leaseMs?: number;\n retryBaseMs?: number;\n retryMaxMs?: number;\n audit?: ForgeProjectionAuditHook;\n}\n\n/**\n * Claims and projects one delivery at a time.\n *\n * The ownership assertion, application projection, monotonic checkpoint and\n * inbox completion are one transaction. The initial no-op UPDATE takes a row\n * write lock, preventing an expired lease from being reclaimed while a valid\n * projection transaction is still in progress.\n */\nexport class ForgeProjectionRuntime {\n readonly db: DatabaseInterface;\n readonly workerId: string;\n readonly providers?: readonly string[];\n readonly leaseMs: number;\n readonly retryBaseMs: number;\n readonly retryMaxMs: number;\n readonly audit?: ForgeProjectionAuditHook;\n\n constructor(options: ForgeProjectionRuntimeOptions) {\n this.db = options.db;\n this.workerId = options.workerId;\n this.providers = options.providers;\n this.leaseMs = options.leaseMs ?? 30_000;\n this.retryBaseMs = options.retryBaseMs ?? 1_000;\n this.retryMaxMs = options.retryMaxMs ?? 300_000;\n assertFinitePositive('leaseMs', this.leaseMs);\n assertFiniteNonNegative('retryBaseMs', this.retryBaseMs);\n assertFiniteNonNegative('retryMaxMs', this.retryMaxMs);\n this.audit = options.audit;\n }\n\n async processNext(\n projector: ForgeProjector,\n options: { now?: Date } = {},\n ): Promise<ForgeDelivery | null> {\n const inbox = await ForgeDeliveryCollection.create({ db: this.db });\n const delivery = await inbox.claimReady(\n {\n workerId: this.workerId,\n leaseMs: this.leaseMs,\n now: options.now,\n providers: this.providers,\n },\n this.audit,\n );\n if (!delivery) return null;\n\n await withTenant({ tenantId: delivery.tenantId }, async () => {\n try {\n const observation = await projector.observe(delivery);\n await this.commitOwned(delivery, observation, projector, options.now);\n } catch (error) {\n await this.failOwned(delivery, error, options.now);\n }\n });\n return delivery;\n }\n\n private async commitOwned(\n delivery: ForgeDelivery,\n observation: ForgeObservation | null,\n projector: ForgeProjector,\n now = new Date(),\n ): Promise<void> {\n if (!this.db.transaction) {\n throw new Error(\n 'Forge projection requires a database adapter with transaction()',\n );\n }\n const nowIso = now.toISOString();\n let stale = false;\n await this.db.transaction(async (tx) => {\n const ownership = await tx.query(\n `UPDATE _smrt_forge_deliveries\n SET updated_at = updated_at\n WHERE id = ? AND tenant_id = ? AND status = 'leased'\n AND lease_token = ?\n AND lease_expires_at >= ?\n RETURNING id`,\n delivery.id,\n delivery.tenantId,\n delivery.leaseToken,\n nowIso,\n );\n if (ownership.rows.length !== 1) {\n throw new Error('Forge delivery lease ownership was lost');\n }\n\n if (observation) {\n assertObservation(observation);\n // Reserve the subject version before invoking application code. This\n // write serializes concurrent first-observation and update races; a\n // stale contender gets no RETURNING row and never applies side effects.\n const reserved = await tx.query(\n `INSERT INTO _smrt_forge_projection_checkpoints (\n id, slug, context, tenant_id, projection, subject_key,\n observation_version, delivery_id, observed_at, created_at,\n updated_at\n ) VALUES (?, ?, '', ?, ?, ?, ?, ?, ?, ?, ?)\n ON CONFLICT (tenant_id, projection, subject_key) DO UPDATE SET\n observation_version = excluded.observation_version,\n delivery_id = excluded.delivery_id,\n observed_at = excluded.observed_at,\n updated_at = excluded.updated_at\n WHERE _smrt_forge_projection_checkpoints.observation_version\n < excluded.observation_version\n RETURNING id`,\n randomUUID(),\n `${observation.projection}-${observation.subjectKey}`.slice(0, 255),\n delivery.tenantId,\n observation.projection,\n observation.subjectKey,\n observation.version,\n delivery.deliveryId,\n nowIso,\n nowIso,\n nowIso,\n );\n stale = reserved.rows.length === 0;\n if (!stale) {\n await projector.project(observation, {\n db: tx,\n tenantId: delivery.tenantId,\n deliveryId: delivery.deliveryId,\n });\n }\n }\n\n const completed = await tx.query(\n `UPDATE _smrt_forge_deliveries\n SET status = 'completed',\n completed_at = ?,\n lease_owner = NULL,\n lease_token = NULL,\n lease_expires_at = NULL,\n last_error = NULL,\n updated_at = ?\n WHERE id = ? AND tenant_id = ? AND status = 'leased'\n AND lease_token = ?\n AND lease_expires_at >= ?\n RETURNING id`,\n nowIso,\n nowIso,\n delivery.id,\n delivery.tenantId,\n delivery.leaseToken,\n nowIso,\n );\n if (completed.rows.length !== 1) {\n throw new Error('Forge delivery completion lost lease ownership');\n }\n });\n await this.audit?.({\n type: stale ? 'observation.stale' : 'delivery.completed',\n tenantId: delivery.tenantId,\n deliveryId: delivery.deliveryId,\n attempt: delivery.attempts,\n });\n }\n\n private async failOwned(\n delivery: ForgeDelivery,\n error: unknown,\n now = new Date(),\n ): Promise<void> {\n const terminal = delivery.attempts >= delivery.maxAttempts;\n const delay = Math.min(\n this.retryMaxMs,\n this.retryBaseMs * 2 ** Math.max(0, delivery.attempts - 1),\n );\n const retryAt = terminal ? now.toISOString() : tryAddDuration(now, delay);\n const scheduleOverflow = retryAt === null;\n const lastError = scheduleOverflow\n ? `${redactErrorForPersistence(error)}; retry schedule exceeds the supported Date range`\n : redactErrorForPersistence(error);\n const result = await this.db.query(\n `UPDATE _smrt_forge_deliveries\n SET status = ?,\n next_attempt_at = ?,\n lease_owner = NULL,\n lease_token = NULL,\n lease_expires_at = NULL,\n last_error = ?,\n updated_at = ?\n WHERE id = ? AND tenant_id = ? AND status = 'leased'\n AND lease_token = ?\n AND lease_expires_at >= ?\n RETURNING id`,\n terminal || scheduleOverflow ? 'dead_letter' : 'retry',\n retryAt ?? now.toISOString(),\n lastError,\n now.toISOString(),\n delivery.id,\n delivery.tenantId,\n delivery.leaseToken,\n now.toISOString(),\n );\n if (result.rows.length === 1) {\n await this.audit?.({\n type:\n terminal || scheduleOverflow\n ? 'delivery.dead_lettered'\n : 'delivery.retry_scheduled',\n tenantId: delivery.tenantId,\n deliveryId: delivery.deliveryId,\n attempt: delivery.attempts,\n });\n }\n }\n}\n\nfunction assertNonEmpty(name: string, value: string): void {\n if (value.trim().length === 0) throw new Error(`${name} must not be empty`);\n}\n\nfunction assertFinitePositive(name: string, value: number): void {\n if (!Number.isFinite(value) || value <= 0) {\n throw new Error(`${name} must be a finite positive number`);\n }\n}\n\nfunction assertFiniteNonNegative(name: string, value: number): void {\n if (!Number.isFinite(value) || value < 0) {\n throw new Error(`${name} must be a finite non-negative number`);\n }\n if (value > MAX_FORGE_DURATION_MS) {\n throw new Error(`${name} must not exceed ${MAX_FORGE_DURATION_MS}`);\n }\n}\n\nfunction tryAddDuration(now: Date, durationMs: number): string | null {\n const timestamp = now.getTime() + durationMs;\n if (\n !Number.isFinite(timestamp) ||\n Math.abs(timestamp) > MAX_DATE_TIMESTAMP_MS\n ) {\n return null;\n }\n return new Date(timestamp).toISOString();\n}\n\nfunction assertObservation(observation: ForgeObservation): void {\n assertNonEmpty('observation.projection', observation.projection);\n assertNonEmpty('observation.subjectKey', observation.subjectKey);\n if (\n !Number.isSafeInteger(observation.version) ||\n observation.version < 0 ||\n observation.version > MAX_OBSERVATION_VERSION\n ) {\n throw new Error(\n `observation.version must be an integer from 0 to ${MAX_OBSERVATION_VERSION}`,\n );\n }\n}\n\nfunction getDatabaseEngine(\n db: DatabaseInterface,\n): ReturnType<typeof detectEngine> {\n const dbWithConfig = db as DatabaseWithConfig;\n return detectEngine(\n db.url || dbWithConfig.config?.url || '',\n dbWithConfig.type || dbWithConfig.config?.type,\n );\n}\n\nfunction clampMaxAttempts(value: number): number {\n if (!Number.isSafeInteger(value) || value <= 0) {\n throw new Error('maxAttempts must be a positive safe integer');\n }\n return Math.min(value, 100);\n}\n","import type { JobStatus, SmrtJob, SmrtJobCollection } from './smrt-job.js';\n\n/**\n * Options for waiting on a job\n */\nexport interface WaitOptions {\n /** Maximum time to wait in milliseconds */\n timeout?: number;\n /** Polling interval in milliseconds */\n pollInterval?: number;\n}\n\n/**\n * Result from a completed job\n */\nexport interface JobResult<T = unknown> {\n /** Whether the job completed successfully */\n success: boolean;\n /** The result data (if successful) */\n result?: T;\n /** Error message (if failed) */\n error?: string;\n /** Pointer to where the full result is stored */\n resultPointer?: string | null;\n}\n\n/**\n * Handle for tracking and managing a background job\n *\n * This provides a convenient interface for:\n * - Checking job status\n * - Waiting for completion\n * - Canceling the job\n * - Retrying failed jobs\n */\nexport class JobHandle<T = unknown> {\n private readonly collection: SmrtJobCollection;\n\n constructor(\n public readonly id: string,\n collection: SmrtJobCollection,\n ) {\n this.collection = collection;\n }\n\n /**\n * Get the current job status\n */\n async status(): Promise<JobStatus> {\n const job = await this.getJob();\n return job.status;\n }\n\n /**\n * Get the full job object\n */\n async getJob(): Promise<SmrtJob> {\n const job = await this.collection.get({ id: this.id });\n if (!job) {\n throw new Error(`Job not found: ${this.id}`);\n }\n return job;\n }\n\n /**\n * Wait for the job to complete\n *\n * @param options - Wait configuration\n * @returns The job result\n * @throws Error if the job fails or times out\n */\n async wait(options: WaitOptions = {}): Promise<JobResult<T>> {\n const { timeout = 60000, pollInterval = 100 } = options;\n const startTime = Date.now();\n\n while (true) {\n const job = await this.getJob();\n\n if (job.status === 'completed') {\n return {\n success: true,\n resultPointer: job.resultPointer,\n };\n }\n\n if (job.status === 'failed') {\n return {\n success: false,\n error: job.lastError ?? 'Job failed',\n };\n }\n\n if (job.status === 'cancelled') {\n return {\n success: false,\n error: 'Job was cancelled',\n };\n }\n\n // Check timeout\n if (Date.now() - startTime >= timeout) {\n throw new Error(`Timeout waiting for job ${this.id}`);\n }\n\n // Wait before next poll\n await new Promise((resolve) => setTimeout(resolve, pollInterval));\n }\n }\n\n /**\n * Cancel the job\n */\n async cancel(): Promise<void> {\n const job = await this.getJob();\n await job.cancel();\n }\n\n /**\n * Retry a failed job\n */\n async retry(): Promise<void> {\n const job = await this.getJob();\n await job.retry();\n }\n\n /**\n * Check if the job is still running\n */\n async isRunning(): Promise<boolean> {\n const status = await this.status();\n return status === 'pending' || status === 'running';\n }\n\n /**\n * Check if the job has completed (successfully or not)\n */\n async isDone(): Promise<boolean> {\n const status = await this.status();\n return (\n status === 'completed' || status === 'failed' || status === 'cancelled'\n );\n }\n}\n\nexport default JobHandle;\n","import type { RetryStrategy, RetryStrategyConfig } from '@happyvertical/jobs';\nimport { clampRetries, DEFAULT_TENANT_JOB_CAP } from './background-policy.js';\nimport { JobHandle } from './job-handle.js';\nimport type { SmrtJobCollection, TimeoutBehavior } from './smrt-job.js';\n\n/**\n * Priority levels for jobs\n */\nexport type Priority = 'critical' | 'high' | 'normal' | 'low' | number;\n\n/**\n * Convert priority to numeric value\n */\nexport function priorityToNumber(priority: Priority): number {\n if (typeof priority === 'number') return priority;\n switch (priority) {\n case 'critical':\n return 100;\n case 'high':\n return 75;\n case 'normal':\n return 50;\n case 'low':\n return 25;\n default:\n return 50;\n }\n}\n\n/**\n * Parse delay string to milliseconds\n */\nexport function parseDelay(delay: string | number): number {\n if (typeof delay === 'number') {\n // Guard against NaN/Infinity: a non-finite delay flows into\n // `new Date(Date.now() + delay)`, persisting an `Invalid Date` `runAt`\n // that the claim query can never match (S3 in the #1401 review).\n if (!Number.isFinite(delay)) {\n throw new Error(`Invalid delay value: ${delay}`);\n }\n return delay;\n }\n\n const match = delay.match(/^(\\d+)(ms|s|m|h|d)?$/);\n if (!match) {\n throw new Error(`Invalid delay format: ${delay}`);\n }\n\n const value = parseInt(match[1], 10);\n const unit = match[2] || 'ms';\n\n switch (unit) {\n case 'ms':\n return value;\n case 's':\n return value * 1000;\n case 'm':\n return value * 60 * 1000;\n case 'h':\n return value * 60 * 60 * 1000;\n case 'd':\n return value * 24 * 60 * 60 * 1000;\n default:\n return value;\n }\n}\n\n/**\n * Fluent builder for creating background jobs\n *\n * Example:\n * ```typescript\n * const handle = await doc.background('generateSummary', { format: 'md' })\n * .delay('5m')\n * .retries(5)\n * .priority('high')\n * .queue('summaries')\n * .timeout(300000)\n * .enqueue();\n * ```\n */\nexport class JobBuilder<T = unknown> {\n private _queue: string = 'default';\n private _delay: number = 0;\n private _retries: number = 3;\n private _priority: number = 50;\n private _timeout: number = 300000;\n private _timeoutBehavior: TimeoutBehavior = 'fail';\n private _retryStrategy?: RetryStrategy;\n private _tenantJobCap: number = DEFAULT_TENANT_JOB_CAP;\n\n constructor(\n private readonly objectType: string,\n private readonly objectId: string | null,\n private readonly method: string,\n private readonly args: Record<string, unknown>,\n private readonly collection: SmrtJobCollection,\n ) {}\n\n /**\n * Set the queue name\n */\n queue(name: string): this {\n this._queue = name;\n return this;\n }\n\n /**\n * Set a delay before the job runs\n * @param delay - Delay as milliseconds or string like '5m', '1h', '30s'\n */\n delay(delay: string | number): this {\n this._delay = parseDelay(delay);\n return this;\n }\n\n /**\n * Set when the job should run\n */\n runAt(date: Date): this {\n this._delay = date.getTime() - Date.now();\n return this;\n }\n\n /**\n * Set the maximum number of retry attempts.\n *\n * Clamped to {@link MAX_JOB_RETRIES} so a misconfigured caller cannot pin a\n * worker on a poison job indefinitely (S5 audit #1402).\n */\n retries(count: number): this {\n this._retries = clampRetries(count);\n return this;\n }\n\n /**\n * Set the retry strategy\n */\n retryStrategy(strategy: RetryStrategy): this {\n this._retryStrategy = strategy;\n return this;\n }\n\n /**\n * Set the job priority\n */\n priority(level: Priority): this {\n this._priority = priorityToNumber(level);\n return this;\n }\n\n /**\n * Set the job timeout in milliseconds\n */\n timeout(ms: number): this {\n this._timeout = ms;\n return this;\n }\n\n /**\n * Set what happens when the job times out\n */\n timeoutBehavior(behavior: TimeoutBehavior): this {\n this._timeoutBehavior = behavior;\n return this;\n }\n\n /**\n * Override the per-tenant in-flight job cap for this enqueue.\n *\n * Defaults to {@link DEFAULT_TENANT_JOB_CAP}. Pass `0` (or a negative value)\n * to disable the cap for trusted internal callers (S5 audit #1402).\n */\n tenantJobCap(max: number): this {\n this._tenantJobCap = max;\n return this;\n }\n\n /**\n * Enqueue the job and return a handle\n */\n async enqueue(): Promise<JobHandle<T>> {\n const runAt = new Date(Date.now() + this._delay);\n\n const strategy =\n this._retryStrategy ??\n (await import('@happyvertical/jobs')).exponential();\n\n const retryConfig: RetryStrategyConfig =\n 'toConfig' in strategy\n ? strategy.toConfig()\n : (strategy as RetryStrategyConfig);\n\n // Route through the collection's single creation path so the per-tenant\n // in-flight cap and the retry ceiling are enforced in one place, shared with\n // the ScheduleRunner (S5 audit #1402). The cap applies to the ambient tenant\n // (resolved inside enqueueJob); global (no-context) jobs are exempt.\n const job = await this.collection.enqueueJob(\n {\n queue: this._queue,\n objectType: this.objectType,\n objectId: this.objectId,\n method: this.method,\n args: this.args,\n runAt,\n priority: this._priority,\n maxAttempts: this._retries,\n timeout: this._timeout,\n timeoutBehavior: this._timeoutBehavior,\n retryStrategy: retryConfig,\n },\n { tenantJobCap: this._tenantJobCap },\n );\n\n const jobId = job.id;\n if (!jobId) {\n throw new Error('Job was created but has no ID');\n }\n\n return new JobHandle<T>(jobId, this.collection);\n }\n}\n\nexport default JobBuilder;\n","import {\n ObjectRegistry,\n type SmrtObject,\n type SmrtObjectOptions,\n} from '@happyvertical/smrt-core';\nimport type { DatabaseInterface } from '@happyvertical/sql';\nimport {\n JobBuilder,\n type Priority,\n parseDelay,\n priorityToNumber,\n} from './job-builder.js';\nimport type { JobHandle } from './job-handle.js';\nimport { SmrtJobCollection } from './smrt-job.js';\n\n/**\n * Options for the simple .bg() method\n */\nexport interface BgOptions {\n /** Queue name */\n queue?: string;\n /** Priority level */\n priority?: 'critical' | 'high' | 'normal' | 'low' | number;\n /** Delay before running (ms or string like '5m') */\n delay?: string | number;\n /** Maximum retries */\n retries?: number;\n /** Timeout in milliseconds */\n timeout?: number;\n}\n\n/**\n * Type for the extended SmrtObject with background job methods\n */\nexport interface BackgroundCapable {\n /**\n * Simple background job submission\n *\n * @param method - Method name to invoke\n * @param args - Arguments to pass to the method\n * @param options - Job options\n * @returns JobHandle for tracking the job\n *\n * @example\n * const handle = await doc.bg('generateSummary', { format: 'md' });\n */\n bg<T = unknown>(\n method: string,\n args?: Record<string, unknown>,\n options?: BgOptions,\n ): Promise<JobHandle<T>>;\n\n /**\n * Fluent job builder for advanced options\n *\n * @param method - Method name to invoke\n * @param args - Arguments to pass to the method\n * @returns JobBuilder for fluent configuration\n *\n * @example\n * const handle = await doc.background('generateSummary', { format: 'md' })\n * .delay('5m')\n * .retries(5)\n * .priority('high')\n * .enqueue();\n */\n background<T = unknown>(\n method: string,\n args?: Record<string, unknown>,\n ): JobBuilder<T>;\n}\n\n// Cache for job collections per database\nconst collectionCache = new WeakMap<DatabaseInterface, SmrtJobCollection>();\n\n/**\n * Get or create a job collection for the given database\n */\nasync function getJobCollection(\n db: DatabaseInterface,\n): Promise<SmrtJobCollection> {\n let collection = collectionCache.get(db);\n if (!collection) {\n collection = await SmrtJobCollection.create({\n db: { type: 'sqlite', url: ':memory:' }, // Placeholder\n });\n // Override internal db reference\n (collection as unknown as { _db: DatabaseInterface })._db = db;\n collectionCache.set(db, collection);\n }\n return collection;\n}\n\nfunction getObjectTypeName(instance: SmrtObject): string {\n const metaType = (instance as { _meta_type?: unknown })._meta_type;\n if (typeof metaType === 'string' && metaType.length > 0) {\n return metaType;\n }\n\n const className = instance.constructor.name;\n return ObjectRegistry.getClass(className)?.qualifiedName || className;\n}\n\n// Type for a SmrtObject constructor. `never[]` (not `any[]`) satisfies\n// noExplicitAny while preserving assignability: constructor parameters are\n// checked contravariantly under strictFunctionTypes, and `never` (the bottom\n// type) is assignable to any concrete parameter type, so a typed-options\n// constructor like `new (options?: SmrtObjectOptions) => Doc` still satisfies\n// the constraint — `unknown[]` would NOT, since `unknown` is not assignable to\n// `SmrtObjectOptions`, breaking the documented `withBackgroundJobs(Document)`\n// API for consumers.\ntype SmrtObjectConstructor = new (...args: never[]) => SmrtObject;\ntype BackgroundCapableConstructor<T extends SmrtObjectConstructor> = {\n new (...args: ConstructorParameters<T>): InstanceType<T> & BackgroundCapable;\n} & T;\n\n// Compile-time regression guard (#1658, PR #1658): a typed-options SmrtObject\n// subclass constructor — the documented `withBackgroundJobs(Document)` pattern,\n// where a model's ctor is `(options?: SomeOptions)` — MUST satisfy the\n// constraint. A `unknown[]` rest param (instead of `never[]`) makes this\n// resolve to `false` and fails the build, since `unknown` is not assignable to\n// the typed options parameter. Keep this guard in production source so the\n// published constructor declaration stays checked during builds as well.\ntype AssertTrue<T extends true> = T;\ntype _TypedOptionsCtorStaysAssignable = AssertTrue<\n (new (\n options?: SmrtObjectOptions,\n ) => SmrtObject) extends SmrtObjectConstructor\n ? true\n : false\n>;\n\nfunction requireObjectDb(instance: SmrtObject): DatabaseInterface {\n const db = (instance as unknown as { _db?: DatabaseInterface })._db;\n if (!db) {\n throw new Error('Object not initialized. Call initialize() first.');\n }\n\n return db;\n}\n\nasync function bgImpl<R = unknown>(\n this: SmrtObject,\n method: string,\n args: Record<string, unknown> = {},\n options: BgOptions = {},\n): Promise<JobHandle<R>> {\n const db = requireObjectDb(this);\n const collection = await getJobCollection(db);\n const builder = new JobBuilder<R>(\n getObjectTypeName(this),\n this.id ?? null,\n method,\n args,\n collection,\n );\n\n if (options.queue) builder.queue(options.queue);\n if (options.priority) builder.priority(options.priority);\n if (options.delay) builder.delay(options.delay);\n if (options.retries !== undefined) builder.retries(options.retries);\n if (options.timeout) builder.timeout(options.timeout);\n\n return builder.enqueue();\n}\n\nfunction backgroundImpl<R = unknown>(\n this: SmrtObject,\n method: string,\n args: Record<string, unknown> = {},\n): JobBuilder<R> {\n const db = requireObjectDb(this);\n const objectType = getObjectTypeName(this);\n const objectId = this.id ?? null;\n\n // Create a proxy builder that defers collection access until enqueue().\n const lazyBuilder = {\n _queue: 'default',\n _delay: 0,\n _retries: 3,\n _priority: 50,\n _timeout: 300000,\n _timeoutBehavior: 'fail' as 'fail' | 'kill' | 'warn',\n _retryStrategy: null as unknown,\n // `undefined` => fall through to JobBuilder's DEFAULT_TENANT_JOB_CAP. A\n // caller can override (incl. `0` to disable) via tenantJobCap() below.\n _tenantJobCap: undefined as number | undefined,\n\n queue(name: string) {\n this._queue = name;\n return this;\n },\n delay(d: string | number) {\n this._delay = parseDelay(d);\n return this;\n },\n runAt(date: Date) {\n this._delay = date.getTime() - Date.now();\n return this;\n },\n retries(count: number) {\n this._retries = count;\n return this;\n },\n retryStrategy(strategy: unknown) {\n this._retryStrategy = strategy;\n return this;\n },\n priority(level: Priority) {\n this._priority = priorityToNumber(level);\n return this;\n },\n timeout(ms: number) {\n this._timeout = ms;\n return this;\n },\n timeoutBehavior(behavior: 'fail' | 'kill' | 'warn') {\n this._timeoutBehavior = behavior;\n return this;\n },\n tenantJobCap(max: number) {\n this._tenantJobCap = max;\n return this;\n },\n async enqueue(): Promise<JobHandle<R>> {\n const collection = await getJobCollection(db);\n const builder = new JobBuilder<R>(\n objectType,\n objectId,\n method,\n args,\n collection,\n );\n\n builder.queue(this._queue);\n builder.delay(this._delay);\n builder.retries(this._retries);\n builder.priority(this._priority);\n builder.timeout(this._timeout);\n builder.timeoutBehavior(this._timeoutBehavior);\n // Only forward an explicit override; leaving it unset preserves the\n // JobBuilder default (DEFAULT_TENANT_JOB_CAP).\n if (this._tenantJobCap !== undefined) {\n builder.tenantJobCap(this._tenantJobCap);\n }\n\n if (this._retryStrategy) {\n builder.retryStrategy(\n this._retryStrategy as Parameters<typeof builder.retryStrategy>[0],\n );\n }\n\n return builder.enqueue();\n },\n };\n\n return lazyBuilder as unknown as JobBuilder<R>;\n}\n\n/**\n * Extend a SmrtObject class with background job methods\n *\n * @param BaseClass - The SmrtObject class to extend\n * @returns Extended class with .bg() and .background() methods\n *\n * @example\n * const BackgroundDocument = withBackgroundJobs(Document);\n * const doc = new BackgroundDocument({ ... });\n * const handle = await doc.bg('generateSummary', { format: 'md' });\n */\nexport function withBackgroundJobs<T extends SmrtObjectConstructor>(\n BaseClass: T,\n): BackgroundCapableConstructor<T> {\n const prototype = BaseClass.prototype as SmrtObject &\n Partial<BackgroundCapable>;\n\n if (typeof prototype.bg !== 'function') {\n Object.defineProperty(prototype, 'bg', {\n value: bgImpl,\n writable: true,\n configurable: true,\n });\n }\n\n if (typeof prototype.background !== 'function') {\n Object.defineProperty(prototype, 'background', {\n value: backgroundImpl,\n writable: true,\n configurable: true,\n });\n }\n\n return BaseClass as BackgroundCapableConstructor<T>;\n}\n\nexport default withBackgroundJobs;\n","import type {\n DurableJobPayloadIntegrity,\n DurableJobPayloadSigner,\n} from './durable-payload-integrity.js';\n\n/** Durable, versioned requirement persisted in AgentSchedule.methodArgs. */\nexport interface ScheduleAdmissionPolicy {\n version: 1;\n requireIntegrity: true;\n queue: string;\n keyId: string;\n}\n\n/** Absent policy preserves legacy behavior; any malformed present policy fails closed. */\nexport function getScheduleAdmissionPolicy(\n args: unknown,\n): ScheduleAdmissionPolicy | null {\n if (typeof args === 'string') args = JSON.parse(args);\n if (!record(args))\n throw new TypeError('Schedule method_args must be a JSON object');\n if (!Object.hasOwn(args, '_scheduleAdmissionPolicy')) return null;\n const value = args._scheduleAdmissionPolicy;\n if (\n !record(value) ||\n Object.keys(value).sort().join(',') !==\n 'keyId,queue,requireIntegrity,version' ||\n value.version !== 1 ||\n value.requireIntegrity !== true ||\n typeof value.queue !== 'string' ||\n !value.queue.trim() ||\n typeof value.keyId !== 'string' ||\n !value.keyId.trim() ||\n value.keyId.length > 256\n ) {\n throw new TypeError('Unsupported or malformed schedule admission policy');\n }\n return {\n version: 1,\n requireIntegrity: true,\n queue: value.queue,\n keyId: value.keyId,\n };\n}\n\n/** Purpose-separated, immutable JSON identity of one scheduler admission. */\nexport interface ScheduleAdmissionPayload {\n purpose: 'smrt.schedule-admission';\n version: 1;\n keyId: string;\n jobId: string;\n tenantId: string | null;\n scheduleId: string;\n scheduledFor: string;\n queue: string;\n objectType: string;\n objectId: string | null;\n method: string;\n args: Record<string, unknown>;\n}\n\nfunction record(value: unknown): value is Record<string, unknown> {\n if (!value || typeof value !== 'object' || Array.isArray(value)) return false;\n const prototype = Object.getPrototypeOf(value);\n return prototype === Object.prototype || prototype === null;\n}\n\nfunction identity(value: unknown, name: string): string {\n if (typeof value !== 'string' || !value.trim()) {\n throw new TypeError(`Schedule admission requires ${name}`);\n }\n return value;\n}\n\n/**\n * Build the public signature payload from an authoritative persisted job row.\n *\n * This pure helper never signs or acquires a key. Only `_scheduleAdmission` is\n * omitted; every other persisted argument, including constructor/static consent\n * metadata, participates. Lifecycle fields may change during a legitimate retry.\n * Malformed identities or noncanonical UTC occurrence metadata throw.\n */\nexport function getScheduleAdmissionPayload(\n job: unknown,\n keyId: string,\n): ScheduleAdmissionPayload {\n if (!job || typeof job !== 'object') {\n throw new TypeError('Schedule admission requires a job');\n }\n const row = job as Record<string, unknown>;\n if (!record(row.args)) {\n throw new TypeError('Schedule admission requires JSON object arguments');\n }\n const scheduledFor = identity(row.args._scheduledFor, 'scheduledFor');\n const epoch = Date.parse(scheduledFor);\n if (\n !Number.isFinite(epoch) ||\n new Date(epoch).toISOString() !== scheduledFor\n ) {\n throw new TypeError(\n 'Schedule admission requires canonical UTC scheduledFor',\n );\n }\n const signatureKey = identity(keyId, 'keyId');\n if (signatureKey.length > 256) throw new TypeError('Invalid admission keyId');\n const policy = getScheduleAdmissionPolicy(row.args);\n if (policy && (policy.queue !== row.queue || policy.keyId !== signatureKey)) {\n throw new TypeError('Schedule admission does not match its durable policy');\n }\n const { _scheduleAdmission: _, ...argumentsWithoutSignature } = row.args;\n // Match the representation actually stored as JSON, preserving own __proto__\n // keys and Date serialization. Never retain a mutable reference to caller args.\n const args = JSON.parse(JSON.stringify(argumentsWithoutSignature)) as Record<\n string,\n unknown\n >;\n return {\n purpose: 'smrt.schedule-admission',\n version: 1,\n keyId: signatureKey,\n jobId: identity(row.id, 'jobId'),\n tenantId: row.tenantId === null ? null : identity(row.tenantId, 'tenantId'),\n scheduleId: identity(row.args._scheduleId, 'scheduleId'),\n scheduledFor,\n queue: identity(row.queue, 'queue'),\n objectType: identity(row.objectType, 'objectType'),\n objectId: row.objectId === null ? null : identity(row.objectId, 'objectId'),\n method: identity(row.method, 'method'),\n args,\n };\n}\n\n/**\n * Verify one exact admitted job, failing closed on missing/unknown metadata.\n *\n * `signer.verify` may be a trusted keyring retaining old verification keys while\n * `signer.keyId` selects a new minting key. Unknown or retired keys must deny.\n * A valid signature proves admission, never current user authority, deduplication\n * or exactly-once execution. No protection is claimed against code holding keys.\n */\nexport function verifyScheduleAdmission(\n job: unknown,\n signer: DurableJobPayloadSigner,\n): boolean {\n try {\n if (!job || typeof job !== 'object') return false;\n const args = (job as Record<string, unknown>).args;\n if (!record(args)) return false;\n const integrity = args._scheduleAdmission;\n if (\n !record(integrity) ||\n Object.keys(integrity).length !== 3 ||\n !['version', 'keyId', 'signature'].every((key) =>\n Object.hasOwn(integrity, key),\n ) ||\n integrity.version !== 1 ||\n typeof integrity.keyId !== 'string' ||\n !integrity.keyId.trim() ||\n integrity.keyId.length > 256 ||\n typeof integrity.signature !== 'string' ||\n !integrity.signature.trim()\n ) {\n return false;\n }\n return (\n signer.verify(\n getScheduleAdmissionPayload(job, integrity.keyId),\n integrity as unknown as DurableJobPayloadIntegrity,\n ) === true\n );\n } catch {\n return false;\n }\n}\n","import { EventEmitter } from 'node:events';\nimport { createLogger } from '@happyvertical/logger';\nimport { ObjectRegistry } from '@happyvertical/smrt-core';\nimport type { DatabaseInterface } from '@happyvertical/sql';\nimport { createId } from '@happyvertical/utils';\nimport type { DurableJobPayloadSigner } from './durable-payload-integrity.js';\nimport {\n redactErrorForPersistence,\n redactErrorMessage,\n} from './error-redaction.js';\nimport {\n getScheduleAdmissionPayload,\n getScheduleAdmissionPolicy,\n verifyScheduleAdmission,\n} from './schedule-admission.js';\nimport { countScheduleJobs, SmrtJobCollection } from './smrt-job.js';\nimport { DEFAULT_TASK_HEARTBEAT_INTERVAL_MS } from './stale-recovery.js';\n\n/** A blocked host must not consume or alter a protected schedule. */\nclass ScheduleAdmissionBlockedError extends Error {}\n\n/**\n * ScheduleRunner configuration\n */\n/**\n * Queue that {@link ScheduleRunner} enqueues triggered schedules to. A task\n * worker must poll it (alongside `default`) or scheduled jobs stay `pending`\n * (#3141).\n */\nexport const SCHEDULED_JOB_QUEUE = 'agents';\n\nexport interface ScheduleRunnerConfig {\n /** Runner ID (auto-generated if not provided) */\n id?: string;\n /** Polling interval in milliseconds (default: 60000 - 1 minute) */\n pollInterval?: number;\n /** Maximum schedules to process per poll */\n batchSize?: number;\n /** Trusted host signer for exact occurrence/job integrity; null preserves unsigned behavior. */\n occurrenceSigner?: DurableJobPayloadSigner | null;\n /** Exact registered agent types this host may admit; empty means none. */\n agentTypes?: readonly string[];\n /** Tenant identities this host may admit; null selects global schedules. */\n tenantIds?: readonly (string | null)[];\n /** Queue consumed by this host's task worker (default: agents). */\n queue?: string;\n /**\n * @deprecated No longer used. Slot reconciliation keys on worker liveness\n * (the `_smrt_workers` lease), not per-job heartbeat staleness (#1474).\n */\n staleJobThresholdMs?: number;\n /**\n * @deprecated No longer used. See {@link staleJobThresholdMs}.\n */\n taskHeartbeatInterval?: number;\n}\n\n/**\n * ScheduleRunner events\n */\nexport interface ScheduleRunnerEvents {\n 'schedule:blocked': (diagnostic: {\n scheduleId: string;\n reason: string;\n }) => void;\n 'schedule:triggered': (schedule: ScheduleInfo) => void;\n 'schedule:error': (schedule: ScheduleInfo, error: Error) => void;\n 'schedule:completed': (scheduleId: string) => void;\n 'schedule:failed': (scheduleId: string, error: string) => void;\n 'runner:started': () => void;\n 'runner:stopped': () => void;\n 'runner:error': (error: Error) => void;\n}\n\n/**\n * Schedule info for events\n */\nexport interface ScheduleInfo {\n id: string;\n agentType: string;\n agentId: string | null;\n cron: string;\n}\n\n/**\n * Default configuration\n */\ntype ResolvedScheduleRunnerConfig = Required<\n Omit<ScheduleRunnerConfig, 'agentTypes' | 'tenantIds'>\n> &\n Pick<ScheduleRunnerConfig, 'agentTypes' | 'tenantIds'>;\n\nconst DEFAULT_CONFIG: ResolvedScheduleRunnerConfig = {\n id: '',\n pollInterval: 60000, // 1 minute\n batchSize: 50,\n occurrenceSigner: null,\n queue: SCHEDULED_JOB_QUEUE,\n staleJobThresholdMs: 90000,\n taskHeartbeatInterval: DEFAULT_TASK_HEARTBEAT_INTERVAL_MS,\n};\n\n/**\n * ScheduleRunner polls for due agent schedules and creates jobs for them\n *\n * This runner works in conjunction with TaskRunner:\n * 1. ScheduleRunner checks for due schedules based on cron expressions\n * 2. When a schedule is due, it creates a SmrtJob for the agent\n * 3. TaskRunner picks up and executes the job\n * 4. On job completion/failure, call handleJobCompletion() to update the schedule\n *\n * @example\n * ```typescript\n * const scheduleRunner = new ScheduleRunner({ pollInterval: 30000 });\n * await scheduleRunner.initialize(db);\n * await scheduleRunner.start();\n *\n * // Wire up TaskRunner events to update schedule state\n * taskRunner.on('job:completed', (job) => {\n * const scheduleId = job.args?._scheduleId;\n * if (scheduleId) scheduleRunner.handleJobCompletion(scheduleId, true);\n * });\n * taskRunner.on('job:failed', (job, error) => {\n * const scheduleId = job.args?._scheduleId;\n * if (scheduleId) scheduleRunner.handleJobCompletion(scheduleId, false, error.message);\n * });\n *\n * // Graceful shutdown\n * process.on('SIGTERM', () => scheduleRunner.stop());\n * ```\n */\nexport class ScheduleRunner extends EventEmitter {\n /** Public contracts hosts may require before admitting enabled schedules. */\n static readonly capabilities = Object.freeze({\n atomicOccurrences: true,\n scopedAdmission: true,\n drain: true,\n occurrenceIntegrity: true,\n requiredOccurrenceIntegrity: true,\n } as const);\n readonly id: string;\n private readonly config: ResolvedScheduleRunnerConfig;\n private jobCollection: SmrtJobCollection | null = null;\n private running = false;\n private pollTimer: NodeJS.Timeout | null = null;\n private pollInFlight: Promise<void> | null = null;\n private stopping: Promise<void> | null = null;\n private db: DatabaseInterface | null = null;\n private logger = createLogger(true);\n\n constructor(config: ScheduleRunnerConfig = {}) {\n super();\n this.config = {\n ...DEFAULT_CONFIG,\n ...config,\n id: config.id || `schedule_${createId().slice(0, 8)}`,\n };\n this.id = this.config.id;\n const signer = this.config.occurrenceSigner;\n if (\n signer != null &&\n (typeof signer.keyId !== 'string' ||\n !signer.keyId.trim() ||\n signer.keyId.length > 256 ||\n typeof signer.sign !== 'function' ||\n typeof signer.verify !== 'function')\n ) {\n throw new TypeError(\n 'occurrenceSigner must be a trusted host signer with a current keyId',\n );\n }\n if (\n !Number.isInteger(this.config.batchSize) ||\n this.config.batchSize <= 0\n ) {\n throw new TypeError('batchSize must be a positive integer');\n }\n if (\n !Number.isFinite(this.config.pollInterval) ||\n this.config.pollInterval <= 0 ||\n this.config.pollInterval > 2_147_483_647\n ) {\n throw new TypeError(\n 'pollInterval must be a finite positive Node timer interval',\n );\n }\n if (typeof this.config.queue !== 'string' || !this.config.queue.trim())\n throw new TypeError('queue must be nonblank');\n for (const values of [this.config.agentTypes, this.config.tenantIds]) {\n if (\n values !== undefined &&\n (!Array.isArray(values) ||\n values.some(\n (value) =>\n value !== null && (typeof value !== 'string' || !value.trim()),\n ))\n ) {\n throw new TypeError(\n 'ScheduleRunner scopes must contain nonblank identities',\n );\n }\n }\n if (this.config.agentTypes?.some((value) => value == null))\n throw new TypeError('agentTypes cannot contain null');\n if (this.config.agentTypes)\n this.config.agentTypes = [...this.config.agentTypes];\n if (this.config.tenantIds)\n this.config.tenantIds = [...this.config.tenantIds];\n }\n\n private scheduleScope(): { sql: string; params: unknown[] } {\n const terms: string[] = [];\n const params: unknown[] = [];\n if (this.config.agentTypes !== undefined) {\n terms.push(\n this.config.agentTypes.length\n ? `agent_type IN (${this.config.agentTypes.map(() => '?').join(', ')})`\n : '1 = 0',\n );\n params.push(...this.config.agentTypes);\n }\n if (this.config.tenantIds !== undefined) {\n const tenants = this.config.tenantIds.filter(\n (id): id is string => id !== null,\n );\n const parts: string[] = [];\n if (tenants.length)\n parts.push(`tenant_id IN (${tenants.map(() => '?').join(', ')})`);\n if (this.config.tenantIds.includes(null)) parts.push('tenant_id IS NULL');\n terms.push(parts.length ? `(${parts.join(' OR ')})` : '1 = 0');\n params.push(...tenants);\n }\n return { sql: terms.length ? ` AND ${terms.join(' AND ')}` : '', params };\n }\n\n /**\n * Initialize the runner with database connection\n */\n async initialize(db: DatabaseInterface): Promise<void> {\n this.db = db;\n this.jobCollection = await SmrtJobCollection.create({ db });\n }\n\n /**\n * Start processing schedules\n */\n async start(): Promise<void> {\n if (this.stopping) await this.stopping;\n if (this.running) return;\n if (!this.db) {\n throw new Error(\n 'ScheduleRunner not initialized. Call initialize() first.',\n );\n }\n\n if (!this.db.transaction) {\n throw new Error('ScheduleRunner requires transaction support');\n }\n this.running = true;\n\n // Start polling loop\n this.startPolling();\n\n this.emit('runner:started');\n this.logger.info('ScheduleRunner started', { id: this.id });\n }\n\n /**\n * Stop processing schedules\n */\n async stop(): Promise<void> {\n if (this.stopping) return this.stopping;\n if (!this.running && !this.pollInFlight) return;\n this.running = false;\n if (this.pollTimer) {\n clearTimeout(this.pollTimer);\n this.pollTimer = null;\n }\n this.stopping = (async () => {\n await this.pollInFlight;\n this.emit('runner:stopped');\n this.logger.info('ScheduleRunner stopped', { id: this.id });\n })();\n try {\n await this.stopping;\n } finally {\n this.stopping = null;\n }\n }\n\n /**\n * Check if runner is running\n */\n isRunning(): boolean {\n return this.running;\n }\n\n /**\n * Handle job completion for a scheduled job.\n *\n * Call this from TaskRunner's job:completed / job:failed events\n * when the job has a `_scheduleId` in its args.\n */\n async handleJobCompletion(\n scheduleId: string,\n success: boolean,\n errorMessage?: string,\n ): Promise<void> {\n if (!this.db) return;\n\n const scope = this.scheduleScope();\n\n // `last_error` is persisted to a durable schedule row; strip secret-shaped\n // substrings the same way the job runner does (S5 audit #1402).\n const safeErrorMessage = redactErrorMessage(\n errorMessage ?? 'Unknown error',\n );\n\n try {\n if (success) {\n const result = await this.db.query(\n `UPDATE _smrt_agent_schedules\n SET running_count = CASE WHEN COALESCE(running_count, 0) > 0 THEN running_count - 1 ELSE 0 END,\n last_run = ?,\n last_status = 'success',\n last_error = NULL,\n run_count = COALESCE(run_count, 0) + 1,\n success_count = COALESCE(success_count, 0) + 1\n WHERE id = ?${scope.sql} RETURNING id`,\n new Date().toISOString(),\n scheduleId,\n ...scope.params,\n );\n if (result.rows.length !== 1) return;\n this.emit('schedule:completed', scheduleId);\n } else {\n const result = await this.db.query(\n `UPDATE _smrt_agent_schedules\n SET running_count = CASE WHEN COALESCE(running_count, 0) > 0 THEN running_count - 1 ELSE 0 END,\n last_run = ?,\n last_status = 'failed',\n last_error = ?,\n run_count = COALESCE(run_count, 0) + 1,\n failure_count = COALESCE(failure_count, 0) + 1\n WHERE id = ?${scope.sql} RETURNING id`,\n new Date().toISOString(),\n safeErrorMessage,\n scheduleId,\n ...scope.params,\n );\n if (result.rows.length !== 1) return;\n this.emit('schedule:failed', scheduleId, safeErrorMessage);\n }\n } catch (err) {\n this.logger.error('Failed to update schedule after job completion', {\n scheduleId,\n error: err,\n });\n }\n }\n\n /**\n * Start the polling loop\n */\n private startPolling(): void {\n const poll = async () => {\n if (!this.running) return;\n\n try {\n this.pollInFlight = this.poll();\n await this.pollInFlight;\n } catch (error) {\n this.emit('runner:error', error as Error);\n this.logger.error('ScheduleRunner poll error', { error });\n } finally {\n this.pollInFlight = null;\n }\n\n // Schedule next poll\n if (this.running) {\n this.pollTimer = setTimeout(poll, this.config.pollInterval);\n }\n };\n\n // Start immediately\n poll();\n }\n\n /**\n * Poll for due schedules and create jobs\n */\n private async poll(): Promise<void> {\n if (!this.db || !this.jobCollection) return;\n\n const managedPoll = this.running;\n await this.recoverStaleScheduleState();\n const now = new Date().toISOString();\n\n const scope = this.scheduleScope();\n // Find due schedules\n const result = await this.db.query(\n `SELECT *, CAST(id AS VARCHAR) AS schedule_id_text, CAST(tenant_id AS VARCHAR) AS schedule_tenant_text, CAST(next_run AS VARCHAR) AS occurrence_time FROM _smrt_agent_schedules\n WHERE enabled = true\n AND status = 'active'\n AND next_run <= ?${scope.sql}\n AND COALESCE(running_count, 0) < COALESCE(max_concurrent, 1)\n ORDER BY next_run ASC\n LIMIT ?`,\n now,\n ...scope.params,\n this.config.batchSize,\n );\n\n for (const row of result.rows) {\n if (managedPoll && !this.running) break;\n await this.triggerSchedule(\n portableScheduleRow(row as ScheduleRow),\n managedPoll,\n );\n }\n }\n\n private assertAdmissionHost(schedule: ScheduleRow): void {\n let policy: ReturnType<typeof getScheduleAdmissionPolicy>;\n try {\n policy = getScheduleAdmissionPolicy(schedule.method_args || {});\n } catch {\n throw new ScheduleAdmissionBlockedError('INVALID_ADMISSION_POLICY');\n }\n if (!policy) return;\n if (!this.config.occurrenceSigner)\n throw new ScheduleAdmissionBlockedError('MISSING_OCCURRENCE_SIGNER');\n if (this.config.occurrenceSigner.keyId !== policy.keyId)\n throw new ScheduleAdmissionBlockedError('WRONG_OCCURRENCE_KEY');\n if (this.config.queue !== policy.queue)\n throw new ScheduleAdmissionBlockedError('WRONG_OCCURRENCE_QUEUE');\n }\n\n private reportBlocked(schedule: ScheduleRow, error: Error): void {\n const diagnostic = {\n scheduleId: String(schedule.id),\n reason: error.message,\n };\n this.emit('schedule:blocked', diagnostic);\n this.logger.warn(\n 'Schedule admission blocked by durable policy',\n diagnostic,\n );\n }\n\n /** Pending retries occupy slots too; TaskRunner alone owns worker recovery. */\n private async countScheduleJobs(\n db: DatabaseInterface,\n schedule: ScheduleRow,\n ): Promise<number> {\n return countScheduleJobs(\n db,\n String(schedule.id),\n schedule.tenant_id == null ? null : String(schedule.tenant_id),\n {\n objectType: String(schedule.agent_type),\n objectId: schedule.agent_id == null ? null : String(schedule.agent_id),\n method: String(schedule.method || 'run'),\n },\n );\n }\n\n /** Reconcile cached slots without changing TaskRunner-owned job lifecycle. */\n private async recoverStaleScheduleState(): Promise<void> {\n const db = this.db;\n if (!db?.transaction) return;\n const scope = this.scheduleScope();\n const schedules = await db.query(\n `SELECT *, CAST(id AS VARCHAR) AS schedule_id_text, CAST(tenant_id AS VARCHAR) AS schedule_tenant_text FROM _smrt_agent_schedules WHERE 1 = 1${scope.sql}`,\n ...scope.params,\n );\n for (const row of schedules.rows) {\n const candidate = portableScheduleRow(row as ScheduleRow);\n try {\n this.assertAdmissionHost(candidate);\n await db.transaction(async (tx) => {\n const locked = await tx.query(\n `UPDATE _smrt_agent_schedules SET running_count = running_count WHERE id = ?${scope.sql} RETURNING *, CAST(id AS VARCHAR) AS schedule_id_text, CAST(tenant_id AS VARCHAR) AS schedule_tenant_text, CAST(next_run AS VARCHAR) AS occurrence_time`,\n candidate.id,\n ...scope.params,\n );\n if (locked.rows.length !== 1) return;\n const schedule = portableScheduleRow(locked.rows[0] as ScheduleRow);\n this.assertAdmissionHost(schedule);\n const occupied = await this.countScheduleJobs(tx, schedule);\n await tx.query(\n 'UPDATE _smrt_agent_schedules SET running_count = ? WHERE id = ?',\n occupied,\n candidate.id,\n );\n });\n } catch (error) {\n if (!(error instanceof ScheduleAdmissionBlockedError)) throw error;\n this.reportBlocked(candidate, error);\n }\n }\n }\n\n /**\n * Trigger a schedule by creating a job\n */\n private async triggerSchedule(\n candidate: ScheduleRow,\n managedPoll = false,\n ): Promise<void> {\n if (!this.db || !this.jobCollection) return;\n candidate = portableScheduleRow(candidate);\n const db = this.db;\n let admission: { schedule: ScheduleInfo; error?: Error } | undefined;\n try {\n this.assertAdmissionHost(candidate);\n if (!db.transaction)\n throw new Error('ScheduleRunner requires transaction support');\n admission = await db.transaction(async (tx) => {\n if (managedPoll && !this.running) return;\n // The write locks the current row. PostgreSQL rechecks its predicate\n // after a competing writer commits; stale selected occurrences lose.\n const expected = candidate.occurrence_time ?? candidate.next_run;\n const scope = this.scheduleScope();\n const claimed = await tx.query(\n `UPDATE _smrt_agent_schedules SET running_count = running_count\n WHERE id = ? AND enabled = TRUE AND status = 'active'\n AND next_run <= ?${expected == null ? '' : ' AND next_run = ?'}${scope.sql}\n RETURNING *, CAST(id AS VARCHAR) AS schedule_id_text, CAST(tenant_id AS VARCHAR) AS schedule_tenant_text, CAST(next_run AS VARCHAR) AS occurrence_time`,\n candidate.id,\n new Date().toISOString(),\n ...(expected == null ? [] : [expected]),\n ...scope.params,\n );\n if (claimed.rows.length !== 1 || (managedPoll && !this.running)) return;\n const schedule = portableScheduleRow(claimed.rows[0] as ScheduleRow);\n this.assertAdmissionHost(schedule);\n const occupied = await this.countScheduleJobs(tx, schedule);\n await tx.query(\n 'UPDATE _smrt_agent_schedules SET running_count = ? WHERE id = ?',\n occupied,\n schedule.id,\n );\n if (occupied >= Number(schedule.max_concurrent ?? 1)) return;\n const jobs = await SmrtJobCollection.create({ db: tx });\n return this.triggerLockedSchedule(schedule, tx, jobs, occupied);\n });\n } catch (error) {\n if (error instanceof ScheduleAdmissionBlockedError) {\n this.reportBlocked(candidate, error);\n return;\n }\n await db.query(\n 'UPDATE _smrt_agent_schedules SET last_error = ? WHERE id = ?',\n redactErrorForPersistence(error),\n candidate.id,\n );\n this.emit(\n 'schedule:error',\n {\n id: String(candidate.id),\n agentType: String(candidate.agent_type),\n agentId: candidate.agent_id as string | null,\n cron: String(candidate.cron),\n },\n error as Error,\n );\n return;\n }\n // Notify subscribers only after the occurrence and job have committed.\n if (admission?.error) {\n this.emit('schedule:error', admission.schedule, admission.error);\n } else if (admission) {\n this.emit('schedule:triggered', admission.schedule);\n this.logger.info('Schedule triggered', {\n scheduleId: admission.schedule.id,\n });\n }\n }\n\n private async triggerLockedSchedule(\n schedule: ScheduleRow,\n db: DatabaseInterface,\n jobs: SmrtJobCollection,\n occupied: number,\n ): Promise<{ schedule: ScheduleInfo; error?: Error } | undefined> {\n const rawAgentType = schedule.agent_type as string;\n const canonicalAgentType =\n ObjectRegistry.getClass(rawAgentType)?.qualifiedName || rawAgentType;\n\n const scheduleInfo: ScheduleInfo = {\n id: schedule.id as string,\n agentType: canonicalAgentType,\n agentId: schedule.agent_id as string | null,\n cron: schedule.cron as string,\n };\n\n // Parse method_args and agent_config from JSON strings if needed\n let methodArgs: Record<string, unknown> = {};\n if (schedule.method_args) {\n methodArgs =\n typeof schedule.method_args === 'string'\n ? JSON.parse(schedule.method_args as string)\n : (schedule.method_args as Record<string, unknown>);\n }\n if (\n !methodArgs ||\n typeof methodArgs !== 'object' ||\n Array.isArray(methodArgs)\n )\n throw new TypeError('Schedule method_args must be a JSON object');\n for (const key of [\n '_scheduleId',\n '_scheduledFor',\n '_agentConfig',\n '_scheduleAdmission',\n ]) {\n if (Object.hasOwn(methodArgs, key))\n throw new TypeError(`Schedule method_args cannot set reserved ${key}`);\n }\n let agentConfig: Record<string, unknown> = {};\n if (schedule.agent_config) {\n agentConfig =\n typeof schedule.agent_config === 'string'\n ? JSON.parse(schedule.agent_config as string)\n : (schedule.agent_config as Record<string, unknown>);\n }\n\n // Compute next run time from cron before creating the job, evaluated\n // in the row's zone; a missing/blank zone falls back to the column\n // default (UTC) rather than the host's process zone (#3859).\n // An invalid cron or zone is a deterministic configuration failure:\n // retrying it every poll can never succeed, so move the row to\n // status='error' (as AgentSchedule.calculateNextRun does). Only these\n // validation errors are terminal; a valid cron whose next run lies past\n // the search horizon (a leap-day schedule) stays active.\n const timezone =\n typeof schedule.timezone === 'string' && schedule.timezone.trim()\n ? schedule.timezone.trim()\n : 'UTC';\n try {\n validateCronExpression(schedule.cron as string);\n validateCronTimezone(timezone);\n } catch (error) {\n await db.query(\n `UPDATE _smrt_agent_schedules\n SET status = 'error', last_error = ?\n WHERE id = ?`,\n redactErrorForPersistence(error),\n schedule.id,\n );\n this.logger.error('Schedule has an invalid cron or time zone', {\n scheduleId: schedule.id,\n error,\n });\n return { schedule: scheduleInfo, error: error as Error };\n }\n const nextRun = getNextCronDate(schedule.cron as string, timezone);\n\n // Create a job for this schedule\n // Nest agent_config under _agentConfig so TaskRunner can pass it\n // to the agent constructor separately from method args\n const args: Record<string, unknown> = {\n ...methodArgs,\n _scheduleId: String(schedule.id),\n _scheduledFor: scheduleOccurrenceInstant(schedule),\n };\n if (Object.keys(agentConfig).length > 0) {\n args._agentConfig = agentConfig;\n }\n\n // The occurrence, job insert and slot update share the locked transaction.\n const job = await jobs.enqueueJob({\n tenantId:\n typeof schedule.tenant_id === 'string' && schedule.tenant_id.length > 0\n ? (schedule.tenant_id as string)\n : null,\n queue: this.config.queue,\n objectType: canonicalAgentType,\n objectId: schedule.agent_id as string | null,\n method: (schedule.method as string) || 'run',\n args,\n priority: 75, // High priority for scheduled agents\n maxAttempts: 3,\n timeout: (schedule.timeout as number) || 3600000,\n });\n\n if (this.config.occurrenceSigner) {\n const signer = this.config.occurrenceSigner;\n const integrity = signer.sign(\n getScheduleAdmissionPayload(job, signer.keyId),\n );\n job.args = { ...job.args, _scheduleAdmission: integrity };\n if (!verifyScheduleAdmission(job, signer)) {\n throw new Error(\n 'Occurrence signer returned invalid schedule admission integrity',\n );\n }\n // This model is bound to the admission transaction. No consumer can see\n // an unsigned protected job, and no producer save follows the commit.\n await job.save();\n }\n\n // Only now that the job is durably enqueued do we consume the slot:\n // increment running_count and advance next_run in one update.\n await db.query(\n `UPDATE _smrt_agent_schedules\n SET agent_type = ?,\n running_count = ?,\n next_run = ?\n WHERE id = ?`,\n canonicalAgentType,\n occupied + 1,\n nextRun.toISOString(),\n schedule.id,\n );\n\n return { schedule: scheduleInfo };\n }\n}\n\n/**\n * Database row type for schedule\n */\ninterface ScheduleRow {\n id: unknown;\n agent_type: unknown;\n agent_id: unknown;\n tenant_id: unknown;\n agent_config: unknown;\n cron: unknown;\n timezone: unknown;\n method: unknown;\n method_args: unknown;\n timeout: unknown;\n next_run?: unknown;\n occurrence_time?: unknown;\n schedule_id_text?: string;\n schedule_tenant_text?: string | null;\n max_concurrent?: unknown;\n}\n\nfunction portableScheduleRow(row: ScheduleRow): ScheduleRow {\n return {\n ...row,\n id: row.schedule_id_text ?? row.id,\n tenant_id: Object.hasOwn(row, 'schedule_tenant_text')\n ? row.schedule_tenant_text\n : row.tenant_id,\n };\n}\n\n/** SQL datetime columns store UTC wall clocks; never parse them in host TZ. */\nfunction scheduleOccurrenceInstant(schedule: ScheduleRow): string {\n const raw = schedule.occurrence_time ?? schedule.next_run;\n if (raw instanceof Date) return raw.toISOString();\n let text = String(raw).trim();\n if (/^\\d{4}-\\d{2}-\\d{2}[ T]\\d{2}:\\d{2}:\\d{2}(?:\\.\\d+)?$/.test(text)) {\n text = `${text.replace(' ', 'T')}Z`;\n }\n return new Date(text).toISOString();\n}\n\n// --- Cron helpers (self-contained, no external dependency) ---\n\n/**\n * Inclusive valid range for each cron field, by position.\n * minute, hour, day-of-month, month, day-of-week.\n * Day-of-week accepts 0-7 where both 0 and 7 represent Sunday.\n */\nconst CRON_FIELD_RANGES: ReadonlyArray<{\n name: string;\n min: number;\n max: number;\n}> = [\n { name: 'minute', min: 0, max: 59 },\n { name: 'hour', min: 0, max: 23 },\n { name: 'day-of-month', min: 1, max: 31 },\n { name: 'month', min: 1, max: 12 },\n { name: 'day-of-week', min: 0, max: 7 },\n];\n\n/**\n * Validate that every numeric component of a single cron field falls within\n * the field's inclusive range. Rejects malformed values up front so an\n * out-of-range field (e.g. `minute=70`) fails fast at schedule-trigger time\n * instead of silently scanning ~525k candidate minutes and never matching\n * (S5 audit #1402).\n */\nfunction validateCronField(\n expr: string,\n range: { name: string; min: number; max: number },\n): void {\n if (expr === '*') return;\n\n const reject = (detail: string): never => {\n throw new Error(\n `Invalid cron expression: ${range.name} field \"${expr}\" ${detail} ` +\n `(valid range ${range.min}-${range.max})`,\n );\n };\n\n const assertInRange = (value: number): void => {\n if (!Number.isInteger(value) || value < range.min || value > range.max) {\n reject('is out of range');\n }\n };\n\n for (const term of expr.split(',')) {\n if (term === '') reject('contains an empty value');\n\n let body = term;\n if (body.includes('/')) {\n // Exactly one '/' is valid (`base/step`). `1/2/3` must be rejected, not\n // silently parsed as `1/2` by dropping the trailing segment.\n const stepParts = body.split('/');\n if (stepParts.length !== 2) {\n reject('has malformed step syntax');\n }\n const [rangePart, stepStr] = stepParts;\n const step = Number(stepStr);\n if (!Number.isInteger(step) || step <= 0) {\n reject('has an invalid step');\n }\n body = rangePart;\n if (body === '*') continue;\n }\n\n if (body.includes('-')) {\n // Exactly one '-' is valid (`start-end`). `1-2-3` must be rejected, not\n // silently parsed as `1-2` by dropping the trailing segment.\n const rangeParts = body.split('-');\n if (rangeParts.length !== 2) {\n reject('has malformed range syntax');\n }\n const [startStr, endStr] = rangeParts;\n if (startStr === '' || endStr === '') {\n reject('has an empty range part');\n }\n const start = Number(startStr);\n const end = Number(endStr);\n assertInRange(start);\n assertInRange(end);\n if (start > end) reject('has an inverted range');\n } else {\n assertInRange(Number(body));\n }\n }\n}\n\n/**\n * Validate a standard 5-field cron expression: field count plus per-field\n * value ranges. Throws a descriptive `Error` on the first invalid field.\n *\n * Exposed so callers (and the agents package, which owns schedule creation)\n * can reject a bad cron at write time rather than letting an out-of-range\n * field silently never match (S5 audit #1402).\n *\n * @param cron - The cron expression to validate.\n * @returns The trimmed, whitespace-split fields when valid.\n */\nexport function validateCronExpression(cron: string): string[] {\n const parts = cron.trim().split(/\\s+/);\n if (parts.length !== 5) {\n throw new Error(\n `Invalid cron expression: expected 5 fields, got ${parts.length}`,\n );\n }\n\n parts.forEach((field, index) => {\n validateCronField(field, CRON_FIELD_RANGES[index]);\n });\n\n return parts;\n}\n\nconst MINUTE_MS = 60_000;\nconst HOUR_MS = 60 * MINUTE_MS;\nconst DAY_MS = 24 * HOUR_MS;\n\n/** Wall-clock minutes scanned before giving up (one year, as before). */\nconst CRON_SEARCH_HORIZON_MS = 525_600 * MINUTE_MS;\n\n/** UTC offset (ms, east-positive) of a zone at an instant. */\ntype ZoneOffsetAt = (epochMs: number) => number;\n\nconst zoneFormatters = new Map<string, Intl.DateTimeFormat>();\n\n/**\n * Resolve the offset function for a cron time zone. `undefined`/`null` keeps\n * the legacy host-local behaviour (the process `TZ`); any other value must be\n * an IANA zone name accepted by `Intl.DateTimeFormat`.\n */\nfunction resolveZoneOffset(timezone: string | null | undefined): ZoneOffsetAt {\n if (timezone === undefined || timezone === null) {\n return (epochMs) => -new Date(epochMs).getTimezoneOffset() * MINUTE_MS;\n }\n\n let formatter = zoneFormatters.get(timezone);\n if (!formatter) {\n try {\n formatter = new Intl.DateTimeFormat('en-US', {\n timeZone: timezone,\n hourCycle: 'h23',\n year: 'numeric',\n month: 'numeric',\n day: 'numeric',\n hour: 'numeric',\n minute: 'numeric',\n second: 'numeric',\n });\n } catch {\n throw new Error(\n `Invalid cron timezone: \"${timezone}\" is not a recognized IANA time zone`,\n );\n }\n zoneFormatters.set(timezone, formatter);\n }\n\n const zoned = formatter;\n return (epochMs) => {\n const fields: Record<string, number> = {};\n for (const part of zoned.formatToParts(epochMs)) {\n if (part.type !== 'literal') fields[part.type] = Number(part.value);\n }\n const wallMs = Date.UTC(\n fields.year,\n fields.month - 1,\n fields.day,\n // `% 24` guards ICU builds that render midnight as hour 24.\n fields.hour % 24,\n fields.minute,\n fields.second,\n );\n return wallMs - (epochMs - (((epochMs % 1000) + 1000) % 1000));\n };\n}\n\n/**\n * Instants at which a wall-clock time (given as UTC-epoch ms of its naive\n * fields) occurs in the zone: one normally, two in a backward-transition\n * overlap (earlier first), none in a forward-transition gap. Assumes at most\n * one offset transition within a day either side, true of every IANA zone.\n */\nfunction wallTimeInstants(\n wallMs: number,\n offsetAt: ZoneOffsetAt,\n): { instants: number[]; offsetBefore: number; offsetAfter: number } {\n const offsetBefore = offsetAt(wallMs - DAY_MS);\n const offsetAfter = offsetAt(wallMs + DAY_MS);\n const instants: number[] = [];\n for (const offset of new Set([offsetBefore, offsetAfter])) {\n const instant = wallMs - offset;\n if (offsetAt(instant) === offset) instants.push(instant);\n }\n instants.sort((a, b) => a - b);\n return { instants, offsetBefore, offsetAfter };\n}\n\n/**\n * Validate a cron time zone without computing a run date.\n *\n * @throws `Invalid cron timezone` when the name is not an IANA zone.\n */\nfunction validateCronTimezone(timezone: string): void {\n resolveZoneOffset(timezone);\n}\n\n/**\n * Parse a cron expression and get the next run date.\n * Supports standard 5-field cron: minute hour day-of-month month day-of-week\n *\n * Fields are matched against the wall clock of `timezone`, an IANA zone name\n * such as `America/Edmonton` (DST-correct via `Intl.DateTimeFormat`). When\n * `timezone` is omitted (`undefined`/`null`) the host process's local zone is\n * used — the legacy behaviour, kept for callers that have no zone to pass.\n * Persisted schedules should always pass their row's zone; the\n * `_smrt_agent_schedules.timezone` column defaults to `UTC`.\n *\n * Daylight-saving transitions follow Vixie cron's split:\n * - **Fixed-time** expressions (no `*` in the minute or hour field) run once\n * per matching day. A wall time skipped by a forward transition runs\n * shifted forward by the gap (`30 2 * * *` on the spring-forward day in\n * `America/Edmonton` runs at 03:30 MDT, RFC 5545 / Temporal \"compatible\"\n * resolution); a wall time repeated by a backward transition runs only at\n * its first occurrence.\n * - **Wildcard** expressions (`*` in the minute or hour field, including\n * `*\\/n`) follow elapsed time: skipped wall times do not run and repeated\n * wall times run again in the repeated hour.\n *\n * Limitations:\n * - Numeric values only (no abbreviated names like JAN, MON)\n * - Day-of-week accepts 0-7 where both 0 and 7 represent Sunday\n *\n * Out-of-range fields and unknown time zones are rejected eagerly (see\n * {@link validateCronExpression}).\n *\n * @param cron - 5-field cron expression.\n * @param timezone - IANA zone the cron is evaluated in; omit for host-local.\n * @returns The first matching instant at least one minute after now.\n */\nexport function getNextCronDate(cron: string, timezone?: string | null): Date {\n const [minuteExpr, hourExpr, dayExpr, monthExpr, dowExpr] =\n validateCronExpression(cron);\n const offsetAt = resolveZoneOffset(timezone);\n\n // Standard cron DOM/DOW semantics:\n // When both day-of-month and day-of-week are restricted (not *),\n // a date matches if EITHER condition is met (OR logic).\n const dayIsWildcard = dayExpr === '*';\n const dowIsWildcard = dowExpr === '*';\n const fixedTime = !minuteExpr.includes('*') && !hourExpr.includes('*');\n\n const dayMatches = (wall: Date): boolean => {\n const domMatches = matchesCronField(\n wall.getUTCDate(),\n dayExpr,\n CRON_FIELD_RANGES[2],\n );\n // getUTCDay() returns 0 for Sunday; standard cron accepts both 0 and 7\n const dow = wall.getUTCDay();\n const dowMatches =\n matchesCronField(dow, dowExpr, CRON_FIELD_RANGES[4]) ||\n (dow === 0 && matchesCronField(7, dowExpr, CRON_FIELD_RANGES[4]));\n if (!dayIsWildcard && !dowIsWildcard) return domMatches || dowMatches;\n if (!dayIsWildcard) return domMatches;\n if (!dowIsWildcard) return dowMatches;\n return true;\n };\n\n // The earliest eligible instant: the start of the next minute.\n const now = Date.now();\n const threshold =\n now - (((now % MINUTE_MS) + MINUTE_MS) % MINUTE_MS) + MINUTE_MS;\n\n // Scan naive wall-clock minutes (UTC accessors on wall-time epochs). A\n // transition near the threshold can map earlier wall times to eligible\n // instants (the repeated hour, or a gap shifted forward), so start the\n // scan one transition-width before the threshold's wall time.\n const thresholdOffset = offsetAt(threshold);\n const thresholdSpread = Math.abs(\n offsetAt(threshold - DAY_MS) - offsetAt(threshold + DAY_MS),\n );\n let wallMs = threshold + thresholdOffset - thresholdSpread;\n const wallEnd = threshold + thresholdOffset + CRON_SEARCH_HORIZON_MS;\n\n let best: number | null = null;\n let stopAfterWall = Number.POSITIVE_INFINITY;\n\n while (wallMs <= wallEnd && wallMs <= stopAfterWall) {\n const wall = new Date(wallMs);\n const year = wall.getUTCFullYear();\n const month = wall.getUTCMonth();\n const day = wall.getUTCDate();\n const hour = wall.getUTCHours();\n\n if (!matchesCronField(month + 1, monthExpr, CRON_FIELD_RANGES[3])) {\n wallMs = Date.UTC(year, month + 1, 1);\n continue;\n }\n if (!dayMatches(wall)) {\n wallMs = Date.UTC(year, month, day + 1);\n continue;\n }\n if (!matchesCronField(hour, hourExpr, CRON_FIELD_RANGES[1])) {\n wallMs = Date.UTC(year, month, day, hour + 1);\n continue;\n }\n if (\n !matchesCronField(wall.getUTCMinutes(), minuteExpr, CRON_FIELD_RANGES[0])\n ) {\n wallMs += MINUTE_MS;\n continue;\n }\n\n const { instants, offsetBefore, offsetAfter } = wallTimeInstants(\n wallMs,\n offsetAt,\n );\n let candidates = instants;\n if (instants.length === 0) {\n // Forward-transition gap: fixed-time runs shift forward by the gap.\n candidates = fixedTime ? [wallMs - offsetBefore] : [];\n } else if (instants.length > 1 && fixedTime) {\n // Backward-transition overlap: fixed-time runs fire once, first.\n candidates = [instants[0]];\n }\n\n for (const instant of candidates) {\n if (instant >= threshold && (best === null || instant < best)) {\n if (best === null) {\n // Later wall times within one transition width can still map to\n // an earlier instant (the repeated hour); keep scanning that far.\n stopAfterWall = wallMs + Math.abs(offsetBefore - offsetAfter);\n }\n best = instant;\n }\n }\n\n wallMs += MINUTE_MS;\n }\n\n if (best === null) {\n throw new Error(`Could not find next run date for cron: ${cron}`);\n }\n return new Date(best);\n}\n\n/**\n * Check if a value matches a cron field expression.\n *\n * Each comma-separated term is evaluated on its own, so mixed lists such as\n * `1-5,10` or `0,30-40/5` match every term rather than parsing the whole\n * list as one range. `*\\/step` steps from the field minimum (day-of-month\n * `*\\/2` is 1,3,5,…; month `*\\/3` is 1,4,7,10), and `base/step` without a range\n * (`5/15`) steps from `base` to the field maximum — the common cron extension\n * the validator already accepts.\n */\nfunction matchesCronField(\n value: number,\n expr: string,\n range: { min: number; max: number },\n): boolean {\n if (expr === '*') return true;\n return expr.split(',').some((term) => {\n const [body, stepStr] = term.split('/');\n const step = stepStr === undefined ? 1 : parseInt(stepStr, 10);\n let start: number;\n let end: number;\n if (body === '*') {\n start = range.min;\n end = range.max;\n } else if (body.includes('-')) {\n const [startStr, endStr] = body.split('-');\n start = parseInt(startStr, 10);\n end = parseInt(endStr, 10);\n } else {\n start = parseInt(body, 10);\n end = stepStr === undefined ? start : range.max;\n }\n return value >= start && value <= end && (value - start) % step === 0;\n });\n}\n\n/**\n * Create a ScheduleRunner instance\n */\nexport function createScheduleRunner(\n config?: ScheduleRunnerConfig,\n): ScheduleRunner {\n return new ScheduleRunner(config);\n}\n\nexport default ScheduleRunner;\n","/**\n * @happyvertical/smrt-jobs\n *\n * Background job execution for SMRT objects.\n * Provides persistence, retries, and scheduling for any SmrtObject method.\n *\n * @example\n * ```typescript\n * import { withBackgroundJobs, TaskRunner } from '@happyvertical/smrt-jobs';\n *\n * // Add background capabilities to your class\n * const BackgroundDocument = withBackgroundJobs(Document);\n * const doc = new BackgroundDocument({ ... });\n *\n * // Simple background execution\n * const handle = await doc.bg('generateSummary', { format: 'md' });\n *\n * // Fluent builder for advanced options\n * const handle = await doc.background('generateSummary', { format: 'md' })\n * .delay('5m')\n * .retries(5)\n * .priority('high')\n * .enqueue();\n *\n * // Wait for result\n * const result = await handle.wait();\n *\n * // Start a task runner to process jobs\n * const runner = new TaskRunner({ concurrency: 5 });\n * await runner.initialize(db);\n * await runner.start();\n * ```\n */\n\n// Self-register this package's manifest before any @smrt() decorator fires\n// downstream. Must come first so the side effect runs ahead of the class\n// module loads below. See __smrt-register__.ts for issue #1132 context.\nimport './__smrt-register__.js';\n// Contribute `_smrt_jobs`/`_smrt_job_events` retention to the framework sweep\n// as soon as this package is loaded (#2375), so `smrt db:prune` and any host\n// process see the tasks without an app-level wiring step. Registering is not\n// scheduling: nothing deletes until something runs a sweep, and the policy can\n// still disable either task by name.\nimport { registerJobRetentionTasks } from './retention.js';\n\nregisterJobRetentionTasks();\n\n// Background-job policy controls (retry ceiling, per-tenant cap, opt-in\n// method allowlist). Shared with the agents package (S5 audit #1402).\nexport {\n assertWithinTenantCreationCap,\n type BackgroundEligibleClass,\n backgroundEligible,\n clampRetries,\n DEFAULT_TENANT_JOB_CAP,\n getBackgroundEligibleMethods,\n isBackgroundEligibleMethod,\n MAX_JOB_RETRIES,\n markBackgroundEligible,\n TenantJobCapExceededError,\n} from './background-policy.js';\nexport {\n createHmacDurableJobPayloadSigner,\n type DurableJobPayloadIntegrity,\n type DurableJobPayloadSigner,\n} from './durable-payload-integrity.js';\n// Error-message redaction for durable job error persistence.\nexport {\n redactErrorForPersistence,\n redactErrorMessage,\n} from './error-redaction.js';\n// Durable provider-neutral forge delivery inbox and projection runtime.\nexport {\n type AcceptedForgeDelivery,\n type AcceptForgeDeliveryInput,\n type ClaimForgeDeliveryOptions,\n ForgeDelivery,\n ForgeDeliveryCollection,\n type ForgeDeliveryStatus,\n type ForgeObservation,\n type ForgeProjectionAuditEvent,\n type ForgeProjectionAuditHook,\n ForgeProjectionCheckpoint,\n type ForgeProjectionContext,\n ForgeProjectionRuntime,\n type ForgeProjectionRuntimeOptions,\n type ForgeProjector,\n} from './forge-projection.js';\n// Fluent job builder and utilities\nexport {\n JobBuilder,\n type Priority,\n parseDelay,\n priorityToNumber,\n} from './job-builder.js';\n// Job handle for tracking\nexport {\n JobHandle,\n type JobResult,\n type WaitOptions,\n} from './job-handle.js';\n// Logger extension\nexport {\n type JobContext,\n JobContextLogger,\n type JobEventInput,\n type JobExecutionContext,\n type JobProgressInput,\n} from './logger-extension.js';\n// Durable MCP Tasks extension adapter.\nexport {\n type CreateMcpTaskInput,\n createMcpTaskResult,\n getMcpTaskMarker,\n MCP_TASKS_EXTENSION,\n type McpTask,\n type McpTaskAuthority,\n McpTaskCancelledError,\n type McpTaskContinuation,\n type McpTaskJobMarker,\n McpTaskNotFoundError,\n type McpTaskStatus,\n McpTaskStore,\n McpTaskSuspendedError,\n requestMcpTaskContinuation,\n requestMcpTaskInput,\n taskFromJob,\n} from './mcp-task.js';\n// Object extension (mixin)\nexport {\n type BackgroundCapable,\n type BgOptions,\n withBackgroundJobs,\n} from './object-extension.js';\n// Job retention — bounded growth for _smrt_jobs / _smrt_job_events (#2375)\nexport {\n DEFAULT_JOB_RETENTION,\n DEFAULT_RETENTION_SWEEP_INTERVAL_MS,\n JOB_EVENTS_RETENTION_TASK,\n JOBS_RETENTION_TASK,\n type JobRetentionOptions,\n type RetentionSweeper,\n type RetentionSweeperOptions,\n registerJobRetentionTasks,\n startRetentionSweeper,\n unregisterJobRetentionTasks,\n} from './retention.js';\n// Task runner\nexport {\n createTaskRunner,\n getActiveJobExecutionContext,\n isRunnerExecutionContext,\n JobCancelledError,\n JobTimeoutError,\n TaskRunner,\n type TaskRunnerConfig,\n type TaskRunnerEvents,\n} from './runner.js';\nexport {\n getScheduleAdmissionPayload,\n getScheduleAdmissionPolicy,\n type ScheduleAdmissionPayload,\n type ScheduleAdmissionPolicy,\n verifyScheduleAdmission,\n} from './schedule-admission.js';\n\n// Schedule runner (for cron-based agent scheduling)\nexport {\n createScheduleRunner,\n getNextCronDate,\n SCHEDULED_JOB_QUEUE,\n type ScheduleInfo,\n ScheduleRunner,\n type ScheduleRunnerConfig,\n type ScheduleRunnerEvents,\n validateCronExpression,\n} from './schedule-runner.js';\n// Core job model\nexport {\n type ClaimReadyOptions,\n type JobStatus,\n type ListReadyOptions,\n SmrtJob,\n SmrtJobCollection,\n type SmrtJobData,\n type TimeoutBehavior,\n} from './smrt-job.js';\nexport { SmrtJobDedupeSlot } from './smrt-job-dedupe-slot.js';\n// Durable job telemetry\nexport {\n type JobEventCursor,\n type ListJobEventsOptions,\n type ListTerminalOutcomesOptions,\n SmrtJobEvent,\n SmrtJobEventCollection,\n type SmrtJobEventData,\n type SmrtJobEventLevel,\n type SmrtJobEventType,\n type SmrtJobTerminalOutcome,\n type SmrtJobTerminalOutcomePage,\n type SmrtJobTerminalStatus,\n} from './smrt-job-event.js';\n// Worker liveness lease model\nexport {\n type RegisterWorkerInput,\n SmrtWorker,\n SmrtWorkerCollection,\n} from './smrt-worker.js';\nexport {\n createWorkerKey,\n isWorkerAlive,\n registerLiveWorker,\n unregisterLiveWorker,\n} from './worker-liveness.js';\n"],"mappings":";;;;;;;;;AAeO,SAAS,kCAAkC,SAGtB;CAC1B,IAAI,CAAC,QAAQ,SAAS,QAAQ,MAAM,SAAS,KAC3C,MAAM,IAAI,MACR,2DACF;CAMF,KAHE,OAAO,QAAQ,QAAQ,WACnB,OAAO,WAAW,QAAQ,GAAG,IAC7B,QAAQ,IAAI,cACF,IACd,M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T;EAGF,UAAU;CACZ;CAEA,IAAI,SAAS,MACX,MAAM,IAAI,MAAM,0CAA0C,MAAM;CAElE,OAAO,IAAI,KAAK,IAAI;AACtB;AAYA,SAAS,iBACP,OACA,MACA,OACS;CACT,IAAI,SAAS,KAAK,OAAO;CACzB,OAAO,KAAK,MAAM,GAAG,CAAA,CAAE,MAAM,SAAS;EACpC,MAAM,CAAC,MAAM,WAAW,KAAK,MAAM,GAAG;EACtC,MAAM,OAAO,YAAY,KAAA,IAAY,IAAI,SAAS,SAAS,EAAE;EAC7D,IAAI;EACJ,IAAI;EACJ,IAAI,SAAS,KAAK;GAChB,QAAQ,MAAM;GACd,MAAM,MAAM;EACd,OAAA,IAAW,KAAK,SAAS,GAAG,GAAG;GAC7B,MAAM,CAAC,UAAU,UAAU,KAAK,MAAM,GAAG;GACzC,QAAQ,SAAS,UAAU,EAAE;GAC7B,MAAM,SAAS,QAAQ,EAAE;EAC3B,OAAO;GACL,QAAQ,SAAS,MAAM,EAAE;GACzB,MAAM,YAAY,KAAA,IAAY,QAAQ,MAAM;EAC9C;EACA,OAAO,SAAS,SAAS,SAAS,QAAQ,QAAQ,SAAS,SAAS;CACtE,CAAC;AACH;AAKO,SAAS,qBACd,QACgB;CAChB,OAAO,IAAI,eAAe,MAAM;AAClC;;;ACllCA,0BAA0B"}
|
|
1
|
+
{"version":3,"file":"index.js","names":["result"],"sources":["../src/durable-payload-integrity.ts","../src/forge-projection.ts","../src/job-handle.ts","../src/job-builder.ts","../src/object-extension.ts","../src/schedule-admission.ts","../src/schedule-runner.ts","../src/index.ts"],"sourcesContent":["import { createHmac, timingSafeEqual } from 'node:crypto';\n\nexport interface DurableJobPayloadIntegrity {\n version: 1;\n keyId: string;\n signature: string;\n}\n\nexport interface DurableJobPayloadSigner {\n readonly keyId: string;\n sign(payload: unknown): DurableJobPayloadIntegrity;\n verify(payload: unknown, integrity: DurableJobPayloadIntegrity): boolean;\n}\n\n/** Create a deterministic HMAC signer for JSON job payloads. The key is never persisted. */\nexport function createHmacDurableJobPayloadSigner(options: {\n keyId: string;\n key: string | Uint8Array;\n}): DurableJobPayloadSigner {\n if (!options.keyId || options.keyId.length > 256) {\n throw new Error(\n 'Durable job integrity keyId must contain 1-256 characters',\n );\n }\n const keyLength =\n typeof options.key === 'string'\n ? Buffer.byteLength(options.key)\n : options.key.byteLength;\n if (keyLength < 32) {\n throw new Error('Durable job integrity key must contain at least 32 bytes');\n }\n const signature = (payload: unknown) =>\n createHmac('sha256', options.key)\n .update(canonicalJson(payload))\n .digest('base64url');\n return Object.freeze({\n keyId: options.keyId,\n sign(payload: unknown): DurableJobPayloadIntegrity {\n return {\n version: 1,\n keyId: options.keyId,\n signature: signature(payload),\n };\n },\n verify(payload: unknown, integrity: DurableJobPayloadIntegrity): boolean {\n if (\n integrity?.version !== 1 ||\n integrity.keyId !== options.keyId ||\n typeof integrity.signature !== 'string'\n ) {\n return false;\n }\n const expected = Buffer.from(signature(payload));\n const actual = Buffer.from(integrity.signature);\n return (\n actual.length === expected.length && timingSafeEqual(actual, expected)\n );\n },\n });\n}\n\nfunction canonicalJson(value: unknown): string {\n // Jobs persist `args` as JSON. Normalize through that exact representation\n // before sorting keys so a value with JSON serialization (notably Date) is\n // signed identically before enqueue and after the worker reloads the row.\n let persisted: string | undefined;\n try {\n persisted = JSON.stringify(value);\n } catch {\n throw new Error('Durable job integrity payload must be acyclic JSON');\n }\n if (persisted === undefined) {\n throw new Error('Durable job integrity payload must be JSON-serializable');\n }\n\n const seen = new Set<object>();\n const canonicalize = (item: unknown, inArray = false): unknown => {\n if (\n item === null ||\n typeof item === 'string' ||\n typeof item === 'boolean'\n ) {\n return item;\n }\n if (typeof item === 'number') return Number.isFinite(item) ? item : null;\n if (\n item === undefined ||\n typeof item === 'function' ||\n typeof item === 'symbol'\n ) {\n return inArray ? null : undefined;\n }\n if (typeof item !== 'object' || seen.has(item)) {\n throw new Error('Durable job integrity payload must be acyclic JSON');\n }\n seen.add(item);\n if (Array.isArray(item)) {\n const result = item.map((entry) => canonicalize(entry, true));\n seen.delete(item);\n return result;\n }\n // JSON may contain an own `__proto__` property. A normal object would invoke\n // Object.prototype's legacy prototype setter here and omit that property\n // from the signed representation.\n const result: Record<string, unknown> = Object.create(null);\n for (const key of Object.keys(item as Record<string, unknown>).sort()) {\n const entry = canonicalize((item as Record<string, unknown>)[key]);\n if (entry !== undefined) result[key] = entry;\n }\n seen.delete(item);\n return result;\n };\n return JSON.stringify(canonicalize(JSON.parse(persisted)));\n}\n","// Self-register this package's manifest for consumers importing this module\n// directly. See __smrt-register__.ts (issue #1132).\nimport './__smrt-register__.js';\n\nimport { randomUUID } from 'node:crypto';\nimport {\n detectEngine,\n field,\n SmrtCollection,\n SmrtObject,\n smrt,\n} from '@happyvertical/smrt-core';\nimport {\n requireTenant,\n TenantScoped,\n tenantId,\n withTenant,\n} from '@happyvertical/smrt-tenancy';\nimport type { DatabaseInterface } from '@happyvertical/sql';\nimport { redactErrorForPersistence } from './error-redaction.js';\n\nconst MAX_OBSERVATION_VERSION = 2_147_483_647;\nconst MAX_FORGE_DURATION_MS = 2_147_483_647;\nconst MAX_DATE_TIMESTAMP_MS = 8_640_000_000_000_000;\n\ntype DatabaseWithConfig = DatabaseInterface & {\n config?: {\n type?: string;\n url?: string;\n };\n type?: string;\n};\n\nexport type ForgeDeliveryStatus =\n | 'pending'\n | 'leased'\n | 'retry'\n | 'completed'\n | 'dead_letter';\n\n/**\n * A provider-neutral observation emitted by a forge delivery adapter.\n *\n * `version` is a monotonically increasing provider/domain revision for one\n * `(projection, subjectKey)` pair. Projectors never infer issue semantics from\n * pull requests; applications choose both the projection and subject identity.\n */\nexport interface ForgeObservation<T = unknown> {\n projection: string;\n subjectKey: string;\n version: number;\n value: T;\n}\n\nexport interface ForgeProjectionContext {\n /** Transaction-scoped database. Projection writes must use this handle. */\n db: DatabaseInterface;\n tenantId: string;\n deliveryId: string;\n}\n\nexport interface ForgeProjector<T = unknown> {\n /**\n * Normalize a provider delivery into a tracker-independent observation.\n * Return null when the delivery is intentionally ignored.\n */\n observe(delivery: ForgeDelivery): Promise<ForgeObservation<T> | null>;\n /**\n * Apply the observation. The callback and checkpoint/delivery updates share\n * one database transaction.\n */\n project(\n observation: ForgeObservation<T>,\n context: ForgeProjectionContext,\n ): Promise<void>;\n}\n\nexport type ForgeProjectionAuditEvent =\n | {\n type: 'delivery.accepted' | 'delivery.duplicate';\n tenantId: string;\n deliveryId: string;\n provider: string;\n }\n | {\n type:\n | 'delivery.leased'\n | 'delivery.completed'\n | 'delivery.retry_scheduled'\n | 'delivery.dead_lettered'\n | 'delivery.replayed'\n | 'observation.stale';\n tenantId: string;\n deliveryId: string;\n attempt: number;\n };\n\nexport type ForgeProjectionAuditHook = (\n event: ForgeProjectionAuditEvent,\n) => void | Promise<void>;\n\n@smrt({\n tableName: '_smrt_forge_deliveries',\n conflictColumns: ['tenant_id', 'provider', 'delivery_id'],\n api: false,\n cli: false,\n mcp: false,\n // `claimReady()` scans two OR-branches every poll (#2364, epic #2382\n // finding A3): `status IN ('pending','retry') AND next_attempt_at <= ?`\n // (the common ready-to-run case) and `status = 'leased' AND\n // lease_expires_at < ?` (reclaiming an expired lease — also the predicate\n // of the lease-expiry-to-dead_letter sweep above it in the same method).\n // Neither branch is a prefix of the other, so both composites are\n // declared; PostgreSQL can combine them with a BitmapOr when planning the\n // OR. Roll this out with `smrt db:migrate --postgres-safe` (#2362), same\n // as `_smrt_jobs` above — deliveries are claimed continuously too.\n indexes: [\n {\n name: '_smrt_forge_deliveries_status_next_attempt_at_idx',\n columns: ['status', 'nextAttemptAt'],\n },\n {\n name: '_smrt_forge_deliveries_status_lease_expires_at_idx',\n columns: ['status', 'leaseExpiresAt'],\n },\n ],\n})\n@TenantScoped({ mode: 'required' })\nexport class ForgeDelivery extends SmrtObject { static __smrtPackage__ = \"@happyvertical/smrt-jobs\";\n @tenantId()\n tenantId: string = '';\n\n @field({ type: 'text', required: true, requiredFor: 'identity' })\n provider: string = '';\n\n @field({ type: 'text', required: true, requiredFor: 'identity' })\n deliveryId: string = '';\n\n @field({ type: 'text', nullable: true })\n installationKey: string | null = null;\n\n @field({ type: 'text', nullable: true })\n repositoryKey: string | null = null;\n\n @field({ type: 'text' })\n eventName: string = '';\n\n @field({ type: 'json' })\n payload: Record<string, unknown> = {};\n\n @field({ type: 'text', required: true, default: 'pending' })\n status: ForgeDeliveryStatus = 'pending';\n\n @field({ type: 'integer', required: true, default: 0 })\n attempts: number = 0;\n\n @field({ type: 'integer', required: true, default: 5 })\n maxAttempts: number = 5;\n\n @field({ type: 'datetime', required: true })\n receivedAt: Date = new Date();\n\n @field({ type: 'datetime', required: true })\n nextAttemptAt: Date = new Date();\n\n @field({ type: 'text', nullable: true })\n leaseOwner: string | null = null;\n\n @field({ type: 'text', nullable: true })\n leaseToken: string | null = null;\n\n @field({ type: 'datetime', nullable: true })\n leaseExpiresAt: Date | null = null;\n\n @field({ type: 'text', nullable: true })\n lastError: string | null = null;\n\n @field({ type: 'datetime', nullable: true })\n completedAt: Date | null = null;\n\n @field({ type: 'integer', required: true, default: 0 })\n replayCount: number = 0;\n}\n\n@smrt({\n tableName: '_smrt_forge_projection_checkpoints',\n conflictColumns: ['tenant_id', 'projection', 'subject_key'],\n api: false,\n cli: false,\n mcp: false,\n})\n@TenantScoped({ mode: 'required' })\nexport class ForgeProjectionCheckpoint extends SmrtObject { static __smrtPackage__ = \"@happyvertical/smrt-jobs\";\n @tenantId()\n tenantId: string = '';\n\n @field({ type: 'text', required: true, requiredFor: 'identity' })\n projection: string = '';\n\n @field({ type: 'text', required: true, requiredFor: 'identity' })\n subjectKey: string = '';\n\n // The current portable field contract persists this as a signed 32-bit\n // integer. `assertObservation()` enforces the matching public range.\n @field({ type: 'integer', required: true })\n observationVersion: number = 0;\n\n @field({ type: 'text' })\n deliveryId: string = '';\n\n @field({ type: 'datetime', required: true })\n observedAt: Date = new Date();\n}\n\nexport interface AcceptForgeDeliveryInput {\n provider: string;\n deliveryId: string;\n installationKey?: string | null;\n repositoryKey?: string | null;\n eventName: string;\n payload: Record<string, unknown>;\n maxAttempts?: number;\n receivedAt?: Date;\n}\n\nexport interface AcceptedForgeDelivery {\n delivery: ForgeDelivery;\n accepted: boolean;\n}\n\nexport interface ClaimForgeDeliveryOptions {\n workerId: string;\n leaseMs: number;\n now?: Date;\n /**\n * Claim only deliveries from these providers. Runtimes that share the inbox\n * with other projections must set it so each claims only its own\n * deliveries; omitted, every provider is claimable.\n */\n providers?: readonly string[];\n}\n\n/**\n * Durable provider delivery inbox.\n *\n * All tenant-facing operations require ambient tenant context. `claimReady`\n * is the sole cross-tenant worker scan and returns the captured tenant so the\n * runtime can restore it before normalization or projection.\n */\n@smrt({\n api: false,\n cli: false,\n mcp: false,\n})\nexport class ForgeDeliveryCollection extends SmrtCollection<ForgeDelivery> { static __smrtPackage__ = \"@happyvertical/smrt-jobs\";\n static readonly _itemClass = ForgeDelivery;\n\n async accept(\n input: AcceptForgeDeliveryInput,\n audit?: ForgeProjectionAuditHook,\n ): Promise<AcceptedForgeDelivery> {\n const tenant = requireTenant().tenantId;\n assertNonEmpty('provider', input.provider);\n assertNonEmpty('deliveryId', input.deliveryId);\n assertNonEmpty('eventName', input.eventName);\n\n const now = input.receivedAt ?? new Date();\n const id = randomUUID();\n const inserted = await this.db.query(\n `INSERT INTO _smrt_forge_deliveries (\n id, slug, context, tenant_id, provider, delivery_id, installation_key,\n repository_key, event_name, payload, status, attempts, max_attempts,\n received_at, next_attempt_at, replay_count, created_at, updated_at\n ) VALUES (?, ?, '', ?, ?, ?, ?, ?, ?, ?, 'pending', 0, ?, ?, ?, 0, ?, ?)\n ON CONFLICT (tenant_id, provider, delivery_id) DO NOTHING\n RETURNING id`,\n id,\n `${input.provider}-${input.deliveryId}`.slice(0, 255),\n tenant,\n input.provider,\n input.deliveryId,\n input.installationKey ?? null,\n input.repositoryKey ?? null,\n input.eventName,\n JSON.stringify(input.payload),\n clampMaxAttempts(input.maxAttempts ?? 5),\n now.toISOString(),\n now.toISOString(),\n now.toISOString(),\n now.toISOString(),\n );\n const accepted = inserted.rows.length === 1;\n // Read back through the tenant-scoped collection path, not raw SQL: the\n // tenancy interceptor applies the ambient tenant filter itself, so this\n // works under `rawQueryPolicy: 'throw'` without any bypass (#3100).\n const [delivery] = await this.list({\n where: {\n tenantId: tenant,\n provider: input.provider,\n deliveryId: input.deliveryId,\n },\n limit: 1,\n });\n if (!delivery) throw new Error('Forge delivery insert could not be read');\n await audit?.({\n type: accepted ? 'delivery.accepted' : 'delivery.duplicate',\n tenantId: tenant,\n deliveryId: delivery.deliveryId,\n provider: delivery.provider,\n });\n return { delivery, accepted };\n }\n\n async claimReady(\n options: ClaimForgeDeliveryOptions,\n audit?: ForgeProjectionAuditHook,\n ): Promise<ForgeDelivery | null> {\n assertFinitePositive('leaseMs', options.leaseMs);\n const now = options.now ?? new Date();\n const nowIso = now.toISOString();\n const leaseExpiresAt = tryAddDuration(now, options.leaseMs);\n if (!leaseExpiresAt) {\n throw new Error('leaseMs extends past the supported Date range');\n }\n const token = randomUUID();\n const isPostgres = getDatabaseEngine(this.db) === 'postgres';\n const lockClause = isPostgres ? ' FOR UPDATE SKIP LOCKED' : '';\n const providers = options.providers;\n if (providers !== undefined) {\n if (providers.length === 0) {\n throw new Error('providers must name at least one provider');\n }\n for (const provider of providers) assertNonEmpty('providers[]', provider);\n }\n const providerClause = providers\n ? ` AND provider IN (${providers.map(() => '?').join(', ')})`\n : '';\n const providerParams = providers ? [...providers] : [];\n\n // An expired final attempt cannot be safely re-run. Move it to the\n // operator-recoverable terminal state before selecting another candidate.\n await this.query(\n `UPDATE _smrt_forge_deliveries\n SET status = 'dead_letter',\n lease_owner = NULL,\n lease_token = NULL,\n lease_expires_at = NULL,\n last_error = 'worker lease expired',\n updated_at = ?\n WHERE status = 'leased'\n AND lease_expires_at < ?\n AND attempts >= max_attempts${providerClause}`,\n [nowIso, nowIso, ...providerParams],\n { allowRawOnTenantScoped: true },\n );\n\n const candidateSelect = `\n SELECT id AS claim_id\n FROM _smrt_forge_deliveries\n WHERE attempts < max_attempts${providerClause}\n AND (\n (status IN ('pending', 'retry') AND next_attempt_at <= ?)\n OR (status = 'leased' AND lease_expires_at < ?)\n )\n ORDER BY next_attempt_at ASC, received_at ASC, created_at ASC, id ASC\n LIMIT 1${lockClause}`;\n const candidateParams = [...providerParams, nowIso, nowIso];\n const setClause = `\n SET status = 'leased',\n attempts = attempts + 1,\n lease_owner = ?,\n lease_token = ?,\n lease_expires_at = ?,\n updated_at = ?`;\n const setParams = [options.workerId, token, leaseExpiresAt, nowIso];\n const stillClaimable = `(\n (status IN ('pending', 'retry') AND next_attempt_at <= ?)\n OR (status = 'leased' AND lease_expires_at < ?)\n )`;\n // PostgreSQL selects the candidate once in a MATERIALIZED CTE: an\n // `IN (SELECT … LIMIT 1 FOR UPDATE SKIP LOCKED)` subquery can be rescanned\n // per outer row by a nested-loop semi join, leasing several deliveries\n // under one token while only the first is returned (#3105, #3145).\n const claimed = isPostgres\n ? await this.query(\n `WITH claim_candidates AS MATERIALIZED (${candidateSelect})\n UPDATE _smrt_forge_deliveries${setClause}\n FROM claim_candidates\n WHERE _smrt_forge_deliveries.id = claim_candidates.claim_id\n AND ${stillClaimable}\n RETURNING _smrt_forge_deliveries.*`,\n [...candidateParams, ...setParams, nowIso, nowIso],\n { allowRawOnTenantScoped: true },\n )\n : await this.query(\n `UPDATE _smrt_forge_deliveries${setClause}\n WHERE id IN (${candidateSelect})\n AND ${stillClaimable}\n RETURNING *`,\n [...setParams, ...candidateParams, nowIso, nowIso],\n { allowRawOnTenantScoped: true },\n );\n const delivery = claimed[0] ?? null;\n if (delivery) {\n await withTenant({ tenantId: delivery.tenantId }, async () => {\n try {\n await audit?.({\n type: 'delivery.leased',\n tenantId: delivery.tenantId,\n deliveryId: delivery.deliveryId,\n attempt: delivery.attempts,\n });\n } catch {\n // The durable lease already committed. Observability failures must\n // not strand it or consume an attempt before its projector runs.\n }\n });\n }\n return delivery;\n }\n\n async replay(id: string, audit?: ForgeProjectionAuditHook): Promise<boolean> {\n const tenant = requireTenant().tenantId;\n const now = new Date().toISOString();\n const result = await this.db.query(\n `UPDATE _smrt_forge_deliveries\n SET status = 'pending',\n attempts = 0,\n next_attempt_at = ?,\n lease_owner = NULL,\n lease_token = NULL,\n lease_expires_at = NULL,\n last_error = NULL,\n completed_at = NULL,\n replay_count = replay_count + 1,\n updated_at = ?\n WHERE id = ?\n AND tenant_id = ?\n AND status = 'dead_letter'\n RETURNING delivery_id, replay_count`,\n now,\n now,\n id,\n tenant,\n );\n const replayed = result.rows.length === 1;\n if (replayed) {\n const row = result.rows[0] as {\n delivery_id: string;\n replay_count: number;\n };\n await audit?.({\n type: 'delivery.replayed',\n tenantId: tenant,\n deliveryId: row.delivery_id,\n attempt: Number(row.replay_count),\n });\n }\n return replayed;\n }\n}\n\nexport interface ForgeProjectionRuntimeOptions {\n db: DatabaseInterface;\n workerId: string;\n /** Claim only these providers' deliveries; see {@link ClaimForgeDeliveryOptions}. */\n providers?: readonly string[];\n leaseMs?: number;\n retryBaseMs?: number;\n retryMaxMs?: number;\n audit?: ForgeProjectionAuditHook;\n}\n\n/**\n * Claims and projects one delivery at a time.\n *\n * The ownership assertion, application projection, monotonic checkpoint and\n * inbox completion are one transaction. The initial no-op UPDATE takes a row\n * write lock, preventing an expired lease from being reclaimed while a valid\n * projection transaction is still in progress.\n */\nexport class ForgeProjectionRuntime {\n readonly db: DatabaseInterface;\n readonly workerId: string;\n readonly providers?: readonly string[];\n readonly leaseMs: number;\n readonly retryBaseMs: number;\n readonly retryMaxMs: number;\n readonly audit?: ForgeProjectionAuditHook;\n\n constructor(options: ForgeProjectionRuntimeOptions) {\n this.db = options.db;\n this.workerId = options.workerId;\n this.providers = options.providers;\n this.leaseMs = options.leaseMs ?? 30_000;\n this.retryBaseMs = options.retryBaseMs ?? 1_000;\n this.retryMaxMs = options.retryMaxMs ?? 300_000;\n assertFinitePositive('leaseMs', this.leaseMs);\n assertFiniteNonNegative('retryBaseMs', this.retryBaseMs);\n assertFiniteNonNegative('retryMaxMs', this.retryMaxMs);\n this.audit = options.audit;\n }\n\n async processNext(\n projector: ForgeProjector,\n options: { now?: Date } = {},\n ): Promise<ForgeDelivery | null> {\n const inbox = await ForgeDeliveryCollection.create({ db: this.db });\n const delivery = await inbox.claimReady(\n {\n workerId: this.workerId,\n leaseMs: this.leaseMs,\n now: options.now,\n providers: this.providers,\n },\n this.audit,\n );\n if (!delivery) return null;\n\n await withTenant({ tenantId: delivery.tenantId }, async () => {\n try {\n const observation = await projector.observe(delivery);\n await this.commitOwned(delivery, observation, projector, options.now);\n } catch (error) {\n await this.failOwned(delivery, error, options.now);\n }\n });\n return delivery;\n }\n\n private async commitOwned(\n delivery: ForgeDelivery,\n observation: ForgeObservation | null,\n projector: ForgeProjector,\n now = new Date(),\n ): Promise<void> {\n if (!this.db.transaction) {\n throw new Error(\n 'Forge projection requires a database adapter with transaction()',\n );\n }\n const nowIso = now.toISOString();\n let stale = false;\n await this.db.transaction(async (tx) => {\n const ownership = await tx.query(\n `UPDATE _smrt_forge_deliveries\n SET updated_at = updated_at\n WHERE id = ? AND tenant_id = ? AND status = 'leased'\n AND lease_token = ?\n AND lease_expires_at >= ?\n RETURNING id`,\n delivery.id,\n delivery.tenantId,\n delivery.leaseToken,\n nowIso,\n );\n if (ownership.rows.length !== 1) {\n throw new Error('Forge delivery lease ownership was lost');\n }\n\n if (observation) {\n assertObservation(observation);\n // Reserve the subject version before invoking application code. This\n // write serializes concurrent first-observation and update races; a\n // stale contender gets no RETURNING row and never applies side effects.\n const reserved = await tx.query(\n `INSERT INTO _smrt_forge_projection_checkpoints (\n id, slug, context, tenant_id, projection, subject_key,\n observation_version, delivery_id, observed_at, created_at,\n updated_at\n ) VALUES (?, ?, '', ?, ?, ?, ?, ?, ?, ?, ?)\n ON CONFLICT (tenant_id, projection, subject_key) DO UPDATE SET\n observation_version = excluded.observation_version,\n delivery_id = excluded.delivery_id,\n observed_at = excluded.observed_at,\n updated_at = excluded.updated_at\n WHERE _smrt_forge_projection_checkpoints.observation_version\n < excluded.observation_version\n RETURNING id`,\n randomUUID(),\n `${observation.projection}-${observation.subjectKey}`.slice(0, 255),\n delivery.tenantId,\n observation.projection,\n observation.subjectKey,\n observation.version,\n delivery.deliveryId,\n nowIso,\n nowIso,\n nowIso,\n );\n stale = reserved.rows.length === 0;\n if (!stale) {\n await projector.project(observation, {\n db: tx,\n tenantId: delivery.tenantId,\n deliveryId: delivery.deliveryId,\n });\n }\n }\n\n const completed = await tx.query(\n `UPDATE _smrt_forge_deliveries\n SET status = 'completed',\n completed_at = ?,\n lease_owner = NULL,\n lease_token = NULL,\n lease_expires_at = NULL,\n last_error = NULL,\n updated_at = ?\n WHERE id = ? AND tenant_id = ? AND status = 'leased'\n AND lease_token = ?\n AND lease_expires_at >= ?\n RETURNING id`,\n nowIso,\n nowIso,\n delivery.id,\n delivery.tenantId,\n delivery.leaseToken,\n nowIso,\n );\n if (completed.rows.length !== 1) {\n throw new Error('Forge delivery completion lost lease ownership');\n }\n });\n await this.audit?.({\n type: stale ? 'observation.stale' : 'delivery.completed',\n tenantId: delivery.tenantId,\n deliveryId: delivery.deliveryId,\n attempt: delivery.attempts,\n });\n }\n\n private async failOwned(\n delivery: ForgeDelivery,\n error: unknown,\n now = new Date(),\n ): Promise<void> {\n const terminal = delivery.attempts >= delivery.maxAttempts;\n const delay = Math.min(\n this.retryMaxMs,\n this.retryBaseMs * 2 ** Math.max(0, delivery.attempts - 1),\n );\n const retryAt = terminal ? now.toISOString() : tryAddDuration(now, delay);\n const scheduleOverflow = retryAt === null;\n const lastError = scheduleOverflow\n ? `${redactErrorForPersistence(error)}; retry schedule exceeds the supported Date range`\n : redactErrorForPersistence(error);\n const result = await this.db.query(\n `UPDATE _smrt_forge_deliveries\n SET status = ?,\n next_attempt_at = ?,\n lease_owner = NULL,\n lease_token = NULL,\n lease_expires_at = NULL,\n last_error = ?,\n updated_at = ?\n WHERE id = ? AND tenant_id = ? AND status = 'leased'\n AND lease_token = ?\n AND lease_expires_at >= ?\n RETURNING id`,\n terminal || scheduleOverflow ? 'dead_letter' : 'retry',\n retryAt ?? now.toISOString(),\n lastError,\n now.toISOString(),\n delivery.id,\n delivery.tenantId,\n delivery.leaseToken,\n now.toISOString(),\n );\n if (result.rows.length === 1) {\n await this.audit?.({\n type:\n terminal || scheduleOverflow\n ? 'delivery.dead_lettered'\n : 'delivery.retry_scheduled',\n tenantId: delivery.tenantId,\n deliveryId: delivery.deliveryId,\n attempt: delivery.attempts,\n });\n }\n }\n}\n\nfunction assertNonEmpty(name: string, value: string): void {\n if (value.trim().length === 0) throw new Error(`${name} must not be empty`);\n}\n\nfunction assertFinitePositive(name: string, value: number): void {\n if (!Number.isFinite(value) || value <= 0) {\n throw new Error(`${name} must be a finite positive number`);\n }\n}\n\nfunction assertFiniteNonNegative(name: string, value: number): void {\n if (!Number.isFinite(value) || value < 0) {\n throw new Error(`${name} must be a finite non-negative number`);\n }\n if (value > MAX_FORGE_DURATION_MS) {\n throw new Error(`${name} must not exceed ${MAX_FORGE_DURATION_MS}`);\n }\n}\n\nfunction tryAddDuration(now: Date, durationMs: number): string | null {\n const timestamp = now.getTime() + durationMs;\n if (\n !Number.isFinite(timestamp) ||\n Math.abs(timestamp) > MAX_DATE_TIMESTAMP_MS\n ) {\n return null;\n }\n return new Date(timestamp).toISOString();\n}\n\nfunction assertObservation(observation: ForgeObservation): void {\n assertNonEmpty('observation.projection', observation.projection);\n assertNonEmpty('observation.subjectKey', observation.subjectKey);\n if (\n !Number.isSafeInteger(observation.version) ||\n observation.version < 0 ||\n observation.version > MAX_OBSERVATION_VERSION\n ) {\n throw new Error(\n `observation.version must be an integer from 0 to ${MAX_OBSERVATION_VERSION}`,\n );\n }\n}\n\nfunction getDatabaseEngine(\n db: DatabaseInterface,\n): ReturnType<typeof detectEngine> {\n const dbWithConfig = db as DatabaseWithConfig;\n return detectEngine(\n db.url || dbWithConfig.config?.url || '',\n dbWithConfig.type || dbWithConfig.config?.type,\n );\n}\n\nfunction clampMaxAttempts(value: number): number {\n if (!Number.isSafeInteger(value) || value <= 0) {\n throw new Error('maxAttempts must be a positive safe integer');\n }\n return Math.min(value, 100);\n}\n","import type { JobStatus, SmrtJob, SmrtJobCollection } from './smrt-job.js';\n\n/**\n * Options for waiting on a job\n */\nexport interface WaitOptions {\n /** Maximum time to wait in milliseconds */\n timeout?: number;\n /** Polling interval in milliseconds */\n pollInterval?: number;\n}\n\n/**\n * Result from a completed job\n */\nexport interface JobResult<T = unknown> {\n /** Whether the job completed successfully */\n success: boolean;\n /** The result data (if successful) */\n result?: T;\n /** Error message (if failed) */\n error?: string;\n /** Pointer to where the full result is stored */\n resultPointer?: string | null;\n}\n\n/**\n * Handle for tracking and managing a background job\n *\n * This provides a convenient interface for:\n * - Checking job status\n * - Waiting for completion\n * - Canceling the job\n * - Retrying failed jobs\n */\nexport class JobHandle<T = unknown> {\n private readonly collection: SmrtJobCollection;\n\n constructor(\n public readonly id: string,\n collection: SmrtJobCollection,\n ) {\n this.collection = collection;\n }\n\n /**\n * Get the current job status\n */\n async status(): Promise<JobStatus> {\n const job = await this.getJob();\n return job.status;\n }\n\n /**\n * Get the full job object\n */\n async getJob(): Promise<SmrtJob> {\n const job = await this.collection.get({ id: this.id });\n if (!job) {\n throw new Error(`Job not found: ${this.id}`);\n }\n return job;\n }\n\n /**\n * Wait for the job to complete\n *\n * @param options - Wait configuration\n * @returns The job result\n * @throws Error if the job fails or times out\n */\n async wait(options: WaitOptions = {}): Promise<JobResult<T>> {\n const { timeout = 60000, pollInterval = 100 } = options;\n const startTime = Date.now();\n\n while (true) {\n const job = await this.getJob();\n\n if (job.status === 'completed') {\n return {\n success: true,\n resultPointer: job.resultPointer,\n };\n }\n\n if (job.status === 'failed') {\n return {\n success: false,\n error: job.lastError ?? 'Job failed',\n };\n }\n\n if (job.status === 'cancelled') {\n return {\n success: false,\n error: 'Job was cancelled',\n };\n }\n\n // Check timeout\n if (Date.now() - startTime >= timeout) {\n throw new Error(`Timeout waiting for job ${this.id}`);\n }\n\n // Wait before next poll\n await new Promise((resolve) => setTimeout(resolve, pollInterval));\n }\n }\n\n /**\n * Cancel the job\n */\n async cancel(): Promise<void> {\n const job = await this.getJob();\n await job.cancel();\n }\n\n /**\n * Retry a failed job\n */\n async retry(): Promise<void> {\n const job = await this.getJob();\n await job.retry();\n }\n\n /**\n * Check if the job is still running\n */\n async isRunning(): Promise<boolean> {\n const status = await this.status();\n return status === 'pending' || status === 'running';\n }\n\n /**\n * Check if the job has completed (successfully or not)\n */\n async isDone(): Promise<boolean> {\n const status = await this.status();\n return (\n status === 'completed' || status === 'failed' || status === 'cancelled'\n );\n }\n}\n\nexport default JobHandle;\n","import type { RetryStrategy, RetryStrategyConfig } from '@happyvertical/jobs';\nimport { clampRetries, DEFAULT_TENANT_JOB_CAP } from './background-policy.js';\nimport { JobHandle } from './job-handle.js';\nimport type { SmrtJobCollection, TimeoutBehavior } from './smrt-job.js';\n\n/**\n * Priority levels for jobs\n */\nexport type Priority = 'critical' | 'high' | 'normal' | 'low' | number;\n\n/**\n * Convert priority to numeric value\n */\nexport function priorityToNumber(priority: Priority): number {\n if (typeof priority === 'number') return priority;\n switch (priority) {\n case 'critical':\n return 100;\n case 'high':\n return 75;\n case 'normal':\n return 50;\n case 'low':\n return 25;\n default:\n return 50;\n }\n}\n\n/**\n * Parse delay string to milliseconds\n */\nexport function parseDelay(delay: string | number): number {\n if (typeof delay === 'number') {\n // Guard against NaN/Infinity: a non-finite delay flows into\n // `new Date(Date.now() + delay)`, persisting an `Invalid Date` `runAt`\n // that the claim query can never match (S3 in the #1401 review).\n if (!Number.isFinite(delay)) {\n throw new Error(`Invalid delay value: ${delay}`);\n }\n return delay;\n }\n\n const match = delay.match(/^(\\d+)(ms|s|m|h|d)?$/);\n if (!match) {\n throw new Error(`Invalid delay format: ${delay}`);\n }\n\n const value = parseInt(match[1], 10);\n const unit = match[2] || 'ms';\n\n switch (unit) {\n case 'ms':\n return value;\n case 's':\n return value * 1000;\n case 'm':\n return value * 60 * 1000;\n case 'h':\n return value * 60 * 60 * 1000;\n case 'd':\n return value * 24 * 60 * 60 * 1000;\n default:\n return value;\n }\n}\n\n/**\n * Fluent builder for creating background jobs\n *\n * Example:\n * ```typescript\n * const handle = await doc.background('generateSummary', { format: 'md' })\n * .delay('5m')\n * .retries(5)\n * .priority('high')\n * .queue('summaries')\n * .timeout(300000)\n * .enqueue();\n * ```\n */\nexport class JobBuilder<T = unknown> {\n private _queue: string = 'default';\n private _delay: number = 0;\n private _retries: number = 3;\n private _priority: number = 50;\n private _timeout: number = 300000;\n private _timeoutBehavior: TimeoutBehavior = 'fail';\n private _retryStrategy?: RetryStrategy;\n private _tenantJobCap: number = DEFAULT_TENANT_JOB_CAP;\n\n constructor(\n private readonly objectType: string,\n private readonly objectId: string | null,\n private readonly method: string,\n private readonly args: Record<string, unknown>,\n private readonly collection: SmrtJobCollection,\n ) {}\n\n /**\n * Set the queue name\n */\n queue(name: string): this {\n this._queue = name;\n return this;\n }\n\n /**\n * Set a delay before the job runs\n * @param delay - Delay as milliseconds or string like '5m', '1h', '30s'\n */\n delay(delay: string | number): this {\n this._delay = parseDelay(delay);\n return this;\n }\n\n /**\n * Set when the job should run\n */\n runAt(date: Date): this {\n this._delay = date.getTime() - Date.now();\n return this;\n }\n\n /**\n * Set the maximum number of retry attempts.\n *\n * Clamped to {@link MAX_JOB_RETRIES} so a misconfigured caller cannot pin a\n * worker on a poison job indefinitely (S5 audit #1402).\n */\n retries(count: number): this {\n this._retries = clampRetries(count);\n return this;\n }\n\n /**\n * Set the retry strategy\n */\n retryStrategy(strategy: RetryStrategy): this {\n this._retryStrategy = strategy;\n return this;\n }\n\n /**\n * Set the job priority\n */\n priority(level: Priority): this {\n this._priority = priorityToNumber(level);\n return this;\n }\n\n /**\n * Set the job timeout in milliseconds\n */\n timeout(ms: number): this {\n this._timeout = ms;\n return this;\n }\n\n /**\n * Set what happens when the job times out\n */\n timeoutBehavior(behavior: TimeoutBehavior): this {\n this._timeoutBehavior = behavior;\n return this;\n }\n\n /**\n * Override the per-tenant in-flight job cap for this enqueue.\n *\n * Defaults to {@link DEFAULT_TENANT_JOB_CAP}. Pass `0` (or a negative value)\n * to disable the cap for trusted internal callers (S5 audit #1402).\n */\n tenantJobCap(max: number): this {\n this._tenantJobCap = max;\n return this;\n }\n\n /**\n * Enqueue the job and return a handle\n */\n async enqueue(): Promise<JobHandle<T>> {\n const runAt = new Date(Date.now() + this._delay);\n\n const strategy =\n this._retryStrategy ??\n (await import('@happyvertical/jobs')).exponential();\n\n const retryConfig: RetryStrategyConfig =\n 'toConfig' in strategy\n ? strategy.toConfig()\n : (strategy as RetryStrategyConfig);\n\n // Route through the collection's single creation path so the per-tenant\n // in-flight cap and the retry ceiling are enforced in one place, shared with\n // the ScheduleRunner (S5 audit #1402). The cap applies to the ambient tenant\n // (resolved inside enqueueJob); global (no-context) jobs are exempt.\n const job = await this.collection.enqueueJob(\n {\n queue: this._queue,\n objectType: this.objectType,\n objectId: this.objectId,\n method: this.method,\n args: this.args,\n runAt,\n priority: this._priority,\n maxAttempts: this._retries,\n timeout: this._timeout,\n timeoutBehavior: this._timeoutBehavior,\n retryStrategy: retryConfig,\n },\n { tenantJobCap: this._tenantJobCap },\n );\n\n const jobId = job.id;\n if (!jobId) {\n throw new Error('Job was created but has no ID');\n }\n\n return new JobHandle<T>(jobId, this.collection);\n }\n}\n\nexport default JobBuilder;\n","import {\n ObjectRegistry,\n type SmrtObject,\n type SmrtObjectOptions,\n} from '@happyvertical/smrt-core';\nimport type { DatabaseInterface } from '@happyvertical/sql';\nimport {\n JobBuilder,\n type Priority,\n parseDelay,\n priorityToNumber,\n} from './job-builder.js';\nimport type { JobHandle } from './job-handle.js';\nimport { SmrtJobCollection } from './smrt-job.js';\n\n/**\n * Options for the simple .bg() method\n */\nexport interface BgOptions {\n /** Queue name */\n queue?: string;\n /** Priority level */\n priority?: 'critical' | 'high' | 'normal' | 'low' | number;\n /** Delay before running (ms or string like '5m') */\n delay?: string | number;\n /** Maximum retries */\n retries?: number;\n /** Timeout in milliseconds */\n timeout?: number;\n}\n\n/**\n * Type for the extended SmrtObject with background job methods\n */\nexport interface BackgroundCapable {\n /**\n * Simple background job submission\n *\n * @param method - Method name to invoke\n * @param args - Arguments to pass to the method\n * @param options - Job options\n * @returns JobHandle for tracking the job\n *\n * @example\n * const handle = await doc.bg('generateSummary', { format: 'md' });\n */\n bg<T = unknown>(\n method: string,\n args?: Record<string, unknown>,\n options?: BgOptions,\n ): Promise<JobHandle<T>>;\n\n /**\n * Fluent job builder for advanced options\n *\n * @param method - Method name to invoke\n * @param args - Arguments to pass to the method\n * @returns JobBuilder for fluent configuration\n *\n * @example\n * const handle = await doc.background('generateSummary', { format: 'md' })\n * .delay('5m')\n * .retries(5)\n * .priority('high')\n * .enqueue();\n */\n background<T = unknown>(\n method: string,\n args?: Record<string, unknown>,\n ): JobBuilder<T>;\n}\n\n// Cache for job collections per database\nconst collectionCache = new WeakMap<DatabaseInterface, SmrtJobCollection>();\n\n/**\n * Get or create a job collection for the given database\n */\nasync function getJobCollection(\n db: DatabaseInterface,\n): Promise<SmrtJobCollection> {\n let collection = collectionCache.get(db);\n if (!collection) {\n collection = await SmrtJobCollection.create({\n db: { type: 'sqlite', url: ':memory:' }, // Placeholder\n });\n // Override internal db reference\n (collection as unknown as { _db: DatabaseInterface })._db = db;\n collectionCache.set(db, collection);\n }\n return collection;\n}\n\nfunction getObjectTypeName(instance: SmrtObject): string {\n const metaType = (instance as { _meta_type?: unknown })._meta_type;\n if (typeof metaType === 'string' && metaType.length > 0) {\n return metaType;\n }\n\n const className = instance.constructor.name;\n return ObjectRegistry.getClass(className)?.qualifiedName || className;\n}\n\n// Type for a SmrtObject constructor. `never[]` (not `any[]`) satisfies\n// noExplicitAny while preserving assignability: constructor parameters are\n// checked contravariantly under strictFunctionTypes, and `never` (the bottom\n// type) is assignable to any concrete parameter type, so a typed-options\n// constructor like `new (options?: SmrtObjectOptions) => Doc` still satisfies\n// the constraint — `unknown[]` would NOT, since `unknown` is not assignable to\n// `SmrtObjectOptions`, breaking the documented `withBackgroundJobs(Document)`\n// API for consumers.\ntype SmrtObjectConstructor = new (...args: never[]) => SmrtObject;\ntype BackgroundCapableConstructor<T extends SmrtObjectConstructor> = {\n new (...args: ConstructorParameters<T>): InstanceType<T> & BackgroundCapable;\n} & T;\n\n// Compile-time regression guard (#1658, PR #1658): a typed-options SmrtObject\n// subclass constructor — the documented `withBackgroundJobs(Document)` pattern,\n// where a model's ctor is `(options?: SomeOptions)` — MUST satisfy the\n// constraint. A `unknown[]` rest param (instead of `never[]`) makes this\n// resolve to `false` and fails the build, since `unknown` is not assignable to\n// the typed options parameter. Keep this guard in production source so the\n// published constructor declaration stays checked during builds as well.\ntype AssertTrue<T extends true> = T;\ntype _TypedOptionsCtorStaysAssignable = AssertTrue<\n (new (\n options?: SmrtObjectOptions,\n ) => SmrtObject) extends SmrtObjectConstructor\n ? true\n : false\n>;\n\nfunction requireObjectDb(instance: SmrtObject): DatabaseInterface {\n const db = (instance as unknown as { _db?: DatabaseInterface })._db;\n if (!db) {\n throw new Error('Object not initialized. Call initialize() first.');\n }\n\n return db;\n}\n\nasync function bgImpl<R = unknown>(\n this: SmrtObject,\n method: string,\n args: Record<string, unknown> = {},\n options: BgOptions = {},\n): Promise<JobHandle<R>> {\n const db = requireObjectDb(this);\n const collection = await getJobCollection(db);\n const builder = new JobBuilder<R>(\n getObjectTypeName(this),\n this.id ?? null,\n method,\n args,\n collection,\n );\n\n if (options.queue) builder.queue(options.queue);\n if (options.priority) builder.priority(options.priority);\n if (options.delay) builder.delay(options.delay);\n if (options.retries !== undefined) builder.retries(options.retries);\n if (options.timeout) builder.timeout(options.timeout);\n\n return builder.enqueue();\n}\n\nfunction backgroundImpl<R = unknown>(\n this: SmrtObject,\n method: string,\n args: Record<string, unknown> = {},\n): JobBuilder<R> {\n const db = requireObjectDb(this);\n const objectType = getObjectTypeName(this);\n const objectId = this.id ?? null;\n\n // Create a proxy builder that defers collection access until enqueue().\n const lazyBuilder = {\n _queue: 'default',\n _delay: 0,\n _retries: 3,\n _priority: 50,\n _timeout: 300000,\n _timeoutBehavior: 'fail' as 'fail' | 'kill' | 'warn',\n _retryStrategy: null as unknown,\n // `undefined` => fall through to JobBuilder's DEFAULT_TENANT_JOB_CAP. A\n // caller can override (incl. `0` to disable) via tenantJobCap() below.\n _tenantJobCap: undefined as number | undefined,\n\n queue(name: string) {\n this._queue = name;\n return this;\n },\n delay(d: string | number) {\n this._delay = parseDelay(d);\n return this;\n },\n runAt(date: Date) {\n this._delay = date.getTime() - Date.now();\n return this;\n },\n retries(count: number) {\n this._retries = count;\n return this;\n },\n retryStrategy(strategy: unknown) {\n this._retryStrategy = strategy;\n return this;\n },\n priority(level: Priority) {\n this._priority = priorityToNumber(level);\n return this;\n },\n timeout(ms: number) {\n this._timeout = ms;\n return this;\n },\n timeoutBehavior(behavior: 'fail' | 'kill' | 'warn') {\n this._timeoutBehavior = behavior;\n return this;\n },\n tenantJobCap(max: number) {\n this._tenantJobCap = max;\n return this;\n },\n async enqueue(): Promise<JobHandle<R>> {\n const collection = await getJobCollection(db);\n const builder = new JobBuilder<R>(\n objectType,\n objectId,\n method,\n args,\n collection,\n );\n\n builder.queue(this._queue);\n builder.delay(this._delay);\n builder.retries(this._retries);\n builder.priority(this._priority);\n builder.timeout(this._timeout);\n builder.timeoutBehavior(this._timeoutBehavior);\n // Only forward an explicit override; leaving it unset preserves the\n // JobBuilder default (DEFAULT_TENANT_JOB_CAP).\n if (this._tenantJobCap !== undefined) {\n builder.tenantJobCap(this._tenantJobCap);\n }\n\n if (this._retryStrategy) {\n builder.retryStrategy(\n this._retryStrategy as Parameters<typeof builder.retryStrategy>[0],\n );\n }\n\n return builder.enqueue();\n },\n };\n\n return lazyBuilder as unknown as JobBuilder<R>;\n}\n\n/**\n * Extend a SmrtObject class with background job methods\n *\n * @param BaseClass - The SmrtObject class to extend\n * @returns Extended class with .bg() and .background() methods\n *\n * @example\n * const BackgroundDocument = withBackgroundJobs(Document);\n * const doc = new BackgroundDocument({ ... });\n * const handle = await doc.bg('generateSummary', { format: 'md' });\n */\nexport function withBackgroundJobs<T extends SmrtObjectConstructor>(\n BaseClass: T,\n): BackgroundCapableConstructor<T> {\n const prototype = BaseClass.prototype as SmrtObject &\n Partial<BackgroundCapable>;\n\n if (typeof prototype.bg !== 'function') {\n Object.defineProperty(prototype, 'bg', {\n value: bgImpl,\n writable: true,\n configurable: true,\n });\n }\n\n if (typeof prototype.background !== 'function') {\n Object.defineProperty(prototype, 'background', {\n value: backgroundImpl,\n writable: true,\n configurable: true,\n });\n }\n\n return BaseClass as BackgroundCapableConstructor<T>;\n}\n\nexport default withBackgroundJobs;\n","import type {\n DurableJobPayloadIntegrity,\n DurableJobPayloadSigner,\n} from './durable-payload-integrity.js';\n\n/** Durable, versioned requirement persisted in AgentSchedule.methodArgs. */\nexport interface ScheduleAdmissionPolicy {\n version: 1;\n requireIntegrity: true;\n queue: string;\n keyId: string;\n}\n\n/** Absent policy preserves legacy behavior; any malformed present policy fails closed. */\nexport function getScheduleAdmissionPolicy(\n args: unknown,\n): ScheduleAdmissionPolicy | null {\n if (typeof args === 'string') args = JSON.parse(args);\n if (!record(args))\n throw new TypeError('Schedule method_args must be a JSON object');\n if (!Object.hasOwn(args, '_scheduleAdmissionPolicy')) return null;\n const value = args._scheduleAdmissionPolicy;\n if (\n !record(value) ||\n Object.keys(value).sort().join(',') !==\n 'keyId,queue,requireIntegrity,version' ||\n value.version !== 1 ||\n value.requireIntegrity !== true ||\n typeof value.queue !== 'string' ||\n !value.queue.trim() ||\n typeof value.keyId !== 'string' ||\n !value.keyId.trim() ||\n value.keyId.length > 256\n ) {\n throw new TypeError('Unsupported or malformed schedule admission policy');\n }\n return {\n version: 1,\n requireIntegrity: true,\n queue: value.queue,\n keyId: value.keyId,\n };\n}\n\n/** Purpose-separated, immutable JSON identity of one scheduler admission. */\nexport interface ScheduleAdmissionPayload {\n purpose: 'smrt.schedule-admission';\n version: 1;\n keyId: string;\n jobId: string;\n tenantId: string | null;\n scheduleId: string;\n scheduledFor: string;\n queue: string;\n objectType: string;\n objectId: string | null;\n method: string;\n args: Record<string, unknown>;\n}\n\nfunction record(value: unknown): value is Record<string, unknown> {\n if (!value || typeof value !== 'object' || Array.isArray(value)) return false;\n const prototype = Object.getPrototypeOf(value);\n return prototype === Object.prototype || prototype === null;\n}\n\nfunction identity(value: unknown, name: string): string {\n if (typeof value !== 'string' || !value.trim()) {\n throw new TypeError(`Schedule admission requires ${name}`);\n }\n return value;\n}\n\n/**\n * Build the public signature payload from an authoritative persisted job row.\n *\n * This pure helper never signs or acquires a key. Only `_scheduleAdmission` is\n * omitted; every other persisted argument, including constructor/static consent\n * metadata, participates. Lifecycle fields may change during a legitimate retry.\n * Malformed identities or noncanonical UTC occurrence metadata throw.\n */\nexport function getScheduleAdmissionPayload(\n job: unknown,\n keyId: string,\n): ScheduleAdmissionPayload {\n if (!job || typeof job !== 'object') {\n throw new TypeError('Schedule admission requires a job');\n }\n const row = job as Record<string, unknown>;\n if (!record(row.args)) {\n throw new TypeError('Schedule admission requires JSON object arguments');\n }\n const scheduledFor = identity(row.args._scheduledFor, 'scheduledFor');\n const epoch = Date.parse(scheduledFor);\n if (\n !Number.isFinite(epoch) ||\n new Date(epoch).toISOString() !== scheduledFor\n ) {\n throw new TypeError(\n 'Schedule admission requires canonical UTC scheduledFor',\n );\n }\n const signatureKey = identity(keyId, 'keyId');\n if (signatureKey.length > 256) throw new TypeError('Invalid admission keyId');\n const policy = getScheduleAdmissionPolicy(row.args);\n if (policy && (policy.queue !== row.queue || policy.keyId !== signatureKey)) {\n throw new TypeError('Schedule admission does not match its durable policy');\n }\n const { _scheduleAdmission: _, ...argumentsWithoutSignature } = row.args;\n // Match the representation actually stored as JSON, preserving own __proto__\n // keys and Date serialization. Never retain a mutable reference to caller args.\n const args = JSON.parse(JSON.stringify(argumentsWithoutSignature)) as Record<\n string,\n unknown\n >;\n return {\n purpose: 'smrt.schedule-admission',\n version: 1,\n keyId: signatureKey,\n jobId: identity(row.id, 'jobId'),\n tenantId: row.tenantId === null ? null : identity(row.tenantId, 'tenantId'),\n scheduleId: identity(row.args._scheduleId, 'scheduleId'),\n scheduledFor,\n queue: identity(row.queue, 'queue'),\n objectType: identity(row.objectType, 'objectType'),\n objectId: row.objectId === null ? null : identity(row.objectId, 'objectId'),\n method: identity(row.method, 'method'),\n args,\n };\n}\n\n/**\n * Verify one exact admitted job, failing closed on missing/unknown metadata.\n *\n * `signer.verify` may be a trusted keyring retaining old verification keys while\n * `signer.keyId` selects a new minting key. Unknown or retired keys must deny.\n * A valid signature proves admission, never current user authority, deduplication\n * or exactly-once execution. No protection is claimed against code holding keys.\n */\nexport function verifyScheduleAdmission(\n job: unknown,\n signer: DurableJobPayloadSigner,\n): boolean {\n try {\n if (!job || typeof job !== 'object') return false;\n const args = (job as Record<string, unknown>).args;\n if (!record(args)) return false;\n const integrity = args._scheduleAdmission;\n if (\n !record(integrity) ||\n Object.keys(integrity).length !== 3 ||\n !['version', 'keyId', 'signature'].every((key) =>\n Object.hasOwn(integrity, key),\n ) ||\n integrity.version !== 1 ||\n typeof integrity.keyId !== 'string' ||\n !integrity.keyId.trim() ||\n integrity.keyId.length > 256 ||\n typeof integrity.signature !== 'string' ||\n !integrity.signature.trim()\n ) {\n return false;\n }\n return (\n signer.verify(\n getScheduleAdmissionPayload(job, integrity.keyId),\n integrity as unknown as DurableJobPayloadIntegrity,\n ) === true\n );\n } catch {\n return false;\n }\n}\n","import { EventEmitter } from 'node:events';\nimport { createLogger } from '@happyvertical/logger';\nimport {\n assertDatabaseMigratedForBuild,\n ObjectRegistry,\n} from '@happyvertical/smrt-core';\nimport type { DatabaseInterface } from '@happyvertical/sql';\nimport { createId } from '@happyvertical/utils';\nimport type { DurableJobPayloadSigner } from './durable-payload-integrity.js';\nimport {\n redactErrorForPersistence,\n redactErrorMessage,\n} from './error-redaction.js';\nimport {\n getScheduleAdmissionPayload,\n getScheduleAdmissionPolicy,\n verifyScheduleAdmission,\n} from './schedule-admission.js';\nimport { countScheduleJobs, SmrtJobCollection } from './smrt-job.js';\nimport { DEFAULT_TASK_HEARTBEAT_INTERVAL_MS } from './stale-recovery.js';\n\n/** A blocked host must not consume or alter a protected schedule. */\nclass ScheduleAdmissionBlockedError extends Error {}\n\n/**\n * ScheduleRunner configuration\n */\n/**\n * Queue that {@link ScheduleRunner} enqueues triggered schedules to. A task\n * worker must poll it (alongside `default`) or scheduled jobs stay `pending`\n * (#3141).\n */\nexport const SCHEDULED_JOB_QUEUE = 'agents';\n\nexport interface ScheduleRunnerConfig {\n /** Runner ID (auto-generated if not provided) */\n id?: string;\n /** Polling interval in milliseconds (default: 60000 - 1 minute) */\n pollInterval?: number;\n /** Maximum schedules to process per poll */\n batchSize?: number;\n /** Trusted host signer for exact occurrence/job integrity; null preserves unsigned behavior. */\n occurrenceSigner?: DurableJobPayloadSigner | null;\n /** Exact registered agent types this host may admit; empty means none. */\n agentTypes?: readonly string[];\n /** Tenant identities this host may admit; null selects global schedules. */\n tenantIds?: readonly (string | null)[];\n /** Queue consumed by this host's task worker (default: agents). */\n queue?: string;\n /**\n * @deprecated No longer used. Slot reconciliation keys on worker liveness\n * (the `_smrt_workers` lease), not per-job heartbeat staleness (#1474).\n */\n staleJobThresholdMs?: number;\n /**\n * @deprecated No longer used. See {@link staleJobThresholdMs}.\n */\n taskHeartbeatInterval?: number;\n}\n\n/**\n * ScheduleRunner events\n */\nexport interface ScheduleRunnerEvents {\n 'schedule:blocked': (diagnostic: {\n scheduleId: string;\n reason: string;\n }) => void;\n 'schedule:triggered': (schedule: ScheduleInfo) => void;\n 'schedule:error': (schedule: ScheduleInfo, error: Error) => void;\n 'schedule:completed': (scheduleId: string) => void;\n 'schedule:failed': (scheduleId: string, error: string) => void;\n 'runner:started': () => void;\n 'runner:stopped': () => void;\n 'runner:error': (error: Error) => void;\n}\n\n/**\n * Schedule info for events\n */\nexport interface ScheduleInfo {\n id: string;\n agentType: string;\n agentId: string | null;\n cron: string;\n}\n\n/**\n * Default configuration\n */\ntype ResolvedScheduleRunnerConfig = Required<\n Omit<ScheduleRunnerConfig, 'agentTypes' | 'tenantIds'>\n> &\n Pick<ScheduleRunnerConfig, 'agentTypes' | 'tenantIds'>;\n\nconst DEFAULT_CONFIG: ResolvedScheduleRunnerConfig = {\n id: '',\n pollInterval: 60000, // 1 minute\n batchSize: 50,\n occurrenceSigner: null,\n queue: SCHEDULED_JOB_QUEUE,\n staleJobThresholdMs: 90000,\n taskHeartbeatInterval: DEFAULT_TASK_HEARTBEAT_INTERVAL_MS,\n};\n\n/**\n * ScheduleRunner polls for due agent schedules and creates jobs for them\n *\n * This runner works in conjunction with TaskRunner:\n * 1. ScheduleRunner checks for due schedules based on cron expressions\n * 2. When a schedule is due, it creates a SmrtJob for the agent\n * 3. TaskRunner picks up and executes the job\n * 4. On job completion/failure, call handleJobCompletion() to update the schedule\n *\n * @example\n * ```typescript\n * const scheduleRunner = new ScheduleRunner({ pollInterval: 30000 });\n * await scheduleRunner.initialize(db);\n * await scheduleRunner.start();\n *\n * // Wire up TaskRunner events to update schedule state\n * taskRunner.on('job:completed', (job) => {\n * const scheduleId = job.args?._scheduleId;\n * if (scheduleId) scheduleRunner.handleJobCompletion(scheduleId, true);\n * });\n * taskRunner.on('job:failed', (job, error) => {\n * const scheduleId = job.args?._scheduleId;\n * if (scheduleId) scheduleRunner.handleJobCompletion(scheduleId, false, error.message);\n * });\n *\n * // Graceful shutdown\n * process.on('SIGTERM', () => scheduleRunner.stop());\n * ```\n */\nexport class ScheduleRunner extends EventEmitter {\n /** Public contracts hosts may require before admitting enabled schedules. */\n static readonly capabilities = Object.freeze({\n atomicOccurrences: true,\n scopedAdmission: true,\n drain: true,\n occurrenceIntegrity: true,\n requiredOccurrenceIntegrity: true,\n } as const);\n readonly id: string;\n private readonly config: ResolvedScheduleRunnerConfig;\n private jobCollection: SmrtJobCollection | null = null;\n private running = false;\n private pollTimer: NodeJS.Timeout | null = null;\n private pollInFlight: Promise<void> | null = null;\n private stopping: Promise<void> | null = null;\n private db: DatabaseInterface | null = null;\n private logger = createLogger(true);\n\n constructor(config: ScheduleRunnerConfig = {}) {\n super();\n this.config = {\n ...DEFAULT_CONFIG,\n ...config,\n id: config.id || `schedule_${createId().slice(0, 8)}`,\n };\n this.id = this.config.id;\n const signer = this.config.occurrenceSigner;\n if (\n signer != null &&\n (typeof signer.keyId !== 'string' ||\n !signer.keyId.trim() ||\n signer.keyId.length > 256 ||\n typeof signer.sign !== 'function' ||\n typeof signer.verify !== 'function')\n ) {\n throw new TypeError(\n 'occurrenceSigner must be a trusted host signer with a current keyId',\n );\n }\n if (\n !Number.isInteger(this.config.batchSize) ||\n this.config.batchSize <= 0\n ) {\n throw new TypeError('batchSize must be a positive integer');\n }\n if (\n !Number.isFinite(this.config.pollInterval) ||\n this.config.pollInterval <= 0 ||\n this.config.pollInterval > 2_147_483_647\n ) {\n throw new TypeError(\n 'pollInterval must be a finite positive Node timer interval',\n );\n }\n if (typeof this.config.queue !== 'string' || !this.config.queue.trim())\n throw new TypeError('queue must be nonblank');\n for (const values of [this.config.agentTypes, this.config.tenantIds]) {\n if (\n values !== undefined &&\n (!Array.isArray(values) ||\n values.some(\n (value) =>\n value !== null && (typeof value !== 'string' || !value.trim()),\n ))\n ) {\n throw new TypeError(\n 'ScheduleRunner scopes must contain nonblank identities',\n );\n }\n }\n if (this.config.agentTypes?.some((value) => value == null))\n throw new TypeError('agentTypes cannot contain null');\n if (this.config.agentTypes)\n this.config.agentTypes = [...this.config.agentTypes];\n if (this.config.tenantIds)\n this.config.tenantIds = [...this.config.tenantIds];\n }\n\n private scheduleScope(): { sql: string; params: unknown[] } {\n const terms: string[] = [];\n const params: unknown[] = [];\n if (this.config.agentTypes !== undefined) {\n terms.push(\n this.config.agentTypes.length\n ? `agent_type IN (${this.config.agentTypes.map(() => '?').join(', ')})`\n : '1 = 0',\n );\n params.push(...this.config.agentTypes);\n }\n if (this.config.tenantIds !== undefined) {\n const tenants = this.config.tenantIds.filter(\n (id): id is string => id !== null,\n );\n const parts: string[] = [];\n if (tenants.length)\n parts.push(`tenant_id IN (${tenants.map(() => '?').join(', ')})`);\n if (this.config.tenantIds.includes(null)) parts.push('tenant_id IS NULL');\n terms.push(parts.length ? `(${parts.join(' OR ')})` : '1 = 0');\n params.push(...tenants);\n }\n return { sql: terms.length ? ` AND ${terms.join(' AND ')}` : '', params };\n }\n\n /**\n * Initialize the runner with database connection\n */\n async initialize(db: DatabaseInterface): Promise<void> {\n this.db = db;\n this.jobCollection = await SmrtJobCollection.create({ db });\n }\n\n /**\n * Start processing schedules\n */\n async start(): Promise<void> {\n if (this.stopping) await this.stopping;\n if (this.running) return;\n if (!this.db) {\n throw new Error(\n 'ScheduleRunner not initialized. Call initialize() first.',\n );\n }\n\n if (!this.db.transaction) {\n throw new Error('ScheduleRunner requires transaction support');\n }\n await assertDatabaseMigratedForBuild(this.db);\n this.running = true;\n\n // Start polling loop\n this.startPolling();\n\n this.emit('runner:started');\n this.logger.info('ScheduleRunner started', { id: this.id });\n }\n\n /**\n * Stop processing schedules\n */\n async stop(): Promise<void> {\n if (this.stopping) return this.stopping;\n if (!this.running && !this.pollInFlight) return;\n this.running = false;\n if (this.pollTimer) {\n clearTimeout(this.pollTimer);\n this.pollTimer = null;\n }\n this.stopping = (async () => {\n await this.pollInFlight;\n this.emit('runner:stopped');\n this.logger.info('ScheduleRunner stopped', { id: this.id });\n })();\n try {\n await this.stopping;\n } finally {\n this.stopping = null;\n }\n }\n\n /**\n * Check if runner is running\n */\n isRunning(): boolean {\n return this.running;\n }\n\n /**\n * Handle job completion for a scheduled job.\n *\n * Call this from TaskRunner's job:completed / job:failed events\n * when the job has a `_scheduleId` in its args.\n */\n async handleJobCompletion(\n scheduleId: string,\n success: boolean,\n errorMessage?: string,\n ): Promise<void> {\n if (!this.db) return;\n\n const scope = this.scheduleScope();\n\n // `last_error` is persisted to a durable schedule row; strip secret-shaped\n // substrings the same way the job runner does (S5 audit #1402).\n const safeErrorMessage = redactErrorMessage(\n errorMessage ?? 'Unknown error',\n );\n\n try {\n if (success) {\n const result = await this.db.query(\n `UPDATE _smrt_agent_schedules\n SET running_count = CASE WHEN COALESCE(running_count, 0) > 0 THEN running_count - 1 ELSE 0 END,\n last_run = ?,\n last_status = 'success',\n last_error = NULL,\n run_count = COALESCE(run_count, 0) + 1,\n success_count = COALESCE(success_count, 0) + 1\n WHERE id = ?${scope.sql} RETURNING id`,\n new Date().toISOString(),\n scheduleId,\n ...scope.params,\n );\n if (result.rows.length !== 1) return;\n this.emit('schedule:completed', scheduleId);\n } else {\n const result = await this.db.query(\n `UPDATE _smrt_agent_schedules\n SET running_count = CASE WHEN COALESCE(running_count, 0) > 0 THEN running_count - 1 ELSE 0 END,\n last_run = ?,\n last_status = 'failed',\n last_error = ?,\n run_count = COALESCE(run_count, 0) + 1,\n failure_count = COALESCE(failure_count, 0) + 1\n WHERE id = ?${scope.sql} RETURNING id`,\n new Date().toISOString(),\n safeErrorMessage,\n scheduleId,\n ...scope.params,\n );\n if (result.rows.length !== 1) return;\n this.emit('schedule:failed', scheduleId, safeErrorMessage);\n }\n } catch (err) {\n this.logger.error('Failed to update schedule after job completion', {\n scheduleId,\n error: err,\n });\n }\n }\n\n /**\n * Start the polling loop\n */\n private startPolling(): void {\n const poll = async () => {\n if (!this.running) return;\n\n try {\n this.pollInFlight = this.poll();\n await this.pollInFlight;\n } catch (error) {\n this.emit('runner:error', error as Error);\n this.logger.error('ScheduleRunner poll error', { error });\n } finally {\n this.pollInFlight = null;\n }\n\n // Schedule next poll\n if (this.running) {\n this.pollTimer = setTimeout(poll, this.config.pollInterval);\n }\n };\n\n // Start immediately\n poll();\n }\n\n /**\n * Poll for due schedules and create jobs\n */\n private async poll(): Promise<void> {\n if (!this.db || !this.jobCollection) return;\n\n const managedPoll = this.running;\n await this.recoverStaleScheduleState();\n const now = new Date().toISOString();\n\n const scope = this.scheduleScope();\n // Find due schedules\n const result = await this.db.query(\n `SELECT *, CAST(id AS VARCHAR) AS schedule_id_text, CAST(tenant_id AS VARCHAR) AS schedule_tenant_text, CAST(next_run AS VARCHAR) AS occurrence_time FROM _smrt_agent_schedules\n WHERE enabled = true\n AND status = 'active'\n AND next_run <= ?${scope.sql}\n AND COALESCE(running_count, 0) < COALESCE(max_concurrent, 1)\n ORDER BY next_run ASC\n LIMIT ?`,\n now,\n ...scope.params,\n this.config.batchSize,\n );\n\n for (const row of result.rows) {\n if (managedPoll && !this.running) break;\n await this.triggerSchedule(\n portableScheduleRow(row as ScheduleRow),\n managedPoll,\n );\n }\n }\n\n private assertAdmissionHost(schedule: ScheduleRow): void {\n let policy: ReturnType<typeof getScheduleAdmissionPolicy>;\n try {\n policy = getScheduleAdmissionPolicy(schedule.method_args || {});\n } catch {\n throw new ScheduleAdmissionBlockedError('INVALID_ADMISSION_POLICY');\n }\n if (!policy) return;\n if (!this.config.occurrenceSigner)\n throw new ScheduleAdmissionBlockedError('MISSING_OCCURRENCE_SIGNER');\n if (this.config.occurrenceSigner.keyId !== policy.keyId)\n throw new ScheduleAdmissionBlockedError('WRONG_OCCURRENCE_KEY');\n if (this.config.queue !== policy.queue)\n throw new ScheduleAdmissionBlockedError('WRONG_OCCURRENCE_QUEUE');\n }\n\n private reportBlocked(schedule: ScheduleRow, error: Error): void {\n const diagnostic = {\n scheduleId: String(schedule.id),\n reason: error.message,\n };\n this.emit('schedule:blocked', diagnostic);\n this.logger.warn(\n 'Schedule admission blocked by durable policy',\n diagnostic,\n );\n }\n\n /** Pending retries occupy slots too; TaskRunner alone owns worker recovery. */\n private async countScheduleJobs(\n db: DatabaseInterface,\n schedule: ScheduleRow,\n ): Promise<number> {\n return countScheduleJobs(\n db,\n String(schedule.id),\n schedule.tenant_id == null ? null : String(schedule.tenant_id),\n {\n objectType: String(schedule.agent_type),\n objectId: schedule.agent_id == null ? null : String(schedule.agent_id),\n method: String(schedule.method || 'run'),\n },\n );\n }\n\n /** Reconcile cached slots without changing TaskRunner-owned job lifecycle. */\n private async recoverStaleScheduleState(): Promise<void> {\n const db = this.db;\n if (!db?.transaction) return;\n const scope = this.scheduleScope();\n const schedules = await db.query(\n `SELECT *, CAST(id AS VARCHAR) AS schedule_id_text, CAST(tenant_id AS VARCHAR) AS schedule_tenant_text FROM _smrt_agent_schedules WHERE 1 = 1${scope.sql}`,\n ...scope.params,\n );\n for (const row of schedules.rows) {\n const candidate = portableScheduleRow(row as ScheduleRow);\n try {\n this.assertAdmissionHost(candidate);\n await db.transaction(async (tx) => {\n const locked = await tx.query(\n `UPDATE _smrt_agent_schedules SET running_count = running_count WHERE id = ?${scope.sql} RETURNING *, CAST(id AS VARCHAR) AS schedule_id_text, CAST(tenant_id AS VARCHAR) AS schedule_tenant_text, CAST(next_run AS VARCHAR) AS occurrence_time`,\n candidate.id,\n ...scope.params,\n );\n if (locked.rows.length !== 1) return;\n const schedule = portableScheduleRow(locked.rows[0] as ScheduleRow);\n this.assertAdmissionHost(schedule);\n const occupied = await this.countScheduleJobs(tx, schedule);\n await tx.query(\n 'UPDATE _smrt_agent_schedules SET running_count = ? WHERE id = ?',\n occupied,\n candidate.id,\n );\n });\n } catch (error) {\n if (!(error instanceof ScheduleAdmissionBlockedError)) throw error;\n this.reportBlocked(candidate, error);\n }\n }\n }\n\n /**\n * Trigger a schedule by creating a job\n */\n private async triggerSchedule(\n candidate: ScheduleRow,\n managedPoll = false,\n ): Promise<void> {\n if (!this.db || !this.jobCollection) return;\n candidate = portableScheduleRow(candidate);\n const db = this.db;\n let admission: { schedule: ScheduleInfo; error?: Error } | undefined;\n try {\n this.assertAdmissionHost(candidate);\n if (!db.transaction)\n throw new Error('ScheduleRunner requires transaction support');\n admission = await db.transaction(async (tx) => {\n if (managedPoll && !this.running) return;\n // The write locks the current row. PostgreSQL rechecks its predicate\n // after a competing writer commits; stale selected occurrences lose.\n const expected = candidate.occurrence_time ?? candidate.next_run;\n const scope = this.scheduleScope();\n const claimed = await tx.query(\n `UPDATE _smrt_agent_schedules SET running_count = running_count\n WHERE id = ? AND enabled = TRUE AND status = 'active'\n AND next_run <= ?${expected == null ? '' : ' AND next_run = ?'}${scope.sql}\n RETURNING *, CAST(id AS VARCHAR) AS schedule_id_text, CAST(tenant_id AS VARCHAR) AS schedule_tenant_text, CAST(next_run AS VARCHAR) AS occurrence_time`,\n candidate.id,\n new Date().toISOString(),\n ...(expected == null ? [] : [expected]),\n ...scope.params,\n );\n if (claimed.rows.length !== 1 || (managedPoll && !this.running)) return;\n const schedule = portableScheduleRow(claimed.rows[0] as ScheduleRow);\n this.assertAdmissionHost(schedule);\n const occupied = await this.countScheduleJobs(tx, schedule);\n await tx.query(\n 'UPDATE _smrt_agent_schedules SET running_count = ? WHERE id = ?',\n occupied,\n schedule.id,\n );\n if (occupied >= Number(schedule.max_concurrent ?? 1)) return;\n const jobs = await SmrtJobCollection.create({ db: tx });\n return this.triggerLockedSchedule(schedule, tx, jobs, occupied);\n });\n } catch (error) {\n if (error instanceof ScheduleAdmissionBlockedError) {\n this.reportBlocked(candidate, error);\n return;\n }\n await db.query(\n 'UPDATE _smrt_agent_schedules SET last_error = ? WHERE id = ?',\n redactErrorForPersistence(error),\n candidate.id,\n );\n this.emit(\n 'schedule:error',\n {\n id: String(candidate.id),\n agentType: String(candidate.agent_type),\n agentId: candidate.agent_id as string | null,\n cron: String(candidate.cron),\n },\n error as Error,\n );\n return;\n }\n // Notify subscribers only after the occurrence and job have committed.\n if (admission?.error) {\n this.emit('schedule:error', admission.schedule, admission.error);\n } else if (admission) {\n this.emit('schedule:triggered', admission.schedule);\n this.logger.info('Schedule triggered', {\n scheduleId: admission.schedule.id,\n });\n }\n }\n\n private async triggerLockedSchedule(\n schedule: ScheduleRow,\n db: DatabaseInterface,\n jobs: SmrtJobCollection,\n occupied: number,\n ): Promise<{ schedule: ScheduleInfo; error?: Error } | undefined> {\n const rawAgentType = schedule.agent_type as string;\n const canonicalAgentType =\n ObjectRegistry.getClass(rawAgentType)?.qualifiedName || rawAgentType;\n\n const scheduleInfo: ScheduleInfo = {\n id: schedule.id as string,\n agentType: canonicalAgentType,\n agentId: schedule.agent_id as string | null,\n cron: schedule.cron as string,\n };\n\n // Parse method_args and agent_config from JSON strings if needed\n let methodArgs: Record<string, unknown> = {};\n if (schedule.method_args) {\n methodArgs =\n typeof schedule.method_args === 'string'\n ? JSON.parse(schedule.method_args as string)\n : (schedule.method_args as Record<string, unknown>);\n }\n if (\n !methodArgs ||\n typeof methodArgs !== 'object' ||\n Array.isArray(methodArgs)\n )\n throw new TypeError('Schedule method_args must be a JSON object');\n for (const key of [\n '_scheduleId',\n '_scheduledFor',\n '_agentConfig',\n '_scheduleAdmission',\n ]) {\n if (Object.hasOwn(methodArgs, key))\n throw new TypeError(`Schedule method_args cannot set reserved ${key}`);\n }\n let agentConfig: Record<string, unknown> = {};\n if (schedule.agent_config) {\n agentConfig =\n typeof schedule.agent_config === 'string'\n ? JSON.parse(schedule.agent_config as string)\n : (schedule.agent_config as Record<string, unknown>);\n }\n\n // Compute next run time from cron before creating the job, evaluated\n // in the row's zone; a missing/blank zone falls back to the column\n // default (UTC) rather than the host's process zone (#3859).\n // An invalid cron or zone is a deterministic configuration failure:\n // retrying it every poll can never succeed, so move the row to\n // status='error' (as AgentSchedule.calculateNextRun does). Only these\n // validation errors are terminal; a valid cron whose next run lies past\n // the search horizon (a leap-day schedule) stays active.\n const timezone =\n typeof schedule.timezone === 'string' && schedule.timezone.trim()\n ? schedule.timezone.trim()\n : 'UTC';\n try {\n validateCronExpression(schedule.cron as string);\n validateCronTimezone(timezone);\n } catch (error) {\n await db.query(\n `UPDATE _smrt_agent_schedules\n SET status = 'error', last_error = ?\n WHERE id = ?`,\n redactErrorForPersistence(error),\n schedule.id,\n );\n this.logger.error('Schedule has an invalid cron or time zone', {\n scheduleId: schedule.id,\n error,\n });\n return { schedule: scheduleInfo, error: error as Error };\n }\n const nextRun = getNextCronDate(schedule.cron as string, timezone);\n\n // Create a job for this schedule\n // Nest agent_config under _agentConfig so TaskRunner can pass it\n // to the agent constructor separately from method args\n const args: Record<string, unknown> = {\n ...methodArgs,\n _scheduleId: String(schedule.id),\n _scheduledFor: scheduleOccurrenceInstant(schedule),\n };\n if (Object.keys(agentConfig).length > 0) {\n args._agentConfig = agentConfig;\n }\n\n // The occurrence, job insert and slot update share the locked transaction.\n const job = await jobs.enqueueJob({\n tenantId:\n typeof schedule.tenant_id === 'string' && schedule.tenant_id.length > 0\n ? (schedule.tenant_id as string)\n : null,\n queue: this.config.queue,\n objectType: canonicalAgentType,\n objectId: schedule.agent_id as string | null,\n method: (schedule.method as string) || 'run',\n args,\n priority: 75, // High priority for scheduled agents\n maxAttempts: 3,\n timeout: (schedule.timeout as number) || 3600000,\n });\n\n if (this.config.occurrenceSigner) {\n const signer = this.config.occurrenceSigner;\n const integrity = signer.sign(\n getScheduleAdmissionPayload(job, signer.keyId),\n );\n job.args = { ...job.args, _scheduleAdmission: integrity };\n if (!verifyScheduleAdmission(job, signer)) {\n throw new Error(\n 'Occurrence signer returned invalid schedule admission integrity',\n );\n }\n // This model is bound to the admission transaction. No consumer can see\n // an unsigned protected job, and no producer save follows the commit.\n await job.save();\n }\n\n // Only now that the job is durably enqueued do we consume the slot:\n // increment running_count and advance next_run in one update.\n await db.query(\n `UPDATE _smrt_agent_schedules\n SET agent_type = ?,\n running_count = ?,\n next_run = ?\n WHERE id = ?`,\n canonicalAgentType,\n occupied + 1,\n nextRun.toISOString(),\n schedule.id,\n );\n\n return { schedule: scheduleInfo };\n }\n}\n\n/**\n * Database row type for schedule\n */\ninterface ScheduleRow {\n id: unknown;\n agent_type: unknown;\n agent_id: unknown;\n tenant_id: unknown;\n agent_config: unknown;\n cron: unknown;\n timezone: unknown;\n method: unknown;\n method_args: unknown;\n timeout: unknown;\n next_run?: unknown;\n occurrence_time?: unknown;\n schedule_id_text?: string;\n schedule_tenant_text?: string | null;\n max_concurrent?: unknown;\n}\n\nfunction portableScheduleRow(row: ScheduleRow): ScheduleRow {\n return {\n ...row,\n id: row.schedule_id_text ?? row.id,\n tenant_id: Object.hasOwn(row, 'schedule_tenant_text')\n ? row.schedule_tenant_text\n : row.tenant_id,\n };\n}\n\n/** SQL datetime columns store UTC wall clocks; never parse them in host TZ. */\nfunction scheduleOccurrenceInstant(schedule: ScheduleRow): string {\n const raw = schedule.occurrence_time ?? schedule.next_run;\n if (raw instanceof Date) return raw.toISOString();\n let text = String(raw).trim();\n if (/^\\d{4}-\\d{2}-\\d{2}[ T]\\d{2}:\\d{2}:\\d{2}(?:\\.\\d+)?$/.test(text)) {\n text = `${text.replace(' ', 'T')}Z`;\n }\n return new Date(text).toISOString();\n}\n\n// --- Cron helpers (self-contained, no external dependency) ---\n\n/**\n * Inclusive valid range for each cron field, by position.\n * minute, hour, day-of-month, month, day-of-week.\n * Day-of-week accepts 0-7 where both 0 and 7 represent Sunday.\n */\nconst CRON_FIELD_RANGES: ReadonlyArray<{\n name: string;\n min: number;\n max: number;\n}> = [\n { name: 'minute', min: 0, max: 59 },\n { name: 'hour', min: 0, max: 23 },\n { name: 'day-of-month', min: 1, max: 31 },\n { name: 'month', min: 1, max: 12 },\n { name: 'day-of-week', min: 0, max: 7 },\n];\n\n/**\n * Validate that every numeric component of a single cron field falls within\n * the field's inclusive range. Rejects malformed values up front so an\n * out-of-range field (e.g. `minute=70`) fails fast at schedule-trigger time\n * instead of silently scanning ~525k candidate minutes and never matching\n * (S5 audit #1402).\n */\nfunction validateCronField(\n expr: string,\n range: { name: string; min: number; max: number },\n): void {\n if (expr === '*') return;\n\n const reject = (detail: string): never => {\n throw new Error(\n `Invalid cron expression: ${range.name} field \"${expr}\" ${detail} ` +\n `(valid range ${range.min}-${range.max})`,\n );\n };\n\n const assertInRange = (value: number): void => {\n if (!Number.isInteger(value) || value < range.min || value > range.max) {\n reject('is out of range');\n }\n };\n\n for (const term of expr.split(',')) {\n if (term === '') reject('contains an empty value');\n\n let body = term;\n if (body.includes('/')) {\n // Exactly one '/' is valid (`base/step`). `1/2/3` must be rejected, not\n // silently parsed as `1/2` by dropping the trailing segment.\n const stepParts = body.split('/');\n if (stepParts.length !== 2) {\n reject('has malformed step syntax');\n }\n const [rangePart, stepStr] = stepParts;\n const step = Number(stepStr);\n if (!Number.isInteger(step) || step <= 0) {\n reject('has an invalid step');\n }\n body = rangePart;\n if (body === '*') continue;\n }\n\n if (body.includes('-')) {\n // Exactly one '-' is valid (`start-end`). `1-2-3` must be rejected, not\n // silently parsed as `1-2` by dropping the trailing segment.\n const rangeParts = body.split('-');\n if (rangeParts.length !== 2) {\n reject('has malformed range syntax');\n }\n const [startStr, endStr] = rangeParts;\n if (startStr === '' || endStr === '') {\n reject('has an empty range part');\n }\n const start = Number(startStr);\n const end = Number(endStr);\n assertInRange(start);\n assertInRange(end);\n if (start > end) reject('has an inverted range');\n } else {\n assertInRange(Number(body));\n }\n }\n}\n\n/**\n * Validate a standard 5-field cron expression: field count plus per-field\n * value ranges. Throws a descriptive `Error` on the first invalid field.\n *\n * Exposed so callers (and the agents package, which owns schedule creation)\n * can reject a bad cron at write time rather than letting an out-of-range\n * field silently never match (S5 audit #1402).\n *\n * @param cron - The cron expression to validate.\n * @returns The trimmed, whitespace-split fields when valid.\n */\nexport function validateCronExpression(cron: string): string[] {\n const parts = cron.trim().split(/\\s+/);\n if (parts.length !== 5) {\n throw new Error(\n `Invalid cron expression: expected 5 fields, got ${parts.length}`,\n );\n }\n\n parts.forEach((field, index) => {\n validateCronField(field, CRON_FIELD_RANGES[index]);\n });\n\n return parts;\n}\n\nconst MINUTE_MS = 60_000;\nconst HOUR_MS = 60 * MINUTE_MS;\nconst DAY_MS = 24 * HOUR_MS;\n\n/** Wall-clock minutes scanned before giving up (one year, as before). */\nconst CRON_SEARCH_HORIZON_MS = 525_600 * MINUTE_MS;\n\n/** UTC offset (ms, east-positive) of a zone at an instant. */\ntype ZoneOffsetAt = (epochMs: number) => number;\n\nconst zoneFormatters = new Map<string, Intl.DateTimeFormat>();\n\n/**\n * Resolve the offset function for a cron time zone. `undefined`/`null` keeps\n * the legacy host-local behaviour (the process `TZ`); any other value must be\n * an IANA zone name accepted by `Intl.DateTimeFormat`.\n */\nfunction resolveZoneOffset(timezone: string | null | undefined): ZoneOffsetAt {\n if (timezone === undefined || timezone === null) {\n return (epochMs) => -new Date(epochMs).getTimezoneOffset() * MINUTE_MS;\n }\n\n let formatter = zoneFormatters.get(timezone);\n if (!formatter) {\n try {\n formatter = new Intl.DateTimeFormat('en-US', {\n timeZone: timezone,\n hourCycle: 'h23',\n year: 'numeric',\n month: 'numeric',\n day: 'numeric',\n hour: 'numeric',\n minute: 'numeric',\n second: 'numeric',\n });\n } catch {\n throw new Error(\n `Invalid cron timezone: \"${timezone}\" is not a recognized IANA time zone`,\n );\n }\n zoneFormatters.set(timezone, formatter);\n }\n\n const zoned = formatter;\n return (epochMs) => {\n const fields: Record<string, number> = {};\n for (const part of zoned.formatToParts(epochMs)) {\n if (part.type !== 'literal') fields[part.type] = Number(part.value);\n }\n const wallMs = Date.UTC(\n fields.year,\n fields.month - 1,\n fields.day,\n // `% 24` guards ICU builds that render midnight as hour 24.\n fields.hour % 24,\n fields.minute,\n fields.second,\n );\n return wallMs - (epochMs - (((epochMs % 1000) + 1000) % 1000));\n };\n}\n\n/**\n * Instants at which a wall-clock time (given as UTC-epoch ms of its naive\n * fields) occurs in the zone: one normally, two in a backward-transition\n * overlap (earlier first), none in a forward-transition gap. Assumes at most\n * one offset transition within a day either side, true of every IANA zone.\n */\nfunction wallTimeInstants(\n wallMs: number,\n offsetAt: ZoneOffsetAt,\n): { instants: number[]; offsetBefore: number; offsetAfter: number } {\n const offsetBefore = offsetAt(wallMs - DAY_MS);\n const offsetAfter = offsetAt(wallMs + DAY_MS);\n const instants: number[] = [];\n for (const offset of new Set([offsetBefore, offsetAfter])) {\n const instant = wallMs - offset;\n if (offsetAt(instant) === offset) instants.push(instant);\n }\n instants.sort((a, b) => a - b);\n return { instants, offsetBefore, offsetAfter };\n}\n\n/**\n * Validate a cron time zone without computing a run date.\n *\n * @throws `Invalid cron timezone` when the name is not an IANA zone.\n */\nfunction validateCronTimezone(timezone: string): void {\n resolveZoneOffset(timezone);\n}\n\n/**\n * Parse a cron expression and get the next run date.\n * Supports standard 5-field cron: minute hour day-of-month month day-of-week\n *\n * Fields are matched against the wall clock of `timezone`, an IANA zone name\n * such as `America/Edmonton` (DST-correct via `Intl.DateTimeFormat`). When\n * `timezone` is omitted (`undefined`/`null`) the host process's local zone is\n * used — the legacy behaviour, kept for callers that have no zone to pass.\n * Persisted schedules should always pass their row's zone; the\n * `_smrt_agent_schedules.timezone` column defaults to `UTC`.\n *\n * Daylight-saving transitions follow Vixie cron's split:\n * - **Fixed-time** expressions (no `*` in the minute or hour field) run once\n * per matching day. A wall time skipped by a forward transition runs\n * shifted forward by the gap (`30 2 * * *` on the spring-forward day in\n * `America/Edmonton` runs at 03:30 MDT, RFC 5545 / Temporal \"compatible\"\n * resolution); a wall time repeated by a backward transition runs only at\n * its first occurrence.\n * - **Wildcard** expressions (`*` in the minute or hour field, including\n * `*\\/n`) follow elapsed time: skipped wall times do not run and repeated\n * wall times run again in the repeated hour.\n *\n * Limitations:\n * - Numeric values only (no abbreviated names like JAN, MON)\n * - Day-of-week accepts 0-7 where both 0 and 7 represent Sunday\n *\n * Out-of-range fields and unknown time zones are rejected eagerly (see\n * {@link validateCronExpression}).\n *\n * @param cron - 5-field cron expression.\n * @param timezone - IANA zone the cron is evaluated in; omit for host-local.\n * @returns The first matching instant at least one minute after now.\n */\nexport function getNextCronDate(cron: string, timezone?: string | null): Date {\n const [minuteExpr, hourExpr, dayExpr, monthExpr, dowExpr] =\n validateCronExpression(cron);\n const offsetAt = resolveZoneOffset(timezone);\n\n // Standard cron DOM/DOW semantics:\n // When both day-of-month and day-of-week are restricted (not *),\n // a date matches if EITHER condition is met (OR logic).\n const dayIsWildcard = dayExpr === '*';\n const dowIsWildcard = dowExpr === '*';\n const fixedTime = !minuteExpr.includes('*') && !hourExpr.includes('*');\n\n const dayMatches = (wall: Date): boolean => {\n const domMatches = matchesCronField(\n wall.getUTCDate(),\n dayExpr,\n CRON_FIELD_RANGES[2],\n );\n // getUTCDay() returns 0 for Sunday; standard cron accepts both 0 and 7\n const dow = wall.getUTCDay();\n const dowMatches =\n matchesCronField(dow, dowExpr, CRON_FIELD_RANGES[4]) ||\n (dow === 0 && matchesCronField(7, dowExpr, CRON_FIELD_RANGES[4]));\n if (!dayIsWildcard && !dowIsWildcard) return domMatches || dowMatches;\n if (!dayIsWildcard) return domMatches;\n if (!dowIsWildcard) return dowMatches;\n return true;\n };\n\n // The earliest eligible instant: the start of the next minute.\n const now = Date.now();\n const threshold =\n now - (((now % MINUTE_MS) + MINUTE_MS) % MINUTE_MS) + MINUTE_MS;\n\n // Scan naive wall-clock minutes (UTC accessors on wall-time epochs). A\n // transition near the threshold can map earlier wall times to eligible\n // instants (the repeated hour, or a gap shifted forward), so start the\n // scan one transition-width before the threshold's wall time.\n const thresholdOffset = offsetAt(threshold);\n const thresholdSpread = Math.abs(\n offsetAt(threshold - DAY_MS) - offsetAt(threshold + DAY_MS),\n );\n let wallMs = threshold + thresholdOffset - thresholdSpread;\n const wallEnd = threshold + thresholdOffset + CRON_SEARCH_HORIZON_MS;\n\n let best: number | null = null;\n let stopAfterWall = Number.POSITIVE_INFINITY;\n\n while (wallMs <= wallEnd && wallMs <= stopAfterWall) {\n const wall = new Date(wallMs);\n const year = wall.getUTCFullYear();\n const month = wall.getUTCMonth();\n const day = wall.getUTCDate();\n const hour = wall.getUTCHours();\n\n if (!matchesCronField(month + 1, monthExpr, CRON_FIELD_RANGES[3])) {\n wallMs = Date.UTC(year, month + 1, 1);\n continue;\n }\n if (!dayMatches(wall)) {\n wallMs = Date.UTC(year, month, day + 1);\n continue;\n }\n if (!matchesCronField(hour, hourExpr, CRON_FIELD_RANGES[1])) {\n wallMs = Date.UTC(year, month, day, hour + 1);\n continue;\n }\n if (\n !matchesCronField(wall.getUTCMinutes(), minuteExpr, CRON_FIELD_RANGES[0])\n ) {\n wallMs += MINUTE_MS;\n continue;\n }\n\n const { instants, offsetBefore, offsetAfter } = wallTimeInstants(\n wallMs,\n offsetAt,\n );\n let candidates = instants;\n if (instants.length === 0) {\n // Forward-transition gap: fixed-time runs shift forward by the gap.\n candidates = fixedTime ? [wallMs - offsetBefore] : [];\n } else if (instants.length > 1 && fixedTime) {\n // Backward-transition overlap: fixed-time runs fire once, first.\n candidates = [instants[0]];\n }\n\n for (const instant of candidates) {\n if (instant >= threshold && (best === null || instant < best)) {\n if (best === null) {\n // Later wall times within one transition width can still map to\n // an earlier instant (the repeated hour); keep scanning that far.\n stopAfterWall = wallMs + Math.abs(offsetBefore - offsetAfter);\n }\n best = instant;\n }\n }\n\n wallMs += MINUTE_MS;\n }\n\n if (best === null) {\n throw new Error(`Could not find next run date for cron: ${cron}`);\n }\n return new Date(best);\n}\n\n/**\n * Check if a value matches a cron field expression.\n *\n * Each comma-separated term is evaluated on its own, so mixed lists such as\n * `1-5,10` or `0,30-40/5` match every term rather than parsing the whole\n * list as one range. `*\\/step` steps from the field minimum (day-of-month\n * `*\\/2` is 1,3,5,…; month `*\\/3` is 1,4,7,10), and `base/step` without a range\n * (`5/15`) steps from `base` to the field maximum — the common cron extension\n * the validator already accepts.\n */\nfunction matchesCronField(\n value: number,\n expr: string,\n range: { min: number; max: number },\n): boolean {\n if (expr === '*') return true;\n return expr.split(',').some((term) => {\n const [body, stepStr] = term.split('/');\n const step = stepStr === undefined ? 1 : parseInt(stepStr, 10);\n let start: number;\n let end: number;\n if (body === '*') {\n start = range.min;\n end = range.max;\n } else if (body.includes('-')) {\n const [startStr, endStr] = body.split('-');\n start = parseInt(startStr, 10);\n end = parseInt(endStr, 10);\n } else {\n start = parseInt(body, 10);\n end = stepStr === undefined ? start : range.max;\n }\n return value >= start && value <= end && (value - start) % step === 0;\n });\n}\n\n/**\n * Create a ScheduleRunner instance\n */\nexport function createScheduleRunner(\n config?: ScheduleRunnerConfig,\n): ScheduleRunner {\n return new ScheduleRunner(config);\n}\n\nexport default ScheduleRunner;\n","/**\n * @happyvertical/smrt-jobs\n *\n * Background job execution for SMRT objects.\n * Provides persistence, retries, and scheduling for any SmrtObject method.\n *\n * @example\n * ```typescript\n * import { withBackgroundJobs, TaskRunner } from '@happyvertical/smrt-jobs';\n *\n * // Add background capabilities to your class\n * const BackgroundDocument = withBackgroundJobs(Document);\n * const doc = new BackgroundDocument({ ... });\n *\n * // Simple background execution\n * const handle = await doc.bg('generateSummary', { format: 'md' });\n *\n * // Fluent builder for advanced options\n * const handle = await doc.background('generateSummary', { format: 'md' })\n * .delay('5m')\n * .retries(5)\n * .priority('high')\n * .enqueue();\n *\n * // Wait for result\n * const result = await handle.wait();\n *\n * // Start a task runner to process jobs\n * const runner = new TaskRunner({ concurrency: 5 });\n * await runner.initialize(db);\n * await runner.start();\n * ```\n */\n\n// Self-register this package's manifest before any @smrt() decorator fires\n// downstream. Must come first so the side effect runs ahead of the class\n// module loads below. See __smrt-register__.ts for issue #1132 context.\nimport './__smrt-register__.js';\n// Contribute `_smrt_jobs`/`_smrt_job_events` retention to the framework sweep\n// as soon as this package is loaded (#2375), so `smrt db:prune` and any host\n// process see the tasks without an app-level wiring step. Registering is not\n// scheduling: nothing deletes until something runs a sweep, and the policy can\n// still disable either task by name.\nimport { registerJobRetentionTasks } from './retention.js';\n\nregisterJobRetentionTasks();\n\n// Background-job policy controls (retry ceiling, per-tenant cap, opt-in\n// method allowlist). Shared with the agents package (S5 audit #1402).\nexport {\n assertWithinTenantCreationCap,\n type BackgroundEligibleClass,\n backgroundEligible,\n clampRetries,\n DEFAULT_TENANT_JOB_CAP,\n getBackgroundEligibleMethods,\n isBackgroundEligibleMethod,\n MAX_JOB_RETRIES,\n markBackgroundEligible,\n TenantJobCapExceededError,\n} from './background-policy.js';\nexport {\n createHmacDurableJobPayloadSigner,\n type DurableJobPayloadIntegrity,\n type DurableJobPayloadSigner,\n} from './durable-payload-integrity.js';\n// Error-message redaction for durable job error persistence.\nexport {\n redactErrorForPersistence,\n redactErrorMessage,\n} from './error-redaction.js';\n// Durable provider-neutral forge delivery inbox and projection runtime.\nexport {\n type AcceptedForgeDelivery,\n type AcceptForgeDeliveryInput,\n type ClaimForgeDeliveryOptions,\n ForgeDelivery,\n ForgeDeliveryCollection,\n type ForgeDeliveryStatus,\n type ForgeObservation,\n type ForgeProjectionAuditEvent,\n type ForgeProjectionAuditHook,\n ForgeProjectionCheckpoint,\n type ForgeProjectionContext,\n ForgeProjectionRuntime,\n type ForgeProjectionRuntimeOptions,\n type ForgeProjector,\n} from './forge-projection.js';\n// Fluent job builder and utilities\nexport {\n JobBuilder,\n type Priority,\n parseDelay,\n priorityToNumber,\n} from './job-builder.js';\n// Job handle for tracking\nexport {\n JobHandle,\n type JobResult,\n type WaitOptions,\n} from './job-handle.js';\n// Logger extension\nexport {\n type JobContext,\n JobContextLogger,\n type JobEventInput,\n type JobExecutionContext,\n type JobProgressInput,\n} from './logger-extension.js';\n// Durable MCP Tasks extension adapter.\nexport {\n type CreateMcpTaskInput,\n createMcpTaskResult,\n getMcpTaskMarker,\n MCP_TASKS_EXTENSION,\n type McpTask,\n type McpTaskAuthority,\n McpTaskCancelledError,\n type McpTaskContinuation,\n type McpTaskJobMarker,\n McpTaskNotFoundError,\n type McpTaskStatus,\n McpTaskStore,\n McpTaskSuspendedError,\n requestMcpTaskContinuation,\n requestMcpTaskInput,\n taskFromJob,\n} from './mcp-task.js';\n// Object extension (mixin)\nexport {\n type BackgroundCapable,\n type BgOptions,\n withBackgroundJobs,\n} from './object-extension.js';\n// Job retention — bounded growth for _smrt_jobs / _smrt_job_events (#2375)\nexport {\n DEFAULT_JOB_RETENTION,\n DEFAULT_RETENTION_SWEEP_INTERVAL_MS,\n JOB_EVENTS_RETENTION_TASK,\n JOBS_RETENTION_TASK,\n type JobRetentionOptions,\n type RetentionSweeper,\n type RetentionSweeperOptions,\n registerJobRetentionTasks,\n startRetentionSweeper,\n unregisterJobRetentionTasks,\n} from './retention.js';\n// Task runner\nexport {\n createTaskRunner,\n getActiveJobExecutionContext,\n isRunnerExecutionContext,\n JobCancelledError,\n JobTimeoutError,\n TaskRunner,\n type TaskRunnerConfig,\n type TaskRunnerEvents,\n} from './runner.js';\nexport {\n getScheduleAdmissionPayload,\n getScheduleAdmissionPolicy,\n type ScheduleAdmissionPayload,\n type ScheduleAdmissionPolicy,\n verifyScheduleAdmission,\n} from './schedule-admission.js';\n\n// Schedule runner (for cron-based agent scheduling)\nexport {\n createScheduleRunner,\n getNextCronDate,\n SCHEDULED_JOB_QUEUE,\n type ScheduleInfo,\n ScheduleRunner,\n type ScheduleRunnerConfig,\n type ScheduleRunnerEvents,\n validateCronExpression,\n} from './schedule-runner.js';\n// Core job model\nexport {\n type ClaimReadyOptions,\n type JobStatus,\n type ListReadyOptions,\n SmrtJob,\n SmrtJobCollection,\n type SmrtJobData,\n type TimeoutBehavior,\n} from './smrt-job.js';\nexport { SmrtJobDedupeSlot } from './smrt-job-dedupe-slot.js';\n// Durable job telemetry\nexport {\n type JobEventCursor,\n type ListJobEventsOptions,\n type ListTerminalOutcomesOptions,\n SmrtJobEvent,\n SmrtJobEventCollection,\n type SmrtJobEventData,\n type SmrtJobEventLevel,\n type SmrtJobEventType,\n type SmrtJobTerminalOutcome,\n type SmrtJobTerminalOutcomePage,\n type SmrtJobTerminalStatus,\n} from './smrt-job-event.js';\n// Worker liveness lease model\nexport {\n type RegisterWorkerInput,\n SmrtWorker,\n SmrtWorkerCollection,\n} from './smrt-worker.js';\nexport {\n createWorkerKey,\n isWorkerAlive,\n registerLiveWorker,\n unregisterLiveWorker,\n} from './worker-liveness.js';\n"],"mappings":";;;;;;;;AAeO,SAAS,kCAAkC,SAGtB;CAC1B,IAAI,CAAC,QAAQ,SAAS,QAAQ,MAAM,SAAS,KAC3C,MAAM,IAAI,MACR,2DACF;CAMF,KAHE,OAAO,QAAQ,QAAQ,WACnB,OAAO,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