Data Layer
This document defines the data adapter contract, how Zakardo integrates with developer-chosen ORMs, how schema metadata flows to the Planner, how mode-aware connections work, how Zakardo-managed tables coexist with business tables, and what the official adapters provide. It is the specification for everything between Zakardo’s execution model and the database.
Prerequisites: This document assumes familiarity with System Architecture, Full-Stack Framework, Capability System, and Execution Engine.
1. Design Principles
Section titled “1. Design Principles”1.1 Zakardo Does Not Own Business Data
Section titled “1.1 Zakardo Does Not Own Business Data”Zakardo does not provide a database, an ORM, or a query builder. The developer chooses their database (PostgreSQL, MySQL, SQLite, etc.) and their ORM (Prisma, Drizzle, etc.). Capabilities write native ORM code to read and write business data.
Zakardo provides:
- A thin Data Adapter contract that adapters implement.
- Official adapters for Prisma and Drizzle that implement this contract.
- Mode-aware connection switching so the same capability code runs against different databases in different execution modes.
- Schema metadata extraction so the Planner understands what business entities exist.
- Trace integration via proxy wrappers that record database operations.
- Zakardo-managed tables for its own runtime state (executions, traces, plans, etc.).
Zakardo does NOT:
- Generate queries.
- Abstract or wrap the ORM’s query API.
- Own or manage business data migrations.
- Enforce a particular data modeling style.
1.2 Capabilities Use the Native ORM Client
Section titled “1.2 Capabilities Use the Native ORM Client”Capabilities receive the ORM client via context.services.db. They call the ORM’s native API directly:
// Prisma: native Prisma Client APIconst customer = await context.services.db.customer.findUnique({ where: { id: input.customer_id }, include: { orders: true },});
// Drizzle: native Drizzle query APIconst customer = await context.services.db .select() .from(customers) .where(eq(customers.id, input.customer_id));There is no context.db.zakardoQuery(...) or any Zakardo-specific query interface. The developer writes the same code they would write outside of Zakardo.
1.3 One Database, Two Owners
Section titled “1.3 One Database, Two Owners”A Zakardo application has one database with two sets of tables:
| Owner | Tables | Managed By | Migrated By |
|---|---|---|---|
| Developer | Business tables (customers, orders, invoices, etc.) | Developer via their ORM | Developer’s ORM migration tooling (Prisma Migrate, Drizzle Kit) |
| Zakardo | Runtime tables (executions, traces, plans, policies, etc.) | Zakardo runtime | Zakardo’s built-in migration system (runs on startup) |
Both sets of tables live in the same database. They do not conflict because Zakardo tables use a zakardo_ prefix.
2. Data Adapter Contract
Section titled “2. Data Adapter Contract”2.1 Interface
Section titled “2.1 Interface”The DataAdapter is the contract that every data adapter must implement. It is a TypeScript interface exported from @zakardo/core.
interface DataAdapter<TClient = unknown> { /** * Unique identifier for this adapter (e.g., 'prisma', 'drizzle'). */ readonly id: string;
/** * Initialize the adapter. Called once on startup. * Should establish connections, run health checks, etc. */ initialize(config: DataAdapterConfig): Promise<void>;
/** * Shut down the adapter. Called on graceful shutdown. * Should close connections, flush pending operations. */ shutdown(): Promise<void>;
/** * Return the native ORM client for the given execution mode. * This is what capabilities receive via context.services.db. */ getClient(mode: ExecutionMode): TClient;
/** * Return a traced proxy of the client that records operations * to the active Trace. Called by the Execution Engine before * injecting the client into capability context. */ getTracedClient(mode: ExecutionMode, traceContext: TraceContext): TClient;
/** * Extract schema metadata from the ORM's data model. * Returns a normalized representation of tables, columns, * types, and relations that the Planner can use. */ getSchemaMetadata(): Promise<SchemaMetadata>;
/** * Run Zakardo's internal migrations (zakardo_* tables). * Called on startup before any other runtime operations. */ runZakardoMigrations(): Promise<MigrationResult>;
/** * Check if there are pending developer migrations. * Used by `zakardo dev` to prompt the developer. */ hasPendingMigrations(): Promise<boolean>;
/** * Delegate to the ORM's migration tool. * Used by `zakardo migrate` CLI command. */ runMigrations(options?: MigrationOptions): Promise<MigrationResult>;
/** * Health check. Returns true if the database is reachable. */ healthCheck(): Promise<boolean>;
/** * Begin a transaction. Returns a transactional client that * capabilities can use. If the capability fails, the transaction * is rolled back. */ transaction<T>(mode: ExecutionMode, fn: (tx: TClient) => Promise<T>): Promise<T>;}2.2 Configuration
Section titled “2.2 Configuration”interface DataAdapterConfig { /** * Factory function that creates the native ORM client. * Called once per mode on initialization. */ client: () => TClient;
/** * Per-mode overrides. If a mode is not specified, * the default client is used. */ modes?: { live?: ModeConfig<TClient>; dry_run?: ModeConfig<TClient>; simulated?: ModeConfig<TClient>; training?: ModeConfig<TClient>; };}
interface ModeConfig<TClient> { /** Override client factory for this mode. */ client?: () => TClient;
/** If true, wrap the client in a read-only proxy. */ readOnly?: boolean;
/** If true, use an in-memory mock database. */ inMemory?: boolean;}2.3 Adapter Responsibilities
Section titled “2.3 Adapter Responsibilities”| Responsibility | Required | Description |
|---|---|---|
| Connection lifecycle | Yes | Initialize connections on startup, close on shutdown. Handle connection pooling if the ORM supports it. |
| Mode-aware client resolution | Yes | Return the correct client for the active execution mode (LIVE, DRY_RUN, SIMULATED, TRAINING). |
| Read-only proxy | Yes | For DRY_RUN mode: wrap the client so all write operations throw an error instead of executing. |
| In-memory mock | Yes | For SIMULATED mode: provide an in-memory database that capabilities can read/write without touching the real database. |
| Schema metadata extraction | Yes | Read the ORM’s schema definition and produce a normalized SchemaMetadata object. |
| Trace integration | Yes | Wrap client method calls to record query type, table, duration, and row count in the active Trace. |
| Zakardo migration runner | Yes | Apply Zakardo’s internal table migrations to the database. |
| Developer migration delegation | Yes | Delegate zakardo migrate commands to the ORM’s native migration tool. |
| Developer migration detection | Yes | Detect pending developer migrations (for zakardo dev prompts). |
| Transaction support | Yes | Provide transactional execution for capabilities that need it. |
| Health check | Yes | Simple ping/query to verify the database is reachable. |
3. Schema Metadata
Section titled “3. Schema Metadata”3.1 Purpose
Section titled “3.1 Purpose”Schema metadata lets the Planner understand what business entities exist in the application. When the user says “show me all customers with overdue invoices,” the Planner needs to know that customers and invoices tables exist, what columns they have, and how they relate.
Schema metadata is read-only and extracted at startup (and re-extracted when the developer runs migrations). It is a static snapshot of the database schema, not a live query interface.
3.2 Schema Metadata Model
Section titled “3.2 Schema Metadata Model”interface SchemaMetadata { /** Adapter that produced this metadata. */ adapter: string;
/** When this metadata was extracted. */ extractedAt: string; // ISO 8601
/** All tables/models in the schema. */ tables: TableMetadata[];
/** Named relations between tables. */ relations: RelationMetadata[];}
interface TableMetadata { /** Table name as it appears in the database. */ name: string;
/** Human-readable model name (e.g., 'Customer' from Prisma model). */ modelName: string;
/** Optional description from schema comments/annotations. */ description?: string;
/** Columns in this table. */ columns: ColumnMetadata[];
/** Primary key column(s). */ primaryKey: string[];
/** Unique constraints. */ uniqueConstraints: UniqueConstraint[];}
interface ColumnMetadata { /** Column name. */ name: string;
/** Database type (e.g., 'varchar', 'integer', 'timestamp'). */ dbType: string;
/** Normalized Zakardo type (maps to JSON Schema type). */ type: | 'string' | 'number' | 'integer' | 'boolean' | 'date' | 'datetime' | 'json' | 'array' | 'unknown';
/** Is this column nullable? */ nullable: boolean;
/** Is this column auto-generated (auto-increment, UUID default, etc.)? */ generated: boolean;
/** Default value expression, if any. */ defaultValue?: string;
/** Optional description from schema comments. */ description?: string;
/** Is this a foreign key? If so, which table/column does it reference? */ foreignKey?: { table: string; column: string; };}
interface RelationMetadata { /** Name of this relation (e.g., 'customer_orders'). */ name: string;
/** Source table. */ from: { table: string; column: string };
/** Target table. */ to: { table: string; column: string };
/** Relation type. */ type: 'one-to-one' | 'one-to-many' | 'many-to-many';}
interface UniqueConstraint { name: string; columns: string[];}3.3 How the Planner Uses Schema Metadata
Section titled “3.3 How the Planner Uses Schema Metadata”Schema metadata is injected into the Planner’s context as part of the system prompt. The Planner uses it to:
- Understand entities. When the user says “customer,” the Planner knows the
customerstable exists with columnsid,name,email,company,created_at. - Understand relations. When the user says “customer’s orders,” the Planner knows there is a one-to-many relation from
customerstoordersviacustomer_id. - Match capabilities. If a capability’s input schema requires a
customer_id: string, the Planner can infer that this references thecustomers.idcolumn. - Generate accurate plans. Instead of guessing what data exists, the Planner has the actual schema to ground its reasoning.
Schema metadata is included in the Application Context Layer of the Planner’s prompt architecture (defined in the Planner Specification). It is a structured JSON block, not free-form text:
Available data entities:- Customer: id, name, email, company, created_at, status Relations: has many Orders, has many Contacts- Order: id, customer_id, amount, status, created_at Relations: belongs to Customer, has many LineItems- Invoice: id, order_id, amount, due_date, paid_at, status Relations: belongs to Order3.4 Metadata Filtering
Section titled “3.4 Metadata Filtering”Not all tables should be visible to the Planner. Zakardo-managed tables (zakardo_*) are always excluded. Developers can additionally exclude tables via configuration:
export const data = defineDataConfig({ adapter: PrismaAdapter, client: () => new PrismaClient({ datasourceUrl: env.DATABASE_URL }),
metadata: { exclude: ['_prisma_migrations', 'audit_log', 'system_config'], // Only include these tables (if set, overrides exclude): // include: ['customers', 'orders', 'invoices', 'contacts'], },});3.5 Metadata Refresh
Section titled “3.5 Metadata Refresh”Schema metadata is extracted:
- On startup — when the Zakardo runtime initializes.
- After migrations — when
zakardo migratecompletes successfully. - On demand — via
zakardo metadata:refreshCLI command or Studio button.
Metadata is cached in memory. It does not change between refreshes.
4. Mode-Aware Connections
Section titled “4. Mode-Aware Connections”4.1 The Problem
Section titled “4.1 The Problem”A capability like create_customer needs to write to the database in LIVE mode, but in SIMULATED mode it should write to an in-memory store, and in DRY_RUN mode it should fail if it tries to write. The capability code should not change between modes.
4.2 Mode Resolution
Section titled “4.2 Mode Resolution”When the Execution Engine begins executing a step, it asks the Data Adapter for the client matching the current execution mode:
Execution Mode → Adapter.getClient(mode) → What the Capability Gets─────────────────────────────────────────────────────────────────────────LIVE → getClient('live') → Real database clientDRY_RUN → getClient('dry_run') → Read-only proxySIMULATED → getClient('simulated') → In-memory mockTRAINING → getClient('training') → Fixtures database clientThe capability always calls context.services.db.customer.create(...). What happens depends on the mode:
| Mode | db.customer.create(...) | db.customer.findMany(...) |
|---|---|---|
| LIVE | Creates a real record in the production/dev database | Reads real data |
| DRY_RUN | Throws ReadOnlyError (write rejected) | Reads real data |
| SIMULATED | Creates a record in the in-memory store | Reads from in-memory store (seeded or empty) |
| TRAINING | Creates a record in the fixtures database | Reads from fixtures database |
4.3 Read-Only Proxy
Section titled “4.3 Read-Only Proxy”For DRY_RUN mode, the adapter wraps the real client in a proxy that intercepts write operations:
// Conceptual -- actual implementation in @zakardo/adapter-prismafunction createReadOnlyProxy(client: PrismaClient): PrismaClient { return new Proxy(client, { get(target, prop) { const model = target[prop]; if (typeof model !== 'object') return model;
return new Proxy(model, { get(modelTarget, methodName) { const writeMethods = [ 'create', 'update', 'upsert', 'delete', 'createMany', 'updateMany', 'deleteMany', ]; if (writeMethods.includes(methodName as string)) { return async () => { throw new ReadOnlyError( `Write operation '${String(methodName)}' blocked in DRY_RUN mode`, ); }; } return modelTarget[methodName]; }, }); }, });}Read operations work normally against the real database. This allows DRY_RUN plans to verify that data exists and can be read, while preventing any mutations.
4.4 In-Memory Mock
Section titled “4.4 In-Memory Mock”For SIMULATED mode, the adapter provides an in-memory database that mimics the ORM client API. This is adapter-specific:
- Prisma adapter: Uses an in-memory SQLite database with the same schema. Prisma Client connects to it normally.
- Drizzle adapter: Uses an in-memory SQLite driver with the Drizzle schema applied.
The in-memory mock starts empty (or can be seeded via context.services.db.__seed(data) in test setup). It is isolated per execution — concurrent simulated executions do not share state.
4.5 Fixtures Database
Section titled “4.5 Fixtures Database”For TRAINING mode, the adapter connects to a separate database (specified by FIXTURES_DB_URL) pre-populated with known test data. Training datasets reference this data to verify that capabilities produce expected results given known inputs.
The fixtures database is:
- A real database (same engine as production).
- Pre-seeded with deterministic data (via
zakardo seedor custom seed scripts). - Read-write during training execution (training runs may create/modify data).
- Reset between training runs (if configured) to ensure deterministic results.
5. Trace Integration
Section titled “5. Trace Integration”5.1 How It Works
Section titled “5.1 How It Works”When the Execution Engine injects context.services.db into a capability, it wraps the client from getClient() with a tracing proxy from getTracedClient(). The traced client records every database operation in the active Trace.
Capability calls: context.services.db.customer.findMany({ where: { status: 'active' } })
Trace proxy intercepts and records: { type: 'DB_QUERY', operation: 'findMany', table: 'customers', duration_ms: 12, row_count: 47, // Query details (if trace level is 'verbose') query: "SELECT * FROM customers WHERE status = 'active'" }
Then forwards the call to the real client and returns the result.5.2 Trace Levels
Section titled “5.2 Trace Levels”What the DB trace proxy records depends on the trace level configured in config/trace.ts:
| Trace Level | Records |
|---|---|
minimal | Operation type, table, duration_ms only |
standard | Operation type, table, duration_ms, row_count |
verbose | All of the above + raw query string + parameters (with sensitive data handling) |
5.3 Sensitive Data in Traces
Section titled “5.3 Sensitive Data in Traces”The trace proxy respects the Type System’s sensitive annotations. In standard and verbose mode:
- Query parameters that match sensitive columns (as defined in schema metadata annotations) are hashed or omitted per the
sensitiveDataModeinconfig/trace.ts. - Result data is never included in traces (only row count). Traces record what happened, not what data was returned.
6. Zakardo-Managed Tables
Section titled “6. Zakardo-Managed Tables”6.1 Table Inventory
Section titled “6.1 Table Inventory”Zakardo creates and manages its own tables in the developer’s database. All tables use the zakardo_ prefix to avoid name collisions.
| Table | Purpose | Key Columns |
|---|---|---|
zakardo_executions | Execution checkpoints (durable state machine) | execution_id, plan_id, status, checkpoint_data, created_at, updated_at |
zakardo_execution_events | Persisted execution events (store-then-emit) | event_id, execution_id, event_type, event_data, created_at |
zakardo_traces | Trace headers (one row per execution) | trace_id, execution_id, plan_id, outcome, started_at, completed_at |
zakardo_trace_entries | Individual trace entries (one per step/event) | entry_id, trace_id, entry_type, step_index, data, timestamp |
zakardo_plans | Plan Library (plan IR, lifecycle state, trust scores) | plan_id, version, lifecycle_state, trust_score, plan_ir, created_at |
zakardo_policies | Loaded policy definitions (for persistence across restarts) | policy_id, version, rules, created_at |
zakardo_capabilities | Capability registry (metadata, not code) | capability_id, version, metadata, schema_hash |
zakardo_training_runs | Training execution results | run_id, dataset_id, status, results, started_at, completed_at |
zakardo_audit_log | Execution audit entries (structured summaries) | audit_id, user_id, plan_id, outcome, capabilities_used, timestamp |
zakardo_outbox | Staged external side effects | entry_id, execution_id, step_index, payload, status, idempotency_key |
zakardo_migrations | Zakardo’s own migration tracking | migration_id, applied_at |
6.2 Migration Strategy
Section titled “6.2 Migration Strategy”Zakardo’s tables are migrated separately from the developer’s tables:
Developer tables:
- Managed by the developer’s ORM migration tooling (Prisma Migrate, Drizzle Kit, etc.).
- The developer runs
zakardo migratewhich delegates to the ORM’s migration command. - Zakardo never touches, generates, or modifies developer migration files.
Zakardo tables:
- Managed by Zakardo’s built-in migration runner.
- Migrations are embedded in the
@zakardo/corepackage as SQL files. - Applied automatically on runtime startup (before any other runtime initialization).
- Tracked in the
zakardo_migrationstable. - Non-destructive: Zakardo only adds tables/columns, never drops.
Startup sequence: 1. Data adapter initializes (connects to database) 2. Zakardo migration runner checks zakardo_migrations table 3. Applies any pending Zakardo migrations 4. Data adapter extracts schema metadata 5. Runtime initializes (loads capabilities, policies, plans) 6. Server starts accepting requests6.3 Co-location Considerations
Section titled “6.3 Co-location Considerations”Both developer tables and Zakardo tables share the same database. This is intentional:
Benefits:
- Single database to manage. No separate “Zakardo database” to provision and maintain.
- Capabilities can query Zakardo tables if needed (e.g., check execution status from a Foundation route).
- Simpler backup/restore (one database dump captures everything).
- Transactional consistency when capabilities write business data and Zakardo writes checkpoints.
Risks and mitigations:
| Risk | Mitigation |
|---|---|
| Name collision | zakardo_ prefix on all Zakardo tables. ORM tools configured to ignore zakardo_* tables. |
| Migration conflict | Zakardo migrations run first on startup. Developer migrations run separately via zakardo migrate. |
| Performance impact | Zakardo tables are small relative to business data. Checkpoint writes are single-row upserts. Trace writes are append-only inserts. |
| Developer accidentally modifies Zakardo tables | Zakardo tables are not included in the ORM schema. They exist only at the SQL level. The developer’s ORM is unaware of them. |
6.4 Separate Database Option
Section titled “6.4 Separate Database Option”For advanced deployments, Zakardo supports a separate database for its managed tables. This is configured in config/data.ts:
export const data = defineDataConfig({ adapter: PrismaAdapter, client: () => new PrismaClient({ datasourceUrl: env.DATABASE_URL }),
// Optional: separate database for Zakardo runtime tables zakardoStore: { url: env.ZAKARDO_DB_URL, // If omitted, uses the same database as the adapter },});When zakardoStore is configured, Zakardo’s internal tables live in a separate database. The checkpoint store, trace store, plan library, and outbox all use this separate connection. The developer’s business database remains clean.
7. Official Adapters
Section titled “7. Official Adapters”7.1 @zakardo/adapter-prisma
Section titled “7.1 @zakardo/adapter-prisma”The Prisma adapter is the recommended default for Zakardo applications.
Package: @zakardo/adapter-prisma
What it provides:
| Feature | Implementation |
|---|---|
| Connection lifecycle | Wraps Prisma Client’s $connect() and $disconnect(). |
| Mode-aware switching | Maintains separate Prisma Client instances per mode. DRY_RUN uses a Proxy-based read-only wrapper. SIMULATED uses an in-memory SQLite Prisma Client. |
| Schema metadata extraction | Reads Prisma’s DMMF (Data Model Meta Format) — the parsed representation of schema.prisma. Extracts models, fields, types, relations, and constraints. No runtime introspection needed. |
| Trace integration | Wraps Prisma Client using Prisma’s $extends API (Client Extensions) to intercept queries. Records operation, model, duration, and row count. |
| Zakardo migration runner | Executes embedded SQL migration files against the database using Prisma’s $executeRawUnsafe. |
| Developer migration delegation | Shells out to npx prisma migrate dev (development) or npx prisma migrate deploy (production). |
| Developer migration detection | Checks for pending migrations via npx prisma migrate status. |
| Transaction support | Uses Prisma’s interactive transaction API ($transaction). |
| Health check | Executes SELECT 1 via $queryRaw. |
| Read-only proxy | Proxy wraps all model methods. Write methods (create, update, delete, upsert, createMany, updateMany, deleteMany) throw ReadOnlyError. |
| In-memory mock | Creates a Prisma Client connected to an in-memory SQLite database. Applies the schema via prisma db push at initialization. |
Usage:
import { defineDataConfig } from '@zakardo/core';import { PrismaAdapter } from '@zakardo/adapter-prisma';import { PrismaClient } from '@my-app/db';import { env } from '../env/schema';
export const data = defineDataConfig({ adapter: PrismaAdapter, client: () => new PrismaClient({ datasourceUrl: env.DATABASE_URL }),
modes: { dry_run: { readOnly: true }, simulated: { inMemory: true }, training: { client: () => new PrismaClient({ datasourceUrl: env.FIXTURES_DB_URL }), }, },});Schema metadata example (extracted from Prisma DMMF):
Input (schema.prisma): model Customer { id String @id @default(uuid()) name String email String @unique company String? orders Order[] createdAt DateTime @default(now()) }
Output (SchemaMetadata): { tables: [{ name: "Customer", modelName: "Customer", columns: [ { name: "id", type: "string", generated: true, nullable: false }, { name: "name", type: "string", generated: false, nullable: false }, { name: "email", type: "string", generated: false, nullable: false }, { name: "company", type: "string", generated: false, nullable: true }, { name: "createdAt", type: "datetime", generated: true, nullable: false }, ], primaryKey: ["id"], uniqueConstraints: [{ name: "Customer_email_key", columns: ["email"] }], }], relations: [{ name: "Customer_orders", from: { table: "Customer", column: "id" }, to: { table: "Order", column: "customerId" }, type: "one-to-many", }], }7.2 @zakardo/adapter-drizzle
Section titled “7.2 @zakardo/adapter-drizzle”The Drizzle adapter is an alternative for developers who prefer a code-first, lightweight ORM.
Package: @zakardo/adapter-drizzle
What it provides:
| Feature | Implementation |
|---|---|
| Connection lifecycle | Manages the underlying database driver connection (pg, mysql2, better-sqlite3, etc.). |
| Mode-aware switching | Maintains separate Drizzle instances per mode. DRY_RUN uses a transaction wrapper that rolls back all writes. SIMULATED uses an in-memory SQLite Drizzle instance. |
| Schema metadata extraction | Reads Drizzle’s schema definition (the TypeScript pgTable(), mysqlTable(), etc. calls). Extracts tables, columns, types, relations from Drizzle’s internal schema representation. |
| Trace integration | Wraps the Drizzle query builder using Drizzle’s .execute() interceptor to record queries. |
| Zakardo migration runner | Executes embedded SQL migration files via the raw driver. |
| Developer migration delegation | Shells out to npx drizzle-kit push or npx drizzle-kit migrate. |
| Developer migration detection | Checks for pending migrations via Drizzle Kit’s status API. |
| Transaction support | Uses Drizzle’s db.transaction() API. |
| Health check | Executes SELECT 1 via raw driver. |
| Read-only proxy (DRY_RUN) | Wraps execution in a transaction that auto-rolls back on completion. Writes execute against the real DB but are never committed. |
| In-memory mock | Creates a Drizzle instance on better-sqlite3 (in-memory mode) with the schema applied. |
Usage:
import { defineDataConfig } from '@zakardo/core';import { DrizzleAdapter } from '@zakardo/adapter-drizzle';import { db } from '@my-app/db';import { env } from '../env/schema';
export const data = defineDataConfig({ adapter: DrizzleAdapter, client: () => db, // Pre-configured Drizzle instance from packages/db
modes: { dry_run: { readOnly: true }, simulated: { inMemory: true }, training: { client: () => createDrizzle(env.FIXTURES_DB_URL), }, },});7.3 Adapter Comparison
Section titled “7.3 Adapter Comparison”| Aspect | Prisma Adapter | Drizzle Adapter |
|---|---|---|
| Schema metadata source | Prisma DMMF (parsed from schema.prisma) | Drizzle schema objects (parsed from TypeScript) |
| Read-only (DRY_RUN) | Proxy-based method interception | Transaction-based auto-rollback |
| In-memory (SIMULATED) | SQLite via Prisma Client | SQLite via better-sqlite3 |
| Trace integration | Prisma Client Extensions ($extends) | Drizzle query interceptor |
| Migration tooling | Prisma Migrate | Drizzle Kit |
| Best for | Schema-first workflows, teams that want declarative schema files | Code-first workflows, teams that want schema-as-code |
8. Custom Adapters
Section titled “8. Custom Adapters”Developers can create custom adapters for ORMs not covered by official adapters. A custom adapter implements the DataAdapter interface from @zakardo/core.
8.1 Minimum Viable Adapter
Section titled “8.1 Minimum Viable Adapter”A minimal adapter must implement:
initialize()andshutdown()— connect and disconnect.getClient(mode)— return the client for the given mode (at minimum, return the same client for all modes).getTracedClient(mode, traceContext)— return a traced version (can start as a passthrough).getSchemaMetadata()— return an emptySchemaMetadata(the Planner works without it, just less effectively).runZakardoMigrations()— execute the embedded SQL files.healthCheck()— ping the database.
Schema metadata, mode-aware switching, and full trace integration can be added incrementally.
8.2 Registration
Section titled “8.2 Registration”import { defineDataConfig } from '@zakardo/core';import { MyCustomAdapter } from './adapters/my-adapter';
export const data = defineDataConfig({ adapter: MyCustomAdapter, client: () => myDatabaseClient,});The adapter is instantiated and called by @zakardo/core — the developer does not need to manage its lifecycle.
9. Transaction Handling
Section titled “9. Transaction Handling”9.1 Capability-Level Transactions
Section titled “9.1 Capability-Level Transactions”Capabilities that need to perform multiple write operations atomically can use the transaction API:
export default defineCapability({ name: 'create_order_with_items', // ... execute: async (input, context) => { return context.services.db.transaction(async (tx) => { const order = await tx.order.create({ data: { customer_id: input.customer_id, status: 'pending' }, });
for (const item of input.items) { await tx.orderItem.create({ data: { order_id: order.id, ...item }, }); }
return { order_id: order.id, item_count: input.items.length }; }); },});If any operation within the transaction fails, all writes are rolled back. The capability reports a failure, and the Execution Engine handles it according to the plan’s error policy.
9.2 No Implicit Plan-Level Transactions
Section titled “9.2 No Implicit Plan-Level Transactions”Zakardo does NOT wrap an entire plan execution in a single database transaction. Each capability manages its own transactions.
Rationale:
- Plans may execute over minutes or hours (waiting for gates, interactions, retries). Long-running transactions are impractical and would hold database locks indefinitely.
- The deferred outbox model handles external side effects. Internal write consistency is the capability’s responsibility.
- The idempotency requirement (capabilities must be safe to re-execute) makes plan-level transactions unnecessary for recovery.
9.3 Transaction and Mode Interaction
Section titled “9.3 Transaction and Mode Interaction”| Mode | Transaction Behavior |
|---|---|
| LIVE | Normal database transaction. Committed on success, rolled back on failure. |
| DRY_RUN | Transaction executes but is always rolled back at the end (even on success). The capability sees normal behavior but no data persists. |
| SIMULATED | Transaction against the in-memory database. Committed on success. |
| TRAINING | Normal transaction against the fixtures database. |
10. Idempotency Support
Section titled “10. Idempotency Support”10.1 The Idempotency Key
Section titled “10.1 The Idempotency Key”As defined in the Execution Engine Specification, capabilities with side effects must be idempotent. The Execution Engine provides a natural idempotency key: {execution_id}:{step_index}.
The Data Adapter does not enforce idempotency — that is the capability’s responsibility. However, the adapter provides the key via the execution context:
execute: async (input, context) => { const key = `${context.execution_id}:${context.step_index}`;
// Upsert pattern: safe to call twice (e.g., after crash recovery) const order = await context.services.db.order.upsert({ where: { idempotency_key: key }, create: { ...input, idempotency_key: key }, update: {}, // No-op if already exists });
return { order_id: order.id };};10.2 Idempotency Column Convention
Section titled “10.2 Idempotency Column Convention”Zakardo does not require a specific column name, but recommends that tables involved in write capabilities include an idempotency_key column (or equivalent unique constraint) for safe re-execution.
The zakardo validate CLI command checks WRITE_INTERNAL and DESTRUCTIVE capabilities for idempotency patterns and emits a warning if none are detected.
11. Database Support Matrix
Section titled “11. Database Support Matrix”11.1 Supported Databases
Section titled “11.1 Supported Databases”| Database | Prisma Adapter | Drizzle Adapter | Notes |
|---|---|---|---|
| PostgreSQL | Full support | Full support | Recommended for production |
| MySQL / MariaDB | Full support | Full support | |
| SQLite | Full support | Full support | Recommended for development. Used for in-memory mocks. |
| SQL Server | Full support (Prisma) | Full support (Drizzle) | |
| CockroachDB | Full support (Prisma) | Via pg driver (Drizzle) | |
| PlanetScale | Via Prisma adapter | Via mysql2 driver | Requires serverless driver mode |
11.2 Minimum Database Requirements
Section titled “11.2 Minimum Database Requirements”- Must support transactions (for capability-level transactions and DRY_RUN rollback).
- Must support
CREATE TABLE IF NOT EXISTS(for Zakardo migration runner). - Must support
INSERT ... ON CONFLICTor equivalent (for idempotent checkpointing).
12. Decisions Made in This Document
Section titled “12. Decisions Made in This Document”| Decision | Rationale |
|---|---|
| Thin adapter contract, native ORM usage | Developers should not learn a new query API. Capabilities use the ORM they already know. Zakardo adds mode-awareness, tracing, and metadata — not query abstraction. |
| Schema metadata for Planner context | The Planner is more effective when it knows what data exists. Metadata extraction is a one-time cost at startup. |
| Same database for business + Zakardo tables | Simpler ops (one database to manage). Transactional consistency for checkpoints. zakardo_ prefix prevents collision. |
| Separate migration tracks | Zakardo migrations must never interfere with developer migrations. Different tooling, different tracking tables, run at different times. |
| Read-only proxy for DRY_RUN | Prevents accidental writes while allowing read queries against real data. The proxy is transparent to the capability. |
| In-memory SQLite for SIMULATED | Fast, isolated, no external dependencies. Each simulated execution gets a fresh database. |
| No plan-level transactions | Plans are long-lived. Database transactions are not. Idempotency + deferred outbox is the consistency model. |
| Adapter-specific implementation details | Prisma and Drizzle have fundamentally different architectures. The adapter contract is abstract; implementations are ORM-specific. |
13. Questions Deferred to Other Specifications
Section titled “13. Questions Deferred to Other Specifications”| Question | Deferred To |
|---|---|
How does the Execution Engine checkpoint to zakardo_executions? | Execution Engine Specification |
How does the Trace Store write to zakardo_traces and zakardo_trace_entries? | Trace System Specification |
How does the Plan Library use zakardo_plans? | Plan Library Specification |
What is the full AuthProvider interface and how does it relate to the database? | Runtime API Specification |
How does zakardo migrate CLI command work? | CLI and DX Specification |
How does zakardo seed populate the fixtures database? | CLI and DX Specification |
What are the exact SQL schemas for all zakardo_* tables? | Implementation detail (embedded in @zakardo/core) |