Skip to content

Framework

This document defines Zakardo as a full-stack application framework: project structure, monorepo architecture, configuration system, HTTP layer, two-layer backend, environment management, infrastructure, development server, build pipeline, and scaffolding. It is the bridge between Zakardo’s runtime specs and the concrete developer experience.

Prerequisites: This document assumes familiarity with System Architecture, Glossary, Capability System, Execution Engine, and Policy and Governance.


Zakardo is a full-stack application framework for building new agent-native applications from the ground up.

It is not an integration library. It is not a plugin for existing apps. It is the framework developers choose when they start a new project and want capabilities, plans, and intents as first-class primitives from day one.

A Zakardo application includes:

  • A backend (Hono HTTP server) with a Foundation Layer (non-agentic) and the Zakardo Runtime (agentic).
  • A frontend (developer’s framework of choice + A2UI surfaces for agent-driven UI).
  • A data layer (developer’s ORM with a Zakardo data adapter).
  • Configuration (atomic, type-safe config files).
  • Policies, plans, and training datasets (declarative JSON artifacts).
  • Infrastructure (Docker, deployment configs).
  • Tooling (CLI, Studio, scaffolders).

Everything lives in a single monorepo with clear separation of concerns.


A Zakardo application has multiple deployable units (API server, web frontend) and multiple shared packages (database, business logic, capabilities, UI catalogs). A monorepo provides:

  • Single source of truth. All code, config, policies, and training data in one repo.
  • Atomic changes. A capability change that affects the API, the frontend catalog, and a training dataset is one commit, one PR, one review.
  • Shared tooling. TypeScript config, linting, testing, and CI are configured once.
  • Package dependency graph. Internal packages depend on each other with workspace references (no publishing to npm for internal packages).
  • Consistent versioning. All packages in the monorepo share a version or follow a coordinated versioning strategy.

Zakardo uses Turborepo for task orchestration and pnpm for package management.

Why Turborepo:

  • Zero-config task caching (build outputs, lint results, test results are cached and replayed).
  • Dependency-aware task execution (turbo run build builds packages in dependency order).
  • Parallel execution of independent tasks.
  • Remote caching support (share build caches across CI and team members).
  • Minimal configuration (single turbo.json file).

Why pnpm:

  • Strict dependency isolation (no phantom dependencies).
  • Workspace protocol (workspace:*) for internal package references.
  • Faster installs via content-addressed storage.
  • Native monorepo support with pnpm-workspace.yaml.
my-app/
├── apps/ # Deployable applications
│ ├── api/ # Backend server
│ └── web/ # Frontend application
│
├── packages/ # Shared packages (internal)
│ ├── db/ # Database schema, client, migrations
│ ├── core/ # Shared non-agentic business logic
│ ├── capabilities/ # Zakardo capabilities
│ ├── catalog/ # Custom A2UI components
│ └── shared/ # Shared types, constants, utilities
│
├── config/ # Zakardo configuration (atomic files)
├── policies/ # System-level policy definitions
├── plans/ # Developer-authored plans
├── training/ # Training datasets
├── env/ # Environment management
├── infra/ # Infrastructure and deployment
│
├── turbo.json # Turborepo task definitions
├── pnpm-workspace.yaml # Workspace package list
├── tsconfig.json # Root TypeScript config (shared)
└── package.json # Root scripts and devDependencies
pnpm-workspace.yaml
packages:
- 'apps/*'
- 'packages/*'
{
"$schema": "https://turbo.build/schema.json",
"globalDependencies": ["tsconfig.json", "config/**", "env/**"],
"tasks": {
"build": {
"dependsOn": ["^build"],
"outputs": ["dist/**"]
},
"dev": {
"cache": false,
"persistent": true
},
"lint": {
"dependsOn": ["^build"]
},
"test": {
"dependsOn": ["^build"]
},
"typecheck": {
"dependsOn": ["^build"]
}
}
}
@my-app/shared ← Pure types, constants (no runtime deps)
↑
@my-app/db ← ORM schema + client (depends on shared)
↑
@my-app/core ← Business logic services (depends on db, shared)
↑
@my-app/capabilities ← Zakardo capabilities (depends on core, db, shared)
↑
apps/api ← Backend server (depends on all packages above)
@my-app/catalog ← Custom A2UI components (depends on shared)
↑
apps/web ← Frontend (depends on catalog, shared)

Dependencies flow one direction. No circular dependencies. Each package has a single responsibility.

Rules:

  • packages/shared imports nothing from the monorepo. It is the leaf.
  • packages/db depends only on shared.
  • packages/core depends on db and shared. It is pure business logic — no Zakardo runtime imports.
  • packages/capabilities depends on core, db, and shared. It imports @zakardo/core for the defineCapability API.
  • packages/catalog depends only on shared. It has no backend dependencies.
  • apps/api imports everything. It is the composition root for the backend.
  • apps/web imports catalog and shared. It has no backend dependencies (communicates via HTTP/SSE).

The backend uses Hono as its HTTP framework.

Why Hono:

  • TypeScript-native. Written in TypeScript, designed for TypeScript.
  • Lightweight. ~14kB. No runtime overhead from abstractions the developer doesn’t use.
  • Web Standards. Built on the Web Standards API (Request, Response, Headers). Runs on Node.js, Deno, Bun, Cloudflare Workers, and other edge runtimes.
  • Middleware ecosystem. cors, compress, logger, bearer auth, basic auth, rate limiting, CSRF, secure headers — all available.
  • Router performance. One of the fastest routers in the Node.js ecosystem.
  • Familiar. Express-like API (app.get(), app.post(), middleware) with modern TypeScript ergonomics.

Zakardo does not wrap or abstract Hono. The developer has full access to the Hono app instance for custom routes, middleware, and any standard Hono pattern.

The backend serves both agentic and non-agentic concerns through a single Hono server.

