@multiplier-labs/stepflow 0.3.3 → 0.3.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (69) hide show
  1. package/.codekin/reports/code-review/2026-04-11_code-review-daily.md +146 -0
  2. package/.codekin/reports/code-review/2026-04-13_code-review-daily.md +74 -0
  3. package/.codekin/reports/comments/2026-04-11_comment-assessment.md +161 -0
  4. package/.codekin/reports/comments/2026-04-14_comment-assessment.md +34 -0
  5. package/.codekin/reports/complexity/2026-04-11_complexity-report.md +152 -0
  6. package/.codekin/reports/complexity/2026-04-14_complexity-report.md +34 -0
  7. package/.codekin/reports/dependencies/2026-04-11_dependency-health.md +93 -0
  8. package/.codekin/reports/docs-audit/2026-04-11_docs-audit.md +138 -0
  9. package/.codekin/reports/docs-audit/2026-04-13_docs-audit.md +121 -0
  10. package/.codekin/reports/security/2026-04-11_security-audit.md +297 -0
  11. package/.github/workflows/publish.yml +6 -0
  12. package/dist/{chunk-4VOKMGP6.js → chunk-5XJBAPXF.js} +517 -522
  13. package/dist/chunk-5XJBAPXF.js.map +1 -0
  14. package/dist/{chunk-KHTUWLVZ.js → chunk-FMPJBK2N.js} +55 -10
  15. package/dist/chunk-FMPJBK2N.js.map +1 -0
  16. package/dist/{chunk-ML35PIHX.js → chunk-JPXPB7U5.js} +52 -2
  17. package/dist/chunk-JPXPB7U5.js.map +1 -0
  18. package/dist/{chunk-GYPNJBDP.js → chunk-U3PCVK6O.js} +266 -47
  19. package/dist/chunk-U3PCVK6O.js.map +1 -0
  20. package/dist/events/index.d.ts +56 -3
  21. package/dist/events/index.js +1 -1
  22. package/dist/{index-Dzr437iW.d.ts → index-Cd0IZ40L.d.ts} +50 -11
  23. package/dist/index.d.ts +2 -12
  24. package/dist/index.js +764 -485
  25. package/dist/index.js.map +1 -1
  26. package/dist/scheduler/index.d.ts +1 -1
  27. package/dist/scheduler/index.js +2 -2
  28. package/dist/storage/index.d.ts +313 -47
  29. package/dist/storage/index.js +4 -2
  30. package/docs/stepflow-api-reference.md +3 -1
  31. package/package.json +7 -4
  32. package/src/core/engine/concurrency.ts +229 -0
  33. package/src/core/engine/lifecycle.ts +176 -0
  34. package/src/core/engine.test.ts +70 -0
  35. package/src/core/engine.ts +91 -185
  36. package/src/core/orchestrator/persistence.ts +165 -0
  37. package/src/core/orchestrator/plan-resolution.ts +140 -0
  38. package/src/core/orchestrator/state-transitions.ts +109 -0
  39. package/src/core/orchestrator/step-runner.ts +427 -0
  40. package/src/core/orchestrator.ts +40 -359
  41. package/src/events/webhook.test.ts +292 -0
  42. package/src/events/webhook.ts +320 -77
  43. package/src/planning/evaluate-condition.test.ts +153 -0
  44. package/src/planning/evaluate-condition.ts +105 -0
  45. package/src/planning/planner.ts +1 -83
  46. package/src/planning/registry.ts +3 -85
  47. package/src/scheduler/cron.test.ts +9 -1
  48. package/src/scheduler/cron.ts +26 -2
  49. package/src/scheduler/postgres-persistence.ts +27 -15
  50. package/src/scheduler/sqlite-persistence.ts +28 -3
  51. package/src/storage/postgres-core.ts +550 -0
  52. package/src/storage/postgres-migration.test.ts +69 -0
  53. package/src/storage/postgres-transaction-pagination.test.ts +107 -0
  54. package/src/storage/postgres.ts +171 -690
  55. package/src/storage/sqlite-core.ts +151 -0
  56. package/src/storage/sqlite.test.ts +177 -1
  57. package/src/storage/sqlite.ts +183 -93
  58. package/src/utils/index.ts +2 -0
  59. package/src/utils/pinned-fetch.test.ts +84 -0
  60. package/src/utils/pinned-fetch.ts +118 -0
  61. package/src/utils/postgres-deps.ts +16 -0
  62. package/src/utils/safe-json.test.ts +166 -0
  63. package/src/utils/safe-json.ts +107 -0
  64. package/src/utils/webhook-signature.test.ts +111 -0
  65. package/src/utils/webhook-signature.ts +74 -0
  66. package/dist/chunk-4VOKMGP6.js.map +0 -1
  67. package/dist/chunk-GYPNJBDP.js.map +0 -1
  68. package/dist/chunk-KHTUWLVZ.js.map +0 -1
  69. package/dist/chunk-ML35PIHX.js.map +0 -1
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/storage/memory.ts","../src/storage/sqlite-core.ts","../src/storage/sqlite.ts","../src/storage/postgres-core.ts","../src/storage/postgres.ts"],"sourcesContent":["/**\n * In-memory storage adapter for development and testing.\n * All data is lost when the process exits.\n *\n * NOTE: This adapter is intended for development and testing only. It stores\n * all state in-process with no persistence or multi-process safety guarantees.\n */\n\nimport { generateId } from '../utils/id';\nimport type {\n StorageAdapter,\n WorkflowRunRecord,\n WorkflowRunStepRecord,\n WorkflowEventRecord,\n ListRunsOptions,\n ListEventsOptions,\n PaginatedResult,\n} from './types';\n\n/**\n * In-memory implementation of StorageAdapter.\n * Useful for development, testing, and lightweight deployments.\n *\n * @example\n * ```typescript\n * import { WorkflowEngine } from 'stepflow';\n * import { MemoryStorageAdapter } from 'stepflow/storage';\n *\n * const storage = new MemoryStorageAdapter();\n * const engine = new WorkflowEngine({ storage });\n * ```\n */\nexport class MemoryStorageAdapter implements StorageAdapter {\n private runs = new Map<string, WorkflowRunRecord>();\n private steps = new Map<string, WorkflowRunStepRecord>();\n private events = new Map<string, WorkflowEventRecord>();\n\n // ============================================================================\n // Run Operations\n // ============================================================================\n\n /** Create and persist a new workflow run record. */\n async createRun(run: Omit<WorkflowRunRecord, 'id' | 'createdAt'>): Promise<WorkflowRunRecord> {\n const record: WorkflowRunRecord = {\n ...run,\n id: generateId(),\n createdAt: new Date(),\n };\n this.runs.set(record.id, record);\n return record;\n }\n\n /** Retrieve a workflow run by ID, or null if not found. */\n async getRun(runId: string): Promise<WorkflowRunRecord | null> {\n return this.runs.get(runId) ?? null;\n }\n\n /** Apply partial updates to an existing workflow run. No-op if the run does not exist. */\n async updateRun(runId: string, updates: Partial<WorkflowRunRecord>): Promise<void> {\n const run = this.runs.get(runId);\n if (run) {\n Object.assign(run, updates);\n }\n }\n\n /** List workflow runs with optional filtering, sorting, and pagination. */\n async listRuns(options: ListRunsOptions = {}): Promise<PaginatedResult<WorkflowRunRecord>> {\n let items = Array.from(this.runs.values());\n\n // Filter by kind\n if (options.kind) {\n items = items.filter(r => r.kind === options.kind);\n }\n\n // Filter by status\n if (options.status) {\n const statuses = Array.isArray(options.status) ? options.status : [options.status];\n items = items.filter(r => statuses.includes(r.status));\n }\n\n // Filter by parentRunId\n if (options.parentRunId !== undefined) {\n items = items.filter(r => r.parentRunId === options.parentRunId);\n }\n\n // Sort\n const orderBy = options.orderBy ?? 'createdAt';\n const direction = options.orderDirection ?? 'desc';\n items.sort((a, b) => {\n const aVal = a[orderBy]?.getTime() ?? 0;\n const bVal = b[orderBy]?.getTime() ?? 0;\n return direction === 'asc' ? aVal - bVal : bVal - aVal;\n });\n\n const total = items.length;\n const offset = options.offset ?? 0;\n const limit = options.limit ?? 50;\n\n items = items.slice(offset, offset + limit);\n\n return { items, total, limit, offset };\n }\n\n // ============================================================================\n // Step Operations\n // ============================================================================\n\n /** Create and persist a new step execution record. */\n async createStep(step: Omit<WorkflowRunStepRecord, 'id'>): Promise<WorkflowRunStepRecord> {\n const record: WorkflowRunStepRecord = {\n ...step,\n id: generateId(),\n };\n this.steps.set(record.id, record);\n return record;\n }\n\n /** Retrieve a step record by ID, or null if not found. */\n async getStep(stepId: string): Promise<WorkflowRunStepRecord | null> {\n return this.steps.get(stepId) ?? null;\n }\n\n /** Apply partial updates to an existing step record. No-op if the step does not exist. */\n async updateStep(stepId: string, updates: Partial<WorkflowRunStepRecord>): Promise<void> {\n const step = this.steps.get(stepId);\n if (step) {\n Object.assign(step, updates);\n }\n }\n\n /** Retrieve all step records for a workflow run, ordered by start time ascending. */\n async getStepsForRun(runId: string): Promise<WorkflowRunStepRecord[]> {\n return Array.from(this.steps.values())\n .filter(s => s.runId === runId)\n .sort((a, b) => (a.startedAt?.getTime() ?? 0) - (b.startedAt?.getTime() ?? 0));\n }\n\n // ============================================================================\n // Event Operations\n // ============================================================================\n\n /** Persist a workflow event record. */\n async saveEvent(event: Omit<WorkflowEventRecord, 'id'>): Promise<void> {\n const record: WorkflowEventRecord = {\n ...event,\n id: generateId(),\n };\n this.events.set(record.id, record);\n }\n\n /** Retrieve events for a workflow run with optional filtering and pagination. */\n async getEventsForRun(runId: string, options: ListEventsOptions = {}): Promise<WorkflowEventRecord[]> {\n let items = Array.from(this.events.values()).filter(e => e.runId === runId);\n\n // Filter by step\n if (options.stepKey) {\n items = items.filter(e => e.stepKey === options.stepKey);\n }\n\n // Filter by level\n if (options.level) {\n items = items.filter(e => e.level === options.level);\n }\n\n // Sort by timestamp\n items.sort((a, b) => a.timestamp.getTime() - b.timestamp.getTime());\n\n // Apply pagination\n const offset = options.offset ?? 0;\n const limit = options.limit ?? 100;\n\n return items.slice(offset, offset + limit);\n }\n\n // ============================================================================\n // Optional Operations\n // ============================================================================\n\n /** Delete runs (and their associated steps and events) created before the given date. Returns the number of deleted runs. */\n async deleteOldRuns(olderThan: Date): Promise<number> {\n let deleted = 0;\n for (const [id, run] of this.runs) {\n if (run.createdAt < olderThan) {\n // Delete associated steps\n for (const [stepId, step] of this.steps) {\n if (step.runId === id) {\n this.steps.delete(stepId);\n }\n }\n // Delete associated events\n for (const [eventId, event] of this.events) {\n if (event.runId === id) {\n this.events.delete(eventId);\n }\n }\n // Delete run\n this.runs.delete(id);\n deleted++;\n }\n }\n return deleted;\n }\n\n // ============================================================================\n // Testing Utilities\n // ============================================================================\n\n /**\n * Clear all stored data. Useful for testing.\n */\n clear(): void {\n this.runs.clear();\n this.steps.clear();\n this.events.clear();\n }\n\n /**\n * Get counts of stored records. Useful for testing.\n */\n getStats(): { runs: number; steps: number; events: number } {\n return {\n runs: this.runs.size,\n steps: this.steps.size,\n events: this.events.size,\n };\n }\n}\n","/**\n * Shared core for the SQLite storage adapter.\n *\n * Mirrors the structure introduced for Postgres in `postgres-core.ts` (PR #50)\n * so all storage adapters expose row mappers and types in the same shape.\n *\n * The SQLite case is simpler than Postgres: there is only one adapter class\n * (`SQLiteStorageAdapter`), with no transaction-scoped twin. So this module\n * carries only the *pure* portion of the postgres-core split:\n *\n * - SQLite row type interfaces for the three core tables\n * (`workflow_runs`, `workflow_run_steps`, `workflow_events`).\n * - Pure row mappers (`mapRunRow`, `mapStepRow`, `mapEventRow`) that take\n * a `MapperContext = { component, logger }` and route every JSON-column\n * parse through the shared `safeParseField` / `safeParseOptionalField`\n * helpers. Corruption is reported via the configured logger with safe\n * metadata only — the raw value is never logged (audit M2 / L3, PR #52).\n *\n * No abstract base class is needed: the adapter class binds the prepared\n * statements + better-sqlite3 connection in one place and would gain nothing\n * from inheritance. The mappers and row types are extracted purely so they\n * are reusable, testable, and consistent with `postgres-core.ts`.\n */\n\nimport {\n safeParseField as sharedSafeParseField,\n safeParseOptionalField as sharedSafeParseOptionalField,\n type MapperContext,\n type SafeJsonParseContext,\n} from '../utils/safe-json';\nimport type {\n WorkflowRunRecord,\n WorkflowRunStepRecord,\n WorkflowEventRecord,\n} from './types';\nimport type { RunStatus, StepStatus, WorkflowError } from '../core/types';\n\n/**\n * Re-export the shared `MapperContext` so callers can `import { MapperContext }`\n * from either storage core module.\n */\nexport type { MapperContext };\n\n// ============================================================================\n// SQLite row types\n// ============================================================================\n//\n// SQLite stores everything as text/integer/real, so timestamps come back as\n// ISO-8601 strings (the adapter writes them via `Date.prototype.toISOString`)\n// and JSON columns come back as the original `JSON.stringify` output. The\n// mappers below convert each row back to the public record shape.\n\n/** Row shape for the `workflow_runs` table. */\nexport interface SQLiteRunRow {\n id: string;\n kind: string;\n status: string;\n parent_run_id: string | null;\n input_json: string;\n metadata_json: string;\n context_json: string;\n completed_steps_json: string | null;\n error_json: string | null;\n created_at: string;\n started_at: string | null;\n finished_at: string | null;\n}\n\n/** Row shape for the `workflow_run_steps` table. */\nexport interface SQLiteStepRow {\n id: string;\n run_id: string;\n step_key: string;\n step_name: string;\n status: string;\n attempt: number;\n result_json: string | null;\n error_json: string | null;\n started_at: string | null;\n finished_at: string | null;\n}\n\n/** Row shape for the `workflow_events` table. */\nexport interface SQLiteEventRow {\n id: string;\n run_id: string;\n step_key: string | null;\n event_type: string;\n level: string;\n payload_json: string | null;\n timestamp: string;\n}\n\n// ============================================================================\n// Row mappers (pure)\n// ============================================================================\n//\n// Adapters supply a `MapperContext` ({ component, logger }); each helper\n// extends it with the row id and column being parsed so a structured log\n// emitted on corruption identifies the bad row. The raw value is never\n// logged — see `src/utils/safe-json.ts`.\n\n/** Map a `workflow_runs` row to the public `WorkflowRunRecord` shape. */\nexport function mapRunRow(row: SQLiteRunRow, ctx: MapperContext): WorkflowRunRecord {\n const fieldCtx = (column: string): SafeJsonParseContext => ({ ...ctx, rowId: row.id, column });\n return {\n id: row.id,\n kind: row.kind,\n status: row.status as RunStatus,\n parentRunId: row.parent_run_id ?? undefined,\n input: sharedSafeParseField(row.input_json, {}, fieldCtx('input_json')) as Record<string, unknown>,\n metadata: sharedSafeParseField(row.metadata_json, {}, fieldCtx('metadata_json')) as Record<string, unknown>,\n context: sharedSafeParseField(row.context_json, {}, fieldCtx('context_json')) as Record<string, unknown>,\n completedSteps: sharedSafeParseOptionalField(row.completed_steps_json, fieldCtx('completed_steps_json')) as string[] | undefined,\n error: sharedSafeParseOptionalField(row.error_json, fieldCtx('error_json')) as WorkflowError | undefined,\n createdAt: new Date(row.created_at),\n startedAt: row.started_at ? new Date(row.started_at) : undefined,\n finishedAt: row.finished_at ? new Date(row.finished_at) : undefined,\n };\n}\n\n/** Map a `workflow_run_steps` row to the public `WorkflowRunStepRecord` shape. */\nexport function mapStepRow(row: SQLiteStepRow, ctx: MapperContext): WorkflowRunStepRecord {\n const fieldCtx = (column: string): SafeJsonParseContext => ({ ...ctx, rowId: row.id, column });\n return {\n id: row.id,\n runId: row.run_id,\n stepKey: row.step_key,\n stepName: row.step_name,\n status: row.status as StepStatus,\n attempt: row.attempt,\n result: sharedSafeParseOptionalField(row.result_json, fieldCtx('result_json')),\n error: sharedSafeParseOptionalField(row.error_json, fieldCtx('error_json')) as WorkflowError | undefined,\n startedAt: row.started_at ? new Date(row.started_at) : undefined,\n finishedAt: row.finished_at ? new Date(row.finished_at) : undefined,\n };\n}\n\n/** Map a `workflow_events` row to the public `WorkflowEventRecord` shape. */\nexport function mapEventRow(row: SQLiteEventRow, ctx: MapperContext): WorkflowEventRecord {\n const fieldCtx: SafeJsonParseContext = { ...ctx, rowId: row.id, column: 'payload_json' };\n return {\n id: row.id,\n runId: row.run_id,\n stepKey: row.step_key ?? undefined,\n eventType: row.event_type,\n level: row.level as 'info' | 'warn' | 'error',\n payload: sharedSafeParseOptionalField(row.payload_json, fieldCtx),\n timestamp: new Date(row.timestamp),\n };\n}\n","/**\n * SQLite storage adapter using better-sqlite3.\n *\n * Provides durable persistence for workflow runs, steps, and events.\n *\n * ## Module layout\n *\n * - `SQLiteStorageAdapter` (this file) owns the better-sqlite3 connection,\n * the prepared-statement cache, and every method on `StorageAdapter`. It\n * is the only adapter class — unlike the Postgres adapter there is no\n * transaction-scoped twin, so no abstract CRUD base class is required.\n *\n * - `sqlite-core.ts` holds the pure row-type interfaces and row mappers\n * (`mapRunRow`, `mapStepRow`, `mapEventRow`). The mappers route every\n * JSON-column parse through `safeParseField` / `safeParseOptionalField`\n * in `src/utils/safe-json.ts`, sharing the corruption-counter +\n * structured-warn behavior with the Postgres core (audit M2 / L3,\n * PR #52). The split mirrors `postgres-core.ts` so both adapters\n * expose mappers in the same shape.\n */\n\nimport type Database from 'better-sqlite3';\nimport { generateId } from '../utils/id';\nimport type {\n StorageAdapter,\n WorkflowRunRecord,\n WorkflowRunStepRecord,\n WorkflowEventRecord,\n ListRunsOptions,\n ListEventsOptions,\n PaginatedResult,\n} from './types';\nimport type { Logger } from '../core/types';\nimport { sanitizeErrorForStorage } from '../utils/logger';\nimport type { MapperContext } from '../utils/safe-json';\nimport {\n mapRunRow,\n mapStepRow,\n mapEventRow,\n type SQLiteRunRow,\n type SQLiteStepRow,\n type SQLiteEventRow,\n} from './sqlite-core';\n\n// ============================================================================\n// Schema SQL\n// ============================================================================\n\n/**\n * SQL statements to create the workflow tables.\n * These create the workflow tables in your database.\n */\nconst CREATE_TABLES_SQL = `\n-- Workflow runs table\nCREATE TABLE IF NOT EXISTS workflow_runs (\n id TEXT PRIMARY KEY,\n kind TEXT NOT NULL,\n status TEXT NOT NULL,\n parent_run_id TEXT,\n input_json TEXT NOT NULL,\n metadata_json TEXT NOT NULL,\n context_json TEXT NOT NULL,\n completed_steps_json TEXT,\n error_json TEXT,\n created_at TEXT NOT NULL,\n started_at TEXT,\n finished_at TEXT\n);\n\nCREATE INDEX IF NOT EXISTS idx_workflow_runs_kind_status ON workflow_runs(kind, status);\nCREATE INDEX IF NOT EXISTS idx_workflow_runs_parent ON workflow_runs(parent_run_id);\nCREATE INDEX IF NOT EXISTS idx_workflow_runs_created ON workflow_runs(created_at);\nCREATE INDEX IF NOT EXISTS idx_workflow_runs_status ON workflow_runs(status);\n\n-- Workflow run steps table\nCREATE TABLE IF NOT EXISTS workflow_run_steps (\n id TEXT PRIMARY KEY,\n run_id TEXT NOT NULL,\n step_key TEXT NOT NULL,\n step_name TEXT,\n status TEXT NOT NULL,\n attempt INTEGER NOT NULL DEFAULT 1,\n result_json TEXT,\n error_json TEXT,\n started_at TEXT,\n finished_at TEXT,\n FOREIGN KEY (run_id) REFERENCES workflow_runs(id) ON DELETE CASCADE\n);\n\nCREATE INDEX IF NOT EXISTS idx_workflow_run_steps_run ON workflow_run_steps(run_id);\nCREATE INDEX IF NOT EXISTS idx_workflow_run_steps_run_key ON workflow_run_steps(run_id, step_key);\n\n-- Workflow events table\nCREATE TABLE IF NOT EXISTS workflow_events (\n id TEXT PRIMARY KEY,\n run_id TEXT NOT NULL,\n step_key TEXT,\n event_type TEXT NOT NULL,\n level TEXT NOT NULL,\n payload_json TEXT,\n timestamp TEXT NOT NULL,\n FOREIGN KEY (run_id) REFERENCES workflow_runs(id) ON DELETE CASCADE\n);\n\nCREATE INDEX IF NOT EXISTS idx_workflow_events_run ON workflow_events(run_id);\nCREATE INDEX IF NOT EXISTS idx_workflow_events_run_ts ON workflow_events(run_id, timestamp);\n`;\n\n/**\n * Columns added to {@link CREATE_TABLES_SQL} after the initial schema, expressed\n * as `ALTER TABLE ADD COLUMN` migrations. SQLite's `CREATE TABLE IF NOT EXISTS`\n * does not reconcile column lists against existing tables, so a deploy that ran\n * an older version of this adapter will be missing any column added later. The\n * adapter applies these on startup so existing databases stay usable across\n * upgrades.\n *\n * Append-only: SQLite does not support DROP COLUMN or general ALTER COLUMN, so\n * removing or changing an entry here would break upgrades from older versions.\n * Only add new entries when a column is added to {@link CREATE_TABLES_SQL}.\n */\nconst SCHEMA_MIGRATIONS: ReadonlyArray<{ table: string; column: string; type: string }> = [\n { table: 'workflow_runs', column: 'completed_steps_json', type: 'TEXT' },\n];\n\n// ============================================================================\n// Configuration\n// ============================================================================\n\n/**\n * Configuration options for the SQLite storage adapter.\n */\nexport interface SQLiteStorageConfig {\n /**\n * The better-sqlite3 database instance.\n * Can be an in-memory database (`:memory:`) or a file path.\n */\n db: Database.Database;\n\n /**\n * Whether to automatically create tables on initialization.\n * Default: true\n */\n autoCreateTables?: boolean;\n\n /**\n * @deprecated This option is not currently supported and will be ignored.\n * Table names are always prefixed with 'workflow_'.\n */\n tablePrefix?: string;\n\n /**\n * Optional structured logger used to surface JSON corruption events.\n * Without one, parse failures still increment the corruption counter\n * exposed via `getJsonParseCorruptionCount()` but produce no log output.\n */\n logger?: Logger;\n}\n\n// ============================================================================\n// Helpers\n// ============================================================================\n\n/**\n * better-sqlite3 raises `SqliteError { code: 'SQLITE_ERROR', message:\n * 'duplicate column name: <name>' }` when an `ALTER TABLE ADD COLUMN` targets\n * a column that already exists. Treat that as a benign no-op so concurrent\n * startups (or any race between the {@link runMigrations} existence check and\n * the ALTER) don't crash. All other errors propagate.\n */\nfunction isDuplicateColumnError(err: unknown): boolean {\n if (!err || typeof err !== 'object') return false;\n const code = (err as { code?: unknown }).code;\n const message = (err as { message?: unknown }).message;\n return (\n code === 'SQLITE_ERROR' &&\n typeof message === 'string' &&\n message.toLowerCase().includes('duplicate column name')\n );\n}\n\n/**\n * Resolve to `true` if `p` settles within a few microtask ticks of being\n * inspected, otherwise `false`. Used by the deprecated async `transaction()`\n * to detect callbacks that suspend on real async I/O — by the time we ask,\n * the synchronous COMMIT has already run, so a still-pending promise means\n * any post-await operations land outside the transaction.\n */\nasync function isPromiseSettled(p: Promise<unknown>): Promise<boolean> {\n let settled = false;\n p.then(\n () => {\n settled = true;\n },\n () => {\n settled = true;\n }\n );\n // Drain a handful of microtask ticks. `await Promise.resolve()` callbacks\n // and other already-resolved continuations finish in 1-2 ticks; anything\n // still pending after this is doing real async I/O (timers, network, etc.).\n for (let i = 0; i < 5 && !settled; i++) {\n await Promise.resolve();\n }\n return settled;\n}\n\n// ============================================================================\n// SQLite Storage Adapter\n// ============================================================================\n\n/**\n * SQLite implementation of StorageAdapter using better-sqlite3.\n *\n * Features:\n * - Synchronous operations (better-sqlite3 is sync by design)\n * - Automatic table creation\n * - Transaction support\n * - Customizable table prefix\n *\n * @example\n * ```typescript\n * import Database from 'better-sqlite3';\n * import { SQLiteStorageAdapter } from 'stepflow/storage';\n *\n * const db = new Database('./workflows.db');\n * const storage = new SQLiteStorageAdapter({ db });\n *\n * const engine = new WorkflowEngine({ storage });\n * ```\n */\nexport class SQLiteStorageAdapter implements StorageAdapter {\n private db: Database.Database;\n private prefix: string;\n private logger: Logger | undefined;\n\n // Prepared statements (cached for performance)\n private stmts: {\n insertRun: Database.Statement;\n getRun: Database.Statement;\n updateRun: Database.Statement;\n listRuns: Database.Statement;\n countRuns: Database.Statement;\n insertStep: Database.Statement;\n getStep: Database.Statement;\n updateStep: Database.Statement;\n getStepsForRun: Database.Statement;\n insertEvent: Database.Statement;\n getEventsForRun: Database.Statement;\n deleteOldRuns: Database.Statement;\n deleteStepsForRuns: Database.Statement;\n deleteEventsForRuns: Database.Statement;\n getInterruptedRuns: Database.Statement;\n getLastCompletedStep: Database.Statement;\n } | null = null;\n\n constructor(config: SQLiteStorageConfig) {\n this.db = config.db;\n this.prefix = config.tablePrefix ?? 'workflow';\n this.logger = config.logger;\n\n // Enable foreign keys\n this.db.pragma('foreign_keys = ON');\n\n // Create tables if needed\n if (config.autoCreateTables !== false) {\n this.createTables();\n }\n\n // Always reconcile column-level migrations: the prepared statements below\n // reference the latest schema, so an adapter sitting on top of an older\n // table layout (e.g., a database created by a previous version, or a\n // caller-managed schema with `autoCreateTables: false` that has not been\n // hand-upgraded) would crash on the first INSERT/SELECT. Migrations are\n // idempotent and skip tables that don't exist.\n this.runMigrations();\n\n // Prepare statements\n this.prepareStatements();\n }\n\n /**\n * Create the workflow tables if they don't exist.\n */\n private createTables(): void {\n this.db.exec(CREATE_TABLES_SQL);\n }\n\n /**\n * Apply additive schema migrations to existing tables.\n *\n * `CREATE TABLE IF NOT EXISTS` is a no-op when the table already exists, so\n * any column added to {@link CREATE_TABLES_SQL} after the initial schema is\n * silently absent on databases created by older versions of this adapter.\n * Without this step, the first INSERT/SELECT crashes with\n * `SqliteError: table X has no column named Y`. This mirrors the\n * `ALTER TABLE ADD COLUMN IF NOT EXISTS` block in `postgres.ts`'s\n * `createTables()`.\n *\n * For each entry in {@link SCHEMA_MIGRATIONS}: if the table exists and the\n * column does not, run `ALTER TABLE ADD COLUMN`. The ALTER is wrapped in a\n * try/catch that tolerates `duplicate column` errors so concurrent startups\n * (or any race between the existence check and the ALTER) do not crash.\n * Other SQLite errors propagate.\n */\n private runMigrations(): void {\n for (const { table, column, type } of SCHEMA_MIGRATIONS) {\n const tableInfo = this.db.prepare(`PRAGMA table_info(${table})`).all() as Array<{ name: string }>;\n // PRAGMA table_info on a missing table returns []; CREATE TABLE handles that case.\n if (tableInfo.length === 0) continue;\n if (tableInfo.some((col) => col.name === column)) continue;\n\n try {\n this.db.exec(`ALTER TABLE ${table} ADD COLUMN ${column} ${type}`);\n } catch (err) {\n if (isDuplicateColumnError(err)) continue;\n throw err;\n }\n }\n }\n\n /**\n * Prepare all SQL statements for better performance.\n */\n private prepareStatements(): void {\n this.stmts = {\n insertRun: this.db.prepare(`\n INSERT INTO workflow_runs (id, kind, status, parent_run_id, input_json, metadata_json, context_json, completed_steps_json, error_json, created_at, started_at, finished_at)\n VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)\n `),\n getRun: this.db.prepare(`\n SELECT * FROM workflow_runs WHERE id = ?\n `),\n updateRun: this.db.prepare(`\n UPDATE workflow_runs\n SET status = COALESCE(?, status),\n context_json = COALESCE(?, context_json),\n completed_steps_json = COALESCE(?, completed_steps_json),\n error_json = COALESCE(?, error_json),\n started_at = COALESCE(?, started_at),\n finished_at = COALESCE(?, finished_at)\n WHERE id = ?\n `),\n // json_each() is a SQLite table-valued function that expands a JSON array into rows.\n // We use it here to support filtering by multiple statuses in a single prepared statement:\n // the caller passes a JSON array like '[\"running\",\"failed\"]', and json_each unpacks it\n // so the IN clause can match against each value. When status is NULL, the entire\n // condition is bypassed via the (? IS NULL OR ...) guard.\n listRuns: this.db.prepare(`\n SELECT * FROM workflow_runs\n WHERE (? IS NULL OR kind = ?)\n AND (? IS NULL OR status IN (SELECT value FROM json_each(?)))\n AND (? IS NULL OR parent_run_id = ?)\n ORDER BY created_at DESC\n LIMIT ? OFFSET ?\n `),\n countRuns: this.db.prepare(`\n SELECT COUNT(*) as count FROM workflow_runs\n WHERE (? IS NULL OR kind = ?)\n AND (? IS NULL OR status IN (SELECT value FROM json_each(?)))\n AND (? IS NULL OR parent_run_id = ?)\n `),\n insertStep: this.db.prepare(`\n INSERT INTO workflow_run_steps (id, run_id, step_key, step_name, status, attempt, result_json, error_json, started_at, finished_at)\n VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)\n `),\n getStep: this.db.prepare(`\n SELECT * FROM workflow_run_steps WHERE id = ?\n `),\n updateStep: this.db.prepare(`\n UPDATE workflow_run_steps\n SET status = COALESCE(?, status),\n attempt = COALESCE(?, attempt),\n result_json = COALESCE(?, result_json),\n error_json = COALESCE(?, error_json),\n finished_at = COALESCE(?, finished_at)\n WHERE id = ?\n `),\n getStepsForRun: this.db.prepare(`\n SELECT * FROM workflow_run_steps WHERE run_id = ? ORDER BY started_at ASC\n `),\n insertEvent: this.db.prepare(`\n INSERT INTO workflow_events (id, run_id, step_key, event_type, level, payload_json, timestamp)\n VALUES (?, ?, ?, ?, ?, ?, ?)\n `),\n getEventsForRun: this.db.prepare(`\n SELECT * FROM workflow_events\n WHERE run_id = ?\n AND (? IS NULL OR step_key = ?)\n AND (? IS NULL OR level = ?)\n ORDER BY timestamp ASC\n LIMIT ? OFFSET ?\n `),\n deleteOldRuns: this.db.prepare(`\n DELETE FROM workflow_runs WHERE created_at < ?\n `),\n deleteStepsForRuns: this.db.prepare(`\n DELETE FROM workflow_run_steps WHERE run_id IN (SELECT id FROM workflow_runs WHERE created_at < ?)\n `),\n deleteEventsForRuns: this.db.prepare(`\n DELETE FROM workflow_events WHERE run_id IN (SELECT id FROM workflow_runs WHERE created_at < ?)\n `),\n getInterruptedRuns: this.db.prepare(`\n SELECT * FROM workflow_runs\n WHERE status IN ('queued', 'running')\n ORDER BY created_at ASC\n `),\n getLastCompletedStep: this.db.prepare(`\n SELECT * FROM workflow_run_steps\n WHERE run_id = ? AND status = 'succeeded'\n ORDER BY finished_at DESC\n LIMIT 1\n `),\n };\n }\n\n // ============================================================================\n // Run Operations\n // ============================================================================\n\n async createRun(run: Omit<WorkflowRunRecord, 'id' | 'createdAt'>): Promise<WorkflowRunRecord> {\n const id = generateId();\n const createdAt = new Date();\n\n this.stmts!.insertRun.run(\n id,\n run.kind,\n run.status,\n run.parentRunId ?? null,\n JSON.stringify(run.input),\n JSON.stringify(run.metadata),\n JSON.stringify(run.context),\n run.completedSteps ? JSON.stringify(run.completedSteps) : null,\n run.error ? JSON.stringify(sanitizeErrorForStorage(run.error)) : null,\n createdAt.toISOString(),\n run.startedAt?.toISOString() ?? null,\n run.finishedAt?.toISOString() ?? null\n );\n\n return {\n ...run,\n id,\n createdAt,\n };\n }\n\n async getRun(runId: string): Promise<WorkflowRunRecord | null> {\n const row = this.stmts!.getRun.get(runId) as SQLiteRunRow | undefined;\n return row ? mapRunRow(row, this.mapperCtx) : null;\n }\n\n async updateRun(runId: string, updates: Partial<WorkflowRunRecord>): Promise<void> {\n this.stmts!.updateRun.run(\n updates.status ?? null,\n updates.context ? JSON.stringify(updates.context) : null,\n updates.completedSteps ? JSON.stringify(updates.completedSteps) : null,\n updates.error ? JSON.stringify(sanitizeErrorForStorage(updates.error)) : null,\n updates.startedAt?.toISOString() ?? null,\n updates.finishedAt?.toISOString() ?? null,\n runId\n );\n }\n\n async listRuns(options: ListRunsOptions = {}): Promise<PaginatedResult<WorkflowRunRecord>> {\n const limit = options.limit ?? 50;\n const offset = options.offset ?? 0;\n const kind = options.kind ?? null;\n const status = options.status ?? null;\n const statusJson = status ? JSON.stringify(Array.isArray(status) ? status : [status]) : null;\n const parentRunId = options.parentRunId ?? null;\n\n const rows = this.stmts!.listRuns.all(\n kind, kind,\n statusJson, statusJson,\n parentRunId, parentRunId,\n limit, offset\n ) as SQLiteRunRow[];\n\n const countResult = this.stmts!.countRuns.get(\n kind, kind,\n statusJson, statusJson,\n parentRunId, parentRunId\n ) as { count: number };\n\n return {\n items: rows.map(row => mapRunRow(row, this.mapperCtx)),\n total: countResult.count,\n limit,\n offset,\n };\n }\n\n // ============================================================================\n // Step Operations\n // ============================================================================\n\n async createStep(step: Omit<WorkflowRunStepRecord, 'id'>): Promise<WorkflowRunStepRecord> {\n const id = generateId();\n\n this.stmts!.insertStep.run(\n id,\n step.runId,\n step.stepKey,\n step.stepName,\n step.status,\n step.attempt,\n step.result !== undefined ? JSON.stringify(step.result) : null,\n step.error ? JSON.stringify(sanitizeErrorForStorage(step.error)) : null,\n step.startedAt?.toISOString() ?? null,\n step.finishedAt?.toISOString() ?? null\n );\n\n return { ...step, id };\n }\n\n async getStep(stepId: string): Promise<WorkflowRunStepRecord | null> {\n const row = this.stmts!.getStep.get(stepId) as SQLiteStepRow | undefined;\n return row ? mapStepRow(row, this.mapperCtx) : null;\n }\n\n async updateStep(stepId: string, updates: Partial<WorkflowRunStepRecord>): Promise<void> {\n this.stmts!.updateStep.run(\n updates.status ?? null,\n updates.attempt ?? null,\n updates.result !== undefined ? JSON.stringify(updates.result) : null,\n updates.error ? JSON.stringify(sanitizeErrorForStorage(updates.error)) : null,\n updates.finishedAt?.toISOString() ?? null,\n stepId\n );\n }\n\n async getStepsForRun(runId: string): Promise<WorkflowRunStepRecord[]> {\n const rows = this.stmts!.getStepsForRun.all(runId) as SQLiteStepRow[];\n return rows.map(row => mapStepRow(row, this.mapperCtx));\n }\n\n // ============================================================================\n // Event Operations\n // ============================================================================\n\n async saveEvent(event: Omit<WorkflowEventRecord, 'id'>): Promise<void> {\n const id = generateId();\n\n this.stmts!.insertEvent.run(\n id,\n event.runId,\n event.stepKey ?? null,\n event.eventType,\n event.level,\n event.payload !== undefined ? JSON.stringify(event.payload) : null,\n event.timestamp.toISOString()\n );\n }\n\n async getEventsForRun(runId: string, options: ListEventsOptions = {}): Promise<WorkflowEventRecord[]> {\n const limit = options.limit ?? 1000;\n const offset = options.offset ?? 0;\n const stepKey = options.stepKey ?? null;\n const level = options.level ?? null;\n\n const rows = this.stmts!.getEventsForRun.all(\n runId,\n stepKey, stepKey,\n level, level,\n limit, offset\n ) as SQLiteEventRow[];\n\n return rows.map(row => mapEventRow(row, this.mapperCtx));\n }\n\n // ============================================================================\n // Transaction Support\n // ============================================================================\n\n /**\n * Execute a function within a database transaction (async interface).\n *\n * @deprecated Use {@link transactionSync} instead. better-sqlite3 transactions\n * are synchronous: COMMIT happens the moment the callback returns control to\n * `db.transaction(fn)()`. If the callback awaits real async I/O (network,\n * timers, etc.), the COMMIT has already happened by the time the awaited work\n * runs, so its operations are **not** transactional.\n *\n * To make the footgun visible the adapter installs a runtime guard: when the\n * callback's promise has not settled by the time the COMMIT returns, the\n * deprecated method emits a `console.warn` so that the misuse surfaces in\n * production logs. The promise is still returned so existing callers keep\n * working — switch to `transactionSync` to silence the warning.\n */\n async transaction<T>(fn: (tx: StorageAdapter) => Promise<T>): Promise<T> {\n let fnPromise!: Promise<T>;\n this.transactionSync(() => {\n fnPromise = fn(this);\n });\n\n // COMMIT has already executed at this point. If the callback's promise is\n // still pending, the callback is doing async work outside the transaction\n // boundary — log a warning so the misuse is visible in production logs.\n if (!(await isPromiseSettled(fnPromise))) {\n console.warn(\n '[SQLiteStorageAdapter] transaction() callback did not settle synchronously. ' +\n 'better-sqlite3 transactions are synchronous and the COMMIT has already executed; ' +\n 'any async work inside the callback is NOT transactional. ' +\n 'Use transactionSync() with purely synchronous operations instead.'\n );\n }\n\n return fnPromise;\n }\n\n /**\n * Execute a synchronous transaction (preferred for better-sqlite3).\n * Use this when you need transaction guarantees.\n *\n * @example\n * ```typescript\n * storage.transactionSync(() => {\n * // Multiple operations in a single transaction\n * const run = storage.createRunSync(...);\n * storage.updateRunSync(run.id, ...);\n * });\n * ```\n */\n transactionSync<T>(fn: () => T): T {\n return this.db.transaction(fn)();\n }\n\n // ============================================================================\n // Cleanup Operations\n // ============================================================================\n\n /**\n * Delete runs older than the specified date.\n * Also deletes associated steps and events (via CASCADE).\n */\n async deleteOldRuns(olderThan: Date): Promise<number> {\n const isoDate = olderThan.toISOString();\n\n // Due to CASCADE, steps and events are deleted automatically\n // But we do it explicitly for databases without CASCADE support\n return this.db.transaction(() => {\n this.stmts!.deleteEventsForRuns.run(isoDate);\n this.stmts!.deleteStepsForRuns.run(isoDate);\n const result = this.stmts!.deleteOldRuns.run(isoDate);\n return result.changes;\n })();\n }\n\n // ============================================================================\n // Resume Support\n // ============================================================================\n\n /**\n * Get all runs that were interrupted (status is 'running' or 'queued').\n * These runs can potentially be resumed.\n */\n async getInterruptedRuns(): Promise<WorkflowRunRecord[]> {\n const rows = this.stmts!.getInterruptedRuns.all() as SQLiteRunRow[];\n return rows.map(row => mapRunRow(row, this.mapperCtx));\n }\n\n /**\n * Get the last completed step for a run.\n * Useful for resuming from a checkpoint.\n */\n async getLastCompletedStep(runId: string): Promise<WorkflowRunStepRecord | null> {\n const row = this.stmts!.getLastCompletedStep.get(runId) as SQLiteStepRow | undefined;\n return row ? mapStepRow(row, this.mapperCtx) : null;\n }\n\n // ============================================================================\n // Row Mapping\n // ============================================================================\n //\n // The pure row mappers (`mapRunRow`, `mapStepRow`, `mapEventRow`) live in\n // `./sqlite-core.ts`. Each call site here builds a `MapperContext` once via\n // `this.mapperCtx` and hands it to the mapper, which extends it with\n // `rowId` + `column` per JSON-parse so corruption logs identify the bad row\n // (audit M2 / L3 — PR #52).\n\n /** Mapper context paired with the adapter's component label + optional logger. */\n private get mapperCtx(): MapperContext {\n return { component: 'SQLiteStorageAdapter', logger: this.logger };\n }\n\n // ============================================================================\n // Utility Methods\n // ============================================================================\n\n /**\n * Close the database connection.\n */\n close(): void {\n this.db.close();\n }\n\n /**\n * Get database statistics.\n */\n getStats(): { runs: number; steps: number; events: number } {\n const runsCount = this.db.prepare('SELECT COUNT(*) as count FROM workflow_runs').get() as { count: number };\n const stepsCount = this.db.prepare('SELECT COUNT(*) as count FROM workflow_run_steps').get() as { count: number };\n const eventsCount = this.db.prepare('SELECT COUNT(*) as count FROM workflow_events').get() as { count: number };\n\n return {\n runs: runsCount.count,\n steps: stepsCount.count,\n events: eventsCount.count,\n };\n }\n}\n\n// ============================================================================\n// SQLite Row Types\n// ============================================================================\n//\n// `SQLiteRunRow`, `SQLiteStepRow`, and `SQLiteEventRow` now live in\n// `./sqlite-core.ts` alongside their pure row mappers.\n","/**\n * Shared core for the PostgreSQL storage adapters.\n *\n * `PostgresStorageAdapter` (the public, pool-owning adapter) and\n * `PostgresTransactionAdapter` (the in-transaction wrapper used by\n * `PostgresStorageAdapter.transaction()`) both implement the same CRUD subset\n * of `StorageAdapter`. Before this refactor they each carried their own copy\n * of every CRUD method, every row mapper, and every JSON-parse helper. The\n * only meaningful difference between them is which Kysely query builder they\n * target — an instance-bound one (`db.withSchema(schema)`) versus a\n * transaction-bound one (`trx.withSchema(schema)`).\n *\n * This module collapses that duplication:\n *\n * - Pure helpers (`safeJsonParse`, `safeParseField`, `safeParseOptionalField`,\n * row mappers, `applyRunsFilters`) live as standalone functions so callers\n * can use them directly without inheritance.\n *\n * - `PostgresStorageCore` is an abstract base class that implements the\n * CRUD subset of `StorageAdapter` against an abstract `qb` accessor and\n * an `ensureReady()` hook. Subclasses supply the schema-scoped query\n * builder (and an optional pre-call guard, e.g.\n * `PostgresStorageAdapter.ensureInitialized()`).\n *\n * No behavior change: every query and every JSON-parse path matches the\n * previous in-line implementations. The C2 transaction-pagination fix\n * (same-connection COUNT(*)) is preserved by the shared `listRuns`\n * implementation. The C1 migration error-propagation fix lives on\n * `PostgresStorageAdapter` and is unaffected by this module.\n */\n\nimport type { Kysely as KyselyType } from 'kysely';\nimport { generateId } from '../utils/id.js';\nimport { requirePostgresDeps } from '../utils/postgres-deps.js';\nimport { sanitizeErrorForStorage } from '../utils/logger.js';\nimport {\n safeParseField as sharedSafeParseField,\n safeParseOptionalField as sharedSafeParseOptionalField,\n type MapperContext,\n type SafeJsonParseContext,\n} from '../utils/safe-json.js';\nimport type {\n StorageAdapter,\n WorkflowRunRecord,\n WorkflowRunStepRecord,\n WorkflowEventRecord,\n ListRunsOptions,\n ListEventsOptions,\n PaginatedResult,\n CreateRunInput,\n UpdateRunInput,\n} from './types.js';\nimport type { Logger, RunStatus, StepStatus, WorkflowError } from '../core/types.js';\n\n/**\n * Re-export the shared `MapperContext` from `src/utils/safe-json.ts` so\n * existing imports of `MapperContext` from this module continue to work.\n */\nexport type { MapperContext };\n\n// ============================================================================\n// Database row types (re-declared here so postgres-core.ts is self-contained;\n// they mirror the table definitions in postgres.ts)\n// ============================================================================\n\n/** Kysely row type for the workflow_runs table. */\nexport interface WorkflowRunsTable {\n id: string;\n kind: string;\n status: string;\n parent_run_id: string | null;\n input_json: string;\n metadata_json: string;\n context_json: string;\n output_json: string | null;\n error_json: string | null;\n priority: number;\n timeout_ms: number | null;\n created_at: Date;\n started_at: Date | null;\n finished_at: Date | null;\n}\n\n/** Kysely row type for the workflow_run_steps table. */\nexport interface WorkflowRunStepsTable {\n id: string;\n run_id: string;\n step_key: string;\n step_name: string;\n status: string;\n attempt: number;\n result_json: string | null;\n error_json: string | null;\n started_at: Date | null;\n finished_at: Date | null;\n}\n\n/** Kysely row type for the workflow_events table. */\nexport interface WorkflowEventsTable {\n id: string;\n run_id: string;\n step_key: string | null;\n event_type: string;\n level: string;\n payload_json: string | null;\n timestamp: Date;\n}\n\n/** Combined Kysely schema covering the tables touched by the shared core. */\nexport interface PostgresCoreDatabase {\n runs: WorkflowRunsTable;\n workflow_run_steps: WorkflowRunStepsTable;\n workflow_events: WorkflowEventsTable;\n}\n\n/** Schema-scoped query builder produced by `db.withSchema(schemaName)`. */\nexport type SchemaQueryBuilder<DB extends PostgresCoreDatabase = PostgresCoreDatabase> =\n ReturnType<KyselyType<DB>['withSchema']>;\n\n/** Concrete core-only schema query builder used inside the shared base class. */\nexport type CoreSchemaQueryBuilder = SchemaQueryBuilder<PostgresCoreDatabase>;\n\n// ============================================================================\n// JSON-parse helpers (pure)\n// ============================================================================\n//\n// Storage adapters supply a `MapperContext` ({ component, logger }); each\n// helper extends it with the row id and column being parsed so a structured\n// log emitted on corruption identifies the bad row. The raw value is never\n// logged — see `src/utils/safe-json.ts`.\n\n/** Parse a column value if it's still a JSON string; pass through otherwise. */\nexport function safeParseField(\n value: unknown,\n fallback: unknown,\n ctx: SafeJsonParseContext,\n): unknown {\n return sharedSafeParseField(value, fallback, ctx);\n}\n\n/** Same as `safeParseField` but returns `undefined` for falsy/missing values. */\nexport function safeParseOptionalField(\n value: unknown,\n ctx: SafeJsonParseContext,\n): unknown {\n return sharedSafeParseOptionalField(value, ctx);\n}\n\n// ============================================================================\n// Row mappers (pure)\n// ============================================================================\n\n/** Map a `runs` row to the public `WorkflowRunRecord` shape. */\nexport function mapRunRow(row: WorkflowRunsTable, ctx: MapperContext): WorkflowRunRecord {\n const fieldCtx = (column: string): SafeJsonParseContext => ({ ...ctx, rowId: row.id, column });\n return {\n id: row.id,\n kind: row.kind,\n status: row.status as RunStatus,\n parentRunId: row.parent_run_id ?? undefined,\n input: safeParseField(row.input_json, {}, fieldCtx('input_json')) as Record<string, unknown>,\n context: safeParseField(row.context_json, {}, fieldCtx('context_json')) as Record<string, unknown>,\n output: safeParseOptionalField(row.output_json, fieldCtx('output_json')) as Record<string, unknown> | undefined,\n error: safeParseOptionalField(row.error_json, fieldCtx('error_json')) as WorkflowError | undefined,\n metadata: safeParseField(row.metadata_json, {}, fieldCtx('metadata_json')) as Record<string, unknown>,\n priority: row.priority ?? 0,\n timeoutMs: row.timeout_ms ?? undefined,\n createdAt: new Date(row.created_at),\n startedAt: row.started_at ? new Date(row.started_at) : undefined,\n finishedAt: row.finished_at ? new Date(row.finished_at) : undefined,\n };\n}\n\n/** Map a `workflow_run_steps` row to the public `WorkflowRunStepRecord` shape. */\nexport function mapStepRow(row: WorkflowRunStepsTable, ctx: MapperContext): WorkflowRunStepRecord {\n const fieldCtx = (column: string): SafeJsonParseContext => ({ ...ctx, rowId: row.id, column });\n return {\n id: row.id,\n runId: row.run_id,\n stepKey: row.step_key,\n stepName: row.step_name,\n status: row.status as StepStatus,\n attempt: row.attempt,\n result: safeParseOptionalField(row.result_json, fieldCtx('result_json')),\n error: safeParseOptionalField(row.error_json, fieldCtx('error_json')) as WorkflowError | undefined,\n startedAt: row.started_at ? new Date(row.started_at) : undefined,\n finishedAt: row.finished_at ? new Date(row.finished_at) : undefined,\n };\n}\n\n/** Map a `workflow_events` row to the public `WorkflowEventRecord` shape. */\nexport function mapEventRow(row: WorkflowEventsTable, ctx: MapperContext): WorkflowEventRecord {\n const fieldCtx: SafeJsonParseContext = { ...ctx, rowId: row.id, column: 'payload_json' };\n return {\n id: row.id,\n runId: row.run_id,\n stepKey: row.step_key ?? undefined,\n eventType: row.event_type,\n level: row.level as 'info' | 'warn' | 'error',\n payload: safeParseOptionalField(row.payload_json, fieldCtx),\n timestamp: new Date(row.timestamp),\n };\n}\n\n// ============================================================================\n// Filter helpers (pure)\n// ============================================================================\n\n/**\n * Apply the common `kind`/`status`/`parentRunId` filters from `ListRunsOptions`\n * to a Kysely select query. Used by both the data and count queries in\n * `listRuns` so they share exactly the same WHERE clause.\n */\nexport function applyRunsFilters<T extends { where(col: any, op: any, val: any): T }>(\n query: T,\n options: ListRunsOptions,\n): T {\n if (options.kind) {\n query = query.where('kind', '=', options.kind);\n }\n if (options.status) {\n const statuses = Array.isArray(options.status) ? options.status : [options.status];\n query = query.where('status', 'in', statuses);\n }\n if (options.parentRunId !== undefined) {\n query = query.where('parent_run_id', '=', options.parentRunId);\n }\n return query;\n}\n\n// ============================================================================\n// Shared base class\n// ============================================================================\n\n/**\n * Abstract base implementing the CRUD subset of `StorageAdapter` against a\n * schema-scoped Kysely query builder. Subclasses must provide the query\n * builder via `qb` and may override `ensureReady()` to gate calls (the\n * pool-owning adapter uses this to enforce `initialize()` having run).\n *\n * The base class deliberately does **not** own the connection pool, schema\n * migrations, or transaction control — those stay with `PostgresStorageAdapter`.\n *\n * The base class targets `PostgresCoreDatabase` (the three core tables) so\n * Kysely's row-type machinery can fully resolve column types on every query.\n * Subclasses with a wider schema (e.g. `PostgresStorageAdapter` with\n * `stepflow_step_results`) keep their own typed handle for the extra tables\n * and return a core-typed view here.\n */\nexport abstract class PostgresStorageCore implements StorageAdapter {\n protected constructor(\n protected readonly schema: string,\n protected readonly logger?: Logger,\n ) {}\n\n /** Schema-scoped query builder. Subclasses return the bound builder. */\n protected abstract get qb(): CoreSchemaQueryBuilder;\n\n /** Component label used in corruption warnings; defines the JSON-parse `MapperContext`. */\n protected abstract get warnLabel(): string;\n\n /** Mapper context handed to row mappers — pairs the component label with the optional logger. */\n protected get mapperCtx(): MapperContext {\n return { component: this.warnLabel, logger: this.logger };\n }\n\n /**\n * Hook called at the start of every CRUD method. The pool-owning adapter\n * overrides this to throw before `initialize()` has run; the transaction\n * wrapper leaves it as a no-op.\n */\n protected ensureReady(): void {}\n\n // --------------------------------------------------------------------------\n // Run operations\n // --------------------------------------------------------------------------\n\n async createRun(\n run: CreateRunInput | Omit<WorkflowRunRecord, 'id' | 'createdAt'>,\n ): Promise<WorkflowRunRecord> {\n this.ensureReady();\n const id = 'id' in run && run.id ? run.id : generateId();\n const createdAt = new Date();\n\n await this.qb\n .insertInto('runs')\n .values({\n id,\n kind: run.kind,\n status: run.status,\n parent_run_id: 'parentRunId' in run ? (run.parentRunId ?? null) : null,\n input_json: JSON.stringify(run.input),\n metadata_json: JSON.stringify(run.metadata ?? {}),\n context_json: JSON.stringify(run.context ?? {}),\n output_json: null,\n error_json:\n 'error' in run && run.error\n ? JSON.stringify(sanitizeErrorForStorage(run.error))\n : null,\n priority: 'priority' in run ? (run.priority ?? 0) : 0,\n timeout_ms: 'timeoutMs' in run ? (run.timeoutMs ?? null) : null,\n created_at: createdAt,\n started_at: null,\n finished_at: null,\n })\n .execute();\n\n return {\n id,\n kind: run.kind,\n status: run.status as RunStatus,\n parentRunId: 'parentRunId' in run ? run.parentRunId : undefined,\n input: run.input,\n context: run.context ?? {},\n output: undefined,\n error: undefined,\n metadata: run.metadata ?? {},\n priority: 'priority' in run ? (run.priority ?? 0) : 0,\n timeoutMs: 'timeoutMs' in run ? run.timeoutMs : undefined,\n createdAt,\n };\n }\n\n async getRun(runId: string): Promise<WorkflowRunRecord | null> {\n this.ensureReady();\n const row = await this.qb\n .selectFrom('runs')\n .selectAll()\n .where('id', '=', runId)\n .executeTakeFirst();\n\n return row ? mapRunRow(row as WorkflowRunsTable, this.mapperCtx) : null;\n }\n\n async updateRun(\n runId: string,\n updates: UpdateRunInput | Partial<WorkflowRunRecord>,\n ): Promise<void> {\n this.ensureReady();\n const updateData: Partial<WorkflowRunsTable> = {};\n\n if (updates.status !== undefined) {\n updateData.status = updates.status;\n }\n if (updates.context !== undefined) {\n updateData.context_json = JSON.stringify(updates.context);\n }\n if ('output' in updates && updates.output !== undefined) {\n updateData.output_json = JSON.stringify(updates.output);\n }\n if (updates.error !== undefined) {\n updateData.error_json = JSON.stringify(\n sanitizeErrorForStorage(updates.error as WorkflowError),\n );\n }\n if (updates.startedAt !== undefined) {\n updateData.started_at = updates.startedAt;\n }\n if (updates.finishedAt !== undefined) {\n updateData.finished_at = updates.finishedAt;\n }\n\n if (Object.keys(updateData).length > 0) {\n await this.qb\n .updateTable('runs')\n .set(updateData)\n .where('id', '=', runId)\n .execute();\n }\n }\n\n async listRuns(\n options: ListRunsOptions = {},\n ): Promise<PaginatedResult<WorkflowRunRecord>> {\n this.ensureReady();\n const { sql } = requirePostgresDeps();\n const limit = options.limit ?? 50;\n const offset = options.offset ?? 0;\n\n // Same-connection COUNT(*) so totals reflect rows visible to this builder\n // (preserves the C2 transaction-pagination fix from PR #47).\n const countQuery = applyRunsFilters(\n this.qb.selectFrom('runs').select(sql<number>`count(*)`.as('count')),\n options,\n );\n const dataQuery = applyRunsFilters(this.qb.selectFrom('runs').selectAll(), options);\n\n const orderBy = options.orderBy ?? 'createdAt';\n const orderDirection = options.orderDirection ?? 'desc';\n const orderColumn =\n orderBy === 'createdAt'\n ? 'created_at'\n : orderBy === 'startedAt'\n ? 'started_at'\n : 'finished_at';\n\n const countResult = (await countQuery.executeTakeFirst()) as\n | { count?: string | number }\n | undefined;\n const total = Number(countResult?.count ?? 0);\n\n const rows = await dataQuery\n .orderBy(orderColumn, orderDirection)\n .limit(limit)\n .offset(offset)\n .execute();\n\n return {\n items: rows.map((row) => mapRunRow(row as WorkflowRunsTable, this.mapperCtx)),\n total,\n };\n }\n\n // --------------------------------------------------------------------------\n // Step operations\n // --------------------------------------------------------------------------\n\n async createStep(\n step: Omit<WorkflowRunStepRecord, 'id'>,\n ): Promise<WorkflowRunStepRecord> {\n this.ensureReady();\n const id = generateId();\n\n await this.qb\n .insertInto('workflow_run_steps')\n .values({\n id,\n run_id: step.runId,\n step_key: step.stepKey,\n step_name: step.stepName,\n status: step.status,\n attempt: step.attempt,\n result_json: step.result !== undefined ? JSON.stringify(step.result) : null,\n error_json: step.error\n ? JSON.stringify(sanitizeErrorForStorage(step.error))\n : null,\n started_at: step.startedAt ?? null,\n finished_at: step.finishedAt ?? null,\n })\n .execute();\n\n return { ...step, id };\n }\n\n async getStep(stepId: string): Promise<WorkflowRunStepRecord | null> {\n this.ensureReady();\n const row = await this.qb\n .selectFrom('workflow_run_steps')\n .selectAll()\n .where('id', '=', stepId)\n .executeTakeFirst();\n\n return row ? mapStepRow(row as WorkflowRunStepsTable, this.mapperCtx) : null;\n }\n\n async updateStep(\n stepId: string,\n updates: Partial<WorkflowRunStepRecord>,\n ): Promise<void> {\n this.ensureReady();\n const updateData: Partial<WorkflowRunStepsTable> = {};\n\n if (updates.status !== undefined) {\n updateData.status = updates.status;\n }\n if (updates.attempt !== undefined) {\n updateData.attempt = updates.attempt;\n }\n if (updates.result !== undefined) {\n updateData.result_json = JSON.stringify(updates.result);\n }\n if (updates.error !== undefined) {\n updateData.error_json = JSON.stringify(\n sanitizeErrorForStorage(updates.error as WorkflowError),\n );\n }\n if (updates.finishedAt !== undefined) {\n updateData.finished_at = updates.finishedAt;\n }\n\n if (Object.keys(updateData).length > 0) {\n await this.qb\n .updateTable('workflow_run_steps')\n .set(updateData)\n .where('id', '=', stepId)\n .execute();\n }\n }\n\n async getStepsForRun(runId: string): Promise<WorkflowRunStepRecord[]> {\n this.ensureReady();\n const rows = await this.qb\n .selectFrom('workflow_run_steps')\n .selectAll()\n .where('run_id', '=', runId)\n .orderBy('started_at', 'asc')\n .execute();\n\n return rows.map((row) => mapStepRow(row as WorkflowRunStepsTable, this.mapperCtx));\n }\n\n // --------------------------------------------------------------------------\n // Event operations\n // --------------------------------------------------------------------------\n\n async saveEvent(event: Omit<WorkflowEventRecord, 'id'>): Promise<void> {\n this.ensureReady();\n const id = generateId();\n\n await this.qb\n .insertInto('workflow_events')\n .values({\n id,\n run_id: event.runId,\n step_key: event.stepKey ?? null,\n event_type: event.eventType,\n level: event.level,\n payload_json: event.payload !== undefined ? JSON.stringify(event.payload) : null,\n timestamp: event.timestamp,\n })\n .execute();\n }\n\n async getEventsForRun(\n runId: string,\n options: ListEventsOptions = {},\n ): Promise<WorkflowEventRecord[]> {\n this.ensureReady();\n const limit = options.limit ?? 1000;\n const offset = options.offset ?? 0;\n\n let query = this.qb\n .selectFrom('workflow_events')\n .selectAll()\n .where('run_id', '=', runId);\n\n if (options.stepKey) {\n query = query.where('step_key', '=', options.stepKey);\n }\n if (options.level) {\n query = query.where('level', '=', options.level);\n }\n\n query = query.orderBy('timestamp', 'asc').limit(limit).offset(offset);\n\n const rows = await query.execute();\n\n return rows.map((row) => mapEventRow(row as WorkflowEventsTable, this.mapperCtx));\n }\n}\n","/**\n * PostgreSQL storage adapter using Kysely.\n *\n * Provides durable persistence for workflow runs, steps, and events with\n * support for distributed deployments and connection pooling.\n *\n * ## Module layout\n *\n * - `PostgresStorageAdapter` (this file) owns the `pg.Pool` / Kysely\n * instance, runs schema migrations on `initialize()`, and implements all\n * non-CRUD methods: connection lifecycle (`close`, `transaction`),\n * workflow-level operations (`dequeueRun`, `cleanupStaleRuns`,\n * `markRunsAsFailed`, `getStats`, `deleteRun`, `deleteOldRuns`,\n * `getInterruptedRuns`, `getLastCompletedStep`), and the\n * `stepflow_step_results` accessors.\n *\n * - `PostgresTransactionAdapter` (this file) is a thin shell used by\n * `PostgresStorageAdapter.transaction()`. It binds a transaction-scoped\n * Kysely query builder; everything else comes from the shared core.\n * Exported only for regression tests.\n *\n * - `PostgresStorageCore` (./postgres-core.ts) holds the shared CRUD\n * methods (`createRun`, `getRun`, `updateRun`, `listRuns`, `createStep`,\n * `getStep`, `updateStep`, `getStepsForRun`, `saveEvent`,\n * `getEventsForRun`), the row mappers, and the JSON-parse helpers. Both\n * classes here extend it.\n */\n\nimport type { Kysely as KyselyType } from 'kysely';\nimport type { Pool, PoolConfig } from 'pg';\nimport type { Logger } from '../core/types.js';\nimport { loadPostgresDeps } from '../utils/postgres-deps.js';\n\n// Lazy-loaded dependencies - populated by loadPostgresDeps() during initialize()\nlet Kysely: any;\nlet PostgresDialect: any;\nlet sql: any;\nlet pgModule: any;\nimport { generateId } from '../utils/id.js';\nimport type {\n StorageAdapter,\n WorkflowRunRecord,\n WorkflowRunStepRecord,\n StepResult,\n ExtendedStepStatus,\n} from './types.js';\nimport {\n PostgresStorageCore,\n mapRunRow,\n mapStepRow,\n safeParseOptionalField,\n type CoreSchemaQueryBuilder,\n type PostgresCoreDatabase,\n type SchemaQueryBuilder,\n type WorkflowRunsTable,\n type WorkflowRunStepsTable,\n} from './postgres-core.js';\n\n/** Strip `stack` from a generic error record before persistence. */\nfunction stripStack<T extends Record<string, unknown>>(error: T): Omit<T, 'stack'> {\n const { stack: _stack, ...rest } = error;\n return rest as Omit<T, 'stack'>;\n}\n\n// ============================================================================\n// Database Types (Kysely schema)\n// ============================================================================\n//\n// The `runs`, `workflow_run_steps`, and `workflow_events` table shapes live\n// in `./postgres-core.ts` so the shared CRUD core can target them without\n// re-declaration. The full `StepflowDatabase` schema below adds the\n// adapter-only `stepflow_step_results` table (extended storage).\n\n/** Kysely row type for the stepflow_step_results table (extended storage). */\ninterface StepflowStepResultsTable {\n id: string;\n /** Foreign key to runs.id. */\n run_id: string;\n /** Step name identifier. */\n step_name: string;\n /** Current step status (maps to ExtendedStepStatus). */\n status: string;\n /** JSON-serialized step output, null until step completes. */\n output_json: string | null;\n /** JSON-serialized error object, null unless step failed. */\n error_json: string | null;\n /** Current retry attempt number (1-based). */\n attempt: number;\n started_at: Date | null;\n completed_at: Date | null;\n}\n\ninterface StepflowDatabase extends PostgresCoreDatabase {\n stepflow_step_results: StepflowStepResultsTable;\n}\n\n// ============================================================================\n// Configuration\n// ============================================================================\n\n/**\n * Configuration options for the PostgreSQL storage adapter.\n */\nexport interface PostgresStorageConfig {\n /**\n * PostgreSQL connection string.\n * Example: \"postgresql://user:pass@localhost:5432/dbname\"\n */\n connectionString?: string;\n\n /**\n * Existing pg.Pool instance for connection sharing with application.\n * If provided, the adapter will not close this pool on close().\n */\n pool?: Pool;\n\n /**\n * Pool configuration options (if not providing pool or connectionString).\n */\n poolConfig?: PoolConfig;\n\n /**\n * Schema name for Stepflow tables.\n * @default 'public'\n */\n schema?: string;\n\n /**\n * Automatically create tables on initialize().\n * @default true\n */\n autoMigrate?: boolean;\n\n /**\n * Optional structured logger used to surface JSON corruption events.\n * Without one, parse failures still increment the corruption counter\n * exposed via `getJsonParseCorruptionCount()` but produce no log output.\n */\n logger?: Logger;\n}\n\n// ============================================================================\n// PostgreSQL Storage Adapter\n// ============================================================================\n\n/**\n * PostgreSQL implementation of StorageAdapter using Kysely.\n *\n * Features:\n * - Connection pooling (shared or dedicated)\n * - Automatic table creation\n * - Transaction support\n * - Atomic dequeue operations for distributed workers\n * - JSONB storage for flexible data\n *\n * @example\n * ```typescript\n * import { PostgresStorageAdapter } from 'stepflow/storage';\n *\n * const storage = new PostgresStorageAdapter({\n * connectionString: process.env.DATABASE_URL,\n * });\n *\n * await storage.initialize();\n *\n * const engine = new WorkflowEngine({ storage });\n * ```\n *\n * @example Sharing connection pool\n * ```typescript\n * import pg from 'pg';\n * import { PostgresStorageAdapter } from 'stepflow/storage';\n *\n * // Application's existing pool\n * const pool = new pg.Pool({\n * connectionString: process.env.DATABASE_URL,\n * max: 20,\n * });\n *\n * // Share with Stepflow\n * const storage = new PostgresStorageAdapter({ pool });\n * ```\n */\nexport class PostgresStorageAdapter extends PostgresStorageCore {\n private db!: KyselyType<StepflowDatabase>;\n private pool!: Pool;\n private ownsPool = false;\n private autoMigrate: boolean;\n private initialized = false;\n private config: PostgresStorageConfig;\n\n constructor(config: PostgresStorageConfig) {\n const schema = config.schema ?? 'public';\n if (!/^[a-zA-Z_][a-zA-Z0-9_]{0,62}$/.test(schema)) {\n throw new Error(\n `Invalid schema name \"${schema}\". Schema must start with a letter or underscore, ` +\n `contain only alphanumeric characters and underscores, and be at most 63 characters.`\n );\n }\n super(schema, config.logger);\n this.autoMigrate = config.autoMigrate !== false;\n this.config = config;\n }\n\n /**\n * Core-tables query builder consumed by `PostgresStorageCore`. Returns the\n * schema-scoped Kysely view typed against the three core tables, which is\n * what the shared CRUD methods need.\n */\n protected override get qb(): CoreSchemaQueryBuilder {\n return this.db.withSchema(this.schema) as unknown as CoreSchemaQueryBuilder;\n }\n\n /**\n * Extended query builder for adapter-only tables (currently\n * `stepflow_step_results`). Kept separate from `qb` so the base class stays\n * typed against the core schema.\n */\n private get extQb(): SchemaQueryBuilder<StepflowDatabase> {\n return this.db.withSchema(this.schema);\n }\n\n /** Tag used by shared row mappers in `console.warn` messages. */\n protected override get warnLabel(): string {\n return 'PostgresStorageAdapter';\n }\n\n /** Override of `PostgresStorageCore.ensureReady()` — enforces `initialize()`. */\n protected override ensureReady(): void {\n this.ensureInitialized();\n }\n\n private ensureInitialized(): void {\n if (!this.initialized) {\n throw new Error(\n 'PostgresStorageAdapter is not initialized. Call initialize() before using the adapter.'\n );\n }\n }\n\n /**\n * Initialize the storage adapter.\n * Creates tables if autoMigrate is enabled.\n */\n async initialize(): Promise<void> {\n if (this.initialized) {\n return;\n }\n\n const deps = await loadPostgresDeps();\n Kysely = deps.Kysely;\n PostgresDialect = deps.PostgresDialect;\n sql = deps.sql;\n pgModule = deps.pgModule;\n\n if (this.config.pool) {\n this.pool = this.config.pool;\n this.ownsPool = false;\n } else if (this.config.connectionString) {\n this.pool = new pgModule.Pool({ connectionString: this.config.connectionString });\n this.ownsPool = true;\n } else if (this.config.poolConfig) {\n this.pool = new pgModule.Pool(this.config.poolConfig);\n this.ownsPool = true;\n } else {\n throw new Error(\n 'PostgresStorageConfig must include either pool, connectionString, or poolConfig'\n );\n }\n\n this.db = new Kysely({\n dialect: new PostgresDialect({\n pool: this.pool,\n }),\n });\n\n if (this.autoMigrate) {\n await this.createTables();\n }\n\n this.initialized = true;\n }\n\n /**\n * Close the database connection.\n * Only closes the pool if it was created by this adapter.\n */\n async close(): Promise<void> {\n await this.db.destroy();\n // Kysely's destroy() already calls pool.end() via PostgresDialect,\n // so we must NOT call pool.end() again.\n }\n\n // ============================================================================\n // Schema Creation\n // ============================================================================\n\n /**\n * Run a single migration step. Tolerates only known-benign Postgres errors\n * (duplicate object codes that map to \"already applied\"), and rethrows\n * everything else with a clear message so partial-state upgrades are not\n * silently swallowed.\n */\n protected async runMigration(label: string, fn: () => Promise<unknown>): Promise<void> {\n try {\n await fn();\n } catch (err) {\n if (PostgresStorageAdapter.isBenignMigrationError(err)) {\n return;\n }\n const message = err instanceof Error ? err.message : String(err);\n throw new Error(`Schema migration failed (${label}): ${message}`, { cause: err });\n }\n }\n\n /**\n * Postgres SQLSTATE codes that indicate a migration step has already been\n * applied (object already exists). These are safe to ignore on idempotent\n * re-runs; everything else must propagate.\n *\n * - 42701: duplicate_column\n * - 42P07: duplicate_table\n * - 42P06: duplicate_schema\n * - 42710: duplicate_object (e.g., index, constraint)\n */\n private static readonly BENIGN_MIGRATION_CODES = new Set([\n '42701',\n '42P07',\n '42P06',\n '42710',\n ]);\n\n private static isBenignMigrationError(err: unknown): boolean {\n if (!err || typeof err !== 'object') return false;\n const code = (err as { code?: unknown }).code;\n return typeof code === 'string' && PostgresStorageAdapter.BENIGN_MIGRATION_CODES.has(code);\n }\n\n /**\n * Create the workflow tables if they don't exist.\n */\n private async createTables(): Promise<void> {\n // Create schema if not public\n if (this.schema !== 'public') {\n await sql`CREATE SCHEMA IF NOT EXISTS ${sql.ref(this.schema)}`.execute(this.db);\n }\n\n // Create runs table with new columns\n await sql`\n CREATE TABLE IF NOT EXISTS ${sql.table(`${this.schema}.runs`)} (\n id TEXT PRIMARY KEY,\n kind TEXT NOT NULL,\n status TEXT NOT NULL,\n parent_run_id TEXT,\n input_json JSONB NOT NULL DEFAULT '{}',\n metadata_json JSONB NOT NULL DEFAULT '{}',\n context_json JSONB NOT NULL DEFAULT '{}',\n output_json JSONB,\n error_json JSONB,\n priority INTEGER NOT NULL DEFAULT 0,\n timeout_ms INTEGER,\n created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),\n started_at TIMESTAMPTZ,\n finished_at TIMESTAMPTZ,\n CONSTRAINT runs_status_check CHECK (\n status IN ('pending', 'queued', 'running', 'succeeded', 'failed', 'canceled', 'timeout')\n )\n )\n `.execute(this.db);\n\n // Add new columns if they don't exist (for migrations)\n await this.runMigration(\n `add columns to ${this.schema}.runs`,\n () => sql`\n ALTER TABLE ${sql.table(`${this.schema}.runs`)}\n ADD COLUMN IF NOT EXISTS output_json JSONB,\n ADD COLUMN IF NOT EXISTS priority INTEGER NOT NULL DEFAULT 0,\n ADD COLUMN IF NOT EXISTS timeout_ms INTEGER\n `.execute(this.db)\n );\n\n // Create indexes for runs\n await sql`\n CREATE INDEX IF NOT EXISTS idx_runs_kind_status\n ON ${sql.table(`${this.schema}.runs`)} (kind, status)\n `.execute(this.db);\n\n await sql`\n CREATE INDEX IF NOT EXISTS idx_runs_parent\n ON ${sql.table(`${this.schema}.runs`)} (parent_run_id)\n `.execute(this.db);\n\n await sql`\n CREATE INDEX IF NOT EXISTS idx_runs_created\n ON ${sql.table(`${this.schema}.runs`)} (created_at DESC)\n `.execute(this.db);\n\n await sql`\n CREATE INDEX IF NOT EXISTS idx_runs_status\n ON ${sql.table(`${this.schema}.runs`)} (status)\n `.execute(this.db);\n\n await sql`\n CREATE INDEX IF NOT EXISTS idx_runs_priority\n ON ${sql.table(`${this.schema}.runs`)} (priority DESC, created_at ASC)\n `.execute(this.db);\n\n // Create workflow_run_steps table (legacy)\n await sql`\n CREATE TABLE IF NOT EXISTS ${sql.table(`${this.schema}.workflow_run_steps`)} (\n id TEXT PRIMARY KEY,\n run_id TEXT NOT NULL REFERENCES ${sql.table(`${this.schema}.runs`)} (id) ON DELETE CASCADE,\n step_key TEXT NOT NULL,\n step_name TEXT,\n status TEXT NOT NULL,\n attempt INTEGER NOT NULL DEFAULT 1,\n result_json JSONB,\n error_json JSONB,\n started_at TIMESTAMPTZ,\n finished_at TIMESTAMPTZ,\n CONSTRAINT workflow_run_steps_status_check CHECK (\n status IN ('pending', 'running', 'succeeded', 'failed', 'skipped', 'completed')\n )\n )\n `.execute(this.db);\n\n // Create indexes for workflow_run_steps\n await sql`\n CREATE INDEX IF NOT EXISTS idx_workflow_run_steps_run\n ON ${sql.table(`${this.schema}.workflow_run_steps`)} (run_id)\n `.execute(this.db);\n\n await sql`\n CREATE INDEX IF NOT EXISTS idx_workflow_run_steps_run_key\n ON ${sql.table(`${this.schema}.workflow_run_steps`)} (run_id, step_key)\n `.execute(this.db);\n\n // Create stepflow_step_results table (new)\n await sql`\n CREATE TABLE IF NOT EXISTS ${sql.table(`${this.schema}.stepflow_step_results`)} (\n id TEXT PRIMARY KEY DEFAULT gen_random_uuid()::text,\n run_id TEXT NOT NULL REFERENCES ${sql.table(`${this.schema}.runs`)} (id) ON DELETE CASCADE,\n step_name TEXT NOT NULL,\n status TEXT NOT NULL,\n output_json JSONB,\n error_json JSONB,\n attempt INTEGER NOT NULL DEFAULT 1,\n started_at TIMESTAMPTZ,\n completed_at TIMESTAMPTZ,\n CONSTRAINT stepflow_step_results_status_check CHECK (\n status IN ('pending', 'running', 'completed', 'failed', 'skipped')\n ),\n UNIQUE (run_id, step_name)\n )\n `.execute(this.db);\n\n // Create indexes for stepflow_step_results\n await sql`\n CREATE INDEX IF NOT EXISTS idx_stepflow_step_results_run\n ON ${sql.table(`${this.schema}.stepflow_step_results`)} (run_id)\n `.execute(this.db);\n\n await sql`\n CREATE INDEX IF NOT EXISTS idx_stepflow_step_results_run_name\n ON ${sql.table(`${this.schema}.stepflow_step_results`)} (run_id, step_name)\n `.execute(this.db);\n\n // Create workflow_events table\n await sql`\n CREATE TABLE IF NOT EXISTS ${sql.table(`${this.schema}.workflow_events`)} (\n id TEXT PRIMARY KEY,\n run_id TEXT NOT NULL REFERENCES ${sql.table(`${this.schema}.runs`)} (id) ON DELETE CASCADE,\n step_key TEXT,\n event_type TEXT NOT NULL,\n level TEXT NOT NULL,\n payload_json JSONB,\n timestamp TIMESTAMPTZ NOT NULL DEFAULT NOW(),\n CONSTRAINT workflow_events_level_check CHECK (\n level IN ('info', 'warn', 'error')\n )\n )\n `.execute(this.db);\n\n // Create indexes for workflow_events\n await sql`\n CREATE INDEX IF NOT EXISTS idx_workflow_events_run\n ON ${sql.table(`${this.schema}.workflow_events`)} (run_id)\n `.execute(this.db);\n\n await sql`\n CREATE INDEX IF NOT EXISTS idx_workflow_events_run_ts\n ON ${sql.table(`${this.schema}.workflow_events`)} (run_id, timestamp)\n `.execute(this.db);\n }\n\n // ============================================================================\n // Run / Step / Event CRUD\n // ============================================================================\n //\n // The CRUD methods (`createRun`, `getRun`, `updateRun`, `listRuns`,\n // `createStep`, `getStep`, `updateStep`, `getStepsForRun`, `saveEvent`,\n // `getEventsForRun`) are inherited from `PostgresStorageCore`. Each call\n // routes through `this.qb` (overridden above) and `this.ensureReady()`\n // which calls `this.ensureInitialized()`.\n\n // ============================================================================\n // Transaction Support\n // ============================================================================\n\n /**\n * Execute a function within a database transaction.\n */\n async transaction<T>(fn: (tx: StorageAdapter) => Promise<T>): Promise<T> {\n this.ensureInitialized();\n return await this.db.transaction().execute(async (trx) => {\n // Create a transactional adapter wrapper\n const txAdapter = new PostgresTransactionAdapter(trx, this.schema, this.logger);\n return await fn(txAdapter);\n });\n }\n\n // ============================================================================\n // Cleanup Operations\n // ============================================================================\n\n /**\n * Delete runs older than the specified date.\n * Also deletes associated steps and events (via CASCADE).\n */\n async deleteOldRuns(olderThan: Date): Promise<number> {\n this.ensureInitialized();\n const result = await this.qb\n .deleteFrom('runs')\n .where('created_at', '<', olderThan)\n .executeTakeFirst();\n\n return Number(result.numDeletedRows);\n }\n\n // ============================================================================\n // Resume Support\n // ============================================================================\n\n /**\n * Get all runs that were interrupted (status is 'running' or 'queued').\n * These runs can potentially be resumed.\n */\n async getInterruptedRuns(): Promise<WorkflowRunRecord[]> {\n this.ensureInitialized();\n const rows = await this.qb\n .selectFrom('runs')\n .selectAll()\n .where('status', 'in', ['queued', 'running'])\n .orderBy('created_at', 'asc')\n .execute();\n\n return rows.map(row => mapRunRow(row as WorkflowRunsTable, this.mapperCtx));\n }\n\n /**\n * Get the last completed step for a run.\n * Useful for resuming from a checkpoint.\n */\n async getLastCompletedStep(runId: string): Promise<WorkflowRunStepRecord | null> {\n this.ensureInitialized();\n const row = await this.qb\n .selectFrom('workflow_run_steps')\n .selectAll()\n .where('run_id', '=', runId)\n .where('status', '=', 'succeeded')\n .orderBy('finished_at', 'desc')\n .limit(1)\n .executeTakeFirst();\n\n return row ? mapStepRow(row as WorkflowRunStepsTable, this.mapperCtx) : null;\n }\n\n // ============================================================================\n // Atomic Dequeue (for distributed workers)\n // ============================================================================\n\n /**\n * Atomically dequeue a run for processing.\n * Uses FOR UPDATE SKIP LOCKED for safe concurrent access.\n *\n * @param workflowKinds - Optional list of workflow kinds to filter by\n * @returns The dequeued run, or null if no runs are available\n */\n async dequeueRun(workflowKinds?: string[]): Promise<WorkflowRunRecord | null> {\n this.ensureInitialized();\n // Use raw SQL for FOR UPDATE SKIP LOCKED\n const kindFilter = workflowKinds && workflowKinds.length > 0\n ? sql`AND kind = ANY(${workflowKinds}::text[])`\n : sql``;\n\n const result = await sql<WorkflowRunsTable>`\n UPDATE ${sql.table(`${this.schema}.runs`)}\n SET status = 'running', started_at = NOW()\n WHERE id = (\n SELECT id FROM ${sql.table(`${this.schema}.runs`)}\n WHERE status = 'queued' ${kindFilter}\n ORDER BY priority DESC, created_at ASC\n LIMIT 1\n FOR UPDATE SKIP LOCKED\n )\n RETURNING *\n `.execute(this.db);\n\n const row = result.rows[0];\n return row ? mapRunRow(row, this.mapperCtx) : null;\n }\n\n // ============================================================================\n // Row Mapping (adapter-only tables)\n // ============================================================================\n //\n // Mappers and JSON-parse helpers for the three core tables live in\n // `./postgres-core.ts`. The single mapper kept here covers\n // `stepflow_step_results`, the only table outside the core schema.\n\n private mapStepResultRow(row: StepflowStepResultsTable): StepResult {\n const ctx = this.mapperCtx;\n return {\n id: row.id,\n runId: row.run_id,\n stepName: row.step_name,\n status: row.status as ExtendedStepStatus,\n output: safeParseOptionalField(row.output_json, {\n ...ctx,\n rowId: row.id,\n column: 'output_json',\n }) as Record<string, unknown> | undefined,\n error: safeParseOptionalField(row.error_json, {\n ...ctx,\n rowId: row.id,\n column: 'error_json',\n }) as Record<string, unknown> | undefined,\n attempt: row.attempt,\n startedAt: row.started_at ? new Date(row.started_at) : undefined,\n completedAt: row.completed_at ? new Date(row.completed_at) : undefined,\n };\n }\n\n // ============================================================================\n // New WorkflowStorage Methods\n // ============================================================================\n\n /**\n * Delete a workflow run by ID.\n * Also deletes associated steps and events (via CASCADE).\n */\n async deleteRun(id: string): Promise<void> {\n this.ensureInitialized();\n await this.qb\n .deleteFrom('runs')\n .where('id', '=', id)\n .execute();\n }\n\n /**\n * Cleanup stale runs that have exceeded their timeout.\n * Marks them as 'timeout' status with an appropriate error.\n *\n * @param defaultTimeoutMs - Default timeout in ms for runs without explicit timeout (default: 600000 = 10 minutes)\n * @returns Number of runs marked as timed out\n */\n async cleanupStaleRuns(defaultTimeoutMs: number = 600000): Promise<number> {\n this.ensureInitialized();\n const result = await sql<{ id: string }>`\n UPDATE ${sql.table(`${this.schema}.runs`)}\n SET\n status = 'timeout',\n error_json = jsonb_build_object(\n 'code', 'WORKFLOW_TIMEOUT',\n 'message', 'Workflow exceeded maximum execution time and was marked as timed out'\n ),\n finished_at = NOW()\n WHERE status = 'running'\n AND started_at IS NOT NULL\n AND (\n (timeout_ms IS NOT NULL AND started_at < NOW() - (timeout_ms || ' milliseconds')::interval)\n OR\n (timeout_ms IS NULL AND started_at < NOW() - (${defaultTimeoutMs} || ' milliseconds')::interval)\n )\n RETURNING id\n `.execute(this.db);\n\n return result.rows.length;\n }\n\n /**\n * Mark multiple runs as failed with a given reason.\n * Useful for cleanup when a worker shuts down unexpectedly.\n *\n * @param runIds - Array of run IDs to mark as failed\n * @param reason - Reason message for the failure\n */\n async markRunsAsFailed(runIds: string[], reason: string): Promise<void> {\n this.ensureInitialized();\n if (runIds.length === 0) return;\n\n await sql`\n UPDATE ${sql.table(`${this.schema}.runs`)}\n SET\n status = 'failed',\n error_json = jsonb_build_object(\n 'code', 'WORKER_SHUTDOWN',\n 'message', ${reason}\n ),\n finished_at = NOW()\n WHERE id = ANY(${runIds})\n AND status = 'running'\n `.execute(this.db);\n }\n\n /**\n * Get a specific step result by run ID and step name.\n */\n async getStepResult(runId: string, stepName: string): Promise<StepResult | undefined> {\n this.ensureInitialized();\n const row = await this.extQb\n .selectFrom('stepflow_step_results')\n .selectAll()\n .where('run_id', '=', runId)\n .where('step_name', '=', stepName)\n .executeTakeFirst();\n\n return row ? this.mapStepResultRow(row) : undefined;\n }\n\n /**\n * Get all step results for a run.\n */\n async getStepResults(runId: string): Promise<StepResult[]> {\n this.ensureInitialized();\n const rows = await this.extQb\n .selectFrom('stepflow_step_results')\n .selectAll()\n .where('run_id', '=', runId)\n .orderBy('started_at', 'asc')\n .execute();\n\n return rows.map(row => this.mapStepResultRow(row));\n }\n\n /**\n * Save or update a step result.\n * Uses upsert to handle both new and existing results.\n */\n async saveStepResult(result: Omit<StepResult, 'id'> & { id?: string }): Promise<void> {\n this.ensureInitialized();\n const id = result.id ?? generateId();\n\n await this.extQb\n .insertInto('stepflow_step_results')\n .values({\n id,\n run_id: result.runId,\n step_name: result.stepName,\n status: result.status,\n output_json: result.output ? JSON.stringify(result.output) : null,\n error_json: result.error ? JSON.stringify(stripStack(result.error)) : null,\n attempt: result.attempt,\n started_at: result.startedAt ?? null,\n completed_at: result.completedAt ?? null,\n })\n .onConflict(oc =>\n oc.columns(['run_id', 'step_name']).doUpdateSet({\n status: result.status,\n output_json: result.output ? JSON.stringify(result.output) : null,\n error_json: result.error ? JSON.stringify(stripStack(result.error)) : null,\n attempt: result.attempt,\n started_at: result.startedAt ?? null,\n completed_at: result.completedAt ?? null,\n })\n )\n .execute();\n }\n\n // ============================================================================\n // Utility Methods\n // ============================================================================\n\n /**\n * Get database statistics.\n */\n async getStats(): Promise<{ runs: number; steps: number; events: number }> {\n this.ensureInitialized();\n const [runsCount, stepsCount, eventsCount] = await Promise.all([\n this.qb.selectFrom('runs').select(sql`count(*)`.as('count')).executeTakeFirst(),\n this.qb.selectFrom('workflow_run_steps').select(sql`count(*)`.as('count')).executeTakeFirst(),\n this.qb.selectFrom('workflow_events').select(sql`count(*)`.as('count')).executeTakeFirst(),\n ]) as { count?: string | number }[];\n\n return {\n runs: Number(runsCount?.count ?? 0),\n steps: Number(stepsCount?.count ?? 0),\n events: Number(eventsCount?.count ?? 0),\n };\n }\n}\n\n// ============================================================================\n// Transaction Adapter (wraps Kysely transaction)\n// ============================================================================\n\n/**\n * A StorageAdapter wrapper for use within transactions.\n *\n * Used internally by `PostgresStorageAdapter.transaction()`. All CRUD methods\n * are inherited from `PostgresStorageCore`; this class only binds the\n * transaction-scoped query builder.\n *\n * Exported for regression testing; not part of the public API.\n */\nexport class PostgresTransactionAdapter extends PostgresStorageCore {\n private readonly _qb: CoreSchemaQueryBuilder;\n\n constructor(trx: KyselyType<StepflowDatabase>, schema: string, logger?: Logger) {\n super(schema, logger);\n this._qb = trx.withSchema(schema) as unknown as CoreSchemaQueryBuilder;\n }\n\n protected override get qb(): CoreSchemaQueryBuilder {\n return this._qb;\n }\n\n protected override get warnLabel(): string {\n return 'PostgresTransactionAdapter';\n }\n}\n\n// Convenience aliases for shorter naming\nexport { PostgresStorageAdapter as PostgresStorage };\nexport type { PostgresStorageConfig as PostgresStorageOptions };\n"],"mappings":";;;;;;;;;;AAgCO,IAAM,uBAAN,MAAqD;AAAA,EAClD,OAAO,oBAAI,IAA+B;AAAA,EAC1C,QAAQ,oBAAI,IAAmC;AAAA,EAC/C,SAAS,oBAAI,IAAiC;AAAA;AAAA;AAAA;AAAA;AAAA,EAOtD,MAAM,UAAU,KAA8E;AAC5F,UAAM,SAA4B;AAAA,MAChC,GAAG;AAAA,MACH,IAAI,WAAW;AAAA,MACf,WAAW,oBAAI,KAAK;AAAA,IACtB;AACA,SAAK,K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,WAAW,OAAO,KAAK,CAAC,IAAI;AAAA,QACtE,SAAS,OAAO;AAAA,QAChB,YAAY,OAAO,aAAa;AAAA,QAChC,cAAc,OAAO,eAAe;AAAA,MACtC,CAAC;AAAA,IACH,EACC,QAAQ;AAAA,EACb;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EASA,MAAM,WAAqE;AACzE,SAAK,kBAAkB;AACvB,UAAM,CAAC,WAAW,YAAY,WAAW,IAAI,MAAM,QAAQ,IAAI;AAAA,MAC7D,KAAK,GAAG,WAAW,MAAM,EAAE,OAAO,cAAc,GAAG,OAAO,CAAC,EAAE,iBAAiB;AAAA,MAC9E,KAAK,GAAG,WAAW,oBAAoB,EAAE,OAAO,cAAc,GAAG,OAAO,CAAC,EAAE,iBAAiB;AAAA,MAC5F,KAAK,GAAG,WAAW,iBAAiB,EAAE,OAAO,cAAc,GAAG,OAAO,CAAC,EAAE,iBAAiB;AAAA,IAC3F,CAAC;AAED,WAAO;AAAA,MACL,MAAM,OAAO,WAAW,SAAS,CAAC;AAAA,MAClC,OAAO,OAAO,YAAY,SAAS,CAAC;AAAA,MACpC,QAAQ,OAAO,aAAa,SAAS,CAAC;AAAA,IACxC;AAAA,EACF;AACF;AAeO,IAAM,6BAAN,cAAyC,oBAAoB;AAAA,EACjD;AAAA,EAEjB,YAAY,KAAmC,QAAgB,QAAiB;AAC9E,UAAM,QAAQ,MAAM;AACpB,SAAK,MAAM,IAAI,WAAW,MAAM;AAAA,EAClC;AAAA,EAEA,IAAuB,KAA6B;AAClD,WAAO,KAAK;AAAA,EACd;AAAA,EAEA,IAAuB,YAAoB;AACzC,WAAO;AAAA,EACT;AACF;","names":["safeParseField","safeParseOptionalField","mapRunRow","mapStepRow","mapEventRow","sql","mapRunRow","mapStepRow","safeParseOptionalField"]}
@@ -1,8 +1,9 @@
1
1
  import {
2
2
  ConsoleLogger,
3
3
  generateId,
4
- loadPostgresDeps
5
- } from "./chunk-ML35PIHX.js";
4
+ loadPostgresDeps,
5
+ safeJsonParse
6
+ } from "./chunk-JPXPB7U5.js";
6
7
 
