@multiplier-labs/stepflow 0.3.4 → 0.3.6
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +9 -0
- package/dist/{chunk-U3PCVK6O.js → chunk-D5HW7VEG.js} +4 -2
- package/dist/chunk-D5HW7VEG.js.map +1 -0
- package/dist/{chunk-5XJBAPXF.js → chunk-JUPZEBR3.js} +3 -1
- package/dist/{chunk-5XJBAPXF.js.map → chunk-JUPZEBR3.js.map} +1 -1
- package/dist/events/index.d.ts +2 -0
- package/dist/events/index.js +1 -1
- package/dist/index.js +2 -2
- package/dist/storage/index.js +1 -1
- package/package.json +23 -12
- package/.codekin/reports/code-review/2026-04-11_code-review-daily.md +0 -146
- package/.codekin/reports/code-review/2026-04-13_code-review-daily.md +0 -74
- package/.codekin/reports/comments/2026-04-04_comment-assessment.md +0 -179
- package/.codekin/reports/comments/2026-04-11_comment-assessment.md +0 -161
- package/.codekin/reports/comments/2026-04-14_comment-assessment.md +0 -34
- package/.codekin/reports/complexity/2026-04-03_complexity-report.md +0 -152
- package/.codekin/reports/complexity/2026-04-11_complexity-report.md +0 -152
- package/.codekin/reports/complexity/2026-04-14_complexity-report.md +0 -34
- package/.codekin/reports/dependencies/2026-04-04_dependency-health.md +0 -94
- package/.codekin/reports/dependencies/2026-04-11_dependency-health.md +0 -93
- package/.codekin/reports/docs-audit/2026-04-04_docs-audit.md +0 -10
- package/.codekin/reports/docs-audit/2026-04-11_docs-audit.md +0 -138
- package/.codekin/reports/docs-audit/2026-04-13_docs-audit.md +0 -121
- package/.codekin/reports/security/2026-04-03_security-audit.md +0 -208
- package/.codekin/reports/security/2026-04-11_security-audit.md +0 -297
- package/.github/CODEOWNERS +0 -15
- package/.github/dependabot.yml +0 -23
- package/.github/workflows/ci.yml +0 -38
- package/.github/workflows/publish.yml +0 -42
- package/.github/workflows/security.yml +0 -29
- package/CHANGELOG.md +0 -34
- package/SECURITY.md +0 -40
- package/dist/chunk-U3PCVK6O.js.map +0 -1
- package/docs/github-packages-setup.md +0 -97
- package/docs/stepflow-api-reference.md +0 -1663
- package/src/core/engine/concurrency.ts +0 -229
- package/src/core/engine/lifecycle.ts +0 -176
- package/src/core/engine.test.ts +0 -1435
- package/src/core/engine.ts +0 -598
- package/src/core/index.ts +0 -7
- package/src/core/orchestrator/persistence.ts +0 -165
- package/src/core/orchestrator/plan-resolution.ts +0 -140
- package/src/core/orchestrator/state-transitions.ts +0 -109
- package/src/core/orchestrator/step-runner.ts +0 -427
- package/src/core/orchestrator.ts +0 -252
- package/src/core/types.ts +0 -220
- package/src/events/index.ts +0 -8
- package/src/events/memory.test.ts +0 -107
- package/src/events/memory.ts +0 -92
- package/src/events/socketio.test.ts +0 -378
- package/src/events/socketio.ts +0 -262
- package/src/events/types.ts +0 -118
- package/src/events/webhook.test.ts +0 -949
- package/src/events/webhook.ts +0 -807
- package/src/index.ts +0 -270
- package/src/planning/evaluate-condition.test.ts +0 -153
- package/src/planning/evaluate-condition.ts +0 -105
- package/src/planning/index.ts +0 -55
- package/src/planning/planner.ts +0 -494
- package/src/planning/planning.test.ts +0 -727
- package/src/planning/registry.test.ts +0 -398
- package/src/planning/registry.ts +0 -283
- package/src/planning/types.ts +0 -566
- package/src/scheduler/cron.test.ts +0 -479
- package/src/scheduler/cron.ts +0 -438
- package/src/scheduler/index.ts +0 -8
- package/src/scheduler/postgres-persistence.ts +0 -530
- package/src/scheduler/sqlite-persistence.test.ts +0 -235
- package/src/scheduler/sqlite-persistence.ts +0 -286
- package/src/scheduler/types.ts +0 -73
- package/src/storage/index.ts +0 -27
- package/src/storage/memory.test.ts +0 -349
- package/src/storage/memory.ts +0 -227
- package/src/storage/postgres-core.ts +0 -550
- package/src/storage/postgres-migration.test.ts +0 -69
- package/src/storage/postgres-transaction-pagination.test.ts +0 -107
- package/src/storage/postgres.ts +0 -835
- package/src/storage/sqlite-core.ts +0 -151
- package/src/storage/sqlite.test.ts +0 -642
- package/src/storage/sqlite.ts +0 -717
- package/src/storage/types.ts +0 -343
- package/src/utils/errors.test.ts +0 -150
- package/src/utils/errors.ts +0 -161
- package/src/utils/id.ts +0 -21
- package/src/utils/index.ts +0 -10
- package/src/utils/logger.test.ts +0 -121
- package/src/utils/logger.ts +0 -96
- package/src/utils/pinned-fetch.test.ts +0 -84
- package/src/utils/pinned-fetch.ts +0 -118
- package/src/utils/postgres-deps.ts +0 -79
- package/src/utils/retry.test.ts +0 -177
- package/src/utils/retry.ts +0 -121
- package/src/utils/safe-json.test.ts +0 -166
- package/src/utils/safe-json.ts +0 -107
- package/src/utils/webhook-signature.test.ts +0 -111
- package/src/utils/webhook-signature.ts +0 -74
- package/tsconfig.json +0 -21
- package/tsup.config.ts +0 -14
- package/vitest.config.ts +0 -9
|
@@ -1 +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,KAAK,IAAI,OAAO,IAAI,MAAM;AAC/B,WAAO;AAAA,EACT;AAAA;AAAA,EAGA,MAAM,OAAO,OAAkD;AAC7D,WAAO,KAAK,KAAK,IAAI,KAAK,KAAK;AAAA,EACjC;AAAA;AAAA,EAGA,MAAM,UAAU,OAAe,SAAoD;AACjF,UAAM,MAAM,KAAK,KAAK,IAAI,KAAK;AAC/B,QAAI,KAAK;AACP,aAAO,OAAO,KAAK,OAAO;AAAA,IAC5B;AAAA,EACF;AAAA;AAAA,EAGA,MAAM,SAAS,UAA2B,CAAC,GAAgD;AACzF,QAAI,QAAQ,MAAM,KAAK,KAAK,KAAK,OAAO,CAAC;AAGzC,QAAI,QAAQ,MAAM;AAChB,cAAQ,MAAM,OAAO,OAAK,EAAE,SAAS,QAAQ,IAAI;AAAA,IACnD;AAGA,QAAI,QAAQ,QAAQ;AAClB,YAAM,WAAW,MAAM,QAAQ,QAAQ,MAAM,IAAI,QAAQ,SAAS,CAAC,QAAQ,MAAM;AACjF,cAAQ,MAAM,OAAO,OAAK,SAAS,SAAS,EAAE,MAAM,CAAC;AAAA,IACvD;AAGA,QAAI,QAAQ,gBAAgB,QAAW;AACrC,cAAQ,MAAM,OAAO,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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
|
+
{"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 PostgresSt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AiB;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"]}
|
package/dist/events/index.d.ts
CHANGED
|
@@ -19,6 +19,8 @@ declare class MemoryEventTransport implements EventTransport {
|
|
|
19
19
|
constructor();
|
|
20
20
|
/**
|
|
21
21
|
* Emit an event to all subscribers.
|
|
22
|
+
* Each channel is isolated so a failing listener on one channel
|
|
23
|
+
* cannot prevent delivery to the others.
|
|
22
24
|
*/
|
|
23
25
|
emit(event: WorkflowEvent): void;
|
|
24
26
|
/**
|