┌─────────────────────────────────────────────────────────────────┐
│ Hono HTTP Server │
│ │
│ ┌──────────────────────────────┐ ┌───────────────────────────┐ │
│ │ Foundation Layer │ │ Zakardo Runtime │ │
│ │ (non-agentic) │ │ (agentic) │ │
│ │ │ │ │ │
│ │ /auth/* Auth flows │ │ /zakardo/* Runtime API │ │
│ │ /billing/* Billing │ │ │ │
│ │ /admin/* Admin CRUD │ │ Planner │ │
│ │ /api/v1/* Public REST │ │ Execution Engine │ │
│ │ /webhooks/* Incoming hooks │ │ Policy Engine │ │
│ │ │ │ A2UI Composition │ │
│ │ Standard Hono routes. │ │ Trace, Outbox, etc. │ │
│ │ Full framework access. │ │ │ │
│ └──────────────────────────────┘ └───────────────────────────┘ │
│ │
│ Shared: Auth middleware, DB connection, Service providers │
└─────────────────────────────────────────────────────────────────┘

Foundation Layer (apps/api/src/foundation/):

The Foundation Layer is standard backend code for concerns that do not go through intents and capabilities:

DirectoryPurposeExamples
auth/Authentication routes, session middleware, OAuth callbacks/auth/login, /auth/signup, /auth/callback/google
billing/Billing routes, subscription management, usage tracking/billing/subscribe, /billing/portal
admin/Admin CRUD endpoints, internal dashboards/admin/users, /admin/settings
api/Public REST API for external integrations/api/v1/customers, /api/v1/orders
jobs/Background job definitions and schedulingCron tasks, queue workers. In worker dispatch mode, also runs createZakardoWorker() (see Execution Engine \u00a74.7).
webhooks/Incoming webhook handlers/webhooks/stripe, /webhooks/github

Foundation routes are standard Hono code. No Zakardo abstractions. Developers write app.get('/api/v1/customers', ...) as they would in any Hono app.

Zakardo Runtime (apps/api/src/zakardo/):

The Zakardo Runtime mounts at /zakardo/* and exposes the Runtime API. It is initialized by calling mountZakardo() which:

  1. Loads all capabilities from packages/capabilities.
  2. Loads configuration from config/.
  3. Loads policies from policies/.
  4. Loads plans from plans/.
  5. Initializes the Execution Engine, Planner, Validator, Policy Engine.
  6. Registers all /zakardo/* HTTP routes and SSE endpoints.
apps/api/src/server.ts
import { Hono } from 'hono';
import { cors } from 'hono/cors';
import { logger } from 'hono/logger';
import { authMiddleware } from './foundation/auth/middleware';
import { authRoutes } from './foundation/auth/routes';
import { billingRoutes } from './foundation/billing/routes';
import { adminRoutes } from './foundation/admin/routes';
import { publicApiRoutes } from './foundation/api/routes';
import { webhookRoutes } from './foundation/webhooks/routes';
import { mountZakardo } from './zakardo';
const app = new Hono();
// Global middleware
app.use('*', cors());
app.use('*', logger());
// Foundation routes (non-agentic)
app.route('/auth', authRoutes);
app.route('/webhooks', webhookRoutes); // No auth (webhook verification)
app.use('/billing/*', authMiddleware);
app.route('/billing', billingRoutes);
app.use('/admin/*', authMiddleware);
app.route('/admin', adminRoutes);
app.use('/api/v1/*', authMiddleware);
app.route('/api/v1', publicApiRoutes);
// Zakardo Runtime (agentic)
app.use('/zakardo/*', authMiddleware);
app.route('/zakardo', mountZakardo());
export default app;
apps/api/src/zakardo/index.ts
import { createZakardoApp } from '@zakardo/core';
import config from '../../config/zakardo';
import * as capabilities from '@my-app/capabilities';
export function mountZakardo() {
return createZakardoApp({
config,
capabilities: capabilities.all,
});
}

createZakardoApp returns a Hono sub-application with all /zakardo/* routes pre-configured. The developer does not manually wire Planner, Validator, or Execution Engine routes.

Both layers share:

  • Auth middleware. The same authMiddleware protects Foundation routes and Zakardo routes. The Auth Provider (configured in config/auth.ts) resolves user identity.
  • Database connection. The same ORM client (from packages/db) is used by Foundation services and injected into capabilities via context.services.db.
  • Service providers. Foundation services (billing, notifications, etc.) defined in packages/core can be injected into capabilities via config/services.ts.

Capabilities can call Foundation services. Foundation services cannot call capabilities.

Capability → context.services.billing → BillingService (from packages/core) ✅
Capability → context.services.email → EmailService (from packages/core) ✅
Foundation route → submitIntent(...) → Zakardo Runtime ❌

The direction is deliberate: capabilities are the agentic bridge that uses traditional services, not the other way around. If a Foundation route needs to trigger an agentic workflow, it should do so via the Runtime API (HTTP), not via internal function calls.


Pure types, constants, and utility functions with no runtime dependencies.

packages/shared/
├── src/
│ ├── types/
│ │ ├── customer.ts # Business entity types
│ │ ├── order.ts
│ │ └── index.ts
│ ├── constants/
│ │ ├── status.ts # Enum-like constants
│ │ └── index.ts
│ └── utils/
│ ├── format.ts # Pure utility functions
│ └── index.ts
├── package.json
└── tsconfig.json

Rules: No database imports. No API imports. No framework imports. Only pure TypeScript.

Database schema, client, and migrations. This is where the developer defines their data model.

packages/db/
├── prisma/ # Prisma (if chosen)
│ ├── schema.prisma
│ └── migrations/
├── src/
│ ├── client.ts # Configured Prisma/Drizzle client
│ ├── seed.ts # Database seed script
│ └── index.ts # Exports client + types
├── package.json
└── tsconfig.json

The packages/db package exports:

  • The ORM client (e.g., PrismaClient or Drizzle db instance).
  • Generated types from the ORM (e.g., Prisma generated types).
  • A seed function for development and testing.

This package has no Zakardo dependencies. It is a standard ORM setup. The Zakardo data adapter (@zakardo/adapter-prisma or @zakardo/adapter-drizzle) wraps this client for mode-aware injection.

Shared non-agentic business logic — services that both Foundation routes and capabilities use.

packages/core/
├── src/
│ ├── services/
│ │ ├── billing.ts # BillingService class
│ │ ├── email.ts # EmailService class
│ │ ├── notification.ts # NotificationService class
│ │ └── index.ts
│ ├── domain/
│ │ ├── customer.ts # Business logic (not CRUD, not capabilities)
│ │ ├── order.ts
│ │ └── index.ts
│ └── index.ts
├── package.json
└── tsconfig.json

What goes in core:

  • Business logic that is not capability-specific but is used by capabilities. Example: A calculateOrderTotal function used by both the create_order capability and the /api/v1/orders Foundation endpoint.
  • Service classes that wrap external APIs (Stripe, SendGrid) and are injected into capabilities via context.services.
  • Domain logic that enforces business rules regardless of whether the caller is a capability or a REST endpoint.

What does NOT go in core:

  • Capability definitions (those go in packages/capabilities).
  • HTTP route handlers (those go in apps/api/src/foundation/).
  • UI components (those go in packages/catalog).

Zakardo capabilities — the agentic instruction set.

packages/capabilities/
├── src/
│ ├── customers/
│ │ ├── get_customer.ts
│ │ ├── create_customer.ts
│ │ ├── delete_customer.ts
│ │ ├── request_customer_deletion.ts
│ │ └── index.ts
│ ├── orders/
│ │ ├── create_order.ts
│ │ ├── list_orders.ts
│ │ └── index.ts
│ ├── reports/
│ │ └── generate_sales_report.ts
│ └── index.ts # Exports { all: [...capabilities] }
├── package.json
└── tsconfig.json

Each capability is defined using defineCapability from @zakardo/core:

packages/capabilities/src/customers/create_customer.ts
import { defineCapability } from '@zakardo/core';
import type { CustomerCreate } from '@my-app/shared';
export default defineCapability({
name: 'create_customer',
version: '1.0.0',
description: 'Creates a new customer record',
tags: ['customers', 'crm'],
effect: 'WRITE_INTERNAL',
boundary: 'LOCAL',
input: {
type: 'object',
properties: {
name: { type: 'string' },
email: { type: 'string', format: 'email' },
company: { type: 'string' },
},
required: ['name', 'email'],
},
output: {
type: 'object',
properties: {
customer_id: { type: 'string' },
name: { type: 'string' },
email: { type: 'string' },
created_at: { type: 'string', format: 'date-time' },
},
},
execute: async (input, context) => {
const db = context.services.db;
const idempotencyKey = `${context.execution_id}:create_customer`;
const customer = await db.customer.upsert({
where: { idempotency_key: idempotencyKey },
create: {
...input,
idempotency_key: idempotencyKey,
},
update: {},
});
return {
customer_id: customer.id,
name: customer.name,
email: customer.email,
created_at: customer.created_at.toISOString(),
};
},
});

Custom A2UI components for domain-specific UI needs.

packages/catalog/
├── src/
│ ├── components/
│ │ ├── DealPipeline.ts # Custom pipeline visualization
│ │ ├── CustomerCard.ts # Custom customer detail card
│ │ └── index.ts
│ ├── catalog.ts # Catalog definition (component registry)
│ └── index.ts
├── package.json
└── tsconfig.json

Custom catalogs extend the Zakardo Standard Catalog. Components are registered via A2UI’s extensible catalog mechanism so capabilities can reference them in view declarations.


  • Atomic files. Each config file has a single responsibility. No monolithic config file that grows unbounded.
  • Type-safe. Every config file exports a typed object using define* helper functions from @zakardo/core.
  • Composable. The root zakardo.ts imports and composes all other config files. It is the single entry point the runtime reads.
  • Environment-aware. Config values can reference environment variables. The env schema validates them at startup.
  • Mode-aware. Service providers define different implementations per execution mode (LIVE, DRY_RUN, SIMULATED, TRAINING).
config/
├── zakardo.ts # Root config (composes everything)
├── data.ts # Data adapter + mode-aware DB connections
├── auth.ts # Auth provider
├── llm.ts # LLM providers, fallback chain, BYOK
├── services.ts # External service providers (per mode)
├── execution.ts # Execution engine settings
├── trace.ts # Trace levels, retention
├── training.ts # Training pipeline settings
└── frontend.ts # Frontend catalog, surface configuration
config/zakardo.ts
import { defineConfig } from '@zakardo/core';
import { data } from './data';
import { auth } from './auth';
import { llm } from './llm';
import { services } from './services';
import { execution } from './execution';
import { trace } from './trace';
import { training } from './training';
import { frontend } from './frontend';
export default defineConfig({
name: 'my-crm',
version: '0.1.0',
data,
auth,
llm,
services,
execution,
trace,
training,
frontend,
});

defineConfig returns a typed, validated configuration object. It fails at startup if any required fields are missing or invalid.

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: {
live: { client: () => new PrismaClient({ datasourceUrl: env.DATABASE_URL }) },
dry_run: { readOnly: true },
simulated: { inMemory: true },
training: { client: () => new PrismaClient({ datasourceUrl: env.FIXTURES_DB_URL }) },
},
});
config/auth.ts
import { defineAuthConfig } from '@zakardo/core';
import { BetterAuthAdapter } from '@zakardo/auth-better-auth';
import { env } from '../env/schema';
export const auth = defineAuthConfig({
adapter: BetterAuthAdapter,
options: {
secret: env.AUTH_SECRET,
database: env.DATABASE_URL,
socialProviders: {
google: {
clientId: env.GOOGLE_CLIENT_ID,
clientSecret: env.GOOGLE_CLIENT_SECRET,
},
},
},
});
config/llm.ts
import { defineLLMConfig } from '@zakardo/core';
import { env } from '../env/schema';
export const llm = defineLLMConfig({
defaultProvider: 'openai',
providers: {
openai: {
apiKey: env.OPENAI_API_KEY,
defaultModel: 'gpt-4o',
models: {
planning: 'gpt-4o',
classification: 'gpt-4o-mini',
},
},
anthropic: {
apiKey: env.ANTHROPIC_API_KEY,
defaultModel: 'claude-sonnet-4-20250514',
},
},
fallbackChain: ['openai', 'anthropic'],
applicationPrompt: `
You are an AI assistant for a CRM application.
The system manages customers, deals, contacts, and activities.
Users are sales representatives and sales managers.
Always prefer creating request capabilities over direct destructive actions.
`,
planningHints: [
'When users ask about "pipeline", they mean the deals pipeline.',
'Customer deletion always requires a request -- use request_customer_deletion.',
],
});
config/services.ts
import { defineServicesConfig } from '@zakardo/core';
import { BillingService, EmailService } from '@my-app/core';
import { env } from '../env/schema';
export const services = defineServicesConfig({
billing: {
live: () => new BillingService(env.STRIPE_LIVE_KEY),
dry_run: () => new BillingService(env.STRIPE_TEST_KEY),
simulated: () => BillingService.mock(),
training: () => BillingService.mock(),
},
email: {
live: () => new EmailService(env.SENDGRID_API_KEY),
dry_run: () => EmailService.dryRun(),
simulated: () => EmailService.mock(),
training: () => EmailService.mock(),
},
});
config/execution.ts
import { defineExecutionConfig } from '@zakardo/core';
export const execution = defineExecutionConfig({
defaultMode: 'live',
retry: {
maxAttempts: 3,
initialDelayMs: 1000,
maxDelayMs: 30000,
backoffMultiplier: 2,
},
timeout: {
stepTimeoutMs: 60000,
gateTimeoutMs: 300000,
interactionTimeoutMs: 300000,
},
outbox: {
commitRetries: 3,
commitRetryDelayMs: 2000,
},
checkpoint: {
// Cleanup terminal checkpoints older than 30 days
retentionDays: 30,
},
});
config/trace.ts
import { defineTraceConfig } from '@zakardo/core';
export const trace = defineTraceConfig({
level: 'standard', // 'minimal' | 'standard' | 'verbose'
captureInputs: true,
captureOutputs: true,
sensitiveDataMode: 'hash', // 'omit' | 'hash' | 'include'
retention: {
localDays: 90,
},
});
config/training.ts
import { defineTrainingConfig } from '@zakardo/core';
export const training = defineTrainingConfig({
datasetsDir: './training',
comparison: {
defaultMode: 'structural', // 'exact' | 'structural' | 'semantic'
structuralTolerance: 0.1,
},
promotion: {
minPassRate: 0.95,
minExecutions: 10,
},
});

Environment variables are validated at startup using a typed schema. Invalid or missing variables cause an immediate, descriptive error — not a runtime crash deep in the application.

The pattern follows t3-env:

  • A single env/schema.ts defines all required and optional variables with Zod schemas.
  • Per-environment .env files provide values.
  • The schema is imported wherever env vars are needed.
  • Server-only and client-safe variables are separated.
env/schema.ts
import { createEnv } from '@t3-oss/env-core';
import { z } from 'zod';
export const env = createEnv({
server: {
// Database
DATABASE_URL: z.string().url(),
FIXTURES_DB_URL: z.string().url().optional(),
// Auth
AUTH_SECRET: z.string().min(32),
GOOGLE_CLIENT_ID: z.string().optional(),
GOOGLE_CLIENT_SECRET: z.string().optional(),
// LLM
OPENAI_API_KEY: z.string().startsWith('sk-'),
ANTHROPIC_API_KEY: z.string().optional(),
// Services
STRIPE_LIVE_KEY: z.string().startsWith('sk_live_').optional(),
STRIPE_TEST_KEY: z.string().startsWith('sk_test_'),
SENDGRID_API_KEY: z.string().optional(),
// Runtime
NODE_ENV: z.enum(['development', 'staging', 'production']).default('development'),
PORT: z.coerce.number().default(3000),
},
client: {
// Public variables accessible by the frontend
NEXT_PUBLIC_API_URL: z.string().url().optional(),
},
runtimeEnv: process.env,
emptyStringAsUndefined: true,
});
env/
├── schema.ts # Typed validation (committed)
├── .env # Local development defaults (gitignored)
├── .env.example # Template with dummy values (committed)
├── .env.staging # Staging overrides (gitignored or encrypted)
└── .env.production # Production overrides (gitignored or encrypted)

Rules:

  • .env.example is committed to the repo. It contains every variable with a dummy/placeholder value and a comment explaining its purpose.
  • .env, .env.staging, .env.production are gitignored (they contain secrets).
  • env/schema.ts is committed. It is the source of truth for what variables exist and what shape they must have.
  • The env import is used in config/*.ts files and in apps/api/src/server.ts. It is never imported directly in capabilities — capabilities receive services via context injection.

At startup, the runtime resolves the active environment:

  1. Read NODE_ENV (defaults to development).
  2. Load .env (base).
  3. Load .env.{NODE_ENV} if it exists (overrides base).
  4. Validate all variables against env/schema.ts.
  5. If validation fails: print a clear error listing every invalid/missing variable and exit.

infra/docker-compose.yml
services:
postgres:
image: postgres:16-alpine
ports:
- '5432:5432'
environment:
POSTGRES_USER: zakardo
POSTGRES_PASSWORD: zakardo
POSTGRES_DB: my_crm_dev
volumes:
- postgres_data:/var/lib/postgresql/data
redis:
image: redis:7-alpine
ports:
- '6379:6379'
volumes:
postgres_data:

zakardo dev starts this Docker Compose stack automatically before launching the dev server (if not already running).

infra/Dockerfile.api
FROM node:20-alpine AS base
RUN corepack enable && corepack prepare pnpm@latest --activate
FROM base AS build
WORKDIR /app
COPY pnpm-lock.yaml pnpm-workspace.yaml package.json turbo.json ./
COPY packages/ packages/
COPY apps/api/ apps/api/
COPY config/ config/
COPY policies/ policies/
COPY plans/ plans/
COPY training/ training/
COPY env/ env/
RUN pnpm install --frozen-lockfile
RUN pnpm turbo build --filter=api
FROM base AS runtime
WORKDIR /app
COPY --from=build /app/apps/api/dist ./dist
COPY --from=build /app/node_modules ./node_modules
EXPOSE 3000
CMD ["node", "dist/server.js"]
infra/Dockerfile.web
FROM node:20-alpine AS base
RUN corepack enable && corepack prepare pnpm@latest --activate
FROM base AS build
WORKDIR /app
COPY pnpm-lock.yaml pnpm-workspace.yaml package.json turbo.json ./
COPY packages/ packages/
COPY apps/web/ apps/web/
RUN pnpm install --frozen-lockfile
RUN pnpm turbo build --filter=web
FROM nginx:alpine AS runtime
COPY --from=build /app/apps/web/dist /usr/share/nginx/html
COPY infra/nginx.conf /etc/nginx/conf.d/default.conf
EXPOSE 80

The Framework Specification does not prescribe a specific deployment platform. The infrastructure directory provides the building blocks:

FilePurpose
infra/docker-compose.ymlLocal dev: Postgres + Redis
infra/docker-compose.prod.ymlProduction-like local setup (API + Web + Postgres)
infra/Dockerfile.apiAPI server container
infra/Dockerfile.webFrontend static build container
infra/nginx.confNginx config for frontend SPA routing

Developers add platform-specific deployment configs as needed (Fly.io fly.toml, Railway railway.json, Kubernetes manifests, Terraform, etc.).


The primary development command. It starts everything the developer needs:

$ zakardo dev
Starting infrastructure...
✓ Docker Compose (postgres, redis)
Starting backend...
✓ Hono server on http://localhost:3000
├── Foundation routes: /auth, /billing, /admin, /api/v1, /webhooks
└── Zakardo Runtime: /zakardo/*
✓ 14 capabilities loaded
✓ 3 policies loaded
✓ 2 plans loaded
Starting frontend...
✓ Vite dev server on http://localhost:5173
Starting Zakardo Studio...
✓ Studio on http://localhost:3000/zakardo/studio
Watching for changes...
├── packages/capabilities/** → auto-reload capabilities
├── policies/** → auto-reload policies
├── plans/** → auto-reload plans
├── config/** → restart runtime
└── packages/db/prisma/** → prompt migration
  1. Checks prerequisites. Docker running? Node.js version? pnpm installed?
  2. Starts infrastructure. Runs docker compose up -d from infra/docker-compose.yml if not already running.
  3. Runs migrations. Checks for pending database migrations and applies them.
  4. Validates environment. Loads env/schema.ts and validates all variables.
  5. Starts backend. Launches the Hono server with hot-reload (via tsx watch or similar). Automatically loads capabilities, policies, and plans.
  6. Starts frontend. Launches Vite dev server with HMR for the frontend app.
  7. Starts Zakardo Studio. Mounts the Studio UI at /zakardo/studio within the backend server.
  8. Watches for changes. File watchers on capabilities, policies, plans, and config trigger appropriate reloads:
ChangeAction
Capability source codeRe-register capability (no server restart)
Policy JSON fileRe-load policy set (no server restart)
Plan JSON fileRe-load plan library (no server restart)
Config fileRestart Zakardo Runtime
Database schemaPrompt developer to run migration
Foundation routeHot-reload via standard Hono/tsx mechanism
Frontend codeVite HMR (instant)

Developers can start only what they need:

Terminal window
zakardo dev api # Backend only (no frontend, no Studio)
zakardo dev web # Frontend only (expects backend running)
zakardo dev studio # Studio only (opens in browser)
zakardo dev --no-infra # Skip Docker Compose

Builds the application for production:

Terminal window
$ zakardo build
Validating environment...
✓ env/schema.ts valid
Type-checking...
✓ packages/shared
✓ packages/db
✓ packages/core
✓ packages/capabilities
✓ packages/catalog
✓ apps/api
✓ apps/web
Validating Zakardo artifacts...
✓ 14 capabilities: schemas valid, effects declared
✓ 3 policies: syntax valid, referenced capabilities exist
✓ 2 plans: IR valid, capabilities available, policies satisfied
✓ 5 training datasets: intent payloads parse, expected responses valid
Building...
✓ apps/api → apps/api/dist/
✓ apps/web → apps/web/dist/
Build complete.

Validates all Zakardo artifacts without building:

Terminal window
$ zakardo validate
Capabilities...
✓ 14 capabilities: schemas valid
✓ Effect classes declared
✓ Idempotency patterns verified for WRITE/DESTRUCTIVE capabilities
✓ Interaction Specs have valid response schemas
Policies...
✓ 3 policies: syntax valid
✓ Referenced capabilities and tags exist
✓ Gate approver roles exist in auth config
Plans...
✓ 2 plans: IR valid
✓ Capability references resolve
✓ Data bindings valid
✓ Policy compliance verified
Training datasets...
✓ 5 datasets: format valid
✓ Intent payloads parseable
✓ Expected responses match output schemas
Config...
✓ config/zakardo.ts composes successfully
✓ Data adapter connects (dry-run)
✓ Auth provider initializes
✓ LLM providers reachable
All artifacts valid. ✓

The project scaffolding CLI:

Terminal window
$ npx create-zakardo my-crm
┌─────────────────────────────────────────┐
│ │
│ create-zakardo │
│ │
│ Creating a new Zakardo application │
│ │
└─────────────────────────────────────────┘
? Database ORM:
❯ Prisma (schema-first, mature migrations)
Drizzle (code-first, lightweight)
? Authentication:
❯ Better Auth (self-hosted, default)
None (configure later)
? Frontend framework:
❯ React (with Vite)
Vue (with Vite)
Angular
None (API only)
? Include example capabilities?
❯ Yes (customer CRUD + request pattern example)
No (empty project)
Creating project...
✓ Monorepo structure
✓ packages/shared
✓ packages/db (Prisma schema)
✓ packages/core
✓ packages/capabilities
✓ packages/catalog
✓ apps/api (Hono + Foundation + Zakardo)
✓ apps/web (React + A2UI)
✓ config/ (atomic config files)
✓ env/ (schema + .env.example)
✓ infra/ (Docker Compose + Dockerfiles)
✓ policies/ (example policy)
✓ training/ (example dataset)
Installing dependencies...
✓ pnpm install
Initializing database...
✓ docker compose up -d
✓ prisma migrate dev
Done! Next steps:
cd my-crm
zakardo dev

The CLI provides generators for common artifacts:

CommandCreatesLocation
zakardo capability:new customers/get_customerCapability scaffoldpackages/capabilities/src/customers/get_customer.ts
zakardo route:new api/v1/reportsFoundation route scaffoldapps/api/src/foundation/api/reports.ts
zakardo policy:new high-value-approvalPolicy JSON scaffoldpolicies/high-value-approval.json
zakardo plan:new onboard-customerPlan IR scaffoldplans/onboard-customer.json
zakardo service:new notificationService provider scaffoldpackages/core/src/services/notification.ts + config/services.ts update
zakardo component:new DealPipelineCustom A2UI component scaffoldpackages/catalog/src/components/DealPipeline.ts

Each generator:

  1. Creates the file with a working scaffold (imports, types, stub implementation).
  2. Updates the relevant index file to export the new artifact.
  3. Runs the TypeScript compiler to verify no errors.

Zakardo Studio is a built-in visual development tool served at /zakardo/studio during development. It provides a GUI for tasks that are otherwise CLI-driven.

FeatureDescription
Capability BrowserList all registered capabilities. View schemas, effect classes, constraints, interaction specs. Test individual capabilities with mock inputs.
Intent PlaygroundSubmit intents and see the full pipeline: Planner response (GENERATE/CLARIFY/CONVERSE), Plan Draft, enriched Plan IR, Validator result.
Plan TesterLoad a plan, execute it in SIMULATED mode, inspect results step by step.
Trace ViewerBrowse execution traces. Expand each step to see inputs, outputs, timing, gate resolutions, interaction responses.
Plan ExplorerNavigate plan history with filtering, search, and drill-down. View execution audit log, plan analytics (success rate, cost, duration), and plan reuse metrics. Compare plan versions side by side. Export audit data for compliance (CSV, JSON). See §13B below.
Prompt BrowserView all registered prompts (system + overrides + custom). Preview rendered prompt output with sample variables. Compare prompt versions. See §13 below.
Policy InspectorView all loaded policies. Test a policy against a mock capability invocation.
Training DashboardRun training datasets, view pass/fail results, compare actual vs. expected. Manage Plan Library snapshots and warmup configuration. See §14 below.
Config ViewerView the resolved configuration (with secrets redacted). Verify mode-aware service resolution.
A2UI PreviewPreview A2UI surfaces. Test anchored views with sample data.

Studio is a self-contained web application shipped as @zakardo/studio. In development, it is mounted as a Hono sub-route on the backend server. It communicates with the Zakardo Runtime via the same Runtime API used by the frontend.

Studio is development-only. It is not included in production builds.


// tsconfig.json (root)
{
"compilerOptions": {
"target": "ES2022",
"module": "ESNext",
"moduleResolution": "bundler",
"strict": true,
"esModuleInterop": true,
"skipLibCheck": true,
"declaration": true,
"declarationMap": true,
"sourceMap": true,
"outDir": "dist",
"rootDir": "src",
"paths": {
"@my-app/*": ["./packages/*/src"]
}
},
"exclude": ["node_modules", "dist"]
}