7
8
  // src/scheduler/cron.ts
8
9
  import { CronExpressionParser } from "cron-parser";
@@ -33,6 +34,14 @@ var CronScheduler = class {
33
34
  this.logger.warn("Scheduler is already running");
34
35
  return;
35
36
  }
37
+ if (this.eventUnsubscribe) {
38
+ this.eventUnsubscribe();
39
+ this.eventUnsubscribe = null;
40
+ }
41
+ if (this.pollTimer) {
42
+ clearInterval(this.pollTimer);
43
+ this.pollTimer = null;
44
+ }
36
45
  this.logger.info("Starting scheduler...");
37
46
  if (this.persistence) {
38
47
  const loaded = await this.persistence.loadSchedules();
@@ -43,7 +52,19 @@ var CronScheduler = class {
43
52
  }
44
53
  for (const schedule of this.schedules.values()) {
45
54
  if (schedule.triggerType === "cron" && schedule.cronExpression) {
46
- this.updateNextRunTime(schedule);
55
+ try {
56
+ CronExpressionParser.parse(schedule.cronExpression, {
57
+ tz: schedule.timezone
58
+ });
59
+ this.updateNextRunTime(schedule);
60
+ } catch (error) {
61
+ this.logger.error(
62
+ `Invalid cron expression "${schedule.cronExpression}" for schedule ${schedule.id}, disabling schedule:`,
63
+ error
64
+ );
65
+ schedule.enabled = false;
66
+ schedule.nextRunAt = void 0;
67
+ }
47
68
  }
48
69
  }
49
70
  this.pollTimer = setInterval(() => this.checkSchedules(), this.pollInterval);
@@ -258,6 +279,7 @@ var CronScheduler = class {
258
279
  var SQLiteSchedulePersistence = class {
259
280
  db;
260
281
  tableName;
282
+ logger;
261
283
  stmts = null;
262
284
  constructor(config) {
263
285
  this.db = config.db;
@@ -265,6 +287,7 @@ var SQLiteSchedulePersistence = class {
265
287
  if (!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(this.tableName)) {
266
288
  throw new Error(`Invalid table name: ${this.tableName}`);
267
289
  }
290
+ this.logger = config.logger;
268
291
  this.initializeDatabase();
269
292
  }
270
293
  // ============================================================================
@@ -391,6 +414,14 @@ var SQLiteSchedulePersistence = class {
391
414
  // ============================================================================
392
415
  // Helper Methods
393
416
  // ============================================================================
417
+ safeJsonParse(json, fallback, rowId, column) {
418
+ return safeJsonParse(json, fallback, {
419
+ component: "SQLiteSchedulePersistence",
420
+ rowId,
421
+ column,
422
+ logger: this.logger
423
+ });
424
+ }
394
425
  rowToSchedule(row) {
395
426
  return {
396
427
  id: row.id,
@@ -399,9 +430,9 @@ var SQLiteSchedulePersistence = class {
399
430
  cronExpression: row.cron_expression ?? void 0,
400
431
  timezone: row.timezone ?? void 0,
401
432
  triggerOnWorkflowKind: row.trigger_on_workflow_kind ?? void 0,
402
- triggerOnStatus: row.trigger_on_status ? JSON.parse(row.trigger_on_status) : void 0,
403
- input: row.input ? JSON.parse(row.input) : void 0,
404
- metadata: row.metadata ? JSON.parse(row.metadata) : void 0,
433
+ triggerOnStatus: row.trigger_on_status ? this.safeJsonParse(row.trigger_on_status, void 0, row.id, "trigger_on_status") : void 0,
434
+ input: row.input ? this.safeJsonParse(row.input, void 0, row.id, "input") : void 0,
435
+ metadata: row.metadata ? this.safeJsonParse(row.metadata, void 0, row.id, "metadata") : void 0,
405
436
  enabled: row.enabled === 1,
406
437
  lastRunAt: row.last_run_at ? new Date(row.last_run_at) : void 0,
407
438
  lastRunId: row.last_run_id ?? void 0,
@@ -424,6 +455,7 @@ var PostgresSchedulePersistence = class {
424
455
  autoMigrate;
425
456
  initialized = false;
426
457
  config;
458
+ logger;
427
459
  constructor(config) {
428
460
  this.schema = config.schema ?? "public";
429
461
  if (!/^[a-zA-Z_][a-zA-Z0-9_]{0,62}$/.test(this.schema)) {
@@ -439,6 +471,7 @@ var PostgresSchedulePersistence = class {
439
471
  }
440
472
  this.autoMigrate = config.autoMigrate !== false;
441
473
  this.config = config;
474
+ this.logger = config.logger;
442
475
  }
443
476
  /**
444
477
  * Get a schema-scoped query builder.
@@ -655,6 +688,18 @@ var PostgresSchedulePersistence = class {
655
688
  // ============================================================================
656
689
  // Helper Methods
657
690
  // ============================================================================
691
+ safeParseOptionalField(value, rowId, column) {
692
+ if (!value) return void 0;
693
+ if (typeof value === "string") {
694
+ return safeJsonParse(value, void 0, {
695
+ component: "PostgresSchedulePersistence",
696
+ rowId,
697
+ column,
698
+ logger: this.logger
699
+ });
700
+ }
701
+ return value;
702
+ }
658
703
  rowToSchedule(row) {
659
704
  return {
660
705
  id: row.id,
@@ -663,9 +708,9 @@ var PostgresSchedulePersistence = class {
663
708
  cronExpression: row.cron_expression ?? void 0,
664
709
  timezone: row.timezone ?? void 0,
665
710
  triggerOnWorkflowKind: row.trigger_on_workflow_kind ?? void 0,
666
- triggerOnStatus: row.trigger_on_status ? typeof row.trigger_on_status === "string" ? JSON.parse(row.trigger_on_status) : row.trigger_on_status : void 0,
667
- input: row.input_json ? typeof row.input_json === "string" ? JSON.parse(row.input_json) : row.input_json : void 0,
668
- metadata: row.metadata_json ? typeof row.metadata_json === "string" ? JSON.parse(row.metadata_json) : row.metadata_json : void 0,
711
+ triggerOnStatus: this.safeParseOptionalField(row.trigger_on_status, row.id, "trigger_on_status"),
712
+ input: this.safeParseOptionalField(row.input_json, row.id, "input_json"),
713
+ metadata: this.safeParseOptionalField(row.metadata_json, row.id, "metadata_json"),
669
714
  enabled: row.enabled,
670
715
  lastRunAt: row.last_run_at ? new Date(row.last_run_at) : void 0,
671
716
  lastRunId: row.last_run_id ?? void 0,
@@ -679,4 +724,4 @@ export {
679
724
  SQLiteSchedulePersistence,
680
725
  PostgresSchedulePersistence
681
726
  };
682
- //# sourceMappingURL=chunk-KHTUWLVZ.js.map
727
+ //# sourceMappingURL=chunk-FMPJBK2N.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/scheduler/cron.ts","../src/scheduler/sqlite-persistence.ts","../src/scheduler/postgres-persistence.ts"],"sourcesContent":["/**\n * CronScheduler - Scheduler implementation using cron expressions.\n *\n * Provides time-based and workflow-completion-based triggers for workflows.\n */\n\nimport { CronExpressionParser } from 'cron-parser';\nimport type { WorkflowKind, RunStatus, Logger } from '../core/types';\nimport type { WorkflowEngine } from '../core/engine';\nimport type { Scheduler, WorkflowSchedule, TriggerType } from './types';\nimport type { WorkflowEvent } from '../events/types';\nimport { generateId } from '../utils/id';\nimport { ConsoleLogger } from '../utils/logger';\n\n// ============================================================================\n// Configuration Types\n// ============================================================================\n\n/**\n * Configuration for the CronScheduler.\n */\nexport interface CronSchedulerConfig {\n /** The workflow engine instance */\n engine: WorkflowEngine;\n\n /** Logger instance */\n logger?: Logger;\n\n /** Poll interval for checking schedules (ms, default: 1000) */\n pollInterval?: number;\n\n /** Optional persistence adapter for schedules */\n persistence?: SchedulePersistence;\n}\n\n/**\n * Interface for schedule persistence.\n * Implement this to persist schedules to a database.\n */\nexport interface SchedulePersistence {\n /** Load all schedules from storage */\n loadSchedules(): Promise<WorkflowSchedule[]>;\n\n /** Save a schedule */\n saveSchedule(schedule: WorkflowSchedule): Promise<void>;\n\n /** Update a schedule */\n updateSchedule(scheduleId: string, updates: Partial<WorkflowSchedule>): Promise<void>;\n\n /** Delete a schedule */\n deleteSchedule(scheduleId: string): Promise<void>;\n}\n\n// ============================================================================\n// CronScheduler Class\n// ============================================================================\n\n/**\n * Scheduler implementation that supports cron expressions and workflow completion triggers.\n *\n * @example\n * ```typescript\n * const scheduler = new CronScheduler({\n * engine,\n * pollInterval: 1000,\n * });\n *\n * // Add a cron schedule (every day at midnight)\n * await scheduler.addSchedule({\n * workflowKind: 'cleanup.daily',\n * triggerType: 'cron',\n * cronExpression: '0 0 * * *',\n * enabled: true,\n * });\n *\n * // Add a workflow completion trigger\n * await scheduler.addSchedule({\n * workflowKind: 'notification.send',\n * triggerType: 'workflow_completed',\n * triggerOnWorkflowKind: 'order.process',\n * triggerOnStatus: ['succeeded'],\n * enabled: true,\n * });\n *\n * await scheduler.start();\n * ```\n */\nexport class CronScheduler implements Scheduler {\n private engine: WorkflowEngine;\n private logger: Logger;\n private pollInterval: number;\n private persistence?: SchedulePersistence;\n\n private schedules = new Map<string, WorkflowSchedule>();\n private running = false;\n private pollTimer: ReturnType<typeof setInterval> | null = null;\n private eventUnsubscribe: (() => void) | null = null;\n\n constructor(config: CronSchedulerConfig) {\n this.engine = config.engine;\n this.logger = config.logger ?? new ConsoleLogger();\n this.pollInterval = config.pollInterval ?? 1000;\n this.persistence = config.persistence;\n }\n\n // ============================================================================\n // Scheduler Interface Implementation\n // ============================================================================\n\n /**\n * Start the scheduler.\n * Begins polling for cron schedules and subscribes to workflow completion events.\n */\n async start(): Promise<void> {\n if (this.running) {\n this.logger.warn('Scheduler is already running');\n return;\n }\n\n // Clean up any leftover subscriptions from a previous start/stop cycle\n if (this.eventUnsubscribe) {\n this.eventUnsubscribe();\n this.eventUnsubscribe = null;\n }\n if (this.pollTimer) {\n clearInterval(this.pollTimer);\n this.pollTimer = null;\n }\n\n this.logger.info('Starting scheduler...');\n\n // Load schedules from persistence if available\n if (this.persistence) {\n const loaded = await this.persistence.loadSchedules();\n for (const schedule of loaded) {\n this.schedules.set(schedule.id, schedule);\n }\n this.logger.info(`Loaded ${loaded.length} schedules from persistence`);\n }\n\n // Calculate next run times for cron schedules.\n // Wrap each schedule in try-catch so one invalid persisted cron expression\n // doesn't prevent the rest from loading.\n for (const schedule of this.schedules.values()) {\n if (schedule.triggerType === 'cron' && schedule.cronExpression) {\n try {\n CronExpressionParser.parse(schedule.cronExpression, {\n tz: schedule.timezone,\n });\n this.updateNextRunTime(schedule);\n } catch (error) {\n this.logger.error(\n `Invalid cron expression \"${schedule.cronExpression}\" for schedule ${schedule.id}, disabling schedule:`,\n error\n );\n schedule.enabled = false;\n schedule.nextRunAt = undefined;\n }\n }\n }\n\n // Start polling for cron schedules\n this.pollTimer = setInterval(() => this.checkSchedules(), this.pollInterval);\n\n // Subscribe to workflow completion events\n this.eventUnsubscribe = this.engine.subscribeToAll((event) => {\n this.handleWorkflowEvent(event);\n });\n\n this.running = true;\n this.logger.info('Scheduler started');\n }\n\n /**\n * Stop the scheduler.\n * Stops polling and unsubscribes from events.\n */\n async stop(): Promise<void> {\n if (!this.running) {\n return;\n }\n\n this.logger.info('Stopping scheduler...');\n\n if (this.pollTimer) {\n clearInterval(this.pollTimer);\n this.pollTimer = null;\n }\n\n if (this.eventUnsubscribe) {\n this.eventUnsubscribe();\n this.eventUnsubscribe = null;\n }\n\n this.running = false;\n this.logger.info('Scheduler stopped');\n }\n\n /**\n * Add a new schedule.\n */\n async addSchedule(scheduleData: Omit<WorkflowSchedule, 'id'>): Promise<WorkflowSchedule> {\n const schedule: WorkflowSchedule = {\n ...scheduleData,\n id: generateId(),\n };\n\n // Validate cron expression if provided\n if (schedule.triggerType === 'cron' && schedule.cronExpression) {\n try {\n CronExpressionParser.parse(schedule.cronExpression, {\n tz: schedule.timezone,\n });\n } catch (error) {\n throw new Error(`Invalid cron expression: ${schedule.cronExpression}`);\n }\n\n // Calculate next run time\n this.updateNextRunTime(schedule);\n }\n\n // Validate workflow completion trigger\n if (schedule.triggerType === 'workflow_completed') {\n if (!schedule.triggerOnWorkflowKind) {\n throw new Error('triggerOnWorkflowKind is required for workflow_completed triggers');\n }\n }\n\n this.schedules.set(schedule.id, schedule);\n\n // Persist if available\n if (this.persistence) {\n await this.persistence.saveSchedule(schedule);\n }\n\n this.logger.info(`Added schedule: ${schedule.id} (${schedule.workflowKind})`);\n\n return schedule;\n }\n\n /**\n * Remove a schedule.\n */\n async removeSchedule(scheduleId: string): Promise<void> {\n if (!this.schedules.has(scheduleId)) {\n throw new Error(`Schedule not found: ${scheduleId}`);\n }\n\n this.schedules.delete(scheduleId);\n\n if (this.persistence) {\n await this.persistence.deleteSchedule(scheduleId);\n }\n\n this.logger.info(`Removed schedule: ${scheduleId}`);\n }\n\n /**\n * Update a schedule.\n */\n async updateSchedule(scheduleId: string, updates: Partial<WorkflowSchedule>): Promise<void> {\n const schedule = this.schedules.get(scheduleId);\n if (!schedule) {\n throw new Error(`Schedule not found: ${scheduleId}`);\n }\n\n // Don't allow changing the ID\n delete updates.id;\n\n // Update the schedule\n Object.assign(schedule, updates);\n\n // Revalidate and update next run time if cron expression changed\n if (updates.cronExpression !== undefined || updates.timezone !== undefined) {\n if (schedule.cronExpression) {\n try {\n CronExpressionParser.parse(schedule.cronExpression, {\n tz: schedule.timezone,\n });\n this.updateNextRunTime(schedule);\n } catch (error) {\n throw new Error(`Invalid cron expression: ${schedule.cronExpression}`);\n }\n }\n }\n\n if (this.persistence) {\n await this.persistence.updateSchedule(scheduleId, updates);\n }\n\n this.logger.debug(`Updated schedule: ${scheduleId}`);\n }\n\n /**\n * Get all schedules.\n */\n async getSchedules(): Promise<WorkflowSchedule[]> {\n return Array.from(this.schedules.values());\n }\n\n /**\n * Get a schedule by ID.\n */\n getSchedule(scheduleId: string): WorkflowSchedule | undefined {\n return this.schedules.get(scheduleId);\n }\n\n /**\n * Manually trigger a scheduled workflow.\n */\n async triggerNow(scheduleId: string): Promise<string> {\n const schedule = this.schedules.get(scheduleId);\n if (!schedule) {\n throw new Error(`Schedule not found: ${scheduleId}`);\n }\n\n return this.executeSchedule(schedule);\n }\n\n // ============================================================================\n // Internal Methods\n // ============================================================================\n\n /**\n * Check all cron schedules and execute those that are due.\n */\n private checkSchedules(): void {\n const now = new Date();\n\n for (const schedule of this.schedules.values()) {\n if (!schedule.enabled) continue;\n if (schedule.triggerType !== 'cron') continue;\n if (!schedule.nextRunAt) continue;\n\n if (schedule.nextRunAt <= now) {\n // Execute the schedule\n this.executeSchedule(schedule).catch((error) => {\n this.logger.error(`Failed to execute schedule ${schedule.id}:`, error);\n });\n\n // Update next run time\n this.updateNextRunTime(schedule);\n }\n }\n }\n\n /**\n * Handle workflow events for completion triggers.\n */\n private handleWorkflowEvent(event: WorkflowEvent): void {\n // Only handle run completion events\n // Note: orchestrator emits 'run.completed' for success, 'run.failed' for failure\n if (event.eventType !== 'run.completed' && event.eventType !== 'run.failed') {\n return;\n }\n\n const completedStatus: RunStatus = event.eventType === 'run.completed' ? 'succeeded' : 'failed';\n const completedKind = event.kind;\n\n // Find schedules triggered by this workflow completion\n for (const schedule of this.schedules.values()) {\n if (!schedule.enabled) continue;\n if (schedule.triggerType !== 'workflow_completed') continue;\n if (schedule.triggerOnWorkflowKind !== completedKind) continue;\n\n // Check if the status matches\n if (schedule.triggerOnStatus && !schedule.triggerOnStatus.includes(completedStatus)) {\n continue;\n }\n\n // Execute the schedule\n this.executeSchedule(schedule, {\n triggerRunId: event.runId,\n triggerStatus: completedStatus,\n }).catch((error) => {\n this.logger.error(`Failed to execute schedule ${schedule.id}:`, error);\n });\n }\n }\n\n /**\n * Execute a schedule by starting the workflow.\n */\n private async executeSchedule(\n schedule: WorkflowSchedule,\n triggerContext?: { triggerRunId?: string; triggerStatus?: RunStatus }\n ): Promise<string> {\n this.logger.info(`Executing schedule: ${schedule.id} (${schedule.workflowKind})`);\n\n // Build metadata with trigger info\n const metadata = {\n ...schedule.metadata,\n scheduleId: schedule.id,\n triggerType: schedule.triggerType,\n ...(triggerContext ?? {}),\n };\n\n // Start the workflow\n const runId = await this.engine.startRun({\n kind: schedule.workflowKind,\n input: schedule.input,\n metadata,\n });\n\n // Update schedule state\n schedule.lastRunAt = new Date();\n schedule.lastRunId = runId;\n\n if (this.persistence) {\n await this.persistence.updateSchedule(schedule.id, {\n lastRunAt: schedule.lastRunAt,\n lastRunId: schedule.lastRunId,\n nextRunAt: schedule.nextRunAt,\n });\n }\n\n return runId;\n }\n\n /**\n * Update the next run time for a cron schedule.\n */\n private updateNextRunTime(schedule: WorkflowSchedule): void {\n if (!schedule.cronExpression) return;\n\n try {\n const interval = CronExpressionParser.parse(schedule.cronExpression, {\n currentDate: new Date(),\n tz: schedule.timezone,\n });\n\n schedule.nextRunAt = interval.next().toDate();\n } catch (error) {\n this.logger.error(`Failed to parse cron expression for schedule ${schedule.id}:`, error);\n schedule.nextRunAt = undefined;\n }\n }\n}\n","/**\n * SQLite persistence adapter for schedules.\n *\n * Stores workflow schedules in a SQLite database table.\n */\n\nimport type { Database, Statement } from 'better-sqlite3';\nimport type { WorkflowSchedule } from './types';\nimport type { SchedulePersistence } from './cron';\nimport type { Logger, RunStatus } from '../core/types';\nimport { generateId } from '../utils/id';\nimport { safeJsonParse as sharedSafeJsonParse } from '../utils/safe-json';\n\n// ============================================================================\n// Configuration Types\n// ============================================================================\n\n/**\n * Configuration for SQLiteSchedulePersistence.\n */\nexport interface SQLiteSchedulePersistenceConfig {\n /** SQLite database instance */\n db: Database;\n\n /** Table name for schedules (default: workflow_schedules) */\n tableName?: string;\n\n /**\n * Optional structured logger used to surface JSON corruption events.\n * Without one, parse failures still increment the corruption counter\n * exposed via `getJsonParseCorruptionCount()` but produce no log output.\n */\n logger?: Logger;\n}\n\n// ============================================================================\n// SQLiteSchedulePersistence Class\n// ============================================================================\n\n/**\n * SQLite-based persistence for workflow schedules.\n *\n * @example\n * ```typescript\n * import Database from 'better-sqlite3';\n *\n * const db = new Database('workflow.db');\n * const persistence = new SQLiteSchedulePersistence({ db });\n *\n * const scheduler = new CronScheduler({\n * engine,\n * persistence,\n * });\n * ```\n */\nexport class SQLiteSchedulePersistence implements SchedulePersistence {\n private db: Database;\n private tableName: string;\n private logger: Logger | undefined;\n private stmts: {\n insert: Statement;\n update: Statement;\n delete: Statement;\n getAll: Statement;\n getById: Statement;\n } | null = null;\n\n constructor(config: SQLiteSchedulePersistenceConfig) {\n this.db = config.db;\n this.tableName = config.tableName ?? 'workflow_schedules';\n if (!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(this.tableName)) {\n throw new Error(`Invalid table name: ${this.tableName}`);\n }\n this.logger = config.logger;\n this.initializeDatabase();\n }\n\n // ============================================================================\n // Database Initialization\n // ============================================================================\n\n private initializeDatabase(): void {\n // Create schedules table.\n // Schema layout:\n // id — unique schedule identifier (TEXT PK)\n // workflow_kind — target workflow type to spawn\n // trigger_type — 'cron', 'workflow_completed', or 'manual'\n // cron_expression — cron expression for time-based triggers (nullable)\n // timezone — IANA timezone for cron evaluation (nullable)\n // trigger_on_* — fields for workflow-completion triggers\n // input / metadata — JSON-serialized payloads for spawned runs\n // enabled — whether this schedule is active (0/1)\n // last_run_at/id — most recent execution tracking\n // next_run_at — next scheduled execution time\n // created_at/updated_at — audit timestamps\n // No migration strategy is currently implemented; table is created idempotently.\n this.db.exec(`\n CREATE TABLE IF NOT EXISTS ${this.tableName} (\n id TEXT PRIMARY KEY,\n workflow_kind TEXT NOT NULL,\n trigger_type TEXT NOT NULL,\n cron_expression TEXT,\n timezone TEXT,\n trigger_on_workflow_kind TEXT,\n trigger_on_status TEXT,\n input TEXT,\n metadata TEXT,\n enabled INTEGER NOT NULL DEFAULT 1,\n last_run_at TEXT,\n last_run_id TEXT,\n next_run_at TEXT,\n created_at TEXT NOT NULL DEFAULT (datetime('now')),\n updated_at TEXT NOT NULL DEFAULT (datetime('now'))\n )\n `);\n\n // Create indexes\n this.db.exec(`\n CREATE INDEX IF NOT EXISTS idx_${this.tableName}_workflow_kind\n ON ${this.tableName}(workflow_kind);\n\n CREATE INDEX IF NOT EXISTS idx_${this.tableName}_enabled\n ON ${this.tableName}(enabled);\n\n CREATE INDEX IF NOT EXISTS idx_${this.tableName}_trigger_type\n ON ${this.tableName}(trigger_type);\n `);\n\n // Prepare statements\n this.stmts = {\n insert: this.db.prepare(`\n INSERT INTO ${this.tableName} (\n id, workflow_kind, trigger_type, cron_expression, timezone,\n trigger_on_workflow_kind, trigger_on_status, input, metadata,\n enabled, last_run_at, last_run_id, next_run_at\n ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)\n `),\n update: this.db.prepare(`\n UPDATE ${this.tableName}\n SET workflow_kind = COALESCE(?, workflow_kind),\n trigger_type = COALESCE(?, trigger_type),\n cron_expression = ?,\n timezone = ?,\n trigger_on_workflow_kind = ?,\n trigger_on_status = ?,\n input = ?,\n metadata = ?,\n enabled = COALESCE(?, enabled),\n last_run_at = ?,\n last_run_id = ?,\n next_run_at = ?,\n updated_at = datetime('now')\n WHERE id = ?\n `),\n delete: this.db.prepare(`\n DELETE FROM ${this.tableName} WHERE id = ?\n `),\n getAll: this.db.prepare(`\n SELECT * FROM ${this.tableName}\n `),\n getById: this.db.prepare(`\n SELECT * FROM ${this.tableName} WHERE id = ?\n `),\n };\n }\n\n // ============================================================================\n // SchedulePersistence Interface Implementation\n // ============================================================================\n\n async loadSchedules(): Promise<WorkflowSchedule[]> {\n const rows = this.stmts!.getAll.all() as ScheduleRow[];\n return rows.map(row => this.rowToSchedule(row));\n }\n\n async saveSchedule(schedule: WorkflowSchedule): Promise<void> {\n this.stmts!.insert.run(\n schedule.id,\n schedule.workflowKind,\n schedule.triggerType,\n schedule.cronExpression ?? null,\n schedule.timezone ?? null,\n schedule.triggerOnWorkflowKind ?? null,\n schedule.triggerOnStatus ? JSON.stringify(schedule.triggerOnStatus) : null,\n schedule.input ? JSON.stringify(schedule.input) : null,\n schedule.metadata ? JSON.stringify(schedule.metadata) : null,\n schedule.enabled ? 1 : 0,\n schedule.lastRunAt?.toISOString() ?? null,\n schedule.lastRunId ?? null,\n schedule.nextRunAt?.toISOString() ?? null\n );\n }\n\n async updateSchedule(scheduleId: string, updates: Partial<WorkflowSchedule>): Promise<void> {\n // Get existing schedule to merge with updates\n const existing = this.stmts!.getById.get(scheduleId) as ScheduleRow | undefined;\n if (!existing) {\n throw new Error(`Schedule not found: ${scheduleId}`);\n }\n\n const merged = {\n ...this.rowToSchedule(existing),\n ...updates,\n };\n\n this.stmts!.update.run(\n updates.workflowKind ?? null,\n updates.triggerType ?? null,\n merged.cronExpression ?? null,\n merged.timezone ?? null,\n merged.triggerOnWorkflowKind ?? null,\n merged.triggerOnStatus ? JSON.stringify(merged.triggerOnStatus) : null,\n merged.input ? JSON.stringify(merged.input) : null,\n merged.metadata ? JSON.stringify(merged.metadata) : null,\n updates.enabled !== undefined ? (updates.enabled ? 1 : 0) : null,\n merged.lastRunAt?.toISOString() ?? null,\n merged.lastRunId ?? null,\n merged.nextRunAt?.toISOString() ?? null,\n scheduleId\n );\n }\n\n async deleteSchedule(scheduleId: string): Promise<void> {\n this.stmts!.delete.run(scheduleId);\n }\n\n // ============================================================================\n // Helper Methods\n // ============================================================================\n\n private safeJsonParse(\n json: string,\n fallback: unknown,\n rowId: string,\n column: string,\n ): unknown {\n return sharedSafeJsonParse(json, fallback, {\n component: 'SQLiteSchedulePersistence',\n rowId,\n column,\n logger: this.logger,\n });\n }\n\n private rowToSchedule(row: ScheduleRow): WorkflowSchedule {\n return {\n id: row.id,\n workflowKind: row.workflow_kind,\n triggerType: row.trigger_type as WorkflowSchedule['triggerType'],\n cronExpression: row.cron_expression ?? undefined,\n timezone: row.timezone ?? undefined,\n triggerOnWorkflowKind: row.trigger_on_workflow_kind ?? undefined,\n triggerOnStatus: row.trigger_on_status\n ? this.safeJsonParse(row.trigger_on_status, undefined, row.id, 'trigger_on_status') as RunStatus[] | undefined\n : undefined,\n input: row.input ? this.safeJsonParse(row.input, undefined, row.id, 'input') as Record<string, unknown> | undefined : undefined,\n metadata: row.metadata ? this.safeJsonParse(row.metadata, undefined, row.id, 'metadata') as Record<string, unknown> | undefined : undefined,\n enabled: row.enabled === 1,\n lastRunAt: row.last_run_at ? new Date(row.last_run_at) : undefined,\n lastRunId: row.last_run_id ?? undefined,\n nextRunAt: row.next_run_at ? new Date(row.next_run_at) : undefined,\n };\n }\n}\n\n// ============================================================================\n// Types\n// ============================================================================\n\ninterface ScheduleRow {\n id: string;\n workflow_kind: string;\n trigger_type: string;\n cron_expression: string | null;\n timezone: string | null;\n trigger_on_workflow_kind: string | null;\n trigger_on_status: string | null;\n input: string | null;\n metadata: string | null;\n enabled: number;\n last_run_at: string | null;\n last_run_id: string | null;\n next_run_at: string | null;\n created_at: string;\n updated_at: string;\n}\n","/**\n * PostgreSQL persistence adapter for schedules.\n *\n * Stores workflow schedules in a PostgreSQL database table using Kysely.\n */\n\nimport type { Kysely as KyselyType } from 'kysely';\nimport type { Pool, PoolConfig } from 'pg';\nimport { loadPostgresDeps } from '../utils/postgres-deps.js';\n\n// Lazy-loaded dependencies - populated by loadPostgresDeps() during initialize()\nlet Kysely: any;\nlet PostgresDialect: any;\nlet sql: any;\nlet pgModule: any;\nimport type { WorkflowSchedule } from './types.js';\nimport type { SchedulePersistence } from './cron.js';\nimport type { Logger, RunStatus } from '../core/types.js';\nimport { safeJsonParse as sharedSafeJsonParse } from '../utils/safe-json.js';\n\n// ============================================================================\n// Database Types (Kysely schema)\n// ============================================================================\n\n/** Kysely row type for the workflow_schedules table. */\ninterface WorkflowSchedulesTable {\n id: string;\n /** Workflow kind this schedule targets. */\n workflow_kind: string;\n /** Trigger type: 'cron', 'workflow_completed', or 'manual'. */\n trigger_type: string;\n /** Cron expression for time-based triggers, null for non-cron schedules. */\n cron_expression: string | null;\n /** IANA timezone for cron evaluation, null defaults to UTC. */\n timezone: string | null;\n /** Workflow kind that triggers on completion, null for non-completion triggers. */\n trigger_on_workflow_kind: string | null;\n /** JSON-serialized array of RunStatus values that activate the trigger. */\n trigger_on_status: string | null;\n /** JSON-serialized input payload for spawned runs. */\n input_json: string | null;\n /** JSON-serialized arbitrary metadata for spawned runs. */\n metadata_json: string | null;\n /** Whether this schedule is active. */\n enabled: boolean;\n /** Timestamp of the most recent run spawned by this schedule. */\n last_run_at: Date | null;\n /** Run ID of the most recent run spawned by this schedule. */\n last_run_id: string | null;\n /** Next scheduled execution time. */\n next_run_at: Date | null;\n created_at: Date;\n updated_at: Date;\n}\n\ninterface SchedulesDatabase {\n workflow_schedules: WorkflowSchedulesTable;\n}\n\n// ============================================================================\n// Configuration Types\n// ============================================================================\n\n/**\n * Configuration for PostgresSchedulePersistence.\n */\nexport interface PostgresSchedulePersistenceConfig {\n /**\n * PostgreSQL connection string.\n * Example: \"postgresql://user:pass@localhost:5432/dbname\"\n */\n connectionString?: string;\n\n /**\n * Existing pg.Pool instance for connection sharing with application.\n * If provided, the adapter will not close this pool on close().\n */\n pool?: Pool;\n\n /**\n * Pool configuration options (if not providing pool or connectionString).\n */\n poolConfig?: PoolConfig;\n\n /**\n * Schema name for the schedules table.\n * @default 'public'\n */\n schema?: string;\n\n /**\n * Table name for schedules.\n * @default 'workflow_schedules'\n */\n tableName?: string;\n\n /**\n * Automatically create tables on initialization.\n * @default true\n */\n autoMigrate?: boolean;\n\n /**\n * Optional structured logger used to surface JSON corruption events.\n * Without one, parse failures still increment the corruption counter\n * exposed via `getJsonParseCorruptionCount()` but produce no log output.\n */\n logger?: Logger;\n}\n\n// ============================================================================\n// PostgresSchedulePersistence Class\n// ============================================================================\n\n/**\n * PostgreSQL-based persistence for workflow schedules.\n *\n * @example\n * ```typescript\n * const persistence = new PostgresSchedulePersistence({\n * connectionString: process.env.DATABASE_URL,\n * });\n *\n * await persistence.initialize();\n *\n * const scheduler = new CronScheduler({\n * engine,\n * persistence,\n * });\n * ```\n *\n * @example Sharing connection pool\n * ```typescript\n * import pg from 'pg';\n *\n * const pool = new pg.Pool({\n * connectionString: process.env.DATABASE_URL,\n * });\n *\n * const persistence = new PostgresSchedulePersistence({ pool });\n * await persistence.initialize();\n * ```\n */\nexport class PostgresSchedulePersistence implements SchedulePersistence {\n private db!: KyselyType<SchedulesDatabase>;\n private pool!: Pool;\n private ownsPool = false;\n private schema: string;\n private tableName: string;\n private autoMigrate: boolean;\n private initialized = false;\n private config: PostgresSchedulePersistenceConfig;\n private logger: Logger | undefined;\n\n constructor(config: PostgresSchedulePersistenceConfig) {\n this.schema = config.schema ?? 'public';\n if (!/^[a-zA-Z_][a-zA-Z0-9_]{0,62}$/.test(this.schema)) {\n throw new Error(\n `Invalid schema name \"${this.schema}\". Schema must start with a letter or underscore, ` +\n `contain only alphanumeric characters and underscores, and be at most 63 characters.`\n );\n }\n this.tableName = config.tableName ?? 'workflow_schedules';\n if (!/^[a-zA-Z_][a-zA-Z0-9_]{0,62}$/.test(this.tableName)) {\n throw new Error(\n `Invalid table name \"${this.tableName}\". Table name must start with a letter or underscore, ` +\n `contain only alphanumeric characters and underscores, and be at most 63 characters.`\n );\n }\n this.autoMigrate = config.autoMigrate !== false;\n this.config = config;\n this.logger = config.logger;\n }\n\n /**\n * Get a schema-scoped query builder.\n * All queries MUST use this instead of this.db directly to respect config.schema.\n */\n private get qb() {\n return this.db.withSchema(this.schema);\n }\n\n private ensureInitialized(): void {\n if (!this.initialized) {\n throw new Error(\n 'PostgresSchedulePersistence is not initialized. Call initialize() before using the adapter.'\n );\n }\n }\n\n /**\n * Initialize the persistence layer.\n * Creates the schedules table if autoMigrate is enabled.\n */\n async initialize(): Promise<void> {\n if (this.initialized) {\n return;\n }\n\n const deps = await loadPostgresDeps();\n Kysely = deps.Kysely;\n PostgresDialect = deps.PostgresDialect;\n sql = deps.sql;\n pgModule = deps.pgModule;\n\n if (this.config.pool) {\n this.pool = this.config.pool;\n this.ownsPool = false;\n } else if (this.config.connectionString) {\n this.pool = new pgModule.Pool({ connectionString: this.config.connectionString });\n this.ownsPool = true;\n } else if (this.config.poolConfig) {\n this.pool = new pgModule.Pool(this.config.poolConfig);\n this.ownsPool = true;\n } else {\n throw new Error(\n 'PostgresSchedulePersistenceConfig must include either pool, connectionString, or poolConfig'\n );\n }\n\n this.db = new Kysely({\n dialect: new PostgresDialect({\n pool: this.pool,\n }),\n });\n\n if (this.autoMigrate) {\n await this.createTables();\n }\n\n this.initialized = true;\n }\n\n /**\n * Close the database connection.\n * Only closes the pool if it was created by this adapter.\n */\n async close(): Promise<void> {\n await this.db.destroy();\n if (this.ownsPool) {\n await this.pool.end();\n }\n }\n\n // ============================================================================\n // Database Initialization\n // ============================================================================\n\n private async createTables(): Promise<void> {\n const fullTableName = this.schema === 'public'\n ? this.tableName\n : `${this.schema}.${this.tableName}`;\n\n // Create schema if not public\n if (this.schema !== 'public') {\n await sql`CREATE SCHEMA IF NOT EXISTS ${sql.ref(this.schema)}`.execute(this.db);\n }\n\n // Create schedules table.\n // Schema layout:\n // id — unique schedule identifier (TEXT PK)\n // workflow_kind — target workflow type to spawn\n // trigger_type — constrained to 'cron' | 'workflow_completed' | 'manual'\n // cron_expression / timezone — cron trigger configuration\n // trigger_on_workflow_kind — completion trigger source kind\n // trigger_on_status — JSONB array of RunStatus values for completion triggers\n // input_json / metadata_json — JSONB payloads for spawned runs\n // enabled — whether this schedule is active\n // last_run_at / last_run_id — most recent execution tracking\n // next_run_at — next scheduled execution time\n // created_at / updated_at — audit timestamps (TIMESTAMPTZ)\n // No migration strategy is currently implemented; table is created idempotently.\n await sql`\n CREATE TABLE IF NOT EXISTS ${sql.table(fullTableName)} (\n id TEXT PRIMARY KEY,\n workflow_kind TEXT NOT NULL,\n trigger_type TEXT NOT NULL,\n cron_expression TEXT,\n timezone TEXT DEFAULT 'UTC',\n trigger_on_workflow_kind TEXT,\n trigger_on_status JSONB,\n input_json JSONB NOT NULL DEFAULT '{}',\n metadata_json JSONB NOT NULL DEFAULT '{}',\n enabled BOOLEAN NOT NULL DEFAULT true,\n last_run_at TIMESTAMPTZ,\n last_run_id TEXT,\n next_run_at TIMESTAMPTZ,\n created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),\n updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),\n CONSTRAINT ${sql.ref(`${this.tableName}_trigger_type_check`)} CHECK (\n trigger_type IN ('cron', 'workflow_completed', 'manual')\n )\n )\n `.execute(this.db);\n\n // Create indexes\n await sql`\n CREATE INDEX IF NOT EXISTS ${sql.ref(`idx_${this.tableName}_workflow_kind`)}\n ON ${sql.table(fullTableName)} (workflow_kind)\n `.execute(this.db);\n\n await sql`\n CREATE INDEX IF NOT EXISTS ${sql.ref(`idx_${this.tableName}_enabled`)}\n ON ${sql.table(fullTableName)} (enabled)\n `.execute(this.db);\n\n await sql`\n CREATE INDEX IF NOT EXISTS ${sql.ref(`idx_${this.tableName}_trigger_type`)}\n ON ${sql.table(fullTableName)} (trigger_type)\n `.execute(this.db);\n\n await sql`\n CREATE INDEX IF NOT EXISTS ${sql.ref(`idx_${this.tableName}_next_run`)}\n ON ${sql.table(fullTableName)} (next_run_at)\n WHERE enabled = true\n `.execute(this.db);\n }\n\n // ============================================================================\n // SchedulePersistence Interface Implementation\n // ============================================================================\n\n async loadSchedules(): Promise<WorkflowSchedule[]> {\n this.ensureInitialized();\n const rows = await this.qb\n .selectFrom(this.tableName as any)\n .selectAll()\n .execute() as WorkflowSchedulesTable[];\n\n return rows.map(row => this.rowToSchedule(row));\n }\n\n async saveSchedule(schedule: WorkflowSchedule): Promise<void> {\n this.ensureInitialized();\n await this.qb\n .insertInto(this.tableName as any)\n .values({\n id: schedule.id,\n workflow_kind: schedule.workflowKind,\n trigger_type: schedule.triggerType,\n cron_expression: schedule.cronExpression ?? null,\n timezone: schedule.timezone ?? null,\n trigger_on_workflow_kind: schedule.triggerOnWorkflowKind ?? null,\n trigger_on_status: schedule.triggerOnStatus ? JSON.stringify(schedule.triggerOnStatus) : null,\n input_json: schedule.input ? JSON.stringify(schedule.input) : null,\n metadata_json: schedule.metadata ? JSON.stringify(schedule.metadata) : null,\n enabled: schedule.enabled,\n last_run_at: schedule.lastRunAt ?? null,\n last_run_id: schedule.lastRunId ?? null,\n next_run_at: schedule.nextRunAt ?? null,\n created_at: new Date(),\n updated_at: new Date(),\n })\n .execute();\n }\n\n async updateSchedule(scheduleId: string, updates: Partial<WorkflowSchedule>): Promise<void> {\n this.ensureInitialized();\n // Partial update pattern: fetch the existing row, merge with incoming updates,\n // then build a column-level update object. Each field is only included if it was\n // explicitly provided in `updates` (or affected by the merge), so unchanged\n // columns are left untouched in the database.\n const existing = await this.qb\n .selectFrom(this.tableName as any)\n .selectAll()\n .where('id', '=', scheduleId)\n .executeTakeFirst() as WorkflowSchedulesTable | undefined;\n\n if (!existing) {\n throw new Error(`Schedule not found: ${scheduleId}`);\n }\n\n const merged = {\n ...this.rowToSchedule(existing),\n ...updates,\n };\n\n // Field mapping: { domainKey, dbKey, serialize? }\n // Each entry maps a WorkflowSchedule field to its DB column, with optional serialization.\n const fieldMappings: Array<{\n domainKey: keyof WorkflowSchedule;\n dbKey: keyof WorkflowSchedulesTable;\n serialize?: (value: any) => any;\n }> = [\n { domainKey: 'workflowKind', dbKey: 'workflow_kind' },\n { domainKey: 'triggerType', dbKey: 'trigger_type' },\n { domainKey: 'cronExpression', dbKey: 'cron_expression' },\n { domainKey: 'timezone', dbKey: 'timezone' },\n { domainKey: 'triggerOnWorkflowKind', dbKey: 'trigger_on_workflow_kind' },\n { domainKey: 'triggerOnStatus', dbKey: 'trigger_on_status', serialize: v => v ? JSON.stringify(v) : null },\n { domainKey: 'input', dbKey: 'input_json', serialize: v => v ? JSON.stringify(v) : null },\n { domainKey: 'metadata', dbKey: 'metadata_json', serialize: v => v ? JSON.stringify(v) : null },\n { domainKey: 'enabled', dbKey: 'enabled' },\n { domainKey: 'lastRunAt', dbKey: 'last_run_at' },\n { domainKey: 'lastRunId', dbKey: 'last_run_id' },\n { domainKey: 'nextRunAt', dbKey: 'next_run_at' },\n ];\n\n const updateData: Partial<WorkflowSchedulesTable> = {\n updated_at: new Date(),\n };\n\n for (const { domainKey, dbKey, serialize } of fieldMappings) {\n if (updates[domainKey] !== undefined || merged[domainKey] !== undefined) {\n const value = serialize\n ? serialize(merged[domainKey])\n : (merged[domainKey] ?? null);\n (updateData as any)[dbKey] = value;\n }\n }\n\n await this.qb\n .updateTable(this.tableName as any)\n .set(updateData)\n .where('id', '=', scheduleId)\n .execute();\n }\n\n async deleteSchedule(scheduleId: string): Promise<void> {\n this.ensureInitialized();\n await this.qb\n .deleteFrom(this.tableName as any)\n .where('id', '=', scheduleId)\n .execute();\n }\n\n // ============================================================================\n // Additional Methods\n // ============================================================================\n\n /**\n * Get a schedule by ID.\n */\n async getSchedule(scheduleId: string): Promise<WorkflowSchedule | null> {\n this.ensureInitialized();\n const row = await this.qb\n .selectFrom(this.tableName as any)\n .selectAll()\n .where('id', '=', scheduleId)\n .executeTakeFirst() as WorkflowSchedulesTable | undefined;\n\n return row ? this.rowToSchedule(row) : null;\n }\n\n /**\n * Get all enabled schedules that are due to run.\n */\n async getDueSchedules(): Promise<WorkflowSchedule[]> {\n this.ensureInitialized();\n const now = new Date();\n\n const rows = await this.qb\n .selectFrom(this.tableName as any)\n .selectAll()\n .where('enabled', '=', true)\n .where('trigger_type', '=', 'cron')\n .where('next_run_at', '<=', now)\n .execute() as WorkflowSchedulesTable[];\n\n return rows.map(row => this.rowToSchedule(row));\n }\n\n /**\n * Get schedules by workflow kind.\n */\n async getSchedulesByWorkflowKind(workflowKind: string): Promise<WorkflowSchedule[]> {\n this.ensureInitialized();\n const rows = await this.qb\n .selectFrom(this.tableName as any)\n .selectAll()\n .where('workflow_kind', '=', workflowKind)\n .execute() as WorkflowSchedulesTable[];\n\n return rows.map(row => this.rowToSchedule(row));\n }\n\n /**\n * Get workflow completion triggers for a specific workflow kind.\n */\n async getCompletionTriggers(triggerOnWorkflowKind: string): Promise<WorkflowSchedule[]> {\n this.ensureInitialized();\n const rows = await this.qb\n .selectFrom(this.tableName as any)\n .selectAll()\n .where('enabled', '=', true)\n .where('trigger_type', '=', 'workflow_completed')\n .where('trigger_on_workflow_kind', '=', triggerOnWorkflowKind)\n .execute() as WorkflowSchedulesTable[];\n\n return rows.map(row => this.rowToSchedule(row));\n }\n\n // ============================================================================\n // Helper Methods\n // ============================================================================\n\n private safeParseOptionalField(value: unknown, rowId: string, column: string): unknown {\n if (!value) return undefined;\n if (typeof value === 'string') {\n return sharedSafeJsonParse(value, undefined, {\n component: 'PostgresSchedulePersistence',\n rowId,\n column,\n logger: this.logger,\n });\n }\n return value;\n }\n\n private rowToSchedule(row: WorkflowSchedulesTable): WorkflowSchedule {\n return {\n id: row.id,\n workflowKind: row.workflow_kind,\n triggerType: row.trigger_type as WorkflowSchedule['triggerType'],\n cronExpression: row.cron_expression ?? undefined,\n timezone: row.timezone ?? undefined,\n triggerOnWorkflowKind: row.trigger_on_workflow_kind ?? undefined,\n triggerOnStatus: this.safeParseOptionalField(row.trigger_on_status, row.id, 'trigger_on_status') as RunStatus[] | undefined,\n input: this.safeParseOptionalField(row.input_json, row.id, 'input_json') as Record<string, unknown> | undefined,\n metadata: this.safeParseOptionalField(row.metadata_json, row.id, 'metadata_json') as Record<string, unknown> | undefined,\n enabled: row.enabled,\n lastRunAt: row.last_run_at ? new Date(row.last_run_at) : undefined,\n lastRunId: row.last_run_id ?? undefined,\n nextRunAt: row.next_run_at ? new Date(row.next_run_at) : undefined,\n };\n }\n}\n\n// Convenience alias for shorter naming\nexport type { PostgresSchedulePersistenceConfig as PostgresSchedulePersistenceOptions };\n"],"mappings":";;;;;;;;AAMA,SAAS,4BAA4B;AAiF9B,IAAM,gBAAN,MAAyC;AAAA,EACtC;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EAEA,YAAY,oBAAI,IAA8B;AAAA,EAC9C,UAAU;AAAA,EACV,YAAmD;AAAA,EACnD,mBAAwC;AAAA,EAEhD,YAAY,QAA6B;AACvC,SAAK,SAAS,OAAO;AACrB,SAAK,SAAS,OAAO,UAAU,IAAI,cAAc;AACjD,SAAK,eAAe,OAAO,gBAAgB;AAC3C,SAAK,cAAc,OAAO;AAAA,EAC5B;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAUA,MAAM,QAAuB;AAC3B,QAAI,KAAK,SAAS;AAChB,WAAK,OAAO,KAAK,8BAA8B;AAC/C;AAAA,IACF;AAGA,QAAI,KAAK,kBAAkB;AACzB,WAAK,iBAAiB;AACtB,WAAK,mBAAmB;AAAA,IAC1B;AACA,QAAI,KAAK,WAAW;AAClB,oBAAc,KAAK,SAAS;AAC5B,WAAK,YAAY;AAAA,IACnB;AAEA,SAAK,OAAO,KAAK,uBAAuB;AAGxC,QAAI,KAAK,aAAa;AACpB,YAAM,SAAS,MAAM,KAAK,YAAY,cAAc;AACpD,iBAAW,YAAY,QAAQ;AAC7B,aAAK,UAAU,IAAI,SAAS,IAAI,QAAQ;AAAA,MAC1C;AACA,WAAK,OAAO,KAAK,UAAU,OAAO,MAAM,6BAA6B;AAAA,IACvE;AAKA,eAAW,YAAY,KAAK,UAAU,OAAO,GAAG;AAC9C,UAAI,SAAS,gBAAgB,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