diff --git a/content/docs/references/ai/devops-agent.mdx b/content/docs/references/ai/devops-agent.mdx
new file mode 100644
index 000000000..4f7583ce0
--- /dev/null
+++ b/content/docs/references/ai/devops-agent.mdx
@@ -0,0 +1,293 @@
+---
+title: DevOps Agent
+description: DevOps Agent protocol schemas
+---
+
+# DevOps Agent
+
+
+**Source:** `packages/spec/src/ai/devops-agent.zod.ts`
+
+
+## Overview
+
+The DevOps Agent Protocol defines autonomous DevOps agents that can self-iterate on enterprise management software development using the ObjectStack specification. These agents integrate with GitHub for version control and Vercel for deployment, enabling fully automated development, testing, and release cycles.
+
+## TypeScript Usage
+
+```typescript
+import {
+ DevOpsAgentSchema,
+ CodeGenerationConfigSchema,
+ CICDPipelineConfigSchema,
+ DeploymentStrategySchema,
+ MonitoringConfigSchema
+} from '@objectstack/spec/ai';
+
+import type {
+ DevOpsAgent,
+ CodeGenerationConfig,
+ CICDPipelineConfig,
+ DeploymentStrategy,
+ MonitoringConfig
+} from '@objectstack/spec/ai';
+
+// Define a DevOps agent
+const devOpsAgent: DevOpsAgent = {
+ name: 'devops_automation_agent',
+ label: 'DevOps Automation Agent',
+ role: 'Senior Full-Stack DevOps Engineer',
+ instructions: '...',
+ model: {
+ provider: 'openai',
+ model: 'gpt-4-turbo-preview',
+ temperature: 0.3
+ },
+ developmentConfig: {
+ specificationSource: 'packages/spec',
+ codeGeneration: {
+ enabled: true,
+ targets: ['frontend', 'backend', 'api']
+ }
+ },
+ integrations: {
+ github: {
+ connector: 'github_production',
+ repository: {
+ owner: 'objectstack-ai',
+ name: 'app'
+ }
+ },
+ vercel: {
+ connector: 'vercel_production',
+ project: 'objectstack-app'
+ }
+ }
+};
+
+// Validate
+const validatedAgent = DevOpsAgentSchema.parse(devOpsAgent);
+```
+
+---
+
+## Key Components
+
+### DevOpsAgent
+
+Extends the base `AgentSchema` with DevOps-specific configurations:
+
+**Additional Properties:**
+- `developmentConfig` (DevelopmentConfig) - Development configuration
+- `pipelines` (CICDPipelineConfig[], optional) - CI/CD pipelines
+- `versionManagement` (VersionManagement, optional) - Version management
+- `deploymentStrategy` (DeploymentStrategy, optional) - Deployment strategy
+- `monitoring` (MonitoringConfig, optional) - Monitoring configuration
+- `integrations` (IntegrationConfig) - GitHub and Vercel integrations
+- `selfIteration` (object, optional) - Self-iteration configuration
+
+---
+
+### CodeGenerationConfig
+
+Configuration for automated code generation.
+
+**Properties:**
+- `enabled` (boolean) - Enable code generation (default: true)
+- `targets` (CodeGenerationTarget[]) - Generation targets
+- `templateRepo` (string, optional) - Template repository
+- `styleGuide` (string, optional) - Code style guide
+- `includeTests` (boolean) - Generate tests (default: true)
+- `includeDocumentation` (boolean) - Generate docs (default: true)
+- `validationMode` ('strict' | 'moderate' | 'permissive') - Validation strictness
+
+**Code Generation Targets:**
+- `frontend` - Frontend UI components
+- `backend` - Backend services
+- `api` - API endpoints
+- `database` - Database schemas
+- `tests` - Test suites
+- `documentation` - Documentation
+- `infrastructure` - Infrastructure as code
+
+---
+
+### CICDPipelineConfig
+
+CI/CD pipeline configuration.
+
+**Properties:**
+- `name` (string) - Pipeline name
+- `trigger` ('push' | 'pull_request' | 'release' | 'schedule' | 'manual') - Trigger type
+- `branches` (string[], optional) - Branch filters
+- `stages` (PipelineStage[]) - Pipeline stages
+- `notifications` (object, optional) - Notification settings
+
+**Pipeline Stage Types:**
+- `build` - Build stage
+- `test` - Test execution
+- `lint` - Code linting
+- `security_scan` - Security scanning
+- `deploy` - Deployment
+- `smoke_test` - Post-deployment tests
+- `rollback` - Rollback to previous version
+
+---
+
+### DeploymentStrategy
+
+Deployment strategy configuration.
+
+**Properties:**
+- `type` ('rolling' | 'blue_green' | 'canary' | 'recreate') - Strategy type
+- `canaryPercentage` (number) - Canary percentage (default: 10)
+- `healthCheckUrl` (string, optional) - Health check endpoint
+- `healthCheckTimeout` (number) - Timeout in seconds (default: 60)
+- `autoRollback` (boolean) - Auto-rollback on failure (default: true)
+- `smokeTests` (string[], optional) - Smoke test commands
+
+---
+
+### GitHubIntegration
+
+GitHub integration configuration.
+
+**Properties:**
+- `connector` (string) - GitHub connector name
+- `repository` (object) - Repository config (owner, name)
+- `featureBranch` (string) - Default feature branch (default: 'develop')
+- `pullRequest` (object, optional) - PR settings
+ - `autoCreate` (boolean) - Auto-create PRs (default: true)
+ - `autoMerge` (boolean) - Auto-merge when checks pass (default: false)
+ - `requireReviews` (boolean) - Require reviews (default: true)
+ - `deleteBranchOnMerge` (boolean) - Delete after merge (default: true)
+
+---
+
+### VercelIntegration
+
+Vercel deployment integration configuration.
+
+**Properties:**
+- `connector` (string) - Vercel connector name
+- `project` (string) - Vercel project name
+- `environments` (object, optional) - Environment mapping
+ - `production` (string) - Production branch (default: 'main')
+ - `preview` (string[]) - Preview branches
+- `deployment` (object, optional) - Deployment settings
+ - `autoDeployProduction` (boolean) - Auto-deploy prod (default: false)
+ - `autoDeployPreview` (boolean) - Auto-deploy preview (default: true)
+ - `requireApproval` (boolean) - Require approval (default: true)
+
+---
+
+## Use Cases
+
+### 1. Automated Feature Development
+
+```typescript
+const featureDevAgent: DevOpsAgent = {
+ name: 'feature_dev_agent',
+ label: 'Feature Development Agent',
+ role: 'Full-Stack Developer',
+ instructions: 'Generate features from specifications',
+ model: { provider: 'openai', model: 'gpt-4-turbo' },
+ developmentConfig: {
+ specificationSource: 'packages/spec',
+ codeGeneration: {
+ enabled: true,
+ targets: ['frontend', 'backend', 'api', 'tests'],
+ validationMode: 'strict',
+ includeTests: true
+ }
+ },
+ integrations: {
+ github: {
+ connector: 'github_main',
+ repository: { owner: 'myorg', name: 'app' },
+ pullRequest: {
+ autoCreate: true,
+ requireReviews: true
+ }
+ },
+ vercel: {
+ connector: 'vercel_main',
+ project: 'myapp',
+ deployment: {
+ autoDeployPreview: true,
+ autoDeployProduction: false
+ }
+ }
+ }
+};
+```
+
+### 2. Continuous Integration Pipeline
+
+```typescript
+const ciPipeline: CICDPipelineConfig = {
+ name: 'CI Pipeline',
+ trigger: 'pull_request',
+ branches: ['main', 'develop'],
+ stages: [
+ {
+ name: 'Lint',
+ type: 'lint',
+ order: 1,
+ parallel: false,
+ commands: ['pnpm run lint'],
+ timeout: 180,
+ retryOnFailure: false,
+ maxRetries: 0
+ },
+ {
+ name: 'Test',
+ type: 'test',
+ order: 2,
+ parallel: false,
+ commands: ['pnpm run test:ci'],
+ timeout: 600,
+ retryOnFailure: false,
+ maxRetries: 0
+ }
+ ]
+};
+```
+
+### 3. Canary Deployment
+
+```typescript
+const canaryDeployment: DeploymentStrategy = {
+ type: 'canary',
+ canaryPercentage: 10,
+ healthCheckUrl: '/api/health',
+ healthCheckTimeout: 60,
+ autoRollback: true,
+ smokeTests: ['pnpm run test:smoke']
+};
+```
+
+---
+
+## Architecture
+
+The DevOps Agent follows these principles:
+
+1. **Self-Iterating Development**: Continuously improves based on feedback
+2. **Automated Code Generation**: Follows ObjectStack specifications
+3. **Continuous Integration**: Automated testing and validation
+4. **Version Management**: Semantic versioning with changelogs
+5. **Monitoring and Rollback**: Automated health checks and rollbacks
+
+---
+
+## Best Practices
+
+1. **Start with strict validation**: Use `validationMode: 'strict'` for production
+2. **Enable testing**: Always set `includeTests: true`
+3. **Require reviews**: Set `requireReviews: true` for production deployments
+4. **Auto-rollback**: Enable `autoRollback: true` for safety
+5. **Monitor deployments**: Configure comprehensive monitoring alerts
+6. **Use feature branches**: Follow Git flow with feature branches
+7. **Semantic versioning**: Use `scheme: 'semver'` for version management
+8. **Gradual rollouts**: Use canary deployments for critical changes
diff --git a/content/docs/references/ai/feedback-loop.mdx b/content/docs/references/ai/feedback-loop.mdx
new file mode 100644
index 000000000..eb440bcc0
--- /dev/null
+++ b/content/docs/references/ai/feedback-loop.mdx
@@ -0,0 +1,427 @@
+---
+title: Feedback Loop
+description: Feedback Loop protocol schemas
+---
+
+# Feedback Loop
+
+
+**Source:** `packages/spec/src/ai/feedback-loop.zod.ts`
+
+
+## Overview
+
+The Feedback Loop Protocol defines the structure for AI-powered runtime issue detection, analysis, and automated resolution. It enables the system to identify issues, trace them back to their metadata source, and propose automated fixes.
+
+This creates a self-healing architecture where runtime errors can trigger metadata changes, closing the loop between development and production.
+
+## TypeScript Usage
+
+```typescript
+import {
+ FeedbackLoopSchema,
+ IssueSchema,
+ ResolutionSchema,
+ MetadataSourceSchema
+} from '@objectstack/spec/ai';
+
+import type {
+ FeedbackLoop,
+ Issue,
+ Resolution,
+ MetadataSource
+} from '@objectstack/spec/ai';
+
+// Record a runtime issue
+const issue: Issue = {
+ id: 'issue-001',
+ severity: 'error',
+ message: 'Validation failed on field "email"',
+ timestamp: new Date().toISOString(),
+ userId: 'user-123',
+ context: {
+ object: 'contact',
+ field: 'email',
+ value: 'invalid-email'
+ },
+ source: {
+ package: '@myapp/crm',
+ object: 'contact',
+ field: 'email',
+ file: 'packages/crm/src/objects/contact.object.ts',
+ line: 45
+ }
+};
+
+// Create a feedback loop
+const feedbackLoop: FeedbackLoop = {
+ issue,
+ analysis: 'Email validation rule is too permissive',
+ resolutions: [
+ {
+ issueId: 'issue-001',
+ reasoning: 'Add stricter email validation pattern',
+ confidence: 0.95,
+ fix: {
+ type: 'metadata_change',
+ changeSet: {
+ // ChangeSet definition
+ }
+ }
+ }
+ ],
+ status: 'analyzing'
+};
+
+// Validate
+const validatedLoop = FeedbackLoopSchema.parse(feedbackLoop);
+```
+
+---
+
+## MetadataSource
+
+Identifies the source of truth for metadata that caused the issue.
+
+**Properties:**
+- `file` (string, optional) - Source file path
+- `line` (number, optional) - Line number in file
+- `column` (number, optional) - Column number in file
+- `package` (string, optional) - Package name
+- `object` (string, optional) - Object name
+- `field` (string, optional) - Field name
+- `component` (string, optional) - UI component or flow node
+
+**Example:**
+```typescript
+const source: MetadataSource = {
+ file: 'packages/crm/src/objects/contact.object.ts',
+ line: 45,
+ column: 12,
+ package: '@myapp/crm',
+ object: 'contact',
+ field: 'email'
+};
+```
+
+---
+
+## Issue
+
+Represents a runtime issue detected in the system.
+
+**Properties:**
+- `id` (string) - Unique issue identifier
+- `severity` ('critical' | 'error' | 'warning' | 'info') - Issue severity
+- `message` (string) - Error message
+- `stackTrace` (string, optional) - Stack trace
+- `timestamp` (string) - ISO datetime when issue occurred
+- `userId` (string, optional) - User who encountered the issue
+- `context` (`Record`, optional) - Context snapshot
+- `source` (MetadataSource, optional) - Suspected metadata source
+
+**Severity Levels:**
+- `critical` - System-breaking issues requiring immediate attention
+- `error` - Functional errors that prevent normal operation
+- `warning` - Issues that may cause problems but don't break functionality
+- `info` - Informational issues for optimization
+
+**Example:**
+```typescript
+const issue: Issue = {
+ id: 'issue-002',
+ severity: 'critical',
+ message: 'Database connection failed',
+ stackTrace: 'Error: ECONNREFUSED...',
+ timestamp: '2026-02-02T10:30:00.000Z',
+ context: {
+ datasource: 'postgres_main',
+ operation: 'connect'
+ },
+ source: {
+ package: '@myapp/core',
+ file: 'packages/core/src/datasources.ts',
+ line: 23
+ }
+};
+```
+
+---
+
+## Resolution
+
+AI-proposed resolution for an issue.
+
+**Properties:**
+- `issueId` (string) - Reference to issue ID
+- `reasoning` (string) - Explanation of why this fix is needed
+- `confidence` (number) - Confidence score (0-1)
+- `fix` (discriminated union) - The proposed fix
+
+**Fix Types:**
+
+### 1. Metadata Change
+Proposes a change to metadata configuration.
+
+```typescript
+{
+ type: 'metadata_change',
+ changeSet: ChangeSetSchema
+}
+```
+
+### 2. Manual Intervention
+Requires human intervention with instructions.
+
+```typescript
+{
+ type: 'manual_intervention',
+ instructions: 'Update database credentials in environment variables'
+}
+```
+
+**Example:**
+```typescript
+const resolution: Resolution = {
+ issueId: 'issue-001',
+ reasoning: 'Add email validation pattern to prevent invalid formats',
+ confidence: 0.95,
+ fix: {
+ type: 'metadata_change',
+ changeSet: {
+ operation: 'update',
+ object: 'contact',
+ field: 'email',
+ changes: {
+ validation: {
+ pattern: '^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}$',
+ message: 'Please enter a valid email address'
+ }
+ }
+ }
+ }
+};
+```
+
+---
+
+## FeedbackLoop
+
+Complete feedback loop record tracking issue resolution.
+
+**Properties:**
+- `issue` (Issue) - The detected issue
+- `analysis` (string, optional) - AI analysis of root cause
+- `resolutions` (Resolution[], optional) - Proposed resolutions
+- `status` ('open' | 'analyzing' | 'resolved' | 'ignored') - Current status
+
+**Workflow:**
+1. **open** - Issue detected, awaiting analysis
+2. **analyzing** - AI is analyzing the issue
+3. **resolved** - Fix applied successfully
+4. **ignored** - Issue marked as non-critical or false positive
+
+**Example:**
+```typescript
+const feedbackLoop: FeedbackLoop = {
+ issue: {
+ id: 'issue-003',
+ severity: 'warning',
+ message: 'Slow query detected on contact list',
+ timestamp: '2026-02-02T11:00:00.000Z',
+ context: {
+ object: 'contact',
+ query: 'list_all_contacts',
+ duration: 2500
+ }
+ },
+ analysis: 'Missing database index on frequently queried field "last_name"',
+ resolutions: [
+ {
+ issueId: 'issue-003',
+ reasoning: 'Add index on last_name field to improve query performance',
+ confidence: 0.98,
+ fix: {
+ type: 'metadata_change',
+ changeSet: {
+ operation: 'add_index',
+ object: 'contact',
+ index: {
+ fields: ['last_name'],
+ type: 'btree'
+ }
+ }
+ }
+ }
+ ],
+ status: 'resolved'
+};
+```
+
+---
+
+## Use Cases
+
+### 1. Automated Validation Fix
+
+```typescript
+const validationIssue: FeedbackLoop = {
+ issue: {
+ id: 'val-001',
+ severity: 'error',
+ message: 'Invalid phone number format',
+ timestamp: new Date().toISOString(),
+ context: {
+ object: 'contact',
+ field: 'phone',
+ value: '123'
+ },
+ source: {
+ object: 'contact',
+ field: 'phone'
+ }
+ },
+ analysis: 'Phone validation rule is missing or too permissive',
+ resolutions: [
+ {
+ issueId: 'val-001',
+ reasoning: 'Add phone number validation pattern',
+ confidence: 0.92,
+ fix: {
+ type: 'metadata_change',
+ changeSet: {
+ operation: 'update',
+ object: 'contact',
+ field: 'phone',
+ changes: {
+ validation: {
+ pattern: '^\\+?[1-9]\\d{1,14}$',
+ message: 'Please enter a valid phone number'
+ }
+ }
+ }
+ }
+ }
+ ],
+ status: 'resolved'
+};
+```
+
+### 2. Permission Issue Detection
+
+```typescript
+const permissionIssue: FeedbackLoop = {
+ issue: {
+ id: 'perm-001',
+ severity: 'critical',
+ message: 'Unauthorized access to sensitive data',
+ timestamp: new Date().toISOString(),
+ userId: 'user-456',
+ context: {
+ object: 'financial_record',
+ operation: 'read',
+ userRole: 'guest'
+ },
+ source: {
+ object: 'financial_record',
+ file: 'packages/finance/src/objects/financial-record.object.ts'
+ }
+ },
+ analysis: 'Missing or incorrect permission rules for financial_record object',
+ resolutions: [
+ {
+ issueId: 'perm-001',
+ reasoning: 'Add strict permission rules to prevent unauthorized access',
+ confidence: 0.99,
+ fix: {
+ type: 'metadata_change',
+ changeSet: {
+ operation: 'update',
+ object: 'financial_record',
+ changes: {
+ permissions: {
+ read: ['admin', 'finance_manager'],
+ write: ['admin'],
+ delete: ['admin']
+ }
+ }
+ }
+ }
+ }
+ ],
+ status: 'resolved'
+};
+```
+
+### 3. Performance Optimization
+
+```typescript
+const performanceIssue: FeedbackLoop = {
+ issue: {
+ id: 'perf-001',
+ severity: 'warning',
+ message: 'Query timeout on large dataset',
+ timestamp: new Date().toISOString(),
+ context: {
+ object: 'order',
+ query: 'list_orders',
+ duration: 5000,
+ recordCount: 50000
+ }
+ },
+ analysis: 'Missing indexes on frequently queried fields',
+ resolutions: [
+ {
+ issueId: 'perf-001',
+ reasoning: 'Add composite index on status and created_at for better query performance',
+ confidence: 0.97,
+ fix: {
+ type: 'metadata_change',
+ changeSet: {
+ operation: 'add_index',
+ object: 'order',
+ index: {
+ fields: ['status', 'created_at'],
+ type: 'btree'
+ }
+ }
+ }
+ }
+ ],
+ status: 'resolved'
+};
+```
+
+---
+
+## Architecture
+
+The Feedback Loop creates a self-healing system:
+
+```
+Runtime Issue → AI Analysis → Metadata Fix → Deployment → Monitoring
+ ↑ ↓
+ └─────────────────── Continuous Learning ←───────────────┘
+```
+
+**Flow:**
+1. **Detection**: Runtime issue occurs in production
+2. **Capture**: Issue details and context are captured
+3. **Analysis**: AI analyzes the root cause
+4. **Resolution**: AI proposes metadata changes
+5. **Validation**: Changes are validated before deployment
+6. **Deployment**: Metadata updates are deployed
+7. **Monitoring**: Issue is monitored to confirm resolution
+
+---
+
+## Best Practices
+
+1. **Capture rich context**: Include as much context as possible in issues
+2. **Track metadata source**: Always include source file/line information
+3. **High confidence threshold**: Only auto-apply fixes with confidence > 0.9
+4. **Human review for critical**: Require manual approval for critical severity
+5. **Version control**: Store all metadata changes in version control
+6. **Monitor resolutions**: Track if resolutions actually fixed the issue
+7. **Learn from patterns**: Use historical data to improve future resolutions
+8. **Graceful fallback**: Use manual intervention for low-confidence fixes
diff --git a/content/docs/references/contracts/data-engine.mdx b/content/docs/references/contracts/data-engine.mdx
new file mode 100644
index 000000000..14341d3ea
--- /dev/null
+++ b/content/docs/references/contracts/data-engine.mdx
@@ -0,0 +1,345 @@
+---
+title: Data Engine
+description: Data Engine contract interface
+---
+
+# Data Engine
+
+
+**Source:** `packages/spec/src/contracts/data-engine.ts`
+
+
+## Overview
+
+The Data Engine contract defines the standard interface for data persistence capabilities in ObjectStack. It follows the Dependency Inversion Principle - plugins depend on this abstract interface, not on concrete database implementations.
+
+## TypeScript Usage
+
+```typescript
+import type { IDataEngine, DriverInterface } from '@objectstack/spec/contracts';
+import type {
+ DataEngineQueryOptions,
+ DataEngineInsertOptions,
+ DataEngineUpdateOptions,
+ DataEngineDeleteOptions,
+ QueryAST
+} from '@objectstack/spec/data';
+
+// Implement the Data Engine interface
+class MyDataEngine implements IDataEngine {
+ async find(objectName: string, query?: DataEngineQueryOptions): Promise {
+ // Implementation
+ }
+
+ async findOne(objectName: string, query?: DataEngineQueryOptions): Promise {
+ // Implementation
+ }
+
+ async insert(objectName: string, data: any | any[], options?: DataEngineInsertOptions): Promise {
+ // Implementation
+ }
+
+ // ... other methods
+}
+```
+
+---
+
+## IDataEngine
+
+Standard Data Engine Interface for data persistence operations.
+
+### Methods
+
+#### `find(objectName: string, query?: DataEngineQueryOptions): Promise`
+
+Query multiple records from an object.
+
+**Parameters:**
+- `objectName` (string) - The name of the object to query
+- `query` (DataEngineQueryOptions, optional) - Query options (filters, select, sort, pagination)
+
+**Returns:** `Promise` - Array of matching records
+
+**Example:**
+```typescript
+const tasks = await dataEngine.find('project_task', {
+ select: ['subject', 'priority', 'status'],
+ filters: ['status', '=', 'active'],
+ sort: ['-priority'],
+ top: 10
+});
+```
+
+---
+
+#### `findOne(objectName: string, query?: DataEngineQueryOptions): Promise`
+
+Query a single record from an object.
+
+**Parameters:**
+- `objectName` (string) - The name of the object to query
+- `query` (DataEngineQueryOptions, optional) - Query options
+
+**Returns:** `Promise` - The matching record or null
+
+**Example:**
+```typescript
+const task = await dataEngine.findOne('project_task', {
+ filters: ['_id', '=', 'task-123']
+});
+```
+
+---
+
+#### `insert(objectName: string, data: any | any[], options?: DataEngineInsertOptions): Promise`
+
+Insert one or more records.
+
+**Parameters:**
+- `objectName` (string) - The name of the object
+- `data` (any | any[]) - Single record or array of records to insert
+- `options` (DataEngineInsertOptions, optional) - Insert options
+
+**Returns:** `Promise` - The created record(s)
+
+**Example:**
+```typescript
+// Insert single record
+const task = await dataEngine.insert('project_task', {
+ subject: 'New task',
+ priority: 1,
+ status: 'active'
+});
+
+// Insert multiple records
+const tasks = await dataEngine.insert('project_task', [
+ { subject: 'Task 1', priority: 1 },
+ { subject: 'Task 2', priority: 2 }
+]);
+```
+
+---
+
+#### `update(objectName: string, data: any, options?: DataEngineUpdateOptions): Promise`
+
+Update a record.
+
+**Parameters:**
+- `objectName` (string) - The name of the object
+- `data` (any) - Record data with _id or update criteria
+- `options` (DataEngineUpdateOptions, optional) - Update options
+
+**Returns:** `Promise` - The updated record
+
+**Example:**
+```typescript
+const updatedTask = await dataEngine.update('project_task', {
+ _id: 'task-123',
+ status: 'completed'
+});
+```
+
+---
+
+#### `delete(objectName: string, options?: DataEngineDeleteOptions): Promise`
+
+Delete one or more records.
+
+**Parameters:**
+- `objectName` (string) - The name of the object
+- `options` (DataEngineDeleteOptions, optional) - Delete options (filters, _id)
+
+**Returns:** `Promise` - Deletion result
+
+**Example:**
+```typescript
+// Delete by ID
+await dataEngine.delete('project_task', {
+ filters: ['_id', '=', 'task-123']
+});
+
+// Delete multiple
+await dataEngine.delete('project_task', {
+ filters: ['status', '=', 'completed']
+});
+```
+
+---
+
+#### `count(objectName: string, query?: DataEngineCountOptions): Promise`
+
+Count records matching criteria.
+
+**Parameters:**
+- `objectName` (string) - The name of the object
+- `query` (DataEngineCountOptions, optional) - Count options (filters)
+
+**Returns:** `Promise` - Number of matching records
+
+**Example:**
+```typescript
+const activeTaskCount = await dataEngine.count('project_task', {
+ filters: ['status', '=', 'active']
+});
+```
+
+---
+
+#### `aggregate(objectName: string, query: DataEngineAggregateOptions): Promise`
+
+Perform aggregation queries.
+
+**Parameters:**
+- `objectName` (string) - The name of the object
+- `query` (DataEngineAggregateOptions) - Aggregation options (groupBy, aggregations)
+
+**Returns:** `Promise` - Aggregation results
+
+**Example:**
+```typescript
+const taskStats = await dataEngine.aggregate('project_task', {
+ groupBy: ['status'],
+ aggregations: [
+ { field: '_id', function: 'count', alias: 'total' },
+ { field: 'priority', function: 'avg', alias: 'avg_priority' }
+ ]
+});
+```
+
+---
+
+### Optional Methods
+
+#### `vectorFind?(objectName: string, vector: number[], options?): Promise`
+
+Vector similarity search for AI/RAG applications.
+
+**Parameters:**
+- `objectName` (string) - The name of the object
+- `vector` (number[]) - Query vector
+- `options` (object, optional)
+ - `filter` (any, optional) - Additional filters
+ - `limit` (number, optional) - Max results
+ - `select` (string[], optional) - Fields to return
+ - `threshold` (number, optional) - Similarity threshold
+
+**Returns:** `Promise` - Similar records
+
+**Example:**
+```typescript
+const similarDocs = await dataEngine.vectorFind('knowledge_base', queryVector, {
+ limit: 5,
+ threshold: 0.8
+});
+```
+
+---
+
+#### `batch?(requests: DataEngineRequest[], options?): Promise`
+
+Execute multiple operations in a batch, optionally with transaction support.
+
+**Parameters:**
+- `requests` (DataEngineRequest[]) - Array of operations
+- `options` (object, optional)
+ - `transaction` (boolean, optional) - Execute in transaction
+
+**Returns:** `Promise` - Results for each operation
+
+**Example:**
+```typescript
+const results = await dataEngine.batch([
+ { operation: 'insert', object: 'project_task', data: {...} },
+ { operation: 'update', object: 'project', data: {...} }
+], { transaction: true });
+```
+
+---
+
+#### `execute?(command: any, options?): Promise`
+
+Execute raw database command (escape hatch).
+
+**Parameters:**
+- `command` (any) - Database-specific command
+- `options` (`Record`, optional) - Command options
+
+**Returns:** `Promise` - Command result
+
+**Warning:** Use sparingly - this breaks abstraction.
+
+---
+
+## DriverInterface
+
+Low-level driver interface for database implementations.
+
+### Properties
+
+- `name` (string) - Driver name
+- `version` (string) - Driver version
+
+### Methods
+
+#### Core CRUD Operations
+
+- `connect(): Promise` - Establish database connection
+- `disconnect(): Promise` - Close database connection
+- `find(object: string, query: QueryAST, options?: DriverOptions): Promise` - Query records
+- `findOne(object: string, query: QueryAST, options?: DriverOptions): Promise` - Query single record
+- `create(object: string, data: any, options?: DriverOptions): Promise` - Create record
+- `update(object: string, id: any, data: any, options?: DriverOptions): Promise` - Update record
+- `delete(object: string, id: any, options?: DriverOptions): Promise` - Delete record
+
+#### Optional Bulk Operations
+
+- `bulkCreate?(object: string, data: any[], options?: DriverOptions): Promise` - Bulk insert
+- `updateMany?(object: string, query: QueryAST, data: any, options?: DriverOptions): Promise` - Bulk update
+- `deleteMany?(object: string, query: QueryAST, options?: DriverOptions): Promise` - Bulk delete
+- `count?(object: string, query: QueryAST, options?: DriverOptions): Promise` - Count records
+
+#### Raw Execution
+
+- `execute?(command: any, params?: any, options?: DriverOptions): Promise` - Execute raw command
+
+---
+
+## Implementation Example
+
+```typescript
+import type { IDataEngine } from '@objectstack/spec/contracts';
+
+class PostgresDataEngine implements IDataEngine {
+ constructor(private pool: Pool) {}
+
+ async find(objectName: string, query?: DataEngineQueryOptions): Promise {
+ const sql = this.buildSelectSQL(objectName, query);
+ const result = await this.pool.query(sql);
+ return result.rows;
+ }
+
+ async insert(objectName: string, data: any): Promise {
+ const sql = this.buildInsertSQL(objectName, data);
+ const result = await this.pool.query(sql);
+ return result.rows[0];
+ }
+
+ // ... other implementations
+
+ private buildSelectSQL(objectName: string, query?: DataEngineQueryOptions): string {
+ // SQL building logic
+ }
+}
+```
+
+---
+
+## Best Practices
+
+1. **Use the abstraction**: Depend on IDataEngine, not concrete implementations
+2. **Handle errors gracefully**: Wrap database errors in consistent error types
+3. **Support transactions**: Implement batch operations with transaction support when possible
+4. **Optimize queries**: Use indexes and query optimization for better performance
+5. **Test thoroughly**: Test with different drivers to ensure compatibility
+6. **Document limitations**: Clearly document which optional methods are supported
diff --git a/content/docs/references/contracts/http-server.mdx b/content/docs/references/contracts/http-server.mdx
new file mode 100644
index 000000000..acddb9c9e
--- /dev/null
+++ b/content/docs/references/contracts/http-server.mdx
@@ -0,0 +1,16 @@
+---
+title: HTTP Server
+description: HTTP Server contract interface
+---
+
+# HTTP Server
+
+
+**Source:** `packages/spec/src/contracts/http-server.ts`
+
+
+## Overview
+
+The HTTP Server contract defines the interface for HTTP server functionality in ObjectStack.
+
+For detailed API reference, see the source file: `packages/spec/src/contracts/http-server.ts`
diff --git a/content/docs/references/contracts/index.mdx b/content/docs/references/contracts/index.mdx
new file mode 100644
index 000000000..59e23c0c2
--- /dev/null
+++ b/content/docs/references/contracts/index.mdx
@@ -0,0 +1,60 @@
+---
+title: Contracts Overview
+description: Complete reference for all TypeScript contract interfaces
+---
+
+# Contracts
+
+This section contains all TypeScript contract interfaces for ObjectStack. These interfaces define the contracts that plugins and components must implement.
+
+## What are Contracts?
+
+Contracts are TypeScript interfaces that define the behavior and structure of ObjectStack components. Unlike Zod schemas which provide runtime validation, contracts focus on compile-time type safety and dependency inversion.
+
+**Key Principles:**
+- **Dependency Inversion**: Plugins depend on abstract interfaces, not concrete implementations
+- **Type Safety**: Compile-time guarantees for correct implementation
+- **Extensibility**: Easy to extend and customize behavior
+
+
+
+
+
+
+
+
+
+
+
+
+## Usage Pattern
+
+```typescript
+import type { IDataEngine, DriverInterface } from '@objectstack/spec/contracts';
+
+// Implement the contract
+class MyCustomDriver implements DriverInterface {
+ name = 'my-driver';
+ version = '1.0.0';
+
+ async connect() {
+ // Implementation
+ }
+
+ async find(object: string, query: QueryAST) {
+ // Implementation
+ }
+
+ // ... other methods
+}
+```
+
+## Contracts vs Zod Schemas
+
+| Aspect | Contracts | Zod Schemas |
+|--------|-----------|-------------|
+| **Purpose** | Compile-time contracts | Runtime validation |
+| **Location** | `packages/spec/src/contracts/` | `packages/spec/src/**/*.zod.ts` |
+| **Usage** | Interface implementation | Data validation |
+| **Type Safety** | TypeScript only | Runtime + TypeScript |
+| **When to Use** | Plugin interfaces, service contracts | Configuration, API requests, data objects |
diff --git a/content/docs/references/contracts/logger.mdx b/content/docs/references/contracts/logger.mdx
new file mode 100644
index 000000000..71a5346a7
--- /dev/null
+++ b/content/docs/references/contracts/logger.mdx
@@ -0,0 +1,40 @@
+---
+title: Logger
+description: Logger contract interface
+---
+
+# Logger
+
+
+**Source:** `packages/spec/src/contracts/logger.ts`
+
+
+## Overview
+
+The Logger contract defines the standard interface for logging in ObjectStack. It provides consistent logging capabilities across all plugins and components.
+
+## TypeScript Usage
+
+```typescript
+import type { ILogger } from '@objectstack/spec/contracts';
+
+class MyLogger implements ILogger {
+ debug(message: string, context?: any): void {
+ console.debug(message, context);
+ }
+
+ info(message: string, context?: any): void {
+ console.info(message, context);
+ }
+
+ warn(message: string, context?: any): void {
+ console.warn(message, context);
+ }
+
+ error(message: string, context?: any): void {
+ console.error(message, context);
+ }
+}
+```
+
+For detailed API reference, see the source file: `packages/spec/src/contracts/logger.ts`
diff --git a/content/docs/references/contracts/meta.json b/content/docs/references/contracts/meta.json
new file mode 100644
index 000000000..9a1fbb7e8
--- /dev/null
+++ b/content/docs/references/contracts/meta.json
@@ -0,0 +1,14 @@
+{
+ "title": "Contracts",
+ "pages": [
+ "index",
+ "data-engine",
+ "plugin-validator",
+ "logger",
+ "http-server",
+ "schema-driver",
+ "service-registry",
+ "plugin-lifecycle-events",
+ "startup-orchestrator"
+ ]
+}
diff --git a/content/docs/references/contracts/plugin-lifecycle-events.mdx b/content/docs/references/contracts/plugin-lifecycle-events.mdx
new file mode 100644
index 000000000..34d290360
--- /dev/null
+++ b/content/docs/references/contracts/plugin-lifecycle-events.mdx
@@ -0,0 +1,16 @@
+---
+title: Plugin Lifecycle Events
+description: Plugin Lifecycle Events contract interface
+---
+
+# Plugin Lifecycle Events
+
+
+**Source:** `packages/spec/src/contracts/plugin-lifecycle-events.ts`
+
+
+## Overview
+
+The Plugin Lifecycle Events contract defines the event interfaces for plugin lifecycle management in ObjectStack. It specifies events triggered during plugin initialization (init), startup (start), shutdown (stop), and destruction (destroy) phases.
+
+For detailed API reference, see the source file: `packages/spec/src/contracts/plugin-lifecycle-events.ts`
diff --git a/content/docs/references/contracts/plugin-validator.mdx b/content/docs/references/contracts/plugin-validator.mdx
new file mode 100644
index 000000000..267d72b7d
--- /dev/null
+++ b/content/docs/references/contracts/plugin-validator.mdx
@@ -0,0 +1,481 @@
+---
+title: Plugin Validator
+description: Plugin Validator contract interface
+---
+
+# Plugin Validator
+
+
+**Source:** `packages/spec/src/contracts/plugin-validator.ts`
+
+
+## Overview
+
+The Plugin Validator contract defines the interface for validating plugins before registration and startup. It follows the Single Responsibility Principle by separating validation logic from plugin loading.
+
+## TypeScript Usage
+
+```typescript
+import type { IPluginValidator, Plugin, ValidationResult } from '@objectstack/spec/contracts';
+
+// Implement the Plugin Validator interface
+class MyPluginValidator implements IPluginValidator {
+ validate(plugin: unknown): ValidationResult {
+ // Validation logic
+ return {
+ valid: true,
+ errors: [],
+ warnings: []
+ };
+ }
+
+ validateVersion(version: string): boolean {
+ // Version validation logic
+ return /^\d+\.\d+\.\d+/.test(version);
+ }
+
+ validateSignature(plugin: Plugin, signature: string): boolean {
+ // Signature validation logic
+ return true;
+ }
+}
+```
+
+---
+
+## ValidationResult
+
+Result of plugin validation.
+
+**Properties:**
+- `valid` (boolean) - Whether the plugin passed validation
+- `errors` (Array, optional) - Validation errors (if any)
+ - `field` (string) - Field that failed validation
+ - `message` (string) - Error message
+ - `code` (string, optional) - Error code
+- `warnings` (Array, optional) - Validation warnings (non-fatal issues)
+ - `field` (string) - Field with warning
+ - `message` (string) - Warning message
+ - `code` (string, optional) - Warning code
+
+**Example:**
+```typescript
+const result: ValidationResult = {
+ valid: false,
+ errors: [
+ {
+ field: 'name',
+ message: 'Plugin name is required',
+ code: 'MISSING_NAME'
+ }
+ ],
+ warnings: [
+ {
+ field: 'version',
+ message: 'Version format recommended: x.y.z',
+ code: 'VERSION_FORMAT'
+ }
+ ]
+};
+```
+
+---
+
+## Plugin
+
+Plugin metadata for validation.
+
+**Properties:**
+- `name` (string) - Unique plugin identifier
+- `version` (string, optional) - Plugin version (semver)
+- `dependencies` (string[], optional) - Plugin dependencies
+- `init` (function, optional) - Plugin initialization function
+ - Signature: `(context: any) => void | Promise`
+- `start` (function, optional) - Plugin startup function
+ - Signature: `(context: any) => void | Promise`
+- `destroy` (function, optional) - Plugin destruction function
+ - Signature: `(context: any) => void | Promise`
+- `signature` (string, optional) - Plugin signature for verification
+- Additional properties allowed via index signature
+
+**Example:**
+```typescript
+const plugin: Plugin = {
+ name: '@myorg/my-plugin',
+ version: '1.0.0',
+ dependencies: ['@objectstack/core'],
+ init: async (context) => {
+ console.log('Initializing plugin');
+ },
+ start: async (context) => {
+ console.log('Starting plugin');
+ },
+ destroy: async (context) => {
+ console.log('Destroying plugin');
+ }
+};
+```
+
+---
+
+## IPluginValidator
+
+Plugin validation interface.
+
+### Methods
+
+#### `validate(plugin: unknown): ValidationResult`
+
+Validate a plugin object structure.
+
+**Parameters:**
+- `plugin` (unknown) - Plugin to validate
+
+**Returns:** ValidationResult - Validation result with errors/warnings
+
+**Example:**
+```typescript
+const validator = new MyPluginValidator();
+const result = validator.validate({
+ name: '@myorg/plugin',
+ version: '1.0.0'
+});
+
+if (!result.valid) {
+ console.error('Validation failed:', result.errors);
+}
+```
+
+---
+
+#### `validateVersion(version: string): boolean`
+
+Validate plugin version format (semver).
+
+**Parameters:**
+- `version` (string) - Version string to validate
+
+**Returns:** boolean - True if version is valid, false otherwise
+
+**Example:**
+```typescript
+const validator = new MyPluginValidator();
+
+console.log(validator.validateVersion('1.0.0')); // true
+console.log(validator.validateVersion('1.0')); // false
+console.log(validator.validateVersion('v1.0.0')); // true (with prefix)
+```
+
+---
+
+#### `validateSignature(plugin: Plugin, signature: string): boolean`
+
+Validate plugin cryptographic signature (optional security feature).
+
+**Parameters:**
+- `plugin` (Plugin) - Plugin to validate
+- `signature` (string) - Cryptographic signature
+
+**Returns:** boolean - True if signature is valid, false otherwise
+
+**Example:**
+```typescript
+const validator = new MyPluginValidator();
+const plugin = {
+ name: '@myorg/plugin',
+ version: '1.0.0',
+ signature: 'sha256:abc123...'
+};
+
+const isValid = validator.validateSignature(plugin, plugin.signature);
+```
+
+---
+
+## Implementation Example
+
+### Basic Validator
+
+```typescript
+import type { IPluginValidator, Plugin, ValidationResult } from '@objectstack/spec/contracts';
+
+class BasicPluginValidator implements IPluginValidator {
+ validate(plugin: unknown): ValidationResult {
+ const errors: ValidationResult['errors'] = [];
+ const warnings: ValidationResult['warnings'] = [];
+
+ // Type check
+ if (typeof plugin !== 'object' || plugin === null) {
+ return {
+ valid: false,
+ errors: [{ field: 'plugin', message: 'Plugin must be an object' }]
+ };
+ }
+
+ const p = plugin as Partial;
+
+ // Required fields
+ if (!p.name || typeof p.name !== 'string') {
+ errors.push({
+ field: 'name',
+ message: 'Plugin name is required and must be a string',
+ code: 'MISSING_NAME'
+ });
+ }
+
+ // Version validation
+ if (p.version && !this.validateVersion(p.version)) {
+ errors.push({
+ field: 'version',
+ message: 'Invalid version format. Use semver (x.y.z)',
+ code: 'INVALID_VERSION'
+ });
+ }
+
+ // Lifecycle methods
+ if (p.init && typeof p.init !== 'function') {
+ errors.push({
+ field: 'init',
+ message: 'init must be a function',
+ code: 'INVALID_INIT'
+ });
+ }
+
+ if (p.start && typeof p.start !== 'function') {
+ errors.push({
+ field: 'start',
+ message: 'start must be a function',
+ code: 'INVALID_START'
+ });
+ }
+
+ if (p.destroy && typeof p.destroy !== 'function') {
+ errors.push({
+ field: 'destroy',
+ message: 'destroy must be a function',
+ code: 'INVALID_DESTROY'
+ });
+ }
+
+ // Dependencies check
+ if (p.dependencies) {
+ if (!Array.isArray(p.dependencies)) {
+ errors.push({
+ field: 'dependencies',
+ message: 'dependencies must be an array',
+ code: 'INVALID_DEPENDENCIES'
+ });
+ } else if (p.dependencies.some(d => typeof d !== 'string')) {
+ errors.push({
+ field: 'dependencies',
+ message: 'All dependencies must be strings',
+ code: 'INVALID_DEPENDENCY_TYPE'
+ });
+ }
+ }
+
+ return {
+ valid: errors.length === 0,
+ errors: errors.length > 0 ? errors : undefined,
+ warnings: warnings.length > 0 ? warnings : undefined
+ };
+ }
+
+ validateVersion(version: string): boolean {
+ // Semver regex: x.y.z with optional v prefix and pre-release
+ const semverRegex = /^v?(\d+)\.(\d+)\.(\d+)(-[a-zA-Z0-9.-]+)?(\+[a-zA-Z0-9.-]+)?$/;
+ return semverRegex.test(version);
+ }
+
+ validateSignature(plugin: Plugin, signature: string): boolean {
+ // Placeholder - implement cryptographic verification
+ // This would verify the plugin code against the signature
+ return signature.startsWith('sha256:');
+ }
+}
+```
+
+### Advanced Validator with Security
+
+```typescript
+import crypto from 'crypto';
+import type { IPluginValidator, Plugin, ValidationResult } from '@objectstack/spec/contracts';
+
+class SecurePluginValidator implements IPluginValidator {
+ constructor(
+ private trustedPublicKeys: Map = new Map()
+ ) {}
+
+ validate(plugin: unknown): ValidationResult {
+ const basicResult = this.basicValidation(plugin);
+ if (!basicResult.valid) {
+ return basicResult;
+ }
+
+ const p = plugin as Plugin;
+ const warnings: ValidationResult['warnings'] = [];
+
+ // Security checks
+ if (!p.signature) {
+ warnings.push({
+ field: 'signature',
+ message: 'Plugin is not signed. This may pose a security risk.',
+ code: 'MISSING_SIGNATURE'
+ });
+ }
+
+ // Check for suspicious patterns
+ if (this.hasSuspiciousCode(p)) {
+ warnings.push({
+ field: 'code',
+ message: 'Plugin contains potentially suspicious code patterns',
+ code: 'SUSPICIOUS_CODE'
+ });
+ }
+
+ return {
+ valid: true,
+ warnings: warnings.length > 0 ? warnings : undefined
+ };
+ }
+
+ validateVersion(version: string): boolean {
+ const semverRegex = /^v?(\d+)\.(\d+)\.(\d+)(-[a-zA-Z0-9.-]+)?(\+[a-zA-Z0-9.-]+)?$/;
+ return semverRegex.test(version);
+ }
+
+ validateSignature(plugin: Plugin, signature: string): boolean {
+ if (!signature || !plugin.name) {
+ return false;
+ }
+
+ // Get public key for this plugin
+ const publicKey = this.trustedPublicKeys.get(plugin.name);
+ if (!publicKey) {
+ return false;
+ }
+
+ try {
+ // Verify signature (simplified example)
+ const verify = crypto.createVerify('SHA256');
+ verify.update(JSON.stringify(plugin));
+ verify.end();
+
+ return verify.verify(publicKey, signature, 'hex');
+ } catch (error) {
+ return false;
+ }
+ }
+
+ private basicValidation(plugin: unknown): ValidationResult {
+ // Reuse basic validation logic
+ return { valid: true };
+ }
+
+ private hasSuspiciousCode(plugin: Plugin): boolean {
+ // Check for dangerous patterns
+ const suspiciousPatterns = [
+ 'eval(',
+ 'Function(',
+ 'require.cache',
+ 'process.exit'
+ ];
+
+ const pluginStr = JSON.stringify(plugin);
+ return suspiciousPatterns.some(pattern => pluginStr.includes(pattern));
+ }
+
+ addTrustedKey(pluginName: string, publicKey: string): void {
+ this.trustedPublicKeys.set(pluginName, publicKey);
+ }
+}
+```
+
+---
+
+## Use Cases
+
+### 1. Plugin Registry Validation
+
+```typescript
+const validator = new BasicPluginValidator();
+
+function registerPlugin(plugin: unknown) {
+ const result = validator.validate(plugin);
+
+ if (!result.valid) {
+ throw new Error(`Plugin validation failed: ${
+ result.errors?.map(e => e.message).join(', ')
+ }`);
+ }
+
+ if (result.warnings) {
+ console.warn('Plugin warnings:', result.warnings);
+ }
+
+ // Proceed with registration
+ registry.add(plugin as Plugin);
+}
+```
+
+### 2. Marketplace Plugin Verification
+
+```typescript
+const secureValidator = new SecurePluginValidator();
+
+async function installMarketplacePlugin(pluginData: unknown) {
+ // Validate structure
+ const result = secureValidator.validate(pluginData);
+ if (!result.valid) {
+ throw new Error('Invalid plugin structure');
+ }
+
+ const plugin = pluginData as Plugin;
+
+ // Verify signature
+ if (plugin.signature && !secureValidator.validateSignature(plugin, plugin.signature)) {
+ throw new Error('Plugin signature verification failed');
+ }
+
+ // Install plugin
+ await installPlugin(plugin);
+}
+```
+
+### 3. Development Plugin Hot Reload
+
+```typescript
+const devValidator = new BasicPluginValidator();
+
+function reloadPlugin(pluginPath: string) {
+ const plugin = require(pluginPath);
+
+ const result = devValidator.validate(plugin);
+
+ if (!result.valid) {
+ console.error('Plugin reload failed:', result.errors);
+ return false;
+ }
+
+ if (result.warnings) {
+ console.warn('Plugin warnings:', result.warnings);
+ }
+
+ // Hot reload the plugin
+ hotReload(plugin);
+ return true;
+}
+```
+
+---
+
+## Best Practices
+
+1. **Validate early**: Validate plugins before loading or registration
+2. **Clear error messages**: Provide actionable error messages with field context
+3. **Use error codes**: Include error codes for programmatic handling
+4. **Security first**: Implement signature validation for production plugins
+5. **Graceful warnings**: Use warnings for non-critical issues
+6. **Semver compliance**: Enforce semantic versioning for compatibility
+7. **Test validation**: Write comprehensive tests for edge cases
+8. **Document requirements**: Clearly document what makes a valid plugin
diff --git a/content/docs/references/contracts/schema-driver.mdx b/content/docs/references/contracts/schema-driver.mdx
new file mode 100644
index 000000000..215ae7ad4
--- /dev/null
+++ b/content/docs/references/contracts/schema-driver.mdx
@@ -0,0 +1,16 @@
+---
+title: Schema Driver
+description: Schema Driver contract interface
+---
+
+# Schema Driver
+
+
+**Source:** `packages/spec/src/contracts/schema-driver.ts`
+
+
+## Overview
+
+The Schema Driver contract defines the interface for schema management in ObjectStack. It handles database schema creation, migration, versioning, and synchronization between ObjectStack metadata definitions and database structures.
+
+For detailed API reference, see the source file: `packages/spec/src/contracts/schema-driver.ts`
diff --git a/content/docs/references/contracts/service-registry.mdx b/content/docs/references/contracts/service-registry.mdx
new file mode 100644
index 000000000..305859670
--- /dev/null
+++ b/content/docs/references/contracts/service-registry.mdx
@@ -0,0 +1,16 @@
+---
+title: Service Registry
+description: Service Registry contract interface
+---
+
+# Service Registry
+
+
+**Source:** `packages/spec/src/contracts/service-registry.ts`
+
+
+## Overview
+
+The Service Registry contract defines the interface for service discovery and registration in ObjectStack. It manages the registration, lookup, and lifecycle of services within the microkernel architecture.
+
+For detailed API reference, see the source file: `packages/spec/src/contracts/service-registry.ts`
diff --git a/content/docs/references/contracts/startup-orchestrator.mdx b/content/docs/references/contracts/startup-orchestrator.mdx
new file mode 100644
index 000000000..040d00f25
--- /dev/null
+++ b/content/docs/references/contracts/startup-orchestrator.mdx
@@ -0,0 +1,16 @@
+---
+title: Startup Orchestrator
+description: Startup Orchestrator contract interface
+---
+
+# Startup Orchestrator
+
+
+**Source:** `packages/spec/src/contracts/startup-orchestrator.ts`
+
+
+## Overview
+
+The Startup Orchestrator contract defines the interface for managing the system initialization sequence in ObjectStack. It handles plugin loading order, dependency resolution, and ensures proper startup of all components in the correct sequence.
+
+For detailed API reference, see the source file: `packages/spec/src/contracts/startup-orchestrator.ts`
diff --git a/content/docs/references/index.mdx b/content/docs/references/index.mdx
index f12bbfd6b..d535bdb03 100644
--- a/content/docs/references/index.mdx
+++ b/content/docs/references/index.mdx
@@ -21,10 +21,12 @@ This is the complete reference for all protocol specifications in the ObjectStac
| [Permission Protocol](#permission-protocol) | 4 | Access control and security policies |
| [Hub Protocol](#hub-protocol) | 6 | Marketplace and multi-tenancy |
| [Integration Protocol](#integration-protocol) | 5 | External system connectors and adapters |
+| [QA Protocol](#qa-protocol) | 1 | Testing and quality assurance |
+| [Contracts](#contracts) | 9 | TypeScript contract interfaces |
| [Shared Protocol](#shared-protocol) | 3 | Common utilities and identifiers |
| [Stack Protocol](#stack-protocol) | 1 | Root stack definition |
-**Total: 109 protocols**
+**Total: 119 protocols**
---
@@ -256,6 +258,55 @@ Defines external system connectors and adapters.
---
+## QA Protocol
+
+**Location:** `packages/spec/src/qa/`
+**Count:** 1 protocol
+
+Defines testing and quality assurance capabilities.
+
+| File | Schema | Purpose |
+| :--- | :--- | :--- |
+| `testing.zod.ts` | `TestSuiteSchema` | Test suites, scenarios, steps, actions, and assertions |
+
+**Key Features:**
+- Declarative test definitions with setup/teardown
+- Action-based testing (create, update, delete, API calls)
+- Comprehensive assertion operators
+- Test context and variable capture between steps
+- Permission testing with user impersonation
+
+**Learn more:** [QA Protocol Reference](/docs/references/qa)
+
+---
+
+## Contracts
+
+**Location:** `packages/spec/src/contracts/`
+**Count:** 9 contracts
+
+Defines TypeScript contract interfaces for plugin implementations.
+
+| File | Interface | Purpose |
+| :--- | :--- | :--- |
+| `data-engine.ts` | `IDataEngine`, `DriverInterface` | Standard data persistence interface |
+| `plugin-validator.ts` | `IPluginValidator` | Plugin validation interface |
+| `logger.ts` | `ILogger` | Logging interface |
+| `http-server.ts` | `IHTTPServer` | HTTP server interface |
+| `schema-driver.ts` | `ISchemaDriver` | Schema management interface |
+| `service-registry.ts` | `IServiceRegistry` | Service discovery interface |
+| `plugin-lifecycle-events.ts` | Plugin lifecycle events | Plugin event interfaces |
+| `startup-orchestrator.ts` | `IStartupOrchestrator` | Startup orchestration interface |
+
+**Key Principles:**
+- **Dependency Inversion**: Plugins depend on abstract interfaces
+- **Type Safety**: Compile-time guarantees for implementations
+- **Extensibility**: Easy to extend and customize behavior
+
+**Learn more:** [Contracts Reference](/docs/references/contracts)
+
+---
+
## Recent Additions (2026-01-27)
**ObjectQL Advanced Features:**
diff --git a/content/docs/references/qa/index.mdx b/content/docs/references/qa/index.mdx
new file mode 100644
index 000000000..281b76aca
--- /dev/null
+++ b/content/docs/references/qa/index.mdx
@@ -0,0 +1,19 @@
+---
+title: QA Protocol Overview
+description: Complete reference for all QA protocol schemas
+---
+
+# QA Protocol
+
+This section contains all protocol schemas for the QA (Quality Assurance) layer of ObjectStack.
+
+The QA Protocol provides comprehensive testing capabilities for ObjectStack applications, including:
+- Test suites and scenarios
+- Action-based test steps
+- Assertion operators
+- Test context and variable capture
+- Setup and teardown lifecycle
+
+
+
+
diff --git a/content/docs/references/qa/meta.json b/content/docs/references/qa/meta.json
new file mode 100644
index 000000000..1fa7405b3
--- /dev/null
+++ b/content/docs/references/qa/meta.json
@@ -0,0 +1,7 @@
+{
+ "title": "QA Protocol",
+ "pages": [
+ "index",
+ "testing"
+ ]
+}
diff --git a/content/docs/references/qa/testing.mdx b/content/docs/references/qa/testing.mdx
new file mode 100644
index 000000000..07e232eab
--- /dev/null
+++ b/content/docs/references/qa/testing.mdx
@@ -0,0 +1,465 @@
+---
+title: Testing
+description: Testing protocol schemas
+---
+
+# Testing
+
+
+**Source:** `packages/spec/src/qa/testing.zod.ts`
+
+
+## Overview
+
+The Testing protocol provides a comprehensive framework for defining and executing tests in ObjectStack applications. It supports:
+- Declarative test definitions
+- Action-based testing (create, update, delete, API calls)
+- Assertion operators for validation
+- Test context and variable capture
+- Setup and teardown lifecycle management
+
+## TypeScript Usage
+
+```typescript
+import {
+ TestSuiteSchema,
+ TestScenarioSchema,
+ TestStepSchema,
+ TestActionSchema,
+ TestAssertionSchema,
+ TestContextSchema
+} from '@objectstack/spec/qa';
+
+import type {
+ TestSuite,
+ TestScenario,
+ TestStep,
+ TestAction,
+ TestAssertion
+} from '@objectstack/spec/qa';
+
+// Define a test suite
+const testSuite: TestSuite = {
+ name: 'CRM Contact Tests',
+ scenarios: [
+ {
+ id: 'test-001',
+ name: 'Create and verify contact',
+ tags: ['critical', 'crm'],
+ steps: [
+ {
+ name: 'Create contact',
+ action: {
+ type: 'create_record',
+ target: 'crm_contact',
+ payload: {
+ first_name: 'John',
+ last_name: 'Doe',
+ email: 'john.doe@example.com'
+ }
+ },
+ assertions: [
+ {
+ field: 'body._id',
+ operator: 'not_null',
+ expectedValue: null
+ }
+ ],
+ capture: {
+ contactId: 'body._id'
+ }
+ }
+ ]
+ }
+ ]
+};
+
+// Validate test suite
+const validatedSuite = TestSuiteSchema.parse(testSuite);
+```
+
+---
+
+## TestContext
+
+Context variables and initial data for test execution.
+
+**Type:** `Record`
+
+**Description:** Initial context or variables for the test
+
+---
+
+## TestActionType
+
+Available test action types.
+
+**Values:**
+- `create_record` - Create a new record
+- `update_record` - Update an existing record
+- `delete_record` - Delete a record
+- `read_record` - Read a single record
+- `query_records` - Query multiple records
+- `api_call` - Make an API call
+- `run_script` - Execute a script
+- `wait` - Wait for async processes
+
+---
+
+## TestAction
+
+Defines an action to be performed during a test step.
+
+**Properties:**
+- `type` (TestActionType) - The type of action to perform
+- `target` (string) - Target Object, API Endpoint, or Function Name
+- `payload` (`Record`, optional) - Data to send or use
+- `user` (string, optional) - Run as specific user/role (impersonation)
+
+**Example:**
+```typescript
+const action: TestAction = {
+ type: 'create_record',
+ target: 'project_task',
+ payload: {
+ subject: 'Implement feature',
+ priority: 1
+ },
+ user: 'admin@example.com'
+};
+```
+
+---
+
+## TestAssertionType
+
+Available assertion operators.
+
+**Values:**
+- `equals` - Value equals expected
+- `not_equals` - Value does not equal expected
+- `contains` - Value contains expected (string/array)
+- `not_contains` - Value does not contain expected
+- `is_null` - Value is null
+- `not_null` - Value is not null
+- `gt` - Value is greater than expected
+- `gte` - Value is greater than or equal to expected
+- `lt` - Value is less than expected
+- `lte` - Value is less than or equal to expected
+- `error` - Expecting an error
+
+---
+
+## TestAssertion
+
+Defines an assertion to validate test results.
+
+**Properties:**
+- `field` (string) - Field path in the result to check (e.g., "body.data.0.status")
+- `operator` (TestAssertionType) - Assertion operator to apply
+- `expectedValue` (unknown) - The expected value
+
+**Example:**
+```typescript
+const assertion: TestAssertion = {
+ field: 'body.status',
+ operator: 'equals',
+ expectedValue: 'active'
+};
+```
+
+---
+
+## TestStep
+
+A single step in a test scenario.
+
+**Properties:**
+- `name` (string) - Step name
+- `description` (string, optional) - Step description
+- `action` (TestAction) - Action to perform
+- `assertions` (TestAssertion[], optional) - Assertions to validate
+- `capture` (`Record`, optional) - Capture result fields to context variables
+
+**Example:**
+```typescript
+const step: TestStep = {
+ name: 'Create and verify project',
+ action: {
+ type: 'create_record',
+ target: 'project',
+ payload: {
+ name: 'Test Project',
+ status: 'active'
+ }
+ },
+ assertions: [
+ {
+ field: 'body._id',
+ operator: 'not_null',
+ expectedValue: null
+ },
+ {
+ field: 'body.status',
+ operator: 'equals',
+ expectedValue: 'active'
+ }
+ ],
+ capture: {
+ projectId: 'body._id'
+ }
+};
+```
+
+---
+
+## TestScenario
+
+A complete test scenario with setup, steps, and teardown.
+
+**Properties:**
+- `id` (string) - Unique scenario identifier
+- `name` (string) - Scenario name
+- `description` (string, optional) - Scenario description
+- `tags` (string[], optional) - Tags for categorization (e.g., "critical", "regression", "crm")
+- `setup` (TestStep[], optional) - Steps to run before main test
+- `steps` (TestStep[]) - Main test sequence
+- `teardown` (TestStep[], optional) - Steps to cleanup
+- `requires` (object, optional) - Environment requirements
+ - `params` (string[], optional) - Required env vars or params
+ - `plugins` (string[], optional) - Required plugins
+
+**Example:**
+```typescript
+const scenario: TestScenario = {
+ id: 'crm-contact-lifecycle',
+ name: 'Complete contact lifecycle test',
+ description: 'Create, update, query, and delete a contact',
+ tags: ['integration', 'crm', 'critical'],
+ setup: [
+ {
+ name: 'Initialize test data',
+ action: {
+ type: 'run_script',
+ target: 'setupTestData',
+ payload: {}
+ }
+ }
+ ],
+ steps: [
+ {
+ name: 'Create contact',
+ action: {
+ type: 'create_record',
+ target: 'crm_contact',
+ payload: {
+ first_name: 'Jane',
+ last_name: 'Smith',
+ email: 'jane.smith@example.com'
+ }
+ },
+ capture: {
+ contactId: 'body._id'
+ }
+ },
+ {
+ name: 'Update contact',
+ action: {
+ type: 'update_record',
+ target: 'crm_contact',
+ payload: {
+ _id: '{{contactId}}',
+ phone: '+1-555-1234'
+ }
+ }
+ }
+ ],
+ teardown: [
+ {
+ name: 'Cleanup test data',
+ action: {
+ type: 'delete_record',
+ target: 'crm_contact',
+ payload: {
+ _id: '{{contactId}}'
+ }
+ }
+ }
+ ],
+ requires: {
+ plugins: ['@objectstack/driver-memory']
+ }
+};
+```
+
+---
+
+## TestSuite
+
+A collection of test scenarios.
+
+**Properties:**
+- `name` (string) - Test suite name
+- `scenarios` (TestScenario[]) - Array of test scenarios
+
+**Example:**
+```typescript
+const testSuite: TestSuite = {
+ name: 'CRM Module Tests',
+ scenarios: [
+ {
+ id: 'contact-crud',
+ name: 'Contact CRUD operations',
+ steps: [/* ... */]
+ },
+ {
+ id: 'account-validation',
+ name: 'Account validation rules',
+ steps: [/* ... */]
+ }
+ ]
+};
+```
+
+---
+
+## Use Cases
+
+### 1. API Integration Testing
+
+```typescript
+const apiTestSuite: TestSuite = {
+ name: 'API Integration Tests',
+ scenarios: [
+ {
+ id: 'api-auth',
+ name: 'Test API authentication',
+ steps: [
+ {
+ name: 'Login request',
+ action: {
+ type: 'api_call',
+ target: '/api/auth/login',
+ payload: {
+ email: 'test@example.com',
+ password: 'test123'
+ }
+ },
+ assertions: [
+ {
+ field: 'body.token',
+ operator: 'not_null',
+ expectedValue: null
+ }
+ ],
+ capture: {
+ authToken: 'body.token'
+ }
+ }
+ ]
+ }
+ ]
+};
+```
+
+### 2. Permission Testing
+
+```typescript
+const permissionTest: TestScenario = {
+ id: 'permission-check',
+ name: 'Verify role-based access',
+ steps: [
+ {
+ name: 'Admin can create',
+ action: {
+ type: 'create_record',
+ target: 'project',
+ payload: { name: 'Test' },
+ user: 'admin@example.com'
+ },
+ assertions: [
+ {
+ field: 'body._id',
+ operator: 'not_null',
+ expectedValue: null
+ }
+ ]
+ },
+ {
+ name: 'Guest cannot create',
+ action: {
+ type: 'create_record',
+ target: 'project',
+ payload: { name: 'Test' },
+ user: 'guest@example.com'
+ },
+ assertions: [
+ {
+ field: 'error',
+ operator: 'equals',
+ expectedValue: 'Permission denied'
+ }
+ ]
+ }
+ ]
+};
+```
+
+### 3. Workflow Testing
+
+```typescript
+const workflowTest: TestScenario = {
+ id: 'approval-workflow',
+ name: 'Test approval workflow',
+ steps: [
+ {
+ name: 'Submit for approval',
+ action: {
+ type: 'update_record',
+ target: 'expense_report',
+ payload: {
+ _id: '{{reportId}}',
+ status: 'pending_approval'
+ }
+ }
+ },
+ {
+ name: 'Wait for async processing',
+ action: {
+ type: 'wait',
+ target: 'workflow_completion',
+ payload: { timeout: 5000 }
+ }
+ },
+ {
+ name: 'Verify approval sent',
+ action: {
+ type: 'query_records',
+ target: 'approval_request',
+ payload: {
+ filters: ['report_id', '=', '{{reportId}}']
+ }
+ },
+ assertions: [
+ {
+ field: 'body.length',
+ operator: 'gte',
+ expectedValue: 1
+ }
+ ]
+ }
+ ]
+};
+```
+
+---
+
+## Best Practices
+
+1. **Use descriptive names**: Make test names clear and self-documenting
+2. **Tag appropriately**: Use tags like "critical", "regression", "smoke" for filtering
+3. **Capture variables**: Use `capture` to pass data between steps
+4. **Clean up**: Always use teardown to clean test data
+5. **Test permissions**: Use the `user` field to test role-based access
+6. **Test errors**: Use the `error` assertion operator to verify error handling
+7. **Organize suites**: Group related scenarios into logical test suites