Each package and app extends this with its own tsconfig.json:

packages/capabilities/tsconfig.json
{
"extends": "../../tsconfig.json",
"compilerOptions": {
"outDir": "dist",
"rootDir": "src"
},
"include": ["src"],
"references": [{ "path": "../shared" }, { "path": "../db" }, { "path": "../core" }]
}

Every LLM call in the Zakardo runtime is driven by a prompt template. The Planner alone makes 9 distinct LLM calls per pipeline execution (see Planner Specification §6.3), and future capabilities may add more. These prompts are the instructions that shape agent behavior — they must be versioned, configurable, validatable, and auditable.

The Prompt Management System provides:

  • A Prompt Registry — all prompts used by the runtime are named, versioned, and registered.
  • Developer overrides — developers can customize any system prompt without forking.
  • Validation — prompt templates are validated at build time.
  • Traceability — traces record exactly which prompt version produced each plan.

All prompts live in the prompts/ directory:

prompts/
├── system/ # Zakardo system prompts (shipped with @zakardo/core)
│ ├── intent-classifier.hbs # Intent classification (GENERATE/CLARIFY/CONVERSE)
│ ├── goal-extractor.hbs # Parse intent into goal + parameters
│ ├── capability-scorer.hbs # Score candidate capabilities against goal
│ ├── alternative-evaluator.hbs # Score alternative capabilities when blocked
│ ├── gap-interpreter.hbs # Determine if gap can be defaulted or needs input
│ ├── condition-generator.hbs # Express step conditions in natural language
│ ├── plan-namer.hbs # Generate concise plan name
│ ├── clarification-composer.hbs # Formulate clarification question
│ └── conversational-responder.hbs # Generate conversational response
├── overrides/ # Developer overrides (same filenames as system/)
├── custom/ # Developer-authored custom prompts
└── prompt.config.ts # Prompt configuration

