Skip to content

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.


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 API
const customer = await context.services.db.customer.findUnique({
where: { id: input.customer_id },
include: { orders: true },
});
// Drizzle: native Drizzle query API
const 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.

A Zakardo application has one database with two sets of tables:

OwnerTablesManaged ByMigrated By
DeveloperBusiness tables (customers, orders, invoices, etc.)Developer via their ORMDeveloper’s ORM migration tooling (Prisma Migrate, Drizzle Kit)
ZakardoRuntime tables (executions, traces, plans, policies, etc.)Zakardo runtimeZakardo’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.


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>;
}
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;
}
ResponsibilityRequiredDescription
Connection lifecycleYesInitialize connections on startup, close on shutdown. Handle connection pooling if the ORM supports it.
Mode-aware client resolutionYesReturn the correct client for the active execution mode (LIVE, DRY_RUN, SIMULATED, TRAINING).
Read-only proxyYesFor DRY_RUN mode: wrap the client so all write operations throw an error instead of executing.
In-memory mockYesFor SIMULATED mode: provide an in-memory database that capabilities can read/write without touching the real database.
Schema metadata extractionYesRead the ORM’s schema definition and produce a normalized SchemaMetadata object.
Trace integrationYesWrap client method calls to record query type, table, duration, and row count in the active Trace.
Zakardo migration runnerYesApply Zakardo’s internal table migrations to the database.
Developer migration delegationYesDelegate zakardo migrate commands to the ORM’s native migration tool.
Developer migration detectionYesDetect pending developer migrations (for zakardo dev prompts).
Transaction supportYesProvide transactional execution for capabilities that need it.
Health checkYesSimple ping/query to verify the database is reachable.

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.

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[];
}

Schema metadata is injected into the Planner’s context as part of the system prompt. The Planner uses it to:

  1. Understand entities. When the user says “customer,” the Planner knows the customers table exists with columns id, name, email, company, created_at.
  2. Understand relations. When the user says “customer’s orders,” the Planner knows there is a one-to-many relation from customers to orders via customer_id.
  3. Match capabilities. If a capability’s input schema requires a customer_id: string, the Planner can infer that this references the customers.id column.
  4. 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 Order

Not all tables should be visible to the Planner. Zakardo-managed tables (zakardo_*) are always excluded. Developers can additionally exclude tables via configuration:

config/data.ts
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'],
},
});

Schema metadata is extracted:

  1. On startup — when the Zakardo runtime initializes.
  2. After migrations — when zakardo migrate completes successfully.
  3. On demand — via zakardo metadata:refresh CLI command or Studio button.

Metadata is cached in memory. It does not change between refreshes.


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.

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 client
DRY_RUN → getClient('dry_run') → Read-only proxy
SIMULATED → getClient('simulated') → In-memory mock
TRAINING → getClient('training') → Fixtures database client

The capability always calls context.services.db.customer.create(...). What happens depends on the mode:

Modedb.customer.create(...)db.customer.findMany(...)
LIVECreates a real record in the production/dev databaseReads real data
DRY_RUNThrows ReadOnlyError (write rejected)Reads real data
SIMULATEDCreates a record in the in-memory storeReads from in-memory store (seeded or empty)
TRAININGCreates a record in the fixtures databaseReads from fixtures database

For DRY_RUN mode, the adapter wraps the real client in a proxy that intercepts write operations:

// Conceptual -- actual implementation in @zakardo/adapter-prisma
function 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.

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.

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 seed or custom seed scripts).
  • Read-write during training execution (training runs may create/modify data).
  • Reset between training runs (if configured) to ensure deterministic results.

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.

What the DB trace proxy records depends on the trace level configured in config/trace.ts:

Trace LevelRecords
minimalOperation type, table, duration_ms only
standardOperation type, table, duration_ms, row_count
verboseAll of the above + raw query string + parameters (with sensitive data handling)

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 sensitiveDataMode in config/trace.ts.
  • Result data is never included in traces (only row count). Traces record what happened, not what data was returned.

Zakardo creates and manages its own tables in the developer’s database. All tables use the zakardo_ prefix to avoid name collisions.

TablePurposeKey Columns
zakardo_executionsExecution checkpoints (durable state machine)execution_id, plan_id, status, checkpoint_data, created_at, updated_at
zakardo_execution_eventsPersisted execution events (store-then-emit)event_id, execution_id, event_type, event_data, created_at
zakardo_tracesTrace headers (one row per execution)trace_id, execution_id, plan_id, outcome, started_at, completed_at
zakardo_trace_entriesIndividual trace entries (one per step/event)entry_id, trace_id, entry_type, step_index, data, timestamp
zakardo_plansPlan Library (plan IR, lifecycle state, trust scores)plan_id, version, lifecycle_state, trust_score, plan_ir, created_at
zakardo_policiesLoaded policy definitions (for persistence across restarts)policy_id, version, rules, created_at
zakardo_capabilitiesCapability registry (metadata, not code)capability_id, version, metadata, schema_hash
zakardo_training_runsTraining execution resultsrun_id, dataset_id, status, results, started_at, completed_at
zakardo_audit_logExecution audit entries (structured summaries)audit_id, user_id, plan_id, outcome, capabilities_used, timestamp
zakardo_outboxStaged external side effectsentry_id, execution_id, step_index, payload, status, idempotency_key
zakardo_migrationsZakardo’s own migration trackingmigration_id, applied_at

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 migrate which 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/core package as SQL files.
  • Applied automatically on runtime startup (before any other runtime initialization).
  • Tracked in the zakardo_migrations table.
  • 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 requests

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:

