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.
1. Identity
Section titled “1. Identity”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.
2. Monorepo Architecture
Section titled “2. Monorepo Architecture”2.1 Why a Monorepo
Section titled “2.1 Why a Monorepo”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.
2.2 Tooling: Turborepo + pnpm
Section titled “2.2 Tooling: Turborepo + pnpm”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 buildbuilds packages in dependency order). - Parallel execution of independent tasks.
- Remote caching support (share build caches across CI and team members).
- Minimal configuration (single
turbo.jsonfile).
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.
2.3 Workspace Layout
Section titled “2.3 Workspace Layout”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 devDependencies2.4 Workspace Definition
Section titled “2.4 Workspace Definition”packages: - 'apps/*' - 'packages/*'2.5 Turborepo Configuration
Section titled “2.5 Turborepo Configuration”{ "$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"] } }}2.6 Package Dependency Graph
Section titled “2.6 Package Dependency Graph”@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/sharedimports nothing from the monorepo. It is the leaf.packages/dbdepends only onshared.packages/coredepends ondbandshared. It is pure business logic — no Zakardo runtime imports.packages/capabilitiesdepends oncore,db, andshared. It imports@zakardo/corefor thedefineCapabilityAPI.packages/catalogdepends only onshared. It has no backend dependencies.apps/apiimports everything. It is the composition root for the backend.apps/webimportscatalogandshared. It has no backend dependencies (communicates via HTTP/SSE).
3. Backend: apps/api
Section titled “3. Backend: apps/api”3.1 HTTP Layer: Hono
Section titled “3.1 HTTP Layer: Hono”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.
3.2 Two-Layer Backend
Section titled “3.2 Two-Layer Backend”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:
| Directory | Purpose | Examples |
|---|---|---|
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 scheduling | Cron 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:
- Loads all capabilities from
packages/capabilities. - Loads configuration from
config/. - Loads policies from
policies/. - Loads plans from
plans/. - Initializes the Execution Engine, Planner, Validator, Policy Engine.
- Registers all
/zakardo/*HTTP routes and SSE endpoints.
3.3 Server Entry Point
Section titled “3.3 Server Entry Point”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 middlewareapp.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;3.4 Zakardo Mount
Section titled “3.4 Zakardo Mount”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.
3.5 Shared Resources
Section titled “3.5 Shared Resources”Both layers share:
- Auth middleware. The same
authMiddlewareprotects Foundation routes and Zakardo routes. The Auth Provider (configured inconfig/auth.ts) resolves user identity. - Database connection. The same ORM client (from
packages/db) is used by Foundation services and injected into capabilities viacontext.services.db. - Service providers. Foundation services (billing, notifications, etc.) defined in
packages/corecan be injected into capabilities viaconfig/services.ts.
3.6 Foundation ↔ Capability Interaction
Section titled “3.6 Foundation ↔ Capability Interaction”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.
4. Shared Packages
Section titled “4. Shared Packages”4.1 packages/shared
Section titled “4.1 packages/shared”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.jsonRules: No database imports. No API imports. No framework imports. Only pure TypeScript.
4.2 packages/db
Section titled “4.2 packages/db”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.jsonThe packages/db package exports:
- The ORM client (e.g.,
PrismaClientor Drizzledbinstance). - 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.
4.3 packages/core
Section titled “4.3 packages/core”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.jsonWhat goes in core:
- Business logic that is not capability-specific but is used by capabilities. Example: A
calculateOrderTotalfunction used by both thecreate_ordercapability and the/api/v1/ordersFoundation 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).
4.4 packages/capabilities
Section titled “4.4 packages/capabilities”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.jsonEach capability is defined using defineCapability from @zakardo/core:
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(), }; },});4.5 packages/catalog
Section titled “4.5 packages/catalog”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.jsonCustom catalogs extend the Zakardo Standard Catalog. Components are registered via A2UI’s extensible catalog mechanism so capabilities can reference them in view declarations.
5. Configuration Architecture
Section titled “5. Configuration Architecture”5.1 Design Principles
Section titled “5.1 Design Principles”- 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.tsimports 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).
5.2 Config Directory
Section titled “5.2 Config Directory”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 configuration5.3 Root Config
Section titled “5.3 Root Config”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.
5.4 Data Config
Section titled “5.4 Data Config”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 }) }, },});5.5 Auth Config
Section titled “5.5 Auth Config”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, }, }, },});5.6 LLM Config
Section titled “5.6 LLM Config”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.', ],});5.7 Services Config
Section titled “5.7 Services Config”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(), },});5.8 Execution Config
Section titled “5.8 Execution Config”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, },});5.9 Trace Config
Section titled “5.9 Trace Config”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, },});5.10 Training Config
Section titled “5.10 Training Config”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, },});6. Environment Management
Section titled “6. Environment Management”6.1 Design
Section titled “6.1 Design”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.tsdefines all required and optional variables with Zod schemas. - Per-environment
.envfiles provide values. - The schema is imported wherever env vars are needed.
- Server-only and client-safe variables are separated.
6.2 Schema
Section titled “6.2 Schema”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,});6.3 Environment Files
Section titled “6.3 Environment Files”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.exampleis committed to the repo. It contains every variable with a dummy/placeholder value and a comment explaining its purpose..env,.env.staging,.env.productionare gitignored (they contain secrets).env/schema.tsis committed. It is the source of truth for what variables exist and what shape they must have.- The
envimport is used inconfig/*.tsfiles and inapps/api/src/server.ts. It is never imported directly in capabilities — capabilities receive services via context injection.
6.4 Environment Resolution
Section titled “6.4 Environment Resolution”At startup, the runtime resolves the active environment:
- Read
NODE_ENV(defaults todevelopment). - Load
.env(base). - Load
.env.{NODE_ENV}if it exists (overrides base). - Validate all variables against
env/schema.ts. - If validation fails: print a clear error listing every invalid/missing variable and exit.
7. Infrastructure
Section titled “7. Infrastructure”7.1 Local Development Infrastructure
Section titled “7.1 Local Development Infrastructure”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).
7.2 Production Dockerfiles
Section titled “7.2 Production Dockerfiles”FROM node:20-alpine AS baseRUN corepack enable && corepack prepare pnpm@latest --activate
FROM base AS buildWORKDIR /appCOPY 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-lockfileRUN pnpm turbo build --filter=api
FROM base AS runtimeWORKDIR /appCOPY --from=build /app/apps/api/dist ./distCOPY --from=build /app/node_modules ./node_modulesEXPOSE 3000CMD ["node", "dist/server.js"]FROM node:20-alpine AS baseRUN corepack enable && corepack prepare pnpm@latest --activate
FROM base AS buildWORKDIR /appCOPY pnpm-lock.yaml pnpm-workspace.yaml package.json turbo.json ./COPY packages/ packages/COPY apps/web/ apps/web/RUN pnpm install --frozen-lockfileRUN pnpm turbo build --filter=web
FROM nginx:alpine AS runtimeCOPY --from=build /app/apps/web/dist /usr/share/nginx/htmlCOPY infra/nginx.conf /etc/nginx/conf.d/default.confEXPOSE 807.3 Deployment
Section titled “7.3 Deployment”The Framework Specification does not prescribe a specific deployment platform. The infrastructure directory provides the building blocks:
| File | Purpose |
|---|---|
infra/docker-compose.yml | Local dev: Postgres + Redis |
infra/docker-compose.prod.yml | Production-like local setup (API + Web + Postgres) |
infra/Dockerfile.api | API server container |
infra/Dockerfile.web | Frontend static build container |
infra/nginx.conf | Nginx config for frontend SPA routing |
Developers add platform-specific deployment configs as needed (Fly.io fly.toml, Railway railway.json, Kubernetes manifests, Terraform, etc.).
8. Development Server
Section titled “8. Development Server”8.1 zakardo dev
Section titled “8.1 zakardo dev”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 migration8.2 What zakardo dev Does
Section titled “8.2 What zakardo dev Does”- Checks prerequisites. Docker running? Node.js version? pnpm installed?
- Starts infrastructure. Runs
docker compose up -dfrominfra/docker-compose.ymlif not already running. - Runs migrations. Checks for pending database migrations and applies them.
- Validates environment. Loads
env/schema.tsand validates all variables. - Starts backend. Launches the Hono server with hot-reload (via
tsx watchor similar). Automatically loads capabilities, policies, and plans. - Starts frontend. Launches Vite dev server with HMR for the frontend app.
- Starts Zakardo Studio. Mounts the Studio UI at
/zakardo/studiowithin the backend server. - Watches for changes. File watchers on capabilities, policies, plans, and config trigger appropriate reloads:
| Change | Action |
|---|---|
| Capability source code | Re-register capability (no server restart) |
| Policy JSON file | Re-load policy set (no server restart) |
| Plan JSON file | Re-load plan library (no server restart) |
| Config file | Restart Zakardo Runtime |
| Database schema | Prompt developer to run migration |
| Foundation route | Hot-reload via standard Hono/tsx mechanism |
| Frontend code | Vite HMR (instant) |
8.3 Selective Start
Section titled “8.3 Selective Start”Developers can start only what they need:
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 Compose9. Build and Validation
Section titled “9. Build and Validation”9.1 zakardo build
Section titled “9.1 zakardo build”Builds the application for production:
$ 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.9.2 zakardo validate
Section titled “9.2 zakardo validate”Validates all Zakardo artifacts without building:
$ 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. ✓10. Scaffolding
Section titled “10. Scaffolding”10.1 create-zakardo
Section titled “10.1 create-zakardo”The project scaffolding CLI:
$ 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 dev10.2 Component Generators
Section titled “10.2 Component Generators”The CLI provides generators for common artifacts:
| Command | Creates | Location |
|---|---|---|
zakardo capability:new customers/get_customer | Capability scaffold | packages/capabilities/src/customers/get_customer.ts |
zakardo route:new api/v1/reports | Foundation route scaffold | apps/api/src/foundation/api/reports.ts |
zakardo policy:new high-value-approval | Policy JSON scaffold | policies/high-value-approval.json |
zakardo plan:new onboard-customer | Plan IR scaffold | plans/onboard-customer.json |
zakardo service:new notification | Service provider scaffold | packages/core/src/services/notification.ts + config/services.ts update |
zakardo component:new DealPipeline | Custom A2UI component scaffold | packages/catalog/src/components/DealPipeline.ts |
Each generator:
- Creates the file with a working scaffold (imports, types, stub implementation).
- Updates the relevant index file to export the new artifact.
- Runs the TypeScript compiler to verify no errors.
11. Zakardo Studio
Section titled “11. Zakardo Studio”11.1 Overview
Section titled “11.1 Overview”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.
11.2 Features
Section titled “11.2 Features”| Feature | Description |
|---|---|
| Capability Browser | List all registered capabilities. View schemas, effect classes, constraints, interaction specs. Test individual capabilities with mock inputs. |
| Intent Playground | Submit intents and see the full pipeline: Planner response (GENERATE/CLARIFY/CONVERSE), Plan Draft, enriched Plan IR, Validator result. |
| Plan Tester | Load a plan, execute it in SIMULATED mode, inspect results step by step. |
| Trace Viewer | Browse execution traces. Expand each step to see inputs, outputs, timing, gate resolutions, interaction responses. |
| Plan Explorer | Navigate 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 Browser | View all registered prompts (system + overrides + custom). Preview rendered prompt output with sample variables. Compare prompt versions. See §13 below. |
| Policy Inspector | View all loaded policies. Test a policy against a mock capability invocation. |
| Training Dashboard | Run training datasets, view pass/fail results, compare actual vs. expected. Manage Plan Library snapshots and warmup configuration. See §14 below. |
| Config Viewer | View the resolved configuration (with secrets redacted). Verify mode-aware service resolution. |
| A2UI Preview | Preview A2UI surfaces. Test anchored views with sample data. |
11.3 Implementation
Section titled “11.3 Implementation”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.
12. TypeScript Configuration
Section titled “12. TypeScript Configuration”12.1 Shared Base Config
Section titled “12.1 Shared Base Config”// 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:
{ "extends": "../../tsconfig.json", "compilerOptions": { "outDir": "dist", "rootDir": "src" }, "include": ["src"], "references": [{ "path": "../shared" }, { "path": "../db" }, { "path": "../core" }]}13. Prompt Management System
Section titled “13. Prompt Management System”13.1 Overview
Section titled “13.1 Overview”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.
13.2 Prompt Registry
Section titled “13.2 Prompt Registry”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 configurationOn startup, the runtime loads prompts with a resolution order:
- Developer override (
prompts/overrides/<name>.hbs) — highest priority. - System default (
prompts/system/<name>.hbs) — shipped with@zakardo/core, copied to project on scaffold.
13.3 Template Format
Section titled “13.3 Template Format”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 donethat maps to available capabilities. - EXPLORATORY: The user is asking a question or seekinginformation. - 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:
| Field | Purpose |
|---|---|
@name | Unique prompt identifier (matches filename) |
@version | Semver version. Must be bumped when content changes. |
@description | Human-readable description |
@model | Target model role from LLM config (planning, classification, etc.) |
@variables | Comma-separated list of required template variables |
13.4 Developer Overrides
Section titled “13.4 Developer Overrides”To customize a system prompt, the developer copies it to prompts/overrides/ and modifies:
# Copy and customizecp prompts/system/intent-classifier.hbs prompts/overrides/intent-classifier.hbs# Edit the override...Override rules:
- The override file must use the same
@nameas 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.
13.5 Custom Prompts
Section titled “13.5 Custom Prompts”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.
13.6 Prompt Configuration
Section titled “13.6 Prompt Configuration”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', },});13.7 Validation
Section titled “13.7 Validation”zakardo validate prompts checks:
| Check | Description |
|---|---|
| Template syntax | All .hbs files parse without errors |
| Metadata present | @name, @version, @variables defined |
| Variables declared | All {{variable}} references have matching @variables declaration |
| Version bumped | If content changed since last build, version must be bumped |
| Override compatibility | Override declares same @variables as system original |
| No orphan overrides | Every file in overrides/ has a matching system prompt |
13.8 Prompt Traceability
Section titled “13.8 Prompt Traceability”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.
13B. Plan Explorer
Section titled “13B. Plan Explorer”13B.1 Overview
Section titled “13B.1 Overview”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.
13B.2 Execution Audit Log
Section titled “13B.2 Execution Audit Log”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"}13B.3 Plan Analytics
Section titled “13B.3 Plan Analytics”The runtime computes aggregate metrics from audit entries:
| Metric | Description |
|---|---|
| Plan generation frequency | How 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 plan | Mean execution time per plan |
| Cost per plan | Average LLM token cost per plan execution |
| Capability hotspots | Most frequently invoked capabilities |
| Gate trigger rate | % of executions that hit a governance gate |
| Error distribution | Error types grouped by category |
13B.4 API Endpoints
Section titled “13B.4 API Endpoints”GET /zakardo/v1/audit-log # Paginated audit entriesGET /zakardo/v1/audit-log/:auditId # Single audit entryGET /zakardo/v1/audit-log/export # Export as CSV or JSONGET /zakardo/v1/plans/analytics # Aggregate plan analyticsGET /zakardo/v1/plans/analytics/:planId # Analytics for a specific planGET /zakardo/v1/plans/:planId/versions # Version history with diffAll endpoints support filtering:
| Filter | Example |
|---|---|
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 |
13B.5 Storage
Section titled “13B.5 Storage”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));13B.6 Studio Plan Explorer Panel
Section titled “13B.6 Studio Plan Explorer Panel”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.
14. Training Infrastructure
Section titled “14. Training Infrastructure”14.1 Overview
Section titled “14.1 Overview”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.
14.2 Warmup
Section titled “14.2 Warmup”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:
# Run warmup training (typically in CI/CD before deploy)zakardo training warmupThis executes:
- Load all datasets listed in
training/warmup.json. - Run each dataset through the full pipeline (Planner → Enrichment → Validator → Execution Engine in TRAINING mode).
- Plans that pass are promoted to the Plan Library.
- Export a Plan Library snapshot (see §14.3).
{ "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 }}14.3 Plan Library Snapshots
Section titled “14.3 Plan Library Snapshots”The output of training is a Plan Library snapshot — a JSON export of all promoted plans with their trust scores, version metadata, and associations:
{ "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 calls14.4 Incremental Training
Section titled “14.4 Incremental Training”When a developer adds a new capability, they should not need to retrain everything:
# Run only new or changed datasetszakardo training run --incrementalHow --incremental works:
- Compare current datasets to the last training run’s dataset manifest.
- Identify new datasets (not in previous manifest) and changed datasets (content hash differs).
- Run only those datasets.
- Existing promoted plans that don’t reference changed capabilities are untouched.
- 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 updated14.5 Continuous Improvement Loop
Section titled “14.5 Continuous Improvement Loop”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 planThis creates a virtuous cycle: production executions produce traces, traces become training data, training data produces better plans, better plans improve production executions.
14.6 Training Environments
Section titled “14.6 Training Environments”| Command | Environment | External Services | Database |
|---|---|---|---|
zakardo training run | TRAINING mode | Mock services (fixtures) | Fixtures DB (FIXTURES_DB_URL) |
zakardo training run --mode dry_run | DRY_RUN mode | Real services (read-only) | Real DB (read-only) |
zakardo training warmup | TRAINING mode | Mock services | Fixtures DB |
14.7 Cost Management
Section titled “14.7 Cost Management”Training runs consume LLM tokens for planning. Configuration options:
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});14.8 Project Structure
Section titled “14.8 Project Structure”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 script14.9 Cloud Integration
Section titled “14.9 Cloud Integration”Zakardo Cloud extends the local training infrastructure with:
| Feature | OSS (Local) | Cloud |
|---|---|---|
| Training run execution | CLI (zakardo training run) | Scheduled runs, webhook triggers |
| Results storage | Local zakardo_training_runs table | Cloud-hosted, cross-environment aggregation |
| Regression alerts | CLI output, exit codes | Slack/email notifications, dashboard alerts |
| Training dashboard | Studio Training Dashboard | Cloud Training Dashboard with historical trends |
| Snapshot management | Local files | Versioned cloud storage, rollback support |
| Cost tracking | Config-based caps | Per-run cost tracking, budget dashboards |
The OSS framework provides a complete, self-contained training experience. Cloud adds visibility, automation, and team-scale management.
15. Testing Framework
Section titled “15. Testing Framework”15.1 Overview
Section titled “15.1 Overview”Zakardo introduces new execution primitives (capabilities, plans, policies, A2UI composition) that require new testing primitives. The testing framework serves two audiences:
- Zakardo contributors — testing
@zakardo/coreinternals. - Zakardo consumers — testing applications built on the framework.
This section focuses on the consumer testing framework: @zakardo/test.
15.2 @zakardo/test Package
Section titled “15.2 @zakardo/test Package”@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.
15.3 Core API
Section titled “15.3 Core API”createTestRuntime()
Section titled “createTestRuntime()”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.
testIntent()
Section titled “testIntent()”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;}testCapability()
Section titled “testCapability()”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', { });
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) }, ]);});testPlan()
Section titled “testPlan()”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);});testPolicy()
Section titled “testPolicy()”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');});mockCapability()
Section titled “mockCapability()”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});15.4 Snapshot Testing
Section titled “15.4 Snapshot Testing”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).
15.5 A2UI Output Testing
Section titled “15.5 A2UI Output Testing”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);});15.6 Test Configuration
Section titled “15.6 Test Configuration”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'], },});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});15.7 CLI Integration
Section titled “15.7 CLI Integration”# Run all testszakardo test
# Run specific test fileszakardo test capabilitieszakardo test planszakardo test policies
# Run with real LLM (integration tests)zakardo test --llm real
# Run with coveragezakardo test --coveragezakardo test is a thin wrapper around vitest that pre-configures the Zakardo test environment.
15.8 What to Test (Guidelines)
Section titled “15.8 What to Test (Guidelines)”| What | How | Example |
|---|---|---|
| Individual capabilities | testCapability() — verify input/output, side effects | Does create_customer validate email format? |
| Plans end-to-end | testPlan() — verify step sequence, data flow, final output | Does the onboarding plan send a welcome email? |
| Intent resolution | testIntent() — verify the full pipeline from NL to result | Does “show inactive customers” resolve correctly? |
| Policy enforcement | testPolicy() — verify gate triggers and allow/deny | Do high-value orders require approval? |
| Plan regression | toMatchPlanSnapshot() — verify plan structure stability | Did the plan change after a capability update? |
| A2UI output | testA2UIOutput() — verify component rendering | Does the dashboard capability produce a DataTable? |
| Error handling | mockCapability() + testPlan() — verify failure paths | Does the plan handle Stripe API failures gracefully? |
| Training datasets | zakardo training run — verify known inputs produce expected outputs | See Training and Validation Specification |
16. Decisions Made in This Document
Section titled “16. Decisions Made in This Document”| Decision | Rationale |
|---|---|
| Turborepo + pnpm for monorepo | Best-in-class for TypeScript monorepos. Zero-config caching, strict deps, workspace protocol. |
| Hono as HTTP layer | TypeScript-native, lightweight, web-standards, fast router, edge-compatible. Does not constrain deployment. |
| Two-layer backend | Not everything is agentic. Auth, billing, CRUD, webhooks need standard HTTP endpoints. One server, two concerns. |
| Atomic config files | Single-responsibility. Each file grows independently. No 500-line monolithic config. |
| t3-env for environment management | Type-safe, fail-fast. No more “undefined is not a function” because a env var was missing. |
| Foundation ↔ Capability direction | Capabilities call Foundation services, not the reverse. Prevents coupling Foundation routes to the Zakardo runtime. |
| Studio as dev-only tool | Reduces 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 dev | Fast HMR, wide framework support (React, Vue, Svelte, Angular via analog). Standard for modern frontend development. |
| Prompts as versioned templates | Prompts drive agent behavior and must be auditable, customizable, and reproducible. Handlebars templates with metadata provide all three. |
| Developer prompt overrides | Developers need to customize agent behavior for their domain without forking the framework. Override-by-filename is simple and visible. |
| Plan Explorer as framework layer | Audit and analytics are too important to be Studio-only. API endpoints + data model enable Cloud dashboard and custom integrations. |
| Warmup + Plan Library snapshots | Pre-generating proven plans eliminates cold-start latency and LLM cost for common intents. |
| Incremental training | Full retraining on every change is wasteful. Only new/changed datasets run; existing promoted plans are preserved. |
@zakardo/test as dedicated package | Agent-native testing needs agent-native primitives (testIntent, testCapability, testPolicy). Generic test utils cannot provide the right abstractions. |
| Vitest as test runner | Modern, fast, TypeScript-native, compatible with the Vite-based frontend. |
17. Questions Deferred to Other Specifications
Section titled “17. Questions Deferred to Other Specifications”| Question | Deferred 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 |