On startup, the runtime loads prompts with a resolution order:

  1. Developer override (prompts/overrides/<name>.hbs) — highest priority.
  2. System default (prompts/system/<name>.hbs) — shipped with @zakardo/core, copied to project on scaffold.

Prompts use Handlebars-style templates with typed variables:

{{! prompts/system/intent-classifier.hbs }}
{{! @name: intent-classifier }}
{{! @version: 1.2.0 }}
{{! @description: Classifies user intent as actionable, exploratory, or ambiguous }}
{{! @model: classification }}
{{! @variables: application_context, application_prompt, capability_summaries, user_context, user_message }}
You are an intent classifier for the
{{application_context.name}}
application.
{{application_prompt}}
## Available Capabilities
{{#each capability_summaries}}
-
{{this.name}}:
{{this.description}}
[{{this.effect_class}}]
{{/each}}
## User Context User:
{{user_context.user_id}}, Roles:
{{user_context.roles}}
Environment:
{{user_context.environment}}
## Task Classify the following user message as one of: - ACTIONABLE: The user wants something done
that maps to available capabilities. - EXPLORATORY: The user is asking a question or seeking
information. - AMBIGUOUS: The intent is unclear and needs clarification. Respond with JSON: {
"classification": "...", "confidence": 0.0-1.0, "reasoning": "..." } ## User Message
{{user_message}}

Metadata comments at the top of each template:

FieldPurpose
@nameUnique prompt identifier (matches filename)
@versionSemver version. Must be bumped when content changes.
@descriptionHuman-readable description
@modelTarget model role from LLM config (planning, classification, etc.)
@variablesComma-separated list of required template variables

To customize a system prompt, the developer copies it to prompts/overrides/ and modifies:

Terminal window
# Copy and customize
cp prompts/system/intent-classifier.hbs prompts/overrides/intent-classifier.hbs
# Edit the override...

Override rules:

  • The override file must use the same @name as the original.
  • The override file must declare all required @variables (the runtime validates this).
  • The override gets its own version — it is tracked independently.
  • Traces record whether the system or override version was used.

Developers can create custom prompts in prompts/custom/ for use in custom capabilities or services:

import { renderPrompt } from '@zakardo/core';
const response = await renderPrompt('custom/summarize-report', {
report_data: reportJson,
summary_style: 'executive',
});

Custom prompts follow the same template format and validation rules.

prompts/prompt.config.ts
import { definePromptConfig } from '@zakardo/core';
export default definePromptConfig({
// Global settings
templateEngine: 'handlebars', // Template engine (handlebars is default)
// Per-prompt overrides
overrides: {
'intent-classifier': {
temperature: 0.1, // Override default temperature for this prompt
max_tokens: 500, // Override max tokens
},
'capability-scorer': {
temperature: 0.2,
},
},
// Variable injection hooks — add global variables to all prompts
globalVariables: {
company_name: 'Acme Corp',
industry: 'SaaS',
tone: 'professional',
},
});

zakardo validate prompts checks:

CheckDescription
Template syntaxAll .hbs files parse without errors
Metadata present@name, @version, @variables defined
Variables declaredAll {{variable}} references have matching @variables declaration
Version bumpedIf content changed since last build, version must be bumped
Override compatibilityOverride declares same @variables as system original
No orphan overridesEvery file in overrides/ has a matching system prompt

Every trace entry for an LLM call records:

interface PromptTraceEntry {
prompt_name: string; // e.g. 'intent-classifier'
prompt_version: string; // e.g. '1.2.0'
prompt_source: 'system' | 'override' | 'custom';
prompt_hash: string; // SHA-256 of rendered prompt text
rendered_length: number; // Character count of rendered prompt
model_used: string; // e.g. 'gpt-4o-mini'
token_count?: number; // If available from provider
}

This enables:

  • Replay — re-execute with the exact same prompt version.
  • A/B testing — compare outcomes between prompt versions.
  • Audit — prove which instructions drove a particular plan.

The Plan Explorer is a framework-level capability for navigating, auditing, and analyzing plan executions. While the Trace System (see Trace System Specification) records raw execution data, the Plan Explorer provides a structured, queryable layer built on top of traces — designed for operational review, compliance, and continuous improvement.

The Plan Explorer is the foundation for Zakardo Cloud’s Monitoring Dashboard. The open-source framework provides the data model, APIs, and a Studio panel. Cloud adds hosted dashboards, alerting, and cross-environment aggregation.

Every intent-to-completion cycle produces an audit entry — a structured summary of what happened, designed for non-technical review:

interface AuditEntry {
audit_id: string;
timestamp: string;
// Who
user_id: string;
user_roles: string[];
tenant_id?: string;
// What was requested
intent_summary: string; // Human-readable intent description
intent_mode: 'expressed' | 'structured' | 'packaged';
// What plan was used
plan_id: string;
plan_version: string;
plan_source: 'generated' | 'library' | 'direct'; // Was it planned fresh, reused, or submitted directly?
plan_lifecycle_state: string;
// What happened
outcome: 'COMPLETED' | 'FAILED' | 'AWAITING_GATE' | 'AWAITING_INTERACTION' | 'CANCELLED';
capabilities_used: string[]; // List of capability names invoked
effect_classes: string[]; // Unique effect classes encountered
side_effects: SideEffectSummary[]; // External side effects that occurred
// Governance
gates_triggered: number;
gates_approved: number;
gates_denied: number;
policy_violations: string[]; // Policies that blocked or gated execution
// Performance
total_duration_ms: number;
planner_duration_ms: number;
execution_duration_ms: number;
llm_tokens_used: number;
estimated_cost_usd: number;
// References
execution_id: string;
trace_id: string;
}
interface SideEffectSummary {
capability: string;
effect_class: string;
boundary: string;
description: string; // e.g. "Created Stripe charge ch_abc123"
}

The runtime computes aggregate metrics from audit entries:

MetricDescription
Plan generation frequencyHow often each plan is generated vs. reused from library
Plan reuse rate% of executions that used a library plan vs. fresh generation
Success rate by plan% of executions that completed successfully per plan
Average duration by planMean execution time per plan
Cost per planAverage LLM token cost per plan execution
Capability hotspotsMost frequently invoked capabilities
Gate trigger rate% of executions that hit a governance gate
Error distributionError types grouped by category
GET /zakardo/v1/audit-log # Paginated audit entries
GET /zakardo/v1/audit-log/:auditId # Single audit entry
GET /zakardo/v1/audit-log/export # Export as CSV or JSON
GET /zakardo/v1/plans/analytics # Aggregate plan analytics
GET /zakardo/v1/plans/analytics/:planId # Analytics for a specific plan
GET /zakardo/v1/plans/:planId/versions # Version history with diff

All endpoints support filtering:

FilterExample
user_id?user_id=u-456
date_range?from=2025-01-01&to=2025-01-31
outcome?outcome=FAILED
capability?capability=create_order
effect_class?effect_class=WRITE_EXTERNAL
plan_source?plan_source=generated
has_gates?has_gates=true
CREATE TABLE zakardo_audit_log (
audit_id TEXT PRIMARY KEY,
timestamp TIMESTAMP NOT NULL,
user_id TEXT NOT NULL,
user_roles JSONB NOT NULL DEFAULT '[]',
tenant_id TEXT,
intent_summary TEXT NOT NULL,
intent_mode TEXT NOT NULL,
plan_id TEXT NOT NULL,
plan_version TEXT NOT NULL,
plan_source TEXT NOT NULL,
outcome TEXT NOT NULL,
capabilities_used JSONB NOT NULL DEFAULT '[]',
effect_classes JSONB NOT NULL DEFAULT '[]',
side_effects JSONB NOT NULL DEFAULT '[]',
gates_triggered INTEGER NOT NULL DEFAULT 0,
gates_approved INTEGER NOT NULL DEFAULT 0,
gates_denied INTEGER NOT NULL DEFAULT 0,
policy_violations JSONB NOT NULL DEFAULT '[]',
total_duration_ms INTEGER,
planner_duration_ms INTEGER,
execution_duration_ms INTEGER,
llm_tokens_used INTEGER,
estimated_cost_usd REAL,
execution_id TEXT NOT NULL,
trace_id TEXT NOT NULL,
INDEX idx_audit_user (user_id),
INDEX idx_audit_plan (plan_id),
INDEX idx_audit_timestamp (timestamp),
INDEX idx_audit_outcome (outcome)
);

The Studio Plan Explorer provides:

  • Execution timeline — chronological view of all executions with status indicators.
  • Plan drill-down — click any execution to see the full plan IR, step-by-step results, and linked trace.
  • Version comparison — side-by-side diff of two plan IR versions.
  • Analytics dashboard — charts for success rate, cost trends, capability usage, gate frequency.
  • Audit export — download filtered audit entries as CSV or JSON for compliance.
  • Search — full-text search across intents, plan names, capability names, and error messages.

The Training and Validation Specification defines the dataset format and pipeline. This section defines the framework-level infrastructure: how training produces deployable artifacts, how incremental training works, and how the system warms up for production.

Warmup is the process of pre-generating a Plan Library from training datasets before the system goes live. Without warmup, the first time a user submits an intent, the Planner must reason from scratch — using LLM tokens, adding latency, and producing an unproven plan. With warmup, common intents resolve instantly to promoted, trusted plans.

Warmup runs during deployment:

Terminal window
# Run warmup training (typically in CI/CD before deploy)
zakardo training warmup

This executes:

  1. Load all datasets listed in training/warmup.json.
  2. Run each dataset through the full pipeline (Planner → Enrichment → Validator → Execution Engine in TRAINING mode).
  3. Plans that pass are promoted to the Plan Library.
  4. Export a Plan Library snapshot (see §14.3).
training/warmup.json
{
"description": "Datasets to run on first deployment",
"datasets": [
"training/datasets/customer-operations.dataset.json",
"training/datasets/order-management.dataset.json",
"training/datasets/reporting.dataset.json"
],
"options": {
"parallel_cases": 5,
"auto_promote": true,
"promotion_threshold": 0.95
}
}

The output of training is a Plan Library snapshot — a JSON export of all promoted plans with their trust scores, version metadata, and associations:

training/snapshots/latest.json
{
"snapshot_id": "snap_20250212_001",
"created_at": "2025-02-12T00:00:00Z",
"runtime_version": "1.0.0",
"plans": [
{
"plan_id": "plan_get_customers",
"version": "2.0.0",
"lifecycle_state": "PROMOTED",
"trust_score": 0.97,
"training_pass_rate": 1.0,
"intent_patterns": ["show me all customers", "list customers", "get customer list"],
"capabilities_used": ["list_customers"],
"plan_ir": {
/* full Plan IR */
}
}
],
"stats": {
"total_plans": 15,
"promoted": 12,
"shadow": 3,
"total_training_cases": 87,
"overall_pass_rate": 0.96
}
}

Deployment flow:

CI/CD pipeline:
1. zakardo build
2. zakardo training warmup
3. training/snapshots/latest.json → included in Docker image
4. On startup, runtime loads snapshot → Plan Library pre-populated
5. Common intents resolve from library without LLM calls

When a developer adds a new capability, they should not need to retrain everything:

Terminal window
# Run only new or changed datasets
zakardo training run --incremental

How --incremental works:

  1. Compare current datasets to the last training run’s dataset manifest.
  2. Identify new datasets (not in previous manifest) and changed datasets (content hash differs).
  3. Run only those datasets.
  4. Existing promoted plans that don’t reference changed capabilities are untouched.
  5. If a changed capability is used by an existing promoted plan, that plan’s dataset is automatically re-run (regression check).
Developer adds new capability: generate_invoice
→ Creates training/datasets/invoice-generation.dataset.json
→ Runs: zakardo training run --incremental
→ Only invoice-generation dataset runs
→ Existing customer-operations plans remain promoted
→ New invoice plans are promoted if they pass
→ Snapshot updated

Training is not a one-time event. The system improves over time:

Production execution succeeds
→ Trace recorded
→ Developer reviews trace in Studio Plan Explorer
→ Developer generates dataset from trace:
zakardo training generate-dataset --trace <trace_id>
→ Developer refines generated dataset (adds edge cases, adjusts expectations)
→ Runs: zakardo training run --dataset invoice-edge-cases
→ New plan promoted with higher trust score
→ Next snapshot includes the improved plan

This creates a virtuous cycle: production executions produce traces, traces become training data, training data produces better plans, better plans improve production executions.

CommandEnvironmentExternal ServicesDatabase
zakardo training runTRAINING modeMock services (fixtures)Fixtures DB (FIXTURES_DB_URL)
zakardo training run --mode dry_runDRY_RUN modeReal services (read-only)Real DB (read-only)
zakardo training warmupTRAINING modeMock servicesFixtures DB

Training runs consume LLM tokens for planning. Configuration options:

config/training.ts
export const training = defineTrainingConfig({
// Cost controls
llm_budget: {
max_tokens_per_run: 100_000, // Cap per training run
max_cost_per_run_usd: 5.0, // Dollar cap (estimated)
model_override: 'gpt-4o-mini', // Use cheaper model for training
},
// Caching
cache_planner_results: true, // Cache plan generation for identical intents
});
training/
├── datasets/ # Training datasets
│ ├── customer-operations.dataset.json
│ ├── order-management.dataset.json
│ └── reporting.dataset.json
├── snapshots/ # Plan Library snapshots (training output)
│ ├── latest.json # Current snapshot (deployed to production)
│ └── snap_20250211_001.json # Historical snapshots
├── warmup.json # Warmup configuration
└── fixtures/ # Fixture data for TRAINING mode
├── customers.json
├── orders.json
└── seed.ts # Programmatic seed script

Zakardo Cloud extends the local training infrastructure with:

FeatureOSS (Local)Cloud
Training run executionCLI (zakardo training run)Scheduled runs, webhook triggers
Results storageLocal zakardo_training_runs tableCloud-hosted, cross-environment aggregation
Regression alertsCLI output, exit codesSlack/email notifications, dashboard alerts
Training dashboardStudio Training DashboardCloud Training Dashboard with historical trends
Snapshot managementLocal filesVersioned cloud storage, rollback support
Cost trackingConfig-based capsPer-run cost tracking, budget dashboards

The OSS framework provides a complete, self-contained training experience. Cloud adds visibility, automation, and team-scale management.


Zakardo introduces new execution primitives (capabilities, plans, policies, A2UI composition) that require new testing primitives. The testing framework serves two audiences:

  1. Zakardo contributors — testing @zakardo/core internals.
  2. Zakardo consumers — testing applications built on the framework.

This section focuses on the consumer testing framework: @zakardo/test.

@zakardo/test is a testing utilities package designed to work with Vitest (the default test runner for Zakardo projects). It provides:

  • An in-memory Zakardo runtime (no Docker, no external dependencies).
  • Typed helpers for testing every Zakardo primitive.
  • Snapshot testing for plan structure regression.
  • A2UI output assertions.

Spins up an in-memory Zakardo runtime with all components initialized:

import { createTestRuntime } from '@zakardo/test';
import * as capabilities from '@my-app/capabilities';
const runtime = createTestRuntime({
capabilities: capabilities.all,
// Optional: fixture data for services
fixtures: {
customers: [
{ id: 'c1', name: 'Acme Corp', status: 'active' },
{ id: 'c2', name: 'Widget Inc', status: 'inactive' },
],
},
// Optional: mock external services
mocks: {
stripe: { charge: { id: 'ch_test', status: 'succeeded' } },
},
// Optional: policies
policies: ['policies/high-value-approval.json'],
// Optional: prompts
prompts: 'prompts/',
});

The test runtime uses:

  • In-memory Plan Library (no database).
  • Mock LLM provider (deterministic responses for testing, or real LLM for integration tests).
  • Mock services (fixture-based).
  • SIMULATED execution mode by default.

Submits an intent and returns the full pipeline result:

import { testIntent } from '@zakardo/test';
test('natural language intent resolves to correct plan', async () => {
const result = await testIntent(runtime, 'Show me all active customers');
expect(result.classification).toBe('ACTIONABLE');
expect(result.planner_mode).toBe('GENERATE');
expect(result.plan.capabilities_used).toContain('list_customers');
expect(result.outcome).toBe('COMPLETED');
expect(result.output.customers).toHaveLength(1);
expect(result.output.customers[0].name).toBe('Acme Corp');
});

testIntent() returns a TestIntentResult:

interface TestIntentResult {
// Planner phase
classification: 'ACTIONABLE' | 'EXPLORATORY' | 'AMBIGUOUS';
planner_mode: 'GENERATE' | 'CLARIFY' | 'CONVERSE';
// Plan phase (if GENERATE)
plan: {
plan_id: string;
steps: number;
capabilities_used: string[];
ir: PlanIR; // Full Plan IR for inspection
};
// Validation phase
validation: {
passed: boolean;
issues: ValidationIssue[];
};
// Execution phase
outcome: 'COMPLETED' | 'PERMANENTLY_FAILED' | 'AWAITING_GATE' | 'AWAITING_INTERACTION';
output: Record<string, any>; // Final execution output
trace: Trace; // Full execution trace
duration_ms: number;
// For CLARIFY/CONVERSE modes
clarification?: string;
response?: string;
}

Executes a single capability in isolation:

import { testCapability } from '@zakardo/test';
test('create_customer writes to database', async () => {
const result = await testCapability(runtime, 'create_customer', {
input: { name: 'New Corp', email: '[email protected]' },
});
expect(result.outcome).toBe('SUCCESS');
expect(result.output).toMatchObject({ id: expect.any(String), name: 'New Corp' });
expect(result.side_effects).toEqual([
{ type: 'WRITE_INTERNAL', description: expect.any(String) },
]);
});

Executes a specific plan directly (skips the Planner):

import { testPlan } from '@zakardo/test';
test('onboard-customer plan completes all steps', async () => {
const result = await testPlan(runtime, 'plans/onboard-customer.json', {
inputs: { customer_id: 'c1' },
gate_responses: { 0: { approved: true } }, // Auto-approve gate at step 0
});
expect(result.outcome).toBe('COMPLETED');
expect(result.steps_completed).toBe(3);
expect(result.output).toHaveProperty('welcome_email_sent', true);
});

Evaluates a policy against a mock capability invocation:

import { testPolicy } from '@zakardo/test';
test('high-value orders require approval', async () => {
const result = await testPolicy(runtime, 'high-value-approval', {
capability: 'create_order',
input: { amount: 15000, customer_id: 'c1' },
user: { roles: ['sales_rep'] },
});
expect(result.action).toBe('GATE');
expect(result.gate_type).toBe('HUMAN_APPROVAL');
});
test('small orders pass without gate', async () => {
const result = await testPolicy(runtime, 'high-value-approval', {
capability: 'create_order',
input: { amount: 50, customer_id: 'c1' },
user: { roles: ['sales_rep'] },
});
expect(result.action).toBe('ALLOW');
});

Replaces a capability with a mock implementation for plan-level testing:

import { mockCapability } from '@zakardo/test';
test('plan handles email service failure', async () => {
mockCapability(runtime, 'send_email', {
execute: async () => {
throw new Error('SMTP connection failed');
},
});
const result = await testPlan(runtime, 'plans/onboard-customer.json', {
inputs: { customer_id: 'c1' },
});
expect(result.outcome).toBe('PERMANENTLY_FAILED');
expect(result.error.step_index).toBe(2); // send_email is step 2
});

Plan structure regression testing:

test('create-customer plan structure is stable', async () => {
const result = await testIntent(runtime, 'Create a customer named Test Corp');
// Snapshots the plan IR structure (capabilities, bindings, flow)
// Strips non-deterministic fields (timestamps, IDs)
expect(result.plan.ir).toMatchPlanSnapshot();
});

toMatchPlanSnapshot() is a custom Vitest matcher that:

  • Normalizes the plan IR (removes timestamps, generated IDs).
  • Compares capability sequence, data bindings, and flow structure.
  • Ignores cosmetic differences (plan name text, description wording).
import { testA2UIOutput } from '@zakardo/test';
test('list_customers produces DataTable A2UI', async () => {
const result = await testCapability(runtime, 'list_customers', {
input: { status: 'active' },
});
const a2ui = testA2UIOutput(result);
expect(a2ui.surface).toBe('workspace');
expect(a2ui.components).toContainComponent('DataTable');
expect(a2ui.dataModel).toHaveProperty('/customers');
expect(a2ui.dataModel['/customers']).toHaveLength(1);
});
vitest.config.ts
import { defineConfig } from 'vitest/config';
import { zakardoPlugin } from '@zakardo/test/vitest';
export default defineConfig({
plugins: [zakardoPlugin()],
test: {
globals: true,
environment: 'node',
setupFiles: ['./test/setup.ts'],
},
});
test/setup.ts
import { setupZakardoTest } from '@zakardo/test';
setupZakardoTest({
// Register custom matchers (toMatchPlanSnapshot, toContainComponent, etc.)
matchers: true,
// Global test runtime config
llm: 'mock', // 'mock' for unit tests, 'real' for integration tests
timeout: 30_000, // Default timeout for plan execution tests
});
Terminal window
# Run all tests
zakardo test
# Run specific test files
zakardo test capabilities
zakardo test plans
zakardo test policies
# Run with real LLM (integration tests)
zakardo test --llm real
# Run with coverage
zakardo test --coverage

zakardo test is a thin wrapper around vitest that pre-configures the Zakardo test environment.

WhatHowExample
Individual capabilitiestestCapability() — verify input/output, side effectsDoes create_customer validate email format?
Plans end-to-endtestPlan() — verify step sequence, data flow, final outputDoes the onboarding plan send a welcome email?
Intent resolutiontestIntent() — verify the full pipeline from NL to resultDoes “show inactive customers” resolve correctly?
Policy enforcementtestPolicy() — verify gate triggers and allow/denyDo high-value orders require approval?
Plan regressiontoMatchPlanSnapshot() — verify plan structure stabilityDid the plan change after a capability update?
A2UI outputtestA2UIOutput() — verify component renderingDoes the dashboard capability produce a DataTable?
Error handlingmockCapability() + testPlan() — verify failure pathsDoes the plan handle Stripe API failures gracefully?
Training datasetszakardo training run — verify known inputs produce expected outputsSee Training and Validation Specification

DecisionRationale
Turborepo + pnpm for monorepoBest-in-class for TypeScript monorepos. Zero-config caching, strict deps, workspace protocol.
Hono as HTTP layerTypeScript-native, lightweight, web-standards, fast router, edge-compatible. Does not constrain deployment.
Two-layer backendNot everything is agentic. Auth, billing, CRUD, webhooks need standard HTTP endpoints. One server, two concerns.
Atomic config filesSingle-responsibility. Each file grows independently. No 500-line monolithic config.
t3-env for environment managementType-safe, fail-fast. No more “undefined is not a function” because a env var was missing.
Foundation ↔ Capability directionCapabilities call Foundation services, not the reverse. Prevents coupling Foundation routes to the Zakardo runtime.
Studio as dev-only toolReduces production surface area. Studio uses the same Runtime API as the frontend — no special internal APIs needed.
Infrastructure in infra/Keep deployment concerns separate from application code. Not prescriptive about hosting platform.
Vite for frontend devFast HMR, wide framework support (React, Vue, Svelte, Angular via analog). Standard for modern frontend development.
Prompts as versioned templatesPrompts drive agent behavior and must be auditable, customizable, and reproducible. Handlebars templates with metadata provide all three.
Developer prompt overridesDevelopers need to customize agent behavior for their domain without forking the framework. Override-by-filename is simple and visible.
Plan Explorer as framework layerAudit and analytics are too important to be Studio-only. API endpoints + data model enable Cloud dashboard and custom integrations.
Warmup + Plan Library snapshotsPre-generating proven plans eliminates cold-start latency and LLM cost for common intents.
Incremental trainingFull retraining on every change is wasteful. Only new/changed datasets run; existing promoted plans are preserved.
@zakardo/test as dedicated packageAgent-native testing needs agent-native primitives (testIntent, testCapability, testPolicy). Generic test utils cannot provide the right abstractions.
Vitest as test runnerModern, fast, TypeScript-native, compatible with the Vite-based frontend.

17. Questions Deferred to Other Specifications

Section titled “17. Questions Deferred to Other Specifications”
QuestionDeferred To
What is the full DataAdapter interface?Data Layer Specification
What are the /zakardo/* API endpoints?Runtime API Specification
What CLI commands exist beyond dev, build, validate?CLI and DX Specification
How does A2UI rendering work in the frontend?Frontend Architecture Specification
What is the AuthProvider interface?Data Layer Specification (or dedicated Auth Spec)
How does @zakardo/core’s createZakardoApp work internally?Runtime API Specification
What are the full schemas for defineCapability, defineConfig, etc.?Type System Specification (addendum)
How does Zakardo Cloud aggregate audit logs across environments?PRD — Zakardo Cloud
What is the zakardo validate prompts CLI interface?CLI and DX Specification
How does @zakardo/test mock the LLM provider deterministically?Implementation detail