@happyvertical/smrt-jobs 0.70.2 → 0.70.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"runner-rbQGGKEG.js","names":["expression","tenantId","tenantId","jobId","job"],"sources":["../../src/__smrt-register__.ts","../../src/background-policy.ts","../../src/job-handlers.ts","../../src/smrt-job-dedupe-slot.ts","../../src/worker-liveness.ts","../../src/smrt-job-event.ts","../../src/terminal-outcome.ts","../../src/smrt-job.ts","../../src/retention.ts","../../src/error-redaction.ts","../../src/smrt-worker.ts","../../src/logger-extension.ts","../../src/mcp-task.ts","../../src/stale-recovery.ts","../../src/runner.ts"],"sourcesContent":["// Generated by @happyvertical/smrt-core smrtPlugin at library build time.\n// The package manifest is inlined so self-registration cannot miss when a\n// downstream bundler relocates this module away from dist/manifest.json\n// (https://github.com/happyvertical/smrt/issues/1506,\n// https://github.com/happyvertical/smrt/issues/1507).\nimport { ObjectRegistry } from '@happyvertical/smrt-core';\n\nObjectRegistry.registerPackageManifest(JSON.parse(\"{\\\"version\\\":\\\"1.0.0\\\",\\\"timestamp\\\":0,\\\"packageName\\\":\\\"@happyvertical/smrt-jobs\\\",\\\"packageVersion\\\":\\\"0.70.2\\\",\\\"objects\\\":{\\\"@happyvertical/smrt-jobs:SmrtJobEvent\\\":{\\\"name\\\":\\\"smrtjobevent\\\",\\\"className\\\":\\\"SmrtJobEvent\\\",\\\"qualifiedName\\\":\\\"@happyvertical/smrt-jobs:SmrtJobEvent\\\",\\\"collection\\\":\\\"smrtjobevents\\\",\\\"filePath\\\":\\\"src/smrt-job-event.ts\\\",\\\"packageName\\\":\\\"@happyvertical/smrt-jobs\\\",\\\"fields\\\":{\\\"tenantId\\\":{\\\"type\\\":\\\"text\\\",\\\"_meta\\\":{\\\"__tenancy\\\":{\\\"isTenantIdField\\\":true,\\\"autoFilter\\\":true,\\\"required\\\":false,\\\"autoPopulate\\\":true,\\\"nullable\\\":true,\\\"mode\\\":\\\"optional\\\",\\\"field\\\":\\\"tenantId\\\",\\\"allowSuperAdminBypass\\\":false},\\\"__statedOptions\\\":[\\\"sqlType\\\",\\\"nullable\\\",\\\"__tenancy\\\",\\\"required\\\"],\\\"sqlType\\\":\\\"UUID\\\",\\\"nullable\\\":true,\\\"required\\\":false},\\\"required\\\":false},\\\"jobId\\\":{\\\"type\\\":\\\"foreignKey\\\",\\\"_meta\\\":{\\\"__statedOptions\\\":[\\\"required\\\",\\\"requiredFor\\\",\\\"constraint\\\",\\\"related\\\"],\\\"required\\\":true,\\\"requiredFor\\\":\\\"identity\\\",\\\"constraint\\\":false},\\\"required\\\":true,\\\"related\\\":\\\"SmrtJob\\\"},\\\"type\\\":{\\\"type\\\":\\\"text\\\",\\\"_meta\\\":{\\\"__statedOptions\\\":[\\\"required\\\",\\\"default\\\"],\\\"required\\\":true,\\\"default\\\":\\\"log\\\"},\\\"required\\\":true,\\\"default\\\":\\\"log\\\"},\\\"level\\\":{\\\"type\\\":\\\"text\\\",\\\"_meta\\\":{\\\"__statedOptions\\\":[\\\"required\\\",\\\"default\\\",\\\"enum\\\"],\\\"required\\\":true,\\\"default\\\":\\\"info\\\"},\\\"required\\\":true,\\\"default\\\":\\\"info\\\",\\\"enum\\\":[\\\"debug\\\",\\\"info\\\",\\\"warn\\\",\\\"error\\\"]},\\\"stage\\\":{\\\"type\\\":\\\"text\\\",\\\"_meta\\\":{\\\"__statedOptions\\\":[\\\"nullable\\\",\\\"required\\\"],\\\"nullable\\\":true,\\\"required\\\":false},\\\"required\\\":false},\\\"progress\\\":{\\\"type\\\":\\\"integer\\\",\\\"_meta\\\":{\\\"__statedOptions\\\":[\\\"nullable\\\",\\\"required\\\"],\\\"nullable\\\":true,\\\"required\\\":false},\\\"required\\\":false},\\\"message\\\":{\\\"type\\\":\\\"text\\\",\\\"_meta\\\":{\\\"__statedOptions\\\":[\\\"default\\\"],\\\"default\\\":\\\"\\\"},\\\"required\\\":false,\\\"default\\\":\\\"\\\"},\\\"data\\\":{\\\"type\\\":\\\"json\\\",\\\"_meta\\\":{\\\"__statedOptions\\\":[]},\\\"required\\\":false},\\\"createdAt\\\":{\\\"type\\\":\\\"datetime\\\",\\\"_meta\\\":{\\\"__statedOptions\\\":[\\\"required\\\"],\\\"required\\\":true},\\\"required\\\":true}},\\\"methods\\\":{\\\"toCursor\\\":{\\\"name\\\":\\\"toCursor\\\",\\\"async\\\":false,\\\"parameters\\\":[],\\\"returnType\\\":\\\"string\\\",\\\"isStatic\\\":false,\\\"isPublic\\\":true}},\\\"decoratorConfig\\\":{\\\"tableName\\\":\\\"_smrt_job_events\\\",\\\"api\\\":false,\\\"cli\\\":{\\\"include\\\":[\\\"list\\\",\\\"get\\\"],\\\"http\\\":false,\\\"skipApiCheck\\\":true},\\\"mcp\\\":false,\\\"tenantScoped\\\":{\\\"mode\\\":\\\"optional\\\"},\\\"conflictColumns\\\":[\\\"tenant_id\\\",\\\"slug\\\",\\\"context\\\"]},\\\"extends\\\":\\\"SmrtObject\\\",\\\"exportName\\\":\\\"SmrtJobEvent\\\",\\\"collectionExportName\\\":\\\"SmrtJobEventCollection\\\",\\\"validationRules\\\":[{\\\"field\\\":\\\"jobId\\\",\\\"rule\\\":\\\"required\\\",\\\"fieldType\\\":\\\"foreignKey\\\"},{\\\"field\\\":\\\"type\\\",\\\"rule\\\":\\\"required\\\",\\\"fieldType\\\":\\\"text\\\"},{\\\"field\\\":\\\"level\\\",\\\"rule\\\":\\\"required\\\",\\\"fieldType\\\":\\\"text\\\"},{\\\"field\\\":\\\"createdAt\\\",\\\"rule\\\":\\\"required\\\",\\\"fieldType\\\":\\\"datetime\\\"}],\\\"schema\\\":{\\\"tableName\\\":\\\"_smrt_job_events\\\",\\\"ddl\\\":\\\"CREATE TABLE IF NOT EXISTS \\\\\\\"_smrt_job_events\\\\\\\" (\\\\n \\\\\\\"_sync_origin_device_id\\\\\\\" TEXT,\\\\n \\\\\\\"_sync_revision\\\\\\\" INTEGER,\\\\n \\\\\\\"id\\\\\\\" UUID PRIMARY KEY NOT NULL,\\\\n \\\\\\\"slug\\\\\\\" TEXT NOT NULL,\\\\n \\\\\\\"context\\\\\\\" TEXT NOT NULL DEFAULT '',\\\\n \\\\\\\"created_at\\\\\\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\\\n \\\\\\\"updated_at\\\\\\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\\\n \\\\\\\"tenant_id\\\\\\\" UUID,\\\\n \\\\\\\"job_id\\\\\\\" UUID NOT NULL,\\\\n \\\\\\\"type\\\\\\\" TEXT NOT NULL DEFAULT 'log',\\\\n \\\\\\\"level\\\\\\\" TEXT NOT NULL DEFAULT 'info',\\\\n \\\\\\\"stage\\\\\\\" TEXT,\\\\n \\\\\\\"progress\\\\\\\" INTEGER,\\\\n \\\\\\\"message\\\\\\\" TEXT DEFAULT '',\\\\n \\\\\\\"data\\\\\\\" JSON\\\\n);\\\",\\\"columns\\\":{\\\"_sync_origin_device_id\\\":{\\\"type\\\":\\\"TEXT\\\"},\\\"_sync_revision\\\":{\\\"type\\\":\\\"INTEGER\\\"},\\\"id\\\":{\\\"type\\\":\\\"UUID\\\",\\\"primaryKey\\\":true,\\\"referenceKind\\\":\\\"id\\\",\\\"notNull\\\":true},\\\"slug\\\":{\\\"type\\\":\\\"TEXT\\\",\\\"notNull\\\":true},\\\"context\\\":{\\\"type\\\":\\\"TEXT\\\",\\\"notNull\\\":true,\\\"default\\\":\\\"\\\"},\\\"created_at\\\":{\\\"type\\\":\\\"TIMESTAMP\\\",\\\"notNull\\\":true,\\\"default\\\":\\\"current_timestamp\\\"},\\\"updated_at\\\":{\\\"type\\\":\\\"TIMESTAMP\\\",\\\"notNull\\\":true,\\\"default\\\":\\\"current_timestamp\\\"},\\\"tenant_id\\\":{\\\"type\\\":\\\"UUID\\\",\\\"referenceKind\\\":\\\"tenantId\\\",\\\"notNull\\\":false,\\\"unique\\\":false},\\\"job_id\\\":{\\\"type\\\":\\\"UUID\\\",\\\"referenceKind\\\":\\\"foreignKey\\\",\\\"notNull\\\":true,\\\"unique\\\":false},\\\"type\\\":{\\\"type\\\":\\\"TEXT\\\",\\\"notNull\\\":true,\\\"unique\\\":false,\\\"default\\\":\\\"log\\\"},\\\"level\\\":{\\\"type\\\":\\\"TEXT\\\",\\\"notNull\\\":true,\\\"unique\\\":false,\\\"default\\\":\\\"info\\\"},\\\"stage\\\":{\\\"type\\\":\\\"TEXT\\\",\\\"notNull\\\":false,\\\"unique\\\":false},\\\"progress\\\":{\\\"type\\\":\\\"INTEGER\\\",\\\"notNull\\\":false,\\\"unique\\\":false},\\\"message\\\":{\\\"type\\\":\\\"TEXT\\\",\\\"notNull\\\":false,\\\"unique\\\":false,\\\"default\\\":\\\"\\\"},\\\"data\\\":{\\\"type\\\":\\\"JSON\\\",\\\"notNull\\\":false,\\\"unique\\\":false}},\\\"indexes\\\":[{\\\"name\\\":\\\"_smrt_job_events_slug_context_idx\\\",\\\"columns\\\":[\\\"tenant_id\\\",\\\"slug\\\",\\\"context\\\"],\\\"unique\\\":true,\\\"nullsNotDistinct\\\":true},{\\\"name\\\":\\\"_smrt_job_events_tenant_id_created_at_idx\\\",\\\"columns\\\":[\\\"tenant_id\\\",\\\"created_at\\\"]},{\\\"name\\\":\\\"_smrt_job_events_job_id_idx\\\",\\\"columns\\\":[\\\"job_id\\\"]}],\\\"version\\\":\\\"8645e1da\\\"},\\\"importPath\\\":\\\"@happyvertical/smrt-jobs\\\"},\\\"@happyvertical/smrt-jobs:ForgeDelivery\\\":{\\\"name\\\":\\\"forgedelivery\\\",\\\"className\\\":\\\"ForgeDelivery\\\",\\\"qualifiedName\\\":\\\"@happyvertical/smrt-jobs:ForgeDelivery\\\",\\\"collection\\\":\\\"forgedeliveries\\\",\\\"filePath\\\":\\\"src/forge-projection.ts\\\",\\\"packageName\\\":\\\"@happyvertical/smrt-jobs\\\",\\\"fields\\\":{\\\"tenantId\\\":{\\\"type\\\":\\\"text\\\",\\\"_meta\\\":{\\\"__tenancy\\\":{\\\"isTenantIdField\\\":true,\\\"autoFilter\\\":true,\\\"required\\\":true,\\\"autoPopulate\\\":true,\\\"nullable\\\":false,\\\"mode\\\":\\\"required\\\",\\\"field\\\":\\\"tenantId\\\",\\\"allowSuperAdminBypass\\\":false},\\\"__statedOptions\\\":[\\\"sqlType\\\",\\\"requiredFor\\\",\\\"__tenancy\\\"],\\\"sqlType\\\":\\\"UUID\\\",\\\"requiredFor\\\":\\\"tenant-scope\\\"},\\\"required\\\":true},\\\"provider\\\":{\\\"type\\\":\\\"text\\\",\\\"_meta\\\":{\\\"__statedOptions\\\":[\\\"required\\\",\\\"requiredFor\\\"],\\\"required\\\":true,\\\"requiredFor\\\":\\\"identity\\\"},\\\"required\\\":true},\\\"deliveryId\\\":{\\\"type\\\":\\\"text\\\",\\\"_meta\\\":{\\\"__statedOptions\\\":[\\\"required\\\",\\\"requiredFor\\\"],\\\"required\\\":true,\\\"requiredFor\\\":\\\"identity\\\"},\\\"required\\\":true},\\\"installationKey\\\":{\\\"type\\\":\\\"text\\\",\\\"_meta\\\":{\\\"__statedOptions\\\":[\\\"nullable\\\",\\\"required\\\"],\\\"nullable\\\":true,\\\"required\\\":false},\\\"required\\\":false},\\\"repositoryKey\\\":{\\\"type\\\":\\\"text\\\",\\\"_meta\\\":{\\\"__statedOptions\\\":[\\\"nullable\\\",\\\"required\\\"],\\\"nullable\\\":true,\\\"required\\\":false},\\\"required\\\":false},\\\"eventName\\\":{\\\"type\\\":\\\"text\\\",\\\"_meta\\\":{\\\"__statedOptions\\\":[]},\\\"required\\\":false},\\\"payload\\\":{\\\"type\\\":\\\"json\\\",\\\"_meta\\\":{\\\"__statedOptions\\\":[]},\\\"required\\\":false},\\\"status\\\":{\\\"type\\\":\\\"text\\\",\\\"_meta\\\":{\\\"__statedOptions\\\":[\\\"required\\\",\\\"default\\\",\\\"enum\\\"],\\\"required\\\":true,\\\"default\\\":\\\"pending\\\"},\\\"required\\\":true,\\\"default\\\":\\\"pending\\\",\\\"enum\\\":[\\\"pending\\\",\\\"leased\\\",\\\"retry\\\",\\\"completed\\\",\\\"dead_letter\\\"]},\\\"attempts\\\":{\\\"type\\\":\\\"integer\\\",\\\"_meta\\\":{\\\"__statedOptions\\\":[\\\"required\\\",\\\"default\\\"],\\\"required\\\":true,\\\"default\\\":0},\\\"required\\\":true,\\\"default\\\":0},\\\"maxAttempts\\\":{\\\"type\\\":\\\"integer\\\",\\\"_meta\\\":{\\\"__statedOptions\\\":[\\\"required\\\",\\\"default\\\"],\\\"required\\\":true,\\\"default\\\":5},\\\"required\\\":true,\\\"default\\\":5},\\\"receivedAt\\\":{\\\"type\\\":\\\"datetime\\\",\\\"_meta\\\":{\\\"__statedOptions\\\":[\\\"required\\\"],\\\"required\\\":true},\\\"required\\\":true},\\\"nextAttemptAt\\\":{\\\"type\\\":\\\"datetime\\\",\\\"_meta\\\":{\\\"__statedOptions\\\":[\\\"required\\\"],\\\"required\\\":true},\\\"required\\\":true},\\\"leaseOwner\\\":{\\\"type\\\":\\\"text\\\",\\\"_meta\\\":{\\\"__statedOptions\\\":[\\\"nullable\\\",\\\"required\\\"],\\\"nullable\\\":true,\\\"required\\\":false},\\\"required\\\":false},\\\"leaseToken\\\":{\\\"type\\\":\\\"text\\\",\\\"_meta\\\":{\\\"__statedOptions\\\":[\\\"nullable\\\",\\\"required\\\"],\\\"nullable\\\":true,\\\"required\\\":false},\\\"required\\\":false},\\\"leaseExpiresAt\\\":{\\\"type\\\":\\\"datetime\\\",\\\"_meta\\\":{\\\"__statedOptions\\\":[\\\"nullable\\\",\\\"required\\\"],\\\"nullable\\\":true,\\\"required\\\":false},\\\"required\\\":false},\\\"lastError\\\":{\\\"type\\\":\\\"text\\\",\\\"_meta\\\":{\\\"__statedOptions\\\":[\\\"nullable\\\",\\\"required\\\"],\\\"nullable\\\":true,\\\"required\\\":false},\\\"required\\\":false},\\\"completedAt\\\":{\\\"type\\\":\\\"datetime\\\",\\\"_meta\\\":{\\\"__statedOptions\\\":[\\\"nullable\\\",\\\"required\\\"],\\\"nullable\\\":true,\\\"required\\\":false},\\\"required\\\":false},\\\"replayCount\\\":{\\\"type\\\":\\\"integer\\\",\\\"_meta\\\":{\\\"__statedOptions\\\":[\\\"required\\\",\\\"default\\\"],\\\"required\\\":true,\\\"default\\\":0},\\\"required\\\":true,\\\"default\\\":0}},\\\"methods\\\":{},\\\"decoratorConfig\\\":{\\\"tableName\\\":\\\"_smrt_forge_deliveries\\\",\\\"conflictColumns\\\":[\\\"tenant_id\\\",\\\"provider\\\",\\\"delivery_id\\\"],\\\"api\\\":false,\\\"cli\\\":false,\\\"mcp\\\":false,\\\"indexes\\\":[{\\\"name\\\":\\\"_smrt_forge_deliveries_status_next_attempt_at_idx\\\",\\\"columns\\\":[\\\"status\\\",\\\"nextAttemptAt\\\"]},{\\\"name\\\":\\\"_smrt_forge_deliveries_status_lease_expires_at_idx\\\",\\\"columns\\\":[\\\"status\\\",\\\"leaseExpiresAt\\\"]}],\\\"tenantScoped\\\":{\\\"mode\\\":\\\"required\\\"}},\\\"extends\\\":\\\"SmrtObject\\\",\\\"exportName\\\":\\\"ForgeDelivery\\\",\\\"collectionExportName\\\":\\\"ForgeDeliveryCollection\\\",\\\"validationRules\\\":[{\\\"field\\\":\\\"provider\\\",\\\"rule\\\":\\\"required\\\",\\\"fieldType\\\":\\\"text\\\"},{\\\"field\\\":\\\"deliveryId\\\",\\\"rule\\\":\\\"required\\\",\\\"fieldType\\\":\\\"text\\\"},{\\\"field\\\":\\\"status\\\",\\\"rule\\\":\\\"required\\\",\\\"fieldType\\\":\\\"text\\\"},{\\\"field\\\":\\\"attempts\\\",\\\"rule\\\":\\\"required\\\",\\\"fieldType\\\":\\\"integer\\\"},{\\\"field\\\":\\\"maxAttempts\\\",\\\"rule\\\":\\\"required\\\",\\\"fieldType\\\":\\\"integer\\\"},{\\\"field\\\":\\\"receivedAt\\\",\\\"rule\\\":\\\"required\\\",\\\"fieldType\\\":\\\"datetime\\\"},{\\\"field\\\":\\\"nextAttemptAt\\\",\\\"rule\\\":\\\"required\\\",\\\"fieldType\\\":\\\"datetime\\\"},{\\\"field\\\":\\\"replayCount\\\",\\\"rule\\\":\\\"required\\\",\\\"fieldType\\\":\\\"integer\\\"}],\\\"schema\\\":{\\\"tableName\\\":\\\"_smrt_forge_deliveries\\\",\\\"ddl\\\":\\\"CREATE TABLE IF NOT EXISTS \\\\\\\"_smrt_forge_deliveries\\\\\\\" (\\\\n \\\\\\\"_sync_origin_device_id\\\\\\\" TEXT,\\\\n \\\\\\\"_sync_revision\\\\\\\" INTEGER,\\\\n \\\\\\\"id\\\\\\\" UUID PRIMARY KEY NOT NULL,\\\\n \\\\\\\"slug\\\\\\\" TEXT NOT NULL,\\\\n \\\\\\\"context\\\\\\\" TEXT NOT NULL DEFAULT '',\\\\n \\\\\\\"created_at\\\\\\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\\\n \\\\\\\"updated_at\\\\\\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\\\n \\\\\\\"tenant_id\\\\\\\" UUID NOT NULL,\\\\n \\\\\\\"provider\\\\\\\" TEXT NOT NULL,\\\\n \\\\\\\"delivery_id\\\\\\\" TEXT NOT NULL,\\\\n \\\\\\\"installation_key\\\\\\\" TEXT,\\\\n \\\\\\\"repository_key\\\\\\\" TEXT,\\\\n \\\\\\\"event_name\\\\\\\" TEXT,\\\\n \\\\\\\"payload\\\\\\\" JSON,\\\\n \\\\\\\"status\\\\\\\" TEXT NOT NULL DEFAULT 'pending',\\\\n \\\\\\\"attempts\\\\\\\" INTEGER NOT NULL DEFAULT 0,\\\\n \\\\\\\"max_attempts\\\\\\\" INTEGER NOT NULL DEFAULT 5,\\\\n \\\\\\\"received_at\\\\\\\" TIMESTAMP NOT NULL,\\\\n \\\\\\\"next_attempt_at\\\\\\\" TIMESTAMP NOT NULL,\\\\n \\\\\\\"lease_owner\\\\\\\" TEXT,\\\\n \\\\\\\"lease_token\\\\\\\" TEXT,\\\\n \\\\\\\"lease_expires_at\\\\\\\" TIMESTAMP,\\\\n \\\\\\\"last_error\\\\\\\" TEXT,\\\\n \\\\\\\"completed_at\\\\\\\" TIMESTAMP,\\\\n \\\\\\\"replay_count\\\\\\\" INTEGER NOT NULL DEFAULT 0\\\\n);\\\",\\\"columns\\\":{\\\"_sync_origin_device_id\\\":{\\\"type\\\":\\\"TEXT\\\"},\\\"_sync_revision\\\":{\\\"type\\\":\\\"INTEGER\\\"},\\\"id\\\":{\\\"type\\\":\\\"UUID\\\",\\\"primaryKey\\\":true,\\\"referenceKind\\\":\\\"id\\\",\\\"notNull\\\":true},\\\"slug\\\":{\\\"type\\\":\\\"TEXT\\\",\\\"notNull\\\":true},\\\"context\\\":{\\\"type\\\":\\\"TEXT\\\",\\\"notNull\\\":true,\\\"default\\\":\\\"\\\"},\\\"created_at\\\":{\\\"type\\\":\\\"TIMESTAMP\\\",\\\"notNull\\\":true,\\\"default\\\":\\\"current_timestamp\\\"},\\\"updated_at\\\":{\\\"type\\\":\\\"TIMESTAMP\\\",\\\"notNull\\\":true,\\\"default\\\":\\\"current_timestamp\\\"},\\\"tenant_id\\\":{\\\"type\\\":\\\"UUID\\\",\\\"referenceKind\\\":\\\"tenantId\\\",\\\"notNull\\\":true,\\\"unique\\\":false},\\\"provider\\\":{\\\"type\\\":\\\"TEXT\\\",\\\"notNull\\\":true,\\\"unique\\\":false},\\\"delivery_id\\\":{\\\"type\\\":\\\"TEXT\\\",\\\"notNull\\\":true,\\\"unique\\\":false},\\\"installation_key\\\":{\\\"type\\\":\\\"TEXT\\\",\\\"notNull\\\":false,\\\"unique\\\":false},\\\"repository_key\\\":{\\\"type\\\":\\\"TEXT\\\",\\\"notNull\\\":false,\\\"unique\\\":false},\\\"event_name\\\":{\\\"type\\\":\\\"TEXT\\\",\\\"notNull\\\":false,\\\"unique\\\":false},\\\"payload\\\":{\\\"type\\\":\\\"JSON\\\",\\\"notNull\\\":false,\\\"unique\\\":false},\\\"status\\\":{\\\"type\\\":\\\"TEXT\\\",\\\"notNull\\\":true,\\\"unique\\\":false,\\\"default\\\":\\\"pending\\\"},\\\"attempts\\\":{\\\"type\\\":\\\"INTEGER\\\",\\\"notNull\\\":true,\\\"unique\\\":false,\\\"default\\\":0},\\\"max_attempts\\\":{\\\"type\\\":\\\"INTEGER\\\",\\\"notNull\\\":true,\\\"unique\\\":false,\\\"default\\\":5},\\\"received_at\\\":{\\\"type\\\":\\\"TIMESTAMP\\\",\\\"notNull\\\":true,\\\"unique\\\":false},\\\"next_attempt_at\\\":{\\\"type\\\":\\\"TIMESTAMP\\\",\\\"notNull\\\":true,\\\"unique\\\":false},\\\"lease_owner\\\":{\\\"type\\\":\\\"TEXT\\\",\\\"notNull\\\":false,\\\"unique\\\":false},\\\"lease_token\\\":{\\\"type\\\":\\\"TEXT\\\",\\\"notNull\\\":false,\\\"unique\\\":false},\\\"lease_expires_at\\\":{\\\"type\\\":\\\"TIMESTAMP\\\",\\\"notNull\\\":false,\\\"unique\\\":false},\\\"last_error\\\":{\\\"type\\\":\\\"TEXT\\\",\\\"notNull\\\":false,\\\"unique\\\":false},\\\"completed_at\\\":{\\\"type\\\":\\\"TIMESTAMP\\\",\\\"notNull\\\":false,\\\"unique\\\":false},\\\"replay_count\\\":{\\\"type\\\":\\\"INTEGER\\\",\\\"notNull\\\":true,\\\"unique\\\":false,\\\"default\\\":0}},\\\"indexes\\\":[{\\\"name\\\":\\\"_smrt_forge_deliveries_tenant_id_provider_idx\\\",\\\"columns\\\":[\\\"tenant_id\\\",\\\"provider\\\",\\\"delivery_id\\\"],\\\"unique\\\":true},{\\\"name\\\":\\\"_smrt_forge_deliveries_slug_context_idx\\\",\\\"columns\\\":[\\\"slug\\\",\\\"context\\\"]},{\\\"name\\\":\\\"_smrt_forge_deliveries_status_next_attempt_at_idx\\\",\\\"columns\\\":[\\\"status\\\",\\\"next_attempt_at\\\"]},{\\\"name\\\":\\\"_smrt_forge_deliveries_status_lease_expires_at_idx\\\",\\\"columns\\\":[\\\"status\\\",\\\"lease_expires_at\\\"]},{\\\"name\\\":\\\"_smrt_forge_deliveries_tenant_id_created_at_idx\\\",\\\"columns\\\":[\\\"tenant_id\\\",\\\"created_at\\\"]}],\\\"version\\\":\\\"870ae64b\\\"},\\\"importPath\\\":\\\"@happyvertical/smrt-jobs\\\"},\\\"@happyvertical/smrt-jobs:ForgeProjectionCheckpoint\\\":{\\\"name\\\":\\\"forgeprojectioncheckpoint\\\",\\\"className\\\":\\\"ForgeProjectionCheckpoint\\\",\\\"qualifiedName\\\":\\\"@happyvertical/smrt-jobs:ForgeProjectionCheckpoint\\\",\\\"collection\\\":\\\"forgeprojectioncheckpoints\\\",\\\"filePath\\\":\\\"src/forge-projection.ts\\\",\\\"packageName\\\":\\\"@happyvertical/smrt-jobs\\\",\\\"fields\\\":{\\\"tenantId\\\":{\\\"type\\\":\\\"text\\\",\\\"_meta\\\":{\\\"__tenancy\\\":{\\\"isTenantIdField\\\":true,\\\"autoFilter\\\":true,\\\"required\\\":true,\\\"autoPopulate\\\":true,\\\"nullable\\\":false,\\\"mode\\\":\\\"required\\\",\\\"field\\\":\\\"tenantId\\\",\\\"allowSuperAdminBypass\\\":false},\\\"__statedOptions\\\":[\\\"sqlType\\\",\\\"requiredFor\\\",\\\"__tenancy\\\"],\\\"sqlType\\\":\\\"UUID\\\",\\\"requiredFor\\\":\\\"tenant-scope\\\"},\\\"required\\\":true},\\\"projection\\\":{\\\"type\\\":\\\"text\\\",\\\"_meta\\\":{\\\"__statedOptions\\\":[\\\"required\\\",\\\"requiredFor\\\"],\\\"required\\\":true,\\\"requiredFor\\\":\\\"identity\\\"},\\\"required\\\":true},\\\"subjectKey\\\":{\\\"type\\\":\\\"text\\\",\\\"_meta\\\":{\\\"__statedOptions\\\":[\\\"required\\\",\\\"requiredFor\\\"],\\\"required\\\":true,\\\"requiredFor\\\":\\\"identity\\\"},\\\"required\\\":true},\\\"observationVersion\\\":{\\\"type\\\":\\\"integer\\\",\\\"_meta\\\":{\\\"__statedOptions\\\":[\\\"required\\\"],\\\"required\\\":true},\\\"required\\\":true},\\\"deliveryId\\\":{\\\"type\\\":\\\"text\\\",\\\"_meta\\\":{\\\"__statedOptions\\\":[]},\\\"required\\\":false},\\\"observedAt\\\":{\\\"type\\\":\\\"datetime\\\",\\\"_meta\\\":{\\\"__statedOptions\\\":[\\\"required\\\"],\\\"required\\\":true},\\\"required\\\":true}},\\\"methods\\\":{},\\\"decoratorConfig\\\":{\\\"tableName\\\":\\\"_smrt_forge_projection_checkpoints\\\",\\\"conflictColumns\\\":[\\\"tenant_id\\\",\\\"projection\\\",\\\"subject_key\\\"],\\\"api\\\":false,\\\"cli\\\":false,\\\"mcp\\\":false,\\\"tenantScoped\\\":{\\\"mode\\\":\\\"required\\\"}},\\\"extends\\\":\\\"SmrtObject\\\",\\\"exportName\\\":\\\"ForgeProjectionCheckpoint\\\",\\\"collectionExportName\\\":\\\"ForgeProjectionCheckpointCollection\\\",\\\"validationRules\\\":[{\\\"field\\\":\\\"projection\\\",\\\"rule\\\":\\\"required\\\",\\\"fieldType\\\":\\\"text\\\"},{\\\"field\\\":\\\"subjectKey\\\",\\\"rule\\\":\\\"required\\\",\\\"fieldType\\\":\\\"text\\\"},{\\\"field\\\":\\\"observationVersion\\\",\\\"rule\\\":\\\"required\\\",\\\"fieldType\\\":\\\"integer\\\"},{\\\"field\\\":\\\"observedAt\\\",\\\"rule\\\":\\\"required\\\",\\\"fieldType\\\":\\\"datetime\\\"}],\\\"schema\\\":{\\\"tableName\\\":\\\"_smrt_forge_projection_checkpoints\\\",\\\"ddl\\\":\\\"CREATE TABLE IF NOT EXISTS \\\\\\\"_smrt_forge_projection_checkpoints\\\\\\\" (\\\\n \\\\\\\"_sync_origin_device_id\\\\\\\" TEXT,\\\\n \\\\\\\"_sync_revision\\\\\\\" INTEGER,\\\\n \\\\\\\"id\\\\\\\" UUID PRIMARY KEY NOT NULL,\\\\n \\\\\\\"slug\\\\\\\" TEXT NOT NULL,\\\\n \\\\\\\"context\\\\\\\" TEXT NOT NULL DEFAULT '',\\\\n \\\\\\\"created_at\\\\\\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\\\n \\\\\\\"updated_at\\\\\\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\\\n \\\\\\\"tenant_id\\\\\\\" UUID NOT NULL,\\\\n \\\\\\\"projection\\\\\\\" TEXT NOT NULL,\\\\n \\\\\\\"subject_key\\\\\\\" TEXT NOT NULL,\\\\n \\\\\\\"observation_version\\\\\\\" INTEGER NOT NULL,\\\\n \\\\\\\"delivery_id\\\\\\\" TEXT,\\\\n \\\\\\\"observed_at\\\\\\\" TIMESTAMP NOT NULL\\\\n);\\\",\\\"columns\\\":{\\\"_sync_origin_device_id\\\":{\\\"type\\\":\\\"TEXT\\\"},\\\"_sync_revision\\\":{\\\"type\\\":\\\"INTEGER\\\"},\\\"id\\\":{\\\"type\\\":\\\"UUID\\\",\\\"primaryKey\\\":true,\\\"referenceKind\\\":\\\"id\\\",\\\"notNull\\\":true},\\\"slug\\\":{\\\"type\\\":\\\"TEXT\\\",\\\"notNull\\\":true},\\\"context\\\":{\\\"type\\\":\\\"TEXT\\\",\\\"notNull\\\":true,\\\"default\\\":\\\"\\\"},\\\"created_at\\\":{\\\"type\\\":\\\"TIMESTAMP\\\",\\\"notNull\\\":true,\\\"default\\\":\\\"current_timestamp\\\"},\\\"updated_at\\\":{\\\"type\\\":\\\"TIMESTAMP\\\",\\\"notNull\\\":true,\\\"default\\\":\\\"current_timestamp\\\"},\\\"tenant_id\\\":{\\\"type\\\":\\\"UUID\\\",\\\"referenceKind\\\":\\\"tenantId\\\",\\\"notNull\\\":true,\\\"unique\\\":false},\\\"projection\\\":{\\\"type\\\":\\\"TEXT\\\",\\\"notNull\\\":true,\\\"unique\\\":false},\\\"subject_key\\\":{\\\"type\\\":\\\"TEXT\\\",\\\"notNull\\\":true,\\\"unique\\\":false},\\\"observation_version\\\":{\\\"type\\\":\\\"INTEGER\\\",\\\"notNull\\\":true,\\\"unique\\\":false},\\\"delivery_id\\\":{\\\"type\\\":\\\"TEXT\\\",\\\"notNull\\\":false,\\\"unique\\\":false},\\\"observed_at\\\":{\\\"type\\\":\\\"TIMESTAMP\\\",\\\"notNull\\\":true,\\\"unique\\\":false}},\\\"indexes\\\":[{\\\"name\\\":\\\"_smrt_forge_projection_checkpoints_tenant_id_projection_idx\\\",\\\"columns\\\":[\\\"tenant_id\\\",\\\"projection\\\",\\\"subject_key\\\"],\\\"unique\\\":true},{\\\"name\\\":\\\"_smrt_forge_projection_checkpoints_slug_context_idx\\\",\\\"columns\\\":[\\\"slug\\\",\\\"context\\\"]},{\\\"name\\\":\\\"_smrt_forge_projection_checkpoints_tenant_id_created_at_idx\\\",\\\"columns\\\":[\\\"tenant_id\\\",\\\"created_at\\\"]}],\\\"version\\\":\\\"4493e9ae\\\"},\\\"importPath\\\":\\\"@happyvertical/smrt-jobs\\\"},\\\"@happyvertical/smrt-jobs:ForgeDeliveryCollection\\\":{\\\"name\\\":\\\"forgedeliverycollection\\\",\\\"className\\\":\\\"ForgeDeliveryCollection\\\",\\\"qualifiedName\\\":\\\"@happyvertical/smrt-jobs:ForgeDeliveryCollection\\\",\\\"collection\\\":\\\"forgedeliveries\\\",\\\"description\\\":\\\"Durable provider delivery inbox.\\\",\\\"filePath\\\":\\\"src/forge-projection.ts\\\",\\\"packageName\\\":\\\"@happyvertical/smrt-jobs\\\",\\\"fields\\\":{},\\\"methods\\\":{\\\"accept\\\":{\\\"name\\\":\\\"accept\\\",\\\"async\\\":true,\\\"parameters\\\":[{\\\"name\\\":\\\"input\\\",\\\"type\\\":\\\"AcceptForgeDeliveryInput\\\",\\\"optional\\\":false},{\\\"name\\\":\\\"audit\\\",\\\"type\\\":\\\"ForgeProjectionAuditHook\\\",\\\"optional\\\":true,\\\"resolvedType\\\":\\\"Function\\\"}],\\\"returnType\\\":\\\"Promise<AcceptedForgeDelivery>\\\",\\\"isStatic\\\":false,\\\"isPublic\\\":true},\\\"claimReady\\\":{\\\"name\\\":\\\"claimReady\\\",\\\"async\\\":true,\\\"parameters\\\":[{\\\"name\\\":\\\"options\\\",\\\"type\\\":\\\"ClaimForgeDeliveryOptions\\\",\\\"optional\\\":false},{\\\"name\\\":\\\"audit\\\",\\\"type\\\":\\\"ForgeProjectionAuditHook\\\",\\\"optional\\\":true,\\\"resolvedType\\\":\\\"Function\\\"}],\\\"returnType\\\":\\\"Promise<ForgeDelivery | null>\\\",\\\"isStatic\\\":false,\\\"isPublic\\\":true},\\\"replay\\\":{\\\"name\\\":\\\"replay\\\",\\\"async\\\":true,\\\"parameters\\\":[{\\\"name\\\":\\\"id\\\",\\\"type\\\":\\\"string\\\",\\\"optional\\\":false},{\\\"name\\\":\\\"audit\\\",\\\"type\\\":\\\"ForgeProjectionAuditHook\\\",\\\"optional\\\":true,\\\"resolvedType\\\":\\\"Function\\\"}],\\\"returnType\\\":\\\"Promise<boolean>\\\",\\\"isStatic\\\":false,\\\"isPublic\\\":true}},\\\"decoratorConfig\\\":{\\\"api\\\":false,\\\"cli\\\":false,\\\"mcp\\\":false,\\\"tableName\\\":\\\"_smrt_forge_deliveries\\\"},\\\"extends\\\":\\\"SmrtCollection\\\",\\\"extendsTypeArg\\\":\\\"ForgeDelivery\\\",\\\"exportName\\\":\\\"ForgeDeliveryCollection\\\",\\\"collectionExportName\\\":\\\"ForgeDeliveryCollectionCollection\\\",\\\"collectionOf\\\":\\\"@happyvertical/smrt-jobs:ForgeDelivery\\\",\\\"schema\\\":{\\\"tableName\\\":\\\"_smrt_forge_deliveries\\\",\\\"ddl\\\":\\\"CREATE TABLE IF NOT EXISTS \\\\\\\"_smrt_forge_deliveries\\\\\\\" (\\\\n \\\\\\\"_sync_origin_device_id\\\\\\\" TEXT,\\\\n \\\\\\\"_sync_revision\\\\\\\" INTEGER,\\\\n \\\\\\\"id\\\\\\\" UUID PRIMARY KEY NOT NULL,\\\\n \\\\\\\"slug\\\\\\\" TEXT NOT NULL,\\\\n \\\\\\\"context\\\\\\\" TEXT NOT NULL DEFAULT '',\\\\n \\\\\\\"created_at\\\\\\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\\\n \\\\\\\"updated_at\\\\\\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\\\n \\\\\\\"tenant_id\\\\\\\" UUID NOT NULL,\\\\n \\\\\\\"provider\\\\\\\" TEXT NOT NULL,\\\\n \\\\\\\"delivery_id\\\\\\\" TEXT NOT NULL,\\\\n \\\\\\\"installation_key\\\\\\\" TEXT,\\\\n \\\\\\\"repository_key\\\\\\\" TEXT,\\\\n \\\\\\\"event_name\\\\\\\" TEXT,\\\\n \\\\\\\"payload\\\\\\\" JSON,\\\\n \\\\\\\"status\\\\\\\" TEXT NOT NULL DEFAULT 'pending',\\\\n \\\\\\\"attempts\\\\\\\" INTEGER NOT NULL DEFAULT 0,\\\\n \\\\\\\"max_attempts\\\\\\\" INTEGER NOT NULL DEFAULT 5,\\\\n \\\\\\\"received_at\\\\\\\" TIMESTAMP NOT NULL,\\\\n \\\\\\\"next_attempt_at\\\\\\\" TIMESTAMP NOT NULL,\\\\n \\\\\\\"lease_owner\\\\\\\" TEXT,\\\\n \\\\\\\"lease_token\\\\\\\" TEXT,\\\\n \\\\\\\"lease_expires_at\\\\\\\" TIMESTAMP,\\\\n \\\\\\\"last_error\\\\\\\" TEXT,\\\\n \\\\\\\"completed_at\\\\\\\" TIMESTAMP,\\\\n \\\\\\\"replay_count\\\\\\\" INTEGER NOT NULL DEFAULT 0\\\\n);\\\",\\\"columns\\\":{\\\"_sync_origin_device_id\\\":{\\\"type\\\":\\\"TEXT\\\"},\\\"_sync_revision\\\":{\\\"type\\\":\\\"INTEGER\\\"},\\\"id\\\":{\\\"type\\\":\\\"UUID\\\",\\\"primaryKey\\\":true,\\\"referenceKind\\\":\\\"id\\\",\\\"notNull\\\":true},\\\"slug\\\":{\\\"type\\\":\\\"TEXT\\\",\\\"notNull\\\":true},\\\"context\\\":{\\\"type\\\":\\\"TEXT\\\",\\\"notNull\\\":true,\\\"default\\\":\\\"\\\"},\\\"created_at\\\":{\\\"type\\\":\\\"TIMESTAMP\\\",\\\"notNull\\\":true,\\\"default\\\":\\\"current_timestamp\\\"},\\\"updated_at\\\":{\\\"type\\\":\\\"TIMESTAMP\\\",\\\"notNull\\\":true,\\\"default\\\":\\\"current_timestamp\\\"},\\\"tenant_id\\\":{\\\"type\\\":\\\"UUID\\\",\\\"referenceKind\\\":\\\"tenantId\\\",\\\"notNull\\\":true,\\\"unique\\\":false},\\\"provider\\\":{\\\"type\\\":\\\"TEXT\\\",\\\"notNull\\\":true,\\\"unique\\\":false},\\\"delivery_id\\\":{\\\"type\\\":\\\"TEXT\\\",\\\"notNull\\\":true,\\\"unique\\\":false},\\\"installation_key\\\":{\\\"type\\\":\\\"TEXT\\\",\\\"notNull\\\":false,\\\"unique\\\":false},\\\"repository_key\\\":{\\\"type\\\":\\\"TEXT\\\",\\\"notNull\\\":false,\\\"unique\\\":false},\\\"event_name\\\":{\\\"type\\\":\\\"TEXT\\\",\\\"notNull\\\":false,\\\"unique\\\":false},\\\"payload\\\":{\\\"type\\\":\\\"JSON\\\",\\\"notNull\\\":false,\\\"unique\\\":false},\\\"status\\\":{\\\"type\\\":\\\"TEXT\\\",\\\"notNull\\\":true,\\\"unique\\\":false,\\\"default\\\":\\\"pending\\\"},\\\"attempts\\\":{\\\"type\\\":\\\"INTEGER\\\",\\\"notNull\\\":true,\\\"unique\\\":false,\\\"default\\\":0},\\\"max_attempts\\\":{\\\"type\\\":\\\"INTEGER\\\",\\\"notNull\\\":true,\\\"unique\\\":false,\\\"default\\\":5},\\\"received_at\\\":{\\\"type\\\":\\\"TIMESTAMP\\\",\\\"notNull\\\":true,\\\"unique\\\":false},\\\"next_attempt_at\\\":{\\\"type\\\":\\\"TIMESTAMP\\\",\\\"notNull\\\":true,\\\"unique\\\":false},\\\"lease_owner\\\":{\\\"type\\\":\\\"TEXT\\\",\\\"notNull\\\":false,\\\"unique\\\":false},\\\"lease_token\\\":{\\\"type\\\":\\\"TEXT\\\",\\\"notNull\\\":false,\\\"unique\\\":false},\\\"lease_expires_at\\\":{\\\"type\\\":\\\"TIMESTAMP\\\",\\\"notNull\\\":false,\\\"unique\\\":false},\\\"last_error\\\":{\\\"type\\\":\\\"TEXT\\\",\\\"notNull\\\":false,\\\"unique\\\":false},\\\"completed_at\\\":{\\\"type\\\":\\\"TIMESTAMP\\\",\\\"notNull\\\":false,\\\"unique\\\":false},\\\"replay_count\\\":{\\\"type\\\":\\\"INTEGER\\\",\\\"notNull\\\":true,\\\"unique\\\":false,\\\"default\\\":0}},\\\"indexes\\\":[{\\\"name\\\":\\\"_smrt_forge_deliveries_tenant_id_provider_idx\\\",\\\"columns\\\":[\\\"tenant_id\\\",\\\"provider\\\",\\\"delivery_id\\\"],\\\"unique\\\":true},{\\\"name\\\":\\\"_smrt_forge_deliveries_slug_context_idx\\\",\\\"columns\\\":[\\\"slug\\\",\\\"context\\\"]},{\\\"name\\\":\\\"_smrt_forge_deliveries_status_next_attempt_at_idx\\\",\\\"columns\\\":[\\\"status\\\",\\\"next_attempt_at\\\"]},{\\\"name\\\":\\\"_smrt_forge_deliveries_status_lease_expires_at_idx\\\",\\\"columns\\\":[\\\"status\\\",\\\"lease_expires_at\\\"]},{\\\"name\\\":\\\"_smrt_forge_deliveries_tenant_id_created_at_idx\\\",\\\"columns\\\":[\\\"tenant_id\\\",\\\"created_at\\\"]}],\\\"version\\\":\\\"870ae64b\\\"},\\\"importPath\\\":\\\"@happyvertical/smrt-jobs\\\"},\\\"@happyvertical/smrt-jobs:SmrtJobDedupeSlot\\\":{\\\"name\\\":\\\"smrtjobdedupeslot\\\",\\\"className\\\":\\\"SmrtJobDedupeSlot\\\",\\\"qualifiedName\\\":\\\"@happyvertical/smrt-jobs:SmrtJobDedupeSlot\\\",\\\"collection\\\":\\\"smrtjobdedupeslots\\\",\\\"description\\\":\\\"Store-owned serialization row for a tenant-partitioned job deduplication key.\\\",\\\"filePath\\\":\\\"src/smrt-job-dedupe-slot.ts\\\",\\\"packageName\\\":\\\"@happyvertical/smrt-jobs\\\",\\\"fields\\\":{\\\"slotKey\\\":{\\\"type\\\":\\\"text\\\",\\\"_meta\\\":{\\\"__statedOptions\\\":[\\\"required\\\",\\\"requiredFor\\\",\\\"unique\\\"],\\\"required\\\":true,\\\"requiredFor\\\":\\\"idempotency\\\",\\\"unique\\\":true},\\\"required\\\":true},\\\"jobId\\\":{\\\"type\\\":\\\"text\\\",\\\"_meta\\\":{\\\"__statedOptions\\\":[\\\"nullable\\\",\\\"required\\\"],\\\"nullable\\\":true,\\\"required\\\":false},\\\"required\\\":false}},\\\"methods\\\":{},\\\"decoratorConfig\\\":{\\\"tableName\\\":\\\"_smrt_job_dedupe_slots\\\",\\\"api\\\":false,\\\"cli\\\":false,\\\"mcp\\\":false},\\\"extends\\\":\\\"SmrtObject\\\",\\\"exportName\\\":\\\"SmrtJobDedupeSlot\\\",\\\"collectionExportName\\\":\\\"SmrtJobDedupeSlotCollection\\\",\\\"validationRules\\\":[{\\\"field\\\":\\\"slotKey\\\",\\\"rule\\\":\\\"required\\\",\\\"fieldType\\\":\\\"text\\\"}],\\\"schema\\\":{\\\"tableName\\\":\\\"_smrt_job_dedupe_slots\\\",\\\"ddl\\\":\\\"CREATE TABLE IF NOT EXISTS \\\\\\\"_smrt_job_dedupe_slots\\\\\\\" (\\\\n \\\\\\\"_sync_origin_device_id\\\\\\\" TEXT,\\\\n \\\\\\\"_sync_revision\\\\\\\" INTEGER,\\\\n \\\\\\\"id\\\\\\\" UUID PRIMARY KEY NOT NULL,\\\\n \\\\\\\"slug\\\\\\\" TEXT NOT NULL,\\\\n \\\\\\\"context\\\\\\\" TEXT NOT NULL DEFAULT '',\\\\n \\\\\\\"created_at\\\\\\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\\\n \\\\\\\"updated_at\\\\\\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\\\n \\\\\\\"slot_key\\\\\\\" TEXT NOT NULL UNIQUE,\\\\n \\\\\\\"job_id\\\\\\\" TEXT\\\\n);\\\",\\\"columns\\\":{\\\"_sync_origin_device_id\\\":{\\\"type\\\":\\\"TEXT\\\"},\\\"_sync_revision\\\":{\\\"type\\\":\\\"INTEGER\\\"},\\\"id\\\":{\\\"type\\\":\\\"UUID\\\",\\\"primaryKey\\\":true,\\\"referenceKind\\\":\\\"id\\\",\\\"notNull\\\":true},\\\"slug\\\":{\\\"type\\\":\\\"TEXT\\\",\\\"notNull\\\":true},\\\"context\\\":{\\\"type\\\":\\\"TEXT\\\",\\\"notNull\\\":true,\\\"default\\\":\\\"\\\"},\\\"created_at\\\":{\\\"type\\\":\\\"TIMESTAMP\\\",\\\"notNull\\\":true,\\\"default\\\":\\\"current_timestamp\\\"},\\\"updated_at\\\":{\\\"type\\\":\\\"TIMESTAMP\\\",\\\"notNull\\\":true,\\\"default\\\":\\\"current_timestamp\\\"},\\\"slot_key\\\":{\\\"type\\\":\\\"TEXT\\\",\\\"notNull\\\":true,\\\"unique\\\":true},\\\"job_id\\\":{\\\"type\\\":\\\"TEXT\\\",\\\"notNull\\\":false,\\\"unique\\\":false}},\\\"indexes\\\":[{\\\"name\\\":\\\"_smrt_job_dedupe_slots_slug_context_idx\\\",\\\"columns\\\":[\\\"slug\\\",\\\"context\\\"],\\\"unique\\\":true},{\\\"name\\\":\\\"_smrt_job_dedupe_slots_created_at_idx\\\",\\\"columns\\\":[\\\"created_at\\\"]}],\\\"version\\\":\\\"f876c2d7\\\"},\\\"importPath\\\":\\\"@happyvertical/smrt-jobs\\\"},\\\"@happyvertical/smrt-jobs:SmrtJobDedupeSlotCollection\\\":{\\\"name\\\":\\\"smrtjobdedupeslotcollection\\\",\\\"className\\\":\\\"SmrtJobDedupeSlotCollection\\\",\\\"qualifiedName\\\":\\\"@happyvertical/smrt-jobs:SmrtJobDedupeSlotCollection\\\",\\\"collection\\\":\\\"smrtjobdedupeslots\\\",\\\"description\\\":\\\"Internal collection for provisioning the registered store-owned model.\\\",\\\"filePath\\\":\\\"src/smrt-job-dedupe-slot.ts\\\",\\\"packageName\\\":\\\"@happyvertical/smrt-jobs\\\",\\\"fields\\\":{},\\\"methods\\\":{},\\\"decoratorConfig\\\":{\\\"tableName\\\":\\\"_smrt_job_dedupe_slots\\\",\\\"api\\\":false,\\\"mcp\\\":false,\\\"cli\\\":false},\\\"extends\\\":\\\"SmrtCollection\\\",\\\"extendsTypeArg\\\":\\\"SmrtJobDedupeSlot\\\",\\\"exportName\\\":\\\"SmrtJobDedupeSlotCollection\\\",\\\"collectionExportName\\\":\\\"SmrtJobDedupeSlotCollectionCollection\\\",\\\"collectionOf\\\":\\\"@happyvertical/smrt-jobs:SmrtJobDedupeSlot\\\",\\\"inheritedExposure\\\":[\\\"api\\\",\\\"mcp\\\",\\\"cli\\\"],\\\"schema\\\":{\\\"tableName\\\":\\\"_smrt_job_dedupe_slots\\\",\\\"ddl\\\":\\\"CREATE TABLE IF NOT EXISTS \\\\\\\"_smrt_job_dedupe_slots\\\\\\\" (\\\\n \\\\\\\"_sync_origin_device_id\\\\\\\" TEXT,\\\\n \\\\\\\"_sync_revision\\\\\\\" INTEGER,\\\\n \\\\\\\"id\\\\\\\" UUID PRIMARY KEY NOT NULL,\\\\n \\\\\\\"slug\\\\\\\" TEXT NOT NULL,\\\\n \\\\\\\"context\\\\\\\" TEXT NOT NULL DEFAULT '',\\\\n \\\\\\\"created_at\\\\\\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\\\n \\\\\\\"updated_at\\\\\\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\\\n \\\\\\\"slot_key\\\\\\\" TEXT NOT NULL UNIQUE,\\\\n \\\\\\\"job_id\\\\\\\" TEXT\\\\n);\\\",\\\"columns\\\":{\\\"_sync_origin_device_id\\\":{\\\"type\\\":\\\"TEXT\\\"},\\\"_sync_revision\\\":{\\\"type\\\":\\\"INTEGER\\\"},\\\"id\\\":{\\\"type\\\":\\\"UUID\\\",\\\"primaryKey\\\":true,\\\"referenceKind\\\":\\\"id\\\",\\\"notNull\\\":true},\\\"slug\\\":{\\\"type\\\":\\\"TEXT\\\",\\\"notNull\\\":true},\\\"context\\\":{\\\"type\\\":\\\"TEXT\\\",\\\"notNull\\\":true,\\\"default\\\":\\\"\\\"},\\\"created_at\\\":{\\\"type\\\":\\\"TIMESTAMP\\\",\\\"notNull\\\":true,\\\"default\\\":\\\"current_timestamp\\\"},\\\"updated_at\\\":{\\\"type\\\":\\\"TIMESTAMP\\\",\\\"notNull\\\":true,\\\"default\\\":\\\"current_timestamp\\\"},\\\"slot_key\\\":{\\\"type\\\":\\\"TEXT\\\",\\\"notNull\\\":true,\\\"unique\\\":true},\\\"job_id\\\":{\\\"type\\\":\\\"TEXT\\\",\\\"notNull\\\":false,\\\"unique\\\":false}},\\\"indexes\\\":[{\\\"name\\\":\\\"_smrt_job_dedupe_slots_slug_context_idx\\\",\\\"columns\\\":[\\\"slug\\\",\\\"context\\\"],\\\"unique\\\":true},{\\\"name\\\":\\\"_smrt_job_dedupe_slots_created_at_idx\\\",\\\"columns\\\":[\\\"created_at\\\"]}],\\\"version\\\":\\\"f876c2d7\\\"},\\\"importPath\\\":\\\"@happyvertical/smrt-jobs\\\"},\\\"@happyvertical/smrt-jobs:SmrtJobEventCollection\\\":{\\\"name\\\":\\\"smrtjobeventcollection\\\",\\\"className\\\":\\\"SmrtJobEventCollection\\\",\\\"qualifiedName\\\":\\\"@happyvertical/smrt-jobs:SmrtJobEventCollection\\\",\\\"collection\\\":\\\"smrtjobevents\\\",\\\"filePath\\\":\\\"src/smrt-job-event.ts\\\",\\\"packageName\\\":\\\"@happyvertical/smrt-jobs\\\",\\\"fields\\\":{},\\\"methods\\\":{\\\"initialize\\\":{\\\"name\\\":\\\"initialize\\\",\\\"async\\\":true,\\\"parameters\\\":[],\\\"returnType\\\":\\\"Promise<this>\\\",\\\"isStatic\\\":false,\\\"isPublic\\\":true},\\\"append\\\":{\\\"name\\\":\\\"append\\\",\\\"async\\\":true,\\\"parameters\\\":[{\\\"name\\\":\\\"input\\\",\\\"type\\\":\\\"SmrtJobEventData\\\",\\\"optional\\\":false}],\\\"returnType\\\":\\\"Promise<SmrtJobEvent>\\\",\\\"isStatic\\\":false,\\\"isPublic\\\":true},\\\"listByJob\\\":{\\\"name\\\":\\\"listByJob\\\",\\\"async\\\":true,\\\"parameters\\\":[{\\\"name\\\":\\\"jobId\\\",\\\"type\\\":\\\"string\\\",\\\"optional\\\":false},{\\\"name\\\":\\\"options\\\",\\\"type\\\":\\\"ListJobEventsOptions\\\",\\\"optional\\\":true}],\\\"returnType\\\":\\\"Promise<SmrtJobEvent[]>\\\",\\\"isStatic\\\":false,\\\"isPublic\\\":true},\\\"listSinceCursor\\\":{\\\"name\\\":\\\"listSinceCursor\\\",\\\"async\\\":true,\\\"parameters\\\":[{\\\"name\\\":\\\"options\\\",\\\"type\\\":\\\"any\\\",\\\"optional\\\":true,\\\"typeUnresolved\\\":true}],\\\"returnType\\\":\\\"Promise<SmrtJobEvent[]>\\\",\\\"isStatic\\\":false,\\\"isPublic\\\":true},\\\"latestProgressByJobIds\\\":{\\\"name\\\":\\\"latestProgressByJobIds\\\",\\\"async\\\":true,\\\"parameters\\\":[{\\\"name\\\":\\\"jobIds\\\",\\\"type\\\":\\\"string[]\\\",\\\"optional\\\":false},{\\\"name\\\":\\\"options\\\",\\\"type\\\":\\\"object\\\",\\\"optional\\\":true,\\\"memberTypes\\\":[\\\"string | null\\\"]}],\\\"returnType\\\":\\\"Promise<Map<string, SmrtJobEvent>>\\\",\\\"isStatic\\\":false,\\\"isPublic\\\":true},\\\"listTerminalOutcomes\\\":{\\\"name\\\":\\\"listTerminalOutcomes\\\",\\\"async\\\":true,\\\"parameters\\\":[{\\\"name\\\":\\\"options\\\",\\\"type\\\":\\\"ListTerminalOutcomesOptions\\\",\\\"optional\\\":false}],\\\"returnType\\\":\\\"Promise<SmrtJobTerminalOutcomePage>\\\",\\\"isStatic\\\":false,\\\"isPublic\\\":true},\\\"getTerminalOutcome\\\":{\\\"name\\\":\\\"getTerminalOutcome\\\",\\\"async\\\":true,\\\"parameters\\\":[{\\\"name\\\":\\\"jobId\\\",\\\"type\\\":\\\"string\\\",\\\"optional\\\":false},{\\\"name\\\":\\\"options\\\",\\\"type\\\":\\\"GetTerminalOutcomeOptions\\\",\\\"optional\\\":false}],\\\"returnType\\\":\\\"Promise<SmrtJobTerminalOutcome | null>\\\",\\\"isStatic\\\":false,\\\"isPublic\\\":true},\\\"cleanup\\\":{\\\"name\\\":\\\"cleanup\\\",\\\"async\\\":true,\\\"parameters\\\":[{\\\"name\\\":\\\"options\\\",\\\"type\\\":\\\"object\\\",\\\"optional\\\":false,\\\"memberTypes\\\":[\\\"Date\\\",\\\"boolean\\\"]}],\\\"returnType\\\":\\\"Promise<number>\\\",\\\"isStatic\\\":false,\\\"isPublic\\\":true}},\\\"decoratorConfig\\\":{\\\"tableName\\\":\\\"_smrt_job_events\\\",\\\"api\\\":false,\\\"mcp\\\":false,\\\"cli\\\":{\\\"include\\\":[\\\"list\\\",\\\"get\\\"],\\\"skipApiCheck\\\":true}},\\\"extends\\\":\\\"SmrtCollection\\\",\\\"extendsTypeArg\\\":\\\"SmrtJobEvent\\\",\\\"exportName\\\":\\\"SmrtJobEventCollection\\\",\\\"collectionExportName\\\":\\\"SmrtJobEventCollectionCollection\\\",\\\"collectionOf\\\":\\\"@happyvertical/smrt-jobs:SmrtJobEvent\\\",\\\"inheritedExposure\\\":[\\\"api\\\",\\\"mcp\\\",\\\"cli\\\"],\\\"schema\\\":{\\\"tableName\\\":\\\"_smrt_job_events\\\",\\\"ddl\\\":\\\"CREATE TABLE IF NOT EXISTS \\\\\\\"_smrt_job_events\\\\\\\" (\\\\n \\\\\\\"_sync_origin_device_id\\\\\\\" TEXT,\\\\n \\\\\\\"_sync_revision\\\\\\\" INTEGER,\\\\n \\\\\\\"id\\\\\\\" UUID PRIMARY KEY NOT NULL,\\\\n \\\\\\\"slug\\\\\\\" TEXT NOT NULL,\\\\n \\\\\\\"context\\\\\\\" TEXT NOT NULL DEFAULT '',\\\\n \\\\\\\"created_at\\\\\\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\\\n \\\\\\\"updated_at\\\\\\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\\\n \\\\\\\"tenant_id\\\\\\\" UUID,\\\\n \\\\\\\"job_id\\\\\\\" UUID NOT NULL,\\\\n \\\\\\\"type\\\\\\\" TEXT NOT NULL DEFAULT 'log',\\\\n \\\\\\\"level\\\\\\\" TEXT NOT NULL DEFAULT 'info',\\\\n \\\\\\\"stage\\\\\\\" TEXT,\\\\n \\\\\\\"progress\\\\\\\" INTEGER,\\\\n \\\\\\\"message\\\\\\\" TEXT DEFAULT '',\\\\n \\\\\\\"data\\\\\\\" JSON\\\\n);\\\",\\\"columns\\\":{\\\"_sync_origin_device_id\\\":{\\\"type\\\":\\\"TEXT\\\"},\\\"_sync_revision\\\":{\\\"type\\\":\\\"INTEGER\\\"},\\\"id\\\":{\\\"type\\\":\\\"UUID\\\",\\\"primaryKey\\\":true,\\\"referenceKind\\\":\\\"id\\\",\\\"notNull\\\":true},\\\"slug\\\":{\\\"type\\\":\\\"TEXT\\\",\\\"notNull\\\":true},\\\"context\\\":{\\\"type\\\":\\\"TEXT\\\",\\\"notNull\\\":true,\\\"default\\\":\\\"\\\"},\\\"created_at\\\":{\\\"type\\\":\\\"TIMESTAMP\\\",\\\"notNull\\\":true,\\\"default\\\":\\\"current_timestamp\\\"},\\\"updated_at\\\":{\\\"type\\\":\\\"TIMESTAMP\\\",\\\"notNull\\\":true,\\\"default\\\":\\\"current_timestamp\\\"},\\\"tenant_id\\\":{\\\"type\\\":\\\"UUID\\\",\\\"referenceKind\\\":\\\"tenantId\\\",\\\"notNull\\\":false,\\\"unique\\\":false},\\\"job_id\\\":{\\\"type\\\":\\\"UUID\\\",\\\"referenceKind\\\":\\\"foreignKey\\\",\\\"notNull\\\":true,\\\"unique\\\":false},\\\"type\\\":{\\\"type\\\":\\\"TEXT\\\",\\\"notNull\\\":true,\\\"unique\\\":false,\\\"default\\\":\\\"log\\\"},\\\"level\\\":{\\\"type\\\":\\\"TEXT\\\",\\\"notNull\\\":true,\\\"unique\\\":false,\\\"default\\\":\\\"info\\\"},\\\"stage\\\":{\\\"type\\\":\\\"TEXT\\\",\\\"notNull\\\":false,\\\"unique\\\":false},\\\"progress\\\":{\\\"type\\\":\\\"INTEGER\\\",\\\"notNull\\\":false,\\\"unique\\\":false},\\\"message\\\":{\\\"type\\\":\\\"TEXT\\\",\\\"notNull\\\":false,\\\"unique\\\":false,\\\"default\\\":\\\"\\\"},\\\"data\\\":{\\\"type\\\":\\\"JSON\\\",\\\"notNull\\\":false,\\\"unique\\\":false}},\\\"indexes\\\":[{\\\"name\\\":\\\"_smrt_job_events_slug_context_idx\\\",\\\"columns\\\":[\\\"tenant_id\\\",\\\"slug\\\",\\\"context\\\"],\\\"unique\\\":true,\\\"nullsNotDistinct\\\":true},{\\\"name\\\":\\\"_smrt_job_events_tenant_id_created_at_idx\\\",\\\"columns\\\":[\\\"tenant_id\\\",\\\"created_at\\\"]},{\\\"name\\\":\\\"_smrt_job_events_job_id_idx\\\",\\\"columns\\\":[\\\"job_id\\\"]}],\\\"version\\\":\\\"8645e1da\\\"},\\\"importPath\\\":\\\"@happyvertical/smrt-jobs\\\"},\\\"@happyvertical/smrt-jobs:SmrtJob\\\":{\\\"name\\\":\\\"smrtjob\\\",\\\"className\\\":\\\"SmrtJob\\\",\\\"qualifiedName\\\":\\\"@happyvertical/smrt-jobs:SmrtJob\\\",\\\"collection\\\":\\\"smrtjobs\\\",\\\"description\\\":\\\"Persistent job record stored in the _smrt_jobs system table.\\\",\\\"filePath\\\":\\\"src/smrt-job.ts\\\",\\\"packageName\\\":\\\"@happyvertical/smrt-jobs\\\",\\\"fields\\\":{\\\"tenantId\\\":{\\\"type\\\":\\\"text\\\",\\\"_meta\\\":{\\\"__tenancy\\\":{\\\"isTenantIdField\\\":true,\\\"autoFilter\\\":true,\\\"required\\\":false,\\\"autoPopulate\\\":true,\\\"nullable\\\":true,\\\"mode\\\":\\\"optional\\\",\\\"field\\\":\\\"tenantId\\\",\\\"allowSuperAdminBypass\\\":false},\\\"__statedOptions\\\":[\\\"sqlType\\\",\\\"nullable\\\",\\\"__tenancy\\\",\\\"required\\\"],\\\"sqlType\\\":\\\"UUID\\\",\\\"nullable\\\":true,\\\"required\\\":false},\\\"required\\\":false},\\\"dedupeKey\\\":{\\\"type\\\":\\\"text\\\",\\\"_meta\\\":{\\\"__statedOptions\\\":[\\\"nullable\\\",\\\"indexed\\\",\\\"required\\\"],\\\"nullable\\\":true,\\\"indexed\\\":true,\\\"required\\\":false},\\\"required\\\":false},\\\"queue\\\":{\\\"type\\\":\\\"text\\\",\\\"_meta\\\":{\\\"__statedOptions\\\":[\\\"required\\\",\\\"default\\\"],\\\"required\\\":true,\\\"default\\\":\\\"default\\\"},\\\"required\\\":true,\\\"default\\\":\\\"default\\\"},\\\"objectType\\\":{\\\"type\\\":\\\"text\\\",\\\"_meta\\\":{\\\"__statedOptions\\\":[\\\"required\\\",\\\"requiredFor\\\"],\\\"required\\\":true,\\\"requiredFor\\\":\\\"identity\\\"},\\\"required\\\":true},\\\"objectId\\\":{\\\"type\\\":\\\"text\\\",\\\"_meta\\\":{\\\"__statedOptions\\\":[\\\"nullable\\\",\\\"required\\\"],\\\"nullable\\\":true,\\\"required\\\":false},\\\"required\\\":false},\\\"method\\\":{\\\"type\\\":\\\"text\\\",\\\"_meta\\\":{\\\"__statedOptions\\\":[\\\"required\\\",\\\"requiredFor\\\"],\\\"required\\\":true,\\\"requiredFor\\\":\\\"identity\\\"},\\\"required\\\":true},\\\"args\\\":{\\\"type\\\":\\\"json\\\",\\\"_meta\\\":{\\\"__statedOptions\\\":[]},\\\"required\\\":false},\\\"runAt\\\":{\\\"type\\\":\\\"datetime\\\",\\\"_meta\\\":{\\\"__statedOptions\\\":[\\\"required\\\",\\\"indexed\\\"],\\\"required\\\":true,\\\"indexed\\\":true},\\\"required\\\":true},\\\"priority\\\":{\\\"type\\\":\\\"integer\\\",\\\"_meta\\\":{\\\"__statedOptions\\\":[\\\"required\\\",\\\"default\\\"],\\\"required\\\":true,\\\"default\\\":50},\\\"required\\\":true,\\\"default\\\":50},\\\"status\\\":{\\\"type\\\":\\\"text\\\",\\\"_meta\\\":{\\\"__statedOptions\\\":[\\\"required\\\",\\\"default\\\",\\\"indexed\\\",\\\"enum\\\"],\\\"required\\\":true,\\\"default\\\":\\\"pending\\\",\\\"indexed\\\":true},\\\"required\\\":true,\\\"default\\\":\\\"pending\\\",\\\"enum\\\":[\\\"pending\\\",\\\"ready\\\",\\\"running\\\",\\\"completed\\\",\\\"failed\\\",\\\"cancelled\\\"]},\\\"attempts\\\":{\\\"type\\\":\\\"integer\\\",\\\"_meta\\\":{\\\"__statedOptions\\\":[\\\"required\\\",\\\"default\\\"],\\\"required\\\":true,\\\"default\\\":0},\\\"required\\\":true,\\\"default\\\":0},\\\"maxAttempts\\\":{\\\"type\\\":\\\"integer\\\",\\\"_meta\\\":{\\\"__statedOptions\\\":[\\\"required\\\",\\\"default\\\"],\\\"required\\\":true,\\\"default\\\":3},\\\"required\\\":true,\\\"default\\\":3},\\\"timeout\\\":{\\\"type\\\":\\\"integer\\\",\\\"_meta\\\":{\\\"__statedOptions\\\":[\\\"required\\\",\\\"default\\\"],\\\"required\\\":true,\\\"default\\\":300000},\\\"required\\\":true,\\\"default\\\":300000},\\\"timeoutBehavior\\\":{\\\"type\\\":\\\"text\\\",\\\"_meta\\\":{\\\"__statedOptions\\\":[\\\"required\\\",\\\"default\\\",\\\"enum\\\"],\\\"required\\\":true,\\\"default\\\":\\\"fail\\\"},\\\"required\\\":true,\\\"default\\\":\\\"fail\\\",\\\"enum\\\":[\\\"fail\\\",\\\"kill\\\",\\\"warn\\\"]},\\\"startedAt\\\":{\\\"type\\\":\\\"datetime\\\",\\\"_meta\\\":{\\\"__statedOptions\\\":[\\\"nullable\\\",\\\"required\\\"],\\\"nullable\\\":true,\\\"required\\\":false},\\\"required\\\":false},\\\"completedAt\\\":{\\\"type\\\":\\\"datetime\\\",\\\"_meta\\\":{\\\"__statedOptions\\\":[\\\"nullable\\\",\\\"required\\\"],\\\"nullable\\\":true,\\\"required\\\":false},\\\"required\\\":false},\\\"lastError\\\":{\\\"type\\\":\\\"text\\\",\\\"_meta\\\":{\\\"__statedOptions\\\":[\\\"nullable\\\",\\\"required\\\"],\\\"nullable\\\":true,\\\"required\\\":false},\\\"required\\\":false},\\\"resultPointer\\\":{\\\"type\\\":\\\"text\\\",\\\"_meta\\\":{\\\"__statedOptions\\\":[\\\"nullable\\\",\\\"required\\\"],\\\"nullable\\\":true,\\\"required\\\":false},\\\"required\\\":false},\\\"taskId\\\":{\\\"type\\\":\\\"text\\\",\\\"_meta\\\":{\\\"__statedOptions\\\":[\\\"nullable\\\",\\\"unique\\\",\\\"required\\\"],\\\"nullable\\\":true,\\\"unique\\\":true,\\\"required\\\":false},\\\"required\\\":false},\\\"taskOwnerId\\\":{\\\"type\\\":\\\"text\\\",\\\"_meta\\\":{\\\"__statedOptions\\\":[\\\"nullable\\\",\\\"required\\\"],\\\"nullable\\\":true,\\\"required\\\":false},\\\"required\\\":false},\\\"taskResult\\\":{\\\"type\\\":\\\"json\\\",\\\"_meta\\\":{\\\"__statedOptions\\\":[\\\"nullable\\\",\\\"required\\\"],\\\"nullable\\\":true,\\\"required\\\":false},\\\"required\\\":false},\\\"taskInputRequests\\\":{\\\"type\\\":\\\"json\\\",\\\"_meta\\\":{\\\"__statedOptions\\\":[\\\"nullable\\\",\\\"required\\\"],\\\"nullable\\\":true,\\\"required\\\":false},\\\"required\\\":false},\\\"taskInputResponses\\\":{\\\"type\\\":\\\"json\\\",\\\"_meta\\\":{\\\"__statedOptions\\\":[\\\"nullable\\\",\\\"required\\\"],\\\"nullable\\\":true,\\\"required\\\":false},\\\"required\\\":false},\\\"retryStrategy\\\":{\\\"type\\\":\\\"json\\\",\\\"_meta\\\":{\\\"__statedOptions\\\":[]},\\\"required\\\":false},\\\"workerId\\\":{\\\"type\\\":\\\"text\\\",\\\"_meta\\\":{\\\"__statedOptions\\\":[\\\"nullable\\\",\\\"required\\\"],\\\"nullable\\\":true,\\\"required\\\":false},\\\"required\\\":false},\\\"workerHeartbeat\\\":{\\\"type\\\":\\\"datetime\\\",\\\"_meta\\\":{\\\"__statedOptions\\\":[\\\"nullable\\\",\\\"required\\\"],\\\"nullable\\\":true,\\\"required\\\":false},\\\"required\\\":false}},\\\"methods\\\":{\\\"save\\\":{\\\"name\\\":\\\"save\\\",\\\"async\\\":true,\\\"parameters\\\":[{\\\"name\\\":\\\"options\\\",\\\"type\\\":\\\"SmrtSaveOptions\\\",\\\"optional\\\":true}],\\\"returnType\\\":\\\"Promise<this>\\\",\\\"isStatic\\\":false,\\\"isPublic\\\":true},\\\"retry\\\":{\\\"name\\\":\\\"retry\\\",\\\"async\\\":true,\\\"parameters\\\":[{\\\"name\\\":\\\"options\\\",\\\"type\\\":\\\"Pick<EnqueueJobOptions, 'transaction'>\\\",\\\"optional\\\":true}],\\\"returnType\\\":\\\"Promise<void>\\\",\\\"isStatic\\\":false,\\\"isPublic\\\":true},\\\"cancel\\\":{\\\"name\\\":\\\"cancel\\\",\\\"async\\\":true,\\\"parameters\\\":[],\\\"returnType\\\":\\\"Promise<void>\\\",\\\"isStatic\\\":false,\\\"isPublic\\\":true},\\\"getDescription\\\":{\\\"name\\\":\\\"getDescription\\\",\\\"async\\\":false,\\\"parameters\\\":[],\\\"returnType\\\":\\\"string\\\",\\\"isStatic\\\":false,\\\"isPublic\\\":true}},\\\"decoratorConfig\\\":{\\\"tableName\\\":\\\"_smrt_jobs\\\",\\\"api\\\":false,\\\"cli\\\":{\\\"include\\\":[\\\"list\\\",\\\"get\\\",\\\"retry\\\",\\\"cancel\\\"],\\\"skipApiCheck\\\":true,\\\"http\\\":false},\\\"mcp\\\":false,\\\"indexes\\\":[{\\\"name\\\":\\\"_smrt_jobs_status_run_at_idx\\\",\\\"columns\\\":[\\\"status\\\",\\\"runAt\\\"]},{\\\"name\\\":\\\"_smrt_jobs_ready_idx\\\",\\\"columns\\\":[\\\"status\\\",\\\"runAt\\\"],\\\"where\\\":\\\"status = 'pending' AND (task_input_requests IS NULL OR task_input_responses IS NOT NULL)\\\"}],\\\"tenantScoped\\\":{\\\"mode\\\":\\\"optional\\\"},\\\"conflictColumns\\\":[\\\"tenant_id\\\",\\\"slug\\\",\\\"context\\\"]},\\\"extends\\\":\\\"SmrtObject\\\",\\\"exportName\\\":\\\"SmrtJob\\\",\\\"collectionExportName\\\":\\\"SmrtJobCollection\\\",\\\"validationRules\\\":[{\\\"field\\\":\\\"queue\\\",\\\"rule\\\":\\\"required\\\",\\\"fieldType\\\":\\\"text\\\"},{\\\"field\\\":\\\"objectType\\\",\\\"rule\\\":\\\"required\\\",\\\"fieldType\\\":\\\"text\\\"},{\\\"field\\\":\\\"method\\\",\\\"rule\\\":\\\"required\\\",\\\"fieldType\\\":\\\"text\\\"},{\\\"field\\\":\\\"runAt\\\",\\\"rule\\\":\\\"required\\\",\\\"fieldType\\\":\\\"datetime\\\"},{\\\"field\\\":\\\"priority\\\",\\\"rule\\\":\\\"required\\\",\\\"fieldType\\\":\\\"integer\\\"},{\\\"field\\\":\\\"status\\\",\\\"rule\\\":\\\"required\\\",\\\"fieldType\\\":\\\"text\\\"},{\\\"field\\\":\\\"attempts\\\",\\\"rule\\\":\\\"required\\\",\\\"fieldType\\\":\\\"integer\\\"},{\\\"field\\\":\\\"maxAttempts\\\",\\\"rule\\\":\\\"required\\\",\\\"fieldType\\\":\\\"integer\\\"},{\\\"field\\\":\\\"timeout\\\",\\\"rule\\\":\\\"required\\\",\\\"fieldType\\\":\\\"integer\\\"},{\\\"field\\\":\\\"timeoutBehavior\\\",\\\"rule\\\":\\\"required\\\",\\\"fieldType\\\":\\\"text\\\"}],\\\"schema\\\":{\\\"tableName\\\":\\\"_smrt_jobs\\\",\\\"ddl\\\":\\\"CREATE TABLE IF NOT EXISTS \\\\\\\"_smrt_jobs\\\\\\\" (\\\\n \\\\\\\"_sync_origin_device_id\\\\\\\" TEXT,\\\\n \\\\\\\"_sync_revision\\\\\\\" INTEGER,\\\\n \\\\\\\"id\\\\\\\" UUID PRIMARY KEY NOT NULL,\\\\n \\\\\\\"slug\\\\\\\" TEXT NOT NULL,\\\\n \\\\\\\"context\\\\\\\" TEXT NOT NULL DEFAULT '',\\\\n \\\\\\\"created_at\\\\\\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\\\n \\\\\\\"updated_at\\\\\\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\\\n \\\\\\\"tenant_id\\\\\\\" UUID,\\\\n \\\\\\\"dedupe_key\\\\\\\" TEXT,\\\\n \\\\\\\"queue\\\\\\\" TEXT NOT NULL DEFAULT 'default',\\\\n \\\\\\\"object_type\\\\\\\" TEXT NOT NULL,\\\\n \\\\\\\"object_id\\\\\\\" TEXT,\\\\n \\\\\\\"method\\\\\\\" TEXT NOT NULL,\\\\n \\\\\\\"args\\\\\\\" JSON,\\\\n \\\\\\\"run_at\\\\\\\" TIMESTAMP NOT NULL,\\\\n \\\\\\\"priority\\\\\\\" INTEGER NOT NULL DEFAULT 50,\\\\n \\\\\\\"status\\\\\\\" TEXT NOT NULL DEFAULT 'pending',\\\\n \\\\\\\"attempts\\\\\\\" INTEGER NOT NULL DEFAULT 0,\\\\n \\\\\\\"max_attempts\\\\\\\" INTEGER NOT NULL DEFAULT 3,\\\\n \\\\\\\"timeout\\\\\\\" INTEGER NOT NULL DEFAULT 300000,\\\\n \\\\\\\"timeout_behavior\\\\\\\" TEXT NOT NULL DEFAULT 'fail',\\\\n \\\\\\\"started_at\\\\\\\" TIMESTAMP,\\\\n \\\\\\\"completed_at\\\\\\\" TIMESTAMP,\\\\n \\\\\\\"last_error\\\\\\\" TEXT,\\\\n \\\\\\\"result_pointer\\\\\\\" TEXT,\\\\n \\\\\\\"task_id\\\\\\\" TEXT UNIQUE,\\\\n \\\\\\\"task_owner_id\\\\\\\" TEXT,\\\\n \\\\\\\"task_result\\\\\\\" JSON,\\\\n \\\\\\\"task_input_requests\\\\\\\" JSON,\\\\n \\\\\\\"task_input_responses\\\\\\\" JSON,\\\\n \\\\\\\"retry_strategy\\\\\\\" JSON,\\\\n \\\\\\\"worker_id\\\\\\\" TEXT,\\\\n \\\\\\\"worker_heartbeat\\\\\\\" TIMESTAMP\\\\n);\\\",\\\"columns\\\":{\\\"_sync_origin_device_id\\\":{\\\"type\\\":\\\"TEXT\\\"},\\\"_sync_revision\\\":{\\\"type\\\":\\\"INTEGER\\\"},\\\"id\\\":{\\\"type\\\":\\\"UUID\\\",\\\"primaryKey\\\":true,\\\"referenceKind\\\":\\\"id\\\",\\\"notNull\\\":true},\\\"slug\\\":{\\\"type\\\":\\\"TEXT\\\",\\\"notNull\\\":true},\\\"context\\\":{\\\"type\\\":\\\"TEXT\\\",\\\"notNull\\\":true,\\\"default\\\":\\\"\\\"},\\\"created_at\\\":{\\\"type\\\":\\\"TIMESTAMP\\\",\\\"notNull\\\":true,\\\"default\\\":\\\"current_timestamp\\\"},\\\"updated_at\\\":{\\\"type\\\":\\\"TIMESTAMP\\\",\\\"notNull\\\":true,\\\"default\\\":\\\"current_timestamp\\\"},\\\"tenant_id\\\":{\\\"type\\\":\\\"UUID\\\",\\\"referenceKind\\\":\\\"tenantId\\\",\\\"notNull\\\":false,\\\"unique\\\":false},\\\"dedupe_key\\\":{\\\"type\\\":\\\"TEXT\\\",\\\"notNull\\\":false,\\\"unique\\\":false},\\\"queue\\\":{\\\"type\\\":\\\"TEXT\\\",\\\"notNull\\\":true,\\\"unique\\\":false,\\\"default\\\":\\\"default\\\"},\\\"object_type\\\":{\\\"type\\\":\\\"TEXT\\\",\\\"notNull\\\":true,\\\"unique\\\":false},\\\"object_id\\\":{\\\"type\\\":\\\"TEXT\\\",\\\"notNull\\\":false,\\\"unique\\\":false},\\\"method\\\":{\\\"type\\\":\\\"TEXT\\\",\\\"notNull\\\":true,\\\"unique\\\":false},\\\"args\\\":{\\\"type\\\":\\\"JSON\\\",\\\"notNull\\\":false,\\\"unique\\\":false},\\\"run_at\\\":{\\\"type\\\":\\\"TIMESTAMP\\\",\\\"notNull\\\":true,\\\"unique\\\":false},\\\"priority\\\":{\\\"type\\\":\\\"INTEGER\\\",\\\"notNull\\\":true,\\\"unique\\\":false,\\\"default\\\":50},\\\"status\\\":{\\\"type\\\":\\\"TEXT\\\",\\\"notNull\\\":true,\\\"unique\\\":false,\\\"default\\\":\\\"pending\\\"},\\\"attempts\\\":{\\\"type\\\":\\\"INTEGER\\\",\\\"notNull\\\":true,\\\"unique\\\":false,\\\"default\\\":0},\\\"max_attempts\\\":{\\\"type\\\":\\\"INTEGER\\\",\\\"notNull\\\":true,\\\"unique\\\":false,\\\"default\\\":3},\\\"timeout\\\":{\\\"type\\\":\\\"INTEGER\\\",\\\"notNull\\\":true,\\\"unique\\\":false,\\\"default\\\":300000},\\\"timeout_behavior\\\":{\\\"type\\\":\\\"TEXT\\\",\\\"notNull\\\":true,\\\"unique\\\":false,\\\"default\\\":\\\"fail\\\"},\\\"started_at\\\":{\\\"type\\\":\\\"TIMESTAMP\\\",\\\"notNull\\\":false,\\\"unique\\\":false},\\\"completed_at\\\":{\\\"type\\\":\\\"TIMESTAMP\\\",\\\"notNull\\\":false,\\\"unique\\\":false},\\\"last_error\\\":{\\\"type\\\":\\\"TEXT\\\",\\\"notNull\\\":false,\\\"unique\\\":false},\\\"result_pointer\\\":{\\\"type\\\":\\\"TEXT\\\",\\\"notNull\\\":false,\\\"unique\\\":false},\\\"task_id\\\":{\\\"type\\\":\\\"TEXT\\\",\\\"notNull\\\":false,\\\"unique\\\":true},\\\"task_owner_id\\\":{\\\"type\\\":\\\"TEXT\\\",\\\"notNull\\\":false,\\\"unique\\\":false},\\\"task_result\\\":{\\\"type\\\":\\\"JSON\\\",\\\"notNull\\\":false,\\\"unique\\\":false},\\\"task_input_requests\\\":{\\\"type\\\":\\\"JSON\\\",\\\"notNull\\\":false,\\\"unique\\\":false},\\\"task_input_responses\\\":{\\\"type\\\":\\\"JSON\\\",\\\"notNull\\\":false,\\\"unique\\\":false},\\\"retry_strategy\\\":{\\\"type\\\":\\\"JSON\\\",\\\"notNull\\\":false,\\\"unique\\\":false},\\\"worker_id\\\":{\\\"type\\\":\\\"TEXT\\\",\\\"notNull\\\":false,\\\"unique\\\":false},\\\"worker_heartbeat\\\":{\\\"type\\\":\\\"TIMESTAMP\\\",\\\"notNull\\\":false,\\\"unique\\\":false}},\\\"indexes\\\":[{\\\"name\\\":\\\"_smrt_jobs_slug_context_idx\\\",\\\"columns\\\":[\\\"tenant_id\\\",\\\"slug\\\",\\\"context\\\"],\\\"unique\\\":true,\\\"nullsNotDistinct\\\":true},{\\\"name\\\":\\\"_smrt_jobs_dedupe_key_idx\\\",\\\"columns\\\":[\\\"dedupe_key\\\"]},{\\\"name\\\":\\\"_smrt_jobs_run_at_idx\\\",\\\"columns\\\":[\\\"run_at\\\"]},{\\\"name\\\":\\\"_smrt_jobs_status_idx\\\",\\\"columns\\\":[\\\"status\\\"]},{\\\"name\\\":\\\"_smrt_jobs_status_run_at_idx\\\",\\\"columns\\\":[\\\"status\\\",\\\"run_at\\\"]},{\\\"name\\\":\\\"_smrt_jobs_ready_idx\\\",\\\"columns\\\":[\\\"status\\\",\\\"run_at\\\"],\\\"where\\\":\\\"status = 'pending' AND (task_input_requests IS NULL OR task_input_responses IS NOT NULL)\\\"},{\\\"name\\\":\\\"_smrt_jobs_tenant_id_created_at_idx\\\",\\\"columns\\\":[\\\"tenant_id\\\",\\\"created_at\\\"]}],\\\"version\\\":\\\"4cc5c3e5\\\"},\\\"importPath\\\":\\\"@happyvertical/smrt-jobs\\\"},\\\"@happyvertical/smrt-jobs:SmrtJobCollection\\\":{\\\"name\\\":\\\"smrtjobcollection\\\",\\\"className\\\":\\\"SmrtJobCollection\\\",\\\"qualifiedName\\\":\\\"@happyvertical/smrt-jobs:SmrtJobCollection\\\",\\\"collection\\\":\\\"smrtjobs\\\",\\\"description\\\":\\\"Collection for managing SmrtJob objects\\\",\\\"filePath\\\":\\\"src/smrt-job.ts\\\",\\\"packageName\\\":\\\"@happyvertical/smrt-jobs\\\",\\\"fields\\\":{},\\\"methods\\\":{\\\"initialize\\\":{\\\"name\\\":\\\"initialize\\\",\\\"async\\\":true,\\\"parameters\\\":[],\\\"returnType\\\":\\\"Promise<this>\\\",\\\"isStatic\\\":false,\\\"isPublic\\\":true},\\\"listByStatus\\\":{\\\"name\\\":\\\"listByStatus\\\",\\\"async\\\":true,\\\"parameters\\\":[{\\\"name\\\":\\\"status\\\",\\\"type\\\":\\\"JobStatus | JobStatus[]\\\",\\\"optional\\\":false,\\\"unionBranches\\\":[{\\\"type\\\":\\\"JobStatus\\\"},{\\\"type\\\":\\\"JobStatus[]\\\"}]},{\\\"name\\\":\\\"options\\\",\\\"type\\\":\\\"object\\\",\\\"optional\\\":true,\\\"memberTypes\\\":[\\\"number\\\",\\\"string\\\"]}],\\\"returnType\\\":\\\"Promise<SmrtJob[]>\\\",\\\"isStatic\\\":false,\\\"isPublic\\\":true},\\\"listReady\\\":{\\\"name\\\":\\\"listReady\\\",\\\"async\\\":true,\\\"parameters\\\":[{\\\"name\\\":\\\"options\\\",\\\"type\\\":\\\"ListReadyOptions\\\",\\\"optional\\\":true}],\\\"returnType\\\":\\\"Promise<SmrtJob[]>\\\",\\\"isStatic\\\":false,\\\"isPublic\\\":true},\\\"claimReady\\\":{\\\"name\\\":\\\"claimReady\\\",\\\"async\\\":true,\\\"parameters\\\":[{\\\"name\\\":\\\"options\\\",\\\"type\\\":\\\"ClaimReadyOptions\\\",\\\"optional\\\":false}],\\\"returnType\\\":\\\"Promise<SmrtJob[]>\\\",\\\"isStatic\\\":false,\\\"isPublic\\\":true},\\\"countInFlightForTenant\\\":{\\\"name\\\":\\\"countInFlightForTenant\\\",\\\"async\\\":true,\\\"parameters\\\":[{\\\"name\\\":\\\"tenantId\\\",\\\"type\\\":\\\"string | null\\\",\\\"optional\\\":false,\\\"unionBranches\\\":[{\\\"type\\\":\\\"string\\\"},{\\\"type\\\":\\\"null\\\"}]}],\\\"returnType\\\":\\\"Promise<number>\\\",\\\"isStatic\\\":false,\\\"isPublic\\\":true},\\\"enqueueJob\\\":{\\\"name\\\":\\\"enqueueJob\\\",\\\"async\\\":true,\\\"parameters\\\":[{\\\"name\\\":\\\"data\\\",\\\"type\\\":\\\"SmrtJobData\\\",\\\"optional\\\":false},{\\\"name\\\":\\\"options\\\",\\\"type\\\":\\\"EnqueueJobOptions\\\",\\\"optional\\\":true}],\\\"returnType\\\":\\\"Promise<SmrtJob>\\\",\\\"isStatic\\\":false,\\\"isPublic\\\":true},\\\"enqueueHandlerJob\\\":{\\\"name\\\":\\\"enqueueHandlerJob\\\",\\\"async\\\":true,\\\"parameters\\\":[{\\\"name\\\":\\\"data\\\",\\\"type\\\":\\\"HandlerJobData\\\",\\\"optional\\\":false},{\\\"name\\\":\\\"options\\\",\\\"type\\\":\\\"EnqueueJobOptions\\\",\\\"optional\\\":true}],\\\"returnType\\\":\\\"Promise<SmrtJob>\\\",\\\"isStatic\\\":false,\\\"isPublic\\\":true},\\\"stats\\\":{\\\"name\\\":\\\"stats\\\",\\\"async\\\":true,\\\"parameters\\\":[{\\\"name\\\":\\\"queue\\\",\\\"type\\\":\\\"string\\\",\\\"optional\\\":true}],\\\"returnType\\\":\\\"Promise<object>\\\",\\\"isStatic\\\":false,\\\"isPublic\\\":true},\\\"cleanup\\\":{\\\"name\\\":\\\"cleanup\\\",\\\"async\\\":true,\\\"parameters\\\":[{\\\"name\\\":\\\"options\\\",\\\"type\\\":\\\"object\\\",\\\"optional\\\":false,\\\"memberTypes\\\":[\\\"Date\\\",\\\"number\\\",\\\"boolean\\\"]}],\\\"returnType\\\":\\\"Promise<number>\\\",\\\"isStatic\\\":false,\\\"isPublic\\\":true}},\\\"decoratorConfig\\\":{\\\"tableName\\\":\\\"_smrt_jobs\\\",\\\"api\\\":false,\\\"mcp\\\":false,\\\"cli\\\":{\\\"include\\\":[\\\"list\\\",\\\"get\\\"],\\\"skipApiCheck\\\":true}},\\\"extends\\\":\\\"SmrtCollection\\\",\\\"extendsTypeArg\\\":\\\"SmrtJob\\\",\\\"exportName\\\":\\\"SmrtJobCollection\\\",\\\"collectionExportName\\\":\\\"SmrtJobCollectionCollection\\\",\\\"collectionOf\\\":\\\"@happyvertical/smrt-jobs:SmrtJob\\\",\\\"inheritedExposure\\\":[\\\"api\\\",\\\"mcp\\\",\\\"cli\\\"],\\\"schema\\\":{\\\"tableName\\\":\\\"_smrt_jobs\\\",\\\"ddl\\\":\\\"CREATE TABLE IF NOT EXISTS \\\\\\\"_smrt_jobs\\\\\\\" (\\\\n \\\\\\\"_sync_origin_device_id\\\\\\\" TEXT,\\\\n \\\\\\\"_sync_revision\\\\\\\" INTEGER,\\\\n \\\\\\\"id\\\\\\\" UUID PRIMARY KEY NOT NULL,\\\\n \\\\\\\"slug\\\\\\\" TEXT NOT NULL,\\\\n \\\\\\\"context\\\\\\\" TEXT NOT NULL DEFAULT '',\\\\n \\\\\\\"created_at\\\\\\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\\\n \\\\\\\"updated_at\\\\\\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\\\n \\\\\\\"tenant_id\\\\\\\" UUID,\\\\n \\\\\\\"dedupe_key\\\\\\\" TEXT,\\\\n \\\\\\\"queue\\\\\\\" TEXT NOT NULL DEFAULT 'default',\\\\n \\\\\\\"object_type\\\\\\\" TEXT NOT NULL,\\\\n \\\\\\\"object_id\\\\\\\" TEXT,\\\\n \\\\\\\"method\\\\\\\" TEXT NOT NULL,\\\\n \\\\\\\"args\\\\\\\" JSON,\\\\n \\\\\\\"run_at\\\\\\\" TIMESTAMP NOT NULL,\\\\n \\\\\\\"priority\\\\\\\" INTEGER NOT NULL DEFAULT 50,\\\\n \\\\\\\"status\\\\\\\" TEXT NOT NULL DEFAULT 'pending',\\\\n \\\\\\\"attempts\\\\\\\" INTEGER NOT NULL DEFAULT 0,\\\\n \\\\\\\"max_attempts\\\\\\\" INTEGER NOT NULL DEFAULT 3,\\\\n \\\\\\\"timeout\\\\\\\" INTEGER NOT NULL DEFAULT 300000,\\\\n \\\\\\\"timeout_behavior\\\\\\\" TEXT NOT NULL DEFAULT 'fail',\\\\n \\\\\\\"started_at\\\\\\\" TIMESTAMP,\\\\n \\\\\\\"completed_at\\\\\\\" TIMESTAMP,\\\\n \\\\\\\"last_error\\\\\\\" TEXT,\\\\n \\\\\\\"result_pointer\\\\\\\" TEXT,\\\\n \\\\\\\"task_id\\\\\\\" TEXT UNIQUE,\\\\n \\\\\\\"task_owner_id\\\\\\\" TEXT,\\\\n \\\\\\\"task_result\\\\\\\" JSON,\\\\n \\\\\\\"task_input_requests\\\\\\\" JSON,\\\\n \\\\\\\"task_input_responses\\\\\\\" JSON,\\\\n \\\\\\\"retry_strategy\\\\\\\" JSON,\\\\n \\\\\\\"worker_id\\\\\\\" TEXT,\\\\n \\\\\\\"worker_heartbeat\\\\\\\" TIMESTAMP\\\\n);\\\",\\\"columns\\\":{\\\"_sync_origin_device_id\\\":{\\\"type\\\":\\\"TEXT\\\"},\\\"_sync_revision\\\":{\\\"type\\\":\\\"INTEGER\\\"},\\\"id\\\":{\\\"type\\\":\\\"UUID\\\",\\\"primaryKey\\\":true,\\\"referenceKind\\\":\\\"id\\\",\\\"notNull\\\":true},\\\"slug\\\":{\\\"type\\\":\\\"TEXT\\\",\\\"notNull\\\":true},\\\"context\\\":{\\\"type\\\":\\\"TEXT\\\",\\\"notNull\\\":true,\\\"default\\\":\\\"\\\"},\\\"created_at\\\":{\\\"type\\\":\\\"TIMESTAMP\\\",\\\"notNull\\\":true,\\\"default\\\":\\\"current_timestamp\\\"},\\\"updated_at\\\":{\\\"type\\\":\\\"TIMESTAMP\\\",\\\"notNull\\\":true,\\\"default\\\":\\\"current_timestamp\\\"},\\\"tenant_id\\\":{\\\"type\\\":\\\"UUID\\\",\\\"referenceKind\\\":\\\"tenantId\\\",\\\"notNull\\\":false,\\\"unique\\\":false},\\\"dedupe_key\\\":{\\\"type\\\":\\\"TEXT\\\",\\\"notNull\\\":false,\\\"unique\\\":false},\\\"queue\\\":{\\\"type\\\":\\\"TEXT\\\",\\\"notNull\\\":true,\\\"unique\\\":false,\\\"default\\\":\\\"default\\\"},\\\"object_type\\\":{\\\"type\\\":\\\"TEXT\\\",\\\"notNull\\\":true,\\\"unique\\\":false},\\\"object_id\\\":{\\\"type\\\":\\\"TEXT\\\",\\\"notNull\\\":false,\\\"unique\\\":false},\\\"method\\\":{\\\"type\\\":\\\"TEXT\\\",\\\"notNull\\\":true,\\\"unique\\\":false},\\\"args\\\":{\\\"type\\\":\\\"JSON\\\",\\\"notNull\\\":false,\\\"unique\\\":false},\\\"run_at\\\":{\\\"type\\\":\\\"TIMESTAMP\\\",\\\"notNull\\\":true,\\\"unique\\\":false},\\\"priority\\\":{\\\"type\\\":\\\"INTEGER\\\",\\\"notNull\\\":true,\\\"unique\\\":false,\\\"default\\\":50},\\\"status\\\":{\\\"type\\\":\\\"TEXT\\\",\\\"notNull\\\":true,\\\"unique\\\":false,\\\"default\\\":\\\"pending\\\"},\\\"attempts\\\":{\\\"type\\\":\\\"INTEGER\\\",\\\"notNull\\\":true,\\\"unique\\\":false,\\\"default\\\":0},\\\"max_attempts\\\":{\\\"type\\\":\\\"INTEGER\\\",\\\"notNull\\\":true,\\\"unique\\\":false,\\\"default\\\":3},\\\"timeout\\\":{\\\"type\\\":\\\"INTEGER\\\",\\\"notNull\\\":true,\\\"unique\\\":false,\\\"default\\\":300000},\\\"timeout_behavior\\\":{\\\"type\\\":\\\"TEXT\\\",\\\"notNull\\\":true,\\\"unique\\\":false,\\\"default\\\":\\\"fail\\\"},\\\"started_at\\\":{\\\"type\\\":\\\"TIMESTAMP\\\",\\\"notNull\\\":false,\\\"unique\\\":false},\\\"completed_at\\\":{\\\"type\\\":\\\"TIMESTAMP\\\",\\\"notNull\\\":false,\\\"unique\\\":false},\\\"last_error\\\":{\\\"type\\\":\\\"TEXT\\\",\\\"notNull\\\":false,\\\"unique\\\":false},\\\"result_pointer\\\":{\\\"type\\\":\\\"TEXT\\\",\\\"notNull\\\":false,\\\"unique\\\":false},\\\"task_id\\\":{\\\"type\\\":\\\"TEXT\\\",\\\"notNull\\\":false,\\\"unique\\\":true},\\\"task_owner_id\\\":{\\\"type\\\":\\\"TEXT\\\",\\\"notNull\\\":false,\\\"unique\\\":false},\\\"task_result\\\":{\\\"type\\\":\\\"JSON\\\",\\\"notNull\\\":false,\\\"unique\\\":false},\\\"task_input_requests\\\":{\\\"type\\\":\\\"JSON\\\",\\\"notNull\\\":false,\\\"unique\\\":false},\\\"task_input_responses\\\":{\\\"type\\\":\\\"JSON\\\",\\\"notNull\\\":false,\\\"unique\\\":false},\\\"retry_strategy\\\":{\\\"type\\\":\\\"JSON\\\",\\\"notNull\\\":false,\\\"unique\\\":false},\\\"worker_id\\\":{\\\"type\\\":\\\"TEXT\\\",\\\"notNull\\\":false,\\\"unique\\\":false},\\\"worker_heartbeat\\\":{\\\"type\\\":\\\"TIMESTAMP\\\",\\\"notNull\\\":false,\\\"unique\\\":false}},\\\"indexes\\\":[{\\\"name\\\":\\\"_smrt_jobs_slug_context_idx\\\",\\\"columns\\\":[\\\"tenant_id\\\",\\\"slug\\\",\\\"context\\\"],\\\"unique\\\":true,\\\"nullsNotDistinct\\\":true},{\\\"name\\\":\\\"_smrt_jobs_dedupe_key_idx\\\",\\\"columns\\\":[\\\"dedupe_key\\\"]},{\\\"name\\\":\\\"_smrt_jobs_run_at_idx\\\",\\\"columns\\\":[\\\"run_at\\\"]},{\\\"name\\\":\\\"_smrt_jobs_status_idx\\\",\\\"columns\\\":[\\\"status\\\"]},{\\\"name\\\":\\\"_smrt_jobs_status_run_at_idx\\\",\\\"columns\\\":[\\\"status\\\",\\\"run_at\\\"]},{\\\"name\\\":\\\"_smrt_jobs_ready_idx\\\",\\\"columns\\\":[\\\"status\\\",\\\"run_at\\\"],\\\"where\\\":\\\"status = 'pending' AND (task_input_requests IS NULL OR task_input_responses IS NOT NULL)\\\"},{\\\"name\\\":\\\"_smrt_jobs_tenant_id_created_at_idx\\\",\\\"columns\\\":[\\\"tenant_id\\\",\\\"created_at\\\"]}],\\\"version\\\":\\\"4cc5c3e5\\\"},\\\"importPath\\\":\\\"@happyvertical/smrt-jobs\\\"},\\\"@happyvertical/smrt-jobs:SmrtWorker\\\":{\\\"name\\\":\\\"smrtworker\\\",\\\"className\\\":\\\"SmrtWorker\\\",\\\"qualifiedName\\\":\\\"@happyvertical/smrt-jobs:SmrtWorker\\\",\\\"collection\\\":\\\"smrtworkers\\\",\\\"description\\\":\\\"Liveness record for a single TaskRunner / ScheduleRunner incarnation, stored in the _smrt_workers system table.\\\",\\\"filePath\\\":\\\"src/smrt-worker.ts\\\",\\\"packageName\\\":\\\"@happyvertical/smrt-jobs\\\",\\\"fields\\\":{\\\"workerId\\\":{\\\"type\\\":\\\"text\\\",\\\"_meta\\\":{\\\"__statedOptions\\\":[\\\"required\\\",\\\"requiredFor\\\"],\\\"required\\\":true,\\\"requiredFor\\\":\\\"identity\\\"},\\\"required\\\":true},\\\"pid\\\":{\\\"type\\\":\\\"integer\\\",\\\"_meta\\\":{\\\"__statedOptions\\\":[\\\"nullable\\\",\\\"required\\\"],\\\"nullable\\\":true,\\\"required\\\":false},\\\"required\\\":false},\\\"hostname\\\":{\\\"type\\\":\\\"text\\\",\\\"_meta\\\":{\\\"__statedOptions\\\":[\\\"nullable\\\",\\\"required\\\"],\\\"nullable\\\":true,\\\"required\\\":false},\\\"required\\\":false},\\\"startedAt\\\":{\\\"type\\\":\\\"datetime\\\",\\\"_meta\\\":{\\\"__statedOptions\\\":[\\\"nullable\\\",\\\"required\\\"],\\\"nullable\\\":true,\\\"required\\\":false},\\\"required\\\":false},\\\"heartbeatAt\\\":{\\\"type\\\":\\\"datetime\\\",\\\"_meta\\\":{\\\"__statedOptions\\\":[\\\"nullable\\\",\\\"required\\\"],\\\"nullable\\\":true,\\\"required\\\":false},\\\"required\\\":false},\\\"leaseExpiresAt\\\":{\\\"type\\\":\\\"datetime\\\",\\\"_meta\\\":{\\\"__statedOptions\\\":[\\\"nullable\\\",\\\"required\\\"],\\\"nullable\\\":true,\\\"required\\\":false},\\\"required\\\":false},\\\"queues\\\":{\\\"type\\\":\\\"json\\\",\\\"_meta\\\":{\\\"__statedOptions\\\":[\\\"nullable\\\",\\\"required\\\"],\\\"nullable\\\":true,\\\"required\\\":false},\\\"required\\\":false},\\\"status\\\":{\\\"type\\\":\\\"text\\\",\\\"_meta\\\":{\\\"__statedOptions\\\":[\\\"required\\\",\\\"default\\\"],\\\"required\\\":true,\\\"default\\\":\\\"running\\\"},\\\"required\\\":true,\\\"default\\\":\\\"running\\\"}},\\\"methods\\\":{},\\\"decoratorConfig\\\":{\\\"tableName\\\":\\\"_smrt_workers\\\",\\\"conflictColumns\\\":[\\\"worker_id\\\"],\\\"api\\\":false,\\\"cli\\\":false,\\\"mcp\\\":false},\\\"extends\\\":\\\"SmrtObject\\\",\\\"exportName\\\":\\\"SmrtWorker\\\",\\\"collectionExportName\\\":\\\"SmrtWorkerCollection\\\",\\\"validationRules\\\":[{\\\"field\\\":\\\"workerId\\\",\\\"rule\\\":\\\"required\\\",\\\"fieldType\\\":\\\"text\\\"},{\\\"field\\\":\\\"status\\\",\\\"rule\\\":\\\"required\\\",\\\"fieldType\\\":\\\"text\\\"}],\\\"schema\\\":{\\\"tableName\\\":\\\"_smrt_workers\\\",\\\"ddl\\\":\\\"CREATE TABLE IF NOT EXISTS \\\\\\\"_smrt_workers\\\\\\\" (\\\\n \\\\\\\"_sync_origin_device_id\\\\\\\" TEXT,\\\\n \\\\\\\"_sync_revision\\\\\\\" INTEGER,\\\\n \\\\\\\"id\\\\\\\" UUID PRIMARY KEY NOT NULL,\\\\n \\\\\\\"slug\\\\\\\" TEXT NOT NULL,\\\\n \\\\\\\"context\\\\\\\" TEXT NOT NULL DEFAULT '',\\\\n \\\\\\\"created_at\\\\\\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\\\n \\\\\\\"updated_at\\\\\\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\\\n \\\\\\\"worker_id\\\\\\\" TEXT NOT NULL,\\\\n \\\\\\\"pid\\\\\\\" INTEGER,\\\\n \\\\\\\"hostname\\\\\\\" TEXT,\\\\n \\\\\\\"started_at\\\\\\\" TIMESTAMP,\\\\n \\\\\\\"heartbeat_at\\\\\\\" TIMESTAMP,\\\\n \\\\\\\"lease_expires_at\\\\\\\" TIMESTAMP,\\\\n \\\\\\\"queues\\\\\\\" JSON,\\\\n \\\\\\\"status\\\\\\\" TEXT NOT NULL DEFAULT 'running'\\\\n);\\\",\\\"columns\\\":{\\\"_sync_origin_device_id\\\":{\\\"type\\\":\\\"TEXT\\\"},\\\"_sync_revision\\\":{\\\"type\\\":\\\"INTEGER\\\"},\\\"id\\\":{\\\"type\\\":\\\"UUID\\\",\\\"primaryKey\\\":true,\\\"referenceKind\\\":\\\"id\\\",\\\"notNull\\\":true},\\\"slug\\\":{\\\"type\\\":\\\"TEXT\\\",\\\"notNull\\\":true},\\\"context\\\":{\\\"type\\\":\\\"TEXT\\\",\\\"notNull\\\":true,\\\"default\\\":\\\"\\\"},\\\"created_at\\\":{\\\"type\\\":\\\"TIMESTAMP\\\",\\\"notNull\\\":true,\\\"default\\\":\\\"current_timestamp\\\"},\\\"updated_at\\\":{\\\"type\\\":\\\"TIMESTAMP\\\",\\\"notNull\\\":true,\\\"default\\\":\\\"current_timestamp\\\"},\\\"worker_id\\\":{\\\"type\\\":\\\"TEXT\\\",\\\"notNull\\\":true,\\\"unique\\\":false},\\\"pid\\\":{\\\"type\\\":\\\"INTEGER\\\",\\\"notNull\\\":false,\\\"unique\\\":false},\\\"hostname\\\":{\\\"type\\\":\\\"TEXT\\\",\\\"notNull\\\":false,\\\"unique\\\":false},\\\"started_at\\\":{\\\"type\\\":\\\"TIMESTAMP\\\",\\\"notNull\\\":false,\\\"unique\\\":false},\\\"heartbeat_at\\\":{\\\"type\\\":\\\"TIMESTAMP\\\",\\\"notNull\\\":false,\\\"unique\\\":false},\\\"lease_expires_at\\\":{\\\"type\\\":\\\"TIMESTAMP\\\",\\\"notNull\\\":false,\\\"unique\\\":false},\\\"queues\\\":{\\\"type\\\":\\\"JSON\\\",\\\"notNull\\\":false,\\\"unique\\\":false},\\\"status\\\":{\\\"type\\\":\\\"TEXT\\\",\\\"notNull\\\":true,\\\"unique\\\":false,\\\"default\\\":\\\"running\\\"}},\\\"indexes\\\":[{\\\"name\\\":\\\"_smrt_workers_worker_id_idx\\\",\\\"columns\\\":[\\\"worker_id\\\"],\\\"unique\\\":true},{\\\"name\\\":\\\"_smrt_workers_slug_context_idx\\\",\\\"columns\\\":[\\\"slug\\\",\\\"context\\\"]},{\\\"name\\\":\\\"_smrt_workers_created_at_idx\\\",\\\"columns\\\":[\\\"created_at\\\"]}],\\\"version\\\":\\\"2cdf9341\\\"},\\\"importPath\\\":\\\"@happyvertical/smrt-jobs\\\"},\\\"@happyvertical/smrt-jobs:SmrtWorkerCollection\\\":{\\\"name\\\":\\\"smrtworkercollection\\\",\\\"className\\\":\\\"SmrtWorkerCollection\\\",\\\"qualifiedName\\\":\\\"@happyvertical/smrt-jobs:SmrtWorkerCollection\\\",\\\"collection\\\":\\\"smrtworkers\\\",\\\"description\\\":\\\"Collection for managing _smrt_workers liveness rows.\\\",\\\"filePath\\\":\\\"src/smrt-worker.ts\\\",\\\"packageName\\\":\\\"@happyvertical/smrt-jobs\\\",\\\"fields\\\":{},\\\"methods\\\":{\\\"assertReady\\\":{\\\"name\\\":\\\"assertReady\\\",\\\"async\\\":true,\\\"parameters\\\":[],\\\"returnType\\\":\\\"Promise<void>\\\",\\\"isStatic\\\":false,\\\"isPublic\\\":true},\\\"tableReady\\\":{\\\"name\\\":\\\"tableReady\\\",\\\"async\\\":true,\\\"parameters\\\":[],\\\"returnType\\\":\\\"Promise<boolean>\\\",\\\"isStatic\\\":false,\\\"isPublic\\\":true},\\\"registerWorker\\\":{\\\"name\\\":\\\"registerWorker\\\",\\\"async\\\":true,\\\"parameters\\\":[{\\\"name\\\":\\\"input\\\",\\\"type\\\":\\\"RegisterWorkerInput\\\",\\\"optional\\\":false}],\\\"returnType\\\":\\\"Promise<void>\\\",\\\"isStatic\\\":false,\\\"isPublic\\\":true},\\\"renewLease\\\":{\\\"name\\\":\\\"renewLease\\\",\\\"async\\\":true,\\\"parameters\\\":[{\\\"name\\\":\\\"workerKey\\\",\\\"type\\\":\\\"string\\\",\\\"optional\\\":false},{\\\"name\\\":\\\"leaseTtlMs\\\",\\\"type\\\":\\\"number\\\",\\\"optional\\\":false},{\\\"name\\\":\\\"queues\\\",\\\"type\\\":\\\"string[] | null\\\",\\\"optional\\\":true,\\\"unionBranches\\\":[{\\\"type\\\":\\\"string[]\\\"},{\\\"type\\\":\\\"null\\\"}]}],\\\"returnType\\\":\\\"Promise<void>\\\",\\\"isStatic\\\":false,\\\"isPublic\\\":true},\\\"expireWorker\\\":{\\\"name\\\":\\\"expireWorker\\\",\\\"async\\\":true,\\\"parameters\\\":[{\\\"name\\\":\\\"workerKey\\\",\\\"type\\\":\\\"string\\\",\\\"optional\\\":false}],\\\"returnType\\\":\\\"Promise<void>\\\",\\\"isStatic\\\":false,\\\"isPublic\\\":true},\\\"freshLeaseWorkerKeys\\\":{\\\"name\\\":\\\"freshLeaseWorkerKeys\\\",\\\"async\\\":true,\\\"parameters\\\":[],\\\"returnType\\\":\\\"Promise<Set<string>>\\\",\\\"isStatic\\\":false,\\\"isPublic\\\":true},\\\"liveWorkerKeysForQueue\\\":{\\\"name\\\":\\\"liveWorkerKeysForQueue\\\",\\\"async\\\":true,\\\"parameters\\\":[{\\\"name\\\":\\\"queue\\\",\\\"type\\\":\\\"string\\\",\\\"optional\\\":false}],\\\"returnType\\\":\\\"Promise<Set<string>>\\\",\\\"isStatic\\\":false,\\\"isPublic\\\":true},\\\"pruneExpired\\\":{\\\"name\\\":\\\"pruneExpired\\\",\\\"async\\\":true,\\\"parameters\\\":[{\\\"name\\\":\\\"graceMs\\\",\\\"type\\\":\\\"number\\\",\\\"optional\\\":false}],\\\"returnType\\\":\\\"Promise<void>\\\",\\\"isStatic\\\":false,\\\"isPublic\\\":true}},\\\"decoratorConfig\\\":{\\\"tableName\\\":\\\"_smrt_workers\\\",\\\"api\\\":false,\\\"mcp\\\":false,\\\"cli\\\":false},\\\"extends\\\":\\\"SmrtCollection\\\",\\\"extendsTypeArg\\\":\\\"SmrtWorker\\\",\\\"exportName\\\":\\\"SmrtWorkerCollection\\\",\\\"collectionExportName\\\":\\\"SmrtWorkerCollectionCollection\\\",\\\"collectionOf\\\":\\\"@happyvertical/smrt-jobs:SmrtWorker\\\",\\\"inheritedExposure\\\":[\\\"api\\\",\\\"mcp\\\",\\\"cli\\\"],\\\"schema\\\":{\\\"tableName\\\":\\\"_smrt_workers\\\",\\\"ddl\\\":\\\"CREATE TABLE IF NOT EXISTS \\\\\\\"_smrt_workers\\\\\\\" (\\\\n \\\\\\\"_sync_origin_device_id\\\\\\\" TEXT,\\\\n \\\\\\\"_sync_revision\\\\\\\" INTEGER,\\\\n \\\\\\\"id\\\\\\\" UUID PRIMARY KEY NOT NULL,\\\\n \\\\\\\"slug\\\\\\\" TEXT NOT NULL,\\\\n \\\\\\\"context\\\\\\\" TEXT NOT NULL DEFAULT '',\\\\n \\\\\\\"created_at\\\\\\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\\\n \\\\\\\"updated_at\\\\\\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\\\n \\\\\\\"worker_id\\\\\\\" TEXT NOT NULL,\\\\n \\\\\\\"pid\\\\\\\" INTEGER,\\\\n \\\\\\\"hostname\\\\\\\" TEXT,\\\\n \\\\\\\"started_at\\\\\\\" TIMESTAMP,\\\\n \\\\\\\"heartbeat_at\\\\\\\" TIMESTAMP,\\\\n \\\\\\\"lease_expires_at\\\\\\\" TIMESTAMP,\\\\n \\\\\\\"queues\\\\\\\" JSON,\\\\n \\\\\\\"status\\\\\\\" TEXT NOT NULL DEFAULT 'running'\\\\n);\\\",\\\"columns\\\":{\\\"_sync_origin_device_id\\\":{\\\"type\\\":\\\"TEXT\\\"},\\\"_sync_revision\\\":{\\\"type\\\":\\\"INTEGER\\\"},\\\"id\\\":{\\\"type\\\":\\\"UUID\\\",\\\"primaryKey\\\":true,\\\"referenceKind\\\":\\\"id\\\",\\\"notNull\\\":true},\\\"slug\\\":{\\\"type\\\":\\\"TEXT\\\",\\\"notNull\\\":true},\\\"context\\\":{\\\"type\\\":\\\"TEXT\\\",\\\"notNull\\\":true,\\\"default\\\":\\\"\\\"},\\\"created_at\\\":{\\\"type\\\":\\\"TIMESTAMP\\\",\\\"notNull\\\":true,\\\"default\\\":\\\"current_timestamp\\\"},\\\"updated_at\\\":{\\\"type\\\":\\\"TIMESTAMP\\\",\\\"notNull\\\":true,\\\"default\\\":\\\"current_timestamp\\\"},\\\"worker_id\\\":{\\\"type\\\":\\\"TEXT\\\",\\\"notNull\\\":true,\\\"unique\\\":false},\\\"pid\\\":{\\\"type\\\":\\\"INTEGER\\\",\\\"notNull\\\":false,\\\"unique\\\":false},\\\"hostname\\\":{\\\"type\\\":\\\"TEXT\\\",\\\"notNull\\\":false,\\\"unique\\\":false},\\\"started_at\\\":{\\\"type\\\":\\\"TIMESTAMP\\\",\\\"notNull\\\":false,\\\"unique\\\":false},\\\"heartbeat_at\\\":{\\\"type\\\":\\\"TIMESTAMP\\\",\\\"notNull\\\":false,\\\"unique\\\":false},\\\"lease_expires_at\\\":{\\\"type\\\":\\\"TIMESTAMP\\\",\\\"notNull\\\":false,\\\"unique\\\":false},\\\"queues\\\":{\\\"type\\\":\\\"JSON\\\",\\\"notNull\\\":false,\\\"unique\\\":false},\\\"status\\\":{\\\"type\\\":\\\"TEXT\\\",\\\"notNull\\\":true,\\\"unique\\\":false,\\\"default\\\":\\\"running\\\"}},\\\"indexes\\\":[{\\\"name\\\":\\\"_smrt_workers_worker_id_idx\\\",\\\"columns\\\":[\\\"worker_id\\\"],\\\"unique\\\":true},{\\\"name\\\":\\\"_smrt_workers_slug_context_idx\\\",\\\"columns\\\":[\\\"slug\\\",\\\"context\\\"]},{\\\"name\\\":\\\"_smrt_workers_created_at_idx\\\",\\\"columns\\\":[\\\"created_at\\\"]}],\\\"version\\\":\\\"2cdf9341\\\"},\\\"importPath\\\":\\\"@happyvertical/smrt-jobs\\\"}},\\\"moduleType\\\":\\\"smrt\\\",\\\"smrtDependencies\\\":[\\\"@happyvertical/smrt-core\\\",\\\"@happyvertical/smrt-tenancy\\\"],\\\"browser\\\":{\\\"status\\\":\\\"server-only\\\",\\\"issues\\\":[\\\"#3615\\\",\\\"#3624\\\",\\\"#3627\\\"],\\\"reason\\\":\\\"worker_threads runner (the edge commerce inherits), node:events/crypto, bull/bullmq/cloud-tasks SDK graph\\\",\\\"via\\\":[\\\"@happyvertical/smrt-tenancy\\\"]},\\\"stampsConstructors\\\":true}\"));\n","/**\n * Opt-in policy controls for background job creation and dispatch.\n *\n * @remarks\n * These guards harden the background-jobs surface flagged by the S5 audit\n * (#1402):\n *\n * - {@link MAX_JOB_RETRIES} caps the retry count a caller can request so a\n * misconfigured `.retries(n)` cannot pin a worker on a poison job forever.\n * - {@link assertWithinTenantCreationCap} bounds how many jobs a single tenant\n * may hold in the queue at once, so one tenant cannot exhaust the shared\n * worker pool (a cross-tenant denial of service).\n * - {@link isBackgroundEligibleMethod} / {@link backgroundEligible} provide an\n * opt-in allowlist of methods that may be invoked by the runner. The runner's\n * dispatch is already bounded to existing prototype methods (no eval / dynamic\n * import), but a class can further restrict which of its methods are reachable\n * from a persisted job row.\n *\n * All three live in and are enforced by this package (`@happyvertical/smrt-jobs`).\n * Other packages apply the marker (`smrt-reports`, `smrt-support`,\n * `smrt-fields`), but the only thing that reads it is `TaskRunner`'s dispatch in\n * `runner.ts`. `@happyvertical/smrt-agents` neither imports nor honours it (it depends on\n * this package only for the cron parser). Marking a method does **not** make it\n * background-eligible anywhere outside the jobs runner.\n */\n\n/**\n * Hard ceiling on retry attempts a caller may request via `.retries(n)` /\n * `bg(..., { retries })`. Requests above this are clamped (not rejected) so\n * existing callers keep working while the worst case stays bounded.\n */\nexport const MAX_JOB_RETRIES = 25;\n\n/**\n * Default maximum number of non-terminal (pending/running) jobs a single\n * tenant may hold in the queue at once. Configurable per call; `0` / negative\n * disables the cap.\n */\nexport const DEFAULT_TENANT_JOB_CAP = 10_000;\n\n/**\n * Clamp a requested retry count to {@link MAX_JOB_RETRIES}.\n *\n * @param requested - The retry count supplied by the caller.\n * @returns A non-negative integer no greater than {@link MAX_JOB_RETRIES}.\n */\nexport function clampRetries(requested: number): number {\n if (Number.isNaN(requested) || requested < 0) {\n return 0;\n }\n if (requested === Number.POSITIVE_INFINITY) {\n return MAX_JOB_RETRIES;\n }\n return Math.min(Math.floor(requested), MAX_JOB_RETRIES);\n}\n\n/**\n * Error thrown when a tenant exceeds its allowed in-flight job count.\n */\nexport class TenantJobCapExceededError extends Error {\n constructor(\n public readonly tenantId: string,\n public readonly cap: number,\n public readonly current: number,\n ) {\n super(\n `Tenant \"${tenantId}\" has reached its background-job cap ` +\n `(${current}/${cap} in-flight). Refusing to enqueue another job.`,\n );\n this.name = 'TenantJobCapExceededError';\n }\n}\n\n/**\n * Throw {@link TenantJobCapExceededError} when a tenant is at or above its cap.\n *\n * @param tenantId - Tenant the new job would belong to (`null` = global; not\n * subject to the per-tenant cap).\n * @param current - Current count of non-terminal jobs for the tenant.\n * @param cap - Maximum allowed; `<= 0` disables the check.\n */\nexport function assertWithinTenantCreationCap(\n tenantId: string | null | undefined,\n current: number,\n cap: number,\n): void {\n if (!tenantId || cap <= 0) return;\n if (current >= cap) {\n throw new TenantJobCapExceededError(tenantId, cap, current);\n }\n}\n\n/**\n * Class shape that opts into a background-method allowlist by declaring a\n * static set/array of method names.\n */\nexport interface BackgroundEligibleClass {\n /**\n * Method names that may be invoked by `TaskRunner`. When present (even if\n * empty), it is treated as an exhaustive allowlist. When absent, the runner\n * falls back to its default behaviour (any existing method).\n */\n backgroundEligibleMethods?: ReadonlyArray<string> | ReadonlySet<string>;\n}\n\n/**\n * Add method names to a class's background-eligible allowlist.\n *\n * Installs/extends a static `backgroundEligibleMethods` set on the constructor.\n * Once any method is marked, the runner refuses to dispatch a job whose\n * `method` is not in the set — turning the dispatch surface from \"any prototype\n * method\" into an explicit contract. Use this when applying the\n * {@link backgroundEligible} decorator is inconvenient. Non-decorator code can\n * skip the helper entirely and declare the static array directly, as\n * `smrt-fields` does in `usage-learning.ts`.\n *\n * @param ctor - The class constructor to annotate.\n * @param methods - Method names to allow.\n */\nexport function markBackgroundEligible(\n ctor: object,\n ...methods: string[]\n): void {\n const target = ctor as { backgroundEligibleMethods?: ReadonlySet<string> };\n const existing = target.backgroundEligibleMethods;\n const set =\n existing instanceof Set\n ? new Set<string>(existing)\n : new Set<string>(existing ?? []);\n for (const method of methods) set.add(method);\n target.backgroundEligibleMethods = set;\n}\n\n/**\n * Decorator: mark a method as background-eligible.\n *\n * This is **restrictive, not enabling**. Without it, `TaskRunner` will dispatch\n * any existing prototype method; the first `@backgroundEligible()` on a class\n * closes that surface and turns the set into an exhaustive allowlist, so every\n * *other* method on that class stops being reachable from a persisted job row.\n * Adding it to one method of an existing class is therefore a behaviour change\n * for its siblings — mark all the methods you dispatch, or none of them.\n *\n * This is a legacy (`experimentalDecorators`) method decorator — the mode the\n * SMRT monorepo compiles with. Applying it (one or more times) builds up the\n * static `backgroundEligibleMethods` allowlist on the owning class.\n *\n * @example\n * ```ts\n * class Report extends SmrtObject {\n * \\@backgroundEligible()\n * async regenerate() {} // reachable from a job\n *\n * async deleteEverything() {} // NOT reachable from a job\n * }\n * ```\n */\nexport function backgroundEligible() {\n return (\n target: object,\n propertyKey: string | symbol,\n descriptor?: PropertyDescriptor,\n ): PropertyDescriptor | undefined => {\n // Legacy method decorators receive the prototype as `target`; the class\n // constructor (where we keep the static allowlist) is `target.constructor`.\n const ctor = (target as { constructor: object }).constructor;\n markBackgroundEligible(ctor, String(propertyKey));\n return descriptor;\n };\n}\n\n/**\n * Resolve the declared allowlist for a class, if any.\n *\n * @param ctor - The target object's constructor.\n * @returns A `Set` of allowed method names, or `null` when the class did not\n * opt in (runner should fall back to default behaviour).\n */\nexport function getBackgroundEligibleMethods(\n ctor: unknown,\n): ReadonlySet<string> | null {\n const declared = (ctor as BackgroundEligibleClass | undefined)\n ?.backgroundEligibleMethods;\n if (declared == null) return null;\n return declared instanceof Set ? declared : new Set(declared);\n}\n\n/**\n * Whether a method may be invoked by the runner for a given target class.\n *\n * @param ctor - Constructor of the resolved target class.\n * @param method - Method name from the persisted job row.\n * @returns `true` when the class declared no allowlist (default) or when the\n * method is on the allowlist; `false` when an allowlist exists and excludes\n * the method.\n */\nexport function isBackgroundEligibleMethod(\n ctor: unknown,\n method: string,\n): boolean {\n const allow = getBackgroundEligibleMethods(ctor);\n if (allow == null) return true;\n return allow.has(method);\n}\n","import type { JobExecutionContext } from './logger-extension.js';\n\n/**\n * Named job handlers (#5005).\n *\n * A job targets either a model method (`objectType` is a registered class,\n * `method` one of its methods) or a handler registered here under a\n * namespaced name. A handler job is stored in `_smrt_jobs` in a reserved\n * form, with no schema change:\n *\n * - `object_type` = `handler:<name>` (see {@link JOB_HANDLER_TARGET_PREFIX})\n * - `method` = `handle` (see {@link JOB_HANDLER_METHOD})\n * - `object_id` = NULL\n * - `args` = the handler's JSON payload\n *\n * The `handler:` prefix keeps a handler name out of the model namespace: a\n * name such as `@happyvertical/smrt-workflows:workflow-run` has the grammar of\n * a qualified class name, and the registry's qualified-name fallback looks a\n * class up by that tail (`workflow-run` is not a class name today, but the\n * namespaces would overlap). `handler:@…` is not a qualified class name (its\n * package part does not start with `@`) and cannot be a class key.\n */\n\n/** Prefix that marks a stored job target as a named handler. */\nexport const JOB_HANDLER_TARGET_PREFIX = 'handler:';\n\n/** The fixed `method` value of every handler job row. */\nexport const JOB_HANDLER_METHOD = 'handle';\n\n/**\n * Most handlers one process may register. A runner's claim names each of its\n * handlers as one bound parameter (#5005 claim filter), so the registry is\n * capped to keep that statement inside every engine's parameter limit.\n */\nexport const MAX_JOB_HANDLERS = 256;\n\n/** Longest accepted handler name. */\nconst MAX_HANDLER_NAME_LENGTH = 200;\n\n/**\n * `<package>:<name>`: an npm package name (scoped or not), a colon, and a\n * lowercase kebab-case local name, optionally dotted (`run.step`).\n */\nconst HANDLER_NAME_PATTERN =\n /^(?:@[a-z0-9][a-z0-9._~-]*\\/)?[a-z0-9][a-z0-9._~-]*:[a-z][a-z0-9-]*(?:\\.[a-z][a-z0-9-]*)*$/;\n\n/** A job payload: a JSON object, exactly like a model job's `args`. */\nexport type JobHandlerPayload = Record<string, unknown>;\n\n/**\n * A named job handler. It receives the job's payload and the same runner\n * execution context a model method receives: job id, attempt, tenant, queue,\n * logger, `signal`, `event`/`progress`/`log`, and — on a runner started with\n * `claimFencing: true` — the claim read by `getJobClaim(context)`.\n * `context.job.handler` names the handler. Lease renewal is per worker, not\n * per job: the runner renews its own lease while the handler runs.\n */\nexport type JobHandler<\n TPayload extends JobHandlerPayload = JobHandlerPayload,\n TResult = unknown,\n> = (\n payload: TPayload,\n context: JobExecutionContext,\n) => Promise<TResult> | TResult;\n\n/** The stored target of a handler job. */\nexport interface JobHandlerTarget {\n objectType: string;\n method: string;\n}\n\n/** A handler name that is not `<package>:<name>`. */\nexport class JobHandlerNameError extends TypeError {\n constructor(readonly handler: unknown) {\n super(\n `Invalid job handler name ${JSON.stringify(handler)}: expected \"<package>:<name>\", e.g. \"@happyvertical/smrt-workflows:workflow-run\"`,\n );\n this.name = 'JobHandlerNameError';\n }\n}\n\n/** A second registration under a name that is already registered. */\nexport class JobHandlerAlreadyRegisteredError extends Error {\n constructor(readonly handler: string) {\n super(`Job handler already registered: ${handler}`);\n this.name = 'JobHandlerAlreadyRegisteredError';\n }\n}\n\n/** A registration past {@link MAX_JOB_HANDLERS}. */\nexport class JobHandlerLimitError extends RangeError {\n constructor(readonly handler: string) {\n super(\n `Cannot register job handler ${handler}: a process may register at most ${MAX_JOB_HANDLERS} job handlers`,\n );\n this.name = 'JobHandlerLimitError';\n }\n}\n\n/**\n * Registration or removal while a TaskRunner in this process is running.\n * Register every handler before `runner.start()`.\n */\nexport class JobHandlerRegistrationClosedError extends Error {\n constructor(readonly handler: string) {\n super(\n `Cannot change job handler ${handler} while a TaskRunner is running; register handlers before runner.start()`,\n );\n this.name = 'JobHandlerRegistrationClosedError';\n }\n}\n\n/**\n * The runner that claimed a handler job has no handler under its name. The\n * job fails terminally on that claim (failure kind `handler-unregistered`),\n * whatever its `maxAttempts`. A runner claims only the handler jobs it has\n * registered, so this is the backstop for a claim made without that filter.\n */\nexport class JobHandlerUnregisteredError extends Error {\n /** Read by the runner's retry hints: never retried. */\n readonly retryable = false;\n constructor(readonly handler: string) {\n super(`Job handler not registered: ${handler}`);\n this.name = 'JobHandlerUnregisteredError';\n }\n}\n\n/** A handler job row that is not in the canonical handler form. */\nexport class JobHandlerTargetError extends Error {\n /** Read by the runner's retry hints: never retried. */\n readonly retryable = false;\n constructor(message: string) {\n super(message);\n this.name = 'JobHandlerTargetError';\n }\n}\n\nconst REGISTRY_KEY = '__smrtJobHandlers';\n\ninterface JobHandlerRegistryState {\n handlers: Map<string, JobHandler>;\n /** Worker keys of running TaskRunners; registration is closed while any. */\n sealedBy: Set<string>;\n}\n\ntype GlobalWithJobHandlers = typeof globalThis & {\n [REGISTRY_KEY]?: JobHandlerRegistryState;\n};\n\nfunction registry(): JobHandlerRegistryState {\n const g = globalThis as GlobalWithJobHandlers;\n let state = g[REGISTRY_KEY];\n if (!state) {\n // Process-wide singleton, like the live-worker set: it survives HMR and\n // a duplicated module instance (the runner is bundled into a chunk).\n state = { handlers: new Map(), sealedBy: new Set() };\n g[REGISTRY_KEY] = state;\n }\n return state;\n}\n\n/** True when `name` is a valid namespaced handler name. */\nexport function isJobHandlerName(name: unknown): name is string {\n return (\n typeof name === 'string' &&\n name.length <= MAX_HANDLER_NAME_LENGTH &&\n HANDLER_NAME_PATTERN.test(name)\n );\n}\n\n/** Throw {@link JobHandlerNameError} unless `name` is a valid handler name. */\nexport function assertJobHandlerName(name: unknown): asserts name is string {\n if (!isJobHandlerName(name)) throw new JobHandlerNameError(name);\n}\n\nfunction assertRegistrationOpen(name: string): void {\n if (registry().sealedBy.size > 0)\n throw new JobHandlerRegistrationClosedError(name);\n}\n\n/**\n * Register a named job handler for this process. Call before any\n * `TaskRunner.start()`: a runner snapshots the registry when it starts, and\n * registration while one is running throws\n * {@link JobHandlerRegistrationClosedError}.\n *\n * @param name - Namespaced `<package>:<name>`, e.g. `@scope/pkg:workflow-run`.\n * @param handler - Called with the job payload and runner execution context.\n * @throws JobHandlerNameError, JobHandlerAlreadyRegisteredError,\n * JobHandlerLimitError, JobHandlerRegistrationClosedError\n */\nexport function registerJobHandler<\n TPayload extends JobHandlerPayload = JobHandlerPayload,\n>(name: string, handler: JobHandler<TPayload>): void {\n assertJobHandlerName(name);\n if (typeof handler !== 'function')\n throw new TypeError(`Job handler ${name} must be a function`);\n assertRegistrationOpen(name);\n const { handlers } = registry();\n if (handlers.has(name)) throw new JobHandlerAlreadyRegisteredError(name);\n if (handlers.size >= MAX_JOB_HANDLERS) throw new JobHandlerLimitError(name);\n handlers.set(name, handler as JobHandler);\n}\n\n/**\n * Remove a registered handler (tests and teardown). Closed while a runner is\n * running, like registration.\n * @returns Whether a handler was registered under `name`.\n */\nexport function unregisterJobHandler(name: string): boolean {\n assertRegistrationOpen(name);\n return registry().handlers.delete(name);\n}\n\n/** Names of the handlers registered in this process, sorted. */\nexport function listJobHandlers(): string[] {\n return [...registry().handlers.keys()].sort();\n}\n\n/** The stored job target for a handler name. */\nexport function jobHandlerTarget(name: string): JobHandlerTarget {\n assertJobHandlerName(name);\n return {\n objectType: `${JOB_HANDLER_TARGET_PREFIX}${name}`,\n method: JOB_HANDLER_METHOD,\n };\n}\n\n/** True when a stored `objectType` is in the reserved handler form. */\nexport function isJobHandlerTarget(objectType: unknown): boolean {\n return (\n typeof objectType === 'string' &&\n objectType.startsWith(JOB_HANDLER_TARGET_PREFIX)\n );\n}\n\n/**\n * The handler name of a stored `objectType`, or null for a model target. The\n * name is returned as stored; it may be invalid on a row not written through\n * the enqueue API.\n */\nexport function jobHandlerName(objectType: unknown): string | null {\n return isJobHandlerTarget(objectType)\n ? (objectType as string).slice(JOB_HANDLER_TARGET_PREFIX.length)\n : null;\n}\n\n/** @internal Close registration for a starting runner; returns its snapshot. */\nexport function sealJobHandlerRegistry(\n workerKey: string,\n): ReadonlyMap<string, JobHandler> {\n const state = registry();\n state.sealedBy.add(workerKey);\n return new Map(state.handlers);\n}\n\n/** @internal Reopen registration when that runner has stopped. */\nexport function releaseJobHandlerRegistry(workerKey: string): void {\n registry().sealedBy.delete(workerKey);\n}\n","import {\n field,\n SmrtCollection,\n SmrtObject,\n smrt,\n} from '@happyvertical/smrt-core';\n\n/**\n * Store-owned serialization row for a tenant-partitioned job deduplication key.\n *\n * The opaque hash includes tenant identity. Job pointers deliberately have no\n * physical FK: job retention can prune a terminal job before the key is reused.\n * Generated access is disabled; callers use SmrtJobCollection.enqueueJob().\n */\n@smrt({\n tableName: '_smrt_job_dedupe_slots',\n api: false,\n cli: false,\n mcp: false,\n})\nexport class SmrtJobDedupeSlot extends SmrtObject { static __smrtPackage__ = \"@happyvertical/smrt-jobs\";\n /** SHA-256 identity of the tenant and caller key. */\n @field({\n type: 'text',\n required: true,\n requiredFor: 'idempotency',\n unique: true,\n })\n slotKey: string = '';\n\n /** Last admitted job, which may already have been pruned by retention. */\n @field({ type: 'text', nullable: true })\n jobId: string | null = null;\n}\n\n/** Internal collection for provisioning the registered store-owned model. */\nexport class SmrtJobDedupeSlotCollection extends SmrtCollection<SmrtJobDedupeSlot> {\n static readonly _itemClass = SmrtJobDedupeSlot;\n}\n","import {\n detectEngine,\n SQLITE_BUSY_TIMEOUT_MS,\n setBusyTimeoutIfUnset,\n} from '@happyvertical/smrt-core';\nimport type {\n DatabaseInterface,\n ReopenOptions,\n DatabaseEngine as SqlEngine,\n} from '@happyvertical/sql';\nimport { createId } from '@happyvertical/utils';\n\ntype DatabaseEngine = ReturnType<typeof detectEngine>;\n\n/**\n * Worker liveness primitives shared by {@link ../runner.js} and\n * {@link ../schedule-runner.js}.\n *\n * Job recovery keys on whether a job's *owning worker* is alive, never on\n * per-job heartbeat freshness (issue #1474). \"Alive\" has two independent\n * sources, combined by {@link isWorkerAlive}:\n *\n * 1. **Process-global live set** — an in-memory {@link Set} of worker keys\n * whose runner is live *in this process*. Checked synchronously, so it can\n * never be starved by a CPU-bound handler holding the event loop. Covers\n * every same-process topology (a runner's own jobs, a co-located\n * ScheduleRunner, a second in-process runner).\n * 2. **Database lease** — a `_smrt_workers` row whose `lease_expires_at` is\n * still in the future. Covers cross-process recovery. The lease is renewed\n * by the owning runner; a dead worker stops renewing and its lease expires.\n *\n * The live set takes precedence: a worker live in this process is alive even\n * if its database lease looks stale.\n *\n * The lease is compared against the recovering host's clock (the same approach\n * the previous heartbeat recovery used), so it is no more sensitive to clock\n * skew than the code it replaces. For eligible engines the lease is renewed off\n * the main loop by a worker thread (see worker-liveness-ticker.ts) so a blocked\n * handler can't starve it; otherwise it is renewed on the main loop and the\n * live set covers same-process correctness.\n */\n\nconst LIVE_WORKERS_KEY = '__smrtLiveWorkers';\n\ntype GlobalWithLiveWorkers = typeof globalThis & {\n [LIVE_WORKERS_KEY]?: Set<string>;\n};\n\nfunction liveWorkers(): Set<string> {\n const g = globalThis as GlobalWithLiveWorkers;\n let set = g[LIVE_WORKERS_KEY];\n if (!set) {\n // Singleton on globalThis so it survives HMR / duplicate module instances,\n // mirroring the ObjectRegistry pattern.\n set = new Set<string>();\n g[LIVE_WORKERS_KEY] = set;\n }\n return set;\n}\n\n/** Mark a worker key as live in this process. */\nexport function registerLiveWorker(workerKey: string): void {\n liveWorkers().add(workerKey);\n}\n\n/** Remove a worker key from this process's live set. */\nexport function unregisterLiveWorker(workerKey: string): void {\n liveWorkers().delete(workerKey);\n}\n\n/** Whether a worker key is live in this process. */\nexport function isLiveWorker(workerKey: string): boolean {\n return liveWorkers().has(workerKey);\n}\n\n/** Snapshot of every worker key live in this process. */\nexport function liveWorkerKeys(): Set<string> {\n return new Set(liveWorkers());\n}\n\n/**\n * Whether a worker is alive: live in *this* process (synchronous truth, never\n * starved), or holding a fresh database lease in some process. `null`/unknown\n * worker keys are never alive.\n */\nexport function isWorkerAlive(\n workerKey: string | null | undefined,\n freshLeaseKeys: Set<string>,\n): boolean {\n if (!workerKey) return false;\n return isLiveWorker(workerKey) || freshLeaseKeys.has(workerKey);\n}\n\n/**\n * Build a per-incarnation-unique worker key.\n *\n * Recovery treats a worker key as the unit of liveness, so the key must be\n * unique per process incarnation: a runner that crashes and restarts under the\n * same configured `id` must get a *new* key, otherwise its orphaned `running`\n * jobs would look owned by the live restart and never be recovered. We append\n * a random token to the (optional) configured id, which also keeps the\n * human-facing runner id stable for logs/events.\n */\nexport function createWorkerKey(baseId: string): string {\n return `${baseId}~${createId().slice(0, 8)}`;\n}\n\n/**\n * The connection URL, honoring adapters that leave `db.url` empty and carry the\n * real URL on `db.config.url`. Used consistently for engine detection, the\n * in-memory check, and the URL handed to the off-loop thread so they never\n * disagree.\n */\nexport function resolveUrl(db: DatabaseInterface): string {\n const withConfig = db as DatabaseInterface & { config?: { url?: string } };\n return db.url || withConfig.config?.url || '';\n}\n\n/**\n * Tune a SQLite connection for the off-loop liveness topology.\n *\n * The runner's main connection and the off-loop ticker's connection both touch\n * the same file. Stock libsql/SQLite opens in rollback-journal mode with no busy\n * timeout, so the instant two connections contend it returns `SQLITE_BUSY` —\n * surfacing as a flaky \"Failed to execute raw query\" under CI load. WAL lets\n * readers run concurrently with the single writer, and `busy_timeout` makes a\n * contended writer wait for the lock instead of failing immediately. Both are\n * idempotent and file-level (WAL persists for every connection to the file).\n *\n * Best-effort: a PRAGMA failure must never break startup — the in-process live\n * set keeps same-process recovery correct regardless. Callers gate this on a\n * SQLite engine so it is never issued to Postgres.\n */\nexport async function tuneSqliteForConcurrency(\n db: DatabaseInterface,\n): Promise<void> {\n try {\n // Only when unset: a shared collection connection keeps its shorter\n // main-thread wait (#4978) and the runtime's own keeps its 5000.\n await setBusyTimeoutIfUnset(db, SQLITE_BUSY_TIMEOUT_MS);\n await db.query('PRAGMA journal_mode = WAL');\n } catch {\n // Best-effort connection tuning.\n }\n}\n\nconst enabledPgliteClients = new WeakSet<object>();\n\n/**\n * Opt a shared SDK PGlite client into PostgreSQL job SQL and main-loop leases.\n * Call before creating jobs collections or starting runners on that client.\n * Detection alone never changes existing consumers' engine selection.\n * @param db - SDK connection whose public client exposes dumpDataDir.\n */\nexport function enablePgliteJobs(db: DatabaseInterface): void {\n const client = db.client as { dumpDataDir?: unknown } | undefined;\n if (!client || typeof client.dumpDataDir !== 'function')\n throw new Error('enablePgliteJobs requires an SDK PGlite client');\n enabledPgliteClients.add(client);\n}\n\n/** Only explicitly enabled clients use the PGlite jobs path. */\nexport function isPglite(db: DatabaseInterface): boolean {\n return !!db.client && enabledPgliteClients.has(db.client as object);\n}\n\n/** Resolve the database engine for a connection. */\nexport function resolveEngine(db: DatabaseInterface): DatabaseEngine {\n if (isPglite(db)) return 'postgres';\n const withConfig = db as DatabaseInterface & {\n config?: { type?: string };\n type?: string;\n };\n const type = withConfig.type || withConfig.config?.type;\n return detectEngine(resolveUrl(db), type);\n}\n\n/**\n * Whether a connection points at an in-memory SQLite database. In-memory\n * databases are single-process (nothing to recover cross-process) and a second\n * connection cannot see the same data, so the off-loop liveness thread is\n * skipped for them.\n */\nexport function isInMemory(db: DatabaseInterface): boolean {\n const url = resolveUrl(db).toLowerCase();\n return (\n url === ':memory:' ||\n url.includes('mode=memory') ||\n url.includes('file::memory:')\n );\n}\n\n/**\n * How the off-loop liveness thread gets its database connection, or why it\n * must not run.\n *\n * - `reopen`: file-backed SQLite whose connection can be reopened on the same\n * engine (`db.engine` plus `db.reopenOptions()`). The thread opens exactly\n * those options and checks that the engine it got is `engine`.\n * - `url`: PostgreSQL, which has no second-engine hazard. The thread builds its\n * own pooled connection from the URL, as it always has.\n * - `none`: no safe second connection; the runner renews the lease on its own\n * connection from the main loop and logs `reason` once.\n *\n * Two SQLite engines (`node:sqlite`, `@libsql/client`) hold their own copy of\n * SQLite whose file locks do not coordinate, so a second connection on the\n * other engine can corrupt a WAL file (#4978). A connection that does not say\n * which engine it uses is treated as unsafe to share.\n */\nexport type LivenessConnectionPlan =\n | {\n kind: 'reopen';\n engine: SqlEngine;\n reopen: ReopenOptions;\n }\n | { kind: 'url'; url: string; type: string }\n | {\n kind: 'none';\n reason: string;\n /**\n * True where a liveness thread used to run and now cannot (file-backed\n * SQLite without a same-engine connection, or secure SQLite on Windows).\n * False for engines that never had a usable second connection\n * (in-memory SQLite, DuckDB, JSON), where main-loop renewal is the\n * long-standing design and not a degradation.\n */\n degraded: boolean;\n };\n\n/** Decide how (and whether) the liveness thread may open its connection. */\nexport function planLivenessConnection(\n db: DatabaseInterface,\n platform: NodeJS.Platform = process.platform,\n): LivenessConnectionPlan {\n if (isPglite(db)) {\n // No independent backend can open this WASM instance.\n return {\n kind: 'none',\n degraded: false,\n reason: 'a PGlite instance cannot be reached by a second connection',\n };\n }\n const engine = resolveEngine(db);\n if (engine === 'postgres') {\n return { kind: 'url', url: resolveUrl(db), type: engine };\n }\n if (engine !== 'sqlite') {\n return {\n kind: 'none',\n degraded: false,\n reason: `the ${engine} engine has one owner per database`,\n };\n }\n if (isInMemory(db)) {\n return {\n kind: 'none',\n degraded: false,\n reason:\n 'an in-memory SQLite database cannot be reached by a second connection',\n };\n }\n const dbEngine = db.engine;\n if (dbEngine !== 'node-sqlite' && dbEngine !== 'libsql') {\n return {\n kind: 'none',\n degraded: true,\n reason:\n 'the connection does not report which SQLite engine it uses, so a second connection may use a different engine on the same file',\n };\n }\n if (typeof db.reopenOptions !== 'function') {\n return {\n kind: 'none',\n degraded: true,\n reason: 'the connection cannot give options to reopen the same database',\n };\n }\n let reopen: ReopenOptions;\n try {\n reopen = db.reopenOptions();\n } catch (error) {\n return {\n kind: 'none',\n degraded: true,\n reason: `the connection cannot be reopened on the same engine (${\n error instanceof Error ? error.message : String(error)\n })`,\n };\n }\n if (\n platform === 'win32' &&\n dbEngine === 'node-sqlite' &&\n (reopen as { secureFile?: unknown }).secureFile\n ) {\n return {\n kind: 'none',\n degraded: true,\n reason:\n 'on Windows the secure SQLite custody verifier cannot be handed to a worker thread',\n };\n }\n return { kind: 'reopen', engine: dbEngine, reopen };\n}\n","// Self-register this package's manifest for consumers that import via this\n// subpath without the main entry. See src/__smrt-register__.ts (issue #1132).\nimport './__smrt-register__.js';\n\nimport {\n type detectEngine,\n ensureJobEventsSystemTableCompatibility,\n field,\n foreignKey,\n SmrtCollection,\n SmrtObject,\n smrt,\n} from '@happyvertical/smrt-core';\nimport {\n getTenantId,\n TenantScoped,\n tenantId,\n} from '@happyvertical/smrt-tenancy';\nimport type { DatabaseInterface } from '@happyvertical/sql';\nimport { resolveEngine } from './worker-liveness.js';\n\nexport type SmrtJobEventType = 'status' | 'progress' | 'log' | 'error' | string;\n\nexport type SmrtJobEventLevel = 'debug' | 'info' | 'warn' | 'error';\n\nexport interface SmrtJobEventData {\n tenantId?: string | null;\n jobId: string;\n type?: SmrtJobEventType;\n level?: SmrtJobEventLevel;\n stage?: string | null;\n progress?: number | null;\n message?: string;\n data?: Record<string, unknown>;\n createdAt?: Date;\n}\n\nexport interface JobEventCursor {\n createdAt: string | Date;\n id: string;\n}\n\nexport interface ListJobEventsOptions {\n tenantId?: string | null;\n limit?: number;\n since?: string | Date;\n afterId?: string;\n cursor?: string | JobEventCursor;\n}\n\nexport type SmrtJobTerminalStatus = 'completed' | 'failed' | 'cancelled';\n\nexport interface SmrtJobTerminalOutcome {\n eventId: string;\n jobId: string;\n tenantId: string | null;\n status: SmrtJobTerminalStatus;\n queue: string;\n objectType: string;\n method: string;\n attempts: number;\n /**\n * Why a `failed` job failed. `handler-unregistered` (#5005): the runner that\n * claimed a handler job had no handler registered under its name.\n * `handler-unclaimed` (#5005): no runner registered for the handler claimed\n * it before the unclaimed deadline; it never ran.\n */\n failureKind?:\n | 'execution'\n | 'timeout'\n | 'stale-recovery'\n | 'handler-unregistered'\n | 'handler-unclaimed';\n completedAt: string;\n cursor: string;\n}\n\nexport interface ListTerminalOutcomesOptions {\n /** Explicit tenant boundary. Pass null only for global jobs. */\n tenantId: string | null;\n limit?: number;\n since?: string | Date;\n before?: string | JobEventCursor;\n statuses?: SmrtJobTerminalStatus[];\n queues?: string[];\n objectTypes?: string[];\n methods?: string[];\n}\n\n/** Exact-job lookup; optional dispatch outcome fields bind a current job snapshot. */\nexport interface GetTerminalOutcomeOptions {\n tenantId: string | null;\n attempts?: number;\n completedAt?: string;\n}\n\nexport interface SmrtJobTerminalOutcomePage {\n outcomes: SmrtJobTerminalOutcome[];\n limit: number;\n candidateLimit: 1000;\n truncated: boolean;\n nextCursor: string | null;\n}\n\nconst JOB_EVENT_STORAGE_COLUMNS = [\n 'id',\n 'slug',\n 'context',\n 'created_at',\n 'updated_at',\n 'tenant_id',\n 'job_id',\n 'type',\n 'level',\n 'stage',\n 'progress',\n 'message',\n 'data',\n].join(', ');\nconst TERMINAL_OUTCOME_CANDIDATE_LIMIT = 1000 as const;\n\n@smrt({\n tableName: '_smrt_job_events',\n // Fail closed: same reasoning as SmrtJob. `_smrt_job_events` carries job\n // progress/log/error payloads for every tenant; an `optional`-mode generated\n // read reached without tenant context returns UNFILTERED rows. Consumers read\n // events through the collection's tenant-aware methods (listByJob /\n // listSinceCursor, which require an explicit tenantId or ambient context), not\n // through generated routes — so we do not generate a read surface here\n // (S5 audit #1402).\n api: false,\n // In-process operator commands only (http: false). skipApiCheck acknowledges\n // that these CLI reads intentionally have no HTTP/API route now that api is\n // disabled (S5 audit #1402).\n cli: { include: ['list', 'get'], http: false, skipApiCheck: true },\n mcp: false,\n})\n// Keep the data model tenant-scoped (defense in depth); the @tenantId() field\n// alone does not make collection reads filter by tenant. `optional` keeps global\n// (NULL tenant) events working (S5 audit #1402).\n@TenantScoped({ mode: 'optional' })\nexport class SmrtJobEvent extends SmrtObject { static __smrtPackage__ = \"@happyvertical/smrt-jobs\";\n @tenantId({ nullable: true })\n tenantId: string | null | undefined = undefined;\n\n // Job events intentionally outlive completed job rows (30-day event\n // retention vs 7-day completed-job retention). Keep the typed relationship,\n // index, and retained job identifier, but do not install a physical FK or\n // app-side delete action that would make the documented retention sweep\n // impossible (#2375, #2413).\n @foreignKey('SmrtJob', {\n required: true,\n requiredFor: 'identity',\n constraint: false,\n })\n jobId: string = '';\n\n @field({ type: 'text', required: true, default: 'log' })\n type: SmrtJobEventType = 'log';\n\n @field({ type: 'text', required: true, default: 'info' })\n level: SmrtJobEventLevel = 'info';\n\n @field({ type: 'text', nullable: true })\n stage: string | null = null;\n\n @field({ type: 'integer', nullable: true })\n progress: number | null = null;\n\n @field({ type: 'text', default: '' })\n message: string = '';\n\n @field({ type: 'json' })\n data: Record<string, unknown> = {};\n\n @field({ type: 'datetime', required: true })\n createdAt: Date = new Date();\n\n toCursor(): string {\n const createdAt =\n this.createdAt instanceof Date\n ? this.createdAt.toISOString()\n : String(this.createdAt);\n return `${createdAt}|${this.id ?? ''}`;\n }\n}\n\nfunction normalizeLimit(limit: number | undefined): number {\n const numeric =\n typeof limit === 'number' && Number.isFinite(limit) ? limit : 250;\n return Math.max(1, Math.min(1000, Math.floor(numeric)));\n}\n\nfunction normalizeProgress(progress: unknown): number | null {\n if (typeof progress !== 'number' || !Number.isFinite(progress)) {\n return null;\n }\n\n return Math.max(0, Math.min(100, Math.round(progress)));\n}\n\nfunction parseCursor(cursor: string | JobEventCursor): JobEventCursor {\n if (typeof cursor !== 'string') return cursor;\n const separator = cursor.lastIndexOf('|');\n if (separator === -1) {\n return { createdAt: cursor, id: '' };\n }\n return {\n createdAt: cursor.slice(0, separator),\n id: cursor.slice(separator + 1),\n };\n}\n\nfunction normalizeCursorDate(value: string | Date): string {\n if (value instanceof Date) {\n return value.toISOString();\n }\n\n const parsed = new Date(value);\n if (!Number.isNaN(parsed.getTime())) {\n return parsed.toISOString();\n }\n\n return value;\n}\n\nfunction databaseEngine(\n db: DatabaseInterface,\n): ReturnType<typeof detectEngine> {\n const configured = db as DatabaseInterface & {\n config?: { type?: string; url?: string };\n type?: string;\n client?: { constructor?: { name?: string }; connection?: unknown };\n };\n const engine = resolveEngine(db);\n const clientName = configured.client?.constructor?.name?.toLowerCase() ?? '';\n if (\n engine === 'sqlite' &&\n (clientName.includes('duckdb') ||\n configured.client?.connection !== undefined)\n ) {\n return 'duckdb';\n }\n return engine;\n}\n\nfunction getQueryRows(result: unknown): Record<string, unknown>[] {\n if (Array.isArray(result)) {\n return result as Record<string, unknown>[];\n }\n\n return (result as { rows?: Record<string, unknown>[] }).rows ?? [];\n}\n\nexport class SmrtJobEventCollection extends SmrtCollection<SmrtJobEvent> {\n static readonly _itemClass = SmrtJobEvent;\n\n override async initialize(): Promise<this> {\n await super.initialize();\n await ensureJobEventsSystemTableCompatibility(this.db);\n return this;\n }\n\n async append(input: SmrtJobEventData): Promise<SmrtJobEvent> {\n return this.create({\n tenantId: input.tenantId,\n jobId: input.jobId,\n type: input.type ?? 'log',\n level: input.level ?? 'info',\n stage: input.stage ?? null,\n progress: normalizeProgress(input.progress),\n message: input.message ?? '',\n data: input.data ?? {},\n createdAt: input.createdAt ?? new Date(),\n });\n }\n\n async listByJob(\n jobId: string,\n options: ListJobEventsOptions = {},\n ): Promise<SmrtJobEvent[]> {\n return this.listSinceCursor({\n ...options,\n jobId,\n });\n }\n\n async listSinceCursor(\n options: ListJobEventsOptions & { jobId?: string } = {},\n ): Promise<SmrtJobEvent[]> {\n const where: string[] = [];\n const params: unknown[] = [];\n\n if (options.jobId) {\n where.push('job_id = ?');\n params.push(options.jobId);\n }\n\n this.addTenantPredicate(where, params, options);\n\n if (options.cursor) {\n const cursor = parseCursor(options.cursor);\n const createdAt = await this.resolveCursorCreatedAt(cursor, options);\n const createdAtExpression = this.createdAtComparableExpression();\n where.push(\n `(${createdAtExpression} > ? OR (${createdAtExpression} = ? AND id > ?))`,\n );\n params.push(createdAt, createdAt, cursor.id);\n } else if (options.since) {\n where.push(`${this.createdAtComparableExpression()} > ?`);\n params.push(normalizeCursorDate(options.since));\n }\n\n if (options.afterId) {\n where.push('id > ?');\n params.push(options.afterId);\n }\n\n params.push(normalizeLimit(options.limit));\n\n const whereSql = where.length ? `WHERE ${where.join(' AND ')}` : '';\n return this.query(\n `SELECT ${JOB_EVENT_STORAGE_COLUMNS}\n FROM _smrt_job_events\n ${whereSql}\n ORDER BY ${this.createdAtComparableExpression()} ASC, id ASC\n LIMIT ?`,\n params,\n { allowRawOnTenantScoped: true },\n );\n }\n\n async latestProgressByJobIds(\n jobIds: string[],\n options: { tenantId?: string | null } = {},\n ): Promise<Map<string, SmrtJobEvent>> {\n const uniqueJobIds = [...new Set(jobIds.filter(Boolean))];\n const latestByJobId = new Map<string, SmrtJobEvent>();\n if (uniqueJobIds.length === 0) return latestByJobId;\n\n const placeholders = uniqueJobIds.map(() => '?').join(', ');\n const where: string[] = [\n `job_id IN (${placeholders})`,\n \"type = 'progress'\",\n ];\n const params: unknown[] = [...uniqueJobIds];\n\n this.addTenantPredicate(where, params, options);\n const createdAtExpression = this.createdAtComparableExpression();\n\n const events = await this.query(\n `SELECT ${JOB_EVENT_STORAGE_COLUMNS}\n FROM (\n SELECT ${JOB_EVENT_STORAGE_COLUMNS},\n ${createdAtExpression} AS smrt_created_at_sort,\n ROW_NUMBER() OVER (\n PARTITION BY job_id\n ORDER BY ${createdAtExpression} DESC, id DESC\n ) AS smrt_rank\n FROM _smrt_job_events\n WHERE ${where.join(' AND ')}\n ) ranked\n WHERE smrt_rank = 1\n ORDER BY smrt_created_at_sort DESC, id DESC`,\n params,\n { allowRawOnTenantScoped: true },\n );\n\n for (const event of events) {\n latestByJobId.set(event.jobId, event);\n }\n\n return latestByJobId;\n }\n\n /**\n * Read the newest safe, authoritative terminal outcomes for one tenant.\n *\n * The projection is built only from versioned terminal events written in the\n * same transaction as their job status. It never returns job arguments,\n * object ids, results, raw errors, or stack traces. Events follow the package\n * retention policy (30 days by default), independently of job-row cleanup.\n */\n async listTerminalOutcomes(\n options: ListTerminalOutcomesOptions,\n ): Promise<SmrtJobTerminalOutcomePage> {\n if (!Object.hasOwn(options, 'tenantId') || options.tenantId === undefined) {\n throw new Error(\n 'Terminal outcome queries require tenantId or tenantId: null',\n );\n }\n const limit = normalizeLimit(options.limit ?? 100);\n const where = [\n \"stage IN ('completed', 'failed', 'cancelled', 'stale-recovery')\",\n ];\n const params: unknown[] = [];\n this.addTenantPredicate(where, params, options);\n\n if (options.statuses?.length) {\n const stages = options.statuses.flatMap((status) =>\n status === 'failed' ? ['failed', 'stale-recovery'] : [status],\n );\n where.push(`stage IN (${stages.map(() => '?').join(', ')})`);\n params.push(...stages);\n }\n if (options.since) {\n where.push(`${this.createdAtComparableExpression()} > ?`);\n params.push(normalizeCursorDate(options.since));\n }\n if (options.before) {\n const cursor = parseCursor(options.before);\n const createdAt = await this.resolveCursorCreatedAt(cursor, options);\n const expression = this.createdAtComparableExpression();\n where.push(`(${expression} < ? OR (${expression} = ? AND id < ?))`);\n params.push(createdAt, createdAt, cursor.id);\n }\n\n params.push(TERMINAL_OUTCOME_CANDIDATE_LIMIT);\n const expression = this.createdAtComparableExpression();\n const candidates = await this.query(\n `SELECT ${JOB_EVENT_STORAGE_COLUMNS}\n FROM _smrt_job_events\n WHERE ${where.join(' AND ')}\n ORDER BY ${expression} DESC, id DESC\n LIMIT ?`,\n params,\n { allowRawOnTenantScoped: true },\n );\n\n const outcomes: SmrtJobTerminalOutcome[] = [];\n let scanned: SmrtJobEvent | undefined;\n for (const event of candidates) {\n scanned = event;\n const outcome = terminalOutcome(event);\n if (!outcome || !matchesTerminalOutcome(outcome, options)) continue;\n outcomes.push(outcome);\n if (outcomes.length === limit) break;\n }\n const stoppedAtLimit = outcomes.length === limit;\n const candidateBoundReached =\n candidates.length === TERMINAL_OUTCOME_CANDIDATE_LIMIT;\n\n return {\n outcomes,\n limit,\n candidateLimit: TERMINAL_OUTCOME_CANDIDATE_LIMIT,\n truncated: stoppedAtLimit || candidateBoundReached,\n nextCursor:\n (stoppedAtLimit || candidateBoundReached) && scanned\n ? scanned.toCursor()\n : null,\n };\n }\n\n /**\n * Read one job's newest matching authoritative outcome, independently of the\n * tenant-wide feed's 1,000-candidate limit. Retention still applies.\n * @param jobId - Authorized job identity; the caller owns resource authorization.\n * @param options - Explicit tenant and optional current completion identity.\n * @returns A safe outcome or null; never raw errors, arguments or results.\n */\n async getTerminalOutcome(\n jobId: string,\n options: GetTerminalOutcomeOptions,\n ): Promise<SmrtJobTerminalOutcome | null> {\n if (!Object.hasOwn(options, 'tenantId') || options.tenantId === undefined)\n throw new Error(\n 'Terminal outcome queries require tenantId or tenantId: null',\n );\n const where = [\n 'job_id = ?',\n \"stage IN ('completed', 'failed', 'cancelled', 'stale-recovery')\",\n ];\n const params: unknown[] = [jobId];\n this.addTenantPredicate(where, params, options);\n const events = await this.query(\n `SELECT ${JOB_EVENT_STORAGE_COLUMNS} FROM _smrt_job_events\n WHERE ${where.join(' AND ')} ORDER BY ${this.createdAtComparableExpression()} DESC, id DESC`,\n params,\n { allowRawOnTenantScoped: true },\n );\n for (const event of events) {\n const outcome = terminalOutcome(event);\n if (\n outcome &&\n (options.attempts === undefined ||\n options.attempts === outcome.attempts) &&\n (options.completedAt === undefined ||\n options.completedAt === outcome.completedAt)\n )\n return outcome;\n }\n return null;\n }\n\n private addTenantPredicate(\n where: string[],\n params: unknown[],\n options: { tenantId?: string | null },\n ): void {\n if (options.tenantId === null) {\n where.push('tenant_id IS NULL');\n return;\n }\n\n const tenantId =\n typeof options.tenantId === 'string' ? options.tenantId : getTenantId();\n\n if (tenantId) {\n where.push('tenant_id = ?');\n params.push(tenantId);\n return;\n }\n\n throw new Error(\n 'Tenant-scoped job event queries require tenantId, tenantId: null, or an ambient tenant context.',\n );\n }\n\n /**\n * Delete job events recorded before a cutoff (#2375).\n *\n * `_smrt_job_events` is append-only — every log line, progress tick and\n * lifecycle transition of every job — so it outgrows `_smrt_jobs` by an\n * order of magnitude and had no prune path at all. Events are pruned on\n * their own clock rather than by following job deletion: a long-running job\n * accumulates events for as long as it runs.\n *\n * The cutoff uses the same engine-normalized `created_at` expression the\n * cursor reads use. On PostgreSQL that is the bare column, so\n * `idx_smrt_job_events_created_at` serves it; on SQLite the `strftime()`\n * wrapper makes the comparison non-sargable and the prune is a scan. That is\n * acceptable for a periodic maintenance pass and is preferable to comparing\n * two differently-formatted timestamps, which is what the wrapper exists to\n * prevent.\n *\n * @param options.before - Delete events created strictly before this time.\n * @param options.dryRun - Count matching events without deleting them.\n * @returns Number of events deleted (or, under `dryRun`, matched).\n */\n async cleanup(options: { before: Date; dryRun?: boolean }): Promise<number> {\n const expression = this.createdAtComparableExpression();\n const where = `${expression} < ?`;\n const cutoff = options.before.toISOString();\n\n const counted = await this.db.query(\n `SELECT COUNT(*) AS total FROM _smrt_job_events WHERE ${where}`,\n cutoff,\n );\n const total = Number(counted.rows?.[0]?.total ?? 0);\n if (!Number.isFinite(total) || total <= 0) return 0;\n\n if (!options.dryRun) {\n await this.db.query(\n `DELETE FROM _smrt_job_events WHERE ${where}`,\n cutoff,\n );\n }\n\n return total;\n }\n\n private createdAtComparableExpression(): string {\n const engine = databaseEngine(this.db);\n if (engine === 'sqlite') {\n return \"strftime('%Y-%m-%dT%H:%M:%fZ', created_at)\";\n }\n if (engine === 'duckdb') {\n return \"strftime(created_at, '%Y-%m-%dT%H:%M:%S.%gZ')\";\n }\n\n return 'created_at';\n }\n\n private async resolveCursorCreatedAt(\n cursor: JobEventCursor,\n options: ListJobEventsOptions & { jobId?: string },\n ): Promise<string> {\n if (!cursor.id) {\n return normalizeCursorDate(cursor.createdAt);\n }\n\n const where = ['id = ?'];\n const params: unknown[] = [cursor.id];\n if (options.jobId) {\n where.push('job_id = ?');\n params.push(options.jobId);\n }\n this.addTenantPredicate(where, params, options);\n\n const result = await this.db.query(\n `SELECT ${this.createdAtComparableExpression()} AS cursor_created_at\n FROM _smrt_job_events\n WHERE ${where.join(' AND ')}\n LIMIT 1`,\n ...params,\n );\n const cursorCreatedAt = getQueryRows(result)[0]?.cursor_created_at;\n\n return typeof cursorCreatedAt === 'string' && cursorCreatedAt.trim()\n ? cursorCreatedAt\n : normalizeCursorDate(cursor.createdAt);\n }\n}\n\nfunction terminalOutcome(event: SmrtJobEvent): SmrtJobTerminalOutcome | null {\n const data = event.data;\n if (\n data?.version !== 1 ||\n data.terminal !== true ||\n !isTerminalStatus(data.status) ||\n !matchesTerminalStage(data.status, data.failureKind, event.stage) ||\n typeof data.queue !== 'string' ||\n typeof data.objectType !== 'string' ||\n typeof data.method !== 'string' ||\n typeof data.attempts !== 'number' ||\n !Number.isSafeInteger(data.attempts) ||\n data.attempts < 0 ||\n typeof data.completedAt !== 'string' ||\n Number.isNaN(Date.parse(data.completedAt)) ||\n (data.status === 'failed'\n ? !isFailureKind(data.failureKind)\n : data.failureKind !== undefined) ||\n !event.id\n ) {\n return null;\n }\n const failureKind =\n data.status === 'failed'\n ? (data.failureKind as SmrtJobTerminalOutcome['failureKind'])\n : undefined;\n\n return {\n eventId: event.id,\n jobId: event.jobId,\n tenantId: event.tenantId ?? null,\n status: data.status,\n queue: data.queue,\n objectType: data.objectType,\n method: data.method,\n attempts: data.attempts,\n ...(failureKind ? { failureKind } : {}),\n completedAt: new Date(data.completedAt).toISOString(),\n cursor: event.toCursor(),\n };\n}\n\nfunction isFailureKind(\n value: unknown,\n): value is NonNullable<SmrtJobTerminalOutcome['failureKind']> {\n return (\n value === 'execution' ||\n value === 'timeout' ||\n value === 'stale-recovery' ||\n value === 'handler-unregistered' ||\n value === 'handler-unclaimed'\n );\n}\n\nfunction isTerminalStatus(value: unknown): value is SmrtJobTerminalStatus {\n return value === 'completed' || value === 'failed' || value === 'cancelled';\n}\n\nfunction matchesTerminalStage(\n status: SmrtJobTerminalStatus,\n failureKind: unknown,\n stage: string | null,\n): boolean {\n return (\n stage === status ||\n (status === 'failed' &&\n failureKind === 'stale-recovery' &&\n stage === 'stale-recovery')\n );\n}\n\nfunction matchesTerminalOutcome(\n outcome: SmrtJobTerminalOutcome,\n options: ListTerminalOutcomesOptions,\n): boolean {\n return (\n (!options.queues?.length || options.queues.includes(outcome.queue)) &&\n (!options.objectTypes?.length ||\n options.objectTypes.includes(outcome.objectType)) &&\n (!options.methods?.length || options.methods.includes(outcome.method))\n );\n}\n\nexport default SmrtJobEvent;\n","import { randomUUID } from 'node:crypto';\nimport {\n ensureJobEventsSystemTableCompatibility,\n ObjectRegistry,\n} from '@happyvertical/smrt-core';\nimport { ensureSchema } from '@happyvertical/smrt-core/schema/utils';\nimport type { DatabaseInterface } from '@happyvertical/sql';\nimport type { JobStatus, SmrtJob } from './smrt-job.js';\nimport { SmrtJobEvent, type SmrtJobTerminalStatus } from './smrt-job-event.js';\n\nconst terminalStorageReady = new WeakMap<object, Promise<void>>();\n\n/**\n * Prepare, once per database, the storage every terminal transition writes.\n *\n * Preparing it builds the registry's merged schemas, so it can fail for a\n * reason unrelated to jobs (two unrelated classes claiming one table, #4735).\n * `TaskRunner.start()` calls this before it claims anything, so that failure\n * stops the runner at startup instead of stranding every claimed job; later\n * transitions reuse the cached readiness and no longer depend on models that\n * register after start.\n */\nexport async function ensureTerminalOutcomeStorage(\n db: DatabaseInterface,\n): Promise<void> {\n const key = db as object;\n const existing = terminalStorageReady.get(key);\n if (existing) return existing;\n\n const pending = (async () => {\n // SmrtJob.cancel() has historically worked for consumers that prepare only\n // the job model. Terminal outcomes now require their package-owned event\n // table as well, so prepare that registered schema before opening the\n // state+event transaction. Never fall back to a state-only transition.\n await ensureSchema(db, 'SmrtJobEvent');\n await ensureJobEventsSystemTableCompatibility(db);\n })();\n terminalStorageReady.set(key, pending);\n try {\n await pending;\n } catch (error) {\n terminalStorageReady.delete(key);\n throw error;\n }\n}\n\nexport interface SmrtJobTerminalSnapshot {\n id: string;\n tenantId: string | null;\n queue: string;\n objectType: string;\n method: string;\n attempts: number;\n startedAt?: string | null;\n}\n\nexport interface TransitionTerminalJobOptions {\n job: SmrtJobTerminalSnapshot;\n status: SmrtJobTerminalStatus;\n completedAt: Date;\n expectedStatuses: JobStatus[];\n expectedWorkerId?: string | null;\n expectedTaskId?: string;\n /** Also require `run_at <= ?` (ISO): a requeued row is not this transition's. */\n expectedRunAtAtOrBefore?: string;\n clearWorker?: boolean;\n lastError?: string | null;\n failureKind?:\n | 'execution'\n | 'timeout'\n | 'stale-recovery'\n | 'handler-unregistered'\n | 'handler-unclaimed';\n resultPointer?: string | null;\n taskResult?: Record<string, unknown> | null;\n}\n\n/**\n * Atomically persist an owned terminal job transition and its durable outcome.\n *\n * A null result means the conditional transition lost a race. Neither the job\n * row nor an event is written in that case.\n */\nexport async function transitionTerminalJob(\n db: DatabaseInterface,\n options: TransitionTerminalJobOptions,\n): Promise<SmrtJobEvent | null> {\n if (!db.transaction) {\n throw new Error('Terminal job transitions require transaction support');\n }\n if (options.expectedStatuses.length === 0) {\n throw new Error('Terminal job transitions require an expected status');\n }\n\n await ensureTerminalOutcomeStorage(db);\n\n const persisted = await db.transaction(async (tx) => {\n const assignments: Array<[string, unknown]> = [\n ['status', options.status],\n ['completed_at', options.completedAt.toISOString()],\n ['updated_at', options.completedAt.toISOString()],\n ];\n if (options.clearWorker) {\n assignments.push(['worker_id', null], ['worker_heartbeat', null]);\n }\n if (options.lastError !== undefined) {\n assignments.push(['last_error', options.lastError]);\n }\n if (options.resultPointer !== undefined) {\n assignments.push(['result_pointer', options.resultPointer]);\n }\n if (options.taskResult !== undefined) {\n assignments.push([\n 'task_result',\n options.taskResult === null ? null : JSON.stringify(options.taskResult),\n ]);\n }\n\n const where = ['id = ?'];\n const whereValues: unknown[] = [options.job.id];\n if (options.job.tenantId === null) {\n where.push('tenant_id IS NULL');\n } else {\n where.push('tenant_id = ?');\n whereValues.push(options.job.tenantId);\n }\n where.push(\n `status IN (${options.expectedStatuses.map(() => '?').join(', ')})`,\n );\n whereValues.push(...options.expectedStatuses);\n if (options.expectedWorkerId === null) {\n where.push('worker_id IS NULL');\n } else if (options.expectedWorkerId !== undefined) {\n where.push('worker_id = ?');\n whereValues.push(options.expectedWorkerId);\n }\n if (\n options.expectedWorkerId !== undefined &&\n options.job.startedAt !== undefined\n ) {\n where.push('attempts = ?');\n whereValues.push(options.job.attempts);\n if (options.job.startedAt === null) where.push('started_at IS NULL');\n else if (options.job.startedAt !== undefined) {\n where.push('started_at = ?');\n whereValues.push(options.job.startedAt);\n }\n }\n if (options.expectedTaskId !== undefined) {\n where.push('task_id = ?');\n whereValues.push(options.expectedTaskId);\n }\n if (options.expectedRunAtAtOrBefore !== undefined) {\n where.push('run_at <= ?');\n whereValues.push(options.expectedRunAtAtOrBefore);\n }\n\n const updated = await tx.query(\n `UPDATE _smrt_jobs\n SET ${assignments.map(([column]) => `${column} = ?`).join(', ')}\n WHERE ${where.join(' AND ')}\n RETURNING CAST(tenant_id AS VARCHAR) AS tenant_id,\n queue, object_type, method, attempts`,\n ...assignments.map(([, value]) => value),\n ...whereValues,\n );\n if (updated.rows.length !== 1) return null;\n const authoritative = updated.rows[0] as {\n tenant_id: string | null;\n queue: string;\n object_type: string;\n method: string;\n attempts: number | string;\n };\n const attempts = Number(authoritative.attempts);\n if (!Number.isSafeInteger(attempts) || attempts < 0) {\n throw new Error('Terminal job transition returned invalid attempts');\n }\n\n const stage =\n options.status === 'failed' && options.failureKind === 'stale-recovery'\n ? 'stale-recovery'\n : options.status;\n const id = randomUUID();\n const type =\n options.status === 'completed'\n ? 'progress'\n : options.status === 'failed'\n ? 'error'\n : 'status';\n const level = options.status === 'failed' ? 'error' : 'info';\n const progress = options.status === 'completed' ? 100 : null;\n const message = `Job ${options.status}`;\n const data = {\n version: 1,\n terminal: true,\n status: options.status,\n queue: authoritative.queue,\n objectType: authoritative.object_type,\n method: authoritative.method,\n attempts,\n completedAt: options.completedAt.toISOString(),\n ...(options.status === 'failed' && options.failureKind\n ? { failureKind: options.failureKind }\n : {}),\n };\n const timestamp = options.completedAt.toISOString();\n await tx.query(\n `INSERT INTO _smrt_job_events\n (id, slug, context, created_at, updated_at, tenant_id, job_id,\n type, level, stage, progress, message, data)\n VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,\n id,\n id,\n '',\n timestamp,\n timestamp,\n authoritative.tenant_id,\n options.job.id,\n type,\n level,\n stage,\n progress,\n message,\n JSON.stringify(data),\n );\n return {\n id,\n slug: id,\n context: '',\n created_at: timestamp,\n updated_at: timestamp,\n tenant_id: authoritative.tenant_id,\n job_id: options.job.id,\n type,\n level,\n stage,\n progress,\n message,\n data,\n };\n });\n\n if (!persisted) return null;\n const event = new (ObjectRegistry.resolveEffectiveConstructor(SmrtJobEvent))({\n db,\n });\n await event.initialize();\n await event.loadDataFromDb(persisted);\n return event;\n}\n\nexport function terminalSnapshot(\n job: Pick<\n SmrtJob,\n 'id' | 'tenantId' | 'queue' | 'objectType' | 'method' | 'attempts'\n > &\n Partial<Pick<SmrtJob, 'startedAt'>>,\n fenceDispatch = false,\n): SmrtJobTerminalSnapshot | null {\n if (!job.id) return null;\n return {\n id: job.id,\n tenantId: job.tenantId ?? null,\n queue: job.queue,\n objectType: job.objectType,\n method: job.method,\n attempts: job.attempts,\n ...(fenceDispatch && job.startedAt !== undefined\n ? { startedAt: job.startedAt?.toISOString() ?? null }\n : {}),\n };\n}\n","import { createHash, randomUUID } from 'node:crypto';\nimport type { RetryStrategyConfig } from '@happyvertical/jobs';\nimport {\n type detectEngine,\n ensureJobsSystemTableCompatibility,\n field,\n ObjectRegistry,\n SmrtCollection,\n SmrtObject,\n type SmrtSaveOptions,\n smrt,\n} from '@happyvertical/smrt-core';\nimport {\n getTenantId,\n isSuperAdminBypass,\n isSystemContext,\n TenantIsolationError,\n TenantScoped,\n tenantId,\n} from '@happyvertical/smrt-tenancy';\nimport type { DatabaseInterface } from '@happyvertical/sql';\nimport {\n assertWithinTenantCreationCap,\n clampRetries,\n DEFAULT_TENANT_JOB_CAP,\n} from './background-policy.js';\nimport {\n assertJobHandlerName,\n isJobHandlerTarget,\n JOB_HANDLER_METHOD,\n JOB_HANDLER_TARGET_PREFIX,\n jobHandlerName,\n jobHandlerTarget,\n MAX_JOB_HANDLERS,\n} from './job-handlers.js';\nimport { SmrtJobDedupeSlotCollection } from './smrt-job-dedupe-slot.js';\nimport { terminalSnapshot, transitionTerminalJob } from './terminal-outcome.js';\nimport { resolveEngine } from './worker-liveness.js';\n\n/**\n * Job status type\n */\nexport type JobStatus =\n | 'pending'\n | 'running'\n | 'completed'\n | 'failed'\n | 'cancelled';\n\n/**\n * Timeout behavior type\n */\nexport type TimeoutBehavior = 'fail' | 'kill' | 'warn';\n\n/**\n * Full job projection with portable string job and tenant identities.\n *\n * Native DuckDB currently exposes UUID result values as internal objects.\n * Worker claim/recovery state and restored tenant context use string IDs.\n * Both paths use this projection instead of hydrating raw UUIDs from `SELECT *`.\n */\nexport const SMRT_JOB_PORTABLE_SELECT_COLUMNS = `\n CAST(id AS VARCHAR) AS id,\n slug, context, created_at, updated_at,\n CAST(tenant_id AS VARCHAR) AS tenant_id, queue,\n object_type, object_id, method, args, run_at,\n priority, status, attempts, max_attempts, timeout,\n timeout_behavior, started_at, completed_at, last_error,\n result_pointer, task_id, task_owner_id, task_result,\n task_input_requests, task_input_responses, retry_strategy,\n worker_id, worker_heartbeat, dedupe_key\n`;\n\n/**\n * Persistent job record stored in the `_smrt_jobs` system table.\n *\n * @remarks\n * Each SmrtJob represents a deferred method call on a SmrtObject. The TaskRunner polls for\n * pending jobs, resolves the target class via ObjectRegistry, and invokes the method. Jobs\n * track status (`pending -> running -> completed/failed/cancelled`), retry attempts with\n * configurable strategies, worker heartbeats for stale-job detection, and optional result pointers.\n * Priority ordering is `higher = sooner`; the default timeout is 5 minutes (300000ms).\n */\n@smrt({\n tableName: '_smrt_jobs',\n // Fail closed: `_smrt_jobs` is an internal operational queue table. Generated\n // REST/MCP list/get only filter by tenant when a tenant context is active;\n // reached without context (a tenant-less/admin principal, or any non-SvelteKit\n // surface) an `optional`-mode class returns UNFILTERED rows, leaking every\n // tenant's jobs. Workers read this table via the collection directly\n // (allowRawOnTenantScoped), never through generated routes, so nothing\n // internal needs the read surface — so we do not generate one (S5 audit #1402).\n api: false,\n // retry/cancel are operator commands invoked in-process via the CLI;\n // they intentionally aren't exposed over HTTP.\n cli: {\n include: ['list', 'get', 'retry', 'cancel'],\n skipApiCheck: true,\n http: false,\n },\n mcp: false,\n // Composite for the claim-loop predicate every runner polls roughly once\n // per second (`claimReady()`/`listReady()`: `status = 'pending' AND\n // run_at <= ?`, #2364, epic #2382 finding A3). Declared here rather than\n // left to the jobs-compat path (`ensureJobsSystemTableCompatibility()`,\n // #2375/#2376): that path exists to reshape a table that predates the\n // column/index it adds on databases where the manifest hasn't migrated\n // yet, not as the default route for new indexes on a normal decorated\n // class — this one reaches every path (manifest, registry, `db:migrate`)\n // the standard way and rolls out on the next `smrt db:migrate`.\n //\n // Roll this out with `smrt db:migrate --postgres-safe` (#2362): `_smrt_jobs`\n // is under continuous write load (every claim is an UPDATE), so a plain\n // atomic `CREATE INDEX` would hold ACCESS EXCLUSIVE for the build and stall\n // claiming on a busy deployment.\n indexes: [\n { name: '_smrt_jobs_status_run_at_idx', columns: ['status', 'runAt'] },\n // Keep suspended, already-due tasks out of the hot ready scan (#3211).\n // SQLite/PostgreSQL partial index; DuckDB/JSON retain a full index fallback.\n {\n name: '_smrt_jobs_ready_idx',\n columns: ['status', 'runAt'],\n where:\n \"status = 'pending' AND (task_input_requests IS NULL OR task_input_responses IS NOT NULL)\",\n },\n ],\n})\n// Keep the data model tenant-scoped (defense in depth): even without a generated\n// read route, the @tenantId() field alone does NOT make collection reads filter\n// by tenant. `optional` mode preserves global (NULL tenant) jobs while scoping\n// tenant-owned rows for any future tenant-context-required path (S5 audit #1402).\n@TenantScoped({ mode: 'optional' })\nexport class SmrtJob extends SmrtObject { static __smrtPackage__ = \"@happyvertical/smrt-jobs\";\n /** Tenant context captured for this job, if any */\n @tenantId({ nullable: true })\n tenantId: string | null | undefined = undefined;\n\n /** Caller key retained as provenance; only pending/running jobs reserve it. */\n @field({ type: 'text', nullable: true, indexed: true })\n dedupeKey: string | null = null;\n\n /** Queue name for the job */\n @field({ type: 'text', required: true, default: 'default' })\n queue: string = 'default';\n\n /** Type of object to invoke method on */\n @field({ type: 'text', required: true, requiredFor: 'identity' })\n objectType: string = '';\n\n /** ID of the specific object (null for static methods) */\n @field({ type: 'text', nullable: true })\n objectId: string | null = null;\n\n /** Method name to invoke */\n @field({ type: 'text', required: true, requiredFor: 'identity' })\n method: string = '';\n\n /** Arguments to pass to the method (JSON) */\n @field({ type: 'json' })\n args: Record<string, unknown> = {};\n\n /**\n * When to run the job.\n *\n * Indexed (single-column, plus the class-level `(status, run_at)`\n * composite): the claim-loop predicate every runner polls roughly once per\n * second (#2364).\n */\n @field({ type: 'datetime', required: true, indexed: true })\n runAt: Date = new Date();\n\n /** Priority (higher = sooner) */\n @field({ type: 'integer', required: true, default: 50 })\n priority: number = 50;\n\n /**\n * Current status.\n *\n * Indexed (single-column, plus the class-level `(status, run_at)`\n * composite): the claim-loop predicate every runner polls roughly once per\n * second (#2364). `(status, completed_at)` — the retention cleanup\n * predicate — is a separate index from `ensureJobsSystemTableCompatibility()`\n * (#2375).\n */\n @field({ type: 'text', required: true, default: 'pending', indexed: true })\n status: JobStatus = 'pending';\n\n /** Number of execution attempts */\n @field({ type: 'integer', required: true, default: 0 })\n attempts: number = 0;\n\n /** Maximum retry attempts */\n @field({ type: 'integer', required: true, default: 3 })\n maxAttempts: number = 3;\n\n /** Timeout in milliseconds */\n @field({ type: 'integer', required: true, default: 300000 })\n timeout: number = 300000;\n\n /** What to do on timeout */\n @field({ type: 'text', required: true, default: 'fail' })\n timeoutBehavior: TimeoutBehavior = 'fail';\n\n /** When execution started. Public retry and surplus release clear this field. */\n @field({ type: 'datetime', nullable: true })\n startedAt: Date | null = null;\n\n /** When execution completed */\n @field({ type: 'datetime', nullable: true })\n completedAt: Date | null = null;\n\n /** Last error message */\n @field({ type: 'text', nullable: true })\n lastError: string | null = null;\n\n /** Pointer to where result is stored */\n @field({ type: 'text', nullable: true })\n resultPointer: string | null = null;\n\n /**\n * Correlation identifier for an MCP Tasks extension task.\n *\n * A task is deliberately represented by its backing job rather than a second\n * queue row: every task transition therefore has exactly one durable worker\n * target to cancel, recover, and inspect.\n */\n @field({ type: 'text', nullable: true, unique: true })\n taskId: string | null = null;\n\n /** Principal that created an MCP task, when the transport has one. */\n @field({ type: 'text', nullable: true })\n taskOwnerId: string | null = null;\n\n /** Completed MCP CallToolResult, stored only for MCP task jobs. */\n @field({ type: 'json', nullable: true })\n taskResult: Record<string, unknown> | null = null;\n\n /** Outstanding input requests made through JobExecutionContext.task. */\n @field({ type: 'json', nullable: true })\n taskInputRequests: Record<string, unknown> | null = null;\n\n /** Accepted task input responses, keyed by the requested input name. */\n @field({ type: 'json', nullable: true })\n taskInputResponses: Record<string, unknown> | null = null;\n\n /** Retry strategy configuration */\n @field({ type: 'json' })\n retryStrategy: RetryStrategyConfig = {\n type: 'exponential',\n config: { initialDelay: 1000, multiplier: 2, maxDelay: 300000 },\n };\n\n /** ID of the worker processing this job */\n @field({ type: 'text', nullable: true })\n workerId: string | null = null;\n\n /** Last heartbeat from the worker */\n @field({ type: 'datetime', nullable: true })\n workerHeartbeat: Date | null = null;\n\n /**\n * Capture ambient tenant context when a job is saved inside withTenant().\n *\n * Scheduled jobs can also set this explicitly from their owning schedule.\n */\n override async save(options?: SmrtSaveOptions): Promise<this> {\n if (this.tenantId === undefined) {\n const contextTenantId = getTenantId();\n if (contextTenantId) {\n this.tenantId = contextTenantId;\n }\n }\n\n return super.save(options);\n }\n\n /**\n * Mark the job for retry\n */\n async retry(\n options: Pick<EnqueueJobOptions, 'transaction'> = {},\n ): Promise<void> {\n if (!this.id) throw new Error('Cannot retry an unpersisted job');\n const executor = options.transaction ?? this.db;\n const initial = await readRetryJob(executor, this.id);\n assertRetryTenant(initial.tenant_id);\n assertRetryStatus(initial.status);\n const association = persistedScheduleAssociation(initial.args);\n const originalArguments = JSON.stringify(persistedArguments(initial.args));\n const originalTarget = persistedJobTarget(initial);\n const dedupeKey = persistedDedupeKey(initial.dedupe_key);\n const tenant = initial.tenant_id;\n const tenantPredicate =\n tenant === null ? 'tenant_id IS NULL' : 'tenant_id = ?';\n const tenantValues = tenant === null ? [] : [tenant];\n\n const retry = async (\n tx: DatabaseInterface,\n ): Promise<Record<string, unknown>> => {\n // All paths acquire schedule -> dedupe slot -> job. Completion's job\n // transaction commits before its separate schedule callback acquires a row.\n const schedule = association\n ? await lockRetrySchedule(tx, association, initial)\n : null;\n let slotKey: string | null = null;\n let slotJobId: unknown;\n if (dedupeKey !== null) {\n slotKey = jobSlotKey(tenant, dedupeKey);\n const slot = await tx.query(\n 'UPDATE _smrt_job_dedupe_slots SET slot_key = slot_key WHERE slot_key = ? RETURNING job_id',\n slotKey,\n );\n if (slot.rows.length !== 1)\n throw new Error('Keyed job retry requires its enqueue slot');\n slotJobId = slot.rows[0].job_id;\n }\n const locked = await tx.query(\n `UPDATE _smrt_jobs SET id = id WHERE id = ? AND ${tenantPredicate}\n RETURNING ${SMRT_JOB_PORTABLE_SELECT_COLUMNS}`,\n initial.id,\n ...tenantValues,\n );\n if (locked.rows.length !== 1)\n throw new Error('Job ownership changed before retry');\n const current = retryRow(locked.rows[0]);\n assertRetryTenant(current.tenant_id);\n if (\n current.tenant_id !== tenant ||\n JSON.stringify(persistedScheduleAssociation(current.args)) !==\n JSON.stringify(association) ||\n JSON.stringify(persistedArguments(current.args)) !==\n originalArguments ||\n JSON.stringify(persistedJobTarget(current)) !==\n JSON.stringify(originalTarget) ||\n persistedDedupeKey(current.dedupe_key) !== dedupeKey\n ) {\n throw new Error(\n 'Persisted retry association changed; retry from current state',\n );\n }\n assertRetryStatus(current.status);\n const occupied = schedule\n ? await countScheduleJobs(\n tx,\n schedule.id,\n tenant,\n schedule.target,\n current.id,\n )\n : 0;\n if (schedule && occupied >= schedule.capacity)\n throw new Error('Scheduled retry capacity is full');\n if (\n slotKey &&\n typeof slotJobId === 'string' &&\n slotJobId !== current.id\n ) {\n const active = await tx.query(\n \"SELECT id FROM _smrt_jobs WHERE id = ? AND status IN ('pending', 'running')\",\n slotJobId,\n );\n if (active.rows.length)\n throw new Error('Another job already reserves this dedupeKey');\n }\n const retriedAt = new Date().toISOString();\n // A handler job's unclaimed deadline counts from run_at (#5005): a\n // retry restarts it, or the next sweep would fail the job again.\n const retried = await tx.query(\n `UPDATE _smrt_jobs SET status = 'pending', attempts = 0, last_error = NULL,\n started_at = NULL, completed_at = NULL, worker_id = NULL, worker_heartbeat = NULL,\n run_at = CASE WHEN ${HANDLER_TARGET_SQL} AND run_at < ? THEN ? ELSE run_at END,\n updated_at = ? WHERE id = ? AND ${tenantPredicate}\n AND status IN ('pending', 'failed', 'cancelled')\n RETURNING ${SMRT_JOB_PORTABLE_SELECT_COLUMNS}`,\n retriedAt,\n retriedAt,\n retriedAt,\n current.id,\n ...tenantValues,\n );\n if (retried.rows.length !== 1)\n throw new Error('Job status changed before retry');\n if (slotKey)\n await tx.query(\n 'UPDATE _smrt_job_dedupe_slots SET job_id = ? WHERE slot_key = ?',\n current.id,\n slotKey,\n );\n if (schedule)\n await tx.query(\n `UPDATE _smrt_agent_schedules SET running_count = ? WHERE id = ? AND ${tenantPredicate}`,\n occupied + 1,\n schedule.id,\n ...tenantValues,\n );\n return retried.rows[0];\n };\n let row: Record<string, unknown>;\n if (options.transaction) row = await retry(options.transaction);\n else {\n if (!executor.transaction)\n throw new Error('Job retry requires transaction support');\n row = await executor.transaction(retry);\n }\n // Hydrate the authoritative revision and immutable stored arguments. Do not\n // save caller-edited business fields or leak an ended transaction handle.\n await this.loadDataFromDb(row);\n }\n\n /**\n * Cancel the job\n */\n async cancel(): Promise<void> {\n if (this.status === 'completed' || this.status === 'cancelled') {\n throw new Error(`Cannot cancel job with status: ${this.status}`);\n }\n\n const snapshot = terminalSnapshot(this);\n if (!snapshot) throw new Error('Cannot cancel an unpersisted job');\n const contextTenantId = getTenantId();\n if (\n contextTenantId &&\n snapshot.tenantId !== contextTenantId &&\n !isSystemContext() &&\n !isSuperAdminBypass()\n ) {\n throw new TenantIsolationError(\n `Tenant isolation violation: cannot cancel SmrtJob with tenantId '${snapshot.tenantId}' in context of tenant '${contextTenantId}'`,\n {\n tenantId: contextTenantId,\n attemptedTenantId: snapshot.tenantId ?? 'null',\n },\n );\n }\n const completedAt = new Date();\n const event = await transitionTerminalJob(this.db, {\n job: snapshot,\n status: 'cancelled',\n completedAt,\n expectedStatuses: ['pending', 'running', 'failed'],\n });\n if (!event) throw new Error('Job status changed before cancellation');\n\n this.status = 'cancelled';\n this.completedAt = completedAt;\n this.updated_at = completedAt;\n }\n\n /**\n * Get a human-readable description of the job\n */\n getDescription(): string {\n const target = this.objectId\n ? `${this.objectType}#${this.objectId}`\n : this.objectType;\n return `${target}.${this.method}()`;\n }\n}\n\n/**\n * Job data type (for create operations)\n */\nexport interface SmrtJobData {\n /** At most one pending/running job per effective tenant and key. */\n dedupeKey?: string | null;\n tenantId?: string | null;\n queue?: string;\n objectType: string;\n objectId?: string | null;\n method: string;\n args?: Record<string, unknown>;\n runAt?: Date;\n priority?: number;\n maxAttempts?: number;\n timeout?: number;\n timeoutBehavior?: TimeoutBehavior;\n retryStrategy?: RetryStrategyConfig;\n /** MCP task correlation ID. Internal callers only. */\n taskId?: string | null;\n /** MCP task owner/principal ID. Internal callers only. */\n taskOwnerId?: string | null;\n /** Completed MCP CallToolResult. Internal callers only. */\n taskResult?: Record<string, unknown> | null;\n /** Outstanding MCP task input requests. Internal callers only. */\n taskInputRequests?: Record<string, unknown> | null;\n /** Accepted MCP task input responses. Internal callers only. */\n taskInputResponses?: Record<string, unknown> | null;\n}\n\n/**\n * A job that targets a registered named handler (#5005) instead of a model\n * method. Stored as `object_type = 'handler:<handler>'`, `method = 'handle'`,\n * `object_id = NULL`, `args = payload`.\n */\nexport interface HandlerJobData\n extends Omit<\n SmrtJobData,\n | 'objectType'\n | 'objectId'\n | 'method'\n | 'args'\n | 'taskId'\n | 'taskOwnerId'\n | 'taskResult'\n | 'taskInputRequests'\n | 'taskInputResponses'\n > {\n /** Namespaced handler name, e.g. `@happyvertical/smrt-workflows:workflow-run`. */\n handler: string;\n /** JSON payload passed to the handler. Reserved `_`-prefixed runner keys are refused. */\n payload?: Record<string, unknown>;\n}\n\n/** Runner-owned argument keys a handler payload may not carry. */\nconst HANDLER_RESERVED_ARG_KEYS = [\n '_mcpTask',\n '_agentConfig',\n '_scheduleId',\n '_scheduledFor',\n '_scheduleAdmission',\n] as const;\n\n/**\n * A handler-form row must be canonical: valid name, fixed method, no object\n * id, no MCP task fields, a plain JSON object payload without runner keys.\n */\nfunction assertHandlerJobData(data: SmrtJobData): void {\n assertJobHandlerName(jobHandlerName(data.objectType));\n if (data.method !== JOB_HANDLER_METHOD)\n throw new TypeError(\n `A handler job's method must be '${JOB_HANDLER_METHOD}'`,\n );\n if (data.objectId != null)\n throw new TypeError('A handler job cannot have an objectId');\n if (\n data.taskId != null ||\n data.taskOwnerId != null ||\n data.taskResult != null ||\n data.taskInputRequests != null ||\n data.taskInputResponses != null\n )\n throw new TypeError('A handler job cannot be an MCP task');\n const args = data.args ?? {};\n if (!args || typeof args !== 'object' || Array.isArray(args))\n throw new TypeError('A handler job payload must be a JSON object');\n for (const key of HANDLER_RESERVED_ARG_KEYS) {\n if (Object.hasOwn(args, key))\n throw new TypeError(`A handler job payload cannot set reserved ${key}`);\n }\n}\n\n/**\n * Options controlling a centralized {@link SmrtJobCollection.enqueueJob} call.\n */\nexport interface EnqueueJobOptions {\n /**\n * Per-tenant in-flight cap. Defaults to {@link DEFAULT_TENANT_JOB_CAP}.\n * `0`/negative disables the cap (trusted internal callers). Global\n * (no-context / null tenant) jobs are always exempt.\n */\n tenantJobCap?: number;\n /**\n * Existing caller-owned transaction. All enqueue reads/writes use this handle;\n * the caller must propagate failures and commit/rollback the transaction.\n * Avoids nested transactions on engines without savepoints (DuckDB).\n */\n transaction?: DatabaseInterface;\n}\n\n/**\n * Options for listReady\n */\nexport interface ListReadyOptions {\n limit?: number;\n queues?: string[];\n /** Allowed tenant identities; undefined selects all, [] selects none. */\n tenantIds?: readonly (string | null)[];\n}\n\n// The DB and worker incarnation own this clock, not the job row. Legacy retry\n// and surplus-release paths may clear started_at without reusing this identity.\nconst fencedClaimTimes = new WeakMap<object, Map<string, number>>();\n\n/** Options for atomically claiming ready jobs. */\nexport interface ClaimReadyOptions extends ListReadyOptions {\n /** Opt into dispatch fencing; one unique worker incarnation per DB/process. */\n claimFencing?: boolean;\n workerId: string;\n now?: Date;\n /**\n * Handler names this claimant serves (#5005). When set, the claim takes\n * model jobs and only the handler jobs named here; `[]` takes no handler\n * job. Omitted, the claim does not filter by target. At most\n * {@link MAX_JOB_HANDLERS} names (one bound parameter each).\n */\n handlerNames?: readonly string[];\n}\n\n/**\n * SQL that is true for a stored handler target. A case-exact, wildcard-free\n * prefix test (SQLite `LIKE` is case-insensitive), the same on SQLite,\n * PostgreSQL and PGlite, and matching `isJobHandlerTarget`.\n */\nexport const HANDLER_TARGET_SQL = `substr(object_type, 1, ${JOB_HANDLER_TARGET_PREFIX.length}) = '${JOB_HANDLER_TARGET_PREFIX}'`;\n\n/** The claim filter for a claimant serving `handlerNames` (#5005). */\nfunction handlerClaimFilter(handlerNames: readonly string[]): {\n sql: string;\n params: string[];\n} {\n if (handlerNames.length > MAX_JOB_HANDLERS) {\n throw new RangeError(\n `claimReady accepts at most ${MAX_JOB_HANDLERS} handler names`,\n );\n }\n const notHandler = `NOT (${HANDLER_TARGET_SQL})`;\n if (handlerNames.length === 0) return { sql: notHandler, params: [] };\n return {\n sql: `(${notHandler} OR object_type IN (${handlerNames.map(() => '?').join(', ')}))`,\n params: handlerNames.map((name) => jobHandlerTarget(name).objectType),\n };\n}\n\ntype DatabaseWithConfig = DatabaseInterface & {\n config?: {\n type?: string;\n url?: string;\n };\n type?: string;\n};\n\n/**\n * Collection for managing SmrtJob objects\n */\nexport class SmrtJobCollection extends SmrtCollection<SmrtJob> {\n static readonly _itemClass = SmrtJob;\n\n override async initialize(): Promise<this> {\n await super.initialize();\n await ensureJobsSystemTableCompatibility(this.db);\n return this;\n }\n\n /**\n * List jobs by status\n */\n async listByStatus(\n status: JobStatus | JobStatus[],\n options: { limit?: number; queue?: string } = {},\n ): Promise<SmrtJob[]> {\n const where: Record<string, unknown> = {\n status: Array.isArray(status) ? status : [status],\n };\n\n if (options.queue) {\n where.queue = options.queue;\n }\n\n return this.list({\n where,\n orderBy: ['priority DESC', 'run_at ASC'],\n limit: options.limit,\n });\n }\n\n /**\n * List pending jobs ready to run\n */\n async listReady(options: ListReadyOptions = {}): Promise<SmrtJob[]> {\n const now = new Date().toISOString();\n const whereConditions: string[] = [\n \"status = 'pending'\",\n 'run_at <= ?',\n '(task_input_requests IS NULL OR task_input_responses IS NOT NULL)',\n ];\n const params: unknown[] = [now];\n\n if (options.queues?.length) {\n const placeholders = options.queues.map(() => '?').join(', ');\n whereConditions.push(`queue IN (${placeholders})`);\n params.push(...options.queues);\n }\n\n const scope = jobTenantScope(options.tenantIds);\n params.push(...scope.params);\n params.push(options.limit || 100);\n\n // Worker-internal scan: the runner intentionally processes ready jobs\n // across all tenants, so it manages tenant context per-job at execution\n // time rather than filtering here (SmrtJob is now @TenantScoped, S5 #1402).\n return this.query(\n `SELECT * FROM _smrt_jobs WHERE ${whereConditions.join(' AND ')}${scope.sql} ORDER BY priority DESC, run_at ASC LIMIT ?`,\n params,\n { allowRawOnTenantScoped: true },\n );\n }\n\n /**\n * Atomically claim pending jobs ready to run for a worker.\n *\n * The claim is performed as one conditional UPDATE so concurrent workers\n * cannot receive the same pending row, and it never claims more than\n * `limit` rows. PostgreSQL additionally skips rows locked by other workers\n * instead of waiting behind them.\n *\n * On PostgreSQL the candidate set is selected once in a `MATERIALIZED` CTE\n * and the UPDATE joins to it. The previous `WHERE id IN (SELECT … LIMIT ?\n * FOR UPDATE SKIP LOCKED)` form let the planner choose a nested-loop semi\n * join that rescans the subquery for every outer pending row; each rescan\n * skipped the row the statement had just updated and returned the next one,\n * so a single claim could take the whole backlog and a `concurrency: 1`\n * runner started every ready job at once (#3145).\n */\n async claimReady(options: ClaimReadyOptions): Promise<SmrtJob[]> {\n const limit = options.limit ?? 100;\n if (limit <= 0) return [];\n\n const now = options.now ?? new Date();\n const nowIso = now.toISOString();\n let startedAt = nowIso;\n if (options.claimFencing) {\n let clock = fencedClaimTimes.get(this.db);\n if (!clock) {\n clock = new Map();\n fencedClaimTimes.set(this.db, clock);\n }\n // Reserve before awaiting SQL: concurrent claims on this incarnation also\n // get distinct generations. Clock steps never defer ready work. A restart\n // must use a new worker incarnation (TaskRunner already guarantees this).\n const stamp = Math.max(\n now.getTime(),\n (clock.get(options.workerId) ?? -Infinity) + 1,\n );\n startedAt = new Date(stamp).toISOString();\n clock.set(options.workerId, stamp);\n }\n const whereConditions: string[] = [\n \"status = 'pending'\",\n 'run_at <= ?',\n '(task_input_requests IS NULL OR task_input_responses IS NOT NULL)',\n ];\n const whereParams: unknown[] = [nowIso];\n\n if (options.queues?.length) {\n const placeholders = options.queues.map(() => '?').join(', ');\n whereConditions.push(`queue IN (${placeholders})`);\n whereParams.push(...options.queues);\n }\n\n // Inside the candidate select, before its LIMIT: handler rows this\n // claimant cannot run must not fill the window and starve its work.\n if (options.handlerNames !== undefined) {\n const filter = handlerClaimFilter(options.handlerNames);\n whereConditions.push(filter.sql);\n whereParams.push(...filter.params);\n }\n\n const scope = jobTenantScope(options.tenantIds);\n whereParams.push(...scope.params);\n const isPostgres = getDatabaseEngine(this.db) === 'postgres';\n const candidateSelect = `\n SELECT id AS claim_id\n FROM _smrt_jobs\n WHERE ${whereConditions.join(' AND ')}${scope.sql}\n ORDER BY priority DESC, run_at ASC, created_at ASC, id ASC\n LIMIT ?${isPostgres ? ' FOR UPDATE SKIP LOCKED' : ''}\n `;\n const setClause = `\n SET status = 'running',\n worker_id = ?,\n worker_heartbeat = ?,\n started_at = ?,\n attempts = attempts + 1,\n updated_at = ?`;\n const setParams = [options.workerId, nowIso, startedAt, nowIso];\n\n // Worker-internal cross-tenant claim; tenant context is restored\n // per-job at execution (SmrtJob is now @TenantScoped, S5 #1402).\n const claimed = isPostgres\n ? await this.query(\n `WITH claim_candidates AS MATERIALIZED (${candidateSelect})\n UPDATE _smrt_jobs${setClause}\n FROM claim_candidates\n WHERE _smrt_jobs.id = claim_candidates.claim_id\n AND _smrt_jobs.status = 'pending'\n RETURNING ${SMRT_JOB_PORTABLE_SELECT_COLUMNS}`,\n [...whereParams, limit, ...setParams],\n { allowRawOnTenantScoped: true },\n )\n : await this.query(\n `UPDATE _smrt_jobs${setClause}\n WHERE id IN (${candidateSelect})\n AND status = 'pending'\n RETURNING ${SMRT_JOB_PORTABLE_SELECT_COLUMNS}`,\n [...setParams, ...whereParams, limit],\n { allowRawOnTenantScoped: true },\n );\n\n return claimed.toSorted(compareClaimOrder);\n }\n\n /**\n * Count non-terminal (pending/running) jobs owned by a tenant.\n *\n * Used to enforce the per-tenant creation cap so one tenant cannot exhaust\n * the shared worker pool (S5 audit #1402). Reads `_smrt_jobs` directly so it\n * works regardless of ambient tenant context.\n *\n * @param tenantId - Tenant to count for. `null` counts global (NULL-tenant)\n * jobs.\n */\n async countInFlightForTenant(tenantId: string | null): Promise<number> {\n const predicate = tenantId === null ? 'tenant_id IS NULL' : 'tenant_id = ?';\n const params = tenantId === null ? [] : [tenantId];\n\n // Use the public `db` accessor (with its init guard), not the protected\n // `_db` internal — consistent with claimReady()/this.db usage above. This\n // is a deliberately cross-tenant count (it must see every tenant's rows to\n // bound a single tenant), so it intentionally bypasses the tenant-scoped\n // query interceptor rather than routing through this.query().\n const result = await this.db.query(\n `SELECT COUNT(*) AS count\n FROM _smrt_jobs\n WHERE status IN ('pending', 'running')\n AND ${predicate}`,\n ...params,\n );\n\n const row = result.rows[0] as { count?: number | string } | undefined;\n return Number(row?.count ?? 0);\n }\n\n /**\n * The single creation path for queued jobs.\n *\n * Centralizes the two creation-time security guards from the S5 audit (#1402)\n * so every enqueue — the fluent {@link \"./job-builder\".JobBuilder} *and* the\n * ScheduleRunner's cron-triggered jobs — goes through one place:\n *\n * 1. `maxAttempts` is clamped to {@link MAX_JOB_RETRIES} so a misconfigured\n * caller cannot pin a worker on a poison job indefinitely.\n * 2. A per-tenant in-flight cap bounds how many non-terminal jobs one tenant\n * may hold, so one tenant cannot exhaust the shared worker pool\n * (cross-tenant denial of service). The cap applies to the row's effective\n * tenant (explicit `data.tenantId` or, when absent, the ambient context);\n * global (null-tenant) jobs are exempt.\n *\n * Atomicity note (best-effort soft cap, by design): the cap is a\n * count-then-insert, NOT a hard transactional invariant. It is intentionally\n * left non-atomic. A plain transaction would not help — under the adapters'\n * default isolation two concurrent same-tenant enqueues would each read the\n * same COUNT and both insert, so serializing them would require either a\n * per-tenant lock row (`SELECT ... FOR UPDATE`) or SERIALIZABLE-isolation\n * retry loops. That cross-process locking is fragile (lock-row contention,\n * adapter-specific isolation behavior, the `transaction` adapter method being\n * optional) and out of proportion to the threat: this cap is defense in depth\n * against runaway/accidental creation exhausting the shared worker pool, not a\n * billing/quota boundary. So under truly simultaneous enqueues a tenant may\n * momentarily overshoot by the number of in-flight creators; the bound still\n * prevents unbounded growth and closes the prior ScheduleRunner bypass. If a\n * hard guarantee is ever needed, enforce it with a DB CHECK/trigger or a\n * dedicated counter row, not an application-level lock.\n */\n async enqueueJob(\n data: SmrtJobData,\n options: EnqueueJobOptions = {},\n ): Promise<SmrtJob> {\n const cap = options.tenantJobCap ?? DEFAULT_TENANT_JOB_CAP;\n if (isJobHandlerTarget(data.objectType)) assertHandlerJobData(data);\n\n // Effective tenant: an explicitly provided tenantId wins (ScheduleRunner\n // passes the schedule's tenant even when no ambient context exists);\n // otherwise fall back to the ambient context (JobBuilder path).\n const explicitTenant =\n typeof data.tenantId === 'string' && data.tenantId.length > 0\n ? data.tenantId\n : data.tenantId === null\n ? null\n : undefined;\n const effectiveTenant =\n explicitTenant !== undefined ? explicitTenant : (getTenantId() ?? null);\n\n if (data.dedupeKey != null) {\n if (\n typeof data.dedupeKey !== 'string' ||\n data.dedupeKey.trim().length === 0 ||\n data.dedupeKey.length > 512\n ) {\n throw new TypeError(\n 'dedupeKey must be a nonblank string of at most 512 characters',\n );\n }\n assertDedupeTenantSpelling(effectiveTenant);\n const ambientTenant = getTenantId();\n assertDedupeTenantSpelling(ambientTenant ?? null);\n if (\n ambientTenant &&\n effectiveTenant !== ambientTenant &&\n !isSystemContext() &&\n !isSuperAdminBypass()\n ) {\n throw new TenantIsolationError(\n 'Cannot enqueue a job for another tenant',\n {\n tenantId: ambientTenant,\n attemptedTenantId: effectiveTenant ?? 'null',\n },\n );\n }\n const db = options.transaction ?? this.db;\n if (!options.transaction && !db.transaction)\n throw new Error('Job deduplication requires transaction support');\n await SmrtJobDedupeSlotCollection.create({ db });\n const slotKey = jobSlotKey(effectiveTenant, data.dedupeKey);\n const enqueue = async (tx: DatabaseInterface): Promise<string> => {\n const id = randomUUID();\n const now = new Date().toISOString();\n await tx.query(\n `INSERT INTO _smrt_job_dedupe_slots\n (id, slug, context, created_at, updated_at, slot_key, job_id)\n VALUES (?, ?, '', ?, ?, ?, NULL) ON CONFLICT (slot_key) DO NOTHING`,\n id,\n id,\n now,\n now,\n slotKey,\n );\n const slot = await tx.query(\n `UPDATE _smrt_job_dedupe_slots SET updated_at = ?\n WHERE slot_key = ? RETURNING job_id`,\n now,\n slotKey,\n );\n if (slot.rows.length !== 1)\n throw new Error('Job deduplication slot unavailable; retry enqueue');\n const jobs = await SmrtJobCollection.create({ db: tx });\n const jobId = slot.rows[0].job_id;\n if (typeof jobId === 'string') {\n const existing = await jobs.get({ id: jobId });\n if (existing && (existing.tenantId ?? null) !== effectiveTenant)\n throw new Error(\n 'Job deduplication slot has invalid tenant ownership',\n );\n if (\n existing &&\n (existing.status === 'pending' || existing.status === 'running')\n )\n return String(existing.id);\n }\n // Store provenance in the initial insert without reacquiring the slot.\n const job = await jobs.createQueuedJob(\n { ...data, tenantId: effectiveTenant },\n cap,\n );\n await tx.query(\n 'UPDATE _smrt_job_dedupe_slots SET job_id = ? WHERE slot_key = ?',\n job.id,\n slotKey,\n );\n return String(job.id);\n };\n let jobId: string;\n if (options.transaction) jobId = await enqueue(options.transaction);\n else {\n if (!db.transaction)\n throw new Error('Job deduplication requires transaction support');\n jobId = await db.transaction(enqueue);\n }\n // Do not return a model bound to a now-ended transaction.\n const resultCollection = options.transaction\n ? await SmrtJobCollection.create({ db: options.transaction })\n : this;\n const job = await resultCollection.get({ id: jobId });\n if (!job) throw new Error('Enqueued job is unavailable');\n return job;\n }\n if (options.transaction) {\n const jobs = await SmrtJobCollection.create({ db: options.transaction });\n return jobs.createQueuedJob({ ...data, tenantId: effectiveTenant }, cap);\n }\n return this.createQueuedJob({ ...data, tenantId: effectiveTenant }, cap);\n }\n\n /**\n * Enqueue a job for a registered named handler (#5005). The handler need\n * not be registered in this process: producers and runners are usually\n * different processes. Only runners that registered the handler claim the\n * job; one still `pending` past the runners' `handlerUnclaimedDeadlineMs`\n * is failed `handler-unclaimed`. Guards, dedupe and tenancy are those of\n * {@link enqueueJob}.\n */\n async enqueueHandlerJob(\n data: HandlerJobData,\n options: EnqueueJobOptions = {},\n ): Promise<SmrtJob> {\n const { handler, payload, ...rest } = data;\n return this.enqueueJob(\n {\n ...rest,\n ...jobHandlerTarget(handler),\n objectId: null,\n args: payload ?? {},\n },\n options,\n );\n }\n\n /** Persist once, without a second save racing a consumer's first claim. */\n private async createQueuedJob(\n data: SmrtJobData,\n cap: number,\n ): Promise<SmrtJob> {\n const effectiveTenant = data.tenantId;\n if (effectiveTenant && cap > 0) {\n const current = await this.countInFlightForTenant(effectiveTenant);\n assertWithinTenantCreationCap(effectiveTenant, current, cap);\n }\n\n const job = await this.create({\n ...data,\n // Clamp here so neither the builder nor the schedule runner can bypass the\n // retry ceiling (S5 audit #1402).\n maxAttempts: clampRetries(data.maxAttempts ?? 3),\n });\n return job;\n }\n\n /**\n * Get job statistics\n */\n async stats(queue?: string): Promise<{\n pending: number;\n running: number;\n completed: number;\n failed: number;\n cancelled: number;\n }> {\n const query = queue\n ? 'SELECT status, COUNT(*) as count FROM _smrt_jobs WHERE queue = ? GROUP BY status'\n : 'SELECT status, COUNT(*) as count FROM _smrt_jobs GROUP BY status';\n const params = queue ? [queue] : [];\n\n const result = await this._db.query(query, ...params);\n\n const counts: Record<string, number> = {};\n for (const row of result.rows) {\n counts[row.status as string] = row.count as number;\n }\n\n return {\n pending: counts.pending ?? 0,\n running: counts.running ?? 0,\n completed: counts.completed ?? 0,\n failed: counts.failed ?? 0,\n cancelled: counts.cancelled ?? 0,\n };\n }\n\n /**\n * Cleanup old completed/failed jobs.\n *\n * Predicates are `(status, completed_at)` pairs, covered by\n * `idx_smrt_jobs_status_completed_at` (created by the jobs compatibility\n * path this collection runs on initialize — #2375).\n *\n * @param options.dryRun - Count the jobs the cutoffs select without deleting\n * them, so a retention preview reports exactly what a real run removes.\n * @returns Number of jobs deleted (or, under `dryRun`, matched).\n */\n async cleanup(options: {\n completedBefore?: Date;\n failedBefore?: Date;\n cancelledBefore?: Date;\n limit?: number;\n dryRun?: boolean;\n }): Promise<number> {\n const conditions: string[] = [];\n const params: unknown[] = [];\n\n if (options.completedBefore) {\n conditions.push(\"(status = 'completed' AND completed_at < ?)\");\n params.push(options.completedBefore.toISOString());\n }\n\n if (options.failedBefore) {\n conditions.push(\"(status = 'failed' AND completed_at < ?)\");\n params.push(options.failedBefore.toISOString());\n }\n\n if (options.cancelledBefore) {\n conditions.push(\"(status = 'cancelled' AND completed_at < ?)\");\n params.push(options.cancelledBefore.toISOString());\n }\n\n if (conditions.length === 0) return 0;\n\n const selector = options.limit\n ? `id IN (\n SELECT id FROM _smrt_jobs\n WHERE (${conditions.join(' OR ')})\n LIMIT ?\n )`\n : `(${conditions.join(' OR ')})`;\n const selectorParams = options.limit\n ? [...params, options.limit]\n : [...params];\n\n // Count first: `rowCount` is not reliably populated across the engines\n // SMRT supports, and counting is what lets `dryRun` preview the exact\n // predicate a real cleanup would delete (#2375).\n const counted = await this._db.query(\n `SELECT COUNT(*) AS total FROM _smrt_jobs WHERE ${selector}`,\n ...selectorParams,\n );\n const total = Number(counted.rows?.[0]?.total ?? 0);\n if (!Number.isFinite(total) || total <= 0) return 0;\n\n if (!options.dryRun) {\n await this._db.query(\n `DELETE FROM _smrt_jobs WHERE ${selector}`,\n ...selectorParams,\n );\n }\n\n return total;\n }\n}\n\nfunction getDatabaseEngine(\n db: DatabaseInterface,\n): ReturnType<typeof detectEngine> {\n return resolveEngine(db);\n}\n\nfunction compareClaimOrder(left: SmrtJob, right: SmrtJob): number {\n const priority = right.priority - left.priority;\n if (priority !== 0) return priority;\n\n const runAt = left.runAt.getTime() - right.runAt.getTime();\n if (runAt !== 0) return runAt;\n\n const createdAt = timestamp(left.created_at) - timestamp(right.created_at);\n if (createdAt !== 0) return createdAt;\n\n return (left.id ?? '').localeCompare(right.id ?? '');\n}\n\nfunction timestamp(value: Date | null | undefined): number {\n return value?.getTime() ?? 0;\n}\n\nexport default SmrtJob;\n\nfunction jobSlotKey(tenant: string | null, key: string): string {\n return createHash('sha256')\n .update(JSON.stringify([tenant, key]))\n .digest('hex');\n}\n\n/** Internal SQL predicate shared by ready claims and worker recovery. */\nexport function jobTenantScope(\n tenantIds: readonly (string | null)[] | undefined,\n): { sql: string; params: string[] } {\n if (tenantIds === undefined) return { sql: '', params: [] };\n if (\n !Array.isArray(tenantIds) ||\n tenantIds.some(\n (id) => id !== null && (typeof id !== 'string' || !id.trim()),\n )\n )\n throw new TypeError('tenantIds must contain nonblank identities or null');\n const ids = tenantIds.filter((id): id is string => id !== null);\n const terms: string[] = [];\n if (ids.length) terms.push(`tenant_id IN (${ids.map(() => '?').join(', ')})`);\n if (tenantIds.includes(null)) terms.push('tenant_id IS NULL');\n return {\n sql: ` AND ${terms.length ? `(${terms.join(' OR ')})` : '1 = 0'}`,\n params: ids,\n };\n}\n\ntype RetryJobRow = Record<string, unknown> & {\n id: string;\n tenant_id: string | null;\n dedupe_key: string | null;\n status: JobStatus;\n args: unknown;\n};\n\nfunction retryRow(row: Record<string, unknown>): RetryJobRow {\n if (\n typeof row.id !== 'string' ||\n (row.tenant_id !== null && typeof row.tenant_id !== 'string')\n )\n throw new Error('Invalid persisted job identity');\n return row as RetryJobRow;\n}\n\nasync function readRetryJob(\n db: DatabaseInterface,\n id: string,\n): Promise<RetryJobRow> {\n const result = await db.query(\n `SELECT ${SMRT_JOB_PORTABLE_SELECT_COLUMNS} FROM _smrt_jobs WHERE id = ?`,\n id,\n );\n if (result.rows.length !== 1)\n throw new Error('Persisted retry job is unavailable');\n return retryRow(result.rows[0]);\n}\n\nfunction assertRetryTenant(tenant: string | null): void {\n const ambient = getTenantId();\n if (\n ambient &&\n tenant !== ambient &&\n !isSystemContext() &&\n !isSuperAdminBypass()\n ) {\n throw new TenantIsolationError('Cannot retry a job for another tenant', {\n tenantId: ambient,\n attemptedTenantId: tenant ?? 'null',\n });\n }\n}\n\nfunction assertRetryStatus(status: JobStatus): void {\n if (status === 'completed' || status === 'running')\n throw new Error(`Cannot retry a ${status} job`);\n if (!['pending', 'failed', 'cancelled'].includes(status))\n throw new Error('Unknown persisted retry job status');\n}\n\nfunction persistedDedupeKey(value: unknown): string | null {\n if (value === null) return null;\n if (typeof value !== 'string' || !value.trim())\n throw new Error('Invalid persisted dedupeKey');\n return value;\n}\n\nfunction persistedArguments(value: unknown): Record<string, unknown> {\n const args = typeof value === 'string' ? JSON.parse(value) : value;\n if (!args || typeof args !== 'object' || Array.isArray(args))\n throw new Error('Invalid persisted job arguments');\n return args as Record<string, unknown>;\n}\n\ninterface PersistedScheduleAssociation {\n id: string;\n canonicalOccurrence: boolean;\n}\nfunction persistedScheduleAssociation(\n value: unknown,\n): PersistedScheduleAssociation | null {\n const args = persistedArguments(value);\n const canonicalOccurrence =\n Object.hasOwn(args, '_scheduledFor') ||\n Object.hasOwn(args, '_scheduleAdmission');\n if (!Object.hasOwn(args, '_scheduleId')) {\n if (canonicalOccurrence)\n throw new Error('Invalid persisted schedule association');\n return null;\n }\n if (typeof args._scheduleId !== 'string' || !args._scheduleId.trim())\n throw new Error('Invalid persisted schedule association');\n return { id: args._scheduleId, canonicalOccurrence };\n}\n\n/** @internal Execution target of an AgentSchedule, independent of caller metadata names. */\nexport interface ScheduleJobTarget {\n objectType: string;\n objectId: string | null;\n method: string;\n}\nfunction persistedJobTarget(row: Record<string, unknown>): ScheduleJobTarget {\n if (\n typeof row.object_type !== 'string' ||\n typeof row.method !== 'string' ||\n (row.object_id !== null && typeof row.object_id !== 'string')\n )\n throw new Error('Invalid persisted retry target');\n return {\n objectType: row.object_type,\n objectId: row.object_id as string | null,\n method: row.method,\n };\n}\nfunction scheduleJobTarget(row: Record<string, unknown>): ScheduleJobTarget {\n return {\n objectType: String(row.agent_type ?? ''),\n objectId: row.agent_id == null ? null : String(row.agent_id),\n method: String(row.method || 'run'),\n };\n}\nfunction sameScheduleTarget(\n left: ScheduleJobTarget,\n right: ScheduleJobTarget,\n): boolean {\n const canonical = (name: string) =>\n ObjectRegistry.getClass(name)?.qualifiedName || name;\n return (\n canonical(left.objectType) === canonical(right.objectType) &&\n left.objectId === right.objectId &&\n left.method === right.method\n );\n}\nasync function lockRetrySchedule(\n tx: DatabaseInterface,\n association: PersistedScheduleAssociation,\n job: RetryJobRow,\n): Promise<{ id: string; capacity: number; target: ScheduleJobTarget } | null> {\n // _scheduleId predates AgentSchedule admission and is also ordinary producer\n // metadata. Do not issue missing-table SQL and then continue an aborted PG tx.\n if (!(await tx.tableExists('_smrt_agent_schedules'))) {\n if (association.canonicalOccurrence)\n throw new Error('Scheduled retry association is unavailable');\n return null;\n }\n const predicate =\n job.tenant_id === null ? 'tenant_id IS NULL' : 'tenant_id = ?';\n const tenants = job.tenant_id === null ? [] : [job.tenant_id];\n const columns =\n 'CAST(id AS VARCHAR) AS id, agent_type, CAST(agent_id AS VARCHAR) AS agent_id, method, max_concurrent';\n // Cast the read identity so unrelated producers' opaque metadata never causes\n // an invalid-UUID error merely because an AgentSchedule table is installed.\n const candidate = (\n await tx.query(\n `SELECT ${columns} FROM _smrt_agent_schedules WHERE CAST(id AS VARCHAR) = ? AND ${predicate}`,\n association.id,\n ...tenants,\n )\n ).rows[0];\n if (\n !candidate ||\n (!association.canonicalOccurrence &&\n !sameScheduleTarget(\n persistedJobTarget(job),\n scheduleJobTarget(candidate),\n ))\n ) {\n if (association.canonicalOccurrence)\n throw new Error('Scheduled retry association is unavailable');\n return null;\n }\n const locked = (\n await tx.query(\n `UPDATE _smrt_agent_schedules SET running_count = running_count\n WHERE id = ? AND ${predicate} RETURNING ${columns}`,\n candidate.id,\n ...tenants,\n )\n ).rows[0];\n if (\n !locked ||\n (!association.canonicalOccurrence &&\n !sameScheduleTarget(persistedJobTarget(job), scheduleJobTarget(locked)))\n )\n throw new Error(\n 'Scheduled retry association changed; retry from current state',\n );\n const capacity = Number(locked.max_concurrent ?? 1);\n if (!Number.isSafeInteger(capacity) || capacity < 1)\n throw new Error('Scheduled retry capacity is invalid');\n return { id: String(locked.id), capacity, target: scheduleJobTarget(locked) };\n}\n\n/** @internal Count canonical occurrences and matching legacy target slots for admission/retry. */\nexport async function countScheduleJobs(\n db: DatabaseInterface,\n scheduleId: string,\n tenant: string | null,\n target: ScheduleJobTarget,\n excludeJobId?: string,\n): Promise<number> {\n const result = await db.query(\n `SELECT args, object_type, CAST(object_id AS VARCHAR) AS object_id, method FROM _smrt_jobs WHERE status IN ('pending', 'running')\n AND ${tenant === null ? 'tenant_id IS NULL' : 'tenant_id = ?'}${excludeJobId ? ' AND id <> ?' : ''}`,\n ...(tenant === null ? [] : [tenant]),\n ...(excludeJobId ? [excludeJobId] : []),\n );\n return result.rows.filter((row) => {\n try {\n const association = persistedScheduleAssociation(row.args);\n return (\n association?.id === scheduleId &&\n (association.canonicalOccurrence ||\n sameScheduleTarget(persistedJobTarget(row), target))\n );\n } catch {\n return false;\n }\n }).length;\n}\n\nfunction assertDedupeTenantSpelling(tenant: string | null): void {\n if (tenant === null) return;\n const uuidLike = /^[0-9a-f]{32}$/i.test(tenant.replace(/[{}-]/g, ''));\n const canonical =\n /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/.test(\n tenant,\n );\n if (uuidLike && !canonical)\n throw new TypeError(\n 'Keyed jobs require canonical lowercase hyphenated UUID tenant IDs; load the canonical tenant identity before enqueue',\n );\n}\n","/**\n * Job retention — bounded growth for `_smrt_jobs` and `_smrt_job_events`\n * (issue #2375, assessment finding F2).\n *\n * `SmrtJobCollection.cleanup()` has always existed but nothing ever called it,\n * and `_smrt_job_events` — one row per log line, progress tick and lifecycle\n * transition — had no prune path at all. This module contributes both to the\n * framework retention sweep so `smrt db:prune` and the `TaskRunner`'s periodic\n * sweep drive them like every other framework-owned table.\n *\n * The package entry point registers both tasks on import (see `index.ts`), so\n * any process that loaded `@happyvertical/smrt-jobs` — a worker, an app, or\n * `smrt db:prune` — contributes them. Registration is not scheduling: a task\n * runs only when something calls `runRetentionSweep()`, and a policy can turn\n * it off by name. Call {@link registerJobRetentionTasks} again to change the\n * windows, or {@link unregisterJobRetentionTasks} to remove them entirely.\n *\n * Task names are prefixed with the owning package's short name, because the\n * registry is one process-global namespace shared with every other package.\n *\n * @see https://github.com/happyvertical/smrt/issues/2375\n * @packageDocumentation\n */\n\nimport { createLogger } from '@happyvertical/logger';\nimport {\n type RetentionPolicy,\n type RetentionSweepResult,\n registerRetentionTask,\n runRetentionSweep,\n unregisterRetentionTask,\n} from '@happyvertical/smrt-core';\nimport type { DatabaseInterface } from '@happyvertical/sql';\nimport { SmrtJobCollection } from './smrt-job.js';\nimport { SmrtJobEventCollection } from './smrt-job-event.js';\n\nconst logger = createLogger({ level: 'info' });\n\nconst MS_PER_DAY = 24 * 60 * 60 * 1000;\n\n/** Retention task name for terminal rows in `_smrt_jobs`. */\nexport const JOBS_RETENTION_TASK = 'jobs-records';\n\n/** Retention task name for `_smrt_job_events`. */\nexport const JOB_EVENTS_RETENTION_TASK = 'jobs-events';\n\n/** Windows applied by the job retention tasks. */\nexport interface JobRetentionOptions {\n /** Delete completed jobs finished more than this many days ago (default 7). */\n completedOlderThanDays?: number;\n /** Delete cancelled jobs finished more than this many days ago (default 7). */\n cancelledOlderThanDays?: number;\n /** Delete failed jobs finished more than this many days ago (default 30). */\n failedOlderThanDays?: number;\n /** Delete job events recorded more than this many days ago (default 30). */\n eventsOlderThanDays?: number;\n /** Maximum job rows removed per sweep (default 10 000). */\n batchSize?: number;\n}\n\n/**\n * Documented job retention defaults.\n *\n * Completed and cancelled work is the bulk of the table and is uninteresting\n * within a week; failures are kept a month because that is how long anyone\n * looks at them. Events outlive the jobs they describe by design — a job row\n * deleted at 7 days can still have its log read for another three weeks.\n */\nexport const DEFAULT_JOB_RETENTION: Required<JobRetentionOptions> = {\n completedOlderThanDays: 7,\n cancelledOlderThanDays: 7,\n failedOlderThanDays: 30,\n eventsOlderThanDays: 30,\n batchSize: 10_000,\n};\n\n/**\n * Register the job and job-event retention tasks with the framework sweep.\n *\n * Idempotent: re-registering replaces the previous tasks, so repeated calls\n * (multiple runners in one process, module re-evaluation) do not duplicate\n * work.\n */\nexport function registerJobRetentionTasks(\n options: JobRetentionOptions = {},\n): void {\n const config = { ...DEFAULT_JOB_RETENTION, ...options };\n\n registerRetentionTask({\n name: JOBS_RETENTION_TASK,\n description: 'Prune terminal job rows (_smrt_jobs)',\n run: async (db, context) => {\n const jobs = await SmrtJobCollection.create({ db });\n const cutoff = (days: number) =>\n new Date(context.now.getTime() - days * MS_PER_DAY);\n\n return jobs.cleanup({\n completedBefore: cutoff(config.completedOlderThanDays),\n cancelledBefore: cutoff(config.cancelledOlderThanDays),\n failedBefore: cutoff(config.failedOlderThanDays),\n limit: config.batchSize,\n dryRun: context.dryRun,\n });\n },\n });\n\n registerRetentionTask({\n name: JOB_EVENTS_RETENTION_TASK,\n description: 'Prune job event history (_smrt_job_events)',\n run: async (db, context) => {\n const events = await SmrtJobEventCollection.create({ db });\n return events.cleanup({\n before: new Date(\n context.now.getTime() - config.eventsOlderThanDays * MS_PER_DAY,\n ),\n dryRun: context.dryRun,\n });\n },\n });\n}\n\n/** Remove the job retention tasks from the framework sweep. */\nexport function unregisterJobRetentionTasks(): void {\n unregisterRetentionTask(JOBS_RETENTION_TASK);\n unregisterRetentionTask(JOB_EVENTS_RETENTION_TASK);\n}\n\n/** Configuration for {@link startRetentionSweeper}. */\nexport interface RetentionSweeperOptions {\n /** How often to sweep, in milliseconds (default 6 hours). */\n intervalMs?: number;\n /** Policy handed to `runRetentionSweep` on each tick. */\n policy?: RetentionPolicy;\n /** Windows for the job retention tasks this sweeper registers. */\n jobs?: JobRetentionOptions;\n}\n\n/** Handle returned by {@link startRetentionSweeper}. */\nexport interface RetentionSweeper {\n /** Stop the periodic sweep timer. Does not unregister the job tasks. */\n stop(): void;\n /** Run one sweep immediately (used by tests and by manual triggers). */\n sweepNow(): Promise<RetentionSweepResult>;\n}\n\n/** Default sweep cadence: four times a day is ample for day-scale windows. */\nexport const DEFAULT_RETENTION_SWEEP_INTERVAL_MS = 6 * 60 * 60 * 1000;\n\n/**\n * Start a periodic retention sweep on an interval.\n *\n * The first sweep runs one full interval after start, never at start: a worker\n * process restarting in a crash loop must not turn into a delete loop, and a\n * short-lived process (a test, a one-shot worker) should exit without having\n * deleted anything it was not asked to.\n *\n * The timer is `unref`'d where the runtime supports it, so a pending sweep\n * never keeps a process alive.\n *\n * **`stop()` never unregisters the job tasks.** The package entry point\n * (`index.ts`) registers them unconditionally on import, so \"this process\n * loaded `@happyvertical/smrt-jobs`\" is what contributes them — not \"a\n * sweeper happens to be running\". Making `stop()` unregister would silently\n * break that contract the moment a `TaskRunner` restarts (or a second,\n * independent caller in the same process runs `runRetentionSweep()` after\n * the first sweeper stops): the tasks would vanish from the sweep even\n * though the package is still loaded. `options.jobs` still lets a caller\n * override the default windows — each call to this function re-registers\n * with whatever config it was given, the same idempotent replace\n * {@link registerJobRetentionTasks} already documents. Callers that want a\n * genuinely clean registry (tests, teardown) call\n * {@link unregisterJobRetentionTasks} themselves.\n *\n * @param db - Database holding the system tables.\n * @param options - Cadence and policy overrides.\n * @returns A handle that stops the periodic timer.\n */\nexport function startRetentionSweeper(\n db: DatabaseInterface,\n options: RetentionSweeperOptions = {},\n): RetentionSweeper {\n registerJobRetentionTasks(options.jobs);\n\n const intervalMs = options.intervalMs ?? DEFAULT_RETENTION_SWEEP_INTERVAL_MS;\n let stopped = false;\n\n const sweepNow = async (): Promise<RetentionSweepResult> =>\n runRetentionSweep(db, options.policy);\n\n const timer = setInterval(() => {\n if (stopped) return;\n sweepNow().catch((error) => {\n logger.warn(\n `[smrt-jobs] retention sweep failed: ${\n error instanceof Error ? error.message : String(error)\n }`,\n );\n });\n }, intervalMs);\n\n if (typeof timer === 'object' && typeof timer.unref === 'function') {\n timer.unref();\n }\n\n return {\n stop() {\n if (stopped) return;\n stopped = true;\n clearInterval(timer);\n },\n sweepNow,\n };\n}\n","/**\n * Redact secret-shaped substrings from a job error message before it is\n * persisted to the `_smrt_jobs.last_error` column.\n *\n * @remarks\n * `last_error` is durable and readable through generated `list`/`get` routes\n * (now tenant-scoped — see {@link \"./smrt-job\".SmrtJob}). Error messages thrown\n * from a failing job frequently echo back the arguments or environment that\n * caused the failure: a database URL with embedded credentials, a `Bearer`\n * token, an `Authorization` header, an API key, or a `key=value` secret pair.\n * Persisting those verbatim turns a transient failure into a durable credential\n * leak (S5 audit #1402).\n *\n * The policy biases toward over-redaction: matching a benign string is a\n * cosmetic loss, while leaking a credential is a security incident. Patterns are\n * intentionally conservative and order-independent — each is applied globally so\n * multiple secrets in one message are all masked.\n */\n\nconst REDACTED = '***REDACTED***';\n\n/**\n * Credentials embedded in a URL userinfo segment:\n * `scheme://user:pass@host` → `scheme://***REDACTED***@host`.\n * The host is preserved so the message stays diagnosable.\n */\nconst CREDENTIAL_URL_RE = /([a-z][a-z0-9+.-]*:\\/\\/)[^/?#@\\s]+@/gi;\n\n/**\n * `Bearer <token>` / `token <token>` style authorization values.\n */\nconst BEARER_TOKEN_RE = /\\b(bearer|token)\\s+[A-Za-z0-9._\\-+/=]{8,}/gi;\n\n/**\n * An `Authorization:` header value (covers Basic/Bearer/etc.). Captures the\n * scheme word plus the credential token that follows it so the whole value is\n * masked, not just the scheme.\n */\nconst AUTHORIZATION_HEADER_RE =\n /\\bauthorization\\s*[:=]\\s*(?:[A-Za-z]+\\s+)?[^\\s,;)]+/gi;\n\n/**\n * Common secret-bearing `key=value` / `key: value` pairs. The key portion is\n * preserved so the shape of the failure remains legible; only the value is\n * masked. Matches camelCase / snake_case / kebab / UPPER variants.\n */\nconst SECRET_KEY_VALUE_RE =\n /\\b([A-Za-z0-9_-]*(?:password|passwd|pwd|secret|api[_-]?key|access[_-]?key|secret[_-]?key|private[_-]?key|client[_-]?secret|token|credential|auth)[A-Za-z0-9_-]*)\\s*([:=])\\s*(\"[^\"]*\"|'[^']*'|[^\\s,;)]+)/gi;\n\n/**\n * Secret-bearing keys written as JSON object members, e.g.\n * `{\"password\":\"x\"}` or `{ \"apiKey\" : \"y\" }`. The generic key=value rule above\n * cannot see these because the key is wrapped in quotes (so the separator does\n * not immediately follow the key word). The quoted key is preserved; only the\n * quoted value is masked (S5 audit #1402).\n */\nconst JSON_SECRET_KEY_VALUE_RE =\n /(\"(?:[A-Za-z0-9_-]*(?:password|passwd|pwd|secret|api[_-]?key|access[_-]?key|secret[_-]?key|private[_-]?key|client[_-]?secret|token|credential|auth)[A-Za-z0-9_-]*)\")\\s*:\\s*\"[^\"]*\"/gi;\n\n/**\n * Provider-recognizable standalone secrets that may appear without a key:\n * OpenAI `sk-...` (incl. hyphenated project keys like `sk-proj-...`) /\n * `sk_live_...` / `sk_test_...`, AWS access key id (`AKIA...`), GitHub tokens\n * (`ghp_`/`gho_`/`ghu_`/`ghs_`/`ghr_`), Google API keys (`AIza...`), and Slack\n * bot/user tokens (`xoxb-`/`xoxp-`) (S5 audit #1402).\n *\n * The OpenAI patterns allow internal hyphens/underscores in the token *body*\n * (after the `sk-`/`sk_` prefix) so segmented keys such as `sk-proj-ABC123...`\n * are matched whole rather than truncated at the first separator. The body must\n * end on an alphanumeric so a trailing separator is not swallowed, and a length\n * floor keeps short benign `sk-foo` tokens from over-matching.\n */\nconst STANDALONE_SECRET_RE =\n /\\b(sk-[A-Za-z0-9_-]{14,}[A-Za-z0-9]|sk_(?:live|test)_[A-Za-z0-9_-]{14,}[A-Za-z0-9]|AKIA[0-9A-Z]{12,}|gh[pousr]_[A-Za-z0-9]{20,}|AIza[A-Za-z0-9_-]{20,}|xox[bp]-[A-Za-z0-9-]{10,})\\b/g;\n\n/**\n * Mask secret-shaped substrings in an error message.\n *\n * Strictly `string => string`: pass a known message here. For an arbitrary\n * throwable of unknown shape (e.g. a caught `unknown`), call\n * {@link redactErrorForPersistence} instead — it coerces non-`Error` values to\n * a string first. The runtime non-string guard below is defensive depth only;\n * the type contract is that callers supply a string.\n *\n * @param message - Raw error message (e.g. `error.message`).\n * @returns The message with credential-like substrings replaced by\n * `***REDACTED***`. Empty input is returned unchanged.\n *\n * @example\n * ```ts\n * redactErrorMessage('connect failed: postgres://u:p@db/app')\n * // => 'connect failed: postgres://***REDACTED***@db/app'\n * redactErrorMessage('401 from api: apiKey=<the-key>')\n * // => '401 from api: apiKey=***REDACTED***'\n * ```\n */\nexport function redactErrorMessage(message: string): string {\n if (typeof message !== 'string' || message.length === 0) {\n return message;\n }\n\n return (\n message\n .replace(CREDENTIAL_URL_RE, `$1${REDACTED}@`)\n // Authorization headers run before the generic key=value rule so the\n // full `<scheme> <token>` value is masked rather than just the scheme.\n .replace(AUTHORIZATION_HEADER_RE, `authorization=${REDACTED}`)\n .replace(BEARER_TOKEN_RE, `$1 ${REDACTED}`)\n // JSON-shaped secrets run before the generic key=value rule (which cannot\n // match a quoted key) so `{\"password\":\"x\"}` is masked to a valid shape.\n .replace(JSON_SECRET_KEY_VALUE_RE, `$1:\"${REDACTED}\"`)\n .replace(SECRET_KEY_VALUE_RE, `$1$2${REDACTED}`)\n .replace(STANDALONE_SECRET_RE, REDACTED)\n );\n}\n\n/**\n * Redact an arbitrary error's message, tolerating non-Error throwables.\n *\n * @param error - Anything thrown (`Error`, string, or unknown).\n * @returns A redacted message string suitable for persistence.\n */\nexport function redactErrorForPersistence(error: unknown): string {\n if (error instanceof Error) {\n return redactErrorMessage(error.message);\n }\n return redactErrorMessage(String(error));\n}\n","// Self-register this package's manifest for consumers that import via this\n// subpath without the main entry. See src/__smrt-register__.ts (issue #1132).\nimport './__smrt-register__.js';\n\nimport {\n field,\n SmrtCollection,\n SmrtObject,\n smrt,\n} from '@happyvertical/smrt-core';\n\n/**\n * Liveness record for a single TaskRunner / ScheduleRunner incarnation,\n * stored in the `_smrt_workers` system table.\n *\n * @remarks\n * Job recovery asks \"is this job's owning worker alive?\" rather than \"is this\n * job's heartbeat fresh?\" (issue #1474). Each running worker keeps a row here\n * and renews `leaseExpiresAt` on a fixed cadence; a worker that dies stops\n * renewing and its lease expires, so its `running` jobs are recovered.\n *\n * `workerId` is unique per *incarnation* (a restarted runner gets a new key —\n * see `createWorkerKey`), which is what lets recovery distinguish a crashed\n * worker's orphaned jobs from an identically-configured restart.\n *\n * `leaseExpiresAt` is a `datetime` so it maps to a real timestamp column on\n * every engine (an integer epoch-ms column overflows `int4`/`INT32` on\n * Postgres and DuckDB). Stage 1 writes/compares it against the host clock —\n * the same approach the previous heartbeat recovery used; Stage 2 will move to\n * database-side time once an off-loop writer exists.\n */\n@smrt({\n tableName: '_smrt_workers',\n conflictColumns: ['worker_id'],\n api: false,\n cli: false,\n mcp: false,\n})\nexport class SmrtWorker extends SmrtObject { static __smrtPackage__ = \"@happyvertical/smrt-jobs\";\n /** Per-incarnation-unique worker key (also stored on owned jobs' workerId). */\n @field({ type: 'text', required: true, requiredFor: 'identity' })\n workerId: string = '';\n\n /** OS process id of the owning runner (diagnostic). */\n @field({ type: 'integer', nullable: true })\n pid: number | null = null;\n\n /** Hostname of the owning runner (diagnostic). */\n @field({ type: 'text', nullable: true })\n hostname: string | null = null;\n\n /** When this incarnation started. */\n @field({ type: 'datetime', nullable: true })\n startedAt: Date | null = null;\n\n /** Last lease renewal time (diagnostic; liveness uses leaseExpiresAt). */\n @field({ type: 'datetime', nullable: true })\n heartbeatAt: Date | null = null;\n\n /** Lease expiry — the worker is alive while this is in the future. */\n @field({ type: 'datetime', nullable: true })\n leaseExpiresAt: Date | null = null;\n\n /**\n * Queues this runner polls (its `TaskRunnerConfig.queues`), written at\n * registration and refreshed on every lease renewal. `null` for rows that\n * predate the column or belong to a runner that polls no queue.\n */\n @field({ type: 'json', nullable: true })\n queues: string[] | null = null;\n\n /** Lifecycle status (`running` while the runner is processing). */\n @field({ type: 'text', required: true, default: 'running' })\n status: string = 'running';\n}\n\nexport interface RegisterWorkerInput {\n workerKey: string;\n pid?: number | null;\n hostname?: string | null;\n leaseTtlMs: number;\n /** Queues the runner polls; stored so hosts can tell who reads a queue. */\n queues?: string[] | null;\n}\n\n/** Normalise a stored `queues` value (JSON text on SQLite, array on Postgres). */\nfunction parseQueues(value: unknown): string[] | null {\n let parsed = value;\n if (typeof value === 'string') {\n try {\n parsed = JSON.parse(value);\n } catch {\n return null;\n }\n }\n if (!Array.isArray(parsed)) return null;\n return parsed.filter((q): q is string => typeof q === 'string');\n}\n\n/**\n * Collection for managing `_smrt_workers` liveness rows.\n */\nexport class SmrtWorkerCollection extends SmrtCollection<SmrtWorker> {\n static readonly _itemClass = SmrtWorker;\n\n /**\n * Fail fast if the `_smrt_workers` table has not been migrated.\n *\n * The framework never creates application/system tables at runtime; the\n * table is created by `smrt db:migrate` (or `getTestDatabase`). A consumer\n * that upgrades smrt-jobs without migrating must get a clear, actionable\n * error at `start()` rather than a confusing recovery failure later.\n */\n async assertReady(): Promise<void> {\n try {\n await this.db.query('SELECT 1 FROM _smrt_workers LIMIT 1');\n } catch (error) {\n throw new Error(\n 'The _smrt_workers table is missing. Run `smrt db:migrate` to create ' +\n 'job-system tables before starting a TaskRunner/ScheduleRunner. ' +\n `(underlying error: ${(error as Error).message})`,\n );\n }\n }\n\n /** Whether the `_smrt_workers` table exists (recovery skips lease checks if not). */\n async tableReady(): Promise<boolean> {\n try {\n await this.db.query('SELECT 1 FROM _smrt_workers LIMIT 1');\n return true;\n } catch {\n return false;\n }\n }\n\n /** Register a worker incarnation with its lease seeded to `now + ttl`. */\n async registerWorker(input: RegisterWorkerInput): Promise<void> {\n const now = new Date();\n await this.create({\n workerId: input.workerKey,\n pid: input.pid ?? null,\n hostname: input.hostname ?? null,\n startedAt: now,\n heartbeatAt: now,\n // Seed the lease in the same write so the worker is immediately \"alive\",\n // closing the window between registration and the first claimReady().\n leaseExpiresAt: new Date(now.getTime() + input.leaseTtlMs),\n queues: input.queues ? [...input.queues] : null,\n status: 'running',\n });\n }\n\n /** Renew a worker's lease to `now + ttl`. */\n async renewLease(\n workerKey: string,\n leaseTtlMs: number,\n queues?: string[] | null,\n ): Promise<void> {\n const now = new Date();\n const expiresAt = new Date(now.getTime() + leaseTtlMs).toISOString();\n if (queues) {\n await this.db.query(\n `UPDATE _smrt_workers\n SET lease_expires_at = ?,\n heartbeat_at = ?,\n queues = ?\n WHERE worker_id = ?`,\n expiresAt,\n now.toISOString(),\n JSON.stringify(queues),\n workerKey,\n );\n return;\n }\n await this.db.query(\n `UPDATE _smrt_workers\n SET lease_expires_at = ?,\n heartbeat_at = ?\n WHERE worker_id = ?`,\n expiresAt,\n now.toISOString(),\n workerKey,\n );\n }\n\n /** Remove a worker incarnation (graceful shutdown). */\n async expireWorker(workerKey: string): Promise<void> {\n await this.db.query(\n 'DELETE FROM _smrt_workers WHERE worker_id = ?',\n workerKey,\n );\n }\n\n /** Worker keys whose database lease is still fresh (alive cross-process). */\n async freshLeaseWorkerKeys(): Promise<Set<string>> {\n const result = await this.db.query(\n `SELECT worker_id\n FROM _smrt_workers\n WHERE lease_expires_at IS NOT NULL\n AND lease_expires_at >= ?`,\n new Date().toISOString(),\n );\n const keys = new Set<string>();\n for (const row of result.rows as Array<{ worker_id?: unknown }>) {\n if (typeof row.worker_id === 'string') keys.add(row.worker_id);\n }\n return keys;\n }\n\n /**\n * Worker keys holding a fresh lease whose recorded `queues` include `queue`.\n * Rows with no recorded queues (older runners, schedule runners) never match.\n */\n async liveWorkerKeysForQueue(queue: string): Promise<Set<string>> {\n const result = await this.db.query(\n `SELECT worker_id, queues\n FROM _smrt_workers\n WHERE lease_expires_at IS NOT NULL\n AND lease_expires_at >= ?`,\n new Date().toISOString(),\n );\n const keys = new Set<string>();\n for (const row of result.rows as Array<{\n worker_id?: unknown;\n queues?: unknown;\n }>) {\n if (typeof row.worker_id !== 'string') continue;\n if (parseQueues(row.queues)?.includes(queue)) keys.add(row.worker_id);\n }\n return keys;\n }\n\n /** Delete worker rows whose lease expired more than `graceMs` ago. */\n async pruneExpired(graceMs: number): Promise<void> {\n const cutoff = new Date(Date.now() - Math.max(0, graceMs)).toISOString();\n await this.db.query(\n `DELETE FROM _smrt_workers\n WHERE lease_expires_at IS NOT NULL\n AND lease_expires_at < ?`,\n cutoff,\n );\n }\n}\n\nexport default SmrtWorker;\n","import type { Logger } from '@happyvertical/logger';\nimport type { McpTaskContinuation } from './mcp-task.js';\n\n/**\n * Job context for logging\n */\nexport interface JobContext {\n jobId: string;\n attempt: number;\n queue: string;\n objectType: string;\n method: string;\n}\n\nexport interface JobEventInput {\n type?: string;\n level?: 'debug' | 'info' | 'warn' | 'error';\n stage?: string | null;\n progress?: number | null;\n message?: string;\n data?: Record<string, unknown>;\n}\n\nexport interface JobProgressInput {\n stage: string;\n progress: number;\n message?: string;\n detail?: string;\n source?: string;\n data?: Record<string, unknown>;\n}\n\nexport interface JobExecutionContext {\n /**\n * `handler` is set only for a job that targets a registered named handler\n * (#5005); it is absent for a model-method job.\n */\n job: JobContext & { tenantId?: string | null; handler?: string };\n logger: Logger;\n /**\n * Cooperative cancellation signal. Aborts when the job row is observed as\n * `cancelled` (reason: `JobCancelledError`) or when the job times out under\n * `timeoutBehavior` `'fail'`/`'kill'` (reason: `JobTimeoutError`). A plain\n * `AbortSignal`: pass it to `fetch` or an LLM SDK. Handlers that ignore it\n * behave exactly as before; aborting never changes job lifecycle state.\n */\n signal: AbortSignal;\n event(input: JobEventInput): Promise<void>;\n progress(input: JobProgressInput): Promise<void>;\n log(\n level: 'debug' | 'info' | 'warn' | 'error',\n message: string,\n data?: Record<string, unknown>,\n ): Promise<void>;\n /**\n * Present only for a job created by the MCP Tasks extension. Calling this\n * persists an input request and resolves after `tasks/update` supplies every\n * requested key (or rejects cooperatively if the task is cancelled).\n */\n task?: {\n /** Recheck live authority and job ownership immediately before apply. */\n assertAuthorized(): Promise<void>;\n /** Durable single input round; suspends this execution until a new claim. */\n requestContinuation(\n binding: McpTaskContinuation,\n inputRequest: unknown,\n ): Promise<unknown>;\n requestInput(\n inputRequests: Record<string, unknown>,\n ): Promise<Record<string, unknown>>;\n };\n}\n\n/**\n * Logger extension that auto-injects job context into all log entries\n *\n * During job execution, all logs automatically include:\n * - jobId: The job's unique identifier\n * - attempt: Which attempt this is (1, 2, 3...)\n * - queue: Which queue the job is in\n * - objectType: The type of object being operated on\n * - method: The method being invoked\n */\nexport class JobContextLogger implements Logger {\n constructor(\n private readonly baseLogger: Logger,\n private readonly jobContext: JobContext,\n ) {}\n\n private addContext(data?: Record<string, unknown>): Record<string, unknown> {\n return {\n ...data,\n _job: {\n id: this.jobContext.jobId,\n attempt: this.jobContext.attempt,\n queue: this.jobContext.queue,\n objectType: this.jobContext.objectType,\n method: this.jobContext.method,\n },\n };\n }\n\n debug(message: string, data?: Record<string, unknown>): void {\n this.baseLogger.debug(message, this.addContext(data));\n }\n\n info(message: string, data?: Record<string, unknown>): void {\n this.baseLogger.info(message, this.addContext(data));\n }\n\n warn(message: string, data?: Record<string, unknown>): void {\n this.baseLogger.warn(message, this.addContext(data));\n }\n\n error(message: string, data?: Record<string, unknown>): void {\n this.baseLogger.error(message, this.addContext(data));\n }\n}\n\nexport default JobContextLogger;\n","import type { DatabaseInterface } from '@happyvertical/sql';\nimport { createId } from '@happyvertical/utils';\nimport { type SmrtJob, SmrtJobCollection } from './smrt-job.js';\nimport { terminalSnapshot, transitionTerminalJob } from './terminal-outcome.js';\n\n/** The MCP Tasks extension identifier implemented by this durable adapter. */\nexport const MCP_TASKS_EXTENSION = 'io.modelcontextprotocol/tasks';\n\n/** MCP task states defined by the Tasks extension. */\nexport type McpTaskStatus =\n | 'working'\n | 'input_required'\n | 'completed'\n | 'cancelled'\n | 'failed';\n\n/** Durable shape returned by `tasks/get` after the transport adds `resultType`. */\nexport interface McpTask {\n taskId: string;\n status: McpTaskStatus;\n createdAt: string;\n lastUpdatedAt: string;\n ttlMs: number;\n pollIntervalMs?: number;\n statusMessage?: string;\n result?: Record<string, unknown>;\n error?: { code: number; message: string };\n}\n\n/** Immutable reference to an owning workflow record, never an approval. */\nexport interface McpTaskContinuation {\n recordId: string;\n revision: string;\n inputKey: string;\n}\n\n/** Live runner authority: implementations resolve current grants, never snapshots. */\nexport interface McpTaskAuthority {\n continuation?: Readonly<McpTaskContinuation>;\n ownerId: string;\n tenantId: string | null;\n taskId: string;\n objectType: string;\n objectId: string;\n method: string;\n}\n\n/** Internal control flow after input is durably persisted and the worker released. */\nexport class McpTaskSuspendedError extends Error {}\n\n/** Arguments passed through an MCP tool action into its backing job. */\nexport interface CreateMcpTaskInput {\n objectType: string;\n objectId: string;\n method: string;\n /** Exact positional custom-action invocation produced by the MCP generator. */\n invocationArgs: unknown[];\n tenantId?: string | null;\n continuation?: McpTaskContinuation;\n /** Optional agent constructor configuration retained by normal background jobs. */\n agentConfig?: Record<string, unknown>;\n timeout?: number;\n pollIntervalMs?: number;\n ttlMs?: number;\n}\n\n/** Internal persisted marker distinguishing task invocations from normal jobs. */\nexport interface McpTaskJobMarker {\n /** Set by the trusted app task store, never by tool arguments. */\n authorizationRequired?: boolean;\n continuation?: McpTaskContinuation;\n invocationArgs: unknown[];\n pollIntervalMs: number;\n ttlMs: number;\n}\n\n/** Serialize a completed task exactly as an MCP CallToolResult. */\nexport function createMcpTaskResult(result: unknown): Record<string, unknown> {\n // JSON.stringify(undefined) returns undefined rather than valid JSON. The\n // generated MCP result boundary represents non-JSON/void action results as\n // null, so preserve that contract in the durable task payload too.\n const publicResult = toPublicTaskData(result) ?? null;\n return {\n content: [{ type: 'text', text: JSON.stringify(publicResult) }],\n structuredContent: { data: publicResult },\n };\n}\n\n/** Thrown when a task doesn't belong to the current task-store principal. */\nexport class McpTaskNotFoundError extends Error {\n constructor(taskId: string) {\n super(`MCP task not found: ${taskId}`);\n this.name = 'McpTaskNotFoundError';\n }\n}\n\n/** Cooperative cancellation observed by an operation awaiting task input. */\nexport class McpTaskCancelledError extends Error {\n constructor(taskId: string) {\n super(`MCP task was cancelled: ${taskId}`);\n this.name = 'McpTaskCancelledError';\n }\n}\n\n/**\n * Durable adapter between the MCP Tasks extension and `_smrt_jobs`.\n *\n * A task is a projection of exactly one job row: `task_id` is a unique\n * correlation key on the row and cancellation changes that same row. This is\n * intentionally not a second task table, which prevents an orphaned queued\n * job when a caller cancels an MCP task.\n */\nexport class McpTaskStore {\n private readonly ownerId: string | null;\n private readonly requireAuthorization: boolean;\n private readonly tenantId: string | null;\n\n private constructor(\n private readonly collection: SmrtJobCollection,\n options: {\n /** Require live worker authorization for every task from this store. */\n requireAuthorization?: boolean;\n ownerId?: string | null;\n tenantId?: string | null;\n pollIntervalMs?: number;\n ttlMs?: number;\n },\n ) {\n this.ownerId = options.ownerId ?? null;\n this.requireAuthorization = options.requireAuthorization ?? false;\n this.tenantId = options.tenantId ?? null;\n this.pollIntervalMs = options.pollIntervalMs ?? 250;\n this.ttlMs = options.ttlMs ?? 86_400_000;\n }\n\n readonly pollIntervalMs: number;\n readonly ttlMs: number;\n\n static async create(\n db: DatabaseInterface,\n options: {\n /** Require live worker authorization for every task from this store. */\n requireAuthorization?: boolean;\n ownerId?: string | null;\n tenantId?: string | null;\n pollIntervalMs?: number;\n ttlMs?: number;\n } = {},\n ): Promise<McpTaskStore> {\n const collection = await SmrtJobCollection.create({ db });\n return new McpTaskStore(collection, options);\n }\n\n /** Create one pending job and return its immediately-pollable task projection. */\n async createTask(input: CreateMcpTaskInput): Promise<McpTask> {\n if ((input.tenantId ?? null) !== this.tenantId) {\n throw new Error('MCP task tenant does not match active tenant');\n }\n if (this.requireAuthorization && !this.ownerId)\n throw new Error('Authorized tasks require an owner');\n const continuation = input.continuation\n ? Object.freeze(validateContinuation(input.continuation))\n : undefined;\n if (continuation) {\n if (!this.ownerId)\n throw new Error('Durable continuation requires an owner');\n }\n const taskId = createId();\n const pollIntervalMs = input.pollIntervalMs ?? this.pollIntervalMs;\n const ttlMs = input.ttlMs ?? this.ttlMs;\n const marker: McpTaskJobMarker = {\n invocationArgs: input.invocationArgs,\n ...(this.requireAuthorization ? { authorizationRequired: true } : {}),\n ...(continuation ? { continuation } : {}),\n pollIntervalMs,\n ttlMs,\n };\n const args: Record<string, unknown> = {\n _mcpTask: marker,\n ...(input.agentConfig ? { _agentConfig: input.agentConfig } : {}),\n };\n\n const job = await this.collection.enqueueJob({\n tenantId: input.tenantId ?? null,\n queue: 'mcp-tasks',\n objectType: input.objectType,\n objectId: input.objectId,\n method: input.method,\n args,\n timeout: input.timeout,\n ...(continuation || this.requireAuthorization ? { maxAttempts: 1 } : {}),\n taskId,\n taskOwnerId: this.ownerId,\n taskInputRequests: null,\n taskInputResponses: null,\n });\n\n return taskFromJob(job, { pollIntervalMs, ttlMs });\n }\n\n /**\n * Read a waiting task's application input descriptor for an explicitly declared\n * workflow tool or authenticated form. This is not an MCP protocol extension.\n */\n async getContinuation(taskId: string): Promise<{\n binding: McpTaskContinuation;\n inputRequests: Record<string, unknown>;\n } | null> {\n const job = await this.findTaskJob(taskId);\n const binding = getMcpTaskMarker(job)?.continuation;\n if (!binding || job.status !== 'pending' || job.taskInputResponses !== null)\n return null;\n const inputRequests = asRecord(job.taskInputRequests);\n if (!Object.keys(inputRequests).length) return null;\n return { binding, inputRequests };\n }\n\n /** Get a task only when it belongs to this store's principal. */\n async getTask(taskId: string): Promise<McpTask> {\n const job = await this.findTaskJob(taskId);\n const marker = getMcpTaskMarker(job);\n return taskFromJob(\n job,\n marker ?? {\n pollIntervalMs: this.pollIntervalMs,\n ttlMs: this.ttlMs,\n },\n );\n }\n\n /**\n * Persist only values requested by an outstanding `requestInput()` call.\n * Unknown and already-consumed keys are intentionally ignored per SEP-2663.\n */\n async updateTask(\n taskId: string,\n inputResponses: Record<string, unknown>,\n ): Promise<void> {\n const job = await this.findTaskJob(taskId);\n const requested = asRecord(job.taskInputRequests);\n if (getMcpTaskMarker(job)?.continuation) {\n if (\n !Object.keys(requested).length ||\n !Object.keys(requested).every((key) =>\n Object.hasOwn(inputResponses, key),\n )\n )\n return;\n const selected = Object.fromEntries(\n Object.keys(requested).map((key) => [key, inputResponses[key]]),\n );\n await this.collection.query(\n `UPDATE _smrt_jobs SET task_input_responses = ?, updated_at = ?\n WHERE id = ? AND task_id = ? AND status = 'pending'\n AND task_input_responses IS NULL`,\n [\n encodeContinuationJson(selected),\n new Date().toISOString(),\n job.id,\n taskId,\n ],\n { allowRawOnTenantScoped: true },\n );\n return;\n }\n if (Object.keys(requested).length === 0) return;\n\n const current = asRecord(job.taskInputResponses);\n const accepted: Record<string, unknown> = { ...current };\n for (const key of Object.keys(requested)) {\n if (Object.hasOwn(inputResponses, key)) {\n accepted[key] = inputResponses[key];\n }\n }\n\n await this.collection.query(\n `UPDATE _smrt_jobs\n SET task_input_responses = ?, updated_at = ?\n WHERE id = ? AND task_id = ?`,\n [JSON.stringify(accepted), new Date().toISOString(), job.id, taskId],\n { allowRawOnTenantScoped: true },\n );\n }\n\n /**\n * Cooperatively cancel the backing job. A completion race cannot resurrect\n * it because TaskRunner terminal writes require `status = 'running'`.\n */\n async cancelTask(taskId: string): Promise<void> {\n const job = await this.findTaskJob(taskId);\n if (\n job.status === 'completed' ||\n job.status === 'failed' ||\n job.status === 'cancelled'\n ) {\n return;\n }\n\n const snapshot = terminalSnapshot(job);\n if (!snapshot) throw new McpTaskNotFoundError(taskId);\n await transitionTerminalJob(this.collection.db, {\n job: snapshot,\n status: 'cancelled',\n completedAt: new Date(),\n expectedStatuses: ['pending', 'running'],\n expectedTaskId: taskId,\n });\n }\n\n private async findTaskJob(taskId: string): Promise<SmrtJob> {\n const ownerPredicate =\n this.ownerId === null ? 'task_owner_id IS NULL' : 'task_owner_id = ?';\n const params: unknown[] =\n this.ownerId === null ? [taskId] : [taskId, this.ownerId];\n const tenantPredicate =\n this.tenantId === null ? 'tenant_id IS NULL' : 'tenant_id = ?';\n if (this.tenantId !== null) params.push(this.tenantId);\n const jobs = await this.collection.query(\n `SELECT * FROM _smrt_jobs WHERE task_id = ? AND ${ownerPredicate} AND ${tenantPredicate} LIMIT 1`,\n params,\n { allowRawOnTenantScoped: true },\n );\n const job = jobs[0];\n if (!job) throw new McpTaskNotFoundError(taskId);\n return job;\n }\n}\n\n/** Retrieve an internal task marker without exposing it to ordinary job callers. */\nexport function getMcpTaskMarker(\n job: Pick<SmrtJob, 'args'>,\n): McpTaskJobMarker | null {\n const marker = asRecord(asRecord(job.args)._mcpTask);\n if (!Array.isArray(marker.invocationArgs)) return null;\n return {\n invocationArgs: marker.invocationArgs,\n ...(marker.authorizationRequired === true\n ? { authorizationRequired: true }\n : {}),\n ...(marker.continuation\n ? { continuation: validateContinuation(marker.continuation) }\n : {}),\n pollIntervalMs: asPositiveInt(marker.pollIntervalMs, 250),\n ttlMs: asPositiveInt(marker.ttlMs, 86_400_000),\n };\n}\n\n/**\n * Persist one immutable input round and release the worker. On replay the handler\n * starts again; work before this seam must be read-only or use owning runOnce /\n * action idempotency. An answer is input only, never domain approval.\n */\nexport async function requestMcpTaskContinuation(\n db: DatabaseInterface,\n job: Pick<SmrtJob, 'id' | 'taskId' | 'workerId' | 'args'>,\n binding: McpTaskContinuation,\n inputRequest: unknown,\n): Promise<unknown> {\n validateContinuation(binding);\n const expected = getMcpTaskMarker(job)?.continuation;\n if (\n !expected ||\n expected.recordId !== binding.recordId ||\n expected.revision !== binding.revision ||\n expected.inputKey !== binding.inputKey\n ) {\n throw new Error('MCP continuation binding mismatch');\n }\n const found = await db.query(\n `SELECT task_input_responses FROM _smrt_jobs\n WHERE id = ? AND task_id = ? AND worker_id = ? AND status = 'running'`,\n job.id,\n job.taskId,\n job.workerId,\n );\n if (found.rows.length !== 1)\n throw new McpTaskCancelledError(job.taskId ?? '');\n const answers = asRecord(parseJson(found.rows[0].task_input_responses));\n if (Object.hasOwn(answers, binding.inputKey))\n return answers[binding.inputKey];\n const suspended = await db.query(\n `UPDATE _smrt_jobs SET status = 'pending', worker_id = NULL,\n worker_heartbeat = NULL, task_input_requests = ?, updated_at = ?\n WHERE id = ? AND task_id = ? AND worker_id = ? AND status = 'running'\n RETURNING id`,\n encodeContinuationJson({ [binding.inputKey]: inputRequest }),\n new Date().toISOString(),\n job.id,\n job.taskId,\n job.workerId,\n );\n if (suspended.rows.length !== 1)\n throw new McpTaskCancelledError(job.taskId ?? '');\n throw new McpTaskSuspendedError('MCP task awaits durable input');\n}\n\nfunction encodeContinuationJson(value: unknown): string {\n try {\n const json = JSON.stringify(value, (_key, item) => {\n if (\n item === undefined ||\n typeof item === 'function' ||\n typeof item === 'symbol' ||\n typeof item === 'bigint' ||\n (typeof item === 'number' && !Number.isFinite(item))\n ) {\n throw new Error('Invalid JSON');\n }\n return item;\n });\n if (!json || new TextEncoder().encode(json).byteLength > 65_536)\n throw new Error('Oversized JSON');\n return json;\n } catch {\n throw new Error('MCP continuation input must be JSON within 65536 bytes');\n }\n}\n\nfunction validateContinuation(value: unknown): McpTaskContinuation {\n const source = asRecord(value);\n const record: Record<string, unknown> = {\n recordId: source.recordId,\n revision: source.revision,\n inputKey: source.inputKey,\n };\n for (const key of ['recordId', 'revision', 'inputKey']) {\n if (\n typeof record[key] !== 'string' ||\n !record[key] ||\n record[key].length > 256\n ) {\n throw new Error('Invalid MCP continuation binding');\n }\n }\n return {\n recordId: record.recordId as string,\n revision: record.revision as string,\n inputKey: record.inputKey as string,\n };\n}\n\n/**\n * Make a task operation wait for user input. It is intentionally a method on\n * JobExecutionContext rather than an MCP transport concern, so generated\n * stdio and stateless HTTP share one durable input seam.\n */\nexport async function requestMcpTaskInput(\n db: DatabaseInterface,\n job: Pick<SmrtJob, 'id' | 'taskId' | 'workerId'>,\n inputRequests: Record<string, unknown>,\n): Promise<Record<string, unknown>> {\n const jobId = job.id;\n const taskId = job.taskId;\n if (!jobId || !taskId || !job.workerId) {\n throw new Error(\n 'Task input is only available while an MCP task job is running',\n );\n }\n if (Object.keys(inputRequests).length === 0) return {};\n\n const now = new Date().toISOString();\n await db.query(\n `UPDATE _smrt_jobs\n SET task_input_requests = ?, task_input_responses = NULL, updated_at = ?\n WHERE id = ? AND task_id = ? AND worker_id = ? AND status = 'running'`,\n JSON.stringify(inputRequests),\n now,\n jobId,\n taskId,\n job.workerId,\n );\n\n while (true) {\n const result = await db.query(\n `SELECT status, task_input_responses FROM _smrt_jobs WHERE id = ? AND task_id = ?`,\n jobId,\n taskId,\n );\n const row = result.rows[0] as\n | { status?: string; task_input_responses?: unknown }\n | undefined;\n if (!row || row.status === 'cancelled')\n throw new McpTaskCancelledError(taskId);\n if (row.status !== 'running')\n throw new Error(`MCP task is no longer running: ${taskId}`);\n\n const responses = asRecord(parseJson(row.task_input_responses));\n if (\n Object.keys(inputRequests).every((key) => Object.hasOwn(responses, key))\n ) {\n const selected = Object.fromEntries(\n Object.keys(inputRequests).map((key) => [key, responses[key]]),\n );\n await db.query(\n `UPDATE _smrt_jobs\n SET task_input_requests = NULL, updated_at = ?\n WHERE id = ? AND task_id = ? AND worker_id = ? AND status = 'running'`,\n new Date().toISOString(),\n jobId,\n taskId,\n job.workerId,\n );\n return selected;\n }\n await new Promise((resolve) => setTimeout(resolve, 50));\n }\n}\n\n/** Convert the job state into the flat task shape required by `tasks/get`. */\nexport function taskFromJob(\n job: SmrtJob,\n marker: Pick<McpTaskJobMarker, 'pollIntervalMs' | 'ttlMs'>,\n): McpTask {\n const status = taskStatusFromJob(job);\n const createdAt = toIso(job.created_at) ?? new Date().toISOString();\n const lastUpdatedAt = toIso(job.updated_at) ?? createdAt;\n const task: McpTask = {\n taskId: job.taskId ?? '',\n status,\n createdAt,\n lastUpdatedAt,\n ttlMs: marker.ttlMs,\n pollIntervalMs: marker.pollIntervalMs,\n };\n if (status === 'input_required')\n task.statusMessage = 'Waiting for required input';\n if (status === 'cancelled') task.statusMessage = 'Task cancelled';\n if (status === 'failed') {\n task.statusMessage = job.lastError ?? 'Task failed';\n task.error = { code: -32603, message: task.statusMessage };\n }\n if (status === 'completed' && job.taskResult) task.result = job.taskResult;\n return task;\n}\n\nfunction taskStatusFromJob(job: SmrtJob): McpTaskStatus {\n if (job.status === 'completed') return 'completed';\n if (job.status === 'cancelled') return 'cancelled';\n if (job.status === 'failed') return 'failed';\n if (\n Object.keys(asRecord(job.taskInputRequests)).length > 0 &&\n !(getMcpTaskMarker(job)?.continuation && job.taskInputResponses !== null)\n )\n return 'input_required';\n return 'working';\n}\n\nfunction asRecord(value: unknown): Record<string, unknown> {\n if (value === null || typeof value !== 'object' || Array.isArray(value))\n return {};\n return value as Record<string, unknown>;\n}\n\nfunction parseJson(value: unknown): unknown {\n if (typeof value !== 'string') return value;\n try {\n return JSON.parse(value);\n } catch {\n return {};\n }\n}\n\nfunction asPositiveInt(value: unknown, fallback: number): number {\n return typeof value === 'number' && Number.isInteger(value) && value > 0\n ? value\n : fallback;\n}\n\nfunction toIso(value: Date | string | null | undefined): string | undefined {\n if (value instanceof Date) return value.toISOString();\n if (typeof value === 'string') return value;\n return undefined;\n}\n\n/** Match generated MCP's sensitive-field-safe public serialization boundary. */\nfunction toPublicTaskData(\n value: unknown,\n seen: WeakSet<object> = new WeakSet(),\n): unknown {\n if (value === null || typeof value !== 'object') return value;\n const publicSource = value as {\n toPublicJSON?: (options?: Record<string, unknown>) => unknown;\n };\n if (typeof publicSource.toPublicJSON === 'function') {\n return publicSource.toPublicJSON({});\n }\n if (Array.isArray(value)) {\n if (seen.has(value)) return '[Circular]';\n seen.add(value);\n return value.map((entry) => toPublicTaskData(entry, seen));\n }\n const prototype = Object.getPrototypeOf(value);\n if (prototype !== Object.prototype && prototype !== null) return value;\n if (seen.has(value)) return '[Circular]';\n seen.add(value);\n const out: Record<string, unknown> = {};\n for (const [key, nested] of Object.entries(value)) {\n out[key] = toPublicTaskData(nested, seen);\n }\n return out;\n}\n","export const DEFAULT_TASK_HEARTBEAT_INTERVAL_MS = 30000;\nconst STALE_HEARTBEAT_GRACE_MULTIPLIER = 3;\n\n/**\n * Default cadence for renewing a worker's liveness lease.\n *\n * Liveness is a per-*worker* lease (see {@link ../smrt-worker.js}), not a\n * per-job heartbeat. The runner renews its lease on this interval; a dead\n * worker stops renewing and its lease expires after {@link DEFAULT_LEASE_TTL_MS}.\n */\nexport const DEFAULT_LEASE_TICK_MS = 10000;\n\n/**\n * Default time-to-live for a worker liveness lease.\n *\n * A `running` job is only recovered when its owning worker is neither live in\n * this process nor holding a fresh lease in the database. The TTL is the\n * cross-process detection latency for a genuinely dead worker.\n */\nexport const DEFAULT_LEASE_TTL_MS = 30000;\n\nconst LEASE_TTL_GRACE_MULTIPLIER = 3;\n\n/**\n * Keep stale-job recovery aligned with the actual heartbeat cadence.\n *\n * @deprecated Recovery no longer keys on per-job heartbeat staleness (#1474);\n * it keys on worker liveness. Retained for one release for any external caller.\n * Use {@link getEffectiveLeaseTtlMs} with the lease tick instead.\n */\nexport function getEffectiveStaleJobThresholdMs(\n staleJobThresholdMs: number,\n heartbeatIntervalMs: number,\n): number {\n return Math.max(\n staleJobThresholdMs,\n heartbeatIntervalMs * STALE_HEARTBEAT_GRACE_MULTIPLIER,\n );\n}\n\n/**\n * Never let a lease expire in fewer than three renewal ticks.\n *\n * A single missed renewal (GC pause, a slow database round-trip) must not be\n * enough to declare a healthy worker dead. Mirrors the floor applied by\n * {@link getEffectiveStaleJobThresholdMs} for the legacy heartbeat path.\n */\nexport function getEffectiveLeaseTtlMs(\n leaseTtlMs: number,\n leaseTickMs: number,\n): number {\n return Math.max(leaseTtlMs, leaseTickMs * LEASE_TTL_GRACE_MULTIPLIER);\n}\n","// Self-register this package's manifest for consumers that import via this\n// subpath without the main entry. See src/__smrt-register__.ts (issue #1132).\nimport './__smrt-register__.js';\n\nimport { AsyncLocalStorage } from 'node:async_hooks';\nimport { EventEmitter } from 'node:events';\nimport { Worker } from 'node:worker_threads';\nimport type { RetryDecision } from '@happyvertical/jobs';\nimport { createLogger } from '@happyvertical/logger';\nimport {\n assertDatabaseMigratedForBuild,\n getClassConfigResolvers,\n normalizeCustomActionFailure,\n ObjectRegistry,\n resolveLazyConfig,\n type SmrtObject,\n} from '@happyvertical/smrt-core';\nimport { TenantContext } from '@happyvertical/smrt-tenancy';\nimport type { DatabaseInterface } from '@happyvertical/sql';\nimport { createId } from '@happyvertical/utils';\nimport { isBackgroundEligibleMethod } from './background-policy.js';\nimport { redactErrorForPersistence } from './error-redaction.js';\nimport type { JobClaim } from './job-claim.js';\nimport {\n JOB_HANDLER_METHOD,\n type JobHandler,\n JobHandlerTargetError,\n JobHandlerUnregisteredError,\n jobHandlerName,\n jobHandlerTarget,\n releaseJobHandlerRegistry,\n sealJobHandlerRegistry,\n} from './job-handlers.js';\nimport {\n JobContextLogger,\n type JobEventInput,\n type JobExecutionContext,\n type JobProgressInput,\n} from './logger-extension.js';\nimport {\n createMcpTaskResult,\n getMcpTaskMarker,\n type McpTaskAuthority,\n McpTaskSuspendedError,\n requestMcpTaskContinuation,\n requestMcpTaskInput,\n} from './mcp-task.js';\nimport {\n type RetentionSweeper,\n type RetentionSweeperOptions,\n startRetentionSweeper,\n} from './retention.js';\nimport {\n HANDLER_TARGET_SQL,\n jobTenantScope,\n SMRT_JOB_PORTABLE_SELECT_COLUMNS,\n type SmrtJob,\n SmrtJobCollection,\n} from './smrt-job.js';\nimport { type SmrtJobEvent, SmrtJobEventCollection } from './smrt-job-event.js';\nimport { SmrtWorkerCollection } from './smrt-worker.js';\nimport {\n DEFAULT_LEASE_TICK_MS,\n DEFAULT_LEASE_TTL_MS,\n DEFAULT_TASK_HEARTBEAT_INTERVAL_MS,\n getEffectiveLeaseTtlMs,\n} from './stale-recovery.js';\nimport {\n ensureTerminalOutcomeStorage,\n terminalSnapshot,\n transitionTerminalJob,\n} from './terminal-outcome.js';\nimport {\n createWorkerKey,\n isWorkerAlive,\n type LivenessConnectionPlan,\n planLivenessConnection,\n registerLiveWorker,\n resolveEngine,\n tuneSqliteForConcurrency,\n unregisterLiveWorker,\n} from './worker-liveness.js';\n\n// Job rows are durable but untrusted transport. This marker is deliberately\n// module-private: a JSON task invocation cannot synthesize the runner-owned\n// execution context that security-sensitive task targets receive.\nconst runnerExecutionContextIdentities = new WeakSet<object>();\nconst runnerJobClaims = new WeakMap<object, Readonly<JobClaim>>();\nconst runnerExecutionContexts = new AsyncLocalStorage<JobExecutionContext>();\n\n/** True only for an execution context constructed by this TaskRunner module. */\nexport function isRunnerExecutionContext(\n value: unknown,\n): value is JobExecutionContext {\n return (\n typeof value === 'object' &&\n value !== null &&\n runnerExecutionContextIdentities.has(value)\n );\n}\n\n/** The runner-owned context for the currently executing task, if any. */\nexport function getActiveJobExecutionContext():\n | JobExecutionContext\n | undefined {\n return runnerExecutionContexts.getStore();\n}\n\n/**\n * Read the immutable dispatch-time claim from an authentic runner context.\n * Reading current job rows cannot recover this identity after ownership changes.\n * @param context - Context supplied to a handler by TaskRunner.\n * @returns The captured claim; use assertJobClaim for current ownership proof.\n */\nexport function getJobClaim(context: unknown): Readonly<JobClaim> {\n const claim = isRunnerExecutionContext(context)\n ? runnerJobClaims.get(context)\n : undefined;\n if (!claim)\n throw new Error(\n 'Job claim requires TaskRunner context with claimFencing: true',\n );\n return claim;\n}\n\n/**\n * TaskRunner configuration\n */\nexport interface TaskRunnerConfig {\n /** Opt into immutable claim proofs and dispatch-fenced runner writes. Default false. */\n claimFencing?: boolean;\n /** Worker ID (auto-generated if not provided) */\n id?: string;\n /** Resolve live authority for durable tasks at each execution/replay. */\n authorizeMcpTask?: (\n authority: Readonly<McpTaskAuthority>,\n ) => Promise<boolean>;\n /** Number of concurrent jobs to process */\n concurrency?: number;\n /** Queues to process (default: ['default']) */\n queues?: string[];\n /** Limit claims and orphan recovery to these tenants; [] selects none. */\n tenantIds?: readonly (string | null)[];\n /** Base polling interval in milliseconds, capped at the effective lease TTL. */\n pollInterval?: number;\n /**\n * Longest delay between empty queue checks in milliseconds.\n *\n * Empty checks back off exponentially from {@link pollInterval} to this\n * value. Leave unset to cap idle checks at twenty times `pollInterval`.\n * Every delay is bounded by the effective worker lease TTL (plus query and\n * event-loop time), including a base interval larger than that TTL.\n */\n idlePollInterval?: number;\n /** Heartbeat interval in milliseconds */\n heartbeatInterval?: number;\n /**\n * How often a running job's row is checked for cancellation, in\n * milliseconds, so `JobExecutionContext.signal` can abort. Default 1000.\n * One read-only query per active job per interval; no writes.\n */\n cancelPollInterval?: number;\n /** Maximum time to wait for jobs to complete on shutdown */\n shutdownTimeout?: number;\n /**\n * @deprecated No longer used. Recovery keys on worker liveness, not per-job\n * heartbeat staleness (#1474). Use {@link leaseTtlMs} / {@link leaseTickMs}.\n */\n staleJobThresholdMs?: number;\n /** Worker liveness lease time-to-live in milliseconds */\n leaseTtlMs?: number;\n /** How often to renew the worker liveness lease, in milliseconds */\n leaseTickMs?: number;\n /**\n * Periodic system-table retention sweep (#2375).\n *\n * A running worker is the framework's only always-on scheduler, so it is\n * also where the retention sweep is scheduled by default. Set to `false` to\n * opt out entirely (for example when a cron job runs `smrt db:prune`\n * instead), or pass options to change the cadence or the policy. The first\n * sweep runs one interval after `start()`, never at start.\n */\n retention?: RetentionSweeperOptions | false;\n /**\n * How long a named handler job (#5005) may stay `pending` past its `run_at`\n * before this runner fails it with failure kind `handler-unclaimed`, in\n * milliseconds. Default 24 h. A runner claims only the handler jobs it\n * registered, so a job no runner serves would otherwise wait forever.\n * Every runner sweeps the handler jobs in its own queues and tenant scope\n * that it did not register itself (those it claims), from its poll, at\n * most once per 1% of this deadline (between one lease tick and 15 min)\n * and {@link HANDLER_UNCLAIMED_SWEEP_LIMIT} rows per sweep, emitting\n * `job:unclaimed`; with different values across a fleet the shortest wins.\n */\n handlerUnclaimedDeadlineMs?: number;\n}\n\n/**\n * TaskRunner events\n */\nexport interface TaskRunnerEvents {\n 'job:started': (job: SmrtJob) => void;\n 'job:event': (job: SmrtJob, event: SmrtJobEvent) => void;\n 'job:progress': (job: SmrtJob, event: SmrtJobEvent) => void;\n 'job:completed': (job: SmrtJob, result: unknown) => void;\n 'job:failed': (job: SmrtJob, error: Error) => void;\n /**\n * A handler job this runner failed `handler-unclaimed` in its sweep: no\n * runner serving the handler claimed it in time (#5005). Not `job:failed`,\n * because this runner never claimed or ran it.\n */\n 'job:unclaimed': (job: SmrtJob, error: Error) => void;\n 'job:retrying': (job: SmrtJob, error: Error, delay: number) => void;\n 'runner:started': () => void;\n 'runner:stopped': () => void;\n 'runner:error': (error: Error) => void;\n}\n\nfunction errorText(error: unknown): string {\n return error instanceof Error ? error.message : String(error);\n}\n\n/**\n * Max time to wait for the liveness thread to report ready before giving up and\n * falling back to main-loop renewal (guards against a hung connect in-thread).\n */\nconst LIVENESS_THREAD_START_TIMEOUT_MS = 10000;\n/**\n * Max time to wait for a liveness thread that has been asked to stop (or has\n * already failed) to exit on its own before terminating it.\n */\nconst LIVENESS_THREAD_EXIT_TIMEOUT_MS = 5000;\n\n/**\n * Wait (bounded) for a liveness thread to exit on its own; terminate it only\n * if it does not. Never terminate first: Node aborts the whole process when a\n * worker is terminated while a crypto job's completion is still pending, and\n * the SDK starts one when the thread imports it (smrt#4865).\n */\nasync function retireLivenessWorker(\n worker: Worker,\n exited: Promise<void>,\n): Promise<void> {\n let timer: ReturnType<typeof setTimeout> | undefined;\n const exitedInTime = await Promise.race([\n exited.then(() => true),\n new Promise<boolean>((resolve) => {\n timer = setTimeout(() => resolve(false), LIVENESS_THREAD_EXIT_TIMEOUT_MS);\n if (typeof timer.unref === 'function') timer.unref();\n }),\n ]);\n clearTimeout(timer);\n if (!exitedInTime) await worker.terminate().catch(() => {});\n}\n\nconst DEFAULT_IDLE_POLL_INTERVAL_MULTIPLIER = 20;\n/** Default {@link TaskRunnerConfig.handlerUnclaimedDeadlineMs}: 24 h. */\nexport const DEFAULT_HANDLER_UNCLAIMED_DEADLINE_MS = 24 * 60 * 60 * 1000;\n/** Most unclaimed handler jobs one sweep fails (#5005). */\nexport const HANDLER_UNCLAIMED_SWEEP_LIMIT = 100;\n/** Longest accepted unclaimed deadline: 10 years. */\nconst MAX_HANDLER_UNCLAIMED_DEADLINE_MS = 10 * 365 * 24 * 60 * 60 * 1000;\n/** Longest wait between unclaimed-handler sweeps: 15 min. */\nconst HANDLER_UNCLAIMED_SWEEP_MAX_INTERVAL_MS = 15 * 60 * 1000;\n/** Ids per surplus-release statement, well under driver bind-parameter caps. */\nconst SURPLUS_RELEASE_CHUNK = 500;\n/** Upper bound on a handler error's `retryAfterMs` hint (#3308). */\nconst MAX_RETRY_AFTER_MS = 24 * 60 * 60 * 1000;\n\n/**\n * Retry hints a handler error may carry (#3308): `retryable: false` for an\n * error a retry cannot fix (bad credentials, unknown model), `retryAfterMs`\n * for a provider-given reset time. Both are read from the error itself.\n */\nfunction errorRetryHints(error: unknown): {\n retryable: boolean;\n retryAfterMs: number | null;\n} {\n if (!error || typeof error !== 'object') {\n return { retryable: true, retryAfterMs: null };\n }\n const hints = error as { retryable?: unknown; retryAfterMs?: unknown };\n const retryAfterMs =\n typeof hints.retryAfterMs === 'number' &&\n Number.isFinite(hints.retryAfterMs) &&\n hints.retryAfterMs > 0\n ? Math.min(hints.retryAfterMs, MAX_RETRY_AFTER_MS)\n : null;\n return { retryable: hints.retryable !== false, retryAfterMs };\n}\n\n/**\n * Raised when a job exceeds its timeout under `timeoutBehavior` `'fail'`/`'kill'`.\n *\n * Distinguished from an ordinary handler error so the failure path can choose\n * NOT to auto-retry: the original handler keeps running after a timeout (JS\n * can't preempt it), so re-queueing the row as `pending` while the original\n * still executes guarantees concurrent duplicate execution (see #2 in the\n * #1401 review). A timed-out job is therefore failed terminally rather than\n * retried, shrinking — though, given the at-least-once contract, not fully\n * eliminating — the overlap window.\n */\nexport class JobTimeoutError extends Error {\n constructor(message: string) {\n super(message);\n this.name = 'JobTimeoutError';\n }\n}\n\n/**\n * Abort reason of `JobExecutionContext.signal` when the job row was cancelled\n * while its handler was running.\n */\nexport class JobCancelledError extends Error {\n constructor(message: string) {\n super(message);\n this.name = 'JobCancelledError';\n }\n}\n\n/**\n * Default configuration\n */\ntype ResolvedTaskRunnerConfig = Required<Omit<TaskRunnerConfig, 'tenantIds'>> &\n Pick<TaskRunnerConfig, 'tenantIds'>;\n\nconst DEFAULT_CONFIG: ResolvedTaskRunnerConfig = {\n id: '',\n claimFencing: false,\n authorizeMcpTask: async () => false,\n concurrency: 5,\n queues: ['default'],\n pollInterval: 1000,\n idlePollInterval: 0,\n heartbeatInterval: DEFAULT_TASK_HEARTBEAT_INTERVAL_MS,\n cancelPollInterval: 1000,\n shutdownTimeout: 30000,\n staleJobThresholdMs: 90000,\n leaseTtlMs: DEFAULT_LEASE_TTL_MS,\n leaseTickMs: DEFAULT_LEASE_TICK_MS,\n retention: {},\n handlerUnclaimedDeadlineMs: DEFAULT_HANDLER_UNCLAIMED_DEADLINE_MS,\n};\n\n/**\n * A rejection from one of a job's own state writes, as opposed to a listener\n * or telemetry call that threw after the write committed.\n */\nclass UnpersistedJobWriteError extends Error {\n constructor(readonly writeError: unknown) {\n super('Job state write could not be persisted');\n }\n}\n\n/**\n * TaskRunner processes SMRT jobs by invoking methods on SmrtObjects\n *\n * Features:\n * - Executes jobs via SmrtObject method invocation\n * - Configurable concurrency and timeout behavior\n * - Automatic retry with configurable strategies\n * - Job context logging for visibility\n * - Embedded mode (in-process) or standalone (CLI)\n */\nexport class TaskRunner extends EventEmitter {\n /** Tenant selection is applied before claims and recovery ownership writes. */\n static readonly capabilities = Object.freeze({\n tenantSelection: true,\n } as const);\n readonly id: string;\n /**\n * Per-incarnation-unique worker key. Stored as the `worker_id` on claimed\n * jobs and in `_smrt_workers`, so a restart of a runner sharing the same\n * configured `id` does not look like it still owns the previous\n * incarnation's orphaned jobs. The human-facing {@link id} stays stable for\n * events/logs.\n */\n private readonly workerKey: string;\n private readonly config: ResolvedTaskRunnerConfig;\n private readonly maxIdlePollIntervalMs: number;\n private readonly effectiveLeaseTtlMs: number;\n private collection: SmrtJobCollection | null = null;\n private eventCollection: SmrtJobEventCollection | null = null;\n private workerCollection: SmrtWorkerCollection | null = null;\n private workersTableVerified = false;\n private lastRecoverySweepAt = 0;\n private lastUnclaimedSweepAt = 0;\n private running = false;\n private activeJobs = new Map<string, SmrtJob>();\n /**\n * Rows this runner still owns as `running` because their terminal or retry\n * write could not be persisted, with the `last_error` to record. The owner\n * is alive, so liveness-based recovery would never touch them; this runner's\n * own sweep settles them (#4735).\n */\n private unsettledJobs = new Map<string, string>();\n /** Orphans whose recovery failure was already logged; one line per job. */\n private recoveryFailuresLogged = new Set<string>();\n /** Per-job cooperative cancellation controllers, alive while the job runs. */\n private jobAborts = new Map<string, AbortController>();\n /** Over-claimed job ids whose release back to `pending` has not landed. */\n private unreleasedSurplus = new Set<string>();\n private pollTimer: NodeJS.Timeout | null = null;\n private pollPromise: Promise<boolean> | null = null;\n private pollGeneration = 0;\n private idlePollDelayMs: number;\n private heartbeatTimer: NodeJS.Timeout | null = null;\n private leaseTimer: NodeJS.Timeout | null = null;\n /** Periodic system-table retention sweep, when not opted out (#2375). */\n private retentionSweeper: RetentionSweeper | null = null;\n private livenessWorker: Worker | null = null;\n /** Resolves when {@link livenessWorker} has exited (set together with it). */\n private livenessWorkerExited: Promise<void> | null = null;\n private shutdownPromise: Promise<void> | null = null;\n /** The in-flight {@link start}, shared by overlapping callers (#4944). */\n private startPromise: Promise<void> | null = null;\n /** The in-flight {@link stop}, shared by overlapping callers (#4944). */\n private stopPromise: Promise<void> | null = null;\n /** Set by a {@link stop} that lands while {@link start} is in flight. */\n private startCancelled = false;\n private db: DatabaseInterface | null = null;\n /**\n * Handlers this runner dispatches to, snapshotted when it starts (#5005).\n * Registration is closed while it runs, so the snapshot is the registry.\n */\n private jobHandlers: ReadonlyMap<string, JobHandler> = new Map();\n /** The snapshot's names: the only handler jobs this runner claims. */\n private handlerNames: readonly string[] = [];\n private logger = createLogger(true);\n\n constructor(config: TaskRunnerConfig = {}) {\n super();\n this.config = {\n ...DEFAULT_CONFIG,\n ...config,\n id: config.id || `runner_${createId().slice(0, 8)}`,\n };\n jobTenantScope(this.config.tenantIds);\n if (this.config.tenantIds !== undefined) {\n this.config.tenantIds = [...this.config.tenantIds];\n // The default retention sweep is system-wide maintenance, not tenant work.\n if (config.retention === undefined) this.config.retention = false;\n }\n this.id = this.config.id;\n this.workerKey = createWorkerKey(this.id);\n const deadline = this.config.handlerUnclaimedDeadlineMs;\n // Bounded so the sweep's cutoff is always a valid date.\n if (\n !Number.isFinite(deadline) ||\n deadline < 1 ||\n deadline > MAX_HANDLER_UNCLAIMED_DEADLINE_MS\n ) {\n throw new RangeError(\n `handlerUnclaimedDeadlineMs must be between 1 and ${MAX_HANDLER_UNCLAIMED_DEADLINE_MS} milliseconds`,\n );\n }\n for (const [name, value] of [\n ['pollInterval', this.config.pollInterval],\n ['idlePollInterval', config.idlePollInterval ?? this.config.pollInterval],\n ] as const) {\n if (!Number.isFinite(value) || value < 1 || value > 2_147_483_647) {\n throw new RangeError(\n `${name} must be between 1 and 2147483647 milliseconds`,\n );\n }\n }\n this.maxIdlePollIntervalMs = Math.min(\n 2_147_483_647,\n Math.max(\n this.config.pollInterval,\n config.idlePollInterval ??\n this.config.pollInterval * DEFAULT_IDLE_POLL_INTERVAL_MULTIPLIER,\n ),\n );\n this.idlePollDelayMs = this.config.pollInterval;\n this.effectiveLeaseTtlMs = getEffectiveLeaseTtlMs(\n this.config.leaseTtlMs,\n this.config.leaseTickMs,\n );\n }\n\n /**\n * Initialize the runner with database connection\n */\n async initialize(db: DatabaseInterface): Promise<void> {\n this.db = db;\n this.collection = await SmrtJobCollection.create({ db });\n this.eventCollection = await SmrtJobEventCollection.create({ db });\n this.workerCollection = await SmrtWorkerCollection.create({ db });\n }\n\n /**\n * Start processing jobs\n */\n async start(): Promise<void> {\n // Checked first: a start() during an in-flight stop() is refused even when\n // that stop is still waiting on an earlier start (#4944).\n if (this.stopPromise) {\n throw new Error('TaskRunner shutdown is still draining');\n }\n if (this.startPromise) return this.startPromise;\n if (this.running) return;\n if (this.shutdownPromise || this.pollPromise || this.activeJobs.size > 0) {\n throw new Error('TaskRunner shutdown is still draining');\n }\n if (!this.collection || !this.workerCollection) {\n throw new Error('TaskRunner not initialized. Call initialize() first.');\n }\n\n this.startCancelled = false;\n const starting = this.startRunning();\n this.startPromise = starting;\n try {\n await starting;\n } finally {\n if (this.startPromise === starting) this.startPromise = null;\n }\n }\n\n /**\n * The body of {@link start}. A {@link stop} that lands while it runs sets\n * {@link startCancelled}; the checks below then skip whatever has not\n * started yet, and that stop tears down what has, once this settles (#4944).\n */\n private async startRunning(): Promise<void> {\n if (!this.collection || !this.workerCollection) return;\n\n // Fail fast if the job-system tables were never migrated, with an\n // actionable error rather than a confusing recovery failure later.\n await assertDatabaseMigratedForBuild(this.collection.db);\n await this.workerCollection.assertReady();\n\n await this.prepareTerminalOutcomeStorage();\n\n // On SQLite, the runner's writes will race the off-loop ticker's writes to\n // the same file; enable WAL + a busy timeout up front so neither loses a\n // lock race under load (#1474 flake). Best-effort, file-level.\n if (this.db && resolveEngine(this.db) === 'sqlite') {\n await tuneSqliteForConcurrency(this.db);\n }\n\n // Stopped before anything was registered: there is nothing to tear down.\n if (this.startCancelled) return;\n\n // Register this worker incarnation with a seeded lease BEFORE polling, so\n // the first claimReady() cannot leave just-claimed jobs looking orphaned to\n // a concurrent recoverer.\n await this.workerCollection.registerWorker({\n workerKey: this.workerKey,\n pid: typeof process !== 'undefined' ? process.pid : null,\n hostname:\n typeof process !== 'undefined' ? (process.env.HOSTNAME ?? null) : null,\n leaseTtlMs: this.effectiveLeaseTtlMs,\n queues: this.config.queues,\n });\n registerLiveWorker(this.workerKey);\n\n // Close handler registration before the first claim and dispatch from a\n // snapshot: a handler registered after start() would race the claims it\n // should serve (#5005). Reopened when this runner has stopped.\n this.jobHandlers = sealJobHandlerRegistry(this.workerKey);\n this.handlerNames = [...this.jobHandlers.keys()];\n this.running = true;\n\n // Renew the worker lease. Prefer an off-loop worker thread so a CPU-bound\n // synchronous handler can never starve renewal (#1474); fall back to\n // main-loop renewal for engines a second connection can't reach\n // (in-memory SQLite, DuckDB), for SQLite when no second connection on the\n // runtime's own engine is available (#4978), or if the thread fails to\n // start.\n const plan = planLivenessConnection(this.db as DatabaseInterface);\n if (plan.kind === 'none') {\n // Warn only where a thread used to run and now cannot; engines that never\n // had a usable second connection keep renewing on the main loop quietly.\n const log = plan.degraded ? this.logger.warn : this.logger.debug;\n log.call(\n this.logger,\n `Liveness thread not used: ${plan.reason}. Renewing the worker lease on the main loop; a long synchronous handler can delay renewal, so keep leaseTtlMs well above the longest synchronous section.`,\n );\n this.startLeaseRenewal();\n } else {\n const started = await this.startLivenessThread(plan);\n if (!started.ok) {\n this.logger.warn(\n `Liveness thread did not start (${started.reason}); renewing the worker lease on the main loop.`,\n );\n this.startLeaseRenewal();\n }\n }\n\n // Stopped during the liveness handshake: start nothing more. The waiting\n // stop() releases the lease, the live set, the handler registry and the\n // thread stored above, so none of them outlives it.\n if (this.startCancelled) return;\n\n // Start polling loop\n this.resetIdlePollDelay();\n this.startPolling();\n\n // Start heartbeat loop (per-job telemetry only; no longer gates recovery)\n this.startHeartbeat();\n\n // Bound system-table growth while a worker is up (#2375). Opt out with\n // `retention: false`; the first sweep is one interval away, so a runner\n // that starts and stops (a test, a one-shot worker) deletes nothing.\n if (this.config.retention !== false && this.db) {\n this.retentionSweeper = startRetentionSweeper(this.db, {\n ...this.config.retention,\n });\n }\n\n this.emit('runner:started');\n }\n\n /**\n * Stop processing jobs (graceful shutdown)\n */\n async stop(): Promise<void> {\n if (this.stopPromise) return this.stopPromise;\n const pendingStart = this.startPromise;\n if (!this.running && !pendingStart) return;\n\n // A stop that overlaps start() (a SIGTERM during startup) cancels what\n // start() has not begun yet, waits for it to settle, then tears down what\n // it did begin. Returning earlier would leave the liveness thread renewing\n // a stopped runner's lease, and polling running after stop() (#4944).\n if (pendingStart) this.startCancelled = true;\n const stopping = (async () => {\n if (pendingStart) {\n try {\n await pendingStart;\n } catch {\n // A failed start() is the caller's error; tear down what it left.\n }\n }\n await this.shutdown();\n })();\n this.stopPromise = stopping;\n try {\n await stopping;\n } finally {\n if (this.stopPromise === stopping) this.stopPromise = null;\n }\n }\n\n /** The body of {@link stop}: drain, then release lease renewal and liveness. */\n private async shutdown(): Promise<void> {\n if (!this.running) return;\n if (this.shutdownPromise) return this.shutdownPromise;\n\n this.running = false;\n this.pollGeneration++;\n\n // Stop polling and the telemetry heartbeat immediately; no new jobs claim.\n if (this.pollTimer) {\n clearTimeout(this.pollTimer);\n this.pollTimer = null;\n }\n if (this.heartbeatTimer) {\n clearInterval(this.heartbeatTimer);\n this.heartbeatTimer = null;\n }\n if (this.retentionSweeper) {\n this.retentionSweeper.stop();\n this.retentionSweeper = null;\n }\n // NOTE: leave lease renewal (the leaseTimer or the off-loop thread) running\n // through the drain so a still-executing handler keeps its lease fresh and\n // isn't recovered by a peer; both are torn down after the drain below.\n\n // A planned stop must not leave over-claimed rows `running`: the next\n // incarnation's recovery would fail them as orphans without running them.\n await this.retryUnreleasedSurplus();\n\n // Wait for active jobs to complete (with timeout)\n this.shutdownPromise = this.waitForActiveJobs();\n\n try {\n await this.shutdownPromise;\n } finally {\n this.shutdownPromise = null;\n // The drain also waited for an in-flight poll, whose own surplus\n // release may have failed after the flush above: flush again (#3148).\n await this.retryUnreleasedSurplus();\n // Stop off-loop lease renewal (thread) and main-loop renewal (timer) only\n // AFTER the drain, so a still-running handler kept its lease fresh.\n await this.stopLivenessThread();\n if (this.leaseTimer) {\n clearInterval(this.leaseTimer);\n this.leaseTimer = null;\n }\n // Release liveness only AFTER the drain: doing it earlier would make\n // still-draining jobs look orphaned to other recoverers.\n unregisterLiveWorker(this.workerKey);\n releaseJobHandlerRegistry(this.workerKey);\n // Only delete the lease row if the drain finished cleanly. If jobs are\n // still executing past the shutdown timeout, leave the row to lapse\n // naturally (≤ TTL) so a nearly-finished handler keeps its chance to land\n // its own completion before peers can recover it.\n if (this.activeJobs.size === 0 && !this.pollPromise) {\n try {\n await this.workerCollection?.expireWorker(this.workerKey);\n } catch {\n // Best-effort: a left-over row simply expires via its lease.\n }\n }\n this.emit('runner:stopped');\n }\n }\n\n /**\n * Check if runner is running\n */\n isRunning(): boolean {\n return this.running;\n }\n\n /**\n * Get count of active jobs\n */\n activeJobCount(): number {\n return this.activeJobs.size;\n }\n\n /**\n * Start the polling loop\n */\n private startPolling(): void {\n const poll = async () => {\n if (!this.running) return;\n\n let foundWork = true;\n try {\n this.pollPromise = this.poll();\n foundWork = await this.pollPromise;\n } catch (error) {\n this.emit('runner:error', error as Error);\n } finally {\n this.pollPromise = null;\n }\n\n // Schedule next poll\n if (this.running) {\n this.pollTimer = setTimeout(poll, this.nextPollDelay(foundWork));\n }\n };\n\n // Start immediately\n poll();\n }\n\n /**\n * Poll for and process jobs\n */\n private nextPollDelay(foundWork: boolean): number {\n if (foundWork) {\n this.resetIdlePollDelay();\n return this.boundPollDelay(this.config.pollInterval);\n }\n\n const delay = this.idlePollDelayMs;\n this.idlePollDelayMs = Math.min(delay * 2, this.maxIdlePollIntervalMs);\n return this.boundPollDelay(delay);\n }\n\n private boundPollDelay(delay: number): number {\n // A throttled sweep may have been skipped on this poll. Bound the next\n // wait by the remaining recovery budget, not a fresh TTL from this poll.\n const elapsed = this.workersTableVerified\n ? Date.now() - this.lastRecoverySweepAt\n : 0;\n return Math.min(delay, Math.max(1, this.effectiveLeaseTtlMs - elapsed));\n }\n\n private resetIdlePollDelay(): void {\n this.idlePollDelayMs = this.config.pollInterval;\n }\n\n private async poll(): Promise<boolean> {\n const generation = this.pollGeneration;\n if (!this.collection || !this.db) return true;\n\n // stop() may begin while any await below is pending; it waits for this\n // poll, so bail out instead of claiming work after shutdown began (#3148).\n await this.recoverStaleJobs();\n if (generation !== this.pollGeneration) return false;\n await this.retryUnreleasedSurplus();\n if (generation !== this.pollGeneration) return false;\n await this.sweepUnclaimedHandlerJobs();\n if (generation !== this.pollGeneration) return false;\n\n // Calculate how many jobs we can take\n const available = this.config.concurrency - this.activeJobs.size;\n if (available <= 0) return true;\n\n // Atomically claim ready jobs before processing so multiple workers cannot\n // receive the same pending row.\n const claimed = await this.collection.claimReady({\n claimFencing: this.config.claimFencing,\n workerId: this.workerKey,\n queues: this.config.queues,\n tenantIds: this.config.tenantIds,\n // Model jobs, and only the handler jobs this runner can run (#5005).\n handlerNames: this.handlerNames,\n limit: available,\n });\n\n // `concurrency` is a hard cap: never start more jobs than free slots, even\n // if a claim returns extra rows (a PostgreSQL claim once took the whole\n // backlog, #3145). Surplus rows go back to `pending` untouched.\n const jobs = claimed.slice(0, available);\n if (claimed.length > available) {\n await this.releaseSurplusClaims(claimed.slice(available));\n }\n\n for (const [index, job] of jobs.entries()) {\n // Shutdown may start during the claim, surplus release, or a previous\n // job's synchronous started listener. Never dispatch an unstarted claim.\n if (generation !== this.pollGeneration) {\n await this.releaseSurplusClaims(jobs.slice(index), false);\n return false;\n }\n const jobId = job.id;\n if (!jobId) continue;\n\n // Process asynchronously. We deliberately do NOT await — concurrency is\n // bounded by `activeJobs` above, not by serializing here. But a bare\n // fire-and-forget call means any unexpected rejection (e.g. the failure-\n // path write in handleJobError rejecting, a failure mode correlated with\n // whatever is already failing the job) escapes as an unhandled promise\n // rejection and crashes the worker under Node's default\n // `--unhandled-rejections=throw`. handleJobError is itself wrapped in\n // try/catch, but guard the caller too as defense in depth so no rejection\n // can ever escape the poll loop.\n this.processJob(job).catch((error) => {\n this.emit('runner:error', error as Error);\n });\n }\n\n return jobs.length > 0;\n }\n\n /**\n * Return over-claimed rows to `pending` with their claim undone, so the\n * attempt is not consumed and any worker can claim them normally. Only rows\n * this incarnation still owns as `running` and is not executing are\n * touched, in chunked statements.\n *\n * A failed release keeps the ids; it is retried at the start of every poll\n * and by `stop()` both before and after its drain. If the process dies\n * first, stale recovery fails those rows as orphaned (it does not requeue\n * them).\n */\n private async releaseSurplusClaims(\n surplus: SmrtJob[],\n reportExceededLimit = true,\n ): Promise<void> {\n const ids = surplus\n .map((job) => job.id)\n .filter((id): id is string => typeof id === 'string' && id.length > 0);\n if (ids.length === 0) return;\n if (reportExceededLimit)\n this.emit(\n 'runner:error',\n new Error(\n `claimReady returned ${ids.length} job(s) beyond the concurrency limit (${this.config.concurrency}); releasing them back to pending`,\n ),\n );\n for (const id of ids) this.unreleasedSurplus.add(id);\n await this.retryUnreleasedSurplus();\n }\n\n private async retryUnreleasedSurplus(): Promise<void> {\n if (!this.db) return;\n // A retained id this runner has since claimed normally is live work, not\n // surplus: never unclaim a job this incarnation is executing.\n for (const id of this.unreleasedSurplus) {\n if (this.activeJobs.has(id)) this.unreleasedSurplus.delete(id);\n }\n const ids = [...this.unreleasedSurplus];\n for (let i = 0; i < ids.length; i += SURPLUS_RELEASE_CHUNK) {\n const chunk = ids.slice(i, i + SURPLUS_RELEASE_CHUNK);\n const placeholders = chunk.map(() => '?').join(', ');\n try {\n await this.db.query(\n `UPDATE _smrt_jobs\n SET status = 'pending',\n worker_id = NULL,\n worker_heartbeat = NULL,\n started_at = NULL,\n attempts = CASE WHEN attempts > 0 THEN attempts - 1 ELSE 0 END,\n updated_at = ?\n WHERE worker_id = ? AND status = 'running' AND id IN (${placeholders})`,\n new Date().toISOString(),\n this.workerKey,\n ...chunk,\n );\n // Rows the statement did not match are no longer this worker's\n // `running` claim, so there is nothing left to release for them.\n for (const id of chunk) this.unreleasedSurplus.delete(id);\n } catch (error) {\n // Still `running` under this worker's live lease; never started here.\n this.emit('runner:error', error as Error);\n }\n }\n }\n\n /**\n * Process a single job.\n *\n * AT-LEAST-ONCE EXECUTION CONTRACT: a `timeout` only races the handler's\n * promise — JavaScript cannot preempt an already-running handler, so on a\n * `'fail'` (or `'kill'`) timeout the original handler keeps executing in the\n * background while the job row is failed. Timeouts are NOT auto-retried (see\n * handleJobError) precisely so a still-running handler is not duplicated by a\n * retry; but the orphaned handler's own side effects still happen, and an\n * ordinary (non-timeout) failure IS retried and re-claimable by any worker.\n * Handlers invoked from a job MUST be idempotent (e.g. keyed by\n * `context.job.jobId` or a caller-supplied idempotency key); do not rely on a\n * job body running exactly once. See AGENTS.md \"Timeouts & at-least-once\".\n */\n private async processJob(job: SmrtJob): Promise<void> {\n const jobId = job.id;\n if (!jobId) {\n this.emit('runner:error', new Error('Job has no ID'));\n return;\n }\n\n this.activeJobs.set(jobId, job);\n this.emit('job:started', job);\n await this.appendJobEvent(job, {\n type: 'status',\n level: 'info',\n stage: 'started',\n progress: 0,\n message: `Started job: ${job.getDescription()}`,\n });\n\n // Capture the timeout handle so it is always cleared in `finally`. Without\n // this, every fast job left a ~5-min (default) armed timer on the heap\n // until it fired and was swallowed by the settled race — timer-heap\n // pressure plus a delayed clean process exit.\n let timeoutHandle: NodeJS.Timeout | null = null;\n let cancelPollHandle: NodeJS.Timeout | null = null;\n const abortController = new AbortController();\n this.jobAborts.set(jobId, abortController);\n\n try {\n cancelPollHandle = this.startCancelPoll(job, abortController);\n const result = await this.runWithTimeout(job, (handle) => {\n timeoutHandle = handle;\n });\n\n // Job completed successfully. Write the terminal state conditionally so a\n // recovered/reclaimed row (worker died, recovery ran, the work finished\n // anyway) is never stomped back to 'completed'.\n const completedAt = new Date();\n const snapshot = terminalSnapshot(job, this.config.claimFencing);\n let event: SmrtJobEvent | null = null;\n try {\n event = snapshot\n ? await transitionTerminalJob(this.db as DatabaseInterface, {\n job: snapshot,\n status: 'completed',\n completedAt,\n expectedStatuses: ['running'],\n expectedWorkerId: this.workerKey,\n resultPointer: result?.resultPointer ?? null,\n taskResult: result?.taskResult ?? null,\n })\n : null;\n } catch (persistenceError) {\n // The handler already returned successfully. A terminal persistence\n // failure is an operator fault, not a business execution failure: the\n // transaction left the owned row running, and it must not be retried\n // through handleJobError(). The recovery sweep settles it as failed,\n // with its event, saying what happened.\n this.reportUnpersistedJobWrite(\n job,\n 'completion',\n persistenceError,\n `Job handler returned but its completion could not be persisted (${redactErrorForPersistence(persistenceError)}); settled as failed by recovery, not retried.`,\n );\n return;\n }\n\n if (event) {\n job.status = 'completed';\n job.completedAt = completedAt;\n job.resultPointer = result?.resultPointer ?? null;\n job.taskResult = result?.taskResult ?? null;\n this.emitPersistedJobEvent(job, event);\n this.emit('job:completed', job, result);\n }\n } catch (error) {\n // handleJobError is wrapped so its own failure-path write (a `db.query`\n // that may reject for the same reason the job is failing) cannot turn\n // into an unhandled rejection / unbounded crash. A failure to persist the\n // failure is surfaced as a runner error, not a thrown rejection.\n try {\n await this.handleJobError(job, error as Error);\n } catch (handlerError) {\n if (handlerError instanceof UnpersistedJobWriteError) {\n this.reportUnpersistedJobWrite(\n job,\n 'failure',\n handlerError.writeError,\n `${redactErrorForPersistence(error)} (the failure could not be persisted when it happened: ${redactErrorForPersistence(handlerError.writeError)}; settled as failed by recovery, not retried.)`,\n );\n } else {\n // A listener or telemetry call threw after the write committed:\n // the row is not stranded, so this is only a runner error.\n this.emit('runner:error', handlerError as Error);\n }\n }\n } finally {\n if (timeoutHandle) clearTimeout(timeoutHandle);\n if (cancelPollHandle) clearInterval(cancelPollHandle);\n this.jobAborts.delete(jobId);\n this.activeJobs.delete(jobId);\n }\n }\n\n /**\n * Every terminal write needs the terminal-outcome storage, and preparing it\n * builds the registry's merged schemas. Prepare it before claiming anything\n * (#4735): a registry inconsistency then stops the runner at start, naming\n * itself, instead of leaving every claimed job `running`; and models that\n * register after start can no longer block a terminal write, because\n * readiness is cached for this database.\n */\n private async prepareTerminalOutcomeStorage(): Promise<void> {\n try {\n await ensureTerminalOutcomeStorage(this.db as DatabaseInterface);\n } catch (error) {\n this.logger.error(\n `TaskRunner cannot start: terminal job outcomes cannot be persisted: ${redactErrorForPersistence(error)}`,\n );\n throw error;\n }\n }\n\n /**\n * A job's terminal (or retry) write could not be persisted. The state and\n * its event commit together or not at all, so the row is still `running`.\n *\n * It must not be silent (#4735): `runner:error` is only heard by a caller\n * that listens, so say it at error level with the job id as well. And it\n * must not stay `running` for good: the owning worker is alive, so\n * liveness-based recovery would skip the row until this process stops.\n * `settleAs` records the `last_error` this runner's own recovery sweep\n * settles it with, atomically with its event, once the fault clears.\n */\n private reportUnpersistedJobWrite(\n job: SmrtJob,\n write: 'completion' | 'failure' | 'stale recovery',\n cause: unknown,\n settleAs?: string,\n ): void {\n const error = cause instanceof Error ? cause : new Error(String(cause));\n const jobId = job.id;\n if (settleAs && jobId) this.unsettledJobs.set(jobId, settleAs);\n const firstReport =\n write !== 'stale recovery' ||\n !jobId ||\n !this.recoveryFailuresLogged.has(jobId);\n if (firstReport) {\n if (write === 'stale recovery' && jobId) {\n this.recoveryFailuresLogged.add(jobId);\n }\n const next =\n write === 'stale recovery'\n ? 'it stays running and each recovery sweep retries it'\n : \"it stays running until this runner's next recovery sweep settles it as failed\";\n this.logger.error(\n `Job ${jobId} (${job.getDescription()}) ${write} could not be persisted; ${next}: ${redactErrorForPersistence(error)}`,\n );\n }\n this.emit('runner:error', error);\n }\n\n /** Tag a rejection from a job's own state write (see the caller's catch). */\n private async persistJobWrite<T>(write: () => Promise<T>): Promise<T> {\n try {\n return await write();\n } catch (cause) {\n throw new UnpersistedJobWriteError(cause);\n }\n }\n\n /**\n * Execute a job honoring its {@link SmrtJob.timeoutBehavior}.\n *\n * - `'fail'` (default) and `'kill'`: race the handler against a timeout. On\n * timeout the race rejects and the caller fails/retries the job.\n * `'kill'` cannot actually preempt the handler in-process (JavaScript has\n * no thread interruption), so it is treated identically to `'fail'` — the\n * handler keeps running in the background; only the job row is failed. This\n * is documented in AGENTS.md so `'kill'` is honest about what it does\n * rather than silently behaving like a no-op.\n * - `'warn'`: do NOT fail on timeout. Arm a one-shot warning (logged + emitted\n * as a job event) at the deadline, but await the handler to completion so a\n * slow-but-successful handler still completes. This makes `'warn'` honest:\n * previously every timeout was treated as `'fail'` regardless of the\n * persisted/UI-shown behavior.\n */\n private async runWithTimeout(\n job: SmrtJob,\n captureHandle: (handle: NodeJS.Timeout) => void,\n ): Promise<{\n result?: unknown;\n resultPointer?: string;\n taskResult?: Record<string, unknown>;\n }> {\n if (job.timeoutBehavior === 'warn') {\n const handle = setTimeout(() => {\n this.logger.warn(\n `Job exceeded timeout (${job.timeout}ms) but timeoutBehavior='warn'; letting it finish: ${job.getDescription()}`,\n );\n // Best-effort telemetry; must not change the job outcome.\n void this.appendJobEvent(job, {\n type: 'status',\n level: 'warn',\n stage: 'timeout-warning',\n message: `Job exceeded timeout of ${job.timeout}ms (timeoutBehavior='warn')`,\n data: { timeout: job.timeout },\n });\n }, job.timeout);\n captureHandle(handle);\n return this.executeJob(job);\n }\n\n // 'fail' (default) and 'kill' (treated as 'fail'; see doc comment).\n const timeoutPromise = new Promise<never>((_, reject) => {\n const handle = setTimeout(() => {\n const timeoutError = new JobTimeoutError(\n `Job timeout after ${job.timeout}ms`,\n );\n // Let the orphaned handler stop; the row is failed by the rejection.\n const controller = job.id ? this.jobAborts.get(job.id) : undefined;\n controller?.abort(timeoutError);\n reject(timeoutError);\n }, job.timeout);\n captureHandle(handle);\n });\n\n return Promise.race([this.executeJob(job), timeoutPromise]);\n }\n\n /**\n * Poll the owned row while its handler runs and abort the job's signal when\n * it is observed as cancelled. Read-only; failures are ignored (the next tick\n * retries). Returns an unref'd interval the caller must clear.\n */\n private startCancelPoll(\n job: SmrtJob,\n controller: AbortController,\n ): NodeJS.Timeout | null {\n const jobId = job.id;\n const db = this.db;\n if (!jobId || !db) return null;\n let inFlight = false;\n const handle = setInterval(() => {\n if (inFlight || controller.signal.aborted) return;\n inFlight = true;\n void Promise.resolve()\n .then(() =>\n db.query(`SELECT status FROM _smrt_jobs WHERE id = ?`, jobId),\n )\n .then((res) => {\n const status = (res?.rows?.[0] as { status?: string } | undefined)\n ?.status;\n if (status === 'cancelled' && !controller.signal.aborted) {\n controller.abort(\n new JobCancelledError(`Job cancelled: ${job.getDescription()}`),\n );\n }\n })\n .catch(() => {})\n .finally(() => {\n inFlight = false;\n });\n }, this.config.cancelPollInterval);\n handle.unref();\n return handle;\n }\n\n /**\n * Apply a terminal/retry state transition to a job only if this worker still\n * owns it and it is still `running`. Returns whether the write applied.\n *\n * This closes the completion-vs-recovery race: if recovery already failed a\n * job out from under a finishing handler (a genuine zombie), the handler's\n * outcome is dropped rather than resurrecting the row.\n */\n private async writeOwnedJob(\n jobId: string,\n assignments: Record<string, unknown>,\n dispatch?: SmrtJob,\n ): Promise<boolean> {\n if (!this.db) return false;\n const columns = Object.keys(assignments);\n const setSql = columns.map((column) => `${column} = ?`).join(', ');\n const values = columns.map((column) => assignments[column]);\n // RETURNING id (not rowCount): the DuckDB/JSON adapters report rowCount as\n // the number of result rows, so an UPDATE that matched nothing still\n // reports 1 — only the returned-row set is a reliable \"did it apply\".\n const fenced = this.config.claimFencing && dispatch;\n const result = await this.db.query(\n `UPDATE _smrt_jobs\n SET ${setSql}\n WHERE id = ? AND worker_id = ? AND status = 'running'${fenced ? ' AND attempts = ? AND started_at = ?' : ''}\n RETURNING id`,\n ...values,\n jobId,\n this.workerKey,\n ...(fenced\n ? [dispatch.attempts, dispatch.startedAt?.toISOString() ?? null]\n : []),\n );\n return (result.rows?.length ?? 0) > 0;\n }\n\n /**\n * Execute a job by invoking the method on the SmrtObject\n */\n private async executeJob(job: SmrtJob): Promise<{\n result?: unknown;\n resultPointer?: string;\n taskResult?: Record<string, unknown>;\n }> {\n const runJob = async (): Promise<{\n result?: unknown;\n resultPointer?: string;\n taskResult?: Record<string, unknown>;\n }> => {\n await this.assertMcpTaskAuthority(job);\n // A reserved `handler:` target never reaches the model registry (#5005).\n const handlerName = jobHandlerName(job.objectType);\n if (handlerName !== null) return this.executeHandlerJob(job, handlerName);\n // Get the object class from registry\n const registeredClass = ObjectRegistry.getClass(job.objectType);\n if (!registeredClass) {\n throw new Error(`Unknown object type: ${job.objectType}`);\n }\n\n // Get the constructor from the registry entry\n const ObjectClass = registeredClass.constructor as unknown as new (\n options: Record<string, unknown>,\n ) => SmrtObject;\n\n // Extract internal keys from args before passing to constructor/method\n const rawArgs = (job.args ?? {}) as Record<string, unknown>;\n const persistedAgentConfig = (rawArgs._agentConfig ?? {}) as Record<\n string,\n unknown\n >;\n const {\n _agentConfig: _,\n _scheduleId: __,\n _mcpTask: ___,\n ...methodArgs\n } = rawArgs;\n\n // Resolve any lazy / env-derived config sentinels at execute time so\n // operators can rotate env vars without rewriting persisted schedule\n // rows (issue #1161). Class-level `static configResolvers` are layered\n // on top so live values always win over snapshotted ones.\n //\n // `onError: 'throw'` so a misconfigured deployment fails fast at the\n // job boundary with a clear \"unknown resolver X\" error, rather than\n // silently spreading a `{ $env: '...' }` sentinel object into the\n // agent constructor (where it would surface much later as a confusing\n // downstream failure — e.g. `[object Object]` masquerading as a\n // bucket name).\n //\n // Every resolver receives this job's own agent identity and the value\n // this instance's persisted config holds for its key (#2806), so a\n // per-agent credential resolver can defer to the agent's own value. The\n // identity comes only from the job row — never from scanning the\n // tenant's other agents.\n const classResolvers = getClassConfigResolvers(ObjectClass);\n const scheduleId =\n typeof rawArgs._scheduleId === 'string'\n ? rawArgs._scheduleId\n : undefined;\n const agentConfig = await resolveLazyConfig(persistedAgentConfig, {\n classResolvers,\n onError: 'throw',\n context: {\n agentId:\n typeof job.objectId === 'string' && job.objectId.length > 0\n ? job.objectId\n : undefined,\n agentClass: registeredClass.qualifiedName ?? job.objectType,\n tenantId: job.tenantId ?? null,\n scheduleId,\n jobId: job.id ?? undefined,\n },\n });\n\n // Persistence identity and the database connection belong to the\n // runner. Persisted constructor config may configure the target, but it\n // must never redirect hydration or execution to a different store.\n const safeAgentConfig = { ...agentConfig };\n delete safeAgentConfig.db;\n delete safeAgentConfig.id;\n delete safeAgentConfig._skipLoad;\n\n // Create or load the object instance\n let instance: SmrtObject;\n\n if (job.objectId) {\n // initialize() performs the canonical hydration when the persisted ID\n // is supplied to the constructor.\n instance = new ObjectClass({\n db: this.db,\n id: job.objectId,\n ...safeAgentConfig,\n });\n await instance.initialize();\n\n if (!instance.isPersisted) {\n throw new Error(\n `Object-bound job target not found: ${job.objectType}#${job.objectId}`,\n );\n }\n } else {\n // Create new instance for static-like methods\n instance = new ObjectClass({ db: this.db, ...safeAgentConfig });\n await instance.initialize();\n }\n\n const jobId = job.id;\n if (!jobId) {\n throw new Error('Job has no ID');\n }\n\n // Create a base logger for job context\n const baseLogger = createLogger(true);\n\n // Inject job context logger\n const contextLogger = new JobContextLogger(baseLogger, {\n jobId,\n attempt: job.attempts,\n queue: job.queue,\n objectType: job.objectType,\n method: job.method,\n });\n\n // Log job start\n contextLogger.info(`Starting job: ${job.getDescription()}`);\n const executionContext = this.createExecutionContext(job, contextLogger);\n\n // Invoke the method with cleaned args (no internal keys)\n const method = (\n instance as unknown as Record<\n string,\n (\n args: unknown,\n context?: JobExecutionContext,\n ) => Promise<unknown> | unknown\n >\n )[job.method];\n if (typeof method !== 'function') {\n throw new Error(`Method not found: ${job.objectType}.${job.method}`);\n }\n\n // Opt-in allowlist: if the target class declares background-eligible\n // methods, refuse to invoke anything outside that set. Dispatch is already\n // bounded to existing prototype methods (no eval/dynamic import), but a\n // class can narrow the reachable surface to an explicit contract\n // (S5 audit #1402). Classes that don't opt in keep current behaviour.\n if (!isBackgroundEligibleMethod(ObjectClass, job.method)) {\n throw new Error(\n `Method not background-eligible: ${job.objectType}.${job.method}`,\n );\n }\n\n const taskMarker = getMcpTaskMarker(job);\n const result = await runnerExecutionContexts.run(\n executionContext,\n async () =>\n taskMarker\n ? await (\n method as (...args: unknown[]) => Promise<unknown> | unknown\n ).call(instance, ...taskMarker.invocationArgs, executionContext)\n : await method.call(instance, methodArgs, executionContext),\n );\n\n // Generated custom actions use an explicit `{ ok: false, ... }` return\n // convention. A task must surface that as a failed terminal state, not\n // a successfully completed task whose payload happens to describe an\n // error.\n if (taskMarker) {\n const failure = normalizeCustomActionFailure(result);\n if (failure) throw new Error(failure.message);\n }\n\n return {\n result,\n ...(taskMarker ? { taskResult: createMcpTaskResult(result) } : {}),\n };\n };\n\n if (job.tenantId) {\n return TenantContext.runWithJobContext(\n { tenantId: job.tenantId },\n runJob,\n );\n }\n\n return runJob();\n }\n\n /**\n * Run a job that targets a registered named handler (#5005). Called inside\n * `executeJob`'s tenant context, after the same MCP authority check as a\n * model job; timeout, cancellation, claim fencing and terminal writes are\n * the shared model-job paths.\n */\n private async executeHandlerJob(\n job: SmrtJob,\n name: string,\n ): Promise<{ result?: unknown }> {\n if (job.method !== JOB_HANDLER_METHOD || job.objectId != null)\n throw new JobHandlerTargetError(\n `Handler job ${job.objectType} must have method '${JOB_HANDLER_METHOD}' and no objectId`,\n );\n if (getMcpTaskMarker(job) || job.taskId != null || job.taskOwnerId != null)\n throw new JobHandlerTargetError(\n `Handler job ${job.objectType} cannot be an MCP task`,\n );\n const handler = this.jobHandlers.get(name);\n if (!handler) throw new JobHandlerUnregisteredError(name);\n\n const jobId = job.id;\n if (!jobId) throw new Error('Job has no ID');\n const {\n _agentConfig: _,\n _scheduleId: __,\n _mcpTask: ___,\n ...payload\n } = (job.args ?? {}) as Record<string, unknown>;\n const contextLogger = new JobContextLogger(createLogger(true), {\n jobId,\n attempt: job.attempts,\n queue: job.queue,\n objectType: job.objectType,\n method: job.method,\n });\n contextLogger.info(`Starting job: ${job.getDescription()}`);\n const executionContext = this.createExecutionContext(\n job,\n contextLogger,\n name,\n );\n const result = await runnerExecutionContexts.run(\n executionContext,\n async () => await handler(payload, executionContext),\n );\n return { result };\n }\n\n /**\n * Handle job execution error\n */\n private async handleJobError(job: SmrtJob, error: Error): Promise<void> {\n if (error instanceof McpTaskSuspendedError) return;\n const { fromConfig } = await import('@happyvertical/jobs');\n const strategy = fromConfig(job.retryStrategy);\n const decision: RetryDecision = strategy.shouldRetry(job.attempts, error);\n\n const jobId = job.id;\n if (!jobId) return;\n\n // A timed-out handler keeps running in the background (JS can't preempt it).\n // Re-queueing the row as `pending` while the original still executes would\n // make the next worker run a *second* concurrent copy. So do not auto-retry\n // a timeout — fail it terminally. This narrows the duplicate-execution\n // window from the at-least-once contract (#2 in the #1401 review); it does\n // not remove it (the orphaned handler can still finish and write a terminal\n // state, which writeOwnedJob's ownership guard then drops).\n const isTimeout = error instanceof JobTimeoutError;\n\n // `last_error` is persisted to the durable `_smrt_jobs` row and is readable\n // through generated (tenant-scoped) list/get routes. Strip secret-shaped\n // substrings before persistence so a failing job that echoes a credential\n // in its message does not turn into a durable leak (S5 audit #1402).\n // Use the throwable-tolerant wrapper: `error` is typed `Error` but reaches\n // here via an `as Error` cast at the call site, so a non-Error throwable\n // (no `.message`) would otherwise persist an empty `last_error`.\n const safeMessage = redactErrorForPersistence(error);\n\n // The handler's own hints win over the strategy: `retryable: false` is\n // terminal, and `retryAfterMs` is a floor on the strategy's backoff.\n const hints = errorRetryHints(error);\n const delay = Math.max(decision.delay, hints.retryAfterMs ?? 0);\n\n if (\n !isTimeout &&\n hints.retryable &&\n decision.shouldRetry &&\n job.attempts < job.maxAttempts\n ) {\n // Schedule retry\n const nextRunAt = new Date(Date.now() + delay);\n\n // Conditional: don't resurrect a row that recovery already failed.\n const applied = await this.persistJobWrite(() =>\n this.writeOwnedJob(\n jobId,\n {\n status: 'pending',\n last_error: safeMessage,\n run_at: nextRunAt.toISOString(),\n worker_id: null,\n worker_heartbeat: null,\n updated_at: new Date().toISOString(),\n },\n job,\n ),\n );\n if (!applied) return;\n\n job.status = 'pending';\n job.lastError = safeMessage;\n job.runAt = nextRunAt;\n job.workerId = null;\n job.workerHeartbeat = null;\n\n await this.appendJobEvent(job, {\n type: 'status',\n level: 'warn',\n stage: 'retrying',\n message: `Retrying job after failure: ${safeMessage}`,\n data: { delay, attempts: job.attempts },\n });\n this.emit('job:retrying', job, error, delay);\n } else {\n // Job failed permanently\n const completedAt = new Date();\n const snapshot = terminalSnapshot(job, this.config.claimFencing);\n const event = snapshot\n ? await this.persistJobWrite(() =>\n transitionTerminalJob(this.db as DatabaseInterface, {\n job: snapshot,\n status: 'failed',\n completedAt,\n expectedStatuses: ['running'],\n expectedWorkerId: this.workerKey,\n lastError: safeMessage,\n failureKind: isTimeout\n ? 'timeout'\n : error instanceof JobHandlerUnregisteredError\n ? 'handler-unregistered'\n : 'execution',\n }),\n )\n : null;\n if (!event) return;\n\n job.status = 'failed';\n job.completedAt = completedAt;\n job.lastError = safeMessage;\n\n this.emitPersistedJobEvent(job, event);\n this.emit('job:failed', job, error);\n }\n }\n\n private async assertMcpTaskAuthority(job: SmrtJob): Promise<void> {\n const marker = getMcpTaskMarker(job);\n const continuation = marker?.continuation;\n if (!continuation && !marker?.authorizationRequired) return;\n let authorized = false;\n try {\n authorized =\n !!job.taskOwnerId &&\n (await this.config.authorizeMcpTask(\n Object.freeze({\n ownerId: job.taskOwnerId,\n tenantId: job.tenantId ?? null,\n taskId: job.taskId ?? '',\n objectType: job.objectType,\n objectId: job.objectId ?? '',\n method: job.method,\n ...(continuation\n ? { continuation: Object.freeze({ ...continuation }) }\n : {}),\n }),\n ));\n } catch {\n // Provider failures are internal; never persist their details in tasks/get.\n }\n if (!authorized) throw new Error('MCP task authorization denied');\n // Authority lookup may await network I/O; cancellation can win meanwhile.\n const owned = await this.db?.query(\n `SELECT id FROM _smrt_jobs WHERE id = ? AND worker_id = ? AND status = 'running'`,\n job.id,\n job.workerId,\n );\n if (owned?.rows.length !== 1)\n throw new Error('MCP task is no longer active');\n }\n\n private createExecutionContext(\n job: SmrtJob,\n contextLogger: JobContextLogger,\n handler?: string,\n ): JobExecutionContext {\n const jobContext = {\n jobId: job.id ?? '',\n tenantId: job.tenantId ?? null,\n attempt: job.attempts,\n queue: job.queue,\n objectType: job.objectType,\n method: job.method,\n ...(handler === undefined ? {} : { handler }),\n };\n\n const context: JobExecutionContext = {\n job: jobContext,\n logger: contextLogger,\n signal:\n (job.id ? this.jobAborts.get(job.id)?.signal : undefined) ??\n new AbortController().signal,\n event: async (input: JobEventInput) => {\n await this.appendJobEvent(job, input);\n },\n progress: async (input: JobProgressInput) => {\n const data = {\n ...(input.data ?? {}),\n ...(input.detail ? { detail: input.detail } : {}),\n ...(input.source ? { source: input.source } : {}),\n };\n await this.appendJobEvent(job, {\n type: 'progress',\n level: 'info',\n stage: input.stage,\n progress: input.progress,\n message:\n input.message ??\n input.detail ??\n `${input.stage} ${Math.round(input.progress)}%`,\n data,\n });\n },\n log: async (\n level: 'debug' | 'info' | 'warn' | 'error',\n message: string,\n data?: Record<string, unknown>,\n ) => {\n contextLogger[level](message, data);\n await this.appendJobEvent(job, {\n type: level === 'error' ? 'error' : 'log',\n level,\n message,\n data,\n });\n },\n ...(job.taskId && this.db\n ? {\n task: {\n assertAuthorized: () => this.assertMcpTaskAuthority(job),\n requestContinuation: (binding, inputRequest) =>\n requestMcpTaskContinuation(\n this.db as DatabaseInterface,\n job,\n binding,\n inputRequest,\n ),\n requestInput: async (inputRequests: Record<string, unknown>) => {\n await this.assertMcpTaskAuthority(job);\n const answers = await requestMcpTaskInput(\n this.db as DatabaseInterface,\n job,\n inputRequests,\n );\n await this.assertMcpTaskAuthority(job);\n return answers;\n },\n },\n }\n : {}),\n };\n runnerExecutionContextIdentities.add(context);\n if (this.config.claimFencing)\n runnerJobClaims.set(\n context,\n Object.freeze({\n jobId: job.id ?? '',\n workerId: this.workerKey,\n attempt: job.attempts,\n startedAt: job.startedAt?.toISOString() ?? '',\n tenantId: job.tenantId ?? null,\n objectType: job.objectType,\n objectId: job.objectId ?? null,\n method: job.method,\n }),\n );\n return context;\n }\n\n private async appendJobEvent(\n job: SmrtJob,\n input: JobEventInput,\n ): Promise<SmrtJobEvent | null> {\n if (!this.eventCollection || !job.id) {\n return null;\n }\n\n try {\n const event = await this.eventCollection.append({\n tenantId: job.tenantId ?? null,\n jobId: job.id,\n type: input.type ?? 'log',\n level: input.level ?? 'info',\n stage: input.stage ?? null,\n progress: input.progress ?? null,\n message: input.message ?? '',\n data: input.data ?? {},\n });\n\n this.emitPersistedJobEvent(job, event);\n\n return event;\n } catch (error) {\n const telemetryError =\n error instanceof Error\n ? error\n : new Error(`Failed to append job telemetry: ${String(error)}`);\n\n try {\n this.emit('runner:error', telemetryError);\n } catch {\n // Telemetry is best-effort and must not change job outcomes.\n }\n\n return null;\n }\n }\n\n private emitPersistedJobEvent(job: SmrtJob, event: SmrtJobEvent): void {\n try {\n this.emit('job:event', job, event);\n } catch (error) {\n this.emitTelemetryError(error);\n }\n if (event.type === 'progress') {\n try {\n this.emit('job:progress', job, event);\n } catch (error) {\n this.emitTelemetryError(error);\n }\n }\n }\n\n private emitTelemetryError(error: unknown): void {\n const telemetryError =\n error instanceof Error\n ? error\n : new Error(`Job telemetry listener failed: ${String(error)}`);\n try {\n this.emit('runner:error', telemetryError);\n } catch {\n // Telemetry is best-effort and must not change job outcomes.\n }\n }\n\n /**\n * Whether the `_smrt_workers` table exists. Cached once positive — the table\n * never disappears mid-run, so this avoids a probe query on every poll.\n */\n private async workersTableReady(): Promise<boolean> {\n if (this.workersTableVerified) return true;\n const ready = (await this.workerCollection?.tableReady()) ?? false;\n if (ready) this.workersTableVerified = true;\n return ready;\n }\n\n /**\n * Recover jobs orphaned by dead/restarted workers.\n *\n * A `running` job is recovered only when its owning worker is *not alive*\n * (issue #1474): not live in this process and holding no fresh lease in\n * `_smrt_workers`. This is independent of the handler event loop, so a worker\n * whose handler holds the loop synchronously keeps a fresh lease (renewed off\n * the loop by the liveness thread) or stays in this process's live set, and is\n * never false-recovered. The live set takes precedence over a stale lease, and\n * a runner never recovers its own active jobs.\n *\n * Recovery is swept at most once per lease tick (not every poll), since\n * detection is TTL-bound anyway — this bounds the per-poll database load.\n */\n private async recoverStaleJobs(): Promise<void> {\n if (!this.db || !this.collection || !this.workerCollection) return;\n\n // Without the workers table we cannot reason about liveness; skip rather\n // than treat every worker as unknown and mass-recover live jobs.\n if (!(await this.workersTableReady())) return;\n\n // Throttle: at most one sweep per lease tick. Detection latency is bounded\n // by the lease TTL (>= 3x tick), so a faster cadence only adds DB load.\n const now = Date.now();\n if (now - this.lastRecoverySweepAt < this.config.leaseTickMs) return;\n this.lastRecoverySweepAt = now;\n\n // Drop long-dead worker rows so the table stays small, regardless of\n // whether any orphan is found this sweep.\n try {\n await this.workerCollection.pruneExpired(this.effectiveLeaseTtlMs * 10);\n } catch {\n // Pruning is best-effort and must not affect recovery outcomes.\n }\n\n const freshLeaseKeys = await this.workerCollection.freshLeaseWorkerKeys();\n // Worker-internal cross-tenant recovery scan; SmrtJob is @TenantScoped\n // (S5 #1402) so this raw read needs an explicit opt-in.\n const scope = jobTenantScope(this.config.tenantIds);\n const queuePredicate = this.config.queues.length\n ? ` AND queue IN (${this.config.queues.map(() => '?').join(', ')})`\n : '';\n const running = await this.collection.query(\n `SELECT ${SMRT_JOB_PORTABLE_SELECT_COLUMNS}\n FROM _smrt_jobs\n WHERE status = 'running'${scope.sql}${queuePredicate}`,\n [...scope.params, ...this.config.queues],\n { allowRawOnTenantScoped: true },\n );\n // Forget rows that are no longer running: settled by a peer, cancelled,\n // or committed after all.\n const runningIds = new Set(running.map((job) => job.id));\n for (const jobId of this.unsettledJobs.keys()) {\n if (!runningIds.has(jobId)) this.unsettledJobs.delete(jobId);\n }\n for (const jobId of this.recoveryFailuresLogged) {\n if (!runningIds.has(jobId)) this.recoveryFailuresLogged.delete(jobId);\n }\n if (running.length === 0) return;\n\n // A job is orphaned iff its owning worker is not alive: not live in this\n // process AND no fresh database lease. The live set takes precedence over a\n // stale lease (a worker whose lease lapsed while its loop was blocked is\n // still alive here); a runner also never recovers its own active jobs.\n // The exception is a row this runner itself could not settle (#4735): it\n // finished here, nothing will run it again, and no other worker may touch\n // it while this one is alive.\n const orphans = running.filter((job) => {\n const jobId = job.id;\n if (jobId && this.activeJobs.has(jobId)) return false;\n if (\n jobId &&\n this.unsettledJobs.has(jobId) &&\n job.workerId === this.workerKey\n ) {\n return true;\n }\n return !isWorkerAlive(job.workerId, freshLeaseKeys);\n });\n if (orphans.length === 0) return;\n\n const recoveredAt = new Date();\n const errorMessage =\n 'Recovered orphaned running job: its owning worker is no longer alive ' +\n '(no fresh liveness lease in _smrt_workers and not running in this process).';\n\n for (const job of orphans) {\n const snapshot = terminalSnapshot(job, this.config.claimFencing);\n if (!snapshot) continue;\n const lastError =\n (job.id ? this.unsettledJobs.get(job.id) : undefined) ?? errorMessage;\n let event: SmrtJobEvent | null;\n try {\n event = await transitionTerminalJob(this.db, {\n job: snapshot,\n status: 'failed',\n completedAt: recoveredAt,\n expectedStatuses: ['running'],\n expectedWorkerId: job.workerId ?? null,\n clearWorker: !this.config.claimFencing,\n lastError,\n failureKind: 'stale-recovery',\n });\n } catch (persistenceError) {\n // One orphan that cannot be settled must not stop the sweep for the\n // others, or stop this poll from claiming work (#4735).\n this.reportUnpersistedJobWrite(job, 'stale recovery', persistenceError);\n continue;\n }\n if (job.id) {\n this.unsettledJobs.delete(job.id);\n this.recoveryFailuresLogged.delete(job.id);\n }\n if (!event) continue;\n job.status = 'failed';\n job.completedAt = recoveredAt;\n job.lastError = lastError;\n job.workerId = null;\n job.workerHeartbeat = null;\n const error = new Error(lastError);\n this.emitPersistedJobEvent(job, event);\n this.emit('job:failed', job, error);\n }\n }\n\n /**\n * Fail named handler jobs left `pending` past their `run_at` by more than\n * `handlerUnclaimedDeadlineMs` (#5005), failure kind `handler-unclaimed`.\n *\n * Claims skip handler jobs a runner has not registered, so a job no runner\n * serves would wait forever. Every runner runs this sweep from its poll over\n * its own queues and tenant scope, at most once per 1% of the deadline\n * (between one lease tick and 15 min) and\n * {@link HANDLER_UNCLAIMED_SWEEP_LIMIT} rows at a time. It leaves out the\n * handlers this runner registered: it can claim those itself, so an\n * overdue backlog it serves (a saturated queue, a fleet back after a long\n * outage) is run, not failed. The deadline is measured from `run_at`.\n * Residual: while every runner serving a handler is down past the deadline,\n * a runner without it in the same queue still fails its jobs. Races are harmless:\n * each row is failed by one conditional transition (`pending` and still\n * past the deadline), so a concurrent sweeper, a claim or a requeue wins\n * and this one writes nothing. Model jobs are never swept. A failed sweep is\n * a `runner:error` and never stops the poll from claiming.\n */\n private async sweepUnclaimedHandlerJobs(): Promise<void> {\n if (!this.db || !this.collection) return;\n const now = Date.now();\n const deadlineMs = this.config.handlerUnclaimedDeadlineMs;\n // 1% of the deadline, between one lease tick and 15 min: the sweep adds\n // no measurable idle SQL (one SELECT per ~14 min at the 24 h default).\n const interval = Math.max(\n this.config.leaseTickMs,\n Math.min(HANDLER_UNCLAIMED_SWEEP_MAX_INTERVAL_MS, deadlineMs / 100),\n );\n if (now - this.lastUnclaimedSweepAt < interval) return;\n this.lastUnclaimedSweepAt = now;\n\n const cutoff = new Date(now - deadlineMs).toISOString();\n const scope = jobTenantScope(this.config.tenantIds);\n const queuePredicate = this.config.queues.length\n ? ` AND queue IN (${this.config.queues.map(() => '?').join(', ')})`\n : '';\n // Its own handlers are claimed, not swept (at most MAX_JOB_HANDLERS).\n const served = this.handlerNames.map(\n (name) => jobHandlerTarget(name).objectType,\n );\n const servedPredicate = served.length\n ? ` AND object_type NOT IN (${served.map(() => '?').join(', ')})`\n : '';\n let unclaimed: SmrtJob[];\n try {\n // Worker-internal cross-tenant scan, scoped like stale recovery.\n unclaimed = await this.collection.query(\n `SELECT ${SMRT_JOB_PORTABLE_SELECT_COLUMNS}\n FROM _smrt_jobs\n WHERE status = 'pending' AND run_at <= ? AND ${HANDLER_TARGET_SQL}${scope.sql}${queuePredicate}${servedPredicate}\n ORDER BY run_at ASC, id ASC\n LIMIT ?`,\n [\n cutoff,\n ...scope.params,\n ...this.config.queues,\n ...served,\n HANDLER_UNCLAIMED_SWEEP_LIMIT,\n ],\n { allowRawOnTenantScoped: true },\n );\n } catch (error) {\n this.emit('runner:error', error as Error);\n return;\n }\n\n // A full batch may leave more overdue rows: sweep again next poll.\n if (unclaimed.length >= HANDLER_UNCLAIMED_SWEEP_LIMIT) {\n this.lastUnclaimedSweepAt = 0;\n }\n const sweptAt = new Date();\n for (const job of unclaimed) {\n const snapshot = terminalSnapshot(job);\n if (!snapshot) continue;\n const lastError = `Job handler not claimed: no runner registered for ${jobHandlerName(job.objectType)} claimed this job within ${deadlineMs} ms of its run_at.`;\n let event: SmrtJobEvent | null;\n try {\n event = await transitionTerminalJob(this.db, {\n job: snapshot,\n status: 'failed',\n completedAt: sweptAt,\n expectedStatuses: ['pending'],\n expectedRunAtAtOrBefore: cutoff,\n clearWorker: true,\n lastError,\n failureKind: 'handler-unclaimed',\n });\n } catch (error) {\n this.emit('runner:error', error as Error);\n continue;\n }\n if (!event) continue;\n job.status = 'failed';\n job.completedAt = sweptAt;\n job.lastError = lastError;\n this.emitPersistedJobEvent(job, event);\n this.emit('job:unclaimed', job, new Error(lastError));\n }\n }\n\n /**\n * Renew this worker's liveness lease.\n *\n * In Stage 1 this runs on the main event loop, so it provides cross-process\n * detection no weaker than the old per-job heartbeat. Stage 2 moves the\n * renewal to an off-loop worker thread so a synchronous handler can no longer\n * starve it. Same-process correctness never depends on this timer — the\n * in-memory live set covers it.\n */\n private startLeaseRenewal(): void {\n this.leaseTimer = setInterval(async () => {\n try {\n await this.workerCollection?.renewLease(\n this.workerKey,\n this.effectiveLeaseTtlMs,\n this.config.queues,\n );\n } catch {\n // Ignore transient lease-renewal errors; the next tick retries.\n }\n }, this.config.leaseTickMs);\n }\n\n /**\n * Spawn the off-loop liveness thread. It opens its own connection and renews\n * this worker's lease on its own thread (unstarvable by handler CPU). Returns\n * false if the thread can't be resolved or fails to start, so the caller can\n * fall back to main-loop renewal.\n */\n private async startLivenessThread(\n plan: Exclude<LivenessConnectionPlan, { kind: 'none' }>,\n ): Promise<{ ok: true } | { ok: false; reason: string }> {\n if (!this.db) return { ok: false, reason: 'no database' };\n let entry: string;\n try {\n // Resolve by package subpath, not as a sibling of this module: the bundle\n // hoists `runner` into dist/chunks/, so a relative URL would miss.\n entry = (\n import.meta as unknown as { resolve(s: string): string }\n ).resolve('@happyvertical/smrt-jobs/worker-liveness-thread');\n } catch (error) {\n return {\n ok: false,\n reason: `worker entry not resolvable: ${errorText(error)}`,\n };\n }\n\n let worker: Worker;\n try {\n worker = new Worker(new URL(entry), {\n workerData: {\n ...(plan.kind === 'reopen'\n ? {\n url: '',\n reopen: plan.reopen,\n expectedEngine: plan.engine,\n }\n : { url: plan.url, type: plan.type }),\n workerKey: this.workerKey,\n leaseTtlMs: this.effectiveLeaseTtlMs,\n leaseTickMs: this.config.leaseTickMs,\n queues: this.config.queues,\n },\n });\n } catch (error) {\n return {\n ok: false,\n reason: `worker could not be spawned: ${errorText(error)}`,\n };\n }\n const exited = new Promise<void>((resolve) => {\n worker.once('exit', () => resolve());\n });\n\n // Bound the handshake so a hung connect inside the thread (slow/unreachable\n // database) can't stall start() forever — fall back to main-loop renewal.\n let failure = 'thread exited before it was ready';\n const handshake = await new Promise<'ready' | 'failed' | 'timeout'>(\n (resolve) => {\n const onMessage = (message: unknown) => {\n if (message === 'ready') {\n cleanup();\n resolve('ready');\n } else if (\n message &&\n typeof message === 'object' &&\n (message as { type?: string }).type === 'error'\n ) {\n failure = String((message as { message?: unknown }).message);\n cleanup();\n resolve('failed');\n }\n };\n const onFail = (error?: unknown) => {\n if (error instanceof Error) failure = error.message;\n cleanup();\n resolve('failed');\n };\n const cleanup = () => {\n clearTimeout(timer);\n worker.off('message', onMessage);\n worker.off('error', onFail);\n worker.off('exit', onFail);\n };\n const timer = setTimeout(() => {\n cleanup();\n resolve('timeout');\n }, LIVENESS_THREAD_START_TIMEOUT_MS);\n if (typeof timer.unref === 'function') timer.unref();\n worker.on('message', onMessage);\n worker.once('error', onFail);\n worker.once('exit', onFail);\n },\n );\n\n if (handshake === 'timeout') {\n // A hung thread will not exit on its own; terminating is the last resort.\n await worker.terminate().catch(() => {});\n return {\n ok: false,\n reason: `no ready signal within ${LIVENESS_THREAD_START_TIMEOUT_MS} ms`,\n };\n }\n if (handshake === 'failed') {\n // A failed startup leaves the thread nothing to wait on: it exits.\n await retireLivenessWorker(worker, exited);\n return { ok: false, reason: failure };\n }\n\n this.livenessWorker = worker;\n this.livenessWorkerExited = exited;\n // Don't keep the process alive on the liveness thread alone.\n worker.unref();\n // If the thread dies while we're still running, fall back to main-loop\n // renewal so the lease keeps being renewed.\n worker.once('error', () => this.handleLivenessThreadLoss(worker));\n worker.once('exit', () => this.handleLivenessThreadLoss(worker));\n return { ok: true };\n }\n\n private handleLivenessThreadLoss(worker: Worker): void {\n if (this.livenessWorker !== worker) return;\n this.livenessWorker = null;\n this.livenessWorkerExited = null;\n if (this.running && !this.leaseTimer) {\n this.startLeaseRenewal();\n }\n }\n\n /**\n * Stop the liveness thread, if running: ask it to stop, then let it exit on\n * its own (bounded; terminated only if it does not, see\n * {@link retireLivenessWorker}).\n */\n private async stopLivenessThread(): Promise<void> {\n const worker = this.livenessWorker;\n const exited = this.livenessWorkerExited;\n if (!worker || !exited) return;\n this.livenessWorker = null;\n this.livenessWorkerExited = null;\n\n try {\n // The worker may have already exited (it's unref'd and best-effort);\n // postMessage to a dead worker throws ERR_WORKER_NOT_RUNNING.\n worker.postMessage('stop');\n } catch {\n // Nothing to ask it to do; the exit wait below returns at once.\n }\n await retireLivenessWorker(worker, exited);\n }\n\n /**\n * Per-job heartbeat loop — telemetry only (\"last activity\" for the UI). It no\n * longer gates recovery (that is the worker lease), so a blocked loop missing\n * a heartbeat is harmless.\n */\n private startHeartbeat(): void {\n this.heartbeatTimer = setInterval(async () => {\n if (!this.db) return;\n const jobIds = [...this.activeJobs.keys()];\n if (jobIds.length === 0) return;\n const placeholders = jobIds.map(() => '?').join(', ');\n try {\n await this.db.query(\n `UPDATE _smrt_jobs\n SET worker_heartbeat = ?\n WHERE status = 'running'\n AND id IN (${placeholders})`,\n new Date().toISOString(),\n ...jobIds,\n );\n } catch {\n // Telemetry is best-effort.\n }\n }, this.config.heartbeatInterval);\n }\n\n /**\n * Wait for active jobs to complete with timeout\n */\n private async waitForActiveJobs(): Promise<void> {\n // A claim is not in activeJobs yet. Keep the lease while it drains, using\n // the same shutdown deadline as handlers rather than an unbounded await.\n if (this.activeJobs.size === 0 && !this.pollPromise) return;\n\n return new Promise((resolve) => {\n const checkInterval = setInterval(() => {\n if (this.activeJobs.size === 0 && !this.pollPromise) {\n clearInterval(checkInterval);\n clearTimeout(timeout);\n resolve();\n }\n }, 100);\n\n const timeout = setTimeout(() => {\n clearInterval(checkInterval);\n this.logger.warn(\n `Shutdown timeout: ${this.activeJobs.size} jobs still active`,\n );\n resolve();\n }, this.config.shutdownTimeout);\n });\n }\n}\n\n/**\n * Create a TaskRunner instance\n */\nexport function createTaskRunner(config?: TaskRunnerConfig): TaskRunner {\n return new TaskRunner(config);\n}\n\nexport default TaskRunner;\n"],"mappings":";;;;;;;;;;AAOA,eAAe,wBAAwB,KAAK,MAAM,05pDAA463D,CAAC;;;ACwBx93D,IAAM,kBAAkB;AAOxB,IAAM,yBAAyB;AAQ/B,SAAS,aAAa,WAA2B;CACtD,IAAI,OAAO,MAAM,SAAS,KAAK,YAAY,GACzC,OAAO;CAET,IAAI,cAAc,OAAO,mBACvB,OAAA;CAEF,OAAO,KAAK,IAAI,KAAK,MAAM,SAAS,GAAA,EAAkB;AACxD;AAKO,IAAM,4BAAN,cAAwC,MAAM;CACnD,YACkB,UACA,KACA,SAChB;EACA,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;EAErD,OAAO,IAAI,SAAS,YAAY;GAC9B,MAAM,gBAAgB,kBAAkB;IACtC,IAAI,KAAK,WAAW,SAAS,KAAK,CAAC,KAAK,aAAa;KACnD,cAAc,aAAa;KAC3B,aAAa,OAAO;KACpB,QAAQ;IACV;GACF,GAAG,GAAG;GAEN,MAAM,UAAU,iBAAiB;IAC/B,cAAc,aAAa;IAC3B,KAAK,OAAO,KACV,qBAAqB,KAAK,WAAW,KAAI,mBAC3C;IACA,QAAQ;GACV,GAAG,KAAK,OAAO,eAAe;EAChC,CAAC;CACH;AACF;AAKO,SAAS,iBAAiB,QAAuC;CACtE,OAAO,IAAI,WAAW,MAAM;AAC9B"}
|
|
1
|
+
{"version":3,"file":"runner-fIHyIknP.js","names":["expression","tenantId","tenantId","jobId","job"],"sources":["../../src/__smrt-register__.ts","../../src/background-policy.ts","../../src/job-handlers.ts","../../src/smrt-job-dedupe-slot.ts","../../src/worker-liveness.ts","../../src/smrt-job-event.ts","../../src/terminal-outcome.ts","../../src/smrt-job.ts","../../src/retention.ts","../../src/error-redaction.ts","../../src/smrt-worker.ts","../../src/logger-extension.ts","../../src/mcp-task.ts","../../src/stale-recovery.ts","../../src/runner.ts"],"sourcesContent":["// Generated by @happyvertical/smrt-core smrtPlugin at library build time.\n// The package manifest is inlined so self-registration cannot miss when a\n// downstream bundler relocates this module away from dist/manifest.json\n// (https://github.com/happyvertical/smrt/issues/1506,\n// https://github.com/happyvertical/smrt/issues/1507).\nimport { ObjectRegistry } from '@happyvertical/smrt-core';\n\nObjectRegistry.registerPackageManifest(JSON.parse(\"{\\\"version\\\":\\\"1.0.0\\\",\\\"timestamp\\\":0,\\\"packageName\\\":\\\"@happyvertical/smrt-jobs\\\",\\\"packageVersion\\\":\\\"0.70.3\\\",\\\"objects\\\":{\\\"@happyvertical/smrt-jobs:SmrtJobEvent\\\":{\\\"name\\\":\\\"smrtjobevent\\\",\\\"className\\\":\\\"SmrtJobEvent\\\",\\\"qualifiedName\\\":\\\"@happyvertical/smrt-jobs:SmrtJobEvent\\\",\\\"collection\\\":\\\"smrtjobevents\\\",\\\"filePath\\\":\\\"src/smrt-job-event.ts\\\",\\\"packageName\\\":\\\"@happyvertical/smrt-jobs\\\",\\\"fields\\\":{\\\"tenantId\\\":{\\\"type\\\":\\\"text\\\",\\\"_meta\\\":{\\\"__tenancy\\\":{\\\"isTenantIdField\\\":true,\\\"autoFilter\\\":true,\\\"required\\\":false,\\\"autoPopulate\\\":true,\\\"nullable\\\":true,\\\"mode\\\":\\\"optional\\\",\\\"field\\\":\\\"tenantId\\\",\\\"allowSuperAdminBypass\\\":false},\\\"__statedOptions\\\":[\\\"sqlType\\\",\\\"nullable\\\",\\\"__tenancy\\\",\\\"required\\\"],\\\"sqlType\\\":\\\"UUID\\\",\\\"nullable\\\":true,\\\"required\\\":false},\\\"required\\\":false},\\\"jobId\\\":{\\\"type\\\":\\\"foreignKey\\\",\\\"_meta\\\":{\\\"__statedOptions\\\":[\\\"required\\\",\\\"requiredFor\\\",\\\"constraint\\\",\\\"related\\\"],\\\"required\\\":true,\\\"requiredFor\\\":\\\"identity\\\",\\\"constraint\\\":false},\\\"required\\\":true,\\\"related\\\":\\\"SmrtJob\\\"},\\\"type\\\":{\\\"type\\\":\\\"text\\\",\\\"_meta\\\":{\\\"__statedOptions\\\":[\\\"required\\\",\\\"default\\\"],\\\"required\\\":true,\\\"default\\\":\\\"log\\\"},\\\"required\\\":true,\\\"default\\\":\\\"log\\\"},\\\"level\\\":{\\\"type\\\":\\\"text\\\",\\\"_meta\\\":{\\\"__statedOptions\\\":[\\\"required\\\",\\\"default\\\",\\\"enum\\\"],\\\"required\\\":true,\\\"default\\\":\\\"info\\\"},\\\"required\\\":true,\\\"default\\\":\\\"info\\\",\\\"enum\\\":[\\\"debug\\\",\\\"info\\\",\\\"warn\\\",\\\"error\\\"]},\\\"stage\\\":{\\\"type\\\":\\\"text\\\",\\\"_meta\\\":{\\\"__statedOptions\\\":[\\\"nullable\\\",\\\"required\\\"],\\\"nullable\\\":true,\\\"required\\\":false},\\\"required\\\":false},\\\"progress\\\":{\\\"type\\\":\\\"integer\\\",\\\"_meta\\\":{\\\"__statedOptions\\\":[\\\"nullable\\\",\\\"required\\\"],\\\"nullable\\\":true,\\\"required\\\":false},\\\"required\\\":false},\\\"message\\\":{\\\"type\\\":\\\"text\\\",\\\"_meta\\\":{\\\"__statedOptions\\\":[\\\"default\\\"],\\\"default\\\":\\\"\\\"},\\\"required\\\":false,\\\"default\\\":\\\"\\\"},\\\"data\\\":{\\\"type\\\":\\\"json\\\",\\\"_meta\\\":{\\\"__statedOptions\\\":[]},\\\"required\\\":false},\\\"createdAt\\\":{\\\"type\\\":\\\"datetime\\\",\\\"_meta\\\":{\\\"__statedOptions\\\":[\\\"required\\\"],\\\"required\\\":true},\\\"required\\\":true}},\\\"methods\\\":{\\\"toCursor\\\":{\\\"name\\\":\\\"toCursor\\\",\\\"async\\\":false,\\\"parameters\\\":[],\\\"returnType\\\":\\\"string\\\",\\\"isStatic\\\":false,\\\"isPublic\\\":true}},\\\"decoratorConfig\\\":{\\\"tableName\\\":\\\"_smrt_job_events\\\",\\\"api\\\":false,\\\"cli\\\":{\\\"include\\\":[\\\"list\\\",\\\"get\\\"],\\\"http\\\":false,\\\"skipApiCheck\\\":true},\\\"mcp\\\":false,\\\"tenantScoped\\\":{\\\"mode\\\":\\\"optional\\\"},\\\"conflictColumns\\\":[\\\"tenant_id\\\",\\\"slug\\\",\\\"context\\\"]},\\\"extends\\\":\\\"SmrtObject\\\",\\\"exportName\\\":\\\"SmrtJobEvent\\\",\\\"collectionExportName\\\":\\\"SmrtJobEventCollection\\\",\\\"validationRules\\\":[{\\\"field\\\":\\\"jobId\\\",\\\"rule\\\":\\\"required\\\",\\\"fieldType\\\":\\\"foreignKey\\\"},{\\\"field\\\":\\\"type\\\",\\\"rule\\\":\\\"required\\\",\\\"fieldType\\\":\\\"text\\\"},{\\\"field\\\":\\\"level\\\",\\\"rule\\\":\\\"required\\\",\\\"fieldType\\\":\\\"text\\\"},{\\\"field\\\":\\\"createdAt\\\",\\\"rule\\\":\\\"required\\\",\\\"fieldType\\\":\\\"datetime\\\"}],\\\"schema\\\":{\\\"tableName\\\":\\\"_smrt_job_events\\\",\\\"ddl\\\":\\\"CREATE TABLE IF NOT EXISTS \\\\\\\"_smrt_job_events\\\\\\\" (\\\\n \\\\\\\"_sync_origin_device_id\\\\\\\" TEXT,\\\\n \\\\\\\"_sync_revision\\\\\\\" INTEGER,\\\\n \\\\\\\"id\\\\\\\" UUID PRIMARY KEY NOT NULL,\\\\n \\\\\\\"slug\\\\\\\" TEXT NOT NULL,\\\\n \\\\\\\"context\\\\\\\" TEXT NOT NULL DEFAULT '',\\\\n \\\\\\\"created_at\\\\\\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\\\n \\\\\\\"updated_at\\\\\\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\\\n \\\\\\\"tenant_id\\\\\\\" UUID,\\\\n \\\\\\\"job_id\\\\\\\" UUID NOT NULL,\\\\n \\\\\\\"type\\\\\\\" TEXT NOT NULL DEFAULT 'log',\\\\n \\\\\\\"level\\\\\\\" TEXT NOT NULL DEFAULT 'info',\\\\n \\\\\\\"stage\\\\\\\" TEXT,\\\\n \\\\\\\"progress\\\\\\\" INTEGER,\\\\n \\\\\\\"message\\\\\\\" TEXT DEFAULT '',\\\\n \\\\\\\"data\\\\\\\" JSON\\\\n);\\\",\\\"columns\\\":{\\\"_sync_origin_device_id\\\":{\\\"type\\\":\\\"TEXT\\\"},\\\"_sync_revision\\\":{\\\"type\\\":\\\"INTEGER\\\"},\\\"id\\\":{\\\"type\\\":\\\"UUID\\\",\\\"primaryKey\\\":true,\\\"referenceKind\\\":\\\"id\\\",\\\"notNull\\\":true},\\\"slug\\\":{\\\"type\\\":\\\"TEXT\\\",\\\"notNull\\\":true},\\\"context\\\":{\\\"type\\\":\\\"TEXT\\\",\\\"notNull\\\":true,\\\"default\\\":\\\"\\\"},\\\"created_at\\\":{\\\"type\\\":\\\"TIMESTAMP\\\",\\\"notNull\\\":true,\\\"default\\\":\\\"current_timestamp\\\"},\\\"updated_at\\\":{\\\"type\\\":\\\"TIMESTAMP\\\",\\\"notNull\\\":true,\\\"default\\\":\\\"current_timestamp\\\"},\\\"tenant_id\\\":{\\\"type\\\":\\\"UUID\\\",\\\"referenceKind\\\":\\\"tenantId\\\",\\\"notNull\\\":false,\\\"unique\\\":false},\\\"job_id\\\":{\\\"type\\\":\\\"UUID\\\",\\\"referenceKind\\\":\\\"foreignKey\\\",\\\"notNull\\\":true,\\\"unique\\\":false},\\\"type\\\":{\\\"type\\\":\\\"TEXT\\\",\\\"notNull\\\":true,\\\"unique\\\":false,\\\"default\\\":\\\"log\\\"},\\\"level\\\":{\\\"type\\\":\\\"TEXT\\\",\\\"notNull\\\":true,\\\"unique\\\":false,\\\"default\\\":\\\"info\\\"},\\\"stage\\\":{\\\"type\\\":\\\"TEXT\\\",\\\"notNull\\\":false,\\\"unique\\\":false},\\\"progress\\\":{\\\"type\\\":\\\"INTEGER\\\",\\\"notNull\\\":false,\\\"unique\\\":false},\\\"message\\\":{\\\"type\\\":\\\"TEXT\\\",\\\"notNull\\\":false,\\\"unique\\\":false,\\\"default\\\":\\\"\\\"},\\\"data\\\":{\\\"type\\\":\\\"JSON\\\",\\\"notNull\\\":false,\\\"unique\\\":false}},\\\"indexes\\\":[{\\\"name\\\":\\\"_smrt_job_events_slug_context_idx\\\",\\\"columns\\\":[\\\"tenant_id\\\",\\\"slug\\\",\\\"context\\\"],\\\"unique\\\":true,\\\"nullsNotDistinct\\\":true},{\\\"name\\\":\\\"_smrt_job_events_tenant_id_created_at_idx\\\",\\\"columns\\\":[\\\"tenant_id\\\",\\\"created_at\\\"]},{\\\"name\\\":\\\"_smrt_job_events_job_id_idx\\\",\\\"columns\\\":[\\\"job_id\\\"]}],\\\"version\\\":\\\"8645e1da\\\"},\\\"importPath\\\":\\\"@happyvertical/smrt-jobs\\\"},\\\"@happyvertical/smrt-jobs:ForgeDelivery\\\":{\\\"name\\\":\\\"forgedelivery\\\",\\\"className\\\":\\\"ForgeDelivery\\\",\\\"qualifiedName\\\":\\\"@happyvertical/smrt-jobs:ForgeDelivery\\\",\\\"collection\\\":\\\"forgedeliveries\\\",\\\"filePath\\\":\\\"src/forge-projection.ts\\\",\\\"packageName\\\":\\\"@happyvertical/smrt-jobs\\\",\\\"fields\\\":{\\\"tenantId\\\":{\\\"type\\\":\\\"text\\\",\\\"_meta\\\":{\\\"__tenancy\\\":{\\\"isTenantIdField\\\":true,\\\"autoFilter\\\":true,\\\"required\\\":true,\\\"autoPopulate\\\":true,\\\"nullable\\\":false,\\\"mode\\\":\\\"required\\\",\\\"field\\\":\\\"tenantId\\\",\\\"allowSuperAdminBypass\\\":false},\\\"__statedOptions\\\":[\\\"sqlType\\\",\\\"requiredFor\\\",\\\"__tenancy\\\"],\\\"sqlType\\\":\\\"UUID\\\",\\\"requiredFor\\\":\\\"tenant-scope\\\"},\\\"required\\\":true},\\\"provider\\\":{\\\"type\\\":\\\"text\\\",\\\"_meta\\\":{\\\"__statedOptions\\\":[\\\"required\\\",\\\"requiredFor\\\"],\\\"required\\\":true,\\\"requiredFor\\\":\\\"identity\\\"},\\\"required\\\":true},\\\"deliveryId\\\":{\\\"type\\\":\\\"text\\\",\\\"_meta\\\":{\\\"__statedOptions\\\":[\\\"required\\\",\\\"requiredFor\\\"],\\\"required\\\":true,\\\"requiredFor\\\":\\\"identity\\\"},\\\"required\\\":true},\\\"installationKey\\\":{\\\"type\\\":\\\"text\\\",\\\"_meta\\\":{\\\"__statedOptions\\\":[\\\"nullable\\\",\\\"required\\\"],\\\"nullable\\\":true,\\\"required\\\":false},\\\"required\\\":false},\\\"repositoryKey\\\":{\\\"type\\\":\\\"text\\\",\\\"_meta\\\":{\\\"__statedOptions\\\":[\\\"nullable\\\",\\\"required\\\"],\\\"nullable\\\":true,\\\"required\\\":false},\\\"required\\\":false},\\\"eventName\\\":{\\\"type\\\":\\\"text\\\",\\\"_meta\\\":{\\\"__statedOptions\\\":[]},\\\"required\\\":false},\\\"payload\\\":{\\\"type\\\":\\\"json\\\",\\\"_meta\\\":{\\\"__statedOptions\\\":[]},\\\"required\\\":false},\\\"status\\\":{\\\"type\\\":\\\"text\\\",\\\"_meta\\\":{\\\"__statedOptions\\\":[\\\"required\\\",\\\"default\\\",\\\"enum\\\"],\\\"required\\\":true,\\\"default\\\":\\\"pending\\\"},\\\"required\\\":true,\\\"default\\\":\\\"pending\\\",\\\"enum\\\":[\\\"pending\\\",\\\"leased\\\",\\\"retry\\\",\\\"completed\\\",\\\"dead_letter\\\"]},\\\"attempts\\\":{\\\"type\\\":\\\"integer\\\",\\\"_meta\\\":{\\\"__statedOptions\\\":[\\\"required\\\",\\\"default\\\"],\\\"required\\\":true,\\\"default\\\":0},\\\"required\\\":true,\\\"default\\\":0},\\\"maxAttempts\\\":{\\\"type\\\":\\\"integer\\\",\\\"_meta\\\":{\\\"__statedOptions\\\":[\\\"required\\\",\\\"default\\\"],\\\"required\\\":true,\\\"default\\\":5},\\\"required\\\":true,\\\"default\\\":5},\\\"receivedAt\\\":{\\\"type\\\":\\\"datetime\\\",\\\"_meta\\\":{\\\"__statedOptions\\\":[\\\"required\\\"],\\\"required\\\":true},\\\"required\\\":true},\\\"nextAttemptAt\\\":{\\\"type\\\":\\\"datetime\\\",\\\"_meta\\\":{\\\"__statedOptions\\\":[\\\"required\\\"],\\\"required\\\":true},\\\"required\\\":true},\\\"leaseOwner\\\":{\\\"type\\\":\\\"text\\\",\\\"_meta\\\":{\\\"__statedOptions\\\":[\\\"nullable\\\",\\\"required\\\"],\\\"nullable\\\":true,\\\"required\\\":false},\\\"required\\\":false},\\\"leaseToken\\\":{\\\"type\\\":\\\"text\\\",\\\"_meta\\\":{\\\"__statedOptions\\\":[\\\"nullable\\\",\\\"required\\\"],\\\"nullable\\\":true,\\\"required\\\":false},\\\"required\\\":false},\\\"leaseExpiresAt\\\":{\\\"type\\\":\\\"datetime\\\",\\\"_meta\\\":{\\\"__statedOptions\\\":[\\\"nullable\\\",\\\"required\\\"],\\\"nullable\\\":true,\\\"required\\\":false},\\\"required\\\":false},\\\"lastError\\\":{\\\"type\\\":\\\"text\\\",\\\"_meta\\\":{\\\"__statedOptions\\\":[\\\"nullable\\\",\\\"required\\\"],\\\"nullable\\\":true,\\\"required\\\":false},\\\"required\\\":false},\\\"completedAt\\\":{\\\"type\\\":\\\"datetime\\\",\\\"_meta\\\":{\\\"__statedOptions\\\":[\\\"nullable\\\",\\\"required\\\"],\\\"nullable\\\":true,\\\"required\\\":false},\\\"required\\\":false},\\\"replayCount\\\":{\\\"type\\\":\\\"integer\\\",\\\"_meta\\\":{\\\"__statedOptions\\\":[\\\"required\\\",\\\"default\\\"],\\\"required\\\":true,\\\"default\\\":0},\\\"required\\\":true,\\\"default\\\":0}},\\\"methods\\\":{},\\\"decoratorConfig\\\":{\\\"tableName\\\":\\\"_smrt_forge_deliveries\\\",\\\"conflictColumns\\\":[\\\"tenant_id\\\",\\\"provider\\\",\\\"delivery_id\\\"],\\\"api\\\":false,\\\"cli\\\":false,\\\"mcp\\\":false,\\\"indexes\\\":[{\\\"name\\\":\\\"_smrt_forge_deliveries_status_next_attempt_at_idx\\\",\\\"columns\\\":[\\\"status\\\",\\\"nextAttemptAt\\\"]},{\\\"name\\\":\\\"_smrt_forge_deliveries_status_lease_expires_at_idx\\\",\\\"columns\\\":[\\\"status\\\",\\\"leaseExpiresAt\\\"]}],\\\"tenantScoped\\\":{\\\"mode\\\":\\\"required\\\"}},\\\"extends\\\":\\\"SmrtObject\\\",\\\"exportName\\\":\\\"ForgeDelivery\\\",\\\"collectionExportName\\\":\\\"ForgeDeliveryCollection\\\",\\\"validationRules\\\":[{\\\"field\\\":\\\"provider\\\",\\\"rule\\\":\\\"required\\\",\\\"fieldType\\\":\\\"text\\\"},{\\\"field\\\":\\\"deliveryId\\\",\\\"rule\\\":\\\"required\\\",\\\"fieldType\\\":\\\"text\\\"},{\\\"field\\\":\\\"status\\\",\\\"rule\\\":\\\"required\\\",\\\"fieldType\\\":\\\"text\\\"},{\\\"field\\\":\\\"attempts\\\",\\\"rule\\\":\\\"required\\\",\\\"fieldType\\\":\\\"integer\\\"},{\\\"field\\\":\\\"maxAttempts\\\",\\\"rule\\\":\\\"required\\\",\\\"fieldType\\\":\\\"integer\\\"},{\\\"field\\\":\\\"receivedAt\\\",\\\"rule\\\":\\\"required\\\",\\\"fieldType\\\":\\\"datetime\\\"},{\\\"field\\\":\\\"nextAttemptAt\\\",\\\"rule\\\":\\\"required\\\",\\\"fieldType\\\":\\\"datetime\\\"},{\\\"field\\\":\\\"replayCount\\\",\\\"rule\\\":\\\"required\\\",\\\"fieldType\\\":\\\"integer\\\"}],\\\"schema\\\":{\\\"tableName\\\":\\\"_smrt_forge_deliveries\\\",\\\"ddl\\\":\\\"CREATE TABLE IF NOT EXISTS \\\\\\\"_smrt_forge_deliveries\\\\\\\" (\\\\n \\\\\\\"_sync_origin_device_id\\\\\\\" TEXT,\\\\n \\\\\\\"_sync_revision\\\\\\\" INTEGER,\\\\n \\\\\\\"id\\\\\\\" UUID PRIMARY KEY NOT NULL,\\\\n \\\\\\\"slug\\\\\\\" TEXT NOT NULL,\\\\n \\\\\\\"context\\\\\\\" TEXT NOT NULL DEFAULT '',\\\\n \\\\\\\"created_at\\\\\\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\\\n \\\\\\\"updated_at\\\\\\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\\\n \\\\\\\"tenant_id\\\\\\\" UUID NOT NULL,\\\\n \\\\\\\"provider\\\\\\\" TEXT NOT NULL,\\\\n \\\\\\\"delivery_id\\\\\\\" TEXT NOT NULL,\\\\n \\\\\\\"installation_key\\\\\\\" TEXT,\\\\n \\\\\\\"repository_key\\\\\\\" TEXT,\\\\n \\\\\\\"event_name\\\\\\\" TEXT,\\\\n \\\\\\\"payload\\\\\\\" JSON,\\\\n \\\\\\\"status\\\\\\\" TEXT NOT NULL DEFAULT 'pending',\\\\n \\\\\\\"attempts\\\\\\\" INTEGER NOT NULL DEFAULT 0,\\\\n \\\\\\\"max_attempts\\\\\\\" INTEGER NOT NULL DEFAULT 5,\\\\n \\\\\\\"received_at\\\\\\\" TIMESTAMP NOT NULL,\\\\n \\\\\\\"next_attempt_at\\\\\\\" TIMESTAMP NOT NULL,\\\\n \\\\\\\"lease_owner\\\\\\\" TEXT,\\\\n \\\\\\\"lease_token\\\\\\\" TEXT,\\\\n \\\\\\\"lease_expires_at\\\\\\\" TIMESTAMP,\\\\n \\\\\\\"last_error\\\\\\\" TEXT,\\\\n \\\\\\\"completed_at\\\\\\\" TIMESTAMP,\\\\n \\\\\\\"replay_count\\\\\\\" INTEGER NOT NULL DEFAULT 0\\\\n);\\\",\\\"columns\\\":{\\\"_sync_origin_device_id\\\":{\\\"type\\\":\\\"TEXT\\\"},\\\"_sync_revision\\\":{\\\"type\\\":\\\"INTEGER\\\"},\\\"id\\\":{\\\"type\\\":\\\"UUID\\\",\\\"primaryKey\\\":true,\\\"referenceKind\\\":\\\"id\\\",\\\"notNull\\\":true},\\\"slug\\\":{\\\"type\\\":\\\"TEXT\\\",\\\"notNull\\\":true},\\\"context\\\":{\\\"type\\\":\\\"TEXT\\\",\\\"notNull\\\":true,\\\"default\\\":\\\"\\\"},\\\"created_at\\\":{\\\"type\\\":\\\"TIMESTAMP\\\",\\\"notNull\\\":true,\\\"default\\\":\\\"current_timestamp\\\"},\\\"updated_at\\\":{\\\"type\\\":\\\"TIMESTAMP\\\",\\\"notNull\\\":true,\\\"default\\\":\\\"current_timestamp\\\"},\\\"tenant_id\\\":{\\\"type\\\":\\\"UUID\\\",\\\"referenceKind\\\":\\\"tenantId\\\",\\\"notNull\\\":true,\\\"unique\\\":false},\\\"provider\\\":{\\\"type\\\":\\\"TEXT\\\",\\\"notNull\\\":true,\\\"unique\\\":false},\\\"delivery_id\\\":{\\\"type\\\":\\\"TEXT\\\",\\\"notNull\\\":true,\\\"unique\\\":false},\\\"installation_key\\\":{\\\"type\\\":\\\"TEXT\\\",\\\"notNull\\\":false,\\\"unique\\\":false},\\\"repository_key\\\":{\\\"type\\\":\\\"TEXT\\\",\\\"notNull\\\":false,\\\"unique\\\":false},\\\"event_name\\\":{\\\"type\\\":\\\"TEXT\\\",\\\"notNull\\\":false,\\\"unique\\\":false},\\\"payload\\\":{\\\"type\\\":\\\"JSON\\\",\\\"notNull\\\":false,\\\"unique\\\":false},\\\"status\\\":{\\\"type\\\":\\\"TEXT\\\",\\\"notNull\\\":true,\\\"unique\\\":false,\\\"default\\\":\\\"pending\\\"},\\\"attempts\\\":{\\\"type\\\":\\\"INTEGER\\\",\\\"notNull\\\":true,\\\"unique\\\":false,\\\"default\\\":0},\\\"max_attempts\\\":{\\\"type\\\":\\\"INTEGER\\\",\\\"notNull\\\":true,\\\"unique\\\":false,\\\"default\\\":5},\\\"received_at\\\":{\\\"type\\\":\\\"TIMESTAMP\\\",\\\"notNull\\\":true,\\\"unique\\\":false},\\\"next_attempt_at\\\":{\\\"type\\\":\\\"TIMESTAMP\\\",\\\"notNull\\\":true,\\\"unique\\\":false},\\\"lease_owner\\\":{\\\"type\\\":\\\"TEXT\\\",\\\"notNull\\\":false,\\\"unique\\\":false},\\\"lease_token\\\":{\\\"type\\\":\\\"TEXT\\\",\\\"notNull\\\":false,\\\"unique\\\":false},\\\"lease_expires_at\\\":{\\\"type\\\":\\\"TIMESTAMP\\\",\\\"notNull\\\":false,\\\"unique\\\":false},\\\"last_error\\\":{\\\"type\\\":\\\"TEXT\\\",\\\"notNull\\\":false,\\\"unique\\\":false},\\\"completed_at\\\":{\\\"type\\\":\\\"TIMESTAMP\\\",\\\"notNull\\\":false,\\\"unique\\\":false},\\\"replay_count\\\":{\\\"type\\\":\\\"INTEGER\\\",\\\"notNull\\\":true,\\\"unique\\\":false,\\\"default\\\":0}},\\\"indexes\\\":[{\\\"name\\\":\\\"_smrt_forge_deliveries_tenant_id_provider_idx\\\",\\\"columns\\\":[\\\"tenant_id\\\",\\\"provider\\\",\\\"delivery_id\\\"],\\\"unique\\\":true},{\\\"name\\\":\\\"_smrt_forge_deliveries_slug_context_idx\\\",\\\"columns\\\":[\\\"slug\\\",\\\"context\\\"]},{\\\"name\\\":\\\"_smrt_forge_deliveries_status_next_attempt_at_idx\\\",\\\"columns\\\":[\\\"status\\\",\\\"next_attempt_at\\\"]},{\\\"name\\\":\\\"_smrt_forge_deliveries_status_lease_expires_at_idx\\\",\\\"columns\\\":[\\\"status\\\",\\\"lease_expires_at\\\"]},{\\\"name\\\":\\\"_smrt_forge_deliveries_tenant_id_created_at_idx\\\",\\\"columns\\\":[\\\"tenant_id\\\",\\\"created_at\\\"]}],\\\"version\\\":\\\"870ae64b\\\"},\\\"importPath\\\":\\\"@happyvertical/smrt-jobs\\\"},\\\"@happyvertical/smrt-jobs:ForgeProjectionCheckpoint\\\":{\\\"name\\\":\\\"forgeprojectioncheckpoint\\\",\\\"className\\\":\\\"ForgeProjectionCheckpoint\\\",\\\"qualifiedName\\\":\\\"@happyvertical/smrt-jobs:ForgeProjectionCheckpoint\\\",\\\"collection\\\":\\\"forgeprojectioncheckpoints\\\",\\\"filePath\\\":\\\"src/forge-projection.ts\\\",\\\"packageName\\\":\\\"@happyvertical/smrt-jobs\\\",\\\"fields\\\":{\\\"tenantId\\\":{\\\"type\\\":\\\"text\\\",\\\"_meta\\\":{\\\"__tenancy\\\":{\\\"isTenantIdField\\\":true,\\\"autoFilter\\\":true,\\\"required\\\":true,\\\"autoPopulate\\\":true,\\\"nullable\\\":false,\\\"mode\\\":\\\"required\\\",\\\"field\\\":\\\"tenantId\\\",\\\"allowSuperAdminBypass\\\":false},\\\"__statedOptions\\\":[\\\"sqlType\\\",\\\"requiredFor\\\",\\\"__tenancy\\\"],\\\"sqlType\\\":\\\"UUID\\\",\\\"requiredFor\\\":\\\"tenant-scope\\\"},\\\"required\\\":true},\\\"projection\\\":{\\\"type\\\":\\\"text\\\",\\\"_meta\\\":{\\\"__statedOptions\\\":[\\\"required\\\",\\\"requiredFor\\\"],\\\"required\\\":true,\\\"requiredFor\\\":\\\"identity\\\"},\\\"required\\\":true},\\\"subjectKey\\\":{\\\"type\\\":\\\"text\\\",\\\"_meta\\\":{\\\"__statedOptions\\\":[\\\"required\\\",\\\"requiredFor\\\"],\\\"required\\\":true,\\\"requiredFor\\\":\\\"identity\\\"},\\\"required\\\":true},\\\"observationVersion\\\":{\\\"type\\\":\\\"integer\\\",\\\"_meta\\\":{\\\"__statedOptions\\\":[\\\"required\\\"],\\\"required\\\":true},\\\"required\\\":true},\\\"deliveryId\\\":{\\\"type\\\":\\\"text\\\",\\\"_meta\\\":{\\\"__statedOptions\\\":[]},\\\"required\\\":false},\\\"observedAt\\\":{\\\"type\\\":\\\"datetime\\\",\\\"_meta\\\":{\\\"__statedOptions\\\":[\\\"required\\\"],\\\"required\\\":true},\\\"required\\\":true}},\\\"methods\\\":{},\\\"decoratorConfig\\\":{\\\"tableName\\\":\\\"_smrt_forge_projection_checkpoints\\\",\\\"conflictColumns\\\":[\\\"tenant_id\\\",\\\"projection\\\",\\\"subject_key\\\"],\\\"api\\\":false,\\\"cli\\\":false,\\\"mcp\\\":false,\\\"tenantScoped\\\":{\\\"mode\\\":\\\"required\\\"}},\\\"extends\\\":\\\"SmrtObject\\\",\\\"exportName\\\":\\\"ForgeProjectionCheckpoint\\\",\\\"collectionExportName\\\":\\\"ForgeProjectionCheckpointCollection\\\",\\\"validationRules\\\":[{\\\"field\\\":\\\"projection\\\",\\\"rule\\\":\\\"required\\\",\\\"fieldType\\\":\\\"text\\\"},{\\\"field\\\":\\\"subjectKey\\\",\\\"rule\\\":\\\"required\\\",\\\"fieldType\\\":\\\"text\\\"},{\\\"field\\\":\\\"observationVersion\\\",\\\"rule\\\":\\\"required\\\",\\\"fieldType\\\":\\\"integer\\\"},{\\\"field\\\":\\\"observedAt\\\",\\\"rule\\\":\\\"required\\\",\\\"fieldType\\\":\\\"datetime\\\"}],\\\"schema\\\":{\\\"tableName\\\":\\\"_smrt_forge_projection_checkpoints\\\",\\\"ddl\\\":\\\"CREATE TABLE IF NOT EXISTS \\\\\\\"_smrt_forge_projection_checkpoints\\\\\\\" (\\\\n \\\\\\\"_sync_origin_device_id\\\\\\\" TEXT,\\\\n \\\\\\\"_sync_revision\\\\\\\" INTEGER,\\\\n \\\\\\\"id\\\\\\\" UUID PRIMARY KEY NOT NULL,\\\\n \\\\\\\"slug\\\\\\\" TEXT NOT NULL,\\\\n \\\\\\\"context\\\\\\\" TEXT NOT NULL DEFAULT '',\\\\n \\\\\\\"created_at\\\\\\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\\\n \\\\\\\"updated_at\\\\\\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\\\n \\\\\\\"tenant_id\\\\\\\" UUID NOT NULL,\\\\n \\\\\\\"projection\\\\\\\" TEXT NOT NULL,\\\\n \\\\\\\"subject_key\\\\\\\" TEXT NOT NULL,\\\\n \\\\\\\"observation_version\\\\\\\" INTEGER NOT NULL,\\\\n \\\\\\\"delivery_id\\\\\\\" TEXT,\\\\n \\\\\\\"observed_at\\\\\\\" TIMESTAMP NOT NULL\\\\n);\\\",\\\"columns\\\":{\\\"_sync_origin_device_id\\\":{\\\"type\\\":\\\"TEXT\\\"},\\\"_sync_revision\\\":{\\\"type\\\":\\\"INTEGER\\\"},\\\"id\\\":{\\\"type\\\":\\\"UUID\\\",\\\"primaryKey\\\":true,\\\"referenceKind\\\":\\\"id\\\",\\\"notNull\\\":true},\\\"slug\\\":{\\\"type\\\":\\\"TEXT\\\",\\\"notNull\\\":true},\\\"context\\\":{\\\"type\\\":\\\"TEXT\\\",\\\"notNull\\\":true,\\\"default\\\":\\\"\\\"},\\\"created_at\\\":{\\\"type\\\":\\\"TIMESTAMP\\\",\\\"notNull\\\":true,\\\"default\\\":\\\"current_timestamp\\\"},\\\"updated_at\\\":{\\\"type\\\":\\\"TIMESTAMP\\\",\\\"notNull\\\":true,\\\"default\\\":\\\"current_timestamp\\\"},\\\"tenant_id\\\":{\\\"type\\\":\\\"UUID\\\",\\\"referenceKind\\\":\\\"tenantId\\\",\\\"notNull\\\":true,\\\"unique\\\":false},\\\"projection\\\":{\\\"type\\\":\\\"TEXT\\\",\\\"notNull\\\":true,\\\"unique\\\":false},\\\"subject_key\\\":{\\\"type\\\":\\\"TEXT\\\",\\\"notNull\\\":true,\\\"unique\\\":false},\\\"observation_version\\\":{\\\"type\\\":\\\"INTEGER\\\",\\\"notNull\\\":true,\\\"unique\\\":false},\\\"delivery_id\\\":{\\\"type\\\":\\\"TEXT\\\",\\\"notNull\\\":false,\\\"unique\\\":false},\\\"observed_at\\\":{\\\"type\\\":\\\"TIMESTAMP\\\",\\\"notNull\\\":true,\\\"unique\\\":false}},\\\"indexes\\\":[{\\\"name\\\":\\\"_smrt_forge_projection_checkpoints_tenant_id_projection_idx\\\",\\\"columns\\\":[\\\"tenant_id\\\",\\\"projection\\\",\\\"subject_key\\\"],\\\"unique\\\":true},{\\\"name\\\":\\\"_smrt_forge_projection_checkpoints_slug_context_idx\\\",\\\"columns\\\":[\\\"slug\\\",\\\"context\\\"]},{\\\"name\\\":\\\"_smrt_forge_projection_checkpoints_tenant_id_created_at_idx\\\",\\\"columns\\\":[\\\"tenant_id\\\",\\\"created_at\\\"]}],\\\"version\\\":\\\"4493e9ae\\\"},\\\"importPath\\\":\\\"@happyvertical/smrt-jobs\\\"},\\\"@happyvertical/smrt-jobs:ForgeDeliveryCollection\\\":{\\\"name\\\":\\\"forgedeliverycollection\\\",\\\"className\\\":\\\"ForgeDeliveryCollection\\\",\\\"qualifiedName\\\":\\\"@happyvertical/smrt-jobs:ForgeDeliveryCollection\\\",\\\"collection\\\":\\\"forgedeliveries\\\",\\\"description\\\":\\\"Durable provider delivery inbox.\\\",\\\"filePath\\\":\\\"src/forge-projection.ts\\\",\\\"packageName\\\":\\\"@happyvertical/smrt-jobs\\\",\\\"fields\\\":{},\\\"methods\\\":{\\\"accept\\\":{\\\"name\\\":\\\"accept\\\",\\\"async\\\":true,\\\"parameters\\\":[{\\\"name\\\":\\\"input\\\",\\\"type\\\":\\\"AcceptForgeDeliveryInput\\\",\\\"optional\\\":false},{\\\"name\\\":\\\"audit\\\",\\\"type\\\":\\\"ForgeProjectionAuditHook\\\",\\\"optional\\\":true,\\\"resolvedType\\\":\\\"Function\\\"}],\\\"returnType\\\":\\\"Promise<AcceptedForgeDelivery>\\\",\\\"isStatic\\\":false,\\\"isPublic\\\":true},\\\"claimReady\\\":{\\\"name\\\":\\\"claimReady\\\",\\\"async\\\":true,\\\"parameters\\\":[{\\\"name\\\":\\\"options\\\",\\\"type\\\":\\\"ClaimForgeDeliveryOptions\\\",\\\"optional\\\":false},{\\\"name\\\":\\\"audit\\\",\\\"type\\\":\\\"ForgeProjectionAuditHook\\\",\\\"optional\\\":true,\\\"resolvedType\\\":\\\"Function\\\"}],\\\"returnType\\\":\\\"Promise<ForgeDelivery | null>\\\",\\\"isStatic\\\":false,\\\"isPublic\\\":true},\\\"replay\\\":{\\\"name\\\":\\\"replay\\\",\\\"async\\\":true,\\\"parameters\\\":[{\\\"name\\\":\\\"id\\\",\\\"type\\\":\\\"string\\\",\\\"optional\\\":false},{\\\"name\\\":\\\"audit\\\",\\\"type\\\":\\\"ForgeProjectionAuditHook\\\",\\\"optional\\\":true,\\\"resolvedType\\\":\\\"Function\\\"}],\\\"returnType\\\":\\\"Promise<boolean>\\\",\\\"isStatic\\\":false,\\\"isPublic\\\":true}},\\\"decoratorConfig\\\":{\\\"api\\\":false,\\\"cli\\\":false,\\\"mcp\\\":false,\\\"tableName\\\":\\\"_smrt_forge_deliveries\\\"},\\\"extends\\\":\\\"SmrtCollection\\\",\\\"extendsTypeArg\\\":\\\"ForgeDelivery\\\",\\\"exportName\\\":\\\"ForgeDeliveryCollection\\\",\\\"collectionExportName\\\":\\\"ForgeDeliveryCollectionCollection\\\",\\\"collectionOf\\\":\\\"@happyvertical/smrt-jobs:ForgeDelivery\\\",\\\"schema\\\":{\\\"tableName\\\":\\\"_smrt_forge_deliveries\\\",\\\"ddl\\\":\\\"CREATE TABLE IF NOT EXISTS \\\\\\\"_smrt_forge_deliveries\\\\\\\" (\\\\n \\\\\\\"_sync_origin_device_id\\\\\\\" TEXT,\\\\n \\\\\\\"_sync_revision\\\\\\\" INTEGER,\\\\n \\\\\\\"id\\\\\\\" UUID PRIMARY KEY NOT NULL,\\\\n \\\\\\\"slug\\\\\\\" TEXT NOT NULL,\\\\n \\\\\\\"context\\\\\\\" TEXT NOT NULL DEFAULT '',\\\\n \\\\\\\"created_at\\\\\\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\\\n \\\\\\\"updated_at\\\\\\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\\\n \\\\\\\"tenant_id\\\\\\\" UUID NOT NULL,\\\\n \\\\\\\"provider\\\\\\\" TEXT NOT NULL,\\\\n \\\\\\\"delivery_id\\\\\\\" TEXT NOT NULL,\\\\n \\\\\\\"installation_key\\\\\\\" TEXT,\\\\n \\\\\\\"repository_key\\\\\\\" TEXT,\\\\n \\\\\\\"event_name\\\\\\\" TEXT,\\\\n \\\\\\\"payload\\\\\\\" JSON,\\\\n \\\\\\\"status\\\\\\\" TEXT NOT NULL DEFAULT 'pending',\\\\n \\\\\\\"attempts\\\\\\\" INTEGER NOT NULL DEFAULT 0,\\\\n \\\\\\\"max_attempts\\\\\\\" INTEGER NOT NULL DEFAULT 5,\\\\n \\\\\\\"received_at\\\\\\\" TIMESTAMP NOT NULL,\\\\n \\\\\\\"next_attempt_at\\\\\\\" TIMESTAMP NOT NULL,\\\\n \\\\\\\"lease_owner\\\\\\\" TEXT,\\\\n \\\\\\\"lease_token\\\\\\\" TEXT,\\\\n \\\\\\\"lease_expires_at\\\\\\\" TIMESTAMP,\\\\n \\\\\\\"last_error\\\\\\\" TEXT,\\\\n \\\\\\\"completed_at\\\\\\\" TIMESTAMP,\\\\n \\\\\\\"replay_count\\\\\\\" INTEGER NOT NULL DEFAULT 0\\\\n);\\\",\\\"columns\\\":{\\\"_sync_origin_device_id\\\":{\\\"type\\\":\\\"TEXT\\\"},\\\"_sync_revision\\\":{\\\"type\\\":\\\"INTEGER\\\"},\\\"id\\\":{\\\"type\\\":\\\"UUID\\\",\\\"primaryKey\\\":true,\\\"referenceKind\\\":\\\"id\\\",\\\"notNull\\\":true},\\\"slug\\\":{\\\"type\\\":\\\"TEXT\\\",\\\"notNull\\\":true},\\\"context\\\":{\\\"type\\\":\\\"TEXT\\\",\\\"notNull\\\":true,\\\"default\\\":\\\"\\\"},\\\"created_at\\\":{\\\"type\\\":\\\"TIMESTAMP\\\",\\\"notNull\\\":true,\\\"default\\\":\\\"current_timestamp\\\"},\\\"updated_at\\\":{\\\"type\\\":\\\"TIMESTAMP\\\",\\\"notNull\\\":true,\\\"default\\\":\\\"current_timestamp\\\"},\\\"tenant_id\\\":{\\\"type\\\":\\\"UUID\\\",\\\"referenceKind\\\":\\\"tenantId\\\",\\\"notNull\\\":true,\\\"unique\\\":false},\\\"provider\\\":{\\\"type\\\":\\\"TEXT\\\",\\\"notNull\\\":true,\\\"unique\\\":false},\\\"delivery_id\\\":{\\\"type\\\":\\\"TEXT\\\",\\\"notNull\\\":true,\\\"unique\\\":false},\\\"installation_key\\\":{\\\"type\\\":\\\"TEXT\\\",\\\"notNull\\\":false,\\\"unique\\\":false},\\\"repository_key\\\":{\\\"type\\\":\\\"TEXT\\\",\\\"notNull\\\":false,\\\"unique\\\":false},\\\"event_name\\\":{\\\"type\\\":\\\"TEXT\\\",\\\"notNull\\\":false,\\\"unique\\\":false},\\\"payload\\\":{\\\"type\\\":\\\"JSON\\\",\\\"notNull\\\":false,\\\"unique\\\":false},\\\"status\\\":{\\\"type\\\":\\\"TEXT\\\",\\\"notNull\\\":true,\\\"unique\\\":false,\\\"default\\\":\\\"pending\\\"},\\\"attempts\\\":{\\\"type\\\":\\\"INTEGER\\\",\\\"notNull\\\":true,\\\"unique\\\":false,\\\"default\\\":0},\\\"max_attempts\\\":{\\\"type\\\":\\\"INTEGER\\\",\\\"notNull\\\":true,\\\"unique\\\":false,\\\"default\\\":5},\\\"received_at\\\":{\\\"type\\\":\\\"TIMESTAMP\\\",\\\"notNull\\\":true,\\\"unique\\\":false},\\\"next_attempt_at\\\":{\\\"type\\\":\\\"TIMESTAMP\\\",\\\"notNull\\\":true,\\\"unique\\\":false},\\\"lease_owner\\\":{\\\"type\\\":\\\"TEXT\\\",\\\"notNull\\\":false,\\\"unique\\\":false},\\\"lease_token\\\":{\\\"type\\\":\\\"TEXT\\\",\\\"notNull\\\":false,\\\"unique\\\":false},\\\"lease_expires_at\\\":{\\\"type\\\":\\\"TIMESTAMP\\\",\\\"notNull\\\":false,\\\"unique\\\":false},\\\"last_error\\\":{\\\"type\\\":\\\"TEXT\\\",\\\"notNull\\\":false,\\\"unique\\\":false},\\\"completed_at\\\":{\\\"type\\\":\\\"TIMESTAMP\\\",\\\"notNull\\\":false,\\\"unique\\\":false},\\\"replay_count\\\":{\\\"type\\\":\\\"INTEGER\\\",\\\"notNull\\\":true,\\\"unique\\\":false,\\\"default\\\":0}},\\\"indexes\\\":[{\\\"name\\\":\\\"_smrt_forge_deliveries_tenant_id_provider_idx\\\",\\\"columns\\\":[\\\"tenant_id\\\",\\\"provider\\\",\\\"delivery_id\\\"],\\\"unique\\\":true},{\\\"name\\\":\\\"_smrt_forge_deliveries_slug_context_idx\\\",\\\"columns\\\":[\\\"slug\\\",\\\"context\\\"]},{\\\"name\\\":\\\"_smrt_forge_deliveries_status_next_attempt_at_idx\\\",\\\"columns\\\":[\\\"status\\\",\\\"next_attempt_at\\\"]},{\\\"name\\\":\\\"_smrt_forge_deliveries_status_lease_expires_at_idx\\\",\\\"columns\\\":[\\\"status\\\",\\\"lease_expires_at\\\"]},{\\\"name\\\":\\\"_smrt_forge_deliveries_tenant_id_created_at_idx\\\",\\\"columns\\\":[\\\"tenant_id\\\",\\\"created_at\\\"]}],\\\"version\\\":\\\"870ae64b\\\"},\\\"importPath\\\":\\\"@happyvertical/smrt-jobs\\\"},\\\"@happyvertical/smrt-jobs:SmrtJobDedupeSlot\\\":{\\\"name\\\":\\\"smrtjobdedupeslot\\\",\\\"className\\\":\\\"SmrtJobDedupeSlot\\\",\\\"qualifiedName\\\":\\\"@happyvertical/smrt-jobs:SmrtJobDedupeSlot\\\",\\\"collection\\\":\\\"smrtjobdedupeslots\\\",\\\"description\\\":\\\"Store-owned serialization row for a tenant-partitioned job deduplication key.\\\",\\\"filePath\\\":\\\"src/smrt-job-dedupe-slot.ts\\\",\\\"packageName\\\":\\\"@happyvertical/smrt-jobs\\\",\\\"fields\\\":{\\\"slotKey\\\":{\\\"type\\\":\\\"text\\\",\\\"_meta\\\":{\\\"__statedOptions\\\":[\\\"required\\\",\\\"requiredFor\\\",\\\"unique\\\"],\\\"required\\\":true,\\\"requiredFor\\\":\\\"idempotency\\\",\\\"unique\\\":true},\\\"required\\\":true},\\\"jobId\\\":{\\\"type\\\":\\\"text\\\",\\\"_meta\\\":{\\\"__statedOptions\\\":[\\\"nullable\\\",\\\"required\\\"],\\\"nullable\\\":true,\\\"required\\\":false},\\\"required\\\":false}},\\\"methods\\\":{},\\\"decoratorConfig\\\":{\\\"tableName\\\":\\\"_smrt_job_dedupe_slots\\\",\\\"api\\\":false,\\\"cli\\\":false,\\\"mcp\\\":false},\\\"extends\\\":\\\"SmrtObject\\\",\\\"exportName\\\":\\\"SmrtJobDedupeSlot\\\",\\\"collectionExportName\\\":\\\"SmrtJobDedupeSlotCollection\\\",\\\"validationRules\\\":[{\\\"field\\\":\\\"slotKey\\\",\\\"rule\\\":\\\"required\\\",\\\"fieldType\\\":\\\"text\\\"}],\\\"schema\\\":{\\\"tableName\\\":\\\"_smrt_job_dedupe_slots\\\",\\\"ddl\\\":\\\"CREATE TABLE IF NOT EXISTS \\\\\\\"_smrt_job_dedupe_slots\\\\\\\" (\\\\n \\\\\\\"_sync_origin_device_id\\\\\\\" TEXT,\\\\n \\\\\\\"_sync_revision\\\\\\\" INTEGER,\\\\n \\\\\\\"id\\\\\\\" UUID PRIMARY KEY NOT NULL,\\\\n \\\\\\\"slug\\\\\\\" TEXT NOT NULL,\\\\n \\\\\\\"context\\\\\\\" TEXT NOT NULL DEFAULT '',\\\\n \\\\\\\"created_at\\\\\\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\\\n \\\\\\\"updated_at\\\\\\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\\\n \\\\\\\"slot_key\\\\\\\" TEXT NOT NULL UNIQUE,\\\\n \\\\\\\"job_id\\\\\\\" TEXT\\\\n);\\\",\\\"columns\\\":{\\\"_sync_origin_device_id\\\":{\\\"type\\\":\\\"TEXT\\\"},\\\"_sync_revision\\\":{\\\"type\\\":\\\"INTEGER\\\"},\\\"id\\\":{\\\"type\\\":\\\"UUID\\\",\\\"primaryKey\\\":true,\\\"referenceKind\\\":\\\"id\\\",\\\"notNull\\\":true},\\\"slug\\\":{\\\"type\\\":\\\"TEXT\\\",\\\"notNull\\\":true},\\\"context\\\":{\\\"type\\\":\\\"TEXT\\\",\\\"notNull\\\":true,\\\"default\\\":\\\"\\\"},\\\"created_at\\\":{\\\"type\\\":\\\"TIMESTAMP\\\",\\\"notNull\\\":true,\\\"default\\\":\\\"current_timestamp\\\"},\\\"updated_at\\\":{\\\"type\\\":\\\"TIMESTAMP\\\",\\\"notNull\\\":true,\\\"default\\\":\\\"current_timestamp\\\"},\\\"slot_key\\\":{\\\"type\\\":\\\"TEXT\\\",\\\"notNull\\\":true,\\\"unique\\\":true},\\\"job_id\\\":{\\\"type\\\":\\\"TEXT\\\",\\\"notNull\\\":false,\\\"unique\\\":false}},\\\"indexes\\\":[{\\\"name\\\":\\\"_smrt_job_dedupe_slots_slug_context_idx\\\",\\\"columns\\\":[\\\"slug\\\",\\\"context\\\"],\\\"unique\\\":true},{\\\"name\\\":\\\"_smrt_job_dedupe_slots_created_at_idx\\\",\\\"columns\\\":[\\\"created_at\\\"]}],\\\"version\\\":\\\"f876c2d7\\\"},\\\"importPath\\\":\\\"@happyvertical/smrt-jobs\\\"},\\\"@happyvertical/smrt-jobs:SmrtJobDedupeSlotCollection\\\":{\\\"name\\\":\\\"smrtjobdedupeslotcollection\\\",\\\"className\\\":\\\"SmrtJobDedupeSlotCollection\\\",\\\"qualifiedName\\\":\\\"@happyvertical/smrt-jobs:SmrtJobDedupeSlotCollection\\\",\\\"collection\\\":\\\"smrtjobdedupeslots\\\",\\\"description\\\":\\\"Internal collection for provisioning the registered store-owned model.\\\",\\\"filePath\\\":\\\"src/smrt-job-dedupe-slot.ts\\\",\\\"packageName\\\":\\\"@happyvertical/smrt-jobs\\\",\\\"fields\\\":{},\\\"methods\\\":{},\\\"decoratorConfig\\\":{\\\"tableName\\\":\\\"_smrt_job_dedupe_slots\\\",\\\"api\\\":false,\\\"mcp\\\":false,\\\"cli\\\":false},\\\"extends\\\":\\\"SmrtCollection\\\",\\\"extendsTypeArg\\\":\\\"SmrtJobDedupeSlot\\\",\\\"exportName\\\":\\\"SmrtJobDedupeSlotCollection\\\",\\\"collectionExportName\\\":\\\"SmrtJobDedupeSlotCollectionCollection\\\",\\\"collectionOf\\\":\\\"@happyvertical/smrt-jobs:SmrtJobDedupeSlot\\\",\\\"inheritedExposure\\\":[\\\"api\\\",\\\"mcp\\\",\\\"cli\\\"],\\\"schema\\\":{\\\"tableName\\\":\\\"_smrt_job_dedupe_slots\\\",\\\"ddl\\\":\\\"CREATE TABLE IF NOT EXISTS \\\\\\\"_smrt_job_dedupe_slots\\\\\\\" (\\\\n \\\\\\\"_sync_origin_device_id\\\\\\\" TEXT,\\\\n \\\\\\\"_sync_revision\\\\\\\" INTEGER,\\\\n \\\\\\\"id\\\\\\\" UUID PRIMARY KEY NOT NULL,\\\\n \\\\\\\"slug\\\\\\\" TEXT NOT NULL,\\\\n \\\\\\\"context\\\\\\\" TEXT NOT NULL DEFAULT '',\\\\n \\\\\\\"created_at\\\\\\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\\\n \\\\\\\"updated_at\\\\\\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\\\n \\\\\\\"slot_key\\\\\\\" TEXT NOT NULL UNIQUE,\\\\n \\\\\\\"job_id\\\\\\\" TEXT\\\\n);\\\",\\\"columns\\\":{\\\"_sync_origin_device_id\\\":{\\\"type\\\":\\\"TEXT\\\"},\\\"_sync_revision\\\":{\\\"type\\\":\\\"INTEGER\\\"},\\\"id\\\":{\\\"type\\\":\\\"UUID\\\",\\\"primaryKey\\\":true,\\\"referenceKind\\\":\\\"id\\\",\\\"notNull\\\":true},\\\"slug\\\":{\\\"type\\\":\\\"TEXT\\\",\\\"notNull\\\":true},\\\"context\\\":{\\\"type\\\":\\\"TEXT\\\",\\\"notNull\\\":true,\\\"default\\\":\\\"\\\"},\\\"created_at\\\":{\\\"type\\\":\\\"TIMESTAMP\\\",\\\"notNull\\\":true,\\\"default\\\":\\\"current_timestamp\\\"},\\\"updated_at\\\":{\\\"type\\\":\\\"TIMESTAMP\\\",\\\"notNull\\\":true,\\\"default\\\":\\\"current_timestamp\\\"},\\\"slot_key\\\":{\\\"type\\\":\\\"TEXT\\\",\\\"notNull\\\":true,\\\"unique\\\":true},\\\"job_id\\\":{\\\"type\\\":\\\"TEXT\\\",\\\"notNull\\\":false,\\\"unique\\\":false}},\\\"indexes\\\":[{\\\"name\\\":\\\"_smrt_job_dedupe_slots_slug_context_idx\\\",\\\"columns\\\":[\\\"slug\\\",\\\"context\\\"],\\\"unique\\\":true},{\\\"name\\\":\\\"_smrt_job_dedupe_slots_created_at_idx\\\",\\\"columns\\\":[\\\"created_at\\\"]}],\\\"version\\\":\\\"f876c2d7\\\"},\\\"importPath\\\":\\\"@happyvertical/smrt-jobs\\\"},\\\"@happyvertical/smrt-jobs:SmrtJobEventCollection\\\":{\\\"name\\\":\\\"smrtjobeventcollection\\\",\\\"className\\\":\\\"SmrtJobEventCollection\\\",\\\"qualifiedName\\\":\\\"@happyvertical/smrt-jobs:SmrtJobEventCollection\\\",\\\"collection\\\":\\\"smrtjobevents\\\",\\\"filePath\\\":\\\"src/smrt-job-event.ts\\\",\\\"packageName\\\":\\\"@happyvertical/smrt-jobs\\\",\\\"fields\\\":{},\\\"methods\\\":{\\\"initialize\\\":{\\\"name\\\":\\\"initialize\\\",\\\"async\\\":true,\\\"parameters\\\":[],\\\"returnType\\\":\\\"Promise<this>\\\",\\\"isStatic\\\":false,\\\"isPublic\\\":true},\\\"append\\\":{\\\"name\\\":\\\"append\\\",\\\"async\\\":true,\\\"parameters\\\":[{\\\"name\\\":\\\"input\\\",\\\"type\\\":\\\"SmrtJobEventData\\\",\\\"optional\\\":false}],\\\"returnType\\\":\\\"Promise<SmrtJobEvent>\\\",\\\"isStatic\\\":false,\\\"isPublic\\\":true},\\\"listByJob\\\":{\\\"name\\\":\\\"listByJob\\\",\\\"async\\\":true,\\\"parameters\\\":[{\\\"name\\\":\\\"jobId\\\",\\\"type\\\":\\\"string\\\",\\\"optional\\\":false},{\\\"name\\\":\\\"options\\\",\\\"type\\\":\\\"ListJobEventsOptions\\\",\\\"optional\\\":true}],\\\"returnType\\\":\\\"Promise<SmrtJobEvent[]>\\\",\\\"isStatic\\\":false,\\\"isPublic\\\":true},\\\"listSinceCursor\\\":{\\\"name\\\":\\\"listSinceCursor\\\",\\\"async\\\":true,\\\"parameters\\\":[{\\\"name\\\":\\\"options\\\",\\\"type\\\":\\\"any\\\",\\\"optional\\\":true,\\\"typeUnresolved\\\":true}],\\\"returnType\\\":\\\"Promise<SmrtJobEvent[]>\\\",\\\"isStatic\\\":false,\\\"isPublic\\\":true},\\\"latestProgressByJobIds\\\":{\\\"name\\\":\\\"latestProgressByJobIds\\\",\\\"async\\\":true,\\\"parameters\\\":[{\\\"name\\\":\\\"jobIds\\\",\\\"type\\\":\\\"string[]\\\",\\\"optional\\\":false},{\\\"name\\\":\\\"options\\\",\\\"type\\\":\\\"object\\\",\\\"optional\\\":true,\\\"memberTypes\\\":[\\\"string | null\\\"]}],\\\"returnType\\\":\\\"Promise<Map<string, SmrtJobEvent>>\\\",\\\"isStatic\\\":false,\\\"isPublic\\\":true},\\\"listTerminalOutcomes\\\":{\\\"name\\\":\\\"listTerminalOutcomes\\\",\\\"async\\\":true,\\\"parameters\\\":[{\\\"name\\\":\\\"options\\\",\\\"type\\\":\\\"ListTerminalOutcomesOptions\\\",\\\"optional\\\":false}],\\\"returnType\\\":\\\"Promise<SmrtJobTerminalOutcomePage>\\\",\\\"isStatic\\\":false,\\\"isPublic\\\":true},\\\"getTerminalOutcome\\\":{\\\"name\\\":\\\"getTerminalOutcome\\\",\\\"async\\\":true,\\\"parameters\\\":[{\\\"name\\\":\\\"jobId\\\",\\\"type\\\":\\\"string\\\",\\\"optional\\\":false},{\\\"name\\\":\\\"options\\\",\\\"type\\\":\\\"GetTerminalOutcomeOptions\\\",\\\"optional\\\":false}],\\\"returnType\\\":\\\"Promise<SmrtJobTerminalOutcome | null>\\\",\\\"isStatic\\\":false,\\\"isPublic\\\":true},\\\"cleanup\\\":{\\\"name\\\":\\\"cleanup\\\",\\\"async\\\":true,\\\"parameters\\\":[{\\\"name\\\":\\\"options\\\",\\\"type\\\":\\\"object\\\",\\\"optional\\\":false,\\\"memberTypes\\\":[\\\"Date\\\",\\\"boolean\\\"]}],\\\"returnType\\\":\\\"Promise<number>\\\",\\\"isStatic\\\":false,\\\"isPublic\\\":true}},\\\"decoratorConfig\\\":{\\\"tableName\\\":\\\"_smrt_job_events\\\",\\\"api\\\":false,\\\"mcp\\\":false,\\\"cli\\\":{\\\"include\\\":[\\\"list\\\",\\\"get\\\"],\\\"skipApiCheck\\\":true}},\\\"extends\\\":\\\"SmrtCollection\\\",\\\"extendsTypeArg\\\":\\\"SmrtJobEvent\\\",\\\"exportName\\\":\\\"SmrtJobEventCollection\\\",\\\"collectionExportName\\\":\\\"SmrtJobEventCollectionCollection\\\",\\\"collectionOf\\\":\\\"@happyvertical/smrt-jobs:SmrtJobEvent\\\",\\\"inheritedExposure\\\":[\\\"api\\\",\\\"mcp\\\",\\\"cli\\\"],\\\"schema\\\":{\\\"tableName\\\":\\\"_smrt_job_events\\\",\\\"ddl\\\":\\\"CREATE TABLE IF NOT EXISTS \\\\\\\"_smrt_job_events\\\\\\\" (\\\\n \\\\\\\"_sync_origin_device_id\\\\\\\" TEXT,\\\\n \\\\\\\"_sync_revision\\\\\\\" INTEGER,\\\\n \\\\\\\"id\\\\\\\" UUID PRIMARY KEY NOT NULL,\\\\n \\\\\\\"slug\\\\\\\" TEXT NOT NULL,\\\\n \\\\\\\"context\\\\\\\" TEXT NOT NULL DEFAULT '',\\\\n \\\\\\\"created_at\\\\\\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\\\n \\\\\\\"updated_at\\\\\\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\\\n \\\\\\\"tenant_id\\\\\\\" UUID,\\\\n \\\\\\\"job_id\\\\\\\" UUID NOT NULL,\\\\n \\\\\\\"type\\\\\\\" TEXT NOT NULL DEFAULT 'log',\\\\n \\\\\\\"level\\\\\\\" TEXT NOT NULL DEFAULT 'info',\\\\n \\\\\\\"stage\\\\\\\" TEXT,\\\\n \\\\\\\"progress\\\\\\\" INTEGER,\\\\n \\\\\\\"message\\\\\\\" TEXT DEFAULT '',\\\\n \\\\\\\"data\\\\\\\" JSON\\\\n);\\\",\\\"columns\\\":{\\\"_sync_origin_device_id\\\":{\\\"type\\\":\\\"TEXT\\\"},\\\"_sync_revision\\\":{\\\"type\\\":\\\"INTEGER\\\"},\\\"id\\\":{\\\"type\\\":\\\"UUID\\\",\\\"primaryKey\\\":true,\\\"referenceKind\\\":\\\"id\\\",\\\"notNull\\\":true},\\\"slug\\\":{\\\"type\\\":\\\"TEXT\\\",\\\"notNull\\\":true},\\\"context\\\":{\\\"type\\\":\\\"TEXT\\\",\\\"notNull\\\":true,\\\"default\\\":\\\"\\\"},\\\"created_at\\\":{\\\"type\\\":\\\"TIMESTAMP\\\",\\\"notNull\\\":true,\\\"default\\\":\\\"current_timestamp\\\"},\\\"updated_at\\\":{\\\"type\\\":\\\"TIMESTAMP\\\",\\\"notNull\\\":true,\\\"default\\\":\\\"current_timestamp\\\"},\\\"tenant_id\\\":{\\\"type\\\":\\\"UUID\\\",\\\"referenceKind\\\":\\\"tenantId\\\",\\\"notNull\\\":false,\\\"unique\\\":false},\\\"job_id\\\":{\\\"type\\\":\\\"UUID\\\",\\\"referenceKind\\\":\\\"foreignKey\\\",\\\"notNull\\\":true,\\\"unique\\\":false},\\\"type\\\":{\\\"type\\\":\\\"TEXT\\\",\\\"notNull\\\":true,\\\"unique\\\":false,\\\"default\\\":\\\"log\\\"},\\\"level\\\":{\\\"type\\\":\\\"TEXT\\\",\\\"notNull\\\":true,\\\"unique\\\":false,\\\"default\\\":\\\"info\\\"},\\\"stage\\\":{\\\"type\\\":\\\"TEXT\\\",\\\"notNull\\\":false,\\\"unique\\\":false},\\\"progress\\\":{\\\"type\\\":\\\"INTEGER\\\",\\\"notNull\\\":false,\\\"unique\\\":false},\\\"message\\\":{\\\"type\\\":\\\"TEXT\\\",\\\"notNull\\\":false,\\\"unique\\\":false,\\\"default\\\":\\\"\\\"},\\\"data\\\":{\\\"type\\\":\\\"JSON\\\",\\\"notNull\\\":false,\\\"unique\\\":false}},\\\"indexes\\\":[{\\\"name\\\":\\\"_smrt_job_events_slug_context_idx\\\",\\\"columns\\\":[\\\"tenant_id\\\",\\\"slug\\\",\\\"context\\\"],\\\"unique\\\":true,\\\"nullsNotDistinct\\\":true},{\\\"name\\\":\\\"_smrt_job_events_tenant_id_created_at_idx\\\",\\\"columns\\\":[\\\"tenant_id\\\",\\\"created_at\\\"]},{\\\"name\\\":\\\"_smrt_job_events_job_id_idx\\\",\\\"columns\\\":[\\\"job_id\\\"]}],\\\"version\\\":\\\"8645e1da\\\"},\\\"importPath\\\":\\\"@happyvertical/smrt-jobs\\\"},\\\"@happyvertical/smrt-jobs:SmrtJob\\\":{\\\"name\\\":\\\"smrtjob\\\",\\\"className\\\":\\\"SmrtJob\\\",\\\"qualifiedName\\\":\\\"@happyvertical/smrt-jobs:SmrtJob\\\",\\\"collection\\\":\\\"smrtjobs\\\",\\\"description\\\":\\\"Persistent job record stored in the _smrt_jobs system table.\\\",\\\"filePath\\\":\\\"src/smrt-job.ts\\\",\\\"packageName\\\":\\\"@happyvertical/smrt-jobs\\\",\\\"fields\\\":{\\\"tenantId\\\":{\\\"type\\\":\\\"text\\\",\\\"_meta\\\":{\\\"__tenancy\\\":{\\\"isTenantIdField\\\":true,\\\"autoFilter\\\":true,\\\"required\\\":false,\\\"autoPopulate\\\":true,\\\"nullable\\\":true,\\\"mode\\\":\\\"optional\\\",\\\"field\\\":\\\"tenantId\\\",\\\"allowSuperAdminBypass\\\":false},\\\"__statedOptions\\\":[\\\"sqlType\\\",\\\"nullable\\\",\\\"__tenancy\\\",\\\"required\\\"],\\\"sqlType\\\":\\\"UUID\\\",\\\"nullable\\\":true,\\\"required\\\":false},\\\"required\\\":false},\\\"dedupeKey\\\":{\\\"type\\\":\\\"text\\\",\\\"_meta\\\":{\\\"__statedOptions\\\":[\\\"nullable\\\",\\\"indexed\\\",\\\"required\\\"],\\\"nullable\\\":true,\\\"indexed\\\":true,\\\"required\\\":false},\\\"required\\\":false},\\\"queue\\\":{\\\"type\\\":\\\"text\\\",\\\"_meta\\\":{\\\"__statedOptions\\\":[\\\"required\\\",\\\"default\\\"],\\\"required\\\":true,\\\"default\\\":\\\"default\\\"},\\\"required\\\":true,\\\"default\\\":\\\"default\\\"},\\\"objectType\\\":{\\\"type\\\":\\\"text\\\",\\\"_meta\\\":{\\\"__statedOptions\\\":[\\\"required\\\",\\\"requiredFor\\\"],\\\"required\\\":true,\\\"requiredFor\\\":\\\"identity\\\"},\\\"required\\\":true},\\\"objectId\\\":{\\\"type\\\":\\\"text\\\",\\\"_meta\\\":{\\\"__statedOptions\\\":[\\\"nullable\\\",\\\"required\\\"],\\\"nullable\\\":true,\\\"required\\\":false},\\\"required\\\":false},\\\"method\\\":{\\\"type\\\":\\\"text\\\",\\\"_meta\\\":{\\\"__statedOptions\\\":[\\\"required\\\",\\\"requiredFor\\\"],\\\"required\\\":true,\\\"requiredFor\\\":\\\"identity\\\"},\\\"required\\\":true},\\\"args\\\":{\\\"type\\\":\\\"json\\\",\\\"_meta\\\":{\\\"__statedOptions\\\":[]},\\\"required\\\":false},\\\"runAt\\\":{\\\"type\\\":\\\"datetime\\\",\\\"_meta\\\":{\\\"__statedOptions\\\":[\\\"required\\\",\\\"indexed\\\"],\\\"required\\\":true,\\\"indexed\\\":true},\\\"required\\\":true},\\\"priority\\\":{\\\"type\\\":\\\"integer\\\",\\\"_meta\\\":{\\\"__statedOptions\\\":[\\\"required\\\",\\\"default\\\"],\\\"required\\\":true,\\\"default\\\":50},\\\"required\\\":true,\\\"default\\\":50},\\\"status\\\":{\\\"type\\\":\\\"text\\\",\\\"_meta\\\":{\\\"__statedOptions\\\":[\\\"required\\\",\\\"default\\\",\\\"indexed\\\",\\\"enum\\\"],\\\"required\\\":true,\\\"default\\\":\\\"pending\\\",\\\"indexed\\\":true},\\\"required\\\":true,\\\"default\\\":\\\"pending\\\",\\\"enum\\\":[\\\"pending\\\",\\\"ready\\\",\\\"running\\\",\\\"completed\\\",\\\"failed\\\",\\\"cancelled\\\"]},\\\"attempts\\\":{\\\"type\\\":\\\"integer\\\",\\\"_meta\\\":{\\\"__statedOptions\\\":[\\\"required\\\",\\\"default\\\"],\\\"required\\\":true,\\\"default\\\":0},\\\"required\\\":true,\\\"default\\\":0},\\\"maxAttempts\\\":{\\\"type\\\":\\\"integer\\\",\\\"_meta\\\":{\\\"__statedOptions\\\":[\\\"required\\\",\\\"default\\\"],\\\"required\\\":true,\\\"default\\\":3},\\\"required\\\":true,\\\"default\\\":3},\\\"timeout\\\":{\\\"type\\\":\\\"integer\\\",\\\"_meta\\\":{\\\"__statedOptions\\\":[\\\"required\\\",\\\"default\\\"],\\\"required\\\":true,\\\"default\\\":300000},\\\"required\\\":true,\\\"default\\\":300000},\\\"timeoutBehavior\\\":{\\\"type\\\":\\\"text\\\",\\\"_meta\\\":{\\\"__statedOptions\\\":[\\\"required\\\",\\\"default\\\",\\\"enum\\\"],\\\"required\\\":true,\\\"default\\\":\\\"fail\\\"},\\\"required\\\":true,\\\"default\\\":\\\"fail\\\",\\\"enum\\\":[\\\"fail\\\",\\\"kill\\\",\\\"warn\\\"]},\\\"startedAt\\\":{\\\"type\\\":\\\"datetime\\\",\\\"_meta\\\":{\\\"__statedOptions\\\":[\\\"nullable\\\",\\\"required\\\"],\\\"nullable\\\":true,\\\"required\\\":false},\\\"required\\\":false},\\\"completedAt\\\":{\\\"type\\\":\\\"datetime\\\",\\\"_meta\\\":{\\\"__statedOptions\\\":[\\\"nullable\\\",\\\"required\\\"],\\\"nullable\\\":true,\\\"required\\\":false},\\\"required\\\":false},\\\"lastError\\\":{\\\"type\\\":\\\"text\\\",\\\"_meta\\\":{\\\"__statedOptions\\\":[\\\"nullable\\\",\\\"required\\\"],\\\"nullable\\\":true,\\\"required\\\":false},\\\"required\\\":false},\\\"resultPointer\\\":{\\\"type\\\":\\\"text\\\",\\\"_meta\\\":{\\\"__statedOptions\\\":[\\\"nullable\\\",\\\"required\\\"],\\\"nullable\\\":true,\\\"required\\\":false},\\\"required\\\":false},\\\"taskId\\\":{\\\"type\\\":\\\"text\\\",\\\"_meta\\\":{\\\"__statedOptions\\\":[\\\"nullable\\\",\\\"unique\\\",\\\"required\\\"],\\\"nullable\\\":true,\\\"unique\\\":true,\\\"required\\\":false},\\\"required\\\":false},\\\"taskOwnerId\\\":{\\\"type\\\":\\\"text\\\",\\\"_meta\\\":{\\\"__statedOptions\\\":[\\\"nullable\\\",\\\"required\\\"],\\\"nullable\\\":true,\\\"required\\\":false},\\\"required\\\":false},\\\"taskResult\\\":{\\\"type\\\":\\\"json\\\",\\\"_meta\\\":{\\\"__statedOptions\\\":[\\\"nullable\\\",\\\"required\\\"],\\\"nullable\\\":true,\\\"required\\\":false},\\\"required\\\":false},\\\"taskInputRequests\\\":{\\\"type\\\":\\\"json\\\",\\\"_meta\\\":{\\\"__statedOptions\\\":[\\\"nullable\\\",\\\"required\\\"],\\\"nullable\\\":true,\\\"required\\\":false},\\\"required\\\":false},\\\"taskInputResponses\\\":{\\\"type\\\":\\\"json\\\",\\\"_meta\\\":{\\\"__statedOptions\\\":[\\\"nullable\\\",\\\"required\\\"],\\\"nullable\\\":true,\\\"required\\\":false},\\\"required\\\":false},\\\"retryStrategy\\\":{\\\"type\\\":\\\"json\\\",\\\"_meta\\\":{\\\"__statedOptions\\\":[]},\\\"required\\\":false},\\\"workerId\\\":{\\\"type\\\":\\\"text\\\",\\\"_meta\\\":{\\\"__statedOptions\\\":[\\\"nullable\\\",\\\"required\\\"],\\\"nullable\\\":true,\\\"required\\\":false},\\\"required\\\":false},\\\"workerHeartbeat\\\":{\\\"type\\\":\\\"datetime\\\",\\\"_meta\\\":{\\\"__statedOptions\\\":[\\\"nullable\\\",\\\"required\\\"],\\\"nullable\\\":true,\\\"required\\\":false},\\\"required\\\":false}},\\\"methods\\\":{\\\"save\\\":{\\\"name\\\":\\\"save\\\",\\\"async\\\":true,\\\"parameters\\\":[{\\\"name\\\":\\\"options\\\",\\\"type\\\":\\\"SmrtSaveOptions\\\",\\\"optional\\\":true}],\\\"returnType\\\":\\\"Promise<this>\\\",\\\"isStatic\\\":false,\\\"isPublic\\\":true},\\\"retry\\\":{\\\"name\\\":\\\"retry\\\",\\\"async\\\":true,\\\"parameters\\\":[{\\\"name\\\":\\\"options\\\",\\\"type\\\":\\\"Pick<EnqueueJobOptions, 'transaction'>\\\",\\\"optional\\\":true}],\\\"returnType\\\":\\\"Promise<void>\\\",\\\"isStatic\\\":false,\\\"isPublic\\\":true},\\\"cancel\\\":{\\\"name\\\":\\\"cancel\\\",\\\"async\\\":true,\\\"parameters\\\":[],\\\"returnType\\\":\\\"Promise<void>\\\",\\\"isStatic\\\":false,\\\"isPublic\\\":true},\\\"getDescription\\\":{\\\"name\\\":\\\"getDescription\\\",\\\"async\\\":false,\\\"parameters\\\":[],\\\"returnType\\\":\\\"string\\\",\\\"isStatic\\\":false,\\\"isPublic\\\":true}},\\\"decoratorConfig\\\":{\\\"tableName\\\":\\\"_smrt_jobs\\\",\\\"api\\\":false,\\\"cli\\\":{\\\"include\\\":[\\\"list\\\",\\\"get\\\",\\\"retry\\\",\\\"cancel\\\"],\\\"skipApiCheck\\\":true,\\\"http\\\":false},\\\"mcp\\\":false,\\\"indexes\\\":[{\\\"name\\\":\\\"_smrt_jobs_status_run_at_idx\\\",\\\"columns\\\":[\\\"status\\\",\\\"runAt\\\"]},{\\\"name\\\":\\\"_smrt_jobs_ready_idx\\\",\\\"columns\\\":[\\\"status\\\",\\\"runAt\\\"],\\\"where\\\":\\\"status = 'pending' AND (task_input_requests IS NULL OR task_input_responses IS NOT NULL)\\\"}],\\\"tenantScoped\\\":{\\\"mode\\\":\\\"optional\\\"},\\\"conflictColumns\\\":[\\\"tenant_id\\\",\\\"slug\\\",\\\"context\\\"]},\\\"extends\\\":\\\"SmrtObject\\\",\\\"exportName\\\":\\\"SmrtJob\\\",\\\"collectionExportName\\\":\\\"SmrtJobCollection\\\",\\\"validationRules\\\":[{\\\"field\\\":\\\"queue\\\",\\\"rule\\\":\\\"required\\\",\\\"fieldType\\\":\\\"text\\\"},{\\\"field\\\":\\\"objectType\\\",\\\"rule\\\":\\\"required\\\",\\\"fieldType\\\":\\\"text\\\"},{\\\"field\\\":\\\"method\\\",\\\"rule\\\":\\\"required\\\",\\\"fieldType\\\":\\\"text\\\"},{\\\"field\\\":\\\"runAt\\\",\\\"rule\\\":\\\"required\\\",\\\"fieldType\\\":\\\"datetime\\\"},{\\\"field\\\":\\\"priority\\\",\\\"rule\\\":\\\"required\\\",\\\"fieldType\\\":\\\"integer\\\"},{\\\"field\\\":\\\"status\\\",\\\"rule\\\":\\\"required\\\",\\\"fieldType\\\":\\\"text\\\"},{\\\"field\\\":\\\"attempts\\\",\\\"rule\\\":\\\"required\\\",\\\"fieldType\\\":\\\"integer\\\"},{\\\"field\\\":\\\"maxAttempts\\\",\\\"rule\\\":\\\"required\\\",\\\"fieldType\\\":\\\"integer\\\"},{\\\"field\\\":\\\"timeout\\\",\\\"rule\\\":\\\"required\\\",\\\"fieldType\\\":\\\"integer\\\"},{\\\"field\\\":\\\"timeoutBehavior\\\",\\\"rule\\\":\\\"required\\\",\\\"fieldType\\\":\\\"text\\\"}],\\\"schema\\\":{\\\"tableName\\\":\\\"_smrt_jobs\\\",\\\"ddl\\\":\\\"CREATE TABLE IF NOT EXISTS \\\\\\\"_smrt_jobs\\\\\\\" (\\\\n \\\\\\\"_sync_origin_device_id\\\\\\\" TEXT,\\\\n \\\\\\\"_sync_revision\\\\\\\" INTEGER,\\\\n \\\\\\\"id\\\\\\\" UUID PRIMARY KEY NOT NULL,\\\\n \\\\\\\"slug\\\\\\\" TEXT NOT NULL,\\\\n \\\\\\\"context\\\\\\\" TEXT NOT NULL DEFAULT '',\\\\n \\\\\\\"created_at\\\\\\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\\\n \\\\\\\"updated_at\\\\\\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\\\n \\\\\\\"tenant_id\\\\\\\" UUID,\\\\n \\\\\\\"dedupe_key\\\\\\\" TEXT,\\\\n \\\\\\\"queue\\\\\\\" TEXT NOT NULL DEFAULT 'default',\\\\n \\\\\\\"object_type\\\\\\\" TEXT NOT NULL,\\\\n \\\\\\\"object_id\\\\\\\" TEXT,\\\\n \\\\\\\"method\\\\\\\" TEXT NOT NULL,\\\\n \\\\\\\"args\\\\\\\" JSON,\\\\n \\\\\\\"run_at\\\\\\\" TIMESTAMP NOT NULL,\\\\n \\\\\\\"priority\\\\\\\" INTEGER NOT NULL DEFAULT 50,\\\\n \\\\\\\"status\\\\\\\" TEXT NOT NULL DEFAULT 'pending',\\\\n \\\\\\\"attempts\\\\\\\" INTEGER NOT NULL DEFAULT 0,\\\\n \\\\\\\"max_attempts\\\\\\\" INTEGER NOT NULL DEFAULT 3,\\\\n \\\\\\\"timeout\\\\\\\" INTEGER NOT NULL DEFAULT 300000,\\\\n \\\\\\\"timeout_behavior\\\\\\\" TEXT NOT NULL DEFAULT 'fail',\\\\n \\\\\\\"started_at\\\\\\\" TIMESTAMP,\\\\n \\\\\\\"completed_at\\\\\\\" TIMESTAMP,\\\\n \\\\\\\"last_error\\\\\\\" TEXT,\\\\n \\\\\\\"result_pointer\\\\\\\" TEXT,\\\\n \\\\\\\"task_id\\\\\\\" TEXT UNIQUE,\\\\n \\\\\\\"task_owner_id\\\\\\\" TEXT,\\\\n \\\\\\\"task_result\\\\\\\" JSON,\\\\n \\\\\\\"task_input_requests\\\\\\\" JSON,\\\\n \\\\\\\"task_input_responses\\\\\\\" JSON,\\\\n \\\\\\\"retry_strategy\\\\\\\" JSON,\\\\n \\\\\\\"worker_id\\\\\\\" TEXT,\\\\n \\\\\\\"worker_heartbeat\\\\\\\" TIMESTAMP\\\\n);\\\",\\\"columns\\\":{\\\"_sync_origin_device_id\\\":{\\\"type\\\":\\\"TEXT\\\"},\\\"_sync_revision\\\":{\\\"type\\\":\\\"INTEGER\\\"},\\\"id\\\":{\\\"type\\\":\\\"UUID\\\",\\\"primaryKey\\\":true,\\\"referenceKind\\\":\\\"id\\\",\\\"notNull\\\":true},\\\"slug\\\":{\\\"type\\\":\\\"TEXT\\\",\\\"notNull\\\":true},\\\"context\\\":{\\\"type\\\":\\\"TEXT\\\",\\\"notNull\\\":true,\\\"default\\\":\\\"\\\"},\\\"created_at\\\":{\\\"type\\\":\\\"TIMESTAMP\\\",\\\"notNull\\\":true,\\\"default\\\":\\\"current_timestamp\\\"},\\\"updated_at\\\":{\\\"type\\\":\\\"TIMESTAMP\\\",\\\"notNull\\\":true,\\\"default\\\":\\\"current_timestamp\\\"},\\\"tenant_id\\\":{\\\"type\\\":\\\"UUID\\\",\\\"referenceKind\\\":\\\"tenantId\\\",\\\"notNull\\\":false,\\\"unique\\\":false},\\\"dedupe_key\\\":{\\\"type\\\":\\\"TEXT\\\",\\\"notNull\\\":false,\\\"unique\\\":false},\\\"queue\\\":{\\\"type\\\":\\\"TEXT\\\",\\\"notNull\\\":true,\\\"unique\\\":false,\\\"default\\\":\\\"default\\\"},\\\"object_type\\\":{\\\"type\\\":\\\"TEXT\\\",\\\"notNull\\\":true,\\\"unique\\\":false},\\\"object_id\\\":{\\\"type\\\":\\\"TEXT\\\",\\\"notNull\\\":false,\\\"unique\\\":false},\\\"method\\\":{\\\"type\\\":\\\"TEXT\\\",\\\"notNull\\\":true,\\\"unique\\\":false},\\\"args\\\":{\\\"type\\\":\\\"JSON\\\",\\\"notNull\\\":false,\\\"unique\\\":false},\\\"run_at\\\":{\\\"type\\\":\\\"TIMESTAMP\\\",\\\"notNull\\\":true,\\\"unique\\\":false},\\\"priority\\\":{\\\"type\\\":\\\"INTEGER\\\",\\\"notNull\\\":true,\\\"unique\\\":false,\\\"default\\\":50},\\\"status\\\":{\\\"type\\\":\\\"TEXT\\\",\\\"notNull\\\":true,\\\"unique\\\":false,\\\"default\\\":\\\"pending\\\"},\\\"attempts\\\":{\\\"type\\\":\\\"INTEGER\\\",\\\"notNull\\\":true,\\\"unique\\\":false,\\\"default\\\":0},\\\"max_attempts\\\":{\\\"type\\\":\\\"INTEGER\\\",\\\"notNull\\\":true,\\\"unique\\\":false,\\\"default\\\":3},\\\"timeout\\\":{\\\"type\\\":\\\"INTEGER\\\",\\\"notNull\\\":true,\\\"unique\\\":false,\\\"default\\\":300000},\\\"timeout_behavior\\\":{\\\"type\\\":\\\"TEXT\\\",\\\"notNull\\\":true,\\\"unique\\\":false,\\\"default\\\":\\\"fail\\\"},\\\"started_at\\\":{\\\"type\\\":\\\"TIMESTAMP\\\",\\\"notNull\\\":false,\\\"unique\\\":false},\\\"completed_at\\\":{\\\"type\\\":\\\"TIMESTAMP\\\",\\\"notNull\\\":false,\\\"unique\\\":false},\\\"last_error\\\":{\\\"type\\\":\\\"TEXT\\\",\\\"notNull\\\":false,\\\"unique\\\":false},\\\"result_pointer\\\":{\\\"type\\\":\\\"TEXT\\\",\\\"notNull\\\":false,\\\"unique\\\":false},\\\"task_id\\\":{\\\"type\\\":\\\"TEXT\\\",\\\"notNull\\\":false,\\\"unique\\\":true},\\\"task_owner_id\\\":{\\\"type\\\":\\\"TEXT\\\",\\\"notNull\\\":false,\\\"unique\\\":false},\\\"task_result\\\":{\\\"type\\\":\\\"JSON\\\",\\\"notNull\\\":false,\\\"unique\\\":false},\\\"task_input_requests\\\":{\\\"type\\\":\\\"JSON\\\",\\\"notNull\\\":false,\\\"unique\\\":false},\\\"task_input_responses\\\":{\\\"type\\\":\\\"JSON\\\",\\\"notNull\\\":false,\\\"unique\\\":false},\\\"retry_strategy\\\":{\\\"type\\\":\\\"JSON\\\",\\\"notNull\\\":false,\\\"unique\\\":false},\\\"worker_id\\\":{\\\"type\\\":\\\"TEXT\\\",\\\"notNull\\\":false,\\\"unique\\\":false},\\\"worker_heartbeat\\\":{\\\"type\\\":\\\"TIMESTAMP\\\",\\\"notNull\\\":false,\\\"unique\\\":false}},\\\"indexes\\\":[{\\\"name\\\":\\\"_smrt_jobs_slug_context_idx\\\",\\\"columns\\\":[\\\"tenant_id\\\",\\\"slug\\\",\\\"context\\\"],\\\"unique\\\":true,\\\"nullsNotDistinct\\\":true},{\\\"name\\\":\\\"_smrt_jobs_dedupe_key_idx\\\",\\\"columns\\\":[\\\"dedupe_key\\\"]},{\\\"name\\\":\\\"_smrt_jobs_run_at_idx\\\",\\\"columns\\\":[\\\"run_at\\\"]},{\\\"name\\\":\\\"_smrt_jobs_status_idx\\\",\\\"columns\\\":[\\\"status\\\"]},{\\\"name\\\":\\\"_smrt_jobs_status_run_at_idx\\\",\\\"columns\\\":[\\\"status\\\",\\\"run_at\\\"]},{\\\"name\\\":\\\"_smrt_jobs_ready_idx\\\",\\\"columns\\\":[\\\"status\\\",\\\"run_at\\\"],\\\"where\\\":\\\"status = 'pending' AND (task_input_requests IS NULL OR task_input_responses IS NOT NULL)\\\"},{\\\"name\\\":\\\"_smrt_jobs_tenant_id_created_at_idx\\\",\\\"columns\\\":[\\\"tenant_id\\\",\\\"created_at\\\"]}],\\\"version\\\":\\\"4cc5c3e5\\\"},\\\"importPath\\\":\\\"@happyvertical/smrt-jobs\\\"},\\\"@happyvertical/smrt-jobs:SmrtJobCollection\\\":{\\\"name\\\":\\\"smrtjobcollection\\\",\\\"className\\\":\\\"SmrtJobCollection\\\",\\\"qualifiedName\\\":\\\"@happyvertical/smrt-jobs:SmrtJobCollection\\\",\\\"collection\\\":\\\"smrtjobs\\\",\\\"description\\\":\\\"Collection for managing SmrtJob objects\\\",\\\"filePath\\\":\\\"src/smrt-job.ts\\\",\\\"packageName\\\":\\\"@happyvertical/smrt-jobs\\\",\\\"fields\\\":{},\\\"methods\\\":{\\\"initialize\\\":{\\\"name\\\":\\\"initialize\\\",\\\"async\\\":true,\\\"parameters\\\":[],\\\"returnType\\\":\\\"Promise<this>\\\",\\\"isStatic\\\":false,\\\"isPublic\\\":true},\\\"listByStatus\\\":{\\\"name\\\":\\\"listByStatus\\\",\\\"async\\\":true,\\\"parameters\\\":[{\\\"name\\\":\\\"status\\\",\\\"type\\\":\\\"JobStatus | JobStatus[]\\\",\\\"optional\\\":false,\\\"unionBranches\\\":[{\\\"type\\\":\\\"JobStatus\\\"},{\\\"type\\\":\\\"JobStatus[]\\\"}]},{\\\"name\\\":\\\"options\\\",\\\"type\\\":\\\"object\\\",\\\"optional\\\":true,\\\"memberTypes\\\":[\\\"number\\\",\\\"string\\\"]}],\\\"returnType\\\":\\\"Promise<SmrtJob[]>\\\",\\\"isStatic\\\":false,\\\"isPublic\\\":true},\\\"listReady\\\":{\\\"name\\\":\\\"listReady\\\",\\\"async\\\":true,\\\"parameters\\\":[{\\\"name\\\":\\\"options\\\",\\\"type\\\":\\\"ListReadyOptions\\\",\\\"optional\\\":true}],\\\"returnType\\\":\\\"Promise<SmrtJob[]>\\\",\\\"isStatic\\\":false,\\\"isPublic\\\":true},\\\"claimReady\\\":{\\\"name\\\":\\\"claimReady\\\",\\\"async\\\":true,\\\"parameters\\\":[{\\\"name\\\":\\\"options\\\",\\\"type\\\":\\\"ClaimReadyOptions\\\",\\\"optional\\\":false}],\\\"returnType\\\":\\\"Promise<SmrtJob[]>\\\",\\\"isStatic\\\":false,\\\"isPublic\\\":true},\\\"countInFlightForTenant\\\":{\\\"name\\\":\\\"countInFlightForTenant\\\",\\\"async\\\":true,\\\"parameters\\\":[{\\\"name\\\":\\\"tenantId\\\",\\\"type\\\":\\\"string | null\\\",\\\"optional\\\":false,\\\"unionBranches\\\":[{\\\"type\\\":\\\"string\\\"},{\\\"type\\\":\\\"null\\\"}]}],\\\"returnType\\\":\\\"Promise<number>\\\",\\\"isStatic\\\":false,\\\"isPublic\\\":true},\\\"enqueueJob\\\":{\\\"name\\\":\\\"enqueueJob\\\",\\\"async\\\":true,\\\"parameters\\\":[{\\\"name\\\":\\\"data\\\",\\\"type\\\":\\\"SmrtJobData\\\",\\\"optional\\\":false},{\\\"name\\\":\\\"options\\\",\\\"type\\\":\\\"EnqueueJobOptions\\\",\\\"optional\\\":true}],\\\"returnType\\\":\\\"Promise<SmrtJob>\\\",\\\"isStatic\\\":false,\\\"isPublic\\\":true},\\\"enqueueHandlerJob\\\":{\\\"name\\\":\\\"enqueueHandlerJob\\\",\\\"async\\\":true,\\\"parameters\\\":[{\\\"name\\\":\\\"data\\\",\\\"type\\\":\\\"HandlerJobData\\\",\\\"optional\\\":false},{\\\"name\\\":\\\"options\\\",\\\"type\\\":\\\"EnqueueJobOptions\\\",\\\"optional\\\":true}],\\\"returnType\\\":\\\"Promise<SmrtJob>\\\",\\\"isStatic\\\":false,\\\"isPublic\\\":true},\\\"stats\\\":{\\\"name\\\":\\\"stats\\\",\\\"async\\\":true,\\\"parameters\\\":[{\\\"name\\\":\\\"queue\\\",\\\"type\\\":\\\"string\\\",\\\"optional\\\":true}],\\\"returnType\\\":\\\"Promise<object>\\\",\\\"isStatic\\\":false,\\\"isPublic\\\":true},\\\"cleanup\\\":{\\\"name\\\":\\\"cleanup\\\",\\\"async\\\":true,\\\"parameters\\\":[{\\\"name\\\":\\\"options\\\",\\\"type\\\":\\\"object\\\",\\\"optional\\\":false,\\\"memberTypes\\\":[\\\"Date\\\",\\\"number\\\",\\\"boolean\\\"]}],\\\"returnType\\\":\\\"Promise<number>\\\",\\\"isStatic\\\":false,\\\"isPublic\\\":true}},\\\"decoratorConfig\\\":{\\\"tableName\\\":\\\"_smrt_jobs\\\",\\\"api\\\":false,\\\"mcp\\\":false,\\\"cli\\\":{\\\"include\\\":[\\\"list\\\",\\\"get\\\"],\\\"skipApiCheck\\\":true}},\\\"extends\\\":\\\"SmrtCollection\\\",\\\"extendsTypeArg\\\":\\\"SmrtJob\\\",\\\"exportName\\\":\\\"SmrtJobCollection\\\",\\\"collectionExportName\\\":\\\"SmrtJobCollectionCollection\\\",\\\"collectionOf\\\":\\\"@happyvertical/smrt-jobs:SmrtJob\\\",\\\"inheritedExposure\\\":[\\\"api\\\",\\\"mcp\\\",\\\"cli\\\"],\\\"schema\\\":{\\\"tableName\\\":\\\"_smrt_jobs\\\",\\\"ddl\\\":\\\"CREATE TABLE IF NOT EXISTS \\\\\\\"_smrt_jobs\\\\\\\" (\\\\n \\\\\\\"_sync_origin_device_id\\\\\\\" TEXT,\\\\n \\\\\\\"_sync_revision\\\\\\\" INTEGER,\\\\n \\\\\\\"id\\\\\\\" UUID PRIMARY KEY NOT NULL,\\\\n \\\\\\\"slug\\\\\\\" TEXT NOT NULL,\\\\n \\\\\\\"context\\\\\\\" TEXT NOT NULL DEFAULT '',\\\\n \\\\\\\"created_at\\\\\\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\\\n \\\\\\\"updated_at\\\\\\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\\\n \\\\\\\"tenant_id\\\\\\\" UUID,\\\\n \\\\\\\"dedupe_key\\\\\\\" TEXT,\\\\n \\\\\\\"queue\\\\\\\" TEXT NOT NULL DEFAULT 'default',\\\\n \\\\\\\"object_type\\\\\\\" TEXT NOT NULL,\\\\n \\\\\\\"object_id\\\\\\\" TEXT,\\\\n \\\\\\\"method\\\\\\\" TEXT NOT NULL,\\\\n \\\\\\\"args\\\\\\\" JSON,\\\\n \\\\\\\"run_at\\\\\\\" TIMESTAMP NOT NULL,\\\\n \\\\\\\"priority\\\\\\\" INTEGER NOT NULL DEFAULT 50,\\\\n \\\\\\\"status\\\\\\\" TEXT NOT NULL DEFAULT 'pending',\\\\n \\\\\\\"attempts\\\\\\\" INTEGER NOT NULL DEFAULT 0,\\\\n \\\\\\\"max_attempts\\\\\\\" INTEGER NOT NULL DEFAULT 3,\\\\n \\\\\\\"timeout\\\\\\\" INTEGER NOT NULL DEFAULT 300000,\\\\n \\\\\\\"timeout_behavior\\\\\\\" TEXT NOT NULL DEFAULT 'fail',\\\\n \\\\\\\"started_at\\\\\\\" TIMESTAMP,\\\\n \\\\\\\"completed_at\\\\\\\" TIMESTAMP,\\\\n \\\\\\\"last_error\\\\\\\" TEXT,\\\\n \\\\\\\"result_pointer\\\\\\\" TEXT,\\\\n \\\\\\\"task_id\\\\\\\" TEXT UNIQUE,\\\\n \\\\\\\"task_owner_id\\\\\\\" TEXT,\\\\n \\\\\\\"task_result\\\\\\\" JSON,\\\\n \\\\\\\"task_input_requests\\\\\\\" JSON,\\\\n \\\\\\\"task_input_responses\\\\\\\" JSON,\\\\n \\\\\\\"retry_strategy\\\\\\\" JSON,\\\\n \\\\\\\"worker_id\\\\\\\" TEXT,\\\\n \\\\\\\"worker_heartbeat\\\\\\\" TIMESTAMP\\\\n);\\\",\\\"columns\\\":{\\\"_sync_origin_device_id\\\":{\\\"type\\\":\\\"TEXT\\\"},\\\"_sync_revision\\\":{\\\"type\\\":\\\"INTEGER\\\"},\\\"id\\\":{\\\"type\\\":\\\"UUID\\\",\\\"primaryKey\\\":true,\\\"referenceKind\\\":\\\"id\\\",\\\"notNull\\\":true},\\\"slug\\\":{\\\"type\\\":\\\"TEXT\\\",\\\"notNull\\\":true},\\\"context\\\":{\\\"type\\\":\\\"TEXT\\\",\\\"notNull\\\":true,\\\"default\\\":\\\"\\\"},\\\"created_at\\\":{\\\"type\\\":\\\"TIMESTAMP\\\",\\\"notNull\\\":true,\\\"default\\\":\\\"current_timestamp\\\"},\\\"updated_at\\\":{\\\"type\\\":\\\"TIMESTAMP\\\",\\\"notNull\\\":true,\\\"default\\\":\\\"current_timestamp\\\"},\\\"tenant_id\\\":{\\\"type\\\":\\\"UUID\\\",\\\"referenceKind\\\":\\\"tenantId\\\",\\\"notNull\\\":false,\\\"unique\\\":false},\\\"dedupe_key\\\":{\\\"type\\\":\\\"TEXT\\\",\\\"notNull\\\":false,\\\"unique\\\":false},\\\"queue\\\":{\\\"type\\\":\\\"TEXT\\\",\\\"notNull\\\":true,\\\"unique\\\":false,\\\"default\\\":\\\"default\\\"},\\\"object_type\\\":{\\\"type\\\":\\\"TEXT\\\",\\\"notNull\\\":true,\\\"unique\\\":false},\\\"object_id\\\":{\\\"type\\\":\\\"TEXT\\\",\\\"notNull\\\":false,\\\"unique\\\":false},\\\"method\\\":{\\\"type\\\":\\\"TEXT\\\",\\\"notNull\\\":true,\\\"unique\\\":false},\\\"args\\\":{\\\"type\\\":\\\"JSON\\\",\\\"notNull\\\":false,\\\"unique\\\":false},\\\"run_at\\\":{\\\"type\\\":\\\"TIMESTAMP\\\",\\\"notNull\\\":true,\\\"unique\\\":false},\\\"priority\\\":{\\\"type\\\":\\\"INTEGER\\\",\\\"notNull\\\":true,\\\"unique\\\":false,\\\"default\\\":50},\\\"status\\\":{\\\"type\\\":\\\"TEXT\\\",\\\"notNull\\\":true,\\\"unique\\\":false,\\\"default\\\":\\\"pending\\\"},\\\"attempts\\\":{\\\"type\\\":\\\"INTEGER\\\",\\\"notNull\\\":true,\\\"unique\\\":false,\\\"default\\\":0},\\\"max_attempts\\\":{\\\"type\\\":\\\"INTEGER\\\",\\\"notNull\\\":true,\\\"unique\\\":false,\\\"default\\\":3},\\\"timeout\\\":{\\\"type\\\":\\\"INTEGER\\\",\\\"notNull\\\":true,\\\"unique\\\":false,\\\"default\\\":300000},\\\"timeout_behavior\\\":{\\\"type\\\":\\\"TEXT\\\",\\\"notNull\\\":true,\\\"unique\\\":false,\\\"default\\\":\\\"fail\\\"},\\\"started_at\\\":{\\\"type\\\":\\\"TIMESTAMP\\\",\\\"notNull\\\":false,\\\"unique\\\":false},\\\"completed_at\\\":{\\\"type\\\":\\\"TIMESTAMP\\\",\\\"notNull\\\":false,\\\"unique\\\":false},\\\"last_error\\\":{\\\"type\\\":\\\"TEXT\\\",\\\"notNull\\\":false,\\\"unique\\\":false},\\\"result_pointer\\\":{\\\"type\\\":\\\"TEXT\\\",\\\"notNull\\\":false,\\\"unique\\\":false},\\\"task_id\\\":{\\\"type\\\":\\\"TEXT\\\",\\\"notNull\\\":false,\\\"unique\\\":true},\\\"task_owner_id\\\":{\\\"type\\\":\\\"TEXT\\\",\\\"notNull\\\":false,\\\"unique\\\":false},\\\"task_result\\\":{\\\"type\\\":\\\"JSON\\\",\\\"notNull\\\":false,\\\"unique\\\":false},\\\"task_input_requests\\\":{\\\"type\\\":\\\"JSON\\\",\\\"notNull\\\":false,\\\"unique\\\":false},\\\"task_input_responses\\\":{\\\"type\\\":\\\"JSON\\\",\\\"notNull\\\":false,\\\"unique\\\":false},\\\"retry_strategy\\\":{\\\"type\\\":\\\"JSON\\\",\\\"notNull\\\":false,\\\"unique\\\":false},\\\"worker_id\\\":{\\\"type\\\":\\\"TEXT\\\",\\\"notNull\\\":false,\\\"unique\\\":false},\\\"worker_heartbeat\\\":{\\\"type\\\":\\\"TIMESTAMP\\\",\\\"notNull\\\":false,\\\"unique\\\":false}},\\\"indexes\\\":[{\\\"name\\\":\\\"_smrt_jobs_slug_context_idx\\\",\\\"columns\\\":[\\\"tenant_id\\\",\\\"slug\\\",\\\"context\\\"],\\\"unique\\\":true,\\\"nullsNotDistinct\\\":true},{\\\"name\\\":\\\"_smrt_jobs_dedupe_key_idx\\\",\\\"columns\\\":[\\\"dedupe_key\\\"]},{\\\"name\\\":\\\"_smrt_jobs_run_at_idx\\\",\\\"columns\\\":[\\\"run_at\\\"]},{\\\"name\\\":\\\"_smrt_jobs_status_idx\\\",\\\"columns\\\":[\\\"status\\\"]},{\\\"name\\\":\\\"_smrt_jobs_status_run_at_idx\\\",\\\"columns\\\":[\\\"status\\\",\\\"run_at\\\"]},{\\\"name\\\":\\\"_smrt_jobs_ready_idx\\\",\\\"columns\\\":[\\\"status\\\",\\\"run_at\\\"],\\\"where\\\":\\\"status = 'pending' AND (task_input_requests IS NULL OR task_input_responses IS NOT NULL)\\\"},{\\\"name\\\":\\\"_smrt_jobs_tenant_id_created_at_idx\\\",\\\"columns\\\":[\\\"tenant_id\\\",\\\"created_at\\\"]}],\\\"version\\\":\\\"4cc5c3e5\\\"},\\\"importPath\\\":\\\"@happyvertical/smrt-jobs\\\"},\\\"@happyvertical/smrt-jobs:SmrtWorker\\\":{\\\"name\\\":\\\"smrtworker\\\",\\\"className\\\":\\\"SmrtWorker\\\",\\\"qualifiedName\\\":\\\"@happyvertical/smrt-jobs:SmrtWorker\\\",\\\"collection\\\":\\\"smrtworkers\\\",\\\"description\\\":\\\"Liveness record for a single TaskRunner / ScheduleRunner incarnation, stored in the _smrt_workers system table.\\\",\\\"filePath\\\":\\\"src/smrt-worker.ts\\\",\\\"packageName\\\":\\\"@happyvertical/smrt-jobs\\\",\\\"fields\\\":{\\\"workerId\\\":{\\\"type\\\":\\\"text\\\",\\\"_meta\\\":{\\\"__statedOptions\\\":[\\\"required\\\",\\\"requiredFor\\\"],\\\"required\\\":true,\\\"requiredFor\\\":\\\"identity\\\"},\\\"required\\\":true},\\\"pid\\\":{\\\"type\\\":\\\"integer\\\",\\\"_meta\\\":{\\\"__statedOptions\\\":[\\\"nullable\\\",\\\"required\\\"],\\\"nullable\\\":true,\\\"required\\\":false},\\\"required\\\":false},\\\"hostname\\\":{\\\"type\\\":\\\"text\\\",\\\"_meta\\\":{\\\"__statedOptions\\\":[\\\"nullable\\\",\\\"required\\\"],\\\"nullable\\\":true,\\\"required\\\":false},\\\"required\\\":false},\\\"startedAt\\\":{\\\"type\\\":\\\"datetime\\\",\\\"_meta\\\":{\\\"__statedOptions\\\":[\\\"nullable\\\",\\\"required\\\"],\\\"nullable\\\":true,\\\"required\\\":false},\\\"required\\\":false},\\\"heartbeatAt\\\":{\\\"type\\\":\\\"datetime\\\",\\\"_meta\\\":{\\\"__statedOptions\\\":[\\\"nullable\\\",\\\"required\\\"],\\\"nullable\\\":true,\\\"required\\\":false},\\\"required\\\":false},\\\"leaseExpiresAt\\\":{\\\"type\\\":\\\"datetime\\\",\\\"_meta\\\":{\\\"__statedOptions\\\":[\\\"nullable\\\",\\\"required\\\"],\\\"nullable\\\":true,\\\"required\\\":false},\\\"required\\\":false},\\\"queues\\\":{\\\"type\\\":\\\"json\\\",\\\"_meta\\\":{\\\"__statedOptions\\\":[\\\"nullable\\\",\\\"required\\\"],\\\"nullable\\\":true,\\\"required\\\":false},\\\"required\\\":false},\\\"status\\\":{\\\"type\\\":\\\"text\\\",\\\"_meta\\\":{\\\"__statedOptions\\\":[\\\"required\\\",\\\"default\\\"],\\\"required\\\":true,\\\"default\\\":\\\"running\\\"},\\\"required\\\":true,\\\"default\\\":\\\"running\\\"}},\\\"methods\\\":{},\\\"decoratorConfig\\\":{\\\"tableName\\\":\\\"_smrt_workers\\\",\\\"conflictColumns\\\":[\\\"worker_id\\\"],\\\"api\\\":false,\\\"cli\\\":false,\\\"mcp\\\":false},\\\"extends\\\":\\\"SmrtObject\\\",\\\"exportName\\\":\\\"SmrtWorker\\\",\\\"collectionExportName\\\":\\\"SmrtWorkerCollection\\\",\\\"validationRules\\\":[{\\\"field\\\":\\\"workerId\\\",\\\"rule\\\":\\\"required\\\",\\\"fieldType\\\":\\\"text\\\"},{\\\"field\\\":\\\"status\\\",\\\"rule\\\":\\\"required\\\",\\\"fieldType\\\":\\\"text\\\"}],\\\"schema\\\":{\\\"tableName\\\":\\\"_smrt_workers\\\",\\\"ddl\\\":\\\"CREATE TABLE IF NOT EXISTS \\\\\\\"_smrt_workers\\\\\\\" (\\\\n \\\\\\\"_sync_origin_device_id\\\\\\\" TEXT,\\\\n \\\\\\\"_sync_revision\\\\\\\" INTEGER,\\\\n \\\\\\\"id\\\\\\\" UUID PRIMARY KEY NOT NULL,\\\\n \\\\\\\"slug\\\\\\\" TEXT NOT NULL,\\\\n \\\\\\\"context\\\\\\\" TEXT NOT NULL DEFAULT '',\\\\n \\\\\\\"created_at\\\\\\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\\\n \\\\\\\"updated_at\\\\\\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\\\n \\\\\\\"worker_id\\\\\\\" TEXT NOT NULL,\\\\n \\\\\\\"pid\\\\\\\" INTEGER,\\\\n \\\\\\\"hostname\\\\\\\" TEXT,\\\\n \\\\\\\"started_at\\\\\\\" TIMESTAMP,\\\\n \\\\\\\"heartbeat_at\\\\\\\" TIMESTAMP,\\\\n \\\\\\\"lease_expires_at\\\\\\\" TIMESTAMP,\\\\n \\\\\\\"queues\\\\\\\" JSON,\\\\n \\\\\\\"status\\\\\\\" TEXT NOT NULL DEFAULT 'running'\\\\n);\\\",\\\"columns\\\":{\\\"_sync_origin_device_id\\\":{\\\"type\\\":\\\"TEXT\\\"},\\\"_sync_revision\\\":{\\\"type\\\":\\\"INTEGER\\\"},\\\"id\\\":{\\\"type\\\":\\\"UUID\\\",\\\"primaryKey\\\":true,\\\"referenceKind\\\":\\\"id\\\",\\\"notNull\\\":true},\\\"slug\\\":{\\\"type\\\":\\\"TEXT\\\",\\\"notNull\\\":true},\\\"context\\\":{\\\"type\\\":\\\"TEXT\\\",\\\"notNull\\\":true,\\\"default\\\":\\\"\\\"},\\\"created_at\\\":{\\\"type\\\":\\\"TIMESTAMP\\\",\\\"notNull\\\":true,\\\"default\\\":\\\"current_timestamp\\\"},\\\"updated_at\\\":{\\\"type\\\":\\\"TIMESTAMP\\\",\\\"notNull\\\":true,\\\"default\\\":\\\"current_timestamp\\\"},\\\"worker_id\\\":{\\\"type\\\":\\\"TEXT\\\",\\\"notNull\\\":true,\\\"unique\\\":false},\\\"pid\\\":{\\\"type\\\":\\\"INTEGER\\\",\\\"notNull\\\":false,\\\"unique\\\":false},\\\"hostname\\\":{\\\"type\\\":\\\"TEXT\\\",\\\"notNull\\\":false,\\\"unique\\\":false},\\\"started_at\\\":{\\\"type\\\":\\\"TIMESTAMP\\\",\\\"notNull\\\":false,\\\"unique\\\":false},\\\"heartbeat_at\\\":{\\\"type\\\":\\\"TIMESTAMP\\\",\\\"notNull\\\":false,\\\"unique\\\":false},\\\"lease_expires_at\\\":{\\\"type\\\":\\\"TIMESTAMP\\\",\\\"notNull\\\":false,\\\"unique\\\":false},\\\"queues\\\":{\\\"type\\\":\\\"JSON\\\",\\\"notNull\\\":false,\\\"unique\\\":false},\\\"status\\\":{\\\"type\\\":\\\"TEXT\\\",\\\"notNull\\\":true,\\\"unique\\\":false,\\\"default\\\":\\\"running\\\"}},\\\"indexes\\\":[{\\\"name\\\":\\\"_smrt_workers_worker_id_idx\\\",\\\"columns\\\":[\\\"worker_id\\\"],\\\"unique\\\":true},{\\\"name\\\":\\\"_smrt_workers_slug_context_idx\\\",\\\"columns\\\":[\\\"slug\\\",\\\"context\\\"]},{\\\"name\\\":\\\"_smrt_workers_created_at_idx\\\",\\\"columns\\\":[\\\"created_at\\\"]}],\\\"version\\\":\\\"2cdf9341\\\"},\\\"importPath\\\":\\\"@happyvertical/smrt-jobs\\\"},\\\"@happyvertical/smrt-jobs:SmrtWorkerCollection\\\":{\\\"name\\\":\\\"smrtworkercollection\\\",\\\"className\\\":\\\"SmrtWorkerCollection\\\",\\\"qualifiedName\\\":\\\"@happyvertical/smrt-jobs:SmrtWorkerCollection\\\",\\\"collection\\\":\\\"smrtworkers\\\",\\\"description\\\":\\\"Collection for managing _smrt_workers liveness rows.\\\",\\\"filePath\\\":\\\"src/smrt-worker.ts\\\",\\\"packageName\\\":\\\"@happyvertical/smrt-jobs\\\",\\\"fields\\\":{},\\\"methods\\\":{\\\"assertReady\\\":{\\\"name\\\":\\\"assertReady\\\",\\\"async\\\":true,\\\"parameters\\\":[],\\\"returnType\\\":\\\"Promise<void>\\\",\\\"isStatic\\\":false,\\\"isPublic\\\":true},\\\"tableReady\\\":{\\\"name\\\":\\\"tableReady\\\",\\\"async\\\":true,\\\"parameters\\\":[],\\\"returnType\\\":\\\"Promise<boolean>\\\",\\\"isStatic\\\":false,\\\"isPublic\\\":true},\\\"registerWorker\\\":{\\\"name\\\":\\\"registerWorker\\\",\\\"async\\\":true,\\\"parameters\\\":[{\\\"name\\\":\\\"input\\\",\\\"type\\\":\\\"RegisterWorkerInput\\\",\\\"optional\\\":false}],\\\"returnType\\\":\\\"Promise<void>\\\",\\\"isStatic\\\":false,\\\"isPublic\\\":true},\\\"renewLease\\\":{\\\"name\\\":\\\"renewLease\\\",\\\"async\\\":true,\\\"parameters\\\":[{\\\"name\\\":\\\"workerKey\\\",\\\"type\\\":\\\"string\\\",\\\"optional\\\":false},{\\\"name\\\":\\\"leaseTtlMs\\\",\\\"type\\\":\\\"number\\\",\\\"optional\\\":false},{\\\"name\\\":\\\"queues\\\",\\\"type\\\":\\\"string[] | null\\\",\\\"optional\\\":true,\\\"unionBranches\\\":[{\\\"type\\\":\\\"string[]\\\"},{\\\"type\\\":\\\"null\\\"}]}],\\\"returnType\\\":\\\"Promise<void>\\\",\\\"isStatic\\\":false,\\\"isPublic\\\":true},\\\"expireWorker\\\":{\\\"name\\\":\\\"expireWorker\\\",\\\"async\\\":true,\\\"parameters\\\":[{\\\"name\\\":\\\"workerKey\\\",\\\"type\\\":\\\"string\\\",\\\"optional\\\":false}],\\\"returnType\\\":\\\"Promise<void>\\\",\\\"isStatic\\\":false,\\\"isPublic\\\":true},\\\"freshLeaseWorkerKeys\\\":{\\\"name\\\":\\\"freshLeaseWorkerKeys\\\",\\\"async\\\":true,\\\"parameters\\\":[],\\\"returnType\\\":\\\"Promise<Set<string>>\\\",\\\"isStatic\\\":false,\\\"isPublic\\\":true},\\\"liveWorkerKeysForQueue\\\":{\\\"name\\\":\\\"liveWorkerKeysForQueue\\\",\\\"async\\\":true,\\\"parameters\\\":[{\\\"name\\\":\\\"queue\\\",\\\"type\\\":\\\"string\\\",\\\"optional\\\":false}],\\\"returnType\\\":\\\"Promise<Set<string>>\\\",\\\"isStatic\\\":false,\\\"isPublic\\\":true},\\\"pruneExpired\\\":{\\\"name\\\":\\\"pruneExpired\\\",\\\"async\\\":true,\\\"parameters\\\":[{\\\"name\\\":\\\"graceMs\\\",\\\"type\\\":\\\"number\\\",\\\"optional\\\":false}],\\\"returnType\\\":\\\"Promise<void>\\\",\\\"isStatic\\\":false,\\\"isPublic\\\":true}},\\\"decoratorConfig\\\":{\\\"tableName\\\":\\\"_smrt_workers\\\",\\\"api\\\":false,\\\"mcp\\\":false,\\\"cli\\\":false},\\\"extends\\\":\\\"SmrtCollection\\\",\\\"extendsTypeArg\\\":\\\"SmrtWorker\\\",\\\"exportName\\\":\\\"SmrtWorkerCollection\\\",\\\"collectionExportName\\\":\\\"SmrtWorkerCollectionCollection\\\",\\\"collectionOf\\\":\\\"@happyvertical/smrt-jobs:SmrtWorker\\\",\\\"inheritedExposure\\\":[\\\"api\\\",\\\"mcp\\\",\\\"cli\\\"],\\\"schema\\\":{\\\"tableName\\\":\\\"_smrt_workers\\\",\\\"ddl\\\":\\\"CREATE TABLE IF NOT EXISTS \\\\\\\"_smrt_workers\\\\\\\" (\\\\n \\\\\\\"_sync_origin_device_id\\\\\\\" TEXT,\\\\n \\\\\\\"_sync_revision\\\\\\\" INTEGER,\\\\n \\\\\\\"id\\\\\\\" UUID PRIMARY KEY NOT NULL,\\\\n \\\\\\\"slug\\\\\\\" TEXT NOT NULL,\\\\n \\\\\\\"context\\\\\\\" TEXT NOT NULL DEFAULT '',\\\\n \\\\\\\"created_at\\\\\\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\\\n \\\\\\\"updated_at\\\\\\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\\\n \\\\\\\"worker_id\\\\\\\" TEXT NOT NULL,\\\\n \\\\\\\"pid\\\\\\\" INTEGER,\\\\n \\\\\\\"hostname\\\\\\\" TEXT,\\\\n \\\\\\\"started_at\\\\\\\" TIMESTAMP,\\\\n \\\\\\\"heartbeat_at\\\\\\\" TIMESTAMP,\\\\n \\\\\\\"lease_expires_at\\\\\\\" TIMESTAMP,\\\\n \\\\\\\"queues\\\\\\\" JSON,\\\\n \\\\\\\"status\\\\\\\" TEXT NOT NULL DEFAULT 'running'\\\\n);\\\",\\\"columns\\\":{\\\"_sync_origin_device_id\\\":{\\\"type\\\":\\\"TEXT\\\"},\\\"_sync_revision\\\":{\\\"type\\\":\\\"INTEGER\\\"},\\\"id\\\":{\\\"type\\\":\\\"UUID\\\",\\\"primaryKey\\\":true,\\\"referenceKind\\\":\\\"id\\\",\\\"notNull\\\":true},\\\"slug\\\":{\\\"type\\\":\\\"TEXT\\\",\\\"notNull\\\":true},\\\"context\\\":{\\\"type\\\":\\\"TEXT\\\",\\\"notNull\\\":true,\\\"default\\\":\\\"\\\"},\\\"created_at\\\":{\\\"type\\\":\\\"TIMESTAMP\\\",\\\"notNull\\\":true,\\\"default\\\":\\\"current_timestamp\\\"},\\\"updated_at\\\":{\\\"type\\\":\\\"TIMESTAMP\\\",\\\"notNull\\\":true,\\\"default\\\":\\\"current_timestamp\\\"},\\\"worker_id\\\":{\\\"type\\\":\\\"TEXT\\\",\\\"notNull\\\":true,\\\"unique\\\":false},\\\"pid\\\":{\\\"type\\\":\\\"INTEGER\\\",\\\"notNull\\\":false,\\\"unique\\\":false},\\\"hostname\\\":{\\\"type\\\":\\\"TEXT\\\",\\\"notNull\\\":false,\\\"unique\\\":false},\\\"started_at\\\":{\\\"type\\\":\\\"TIMESTAMP\\\",\\\"notNull\\\":false,\\\"unique\\\":false},\\\"heartbeat_at\\\":{\\\"type\\\":\\\"TIMESTAMP\\\",\\\"notNull\\\":false,\\\"unique\\\":false},\\\"lease_expires_at\\\":{\\\"type\\\":\\\"TIMESTAMP\\\",\\\"notNull\\\":false,\\\"unique\\\":false},\\\"queues\\\":{\\\"type\\\":\\\"JSON\\\",\\\"notNull\\\":false,\\\"unique\\\":false},\\\"status\\\":{\\\"type\\\":\\\"TEXT\\\",\\\"notNull\\\":true,\\\"unique\\\":false,\\\"default\\\":\\\"running\\\"}},\\\"indexes\\\":[{\\\"name\\\":\\\"_smrt_workers_worker_id_idx\\\",\\\"columns\\\":[\\\"worker_id\\\"],\\\"unique\\\":true},{\\\"name\\\":\\\"_smrt_workers_slug_context_idx\\\",\\\"columns\\\":[\\\"slug\\\",\\\"context\\\"]},{\\\"name\\\":\\\"_smrt_workers_created_at_idx\\\",\\\"columns\\\":[\\\"created_at\\\"]}],\\\"version\\\":\\\"2cdf9341\\\"},\\\"importPath\\\":\\\"@happyvertical/smrt-jobs\\\"}},\\\"moduleType\\\":\\\"smrt\\\",\\\"smrtDependencies\\\":[\\\"@happyvertical/smrt-core\\\",\\\"@happyvertical/smrt-tenancy\\\"],\\\"browser\\\":{\\\"status\\\":\\\"server-only\\\",\\\"issues\\\":[\\\"#3615\\\",\\\"#3624\\\",\\\"#3627\\\"],\\\"reason\\\":\\\"worker_threads runner (the edge commerce inherits), node:events/crypto, bull/bullmq/cloud-tasks SDK graph\\\",\\\"via\\\":[\\\"@happyvertical/smrt-tenancy\\\"]},\\\"stampsConstructors\\\":true}\"));\n","/**\n * Opt-in policy controls for background job creation and dispatch.\n *\n * @remarks\n * These guards harden the background-jobs surface flagged by the S5 audit\n * (#1402):\n *\n * - {@link MAX_JOB_RETRIES} caps the retry count a caller can request so a\n * misconfigured `.retries(n)` cannot pin a worker on a poison job forever.\n * - {@link assertWithinTenantCreationCap} bounds how many jobs a single tenant\n * may hold in the queue at once, so one tenant cannot exhaust the shared\n * worker pool (a cross-tenant denial of service).\n * - {@link isBackgroundEligibleMethod} / {@link backgroundEligible} provide an\n * opt-in allowlist of methods that may be invoked by the runner. The runner's\n * dispatch is already bounded to existing prototype methods (no eval / dynamic\n * import), but a class can further restrict which of its methods are reachable\n * from a persisted job row.\n *\n * All three live in and are enforced by this package (`@happyvertical/smrt-jobs`).\n * Other packages apply the marker (`smrt-reports`, `smrt-support`,\n * `smrt-fields`), but the only thing that reads it is `TaskRunner`'s dispatch in\n * `runner.ts`. `@happyvertical/smrt-agents` neither imports nor honours it (it depends on\n * this package only for the cron parser). Marking a method does **not** make it\n * background-eligible anywhere outside the jobs runner.\n */\n\n/**\n * Hard ceiling on retry attempts a caller may request via `.retries(n)` /\n * `bg(..., { retries })`. Requests above this are clamped (not rejected) so\n * existing callers keep working while the worst case stays bounded.\n */\nexport const MAX_JOB_RETRIES = 25;\n\n/**\n * Default maximum number of non-terminal (pending/running) jobs a single\n * tenant may hold in the queue at once. Configurable per call; `0` / negative\n * disables the cap.\n */\nexport const DEFAULT_TENANT_JOB_CAP = 10_000;\n\n/**\n * Clamp a requested retry count to {@link MAX_JOB_RETRIES}.\n *\n * @param requested - The retry count supplied by the caller.\n * @returns A non-negative integer no greater than {@link MAX_JOB_RETRIES}.\n */\nexport function clampRetries(requested: number): number {\n if (Number.isNaN(requested) || requested < 0) {\n return 0;\n }\n if (requested === Number.POSITIVE_INFINITY) {\n return MAX_JOB_RETRIES;\n }\n return Math.min(Math.floor(requested), MAX_JOB_RETRIES);\n}\n\n/**\n * Error thrown when a tenant exceeds its allowed in-flight job count.\n */\nexport class TenantJobCapExceededError extends Error {\n constructor(\n public readonly tenantId: string,\n public readonly cap: number,\n public readonly current: number,\n ) {\n super(\n `Tenant \"${tenantId}\" has reached its background-job cap ` +\n `(${current}/${cap} in-flight). Refusing to enqueue another job.`,\n );\n this.name = 'TenantJobCapExceededError';\n }\n}\n\n/**\n * Throw {@link TenantJobCapExceededError} when a tenant is at or above its cap.\n *\n * @param tenantId - Tenant the new job would belong to (`null` = global; not\n * subject to the per-tenant cap).\n * @param current - Current count of non-terminal jobs for the tenant.\n * @param cap - Maximum allowed; `<= 0` disables the check.\n */\nexport function assertWithinTenantCreationCap(\n tenantId: string | null | undefined,\n current: number,\n cap: number,\n): void {\n if (!tenantId || cap <= 0) return;\n if (current >= cap) {\n throw new TenantJobCapExceededError(tenantId, cap, current);\n }\n}\n\n/**\n * Class shape that opts into a background-method allowlist by declaring a\n * static set/array of method names.\n */\nexport interface BackgroundEligibleClass {\n /**\n * Method names that may be invoked by `TaskRunner`. When present (even if\n * empty), it is treated as an exhaustive allowlist. When absent, the runner\n * falls back to its default behaviour (any existing method).\n */\n backgroundEligibleMethods?: ReadonlyArray<string> | ReadonlySet<string>;\n}\n\n/**\n * Add method names to a class's background-eligible allowlist.\n *\n * Installs/extends a static `backgroundEligibleMethods` set on the constructor.\n * Once any method is marked, the runner refuses to dispatch a job whose\n * `method` is not in the set — turning the dispatch surface from \"any prototype\n * method\" into an explicit contract. Use this when applying the\n * {@link backgroundEligible} decorator is inconvenient. Non-decorator code can\n * skip the helper entirely and declare the static array directly, as\n * `smrt-fields` does in `usage-learning.ts`.\n *\n * @param ctor - The class constructor to annotate.\n * @param methods - Method names to allow.\n */\nexport function markBackgroundEligible(\n ctor: object,\n ...methods: string[]\n): void {\n const target = ctor as { backgroundEligibleMethods?: ReadonlySet<string> };\n const existing = target.backgroundEligibleMethods;\n const set =\n existing instanceof Set\n ? new Set<string>(existing)\n : new Set<string>(existing ?? []);\n for (const method of methods) set.add(method);\n target.backgroundEligibleMethods = set;\n}\n\n/**\n * Decorator: mark a method as background-eligible.\n *\n * This is **restrictive, not enabling**. Without it, `TaskRunner` will dispatch\n * any existing prototype method; the first `@backgroundEligible()` on a class\n * closes that surface and turns the set into an exhaustive allowlist, so every\n * *other* method on that class stops being reachable from a persisted job row.\n * Adding it to one method of an existing class is therefore a behaviour change\n * for its siblings — mark all the methods you dispatch, or none of them.\n *\n * This is a legacy (`experimentalDecorators`) method decorator — the mode the\n * SMRT monorepo compiles with. Applying it (one or more times) builds up the\n * static `backgroundEligibleMethods` allowlist on the owning class.\n *\n * @example\n * ```ts\n * class Report extends SmrtObject {\n * \\@backgroundEligible()\n * async regenerate() {} // reachable from a job\n *\n * async deleteEverything() {} // NOT reachable from a job\n * }\n * ```\n */\nexport function backgroundEligible() {\n return (\n target: object,\n propertyKey: string | symbol,\n descriptor?: PropertyDescriptor,\n ): PropertyDescriptor | undefined => {\n // Legacy method decorators receive the prototype as `target`; the class\n // constructor (where we keep the static allowlist) is `target.constructor`.\n const ctor = (target as { constructor: object }).constructor;\n markBackgroundEligible(ctor, String(propertyKey));\n return descriptor;\n };\n}\n\n/**\n * Resolve the declared allowlist for a class, if any.\n *\n * @param ctor - The target object's constructor.\n * @returns A `Set` of allowed method names, or `null` when the class did not\n * opt in (runner should fall back to default behaviour).\n */\nexport function getBackgroundEligibleMethods(\n ctor: unknown,\n): ReadonlySet<string> | null {\n const declared = (ctor as BackgroundEligibleClass | undefined)\n ?.backgroundEligibleMethods;\n if (declared == null) return null;\n return declared instanceof Set ? declared : new Set(declared);\n}\n\n/**\n * Whether a method may be invoked by the runner for a given target class.\n *\n * @param ctor - Constructor of the resolved target class.\n * @param method - Method name from the persisted job row.\n * @returns `true` when the class declared no allowlist (default) or when the\n * method is on the allowlist; `false` when an allowlist exists and excludes\n * the method.\n */\nexport function isBackgroundEligibleMethod(\n ctor: unknown,\n method: string,\n): boolean {\n const allow = getBackgroundEligibleMethods(ctor);\n if (allow == null) return true;\n return allow.has(method);\n}\n","import type { JobExecutionContext } from './logger-extension.js';\n\n/**\n * Named job handlers (#5005).\n *\n * A job targets either a model method (`objectType` is a registered class,\n * `method` one of its methods) or a handler registered here under a\n * namespaced name. A handler job is stored in `_smrt_jobs` in a reserved\n * form, with no schema change:\n *\n * - `object_type` = `handler:<name>` (see {@link JOB_HANDLER_TARGET_PREFIX})\n * - `method` = `handle` (see {@link JOB_HANDLER_METHOD})\n * - `object_id` = NULL\n * - `args` = the handler's JSON payload\n *\n * The `handler:` prefix keeps a handler name out of the model namespace: a\n * name such as `@happyvertical/smrt-workflows:workflow-run` has the grammar of\n * a qualified class name, and the registry's qualified-name fallback looks a\n * class up by that tail (`workflow-run` is not a class name today, but the\n * namespaces would overlap). `handler:@…` is not a qualified class name (its\n * package part does not start with `@`) and cannot be a class key.\n */\n\n/** Prefix that marks a stored job target as a named handler. */\nexport const JOB_HANDLER_TARGET_PREFIX = 'handler:';\n\n/** The fixed `method` value of every handler job row. */\nexport const JOB_HANDLER_METHOD = 'handle';\n\n/**\n * Most handlers one process may register. A runner's claim names each of its\n * handlers as one bound parameter (#5005 claim filter), so the registry is\n * capped to keep that statement inside every engine's parameter limit.\n */\nexport const MAX_JOB_HANDLERS = 256;\n\n/** Longest accepted handler name. */\nconst MAX_HANDLER_NAME_LENGTH = 200;\n\n/**\n * `<package>:<name>`: an npm package name (scoped or not), a colon, and a\n * lowercase kebab-case local name, optionally dotted (`run.step`).\n */\nconst HANDLER_NAME_PATTERN =\n /^(?:@[a-z0-9][a-z0-9._~-]*\\/)?[a-z0-9][a-z0-9._~-]*:[a-z][a-z0-9-]*(?:\\.[a-z][a-z0-9-]*)*$/;\n\n/** A job payload: a JSON object, exactly like a model job's `args`. */\nexport type JobHandlerPayload = Record<string, unknown>;\n\n/**\n * A named job handler. It receives the job's payload and the same runner\n * execution context a model method receives: job id, attempt, tenant, queue,\n * logger, `signal`, `event`/`progress`/`log`, and — on a runner started with\n * `claimFencing: true` — the claim read by `getJobClaim(context)`.\n * `context.job.handler` names the handler. Lease renewal is per worker, not\n * per job: the runner renews its own lease while the handler runs.\n */\nexport type JobHandler<\n TPayload extends JobHandlerPayload = JobHandlerPayload,\n TResult = unknown,\n> = (\n payload: TPayload,\n context: JobExecutionContext,\n) => Promise<TResult> | TResult;\n\n/** The stored target of a handler job. */\nexport interface JobHandlerTarget {\n objectType: string;\n method: string;\n}\n\n/** A handler name that is not `<package>:<name>`. */\nexport class JobHandlerNameError extends TypeError {\n constructor(readonly handler: unknown) {\n super(\n `Invalid job handler name ${JSON.stringify(handler)}: expected \"<package>:<name>\", e.g. \"@happyvertical/smrt-workflows:workflow-run\"`,\n );\n this.name = 'JobHandlerNameError';\n }\n}\n\n/** A second registration under a name that is already registered. */\nexport class JobHandlerAlreadyRegisteredError extends Error {\n constructor(readonly handler: string) {\n super(`Job handler already registered: ${handler}`);\n this.name = 'JobHandlerAlreadyRegisteredError';\n }\n}\n\n/** A registration past {@link MAX_JOB_HANDLERS}. */\nexport class JobHandlerLimitError extends RangeError {\n constructor(readonly handler: string) {\n super(\n `Cannot register job handler ${handler}: a process may register at most ${MAX_JOB_HANDLERS} job handlers`,\n );\n this.name = 'JobHandlerLimitError';\n }\n}\n\n/**\n * Registration or removal while a TaskRunner in this process is running.\n * Register every handler before `runner.start()`.\n */\nexport class JobHandlerRegistrationClosedError extends Error {\n constructor(readonly handler: string) {\n super(\n `Cannot change job handler ${handler} while a TaskRunner is running; register handlers before runner.start()`,\n );\n this.name = 'JobHandlerRegistrationClosedError';\n }\n}\n\n/**\n * The runner that claimed a handler job has no handler under its name. The\n * job fails terminally on that claim (failure kind `handler-unregistered`),\n * whatever its `maxAttempts`. A runner claims only the handler jobs it has\n * registered, so this is the backstop for a claim made without that filter.\n */\nexport class JobHandlerUnregisteredError extends Error {\n /** Read by the runner's retry hints: never retried. */\n readonly retryable = false;\n constructor(readonly handler: string) {\n super(`Job handler not registered: ${handler}`);\n this.name = 'JobHandlerUnregisteredError';\n }\n}\n\n/** A handler job row that is not in the canonical handler form. */\nexport class JobHandlerTargetError extends Error {\n /** Read by the runner's retry hints: never retried. */\n readonly retryable = false;\n constructor(message: string) {\n super(message);\n this.name = 'JobHandlerTargetError';\n }\n}\n\nconst REGISTRY_KEY = '__smrtJobHandlers';\n\ninterface JobHandlerRegistryState {\n handlers: Map<string, JobHandler>;\n /** Worker keys of running TaskRunners; registration is closed while any. */\n sealedBy: Set<string>;\n}\n\ntype GlobalWithJobHandlers = typeof globalThis & {\n [REGISTRY_KEY]?: JobHandlerRegistryState;\n};\n\nfunction registry(): JobHandlerRegistryState {\n const g = globalThis as GlobalWithJobHandlers;\n let state = g[REGISTRY_KEY];\n if (!state) {\n // Process-wide singleton, like the live-worker set: it survives HMR and\n // a duplicated module instance (the runner is bundled into a chunk).\n state = { handlers: new Map(), sealedBy: new Set() };\n g[REGISTRY_KEY] = state;\n }\n return state;\n}\n\n/** True when `name` is a valid namespaced handler name. */\nexport function isJobHandlerName(name: unknown): name is string {\n return (\n typeof name === 'string' &&\n name.length <= MAX_HANDLER_NAME_LENGTH &&\n HANDLER_NAME_PATTERN.test(name)\n );\n}\n\n/** Throw {@link JobHandlerNameError} unless `name` is a valid handler name. */\nexport function assertJobHandlerName(name: unknown): asserts name is string {\n if (!isJobHandlerName(name)) throw new JobHandlerNameError(name);\n}\n\nfunction assertRegistrationOpen(name: string): void {\n if (registry().sealedBy.size > 0)\n throw new JobHandlerRegistrationClosedError(name);\n}\n\n/**\n * Register a named job handler for this process. Call before any\n * `TaskRunner.start()`: a runner snapshots the registry when it starts, and\n * registration while one is running throws\n * {@link JobHandlerRegistrationClosedError}.\n *\n * @param name - Namespaced `<package>:<name>`, e.g. `@scope/pkg:workflow-run`.\n * @param handler - Called with the job payload and runner execution context.\n * @throws JobHandlerNameError, JobHandlerAlreadyRegisteredError,\n * JobHandlerLimitError, JobHandlerRegistrationClosedError\n */\nexport function registerJobHandler<\n TPayload extends JobHandlerPayload = JobHandlerPayload,\n>(name: string, handler: JobHandler<TPayload>): void {\n assertJobHandlerName(name);\n if (typeof handler !== 'function')\n throw new TypeError(`Job handler ${name} must be a function`);\n assertRegistrationOpen(name);\n const { handlers } = registry();\n if (handlers.has(name)) throw new JobHandlerAlreadyRegisteredError(name);\n if (handlers.size >= MAX_JOB_HANDLERS) throw new JobHandlerLimitError(name);\n handlers.set(name, handler as JobHandler);\n}\n\n/**\n * Remove a registered handler (tests and teardown). Closed while a runner is\n * running, like registration.\n * @returns Whether a handler was registered under `name`.\n */\nexport function unregisterJobHandler(name: string): boolean {\n assertRegistrationOpen(name);\n return registry().handlers.delete(name);\n}\n\n/** Names of the handlers registered in this process, sorted. */\nexport function listJobHandlers(): string[] {\n return [...registry().handlers.keys()].sort();\n}\n\n/** The stored job target for a handler name. */\nexport function jobHandlerTarget(name: string): JobHandlerTarget {\n assertJobHandlerName(name);\n return {\n objectType: `${JOB_HANDLER_TARGET_PREFIX}${name}`,\n method: JOB_HANDLER_METHOD,\n };\n}\n\n/** True when a stored `objectType` is in the reserved handler form. */\nexport function isJobHandlerTarget(objectType: unknown): boolean {\n return (\n typeof objectType === 'string' &&\n objectType.startsWith(JOB_HANDLER_TARGET_PREFIX)\n );\n}\n\n/**\n * The handler name of a stored `objectType`, or null for a model target. The\n * name is returned as stored; it may be invalid on a row not written through\n * the enqueue API.\n */\nexport function jobHandlerName(objectType: unknown): string | null {\n return isJobHandlerTarget(objectType)\n ? (objectType as string).slice(JOB_HANDLER_TARGET_PREFIX.length)\n : null;\n}\n\n/** @internal Close registration for a starting runner; returns its snapshot. */\nexport function sealJobHandlerRegistry(\n workerKey: string,\n): ReadonlyMap<string, JobHandler> {\n const state = registry();\n state.sealedBy.add(workerKey);\n return new Map(state.handlers);\n}\n\n/** @internal Reopen registration when that runner has stopped. */\nexport function releaseJobHandlerRegistry(workerKey: string): void {\n registry().sealedBy.delete(workerKey);\n}\n","import {\n field,\n SmrtCollection,\n SmrtObject,\n smrt,\n} from '@happyvertical/smrt-core';\n\n/**\n * Store-owned serialization row for a tenant-partitioned job deduplication key.\n *\n * The opaque hash includes tenant identity. Job pointers deliberately have no\n * physical FK: job retention can prune a terminal job before the key is reused.\n * Generated access is disabled; callers use SmrtJobCollection.enqueueJob().\n */\n@smrt({\n tableName: '_smrt_job_dedupe_slots',\n api: false,\n cli: false,\n mcp: false,\n})\nexport class SmrtJobDedupeSlot extends SmrtObject { static __smrtPackage__ = \"@happyvertical/smrt-jobs\";\n /** SHA-256 identity of the tenant and caller key. */\n @field({\n type: 'text',\n required: true,\n requiredFor: 'idempotency',\n unique: true,\n })\n slotKey: string = '';\n\n /** Last admitted job, which may already have been pruned by retention. */\n @field({ type: 'text', nullable: true })\n jobId: string | null = null;\n}\n\n/** Internal collection for provisioning the registered store-owned model. */\nexport class SmrtJobDedupeSlotCollection extends SmrtCollection<SmrtJobDedupeSlot> {\n static readonly _itemClass = SmrtJobDedupeSlot;\n}\n","import {\n detectEngine,\n SQLITE_BUSY_TIMEOUT_MS,\n setBusyTimeoutIfUnset,\n} from '@happyvertical/smrt-core';\nimport type {\n DatabaseInterface,\n ReopenOptions,\n DatabaseEngine as SqlEngine,\n} from '@happyvertical/sql';\nimport { createId } from '@happyvertical/utils';\n\ntype DatabaseEngine = ReturnType<typeof detectEngine>;\n\n/**\n * Worker liveness primitives shared by {@link ../runner.js} and\n * {@link ../schedule-runner.js}.\n *\n * Job recovery keys on whether a job's *owning worker* is alive, never on\n * per-job heartbeat freshness (issue #1474). \"Alive\" has two independent\n * sources, combined by {@link isWorkerAlive}:\n *\n * 1. **Process-global live set** — an in-memory {@link Set} of worker keys\n * whose runner is live *in this process*. Checked synchronously, so it can\n * never be starved by a CPU-bound handler holding the event loop. Covers\n * every same-process topology (a runner's own jobs, a co-located\n * ScheduleRunner, a second in-process runner).\n * 2. **Database lease** — a `_smrt_workers` row whose `lease_expires_at` is\n * still in the future. Covers cross-process recovery. The lease is renewed\n * by the owning runner; a dead worker stops renewing and its lease expires.\n *\n * The live set takes precedence: a worker live in this process is alive even\n * if its database lease looks stale.\n *\n * The lease is compared against the recovering host's clock (the same approach\n * the previous heartbeat recovery used), so it is no more sensitive to clock\n * skew than the code it replaces. For eligible engines the lease is renewed off\n * the main loop by a worker thread (see worker-liveness-ticker.ts) so a blocked\n * handler can't starve it; otherwise it is renewed on the main loop and the\n * live set covers same-process correctness.\n */\n\nconst LIVE_WORKERS_KEY = '__smrtLiveWorkers';\n\ntype GlobalWithLiveWorkers = typeof globalThis & {\n [LIVE_WORKERS_KEY]?: Set<string>;\n};\n\nfunction liveWorkers(): Set<string> {\n const g = globalThis as GlobalWithLiveWorkers;\n let set = g[LIVE_WORKERS_KEY];\n if (!set) {\n // Singleton on globalThis so it survives HMR / duplicate module instances,\n // mirroring the ObjectRegistry pattern.\n set = new Set<string>();\n g[LIVE_WORKERS_KEY] = set;\n }\n return set;\n}\n\n/** Mark a worker key as live in this process. */\nexport function registerLiveWorker(workerKey: string): void {\n liveWorkers().add(workerKey);\n}\n\n/** Remove a worker key from this process's live set. */\nexport function unregisterLiveWorker(workerKey: string): void {\n liveWorkers().delete(workerKey);\n}\n\n/** Whether a worker key is live in this process. */\nexport function isLiveWorker(workerKey: string): boolean {\n return liveWorkers().has(workerKey);\n}\n\n/** Snapshot of every worker key live in this process. */\nexport function liveWorkerKeys(): Set<string> {\n return new Set(liveWorkers());\n}\n\n/**\n * Whether a worker is alive: live in *this* process (synchronous truth, never\n * starved), or holding a fresh database lease in some process. `null`/unknown\n * worker keys are never alive.\n */\nexport function isWorkerAlive(\n workerKey: string | null | undefined,\n freshLeaseKeys: Set<string>,\n): boolean {\n if (!workerKey) return false;\n return isLiveWorker(workerKey) || freshLeaseKeys.has(workerKey);\n}\n\n/**\n * Build a per-incarnation-unique worker key.\n *\n * Recovery treats a worker key as the unit of liveness, so the key must be\n * unique per process incarnation: a runner that crashes and restarts under the\n * same configured `id` must get a *new* key, otherwise its orphaned `running`\n * jobs would look owned by the live restart and never be recovered. We append\n * a random token to the (optional) configured id, which also keeps the\n * human-facing runner id stable for logs/events.\n */\nexport function createWorkerKey(baseId: string): string {\n return `${baseId}~${createId().slice(0, 8)}`;\n}\n\n/**\n * The connection URL, honoring adapters that leave `db.url` empty and carry the\n * real URL on `db.config.url`. Used consistently for engine detection, the\n * in-memory check, and the URL handed to the off-loop thread so they never\n * disagree.\n */\nexport function resolveUrl(db: DatabaseInterface): string {\n const withConfig = db as DatabaseInterface & { config?: { url?: string } };\n return db.url || withConfig.config?.url || '';\n}\n\n/**\n * Tune a SQLite connection for the off-loop liveness topology.\n *\n * The runner's main connection and the off-loop ticker's connection both touch\n * the same file. Stock libsql/SQLite opens in rollback-journal mode with no busy\n * timeout, so the instant two connections contend it returns `SQLITE_BUSY` —\n * surfacing as a flaky \"Failed to execute raw query\" under CI load. WAL lets\n * readers run concurrently with the single writer, and `busy_timeout` makes a\n * contended writer wait for the lock instead of failing immediately. Both are\n * idempotent and file-level (WAL persists for every connection to the file).\n *\n * Best-effort: a PRAGMA failure must never break startup — the in-process live\n * set keeps same-process recovery correct regardless. Callers gate this on a\n * SQLite engine so it is never issued to Postgres.\n */\nexport async function tuneSqliteForConcurrency(\n db: DatabaseInterface,\n): Promise<void> {\n try {\n // Only when unset: a shared collection connection keeps its shorter\n // main-thread wait (#4978) and the runtime's own keeps its 5000.\n await setBusyTimeoutIfUnset(db, SQLITE_BUSY_TIMEOUT_MS);\n await db.query('PRAGMA journal_mode = WAL');\n } catch {\n // Best-effort connection tuning.\n }\n}\n\nconst enabledPgliteClients = new WeakSet<object>();\n\n/**\n * Opt a shared SDK PGlite client into PostgreSQL job SQL and main-loop leases.\n * Call before creating jobs collections or starting runners on that client.\n * Detection alone never changes existing consumers' engine selection.\n * @param db - SDK connection whose public client exposes dumpDataDir.\n */\nexport function enablePgliteJobs(db: DatabaseInterface): void {\n const client = db.client as { dumpDataDir?: unknown } | undefined;\n if (!client || typeof client.dumpDataDir !== 'function')\n throw new Error('enablePgliteJobs requires an SDK PGlite client');\n enabledPgliteClients.add(client);\n}\n\n/** Only explicitly enabled clients use the PGlite jobs path. */\nexport function isPglite(db: DatabaseInterface): boolean {\n return !!db.client && enabledPgliteClients.has(db.client as object);\n}\n\n/** Resolve the database engine for a connection. */\nexport function resolveEngine(db: DatabaseInterface): DatabaseEngine {\n if (isPglite(db)) return 'postgres';\n const withConfig = db as DatabaseInterface & {\n config?: { type?: string };\n type?: string;\n };\n const type = withConfig.type || withConfig.config?.type;\n return detectEngine(resolveUrl(db), type);\n}\n\n/**\n * Whether a connection points at an in-memory SQLite database. In-memory\n * databases are single-process (nothing to recover cross-process) and a second\n * connection cannot see the same data, so the off-loop liveness thread is\n * skipped for them.\n */\nexport function isInMemory(db: DatabaseInterface): boolean {\n const url = resolveUrl(db).toLowerCase();\n return (\n url === ':memory:' ||\n url.includes('mode=memory') ||\n url.includes('file::memory:')\n );\n}\n\n/**\n * How the off-loop liveness thread gets its database connection, or why it\n * must not run.\n *\n * - `reopen`: file-backed SQLite whose connection can be reopened on the same\n * engine (`db.engine` plus `db.reopenOptions()`). The thread opens exactly\n * those options and checks that the engine it got is `engine`.\n * - `url`: PostgreSQL, which has no second-engine hazard. The thread builds its\n * own pooled connection from the URL, as it always has.\n * - `none`: no safe second connection; the runner renews the lease on its own\n * connection from the main loop and logs `reason` once.\n *\n * Two SQLite engines (`node:sqlite`, `@libsql/client`) hold their own copy of\n * SQLite whose file locks do not coordinate, so a second connection on the\n * other engine can corrupt a WAL file (#4978). A connection that does not say\n * which engine it uses is treated as unsafe to share.\n */\nexport type LivenessConnectionPlan =\n | {\n kind: 'reopen';\n engine: SqlEngine;\n reopen: ReopenOptions;\n }\n | { kind: 'url'; url: string; type: string }\n | {\n kind: 'none';\n reason: string;\n /**\n * True where a liveness thread used to run and now cannot (file-backed\n * SQLite without a same-engine connection, or secure SQLite on Windows).\n * False for engines that never had a usable second connection\n * (in-memory SQLite, DuckDB, JSON), where main-loop renewal is the\n * long-standing design and not a degradation.\n */\n degraded: boolean;\n };\n\n/** Decide how (and whether) the liveness thread may open its connection. */\nexport function planLivenessConnection(\n db: DatabaseInterface,\n platform: NodeJS.Platform = process.platform,\n): LivenessConnectionPlan {\n if (isPglite(db)) {\n // No independent backend can open this WASM instance.\n return {\n kind: 'none',\n degraded: false,\n reason: 'a PGlite instance cannot be reached by a second connection',\n };\n }\n const engine = resolveEngine(db);\n if (engine === 'postgres') {\n return { kind: 'url', url: resolveUrl(db), type: engine };\n }\n if (engine !== 'sqlite') {\n return {\n kind: 'none',\n degraded: false,\n reason: `the ${engine} engine has one owner per database`,\n };\n }\n if (isInMemory(db)) {\n return {\n kind: 'none',\n degraded: false,\n reason:\n 'an in-memory SQLite database cannot be reached by a second connection',\n };\n }\n const dbEngine = db.engine;\n if (dbEngine !== 'node-sqlite' && dbEngine !== 'libsql') {\n return {\n kind: 'none',\n degraded: true,\n reason:\n 'the connection does not report which SQLite engine it uses, so a second connection may use a different engine on the same file',\n };\n }\n if (typeof db.reopenOptions !== 'function') {\n return {\n kind: 'none',\n degraded: true,\n reason: 'the connection cannot give options to reopen the same database',\n };\n }\n let reopen: ReopenOptions;\n try {\n reopen = db.reopenOptions();\n } catch (error) {\n return {\n kind: 'none',\n degraded: true,\n reason: `the connection cannot be reopened on the same engine (${\n error instanceof Error ? error.message : String(error)\n })`,\n };\n }\n if (\n platform === 'win32' &&\n dbEngine === 'node-sqlite' &&\n (reopen as { secureFile?: unknown }).secureFile\n ) {\n return {\n kind: 'none',\n degraded: true,\n reason:\n 'on Windows the secure SQLite custody verifier cannot be handed to a worker thread',\n };\n }\n return { kind: 'reopen', engine: dbEngine, reopen };\n}\n","// Self-register this package's manifest for consumers that import via this\n// subpath without the main entry. See src/__smrt-register__.ts (issue #1132).\nimport './__smrt-register__.js';\n\nimport {\n type detectEngine,\n ensureJobEventsSystemTableCompatibility,\n field,\n foreignKey,\n SmrtCollection,\n SmrtObject,\n smrt,\n} from '@happyvertical/smrt-core';\nimport {\n getTenantId,\n TenantScoped,\n tenantId,\n} from '@happyvertical/smrt-tenancy';\nimport type { DatabaseInterface } from '@happyvertical/sql';\nimport { resolveEngine } from './worker-liveness.js';\n\nexport type SmrtJobEventType = 'status' | 'progress' | 'log' | 'error' | string;\n\nexport type SmrtJobEventLevel = 'debug' | 'info' | 'warn' | 'error';\n\nexport interface SmrtJobEventData {\n tenantId?: string | null;\n jobId: string;\n type?: SmrtJobEventType;\n level?: SmrtJobEventLevel;\n stage?: string | null;\n progress?: number | null;\n message?: string;\n data?: Record<string, unknown>;\n createdAt?: Date;\n}\n\nexport interface JobEventCursor {\n createdAt: string | Date;\n id: string;\n}\n\nexport interface ListJobEventsOptions {\n tenantId?: string | null;\n limit?: number;\n since?: string | Date;\n afterId?: string;\n cursor?: string | JobEventCursor;\n}\n\nexport type SmrtJobTerminalStatus = 'completed' | 'failed' | 'cancelled';\n\nexport interface SmrtJobTerminalOutcome {\n eventId: string;\n jobId: string;\n tenantId: string | null;\n status: SmrtJobTerminalStatus;\n queue: string;\n objectType: string;\n method: string;\n attempts: number;\n /**\n * Why a `failed` job failed. `handler-unregistered` (#5005): the runner that\n * claimed a handler job had no handler registered under its name.\n * `handler-unclaimed` (#5005): no runner registered for the handler claimed\n * it before the unclaimed deadline; it never ran.\n */\n failureKind?:\n | 'execution'\n | 'timeout'\n | 'stale-recovery'\n | 'handler-unregistered'\n | 'handler-unclaimed';\n completedAt: string;\n cursor: string;\n}\n\nexport interface ListTerminalOutcomesOptions {\n /** Explicit tenant boundary. Pass null only for global jobs. */\n tenantId: string | null;\n limit?: number;\n since?: string | Date;\n before?: string | JobEventCursor;\n statuses?: SmrtJobTerminalStatus[];\n queues?: string[];\n objectTypes?: string[];\n methods?: string[];\n}\n\n/** Exact-job lookup; optional dispatch outcome fields bind a current job snapshot. */\nexport interface GetTerminalOutcomeOptions {\n tenantId: string | null;\n attempts?: number;\n completedAt?: string;\n}\n\nexport interface SmrtJobTerminalOutcomePage {\n outcomes: SmrtJobTerminalOutcome[];\n limit: number;\n candidateLimit: 1000;\n truncated: boolean;\n nextCursor: string | null;\n}\n\nconst JOB_EVENT_STORAGE_COLUMNS = [\n 'id',\n 'slug',\n 'context',\n 'created_at',\n 'updated_at',\n 'tenant_id',\n 'job_id',\n 'type',\n 'level',\n 'stage',\n 'progress',\n 'message',\n 'data',\n].join(', ');\nconst TERMINAL_OUTCOME_CANDIDATE_LIMIT = 1000 as const;\n\n@smrt({\n tableName: '_smrt_job_events',\n // Fail closed: same reasoning as SmrtJob. `_smrt_job_events` carries job\n // progress/log/error payloads for every tenant; an `optional`-mode generated\n // read reached without tenant context returns UNFILTERED rows. Consumers read\n // events through the collection's tenant-aware methods (listByJob /\n // listSinceCursor, which require an explicit tenantId or ambient context), not\n // through generated routes — so we do not generate a read surface here\n // (S5 audit #1402).\n api: false,\n // In-process operator commands only (http: false). skipApiCheck acknowledges\n // that these CLI reads intentionally have no HTTP/API route now that api is\n // disabled (S5 audit #1402).\n cli: { include: ['list', 'get'], http: false, skipApiCheck: true },\n mcp: false,\n})\n// Keep the data model tenant-scoped (defense in depth); the @tenantId() field\n// alone does not make collection reads filter by tenant. `optional` keeps global\n// (NULL tenant) events working (S5 audit #1402).\n@TenantScoped({ mode: 'optional' })\nexport class SmrtJobEvent extends SmrtObject { static __smrtPackage__ = \"@happyvertical/smrt-jobs\";\n @tenantId({ nullable: true })\n tenantId: string | null | undefined = undefined;\n\n // Job events intentionally outlive completed job rows (30-day event\n // retention vs 7-day completed-job retention). Keep the typed relationship,\n // index, and retained job identifier, but do not install a physical FK or\n // app-side delete action that would make the documented retention sweep\n // impossible (#2375, #2413).\n @foreignKey('SmrtJob', {\n required: true,\n requiredFor: 'identity',\n constraint: false,\n })\n jobId: string = '';\n\n @field({ type: 'text', required: true, default: 'log' })\n type: SmrtJobEventType = 'log';\n\n @field({ type: 'text', required: true, default: 'info' })\n level: SmrtJobEventLevel = 'info';\n\n @field({ type: 'text', nullable: true })\n stage: string | null = null;\n\n @field({ type: 'integer', nullable: true })\n progress: number | null = null;\n\n @field({ type: 'text', default: '' })\n message: string = '';\n\n @field({ type: 'json' })\n data: Record<string, unknown> = {};\n\n @field({ type: 'datetime', required: true })\n createdAt: Date = new Date();\n\n toCursor(): string {\n const createdAt =\n this.createdAt instanceof Date\n ? this.createdAt.toISOString()\n : String(this.createdAt);\n return `${createdAt}|${this.id ?? ''}`;\n }\n}\n\nfunction normalizeLimit(limit: number | undefined): number {\n const numeric =\n typeof limit === 'number' && Number.isFinite(limit) ? limit : 250;\n return Math.max(1, Math.min(1000, Math.floor(numeric)));\n}\n\nfunction normalizeProgress(progress: unknown): number | null {\n if (typeof progress !== 'number' || !Number.isFinite(progress)) {\n return null;\n }\n\n return Math.max(0, Math.min(100, Math.round(progress)));\n}\n\nfunction parseCursor(cursor: string | JobEventCursor): JobEventCursor {\n if (typeof cursor !== 'string') return cursor;\n const separator = cursor.lastIndexOf('|');\n if (separator === -1) {\n return { createdAt: cursor, id: '' };\n }\n return {\n createdAt: cursor.slice(0, separator),\n id: cursor.slice(separator + 1),\n };\n}\n\nfunction normalizeCursorDate(value: string | Date): string {\n if (value instanceof Date) {\n return value.toISOString();\n }\n\n const parsed = new Date(value);\n if (!Number.isNaN(parsed.getTime())) {\n return parsed.toISOString();\n }\n\n return value;\n}\n\nfunction databaseEngine(\n db: DatabaseInterface,\n): ReturnType<typeof detectEngine> {\n const configured = db as DatabaseInterface & {\n config?: { type?: string; url?: string };\n type?: string;\n client?: { constructor?: { name?: string }; connection?: unknown };\n };\n const engine = resolveEngine(db);\n const clientName = configured.client?.constructor?.name?.toLowerCase() ?? '';\n if (\n engine === 'sqlite' &&\n (clientName.includes('duckdb') ||\n configured.client?.connection !== undefined)\n ) {\n return 'duckdb';\n }\n return engine;\n}\n\nfunction getQueryRows(result: unknown): Record<string, unknown>[] {\n if (Array.isArray(result)) {\n return result as Record<string, unknown>[];\n }\n\n return (result as { rows?: Record<string, unknown>[] }).rows ?? [];\n}\n\nexport class SmrtJobEventCollection extends SmrtCollection<SmrtJobEvent> {\n static readonly _itemClass = SmrtJobEvent;\n\n override async initialize(): Promise<this> {\n await super.initialize();\n await ensureJobEventsSystemTableCompatibility(this.db);\n return this;\n }\n\n async append(input: SmrtJobEventData): Promise<SmrtJobEvent> {\n return this.create({\n tenantId: input.tenantId,\n jobId: input.jobId,\n type: input.type ?? 'log',\n level: input.level ?? 'info',\n stage: input.stage ?? null,\n progress: normalizeProgress(input.progress),\n message: input.message ?? '',\n data: input.data ?? {},\n createdAt: input.createdAt ?? new Date(),\n });\n }\n\n async listByJob(\n jobId: string,\n options: ListJobEventsOptions = {},\n ): Promise<SmrtJobEvent[]> {\n return this.listSinceCursor({\n ...options,\n jobId,\n });\n }\n\n async listSinceCursor(\n options: ListJobEventsOptions & { jobId?: string } = {},\n ): Promise<SmrtJobEvent[]> {\n const where: string[] = [];\n const params: unknown[] = [];\n\n if (options.jobId) {\n where.push('job_id = ?');\n params.push(options.jobId);\n }\n\n this.addTenantPredicate(where, params, options);\n\n if (options.cursor) {\n const cursor = parseCursor(options.cursor);\n const createdAt = await this.resolveCursorCreatedAt(cursor, options);\n const createdAtExpression = this.createdAtComparableExpression();\n where.push(\n `(${createdAtExpression} > ? OR (${createdAtExpression} = ? AND id > ?))`,\n );\n params.push(createdAt, createdAt, cursor.id);\n } else if (options.since) {\n where.push(`${this.createdAtComparableExpression()} > ?`);\n params.push(normalizeCursorDate(options.since));\n }\n\n if (options.afterId) {\n where.push('id > ?');\n params.push(options.afterId);\n }\n\n params.push(normalizeLimit(options.limit));\n\n const whereSql = where.length ? `WHERE ${where.join(' AND ')}` : '';\n return this.query(\n `SELECT ${JOB_EVENT_STORAGE_COLUMNS}\n FROM _smrt_job_events\n ${whereSql}\n ORDER BY ${this.createdAtComparableExpression()} ASC, id ASC\n LIMIT ?`,\n params,\n { allowRawOnTenantScoped: true },\n );\n }\n\n async latestProgressByJobIds(\n jobIds: string[],\n options: { tenantId?: string | null } = {},\n ): Promise<Map<string, SmrtJobEvent>> {\n const uniqueJobIds = [...new Set(jobIds.filter(Boolean))];\n const latestByJobId = new Map<string, SmrtJobEvent>();\n if (uniqueJobIds.length === 0) return latestByJobId;\n\n const placeholders = uniqueJobIds.map(() => '?').join(', ');\n const where: string[] = [\n `job_id IN (${placeholders})`,\n \"type = 'progress'\",\n ];\n const params: unknown[] = [...uniqueJobIds];\n\n this.addTenantPredicate(where, params, options);\n const createdAtExpression = this.createdAtComparableExpression();\n\n const events = await this.query(\n `SELECT ${JOB_EVENT_STORAGE_COLUMNS}\n FROM (\n SELECT ${JOB_EVENT_STORAGE_COLUMNS},\n ${createdAtExpression} AS smrt_created_at_sort,\n ROW_NUMBER() OVER (\n PARTITION BY job_id\n ORDER BY ${createdAtExpression} DESC, id DESC\n ) AS smrt_rank\n FROM _smrt_job_events\n WHERE ${where.join(' AND ')}\n ) ranked\n WHERE smrt_rank = 1\n ORDER BY smrt_created_at_sort DESC, id DESC`,\n params,\n { allowRawOnTenantScoped: true },\n );\n\n for (const event of events) {\n latestByJobId.set(event.jobId, event);\n }\n\n return latestByJobId;\n }\n\n /**\n * Read the newest safe, authoritative terminal outcomes for one tenant.\n *\n * The projection is built only from versioned terminal events written in the\n * same transaction as their job status. It never returns job arguments,\n * object ids, results, raw errors, or stack traces. Events follow the package\n * retention policy (30 days by default), independently of job-row cleanup.\n */\n async listTerminalOutcomes(\n options: ListTerminalOutcomesOptions,\n ): Promise<SmrtJobTerminalOutcomePage> {\n if (!Object.hasOwn(options, 'tenantId') || options.tenantId === undefined) {\n throw new Error(\n 'Terminal outcome queries require tenantId or tenantId: null',\n );\n }\n const limit = normalizeLimit(options.limit ?? 100);\n const where = [\n \"stage IN ('completed', 'failed', 'cancelled', 'stale-recovery')\",\n ];\n const params: unknown[] = [];\n this.addTenantPredicate(where, params, options);\n\n if (options.statuses?.length) {\n const stages = options.statuses.flatMap((status) =>\n status === 'failed' ? ['failed', 'stale-recovery'] : [status],\n );\n where.push(`stage IN (${stages.map(() => '?').join(', ')})`);\n params.push(...stages);\n }\n if (options.since) {\n where.push(`${this.createdAtComparableExpression()} > ?`);\n params.push(normalizeCursorDate(options.since));\n }\n if (options.before) {\n const cursor = parseCursor(options.before);\n const createdAt = await this.resolveCursorCreatedAt(cursor, options);\n const expression = this.createdAtComparableExpression();\n where.push(`(${expression} < ? OR (${expression} = ? AND id < ?))`);\n params.push(createdAt, createdAt, cursor.id);\n }\n\n params.push(TERMINAL_OUTCOME_CANDIDATE_LIMIT);\n const expression = this.createdAtComparableExpression();\n const candidates = await this.query(\n `SELECT ${JOB_EVENT_STORAGE_COLUMNS}\n FROM _smrt_job_events\n WHERE ${where.join(' AND ')}\n ORDER BY ${expression} DESC, id DESC\n LIMIT ?`,\n params,\n { allowRawOnTenantScoped: true },\n );\n\n const outcomes: SmrtJobTerminalOutcome[] = [];\n let scanned: SmrtJobEvent | undefined;\n for (const event of candidates) {\n scanned = event;\n const outcome = terminalOutcome(event);\n if (!outcome || !matchesTerminalOutcome(outcome, options)) continue;\n outcomes.push(outcome);\n if (outcomes.length === limit) break;\n }\n const stoppedAtLimit = outcomes.length === limit;\n const candidateBoundReached =\n candidates.length === TERMINAL_OUTCOME_CANDIDATE_LIMIT;\n\n return {\n outcomes,\n limit,\n candidateLimit: TERMINAL_OUTCOME_CANDIDATE_LIMIT,\n truncated: stoppedAtLimit || candidateBoundReached,\n nextCursor:\n (stoppedAtLimit || candidateBoundReached) && scanned\n ? scanned.toCursor()\n : null,\n };\n }\n\n /**\n * Read one job's newest matching authoritative outcome, independently of the\n * tenant-wide feed's 1,000-candidate limit. Retention still applies.\n * @param jobId - Authorized job identity; the caller owns resource authorization.\n * @param options - Explicit tenant and optional current completion identity.\n * @returns A safe outcome or null; never raw errors, arguments or results.\n */\n async getTerminalOutcome(\n jobId: string,\n options: GetTerminalOutcomeOptions,\n ): Promise<SmrtJobTerminalOutcome | null> {\n if (!Object.hasOwn(options, 'tenantId') || options.tenantId === undefined)\n throw new Error(\n 'Terminal outcome queries require tenantId or tenantId: null',\n );\n const where = [\n 'job_id = ?',\n \"stage IN ('completed', 'failed', 'cancelled', 'stale-recovery')\",\n ];\n const params: unknown[] = [jobId];\n this.addTenantPredicate(where, params, options);\n const events = await this.query(\n `SELECT ${JOB_EVENT_STORAGE_COLUMNS} FROM _smrt_job_events\n WHERE ${where.join(' AND ')} ORDER BY ${this.createdAtComparableExpression()} DESC, id DESC`,\n params,\n { allowRawOnTenantScoped: true },\n );\n for (const event of events) {\n const outcome = terminalOutcome(event);\n if (\n outcome &&\n (options.attempts === undefined ||\n options.attempts === outcome.attempts) &&\n (options.completedAt === undefined ||\n options.completedAt === outcome.completedAt)\n )\n return outcome;\n }\n return null;\n }\n\n private addTenantPredicate(\n where: string[],\n params: unknown[],\n options: { tenantId?: string | null },\n ): void {\n if (options.tenantId === null) {\n where.push('tenant_id IS NULL');\n return;\n }\n\n const tenantId =\n typeof options.tenantId === 'string' ? options.tenantId : getTenantId();\n\n if (tenantId) {\n where.push('tenant_id = ?');\n params.push(tenantId);\n return;\n }\n\n throw new Error(\n 'Tenant-scoped job event queries require tenantId, tenantId: null, or an ambient tenant context.',\n );\n }\n\n /**\n * Delete job events recorded before a cutoff (#2375).\n *\n * `_smrt_job_events` is append-only — every log line, progress tick and\n * lifecycle transition of every job — so it outgrows `_smrt_jobs` by an\n * order of magnitude and had no prune path at all. Events are pruned on\n * their own clock rather than by following job deletion: a long-running job\n * accumulates events for as long as it runs.\n *\n * The cutoff uses the same engine-normalized `created_at` expression the\n * cursor reads use. On PostgreSQL that is the bare column, so\n * `idx_smrt_job_events_created_at` serves it; on SQLite the `strftime()`\n * wrapper makes the comparison non-sargable and the prune is a scan. That is\n * acceptable for a periodic maintenance pass and is preferable to comparing\n * two differently-formatted timestamps, which is what the wrapper exists to\n * prevent.\n *\n * @param options.before - Delete events created strictly before this time.\n * @param options.dryRun - Count matching events without deleting them.\n * @returns Number of events deleted (or, under `dryRun`, matched).\n */\n async cleanup(options: { before: Date; dryRun?: boolean }): Promise<number> {\n const expression = this.createdAtComparableExpression();\n const where = `${expression} < ?`;\n const cutoff = options.before.toISOString();\n\n const counted = await this.db.query(\n `SELECT COUNT(*) AS total FROM _smrt_job_events WHERE ${where}`,\n cutoff,\n );\n const total = Number(counted.rows?.[0]?.total ?? 0);\n if (!Number.isFinite(total) || total <= 0) return 0;\n\n if (!options.dryRun) {\n await this.db.query(\n `DELETE FROM _smrt_job_events WHERE ${where}`,\n cutoff,\n );\n }\n\n return total;\n }\n\n private createdAtComparableExpression(): string {\n const engine = databaseEngine(this.db);\n if (engine === 'sqlite') {\n return \"strftime('%Y-%m-%dT%H:%M:%fZ', created_at)\";\n }\n if (engine === 'duckdb') {\n return \"strftime(created_at, '%Y-%m-%dT%H:%M:%S.%gZ')\";\n }\n\n return 'created_at';\n }\n\n private async resolveCursorCreatedAt(\n cursor: JobEventCursor,\n options: ListJobEventsOptions & { jobId?: string },\n ): Promise<string> {\n if (!cursor.id) {\n return normalizeCursorDate(cursor.createdAt);\n }\n\n const where = ['id = ?'];\n const params: unknown[] = [cursor.id];\n if (options.jobId) {\n where.push('job_id = ?');\n params.push(options.jobId);\n }\n this.addTenantPredicate(where, params, options);\n\n const result = await this.db.query(\n `SELECT ${this.createdAtComparableExpression()} AS cursor_created_at\n FROM _smrt_job_events\n WHERE ${where.join(' AND ')}\n LIMIT 1`,\n ...params,\n );\n const cursorCreatedAt = getQueryRows(result)[0]?.cursor_created_at;\n\n return typeof cursorCreatedAt === 'string' && cursorCreatedAt.trim()\n ? cursorCreatedAt\n : normalizeCursorDate(cursor.createdAt);\n }\n}\n\nfunction terminalOutcome(event: SmrtJobEvent): SmrtJobTerminalOutcome | null {\n const data = event.data;\n if (\n data?.version !== 1 ||\n data.terminal !== true ||\n !isTerminalStatus(data.status) ||\n !matchesTerminalStage(data.status, data.failureKind, event.stage) ||\n typeof data.queue !== 'string' ||\n typeof data.objectType !== 'string' ||\n typeof data.method !== 'string' ||\n typeof data.attempts !== 'number' ||\n !Number.isSafeInteger(data.attempts) ||\n data.attempts < 0 ||\n typeof data.completedAt !== 'string' ||\n Number.isNaN(Date.parse(data.completedAt)) ||\n (data.status === 'failed'\n ? !isFailureKind(data.failureKind)\n : data.failureKind !== undefined) ||\n !event.id\n ) {\n return null;\n }\n const failureKind =\n data.status === 'failed'\n ? (data.failureKind as SmrtJobTerminalOutcome['failureKind'])\n : undefined;\n\n return {\n eventId: event.id,\n jobId: event.jobId,\n tenantId: event.tenantId ?? null,\n status: data.status,\n queue: data.queue,\n objectType: data.objectType,\n method: data.method,\n attempts: data.attempts,\n ...(failureKind ? { failureKind } : {}),\n completedAt: new Date(data.completedAt).toISOString(),\n cursor: event.toCursor(),\n };\n}\n\nfunction isFailureKind(\n value: unknown,\n): value is NonNullable<SmrtJobTerminalOutcome['failureKind']> {\n return (\n value === 'execution' ||\n value === 'timeout' ||\n value === 'stale-recovery' ||\n value === 'handler-unregistered' ||\n value === 'handler-unclaimed'\n );\n}\n\nfunction isTerminalStatus(value: unknown): value is SmrtJobTerminalStatus {\n return value === 'completed' || value === 'failed' || value === 'cancelled';\n}\n\nfunction matchesTerminalStage(\n status: SmrtJobTerminalStatus,\n failureKind: unknown,\n stage: string | null,\n): boolean {\n return (\n stage === status ||\n (status === 'failed' &&\n failureKind === 'stale-recovery' &&\n stage === 'stale-recovery')\n );\n}\n\nfunction matchesTerminalOutcome(\n outcome: SmrtJobTerminalOutcome,\n options: ListTerminalOutcomesOptions,\n): boolean {\n return (\n (!options.queues?.length || options.queues.includes(outcome.queue)) &&\n (!options.objectTypes?.length ||\n options.objectTypes.includes(outcome.objectType)) &&\n (!options.methods?.length || options.methods.includes(outcome.method))\n );\n}\n\nexport default SmrtJobEvent;\n","import { randomUUID } from 'node:crypto';\nimport {\n ensureJobEventsSystemTableCompatibility,\n ObjectRegistry,\n} from '@happyvertical/smrt-core';\nimport { ensureSchema } from '@happyvertical/smrt-core/schema/utils';\nimport type { DatabaseInterface } from '@happyvertical/sql';\nimport type { JobStatus, SmrtJob } from './smrt-job.js';\nimport { SmrtJobEvent, type SmrtJobTerminalStatus } from './smrt-job-event.js';\n\nconst terminalStorageReady = new WeakMap<object, Promise<void>>();\n\n/**\n * Prepare, once per database, the storage every terminal transition writes.\n *\n * Preparing it builds the registry's merged schemas, so it can fail for a\n * reason unrelated to jobs (two unrelated classes claiming one table, #4735).\n * `TaskRunner.start()` calls this before it claims anything, so that failure\n * stops the runner at startup instead of stranding every claimed job; later\n * transitions reuse the cached readiness and no longer depend on models that\n * register after start.\n */\nexport async function ensureTerminalOutcomeStorage(\n db: DatabaseInterface,\n): Promise<void> {\n const key = db as object;\n const existing = terminalStorageReady.get(key);\n if (existing) return existing;\n\n const pending = (async () => {\n // SmrtJob.cancel() has historically worked for consumers that prepare only\n // the job model. Terminal outcomes now require their package-owned event\n // table as well, so prepare that registered schema before opening the\n // state+event transaction. Never fall back to a state-only transition.\n await ensureSchema(db, 'SmrtJobEvent');\n await ensureJobEventsSystemTableCompatibility(db);\n })();\n terminalStorageReady.set(key, pending);\n try {\n await pending;\n } catch (error) {\n terminalStorageReady.delete(key);\n throw error;\n }\n}\n\nexport interface SmrtJobTerminalSnapshot {\n id: string;\n tenantId: string | null;\n queue: string;\n objectType: string;\n method: string;\n attempts: number;\n startedAt?: string | null;\n}\n\nexport interface TransitionTerminalJobOptions {\n job: SmrtJobTerminalSnapshot;\n status: SmrtJobTerminalStatus;\n completedAt: Date;\n expectedStatuses: JobStatus[];\n expectedWorkerId?: string | null;\n expectedTaskId?: string;\n /** Also require `run_at <= ?` (ISO): a requeued row is not this transition's. */\n expectedRunAtAtOrBefore?: string;\n clearWorker?: boolean;\n lastError?: string | null;\n failureKind?:\n | 'execution'\n | 'timeout'\n | 'stale-recovery'\n | 'handler-unregistered'\n | 'handler-unclaimed';\n resultPointer?: string | null;\n taskResult?: Record<string, unknown> | null;\n}\n\n/**\n * Atomically persist an owned terminal job transition and its durable outcome.\n *\n * A null result means the conditional transition lost a race. Neither the job\n * row nor an event is written in that case.\n */\nexport async function transitionTerminalJob(\n db: DatabaseInterface,\n options: TransitionTerminalJobOptions,\n): Promise<SmrtJobEvent | null> {\n if (!db.transaction) {\n throw new Error('Terminal job transitions require transaction support');\n }\n if (options.expectedStatuses.length === 0) {\n throw new Error('Terminal job transitions require an expected status');\n }\n\n await ensureTerminalOutcomeStorage(db);\n\n const persisted = await db.transaction(async (tx) => {\n const assignments: Array<[string, unknown]> = [\n ['status', options.status],\n ['completed_at', options.completedAt.toISOString()],\n ['updated_at', options.completedAt.toISOString()],\n ];\n if (options.clearWorker) {\n assignments.push(['worker_id', null], ['worker_heartbeat', null]);\n }\n if (options.lastError !== undefined) {\n assignments.push(['last_error', options.lastError]);\n }\n if (options.resultPointer !== undefined) {\n assignments.push(['result_pointer', options.resultPointer]);\n }\n if (options.taskResult !== undefined) {\n assignments.push([\n 'task_result',\n options.taskResult === null ? null : JSON.stringify(options.taskResult),\n ]);\n }\n\n const where = ['id = ?'];\n const whereValues: unknown[] = [options.job.id];\n if (options.job.tenantId === null) {\n where.push('tenant_id IS NULL');\n } else {\n where.push('tenant_id = ?');\n whereValues.push(options.job.tenantId);\n }\n where.push(\n `status IN (${options.expectedStatuses.map(() => '?').join(', ')})`,\n );\n whereValues.push(...options.expectedStatuses);\n if (options.expectedWorkerId === null) {\n where.push('worker_id IS NULL');\n } else if (options.expectedWorkerId !== undefined) {\n where.push('worker_id = ?');\n whereValues.push(options.expectedWorkerId);\n }\n if (\n options.expectedWorkerId !== undefined &&\n options.job.startedAt !== undefined\n ) {\n where.push('attempts = ?');\n whereValues.push(options.job.attempts);\n if (options.job.startedAt === null) where.push('started_at IS NULL');\n else if (options.job.startedAt !== undefined) {\n where.push('started_at = ?');\n whereValues.push(options.job.startedAt);\n }\n }\n if (options.expectedTaskId !== undefined) {\n where.push('task_id = ?');\n whereValues.push(options.expectedTaskId);\n }\n if (options.expectedRunAtAtOrBefore !== undefined) {\n where.push('run_at <= ?');\n whereValues.push(options.expectedRunAtAtOrBefore);\n }\n\n const updated = await tx.query(\n `UPDATE _smrt_jobs\n SET ${assignments.map(([column]) => `${column} = ?`).join(', ')}\n WHERE ${where.join(' AND ')}\n RETURNING CAST(tenant_id AS VARCHAR) AS tenant_id,\n queue, object_type, method, attempts`,\n ...assignments.map(([, value]) => value),\n ...whereValues,\n );\n if (updated.rows.length !== 1) return null;\n const authoritative = updated.rows[0] as {\n tenant_id: string | null;\n queue: string;\n object_type: string;\n method: string;\n attempts: number | string;\n };\n const attempts = Number(authoritative.attempts);\n if (!Number.isSafeInteger(attempts) || attempts < 0) {\n throw new Error('Terminal job transition returned invalid attempts');\n }\n\n const stage =\n options.status === 'failed' && options.failureKind === 'stale-recovery'\n ? 'stale-recovery'\n : options.status;\n const id = randomUUID();\n const type =\n options.status === 'completed'\n ? 'progress'\n : options.status === 'failed'\n ? 'error'\n : 'status';\n const level = options.status === 'failed' ? 'error' : 'info';\n const progress = options.status === 'completed' ? 100 : null;\n const message = `Job ${options.status}`;\n const data = {\n version: 1,\n terminal: true,\n status: options.status,\n queue: authoritative.queue,\n objectType: authoritative.object_type,\n method: authoritative.method,\n attempts,\n completedAt: options.completedAt.toISOString(),\n ...(options.status === 'failed' && options.failureKind\n ? { failureKind: options.failureKind }\n : {}),\n };\n const timestamp = options.completedAt.toISOString();\n await tx.query(\n `INSERT INTO _smrt_job_events\n (id, slug, context, created_at, updated_at, tenant_id, job_id,\n type, level, stage, progress, message, data)\n VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,\n id,\n id,\n '',\n timestamp,\n timestamp,\n authoritative.tenant_id,\n options.job.id,\n type,\n level,\n stage,\n progress,\n message,\n JSON.stringify(data),\n );\n return {\n id,\n slug: id,\n context: '',\n created_at: timestamp,\n updated_at: timestamp,\n tenant_id: authoritative.tenant_id,\n job_id: options.job.id,\n type,\n level,\n stage,\n progress,\n message,\n data,\n };\n });\n\n if (!persisted) return null;\n const event = new (ObjectRegistry.resolveEffectiveConstructor(SmrtJobEvent))({\n db,\n });\n await event.initialize();\n await event.loadDataFromDb(persisted);\n return event;\n}\n\nexport function terminalSnapshot(\n job: Pick<\n SmrtJob,\n 'id' | 'tenantId' | 'queue' | 'objectType' | 'method' | 'attempts'\n > &\n Partial<Pick<SmrtJob, 'startedAt'>>,\n fenceDispatch = false,\n): SmrtJobTerminalSnapshot | null {\n if (!job.id) return null;\n return {\n id: job.id,\n tenantId: job.tenantId ?? null,\n queue: job.queue,\n objectType: job.objectType,\n method: job.method,\n attempts: job.attempts,\n ...(fenceDispatch && job.startedAt !== undefined\n ? { startedAt: job.startedAt?.toISOString() ?? null }\n : {}),\n };\n}\n","import { createHash, randomUUID } from 'node:crypto';\nimport type { RetryStrategyConfig } from '@happyvertical/jobs';\nimport {\n type detectEngine,\n ensureJobsSystemTableCompatibility,\n field,\n ObjectRegistry,\n SmrtCollection,\n SmrtObject,\n type SmrtSaveOptions,\n smrt,\n} from '@happyvertical/smrt-core';\nimport {\n getTenantId,\n isSuperAdminBypass,\n isSystemContext,\n TenantIsolationError,\n TenantScoped,\n tenantId,\n} from '@happyvertical/smrt-tenancy';\nimport type { DatabaseInterface } from '@happyvertical/sql';\nimport {\n assertWithinTenantCreationCap,\n clampRetries,\n DEFAULT_TENANT_JOB_CAP,\n} from './background-policy.js';\nimport {\n assertJobHandlerName,\n isJobHandlerTarget,\n JOB_HANDLER_METHOD,\n JOB_HANDLER_TARGET_PREFIX,\n jobHandlerName,\n jobHandlerTarget,\n MAX_JOB_HANDLERS,\n} from './job-handlers.js';\nimport { SmrtJobDedupeSlotCollection } from './smrt-job-dedupe-slot.js';\nimport { terminalSnapshot, transitionTerminalJob } from './terminal-outcome.js';\nimport { resolveEngine } from './worker-liveness.js';\n\n/**\n * Job status type\n */\nexport type JobStatus =\n | 'pending'\n | 'running'\n | 'completed'\n | 'failed'\n | 'cancelled';\n\n/**\n * Timeout behavior type\n */\nexport type TimeoutBehavior = 'fail' | 'kill' | 'warn';\n\n/**\n * Full job projection with portable string job and tenant identities.\n *\n * Native DuckDB currently exposes UUID result values as internal objects.\n * Worker claim/recovery state and restored tenant context use string IDs.\n * Both paths use this projection instead of hydrating raw UUIDs from `SELECT *`.\n */\nexport const SMRT_JOB_PORTABLE_SELECT_COLUMNS = `\n CAST(id AS VARCHAR) AS id,\n slug, context, created_at, updated_at,\n CAST(tenant_id AS VARCHAR) AS tenant_id, queue,\n object_type, object_id, method, args, run_at,\n priority, status, attempts, max_attempts, timeout,\n timeout_behavior, started_at, completed_at, last_error,\n result_pointer, task_id, task_owner_id, task_result,\n task_input_requests, task_input_responses, retry_strategy,\n worker_id, worker_heartbeat, dedupe_key\n`;\n\n/**\n * Persistent job record stored in the `_smrt_jobs` system table.\n *\n * @remarks\n * Each SmrtJob represents a deferred method call on a SmrtObject. The TaskRunner polls for\n * pending jobs, resolves the target class via ObjectRegistry, and invokes the method. Jobs\n * track status (`pending -> running -> completed/failed/cancelled`), retry attempts with\n * configurable strategies, worker heartbeats for stale-job detection, and optional result pointers.\n * Priority ordering is `higher = sooner`; the default timeout is 5 minutes (300000ms).\n */\n@smrt({\n tableName: '_smrt_jobs',\n // Fail closed: `_smrt_jobs` is an internal operational queue table. Generated\n // REST/MCP list/get only filter by tenant when a tenant context is active;\n // reached without context (a tenant-less/admin principal, or any non-SvelteKit\n // surface) an `optional`-mode class returns UNFILTERED rows, leaking every\n // tenant's jobs. Workers read this table via the collection directly\n // (allowRawOnTenantScoped), never through generated routes, so nothing\n // internal needs the read surface — so we do not generate one (S5 audit #1402).\n api: false,\n // retry/cancel are operator commands invoked in-process via the CLI;\n // they intentionally aren't exposed over HTTP.\n cli: {\n include: ['list', 'get', 'retry', 'cancel'],\n skipApiCheck: true,\n http: false,\n },\n mcp: false,\n // Composite for the claim-loop predicate every runner polls roughly once\n // per second (`claimReady()`/`listReady()`: `status = 'pending' AND\n // run_at <= ?`, #2364, epic #2382 finding A3). Declared here rather than\n // left to the jobs-compat path (`ensureJobsSystemTableCompatibility()`,\n // #2375/#2376): that path exists to reshape a table that predates the\n // column/index it adds on databases where the manifest hasn't migrated\n // yet, not as the default route for new indexes on a normal decorated\n // class — this one reaches every path (manifest, registry, `db:migrate`)\n // the standard way and rolls out on the next `smrt db:migrate`.\n //\n // Roll this out with `smrt db:migrate --postgres-safe` (#2362): `_smrt_jobs`\n // is under continuous write load (every claim is an UPDATE), so a plain\n // atomic `CREATE INDEX` would hold ACCESS EXCLUSIVE for the build and stall\n // claiming on a busy deployment.\n indexes: [\n { name: '_smrt_jobs_status_run_at_idx', columns: ['status', 'runAt'] },\n // Keep suspended, already-due tasks out of the hot ready scan (#3211).\n // SQLite/PostgreSQL partial index; DuckDB/JSON retain a full index fallback.\n {\n name: '_smrt_jobs_ready_idx',\n columns: ['status', 'runAt'],\n where:\n \"status = 'pending' AND (task_input_requests IS NULL OR task_input_responses IS NOT NULL)\",\n },\n ],\n})\n// Keep the data model tenant-scoped (defense in depth): even without a generated\n// read route, the @tenantId() field alone does NOT make collection reads filter\n// by tenant. `optional` mode preserves global (NULL tenant) jobs while scoping\n// tenant-owned rows for any future tenant-context-required path (S5 audit #1402).\n@TenantScoped({ mode: 'optional' })\nexport class SmrtJob extends SmrtObject { static __smrtPackage__ = \"@happyvertical/smrt-jobs\";\n /** Tenant context captured for this job, if any */\n @tenantId({ nullable: true })\n tenantId: string | null | undefined = undefined;\n\n /** Caller key retained as provenance; only pending/running jobs reserve it. */\n @field({ type: 'text', nullable: true, indexed: true })\n dedupeKey: string | null = null;\n\n /** Queue name for the job */\n @field({ type: 'text', required: true, default: 'default' })\n queue: string = 'default';\n\n /** Type of object to invoke method on */\n @field({ type: 'text', required: true, requiredFor: 'identity' })\n objectType: string = '';\n\n /** ID of the specific object (null for static methods) */\n @field({ type: 'text', nullable: true })\n objectId: string | null = null;\n\n /** Method name to invoke */\n @field({ type: 'text', required: true, requiredFor: 'identity' })\n method: string = '';\n\n /** Arguments to pass to the method (JSON) */\n @field({ type: 'json' })\n args: Record<string, unknown> = {};\n\n /**\n * When to run the job.\n *\n * Indexed (single-column, plus the class-level `(status, run_at)`\n * composite): the claim-loop predicate every runner polls roughly once per\n * second (#2364).\n */\n @field({ type: 'datetime', required: true, indexed: true })\n runAt: Date = new Date();\n\n /** Priority (higher = sooner) */\n @field({ type: 'integer', required: true, default: 50 })\n priority: number = 50;\n\n /**\n * Current status.\n *\n * Indexed (single-column, plus the class-level `(status, run_at)`\n * composite): the claim-loop predicate every runner polls roughly once per\n * second (#2364). `(status, completed_at)` — the retention cleanup\n * predicate — is a separate index from `ensureJobsSystemTableCompatibility()`\n * (#2375).\n */\n @field({ type: 'text', required: true, default: 'pending', indexed: true })\n status: JobStatus = 'pending';\n\n /** Number of execution attempts */\n @field({ type: 'integer', required: true, default: 0 })\n attempts: number = 0;\n\n /** Maximum retry attempts */\n @field({ type: 'integer', required: true, default: 3 })\n maxAttempts: number = 3;\n\n /** Timeout in milliseconds */\n @field({ type: 'integer', required: true, default: 300000 })\n timeout: number = 300000;\n\n /** What to do on timeout */\n @field({ type: 'text', required: true, default: 'fail' })\n timeoutBehavior: TimeoutBehavior = 'fail';\n\n /** When execution started. Public retry and surplus release clear this field. */\n @field({ type: 'datetime', nullable: true })\n startedAt: Date | null = null;\n\n /** When execution completed */\n @field({ type: 'datetime', nullable: true })\n completedAt: Date | null = null;\n\n /** Last error message */\n @field({ type: 'text', nullable: true })\n lastError: string | null = null;\n\n /** Pointer to where result is stored */\n @field({ type: 'text', nullable: true })\n resultPointer: string | null = null;\n\n /**\n * Correlation identifier for an MCP Tasks extension task.\n *\n * A task is deliberately represented by its backing job rather than a second\n * queue row: every task transition therefore has exactly one durable worker\n * target to cancel, recover, and inspect.\n */\n @field({ type: 'text', nullable: true, unique: true })\n taskId: string | null = null;\n\n /** Principal that created an MCP task, when the transport has one. */\n @field({ type: 'text', nullable: true })\n taskOwnerId: string | null = null;\n\n /** Completed MCP CallToolResult, stored only for MCP task jobs. */\n @field({ type: 'json', nullable: true })\n taskResult: Record<string, unknown> | null = null;\n\n /** Outstanding input requests made through JobExecutionContext.task. */\n @field({ type: 'json', nullable: true })\n taskInputRequests: Record<string, unknown> | null = null;\n\n /** Accepted task input responses, keyed by the requested input name. */\n @field({ type: 'json', nullable: true })\n taskInputResponses: Record<string, unknown> | null = null;\n\n /** Retry strategy configuration */\n @field({ type: 'json' })\n retryStrategy: RetryStrategyConfig = {\n type: 'exponential',\n config: { initialDelay: 1000, multiplier: 2, maxDelay: 300000 },\n };\n\n /** ID of the worker processing this job */\n @field({ type: 'text', nullable: true })\n workerId: string | null = null;\n\n /** Last heartbeat from the worker */\n @field({ type: 'datetime', nullable: true })\n workerHeartbeat: Date | null = null;\n\n /**\n * Capture ambient tenant context when a job is saved inside withTenant().\n *\n * Scheduled jobs can also set this explicitly from their owning schedule.\n */\n override async save(options?: SmrtSaveOptions): Promise<this> {\n if (this.tenantId === undefined) {\n const contextTenantId = getTenantId();\n if (contextTenantId) {\n this.tenantId = contextTenantId;\n }\n }\n\n return super.save(options);\n }\n\n /**\n * Mark the job for retry\n */\n async retry(\n options: Pick<EnqueueJobOptions, 'transaction'> = {},\n ): Promise<void> {\n if (!this.id) throw new Error('Cannot retry an unpersisted job');\n const executor = options.transaction ?? this.db;\n const initial = await readRetryJob(executor, this.id);\n assertRetryTenant(initial.tenant_id);\n assertRetryStatus(initial.status);\n const association = persistedScheduleAssociation(initial.args);\n const originalArguments = JSON.stringify(persistedArguments(initial.args));\n const originalTarget = persistedJobTarget(initial);\n const dedupeKey = persistedDedupeKey(initial.dedupe_key);\n const tenant = initial.tenant_id;\n const tenantPredicate =\n tenant === null ? 'tenant_id IS NULL' : 'tenant_id = ?';\n const tenantValues = tenant === null ? [] : [tenant];\n\n const retry = async (\n tx: DatabaseInterface,\n ): Promise<Record<string, unknown>> => {\n // All paths acquire schedule -> dedupe slot -> job. Completion's job\n // transaction commits before its separate schedule callback acquires a row.\n const schedule = association\n ? await lockRetrySchedule(tx, association, initial)\n : null;\n let slotKey: string | null = null;\n let slotJobId: unknown;\n if (dedupeKey !== null) {\n slotKey = jobSlotKey(tenant, dedupeKey);\n const slot = await tx.query(\n 'UPDATE _smrt_job_dedupe_slots SET slot_key = slot_key WHERE slot_key = ? RETURNING job_id',\n slotKey,\n );\n if (slot.rows.length !== 1)\n throw new Error('Keyed job retry requires its enqueue slot');\n slotJobId = slot.rows[0].job_id;\n }\n const locked = await tx.query(\n `UPDATE _smrt_jobs SET id = id WHERE id = ? AND ${tenantPredicate}\n RETURNING ${SMRT_JOB_PORTABLE_SELECT_COLUMNS}`,\n initial.id,\n ...tenantValues,\n );\n if (locked.rows.length !== 1)\n throw new Error('Job ownership changed before retry');\n const current = retryRow(locked.rows[0]);\n assertRetryTenant(current.tenant_id);\n if (\n current.tenant_id !== tenant ||\n JSON.stringify(persistedScheduleAssociation(current.args)) !==\n JSON.stringify(association) ||\n JSON.stringify(persistedArguments(current.args)) !==\n originalArguments ||\n JSON.stringify(persistedJobTarget(current)) !==\n JSON.stringify(originalTarget) ||\n persistedDedupeKey(current.dedupe_key) !== dedupeKey\n ) {\n throw new Error(\n 'Persisted retry association changed; retry from current state',\n );\n }\n assertRetryStatus(current.status);\n const occupied = schedule\n ? await countScheduleJobs(\n tx,\n schedule.id,\n tenant,\n schedule.target,\n current.id,\n )\n : 0;\n if (schedule && occupied >= schedule.capacity)\n throw new Error('Scheduled retry capacity is full');\n if (\n slotKey &&\n typeof slotJobId === 'string' &&\n slotJobId !== current.id\n ) {\n const active = await tx.query(\n \"SELECT id FROM _smrt_jobs WHERE id = ? AND status IN ('pending', 'running')\",\n slotJobId,\n );\n if (active.rows.length)\n throw new Error('Another job already reserves this dedupeKey');\n }\n const retriedAt = new Date().toISOString();\n // A handler job's unclaimed deadline counts from run_at (#5005): a\n // retry restarts it, or the next sweep would fail the job again.\n const retried = await tx.query(\n `UPDATE _smrt_jobs SET status = 'pending', attempts = 0, last_error = NULL,\n started_at = NULL, completed_at = NULL, worker_id = NULL, worker_heartbeat = NULL,\n run_at = CASE WHEN ${HANDLER_TARGET_SQL} AND run_at < ? THEN ? ELSE run_at END,\n updated_at = ? WHERE id = ? AND ${tenantPredicate}\n AND status IN ('pending', 'failed', 'cancelled')\n RETURNING ${SMRT_JOB_PORTABLE_SELECT_COLUMNS}`,\n retriedAt,\n retriedAt,\n retriedAt,\n current.id,\n ...tenantValues,\n );\n if (retried.rows.length !== 1)\n throw new Error('Job status changed before retry');\n if (slotKey)\n await tx.query(\n 'UPDATE _smrt_job_dedupe_slots SET job_id = ? WHERE slot_key = ?',\n current.id,\n slotKey,\n );\n if (schedule)\n await tx.query(\n `UPDATE _smrt_agent_schedules SET running_count = ? WHERE id = ? AND ${tenantPredicate}`,\n occupied + 1,\n schedule.id,\n ...tenantValues,\n );\n return retried.rows[0];\n };\n let row: Record<string, unknown>;\n if (options.transaction) row = await retry(options.transaction);\n else {\n if (!executor.transaction)\n throw new Error('Job retry requires transaction support');\n row = await executor.transaction(retry);\n }\n // Hydrate the authoritative revision and immutable stored arguments. Do not\n // save caller-edited business fields or leak an ended transaction handle.\n await this.loadDataFromDb(row);\n }\n\n /**\n * Cancel the job\n */\n async cancel(): Promise<void> {\n if (this.status === 'completed' || this.status === 'cancelled') {\n throw new Error(`Cannot cancel job with status: ${this.status}`);\n }\n\n const snapshot = terminalSnapshot(this);\n if (!snapshot) throw new Error('Cannot cancel an unpersisted job');\n const contextTenantId = getTenantId();\n if (\n contextTenantId &&\n snapshot.tenantId !== contextTenantId &&\n !isSystemContext() &&\n !isSuperAdminBypass()\n ) {\n throw new TenantIsolationError(\n `Tenant isolation violation: cannot cancel SmrtJob with tenantId '${snapshot.tenantId}' in context of tenant '${contextTenantId}'`,\n {\n tenantId: contextTenantId,\n attemptedTenantId: snapshot.tenantId ?? 'null',\n },\n );\n }\n const completedAt = new Date();\n const event = await transitionTerminalJob(this.db, {\n job: snapshot,\n status: 'cancelled',\n completedAt,\n expectedStatuses: ['pending', 'running', 'failed'],\n });\n if (!event) throw new Error('Job status changed before cancellation');\n\n this.status = 'cancelled';\n this.completedAt = completedAt;\n this.updated_at = completedAt;\n }\n\n /**\n * Get a human-readable description of the job\n */\n getDescription(): string {\n const target = this.objectId\n ? `${this.objectType}#${this.objectId}`\n : this.objectType;\n return `${target}.${this.method}()`;\n }\n}\n\n/**\n * Job data type (for create operations)\n */\nexport interface SmrtJobData {\n /** At most one pending/running job per effective tenant and key. */\n dedupeKey?: string | null;\n tenantId?: string | null;\n queue?: string;\n objectType: string;\n objectId?: string | null;\n method: string;\n args?: Record<string, unknown>;\n runAt?: Date;\n priority?: number;\n maxAttempts?: number;\n timeout?: number;\n timeoutBehavior?: TimeoutBehavior;\n retryStrategy?: RetryStrategyConfig;\n /** MCP task correlation ID. Internal callers only. */\n taskId?: string | null;\n /** MCP task owner/principal ID. Internal callers only. */\n taskOwnerId?: string | null;\n /** Completed MCP CallToolResult. Internal callers only. */\n taskResult?: Record<string, unknown> | null;\n /** Outstanding MCP task input requests. Internal callers only. */\n taskInputRequests?: Record<string, unknown> | null;\n /** Accepted MCP task input responses. Internal callers only. */\n taskInputResponses?: Record<string, unknown> | null;\n}\n\n/**\n * A job that targets a registered named handler (#5005) instead of a model\n * method. Stored as `object_type = 'handler:<handler>'`, `method = 'handle'`,\n * `object_id = NULL`, `args = payload`.\n */\nexport interface HandlerJobData\n extends Omit<\n SmrtJobData,\n | 'objectType'\n | 'objectId'\n | 'method'\n | 'args'\n | 'taskId'\n | 'taskOwnerId'\n | 'taskResult'\n | 'taskInputRequests'\n | 'taskInputResponses'\n > {\n /** Namespaced handler name, e.g. `@happyvertical/smrt-workflows:workflow-run`. */\n handler: string;\n /** JSON payload passed to the handler. Reserved `_`-prefixed runner keys are refused. */\n payload?: Record<string, unknown>;\n}\n\n/** Runner-owned argument keys a handler payload may not carry. */\nconst HANDLER_RESERVED_ARG_KEYS = [\n '_mcpTask',\n '_agentConfig',\n '_scheduleId',\n '_scheduledFor',\n '_scheduleAdmission',\n] as const;\n\n/**\n * A handler-form row must be canonical: valid name, fixed method, no object\n * id, no MCP task fields, a plain JSON object payload without runner keys.\n */\nfunction assertHandlerJobData(data: SmrtJobData): void {\n assertJobHandlerName(jobHandlerName(data.objectType));\n if (data.method !== JOB_HANDLER_METHOD)\n throw new TypeError(\n `A handler job's method must be '${JOB_HANDLER_METHOD}'`,\n );\n if (data.objectId != null)\n throw new TypeError('A handler job cannot have an objectId');\n if (\n data.taskId != null ||\n data.taskOwnerId != null ||\n data.taskResult != null ||\n data.taskInputRequests != null ||\n data.taskInputResponses != null\n )\n throw new TypeError('A handler job cannot be an MCP task');\n const args = data.args ?? {};\n if (!args || typeof args !== 'object' || Array.isArray(args))\n throw new TypeError('A handler job payload must be a JSON object');\n for (const key of HANDLER_RESERVED_ARG_KEYS) {\n if (Object.hasOwn(args, key))\n throw new TypeError(`A handler job payload cannot set reserved ${key}`);\n }\n}\n\n/**\n * Options controlling a centralized {@link SmrtJobCollection.enqueueJob} call.\n */\nexport interface EnqueueJobOptions {\n /**\n * Per-tenant in-flight cap. Defaults to {@link DEFAULT_TENANT_JOB_CAP}.\n * `0`/negative disables the cap (trusted internal callers). Global\n * (no-context / null tenant) jobs are always exempt.\n */\n tenantJobCap?: number;\n /**\n * Existing caller-owned transaction. All enqueue reads/writes use this handle;\n * the caller must propagate failures and commit/rollback the transaction.\n * Avoids nested transactions on engines without savepoints (DuckDB).\n */\n transaction?: DatabaseInterface;\n}\n\n/**\n * Options for listReady\n */\nexport interface ListReadyOptions {\n limit?: number;\n queues?: string[];\n /** Allowed tenant identities; undefined selects all, [] selects none. */\n tenantIds?: readonly (string | null)[];\n}\n\n// The DB and worker incarnation own this clock, not the job row. Legacy retry\n// and surplus-release paths may clear started_at without reusing this identity.\nconst fencedClaimTimes = new WeakMap<object, Map<string, number>>();\n\n/** Options for atomically claiming ready jobs. */\nexport interface ClaimReadyOptions extends ListReadyOptions {\n /** Opt into dispatch fencing; one unique worker incarnation per DB/process. */\n claimFencing?: boolean;\n workerId: string;\n now?: Date;\n /**\n * Handler names this claimant serves (#5005). When set, the claim takes\n * model jobs and only the handler jobs named here; `[]` takes no handler\n * job. Omitted, the claim does not filter by target. At most\n * {@link MAX_JOB_HANDLERS} names (one bound parameter each).\n */\n handlerNames?: readonly string[];\n}\n\n/**\n * SQL that is true for a stored handler target. A case-exact, wildcard-free\n * prefix test (SQLite `LIKE` is case-insensitive), the same on SQLite,\n * PostgreSQL and PGlite, and matching `isJobHandlerTarget`.\n */\nexport const HANDLER_TARGET_SQL = `substr(object_type, 1, ${JOB_HANDLER_TARGET_PREFIX.length}) = '${JOB_HANDLER_TARGET_PREFIX}'`;\n\n/** The claim filter for a claimant serving `handlerNames` (#5005). */\nfunction handlerClaimFilter(handlerNames: readonly string[]): {\n sql: string;\n params: string[];\n} {\n if (handlerNames.length > MAX_JOB_HANDLERS) {\n throw new RangeError(\n `claimReady accepts at most ${MAX_JOB_HANDLERS} handler names`,\n );\n }\n const notHandler = `NOT (${HANDLER_TARGET_SQL})`;\n if (handlerNames.length === 0) return { sql: notHandler, params: [] };\n return {\n sql: `(${notHandler} OR object_type IN (${handlerNames.map(() => '?').join(', ')}))`,\n params: handlerNames.map((name) => jobHandlerTarget(name).objectType),\n };\n}\n\ntype DatabaseWithConfig = DatabaseInterface & {\n config?: {\n type?: string;\n url?: string;\n };\n type?: string;\n};\n\n/**\n * Collection for managing SmrtJob objects\n */\nexport class SmrtJobCollection extends SmrtCollection<SmrtJob> {\n static readonly _itemClass = SmrtJob;\n\n override async initialize(): Promise<this> {\n await super.initialize();\n await ensureJobsSystemTableCompatibility(this.db);\n return this;\n }\n\n /**\n * List jobs by status\n */\n async listByStatus(\n status: JobStatus | JobStatus[],\n options: { limit?: number; queue?: string } = {},\n ): Promise<SmrtJob[]> {\n const where: Record<string, unknown> = {\n status: Array.isArray(status) ? status : [status],\n };\n\n if (options.queue) {\n where.queue = options.queue;\n }\n\n return this.list({\n where,\n orderBy: ['priority DESC', 'run_at ASC'],\n limit: options.limit,\n });\n }\n\n /**\n * List pending jobs ready to run\n */\n async listReady(options: ListReadyOptions = {}): Promise<SmrtJob[]> {\n const now = new Date().toISOString();\n const whereConditions: string[] = [\n \"status = 'pending'\",\n 'run_at <= ?',\n '(task_input_requests IS NULL OR task_input_responses IS NOT NULL)',\n ];\n const params: unknown[] = [now];\n\n if (options.queues?.length) {\n const placeholders = options.queues.map(() => '?').join(', ');\n whereConditions.push(`queue IN (${placeholders})`);\n params.push(...options.queues);\n }\n\n const scope = jobTenantScope(options.tenantIds);\n params.push(...scope.params);\n params.push(options.limit || 100);\n\n // Worker-internal scan: the runner intentionally processes ready jobs\n // across all tenants, so it manages tenant context per-job at execution\n // time rather than filtering here (SmrtJob is now @TenantScoped, S5 #1402).\n return this.query(\n `SELECT * FROM _smrt_jobs WHERE ${whereConditions.join(' AND ')}${scope.sql} ORDER BY priority DESC, run_at ASC LIMIT ?`,\n params,\n { allowRawOnTenantScoped: true },\n );\n }\n\n /**\n * Atomically claim pending jobs ready to run for a worker.\n *\n * The claim is performed as one conditional UPDATE so concurrent workers\n * cannot receive the same pending row, and it never claims more than\n * `limit` rows. PostgreSQL additionally skips rows locked by other workers\n * instead of waiting behind them.\n *\n * On PostgreSQL the candidate set is selected once in a `MATERIALIZED` CTE\n * and the UPDATE joins to it. The previous `WHERE id IN (SELECT … LIMIT ?\n * FOR UPDATE SKIP LOCKED)` form let the planner choose a nested-loop semi\n * join that rescans the subquery for every outer pending row; each rescan\n * skipped the row the statement had just updated and returned the next one,\n * so a single claim could take the whole backlog and a `concurrency: 1`\n * runner started every ready job at once (#3145).\n */\n async claimReady(options: ClaimReadyOptions): Promise<SmrtJob[]> {\n const limit = options.limit ?? 100;\n if (limit <= 0) return [];\n\n const now = options.now ?? new Date();\n const nowIso = now.toISOString();\n let startedAt = nowIso;\n if (options.claimFencing) {\n let clock = fencedClaimTimes.get(this.db);\n if (!clock) {\n clock = new Map();\n fencedClaimTimes.set(this.db, clock);\n }\n // Reserve before awaiting SQL: concurrent claims on this incarnation also\n // get distinct generations. Clock steps never defer ready work. A restart\n // must use a new worker incarnation (TaskRunner already guarantees this).\n const stamp = Math.max(\n now.getTime(),\n (clock.get(options.workerId) ?? -Infinity) + 1,\n );\n startedAt = new Date(stamp).toISOString();\n clock.set(options.workerId, stamp);\n }\n const whereConditions: string[] = [\n \"status = 'pending'\",\n 'run_at <= ?',\n '(task_input_requests IS NULL OR task_input_responses IS NOT NULL)',\n ];\n const whereParams: unknown[] = [nowIso];\n\n if (options.queues?.length) {\n const placeholders = options.queues.map(() => '?').join(', ');\n whereConditions.push(`queue IN (${placeholders})`);\n whereParams.push(...options.queues);\n }\n\n // Inside the candidate select, before its LIMIT: handler rows this\n // claimant cannot run must not fill the window and starve its work.\n if (options.handlerNames !== undefined) {\n const filter = handlerClaimFilter(options.handlerNames);\n whereConditions.push(filter.sql);\n whereParams.push(...filter.params);\n }\n\n const scope = jobTenantScope(options.tenantIds);\n whereParams.push(...scope.params);\n const isPostgres = getDatabaseEngine(this.db) === 'postgres';\n const candidateSelect = `\n SELECT id AS claim_id\n FROM _smrt_jobs\n WHERE ${whereConditions.join(' AND ')}${scope.sql}\n ORDER BY priority DESC, run_at ASC, created_at ASC, id ASC\n LIMIT ?${isPostgres ? ' FOR UPDATE SKIP LOCKED' : ''}\n `;\n const setClause = `\n SET status = 'running',\n worker_id = ?,\n worker_heartbeat = ?,\n started_at = ?,\n attempts = attempts + 1,\n updated_at = ?`;\n const setParams = [options.workerId, nowIso, startedAt, nowIso];\n\n // Worker-internal cross-tenant claim; tenant context is restored\n // per-job at execution (SmrtJob is now @TenantScoped, S5 #1402).\n const claimed = isPostgres\n ? await this.query(\n `WITH claim_candidates AS MATERIALIZED (${candidateSelect})\n UPDATE _smrt_jobs${setClause}\n FROM claim_candidates\n WHERE _smrt_jobs.id = claim_candidates.claim_id\n AND _smrt_jobs.status = 'pending'\n RETURNING ${SMRT_JOB_PORTABLE_SELECT_COLUMNS}`,\n [...whereParams, limit, ...setParams],\n { allowRawOnTenantScoped: true },\n )\n : await this.query(\n `UPDATE _smrt_jobs${setClause}\n WHERE id IN (${candidateSelect})\n AND status = 'pending'\n RETURNING ${SMRT_JOB_PORTABLE_SELECT_COLUMNS}`,\n [...setParams, ...whereParams, limit],\n { allowRawOnTenantScoped: true },\n );\n\n return claimed.toSorted(compareClaimOrder);\n }\n\n /**\n * Count non-terminal (pending/running) jobs owned by a tenant.\n *\n * Used to enforce the per-tenant creation cap so one tenant cannot exhaust\n * the shared worker pool (S5 audit #1402). Reads `_smrt_jobs` directly so it\n * works regardless of ambient tenant context.\n *\n * @param tenantId - Tenant to count for. `null` counts global (NULL-tenant)\n * jobs.\n */\n async countInFlightForTenant(tenantId: string | null): Promise<number> {\n const predicate = tenantId === null ? 'tenant_id IS NULL' : 'tenant_id = ?';\n const params = tenantId === null ? [] : [tenantId];\n\n // Use the public `db` accessor (with its init guard), not the protected\n // `_db` internal — consistent with claimReady()/this.db usage above. This\n // is a deliberately cross-tenant count (it must see every tenant's rows to\n // bound a single tenant), so it intentionally bypasses the tenant-scoped\n // query interceptor rather than routing through this.query().\n const result = await this.db.query(\n `SELECT COUNT(*) AS count\n FROM _smrt_jobs\n WHERE status IN ('pending', 'running')\n AND ${predicate}`,\n ...params,\n );\n\n const row = result.rows[0] as { count?: number | string } | undefined;\n return Number(row?.count ?? 0);\n }\n\n /**\n * The single creation path for queued jobs.\n *\n * Centralizes the two creation-time security guards from the S5 audit (#1402)\n * so every enqueue — the fluent {@link \"./job-builder\".JobBuilder} *and* the\n * ScheduleRunner's cron-triggered jobs — goes through one place:\n *\n * 1. `maxAttempts` is clamped to {@link MAX_JOB_RETRIES} so a misconfigured\n * caller cannot pin a worker on a poison job indefinitely.\n * 2. A per-tenant in-flight cap bounds how many non-terminal jobs one tenant\n * may hold, so one tenant cannot exhaust the shared worker pool\n * (cross-tenant denial of service). The cap applies to the row's effective\n * tenant (explicit `data.tenantId` or, when absent, the ambient context);\n * global (null-tenant) jobs are exempt.\n *\n * Atomicity note (best-effort soft cap, by design): the cap is a\n * count-then-insert, NOT a hard transactional invariant. It is intentionally\n * left non-atomic. A plain transaction would not help — under the adapters'\n * default isolation two concurrent same-tenant enqueues would each read the\n * same COUNT and both insert, so serializing them would require either a\n * per-tenant lock row (`SELECT ... FOR UPDATE`) or SERIALIZABLE-isolation\n * retry loops. That cross-process locking is fragile (lock-row contention,\n * adapter-specific isolation behavior, the `transaction` adapter method being\n * optional) and out of proportion to the threat: this cap is defense in depth\n * against runaway/accidental creation exhausting the shared worker pool, not a\n * billing/quota boundary. So under truly simultaneous enqueues a tenant may\n * momentarily overshoot by the number of in-flight creators; the bound still\n * prevents unbounded growth and closes the prior ScheduleRunner bypass. If a\n * hard guarantee is ever needed, enforce it with a DB CHECK/trigger or a\n * dedicated counter row, not an application-level lock.\n */\n async enqueueJob(\n data: SmrtJobData,\n options: EnqueueJobOptions = {},\n ): Promise<SmrtJob> {\n const cap = options.tenantJobCap ?? DEFAULT_TENANT_JOB_CAP;\n if (isJobHandlerTarget(data.objectType)) assertHandlerJobData(data);\n\n // Effective tenant: an explicitly provided tenantId wins (ScheduleRunner\n // passes the schedule's tenant even when no ambient context exists);\n // otherwise fall back to the ambient context (JobBuilder path).\n const explicitTenant =\n typeof data.tenantId === 'string' && data.tenantId.length > 0\n ? data.tenantId\n : data.tenantId === null\n ? null\n : undefined;\n const effectiveTenant =\n explicitTenant !== undefined ? explicitTenant : (getTenantId() ?? null);\n\n if (data.dedupeKey != null) {\n if (\n typeof data.dedupeKey !== 'string' ||\n data.dedupeKey.trim().length === 0 ||\n data.dedupeKey.length > 512\n ) {\n throw new TypeError(\n 'dedupeKey must be a nonblank string of at most 512 characters',\n );\n }\n assertDedupeTenantSpelling(effectiveTenant);\n const ambientTenant = getTenantId();\n assertDedupeTenantSpelling(ambientTenant ?? null);\n if (\n ambientTenant &&\n effectiveTenant !== ambientTenant &&\n !isSystemContext() &&\n !isSuperAdminBypass()\n ) {\n throw new TenantIsolationError(\n 'Cannot enqueue a job for another tenant',\n {\n tenantId: ambientTenant,\n attemptedTenantId: effectiveTenant ?? 'null',\n },\n );\n }\n const db = options.transaction ?? this.db;\n if (!options.transaction && !db.transaction)\n throw new Error('Job deduplication requires transaction support');\n await SmrtJobDedupeSlotCollection.create({ db });\n const slotKey = jobSlotKey(effectiveTenant, data.dedupeKey);\n const enqueue = async (tx: DatabaseInterface): Promise<string> => {\n const id = randomUUID();\n const now = new Date().toISOString();\n await tx.query(\n `INSERT INTO _smrt_job_dedupe_slots\n (id, slug, context, created_at, updated_at, slot_key, job_id)\n VALUES (?, ?, '', ?, ?, ?, NULL) ON CONFLICT (slot_key) DO NOTHING`,\n id,\n id,\n now,\n now,\n slotKey,\n );\n const slot = await tx.query(\n `UPDATE _smrt_job_dedupe_slots SET updated_at = ?\n WHERE slot_key = ? RETURNING job_id`,\n now,\n slotKey,\n );\n if (slot.rows.length !== 1)\n throw new Error('Job deduplication slot unavailable; retry enqueue');\n const jobs = await SmrtJobCollection.create({ db: tx });\n const jobId = slot.rows[0].job_id;\n if (typeof jobId === 'string') {\n const existing = await jobs.get({ id: jobId });\n if (existing && (existing.tenantId ?? null) !== effectiveTenant)\n throw new Error(\n 'Job deduplication slot has invalid tenant ownership',\n );\n if (\n existing &&\n (existing.status === 'pending' || existing.status === 'running')\n )\n return String(existing.id);\n }\n // Store provenance in the initial insert without reacquiring the slot.\n const job = await jobs.createQueuedJob(\n { ...data, tenantId: effectiveTenant },\n cap,\n );\n await tx.query(\n 'UPDATE _smrt_job_dedupe_slots SET job_id = ? WHERE slot_key = ?',\n job.id,\n slotKey,\n );\n return String(job.id);\n };\n let jobId: string;\n if (options.transaction) jobId = await enqueue(options.transaction);\n else {\n if (!db.transaction)\n throw new Error('Job deduplication requires transaction support');\n jobId = await db.transaction(enqueue);\n }\n // Do not return a model bound to a now-ended transaction.\n const resultCollection = options.transaction\n ? await SmrtJobCollection.create({ db: options.transaction })\n : this;\n const job = await resultCollection.get({ id: jobId });\n if (!job) throw new Error('Enqueued job is unavailable');\n return job;\n }\n if (options.transaction) {\n const jobs = await SmrtJobCollection.create({ db: options.transaction });\n return jobs.createQueuedJob({ ...data, tenantId: effectiveTenant }, cap);\n }\n return this.createQueuedJob({ ...data, tenantId: effectiveTenant }, cap);\n }\n\n /**\n * Enqueue a job for a registered named handler (#5005). The handler need\n * not be registered in this process: producers and runners are usually\n * different processes. Only runners that registered the handler claim the\n * job; one still `pending` past the runners' `handlerUnclaimedDeadlineMs`\n * is failed `handler-unclaimed`. Guards, dedupe and tenancy are those of\n * {@link enqueueJob}.\n */\n async enqueueHandlerJob(\n data: HandlerJobData,\n options: EnqueueJobOptions = {},\n ): Promise<SmrtJob> {\n const { handler, payload, ...rest } = data;\n return this.enqueueJob(\n {\n ...rest,\n ...jobHandlerTarget(handler),\n objectId: null,\n args: payload ?? {},\n },\n options,\n );\n }\n\n /** Persist once, without a second save racing a consumer's first claim. */\n private async createQueuedJob(\n data: SmrtJobData,\n cap: number,\n ): Promise<SmrtJob> {\n const effectiveTenant = data.tenantId;\n if (effectiveTenant && cap > 0) {\n const current = await this.countInFlightForTenant(effectiveTenant);\n assertWithinTenantCreationCap(effectiveTenant, current, cap);\n }\n\n const job = await this.create({\n ...data,\n // Clamp here so neither the builder nor the schedule runner can bypass the\n // retry ceiling (S5 audit #1402).\n maxAttempts: clampRetries(data.maxAttempts ?? 3),\n });\n return job;\n }\n\n /**\n * Get job statistics\n */\n async stats(queue?: string): Promise<{\n pending: number;\n running: number;\n completed: number;\n failed: number;\n cancelled: number;\n }> {\n const query = queue\n ? 'SELECT status, COUNT(*) as count FROM _smrt_jobs WHERE queue = ? GROUP BY status'\n : 'SELECT status, COUNT(*) as count FROM _smrt_jobs GROUP BY status';\n const params = queue ? [queue] : [];\n\n const result = await this._db.query(query, ...params);\n\n const counts: Record<string, number> = {};\n for (const row of result.rows) {\n counts[row.status as string] = row.count as number;\n }\n\n return {\n pending: counts.pending ?? 0,\n running: counts.running ?? 0,\n completed: counts.completed ?? 0,\n failed: counts.failed ?? 0,\n cancelled: counts.cancelled ?? 0,\n };\n }\n\n /**\n * Cleanup old completed/failed jobs.\n *\n * Predicates are `(status, completed_at)` pairs, covered by\n * `idx_smrt_jobs_status_completed_at` (created by the jobs compatibility\n * path this collection runs on initialize — #2375).\n *\n * @param options.dryRun - Count the jobs the cutoffs select without deleting\n * them, so a retention preview reports exactly what a real run removes.\n * @returns Number of jobs deleted (or, under `dryRun`, matched).\n */\n async cleanup(options: {\n completedBefore?: Date;\n failedBefore?: Date;\n cancelledBefore?: Date;\n limit?: number;\n dryRun?: boolean;\n }): Promise<number> {\n const conditions: string[] = [];\n const params: unknown[] = [];\n\n if (options.completedBefore) {\n conditions.push(\"(status = 'completed' AND completed_at < ?)\");\n params.push(options.completedBefore.toISOString());\n }\n\n if (options.failedBefore) {\n conditions.push(\"(status = 'failed' AND completed_at < ?)\");\n params.push(options.failedBefore.toISOString());\n }\n\n if (options.cancelledBefore) {\n conditions.push(\"(status = 'cancelled' AND completed_at < ?)\");\n params.push(options.cancelledBefore.toISOString());\n }\n\n if (conditions.length === 0) return 0;\n\n const selector = options.limit\n ? `id IN (\n SELECT id FROM _smrt_jobs\n WHERE (${conditions.join(' OR ')})\n LIMIT ?\n )`\n : `(${conditions.join(' OR ')})`;\n const selectorParams = options.limit\n ? [...params, options.limit]\n : [...params];\n\n // Count first: `rowCount` is not reliably populated across the engines\n // SMRT supports, and counting is what lets `dryRun` preview the exact\n // predicate a real cleanup would delete (#2375).\n const counted = await this._db.query(\n `SELECT COUNT(*) AS total FROM _smrt_jobs WHERE ${selector}`,\n ...selectorParams,\n );\n const total = Number(counted.rows?.[0]?.total ?? 0);\n if (!Number.isFinite(total) || total <= 0) return 0;\n\n if (!options.dryRun) {\n await this._db.query(\n `DELETE FROM _smrt_jobs WHERE ${selector}`,\n ...selectorParams,\n );\n }\n\n return total;\n }\n}\n\nfunction getDatabaseEngine(\n db: DatabaseInterface,\n): ReturnType<typeof detectEngine> {\n return resolveEngine(db);\n}\n\nfunction compareClaimOrder(left: SmrtJob, right: SmrtJob): number {\n const priority = right.priority - left.priority;\n if (priority !== 0) return priority;\n\n const runAt = left.runAt.getTime() - right.runAt.getTime();\n if (runAt !== 0) return runAt;\n\n const createdAt = timestamp(left.created_at) - timestamp(right.created_at);\n if (createdAt !== 0) return createdAt;\n\n return (left.id ?? '').localeCompare(right.id ?? '');\n}\n\nfunction timestamp(value: Date | null | undefined): number {\n return value?.getTime() ?? 0;\n}\n\nexport default SmrtJob;\n\nfunction jobSlotKey(tenant: string | null, key: string): string {\n return createHash('sha256')\n .update(JSON.stringify([tenant, key]))\n .digest('hex');\n}\n\n/** Internal SQL predicate shared by ready claims and worker recovery. */\nexport function jobTenantScope(\n tenantIds: readonly (string | null)[] | undefined,\n): { sql: string; params: string[] } {\n if (tenantIds === undefined) return { sql: '', params: [] };\n if (\n !Array.isArray(tenantIds) ||\n tenantIds.some(\n (id) => id !== null && (typeof id !== 'string' || !id.trim()),\n )\n )\n throw new TypeError('tenantIds must contain nonblank identities or null');\n const ids = tenantIds.filter((id): id is string => id !== null);\n const terms: string[] = [];\n if (ids.length) terms.push(`tenant_id IN (${ids.map(() => '?').join(', ')})`);\n if (tenantIds.includes(null)) terms.push('tenant_id IS NULL');\n return {\n sql: ` AND ${terms.length ? `(${terms.join(' OR ')})` : '1 = 0'}`,\n params: ids,\n };\n}\n\ntype RetryJobRow = Record<string, unknown> & {\n id: string;\n tenant_id: string | null;\n dedupe_key: string | null;\n status: JobStatus;\n args: unknown;\n};\n\nfunction retryRow(row: Record<string, unknown>): RetryJobRow {\n if (\n typeof row.id !== 'string' ||\n (row.tenant_id !== null && typeof row.tenant_id !== 'string')\n )\n throw new Error('Invalid persisted job identity');\n return row as RetryJobRow;\n}\n\nasync function readRetryJob(\n db: DatabaseInterface,\n id: string,\n): Promise<RetryJobRow> {\n const result = await db.query(\n `SELECT ${SMRT_JOB_PORTABLE_SELECT_COLUMNS} FROM _smrt_jobs WHERE id = ?`,\n id,\n );\n if (result.rows.length !== 1)\n throw new Error('Persisted retry job is unavailable');\n return retryRow(result.rows[0]);\n}\n\nfunction assertRetryTenant(tenant: string | null): void {\n const ambient = getTenantId();\n if (\n ambient &&\n tenant !== ambient &&\n !isSystemContext() &&\n !isSuperAdminBypass()\n ) {\n throw new TenantIsolationError('Cannot retry a job for another tenant', {\n tenantId: ambient,\n attemptedTenantId: tenant ?? 'null',\n });\n }\n}\n\nfunction assertRetryStatus(status: JobStatus): void {\n if (status === 'completed' || status === 'running')\n throw new Error(`Cannot retry a ${status} job`);\n if (!['pending', 'failed', 'cancelled'].includes(status))\n throw new Error('Unknown persisted retry job status');\n}\n\nfunction persistedDedupeKey(value: unknown): string | null {\n if (value === null) return null;\n if (typeof value !== 'string' || !value.trim())\n throw new Error('Invalid persisted dedupeKey');\n return value;\n}\n\nfunction persistedArguments(value: unknown): Record<string, unknown> {\n const args = typeof value === 'string' ? JSON.parse(value) : value;\n if (!args || typeof args !== 'object' || Array.isArray(args))\n throw new Error('Invalid persisted job arguments');\n return args as Record<string, unknown>;\n}\n\ninterface PersistedScheduleAssociation {\n id: string;\n canonicalOccurrence: boolean;\n}\nfunction persistedScheduleAssociation(\n value: unknown,\n): PersistedScheduleAssociation | null {\n const args = persistedArguments(value);\n const canonicalOccurrence =\n Object.hasOwn(args, '_scheduledFor') ||\n Object.hasOwn(args, '_scheduleAdmission');\n if (!Object.hasOwn(args, '_scheduleId')) {\n if (canonicalOccurrence)\n throw new Error('Invalid persisted schedule association');\n return null;\n }\n if (typeof args._scheduleId !== 'string' || !args._scheduleId.trim())\n throw new Error('Invalid persisted schedule association');\n return { id: args._scheduleId, canonicalOccurrence };\n}\n\n/** @internal Execution target of an AgentSchedule, independent of caller metadata names. */\nexport interface ScheduleJobTarget {\n objectType: string;\n objectId: string | null;\n method: string;\n}\nfunction persistedJobTarget(row: Record<string, unknown>): ScheduleJobTarget {\n if (\n typeof row.object_type !== 'string' ||\n typeof row.method !== 'string' ||\n (row.object_id !== null && typeof row.object_id !== 'string')\n )\n throw new Error('Invalid persisted retry target');\n return {\n objectType: row.object_type,\n objectId: row.object_id as string | null,\n method: row.method,\n };\n}\nfunction scheduleJobTarget(row: Record<string, unknown>): ScheduleJobTarget {\n return {\n objectType: String(row.agent_type ?? ''),\n objectId: row.agent_id == null ? null : String(row.agent_id),\n method: String(row.method || 'run'),\n };\n}\nfunction sameScheduleTarget(\n left: ScheduleJobTarget,\n right: ScheduleJobTarget,\n): boolean {\n const canonical = (name: string) =>\n ObjectRegistry.getClass(name)?.qualifiedName || name;\n return (\n canonical(left.objectType) === canonical(right.objectType) &&\n left.objectId === right.objectId &&\n left.method === right.method\n );\n}\nasync function lockRetrySchedule(\n tx: DatabaseInterface,\n association: PersistedScheduleAssociation,\n job: RetryJobRow,\n): Promise<{ id: string; capacity: number; target: ScheduleJobTarget } | null> {\n // _scheduleId predates AgentSchedule admission and is also ordinary producer\n // metadata. Do not issue missing-table SQL and then continue an aborted PG tx.\n if (!(await tx.tableExists('_smrt_agent_schedules'))) {\n if (association.canonicalOccurrence)\n throw new Error('Scheduled retry association is unavailable');\n return null;\n }\n const predicate =\n job.tenant_id === null ? 'tenant_id IS NULL' : 'tenant_id = ?';\n const tenants = job.tenant_id === null ? [] : [job.tenant_id];\n const columns =\n 'CAST(id AS VARCHAR) AS id, agent_type, CAST(agent_id AS VARCHAR) AS agent_id, method, max_concurrent';\n // Cast the read identity so unrelated producers' opaque metadata never causes\n // an invalid-UUID error merely because an AgentSchedule table is installed.\n const candidate = (\n await tx.query(\n `SELECT ${columns} FROM _smrt_agent_schedules WHERE CAST(id AS VARCHAR) = ? AND ${predicate}`,\n association.id,\n ...tenants,\n )\n ).rows[0];\n if (\n !candidate ||\n (!association.canonicalOccurrence &&\n !sameScheduleTarget(\n persistedJobTarget(job),\n scheduleJobTarget(candidate),\n ))\n ) {\n if (association.canonicalOccurrence)\n throw new Error('Scheduled retry association is unavailable');\n return null;\n }\n const locked = (\n await tx.query(\n `UPDATE _smrt_agent_schedules SET running_count = running_count\n WHERE id = ? AND ${predicate} RETURNING ${columns}`,\n candidate.id,\n ...tenants,\n )\n ).rows[0];\n if (\n !locked ||\n (!association.canonicalOccurrence &&\n !sameScheduleTarget(persistedJobTarget(job), scheduleJobTarget(locked)))\n )\n throw new Error(\n 'Scheduled retry association changed; retry from current state',\n );\n const capacity = Number(locked.max_concurrent ?? 1);\n if (!Number.isSafeInteger(capacity) || capacity < 1)\n throw new Error('Scheduled retry capacity is invalid');\n return { id: String(locked.id), capacity, target: scheduleJobTarget(locked) };\n}\n\n/** @internal Count canonical occurrences and matching legacy target slots for admission/retry. */\nexport async function countScheduleJobs(\n db: DatabaseInterface,\n scheduleId: string,\n tenant: string | null,\n target: ScheduleJobTarget,\n excludeJobId?: string,\n): Promise<number> {\n const result = await db.query(\n `SELECT args, object_type, CAST(object_id AS VARCHAR) AS object_id, method FROM _smrt_jobs WHERE status IN ('pending', 'running')\n AND ${tenant === null ? 'tenant_id IS NULL' : 'tenant_id = ?'}${excludeJobId ? ' AND id <> ?' : ''}`,\n ...(tenant === null ? [] : [tenant]),\n ...(excludeJobId ? [excludeJobId] : []),\n );\n return result.rows.filter((row) => {\n try {\n const association = persistedScheduleAssociation(row.args);\n return (\n association?.id === scheduleId &&\n (association.canonicalOccurrence ||\n sameScheduleTarget(persistedJobTarget(row), target))\n );\n } catch {\n return false;\n }\n }).length;\n}\n\nfunction assertDedupeTenantSpelling(tenant: string | null): void {\n if (tenant === null) return;\n const uuidLike = /^[0-9a-f]{32}$/i.test(tenant.replace(/[{}-]/g, ''));\n const canonical =\n /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/.test(\n tenant,\n );\n if (uuidLike && !canonical)\n throw new TypeError(\n 'Keyed jobs require canonical lowercase hyphenated UUID tenant IDs; load the canonical tenant identity before enqueue',\n );\n}\n","/**\n * Job retention — bounded growth for `_smrt_jobs` and `_smrt_job_events`\n * (issue #2375, assessment finding F2).\n *\n * `SmrtJobCollection.cleanup()` has always existed but nothing ever called it,\n * and `_smrt_job_events` — one row per log line, progress tick and lifecycle\n * transition — had no prune path at all. This module contributes both to the\n * framework retention sweep so `smrt db:prune` and the `TaskRunner`'s periodic\n * sweep drive them like every other framework-owned table.\n *\n * The package entry point registers both tasks on import (see `index.ts`), so\n * any process that loaded `@happyvertical/smrt-jobs` — a worker, an app, or\n * `smrt db:prune` — contributes them. Registration is not scheduling: a task\n * runs only when something calls `runRetentionSweep()`, and a policy can turn\n * it off by name. Call {@link registerJobRetentionTasks} again to change the\n * windows, or {@link unregisterJobRetentionTasks} to remove them entirely.\n *\n * Task names are prefixed with the owning package's short name, because the\n * registry is one process-global namespace shared with every other package.\n *\n * @see https://github.com/happyvertical/smrt/issues/2375\n * @packageDocumentation\n */\n\nimport { createLogger } from '@happyvertical/logger';\nimport {\n type RetentionPolicy,\n type RetentionSweepResult,\n registerRetentionTask,\n runRetentionSweep,\n unregisterRetentionTask,\n} from '@happyvertical/smrt-core';\nimport type { DatabaseInterface } from '@happyvertical/sql';\nimport { SmrtJobCollection } from './smrt-job.js';\nimport { SmrtJobEventCollection } from './smrt-job-event.js';\n\nconst logger = createLogger({ level: 'info' });\n\nconst MS_PER_DAY = 24 * 60 * 60 * 1000;\n\n/** Retention task name for terminal rows in `_smrt_jobs`. */\nexport const JOBS_RETENTION_TASK = 'jobs-records';\n\n/** Retention task name for `_smrt_job_events`. */\nexport const JOB_EVENTS_RETENTION_TASK = 'jobs-events';\n\n/** Windows applied by the job retention tasks. */\nexport interface JobRetentionOptions {\n /** Delete completed jobs finished more than this many days ago (default 7). */\n completedOlderThanDays?: number;\n /** Delete cancelled jobs finished more than this many days ago (default 7). */\n cancelledOlderThanDays?: number;\n /** Delete failed jobs finished more than this many days ago (default 30). */\n failedOlderThanDays?: number;\n /** Delete job events recorded more than this many days ago (default 30). */\n eventsOlderThanDays?: number;\n /** Maximum job rows removed per sweep (default 10 000). */\n batchSize?: number;\n}\n\n/**\n * Documented job retention defaults.\n *\n * Completed and cancelled work is the bulk of the table and is uninteresting\n * within a week; failures are kept a month because that is how long anyone\n * looks at them. Events outlive the jobs they describe by design — a job row\n * deleted at 7 days can still have its log read for another three weeks.\n */\nexport const DEFAULT_JOB_RETENTION: Required<JobRetentionOptions> = {\n completedOlderThanDays: 7,\n cancelledOlderThanDays: 7,\n failedOlderThanDays: 30,\n eventsOlderThanDays: 30,\n batchSize: 10_000,\n};\n\n/**\n * Register the job and job-event retention tasks with the framework sweep.\n *\n * Idempotent: re-registering replaces the previous tasks, so repeated calls\n * (multiple runners in one process, module re-evaluation) do not duplicate\n * work.\n */\nexport function registerJobRetentionTasks(\n options: JobRetentionOptions = {},\n): void {\n const config = { ...DEFAULT_JOB_RETENTION, ...options };\n\n registerRetentionTask({\n name: JOBS_RETENTION_TASK,\n description: 'Prune terminal job rows (_smrt_jobs)',\n run: async (db, context) => {\n const jobs = await SmrtJobCollection.create({ db });\n const cutoff = (days: number) =>\n new Date(context.now.getTime() - days * MS_PER_DAY);\n\n return jobs.cleanup({\n completedBefore: cutoff(config.completedOlderThanDays),\n cancelledBefore: cutoff(config.cancelledOlderThanDays),\n failedBefore: cutoff(config.failedOlderThanDays),\n limit: config.batchSize,\n dryRun: context.dryRun,\n });\n },\n });\n\n registerRetentionTask({\n name: JOB_EVENTS_RETENTION_TASK,\n description: 'Prune job event history (_smrt_job_events)',\n run: async (db, context) => {\n const events = await SmrtJobEventCollection.create({ db });\n return events.cleanup({\n before: new Date(\n context.now.getTime() - config.eventsOlderThanDays * MS_PER_DAY,\n ),\n dryRun: context.dryRun,\n });\n },\n });\n}\n\n/** Remove the job retention tasks from the framework sweep. */\nexport function unregisterJobRetentionTasks(): void {\n unregisterRetentionTask(JOBS_RETENTION_TASK);\n unregisterRetentionTask(JOB_EVENTS_RETENTION_TASK);\n}\n\n/** Configuration for {@link startRetentionSweeper}. */\nexport interface RetentionSweeperOptions {\n /** How often to sweep, in milliseconds (default 6 hours). */\n intervalMs?: number;\n /** Policy handed to `runRetentionSweep` on each tick. */\n policy?: RetentionPolicy;\n /** Windows for the job retention tasks this sweeper registers. */\n jobs?: JobRetentionOptions;\n}\n\n/** Handle returned by {@link startRetentionSweeper}. */\nexport interface RetentionSweeper {\n /** Stop the periodic sweep timer. Does not unregister the job tasks. */\n stop(): void;\n /** Run one sweep immediately (used by tests and by manual triggers). */\n sweepNow(): Promise<RetentionSweepResult>;\n}\n\n/** Default sweep cadence: four times a day is ample for day-scale windows. */\nexport const DEFAULT_RETENTION_SWEEP_INTERVAL_MS = 6 * 60 * 60 * 1000;\n\n/**\n * Start a periodic retention sweep on an interval.\n *\n * The first sweep runs one full interval after start, never at start: a worker\n * process restarting in a crash loop must not turn into a delete loop, and a\n * short-lived process (a test, a one-shot worker) should exit without having\n * deleted anything it was not asked to.\n *\n * The timer is `unref`'d where the runtime supports it, so a pending sweep\n * never keeps a process alive.\n *\n * **`stop()` never unregisters the job tasks.** The package entry point\n * (`index.ts`) registers them unconditionally on import, so \"this process\n * loaded `@happyvertical/smrt-jobs`\" is what contributes them — not \"a\n * sweeper happens to be running\". Making `stop()` unregister would silently\n * break that contract the moment a `TaskRunner` restarts (or a second,\n * independent caller in the same process runs `runRetentionSweep()` after\n * the first sweeper stops): the tasks would vanish from the sweep even\n * though the package is still loaded. `options.jobs` still lets a caller\n * override the default windows — each call to this function re-registers\n * with whatever config it was given, the same idempotent replace\n * {@link registerJobRetentionTasks} already documents. Callers that want a\n * genuinely clean registry (tests, teardown) call\n * {@link unregisterJobRetentionTasks} themselves.\n *\n * @param db - Database holding the system tables.\n * @param options - Cadence and policy overrides.\n * @returns A handle that stops the periodic timer.\n */\nexport function startRetentionSweeper(\n db: DatabaseInterface,\n options: RetentionSweeperOptions = {},\n): RetentionSweeper {\n registerJobRetentionTasks(options.jobs);\n\n const intervalMs = options.intervalMs ?? DEFAULT_RETENTION_SWEEP_INTERVAL_MS;\n let stopped = false;\n\n const sweepNow = async (): Promise<RetentionSweepResult> =>\n runRetentionSweep(db, options.policy);\n\n const timer = setInterval(() => {\n if (stopped) return;\n sweepNow().catch((error) => {\n logger.warn(\n `[smrt-jobs] retention sweep failed: ${\n error instanceof Error ? error.message : String(error)\n }`,\n );\n });\n }, intervalMs);\n\n if (typeof timer === 'object' && typeof timer.unref === 'function') {\n timer.unref();\n }\n\n return {\n stop() {\n if (stopped) return;\n stopped = true;\n clearInterval(timer);\n },\n sweepNow,\n };\n}\n","/**\n * Redact secret-shaped substrings from a job error message before it is\n * persisted to the `_smrt_jobs.last_error` column.\n *\n * @remarks\n * `last_error` is durable and readable through generated `list`/`get` routes\n * (now tenant-scoped — see {@link \"./smrt-job\".SmrtJob}). Error messages thrown\n * from a failing job frequently echo back the arguments or environment that\n * caused the failure: a database URL with embedded credentials, a `Bearer`\n * token, an `Authorization` header, an API key, or a `key=value` secret pair.\n * Persisting those verbatim turns a transient failure into a durable credential\n * leak (S5 audit #1402).\n *\n * The policy biases toward over-redaction: matching a benign string is a\n * cosmetic loss, while leaking a credential is a security incident. Patterns are\n * intentionally conservative and order-independent — each is applied globally so\n * multiple secrets in one message are all masked.\n */\n\nconst REDACTED = '***REDACTED***';\n\n/**\n * Credentials embedded in a URL userinfo segment:\n * `scheme://user:pass@host` → `scheme://***REDACTED***@host`.\n * The host is preserved so the message stays diagnosable.\n */\nconst CREDENTIAL_URL_RE = /([a-z][a-z0-9+.-]*:\\/\\/)[^/?#@\\s]+@/gi;\n\n/**\n * `Bearer <token>` / `token <token>` style authorization values.\n */\nconst BEARER_TOKEN_RE = /\\b(bearer|token)\\s+[A-Za-z0-9._\\-+/=]{8,}/gi;\n\n/**\n * An `Authorization:` header value (covers Basic/Bearer/etc.). Captures the\n * scheme word plus the credential token that follows it so the whole value is\n * masked, not just the scheme.\n */\nconst AUTHORIZATION_HEADER_RE =\n /\\bauthorization\\s*[:=]\\s*(?:[A-Za-z]+\\s+)?[^\\s,;)]+/gi;\n\n/**\n * Common secret-bearing `key=value` / `key: value` pairs. The key portion is\n * preserved so the shape of the failure remains legible; only the value is\n * masked. Matches camelCase / snake_case / kebab / UPPER variants.\n */\nconst SECRET_KEY_VALUE_RE =\n /\\b([A-Za-z0-9_-]*(?:password|passwd|pwd|secret|api[_-]?key|access[_-]?key|secret[_-]?key|private[_-]?key|client[_-]?secret|token|credential|auth)[A-Za-z0-9_-]*)\\s*([:=])\\s*(\"[^\"]*\"|'[^']*'|[^\\s,;)]+)/gi;\n\n/**\n * Secret-bearing keys written as JSON object members, e.g.\n * `{\"password\":\"x\"}` or `{ \"apiKey\" : \"y\" }`. The generic key=value rule above\n * cannot see these because the key is wrapped in quotes (so the separator does\n * not immediately follow the key word). The quoted key is preserved; only the\n * quoted value is masked (S5 audit #1402).\n */\nconst JSON_SECRET_KEY_VALUE_RE =\n /(\"(?:[A-Za-z0-9_-]*(?:password|passwd|pwd|secret|api[_-]?key|access[_-]?key|secret[_-]?key|private[_-]?key|client[_-]?secret|token|credential|auth)[A-Za-z0-9_-]*)\")\\s*:\\s*\"[^\"]*\"/gi;\n\n/**\n * Provider-recognizable standalone secrets that may appear without a key:\n * OpenAI `sk-...` (incl. hyphenated project keys like `sk-proj-...`) /\n * `sk_live_...` / `sk_test_...`, AWS access key id (`AKIA...`), GitHub tokens\n * (`ghp_`/`gho_`/`ghu_`/`ghs_`/`ghr_`), Google API keys (`AIza...`), and Slack\n * bot/user tokens (`xoxb-`/`xoxp-`) (S5 audit #1402).\n *\n * The OpenAI patterns allow internal hyphens/underscores in the token *body*\n * (after the `sk-`/`sk_` prefix) so segmented keys such as `sk-proj-ABC123...`\n * are matched whole rather than truncated at the first separator. The body must\n * end on an alphanumeric so a trailing separator is not swallowed, and a length\n * floor keeps short benign `sk-foo` tokens from over-matching.\n */\nconst STANDALONE_SECRET_RE =\n /\\b(sk-[A-Za-z0-9_-]{14,}[A-Za-z0-9]|sk_(?:live|test)_[A-Za-z0-9_-]{14,}[A-Za-z0-9]|AKIA[0-9A-Z]{12,}|gh[pousr]_[A-Za-z0-9]{20,}|AIza[A-Za-z0-9_-]{20,}|xox[bp]-[A-Za-z0-9-]{10,})\\b/g;\n\n/**\n * Mask secret-shaped substrings in an error message.\n *\n * Strictly `string => string`: pass a known message here. For an arbitrary\n * throwable of unknown shape (e.g. a caught `unknown`), call\n * {@link redactErrorForPersistence} instead — it coerces non-`Error` values to\n * a string first. The runtime non-string guard below is defensive depth only;\n * the type contract is that callers supply a string.\n *\n * @param message - Raw error message (e.g. `error.message`).\n * @returns The message with credential-like substrings replaced by\n * `***REDACTED***`. Empty input is returned unchanged.\n *\n * @example\n * ```ts\n * redactErrorMessage('connect failed: postgres://u:p@db/app')\n * // => 'connect failed: postgres://***REDACTED***@db/app'\n * redactErrorMessage('401 from api: apiKey=<the-key>')\n * // => '401 from api: apiKey=***REDACTED***'\n * ```\n */\nexport function redactErrorMessage(message: string): string {\n if (typeof message !== 'string' || message.length === 0) {\n return message;\n }\n\n return (\n message\n .replace(CREDENTIAL_URL_RE, `$1${REDACTED}@`)\n // Authorization headers run before the generic key=value rule so the\n // full `<scheme> <token>` value is masked rather than just the scheme.\n .replace(AUTHORIZATION_HEADER_RE, `authorization=${REDACTED}`)\n .replace(BEARER_TOKEN_RE, `$1 ${REDACTED}`)\n // JSON-shaped secrets run before the generic key=value rule (which cannot\n // match a quoted key) so `{\"password\":\"x\"}` is masked to a valid shape.\n .replace(JSON_SECRET_KEY_VALUE_RE, `$1:\"${REDACTED}\"`)\n .replace(SECRET_KEY_VALUE_RE, `$1$2${REDACTED}`)\n .replace(STANDALONE_SECRET_RE, REDACTED)\n );\n}\n\n/**\n * Redact an arbitrary error's message, tolerating non-Error throwables.\n *\n * @param error - Anything thrown (`Error`, string, or unknown).\n * @returns A redacted message string suitable for persistence.\n */\nexport function redactErrorForPersistence(error: unknown): string {\n if (error instanceof Error) {\n return redactErrorMessage(error.message);\n }\n return redactErrorMessage(String(error));\n}\n","// Self-register this package's manifest for consumers that import via this\n// subpath without the main entry. See src/__smrt-register__.ts (issue #1132).\nimport './__smrt-register__.js';\n\nimport {\n field,\n SmrtCollection,\n SmrtObject,\n smrt,\n} from '@happyvertical/smrt-core';\n\n/**\n * Liveness record for a single TaskRunner / ScheduleRunner incarnation,\n * stored in the `_smrt_workers` system table.\n *\n * @remarks\n * Job recovery asks \"is this job's owning worker alive?\" rather than \"is this\n * job's heartbeat fresh?\" (issue #1474). Each running worker keeps a row here\n * and renews `leaseExpiresAt` on a fixed cadence; a worker that dies stops\n * renewing and its lease expires, so its `running` jobs are recovered.\n *\n * `workerId` is unique per *incarnation* (a restarted runner gets a new key —\n * see `createWorkerKey`), which is what lets recovery distinguish a crashed\n * worker's orphaned jobs from an identically-configured restart.\n *\n * `leaseExpiresAt` is a `datetime` so it maps to a real timestamp column on\n * every engine (an integer epoch-ms column overflows `int4`/`INT32` on\n * Postgres and DuckDB). Stage 1 writes/compares it against the host clock —\n * the same approach the previous heartbeat recovery used; Stage 2 will move to\n * database-side time once an off-loop writer exists.\n */\n@smrt({\n tableName: '_smrt_workers',\n conflictColumns: ['worker_id'],\n api: false,\n cli: false,\n mcp: false,\n})\nexport class SmrtWorker extends SmrtObject { static __smrtPackage__ = \"@happyvertical/smrt-jobs\";\n /** Per-incarnation-unique worker key (also stored on owned jobs' workerId). */\n @field({ type: 'text', required: true, requiredFor: 'identity' })\n workerId: string = '';\n\n /** OS process id of the owning runner (diagnostic). */\n @field({ type: 'integer', nullable: true })\n pid: number | null = null;\n\n /** Hostname of the owning runner (diagnostic). */\n @field({ type: 'text', nullable: true })\n hostname: string | null = null;\n\n /** When this incarnation started. */\n @field({ type: 'datetime', nullable: true })\n startedAt: Date | null = null;\n\n /** Last lease renewal time (diagnostic; liveness uses leaseExpiresAt). */\n @field({ type: 'datetime', nullable: true })\n heartbeatAt: Date | null = null;\n\n /** Lease expiry — the worker is alive while this is in the future. */\n @field({ type: 'datetime', nullable: true })\n leaseExpiresAt: Date | null = null;\n\n /**\n * Queues this runner polls (its `TaskRunnerConfig.queues`), written at\n * registration and refreshed on every lease renewal. `null` for rows that\n * predate the column or belong to a runner that polls no queue.\n */\n @field({ type: 'json', nullable: true })\n queues: string[] | null = null;\n\n /** Lifecycle status (`running` while the runner is processing). */\n @field({ type: 'text', required: true, default: 'running' })\n status: string = 'running';\n}\n\nexport interface RegisterWorkerInput {\n workerKey: string;\n pid?: number | null;\n hostname?: string | null;\n leaseTtlMs: number;\n /** Queues the runner polls; stored so hosts can tell who reads a queue. */\n queues?: string[] | null;\n}\n\n/** Normalise a stored `queues` value (JSON text on SQLite, array on Postgres). */\nfunction parseQueues(value: unknown): string[] | null {\n let parsed = value;\n if (typeof value === 'string') {\n try {\n parsed = JSON.parse(value);\n } catch {\n return null;\n }\n }\n if (!Array.isArray(parsed)) return null;\n return parsed.filter((q): q is string => typeof q === 'string');\n}\n\n/**\n * Collection for managing `_smrt_workers` liveness rows.\n */\nexport class SmrtWorkerCollection extends SmrtCollection<SmrtWorker> {\n static readonly _itemClass = SmrtWorker;\n\n /**\n * Fail fast if the `_smrt_workers` table has not been migrated.\n *\n * The framework never creates application/system tables at runtime; the\n * table is created by `smrt db:migrate` (or `getTestDatabase`). A consumer\n * that upgrades smrt-jobs without migrating must get a clear, actionable\n * error at `start()` rather than a confusing recovery failure later.\n */\n async assertReady(): Promise<void> {\n try {\n await this.db.query('SELECT 1 FROM _smrt_workers LIMIT 1');\n } catch (error) {\n throw new Error(\n 'The _smrt_workers table is missing. Run `smrt db:migrate` to create ' +\n 'job-system tables before starting a TaskRunner/ScheduleRunner. ' +\n `(underlying error: ${(error as Error).message})`,\n );\n }\n }\n\n /** Whether the `_smrt_workers` table exists (recovery skips lease checks if not). */\n async tableReady(): Promise<boolean> {\n try {\n await this.db.query('SELECT 1 FROM _smrt_workers LIMIT 1');\n return true;\n } catch {\n return false;\n }\n }\n\n /** Register a worker incarnation with its lease seeded to `now + ttl`. */\n async registerWorker(input: RegisterWorkerInput): Promise<void> {\n const now = new Date();\n await this.create({\n workerId: input.workerKey,\n pid: input.pid ?? null,\n hostname: input.hostname ?? null,\n startedAt: now,\n heartbeatAt: now,\n // Seed the lease in the same write so the worker is immediately \"alive\",\n // closing the window between registration and the first claimReady().\n leaseExpiresAt: new Date(now.getTime() + input.leaseTtlMs),\n queues: input.queues ? [...input.queues] : null,\n status: 'running',\n });\n }\n\n /** Renew a worker's lease to `now + ttl`. */\n async renewLease(\n workerKey: string,\n leaseTtlMs: number,\n queues?: string[] | null,\n ): Promise<void> {\n const now = new Date();\n const expiresAt = new Date(now.getTime() + leaseTtlMs).toISOString();\n if (queues) {\n await this.db.query(\n `UPDATE _smrt_workers\n SET lease_expires_at = ?,\n heartbeat_at = ?,\n queues = ?\n WHERE worker_id = ?`,\n expiresAt,\n now.toISOString(),\n JSON.stringify(queues),\n workerKey,\n );\n return;\n }\n await this.db.query(\n `UPDATE _smrt_workers\n SET lease_expires_at = ?,\n heartbeat_at = ?\n WHERE worker_id = ?`,\n expiresAt,\n now.toISOString(),\n workerKey,\n );\n }\n\n /** Remove a worker incarnation (graceful shutdown). */\n async expireWorker(workerKey: string): Promise<void> {\n await this.db.query(\n 'DELETE FROM _smrt_workers WHERE worker_id = ?',\n workerKey,\n );\n }\n\n /** Worker keys whose database lease is still fresh (alive cross-process). */\n async freshLeaseWorkerKeys(): Promise<Set<string>> {\n const result = await this.db.query(\n `SELECT worker_id\n FROM _smrt_workers\n WHERE lease_expires_at IS NOT NULL\n AND lease_expires_at >= ?`,\n new Date().toISOString(),\n );\n const keys = new Set<string>();\n for (const row of result.rows as Array<{ worker_id?: unknown }>) {\n if (typeof row.worker_id === 'string') keys.add(row.worker_id);\n }\n return keys;\n }\n\n /**\n * Worker keys holding a fresh lease whose recorded `queues` include `queue`.\n * Rows with no recorded queues (older runners, schedule runners) never match.\n */\n async liveWorkerKeysForQueue(queue: string): Promise<Set<string>> {\n const result = await this.db.query(\n `SELECT worker_id, queues\n FROM _smrt_workers\n WHERE lease_expires_at IS NOT NULL\n AND lease_expires_at >= ?`,\n new Date().toISOString(),\n );\n const keys = new Set<string>();\n for (const row of result.rows as Array<{\n worker_id?: unknown;\n queues?: unknown;\n }>) {\n if (typeof row.worker_id !== 'string') continue;\n if (parseQueues(row.queues)?.includes(queue)) keys.add(row.worker_id);\n }\n return keys;\n }\n\n /** Delete worker rows whose lease expired more than `graceMs` ago. */\n async pruneExpired(graceMs: number): Promise<void> {\n const cutoff = new Date(Date.now() - Math.max(0, graceMs)).toISOString();\n await this.db.query(\n `DELETE FROM _smrt_workers\n WHERE lease_expires_at IS NOT NULL\n AND lease_expires_at < ?`,\n cutoff,\n );\n }\n}\n\nexport default SmrtWorker;\n","import type { Logger } from '@happyvertical/logger';\nimport type { McpTaskContinuation } from './mcp-task.js';\n\n/**\n * Job context for logging\n */\nexport interface JobContext {\n jobId: string;\n attempt: number;\n queue: string;\n objectType: string;\n method: string;\n}\n\nexport interface JobEventInput {\n type?: string;\n level?: 'debug' | 'info' | 'warn' | 'error';\n stage?: string | null;\n progress?: number | null;\n message?: string;\n data?: Record<string, unknown>;\n}\n\nexport interface JobProgressInput {\n stage: string;\n progress: number;\n message?: string;\n detail?: string;\n source?: string;\n data?: Record<string, unknown>;\n}\n\nexport interface JobExecutionContext {\n /**\n * `handler` is set only for a job that targets a registered named handler\n * (#5005); it is absent for a model-method job.\n */\n job: JobContext & { tenantId?: string | null; handler?: string };\n logger: Logger;\n /**\n * Cooperative cancellation signal. Aborts when the job row is observed as\n * `cancelled` (reason: `JobCancelledError`) or when the job times out under\n * `timeoutBehavior` `'fail'`/`'kill'` (reason: `JobTimeoutError`). A plain\n * `AbortSignal`: pass it to `fetch` or an LLM SDK. Handlers that ignore it\n * behave exactly as before; aborting never changes job lifecycle state.\n */\n signal: AbortSignal;\n event(input: JobEventInput): Promise<void>;\n progress(input: JobProgressInput): Promise<void>;\n log(\n level: 'debug' | 'info' | 'warn' | 'error',\n message: string,\n data?: Record<string, unknown>,\n ): Promise<void>;\n /**\n * Present only for a job created by the MCP Tasks extension. Calling this\n * persists an input request and resolves after `tasks/update` supplies every\n * requested key (or rejects cooperatively if the task is cancelled).\n */\n task?: {\n /** Recheck live authority and job ownership immediately before apply. */\n assertAuthorized(): Promise<void>;\n /** Durable single input round; suspends this execution until a new claim. */\n requestContinuation(\n binding: McpTaskContinuation,\n inputRequest: unknown,\n ): Promise<unknown>;\n requestInput(\n inputRequests: Record<string, unknown>,\n ): Promise<Record<string, unknown>>;\n };\n}\n\n/**\n * Logger extension that auto-injects job context into all log entries\n *\n * During job execution, all logs automatically include:\n * - jobId: The job's unique identifier\n * - attempt: Which attempt this is (1, 2, 3...)\n * - queue: Which queue the job is in\n * - objectType: The type of object being operated on\n * - method: The method being invoked\n */\nexport class JobContextLogger implements Logger {\n constructor(\n private readonly baseLogger: Logger,\n private readonly jobContext: JobContext,\n ) {}\n\n private addContext(data?: Record<string, unknown>): Record<string, unknown> {\n return {\n ...data,\n _job: {\n id: this.jobContext.jobId,\n attempt: this.jobContext.attempt,\n queue: this.jobContext.queue,\n objectType: this.jobContext.objectType,\n method: this.jobContext.method,\n },\n };\n }\n\n debug(message: string, data?: Record<string, unknown>): void {\n this.baseLogger.debug(message, this.addContext(data));\n }\n\n info(message: string, data?: Record<string, unknown>): void {\n this.baseLogger.info(message, this.addContext(data));\n }\n\n warn(message: string, data?: Record<string, unknown>): void {\n this.baseLogger.warn(message, this.addContext(data));\n }\n\n error(message: string, data?: Record<string, unknown>): void {\n this.baseLogger.error(message, this.addContext(data));\n }\n}\n\nexport default JobContextLogger;\n","import type { DatabaseInterface } from '@happyvertical/sql';\nimport { createId } from '@happyvertical/utils';\nimport { type SmrtJob, SmrtJobCollection } from './smrt-job.js';\nimport { terminalSnapshot, transitionTerminalJob } from './terminal-outcome.js';\n\n/** The MCP Tasks extension identifier implemented by this durable adapter. */\nexport const MCP_TASKS_EXTENSION = 'io.modelcontextprotocol/tasks';\n\n/** MCP task states defined by the Tasks extension. */\nexport type McpTaskStatus =\n | 'working'\n | 'input_required'\n | 'completed'\n | 'cancelled'\n | 'failed';\n\n/** Durable shape returned by `tasks/get` after the transport adds `resultType`. */\nexport interface McpTask {\n taskId: string;\n status: McpTaskStatus;\n createdAt: string;\n lastUpdatedAt: string;\n ttlMs: number;\n pollIntervalMs?: number;\n statusMessage?: string;\n result?: Record<string, unknown>;\n error?: { code: number; message: string };\n}\n\n/** Immutable reference to an owning workflow record, never an approval. */\nexport interface McpTaskContinuation {\n recordId: string;\n revision: string;\n inputKey: string;\n}\n\n/** Live runner authority: implementations resolve current grants, never snapshots. */\nexport interface McpTaskAuthority {\n continuation?: Readonly<McpTaskContinuation>;\n ownerId: string;\n tenantId: string | null;\n taskId: string;\n objectType: string;\n objectId: string;\n method: string;\n}\n\n/** Internal control flow after input is durably persisted and the worker released. */\nexport class McpTaskSuspendedError extends Error {}\n\n/** Arguments passed through an MCP tool action into its backing job. */\nexport interface CreateMcpTaskInput {\n objectType: string;\n objectId: string;\n method: string;\n /** Exact positional custom-action invocation produced by the MCP generator. */\n invocationArgs: unknown[];\n tenantId?: string | null;\n continuation?: McpTaskContinuation;\n /** Optional agent constructor configuration retained by normal background jobs. */\n agentConfig?: Record<string, unknown>;\n timeout?: number;\n pollIntervalMs?: number;\n ttlMs?: number;\n}\n\n/** Internal persisted marker distinguishing task invocations from normal jobs. */\nexport interface McpTaskJobMarker {\n /** Set by the trusted app task store, never by tool arguments. */\n authorizationRequired?: boolean;\n continuation?: McpTaskContinuation;\n invocationArgs: unknown[];\n pollIntervalMs: number;\n ttlMs: number;\n}\n\n/** Serialize a completed task exactly as an MCP CallToolResult. */\nexport function createMcpTaskResult(result: unknown): Record<string, unknown> {\n // JSON.stringify(undefined) returns undefined rather than valid JSON. The\n // generated MCP result boundary represents non-JSON/void action results as\n // null, so preserve that contract in the durable task payload too.\n const publicResult = toPublicTaskData(result) ?? null;\n return {\n content: [{ type: 'text', text: JSON.stringify(publicResult) }],\n structuredContent: { data: publicResult },\n };\n}\n\n/** Thrown when a task doesn't belong to the current task-store principal. */\nexport class McpTaskNotFoundError extends Error {\n constructor(taskId: string) {\n super(`MCP task not found: ${taskId}`);\n this.name = 'McpTaskNotFoundError';\n }\n}\n\n/** Cooperative cancellation observed by an operation awaiting task input. */\nexport class McpTaskCancelledError extends Error {\n constructor(taskId: string) {\n super(`MCP task was cancelled: ${taskId}`);\n this.name = 'McpTaskCancelledError';\n }\n}\n\n/**\n * Durable adapter between the MCP Tasks extension and `_smrt_jobs`.\n *\n * A task is a projection of exactly one job row: `task_id` is a unique\n * correlation key on the row and cancellation changes that same row. This is\n * intentionally not a second task table, which prevents an orphaned queued\n * job when a caller cancels an MCP task.\n */\nexport class McpTaskStore {\n private readonly ownerId: string | null;\n private readonly requireAuthorization: boolean;\n private readonly tenantId: string | null;\n\n private constructor(\n private readonly collection: SmrtJobCollection,\n options: {\n /** Require live worker authorization for every task from this store. */\n requireAuthorization?: boolean;\n ownerId?: string | null;\n tenantId?: string | null;\n pollIntervalMs?: number;\n ttlMs?: number;\n },\n ) {\n this.ownerId = options.ownerId ?? null;\n this.requireAuthorization = options.requireAuthorization ?? false;\n this.tenantId = options.tenantId ?? null;\n this.pollIntervalMs = options.pollIntervalMs ?? 250;\n this.ttlMs = options.ttlMs ?? 86_400_000;\n }\n\n readonly pollIntervalMs: number;\n readonly ttlMs: number;\n\n static async create(\n db: DatabaseInterface,\n options: {\n /** Require live worker authorization for every task from this store. */\n requireAuthorization?: boolean;\n ownerId?: string | null;\n tenantId?: string | null;\n pollIntervalMs?: number;\n ttlMs?: number;\n } = {},\n ): Promise<McpTaskStore> {\n const collection = await SmrtJobCollection.create({ db });\n return new McpTaskStore(collection, options);\n }\n\n /** Create one pending job and return its immediately-pollable task projection. */\n async createTask(input: CreateMcpTaskInput): Promise<McpTask> {\n if ((input.tenantId ?? null) !== this.tenantId) {\n throw new Error('MCP task tenant does not match active tenant');\n }\n if (this.requireAuthorization && !this.ownerId)\n throw new Error('Authorized tasks require an owner');\n const continuation = input.continuation\n ? Object.freeze(validateContinuation(input.continuation))\n : undefined;\n if (continuation) {\n if (!this.ownerId)\n throw new Error('Durable continuation requires an owner');\n }\n const taskId = createId();\n const pollIntervalMs = input.pollIntervalMs ?? this.pollIntervalMs;\n const ttlMs = input.ttlMs ?? this.ttlMs;\n const marker: McpTaskJobMarker = {\n invocationArgs: input.invocationArgs,\n ...(this.requireAuthorization ? { authorizationRequired: true } : {}),\n ...(continuation ? { continuation } : {}),\n pollIntervalMs,\n ttlMs,\n };\n const args: Record<string, unknown> = {\n _mcpTask: marker,\n ...(input.agentConfig ? { _agentConfig: input.agentConfig } : {}),\n };\n\n const job = await this.collection.enqueueJob({\n tenantId: input.tenantId ?? null,\n queue: 'mcp-tasks',\n objectType: input.objectType,\n objectId: input.objectId,\n method: input.method,\n args,\n timeout: input.timeout,\n ...(continuation || this.requireAuthorization ? { maxAttempts: 1 } : {}),\n taskId,\n taskOwnerId: this.ownerId,\n taskInputRequests: null,\n taskInputResponses: null,\n });\n\n return taskFromJob(job, { pollIntervalMs, ttlMs });\n }\n\n /**\n * Read a waiting task's application input descriptor for an explicitly declared\n * workflow tool or authenticated form. This is not an MCP protocol extension.\n */\n async getContinuation(taskId: string): Promise<{\n binding: McpTaskContinuation;\n inputRequests: Record<string, unknown>;\n } | null> {\n const job = await this.findTaskJob(taskId);\n const binding = getMcpTaskMarker(job)?.continuation;\n if (!binding || job.status !== 'pending' || job.taskInputResponses !== null)\n return null;\n const inputRequests = asRecord(job.taskInputRequests);\n if (!Object.keys(inputRequests).length) return null;\n return { binding, inputRequests };\n }\n\n /** Get a task only when it belongs to this store's principal. */\n async getTask(taskId: string): Promise<McpTask> {\n const job = await this.findTaskJob(taskId);\n const marker = getMcpTaskMarker(job);\n return taskFromJob(\n job,\n marker ?? {\n pollIntervalMs: this.pollIntervalMs,\n ttlMs: this.ttlMs,\n },\n );\n }\n\n /**\n * Persist only values requested by an outstanding `requestInput()` call.\n * Unknown and already-consumed keys are intentionally ignored per SEP-2663.\n */\n async updateTask(\n taskId: string,\n inputResponses: Record<string, unknown>,\n ): Promise<void> {\n const job = await this.findTaskJob(taskId);\n const requested = asRecord(job.taskInputRequests);\n if (getMcpTaskMarker(job)?.continuation) {\n if (\n !Object.keys(requested).length ||\n !Object.keys(requested).every((key) =>\n Object.hasOwn(inputResponses, key),\n )\n )\n return;\n const selected = Object.fromEntries(\n Object.keys(requested).map((key) => [key, inputResponses[key]]),\n );\n await this.collection.query(\n `UPDATE _smrt_jobs SET task_input_responses = ?, updated_at = ?\n WHERE id = ? AND task_id = ? AND status = 'pending'\n AND task_input_responses IS NULL`,\n [\n encodeContinuationJson(selected),\n new Date().toISOString(),\n job.id,\n taskId,\n ],\n { allowRawOnTenantScoped: true },\n );\n return;\n }\n if (Object.keys(requested).length === 0) return;\n\n const current = asRecord(job.taskInputResponses);\n const accepted: Record<string, unknown> = { ...current };\n for (const key of Object.keys(requested)) {\n if (Object.hasOwn(inputResponses, key)) {\n accepted[key] = inputResponses[key];\n }\n }\n\n await this.collection.query(\n `UPDATE _smrt_jobs\n SET task_input_responses = ?, updated_at = ?\n WHERE id = ? AND task_id = ?`,\n [JSON.stringify(accepted), new Date().toISOString(), job.id, taskId],\n { allowRawOnTenantScoped: true },\n );\n }\n\n /**\n * Cooperatively cancel the backing job. A completion race cannot resurrect\n * it because TaskRunner terminal writes require `status = 'running'`.\n */\n async cancelTask(taskId: string): Promise<void> {\n const job = await this.findTaskJob(taskId);\n if (\n job.status === 'completed' ||\n job.status === 'failed' ||\n job.status === 'cancelled'\n ) {\n return;\n }\n\n const snapshot = terminalSnapshot(job);\n if (!snapshot) throw new McpTaskNotFoundError(taskId);\n await transitionTerminalJob(this.collection.db, {\n job: snapshot,\n status: 'cancelled',\n completedAt: new Date(),\n expectedStatuses: ['pending', 'running'],\n expectedTaskId: taskId,\n });\n }\n\n private async findTaskJob(taskId: string): Promise<SmrtJob> {\n const ownerPredicate =\n this.ownerId === null ? 'task_owner_id IS NULL' : 'task_owner_id = ?';\n const params: unknown[] =\n this.ownerId === null ? [taskId] : [taskId, this.ownerId];\n const tenantPredicate =\n this.tenantId === null ? 'tenant_id IS NULL' : 'tenant_id = ?';\n if (this.tenantId !== null) params.push(this.tenantId);\n const jobs = await this.collection.query(\n `SELECT * FROM _smrt_jobs WHERE task_id = ? AND ${ownerPredicate} AND ${tenantPredicate} LIMIT 1`,\n params,\n { allowRawOnTenantScoped: true },\n );\n const job = jobs[0];\n if (!job) throw new McpTaskNotFoundError(taskId);\n return job;\n }\n}\n\n/** Retrieve an internal task marker without exposing it to ordinary job callers. */\nexport function getMcpTaskMarker(\n job: Pick<SmrtJob, 'args'>,\n): McpTaskJobMarker | null {\n const marker = asRecord(asRecord(job.args)._mcpTask);\n if (!Array.isArray(marker.invocationArgs)) return null;\n return {\n invocationArgs: marker.invocationArgs,\n ...(marker.authorizationRequired === true\n ? { authorizationRequired: true }\n : {}),\n ...(marker.continuation\n ? { continuation: validateContinuation(marker.continuation) }\n : {}),\n pollIntervalMs: asPositiveInt(marker.pollIntervalMs, 250),\n ttlMs: asPositiveInt(marker.ttlMs, 86_400_000),\n };\n}\n\n/**\n * Persist one immutable input round and release the worker. On replay the handler\n * starts again; work before this seam must be read-only or use owning runOnce /\n * action idempotency. An answer is input only, never domain approval.\n */\nexport async function requestMcpTaskContinuation(\n db: DatabaseInterface,\n job: Pick<SmrtJob, 'id' | 'taskId' | 'workerId' | 'args'>,\n binding: McpTaskContinuation,\n inputRequest: unknown,\n): Promise<unknown> {\n validateContinuation(binding);\n const expected = getMcpTaskMarker(job)?.continuation;\n if (\n !expected ||\n expected.recordId !== binding.recordId ||\n expected.revision !== binding.revision ||\n expected.inputKey !== binding.inputKey\n ) {\n throw new Error('MCP continuation binding mismatch');\n }\n const found = await db.query(\n `SELECT task_input_responses FROM _smrt_jobs\n WHERE id = ? AND task_id = ? AND worker_id = ? AND status = 'running'`,\n job.id,\n job.taskId,\n job.workerId,\n );\n if (found.rows.length !== 1)\n throw new McpTaskCancelledError(job.taskId ?? '');\n const answers = asRecord(parseJson(found.rows[0].task_input_responses));\n if (Object.hasOwn(answers, binding.inputKey))\n return answers[binding.inputKey];\n const suspended = await db.query(\n `UPDATE _smrt_jobs SET status = 'pending', worker_id = NULL,\n worker_heartbeat = NULL, task_input_requests = ?, updated_at = ?\n WHERE id = ? AND task_id = ? AND worker_id = ? AND status = 'running'\n RETURNING id`,\n encodeContinuationJson({ [binding.inputKey]: inputRequest }),\n new Date().toISOString(),\n job.id,\n job.taskId,\n job.workerId,\n );\n if (suspended.rows.length !== 1)\n throw new McpTaskCancelledError(job.taskId ?? '');\n throw new McpTaskSuspendedError('MCP task awaits durable input');\n}\n\nfunction encodeContinuationJson(value: unknown): string {\n try {\n const json = JSON.stringify(value, (_key, item) => {\n if (\n item === undefined ||\n typeof item === 'function' ||\n typeof item === 'symbol' ||\n typeof item === 'bigint' ||\n (typeof item === 'number' && !Number.isFinite(item))\n ) {\n throw new Error('Invalid JSON');\n }\n return item;\n });\n if (!json || new TextEncoder().encode(json).byteLength > 65_536)\n throw new Error('Oversized JSON');\n return json;\n } catch {\n throw new Error('MCP continuation input must be JSON within 65536 bytes');\n }\n}\n\nfunction validateContinuation(value: unknown): McpTaskContinuation {\n const source = asRecord(value);\n const record: Record<string, unknown> = {\n recordId: source.recordId,\n revision: source.revision,\n inputKey: source.inputKey,\n };\n for (const key of ['recordId', 'revision', 'inputKey']) {\n if (\n typeof record[key] !== 'string' ||\n !record[key] ||\n record[key].length > 256\n ) {\n throw new Error('Invalid MCP continuation binding');\n }\n }\n return {\n recordId: record.recordId as string,\n revision: record.revision as string,\n inputKey: record.inputKey as string,\n };\n}\n\n/**\n * Make a task operation wait for user input. It is intentionally a method on\n * JobExecutionContext rather than an MCP transport concern, so generated\n * stdio and stateless HTTP share one durable input seam.\n */\nexport async function requestMcpTaskInput(\n db: DatabaseInterface,\n job: Pick<SmrtJob, 'id' | 'taskId' | 'workerId'>,\n inputRequests: Record<string, unknown>,\n): Promise<Record<string, unknown>> {\n const jobId = job.id;\n const taskId = job.taskId;\n if (!jobId || !taskId || !job.workerId) {\n throw new Error(\n 'Task input is only available while an MCP task job is running',\n );\n }\n if (Object.keys(inputRequests).length === 0) return {};\n\n const now = new Date().toISOString();\n await db.query(\n `UPDATE _smrt_jobs\n SET task_input_requests = ?, task_input_responses = NULL, updated_at = ?\n WHERE id = ? AND task_id = ? AND worker_id = ? AND status = 'running'`,\n JSON.stringify(inputRequests),\n now,\n jobId,\n taskId,\n job.workerId,\n );\n\n while (true) {\n const result = await db.query(\n `SELECT status, task_input_responses FROM _smrt_jobs WHERE id = ? AND task_id = ?`,\n jobId,\n taskId,\n );\n const row = result.rows[0] as\n | { status?: string; task_input_responses?: unknown }\n | undefined;\n if (!row || row.status === 'cancelled')\n throw new McpTaskCancelledError(taskId);\n if (row.status !== 'running')\n throw new Error(`MCP task is no longer running: ${taskId}`);\n\n const responses = asRecord(parseJson(row.task_input_responses));\n if (\n Object.keys(inputRequests).every((key) => Object.hasOwn(responses, key))\n ) {\n const selected = Object.fromEntries(\n Object.keys(inputRequests).map((key) => [key, responses[key]]),\n );\n await db.query(\n `UPDATE _smrt_jobs\n SET task_input_requests = NULL, updated_at = ?\n WHERE id = ? AND task_id = ? AND worker_id = ? AND status = 'running'`,\n new Date().toISOString(),\n jobId,\n taskId,\n job.workerId,\n );\n return selected;\n }\n await new Promise((resolve) => setTimeout(resolve, 50));\n }\n}\n\n/** Convert the job state into the flat task shape required by `tasks/get`. */\nexport function taskFromJob(\n job: SmrtJob,\n marker: Pick<McpTaskJobMarker, 'pollIntervalMs' | 'ttlMs'>,\n): McpTask {\n const status = taskStatusFromJob(job);\n const createdAt = toIso(job.created_at) ?? new Date().toISOString();\n const lastUpdatedAt = toIso(job.updated_at) ?? createdAt;\n const task: McpTask = {\n taskId: job.taskId ?? '',\n status,\n createdAt,\n lastUpdatedAt,\n ttlMs: marker.ttlMs,\n pollIntervalMs: marker.pollIntervalMs,\n };\n if (status === 'input_required')\n task.statusMessage = 'Waiting for required input';\n if (status === 'cancelled') task.statusMessage = 'Task cancelled';\n if (status === 'failed') {\n task.statusMessage = job.lastError ?? 'Task failed';\n task.error = { code: -32603, message: task.statusMessage };\n }\n if (status === 'completed' && job.taskResult) task.result = job.taskResult;\n return task;\n}\n\nfunction taskStatusFromJob(job: SmrtJob): McpTaskStatus {\n if (job.status === 'completed') return 'completed';\n if (job.status === 'cancelled') return 'cancelled';\n if (job.status === 'failed') return 'failed';\n if (\n Object.keys(asRecord(job.taskInputRequests)).length > 0 &&\n !(getMcpTaskMarker(job)?.continuation && job.taskInputResponses !== null)\n )\n return 'input_required';\n return 'working';\n}\n\nfunction asRecord(value: unknown): Record<string, unknown> {\n if (value === null || typeof value !== 'object' || Array.isArray(value))\n return {};\n return value as Record<string, unknown>;\n}\n\nfunction parseJson(value: unknown): unknown {\n if (typeof value !== 'string') return value;\n try {\n return JSON.parse(value);\n } catch {\n return {};\n }\n}\n\nfunction asPositiveInt(value: unknown, fallback: number): number {\n return typeof value === 'number' && Number.isInteger(value) && value > 0\n ? value\n : fallback;\n}\n\nfunction toIso(value: Date | string | null | undefined): string | undefined {\n if (value instanceof Date) return value.toISOString();\n if (typeof value === 'string') return value;\n return undefined;\n}\n\n/** Match generated MCP's sensitive-field-safe public serialization boundary. */\nfunction toPublicTaskData(\n value: unknown,\n seen: WeakSet<object> = new WeakSet(),\n): unknown {\n if (value === null || typeof value !== 'object') return value;\n const publicSource = value as {\n toPublicJSON?: (options?: Record<string, unknown>) => unknown;\n };\n if (typeof publicSource.toPublicJSON === 'function') {\n return publicSource.toPublicJSON({});\n }\n if (Array.isArray(value)) {\n if (seen.has(value)) return '[Circular]';\n seen.add(value);\n return value.map((entry) => toPublicTaskData(entry, seen));\n }\n const prototype = Object.getPrototypeOf(value);\n if (prototype !== Object.prototype && prototype !== null) return value;\n if (seen.has(value)) return '[Circular]';\n seen.add(value);\n const out: Record<string, unknown> = {};\n for (const [key, nested] of Object.entries(value)) {\n out[key] = toPublicTaskData(nested, seen);\n }\n return out;\n}\n","export const DEFAULT_TASK_HEARTBEAT_INTERVAL_MS = 30000;\nconst STALE_HEARTBEAT_GRACE_MULTIPLIER = 3;\n\n/**\n * Default cadence for renewing a worker's liveness lease.\n *\n * Liveness is a per-*worker* lease (see {@link ../smrt-worker.js}), not a\n * per-job heartbeat. The runner renews its lease on this interval; a dead\n * worker stops renewing and its lease expires after {@link DEFAULT_LEASE_TTL_MS}.\n */\nexport const DEFAULT_LEASE_TICK_MS = 10000;\n\n/**\n * Default time-to-live for a worker liveness lease.\n *\n * A `running` job is only recovered when its owning worker is neither live in\n * this process nor holding a fresh lease in the database. The TTL is the\n * cross-process detection latency for a genuinely dead worker.\n */\nexport const DEFAULT_LEASE_TTL_MS = 30000;\n\nconst LEASE_TTL_GRACE_MULTIPLIER = 3;\n\n/**\n * Keep stale-job recovery aligned with the actual heartbeat cadence.\n *\n * @deprecated Recovery no longer keys on per-job heartbeat staleness (#1474);\n * it keys on worker liveness. Retained for one release for any external caller.\n * Use {@link getEffectiveLeaseTtlMs} with the lease tick instead.\n */\nexport function getEffectiveStaleJobThresholdMs(\n staleJobThresholdMs: number,\n heartbeatIntervalMs: number,\n): number {\n return Math.max(\n staleJobThresholdMs,\n heartbeatIntervalMs * STALE_HEARTBEAT_GRACE_MULTIPLIER,\n );\n}\n\n/**\n * Never let a lease expire in fewer than three renewal ticks.\n *\n * A single missed renewal (GC pause, a slow database round-trip) must not be\n * enough to declare a healthy worker dead. Mirrors the floor applied by\n * {@link getEffectiveStaleJobThresholdMs} for the legacy heartbeat path.\n */\nexport function getEffectiveLeaseTtlMs(\n leaseTtlMs: number,\n leaseTickMs: number,\n): number {\n return Math.max(leaseTtlMs, leaseTickMs * LEASE_TTL_GRACE_MULTIPLIER);\n}\n","// Self-register this package's manifest for consumers that import via this\n// subpath without the main entry. See src/__smrt-register__.ts (issue #1132).\nimport './__smrt-register__.js';\n\nimport { AsyncLocalStorage } from 'node:async_hooks';\nimport { EventEmitter } from 'node:events';\nimport { Worker } from 'node:worker_threads';\nimport type { RetryDecision } from '@happyvertical/jobs';\nimport { createLogger } from '@happyvertical/logger';\nimport {\n assertDatabaseMigratedForBuild,\n getClassConfigResolvers,\n normalizeCustomActionFailure,\n ObjectRegistry,\n resolveLazyConfig,\n type SmrtObject,\n} from '@happyvertical/smrt-core';\nimport { TenantContext } from '@happyvertical/smrt-tenancy';\nimport type { DatabaseInterface } from '@happyvertical/sql';\nimport { createId } from '@happyvertical/utils';\nimport { isBackgroundEligibleMethod } from './background-policy.js';\nimport { redactErrorForPersistence } from './error-redaction.js';\nimport type { JobClaim } from './job-claim.js';\nimport {\n JOB_HANDLER_METHOD,\n type JobHandler,\n JobHandlerTargetError,\n JobHandlerUnregisteredError,\n jobHandlerName,\n jobHandlerTarget,\n releaseJobHandlerRegistry,\n sealJobHandlerRegistry,\n} from './job-handlers.js';\nimport {\n JobContextLogger,\n type JobEventInput,\n type JobExecutionContext,\n type JobProgressInput,\n} from './logger-extension.js';\nimport {\n createMcpTaskResult,\n getMcpTaskMarker,\n type McpTaskAuthority,\n McpTaskSuspendedError,\n requestMcpTaskContinuation,\n requestMcpTaskInput,\n} from './mcp-task.js';\nimport {\n type RetentionSweeper,\n type RetentionSweeperOptions,\n startRetentionSweeper,\n} from './retention.js';\nimport {\n HANDLER_TARGET_SQL,\n jobTenantScope,\n SMRT_JOB_PORTABLE_SELECT_COLUMNS,\n type SmrtJob,\n SmrtJobCollection,\n} from './smrt-job.js';\nimport { type SmrtJobEvent, SmrtJobEventCollection } from './smrt-job-event.js';\nimport { SmrtWorkerCollection } from './smrt-worker.js';\nimport {\n DEFAULT_LEASE_TICK_MS,\n DEFAULT_LEASE_TTL_MS,\n DEFAULT_TASK_HEARTBEAT_INTERVAL_MS,\n getEffectiveLeaseTtlMs,\n} from './stale-recovery.js';\nimport {\n ensureTerminalOutcomeStorage,\n terminalSnapshot,\n transitionTerminalJob,\n} from './terminal-outcome.js';\nimport {\n createWorkerKey,\n isWorkerAlive,\n type LivenessConnectionPlan,\n planLivenessConnection,\n registerLiveWorker,\n resolveEngine,\n tuneSqliteForConcurrency,\n unregisterLiveWorker,\n} from './worker-liveness.js';\n\n// Job rows are durable but untrusted transport. This marker is deliberately\n// module-private: a JSON task invocation cannot synthesize the runner-owned\n// execution context that security-sensitive task targets receive.\nconst runnerExecutionContextIdentities = new WeakSet<object>();\nconst runnerJobClaims = new WeakMap<object, Readonly<JobClaim>>();\nconst runnerExecutionContexts = new AsyncLocalStorage<JobExecutionContext>();\n\n/** True only for an execution context constructed by this TaskRunner module. */\nexport function isRunnerExecutionContext(\n value: unknown,\n): value is JobExecutionContext {\n return (\n typeof value === 'object' &&\n value !== null &&\n runnerExecutionContextIdentities.has(value)\n );\n}\n\n/** The runner-owned context for the currently executing task, if any. */\nexport function getActiveJobExecutionContext():\n | JobExecutionContext\n | undefined {\n return runnerExecutionContexts.getStore();\n}\n\n/**\n * Read the immutable dispatch-time claim from an authentic runner context.\n * Reading current job rows cannot recover this identity after ownership changes.\n * @param context - Context supplied to a handler by TaskRunner.\n * @returns The captured claim; use assertJobClaim for current ownership proof.\n */\nexport function getJobClaim(context: unknown): Readonly<JobClaim> {\n const claim = isRunnerExecutionContext(context)\n ? runnerJobClaims.get(context)\n : undefined;\n if (!claim)\n throw new Error(\n 'Job claim requires TaskRunner context with claimFencing: true',\n );\n return claim;\n}\n\n/**\n * TaskRunner configuration\n */\nexport interface TaskRunnerConfig {\n /** Opt into immutable claim proofs and dispatch-fenced runner writes. Default false. */\n claimFencing?: boolean;\n /** Worker ID (auto-generated if not provided) */\n id?: string;\n /** Resolve live authority for durable tasks at each execution/replay. */\n authorizeMcpTask?: (\n authority: Readonly<McpTaskAuthority>,\n ) => Promise<boolean>;\n /** Number of concurrent jobs to process */\n concurrency?: number;\n /** Queues to process (default: ['default']) */\n queues?: string[];\n /** Limit claims and orphan recovery to these tenants; [] selects none. */\n tenantIds?: readonly (string | null)[];\n /** Base polling interval in milliseconds, capped at the effective lease TTL. */\n pollInterval?: number;\n /**\n * Longest delay between empty queue checks in milliseconds.\n *\n * Empty checks back off exponentially from {@link pollInterval} to this\n * value. Leave unset to cap idle checks at twenty times `pollInterval`.\n * Every delay is bounded by the effective worker lease TTL (plus query and\n * event-loop time), including a base interval larger than that TTL.\n */\n idlePollInterval?: number;\n /** Heartbeat interval in milliseconds */\n heartbeatInterval?: number;\n /**\n * How often a running job's row is checked for cancellation, in\n * milliseconds, so `JobExecutionContext.signal` can abort. Default 1000.\n * One read-only query per active job per interval; no writes.\n */\n cancelPollInterval?: number;\n /** Maximum time to wait for jobs to complete on shutdown */\n shutdownTimeout?: number;\n /**\n * @deprecated No longer used. Recovery keys on worker liveness, not per-job\n * heartbeat staleness (#1474). Use {@link leaseTtlMs} / {@link leaseTickMs}.\n */\n staleJobThresholdMs?: number;\n /** Worker liveness lease time-to-live in milliseconds */\n leaseTtlMs?: number;\n /** How often to renew the worker liveness lease, in milliseconds */\n leaseTickMs?: number;\n /**\n * Periodic system-table retention sweep (#2375).\n *\n * A running worker is the framework's only always-on scheduler, so it is\n * also where the retention sweep is scheduled by default. Set to `false` to\n * opt out entirely (for example when a cron job runs `smrt db:prune`\n * instead), or pass options to change the cadence or the policy. The first\n * sweep runs one interval after `start()`, never at start.\n */\n retention?: RetentionSweeperOptions | false;\n /**\n * How long a named handler job (#5005) may stay `pending` past its `run_at`\n * before this runner fails it with failure kind `handler-unclaimed`, in\n * milliseconds. Default 24 h. A runner claims only the handler jobs it\n * registered, so a job no runner serves would otherwise wait forever.\n * Every runner sweeps the handler jobs in its own queues and tenant scope\n * that it did not register itself (those it claims), from its poll, at\n * most once per 1% of this deadline (between one lease tick and 15 min)\n * and {@link HANDLER_UNCLAIMED_SWEEP_LIMIT} rows per sweep, emitting\n * `job:unclaimed`; with different values across a fleet the shortest wins.\n */\n handlerUnclaimedDeadlineMs?: number;\n}\n\n/**\n * TaskRunner events\n */\nexport interface TaskRunnerEvents {\n 'job:started': (job: SmrtJob) => void;\n 'job:event': (job: SmrtJob, event: SmrtJobEvent) => void;\n 'job:progress': (job: SmrtJob, event: SmrtJobEvent) => void;\n 'job:completed': (job: SmrtJob, result: unknown) => void;\n 'job:failed': (job: SmrtJob, error: Error) => void;\n /**\n * A handler job this runner failed `handler-unclaimed` in its sweep: no\n * runner serving the handler claimed it in time (#5005). Not `job:failed`,\n * because this runner never claimed or ran it.\n */\n 'job:unclaimed': (job: SmrtJob, error: Error) => void;\n 'job:retrying': (job: SmrtJob, error: Error, delay: number) => void;\n 'runner:started': () => void;\n 'runner:stopped': () => void;\n 'runner:error': (error: Error) => void;\n}\n\nfunction errorText(error: unknown): string {\n return error instanceof Error ? error.message : String(error);\n}\n\n/**\n * Max time to wait for the liveness thread to report ready before giving up and\n * falling back to main-loop renewal (guards against a hung connect in-thread).\n */\nconst LIVENESS_THREAD_START_TIMEOUT_MS = 10000;\n/**\n * Max time to wait for a liveness thread that has been asked to stop (or has\n * already failed) to exit on its own before terminating it.\n */\nconst LIVENESS_THREAD_EXIT_TIMEOUT_MS = 5000;\n\n/**\n * Wait (bounded) for a liveness thread to exit on its own; terminate it only\n * if it does not. Never terminate first: Node aborts the whole process when a\n * worker is terminated while a crypto job's completion is still pending, and\n * the SDK starts one when the thread imports it (smrt#4865).\n */\nasync function retireLivenessWorker(\n worker: Worker,\n exited: Promise<void>,\n): Promise<void> {\n let timer: ReturnType<typeof setTimeout> | undefined;\n const exitedInTime = await Promise.race([\n exited.then(() => true),\n new Promise<boolean>((resolve) => {\n timer = setTimeout(() => resolve(false), LIVENESS_THREAD_EXIT_TIMEOUT_MS);\n if (typeof timer.unref === 'function') timer.unref();\n }),\n ]);\n clearTimeout(timer);\n if (!exitedInTime) await worker.terminate().catch(() => {});\n}\n\nconst DEFAULT_IDLE_POLL_INTERVAL_MULTIPLIER = 20;\n/** Default {@link TaskRunnerConfig.handlerUnclaimedDeadlineMs}: 24 h. */\nexport const DEFAULT_HANDLER_UNCLAIMED_DEADLINE_MS = 24 * 60 * 60 * 1000;\n/** Most unclaimed handler jobs one sweep fails (#5005). */\nexport const HANDLER_UNCLAIMED_SWEEP_LIMIT = 100;\n/** Longest accepted unclaimed deadline: 10 years. */\nconst MAX_HANDLER_UNCLAIMED_DEADLINE_MS = 10 * 365 * 24 * 60 * 60 * 1000;\n/** Longest wait between unclaimed-handler sweeps: 15 min. */\nconst HANDLER_UNCLAIMED_SWEEP_MAX_INTERVAL_MS = 15 * 60 * 1000;\n/** Ids per surplus-release statement, well under driver bind-parameter caps. */\nconst SURPLUS_RELEASE_CHUNK = 500;\n/** Upper bound on a handler error's `retryAfterMs` hint (#3308). */\nconst MAX_RETRY_AFTER_MS = 24 * 60 * 60 * 1000;\n\n/**\n * Retry hints a handler error may carry (#3308): `retryable: false` for an\n * error a retry cannot fix (bad credentials, unknown model), `retryAfterMs`\n * for a provider-given reset time. Both are read from the error itself.\n */\nfunction errorRetryHints(error: unknown): {\n retryable: boolean;\n retryAfterMs: number | null;\n} {\n if (!error || typeof error !== 'object') {\n return { retryable: true, retryAfterMs: null };\n }\n const hints = error as { retryable?: unknown; retryAfterMs?: unknown };\n const retryAfterMs =\n typeof hints.retryAfterMs === 'number' &&\n Number.isFinite(hints.retryAfterMs) &&\n hints.retryAfterMs > 0\n ? Math.min(hints.retryAfterMs, MAX_RETRY_AFTER_MS)\n : null;\n return { retryable: hints.retryable !== false, retryAfterMs };\n}\n\n/**\n * Raised when a job exceeds its timeout under `timeoutBehavior` `'fail'`/`'kill'`.\n *\n * Distinguished from an ordinary handler error so the failure path can choose\n * NOT to auto-retry: the original handler keeps running after a timeout (JS\n * can't preempt it), so re-queueing the row as `pending` while the original\n * still executes guarantees concurrent duplicate execution (see #2 in the\n * #1401 review). A timed-out job is therefore failed terminally rather than\n * retried, shrinking — though, given the at-least-once contract, not fully\n * eliminating — the overlap window.\n */\nexport class JobTimeoutError extends Error {\n constructor(message: string) {\n super(message);\n this.name = 'JobTimeoutError';\n }\n}\n\n/**\n * Abort reason of `JobExecutionContext.signal` when the job row was cancelled\n * while its handler was running.\n */\nexport class JobCancelledError extends Error {\n constructor(message: string) {\n super(message);\n this.name = 'JobCancelledError';\n }\n}\n\n/**\n * Default configuration\n */\ntype ResolvedTaskRunnerConfig = Required<Omit<TaskRunnerConfig, 'tenantIds'>> &\n Pick<TaskRunnerConfig, 'tenantIds'>;\n\nconst DEFAULT_CONFIG: ResolvedTaskRunnerConfig = {\n id: '',\n claimFencing: false,\n authorizeMcpTask: async () => false,\n concurrency: 5,\n queues: ['default'],\n pollInterval: 1000,\n idlePollInterval: 0,\n heartbeatInterval: DEFAULT_TASK_HEARTBEAT_INTERVAL_MS,\n cancelPollInterval: 1000,\n shutdownTimeout: 30000,\n staleJobThresholdMs: 90000,\n leaseTtlMs: DEFAULT_LEASE_TTL_MS,\n leaseTickMs: DEFAULT_LEASE_TICK_MS,\n retention: {},\n handlerUnclaimedDeadlineMs: DEFAULT_HANDLER_UNCLAIMED_DEADLINE_MS,\n};\n\n/**\n * A rejection from one of a job's own state writes, as opposed to a listener\n * or telemetry call that threw after the write committed.\n */\nclass UnpersistedJobWriteError extends Error {\n constructor(readonly writeError: unknown) {\n super('Job state write could not be persisted');\n }\n}\n\n/**\n * TaskRunner processes SMRT jobs by invoking methods on SmrtObjects\n *\n * Features:\n * - Executes jobs via SmrtObject method invocation\n * - Configurable concurrency and timeout behavior\n * - Automatic retry with configurable strategies\n * - Job context logging for visibility\n * - Embedded mode (in-process) or standalone (CLI)\n */\nexport class TaskRunner extends EventEmitter {\n /** Tenant selection is applied before claims and recovery ownership writes. */\n static readonly capabilities = Object.freeze({\n tenantSelection: true,\n } as const);\n readonly id: string;\n /**\n * Per-incarnation-unique worker key. Stored as the `worker_id` on claimed\n * jobs and in `_smrt_workers`, so a restart of a runner sharing the same\n * configured `id` does not look like it still owns the previous\n * incarnation's orphaned jobs. The human-facing {@link id} stays stable for\n * events/logs.\n */\n private readonly workerKey: string;\n private readonly config: ResolvedTaskRunnerConfig;\n private readonly maxIdlePollIntervalMs: number;\n private readonly effectiveLeaseTtlMs: number;\n private collection: SmrtJobCollection | null = null;\n private eventCollection: SmrtJobEventCollection | null = null;\n private workerCollection: SmrtWorkerCollection | null = null;\n private workersTableVerified = false;\n private lastRecoverySweepAt = 0;\n private lastUnclaimedSweepAt = 0;\n private running = false;\n private activeJobs = new Map<string, SmrtJob>();\n /**\n * Rows this runner still owns as `running` because their terminal or retry\n * write could not be persisted, with the `last_error` to record. The owner\n * is alive, so liveness-based recovery would never touch them; this runner's\n * own sweep settles them (#4735).\n */\n private unsettledJobs = new Map<string, string>();\n /** Orphans whose recovery failure was already logged; one line per job. */\n private recoveryFailuresLogged = new Set<string>();\n /** Per-job cooperative cancellation controllers, alive while the job runs. */\n private jobAborts = new Map<string, AbortController>();\n /** Over-claimed job ids whose release back to `pending` has not landed. */\n private unreleasedSurplus = new Set<string>();\n private pollTimer: NodeJS.Timeout | null = null;\n private pollPromise: Promise<boolean> | null = null;\n private pollGeneration = 0;\n private idlePollDelayMs: number;\n private heartbeatTimer: NodeJS.Timeout | null = null;\n private leaseTimer: NodeJS.Timeout | null = null;\n /** Periodic system-table retention sweep, when not opted out (#2375). */\n private retentionSweeper: RetentionSweeper | null = null;\n private livenessWorker: Worker | null = null;\n /** Resolves when {@link livenessWorker} has exited (set together with it). */\n private livenessWorkerExited: Promise<void> | null = null;\n private shutdownPromise: Promise<void> | null = null;\n /** The in-flight {@link start}, shared by overlapping callers (#4944). */\n private startPromise: Promise<void> | null = null;\n /** The in-flight {@link stop}, shared by overlapping callers (#4944). */\n private stopPromise: Promise<void> | null = null;\n /** Set by a {@link stop} that lands while {@link start} is in flight. */\n private startCancelled = false;\n private db: DatabaseInterface | null = null;\n /**\n * Handlers this runner dispatches to, snapshotted when it starts (#5005).\n * Registration is closed while it runs, so the snapshot is the registry.\n */\n private jobHandlers: ReadonlyMap<string, JobHandler> = new Map();\n /** The snapshot's names: the only handler jobs this runner claims. */\n private handlerNames: readonly string[] = [];\n private logger = createLogger(true);\n\n constructor(config: TaskRunnerConfig = {}) {\n super();\n this.config = {\n ...DEFAULT_CONFIG,\n ...config,\n id: config.id || `runner_${createId().slice(0, 8)}`,\n };\n jobTenantScope(this.config.tenantIds);\n if (this.config.tenantIds !== undefined) {\n this.config.tenantIds = [...this.config.tenantIds];\n // The default retention sweep is system-wide maintenance, not tenant work.\n if (config.retention === undefined) this.config.retention = false;\n }\n this.id = this.config.id;\n this.workerKey = createWorkerKey(this.id);\n const deadline = this.config.handlerUnclaimedDeadlineMs;\n // Bounded so the sweep's cutoff is always a valid date.\n if (\n !Number.isFinite(deadline) ||\n deadline < 1 ||\n deadline > MAX_HANDLER_UNCLAIMED_DEADLINE_MS\n ) {\n throw new RangeError(\n `handlerUnclaimedDeadlineMs must be between 1 and ${MAX_HANDLER_UNCLAIMED_DEADLINE_MS} milliseconds`,\n );\n }\n for (const [name, value] of [\n ['pollInterval', this.config.pollInterval],\n ['idlePollInterval', config.idlePollInterval ?? this.config.pollInterval],\n ] as const) {\n if (!Number.isFinite(value) || value < 1 || value > 2_147_483_647) {\n throw new RangeError(\n `${name} must be between 1 and 2147483647 milliseconds`,\n );\n }\n }\n this.maxIdlePollIntervalMs = Math.min(\n 2_147_483_647,\n Math.max(\n this.config.pollInterval,\n config.idlePollInterval ??\n this.config.pollInterval * DEFAULT_IDLE_POLL_INTERVAL_MULTIPLIER,\n ),\n );\n this.idlePollDelayMs = this.config.pollInterval;\n this.effectiveLeaseTtlMs = getEffectiveLeaseTtlMs(\n this.config.leaseTtlMs,\n this.config.leaseTickMs,\n );\n }\n\n /**\n * Initialize the runner with database connection\n */\n async initialize(db: DatabaseInterface): Promise<void> {\n this.db = db;\n this.collection = await SmrtJobCollection.create({ db });\n this.eventCollection = await SmrtJobEventCollection.create({ db });\n this.workerCollection = await SmrtWorkerCollection.create({ db });\n }\n\n /**\n * Start processing jobs\n */\n async start(): Promise<void> {\n // Checked first: a start() during an in-flight stop() is refused even when\n // that stop is still waiting on an earlier start (#4944).\n if (this.stopPromise) {\n throw new Error('TaskRunner shutdown is still draining');\n }\n if (this.startPromise) return this.startPromise;\n if (this.running) return;\n if (this.shutdownPromise || this.pollPromise || this.activeJobs.size > 0) {\n throw new Error('TaskRunner shutdown is still draining');\n }\n if (!this.collection || !this.workerCollection) {\n throw new Error('TaskRunner not initialized. Call initialize() first.');\n }\n\n this.startCancelled = false;\n const starting = this.startRunning();\n this.startPromise = starting;\n try {\n await starting;\n } finally {\n if (this.startPromise === starting) this.startPromise = null;\n }\n }\n\n /**\n * The body of {@link start}. A {@link stop} that lands while it runs sets\n * {@link startCancelled}; the checks below then skip whatever has not\n * started yet, and that stop tears down what has, once this settles (#4944).\n */\n private async startRunning(): Promise<void> {\n if (!this.collection || !this.workerCollection) return;\n\n // Fail fast if the job-system tables were never migrated, with an\n // actionable error rather than a confusing recovery failure later.\n await assertDatabaseMigratedForBuild(this.collection.db);\n await this.workerCollection.assertReady();\n\n await this.prepareTerminalOutcomeStorage();\n\n // On SQLite, the runner's writes will race the off-loop ticker's writes to\n // the same file; enable WAL + a busy timeout up front so neither loses a\n // lock race under load (#1474 flake). Best-effort, file-level.\n if (this.db && resolveEngine(this.db) === 'sqlite') {\n await tuneSqliteForConcurrency(this.db);\n }\n\n // Stopped before anything was registered: there is nothing to tear down.\n if (this.startCancelled) return;\n\n // Register this worker incarnation with a seeded lease BEFORE polling, so\n // the first claimReady() cannot leave just-claimed jobs looking orphaned to\n // a concurrent recoverer.\n await this.workerCollection.registerWorker({\n workerKey: this.workerKey,\n pid: typeof process !== 'undefined' ? process.pid : null,\n hostname:\n typeof process !== 'undefined' ? (process.env.HOSTNAME ?? null) : null,\n leaseTtlMs: this.effectiveLeaseTtlMs,\n queues: this.config.queues,\n });\n registerLiveWorker(this.workerKey);\n\n // Close handler registration before the first claim and dispatch from a\n // snapshot: a handler registered after start() would race the claims it\n // should serve (#5005). Reopened when this runner has stopped.\n this.jobHandlers = sealJobHandlerRegistry(this.workerKey);\n this.handlerNames = [...this.jobHandlers.keys()];\n this.running = true;\n\n // Renew the worker lease. Prefer an off-loop worker thread so a CPU-bound\n // synchronous handler can never starve renewal (#1474); fall back to\n // main-loop renewal for engines a second connection can't reach\n // (in-memory SQLite, DuckDB), for SQLite when no second connection on the\n // runtime's own engine is available (#4978), or if the thread fails to\n // start.\n const plan = planLivenessConnection(this.db as DatabaseInterface);\n if (plan.kind === 'none') {\n // Warn only where a thread used to run and now cannot; engines that never\n // had a usable second connection keep renewing on the main loop quietly.\n const log = plan.degraded ? this.logger.warn : this.logger.debug;\n log.call(\n this.logger,\n `Liveness thread not used: ${plan.reason}. Renewing the worker lease on the main loop; a long synchronous handler can delay renewal, so keep leaseTtlMs well above the longest synchronous section.`,\n );\n this.startLeaseRenewal();\n } else {\n const started = await this.startLivenessThread(plan);\n if (!started.ok) {\n this.logger.warn(\n `Liveness thread did not start (${started.reason}); renewing the worker lease on the main loop.`,\n );\n this.startLeaseRenewal();\n }\n }\n\n // Stopped during the liveness handshake: start nothing more. The waiting\n // stop() releases the lease, the live set, the handler registry and the\n // thread stored above, so none of them outlives it.\n if (this.startCancelled) return;\n\n // Start polling loop\n this.resetIdlePollDelay();\n this.startPolling();\n\n // Start heartbeat loop (per-job telemetry only; no longer gates recovery)\n this.startHeartbeat();\n\n // Bound system-table growth while a worker is up (#2375). Opt out with\n // `retention: false`; the first sweep is one interval away, so a runner\n // that starts and stops (a test, a one-shot worker) deletes nothing.\n if (this.config.retention !== false && this.db) {\n this.retentionSweeper = startRetentionSweeper(this.db, {\n ...this.config.retention,\n });\n }\n\n this.emit('runner:started');\n }\n\n /**\n * Stop processing jobs (graceful shutdown)\n */\n async stop(): Promise<void> {\n if (this.stopPromise) return this.stopPromise;\n const pendingStart = this.startPromise;\n if (!this.running && !pendingStart) return;\n\n // A stop that overlaps start() (a SIGTERM during startup) cancels what\n // start() has not begun yet, waits for it to settle, then tears down what\n // it did begin. Returning earlier would leave the liveness thread renewing\n // a stopped runner's lease, and polling running after stop() (#4944).\n if (pendingStart) this.startCancelled = true;\n const stopping = (async () => {\n if (pendingStart) {\n try {\n await pendingStart;\n } catch {\n // A failed start() is the caller's error; tear down what it left.\n }\n }\n await this.shutdown();\n })();\n this.stopPromise = stopping;\n try {\n await stopping;\n } finally {\n if (this.stopPromise === stopping) this.stopPromise = null;\n }\n }\n\n /** The body of {@link stop}: drain, then release lease renewal and liveness. */\n private async shutdown(): Promise<void> {\n if (!this.running) return;\n if (this.shutdownPromise) return this.shutdownPromise;\n\n this.running = false;\n this.pollGeneration++;\n\n // Stop polling and the telemetry heartbeat immediately; no new jobs claim.\n if (this.pollTimer) {\n clearTimeout(this.pollTimer);\n this.pollTimer = null;\n }\n if (this.heartbeatTimer) {\n clearInterval(this.heartbeatTimer);\n this.heartbeatTimer = null;\n }\n if (this.retentionSweeper) {\n this.retentionSweeper.stop();\n this.retentionSweeper = null;\n }\n // NOTE: leave lease renewal (the leaseTimer or the off-loop thread) running\n // through the drain so a still-executing handler keeps its lease fresh and\n // isn't recovered by a peer; both are torn down after the drain below.\n\n // A planned stop must not leave over-claimed rows `running`: the next\n // incarnation's recovery would fail them as orphans without running them.\n await this.retryUnreleasedSurplus();\n\n // Wait for active jobs to complete (with timeout)\n this.shutdownPromise = this.waitForActiveJobs();\n\n try {\n await this.shutdownPromise;\n } finally {\n this.shutdownPromise = null;\n // The drain also waited for an in-flight poll, whose own surplus\n // release may have failed after the flush above: flush again (#3148).\n await this.retryUnreleasedSurplus();\n // Stop off-loop lease renewal (thread) and main-loop renewal (timer) only\n // AFTER the drain, so a still-running handler kept its lease fresh.\n await this.stopLivenessThread();\n if (this.leaseTimer) {\n clearInterval(this.leaseTimer);\n this.leaseTimer = null;\n }\n // Release liveness only AFTER the drain: doing it earlier would make\n // still-draining jobs look orphaned to other recoverers.\n unregisterLiveWorker(this.workerKey);\n releaseJobHandlerRegistry(this.workerKey);\n // Only delete the lease row if the drain finished cleanly. If jobs are\n // still executing past the shutdown timeout, leave the row to lapse\n // naturally (≤ TTL) so a nearly-finished handler keeps its chance to land\n // its own completion before peers can recover it.\n if (this.activeJobs.size === 0 && !this.pollPromise) {\n try {\n await this.workerCollection?.expireWorker(this.workerKey);\n } catch {\n // Best-effort: a left-over row simply expires via its lease.\n }\n }\n this.emit('runner:stopped');\n }\n }\n\n /**\n * Check if runner is running\n */\n isRunning(): boolean {\n return this.running;\n }\n\n /**\n * Get count of active jobs\n */\n activeJobCount(): number {\n return this.activeJobs.size;\n }\n\n /**\n * Start the polling loop\n */\n private startPolling(): void {\n const poll = async () => {\n if (!this.running) return;\n\n let foundWork = true;\n try {\n this.pollPromise = this.poll();\n foundWork = await this.pollPromise;\n } catch (error) {\n this.emit('runner:error', error as Error);\n } finally {\n this.pollPromise = null;\n }\n\n // Schedule next poll\n if (this.running) {\n this.pollTimer = setTimeout(poll, this.nextPollDelay(foundWork));\n }\n };\n\n // Start immediately\n poll();\n }\n\n /**\n * Poll for and process jobs\n */\n private nextPollDelay(foundWork: boolean): number {\n if (foundWork) {\n this.resetIdlePollDelay();\n return this.boundPollDelay(this.config.pollInterval);\n }\n\n const delay = this.idlePollDelayMs;\n this.idlePollDelayMs = Math.min(delay * 2, this.maxIdlePollIntervalMs);\n return this.boundPollDelay(delay);\n }\n\n private boundPollDelay(delay: number): number {\n // A throttled sweep may have been skipped on this poll. Bound the next\n // wait by the remaining recovery budget, not a fresh TTL from this poll.\n const elapsed = this.workersTableVerified\n ? Date.now() - this.lastRecoverySweepAt\n : 0;\n return Math.min(delay, Math.max(1, this.effectiveLeaseTtlMs - elapsed));\n }\n\n private resetIdlePollDelay(): void {\n this.idlePollDelayMs = this.config.pollInterval;\n }\n\n private async poll(): Promise<boolean> {\n const generation = this.pollGeneration;\n if (!this.collection || !this.db) return true;\n\n // stop() may begin while any await below is pending; it waits for this\n // poll, so bail out instead of claiming work after shutdown began (#3148).\n await this.recoverStaleJobs();\n if (generation !== this.pollGeneration) return false;\n await this.retryUnreleasedSurplus();\n if (generation !== this.pollGeneration) return false;\n await this.sweepUnclaimedHandlerJobs();\n if (generation !== this.pollGeneration) return false;\n\n // Calculate how many jobs we can take\n const available = this.config.concurrency - this.activeJobs.size;\n if (available <= 0) return true;\n\n // Atomically claim ready jobs before processing so multiple workers cannot\n // receive the same pending row.\n const claimed = await this.collection.claimReady({\n claimFencing: this.config.claimFencing,\n workerId: this.workerKey,\n queues: this.config.queues,\n tenantIds: this.config.tenantIds,\n // Model jobs, and only the handler jobs this runner can run (#5005).\n handlerNames: this.handlerNames,\n limit: available,\n });\n\n // `concurrency` is a hard cap: never start more jobs than free slots, even\n // if a claim returns extra rows (a PostgreSQL claim once took the whole\n // backlog, #3145). Surplus rows go back to `pending` untouched.\n const jobs = claimed.slice(0, available);\n if (claimed.length > available) {\n await this.releaseSurplusClaims(claimed.slice(available));\n }\n\n for (const [index, job] of jobs.entries()) {\n // Shutdown may start during the claim, surplus release, or a previous\n // job's synchronous started listener. Never dispatch an unstarted claim.\n if (generation !== this.pollGeneration) {\n await this.releaseSurplusClaims(jobs.slice(index), false);\n return false;\n }\n const jobId = job.id;\n if (!jobId) continue;\n\n // Process asynchronously. We deliberately do NOT await — concurrency is\n // bounded by `activeJobs` above, not by serializing here. But a bare\n // fire-and-forget call means any unexpected rejection (e.g. the failure-\n // path write in handleJobError rejecting, a failure mode correlated with\n // whatever is already failing the job) escapes as an unhandled promise\n // rejection and crashes the worker under Node's default\n // `--unhandled-rejections=throw`. handleJobError is itself wrapped in\n // try/catch, but guard the caller too as defense in depth so no rejection\n // can ever escape the poll loop.\n this.processJob(job).catch((error) => {\n this.emit('runner:error', error as Error);\n });\n }\n\n return jobs.length > 0;\n }\n\n /**\n * Return over-claimed rows to `pending` with their claim undone, so the\n * attempt is not consumed and any worker can claim them normally. Only rows\n * this incarnation still owns as `running` and is not executing are\n * touched, in chunked statements.\n *\n * A failed release keeps the ids; it is retried at the start of every poll\n * and by `stop()` both before and after its drain. If the process dies\n * first, stale recovery fails those rows as orphaned (it does not requeue\n * them).\n */\n private async releaseSurplusClaims(\n surplus: SmrtJob[],\n reportExceededLimit = true,\n ): Promise<void> {\n const ids = surplus\n .map((job) => job.id)\n .filter((id): id is string => typeof id === 'string' && id.length > 0);\n if (ids.length === 0) return;\n if (reportExceededLimit)\n this.emit(\n 'runner:error',\n new Error(\n `claimReady returned ${ids.length} job(s) beyond the concurrency limit (${this.config.concurrency}); releasing them back to pending`,\n ),\n );\n for (const id of ids) this.unreleasedSurplus.add(id);\n await this.retryUnreleasedSurplus();\n }\n\n private async retryUnreleasedSurplus(): Promise<void> {\n if (!this.db) return;\n // A retained id this runner has since claimed normally is live work, not\n // surplus: never unclaim a job this incarnation is executing.\n for (const id of this.unreleasedSurplus) {\n if (this.activeJobs.has(id)) this.unreleasedSurplus.delete(id);\n }\n const ids = [...this.unreleasedSurplus];\n for (let i = 0; i < ids.length; i += SURPLUS_RELEASE_CHUNK) {\n const chunk = ids.slice(i, i + SURPLUS_RELEASE_CHUNK);\n const placeholders = chunk.map(() => '?').join(', ');\n try {\n await this.db.query(\n `UPDATE _smrt_jobs\n SET status = 'pending',\n worker_id = NULL,\n worker_heartbeat = NULL,\n started_at = NULL,\n attempts = CASE WHEN attempts > 0 THEN attempts - 1 ELSE 0 END,\n updated_at = ?\n WHERE worker_id = ? AND status = 'running' AND id IN (${placeholders})`,\n new Date().toISOString(),\n this.workerKey,\n ...chunk,\n );\n // Rows the statement did not match are no longer this worker's\n // `running` claim, so there is nothing left to release for them.\n for (const id of chunk) this.unreleasedSurplus.delete(id);\n } catch (error) {\n // Still `running` under this worker's live lease; never started here.\n this.emit('runner:error', error as Error);\n }\n }\n }\n\n /**\n * Process a single job.\n *\n * AT-LEAST-ONCE EXECUTION CONTRACT: a `timeout` only races the handler's\n * promise — JavaScript cannot preempt an already-running handler, so on a\n * `'fail'` (or `'kill'`) timeout the original handler keeps executing in the\n * background while the job row is failed. Timeouts are NOT auto-retried (see\n * handleJobError) precisely so a still-running handler is not duplicated by a\n * retry; but the orphaned handler's own side effects still happen, and an\n * ordinary (non-timeout) failure IS retried and re-claimable by any worker.\n * Handlers invoked from a job MUST be idempotent (e.g. keyed by\n * `context.job.jobId` or a caller-supplied idempotency key); do not rely on a\n * job body running exactly once. See AGENTS.md \"Timeouts & at-least-once\".\n */\n private async processJob(job: SmrtJob): Promise<void> {\n const jobId = job.id;\n if (!jobId) {\n this.emit('runner:error', new Error('Job has no ID'));\n return;\n }\n\n this.activeJobs.set(jobId, job);\n this.emit('job:started', job);\n await this.appendJobEvent(job, {\n type: 'status',\n level: 'info',\n stage: 'started',\n progress: 0,\n message: `Started job: ${job.getDescription()}`,\n });\n\n // Capture the timeout handle so it is always cleared in `finally`. Without\n // this, every fast job left a ~5-min (default) armed timer on the heap\n // until it fired and was swallowed by the settled race — timer-heap\n // pressure plus a delayed clean process exit.\n let timeoutHandle: NodeJS.Timeout | null = null;\n let cancelPollHandle: NodeJS.Timeout | null = null;\n const abortController = new AbortController();\n this.jobAborts.set(jobId, abortController);\n\n try {\n cancelPollHandle = this.startCancelPoll(job, abortController);\n const result = await this.runWithTimeout(job, (handle) => {\n timeoutHandle = handle;\n });\n\n // Job completed successfully. Write the terminal state conditionally so a\n // recovered/reclaimed row (worker died, recovery ran, the work finished\n // anyway) is never stomped back to 'completed'.\n const completedAt = new Date();\n const snapshot = terminalSnapshot(job, this.config.claimFencing);\n let event: SmrtJobEvent | null = null;\n try {\n event = snapshot\n ? await transitionTerminalJob(this.db as DatabaseInterface, {\n job: snapshot,\n status: 'completed',\n completedAt,\n expectedStatuses: ['running'],\n expectedWorkerId: this.workerKey,\n resultPointer: result?.resultPointer ?? null,\n taskResult: result?.taskResult ?? null,\n })\n : null;\n } catch (persistenceError) {\n // The handler already returned successfully. A terminal persistence\n // failure is an operator fault, not a business execution failure: the\n // transaction left the owned row running, and it must not be retried\n // through handleJobError(). The recovery sweep settles it as failed,\n // with its event, saying what happened.\n this.reportUnpersistedJobWrite(\n job,\n 'completion',\n persistenceError,\n `Job handler returned but its completion could not be persisted (${redactErrorForPersistence(persistenceError)}); settled as failed by recovery, not retried.`,\n );\n return;\n }\n\n if (event) {\n job.status = 'completed';\n job.completedAt = completedAt;\n job.resultPointer = result?.resultPointer ?? null;\n job.taskResult = result?.taskResult ?? null;\n this.emitPersistedJobEvent(job, event);\n this.emit('job:completed', job, result);\n }\n } catch (error) {\n // handleJobError is wrapped so its own failure-path write (a `db.query`\n // that may reject for the same reason the job is failing) cannot turn\n // into an unhandled rejection / unbounded crash. A failure to persist the\n // failure is surfaced as a runner error, not a thrown rejection.\n try {\n await this.handleJobError(job, error as Error);\n } catch (handlerError) {\n if (handlerError instanceof UnpersistedJobWriteError) {\n this.reportUnpersistedJobWrite(\n job,\n 'failure',\n handlerError.writeError,\n `${redactErrorForPersistence(error)} (the failure could not be persisted when it happened: ${redactErrorForPersistence(handlerError.writeError)}; settled as failed by recovery, not retried.)`,\n );\n } else {\n // A listener or telemetry call threw after the write committed:\n // the row is not stranded, so this is only a runner error.\n this.emit('runner:error', handlerError as Error);\n }\n }\n } finally {\n if (timeoutHandle) clearTimeout(timeoutHandle);\n if (cancelPollHandle) clearInterval(cancelPollHandle);\n this.jobAborts.delete(jobId);\n this.activeJobs.delete(jobId);\n }\n }\n\n /**\n * Every terminal write needs the terminal-outcome storage, and preparing it\n * builds the registry's merged schemas. Prepare it before claiming anything\n * (#4735): a registry inconsistency then stops the runner at start, naming\n * itself, instead of leaving every claimed job `running`; and models that\n * register after start can no longer block a terminal write, because\n * readiness is cached for this database.\n */\n private async prepareTerminalOutcomeStorage(): Promise<void> {\n try {\n await ensureTerminalOutcomeStorage(this.db as DatabaseInterface);\n } catch (error) {\n this.logger.error(\n `TaskRunner cannot start: terminal job outcomes cannot be persisted: ${redactErrorForPersistence(error)}`,\n );\n throw error;\n }\n }\n\n /**\n * A job's terminal (or retry) write could not be persisted. The state and\n * its event commit together or not at all, so the row is still `running`.\n *\n * It must not be silent (#4735): `runner:error` is only heard by a caller\n * that listens, so say it at error level with the job id as well. And it\n * must not stay `running` for good: the owning worker is alive, so\n * liveness-based recovery would skip the row until this process stops.\n * `settleAs` records the `last_error` this runner's own recovery sweep\n * settles it with, atomically with its event, once the fault clears.\n */\n private reportUnpersistedJobWrite(\n job: SmrtJob,\n write: 'completion' | 'failure' | 'stale recovery',\n cause: unknown,\n settleAs?: string,\n ): void {\n const error = cause instanceof Error ? cause : new Error(String(cause));\n const jobId = job.id;\n if (settleAs && jobId) this.unsettledJobs.set(jobId, settleAs);\n const firstReport =\n write !== 'stale recovery' ||\n !jobId ||\n !this.recoveryFailuresLogged.has(jobId);\n if (firstReport) {\n if (write === 'stale recovery' && jobId) {\n this.recoveryFailuresLogged.add(jobId);\n }\n const next =\n write === 'stale recovery'\n ? 'it stays running and each recovery sweep retries it'\n : \"it stays running until this runner's next recovery sweep settles it as failed\";\n this.logger.error(\n `Job ${jobId} (${job.getDescription()}) ${write} could not be persisted; ${next}: ${redactErrorForPersistence(error)}`,\n );\n }\n this.emit('runner:error', error);\n }\n\n /** Tag a rejection from a job's own state write (see the caller's catch). */\n private async persistJobWrite<T>(write: () => Promise<T>): Promise<T> {\n try {\n return await write();\n } catch (cause) {\n throw new UnpersistedJobWriteError(cause);\n }\n }\n\n /**\n * Execute a job honoring its {@link SmrtJob.timeoutBehavior}.\n *\n * - `'fail'` (default) and `'kill'`: race the handler against a timeout. On\n * timeout the race rejects and the caller fails/retries the job.\n * `'kill'` cannot actually preempt the handler in-process (JavaScript has\n * no thread interruption), so it is treated identically to `'fail'` — the\n * handler keeps running in the background; only the job row is failed. This\n * is documented in AGENTS.md so `'kill'` is honest about what it does\n * rather than silently behaving like a no-op.\n * - `'warn'`: do NOT fail on timeout. Arm a one-shot warning (logged + emitted\n * as a job event) at the deadline, but await the handler to completion so a\n * slow-but-successful handler still completes. This makes `'warn'` honest:\n * previously every timeout was treated as `'fail'` regardless of the\n * persisted/UI-shown behavior.\n */\n private async runWithTimeout(\n job: SmrtJob,\n captureHandle: (handle: NodeJS.Timeout) => void,\n ): Promise<{\n result?: unknown;\n resultPointer?: string;\n taskResult?: Record<string, unknown>;\n }> {\n if (job.timeoutBehavior === 'warn') {\n const handle = setTimeout(() => {\n this.logger.warn(\n `Job exceeded timeout (${job.timeout}ms) but timeoutBehavior='warn'; letting it finish: ${job.getDescription()}`,\n );\n // Best-effort telemetry; must not change the job outcome.\n void this.appendJobEvent(job, {\n type: 'status',\n level: 'warn',\n stage: 'timeout-warning',\n message: `Job exceeded timeout of ${job.timeout}ms (timeoutBehavior='warn')`,\n data: { timeout: job.timeout },\n });\n }, job.timeout);\n captureHandle(handle);\n return this.executeJob(job);\n }\n\n // 'fail' (default) and 'kill' (treated as 'fail'; see doc comment).\n const timeoutPromise = new Promise<never>((_, reject) => {\n const handle = setTimeout(() => {\n const timeoutError = new JobTimeoutError(\n `Job timeout after ${job.timeout}ms`,\n );\n // Let the orphaned handler stop; the row is failed by the rejection.\n const controller = job.id ? this.jobAborts.get(job.id) : undefined;\n controller?.abort(timeoutError);\n reject(timeoutError);\n }, job.timeout);\n captureHandle(handle);\n });\n\n return Promise.race([this.executeJob(job), timeoutPromise]);\n }\n\n /**\n * Poll the owned row while its handler runs and abort the job's signal when\n * it is observed as cancelled. Read-only; failures are ignored (the next tick\n * retries). Returns an unref'd interval the caller must clear.\n */\n private startCancelPoll(\n job: SmrtJob,\n controller: AbortController,\n ): NodeJS.Timeout | null {\n const jobId = job.id;\n const db = this.db;\n if (!jobId || !db) return null;\n let inFlight = false;\n const handle = setInterval(() => {\n if (inFlight || controller.signal.aborted) return;\n inFlight = true;\n void Promise.resolve()\n .then(() =>\n db.query(`SELECT status FROM _smrt_jobs WHERE id = ?`, jobId),\n )\n .then((res) => {\n const status = (res?.rows?.[0] as { status?: string } | undefined)\n ?.status;\n if (status === 'cancelled' && !controller.signal.aborted) {\n controller.abort(\n new JobCancelledError(`Job cancelled: ${job.getDescription()}`),\n );\n }\n })\n .catch(() => {})\n .finally(() => {\n inFlight = false;\n });\n }, this.config.cancelPollInterval);\n handle.unref();\n return handle;\n }\n\n /**\n * Apply a terminal/retry state transition to a job only if this worker still\n * owns it and it is still `running`. Returns whether the write applied.\n *\n * This closes the completion-vs-recovery race: if recovery already failed a\n * job out from under a finishing handler (a genuine zombie), the handler's\n * outcome is dropped rather than resurrecting the row.\n */\n private async writeOwnedJob(\n jobId: string,\n assignments: Record<string, unknown>,\n dispatch?: SmrtJob,\n ): Promise<boolean> {\n if (!this.db) return false;\n const columns = Object.keys(assignments);\n const setSql = columns.map((column) => `${column} = ?`).join(', ');\n const values = columns.map((column) => assignments[column]);\n // RETURNING id (not rowCount): the DuckDB/JSON adapters report rowCount as\n // the number of result rows, so an UPDATE that matched nothing still\n // reports 1 — only the returned-row set is a reliable \"did it apply\".\n const fenced = this.config.claimFencing && dispatch;\n const result = await this.db.query(\n `UPDATE _smrt_jobs\n SET ${setSql}\n WHERE id = ? AND worker_id = ? AND status = 'running'${fenced ? ' AND attempts = ? AND started_at = ?' : ''}\n RETURNING id`,\n ...values,\n jobId,\n this.workerKey,\n ...(fenced\n ? [dispatch.attempts, dispatch.startedAt?.toISOString() ?? null]\n : []),\n );\n return (result.rows?.length ?? 0) > 0;\n }\n\n /**\n * Execute a job by invoking the method on the SmrtObject\n */\n private async executeJob(job: SmrtJob): Promise<{\n result?: unknown;\n resultPointer?: string;\n taskResult?: Record<string, unknown>;\n }> {\n const runJob = async (): Promise<{\n result?: unknown;\n resultPointer?: string;\n taskResult?: Record<string, unknown>;\n }> => {\n await this.assertMcpTaskAuthority(job);\n // A reserved `handler:` target never reaches the model registry (#5005).\n const handlerName = jobHandlerName(job.objectType);\n if (handlerName !== null) return this.executeHandlerJob(job, handlerName);\n // Get the object class from registry\n const registeredClass = ObjectRegistry.getClass(job.objectType);\n if (!registeredClass) {\n throw new Error(`Unknown object type: ${job.objectType}`);\n }\n\n // Get the constructor from the registry entry\n const ObjectClass = registeredClass.constructor as unknown as new (\n options: Record<string, unknown>,\n ) => SmrtObject;\n\n // Extract internal keys from args before passing to constructor/method\n const rawArgs = (job.args ?? {}) as Record<string, unknown>;\n const persistedAgentConfig = (rawArgs._agentConfig ?? {}) as Record<\n string,\n unknown\n >;\n const {\n _agentConfig: _,\n _scheduleId: __,\n _mcpTask: ___,\n ...methodArgs\n } = rawArgs;\n\n // Resolve any lazy / env-derived config sentinels at execute time so\n // operators can rotate env vars without rewriting persisted schedule\n // rows (issue #1161). Class-level `static configResolvers` are layered\n // on top so live values always win over snapshotted ones.\n //\n // `onError: 'throw'` so a misconfigured deployment fails fast at the\n // job boundary with a clear \"unknown resolver X\" error, rather than\n // silently spreading a `{ $env: '...' }` sentinel object into the\n // agent constructor (where it would surface much later as a confusing\n // downstream failure — e.g. `[object Object]` masquerading as a\n // bucket name).\n //\n // Every resolver receives this job's own agent identity and the value\n // this instance's persisted config holds for its key (#2806), so a\n // per-agent credential resolver can defer to the agent's own value. The\n // identity comes only from the job row — never from scanning the\n // tenant's other agents.\n const classResolvers = getClassConfigResolvers(ObjectClass);\n const scheduleId =\n typeof rawArgs._scheduleId === 'string'\n ? rawArgs._scheduleId\n : undefined;\n const agentConfig = await resolveLazyConfig(persistedAgentConfig, {\n classResolvers,\n onError: 'throw',\n context: {\n agentId:\n typeof job.objectId === 'string' && job.objectId.length > 0\n ? job.objectId\n : undefined,\n agentClass: registeredClass.qualifiedName ?? job.objectType,\n tenantId: job.tenantId ?? null,\n scheduleId,\n jobId: job.id ?? undefined,\n },\n });\n\n // Persistence identity and the database connection belong to the\n // runner. Persisted constructor config may configure the target, but it\n // must never redirect hydration or execution to a different store.\n const safeAgentConfig = { ...agentConfig };\n delete safeAgentConfig.db;\n delete safeAgentConfig.id;\n delete safeAgentConfig._skipLoad;\n\n // Create or load the object instance\n let instance: SmrtObject;\n\n if (job.objectId) {\n // initialize() performs the canonical hydration when the persisted ID\n // is supplied to the constructor.\n instance = new ObjectClass({\n db: this.db,\n id: job.objectId,\n ...safeAgentConfig,\n });\n await instance.initialize();\n\n if (!instance.isPersisted) {\n throw new Error(\n `Object-bound job target not found: ${job.objectType}#${job.objectId}`,\n );\n }\n } else {\n // Create new instance for static-like methods\n instance = new ObjectClass({ db: this.db, ...safeAgentConfig });\n await instance.initialize();\n }\n\n const jobId = job.id;\n if (!jobId) {\n throw new Error('Job has no ID');\n }\n\n // Create a base logger for job context\n const baseLogger = createLogger(true);\n\n // Inject job context logger\n const contextLogger = new JobContextLogger(baseLogger, {\n jobId,\n attempt: job.attempts,\n queue: job.queue,\n objectType: job.objectType,\n method: job.method,\n });\n\n // Log job start\n contextLogger.info(`Starting job: ${job.getDescription()}`);\n const executionContext = this.createExecutionContext(job, contextLogger);\n\n // Invoke the method with cleaned args (no internal keys)\n const method = (\n instance as unknown as Record<\n string,\n (\n args: unknown,\n context?: JobExecutionContext,\n ) => Promise<unknown> | unknown\n >\n )[job.method];\n if (typeof method !== 'function') {\n throw new Error(`Method not found: ${job.objectType}.${job.method}`);\n }\n\n // Opt-in allowlist: if the target class declares background-eligible\n // methods, refuse to invoke anything outside that set. Dispatch is already\n // bounded to existing prototype methods (no eval/dynamic import), but a\n // class can narrow the reachable surface to an explicit contract\n // (S5 audit #1402). Classes that don't opt in keep current behaviour.\n if (!isBackgroundEligibleMethod(ObjectClass, job.method)) {\n throw new Error(\n `Method not background-eligible: ${job.objectType}.${job.method}`,\n );\n }\n\n const taskMarker = getMcpTaskMarker(job);\n const result = await runnerExecutionContexts.run(\n executionContext,\n async () =>\n taskMarker\n ? await (\n method as (...args: unknown[]) => Promise<unknown> | unknown\n ).call(instance, ...taskMarker.invocationArgs, executionContext)\n : await method.call(instance, methodArgs, executionContext),\n );\n\n // Generated custom actions use an explicit `{ ok: false, ... }` return\n // convention. A task must surface that as a failed terminal state, not\n // a successfully completed task whose payload happens to describe an\n // error.\n if (taskMarker) {\n const failure = normalizeCustomActionFailure(result);\n if (failure) throw new Error(failure.message);\n }\n\n return {\n result,\n ...(taskMarker ? { taskResult: createMcpTaskResult(result) } : {}),\n };\n };\n\n if (job.tenantId) {\n return TenantContext.runWithJobContext(\n { tenantId: job.tenantId },\n runJob,\n );\n }\n\n return runJob();\n }\n\n /**\n * Run a job that targets a registered named handler (#5005). Called inside\n * `executeJob`'s tenant context, after the same MCP authority check as a\n * model job; timeout, cancellation, claim fencing and terminal writes are\n * the shared model-job paths.\n */\n private async executeHandlerJob(\n job: SmrtJob,\n name: string,\n ): Promise<{ result?: unknown }> {\n if (job.method !== JOB_HANDLER_METHOD || job.objectId != null)\n throw new JobHandlerTargetError(\n `Handler job ${job.objectType} must have method '${JOB_HANDLER_METHOD}' and no objectId`,\n );\n if (getMcpTaskMarker(job) || job.taskId != null || job.taskOwnerId != null)\n throw new JobHandlerTargetError(\n `Handler job ${job.objectType} cannot be an MCP task`,\n );\n const handler = this.jobHandlers.get(name);\n if (!handler) throw new JobHandlerUnregisteredError(name);\n\n const jobId = job.id;\n if (!jobId) throw new Error('Job has no ID');\n const {\n _agentConfig: _,\n _scheduleId: __,\n _mcpTask: ___,\n ...payload\n } = (job.args ?? {}) as Record<string, unknown>;\n const contextLogger = new JobContextLogger(createLogger(true), {\n jobId,\n attempt: job.attempts,\n queue: job.queue,\n objectType: job.objectType,\n method: job.method,\n });\n contextLogger.info(`Starting job: ${job.getDescription()}`);\n const executionContext = this.createExecutionContext(\n job,\n contextLogger,\n name,\n );\n const result = await runnerExecutionContexts.run(\n executionContext,\n async () => await handler(payload, executionContext),\n );\n return { result };\n }\n\n /**\n * Handle job execution error\n */\n private async handleJobError(job: SmrtJob, error: Error): Promise<void> {\n if (error instanceof McpTaskSuspendedError) return;\n const { fromConfig } = await import('@happyvertical/jobs');\n const strategy = fromConfig(job.retryStrategy);\n const decision: RetryDecision = strategy.shouldRetry(job.attempts, error);\n\n const jobId = job.id;\n if (!jobId) return;\n\n // A timed-out handler keeps running in the background (JS can't preempt it).\n // Re-queueing the row as `pending` while the original still executes would\n // make the next worker run a *second* concurrent copy. So do not auto-retry\n // a timeout — fail it terminally. This narrows the duplicate-execution\n // window from the at-least-once contract (#2 in the #1401 review); it does\n // not remove it (the orphaned handler can still finish and write a terminal\n // state, which writeOwnedJob's ownership guard then drops).\n const isTimeout = error instanceof JobTimeoutError;\n\n // `last_error` is persisted to the durable `_smrt_jobs` row and is readable\n // through generated (tenant-scoped) list/get routes. Strip secret-shaped\n // substrings before persistence so a failing job that echoes a credential\n // in its message does not turn into a durable leak (S5 audit #1402).\n // Use the throwable-tolerant wrapper: `error` is typed `Error` but reaches\n // here via an `as Error` cast at the call site, so a non-Error throwable\n // (no `.message`) would otherwise persist an empty `last_error`.\n const safeMessage = redactErrorForPersistence(error);\n\n // The handler's own hints win over the strategy: `retryable: false` is\n // terminal, and `retryAfterMs` is a floor on the strategy's backoff.\n const hints = errorRetryHints(error);\n const delay = Math.max(decision.delay, hints.retryAfterMs ?? 0);\n\n if (\n !isTimeout &&\n hints.retryable &&\n decision.shouldRetry &&\n job.attempts < job.maxAttempts\n ) {\n // Schedule retry\n const nextRunAt = new Date(Date.now() + delay);\n\n // Conditional: don't resurrect a row that recovery already failed.\n const applied = await this.persistJobWrite(() =>\n this.writeOwnedJob(\n jobId,\n {\n status: 'pending',\n last_error: safeMessage,\n run_at: nextRunAt.toISOString(),\n worker_id: null,\n worker_heartbeat: null,\n updated_at: new Date().toISOString(),\n },\n job,\n ),\n );\n if (!applied) return;\n\n job.status = 'pending';\n job.lastError = safeMessage;\n job.runAt = nextRunAt;\n job.workerId = null;\n job.workerHeartbeat = null;\n\n await this.appendJobEvent(job, {\n type: 'status',\n level: 'warn',\n stage: 'retrying',\n message: `Retrying job after failure: ${safeMessage}`,\n data: { delay, attempts: job.attempts },\n });\n this.emit('job:retrying', job, error, delay);\n } else {\n // Job failed permanently\n const completedAt = new Date();\n const snapshot = terminalSnapshot(job, this.config.claimFencing);\n const event = snapshot\n ? await this.persistJobWrite(() =>\n transitionTerminalJob(this.db as DatabaseInterface, {\n job: snapshot,\n status: 'failed',\n completedAt,\n expectedStatuses: ['running'],\n expectedWorkerId: this.workerKey,\n lastError: safeMessage,\n failureKind: isTimeout\n ? 'timeout'\n : error instanceof JobHandlerUnregisteredError\n ? 'handler-unregistered'\n : 'execution',\n }),\n )\n : null;\n if (!event) return;\n\n job.status = 'failed';\n job.completedAt = completedAt;\n job.lastError = safeMessage;\n\n this.emitPersistedJobEvent(job, event);\n this.emit('job:failed', job, error);\n }\n }\n\n private async assertMcpTaskAuthority(job: SmrtJob): Promise<void> {\n const marker = getMcpTaskMarker(job);\n const continuation = marker?.continuation;\n if (!continuation && !marker?.authorizationRequired) return;\n let authorized = false;\n try {\n authorized =\n !!job.taskOwnerId &&\n (await this.config.authorizeMcpTask(\n Object.freeze({\n ownerId: job.taskOwnerId,\n tenantId: job.tenantId ?? null,\n taskId: job.taskId ?? '',\n objectType: job.objectType,\n objectId: job.objectId ?? '',\n method: job.method,\n ...(continuation\n ? { continuation: Object.freeze({ ...continuation }) }\n : {}),\n }),\n ));\n } catch {\n // Provider failures are internal; never persist their details in tasks/get.\n }\n if (!authorized) throw new Error('MCP task authorization denied');\n // Authority lookup may await network I/O; cancellation can win meanwhile.\n const owned = await this.db?.query(\n `SELECT id FROM _smrt_jobs WHERE id = ? AND worker_id = ? AND status = 'running'`,\n job.id,\n job.workerId,\n );\n if (owned?.rows.length !== 1)\n throw new Error('MCP task is no longer active');\n }\n\n private createExecutionContext(\n job: SmrtJob,\n contextLogger: JobContextLogger,\n handler?: string,\n ): JobExecutionContext {\n const jobContext = {\n jobId: job.id ?? '',\n tenantId: job.tenantId ?? null,\n attempt: job.attempts,\n queue: job.queue,\n objectType: job.objectType,\n method: job.method,\n ...(handler === undefined ? {} : { handler }),\n };\n\n const context: JobExecutionContext = {\n job: jobContext,\n logger: contextLogger,\n signal:\n (job.id ? this.jobAborts.get(job.id)?.signal : undefined) ??\n new AbortController().signal,\n event: async (input: JobEventInput) => {\n await this.appendJobEvent(job, input);\n },\n progress: async (input: JobProgressInput) => {\n const data = {\n ...(input.data ?? {}),\n ...(input.detail ? { detail: input.detail } : {}),\n ...(input.source ? { source: input.source } : {}),\n };\n await this.appendJobEvent(job, {\n type: 'progress',\n level: 'info',\n stage: input.stage,\n progress: input.progress,\n message:\n input.message ??\n input.detail ??\n `${input.stage} ${Math.round(input.progress)}%`,\n data,\n });\n },\n log: async (\n level: 'debug' | 'info' | 'warn' | 'error',\n message: string,\n data?: Record<string, unknown>,\n ) => {\n contextLogger[level](message, data);\n await this.appendJobEvent(job, {\n type: level === 'error' ? 'error' : 'log',\n level,\n message,\n data,\n });\n },\n ...(job.taskId && this.db\n ? {\n task: {\n assertAuthorized: () => this.assertMcpTaskAuthority(job),\n requestContinuation: (binding, inputRequest) =>\n requestMcpTaskContinuation(\n this.db as DatabaseInterface,\n job,\n binding,\n inputRequest,\n ),\n requestInput: async (inputRequests: Record<string, unknown>) => {\n await this.assertMcpTaskAuthority(job);\n const answers = await requestMcpTaskInput(\n this.db as DatabaseInterface,\n job,\n inputRequests,\n );\n await this.assertMcpTaskAuthority(job);\n return answers;\n },\n },\n }\n : {}),\n };\n runnerExecutionContextIdentities.add(context);\n if (this.config.claimFencing)\n runnerJobClaims.set(\n context,\n Object.freeze({\n jobId: job.id ?? '',\n workerId: this.workerKey,\n attempt: job.attempts,\n startedAt: job.startedAt?.toISOString() ?? '',\n tenantId: job.tenantId ?? null,\n objectType: job.objectType,\n objectId: job.objectId ?? null,\n method: job.method,\n }),\n );\n return context;\n }\n\n private async appendJobEvent(\n job: SmrtJob,\n input: JobEventInput,\n ): Promise<SmrtJobEvent | null> {\n if (!this.eventCollection || !job.id) {\n return null;\n }\n\n try {\n const event = await this.eventCollection.append({\n tenantId: job.tenantId ?? null,\n jobId: job.id,\n type: input.type ?? 'log',\n level: input.level ?? 'info',\n stage: input.stage ?? null,\n progress: input.progress ?? null,\n message: input.message ?? '',\n data: input.data ?? {},\n });\n\n this.emitPersistedJobEvent(job, event);\n\n return event;\n } catch (error) {\n const telemetryError =\n error instanceof Error\n ? error\n : new Error(`Failed to append job telemetry: ${String(error)}`);\n\n try {\n this.emit('runner:error', telemetryError);\n } catch {\n // Telemetry is best-effort and must not change job outcomes.\n }\n\n return null;\n }\n }\n\n private emitPersistedJobEvent(job: SmrtJob, event: SmrtJobEvent): void {\n try {\n this.emit('job:event', job, event);\n } catch (error) {\n this.emitTelemetryError(error);\n }\n if (event.type === 'progress') {\n try {\n this.emit('job:progress', job, event);\n } catch (error) {\n this.emitTelemetryError(error);\n }\n }\n }\n\n private emitTelemetryError(error: unknown): void {\n const telemetryError =\n error instanceof Error\n ? error\n : new Error(`Job telemetry listener failed: ${String(error)}`);\n try {\n this.emit('runner:error', telemetryError);\n } catch {\n // Telemetry is best-effort and must not change job outcomes.\n }\n }\n\n /**\n * Whether the `_smrt_workers` table exists. Cached once positive — the table\n * never disappears mid-run, so this avoids a probe query on every poll.\n */\n private async workersTableReady(): Promise<boolean> {\n if (this.workersTableVerified) return true;\n const ready = (await this.workerCollection?.tableReady()) ?? false;\n if (ready) this.workersTableVerified = true;\n return ready;\n }\n\n /**\n * Recover jobs orphaned by dead/restarted workers.\n *\n * A `running` job is recovered only when its owning worker is *not alive*\n * (issue #1474): not live in this process and holding no fresh lease in\n * `_smrt_workers`. This is independent of the handler event loop, so a worker\n * whose handler holds the loop synchronously keeps a fresh lease (renewed off\n * the loop by the liveness thread) or stays in this process's live set, and is\n * never false-recovered. The live set takes precedence over a stale lease, and\n * a runner never recovers its own active jobs.\n *\n * Recovery is swept at most once per lease tick (not every poll), since\n * detection is TTL-bound anyway — this bounds the per-poll database load.\n */\n private async recoverStaleJobs(): Promise<void> {\n if (!this.db || !this.collection || !this.workerCollection) return;\n\n // Without the workers table we cannot reason about liveness; skip rather\n // than treat every worker as unknown and mass-recover live jobs.\n if (!(await this.workersTableReady())) return;\n\n // Throttle: at most one sweep per lease tick. Detection latency is bounded\n // by the lease TTL (>= 3x tick), so a faster cadence only adds DB load.\n const now = Date.now();\n if (now - this.lastRecoverySweepAt < this.config.leaseTickMs) return;\n this.lastRecoverySweepAt = now;\n\n // Drop long-dead worker rows so the table stays small, regardless of\n // whether any orphan is found this sweep.\n try {\n await this.workerCollection.pruneExpired(this.effectiveLeaseTtlMs * 10);\n } catch {\n // Pruning is best-effort and must not affect recovery outcomes.\n }\n\n const freshLeaseKeys = await this.workerCollection.freshLeaseWorkerKeys();\n // Worker-internal cross-tenant recovery scan; SmrtJob is @TenantScoped\n // (S5 #1402) so this raw read needs an explicit opt-in.\n const scope = jobTenantScope(this.config.tenantIds);\n const queuePredicate = this.config.queues.length\n ? ` AND queue IN (${this.config.queues.map(() => '?').join(', ')})`\n : '';\n const running = await this.collection.query(\n `SELECT ${SMRT_JOB_PORTABLE_SELECT_COLUMNS}\n FROM _smrt_jobs\n WHERE status = 'running'${scope.sql}${queuePredicate}`,\n [...scope.params, ...this.config.queues],\n { allowRawOnTenantScoped: true },\n );\n // Forget rows that are no longer running: settled by a peer, cancelled,\n // or committed after all.\n const runningIds = new Set(running.map((job) => job.id));\n for (const jobId of this.unsettledJobs.keys()) {\n if (!runningIds.has(jobId)) this.unsettledJobs.delete(jobId);\n }\n for (const jobId of this.recoveryFailuresLogged) {\n if (!runningIds.has(jobId)) this.recoveryFailuresLogged.delete(jobId);\n }\n if (running.length === 0) return;\n\n // A job is orphaned iff its owning worker is not alive: not live in this\n // process AND no fresh database lease. The live set takes precedence over a\n // stale lease (a worker whose lease lapsed while its loop was blocked is\n // still alive here); a runner also never recovers its own active jobs.\n // The exception is a row this runner itself could not settle (#4735): it\n // finished here, nothing will run it again, and no other worker may touch\n // it while this one is alive.\n const orphans = running.filter((job) => {\n const jobId = job.id;\n if (jobId && this.activeJobs.has(jobId)) return false;\n if (\n jobId &&\n this.unsettledJobs.has(jobId) &&\n job.workerId === this.workerKey\n ) {\n return true;\n }\n return !isWorkerAlive(job.workerId, freshLeaseKeys);\n });\n if (orphans.length === 0) return;\n\n const recoveredAt = new Date();\n const errorMessage =\n 'Recovered orphaned running job: its owning worker is no longer alive ' +\n '(no fresh liveness lease in _smrt_workers and not running in this process).';\n\n for (const job of orphans) {\n const snapshot = terminalSnapshot(job, this.config.claimFencing);\n if (!snapshot) continue;\n const lastError =\n (job.id ? this.unsettledJobs.get(job.id) : undefined) ?? errorMessage;\n let event: SmrtJobEvent | null;\n try {\n event = await transitionTerminalJob(this.db, {\n job: snapshot,\n status: 'failed',\n completedAt: recoveredAt,\n expectedStatuses: ['running'],\n expectedWorkerId: job.workerId ?? null,\n clearWorker: !this.config.claimFencing,\n lastError,\n failureKind: 'stale-recovery',\n });\n } catch (persistenceError) {\n // One orphan that cannot be settled must not stop the sweep for the\n // others, or stop this poll from claiming work (#4735).\n this.reportUnpersistedJobWrite(job, 'stale recovery', persistenceError);\n continue;\n }\n if (job.id) {\n this.unsettledJobs.delete(job.id);\n this.recoveryFailuresLogged.delete(job.id);\n }\n if (!event) continue;\n job.status = 'failed';\n job.completedAt = recoveredAt;\n job.lastError = lastError;\n job.workerId = null;\n job.workerHeartbeat = null;\n const error = new Error(lastError);\n this.emitPersistedJobEvent(job, event);\n this.emit('job:failed', job, error);\n }\n }\n\n /**\n * Fail named handler jobs left `pending` past their `run_at` by more than\n * `handlerUnclaimedDeadlineMs` (#5005), failure kind `handler-unclaimed`.\n *\n * Claims skip handler jobs a runner has not registered, so a job no runner\n * serves would wait forever. Every runner runs this sweep from its poll over\n * its own queues and tenant scope, at most once per 1% of the deadline\n * (between one lease tick and 15 min) and\n * {@link HANDLER_UNCLAIMED_SWEEP_LIMIT} rows at a time. It leaves out the\n * handlers this runner registered: it can claim those itself, so an\n * overdue backlog it serves (a saturated queue, a fleet back after a long\n * outage) is run, not failed. The deadline is measured from `run_at`.\n * Residual: while every runner serving a handler is down past the deadline,\n * a runner without it in the same queue still fails its jobs. Races are harmless:\n * each row is failed by one conditional transition (`pending` and still\n * past the deadline), so a concurrent sweeper, a claim or a requeue wins\n * and this one writes nothing. Model jobs are never swept. A failed sweep is\n * a `runner:error` and never stops the poll from claiming.\n */\n private async sweepUnclaimedHandlerJobs(): Promise<void> {\n if (!this.db || !this.collection) return;\n const now = Date.now();\n const deadlineMs = this.config.handlerUnclaimedDeadlineMs;\n // 1% of the deadline, between one lease tick and 15 min: the sweep adds\n // no measurable idle SQL (one SELECT per ~14 min at the 24 h default).\n const interval = Math.max(\n this.config.leaseTickMs,\n Math.min(HANDLER_UNCLAIMED_SWEEP_MAX_INTERVAL_MS, deadlineMs / 100),\n );\n if (now - this.lastUnclaimedSweepAt < interval) return;\n this.lastUnclaimedSweepAt = now;\n\n const cutoff = new Date(now - deadlineMs).toISOString();\n const scope = jobTenantScope(this.config.tenantIds);\n const queuePredicate = this.config.queues.length\n ? ` AND queue IN (${this.config.queues.map(() => '?').join(', ')})`\n : '';\n // Its own handlers are claimed, not swept (at most MAX_JOB_HANDLERS).\n const served = this.handlerNames.map(\n (name) => jobHandlerTarget(name).objectType,\n );\n const servedPredicate = served.length\n ? ` AND object_type NOT IN (${served.map(() => '?').join(', ')})`\n : '';\n let unclaimed: SmrtJob[];\n try {\n // Worker-internal cross-tenant scan, scoped like stale recovery.\n unclaimed = await this.collection.query(\n `SELECT ${SMRT_JOB_PORTABLE_SELECT_COLUMNS}\n FROM _smrt_jobs\n WHERE status = 'pending' AND run_at <= ? AND ${HANDLER_TARGET_SQL}${scope.sql}${queuePredicate}${servedPredicate}\n ORDER BY run_at ASC, id ASC\n LIMIT ?`,\n [\n cutoff,\n ...scope.params,\n ...this.config.queues,\n ...served,\n HANDLER_UNCLAIMED_SWEEP_LIMIT,\n ],\n { allowRawOnTenantScoped: true },\n );\n } catch (error) {\n this.emit('runner:error', error as Error);\n return;\n }\n\n // A full batch may leave more overdue rows: sweep again next poll.\n if (unclaimed.length >= HANDLER_UNCLAIMED_SWEEP_LIMIT) {\n this.lastUnclaimedSweepAt = 0;\n }\n const sweptAt = new Date();\n for (const job of unclaimed) {\n const snapshot = terminalSnapshot(job);\n if (!snapshot) continue;\n const lastError = `Job handler not claimed: no runner registered for ${jobHandlerName(job.objectType)} claimed this job within ${deadlineMs} ms of its run_at.`;\n let event: SmrtJobEvent | null;\n try {\n event = await transitionTerminalJob(this.db, {\n job: snapshot,\n status: 'failed',\n completedAt: sweptAt,\n expectedStatuses: ['pending'],\n expectedRunAtAtOrBefore: cutoff,\n clearWorker: true,\n lastError,\n failureKind: 'handler-unclaimed',\n });\n } catch (error) {\n this.emit('runner:error', error as Error);\n continue;\n }\n if (!event) continue;\n job.status = 'failed';\n job.completedAt = sweptAt;\n job.lastError = lastError;\n this.emitPersistedJobEvent(job, event);\n this.emit('job:unclaimed', job, new Error(lastError));\n }\n }\n\n /**\n * Renew this worker's liveness lease.\n *\n * In Stage 1 this runs on the main event loop, so it provides cross-process\n * detection no weaker than the old per-job heartbeat. Stage 2 moves the\n * renewal to an off-loop worker thread so a synchronous handler can no longer\n * starve it. Same-process correctness never depends on this timer — the\n * in-memory live set covers it.\n */\n private startLeaseRenewal(): void {\n this.leaseTimer = setInterval(async () => {\n try {\n await this.workerCollection?.renewLease(\n this.workerKey,\n this.effectiveLeaseTtlMs,\n this.config.queues,\n );\n } catch {\n // Ignore transient lease-renewal errors; the next tick retries.\n }\n }, this.config.leaseTickMs);\n }\n\n /**\n * Spawn the off-loop liveness thread. It opens its own connection and renews\n * this worker's lease on its own thread (unstarvable by handler CPU). Returns\n * false if the thread can't be resolved or fails to start, so the caller can\n * fall back to main-loop renewal.\n */\n private async startLivenessThread(\n plan: Exclude<LivenessConnectionPlan, { kind: 'none' }>,\n ): Promise<{ ok: true } | { ok: false; reason: string }> {\n if (!this.db) return { ok: false, reason: 'no database' };\n let entry: string;\n try {\n // Resolve by package subpath, not as a sibling of this module: the bundle\n // hoists `runner` into dist/chunks/, so a relative URL would miss.\n entry = (\n import.meta as unknown as { resolve(s: string): string }\n ).resolve('@happyvertical/smrt-jobs/worker-liveness-thread');\n } catch (error) {\n return {\n ok: false,\n reason: `worker entry not resolvable: ${errorText(error)}`,\n };\n }\n\n let worker: Worker;\n try {\n worker = new Worker(new URL(entry), {\n workerData: {\n ...(plan.kind === 'reopen'\n ? {\n url: '',\n reopen: plan.reopen,\n expectedEngine: plan.engine,\n }\n : { url: plan.url, type: plan.type }),\n workerKey: this.workerKey,\n leaseTtlMs: this.effectiveLeaseTtlMs,\n leaseTickMs: this.config.leaseTickMs,\n queues: this.config.queues,\n },\n });\n } catch (error) {\n return {\n ok: false,\n reason: `worker could not be spawned: ${errorText(error)}`,\n };\n }\n const exited = new Promise<void>((resolve) => {\n worker.once('exit', () => resolve());\n });\n\n // Bound the handshake so a hung connect inside the thread (slow/unreachable\n // database) can't stall start() forever — fall back to main-loop renewal.\n let failure = 'thread exited before it was ready';\n const handshake = await new Promise<'ready' | 'failed' | 'timeout'>(\n (resolve) => {\n const onMessage = (message: unknown) => {\n if (message === 'ready') {\n cleanup();\n resolve('ready');\n } else if (\n message &&\n typeof message === 'object' &&\n (message as { type?: string }).type === 'error'\n ) {\n failure = String((message as { message?: unknown }).message);\n cleanup();\n resolve('failed');\n }\n };\n const onFail = (error?: unknown) => {\n if (error instanceof Error) failure = error.message;\n cleanup();\n resolve('failed');\n };\n const cleanup = () => {\n clearTimeout(timer);\n worker.off('message', onMessage);\n worker.off('error', onFail);\n worker.off('exit', onFail);\n };\n const timer = setTimeout(() => {\n cleanup();\n resolve('timeout');\n }, LIVENESS_THREAD_START_TIMEOUT_MS);\n if (typeof timer.unref === 'function') timer.unref();\n worker.on('message', onMessage);\n worker.once('error', onFail);\n worker.once('exit', onFail);\n },\n );\n\n if (handshake === 'timeout') {\n // A hung thread will not exit on its own; terminating is the last resort.\n await worker.terminate().catch(() => {});\n return {\n ok: false,\n reason: `no ready signal within ${LIVENESS_THREAD_START_TIMEOUT_MS} ms`,\n };\n }\n if (handshake === 'failed') {\n // A failed startup leaves the thread nothing to wait on: it exits.\n await retireLivenessWorker(worker, exited);\n return { ok: false, reason: failure };\n }\n\n this.livenessWorker = worker;\n this.livenessWorkerExited = exited;\n // Don't keep the process alive on the liveness thread alone.\n worker.unref();\n // If the thread dies while we're still running, fall back to main-loop\n // renewal so the lease keeps being renewed.\n worker.once('error', () => this.handleLivenessThreadLoss(worker));\n worker.once('exit', () => this.handleLivenessThreadLoss(worker));\n return { ok: true };\n }\n\n private handleLivenessThreadLoss(worker: Worker): void {\n if (this.livenessWorker !== worker) return;\n this.livenessWorker = null;\n this.livenessWorkerExited = null;\n if (this.running && !this.leaseTimer) {\n this.startLeaseRenewal();\n }\n }\n\n /**\n * Stop the liveness thread, if running: ask it to stop, then let it exit on\n * its own (bounded; terminated only if it does not, see\n * {@link retireLivenessWorker}).\n */\n private async stopLivenessThread(): Promise<void> {\n const worker = this.livenessWorker;\n const exited = this.livenessWorkerExited;\n if (!worker || !exited) return;\n this.livenessWorker = null;\n this.livenessWorkerExited = null;\n\n try {\n // The worker may have already exited (it's unref'd and best-effort);\n // postMessage to a dead worker throws ERR_WORKER_NOT_RUNNING.\n worker.postMessage('stop');\n } catch {\n // Nothing to ask it to do; the exit wait below returns at once.\n }\n await retireLivenessWorker(worker, exited);\n }\n\n /**\n * Per-job heartbeat loop — telemetry only (\"last activity\" for the UI). It no\n * longer gates recovery (that is the worker lease), so a blocked loop missing\n * a heartbeat is harmless.\n */\n private startHeartbeat(): void {\n this.heartbeatTimer = setInterval(async () => {\n if (!this.db) return;\n const jobIds = [...this.activeJobs.keys()];\n if (jobIds.length === 0) return;\n const placeholders = jobIds.map(() => '?').join(', ');\n try {\n await this.db.query(\n `UPDATE _smrt_jobs\n SET worker_heartbeat = ?\n WHERE status = 'running'\n AND id IN (${placeholders})`,\n new Date().toISOString(),\n ...jobIds,\n );\n } catch {\n // Telemetry is best-effort.\n }\n }, this.config.heartbeatInterval);\n }\n\n /**\n * Wait for active jobs to complete with timeout\n */\n private async waitForActiveJobs(): Promise<void> {\n // A claim is not in activeJobs yet. Keep the lease while it drains, using\n // the same shutdown deadline as handlers rather than an unbounded await.\n if (this.activeJobs.size === 0 && !this.pollPromise) return;\n\n return new Promise((resolve) => {\n const checkInterval = setInterval(() => {\n if (this.activeJobs.size === 0 && !this.pollPromise) {\n clearInterval(checkInterval);\n clearTimeout(timeout);\n resolve();\n }\n }, 100);\n\n const timeout = setTimeout(() => {\n clearInterval(checkInterval);\n this.logger.warn(\n `Shutdown timeout: ${this.activeJobs.size} jobs still active`,\n );\n resolve();\n }, this.config.shutdownTimeout);\n });\n }\n}\n\n/**\n * Create a TaskRunner instance\n */\nexport function createTaskRunner(config?: TaskRunnerConfig): TaskRunner {\n return new TaskRunner(config);\n}\n\nexport default TaskRunner;\n"],"mappings":";;;;;;;;;;AAOA,eAAe,wBAAwB,KAAK,MAAM,05pDAA463D,CAAC;;;ACwBx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