RiskMitigation
Name collisionzakardo_ prefix on all Zakardo tables. ORM tools configured to ignore zakardo_* tables.
Migration conflictZakardo migrations run first on startup. Developer migrations run separately via zakardo migrate.
Performance impactZakardo tables are small relative to business data. Checkpoint writes are single-row upserts. Trace writes are append-only inserts.
Developer accidentally modifies Zakardo tablesZakardo tables are not included in the ORM schema. They exist only at the SQL level. The developer’s ORM is unaware of them.

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.


The Prisma adapter is the recommended default for Zakardo applications.

Package: @zakardo/adapter-prisma

What it provides:

FeatureImplementation
Connection lifecycleWraps Prisma Client’s $connect() and $disconnect().
Mode-aware switchingMaintains 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 extractionReads 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 integrationWraps Prisma Client using Prisma’s $extends API (Client Extensions) to intercept queries. Records operation, model, duration, and row count.
Zakardo migration runnerExecutes embedded SQL migration files against the database using Prisma’s $executeRawUnsafe.
Developer migration delegationShells out to npx prisma migrate dev (development) or npx prisma migrate deploy (production).
Developer migration detectionChecks for pending migrations via npx prisma migrate status.
Transaction supportUses Prisma’s interactive transaction API ($transaction).
Health checkExecutes SELECT 1 via $queryRaw.
Read-only proxyProxy wraps all model methods. Write methods (create, update, delete, upsert, createMany, updateMany, deleteMany) throw ReadOnlyError.
In-memory mockCreates a Prisma Client connected to an in-memory SQLite database. Applies the schema via prisma db push at initialization.

Usage:

config/data.ts
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",
}],
}

The Drizzle adapter is an alternative for developers who prefer a code-first, lightweight ORM.

Package: @zakardo/adapter-drizzle

What it provides:

FeatureImplementation
Connection lifecycleManages the underlying database driver connection (pg, mysql2, better-sqlite3, etc.).
Mode-aware switchingMaintains 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 extractionReads Drizzle’s schema definition (the TypeScript pgTable(), mysqlTable(), etc. calls). Extracts tables, columns, types, relations from Drizzle’s internal schema representation.
Trace integrationWraps the Drizzle query builder using Drizzle’s .execute() interceptor to record queries.
Zakardo migration runnerExecutes embedded SQL migration files via the raw driver.
Developer migration delegationShells out to npx drizzle-kit push or npx drizzle-kit migrate.
Developer migration detectionChecks for pending migrations via Drizzle Kit’s status API.
Transaction supportUses Drizzle’s db.transaction() API.
Health checkExecutes 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 mockCreates a Drizzle instance on better-sqlite3 (in-memory mode) with the schema applied.

Usage:

config/data.ts
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),
},
},
});
AspectPrisma AdapterDrizzle Adapter
Schema metadata sourcePrisma DMMF (parsed from schema.prisma)Drizzle schema objects (parsed from TypeScript)
Read-only (DRY_RUN)Proxy-based method interceptionTransaction-based auto-rollback
In-memory (SIMULATED)SQLite via Prisma ClientSQLite via better-sqlite3
Trace integrationPrisma Client Extensions ($extends)Drizzle query interceptor
Migration toolingPrisma MigrateDrizzle Kit
Best forSchema-first workflows, teams that want declarative schema filesCode-first workflows, teams that want schema-as-code

Developers can create custom adapters for ORMs not covered by official adapters. A custom adapter implements the DataAdapter interface from @zakardo/core.

A minimal adapter must implement:

  1. initialize() and shutdown() — connect and disconnect.
  2. getClient(mode) — return the client for the given mode (at minimum, return the same client for all modes).
  3. getTracedClient(mode, traceContext) — return a traced version (can start as a passthrough).
  4. getSchemaMetadata() — return an empty SchemaMetadata (the Planner works without it, just less effectively).
  5. runZakardoMigrations() — execute the embedded SQL files.
  6. healthCheck() — ping the database.

Schema metadata, mode-aware switching, and full trace integration can be added incrementally.

config/data.ts
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.


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.

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.
ModeTransaction Behavior
LIVENormal database transaction. Committed on success, rolled back on failure.
DRY_RUNTransaction executes but is always rolled back at the end (even on success). The capability sees normal behavior but no data persists.
SIMULATEDTransaction against the in-memory database. Committed on success.
TRAININGNormal transaction against the fixtures database.

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 };
};

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.


DatabasePrisma AdapterDrizzle AdapterNotes
PostgreSQLFull supportFull supportRecommended for production
MySQL / MariaDBFull supportFull support
SQLiteFull supportFull supportRecommended for development. Used for in-memory mocks.
SQL ServerFull support (Prisma)Full support (Drizzle)
CockroachDBFull support (Prisma)Via pg driver (Drizzle)
PlanetScaleVia Prisma adapterVia mysql2 driverRequires serverless driver mode
  • 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 CONFLICT or equivalent (for idempotent checkpointing).

DecisionRationale
Thin adapter contract, native ORM usageDevelopers 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 contextThe Planner is more effective when it knows what data exists. Metadata extraction is a one-time cost at startup.
Same database for business + Zakardo tablesSimpler ops (one database to manage). Transactional consistency for checkpoints. zakardo_ prefix prevents collision.
Separate migration tracksZakardo migrations must never interfere with developer migrations. Different tooling, different tracking tables, run at different times.
Read-only proxy for DRY_RUNPrevents accidental writes while allowing read queries against real data. The proxy is transparent to the capability.
In-memory SQLite for SIMULATEDFast, isolated, no external dependencies. Each simulated execution gets a fresh database.
No plan-level transactionsPlans are long-lived. Database transactions are not. Idempotency + deferred outbox is the consistency model.
Adapter-specific implementation detailsPrisma 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”
QuestionDeferred 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)