From 58b311e3528ee08d8b709f7f0a8d60a038763840 Mon Sep 17 00:00:00 2001
From: "copilot-swe-agent[bot]" <198982749+Copilot@users.noreply.github.com>
Date: Mon, 26 Jan 2026 06:11:07 +0000
Subject: [PATCH 01/22] Initial plan
From 9478e056d576a6333531fadc37225210c91e7af6 Mon Sep 17 00:00:00 2001
From: "copilot-swe-agent[bot]" <198982749+Copilot@users.noreply.github.com>
Date: Mon, 26 Jan 2026 06:49:35 +0000
Subject: [PATCH 02/22] docs: create ObjectOS (System Protocol) documentation
structure
- Add comprehensive ObjectOS overview explaining runtime orchestration
- Document system lifecycle (boot, install, upgrade, rollback)
- Create plugin package specification with manifest examples
- Define configuration resolution with hierarchical merge strategies
- Establish i18n standard with translation bundles and locale resolution
Each page 200-400+ lines with practical examples, code snippets, and cross-references to ObjectQL/ObjectUI. Follows same tone and structure as existing protocol docs.
Co-authored-by: hotlong <50353452+hotlong@users.noreply.github.com>
---
content/docs/00-introduction/architecture.mdx | 201 +++
.../00-introduction/design-principles.mdx | 161 +++
content/docs/00-introduction/glossary.mdx | 189 +++
content/docs/00-introduction/index.mdx | 30 +
content/docs/00-introduction/meta.json | 9 +
content/docs/00-introduction/overview.mdx | 105 ++
content/docs/01-core-concepts/index.mdx | 52 +
content/docs/01-core-concepts/meta.json | 8 +
.../docs/01-core-concepts/metadata-driven.mdx | 253 ++++
.../docs/01-core-concepts/object-model.mdx | 749 +++++++++++
content/docs/01-core-concepts/the-stack.mdx | 505 ++++++++
.../docs/02-protocols/01-objectql/index.mdx | 409 ++++++
.../docs/02-protocols/01-objectql/meta.json | 9 +
.../02-protocols/01-objectql/query-syntax.mdx | 952 ++++++++++++++
.../docs/02-protocols/01-objectql/schema.mdx | 906 ++++++++++++++
.../02-protocols/01-objectql/security.mdx | 902 ++++++++++++++
.../docs/02-protocols/01-objectql/types.mdx | 1091 +++++++++++++++++
.../docs/02-protocols/02-objectui/actions.mdx | 1075 ++++++++++++++++
.../docs/02-protocols/02-objectui/concept.mdx | 726 +++++++++++
.../docs/02-protocols/02-objectui/index.mdx | 568 +++++++++
.../02-protocols/02-objectui/layout-dsl.mdx | 925 ++++++++++++++
.../docs/02-protocols/02-objectui/meta.json | 9 +
.../02-objectui/widget-contract.mdx | 883 +++++++++++++
.../03-objectos/config-resolution.mdx | 878 +++++++++++++
.../03-objectos/i18n-standard.mdx | 841 +++++++++++++
.../docs/02-protocols/03-objectos/index.mdx | 530 ++++++++
.../02-protocols/03-objectos/lifecycle.mdx | 803 ++++++++++++
.../docs/02-protocols/03-objectos/meta.json | 9 +
.../02-protocols/03-objectos/plugin-spec.mdx | 946 ++++++++++++++
content/docs/02-protocols/index.mdx | 212 ++++
content/docs/02-protocols/meta.json | 8 +
31 files changed, 14944 insertions(+)
create mode 100644 content/docs/00-introduction/architecture.mdx
create mode 100644 content/docs/00-introduction/design-principles.mdx
create mode 100644 content/docs/00-introduction/glossary.mdx
create mode 100644 content/docs/00-introduction/index.mdx
create mode 100644 content/docs/00-introduction/meta.json
create mode 100644 content/docs/00-introduction/overview.mdx
create mode 100644 content/docs/01-core-concepts/index.mdx
create mode 100644 content/docs/01-core-concepts/meta.json
create mode 100644 content/docs/01-core-concepts/metadata-driven.mdx
create mode 100644 content/docs/01-core-concepts/object-model.mdx
create mode 100644 content/docs/01-core-concepts/the-stack.mdx
create mode 100644 content/docs/02-protocols/01-objectql/index.mdx
create mode 100644 content/docs/02-protocols/01-objectql/meta.json
create mode 100644 content/docs/02-protocols/01-objectql/query-syntax.mdx
create mode 100644 content/docs/02-protocols/01-objectql/schema.mdx
create mode 100644 content/docs/02-protocols/01-objectql/security.mdx
create mode 100644 content/docs/02-protocols/01-objectql/types.mdx
create mode 100644 content/docs/02-protocols/02-objectui/actions.mdx
create mode 100644 content/docs/02-protocols/02-objectui/concept.mdx
create mode 100644 content/docs/02-protocols/02-objectui/index.mdx
create mode 100644 content/docs/02-protocols/02-objectui/layout-dsl.mdx
create mode 100644 content/docs/02-protocols/02-objectui/meta.json
create mode 100644 content/docs/02-protocols/02-objectui/widget-contract.mdx
create mode 100644 content/docs/02-protocols/03-objectos/config-resolution.mdx
create mode 100644 content/docs/02-protocols/03-objectos/i18n-standard.mdx
create mode 100644 content/docs/02-protocols/03-objectos/index.mdx
create mode 100644 content/docs/02-protocols/03-objectos/lifecycle.mdx
create mode 100644 content/docs/02-protocols/03-objectos/meta.json
create mode 100644 content/docs/02-protocols/03-objectos/plugin-spec.mdx
create mode 100644 content/docs/02-protocols/index.mdx
create mode 100644 content/docs/02-protocols/meta.json
diff --git a/content/docs/00-introduction/architecture.mdx b/content/docs/00-introduction/architecture.mdx
new file mode 100644
index 000000000..c4bedf1e2
--- /dev/null
+++ b/content/docs/00-introduction/architecture.mdx
@@ -0,0 +1,201 @@
+---
+title: Architecture
+description: Understanding the ObjectStack Protocol Architecture - How 11 protocol namespaces collaborate to build the Enterprise Kernel
+---
+
+import { Layers, Database, Layout, ShieldCheck, Lock, Cog, Brain, Cloud, Zap } from 'lucide-react';
+
+# Architecture Overview
+
+ObjectStack is not a monolithic framework. It is a composable ecosystem designed around a **Protocol-Driven Architecture**. The system is organized into **11 protocol namespaces**, each responsible for a specific domain.
+
+Each protocol is decoupled and communicates via standard JSON schemas defined with Zod. This allows you to swap out implementations (e.g., swapping the Postgres driver for MongoDB, or the React renderer for Flutter) without breaking the rest of the stack.
+
+## The 11 Protocol Namespaces
+
+ObjectStack is organized into 11 protocol namespaces:
+
+
+ }
+ title="Data Protocol"
+ description="Object schema, fields, validation, and queries."
+ />
+ }
+ title="Driver Protocol"
+ description="Database adapters (Postgres, MongoDB, SQLite, etc.)."
+ />
+ }
+ title="Permission Protocol"
+ description="Object-level, field-level, sharing, and territory rules."
+ />
+ }
+ title="UI Protocol"
+ description="Apps, views, dashboards, reports, and themes."
+ />
+ }
+ title="System Protocol"
+ description="Events, jobs, translations, and audit logging."
+ />
+ }
+ title="Auth Protocol"
+ description="Identity, roles, sessions, and authentication strategies."
+ />
+ }
+ title="Kernel Protocol"
+ description="Plugin lifecycle, manifest, logging, and context."
+ />
+ }
+ title="Hub Protocol"
+ description="Marketplace, licensing, tenancy, and deployment."
+ />
+ }
+ title="AI Protocol"
+ description="Agents, RAG, NLQ, predictive models, and orchestration."
+ />
+ }
+ title="API Protocol"
+ description="REST contracts, discovery, realtime, and routing."
+ />
+ }
+ title="Automation Protocol"
+ description="Workflows, flows, and webhooks."
+ />
+
+
+## The Three-Layer Architecture
+
+While ObjectStack has 11 protocol namespaces, they are logically grouped into three architectural layers:
+
+### 1. Data Layer (ObjectQL)
+**"The Universal Data Protocol"**
+
+The foundation layer responsible for **Data Definition** and **Data Access**.
+
+**Protocols:**
+- **Data Protocol:** Object schema, fields, validation, queries, filters
+- **Driver Protocol:** Database adapters for Postgres, MongoDB, SQLite, etc.
+- **Permission Protocol:** Object-level CRUD, field-level security, sharing rules
+- **AI Protocol:** AI agents, RAG pipelines, NLQ, predictive models
+
+**Role:** Defines *Structure* (Schema) and *Intent* (Query AST).
+
+**Responsibility:** It knows *what* a "Customer" object looks like, but it doesn't know *who* is accessing it or *how* it is displayed.
+
+**Key Component:** The **Compiler**. It takes an abstract query (`find customers where active = true`) and translates it into optimized SQL/NoSQL queries for the specific underlying database.
+
+### 2. Presentation Layer (ObjectUI)
+**"Server-Driven UI"**
+
+The interface layer responsible for **Visual Representation** and **User Interaction**.
+
+**Protocols:**
+- **UI Protocol:** Apps, views, dashboards, reports, actions, themes
+
+**Role:** Projects the Data Protocol into visual components.
+
+**Responsibility:** It knows *how* to display a "Customer" form, but it doesn't know the business rules or who can access it.
+
+**Key Component:** The **Renderer**. It takes UI metadata (JSON) and renders it as native components (React, Flutter, etc.).
+
+### 3. Control Layer (ObjectOS)
+**"The Business Kernel"**
+
+The orchestration layer responsible for **Runtime** and **Governance**.
+
+**Protocols:**
+- **System Protocol:** Events, jobs, translations, audit logging
+- **Auth Protocol:** Identity, roles, sessions, authentication
+- **Kernel Protocol:** Plugin lifecycle, manifest, context
+- **Hub Protocol:** Marketplace, licensing, tenancy
+- **API Protocol:** REST contracts, discovery, realtime
+- **Automation Protocol:** Workflows, flows, webhooks
+
+**Role:** Orchestrates the entire system and enforces policies.
+
+**Responsibility:** It knows *who* is accessing *what* and *when* actions should happen.
+
+**Key Component:** The **Kernel**. It manages plugins, handles events, enforces security, and coordinates between layers.
+
+## How They Work Together
+
+```
+┌─────────────────────────────────────────┐
+│ Control Layer (ObjectOS) │
+│ ┌──────────┐ ┌────────┐ ┌──────────┐│
+│ │ Kernel │ │ Auth │ │ System ││
+│ │ Protocol │ │Protocol│ │ Protocol ││
+│ └──────────┘ └────────┘ └──────────┘│
+└─────────────────────────────────────────┘
+ ↕ ↕
+┌──────────────────┐ ┌──────────────────┐
+│ Data Layer (QL) │ │ UI Layer (UI) │
+│ ┌────────────┐ │ │ ┌────────────┐ │
+│ │ Data │ │ │ │ UI │ │
+│ │ Protocol │ │ │ │ Protocol │ │
+│ └────────────┘ │ │ └────────────┘ │
+│ ┌────────────┐ │ │ │
+│ │ Driver │ │ │ │
+│ │ Protocol │ │ │ │
+│ └────────────┘ │ │ │
+└──────────────────┘ └──────────────────┘
+ ↕
+ ┌──────────┐
+ │ Database │
+ └──────────┘
+```
+
+### Example: Creating a Record
+
+1. **UI Layer:** User clicks "Save" on a Customer form
+2. **Control Layer:** Kernel receives the request, validates authentication
+3. **Data Layer:** ObjectQL compiler generates SQL INSERT statement
+4. **Driver:** PostgreSQL driver executes the query
+5. **Control Layer:** Event system triggers "after_create" workflow
+6. **UI Layer:** Renderer updates the interface with the new record
+
+## Protocol vs Implementation
+
+**Critical Distinction:**
+
+- **Protocol Layer:** Defined in `packages/spec` (This Repository)
+ - Pure Zod schemas
+ - TypeScript types
+ - No runtime logic
+
+- **Runtime Layer:** Implemented in separate packages
+ - Node.js Kernel (`@objectstack/kernel`)
+ - React Renderer (`@objectstack/react`)
+ - PostgreSQL Driver (`@objectstack/driver-postgres`)
+
+The protocol defines the "what" and "how." The runtime implements it.
+
+## Design Benefits
+
+### 1. Composability
+Each protocol can be used independently or combined with others.
+
+### 2. Replaceability
+Don't like the React renderer? Build a Vue or Flutter one. The protocol stays the same.
+
+### 3. Testability
+Test against the protocol specification, not a specific implementation.
+
+### 4. Future-Proof
+New features are additive, not breaking. Implementations can evolve independently.
+
+## Next Steps
+
+- [Glossary](/docs/00-introduction/glossary) - Key terminology explained
+- [Core Concepts](/docs/01-core-concepts) - Understand metadata-driven development
+- [Protocols](/docs/02-protocols) - Dive into each protocol specification
diff --git a/content/docs/00-introduction/design-principles.mdx b/content/docs/00-introduction/design-principles.mdx
new file mode 100644
index 000000000..1f1eee373
--- /dev/null
+++ b/content/docs/00-introduction/design-principles.mdx
@@ -0,0 +1,161 @@
+---
+title: Design Principles
+description: The unshakable core principles that govern the ObjectStack ecosystem - The Constitution of the Post-SaaS Era
+---
+
+import { Scale, Code2, Database, ScrollText } from 'lucide-react';
+
+# Design Principles
+
+ObjectStack exists to return enterprise application development to its essence: **Data**.
+
+To maintain a healthy, decoupled, and future-proof ecosystem, we uphold the following core principles. These are not suggestions; they are the constraints that enable our freedom.
+
+
+ }
+ title="I. Protocol Neutrality"
+ description="The Protocol is law. The Implementation is merely an opinion."
+ />
+ }
+ title="II. Mechanism over Policy"
+ description="Provide the tools to build rules, do not hardcode the rules themselves."
+ />
+ }
+ title="III. Single Source of Truth"
+ description="There is no 'Code'. There is only Schema."
+ />
+ }
+ title="IV. Local-First by Default"
+ description="The Cloud is a sync peer, not a master."
+ />
+
+
+---
+
+## Principle I: Protocol Neutrality
+
+**"The Protocol is neutral. The Engine is replaceable."**
+
+ObjectQL must not contain any logic specific to a particular language (e.g., Node.js), database (e.g., PostgreSQL), or runtime (e.g., Browser).
+
+### The Law
+
+- **Spec before Engine:** Any feature must first be defined in the Specification layer (`packages/spec`) before a single line of code is written in the Engine layer. We reject the "implement first, standardize later" approach.
+- **Zero Leakage:** Implementation details (like React Hooks usage, or SQL specific syntax) must never leak into the Protocol definition.
+
+### The Benefit
+
+This ensures that an ObjectStack application defined today can theoretically run on:
+
+- A Node.js server with PostgreSQL (Today's Standard)
+- A Python server with SQLite (AI/Data Science)
+- A Rust WASM module in the browser (Local-First)
+
+---
+
+## Principle II: Mechanism over Policy
+
+**"Give them the physics, not the simulation."**
+
+ObjectStack provides the **Mechanisms** (The "How"):
+
+- *"Here is how you define a validation rule."*
+- *"Here is how you define a permission scope."*
+
+ObjectStack never dictates the **Policy** (The "What"):
+
+- *It never says "Passwords must be 8 characters".*
+- *It never says "Users must belong to a Department".*
+
+### Separation of Concerns
+
+We cleanly separate the **Definition** from the **Execution**.
+
+| Layer | Responsibility | Example |
+| :--- | :--- | :--- |
+| **Protocol (Mechanism)** | Defines the capabilities. | `allowRead: string` (A slot for a formula) |
+| **App (Policy)** | Defines the business logic. | `allowRead: "$user.role == 'admin'"` |
+| **Engine (Execution)** | Enforces the logic. | Compiles formula to SQL `WHERE` clause. |
+
+---
+
+## Principle III: The Single Source of Truth
+
+**"There is no 'Code'. There is only Schema."**
+
+In a traditional application, the "truth" is scattered:
+
+1. Database Schema (`table.sql`)
+2. Backend Models (`User.ts`)
+3. Frontend Validation (`schema.zod.ts`)
+4. API Documentation (`swagger.json`)
+
+In ObjectStack, **The Object Protocol is the only truth.**
+
+- The Database is a *derivative* of the Protocol.
+- The UI is a *projection* of the Protocol.
+- The API is a *consequence* of the Protocol.
+
+If you change the Protocol, the entire system (DB, API, UI) must adapt automatically.
+
+---
+
+## Principle IV: Local-First by Default
+
+**"The Cloud is a sync peer, not a master."**
+
+We reject the notion that software must stop working when the internet connection drops.
+
+- **Latency is the enemy:** All interactions should be optimistic and instant (0ms).
+- **Ownership is the goal:** The user's data essentially lives on their device. The server is just a hub for backup and collaboration.
+
+### The "Seven Hops" Problem
+
+In a traditional Cloud app, a simple button click travels through:
+
+```
+Click → Wi-Fi → ISP → Cloud Load Balancer → Web Server → Database → Query Execution
+```
+
+...and then all the way back.
+
+### The Local-First Solution
+
+ObjectStack apps are designed to read and write to a **Local Database** (embedded within the client environment) first.
+
+```
+Click → Local DB → UI Update (0ms Latency)
+```
+
+The synchronization with the cloud happens in the background, asynchronously.
+
+**Benefits:**
+
+1. **Instant Response:** The UI reacts immediately (optimistic UI)
+2. **Offline Capability:** Field workers, airplanes, or spotty connections are no longer blockers
+3. **Data Sovereignty:** The data physically resides on the user's device
+
+---
+
+## Summary
+
+These principles guide every design decision in ObjectStack:
+
+| Principle | What it Means |
+| :--- | :--- |
+| **Protocol Neutrality** | The spec is separate from implementation. ObjectStack can run anywhere. |
+| **Mechanism over Policy** | We provide the tools, you define the rules. |
+| **Single Source of Truth** | The schema is the application. Everything else derives from it. |
+| **Local-First** | Users own their data. The cloud is just for sync. |
+
+By adhering to these values, we build software that is **resilient to change**, **respectful of user time**, and **technically sovereign**.
+
+## Next Steps
+
+- [Architecture](/docs/00-introduction/architecture) - See how these principles shape the system
+- [Glossary](/docs/00-introduction/glossary) - Understand key terms
+- [Core Concepts](/docs/01-core-concepts) - Learn about metadata-driven development
diff --git a/content/docs/00-introduction/glossary.mdx b/content/docs/00-introduction/glossary.mdx
new file mode 100644
index 000000000..a14466a52
--- /dev/null
+++ b/content/docs/00-introduction/glossary.mdx
@@ -0,0 +1,189 @@
+---
+title: Glossary
+description: Key terminology for the ObjectStack ecosystem - Speaking the same language
+---
+
+import { Book, Server, Code, Database } from 'lucide-react';
+
+# Glossary
+
+To navigate the ObjectStack ecosystem effectively, it's helpful to understand the specific vocabulary we use. While many terms are standard in computer science, some have specific nuances in our "Protocol-Driven" context.
+
+## Core Concepts
+
+### ObjectStack
+The umbrella term for the entire suite of protocols and reference implementations. It is organized into **11 protocol namespaces** grouped into three architectural layers.
+
+### Protocol
+A specification defined with Zod schemas that describes how a system component should behave. Protocols are implementation-agnostic - they define the "what" and "how," not the specific code.
+
+### Protocol Namespace
+A logical grouping of related schemas and types. ObjectStack has 11 protocol namespaces: Data, Driver, Permission, UI, System, Auth, Kernel, Hub, AI, API, and Automation.
+
+### Kernel
+The runtime engine (Control Layer) that orchestrates all protocols, manages plugins, and enforces security policies.
+
+---
+
+## The Three Layers
+
+### ObjectQL (Data Layer)
+The database-agnostic data protocol. Defines objects, fields, queries, and filters. Think of it as "universal SQL" that compiles to any backend.
+
+### ObjectUI (Presentation Layer)
+The server-driven UI protocol. Defines apps, views, dashboards, and themes as JSON metadata. The renderer converts this to native components.
+
+### ObjectOS (Control Layer)
+The system protocol layer. Manages runtime, plugins, authentication, events, and automation. The "operating system" for business logic.
+
+---
+
+## Data & Schema
+
+### Object
+The fundamental unit of data modeling. Roughly equivalent to a "Table" in SQL or a "Collection" in NoSQL. An Object definition includes Fields, Validations, and Permissions.
+
+### Field
+A single data attribute within an Object. Has a type (text, number, lookup, etc.) and optional constraints (required, unique, etc.).
+
+### Driver
+An adapter plugin that allows ObjectQL to communicate with a specific database engine.
+- Examples: `@objectstack/driver-postgres`, `@objectstack/driver-mongodb`
+
+### AST (Abstract Syntax Tree)
+The intermediate representation of a query. ObjectQL parses requests into an AST before the Driver translates it into database-specific queries.
+
+### Virtual Field
+A field that doesn't exist physically in the database but is computed on the fly (e.g., calculated fields, aggregations).
+
+---
+
+## UI & Interaction
+
+### View
+A UI component that displays object data. Types include ListView (grid/kanban), FormView (create/edit), and specialized views (calendar, gantt).
+
+### Widget
+A reusable UI component that can be embedded in pages or dashboards. Follows the ObjectUI widget contract.
+
+### Layout
+A JSON structure that describes the visual arrangement of components. Can be nested and dynamic.
+
+### Action
+A discrete unit of logic that can be triggered by a user (button click) or system event. Defines behaviors like navigation, data updates, or API calls.
+
+---
+
+## Automation & Logic
+
+### Workflow
+A business process defined as a Finite State Machine (FSM). Consists of States, Transitions, and Guards. Executes when records move between states.
+
+### Flow
+A visual logic automation tool. Supports:
+- **Screen Flows:** Interactive, user-driven processes
+- **Autolaunched Flows:** Triggered by events
+- **Scheduled Flows:** Run on a schedule
+
+### Webhook
+An HTTP callback that allows external systems to trigger actions or receive data from ObjectStack.
+
+---
+
+## Security & Access
+
+### Permission Set
+A collection of object-level and field-level permissions that can be assigned to users or roles.
+
+### FLS (Field-Level Security)
+Granular access control applied to individual fields (columns), not just entire objects (rows).
+
+### OWD (Organization-Wide Defaults)
+The baseline access level for records before sharing rules are applied. Can be Private, Public Read, or Public Read/Write.
+
+### Sharing Rule
+Additional access grants based on criteria (owner-based) or conditions (criteria-based). Extends access beyond OWD.
+
+### Territory
+A hierarchical access control model that grants data access based on geographic or organizational boundaries.
+
+---
+
+## System & Runtime
+
+### Plugin
+An extension package that adds functionality to ObjectStack. Follows the Kernel Protocol manifest specification.
+
+### Manifest
+The configuration file (`objectstack.config.ts`) that declares a plugin's metadata, dependencies, and resources.
+
+### Event Bus
+The system messaging infrastructure that enables plugins to communicate asynchronously via events.
+
+### Job
+A scheduled or queued background task managed by the System Protocol. Supports cron schedules, intervals, and one-time execution.
+
+---
+
+## Enterprise Features
+
+### Space (Workspace)
+A logical isolation unit for multi-tenancy. Each space has its own data, users, and configuration.
+
+### Tenant
+An organization or customer in a multi-tenant deployment. Each tenant's data is isolated using strategies like schema isolation or row-level filtering.
+
+### Datasource
+An external data connection configuration. Allows ObjectStack to query and sync with external databases or APIs.
+
+---
+
+## Development Terms
+
+### TCK (Technology Compatibility Kit)
+A test suite that validates if a Driver or Renderer complies with the ObjectStack Protocol. Passing the TCK certifies compatibility.
+
+### Compiler
+The component that translates high-level ObjectQL queries into optimized database-specific queries. Not a runtime wrapper like an ORM.
+
+### Renderer
+The UI component that converts ObjectUI metadata (JSON) into native interface elements (React, Flutter, etc.).
+
+---
+
+## Architecture Patterns
+
+### Protocol-Driven
+A development paradigm where logic is defined in declarative data formats (JSON/YAML) with Zod schemas rather than imperative code.
+
+### Local-First
+An architectural pattern where applications read/write to a local database first, with background synchronization to the cloud.
+
+### Database Agnostic
+The ability to swap database backends without changing application code. ObjectQL acts as a universal abstraction layer.
+
+### Server-Driven UI
+A pattern where the server sends UI structure as data (JSON), and the client renders it dynamically. Enables updates without app deployments.
+
+---
+
+## Abbreviations
+
+- **AST:** Abstract Syntax Tree
+- **CRUD:** Create, Read, Update, Delete
+- **DSL:** Domain Specific Language
+- **FLS:** Field-Level Security
+- **FSM:** Finite State Machine
+- **NLQ:** Natural Language Query
+- **OWD:** Organization-Wide Defaults
+- **RAG:** Retrieval-Augmented Generation
+- **RBAC:** Role-Based Access Control
+- **TCK:** Technology Compatibility Kit
+
+---
+
+## Next Steps
+
+- [Core Concepts](/docs/01-core-concepts) - Understand metadata-driven development
+- [Protocols](/docs/02-protocols) - Explore the protocol specifications
+- [Development](/docs/03-development) - Start building with ObjectStack
diff --git a/content/docs/00-introduction/index.mdx b/content/docs/00-introduction/index.mdx
new file mode 100644
index 000000000..e5b44d0fb
--- /dev/null
+++ b/content/docs/00-introduction/index.mdx
@@ -0,0 +1,30 @@
+---
+title: Introduction
+description: Welcome to ObjectStack - The Metadata-Driven Protocol for the Post-SaaS Era
+---
+
+# Introduction to ObjectStack
+
+ObjectStack is a **metadata-driven protocol** that transforms how we build enterprise software. Rather than writing code for every feature, you define your business logic declaratively through metadata (JSON/YAML), and the ObjectStack Kernel handles the execution.
+
+## What is ObjectStack?
+
+ObjectStack is a **full-stack metadata protocol** that provides:
+
+- **ObjectQL**: A database-agnostic data layer
+- **ObjectUI**: Server-driven UI rendering
+- **ObjectOS**: A plugin-based runtime kernel
+
+Think of it as:
+- **Kubernetes** for business applications
+- **Terraform** for data modeling
+- **GraphQL** + **React Server Components** combined into one protocol
+
+## Getting Started
+
+Choose your learning path:
+
+- [Overview](/docs/00-introduction/overview) - What is ObjectStack?
+- [Design Principles](/docs/00-introduction/design-principles) - Core philosophy
+- [Architecture](/docs/00-introduction/architecture) - System overview
+- [Glossary](/docs/00-introduction/glossary) - Key terminology
diff --git a/content/docs/00-introduction/meta.json b/content/docs/00-introduction/meta.json
new file mode 100644
index 000000000..35b133565
--- /dev/null
+++ b/content/docs/00-introduction/meta.json
@@ -0,0 +1,9 @@
+{
+ "title": "📍 Introduction",
+ "pages": [
+ "overview",
+ "design-principles",
+ "architecture",
+ "glossary"
+ ]
+}
diff --git a/content/docs/00-introduction/overview.mdx b/content/docs/00-introduction/overview.mdx
new file mode 100644
index 000000000..9e9b82614
--- /dev/null
+++ b/content/docs/00-introduction/overview.mdx
@@ -0,0 +1,105 @@
+---
+title: Overview
+description: ObjectStack is What? A Full-Stack Metadata Protocol for Building Enterprise Applications
+---
+
+import { Database, Layout, Cog } from 'lucide-react';
+
+# What is ObjectStack?
+
+**ObjectStack** is not just a framework; it is a **Protocol** for building enterprise software. It decouples the *Business Intent* (defined in JSON/YAML) from the *Technical Execution* (handled by the Kernel).
+
+## The Problem
+
+In traditional development, application logic is scattered:
+
+1. **Database Schema** (`table.sql`)
+2. **Backend Models** (`User.ts`)
+3. **Frontend Validation** (`schema.zod.ts`)
+4. **API Documentation** (`swagger.json`)
+
+When requirements change, you update code in multiple places. This is **Implementation Coupling**.
+
+## The Solution
+
+ObjectStack centralizes the "Intent" into a single Protocol Definition (JSON/YAML). The implementation layers (React, Node.js, SQL) act merely as **Runtime Engines** that interpret this protocol.
+
+
+ }
+ title="ObjectQL (Data Layer)"
+ description="Define data structures, queries, and business logic. Database-agnostic abstraction layer."
+ />
+ }
+ title="ObjectUI (Presentation Layer)"
+ description="Server-driven UI definitions. Express interfaces as JSON, not code."
+ />
+ }
+ title="ObjectOS (Control Layer)"
+ description="Runtime kernel, plugins, security, and integration. The platform foundation."
+ />
+
+
+## The "Stack" Analogy
+
+Think of ObjectStack as:
+
+- **Kubernetes** for business applications - Declarative configuration over imperative code
+- **Terraform** for data modeling - Infrastructure as code, but for data
+- **GraphQL + React Server Components** - Schema-driven data + UI rendering combined
+
+## Key Features
+
+### 1. Protocol-Driven Architecture
+
+**The UI is a Projection. The API is a Consequence.**
+
+- ObjectUI does not "build" a form; it *projects* the ObjectQL schema into a visual representation
+- You do not write endpoints; ObjectOS *generates* the secure graph based on the access control protocol
+
+### 2. Local-First by Default
+
+**"The Cloud is a sync peer, not a master."**
+
+- All interactions are optimistic and instant (0ms latency)
+- Data lives on the user's device
+- The server is just a hub for backup and collaboration
+
+### 3. Database Agnostic
+
+**ObjectQL treats the database as an Implementation Detail.**
+
+- Start with SQLite for prototyping
+- Migrate to PostgreSQL for production
+- Archive to Snowflake for analytics
+- **No code changes required**
+
+## Real-World Benefits
+
+| Traditional Approach | ObjectStack Approach |
+| :--- | :--- |
+| Write SQL migrations manually | Schema changes sync automatically |
+| Build CRUD APIs by hand | REST/GraphQL generated from schema |
+| Duplicate validation logic 3x | Define once, enforce everywhere |
+| Lock into one database vendor | Swap databases without code changes |
+| Offline = broken app | Offline-first with background sync |
+
+## Who Should Use ObjectStack?
+
+### Enterprise Developers
+Building internal tools, CRMs, ERPs, or admin panels? ObjectStack eliminates 80% of the boilerplate.
+
+### Platform Builders
+Creating a SaaS product or multi-tenant application? ObjectStack provides enterprise-grade security and isolation.
+
+### Integration Engineers
+Connecting multiple systems? ObjectStack's protocol-driven approach makes it easy to map and transform data.
+
+## Next Steps
+
+- [Design Principles](/docs/00-introduction/design-principles) - Understand the philosophy
+- [Architecture](/docs/00-introduction/architecture) - Deep dive into the system
+- [Glossary](/docs/00-introduction/glossary) - Learn key terminology
+- [Core Concepts](/docs/01-core-concepts) - Metadata-driven development explained
diff --git a/content/docs/01-core-concepts/index.mdx b/content/docs/01-core-concepts/index.mdx
new file mode 100644
index 000000000..a6cfaaf63
--- /dev/null
+++ b/content/docs/01-core-concepts/index.mdx
@@ -0,0 +1,52 @@
+---
+title: Core Concepts
+description: Understanding the fundamental concepts behind ObjectStack's metadata-driven architecture
+---
+
+# Core Concepts
+
+ObjectStack is built on a foundation of three revolutionary concepts that fundamentally change how we build enterprise software:
+
+1. **Metadata-Driven Development** - Define intent, not implementation
+2. **The Stack** - Three protocols working as one
+3. **Universal Object Model** - A unified way to model all business data
+
+These concepts work together to create a platform that is more flexible, maintainable, and powerful than traditional code-first approaches.
+
+## What You'll Learn
+
+- [Metadata-Driven](/docs/01-core-concepts/metadata-driven) - What is metadata-driven development?
+- [The Stack](/docs/01-core-concepts/the-stack) - How ObjectQL + ObjectUI + ObjectOS work together
+- [Object Model](/docs/01-core-concepts/object-model) - The Universal Object Model explained
+
+## Why This Matters
+
+Traditional development requires writing and maintaining code in multiple places:
+
+- Database migrations
+- Backend models and APIs
+- Frontend forms and validation
+- API documentation
+
+With ObjectStack, you define your business logic **once** as metadata, and the system automatically generates:
+
+✅ Database schema
+✅ CRUD APIs (REST/GraphQL)
+✅ Admin interface
+✅ Data validation
+✅ Access control
+
+## The Mental Shift
+
+Think of ObjectStack like this:
+
+| Traditional Approach | ObjectStack Approach |
+| :--- | :--- |
+| Write code for each feature | Define metadata once |
+| Scattered logic across layers | Single source of truth |
+| Imperative (how to do it) | Declarative (what you want) |
+| Coupled to technology stack | Protocol-agnostic |
+
+## Next Steps
+
+Start with [Metadata-Driven](/docs/01-core-concepts/metadata-driven) to understand the foundation of ObjectStack's approach.
diff --git a/content/docs/01-core-concepts/meta.json b/content/docs/01-core-concepts/meta.json
new file mode 100644
index 000000000..1e37d70cc
--- /dev/null
+++ b/content/docs/01-core-concepts/meta.json
@@ -0,0 +1,8 @@
+{
+ "title": "💡 Core Concepts",
+ "pages": [
+ "metadata-driven",
+ "the-stack",
+ "object-model"
+ ]
+}
diff --git a/content/docs/01-core-concepts/metadata-driven.mdx b/content/docs/01-core-concepts/metadata-driven.mdx
new file mode 100644
index 000000000..d5445e5db
--- /dev/null
+++ b/content/docs/01-core-concepts/metadata-driven.mdx
@@ -0,0 +1,253 @@
+---
+title: Metadata-Driven Development
+description: Understanding the core philosophy of defining business logic through metadata instead of code
+---
+
+import { Database, Code, Link, Laptop } from 'lucide-react';
+
+# What is Metadata-Driven Development?
+
+Metadata-driven development is a paradigm shift where **application logic is defined by declarative data (metadata), not imperative code.**
+
+## The Problem with Code-First
+
+In traditional development, the "Intent" (e.g., *"This field is a required email address"*) is scattered across multiple layers:
+
+1. **Database:** SQL constraints (`NOT NULL`, `CHECK`)
+2. **Backend:** ORM validation (TypeORM decorators, Prisma schemas)
+3. **Frontend:** UI validation (React Hook Form + Zod)
+4. **Documentation:** API specs (OpenAPI/Swagger)
+
+When a business requirement changes, you must update code in **three or four places**. This is **Implementation Coupling**.
+
+### Example: Adding a "Phone Number" Field
+
+**Traditional Approach:**
+
+```sql
+-- 1. Database migration
+ALTER TABLE users ADD COLUMN phone VARCHAR(20);
+```
+
+```typescript
+// 2. Backend model
+class User {
+ @Column()
+ @IsPhoneNumber()
+ phone: string;
+}
+```
+
+```typescript
+// 3. Frontend validation
+const schema = z.object({
+ phone: z.string().regex(/^\+?[1-9]\d{1,14}$/),
+});
+```
+
+```yaml
+# 4. API documentation
+components:
+ schemas:
+ User:
+ properties:
+ phone:
+ type: string
+ pattern: '^\+?[1-9]\d{1,14}$'
+```
+
+**4 files to change. 4 places to keep in sync. 4 opportunities for bugs.**
+
+## The Metadata-Driven Solution
+
+ObjectStack centralizes the "Intent" into a **single Protocol Definition**. The implementation layers act as **Runtime Engines** that interpret this protocol.
+
+### Example: The ObjectStack Way
+
+```typescript
+// ONE definition (in objectstack.config.ts)
+export const User = Object({
+ name: 'user',
+ fields: {
+ phone: Field.phone({
+ label: 'Phone Number',
+ required: true,
+ }),
+ },
+});
+```
+
+From this single definition, ObjectStack automatically:
+
+✅ Generates database schema
+✅ Creates validation rules
+✅ Builds CRUD APIs
+✅ Renders form fields
+✅ Produces API documentation
+
+## The Three Truths
+
+In metadata-driven development, we embrace three core truths:
+
+### 1. The UI is a Projection
+
+**Traditional:** Build a form component manually
+**ObjectStack:** The form is a *projection* of the schema
+
+The UI doesn't "build" a form; it **projects** the Object schema into visual components.
+
+```typescript
+// The schema IS the form
+const TaskForm =
+// No manual JSX needed
+```
+
+### 2. The API is a Consequence
+
+**Traditional:** Write REST endpoints by hand
+**ObjectStack:** APIs are *generated* from the schema
+
+You don't write controllers or routes. ObjectOS *generates* the entire API graph based on your Object definitions and permission rules.
+
+```bash
+# Automatically available after defining the object:
+GET /api/v1/task
+POST /api/v1/task
+GET /api/v1/task/:id
+PATCH /api/v1/task/:id
+DELETE /api/v1/task/:id
+```
+
+### 3. The Schema is the Application
+
+**Traditional:** The "application" is code scattered across many files
+**ObjectStack:** The "application" is a collection of metadata files
+
+Your entire business logic lives in:
+- Object definitions (`.object.ts`)
+- View configurations (`.view.ts`)
+- Workflow rules (`.workflow.ts`)
+
+The Kernel simply **interprets** these definitions.
+
+## Benefits of Metadata-Driven
+
+### 1. Single Source of Truth
+
+Change the metadata once, everything updates automatically.
+
+```typescript
+// Change this:
+phone: Field.phone({ required: true })
+
+// To this:
+phone: Field.phone({ required: false })
+
+// ✅ Database constraint updates
+// ✅ API validation updates
+// ✅ UI form updates
+// ✅ Documentation updates
+```
+
+### 2. Type Safety by Default
+
+All metadata is defined with Zod schemas:
+
+```typescript
+// Source: Zod schema
+const FieldSchema = z.object({
+ name: z.string(),
+ type: z.enum(['text', 'number', 'date']),
+});
+
+// Derived: TypeScript type
+type Field = z.infer;
+
+// Derived: JSON Schema (for IDE autocomplete)
+const jsonSchema = zodToJsonSchema(FieldSchema);
+```
+
+### 3. Technology Agnostic
+
+Because logic is declarative, you can swap implementations:
+
+```
+Same Metadata Definition
+ ↓
+┌─────────┴─────────┐
+│ │
+PostgreSQL MongoDB
+Node.js Python
+React Flutter
+```
+
+### 4. Reduced Boilerplate
+
+**Traditional:** ~300 lines of code for a simple CRUD feature
+**ObjectStack:** ~30 lines of metadata
+
+```typescript
+// All you need:
+export const Task = Object({
+ name: 'task',
+ fields: {
+ title: Field.text({ required: true }),
+ status: Field.select({
+ options: ['todo', 'in_progress', 'done'],
+ }),
+ assignee: Field.lookup({ object: 'user' }),
+ },
+});
+
+// That's it. Full CRUD functionality is ready.
+```
+
+## Real-World Analogy
+
+Think of metadata-driven development like **HTML vs Canvas**:
+
+### HTML (Declarative)
+```html
+
Hello World
+```
+You describe **what** you want. The browser handles **how** to render it.
+
+### Canvas (Imperative)
+```javascript
+ctx.font = '32px Arial';
+ctx.fillText('Hello World', 10, 50);
+```
+You specify **exactly how** to draw each pixel.
+
+**ObjectStack is the "HTML" of enterprise applications.**
+
+## When to Use Metadata-Driven
+
+✅ **Use metadata-driven when:**
+- Building CRUD-heavy applications
+- Need rapid prototyping and iteration
+- Want database flexibility (may change backends)
+- Building multi-tenant SaaS platforms
+- Require strict type safety and validation
+
+❌ **Don't use metadata-driven when:**
+- Building highly custom, pixel-perfect UIs
+- Need real-time 3D graphics or games
+- The problem domain is too unique for abstraction
+- Performance requires hand-optimized algorithms
+
+## Summary
+
+| Aspect | Traditional | Metadata-Driven |
+| :--- | :--- | :--- |
+| **Definition** | Code in multiple files | Single metadata definition |
+| **Changes** | Update 3-4 places | Update once |
+| **Type Safety** | Manual synchronization | Automatic from Zod |
+| **Flexibility** | Locked to tech stack | Technology agnostic |
+| **Boilerplate** | High (300+ lines) | Low (30 lines) |
+
+## Next Steps
+
+- [The Stack](/docs/01-core-concepts/the-stack) - How the three protocols work together
+- [Object Model](/docs/01-core-concepts/object-model) - Deep dive into the universal object model
+- [ObjectQL Protocol](/docs/02-protocols/01-objectql) - Learn the data protocol specification
diff --git a/content/docs/01-core-concepts/object-model.mdx b/content/docs/01-core-concepts/object-model.mdx
new file mode 100644
index 000000000..c193aca9c
--- /dev/null
+++ b/content/docs/01-core-concepts/object-model.mdx
@@ -0,0 +1,749 @@
+---
+title: Universal Object Model
+description: Understanding the unified way ObjectStack models all business data
+---
+
+import { Database, Link2, Box, List } from 'lucide-react';
+
+# The Universal Object Model
+
+At the heart of ObjectStack is a simple but powerful idea: **All business data can be modeled as Objects.**
+
+Whether you're building a CRM, ERP, project manager, or custom application, the fundamental building blocks are the same:
+- **Objects** (Customer, Order, Task)
+- **Fields** (Name, Status, Amount)
+- **Relationships** (Customer has many Orders)
+
+ObjectStack provides a **universal data model** that works across any domain.
+
+## What is an Object?
+
+An **Object** is a definition of a business entity. Think of it as:
+- A **database table** (in SQL terms)
+- A **collection** (in NoSQL terms)
+- A **class** (in OOP terms)
+- A **content type** (in CMS terms)
+
+But unlike traditional tables or classes, an Object is **pure metadata**. It's a declarative definition that exists independent of any specific database or programming language.
+
+### Anatomy of an Object
+
+```typescript
+import { Object, Field } from '@objectstack/spec';
+
+export const Task = Object({
+ // Machine name (snake_case)
+ name: 'project_task',
+
+ // Display label
+ label: 'Project Task',
+
+ // Plural label (for UI)
+ labelPlural: 'Project Tasks',
+
+ // Icon (optional)
+ icon: 'check-square',
+
+ // Description
+ description: 'Work items within projects',
+
+ // Field definitions
+ fields: {
+ title: Field.text({
+ label: 'Title',
+ required: true,
+ maxLength: 255,
+ }),
+
+ description: Field.textarea({
+ label: 'Description',
+ maxLength: 5000,
+ }),
+
+ status: Field.select({
+ label: 'Status',
+ options: ['todo', 'in_progress', 'review', 'done'],
+ defaultValue: 'todo',
+ }),
+
+ priority: Field.select({
+ label: 'Priority',
+ options: ['low', 'medium', 'high', 'critical'],
+ defaultValue: 'medium',
+ }),
+
+ assignee: Field.lookup({
+ label: 'Assignee',
+ object: 'user',
+ }),
+
+ project: Field.lookup({
+ label: 'Project',
+ object: 'project',
+ required: true,
+ }),
+
+ due_date: Field.date({
+ label: 'Due Date',
+ }),
+
+ estimated_hours: Field.number({
+ label: 'Estimated Hours',
+ min: 0,
+ max: 1000,
+ }),
+ },
+
+ // Capabilities (optional)
+ enable: {
+ trackHistory: true, // Audit log
+ apiEnabled: true, // REST API
+ search: true, // Full-text search
+ comments: true, // User comments
+ attachments: true, // File uploads
+ },
+});
+```
+
+## Objects vs Database Tables
+
+While Objects **compile to database tables**, they are not the same thing:
+
+| Aspect | Database Table | ObjectStack Object |
+| :--- | :--- | :--- |
+| **Definition** | SQL DDL (`CREATE TABLE`) | TypeScript metadata |
+| **Validation** | Database constraints | Zod schema |
+| **Relationships** | Foreign keys | Lookup fields |
+| **Permissions** | GRANT/REVOKE | Permission rules |
+| **Portability** | Database-specific | Database-agnostic |
+| **Evolution** | Migrations required | Automatic sync |
+
+### Example: Object → Table Mapping
+
+Given this Object:
+
+```typescript
+export const Contact = Object({
+ name: 'contact',
+ fields: {
+ first_name: Field.text({ required: true }),
+ last_name: Field.text({ required: true }),
+ email: Field.email({ unique: true }),
+ phone: Field.phone(),
+ account: Field.lookup({ object: 'account' }),
+ },
+});
+```
+
+ObjectQL generates this Postgres table:
+
+```sql
+CREATE TABLE contact (
+ id VARCHAR(18) PRIMARY KEY, -- Auto-generated
+ first_name VARCHAR(255) NOT NULL,
+ last_name VARCHAR(255) NOT NULL,
+ email VARCHAR(255) UNIQUE,
+ phone VARCHAR(20),
+ account_id VARCHAR(18), -- Foreign key
+
+ created_at TIMESTAMP NOT NULL, -- System fields
+ created_by VARCHAR(18) NOT NULL,
+ updated_at TIMESTAMP NOT NULL,
+ updated_by VARCHAR(18) NOT NULL,
+
+ FOREIGN KEY (account_id) REFERENCES account(id),
+ FOREIGN KEY (created_by) REFERENCES user(id),
+ FOREIGN KEY (updated_by) REFERENCES user(id)
+);
+```
+
+**Key Points:**
+- System fields (`id`, `created_at`, `updated_at`, etc.) are **automatic**
+- Lookups become **foreign keys**
+- Field types map to **appropriate SQL types**
+- Constraints are **enforced at the database level**
+
+## Field Types
+
+ObjectStack provides a comprehensive set of field types that cover 99% of business use cases:
+
+### Text Fields
+
+```typescript
+fields: {
+ // Single-line text
+ name: Field.text({
+ label: 'Name',
+ required: true,
+ maxLength: 120,
+ }),
+
+ // Multi-line text
+ notes: Field.textarea({
+ label: 'Notes',
+ maxLength: 5000,
+ }),
+
+ // Email with validation
+ email: Field.email({
+ label: 'Email',
+ unique: true,
+ }),
+
+ // Phone with formatting
+ phone: Field.phone({
+ label: 'Phone',
+ }),
+
+ // URL with validation
+ website: Field.url({
+ label: 'Website',
+ }),
+}
+```
+
+### Number Fields
+
+```typescript
+fields: {
+ // Integer or decimal
+ quantity: Field.number({
+ label: 'Quantity',
+ min: 0,
+ max: 10000,
+ }),
+
+ // Currency with formatting
+ amount: Field.currency({
+ label: 'Amount',
+ currency: 'USD',
+ }),
+
+ // Percentage
+ discount: Field.percent({
+ label: 'Discount',
+ min: 0,
+ max: 100,
+ }),
+}
+```
+
+### Date/Time Fields
+
+```typescript
+fields: {
+ // Date only
+ due_date: Field.date({
+ label: 'Due Date',
+ }),
+
+ // Date + Time
+ start_time: Field.datetime({
+ label: 'Start Time',
+ }),
+
+ // Time only
+ meeting_time: Field.time({
+ label: 'Meeting Time',
+ }),
+}
+```
+
+### Selection Fields
+
+```typescript
+fields: {
+ // Single select (dropdown)
+ status: Field.select({
+ label: 'Status',
+ options: ['draft', 'active', 'archived'],
+ defaultValue: 'draft',
+ }),
+
+ // Multi-select (checkbox group)
+ skills: Field.multiselect({
+ label: 'Skills',
+ options: ['javascript', 'python', 'go', 'rust'],
+ }),
+}
+```
+
+### Boolean Fields
+
+```typescript
+fields: {
+ is_active: Field.boolean({
+ label: 'Active',
+ defaultValue: true,
+ }),
+}
+```
+
+### Relationship Fields
+
+```typescript
+fields: {
+ // Many-to-one (foreign key)
+ customer: Field.lookup({
+ label: 'Customer',
+ object: 'customer',
+ required: true,
+ }),
+
+ // Many-to-many (junction table)
+ tags: Field.lookup({
+ label: 'Tags',
+ object: 'tag',
+ multiple: true,
+ }),
+}
+```
+
+### Advanced Fields
+
+```typescript
+fields: {
+ // Computed field
+ full_name: Field.formula({
+ label: 'Full Name',
+ returnType: 'text',
+ expression: 'first_name + " " + last_name',
+ }),
+
+ // Rollup aggregation
+ total_revenue: Field.rollup({
+ label: 'Total Revenue',
+ relatedObject: 'opportunity',
+ aggregation: 'sum',
+ field: 'amount',
+ }),
+
+ // JSON data
+ metadata: Field.json({
+ label: 'Metadata',
+ }),
+
+ // File attachment
+ resume: Field.file({
+ label: 'Resume',
+ accept: ['.pdf', '.doc', '.docx'],
+ maxSize: 5 * 1024 * 1024, // 5MB
+ }),
+}
+```
+
+## Relationships
+
+Relationships are the key to modeling complex business logic. ObjectStack supports three types:
+
+### 1. Lookup (Many-to-One)
+
+**Scenario:** Each Task belongs to one Project.
+
+```typescript
+export const Task = Object({
+ name: 'task',
+ fields: {
+ project: Field.lookup({
+ label: 'Project',
+ object: 'project',
+ required: true,
+ }),
+ },
+});
+```
+
+**Database:**
+```sql
+CREATE TABLE task (
+ id VARCHAR(18) PRIMARY KEY,
+ project_id VARCHAR(18) NOT NULL,
+ FOREIGN KEY (project_id) REFERENCES project(id)
+);
+```
+
+**Query:**
+```typescript
+// Get all tasks for a project
+const tasks = await ObjectQL.query({
+ object: 'task',
+ filter: { project: 'project_12345' },
+});
+
+// Include related project data
+const tasks = await ObjectQL.query({
+ object: 'task',
+ include: ['project'],
+});
+```
+
+### 2. Master-Detail (One-to-Many)
+
+**Scenario:** Each Project has many Tasks.
+
+```typescript
+export const Project = Object({
+ name: 'project',
+ fields: {
+ // No explicit field needed, relationship is inferred
+ },
+});
+```
+
+**Query:**
+```typescript
+// Get a project with all its tasks
+const project = await ObjectQL.query({
+ object: 'project',
+ id: 'project_12345',
+ include: {
+ tasks: {
+ object: 'task',
+ filter: { project: '$recordId' },
+ },
+ },
+});
+```
+
+**UI:**
+```typescript
+// In FormView, show related tasks
+{
+ label: 'Tasks',
+ component: 'related_list',
+ object: 'task',
+ filter: { project: '$recordId' },
+}
+```
+
+### 3. Many-to-Many
+
+**Scenario:** Each Task can have multiple Tags, and each Tag can be on multiple Tasks.
+
+```typescript
+export const Task = Object({
+ name: 'task',
+ fields: {
+ tags: Field.lookup({
+ label: 'Tags',
+ object: 'tag',
+ multiple: true, // Enables many-to-many
+ }),
+ },
+});
+```
+
+**Database (Junction Table):**
+```sql
+CREATE TABLE task (
+ id VARCHAR(18) PRIMARY KEY
+);
+
+CREATE TABLE tag (
+ id VARCHAR(18) PRIMARY KEY
+);
+
+-- Auto-generated junction table
+CREATE TABLE task_tag (
+ task_id VARCHAR(18),
+ tag_id VARCHAR(18),
+ PRIMARY KEY (task_id, tag_id),
+ FOREIGN KEY (task_id) REFERENCES task(id),
+ FOREIGN KEY (tag_id) REFERENCES tag(id)
+);
+```
+
+**Query:**
+```typescript
+// Get tasks with specific tags
+const tasks = await ObjectQL.query({
+ object: 'task',
+ filter: {
+ tags: { contains: 'tag_urgent' },
+ },
+ include: ['tags'],
+});
+```
+
+## Reference Filters
+
+When you create a lookup field, you often want to limit which records can be selected. This is where **Reference Filters** come in.
+
+### Example: Territory-Based Filtering
+
+```typescript
+export const Opportunity = Object({
+ name: 'opportunity',
+ fields: {
+ customer: Field.lookup({
+ label: 'Customer',
+ object: 'customer',
+
+ // Only show customers in the same region
+ referenceFilters: [
+ {
+ field: 'region',
+ operator: 'equals',
+ value: '$User.region',
+ },
+ ],
+ }),
+ },
+});
+```
+
+When a user creates an Opportunity, the Customer lookup will only show customers where `customer.region == user.region`.
+
+### Example: Dependent Lookups
+
+```typescript
+export const Task = Object({
+ name: 'task',
+ fields: {
+ project: Field.lookup({
+ label: 'Project',
+ object: 'project',
+ }),
+
+ milestone: Field.lookup({
+ label: 'Milestone',
+ object: 'milestone',
+
+ // Only show milestones from the selected project
+ referenceFilters: [
+ {
+ field: 'project',
+ operator: 'equals',
+ value: '$Record.project',
+ },
+ ],
+ }),
+ },
+});
+```
+
+The Milestone dropdown dynamically filters based on the selected Project.
+
+## System Fields
+
+Every Object automatically includes system fields for auditing and tracking:
+
+```typescript
+// These fields are AUTOMATIC (you don't define them)
+{
+ id: 'task_abc123', // Unique identifier
+ created_at: '2024-01-15T10:30:00Z', // Creation timestamp
+ created_by: 'user_xyz789', // User who created
+ updated_at: '2024-01-16T14:20:00Z', // Last update timestamp
+ updated_by: 'user_xyz789', // User who last updated
+}
+```
+
+If you enable `trackHistory`:
+
+```typescript
+{
+ enable: {
+ trackHistory: true,
+ },
+}
+```
+
+You also get:
+
+```typescript
+{
+ version: 5, // Record version number
+ is_deleted: false, // Soft delete flag
+}
+```
+
+## Validation Rules
+
+Objects support three levels of validation:
+
+### 1. Field-Level Validation
+
+```typescript
+fields: {
+ email: Field.email({
+ label: 'Email',
+ required: true, // Cannot be blank
+ unique: true, // Must be unique across all records
+ }),
+
+ age: Field.number({
+ label: 'Age',
+ min: 18, // Must be >= 18
+ max: 120, // Must be <= 120
+ }),
+}
+```
+
+### 2. Object-Level Validation
+
+```typescript
+import { Validation } from '@objectstack/spec';
+
+export const OpportunityValidation = Validation({
+ object: 'opportunity',
+ rules: [
+ {
+ name: 'amount_required_when_closed',
+ message: 'Amount is required when stage is Closed Won',
+ condition: {
+ field: 'stage',
+ operator: 'equals',
+ value: 'closed_won',
+ },
+ validates: {
+ field: 'amount',
+ operator: 'isNotNull',
+ },
+ },
+ ],
+});
+```
+
+### 3. Custom Validation (Code)
+
+For complex logic that can't be expressed declaratively:
+
+```typescript
+import { CustomValidation } from '@objectstack/spec';
+
+export const LeadValidation = CustomValidation({
+ object: 'lead',
+ async validate(record, context) {
+ // Check if email domain is blacklisted
+ const domain = record.email.split('@')[1];
+ const isBlacklisted = await context.db.query({
+ object: 'blacklist',
+ filter: { domain },
+ });
+
+ if (isBlacklisted.length > 0) {
+ return {
+ valid: false,
+ errors: [{ field: 'email', message: 'Email domain is blacklisted' }],
+ };
+ }
+
+ return { valid: true };
+ },
+});
+```
+
+## Indexing and Performance
+
+ObjectStack automatically creates indexes for:
+- Primary keys (`id`)
+- Unique fields (`email`, etc.)
+- Lookup fields (foreign keys)
+
+For custom performance optimization:
+
+```typescript
+export const Customer = Object({
+ name: 'customer',
+ fields: {
+ name: Field.text({ label: 'Name' }),
+ region: Field.select({ label: 'Region', options: ['US', 'EU', 'APAC'] }),
+ },
+
+ // Custom indexes
+ indexes: [
+ {
+ name: 'idx_customer_region_name',
+ fields: ['region', 'name'],
+ unique: false,
+ },
+ ],
+});
+```
+
+This creates:
+
+```sql
+CREATE INDEX idx_customer_region_name ON customer(region, name);
+```
+
+## Why a Universal Model Matters
+
+### 1. Consistency Across Domains
+
+Whether you're building a CRM, ERP, or custom app, you use the **same primitives**:
+
+```typescript
+// CRM
+const Customer = Object({ ... });
+const Opportunity = Object({ ... });
+
+// ERP
+const Product = Object({ ... });
+const Invoice = Object({ ... });
+
+// Project Management
+const Project = Object({ ... });
+const Task = Object({ ... });
+```
+
+Same API, same patterns, same tooling.
+
+### 2. Interoperability
+
+Because all Objects follow the same model, they can **reference each other**:
+
+```typescript
+// Link CRM to Projects
+export const Opportunity = Object({
+ name: 'opportunity',
+ fields: {
+ customer: Field.lookup({ object: 'customer' }),
+
+ // Reference an object from a different domain
+ project: Field.lookup({ object: 'project' }),
+ },
+});
+```
+
+### 3. Tooling Reuse
+
+Generic tools work across **all objects**:
+
+- **Form Builder:** Works for Customer, Task, Invoice, etc.
+- **Report Builder:** Aggregate any object
+- **API Generator:** Auto-generates endpoints for all objects
+- **Permission System:** Same ACL rules for everything
+
+### 4. AI/RAG Integration
+
+A universal model makes AI integration trivial:
+
+```typescript
+// AI agent can understand ANY object
+const schema = ObjectQL.getSchema('customer');
+const prompt = `Generate a query to find all ${schema.label} records where...`;
+```
+
+The AI doesn't need custom training for each object type.
+
+## Summary
+
+| Concept | Description |
+| :--- | :--- |
+| **Object** | A metadata definition of a business entity |
+| **Field** | A typed property of an object |
+| **Lookup** | A relationship between objects |
+| **Validation** | Rules enforced at save time |
+| **System Fields** | Automatic audit fields (id, created_at, etc.) |
+| **Reference Filters** | Contextual filtering of lookup options |
+
+The Universal Object Model is the foundation of ObjectStack. Every other protocol—permissions, workflows, views, reports—builds on top of these core primitives.
+
+## Next Steps
+
+- [ObjectQL Protocol](/docs/02-protocols/01-objectql) - Full specification of the data protocol
+- [Fields Reference](/docs/03-reference/fields) - Complete guide to all field types
+- [Relationships](/docs/04-guides/relationships) - Deep dive into modeling complex relationships
+- [Validation](/docs/04-guides/validation) - Advanced validation patterns
diff --git a/content/docs/01-core-concepts/the-stack.mdx b/content/docs/01-core-concepts/the-stack.mdx
new file mode 100644
index 000000000..4a24fe55f
--- /dev/null
+++ b/content/docs/01-core-concepts/the-stack.mdx
@@ -0,0 +1,505 @@
+---
+title: The Stack - ObjectQL + ObjectUI + ObjectOS
+description: How the three protocols work together as one cohesive system
+---
+
+import { Database, Layout, Cpu, ArrowRight, CheckCircle, Workflow } from 'lucide-react';
+
+# The Three-Layer Stack
+
+ObjectStack is built on three foundational protocols that work together as a unified system:
+
+
+ }
+ title="ObjectQL"
+ description="Data Protocol - Structure and queries"
+ />
+ }
+ title="ObjectOS"
+ description="Control Protocol - Runtime and governance"
+ />
+ }
+ title="ObjectUI"
+ description="View Protocol - Presentation and interaction"
+ />
+
+
+## Why Three Layers?
+
+Traditional applications tightly couple data, business logic, and presentation. This creates **Implementation Coupling** — changing one layer forces changes across the entire stack.
+
+ObjectStack enforces **Separation of Concerns** through protocol boundaries:
+
+```
+┌─────────────────────────────────────────┐
+│ ObjectUI (View Layer) │
+│ Apps, Views, Dashboards, Reports │
+│ "How do users interact?" │
+└──────────────┬──────────────────────────┘
+ │ API Protocol
+┌──────────────┴──────────────────────────┐
+│ ObjectOS (Control Layer) │
+│ Auth, Permissions, Workflows, Events │
+│ "Who can do what, when?" │
+└──────────────┬──────────────────────────┘
+ │ Query Protocol
+┌──────────────┴──────────────────────────┐
+│ ObjectQL (Data Layer) │
+│ Objects, Fields, Queries, Drivers │
+│ "What is the data structure?" │
+└─────────────────────────────────────────┘
+```
+
+## Layer 1: ObjectQL (Data Protocol)
+
+**Role:** Define the **Structure** and **Intent** of data.
+
+**Responsibilities:**
+- Object schema definitions (what is a "Customer"?)
+- Field types and validation rules
+- Query language (filtering, sorting, aggregation)
+- Database drivers (Postgres, MongoDB, SQLite)
+
+**Key Principle:** ObjectQL knows **nothing** about users, permissions, or UI. It only cares about data structure and queries.
+
+### Example: Defining a Customer Object
+
+```typescript
+// packages/crm/src/objects/customer.object.ts
+import { Object, Field } from '@objectstack/spec';
+
+export const Customer = Object({
+ name: 'customer',
+ label: 'Customer',
+ fields: {
+ name: Field.text({
+ label: 'Company Name',
+ required: true,
+ maxLength: 120,
+ }),
+ industry: Field.select({
+ label: 'Industry',
+ options: ['technology', 'finance', 'healthcare', 'retail'],
+ }),
+ annual_revenue: Field.currency({
+ label: 'Annual Revenue',
+ }),
+ primary_contact: Field.lookup({
+ label: 'Primary Contact',
+ object: 'contact',
+ }),
+ },
+});
+```
+
+This definition is **pure metadata**. It doesn't know:
+- Who can see this data
+- How to render a form
+- When to trigger workflows
+
+That's the job of the other layers.
+
+## Layer 2: ObjectOS (Control Protocol)
+
+**Role:** Manage the **Lifecycle** and **Governance** of requests.
+
+**Responsibilities:**
+- Authentication (who is this user?)
+- Authorization (can they access this field?)
+- Workflows and automations (what happens after save?)
+- Event processing (audit logs, notifications)
+- Multi-tenancy and data isolation
+
+**Key Principle:** ObjectOS acts as the **Gateway**. No layer can directly access the database; all requests must pass through the OS Kernel.
+
+### Example: Permission Rules
+
+```typescript
+// packages/crm/src/permissions/customer.permission.ts
+import { Permission } from '@objectstack/spec';
+
+export const CustomerPermission = Permission({
+ object: 'customer',
+ rules: [
+ {
+ profile: 'sales_rep',
+ crud: {
+ create: true,
+ read: true,
+ update: true,
+ delete: false, // Only managers can delete
+ },
+ fieldPermissions: {
+ annual_revenue: { read: true, edit: false }, // Read-only
+ },
+ },
+ {
+ profile: 'sales_manager',
+ crud: {
+ create: true,
+ read: true,
+ update: true,
+ delete: true,
+ },
+ },
+ ],
+});
+```
+
+### Example: Workflow Automation
+
+```typescript
+// packages/crm/src/workflows/customer.workflow.ts
+import { Workflow } from '@objectstack/spec';
+
+export const CustomerWorkflow = Workflow({
+ object: 'customer',
+ trigger: 'after_create',
+ conditions: [
+ { field: 'annual_revenue', operator: 'greaterThan', value: 1000000 },
+ ],
+ actions: [
+ {
+ type: 'assign_owner',
+ params: { owner: 'enterprise_sales_team' },
+ },
+ {
+ type: 'send_email',
+ params: {
+ template: 'high_value_customer_alert',
+ to: 'sales-leadership@company.com',
+ },
+ },
+ ],
+});
+```
+
+ObjectOS **orchestrates** these rules at runtime, independent of the data structure or UI.
+
+## Layer 3: ObjectUI (View Protocol)
+
+**Role:** Render the **Presentation** and handle **User Interaction**.
+
+**Responsibilities:**
+- App navigation and branding
+- List views (grid, kanban, calendar)
+- Form layouts (simple, tabbed, wizard)
+- Dashboards and reports
+- Actions and buttons
+
+**Key Principle:** ObjectUI is a **Rendering Engine**, not a hardcoded interface. It asks ObjectQL *"What is the schema?"* and dynamically generates the UI.
+
+### Example: List View
+
+```typescript
+// packages/crm/src/views/customer_list.view.ts
+import { ListView } from '@objectstack/spec';
+
+export const CustomerListView = ListView({
+ object: 'customer',
+ label: 'All Customers',
+ type: 'grid',
+ columns: [
+ { field: 'name', width: 200 },
+ { field: 'industry', width: 150 },
+ { field: 'annual_revenue', width: 150 },
+ { field: 'primary_contact', width: 180 },
+ ],
+ filters: [
+ { field: 'industry', operator: 'equals' },
+ { field: 'annual_revenue', operator: 'greaterThan' },
+ ],
+ defaultSort: { field: 'name', direction: 'asc' },
+});
+```
+
+### Example: Form View
+
+```typescript
+// packages/crm/src/views/customer_form.view.ts
+import { FormView } from '@objectstack/spec';
+
+export const CustomerFormView = FormView({
+ object: 'customer',
+ label: 'Customer Details',
+ type: 'tabbed',
+ tabs: [
+ {
+ label: 'Overview',
+ sections: [
+ {
+ label: 'Company Information',
+ fields: ['name', 'industry', 'annual_revenue'],
+ },
+ {
+ label: 'Contact',
+ fields: ['primary_contact'],
+ },
+ ],
+ },
+ {
+ label: 'Related Records',
+ sections: [
+ {
+ label: 'Opportunities',
+ component: 'related_list',
+ object: 'opportunity',
+ filter: { customer: '$recordId' },
+ },
+ ],
+ },
+ ],
+});
+```
+
+The UI doesn't "know" the field types. It asks ObjectQL for the schema and renders accordingly:
+- `Field.text` → Text input
+- `Field.select` → Dropdown
+- `Field.lookup` → Autocomplete lookup
+- `Field.currency` → Number input with currency formatting
+
+## How They Work Together
+
+Let's trace a **real-world scenario**: A sales rep creates a new high-value customer.
+
+### Step 1: User Action (ObjectUI)
+
+```
+User fills out the "Create Customer" form:
+- Name: "Acme Corp"
+- Industry: "Technology"
+- Annual Revenue: $5,000,000
+- Primary Contact: "John Doe"
+
+User clicks "Save"
+```
+
+### Step 2: UI Layer Sends Request
+
+```typescript
+// ObjectUI dispatches an action to ObjectOS
+const request = {
+ action: 'create',
+ object: 'customer',
+ data: {
+ name: 'Acme Corp',
+ industry: 'technology',
+ annual_revenue: 5000000,
+ primary_contact: 'contact_12345',
+ },
+};
+```
+
+### Step 3: ObjectOS Validates Permissions
+
+```typescript
+// Kernel checks: Does this user have permission?
+const user = await Auth.getCurrentUser();
+const canCreate = await Permission.check({
+ user,
+ object: 'customer',
+ operation: 'create',
+});
+
+if (!canCreate) {
+ throw new Error('Permission denied');
+}
+```
+
+### Step 4: ObjectOS Validates Data
+
+```typescript
+// Kernel asks ObjectQL: Is this data valid?
+const schema = ObjectQL.getSchema('customer');
+const validation = schema.validate(request.data);
+
+if (!validation.success) {
+ throw new ValidationError(validation.errors);
+}
+```
+
+### Step 5: ObjectQL Writes to Database
+
+```typescript
+// ObjectQL compiles the request into a database operation
+const driver = ObjectQL.getDriver(); // Postgres, MongoDB, etc.
+const result = await driver.insert('customer', {
+ name: 'Acme Corp',
+ industry: 'technology',
+ annual_revenue: 5000000,
+ primary_contact_id: 'contact_12345',
+});
+```
+
+### Step 6: ObjectOS Triggers Workflows
+
+```typescript
+// Kernel checks: Are there any workflows for this event?
+const workflows = Workflow.getTriggersFor('customer', 'after_create');
+
+for (const workflow of workflows) {
+ if (workflow.conditionsMet(result)) {
+ await workflow.execute(result);
+ }
+}
+
+// In this case:
+// ✅ Annual revenue > $1M
+// → Assign to enterprise sales team
+// → Send alert email to leadership
+```
+
+### Step 7: ObjectUI Updates Display
+
+```typescript
+// Kernel returns success response
+// UI optimistically updates the screen
+// UI shows toast notification: "Customer created successfully"
+// UI navigates to the new customer detail page
+```
+
+## The Full Stack in Action
+
+Here's how all three protocols collaborate for a **Kanban Board** feature:
+
+### 1. ObjectQL: Define the Data
+
+```typescript
+export const Opportunity = Object({
+ name: 'opportunity',
+ fields: {
+ title: Field.text({ required: true }),
+ stage: Field.select({
+ options: ['prospecting', 'qualification', 'proposal', 'closed_won'],
+ }),
+ amount: Field.currency(),
+ customer: Field.lookup({ object: 'customer' }),
+ },
+});
+```
+
+### 2. ObjectOS: Define Business Rules
+
+```typescript
+export const OpportunityWorkflow = Workflow({
+ object: 'opportunity',
+ trigger: 'field_update',
+ conditions: [
+ { field: 'stage', operator: 'equals', value: 'closed_won' },
+ ],
+ actions: [
+ { type: 'create_invoice', params: { object: 'invoice' } },
+ { type: 'send_notification', params: { to: 'sales_team' } },
+ ],
+});
+```
+
+### 3. ObjectUI: Define the Kanban View
+
+```typescript
+export const OpportunityKanban = ListView({
+ object: 'opportunity',
+ type: 'kanban',
+ groupBy: 'stage',
+ columns: [
+ { field: 'title' },
+ { field: 'amount' },
+ { field: 'customer' },
+ ],
+ enableDragDrop: true,
+});
+```
+
+### The Result
+
+When a user **drags an opportunity card** from "Proposal" to "Closed Won":
+
+1. **ObjectUI** captures the drag-drop event
+2. **ObjectOS** checks if the user has permission to update the `stage` field
+3. **ObjectQL** validates that `"closed_won"` is a valid option
+4. **ObjectQL** writes the update to the database
+5. **ObjectOS** triggers the workflow (create invoice, send notification)
+6. **ObjectUI** updates the kanban board to reflect the new state
+
+**All from metadata. Zero hardcoded logic.**
+
+## Benefits of the Three-Layer Architecture
+
+### 1. Technology Independence
+
+Swap implementations without breaking the system:
+
+```
+Same Metadata Definitions
+ ↓
+┌─────────┼─────────┐
+ObjectQL: │ │
+Postgres │ MongoDB
+ │
+ObjectOS: │
+Node.js │ Python
+ │
+ObjectUI: │
+React │ Flutter
+```
+
+### 2. Parallel Development
+
+Teams can work independently on each layer:
+
+- **Data Team:** Define objects in ObjectQL
+- **Backend Team:** Build workflows in ObjectOS
+- **Frontend Team:** Create views in ObjectUI
+
+All communicate through **protocol contracts**, not code dependencies.
+
+### 3. Incremental Migration
+
+Adopt ObjectStack gradually:
+
+- **Phase 1:** Use ObjectQL as an ORM replacement
+- **Phase 2:** Add ObjectOS for permissions and workflows
+- **Phase 3:** Build ObjectUI views to replace custom forms
+
+Each layer is independently useful.
+
+### 4. Testability
+
+Mock any layer for testing:
+
+```typescript
+// Test ObjectOS workflows without a real database
+const mockObjectQL = {
+ getSchema: () => CustomerSchema,
+ insert: jest.fn(),
+};
+
+// Test ObjectUI rendering without a real backend
+const mockObjectOS = {
+ checkPermission: () => true,
+ executeQuery: () => mockData,
+};
+```
+
+## Summary
+
+| Layer | Role | Knows About | Doesn't Know About |
+| :--- | :--- | :--- | :--- |
+| **ObjectQL** | Data structure & queries | Schema, fields, drivers | Users, permissions, UI |
+| **ObjectOS** | Runtime & governance | Auth, workflows, events | Data structure, UI layout |
+| **ObjectUI** | Presentation & interaction | Layout, navigation, actions | Business logic, data storage |
+
+The three protocols are **loosely coupled** but **tightly integrated**:
+- They communicate through **standard contracts** (Zod schemas)
+- They can be **swapped or upgraded** independently
+- They form a **complete system** when combined
+
+## Next Steps
+
+- [Object Model](/docs/01-core-concepts/object-model) - Deep dive into ObjectQL's universal object model
+- [ObjectQL Protocol](/docs/02-protocols/01-objectql) - Full data protocol specification
+- [ObjectOS Protocol](/docs/02-protocols/02-objectos) - Full control protocol specification
+- [ObjectUI Protocol](/docs/02-protocols/03-objectui) - Full view protocol specification
diff --git a/content/docs/02-protocols/01-objectql/index.mdx b/content/docs/02-protocols/01-objectql/index.mdx
new file mode 100644
index 000000000..858ff3318
--- /dev/null
+++ b/content/docs/02-protocols/01-objectql/index.mdx
@@ -0,0 +1,409 @@
+---
+title: ObjectQL Overview
+description: The database-agnostic data abstraction layer - Define once, run anywhere
+---
+
+import { Database, Zap, Shield, GitBranch, Target, CheckCircle } from 'lucide-react';
+
+# ObjectQL: The Data Protocol
+
+**ObjectQL** (Object Query Language) is ObjectStack's database-agnostic data abstraction layer. It provides a single, declarative way to define business data models, validation rules, and queries that work consistently across SQL, NoSQL, Graph, and Time-series databases.
+
+## The Core Problem
+
+Traditional software development chains you to specific database technologies:
+
+- **PostgreSQL → MongoDB Migration:** Rewrite thousands of SQL queries
+- **Schema Evolution:** Coordinate complex migration scripts across environments
+- **Multi-Database Systems:** Maintain separate codebases for each database
+- **Business Logic Scatter:** Validation rules duplicated in frontend, backend, and database triggers
+- **Vendor Lock-in:** Switching databases requires months of rewrites
+
+## The ObjectQL Solution
+
+
+ }
+ title="Write Once, Run Anywhere"
+ description="Define objects in .object.yml. ObjectStack compiles to PostgreSQL, MongoDB, Redis, or Excel—no code changes."
+ />
+ }
+ title="Schema as Code"
+ description="Version control your data model. Automatic migrations. Rollback schema changes like Git commits."
+ />
+ }
+ title="Type Safety"
+ description="Runtime validation with Zod schemas. TypeScript types auto-generated. Catch errors before production."
+ />
+ }
+ title="Business Semantics"
+ description="Fields encode intent: 'lookup' means relationship, 'formula' means calculated. Drivers optimize accordingly."
+ />
+
+
+## Architecture Overview
+
+```
+┌─────────────────────────────────────────────────────────────┐
+│ APPLICATION LAYER │
+│ ┌─────────────┐ ┌─────────────┐ ┌─────────────┐ │
+│ │ REST API │ │ GraphQL │ │ UI Forms │ │
+│ └──────┬──────┘ └──────┬──────┘ └──────┬──────┘ │
+└─────────┼─────────────────┼─────────────────┼───────────────┘
+ │ │ │
+ └─────────────────┼─────────────────┘
+ │
+ ┌─────────────────▼─────────────────┐
+ │ ObjectQL Runtime │
+ │ ┌──────────────────────────────┐ │
+ │ │ Query Planner & Optimizer │ │
+ │ └──────────┬───────────────────┘ │
+ │ │ │
+ │ ┌──────────▼───────────────────┐ │
+ │ │ Driver Layer (Adapters) │ │
+ │ └──┬────────┬────────┬─────────┘ │
+ └─────┼────────┼────────┼────────────┘
+ │ │ │
+ ┌────────▼──┐ ┌──▼─────┐ │ ┌──────────┐
+ │ PostgreSQL│ │MongoDB │ │ │ Redis │
+ └───────────┘ └────────┘ │ └──────────┘
+ │
+ ┌──────▼───┐
+ │ Excel │
+ └──────────┘
+```
+
+## Key Concepts
+
+### 1. Objects: Business Entities
+
+Objects are your business entities—not just database tables. They represent real-world concepts like `Customer`, `Order`, `Project`.
+
+```yaml
+# customer.object.yml
+name: customer
+label: Customer
+icon: standard:account
+enable:
+ audit: true # Track field history
+ full_text_search: true # Global search
+ api: true # REST/GraphQL endpoints
+fields:
+ company_name:
+ type: text
+ label: Company Name
+ required: true
+ industry:
+ type: select
+ options:
+ - { value: tech, label: Technology }
+ - { value: finance, label: Finance }
+```
+
+**What you get automatically:**
+- Database table/collection created
+- REST API endpoints: `GET/POST/PUT/DELETE /api/customer`
+- Admin UI with list view and form
+- Full-text search index
+- Field history tracking
+- TypeScript types
+
+### 2. Fields: Rich Type System
+
+ObjectQL provides 20+ field types that encode business semantics:
+
+| Field Type | Business Meaning | Example |
+|------------|------------------|---------|
+| `lookup` | Relationship | `account_id` references `account` |
+| `formula` | Calculated value | `total = quantity * price` |
+| `summary` | Aggregate children | `total_opportunities` counts child records |
+| `currency` | Money with exchange rates | `{amount: 1000, currency: 'USD'}` |
+| `address` | Geocoding & distance | `{street, city, lat, lng}` |
+
+See [Types Reference](/docs/02-protocols/01-objectql/types) for complete list.
+
+### 3. Query Language: Database-Agnostic AST
+
+Queries are expressed as **Abstract Syntax Trees (AST)**, not SQL strings:
+
+```typescript
+// TypeScript Query
+const query: Query = {
+ object: 'customer',
+ filters: [
+ ['industry', '=', 'tech'],
+ ['annual_revenue', '>', 1000000]
+ ],
+ fields: ['company_name', 'industry', 'owner.name'],
+ sort: [{ field: 'created_at', order: 'desc' }],
+ limit: 10
+};
+```
+
+**Runtime compilation to different databases:**
+
+```sql
+-- PostgreSQL (with JOIN)
+SELECT c.company_name, c.industry, u.name AS "owner.name"
+FROM customer c
+LEFT JOIN user u ON c.owner_id = u._id
+WHERE c.industry = 'tech' AND c.annual_revenue > 1000000
+ORDER BY c.created_at DESC
+LIMIT 10;
+```
+
+```javascript
+// MongoDB
+db.customer.aggregate([
+ {
+ $match: {
+ industry: 'tech',
+ annual_revenue: { $gt: 1000000 }
+ }
+ },
+ {
+ $lookup: {
+ from: 'user',
+ localField: 'owner_id',
+ foreignField: '_id',
+ as: 'owner'
+ }
+ },
+ { $sort: { created_at: -1 } },
+ { $limit: 10 }
+]);
+```
+
+### 4. Validation: Business Rules as Data
+
+Validation rules are declared alongside the schema:
+
+```yaml
+validation_rules:
+ - name: end_after_start
+ condition: "end_date < start_date"
+ message: "End date must be after start date"
+
+ - name: enterprise_requires_contract
+ condition: "account_type = 'Enterprise' AND contract_value = null"
+ message: "Enterprise accounts require contract value"
+```
+
+**Validation executes:**
+- Before database write (server-side)
+- In UI forms (compiled to JavaScript)
+- In API requests (REST/GraphQL)
+- In bulk imports (CSV, Excel)
+
+## Real-World Use Cases
+
+### Multi-Database Architecture
+
+**Scenario:** E-commerce platform with:
+- PostgreSQL: Transactional data (orders, payments)
+- MongoDB: Product catalog (flexible schemas)
+- Redis: Session cache
+- Elasticsearch: Product search
+
+**ObjectQL Solution:**
+```yaml
+# order.object.yml
+name: order
+datasource: postgres_main
+fields:
+ customer_id:
+ type: lookup
+ reference_to: customer # Also in PostgreSQL
+
+# product.object.yml
+name: product
+datasource: mongodb_catalog
+fields:
+ attributes:
+ type: json # Flexible product attributes
+```
+
+**Result:** One query API works across all databases:
+```typescript
+// Same code, different databases
+const orders = await ObjectQL.query({ object: 'order' });
+const products = await ObjectQL.query({ object: 'product' });
+```
+
+### Schema Evolution
+
+**Challenge:** Add a new field to `customer` object with 10M records.
+
+**Traditional Approach:**
+```sql
+-- Manual migration, downtime required
+ALTER TABLE customer ADD COLUMN credit_score INTEGER;
+-- Backfill historical data
+UPDATE customer SET credit_score = 0 WHERE credit_score IS NULL;
+```
+
+**ObjectQL Approach:**
+```yaml
+# Edit customer.object.yml
+fields:
+ credit_score:
+ type: number
+ default_value: 0
+ migration:
+ backfill: true # Automatically backfill existing records
+```
+
+```bash
+# Deploy (zero downtime)
+objectstack deploy --migrate
+```
+
+**What happens:**
+1. ObjectQL analyzes schema diff
+2. Generates database-specific migration
+3. Applies changes online (no downtime)
+4. Backfills data in background
+5. Updates API/UI automatically
+
+### Offline-First Mobile
+
+**Challenge:** Field sales app needs to work offline.
+
+**ObjectQL Solution:**
+```yaml
+# Same object definition
+name: opportunity
+enable:
+ offline_sync: true # Enable offline support
+```
+
+**Runtime:**
+- **Server:** PostgreSQL (production database)
+- **Mobile:** SQLite (on-device database)
+- **Sync:** Conflict resolution built into protocol
+
+**Code is identical:**
+```typescript
+// Works online or offline
+const opportunities = await ObjectQL.query({
+ object: 'opportunity',
+ filters: [['owner_id', '=', currentUser.id]]
+});
+```
+
+## Integration with Other Protocols
+
+ObjectQL is the foundation for other protocols:
+
+```
+ObjectQL (Data Layer)
+ ↓
+ ├→ ObjectUI (UI Protocol)
+ │ └→ Auto-generate forms, tables, dashboards
+ │
+ ├→ Permission Protocol
+ │ └→ Row-level security, field-level access
+ │
+ ├→ API Protocol
+ │ └→ REST/GraphQL endpoints
+ │
+ └→ Automation Protocol
+ └→ Triggers, workflows, scheduled jobs
+```
+
+## Performance Characteristics
+
+### Query Optimization
+
+ObjectQL analyzes queries and applies database-specific optimizations:
+
+- **Index Selection:** Chooses best index based on filters
+- **Join Strategy:** Hash join vs nested loop based on data size
+- **Projection Pushdown:** Only fetches requested fields
+- **Filter Pushdown:** Applies filters at database level
+
+**Example:**
+```typescript
+// This query
+const query = {
+ object: 'customer',
+ filters: [['industry', '=', 'tech']],
+ fields: ['company_name']
+};
+
+// Optimizes to (PostgreSQL)
+SELECT company_name FROM customer WHERE industry = 'tech';
+// NOT: SELECT * FROM customer WHERE industry = 'tech';
+```
+
+### Caching Strategy
+
+- **Schema Cache:** Object definitions cached in memory
+- **Query Plan Cache:** Compiled queries reused
+- **Result Cache:** Redis/Memcached for frequently accessed data
+
+## Security Model
+
+ObjectQL enforces security at the **data layer**, before queries execute:
+
+```typescript
+// User requests data
+const query = { object: 'account' };
+
+// ObjectQL applies permissions
+const securedQuery = {
+ object: 'account',
+ filters: [
+ ...query.filters,
+ ['owner_id', '=', currentUser.id] // Row-level security
+ ],
+ fields: query.fields.filter(f =>
+ currentUser.hasFieldAccess('account', f) // Field-level security
+ )
+};
+```
+
+See [Security Protocol](/docs/02-protocols/01-objectql/security) for details.
+
+## Learning Path
+
+**Start Here:**
+1. [Schema Definition](/docs/02-protocols/01-objectql/schema) - Learn to define objects and fields
+2. [Type System](/docs/02-protocols/01-objectql/types) - Understand field types and relationships
+
+**Intermediate:**
+3. [Query Syntax](/docs/02-protocols/01-objectql/query-syntax) - Master the query language
+4. [Security](/docs/02-protocols/01-objectql/security) - Implement access control
+
+**Advanced:**
+5. [Driver Protocol](/docs/specifications/data/architecture) - Build custom database drivers
+6. [Analytics Protocol](/docs/specifications/data/analytics-protocol) - OLAP queries
+
+## Technical References
+
+- **Zod Schemas:** `packages/spec/src/data/*.zod.ts`
+- **TypeScript Types:** `packages/spec/src/data/*.ts`
+- **Driver Implementations:** `packages/driver-*`
+
+## Next Steps
+
+
+
+
+
+
diff --git a/content/docs/02-protocols/01-objectql/meta.json b/content/docs/02-protocols/01-objectql/meta.json
new file mode 100644
index 000000000..70d7069d5
--- /dev/null
+++ b/content/docs/02-protocols/01-objectql/meta.json
@@ -0,0 +1,9 @@
+{
+ "title": "ObjectQL (Data Protocol)",
+ "pages": [
+ "schema",
+ "types",
+ "query-syntax",
+ "security"
+ ]
+}
diff --git a/content/docs/02-protocols/01-objectql/query-syntax.mdx b/content/docs/02-protocols/01-objectql/query-syntax.mdx
new file mode 100644
index 000000000..f493f3435
--- /dev/null
+++ b/content/docs/02-protocols/01-objectql/query-syntax.mdx
@@ -0,0 +1,952 @@
+---
+title: Query Syntax
+description: Database-agnostic query language with filters, joins, aggregations, and sorting
+---
+
+import { Search, Filter, GitMerge, BarChart } from 'lucide-react';
+
+# ObjectQL Query Syntax
+
+ObjectQL queries are expressed as **Abstract Syntax Trees (AST)** in JSON format. This enables database-agnostic querying—write once, compile to PostgreSQL, MongoDB, Redis, or any supported driver.
+
+## Query Philosophy
+
+**Traditional SQL:**
+```sql
+-- Tightly coupled to PostgreSQL
+SELECT c.name, c.email, a.company_name
+FROM contact c
+LEFT JOIN account a ON c.account_id = a.id
+WHERE c.is_active = true AND a.industry = 'tech'
+ORDER BY c.created_at DESC
+LIMIT 10;
+```
+
+**ObjectQL:**
+```typescript
+// Database-agnostic AST
+const query: Query = {
+ object: 'contact',
+ fields: ['name', 'email', 'account.company_name'],
+ filters: [
+ ['is_active', '=', true],
+ ['account.industry', '=', 'tech']
+ ],
+ sort: [{ field: 'created_at', order: 'desc' }],
+ limit: 10
+};
+```
+
+**Runtime compilation:**
+- PostgreSQL → Optimized SQL with JOINs
+- MongoDB → Aggregation pipeline with $lookup
+- Redis → Key pattern matching + Lua script
+- Excel → Filter + VLOOKUP formulas
+
+---
+
+## Query Structure
+
+### The Query AST
+
+```typescript
+interface Query {
+ object: string; // Target object (required)
+ fields?: string[]; // Projection (SELECT)
+ filters?: FilterNode[]; // Predicates (WHERE)
+ sort?: SortNode[]; // Ordering (ORDER BY)
+ limit?: number; // Max records (LIMIT)
+ offset?: number; // Skip records (OFFSET)
+ expand?: string[]; // Relationships (JOIN)
+ group_by?: string[]; // Grouping (GROUP BY)
+ having?: FilterNode[]; // Group filters (HAVING)
+}
+```
+
+---
+
+## 1. Basic Queries
+
+### Select All Records
+
+```typescript
+const customers = await ObjectQL.query({
+ object: 'customer'
+});
+
+// SQL: SELECT * FROM customer;
+// MongoDB: db.customer.find({})
+```
+
+### Select Specific Fields
+
+```typescript
+const customers = await ObjectQL.query({
+ object: 'customer',
+ fields: ['company_name', 'industry', 'annual_revenue']
+});
+
+// SQL: SELECT company_name, industry, annual_revenue FROM customer;
+// MongoDB: db.customer.find({}, { company_name: 1, industry: 1, annual_revenue: 1 })
+```
+
+### Limit and Offset
+
+```typescript
+const customers = await ObjectQL.query({
+ object: 'customer',
+ limit: 10,
+ offset: 20 // Skip first 20, get next 10
+});
+
+// SQL: SELECT * FROM customer LIMIT 10 OFFSET 20;
+// MongoDB: db.customer.find().skip(20).limit(10)
+```
+
+---
+
+## 2. Filtering
+
+Filters use a **tuple syntax**: `[field, operator, value]`
+
+### Simple Filters
+
+```typescript
+// Equality
+const query = {
+ object: 'customer',
+ filters: [
+ ['industry', '=', 'tech']
+ ]
+};
+
+// Not equal
+const query = {
+ object: 'customer',
+ filters: [
+ ['status', '!=', 'inactive']
+ ]
+};
+
+// Comparison
+const query = {
+ object: 'customer',
+ filters: [
+ ['annual_revenue', '>', 1000000]
+ ]
+};
+```
+
+**SQL compilation:**
+```sql
+WHERE industry = 'tech'
+WHERE status != 'inactive'
+WHERE annual_revenue > 1000000
+```
+
+### Supported Operators
+
+| Operator | Description | Example |
+|----------|-------------|---------|
+| `=` | Equal | `['status', '=', 'active']` |
+| `!=` | Not equal | `['status', '!=', 'closed']` |
+| `>` | Greater than | `['revenue', '>', 10000]` |
+| `>=` | Greater or equal | `['score', '>=', 80]` |
+| `<` | Less than | `['age', '<', 65]` |
+| `<=` | Less or equal | `['discount', '<=', 20]` |
+| `in` | In list | `['stage', 'in', ['proposal', 'negotiation']]` |
+| `not_in` | Not in list | `['status', 'not_in', ['deleted', 'archived']]` |
+| `contains` | String contains | `['name', 'contains', 'Inc']` |
+| `starts_with` | String starts with | `['email', 'starts_with', 'admin']` |
+| `ends_with` | String ends with | `['domain', 'ends_with', '.com']` |
+| `is_null` | Field is null | `['manager_id', 'is_null']` |
+| `is_not_null` | Field is not null | `['phone', 'is_not_null']` |
+| `between` | Range | `['created_at', 'between', ['2024-01-01', '2024-12-31']]` |
+
+### Multiple Filters (AND Logic)
+
+```typescript
+const query = {
+ object: 'opportunity',
+ filters: [
+ ['stage', '=', 'Closed Won'],
+ ['amount', '>', 50000],
+ ['close_date', '>=', '2024-01-01']
+ ]
+};
+
+// SQL: WHERE stage = 'Closed Won' AND amount > 50000 AND close_date >= '2024-01-01'
+```
+
+**Default:** Multiple filters are combined with **AND** logic.
+
+### OR Logic
+
+Use nested arrays with `'or'` operator:
+
+```typescript
+const query = {
+ object: 'contact',
+ filters: [
+ ['or',
+ ['title', 'contains', 'CEO'],
+ ['title', 'contains', 'President'],
+ ['title', 'contains', 'Founder']
+ ]
+ ]
+};
+
+// SQL: WHERE (title LIKE '%CEO%' OR title LIKE '%President%' OR title LIKE '%Founder%')
+```
+
+### Complex Logic (AND + OR)
+
+```typescript
+const query = {
+ object: 'opportunity',
+ filters: [
+ ['account.industry', '=', 'tech'], // AND (industry = tech)
+ ['or', // AND (
+ ['amount', '>', 100000], // amount > 100000
+ ['is_strategic', '=', true] // OR is_strategic = true
+ ] // )
+ ]
+};
+
+// SQL: WHERE account.industry = 'tech'
+// AND (amount > 100000 OR is_strategic = true)
+```
+
+### NOT Logic
+
+```typescript
+const query = {
+ object: 'customer',
+ filters: [
+ ['not',
+ ['status', 'in', ['deleted', 'suspended']]
+ ]
+ ]
+};
+
+// SQL: WHERE NOT (status IN ('deleted', 'suspended'))
+```
+
+### Date Filters
+
+```typescript
+// Specific date
+filters: [
+ ['created_at', '=', '2024-01-15']
+]
+
+// Date range
+filters: [
+ ['created_at', 'between', ['2024-01-01', '2024-12-31']]
+]
+
+// Relative dates (using formulas)
+filters: [
+ ['due_date', '<', '{{TODAY()}}'] // Past due
+]
+
+filters: [
+ ['created_at', '>', '{{TODAY() - 30}}'] // Last 30 days
+]
+```
+
+### Null Checks
+
+```typescript
+// Is null
+filters: [
+ ['manager_id', 'is_null']
+]
+
+// Is not null
+filters: [
+ ['phone', 'is_not_null']
+]
+
+// Has value (not null and not empty string)
+filters: [
+ ['email', '!=', null],
+ ['email', '!=', '']
+]
+```
+
+### Array Filters
+
+```typescript
+// Array contains value
+filters: [
+ ['tags', 'contains', 'important']
+]
+
+// Array contains any of values
+filters: [
+ ['tags', 'contains_any', ['urgent', 'high-priority']]
+]
+
+// Array contains all of values
+filters: [
+ ['tags', 'contains_all', ['customer', 'enterprise']]
+]
+
+// Array length
+filters: [
+ ['tags.length', '>', 3]
+]
+```
+
+### JSON Field Filters
+
+```typescript
+// Query nested JSON properties
+filters: [
+ ['metadata.color', '=', 'red'],
+ ['metadata.size', 'in', ['M', 'L', 'XL']]
+]
+
+// JSON path syntax (PostgreSQL JSONB)
+filters: [
+ ['attributes.dimensions.width', '>', 100]
+]
+```
+
+---
+
+## 3. Sorting
+
+### Single Field Sort
+
+```typescript
+const query = {
+ object: 'customer',
+ sort: [
+ { field: 'company_name', order: 'asc' }
+ ]
+};
+
+// SQL: ORDER BY company_name ASC
+```
+
+### Multiple Fields
+
+```typescript
+const query = {
+ object: 'opportunity',
+ sort: [
+ { field: 'priority', order: 'desc' },
+ { field: 'created_at', order: 'asc' }
+ ]
+};
+
+// SQL: ORDER BY priority DESC, created_at ASC
+```
+
+### Sort on Related Fields
+
+```typescript
+const query = {
+ object: 'contact',
+ sort: [
+ { field: 'account.company_name', order: 'asc' }
+ ]
+};
+
+// SQL: ORDER BY account.company_name ASC
+// (Requires JOIN with account table)
+```
+
+### Null Handling
+
+```typescript
+const query = {
+ object: 'task',
+ sort: [
+ { field: 'due_date', order: 'asc', nulls: 'last' }
+ ]
+};
+
+// SQL: ORDER BY due_date ASC NULLS LAST
+```
+
+**Null options:**
+- `first`: Null values appear first
+- `last`: Null values appear last
+
+---
+
+## 4. Relationships (Joins)
+
+### Basic Lookup
+
+```typescript
+const query = {
+ object: 'opportunity',
+ fields: ['name', 'amount', 'account.company_name'],
+ expand: ['account']
+};
+
+// Result:
+// [
+// {
+// name: 'Big Deal',
+// amount: 100000,
+// account: {
+// company_name: 'Acme Corp'
+// }
+// }
+// ]
+```
+
+**SQL compilation:**
+```sql
+SELECT
+ o.name,
+ o.amount,
+ a.company_name AS "account.company_name"
+FROM opportunity o
+LEFT JOIN account a ON o.account_id = a._id
+```
+
+### Multiple Relationships
+
+```typescript
+const query = {
+ object: 'opportunity',
+ fields: ['name', 'account.company_name', 'owner.name'],
+ expand: ['account', 'owner']
+};
+```
+
+### Deep Relationships
+
+```typescript
+const query = {
+ object: 'contact',
+ fields: ['name', 'account.owner.name'],
+ expand: ['account.owner'] // Nested lookup
+};
+
+// SQL: JOIN account, then JOIN user
+// MongoDB: Nested $lookup
+```
+
+### Filtering on Related Fields
+
+```typescript
+const query = {
+ object: 'opportunity',
+ filters: [
+ ['account.industry', '=', 'tech'],
+ ['account.annual_revenue', '>', 1000000]
+ ],
+ expand: ['account']
+};
+```
+
+### Child Records (Reverse Lookup)
+
+```typescript
+// Get account with all opportunities
+const query = {
+ object: 'account',
+ fields: ['company_name', 'opportunities'],
+ expand: ['opportunities'] // One-to-many
+};
+
+// Result:
+// {
+// company_name: 'Acme Corp',
+// opportunities: [
+// { name: 'Deal 1', amount: 50000 },
+// { name: 'Deal 2', amount: 75000 }
+// ]
+// }
+```
+
+---
+
+## 5. Aggregations
+
+### Count
+
+```typescript
+const count = await ObjectQL.count({
+ object: 'customer',
+ filters: [
+ ['industry', '=', 'tech']
+ ]
+});
+
+// SQL: SELECT COUNT(*) FROM customer WHERE industry = 'tech'
+// Result: 42
+```
+
+### Group By
+
+```typescript
+const query = {
+ object: 'opportunity',
+ group_by: ['stage'],
+ aggregate: {
+ count: { function: 'count' },
+ total_amount: { function: 'sum', field: 'amount' }
+ }
+};
+
+// Result:
+// [
+// { stage: 'Prospecting', count: 10, total_amount: 500000 },
+// { stage: 'Qualification', count: 5, total_amount: 250000 }
+// ]
+```
+
+**SQL compilation:**
+```sql
+SELECT
+ stage,
+ COUNT(*) as count,
+ SUM(amount) as total_amount
+FROM opportunity
+GROUP BY stage
+```
+
+### Aggregate Functions
+
+```typescript
+const query = {
+ object: 'opportunity',
+ aggregate: {
+ count: { function: 'count' },
+ total: { function: 'sum', field: 'amount' },
+ average: { function: 'avg', field: 'amount' },
+ min: { function: 'min', field: 'amount' },
+ max: { function: 'max', field: 'amount' }
+ }
+};
+
+// Result:
+// {
+// count: 100,
+// total: 5000000,
+// average: 50000,
+// min: 10000,
+// max: 500000
+// }
+```
+
+### Group By Multiple Fields
+
+```typescript
+const query = {
+ object: 'opportunity',
+ group_by: ['stage', 'owner.name'],
+ aggregate: {
+ count: { function: 'count' },
+ total: { function: 'sum', field: 'amount' }
+ }
+};
+```
+
+### HAVING Clause
+
+Filter groups after aggregation:
+
+```typescript
+const query = {
+ object: 'opportunity',
+ group_by: ['account_id'],
+ aggregate: {
+ total: { function: 'sum', field: 'amount' }
+ },
+ having: [
+ ['total', '>', 1000000] // Only accounts with >$1M pipeline
+ ]
+};
+
+// SQL: HAVING SUM(amount) > 1000000
+```
+
+---
+
+## 6. Advanced Queries
+
+### Distinct Values
+
+```typescript
+const industries = await ObjectQL.distinct({
+ object: 'account',
+ field: 'industry'
+});
+
+// SQL: SELECT DISTINCT industry FROM account
+// Result: ['tech', 'finance', 'healthcare']
+```
+
+### Exists (Subquery)
+
+```typescript
+const query = {
+ object: 'account',
+ filters: [
+ ['exists', {
+ object: 'opportunity',
+ filters: [
+ ['account_id', '=', '{{parent._id}}'],
+ ['stage', '=', 'Closed Won']
+ ]
+ }]
+ ]
+};
+
+// SQL: WHERE EXISTS (
+// SELECT 1 FROM opportunity
+// WHERE opportunity.account_id = account._id
+// AND opportunity.stage = 'Closed Won'
+// )
+```
+
+### Not Exists
+
+```typescript
+const query = {
+ object: 'account',
+ filters: [
+ ['not_exists', {
+ object: 'opportunity',
+ filters: [
+ ['account_id', '=', '{{parent._id}}']
+ ]
+ }]
+ ]
+};
+
+// Find accounts with no opportunities
+```
+
+### Full-Text Search
+
+```typescript
+const query = {
+ object: 'article',
+ search: 'ObjectStack tutorial',
+ search_fields: ['title', 'content', 'tags']
+};
+
+// PostgreSQL: Uses tsvector/tsquery
+// MongoDB: Uses $text index
+// Elasticsearch: Uses match query
+```
+
+### Geospatial Queries
+
+```typescript
+// Find stores within 10 miles
+const query = {
+ object: 'store',
+ filters: [
+ ['location', 'near', {
+ latitude: 37.7749,
+ longitude: -122.4194,
+ distance: 10,
+ unit: 'miles'
+ }]
+ ]
+};
+
+// PostgreSQL: Uses ST_Distance
+// MongoDB: Uses $near
+```
+
+### Case-Insensitive Search
+
+```typescript
+const query = {
+ object: 'customer',
+ filters: [
+ ['company_name', 'icontains', 'acme'] // Case-insensitive
+ ]
+};
+
+// SQL: WHERE LOWER(company_name) LIKE LOWER('%acme%')
+```
+
+### Regular Expression
+
+```typescript
+const query = {
+ object: 'user',
+ filters: [
+ ['email', 'regex', '^admin@.*\\.com$']
+ ]
+};
+
+// PostgreSQL: WHERE email ~ '^admin@.*\.com$'
+// MongoDB: { email: { $regex: /^admin@.*\.com$/ } }
+```
+
+---
+
+## 7. Query Optimization
+
+### Index Hints
+
+```typescript
+const query = {
+ object: 'customer',
+ filters: [
+ ['email', '=', 'john@example.com']
+ ],
+ use_index: 'idx_email' // Force specific index
+};
+```
+
+### Projection Pushdown
+
+ObjectQL automatically optimizes field selection:
+
+```typescript
+// You write:
+const query = {
+ object: 'customer',
+ fields: ['company_name', 'email']
+};
+
+// ObjectQL compiles to:
+// SELECT company_name, email FROM customer
+// NOT: SELECT * FROM customer (wasteful)
+```
+
+### Filter Pushdown
+
+Filters applied at database level, not in application:
+
+```typescript
+const query = {
+ object: 'opportunity',
+ filters: [['amount', '>', 50000]],
+ expand: ['account']
+};
+
+// SQL: WHERE amount > 50000
+// Filter runs BEFORE join (better performance)
+```
+
+### Query Plan Analysis
+
+```typescript
+const plan = await ObjectQL.explain({
+ object: 'customer',
+ filters: [['industry', '=', 'tech']]
+});
+
+// Returns database-specific execution plan
+// PostgreSQL: EXPLAIN output
+// MongoDB: explain() results
+```
+
+---
+
+## 8. Pagination
+
+### Offset-Based Pagination
+
+```typescript
+// Page 1 (records 0-9)
+const page1 = await ObjectQL.query({
+ object: 'customer',
+ limit: 10,
+ offset: 0
+});
+
+// Page 2 (records 10-19)
+const page2 = await ObjectQL.query({
+ object: 'customer',
+ limit: 10,
+ offset: 10
+});
+```
+
+**Drawback:** Slow for large offsets (database still scans all skipped rows).
+
+### Cursor-Based Pagination
+
+```typescript
+// First page
+const result = await ObjectQL.query({
+ object: 'customer',
+ limit: 10,
+ sort: [{ field: '_id', order: 'asc' }]
+});
+
+// Next page (use last _id as cursor)
+const nextResult = await ObjectQL.query({
+ object: 'customer',
+ filters: [
+ ['_id', '>', result[result.length - 1]._id]
+ ],
+ limit: 10,
+ sort: [{ field: '_id', order: 'asc' }]
+});
+```
+
+**Advantage:** Consistent performance regardless of page depth.
+
+---
+
+## 9. Query Shortcuts
+
+ObjectQL provides convenience methods for common patterns:
+
+### Find by ID
+
+```typescript
+const customer = await ObjectQL.findOne('customer', '123');
+
+// Equivalent to:
+await ObjectQL.query({
+ object: 'customer',
+ filters: [['_id', '=', '123']],
+ limit: 1
+});
+```
+
+### Find by Unique Field
+
+```typescript
+const customer = await ObjectQL.findBy('customer', { email: 'john@example.com' });
+
+// Equivalent to:
+await ObjectQL.query({
+ object: 'customer',
+ filters: [['email', '=', 'john@example.com']],
+ limit: 1
+});
+```
+
+### Find or Create
+
+```typescript
+const customer = await ObjectQL.findOrCreate('customer',
+ { email: 'john@example.com' }, // Search criteria
+ { company_name: 'Acme Corp' } // Default values if creating
+);
+```
+
+---
+
+## 10. Error Handling
+
+### Invalid Query
+
+```typescript
+try {
+ await ObjectQL.query({
+ object: 'customer',
+ filters: [
+ ['invalid_field', '=', 'value'] // Field doesn't exist
+ ]
+ });
+} catch (error) {
+ // QueryValidationError: Field 'invalid_field' does not exist on object 'customer'
+}
+```
+
+### Security Violations
+
+```typescript
+try {
+ await ObjectQL.query({
+ object: 'account',
+ filters: [['owner_id', '!=', currentUser.id]]
+ });
+} catch (error) {
+ // PermissionError: Access denied to object 'account'
+}
+```
+
+---
+
+## Real-World Examples
+
+### CRM: Open Opportunities
+
+```typescript
+const openOpportunities = await ObjectQL.query({
+ object: 'opportunity',
+ filters: [
+ ['stage', 'not_in', ['Closed Won', 'Closed Lost']],
+ ['owner_id', '=', currentUser.id]
+ ],
+ sort: [
+ { field: 'amount', order: 'desc' }
+ ],
+ fields: ['name', 'amount', 'close_date', 'account.company_name'],
+ expand: ['account']
+});
+```
+
+### E-Commerce: Product Search
+
+```typescript
+const products = await ObjectQL.query({
+ object: 'product',
+ search: searchTerm,
+ filters: [
+ ['is_active', '=', true],
+ ['inventory_qty', '>', 0],
+ ['category_id', 'in', selectedCategories],
+ ['price', 'between', [minPrice, maxPrice]]
+ ],
+ sort: [
+ { field: 'popularity_score', order: 'desc' }
+ ],
+ limit: 20
+});
+```
+
+### Analytics: Revenue by Month
+
+```typescript
+const monthlyRevenue = await ObjectQL.query({
+ object: 'order',
+ group_by: ['DATE_TRUNC(created_at, month)'],
+ aggregate: {
+ revenue: { function: 'sum', field: 'total_amount' },
+ order_count: { function: 'count' },
+ avg_order: { function: 'avg', field: 'total_amount' }
+ },
+ filters: [
+ ['status', '=', 'completed'],
+ ['created_at', '>=', '2024-01-01']
+ ],
+ sort: [
+ { field: 'created_at', order: 'asc' }
+ ]
+});
+```
+
+---
+
+## Next Steps
+
+
+
+
+
+
diff --git a/content/docs/02-protocols/01-objectql/schema.mdx b/content/docs/02-protocols/01-objectql/schema.mdx
new file mode 100644
index 000000000..626df0b5d
--- /dev/null
+++ b/content/docs/02-protocols/01-objectql/schema.mdx
@@ -0,0 +1,906 @@
+---
+title: Schema Definition
+description: The complete specification for defining objects, fields, and relationships in ObjectQL
+---
+
+import { FileCode, Database, Layers, Package } from 'lucide-react';
+
+# Schema Definition
+
+In ObjectStack, **data structure is configuration, not code**. The Schema Definition Protocol governs how you declare your data model using declarative `.object.yml` files.
+
+> **Single Source of Truth:** This schema drives database DDL, API generation, UI form layouts, permission scopes, and validation rules.
+
+## File Structure
+
+### The .object.yml Convention
+
+Each business entity is defined in a separate file:
+
+```
+my-app/
+├── objects/
+│ ├── customer.object.yml # Customer entity
+│ ├── order.object.yml # Order entity
+│ ├── product.object.yml # Product entity
+│ └── invoice.object.yml # Invoice entity
+├── objectstack.config.ts # Package manifest
+└── package.json
+```
+
+**Why separate files?**
+- Version control: Git shows clear diffs when objects change
+- Team collaboration: Developers can work on different objects simultaneously
+- Code generation: Each file → Database table + API + UI
+- Deployment: Selective schema deployment (only changed objects)
+
+### Alternative Formats
+
+ObjectStack supports multiple schema formats:
+
+```yaml
+# YAML (Recommended for readability)
+name: customer
+label: Customer
+
+# JSON (Machine-generated)
+{ "name": "customer", "label": "Customer" }
+
+# TypeScript (Programmatic)
+export default defineObject({
+ name: 'customer',
+ label: 'Customer'
+});
+```
+
+## Object Definition
+
+### Minimal Example
+
+```yaml
+name: project
+label: Project
+```
+
+This 2-line definition creates:
+- Database table `project` with system fields (`_id`, `created_at`, `updated_at`)
+- REST API: `GET/POST/PUT/DELETE /api/project`
+- Admin UI: List view + Form
+- TypeScript types
+
+### Complete Example
+
+```yaml
+name: project
+label: Project
+plural_label: Projects
+description: "A business project or initiative"
+icon: standard:case
+color: "#4A90E2"
+bucket: main
+datasource: postgres_primary
+enable:
+ audit: true
+ workflow: true
+ full_text_search: true
+ api: true
+ offline_sync: true
+fields:
+ name:
+ type: text
+ label: Project Name
+ required: true
+ max_length: 255
+ status:
+ type: select
+ label: Status
+ options:
+ - { value: draft, label: Draft }
+ - { value: active, label: Active }
+ - { value: completed, label: Completed }
+ default_value: draft
+ budget:
+ type: currency
+ label: Budget
+ scale: 2
+ precision: 18
+ account_id:
+ type: lookup
+ label: Account
+ reference_to: account
+ required: true
+validation_rules:
+ - name: budget_positive
+ condition: "budget < 0"
+ message: "Budget must be positive"
+```
+
+### Object Properties Reference
+
+| Property | Type | Required | Description |
+|----------|------|----------|-------------|
+| `name` | `string` | ✅ | **Machine name.** Must be `snake_case`, unique across the system. |
+| `label` | `string` | ✅ | **Display name** for UI (singular form). |
+| `plural_label` | `string` | ❌ | Plural form for lists. Defaults to `label + "s"`. |
+| `description` | `string` | ❌ | Human-readable description for documentation. |
+| `icon` | `string` | ❌ | Icon identifier (e.g., `standard:case`, `custom:project`). |
+| `color` | `string` | ❌ | Hex color for UI theming. |
+| `bucket` | `string` | ❌ | Database shard/bucket key for horizontal scaling. |
+| `datasource` | `string` | ❌ | External datasource ID. If omitted, uses default database. |
+| `enable` | `object` | ❌ | Feature flags (see [Capabilities](#capabilities)). |
+| `fields` | `object` | ❌ | Field definitions (see [Field Definition](#field-definition)). |
+| `validation_rules` | `array` | ❌ | Business validation rules (see [Validation](#validation-rules)). |
+| `triggers` | `array` | ❌ | Database triggers (before/after insert/update/delete). |
+| `indexes` | `array` | ❌ | Composite indexes for query optimization. |
+
+### Naming Conventions
+
+**Object Names (Machine Identifiers):**
+- **Format:** `snake_case` (lowercase, underscores)
+- **Pattern:** `/^[a-z][a-z0-9_]*$/`
+- **Examples:** ✅ `customer`, `project_task`, `sales_order`
+- **Invalid:** ❌ `Customer`, `projectTask`, `123project`
+
+**Object Labels (Display Names):**
+- **Format:** Title Case, human-readable
+- **Examples:** ✅ `Customer`, `Project Task`, `Sales Order`
+
+### Capabilities
+
+The `enable` object controls which features are active:
+
+```yaml
+enable:
+ # Data Management
+ audit: true # Track field history (who changed what, when)
+ full_text_search: true # Index for global search
+ versioning: true # Keep record versions for rollback
+
+ # API & Integration
+ api: true # Generate REST/GraphQL endpoints
+ webhooks: true # Allow outbound webhooks
+
+ # Business Logic
+ workflow: true # Enable process builder/flows
+ approval: true # Approval processes
+
+ # Advanced Features
+ offline_sync: true # Mobile offline support
+ realtime: true # WebSocket subscriptions
+ ai_enabled: true # AI features (sentiment, summarization)
+```
+
+**Performance Impact:**
+- `audit: true` adds ~15% write overhead (additional inserts to audit table)
+- `full_text_search: true` adds search indexes (~10% storage overhead)
+- `versioning: true` stores full record copies on each update
+
+**When to enable:**
+- **Audit:** Regulated industries (finance, healthcare), compliance requirements
+- **Full-text search:** User-facing search features
+- **Versioning:** Critical data that may need rollback (legal contracts, pricing)
+
+## Field Definition
+
+Fields are the columns/attributes of your object. Each field has a type and configuration.
+
+### Basic Field Structure
+
+```yaml
+fields:
+ field_name:
+ type: text # Field type (required)
+ label: Field Label # Display label (required)
+ required: false # Validation
+ default_value: null # Default when creating records
+ help_text: "Helper text for users"
+ placeholder: "Enter value..."
+```
+
+### Field Properties Reference
+
+| Property | Type | Applies To | Description |
+|----------|------|------------|-------------|
+| `type` | `string` | All | **Required.** Field type (see [Types](/docs/02-protocols/01-objectql/types)). |
+| `label` | `string` | All | **Required.** Display label in UI. |
+| `required` | `boolean` | All | Validation: Field must have a value. |
+| `unique` | `boolean` | All | Enforce uniqueness at database level. |
+| `index` | `boolean` | All | Create database index for faster queries. |
+| `default_value` | `any` | All | Default value when creating new records. |
+| `help_text` | `string` | All | Tooltip text in forms. |
+| `placeholder` | `string` | Input fields | Placeholder text in input fields. |
+| `read_only` | `boolean` | All | Field cannot be edited after creation. |
+| `deprecated` | `boolean` | All | Mark field as deprecated (still queryable). |
+| `max_length` | `number` | `text`, `textarea` | Maximum character length. |
+| `min_value` | `number` | `number`, `currency` | Minimum numeric value. |
+| `max_value` | `number` | `number`, `currency` | Maximum numeric value. |
+| `scale` | `number` | `number`, `currency` | Decimal places (e.g., `2` for cents). |
+| `precision` | `number` | `number`, `currency` | Total digits (including scale). |
+| `options` | `array` | `select`, `radio` | List of valid values. |
+| `multiple` | `boolean` | `select`, `lookup` | Allow multiple selections. |
+| `reference_to` | `string` | `lookup`, `master_detail` | Target object for relationships. |
+| `formula` | `string` | `formula` | Calculation expression. |
+| `summary_type` | `string` | `summary` | Aggregation type (`count`, `sum`, `min`, `max`). |
+
+### System Fields
+
+Every object automatically includes system fields:
+
+```yaml
+# Auto-generated (not defined in .object.yml)
+_id:
+ type: id
+ label: Record ID
+ read_only: true
+
+created_at:
+ type: datetime
+ label: Created At
+ read_only: true
+
+updated_at:
+ type: datetime
+ label: Updated At
+ read_only: true
+
+created_by:
+ type: lookup
+ reference_to: user
+ label: Created By
+ read_only: true
+
+updated_by:
+ type: lookup
+ reference_to: user
+ label: Updated By
+ read_only: true
+```
+
+**Customizing system fields:**
+```yaml
+# Override system field behavior
+fields:
+ created_at:
+ index: true # Add index to created_at
+```
+
+### Field Examples by Type
+
+#### Text Fields
+
+```yaml
+company_name:
+ type: text
+ label: Company Name
+ required: true
+ max_length: 255
+ index: true
+
+description:
+ type: textarea
+ label: Description
+ max_length: 5000
+ rows: 10
+
+bio:
+ type: html
+ label: Biography
+ sanitize: true # Remove dangerous HTML tags
+```
+
+#### Numeric Fields
+
+```yaml
+quantity:
+ type: number
+ label: Quantity
+ min_value: 0
+ max_value: 9999
+ default_value: 1
+
+discount_rate:
+ type: percent
+ label: Discount
+ scale: 2
+ min_value: 0
+ max_value: 100
+
+revenue:
+ type: currency
+ label: Annual Revenue
+ scale: 2
+ precision: 18
+ default_value: { amount: 0, currency: 'USD' }
+```
+
+#### Date/Time Fields
+
+```yaml
+start_date:
+ type: date
+ label: Start Date
+ required: true
+
+due_datetime:
+ type: datetime
+ label: Due Date & Time
+ default_value: "{{NOW() + 7}}" # 7 days from now
+```
+
+#### Boolean Fields
+
+```yaml
+is_active:
+ type: boolean
+ label: Active
+ default_value: true
+
+email_opt_in:
+ type: checkbox
+ label: Subscribe to Newsletter
+ default_value: false
+```
+
+#### Selection Fields
+
+```yaml
+priority:
+ type: select
+ label: Priority
+ options:
+ - { value: low, label: Low, color: green }
+ - { value: medium, label: Medium, color: yellow }
+ - { value: high, label: High, color: orange }
+ - { value: critical, label: Critical, color: red }
+ default_value: medium
+
+tags:
+ type: multi_select
+ label: Tags
+ options:
+ - { value: customer, label: Customer }
+ - { value: partner, label: Partner }
+ - { value: vendor, label: Vendor }
+ multiple: true
+```
+
+#### Relationship Fields
+
+```yaml
+account_id:
+ type: lookup
+ label: Account
+ reference_to: account
+ required: true
+ reference_filters:
+ - ['is_active', '=', true] # Only show active accounts
+
+project_id:
+ type: master_detail
+ label: Project
+ reference_to: project
+ cascade_delete: true # Delete tasks when project is deleted
+```
+
+## Validation Rules
+
+Validation rules enforce business logic at the data layer:
+
+```yaml
+validation_rules:
+ # Simple comparison
+ - name: end_after_start
+ condition: "end_date < start_date"
+ message: "End date must be after start date"
+ severity: error
+
+ # Cross-field validation
+ - name: discount_requires_approval
+ condition: "discount > 20 AND approved_by = null"
+ message: "Discounts over 20% require manager approval"
+ severity: error
+
+ # Conditional validation
+ - name: enterprise_contract_required
+ condition: "account_type = 'Enterprise' AND contract_value = null"
+ message: "Enterprise accounts must have a contract value"
+ severity: error
+ active: true
+
+ # Warning (non-blocking)
+ - name: budget_threshold_warning
+ condition: "budget > 1000000"
+ message: "Large budget. Please verify approval."
+ severity: warning
+```
+
+### Validation Formula Syntax
+
+Formulas use Excel-like syntax:
+
+**Operators:**
+- Comparison: `=`, `!=`, `>`, `<`, `>=`, `<=`
+- Logical: `AND`, `OR`, `NOT`
+- Arithmetic: `+`, `-`, `*`, `/`, `^` (power)
+- String: `&` (concatenate)
+
+**Functions:**
+- `ISBLANK(field)`: Check if field is empty
+- `LEN(field)`: String length
+- `CONTAINS(field, "text")`: Substring check
+- `REGEX(field, "pattern")`: Regular expression
+- `TODAY()`: Current date
+- `NOW()`: Current datetime
+
+**Examples:**
+```yaml
+# Date validation
+"start_date > TODAY()"
+
+# String validation
+"LEN(email) > 0 AND CONTAINS(email, '@')"
+
+# Null check
+"NOT(ISBLANK(manager_id))"
+
+# Complex logic
+"(status = 'Closed' AND close_date != null) OR status != 'Closed'"
+```
+
+## Indexes
+
+Optimize query performance with indexes:
+
+```yaml
+indexes:
+ # Single-field index (also via field.index: true)
+ - fields: [email]
+ unique: true
+
+ # Composite index
+ - fields: [account_id, status]
+ name: idx_account_status
+
+ # Full-text search index
+ - fields: [name, description]
+ type: fulltext
+
+ # Geospatial index
+ - fields: [location]
+ type: geo
+```
+
+**Index Strategy:**
+- **Add indexes for:**
+ - Foreign keys (lookup fields)
+ - Fields used in `WHERE` clauses
+ - Fields used in `ORDER BY`
+ - Unique constraints
+- **Avoid indexes for:**
+ - Low-cardinality fields (boolean, status with 2-3 values)
+ - Fields that change frequently
+ - Large text fields (use full-text search instead)
+
+## Triggers
+
+Execute code on data changes:
+
+```yaml
+triggers:
+ # Before insert
+ - event: before_insert
+ handler: set_owner
+ code: |
+ record.owner_id = context.user.id;
+
+ # After insert
+ - event: after_insert
+ handler: send_welcome_email
+ async: true
+ code: |
+ await emailService.send({
+ to: record.email,
+ template: 'welcome'
+ });
+
+ # Before update
+ - event: before_update
+ handler: validate_status_change
+ condition: "old.status != new.status"
+ code: |
+ if (old.status === 'Closed' && new.status !== 'Closed') {
+ throw new Error('Cannot reopen closed records');
+ }
+```
+
+**Event Types:**
+- `before_insert`: Before creating a record
+- `after_insert`: After creating a record
+- `before_update`: Before updating a record
+- `after_update`: After updating a record
+- `before_delete`: Before deleting a record
+- `after_delete`: After deleting a record
+
+## Advanced Features
+
+### Inheritance (Mixins)
+
+Reuse field definitions across objects:
+
+```yaml
+# mixins/auditable.mixin.yml
+fields:
+ created_at:
+ type: datetime
+ label: Created At
+ read_only: true
+ updated_at:
+ type: datetime
+ label: Updated At
+ read_only: true
+
+# customer.object.yml
+name: customer
+extends: [auditable] # Inherit fields from mixin
+fields:
+ company_name:
+ type: text
+```
+
+### Polymorphic References
+
+Reference multiple object types:
+
+```yaml
+# activity.object.yml
+parent_id:
+ type: polymorphic
+ label: Related To
+ reference_to: [account, contact, opportunity]
+```
+
+Query polymorphic fields:
+```typescript
+const activity = await ObjectQL.findOne('activity', id);
+// activity.parent_id = { _id: '123', _type: 'account' }
+```
+
+### Computed Fields (Virtual)
+
+Fields calculated at query time (not stored):
+
+```yaml
+full_name:
+ type: formula
+ label: Full Name
+ formula: "first_name & ' ' & last_name"
+ virtual: true # Not stored in database
+```
+
+### Multi-Tenant Schemas
+
+Isolate data by tenant:
+
+```yaml
+name: customer
+tenant_scope: true # Automatically filter by tenant_id
+fields:
+ tenant_id:
+ type: lookup
+ reference_to: tenant
+ required: true
+ default_value: "{{CURRENT_TENANT()}}"
+```
+
+**Runtime behavior:**
+```typescript
+// User in Tenant A queries customers
+const customers = await ObjectQL.query({ object: 'customer' });
+
+// ObjectQL automatically adds: WHERE tenant_id = 'tenant_a'
+// User CANNOT access Tenant B's data
+```
+
+## Schema Versioning
+
+### Migration Strategy
+
+When schemas change, ObjectQL generates migrations:
+
+**Before:**
+```yaml
+# v1: customer.object.yml
+fields:
+ name:
+ type: text
+```
+
+**After:**
+```yaml
+# v2: customer.object.yml
+fields:
+ first_name:
+ type: text
+ migration:
+ from: name
+ transform: "SPLIT(name, ' ')[0]"
+
+ last_name:
+ type: text
+ migration:
+ from: name
+ transform: "SPLIT(name, ' ')[1]"
+```
+
+**Generated migration:**
+```sql
+-- PostgreSQL
+ALTER TABLE customer ADD COLUMN first_name TEXT;
+ALTER TABLE customer ADD COLUMN last_name TEXT;
+
+UPDATE customer SET
+ first_name = SPLIT_PART(name, ' ', 1),
+ last_name = SPLIT_PART(name, ' ', 2);
+
+ALTER TABLE customer DROP COLUMN name;
+```
+
+### Deployment Workflow
+
+```bash
+# 1. Detect schema changes
+objectstack diff
+
+# 2. Generate migration plan
+objectstack migrate:plan
+
+# 3. Review migration SQL
+cat .objectstack/migrations/001_add_customer_name.sql
+
+# 4. Apply migration
+objectstack deploy --migrate
+
+# 5. Rollback if needed
+objectstack migrate:rollback
+```
+
+## Best Practices
+
+### Naming Conventions
+
+```yaml
+# ✅ Good
+name: project_task
+fields:
+ assigned_to_id: # Suffix _id for lookups
+ type: lookup
+ is_active: # Prefix is_ for booleans
+ type: boolean
+ total_amount: # Descriptive, specific
+ type: currency
+
+# ❌ Bad
+name: ProjectTask # Not snake_case
+fields:
+ user: # Ambiguous (assigned? created?)
+ type: lookup
+ active: # Missing is_ prefix
+ type: boolean
+ amount: # Too generic
+ type: currency
+```
+
+### Field Organization
+
+Group related fields:
+
+```yaml
+fields:
+ # Identity
+ name:
+ type: text
+ description:
+ type: textarea
+
+ # Relationships
+ account_id:
+ type: lookup
+ owner_id:
+ type: lookup
+
+ # Status & Lifecycle
+ status:
+ type: select
+ stage:
+ type: select
+
+ # Financial
+ budget:
+ type: currency
+ actual_cost:
+ type: currency
+```
+
+### Performance Optimization
+
+```yaml
+# Index frequently queried fields
+email:
+ type: text
+ index: true
+ unique: true
+
+# Use appropriate field types
+status:
+ type: select # Better than text for fixed values
+ options: [...]
+
+# Avoid large text in main table
+file_content:
+ type: text
+ store: blob_storage # Store in separate table/S3
+```
+
+## Examples: Real-World Schemas
+
+### CRM: Account Object
+
+```yaml
+name: account
+label: Account
+plural_label: Accounts
+icon: standard:account
+enable:
+ audit: true
+ full_text_search: true
+ api: true
+
+fields:
+ # Company Information
+ company_name:
+ type: text
+ label: Company Name
+ required: true
+ max_length: 255
+ index: true
+
+ website:
+ type: url
+ label: Website
+
+ industry:
+ type: select
+ label: Industry
+ options:
+ - { value: tech, label: Technology }
+ - { value: finance, label: Financial Services }
+ - { value: healthcare, label: Healthcare }
+ - { value: retail, label: Retail }
+
+ # Contact Info
+ billing_address:
+ type: address
+ label: Billing Address
+
+ phone:
+ type: phone
+ label: Phone
+
+ # Financial
+ annual_revenue:
+ type: currency
+ label: Annual Revenue
+ scale: 2
+ precision: 18
+
+ # Relationships
+ owner_id:
+ type: lookup
+ label: Account Owner
+ reference_to: user
+ required: true
+
+ parent_account_id:
+ type: lookup
+ label: Parent Account
+ reference_to: account
+
+ # Metrics (Computed)
+ total_opportunities:
+ type: summary
+ label: Total Opportunities
+ summary_object: opportunity
+ summary_type: count
+
+ total_opportunity_value:
+ type: summary
+ label: Total Opportunity Value
+ summary_object: opportunity
+ summary_field: amount
+ summary_type: sum
+
+validation_rules:
+ - name: enterprise_revenue_required
+ condition: "industry = 'finance' AND annual_revenue = null"
+ message: "Financial services accounts must have revenue"
+```
+
+### E-Commerce: Product Object
+
+```yaml
+name: product
+label: Product
+icon: standard:product
+datasource: mongodb_catalog # Use MongoDB for flexible schema
+
+fields:
+ sku:
+ type: text
+ label: SKU
+ required: true
+ unique: true
+ index: true
+
+ name:
+ type: text
+ label: Product Name
+ required: true
+ max_length: 255
+
+ description:
+ type: html
+ label: Description
+
+ category_id:
+ type: lookup
+ label: Category
+ reference_to: category
+
+ price:
+ type: currency
+ label: Price
+ required: true
+
+ inventory_qty:
+ type: number
+ label: Inventory Quantity
+ min_value: 0
+
+ attributes:
+ type: json
+ label: Product Attributes
+ schema:
+ color: string
+ size: string
+ weight: number
+
+ is_active:
+ type: boolean
+ label: Active
+ default_value: true
+
+indexes:
+ - fields: [category_id, is_active]
+ - fields: [name, description]
+ type: fulltext
+```
+
+## Next Steps
+
+
+
+
+
+
diff --git a/content/docs/02-protocols/01-objectql/security.mdx b/content/docs/02-protocols/01-objectql/security.mdx
new file mode 100644
index 000000000..7e9d021fd
--- /dev/null
+++ b/content/docs/02-protocols/01-objectql/security.mdx
@@ -0,0 +1,902 @@
+---
+title: Security & Access Control
+description: Comprehensive security model - ACL, field-level security, row-level permissions, and data isolation
+---
+
+import { Shield, Lock, Users, Eye } from 'lucide-react';
+
+# Security Protocol
+
+ObjectQL implements a **multi-layered security model** that enforces access control at the data layer, before queries execute. Security is declarative—defined in configuration, not scattered in application code.
+
+## Security Philosophy
+
+**Traditional approach:**
+```javascript
+// Security in application code (easily bypassed)
+app.get('/api/accounts', (req, res) => {
+ // Developer must remember to check permissions
+ if (!req.user.hasPermission('read_account')) {
+ return res.status(403).json({ error: 'Forbidden' });
+ }
+
+ // Easy to forget row-level filtering
+ const accounts = await db.query('SELECT * FROM account');
+ res.json(accounts);
+});
+```
+
+**ObjectQL approach:**
+```yaml
+# Security as configuration (enforced automatically)
+name: account
+permissions:
+ read:
+ - role: sales_rep
+ filters:
+ - ['owner_id', '=', '{{CURRENT_USER_ID}}']
+```
+
+```typescript
+// Security enforced automatically
+const accounts = await ObjectQL.query({ object: 'account' });
+// WHERE owner_id = current_user_id (injected by ObjectQL)
+```
+
+---
+
+## Security Layers
+
+
+ }
+ title="Object-Level Security (ACL)"
+ description="Who can Create, Read, Update, Delete which objects"
+ />
+ }
+ title="Field-Level Security"
+ description="Control access to individual fields (e.g., hide salary from non-managers)"
+ />
+ }
+ title="Row-Level Security"
+ description="Filter which records users can see (e.g., see only own accounts)"
+ />
+ }
+ title="Data Masking"
+ description="Obfuscate sensitive data (e.g., show last 4 digits of SSN)"
+ />
+
+
+---
+
+## 1. Object-Level Security (CRUD Permissions)
+
+### Basic ACL
+
+```yaml
+# account.object.yml
+name: account
+permissions:
+ create:
+ - role: sales_rep
+ - role: account_manager
+
+ read:
+ - role: sales_rep
+ - role: account_manager
+ - role: executive
+
+ update:
+ - role: account_manager
+
+ delete:
+ - role: admin
+```
+
+**Behavior:**
+- **Sales Rep:** Can create and read accounts
+- **Account Manager:** Can create, read, and update accounts
+- **Executive:** Can read accounts (read-only)
+- **Admin:** Full access (CRUD)
+
+### Permission Check Flow
+
+```
+User requests: GET /api/account/123
+ ↓
+1. Check Object-Level Permission
+ ✓ User has 'read' on 'account'?
+ ↓
+2. Apply Row-Level Filters
+ ✓ User can see record 123?
+ ↓
+3. Apply Field-Level Security
+ ✓ Remove restricted fields
+ ↓
+Return filtered result
+```
+
+---
+
+## 2. Row-Level Security
+
+### Owner-Based Access
+
+```yaml
+# Only see records you own
+name: opportunity
+permissions:
+ read:
+ - role: sales_rep
+ filters:
+ - ['owner_id', '=', '{{CURRENT_USER_ID}}']
+```
+
+**Runtime behavior:**
+```typescript
+// User queries opportunities
+const opportunities = await ObjectQL.query({ object: 'opportunity' });
+
+// ObjectQL injects filter automatically:
+// WHERE owner_id = 'user_123'
+```
+
+### Team-Based Access
+
+```yaml
+# See records owned by your team
+name: account
+permissions:
+ read:
+ - role: sales_rep
+ filters:
+ - ['owner.team_id', '=', '{{CURRENT_USER.team_id}}']
+```
+
+### Territory-Based Access
+
+```yaml
+# See accounts in your territory
+name: account
+permissions:
+ read:
+ - role: sales_rep
+ filters:
+ - ['territory_id', 'in', '{{CURRENT_USER.territory_ids}}']
+```
+
+### Hierarchical Access
+
+```yaml
+# Managers see their records + subordinates' records
+name: opportunity
+permissions:
+ read:
+ - role: sales_manager
+ filters:
+ - ['or',
+ ['owner_id', '=', '{{CURRENT_USER_ID}}'],
+ ['owner.manager_id', '=', '{{CURRENT_USER_ID}}']
+ ]
+```
+
+### Multi-Tenant Isolation
+
+```yaml
+# Strict tenant isolation
+name: customer
+tenant_scope: true # Auto-inject tenant filter
+permissions:
+ read:
+ - role: user
+ filters:
+ - ['tenant_id', '=', '{{CURRENT_TENANT_ID}}']
+```
+
+**Guarantee:** User in Tenant A **cannot** access Tenant B's data, even with direct API calls or SQL injection attempts.
+
+### Conditional Filters
+
+```yaml
+# Different filters for different roles
+name: account
+permissions:
+ read:
+ # Sales reps: Own accounts only
+ - role: sales_rep
+ filters:
+ - ['owner_id', '=', '{{CURRENT_USER_ID}}']
+
+ # Managers: Team accounts
+ - role: manager
+ filters:
+ - ['owner.team_id', '=', '{{CURRENT_USER.team_id}}']
+
+ # Executives: All accounts
+ - role: executive
+ filters: [] # No restrictions
+```
+
+---
+
+## 3. Field-Level Security
+
+### Hide Sensitive Fields
+
+```yaml
+name: user
+fields:
+ salary:
+ type: currency
+ label: Salary
+ visibility:
+ read:
+ - role: hr_manager
+ - role: executive
+ update:
+ - role: hr_manager
+
+ ssn:
+ type: text
+ label: Social Security Number
+ visibility:
+ read:
+ - role: hr_admin
+ update:
+ - role: hr_admin
+```
+
+**Behavior:**
+```typescript
+// Sales manager queries user
+const user = await ObjectQL.findOne('user', '123');
+
+// Result (salary/ssn stripped):
+// {
+// _id: '123',
+// name: 'John Doe',
+// email: 'john@example.com'
+// // salary: REMOVED
+// // ssn: REMOVED
+// }
+
+// HR manager queries same user
+const user = await ObjectQL.findOne('user', '123');
+
+// Result (salary visible):
+// {
+// _id: '123',
+// name: 'John Doe',
+// email: 'john@example.com',
+// salary: { amount: 120000, currency: 'USD' }
+// // ssn: STILL REMOVED (not hr_admin)
+// }
+```
+
+### Field-Level Permissions Reference
+
+```yaml
+fields:
+ field_name:
+ visibility:
+ read: [role1, role2] # Who can see the field
+ update: [role1] # Who can modify the field
+ create: [role1, role2] # Who can set on creation
+```
+
+### Computed Field Security
+
+```yaml
+fields:
+ commission_rate:
+ type: percent
+ label: Commission Rate
+ visibility:
+ read: [sales_manager, hr_admin]
+
+ total_commission:
+ type: formula
+ formula: "total_sales * commission_rate"
+ # Visibility inherited from commission_rate
+ # Users who can't see commission_rate can't see this
+```
+
+---
+
+## 4. Data Masking
+
+### Partial Masking
+
+```yaml
+fields:
+ ssn:
+ type: text
+ label: SSN
+ masking:
+ mode: partial
+ visible_chars: 4
+ position: end
+ mask_char: '*'
+```
+
+**Display:**
+- **Actual value:** `123-45-6789`
+- **Masked value:** `***-**-6789`
+
+### Full Masking
+
+```yaml
+fields:
+ credit_card:
+ type: text
+ label: Credit Card
+ masking:
+ mode: full
+ mask_char: '*'
+```
+
+**Display:**
+- **Actual value:** `4111111111111111`
+- **Masked value:** `****************`
+
+### Conditional Masking
+
+```yaml
+fields:
+ salary:
+ type: currency
+ label: Salary
+ masking:
+ # Show full value to HR, masked to others
+ roles_with_access: [hr_manager, hr_admin]
+ mode: partial
+ mask_char: 'X'
+```
+
+### Hash Masking
+
+```yaml
+fields:
+ email:
+ type: email
+ label: Email
+ masking:
+ mode: hash
+ algorithm: sha256
+ # Returns: 5d41402abc4b2a76b9719d911017c592
+```
+
+---
+
+## 5. Advanced Security Patterns
+
+### Sharing Rules
+
+Grant additional access beyond base permissions:
+
+```yaml
+name: account
+permissions:
+ read:
+ - role: sales_rep
+ filters: [['owner_id', '=', '{{CURRENT_USER_ID}}']]
+
+sharing_rules:
+ # Share enterprise accounts with all sales reps
+ - name: share_enterprise_accounts
+ criteria:
+ - ['account_type', '=', 'Enterprise']
+ access_level: read
+ shared_with:
+ - role: sales_rep
+```
+
+**Effect:** Sales reps see:
+1. Their own accounts (base permission)
+2. All enterprise accounts (sharing rule)
+
+### Record-Level Sharing
+
+```yaml
+# Manual sharing via junction object
+name: account_share
+fields:
+ account_id:
+ type: lookup
+ reference_to: account
+
+ user_id:
+ type: lookup
+ reference_to: user
+
+ access_level:
+ type: select
+ options: [read, write]
+```
+
+**Query with sharing:**
+```typescript
+const accounts = await ObjectQL.query({
+ object: 'account',
+ // User sees:
+ // 1. Own accounts (owner_id = user)
+ // 2. Shared accounts (via account_share)
+});
+```
+
+### Time-Based Access
+
+```yaml
+permissions:
+ read:
+ - role: contractor
+ filters:
+ - ['contract_start', '<=', '{{TODAY()}}']
+ - ['contract_end', '>=', '{{TODAY()}}']
+```
+
+**Effect:** Contractors only see data during contract period.
+
+### IP-Based Restrictions
+
+```yaml
+permissions:
+ read:
+ - role: user
+ ip_whitelist:
+ - 192.168.1.0/24
+ - 10.0.0.0/8
+```
+
+### Device-Based Access
+
+```yaml
+permissions:
+ update:
+ - role: user
+ require_mfa: true # Require multi-factor authentication
+ allowed_devices: [desktop, mobile_app]
+ # Block: web_browser on mobile
+```
+
+---
+
+## 6. Permission Evaluation
+
+### Priority Rules
+
+When multiple permission rules match:
+
+1. **Most specific wins**
+ - Field-level > Object-level > Global
+
+2. **Deny overrides allow**
+ - Explicit deny > Explicit allow
+
+3. **Role hierarchy**
+ - Admin > Manager > User
+
+**Example:**
+```yaml
+# Global default: No access
+default_access: none
+
+# Object level: Sales can read
+permissions:
+ read: [sales_rep]
+
+# Field level: Salary hidden
+fields:
+ salary:
+ visibility:
+ read: [hr_manager]
+
+# Result for sales_rep:
+# - Can read account (object-level)
+# - Cannot see salary (field-level override)
+```
+
+### Permission Functions
+
+```yaml
+filters:
+ # Current user
+ - ['owner_id', '=', '{{CURRENT_USER_ID}}']
+
+ # Current user's team
+ - ['team_id', '=', '{{CURRENT_USER.team_id}}']
+
+ # Current tenant
+ - ['tenant_id', '=', '{{CURRENT_TENANT_ID}}']
+
+ # Current date/time
+ - ['created_at', '>', '{{TODAY() - 30}}']
+
+ # User attributes
+ - ['territory', 'in', '{{CURRENT_USER.territories}}']
+```
+
+---
+
+## 7. Security Auditing
+
+### Audit Log
+
+Track all data access:
+
+```yaml
+name: account
+enable:
+ audit: true # Enable audit logging
+ audit_fields: [owner_id, annual_revenue, status]
+```
+
+**Audit log captures:**
+- **Who:** User ID, role, IP address
+- **What:** Object, record ID, fields changed
+- **When:** Timestamp
+- **How:** Old value → New value
+
+**Example log:**
+```json
+{
+ "timestamp": "2024-01-15T14:30:00Z",
+ "user_id": "user_123",
+ "user_role": "sales_rep",
+ "action": "update",
+ "object": "account",
+ "record_id": "acc_456",
+ "changes": {
+ "annual_revenue": {
+ "old": 1000000,
+ "new": 1500000
+ }
+ },
+ "ip_address": "192.168.1.100"
+}
+```
+
+### Access Logs
+
+Log all query attempts:
+
+```yaml
+name: account
+enable:
+ access_log: true
+```
+
+**Captures:**
+- Failed permission checks (security violations)
+- Successful queries (for compliance)
+- Export operations (GDPR requirements)
+
+---
+
+## 8. Data Encryption
+
+### At-Rest Encryption
+
+```yaml
+fields:
+ ssn:
+ type: text
+ label: SSN
+ encrypt: true
+ encryption_key: ssn_master_key
+```
+
+**Storage:**
+- Database stores encrypted value
+- Application decrypts on read (if user has permission)
+- Encryption key stored in secure vault (not in database)
+
+### In-Transit Encryption
+
+All ObjectQL communication uses TLS 1.3:
+- API requests: HTTPS
+- Database connections: SSL/TLS
+- Internal services: mTLS (mutual TLS)
+
+### Field-Level Encryption
+
+```yaml
+fields:
+ credit_card:
+ type: text
+ encrypt: true
+ encryption_algorithm: AES-256-GCM
+ key_rotation: 90 # Rotate key every 90 days
+```
+
+---
+
+## 9. Compliance Features
+
+### GDPR: Right to be Forgotten
+
+```yaml
+name: customer
+enable:
+ gdpr_erasure: true
+
+fields:
+ email:
+ pii: true # Mark as personally identifiable
+
+ name:
+ pii: true
+```
+
+**Erasure request:**
+```typescript
+await ObjectQL.gdprErase('customer', 'customer_123');
+
+// Result:
+// - PII fields set to null
+// - Audit log preserved (who requested, when)
+// - Related records handled per cascade rules
+```
+
+### HIPAA: PHI Protection
+
+```yaml
+name: patient
+compliance: hipaa
+
+fields:
+ medical_record_number:
+ type: text
+ phi: true # Protected Health Information
+ encrypt: true
+ audit: true
+```
+
+**Automatic enforcement:**
+- Encryption at rest
+- Access logging
+- Minimum necessary principle (field-level security)
+- Audit trail
+
+### SOC 2: Access Controls
+
+```yaml
+name: financial_record
+compliance: soc2
+
+permissions:
+ read:
+ - role: accountant
+ require_mfa: true
+ session_timeout: 900 # 15 minutes
+ ip_whitelist: [corporate_network]
+```
+
+---
+
+## 10. Security Testing
+
+### Permission Dry Run
+
+```typescript
+// Check if user can access before querying
+const canAccess = await ObjectQL.checkPermission({
+ user: currentUser,
+ action: 'read',
+ object: 'account',
+ record_id: 'acc_123'
+});
+
+if (!canAccess) {
+ // Show error message, don't attempt query
+}
+```
+
+### Security Assertions
+
+```typescript
+// In tests
+await expect(
+ ObjectQL.query({
+ object: 'salary_data',
+ user: salesRepUser
+ })
+).toThrow(PermissionError);
+```
+
+### Penetration Testing
+
+ObjectQL provides security test helpers:
+
+```typescript
+// Test all permission combinations
+await ObjectQL.testSuite.runSecurityTests({
+ objects: ['account', 'opportunity', 'contact'],
+ users: [admin, manager, salesRep, guest],
+ scenarios: ['create', 'read', 'update', 'delete']
+});
+
+// Report:
+// ✓ Admin: Full access to all objects
+// ✓ Manager: Read access to team accounts
+// ✗ Sales Rep: SECURITY ISSUE - Can read salary field
+// ✓ Guest: No access (as expected)
+```
+
+---
+
+## Real-World Examples
+
+### SaaS Multi-Tenancy
+
+```yaml
+name: customer
+tenant_scope: true
+
+permissions:
+ read:
+ - role: user
+ filters:
+ - ['tenant_id', '=', '{{CURRENT_TENANT_ID}}']
+ - ['or',
+ ['owner_id', '=', '{{CURRENT_USER_ID}}'],
+ ['shared_with', 'contains', '{{CURRENT_USER_ID}}']
+ ]
+```
+
+### Healthcare: Patient Records
+
+```yaml
+name: patient_record
+compliance: hipaa
+
+permissions:
+ read:
+ # Doctors: Own patients
+ - role: doctor
+ filters:
+ - ['assigned_doctor_id', '=', '{{CURRENT_USER_ID}}']
+
+ # Nurses: Same department
+ - role: nurse
+ filters:
+ - ['department_id', '=', '{{CURRENT_USER.department_id}}']
+
+ # Patient: Own record only
+ - role: patient
+ filters:
+ - ['patient_id', '=', '{{CURRENT_USER.patient_id}}']
+
+fields:
+ diagnosis:
+ visibility:
+ read: [doctor, nurse] # Hidden from patient
+
+ treatment_notes:
+ visibility:
+ read: [doctor] # Hidden from nurse and patient
+```
+
+### Banking: Transaction Security
+
+```yaml
+name: transaction
+compliance: pci_dss
+
+permissions:
+ read:
+ - role: account_holder
+ filters:
+ - ['account.owner_id', '=', '{{CURRENT_USER_ID}}']
+ require_mfa: true
+
+ update:
+ - role: admin
+ require_approval: true # Transactions require 2-person approval
+
+fields:
+ card_number:
+ type: text
+ encrypt: true
+ masking:
+ mode: partial
+ visible_chars: 4
+ position: end
+
+ cvv:
+ type: text
+ encrypt: true
+ masking:
+ mode: full
+```
+
+---
+
+## Best Practices
+
+### 1. Principle of Least Privilege
+
+```yaml
+# ❌ Bad: Grant broad access by default
+permissions:
+ read: [user] # All users can read everything
+
+# ✅ Good: Restrict by default, grant explicitly
+permissions:
+ read:
+ - role: account_owner
+ filters: [['owner_id', '=', '{{CURRENT_USER_ID}}']]
+```
+
+### 2. Defense in Depth
+
+```yaml
+# Multiple security layers
+permissions:
+ read:
+ - role: user
+ filters: [['owner_id', '=', '{{CURRENT_USER_ID}}']]
+ require_mfa: true
+ ip_whitelist: [corporate_network]
+
+fields:
+ sensitive_data:
+ encrypt: true
+ masking: { mode: partial }
+ audit: true
+```
+
+### 3. Security by Default
+
+```yaml
+# Auto-inject security fields
+name: project
+fields:
+ owner_id:
+ type: lookup
+ reference_to: user
+ default_value: '{{CURRENT_USER_ID}}' # Auto-assign owner
+
+ tenant_id:
+ type: lookup
+ reference_to: tenant
+ default_value: '{{CURRENT_TENANT_ID}}' # Auto-assign tenant
+```
+
+### 4. Regular Audits
+
+```bash
+# Generate security report
+objectstack security:audit
+
+# Output:
+# Objects with no permissions: 3
+# Users with admin access: 5
+# Unencrypted PII fields: 2
+# Shared records: 42
+```
+
+---
+
+## Next Steps
+
+
+
+
+
+
diff --git a/content/docs/02-protocols/01-objectql/types.mdx b/content/docs/02-protocols/01-objectql/types.mdx
new file mode 100644
index 000000000..fcd1e49b7
--- /dev/null
+++ b/content/docs/02-protocols/01-objectql/types.mdx
@@ -0,0 +1,1091 @@
+---
+title: Type System
+description: Complete reference for ObjectQL field types - Scalars, relationships, computed fields, and advanced types
+---
+
+import { Type, Link, Calculator, Database } from 'lucide-react';
+
+# ObjectQL Type System
+
+ObjectQL provides **20+ specialized field types** that encode business semantics, not just data storage primitives. Each type understands its purpose and automatically configures database schemas, UI renderers, validation rules, and API serialization.
+
+## Type Philosophy
+
+**Traditional databases:**
+```sql
+-- Just stores data
+CREATE TABLE customer (
+ revenue DECIMAL(18,2) -- Is this USD? EUR? Monthly? Annual?
+);
+```
+
+**ObjectQL:**
+```yaml
+# Encodes business meaning
+revenue:
+ type: currency
+ label: Annual Revenue
+ scale: 2
+ precision: 18
+ # Automatically knows:
+ # - Store amount + currency code
+ # - UI shows currency symbol
+ # - Validate numeric precision
+ # - Format for display ($1,234.56)
+```
+
+## Type Categories
+
+
+ }
+ title="Scalar Types"
+ description="Primitive values: text, numbers, dates, booleans"
+ />
+ }
+ title="Relationship Types"
+ description="Lookups, master-detail, polymorphic references"
+ />
+ }
+ title="Computed Types"
+ description="Formulas, rollup summaries, auto-numbers"
+ />
+ }
+ title="Complex Types"
+ description="JSON, arrays, geolocation, file attachments"
+ />
+
+
+---
+
+## 1. Scalar Types
+
+### Text Types
+
+#### `text`
+Single-line text field.
+
+```yaml
+company_name:
+ type: text
+ label: Company Name
+ max_length: 255
+ required: true
+ index: true
+```
+
+**Database mapping:**
+- PostgreSQL: `VARCHAR(max_length)` or `TEXT`
+- MongoDB: `String`
+- Redis: `String`
+
+**UI rendering:**
+```html
+
+```
+
+**Use cases:**
+- Names, titles, identifiers
+- Email addresses, phone numbers
+- Short descriptions
+
+---
+
+#### `textarea`
+Multi-line plain text.
+
+```yaml
+description:
+ type: textarea
+ label: Description
+ max_length: 5000
+ rows: 10
+```
+
+**Database mapping:**
+- PostgreSQL: `TEXT`
+- MongoDB: `String`
+
+**UI rendering:**
+```html
+
+```
+
+**Use cases:**
+- Comments, notes
+- Descriptions
+- Plain text content
+
+---
+
+#### `html`
+Rich text with HTML markup.
+
+```yaml
+bio:
+ type: html
+ label: Biography
+ sanitize: true # Remove dangerous tags
+ allowed_tags: [p, br, strong, em, ul, li]
+```
+
+**Database mapping:**
+- PostgreSQL: `TEXT`
+- MongoDB: `String`
+
+**Sanitization:**
+- Removes `
+```
+
+### Svelte Widget
+
+```svelte
+
+
+
+
+ );
+}
+```
+
+### 5. Optimize Re-renders
+
+```typescript
+import { memo } from 'react';
+
+export const MyWidget = memo((props: FieldWidgetProps) => {
+ // Component implementation
+}, (prevProps, nextProps) => {
+ // Custom comparison
+ return prevProps.value === nextProps.value &&
+ prevProps.error === nextProps.error &&
+ prevProps.readonly === nextProps.readonly;
+});
+```
+
+---
+
+## 🔗 Related Resources
+
+- [ObjectUI Protocol](/docs/02-protocols/02-objectui)
+- [Field Types Reference](/docs/guides/field-types)
+- [Plugin Development](/docs/03-development/writing-plugins)
+
+---
+
+## 🆘 Troubleshooting
+
+### Widget Not Rendering
+
+Check that it's registered properly:
+
+```typescript
+export default defineWidget({
+ name: 'my_widget',
+ component: MyWidget,
+ supportedTypes: ['text'],
+});
+```
+
+### onChange Not Working
+
+Ensure you're calling it correctly:
+
+```typescript
+onChange(newValue); // ✅ Correct
+onChange({ target: { value: newValue } }); // ❌ Wrong
+```
+
+### Styles Not Loading
+
+Import CSS in your entry point:
+
+```typescript
+import './styles.css';
+export { MyWidget } from './MyWidget';
+```
+
+---
+
+Ready to build your custom widget? Start with the [Quick Start](#quick-start) guide! 🎨
diff --git a/content/docs/03-development/index.mdx b/content/docs/03-development/index.mdx
new file mode 100644
index 000000000..40f738753
--- /dev/null
+++ b/content/docs/03-development/index.mdx
@@ -0,0 +1,371 @@
+---
+title: Development & Extension
+description: Extend ObjectStack with plugins, custom widgets, and drivers to build powerful business applications.
+---
+
+# Development & Extension
+
+ObjectStack is designed for **extensibility at every layer**. Whether you're building a custom field widget, integrating a third-party API, or creating an entirely new database driver, the platform provides clean interfaces and powerful abstractions.
+
+## 🎯 What You Can Extend
+
+
+
+ Add new objects, routes, scheduled jobs, and business logic
+
+
+
+ Build React/Vue components for custom field rendering
+
+
+
+ Connect to any database or data source (SQL, NoSQL, APIs)
+
+
+
+ Manage projects, generate code, and deploy with objectstack-cli
+
+
+
+---
+
+## 📐 Architecture Overview
+
+ObjectStack follows a **layered, protocol-driven architecture**:
+
+```
+┌─────────────────────────────────────────┐
+│ Your Application Code │
+│ (Objects, Flows, Views, Plugins) │
+├─────────────────────────────────────────┤
+│ ObjectStack Kernel │
+│ • Plugin System • Event Bus │
+│ • Lifecycle Mgmt • Dependency DI │
+├─────────────────────────────────────────┤
+│ Protocol Layer │
+│ • ObjectQL • ObjectUI • ObjectOS │
+├─────────────────────────────────────────┤
+│ Driver Layer │
+│ • PostgreSQL • MongoDB • Redis │
+│ • MySQL • Memory • Custom │
+└─────────────────────────────────────────┘
+```
+
+### Key Principles
+
+1. **Everything is Metadata** - Define structure declaratively, execute dynamically
+2. **Zod-First Design** - All schemas are validated at runtime and compile-time
+3. **Protocol Contracts** - Strict interfaces ensure interoperability
+4. **Local-First** - Own your data, run anywhere
+
+---
+
+## 🚀 Quick Start Paths
+
+### For Frontend Developers
+
+Start with **Custom Widgets** to enhance the UI layer:
+
+```bash
+npm create @objectstack/widget my-rich-editor
+cd my-rich-editor
+npm install
+npm run dev
+```
+
+Build React/Vue components that integrate seamlessly with ObjectStack forms and views.
+
+[→ Custom Widgets Guide](/docs/03-development/custom-widgets)
+
+---
+
+### For Backend Developers
+
+Start with **Plugins** to add business logic:
+
+```bash
+npm create @objectstack/plugin my-api-integration
+cd my-api-integration
+npm install
+npm run build
+```
+
+Create custom Objects, API routes, scheduled jobs, and event listeners.
+
+[→ Plugin Development Guide](/docs/03-development/writing-plugins)
+
+---
+
+### For Database Engineers
+
+Start with **Drivers** to connect new data sources:
+
+```bash
+npm create @objectstack/driver my-custom-db
+cd my-custom-db
+npm install
+npm run build
+```
+
+Implement the `DriverInterface` to bridge ObjectQL with any database.
+
+[→ Driver Development Guide](/docs/03-development/server-drivers)
+
+---
+
+## 🛠️ Development Workflow
+
+### 1. Project Initialization
+
+```bash
+# Create a new ObjectStack project
+npx @objectstack/cli init my-project
+
+# Or add to existing project
+npm install @objectstack/spec @objectstack/kernel
+```
+
+### 2. Define Metadata
+
+All ObjectStack resources are defined as **TypeScript files** using Zod schemas:
+
+```typescript
+// src/objects/task.object.ts
+import { ObjectSchema, Field } from '@objectstack/spec';
+
+export const Task = ObjectSchema.create({
+ name: 'task',
+ label: 'Task',
+ fields: {
+ title: Field.text({ label: 'Title', required: true }),
+ status: Field.select({
+ label: 'Status',
+ options: [
+ { label: 'To Do', value: 'todo' },
+ { label: 'Done', value: 'done' },
+ ],
+ }),
+ },
+});
+```
+
+### 3. Build & Deploy
+
+```bash
+# Validate schemas
+npm run validate
+
+# Build for production
+npm run build
+
+# Deploy to ObjectStack Cloud or self-hosted
+objectstack deploy
+```
+
+---
+
+## 📦 Extension Types Compared
+
+| Extension Type | Use Case | Language | Runtime |
+|----------------|----------|----------|---------|
+| **Plugin** | Add objects, routes, jobs, logic | TypeScript/JavaScript | Server |
+| **Widget** | Custom field rendering | React, Vue, Svelte | Browser |
+| **Driver** | Database connectivity | TypeScript/JavaScript | Server |
+| **Flow Action** | Custom automation steps | TypeScript/JavaScript | Server |
+| **API Adapter** | External service integration | TypeScript/JavaScript | Server |
+
+---
+
+## 🎓 Learning Resources
+
+
+
+
+### Understand the Core Protocols
+
+Before building extensions, familiarize yourself with the three core protocols:
+
+- [ObjectQL](/docs/02-protocols/01-objectql) - Data modeling and queries
+- [ObjectUI](/docs/02-protocols/02-objectui) - User interface definitions
+- [ObjectOS](/docs/02-protocols/03-objectos) - System runtime and plugin architecture
+
+
+
+
+### Study Examples
+
+Explore reference implementations:
+
+- `examples/plugin-crm` - Full-featured CRM plugin
+- `examples/widget-rich-text` - Custom WYSIWYG editor widget
+- `examples/driver-mongodb` - MongoDB driver implementation
+- `examples/flow-action-email` - Email sending flow action
+
+
+
+
+### Build Your Extension
+
+Follow the step-by-step guides for your extension type:
+
+1. [Writing Plugins](/docs/03-development/writing-plugins)
+2. [Custom Widgets](/docs/03-development/custom-widgets)
+3. [Server Drivers](/docs/03-development/server-drivers)
+4. [CLI Tools](/docs/03-development/cli-tools)
+
+
+
+
+
+---
+
+## 🔐 Security & Best Practices
+
+### Input Validation
+
+Always validate user input using Zod schemas:
+
+```typescript
+import { z } from 'zod';
+
+const CreateTaskSchema = z.object({
+ title: z.string().min(1).max(200),
+ priority: z.enum(['low', 'medium', 'high']),
+});
+
+// In your plugin
+export default {
+ onEnable: async (context) => {
+ context.router.post('/api/tasks', async (req, res) => {
+ const data = CreateTaskSchema.parse(req.body); // Throws if invalid
+ // Safe to use data...
+ });
+ },
+};
+```
+
+### Permission Checks
+
+Enforce access control using ObjectStack's permission system:
+
+```typescript
+// Check object-level permissions
+const canCreate = await context.os.checkPermission('task', 'create');
+
+// Check field-level permissions
+const canEditStatus = await context.os.checkFieldPermission(
+ 'task',
+ 'status',
+ 'edit'
+);
+```
+
+### Error Handling
+
+Use structured error responses:
+
+```typescript
+import { ObjectStackError } from '@objectstack/kernel';
+
+throw new ObjectStackError('VALIDATION_ERROR', {
+ message: 'Invalid task status',
+ field: 'status',
+ code: 'INVALID_STATUS',
+});
+```
+
+---
+
+## 🧪 Testing Your Extensions
+
+### Unit Testing
+
+Test your business logic in isolation:
+
+```typescript
+import { describe, it, expect } from 'vitest';
+import { validateTask } from './validators';
+
+describe('Task Validation', () => {
+ it('should reject empty titles', () => {
+ expect(() => validateTask({ title: '' })).toThrow();
+ });
+});
+```
+
+### Integration Testing
+
+Test against a real ObjectStack runtime:
+
+```typescript
+import { createTestContext } from '@objectstack/testing';
+
+const context = await createTestContext({
+ plugins: ['./my-plugin'],
+});
+
+const result = await context.ql.object('task').create({
+ title: 'Test Task',
+});
+
+expect(result.id).toBeDefined();
+```
+
+---
+
+## 🌍 Publishing Extensions
+
+### NPM Packages
+
+Publish plugins and drivers as npm packages:
+
+```json
+{
+ "name": "@mycompany/objectstack-plugin-crm",
+ "version": "1.0.0",
+ "keywords": ["objectstack", "plugin", "crm"],
+ "objectstack": {
+ "type": "plugin",
+ "entry": "./dist/index.js"
+ }
+}
+```
+
+### ObjectStack Hub
+
+Submit your extension to the official marketplace:
+
+```bash
+objectstack publish --registry hub.objectstack.dev
+```
+
+---
+
+## 📚 Next Steps
+
+
+
+ Complete API documentation for all protocols
+
+
+
+ Production-ready example projects
+
+
+
+ Get help from the community
+
+
+
+---
+
+## 🆘 Getting Help
+
+- **Documentation**: [docs.objectstack.dev](https://docs.objectstack.dev)
+- **Discord**: [discord.gg/objectstack](https://discord.gg/objectstack)
+- **GitHub Discussions**: [github.com/objectstack/spec/discussions](https://github.com/objectstack/spec/discussions)
+- **Stack Overflow**: Tag your questions with `objectstack`
+
+---
+
+Ready to start building? Pick your extension type and dive into the guides! 🚀
diff --git a/content/docs/03-development/meta.json b/content/docs/03-development/meta.json
new file mode 100644
index 000000000..9a8119d91
--- /dev/null
+++ b/content/docs/03-development/meta.json
@@ -0,0 +1,9 @@
+{
+ "title": "🔧 Development & Extension",
+ "pages": [
+ "writing-plugins",
+ "custom-widgets",
+ "server-drivers",
+ "cli-tools"
+ ]
+}
diff --git a/content/docs/03-development/server-drivers.mdx b/content/docs/03-development/server-drivers.mdx
new file mode 100644
index 000000000..12cb097ee
--- /dev/null
+++ b/content/docs/03-development/server-drivers.mdx
@@ -0,0 +1,1107 @@
+---
+title: Server Drivers
+description: Connect ObjectStack to any database or data source by implementing the DriverInterface protocol.
+---
+
+# Server Drivers
+
+Drivers are the **bridge between ObjectQL and your data storage**. By implementing the `DriverInterface`, you can connect ObjectStack to any database (SQL, NoSQL, in-memory, or even external APIs).
+
+ObjectStack comes with built-in drivers for PostgreSQL, MySQL, MongoDB, and Redis, but you can create custom drivers for proprietary databases, legacy systems, or specialized data sources.
+
+---
+
+## 🎯 What Are Drivers?
+
+Drivers translate **ObjectQL queries** into database-specific operations and normalize results back into the ObjectStack protocol format.
+
+
+
+ PostgreSQL, MySQL, SQL Server, Oracle
+
+
+
+ MongoDB, Cassandra, DynamoDB, Firestore
+
+
+
+ Redis, Memcached, In-Memory
+
+
+
+ Salesforce, Airtable, REST APIs, GraphQL
+
+
+
+---
+
+## 📋 Prerequisites
+
+- **TypeScript** knowledge
+- Understanding of [ObjectQL Protocol](/docs/02-protocols/01-objectql)
+- Familiarity with target database (SQL, MongoDB, etc.)
+- Node.js 18+ and npm 9+
+
+---
+
+## 🚀 Quick Start
+
+### Step 1: Create a Driver Project
+
+```bash
+# Using the official generator
+npm create @objectstack/driver my-custom-db
+
+cd my-custom-db
+npm install
+```
+
+This generates:
+
+```
+my-custom-db/
+├── src/
+│ ├── index.ts # Driver entry point
+│ ├── driver.ts # Driver implementation
+│ ├── query-builder.ts # Query translation
+│ ├── connection.ts # Connection management
+│ └── types.ts # TypeScript types
+├── tests/
+│ └── driver.test.ts
+├── package.json
+└── tsconfig.json
+```
+
+### Step 2: Implement the DriverInterface
+
+```typescript
+// src/driver.ts
+import {
+ DriverInterface,
+ DriverOptions,
+ DriverCapabilities,
+} from '@objectstack/spec';
+import { Query, QueryResult } from '@objectstack/objectql';
+
+export class MyCustomDriver implements DriverInterface {
+ name = 'MyCustomDB';
+ version = '1.0.0';
+
+ private connection: any;
+
+ // ============================================================================
+ // Connection Management
+ // ============================================================================
+
+ async connect(config: any): Promise {
+ this.connection = await createConnection(config);
+ }
+
+ async disconnect(): Promise {
+ await this.connection.close();
+ }
+
+ async ping(): Promise {
+ return this.connection.isAlive();
+ }
+
+ // ============================================================================
+ // Capabilities Declaration
+ // ============================================================================
+
+ getCapabilities(): DriverCapabilities {
+ return {
+ // Transaction support
+ transactions: true,
+
+ // Query features
+ queryFilters: true,
+ queryAggregations: true,
+ querySorting: true,
+ queryPagination: true,
+ queryJoins: true,
+
+ // Data operations
+ bulkInsert: true,
+ bulkUpdate: true,
+ bulkDelete: true,
+
+ // Advanced features
+ fullTextSearch: true,
+ geospatialQueries: false,
+ jsonQuerying: true,
+ };
+ }
+
+ // ============================================================================
+ // CRUD Operations (See below)
+ // ============================================================================
+
+ async find(object: string, query: Query, options?: DriverOptions): Promise {
+ // Implementation
+ }
+
+ async findOne(object: string, id: string, options?: DriverOptions): Promise {
+ // Implementation
+ }
+
+ async insert(object: string, data: any, options?: DriverOptions): Promise {
+ // Implementation
+ }
+
+ async update(object: string, id: string, data: any, options?: DriverOptions): Promise {
+ // Implementation
+ }
+
+ async delete(object: string, id: string, options?: DriverOptions): Promise {
+ // Implementation
+ }
+}
+```
+
+---
+
+## 🔍 Implementing CRUD Operations
+
+### Find (Query)
+
+The `find` method receives a `Query` object and returns matching records:
+
+```typescript
+async find(
+ object: string,
+ query: Query,
+ options?: DriverOptions
+): Promise {
+ const { filters, sort, limit, offset, fields } = query;
+
+ // ============================================================================
+ // 1. Build the database query
+ // ============================================================================
+
+ let dbQuery = this.connection.from(object);
+
+ // Apply filters
+ if (filters) {
+ dbQuery = this.applyFilters(dbQuery, filters);
+ }
+
+ // Apply sorting
+ if (sort) {
+ for (const [field, direction] of Object.entries(sort)) {
+ dbQuery = dbQuery.orderBy(field, direction);
+ }
+ }
+
+ // Apply pagination
+ if (limit) {
+ dbQuery = dbQuery.limit(limit);
+ }
+ if (offset) {
+ dbQuery = dbQuery.offset(offset);
+ }
+
+ // Select specific fields
+ if (fields && fields.length > 0) {
+ dbQuery = dbQuery.select(fields);
+ }
+
+ // ============================================================================
+ // 2. Execute the query
+ // ============================================================================
+
+ const results = await dbQuery.execute();
+
+ // ============================================================================
+ // 3. Normalize IDs
+ // ============================================================================
+
+ return results.map(record => this.normalizeRecord(record));
+}
+
+/**
+ * Normalize database-specific IDs to ObjectStack format.
+ * All records MUST have a string `id` field.
+ */
+private normalizeRecord(record: any): any {
+ // Example for MongoDB-like databases with _id
+ if (record._id) {
+ return {
+ ...record,
+ id: record._id.toString(), // Convert to string
+ _id: undefined, // Remove internal ID
+ };
+ }
+
+ // Example for SQL databases with numeric IDs
+ if (typeof record.id === 'number') {
+ return {
+ ...record,
+ id: record.id.toString(), // Convert to string
+ };
+ }
+
+ return record;
+}
+```
+
+### Apply Filters
+
+Convert ObjectQL filters to database-specific syntax:
+
+```typescript
+private applyFilters(dbQuery: any, filters: any): any {
+ for (const [field, condition] of Object.entries(filters)) {
+ if (typeof condition === 'object') {
+ // Complex conditions
+ for (const [operator, value] of Object.entries(condition)) {
+ switch (operator) {
+ case '$eq':
+ dbQuery = dbQuery.where(field, '=', value);
+ break;
+ case '$ne':
+ dbQuery = dbQuery.where(field, '!=', value);
+ break;
+ case '$gt':
+ dbQuery = dbQuery.where(field, '>', value);
+ break;
+ case '$gte':
+ dbQuery = dbQuery.where(field, '>=', value);
+ break;
+ case '$lt':
+ dbQuery = dbQuery.where(field, '<', value);
+ break;
+ case '$lte':
+ dbQuery = dbQuery.where(field, '<=', value);
+ break;
+ case '$in':
+ dbQuery = dbQuery.whereIn(field, value);
+ break;
+ case '$nin':
+ dbQuery = dbQuery.whereNotIn(field, value);
+ break;
+ case '$like':
+ dbQuery = dbQuery.where(field, 'LIKE', value);
+ break;
+ case '$regex':
+ dbQuery = dbQuery.whereRaw(`${field} ~ ?`, [value]);
+ break;
+ }
+ }
+ } else {
+ // Simple equality
+ dbQuery = dbQuery.where(field, '=', condition);
+ }
+ }
+
+ return dbQuery;
+}
+```
+
+### FindOne (Get by ID)
+
+```typescript
+async findOne(
+ object: string,
+ id: string,
+ options?: DriverOptions
+): Promise {
+ const result = await this.connection
+ .from(object)
+ .where('id', '=', id)
+ .first();
+
+ if (!result) {
+ throw new Error(`Record not found: ${object}/${id}`);
+ }
+
+ return this.normalizeRecord(result);
+}
+```
+
+### Insert (Create)
+
+```typescript
+async insert(
+ object: string,
+ data: any,
+ options?: DriverOptions
+): Promise {
+ // ============================================================================
+ // 1. Generate ID if not provided
+ // ============================================================================
+
+ if (!data.id) {
+ data.id = this.generateId();
+ }
+
+ // ============================================================================
+ // 2. Add timestamps
+ // ============================================================================
+
+ const now = new Date();
+ const recordWithMeta = {
+ ...data,
+ created_at: now,
+ updated_at: now,
+ };
+
+ // ============================================================================
+ // 3. Insert into database
+ // ============================================================================
+
+ await this.connection
+ .into(object)
+ .insert(recordWithMeta);
+
+ // ============================================================================
+ // 4. Return the created record
+ // ============================================================================
+
+ return this.normalizeRecord(recordWithMeta);
+}
+
+private generateId(): string {
+ // Use UUID, ULID, or database-specific ID generation
+ return crypto.randomUUID();
+}
+```
+
+### Update
+
+```typescript
+async update(
+ object: string,
+ id: string,
+ data: any,
+ options?: DriverOptions
+): Promise {
+ // ============================================================================
+ // 1. Add updated timestamp
+ // ============================================================================
+
+ const updates = {
+ ...data,
+ updated_at: new Date(),
+ };
+
+ // Remove id from updates (can't update primary key)
+ delete updates.id;
+
+ // ============================================================================
+ // 2. Execute update
+ // ============================================================================
+
+ const result = await this.connection
+ .table(object)
+ .where('id', '=', id)
+ .update(updates);
+
+ if (result === 0) {
+ throw new Error(`Record not found: ${object}/${id}`);
+ }
+
+ // ============================================================================
+ // 3. Return updated record
+ // ============================================================================
+
+ return this.findOne(object, id, options);
+}
+```
+
+### Delete
+
+```typescript
+async delete(
+ object: string,
+ id: string,
+ options?: DriverOptions
+): Promise {
+ const result = await this.connection
+ .table(object)
+ .where('id', '=', id)
+ .delete();
+
+ if (result === 0) {
+ throw new Error(`Record not found: ${object}/${id}`);
+ }
+}
+```
+
+---
+
+## 🔄 Transaction Support
+
+If your database supports transactions, implement these methods:
+
+```typescript
+export class MyCustomDriver implements DriverInterface {
+ // ... other methods
+
+ async beginTransaction(options?: DriverOptions): Promise {
+ const tx = await this.connection.transaction();
+ return tx;
+ }
+
+ async commit(transaction: any): Promise {
+ await transaction.commit();
+ }
+
+ async rollback(transaction: any): Promise {
+ await transaction.rollback();
+ }
+}
+```
+
+**Usage:**
+
+```typescript
+const tx = await driver.beginTransaction();
+
+try {
+ await driver.insert('account', { name: 'Acme' }, { transaction: tx });
+ await driver.insert('contact', { account: 'acme-id' }, { transaction: tx });
+ await driver.commit(tx);
+} catch (error) {
+ await driver.rollback(tx);
+ throw error;
+}
+```
+
+---
+
+## 📊 Advanced Features
+
+### Aggregations
+
+```typescript
+async aggregate(
+ object: string,
+ aggregations: any,
+ options?: DriverOptions
+): Promise {
+ let query = this.connection.from(object);
+
+ const results: any = {};
+
+ for (const [alias, agg] of Object.entries(aggregations)) {
+ const { function: fn, field } = agg as any;
+
+ switch (fn) {
+ case 'COUNT':
+ results[alias] = await query.count(field || '*');
+ break;
+ case 'SUM':
+ results[alias] = await query.sum(field);
+ break;
+ case 'AVG':
+ results[alias] = await query.avg(field);
+ break;
+ case 'MIN':
+ results[alias] = await query.min(field);
+ break;
+ case 'MAX':
+ results[alias] = await query.max(field);
+ break;
+ }
+ }
+
+ return results;
+}
+```
+
+### Full-Text Search
+
+```typescript
+async search(
+ object: string,
+ searchTerm: string,
+ fields: string[],
+ options?: DriverOptions
+): Promise {
+ // PostgreSQL example using tsvector
+ const results = await this.connection
+ .from(object)
+ .whereRaw(
+ `to_tsvector('english', ${fields.join(' || ')}) @@ plainto_tsquery('english', ?)`,
+ [searchTerm]
+ );
+
+ return results.map(r => this.normalizeRecord(r));
+}
+```
+
+### Geospatial Queries
+
+```typescript
+async findNearby(
+ object: string,
+ coordinates: { lat: number; lng: number },
+ radiusKm: number,
+ options?: DriverOptions
+): Promise {
+ // PostGIS example
+ const results = await this.connection
+ .from(object)
+ .whereRaw(
+ `ST_DWithin(location::geography, ST_MakePoint(?, ?)::geography, ?)`,
+ [coordinates.lng, coordinates.lat, radiusKm * 1000]
+ );
+
+ return results.map(r => this.normalizeRecord(r));
+}
+```
+
+---
+
+## 🏗️ Example: In-Memory Driver
+
+Complete implementation of a simple in-memory driver:
+
+```typescript
+// src/memory-driver.ts
+import { DriverInterface, DriverCapabilities } from '@objectstack/spec';
+import { Query, QueryResult } from '@objectstack/objectql';
+
+export class InMemoryDriver implements DriverInterface {
+ name = 'InMemory';
+ version = '1.0.0';
+
+ // Storage: Map>
+ private store = new Map>();
+
+ // ============================================================================
+ // Connection (No-op for in-memory)
+ // ============================================================================
+
+ async connect(): Promise {
+ // Nothing to connect
+ }
+
+ async disconnect(): Promise {
+ this.store.clear();
+ }
+
+ async ping(): Promise {
+ return true;
+ }
+
+ // ============================================================================
+ // Capabilities
+ // ============================================================================
+
+ getCapabilities(): DriverCapabilities {
+ return {
+ transactions: false, // No transaction support
+ queryFilters: true, // Basic filtering
+ queryAggregations: true, // In-memory aggregations
+ querySorting: true, // In-memory sorting
+ queryPagination: true, // Simple pagination
+ queryJoins: false, // No joins
+ bulkInsert: true,
+ bulkUpdate: true,
+ bulkDelete: true,
+ fullTextSearch: false,
+ geospatialQueries: false,
+ jsonQuerying: true,
+ };
+ }
+
+ // ============================================================================
+ // CRUD Operations
+ // ============================================================================
+
+ async find(object: string, query: Query): Promise {
+ const table = this.store.get(object) || new Map();
+ let records = Array.from(table.values());
+
+ // Apply filters
+ if (query.filters) {
+ records = records.filter(record => this.matchesFilters(record, query.filters));
+ }
+
+ // Apply sorting
+ if (query.sort) {
+ records = this.sortRecords(records, query.sort);
+ }
+
+ // Apply pagination
+ const offset = query.offset || 0;
+ const limit = query.limit || records.length;
+ records = records.slice(offset, offset + limit);
+
+ // Select fields
+ if (query.fields && query.fields.length > 0) {
+ records = records.map(record =>
+ query.fields!.reduce((acc, field) => {
+ acc[field] = record[field];
+ return acc;
+ }, {} as any)
+ );
+ }
+
+ return records;
+ }
+
+ async findOne(object: string, id: string): Promise {
+ const table = this.store.get(object);
+ if (!table) {
+ throw new Error(`Object not found: ${object}`);
+ }
+
+ const record = table.get(id);
+ if (!record) {
+ throw new Error(`Record not found: ${object}/${id}`);
+ }
+
+ return record;
+ }
+
+ async insert(object: string, data: any): Promise {
+ if (!this.store.has(object)) {
+ this.store.set(object, new Map());
+ }
+
+ const table = this.store.get(object)!;
+
+ const id = data.id || this.generateId();
+ const record = {
+ ...data,
+ id,
+ created_at: new Date(),
+ updated_at: new Date(),
+ };
+
+ table.set(id, record);
+
+ return record;
+ }
+
+ async update(object: string, id: string, data: any): Promise {
+ const table = this.store.get(object);
+ if (!table || !table.has(id)) {
+ throw new Error(`Record not found: ${object}/${id}`);
+ }
+
+ const existing = table.get(id)!;
+ const updated = {
+ ...existing,
+ ...data,
+ id,
+ created_at: existing.created_at,
+ updated_at: new Date(),
+ };
+
+ table.set(id, updated);
+
+ return updated;
+ }
+
+ async delete(object: string, id: string): Promise {
+ const table = this.store.get(object);
+ if (!table || !table.has(id)) {
+ throw new Error(`Record not found: ${object}/${id}`);
+ }
+
+ table.delete(id);
+ }
+
+ // ============================================================================
+ // Bulk Operations
+ // ============================================================================
+
+ async bulkInsert(object: string, records: any[]): Promise {
+ return Promise.all(records.map(r => this.insert(object, r)));
+ }
+
+ async bulkUpdate(object: string, updates: Array<{ id: string; data: any }>): Promise {
+ return Promise.all(updates.map(u => this.update(object, u.id, u.data)));
+ }
+
+ async bulkDelete(object: string, ids: string[]): Promise {
+ await Promise.all(ids.map(id => this.delete(object, id)));
+ }
+
+ // ============================================================================
+ // Helper Methods
+ // ============================================================================
+
+ private matchesFilters(record: any, filters: any): boolean {
+ for (const [field, condition] of Object.entries(filters)) {
+ const value = record[field];
+
+ if (typeof condition === 'object') {
+ for (const [operator, filterValue] of Object.entries(condition)) {
+ switch (operator) {
+ case '$eq':
+ if (value !== filterValue) return false;
+ break;
+ case '$ne':
+ if (value === filterValue) return false;
+ break;
+ case '$gt':
+ if (!(value > filterValue)) return false;
+ break;
+ case '$gte':
+ if (!(value >= filterValue)) return false;
+ break;
+ case '$lt':
+ if (!(value < filterValue)) return false;
+ break;
+ case '$lte':
+ if (!(value <= filterValue)) return false;
+ break;
+ case '$in':
+ if (!filterValue.includes(value)) return false;
+ break;
+ case '$nin':
+ if (filterValue.includes(value)) return false;
+ break;
+ }
+ }
+ } else {
+ if (value !== condition) return false;
+ }
+ }
+
+ return true;
+ }
+
+ private sortRecords(records: any[], sort: any): any[] {
+ return records.sort((a, b) => {
+ for (const [field, direction] of Object.entries(sort)) {
+ const aVal = a[field];
+ const bVal = b[field];
+
+ if (aVal < bVal) return direction === 'asc' ? -1 : 1;
+ if (aVal > bVal) return direction === 'asc' ? 1 : -1;
+ }
+ return 0;
+ });
+ }
+
+ private generateId(): string {
+ return crypto.randomUUID();
+ }
+}
+```
+
+---
+
+## 🗄️ Example: PostgreSQL Driver
+
+```typescript
+// src/postgres-driver.ts
+import { Pool } from 'pg';
+import { DriverInterface } from '@objectstack/spec';
+import { Query } from '@objectstack/objectql';
+
+export class PostgresDriver implements DriverInterface {
+ name = 'PostgreSQL';
+ version = '1.0.0';
+
+ private pool: Pool;
+
+ async connect(config: any): Promise {
+ this.pool = new Pool({
+ host: config.host,
+ port: config.port,
+ database: config.database,
+ user: config.user,
+ password: config.password,
+ });
+ }
+
+ async disconnect(): Promise {
+ await this.pool.end();
+ }
+
+ async find(object: string, query: Query): Promise {
+ const { sql, params } = this.buildSelectQuery(object, query);
+ const result = await this.pool.query(sql, params);
+ return result.rows.map(row => ({
+ ...row,
+ id: row.id.toString(),
+ }));
+ }
+
+ async insert(object: string, data: any): Promise {
+ const id = data.id || crypto.randomUUID();
+ const fields = Object.keys(data);
+ const values = Object.values(data);
+
+ const placeholders = values.map((_, i) => `$${i + 1}`).join(', ');
+
+ const sql = `
+ INSERT INTO ${object} (id, ${fields.join(', ')}, created_at, updated_at)
+ VALUES ($${values.length + 1}, ${placeholders}, NOW(), NOW())
+ RETURNING *
+ `;
+
+ const result = await this.pool.query(sql, [...values, id]);
+ return result.rows[0];
+ }
+
+ private buildSelectQuery(object: string, query: Query): { sql: string; params: any[] } {
+ let sql = `SELECT * FROM ${object}`;
+ const params: any[] = [];
+
+ // WHERE clause
+ if (query.filters) {
+ const { clause, filterParams } = this.buildWhereClause(query.filters);
+ sql += ` WHERE ${clause}`;
+ params.push(...filterParams);
+ }
+
+ // ORDER BY clause
+ if (query.sort) {
+ const orderBy = Object.entries(query.sort)
+ .map(([field, dir]) => `${field} ${dir}`)
+ .join(', ');
+ sql += ` ORDER BY ${orderBy}`;
+ }
+
+ // LIMIT and OFFSET
+ if (query.limit) {
+ sql += ` LIMIT $${params.length + 1}`;
+ params.push(query.limit);
+ }
+ if (query.offset) {
+ sql += ` OFFSET $${params.length + 1}`;
+ params.push(query.offset);
+ }
+
+ return { sql, params };
+ }
+
+ private buildWhereClause(filters: any): { clause: string; filterParams: any[] } {
+ const conditions: string[] = [];
+ const filterParams: any[] = [];
+
+ for (const [field, condition] of Object.entries(filters)) {
+ if (typeof condition === 'object') {
+ for (const [operator, value] of Object.entries(condition)) {
+ const paramIndex = filterParams.length + 1;
+
+ switch (operator) {
+ case '$eq':
+ conditions.push(`${field} = $${paramIndex}`);
+ filterParams.push(value);
+ break;
+ case '$gt':
+ conditions.push(`${field} > $${paramIndex}`);
+ filterParams.push(value);
+ break;
+ case '$in':
+ conditions.push(`${field} = ANY($${paramIndex})`);
+ filterParams.push(value);
+ break;
+ }
+ }
+ } else {
+ const paramIndex = filterParams.length + 1;
+ conditions.push(`${field} = $${paramIndex}`);
+ filterParams.push(condition);
+ }
+ }
+
+ return {
+ clause: conditions.join(' AND '),
+ filterParams,
+ };
+ }
+}
+```
+
+---
+
+## 🧪 Testing Drivers
+
+```typescript
+// tests/driver.test.ts
+import { describe, it, expect, beforeAll, afterAll } from 'vitest';
+import { InMemoryDriver } from '../src/memory-driver';
+
+describe('InMemoryDriver', () => {
+ let driver: InMemoryDriver;
+
+ beforeAll(async () => {
+ driver = new InMemoryDriver();
+ await driver.connect();
+ });
+
+ afterAll(async () => {
+ await driver.disconnect();
+ });
+
+ it('should insert and find records', async () => {
+ const record = await driver.insert('account', {
+ name: 'Acme Corp',
+ status: 'active',
+ });
+
+ expect(record.id).toBeDefined();
+ expect(record.name).toBe('Acme Corp');
+
+ const found = await driver.findOne('account', record.id);
+ expect(found.name).toBe('Acme Corp');
+ });
+
+ it('should filter records', async () => {
+ await driver.insert('account', { name: 'A', status: 'active' });
+ await driver.insert('account', { name: 'B', status: 'inactive' });
+
+ const results = await driver.find('account', {
+ filters: { status: 'active' },
+ });
+
+ expect(results.length).toBe(1);
+ expect(results[0].name).toBe('A');
+ });
+
+ it('should update records', async () => {
+ const record = await driver.insert('account', { name: 'Old Name' });
+
+ const updated = await driver.update('account', record.id, { name: 'New Name' });
+
+ expect(updated.name).toBe('New Name');
+ });
+
+ it('should delete records', async () => {
+ const record = await driver.insert('account', { name: 'To Delete' });
+
+ await driver.delete('account', record.id);
+
+ await expect(driver.findOne('account', record.id)).rejects.toThrow();
+ });
+});
+```
+
+---
+
+## 📦 Packaging & Distribution
+
+```json
+{
+ "name": "@mycompany/objectstack-driver-custom",
+ "version": "1.0.0",
+ "main": "./dist/index.js",
+ "types": "./dist/index.d.ts",
+ "keywords": ["objectstack", "driver", "database"],
+ "files": ["dist"],
+
+ "objectstack": {
+ "type": "driver",
+ "entry": "./dist/index.js"
+ },
+
+ "dependencies": {
+ "@objectstack/spec": "^1.0.0"
+ }
+}
+```
+
+---
+
+## ✅ Best Practices
+
+### 1. Always Normalize IDs
+
+```typescript
+// ✅ Good
+return records.map(r => ({ ...r, id: r.id.toString() }));
+
+// ❌ Bad
+return records; // IDs might be numbers or ObjectIds
+```
+
+### 2. Handle Errors Gracefully
+
+```typescript
+try {
+ await this.connection.query(sql);
+} catch (error) {
+ if (error.code === 'UNIQUE_VIOLATION') {
+ throw new ObjectStackError('DUPLICATE_RECORD', { field: 'email' });
+ }
+ throw error;
+}
+```
+
+### 3. Use Connection Pooling
+
+```typescript
+// ✅ Good
+this.pool = new Pool({ max: 20 });
+
+// ❌ Bad
+const connection = await connect(); // New connection per request
+```
+
+### 4. Implement Bulk Operations
+
+```typescript
+async bulkInsert(object: string, records: any[]): Promise {
+ // ✅ Single query
+ return this.connection.insert(object).values(records);
+
+ // ❌ Multiple queries
+ // return Promise.all(records.map(r => this.insert(object, r)));
+}
+```
+
+### 5. Support Transactions
+
+```typescript
+const tx = await driver.beginTransaction();
+try {
+ // Operations use transaction
+ await driver.commit(tx);
+} catch (error) {
+ await driver.rollback(tx);
+}
+```
+
+---
+
+## 🔗 Related Resources
+
+- [ObjectQL Protocol](/docs/02-protocols/01-objectql)
+- [Plugin Development](/docs/03-development/writing-plugins)
+- [Query Reference](/docs/99-reference/objectql/query)
+
+---
+
+## 🆘 Troubleshooting
+
+### Connection Issues
+
+```typescript
+async ping(): Promise {
+ try {
+ await this.connection.query('SELECT 1');
+ return true;
+ } catch {
+ return false;
+ }
+}
+```
+
+### ID Mapping Problems
+
+Ensure all IDs are strings:
+
+```typescript
+// MongoDB
+id: doc._id.toString()
+
+// SQL with numeric IDs
+id: row.id.toString()
+
+// UUID
+id: row.id // Already a string
+```
+
+---
+
+Ready to build your driver? Start with the [Quick Start](#quick-start) guide! 🚀
diff --git a/content/docs/03-development/writing-plugins.mdx b/content/docs/03-development/writing-plugins.mdx
new file mode 100644
index 000000000..b22e61128
--- /dev/null
+++ b/content/docs/03-development/writing-plugins.mdx
@@ -0,0 +1,830 @@
+---
+title: Writing Plugins
+description: Build powerful server-side extensions with custom objects, routes, scheduled jobs, and event listeners.
+---
+
+# Writing Plugins
+
+Plugins are the **primary extension mechanism** in ObjectStack. They allow you to add custom business logic, integrate external services, define new Objects, register API routes, schedule background jobs, and respond to system events.
+
+Think of plugins as **microservices within your ObjectStack runtime** - isolated, versioned, and composable.
+
+---
+
+## 🎯 What Can Plugins Do?
+
+
+
+ Create custom business entities with fields, relationships, and validations
+
+
+
+ Register custom HTTP endpoints for webhooks or integrations
+
+
+
+ Run background tasks on cron schedules
+
+
+
+ React to data changes (onCreate, onUpdate, onDelete)
+
+
+
+ Connect to external databases or data sources
+
+
+
+ Implement custom authorization rules
+
+
+
+---
+
+## 📋 Prerequisites
+
+Before building a plugin, ensure you have:
+
+- **Node.js** 18+ and **npm** 9+
+- **TypeScript** 5+ knowledge
+- **Zod** familiarity (schema validation library)
+- Understanding of [ObjectQL](/docs/02-protocols/01-objectql) and [ObjectOS](/docs/02-protocols/03-objectos)
+
+---
+
+## 🚀 Quick Start
+
+### Step 1: Create a Plugin Project
+
+```bash
+# Using the official generator
+npm create @objectstack/plugin my-crm-plugin
+
+cd my-crm-plugin
+npm install
+```
+
+This generates a project structure:
+
+```
+my-crm-plugin/
+├── src/
+│ ├── index.ts # Plugin entry point
+│ ├── objects/ # Object definitions
+│ │ └── account.object.ts
+│ ├── routes/ # API route handlers
+│ │ └── webhooks.ts
+│ ├── jobs/ # Scheduled tasks
+│ │ └── sync.ts
+│ └── events/ # Event listeners
+│ └── account-created.ts
+├── package.json
+├── tsconfig.json
+└── objectstack.config.ts # Plugin manifest
+```
+
+### Step 2: Define Your Plugin Manifest
+
+The **manifest** (`objectstack.config.ts`) declares your plugin's metadata:
+
+```typescript
+// objectstack.config.ts
+import { defineManifest } from '@objectstack/spec';
+
+export default defineManifest({
+ name: 'my_crm_plugin',
+ version: '1.0.0',
+ label: 'My CRM Plugin',
+ description: 'Customer relationship management for ObjectStack',
+ author: 'Your Name',
+ license: 'MIT',
+
+ // Dependencies
+ dependencies: {
+ '@objectstack/core': '^1.0.0',
+ },
+
+ // Permissions required
+ permissions: [
+ 'object.create',
+ 'object.read',
+ 'api.register',
+ 'schedule.create',
+ ],
+
+ // Configuration schema
+ settings: {
+ apiKey: {
+ type: 'text',
+ label: 'API Key',
+ required: true,
+ sensitive: true,
+ },
+ syncInterval: {
+ type: 'number',
+ label: 'Sync Interval (minutes)',
+ default: 60,
+ },
+ },
+});
+```
+
+### Step 3: Implement the Plugin Lifecycle
+
+```typescript
+// src/index.ts
+import { PluginContext } from '@objectstack/spec';
+import { Account } from './objects/account.object';
+import { registerWebhooks } from './routes/webhooks';
+import { startSyncJob } from './jobs/sync';
+
+export default {
+ /**
+ * Called when the plugin is enabled.
+ * Register objects, routes, jobs, and event listeners here.
+ */
+ onEnable: async (context: PluginContext) => {
+ const { ql, os, logger, router, scheduler, storage } = context;
+
+ logger.info('My CRM Plugin enabled');
+
+ // Register custom objects
+ await ql.registerObject(Account);
+
+ // Register API routes
+ registerWebhooks(router);
+
+ // Schedule background jobs
+ const interval = await os.getConfig('my_crm_plugin.syncInterval');
+ scheduler.schedule('sync-accounts', `*/${interval} * * * *`, () => {
+ return startSyncJob(context);
+ });
+
+ // Listen to events
+ ql.on('account.created', async (event) => {
+ logger.info('New account created', { id: event.record.id });
+ await storage.set(`last_account_id`, event.record.id);
+ });
+ },
+
+ /**
+ * Called when the plugin is disabled.
+ * Clean up resources here.
+ */
+ onDisable: async (context: PluginContext) => {
+ context.logger.info('My CRM Plugin disabled');
+ // Unregister listeners, close connections, etc.
+ },
+
+ /**
+ * Called when plugin settings are updated.
+ */
+ onSettingsChange: async (context: PluginContext, oldSettings, newSettings) => {
+ context.logger.info('Settings updated', { oldSettings, newSettings });
+ },
+};
+```
+
+---
+
+## 🗂️ Defining Custom Objects
+
+Objects are the **core data model** of ObjectStack. Define them using `ObjectSchema`:
+
+```typescript
+// src/objects/account.object.ts
+import { ObjectSchema, Field } from '@objectstack/spec';
+
+export const Account = ObjectSchema.create({
+ name: 'account',
+ label: 'Account',
+ pluralLabel: 'Accounts',
+ icon: 'building',
+ description: 'Customer organizations',
+
+ // Primary display field
+ nameField: 'company_name',
+
+ fields: {
+ // ============================================================================
+ // Basic Information
+ // ============================================================================
+
+ company_name: Field.text({
+ label: 'Company Name',
+ required: true,
+ maxLength: 200,
+ unique: true,
+ }),
+
+ website: Field.url({
+ label: 'Website',
+ }),
+
+ industry: Field.select({
+ label: 'Industry',
+ options: [
+ { label: 'Technology', value: 'tech' },
+ { label: 'Healthcare', value: 'healthcare' },
+ { label: 'Finance', value: 'finance' },
+ { label: 'Retail', value: 'retail' },
+ ],
+ }),
+
+ // ============================================================================
+ // Contact Information
+ // ============================================================================
+
+ phone: Field.phone({
+ label: 'Phone',
+ }),
+
+ email: Field.email({
+ label: 'Email',
+ }),
+
+ billing_address: Field.address({
+ label: 'Billing Address',
+ }),
+
+ // ============================================================================
+ // Business Metrics
+ // ============================================================================
+
+ annual_revenue: Field.currency({
+ label: 'Annual Revenue',
+ currency: 'USD',
+ }),
+
+ employee_count: Field.number({
+ label: 'Employee Count',
+ min: 1,
+ }),
+
+ // ============================================================================
+ // Status & Lifecycle
+ // ============================================================================
+
+ status: Field.select({
+ label: 'Status',
+ options: [
+ { label: 'Prospect', value: 'prospect', default: true },
+ { label: 'Customer', value: 'customer' },
+ { label: 'Churned', value: 'churned' },
+ ],
+ }),
+
+ active: Field.checkbox({
+ label: 'Active',
+ default: true,
+ }),
+
+ // ============================================================================
+ // Relationships
+ // ============================================================================
+
+ parent_account: Field.lookup('account', {
+ label: 'Parent Account',
+ description: 'Parent organization (for subsidiaries)',
+ }),
+
+ owner: Field.lookup('user', {
+ label: 'Account Owner',
+ required: true,
+ defaultValue: '$currentUser',
+ }),
+
+ // ============================================================================
+ // Calculated Fields
+ // ============================================================================
+
+ lifetime_value: Field.formula({
+ label: 'Lifetime Value',
+ returnType: 'number',
+ expression: 'SUM(opportunities.amount WHERE stage = "closed_won")',
+ }),
+
+ days_since_created: Field.formula({
+ label: 'Days Since Created',
+ returnType: 'number',
+ expression: 'DATEDIFF(NOW(), created_at)',
+ }),
+ },
+
+ // ============================================================================
+ // Object Capabilities
+ // ============================================================================
+
+ enable: {
+ apiEnabled: true,
+ trackHistory: true,
+ allowComments: true,
+ allowAttachments: true,
+ searchEnabled: true,
+ },
+
+ // ============================================================================
+ // Indexes for Performance
+ // ============================================================================
+
+ indexes: [
+ { fields: ['company_name'], unique: true },
+ { fields: ['status', 'active'] },
+ { fields: ['owner', 'status'] },
+ ],
+});
+```
+
+---
+
+## 🌐 Registering API Routes
+
+Add custom HTTP endpoints for webhooks, integrations, or custom APIs:
+
+```typescript
+// src/routes/webhooks.ts
+import { Router } from '@objectstack/spec';
+import { z } from 'zod';
+
+const WebhookPayloadSchema = z.object({
+ event: z.enum(['account.created', 'account.updated']),
+ data: z.record(z.any()),
+ timestamp: z.string(),
+});
+
+export function registerWebhooks(router: Router) {
+
+ // ============================================================================
+ // POST /api/webhooks/account
+ // ============================================================================
+
+ router.post('/api/webhooks/account', async (req, res) => {
+ try {
+ // Validate webhook payload
+ const payload = WebhookPayloadSchema.parse(req.body);
+
+ // Verify webhook signature (example)
+ const signature = req.headers['x-webhook-signature'];
+ if (!verifySignature(signature, req.body)) {
+ return res.status(401).json({ error: 'Invalid signature' });
+ }
+
+ // Process the webhook
+ if (payload.event === 'account.created') {
+ await handleAccountCreated(payload.data);
+ }
+
+ res.status(200).json({ success: true });
+
+ } catch (error) {
+ res.status(400).json({ error: error.message });
+ }
+ });
+
+ // ============================================================================
+ // GET /api/integrations/sync
+ // ============================================================================
+
+ router.get('/api/integrations/sync', async (req, res) => {
+ const { ql, logger } = req.context;
+
+ try {
+ // Fetch accounts from external API
+ const externalAccounts = await fetchFromExternalAPI();
+
+ // Sync to ObjectStack
+ for (const account of externalAccounts) {
+ await ql.object('account').upsert({
+ external_id: account.id,
+ company_name: account.name,
+ website: account.website,
+ });
+ }
+
+ logger.info('Sync completed', { count: externalAccounts.length });
+
+ res.json({
+ success: true,
+ synced: externalAccounts.length,
+ });
+
+ } catch (error) {
+ logger.error('Sync failed', { error });
+ res.status(500).json({ error: 'Sync failed' });
+ }
+ });
+}
+
+// Helper functions
+function verifySignature(signature: string, body: any): boolean {
+ // Implement HMAC verification
+ return true;
+}
+
+async function handleAccountCreated(data: any) {
+ // Send notification, trigger workflow, etc.
+}
+
+async function fetchFromExternalAPI() {
+ // Call external API
+ return [];
+}
+```
+
+---
+
+## ⏰ Scheduling Background Jobs
+
+Run tasks periodically using cron expressions:
+
+```typescript
+// src/jobs/sync.ts
+import { PluginContext } from '@objectstack/spec';
+
+export async function startSyncJob(context: PluginContext) {
+ const { ql, os, logger, storage } = context;
+
+ logger.info('Starting account sync job');
+
+ try {
+ // Get last sync timestamp
+ const lastSync = await storage.get('last_sync_time');
+
+ // Fetch updated accounts from external source
+ const apiKey = await os.getConfig('my_crm_plugin.apiKey');
+ const accounts = await fetchAccountsSince(apiKey, lastSync);
+
+ // Upsert to ObjectStack
+ let syncedCount = 0;
+ for (const account of accounts) {
+ await ql.object('account').upsert({
+ external_id: account.id,
+ company_name: account.name,
+ website: account.website,
+ annual_revenue: account.revenue,
+ });
+ syncedCount++;
+ }
+
+ // Update last sync time
+ await storage.set('last_sync_time', new Date().toISOString());
+
+ logger.info('Sync job completed', { synced: syncedCount });
+
+ } catch (error) {
+ logger.error('Sync job failed', { error });
+ throw error;
+ }
+}
+
+async function fetchAccountsSince(apiKey: string, since: string) {
+ // Implement external API call
+ return [];
+}
+```
+
+Register the job in `onEnable`:
+
+```typescript
+scheduler.schedule('sync-accounts', '*/30 * * * *', () => {
+ return startSyncJob(context);
+});
+```
+
+**Cron Expression Examples:**
+
+- `*/15 * * * *` - Every 15 minutes
+- `0 */2 * * *` - Every 2 hours
+- `0 9 * * 1-5` - 9 AM Monday-Friday
+- `0 0 * * 0` - Every Sunday at midnight
+
+---
+
+## 🎧 Event Listeners
+
+React to data changes in real-time:
+
+```typescript
+// src/events/account-created.ts
+import { PluginContext } from '@objectstack/spec';
+
+export function registerEventListeners(context: PluginContext) {
+ const { ql, logger } = context;
+
+ // ============================================================================
+ // Listen to account creation
+ // ============================================================================
+
+ ql.on('account.created', async (event) => {
+ logger.info('Account created', { id: event.record.id });
+
+ // Send welcome email
+ await sendWelcomeEmail(event.record);
+
+ // Create default opportunities
+ await ql.object('opportunity').create({
+ name: `${event.record.company_name} - Discovery`,
+ account: event.record.id,
+ stage: 'discovery',
+ });
+ });
+
+ // ============================================================================
+ // Listen to status changes
+ // ============================================================================
+
+ ql.on('account.updated', async (event) => {
+ const { oldValues, newValues } = event;
+
+ // Check if status changed to "customer"
+ if (oldValues.status !== 'customer' && newValues.status === 'customer') {
+ logger.info('Account converted to customer', { id: event.record.id });
+
+ // Trigger onboarding workflow
+ await triggerOnboarding(event.record);
+ }
+ });
+
+ // ============================================================================
+ // Prevent deletion of active accounts
+ // ============================================================================
+
+ ql.on('account.beforeDelete', async (event) => {
+ if (event.record.active) {
+ throw new Error('Cannot delete active accounts');
+ }
+ });
+}
+
+async function sendWelcomeEmail(account: any) {
+ // Send email
+}
+
+async function triggerOnboarding(account: any) {
+ // Start onboarding flow
+}
+```
+
+**Available Events:**
+
+- `{object}.beforeCreate` - Before record creation
+- `{object}.created` - After record created
+- `{object}.beforeUpdate` - Before update
+- `{object}.updated` - After update
+- `{object}.beforeDelete` - Before deletion
+- `{object}.deleted` - After deletion
+
+---
+
+## 💾 Using Scoped Storage
+
+Each plugin has isolated key-value storage:
+
+```typescript
+// Save data
+await context.storage.set('api_token', 'abc123');
+await context.storage.set('sync_count', 42);
+
+// Retrieve data
+const token = await context.storage.get('api_token');
+const count = await context.storage.get('sync_count');
+
+// Delete data
+await context.storage.delete('api_token');
+
+// Store complex objects (automatically JSON-serialized)
+await context.storage.set('config', {
+ enabled: true,
+ lastRun: new Date(),
+ settings: { foo: 'bar' },
+});
+```
+
+---
+
+## 🧪 Testing Your Plugin
+
+### Unit Tests
+
+```typescript
+// tests/account.test.ts
+import { describe, it, expect } from 'vitest';
+import { Account } from '../src/objects/account.object';
+
+describe('Account Object', () => {
+ it('should have required fields', () => {
+ expect(Account.fields.company_name.required).toBe(true);
+ });
+
+ it('should validate industry options', () => {
+ const validIndustries = Account.fields.industry.options.map(o => o.value);
+ expect(validIndustries).toContain('tech');
+ });
+});
+```
+
+### Integration Tests
+
+```typescript
+// tests/integration.test.ts
+import { createTestContext } from '@objectstack/testing';
+import MyPlugin from '../src/index';
+
+describe('Plugin Integration', () => {
+ it('should register account object', async () => {
+ const context = await createTestContext({
+ plugins: [MyPlugin],
+ });
+
+ const account = await context.ql.object('account').create({
+ company_name: 'Acme Corp',
+ status: 'prospect',
+ });
+
+ expect(account.id).toBeDefined();
+ expect(account.company_name).toBe('Acme Corp');
+ });
+
+ it('should trigger event on creation', async () => {
+ const context = await createTestContext({
+ plugins: [MyPlugin],
+ });
+
+ let eventFired = false;
+ context.ql.on('account.created', () => {
+ eventFired = true;
+ });
+
+ await context.ql.object('account').create({
+ company_name: 'Test Inc',
+ });
+
+ expect(eventFired).toBe(true);
+ });
+});
+```
+
+---
+
+## 📦 Building & Packaging
+
+### Build for Production
+
+```bash
+# Compile TypeScript
+npm run build
+
+# Output: dist/index.js
+```
+
+### Package Structure
+
+```json
+{
+ "name": "@mycompany/objectstack-plugin-crm",
+ "version": "1.0.0",
+ "main": "./dist/index.js",
+ "types": "./dist/index.d.ts",
+ "keywords": ["objectstack", "plugin", "crm"],
+ "files": ["dist", "README.md", "LICENSE"],
+
+ "objectstack": {
+ "type": "plugin",
+ "entry": "./dist/index.js",
+ "manifest": "./dist/objectstack.config.js"
+ },
+
+ "dependencies": {
+ "@objectstack/spec": "^1.0.0"
+ },
+
+ "peerDependencies": {
+ "@objectstack/kernel": "^1.0.0"
+ }
+}
+```
+
+---
+
+## 🚀 Publishing
+
+### To NPM
+
+```bash
+npm login
+npm publish --access public
+```
+
+### To ObjectStack Hub
+
+```bash
+objectstack login
+objectstack publish --registry hub.objectstack.dev
+```
+
+---
+
+## ✅ Best Practices
+
+### 1. Use Zod for Validation
+
+```typescript
+import { z } from 'zod';
+
+const SettingsSchema = z.object({
+ apiUrl: z.string().url(),
+ timeout: z.number().min(1000).max(30000),
+});
+
+const settings = SettingsSchema.parse(userInput);
+```
+
+### 2. Handle Errors Gracefully
+
+```typescript
+try {
+ await externalAPI.call();
+} catch (error) {
+ context.logger.error('External API failed', { error });
+ // Fallback or retry logic
+}
+```
+
+### 3. Use Transactions
+
+```typescript
+const tx = await context.ql.beginTransaction();
+
+try {
+ await tx.object('account').create({ ... });
+ await tx.object('contact').create({ ... });
+ await tx.commit();
+} catch (error) {
+ await tx.rollback();
+ throw error;
+}
+```
+
+### 4. Optimize Queries
+
+```typescript
+// Bad: N+1 queries
+for (const account of accounts) {
+ const contacts = await ql.object('contact').find({ account: account.id });
+}
+
+// Good: Single query with relationships
+const accounts = await ql.object('account').find({
+ include: ['contacts'],
+});
+```
+
+### 5. Document Your Plugin
+
+Include comprehensive README with:
+- Installation instructions
+- Configuration options
+- API endpoints
+- Event triggers
+- Examples
+
+---
+
+## 🔗 Related Resources
+
+- [ObjectQL Protocol](/docs/02-protocols/01-objectql)
+- [ObjectOS Plugin System](/docs/02-protocols/03-objectos)
+- [Custom Drivers](/docs/03-development/server-drivers)
+- [API Reference](/docs/99-reference)
+
+---
+
+## 🆘 Troubleshooting
+
+### Plugin Not Loading
+
+Check the manifest:
+
+```bash
+objectstack validate ./objectstack.config.ts
+```
+
+### Events Not Firing
+
+Ensure you registered listeners in `onEnable`:
+
+```typescript
+ql.on('account.created', handler); // ✅ Correct
+```
+
+### Permission Denied
+
+Add required permissions to manifest:
+
+```typescript
+permissions: ['object.create', 'api.register']
+```
+
+---
+
+Ready to build your plugin? Start with the [Quick Start](#quick-start) guide! 🚀
diff --git a/content/docs/04-transport/error-handling.mdx b/content/docs/04-transport/error-handling.mdx
new file mode 100644
index 000000000..1daccd4c7
--- /dev/null
+++ b/content/docs/04-transport/error-handling.mdx
@@ -0,0 +1,1058 @@
+---
+title: Error Handling
+description: Global error codes, response formats, and debugging strategies for ObjectStack APIs
+---
+
+import { AlertCircle, Bug, Shield, Info, AlertTriangle, XCircle } from 'lucide-react';
+
+# Error Handling
+
+The **Error Handling Protocol** defines standardized error codes, response formats, and debugging strategies across all ObjectStack APIs (HTTP, WebSocket, GraphQL).
+
+## Why Standardized Errors Matter
+
+**Problem:** Traditional APIs return errors inconsistently:
+
+```javascript
+// Different error structures across endpoints 😱
+API 1: { error: "Not found" }
+API 2: { errors: [{ message: "Not found" }] }
+API 3: { success: false, msg: "Not found", code: 404 }
+API 4: HTTP 200 OK with { status: "error", ... }
+```
+
+**Developer pain:**
+- Every endpoint requires custom error handling logic
+- Difficult to show user-friendly messages
+- Debugging is nightmare (where did this error originate?)
+- Monitoring/alerting is inconsistent
+
+**Solution:** ObjectStack enforces a **single error format** across all communication channels. Every error has a machine-readable code, human-readable message, and context for debugging.
+
+## Business Value Delivered
+
+
+ }
+ title="Better User Experience"
+ description="Consistent error messages guide users to resolution. No generic 'Something went wrong' nonsense."
+ />
+ }
+ title="Faster Debugging"
+ description="Error codes + request IDs = find root cause in seconds. Save hours of log hunting."
+ />
+ }
+ title="Automated Monitoring"
+ description="Alert on specific error codes (e.g., RATE_LIMITED spikes = upgrade prompts working)."
+ />
+ }
+ title="Security Hardening"
+ description="Never leak sensitive info in errors. Attackers can't probe your system via error messages."
+ />
+
+
+## Standard Error Response
+
+Every error follows this structure:
+
+```json
+{
+ "success": false,
+ "error": {
+ "code": "ERROR_CODE",
+ "message": "Human-readable description",
+ "details": { /* Additional context */ },
+ "request_id": "req_abc123",
+ "timestamp": "2024-01-16T14:30:00Z"
+ }
+}
+```
+
+**Fields:**
+- `success`: Always `false` for errors
+- `error.code`: Machine-readable error code (use for conditionals)
+- `error.message`: Human-readable message (show to users or developers)
+- `error.details`: Additional context (field names, constraints, etc.)
+- `error.request_id`: Unique request identifier for debugging
+- `error.timestamp`: When error occurred (ISO 8601)
+
+## HTTP Status Codes
+
+ObjectStack uses standard HTTP status codes:
+
+| Status | Meaning | When Used |
+|--------|---------|-----------|
+| **400** | Bad Request | Invalid input, validation failure |
+| **401** | Unauthorized | Authentication required or failed |
+| **403** | Forbidden | Authenticated but insufficient permissions |
+| **404** | Not Found | Resource doesn't exist |
+| **409** | Conflict | Resource already exists or version mismatch |
+| **422** | Unprocessable Entity | Business logic validation failed |
+| **429** | Too Many Requests | Rate limit exceeded |
+| **500** | Internal Server Error | Server-side error |
+| **503** | Service Unavailable | Server overloaded or maintenance |
+
+**Important:** Even on error, response body always includes JSON error object.
+
+## Error Codes
+
+### Authentication & Authorization
+
+#### `UNAUTHORIZED`
+**HTTP Status:** 401
+**Meaning:** No authentication credentials provided or invalid credentials
+
+**Example:**
+```json
+{
+ "success": false,
+ "error": {
+ "code": "UNAUTHORIZED",
+ "message": "Authentication required",
+ "details": {
+ "hint": "Include 'Authorization: Bearer ' header"
+ }
+ }
+}
+```
+
+**How to fix:**
+- Include valid JWT token in `Authorization` header
+- Refresh expired tokens
+- Re-authenticate user
+
+#### `INVALID_TOKEN`
+**HTTP Status:** 401
+**Meaning:** Token is malformed or invalid
+
+**Example:**
+```json
+{
+ "success": false,
+ "error": {
+ "code": "INVALID_TOKEN",
+ "message": "JWT token is invalid",
+ "details": {
+ "reason": "signature_verification_failed"
+ }
+ }
+}
+```
+
+**How to fix:**
+- Check token hasn't been tampered with
+- Verify token is meant for this API (check `aud` claim)
+- Ensure server secret key is correct
+
+#### `TOKEN_EXPIRED`
+**HTTP Status:** 401
+**Meaning:** JWT token has expired
+
+**Example:**
+```json
+{
+ "success": false,
+ "error": {
+ "code": "TOKEN_EXPIRED",
+ "message": "JWT token expired",
+ "details": {
+ "expired_at": "2024-01-16T10:00:00Z",
+ "current_time": "2024-01-16T14:30:00Z"
+ }
+ }
+}
+```
+
+**How to fix:**
+- Refresh token using refresh token flow
+- Re-authenticate user
+- Check token lifetime settings (typically 15-60 minutes)
+
+#### `FORBIDDEN`
+**HTTP Status:** 403
+**Meaning:** Authenticated but insufficient permissions
+
+**Example:**
+```json
+{
+ "success": false,
+ "error": {
+ "code": "FORBIDDEN",
+ "message": "Insufficient permissions to access this resource",
+ "details": {
+ "required_permission": "account:write",
+ "user_permissions": ["account:read"]
+ }
+ }
+}
+```
+
+**How to fix:**
+- Request permission from administrator
+- Check row-level security rules
+- Verify user role assignments
+
+### Validation Errors
+
+#### `VALIDATION_ERROR`
+**HTTP Status:** 400
+**Meaning:** Input validation failed (schema validation)
+
+**Example:**
+```json
+{
+ "success": false,
+ "error": {
+ "code": "VALIDATION_ERROR",
+ "message": "Validation failed for 2 fields",
+ "details": {
+ "fields": [
+ {
+ "field": "email",
+ "message": "Invalid email format",
+ "constraint": "format",
+ "value": "not-an-email"
+ },
+ {
+ "field": "age",
+ "message": "Must be at least 18",
+ "constraint": "min",
+ "value": 15,
+ "expected": 18
+ }
+ ]
+ }
+ }
+}
+```
+
+**How to fix:**
+- Check field constraints in object schema (`GET /api/meta/objects/{object}`)
+- Validate input client-side before submission
+- Show field-specific errors in UI
+
+**Client-side handling:**
+```javascript
+if (error.code === 'VALIDATION_ERROR') {
+ error.details.fields.forEach(({ field, message }) => {
+ showFieldError(field, message);
+ });
+}
+```
+
+#### `REQUIRED_FIELD`
+**HTTP Status:** 400
+**Meaning:** Required field is missing
+
+**Example:**
+```json
+{
+ "success": false,
+ "error": {
+ "code": "REQUIRED_FIELD",
+ "message": "Missing required field: name",
+ "details": {
+ "field": "name",
+ "constraint": "required"
+ }
+ }
+}
+```
+
+#### `INVALID_TYPE`
+**HTTP Status:** 400
+**Meaning:** Field value has wrong type
+
+**Example:**
+```json
+{
+ "success": false,
+ "error": {
+ "code": "INVALID_TYPE",
+ "message": "Field 'age' must be a number",
+ "details": {
+ "field": "age",
+ "expected_type": "number",
+ "actual_type": "string",
+ "value": "twenty-five"
+ }
+ }
+}
+```
+
+### Resource Errors
+
+#### `NOT_FOUND`
+**HTTP Status:** 404
+**Meaning:** Requested resource doesn't exist
+
+**Example:**
+```json
+{
+ "success": false,
+ "error": {
+ "code": "NOT_FOUND",
+ "message": "Account with id 'acc_999' not found",
+ "details": {
+ "resource": "account",
+ "resource_id": "acc_999"
+ }
+ }
+}
+```
+
+**How to fix:**
+- Verify resource ID is correct
+- Check user has permission to see resource (row-level security)
+- Resource may have been deleted
+
+#### `ALREADY_EXISTS`
+**HTTP Status:** 409
+**Meaning:** Resource with unique constraint already exists
+
+**Example:**
+```json
+{
+ "success": false,
+ "error": {
+ "code": "ALREADY_EXISTS",
+ "message": "Account with email 'john@acme.com' already exists",
+ "details": {
+ "resource": "account",
+ "constraint": "unique",
+ "field": "email",
+ "value": "john@acme.com"
+ }
+ }
+}
+```
+
+**How to fix:**
+- Check for existing resource before creating
+- Update existing resource instead of creating new one
+- Use different value for unique field
+
+#### `CONSTRAINT_VIOLATION`
+**HTTP Status:** 409
+**Meaning:** Operation violates database constraint
+
+**Example:**
+```json
+{
+ "success": false,
+ "error": {
+ "code": "CONSTRAINT_VIOLATION",
+ "message": "Cannot delete account with active opportunities",
+ "details": {
+ "resource": "account",
+ "resource_id": "acc_123",
+ "constraint": "foreign_key",
+ "related_object": "opportunity",
+ "related_count": 5
+ }
+ }
+}
+```
+
+**How to fix:**
+- Delete related records first
+- Enable cascade delete on object schema
+- Archive instead of delete (soft delete)
+
+### Rate Limiting
+
+#### `RATE_LIMITED`
+**HTTP Status:** 429
+**Meaning:** Too many requests, rate limit exceeded
+
+**Example:**
+```json
+{
+ "success": false,
+ "error": {
+ "code": "RATE_LIMITED",
+ "message": "Rate limit exceeded",
+ "details": {
+ "limit": 1000,
+ "window": "1m",
+ "retry_after": 45,
+ "quota_reset": "2024-01-16T14:31:00Z"
+ }
+ }
+}
+```
+
+**HTTP Headers:**
+```http
+HTTP/1.1 429 Too Many Requests
+X-RateLimit-Limit: 1000
+X-RateLimit-Remaining: 0
+X-RateLimit-Reset: 1705412460
+Retry-After: 45
+```
+
+**How to fix:**
+- Implement exponential backoff
+- Batch requests to reduce call count
+- Upgrade to higher tier for increased limits
+- Cache responses to avoid repeated calls
+
+**Client-side handling:**
+```javascript
+async function fetchWithRetry(url, options = {}, maxRetries = 3) {
+ for (let i = 0; i < maxRetries; i++) {
+ const response = await fetch(url, options);
+
+ if (response.status !== 429) {
+ return response;
+ }
+
+ const retryAfter = response.headers.get('Retry-After');
+ await sleep(retryAfter * 1000);
+ }
+
+ throw new Error('Max retries exceeded');
+}
+```
+
+#### `QUOTA_EXCEEDED`
+**HTTP Status:** 429
+**Meaning:** Monthly/daily quota exceeded
+
+**Example:**
+```json
+{
+ "success": false,
+ "error": {
+ "code": "QUOTA_EXCEEDED",
+ "message": "Monthly API quota exceeded",
+ "details": {
+ "quota": 10000,
+ "used": 10000,
+ "period": "monthly",
+ "reset": "2024-02-01T00:00:00Z",
+ "upgrade_url": "https://app.acme.com/billing/upgrade"
+ }
+ }
+}
+```
+
+**How to fix:**
+- Wait for quota reset
+- Upgrade to higher plan
+- Optimize API usage
+
+### Business Logic Errors
+
+#### `BUSINESS_RULE_VIOLATION`
+**HTTP Status:** 422
+**Meaning:** Operation violates business logic rule
+
+**Example:**
+```json
+{
+ "success": false,
+ "error": {
+ "code": "BUSINESS_RULE_VIOLATION",
+ "message": "Cannot close opportunity without selecting a stage reason",
+ "details": {
+ "rule": "opportunity_close_validation",
+ "field": "stage_reason",
+ "required_when": "stage === 'Closed Won' || stage === 'Closed Lost'"
+ }
+ }
+}
+```
+
+**How to fix:**
+- Check validation rules in object schema
+- Provide required fields
+- Follow business process workflow
+
+#### `WORKFLOW_ERROR`
+**HTTP Status:** 422
+**Meaning:** Workflow/automation failed
+
+**Example:**
+```json
+{
+ "success": false,
+ "error": {
+ "code": "WORKFLOW_ERROR",
+ "message": "Approval workflow rejected the request",
+ "details": {
+ "workflow": "purchase_order_approval",
+ "step": "manager_approval",
+ "reason": "Amount exceeds manager approval limit",
+ "limit": 10000,
+ "requested": 15000
+ }
+ }
+}
+```
+
+### Server Errors
+
+#### `SERVER_ERROR`
+**HTTP Status:** 500
+**Meaning:** Internal server error
+
+**Example:**
+```json
+{
+ "success": false,
+ "error": {
+ "code": "SERVER_ERROR",
+ "message": "An internal error occurred",
+ "details": {
+ "request_id": "req_abc123",
+ "support_url": "https://support.acme.com/request/req_abc123"
+ }
+ }
+}
+```
+
+**Important:** Never leak stack traces or sensitive internals to clients.
+
+**How to fix:**
+- Retry request (may be transient)
+- Check server status page
+- Contact support with `request_id`
+
+#### `SERVICE_UNAVAILABLE`
+**HTTP Status:** 503
+**Meaning:** Server temporarily unavailable
+
+**Example:**
+```json
+{
+ "success": false,
+ "error": {
+ "code": "SERVICE_UNAVAILABLE",
+ "message": "Service temporarily unavailable",
+ "details": {
+ "reason": "database_maintenance",
+ "retry_after": 300,
+ "estimated_completion": "2024-01-16T15:00:00Z"
+ }
+ }
+}
+```
+
+**HTTP Headers:**
+```http
+HTTP/1.1 503 Service Unavailable
+Retry-After: 300
+```
+
+### WebSocket-Specific Errors
+
+#### `CONNECTION_LIMIT_EXCEEDED`
+**Meaning:** Too many concurrent WebSocket connections
+
+**Example:**
+```json
+{
+ "type": "error",
+ "error": {
+ "code": "CONNECTION_LIMIT_EXCEEDED",
+ "message": "Maximum 5 concurrent connections per user",
+ "details": {
+ "limit": 5,
+ "current": 5
+ }
+ }
+}
+```
+
+**How to fix:**
+- Close unused connections
+- Implement connection pooling
+- Use fewer browser tabs
+
+#### `SUBSCRIPTION_LIMIT_EXCEEDED`
+**Meaning:** Too many subscriptions per connection
+
+**Example:**
+```json
+{
+ "type": "error",
+ "subscription_id": "sub_99",
+ "error": {
+ "code": "SUBSCRIPTION_LIMIT_EXCEEDED",
+ "message": "Maximum 50 subscriptions per connection",
+ "details": {
+ "limit": 50,
+ "current": 50
+ }
+ }
+}
+```
+
+**How to fix:**
+- Unsubscribe from unused subscriptions
+- Use broader filters instead of many narrow subscriptions
+- Combine related subscriptions
+
+#### `INVALID_MESSAGE`
+**Meaning:** WebSocket message is malformed
+
+**Example:**
+```json
+{
+ "type": "error",
+ "error": {
+ "code": "INVALID_MESSAGE",
+ "message": "Invalid JSON in WebSocket message",
+ "details": {
+ "reason": "unexpected_token",
+ "position": 42
+ }
+ }
+}
+```
+
+## Error Response Examples
+
+### Validation Error (Multiple Fields)
+
+**Request:**
+```http
+POST /api/v1/data/account
+Content-Type: application/json
+
+{
+ "name": "",
+ "email": "not-an-email",
+ "revenue": -1000
+}
+```
+
+**Response:**
+```http
+HTTP/1.1 400 Bad Request
+Content-Type: application/json
+
+{
+ "success": false,
+ "error": {
+ "code": "VALIDATION_ERROR",
+ "message": "Validation failed for 3 fields",
+ "details": {
+ "fields": [
+ {
+ "field": "name",
+ "message": "Name is required",
+ "constraint": "required",
+ "value": ""
+ },
+ {
+ "field": "email",
+ "message": "Invalid email format",
+ "constraint": "format",
+ "value": "not-an-email"
+ },
+ {
+ "field": "revenue",
+ "message": "Revenue must be positive",
+ "constraint": "min",
+ "value": -1000,
+ "expected": 0
+ }
+ ]
+ },
+ "request_id": "req_abc123",
+ "timestamp": "2024-01-16T14:30:00Z"
+ }
+}
+```
+
+### Permission Denied
+
+**Request:**
+```http
+DELETE /api/v1/data/account/acc_123
+Authorization: Bearer
+```
+
+**Response:**
+```http
+HTTP/1.1 403 Forbidden
+Content-Type: application/json
+
+{
+ "success": false,
+ "error": {
+ "code": "FORBIDDEN",
+ "message": "Insufficient permissions to delete accounts",
+ "details": {
+ "resource": "account",
+ "resource_id": "acc_123",
+ "required_permission": "account:delete",
+ "user_permissions": ["account:read", "account:write"],
+ "hint": "Contact your administrator to request delete permission"
+ },
+ "request_id": "req_def456",
+ "timestamp": "2024-01-16T14:35:00Z"
+ }
+}
+```
+
+### Rate Limit Exceeded
+
+**Request:**
+```http
+GET /api/v1/data/task
+Authorization: Bearer
+```
+
+**Response:**
+```http
+HTTP/1.1 429 Too Many Requests
+X-RateLimit-Limit: 1000
+X-RateLimit-Remaining: 0
+X-RateLimit-Reset: 1705412460
+Retry-After: 45
+Content-Type: application/json
+
+{
+ "success": false,
+ "error": {
+ "code": "RATE_LIMITED",
+ "message": "Rate limit exceeded: 1000 requests per minute",
+ "details": {
+ "limit": 1000,
+ "window": "1m",
+ "retry_after": 45,
+ "quota_reset": "2024-01-16T14:31:00Z",
+ "upgrade_url": "https://app.acme.com/billing/upgrade"
+ },
+ "request_id": "req_ghi789",
+ "timestamp": "2024-01-16T14:30:15Z"
+ }
+}
+```
+
+## Error Handling Best Practices
+
+### ✅ Use Error Codes, Not Messages
+
+**Bad:**
+```javascript
+if (error.message.includes('not found')) {
+ // Brittle - breaks if message changes
+}
+```
+
+**Good:**
+```javascript
+if (error.code === 'NOT_FOUND') {
+ // Reliable - code never changes
+}
+```
+
+### ✅ Show User-Friendly Messages
+
+**Bad:**
+```javascript
+alert(error.message); // "VALIDATION_ERROR: Field 'email' constraint 'format' failed"
+```
+
+**Good:**
+```javascript
+const userMessages = {
+ 'VALIDATION_ERROR': 'Please check your input and try again',
+ 'UNAUTHORIZED': 'Please log in to continue',
+ 'RATE_LIMITED': 'Too many requests. Please wait a moment.',
+};
+
+showToast(userMessages[error.code] || 'An error occurred');
+```
+
+### ✅ Handle Field-Specific Validation Errors
+
+**Good:**
+```javascript
+async function handleSubmit(data) {
+ try {
+ const response = await api.createAccount(data);
+ return response.data;
+ } catch (error) {
+ if (error.code === 'VALIDATION_ERROR') {
+ // Show errors next to fields
+ error.details.fields.forEach(({ field, message }) => {
+ setFieldError(field, message);
+ });
+ } else {
+ // Show general error
+ showToast(error.message, 'error');
+ }
+ throw error;
+ }
+}
+```
+
+### ✅ Implement Retry Logic
+
+**Good:**
+```javascript
+async function fetchWithRetry(url, options = {}, maxRetries = 3) {
+ let lastError;
+
+ for (let attempt = 0; attempt < maxRetries; attempt++) {
+ try {
+ const response = await fetch(url, options);
+ const data = await response.json();
+
+ if (!response.ok) {
+ // Check if error is retryable
+ if (data.error.code === 'RATE_LIMITED') {
+ const retryAfter = data.error.details.retry_after || 1;
+ await sleep(retryAfter * 1000);
+ continue;
+ } else if (data.error.code === 'SERVER_ERROR') {
+ // Exponential backoff
+ await sleep(Math.pow(2, attempt) * 1000);
+ continue;
+ } else {
+ // Don't retry validation errors, auth errors, etc.
+ throw new APIError(data.error);
+ }
+ }
+
+ return data;
+ } catch (error) {
+ lastError = error;
+ }
+ }
+
+ throw lastError;
+}
+```
+
+### ✅ Log Request IDs for Debugging
+
+**Good:**
+```javascript
+try {
+ await api.createAccount(data);
+} catch (error) {
+ console.error('Account creation failed', {
+ request_id: error.request_id,
+ code: error.code,
+ message: error.message,
+ timestamp: error.timestamp
+ });
+
+ // Send to error tracking service
+ Sentry.captureException(error, {
+ extra: { request_id: error.request_id }
+ });
+}
+```
+
+### ✅ Handle Network Errors
+
+**Good:**
+```javascript
+try {
+ const response = await fetch('/api/data/task');
+ const data = await response.json();
+
+ if (!data.success) {
+ throw new APIError(data.error);
+ }
+
+ return data.data;
+} catch (error) {
+ if (error instanceof TypeError && error.message === 'Failed to fetch') {
+ // Network error - server unreachable
+ showToast('Network error. Please check your connection.', 'error');
+ } else if (error instanceof APIError) {
+ // API returned error
+ handleAPIError(error);
+ } else {
+ // Unknown error
+ console.error('Unexpected error:', error);
+ showToast('An unexpected error occurred', 'error');
+ }
+}
+```
+
+## Debugging with Request IDs
+
+Every API response includes a `request_id` for debugging:
+
+**Request:**
+```http
+POST /api/v1/data/account
+Content-Type: application/json
+X-Request-ID: my-custom-id-123
+
+{ "name": "Acme Corp" }
+```
+
+**Response:**
+```json
+{
+ "success": true,
+ "data": { ... },
+ "request_id": "my-custom-id-123"
+}
+```
+
+**Server logs:**
+```
+[2024-01-16T14:30:00Z] INFO [my-custom-id-123] POST /api/v1/data/account
+[2024-01-16T14:30:00Z] DEBUG [my-custom-id-123] Validating input
+[2024-01-16T14:30:00Z] DEBUG [my-custom-id-123] Executing query: INSERT INTO accounts...
+[2024-01-16T14:30:00Z] INFO [my-custom-id-123] Request completed in 45ms
+```
+
+**Use request IDs to:**
+- Trace request through logs
+- Debug distributed systems
+- Report issues to support
+- Correlate frontend errors with backend logs
+
+## Monitoring & Alerting
+
+### Error Rate Monitoring
+
+Track error rates by code:
+
+```javascript
+// Metrics dashboard
+{
+ "error_rates": {
+ "VALIDATION_ERROR": 0.05, // 5% of requests
+ "UNAUTHORIZED": 0.02, // 2% of requests
+ "RATE_LIMITED": 0.01, // 1% of requests
+ "SERVER_ERROR": 0.0001 // 0.01% of requests (🚨 alert if > 0.01%)
+ }
+}
+```
+
+### Alert Conditions
+
+**Critical alerts:**
+- `SERVER_ERROR` rate > 0.1%
+- `SERVICE_UNAVAILABLE` > 0
+- Database connection failures
+
+**Warning alerts:**
+- `RATE_LIMITED` spike (may indicate DDoS or integration bug)
+- `UNAUTHORIZED` spike (credential leakage?)
+- `VALIDATION_ERROR` spike on new form (bad client-side validation)
+
+### Error Budgets
+
+Set error budgets per service:
+
+```yaml
+error_budget:
+ target_success_rate: 99.9%
+ measurement_window: 30d
+ budget_remaining: 97.2% # Still have 97.2% of error budget left
+```
+
+**When budget exhausted:**
+- Freeze feature releases
+- Focus on reliability improvements
+- Investigate root causes
+
+## Security Considerations
+
+### ❌ Never Leak Sensitive Info
+
+**Bad:**
+```json
+{
+ "error": {
+ "code": "UNAUTHORIZED",
+ "message": "Password incorrect for user john@acme.com",
+ "details": {
+ "attempted_password": "Password123!", // 🚨 NEVER DO THIS
+ "actual_password_hash": "bcrypt$..." // 🚨 NEVER DO THIS
+ }
+ }
+}
+```
+
+**Good:**
+```json
+{
+ "error": {
+ "code": "UNAUTHORIZED",
+ "message": "Invalid credentials",
+ "details": null
+ }
+}
+```
+
+### ❌ Don't Confirm Resource Existence
+
+**Bad:**
+```json
+// Attacker probes: DELETE /api/data/account/acc_123
+{
+ "error": {
+ "code": "FORBIDDEN",
+ "message": "You don't have permission to delete this account"
+ }
+}
+// Attacker learns: Account acc_123 exists! 🚨
+```
+
+**Good:**
+```json
+// Return NOT_FOUND for both "doesn't exist" and "exists but no permission"
+{
+ "error": {
+ "code": "NOT_FOUND",
+ "message": "Account not found"
+ }
+}
+```
+
+### ✅ Rate Limit Error Responses
+
+Even error responses can be abused:
+
+```javascript
+// Attacker tries to enumerate user emails
+for (let i = 0; i < 1000000; i++) {
+ await register({ email: `user${i}@example.com` });
+ // Response: "ALREADY_EXISTS" or "VALIDATION_ERROR"
+}
+```
+
+**Solution:** Rate limit failed registration attempts:
+```json
+{
+ "error": {
+ "code": "RATE_LIMITED",
+ "message": "Too many failed registration attempts"
+ }
+}
+```
+
+## Next Steps
+
+
+ }
+ title="HTTP API"
+ description="Learn REST endpoint conventions and CRUD operations"
+ href="/docs/transport/http-api"
+ />
+ }
+ title="Real-Time Protocols"
+ description="Implement WebSocket subscriptions and event streaming"
+ href="/docs/transport/realtime"
+ />
+
diff --git a/content/docs/04-transport/http-api.mdx b/content/docs/04-transport/http-api.mdx
new file mode 100644
index 000000000..822cf33c0
--- /dev/null
+++ b/content/docs/04-transport/http-api.mdx
@@ -0,0 +1,933 @@
+---
+title: HTTP API
+description: Standard REST mapping rules, CRUD operations, and request/response formats for ObjectStack
+---
+
+import { Radio, Code, Database, Lock, Zap, CheckCircle } from 'lucide-react';
+
+# HTTP API
+
+The **HTTP API** defines how ObjectStack maps data operations to RESTful HTTP endpoints. Every object you define automatically gets a complete set of CRUD (Create, Read, Update, Delete) operations with consistent request/response formats.
+
+## Core Principles
+
+1. **Convention over Configuration:** REST endpoints follow predictable patterns
+2. **Consistency:** Every object uses the same URL structure and response format
+3. **Discoverability:** API schema available via discovery endpoint
+4. **Security First:** Authentication and permissions enforced on every request
+5. **Performance:** Built-in caching, pagination, and field selection
+
+## API Discovery
+
+### Discovery Endpoint
+
+Before making any API calls, clients should request the discovery endpoint to learn about available services:
+
+**Request:**
+```http
+GET /.well-known/objectstack HTTP/1.1
+Host: api.acme.com
+```
+
+**Alternative endpoint:**
+```http
+GET /api/v1/discovery HTTP/1.1
+```
+
+**Response:**
+```json
+{
+ "name": "Acme CRM Production",
+ "version": "2.1.0",
+ "environment": "production",
+ "routes": {
+ "data": "/api/v1/data",
+ "metadata": "/api/v1/meta",
+ "auth": "/api/v1/auth",
+ "actions": "/api/v1/actions",
+ "storage": "/api/v1/storage",
+ "graphql": "/api/v1/graphql",
+ "realtime": "wss://api.acme.com/ws"
+ },
+ "features": {
+ "graphql": true,
+ "websocket": true,
+ "search": true,
+ "files": true,
+ "batch": true,
+ "webhooks": true
+ },
+ "limits": {
+ "max_page_size": 100,
+ "default_page_size": 25,
+ "max_batch_size": 50,
+ "rate_limit": 1000,
+ "rate_window": "1m"
+ },
+ "locale": {
+ "default": "en-US",
+ "supported": ["en-US", "zh-CN", "es-ES", "fr-FR"],
+ "timezone": "America/Los_Angeles"
+ },
+ "documentation": "https://docs.acme.com/api"
+}
+```
+
+**Why discovery matters:**
+- **Environment agnostic:** Works across dev, staging, production without hardcoding URLs
+- **Version tolerance:** API routes can change without breaking clients
+- **Feature detection:** Clients enable/disable features based on server capabilities
+- **Automatic configuration:** SDKs auto-configure from discovery response
+
+## Standard Data API
+
+All data operations use the base path from `routes.data` (default: `/api/v1/data`).
+
+### URL Structure
+
+```
+{base_path}/{object_name}/{record_id?}
+```
+
+**Examples:**
+- `/api/v1/data/account` - Account collection
+- `/api/v1/data/account/acc_123` - Specific account
+- `/api/v1/data/project_task` - Project task collection (snake_case)
+
+### Authentication
+
+All requests require authentication via one of these methods:
+
+**1. Bearer Token (JWT):**
+```http
+GET /api/v1/data/task
+Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...
+```
+
+**2. API Key:**
+```http
+GET /api/v1/data/task
+X-API-Key: sk_live_abc123...
+```
+
+**3. Session Cookie:**
+```http
+GET /api/v1/data/task
+Cookie: session_id=xyz789...
+```
+
+### Query Operations (List/Search)
+
+Retrieve multiple records from an object.
+
+**Endpoint:**
+```http
+GET /{base_path}/{object_name}
+```
+
+**Query Parameters:**
+
+| Parameter | Type | Description | Example |
+|-----------|------|-------------|---------|
+| `select` | string | Comma-separated field list | `id,name,status` |
+| `filter` | JSON | Filter criteria (see Filtering section) | `{"status":"active"}` |
+| `sort` | string | Sort fields (prefix `-` for desc) | `-created_at,name` |
+| `page` | number | Page number (1-indexed) | `2` |
+| `per_page` | number | Items per page (max from limits) | `50` |
+| `include` | string | Related objects to embed | `assignee,comments` |
+
+**Example Request:**
+```http
+GET /api/v1/data/task?select=id,title,status&filter={"assignee_id":"user_123"}&sort=-created_at&page=1&per_page=25
+Authorization: Bearer
+```
+
+**Success Response:**
+```json
+{
+ "success": true,
+ "data": [
+ {
+ "id": "task_456",
+ "title": "Implement login page",
+ "status": "in_progress",
+ "created_at": "2024-01-15T10:30:00Z"
+ },
+ {
+ "id": "task_789",
+ "title": "Fix navigation bug",
+ "status": "todo",
+ "created_at": "2024-01-14T16:20:00Z"
+ }
+ ],
+ "pagination": {
+ "page": 1,
+ "per_page": 25,
+ "total": 47,
+ "total_pages": 2,
+ "has_next": true,
+ "has_prev": false
+ }
+}
+```
+
+### Filtering
+
+Filters are passed as JSON in the `filter` query parameter.
+
+**Basic equality:**
+```json
+{ "status": "active" }
+```
+```http
+GET /api/data/account?filter={"status":"active"}
+```
+
+**Multiple conditions (AND):**
+```json
+{
+ "status": "active",
+ "industry": "Technology"
+}
+```
+
+**Operators:**
+```json
+{
+ "revenue": { "$gte": 100000 },
+ "employees": { "$lte": 500 },
+ "name": { "$contains": "Tech" },
+ "created_at": { "$between": ["2024-01-01", "2024-12-31"] }
+}
+```
+
+**Supported operators:**
+- `$eq` - Equals (default)
+- `$ne` - Not equals
+- `$gt` - Greater than
+- `$gte` - Greater than or equal
+- `$lt` - Less than
+- `$lte` - Less than or equal
+- `$in` - In array
+- `$nin` - Not in array
+- `$contains` - String contains
+- `$startsWith` - String starts with
+- `$endsWith` - String ends with
+- `$between` - Between two values
+- `$null` - Is null
+- `$notNull` - Is not null
+
+**OR conditions:**
+```json
+{
+ "$or": [
+ { "status": "urgent" },
+ { "priority": "high" }
+ ]
+}
+```
+
+**Complex nested filters:**
+```json
+{
+ "$and": [
+ { "status": "active" },
+ {
+ "$or": [
+ { "industry": "Technology" },
+ { "industry": "SaaS" }
+ ]
+ },
+ { "revenue": { "$gte": 1000000 } }
+ ]
+}
+```
+
+### Sorting
+
+Sort by one or more fields using the `sort` parameter:
+
+**Single field ascending:**
+```http
+GET /api/data/account?sort=name
+```
+
+**Single field descending (prefix with `-`):**
+```http
+GET /api/data/account?sort=-created_at
+```
+
+**Multiple fields:**
+```http
+GET /api/data/account?sort=-priority,created_at
+```
+First sort by priority descending, then by created_at ascending.
+
+### Pagination
+
+ObjectStack uses offset-based pagination:
+
+**Request page 2 with 50 items:**
+```http
+GET /api/data/account?page=2&per_page=50
+```
+
+**Response includes pagination metadata:**
+```json
+{
+ "success": true,
+ "data": [...],
+ "pagination": {
+ "page": 2,
+ "per_page": 50,
+ "total": 247,
+ "total_pages": 5,
+ "has_next": true,
+ "has_prev": true
+ }
+}
+```
+
+**Pagination limits:**
+- Default page size: 25 (from discovery `limits.default_page_size`)
+- Maximum page size: 100 (from discovery `limits.max_page_size`)
+- Requesting `per_page > max_page_size` returns HTTP 400
+
+### Field Selection
+
+Request only the fields you need to reduce payload size:
+
+**Request:**
+```http
+GET /api/data/account?select=id,name,industry,revenue
+```
+
+**Response:**
+```json
+{
+ "success": true,
+ "data": [
+ {
+ "id": "acc_123",
+ "name": "Acme Corp",
+ "industry": "Technology",
+ "revenue": 5000000
+ }
+ ]
+}
+```
+
+**Benefits:**
+- Reduced bandwidth (especially for mobile)
+- Faster response times
+- Lower server CPU usage
+
+**Note:** System fields (`id`, `created_at`, `updated_at`) are always included even if not in `select`.
+
+### Including Related Objects
+
+Embed related objects to avoid N+1 queries:
+
+**Request:**
+```http
+GET /api/data/task?include=assignee,project
+```
+
+**Response:**
+```json
+{
+ "success": true,
+ "data": [
+ {
+ "id": "task_123",
+ "title": "Implement API",
+ "assignee_id": "user_456",
+ "project_id": "proj_789",
+ "assignee": {
+ "id": "user_456",
+ "name": "John Doe",
+ "email": "john@acme.com"
+ },
+ "project": {
+ "id": "proj_789",
+ "name": "CRM Rebuild",
+ "status": "active"
+ }
+ }
+ ]
+}
+```
+
+**Multiple levels:**
+```http
+GET /api/data/task?include=assignee.department,project.owner
+```
+
+**Limits:**
+- Maximum include depth: 3 levels
+- Maximum included relations: 5 per request
+
+### Retrieve Single Record
+
+Get a specific record by ID.
+
+**Endpoint:**
+```http
+GET /{base_path}/{object_name}/{record_id}
+```
+
+**Example Request:**
+```http
+GET /api/v1/data/account/acc_123
+Authorization: Bearer
+```
+
+**Success Response (HTTP 200):**
+```json
+{
+ "success": true,
+ "data": {
+ "id": "acc_123",
+ "name": "Acme Corporation",
+ "industry": "Technology",
+ "revenue": 5000000,
+ "status": "active",
+ "owner_id": "user_456",
+ "created_at": "2024-01-10T14:30:00Z",
+ "updated_at": "2024-01-15T09:20:00Z"
+ }
+}
+```
+
+**Not Found (HTTP 404):**
+```json
+{
+ "success": false,
+ "error": {
+ "code": "NOT_FOUND",
+ "message": "Account with id 'acc_999' not found",
+ "resource": "account",
+ "resource_id": "acc_999"
+ }
+}
+```
+
+### Create Record
+
+Create a new record.
+
+**Endpoint:**
+```http
+POST /{base_path}/{object_name}
+```
+
+**Request:**
+```http
+POST /api/v1/data/account
+Authorization: Bearer
+Content-Type: application/json
+
+{
+ "name": "TechStart Inc",
+ "industry": "SaaS",
+ "revenue": 250000,
+ "owner_id": "user_789"
+}
+```
+
+**Success Response (HTTP 201):**
+```json
+{
+ "success": true,
+ "data": {
+ "id": "acc_124",
+ "name": "TechStart Inc",
+ "industry": "SaaS",
+ "revenue": 250000,
+ "status": "active",
+ "owner_id": "user_789",
+ "created_at": "2024-01-16T10:15:00Z",
+ "updated_at": "2024-01-16T10:15:00Z"
+ }
+}
+```
+
+**Validation Error (HTTP 400):**
+```json
+{
+ "success": false,
+ "error": {
+ "code": "VALIDATION_ERROR",
+ "message": "Validation failed",
+ "fields": [
+ {
+ "field": "name",
+ "message": "Name is required",
+ "constraint": "required"
+ },
+ {
+ "field": "industry",
+ "message": "Must be one of: Technology, SaaS, Healthcare, Finance",
+ "constraint": "enum",
+ "value": "InvalidIndustry"
+ }
+ ]
+ }
+}
+```
+
+### Update Record
+
+Update an existing record (partial update).
+
+**Endpoint:**
+```http
+PATCH /{base_path}/{object_name}/{record_id}
+```
+
+**Request:**
+```http
+PATCH /api/v1/data/account/acc_123
+Authorization: Bearer
+Content-Type: application/json
+
+{
+ "revenue": 6000000,
+ "status": "vip"
+}
+```
+
+**Success Response (HTTP 200):**
+```json
+{
+ "success": true,
+ "data": {
+ "id": "acc_123",
+ "name": "Acme Corporation",
+ "industry": "Technology",
+ "revenue": 6000000,
+ "status": "vip",
+ "owner_id": "user_456",
+ "created_at": "2024-01-10T14:30:00Z",
+ "updated_at": "2024-01-16T11:45:00Z"
+ }
+}
+```
+
+**Note:** Only fields included in the request body are updated. Other fields remain unchanged.
+
+**Read-only fields:**
+Attempting to update read-only fields (e.g., `id`, `created_at`) returns HTTP 400:
+
+```json
+{
+ "success": false,
+ "error": {
+ "code": "VALIDATION_ERROR",
+ "message": "Cannot update read-only fields",
+ "fields": [
+ {
+ "field": "created_at",
+ "message": "Field is read-only"
+ }
+ ]
+ }
+}
+```
+
+### Delete Record
+
+Delete a record by ID.
+
+**Endpoint:**
+```http
+DELETE /{base_path}/{object_name}/{record_id}
+```
+
+**Request:**
+```http
+DELETE /api/v1/data/account/acc_123
+Authorization: Bearer
+```
+
+**Success Response (HTTP 200):**
+```json
+{
+ "success": true,
+ "data": {
+ "id": "acc_123",
+ "deleted": true
+ }
+}
+```
+
+**Soft Delete (if enabled):**
+If object has `enable.softDelete`, record is marked deleted but not removed:
+
+```json
+{
+ "success": true,
+ "data": {
+ "id": "acc_123",
+ "deleted": true,
+ "deleted_at": "2024-01-16T12:00:00Z",
+ "deleted_by": "user_456"
+ }
+}
+```
+
+**Cascade Considerations:**
+If object has related records and cascade delete is not enabled:
+
+```json
+{
+ "success": false,
+ "error": {
+ "code": "CONSTRAINT_VIOLATION",
+ "message": "Cannot delete account with active opportunities",
+ "constraint": "foreign_key",
+ "related_object": "opportunity",
+ "related_count": 5
+ }
+}
+```
+
+## Batch Operations
+
+Perform multiple operations in a single request.
+
+**Endpoint:**
+```http
+POST /{base_path}/_batch
+```
+
+**Request:**
+```http
+POST /api/v1/data/_batch
+Authorization: Bearer
+Content-Type: application/json
+
+{
+ "operations": [
+ {
+ "method": "POST",
+ "path": "/account",
+ "body": { "name": "Company A", "industry": "Tech" }
+ },
+ {
+ "method": "PATCH",
+ "path": "/account/acc_123",
+ "body": { "status": "active" }
+ },
+ {
+ "method": "DELETE",
+ "path": "/account/acc_456"
+ }
+ ]
+}
+```
+
+**Response:**
+```json
+{
+ "success": true,
+ "results": [
+ {
+ "success": true,
+ "status": 201,
+ "data": { "id": "acc_789", "name": "Company A" }
+ },
+ {
+ "success": true,
+ "status": 200,
+ "data": { "id": "acc_123", "status": "active" }
+ },
+ {
+ "success": true,
+ "status": 200,
+ "data": { "id": "acc_456", "deleted": true }
+ }
+ ]
+}
+```
+
+**Limits:**
+- Maximum batch size: 50 operations (from `limits.max_batch_size`)
+- Operations are executed sequentially
+- Failure of one operation doesn't stop others (non-transactional by default)
+
+**Transactional batch:**
+```json
+{
+ "operations": [...],
+ "atomic": true
+}
+```
+If `atomic: true`, all operations execute in a transaction. If any fails, all are rolled back.
+
+## Metadata API
+
+Retrieve object schemas and configuration.
+
+**Base path:** From `routes.metadata` (default: `/api/v1/meta`)
+
+### List All Objects
+
+**Request:**
+```http
+GET /api/v1/meta/objects
+Authorization: Bearer
+```
+
+**Response:**
+```json
+{
+ "success": true,
+ "data": [
+ {
+ "name": "account",
+ "label": "Account",
+ "plural_label": "Accounts",
+ "description": "Business accounts and customers",
+ "api_enabled": true,
+ "searchable": true
+ },
+ {
+ "name": "contact",
+ "label": "Contact",
+ "plural_label": "Contacts",
+ "api_enabled": true,
+ "searchable": true
+ }
+ ]
+}
+```
+
+### Get Object Schema
+
+**Request:**
+```http
+GET /api/v1/meta/objects/account
+Authorization: Bearer
+```
+
+**Response:**
+```json
+{
+ "success": true,
+ "data": {
+ "name": "account",
+ "label": "Account",
+ "plural_label": "Accounts",
+ "fields": {
+ "id": {
+ "name": "id",
+ "label": "ID",
+ "type": "text",
+ "readonly": true,
+ "required": true
+ },
+ "name": {
+ "name": "name",
+ "label": "Account Name",
+ "type": "text",
+ "required": true,
+ "maxLength": 255
+ },
+ "industry": {
+ "name": "industry",
+ "label": "Industry",
+ "type": "select",
+ "options": ["Technology", "SaaS", "Healthcare", "Finance"]
+ },
+ "revenue": {
+ "name": "revenue",
+ "label": "Annual Revenue",
+ "type": "number",
+ "format": "currency"
+ }
+ },
+ "enable": {
+ "trackHistory": true,
+ "apiEnabled": true,
+ "softDelete": true
+ }
+ }
+}
+```
+
+## Request Headers
+
+### Standard Headers
+
+**Required:**
+```http
+Authorization: Bearer
+Content-Type: application/json # For POST/PATCH
+```
+
+**Optional:**
+```http
+Accept-Language: en-US # Preferred language
+X-Request-ID: uuid # Request tracking
+X-API-Version: 2 # API version preference
+```
+
+### CORS Headers
+
+ObjectStack sends CORS headers automatically:
+
+```http
+Access-Control-Allow-Origin: https://app.acme.com
+Access-Control-Allow-Methods: GET, POST, PATCH, DELETE, OPTIONS
+Access-Control-Allow-Headers: Authorization, Content-Type
+Access-Control-Max-Age: 86400
+```
+
+**Preflight request:**
+```http
+OPTIONS /api/v1/data/account
+Origin: https://app.acme.com
+Access-Control-Request-Method: POST
+```
+
+**Preflight response:**
+```http
+HTTP/1.1 204 No Content
+Access-Control-Allow-Origin: https://app.acme.com
+Access-Control-Allow-Methods: POST
+Access-Control-Max-Age: 86400
+```
+
+## Caching
+
+ObjectStack supports HTTP caching for GET requests:
+
+**Response with cache headers:**
+```http
+HTTP/1.1 200 OK
+Cache-Control: private, max-age=60
+ETag: "abc123def456"
+Last-Modified: Wed, 15 Jan 2024 10:30:00 GMT
+```
+
+**Conditional request:**
+```http
+GET /api/v1/data/account/acc_123
+If-None-Match: "abc123def456"
+```
+
+**Not modified response:**
+```http
+HTTP/1.1 304 Not Modified
+ETag: "abc123def456"
+```
+
+**Cache behavior:**
+- GET requests: Cacheable with ETags
+- POST/PATCH/DELETE: Not cacheable
+- Cache duration: Configurable per object (default 60 seconds)
+
+## Rate Limiting
+
+Requests include rate limit headers:
+
+```http
+HTTP/1.1 200 OK
+X-RateLimit-Limit: 1000
+X-RateLimit-Remaining: 847
+X-RateLimit-Reset: 1705324800
+```
+
+**When limit exceeded:**
+```http
+HTTP/1.1 429 Too Many Requests
+Retry-After: 45
+X-RateLimit-Limit: 1000
+X-RateLimit-Remaining: 0
+X-RateLimit-Reset: 1705324800
+
+{
+ "success": false,
+ "error": {
+ "code": "RATE_LIMITED",
+ "message": "Rate limit exceeded",
+ "retry_after": 45,
+ "limit": 1000,
+ "window": "1m"
+ }
+}
+```
+
+See [Error Handling](/docs/transport/error-handling) for more details.
+
+## Best Practices
+
+### Use Field Selection
+❌ **Bad:** Fetch all fields when you only need a few
+```http
+GET /api/data/account
+```
+
+✅ **Good:** Request only needed fields
+```http
+GET /api/data/account?select=id,name,status
+```
+
+### Use Includes for Relations
+❌ **Bad:** N+1 queries
+```javascript
+const tasks = await fetch('/api/data/task');
+for (const task of tasks.data) {
+ task.assignee = await fetch(`/api/data/user/${task.assignee_id}`);
+}
+```
+
+✅ **Good:** Single query with includes
+```javascript
+const tasks = await fetch('/api/data/task?include=assignee');
+```
+
+### Respect Rate Limits
+✅ **Good:** Check headers and implement backoff
+```javascript
+const response = await fetch('/api/data/task');
+const remaining = response.headers.get('X-RateLimit-Remaining');
+
+if (remaining < 10) {
+ console.warn('Approaching rate limit');
+ await sleep(1000);
+}
+```
+
+### Handle Errors Gracefully
+✅ **Good:** Parse error structure
+```javascript
+const response = await fetch('/api/data/task', { method: 'POST', body: data });
+const result = await response.json();
+
+if (!result.success) {
+ if (result.error.code === 'VALIDATION_ERROR') {
+ result.error.fields.forEach(field => {
+ showFieldError(field.field, field.message);
+ });
+ }
+}
+```
+
+## Next Steps
+
+
+ }
+ title="Real-Time Protocols"
+ description="Learn WebSocket subscriptions and event streaming"
+ href="/docs/transport/realtime"
+ />
+ }
+ title="Error Handling"
+ description="Master error codes and debugging strategies"
+ href="/docs/transport/error-handling"
+ />
+
diff --git a/content/docs/04-transport/index.mdx b/content/docs/04-transport/index.mdx
new file mode 100644
index 000000000..399b04bf9
--- /dev/null
+++ b/content/docs/04-transport/index.mdx
@@ -0,0 +1,440 @@
+---
+title: Transport & Interaction
+description: HTTP, WebSocket, and real-time communication protocols for ObjectStack
+---
+
+import { Radio, Zap, Network, Shield, Globe, Code, AlertCircle } from 'lucide-react';
+
+# Transport & Interaction
+
+The **Transport & Interaction Protocol** defines how clients communicate with ObjectStack servers through standardized HTTP/REST APIs, real-time WebSocket connections, and event streaming interfaces.
+
+## Why This Protocol Exists
+
+**Problem:** Modern applications need multiple communication channels—REST for CRUD operations, WebSockets for live updates, webhooks for external integrations. Each requires different infrastructure:
+
+- **REST APIs:** Developers write hundreds of routes manually, struggle with inconsistent response formats, forget to validate inputs
+- **Real-time updates:** Building WebSocket servers requires Redis pub/sub, connection pooling, heartbeat logic, reconnection handling
+- **Error handling:** Every endpoint returns errors differently—some use status codes, others embed errors in `200 OK` responses
+- **API evolution:** Adding a field breaks clients, removing a field breaks others, versioning becomes a nightmare
+- **Security gaps:** One forgotten `if (!authenticated)` check creates a data breach
+
+Traditional approach: Write thousands of lines of Express/FastAPI/Spring Boot code, maintain separate REST and WebSocket codebases, pray nothing breaks during deployments.
+
+**Solution:** The Transport Protocol **auto-generates REST and WebSocket endpoints** from your data model. Every object you define gets CRUD operations, real-time subscriptions, and error handling automatically. Communication patterns are configuration, not code.
+
+## Business Value Delivered
+
+
+ }
+ title="Ship APIs 10x Faster"
+ description="Define a data object, get REST + WebSocket endpoints instantly. Zero boilerplate code to write or maintain."
+ />
+ }
+ title="Zero Transport-Layer Bugs"
+ description="Authentication, validation, error handling, and rate limiting enforced by protocol—not developer discipline."
+ />
+ }
+ title="Multi-Channel by Default"
+ description="Every object supports REST, GraphQL, WebSocket, and webhooks. One definition, four communication channels."
+ />
+ }
+ title="Production-Grade from Day One"
+ description="Built-in CORS, compression, caching, retry logic, and connection pooling. No DevOps required."
+ />
+
+
+## What This Protocol Enables
+
+### 1. Auto-Generated REST Endpoints
+
+Define an object in Data Protocol → get REST endpoints automatically:
+
+```typescript
+// Define object
+const TaskObject = defineObject({
+ name: 'task',
+ label: 'Task',
+ fields: {
+ title: text({ required: true }),
+ status: select({
+ options: ['todo', 'in_progress', 'done']
+ }),
+ assignee: lookup({ reference: 'user' })
+ }
+});
+```
+
+**Auto-generated endpoints:**
+- `GET /api/data/task` - List tasks
+- `POST /api/data/task` - Create task
+- `GET /api/data/task/:id` - Get task by ID
+- `PATCH /api/data/task/:id` - Update task
+- `DELETE /api/data/task/:id` - Delete task
+
+**Advanced features included:**
+- **Filtering:** `GET /api/data/task?filter[status]=todo`
+- **Sorting:** `GET /api/data/task?sort=-created_at`
+- **Pagination:** `GET /api/data/task?page=2&per_page=25`
+- **Field selection:** `GET /api/data/task?fields=title,status`
+- **Relations:** `GET /api/data/task?include=assignee`
+
+**Real-world impact:** A project management SaaS launches with 15 objects (Task, Project, User, Comment, etc.). That's **75 REST endpoints** automatically. Add a new object? 5 more endpoints appear instantly. Zero code written.
+
+### 2. Real-Time WebSocket Subscriptions
+
+Subscribe to live data updates without polling:
+
+```javascript
+// Client subscribes to task updates
+const subscription = ws.subscribe('task', {
+ filter: { assignee_id: currentUser.id },
+ events: ['created', 'updated']
+});
+
+subscription.on('message', (event) => {
+ console.log('Task updated:', event.data);
+ updateUI(event.data);
+});
+```
+
+**Server pushes updates automatically:**
+- When a task is created: `{ event: 'created', object: 'task', data: {...} }`
+- When a task is updated: `{ event: 'updated', object: 'task', data: {...} }`
+- When a task is deleted: `{ event: 'deleted', object: 'task', id: '...' }`
+
+**Why it matters:** Traditional polling (`setInterval(() => fetch('/api/tasks'), 5000)`) wastes bandwidth and delays updates. WebSocket subscriptions deliver updates **instantly** with 95% less network overhead.
+
+**Real-world use case:** A collaborative task board has 50 concurrent users. With polling (5-second intervals), that's **36,000 requests/hour** hitting the database. With WebSockets, users subscribe once and receive push updates—**50 connections total**, 99% reduction in server load.
+
+### 3. Standardized Error Handling
+
+Every API response follows a consistent format:
+
+**Success Response:**
+```json
+{
+ "success": true,
+ "data": {
+ "id": "task_123",
+ "title": "Implement API",
+ "status": "in_progress"
+ }
+}
+```
+
+**Error Response:**
+```json
+{
+ "success": false,
+ "error": {
+ "code": "VALIDATION_ERROR",
+ "message": "Title is required",
+ "field": "title",
+ "details": {
+ "constraint": "required",
+ "value": null
+ }
+ }
+}
+```
+
+**Standard error codes:**
+- `VALIDATION_ERROR` - Input validation failed
+- `NOT_FOUND` - Resource doesn't exist
+- `UNAUTHORIZED` - Authentication required
+- `FORBIDDEN` - Insufficient permissions
+- `RATE_LIMITED` - Too many requests
+- `SERVER_ERROR` - Internal server error
+
+**Business value:** Frontend developers write error handling once. Every API call uses the same error structure. No more `if (response.error || response.errors || response.message)` conditional spaghetti.
+
+### 4. API Discovery and Self-Documentation
+
+Every ObjectStack server exposes a discovery endpoint that returns all available APIs:
+
+```http
+GET /.well-known/objectstack
+```
+
+```json
+{
+ "name": "Acme CRM Production",
+ "version": "2.1.0",
+ "environment": "production",
+ "routes": {
+ "data": "/api/v1/data",
+ "metadata": "/api/v1/meta",
+ "auth": "/api/v1/auth",
+ "realtime": "wss://api.acme.com/ws",
+ "graphql": "/api/v1/graphql"
+ },
+ "features": {
+ "graphql": true,
+ "websocket": true,
+ "webhooks": true,
+ "batch": true
+ },
+ "limits": {
+ "max_page_size": 100,
+ "rate_limit": 1000,
+ "rate_window": "1m"
+ }
+}
+```
+
+**Use cases:**
+- **Client initialization:** Apps request discovery on startup to configure API URLs
+- **SDK generation:** Auto-generate TypeScript/Python/Go SDKs from schema
+- **Partner integrations:** Third parties build integrations without outdated documentation
+
+**Real-world impact:** A company opens their API to partners. Instead of maintaining API docs (always outdated), partners hit `/api/discovery`, get current schema, build integrations without asking engineering for help.
+
+### 5. Rate Limiting and Quota Enforcement
+
+Prevent API abuse with declarative rate limits:
+
+```typescript
+// Configure rate limits per object
+const TaskObject = defineObject({
+ name: 'task',
+ api: {
+ rateLimit: {
+ query: { requests: 100, window: '1m' },
+ create: { requests: 10, window: '1m' },
+ update: { requests: 50, window: '1m' }
+ }
+ }
+});
+```
+
+**When limits are exceeded:**
+```http
+HTTP/1.1 429 Too Many Requests
+Content-Type: application/json
+Retry-After: 45
+
+{
+ "success": false,
+ "error": {
+ "code": "RATE_LIMITED",
+ "message": "Too many requests",
+ "retry_after": 45,
+ "limit": 100,
+ "window": "1m"
+ }
+}
+```
+
+**Per-user quota tracking:**
+- Free tier: 10,000 API calls/month
+- Pro tier: 1,000,000 API calls/month
+- Enterprise: Unlimited
+
+**Business value:** A freemium SaaS gives 10K API calls/month for free. Power users hit the limit in 2 weeks and upgrade to $99/month. Result: $50K/year revenue from API monetization.
+
+## Communication Channels
+
+ObjectStack supports multiple transport mechanisms:
+
+### HTTP/REST
+**Best for:** CRUD operations, stateless requests, third-party integrations
+
+**Characteristics:**
+- Request/response pattern
+- Stateless (each request independent)
+- Cacheable responses
+- Firewall-friendly (port 80/443)
+
+**Use cases:**
+- Mobile app fetching user profile
+- External system creating records via webhook
+- Browser-based CRUD operations
+
+### WebSocket
+**Best for:** Real-time dashboards, collaborative editing, live notifications
+
+**Characteristics:**
+- Bi-directional persistent connection
+- Low latency (no HTTP overhead per message)
+- Server can push without client request
+- Requires connection state management
+
+**Use cases:**
+- Chat applications
+- Live data dashboards
+- Multiplayer collaboration
+- IoT device communication
+
+### Server-Sent Events (SSE)
+**Best for:** One-way server-to-client streaming, simple real-time updates
+
+**Characteristics:**
+- Unidirectional (server to client only)
+- Automatic reconnection built-in
+- Works over HTTP (easier to proxy)
+- Less overhead than WebSocket for read-only updates
+
+**Use cases:**
+- Notification feeds
+- Live activity streams
+- Server status monitoring
+- Progress indicators
+
+### GraphQL
+**Best for:** Complex queries, mobile apps with bandwidth constraints
+
+**Characteristics:**
+- Query exactly the fields you need
+- Batch multiple resources in one request
+- Strongly typed schema
+- Client controls response shape
+
+**Use cases:**
+- Mobile apps minimizing payload size
+- Complex nested data fetching
+- Frontend-driven API exploration
+
+## Security Considerations
+
+### Authentication
+Every request requires authentication:
+
+```http
+GET /api/data/task
+Authorization: Bearer
+```
+
+Supported auth methods:
+- **JWT tokens:** Stateless authentication
+- **API keys:** Third-party integrations
+- **OAuth 2.0:** External services
+- **Session cookies:** Browser-based apps
+
+### CORS Configuration
+Configure allowed origins:
+
+```typescript
+const api = defineApi({
+ cors: {
+ origins: ['https://app.acme.com', 'https://admin.acme.com'],
+ methods: ['GET', 'POST', 'PATCH', 'DELETE'],
+ credentials: true,
+ maxAge: 86400
+ }
+});
+```
+
+### Input Validation
+All requests validated against schema:
+
+```http
+POST /api/data/task
+Content-Type: application/json
+
+{
+ "title": "", // ❌ Validation fails
+ "status": "invalid" // ❌ Not in enum
+}
+```
+
+```json
+{
+ "success": false,
+ "error": {
+ "code": "VALIDATION_ERROR",
+ "message": "Validation failed",
+ "fields": [
+ { "field": "title", "message": "Title is required" },
+ { "field": "status", "message": "Must be one of: todo, in_progress, done" }
+ ]
+ }
+}
+```
+
+### Permission Enforcement
+Row-level security applied to all operations:
+
+```typescript
+// User can only see their own tasks
+const query = {
+ object: 'task',
+ filter: { assignee_id: currentUser.id } // Auto-injected
+};
+```
+
+Even if a client sends:
+```http
+GET /api/data/task?filter[assignee_id]=other_user_id
+```
+
+Permission layer rewrites to:
+```sql
+WHERE assignee_id = 'current_user_id' -- Enforced by server
+```
+
+## Real-World Use Cases
+
+### Case 1: Mobile App Backend
+**Challenge:** A startup needs a backend API for iOS/Android apps. They have no backend engineers.
+
+**Transport Protocol Solution:** Define objects (User, Post, Comment), deploy ObjectStack, get REST APIs + WebSocket support. Mobile app authenticates via OAuth, calls `/api/data/post` to fetch feed, subscribes to WebSocket for live updates.
+
+**Value:** Shipped mobile app in 6 weeks with 1 full-stack engineer (vs. 3-month timeline with dedicated backend team).
+
+### Case 2: Real-Time Dashboard
+**Challenge:** A SaaS app has a revenue dashboard that polls `/api/revenue` every 5 seconds. 1,000 concurrent users = 12M API calls/hour, killing the database.
+
+**Transport Protocol Solution:** Switch dashboard to WebSocket subscriptions. Server pushes revenue updates only when data changes (e.g., new sale). Clients subscribe once, receive updates passively.
+
+**Value:** API load reduced by 95%. Database CPU usage dropped from 80% to 10%. $5K/month infrastructure savings.
+
+### Case 3: Third-Party Integration Platform
+**Challenge:** A CRM vendor wants partners to build integrations (Zapier, Make.com). Partners demand well-documented APIs.
+
+**Transport Protocol Solution:** Enable API discovery. Partners hit `/.well-known/objectstack`, get full schema, generate SDKs, build integrations without contacting engineering team.
+
+**Value:** 50+ partner integrations built in 6 months. Marketplace ecosystem drives 30% of new customer acquisition.
+
+## Integration with Other Protocols
+
+- **Data Protocol:** Transport exposes objects defined in Data Protocol; APIs auto-generated from schemas
+- **Permission Protocol:** Every API call filtered by user's row-level security and object permissions
+- **Auth Protocol:** Transport layer validates JWT tokens, API keys, OAuth credentials
+- **System Protocol:** API calls logged for audit; rate limit violations trigger alerts
+- **Automation Protocol:** Webhooks invoke workflows when API events occur
+
+**Key insight:** Transport Protocol is the **interface layer** of ObjectStack. It exposes your business logic (data, workflows, permissions) to the outside world—web apps, mobile apps, partners, IoT devices—with security and scalability built-in.
+
+## Next Steps
+
+
+ }
+ title="HTTP API"
+ description="Learn REST endpoint conventions, request/response formats, and CRUD operations"
+ href="/docs/transport/http-api"
+ />
+ }
+ title="Real-Time Protocols"
+ description="Implement WebSocket subscriptions, SSE streams, and event-driven updates"
+ href="/docs/transport/realtime"
+ />
+ }
+ title="Error Handling"
+ description="Master error codes, response formats, and debugging strategies"
+ href="/docs/transport/error-handling"
+ />
+ }
+ title="API Reference"
+ description="Explore detailed API specifications and code examples"
+ href="/docs/references/api"
+ />
+
diff --git a/content/docs/04-transport/meta.json b/content/docs/04-transport/meta.json
new file mode 100644
index 000000000..dc631a0b3
--- /dev/null
+++ b/content/docs/04-transport/meta.json
@@ -0,0 +1,8 @@
+{
+ "title": "Transport & Interaction",
+ "pages": [
+ "http-api",
+ "realtime",
+ "error-handling"
+ ]
+}
diff --git a/content/docs/04-transport/realtime.mdx b/content/docs/04-transport/realtime.mdx
new file mode 100644
index 000000000..e28eef9d9
--- /dev/null
+++ b/content/docs/04-transport/realtime.mdx
@@ -0,0 +1,1021 @@
+---
+title: Real-Time Protocols
+description: WebSocket subscriptions, Server-Sent Events, and event-driven communication in ObjectStack
+---
+
+import { Zap, Radio, Activity, Bell, Users, Gauge } from 'lucide-react';
+
+# Real-Time Protocols
+
+The **Real-Time Protocol** enables live data synchronization between clients and servers using WebSocket connections and Server-Sent Events (SSE). Get instant updates when data changes without polling.
+
+## Why Real-Time Matters
+
+**Problem:** Traditional REST APIs require polling to detect changes:
+
+```javascript
+// ❌ Polling approach - wasteful and laggy
+setInterval(async () => {
+ const response = await fetch('/api/data/task');
+ const tasks = await response.json();
+ updateUI(tasks);
+}, 5000); // Check every 5 seconds
+```
+
+**Costs of polling:**
+- **Latency:** Updates delayed by polling interval (5 seconds = 5-second lag)
+- **Bandwidth waste:** 99% of requests return "no changes"
+- **Server load:** 1,000 users polling every 5s = 12M requests/hour
+- **Database strain:** Constant query execution even when nothing changed
+- **Battery drain:** Mobile devices make unnecessary network calls
+
+**Solution:** Real-time subscriptions push updates instantly when data changes. Clients subscribe once, server pushes updates. Zero polling, zero lag.
+
+## Business Value Delivered
+
+
+ }
+ title="Instant User Experience"
+ description="Changes appear immediately across all connected clients. No refresh required."
+ />
+ }
+ title="95% Less Server Load"
+ description="Replace millions of polling requests with persistent connections. Massive infrastructure savings."
+ />
+ }
+ title="Enable Collaboration"
+ description="Multiple users editing the same data see each other's changes in real-time. Google Docs-style UX."
+ />
+ }
+ title="Live Notifications"
+ description="Deliver alerts, messages, and updates the moment they happen. No missed events."
+ />
+
+
+## Communication Channels
+
+ObjectStack supports two real-time protocols:
+
+### WebSocket (Bi-Directional)
+
+**Best for:** Interactive applications requiring two-way communication
+
+**Characteristics:**
+- Full-duplex communication (client and server both send)
+- Low latency (no HTTP overhead per message)
+- Persistent connection
+- Binary and text messages supported
+
+**Use cases:**
+- Chat applications
+- Collaborative editing (Google Docs, Figma)
+- Multiplayer games
+- Live dashboards with user interactions
+- IoT device communication
+
+### Server-Sent Events (SSE) (Server-to-Client)
+
+**Best for:** One-way server-to-client streaming
+
+**Characteristics:**
+- Unidirectional (server pushes only)
+- Works over HTTP (easier firewall traversal)
+- Automatic reconnection built-in
+- Text-based (JSON messages)
+
+**Use cases:**
+- Activity feeds
+- Notification streams
+- Live status updates
+- Progress indicators
+- Read-only dashboards
+
+## WebSocket Connection
+
+### Connection Endpoint
+
+Get WebSocket URL from discovery:
+
+```http
+GET /.well-known/objectstack
+```
+
+```json
+{
+ "routes": {
+ "realtime": "wss://api.acme.com/ws"
+ }
+}
+```
+
+### Establishing Connection
+
+**Client-side (JavaScript):**
+```javascript
+const ws = new WebSocket('wss://api.acme.com/ws');
+
+ws.onopen = () => {
+ console.log('Connected to ObjectStack');
+
+ // Authenticate
+ ws.send(JSON.stringify({
+ type: 'auth',
+ token: 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...'
+ }));
+};
+
+ws.onmessage = (event) => {
+ const message = JSON.parse(event.data);
+ console.log('Received:', message);
+};
+
+ws.onerror = (error) => {
+ console.error('WebSocket error:', error);
+};
+
+ws.onclose = (event) => {
+ console.log('Connection closed:', event.code, event.reason);
+};
+```
+
+### Authentication
+
+Send authentication message immediately after connection:
+
+**Request:**
+```json
+{
+ "type": "auth",
+ "token": "Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..."
+}
+```
+
+**Success Response:**
+```json
+{
+ "type": "auth_success",
+ "user_id": "user_123",
+ "session_id": "session_abc",
+ "expires_at": "2024-01-16T22:30:00Z"
+}
+```
+
+**Failure Response:**
+```json
+{
+ "type": "auth_error",
+ "error": {
+ "code": "INVALID_TOKEN",
+ "message": "JWT token expired"
+ }
+}
+```
+
+**Connection closes on auth failure:** Server closes WebSocket if authentication fails within 10 seconds.
+
+## Subscriptions
+
+### Subscribe to Object Events
+
+Subscribe to changes on a specific object:
+
+**Request:**
+```json
+{
+ "type": "subscribe",
+ "subscription_id": "sub_1",
+ "object": "task",
+ "events": ["created", "updated", "deleted"],
+ "filter": {
+ "assignee_id": "user_123"
+ }
+}
+```
+
+**Parameters:**
+- `subscription_id`: Client-generated unique ID for this subscription
+- `object`: Object name to subscribe to
+- `events`: Array of events to listen for (default: all)
+- `filter`: Optional filter (same syntax as HTTP API filters)
+
+**Success Response:**
+```json
+{
+ "type": "subscribed",
+ "subscription_id": "sub_1",
+ "object": "task",
+ "events": ["created", "updated", "deleted"]
+}
+```
+
+**Error Response:**
+```json
+{
+ "type": "error",
+ "subscription_id": "sub_1",
+ "error": {
+ "code": "FORBIDDEN",
+ "message": "No permission to subscribe to 'task' object"
+ }
+}
+```
+
+### Event Types
+
+| Event | Triggered When | Payload |
+|-------|---------------|---------|
+| `created` | New record created | Full record data |
+| `updated` | Record modified | Changed fields + record ID |
+| `deleted` | Record deleted | Record ID only |
+| `restored` | Soft-deleted record restored | Full record data |
+
+### Receiving Events
+
+When subscribed data changes, server pushes events:
+
+**Created Event:**
+```json
+{
+ "type": "event",
+ "subscription_id": "sub_1",
+ "event": "created",
+ "object": "task",
+ "data": {
+ "id": "task_456",
+ "title": "New task assigned to you",
+ "status": "todo",
+ "assignee_id": "user_123",
+ "created_at": "2024-01-16T14:30:00Z"
+ }
+}
+```
+
+**Updated Event:**
+```json
+{
+ "type": "event",
+ "subscription_id": "sub_1",
+ "event": "updated",
+ "object": "task",
+ "data": {
+ "id": "task_456",
+ "status": "in_progress",
+ "updated_at": "2024-01-16T15:00:00Z"
+ },
+ "changes": {
+ "status": {
+ "old": "todo",
+ "new": "in_progress"
+ }
+ }
+}
+```
+
+**Deleted Event:**
+```json
+{
+ "type": "event",
+ "subscription_id": "sub_1",
+ "event": "deleted",
+ "object": "task",
+ "data": {
+ "id": "task_456",
+ "deleted_at": "2024-01-16T16:00:00Z"
+ }
+}
+```
+
+### Unsubscribe
+
+Stop receiving events for a subscription:
+
+**Request:**
+```json
+{
+ "type": "unsubscribe",
+ "subscription_id": "sub_1"
+}
+```
+
+**Response:**
+```json
+{
+ "type": "unsubscribed",
+ "subscription_id": "sub_1"
+}
+```
+
+### Subscribe to Specific Record
+
+Watch a single record for changes:
+
+**Request:**
+```json
+{
+ "type": "subscribe",
+ "subscription_id": "sub_2",
+ "object": "task",
+ "record_id": "task_456",
+ "events": ["updated", "deleted"]
+}
+```
+
+**Use case:** Detail pages that need to reflect live changes to the currently viewed record.
+
+### Subscribe to Query Results
+
+Subscribe to a dynamic set of records matching a query:
+
+**Request:**
+```json
+{
+ "type": "subscribe",
+ "subscription_id": "sub_3",
+ "object": "task",
+ "query": {
+ "filter": {
+ "status": "todo",
+ "assignee_id": "user_123"
+ },
+ "sort": "-priority"
+ },
+ "events": ["created", "updated", "deleted"]
+}
+```
+
+**Behavior:**
+- Receive `created` events when records matching query are created
+- Receive `updated` events when subscribed records change
+- Receive `deleted` events when subscribed records are deleted
+- Automatically receive events when records enter/exit the query filter
+
+**Example:** Task enters subscription:
+```json
+{
+ "type": "event",
+ "subscription_id": "sub_3",
+ "event": "updated",
+ "object": "task",
+ "data": {
+ "id": "task_789",
+ "status": "todo", // Changed from "in_progress" to "todo"
+ "assignee_id": "user_123"
+ },
+ "reason": "entered_query"
+}
+```
+
+**Example:** Task exits subscription:
+```json
+{
+ "type": "event",
+ "subscription_id": "sub_3",
+ "event": "updated",
+ "object": "task",
+ "data": {
+ "id": "task_456",
+ "status": "done" // No longer matches "todo" filter
+ },
+ "reason": "exited_query"
+}
+```
+
+## Server-Sent Events (SSE)
+
+### Connection Endpoint
+
+**GET request with Accept header:**
+```http
+GET /api/v1/stream
+Authorization: Bearer
+Accept: text/event-stream
+```
+
+**Response:**
+```http
+HTTP/1.1 200 OK
+Content-Type: text/event-stream
+Cache-Control: no-cache
+Connection: keep-alive
+```
+
+### Subscription via Query Parameters
+
+Subscribe using URL parameters:
+
+```http
+GET /api/v1/stream?object=task&events=created,updated&filter={"assignee_id":"user_123"}
+Authorization: Bearer
+Accept: text/event-stream
+```
+
+### Event Format
+
+SSE sends events as text:
+
+```
+id: event_123
+event: task.created
+data: {"id":"task_456","title":"New task","status":"todo"}
+
+id: event_124
+event: task.updated
+data: {"id":"task_456","status":"in_progress"}
+```
+
+**Client-side (JavaScript):**
+```javascript
+const eventSource = new EventSource(
+ '/api/v1/stream?object=task&events=created,updated',
+ {
+ headers: {
+ 'Authorization': 'Bearer ' + token
+ }
+ }
+);
+
+eventSource.addEventListener('task.created', (event) => {
+ const task = JSON.parse(event.data);
+ console.log('Task created:', task);
+});
+
+eventSource.addEventListener('task.updated', (event) => {
+ const task = JSON.parse(event.data);
+ console.log('Task updated:', task);
+});
+
+eventSource.onerror = (error) => {
+ console.error('SSE error:', error);
+ eventSource.close();
+};
+```
+
+### Automatic Reconnection
+
+SSE clients automatically reconnect when connection drops:
+
+```
+id: event_200
+event: task.created
+data: {...}
+
+# Connection lost
+
+# Client reconnects with Last-Event-ID header
+GET /api/v1/stream?object=task
+Last-Event-ID: event_200
+
+# Server resumes from event_201
+id: event_201
+event: task.updated
+data: {...}
+```
+
+## Heartbeat & Keep-Alive
+
+### Server Heartbeat
+
+Server sends periodic ping messages to detect disconnections:
+
+**WebSocket ping (every 30 seconds):**
+```json
+{
+ "type": "ping",
+ "timestamp": "2024-01-16T14:30:00Z"
+}
+```
+
+**Client should respond with pong:**
+```json
+{
+ "type": "pong",
+ "timestamp": "2024-01-16T14:30:00Z"
+}
+```
+
+**SSE heartbeat (comment):**
+```
+: heartbeat
+```
+
+### Client Reconnection
+
+Handle disconnections gracefully:
+
+```javascript
+class ObjectStackClient {
+ constructor(url, token) {
+ this.url = url;
+ this.token = token;
+ this.subscriptions = new Map();
+ this.reconnectDelay = 1000; // Start with 1 second
+ this.maxReconnectDelay = 30000; // Max 30 seconds
+ }
+
+ connect() {
+ this.ws = new WebSocket(this.url);
+
+ this.ws.onopen = () => {
+ console.log('Connected');
+ this.reconnectDelay = 1000; // Reset backoff
+ this.authenticate();
+ this.resubscribe();
+ };
+
+ this.ws.onclose = () => {
+ console.log('Disconnected, reconnecting in', this.reconnectDelay);
+ setTimeout(() => this.connect(), this.reconnectDelay);
+ this.reconnectDelay = Math.min(
+ this.reconnectDelay * 2,
+ this.maxReconnectDelay
+ );
+ };
+ }
+
+ authenticate() {
+ this.send({ type: 'auth', token: this.token });
+ }
+
+ resubscribe() {
+ this.subscriptions.forEach((config, id) => {
+ this.send({ ...config, subscription_id: id });
+ });
+ }
+
+ subscribe(config) {
+ const id = `sub_${Date.now()}`;
+ this.subscriptions.set(id, config);
+ this.send({ ...config, type: 'subscribe', subscription_id: id });
+ return id;
+ }
+
+ send(message) {
+ this.ws.send(JSON.stringify(message));
+ }
+}
+
+// Usage
+const client = new ObjectStackClient('wss://api.acme.com/ws', token);
+client.connect();
+```
+
+## Permission Enforcement
+
+Real-time subscriptions respect object-level and row-level permissions:
+
+**Scenario:** User subscribes to all tasks:
+```json
+{
+ "type": "subscribe",
+ "subscription_id": "sub_1",
+ "object": "task",
+ "events": ["created", "updated"]
+}
+```
+
+**Permission enforcement:**
+- Server applies row-level security filter automatically
+- User only receives events for tasks they have permission to see
+- If a task becomes visible (e.g., gets assigned to user), they receive an `updated` event
+- If a task becomes hidden (e.g., assigned to someone else), no more events sent
+
+**Example:** User has rule "see only assigned tasks":
+
+```javascript
+// User is assigned task_456
+{
+ "type": "event",
+ "event": "updated",
+ "object": "task",
+ "data": { "id": "task_456", "assignee_id": "user_123" },
+ "reason": "entered_query"
+}
+
+// Task reassigned to someone else
+// No event sent - task is now invisible to user
+```
+
+## Scaling Considerations
+
+### Connection Limits
+
+Each WebSocket connection consumes server resources:
+
+**Per-user limits:**
+- Maximum concurrent WebSocket connections: 5
+- Maximum subscriptions per connection: 50
+- Maximum subscriptions per user: 100
+
+**Exceeding limits:**
+```json
+{
+ "type": "error",
+ "error": {
+ "code": "TOO_MANY_SUBSCRIPTIONS",
+ "message": "Maximum 50 subscriptions per connection",
+ "current": 50,
+ "max": 50
+ }
+}
+```
+
+### Load Balancing
+
+WebSocket connections are sticky sessions:
+
+```
+Client → Load Balancer → Server A
+ (remembers)
+
+Client reconnects → Server A (same server)
+```
+
+**Why sticky sessions:**
+- Subscription state lives in server memory
+- Reconnecting to different server would lose subscriptions
+- Load balancer uses session ID cookie to route to same server
+
+### Horizontal Scaling with Redis
+
+For multi-server deployments, ObjectStack uses Redis pub/sub:
+
+```
+Server A ←→ Redis Pub/Sub ←→ Server B
+ ↓ ↓
+Client 1 Client 2
+
+# Data changes on Server A
+Server A publishes to Redis → Server B receives → Client 2 gets update
+```
+
+**How it works:**
+1. User A (connected to Server A) updates a task
+2. Server A publishes event to Redis channel `objectstack:task:updated`
+3. Server B (subscribed to Redis) receives event
+4. Server B pushes event to User B via WebSocket
+
+**Result:** Multi-server deployments with real-time sync across all servers.
+
+## Real-World Use Cases
+
+### Case 1: Collaborative Task Board
+
+**Challenge:** Team of 20 uses Kanban board. When one person moves a task, others see stale state until they refresh.
+
+**Real-Time Solution:**
+```javascript
+// Each client subscribes to tasks
+ws.subscribe({
+ object: 'task',
+ events: ['created', 'updated', 'deleted'],
+ filter: { project_id: currentProject.id }
+});
+
+// When any user drags task to new column
+await api.updateTask(taskId, { status: 'in_progress' });
+
+// All 20 clients instantly see the task move
+ws.on('task.updated', (task) => {
+ moveTaskOnBoard(task.id, task.status);
+});
+```
+
+**Value:** Zero conflicts. Everyone sees same board state in real-time. No "refresh to see latest" UX.
+
+### Case 2: Customer Support Dashboard
+
+**Challenge:** Support agents answer tickets. When agent A claims a ticket, agent B tries to claim the same ticket 2 seconds later (both see it as "unclaimed").
+
+**Real-Time Solution:**
+```javascript
+// All agents subscribe to ticket updates
+ws.subscribe({
+ object: 'support_ticket',
+ events: ['updated'],
+ filter: { status: 'open' }
+});
+
+// Agent A claims ticket
+await api.updateTicket(ticketId, {
+ assigned_to: 'agent_a',
+ status: 'in_progress'
+});
+
+// Agent B's dashboard instantly updates
+ws.on('ticket.updated', (ticket) => {
+ if (ticket.status !== 'open') {
+ removeFromAvailableQueue(ticket.id);
+ }
+});
+```
+
+**Value:** Zero duplicate work. Tickets disappear from queue the instant they're claimed.
+
+### Case 3: Live Notifications
+
+**Challenge:** Users need instant alerts for mentions, assignments, approvals.
+
+**Real-Time Solution:**
+```javascript
+// Subscribe to user's notification stream
+ws.subscribe({
+ object: 'notification',
+ events: ['created'],
+ filter: { recipient_id: currentUser.id }
+});
+
+ws.on('notification.created', (notification) => {
+ showToast(notification.title, notification.message);
+ updateNotificationBadge();
+ playSound();
+});
+```
+
+**Value:** Instant notifications. No 5-second polling delay. Lower server load.
+
+### Case 4: IoT Device Monitoring
+
+**Challenge:** Factory has 500 IoT sensors. Dashboard needs to show live temperature, pressure, vibration data.
+
+**Real-Time Solution:**
+```javascript
+// Subscribe to all sensor readings
+ws.subscribe({
+ object: 'sensor_reading',
+ events: ['created'],
+ filter: { factory_id: 'factory_123' }
+});
+
+ws.on('sensor_reading.created', (reading) => {
+ updateGauge(reading.sensor_id, reading.value);
+
+ if (reading.value > reading.threshold) {
+ triggerAlert(reading.sensor_id, 'THRESHOLD_EXCEEDED');
+ }
+});
+```
+
+**Value:** Real-time monitoring. Instant alerts when thresholds exceeded. No polling 500 sensors every second.
+
+## Debugging Real-Time Connections
+
+### Connection State
+
+Check WebSocket connection state:
+
+```javascript
+console.log(ws.readyState);
+// 0: CONNECTING
+// 1: OPEN
+// 2: CLOSING
+// 3: CLOSED
+```
+
+### Message Logging
+
+Enable debug logging:
+
+```javascript
+ws.onmessage = (event) => {
+ const message = JSON.parse(event.data);
+ console.log('[RX]', message.type, message);
+};
+
+const originalSend = ws.send.bind(ws);
+ws.send = (data) => {
+ const message = JSON.parse(data);
+ console.log('[TX]', message.type, message);
+ originalSend(data);
+};
+```
+
+### Server-Side Events
+
+Request server event log:
+
+```http
+GET /api/v1/realtime/events?subscription_id=sub_1&limit=100
+Authorization: Bearer
+```
+
+**Response:**
+```json
+{
+ "success": true,
+ "data": [
+ {
+ "id": "event_123",
+ "subscription_id": "sub_1",
+ "event": "created",
+ "object": "task",
+ "timestamp": "2024-01-16T14:30:00Z",
+ "delivered": true
+ },
+ {
+ "id": "event_124",
+ "subscription_id": "sub_1",
+ "event": "updated",
+ "object": "task",
+ "timestamp": "2024-01-16T14:35:00Z",
+ "delivered": false,
+ "reason": "client_disconnected"
+ }
+ ]
+}
+```
+
+### Common Issues
+
+**Problem:** Events not received after reconnection
+
+**Solution:** Client should resubscribe after authentication:
+```javascript
+ws.onopen = () => {
+ authenticate().then(() => {
+ subscriptions.forEach(sub => subscribe(sub));
+ });
+};
+```
+
+**Problem:** Duplicate events
+
+**Solution:** Use subscription IDs to deduplicate:
+```javascript
+const seenEvents = new Set();
+
+ws.on('event', (event) => {
+ if (seenEvents.has(event.id)) {
+ return; // Skip duplicate
+ }
+ seenEvents.add(event.id);
+ processEvent(event);
+});
+```
+
+**Problem:** Memory leak from subscriptions
+
+**Solution:** Unsubscribe when component unmounts:
+```javascript
+useEffect(() => {
+ const subId = ws.subscribe({ object: 'task', ... });
+
+ return () => {
+ ws.unsubscribe(subId);
+ };
+}, []);
+```
+
+## Best Practices
+
+### ✅ Subscribe to Specific Queries
+**Bad:** Subscribe to entire object, filter client-side
+```javascript
+ws.subscribe({ object: 'task' }); // Receive ALL tasks
+ws.on('task.created', (task) => {
+ if (task.assignee_id === currentUser.id) { // Filter client-side
+ showTask(task);
+ }
+});
+```
+
+**Good:** Subscribe with server-side filter
+```javascript
+ws.subscribe({
+ object: 'task',
+ filter: { assignee_id: currentUser.id }
+});
+```
+
+### ✅ Implement Reconnection Logic
+**Bad:** No reconnection handling
+```javascript
+const ws = new WebSocket(url);
+// Connection drops → User sees stale data forever
+```
+
+**Good:** Automatic reconnection with exponential backoff
+```javascript
+class ReconnectingWebSocket {
+ connect() {
+ this.ws = new WebSocket(this.url);
+ this.ws.onclose = () => {
+ setTimeout(() => this.connect(), this.backoff());
+ };
+ }
+}
+```
+
+### ✅ Unsubscribe When Not Needed
+**Bad:** Keep subscriptions active on hidden tabs
+```javascript
+ws.subscribe({ object: 'task' });
+// User switches tabs → Still receiving events and processing
+```
+
+**Good:** Pause/resume subscriptions based on visibility
+```javascript
+document.addEventListener('visibilitychange', () => {
+ if (document.hidden) {
+ ws.unsubscribe(subId);
+ } else {
+ subId = ws.subscribe({ object: 'task' });
+ }
+});
+```
+
+### ✅ Handle Permission Changes
+**Good:** React to visibility changes
+```javascript
+ws.on('task.updated', (task) => {
+ if (task.reason === 'exited_query') {
+ removeFromUI(task.id); // User no longer has access
+ } else if (task.reason === 'entered_query') {
+ addToUI(task); // User gained access
+ } else {
+ updateInUI(task);
+ }
+});
+```
+
+## Security Considerations
+
+### Authentication Required
+All WebSocket connections must authenticate within 10 seconds:
+
+```javascript
+ws.onopen = () => {
+ ws.send(JSON.stringify({
+ type: 'auth',
+ token: getToken()
+ }));
+};
+
+// Server closes connection if no auth within 10 seconds
+```
+
+### Token Expiration
+Handle JWT expiration gracefully:
+
+```json
+{
+ "type": "error",
+ "error": {
+ "code": "TOKEN_EXPIRED",
+ "message": "JWT token expired",
+ "expires_at": "2024-01-16T14:30:00Z"
+ }
+}
+```
+
+**Client response:** Refresh token and reconnect
+```javascript
+ws.onmessage = async (event) => {
+ const msg = JSON.parse(event.data);
+ if (msg.error?.code === 'TOKEN_EXPIRED') {
+ const newToken = await refreshToken();
+ ws.close();
+ reconnect(newToken);
+ }
+};
+```
+
+### Rate Limiting
+WebSocket messages are rate-limited:
+
+```json
+{
+ "type": "error",
+ "error": {
+ "code": "RATE_LIMITED",
+ "message": "Too many messages",
+ "retry_after": 5,
+ "limit": 100,
+ "window": "1m"
+ }
+}
+```
+
+**Limits:**
+- Max 100 messages per minute per connection
+- Max 10 subscriptions per minute per connection
+
+## Next Steps
+
+
+ }
+ title="HTTP API"
+ description="Learn REST endpoint conventions and CRUD operations"
+ href="/docs/transport/http-api"
+ />
+ }
+ title="Error Handling"
+ description="Master error codes and debugging strategies"
+ href="/docs/transport/error-handling"
+ />
+
From cc26a98bf71c310d218be2f20ed496a6c8dd72d0 Mon Sep 17 00:00:00 2001
From: "copilot-swe-agent[bot]" <198982749+Copilot@users.noreply.github.com>
Date: Mon, 26 Jan 2026 09:17:16 +0000
Subject: [PATCH 04/22] Remove numbered prefixes from documentation folders and
update navigation
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
- Renamed 00-introduction → introduction
- Renamed 01-core-concepts → core-concepts
- Renamed 02-protocols → protocols
- Also renamed protocols/01-objectql → protocols/objectql
- Also renamed protocols/02-objectui → protocols/objectui
- Also renamed protocols/03-objectos → protocols/objectos
- Renamed 03-development → development
- Renamed 04-transport → transport
- Updated root meta.json to include new sections with proper ordering
- Updated all meta.json files to reference correct folder names
- Updated all internal links to use new folder names
- Fixed MDX syntax errors (< character issues)
Co-authored-by: hotlong <50353452+hotlong@users.noreply.github.com>
---
content/docs/02-protocols/meta.json | 8 -----
content/docs/concepts/protocol-kernel.mdx | 2 +-
.../index.mdx | 8 ++---
.../meta.json | 0
.../metadata-driven.mdx | 6 ++--
.../object-model.mdx | 2 +-
.../the-stack.mdx | 8 ++---
.../cli-tools.mdx | 4 +--
.../custom-widgets.mdx | 6 ++--
.../{03-development => development}/index.mdx | 28 ++++++++---------
.../{03-development => development}/meta.json | 0
.../server-drivers.mdx | 6 ++--
.../writing-plugins.mdx | 8 ++---
.../architecture.mdx | 6 ++--
.../design-principles.mdx | 6 ++--
.../glossary.mdx | 6 ++--
.../index.mdx | 8 ++---
.../meta.json | 0
.../overview.mdx | 8 ++---
content/docs/meta.json | 5 ++++
.../{02-protocols => protocols}/index.mdx | 30 +++++++++----------
content/docs/protocols/meta.json | 8 +++++
.../objectos}/config-resolution.mdx | 0
.../objectos}/i18n-standard.mdx | 4 +--
.../objectos}/index.mdx | 0
.../objectos}/lifecycle.mdx | 0
.../objectos}/meta.json | 0
.../objectos}/plugin-spec.mdx | 0
.../objectql}/index.mdx | 18 +++++------
.../objectql}/meta.json | 0
.../objectql}/query-syntax.mdx | 6 ++--
.../objectql}/schema.mdx | 8 ++---
.../objectql}/security.mdx | 6 ++--
.../objectql}/types.mdx | 6 ++--
.../objectui}/actions.mdx | 2 +-
.../objectui}/concept.mdx | 0
.../objectui}/index.mdx | 0
.../objectui}/layout-dsl.mdx | 6 ++--
.../objectui}/meta.json | 0
.../objectui}/widget-contract.mdx | 0
.../error-handling.mdx | 2 +-
.../{04-transport => transport}/http-api.mdx | 2 +-
.../{04-transport => transport}/index.mdx | 0
.../{04-transport => transport}/meta.json | 0
.../{04-transport => transport}/realtime.mdx | 2 +-
45 files changed, 115 insertions(+), 110 deletions(-)
delete mode 100644 content/docs/02-protocols/meta.json
rename content/docs/{01-core-concepts => core-concepts}/index.mdx (77%)
rename content/docs/{01-core-concepts => core-concepts}/meta.json (100%)
rename content/docs/{01-core-concepts => core-concepts}/metadata-driven.mdx (95%)
rename content/docs/{01-core-concepts => core-concepts}/object-model.mdx (99%)
rename content/docs/{01-core-concepts => core-concepts}/the-stack.mdx (97%)
rename content/docs/{03-development => development}/cli-tools.mdx (99%)
rename content/docs/{03-development => development}/custom-widgets.mdx (99%)
rename content/docs/{03-development => development}/index.mdx (89%)
rename content/docs/{03-development => development}/meta.json (100%)
rename content/docs/{03-development => development}/server-drivers.mdx (99%)
rename content/docs/{03-development => development}/writing-plugins.mdx (98%)
rename content/docs/{00-introduction => introduction}/architecture.mdx (97%)
rename content/docs/{00-introduction => introduction}/design-principles.mdx (95%)
rename content/docs/{00-introduction => introduction}/glossary.mdx (96%)
rename content/docs/{00-introduction => introduction}/index.mdx (75%)
rename content/docs/{00-introduction => introduction}/meta.json (100%)
rename content/docs/{00-introduction => introduction}/overview.mdx (91%)
rename content/docs/{02-protocols => protocols}/index.mdx (84%)
create mode 100644 content/docs/protocols/meta.json
rename content/docs/{02-protocols/03-objectos => protocols/objectos}/config-resolution.mdx (100%)
rename content/docs/{02-protocols/03-objectos => protocols/objectos}/i18n-standard.mdx (99%)
rename content/docs/{02-protocols/03-objectos => protocols/objectos}/index.mdx (100%)
rename content/docs/{02-protocols/03-objectos => protocols/objectos}/lifecycle.mdx (100%)
rename content/docs/{02-protocols/03-objectos => protocols/objectos}/meta.json (100%)
rename content/docs/{02-protocols/03-objectos => protocols/objectos}/plugin-spec.mdx (100%)
rename content/docs/{02-protocols/01-objectql => protocols/objectql}/index.mdx (94%)
rename content/docs/{02-protocols/01-objectql => protocols/objectql}/meta.json (100%)
rename content/docs/{02-protocols/01-objectql => protocols/objectql}/query-syntax.mdx (99%)
rename content/docs/{02-protocols/01-objectql => protocols/objectql}/schema.mdx (99%)
rename content/docs/{02-protocols/01-objectql => protocols/objectql}/security.mdx (99%)
rename content/docs/{02-protocols/01-objectql => protocols/objectql}/types.mdx (99%)
rename content/docs/{02-protocols/02-objectui => protocols/objectui}/actions.mdx (99%)
rename content/docs/{02-protocols/02-objectui => protocols/objectui}/concept.mdx (100%)
rename content/docs/{02-protocols/02-objectui => protocols/objectui}/index.mdx (100%)
rename content/docs/{02-protocols/02-objectui => protocols/objectui}/layout-dsl.mdx (99%)
rename content/docs/{02-protocols/02-objectui => protocols/objectui}/meta.json (100%)
rename content/docs/{02-protocols/02-objectui => protocols/objectui}/widget-contract.mdx (100%)
rename content/docs/{04-transport => transport}/error-handling.mdx (99%)
rename content/docs/{04-transport => transport}/http-api.mdx (99%)
rename content/docs/{04-transport => transport}/index.mdx (100%)
rename content/docs/{04-transport => transport}/meta.json (100%)
rename content/docs/{04-transport => transport}/realtime.mdx (99%)
diff --git a/content/docs/02-protocols/meta.json b/content/docs/02-protocols/meta.json
deleted file mode 100644
index 2376db63e..000000000
--- a/content/docs/02-protocols/meta.json
+++ /dev/null
@@ -1,8 +0,0 @@
-{
- "title": "📜 Protocols",
- "pages": [
- "01-objectql",
- "02-objectui",
- "03-objectos"
- ]
-}
diff --git a/content/docs/concepts/protocol-kernel.mdx b/content/docs/concepts/protocol-kernel.mdx
index f01238a11..ea23e8e42 100644
--- a/content/docs/concepts/protocol-kernel.mdx
+++ b/content/docs/concepts/protocol-kernel.mdx
@@ -18,7 +18,7 @@ The **Kernel Protocol** defines the plugin system and runtime management for Obj
- **Slow innovation:** Want AI-powered search? Wait for the vendor's roadmap (or never get it)
- **License costs:** Pay $150/user/month for "Enterprise Edition" just to get SSO
-**Solution:** The Kernel Protocol implements a **microkernel architecture** like Linux or Kubernetes. The core runtime is <10MB and does almost nothing—just loads plugins. Every feature (data access, UI, workflows, AI) is a plugin. Don't need dashboards? Don't load the dashboard plugin. Want better analytics? Replace the default plugin with your own.
+**Solution:** The Kernel Protocol implements a **microkernel architecture** like Linux or Kubernetes. The core runtime is less than 10MB and does almost nothing—just loads plugins. Every feature (data access, UI, workflows, AI) is a plugin. Don't need dashboards? Don't load the dashboard plugin. Want better analytics? Replace the default plugin with your own.
## Business Value Delivered
diff --git a/content/docs/01-core-concepts/index.mdx b/content/docs/core-concepts/index.mdx
similarity index 77%
rename from content/docs/01-core-concepts/index.mdx
rename to content/docs/core-concepts/index.mdx
index a6cfaaf63..802897166 100644
--- a/content/docs/01-core-concepts/index.mdx
+++ b/content/docs/core-concepts/index.mdx
@@ -15,9 +15,9 @@ These concepts work together to create a platform that is more flexible, maintai
## What You'll Learn
-- [Metadata-Driven](/docs/01-core-concepts/metadata-driven) - What is metadata-driven development?
-- [The Stack](/docs/01-core-concepts/the-stack) - How ObjectQL + ObjectUI + ObjectOS work together
-- [Object Model](/docs/01-core-concepts/object-model) - The Universal Object Model explained
+- [Metadata-Driven](/docs/core-concepts/metadata-driven) - What is metadata-driven development?
+- [The Stack](/docs/core-concepts/the-stack) - How ObjectQL + ObjectUI + ObjectOS work together
+- [Object Model](/docs/core-concepts/object-model) - The Universal Object Model explained
## Why This Matters
@@ -49,4 +49,4 @@ Think of ObjectStack like this:
## Next Steps
-Start with [Metadata-Driven](/docs/01-core-concepts/metadata-driven) to understand the foundation of ObjectStack's approach.
+Start with [Metadata-Driven](/docs/core-concepts/metadata-driven) to understand the foundation of ObjectStack's approach.
diff --git a/content/docs/01-core-concepts/meta.json b/content/docs/core-concepts/meta.json
similarity index 100%
rename from content/docs/01-core-concepts/meta.json
rename to content/docs/core-concepts/meta.json
diff --git a/content/docs/01-core-concepts/metadata-driven.mdx b/content/docs/core-concepts/metadata-driven.mdx
similarity index 95%
rename from content/docs/01-core-concepts/metadata-driven.mdx
rename to content/docs/core-concepts/metadata-driven.mdx
index d5445e5db..1fce5a8b0 100644
--- a/content/docs/01-core-concepts/metadata-driven.mdx
+++ b/content/docs/core-concepts/metadata-driven.mdx
@@ -248,6 +248,6 @@ You specify **exactly how** to draw each pixel.
## Next Steps
-- [The Stack](/docs/01-core-concepts/the-stack) - How the three protocols work together
-- [Object Model](/docs/01-core-concepts/object-model) - Deep dive into the universal object model
-- [ObjectQL Protocol](/docs/02-protocols/01-objectql) - Learn the data protocol specification
+- [The Stack](/docs/core-concepts/the-stack) - How the three protocols work together
+- [Object Model](/docs/core-concepts/object-model) - Deep dive into the universal object model
+- [ObjectQL Protocol](/docs/protocols/objectql) - Learn the data protocol specification
diff --git a/content/docs/01-core-concepts/object-model.mdx b/content/docs/core-concepts/object-model.mdx
similarity index 99%
rename from content/docs/01-core-concepts/object-model.mdx
rename to content/docs/core-concepts/object-model.mdx
index c193aca9c..1fccf9fe6 100644
--- a/content/docs/01-core-concepts/object-model.mdx
+++ b/content/docs/core-concepts/object-model.mdx
@@ -743,7 +743,7 @@ The Universal Object Model is the foundation of ObjectStack. Every other protoco
## Next Steps
-- [ObjectQL Protocol](/docs/02-protocols/01-objectql) - Full specification of the data protocol
+- [ObjectQL Protocol](/docs/protocols/objectql) - Full specification of the data protocol
- [Fields Reference](/docs/03-reference/fields) - Complete guide to all field types
- [Relationships](/docs/04-guides/relationships) - Deep dive into modeling complex relationships
- [Validation](/docs/04-guides/validation) - Advanced validation patterns
diff --git a/content/docs/01-core-concepts/the-stack.mdx b/content/docs/core-concepts/the-stack.mdx
similarity index 97%
rename from content/docs/01-core-concepts/the-stack.mdx
rename to content/docs/core-concepts/the-stack.mdx
index 4a24fe55f..7746304e6 100644
--- a/content/docs/01-core-concepts/the-stack.mdx
+++ b/content/docs/core-concepts/the-stack.mdx
@@ -499,7 +499,7 @@ The three protocols are **loosely coupled** but **tightly integrated**:
## Next Steps
-- [Object Model](/docs/01-core-concepts/object-model) - Deep dive into ObjectQL's universal object model
-- [ObjectQL Protocol](/docs/02-protocols/01-objectql) - Full data protocol specification
-- [ObjectOS Protocol](/docs/02-protocols/02-objectos) - Full control protocol specification
-- [ObjectUI Protocol](/docs/02-protocols/03-objectui) - Full view protocol specification
+- [Object Model](/docs/core-concepts/object-model) - Deep dive into ObjectQL's universal object model
+- [ObjectQL Protocol](/docs/protocols/objectql) - Full data protocol specification
+- [ObjectOS Protocol](/docs/protocols/objectos) - Full control protocol specification
+- [ObjectUI Protocol](/docs/protocols/objectui) - Full view protocol specification
diff --git a/content/docs/03-development/cli-tools.mdx b/content/docs/development/cli-tools.mdx
similarity index 99%
rename from content/docs/03-development/cli-tools.mdx
rename to content/docs/development/cli-tools.mdx
index 6151d8364..428429081 100644
--- a/content/docs/03-development/cli-tools.mdx
+++ b/content/docs/development/cli-tools.mdx
@@ -1009,8 +1009,8 @@ objectstack deploy
## 🔗 Related Resources
- [Project Structure Guide](/docs/guides/project-structure)
-- [Plugin Development](/docs/03-development/writing-plugins)
-- [Deployment Guide](/docs/04-transport)
+- [Plugin Development](/docs/development/writing-plugins)
+- [Deployment Guide](/docs/transport)
---
diff --git a/content/docs/03-development/custom-widgets.mdx b/content/docs/development/custom-widgets.mdx
similarity index 99%
rename from content/docs/03-development/custom-widgets.mdx
rename to content/docs/development/custom-widgets.mdx
index aab647470..8c9582e32 100644
--- a/content/docs/03-development/custom-widgets.mdx
+++ b/content/docs/development/custom-widgets.mdx
@@ -35,7 +35,7 @@ Widgets are **UI components** that render field values in forms and views. Objec
- **React** 18+, **Vue** 3+, or **Svelte** 4+ knowledge
- **TypeScript** familiarity
-- Understanding of [ObjectUI Protocol](/docs/02-protocols/02-objectui)
+- Understanding of [ObjectUI Protocol](/docs/protocols/objectui)
- Node.js 18+ and npm 9+
---
@@ -1093,9 +1093,9 @@ export const MyWidget = memo((props: FieldWidgetProps) => {
## 🔗 Related Resources
-- [ObjectUI Protocol](/docs/02-protocols/02-objectui)
+- [ObjectUI Protocol](/docs/protocols/objectui)
- [Field Types Reference](/docs/guides/field-types)
-- [Plugin Development](/docs/03-development/writing-plugins)
+- [Plugin Development](/docs/development/writing-plugins)
---
diff --git a/content/docs/03-development/index.mdx b/content/docs/development/index.mdx
similarity index 89%
rename from content/docs/03-development/index.mdx
rename to content/docs/development/index.mdx
index 40f738753..c78ad0d2f 100644
--- a/content/docs/03-development/index.mdx
+++ b/content/docs/development/index.mdx
@@ -10,19 +10,19 @@ ObjectStack is designed for **extensibility at every layer**. Whether you're bui
## 🎯 What You Can Extend
-
+
Add new objects, routes, scheduled jobs, and business logic
-
+
Build React/Vue components for custom field rendering
-
+
Connect to any database or data source (SQL, NoSQL, APIs)
-
+
Manage projects, generate code, and deploy with objectstack-cli
@@ -75,7 +75,7 @@ npm run dev
Build React/Vue components that integrate seamlessly with ObjectStack forms and views.
-[→ Custom Widgets Guide](/docs/03-development/custom-widgets)
+[→ Custom Widgets Guide](/docs/development/custom-widgets)
---
@@ -92,7 +92,7 @@ npm run build
Create custom Objects, API routes, scheduled jobs, and event listeners.
-[→ Plugin Development Guide](/docs/03-development/writing-plugins)
+[→ Plugin Development Guide](/docs/development/writing-plugins)
---
@@ -109,7 +109,7 @@ npm run build
Implement the `DriverInterface` to bridge ObjectQL with any database.
-[→ Driver Development Guide](/docs/03-development/server-drivers)
+[→ Driver Development Guide](/docs/development/server-drivers)
---
@@ -185,9 +185,9 @@ objectstack deploy
Before building extensions, familiarize yourself with the three core protocols:
-- [ObjectQL](/docs/02-protocols/01-objectql) - Data modeling and queries
-- [ObjectUI](/docs/02-protocols/02-objectui) - User interface definitions
-- [ObjectOS](/docs/02-protocols/03-objectos) - System runtime and plugin architecture
+- [ObjectQL](/docs/protocols/objectql) - Data modeling and queries
+- [ObjectUI](/docs/protocols/objectui) - User interface definitions
+- [ObjectOS](/docs/protocols/objectos) - System runtime and plugin architecture
@@ -208,10 +208,10 @@ Explore reference implementations:
Follow the step-by-step guides for your extension type:
-1. [Writing Plugins](/docs/03-development/writing-plugins)
-2. [Custom Widgets](/docs/03-development/custom-widgets)
-3. [Server Drivers](/docs/03-development/server-drivers)
-4. [CLI Tools](/docs/03-development/cli-tools)
+1. [Writing Plugins](/docs/development/writing-plugins)
+2. [Custom Widgets](/docs/development/custom-widgets)
+3. [Server Drivers](/docs/development/server-drivers)
+4. [CLI Tools](/docs/development/cli-tools)
diff --git a/content/docs/03-development/meta.json b/content/docs/development/meta.json
similarity index 100%
rename from content/docs/03-development/meta.json
rename to content/docs/development/meta.json
diff --git a/content/docs/03-development/server-drivers.mdx b/content/docs/development/server-drivers.mdx
similarity index 99%
rename from content/docs/03-development/server-drivers.mdx
rename to content/docs/development/server-drivers.mdx
index 12cb097ee..f7783c166 100644
--- a/content/docs/03-development/server-drivers.mdx
+++ b/content/docs/development/server-drivers.mdx
@@ -38,7 +38,7 @@ Drivers translate **ObjectQL queries** into database-specific operations and nor
## 📋 Prerequisites
- **TypeScript** knowledge
-- Understanding of [ObjectQL Protocol](/docs/02-protocols/01-objectql)
+- Understanding of [ObjectQL Protocol](/docs/protocols/objectql)
- Familiarity with target database (SQL, MongoDB, etc.)
- Node.js 18+ and npm 9+
@@ -1066,8 +1066,8 @@ try {
## 🔗 Related Resources
-- [ObjectQL Protocol](/docs/02-protocols/01-objectql)
-- [Plugin Development](/docs/03-development/writing-plugins)
+- [ObjectQL Protocol](/docs/protocols/objectql)
+- [Plugin Development](/docs/development/writing-plugins)
- [Query Reference](/docs/99-reference/objectql/query)
---
diff --git a/content/docs/03-development/writing-plugins.mdx b/content/docs/development/writing-plugins.mdx
similarity index 98%
rename from content/docs/03-development/writing-plugins.mdx
rename to content/docs/development/writing-plugins.mdx
index b22e61128..6fcdee61d 100644
--- a/content/docs/03-development/writing-plugins.mdx
+++ b/content/docs/development/writing-plugins.mdx
@@ -48,7 +48,7 @@ Before building a plugin, ensure you have:
- **Node.js** 18+ and **npm** 9+
- **TypeScript** 5+ knowledge
- **Zod** familiarity (schema validation library)
-- Understanding of [ObjectQL](/docs/02-protocols/01-objectql) and [ObjectOS](/docs/02-protocols/03-objectos)
+- Understanding of [ObjectQL](/docs/protocols/objectql) and [ObjectOS](/docs/protocols/objectos)
---
@@ -792,9 +792,9 @@ Include comprehensive README with:
## 🔗 Related Resources
-- [ObjectQL Protocol](/docs/02-protocols/01-objectql)
-- [ObjectOS Plugin System](/docs/02-protocols/03-objectos)
-- [Custom Drivers](/docs/03-development/server-drivers)
+- [ObjectQL Protocol](/docs/protocols/objectql)
+- [ObjectOS Plugin System](/docs/protocols/objectos)
+- [Custom Drivers](/docs/development/server-drivers)
- [API Reference](/docs/99-reference)
---
diff --git a/content/docs/00-introduction/architecture.mdx b/content/docs/introduction/architecture.mdx
similarity index 97%
rename from content/docs/00-introduction/architecture.mdx
rename to content/docs/introduction/architecture.mdx
index c4bedf1e2..5f293bd33 100644
--- a/content/docs/00-introduction/architecture.mdx
+++ b/content/docs/introduction/architecture.mdx
@@ -196,6 +196,6 @@ New features are additive, not breaking. Implementations can evolve independentl
## Next Steps
-- [Glossary](/docs/00-introduction/glossary) - Key terminology explained
-- [Core Concepts](/docs/01-core-concepts) - Understand metadata-driven development
-- [Protocols](/docs/02-protocols) - Dive into each protocol specification
+- [Glossary](/docs/introduction/glossary) - Key terminology explained
+- [Core Concepts](/docs/core-concepts) - Understand metadata-driven development
+- [Protocols](/docs/protocols) - Dive into each protocol specification
diff --git a/content/docs/00-introduction/design-principles.mdx b/content/docs/introduction/design-principles.mdx
similarity index 95%
rename from content/docs/00-introduction/design-principles.mdx
rename to content/docs/introduction/design-principles.mdx
index 1f1eee373..0baf615b5 100644
--- a/content/docs/00-introduction/design-principles.mdx
+++ b/content/docs/introduction/design-principles.mdx
@@ -156,6 +156,6 @@ By adhering to these values, we build software that is **resilient to change**,
## Next Steps
-- [Architecture](/docs/00-introduction/architecture) - See how these principles shape the system
-- [Glossary](/docs/00-introduction/glossary) - Understand key terms
-- [Core Concepts](/docs/01-core-concepts) - Learn about metadata-driven development
+- [Architecture](/docs/introduction/architecture) - See how these principles shape the system
+- [Glossary](/docs/introduction/glossary) - Understand key terms
+- [Core Concepts](/docs/core-concepts) - Learn about metadata-driven development
diff --git a/content/docs/00-introduction/glossary.mdx b/content/docs/introduction/glossary.mdx
similarity index 96%
rename from content/docs/00-introduction/glossary.mdx
rename to content/docs/introduction/glossary.mdx
index a14466a52..c6e4ac7f0 100644
--- a/content/docs/00-introduction/glossary.mdx
+++ b/content/docs/introduction/glossary.mdx
@@ -184,6 +184,6 @@ A pattern where the server sends UI structure as data (JSON), and the client ren
## Next Steps
-- [Core Concepts](/docs/01-core-concepts) - Understand metadata-driven development
-- [Protocols](/docs/02-protocols) - Explore the protocol specifications
-- [Development](/docs/03-development) - Start building with ObjectStack
+- [Core Concepts](/docs/core-concepts) - Understand metadata-driven development
+- [Protocols](/docs/protocols) - Explore the protocol specifications
+- [Development](/docs/development) - Start building with ObjectStack
diff --git a/content/docs/00-introduction/index.mdx b/content/docs/introduction/index.mdx
similarity index 75%
rename from content/docs/00-introduction/index.mdx
rename to content/docs/introduction/index.mdx
index e5b44d0fb..959d331f4 100644
--- a/content/docs/00-introduction/index.mdx
+++ b/content/docs/introduction/index.mdx
@@ -24,7 +24,7 @@ Think of it as:
Choose your learning path:
-- [Overview](/docs/00-introduction/overview) - What is ObjectStack?
-- [Design Principles](/docs/00-introduction/design-principles) - Core philosophy
-- [Architecture](/docs/00-introduction/architecture) - System overview
-- [Glossary](/docs/00-introduction/glossary) - Key terminology
+- [Overview](/docs/introduction/overview) - What is ObjectStack?
+- [Design Principles](/docs/introduction/design-principles) - Core philosophy
+- [Architecture](/docs/introduction/architecture) - System overview
+- [Glossary](/docs/introduction/glossary) - Key terminology
diff --git a/content/docs/00-introduction/meta.json b/content/docs/introduction/meta.json
similarity index 100%
rename from content/docs/00-introduction/meta.json
rename to content/docs/introduction/meta.json
diff --git a/content/docs/00-introduction/overview.mdx b/content/docs/introduction/overview.mdx
similarity index 91%
rename from content/docs/00-introduction/overview.mdx
rename to content/docs/introduction/overview.mdx
index 9e9b82614..d0979257e 100644
--- a/content/docs/00-introduction/overview.mdx
+++ b/content/docs/introduction/overview.mdx
@@ -99,7 +99,7 @@ Connecting multiple systems? ObjectStack's protocol-driven approach makes it eas
## Next Steps
-- [Design Principles](/docs/00-introduction/design-principles) - Understand the philosophy
-- [Architecture](/docs/00-introduction/architecture) - Deep dive into the system
-- [Glossary](/docs/00-introduction/glossary) - Learn key terminology
-- [Core Concepts](/docs/01-core-concepts) - Metadata-driven development explained
+- [Design Principles](/docs/introduction/design-principles) - Understand the philosophy
+- [Architecture](/docs/introduction/architecture) - Deep dive into the system
+- [Glossary](/docs/introduction/glossary) - Learn key terminology
+- [Core Concepts](/docs/core-concepts) - Metadata-driven development explained
diff --git a/content/docs/meta.json b/content/docs/meta.json
index f2db74f18..8142b6a88 100644
--- a/content/docs/meta.json
+++ b/content/docs/meta.json
@@ -1,6 +1,11 @@
{
"title": "Documentation",
"pages": [
+ "introduction",
+ "core-concepts",
+ "protocols",
+ "development",
+ "transport",
"quick-start",
"tutorials",
"guides",
diff --git a/content/docs/02-protocols/index.mdx b/content/docs/protocols/index.mdx
similarity index 84%
rename from content/docs/02-protocols/index.mdx
rename to content/docs/protocols/index.mdx
index 2e44e3ab2..a078de8a3 100644
--- a/content/docs/02-protocols/index.mdx
+++ b/content/docs/protocols/index.mdx
@@ -15,19 +15,19 @@ The ObjectStack Protocol is defined through three core specifications that work
}
title="ObjectQL (Data Protocol)"
- href="/docs/02-protocols/01-objectql"
+ href="/docs/protocols/objectql"
description="Define data structures, queries, and business logic. Database-agnostic abstraction layer."
/>
}
title="ObjectUI (UI Protocol)"
- href="/docs/02-protocols/02-objectui"
+ href="/docs/protocols/objectui"
description="Server-driven UI definitions. Express interfaces as JSON, not code."
/>
}
title="ObjectOS (System Protocol)"
- href="/docs/02-protocols/03-objectos"
+ href="/docs/protocols/objectos"
description="Runtime kernel, plugins, security, and integration. The platform foundation."
/>
@@ -52,9 +52,9 @@ Building an ObjectStack implementation?
- **Renderer Developers:** Build UI renderers (React, Vue, Flutter)
Start with:
-1. [ObjectOS - Lifecycle](/docs/02-protocols/03-objectos/lifecycle)
-2. [ObjectQL - Schema](/docs/02-protocols/01-objectql/schema)
-3. [ObjectUI - Concept](/docs/02-protocols/02-objectui/concept)
+1. [ObjectOS - Lifecycle](/docs/protocols/objectos/lifecycle)
+2. [ObjectQL - Schema](/docs/protocols/objectql/schema)
+3. [ObjectUI - Concept](/docs/protocols/objectui/concept)
### Platform Architects
@@ -65,9 +65,9 @@ Evaluating ObjectStack for your organization?
- **Solution Architects:** Design integration patterns
Start with:
-1. [ObjectQL - Types](/docs/02-protocols/01-objectql/types)
-2. [ObjectQL - Security](/docs/02-protocols/01-objectql/security)
-3. [ObjectOS - Config Resolution](/docs/02-protocols/03-objectos/config-resolution)
+1. [ObjectQL - Types](/docs/protocols/objectql/types)
+2. [ObjectQL - Security](/docs/protocols/objectql/security)
+3. [ObjectOS - Config Resolution](/docs/protocols/objectos/config-resolution)
### Advanced Users
@@ -78,9 +78,9 @@ Building complex applications with ObjectStack?
- **Integration Engineers:** Connect external systems
Start with:
-1. [ObjectQL - Query Syntax](/docs/02-protocols/01-objectql/query-syntax)
-2. [ObjectUI - Widget Contract](/docs/02-protocols/02-objectui/widget-contract)
-3. [ObjectOS - Plugin Spec](/docs/02-protocols/03-objectos/plugin-spec)
+1. [ObjectQL - Query Syntax](/docs/protocols/objectql/query-syntax)
+2. [ObjectUI - Widget Contract](/docs/protocols/objectui/widget-contract)
+3. [ObjectOS - Plugin Spec](/docs/protocols/objectos/plugin-spec)
## Specification Structure
@@ -196,17 +196,17 @@ Want to propose changes or additions?
diff --git a/content/docs/protocols/meta.json b/content/docs/protocols/meta.json
new file mode 100644
index 000000000..10bba84f1
--- /dev/null
+++ b/content/docs/protocols/meta.json
@@ -0,0 +1,8 @@
+{
+ "title": "📜 Protocols",
+ "pages": [
+ "objectql",
+ "objectui",
+ "objectos"
+ ]
+}
diff --git a/content/docs/02-protocols/03-objectos/config-resolution.mdx b/content/docs/protocols/objectos/config-resolution.mdx
similarity index 100%
rename from content/docs/02-protocols/03-objectos/config-resolution.mdx
rename to content/docs/protocols/objectos/config-resolution.mdx
diff --git a/content/docs/02-protocols/03-objectos/i18n-standard.mdx b/content/docs/protocols/objectos/i18n-standard.mdx
similarity index 99%
rename from content/docs/02-protocols/03-objectos/i18n-standard.mdx
rename to content/docs/protocols/objectos/i18n-standard.mdx
index 562df61e4..072f72057 100644
--- a/content/docs/02-protocols/03-objectos/i18n-standard.mdx
+++ b/content/docs/protocols/objectos/i18n-standard.mdx
@@ -48,7 +48,7 @@ plural('item', 5); // Pluralization
- ✅ Consistent API across all i18n operations
- ✅ Automatic locale detection
- ✅ Plugin-based translation bundles
-- ✅ <50KB total footprint
+- ✅ Less than 50KB total footprint
## Locale Resolution
@@ -838,4 +838,4 @@ ObjectOS i18n provides:
- **Dynamic locale switching** without page reload
- **Translation management tools** for extraction, validation, and coverage
-**Result:** Build globally-ready applications without wrestling with i18n libraries. Support 50+ languages with <100 lines of configuration.
+**Result:** Build globally-ready applications without wrestling with i18n libraries. Support 50+ languages with less than 100 lines of configuration.
diff --git a/content/docs/02-protocols/03-objectos/index.mdx b/content/docs/protocols/objectos/index.mdx
similarity index 100%
rename from content/docs/02-protocols/03-objectos/index.mdx
rename to content/docs/protocols/objectos/index.mdx
diff --git a/content/docs/02-protocols/03-objectos/lifecycle.mdx b/content/docs/protocols/objectos/lifecycle.mdx
similarity index 100%
rename from content/docs/02-protocols/03-objectos/lifecycle.mdx
rename to content/docs/protocols/objectos/lifecycle.mdx
diff --git a/content/docs/02-protocols/03-objectos/meta.json b/content/docs/protocols/objectos/meta.json
similarity index 100%
rename from content/docs/02-protocols/03-objectos/meta.json
rename to content/docs/protocols/objectos/meta.json
diff --git a/content/docs/02-protocols/03-objectos/plugin-spec.mdx b/content/docs/protocols/objectos/plugin-spec.mdx
similarity index 100%
rename from content/docs/02-protocols/03-objectos/plugin-spec.mdx
rename to content/docs/protocols/objectos/plugin-spec.mdx
diff --git a/content/docs/02-protocols/01-objectql/index.mdx b/content/docs/protocols/objectql/index.mdx
similarity index 94%
rename from content/docs/02-protocols/01-objectql/index.mdx
rename to content/docs/protocols/objectql/index.mdx
index 858ff3318..91c2c93bc 100644
--- a/content/docs/02-protocols/01-objectql/index.mdx
+++ b/content/docs/protocols/objectql/index.mdx
@@ -123,7 +123,7 @@ ObjectQL provides 20+ field types that encode business semantics:
| `currency` | Money with exchange rates | `{amount: 1000, currency: 'USD'}` |
| `address` | Geocoding & distance | `{street, city, lat, lng}` |
-See [Types Reference](/docs/02-protocols/01-objectql/types) for complete list.
+See [Types Reference](/docs/protocols/objectql/types) for complete list.
### 3. Query Language: Database-Agnostic AST
@@ -366,17 +366,17 @@ const securedQuery = {
};
```
-See [Security Protocol](/docs/02-protocols/01-objectql/security) for details.
+See [Security Protocol](/docs/protocols/objectql/security) for details.
## Learning Path
**Start Here:**
-1. [Schema Definition](/docs/02-protocols/01-objectql/schema) - Learn to define objects and fields
-2. [Type System](/docs/02-protocols/01-objectql/types) - Understand field types and relationships
+1. [Schema Definition](/docs/protocols/objectql/schema) - Learn to define objects and fields
+2. [Type System](/docs/protocols/objectql/types) - Understand field types and relationships
**Intermediate:**
-3. [Query Syntax](/docs/02-protocols/01-objectql/query-syntax) - Master the query language
-4. [Security](/docs/02-protocols/01-objectql/security) - Implement access control
+3. [Query Syntax](/docs/protocols/objectql/query-syntax) - Master the query language
+4. [Security](/docs/protocols/objectql/security) - Implement access control
**Advanced:**
5. [Driver Protocol](/docs/specifications/data/architecture) - Build custom database drivers
@@ -393,17 +393,17 @@ See [Security Protocol](/docs/02-protocols/01-objectql/security) for details.
diff --git a/content/docs/02-protocols/01-objectql/meta.json b/content/docs/protocols/objectql/meta.json
similarity index 100%
rename from content/docs/02-protocols/01-objectql/meta.json
rename to content/docs/protocols/objectql/meta.json
diff --git a/content/docs/02-protocols/01-objectql/query-syntax.mdx b/content/docs/protocols/objectql/query-syntax.mdx
similarity index 99%
rename from content/docs/02-protocols/01-objectql/query-syntax.mdx
rename to content/docs/protocols/objectql/query-syntax.mdx
index f493f3435..8c0eb8518 100644
--- a/content/docs/02-protocols/01-objectql/query-syntax.mdx
+++ b/content/docs/protocols/objectql/query-syntax.mdx
@@ -936,17 +936,17 @@ const monthlyRevenue = await ObjectQL.query({
diff --git a/content/docs/02-protocols/01-objectql/schema.mdx b/content/docs/protocols/objectql/schema.mdx
similarity index 99%
rename from content/docs/02-protocols/01-objectql/schema.mdx
rename to content/docs/protocols/objectql/schema.mdx
index 626df0b5d..2d560a98f 100644
--- a/content/docs/02-protocols/01-objectql/schema.mdx
+++ b/content/docs/protocols/objectql/schema.mdx
@@ -201,7 +201,7 @@ fields:
| Property | Type | Applies To | Description |
|----------|------|------------|-------------|
-| `type` | `string` | All | **Required.** Field type (see [Types](/docs/02-protocols/01-objectql/types)). |
+| `type` | `string` | All | **Required.** Field type (see [Types](/docs/protocols/objectql/types)). |
| `label` | `string` | All | **Required.** Display label in UI. |
| `required` | `boolean` | All | Validation: Field must have a value. |
| `unique` | `boolean` | All | Enforce uniqueness at database level. |
@@ -890,17 +890,17 @@ indexes:
diff --git a/content/docs/02-protocols/01-objectql/security.mdx b/content/docs/protocols/objectql/security.mdx
similarity index 99%
rename from content/docs/02-protocols/01-objectql/security.mdx
rename to content/docs/protocols/objectql/security.mdx
index 7e9d021fd..b655127a3 100644
--- a/content/docs/02-protocols/01-objectql/security.mdx
+++ b/content/docs/protocols/objectql/security.mdx
@@ -886,17 +886,17 @@ objectstack security:audit
diff --git a/content/docs/02-protocols/01-objectql/types.mdx b/content/docs/protocols/objectql/types.mdx
similarity index 99%
rename from content/docs/02-protocols/01-objectql/types.mdx
rename to content/docs/protocols/objectql/types.mdx
index fcd1e49b7..68538ab48 100644
--- a/content/docs/02-protocols/01-objectql/types.mdx
+++ b/content/docs/protocols/objectql/types.mdx
@@ -1075,17 +1075,17 @@ card_number:
diff --git a/content/docs/02-protocols/02-objectui/actions.mdx b/content/docs/protocols/objectui/actions.mdx
similarity index 99%
rename from content/docs/02-protocols/02-objectui/actions.mdx
rename to content/docs/protocols/objectui/actions.mdx
index 30ff4fd1b..8f239305c 100644
--- a/content/docs/02-protocols/02-objectui/actions.mdx
+++ b/content/docs/protocols/objectui/actions.mdx
@@ -3,7 +3,7 @@ title: Action Protocol
description: Buttons, triggers, navigation, and user interaction definitions
---
-import { MousePointer, Zap, ExternalLink, Workflow, GitBranch, Play } from 'lucide-react';
+import { MousePointer, Zap, ExternalLink, Workflow, GitBranch, Play, Component } from 'lucide-react';
# Action Protocol: Defining User Interactions
diff --git a/content/docs/02-protocols/02-objectui/concept.mdx b/content/docs/protocols/objectui/concept.mdx
similarity index 100%
rename from content/docs/02-protocols/02-objectui/concept.mdx
rename to content/docs/protocols/objectui/concept.mdx
diff --git a/content/docs/02-protocols/02-objectui/index.mdx b/content/docs/protocols/objectui/index.mdx
similarity index 100%
rename from content/docs/02-protocols/02-objectui/index.mdx
rename to content/docs/protocols/objectui/index.mdx
diff --git a/content/docs/02-protocols/02-objectui/layout-dsl.mdx b/content/docs/protocols/objectui/layout-dsl.mdx
similarity index 99%
rename from content/docs/02-protocols/02-objectui/layout-dsl.mdx
rename to content/docs/protocols/objectui/layout-dsl.mdx
index 4437c77a9..984d3e5d6 100644
--- a/content/docs/02-protocols/02-objectui/layout-dsl.mdx
+++ b/content/docs/protocols/objectui/layout-dsl.mdx
@@ -85,7 +85,7 @@ regions:
**Breakpoint Behavior:**
- **Desktop (≥1024px):** Sidebar on right (25% width)
- **Tablet (768-1023px):** Sidebar below main (full width)
-- **Mobile (<768px):** Sidebar below main (full width)
+- **Mobile (less than 768px):** Sidebar below main (full width)
### Console Template
@@ -250,7 +250,7 @@ section:
└──────────────┴──────────────┘
```
-**Mobile (<768px): 1 column**
+**Mobile (less than 768px): 1 column**
```
┌────────────────────────┐
│ Field A │
@@ -736,7 +736,7 @@ interface FieldLayout {
interface ResponsiveColumns {
desktop?: number; // ≥1024px
tablet?: number; // 768-1023px
- mobile?: number; // <768px
+ mobile?: number; // less than 768px
portrait?: number;
landscape?: number;
}
diff --git a/content/docs/02-protocols/02-objectui/meta.json b/content/docs/protocols/objectui/meta.json
similarity index 100%
rename from content/docs/02-protocols/02-objectui/meta.json
rename to content/docs/protocols/objectui/meta.json
diff --git a/content/docs/02-protocols/02-objectui/widget-contract.mdx b/content/docs/protocols/objectui/widget-contract.mdx
similarity index 100%
rename from content/docs/02-protocols/02-objectui/widget-contract.mdx
rename to content/docs/protocols/objectui/widget-contract.mdx
diff --git a/content/docs/04-transport/error-handling.mdx b/content/docs/transport/error-handling.mdx
similarity index 99%
rename from content/docs/04-transport/error-handling.mdx
rename to content/docs/transport/error-handling.mdx
index 1daccd4c7..d269d49f4 100644
--- a/content/docs/04-transport/error-handling.mdx
+++ b/content/docs/transport/error-handling.mdx
@@ -3,7 +3,7 @@ title: Error Handling
description: Global error codes, response formats, and debugging strategies for ObjectStack APIs
---
-import { AlertCircle, Bug, Shield, Info, AlertTriangle, XCircle } from 'lucide-react';
+import { AlertCircle, Bug, Shield, Info, AlertTriangle, XCircle, Radio, Zap } from 'lucide-react';
# Error Handling
diff --git a/content/docs/04-transport/http-api.mdx b/content/docs/transport/http-api.mdx
similarity index 99%
rename from content/docs/04-transport/http-api.mdx
rename to content/docs/transport/http-api.mdx
index 822cf33c0..ff1e49ecd 100644
--- a/content/docs/04-transport/http-api.mdx
+++ b/content/docs/transport/http-api.mdx
@@ -3,7 +3,7 @@ title: HTTP API
description: Standard REST mapping rules, CRUD operations, and request/response formats for ObjectStack
---
-import { Radio, Code, Database, Lock, Zap, CheckCircle } from 'lucide-react';
+import { Radio, Code, Database, Lock, Zap, CheckCircle, AlertCircle } from 'lucide-react';
# HTTP API
diff --git a/content/docs/04-transport/index.mdx b/content/docs/transport/index.mdx
similarity index 100%
rename from content/docs/04-transport/index.mdx
rename to content/docs/transport/index.mdx
diff --git a/content/docs/04-transport/meta.json b/content/docs/transport/meta.json
similarity index 100%
rename from content/docs/04-transport/meta.json
rename to content/docs/transport/meta.json
diff --git a/content/docs/04-transport/realtime.mdx b/content/docs/transport/realtime.mdx
similarity index 99%
rename from content/docs/04-transport/realtime.mdx
rename to content/docs/transport/realtime.mdx
index e28eef9d9..874d9a6cc 100644
--- a/content/docs/04-transport/realtime.mdx
+++ b/content/docs/transport/realtime.mdx
@@ -3,7 +3,7 @@ title: Real-Time Protocols
description: WebSocket subscriptions, Server-Sent Events, and event-driven communication in ObjectStack
---
-import { Zap, Radio, Activity, Bell, Users, Gauge } from 'lucide-react';
+import { Zap, Radio, Activity, Bell, Users, Gauge, AlertCircle } from 'lucide-react';
# Real-Time Protocols
From 82a1f85b48a26b959de20e61d0c51b38a9923b8d Mon Sep 17 00:00:00 2001
From: Jack Zhuang <50353452+hotlong@users.noreply.github.com>
Date: Mon, 26 Jan 2026 20:47:21 +0800
Subject: [PATCH 05/22] Refactor script name in package.json for consistency
---
apps/docs/package.json | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/apps/docs/package.json b/apps/docs/package.json
index 158ae15b6..e3b17a5cd 100644
--- a/apps/docs/package.json
+++ b/apps/docs/package.json
@@ -4,7 +4,7 @@
"private": true,
"description": "ObjectStack Protocol Documentation Site",
"scripts": {
- "site:dev": "next dev",
+ "dev": "next dev",
"build": "NEXT_PRIVATE_BUILD_WORKER=1 next build",
"site:start": "next start",
"site:lint": "next lint"
From 7139e3d529747962cae0fa769acb5439fb591080 Mon Sep 17 00:00:00 2001
From: Jack Zhuang <50353452+hotlong@users.noreply.github.com>
Date: Mon, 26 Jan 2026 21:09:44 +0800
Subject: [PATCH 06/22] Remove Chinese language support and documentation
Removed Chinese ('cn') from supported languages in i18n configuration and deleted extensive documentation files, including guides, FAQs, advanced topics, and field type references. This streamlines the documentation to English-only and removes related content and metadata for the Chinese locale.
---
apps/docs/lib/i18n.ts | 2 +-
content/docs/faq.mdx | 312 -------
.../guides/advanced/ai-integration-guide.mdx | 809 -----------------
.../guides/advanced/ai-integration/meta.json | 6 -
.../advanced/ai-integration/quick-start.mdx | 178 ----
content/docs/guides/advanced/meta.json | 9 -
.../guides/advanced/performance/meta.json | 6 -
.../advanced/performance/optimization.mdx | 140 ---
.../advanced/security/best-practices.mdx | 105 ---
.../docs/guides/advanced/security/meta.json | 6 -
content/docs/guides/custom-driver.cn.mdx | 136 ---
content/docs/guides/custom-driver.mdx | 136 ---
content/docs/guides/field-types.cn.mdx | 755 ----------------
content/docs/guides/field-types.mdx | 817 ------------------
content/docs/guides/getting-started.cn.mdx | 289 -------
content/docs/guides/getting-started.mdx | 289 -------
content/docs/guides/installation.cn.mdx | 46 -
content/docs/guides/installation.mdx | 46 -
content/docs/guides/meta.cn.json | 15 -
content/docs/guides/meta.json | 15 -
content/docs/guides/migration/index.mdx | 26 -
content/docs/guides/migration/meta.json | 7 -
content/docs/guides/migration/v0-to-v1.mdx | 154 ----
content/docs/guides/project-structure.cn.mdx | 45 -
content/docs/guides/project-structure.mdx | 44 -
content/docs/guides/view-configuration.mdx | 806 -----------------
content/docs/guides/workflows-validation.mdx | 733 ----------------
content/docs/index.cn.mdx | 71 --
content/docs/meta.cn.json | 14 -
.../docs/protocols/objectui/layout-dsl.mdx | 2 +-
content/docs/quick-start.mdx | 117 ---
content/docs/quick-start/architects.mdx | 502 -----------
.../docs/quick-start/backend-developers.mdx | 396 ---------
content/docs/quick-start/build-first-app.mdx | 367 --------
.../docs/quick-start/frontend-developers.mdx | 554 ------------
content/docs/quick-start/meta.cn.json | 10 -
content/docs/quick-start/meta.json | 10 -
content/docs/standards/api-design.mdx | 325 -------
content/docs/standards/authentication.mdx | 611 -------------
content/docs/standards/error-handling.mdx | 184 ----
content/docs/standards/index.mdx | 42 -
content/docs/standards/meta.cn.json | 11 -
content/docs/standards/meta.json | 11 -
content/docs/standards/naming-conventions.mdx | 81 --
content/docs/troubleshooting.mdx | 499 -----------
content/docs/tutorials.mdx | 137 ---
content/docs/tutorials/meta.cn.json | 5 -
content/docs/tutorials/meta.json | 5 -
48 files changed, 2 insertions(+), 9884 deletions(-)
delete mode 100644 content/docs/faq.mdx
delete mode 100644 content/docs/guides/advanced/ai-integration-guide.mdx
delete mode 100644 content/docs/guides/advanced/ai-integration/meta.json
delete mode 100644 content/docs/guides/advanced/ai-integration/quick-start.mdx
delete mode 100644 content/docs/guides/advanced/meta.json
delete mode 100644 content/docs/guides/advanced/performance/meta.json
delete mode 100644 content/docs/guides/advanced/performance/optimization.mdx
delete mode 100644 content/docs/guides/advanced/security/best-practices.mdx
delete mode 100644 content/docs/guides/advanced/security/meta.json
delete mode 100644 content/docs/guides/custom-driver.cn.mdx
delete mode 100644 content/docs/guides/custom-driver.mdx
delete mode 100644 content/docs/guides/field-types.cn.mdx
delete mode 100644 content/docs/guides/field-types.mdx
delete mode 100644 content/docs/guides/getting-started.cn.mdx
delete mode 100644 content/docs/guides/getting-started.mdx
delete mode 100644 content/docs/guides/installation.cn.mdx
delete mode 100644 content/docs/guides/installation.mdx
delete mode 100644 content/docs/guides/meta.cn.json
delete mode 100644 content/docs/guides/meta.json
delete mode 100644 content/docs/guides/migration/index.mdx
delete mode 100644 content/docs/guides/migration/meta.json
delete mode 100644 content/docs/guides/migration/v0-to-v1.mdx
delete mode 100644 content/docs/guides/project-structure.cn.mdx
delete mode 100644 content/docs/guides/project-structure.mdx
delete mode 100644 content/docs/guides/view-configuration.mdx
delete mode 100644 content/docs/guides/workflows-validation.mdx
delete mode 100644 content/docs/index.cn.mdx
delete mode 100644 content/docs/meta.cn.json
delete mode 100644 content/docs/quick-start.mdx
delete mode 100644 content/docs/quick-start/architects.mdx
delete mode 100644 content/docs/quick-start/backend-developers.mdx
delete mode 100644 content/docs/quick-start/build-first-app.mdx
delete mode 100644 content/docs/quick-start/frontend-developers.mdx
delete mode 100644 content/docs/quick-start/meta.cn.json
delete mode 100644 content/docs/quick-start/meta.json
delete mode 100644 content/docs/standards/api-design.mdx
delete mode 100644 content/docs/standards/authentication.mdx
delete mode 100644 content/docs/standards/error-handling.mdx
delete mode 100644 content/docs/standards/index.mdx
delete mode 100644 content/docs/standards/meta.cn.json
delete mode 100644 content/docs/standards/meta.json
delete mode 100644 content/docs/standards/naming-conventions.mdx
delete mode 100644 content/docs/troubleshooting.mdx
delete mode 100644 content/docs/tutorials.mdx
delete mode 100644 content/docs/tutorials/meta.cn.json
delete mode 100644 content/docs/tutorials/meta.json
diff --git a/apps/docs/lib/i18n.ts b/apps/docs/lib/i18n.ts
index 965705989..977986aaa 100644
--- a/apps/docs/lib/i18n.ts
+++ b/apps/docs/lib/i18n.ts
@@ -9,7 +9,7 @@ import { defineI18n } from 'fumadocs-core/i18n';
*/
export const i18n = defineI18n({
defaultLanguage: 'en',
- languages: ['en', 'cn'],
+ languages: ['en'],
// Hide locale prefix for default language (e.g., /docs instead of /en/docs)
hideLocale: 'default-locale',
});
diff --git a/content/docs/faq.mdx b/content/docs/faq.mdx
deleted file mode 100644
index c1d875970..000000000
--- a/content/docs/faq.mdx
+++ /dev/null
@@ -1,312 +0,0 @@
----
-title: FAQ
-description: Frequently Asked Questions about ObjectStack Protocol.
----
-
-## General Questions
-
-### What is ObjectStack?
-
-ObjectStack is a **metadata-driven protocol** for building enterprise applications. It lets you define your entire application—data models, business logic, and UI—as type-safe JSON/TypeScript configurations instead of writing code.
-
-Think of it as the "Salesforce Platform" or "ServiceNow Platform" but:
-- ✅ Open source
-- ✅ Self-hosted
-- ✅ Type-safe (TypeScript + Zod)
-- ✅ Database agnostic
-
-### Is ObjectStack a framework or a library?
-
-Neither! ObjectStack is a **protocol** (like HTTP or SQL). It defines:
-1. **Schemas** (what data looks like)
-2. **Contracts** (how systems communicate)
-3. **Standards** (naming conventions, best practices)
-
-You can build **implementations** of the protocol in any language (Node.js, Go, Python, etc.).
-
-### How is ObjectStack different from Prisma/TypeORM?
-
-| Feature | Prisma/TypeORM | ObjectStack |
-| :--- | :--- | :--- |
-| **Scope** | ORM (database only) | Full platform (data + UI + logic) |
-| **Business Logic** | Code-based | Declarative (formulas, workflows) |
-| **UI Generation** | None | Server-driven UI included |
-| **Validation** | Manual | Built-in validation rules |
-| **Multi-DB** | Schema-based | Driver-based (easier to extend) |
-
-**Use Prisma if:** You just need a type-safe ORM.
-**Use ObjectStack if:** You want a complete metadata-driven platform.
-
-### How is ObjectStack different from Strapi/Directus?
-
-| Feature | Strapi/Directus | ObjectStack |
-| :--- | :--- | :--- |
-| **Focus** | Headless CMS | Enterprise platform |
-| **Business Logic** | Code plugins | Declarative (no-code) |
-| **Type Safety** | Partial | Full (Zod schemas) |
-| **Formulas** | None | Yes (like Excel/Salesforce) |
-| **Workflows** | Basic | Advanced (state machines) |
-| **Offline-First** | No | Yes |
-
-**Use Strapi if:** You're building a content website.
-**Use ObjectStack if:** You're building CRUD-heavy apps (CRM, ERP, internal tools).
-
-### Can I use ObjectStack with my existing database?
-
-**Yes!** You have two options:
-
-1. **Generate ObjectStack schemas from your DB:**
- ```bash
- objectstack import --from postgres://...
- ```
-
-2. **Write a custom driver** to wrap your existing DB.
-
-### Is ObjectStack production-ready?
-
-ObjectStack is currently in **beta**. The protocol is stable, but implementations are evolving.
-
-**Stable:**
-- ✅ Schema definitions (`@objectstack/spec`)
-- ✅ TypeScript types
-- ✅ JSON Schema export
-
-**In Development:**
-- 🚧 Reference Kernel implementation
-- 🚧 React renderer
-- 🚧 PostgreSQL driver
-
-**Recommendation:** Use for internal tools and non-critical applications. Wait for v1.0 for production SaaS.
-
-## Technical Questions
-
-### What databases are supported?
-
-ObjectStack uses a **driver model**. Official drivers:
-
-- ✅ **In-Memory Driver** (development/testing)
-- 🚧 **PostgreSQL Driver** (in progress)
-- 🚧 **MySQL Driver** (planned)
-- 🚧 **MongoDB Driver** (planned)
-
-You can build custom drivers for:
-- Any SQL database
-- Any NoSQL database
-- SaaS APIs (Salesforce, Airtable, etc.)
-- Excel files, CSV, etc.
-
-### Does ObjectStack support GraphQL?
-
-**Yes!** ObjectStack auto-generates both REST and GraphQL APIs from your schema definitions.
-
-### Can I customize the generated UI?
-
-**Yes!** You have multiple levels of customization:
-
-1. **Theme-level:** Colors, fonts, spacing
-2. **Component-level:** Override specific components (Button, Input, etc.)
-3. **Layout-level:** Change view configurations
-4. **Complete custom renderer:** Build your own UI that consumes ObjectStack APIs
-
-### How do I handle complex business logic?
-
-ObjectStack provides multiple ways:
-
-1. **Formula Fields:** Excel-like formulas for calculations
- ```typescript
- Field.formula({ expression: 'amount * (1 - discount / 100)' })
- ```
-
-2. **Validation Rules:** Declarative constraints
- ```typescript
- ValidationRule.create({ condition: 'due_date > TODAY()' })
- ```
-
-3. **Workflows:** Trigger actions on events
- ```typescript
- Workflow.create({ trigger: 'after_update', actions: [...] })
- ```
-
-4. **Custom Code:** For truly complex logic, write TypeScript plugins
-
-### How does authentication work?
-
-ObjectStack supports **pluggable authentication providers**:
-
-- OAuth 2.0 / OIDC
-- SAML
-- JWT tokens
-- API keys
-- Custom providers
-
-Configure in your app manifest:
-
-```typescript
-Manifest.create({
- authentication: {
- provider: 'oauth2',
- config: { /* provider config */ },
- },
-});
-```
-
-### Is ObjectStack multi-tenant?
-
-**Yes!** ObjectStack supports multiple multi-tenancy strategies:
-
-1. **Schema-per-tenant:** Each tenant gets their own database schema
-2. **Row-level security:** Single schema with tenant isolation via RLS
-3. **Database-per-tenant:** Complete isolation
-
-Configure based on your needs.
-
-### How do I deploy ObjectStack apps?
-
-ObjectStack apps are standard Node.js applications. Deploy like any Node app:
-
-- **Docker:** `docker build` → `docker run`
-- **Kubernetes:** Standard K8s deployment
-- **Serverless:** AWS Lambda, Google Cloud Functions
-- **PaaS:** Heroku, Railway, Render
-
-See the [Deployment Guide](/docs/guides/deployment) for details.
-
-## Development Questions
-
-### Do I need to know Zod?
-
-**Helpful but not required.** If you've used Yup, Joi, or similar validation libraries, Zod will feel familiar.
-
-Basic example:
-```typescript
-import { z } from 'zod';
-
-const schema = z.object({
- name: z.string(),
- age: z.number().min(0),
-});
-```
-
-ObjectStack provides helper functions to hide Zod complexity:
-
-```typescript
-// Instead of raw Zod
-const raw = z.object({ title: z.string() });
-
-// Use ObjectStack helpers
-const Task = ObjectSchema.create({
- fields: {
- title: Field.text({ label: 'Title' }),
- }
-});
-```
-
-### How do I debug ObjectStack apps?
-
-1. **Schema validation errors:** Zod provides detailed error messages
-2. **Runtime logs:** ObjectStack kernel logs all operations
-3. **Query debugging:** Enable query logging to see generated SQL
-4. **UI debugging:** Inspect JSON configs in browser devtools
-
-### Can I use ObjectStack with React/Vue/Svelte?
-
-**Yes!** ObjectStack is UI-framework agnostic.
-
-**Option 1:** Use official renderers
-- `@objectstack/react-renderer` (recommended)
-- `@objectstack/vue-renderer` (planned)
-
-**Option 2:** Consume REST/GraphQL APIs from any framework
-
-```tsx
-// React example
-function TaskList() {
- const { data } = useFetch('/api/v1/objects/task');
- return
{/* your UI */}
;
-}
-```
-
-### How do I contribute to ObjectStack?
-
-See the [Contributing Guide](https://github.com/objectstack-ai/spec/blob/main/CONTRIBUTING.md).
-
-We welcome:
-- Bug reports
-- Documentation improvements
-- Driver implementations
-- Renderer implementations
-- Example applications
-
-## Business Questions
-
-### What's the license?
-
-**Apache 2.0** (open source, permissive).
-
-You can:
-- ✅ Use commercially
-- ✅ Modify and distribute
-- ✅ Use in proprietary software
-- ✅ Sublicense
-
-### Is there commercial support?
-
-Not yet. Commercial support and managed hosting are planned for the future.
-
-For now:
-- Community support via GitHub Discussions
-- Professional consulting available (contact team)
-
-### Can I build a SaaS product with ObjectStack?
-
-**Absolutely!** ObjectStack is designed for multi-tenant SaaS platforms.
-
-Many use cases:
-- Internal developer platforms
-- Vertical SaaS (industry-specific apps)
-- White-label solutions
-- Agency client portals
-
-### Who is behind ObjectStack?
-
-ObjectStack is an **open-source project** created by the ObjectStack AI team. See [GitHub Contributors](https://github.com/objectstack-ai/spec/graphs/contributors).
-
-## Common Errors
-
-### "Schema validation failed"
-
-**Cause:** Your schema definition doesn't match the Zod schema.
-
-**Solution:** Check the error message for which field failed. Common issues:
-- Missing required fields
-- Wrong field type
-- Invalid enum value
-
-### "Driver not found"
-
-**Cause:** Kernel can't find the database driver.
-
-**Solution:**
-```typescript
-import { MemoryDriver } from '@objectstack/driver-memory';
-
-kernel.registerDriver('memory', new MemoryDriver());
-```
-
-### "Circular dependency in lookup fields"
-
-**Cause:** Two objects reference each other, creating a cycle.
-
-**Solution:** Use lazy references:
-```typescript
-Field.lookup({
- reference: () => import('./other-object'),
-})
-```
-
-## Still Have Questions?
-
-- 📖 Check the [Guides](/docs/guides/getting-started)
-- 💬 Ask in [GitHub Issues](https://github.com/objectstack-ai/spec/issues)
-- 🐛 Report bugs in [GitHub Issues](https://github.com/objectstack-ai/spec/issues)
-- 📧 Email: support@objectstack.dev (for urgent issues)
diff --git a/content/docs/guides/advanced/ai-integration-guide.mdx b/content/docs/guides/advanced/ai-integration-guide.mdx
deleted file mode 100644
index 344f70ef7..000000000
--- a/content/docs/guides/advanced/ai-integration-guide.mdx
+++ /dev/null
@@ -1,809 +0,0 @@
----
-title: AI Integration Guide
-description: Complete guide to building AI-powered ObjectStack applications
----
-
-# AI Integration Guide
-
-> **Complete guide to building AI-powered ObjectStack applications**
-
-## Table of Contents
-
-1. [Introduction](#introduction)
-2. [AI Protocols Overview](#ai-protocols-overview)
-3. [Getting Started](#getting-started)
-4. [Building AI Agents](#building-ai-agents)
-5. [Implementing RAG](#implementing-rag)
-6. [Natural Language Queries](#natural-language-queries)
-7. [Model Registry](#model-registry)
-8. [Production Best Practices](#production-best-practices)
-9. [Example Applications](#example-applications)
-
----
-
-## Introduction
-
-ObjectStack provides a comprehensive AI protocol suite enabling you to build intelligent, context-aware applications. This guide covers all AI capabilities from RAG pipelines to natural language query processing.
-
-### What You Can Build
-
-- **Intelligent Assistants**: Context-aware chatbots with function calling
-- **Natural Language Interfaces**: Query data using plain English
-- **Code Generators**: Generate ObjectStack apps from descriptions
-- **Smart Automation**: AI-powered workflows and decision making
-
----
-
-## AI Protocols Overview
-
-ObjectStack includes four core AI protocols:
-
-### 1. Agent Protocol (`@objectstack/spec/ai/agent`)
-Define autonomous AI agents with:
-- Model configuration
-- Function calling (tools)
-- Knowledge base access (RAG)
-- Access control
-
-### 2. Model Registry Protocol (`@objectstack/spec/ai/model-registry`)
-Centralized LLM management:
-- Model configurations
-- Prompt templates
-- Fallback handling
-- Health monitoring
-
-### 3. RAG Pipeline Protocol (`@objectstack/spec/ai/rag-pipeline`)
-Retrieval-Augmented Generation:
-- Vector store configuration
-- Embedding models
-- Chunking strategies
-- Retrieval methods (similarity, MMR, hybrid)
-
-### 4. Natural Language Query Protocol (`@objectstack/spec/ai/nlq`)
-Transform natural language to ObjectQL:
-- Intent detection
-- Entity recognition
-- Timeframe parsing
-- Field mapping
-
----
-
-## Getting Started
-
-### Installation
-
-```bash
-npm install @objectstack/spec
-```
-
-### Basic Agent
-
-```typescript
-import { Agent } from '@objectstack/spec';
-
-const myAgent: Agent = {
- name: 'my_assistant',
- label: 'My AI Assistant',
- role: 'Customer Support Specialist',
- instructions: 'You are a helpful assistant.',
-
- model: {
- provider: 'openai',
- model: 'gpt-4-turbo-preview',
- temperature: 0.7,
- },
-
- active: true,
-};
-```
-
----
-
-## Building AI Agents
-
-### Agent Components
-
-#### 1. Identity & Role
-```typescript
-const agent: Agent = {
- name: 'support_agent', // snake_case identifier
- label: 'Support Agent', // Display name
- avatar: '/avatars/bot.png', // Optional avatar
- role: 'Customer Support', // Agent persona
-};
-```
-
-#### 2. Instructions (System Prompt)
-```typescript
-instructions: `You are an experienced customer support agent.
-
-Your responsibilities:
-- Answer questions professionally
-- Create support tickets when needed
-- Escalate complex issues
-
-Always be polite and solution-oriented.`
-```
-
-#### 3. Model Configuration
-```typescript
-model: {
- provider: 'openai',
- model: 'gpt-4-turbo-preview',
- temperature: 0.7, // Creativity (0-2)
- maxTokens: 2048, // Response length
- topP: 0.9, // Nucleus sampling
-}
-```
-
-#### 4. Tools (Function Calling)
-```typescript
-tools: [
- {
- type: 'action',
- name: 'create_ticket',
- description: 'Create a new support ticket',
- },
- {
- type: 'query',
- name: 'search_tickets',
- description: 'Search existing tickets',
- },
- {
- type: 'vector_search',
- name: 'kb_search',
- description: 'Search knowledge base',
- },
- {
- type: 'flow',
- name: 'escalate_to_human',
- description: 'Transfer to human agent',
- },
-]
-```
-
-#### 5. Knowledge Base (RAG)
-```typescript
-knowledge: {
- topics: ['product_docs', 'faq', 'troubleshooting'],
- indexes: ['support_kb_v2'],
-}
-```
-
-#### 6. Access Control
-```typescript
-access: ['support_team', 'customers'],
-active: true,
-```
-
-### Advanced Agent Example
-
-```typescript
-import { Agent } from '@objectstack/spec';
-
-export const DataAnalystAgent: Agent = {
- name: 'data_analyst_ai',
- label: 'AI Data Analyst',
- avatar: '/avatars/analyst.png',
- role: 'Business Intelligence Analyst',
-
- instructions: `You are a data analyst helping users understand business metrics.
-
-Skills:
-- Interpret natural language questions about data
-- Generate ObjectQL queries
-- Create visualizations
-- Provide actionable insights
-
-Be precise, data-driven, and clear.`,
-
- model: {
- provider: 'openai',
- model: 'gpt-4',
- temperature: 0.3, // Lower for precision
- maxTokens: 4096,
- },
-
- tools: [
- {
- type: 'query',
- name: 'execute_objectql',
- description: 'Execute ObjectQL queries on data',
- },
- {
- type: 'action',
- name: 'create_dashboard',
- description: 'Generate dashboard from metrics',
- },
- {
- type: 'action',
- name: 'generate_chart',
- description: 'Create visualizations',
- },
- ],
-
- knowledge: {
- topics: ['sql_guides', 'metrics_definitions'],
- indexes: ['analytics_kb'],
- },
-
- access: ['analysts', 'executives', 'managers'],
- active: true,
-};
-```
-
----
-
-## Implementing RAG
-
-### Why RAG?
-
-RAG (Retrieval-Augmented Generation) enables AI to:
-- Access up-to-date information
-- Reduce hallucinations
-- Provide source citations
-- Scale beyond context windows
-
-### RAG Pipeline Configuration
-
-```typescript
-import { RAGPipelineConfig } from '@objectstack/spec';
-
-const myRAG: RAGPipelineConfig = {
- name: 'knowledge_base',
- label: 'Knowledge Base RAG',
- description: 'RAG for product documentation',
-
- // 1. Embedding Model
- embedding: {
- provider: 'openai',
- model: 'text-embedding-3-large',
- dimensions: 3072,
- batchSize: 100,
- },
-
- // 2. Vector Store
- vectorStore: {
- provider: 'pinecone',
- indexName: 'kb-prod',
- namespace: 'v2',
- dimensions: 3072,
- metric: 'cosine',
- },
-
- // 3. Chunking Strategy
- chunking: {
- type: 'markdown',
- maxChunkSize: 1000,
- respectHeaders: true,
- respectCodeBlocks: true,
- },
-
- // 4. Retrieval Method
- retrieval: {
- type: 'mmr', // Maximal Marginal Relevance
- topK: 5,
- fetchK: 20,
- lambda: 0.7, // Balance relevance vs diversity
- },
-
- // 5. Optional Reranking
- reranking: {
- enabled: true,
- model: 'rerank-english-v3.0',
- provider: 'cohere',
- topK: 3,
- },
-
- // 6. Document Loaders
- loaders: [
- {
- type: 'directory',
- source: '/docs',
- fileTypes: ['.md', '.txt', '.pdf'],
- recursive: true,
- },
- ],
-
- maxContextTokens: 6000,
- enableCache: true,
- cacheTTL: 3600,
-};
-```
-
-### Chunking Strategies
-
-#### Fixed Size
-```typescript
-chunking: {
- type: 'fixed',
- chunkSize: 512,
- chunkOverlap: 50,
- unit: 'tokens',
-}
-```
-
-#### Semantic Chunking
-```typescript
-chunking: {
- type: 'semantic',
- minChunkSize: 100,
- maxChunkSize: 1000,
-}
-```
-
-#### Recursive Text Splitting
-```typescript
-chunking: {
- type: 'recursive',
- separators: ['\n\n', '\n', '. ', ' '],
- chunkSize: 1000,
- chunkOverlap: 100,
-}
-```
-
-#### Markdown-Aware
-```typescript
-chunking: {
- type: 'markdown',
- maxChunkSize: 1500,
- respectHeaders: true,
- respectCodeBlocks: true,
-}
-```
-
-### Retrieval Methods
-
-#### Similarity Search
-```typescript
-retrieval: {
- type: 'similarity',
- topK: 5,
- scoreThreshold: 0.7,
-}
-```
-
-#### MMR (Diverse Results)
-```typescript
-retrieval: {
- type: 'mmr',
- topK: 5,
- fetchK: 20,
- lambda: 0.5, // 0=diverse, 1=relevant
-}
-```
-
-#### Hybrid (Vector + Keyword)
-```typescript
-retrieval: {
- type: 'hybrid',
- topK: 10,
- vectorWeight: 0.7,
- keywordWeight: 0.3,
-}
-```
-
-### Querying RAG
-
-```typescript
-import { RAGQueryRequest } from '@objectstack/spec';
-
-const request: RAGQueryRequest = {
- query: 'How do I configure authentication?',
- pipelineName: 'knowledge_base',
- topK: 5,
- metadataFilters: {
- category: 'security',
- },
- includeMetadata: true,
- includeSources: true,
- executeQuery: false, // Just retrieve, don't generate
-};
-```
-
----
-
-## Natural Language Queries
-
-### NLQ Configuration
-
-```typescript
-import { NLQModelConfig } from '@objectstack/spec';
-
-const nlqConfig: NLQModelConfig = {
- modelId: 'gpt-4-turbo',
-
- // Prompt Engineering
- systemPrompt: `Convert natural language to ObjectQL.
- Available objects: account, opportunity, task`,
-
- includeSchema: true,
- includeExamples: true,
-
- // Features
- enableIntentDetection: true,
- enableEntityRecognition: true,
- enableFuzzyMatching: true,
- enableTimeframeDetection: true,
-
- // Caching
- enableCaching: true,
- cacheTTL: 3600,
-};
-```
-
-### Field Synonyms
-
-Help NLQ understand natural variations:
-
-```typescript
-import { FieldSynonymConfig } from '@objectstack/spec';
-
-const synonyms: FieldSynonymConfig[] = [
- {
- object: 'account',
- field: 'name',
- synonyms: [
- 'customer name',
- 'company name',
- 'organization name',
- 'account name',
- ],
- examples: [
- 'show accounts by customer name',
- 'find companies with name containing Acme',
- ],
- },
- {
- object: 'opportunity',
- field: 'amount',
- synonyms: [
- 'value',
- 'deal size',
- 'revenue',
- 'worth',
- ],
- },
-];
-```
-
-### Query Templates
-
-Pre-built patterns for common queries:
-
-```typescript
-import { QueryTemplate } from '@objectstack/spec';
-
-const topNTemplate: QueryTemplate = {
- id: 'top-n-by-field',
- name: 'top_n_by_field',
- label: 'Top N Records',
-
- pattern: 'top {n} {object} by {field}',
-
- variables: [
- { name: 'n', type: 'value', required: true },
- { name: 'object', type: 'object', required: true },
- { name: 'field', type: 'field', required: true },
- ],
-
- astTemplate: {
- object: '{object}',
- sort: [{ field: '{field}', order: 'desc' }],
- limit: '{n}',
- },
-
- examples: [
- 'top 10 accounts by revenue',
- 'top 5 opportunities by amount',
- ],
-};
-```
-
-### Processing NLQ Requests
-
-```typescript
-import { NLQRequest, NLQResponse } from '@objectstack/spec';
-
-const request: NLQRequest = {
- query: 'show me all high priority tickets from last week',
-
- context: {
- userId: 'user-123',
- currentObject: 'ticket',
- defaultLimit: 100,
- },
-
- includeAlternatives: true,
- maxAlternatives: 3,
- minConfidence: 0.7,
-
- executeQuery: true,
- maxResults: 50,
-};
-
-// Response includes:
-// - Parsed intent, entities, timeframe
-// - Generated ObjectQL AST
-// - Optional: Query results
-// - Confidence scores
-// - Alternative interpretations
-```
-
----
-
-## Model Registry
-
-### Registry Configuration
-
-```typescript
-import { ModelRegistry } from '@objectstack/spec';
-
-const registry: ModelRegistry = {
- name: 'production_registry',
-
- models: {
- 'gpt-4-turbo': {
- model: {
- id: 'gpt-4-turbo',
- name: 'GPT-4 Turbo',
- version: 'gpt-4-turbo-2024-04-09',
- provider: 'openai',
-
- capabilities: {
- textGeneration: true,
- functionCalling: true,
- reasoning: true,
- },
-
- limits: {
- maxTokens: 4096,
- contextWindow: 128000,
- rateLimit: {
- requestsPerMinute: 100,
- },
- },
-
- pricing: {
- inputCostPer1kTokens: 0.01,
- outputCostPer1kTokens: 0.03,
- },
- },
-
- status: 'active',
- priority: 10,
- fallbackModels: ['gpt-3.5-turbo'],
-
- healthCheck: {
- enabled: true,
- intervalSeconds: 300,
- status: 'healthy',
- },
- },
- },
-
- defaultModel: 'gpt-4-turbo',
- enableAutoFallback: true,
-};
-```
-
-### Prompt Templates
-
-Reusable prompts with variables:
-
-```typescript
-promptTemplates: {
- support_response: {
- id: 'support-v1',
- name: 'support_response',
- label: 'Support Response',
-
- system: 'You are a helpful support agent.',
- user: `Customer: {{customer_name}}
-Question: {{question}}
-Context: {{context}}`,
-
- variables: [
- { name: 'customer_name', type: 'string', required: true },
- { name: 'question', type: 'string', required: true },
- { name: 'context', type: 'string', required: false },
- ],
-
- modelId: 'gpt-4-turbo',
- temperature: 0.7,
- maxTokens: 2048,
-
- examples: [
- {
- input: {
- customer_name: 'John Doe',
- question: 'How do I reset my password?',
- },
- output: 'To reset your password...',
- },
- ],
- },
-}
-```
-
----
-
-## Production Best Practices
-
-### 1. Model Selection
-
-- **Reasoning tasks**: GPT-4, Claude 3 Opus
-- **Simple tasks**: GPT-3.5, Claude 3 Haiku
-- **Embeddings**: text-embedding-3-large
-- **Creative writing**: Claude 3 Sonnet
-
-### 2. Cost Optimization
-
-- Use smaller models for simple tasks
-- Enable caching for repeated queries
-- Batch embedding requests
-- Set appropriate token limits
-
-### 3. Error Handling
-
-```typescript
-{
- status: 'active',
- priority: 10,
- fallbackModels: ['backup-model'],
- healthCheck: {
- enabled: true,
- intervalSeconds: 300,
- },
-}
-```
-
-### 4. Security
-
-- Store API keys in environment variables
-- Use access control on agents
-- Validate user inputs
-- Implement rate limiting
-- Monitor for abuse
-
-### 5. Monitoring
-
-Track:
-- Response times
-- Token usage
-- Error rates
-- User satisfaction
-- Cache hit rates
-
-### 6. Testing
-
-```typescript
-import { NLQTrainingExample } from '@objectstack/spec';
-
-const trainingExamples: NLQTrainingExample[] = [
- {
- query: 'show all accounts created last month',
- expectedIntent: 'select',
- expectedObject: 'account',
- expectedAST: {
- object: 'account',
- filters: [['created_date', '>=', '2023-12-01']],
- },
- },
-];
-```
-
----
-
-## Example Applications
-
-### 1. AI Support Assistant
-[View Example](/docs/guides/examples/ai-support)
-
-**Features:**
-- RAG knowledge base
-- Ticket management
-- Escalation workflows
-- Customer satisfaction tracking
-
-**Architecture:**
-```
-Customer → GPT-4 Agent → RAG (Pinecone) → Actions → ObjectQL
-```
-
-### 2. AI Data Analyst
-[View Example](/docs/guides/examples/ai-analyst)
-
-**Features:**
-- Natural language queries
-- Auto-generate dashboards
-- Time-based analysis
-- Query templates
-
-### 3. AI Code Generator
-[View Example](/docs/guides/examples/ai-codegen)
-
-**Features:**
-- Generate ObjectStack apps
-- Schema validation
-- Best practices enforcement
-- RAG for documentation
-
-### 4. AI Sales Assistant
-[View Example](/docs/guides/examples/ai-sales)
-
-**Features:**
-- Lead qualification
-- Email personalization
-- Competitive intelligence
-- Deal insights
-
----
-
-## FAQ
-
-### When should I use RAG vs fine-tuning?
-
-**Use RAG when:**
-- Information changes frequently
-- You need source citations
-- Data is too large for context window
-- Privacy/compliance requirements
-
-**Use fine-tuning when:**
-- Teaching specific writing style
-- Domain-specific terminology
-- Consistent behavior needed
-- Cost optimization for high volume
-
-### How do I handle low confidence queries?
-
-```typescript
-if (response.parseResult.confidence < 0.7) {
- if (response.needsClarification) {
- // Ask user for clarification
- showSuggestions(response.suggestions);
- } else {
- // Show alternative interpretations
- showAlternatives(response.parseResult.alternatives);
- }
-}
-```
-
-### What vector database should I use?
-
-- **Pinecone**: Managed, easy to use
-- **Weaviate**: Open source, flexible
-- **Qdrant**: High performance, Rust-based
-- **pgvector**: PostgreSQL extension
-- **Chroma**: Local development
-
-### How do I optimize RAG performance?
-
-1. Use appropriate chunk sizes (500-1000 tokens)
-2. Enable reranking for accuracy
-3. Use MMR for diverse results
-4. Cache frequently accessed chunks
-5. Filter by metadata when possible
-6. Monitor retrieval metrics
-
----
-
-## Resources
-
-- [ObjectStack Documentation](https://docs.objectstack.ai)
-- [AI Protocol Reference](/docs/guides/packages/spec/src/ai)
-- [Example Applications](/docs/guides/examples)
-- [Discord Community](https://discord.gg/objectstack)
-
----
-
-## Next Steps
-
-1. Start with a simple agent
-2. Add RAG for your knowledge base
-3. Implement natural language queries
-4. Deploy to production
-5. Monitor and optimize
-
-Happy building! 🚀
diff --git a/content/docs/guides/advanced/ai-integration/meta.json b/content/docs/guides/advanced/ai-integration/meta.json
deleted file mode 100644
index 921f7be38..000000000
--- a/content/docs/guides/advanced/ai-integration/meta.json
+++ /dev/null
@@ -1,6 +0,0 @@
-{
- "title": "AI Integration",
- "pages": [
- "quick-start"
- ]
-}
diff --git a/content/docs/guides/advanced/ai-integration/quick-start.mdx b/content/docs/guides/advanced/ai-integration/quick-start.mdx
deleted file mode 100644
index c6e793980..000000000
--- a/content/docs/guides/advanced/ai-integration/quick-start.mdx
+++ /dev/null
@@ -1,178 +0,0 @@
----
-title: AI Integration Quick Start
-description: Quick guide to integrating AI features into ObjectStack applications
----
-
-# AI Integration Quick Start
-
-> Quick guide to integrating AI features into ObjectStack applications
-
-## Overview
-
-ObjectStack provides built-in AI capabilities through the AI Protocol. This guide covers the essentials.
-
-## Agent Setup
-
-### 1. Define an AI Agent
-
-```typescript
-const agent = {
- name: 'sales_assistant',
- label: 'Sales Assistant',
- model: {
- provider: 'openai',
- modelName: 'gpt-4',
- temperature: 0.7,
- },
- tools: [
- 'query_records',
- 'create_record',
- 'send_email',
- ],
- systemPrompt: 'You are a helpful sales assistant...',
-};
-```
-
-### 2. Configure Model Registry
-
-```typescript
-const modelRegistry = {
- models: [
- {
- id: 'gpt-4',
- provider: 'openai',
- capabilities: ['chat', 'function_calling'],
- limits: {
- maxTokens: 8192,
- maxContextLength: 128000,
- },
- },
- ],
-};
-```
-
-## RAG Pipeline
-
-### Basic RAG Configuration
-
-```typescript
-const ragConfig = {
- knowledgeBases: ['product_docs', 'sales_playbook'],
-
- chunking: {
- strategy: 'semantic',
- chunkSize: 512,
- overlap: 50,
- },
-
- embedding: {
- model: 'text-embedding-ada-002',
- provider: 'openai',
- },
-
- vectorStore: {
- provider: 'pinecone',
- config: {
- apiKey: process.env.PINECONE_API_KEY,
- environment: 'production',
- },
- },
-
- retrieval: {
- topK: 5,
- minScore: 0.7,
- },
-};
-```
-
-## Natural Language Queries
-
-### Enable NLQ for Objects
-
-```typescript
-const nlqConfig = {
- enabled: true,
- objects: ['customer_account', 'opportunity'],
-
- fieldMappings: [
- {
- synonyms: ['revenue', 'sales', 'income'],
- field: 'annual_revenue',
- },
- {
- synonyms: ['company', 'business', 'organization'],
- field: 'account_name',
- },
- ],
-
- examples: [
- {
- query: 'show me high value customers',
- intent: 'list',
- filters: [{ field: 'annual_revenue', operator: 'gt', value: 1000000 }],
- },
- ],
-};
-```
-
-## Using AI Tools
-
-### Query with Natural Language
-
-```typescript
-const result = await ai.query({
- prompt: 'Show me all accounts in the technology industry with revenue over $1M',
- object: 'customer_account',
-});
-
-// Returns: QueryResult with structured data
-```
-
-### Generate with AI
-
-```typescript
-const generated = await ai.generate({
- prompt: 'Write a follow-up email for this customer',
- context: {
- customer: customerData,
- lastInteraction: interactionData,
- },
-});
-```
-
-## Best Practices
-
-1. **Prompt Engineering**
- - Be specific and clear
- - Provide context
- - Use examples
-
-2. **Model Selection**
- - Use appropriate model for task
- - Balance cost vs. capability
- - Consider latency requirements
-
-3. **RAG Optimization**
- - Chunk documents semantically
- - Use appropriate embedding models
- - Filter results by relevance score
-
-4. **Error Handling**
- - Handle model failures gracefully
- - Implement retry logic
- - Provide fallbacks
-
-## Examples
-
-See the following example implementations:
-
-- [AI Sales Assistant](/docs/examples/ai-sales/)
-- [AI Support Agent](/docs/examples/ai-support/)
-- [AI Code Generator](/docs/examples/ai-codegen/)
-- [AI Analyst](/docs/examples/ai-analyst/)
-
-For complete documentation, see [AI_INTEGRATION_GUIDE.md](/docs/guides/AI_INTEGRATION_GUIDE.md)
-
----
-
-**Last Updated**: 2026-01-22
diff --git a/content/docs/guides/advanced/meta.json b/content/docs/guides/advanced/meta.json
deleted file mode 100644
index 624f5b38e..000000000
--- a/content/docs/guides/advanced/meta.json
+++ /dev/null
@@ -1,9 +0,0 @@
-{
- "title": "Advanced Guides",
- "pages": [
- "ai-integration-guide",
- "ai-integration",
- "security",
- "performance"
- ]
-}
diff --git a/content/docs/guides/advanced/performance/meta.json b/content/docs/guides/advanced/performance/meta.json
deleted file mode 100644
index e4f6c882d..000000000
--- a/content/docs/guides/advanced/performance/meta.json
+++ /dev/null
@@ -1,6 +0,0 @@
-{
- "title": "Performance",
- "pages": [
- "optimization"
- ]
-}
diff --git a/content/docs/guides/advanced/performance/optimization.mdx b/content/docs/guides/advanced/performance/optimization.mdx
deleted file mode 100644
index b8bb38703..000000000
--- a/content/docs/guides/advanced/performance/optimization.mdx
+++ /dev/null
@@ -1,140 +0,0 @@
----
-title: Performance Optimization
-description: Strategies for optimizing ObjectStack Protocol implementations
----
-
-# Performance Optimization Guide
-
-> Strategies for optimizing ObjectStack Protocol implementations
-
-## Query Optimization
-
-### Select Only Needed Fields
-```typescript
-// ✅ Good
-const query = {
- select: ['id', 'name', 'email'],
- from: 'customer_account',
-};
-
-// ❌ Bad
-const query = {
- select: ['*'], // Unnecessary data
- from: 'customer_account',
-};
-```
-
-### Use Efficient Filters
-- Apply filters at database level
-- Use indexed fields in WHERE clauses
-- Implement pagination
-
-### Avoid N+1 Queries
-- Use joins instead of loops
-- Batch load related data
-- Use DataLoader pattern
-
-## Caching Strategies
-
-### Metadata Caching
-- Cache object/field definitions (1 hour TTL)
-- Cache user permissions (10 minutes TTL)
-- Use Redis for distributed caching
-
-### Query Result Caching
-```typescript
-const cacheKey = `query:${JSON.stringify(query)}`;
-const cached = await redis.get(cacheKey);
-if (cached) return JSON.parse(cached);
-
-const results = await executeQuery(query);
-await redis.setEx(cacheKey, 300, JSON.stringify(results));
-```
-
-### Cache Invalidation
-- Invalidate on data changes
-- Use cache tags/patterns
-- Implement TTL strategies
-
-## Database Indexing
-
-### Index Strategy
-```typescript
-const indexes = [
- { fields: ['email'], unique: true },
- { fields: ['status'] },
- { fields: ['industry', 'revenue'] }, // Composite
-];
-```
-
-### Best Practices
-- Index frequently queried fields
-- Use composite indexes for multi-field queries
-- Monitor and remove unused indexes
-
-## API Performance
-
-### Connection Pooling
-```typescript
-const pool = new Pool({
- min: 2,
- max: 10,
- idleTimeoutMillis: 30000,
-});
-```
-
-### Response Compression
-- Enable gzip compression
-- Only compress responses > 1KB
-- Use level 6 compression
-
-### Async Operations
-```typescript
-// Parallel execution
-const [accounts, opportunities] = await Promise.all([
- queryAccounts(),
- queryOpportunities(),
-]);
-```
-
-## Frontend Optimization
-
-### Lazy Loading
-- Load components on demand
-- Code splitting
-- Dynamic imports
-
-### Virtualization
-- Use virtual scrolling for long lists
-- Render only visible items
-- Implement infinite scroll
-
-### Memoization
-- Cache expensive computations
-- Use React.memo for components
-- useMemo for derived data
-
-## Monitoring
-
-### Performance Metrics
-- Track query duration
-- Log slow queries (> 1s)
-- Monitor cache hit rates
-
-### Profiling
-- Use EXPLAIN ANALYZE for queries
-- Profile application code
-- Monitor resource usage
-
-## Performance Targets
-
-| Metric | Target |
-|--------|--------|
-| API Response (p95) | < 500ms |
-| Database Query (p95) | < 200ms |
-| Page Load | < 2s |
-| Cache Hit Rate | > 80% |
-
----
-
-**Last Updated**: 2026-01-22
diff --git a/content/docs/guides/advanced/security/best-practices.mdx b/content/docs/guides/advanced/security/best-practices.mdx
deleted file mode 100644
index 9a3823d44..000000000
--- a/content/docs/guides/advanced/security/best-practices.mdx
+++ /dev/null
@@ -1,105 +0,0 @@
----
-title: Security Best Practices
-description: Comprehensive security guidelines for ObjectStack Protocol implementations
----
-
-# Security Best Practices Guide
-
-> Comprehensive security guidelines for ObjectStack Protocol implementations
-
-## Authentication & Authorization
-
-### Strong Authentication
-```typescript
-const authConfig = {
- providers: [
- {
- type: 'email_password',
- passwordPolicy: {
- minLength: 12,
- requireUppercase: true,
- requireNumbers: true,
- requireSpecialChars: true,
- },
- },
- ],
- twoFactor: {
- enabled: true,
- required: true,
- },
-};
-```
-
-### Session Management
-- Use short session lifetimes (1-24 hours)
-- Set secure cookie flags (httpOnly, secure, sameSite)
-- Invalidate sessions on password change
-
-### RBAC
-- Implement least privilege principle
-- Use role-based access control
-- Apply field-level security
-
-## Data Protection
-
-### Encryption
-- Encrypt sensitive fields at rest
-- Use HTTPS/TLS for all traffic
-- Implement proper key management
-
-### Data Masking
-- Mask sensitive data in logs
-- Sanitize error messages
-- Redact PII in responses
-
-## API Security
-
-### Rate Limiting
-- Limit API requests per user
-- Block brute force attacks
-- Implement exponential backoff
-
-### Input Validation
-- Validate all inputs with Zod schemas
-- Use parameterized queries
-- Prevent SQL/NoSQL injection
-
-### CORS & CSRF
-- Configure CORS properly
-- Enable CSRF protection
-- Validate origin headers
-
-## Secrets Management
-
-- Store secrets in environment variables
-- Never commit secrets to git
-- Rotate secrets regularly
-- Use secret management services
-
-## Audit & Compliance
-
-### Audit Logging
-- Log security events
-- Track data access
-- Monitor authentication attempts
-
-### Compliance
-- GDPR data export/erasure
-- HIPAA encryption requirements
-- SOC2 audit trails
-
-## Security Checklist
-
-- [ ] HTTPS enforced
-- [ ] MFA enabled
-- [ ] Rate limiting configured
-- [ ] Input validation on all endpoints
-- [ ] Secrets in environment variables
-- [ ] Audit logging enabled
-- [ ] Regular security updates
-
-For detailed information, see [AUTHENTICATION_STANDARD.md](/docs/AUTHENTICATION_STANDARD.md)
-
----
-
-**Last Updated**: 2026-01-22
diff --git a/content/docs/guides/advanced/security/meta.json b/content/docs/guides/advanced/security/meta.json
deleted file mode 100644
index 8e41b7a1f..000000000
--- a/content/docs/guides/advanced/security/meta.json
+++ /dev/null
@@ -1,6 +0,0 @@
-{
- "title": "Security",
- "pages": [
- "best-practices"
- ]
-}
diff --git a/content/docs/guides/custom-driver.cn.mdx b/content/docs/guides/custom-driver.cn.mdx
deleted file mode 100644
index 2c7416f12..000000000
--- a/content/docs/guides/custom-driver.cn.mdx
+++ /dev/null
@@ -1,136 +0,0 @@
----
-title: 构建自定义驱动
-description: 学习如何使用驱动接口为 ObjectStack 实现自定义数据库驱动。
----
-
-# 构建自定义驱动
-
-驱动程序(Driver)是 **ObjectQL** 引擎与底层数据存储(SQL、NoSQL、API 等)之间的桥梁。通过实现 `DriverInterface`,您可以将 ObjectStack 连接到任何数据源。
-
-本指南将以创建一个简单的 **内存驱动(In-Memory Driver)** 为例进行讲解。
-
-## 先决条件
-
-- 现有的 ObjectStack 工作区或插件包。
-- 依赖 `@objectstack/objectql` 和 `@objectstack/spec`。
-
-## 1. 驱动接口 (Driver Interface)
-
-所有驱动程序必须实现规范中定义的 `DriverInterface`。
-
-### 重要:ID 兼容性规范
-
-ObjectStack 协议强制要求所有记录必须包含一个类型为 `string` 的 `id` 字段。
-底层数据库可能使用不同的惯例(例如 MongoDB 使用 `_id`,SQL 使用 `int` 类型的 ID)。
-**驱动程序负责将这些转换为标准的字符串 `id`。**
-
-- **输入**: 当 `update` 或 `delete` 方法接收 `id` 参数时,将其视为唯一主键。
-- **输出**: 当 `find`、`create` 或 `update` 返回记录时,确保:
- - 必须包含 `id` 字段(字符串)。
- - 应移除或映射实现特定的 ID(如 `_id`)。
-
-```typescript
-import { DriverInterface, DriverOptions } from '@objectstack/spec';
-import { QueryAST, QueryResult } from '@objectstack/objectql';
-
-export class MyCustomDriver implements DriverInterface {
- name = 'MyCustomDriver';
-
- async connect() {
- // 初始化连接
- }
-
- async disconnect() {
- // 关闭连接
- }
-
- // ... CRUD 方法
-}
-```
-
-## 2. 实现 CRUD 操作
-
-您需要实现 `find`(查询)、`insert`(插入)、`update`(更新)和 `delete`(删除)方法。
-
-### Find (查询)
-
-`find` 方法接收一个 `QueryAST` 对象,其中包含结构化的查询信息(过滤、排序、分页)。
-
-```typescript
-async find(object: string, query: QueryAST, options?: DriverOptions): Promise {
- // 1. 将 QueryAST 转换为数据库的查询语言(例如 SQL)
- // 2. 执行查询
- const results = await db.query(...);
-
- // 3. 规范化 ID (MongoDB 风格示例)
- return results.map(doc => ({
- ...doc,
- id: doc._id.toString(), // 映射 _id -> id
- _id: undefined // 隐藏实现细节
- }));
-}
-```
-
-### Insert (插入)
-
-```typescript
-async insert(object: string, data: Record, options?: DriverOptions) {
- // 将数据插入存储
- return data;
-}
-```
-
-### Update (更新)
-
-```typescript
-async update(object: string, id: string, data: Record, options?: DriverOptions) {
- // 更新由 `id` 标识的记录
- return { id, ...data };
-}
-```
-
-### Delete (删除)
-
-```typescript
-async delete(object: string, id: string, options?: DriverOptions) {
- // 删除记录
-}
-```
-
-## 3. 类型处理
-
-使用 `@objectstack/objectql` 提供的类型以确保兼容性。
-
-- `QueryAST`: 通用的查询抽象语法树。
-- `QueryResult`: `Record[]`.
-
-## 4. 注册驱动
-
-在插件的运行时入口点(例如 `index.ts`)导出驱动程序,以便引擎使用。
-
-```typescript
-import { MyCustomDriver } from './my-driver';
-
-export default {
- drivers: [new MyCustomDriver()]
-};
-```
-
-## 示例:内存驱动
-
-请参考 `examples/plugin-driver-memory` 中的参考实现。
-
-```typescript
-// examples/plugin-driver-memory/src/memory-driver.ts
-export class InMemoryDriver implements DriverInterface {
- name = 'InMemory';
- private store = new Map>();
-
- async find(object: string, query: QueryAST) {
- const table = this.store.get(object) || new Map();
- // 简单的过滤实现...
- return Array.from(table.values());
- }
- // ...
-}
-```
diff --git a/content/docs/guides/custom-driver.mdx b/content/docs/guides/custom-driver.mdx
deleted file mode 100644
index 61fda057b..000000000
--- a/content/docs/guides/custom-driver.mdx
+++ /dev/null
@@ -1,136 +0,0 @@
----
-title: Building a Custom Driver
-description: Learn how to implement a custom database driver for ObjectStack using the Driver Interface.
----
-
-# Building a Custom Driver
-
-Drivers are the bridge between the **ObjectQL** engine and the underlying data storage (SQL, NoSQL, APIs, etc.). By implementing the `DriverInterface`, you can connect ObjectStack to any data source.
-
-In this guide, we will walk through creating a simple **In-Memory Driver** as an example.
-
-## Prerequisites
-
-- Existing ObjectStack workspace or plugin package.
-- Dependency on `@objectstack/objectql` and `@objectstack/spec`.
-
-## 1. The Driver Interface
-
-All drivers must implement the `DriverInterface` defined in the specification.
-
-### Important: ID Compatibility
-
-The ObjectStack protocol mandates that all records MUST have an `id` field of type `string`.
-Underlying databases might use different conventions (e.g., `_id` in MongoDB, `int` IDs in SQL).
-**The Driver is responsible for mapping these to the standard string `id`.**
-
-- **Input:** When receiving an `id` in `update` or `delete`, treat it as the primary key.
-- **Output:** When returning records from `find`, `create`, or `update`, ensure:
- - There is an `id` field (string).
- - Implementation-specific IDs (like `_id`) should be removed or mapped.
-
-```typescript
-import { DriverInterface, DriverOptions } from '@objectstack/spec';
-import { QueryAST, QueryResult } from '@objectstack/objectql';
-
-export class MyCustomDriver implements DriverInterface {
- name = 'MyCustomDriver';
-
- async connect() {
- // Initialize connection
- }
-
- async disconnect() {
- // Close connection
- }
-
- // ... CRUD Methods
-}
-```
-
-## 2. Implementing CRUD Operations
-
-You need to implement `find`, `insert`, `update`, and `delete` methods.
-
-### Find (Query)
-
-The `find` method receives a `QueryAST` object, which contains structured query information (filters, sorting, pagination).
-
-```typescript
-async find(object: string, query: QueryAST, options?: DriverOptions): Promise {
- // 1. Convert QueryAST to your database's query language (e.g., SQL)
- // 2. Execute query
- const results = await db.query(...);
-
- // 3. Normalize ID (Example for Mongo-like DB)
- return results.map(doc => ({
- ...doc,
- id: doc._id.toString(), // Map _id -> id
- _id: undefined // Hide implementation details
- }));
-}
-```
-
-### Insert (Create)
-
-```typescript
-async insert(object: string, data: Record, options?: DriverOptions) {
- // Insert data into the storage
- return data;
-}
-```
-
-### Update
-
-```typescript
-async update(object: string, id: string, data: Record, options?: DriverOptions) {
- // Update the record identified by `id`
- return { id, ...data };
-}
-```
-
-### Delete
-
-```typescript
-async delete(object: string, id: string, options?: DriverOptions) {
- // Remove the record
-}
-```
-
-## 3. Handling Types
-
-Use the types provided by `@objectstack/objectql` to ensure compatibility.
-
-- `QueryAST`: The universal abstract syntax tree for queries.
-- `QueryResult`: `Record[]`.
-
-## 4. Registering the Driver
-
-In your plugin's runtime entry point (e.g., `index.ts`), export the driver so it can be used by the engine.
-
-```typescript
-import { MyCustomDriver } from './my-driver';
-
-export default {
- drivers: [new MyCustomDriver()]
-};
-```
-
-## Example: In-Memory Driver
-
-See the reference implementation in `examples/plugin-driver-memory`.
-
-```typescript
-// examples/plugin-driver-memory/src/memory-driver.ts
-export class InMemoryDriver implements DriverInterface {
- name = 'InMemory';
- private store = new Map>();
-
- async find(object: string, query: QueryAST) {
- const table = this.store.get(object) || new Map();
- // Simple filter implementation...
- return Array.from(table.values());
- }
- // ...
-}
-```
diff --git a/content/docs/guides/field-types.cn.mdx b/content/docs/guides/field-types.cn.mdx
deleted file mode 100644
index 2f90e4668..000000000
--- a/content/docs/guides/field-types.cn.mdx
+++ /dev/null
@@ -1,755 +0,0 @@
----
-title: 字段类型参考
-description: ObjectStack 所有字段类型的完整指南,包含示例和配置选项
----
-
-
-# 字段类型参考
-
-ObjectStack 支持 **35 种字段类型**,涵盖文本、数字、日期、选择、关联、媒体、计算和增强类型。本指南为每种类型提供实用示例。
-
-## 核心文本字段
-
-### Text (文本)
-单行文本输入,用于短字符串。
-
-```typescript
-import { Field } from '@objectstack/spec';
-
-// 基础文本字段
-name: Field.text({
- label: '姓名',
- required: true,
- maxLength: 255,
-})
-
-// 可搜索文本字段
-account_name: Field.text({
- label: '账户名称',
- searchable: true,
- unique: true,
-})
-```
-
-**配置选项:**
-- `required` - 设为必填字段
-- `maxLength` - 最大字符限制
-- `minLength` - 最小字符限制
-- `searchable` - 启用全文搜索
-- `unique` - 强制唯一性约束
-- `defaultValue` - 设置默认值
-
----
-
-### Textarea (多行文本)
-多行文本输入,用于较长内容。
-
-```typescript
-description: Field.textarea({
- label: '描述',
- maxLength: 5000,
- rows: 5, // UI 初始高度提示
-})
-```
-
----
-
-### Email (电子邮件)
-带验证的电子邮件地址字段。
-
-```typescript
-email: Field.email({
- label: '电子邮件',
- required: true,
- unique: true,
-})
-```
-
-> ℹ️ **Info:**
- 自动验证邮箱格式:`user@domain.com`
-
-
----
-
-### URL (网址)
-网站/链接字段,带 URL 验证。
-
-```typescript
-website: Field.url({
- label: '网站',
- placeholder: 'https://example.com',
-})
-```
-
----
-
-### Phone (电话)
-带格式验证的电话号码字段。
-
-```typescript
-phone: Field.phone({
- label: '电话号码',
- format: 'international', // 或 'us', 'uk'
-})
-```
-
----
-
-### Password (密码)
-带加密的安全密码字段。
-
-```typescript
-api_key: Field.password({
- label: 'API 密钥',
- encryption: true, // 静态加密
- readonly: true,
-})
-```
-
-> ⚠️ **Warning:**
- 密码字段在 UI 中自动掩码,如果 `encryption: true` 则加密存储
-
-
----
-
-## 富内容字段
-
-### Markdown
-支持预览的 Markdown 文本编辑器。
-
-```typescript
-documentation: Field.markdown({
- label: '文档',
- description: '支持完整 Markdown 语法',
-})
-```
-
----
-
-### HTML
-原始 HTML 编辑器(谨慎使用)。
-
-```typescript
-html_content: Field.html({
- label: 'HTML 内容',
- description: '原始 HTML - 渲染前需要净化',
-})
-```
-
-> ⚠️ **Warning:**
- 渲染前务必净化 HTML 内容,防止 XSS 攻击
-
-
----
-
-### Rich Text (富文本)
-带格式化工具栏的所见即所得编辑器。
-
-```typescript
-notes: Field.richtext({
- label: '备注',
- description: '富文本支持格式化、列表、链接',
-})
-```
-
-**支持:**
-- 粗体、斜体、下划线
-- 标题、列表、引用
-- 链接和图片
-- 表格
-
----
-
-## 数字字段
-
-### Number (数字)
-整数或小数的数值字段。
-
-```typescript
-quantity: Field.number({
- label: '数量',
- min: 0,
- max: 1000,
- defaultValue: 1,
-})
-
-// 小数
-temperature: Field.number({
- label: '温度',
- precision: 5, // 总位数
- scale: 2, // 小数位
-})
-```
-
----
-
-### Currency (货币)
-带货币符号的金额值。
-
-```typescript
-annual_revenue: Field.currency({
- label: '年收入',
- precision: 18,
- scale: 2,
- min: 0,
-})
-```
-
-**显示:** `$1,234.56`(带货币符号格式化)
-
----
-
-### Percent (百分比)
-百分比值(0-100 或 0-1)。
-
-```typescript
-probability: Field.percent({
- label: '赢单概率',
- min: 0,
- max: 100,
- scale: 1, // 一位小数
-})
-```
-
-**显示:** `75.5%`
-
----
-
-## 日期和时间字段
-
-### Date (日期)
-日期选择器(无时间组件)。
-
-```typescript
-due_date: Field.date({
- label: '截止日期',
- defaultValue: 'today',
-})
-
-birthday: Field.date({
- label: '生日',
- min: '1900-01-01',
- max: 'today',
-})
-```
-
-**格式:** `YYYY-MM-DD`
-
----
-
-### DateTime (日期时间)
-支持时区的日期时间选择器。
-
-```typescript
-created_at: Field.datetime({
- label: '创建时间',
- readonly: true,
- defaultValue: 'now',
-})
-```
-
-**格式:** `YYYY-MM-DD HH:mm:ss`
-
----
-
-### Time (时间)
-时间选择器(无日期组件)。
-
-```typescript
-meeting_time: Field.time({
- label: '会议时间',
- format: '24h', // 或 '12h'
-})
-```
-
-**格式:** `HH:mm:ss`
-
----
-
-## 布尔字段
-
-### Boolean (布尔值)
-真/假值的复选框。
-
-```typescript
-is_active: Field.boolean({
- label: '激活',
- defaultValue: true,
-})
-
-is_completed: Field.boolean({
- label: '已完成',
- defaultValue: false,
-})
-```
-
-**显示:** 复选框或切换开关
-
----
-
-## 选择字段
-
-### Select (选择)
-带预定义选项的下拉菜单。
-
-```typescript
-// 简单选项(字符串数组)
-priority: Field.select({
- label: '优先级',
- options: ['低', '中', '高', '紧急'],
-})
-
-// 高级选项(带值和颜色)
-status: Field.select({
- label: '状态',
- options: [
- { label: '开放', value: 'open', color: '#00AA00', default: true },
- { label: '进行中', value: 'in_progress', color: '#FFA500' },
- { label: '已关闭', value: 'closed', color: '#999999' },
- ],
-})
-
-// 多选
-tags: Field.select({
- label: '标签',
- multiple: true, // 允许多选
- options: ['错误', '功能', '增强', '文档'],
-})
-```
-
-**配置:**
-- `options` - 字符串标签数组或选项对象
-- `multiple` - 允许多选(存储为数组)
-- `color` - 徽章和图表的颜色
-
----
-
-## 关联字段
-
-### Lookup (查找)
-引用另一个对象(多对一)。
-
-```typescript
-// 基础查找
-account: Field.lookup('account', {
- label: '账户',
- required: true,
-})
-
-// 过滤查找
-contact: Field.lookup('contact', {
- label: '联系人',
- referenceFilters: ['account_id = $parent.account_id'], // 按父记录过滤
-})
-
-// 多重查找
-related_cases: Field.lookup('case', {
- label: '相关案例',
- multiple: true, // 多对多
-})
-```
-
-**配置:**
-- `reference` - 目标对象名称(snake_case)
-- `referenceFilters` - 查找对话框的过滤条件
-- `deleteBehavior` - `'set_null'`、`'cascade'` 或 `'restrict'`
-- `multiple` - 允许多个引用
-
----
-
-### Master-Detail (主从)
-带级联删除的父子关系。
-
-```typescript
-account: Field.masterDetail('account', {
- label: '账户',
- required: true,
- deleteBehavior: 'cascade', // 删除父记录时删除子记录
- writeRequiresMasterRead: true, // 安全强制
-})
-```
-
-> ℹ️ **Info:**
- **主从关系 vs 查找:**
- - **主从关系:** 紧密耦合,级联删除,子记录继承安全性
- - **查找:** 松散耦合,删除时置空,独立安全性
-
-
----
-
-## 媒体字段
-
-### Image (图片)
-带预览的图片上传。
-
-```typescript
-product_image: Field.image({
- label: '产品图片',
- multiple: false,
- maxFileSize: 5 * 1024 * 1024, // 5MB
- acceptedFormats: ['image/jpeg', 'image/png', 'image/webp'],
-})
-
-// 多图片
-gallery: Field.image({
- label: '图库',
- multiple: true,
- maxFiles: 10,
-})
-```
-
----
-
-### File (文件)
-任意文件类型的文件上传字段。
-
-```typescript
-attachment: Field.file({
- label: '附件',
- maxFileSize: 25 * 1024 * 1024, // 25MB
- acceptedFormats: ['application/pdf', 'application/msword'],
-})
-```
-
----
-
-### Avatar (头像)
-个人资料图片/头像上传。
-
-```typescript
-profile_picture: Field.avatar({
- label: '头像',
- maxFileSize: 2 * 1024 * 1024, // 2MB
- cropAspectRatio: 1, // 正方形裁剪
-})
-```
-
----
-
-## 计算字段
-
-### Formula (公式)
-基于表达式的计算字段。
-
-```typescript
-full_name: Field.formula({
- label: '全名',
- expression: 'CONCAT(first_name, " ", last_name)',
- readonly: true,
-})
-
-full_address: Field.formula({
- label: '完整地址',
- expression: 'CONCAT(street, ", ", city, ", ", state, " ", postal_code)',
-})
-
-days_open: Field.formula({
- label: '开放天数',
- expression: 'DAYS_BETWEEN(created_at, NOW())',
- type: 'number',
-})
-```
-
-> ℹ️ **Info:**
- 公式字段自动计算且只读。可用函数请参见 [公式函数](/docs/references/data/formulas)。
-
-
----
-
-### Summary (汇总)
-从关联记录聚合数据。
-
-```typescript
-total_opportunities: Field.summary({
- label: '总机会金额',
- summaryOperations: {
- object: 'opportunity',
- field: 'amount',
- function: 'sum',
- },
-})
-
-open_cases_count: Field.summary({
- label: '开放案例数',
- summaryOperations: {
- object: 'case',
- field: 'id',
- function: 'count',
- },
-})
-```
-
-**可用函数:**
-- `count` - 计数关联记录
-- `sum` - 求和数值字段
-- `avg` - 平均数值字段
-- `min` - 最小值
-- `max` - 最大值
-
----
-
-### Autonumber (自动编号)
-自动递增的唯一标识符。
-
-```typescript
-account_number: Field.autonumber({
- label: '账户编号',
- format: 'ACC-{0000}', // ACC-0001, ACC-0002, 等
-})
-
-case_id: Field.autonumber({
- label: '案例 ID',
- format: 'CASE-{YYYY}-{00000}', // CASE-2024-00001
-})
-```
-
-**格式标记:**
-- `{0000}` - 补零数字
-- `{YYYY}` - 年份
-- `{MM}` - 月份
-- `{DD}` - 日期
-
----
-
-## 增强字段类型
-
-### Location (位置)
-带地图显示的 GPS 坐标。
-
-```typescript
-coordinates: Field.location({
- label: '位置',
- displayMap: true,
- allowGeocoding: true, // 将地址转换为坐标
-})
-```
-
-**数据结构:**
-```typescript
-{
- latitude: 37.7749,
- longitude: -122.4194,
- altitude: 100, // 可选
- accuracy: 10, // 可选(米)
-}
-```
-
----
-
-### Address (地址)
-结构化地址字段。
-
-```typescript
-billing_address: Field.address({
- label: '账单地址',
- addressFormat: 'us', // 'us'、'uk' 或 'international'
-})
-```
-
-**数据结构:**
-```typescript
-{
- street: '123 Main St',
- city: 'San Francisco',
- state: 'CA',
- postalCode: '94105',
- country: 'United States',
- countryCode: 'US',
- formatted: '123 Main St, San Francisco, CA 94105',
-}
-```
-
----
-
-### Code (代码)
-带语法高亮的代码编辑器。
-
-```typescript
-code_snippet: Field.code('javascript', {
- label: '代码片段',
- lineNumbers: true,
- theme: 'monokai',
-})
-
-sql_query: Field.code('sql', {
- label: 'SQL 查询',
- readonly: false,
-})
-```
-
-**支持的语言:**
-- `javascript`、`typescript`、`python`、`java`、`sql`、`html`、`css`、`json`、`yaml`、`markdown` 等
-
----
-
-### Color (颜色)
-支持多种格式的颜色选择器。
-
-```typescript
-category_color: Field.color({
- label: '分类颜色',
- colorFormat: 'hex', // 'hex'、'rgb'、'rgba'、'hsl'
- presetColors: ['#FF0000', '#00FF00', '#0000FF', '#FFFF00'],
- allowAlpha: false,
-})
-
-theme_color: Field.color({
- label: '主题颜色',
- colorFormat: 'rgba',
- allowAlpha: true, // 支持透明度
-})
-```
-
----
-
-### Rating (评分)
-星级评分字段。
-
-```typescript
-priority: Field.rating(3, {
- label: '优先级',
- description: '1-3 星',
-})
-
-satisfaction: Field.rating(5, {
- label: '客户满意度',
- allowHalf: true, // 允许 0.5 增量
-})
-```
-
-**配置:**
-- 第一个参数:`maxRating`(默认:5)
-- `allowHalf` - 允许半星评分(例如 3.5)
-
----
-
-### Signature (签名)
-数字签名捕获。
-
-```typescript
-customer_signature: Field.signature({
- label: '客户签名',
- required: true,
- readonly: false,
-})
-```
-
-**存储为:** Base64 编码的图片数据
-
----
-
-## 字段配置参考
-
-### 通用属性
-
-所有字段都支持这些通用属性:
-
-```typescript
-{
- // 标识
- name: 'field_name', // snake_case 机器名称
- label: '字段标签', // 人类可读标签
- description: '帮助文本', // 工具提示/帮助文本
-
- // 约束
- required: false, // 是否必填
- unique: false, // 强制唯一性
- defaultValue: null, // 默认值
-
- // UI 行为
- hidden: false, // 从默认 UI 隐藏
- readonly: false, // UI 中只读
- searchable: false, // 启用搜索索引
-
- // 数据库
- index: false, // 创建数据库索引
- externalId: false, // 用于 upsert 操作
- encryption: false, // 静态加密
-}
-```
-
----
-
-## 最佳实践
-
-### 命名约定
-
-```typescript
-// ✅ 正确:字段名使用 snake_case
-account_name: Field.text({ label: '账户名称' })
-annual_revenue: Field.currency({ label: '年收入' })
-
-// ❌ 错误:camelCase 或 PascalCase
-accountName: Field.text({ label: '账户名称' })
-AnnualRevenue: Field.currency({ label: '年收入' })
-```
-
-### 必填字段
-
-```typescript
-// ✅ 正确:必填关键字段
-name: Field.text({
- label: '名称',
- required: true,
- maxLength: 255,
-})
-
-// ✅ 正确:可选字段提供灵活性
-middle_name: Field.text({
- label: '中间名',
- required: false,
-})
-```
-
-### 可搜索字段
-
-```typescript
-// ✅ 正确:关键字段可搜索
-account_name: Field.text({
- searchable: true,
- label: '账户名称',
-})
-
-// ❌ 错误:不要索引大文本字段
-description: Field.textarea({
- searchable: true, // 可能影响性能
-})
-```
-
-### 默认值
-
-```typescript
-// ✅ 正确:使用有意义的默认值
-status: Field.select({
- options: [
- { label: '开放', value: 'open', default: true },
- { label: '关闭', value: 'closed' },
- ],
-})
-
-created_at: Field.datetime({
- defaultValue: 'now',
- readonly: true,
-})
-```
-
----
-
-## CRM 示例
-
-参见 **[CRM 示例](https://github.com/objectstack-ai/spec/tree/main/examples/crm)** 了解所有字段类型的实际使用:
-
-- **账户:** 自动编号、公式、货币、带颜色的选择
-- **联系人:** 主从关系、公式(全名)、头像、电子邮件、电话
-- **机会:** 工作流自动化、状态机、百分比、日期时间
-- **案例:** 评分(满意度)、SLA 跟踪、公式计算
-- **任务:** 代码、颜色、评分、位置、签名
-
----
-
-## 下一步
-
-- [对象架构指南](/docs/guides/object-schema)
-- [验证规则](/docs/guides/validation-rules)
-- [工作流自动化](/docs/guides/workflows)
-- [字段 API 参考](/docs/references/data/core/Field)
diff --git a/content/docs/guides/field-types.mdx b/content/docs/guides/field-types.mdx
deleted file mode 100644
index b90a58d90..000000000
--- a/content/docs/guides/field-types.mdx
+++ /dev/null
@@ -1,817 +0,0 @@
----
-title: Field Types Reference
-description: Complete guide to all ObjectStack field types with examples and configuration options
----
-
-
-# Field Types Reference
-
-ObjectStack supports **35 field types** covering text, numbers, dates, selections, relationships, media, calculations, and enhanced types. This guide provides practical examples for each type.
-
-## Core Text Fields
-
-### Text
-Single-line text input for short strings.
-
-```typescript
-import { Field } from '@objectstack/spec';
-
-// Basic text field
-name: Field.text({
- label: 'Full Name',
- required: true,
- maxLength: 255,
-})
-
-// Searchable text field
-account_name: Field.text({
- label: 'Account Name',
- searchable: true,
- unique: true,
-})
-```
-
-**Configuration Options:**
-- `required` - Make field mandatory
-- `maxLength` - Maximum character limit
-- `minLength` - Minimum character limit
-- `searchable` - Enable full-text search
-- `unique` - Enforce uniqueness constraint
-- `defaultValue` - Set default value
-
----
-
-### Textarea
-Multi-line text input for longer content.
-
-```typescript
-description: Field.textarea({
- label: 'Description',
- maxLength: 5000,
- rows: 5, // UI hint for initial height
-})
-```
-
----
-
-### Email
-Email address field with validation.
-
-```typescript
-email: Field.email({
- label: 'Email Address',
- required: true,
- unique: true,
-})
-```
-
-> ℹ️ **Info:**
- Automatically validates email format: `user@domain.com`
-
-
----
-
-### URL
-Website/link field with URL validation.
-
-```typescript
-website: Field.url({
- label: 'Website',
- placeholder: 'https://example.com',
-})
-```
-
----
-
-### Phone
-Phone number field with format validation.
-
-```typescript
-phone: Field.phone({
- label: 'Phone Number',
- format: 'international', // or 'us', 'uk'
-})
-```
-
----
-
-### Password
-Secure password field with encryption.
-
-```typescript
-api_key: Field.password({
- label: 'API Key',
- encryption: true, // Encrypt at rest
- readonly: true,
-})
-```
-
-> ⚠️ **Warning:**
- Password fields are automatically masked in UI and encrypted if `encryption: true`
-
-
----
-
-## Rich Content Fields
-
-### Markdown
-Markdown text editor with preview.
-
-```typescript
-documentation: Field.markdown({
- label: 'Documentation',
- description: 'Supports full Markdown syntax',
-})
-```
-
----
-
-### HTML
-Raw HTML editor (use with caution).
-
-```typescript
-html_content: Field.html({
- label: 'HTML Content',
- description: 'Raw HTML - sanitize before rendering',
-})
-```
-
-> ⚠️ **Warning:**
- Always sanitize HTML content before rendering to prevent XSS attacks
-
-
----
-
-### Rich Text
-WYSIWYG editor with formatting toolbar.
-
-```typescript
-notes: Field.richtext({
- label: 'Notes',
- description: 'Rich text with formatting, lists, links',
-})
-```
-
-**Supports:**
-- Bold, italic, underline
-- Headings, lists, quotes
-- Links and images
-- Tables
-
----
-
-## Number Fields
-
-### Number
-Numeric field for integers or decimals.
-
-```typescript
-quantity: Field.number({
- label: 'Quantity',
- min: 0,
- max: 1000,
- defaultValue: 1,
-})
-
-// Decimal numbers
-temperature: Field.number({
- label: 'Temperature',
- precision: 5, // Total digits
- scale: 2, // Decimal places
-})
-```
-
----
-
-### Currency
-Monetary value with currency symbol.
-
-```typescript
-annual_revenue: Field.currency({
- label: 'Annual Revenue',
- precision: 18,
- scale: 2,
- min: 0,
-})
-```
-
-**Display:** `$1,234.56` (formatted with currency symbol)
-
----
-
-### Percent
-Percentage value (0-100 or 0-1).
-
-```typescript
-probability: Field.percent({
- label: 'Win Probability',
- min: 0,
- max: 100,
- scale: 1, // One decimal place
-})
-```
-
-**Display:** `75.5%`
-
----
-
-## Date & Time Fields
-
-### Date
-Date picker (no time component).
-
-```typescript
-due_date: Field.date({
- label: 'Due Date',
- defaultValue: 'today',
-})
-
-birthday: Field.date({
- label: 'Birthday',
- min: '1900-01-01',
- max: 'today',
-})
-```
-
-**Format:** `YYYY-MM-DD`
-
----
-
-### DateTime
-Date and time picker with timezone support.
-
-```typescript
-created_at: Field.datetime({
- label: 'Created At',
- readonly: true,
- defaultValue: 'now',
-})
-```
-
-**Format:** `YYYY-MM-DD HH:mm:ss`
-
----
-
-### Time
-Time picker (no date component).
-
-```typescript
-meeting_time: Field.time({
- label: 'Meeting Time',
- format: '24h', // or '12h'
-})
-```
-
-**Format:** `HH:mm:ss`
-
----
-
-## Boolean Field
-
-### Boolean
-Checkbox for true/false values.
-
-```typescript
-is_active: Field.boolean({
- label: 'Active',
- defaultValue: true,
-})
-
-is_completed: Field.boolean({
- label: 'Completed',
- defaultValue: false,
-})
-```
-
-**Display:** Checkbox or toggle switch
-
----
-
-## Selection Fields
-
-### Select
-Dropdown with predefined options.
-
-```typescript
-// Simple options (string array)
-priority: Field.select({
- label: 'Priority',
- options: ['Low', 'Medium', 'High', 'Critical'],
-})
-
-// Advanced options (with values and colors)
-status: Field.select({
- label: 'Status',
- options: [
- { label: 'Open', value: 'open', color: '#00AA00', default: true },
- { label: 'In Progress', value: 'in_progress', color: '#FFA500' },
- { label: 'Closed', value: 'closed', color: '#999999' },
- ],
-})
-
-// Multi-select
-tags: Field.select({
- label: 'Tags',
- multiple: true, // Allow multiple selections
- options: ['Bug', 'Feature', 'Enhancement', 'Documentation'],
-})
-```
-
-**Configuration:**
-- `options` - Array of string labels or option objects
-- `multiple` - Allow multiple selections (stores as array)
-- `color` - Color for badges and charts
-
----
-
-## Relational Fields
-
-### Lookup
-Reference to another object (many-to-one).
-
-```typescript
-// Basic lookup
-account: Field.lookup('account', {
- label: 'Account',
- required: true,
-})
-
-// Filtered lookup
-contact: Field.lookup('contact', {
- label: 'Contact',
- referenceFilters: ['account_id = $parent.account_id'], // Filter by parent
-})
-
-// Multiple lookup
-related_cases: Field.lookup('case', {
- label: 'Related Cases',
- multiple: true, // Many-to-many
-})
-```
-
-**Configuration:**
-- `reference` - Target object name (snake_case)
-- `referenceFilters` - Filter criteria for lookup dialog
-- `deleteBehavior` - `'set_null'`, `'cascade'`, or `'restrict'`
-- `multiple` - Allow multiple references
-
----
-
-### Master-Detail
-Parent-child relationship with cascade delete.
-
-```typescript
-account: Field.masterDetail('account', {
- label: 'Account',
- required: true,
- deleteBehavior: 'cascade', // Delete children when parent deleted
- writeRequiresMasterRead: true, // Security enforcement
-})
-```
-
-> ℹ️ **Info:**
- **Master-Detail vs Lookup:**
- - **Master-Detail:** Tight coupling, cascade deletes, child inherits security
- - **Lookup:** Loose coupling, set null on delete, independent security
-
-
----
-
-## Media Fields
-
-### Image
-Image upload with preview.
-
-```typescript
-product_image: Field.image({
- label: 'Product Image',
- multiple: false,
- maxFileSize: 5 * 1024 * 1024, // 5MB
- acceptedFormats: ['image/jpeg', 'image/png', 'image/webp'],
-})
-
-// Multiple images
-gallery: Field.image({
- label: 'Gallery',
- multiple: true,
- maxFiles: 10,
-})
-```
-
----
-
-### File
-File upload field for any file type.
-
-```typescript
-attachment: Field.file({
- label: 'Attachment',
- maxFileSize: 25 * 1024 * 1024, // 25MB
- acceptedFormats: ['application/pdf', 'application/msword'],
-})
-```
-
----
-
-### Avatar
-Profile picture/avatar upload.
-
-```typescript
-profile_picture: Field.avatar({
- label: 'Profile Picture',
- maxFileSize: 2 * 1024 * 1024, // 2MB
- cropAspectRatio: 1, // Square crop
-})
-```
-
----
-
-## Calculated Fields
-
-### Formula
-Calculated field based on expression.
-
-```typescript
-full_name: Field.formula({
- label: 'Full Name',
- expression: 'CONCAT(first_name, " ", last_name)',
- readonly: true,
-})
-
-full_address: Field.formula({
- label: 'Full Address',
- expression: 'CONCAT(street, ", ", city, ", ", state, " ", postal_code)',
-})
-
-days_open: Field.formula({
- label: 'Days Open',
- expression: 'DAYS_BETWEEN(created_at, NOW())',
- type: 'number',
-})
-```
-
-> ℹ️ **Info:**
- Formula fields are automatically calculated and readonly. See [Formula Functions](/docs/references/data/formulas) for available functions.
-
-
----
-
-### Summary (Rollup)
-Aggregate data from related records.
-
-```typescript
-total_opportunities: Field.summary({
- label: 'Total Opportunities',
- summaryOperations: {
- object: 'opportunity',
- field: 'amount',
- function: 'sum',
- },
-})
-
-open_cases_count: Field.summary({
- label: 'Open Cases',
- summaryOperations: {
- object: 'case',
- field: 'id',
- function: 'count',
- },
-})
-```
-
-**Available Functions:**
-- `count` - Count related records
-- `sum` - Sum numeric field
-- `avg` - Average numeric field
-- `min` - Minimum value
-- `max` - Maximum value
-
----
-
-### Autonumber
-Auto-incrementing unique identifier.
-
-```typescript
-account_number: Field.autonumber({
- label: 'Account Number',
- format: 'ACC-{0000}', // ACC-0001, ACC-0002, etc.
-})
-
-case_id: Field.autonumber({
- label: 'Case ID',
- format: 'CASE-{YYYY}-{00000}', // CASE-2024-00001
-})
-```
-
-**Format Tokens:**
-- `{0000}` - Zero-padded number
-- `{YYYY}` - Year
-- `{MM}` - Month
-- `{DD}` - Day
-
----
-
-## Enhanced Field Types
-
-### Location
-GPS coordinates with map display.
-
-```typescript
-coordinates: Field.location({
- label: 'Location',
- displayMap: true,
- allowGeocoding: true, // Convert address to coordinates
-})
-```
-
-> **Note:** `geolocation` is an alternative name for the `location` field type. Both refer to the same GPS coordinate field.
-
-**Data Structure:**
-```typescript
-{
- latitude: 37.7749,
- longitude: -122.4194,
- altitude: 100, // Optional
- accuracy: 10, // Optional (meters)
-}
-```
-
----
-
-### Address
-Structured address field.
-
-```typescript
-billing_address: Field.address({
- label: 'Billing Address',
- addressFormat: 'us', // 'us', 'uk', or 'international'
-})
-```
-
-**Data Structure:**
-```typescript
-{
- street: '123 Main St',
- city: 'San Francisco',
- state: 'CA',
- postalCode: '94105',
- country: 'United States',
- countryCode: 'US',
- formatted: '123 Main St, San Francisco, CA 94105',
-}
-```
-
----
-
-### Code
-Code editor with syntax highlighting.
-
-```typescript
-code_snippet: Field.code('javascript', {
- label: 'Code Snippet',
- lineNumbers: true,
- theme: 'monokai',
-})
-
-sql_query: Field.code('sql', {
- label: 'SQL Query',
- readonly: false,
-})
-```
-
-**Supported Languages:**
-- `javascript`, `typescript`, `python`, `java`, `sql`, `html`, `css`, `json`, `yaml`, `markdown`, and more
-
----
-
-### Color
-Color picker with multiple formats.
-
-```typescript
-category_color: Field.color({
- label: 'Category Color',
- colorFormat: 'hex', // 'hex', 'rgb', 'rgba', 'hsl'
- presetColors: ['#FF0000', '#00FF00', '#0000FF', '#FFFF00'],
- allowAlpha: false,
-})
-
-theme_color: Field.color({
- label: 'Theme Color',
- colorFormat: 'rgba',
- allowAlpha: true, // Support transparency
-})
-```
-
----
-
-### Rating
-Star rating field.
-
-```typescript
-priority: Field.rating(3, {
- label: 'Priority',
- description: '1-3 stars',
-})
-
-satisfaction: Field.rating(5, {
- label: 'Customer Satisfaction',
- allowHalf: true, // Allow 0.5 increments
-})
-```
-
-**Configuration:**
-- First parameter: `maxRating` (default: 5)
-- `allowHalf` - Allow half-star ratings (e.g., 3.5)
-
----
-
-### Signature
-Digital signature capture.
-
-```typescript
-customer_signature: Field.signature({
- label: 'Customer Signature',
- required: true,
- readonly: false,
-})
-```
-
-**Stored as:** Base64-encoded image data
-
----
-
-### Slider
-Numeric slider for visual value selection.
-
-```typescript
-volume: Field.slider({
- label: 'Volume Level',
- min: 0,
- max: 100,
- step: 1,
- defaultValue: 50,
-})
-
-price_range: Field.slider({
- label: 'Price Range',
- min: 0,
- max: 10000,
- step: 100,
- marks: { 0: '$0', 5000: '$5K', 10000: '$10K' },
-})
-```
-
-**Configuration:**
-- `min` - Minimum value
-- `max` - Maximum value
-- `step` - Increment step size
-- `marks` - Optional labeled markers on the slider
-
----
-
-### QR Code
-QR code / Barcode field for scanning and generation.
-
-```typescript
-product_barcode: Field.qrcode({
- label: 'Product Barcode',
- format: 'qr', // 'qr', 'barcode', 'ean13', 'code128'
- readonly: false,
-})
-
-ticket_code: Field.qrcode({
- label: 'Event Ticket',
- format: 'qr',
- autoGenerate: true, // Generate on record creation
-})
-```
-
-**Supported Formats:**
-- `qr` - QR Code (2D matrix barcode, best for URLs, text, and complex data)
-- `barcode` - Standard 1D barcode (linear format for simple numeric/text data)
-- `ean13` - EAN-13 barcode (13-digit product identifier, commonly used in retail)
-- `code128` - Code 128 barcode (high-density 1D format supporting full ASCII character set)
-
-**Use Cases:**
-- Product SKUs and inventory management (ean13, code128)
-- Event tickets and access control (qr)
-- Document tracking and verification (qr)
-- Shipping labels and logistics (code128)
-
----
-
-## Field Configuration Reference
-
-### Common Properties
-
-All fields support these common properties:
-
-```typescript
-{
- // Identity
- name: 'field_name', // snake_case machine name
- label: 'Field Label', // Human-readable label
- description: 'Help text', // Tooltip/help text
-
- // Constraints
- required: false, // Is mandatory
- unique: false, // Enforce uniqueness
- defaultValue: null, // Default value
-
- // UI Behavior
- hidden: false, // Hide from default UI
- readonly: false, // Read-only in UI
- searchable: false, // Enable search indexing
-
- // Database
- index: false, // Create database index
- externalId: false, // Use for upsert operations
- encryption: false, // Encrypt at rest
-}
-```
-
----
-
-## Best Practices
-
-### Naming Conventions
-
-```typescript
-// ✅ GOOD: snake_case for field names
-account_name: Field.text({ label: 'Account Name' })
-annual_revenue: Field.currency({ label: 'Annual Revenue' })
-
-// ❌ BAD: camelCase or PascalCase
-accountName: Field.text({ label: 'Account Name' })
-AnnualRevenue: Field.currency({ label: 'Annual Revenue' })
-```
-
-### Required Fields
-
-```typescript
-// ✅ GOOD: Require essential fields
-name: Field.text({
- label: 'Name',
- required: true,
- maxLength: 255,
-})
-
-// ✅ GOOD: Optional fields for flexibility
-middle_name: Field.text({
- label: 'Middle Name',
- required: false,
-})
-```
-
-### Searchable Fields
-
-```typescript
-// ✅ GOOD: Make key fields searchable
-account_name: Field.text({
- searchable: true,
- label: 'Account Name',
-})
-
-// ❌ BAD: Don't index large text fields
-description: Field.textarea({
- searchable: true, // Can impact performance
-})
-```
-
-### Default Values
-
-```typescript
-// ✅ GOOD: Use meaningful defaults
-status: Field.select({
- options: [
- { label: 'Open', value: 'open', default: true },
- { label: 'Closed', value: 'closed' },
- ],
-})
-
-created_at: Field.datetime({
- defaultValue: 'now',
- readonly: true,
-})
-```
-
----
-
-## Examples from CRM
-
-See the **[CRM Example](https://github.com/objectstack-ai/spec/tree/main/examples/crm)** for real-world usage of all field types:
-
-- **Account:** Autonumber, formula, currency, select with colors
-- **Contact:** Master-detail, formula (full_name), avatar, email, phone
-- **Opportunity:** Workflow automation, state machine, percent, datetime
-- **Case:** Rating (satisfaction), SLA tracking, formula calculations
-- **Task:** Code, color, rating, location, signature
-
----
-
-## Next Steps
-
-- [Object Schema Guide](/docs/guides/object-schema)
-- [Validation Rules](/docs/guides/validation-rules)
-- [Workflow Automation](/docs/guides/workflows)
-- [Field API Reference](/docs/references/data/core/Field)
diff --git a/content/docs/guides/getting-started.cn.mdx b/content/docs/guides/getting-started.cn.mdx
deleted file mode 100644
index 26771d352..000000000
--- a/content/docs/guides/getting-started.cn.mdx
+++ /dev/null
@@ -1,289 +0,0 @@
----
-title: 快速开始
-description: 5 分钟内构建你的第一个 ObjectStack 应用程序
----
-
-ObjectStack 是协议优先的平台。`@objectstack/spec` 包提供了 Zod 模式和严格的 TypeScript 类型来构建有效的元数据定义。
-
-
-
-
-## 初始化项目
-
-你可以从头开始或将 ObjectStack 添加到现有的 TypeScript 项目中。
-
-```bash
-mkdir my-app
-cd my-app
-npm init -y
-npm install typescript zod @objectstack/spec
-npx tsc --init
-```
-
-
-
-## 定义第一个对象
-
-创建文件 `src/domains/crm/contact.object.ts`。
-这就是 **Zod 优先定义** 的强大之处。你可以获得开箱即用的自动完成和验证。
-
-```typescript
-import { ObjectSchema, Field } from '@objectstack/spec';
-
-export const Contact = ObjectSchema.create({
- name: 'contact',
- label: '联系人',
- pluralLabel: '联系人',
- icon: 'user',
- description: '与账户关联的人员',
- nameField: 'full_name',
-
- fields: {
- // 基本信息
- first_name: Field.text({
- label: '名',
- required: true,
- maxLength: 100,
- }),
-
- last_name: Field.text({
- label: '姓',
- required: true,
- maxLength: 100,
- }),
-
- // 公式字段 - 自动计算
- full_name: Field.formula({
- label: '全名',
- expression: 'CONCAT(first_name, " ", last_name)',
- }),
-
- // 联系信息
- email: Field.email({
- label: '电子邮件',
- unique: true,
- }),
-
- phone: Field.phone({
- label: '电话',
- }),
-
- // 带预定义选项的选择字段
- type: Field.select({
- label: '联系人类型',
- options: [
- { label: '客户', value: 'customer', default: true },
- { label: '合作伙伴', value: 'partner' },
- { label: '供应商', value: 'vendor' },
- ],
- }),
-
- // 与账户的关系
- account: Field.masterDetail('account', {
- label: '账户',
- required: true,
- deleteBehavior: 'cascade',
- }),
- },
-
- enable: {
- apiEnabled: true,
- trackHistory: true,
- }
-});
-```
-
-
-
-## 添加账户对象
-
-创建 `src/domains/crm/account.object.ts` 作为父对象:
-
-```typescript
-import { ObjectSchema, Field } from '@objectstack/spec';
-
-export const Account = ObjectSchema.create({
- name: 'account',
- label: '账户',
- pluralLabel: '账户',
- icon: 'building',
- nameField: 'name',
-
- fields: {
- // 自动编号字段
- account_number: Field.autonumber({
- label: '账户编号',
- format: 'ACC-{0000}',
- }),
-
- name: Field.text({
- label: '账户名称',
- required: true,
- searchable: true,
- maxLength: 255,
- }),
-
- // 货币字段
- annual_revenue: Field.currency({
- label: '年收入',
- min: 0,
- }),
-
- // 带自定义颜色的选择字段(用于看板)
- type: Field.select({
- label: '账户类型',
- options: [
- { label: '潜在客户', value: 'prospect', color: '#FFA500', default: true },
- { label: '客户', value: 'customer', color: '#00AA00' },
- { label: '合作伙伴', value: 'partner', color: '#0000FF' },
- ],
- }),
- },
-
- enable: {
- apiEnabled: true,
- trackHistory: true,
- }
-});
-```
-
-
-
-## 创建应用程序清单
-
-创建 `objectstack.config.ts` 将对象打包到应用中:
-
-```typescript
-import { defineManifest } from '@objectstack/spec';
-import { Account } from './src/domains/crm/account.object';
-import { Contact } from './src/domains/crm/contact.object';
-
-export default defineManifest({
- name: 'my_crm',
- label: '我的 CRM',
- version: '1.0.0',
- description: '简单的 CRM 应用程序',
-
- objects: [Account, Contact],
-
- navigation: {
- tabs: [
- {
- label: '销售',
- items: [
- { type: 'object', object: 'account' },
- { type: 'object', object: 'contact' },
- ],
- },
- ],
- },
-});
-```
-
-
-
-## 验证协议
-
-创建构建脚本 `src/build.ts` 来验证你的定义:
-
-```typescript
-import config from '../objectstack.config';
-
-// 如果模式无效,这将抛出 ZodError
-console.log(`✅ 应用 '${config.label}' 有效!`);
-console.log(`📦 对象: ${config.objects.map(o => o.name).join(', ')}`);
-
-// 导出为 JSON 供运行时使用
-import fs from 'fs';
-fs.writeFileSync(
- 'dist/manifest.json',
- JSON.stringify(config, null, 2)
-);
-```
-
-运行它:
-
-```bash
-npx tsx src/build.ts
-```
-
-
-
-## 探索高级功能
-
-现在你有了一个可工作的应用,探索高级功能:
-
-### 1. 添加验证规则
-
-```typescript
-validations: [
- {
- name: 'unique_email',
- type: 'unique',
- fields: ['email'],
- message: '电子邮件已存在',
- },
- {
- name: 'positive_revenue',
- type: 'script',
- expression: 'annual_revenue >= 0',
- message: '收入必须为正数',
- },
-]
-```
-
-### 2. 添加工作流规则
-
-```typescript
-workflows: [
- {
- name: 'update_last_activity',
- trigger: 'on_update',
- actions: [
- {
- type: 'field_update',
- field: 'last_activity_date',
- value: 'TODAY()',
- },
- ],
- },
-]
-```
-
-### 3. 配置视图
-
-```typescript
-views: {
- list: {
- type: 'grid',
- columns: ['account_number', 'name', 'type', 'annual_revenue'],
- filters: [
- { field: 'type', operator: '=', value: 'customer' }
- ],
- },
- kanban: {
- type: 'kanban',
- groupBy: 'type',
- columns: ['name', 'annual_revenue'],
- },
-}
-```
-
-
-
-## 下一步
-
-现在你有了有效的元数据,你可以:
-
-1. **探索示例**:查看 [CRM 示例](https://github.com/objectstack-ai/spec/tree/main/examples/crm) 了解完整功能实现
-2. **学习字段类型**:参见 [字段类型指南](/docs/guides/field-types) 了解所有 35 种字段类型
-3. **构建 UI**:使用 ObjectStack 运行时的元数据来生成界面
-4. **部署**:推送到 ObjectStack 内核用于生产环境
-
-**其他资源:**
-- [对象模式参考](/docs/references/data/core/Object)
-- [验证规则](/docs/guides/validation-rules)
-- [工作流自动化](/docs/guides/workflows)
-
-
-
diff --git a/content/docs/guides/getting-started.mdx b/content/docs/guides/getting-started.mdx
deleted file mode 100644
index 92cadb420..000000000
--- a/content/docs/guides/getting-started.mdx
+++ /dev/null
@@ -1,289 +0,0 @@
----
-title: Getting Started
-description: Build your first ObjectStack application in 5 minutes.
----
-
-ObjectStack is a protocol-first platform. The `@objectstack/spec` package provides Zod schemas and strict TypeScript types to build valid metadata definitions.
-
-
-
-
-## Initialize your project
-
-You can start from scratch or add ObjectStack to an existing TypeScript project.
-
-```bash
-mkdir my-app
-cd my-app
-npm init -y
-npm install typescript zod @objectstack/spec
-npx tsc --init
-```
-
-
-
-## Define your first Object
-
-Create a file named `src/domains/crm/contact.object.ts`.
-This is where the power of **Zod-First Definition** comes in. You get autocomplete and validation out of the box.
-
-```typescript
-import { ObjectSchema, Field } from '@objectstack/spec';
-
-export const Contact = ObjectSchema.create({
- name: 'contact',
- label: 'Contact',
- pluralLabel: 'Contacts',
- icon: 'user',
- description: 'People associated with accounts',
- nameField: 'full_name',
-
- fields: {
- // Basic Information
- first_name: Field.text({
- label: 'First Name',
- required: true,
- maxLength: 100,
- }),
-
- last_name: Field.text({
- label: 'Last Name',
- required: true,
- maxLength: 100,
- }),
-
- // Formula field - automatically calculated
- full_name: Field.formula({
- label: 'Full Name',
- expression: 'CONCAT(first_name, " ", last_name)',
- }),
-
- // Contact Information
- email: Field.email({
- label: 'Email',
- unique: true,
- }),
-
- phone: Field.phone({
- label: 'Phone',
- }),
-
- // Selection with predefined options
- type: Field.select({
- label: 'Contact Type',
- options: [
- { label: 'Customer', value: 'customer', default: true },
- { label: 'Partner', value: 'partner' },
- { label: 'Vendor', value: 'vendor' },
- ],
- }),
-
- // Relationship to Account
- account: Field.masterDetail('account', {
- label: 'Account',
- required: true,
- deleteBehavior: 'cascade',
- }),
- },
-
- enable: {
- apiEnabled: true,
- trackHistory: true,
- }
-});
-```
-
-
-
-## Add an Account Object
-
-Create `src/domains/crm/account.object.ts` for the parent object:
-
-```typescript
-import { ObjectSchema, Field } from '@objectstack/spec';
-
-export const Account = ObjectSchema.create({
- name: 'account',
- label: 'Account',
- pluralLabel: 'Accounts',
- icon: 'building',
- nameField: 'name',
-
- fields: {
- // Autonumber field
- account_number: Field.autonumber({
- label: 'Account Number',
- format: 'ACC-{0000}',
- }),
-
- name: Field.text({
- label: 'Account Name',
- required: true,
- searchable: true,
- maxLength: 255,
- }),
-
- // Currency field
- annual_revenue: Field.currency({
- label: 'Annual Revenue',
- min: 0,
- }),
-
- // Select with custom colors (for kanban boards)
- type: Field.select({
- label: 'Account Type',
- options: [
- { label: 'Prospect', value: 'prospect', color: '#FFA500', default: true },
- { label: 'Customer', value: 'customer', color: '#00AA00' },
- { label: 'Partner', value: 'partner', color: '#0000FF' },
- ],
- }),
- },
-
- enable: {
- apiEnabled: true,
- trackHistory: true,
- }
-});
-```
-
-
-
-## Create Application Manifest
-
-Create `objectstack.config.ts` to bundle your objects into an app:
-
-```typescript
-import { defineManifest } from '@objectstack/spec';
-import { Account } from './src/domains/crm/account.object';
-import { Contact } from './src/domains/crm/contact.object';
-
-export default defineManifest({
- name: 'my_crm',
- label: 'My CRM',
- version: '1.0.0',
- description: 'Simple CRM application',
-
- objects: [Account, Contact],
-
- navigation: {
- tabs: [
- {
- label: 'Sales',
- items: [
- { type: 'object', object: 'account' },
- { type: 'object', object: 'contact' },
- ],
- },
- ],
- },
-});
-```
-
-
-
-## Validate the Protocol
-
-Create a build script `src/build.ts` to verify your definitions:
-
-```typescript
-import config from '../objectstack.config';
-
-// This will throw a ZodError if your schema is invalid
-console.log(`✅ App '${config.label}' is valid!`);
-console.log(`📦 Objects: ${config.objects.map(o => o.name).join(', ')}`);
-
-// Export as JSON for runtime use
-import fs from 'fs';
-fs.writeFileSync(
- 'dist/manifest.json',
- JSON.stringify(config, null, 2)
-);
-```
-
-Run it:
-
-```bash
-npx tsx src/build.ts
-```
-
-
-
-## Explore Advanced Features
-
-Now that you have a working app, explore advanced features:
-
-### 1. Add Validation Rules
-
-```typescript
-validations: [
- {
- name: 'unique_email',
- type: 'unique',
- fields: ['email'],
- message: 'Email already exists',
- },
- {
- name: 'positive_revenue',
- type: 'script',
- expression: 'annual_revenue >= 0',
- message: 'Revenue must be positive',
- },
-]
-```
-
-### 2. Add Workflow Rules
-
-```typescript
-workflows: [
- {
- name: 'update_last_activity',
- trigger: 'on_update',
- actions: [
- {
- type: 'field_update',
- field: 'last_activity_date',
- value: 'TODAY()',
- },
- ],
- },
-]
-```
-
-### 3. Configure Views
-
-```typescript
-views: {
- list: {
- type: 'grid',
- columns: ['account_number', 'name', 'type', 'annual_revenue'],
- filters: [
- { field: 'type', operator: '=', value: 'customer' }
- ],
- },
- kanban: {
- type: 'kanban',
- groupBy: 'type',
- columns: ['name', 'annual_revenue'],
- },
-}
-```
-
-
-
-## Next Steps
-
-Now that you have valid metadata, you can:
-
-1. **Explore Examples**: Check out the [CRM Example](https://github.com/objectstack-ai/spec/tree/main/examples/crm) for a full-featured implementation
-2. **Learn Field Types**: See the [Field Types Guide](/docs/guides/field-types) for all 35 field types
-3. **Build UI**: Use the metadata with ObjectStack runtime to generate interfaces
-4. **Deploy**: Push to an ObjectStack kernel for production use
-
-**Additional Resources:**
-- [Object Schema Reference](/docs/references/data/core/Object)
-- [Validation Rules](/docs/guides/validation-rules)
-- [Workflow Automation](/docs/guides/workflows)
-
-
-
diff --git a/content/docs/guides/installation.cn.mdx b/content/docs/guides/installation.cn.mdx
deleted file mode 100644
index 3ba52a7b8..000000000
--- a/content/docs/guides/installation.cn.mdx
+++ /dev/null
@@ -1,46 +0,0 @@
----
-title: 安装
-description: 安装 ObjectStack SDK 和 CLI
----
-
-## 系统要求
-
-* Node.js 18+
-* TypeScript 5+
-
-## 包安装
-
-`@objectstack/spec` 包包含核心 Zod 定义和类型接口。
-
-### npm
-
-```bash
-npm install @objectstack/spec
-```
-
-### pnpm
-
-```bash
-pnpm add @objectstack/spec
-```
-
-### yarn
-
-```bash
-yarn add @objectstack/spec
-```
-
-## CLI 安装(可选)
-
-CLI 工具帮助构建新对象并验证现有元数据。
-
-```bash
-npm install -g @objectstack/cli
-```
-
-## 版本控制
-
-协议遵循语义化版本控制。
-* **主版本 (1.x)**:协议的破坏性更改(JSON 结构)。
-* **次版本 (1.1.x)**:新的字段类型或配置选项。
-* **补丁版本 (1.1.1)**:Zod 验证或类型推断中的错误修复。
diff --git a/content/docs/guides/installation.mdx b/content/docs/guides/installation.mdx
deleted file mode 100644
index 9186a370b..000000000
--- a/content/docs/guides/installation.mdx
+++ /dev/null
@@ -1,46 +0,0 @@
----
-title: Installation
-description: Installing the ObjectStack SDK and CLI.
----
-
-## Requirements
-
-* Node.js 18+
-* TypeScript 5+
-
-## Package Installation
-
-The `@objectstack/spec` package contains the core Zod Definitions and Type Interfaces.
-
-### npm
-
-```bash
-npm install @objectstack/spec
-```
-
-### pnpm
-
-```bash
-pnpm add @objectstack/spec
-```
-
-### yarn
-
-```bash
-yarn add @objectstack/spec
-```
-
-## CLI Installation (Optional)
-
-The CLI tool helps scaffold new objects and validate existing metadata.
-
-```bash
-npm install -g @objectstack/cli
-```
-
-## Versioning
-
-The Protocol follows Semantic Versioning.
-* **Major (1.x)**: Breaking changes to the Protocol (JSON Structure).
-* **Minor (1.1.x)**: New Field Types or Configuration Options.
-* **Patch (1.1.1)**: Bug fixes in Zod validation or Type inference.
diff --git a/content/docs/guides/meta.cn.json b/content/docs/guides/meta.cn.json
deleted file mode 100644
index 2c44b3f41..000000000
--- a/content/docs/guides/meta.cn.json
+++ /dev/null
@@ -1,15 +0,0 @@
-{
- "title": "开发者指南",
- "root": true,
- "pages": [
- "getting-started",
- "installation",
- "project-structure",
- "field-types",
- "view-configuration",
- "workflows-validation",
- "custom-driver",
- "advanced",
- "migration"
- ]
-}
\ No newline at end of file
diff --git a/content/docs/guides/meta.json b/content/docs/guides/meta.json
deleted file mode 100644
index c6e96d3e8..000000000
--- a/content/docs/guides/meta.json
+++ /dev/null
@@ -1,15 +0,0 @@
-{
- "title": "Developer Guides",
- "root": true,
- "pages": [
- "getting-started",
- "installation",
- "project-structure",
- "field-types",
- "view-configuration",
- "workflows-validation",
- "custom-driver",
- "advanced",
- "migration"
- ]
-}
\ No newline at end of file
diff --git a/content/docs/guides/migration/index.mdx b/content/docs/guides/migration/index.mdx
deleted file mode 100644
index 3b0ec014e..000000000
--- a/content/docs/guides/migration/index.mdx
+++ /dev/null
@@ -1,26 +0,0 @@
----
-title: Migration Guides
-description: Guides for migrating between versions
----
-
-# Migration Guides
-
-This section contains guides for migrating your applications between different versions of the ObjectStack Protocol.
-
-## Available Guides
-
-### [Version 0.x to 1.x Migration](/docs/guides/migration/v0-to-v1)
-Complete guide for migrating from version 0.x to 1.x, including:
-- Breaking changes
-- New features
-- Migration steps
-- Code examples
-
-## Migration Best Practices
-
-1. **Read the Full Guide**: Understand all changes before starting
-2. **Backup Your Data**: Always create backups before migration
-3. **Test in Development**: Test the migration in a development environment first
-4. **Update Dependencies**: Ensure all dependencies are compatible
-5. **Review Breaking Changes**: Pay special attention to breaking changes
-6. **Run Tests**: Verify all tests pass after migration
diff --git a/content/docs/guides/migration/meta.json b/content/docs/guides/migration/meta.json
deleted file mode 100644
index 71ec673bc..000000000
--- a/content/docs/guides/migration/meta.json
+++ /dev/null
@@ -1,7 +0,0 @@
-{
- "title": "Migration Guides",
- "pages": [
- "index",
- "v0-to-v1"
- ]
-}
diff --git a/content/docs/guides/migration/v0-to-v1.mdx b/content/docs/guides/migration/v0-to-v1.mdx
deleted file mode 100644
index d5c35b8d2..000000000
--- a/content/docs/guides/migration/v0-to-v1.mdx
+++ /dev/null
@@ -1,154 +0,0 @@
----
-title: Version 0.1.x to 1.0.0 Migration
-description: Guide for migrating from version 0.1.x to 1.0.0
----
-
-# Migration Guide: v0.1.x to v1.0.0
-
-> Guide for migrating from version 0.1.x to 1.0.0
-
-## Overview
-
-This guide helps you migrate your ObjectStack Protocol implementation from version 0.1.x to 1.0.0.
-
-## Breaking Changes
-
-### 1. Naming Convention Changes
-
-**Configuration keys now use camelCase:**
-
-```typescript
-// Before (0.1.x)
-const field = {
- max_length: 100,
- is_required: true,
- default_value: '',
-};
-
-// After (1.0.0)
-const field = {
- maxLength: 100,
- isRequired: true,
- defaultValue: '',
-};
-```
-
-**Machine names still use snake_case:**
-
-```typescript
-// Correct in both versions
-const object = {
- name: 'customer_account', // snake_case for machine names
- fields: {
- first_name: { // snake_case for field names
- maxLength: 100, // camelCase for config
- }
- }
-};
-```
-
-### 2. Schema Changes
-
-**Field type changes:**
-
-```typescript
-// Before (0.1.x)
-type: 'string'
-
-// After (1.0.0)
-type: 'text'
-```
-
-### 3. API Response Structure
-
-**New envelope format:**
-
-```typescript
-// Before (0.1.x)
-{
- data: { /* response */ },
- error: null
-}
-
-// After (1.0.0)
-{
- success: true,
- data: { /* response */ },
- metadata: {
- timestamp: "2026-01-22T10:00:00Z",
- requestId: "req_123"
- }
-}
-```
-
-## Migration Steps
-
-### Step 1: Update Dependencies
-
-```bash
-# Update package.json
-pnpm update @objectstack/spec@^1.0.0
-
-# Install dependencies
-pnpm install
-```
-
-### Step 2: Update Schema Definitions
-
-Run the migration script:
-
-```bash
-pnpm migrate:schemas
-```
-
-Or manually update:
-
-```typescript
-// Update all configuration keys to camelCase
-// Keep machine names in snake_case
-```
-
-### Step 3: Update API Calls
-
-```typescript
-// Update response handling
-const response = await api.createRecord({
- object: 'customer_account',
- data: { /* ... */ }
-});
-
-// Before
-if (!response.error) { /* ... */ }
-
-// After
-if (response.success) { /* ... */ }
-```
-
-### Step 4: Test Your Application
-
-```bash
-# Run tests
-pnpm test
-
-# Build
-pnpm build
-```
-
-## Deprecation Warnings
-
-The following features are deprecated and will be removed in v2.0.0:
-
-- `old_api_format` - Use new envelope format
-- `snake_case_configs` - Use camelCase for configuration
-
-## Getting Help
-
-If you encounter issues:
-
-1. Check the [CHANGELOG.md](/docs/CHANGELOG.md)
-2. Review [CONTRIBUTING.md](/docs/CONTRIBUTING.md)
-3. Open an issue on GitHub
-
----
-
-**Last Updated**: 2026-01-22
diff --git a/content/docs/guides/project-structure.cn.mdx b/content/docs/guides/project-structure.cn.mdx
deleted file mode 100644
index 23097f2b8..000000000
--- a/content/docs/guides/project-structure.cn.mdx
+++ /dev/null
@@ -1,45 +0,0 @@
----
-title: 项目结构
-description: ObjectStack 项目的推荐目录布局
----
-
-为了保持元数据的组织性,我们推荐以下文件夹结构("领域模式")。
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-## 核心概念
-
-### 领域
-
-按业务领域(CRM、财务、人力资源)而不是技术类型组织你的对象。这与**领域驱动设计(DDD)**原则保持一致。
-
-### 命名约定
-
-* **文件**:`kebab-case.suffix.ts`(例如,`project-task.object.ts`、`main-dashboard.view.ts`)
-* **变量**:`PascalCase`(例如,`ProjectTask`、`MainDashboard`)
-* **机器名称**:定义内使用 `snake_case`(例如,`name: 'project_task'`)
diff --git a/content/docs/guides/project-structure.mdx b/content/docs/guides/project-structure.mdx
deleted file mode 100644
index b37b5887c..000000000
--- a/content/docs/guides/project-structure.mdx
+++ /dev/null
@@ -1,44 +0,0 @@
----
-title: Project Structure
-description: Recommended directory layout for ObjectStack projects.
----
-
-To keep your metadata organized, we recommend the following folder structure ("The Domain Pattern").
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-## Key Concepts
-
-### Domains
-Organize your Objects by Business Domain (CRM, Finance, HR) rather than by technical type. This aligns with **Domain-Driven Design (DDD)** principles.
-
-### Naming Conventions
-
-* **Files**: `kebab-case.suffix.ts` (e.g., `project-task.object.ts`, `main-dashboard.view.ts`)
-* **Variables**: `PascalCase` (e.g., `ProjectTask`, `MainDashboard`)
-* **Machine Names**: `snake_case` inside the definition (e.g., `name: 'project_task'`)
diff --git a/content/docs/guides/view-configuration.mdx b/content/docs/guides/view-configuration.mdx
deleted file mode 100644
index 31c0f5139..000000000
--- a/content/docs/guides/view-configuration.mdx
+++ /dev/null
@@ -1,806 +0,0 @@
----
-title: View Configuration
-description: Complete guide to configuring Grid, Kanban, Calendar, Gantt views and forms in ObjectStack
----
-
-
-# View Configuration Guide
-
-ObjectStack provides **5 list view types** and **3 form layouts** to visualize and interact with data. This guide covers all configuration options with practical examples.
-
-## List View Types
-
-1. **Grid** - Traditional table/spreadsheet view
-2. **Kanban** - Card-based workflow board
-3. **Calendar** - Date-based visualization
-4. **Gantt** - Timeline/project management view
-5. **Map** - Geographic location view
-
----
-
-## 1. Grid View
-
-Traditional table view with rows and columns.
-
-### Basic Configuration
-
-```typescript
-import { ObjectSchema, Field } from '@objectstack/spec';
-
-export const Account = ObjectSchema.create({
- name: 'account',
- label: 'Account',
-
- fields: {
- account_number: Field.autonumber({ label: 'Account Number', format: 'ACC-{0000}' }),
- name: Field.text({ label: 'Account Name' }),
- type: Field.select({
- label: 'Type',
- options: [
- { label: 'Customer', value: 'customer' },
- { label: 'Partner', value: 'partner' },
- ],
- }),
- annual_revenue: Field.currency({ label: 'Annual Revenue' }),
- industry: Field.select({ label: 'Industry', options: ['Tech', 'Finance', 'Healthcare'] }),
- created_at: Field.datetime({ label: 'Created' }),
- },
-
- views: {
- list: {
- type: 'grid',
- columns: ['account_number', 'name', 'type', 'annual_revenue', 'industry'],
- sort: [
- { field: 'created_at', order: 'desc' }
- ],
- },
- },
-});
-```
-
-### Advanced Grid Configuration
-
-```typescript
-views: {
- // Default grid view
- list: {
- type: 'grid',
- columns: ['name', 'type', 'annual_revenue', 'owner'],
-
- // Filter configuration
- filter: [
- { field: 'type', operator: '=', value: 'customer' },
- { field: 'annual_revenue', operator: '>', value: 100000 },
- ],
-
- // Sorting
- sort: [
- { field: 'annual_revenue', order: 'desc' },
- { field: 'name', order: 'asc' },
- ],
-
- // Search configuration
- searchableFields: ['name', 'account_number'],
- },
-
- // Additional named views
- listViews: {
- // High-value customers
- high_value: {
- name: 'high_value',
- label: 'High Value Customers',
- type: 'grid',
- columns: ['name', 'annual_revenue', 'owner', 'last_activity'],
- filter: [
- { field: 'type', operator: '=', value: 'customer' },
- { field: 'annual_revenue', operator: '>=', value: 500000 },
- ],
- sort: [{ field: 'annual_revenue', order: 'desc' }],
- },
-
- // Recently created
- recent: {
- name: 'recent',
- label: 'Recently Created',
- type: 'grid',
- columns: ['name', 'type', 'created_at', 'owner'],
- sort: [{ field: 'created_at', order: 'desc' }],
- },
- },
-}
-```
-
-### Filter Operators
-
-Available filter operators:
-
-```typescript
-// Comparison
-{ field: 'amount', operator: '=', value: 1000 }
-{ field: 'amount', operator: '!=', value: 0 }
-{ field: 'amount', operator: '>', value: 5000 }
-{ field: 'amount', operator: '>=', value: 1000 }
-{ field: 'amount', operator: '<', value: 10000 }
-{ field: 'amount', operator: '<=', value: 50000 }
-
-// String
-{ field: 'name', operator: 'contains', value: 'tech' }
-{ field: 'name', operator: 'startsWith', value: 'A' }
-{ field: 'name', operator: 'endsWith', value: 'Inc' }
-
-// NULL checks
-{ field: 'description', operator: 'isNull' }
-{ field: 'description', operator: 'isNotNull' }
-
-// Multi-value
-{ field: 'type', operator: 'in', value: ['customer', 'partner'] }
-{ field: 'type', operator: 'notIn', value: ['former'] }
-```
-
----
-
-## 2. Kanban View
-
-Card-based workflow board grouped by a select field.
-
-### Basic Configuration
-
-```typescript
-export const Opportunity = ObjectSchema.create({
- name: 'opportunity',
- label: 'Opportunity',
-
- fields: {
- name: Field.text({ label: 'Opportunity Name' }),
- stage: Field.select({
- label: 'Stage',
- options: [
- { label: 'Prospecting', value: 'prospecting', color: '#FFA500' },
- { label: 'Qualification', value: 'qualification', color: '#FFD700' },
- { label: 'Proposal', value: 'proposal', color: '#4169E1' },
- { label: 'Negotiation', value: 'negotiation', color: '#9370DB' },
- { label: 'Closed Won', value: 'closed_won', color: '#00AA00' },
- { label: 'Closed Lost', value: 'closed_lost', color: '#DC143C' },
- ],
- }),
- amount: Field.currency({ label: 'Amount' }),
- account: Field.lookup('account', { label: 'Account' }),
- close_date: Field.date({ label: 'Close Date' }),
- },
-
- views: {
- list: {
- type: 'kanban',
- columns: ['name', 'account', 'amount', 'close_date'], // Fields shown on cards
-
- kanban: {
- groupByField: 'stage', // Creates columns for each stage
- summarizeField: 'amount', // Sum amounts at top of each column
- },
- },
- },
-});
-```
-
-### Advanced Kanban
-
-```typescript
-views: {
- listViews: {
- sales_pipeline: {
- name: 'sales_pipeline',
- label: 'Sales Pipeline',
- type: 'kanban',
-
- // Card fields
- columns: ['name', 'account', 'amount', 'probability', 'owner'],
-
- // Kanban configuration
- kanban: {
- groupByField: 'stage',
- summarizeField: 'amount', // Show total $ per column
- },
-
- // Filter to active opportunities only
- filter: [
- { field: 'is_active', operator: '=', value: true },
- ],
-
- // Sort cards within columns
- sort: [
- { field: 'amount', order: 'desc' },
- ],
- },
- },
-}
-```
-
-### Kanban Features
-
-- **Drag & Drop**: Users can drag cards between columns (updates `groupByField`)
-- **Column Headers**: Show count and sum (if `summarizeField` defined)
-- **Colors**: Use option colors from select field for column headers
-- **Filters**: Apply filters to show subset of records
-
----
-
-## 3. Calendar View
-
-Date-based visualization for events, tasks, and deadlines.
-
-### Basic Configuration
-
-```typescript
-export const Event = ObjectSchema.create({
- name: 'event',
- label: 'Event',
-
- fields: {
- title: Field.text({ label: 'Event Title' }),
- start_date: Field.datetime({ label: 'Start Date' }),
- end_date: Field.datetime({ label: 'End Date' }),
- event_type: Field.select({
- label: 'Type',
- options: [
- { label: 'Meeting', value: 'meeting', color: '#4169E1' },
- { label: 'Webinar', value: 'webinar', color: '#00AA00' },
- { label: 'Conference', value: 'conference', color: '#FFA500' },
- ],
- }),
- location: Field.text({ label: 'Location' }),
- },
-
- views: {
- list: {
- type: 'calendar',
- columns: ['title', 'location'], // Extra fields shown in tooltip
-
- calendar: {
- startDateField: 'start_date', // Required
- endDateField: 'end_date', // Optional (single-day events if omitted)
- titleField: 'title', // Event label
- colorField: 'event_type', // Color events by type
- },
- },
- },
-});
-```
-
-### Single-Day Events
-
-For tasks or activities without end dates:
-
-```typescript
-export const Task = ObjectSchema.create({
- name: 'task',
- label: 'Task',
-
- fields: {
- subject: Field.text({ label: 'Subject' }),
- due_date: Field.date({ label: 'Due Date' }),
- priority: Field.select({
- options: [
- { label: 'High', value: 'high', color: '#DC143C' },
- { label: 'Normal', value: 'normal', color: '#4169E1' },
- { label: 'Low', value: 'low', color: '#999999' },
- ],
- }),
- },
-
- views: {
- list: {
- type: 'calendar',
- columns: ['subject'],
-
- calendar: {
- startDateField: 'due_date',
- // No endDateField - shows as single-day events
- titleField: 'subject',
- colorField: 'priority',
- },
- },
- },
-});
-```
-
-### Calendar Features
-
-- **Multiple Views**: Month, Week, Day, Agenda
-- **Color Coding**: By select field option colors
-- **Multi-Day Events**: Span multiple days if `endDateField` provided
-- **Drag & Drop**: Update dates by dragging events
-- **Filters**: Show subset of events
-
----
-
-## 4. Gantt View
-
-Timeline/project management view for tasks with dependencies.
-
-### Configuration
-
-```typescript
-export const ProjectTask = ObjectSchema.create({
- name: 'project_task',
- label: 'Project Task',
-
- fields: {
- task_name: Field.text({ label: 'Task Name' }),
- start_date: Field.date({ label: 'Start Date' }),
- end_date: Field.date({ label: 'End Date' }),
- progress: Field.percent({ label: 'Progress' }),
- dependencies: Field.text({ label: 'Dependencies' }), // Comma-separated task IDs
- assigned_to: Field.lookup('user', { label: 'Assigned To' }),
- },
-
- views: {
- list: {
- type: 'gantt',
- columns: ['task_name', 'assigned_to'], // Shown in left panel
-
- gantt: {
- startDateField: 'start_date', // Required
- endDateField: 'end_date', // Required
- titleField: 'task_name', // Bar label
- progressField: 'progress', // Optional (shows % complete)
- dependenciesField: 'dependencies', // Optional (draws arrows)
- },
-
- sort: [
- { field: 'start_date', order: 'asc' },
- ],
- },
- },
-});
-```
-
-### Gantt Features
-
-- **Timeline Bars**: Visual representation of task duration
-- **Progress Indicator**: Shows completion percentage
-- **Dependencies**: Arrows between related tasks
-- **Critical Path**: Highlight blocking tasks
-- **Drag & Drop**: Adjust dates and dependencies
-- **Zoom Levels**: Day, Week, Month, Quarter, Year
-
----
-
-## 5. Map View
-
-Geographic visualization for location-based data.
-
-### Configuration
-
-```typescript
-export const Store = ObjectSchema.create({
- name: 'store',
- label: 'Store',
-
- fields: {
- store_name: Field.text({ label: 'Store Name' }),
- address: Field.address({ label: 'Address' }),
- location: Field.location({ label: 'Coordinates' }),
- store_type: Field.select({
- options: [
- { label: 'Flagship', value: 'flagship', color: '#FFD700' },
- { label: 'Standard', value: 'standard', color: '#4169E1' },
- { label: 'Outlet', value: 'outlet', color: '#999999' },
- ],
- }),
- },
-
- views: {
- list: {
- type: 'map',
- columns: ['store_name', 'address'], // Info shown in popup
-
- map: {
- locationField: 'location', // GPS coordinates
- titleField: 'store_name',
- colorField: 'store_type', // Marker color
- },
- },
- },
-});
-```
-
----
-
-## Form Views
-
-Three layout types for record detail pages:
-
-1. **Simple** - Single page with sections
-2. **Tabbed** - Multiple tabs for grouped fields
-3. **Wizard** - Step-by-step multi-page form
-
----
-
-## 1. Simple Form
-
-Single-page layout with collapsible sections.
-
-### Configuration
-
-```typescript
-export const Contact = ObjectSchema.create({
- name: 'contact',
- label: 'Contact',
-
- fields: {
- // ... field definitions
- },
-
- views: {
- form: {
- type: 'simple',
- sections: [
- {
- label: 'Basic Information',
- columns: 2, // 2-column layout
- fields: ['first_name', 'last_name', 'email', 'phone'],
- },
- {
- label: 'Address',
- columns: 2,
- collapsible: true,
- collapsed: false,
- fields: ['street', 'city', 'state', 'postal_code', 'country'],
- },
- {
- label: 'Additional Details',
- columns: 1, // Full-width fields
- collapsible: true,
- collapsed: true, // Collapsed by default
- fields: ['notes', 'description'],
- },
- ],
- },
- },
-});
-```
-
-### Section Configuration
-
-```typescript
-{
- label: 'Section Title', // Optional header
- columns: 2, // 1, 2, 3, or 4 columns
- collapsible: true, // Can be collapsed
- collapsed: false, // Initial state
- fields: ['field1', 'field2'], // Fields to include
-}
-```
-
----
-
-## 2. Tabbed Form
-
-Multi-tab layout for complex objects with many fields.
-
-### Configuration
-
-```typescript
-export const Account = ObjectSchema.create({
- name: 'account',
- label: 'Account',
-
- fields: {
- // ... many fields
- },
-
- views: {
- form: {
- type: 'tabbed',
- sections: [
- {
- label: 'Overview', // Tab 1
- columns: 2,
- fields: [
- 'account_number',
- 'name',
- 'type',
- 'industry',
- 'annual_revenue',
- 'website',
- ],
- },
- {
- label: 'Contact Information', // Tab 2
- columns: 2,
- fields: [
- 'phone',
- 'email',
- 'billing_address',
- 'shipping_address',
- ],
- },
- {
- label: 'Description', // Tab 3
- columns: 1,
- fields: ['description', 'notes'],
- },
- ],
- },
- },
-});
-```
-
----
-
-## 3. Wizard Form
-
-Multi-step form for guided data entry.
-
-### Configuration
-
-```typescript
-export const Lead = ObjectSchema.create({
- name: 'lead',
- label: 'Lead',
-
- fields: {
- // ... field definitions
- },
-
- views: {
- form: {
- type: 'wizard',
- sections: [
- {
- label: 'Step 1: Basic Info', // Wizard step 1
- fields: ['first_name', 'last_name', 'company', 'title'],
- },
- {
- label: 'Step 2: Contact Details', // Step 2
- fields: ['email', 'phone', 'address'],
- },
- {
- label: 'Step 3: Qualification', // Step 3
- fields: ['lead_source', 'industry', 'annual_revenue', 'status'],
- },
- ],
- },
- },
-});
-```
-
-### Wizard Features
-
-- **Progress Indicator**: Shows current step
-- **Navigation**: Previous/Next buttons
-- **Validation**: Each step validated before proceeding
-- **Summary**: Review all data before submit
-
----
-
-## Multiple Views
-
-Define multiple views for different use cases.
-
-### Example
-
-```typescript
-export const Opportunity = ObjectSchema.create({
- name: 'opportunity',
- label: 'Opportunity',
-
- fields: {
- // ... fields
- },
-
- views: {
- // Default list view (Grid)
- list: {
- type: 'grid',
- columns: ['name', 'account', 'amount', 'stage', 'close_date'],
- sort: [{ field: 'close_date', order: 'asc' }],
- },
-
- // Default form view
- form: {
- type: 'tabbed',
- sections: [
- { label: 'Details', fields: ['name', 'account', 'amount'] },
- { label: 'Timeline', fields: ['stage', 'close_date'] },
- ],
- },
-
- // Additional list views
- listViews: {
- // Kanban pipeline
- pipeline: {
- name: 'pipeline',
- label: 'Sales Pipeline',
- type: 'kanban',
- columns: ['name', 'amount', 'close_date'],
- kanban: {
- groupByField: 'stage',
- summarizeField: 'amount',
- },
- },
-
- // Calendar of close dates
- timeline: {
- name: 'timeline',
- label: 'Timeline',
- type: 'calendar',
- columns: ['name', 'amount'],
- calendar: {
- startDateField: 'close_date',
- titleField: 'name',
- colorField: 'stage',
- },
- },
-
- // My opportunities
- my_opportunities: {
- name: 'my_opportunities',
- label: 'My Opportunities',
- type: 'grid',
- columns: ['name', 'account', 'amount', 'stage'],
- filter: [
- { field: 'owner', operator: '=', value: '$current_user' },
- ],
- },
- },
-
- // Additional form views
- formViews: {
- // Quick create form
- quick_create: {
- type: 'simple',
- sections: [
- {
- label: 'Essential Fields',
- columns: 2,
- fields: ['name', 'account', 'amount', 'close_date', 'stage'],
- },
- ],
- },
- },
- },
-});
-```
-
----
-
-## Best Practices
-
-### List Views
-
-1. **Column Selection**: Show 4-7 columns for optimal readability
-2. **Default Sort**: Always define a default sort order
-3. **Filters**: Pre-filter common views (e.g., "My Records", "Active Only")
-4. **Searchable**: Enable search on key text fields
-5. **Named Views**: Create specific views for common use cases
-
-### Kanban
-
-1. **Group Field**: Use select fields with 3-7 options (too many = cluttered)
-2. **Card Fields**: Show 3-5 key fields on cards
-3. **Colors**: Define colors for select options
-4. **Summarize**: Add monetary totals for sales/revenue tracking
-
-### Calendar
-
-1. **Date Fields**: Use datetime for multi-day events, date for single-day
-2. **Color Coding**: Use select field with meaningful colors
-3. **Title Field**: Choose concise, descriptive field
-4. **Filters**: Allow filtering by type, owner, etc.
-
-### Gantt
-
-1. **Dependencies**: Use structured format (comma-separated IDs or JSON)
-2. **Progress**: Percentage field (0-100)
-3. **Sort**: Sort by start date for logical flow
-4. **Granularity**: Choose appropriate zoom level (day/week/month)
-
-### Forms
-
-1. **Sections**: Group related fields logically
-2. **Columns**: Use 2 columns for most sections, 1 for wide fields (textarea, rich text)
-3. **Collapsible**: Make optional sections collapsible
-4. **Tabs**: Use tabs when >15 fields
-5. **Wizard**: Use for complex multi-step processes
-
----
-
-## Real-World Example
-
-Complete view configuration for CRM Opportunity:
-
-```typescript
-export const Opportunity = ObjectSchema.create({
- name: 'opportunity',
- label: 'Opportunity',
- pluralLabel: 'Opportunities',
-
- fields: {
- name: Field.text({ label: 'Name' }),
- account: Field.lookup('account', { label: 'Account' }),
- amount: Field.currency({ label: 'Amount' }),
- stage: Field.select({
- label: 'Stage',
- options: [
- { label: 'Prospecting', value: 'prospecting', color: '#FFA500' },
- { label: 'Qualification', value: 'qualification', color: '#FFD700' },
- { label: 'Proposal', value: 'proposal', color: '#4169E1' },
- { label: 'Closed Won', value: 'closed_won', color: '#00AA00' },
- { label: 'Closed Lost', value: 'closed_lost', color: '#DC143C' },
- ],
- }),
- probability: Field.percent({ label: 'Probability' }),
- close_date: Field.date({ label: 'Close Date' }),
- owner: Field.lookup('user', { label: 'Owner' }),
- description: Field.textarea({ label: 'Description' }),
- },
-
- views: {
- // Default grid
- list: {
- type: 'grid',
- columns: ['name', 'account', 'amount', 'stage', 'close_date', 'owner'],
- sort: [{ field: 'close_date', order: 'asc' }],
- searchableFields: ['name', 'account'],
- },
-
- // Default form
- form: {
- type: 'simple',
- sections: [
- {
- label: 'Opportunity Information',
- columns: 2,
- fields: ['name', 'account', 'amount', 'close_date'],
- },
- {
- label: 'Stage & Forecast',
- columns: 2,
- fields: ['stage', 'probability', 'owner'],
- },
- {
- label: 'Description',
- columns: 1,
- fields: ['description'],
- },
- ],
- },
-
- // Named views
- listViews: {
- pipeline: {
- type: 'kanban',
- columns: ['name', 'amount', 'close_date'],
- kanban: {
- groupByField: 'stage',
- summarizeField: 'amount',
- },
- filter: [
- { field: 'stage', operator: 'notIn', value: ['closed_won', 'closed_lost'] },
- ],
- },
-
- closing_soon: {
- type: 'grid',
- columns: ['name', 'account', 'amount', 'close_date', 'probability'],
- filter: [
- { field: 'close_date', operator: '<=', value: '$30_days_from_now' },
- { field: 'stage', operator: '!=', value: 'closed_won' },
- { field: 'stage', operator: '!=', value: 'closed_lost' },
- ],
- sort: [{ field: 'close_date', order: 'asc' }],
- },
- },
- },
-});
-```
-
----
-
-## Next Steps
-
-- [Field Types Guide](/docs/guides/field-types)
-- [Workflows & Validation](/docs/guides/workflows-validation)
-- [Dashboard Configuration](/docs/guides/dashboards)
-- [CRM Example](https://github.com/objectstack-ai/spec/tree/main/examples/crm) - See all view types in action
diff --git a/content/docs/guides/workflows-validation.mdx b/content/docs/guides/workflows-validation.mdx
deleted file mode 100644
index a3cf47afc..000000000
--- a/content/docs/guides/workflows-validation.mdx
+++ /dev/null
@@ -1,733 +0,0 @@
----
-title: Validation Rules & Workflows
-description: Complete guide to validation rules and workflow automation in ObjectStack
----
-
-
-# Validation Rules & Workflows
-
-ObjectStack provides powerful **validation rules** and **workflow automation** to enforce business logic and automate repetitive tasks. This guide covers all validation types and workflow patterns with practical examples.
-
-## Validation Rules
-
-Validation rules ensure data quality by checking record values before save. They can be defined at the object level and execute automatically.
-
-### Types of Validation Rules
-
-ObjectStack supports **7 validation types**, each optimized for specific use cases:
-
-1. **Script Validation** - Generic formula-based validation
-2. **Uniqueness Validation** - Enforce unique constraints
-3. **State Machine Validation** - Control state transitions
-4. **Format Validation** - Regex or format checking
-5. **Cross-Field Validation** - Compare multiple fields
-6. **Async Validation** - Remote API validation
-7. **Custom Validator** - User-defined functions
-
----
-
-## 1. Script Validation
-
-Generic formula-based validation for any business logic.
-
-### Configuration
-
-```typescript
-import { ObjectSchema, Field } from '@objectstack/spec';
-
-export const Opportunity = ObjectSchema.create({
- name: 'opportunity',
- label: 'Opportunity',
-
- fields: {
- amount: Field.currency({ label: 'Amount' }),
- probability: Field.percent({ label: 'Probability' }),
- close_date: Field.date({ label: 'Close Date' }),
- },
-
- validations: [
- {
- name: 'positive_amount',
- type: 'script',
- condition: 'amount < 0', // When TRUE, validation FAILS
- message: 'Amount must be greater than or equal to 0',
- severity: 'error',
- active: true,
- },
- {
- name: 'probability_range',
- type: 'script',
- condition: 'probability < 0 OR probability > 100',
- message: 'Probability must be between 0 and 100',
- severity: 'error',
- },
- {
- name: 'future_close_date',
- type: 'script',
- condition: 'close_date < TODAY()',
- message: 'Close date cannot be in the past',
- severity: 'warning', // Warning instead of error
- },
- ],
-});
-```
-
-> ℹ️ **Info:**
- **Important:** The `condition` is inverted logic - it defines when validation **FAILS**. If the condition evaluates to `TRUE`, the validation error is shown.
-
-
-### Expression Examples
-
-```typescript
-// Number comparisons
-condition: 'revenue < 1000'
-condition: 'quantity <= 0'
-condition: 'discount > 50'
-
-// String checks
-condition: 'LEN(name) < 3'
-condition: 'ISBLANK(description)'
-condition: 'NOT(CONTAINS(email, "@"))'
-
-// Date validations
-condition: 'end_date < start_date'
-condition: 'due_date < TODAY()'
-condition: 'DAYS_BETWEEN(start_date, end_date) > 365'
-
-// Complex logic
-condition: 'stage = "Closed Won" AND amount = 0'
-condition: '(priority = "High" OR priority = "Critical") AND NOT(ISBLANK(assigned_to))'
-```
-
----
-
-## 2. Uniqueness Validation
-
-Optimized validation for enforcing unique constraints, better than script validation for uniqueness checks.
-
-### Configuration
-
-```typescript
-export const Account = ObjectSchema.create({
- name: 'account',
- label: 'Account',
-
- fields: {
- name: Field.text({ label: 'Account Name' }),
- email: Field.email({ label: 'Email' }),
- account_number: Field.text({ label: 'Account Number' }),
- active: Field.boolean({ label: 'Active' }),
- },
-
- validations: [
- // Single field uniqueness
- {
- name: 'unique_email',
- type: 'unique',
- fields: ['email'],
- message: 'Email address already exists',
- caseSensitive: false, // Ignore case
- },
-
- // Compound uniqueness (multiple fields)
- {
- name: 'unique_account_number',
- type: 'unique',
- fields: ['account_number'],
- message: 'Account number must be unique',
- caseSensitive: true,
- },
-
- // Scoped uniqueness (unique within subset)
- {
- name: 'unique_name_active',
- type: 'unique',
- fields: ['name'],
- scope: 'active = true', // Only check uniqueness among active accounts
- message: 'Active account with this name already exists',
- },
- ],
-});
-```
-
-### Use Cases
-
-- Email addresses
-- Username fields
-- Product SKUs
-- Invoice numbers
-- Unique combinations (e.g., name + region)
-
----
-
-## 3. State Machine Validation
-
-Control allowed state transitions to prevent invalid workflow progressions.
-
-### Configuration
-
-```typescript
-export const Opportunity = ObjectSchema.create({
- name: 'opportunity',
- label: 'Opportunity',
-
- fields: {
- stage: Field.select({
- label: 'Stage',
- options: [
- { label: 'Prospecting', value: 'prospecting' },
- { label: 'Qualification', value: 'qualification' },
- { label: 'Proposal', value: 'proposal' },
- { label: 'Negotiation', value: 'negotiation' },
- { label: 'Closed Won', value: 'closed_won' },
- { label: 'Closed Lost', value: 'closed_lost' },
- ],
- }),
- },
-
- validations: [
- {
- name: 'stage_transition',
- type: 'state_machine',
- field: 'stage',
- message: 'Invalid stage transition',
- transitions: {
- // From -> To (allowed states)
- 'prospecting': ['qualification', 'closed_lost'],
- 'qualification': ['prospecting', 'proposal', 'closed_lost'],
- 'proposal': ['qualification', 'negotiation', 'closed_lost'],
- 'negotiation': ['proposal', 'closed_won', 'closed_lost'],
- 'closed_won': [], // No transitions allowed (terminal state)
- 'closed_lost': [], // No transitions allowed (terminal state)
- },
- },
- ],
-});
-```
-
-### Diagram
-
-```
-Prospecting → Qualification → Proposal → Negotiation → Closed Won
- ↓ ↓ ↓ ↓
- Closed Lost ← Closed Lost ← Closed Lost ← Closed Lost
-```
-
----
-
-## 4. Format Validation
-
-Validate field formats using regex or predefined patterns.
-
-### Configuration
-
-```typescript
-export const Contact = ObjectSchema.create({
- name: 'contact',
- label: 'Contact',
-
- fields: {
- phone: Field.phone({ label: 'Phone' }),
- website: Field.url({ label: 'Website' }),
- postal_code: Field.text({ label: 'Postal Code' }),
- json_data: Field.textarea({ label: 'JSON Data' }),
- },
-
- validations: [
- // Regex validation
- {
- name: 'us_postal_code',
- type: 'format',
- field: 'postal_code',
- regex: '^\\d{5}(-\\d{4})?$', // 12345 or 12345-6789
- message: 'Invalid US postal code format',
- },
-
- // Predefined format
- {
- name: 'valid_phone',
- type: 'format',
- field: 'phone',
- format: 'phone',
- message: 'Invalid phone number format',
- },
-
- {
- name: 'valid_json',
- type: 'format',
- field: 'json_data',
- format: 'json',
- message: 'Invalid JSON format',
- },
- ],
-});
-```
-
-### Available Formats
-
-- `email` - Email address
-- `url` - Website URL
-- `phone` - Phone number
-- `json` - Valid JSON
-
----
-
-## 5. Cross-Field Validation
-
-Validate relationships between multiple fields.
-
-### Configuration
-
-```typescript
-export const Event = ObjectSchema.create({
- name: 'event',
- label: 'Event',
-
- fields: {
- start_date: Field.datetime({ label: 'Start Date' }),
- end_date: Field.datetime({ label: 'End Date' }),
- min_attendees: Field.number({ label: 'Min Attendees' }),
- max_attendees: Field.number({ label: 'Max Attendees' }),
- budget: Field.currency({ label: 'Budget' }),
- actual_cost: Field.currency({ label: 'Actual Cost' }),
- },
-
- validations: [
- {
- name: 'end_after_start',
- type: 'cross_field',
- fields: ['start_date', 'end_date'],
- condition: 'end_date <= start_date',
- message: 'End date must be after start date',
- },
-
- {
- name: 'max_greater_than_min',
- type: 'cross_field',
- fields: ['min_attendees', 'max_attendees'],
- condition: 'max_attendees < min_attendees',
- message: 'Maximum attendees must be greater than minimum',
- },
-
- {
- name: 'budget_check',
- type: 'cross_field',
- fields: ['budget', 'actual_cost'],
- condition: 'actual_cost > budget',
- message: 'Actual cost exceeds budget',
- severity: 'warning', // Allow save but warn
- },
- ],
-});
-```
-
----
-
-## 6. Async Validation
-
-Validate data against external APIs or databases.
-
-### Configuration
-
-```typescript
-export const User = ObjectSchema.create({
- name: 'user',
- label: 'User',
-
- fields: {
- username: Field.text({ label: 'Username' }),
- tax_id: Field.text({ label: 'Tax ID' }),
- },
-
- validations: [
- {
- name: 'check_username_availability',
- type: 'async',
- field: 'username',
- validatorUrl: '/api/validate/username',
- timeout: 5000,
- debounce: 500, // Wait 500ms after typing stops
- message: 'Username is already taken',
- params: {
- minLength: 3,
- },
- },
-
- {
- name: 'verify_tax_id',
- type: 'async',
- field: 'tax_id',
- validatorFunction: 'validateTaxId', // Custom function
- timeout: 10000,
- message: 'Invalid tax ID',
- },
- ],
-});
-```
-
----
-
-## 7. Custom Validator
-
-User-defined validation logic with code references.
-
-### Configuration
-
-```typescript
-export const Order = ObjectSchema.create({
- name: 'order',
- label: 'Order',
-
- fields: {
- items: Field.textarea({ label: 'Order Items (JSON)' }),
- total: Field.currency({ label: 'Total' }),
- },
-
- validations: [
- {
- name: 'validate_order_total',
- type: 'custom',
- validatorFunction: 'validateOrderTotal',
- message: 'Order total does not match line items',
- params: {
- includeTax: true,
- includeShipping: true,
- },
- },
- ],
-});
-```
-
----
-
-## Workflow Automation
-
-Workflows automate actions when records are created, updated, or deleted.
-
-### Workflow Components
-
-1. **Trigger** - When to execute (on_create, on_update, on_delete, schedule)
-2. **Criteria** - Condition to check (optional)
-3. **Actions** - What to execute (field_update, email_alert, etc.)
-
----
-
-## Workflow Examples
-
-### 1. Field Update on Create
-
-```typescript
-export const Lead = ObjectSchema.create({
- name: 'lead',
- label: 'Lead',
-
- fields: {
- status: Field.select({
- options: ['New', 'Contacted', 'Qualified', 'Converted'],
- }),
- created_date: Field.datetime({ label: 'Created Date' }),
- last_contacted: Field.datetime({ label: 'Last Contacted' }),
- },
-
- workflows: [
- {
- name: 'set_default_status',
- objectName: 'lead',
- triggerType: 'on_create',
- actions: [
- {
- name: 'set_status_new',
- type: 'field_update',
- field: 'status',
- value: 'New',
- },
- {
- name: 'set_created_date',
- type: 'field_update',
- field: 'created_date',
- value: 'NOW()',
- },
- ],
- active: true,
- },
- ],
-});
-```
-
----
-
-### 2. Conditional Workflow
-
-```typescript
-export const Opportunity = ObjectSchema.create({
- name: 'opportunity',
- label: 'Opportunity',
-
- fields: {
- stage: Field.select({ options: ['...'] }),
- amount: Field.currency({ label: 'Amount' }),
- owner: Field.lookup('user', { label: 'Owner' }),
- approved: Field.boolean({ label: 'Approved' }),
- },
-
- workflows: [
- {
- name: 'require_approval_large_deals',
- objectName: 'opportunity',
- triggerType: 'on_update',
- criteria: 'amount > 100000 AND stage = "Closed Won"', // Only for big deals
- actions: [
- {
- name: 'set_approval_required',
- type: 'field_update',
- field: 'approved',
- value: 'false',
- },
- {
- name: 'notify_manager',
- type: 'email_alert',
- template: 'approval_required_email',
- recipients: ['sales_manager@company.com'],
- },
- ],
- active: true,
- },
- ],
-});
-```
-
----
-
-### 3. Email Alert Workflow
-
-```typescript
-export const Case = ObjectSchema.create({
- name: 'case',
- label: 'Case',
-
- fields: {
- priority: Field.select({ options: ['Low', 'Medium', 'High', 'Critical'] }),
- status: Field.select({ options: ['Open', 'In Progress', 'Resolved'] }),
- contact: Field.lookup('contact', { label: 'Contact' }),
- },
-
- workflows: [
- {
- name: 'escalate_critical_cases',
- objectName: 'case',
- triggerType: 'on_create_or_update',
- criteria: 'priority = "Critical" AND status = "Open"',
- actions: [
- {
- name: 'notify_support_team',
- type: 'email_alert',
- template: 'critical_case_alert',
- recipients: ['support_team@company.com', 'manager@company.com'],
- },
- ],
- active: true,
- },
- ],
-});
-```
-
----
-
-### 4. Update Timestamp Workflow
-
-```typescript
-export const Account = ObjectSchema.create({
- name: 'account',
- label: 'Account',
-
- fields: {
- last_activity_date: Field.datetime({ label: 'Last Activity' }),
- last_modified_date: Field.datetime({ label: 'Last Modified' }),
- },
-
- workflows: [
- {
- name: 'update_last_activity',
- objectName: 'account',
- triggerType: 'on_update',
- actions: [
- {
- name: 'set_last_activity',
- type: 'field_update',
- field: 'last_activity_date',
- value: 'NOW()',
- },
- ],
- active: true,
- },
- ],
-});
-```
-
----
-
-## Best Practices
-
-### Validation Rules
-
-1. **Use Specific Types**: Use `unique` instead of `script` for uniqueness, `state_machine` instead of complex conditions
-2. **Clear Messages**: Provide actionable error messages that guide users
-3. **Severity Levels**: Use `warning` for soft validations, `error` for hard stops
-4. **Performance**: Avoid complex formulas in validations, use indexes for uniqueness checks
-5. **Testing**: Test all edge cases and state transitions
-
-### Workflows
-
-1. **Criteria First**: Use criteria to limit workflow execution, not blanket triggers
-2. **Avoid Loops**: Be careful with `on_update` workflows that update the same record
-3. **Batch-Safe**: Ensure workflows can handle bulk operations
-4. **Error Handling**: Workflows should not block saves on non-critical failures
-5. **Audit Trail**: Use field updates to maintain audit logs (last_modified_by, etc.)
-
----
-
-## Formula Functions Reference
-
-Common functions used in validation conditions and workflow criteria:
-
-### String Functions
-- `CONCAT(str1, str2, ...)` - Concatenate strings
-- `LEN(str)` - String length
-- `ISBLANK(str)` - Check if empty
-- `CONTAINS(str, substring)` - Check if contains
-- `UPPER(str)`, `LOWER(str)` - Case conversion
-
-### Date Functions
-- `TODAY()` - Current date
-- `NOW()` - Current datetime
-- `DAYS_BETWEEN(date1, date2)` - Days between dates
-- `ADDDAYS(date, num)` - Add days to date
-
-### Logic Functions
-- `AND(cond1, cond2, ...)` - Logical AND
-- `OR(cond1, cond2, ...)` - Logical OR
-- `NOT(cond)` - Logical NOT
-- `IF(condition, true_value, false_value)` - Conditional
-
-### Number Functions
-- `ABS(num)` - Absolute value
-- `ROUND(num, decimals)` - Round number
-- `MAX(num1, num2, ...)` - Maximum
-- `MIN(num1, num2, ...)` - Minimum
-
----
-
-## Real-World Example: CRM Opportunity
-
-Complete example combining validations and workflows:
-
-```typescript
-export const Opportunity = ObjectSchema.create({
- name: 'opportunity',
- label: 'Opportunity',
-
- fields: {
- name: Field.text({ label: 'Name', required: true }),
- account: Field.lookup('account', { label: 'Account', required: true }),
- amount: Field.currency({ label: 'Amount' }),
- close_date: Field.date({ label: 'Close Date' }),
- probability: Field.percent({ label: 'Probability' }),
- stage: Field.select({
- options: [
- { label: 'Prospecting', value: 'prospecting' },
- { label: 'Qualification', value: 'qualification' },
- { label: 'Proposal', value: 'proposal' },
- { label: 'Negotiation', value: 'negotiation' },
- { label: 'Closed Won', value: 'closed_won' },
- { label: 'Closed Lost', value: 'closed_lost' },
- ],
- }),
- approved: Field.boolean({ label: 'Approved' }),
- last_stage_change: Field.datetime({ label: 'Last Stage Change' }),
- },
-
- validations: [
- // Basic validations
- {
- name: 'positive_amount',
- type: 'script',
- condition: 'amount < 0',
- message: 'Amount must be positive',
- },
-
- // State machine
- {
- name: 'stage_progression',
- type: 'state_machine',
- field: 'stage',
- message: 'Invalid stage transition',
- transitions: {
- 'prospecting': ['qualification', 'closed_lost'],
- 'qualification': ['prospecting', 'proposal', 'closed_lost'],
- 'proposal': ['qualification', 'negotiation', 'closed_lost'],
- 'negotiation': ['proposal', 'closed_won', 'closed_lost'],
- 'closed_won': [],
- 'closed_lost': [],
- },
- },
-
- // Cross-field validation
- {
- name: 'probability_stage_match',
- type: 'cross_field',
- fields: ['stage', 'probability'],
- condition: 'stage = "Closed Won" AND probability < 100',
- message: 'Closed Won opportunities must have 100% probability',
- },
- ],
-
- workflows: [
- // Update timestamp on stage change
- {
- name: 'track_stage_changes',
- objectName: 'opportunity',
- triggerType: 'on_update',
- criteria: 'ISCHANGED(stage)',
- actions: [
- {
- name: 'update_timestamp',
- type: 'field_update',
- field: 'last_stage_change',
- value: 'NOW()',
- },
- ],
- },
-
- // Require approval for large deals
- {
- name: 'large_deal_approval',
- objectName: 'opportunity',
- triggerType: 'on_update',
- criteria: 'amount > 500000 AND stage = "Negotiation"',
- actions: [
- {
- name: 'request_approval',
- type: 'field_update',
- field: 'approved',
- value: 'false',
- },
- {
- name: 'notify_exec_team',
- type: 'email_alert',
- template: 'large_deal_approval',
- recipients: ['ceo@company.com', 'cfo@company.com'],
- },
- ],
- },
- ],
-});
-```
-
----
-
-## Next Steps
-
-- [Field Types Guide](/docs/guides/field-types)
-- [Object Schema Reference](/docs/references/data/core/Object)
-- [Formula Functions](/docs/references/data/formulas)
-- [CRM Example](https://github.com/objectstack-ai/spec/tree/main/examples/crm) - See validations and workflows in action
diff --git a/content/docs/index.cn.mdx b/content/docs/index.cn.mdx
deleted file mode 100644
index e2058a915..000000000
--- a/content/docs/index.cn.mdx
+++ /dev/null
@@ -1,71 +0,0 @@
----
-title: 欢迎使用 ObjectStack
-description: 后 SaaS 时代的元数据驱动协议。
----
-
-import { Book, Compass, FileText, Layers } from 'lucide-react';
-
-**ObjectStack** 不仅仅是一个框架;它是一个用于构建企业软件的**协议**。
-它将*业务意图*(用 JSON/YAML 定义)与*技术执行*(由内核处理)解耦。
-
-本文档是 ObjectStack 协议的权威参考。
-
-## 如何导航
-
-
- }
- title="快速开始"
- href="/docs/guides/getting-started"
- description="5 分钟内构建你的第一个对象。通过实际示例学习基础知识。"
- />
- }
- title="概念"
- href="/docs/concepts/manifesto"
- description="理解「意图优于实现」和「本地优先」架构的理念。"
- />
- }
- title="规范"
- href="/docs/specifications/data/architecture"
- description="架构蓝图。深入了解 ObjectQL(数据)、ObjectUI(视图)和 ObjectOS(控制)。"
- />
- }
- title="协议参考"
- href="/docs/references/data/core/Object"
- description="字典。每个模式、字段类型和配置选项的全面参考。"
- />
-
-
-## 快速链接
-
-### 基础指南
-- **[字段类型](/docs/guides/field-types)** - 35 种字段类型及示例(文本、数字、选择、查找、公式等)
-- **[视图配置](/docs/guides/view-configuration)** - 网格、看板、日历、甘特图和表单布局
-- **[工作流与验证](/docs/guides/workflows-validation)** - 业务规则和自动化
-- **[项目结构](/docs/guides/project-structure)** - 组织代码的最佳实践
-
-### 示例
-- **[CRM 示例](https://github.com/objectstack-ai/spec/tree/main/examples/crm)** - 全功能应用,包含 6 个对象、工作流、视图、仪表板
-- **[Todo 示例](https://github.com/objectstack-ai/spec/tree/main/examples/todo)** - 快速入门最小化示例
-
-## "五位一体"架构
-
-ObjectStack 建立在五个协同工作的核心模块之上:
-
-| 模块 | 协议 | 职责 |
-| :--- | :--- | :--- |
-| **数据层** | **[ObjectQL](/docs/specifications/data/architecture)** | 定义数据的形状(`Object`、`Field`)以及如何访问它(`Query AST`)。与 SQL/NoSQL 无关。 |
-| **UI 层** | **[ObjectUI](/docs/specifications/ui/sdui-protocol)** | 投影层。将用户界面定义为抽象的 JSON 布局(视图、仪表板、操作)。 |
-| **控制层** | **[ObjectOS](/docs/specifications/server/kernel-architecture)** | 内核。处理身份、安全、同步和自动化。 |
-| **AI 层** | **AI 协议** | AI 代理定义、工具、知识库和模型配置。 |
-| **API 层** | **API 协议** | 标准化的 REST/GraphQL 契约,带请求/响应封装。 |
-
-## 适用对象
-
-* **平台架构师:** 想要构建可扩展的内部开发者平台(IDP)。
-* **协议实现者:** 想要为 ObjectQL 编写新的驱动(例如,用于 FoundationDB)或为 ObjectUI 编写新的渲染器(例如,用于 Flutter)。
-* **AI 代理开发者:** 需要一种确定性、结构化的通用语言来让 AI 生成软件。
-* **低代码构建者:** 想要一个强大的元数据驱动平台来快速应用开发。
diff --git a/content/docs/meta.cn.json b/content/docs/meta.cn.json
deleted file mode 100644
index 917b274ea..000000000
--- a/content/docs/meta.cn.json
+++ /dev/null
@@ -1,14 +0,0 @@
-{
- "title": "文档",
- "pages": [
- "quick-start",
- "tutorials",
- "guides",
- "concepts",
- "specifications",
- "standards",
- "references",
- "faq",
- "troubleshooting"
- ]
-}
diff --git a/content/docs/protocols/objectui/layout-dsl.mdx b/content/docs/protocols/objectui/layout-dsl.mdx
index 984d3e5d6..1c5d81154 100644
--- a/content/docs/protocols/objectui/layout-dsl.mdx
+++ b/content/docs/protocols/objectui/layout-dsl.mdx
@@ -3,7 +3,7 @@ title: Layout DSL
description: Declarative layout description language for pages, sections, and responsive grids
---
-import { Layout, Grid, Columns, Box, Monitor, Smartphone, Tablet } from 'lucide-react';
+import { Layout, Grid, Columns, Box, Monitor, Smartphone, Tablet, MousePointer } from 'lucide-react';
# Layout DSL: Composing User Interfaces
diff --git a/content/docs/quick-start.mdx b/content/docs/quick-start.mdx
deleted file mode 100644
index 16b5f38be..000000000
--- a/content/docs/quick-start.mdx
+++ /dev/null
@@ -1,117 +0,0 @@
----
-title: Quick Start
-description: Get started with ObjectStack in under 5 minutes. Choose your path based on your role and goals.
----
-
-import { Code, Layers, Palette, Zap } from 'lucide-react';
-
-Welcome to ObjectStack! This quick start guide will help you get up and running based on your role and what you want to accomplish.
-
-## Choose Your Path
-
-
- }
- title="I want to build an app"
- href="./quick-start/build-first-app"
- description="Complete tutorial: Build a task management app in 10 minutes"
- />
- }
- title="I'm a backend developer"
- href="./quick-start/backend-developers"
- description="Learn how to define Objects, Fields, and Business Logic"
- />
- }
- title="I'm a frontend developer"
- href="./quick-start/frontend-developers"
- description="Understand Views, Pages, and UI Components"
- />
- }
- title="I'm a platform architect"
- href="./quick-start/architects"
- description="Deep dive into the protocol architecture and design decisions"
- />
-
-
-## 30-Second Overview
-
-ObjectStack is a **metadata-driven protocol** that lets you define your entire application—data models, business logic, and UI—as **type-safe JSON/TypeScript** configurations.
-
-```typescript
-// Define a data model
-export const Task = ObjectSchema.create({
- name: 'task',
- label: 'Task',
- fields: {
- title: Field.text({ label: 'Title', required: true }),
- status: Field.select({
- label: 'Status',
- options: ['todo', 'in_progress', 'done']
- }),
- due_date: Field.date({ label: 'Due Date' }),
- }
-});
-```
-
-**That's it!** You've just defined a complete data model with:
-- ✅ TypeScript type safety
-- ✅ Runtime validation (via Zod)
-- ✅ Automatic API generation
-- ✅ Database schema migration
-- ✅ Admin UI generation
-
-## What Makes ObjectStack Different?
-
-| Traditional Approach | ObjectStack Protocol |
-| :--- | :--- |
-| Write Models + Controllers + Views | **Define metadata once** |
-| SQL migrations by hand | **Auto-generated from schema** |
-| Build CRUD APIs manually | **REST/GraphQL auto-generated** |
-| Hardcoded UI components | **Server-driven UI from JSON** |
-| Scattered business logic | **Declarative rules & workflows** |
-
-## Next Steps
-
-
-
-### 1. Install the package
-
-```bash
-npm install @objectstack/spec zod
-```
-
-### 2. Choose your learning path
-
-- **Quick & Practical:** [Build Your First App](/docs/quick-start/build-first-app) - Hands-on tutorial
-- **Conceptual Understanding:** [Core Concepts](/docs/concepts/manifesto) - Philosophy and architecture
-- **Complete Reference:** [Developer Guides](/docs/guides/getting-started) - Comprehensive documentation
-
-### 3. Explore examples
-
-- [CRM Example](https://github.com/objectstack-ai/spec/tree/main/examples/crm) - Full-featured application
-- [Todo Example](https://github.com/objectstack-ai/spec/tree/main/examples/todo) - Minimal quick-start
-
-
-
-## Common Use Cases
-
-### Internal Tools & Admin Panels
-Build CRUD applications with complex business logic in hours, not weeks.
-
-### CRM & ERP Systems
-Replicate Salesforce-like functionality with complete customization.
-
-### Workflow Automation Platforms
-Define approval flows, state machines, and automation rules declaratively.
-
-### Multi-tenant SaaS Platforms
-One codebase, infinite customizations through metadata configuration.
-
-## Need Help?
-
-- **Documentation:** You're reading it! Use the search bar above.
-- **GitHub Issues:** [Report bugs or request features](https://github.com/objectstack-ai/spec/issues)
-- **Examples:** Browse the `/examples` directory in the repository
diff --git a/content/docs/quick-start/architects.mdx b/content/docs/quick-start/architects.mdx
deleted file mode 100644
index 87ad6241e..000000000
--- a/content/docs/quick-start/architects.mdx
+++ /dev/null
@@ -1,502 +0,0 @@
----
-title: For Platform Architects
-description: Deep dive into ObjectStack's architecture, design decisions, and how it compares to industry standards.
----
-
-Welcome architects! If you're evaluating ObjectStack for your platform or investigating metadata-driven architectures, this guide will help you understand the design philosophy and technical decisions.
-
-## Architectural Overview
-
-ObjectStack is a **protocol-first, metadata-driven platform** that virtualizes the application stack into three declarative layers:
-
-```
-┌──────────────────────────────────────┐
-│ AI Protocol (Optional) │ ← Agent definitions, tools, knowledge
-├──────────────────────────────────────┤
-│ API Protocol │ ← REST/GraphQL contracts
-├──────────────────────────────────────┤
-│ UI Layer (ObjectUI) │ ← Server-Driven UI definitions
-├──────────────────────────────────────┤
-│ Data Layer (ObjectQL) │ ← Schema, queries, business logic
-├──────────────────────────────────────┤
-│ System Layer (ObjectOS) │ ← Runtime kernel, plugins, drivers
-└──────────────────────────────────────┘
-```
-
-## Design Philosophy
-
-### 1. Intent over Implementation
-
-**Problem:** Traditional development couples *what you want* with *how to do it*.
-
-**ObjectStack Solution:** Separate business intent (metadata) from technical execution (kernel).
-
-```typescript
-// INTENT (what you want)
-const Task = ObjectSchema.create({
- name: 'task',
- fields: {
- title: Field.text({ required: true }),
- }
-});
-
-// EXECUTION (handled by kernel)
-// ✓ SQL schema generation
-// ✓ API route creation
-// ✓ Validation logic
-// ✓ UI rendering
-```
-
-### 2. Local-First, Cloud-Optional
-
-Inspired by: [Local-First Software Manifesto](https://www.inkandswitch.com/local-first/)
-
-**Benefits:**
-- ✅ Offline-capable by default
-- ✅ No vendor lock-in
-- ✅ Data ownership
-- ✅ Instant responsiveness
-
-### 3. Protocol, Not Framework
-
-Like **HTTP** or **SQL**, ObjectStack defines a protocol that multiple implementations can follow.
-
-```
-Protocol Definition (this repo)
- ↓
-┌──────────────────────────────────────────────────────┐
-│ Implementations (bring your own) │
-├──────────────────────────────────────────────────────┤
-│ • Kernel: Node.js, Deno, Bun, Go, Python │
-│ • Driver: PostgreSQL, MongoDB, Redis, Custom │
-│ • Renderer: React, Vue, Flutter, Native │
-└──────────────────────────────────────────────────────┘
-```
-
-## Industry Comparison
-
-### Salesforce Platform
-
-| Feature | Salesforce | ObjectStack |
-| :--- | :--- | :--- |
-| **Metadata-Driven** | ✅ Yes | ✅ Yes |
-| **Custom Objects** | ✅ Yes | ✅ Yes |
-| **Formula Fields** | ✅ Yes | ✅ Yes |
-| **Workflows** | ✅ Yes | ✅ Yes |
-| **Open Source** | ❌ No | ✅ Yes |
-| **Self-Hosted** | ❌ No | ✅ Yes |
-| **Type-Safe** | ❌ No | ✅ TypeScript + Zod |
-| **Database Agnostic** | ❌ No | ✅ Yes (Driver Model) |
-
-**ObjectStack = Salesforce's metadata model + Open Source + Type Safety**
-
-### ServiceNow Platform
-
-| Feature | ServiceNow | ObjectStack |
-| :--- | :--- | :--- |
-| **Configuration as Code** | ✅ Yes | ✅ Yes |
-| **Server-Driven UI** | ✅ Yes | ✅ Yes |
-| **Business Rules Engine** | ✅ Yes | ✅ Yes |
-| **Plugin Architecture** | ✅ Yes | ✅ Yes |
-| **Open Protocol** | ❌ No | ✅ Yes |
-| **Local-First** | ❌ No | ✅ Yes |
-| **Modern DX** | ⚠️ XML-based | ✅ TypeScript + JSON |
-
-### Hasura / PostgREST (Auto-API)
-
-| Feature | Hasura | ObjectStack |
-| :--- | :--- | :--- |
-| **Auto-Generated API** | ✅ Yes | ✅ Yes |
-| **GraphQL Support** | ✅ Yes | ✅ Yes |
-| **Database First** | ✅ Yes | ⚠️ Schema-first |
-| **Business Logic** | ⚠️ External | ✅ Built-in (formulas, workflows) |
-| **UI Generation** | ❌ No | ✅ Yes |
-| **Multi-DB Support** | ⚠️ Limited | ✅ Via drivers |
-
-### Strapi / Directus (Headless CMS)
-
-| Feature | Strapi | ObjectStack |
-| :--- | :--- | :--- |
-| **Schema Builder** | ✅ Yes | ✅ Yes |
-| **Auto Admin Panel** | ✅ Yes | ✅ Yes |
-| **API Generation** | ✅ Yes | ✅ Yes |
-| **Business Logic** | ⚠️ Code-based | ✅ Declarative |
-| **Type Safety** | ⚠️ Partial | ✅ Full (Zod) |
-| **Enterprise Features** | ⚠️ Limited | ✅ Workflows, validation, permissions |
-
-## Technical Architecture
-
-### Layer 1: Data Protocol (ObjectQL)
-
-Inspired by: **SQL**, **GraphQL**, **Apache Calcite**
-
-**Abstraction:** Represent queries as an Abstract Syntax Tree (AST).
-
-```typescript
-// High-level query
-const query = Query.create({
- object: 'order',
- filters: { total: { gt: 1000 } },
- include: ['customer'],
-});
-
-// Compiles to AST
-const ast = {
- type: 'SELECT',
- from: { object: 'order' },
- where: {
- type: 'BINARY_OP',
- operator: 'GT',
- left: { type: 'FIELD', name: 'total' },
- right: { type: 'LITERAL', value: 1000 },
- },
- joins: [
- { object: 'customer', type: 'LEFT', on: 'customer_id' },
- ],
-};
-
-// Driver translates AST → SQL/NoSQL/etc.
-```
-
-**Benefits:**
-- ✅ Database agnostic (SQL, NoSQL, SaaS APIs)
-- ✅ Query optimization at AST level
-- ✅ Consistent semantics across backends
-
-### Layer 2: UI Protocol (ObjectUI)
-
-Inspired by: **Salesforce Lightning**, **React Server Components**, **Flutter**
-
-**Server-Driven UI (SDUI):** Client is a "dumb renderer" that interprets JSON configs.
-
-```typescript
-// Server defines UI as JSON
-const view = ListView.create({
- viewType: 'grid',
- columns: [{ field: 'title' }],
-});
-
-// Client renders based on schema
-
-```
-
-**Benefits:**
-- ✅ Update UI without app rebuild
-- ✅ A/B testing at configuration level
-- ✅ Consistent UX across platforms
-- ✅ AI can generate/modify UI
-
-### Layer 3: System Protocol (ObjectOS)
-
-Inspired by: **Kubernetes**, **OSGi**, **Eclipse RCP**
-
-**Plugin Architecture:** Kernel loads and orchestrates plugins.
-
-```typescript
-interface Plugin {
- name: string;
- version: string;
-
- // Lifecycle hooks
- onLoad(kernel: IKernel): void;
- onUnload(): void;
-
- // Capabilities
- provides?: {
- drivers?: Driver[];
- apis?: ApiContract[];
- ui?: Component[];
- };
-}
-```
-
-**Benefits:**
-- ✅ Modular, composable system
-- ✅ Hot-swappable components
-- ✅ Ecosystem of community plugins
-
-## Zod-First Approach
-
-**Decision:** All schemas are defined using Zod.
-
-```typescript
-// Source of truth
-export const TaskSchema = z.object({
- title: z.string().max(200),
- status: z.enum(['todo', 'done']),
-});
-
-// Derived artifacts
-type Task = z.infer; // TypeScript type
-const jsonSchema = zodToJsonSchema(TaskSchema); // JSON Schema
-const sqlSchema = zodToSql(TaskSchema); // SQL DDL
-```
-
-**Benefits:**
-- ✅ **Runtime validation** (Zod validates at runtime)
-- ✅ **Compile-time types** (TypeScript inference)
-- ✅ **Single source of truth** (no drift between types and validators)
-- ✅ **Tooling ecosystem** (JSON Schema for OpenAPI, IDEs, etc.)
-
-## Formula Engine
-
-**Inspired by:** Salesforce Formula Fields, Excel Formulas
-
-ObjectStack includes a declarative formula language:
-
-```typescript
-Field.formula({
- expression: 'IF(discount_code != NULL, subtotal * 0.9, subtotal)',
-})
-```
-
-**Implementation:**
-1. Parse formula → AST
-2. Type-check AST
-3. Compile to JavaScript (or other runtime)
-4. Execute safely (sandboxed)
-
-**Security:**
-- ✅ No arbitrary code execution
-- ✅ Whitelist of allowed functions
-- ✅ Type-safe by construction
-
-## Multi-Tenancy Strategy
-
-ObjectStack supports **multiple multi-tenancy models**:
-
-### 1. Schema-per-Tenant (PostgreSQL)
-
-```sql
-CREATE SCHEMA tenant_acme;
-CREATE SCHEMA tenant_beta;
-```
-
-**Pros:** Strong isolation, easy backup/restore per tenant
-**Cons:** Schema proliferation, migration complexity
-
-### 2. Row-Level Security (RLS)
-
-```sql
-ALTER TABLE orders ENABLE ROW LEVEL SECURITY;
-CREATE POLICY tenant_isolation ON orders
- USING (tenant_id = current_tenant_id());
-```
-
-**Pros:** Efficient, single schema
-**Cons:** Query performance overhead
-
-### 3. Database-per-Tenant
-
-**Pros:** Ultimate isolation
-**Cons:** Resource intensive
-
-**ObjectStack Recommendation:** Configurable per deployment.
-
-## Scalability Considerations
-
-### Horizontal Scalability
-
-```
-┌─────────────────────────────────────────┐
-│ Load Balancer │
-└─────────────┬───────────────────────────┘
- │
- ┌─────────┼─────────┬─────────┐
- ▼ ▼ ▼ ▼
- [Kernel] [Kernel] [Kernel] [Kernel] ← Stateless kernels
- │ │ │ │
- └─────────┴─────────┴─────────┘
- │
- ▼
- [Database] ← Centralized or sharded
-```
-
-**Stateless Kernel:**
-- All state in database or cache
-- Session in Redis/Memcached
-- File uploads in S3/Minio
-
-### Caching Strategy
-
-```typescript
-// Multi-layer cache
-const data = await cache.get('order:123') // L1: Redis
- ?? await dbCache.get('order:123') // L2: DB connection pool
- ?? await database.query({ ... }); // L3: Source
-
-cache.set('order:123', data, { ttl: 60 });
-```
-
-### Database Sharding
-
-ObjectStack AST allows **transparent sharding**:
-
-```typescript
-// Driver detects shard key
-const driver = new ShardedDriver({
- shardKey: 'customer_id',
- shards: [db1, db2, db3],
-});
-
-// Query automatically routed
-await driver.find({
- object: 'order',
- filters: { customer_id: { eq: 'acme-corp' } }, // → shard 1
-});
-```
-
-## Security Architecture
-
-### 1. Authentication
-
-**Pluggable providers:**
-- OAuth 2.0 / OIDC
-- SAML
-- JWT
-- API Keys
-- Custom
-
-### 2. Authorization
-
-**Multi-level access control:**
-
-```typescript
-// Object-level permissions
-Permission.create({
- profile: 'sales_user',
- object: 'opportunity',
- create: true,
- read: true,
- update: { owned: true }, // Only own records
- delete: false,
-});
-
-// Field-level security
-FieldPermission.create({
- profile: 'sales_user',
- object: 'account',
- field: 'annual_revenue',
- read: false, // Hidden field
-});
-
-// Row-level sharing
-SharingRule.create({
- object: 'account',
- sharedTo: 'sales_team',
- accessLevel: 'read',
- criteria: { region: 'US' },
-});
-```
-
-### 3. Data Encryption
-
-**At rest:** Database-level encryption (LUKS, TDE)
-**In transit:** TLS 1.3
-**Field-level:** Encrypt sensitive fields (PII)
-
-```typescript
-Field.text({
- label: 'SSN',
- encrypted: true,
- encryptionKey: 'field_encryption_key',
-})
-```
-
-## Observability
-
-### Structured Logging
-
-```typescript
-logger.info('Query executed', {
- object: 'order',
- duration: 45,
- rowsReturned: 100,
- userId: 'user-123',
-});
-```
-
-### Metrics (OpenTelemetry)
-
-- Request rate, latency, errors (RED metrics)
-- Database query performance
-- Cache hit rate
-- Formula evaluation time
-
-### Tracing
-
-Distributed tracing across:
-1. API request
-2. Kernel processing
-3. Driver query
-4. Database execution
-
-## When to Use ObjectStack
-
-### ✅ Good Fit
-
-- **Internal tools** (admin panels, dashboards)
-- **CRUD-heavy applications** (CRM, ERP, ticketing)
-- **Multi-tenant SaaS** (need customization per tenant)
-- **Rapid prototyping** (MVP in hours/days)
-- **Low-code platforms** (enable non-developers)
-
-### ⚠️ Consider Alternatives
-
-- **Real-time gaming** (too much abstraction overhead)
-- **Ultra-high throughput** (raw SQL might be faster)
-- **Greenfield with simple needs** (might be overkill)
-
-## Migration Path
-
-### Incremental Adoption
-
-```
-Existing App
- ↓
-1. Wrap existing DB with ObjectStack driver
-2. Generate ObjectStack schemas from DB
-3. Replace one module at a time
-4. Gradual migration
-```
-
-### Coexistence Strategy
-
-```typescript
-// Use ObjectStack for new features
-const newFeature = ObjectSchema.create({ ... });
-
-// Keep existing code for legacy features
-app.get('/legacy', legacyController);
-```
-
-## Next Steps for Architects
-
-
-
-
-
-
-
-
-## Resources
-
-- **[Architecture Diagrams](https://github.com/objectstack-ai/spec/blob/main/ARCHITECTURE.md)** - Visual reference
-- **[Development Roadmap](https://github.com/objectstack-ai/spec/blob/main/internal/planning/DEVELOPMENT_ROADMAP.md)** - Future plans
-- **[Contributing Guide](https://github.com/objectstack-ai/spec/blob/main/CONTRIBUTING.md)** - How to contribute
diff --git a/content/docs/quick-start/backend-developers.mdx b/content/docs/quick-start/backend-developers.mdx
deleted file mode 100644
index e813af171..000000000
--- a/content/docs/quick-start/backend-developers.mdx
+++ /dev/null
@@ -1,396 +0,0 @@
----
-title: For Backend Developers
-description: Learn ObjectStack from a backend perspective - focus on data modeling, business logic, and API generation.
----
-
-Welcome backend developers! If you're familiar with ORMs (Sequelize, TypeORM, Prisma) or NoSQL ODMs (Mongoose), you'll find ObjectStack refreshingly familiar yet more powerful.
-
-## Core Concept
-
-ObjectStack replaces traditional:
-```
-Model → Migration → Controller → API Routes
-```
-
-With a single source of truth:
-```typescript
-Object Definition → Everything Auto-Generated
-```
-
-## Quick Comparison
-
-### Traditional Approach (Express + Sequelize)
-
-```typescript
-// 1. Define Model
-const Task = sequelize.define('Task', {
- title: { type: DataTypes.STRING, allowNull: false },
- status: { type: DataTypes.ENUM('todo', 'done') },
- dueDate: { type: DataTypes.DATE },
-});
-
-// 2. Write Migration
-await queryInterface.createTable('tasks', { /* ... */ });
-
-// 3. Write Controller
-router.post('/tasks', async (req, res) => {
- const task = await Task.create(req.body);
- res.json(task);
-});
-
-// 4. Add Validation
-const validateTask = (req, res, next) => {
- if (!req.body.title) return res.status(400).json({ error: 'Title required' });
- next();
-};
-
-// Total: 4 files, ~150 lines of code
-```
-
-### ObjectStack Protocol
-
-```typescript
-// Everything in ONE definition
-export const Task = ObjectSchema.create({
- name: 'task',
- label: 'Task',
- fields: {
- title: Field.text({ label: 'Title', required: true }),
- status: Field.select({
- label: 'Status',
- options: ['todo', 'in_progress', 'done']
- }),
- due_date: Field.date({ label: 'Due Date' }),
- }
-});
-
-// That's it! You get:
-// ✅ TypeScript types
-// ✅ Runtime validation (Zod)
-// ✅ REST API (CRUD operations)
-// ✅ GraphQL API (optional)
-// ✅ Database schema
-// ✅ Admin UI
-
-// Total: 1 file, ~15 lines of code
-```
-
-## Field Types You Know and Love
-
-ObjectStack provides **35 field types** with automatic validation:
-
-| ObjectStack Type | Similar To | Features |
-| :--- | :--- | :--- |
-| `Field.text()` | `VARCHAR` / `String` | Max length, pattern validation |
-| `Field.number()` | `INTEGER` / `Number` | Min, max, precision |
-| `Field.boolean()` | `BOOLEAN` | True/false |
-| `Field.date()` | `DATE` | Date only |
-| `Field.datetime()` | `TIMESTAMP` | Date + time |
-| `Field.select()` | `ENUM` | Predefined options |
-| `Field.lookup()` | `FOREIGN KEY` | Relations |
-| `Field.json()` | `JSON` / `JSONB` | Structured data |
-
-### Example: Complex Data Model
-
-```typescript
-import { ObjectSchema, Field } from '@objectstack/spec';
-
-export const Order = ObjectSchema.create({
- name: 'order',
- label: 'Order',
- nameField: 'order_number',
-
- fields: {
- // Auto-generated unique ID
- order_number: Field.autonumber({
- label: 'Order #',
- format: 'ORD-{0000}',
- }),
-
- // Foreign key relationship
- customer: Field.lookup({
- label: 'Customer',
- reference: 'customer',
- displayField: 'company_name',
- required: true,
- }),
-
- // Multi-select for tags
- tags: Field.multiselect({
- label: 'Tags',
- options: ['urgent', 'wholesale', 'repeat_customer'],
- }),
-
- // Decimal for currency
- total_amount: Field.currency({
- label: 'Total Amount',
- precision: 2,
- min: 0,
- }),
-
- // Calculated field
- discount_percentage: Field.formula({
- label: 'Discount %',
- returnType: 'number',
- expression: '(original_amount - total_amount) / original_amount * 100',
- }),
-
- // JSON for flexible data
- metadata: Field.json({
- label: 'Metadata',
- schema: z.object({
- source: z.enum(['web', 'mobile', 'api']),
- utm_campaign: z.string().optional(),
- }),
- }),
- },
-});
-```
-
-## Business Logic: Validation & Workflows
-
-### Validation Rules
-
-Like database constraints, but more powerful:
-
-```typescript
-import { ValidationRule } from '@objectstack/spec';
-
-export const orderValidations = [
- // Business rule: Discount cannot exceed 50%
- ValidationRule.create({
- name: 'max_discount',
- object: 'order',
- errorMessage: 'Discount cannot exceed 50%',
- condition: 'discount_percentage > 50',
- }),
-
- // Cross-field validation
- ValidationRule.create({
- name: 'delivery_date_after_order',
- object: 'order',
- errorMessage: 'Delivery date must be after order date',
- condition: 'delivery_date <= order_date',
- }),
-];
-```
-
-### Workflows (Triggers)
-
-Like database triggers, but declarative:
-
-```typescript
-import { Workflow, WorkflowAction } from '@objectstack/spec';
-
-export const orderWorkflow = Workflow.create({
- name: 'notify_on_high_value',
- object: 'order',
- trigger: 'after_insert',
-
- // Run when total > 10,000
- condition: 'total_amount > 10000',
-
- actions: [
- // Send email notification
- WorkflowAction.sendEmail({
- to: 'sales@company.com',
- subject: 'High-value order created',
- body: 'Order {order_number} for ${total_amount} created',
- }),
-
- // Update related record
- WorkflowAction.updateField({
- object: 'customer',
- recordId: '{customer.id}',
- fields: {
- last_high_value_order: '{id}',
- },
- }),
- ],
-});
-```
-
-## API Generation
-
-Your ObjectStack definitions automatically generate REST APIs:
-
-```http
-# Auto-generated endpoints
-POST /api/v1/objects/order # Create
-GET /api/v1/objects/order/:id # Read
-PATCH /api/v1/objects/order/:id # Update
-DELETE /api/v1/objects/order/:id # Delete
-GET /api/v1/objects/order # List with query
-
-# Advanced queries
-GET /api/v1/objects/order?filter[total_amount][gt]=1000
-GET /api/v1/objects/order?sort=-created_at&limit=10
-GET /api/v1/objects/order?include=customer,line_items
-```
-
-### Query Builder (Type-Safe)
-
-```typescript
-import { Query } from '@objectstack/spec';
-
-// Build complex queries
-const query = Query.create({
- object: 'order',
-
- // WHERE clause
- filters: {
- total_amount: { gt: 1000 },
- status: { in: ['pending', 'processing'] },
- 'customer.country': { eq: 'US' },
- },
-
- // JOIN / Include related records
- include: ['customer', 'line_items'],
-
- // ORDER BY
- sort: [{ field: 'created_at', direction: 'desc' }],
-
- // LIMIT / OFFSET
- limit: 20,
- offset: 0,
-
- // SELECT (field projection)
- fields: ['order_number', 'total_amount', 'customer.company_name'],
-});
-```
-
-## Database Agnostic
-
-ObjectStack **abstracts** the database layer:
-
-```typescript
-// Your code (driver-agnostic)
-const result = await kernel.query({
- object: 'order',
- filters: { status: { eq: 'pending' } },
-});
-
-// Works with ANY driver:
-// - PostgreSQL Driver
-// - MySQL Driver
-// - MongoDB Driver
-// - Redis Driver
-// - In-Memory Driver
-// - Your Custom Driver
-```
-
-### Custom Driver Example
-
-```typescript
-import { Driver, DriverCapabilities } from '@objectstack/spec';
-
-export class MyCustomDriver implements Driver {
- readonly capabilities: DriverCapabilities = {
- queryFilters: ['eq', 'gt', 'lt', 'in'],
- queryAggregations: ['count', 'sum', 'avg'],
- transactions: true,
- };
-
- async find(query: Query): Promise {
- // Your implementation
- }
-
- async create(object: string, data: Record): Promise {
- // Your implementation
- }
-
- // ... more methods
-}
-```
-
-## Advanced: Formula Engine
-
-ObjectStack includes a **SQL-like formula language**:
-
-```typescript
-// Formulas can reference fields, perform calculations
-Field.formula({
- label: 'Calculated Total',
- returnType: 'number',
-
- // Supports: math, logic, dates, text, lookups
- expression: `
- IF(
- discount_code != NULL,
- subtotal * (1 - discount_percentage / 100),
- subtotal
- ) + shipping_cost
- `,
-})
-```
-
-### Available Formula Functions
-
-- **Math:** `SUM`, `AVG`, `MIN`, `MAX`, `ROUND`, `ABS`
-- **Logic:** `IF`, `AND`, `OR`, `NOT`, `ISNULL`
-- **Text:** `CONCAT`, `UPPER`, `LOWER`, `SUBSTRING`, `LEN`
-- **Date:** `TODAY`, `NOW`, `DATEADD`, `DATEDIFF`, `YEAR`, `MONTH`
-- **Lookup:** `LOOKUP`, `ROLLUP`
-
-## Testing Your Definitions
-
-ObjectStack schemas are **Zod schemas**:
-
-```typescript
-import { Task } from './objects/task';
-
-// Unit test example
-describe('Task Object', () => {
- it('should validate required fields', () => {
- const result = Task.safeParse({
- title: 'My Task',
- status: 'todo',
- });
-
- expect(result.success).toBe(true);
- });
-
- it('should reject invalid status', () => {
- const result = Task.safeParse({
- title: 'My Task',
- status: 'invalid_status', // Not in enum
- });
-
- expect(result.success).toBe(false);
- });
-});
-```
-
-## Next Steps for Backend Developers
-
-
-
-
-
-
-
-
-## Migration Guides
-
-Coming from another framework? We've got you covered:
-
-- [Prisma → ObjectStack](/docs/guides/migration/prisma)
-- [TypeORM → ObjectStack](/docs/guides/migration/typeorm)
-- [Sequelize → ObjectStack](/docs/guides/migration/sequelize)
-- [Mongoose → ObjectStack](/docs/guides/migration/mongoose)
diff --git a/content/docs/quick-start/build-first-app.mdx b/content/docs/quick-start/build-first-app.mdx
deleted file mode 100644
index e20a70577..000000000
--- a/content/docs/quick-start/build-first-app.mdx
+++ /dev/null
@@ -1,367 +0,0 @@
----
-title: Build Your First App
-description: Complete hands-on tutorial - Build a task management application in 10 minutes using ObjectStack Protocol.
----
-
-In this tutorial, you'll build a complete task management application with:
-- ✅ Task object with title, description, status, and assignee
-- ✅ Validation rules
-- ✅ Status workflow (Todo → In Progress → Done)
-- ✅ List and form views
-- ✅ Dashboard with statistics
-
-**Time to complete:** ~10 minutes
-**Prerequisites:** Node.js 18+, basic TypeScript knowledge
-
-## Step 1: Project Setup
-
-Create a new project and install dependencies:
-
-```bash
-mkdir task-manager
-cd task-manager
-npm init -y
-npm install typescript zod @objectstack/spec
-npx tsc --init
-```
-
-Create the directory structure:
-
-```bash
-mkdir -p src/{objects,views,workflows}
-```
-
-## Step 2: Define the Task Object
-
-Create `src/objects/task.object.ts`:
-
-```typescript
-import { ObjectSchema, Field } from '@objectstack/spec';
-
-export const Task = ObjectSchema.create({
- name: 'task',
- label: 'Task',
- pluralLabel: 'Tasks',
- icon: 'check-square',
- description: 'Track work items and their status',
-
- // This field will be used as the record name/title
- nameField: 'title',
-
- // Enable features
- enable: {
- trackHistory: true,
- apiEnabled: true,
- searchEnabled: true,
- },
-
- fields: {
- // Text field - the task title
- title: Field.text({
- label: 'Title',
- required: true,
- maxLength: 200,
- helpText: 'Brief description of the task',
- }),
-
- // Long text for detailed description
- description: Field.textarea({
- label: 'Description',
- maxLength: 5000,
- rows: 5,
- }),
-
- // Select field for status
- status: Field.select({
- label: 'Status',
- required: true,
- defaultValue: 'todo',
- options: [
- { value: 'todo', label: 'To Do', color: 'gray' },
- { value: 'in_progress', label: 'In Progress', color: 'blue' },
- { value: 'done', label: 'Done', color: 'green' },
- ],
- }),
-
- // Select field for priority
- priority: Field.select({
- label: 'Priority',
- defaultValue: 'medium',
- options: [
- { value: 'low', label: 'Low', color: 'gray' },
- { value: 'medium', label: 'Medium', color: 'yellow' },
- { value: 'high', label: 'High', color: 'red' },
- ],
- }),
-
- // Date field for due date
- due_date: Field.date({
- label: 'Due Date',
- }),
-
- // Lookup field for assignee (references user object)
- assignee: Field.lookup({
- label: 'Assignee',
- reference: 'user',
- displayField: 'full_name',
- }),
-
- // Boolean field for completed status
- completed: Field.boolean({
- label: 'Completed',
- defaultValue: false,
- }),
-
- // Formula field - calculates if task is overdue
- is_overdue: Field.formula({
- label: 'Is Overdue',
- returnType: 'boolean',
- expression: 'AND(NOT(completed), due_date < TODAY())',
- }),
- },
-});
-```
-
-## Step 3: Add Validation Rules
-
-Create `src/workflows/task-validation.ts`:
-
-```typescript
-import { ValidationRule } from '@objectstack/spec';
-
-export const taskValidations = [
- // Validation: Due date must be in the future for new tasks
- ValidationRule.create({
- name: 'future_due_date',
- object: 'task',
- active: true,
- errorMessage: 'Due date must be in the future',
- condition: 'AND(ISNEW(), due_date < TODAY())',
- }),
-
- // Validation: Completed tasks must have status = 'done'
- ValidationRule.create({
- name: 'completed_status_match',
- object: 'task',
- active: true,
- errorMessage: 'Completed tasks must have status "Done"',
- condition: 'AND(completed, status != "done")',
- }),
-];
-```
-
-## Step 4: Create a List View
-
-Create `src/views/task-list.view.ts`:
-
-```typescript
-import { ListView } from '@objectstack/spec';
-
-export const TaskListView = ListView.create({
- name: 'all_tasks',
- label: 'All Tasks',
- object: 'task',
-
- // Default view type
- viewType: 'grid',
-
- // Columns to display
- columns: [
- { field: 'title', width: 300 },
- { field: 'status', width: 150 },
- { field: 'priority', width: 120 },
- { field: 'assignee', width: 200 },
- { field: 'due_date', width: 150 },
- { field: 'is_overdue', width: 120 },
- ],
-
- // Default sorting
- sorting: [
- { field: 'due_date', direction: 'asc' },
- ],
-
- // Default filter
- filters: {
- completed: { eq: false },
- },
-
- // Enable features
- enableSearch: true,
- enableFilters: true,
- enableBulkActions: true,
-});
-```
-
-## Step 5: Create a Kanban View
-
-Create `src/views/task-kanban.view.ts`:
-
-```typescript
-import { ListView } from '@objectstack/spec';
-
-export const TaskKanbanView = ListView.create({
- name: 'task_kanban',
- label: 'Task Board',
- object: 'task',
-
- viewType: 'kanban',
-
- // Group by status field
- kanbanConfig: {
- groupByField: 'status',
- cardFields: ['title', 'priority', 'assignee', 'due_date'],
-
- // Define the columns
- columns: [
- { value: 'todo', label: 'To Do' },
- { value: 'in_progress', label: 'In Progress' },
- { value: 'done', label: 'Done' },
- ],
- },
-});
-```
-
-## Step 6: Create a Form View
-
-Create `src/views/task-form.view.ts`:
-
-```typescript
-import { FormView } from '@objectstack/spec';
-
-export const TaskFormView = FormView.create({
- name: 'task_edit',
- label: 'Task Details',
- object: 'task',
-
- // Form layout
- layout: {
- sections: [
- {
- label: 'Basic Information',
- columns: 2,
- fields: ['title', 'description'],
- },
- {
- label: 'Scheduling',
- columns: 2,
- fields: ['status', 'priority', 'due_date', 'assignee'],
- },
- {
- label: 'Completion',
- columns: 1,
- fields: ['completed', 'is_overdue'],
- },
- ],
- },
-
- // Read-only fields (formula fields are auto read-only)
- readOnlyFields: ['is_overdue'],
-});
-```
-
-## Step 7: Bundle Everything
-
-Create `src/index.ts`:
-
-```typescript
-import { Manifest } from '@objectstack/spec';
-import { Task } from './objects/task.object';
-import { taskValidations } from './workflows/task-validation';
-import { TaskListView, TaskKanbanView } from './views/task-list.view';
-import { TaskFormView } from './views/task-form.view';
-
-export const manifest = Manifest.create({
- name: 'task_manager',
- version: '1.0.0',
- label: 'Task Manager',
- description: 'Simple task management application',
-
- // Register all components
- objects: [Task],
- validations: taskValidations,
- views: {
- list: [TaskListView, TaskKanbanView],
- form: [TaskFormView],
- },
-});
-```
-
-## Step 8: Build and Validate
-
-Add to `package.json`:
-
-```json
-{
- "scripts": {
- "build": "tsc",
- "validate": "node -e \"require('./dist/index.js')\""
- }
-}
-```
-
-Build and validate:
-
-```bash
-npm run build
-npm run validate
-```
-
-✅ **Congratulations!** You've built your first ObjectStack application.
-
-## What You've Learned
-
-- ✅ How to define **Objects** with various field types
-- ✅ How to add **validation rules** with formulas
-- ✅ How to create **multiple view types** (Grid, Kanban, Form)
-- ✅ How to use **formula fields** for calculations
-- ✅ How to enable **platform features** (history tracking, search)
-
-## Next Steps
-
-
-
-
-
-
-
-
-## Troubleshooting
-
-### TypeScript Errors
-
-Make sure your `tsconfig.json` has:
-
-```json
-{
- "compilerOptions": {
- "strict": true,
- "esModuleInterop": true,
- "moduleResolution": "node"
- }
-}
-```
-
-### Schema Validation Errors
-
-All schemas are validated at build time using Zod. Check the error message for which field failed validation.
-
-## Full Code
-
-The complete source code for a similar example is available at:
-- [GitHub: examples/todo](https://github.com/objectstack-ai/spec/tree/main/examples/todo)
diff --git a/content/docs/quick-start/frontend-developers.mdx b/content/docs/quick-start/frontend-developers.mdx
deleted file mode 100644
index dfda9b739..000000000
--- a/content/docs/quick-start/frontend-developers.mdx
+++ /dev/null
@@ -1,554 +0,0 @@
----
-title: For Frontend Developers
-description: Learn ObjectStack from a frontend perspective - focus on UI configuration, server-driven UI, and component rendering.
----
-
-Welcome frontend developers! If you're used to building admin panels, dashboards, or data-heavy UIs, ObjectStack will feel like a productivity superpower.
-
-## Core Concept
-
-ObjectStack uses **Server-Driven UI (SDUI)** - instead of hardcoding components, you define UI as JSON configurations that the renderer interprets.
-
-```
-Traditional: Code React components → Build → Deploy
-ObjectStack: Define UI JSON → Instant Update (no rebuild!)
-```
-
-## Quick Comparison
-
-### Traditional React
-
-```tsx
-// 1. Build data grid component
-import { DataGrid } from '@mui/x-data-grid';
-
-function TaskList() {
- const [tasks, setTasks] = useState([]);
-
- useEffect(() => {
- fetch('/api/tasks').then(r => r.json()).then(setTasks);
- }, []);
-
- return (
-
- );
-}
-
-// 2. Build form component
-function TaskForm({ taskId }) {
- const [task, setTask] = useState({});
-
- const handleSubmit = async (e) => {
- e.preventDefault();
- await fetch(`/api/tasks/${taskId}`, {
- method: 'PATCH',
- body: JSON.stringify(task),
- });
- };
-
- return (
-
- );
-}
-
-// Total: 2 components, ~100 lines of code
-```
-
-### ObjectStack Protocol
-
-```typescript
-// Define UI as JSON - Renderer handles everything
-export const TaskListView = ListView.create({
- name: 'all_tasks',
- label: 'All Tasks',
- object: 'task',
-
- viewType: 'grid',
- columns: [
- { field: 'title', width: 200 },
- { field: 'status', width: 150 },
- { field: 'due_date', width: 150 },
- ],
- pageSize: 25,
-});
-
-export const TaskFormView = FormView.create({
- name: 'task_edit',
- label: 'Edit Task',
- object: 'task',
-
- layout: {
- sections: [
- {
- label: 'Details',
- fields: ['title', 'status', 'due_date'],
- },
- ],
- },
-});
-
-// Total: 2 definitions, ~20 lines
-// ✅ Data fetching handled automatically
-// ✅ State management handled automatically
-// ✅ Validation handled automatically
-// ✅ Loading/Error states handled automatically
-```
-
-## View Types
-
-ObjectStack provides **5 pre-built view types**:
-
-### 1. Grid View (Data Table)
-
-```typescript
-const TaskGrid = ListView.create({
- name: 'task_grid',
- object: 'task',
- viewType: 'grid',
-
- columns: [
- { field: 'title', width: 300, sortable: true },
- { field: 'status', width: 120, filterable: true },
- { field: 'assignee', width: 200 },
- ],
-
- // Features
- enableSearch: true,
- enableFilters: true,
- enableExport: true,
- enableBulkActions: true,
-
- // Default state
- defaultSort: [{ field: 'created_at', direction: 'desc' }],
- pageSize: 50,
-});
-```
-
-**Rendered Output:**
-- Sortable columns
-- Filterable columns
-- Search bar
-- Pagination
-- Bulk select + actions
-- Export to CSV/Excel
-
-### 2. Kanban View (Board)
-
-```typescript
-const TaskKanban = ListView.create({
- name: 'task_board',
- object: 'task',
- viewType: 'kanban',
-
- kanbanConfig: {
- groupByField: 'status',
-
- columns: [
- { value: 'todo', label: 'To Do', color: 'gray' },
- { value: 'in_progress', label: 'In Progress', color: 'blue' },
- { value: 'done', label: 'Done', color: 'green' },
- ],
-
- cardFields: ['title', 'assignee', 'due_date'],
-
- // Drag & drop enabled by default
- enableDragDrop: true,
- },
-});
-```
-
-**Rendered Output:**
-- Drag & drop cards between columns
-- Visual grouping
-- Card customization
-- Swimlanes (optional)
-
-### 3. Calendar View
-
-```typescript
-const TaskCalendar = ListView.create({
- name: 'task_calendar',
- object: 'task',
- viewType: 'calendar',
-
- calendarConfig: {
- dateField: 'due_date',
- titleField: 'title',
-
- // Color-code events
- colorField: 'priority',
- colorMapping: {
- high: 'red',
- medium: 'yellow',
- low: 'gray',
- },
-
- // Views: day, week, month
- defaultView: 'month',
- },
-});
-```
-
-### 4. Gantt View (Timeline)
-
-```typescript
-const ProjectGantt = ListView.create({
- name: 'project_timeline',
- object: 'task',
- viewType: 'gantt',
-
- ganttConfig: {
- startDateField: 'start_date',
- endDateField: 'end_date',
- progressField: 'completion_percentage',
-
- // Dependencies
- dependenciesField: 'blocked_by',
-
- // Grouping
- groupByField: 'project',
- },
-});
-```
-
-### 5. Form View
-
-```typescript
-const TaskForm = FormView.create({
- name: 'task_form',
- object: 'task',
-
- layout: {
- sections: [
- {
- label: 'Basic Info',
- columns: 2, // 2-column layout
- fields: ['title', 'description'],
- },
- {
- label: 'Assignment',
- columns: 2,
- fields: ['assignee', 'status', 'priority', 'due_date'],
- },
- {
- label: 'Advanced',
- collapsible: true, // Expandable section
- fields: ['tags', 'metadata'],
- },
- ],
- },
-
- // Conditional visibility
- fieldVisibility: {
- assignee: "status != 'todo'", // Show only when not todo
- },
-
- // Read-only fields
- readOnlyFields: ['created_by', 'created_at'],
-});
-```
-
-## Dashboard & Analytics
-
-Build dashboards with widgets:
-
-```typescript
-import { Dashboard, Widget } from '@objectstack/spec';
-
-export const TaskDashboard = Dashboard.create({
- name: 'task_overview',
- label: 'Task Overview',
-
- // Grid layout (12 columns)
- layout: {
- rows: [
- {
- widgets: [
- // KPI Card - 3 columns wide
- Widget.metric({
- id: 'total_tasks',
- title: 'Total Tasks',
- object: 'task',
- aggregation: 'count',
- width: 3,
- }),
-
- // KPI Card with trend
- Widget.metric({
- id: 'completed_tasks',
- title: 'Completed This Month',
- object: 'task',
- aggregation: 'count',
- filters: {
- status: { eq: 'done' },
- completed_at: { gte: 'START_OF_MONTH()' },
- },
- width: 3,
- showTrend: true,
- }),
- ],
- },
- {
- widgets: [
- // Chart - 6 columns
- Widget.chart({
- id: 'tasks_by_status',
- title: 'Tasks by Status',
- chartType: 'pie',
- object: 'task',
- groupBy: 'status',
- aggregation: 'count',
- width: 6,
- }),
-
- // Chart - 6 columns
- Widget.chart({
- id: 'tasks_over_time',
- title: 'Tasks Created Over Time',
- chartType: 'line',
- object: 'task',
- xAxis: { field: 'created_at', interval: 'day' },
- yAxis: { aggregation: 'count' },
- width: 6,
- }),
- ],
- },
- {
- widgets: [
- // Embedded list view - full width
- Widget.listView({
- id: 'recent_tasks',
- title: 'Recent Tasks',
- view: 'all_tasks',
- limit: 10,
- width: 12,
- }),
- ],
- },
- ],
- },
-});
-```
-
-## Actions & Interactions
-
-Add buttons and actions to your views:
-
-```typescript
-import { Action } from '@objectstack/spec';
-
-// Custom button in list view
-const exportAction = Action.url({
- name: 'export_csv',
- label: 'Export to CSV',
- url: '/api/export/task?format=csv',
- icon: 'download',
-
- // Show in toolbar
- displayLocation: 'toolbar',
-});
-
-// Quick action button
-const approveAction = Action.update({
- name: 'approve_task',
- label: 'Approve',
- icon: 'check',
-
- // Update fields
- updates: {
- status: 'approved',
- approved_by: '{$User.Id}',
- approved_at: '{$Now}',
- },
-
- // Confirmation dialog
- confirmation: {
- title: 'Approve Task?',
- message: 'Are you sure you want to approve this task?',
- },
-});
-
-// Launch a flow/modal
-const assignAction = Action.flow({
- name: 'assign_task',
- label: 'Assign to Me',
- flowName: 'assign_task_flow',
-
- // Pass context
- parameters: {
- taskId: '{recordId}',
- userId: '{$User.Id}',
- },
-});
-```
-
-## Theming & Styling
-
-Customize the look and feel:
-
-```typescript
-import { Theme, ColorPalette } from '@objectstack/spec';
-
-export const customTheme = Theme.create({
- colors: {
- primary: '#3B82F6',
- secondary: '#8B5CF6',
- success: '#10B981',
- warning: '#F59E0B',
- error: '#EF4444',
- },
-
- typography: {
- fontFamily: 'Inter, sans-serif',
- fontSize: {
- xs: '12px',
- sm: '14px',
- base: '16px',
- lg: '18px',
- xl: '20px',
- },
- },
-
- spacing: {
- unit: 8, // 8px base unit
- },
-
- borderRadius: {
- sm: '4px',
- md: '8px',
- lg: '12px',
- },
-});
-```
-
-## App Navigation
-
-Define your app's navigation structure:
-
-```typescript
-import { App, NavigationItem } from '@objectstack/spec';
-
-export const myApp = App.create({
- name: 'task_manager',
- label: 'Task Manager',
-
- branding: {
- logo: '/logo.svg',
- primaryColor: '#3B82F6',
- },
-
- navigation: [
- // Dashboard link
- NavigationItem.dashboard({
- label: 'Home',
- icon: 'home',
- dashboard: 'task_overview',
- }),
-
- // Object link (auto-generates CRUD pages)
- NavigationItem.object({
- label: 'Tasks',
- icon: 'check-square',
- object: 'task',
- defaultView: 'all_tasks',
- }),
-
- // Navigation group
- NavigationItem.group({
- label: 'Reports',
- icon: 'bar-chart',
- items: [
- NavigationItem.page({
- label: 'Task Analytics',
- page: 'task_analytics',
- }),
- ],
- }),
-
- // External URL
- NavigationItem.url({
- label: 'Help',
- icon: 'help-circle',
- url: 'https://docs.objectstack.dev',
- openInNewTab: true,
- }),
- ],
-});
-```
-
-## Rendering the UI
-
-Your renderer consumes the UI definitions:
-
-```tsx
-// Example: React Renderer (conceptual)
-import { ObjectStackRenderer } from '@objectstack/react-renderer';
-import { TaskListView, TaskFormView } from './views';
-
-function App() {
- return (
-
- );
-}
-```
-
-## Benefits for Frontend Developers
-
-✅ **No Boilerplate:** No more `useState`, `useEffect`, form handlers
-✅ **Type-Safe:** Full TypeScript support
-✅ **Instant Updates:** Change UI JSON, see results without rebuilding
-✅ **Consistent UX:** All views follow the same design system
-✅ **Responsive:** Mobile-first, works on all screen sizes
-✅ **Accessible:** WCAG 2.1 AA compliant out of the box
-
-## Next Steps for Frontend Developers
-
-
-
-
-
-
-
diff --git a/content/docs/quick-start/meta.cn.json b/content/docs/quick-start/meta.cn.json
deleted file mode 100644
index 421e76a99..000000000
--- a/content/docs/quick-start/meta.cn.json
+++ /dev/null
@@ -1,10 +0,0 @@
-{
- "title": "快速开始",
- "root": true,
- "pages": [
- "build-first-app",
- "backend-developers",
- "frontend-developers",
- "architects"
- ]
-}
diff --git a/content/docs/quick-start/meta.json b/content/docs/quick-start/meta.json
deleted file mode 100644
index 50b528f4b..000000000
--- a/content/docs/quick-start/meta.json
+++ /dev/null
@@ -1,10 +0,0 @@
-{
- "title": "Quick Start",
- "root": true,
- "pages": [
- "build-first-app",
- "backend-developers",
- "frontend-developers",
- "architects"
- ]
-}
diff --git a/content/docs/standards/api-design.mdx b/content/docs/standards/api-design.mdx
deleted file mode 100644
index 0a0882e26..000000000
--- a/content/docs/standards/api-design.mdx
+++ /dev/null
@@ -1,325 +0,0 @@
----
-title: API Design Principles
-description: Guidelines for designing consistent and developer-friendly APIs in ObjectStack
----
-
-# API Design Principles
-
-> Guidelines for designing consistent and developer-friendly APIs in ObjectStack
-
-## Core Principles
-
-### 1. Protocol-First Design
-
-All APIs must be defined as **Zod schemas** before implementation:
-
-```typescript
-// ✅ Correct - Define schema first
-export const CreateRecordRequestSchema = z.object({
- objectName: z.string(),
- data: z.record(z.any()),
- options: z.object({
- returnFields: z.array(z.string()).optional(),
- validateOnly: z.boolean().default(false),
- }).optional(),
-});
-
-export type CreateRecordRequest = z.infer;
-```
-
-### 2. Consistent Response Envelopes
-
-All API responses use standardized envelope schemas from `@objectstack/spec/api`:
-
-```typescript
-import { BaseResponseSchema, SingleRecordResponseSchema } from '@objectstack/spec';
-
-// Success response
-{
- success: true,
- data: { /* record data */ },
- metadata: { /* optional metadata */ }
-}
-
-// Error response
-{
- success: false,
- error: {
- code: 'VALIDATION_ERROR',
- message: 'Field "email" is required',
- details: { /* error details */ }
- }
-}
-```
-
-### 3. Resource-Oriented Design
-
-Follow RESTful resource conventions:
-
-```
-GET /api/v1/objects/{object}/records # List records
-GET /api/v1/objects/{object}/records/{id} # Get single record
-POST /api/v1/objects/{object}/records # Create record
-PATCH /api/v1/objects/{object}/records/{id} # Update record
-DELETE /api/v1/objects/{object}/records/{id} # Delete record
-```
-
-### 4. Versioning
-
-Use URL path versioning:
-
-```
-/api/v1/... # Current stable version
-/api/v2/... # Next version (if needed)
-```
-
-## Request Design
-
-### Query Parameters
-
-Use `camelCase` for query parameters:
-
-```typescript
-GET /api/v1/objects/account/records?
- fields=name,email&
- filter=status:active&
- orderBy=created_date&
- limit=25&
- offset=0
-```
-
-### Request Body
-
-Use `camelCase` for JSON properties:
-
-```typescript
-POST /api/v1/objects/account/records
-
-{
- "data": {
- "account_name": "Acme Corp", // Field name - snake_case
- "annual_revenue": 1000000 // Field name - snake_case
- },
- "options": {
- "returnFields": ["id", "name"], // Config - camelCase
- "validateOnly": false // Config - camelCase
- }
-}
-```
-
-## Response Design
-
-### Success Response Structure
-
-```typescript
-{
- "success": true,
- "data": { /* primary response data */ },
- "metadata": {
- "timestamp": "2026-01-22T10:00:00Z",
- "requestId": "req_abc123",
- "duration": 45 // milliseconds
- }
-}
-```
-
-### Error Response Structure
-
-```typescript
-{
- "success": false,
- "error": {
- "code": "ERROR_CODE",
- "message": "Human-readable error message",
- "details": {
- "field": "email",
- "reason": "invalid_format"
- }
- },
- "metadata": {
- "timestamp": "2026-01-22T10:00:00Z",
- "requestId": "req_abc123"
- }
-}
-```
-
-### Error Codes
-
-Use consistent error code patterns:
-
-- `VALIDATION_ERROR` - Input validation failed
-- `NOT_FOUND` - Resource not found
-- `UNAUTHORIZED` - Authentication required
-- `FORBIDDEN` - Insufficient permissions
-- `CONFLICT` - Resource conflict (e.g., duplicate)
-- `INTERNAL_ERROR` - Server error
-
-## Pagination
-
-### Offset-Based Pagination
-
-```typescript
-GET /api/v1/objects/account/records?limit=25&offset=0
-
-{
- "success": true,
- "data": [/* records */],
- "pagination": {
- "total": 150,
- "limit": 25,
- "offset": 0,
- "hasMore": true
- }
-}
-```
-
-### Cursor-Based Pagination
-
-```typescript
-GET /api/v1/objects/account/records?limit=25&cursor=abc123
-
-{
- "success": true,
- "data": [/* records */],
- "pagination": {
- "limit": 25,
- "nextCursor": "def456",
- "hasMore": true
- }
-}
-```
-
-## Filtering and Sorting
-
-### Filter Syntax
-
-Use structured filter objects:
-
-```typescript
-GET /api/v1/objects/account/records?filter={"status":"active","revenue_gt":100000}
-
-// Or use query string operators:
-GET /api/v1/objects/account/records?status=active&revenue_gt=100000
-```
-
-### Sort Syntax
-
-```typescript
-GET /api/v1/objects/account/records?orderBy=created_date:desc,name:asc
-```
-
-## Best Practices
-
-### 1. Use Proper HTTP Methods
-
-- `GET` - Read operations (safe, idempotent)
-- `POST` - Create operations
-- `PUT` - Full update (replace)
-- `PATCH` - Partial update
-- `DELETE` - Delete operations
-
-### 2. Return Appropriate Status Codes
-
-- `200 OK` - Successful GET, PATCH, DELETE
-- `201 Created` - Successful POST
-- `400 Bad Request` - Invalid input
-- `401 Unauthorized` - Authentication required
-- `403 Forbidden` - Insufficient permissions
-- `404 Not Found` - Resource not found
-- `409 Conflict` - Resource conflict
-- `500 Internal Server Error` - Server error
-
-### 3. Support Partial Responses
-
-Allow clients to request specific fields:
-
-```typescript
-GET /api/v1/objects/account/records?fields=id,name,email
-```
-
-### 4. Provide Metadata
-
-Include helpful metadata in responses:
-
-```typescript
-{
- "success": true,
- "data": { /* data */ },
- "metadata": {
- "timestamp": "2026-01-22T10:00:00Z",
- "requestId": "req_abc123",
- "duration": 45,
- "version": "1.0"
- }
-}
-```
-
-## Examples
-
-### Create Record
-
-```typescript
-POST /api/v1/objects/customer_account/records
-
-Request:
-{
- "data": {
- "account_name": "Acme Corp",
- "annual_revenue": 1000000,
- "industry": "technology"
- },
- "options": {
- "returnFields": ["id", "account_name", "created_date"],
- "validateOnly": false
- }
-}
-
-Response (201 Created):
-{
- "success": true,
- "data": {
- "id": "acc_123",
- "account_name": "Acme Corp",
- "created_date": "2026-01-22T10:00:00Z"
- },
- "metadata": {
- "timestamp": "2026-01-22T10:00:00Z",
- "requestId": "req_abc123"
- }
-}
-```
-
-### Query Records
-
-```typescript
-GET /api/v1/objects/customer_account/records?
- fields=id,account_name,annual_revenue&
- filter={"industry":"technology","revenue_gt":500000}&
- orderBy=annual_revenue:desc&
- limit=10
-
-Response (200 OK):
-{
- "success": true,
- "data": [
- {
- "id": "acc_123",
- "account_name": "Acme Corp",
- "annual_revenue": 1000000
- }
- // ... more records
- ],
- "pagination": {
- "total": 45,
- "limit": 10,
- "offset": 0,
- "hasMore": true
- }
-}
-```
-
-## Related
-
-- [Naming Conventions](/docs/standards/naming-conventions.md)
-- [Error Handling](/docs/standards/error-handling.md)
-- [REST API Specification](/docs/specifications/server/rest-api.mdx)
diff --git a/content/docs/standards/authentication.mdx b/content/docs/standards/authentication.mdx
deleted file mode 100644
index 18f707e36..000000000
--- a/content/docs/standards/authentication.mdx
+++ /dev/null
@@ -1,611 +0,0 @@
----
-title: Authentication Standard
-description: The standard authentication protocol specification for the ObjectStack ecosystem
----
-
-# ObjectStack Authentication Standard
-
-The standard authentication protocol specification for the ObjectStack ecosystem.
-
-## Overview
-
-This document defines the **ObjectStack Authentication Standard**, a comprehensive, framework-agnostic authentication protocol for ObjectStack applications. This standard supports multiple authentication strategies, session management, and comprehensive security features.
-
-The specification is designed as an **interface** that can be implemented by any authentication library. **better-auth** serves as the **Reference Implementation** (default driver) for this standard.
-
-### Implementation Drivers
-
-The authentication standard can be implemented using various drivers:
-- **better-auth** (default/reference implementation)
-- Auth.js
-- Passport
-- Custom implementations
-
-## Features
-
-### Authentication Strategies
-
-- **Email/Password**: Traditional email and password authentication with customizable password policies
-- **Magic Link**: Passwordless email-based authentication
-- **OAuth**: Social login with popular providers (Google, GitHub, Facebook, Twitter, LinkedIn, Microsoft, Apple, Discord, GitLab)
-- **Passkey**: WebAuthn/FIDO2 biometric authentication
-- **OTP**: One-time password authentication (SMS, Email)
-- **Anonymous**: Guest/anonymous session support
-- **Enterprise SSO**: SAML 2.0, LDAP/Active Directory, and OIDC for enterprise single sign-on
-
-### Security Features
-
-- **Rate Limiting**: Configurable rate limiting to prevent brute-force attacks
-- **CSRF Protection**: Built-in CSRF token validation
-- **Session Fingerprinting**: Enhanced session security with device fingerprinting
-- **Two-Factor Authentication (2FA)**: TOTP-based 2FA with backup codes
-- **Account Linking**: Link multiple authentication methods to a single user account
-- **IP-based Rate Limiting**: Prevent attacks from specific IP addresses
-
-### Session Management
-
-- Customizable session expiry and renewal
-- Secure cookie configuration (HttpOnly, Secure, SameSite)
-- Maximum concurrent sessions per user
-- Session update intervals
-
-### Developer Features
-
-- **Lifecycle Hooks**: `beforeSignIn`, `afterSignIn`, `beforeSignUp`, `afterSignUp`, `beforeSignOut`, `afterSignOut`
-- **Database Adapters**: Support for Prisma, Drizzle, Kysely, and custom adapters
-- **Email Providers**: Integration with SendGrid, Mailgun, AWS SES, Resend, SMTP
-- **Field Mapping**: Map better-auth user fields to your custom user object
-- **Plugin System**: Extend better-auth with custom plugins
-
-## Installation
-
-```bash
-pnpm add @objectstack/plugin-better-auth
-```
-
-## Usage
-
-### Basic Example
-
-```typescript
-import type { AuthConfig } from '@objectstack/spec';
-
-const authConfig: AuthConfig = {
- name: 'main_auth',
- label: 'Main Authentication',
- driver: 'better-auth', // Optional, defaults to 'better-auth'
- strategies: ['email_password'],
- baseUrl: 'https://app.example.com',
- secret: process.env.AUTH_SECRET!,
-
- emailPassword: {
- enabled: true,
- requireEmailVerification: true,
- minPasswordLength: 8,
- },
-
- session: {},
- rateLimit: {},
- csrf: {},
- accountLinking: {},
-};
-```
-
-### OAuth Example
-
-```typescript
-const oauthConfig: AuthConfig = {
- name: 'social_auth',
- label: 'Social Login',
- strategies: ['oauth'],
- baseUrl: 'https://app.example.com',
- secret: process.env.AUTH_SECRET!,
-
- oauth: {
- providers: [
- {
- provider: 'google',
- clientId: process.env.GOOGLE_CLIENT_ID!,
- clientSecret: process.env.GOOGLE_CLIENT_SECRET!,
- scopes: ['openid', 'profile', 'email'],
- },
- ],
- },
-
- session: {},
- rateLimit: {},
- csrf: {},
- accountLinking: {},
-};
-```
-
-### Multi-Strategy Example
-
-```typescript
-const multiAuthConfig: AuthConfig = {
- name: 'multi_auth',
- label: 'Multi-Strategy Auth',
- strategies: ['email_password', 'oauth', 'magic_link'],
- baseUrl: 'https://app.example.com',
- secret: process.env.AUTH_SECRET!,
-
- emailPassword: {
- enabled: true,
- minPasswordLength: 10,
- },
-
- oauth: {
- providers: [
- { provider: 'google', clientId: '...', clientSecret: '...' },
- { provider: 'github', clientId: '...', clientSecret: '...' },
- ],
- },
-
- magicLink: {
- enabled: true,
- expiryTime: 900,
- },
-
- session: {
- expiresIn: 604800, // 7 days
- },
-
- rateLimit: {
- enabled: true,
- maxAttempts: 5,
- },
-
- csrf: {
- enabled: true,
- },
-
- accountLinking: {
- enabled: true,
- autoLink: false,
- },
-};
-```
-
-### Enterprise SSO Example
-
-```typescript
-const enterpriseAuthConfig: AuthConfig = {
- name: 'enterprise_sso',
- label: 'Enterprise SSO',
- strategies: ['oauth'],
- baseUrl: 'https://app.example.com',
- secret: process.env.AUTH_SECRET!,
-
- // Standard OAuth for consumer providers
- oauth: {
- providers: [
- { provider: 'google', clientId: '...', clientSecret: '...' },
- ],
- },
-
- // Enterprise authentication methods
- enterprise: {
- // OIDC (Modern standard for enterprise SSO)
- oidc: {
- enabled: true,
- issuer: 'https://auth.company.com',
- clientId: process.env.OIDC_CLIENT_ID!,
- clientSecret: process.env.OIDC_CLIENT_SECRET!,
- scopes: ['openid', 'profile', 'email', 'groups'],
- attributeMapping: {
- email: 'email',
- name: 'name',
- groups: 'roles',
- },
- displayName: 'Login with Corporate SSO',
- },
-
- // SAML 2.0 (Legacy enterprise SSO)
- saml: {
- enabled: true,
- entryPoint: 'https://idp.company.com/saml/sso',
- cert: process.env.SAML_CERT!,
- issuer: 'https://idp.company.com',
- signatureAlgorithm: 'sha256',
- attributeMapping: {
- email: 'http://schemas.xmlsoap.org/ws/2005/05/identity/claims/emailaddress',
- name: 'http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name',
- },
- displayName: 'Login with SAML',
- },
-
- // LDAP/Active Directory (On-premise)
- ldap: {
- enabled: true,
- url: 'ldaps://ldap.company.com:636',
- bindDn: 'CN=Service Account,OU=Users,DC=company,DC=com',
- bindCredentials: process.env.LDAP_PASSWORD!,
- searchBase: 'OU=Users,DC=company,DC=com',
- searchFilter: '(&(objectClass=user)(sAMAccountName={{username}}))',
- groupSearchBase: 'OU=Groups,DC=company,DC=com',
- displayName: 'Login with Active Directory',
- },
- },
-
- session: {
- expiresIn: 28800, // 8 hours for enterprise
- },
-
- rateLimit: {
- enabled: true,
- maxAttempts: 5,
- },
-
- csrf: {
- enabled: true,
- },
-};
-```
-
-## Configuration Reference
-
-### Core Configuration
-
-| Property | Type | Required | Description |
-|----------|------|----------|-------------|
-| `name` | `string` | ✅ | Configuration identifier (snake_case) |
-| `label` | `string` | ✅ | Human-readable label |
-| `strategies` | `AuthStrategy[]` | ✅ | Enabled authentication strategies |
-| `baseUrl` | `string` | ✅ | Application base URL |
-| `secret` | `string` | ✅ | Secret key for signing (min 32 chars) |
-
-### Strategy Configuration
-
-#### Email/Password
-
-```typescript
-emailPassword: {
- enabled: boolean; // Enable email/password auth
- requireEmailVerification: boolean; // Require email verification
- minPasswordLength: number; // Minimum password length (6-128)
- requirePasswordComplexity: boolean; // Require uppercase, lowercase, numbers, symbols
- allowPasswordReset: boolean; // Enable password reset
- passwordResetExpiry: number; // Reset token expiry in seconds
-}
-```
-
-#### Magic Link
-
-```typescript
-magicLink: {
- enabled: boolean; // Enable magic link auth
- expiryTime: number; // Link expiry in seconds (default: 900)
- sendEmail?: Function; // Custom email sending function
-}
-```
-
-#### Passkey (WebAuthn)
-
-```typescript
-passkey: {
- enabled: boolean; // Enable passkey auth
- rpName: string; // Relying Party name
- rpId?: string; // Relying Party ID (defaults to domain)
- allowedOrigins?: string[]; // Allowed origins
- userVerification?: 'required' | 'preferred' | 'discouraged';
- attestation?: 'none' | 'indirect' | 'direct' | 'enterprise';
-}
-```
-
-#### OAuth
-
-```typescript
-oauth: {
- providers: [{
- provider: 'google' | 'github' | 'facebook' | ...; // OAuth provider
- clientId: string; // OAuth client ID
- clientSecret: string; // OAuth client secret
- scopes?: string[]; // Requested scopes
- redirectUri?: string; // Callback URL
- enabled?: boolean; // Enable/disable provider
- displayName?: string; // Button label
- icon?: string; // Icon URL
- }]
-}
-```
-
-### Session Configuration
-
-```typescript
-session: {
- expiresIn: number; // Session expiry in seconds (default: 604800)
- updateAge: number; // Update interval in seconds (default: 86400)
- cookieName: string; // Cookie name
- cookieSecure: boolean; // Use secure cookies (HTTPS only)
- cookieSameSite: 'strict' | 'lax' | 'none'; // SameSite attribute
- cookieDomain?: string; // Cookie domain
- cookiePath: string; // Cookie path (default: '/')
- cookieHttpOnly: boolean; // HttpOnly attribute
-}
-```
-
-### Security Configuration
-
-```typescript
-rateLimit: {
- enabled: boolean; // Enable rate limiting
- maxAttempts: number; // Max login attempts (default: 5)
- windowMs: number; // Time window in ms (default: 900000)
- blockDuration: number; // Block duration in ms
- skipSuccessfulRequests: boolean; // Only count failed requests
-}
-
-csrf: {
- enabled: boolean; // Enable CSRF protection
- tokenLength: number; // CSRF token length (default: 32)
- cookieName: string; // CSRF cookie name
- headerName: string; // CSRF header name
-}
-
-security: {
- allowedOrigins?: string[]; // CORS allowed origins
- trustProxy: boolean; // Trust proxy headers
- ipRateLimiting: boolean; // Enable IP-based rate limiting
- sessionFingerprinting: boolean; // Enable session fingerprinting
- maxSessions: number; // Max concurrent sessions (default: 5)
-}
-```
-
-### Two-Factor Authentication
-
-```typescript
-twoFactor: {
- enabled: boolean; // Enable 2FA
- issuer?: string; // TOTP issuer name
- qrCodeSize: number; // QR code size in pixels (default: 200)
- backupCodes?: {
- enabled: boolean; // Enable backup codes
- count: number; // Number of backup codes (default: 10)
- }
-}
-```
-
-### Enterprise Authentication
-
-```typescript
-enterprise: {
- // OpenID Connect (Modern enterprise SSO)
- oidc?: {
- enabled: boolean; // Enable OIDC
- issuer: string; // OIDC Issuer URL
- clientId: string; // OIDC client ID
- clientSecret: string; // OIDC client secret
- scopes?: string[]; // OIDC scopes (default: ['openid', 'profile', 'email'])
- attributeMapping?: Record; // Map IdP claims to user fields
- displayName?: string; // Button label
- icon?: string; // Icon URL
- },
-
- // SAML 2.0 (Legacy enterprise SSO)
- saml?: {
- enabled: boolean; // Enable SAML
- entryPoint: string; // IdP SSO URL
- cert: string; // IdP Public Certificate (PEM)
- issuer: string; // Entity ID of the IdP
- signatureAlgorithm?: 'sha256' | 'sha512'; // Signature algorithm
- attributeMapping?: Record; // Map SAML attributes to user fields
- displayName?: string; // Button label
- icon?: string; // Icon URL
- },
-
- // LDAP/Active Directory (On-premise)
- ldap?: {
- enabled: boolean; // Enable LDAP
- url: string; // LDAP Server URL (ldap:// or ldaps://)
- bindDn: string; // Bind DN
- bindCredentials: string; // Bind credentials
- searchBase: string; // Search base DN
- searchFilter: string; // Search filter
- groupSearchBase?: string; // Group search base DN
- displayName?: string; // Button label
- icon?: string; // Icon URL
- }
-}
-```
-
-### Lifecycle Hooks
-
-```typescript
-hooks: {
- beforeSignIn?: ({ email }) => Promise;
- afterSignIn?: ({ user, session }) => Promise;
- beforeSignUp?: ({ email, name? }) => Promise;
- afterSignUp?: ({ user }) => Promise;
- beforeSignOut?: ({ sessionId }) => Promise;
- afterSignOut?: ({ sessionId }) => Promise;
-}
-```
-
-### Database Field Mapping
-
-The `mapping` configuration allows you to map ObjectStack standard field names (which follow Auth.js conventions) to driver-specific field names. This is particularly useful for ensuring compatibility with authentication libraries like `better-auth` that use different column naming conventions.
-
-```typescript
-mapping: {
- // User model field mapping (optional)
- user?: {
- emailVerified: 'email_verified', // Map to snake_case
- createdAt: 'created_at',
- updatedAt: 'updated_at',
- },
-
- // Session model field mapping (default better-auth compatible)
- session: {
- sessionToken: 'token', // better-auth uses 'token'
- expires: 'expiresAt', // better-auth uses 'expiresAt'
- },
-
- // Account model field mapping (default better-auth compatible)
- account: {
- providerAccountId: 'accountId', // better-auth uses 'accountId'
- provider: 'providerId', // better-auth uses 'providerId'
- },
-
- // Verification token field mapping (optional)
- verificationToken?: {
- identifier: 'email',
- },
-}
-```
-
-**Default Mappings for better-auth Compatibility:**
-
-By default, the `session` and `account` mappings are pre-configured for `better-auth` compatibility:
-
-| ObjectStack Field | better-auth Field |
-|------------------|------------------|
-| `sessionToken` | `token` |
-| `expires` | `expiresAt` |
-| `providerAccountId` | `accountId` |
-| `provider` | `providerId` |
-
-You only need to specify the `mapping` configuration if you want to:
-- Use a different authentication driver with non-standard field names
-- Override the default better-auth mappings
-- Add custom mappings for user or verification token fields
-
-**Example with custom mappings:**
-
-```typescript
-const authConfig: AuthConfig = {
- name: 'custom_auth',
- label: 'Custom Auth',
- driver: 'custom-driver',
- strategies: ['email_password'],
- baseUrl: 'https://example.com',
- secret: process.env.AUTH_SECRET!,
-
- mapping: {
- user: {
- emailVerified: 'is_verified',
- createdAt: 'created',
- updatedAt: 'modified',
- },
- session: {
- sessionToken: 'session_id',
- expires: 'expires_at',
- },
- account: {
- providerAccountId: 'external_id',
- provider: 'auth_provider',
- },
- },
-
- session: {},
- rateLimit: {},
- csrf: {},
- accountLinking: {},
-};
-```
-
-## Supported OAuth Providers
-
-- Google (`google`)
-- GitHub (`github`)
-- Facebook (`facebook`)
-- Twitter (`twitter`)
-- LinkedIn (`linkedin`)
-- Microsoft (`microsoft`)
-- Apple (`apple`)
-- Discord (`discord`)
-- GitLab (`gitlab`)
-- Custom OAuth2 (`custom`)
-
-## Database Adapters
-
-- Prisma (`prisma`)
-- Drizzle (`drizzle`)
-- Kysely (`kysely`)
-- Custom (`custom`)
-
-## Email Providers
-
-- SMTP (`smtp`)
-- SendGrid (`sendgrid`)
-- Mailgun (`mailgun`)
-- AWS SES (`ses`)
-- Resend (`resend`)
-- Custom (`custom`)
-
-## Examples
-
-See [examples/auth-better-examples.ts](/docs/examples/auth-better-examples.ts) for comprehensive usage examples including:
-
-- Basic email/password authentication
-- OAuth with Google and GitHub
-- Multi-strategy authentication
-- Production-ready configuration
-- Plugin manifest integration
-
-## Schema Files
-
-The authentication system is organized into three main files:
-
-1. **Configuration** (`packages/spec/src/system/auth.zod.ts`): Defines **how to login** - OAuth, Email, SAML, LDAP, better-auth driver settings
-2. **Data Models** (`packages/spec/src/system/identity.zod.ts`): Defines **who is logged in** - User, Session, Account schemas
-3. **Wire Protocol** (`packages/spec/src/system/auth-protocol.ts`): Defines **how to communicate** - API constants, headers, error codes
-
-Additional files:
-- **Tests**: `packages/spec/src/system/auth.test.ts`
-- **JSON Schema**: `packages/spec/json-schema/AuthConfig.json`
-- **Documentation**: `content/docs/references/system/AuthConfig.mdx`
-
-## Type Safety
-
-All schemas are defined using Zod and TypeScript types are inferred automatically:
-
-```typescript
-// Authentication configuration types
-import type {
- AuthConfig,
- StandardAuthProvider,
- AuthStrategy,
- OAuthProvider,
- SessionConfig,
- EnterpriseAuthConfig,
- OIDCConfig,
- SAMLConfig,
- LDAPConfig,
- // ... and more
-} from '@objectstack/spec';
-
-// User and session data model types
-import type {
- User,
- Account,
- Session,
- VerificationToken,
-} from '@objectstack/spec';
-
-// Wire protocol types
-import type {
- AuthHeaders,
- AuthResponse,
- AuthError,
- TokenPayload,
-} from '@objectstack/spec';
-
-import { AUTH_CONSTANTS, AUTH_ERROR_CODES } from '@objectstack/spec';
-```
-
-## Naming Conventions
-
-Following ObjectStack conventions:
-
-- **Configuration Keys** (TypeScript properties): `camelCase` (e.g., `maxAttempts`, `emailPassword`)
-- **Machine Names** (Data values): `snake_case` (e.g., `name: 'main_auth'`, `strategy: 'email_password'`)
-
-## Resources
-
-- [Better-Auth Documentation](https://better-auth.com)
-- [ObjectStack Documentation](https://objectstack.ai)
-- [JSON Schema Reference](/docs/packages/spec/json-schema/AuthConfig.json)
-
-## License
-
-Apache 2.0
diff --git a/content/docs/standards/error-handling.mdx b/content/docs/standards/error-handling.mdx
deleted file mode 100644
index 0fd321335..000000000
--- a/content/docs/standards/error-handling.mdx
+++ /dev/null
@@ -1,184 +0,0 @@
----
-title: Error Handling Patterns
-description: Consistent error handling strategies for ObjectStack Protocol
----
-
-# Error Handling Patterns
-
-> Consistent error handling strategies for ObjectStack Protocol
-
-## Error Categories
-
-### 1. Validation Errors
-
-Errors from schema validation or business logic validation.
-
-```typescript
-{
- "success": false,
- "error": {
- "code": "VALIDATION_ERROR",
- "message": "Validation failed for field 'email'",
- "details": {
- "field": "email",
- "constraint": "format",
- "value": "invalid-email",
- "expected": "valid email format"
- }
- }
-}
-```
-
-### 2. Not Found Errors
-
-Resource does not exist.
-
-```typescript
-{
- "success": false,
- "error": {
- "code": "NOT_FOUND",
- "message": "Record not found",
- "details": {
- "object": "customer_account",
- "id": "acc_999"
- }
- }
-}
-```
-
-### 3. Permission Errors
-
-Insufficient permissions to perform operation.
-
-```typescript
-{
- "success": false,
- "error": {
- "code": "FORBIDDEN",
- "message": "Insufficient permissions to delete this record",
- "details": {
- "required": "DELETE",
- "object": "customer_account",
- "recordId": "acc_123"
- }
- }
-}
-```
-
-### 4. Conflict Errors
-
-Resource conflicts (e.g., uniqueness violations).
-
-```typescript
-{
- "success": false,
- "error": {
- "code": "CONFLICT",
- "message": "Email already exists",
- "details": {
- "field": "email",
- "constraint": "unique",
- "value": "user@example.com"
- }
- }
-}
-```
-
-## Error Schema
-
-All errors follow the `ApiError` schema:
-
-```typescript
-export const ApiErrorSchema = z.object({
- code: z.string(),
- message: z.string(),
- details: z.record(z.any()).optional(),
- stack: z.string().optional(), // Only in development
-});
-```
-
-## Error Codes
-
-### Standard HTTP-Aligned Codes
-
-- `BAD_REQUEST` (400) - Invalid request
-- `UNAUTHORIZED` (401) - Authentication required
-- `FORBIDDEN` (403) - Insufficient permissions
-- `NOT_FOUND` (404) - Resource not found
-- `CONFLICT` (409) - Resource conflict
-- `VALIDATION_ERROR` (422) - Validation failed
-- `INTERNAL_ERROR` (500) - Server error
-
-### Domain-Specific Codes
-
-- `FIELD_REQUIRED` - Required field missing
-- `FIELD_INVALID` - Field validation failed
-- `DUPLICATE_VALUE` - Uniqueness constraint violated
-- `REFERENCE_INVALID` - Lookup reference invalid
-- `WORKFLOW_ERROR` - Workflow execution failed
-- `PERMISSION_DENIED` - Specific permission denied
-
-## Best Practices
-
-### 1. Always Include Context
-
-```typescript
-// ✅ Good - Includes context
-{
- "code": "VALIDATION_ERROR",
- "message": "Field 'email' must be a valid email address",
- "details": {
- "field": "email",
- "value": "invalid-email",
- "constraint": "format"
- }
-}
-
-// ❌ Bad - No context
-{
- "code": "VALIDATION_ERROR",
- "message": "Invalid input"
-}
-```
-
-### 2. Use Consistent Error Structures
-
-Always return errors in the standard envelope:
-
-```typescript
-{
- "success": false,
- "error": { /* ApiError */ },
- "metadata": { /* request metadata */ }
-}
-```
-
-### 3. Don't Leak Sensitive Information
-
-```typescript
-// ✅ Good - Safe error message
-{
- "code": "UNAUTHORIZED",
- "message": "Invalid credentials"
-}
-
-// ❌ Bad - Leaks information
-{
- "code": "UNAUTHORIZED",
- "message": "Password incorrect for user john@example.com"
-}
-```
-
-### 4. Include Stack Traces in Development Only
-
-```typescript
-if (process.env.NODE_ENV === 'development') {
- error.stack = err.stack;
-}
-```
-
-## Related
-
-- [API Design Principles](/docs/standards/api-design.md)
-- [Security Best Practices](/docs/guides/security/best-practices.md)
diff --git a/content/docs/standards/index.mdx b/content/docs/standards/index.mdx
deleted file mode 100644
index 94ef5ea44..000000000
--- a/content/docs/standards/index.mdx
+++ /dev/null
@@ -1,42 +0,0 @@
----
-title: Standards & Best Practices
-description: Protocol standards and coding conventions
----
-
-# Standards & Best Practices
-
-This section documents the standards, conventions, and best practices for working with the ObjectStack Protocol.
-
-## Protocol Standards
-
-### [Naming Conventions](/docs/standards/naming-conventions)
-Learn the naming rules for schemas, fields, and identifiers:
-- Configuration keys use `camelCase`
-- Machine names use `snake_case`
-- Schema property naming patterns
-
-### [API Design](/docs/standards/api-design)
-API design principles and patterns for building consistent interfaces:
-- RESTful conventions
-- Request/Response envelopes
-- Error handling patterns
-
-### [Error Handling](/docs/standards/error-handling)
-Consistent error handling strategies across the protocol:
-- Error types and codes
-- Error messages and localization
-- Recovery strategies
-
-### [Authentication](/docs/standards/authentication)
-Authentication provider implementation standards:
-- OAuth, SAML, LDAP integration
-- Session management
-- Security best practices
-
-## Why Standards Matter
-
-Standards ensure:
-- **Consistency**: Predictable behavior across implementations
-- **Interoperability**: Different components work together seamlessly
-- **Maintainability**: Code is easier to understand and modify
-- **Quality**: Best practices prevent common pitfalls
diff --git a/content/docs/standards/meta.cn.json b/content/docs/standards/meta.cn.json
deleted file mode 100644
index c5a01a058..000000000
--- a/content/docs/standards/meta.cn.json
+++ /dev/null
@@ -1,11 +0,0 @@
-{
- "title": "标准",
- "root": true,
- "pages": [
- "index",
- "naming-conventions",
- "api-design",
- "error-handling",
- "authentication"
- ]
-}
diff --git a/content/docs/standards/meta.json b/content/docs/standards/meta.json
deleted file mode 100644
index bf955c096..000000000
--- a/content/docs/standards/meta.json
+++ /dev/null
@@ -1,11 +0,0 @@
-{
- "title": "Standards",
- "root": true,
- "pages": [
- "index",
- "naming-conventions",
- "api-design",
- "error-handling",
- "authentication"
- ]
-}
diff --git a/content/docs/standards/naming-conventions.mdx b/content/docs/standards/naming-conventions.mdx
deleted file mode 100644
index b35d580a6..000000000
--- a/content/docs/standards/naming-conventions.mdx
+++ /dev/null
@@ -1,81 +0,0 @@
----
-title: Naming Conventions
-description: Standardized naming rules for ObjectStack Protocol schemas and configurations
----
-
-# Naming Conventions
-
-> Standardized naming rules for ObjectStack Protocol schemas and configurations
-
-## Overview
-
-ObjectStack uses **two distinct naming conventions** depending on the context:
-- **Configuration Keys** (TypeScript properties): `camelCase`
-- **Machine Names** (Data identifiers): `snake_case`
-
-This dual-convention approach aligns with industry best practices from Salesforce, ServiceNow, and Kubernetes.
-
-## Configuration Keys (camelCase)
-
-### When to Use
-
-Use `camelCase` for **all TypeScript property names** in schema definitions:
-- Schema property keys
-- Function parameters
-- Object configuration options
-- API request/response fields (at the protocol level)
-
-### Examples
-
-```typescript
-// ✅ Correct
-export const FieldSchema = z.object({
- maxLength: z.number().optional(),
- minLength: z.number().optional(),
- defaultValue: z.any().optional(),
- referenceFilters: z.array(z.string()).optional(),
- isRequired: z.boolean().default(false),
- isUnique: z.boolean().default(false),
-});
-```
-
-### Rationale
-
-- **TypeScript Convention**: Matches TypeScript/JavaScript ecosystem standards
-- **Developer Experience**: Familiar to frontend and backend developers
-- **IDE Support**: Better autocomplete and type inference
-- **Industry Alignment**: Matches REST API conventions (JSON payloads)
-
-## Machine Names (snake_case)
-
-### When to Use
-
-Use `snake_case` for **all data identifiers** that represent database or system entities:
-- Object names (e.g., `project_task`, `customer_account`)
-- Field names (e.g., `first_name`, `email_address`)
-- Workflow names, Report names
-- Any identifier stored as data
-
-### Examples
-
-```typescript
-// ✅ Correct - Machine names in snake_case
-const field = {
- name: 'first_name', // Data identifier - snake_case
- label: 'First Name', // Display text - Title Case
- type: 'text', // Enum value - lowercase
- maxLength: 50, // Config property - camelCase
-};
-```
-
-## Summary
-
-| Context | Convention | Example |
-|---------|-----------|---------|
-| **Configuration Keys** | `camelCase` | `maxLength`, `isRequired`, `defaultValue` |
-| **Machine Names** | `snake_case` | `customer_account`, `first_name` |
-| **Display Text** | Title Case | `Customer Account`, `First Name` |
-| **Enum Values** | lowercase | `text`, `number`, `date` |
-| **Constants** | UPPER_SNAKE_CASE | `MAX_LENGTH`, `DEFAULT_TIMEOUT` |
-
-For complete details and validation patterns, see [CONTRIBUTING.md](/docs/CONTRIBUTING.md#naming-conventions).
diff --git a/content/docs/troubleshooting.mdx b/content/docs/troubleshooting.mdx
deleted file mode 100644
index 36d9eb091..000000000
--- a/content/docs/troubleshooting.mdx
+++ /dev/null
@@ -1,499 +0,0 @@
----
-title: Troubleshooting
-description: Common issues and how to resolve them when working with ObjectStack.
----
-
-This guide covers common issues you might encounter when working with ObjectStack and how to resolve them.
-
-## Installation Issues
-
-### `npm install @objectstack/spec` fails
-
-**Symptoms:**
-```
-npm ERR! code ERESOLVE
-npm ERR! ERESOLVE unable to resolve dependency tree
-```
-
-**Solutions:**
-
-1. **Clear npm cache:**
- ```bash
- npm cache clean --force
- rm -rf node_modules package-lock.json
- npm install
- ```
-
-2. **Check Node.js version:**
- ```bash
- node --version # Should be 18.0.0 or higher
- ```
-
-3. **Use legacy peer deps (temporary workaround):**
- ```bash
- npm install --legacy-peer-deps
- ```
-
-### TypeScript compilation errors
-
-**Symptoms:**
-```
-error TS2307: Cannot find module '@objectstack/spec'
-```
-
-**Solutions:**
-
-1. **Ensure correct tsconfig.json:**
- ```json
- {
- "compilerOptions": {
- "moduleResolution": "node",
- "esModuleInterop": true,
- "strict": true
- }
- }
- ```
-
-2. **Restart TypeScript server** (VS Code: Cmd+Shift+P → "Restart TS Server")
-
-## Schema Definition Issues
-
-### Validation errors in object definitions
-
-**Symptoms:**
-```
-ZodError: [
- {
- "code": "invalid_type",
- "expected": "string",
- "received": "undefined",
- "path": ["name"]
- }
-]
-```
-
-**Solution:**
-
-Check that all required fields are provided:
-
-```typescript
-// ❌ Wrong - missing required 'name' field
-const Task = ObjectSchema.create({
- label: 'Task',
- fields: { ... }
-});
-
-// ✅ Correct
-const Task = ObjectSchema.create({
- name: 'task', // ← Required
- label: 'Task',
- fields: { ... }
-});
-```
-
-### Field type errors
-
-**Symptoms:**
-```
-Type 'string' is not assignable to type 'FieldType'
-```
-
-**Solution:**
-
-Use Field helper functions, not raw strings:
-
-```typescript
-// ❌ Wrong
-fields: {
- title: { type: 'text', label: 'Title' }
-}
-
-// ✅ Correct
-fields: {
- title: Field.text({ label: 'Title' })
-}
-```
-
-### Circular dependency in lookups
-
-**Symptoms:**
-```
-ReferenceError: Cannot access 'Contact' before initialization
-```
-
-**Solution:**
-
-Use lazy imports for circular references:
-
-```typescript
-// File: account.object.ts
-export const Account = ObjectSchema.create({
- fields: {
- primary_contact: Field.lookup({
- reference: 'contact', // ← String reference, not import
- })
- }
-});
-
-// File: contact.object.ts
-export const Contact = ObjectSchema.create({
- fields: {
- account: Field.lookup({
- reference: 'account', // ← String reference
- })
- }
-});
-```
-
-## Runtime Issues
-
-### "Driver not registered"
-
-**Symptoms:**
-```
-Error: Driver 'postgres' not registered
-```
-
-**Solution:**
-
-Register the driver before using it:
-
-```typescript
-import { Kernel } from '@objectstack/kernel';
-import { PostgresDriver } from '@objectstack/driver-postgres';
-
-const kernel = new Kernel();
-
-// Register driver BEFORE creating queries
-kernel.registerDriver('postgres', new PostgresDriver({
- host: 'localhost',
- database: 'mydb',
-}));
-```
-
-### Query execution fails
-
-**Symptoms:**
-```
-Error: Query failed: syntax error near "SELECT"
-```
-
-**Solutions:**
-
-1. **Enable query logging to see generated SQL:**
- ```typescript
- const kernel = new Kernel({
- logging: {
- level: 'debug',
- logQueries: true,
- },
- });
- ```
-
-2. **Check driver capabilities:**
- ```typescript
- const driver = kernel.getDriver('postgres');
- console.log(driver.capabilities);
-
- // Ensure your query uses supported features
- ```
-
-3. **Simplify the query to isolate the issue:**
- ```typescript
- // Start simple
- const simple = await kernel.query({
- object: 'task',
- });
-
- // Add complexity step by step
- const withFilter = await kernel.query({
- object: 'task',
- filters: { status: { eq: 'open' } },
- });
- ```
-
-### Formula evaluation errors
-
-**Symptoms:**
-```
-Error: Formula evaluation failed: Unknown function 'INVALID'
-```
-
-**Solutions:**
-
-1. **Check formula syntax:**
- ```typescript
- // ❌ Wrong - invalid function
- expression: 'INVALID(field)'
-
- // ✅ Correct - use supported functions
- expression: 'IF(field > 0, field * 2, 0)'
- ```
-
-2. **Verify field references:**
- ```typescript
- // ❌ Wrong - field doesn't exist
- expression: 'nonexistent_field + 10'
-
- // ✅ Correct - reference actual fields
- expression: 'quantity * unit_price'
- ```
-
-3. **Check return type compatibility:**
- ```typescript
- Field.formula({
- returnType: 'number',
- // ❌ Wrong - returns string
- expression: 'CONCAT(first_name, last_name)',
-
- // ✅ Correct - returns number
- expression: 'quantity * unit_price',
- })
- ```
-
-## UI Rendering Issues
-
-### Views not displaying correctly
-
-**Symptoms:**
-- Blank screen
-- Missing columns
-- Incorrect data
-
-**Solutions:**
-
-1. **Verify view is registered:**
- ```typescript
- const manifest = Manifest.create({
- views: {
- list: [TaskListView], // ← Must include your view
- },
- });
- ```
-
-2. **Check field references in columns:**
- ```typescript
- // ❌ Wrong - field doesn't exist on object
- columns: [
- { field: 'nonexistent_field' }
- ]
-
- // ✅ Correct - use actual field names
- columns: [
- { field: 'title' }, // ← Must match field in object
- { field: 'status' },
- ]
- ```
-
-3. **Inspect browser console for errors**
-
-### Form validation not working
-
-**Symptoms:**
-- Form submits invalid data
-- No validation errors shown
-
-**Solutions:**
-
-1. **Ensure validation rules are registered:**
- ```typescript
- const manifest = Manifest.create({
- validations: [
- taskValidations, // ← Include validation rules
- ],
- });
- ```
-
-2. **Check validation rule conditions:**
- ```typescript
- ValidationRule.create({
- // ❌ Wrong - inverted logic
- condition: 'due_date < TODAY()', // Triggers when date is in past
-
- // ✅ Correct - fixed logic
- condition: 'due_date < TODAY()',
- errorMessage: 'Due date cannot be in the past',
- })
- ```
-
-## Performance Issues
-
-### Slow query execution
-
-**Symptoms:**
-- Queries take several seconds
-- UI feels sluggish
-
-**Solutions:**
-
-1. **Add indexes to frequently queried fields:**
- ```typescript
- Field.text({
- label: 'Email',
- indexed: true, // ← Creates database index
- })
- ```
-
-2. **Use pagination for large datasets:**
- ```typescript
- const query = Query.create({
- object: 'task',
- limit: 50, // ← Limit results
- offset: 0,
- });
- ```
-
-3. **Optimize formula fields:**
- ```typescript
- // ❌ Slow - complex nested formulas
- expression: 'IF(IF(IF(...), ...), ...)'
-
- // ✅ Fast - simpler logic
- expression: 'amount * (1 - discount / 100)'
- ```
-
-4. **Enable query result caching:**
- ```typescript
- const kernel = new Kernel({
- cache: {
- enabled: true,
- ttl: 60, // seconds
- },
- });
- ```
-
-### Large bundle size
-
-**Symptoms:**
-- Slow initial page load
-- Large JavaScript bundle
-
-**Solutions:**
-
-1. **Use tree-shaking:**
- ```typescript
- // ❌ Imports everything
- import * as ObjectStack from '@objectstack/spec';
-
- // ✅ Import only what you need
- import { ObjectSchema, Field } from '@objectstack/spec';
- ```
-
-2. **Code-split views:**
- ```typescript
- // Lazy-load views
- const TaskView = lazy(() => import('./views/task-view'));
- ```
-
-## Development Issues
-
-### Hot reload not working
-
-**Symptoms:**
-- Changes not reflected in browser
-- Need to manually refresh
-
-**Solutions:**
-
-1. **Check Next.js dev server is running:**
- ```bash
- pnpm docs:dev
- ```
-
-2. **Clear Next.js cache:**
- ```bash
- rm -rf .next
- pnpm docs:dev
- ```
-
-### TypeScript autocomplete not working
-
-**Symptoms:**
-- No IntelliSense suggestions
-- Type errors not shown
-
-**Solutions:**
-
-1. **Restart TypeScript server** (VS Code: Cmd+Shift+P → "Restart TS Server")
-
-2. **Check tsconfig.json includes source files:**
- ```json
- {
- "include": ["src/**/*", "*.ts"]
- }
- ```
-
-3. **Ensure @objectstack/spec is installed:**
- ```bash
- npm list @objectstack/spec
- ```
-
-## Debugging Tips
-
-### Enable debug logging
-
-```typescript
-const kernel = new Kernel({
- logging: {
- level: 'debug', // 'error' | 'warn' | 'info' | 'debug'
- logQueries: true,
- logValidation: true,
- },
-});
-```
-
-### Inspect generated schemas
-
-```typescript
-import { zodToJsonSchema } from 'zod-to-json-schema';
-
-const jsonSchema = zodToJsonSchema(TaskSchema);
-console.log(JSON.stringify(jsonSchema, null, 2));
-```
-
-### Test schemas in isolation
-
-```typescript
-import { Task } from './objects/task';
-
-// Test valid data
-const validResult = Task.safeParse({
- title: 'Test Task',
- status: 'todo',
-});
-console.log(validResult); // { success: true, data: {...} }
-
-// Test invalid data
-const invalidResult = Task.safeParse({
- title: '', // Empty string (might be invalid)
- status: 'invalid_status',
-});
-console.log(invalidResult); // { success: false, error: {...} }
-```
-
-### Use browser DevTools
-
-1. **Network tab:** Inspect API requests/responses
-2. **Console tab:** View runtime errors
-3. **React DevTools:** Inspect component props (if using React renderer)
-
-## Getting Help
-
-If you're still stuck after trying these solutions:
-
-1. **Search existing issues:**
- - [GitHub Issues](https://github.com/objectstack-ai/spec/issues)
-
-2. **Ask the community:**
- - [GitHub Issues](https://github.com/objectstack-ai/spec/issues)
-
-3. **Report a bug:**
- - [Create a new issue](https://github.com/objectstack-ai/spec/issues/new)
- - Include:
- - ObjectStack version
- - Node.js version
- - Error message and stack trace
- - Minimal reproduction example
-
-4. **Check the FAQ:**
- - [Frequently Asked Questions](/docs/faq)
diff --git a/content/docs/tutorials.mdx b/content/docs/tutorials.mdx
deleted file mode 100644
index 00eadbafc..000000000
--- a/content/docs/tutorials.mdx
+++ /dev/null
@@ -1,137 +0,0 @@
----
-title: Tutorials
-description: Step-by-step hands-on tutorials to learn ObjectStack by building real applications.
----
-
-Learn ObjectStack through practical, hands-on tutorials. Each tutorial is designed to teach specific concepts while building a complete, working application.
-
-## Getting Started Tutorials
-
-
-
-
-
-
-
-## Feature-Focused Tutorials
-
-### Data & Business Logic
-
-
-
-
-
-
-
-
-### UI & User Experience
-
-
-
-
-
-
-
-### Advanced Topics
-
-
-
-
-
-
-
-## Video Tutorials
-
-Coming soon! Subscribe to our [YouTube channel](#) for video tutorials.
-
-## Tutorial Prerequisites
-
-All tutorials assume you have:
-- Node.js 18+ installed
-- Basic TypeScript knowledge
-- Text editor or IDE (VS Code recommended)
-- Terminal/command line familiarity
-
-## Learning Path
-
-Not sure where to start? Follow this recommended path:
-
-
-
-### 1. Start with Quick Start
-Complete [Build Your First App](/docs/quick-start/build-first-app) (10 minutes)
-
-### 2. Choose Your Path
-- **Backend Focus:** [Field Types](/docs/guides/field-types) → [Formulas](/docs/references/data/core/Field) → [Workflows](/docs/guides/workflows-validation)
-- **Frontend Focus:** [Custom Views](/docs/guides/view-configuration) → [Forms](/docs/guides/view-configuration) → [Dashboards](/docs/references/ui/analytics/Dashboard)
-- **Full-Stack:** [CRM System](https://github.com/objectstack-ai/spec/tree/main/examples/crm) → [Multi-Tenancy](/docs/guides/advanced/multi-tenancy)
-
-### 3. Build Your Own
-Apply what you've learned to build your own application!
-
-
-
-## Community Examples
-
-Check out community-contributed examples:
-- [GitHub Issues](https://github.com/objectstack-ai/spec/issues)
-- [Example Gallery](https://github.com/objectstack-ai/spec/tree/main/examples)
-
-## Get Help
-
-Stuck on a tutorial?
-- Check the [Troubleshooting Guide](/docs/troubleshooting)
-- Ask in [GitHub Issues](https://github.com/objectstack-ai/spec/issues)
-- Review the [FAQ](/docs/faq)
diff --git a/content/docs/tutorials/meta.cn.json b/content/docs/tutorials/meta.cn.json
deleted file mode 100644
index 42851c987..000000000
--- a/content/docs/tutorials/meta.cn.json
+++ /dev/null
@@ -1,5 +0,0 @@
-{
- "title": "教程",
- "root": true,
- "pages": []
-}
diff --git a/content/docs/tutorials/meta.json b/content/docs/tutorials/meta.json
deleted file mode 100644
index 329460cc9..000000000
--- a/content/docs/tutorials/meta.json
+++ /dev/null
@@ -1,5 +0,0 @@
-{
- "title": "Tutorials",
- "root": true,
- "pages": []
-}
From 11422fe95f5c8f32329afd7fcba4faacaa4efdd2 Mon Sep 17 00:00:00 2001
From: Jack Zhuang <50353452+hotlong@users.noreply.github.com>
Date: Mon, 26 Jan 2026 21:21:48 +0800
Subject: [PATCH 07/22] Remove concepts and specifications docs, restructure
content
Deleted all files under content/docs/concepts and content/docs/specifications, removing architecture, core values, enterprise patterns, and related protocol documentation. Moved and renamed development docs to developers/, and protocols/ and transport/ docs to objectos/, objectql/, and objectui/ namespaces. Updated introduction and references metadata and content to reflect the new documentation structure. Added docs-structure-proposal.md to outline the proposed new organization.
---
content/docs/concepts/ai-codex.cn.mdx | 81 --
content/docs/concepts/ai-codex.mdx | 81 --
content/docs/concepts/architecture.cn.mdx | 185 -----
content/docs/concepts/architecture.mdx | 185 -----
content/docs/concepts/core-values.cn.mdx | 86 --
content/docs/concepts/core-values.mdx | 93 ---
.../docs/concepts/enterprise-patterns.cn.mdx | 95 ---
content/docs/concepts/enterprise-patterns.mdx | 95 ---
content/docs/concepts/manifesto.cn.mdx | 102 ---
content/docs/concepts/meta.cn.json | 25 -
content/docs/concepts/meta.json | 25 -
content/docs/concepts/plugin-architecture.mdx | 161 ----
content/docs/concepts/protocol-ai.mdx | 175 ----
content/docs/concepts/protocol-api.mdx | 185 -----
content/docs/concepts/protocol-auth.mdx | 150 ----
content/docs/concepts/protocol-automation.mdx | 191 -----
content/docs/concepts/protocol-data.mdx | 134 ----
content/docs/concepts/protocol-driver.mdx | 140 ----
content/docs/concepts/protocol-hub.mdx | 170 ----
content/docs/concepts/protocol-kernel.mdx | 159 ----
content/docs/concepts/protocol-permission.mdx | 304 -------
content/docs/concepts/protocol-system.mdx | 150 ----
content/docs/concepts/protocol-ui.mdx | 138 ----
.../concepts/security_architecture.cn.mdx | 97 ---
.../docs/concepts/security_architecture.mdx | 100 ---
content/docs/concepts/terminology.cn.mdx | 125 ---
content/docs/core-concepts/index.mdx | 52 --
content/docs/core-concepts/meta.json | 8 -
content/docs/core-concepts/object-model.mdx | 749 ------------------
content/docs/core-concepts/the-stack.mdx | 505 ------------
.../{development => developers}/cli-tools.mdx | 0
.../custom-widgets.mdx | 0
.../{development => developers}/index.mdx | 0
.../{development => developers}/meta.json | 1 +
.../server-drivers.mdx | 0
.../writing-plugins.mdx | 0
content/docs/introduction/architecture.mdx | 596 ++++++++++----
content/docs/introduction/glossary.mdx | 189 -----
content/docs/introduction/index.mdx | 113 ++-
.../{concepts => introduction}/manifesto.mdx | 0
content/docs/introduction/meta.json | 11 +-
.../metadata-driven.mdx | 0
content/docs/introduction/overview.mdx | 105 ---
.../terminology.mdx | 0
content/docs/meta.json | 20 +-
.../objectos/config-resolution.mdx | 0
.../objectos/i18n-standard.mdx | 0
.../docs/{protocols => }/objectos/index.mdx | 0
.../{protocols => }/objectos/lifecycle.mdx | 0
.../docs/{protocols => }/objectos/meta.json | 5 +-
.../{protocols => }/objectos/plugin-spec.mdx | 0
.../transport/error-handling.mdx | 0
.../{ => objectos}/transport/http-api.mdx | 0
.../docs/{ => objectos}/transport/index.mdx | 0
.../docs/{ => objectos}/transport/meta.json | 0
.../{ => objectos}/transport/realtime.mdx | 0
.../docs/{protocols => }/objectql/index.mdx | 0
.../docs/{protocols => }/objectql/meta.json | 1 +
.../{protocols => }/objectql/query-syntax.mdx | 0
.../docs/{protocols => }/objectql/schema.mdx | 0
.../{protocols => }/objectql/security.mdx | 0
.../docs/{protocols => }/objectql/types.mdx | 0
.../docs/{protocols => }/objectui/actions.mdx | 0
.../docs/{protocols => }/objectui/concept.mdx | 0
.../docs/{protocols => }/objectui/index.mdx | 0
.../{protocols => }/objectui/layout-dsl.mdx | 0
.../docs/{protocols => }/objectui/meta.json | 1 +
.../objectui/widget-contract.mdx | 0
content/docs/protocols/index.mdx | 212 -----
content/docs/protocols/meta.json | 8 -
content/docs/references/ai/meta.cn.json | 2 +-
content/docs/references/ai/meta.json | 1 -
content/docs/references/api/meta.cn.json | 2 +-
content/docs/references/api/meta.json | 1 -
content/docs/references/auth/meta.cn.json | 2 +-
content/docs/references/auth/meta.json | 2 +-
.../docs/references/automation/meta.cn.json | 2 +-
content/docs/references/automation/meta.json | 2 +-
content/docs/references/data/meta.cn.json | 2 +-
content/docs/references/data/meta.json | 2 +-
content/docs/references/driver/meta.cn.json | 2 +-
content/docs/references/driver/meta.json | 2 +-
content/docs/references/hub/meta.json | 2 +-
content/docs/references/kernel/meta.json | 2 +-
content/docs/references/meta.cn.json | 16 -
content/docs/references/meta.json | 2 +-
.../docs/references/permission/meta.cn.json | 2 +-
content/docs/references/permission/meta.json | 2 +-
content/docs/references/system/meta.cn.json | 2 +-
content/docs/references/system/meta.json | 2 +-
content/docs/references/ui/meta.cn.json | 2 +-
content/docs/references/ui/meta.json | 2 +-
.../architecture/data-layer.mdx | 285 -------
.../specifications/architecture/index.mdx | 38 -
.../specifications/architecture/meta.json | 9 -
.../architecture/system-layer.mdx | 454 -----------
.../specifications/architecture/ui-layer.mdx | 367 ---------
.../specifications/data/advanced-types.mdx | 72 --
.../data/analytics-protocol.mdx | 57 --
.../specifications/data/architecture.cn.mdx | 59 --
.../docs/specifications/data/architecture.mdx | 59 --
.../specifications/data/ast-structure.mdx | 85 --
content/docs/specifications/data/index.mdx | 149 ----
content/docs/specifications/data/meta.cn.json | 12 -
content/docs/specifications/data/meta.json | 13 -
.../specifications/data/schema-definition.mdx | 87 --
.../specifications/data/transaction-model.mdx | 39 -
.../specifications/data/wire-protocol.mdx | 56 --
content/docs/specifications/index.mdx | 245 ------
content/docs/specifications/meta.cn.json | 11 -
content/docs/specifications/meta.json | 11 -
.../server/audit-compliance.mdx | 23 -
.../server/automation-rules.mdx | 31 -
content/docs/specifications/server/index.mdx | 382 ---------
.../specifications/server/integration-etl.mdx | 26 -
.../server/kernel-architecture.cn.mdx | 29 -
.../server/kernel-architecture.mdx | 36 -
.../docs/specifications/server/meta.cn.json | 13 -
content/docs/specifications/server/meta.json | 14 -
.../server/permission-governance.mdx | 36 -
.../specifications/server/plugin-manifest.mdx | 29 -
.../specifications/server/rest-api.cn.mdx | 100 ---
.../docs/specifications/server/rest-api.mdx | 100 ---
.../specifications/server/workflow-engine.mdx | 29 -
.../specifications/ui/action-triggers.mdx | 39 -
.../specifications/ui/component-schema.mdx | 34 -
content/docs/specifications/ui/index.mdx | 278 -------
.../docs/specifications/ui/layout-system.mdx | 39 -
content/docs/specifications/ui/meta.cn.json | 11 -
content/docs/specifications/ui/meta.json | 12 -
.../specifications/ui/report-template.mdx | 25 -
.../specifications/ui/sdui-protocol.cn.mdx | 54 --
.../docs/specifications/ui/sdui-protocol.mdx | 54 --
.../docs/specifications/ui/view-protocol.mdx | 43 -
docs-structure-proposal.md | 90 +++
135 files changed, 673 insertions(+), 9026 deletions(-)
delete mode 100644 content/docs/concepts/ai-codex.cn.mdx
delete mode 100644 content/docs/concepts/ai-codex.mdx
delete mode 100644 content/docs/concepts/architecture.cn.mdx
delete mode 100644 content/docs/concepts/architecture.mdx
delete mode 100644 content/docs/concepts/core-values.cn.mdx
delete mode 100644 content/docs/concepts/core-values.mdx
delete mode 100644 content/docs/concepts/enterprise-patterns.cn.mdx
delete mode 100644 content/docs/concepts/enterprise-patterns.mdx
delete mode 100644 content/docs/concepts/manifesto.cn.mdx
delete mode 100644 content/docs/concepts/meta.cn.json
delete mode 100644 content/docs/concepts/meta.json
delete mode 100644 content/docs/concepts/plugin-architecture.mdx
delete mode 100644 content/docs/concepts/protocol-ai.mdx
delete mode 100644 content/docs/concepts/protocol-api.mdx
delete mode 100644 content/docs/concepts/protocol-auth.mdx
delete mode 100644 content/docs/concepts/protocol-automation.mdx
delete mode 100644 content/docs/concepts/protocol-data.mdx
delete mode 100644 content/docs/concepts/protocol-driver.mdx
delete mode 100644 content/docs/concepts/protocol-hub.mdx
delete mode 100644 content/docs/concepts/protocol-kernel.mdx
delete mode 100644 content/docs/concepts/protocol-permission.mdx
delete mode 100644 content/docs/concepts/protocol-system.mdx
delete mode 100644 content/docs/concepts/protocol-ui.mdx
delete mode 100644 content/docs/concepts/security_architecture.cn.mdx
delete mode 100644 content/docs/concepts/security_architecture.mdx
delete mode 100644 content/docs/concepts/terminology.cn.mdx
delete mode 100644 content/docs/core-concepts/index.mdx
delete mode 100644 content/docs/core-concepts/meta.json
delete mode 100644 content/docs/core-concepts/object-model.mdx
delete mode 100644 content/docs/core-concepts/the-stack.mdx
rename content/docs/{development => developers}/cli-tools.mdx (100%)
rename content/docs/{development => developers}/custom-widgets.mdx (100%)
rename content/docs/{development => developers}/index.mdx (100%)
rename content/docs/{development => developers}/meta.json (90%)
rename content/docs/{development => developers}/server-drivers.mdx (100%)
rename content/docs/{development => developers}/writing-plugins.mdx (100%)
delete mode 100644 content/docs/introduction/glossary.mdx
rename content/docs/{concepts => introduction}/manifesto.mdx (100%)
rename content/docs/{core-concepts => introduction}/metadata-driven.mdx (100%)
delete mode 100644 content/docs/introduction/overview.mdx
rename content/docs/{concepts => introduction}/terminology.mdx (100%)
rename content/docs/{protocols => }/objectos/config-resolution.mdx (100%)
rename content/docs/{protocols => }/objectos/i18n-standard.mdx (100%)
rename content/docs/{protocols => }/objectos/index.mdx (100%)
rename content/docs/{protocols => }/objectos/lifecycle.mdx (100%)
rename content/docs/{protocols => }/objectos/meta.json (65%)
rename content/docs/{protocols => }/objectos/plugin-spec.mdx (100%)
rename content/docs/{ => objectos}/transport/error-handling.mdx (100%)
rename content/docs/{ => objectos}/transport/http-api.mdx (100%)
rename content/docs/{ => objectos}/transport/index.mdx (100%)
rename content/docs/{ => objectos}/transport/meta.json (100%)
rename content/docs/{ => objectos}/transport/realtime.mdx (100%)
rename content/docs/{protocols => }/objectql/index.mdx (100%)
rename content/docs/{protocols => }/objectql/meta.json (88%)
rename content/docs/{protocols => }/objectql/query-syntax.mdx (100%)
rename content/docs/{protocols => }/objectql/schema.mdx (100%)
rename content/docs/{protocols => }/objectql/security.mdx (100%)
rename content/docs/{protocols => }/objectql/types.mdx (100%)
rename content/docs/{protocols => }/objectui/actions.mdx (100%)
rename content/docs/{protocols => }/objectui/concept.mdx (100%)
rename content/docs/{protocols => }/objectui/index.mdx (100%)
rename content/docs/{protocols => }/objectui/layout-dsl.mdx (100%)
rename content/docs/{protocols => }/objectui/meta.json (88%)
rename content/docs/{protocols => }/objectui/widget-contract.mdx (100%)
delete mode 100644 content/docs/protocols/index.mdx
delete mode 100644 content/docs/protocols/meta.json
delete mode 100644 content/docs/references/meta.cn.json
delete mode 100644 content/docs/specifications/architecture/data-layer.mdx
delete mode 100644 content/docs/specifications/architecture/index.mdx
delete mode 100644 content/docs/specifications/architecture/meta.json
delete mode 100644 content/docs/specifications/architecture/system-layer.mdx
delete mode 100644 content/docs/specifications/architecture/ui-layer.mdx
delete mode 100644 content/docs/specifications/data/advanced-types.mdx
delete mode 100644 content/docs/specifications/data/analytics-protocol.mdx
delete mode 100644 content/docs/specifications/data/architecture.cn.mdx
delete mode 100644 content/docs/specifications/data/architecture.mdx
delete mode 100644 content/docs/specifications/data/ast-structure.mdx
delete mode 100644 content/docs/specifications/data/index.mdx
delete mode 100644 content/docs/specifications/data/meta.cn.json
delete mode 100644 content/docs/specifications/data/meta.json
delete mode 100644 content/docs/specifications/data/schema-definition.mdx
delete mode 100644 content/docs/specifications/data/transaction-model.mdx
delete mode 100644 content/docs/specifications/data/wire-protocol.mdx
delete mode 100644 content/docs/specifications/index.mdx
delete mode 100644 content/docs/specifications/meta.cn.json
delete mode 100644 content/docs/specifications/meta.json
delete mode 100644 content/docs/specifications/server/audit-compliance.mdx
delete mode 100644 content/docs/specifications/server/automation-rules.mdx
delete mode 100644 content/docs/specifications/server/index.mdx
delete mode 100644 content/docs/specifications/server/integration-etl.mdx
delete mode 100644 content/docs/specifications/server/kernel-architecture.cn.mdx
delete mode 100644 content/docs/specifications/server/kernel-architecture.mdx
delete mode 100644 content/docs/specifications/server/meta.cn.json
delete mode 100644 content/docs/specifications/server/meta.json
delete mode 100644 content/docs/specifications/server/permission-governance.mdx
delete mode 100644 content/docs/specifications/server/plugin-manifest.mdx
delete mode 100644 content/docs/specifications/server/rest-api.cn.mdx
delete mode 100644 content/docs/specifications/server/rest-api.mdx
delete mode 100644 content/docs/specifications/server/workflow-engine.mdx
delete mode 100644 content/docs/specifications/ui/action-triggers.mdx
delete mode 100644 content/docs/specifications/ui/component-schema.mdx
delete mode 100644 content/docs/specifications/ui/index.mdx
delete mode 100644 content/docs/specifications/ui/layout-system.mdx
delete mode 100644 content/docs/specifications/ui/meta.cn.json
delete mode 100644 content/docs/specifications/ui/meta.json
delete mode 100644 content/docs/specifications/ui/report-template.mdx
delete mode 100644 content/docs/specifications/ui/sdui-protocol.cn.mdx
delete mode 100644 content/docs/specifications/ui/sdui-protocol.mdx
delete mode 100644 content/docs/specifications/ui/view-protocol.mdx
create mode 100644 docs-structure-proposal.md
diff --git a/content/docs/concepts/ai-codex.cn.mdx b/content/docs/concepts/ai-codex.cn.mdx
deleted file mode 100644
index f7ce7c0af..000000000
--- a/content/docs/concepts/ai-codex.cn.mdx
+++ /dev/null
@@ -1,81 +0,0 @@
----
-title: AI 代码手册
-description: 如何与人工智能协作构建 ObjectStack 应用程序。
----
-
-import { Bot, Terminal, FileJson, Sparkles } from 'lucide-react';
-
-ObjectStack 设计为 **AI 原生**。
-
-因为我们的基本构建单元是**协议(JSON/YAML Schema)**而不是命令式代码,所以大型语言模型(LLM)在理解和生成 ObjectStack 应用程序方面表现出色。
-
-本指南为使用 Copilot、ChatGPT 或 Claude 构建 ObjectStack 应用程序的开发人员提供"系统提示"心智模型。
-
-## 为什么 ObjectStack 对 AI 友好
-
-| 功能 | 代码优先支持 | ObjectStack 支持 |
-| :--- | :--- | :--- |
-| **上下文窗口** | 低。需要阅读数千行 TS/SQL。 | 高。Schema 密集且声明性。 |
-| **幻觉** | 高。AI 发明不存在的 API。 | 低。Schema 验证(Zod)拒绝无效输出。 |
-| **重构** | 困难。需要重写详细逻辑。 | 简单。只需更改 JSON 属性键。 |
-
-## "首席协议架构师"角色
-
-当提示 AI 帮助你构建时,为其分配**首席协议架构师**的角色。
-
-### 系统提示
-
-将此复制到你的自定义说明中:
-
-```markdown
-你是一位专家 ObjectStack 架构师。
-你的目标是设计声明性协议,而不是命令式代码。
-
-1. **Schema 优先:** 始终从定义 ObjectQL Schema(YAML/JSON)开始。
-2. **文件**:当被要求提供功能时,输出相关的 `.object.yml` 或 `.view.yml` 文件。
-3. **不要 SQL/React:** 除非明确要求驱动程序或渲染器实现,否则不要编写 SQL 查询或 React 组件。
-4. **样式:** 对机器名称使用 `snake_case`,对配置键使用 `camelCase`。
-```
-
-## 常见任务
-
-### 1. 从需求生成 Schema
-
-**用户:** "我需要一个 CRM 系统来跟踪潜在客户和机会。"
-
-**AI 响应:**
-```yaml
-# objects/lead.yml
-name: lead
-fields:
- status:
- type: select
- options: ['new', 'contacted', 'qualified']
- annual_revenue:
- type: currency
- scale: 2
-
-# objects/opportunity.yml
-name: opportunity
-fields:
- lead_id:
- type: lookup
- reference_to: lead
-```
-
-### 2. 生成 UI 布局
-
-**用户:** "为销售经理创建一个仪表板。"
-
-**AI 响应:**
-```yaml
-# dashboards/sales_overview.yml
-layout: grid
-widgets:
- - type: chart
- title: "按月收入"
- query: "select sum(amount), month(close_date) from opportunity group by month"
- - type: list
- object: opportunity
- filter: [["stage", "=", "closed_won"]]
-```
diff --git a/content/docs/concepts/ai-codex.mdx b/content/docs/concepts/ai-codex.mdx
deleted file mode 100644
index 7f51067cd..000000000
--- a/content/docs/concepts/ai-codex.mdx
+++ /dev/null
@@ -1,81 +0,0 @@
----
-title: AI Codex
-description: How to collaborate with Artificial Intelligence to build ObjectStack applications.
----
-
-import { Bot, Terminal, FileJson, Sparkles } from 'lucide-react';
-
-ObjectStack is designed to be **AI-Native**.
-
-Because our fundamental unit of construction is the **Protocol (JSON/YAML Schema)** rather than imperative code, Large Language Models (LLMs) are exceptionally good at understanding and generating ObjectStack applications.
-
-This guide provides the "System Prompt" mental model for developers working with Copilot, ChatGPT, or Claude to build ObjectStack apps.
-
-## Why ObjectStack is Friendly to AI
-
-| Feature | Code-First Support | ObjectStack Support |
-| :--- | :--- | :--- |
-| **Context Window** | Low. Requires reading thousands of lines of TS/SQL. | High. Schema is dense and declarative. |
-| **Hallucination** | High. AI invents APIs that don't exist. | Low. Schema validation (Zod) rejects invalid output. |
-| **Refactoring** | Hard. Requires rewriting detailed logic. | Easy. Just change a JSON property key. |
-
-## The "Chief Protocol Architect" Persona
-
-When prompting an AI to help you build, assign it the role of **Chief Protocol Architect**.
-
-### The System Prompt
-
-Copy this into your custom instructions:
-
-```markdown
-You are an expert ObjectStack Architect.
-Your goal is to design declarative protocols, NOT imperative code.
-
-1. **Schema First:** Always start by defining the ObjectQL Schema (YAML/JSON).
-2. **Files**: When asked for a feature, output the relevant `.object.yml` or `.view.yml` files.
-3. **No SQL/React:** Do not write SQL queries or React components unless explicitly asked for a Driver or Renderer implementation.
-4. **Style:** Use `snake_case` for machine names and `camelCase` for configuration keys.
-```
-
-## Common Tasks
-
-### 1. Generating Schema from Requirements
-
-**User:** "I need a CRM system to track leads and opportunities."
-
-**AI Response:**
-```yaml
-# objects/lead.yml
-name: lead
-fields:
- status:
- type: select
- options: ['new', 'contacted', 'qualified']
- annual_revenue:
- type: currency
- scale: 2
-
-# objects/opportunity.yml
-name: opportunity
-fields:
- lead_id:
- type: lookup
- reference_to: lead
-```
-
-### 2. Generating UI Layouts
-
-**User:** "Create a dashboard for the Sales Manager."
-
-**AI Response:**
-```yaml
-# dashboards/sales_overview.yml
-layout: grid
-widgets:
- - type: chart
- title: "Revenue by Month"
- query: "select sum(amount), month(close_date) from opportunity group by month"
- - type: list
- object: opportunity
- filter: [["stage", "=", "closed_won"]]
-```
diff --git a/content/docs/concepts/architecture.cn.mdx b/content/docs/concepts/architecture.cn.mdx
deleted file mode 100644
index 54e24e99f..000000000
--- a/content/docs/concepts/architecture.cn.mdx
+++ /dev/null
@@ -1,185 +0,0 @@
----
-title: 架构
-description: 理解 ObjectStack 协议架构。11 个协议命名空间如何协作构建企业内核。
----
-
-import { Layers, Database, Layout, ShieldCheck, Lock, Cog, Brain, Cloud, Zap } from 'lucide-react';
-
-ObjectStack 不是一个单体框架。它是围绕**协议驱动架构**设计的可组合生态系统。系统被组织成 **11 个协议命名空间**,每个命名空间负责特定的领域。
-
-每个协议都是解耦的,并通过使用 Zod 定义的标准 JSON schema 进行通信。这允许你替换实现(例如,将 Postgres 驱动替换为 MongoDB,或将 React 渲染器替换为 Flutter),而不会破坏堆栈的其余部分。
-
-## 协议概览
-
-ObjectStack 组织成 11 个协议命名空间:
-
-
- }
- title="数据协议(Data Protocol)"
- description="对象 schema、字段、验证和查询。"
- />
- }
- title="驱动协议(Driver Protocol)"
- description="数据库适配器(Postgres、MongoDB、SQLite 等)。"
- />
- }
- title="权限协议(Permission Protocol)"
- description="对象级、字段级、共享和区域规则。"
- />
- }
- title="UI 协议(UI Protocol)"
- description="应用、视图、仪表板、报表和主题。"
- />
- }
- title="系统协议(System Protocol)"
- description="事件、作业、翻译和审计日志。"
- />
- }
- title="认证协议(Auth Protocol)"
- description="身份、角色、会话和认证策略。"
- />
- }
- title="内核协议(Kernel Protocol)"
- description="插件生命周期、清单、日志和上下文。"
- />
- }
- title="Hub 协议(Hub Protocol)"
- description="市场、许可、租户和部署。"
- />
- }
- title="AI 协议(AI Protocol)"
- description="AI 代理、RAG、NLQ、预测模型和编排。"
- />
- }
- title="API 协议(API Protocol)"
- description="REST 契约、发现、实时和路由。"
- />
- }
- title="自动化协议(Automation Protocol)"
- description="工作流、流程和 Webhook。"
- />
-
-
-## 三层架构
-
-虽然 ObjectStack 有 11 个协议命名空间,但它们在逻辑上被分组为三个架构层:
-
-### 1. 数据层(ObjectQL)
-**"通用数据协议"**
-
-负责**数据定义**和**数据访问**的基础层。
-
-**协议:**
-* **数据协议:** 对象 schema、字段、验证、查询、过滤器
-* **驱动协议:** 用于 Postgres、MongoDB、SQLite 等的数据库适配器
-* **权限协议:** 对象级 CRUD、字段级安全、共享规则
-* **AI 协议:** AI 代理、RAG 管道、NLQ、预测模型
-
-**角色:** 定义*结构*(Schema)和*意图*(查询 AST)。
-
-**职责:** 它知道*什么是* "客户" 对象,但它不知道*谁*正在访问它或*如何*显示它。
-
-**关键组件:** **编译器**。它接受抽象查询(`find customers where active = true`)并将其转换为特定底层数据库的优化 SQL/NoSQL 查询。
-
-### 2. 控制层(ObjectOS)
-**"业务内核"**
-
-负责**运行时**和**治理**的编排层。
-
-**协议:**
-* **系统协议:** 事件、作业、翻译、审计日志
-* **认证协议:** 身份、角色、会话、认证策略
-* **内核协议:** 插件生命周期、清单、日志、上下文
-* **Hub 协议:** 市场、许可、多租户、部署
-* **自动化协议:** 工作流、流程、Webhook
-
-**角色:** 管理请求的*生命周期*。
-
-**职责:**
-* **身份:** "这个用户是谁?"(身份验证)
-* **安全:** "他们可以看到这个字段吗?"(RBAC/ACL)
-* **同步:** "我们如何合并这些离线更改?"(冲突解决)
-* **流程:** "保存此记录后会发生什么?"(工作流/触发器)
-
-**关键概念:** 它充当网关。不允许直接访问数据库;所有内容都必须通过 OS 内核。
-
-### 3. 视图层(ObjectUI)
-**"投影引擎"**
-
-负责**交互**和**渲染**的表示层。
-
-**协议:**
-* **UI 协议:** 应用、视图、仪表板、报表、主题、操作
-* **API 协议:** REST 契约、发现、实时、路由
-
-**角色:** 使用协议来渲染界面。
-
-**职责:** 它不包含硬编码的表单。相反,它询问数据层:*"客户的 schema 是什么?"* 并根据该元数据动态渲染布局。
-
-**关键概念:** **服务器驱动 UI(SDUI)**。后端规定布局、验证规则和可用操作。前端只是一个高度强大的渲染器。
-
----
-
-## 请求生命周期
-
-为了理解这些部分如何配合,让我们跟踪一个典型的用户交互——例如,销售代表在离线时更新交易状态。
-
-1. **交互(UI 协议):**
- * 用户将 "Deal" 拖到看板中的 "Closed Won" 列。
- * UI 乐观地更新屏幕(0ms)。
- * UI 向本地内核分派 `update` 操作。
-
-2. **内核守卫(内核协议):**
- * 客户端内核通过**认证协议**检查:*用户是否有权编辑 'Status'?*
- * 内核执行**数据协议**验证:*'Status' 是否是有效选项?*
- * 通过**驱动协议**将事务提交到 SQLite(本地 DB)。
-
-3. **同步(系统协议):**
- * 后台进程通过**系统事件**检测更改。
- * 根据 **API 契约**将更改压缩为**操作载荷**。
- * 通过 **API 协议**将载荷发送到服务器 API。
-
-4. **服务器执行(内核协议):**
- * 服务器内核通过**认证协议**验证请求。
- * 服务器内核运行**自动化协议**触发器(例如,检查信用额度)。
- * 服务器将 AST 传递给数据层编译器。
-
-5. **持久化(数据 + 驱动协议):**
- * **驱动协议**为 PostgreSQL 生成 `UPDATE deals SET status = 'closed_won' ...`。
- * 通过**驱动协议**提交写入。
- * **自动化协议**触发器触发(通过 webhook 向经理发送电子邮件)。
-
-## 协议依赖关系
-
-协议具有明确的依赖关系,并以结构化的方式交互:
-
-```
-内核协议(运行时核心)
- ├── 认证协议(身份和会话)
- ├── 系统协议(事件、作业、审计)
- └── Hub 协议(租户、许可)
-
-数据协议(业务逻辑)
- ├── 驱动协议(存储适配器)
- ├── 权限协议(访问控制)
- └── AI 协议(智能层)
-
-UI 协议(表示层)
- └── API 协议(通信)
-
-自动化协议(业务流程)
- └── 依赖于:数据、系统、API
-```
-
-每个协议都在 `@objectstack/spec` 中使用 Zod schema 定义,可以独立验证、版本化和演进。
diff --git a/content/docs/concepts/architecture.mdx b/content/docs/concepts/architecture.mdx
deleted file mode 100644
index 2605c5de9..000000000
--- a/content/docs/concepts/architecture.mdx
+++ /dev/null
@@ -1,185 +0,0 @@
----
-title: Architecture
-description: Understanding the ObjectStack Protocol Architecture. How the 11 protocol namespaces collaborate to build the Enterprise Kernel.
----
-
-import { Layers, Database, Layout, ShieldCheck, Lock, Cog, Brain, Cloud, Zap } from 'lucide-react';
-
-ObjectStack is not a monolithic framework. It is a composable ecosystem designed around a **Protocol-Driven Architecture**. The system is organized into **11 protocol namespaces**, each responsible for a specific domain.
-
-Each protocol is decoupled and communicates via standard JSON schemas defined with Zod. This allows you to swap out implementations (e.g., swapping the Postgres driver for MongoDB, or the React renderer for Flutter) without breaking the rest of the stack.
-
-## Protocol Overview
-
-ObjectStack is organized into 11 protocol namespaces:
-
-
- }
- title="Data Protocol"
- description="Object schema, fields, validation, and queries."
- />
- }
- title="Driver Protocol"
- description="Database adapters (Postgres, MongoDB, SQLite, etc.)."
- />
- }
- title="Permission Protocol"
- description="Object-level, field-level, sharing, and territory rules."
- />
- }
- title="UI Protocol"
- description="Apps, views, dashboards, reports, and themes."
- />
- }
- title="System Protocol"
- description="Events, jobs, translations, and audit logging."
- />
- }
- title="Auth Protocol"
- description="Identity, roles, sessions, and authentication strategies."
- />
- }
- title="Kernel Protocol"
- description="Plugin lifecycle, manifest, logging, and context."
- />
- }
- title="Hub Protocol"
- description="Marketplace, licensing, tenancy, and deployment."
- />
- }
- title="AI Protocol"
- description="Agents, RAG, NLQ, predictive models, and orchestration."
- />
- }
- title="API Protocol"
- description="REST contracts, discovery, realtime, and routing."
- />
- }
- title="Automation Protocol"
- description="Workflows, flows, and webhooks."
- />
-
-
-## The Three-Layer Architecture
-
-While ObjectStack has 11 protocol namespaces, they are logically grouped into three architectural layers:
-
-### 1. Data Layer (ObjectQL)
-**"The Universal Data Protocol"**
-
-The foundation layer responsible for **Data Definition** and **Data Access**.
-
-**Protocols:**
-* **Data Protocol:** Object schema, fields, validation, queries, filters
-* **Driver Protocol:** Database adapters for Postgres, MongoDB, SQLite, etc.
-* **Permission Protocol:** Object-level CRUD, field-level security, sharing rules
-* **AI Protocol:** AI agents, RAG pipelines, NLQ, predictive models
-
-**Role:** Defines *Structure* (Schema) and *Intent* (Query AST).
-
-**Responsibility:** It knows *what* a "Customer" object looks like, but it doesn't know *who* is accessing it or *how* it is displayed.
-
-**Key Component:** The **Compiler**. It takes an abstract query (`find customers where active = true`) and translates it into optimized SQL/NoSQL queries for the specific underlying database.
-
-### 2. Control Layer (ObjectOS)
-**"The Business Kernel"**
-
-The orchestration layer responsible for **Runtime** and **Governance**.
-
-**Protocols:**
-* **System Protocol:** Events, jobs, translations, audit logging
-* **Auth Protocol:** Identity, roles, sessions, authentication strategies
-* **Kernel Protocol:** Plugin lifecycle, manifest, logging, context
-* **Hub Protocol:** Marketplace, licensing, multi-tenancy, deployment
-* **Automation Protocol:** Workflows, flows, webhooks
-
-**Role:** Manages the *Lifecycle* of a request.
-
-**Responsibility:**
-* **Identity:** "Who is this user?" (Authentication)
-* **Security:** "Can they see this field?" (RBAC/ACL)
-* **Sync:** "How do we merge these offline changes?" (Conflict Resolution)
-* **Process:** "What happens after this record is saved?" (Workflows/Triggers)
-
-**Key Concept:** It acts as the gateway. No direct database access is allowed; everything must pass through the OS Kernel.
-
-### 3. View Layer (ObjectUI)
-**"The Projection Engine"**
-
-The presentation layer responsible for **Interaction** and **Rendering**.
-
-**Protocols:**
-* **UI Protocol:** Apps, views, dashboards, reports, themes, actions
-* **API Protocol:** REST contracts, discovery, realtime, routing
-
-**Role:** Consumes the Protocol to render the Interface.
-
-**Responsibility:** It does not contain hardcoded forms. Instead, it asks the Data Layer: *"What is the schema for a Customer?"* and dynamically renders a layout based on that metadata.
-
-**Key Concept:** **Server-Driven UI (SDUI)**. The backend dictates the layout, validation rules, and available actions. The frontend is merely a highly capable renderer.
-
----
-
-## The Request Lifecycle
-
-To understand how these pieces fit together, let's trace a typical user interaction—for example, a Sales Rep updating a deal status while offline.
-
-1. **Interaction (UI Protocol):**
- * User drags "Deal" to "Closed Won" column in Kanban.
- * UI Optimistically updates the screen (0ms).
- * UI dispatches an `update` action to the local Kernel.
-
-2. **Kernel Guard (Kernel Protocol):**
- * Client Kernel checks via **Auth Protocol**: *Does user have permission to edit 'Status'?*
- * Kernel executes **Data Protocol** validation: *Is 'Status' a valid option?*
- * Transaction committed via **Driver Protocol** to SQLite (Local DB).
-
-3. **Synchronization (System Protocol):**
- * Background process detects changes via **System Events**.
- * Compresses change into an **Operation Payload** per **API Contract**.
- * Sends payload to Server API via **API Protocol**.
-
-4. **Server Execution (Kernel Protocol):**
- * Server Kernel authenticates via **Auth Protocol**.
- * Server Kernel runs **Automation Protocol** triggers (e.g., Check credit limit).
- * Server passes AST to Data Layer Compiler.
-
-5. **Persistence (Data + Driver Protocols):**
- * **Driver Protocol** generates `UPDATE deals SET status = 'closed_won' ...` for PostgreSQL.
- * Write is committed via **Driver Protocol**.
- * **Automation Protocol** triggers fire (send email to manager via webhook).
-
-## Protocol Dependencies
-
-The protocols have clear dependencies and interact in a structured way:
-
-```
-Kernel Protocol (Runtime Core)
- ├── Auth Protocol (Identity & Sessions)
- ├── System Protocol (Events, Jobs, Audit)
- └── Hub Protocol (Tenancy, Licensing)
-
-Data Protocol (Business Logic)
- ├── Driver Protocol (Storage Adapters)
- ├── Permission Protocol (Access Control)
- └── AI Protocol (Intelligence Layer)
-
-UI Protocol (Presentation)
- └── API Protocol (Communication)
-
-Automation Protocol (Business Processes)
- └── Depends on: Data, System, API
-```
-
-Each protocol is defined with Zod schemas in `@objectstack/spec` and can be independently validated, versioned, and evolved.
diff --git a/content/docs/concepts/core-values.cn.mdx b/content/docs/concepts/core-values.cn.mdx
deleted file mode 100644
index 693569b2c..000000000
--- a/content/docs/concepts/core-values.cn.mdx
+++ /dev/null
@@ -1,86 +0,0 @@
----
-title: 核心价值
-description: 深入了解 ObjectStack 的三大支柱:协议驱动架构、本地优先数据主权和数据库无关性。
----
-
-import { Database, Link, Laptop } from 'lucide-react';
-
-ObjectStack 建立在三个不可协商的架构价值之上。这些不仅仅是"功能";它们是指导我们做出的每一个设计决策的约束。
-
-## 1. 协议驱动:意图优于实现
-
-ObjectStack 的基本论点是**应用程序逻辑应该由声明性数据定义,而不是命令式代码。**
-
-### "代码优先"的问题
-在现代开发中,"意图"(例如,*"此字段是必填的电子邮件地址"*)通常分散在三层:
-1. **数据库:** SQL 约束(`NOT NULL`)。
-2. **后端:** ORM 验证(例如,TypeORM 装饰器)。
-3. **前端:** UI 验证(例如,React Hook Form + Zod)。
-
-当业务需求发生变化时,你必须在三个地方更新代码。这就是**实现耦合**。
-
-### 协议驱动的解决方案
-ObjectStack 将"意图"集中到单个协议定义(JSON/YAML)中。实现层(React、Node.js、SQL)仅充当解释此协议的**运行时引擎**。
-
-
-UI 是投影。API 是结果。
-
-
-* **UI 是投影:** ObjectUI 不"构建"表单;它*投影* ObjectQL schema 到视觉表示。
-* **API 是结果:** 你不编写端点;ObjectOS *生成*基于访问控制协议的安全图。
-
-> **类比:** 将 ObjectStack 想象成一个 Web 浏览器。你向它发送 HTML(协议),它渲染一个页面。你不必每次想要更改网站上的文本时都重写浏览器引擎(C++)。
-
-## 2. 本地优先:所有权和零延迟
-
-在过去的十年中,"云原生"一直是黄金标准。虽然它解决了部署问题,但它引入了一个新问题:**用户租用他们对数据的访问。**
-
-如果服务器很慢,应用程序就很慢。如果互联网断开,应用程序就死了。
-
-### "七跳"问题
-在传统的云应用程序中,一个简单的按钮点击会经过:
-`点击 -> Wi-Fi -> ISP -> 云负载均衡器 -> Web 服务器 -> 数据库 -> 查询执行` ……然后一路返回。
-
-### 本地优先解决方案
-ObjectStack 应用程序设计为首先读写**本地数据库**(嵌入在客户端环境中)。
-`点击 -> 本地 DB -> UI 更新`(0ms 延迟)。
-
-与云的同步在后台异步发生。
-
-1. **即时响应:** UI 立即反应(乐观 UI),使企业应用程序感觉像原生桌面软件一样快速。
-2. **离线能力:** 现场工作人员、飞机或不稳定的连接不再是障碍。
-3. **数据主权:** 数据实际存储在用户的设备上。云充当同步中心,而不是唯一的看门人。
-
-## 3. 数据库无关性:通用编译器
-
-行业分为 SQL(Postgres、MySQL)和 NoSQL(MongoDB、Redis)阵营。开发人员经常将自己锁定在一个供应商的方言中。
-
-ObjectStack 引入 **ObjectQL**,这是一种统一的查询语言,可以编译到任何后端。
-
-* **供应商锁定自由:** 从 SQLite 开始进行原型设计,迁移到 PostgreSQL 用于生产,并存档到 Snowflake 用于分析——无需重写一行业务逻辑。
-* **一流的驱动程序:** 我们不实现数据库;我们实现*驱动程序*,将数据库视为愚蠢的存储引擎。我们在应用层(内核)处理复杂的逻辑(RBAC、验证)。
-
-### 编译器方法
-与运行时包装器(如 ORM)不同,ObjectQL 作为**编译器**运行。
-1. **输入:** ObjectQL 抽象语法树(AST)。
-2. **处理:** 将 AST 编译为特定方言的 SQL。
-3. **输出:** 针对目标的高度优化查询。
-
-这种架构允许激进的灵活性:
-* **开发:** 在 **SQLite** 上运行(零设置,单个文件)。
-* **生产:** 在 **PostgreSQL** 上运行(稳健,可扩展)。
-* **边缘:** 在 **Cloudflare D1** 上运行(分布式)。
-* **遗留:** 连接到现有的 **Oracle/SQL Server**(集成)。
-
-你更改*驱动程序*,而不是*代码*。
-
-## 总结
-
-| 价值 | 旧方式 | ObjectStack 方式 |
-| :--- | :--- | :--- |
-| **架构** | 代码驱动(命令式) | 协议驱动(声明式) |
-| **逻辑位置** | 分散(DB + API + UI) | 集中(JSON/YAML Schema) |
-| **数据访问** | 依赖云(仅在线) | 本地优先(离线 + 同步) |
-| **存储** | 锁定到供应商 | 数据库无关 |
-
-通过坚持这些价值观,我们构建的软件**对变化有弹性**,**尊重用户时间**,并且**技术自主**。
diff --git a/content/docs/concepts/core-values.mdx b/content/docs/concepts/core-values.mdx
deleted file mode 100644
index 6811844de..000000000
--- a/content/docs/concepts/core-values.mdx
+++ /dev/null
@@ -1,93 +0,0 @@
----
-title: Core Values
-description: "Deep dive into the three pillars of ObjectStack: Protocol-Driven Architecture, Local-First Data Sovereignty, and Database Agnosticism."
----
-
-import { Database, Link, Laptop } from 'lucide-react';
-
-ObjectStack is built upon three non-negotiable architectural values. These are not just "features"; they are the constraints that guide every design decision we make.
-
-## 1. Protocol-Driven: Intent over Implementation
-
-The fundamental thesis of ObjectStack is that **application logic should be defined by declarative data, not imperative code.**
-
-### The Problem with "Code-First"
-In modern development, the "Intent" (e.g., *“This field is a required email address”*) is often scattered across three layers:
-1. **Database:** SQL constraints (`NOT NULL`).
-2. **Backend:** ORM validation (e.g., TypeORM decorators).
-3. **Frontend:** UI validation (e.g., React Hook Form + Zod).
-
-When the business requirement changes, you must update code in three places. This is **Implementation Coupling**.
-
-### The Protocol-Driven Solution
-ObjectStack centralizes the "Intent" into a single Protocol Definition (JSON/YAML). The implementation layers (React, Node.js, SQL) act merely as **Runtime Engines** that interpret this protocol.
-
-
-The UI is a Projection. The API is a Consequence.
-
-
-* **The UI is a Projection:** ObjectUI does not "build" a form; it *projects* the ObjectQL schema into a visual representation.
-* **The API is a Consequence:** You do not write endpoints; ObjectOS *generates* the secure graph based on the access control protocol.
-
-> **Analogy:** Think of ObjectStack as a Web Browser. You send it HTML (Protocol), and it renders a page. You don't rewrite the browser engine (C++) every time you want to change the text on a website.
-
-## 2. Local-First: Ownership & Zero Latency
-
-For the past decade, "Cloud-Native" has been the gold standard. While it solved deployment issues, it introduced a new problem: **The User rents their access to data.**
-
-If the server is slow, the app is slow. If the internet is down, the app is dead.
-
-### The "Seven Hops" Problem
-In a traditional Cloud app, a simple button click travels through:
-`Click -> Wi-Fi -> ISP -> Cloud Load Balancer -> Web Server -> Database -> Query Execution` ...and then all the way back.
-
-### The Local-First Solution
-ObjectStack apps are designed to read and write to a **Local Database** (embedded within the client environment) first.
-`Click -> Local DB -> UI Update` (0ms Latency).
-
-The synchronization with the cloud happens in the background, asynchronously.
-
-1. **Instant Response:** The UI reacts immediately (optimistic UI), making enterprise apps feel as snappy as native desktop software.
-2. **Offline Capability:** Field workers, airplanes, or spotty connections are no longer blockers.
-3. **Data Sovereignty:** The data physically resides on the user's device. The cloud acts as a synchronization hub, not the sole gatekeeper.
-
-## 3. Database Agnosticism: The "Super-SQL"
-
-The industry is fragmented into SQL (Postgres, MySQL) and NoSQL (MongoDB, Redis) camps. Developers often lock themselves into one vendor's dialect.
-
-ObjectStack introduces **ObjectQL**, a unified query language that compiles to any backend.
-
-* **Vendor Lock-in Freedom:** Start with SQLite for prototyping, migrate to PostgreSQL for production, and archive to Snowflake for analytics—without rewriting a single line of business logic.
-* **Best-in-Class Drivers:** We don't implement databases; we implement *drivers* that treat databases as dumb storage engines. We handle the complex logic (RBAC, Validation) in the Application Layer (The Kernel).
-
-
-## 3. Database Agnostic: The "Universal Compiler"
-
-Vendor lock-in is the enemy of longevity. A business application usually outlives the database technology it was originally built on.
-
-ObjectQL treats the underlying database as an **Implementation Detail**.
-
-### The Compiler Approach
-Instead of being a runtime wrapper (like an ORM), ObjectQL functions as a **Compiler**.
-1. **Input:** ObjectQL Abstract Syntax Tree (AST).
-2. **Process:** Compile AST into dialect-specific SQL.
-3. **Output:** Highly optimized queries for the target target.
-
-This architecture allows for radical flexibility:
-* **Dev:** Run on **SQLite** (Zero setup, single file).
-* **Prod:** Run on **PostgreSQL** (Robust, scalable).
-* **Edge:** Run on **Cloudflare D1** (Distributed).
-* **Legacy:** Connect to an existing **Oracle/SQL Server** (Integration).
-
-You change the *Driver*, not the *Code*.
-
-## Summary
-
-| Value | The Old Way | The ObjectStack Way |
-| :--- | :--- | :--- |
-| **Architecture** | Code-Driven (Imperative) | Protocol-Driven (Declarative) |
-| **Logic Location** | Scattered (DB + API + UI) | Centralized (JSON/YAML Schema) |
-| **Data Access** | Cloud-Dependent (Online Only) | Local-First (Offline + Sync) |
-| **Storage** | Locked to Vendor | Database Agnostic |
-
-By adhering to these values, we build software that is **resilient to change**, **respectful of user time**, and **technically sovereign**.
diff --git a/content/docs/concepts/enterprise-patterns.cn.mdx b/content/docs/concepts/enterprise-patterns.cn.mdx
deleted file mode 100644
index 605ba3d59..000000000
--- a/content/docs/concepts/enterprise-patterns.cn.mdx
+++ /dev/null
@@ -1,95 +0,0 @@
----
-title: 企业模式
-description: 使用协议驱动方法处理复杂的 ERP/CRM 业务逻辑(状态机、计算、RBAC)。
----
-
-import { Sliders, GitMerge, Calculator, BookOpen } from 'lucide-react';
-
-关于"低代码"或"协议驱动"平台的一个常见误解是它们只适用于简单的 CRUD 应用程序。
-
-虽然许多可视化构建器确实如此,但 **ObjectStack** 专门为企业资源计划(ERP)和客户关系管理(CRM)系统的复杂性而设计。我们不是通过隐藏复杂性来处理它,而是通过在协议中**显式建模**它来处理。
-
-以下是我们如何将常见的企业模式映射到 ObjectStack 架构。
-
-## 1. 工作流作为状态机(FSM)
-
-在企业软件中,记录(例如,"采购订单")很少只是静态数据。它是一个在生命周期中移动的活实体。
-
-### 反模式
-在控制器中编写分散的 `if/else` 逻辑:
-```javascript
-// 不要这样做
-if (order.status === 'draft' && user.role === 'manager') {
- order.status = 'approved';
-}
-```
-
-### ObjectStack 模式
-我们将生命周期定义为自动化协议(工作流)中的**有限状态机(FSM)**。这使业务流程具有确定性和可视化。
-
-```yaml
-# workflows/purchase_order.yaml
-name: purchase_approval
-object: purchase_order
-states:
- draft:
- initial: true
- on_exit: ['validate_budget']
- transitions:
- submit: pending_approval
- pending_approval:
- transitions:
- approve: approved
- reject: rejected
- guards:
- approve: "user.has_permission('approve_budget')"
- approved:
- final: true
-```
-
-## 2. 动态汇总(计算字段)
-
-ERP 系统通常需要"主-明细"数学。*示例:订单的总额是其行项目的总和。*
-
-### 反模式
-在每个报表中手动编写 SQL `SUM()` 查询,或使用难以调试的数据库触发器。
-
-### ObjectStack 模式
-我们在数据协议(对象 schema)中定义**汇总字段**。数据层编译器处理底层复杂性(通过实时 `JOIN` 或后台聚合)。
-
-```yaml
-# objects/order.yml
-fields:
- total_amount:
- type: summary
- summary_object: line_items
- summary_field: amount
- summary_type: sum
-```
-
-## 3. 多态关系
-
-CRM 系统通常需要"多对任意"关系。*示例:任务可以与潜在客户、联系人或客户相关。*
-
-### ObjectStack 模式
-我们使用具有多个目标的 `reference` 类型。
-
-```yaml
-# objects/task.yml
-fields:
- related_to:
- type: lookup
- reference_to: ['lead', 'contact', 'account', 'opportunity']
-```
-
-这指示数据层编译器生成必要的多态键(例如,`related_to_id` 和 `related_to_type` 列)。
-
-## 总结
-
-ObjectStack 通过**将模式提升为协议**来处理企业复杂性。
-
-| 模式 | 传统代码 | ObjectStack 协议 |
-| :--- | :--- | :--- |
-| **逻辑** | 意大利面条式 `if/else` | 状态机(YAML) |
-| **数学** | 手动循环/SQL | 虚拟/汇总字段 |
-| **关系** | 自定义连接表 | 多态引用 |
diff --git a/content/docs/concepts/enterprise-patterns.mdx b/content/docs/concepts/enterprise-patterns.mdx
deleted file mode 100644
index 4f93dd349..000000000
--- a/content/docs/concepts/enterprise-patterns.mdx
+++ /dev/null
@@ -1,95 +0,0 @@
----
-title: Enterprise Patterns
-description: Handling complex ERP/CRM business logic (State Machines, Calculations, RBAC) using the Protocol-Driven approach.
----
-
-import { Sliders, GitMerge, Calculator, BookOpen } from 'lucide-react';
-
-A common misconception about "Low-Code" or "Protocol-Driven" platforms is that they are only suitable for simple CRUD applications.
-
-While true for many visual builders, **ObjectStack** is architected specifically for the complexity of Enterprise Resource Planning (ERP) and Customer Relationship Management (CRM) systems. We handle complexity not by hiding it, but by **modeling it** explicitly in the protocol.
-
-Here is how we map common Enterprise Patterns to the ObjectStack architecture.
-
-## 1. Workflows as State Machines (FSM)
-
-In enterprise software, a record (e.g., a "Purchase Order") is rarely just static data. It is a living entity that moves through a lifecycle.
-
-### The Anti-Pattern
-Writing scattered `if/else` logic in controllers:
-```javascript
-// Don't do this
-if (order.status === 'draft' && user.role === 'manager') {
- order.status = 'approved';
-}
-```
-
-### The ObjectStack Pattern
-We define the lifecycle as a **Finite State Machine (FSM)** in the Automation Protocol (Workflow). This makes the business process deterministic and visualizeable.
-
-```yaml
-# workflows/purchase_order.yaml
-name: purchase_approval
-object: purchase_order
-states:
- draft:
- initial: true
- on_exit: ['validate_budget']
- transitions:
- submit: pending_approval
- pending_approval:
- transitions:
- approve: approved
- reject: rejected
- guards:
- approve: "user.has_permission('approve_budget')"
- approved:
- final: true
-```
-
-## 2. Dynamic Rollups (Calculated Fields)
-
-ERP systems often require "Master-Detail" math. *Example: An Order's Total is the sum of its Line Items.*
-
-### The Anti-Pattern
-Writing SQL `SUM()` queries manually in every report, or using Database Triggers that are hard to debug.
-
-### The ObjectStack Pattern
-We define **Summary Fields** in the Data Protocol (Object schema). The Data Layer compiler handles the underlying complexity (either by real-time `JOIN` or background aggregation).
-
-```yaml
-# objects/order.yml
-fields:
- total_amount:
- type: summary
- summary_object: line_items
- summary_field: amount
- summary_type: sum
-```
-
-## 3. Polymorphic Relationships
-
-CRM systems often need "Many-to-Any" relationships. *Example: A Task can be related to a Lead, a Contact, OR an Account.*
-
-### The ObjectStack Pattern
-We use the `reference` type with multiple targets.
-
-```yaml
-# objects/task.yml
-fields:
- related_to:
- type: lookup
- reference_to: ['lead', 'contact', 'account', 'opportunity']
-```
-
-This instructs the Data Layer compiler to generate the necessary polymorphic keys (e.g., `related_to_id` and `related_to_type` columns).
-
-## Summary
-
-ObjectStack handles enterprise complexity by **elevating patterns into protocols**.
-
-| Pattern | Traditional Code | ObjectStack Protocol |
-| :--- | :--- | :--- |
-| **Logic** | Spaghetti `if/else` | State Machines (YAML) |
-| **Math** | Manual Loops/SQL | Virtual/Summary fields |
-| **Relations** | Custom Join Tables | Polymorphic References |
diff --git a/content/docs/concepts/manifesto.cn.mdx b/content/docs/concepts/manifesto.cn.mdx
deleted file mode 100644
index 20636dd0b..000000000
--- a/content/docs/concepts/manifesto.cn.mdx
+++ /dev/null
@@ -1,102 +0,0 @@
----
-title: 宣言
-description: 管理 ObjectStack 生态系统的不可动摇的核心原则。后 SaaS 时代的宪法。
----
-
-import { ScrollText, Scale, Database, Code2 } from 'lucide-react';
-
-ObjectStack 的存在是为了将企业应用程序开发回归其本质:**数据**。
-
-为了维护一个健康、解耦和经得起未来考验的生态系统,我们承诺坚守以下不可动摇的核心原则。这些不是建议;它们是使我们获得自由的约束。
-
-
- }
- title="I. 协议中立性"
- description="协议即法律。实现仅仅是一种意见。"
- />
- }
- title="II. 机制优于策略"
- description="提供构建规则的工具,而不是硬编码规则本身。"
- />
- }
- title="III. 数据主权"
- description="数据属于用户,而不是 SaaS 提供商。"
- />
-
-
----
-
-## 原则 I:协议中立性
-
-**"协议是中立的。引擎是可替换的。"**
-
-ObjectQL 不得包含任何特定于特定语言(例如 Node.js)、数据库(例如 PostgreSQL)或运行时(例如浏览器)的逻辑。
-
-### 法则
-* **先规范后引擎:** 在规范层(`packages/spec`)编写任何功能之前,必须首先在规范层定义该功能。我们拒绝"先实现,后标准化"的方法。
-* **零泄漏:** 实现细节(如 React Hooks 使用或 SQL 特定语法)绝不能泄漏到协议定义中。
-
-### 好处
-这确保了今天定义的 ObjectStack 应用程序理论上可以在以下环境中运行:
-* 带 PostgreSQL 的 Node.js 服务器(今天的标准)
-* 带 SQLite 的 Python 服务器(AI/数据科学)
-* 浏览器中的 Rust WASM 模块(本地优先)
-
----
-
-## 原则 II:机制优于策略
-
-**"给他们物理学,而不是模拟。"**
-
-ObjectStack 提供**机制**("如何"):
-* *"这是你如何定义验证规则。"*
-* *"这是你如何定义权限范围。"*
-
-ObjectStack 从不规定**策略**("什么"):
-* *它从不说"密码必须是 8 个字符"。*
-* *它从不说"用户必须属于一个部门"。*
-
-### 关注点分离
-我们清晰地将**定义**与**执行**分离。
-
-| 层 | 职责 | 示例 |
-| :--- | :--- | :--- |
-| **协议(机制)** | 定义能力。 | `allowRead: string`(公式的插槽) |
-| **应用(策略)** | 定义业务逻辑。 | `allowRead: "$user.role == 'admin'"` |
-| **引擎(执行)** | 执行逻辑。 | 将公式编译为 SQL `WHERE` 子句。 |
-
----
-
-## 原则 III:单一数据源
-
-**"没有'代码'。只有 Schema。"**
-
-在传统应用程序中,"真相"是分散的:
-1. 数据库 Schema(`table.sql`)
-2. 后端模型(`User.ts`)
-3. 前端验证(`schema.zod.ts`)
-4. API 文档(`swagger.json`)
-
-在 ObjectStack 中,**对象协议是唯一的真相。**
-* 数据库是协议的*衍生物*。
-* UI 是协议的*投影*。
-* API 是协议的*结果*。
-
-如果你改变了协议,整个系统(DB、API、UI)必须自动适应。
-
----
-
-## 原则 IV:默认本地优先
-
-**"云是同步对等方,而不是主控方。"**
-
-我们拒绝软件在互联网连接中断时必须停止工作的观念。
-* **延迟是敌人:** 所有交互都应该是乐观的和即时的(0ms)。
-* **所有权是目标:** 用户的数据实质上存储在他们的设备上。服务器只是备份和协作的中心。
-
----
-
-> "我们塑造我们的工具,此后我们的工具塑造我们。" — 马歇尔·麦克卢汉
diff --git a/content/docs/concepts/meta.cn.json b/content/docs/concepts/meta.cn.json
deleted file mode 100644
index f7714888b..000000000
--- a/content/docs/concepts/meta.cn.json
+++ /dev/null
@@ -1,25 +0,0 @@
-{
- "title": "概念",
- "root": true,
- "pages": [
- "manifesto",
- "core-values",
- "architecture",
- "protocol-data",
- "protocol-driver",
- "protocol-permission",
- "protocol-ui",
- "protocol-system",
- "protocol-auth",
- "protocol-kernel",
- "protocol-hub",
- "protocol-ai",
- "protocol-api",
- "protocol-automation",
- "plugin-architecture",
- "security_architecture",
- "enterprise-patterns",
- "ai-codex",
- "terminology"
- ]
-}
diff --git a/content/docs/concepts/meta.json b/content/docs/concepts/meta.json
deleted file mode 100644
index 3e6e22122..000000000
--- a/content/docs/concepts/meta.json
+++ /dev/null
@@ -1,25 +0,0 @@
-{
- "title": "Concepts",
- "root": true,
- "pages": [
- "manifesto",
- "core-values",
- "architecture",
- "protocol-data",
- "protocol-driver",
- "protocol-permission",
- "protocol-ui",
- "protocol-system",
- "protocol-auth",
- "protocol-kernel",
- "protocol-hub",
- "protocol-ai",
- "protocol-api",
- "protocol-automation",
- "plugin-architecture",
- "security_architecture",
- "enterprise-patterns",
- "ai-codex",
- "terminology"
- ]
-}
diff --git a/content/docs/concepts/plugin-architecture.mdx b/content/docs/concepts/plugin-architecture.mdx
deleted file mode 100644
index 5cfc4f074..000000000
--- a/content/docs/concepts/plugin-architecture.mdx
+++ /dev/null
@@ -1,161 +0,0 @@
----
-title: Plugin Architecture
-description: The Extension Model and Microkernel Philosophy of ObjectStack.
----
-
-# Plugin Architecture
-
-ObjectStack follows a strict **Microkernel Architecture**. The core platform provides only the minimal runtime environment (Kernel), while all business capabilities, including standard ones like CRM or Project Management, are delivered as **Packages** (Apps or Plugins).
-
-## 1. Philosophy: "Kernel + Plugins"
-
-* **The Kernel**: Responsible for booting, identity, permission enforcement, and loading the manifest. It knows *nothing* about "Leads", "Tasks", or even "Kanban Boards" initially.
-* **The Plugins**: Teach the Kernel new tricks.
- * **Apps**: Combinations of data and UI for end-users (e.g., "Sales App").
- * **Plugins**: Extensions to the system capabilities (e.g., "BI Engine", "SAML Auth", "Stripe Payment").
-
-This separation ensures the platform remains lightweight and un-opinionated, allowing it to evolve indefinitely.
-
-## 2. Anatomy of a Plugin
-
-A plugin is defined by its `Manifest` (objectstack.config.ts) and its runtime `Entry` (index.ts).
-
-### The Manifest (`objectstack.config.ts`)
-
-Critically, the manifest declares **Dependencies**, **Configuration Rules**, and **Contributions**.
-
-```typescript
-// objectstack.config.ts
-import { ObjectStackManifest } from '@objectstack/spec';
-
-const plugin: ObjectStackManifest = {
- id: 'com.vendor.bi',
- version: '1.0.0',
- type: 'plugin',
-
- // 1. Configuration Schema (Settings)
- configuration: {
- title: 'BI Engine Settings',
- properties: {
- 'fullQueryMode': {
- type: 'boolean',
- default: false,
- description: 'Allow unrestricted SQL queries'
- },
- 'apiKey': {
- type: 'string',
- secret: true
- }
- }
- },
-
- // 2. Dependencies
- dependencies: {
- 'com.objectstack.core': '^2.0.0'
- },
-
- // 3. Contributions (Declarative Capabilities)
- contributes: {
- // Define new Metadata Kinds (File Types)
- kinds: [
- {
- id: 'bi.dataset',
- globs: ['**/*.dataset.json'],
- description: 'BI Dataset Definition'
- }
- ],
- // UI Contributions
- menus: {
- 'global/toolbar': [
- { id: 'open_dashboard', label: 'Open BI Dashboard', command: 'bi.open' }
- ]
- },
- // Server Actions (Exposed to Flows/API)
- actions: [
- {
- name: 'generate_forecast',
- label: 'Generate Sales Forecast',
- input: { startDate: 'date' }
- }
- ]
- },
-
- // 4. Runtime Entry
- extensions: {
- runtime: { entry: './src/index.ts' }
- }
-}
-```
-
-## 3. Runtime Context
-
-Plugins receive a rich strictly-typed `PluginContext` during their lifecycle. This context is the bridge to the host operating system.
-
-```typescript
-// src/index.ts
-import { PluginDefinition, PluginContextData } from '@objectstack/spec';
-
-const definition: PluginDefinition = {
- id: 'com.vendor.bi',
-
- onEnable: async (context: PluginContextData) => {
- // A. Access Type-Safe Context
- const { logger, ql, os, app, storage, i18n } = context;
-
- logger.info('Starting BI Engine...');
-
- // B. Use Scoped Storage (KV Store)
- const lastRun = await storage.get('last_run_timestamp');
-
- // C. Register Runtime Routes
- app.router.get('/bi/stats', async () => {
- return { active_reports: 10 };
- });
-
- // D. Interact with Core Data
- const data = await ql.object('account').find({ industry: 'Tech' });
-
- // E. Read Configuration
- const config = await os.getConfig('com.vendor.bi');
- if (config.fullQueryMode) {
- logger.warn('Running in Full Query Mode');
- }
- }
-}
-```
-
-## 4. Extension Capabilities
-
-### A. New Metadata Kinds (CRDs)
-
-This is the most powerful feature. A plugin can introduce entirely new concepts to the platform.
-
-* **Example**: A "BI Plugin" introduces `*.dataset.json` and `*.report.json`.
-* **Mechanism**: The Kernel uses the `contributes.kinds` registry to map file extensions to the plugin's parser.
-* **Result**: The IDE (cursor/vscode) and Runtime automatically recognize these files.
-
-### B. Service Providers
-
-Plugins can implement standard interfaces defined by the system.
-
-* **Auth Providers**: `plugin extends AuthProvider` (SAML, OAuth).
-* **Storage Drivers**: `plugin extends StorageDriver` (S3, MinIO).
-* **Notification Channels**: `plugin extends NotificationChannel` (Slack, SMS).
-
-## 4. Plugin Lifecycle
-
-The runtime manages the plugin states:
-
-1. **Resolve**: Read Manifest, validate dependencies.
-2. **Install (`onInstall`)**: Run migration scripts, setup initial data.
-3. **Boot (`onBoot`)**: Register generic services (before App load).
-4. **Enable (`onEnable`)**: Active and serving traffic.
-
-```typescript
-export class BiPlugin implements PluginLifecycle {
- async onEnable(context: PluginContext) {
- // Register the heavy engine only when enabled
- context.services.register('bi.engine', new BiAnalysisEngine());
- }
-}
-```
diff --git a/content/docs/concepts/protocol-ai.mdx b/content/docs/concepts/protocol-ai.mdx
deleted file mode 100644
index 1e96925dd..000000000
--- a/content/docs/concepts/protocol-ai.mdx
+++ /dev/null
@@ -1,175 +0,0 @@
----
-title: AI Protocol
-description: AI agents, RAG pipelines, natural language queries, predictive models, and cost tracking.
----
-
-import { Brain, Zap, DollarSign, Users, Target } from 'lucide-react';
-
-# AI Protocol
-
-The **AI Protocol** integrates artificial intelligence capabilities including AI agents, RAG (Retrieval-Augmented Generation) pipelines, natural language querying, and predictive analytics.
-
-## Why This Protocol Exists
-
-**Problem:** Every B2B SaaS wants "AI features" but building them is a nightmare:
-
-- **Data silos:** Your CRM data is in Postgres, docs in S3, knowledge base in Notion—LLMs can't access any of it
-- **Cost explosion:** One engineer accidentally racks up $10K OpenAI bill with unoptimized embeddings
-- **Context limitations:** GPT-4 has 128K token limit—your sales playbook is 500K tokens
-- **Hallucinations:** LLM invents plausible-sounding customer names and revenue numbers that don't exist
-- **Integration complexity:** To build "Ask questions about your data," you need: vector DB, embedding pipeline, chunking strategy, retrieval logic, prompt engineering, response streaming, and cost tracking
-
-Teams spend 6+ months building AI features from scratch—or give up and ship nothing.
-
-**Solution:** The AI Protocol provides **Copilot-grade AI infrastructure**. Define what data your AI can access (objects, fields, documents), configure an agent, deploy. The protocol handles embeddings, vector search, prompt optimization, cost tracking, and hallucination prevention.
-
-## Business Value Delivered
-
-
- }
- title="Ship AI Features in Days"
- description="Natural language search, chatbots, and predictive analytics—no ML expertise required."
- />
- }
- title="Control AI Costs"
- description="Built-in token counting, caching, and rate limiting. $10K/month budget? Hard-capped automatically."
- />
- }
- title="10x Support Efficiency"
- description="AI agents answer 80% of customer questions instantly. Support team focuses on complex issues."
- />
- }
- title="Increase Sales Win Rate"
- description="Predictive models identify which leads are 80% likely to close. Reps focus on hot prospects."
- />
-
-
-## What This Protocol Enables
-
-### AI Agents with Business Context
-Build **autonomous agents** that understand your business data:
-- **Customer support agent:** Answers product questions using docs, tickets, and knowledge base
-- **Sales assistant:** Searches CRM for accounts, creates opportunities, suggests next steps
-- **Data analyst agent:** Generates reports, charts, and insights from business data
-
-**Example:** User asks "Show me accounts in California with revenue over $1M that haven't been contacted in 30 days." The agent:
-1. Translates natural language to ObjectQL query
-2. Checks permissions (user can only see their territory)
-3. Executes query and formats results
-4. Suggests follow-up: "Would you like me to draft outreach emails?"
-
-**Why it matters:** Traditional chatbots use predefined scripts. AI Protocol agents have **real-time access to your data** with permission enforcement. They don't hallucinate customer names—they query the database.
-
-**Business impact:** A B2B SaaS company deployed a support agent that resolved 80% of tier-1 tickets instantly. Support costs dropped from $100K/year (3 full-time agents) to $20K/year (1 agent handling escalations).
-
-### RAG Pipelines for Accurate Answers
-**Retrieval-Augmented Generation (RAG)** prevents hallucinations:
-1. User asks "What's our refund policy?"
-2. Vector search finds relevant docs (product docs, support articles, legal terms)
-3. LLM answers using **only retrieved context**, not imagination
-4. Response includes citations: "According to Section 3.2 of Terms of Service..."
-
-**Supported data sources:**
-- **Structured data:** Objects in your database (Accounts, Orders, Products)
-- **Documents:** PDFs, Word docs, Markdown files in S3/Google Drive
-- **Web pages:** Your knowledge base, help center, blog posts
-- **APIs:** Live data from Salesforce, HubSpot, Zendesk
-
-**Real-world value:** A SaaS company embedded their 200-page product manual. Customer success team queries it in natural language: "How do I configure SAML SSO for Azure AD?" Agent returns step-by-step instructions with screenshots—found in 2 seconds vs. 10 minutes of manual searching.
-
-### Natural Language to SQL/ObjectQL
-Convert **plain English** to database queries:
-- "Show me top 10 opportunities by value" → `SELECT * FROM opportunities ORDER BY amount DESC LIMIT 10`
-- "How many deals did we close last quarter?" → `SELECT COUNT(*) FROM opportunities WHERE stage = 'Closed Won' AND close_date >= '2024-01-01'`
-- "Which sales rep has the highest win rate?" → Complex aggregation query with GROUP BY and JOIN
-
-**Why it matters:** Business users get insights without SQL knowledge. CEOs query revenue dashboards in plain English. Finance generates reports without opening Excel.
-
-**Safety features:**
-- **Permission-aware:** Query results filtered by user's row-level security
-- **Read-only:** Natural language can't generate DELETE or UPDATE queries
-- **Cost limits:** Expensive queries (full table scans) require approval
-
-### Predictive Models Without Data Science
-Train **machine learning models** on your business data:
-- **Churn prediction:** Which customers are 70%+ likely to cancel?
-- **Lead scoring:** Which leads are most likely to convert?
-- **Revenue forecasting:** Predict next quarter's sales based on pipeline
-
-**No code required:** Define features (e.g., "last activity date", "support ticket count") and target variable (e.g., "churned = yes/no"). The protocol trains and deploys the model.
-
-**Example:** A SaaS company trained a churn model:
-- **Features:** Last login date, support tickets, feature usage, contract value
-- **Result:** Model predicts churn with 85% accuracy
-- **Action:** Auto-triggers "win-back" campaign for at-risk customers
-
-**Value:** Reduced churn from 8% to 5%. $500K/year revenue saved.
-
-## Real-World Use Cases
-
-### Customer Support Automation
-**Challenge:** A SaaS company gets 500 support tickets/week. 70% are repetitive questions answered in docs.
-
-**AI Protocol Solution:** Deploy a support agent with access to:
-- Product documentation (RAG pipeline)
-- Past ticket resolutions (vector search)
-- Account data (ObjectQL queries with permission checks)
-
-Agent auto-responds to tickets with answers + citations. Escalates complex issues to humans.
-
-**Value:** Support ticket volume reduced by 65%. Response time: instant vs. 4-hour average. $120K/year cost savings.
-
-### Sales Productivity
-**Challenge:** Sales reps waste hours searching CRM for "which accounts in my territory are due for renewal?"
-
-**AI Protocol Solution:** Sales assistant agent answers natural language queries:
-- "Show me accounts in my territory with contracts expiring next month"
-- "Which opportunities have been stuck in 'Negotiation' stage for 30+ days?"
-- "Draft a follow-up email to Acme Corp about their Q4 budget"
-
-**Value:** Reps save 5 hours/week on data admin. Close 2 more deals/month. $500K/year revenue increase.
-
-### Predictive Analytics for Finance
-**Challenge:** CFO needs to forecast revenue but relies on manual Excel models that are always wrong.
-
-**AI Protocol Solution:** Train a **revenue forecasting model**:
-- Features: Pipeline value, historical close rates, seasonality, sales rep performance
-- Output: Revenue prediction with 90% confidence interval
-
-Model updates daily as new data arrives.
-
-**Value:** Forecast accuracy improved from 60% to 92%. Board meetings based on data, not gut feel.
-
-### Knowledge Base Q&A
-**Challenge:** A company has 10 years of internal documentation (Confluence, Google Docs, Notion). New employees can't find anything.
-
-**AI Protocol Solution:** Index all docs into RAG pipeline. Deploy internal chatbot:
-- "How do I submit expense reports?" → Links to HR policy doc
-- "What's the process for deploying to production?" → Engineering runbook
-- "Who owns the billing system?" → Team directory with contact info
-
-**Value:** Onboarding time reduced from 4 weeks to 2 weeks. Engineers stop asking repetitive questions in Slack.
-
-## Integration with Other Protocols
-
-- **Data Protocol:** Agents query objects with ObjectQL; permissions enforced automatically
-- **Permission Protocol:** Users only get AI answers for data they're allowed to see
-- **System Protocol:** Agent actions logged for audit (who asked what, when)
-- **API Protocol:** Expose AI endpoints as REST APIs (`/api/chat`, `/api/predict`)
-- **Automation Protocol:** Agents trigger workflows (e.g., "Create task if churn risk > 80%")
-
-**Key insight:** AI Protocol enables a **conversational interface** to your data. Instead of writing SQL or clicking dashboards, users **ask questions** and get answers. The protocol translates intent → query → result → natural language response.
-
-## Technical Reference
-
-For implementation guides and configuration details, see:
-
-- [Agent Reference](/docs/references/ai/agent/Agent) - Agent configuration, tools, and knowledge sources
-- [RAG Pipeline](/docs/references/ai/rag-pipeline/RAGPipelineConfig) - Vector stores, embedding models, chunking strategies
-- [Natural Language Query](/docs/references/ai/nlq/NLQRequest) - Query translation, confidence scoring, and result formatting
-- [Predictive Models](/docs/references/ai/predictive-model/PredictiveModel) - Feature engineering, training, and deployment
-- [Cost Tracking](/docs/references/ai/cost/CostConfig) - Token counting, budget enforcement, and usage analytics
diff --git a/content/docs/concepts/protocol-api.mdx b/content/docs/concepts/protocol-api.mdx
deleted file mode 100644
index 2198bdac1..000000000
--- a/content/docs/concepts/protocol-api.mdx
+++ /dev/null
@@ -1,185 +0,0 @@
----
-title: API Protocol
-description: REST contracts, API discovery, realtime subscriptions, and routing configuration.
----
-
-import { Zap, Shield, DollarSign, Users } from 'lucide-react';
-
-# API Protocol
-
-The **API Protocol** defines external communication interfaces including REST contracts, API discovery, realtime subscriptions via WebSocket/SSE, and routing configuration.
-
-## Why This Protocol Exists
-
-**Problem:** Modern apps need APIs for everything—web frontends, mobile apps, third-party integrations, webhooks. Building robust APIs is harder than it looks:
-
-- **Inconsistent contracts:** `/api/users` returns `{ data: [] }` but `/api/accounts` returns `{ results: [] }`—no standard
-- **No API discovery:** Developers must read outdated docs or reverse-engineer endpoints from network logs
-- **Rate limiting hell:** One power user DOS attacks your API, crashes the server, takes down everyone
-- **Realtime complexity:** Building WebSocket servers for live updates requires Redis pub/sub, connection state management, and reconnection logic
-- **Versioning nightmares:** API v1 and v2 running side-by-side, different authentication methods, no migration path
-
-Traditional approach: Write 500 lines of Express/Flask code per endpoint, copy-paste auth middleware, pray you don't introduce bugs.
-
-**Solution:** The API Protocol **auto-generates REST/GraphQL APIs** from your data model. Every object you define gets CRUD endpoints automatically. Realtime subscriptions, rate limiting, and versioning are configuration, not code.
-
-## Business Value Delivered
-
-
- }
- title="Ship APIs 10x Faster"
- description="Define a data object, get REST endpoints instantly. Zero boilerplate code to maintain."
- />
- }
- title="Zero API Security Bugs"
- description="Authentication, authorization, input validation, and rate limiting enforced by protocol—not developer discipline."
- />
- }
- title="Monetize API Access"
- description="Tier-based rate limits (Starter: 10K calls/month, Enterprise: unlimited). Auto-upgrade prompts for power users."
- />
- }
- title="Enable Third-Party Integrations"
- description="Self-documenting APIs let partners build integrations without back-and-forth with your eng team."
- />
-
-
-## What This Protocol Enables
-
-### Auto-Generated CRUD Endpoints
-Define an object in Data Protocol → get REST endpoints automatically:
-- `GET /api/data/account` - List accounts
-- `POST /api/data/account` - Create account
-- `GET /api/data/account/:id` - Get account by ID
-- `PATCH /api/data/account/:id` - Update account
-- `DELETE /api/data/account/:id` - Delete account
-
-**Advanced features auto-included:**
-- **Filtering:** `GET /api/data/account?filter[industry]=Technology`
-- **Sorting:** `GET /api/data/account?sort=-created_at` (descending)
-- **Pagination:** `GET /api/data/account?page=2&per_page=25`
-- **Field selection:** `GET /api/data/account?fields=name,industry` (reduce payload size)
-- **Relations:** `GET /api/data/account?include=opportunities,contacts` (eager loading)
-
-**Why it matters:** A startup launches with 10 objects (Account, Contact, Opportunity, etc.). That's **50 REST endpoints** automatically. Add a new object? 5 more endpoints appear instantly. Zero code.
-
-**Real-world impact:** A SaaS company needed a mobile app. Backend team said "3-month API development." CEO found ObjectStack, deployed it, mobile team had APIs in 2 days. App launched 10 weeks early.
-
-### API Discovery and Self-Documentation
-Every API exposes a **discovery endpoint** (`/api/discovery`) that returns:
-- Available objects and their schemas
-- All endpoints with HTTP methods
-- Authentication requirements
-- Rate limits
-- Example requests/responses
-
-**Use cases:**
-- **Postman collections:** Auto-generate from discovery endpoint
-- **SDK generation:** TypeScript/Python/Go SDKs generated from API schema
-- **Partner integrations:** Third parties build integrations without asking your team for docs
-
-**Business value:** A company opens their API to partners. Partners build Zapier/Make.com integrations without 10 email threads asking "what's the schema for orders?"
-
-### Realtime Data Subscriptions
-Support **live updates** without polling:
-- **WebSocket:** Bi-directional real-time connection (chat apps, collaborative editing)
-- **Server-Sent Events (SSE):** One-way server-to-client streaming (dashboards, notifications)
-
-**Example:** Subscribe to new opportunities:
-```javascript
-// Client subscribes
-const subscription = api.subscribe('opportunity.created', {
- filter: { stage: 'Negotiation' }
-});
-
-// Server pushes updates
-subscription.on('data', (opportunity) => {
- console.log('New opportunity:', opportunity);
-});
-```
-
-**Why it matters:** Traditional polling (`setInterval(() => fetch('/api/opportunities'), 5000)`) wastes bandwidth and delays updates. Realtime subscriptions deliver updates **instantly** with zero overhead.
-
-**Real-world use case:** A logistics app shows package locations on a map. With polling, map updates every 10 seconds (laggy, wasteful). With subscriptions, map updates the moment a driver scans a package (instant, efficient).
-
-### Rate Limiting and Quota Enforcement
-Prevent API abuse with **declarative rate limits**:
-- **Per-endpoint limits:** `/api/data/account` = 100 requests/minute, `/api/export` = 5 requests/hour
-- **Per-user limits:** Free tier = 1K calls/month, Pro tier = 100K calls/month
-- **Global limits:** Max 10K concurrent connections
-
-When a user exceeds their quota:
-- **Soft limit:** Return `HTTP 429 Too Many Requests` with retry-after header
-- **Hard limit:** Block API access until billing cycle resets
-- **Auto-upgrade prompt:** "You've used 95% of your API quota. Upgrade to Pro for unlimited calls?"
-
-**Business value:** A freemium SaaS gives 10K API calls/month for free. Power users hit the limit in 2 weeks and upgrade to $99/month plan. $50K/year revenue from API monetization.
-
-### API Versioning Without Pain
-Run **multiple API versions** simultaneously:
-- `GET /api/v1/account` - Legacy format
-- `GET /api/v2/account` - New format with breaking changes
-
-Clients specify version via header: `X-API-Version: 2` or URL: `/api/v2/...`
-
-**Migration strategy:**
-1. Deploy v2 with new schema
-2. Support v1 and v2 in parallel for 6 months
-3. Send deprecation warnings: `Deprecated: true, sunset: 2025-06-01`
-4. Retire v1
-
-**Why it matters:** Breaking changes don't break existing integrations. Partners migrate on their schedule, not yours.
-
-## Real-World Use Cases
-
-### Mobile App Backend
-**Challenge:** A startup needs a backend API for iOS/Android apps. They have no backend engineers.
-
-**API Protocol Solution:** Define objects (User, Post, Comment), deploy ObjectStack, get REST APIs. Mobile app authenticates via OAuth, calls `/api/data/post` to fetch feed.
-
-**Value:** Shipped mobile app in 6 weeks with 1 full-stack engineer (vs. 3-month timeline with dedicated backend team).
-
-### Third-Party Integration Platform
-**Challenge:** A CRM vendor wants partners to build integrations (Zapier, Make.com, custom apps). Partners demand a well-documented API.
-
-**API Protocol Solution:** Enable API discovery. Partners hit `/api/discovery`, get full schema, generate SDKs, build integrations.
-
-**Value:** 50+ partner integrations built in 6 months. Marketplace ecosystem drives 30% of new customer acquisition.
-
-### Realtime Dashboard
-**Challenge:** A SaaS app has a revenue dashboard that polls `/api/revenue` every 5 seconds. 1,000 concurrent users = 12M API calls/hour, killing the database.
-
-**API Protocol Solution:** Switch to SSE subscriptions. Server pushes revenue updates only when data changes (e.g., new sale). Clients subscribe once, receive updates passively.
-
-**Value:** API load reduced by 95%. Database CPU usage dropped from 80% to 10%. $5K/month infrastructure savings.
-
-### API Monetization
-**Challenge:** A data analytics company wants to sell API access: Starter tier (10K calls/month) for $99, Pro tier (1M calls/month) for $499.
-
-**API Protocol Solution:** Configure rate limits per subscription tier. When users exceed quota, auto-block and show upgrade prompt.
-
-**Value:** $200K/year revenue from API subscriptions. Zero ops overhead—rate limiting is declarative config.
-
-## Integration with Other Protocols
-
-- **Data Protocol:** APIs expose objects defined in Data Protocol; field-level security enforced
-- **Permission Protocol:** API calls filtered by user's row-level security and object permissions
-- **Auth Protocol:** API authentication via JWT, OAuth, or API keys
-- **System Protocol:** API calls logged for audit; rate limit violations trigger alerts
-- **Automation Protocol:** Webhooks invoke workflows when API events occur
-
-**Key insight:** API Protocol is the **interface layer** of ObjectStack. It exposes your business logic (data, workflows, permissions) to the outside world—web apps, mobile apps, partners, IoT devices—with security and scalability built-in.
-
-## Technical Reference
-
-For detailed API specifications and implementation guides, see:
-
-- [REST Contracts](/docs/references/api/contract/BaseResponse) - Request/response envelopes, error codes, and pagination
-- [API Discovery](/docs/references/api/discovery/Discovery) - Schema introspection and endpoint metadata
-- [Realtime Subscriptions](/docs/references/api/realtime/RealtimeEvent) - WebSocket and SSE event streaming
-- [Rate Limiting](/docs/references/api/rate-limit/RateLimitConfig) - Quota enforcement and throttling strategies
-- [Routing Configuration](/docs/references/api/routing/RouteDefinition) - Custom endpoints and middleware
diff --git a/content/docs/concepts/protocol-auth.mdx b/content/docs/concepts/protocol-auth.mdx
deleted file mode 100644
index 6efb6601b..000000000
--- a/content/docs/concepts/protocol-auth.mdx
+++ /dev/null
@@ -1,150 +0,0 @@
----
-title: Auth Protocol
-description: Identity and access management with multiple authentication strategies, roles, and organization management.
----
-
-import { Shield, Zap, DollarSign, Target } from 'lucide-react';
-
-# Auth Protocol
-
-The **Auth Protocol** manages identity, authentication, sessions, roles, and organization structure. It supports multiple authentication strategies including OAuth, SAML, LDAP, and passwordless authentication.
-
-## Why This Protocol Exists
-
-**Problem:** Modern applications face an authentication nightmare:
-
-- **Consumer apps:** Users expect "Sign in with Google/Apple/GitHub"—building OAuth flows from scratch takes weeks
-- **Enterprise apps:** Companies demand SAML SSO with Okta/Azure AD—implementing SAML 2.0 spec requires months of debugging XML signatures
-- **Security requirements:** Password policies, 2FA, session management, account lockouts, suspicious login detection—each adds weeks of dev time
-- **Multi-tenancy:** SaaS apps need per-tenant auth configs (Acme Corp uses Okta, SmallCo uses email/password)
-
-Traditional solutions: Roll your own auth (6 months of work, guaranteed security bugs), or use Auth0/Firebase Auth ($10K/month for 100K users). Neither is ideal for startups or enterprises with special requirements.
-
-**Solution:** The Auth Protocol provides **Salesforce/Okta-grade authentication** as infrastructure. OAuth, SAML, LDAP, magic links, passkeys, and 2FA work out-of-the-box. Multi-tenant configurations supported. Security policies (password complexity, session timeouts, IP allowlists) are declarative, not code.
-
-## Business Value Delivered
-
-
- }
- title="Enterprise Sales Ready"
- description="Fortune 500 won't buy without SAML SSO. Deploy Okta/Azure AD integration in hours, not months."
- />
- }
- title="$100K/Year Auth Cost Savings"
- description="Auth0 charges $10K/month at scale. ObjectStack's included auth is free—no per-MAU pricing."
- />
- }
- title="Ship Login Faster"
- description="Google/GitHub OAuth in 10 lines of config, not 500 lines of code. Magic links with zero email infrastructure."
- />
- }
- title="Zero Security Incidents"
- description="Bcrypt hashing, session rotation, CSRF protection, rate limiting—all default. No password breaches."
- />
-
-
-## What This Protocol Enables
-
-### Every Auth Method, One Interface
-Support **all authentication methods** without writing integration code:
-- **OAuth 2.0:** Google, Microsoft, GitHub, Apple, Facebook, Twitter
-- **SAML 2.0:** Okta, Azure AD, OneLogin, Auth0
-- **LDAP/Active Directory:** On-premises enterprise directory services
-- **Magic Links:** Passwordless email authentication (Slack-style)
-- **Passkeys:** WebAuthn/FIDO2 biometric authentication
-- **2FA/MFA:** TOTP (Authenticator apps), SMS, email codes, backup codes
-
-**Why it matters:** An early-stage startup starts with email/password. As they land enterprise customers, they add Okta SAML. Later, they add Google OAuth for freemium users. **All three work simultaneously** with different user pools—no code changes.
-
-**Real-world impact:** A B2B SaaS company won a $500K enterprise deal because they deployed Okta SSO in 2 days. Their competitor's bid included "SAML integration: 3-month timeline, $50K additional."
-
-### Per-Tenant Auth Configuration
-In a multi-tenant SaaS, each tenant can have **different auth requirements**:
-- **Acme Corp (Enterprise):** Okta SAML required, 2FA enforced, password rotation every 90 days
-- **SmallCo (Startup):** Email/password or Google OAuth, optional 2FA
-- **FinCorp (Regulated):** Azure AD SAML required, IP allowlist, session timeout after 30 min
-
-ObjectStack's Auth Protocol lets you define **auth policies per organization**, not globally.
-
-**Business value:** Win enterprise deals without sacrificing startup-friendly onboarding. Compliance-heavy customers get strict policies; casual users get frictionless signup.
-
-### Session Management and Security
-Built-in protection against every auth attack:
-- **Session fixation:** Session IDs regenerated after login
-- **Session hijacking:** Detect concurrent sessions from different IPs, force re-login
-- **CSRF attacks:** CSRF tokens automatically injected and validated
-- **Brute force:** Account locked after 5 failed login attempts
-- **Credential stuffing:** Detect login attempts with leaked passwords (HaveIBeenPwned integration)
-
-**Audit trail:** Every login, logout, failed attempt, password change, and permission escalation is logged with IP, device, and timestamp.
-
-**Compliance value:** A healthcare company passed SOC 2 Type II audit on first attempt because auth events were logged and tamper-proof.
-
-### Organization and Team Management
-Multi-tenant SaaS requires **organization hierarchies**:
-- **Organizations:** Top-level tenant (e.g., "Acme Corp")
-- **Roles:** Admin, Member, Billing Manager, Support Agent
-- **Invitations:** Email-based invites with expiration and role assignment
-- **SSO enforcement:** Require SAML for all org members
-
-**Real-world scenario:** A company buys your SaaS. Their admin invites 50 employees, assigns roles, and configures Okta SSO. Employees log in via SSO—no password setup needed.
-
-## Real-World Use Cases
-
-### Enterprise SSO Requirement
-**Challenge:** A startup demos their product to a Fortune 500 company. Procurement says "we need Okta SAML SSO or the deal is off."
-
-**Auth Protocol Solution:** Configure SAML provider in 10 lines:
-```
-saml.entryPoint = "https://okta.bigcorp.com/saml/sso"
-saml.cert = ""
-```
-Test, deploy, win deal.
-
-**Value:** $1M ARR deal won. Competitor without SAML lost the deal despite having better features.
-
-### Passwordless Onboarding
-**Challenge:** A consumer app wants Slack-style "magic link" login—no passwords, no OAuth popups, just email.
-
-**Auth Protocol Solution:** Enable magic link provider. User enters email, receives login link, clicks, authenticated.
-
-**Value:** 40% higher signup conversion vs. password forms. No "forgot password" support tickets.
-
-### Multi-Region Compliance
-**Challenge:** A fintech app operates in EU (GDPR) and US (SOC 2). EU requires 2FA for all users; US allows optional 2FA.
-
-**Auth Protocol Solution:** Define **auth policies per tenant**:
-- EU tenants: `mfaRequired: true`
-- US tenants: `mfaRequired: false`
-
-**Value:** Passed GDPR audit. $5M fine avoided. No code changes—just configuration.
-
-### Account Takeover Prevention
-**Challenge:** A B2C app detects 10K failed login attempts from a botnet trying credential stuffing (leaked passwords from other breaches).
-
-**Auth Protocol Solution:** Built-in rate limiting (10 attempts/minute per IP) and account lockout (lock after 5 failures). Suspicious login detection alerts user via email: "Login from new device in Russia—was this you?"
-
-**Value:** Zero successful account takeovers. Customer trust maintained. $2M in fraud losses prevented.
-
-## Integration with Other Protocols
-
-- **Permission Protocol:** Roles defined in Auth Protocol map to object permissions
-- **System Protocol:** Authentication events logged for audit compliance
-- **API Protocol:** API keys and JWT tokens managed via Auth Protocol
-- **UI Protocol:** Login forms and user profile pages auto-generated from auth configuration
-
-**Key insight:** Auth Protocol is the **front door** to ObjectStack. Every API call, UI interaction, and automation flow starts with authentication. The protocol ensures that "who you are" is verified before "what you can do" is evaluated.
-
-## Technical Reference
-
-For detailed configuration and implementation guides, see:
-
-- [User Identity](/docs/references/auth/identity/User) - User schema, email/phone verification, and profile management
-- [Authentication Providers](/docs/references/auth/config/AuthConfig) - OAuth, SAML, LDAP, magic link, and passkey configuration
-- [Session Management](/docs/references/auth/session/Session) - Session lifecycle, timeouts, and concurrent session handling
-- [Role and Permission Mapping](/docs/references/auth/role/Role) - Role hierarchies and permission assignment
-- [Organization Structure](/docs/references/auth/organization/Organization) - Multi-tenant organization, member, and invitation management
diff --git a/content/docs/concepts/protocol-automation.mdx b/content/docs/concepts/protocol-automation.mdx
deleted file mode 100644
index bd66ccbc9..000000000
--- a/content/docs/concepts/protocol-automation.mdx
+++ /dev/null
@@ -1,191 +0,0 @@
----
-title: Automation Protocol
-description: Workflows, visual flows, and webhooks for business process automation.
----
-
-import { Zap, DollarSign, Users, Target } from 'lucide-react';
-
-# Automation Protocol
-
-The **Automation Protocol** provides business process automation through workflows (state machines), visual flows, and webhooks.
-
-## Why This Protocol Exists
-
-**Problem:** Business processes have logic that doesn't belong in code:
-
-- "When a deal closes, create an invoice, notify accounting, update the forecast, and send a thank-you email"
-- "When a support ticket goes 48 hours without response, escalate to a manager"
-- "When inventory drops below 100 units, auto-generate a purchase order"
-
-Traditional solutions force you to:
-1. **Hard-code business logic:** Every process change requires developer time, code review, deployment
-2. **Use separate tools:** Zapier for simple tasks, Temporal for complex workflows—two systems, no integration
-3. **Lack visibility:** When automation breaks, nobody knows why or how to fix it
-
-**Real-world cost:** A company has 50 "automated processes" scattered across cron jobs, Lambda functions, and Zapier workflows. One breaks every week. Engineers spend 20% of their time debugging automations instead of building features.
-
-**Solution:** The Automation Protocol provides **Salesforce/ServiceNow-grade workflow automation** as metadata. Define triggers, conditions, and actions declaratively. Visual flow builder for complex processes. Webhooks for third-party integrations. All monitored, versioned, and auditable.
-
-## Business Value Delivered
-
-
- }
- title="Ship Automations 10x Faster"
- description="Business analysts build workflows without developer intervention. IT becomes enablers, not bottlenecks."
- />
- }
- title="$100K/Year Labor Savings"
- description="Automate manual tasks: sending emails, updating records, generating reports. 10 hours/week saved per employee."
- />
- }
- title="Zero Process Inconsistency"
- description="Automations enforce SOP compliance. No 'I forgot to notify the manager' human errors."
- />
- }
- title="Instant Process Changes"
- description="Sales process changes? Update workflow, deploy in minutes. No code changes, no developer sprints."
- />
-
-
-## What This Protocol Enables
-
-### Declarative Workflow Rules
-Build **event-driven automations** that trigger when data changes:
-
-**Example:** Auto-assign leads based on territory
-- **Trigger:** Record created on Lead object
-- **Condition:** Lead status = "New" AND State is not blank
-- **Actions:**
- 1. Update "Owner" field to user in matching territory
- 2. Send email notification to new owner
- 3. Create follow-up task due in 2 days
-
-**Why it matters:** Business users configure this in the UI—no code, no developer needed. Marketing changes lead routing rules? Update the workflow and redeploy in 30 seconds.
-
-**Real-world impact:** A B2B company had leads manually assigned by ops team (20 hours/week). After automating lead assignment, ops team focused on revenue operations strategy. $50K/year labor savings.
-
-### Visual Flow Builder
-For **complex multi-step processes**, use the visual flow builder (think Salesforce Flow or n8n):
-
-**Example:** Opportunity approval process
-1. **Start:** User submits opportunity for approval
-2. **Decision:** Is amount > $100K?
- - **Yes:** Route to VP Sales for approval
- - **No:** Auto-approve
-3. **Screen:** VP sees approval form with notes field
-4. **Decision:** VP approved?
- - **Yes:** Update stage to "Closed Won", create invoice, notify accounting
- - **No:** Update stage to "Closed Lost", send rejection email
-5. **End**
-
-**Nodes supported:** Start, Decision (if/then), Screen (user input), Action (call API, update record, send email), Loop, Subflow
-
-**Why it matters:** Processes that require human input (approvals, multi-step wizards) are trivial to build. Non-developers can build Salesforce-grade automation.
-
-### Webhooks for External Integrations
-Trigger **HTTP callbacks** when events occur:
-
-**Example:** Notify Slack when high-value deal closes
-- **Trigger:** Opportunity record updated
-- **Condition:** Stage changed to "Closed Won" AND Amount > $50K
-- **Action:** POST to Slack webhook with deal details
-
-**Supported integrations:**
-- **Slack:** Channel notifications
-- **Email:** SendGrid, Mailgun, AWS SES
-- **CRMs:** Salesforce, HubSpot, Pipedrive
-- **Accounting:** QuickBooks, Xero, Stripe
-- **Custom:** Any HTTP endpoint
-
-**Business value:** A company integrated their CRM with QuickBooks. When a deal closes, an invoice is auto-created in QuickBooks. Accounting team saves 5 hours/week on manual data entry.
-
-### State Machine Workflows
-For **complex lifecycle management**, use state machines:
-
-**Example:** Order fulfillment workflow
-- **States:** Pending → Processing → Shipped → Delivered → Completed
-- **Transitions:** Can only move from Pending to Processing (not directly to Shipped)
-- **Actions on transition:** Pending → Processing triggers "Reserve inventory" action
-- **Guards:** Can't transition to Shipped if payment failed
-
-**Why it matters:** Prevents invalid state transitions. An order can't be marked "Delivered" if it was never "Shipped"—enforced automatically.
-
-## Real-World Use Cases
-
-### Sales Process Automation
-**Challenge:** A company's sales process has 10 steps from lead to closed deal. Each step requires data entry, email notifications, and CRM updates. Sales reps forget steps, deals stall.
-
-**Automation Protocol Solution:**
-1. Lead created → Auto-assign to territory rep, send welcome email
-2. Lead qualified → Create opportunity, notify manager
-3. Demo scheduled → Send calendar invite, update stage
-4. Proposal sent → Create quote record, set follow-up reminder
-5. Deal closed → Create invoice, notify accounting, update forecast
-
-All automated. Sales reps just move stages; everything else happens automatically.
-
-**Value:** Sales cycle reduced from 45 days to 30 days. Win rate increased 15% (fewer dropped leads). $1M/year revenue impact.
-
-### Customer Onboarding
-**Challenge:** New customer onboarding has 20 steps (create account, send welcome email, schedule kickoff call, provision environment, etc.). Ops team manually tracks spreadsheets, misses steps.
-
-**Automation Protocol Solution:** Build onboarding workflow:
-1. Customer signs contract → Create account, assign CSM
-2. Day 0: Send welcome email with login credentials
-3. Day 1: Create Slack channel, invite customer
-4. Day 3: Schedule kickoff call
-5. Day 7: Send onboarding survey
-6. Day 30: Trigger "renewal reminder" task
-
-**Value:** Onboarding time reduced from 2 weeks to 3 days. Customer satisfaction (CSAT) score increased from 7.5 to 9.2. $200K/year ops savings.
-
-### Compliance Automation
-**Challenge:** A fintech company must send monthly statements to customers, archive for 7 years, and notify regulators if balance > $10K. Manual process, error-prone.
-
-**Automation Protocol Solution:**
-- **Scheduled job:** Generate statements on 1st of each month
-- **Workflow:** For each account:
- 1. Generate PDF statement
- 2. Upload to S3 with 7-year retention
- 3. Send email to customer
- 4. If balance > $10K, notify compliance team
-
-**Value:** Significantly reduced compliance violations. Passed audit on first attempt. Avoided potential regulatory fines.
-
-### Multi-Channel Notifications
-**Challenge:** When a critical event occurs (e.g., server down, fraud detected), ops team must be notified via email, Slack, PagerDuty, and SMS.
-
-**Automation Protocol Solution:**
-- **Trigger:** System event "critical_alert"
-- **Actions (parallel):**
- 1. Send email to ops@company.com
- 2. POST to Slack webhook
- 3. Create PagerDuty incident
- 4. Send SMS via Twilio
-
-All four channels notified simultaneously, guaranteed delivery.
-
-**Value:** Incident response time reduced from 15 minutes (someone notices email) to 30 seconds (PagerDuty alert). $2M/year saved from downtime reduction.
-
-## Integration with Other Protocols
-
-- **Data Protocol:** Workflows trigger on record create/update/delete events
-- **Permission Protocol:** Workflows respect permissions (can't assign record to user without access)
-- **System Protocol:** Scheduled workflows run via job scheduler; events logged for audit
-- **API Protocol:** Webhooks call external APIs; workflows can be triggered via REST endpoints
-- **UI Protocol:** Action buttons in UI trigger workflows (e.g., "Approve" button runs approval flow)
-
-**Key insight:** Automation Protocol is the **orchestration layer** of ObjectStack. It coordinates actions across data, APIs, and external systems—turning isolated events into cohesive business processes.
-
-## Technical Reference
-
-For implementation guides and configuration details, see:
-
-- [Workflow Rules](/docs/references/automation/workflow/WorkflowRule) - Triggers, conditions, and action configuration
-- [Visual Flow Builder](/docs/references/automation/flow/Flow) - Node types, decision logic, and screen flows
-- [Webhook Configuration](/docs/references/automation/webhook/Webhook) - HTTP callbacks, retry policies, and payload templates
-- [State Machines](/docs/references/automation/state-machine/StateMachine) - State transitions, guards, and lifecycle management
diff --git a/content/docs/concepts/protocol-data.mdx b/content/docs/concepts/protocol-data.mdx
deleted file mode 100644
index 77e629e49..000000000
--- a/content/docs/concepts/protocol-data.mdx
+++ /dev/null
@@ -1,134 +0,0 @@
----
-title: Data Protocol
-description: The foundation of ObjectStack - defining business data models, validation rules, and query language.
----
-
-import { Database, CheckCircle, Target, Zap } from 'lucide-react';
-
-# Data Protocol
-
-The **Data Protocol** is the foundation of ObjectStack's data layer (ObjectQL). It defines the core business data model including object schemas, field types, validation rules, and the query language.
-
-## Why This Protocol Exists
-
-**Problem:** Traditional software development requires developers to manually write database schemas, validation logic, and query code for each database system. When business requirements change, developers must update schemas, migrate data, and modify countless SQL queries across the application. This creates:
-
-- **Vendor Lock-in:** Switching from PostgreSQL to MongoDB requires rewriting the entire data layer
-- **Inconsistent Validation:** Business rules scattered across frontend, backend, and database triggers
-- **Slow Iteration:** Schema changes require coordinated deployments and complex migration scripts
-- **Poor Developer Experience:** Writing boilerplate CRUD code instead of focusing on business logic
-
-**Solution:** The Data Protocol provides a **single source of truth** for your business data model. Define your entities once in a declarative, database-agnostic format, and ObjectStack automatically:
-- Generates database schemas for any supported backend (SQL, NoSQL, Graph, Time-series)
-- Enforces validation rules consistently across all layers
-- Migrates data when schemas evolve
-- Optimizes queries for the underlying database
-
-## Business Value Delivered
-
-
- }
- title="10x Faster Development"
- description="No boilerplate CRUD code. Define objects declaratively and get REST APIs, UIs, and validation automatically."
- />
- }
- title="Database Portability"
- description="Start with SQLite, scale to PostgreSQL, add MongoDB for documents—no code changes required."
- />
- }
- title="Business Logic as Data"
- description="Business analysts can define fields and validation rules without developer intervention."
- />
- }
- title="Zero Data Inconsistency"
- description="Validation enforced at the protocol level prevents bad data at write time, not query time."
- />
-
-
-## What This Protocol Enables
-
-### Business Entity Definition
-**Objects** are business entities like "Customer", "Order", "Invoice", "Project". Instead of writing CREATE TABLE statements, you define what the entity *means* to your business. ObjectStack handles the rest:
-- Auto-generates database tables/collections
-- Creates REST/GraphQL APIs
-- Builds admin UIs with forms and lists
-- Enables full-text search
-- Tracks field history for compliance
-
-**Real-world impact:** A 3-person startup can build a CRM with enterprise-grade data modeling capabilities comparable to major platforms, without hiring database architects or DevOps engineers.
-
-### Rich Field Types
-ObjectStack provides **20+ specialized field types** that encode business semantics, not just data types:
-- **Lookup Fields:** Relationships that maintain referential integrity (like foreign keys, but smarter)
-- **Formula Fields:** Auto-calculated values (e.g., `total = quantity × price`) that update in real-time
-- **Rollup Summary:** Aggregate child records (e.g., "Total opportunity value" on Account)
-- **Currency Fields:** Store amounts with currency codes, automatic exchange rate conversion
-- **Address/Location Fields:** Geocoding, distance calculations, territory assignment
-
-**Why it matters:** These aren't just data types—they're business logic primitives. A "lookup" field knows it should display a dropdown in the UI, validate referential integrity, and support cascading deletes. You declare the *intent*, ObjectStack handles the *implementation*.
-
-### Database-Agnostic Query Language
-The protocol defines queries as **Abstract Syntax Trees (AST)**, not SQL strings. This means:
-- Write one query, run on PostgreSQL, MongoDB, or Excel
-- Automatically optimize for the target database (indexes, joins, etc.)
-- Type-safe queries validated at compile time
-- No SQL injection vulnerabilities
-
-**Example use case:** A company starts with PostgreSQL, adds MongoDB for product catalogs, and Redis for caching. The same ObjectQL query (`find customers where industry = 'tech'`) works across all three—no code changes.
-
-### Validation as First-Class Citizen
-Business rules are defined alongside the data model, not scattered in application code:
-- **Cross-field validation:** "If account type is Enterprise, revenue is required"
-- **State machine validation:** "Can't close an opportunity without a quote"
-- **Async validation:** "Check if email domain is blacklisted via external API"
-- **Custom error messages:** Business-friendly error messages, not database errors
-
-**Business impact:** Prevent $10M data quality issues caused by invalid records. Validation rules are auditable, testable, and versionable alongside your schema.
-
-## Real-World Use Cases
-
-### SaaS Multi-Tenancy
-**Challenge:** Building a SaaS product where each customer needs isolated data, but you want to avoid managing hundreds of separate databases.
-
-**Data Protocol Solution:** Define tenant-scoped objects with automatic row-level isolation. ObjectStack ensures Customer A can never query Customer B's data, even if they share the same PostgreSQL database.
-
-**Value:** Launch a multi-tenant SaaS in weeks, not months. Add customers without infrastructure changes.
-
-### Offline-First Mobile Apps
-**Challenge:** Sales reps need to access CRM data on planes, in areas with poor connectivity, and must sync changes when back online.
-
-**Data Protocol Solution:** The same object definitions work with SQLite (on-device) and PostgreSQL (cloud). Queries, validation, and business logic are identical. Conflict resolution is built into the protocol.
-
-**Value:** Your field team stays productive even when offline. No "save failed" errors that lose $100K deals.
-
-### Legacy System Migration
-**Challenge:** You have data in Oracle, MongoDB, and Excel spreadsheets. You want to unify them without a 2-year ETL project.
-
-**Data Protocol Solution:** Define a unified object model, then map each legacy system via a Driver. Data stays in place initially, queries federate across all three. Migrate incrementally as needed.
-
-**Value:** Decouple business logic from legacy tech debt. Retire old systems on your schedule, not the vendor's EOL deadline.
-
-## Integration with Other Protocols
-
-The Data Protocol is the foundation that other protocols build upon:
-
-- **Driver Protocol:** Compiles ObjectQL queries to PostgreSQL, MongoDB, Redis, etc.
-- **Permission Protocol:** Enforces "who can see what" at the data layer, before queries execute
-- **UI Protocol:** Auto-generates forms, tables, and dashboards from object schemas
-- **API Protocol:** Exposes objects as REST/GraphQL endpoints with zero code
-- **Automation Protocol:** Triggers workflows when data changes (e.g., "Send email when deal closes")
-
-**Key insight:** Define your data model once. Everything else—UIs, APIs, permissions, workflows—is auto-generated and stays synchronized.
-
-## Technical Reference
-
-For detailed schema definitions, TypeScript interfaces, and implementation examples, see:
-
-- [Object Schema Reference](/docs/references/data/object/Object) - Complete schema structure and field options
-- [Query Language Reference](/docs/references/data/query/Query) - AST structure and filter operators
-- [Validation Rules Reference](/docs/references/data/validation/ValidationRule) - Formula syntax and validation types
-- [Field Types Guide](/docs/guides/field-types) - All 20+ field types with code examples
diff --git a/content/docs/concepts/protocol-driver.mdx b/content/docs/concepts/protocol-driver.mdx
deleted file mode 100644
index 278450feb..000000000
--- a/content/docs/concepts/protocol-driver.mdx
+++ /dev/null
@@ -1,140 +0,0 @@
----
-title: Driver Protocol
-description: Database adapters connecting ObjectStack to PostgreSQL, MongoDB, SQLite, and other storage engines.
----
-
-import { Plug, Zap, Target, Shield } from 'lucide-react';
-
-# Driver Protocol
-
-The **Driver Protocol** defines the interface for database adapters that connect ObjectStack's Data Layer to various storage engines. Drivers translate the abstract query AST into database-specific queries (SQL, NoSQL, etc.).
-
-## Why This Protocol Exists
-
-**Problem:** Traditional applications hard-code database-specific SQL or NoSQL queries throughout the codebase. This creates devastating vendor lock-in:
-
-- **Migration nightmares:** Moving from MySQL to PostgreSQL requires rewriting thousands of queries
-- **Multi-database impossibility:** Can't use PostgreSQL for transactions AND MongoDB for catalogs in the same app
-- **Performance blind spots:** Developers write queries without understanding database-specific optimizations
-- **Innovation tax:** Can't adopt new databases (DuckDB, ClickHouse, Turso) without massive rewrites
-
-**Solution:** The Driver Protocol decouples business logic from database implementation. Your application writes **one** query in ObjectQL AST format. The Driver compiles it to optimized SQL, MongoDB aggregation pipeline, or Redis commands—depending on which database you choose at runtime.
-
-## Business Value Delivered
-
-
- }
- title="Zero Vendor Lock-in"
- description="Start with SQLite in dev, deploy PostgreSQL in prod, migrate to PlanetScale later—without code changes."
- />
- }
- title="Polyglot Persistence"
- description="Use the right database for each workload: Postgres for transactions, MongoDB for documents, Redis for caching."
- />
- }
- title="Automatic Optimization"
- description="Drivers generate database-specific query plans. Get MongoDB's $lookup or Postgres's LATERAL joins without knowing either."
- />
- }
- title="Built-in Security"
- description="All drivers use parameterized queries. SQL injection is structurally impossible."
- />
-
-
-## What This Protocol Enables
-
-### Unified Interface, Diverse Implementations
-All drivers implement the same contract: `create()`, `find()`, `update()`, `delete()`. Whether you're talking to PostgreSQL or MongoDB, the interface is identical. This enables:
-
-- **Development freedom:** Build with SQLite locally, deploy to PostgreSQL/MySQL in production
-- **Vendor negotiation leverage:** "We can migrate to Aurora in 2 weeks" is a powerful negotiating position
-- **Technology adoption:** Evaluate DuckDB for analytics or Turso for edge deployments—just swap the driver
-- **Team productivity:** Developers learn one data access API, not five different database clients
-
-### Query Compilation, Not Translation
-Drivers don't just "convert" queries—they **compile** them:
-- **Postgres Driver:** Generates window functions, CTEs, and JSONB operators when beneficial
-- **MongoDB Driver:** Uses aggregation pipelines with `$lookup` for joins, `$match` for filters
-- **Redis Driver:** Compiles to Redis Search queries for text search, sorted sets for ordering
-- **SQLite Driver:** Optimizes for single-threaded I/O, uses WITHOUT ROWID tables when appropriate
-
-**Example:** The query `find customers where city = 'SF' AND revenue > 1M` becomes:
-- **PostgreSQL:** `SELECT * FROM customers WHERE city = 'SF' AND revenue > 1000000 USING INDEX idx_city_revenue`
-- **MongoDB:** `db.customers.find({ city: 'SF', revenue: { $gt: 1000000 } }).hint('city_revenue_idx')`
-- **Redis:** `FT.SEARCH customers "@city:SF @revenue:[1000000 +inf]"`
-
-All from the same ObjectQL AST.
-
-### Driver Capabilities Declaration
-Drivers declare what they support (transactions, joins, full-text search, etc.). The ObjectStack runtime:
-- **Validates queries at compile time:** If you use window functions but the driver doesn't support them, you get an error before deployment
-- **Graceful degradation:** Falls back to in-memory processing for unsupported features (e.g., client-side joins)
-- **Capability-aware UI:** Admin UIs only show import/export options if the driver supports bulk operations
-
-## Real-World Use Cases
-
-### Startup to Enterprise Migration
-**Challenge:** A startup launches with Heroku Postgres (free tier). As they grow, they need to migrate to RDS, then eventually to Aurora with read replicas.
-
-**Driver Protocol Solution:** Change one line in config: `driver: 'postgres'` → `driver: 'aurora'`. The application code doesn't change. Run the migration during a maintenance window.
-
-**Value:** Database migration goes from "6-month project with rewrite risk" to "2-hour deployment". Your team stays focused on product features, not infrastructure firefighting.
-
-### Polyglot Persistence for Performance
-**Challenge:** You have transactional data (orders, payments) in PostgreSQL, product catalogs in MongoDB (flexible schemas), and session data in Redis (fast TTL expiry).
-
-**Driver Protocol Solution:** Define three datasources, each with a different driver. ObjectStack routes queries to the appropriate database based on object configuration. Joins across databases work transparently (federation).
-
-**Value:** Use the best tool for each job without sacrificing application simplicity. 10x performance improvement on reads, 50% cost savings on infrastructure.
-
-### Edge Computing with Offline Support
-**Challenge:** Building a point-of-sale (POS) system for retail stores. Each store needs local data when the internet goes down, but must sync to a central cloud database when online.
-
-**Driver Protocol Solution:**
-- **In-store:** SQLite driver with local file storage
-- **Cloud:** PostgreSQL driver with central database
-- **Sync logic:** ObjectStack's built-in replication handles conflict resolution
-
-**Value:** Stores process $50K/day in sales even during internet outages. No lost transactions, no manual reconciliation.
-
-### Legacy System Integration Without Migration
-**Challenge:** You have customer data in Salesforce, inventory in SAP, and orders in an Oracle database from 2005. You want a unified view without a costly ETL project.
-
-**Driver Protocol Solution:** Build drivers for each system (Salesforce REST API, SAP RFC, Oracle JDBC). ObjectStack queries federate across all three. Data stays in place—no migration needed.
-
-**Value:** Deliver a unified dashboard in weeks, not quarters. Retire legacy systems incrementally as business priorities dictate.
- // 2. Execute query
- const results = await this.executeQuery(nativeQuery);
-
- // 3. Transform results to standard format
- return this.transformResults(results);
-## Supported Databases
-
-ObjectStack provides official drivers for:
-
-**SQL:** PostgreSQL, MySQL, SQLite, PlanetScale, Neon, Supabase
-**NoSQL:** MongoDB, Redis
-**Cloud:** Aurora, Cloud SQL, DocumentDB
-**Special:** In-memory (testing), Excel files, Airtable, Google Sheets
-
-**Extensibility:** Create custom drivers for proprietary databases, SaaS APIs, or data warehouses by implementing the `DriverInterface`.
-
-## Integration with Other Protocols
-
-- **Data Protocol:** Compiles ObjectQL queries to database-specific queries
-- **Permission Protocol:** Injects row-level security filters before query execution
-- **System Protocol:** Manages connection pools, monitors query performance
-- **API Protocol:** Exposes driver capabilities via API metadata endpoints
-
-## Technical Reference
-
-For detailed implementation guides and API documentation, see:
-
-- [Driver Interface Reference](/docs/references/driver/driver/DriverInterface) - Complete interface specification
-- [Custom Driver Guide](/docs/guides/custom-driver) - Build your own driver
-- [Datasource Configuration](/docs/references/driver/datasource/Datasource) - Connection and pooling options
-- [Technology Compatibility Kit (TCK)](/docs/guides/driver-tck) - Testing framework for drivers
diff --git a/content/docs/concepts/protocol-hub.mdx b/content/docs/concepts/protocol-hub.mdx
deleted file mode 100644
index b792a14ca..000000000
--- a/content/docs/concepts/protocol-hub.mdx
+++ /dev/null
@@ -1,170 +0,0 @@
----
-title: Hub Protocol
-description: Multi-tenancy, marketplace, licensing, and deployment management for SaaS distribution.
----
-
-import { Zap, DollarSign, Shield, Target } from 'lucide-react';
-
-# Hub Protocol
-
-The **Hub Protocol** provides SaaS and marketplace capabilities including multi-tenancy, licensing, plugin marketplace, and deployment management.
-
-## Why This Protocol Exists
-
-**Problem:** Building a B2B SaaS platform requires infrastructure that has nothing to do with your product:
-
-- **Multi-tenancy:** Isolate Customer A's data from Customer B—with database-level, schema-level, or row-level strategies
-- **Usage billing:** Track API calls, storage, users to enforce quotas and generate invoices
-- **Licensing:** Feature flags for "Starter vs. Enterprise" plans, trial periods, seat limits
-- **Plugin marketplace:** Third-party developers want to sell integrations—you need vetting, payments, and revenue sharing
-- **Deployment management:** Customers want dedicated environments (dev, staging, prod) or private cloud deployments
-
-Building this from scratch takes 12+ months and distracts from your core product. Salesforce, Shopify, and WordPress took years to get this right.
-
-**Solution:** The Hub Protocol provides **Salesforce-AppExchange-grade infrastructure** out of the box. Multi-tenancy, licensing, and marketplace are configuration, not code. Launch a B2B SaaS in weeks, not years.
-
-## Business Value Delivered
-
-
- }
- title="$500K+ SaaS Revenue, Year One"
- description="Launch with tiered pricing (Starter/Pro/Enterprise) from day one. No billing infrastructure to build."
- />
- }
- title="Onboard Customers in Minutes"
- description="New signup creates isolated tenant automatically. Zero manual provisioning, no DevOps tickets."
- />
- }
- title="Pass Enterprise Security Audits"
- description="Database-level isolation proves data separation. SOC 2 auditors love it."
- />
- }
- title="Ecosystem Revenue Sharing"
- description="Third-party plugins sell on your marketplace. You take 30% commission—passive income."
- />
-
-
-## What This Protocol Enables
-
-### Multi-Tenancy That Scales
-Support **three isolation strategies** based on customer requirements:
-
-**Database-level isolation:** Each tenant gets a dedicated database. Best for regulated industries (healthcare, finance) or massive customers (10M+ records). Example: Acme Corp gets `tenant_acme` database.
-
-**Schema-level isolation:** Each tenant gets a schema in a shared database. Good balance between isolation and cost. Example: All tenants share one Postgres instance, Acme Corp uses `acme_schema`.
-
-**Row-level isolation:** All tenants share tables; row-level security filters data by `tenant_id`. Cheapest option, great for SMB SaaS. Example: `SELECT * FROM accounts WHERE tenant_id = 'acme'` enforced automatically.
-
-**Why it matters:** Start with row-level isolation to minimize costs. Land a Fortune 500 customer who demands database isolation? Migrate them without code changes. The Hub Protocol handles routing.
-
-**Real-world impact:** A SaaS company with 5,000 SMB customers (row-level) and 10 enterprise customers (database-level) runs on one codebase. $200K/year infrastructure savings vs. separate deployments.
-
-### Usage-Based Licensing
-Enforce **usage quotas and feature flags** per tenant:
-- **User limits:** Starter plan = 5 users, Pro plan = 50 users, Enterprise = unlimited
-- **Storage limits:** 10GB on Starter, 100GB on Pro, 1TB on Enterprise
-- **API rate limits:** 10K calls/month on Starter, 1M on Pro, unlimited on Enterprise
-- **Feature flags:** `advanced_analytics`, `custom_branding`, `sso`, `api_access`
-
-When a tenant exceeds their quota, the protocol **auto-blocks** further usage and prompts an upgrade.
-
-**Business value:** Monetize power users automatically. A startup on the Starter plan hits 5-user limit? In-app prompt to upgrade to Pro. Conversion happens without sales calls.
-
-### Plugin Marketplace
-Create an **AppExchange-style marketplace** where third-party developers sell plugins:
-
-**For platform owners:**
-- Vet plugins for security/quality before publishing
-- Set commission rates (e.g., 30% platform fee)
-- Auto-bill customers, auto-pay developers
-
-**For plugin developers:**
-- Reach thousands of customers without building distribution
-- Handle billing, licensing, and updates via the marketplace
-- Example: "Shopify Sync Pro" plugin sells for $49/month, developer gets $34, platform gets $15
-
-**For end users:**
-- One-click install from marketplace
-- Billing consolidated in platform subscription
-- Auto-updates when developers push new versions
-
-**Real-world impact:** Salesforce's AppExchange generates **$50B+ in ecosystem revenue**. ObjectStack's Hub Protocol enables the same model for your niche.
-
-### Deployment Spaces
-Support **multi-environment workflows** per tenant:
-- **Development space:** Developers test changes without affecting production
-- **Staging space:** QA tests before prod deployment
-- **Production space:** Live customer data
-
-Each space can run on different infrastructure (local laptop for dev, cloud for prod).
-
-**Enterprise use case:** A large customer wants **dedicated infrastructure**. The Hub Protocol supports private cloud deployments where one tenant gets their own Kubernetes cluster. Same codebase, isolated infra.
-
-## Real-World Use Cases
-
-### SaaS Launch in 30 Days
-**Challenge:** A startup wants to build a vertical SaaS for real estate agents. They need multi-tenancy, tiered pricing (Free/Pro/Enterprise), and trial periods—but have no SaaS experience.
-
-**Hub Protocol Solution:**
-- Enable row-level multi-tenancy: `isolationLevel: 'row'`
-- Define pricing tiers with usage limits
-- Configure 14-day free trial with auto-upgrade prompts
-- Deploy
-
-**Value:** Launched SaaS in 4 weeks. First paying customer in week 6. $50K MRR by month 12.
-
-### Enterprise Customer with Compliance Requirements
-**Challenge:** A healthcare SaaS lands a hospital network. HIPAA requires that patient data be **physically isolated** from other customers.
-
-**Hub Protocol Solution:** Migrate the hospital to database-level isolation:
-```
-tenant: 'hospital_network'
-isolationLevel: 'database'
-dedicatedInfrastructure: true
-```
-Hospital gets their own database on dedicated AWS RDS instance. Audit logs prove isolation.
-
-**Value:** Passed HIPAA audit, won $2M/year contract. Smaller customers stay on row-level isolation—no cost impact.
-
-### Plugin Marketplace Revenue
-**Challenge:** A B2B SaaS platform has 10K customers. Third-party developers want to sell integrations (Slack, Zoom, QuickBooks) but platform owner doesn't want to build them.
-
-**Hub Protocol Solution:**
-- Open plugin marketplace
-- Developer uploads "QuickBooks Sync" plugin, sets price at $29/month
-- Platform takes 30% commission
-- Customers install with one click
-
-**Value:** 500 customers install the plugin (500 × $29 = $14.5K/month). Platform earns $4.35K/month passive income. Developer earns $10.15K/month without building distribution.
-
-### Multi-Region Deployment
-**Challenge:** A SaaS company has EU customers who require data residency (GDPR) and US customers who need low latency.
-
-**Hub Protocol Solution:**
-- EU tenants deployed to `eu-west-1` region
-- US tenants deployed to `us-east-1` region
-- Same codebase, different deployment targets
-
-**Value:** Compliant with GDPR's data residency requirements. Won $5M in EU contracts that were previously blocked by compliance.
-
-## Integration with Other Protocols
-
-- **Auth Protocol:** Per-tenant auth configurations (Acme uses Okta, SmallCo uses email/password)
-- **Data Protocol:** Tenant isolation enforced at query level (automatic `WHERE tenant_id = ?` injection)
-- **Permission Protocol:** Roles and permissions scoped per tenant
-- **Kernel Protocol:** Plugins can be enabled/disabled per tenant
-
-**Key insight:** Hub Protocol is the **business layer** of ObjectStack. While other protocols handle technical concerns (data, auth, UI), Hub Protocol handles **monetization** (licensing, usage tracking, marketplace revenue).
-
-## Technical Reference
-
-For configuration guides and implementation details, see:
-
-- [Tenant Management](/docs/references/hub/tenant/Tenant) - Isolation strategies, quota enforcement, and tenant lifecycle
-- [Licensing System](/docs/references/hub/license/License) - Feature flags, usage limits, and subscription management
-- [Marketplace Plugins](/docs/references/hub/marketplace/MarketplacePlugin) - Plugin publishing, pricing, and distribution
-- [Deployment Spaces](/docs/references/hub/space/HubSpace) - Multi-environment configuration and infrastructure targeting
diff --git a/content/docs/concepts/protocol-kernel.mdx b/content/docs/concepts/protocol-kernel.mdx
deleted file mode 100644
index ea23e8e42..000000000
--- a/content/docs/concepts/protocol-kernel.mdx
+++ /dev/null
@@ -1,159 +0,0 @@
----
-title: Kernel Protocol
-description: Plugin system, manifest definitions, lifecycle management, and runtime context for ObjectStack extensions.
----
-
-import { Zap, Users, DollarSign, Target } from 'lucide-react';
-
-# Kernel Protocol
-
-The **Kernel Protocol** defines the plugin system and runtime management for ObjectStack. It enables a microkernel architecture where the core platform provides minimal runtime, while all capabilities are delivered as plugins.
-
-## Why This Protocol Exists
-
-**Problem:** Monolithic platforms (Salesforce, ServiceNow) force you to use their data model, their UI, their workflow engine—even if you only need 10% of features, you deploy 100% of the platform. This creates:
-
-- **Bloat:** 500MB Docker images with dependencies you'll never use
-- **Vendor lock-in:** Can't swap out their workflow engine for Temporal without forking the entire platform
-- **Slow innovation:** Want AI-powered search? Wait for the vendor's roadmap (or never get it)
-- **License costs:** Pay $150/user/month for "Enterprise Edition" just to get SSO
-
-**Solution:** The Kernel Protocol implements a **microkernel architecture** like Linux or Kubernetes. The core runtime is less than 10MB and does almost nothing—just loads plugins. Every feature (data access, UI, workflows, AI) is a plugin. Don't need dashboards? Don't load the dashboard plugin. Want better analytics? Replace the default plugin with your own.
-
-## Business Value Delivered
-
-
- }
- title="Ship Custom Features in Days"
- description="Build a plugin to integrate Stripe billing or Twilio SMS. Deploy without forking ObjectStack core."
- />
- }
- title="Pay for What You Use"
- description="Disable unused plugins to reduce memory/CPU costs. 50% smaller deployments, 30% lower AWS bills."
- />
- }
- title="Ecosystem Marketplace"
- description="Download plugins from the marketplace: Shopify sync, DocuSign, Slack, Calendly—one-click install."
- />
- }
- title="Zero Core Upgrades"
- description="Core runtime rarely changes. Upgrade plugins independently without breaking dependencies."
- />
-
-
-## What This Protocol Enables
-
-### Plugin Isolation and Composability
-Each plugin is a **self-contained module** with:
-- **Manifest:** Declares what it provides (objects, views, actions) and what it needs (dependencies, configuration)
-- **Lifecycle hooks:** `onInstall`, `onEnable`, `onDisable`, `onUninstall` for setup and teardown
-- **Scoped context:** Plugins can't access each other's data or crash each other
-
-**Why it matters:** A startup builds their CRM with "Sales" and "Support" plugins. Later, they add "Marketing Automation." The new plugin can **reference sales objects** without modifying sales plugin code. This is composability.
-
-**Real-world impact:** An ISV (independent software vendor) sells vertical-specific CRMs (real estate, legal, healthcare). They maintain one core platform and **industry-specific plugin packages**. New vertical? Build a plugin, no core changes.
-
-### Marketplace Economy
-The Kernel Protocol enables a **plugin marketplace** like VS Code extensions or Salesforce AppExchange:
-- **Plugin developers** build integrations (Stripe, QuickBooks, Zapier) and sell them
-- **Platform users** install plugins with one click—no custom code needed
-- **Revenue sharing** incentivizes third-party innovation
-
-**Example:** Need Shopify integration? Search marketplace, find "Shopify Sync Pro" plugin ($29/month), install, configure API key, done. 15-minute setup vs. 2-week custom integration.
-
-### Dependency Management
-Plugins declare dependencies:
-```
-dependencies: {
- '@objectstack/core': '^2.0.0',
- 'com.vendor.calendar': '>=1.5.0'
-}
-```
-The runtime ensures **compatible versions** are loaded. Incompatible plugins fail fast at install time, not at runtime.
-
-**Business value:** A company uses 10 third-party plugins. Core platform upgrades from v2.0 to v3.0. The runtime auto-checks which plugins are compatible. Incompatible plugins are disabled until vendors release updates. No surprise crashes.
-
-### Resource Isolation
-Plugins get **scoped storage and logging**:
-- **Storage:** `context.storage.set('config', {...})` only affects this plugin's namespace
-- **Logging:** `context.logger.info()` tags logs with plugin ID for debugging
-- **Secrets:** Plugin configuration includes `secret: true` fields that are encrypted at rest
-
-**Security impact:** A malicious plugin can't read another plugin's API keys or database credentials. Sandboxing prevents supply chain attacks.
-
-## Real-World Use Cases
-
-### SaaS Vertical Expansion
-**Challenge:** A horizontal CRM vendor wants to sell to dentists, lawyers, and car dealerships. Each industry needs custom objects (Patient, Case, Vehicle) but shares core CRM.
-
-**Kernel Protocol Solution:** Build industry-specific plugins:
-- **Dental Plugin:** Patient object, appointment scheduling, insurance claims
-- **Legal Plugin:** Case object, billable hours, court calendar integration
-- **Auto Plugin:** Vehicle object, service history, DMV integration
-
-Core CRM stays the same. Sell industry bundles.
-
-**Value:** 3x revenue growth by entering new verticals. $0 additional platform maintenance cost.
-
-### Custom Integration Without Vendor Approval
-**Challenge:** A company uses ObjectStack but needs to integrate with an internal ERP system. Vendor doesn't support it.
-
-**Kernel Protocol Solution:** Build a custom plugin:
-```
-onEnable(context) {
- // Sync data from ERP every hour
- context.scheduler.cron('0 * * * *', syncERPData);
-
- // Register custom API endpoint
- context.router.post('/api/erp/sync', handleSyncRequest);
-}
-```
-Deploy the plugin. No pull request to ObjectStack core needed.
-
-**Value:** Integration delivered in 1 week vs. 6-month vendor roadmap wait.
-
-### Multi-Tenant Plugin Configuration
-**Challenge:** A SaaS app has 1,000 tenants. Some use Stripe for billing, others use PayPal or manual invoicing.
-
-**Kernel Protocol Solution:** Build a "Billing" plugin with **per-tenant configuration**:
-- **Tenant A:** `billingProvider: 'stripe', stripeApiKey: 'sk_...'`
-- **Tenant B:** `billingProvider: 'paypal', paypalClientId: 'AX...'`
-- **Tenant C:** `billingProvider: 'manual'`
-
-One plugin, three configurations.
-
-**Value:** Support multiple payment providers without code forks. Win enterprise deals that require specific billing systems.
-
-### Zero-Downtime Plugin Updates
-**Challenge:** A critical bug is found in the "Email Notifications" plugin. Fix must deploy without taking the app offline.
-
-**Kernel Protocol Solution:**
-1. Upload new plugin version: `email-notifications@1.2.1`
-2. Runtime performs **hot reload**: disables v1.2.0, enables v1.2.1
-3. Active requests finish on old version, new requests use new version
-
-**Value:** Fix deployed in 30 seconds, zero downtime. Traditional approach: deploy entire app, 5-minute outage.
-
-## Integration with Other Protocols
-
-- **Data Protocol:** Plugins contribute new objects via their manifest
-- **UI Protocol:** Plugins register views, dashboards, and actions
-- **Automation Protocol:** Plugins define workflows and flows
-- **System Protocol:** Plugins schedule jobs and emit events
-- **API Protocol:** Plugins register custom REST endpoints
-
-**Key insight:** The Kernel Protocol is ObjectStack's **module system**. Just like Linux uses kernel modules (device drivers, file systems), ObjectStack uses plugins for everything. The core is stable; innovation happens at the plugin layer.
-
-## Technical Reference
-
-For implementation guides and API documentation, see:
-
-- [Plugin Architecture](/docs/concepts/plugin-architecture) - Design principles and best practices
-- [Manifest Reference](/docs/references/kernel/manifest/Manifest) - Package metadata, dependencies, and contribution declarations
-- [Plugin Context API](/docs/references/kernel/plugin/PluginContext) - Runtime context with logger, storage, router, and scheduler
-- [Lifecycle Hooks](/docs/references/kernel/plugin/Plugin) - onInstall, onEnable, onDisable, onUninstall event handlers
-- [Logger Configuration](/docs/references/kernel/logger/LoggerConfig) - Log levels, formats, and output destinations
diff --git a/content/docs/concepts/protocol-permission.mdx b/content/docs/concepts/protocol-permission.mdx
deleted file mode 100644
index ecb3fcf82..000000000
--- a/content/docs/concepts/protocol-permission.mdx
+++ /dev/null
@@ -1,304 +0,0 @@
----
-title: Permission Protocol
-description: Fine-grained access control with object permissions, field-level security, sharing rules, and territory management.
----
-
-import { Shield, Lock, Users, Globe } from 'lucide-react';
-
-# Permission Protocol
-
-The **Permission Protocol** provides comprehensive access control for ObjectStack applications. It includes object-level permissions (CRUD), field-level security (FLS), sharing rules, and territory-based access management.
-
-## Overview
-
-ObjectStack implements a multi-layered permission model similar to enterprise platforms like Salesforce. Access is evaluated through multiple checks, from object-level down to individual fields.
-
-
- }
- title="Object Permissions"
- description="CRUD permissions at the object level via roles and permission sets."
- />
- }
- title="Field-Level Security"
- description="Control access to individual fields, independent of object permissions."
- />
- }
- title="Sharing Rules"
- description="Grant access to specific records based on ownership or criteria."
- />
- }
- title="Territory Management"
- description="Geographic or organizational hierarchy-based access control."
- />
-
-
-## Key Concepts
-
-### 1. Object Permissions
-
-Object permissions control CRUD operations at the object level:
-
-```typescript
-import { Permission } from '@objectstack/spec';
-
-const objectPermission: Permission.ObjectPermission = {
- object: 'account',
- allowCreate: true,
- allowRead: true,
- allowUpdate: true,
- allowDelete: false,
- viewAllRecords: false,
- modifyAllRecords: false
-};
-```
-
-**Permission Levels:**
-- `allowCreate` - Can create new records
-- `allowRead` - Can view records (filtered by sharing)
-- `allowUpdate` - Can edit records they have access to
-- `allowDelete` - Can delete records they have access to
-- `viewAllRecords` - Bypass sharing rules for read
-- `modifyAllRecords` - Bypass sharing rules for write
-
-### 2. Field-Level Security (FLS)
-
-Field-level security controls access to individual fields:
-
-```typescript
-const fieldPermission: Permission.FieldPermission = {
- object: 'account',
- field: 'annual_revenue',
- readable: true,
- editable: false
-};
-```
-
-**Use Cases:**
-- Hide sensitive data (SSN, salary) from certain roles
-- Make fields read-only for specific users
-- Require special permissions to edit critical fields
-
-### 3. Organization-Wide Defaults (OWD)
-
-OWD defines the baseline sharing level for each object:
-
-```typescript
-const owdModel: Permission.OWDModel = {
- object: 'account',
- internalAccess: 'private', // private | read_only | read_write
- externalAccess: 'private' // For portal users
-};
-```
-
-**Sharing Levels:**
-- `private` - Only owner can access
-- `read_only` - All users can read, only owner can edit
-- `read_write` - All users can read and edit
-
-### 4. Sharing Rules
-
-Sharing rules grant additional access beyond OWD:
-
-#### Ownership-Based Sharing
-
-```typescript
-const ownerSharingRule: Permission.OwnerSharingRule = {
- name: 'share_accounts_with_managers',
- object: 'account',
- ownedBy: {
- type: 'role',
- value: 'sales_rep'
- },
- sharedWith: {
- type: 'role',
- value: 'sales_manager'
- },
- accessLevel: 'read_only'
-};
-```
-
-#### Criteria-Based Sharing
-
-```typescript
-const criteriaSharingRule: Permission.CriteriaSharingRule = {
- name: 'share_enterprise_accounts',
- object: 'account',
- criteria: {
- and: [
- { field: 'type', operator: 'equals', value: 'Enterprise' },
- { field: 'annual_revenue', operator: 'greaterThan', value: 10000000 }
- ]
- },
- sharedWith: {
- type: 'public_group',
- value: 'enterprise_sales_team'
- },
- accessLevel: 'read_write'
-};
-```
-
-### 5. Territory Management
-
-Territories provide hierarchical, rule-based access:
-
-```typescript
-const territory: Permission.Territory = {
- name: 'north_america',
- label: 'North America',
- parentTerritory: 'global',
- rules: [
- {
- field: 'billing_country',
- operator: 'in',
- values: ['USA', 'Canada', 'Mexico']
- }
- ]
-};
-
-const territoryModel: Permission.TerritoryModel = {
- object: 'account',
- enabled: true,
- assignmentPriority: 'most_specific'
-};
-```
-
-## Permission Evaluation Flow
-
-When a user requests access to a record, the system evaluates:
-
-```
-1. Object Permission
- ├─ Does user's role have READ permission on Account?
- │ ├─ YES → Continue
- │ └─ NO → DENY (403)
- │
-2. Record-Level Access (Sharing)
- ├─ Is user the owner?
- │ └─ YES → GRANT
- ├─ Does OWD grant access?
- │ └─ YES → GRANT
- ├─ Do sharing rules grant access?
- │ └─ YES → GRANT
- ├─ Does user have "View All" permission?
- │ └─ YES → GRANT
- └─ Otherwise → DENY (404 - hide existence)
- │
-3. Field-Level Security
- ├─ For each field in response:
- │ ├─ Is field readable by user?
- │ │ ├─ YES → Include in response
- │ │ └─ NO → Exclude from response
- │
-4. Final Response
- └─ Return record with allowed fields only
-```
-
-## Permission Sets
-
-Permission sets bundle multiple permissions:
-
-```typescript
-const permissionSet: Permission.PermissionSet = {
- name: 'sales_manager_permissions',
- label: 'Sales Manager Permissions',
- objectPermissions: [
- {
- object: 'account',
- allowCreate: true,
- allowRead: true,
- allowUpdate: true,
- allowDelete: false,
- viewAllRecords: true
- },
- {
- object: 'opportunity',
- allowCreate: true,
- allowRead: true,
- allowUpdate: true,
- allowDelete: true,
- modifyAllRecords: true
- }
- ],
- fieldPermissions: [
- {
- object: 'account',
- field: 'annual_revenue',
- readable: true,
- editable: true
- }
- ]
-};
-```
-
-## Role Hierarchy
-
-Roles inherit permissions from parent roles:
-
-```
-CEO (can see everything)
- └── VP Sales (can see sales data)
- ├── Sales Manager West (can see west region)
- │ └── Sales Rep West
- └── Sales Manager East (can see east region)
- └── Sales Rep East
-```
-
-Users in parent roles automatically get access to records visible to child roles.
-
-## Best Practices
-
-1. **Start with restrictive OWD** - Use 'private' as default, grant access via sharing rules
-2. **Use permission sets for temporary access** - Assign additional permissions without changing roles
-3. **Leverage criteria-based sharing** - Automatic sharing based on field values
-4. **Implement territory management for geographic sales** - Cleaner than manual sharing rules
-5. **Audit permission changes** - Track who granted/revoked access and when
-6. **Test with different user profiles** - Verify permissions work as expected
-
-## Common Patterns
-
-### Read-Only Access for External Users
-
-```typescript
-const externalOWD: Permission.OWDModel = {
- object: 'case',
- internalAccess: 'private',
- externalAccess: 'read_only' // Portal users can read their cases
-};
-```
-
-### Manager Access to Team Records
-
-```typescript
-const managerRule: Permission.OwnerSharingRule = {
- name: 'manager_team_access',
- object: 'opportunity',
- ownedBy: { type: 'role_and_subordinates', value: 'sales_rep' },
- sharedWith: { type: 'role', value: 'sales_manager' },
- accessLevel: 'read_write'
-};
-```
-
-### Temporary Project Access
-
-```typescript
-const projectPermissionSet: Permission.PermissionSet = {
- name: 'project_alpha_access',
- label: 'Project Alpha Access (Temporary)',
- objectPermissions: [{
- object: 'confidential_project',
- allowRead: true
- }]
-};
-// Assign to specific users, revoke when project ends
-```
-
-## Learn More
-
-- [Object Permission Reference](/docs/references/permission/permission/ObjectPermission)
-- [Sharing Rules Guide](/docs/references/permission/sharing/SharingRule)
-- [Territory Management](/docs/references/permission/territory/Territory)
-- [Field-Level Security](/docs/references/permission/permission/FieldPermission)
diff --git a/content/docs/concepts/protocol-system.mdx b/content/docs/concepts/protocol-system.mdx
deleted file mode 100644
index 65937c9ff..000000000
--- a/content/docs/concepts/protocol-system.mdx
+++ /dev/null
@@ -1,150 +0,0 @@
----
-title: System Protocol
-description: Infrastructure services including event bus, job scheduling, translations, and audit logging.
----
-
-import { Zap, Globe, Shield, DollarSign } from 'lucide-react';
-
-# System Protocol
-
-The **System Protocol** provides core infrastructure services that support the ObjectStack runtime. It includes event management, background job scheduling, internationalization (i18n), and audit logging.
-
-## Why This Protocol Exists
-
-**Problem:** Enterprise applications need "plumbing" that has nothing to do with business logic:
-
-- **Event handling:** When an order ships, trigger 5 different downstream systems (inventory, email, analytics, CRM, warehouse)
-- **Background jobs:** Generate reports at 3 AM, sync data from Salesforce every 15 minutes, clean up temp files hourly
-- **Multi-language support:** Same app must work in English, Spanish, Mandarin, Arabic—with proper date formats and number formatting
-- **Audit trails:** Regulators demand proof of "who changed what, when" for the last 7 years
-
-Traditional solutions force developers to cobble together disparate libraries: RabbitMQ for events, Cron for jobs, i18next for translations, custom logging for audits. Each has different configuration, monitoring, and failure modes. Integration is a nightmare.
-
-**Solution:** The System Protocol provides **batteries-included infrastructure**. Events, jobs, translations, and audit logging all work the same way—declarative definitions, consistent monitoring, unified error handling. No external dependencies (Redis/RabbitMQ optional), no YAML hell, no 500-line Spring Boot XML configs.
-
-## Business Value Delivered
-
-
- }
- title="Pass Audits the First Time"
- description="SOC 2, GDPR, HIPAA compliance built-in. Auditors get tamper-proof logs showing who accessed what data."
- />
- }
- title="Zero Infrastructure Complexity"
- description="No Kafka clusters to tune, no RabbitMQ nodes to monitor. Event bus scales from 10 to 10M events/sec without config changes."
- />
- }
- title="Go Global in Days, Not Months"
- description="Add a new language by uploading a translation file. No code changes, no redeployment."
- />
- }
- title="$50K/Year Savings on Ops"
- description="No dedicated Kafka engineers, no RabbitMQ consultants. One junior dev manages all infrastructure."
- />
-
-
-## What This Protocol Enables
-
-### Event-Driven Architecture Without Kafka
-Build loosely-coupled systems where components communicate via events, not direct API calls:
-- **Order created** → Trigger inventory reservation, send confirmation email, update analytics, notify warehouse
-- **Payment failed** → Retry billing, send dunning email, pause service, alert finance team
-
-**Why it matters:** When a sales rep closes a deal, 10 different things must happen (update forecast, notify manager, create invoice, log in analytics, etc.). With traditional code, that's 10 function calls scattered across the codebase. With System Protocol events, it's **one event publish** and 10 independent handlers. Add a new side effect? Register a new handler—no changes to the original code.
-
-**Real-world impact:** A B2B SaaS company reduced deployment risk by 80% when they moved from monolithic "order processing" code to event-driven handlers. One broken email template no longer crashes order fulfillment.
-
-### Background Jobs Without Infrastructure
-Schedule tasks with **cron syntax** or **intervals**—no external job scheduler needed:
-- Generate monthly invoices on the 1st at 2 AM
-- Sync CRM data from Salesforce every 15 minutes
-- Clean up temp files every hour
-- Send abandoned cart emails 24 hours after cart creation
-
-**Retry policies built-in:** Job fails? Automatically retry with exponential backoff. Third attempt fails? Trigger dead-letter queue and alert ops.
-
-**Business value:** A fintech company saved $100K/year by eliminating their AWS Batch infrastructure. ObjectStack's built-in scheduler handles 50K daily jobs with zero ops overhead.
-
-### Global Apps Without Localization Complexity
-Support **unlimited languages** with declarative translation bundles:
-- **Field labels:** "Account Name" → "名称" (Chinese) → "Nombre de cuenta" (Spanish)
-- **Error messages:** "Email is required" → "电子邮件是必填项" → "El correo electrónico es obligatorio"
-- **Date/number formats:** US uses MM/DD/YYYY and 1,000.00 → Europe uses DD/MM/YYYY and 1.000,00
-
-**Dynamic switching:** User changes language preference at 3 PM? Next page load shows the new language. No redeployment.
-
-**Real-world impact:** An e-commerce company expanded to 12 new countries in Q1 by shipping translation files, not rewriting code. Revenue grew 3x without hiring international dev teams.
-
-### Tamper-Proof Audit Trails
-Automatically log **every data change** with full context:
-- **Who:** User ID, name, IP address, device
-- **What:** Object, record ID, field changes (old value → new value)
-- **When:** ISO 8601 timestamp with millisecond precision
-- **Why:** Session ID, request ID, source (web UI vs. API vs. automation)
-
-**Suspicious activity detection:** Failed login from new country? Account locked and security team alerted.
-
-**Compliance value:** A healthcare provider passed HIPAA audit on first try because audit logs proved no unauthorized access to patient records. $2M fine avoided.
-
-## Real-World Use Cases
-
-### Microservices Communication
-**Challenge:** A company is migrating from a monolith to microservices. Services need to notify each other when data changes, but HTTP calls create tight coupling.
-
-**System Protocol Solution:** Order Service publishes `order.created` event. Inventory Service, Email Service, and Analytics Service subscribe independently. Add a new service? It subscribes to existing events—no changes to Order Service.
-
-**Value:** Migration completed in 6 months vs. 18-month estimate. Services deployed independently without breaking downstream consumers.
-
-### Multi-Region Compliance
-**Challenge:** A SaaS app must comply with GDPR (EU), CCPA (California), and LGPD (Brazil). Each jurisdiction has different audit retention requirements (1-10 years).
-
-**System Protocol Solution:** Configure **audit retention policies** per tenant:
-- EU tenants: 7-year retention, encrypted storage, right-to-deletion support
-- US tenants: 3-year retention
-- Brazil tenants: 5-year retention with data residency enforcement
-
-**Value:** Passed regulatory audits in 15 jurisdictions. $5M in fines avoided. Customer trust maintained.
-
-### 24/7 Operations with No Ops Team
-**Challenge:** A startup needs to run nightly batch jobs (reports, data cleanup, syncs) but can't afford a DevOps engineer.
-
-**System Protocol Solution:** Define jobs in metadata:
-```
-Daily Sales Report: cron("0 2 * * *"), retry 3 times
-Cleanup Temp Files: interval(1 hour)
-Sync Shopify Orders: cron("*/15 * * * *")
-```
-Jobs run automatically. Failures trigger Slack alerts. Dead-letter queue captures repeated failures.
-
-**Value:** $120K/year saved by not hiring ops staff. Founder sleeps well knowing jobs run reliably.
-
-### International Expansion Without Code Forks
-**Challenge:** A productivity app launches in Japan. Japanese users need date pickers in YYYY年MM月DD日 format, currency in ¥, and vertical text support.
-
-**System Protocol Solution:** Add `ja_JP` locale with custom date/number formats. Upload translation bundle. Deploy.
-
-**Value:** Japan launch completed in 2 weeks. $500K revenue in month one. No code changes to the app—just configuration.
-
-## Integration with Other Protocols
-
-- **Data Protocol:** Object changes automatically emit events (`record.created`, `record.updated`, `record.deleted`)
-- **Automation Protocol:** Workflows trigger on events; jobs invoke automation flows
-- **API Protocol:** API calls logged for audit; rate limits enforced via quota tracking
-- **Permission Protocol:** Audit logs show who had access to what data via permission checks
-- **UI Protocol:** Translation bundles localize all UI labels, buttons, and error messages
-
-**Key insight:** System Protocol is the **nervous system** of ObjectStack. Data flows through APIs, business logic runs in workflows, permissions enforce security—but the System Protocol coordinates it all via events, executes scheduled tasks, translates UIs, and records everything for compliance.
-
-## Technical Reference
-
-For detailed schema definitions and configuration options, see:
-
-- [Event Bus Reference](/docs/references/system/events/Event) - Event structure, handlers, and routing
-- [Job Scheduler Reference](/docs/references/system/job/Job) - Cron syntax, retry policies, and timeout configuration
-- [Translation System](/docs/references/system/translation/TranslationBundle) - Locale management and translation bundles
-- [Audit Configuration](/docs/references/system/audit/AuditConfig) - Retention policies, storage options, and compliance settings
-
diff --git a/content/docs/concepts/protocol-ui.mdx b/content/docs/concepts/protocol-ui.mdx
deleted file mode 100644
index 4b6de313b..000000000
--- a/content/docs/concepts/protocol-ui.mdx
+++ /dev/null
@@ -1,138 +0,0 @@
----
-title: UI Protocol
-description: Server-Driven UI specification for building dynamic, metadata-driven user interfaces.
----
-
-import { Zap, Users, DollarSign, Shield } from 'lucide-react';
-
-# UI Protocol
-
-The **UI Protocol** defines how user interfaces are described and rendered in ObjectStack. It follows the Server-Driven UI (SDUI) pattern where the backend dictates the layout, structure, and behavior, while the frontend acts as a renderer.
-
-## Why This Protocol Exists
-
-**Problem:** Traditional UI development hard-codes every form, table, and dashboard in React/Vue components. When business requirements change, developers must:
-
-- Manually update dozens of components across web, mobile, and desktop apps
-- Wait for app store approvals to fix a simple form layout bug
-- Duplicate validation logic between frontend and backend
-- Rebuild and redeploy entire applications just to add a new field to a form
-
-This creates **months of lag** between business needs and software delivery. Even worse, business analysts can't configure UIs themselves—they must open tickets and wait for developer sprints.
-
-**Solution:** The UI Protocol defines interfaces as **metadata**, not code. Describe your forms, dashboards, and reports in a declarative format. The frontend runtime reads these definitions at runtime and dynamically renders them. Change a form layout? Update metadata, deploy in seconds. Add a dashboard widget? No code changes, no app store submission.
-
-## Business Value Delivered
-
-
- }
- title="Ship UI Changes in Seconds"
- description="Update forms, dashboards, and reports without rebuilding apps. No app store approvals, no deployment pipelines."
- />
- }
- title="Empower Business Users"
- description="Analysts configure dashboards and reports themselves. IT becomes enablers, not bottlenecks."
- />
- }
- title="50% Lower Frontend Costs"
- description="Write UI rendering logic once. Reuse across web, iOS, Android, desktop. One definition, infinite renderers."
- />
- }
- title="Consistent UX Across Platforms"
- description="Same form layout on web, mobile, and desktop. Validation rules enforced everywhere automatically."
- />
-
-
-## What This Protocol Enables
-
-### One Definition, Every Platform
-Define a form layout **once** in metadata. The UI Protocol's renderer architecture automatically adapts it:
-- **Web:** React/Vue components with responsive CSS
-- **Mobile:** Native iOS/Android widgets with platform-specific gestures
-- **Desktop:** Electron/Tauri apps with keyboard shortcuts
-- **Voice:** Alexa/Google Assistant skills with conversational flows
-
-**Why it matters:** A startup ships a CRM with web and mobile apps in weeks, not quarters. Add a "notes" field to the Contact form? It appears everywhere instantly. No code reviews, no QA cycles, no 2-week iOS app approval wait.
-
-### Business User Configurability
-**Dashboards:** Sales managers build their own pipeline dashboards—no SQL, no BI tool expertise required. Drag widgets, set filters, done.
-
-**Reports:** Finance creates matrix reports with cross-tabs and aggregations. IT doesn't need to write Crystal Reports or Power BI queries.
-
-**Forms:** HR reconfigures the employee onboarding wizard when compliance rules change. Add a step, reorder fields, change validation—all in the UI.
-
-**Real-world impact:** A SaaS company reduced IT backlog by 60% when they gave department heads dashboard configurability. The CEO created a real-time P&L dashboard at 11 PM without opening a ticket.
-
-### Dynamic Runtime Updates
-Traditional apps burn UI logic into JavaScript bundles. Every change requires:
-1. Code change → 2. Build → 3. Test → 4. Deploy → 5. (iOS) Wait for Apple approval
-
-**Server-Driven UI changes this:**
-1. Update metadata → 2. Deploy (seconds)
-
-**Use case:** Black Friday sale. Marketing needs to add a "promo code" field to checkout. With traditional UIs: 2-day deploy cycle, miss the sale. With UI Protocol: 30-second metadata update, deployed before lunch.
-
-### Multi-Variant Experimentation
-Run A/B tests on form layouts without developer involvement:
-- **Variant A:** Single-page form with all fields visible
-- **Variant B:** Wizard form with progress indicator
-
-The protocol dynamically serves different `FormView` definitions to different user cohorts. Conversion metrics determine the winner.
-
-**Business impact:** An e-commerce company increased checkout completion by 23% after testing 5 form layouts in a single week—previously impossible with hard-coded UIs.
-
-## Real-World Use Cases
-
-### SaaS White-Label Customization
-**Challenge:** A CRM vendor sells to 500 customers. Each wants custom branding (logo, colors) and slightly different form layouts. Managing 500 React codebases is impossible.
-
-**UI Protocol Solution:** Each tenant gets a custom **App** definition with their branding and **FormView** layouts. Same codebase serves all 500 customers with different UIs.
-
-**Value:** Launch new customers in hours, not weeks. $2M/year saved on custom development work.
-
-### Regulatory Compliance Agility
-**Challenge:** A fintech company operates in 50 countries. Each country has different KYC (Know Your Customer) form requirements. EU requires GDPR consent checkboxes, India requires Aadhaar number, etc.
-
-**UI Protocol Solution:** Define locale-specific **FormView** variants. The app dynamically shows the right form based on user location. Regulatory change? Update metadata, deploy immediately.
-
-**Value:** Avoided $500K fine for non-compliance. New market entry time reduced from 3 months to 1 week.
-
-### Offline-First Mobile Apps
-**Challenge:** Field service technicians use a mobile app in areas with no connectivity. The app must work offline, sync when online, and match the web app's UI exactly.
-
-**UI Protocol Solution:** Ship the same `ListView` and `FormView` definitions to mobile and web. Mobile app renders them natively (SwiftUI/Jetpack Compose). When forms change, push metadata updates via background sync.
-
-**Value:** UI consistency eliminated $100K/year in support tickets caused by "why does mobile look different?" confusion.
-
-### Rapid Prototyping for Startups
-**Challenge:** A 2-person startup needs to validate 5 different product ideas. Building custom UIs for each idea would take months.
-
-**UI Protocol Solution:** Define objects (Customer, Order, Product) and let ObjectStack auto-generate forms, tables, and dashboards. Iterate on product by tweaking metadata, not rewriting code.
-
-**Value:** Shipped 3 MVPs in 6 weeks. Found product-market fit before running out of runway.
-
-## Integration with Other Protocols
-
-- **Data Protocol:** Forms automatically validate against field types and rules. No duplicate validation logic.
-- **Permission Protocol:** Forms hide/disable fields based on field-level security. Action buttons disappear if user lacks permissions.
-- **API Protocol:** Every UI component knows which REST endpoint to call. No manual wiring.
-- **Automation Protocol:** Action buttons trigger workflows. "Approve" button runs approval flow automatically.
-
-**Key insight:** The UI Protocol doesn't just define layouts—it's a **semantic layer** that connects user interactions to business logic. Click "Save" on a form? The protocol knows to validate, check permissions, call the API, trigger workflows, and refresh the dashboard—all without custom code.
-
-## Technical Reference
-
-For detailed schema definitions, component specifications, and implementation examples, see:
-
-- [App Configuration](/docs/references/ui/app/App) - Navigation structure, branding, and app-level settings
-- [ListView Reference](/docs/references/ui/view/ListView) - Grid, kanban, calendar, and gantt view configurations
-- [FormView Reference](/docs/references/ui/view/FormView) - Form layouts with simple, tabbed, and wizard modes
-- [Dashboard Reference](/docs/references/ui/dashboard/Dashboard) - Widget positioning and dashboard composition
-- [Report Builder](/docs/references/ui/report/Report) - Tabular, summary, and matrix report types
-- [Action Reference](/docs/references/ui/action/Action) - Button configuration and custom action definitions
-- [Theme Customization](/docs/references/ui/theme/Theme) - Color schemes, typography, and styling options
-
diff --git a/content/docs/concepts/security_architecture.cn.mdx b/content/docs/concepts/security_architecture.cn.mdx
deleted file mode 100644
index 1d8da62dd..000000000
--- a/content/docs/concepts/security_architecture.cn.mdx
+++ /dev/null
@@ -1,97 +0,0 @@
----
-title: 安全架构
-description: '"纵深防御"模型。为什么我们选择元数据驱动的安全性而不是基于代码的安全性。'
----
-
-import { ShieldAlert, Users, key, Lock } from 'lucide-react';
-
-# ObjectStack 安全模型:"纵深防御"架构
-
-ObjectStack 采用 **"Salesforce 风格"** 的元数据驱动安全模型。之所以选择它而不是 Microsoft(Dataverse)模型,是因为它具有卓越的粒度和解耦性,这对于复杂的企业场景至关重要。
-
-## 1. 主要模型比较
-
-| 层 | ObjectStack / Salesforce | Microsoft Dataverse (Dynamics) | 为什么我们选择 ObjectStack 的方式? |
-| :--- | :--- | :--- | :--- |
-| **这是谁?** | **用户 + 身份** | 用户 + Azure AD | 标准 OIDC/SAML 集成。 |
-| **他们能做什么?** (功能) | **权限集 / 配置文件** *(布尔标志)* | **安全角色** *("点阵")* | 将功能权利(例如,"导出数据")与数据范围解耦,可以实现更灵活的分配。 |
-| **他们坐在哪里?** (层次结构) | **角色** *(报告线)* | **业务单元** *(部门树)* | "角色"意味着逻辑报告(VP 可以看到经理),而"BU"意味着僵化的部门孤岛。 |
-| **他们可以看到什么数据?** (可见性) | **共享规则** *(标准和所有权)* | **访问团队** *(临时)* | **共享规则**是"杀手级功能"。它们允许诸如"将 > 100 万的交易与财务共享"之类的逻辑,而 Microsoft 的静态层次结构无法轻松表达。 |
-| **超级访问** | **查看全部 / 修改全部** | **组织级别**(绿点) | 将"超级访问"与标准"读取"分开可防止意外数据泄漏。 |
-
-## 2. 协议
-
-该模型通过三个关键协议实现:
-
-### A. 配置文件和权限集
-* **什么:** 定义对象和字段的"CRUD"访问权限。
-* **类比:** 你的门禁卡。它说"你可以打开 3 层的门"。
-* **示例:** `leads: { read: true, edit: false }`。
-
-### B. OWD(组织范围默认值)
-* **什么:** 你*不拥有*的记录的基线可见性。
-* **类比:** 办公室门的默认状态。它们是锁定的(私有)还是打开的(公共只读)?
-* **示例:** `Quote: Private`(只有所有者看到它)。
-
-### C. 共享规则
-* **什么:** OWD 的例外,用于开放访问权限。
-* **类比:** "如果你是销售副总裁,你可以进入 CEO 的办公室。"
-* **示例:** `IF amount > 1,000,000 SHARE WITH Group:Executives READ/WRITE`。
-
-## 3. 执行流程
-
-每个查询都通过**安全内核**。
-
-```mermaid
-graph TD
- A[用户请求] --> B{配置文件检查}
- B -- 拒绝 --> X[403 禁止]
- B -- 允许 --> C{字段级安全}
- C -- 剥离字段 --> D{共享计算}
- D -- 添加 WHERE 子句 --> E[最终查询]
-```
-
-### A. 功能权限(`src/data/permission.zod.ts`)
-定义**基线**。
-* 如果 `allowRead = false`,则用户无法看到*任何*记录,无论共享如何。
-* 如果 `allowRead = true`,则用户可以看到*他们自己的*记录(所有权)。
-
-### B. 结构层次结构(`src/system/role.zod.ts`)
-定义**报告线**。
-* 用户被分配到一个角色(例如,"销售经理")。
-* **自动继承**:"销售经理"隐式看到"销售代表"拥有的数据。
-* *注意:这最接近 Microsoft 的"业务单元"概念。*
-
-### C. 数据访问范围(`src/data/sharing.zod.ts`)
-定义**扩展**。
-* 我们从"私有"(OWD)开始。
-* 我们通过**共享规则**扩展访问权限。
- * **基于标准**:"如果状态 = '已发布',则与所有内部用户共享。"
- * **基于所有者**:"将'西部地区'记录与'西部 VP'共享。"
-
-## 3. 术语映射
-
-如果你来自 Microsoft/Dynamics 生态系统:
-
-* **安全角色(用户级别)** -> `allowRead: true`
-* **安全角色(BU 级别)** -> `allowRead: true` + `共享规则(与角色共享)`
-* **安全角色(组织级别)** -> `viewAllRecords: true`
-* **业务单元** -> `角色`(功能层次结构)
-
-## 4. 高级:矩阵管理(区域管理)
-
-对于单一报告线("角色")不足的大型全球企业,ObjectStack 实现了**区域管理**协议(`src/system/territory.zod.ts`)。
-
-这在不破坏严格角色层次结构的情况下解决了"矩阵组织"问题。
-
-* **角色层次结构(HR/报告)**:"谁向谁报告?"(稳定)
- * 示例:销售代表向销售经理报告。
-* **区域层次结构(市场/收入)**:"谁拥有哪个市场?"(灵活,多重分配)
- * 示例:销售代表可能被分配到"西海岸(地理)"和"医疗保健(行业)"。
-
-**工作原理:**
-1. **客户/交易**根据规则分配给**区域**(例如,`State = 'CA'`)。
-2. **用户**被分配给**区域**。
-3. 用户可以访问其区域中的记录,*无论*其角色如何。
-
-这与 **Salesforce 企业区域管理**和 **Oracle Sales Cloud** 的最佳实践保持一致。
diff --git a/content/docs/concepts/security_architecture.mdx b/content/docs/concepts/security_architecture.mdx
deleted file mode 100644
index e4880cbc5..000000000
--- a/content/docs/concepts/security_architecture.mdx
+++ /dev/null
@@ -1,100 +0,0 @@
----
-title: Security Architecture
-description: The "Defense in Depth" Model. Why we chose Metadata-Driven Security over Code-Based Security.
----
-
-import { ShieldAlert, Users, key, Lock } from 'lucide-react';
-
-# ObjectStack Security Model: The "Defense in Depth" Architecture
-
-ObjectStack adopts the **"Salesforce-style"** metadata-driven security model. This is chosen over the Microsoft (Dataverse) model for its superior granularity and decoupling, which is essential for complex enterprise scenarios.
-
-## 1. Comparison of Major Models
-
-| Layer | ObjectStack / Salesforce | Microsoft Dataverse (Dynamics) | Why we chose ObjectStack's way? |
-| :--- | :--- | :--- | :--- |
-| **Who is this?** | **User + Identity** | User + Azure AD | Standard OIDC/SAML integration. |
-| **What can they do?** (Functionality) | **Permission Set / Profile** *(Boolean Flags)* | **Security Role** *(The "Matrix" of Dots)* | Decoupling functional rights (e.g., "Export Data") from data scope allows more flexible assignment. |
-| **Where do they sit?** (Hierarchy) | **Role** *(Reporting Line)* | **Business Unit** *(Department Tree)* | "Role" implies logical reporting (VP can see Manager), whereas "BU" implies rigid department silos. |
-| **What data can they see?** (Visibility) | **Sharing Rules** *(Criteria & Ownership)* | **Access Teams** *(Ad-hoc)* | **Sharing Rules** are the "Killer Feature". They allow logic like "Share Deal > 1M with Finance", which Microsoft's static hierarchy cannot easily express. |
-| **Super Access** | **View All / Modify All** | **Organization Level** (Green Dot) | Separating "Super Access" from standard "Read" prevents accidental data leaks. |
-
-## 2. The Protocols
-
-The Model is implemented via three key protocols:
-
-### A. Profiles & Permission Sets
-* **What:** Defines "CRUD" access on Objects and Fields.
-* **Analogy:** Your Keycard. It says "You can open doors on Level 3".
-* **Example:** `leads: { read: true, edit: false }`.
-
-### B. OWD (Organization-Wide Defaults)
-* **What:** The baseline visibility for records you *do not own*.
-* **Analogy:** The default state of the office doors. Are they locked (Private) or open (Public Read Only)?
-* **Example:** `Quote: Private` (Only owner sees it).
-
-### C. Sharing Rules
-* **What:** Exceptions to the OWD to open up access.
-* **Analogy:** "You can enter the CEO's office IF you are the VP of Sales."
-* **Example:** `IF amount > 1,000,000 SHARE WITH Group:Executives READ/WRITE`.
-
-## 3. The Enforcement Flow
-
-Every query passes through the **Security Kernel**.
-
-```mermaid
-graph TD
- A[User Request] --> B{Profile Check}
- B -- Deny --> X[403 Forbidden]
- B -- Allow --> C{Field Level Security}
- C -- Strip Fields --> D{Sharing Calculation}
- D -- Add WHERE Clause --> E[Final Query]
-```
-
-
-### A. Functional permissions (`src/data/permission.zod.ts`)
-Defines the **Baseline**.
-* If `allowRead = false`, the user cannot see *any* record, regardless of sharing.
-* If `allowRead = true`, the user can see *their own* records (Ownership).
-
-### B. Structural Hierarchy (`src/system/role.zod.ts`)
-Defines the **Reporting Line**.
-* A user is assigned to one Role (e.g., "Sales Manager").
-* **Automatic Inheritance**: The "Sales Manager" implicitly sees data owned by "Sales Rep".
-* *Note: This is closest to Microsoft's "Business Unit" concept.*
-
-### C. Data Access Scope (`src/data/sharing.zod.ts`)
-Defines the **Expansion**.
-* We start with "Private" (OWD).
-* We expand access via **Sharing Rules**.
- * **Criteria-based**: "If Status = 'Published', share with All Internal Users."
- * **Owner-based**: "Share 'Western Region' records with 'Western VP'."
-
-## 3. Terminology Map
-
-If you are coming from the Microsoft/Dynamics ecosystem:
-
-* **Security Role (User Level)** -> `allowRead: true`
-* **Security Role (BU Level)** -> `allowRead: true` + `Sharing Rule (Share with Role)`
-* **Security Role (Org Level)** -> `viewAllRecords: true`
-* **Business Unit** -> `Role` (Functional Hierarchy)
-
-## 4. Advanced: Matrix Management (Territory Management)
-
-For large global enterprises where a single reporting line ("Role") is insufficient, ObjectStack implements the **Territory Management** protocol (`src/system/territory.zod.ts`).
-
-This solves the "Matrix Organization" problem without breaking the strict Role hierarchy.
-
-* **Role Hierarchy (HR/Reporting)**: "Who reports to whom?" (Stable)
- * Example: A Sales Rep reports to a Sales Manager.
-* **Territory Hierarchy (Market/Revenue)**: "Who owns which market?" (Flexible, Multi-assignment)
- * Example: A Sales Rep might be assigned to both "West Coast (Geo)" and "Healthcare (Industry)".
-
-**How it works:**
-1. **Accounts/Deals** are assigned to **Territories** based on rules (e.g., `State = 'CA'`).
-2. **Users** are assigned to **Territories**.
-3. Users gain access to records in their Territories, *regardless* of their Role.
-
-This aligns with best practices from **Salesforce Enterprise Territory Management** and **Oracle Sales Cloud**.
-
-
diff --git a/content/docs/concepts/terminology.cn.mdx b/content/docs/concepts/terminology.cn.mdx
deleted file mode 100644
index 1ffc39517..000000000
--- a/content/docs/concepts/terminology.cn.mdx
+++ /dev/null
@@ -1,125 +0,0 @@
----
-title: 术语表
-description: ObjectStack 生态系统的词汇表。使用相同的语言。
----
-
-import { Book, Server, Code, Database } from 'lucide-react';
-
-为了有效地浏览 ObjectStack 生态系统,了解我们使用的特定词汇是有帮助的。虽然许多术语在计算机科学中是标准的,但在我们的"协议驱动"上下文中,有些术语具有特定的细微差别。
-
-## 生态系统
-
-### ObjectStack
-整个协议和参考实现套件的总称。它被组织成分组到三个架构层的 **11 个协议命名空间**。
-
-### 协议命名空间(Protocol Namespace)
-使用 Zod 定义的相关 schema 和类型的逻辑分组。ObjectStack 有 11 个协议命名空间:数据(Data)、驱动(Driver)、权限(Permission)、UI、系统(System)、认证(Auth)、内核(Kernel)、Hub、AI、API 和自动化(Automation)。
-
----
-
-## 11 个协议命名空间
-
-### 数据协议(Data Protocol)
-定义核心业务数据模型。包括对象 schema、字段类型、验证规则、查询 AST 和过滤条件。这是 ObjectQL 的基础。
-
-### 驱动协议(Driver Protocol)
-用于连接各种存储引擎(PostgreSQL、MongoDB、SQLite、Redis 等)的数据库适配器接口。驱动实现 CRUD 操作和查询执行的标准接口。
-
-### 权限协议(Permission Protocol)
-访问控制系统,包括对象级权限(CRUD)、字段级安全(FLS)、共享规则和区域管理。确定谁可以查看和修改哪些数据。
-
-### UI 协议(UI Protocol)
-用于构建用户界面的服务器驱动 UI 规范。包括应用结构、视图(列表/表单/看板/日历)、仪表板、报表、主题和操作。
-
-### 系统协议(System Protocol)
-基础设施服务,包括事件总线、作业调度、翻译(i18n)和审计日志。管理系统级关注点。
-
-### 认证协议(Auth Protocol)
-身份和访问管理,包括用户账户、会话、角色、组织结构以及各种认证策略(OAuth、SAML、LDAP 等)。
-
-### 内核协议(Kernel Protocol)
-插件系统和运行时管理。包括插件生命周期、清单定义、日志配置和运行时上下文。ObjectOS 的核心。
-
-### Hub 协议(Hub Protocol)
-SaaS 和市场功能,包括多租户、许可、市场插件和部署配置。实现商业分发。
-
-### AI 协议(AI Protocol)
-人工智能功能,包括 AI 代理、RAG 管道、自然语言查询(NLQ)、预测模型、成本跟踪和编排。
-
-### API 协议(API Protocol)
-外部通信层,包括 REST 契约、API 发现、实时订阅(WebSocket/SSE)和路由配置。
-
-### 自动化协议(Automation Protocol)
-业务流程自动化,包括工作流(状态机)、流程(可视化逻辑)和 Webhook(HTTP 回调)。
-
----
-
-## 架构概念
-
-### 协议驱动(Protocol-Driven)
-一种开发范式,其中逻辑在静态声明性数据格式(JSON/YAML)中使用 Zod schema 定义,而不是命令式代码。目标是将**意图**(业务逻辑)与**实现**(技术堆栈)分离。
-
-### 本地优先(Local-First)
-一种架构模式,其中应用程序首先读取和写入嵌入在用户设备(客户端)上的数据库。网络同步在后台进行。这确保了零延迟交互和离线可用性。
-
-### 数据库编译器(Database Compiler)
-一个系统,它接受高级查询 AST(抽象语法树)并将其编译为优化的数据库查询字符串(例如,SQL)。这与 ORM 形成对比,ORM 通常充当运行时包装器对象。
-
-### 虚拟字段(Virtual Field)
-在数据协议 schema 中定义的字段,该字段在数据库表中不物理存在,而是即时计算的。
-* *示例:* 在编译时注入到 `SELECT` 语句中的 SQL 子查询或表达式。
-
----
-
-## 数据和 Schema
-
-### 对象(Object/Entity)
-ObjectStack 中数据建模的基本单元。大致相当于 SQL 中的"表"或 NoSQL 中的"集合"。对象定义包括字段、操作、触发器和权限。
-
-### 驱动程序(Driver)
-允许数据层与特定底层存储引擎通信的适配器插件(驱动协议)。
-* *示例:* `@objectstack/driver-postgres`、`@objectstack/driver-mongodb`、`@objectstack/driver-sqlite`。
-
-### AST(抽象语法树)
-查询或 schema 的中间表示。数据协议在驱动将其转换为 SQL/NoSQL 查询之前,将 JSON 请求解析为 AST。这允许在执行之前进行安全验证和优化。
-
-### 清单(Manifest)
-ObjectStack 插件的入口点配置文件(内核协议)。它使用清单 schema 声明依赖项、资源和扩展。
-
----
-
-## 界面和逻辑
-
-### 布局(Layout)
-在 UI 协议中定义的 JSON 结构,描述组件的视觉排列。布局可以嵌套和动态(例如,主-明细、网格、看板)。
-
-### 工作流(Workflow)
-定义为**有限状态机(FSM)**的业务流程(自动化协议)。它由状态(例如,`draft`、`approved`)、转换和守卫组成。
-
-### 流程(Flow)
-可视化逻辑自动化工具(自动化协议),允许使用基于节点的编辑器构建业务流程。支持屏幕流程、自动启动流程和计划流程。
-
-### 操作(Action)
-可以由用户(UI 按钮)或系统事件(工作流转换)触发的离散逻辑单元(UI 协议)。操作定义按钮行为和导航。
-
-### 组件注册表(Component Registry)
-UI 运行时中的映射,它将字符串标识符(例如,`"chart.bar"`)链接到真实的 React 组件。这允许 UI 协议动态实例化 UI 元素。
-
----
-
-## 治理
-
-### 空间(Space/Workspace)
-多租户的逻辑隔离单元(Hub 协议)。单个 ObjectStack 实例可以托管多个空间。数据通过租户隔离策略物理隔离。
-
-### FLS(字段级安全)
-一种细粒度权限模型(权限协议),其中访问控制应用于单个字段(列),而不仅仅是整个对象(行)。
-
-### OWD(组织范围默认值)
-对象中记录的默认共享级别(权限协议)。在应用共享规则之前确定基线访问级别。
-
-### 区域(Territory)
-分层访问控制模型(权限协议),根据地理或组织边界授予数据访问权限。
-
-### TCK(技术兼容性工具包)
-一套测试,验证驱动程序或渲染器是否符合官方 ObjectStack 协议。如果新驱动程序通过 TCK,则认证为兼容。
diff --git a/content/docs/core-concepts/index.mdx b/content/docs/core-concepts/index.mdx
deleted file mode 100644
index 802897166..000000000
--- a/content/docs/core-concepts/index.mdx
+++ /dev/null
@@ -1,52 +0,0 @@
----
-title: Core Concepts
-description: Understanding the fundamental concepts behind ObjectStack's metadata-driven architecture
----
-
-# Core Concepts
-
-ObjectStack is built on a foundation of three revolutionary concepts that fundamentally change how we build enterprise software:
-
-1. **Metadata-Driven Development** - Define intent, not implementation
-2. **The Stack** - Three protocols working as one
-3. **Universal Object Model** - A unified way to model all business data
-
-These concepts work together to create a platform that is more flexible, maintainable, and powerful than traditional code-first approaches.
-
-## What You'll Learn
-
-- [Metadata-Driven](/docs/core-concepts/metadata-driven) - What is metadata-driven development?
-- [The Stack](/docs/core-concepts/the-stack) - How ObjectQL + ObjectUI + ObjectOS work together
-- [Object Model](/docs/core-concepts/object-model) - The Universal Object Model explained
-
-## Why This Matters
-
-Traditional development requires writing and maintaining code in multiple places:
-
-- Database migrations
-- Backend models and APIs
-- Frontend forms and validation
-- API documentation
-
-With ObjectStack, you define your business logic **once** as metadata, and the system automatically generates:
-
-✅ Database schema
-✅ CRUD APIs (REST/GraphQL)
-✅ Admin interface
-✅ Data validation
-✅ Access control
-
-## The Mental Shift
-
-Think of ObjectStack like this:
-
-| Traditional Approach | ObjectStack Approach |
-| :--- | :--- |
-| Write code for each feature | Define metadata once |
-| Scattered logic across layers | Single source of truth |
-| Imperative (how to do it) | Declarative (what you want) |
-| Coupled to technology stack | Protocol-agnostic |
-
-## Next Steps
-
-Start with [Metadata-Driven](/docs/core-concepts/metadata-driven) to understand the foundation of ObjectStack's approach.
diff --git a/content/docs/core-concepts/meta.json b/content/docs/core-concepts/meta.json
deleted file mode 100644
index 1e37d70cc..000000000
--- a/content/docs/core-concepts/meta.json
+++ /dev/null
@@ -1,8 +0,0 @@
-{
- "title": "💡 Core Concepts",
- "pages": [
- "metadata-driven",
- "the-stack",
- "object-model"
- ]
-}
diff --git a/content/docs/core-concepts/object-model.mdx b/content/docs/core-concepts/object-model.mdx
deleted file mode 100644
index 1fccf9fe6..000000000
--- a/content/docs/core-concepts/object-model.mdx
+++ /dev/null
@@ -1,749 +0,0 @@
----
-title: Universal Object Model
-description: Understanding the unified way ObjectStack models all business data
----
-
-import { Database, Link2, Box, List } from 'lucide-react';
-
-# The Universal Object Model
-
-At the heart of ObjectStack is a simple but powerful idea: **All business data can be modeled as Objects.**
-
-Whether you're building a CRM, ERP, project manager, or custom application, the fundamental building blocks are the same:
-- **Objects** (Customer, Order, Task)
-- **Fields** (Name, Status, Amount)
-- **Relationships** (Customer has many Orders)
-
-ObjectStack provides a **universal data model** that works across any domain.
-
-## What is an Object?
-
-An **Object** is a definition of a business entity. Think of it as:
-- A **database table** (in SQL terms)
-- A **collection** (in NoSQL terms)
-- A **class** (in OOP terms)
-- A **content type** (in CMS terms)
-
-But unlike traditional tables or classes, an Object is **pure metadata**. It's a declarative definition that exists independent of any specific database or programming language.
-
-### Anatomy of an Object
-
-```typescript
-import { Object, Field } from '@objectstack/spec';
-
-export const Task = Object({
- // Machine name (snake_case)
- name: 'project_task',
-
- // Display label
- label: 'Project Task',
-
- // Plural label (for UI)
- labelPlural: 'Project Tasks',
-
- // Icon (optional)
- icon: 'check-square',
-
- // Description
- description: 'Work items within projects',
-
- // Field definitions
- fields: {
- title: Field.text({
- label: 'Title',
- required: true,
- maxLength: 255,
- }),
-
- description: Field.textarea({
- label: 'Description',
- maxLength: 5000,
- }),
-
- status: Field.select({
- label: 'Status',
- options: ['todo', 'in_progress', 'review', 'done'],
- defaultValue: 'todo',
- }),
-
- priority: Field.select({
- label: 'Priority',
- options: ['low', 'medium', 'high', 'critical'],
- defaultValue: 'medium',
- }),
-
- assignee: Field.lookup({
- label: 'Assignee',
- object: 'user',
- }),
-
- project: Field.lookup({
- label: 'Project',
- object: 'project',
- required: true,
- }),
-
- due_date: Field.date({
- label: 'Due Date',
- }),
-
- estimated_hours: Field.number({
- label: 'Estimated Hours',
- min: 0,
- max: 1000,
- }),
- },
-
- // Capabilities (optional)
- enable: {
- trackHistory: true, // Audit log
- apiEnabled: true, // REST API
- search: true, // Full-text search
- comments: true, // User comments
- attachments: true, // File uploads
- },
-});
-```
-
-## Objects vs Database Tables
-
-While Objects **compile to database tables**, they are not the same thing:
-
-| Aspect | Database Table | ObjectStack Object |
-| :--- | :--- | :--- |
-| **Definition** | SQL DDL (`CREATE TABLE`) | TypeScript metadata |
-| **Validation** | Database constraints | Zod schema |
-| **Relationships** | Foreign keys | Lookup fields |
-| **Permissions** | GRANT/REVOKE | Permission rules |
-| **Portability** | Database-specific | Database-agnostic |
-| **Evolution** | Migrations required | Automatic sync |
-
-### Example: Object → Table Mapping
-
-Given this Object:
-
-```typescript
-export const Contact = Object({
- name: 'contact',
- fields: {
- first_name: Field.text({ required: true }),
- last_name: Field.text({ required: true }),
- email: Field.email({ unique: true }),
- phone: Field.phone(),
- account: Field.lookup({ object: 'account' }),
- },
-});
-```
-
-ObjectQL generates this Postgres table:
-
-```sql
-CREATE TABLE contact (
- id VARCHAR(18) PRIMARY KEY, -- Auto-generated
- first_name VARCHAR(255) NOT NULL,
- last_name VARCHAR(255) NOT NULL,
- email VARCHAR(255) UNIQUE,
- phone VARCHAR(20),
- account_id VARCHAR(18), -- Foreign key
-
- created_at TIMESTAMP NOT NULL, -- System fields
- created_by VARCHAR(18) NOT NULL,
- updated_at TIMESTAMP NOT NULL,
- updated_by VARCHAR(18) NOT NULL,
-
- FOREIGN KEY (account_id) REFERENCES account(id),
- FOREIGN KEY (created_by) REFERENCES user(id),
- FOREIGN KEY (updated_by) REFERENCES user(id)
-);
-```
-
-**Key Points:**
-- System fields (`id`, `created_at`, `updated_at`, etc.) are **automatic**
-- Lookups become **foreign keys**
-- Field types map to **appropriate SQL types**
-- Constraints are **enforced at the database level**
-
-## Field Types
-
-ObjectStack provides a comprehensive set of field types that cover 99% of business use cases:
-
-### Text Fields
-
-```typescript
-fields: {
- // Single-line text
- name: Field.text({
- label: 'Name',
- required: true,
- maxLength: 120,
- }),
-
- // Multi-line text
- notes: Field.textarea({
- label: 'Notes',
- maxLength: 5000,
- }),
-
- // Email with validation
- email: Field.email({
- label: 'Email',
- unique: true,
- }),
-
- // Phone with formatting
- phone: Field.phone({
- label: 'Phone',
- }),
-
- // URL with validation
- website: Field.url({
- label: 'Website',
- }),
-}
-```
-
-### Number Fields
-
-```typescript
-fields: {
- // Integer or decimal
- quantity: Field.number({
- label: 'Quantity',
- min: 0,
- max: 10000,
- }),
-
- // Currency with formatting
- amount: Field.currency({
- label: 'Amount',
- currency: 'USD',
- }),
-
- // Percentage
- discount: Field.percent({
- label: 'Discount',
- min: 0,
- max: 100,
- }),
-}
-```
-
-### Date/Time Fields
-
-```typescript
-fields: {
- // Date only
- due_date: Field.date({
- label: 'Due Date',
- }),
-
- // Date + Time
- start_time: Field.datetime({
- label: 'Start Time',
- }),
-
- // Time only
- meeting_time: Field.time({
- label: 'Meeting Time',
- }),
-}
-```
-
-### Selection Fields
-
-```typescript
-fields: {
- // Single select (dropdown)
- status: Field.select({
- label: 'Status',
- options: ['draft', 'active', 'archived'],
- defaultValue: 'draft',
- }),
-
- // Multi-select (checkbox group)
- skills: Field.multiselect({
- label: 'Skills',
- options: ['javascript', 'python', 'go', 'rust'],
- }),
-}
-```
-
-### Boolean Fields
-
-```typescript
-fields: {
- is_active: Field.boolean({
- label: 'Active',
- defaultValue: true,
- }),
-}
-```
-
-### Relationship Fields
-
-```typescript
-fields: {
- // Many-to-one (foreign key)
- customer: Field.lookup({
- label: 'Customer',
- object: 'customer',
- required: true,
- }),
-
- // Many-to-many (junction table)
- tags: Field.lookup({
- label: 'Tags',
- object: 'tag',
- multiple: true,
- }),
-}
-```
-
-### Advanced Fields
-
-```typescript
-fields: {
- // Computed field
- full_name: Field.formula({
- label: 'Full Name',
- returnType: 'text',
- expression: 'first_name + " " + last_name',
- }),
-
- // Rollup aggregation
- total_revenue: Field.rollup({
- label: 'Total Revenue',
- relatedObject: 'opportunity',
- aggregation: 'sum',
- field: 'amount',
- }),
-
- // JSON data
- metadata: Field.json({
- label: 'Metadata',
- }),
-
- // File attachment
- resume: Field.file({
- label: 'Resume',
- accept: ['.pdf', '.doc', '.docx'],
- maxSize: 5 * 1024 * 1024, // 5MB
- }),
-}
-```
-
-## Relationships
-
-Relationships are the key to modeling complex business logic. ObjectStack supports three types:
-
-### 1. Lookup (Many-to-One)
-
-**Scenario:** Each Task belongs to one Project.
-
-```typescript
-export const Task = Object({
- name: 'task',
- fields: {
- project: Field.lookup({
- label: 'Project',
- object: 'project',
- required: true,
- }),
- },
-});
-```
-
-**Database:**
-```sql
-CREATE TABLE task (
- id VARCHAR(18) PRIMARY KEY,
- project_id VARCHAR(18) NOT NULL,
- FOREIGN KEY (project_id) REFERENCES project(id)
-);
-```
-
-**Query:**
-```typescript
-// Get all tasks for a project
-const tasks = await ObjectQL.query({
- object: 'task',
- filter: { project: 'project_12345' },
-});
-
-// Include related project data
-const tasks = await ObjectQL.query({
- object: 'task',
- include: ['project'],
-});
-```
-
-### 2. Master-Detail (One-to-Many)
-
-**Scenario:** Each Project has many Tasks.
-
-```typescript
-export const Project = Object({
- name: 'project',
- fields: {
- // No explicit field needed, relationship is inferred
- },
-});
-```
-
-**Query:**
-```typescript
-// Get a project with all its tasks
-const project = await ObjectQL.query({
- object: 'project',
- id: 'project_12345',
- include: {
- tasks: {
- object: 'task',
- filter: { project: '$recordId' },
- },
- },
-});
-```
-
-**UI:**
-```typescript
-// In FormView, show related tasks
-{
- label: 'Tasks',
- component: 'related_list',
- object: 'task',
- filter: { project: '$recordId' },
-}
-```
-
-### 3. Many-to-Many
-
-**Scenario:** Each Task can have multiple Tags, and each Tag can be on multiple Tasks.
-
-```typescript
-export const Task = Object({
- name: 'task',
- fields: {
- tags: Field.lookup({
- label: 'Tags',
- object: 'tag',
- multiple: true, // Enables many-to-many
- }),
- },
-});
-```
-
-**Database (Junction Table):**
-```sql
-CREATE TABLE task (
- id VARCHAR(18) PRIMARY KEY
-);
-
-CREATE TABLE tag (
- id VARCHAR(18) PRIMARY KEY
-);
-
--- Auto-generated junction table
-CREATE TABLE task_tag (
- task_id VARCHAR(18),
- tag_id VARCHAR(18),
- PRIMARY KEY (task_id, tag_id),
- FOREIGN KEY (task_id) REFERENCES task(id),
- FOREIGN KEY (tag_id) REFERENCES tag(id)
-);
-```
-
-**Query:**
-```typescript
-// Get tasks with specific tags
-const tasks = await ObjectQL.query({
- object: 'task',
- filter: {
- tags: { contains: 'tag_urgent' },
- },
- include: ['tags'],
-});
-```
-
-## Reference Filters
-
-When you create a lookup field, you often want to limit which records can be selected. This is where **Reference Filters** come in.
-
-### Example: Territory-Based Filtering
-
-```typescript
-export const Opportunity = Object({
- name: 'opportunity',
- fields: {
- customer: Field.lookup({
- label: 'Customer',
- object: 'customer',
-
- // Only show customers in the same region
- referenceFilters: [
- {
- field: 'region',
- operator: 'equals',
- value: '$User.region',
- },
- ],
- }),
- },
-});
-```
-
-When a user creates an Opportunity, the Customer lookup will only show customers where `customer.region == user.region`.
-
-### Example: Dependent Lookups
-
-```typescript
-export const Task = Object({
- name: 'task',
- fields: {
- project: Field.lookup({
- label: 'Project',
- object: 'project',
- }),
-
- milestone: Field.lookup({
- label: 'Milestone',
- object: 'milestone',
-
- // Only show milestones from the selected project
- referenceFilters: [
- {
- field: 'project',
- operator: 'equals',
- value: '$Record.project',
- },
- ],
- }),
- },
-});
-```
-
-The Milestone dropdown dynamically filters based on the selected Project.
-
-## System Fields
-
-Every Object automatically includes system fields for auditing and tracking:
-
-```typescript
-// These fields are AUTOMATIC (you don't define them)
-{
- id: 'task_abc123', // Unique identifier
- created_at: '2024-01-15T10:30:00Z', // Creation timestamp
- created_by: 'user_xyz789', // User who created
- updated_at: '2024-01-16T14:20:00Z', // Last update timestamp
- updated_by: 'user_xyz789', // User who last updated
-}
-```
-
-If you enable `trackHistory`:
-
-```typescript
-{
- enable: {
- trackHistory: true,
- },
-}
-```
-
-You also get:
-
-```typescript
-{
- version: 5, // Record version number
- is_deleted: false, // Soft delete flag
-}
-```
-
-## Validation Rules
-
-Objects support three levels of validation:
-
-### 1. Field-Level Validation
-
-```typescript
-fields: {
- email: Field.email({
- label: 'Email',
- required: true, // Cannot be blank
- unique: true, // Must be unique across all records
- }),
-
- age: Field.number({
- label: 'Age',
- min: 18, // Must be >= 18
- max: 120, // Must be <= 120
- }),
-}
-```
-
-### 2. Object-Level Validation
-
-```typescript
-import { Validation } from '@objectstack/spec';
-
-export const OpportunityValidation = Validation({
- object: 'opportunity',
- rules: [
- {
- name: 'amount_required_when_closed',
- message: 'Amount is required when stage is Closed Won',
- condition: {
- field: 'stage',
- operator: 'equals',
- value: 'closed_won',
- },
- validates: {
- field: 'amount',
- operator: 'isNotNull',
- },
- },
- ],
-});
-```
-
-### 3. Custom Validation (Code)
-
-For complex logic that can't be expressed declaratively:
-
-```typescript
-import { CustomValidation } from '@objectstack/spec';
-
-export const LeadValidation = CustomValidation({
- object: 'lead',
- async validate(record, context) {
- // Check if email domain is blacklisted
- const domain = record.email.split('@')[1];
- const isBlacklisted = await context.db.query({
- object: 'blacklist',
- filter: { domain },
- });
-
- if (isBlacklisted.length > 0) {
- return {
- valid: false,
- errors: [{ field: 'email', message: 'Email domain is blacklisted' }],
- };
- }
-
- return { valid: true };
- },
-});
-```
-
-## Indexing and Performance
-
-ObjectStack automatically creates indexes for:
-- Primary keys (`id`)
-- Unique fields (`email`, etc.)
-- Lookup fields (foreign keys)
-
-For custom performance optimization:
-
-```typescript
-export const Customer = Object({
- name: 'customer',
- fields: {
- name: Field.text({ label: 'Name' }),
- region: Field.select({ label: 'Region', options: ['US', 'EU', 'APAC'] }),
- },
-
- // Custom indexes
- indexes: [
- {
- name: 'idx_customer_region_name',
- fields: ['region', 'name'],
- unique: false,
- },
- ],
-});
-```
-
-This creates:
-
-```sql
-CREATE INDEX idx_customer_region_name ON customer(region, name);
-```
-
-## Why a Universal Model Matters
-
-### 1. Consistency Across Domains
-
-Whether you're building a CRM, ERP, or custom app, you use the **same primitives**:
-
-```typescript
-// CRM
-const Customer = Object({ ... });
-const Opportunity = Object({ ... });
-
-// ERP
-const Product = Object({ ... });
-const Invoice = Object({ ... });
-
-// Project Management
-const Project = Object({ ... });
-const Task = Object({ ... });
-```
-
-Same API, same patterns, same tooling.
-
-### 2. Interoperability
-
-Because all Objects follow the same model, they can **reference each other**:
-
-```typescript
-// Link CRM to Projects
-export const Opportunity = Object({
- name: 'opportunity',
- fields: {
- customer: Field.lookup({ object: 'customer' }),
-
- // Reference an object from a different domain
- project: Field.lookup({ object: 'project' }),
- },
-});
-```
-
-### 3. Tooling Reuse
-
-Generic tools work across **all objects**:
-
-- **Form Builder:** Works for Customer, Task, Invoice, etc.
-- **Report Builder:** Aggregate any object
-- **API Generator:** Auto-generates endpoints for all objects
-- **Permission System:** Same ACL rules for everything
-
-### 4. AI/RAG Integration
-
-A universal model makes AI integration trivial:
-
-```typescript
-// AI agent can understand ANY object
-const schema = ObjectQL.getSchema('customer');
-const prompt = `Generate a query to find all ${schema.label} records where...`;
-```
-
-The AI doesn't need custom training for each object type.
-
-## Summary
-
-| Concept | Description |
-| :--- | :--- |
-| **Object** | A metadata definition of a business entity |
-| **Field** | A typed property of an object |
-| **Lookup** | A relationship between objects |
-| **Validation** | Rules enforced at save time |
-| **System Fields** | Automatic audit fields (id, created_at, etc.) |
-| **Reference Filters** | Contextual filtering of lookup options |
-
-The Universal Object Model is the foundation of ObjectStack. Every other protocol—permissions, workflows, views, reports—builds on top of these core primitives.
-
-## Next Steps
-
-- [ObjectQL Protocol](/docs/protocols/objectql) - Full specification of the data protocol
-- [Fields Reference](/docs/03-reference/fields) - Complete guide to all field types
-- [Relationships](/docs/04-guides/relationships) - Deep dive into modeling complex relationships
-- [Validation](/docs/04-guides/validation) - Advanced validation patterns
diff --git a/content/docs/core-concepts/the-stack.mdx b/content/docs/core-concepts/the-stack.mdx
deleted file mode 100644
index 7746304e6..000000000
--- a/content/docs/core-concepts/the-stack.mdx
+++ /dev/null
@@ -1,505 +0,0 @@
----
-title: The Stack - ObjectQL + ObjectUI + ObjectOS
-description: How the three protocols work together as one cohesive system
----
-
-import { Database, Layout, Cpu, ArrowRight, CheckCircle, Workflow } from 'lucide-react';
-
-# The Three-Layer Stack
-
-ObjectStack is built on three foundational protocols that work together as a unified system:
-
-
- }
- title="ObjectQL"
- description="Data Protocol - Structure and queries"
- />
- }
- title="ObjectOS"
- description="Control Protocol - Runtime and governance"
- />
- }
- title="ObjectUI"
- description="View Protocol - Presentation and interaction"
- />
-
-
-## Why Three Layers?
-
-Traditional applications tightly couple data, business logic, and presentation. This creates **Implementation Coupling** — changing one layer forces changes across the entire stack.
-
-ObjectStack enforces **Separation of Concerns** through protocol boundaries:
-
-```
-┌─────────────────────────────────────────┐
-│ ObjectUI (View Layer) │
-│ Apps, Views, Dashboards, Reports │
-│ "How do users interact?" │
-└──────────────┬──────────────────────────┘
- │ API Protocol
-┌──────────────┴──────────────────────────┐
-│ ObjectOS (Control Layer) │
-│ Auth, Permissions, Workflows, Events │
-│ "Who can do what, when?" │
-└──────────────┬──────────────────────────┘
- │ Query Protocol
-┌──────────────┴──────────────────────────┐
-│ ObjectQL (Data Layer) │
-│ Objects, Fields, Queries, Drivers │
-│ "What is the data structure?" │
-└─────────────────────────────────────────┘
-```
-
-## Layer 1: ObjectQL (Data Protocol)
-
-**Role:** Define the **Structure** and **Intent** of data.
-
-**Responsibilities:**
-- Object schema definitions (what is a "Customer"?)
-- Field types and validation rules
-- Query language (filtering, sorting, aggregation)
-- Database drivers (Postgres, MongoDB, SQLite)
-
-**Key Principle:** ObjectQL knows **nothing** about users, permissions, or UI. It only cares about data structure and queries.
-
-### Example: Defining a Customer Object
-
-```typescript
-// packages/crm/src/objects/customer.object.ts
-import { Object, Field } from '@objectstack/spec';
-
-export const Customer = Object({
- name: 'customer',
- label: 'Customer',
- fields: {
- name: Field.text({
- label: 'Company Name',
- required: true,
- maxLength: 120,
- }),
- industry: Field.select({
- label: 'Industry',
- options: ['technology', 'finance', 'healthcare', 'retail'],
- }),
- annual_revenue: Field.currency({
- label: 'Annual Revenue',
- }),
- primary_contact: Field.lookup({
- label: 'Primary Contact',
- object: 'contact',
- }),
- },
-});
-```
-
-This definition is **pure metadata**. It doesn't know:
-- Who can see this data
-- How to render a form
-- When to trigger workflows
-
-That's the job of the other layers.
-
-## Layer 2: ObjectOS (Control Protocol)
-
-**Role:** Manage the **Lifecycle** and **Governance** of requests.
-
-**Responsibilities:**
-- Authentication (who is this user?)
-- Authorization (can they access this field?)
-- Workflows and automations (what happens after save?)
-- Event processing (audit logs, notifications)
-- Multi-tenancy and data isolation
-
-**Key Principle:** ObjectOS acts as the **Gateway**. No layer can directly access the database; all requests must pass through the OS Kernel.
-
-### Example: Permission Rules
-
-```typescript
-// packages/crm/src/permissions/customer.permission.ts
-import { Permission } from '@objectstack/spec';
-
-export const CustomerPermission = Permission({
- object: 'customer',
- rules: [
- {
- profile: 'sales_rep',
- crud: {
- create: true,
- read: true,
- update: true,
- delete: false, // Only managers can delete
- },
- fieldPermissions: {
- annual_revenue: { read: true, edit: false }, // Read-only
- },
- },
- {
- profile: 'sales_manager',
- crud: {
- create: true,
- read: true,
- update: true,
- delete: true,
- },
- },
- ],
-});
-```
-
-### Example: Workflow Automation
-
-```typescript
-// packages/crm/src/workflows/customer.workflow.ts
-import { Workflow } from '@objectstack/spec';
-
-export const CustomerWorkflow = Workflow({
- object: 'customer',
- trigger: 'after_create',
- conditions: [
- { field: 'annual_revenue', operator: 'greaterThan', value: 1000000 },
- ],
- actions: [
- {
- type: 'assign_owner',
- params: { owner: 'enterprise_sales_team' },
- },
- {
- type: 'send_email',
- params: {
- template: 'high_value_customer_alert',
- to: 'sales-leadership@company.com',
- },
- },
- ],
-});
-```
-
-ObjectOS **orchestrates** these rules at runtime, independent of the data structure or UI.
-
-## Layer 3: ObjectUI (View Protocol)
-
-**Role:** Render the **Presentation** and handle **User Interaction**.
-
-**Responsibilities:**
-- App navigation and branding
-- List views (grid, kanban, calendar)
-- Form layouts (simple, tabbed, wizard)
-- Dashboards and reports
-- Actions and buttons
-
-**Key Principle:** ObjectUI is a **Rendering Engine**, not a hardcoded interface. It asks ObjectQL *"What is the schema?"* and dynamically generates the UI.
-
-### Example: List View
-
-```typescript
-// packages/crm/src/views/customer_list.view.ts
-import { ListView } from '@objectstack/spec';
-
-export const CustomerListView = ListView({
- object: 'customer',
- label: 'All Customers',
- type: 'grid',
- columns: [
- { field: 'name', width: 200 },
- { field: 'industry', width: 150 },
- { field: 'annual_revenue', width: 150 },
- { field: 'primary_contact', width: 180 },
- ],
- filters: [
- { field: 'industry', operator: 'equals' },
- { field: 'annual_revenue', operator: 'greaterThan' },
- ],
- defaultSort: { field: 'name', direction: 'asc' },
-});
-```
-
-### Example: Form View
-
-```typescript
-// packages/crm/src/views/customer_form.view.ts
-import { FormView } from '@objectstack/spec';
-
-export const CustomerFormView = FormView({
- object: 'customer',
- label: 'Customer Details',
- type: 'tabbed',
- tabs: [
- {
- label: 'Overview',
- sections: [
- {
- label: 'Company Information',
- fields: ['name', 'industry', 'annual_revenue'],
- },
- {
- label: 'Contact',
- fields: ['primary_contact'],
- },
- ],
- },
- {
- label: 'Related Records',
- sections: [
- {
- label: 'Opportunities',
- component: 'related_list',
- object: 'opportunity',
- filter: { customer: '$recordId' },
- },
- ],
- },
- ],
-});
-```
-
-The UI doesn't "know" the field types. It asks ObjectQL for the schema and renders accordingly:
-- `Field.text` → Text input
-- `Field.select` → Dropdown
-- `Field.lookup` → Autocomplete lookup
-- `Field.currency` → Number input with currency formatting
-
-## How They Work Together
-
-Let's trace a **real-world scenario**: A sales rep creates a new high-value customer.
-
-### Step 1: User Action (ObjectUI)
-
-```
-User fills out the "Create Customer" form:
-- Name: "Acme Corp"
-- Industry: "Technology"
-- Annual Revenue: $5,000,000
-- Primary Contact: "John Doe"
-
-User clicks "Save"
-```
-
-### Step 2: UI Layer Sends Request
-
-```typescript
-// ObjectUI dispatches an action to ObjectOS
-const request = {
- action: 'create',
- object: 'customer',
- data: {
- name: 'Acme Corp',
- industry: 'technology',
- annual_revenue: 5000000,
- primary_contact: 'contact_12345',
- },
-};
-```
-
-### Step 3: ObjectOS Validates Permissions
-
-```typescript
-// Kernel checks: Does this user have permission?
-const user = await Auth.getCurrentUser();
-const canCreate = await Permission.check({
- user,
- object: 'customer',
- operation: 'create',
-});
-
-if (!canCreate) {
- throw new Error('Permission denied');
-}
-```
-
-### Step 4: ObjectOS Validates Data
-
-```typescript
-// Kernel asks ObjectQL: Is this data valid?
-const schema = ObjectQL.getSchema('customer');
-const validation = schema.validate(request.data);
-
-if (!validation.success) {
- throw new ValidationError(validation.errors);
-}
-```
-
-### Step 5: ObjectQL Writes to Database
-
-```typescript
-// ObjectQL compiles the request into a database operation
-const driver = ObjectQL.getDriver(); // Postgres, MongoDB, etc.
-const result = await driver.insert('customer', {
- name: 'Acme Corp',
- industry: 'technology',
- annual_revenue: 5000000,
- primary_contact_id: 'contact_12345',
-});
-```
-
-### Step 6: ObjectOS Triggers Workflows
-
-```typescript
-// Kernel checks: Are there any workflows for this event?
-const workflows = Workflow.getTriggersFor('customer', 'after_create');
-
-for (const workflow of workflows) {
- if (workflow.conditionsMet(result)) {
- await workflow.execute(result);
- }
-}
-
-// In this case:
-// ✅ Annual revenue > $1M
-// → Assign to enterprise sales team
-// → Send alert email to leadership
-```
-
-### Step 7: ObjectUI Updates Display
-
-```typescript
-// Kernel returns success response
-// UI optimistically updates the screen
-// UI shows toast notification: "Customer created successfully"
-// UI navigates to the new customer detail page
-```
-
-## The Full Stack in Action
-
-Here's how all three protocols collaborate for a **Kanban Board** feature:
-
-### 1. ObjectQL: Define the Data
-
-```typescript
-export const Opportunity = Object({
- name: 'opportunity',
- fields: {
- title: Field.text({ required: true }),
- stage: Field.select({
- options: ['prospecting', 'qualification', 'proposal', 'closed_won'],
- }),
- amount: Field.currency(),
- customer: Field.lookup({ object: 'customer' }),
- },
-});
-```
-
-### 2. ObjectOS: Define Business Rules
-
-```typescript
-export const OpportunityWorkflow = Workflow({
- object: 'opportunity',
- trigger: 'field_update',
- conditions: [
- { field: 'stage', operator: 'equals', value: 'closed_won' },
- ],
- actions: [
- { type: 'create_invoice', params: { object: 'invoice' } },
- { type: 'send_notification', params: { to: 'sales_team' } },
- ],
-});
-```
-
-### 3. ObjectUI: Define the Kanban View
-
-```typescript
-export const OpportunityKanban = ListView({
- object: 'opportunity',
- type: 'kanban',
- groupBy: 'stage',
- columns: [
- { field: 'title' },
- { field: 'amount' },
- { field: 'customer' },
- ],
- enableDragDrop: true,
-});
-```
-
-### The Result
-
-When a user **drags an opportunity card** from "Proposal" to "Closed Won":
-
-1. **ObjectUI** captures the drag-drop event
-2. **ObjectOS** checks if the user has permission to update the `stage` field
-3. **ObjectQL** validates that `"closed_won"` is a valid option
-4. **ObjectQL** writes the update to the database
-5. **ObjectOS** triggers the workflow (create invoice, send notification)
-6. **ObjectUI** updates the kanban board to reflect the new state
-
-**All from metadata. Zero hardcoded logic.**
-
-## Benefits of the Three-Layer Architecture
-
-### 1. Technology Independence
-
-Swap implementations without breaking the system:
-
-```
-Same Metadata Definitions
- ↓
-┌─────────┼─────────┐
-ObjectQL: │ │
-Postgres │ MongoDB
- │
-ObjectOS: │
-Node.js │ Python
- │
-ObjectUI: │
-React │ Flutter
-```
-
-### 2. Parallel Development
-
-Teams can work independently on each layer:
-
-- **Data Team:** Define objects in ObjectQL
-- **Backend Team:** Build workflows in ObjectOS
-- **Frontend Team:** Create views in ObjectUI
-
-All communicate through **protocol contracts**, not code dependencies.
-
-### 3. Incremental Migration
-
-Adopt ObjectStack gradually:
-
-- **Phase 1:** Use ObjectQL as an ORM replacement
-- **Phase 2:** Add ObjectOS for permissions and workflows
-- **Phase 3:** Build ObjectUI views to replace custom forms
-
-Each layer is independently useful.
-
-### 4. Testability
-
-Mock any layer for testing:
-
-```typescript
-// Test ObjectOS workflows without a real database
-const mockObjectQL = {
- getSchema: () => CustomerSchema,
- insert: jest.fn(),
-};
-
-// Test ObjectUI rendering without a real backend
-const mockObjectOS = {
- checkPermission: () => true,
- executeQuery: () => mockData,
-};
-```
-
-## Summary
-
-| Layer | Role | Knows About | Doesn't Know About |
-| :--- | :--- | :--- | :--- |
-| **ObjectQL** | Data structure & queries | Schema, fields, drivers | Users, permissions, UI |
-| **ObjectOS** | Runtime & governance | Auth, workflows, events | Data structure, UI layout |
-| **ObjectUI** | Presentation & interaction | Layout, navigation, actions | Business logic, data storage |
-
-The three protocols are **loosely coupled** but **tightly integrated**:
-- They communicate through **standard contracts** (Zod schemas)
-- They can be **swapped or upgraded** independently
-- They form a **complete system** when combined
-
-## Next Steps
-
-- [Object Model](/docs/core-concepts/object-model) - Deep dive into ObjectQL's universal object model
-- [ObjectQL Protocol](/docs/protocols/objectql) - Full data protocol specification
-- [ObjectOS Protocol](/docs/protocols/objectos) - Full control protocol specification
-- [ObjectUI Protocol](/docs/protocols/objectui) - Full view protocol specification
diff --git a/content/docs/development/cli-tools.mdx b/content/docs/developers/cli-tools.mdx
similarity index 100%
rename from content/docs/development/cli-tools.mdx
rename to content/docs/developers/cli-tools.mdx
diff --git a/content/docs/development/custom-widgets.mdx b/content/docs/developers/custom-widgets.mdx
similarity index 100%
rename from content/docs/development/custom-widgets.mdx
rename to content/docs/developers/custom-widgets.mdx
diff --git a/content/docs/development/index.mdx b/content/docs/developers/index.mdx
similarity index 100%
rename from content/docs/development/index.mdx
rename to content/docs/developers/index.mdx
diff --git a/content/docs/development/meta.json b/content/docs/developers/meta.json
similarity index 90%
rename from content/docs/development/meta.json
rename to content/docs/developers/meta.json
index 9a8119d91..456a1fe79 100644
--- a/content/docs/development/meta.json
+++ b/content/docs/developers/meta.json
@@ -1,5 +1,6 @@
{
"title": "🔧 Development & Extension",
+ "root": true,
"pages": [
"writing-plugins",
"custom-widgets",
diff --git a/content/docs/development/server-drivers.mdx b/content/docs/developers/server-drivers.mdx
similarity index 100%
rename from content/docs/development/server-drivers.mdx
rename to content/docs/developers/server-drivers.mdx
diff --git a/content/docs/development/writing-plugins.mdx b/content/docs/developers/writing-plugins.mdx
similarity index 100%
rename from content/docs/development/writing-plugins.mdx
rename to content/docs/developers/writing-plugins.mdx
diff --git a/content/docs/introduction/architecture.mdx b/content/docs/introduction/architecture.mdx
index 5f293bd33..7746304e6 100644
--- a/content/docs/introduction/architecture.mdx
+++ b/content/docs/introduction/architecture.mdx
@@ -1,201 +1,505 @@
---
-title: Architecture
-description: Understanding the ObjectStack Protocol Architecture - How 11 protocol namespaces collaborate to build the Enterprise Kernel
+title: The Stack - ObjectQL + ObjectUI + ObjectOS
+description: How the three protocols work together as one cohesive system
---
-import { Layers, Database, Layout, ShieldCheck, Lock, Cog, Brain, Cloud, Zap } from 'lucide-react';
+import { Database, Layout, Cpu, ArrowRight, CheckCircle, Workflow } from 'lucide-react';
-# Architecture Overview
+# The Three-Layer Stack
-ObjectStack is not a monolithic framework. It is a composable ecosystem designed around a **Protocol-Driven Architecture**. The system is organized into **11 protocol namespaces**, each responsible for a specific domain.
-
-Each protocol is decoupled and communicates via standard JSON schemas defined with Zod. This allows you to swap out implementations (e.g., swapping the Postgres driver for MongoDB, or the React renderer for Flutter) without breaking the rest of the stack.
-
-## The 11 Protocol Namespaces
-
-ObjectStack is organized into 11 protocol namespaces:
+ObjectStack is built on three foundational protocols that work together as a unified system:
}
- title="Data Protocol"
- description="Object schema, fields, validation, and queries."
- />
- }
- title="Driver Protocol"
- description="Database adapters (Postgres, MongoDB, SQLite, etc.)."
+ title="ObjectQL"
+ description="Data Protocol - Structure and queries"
/>
}
- title="Permission Protocol"
- description="Object-level, field-level, sharing, and territory rules."
+ icon={}
+ title="ObjectOS"
+ description="Control Protocol - Runtime and governance"
/>
}
- title="UI Protocol"
- description="Apps, views, dashboards, reports, and themes."
- />
- }
- title="System Protocol"
- description="Events, jobs, translations, and audit logging."
- />
- }
- title="Auth Protocol"
- description="Identity, roles, sessions, and authentication strategies."
- />
- }
- title="Kernel Protocol"
- description="Plugin lifecycle, manifest, logging, and context."
- />
- }
- title="Hub Protocol"
- description="Marketplace, licensing, tenancy, and deployment."
- />
- }
- title="AI Protocol"
- description="Agents, RAG, NLQ, predictive models, and orchestration."
- />
- }
- title="API Protocol"
- description="REST contracts, discovery, realtime, and routing."
- />
- }
- title="Automation Protocol"
- description="Workflows, flows, and webhooks."
+ title="ObjectUI"
+ description="View Protocol - Presentation and interaction"
/>
-## The Three-Layer Architecture
+## Why Three Layers?
-While ObjectStack has 11 protocol namespaces, they are logically grouped into three architectural layers:
+Traditional applications tightly couple data, business logic, and presentation. This creates **Implementation Coupling** — changing one layer forces changes across the entire stack.
-### 1. Data Layer (ObjectQL)
-**"The Universal Data Protocol"**
+ObjectStack enforces **Separation of Concerns** through protocol boundaries:
-The foundation layer responsible for **Data Definition** and **Data Access**.
+```
+┌─────────────────────────────────────────┐
+│ ObjectUI (View Layer) │
+│ Apps, Views, Dashboards, Reports │
+│ "How do users interact?" │
+└──────────────┬──────────────────────────┘
+ │ API Protocol
+┌──────────────┴──────────────────────────┐
+│ ObjectOS (Control Layer) │
+│ Auth, Permissions, Workflows, Events │
+│ "Who can do what, when?" │
+└──────────────┬──────────────────────────┘
+ │ Query Protocol
+┌──────────────┴──────────────────────────┐
+│ ObjectQL (Data Layer) │
+│ Objects, Fields, Queries, Drivers │
+│ "What is the data structure?" │
+└─────────────────────────────────────────┘
+```
-**Protocols:**
-- **Data Protocol:** Object schema, fields, validation, queries, filters
-- **Driver Protocol:** Database adapters for Postgres, MongoDB, SQLite, etc.
-- **Permission Protocol:** Object-level CRUD, field-level security, sharing rules
-- **AI Protocol:** AI agents, RAG pipelines, NLQ, predictive models
+## Layer 1: ObjectQL (Data Protocol)
+
+**Role:** Define the **Structure** and **Intent** of data.
+
+**Responsibilities:**
+- Object schema definitions (what is a "Customer"?)
+- Field types and validation rules
+- Query language (filtering, sorting, aggregation)
+- Database drivers (Postgres, MongoDB, SQLite)
+
+**Key Principle:** ObjectQL knows **nothing** about users, permissions, or UI. It only cares about data structure and queries.
+
+### Example: Defining a Customer Object
+
+```typescript
+// packages/crm/src/objects/customer.object.ts
+import { Object, Field } from '@objectstack/spec';
+
+export const Customer = Object({
+ name: 'customer',
+ label: 'Customer',
+ fields: {
+ name: Field.text({
+ label: 'Company Name',
+ required: true,
+ maxLength: 120,
+ }),
+ industry: Field.select({
+ label: 'Industry',
+ options: ['technology', 'finance', 'healthcare', 'retail'],
+ }),
+ annual_revenue: Field.currency({
+ label: 'Annual Revenue',
+ }),
+ primary_contact: Field.lookup({
+ label: 'Primary Contact',
+ object: 'contact',
+ }),
+ },
+});
+```
-**Role:** Defines *Structure* (Schema) and *Intent* (Query AST).
+This definition is **pure metadata**. It doesn't know:
+- Who can see this data
+- How to render a form
+- When to trigger workflows
+
+That's the job of the other layers.
+
+## Layer 2: ObjectOS (Control Protocol)
+
+**Role:** Manage the **Lifecycle** and **Governance** of requests.
+
+**Responsibilities:**
+- Authentication (who is this user?)
+- Authorization (can they access this field?)
+- Workflows and automations (what happens after save?)
+- Event processing (audit logs, notifications)
+- Multi-tenancy and data isolation
+
+**Key Principle:** ObjectOS acts as the **Gateway**. No layer can directly access the database; all requests must pass through the OS Kernel.
+
+### Example: Permission Rules
+
+```typescript
+// packages/crm/src/permissions/customer.permission.ts
+import { Permission } from '@objectstack/spec';
+
+export const CustomerPermission = Permission({
+ object: 'customer',
+ rules: [
+ {
+ profile: 'sales_rep',
+ crud: {
+ create: true,
+ read: true,
+ update: true,
+ delete: false, // Only managers can delete
+ },
+ fieldPermissions: {
+ annual_revenue: { read: true, edit: false }, // Read-only
+ },
+ },
+ {
+ profile: 'sales_manager',
+ crud: {
+ create: true,
+ read: true,
+ update: true,
+ delete: true,
+ },
+ },
+ ],
+});
+```
-**Responsibility:** It knows *what* a "Customer" object looks like, but it doesn't know *who* is accessing it or *how* it is displayed.
+### Example: Workflow Automation
+
+```typescript
+// packages/crm/src/workflows/customer.workflow.ts
+import { Workflow } from '@objectstack/spec';
+
+export const CustomerWorkflow = Workflow({
+ object: 'customer',
+ trigger: 'after_create',
+ conditions: [
+ { field: 'annual_revenue', operator: 'greaterThan', value: 1000000 },
+ ],
+ actions: [
+ {
+ type: 'assign_owner',
+ params: { owner: 'enterprise_sales_team' },
+ },
+ {
+ type: 'send_email',
+ params: {
+ template: 'high_value_customer_alert',
+ to: 'sales-leadership@company.com',
+ },
+ },
+ ],
+});
+```
-**Key Component:** The **Compiler**. It takes an abstract query (`find customers where active = true`) and translates it into optimized SQL/NoSQL queries for the specific underlying database.
+ObjectOS **orchestrates** these rules at runtime, independent of the data structure or UI.
+
+## Layer 3: ObjectUI (View Protocol)
+
+**Role:** Render the **Presentation** and handle **User Interaction**.
+
+**Responsibilities:**
+- App navigation and branding
+- List views (grid, kanban, calendar)
+- Form layouts (simple, tabbed, wizard)
+- Dashboards and reports
+- Actions and buttons
+
+**Key Principle:** ObjectUI is a **Rendering Engine**, not a hardcoded interface. It asks ObjectQL *"What is the schema?"* and dynamically generates the UI.
+
+### Example: List View
+
+```typescript
+// packages/crm/src/views/customer_list.view.ts
+import { ListView } from '@objectstack/spec';
+
+export const CustomerListView = ListView({
+ object: 'customer',
+ label: 'All Customers',
+ type: 'grid',
+ columns: [
+ { field: 'name', width: 200 },
+ { field: 'industry', width: 150 },
+ { field: 'annual_revenue', width: 150 },
+ { field: 'primary_contact', width: 180 },
+ ],
+ filters: [
+ { field: 'industry', operator: 'equals' },
+ { field: 'annual_revenue', operator: 'greaterThan' },
+ ],
+ defaultSort: { field: 'name', direction: 'asc' },
+});
+```
-### 2. Presentation Layer (ObjectUI)
-**"Server-Driven UI"**
+### Example: Form View
+
+```typescript
+// packages/crm/src/views/customer_form.view.ts
+import { FormView } from '@objectstack/spec';
+
+export const CustomerFormView = FormView({
+ object: 'customer',
+ label: 'Customer Details',
+ type: 'tabbed',
+ tabs: [
+ {
+ label: 'Overview',
+ sections: [
+ {
+ label: 'Company Information',
+ fields: ['name', 'industry', 'annual_revenue'],
+ },
+ {
+ label: 'Contact',
+ fields: ['primary_contact'],
+ },
+ ],
+ },
+ {
+ label: 'Related Records',
+ sections: [
+ {
+ label: 'Opportunities',
+ component: 'related_list',
+ object: 'opportunity',
+ filter: { customer: '$recordId' },
+ },
+ ],
+ },
+ ],
+});
+```
-The interface layer responsible for **Visual Representation** and **User Interaction**.
+The UI doesn't "know" the field types. It asks ObjectQL for the schema and renders accordingly:
+- `Field.text` → Text input
+- `Field.select` → Dropdown
+- `Field.lookup` → Autocomplete lookup
+- `Field.currency` → Number input with currency formatting
-**Protocols:**
-- **UI Protocol:** Apps, views, dashboards, reports, actions, themes
+## How They Work Together
-**Role:** Projects the Data Protocol into visual components.
+Let's trace a **real-world scenario**: A sales rep creates a new high-value customer.
-**Responsibility:** It knows *how* to display a "Customer" form, but it doesn't know the business rules or who can access it.
+### Step 1: User Action (ObjectUI)
-**Key Component:** The **Renderer**. It takes UI metadata (JSON) and renders it as native components (React, Flutter, etc.).
+```
+User fills out the "Create Customer" form:
+- Name: "Acme Corp"
+- Industry: "Technology"
+- Annual Revenue: $5,000,000
+- Primary Contact: "John Doe"
-### 3. Control Layer (ObjectOS)
-**"The Business Kernel"**
+User clicks "Save"
+```
-The orchestration layer responsible for **Runtime** and **Governance**.
+### Step 2: UI Layer Sends Request
+
+```typescript
+// ObjectUI dispatches an action to ObjectOS
+const request = {
+ action: 'create',
+ object: 'customer',
+ data: {
+ name: 'Acme Corp',
+ industry: 'technology',
+ annual_revenue: 5000000,
+ primary_contact: 'contact_12345',
+ },
+};
+```
-**Protocols:**
-- **System Protocol:** Events, jobs, translations, audit logging
-- **Auth Protocol:** Identity, roles, sessions, authentication
-- **Kernel Protocol:** Plugin lifecycle, manifest, context
-- **Hub Protocol:** Marketplace, licensing, tenancy
-- **API Protocol:** REST contracts, discovery, realtime
-- **Automation Protocol:** Workflows, flows, webhooks
+### Step 3: ObjectOS Validates Permissions
-**Role:** Orchestrates the entire system and enforces policies.
+```typescript
+// Kernel checks: Does this user have permission?
+const user = await Auth.getCurrentUser();
+const canCreate = await Permission.check({
+ user,
+ object: 'customer',
+ operation: 'create',
+});
-**Responsibility:** It knows *who* is accessing *what* and *when* actions should happen.
+if (!canCreate) {
+ throw new Error('Permission denied');
+}
+```
-**Key Component:** The **Kernel**. It manages plugins, handles events, enforces security, and coordinates between layers.
+### Step 4: ObjectOS Validates Data
-## How They Work Together
+```typescript
+// Kernel asks ObjectQL: Is this data valid?
+const schema = ObjectQL.getSchema('customer');
+const validation = schema.validate(request.data);
+if (!validation.success) {
+ throw new ValidationError(validation.errors);
+}
```
-┌─────────────────────────────────────────┐
-│ Control Layer (ObjectOS) │
-│ ┌──────────┐ ┌────────┐ ┌──────────┐│
-│ │ Kernel │ │ Auth │ │ System ││
-│ │ Protocol │ │Protocol│ │ Protocol ││
-│ └──────────┘ └────────┘ └──────────┘│
-└─────────────────────────────────────────┘
- ↕ ↕
-┌──────────────────┐ ┌──────────────────┐
-│ Data Layer (QL) │ │ UI Layer (UI) │
-│ ┌────────────┐ │ │ ┌────────────┐ │
-│ │ Data │ │ │ │ UI │ │
-│ │ Protocol │ │ │ │ Protocol │ │
-│ └────────────┘ │ │ └────────────┘ │
-│ ┌────────────┐ │ │ │
-│ │ Driver │ │ │ │
-│ │ Protocol │ │ │ │
-│ └────────────┘ │ │ │
-└──────────────────┘ └──────────────────┘
- ↕
- ┌──────────┐
- │ Database │
- └──────────┘
+
+### Step 5: ObjectQL Writes to Database
+
+```typescript
+// ObjectQL compiles the request into a database operation
+const driver = ObjectQL.getDriver(); // Postgres, MongoDB, etc.
+const result = await driver.insert('customer', {
+ name: 'Acme Corp',
+ industry: 'technology',
+ annual_revenue: 5000000,
+ primary_contact_id: 'contact_12345',
+});
+```
+
+### Step 6: ObjectOS Triggers Workflows
+
+```typescript
+// Kernel checks: Are there any workflows for this event?
+const workflows = Workflow.getTriggersFor('customer', 'after_create');
+
+for (const workflow of workflows) {
+ if (workflow.conditionsMet(result)) {
+ await workflow.execute(result);
+ }
+}
+
+// In this case:
+// ✅ Annual revenue > $1M
+// → Assign to enterprise sales team
+// → Send alert email to leadership
+```
+
+### Step 7: ObjectUI Updates Display
+
+```typescript
+// Kernel returns success response
+// UI optimistically updates the screen
+// UI shows toast notification: "Customer created successfully"
+// UI navigates to the new customer detail page
+```
+
+## The Full Stack in Action
+
+Here's how all three protocols collaborate for a **Kanban Board** feature:
+
+### 1. ObjectQL: Define the Data
+
+```typescript
+export const Opportunity = Object({
+ name: 'opportunity',
+ fields: {
+ title: Field.text({ required: true }),
+ stage: Field.select({
+ options: ['prospecting', 'qualification', 'proposal', 'closed_won'],
+ }),
+ amount: Field.currency(),
+ customer: Field.lookup({ object: 'customer' }),
+ },
+});
+```
+
+### 2. ObjectOS: Define Business Rules
+
+```typescript
+export const OpportunityWorkflow = Workflow({
+ object: 'opportunity',
+ trigger: 'field_update',
+ conditions: [
+ { field: 'stage', operator: 'equals', value: 'closed_won' },
+ ],
+ actions: [
+ { type: 'create_invoice', params: { object: 'invoice' } },
+ { type: 'send_notification', params: { to: 'sales_team' } },
+ ],
+});
+```
+
+### 3. ObjectUI: Define the Kanban View
+
+```typescript
+export const OpportunityKanban = ListView({
+ object: 'opportunity',
+ type: 'kanban',
+ groupBy: 'stage',
+ columns: [
+ { field: 'title' },
+ { field: 'amount' },
+ { field: 'customer' },
+ ],
+ enableDragDrop: true,
+});
```
-### Example: Creating a Record
+### The Result
+
+When a user **drags an opportunity card** from "Proposal" to "Closed Won":
+
+1. **ObjectUI** captures the drag-drop event
+2. **ObjectOS** checks if the user has permission to update the `stage` field
+3. **ObjectQL** validates that `"closed_won"` is a valid option
+4. **ObjectQL** writes the update to the database
+5. **ObjectOS** triggers the workflow (create invoice, send notification)
+6. **ObjectUI** updates the kanban board to reflect the new state
-1. **UI Layer:** User clicks "Save" on a Customer form
-2. **Control Layer:** Kernel receives the request, validates authentication
-3. **Data Layer:** ObjectQL compiler generates SQL INSERT statement
-4. **Driver:** PostgreSQL driver executes the query
-5. **Control Layer:** Event system triggers "after_create" workflow
-6. **UI Layer:** Renderer updates the interface with the new record
+**All from metadata. Zero hardcoded logic.**
-## Protocol vs Implementation
+## Benefits of the Three-Layer Architecture
-**Critical Distinction:**
+### 1. Technology Independence
+
+Swap implementations without breaking the system:
+
+```
+Same Metadata Definitions
+ ↓
+┌─────────┼─────────┐
+ObjectQL: │ │
+Postgres │ MongoDB
+ │
+ObjectOS: │
+Node.js │ Python
+ │
+ObjectUI: │
+React │ Flutter
+```
-- **Protocol Layer:** Defined in `packages/spec` (This Repository)
- - Pure Zod schemas
- - TypeScript types
- - No runtime logic
+### 2. Parallel Development
-- **Runtime Layer:** Implemented in separate packages
- - Node.js Kernel (`@objectstack/kernel`)
- - React Renderer (`@objectstack/react`)
- - PostgreSQL Driver (`@objectstack/driver-postgres`)
+Teams can work independently on each layer:
-The protocol defines the "what" and "how." The runtime implements it.
+- **Data Team:** Define objects in ObjectQL
+- **Backend Team:** Build workflows in ObjectOS
+- **Frontend Team:** Create views in ObjectUI
-## Design Benefits
+All communicate through **protocol contracts**, not code dependencies.
-### 1. Composability
-Each protocol can be used independently or combined with others.
+### 3. Incremental Migration
+
+Adopt ObjectStack gradually:
+
+- **Phase 1:** Use ObjectQL as an ORM replacement
+- **Phase 2:** Add ObjectOS for permissions and workflows
+- **Phase 3:** Build ObjectUI views to replace custom forms
+
+Each layer is independently useful.
+
+### 4. Testability
+
+Mock any layer for testing:
+
+```typescript
+// Test ObjectOS workflows without a real database
+const mockObjectQL = {
+ getSchema: () => CustomerSchema,
+ insert: jest.fn(),
+};
+
+// Test ObjectUI rendering without a real backend
+const mockObjectOS = {
+ checkPermission: () => true,
+ executeQuery: () => mockData,
+};
+```
-### 2. Replaceability
-Don't like the React renderer? Build a Vue or Flutter one. The protocol stays the same.
+## Summary
-### 3. Testability
-Test against the protocol specification, not a specific implementation.
+| Layer | Role | Knows About | Doesn't Know About |
+| :--- | :--- | :--- | :--- |
+| **ObjectQL** | Data structure & queries | Schema, fields, drivers | Users, permissions, UI |
+| **ObjectOS** | Runtime & governance | Auth, workflows, events | Data structure, UI layout |
+| **ObjectUI** | Presentation & interaction | Layout, navigation, actions | Business logic, data storage |
-### 4. Future-Proof
-New features are additive, not breaking. Implementations can evolve independently.
+The three protocols are **loosely coupled** but **tightly integrated**:
+- They communicate through **standard contracts** (Zod schemas)
+- They can be **swapped or upgraded** independently
+- They form a **complete system** when combined
## Next Steps
-- [Glossary](/docs/introduction/glossary) - Key terminology explained
-- [Core Concepts](/docs/core-concepts) - Understand metadata-driven development
-- [Protocols](/docs/protocols) - Dive into each protocol specification
+- [Object Model](/docs/core-concepts/object-model) - Deep dive into ObjectQL's universal object model
+- [ObjectQL Protocol](/docs/protocols/objectql) - Full data protocol specification
+- [ObjectOS Protocol](/docs/protocols/objectos) - Full control protocol specification
+- [ObjectUI Protocol](/docs/protocols/objectui) - Full view protocol specification
diff --git a/content/docs/introduction/glossary.mdx b/content/docs/introduction/glossary.mdx
deleted file mode 100644
index c6e4ac7f0..000000000
--- a/content/docs/introduction/glossary.mdx
+++ /dev/null
@@ -1,189 +0,0 @@
----
-title: Glossary
-description: Key terminology for the ObjectStack ecosystem - Speaking the same language
----
-
-import { Book, Server, Code, Database } from 'lucide-react';
-
-# Glossary
-
-To navigate the ObjectStack ecosystem effectively, it's helpful to understand the specific vocabulary we use. While many terms are standard in computer science, some have specific nuances in our "Protocol-Driven" context.
-
-## Core Concepts
-
-### ObjectStack
-The umbrella term for the entire suite of protocols and reference implementations. It is organized into **11 protocol namespaces** grouped into three architectural layers.
-
-### Protocol
-A specification defined with Zod schemas that describes how a system component should behave. Protocols are implementation-agnostic - they define the "what" and "how," not the specific code.
-
-### Protocol Namespace
-A logical grouping of related schemas and types. ObjectStack has 11 protocol namespaces: Data, Driver, Permission, UI, System, Auth, Kernel, Hub, AI, API, and Automation.
-
-### Kernel
-The runtime engine (Control Layer) that orchestrates all protocols, manages plugins, and enforces security policies.
-
----
-
-## The Three Layers
-
-### ObjectQL (Data Layer)
-The database-agnostic data protocol. Defines objects, fields, queries, and filters. Think of it as "universal SQL" that compiles to any backend.
-
-### ObjectUI (Presentation Layer)
-The server-driven UI protocol. Defines apps, views, dashboards, and themes as JSON metadata. The renderer converts this to native components.
-
-### ObjectOS (Control Layer)
-The system protocol layer. Manages runtime, plugins, authentication, events, and automation. The "operating system" for business logic.
-
----
-
-## Data & Schema
-
-### Object
-The fundamental unit of data modeling. Roughly equivalent to a "Table" in SQL or a "Collection" in NoSQL. An Object definition includes Fields, Validations, and Permissions.
-
-### Field
-A single data attribute within an Object. Has a type (text, number, lookup, etc.) and optional constraints (required, unique, etc.).
-
-### Driver
-An adapter plugin that allows ObjectQL to communicate with a specific database engine.
-- Examples: `@objectstack/driver-postgres`, `@objectstack/driver-mongodb`
-
-### AST (Abstract Syntax Tree)
-The intermediate representation of a query. ObjectQL parses requests into an AST before the Driver translates it into database-specific queries.
-
-### Virtual Field
-A field that doesn't exist physically in the database but is computed on the fly (e.g., calculated fields, aggregations).
-
----
-
-## UI & Interaction
-
-### View
-A UI component that displays object data. Types include ListView (grid/kanban), FormView (create/edit), and specialized views (calendar, gantt).
-
-### Widget
-A reusable UI component that can be embedded in pages or dashboards. Follows the ObjectUI widget contract.
-
-### Layout
-A JSON structure that describes the visual arrangement of components. Can be nested and dynamic.
-
-### Action
-A discrete unit of logic that can be triggered by a user (button click) or system event. Defines behaviors like navigation, data updates, or API calls.
-
----
-
-## Automation & Logic
-
-### Workflow
-A business process defined as a Finite State Machine (FSM). Consists of States, Transitions, and Guards. Executes when records move between states.
-
-### Flow
-A visual logic automation tool. Supports:
-- **Screen Flows:** Interactive, user-driven processes
-- **Autolaunched Flows:** Triggered by events
-- **Scheduled Flows:** Run on a schedule
-
-### Webhook
-An HTTP callback that allows external systems to trigger actions or receive data from ObjectStack.
-
----
-
-## Security & Access
-
-### Permission Set
-A collection of object-level and field-level permissions that can be assigned to users or roles.
-
-### FLS (Field-Level Security)
-Granular access control applied to individual fields (columns), not just entire objects (rows).
-
-### OWD (Organization-Wide Defaults)
-The baseline access level for records before sharing rules are applied. Can be Private, Public Read, or Public Read/Write.
-
-### Sharing Rule
-Additional access grants based on criteria (owner-based) or conditions (criteria-based). Extends access beyond OWD.
-
-### Territory
-A hierarchical access control model that grants data access based on geographic or organizational boundaries.
-
----
-
-## System & Runtime
-
-### Plugin
-An extension package that adds functionality to ObjectStack. Follows the Kernel Protocol manifest specification.
-
-### Manifest
-The configuration file (`objectstack.config.ts`) that declares a plugin's metadata, dependencies, and resources.
-
-### Event Bus
-The system messaging infrastructure that enables plugins to communicate asynchronously via events.
-
-### Job
-A scheduled or queued background task managed by the System Protocol. Supports cron schedules, intervals, and one-time execution.
-
----
-
-## Enterprise Features
-
-### Space (Workspace)
-A logical isolation unit for multi-tenancy. Each space has its own data, users, and configuration.
-
-### Tenant
-An organization or customer in a multi-tenant deployment. Each tenant's data is isolated using strategies like schema isolation or row-level filtering.
-
-### Datasource
-An external data connection configuration. Allows ObjectStack to query and sync with external databases or APIs.
-
----
-
-## Development Terms
-
-### TCK (Technology Compatibility Kit)
-A test suite that validates if a Driver or Renderer complies with the ObjectStack Protocol. Passing the TCK certifies compatibility.
-
-### Compiler
-The component that translates high-level ObjectQL queries into optimized database-specific queries. Not a runtime wrapper like an ORM.
-
-### Renderer
-The UI component that converts ObjectUI metadata (JSON) into native interface elements (React, Flutter, etc.).
-
----
-
-## Architecture Patterns
-
-### Protocol-Driven
-A development paradigm where logic is defined in declarative data formats (JSON/YAML) with Zod schemas rather than imperative code.
-
-### Local-First
-An architectural pattern where applications read/write to a local database first, with background synchronization to the cloud.
-
-### Database Agnostic
-The ability to swap database backends without changing application code. ObjectQL acts as a universal abstraction layer.
-
-### Server-Driven UI
-A pattern where the server sends UI structure as data (JSON), and the client renders it dynamically. Enables updates without app deployments.
-
----
-
-## Abbreviations
-
-- **AST:** Abstract Syntax Tree
-- **CRUD:** Create, Read, Update, Delete
-- **DSL:** Domain Specific Language
-- **FLS:** Field-Level Security
-- **FSM:** Finite State Machine
-- **NLQ:** Natural Language Query
-- **OWD:** Organization-Wide Defaults
-- **RAG:** Retrieval-Augmented Generation
-- **RBAC:** Role-Based Access Control
-- **TCK:** Technology Compatibility Kit
-
----
-
-## Next Steps
-
-- [Core Concepts](/docs/core-concepts) - Understand metadata-driven development
-- [Protocols](/docs/protocols) - Explore the protocol specifications
-- [Development](/docs/development) - Start building with ObjectStack
diff --git a/content/docs/introduction/index.mdx b/content/docs/introduction/index.mdx
index 959d331f4..d0979257e 100644
--- a/content/docs/introduction/index.mdx
+++ b/content/docs/introduction/index.mdx
@@ -1,30 +1,105 @@
---
-title: Introduction
-description: Welcome to ObjectStack - The Metadata-Driven Protocol for the Post-SaaS Era
+title: Overview
+description: ObjectStack is What? A Full-Stack Metadata Protocol for Building Enterprise Applications
---
-# Introduction to ObjectStack
+import { Database, Layout, Cog } from 'lucide-react';
-ObjectStack is a **metadata-driven protocol** that transforms how we build enterprise software. Rather than writing code for every feature, you define your business logic declaratively through metadata (JSON/YAML), and the ObjectStack Kernel handles the execution.
+# What is ObjectStack?
-## What is ObjectStack?
+**ObjectStack** is not just a framework; it is a **Protocol** for building enterprise software. It decouples the *Business Intent* (defined in JSON/YAML) from the *Technical Execution* (handled by the Kernel).
-ObjectStack is a **full-stack metadata protocol** that provides:
+## The Problem
-- **ObjectQL**: A database-agnostic data layer
-- **ObjectUI**: Server-driven UI rendering
-- **ObjectOS**: A plugin-based runtime kernel
+In traditional development, application logic is scattered:
-Think of it as:
-- **Kubernetes** for business applications
-- **Terraform** for data modeling
-- **GraphQL** + **React Server Components** combined into one protocol
+1. **Database Schema** (`table.sql`)
+2. **Backend Models** (`User.ts`)
+3. **Frontend Validation** (`schema.zod.ts`)
+4. **API Documentation** (`swagger.json`)
-## Getting Started
+When requirements change, you update code in multiple places. This is **Implementation Coupling**.
-Choose your learning path:
+## The Solution
-- [Overview](/docs/introduction/overview) - What is ObjectStack?
-- [Design Principles](/docs/introduction/design-principles) - Core philosophy
-- [Architecture](/docs/introduction/architecture) - System overview
-- [Glossary](/docs/introduction/glossary) - Key terminology
+ObjectStack centralizes the "Intent" into a single Protocol Definition (JSON/YAML). The implementation layers (React, Node.js, SQL) act merely as **Runtime Engines** that interpret this protocol.
+
+
+ }
+ title="ObjectQL (Data Layer)"
+ description="Define data structures, queries, and business logic. Database-agnostic abstraction layer."
+ />
+ }
+ title="ObjectUI (Presentation Layer)"
+ description="Server-driven UI definitions. Express interfaces as JSON, not code."
+ />
+ }
+ title="ObjectOS (Control Layer)"
+ description="Runtime kernel, plugins, security, and integration. The platform foundation."
+ />
+
+
+## The "Stack" Analogy
+
+Think of ObjectStack as:
+
+- **Kubernetes** for business applications - Declarative configuration over imperative code
+- **Terraform** for data modeling - Infrastructure as code, but for data
+- **GraphQL + React Server Components** - Schema-driven data + UI rendering combined
+
+## Key Features
+
+### 1. Protocol-Driven Architecture
+
+**The UI is a Projection. The API is a Consequence.**
+
+- ObjectUI does not "build" a form; it *projects* the ObjectQL schema into a visual representation
+- You do not write endpoints; ObjectOS *generates* the secure graph based on the access control protocol
+
+### 2. Local-First by Default
+
+**"The Cloud is a sync peer, not a master."**
+
+- All interactions are optimistic and instant (0ms latency)
+- Data lives on the user's device
+- The server is just a hub for backup and collaboration
+
+### 3. Database Agnostic
+
+**ObjectQL treats the database as an Implementation Detail.**
+
+- Start with SQLite for prototyping
+- Migrate to PostgreSQL for production
+- Archive to Snowflake for analytics
+- **No code changes required**
+
+## Real-World Benefits
+
+| Traditional Approach | ObjectStack Approach |
+| :--- | :--- |
+| Write SQL migrations manually | Schema changes sync automatically |
+| Build CRUD APIs by hand | REST/GraphQL generated from schema |
+| Duplicate validation logic 3x | Define once, enforce everywhere |
+| Lock into one database vendor | Swap databases without code changes |
+| Offline = broken app | Offline-first with background sync |
+
+## Who Should Use ObjectStack?
+
+### Enterprise Developers
+Building internal tools, CRMs, ERPs, or admin panels? ObjectStack eliminates 80% of the boilerplate.
+
+### Platform Builders
+Creating a SaaS product or multi-tenant application? ObjectStack provides enterprise-grade security and isolation.
+
+### Integration Engineers
+Connecting multiple systems? ObjectStack's protocol-driven approach makes it easy to map and transform data.
+
+## Next Steps
+
+- [Design Principles](/docs/introduction/design-principles) - Understand the philosophy
+- [Architecture](/docs/introduction/architecture) - Deep dive into the system
+- [Glossary](/docs/introduction/glossary) - Learn key terminology
+- [Core Concepts](/docs/core-concepts) - Metadata-driven development explained
diff --git a/content/docs/concepts/manifesto.mdx b/content/docs/introduction/manifesto.mdx
similarity index 100%
rename from content/docs/concepts/manifesto.mdx
rename to content/docs/introduction/manifesto.mdx
diff --git a/content/docs/introduction/meta.json b/content/docs/introduction/meta.json
index 35b133565..236d84595 100644
--- a/content/docs/introduction/meta.json
+++ b/content/docs/introduction/meta.json
@@ -1,9 +1,12 @@
{
- "title": "📍 Introduction",
+ "title": "Introduction",
+ "root": true,
"pages": [
- "overview",
- "design-principles",
+ "index",
+ "manifesto",
+ "metadata-driven",
"architecture",
- "glossary"
+ "design-principles",
+ "terminology"
]
}
diff --git a/content/docs/core-concepts/metadata-driven.mdx b/content/docs/introduction/metadata-driven.mdx
similarity index 100%
rename from content/docs/core-concepts/metadata-driven.mdx
rename to content/docs/introduction/metadata-driven.mdx
diff --git a/content/docs/introduction/overview.mdx b/content/docs/introduction/overview.mdx
deleted file mode 100644
index d0979257e..000000000
--- a/content/docs/introduction/overview.mdx
+++ /dev/null
@@ -1,105 +0,0 @@
----
-title: Overview
-description: ObjectStack is What? A Full-Stack Metadata Protocol for Building Enterprise Applications
----
-
-import { Database, Layout, Cog } from 'lucide-react';
-
-# What is ObjectStack?
-
-**ObjectStack** is not just a framework; it is a **Protocol** for building enterprise software. It decouples the *Business Intent* (defined in JSON/YAML) from the *Technical Execution* (handled by the Kernel).
-
-## The Problem
-
-In traditional development, application logic is scattered:
-
-1. **Database Schema** (`table.sql`)
-2. **Backend Models** (`User.ts`)
-3. **Frontend Validation** (`schema.zod.ts`)
-4. **API Documentation** (`swagger.json`)
-
-When requirements change, you update code in multiple places. This is **Implementation Coupling**.
-
-## The Solution
-
-ObjectStack centralizes the "Intent" into a single Protocol Definition (JSON/YAML). The implementation layers (React, Node.js, SQL) act merely as **Runtime Engines** that interpret this protocol.
-
-
- }
- title="ObjectQL (Data Layer)"
- description="Define data structures, queries, and business logic. Database-agnostic abstraction layer."
- />
- }
- title="ObjectUI (Presentation Layer)"
- description="Server-driven UI definitions. Express interfaces as JSON, not code."
- />
- }
- title="ObjectOS (Control Layer)"
- description="Runtime kernel, plugins, security, and integration. The platform foundation."
- />
-
-
-## The "Stack" Analogy
-
-Think of ObjectStack as:
-
-- **Kubernetes** for business applications - Declarative configuration over imperative code
-- **Terraform** for data modeling - Infrastructure as code, but for data
-- **GraphQL + React Server Components** - Schema-driven data + UI rendering combined
-
-## Key Features
-
-### 1. Protocol-Driven Architecture
-
-**The UI is a Projection. The API is a Consequence.**
-
-- ObjectUI does not "build" a form; it *projects* the ObjectQL schema into a visual representation
-- You do not write endpoints; ObjectOS *generates* the secure graph based on the access control protocol
-
-### 2. Local-First by Default
-
-**"The Cloud is a sync peer, not a master."**
-
-- All interactions are optimistic and instant (0ms latency)
-- Data lives on the user's device
-- The server is just a hub for backup and collaboration
-
-### 3. Database Agnostic
-
-**ObjectQL treats the database as an Implementation Detail.**
-
-- Start with SQLite for prototyping
-- Migrate to PostgreSQL for production
-- Archive to Snowflake for analytics
-- **No code changes required**
-
-## Real-World Benefits
-
-| Traditional Approach | ObjectStack Approach |
-| :--- | :--- |
-| Write SQL migrations manually | Schema changes sync automatically |
-| Build CRUD APIs by hand | REST/GraphQL generated from schema |
-| Duplicate validation logic 3x | Define once, enforce everywhere |
-| Lock into one database vendor | Swap databases without code changes |
-| Offline = broken app | Offline-first with background sync |
-
-## Who Should Use ObjectStack?
-
-### Enterprise Developers
-Building internal tools, CRMs, ERPs, or admin panels? ObjectStack eliminates 80% of the boilerplate.
-
-### Platform Builders
-Creating a SaaS product or multi-tenant application? ObjectStack provides enterprise-grade security and isolation.
-
-### Integration Engineers
-Connecting multiple systems? ObjectStack's protocol-driven approach makes it easy to map and transform data.
-
-## Next Steps
-
-- [Design Principles](/docs/introduction/design-principles) - Understand the philosophy
-- [Architecture](/docs/introduction/architecture) - Deep dive into the system
-- [Glossary](/docs/introduction/glossary) - Learn key terminology
-- [Core Concepts](/docs/core-concepts) - Metadata-driven development explained
diff --git a/content/docs/concepts/terminology.mdx b/content/docs/introduction/terminology.mdx
similarity index 100%
rename from content/docs/concepts/terminology.mdx
rename to content/docs/introduction/terminology.mdx
diff --git a/content/docs/meta.json b/content/docs/meta.json
index 8142b6a88..bca8af934 100644
--- a/content/docs/meta.json
+++ b/content/docs/meta.json
@@ -2,18 +2,10 @@
"title": "Documentation",
"pages": [
"introduction",
- "core-concepts",
- "protocols",
- "development",
- "transport",
- "quick-start",
- "tutorials",
- "guides",
- "concepts",
- "specifications",
- "standards",
- "references",
- "faq",
- "troubleshooting"
+ "objectql",
+ "objectui",
+ "objectos",
+ "developers",
+ "references"
]
-}
\ No newline at end of file
+}
diff --git a/content/docs/protocols/objectos/config-resolution.mdx b/content/docs/objectos/config-resolution.mdx
similarity index 100%
rename from content/docs/protocols/objectos/config-resolution.mdx
rename to content/docs/objectos/config-resolution.mdx
diff --git a/content/docs/protocols/objectos/i18n-standard.mdx b/content/docs/objectos/i18n-standard.mdx
similarity index 100%
rename from content/docs/protocols/objectos/i18n-standard.mdx
rename to content/docs/objectos/i18n-standard.mdx
diff --git a/content/docs/protocols/objectos/index.mdx b/content/docs/objectos/index.mdx
similarity index 100%
rename from content/docs/protocols/objectos/index.mdx
rename to content/docs/objectos/index.mdx
diff --git a/content/docs/protocols/objectos/lifecycle.mdx b/content/docs/objectos/lifecycle.mdx
similarity index 100%
rename from content/docs/protocols/objectos/lifecycle.mdx
rename to content/docs/objectos/lifecycle.mdx
diff --git a/content/docs/protocols/objectos/meta.json b/content/docs/objectos/meta.json
similarity index 65%
rename from content/docs/protocols/objectos/meta.json
rename to content/docs/objectos/meta.json
index d47757a21..b6270f246 100644
--- a/content/docs/protocols/objectos/meta.json
+++ b/content/docs/objectos/meta.json
@@ -1,9 +1,12 @@
{
"title": "ObjectOS (System Protocol)",
+ "root": true,
"pages": [
+ "index",
"lifecycle",
"plugin-spec",
"config-resolution",
- "i18n-standard"
+ "i18n-standard",
+ "transport"
]
}
diff --git a/content/docs/protocols/objectos/plugin-spec.mdx b/content/docs/objectos/plugin-spec.mdx
similarity index 100%
rename from content/docs/protocols/objectos/plugin-spec.mdx
rename to content/docs/objectos/plugin-spec.mdx
diff --git a/content/docs/transport/error-handling.mdx b/content/docs/objectos/transport/error-handling.mdx
similarity index 100%
rename from content/docs/transport/error-handling.mdx
rename to content/docs/objectos/transport/error-handling.mdx
diff --git a/content/docs/transport/http-api.mdx b/content/docs/objectos/transport/http-api.mdx
similarity index 100%
rename from content/docs/transport/http-api.mdx
rename to content/docs/objectos/transport/http-api.mdx
diff --git a/content/docs/transport/index.mdx b/content/docs/objectos/transport/index.mdx
similarity index 100%
rename from content/docs/transport/index.mdx
rename to content/docs/objectos/transport/index.mdx
diff --git a/content/docs/transport/meta.json b/content/docs/objectos/transport/meta.json
similarity index 100%
rename from content/docs/transport/meta.json
rename to content/docs/objectos/transport/meta.json
diff --git a/content/docs/transport/realtime.mdx b/content/docs/objectos/transport/realtime.mdx
similarity index 100%
rename from content/docs/transport/realtime.mdx
rename to content/docs/objectos/transport/realtime.mdx
diff --git a/content/docs/protocols/objectql/index.mdx b/content/docs/objectql/index.mdx
similarity index 100%
rename from content/docs/protocols/objectql/index.mdx
rename to content/docs/objectql/index.mdx
diff --git a/content/docs/protocols/objectql/meta.json b/content/docs/objectql/meta.json
similarity index 88%
rename from content/docs/protocols/objectql/meta.json
rename to content/docs/objectql/meta.json
index 70d7069d5..9ca74e64d 100644
--- a/content/docs/protocols/objectql/meta.json
+++ b/content/docs/objectql/meta.json
@@ -1,5 +1,6 @@
{
"title": "ObjectQL (Data Protocol)",
+ "root": true,
"pages": [
"schema",
"types",
diff --git a/content/docs/protocols/objectql/query-syntax.mdx b/content/docs/objectql/query-syntax.mdx
similarity index 100%
rename from content/docs/protocols/objectql/query-syntax.mdx
rename to content/docs/objectql/query-syntax.mdx
diff --git a/content/docs/protocols/objectql/schema.mdx b/content/docs/objectql/schema.mdx
similarity index 100%
rename from content/docs/protocols/objectql/schema.mdx
rename to content/docs/objectql/schema.mdx
diff --git a/content/docs/protocols/objectql/security.mdx b/content/docs/objectql/security.mdx
similarity index 100%
rename from content/docs/protocols/objectql/security.mdx
rename to content/docs/objectql/security.mdx
diff --git a/content/docs/protocols/objectql/types.mdx b/content/docs/objectql/types.mdx
similarity index 100%
rename from content/docs/protocols/objectql/types.mdx
rename to content/docs/objectql/types.mdx
diff --git a/content/docs/protocols/objectui/actions.mdx b/content/docs/objectui/actions.mdx
similarity index 100%
rename from content/docs/protocols/objectui/actions.mdx
rename to content/docs/objectui/actions.mdx
diff --git a/content/docs/protocols/objectui/concept.mdx b/content/docs/objectui/concept.mdx
similarity index 100%
rename from content/docs/protocols/objectui/concept.mdx
rename to content/docs/objectui/concept.mdx
diff --git a/content/docs/protocols/objectui/index.mdx b/content/docs/objectui/index.mdx
similarity index 100%
rename from content/docs/protocols/objectui/index.mdx
rename to content/docs/objectui/index.mdx
diff --git a/content/docs/protocols/objectui/layout-dsl.mdx b/content/docs/objectui/layout-dsl.mdx
similarity index 100%
rename from content/docs/protocols/objectui/layout-dsl.mdx
rename to content/docs/objectui/layout-dsl.mdx
diff --git a/content/docs/protocols/objectui/meta.json b/content/docs/objectui/meta.json
similarity index 88%
rename from content/docs/protocols/objectui/meta.json
rename to content/docs/objectui/meta.json
index f53364462..4c286cabc 100644
--- a/content/docs/protocols/objectui/meta.json
+++ b/content/docs/objectui/meta.json
@@ -1,5 +1,6 @@
{
"title": "ObjectUI (UI Protocol)",
+ "root": true,
"pages": [
"concept",
"layout-dsl",
diff --git a/content/docs/protocols/objectui/widget-contract.mdx b/content/docs/objectui/widget-contract.mdx
similarity index 100%
rename from content/docs/protocols/objectui/widget-contract.mdx
rename to content/docs/objectui/widget-contract.mdx
diff --git a/content/docs/protocols/index.mdx b/content/docs/protocols/index.mdx
deleted file mode 100644
index a078de8a3..000000000
--- a/content/docs/protocols/index.mdx
+++ /dev/null
@@ -1,212 +0,0 @@
----
-title: Protocols
-description: The complete technical specifications for ObjectStack - The "Constitution" of the metadata-driven platform
----
-
-import { Database, Layout, Server } from 'lucide-react';
-
-# Protocol Specifications
-
-The ObjectStack Protocol is defined through three core specifications that work together to create a complete metadata-driven platform.
-
-## The Three Protocol Layers
-
-
- }
- title="ObjectQL (Data Protocol)"
- href="/docs/protocols/objectql"
- description="Define data structures, queries, and business logic. Database-agnostic abstraction layer."
- />
- }
- title="ObjectUI (UI Protocol)"
- href="/docs/protocols/objectui"
- description="Server-driven UI definitions. Express interfaces as JSON, not code."
- />
- }
- title="ObjectOS (System Protocol)"
- href="/docs/protocols/objectos"
- description="Runtime kernel, plugins, security, and integration. The platform foundation."
- />
-
-
-## What Are Specifications?
-
-These documents define the **ObjectStack Protocol** - the rules and standards that all implementations must follow.
-
-Think of them as:
-- **The SQL Specification** → Defines what SQL should do
-- **The HTTP Specification** → Defines how web communication works
-- **The ObjectStack Specification** → Defines how metadata-driven platforms work
-
-## Who Should Read These?
-
-### Protocol Implementers
-
-Building an ObjectStack implementation?
-
-- **Kernel Developers:** Implement the runtime engine
-- **Driver Developers:** Connect new databases (PostgreSQL, MongoDB, etc.)
-- **Renderer Developers:** Build UI renderers (React, Vue, Flutter)
-
-Start with:
-1. [ObjectOS - Lifecycle](/docs/protocols/objectos/lifecycle)
-2. [ObjectQL - Schema](/docs/protocols/objectql/schema)
-3. [ObjectUI - Concept](/docs/protocols/objectui/concept)
-
-### Platform Architects
-
-Evaluating ObjectStack for your organization?
-
-- **CTOs:** Understand architectural decisions
-- **Tech Leads:** Evaluate scalability and security
-- **Solution Architects:** Design integration patterns
-
-Start with:
-1. [ObjectQL - Types](/docs/protocols/objectql/types)
-2. [ObjectQL - Security](/docs/protocols/objectql/security)
-3. [ObjectOS - Config Resolution](/docs/protocols/objectos/config-resolution)
-
-### Advanced Users
-
-Building complex applications with ObjectStack?
-
-- **Power Users:** Understand limits and capabilities
-- **Custom Plugin Developers:** Extend the platform
-- **Integration Engineers:** Connect external systems
-
-Start with:
-1. [ObjectQL - Query Syntax](/docs/protocols/objectql/query-syntax)
-2. [ObjectUI - Widget Contract](/docs/protocols/objectui/widget-contract)
-3. [ObjectOS - Plugin Spec](/docs/protocols/objectos/plugin-spec)
-
-## Specification Structure
-
-Each specification follows a consistent structure:
-
-### 1. Overview
-- **Purpose:** What problem does this solve?
-- **Design Principles:** What are the guiding principles?
-- **Architecture Diagram:** Visual representation
-
-### 2. Core Concepts
-- **Schemas:** Zod definitions
-- **Types:** TypeScript interfaces
-- **Examples:** Real-world usage
-
-### 3. Implementation Notes
-- **Driver Responsibilities:** What must drivers implement?
-- **Renderer Responsibilities:** What must renderers handle?
-- **Kernel Integration:** How does it fit into the system?
-
-## Key Design Principles
-
-### 1. Protocol Over Framework
-
-ObjectStack is a **protocol**, not a framework:
-
-```
-Protocol Definition (Zod schemas)
- ↓
-Multiple Implementations
- • Node.js Kernel
- • Go Kernel
- • Python Kernel
- • Custom Kernel
-```
-
-### 2. Declarative Over Imperative
-
-Express **intent**, not **implementation**:
-
-```typescript
-// What you want (declarative)
-const Task = Object({
- fields: {
- title: Field.text({ required: true }),
- }
-});
-
-// How to do it (handled by kernel)
-// ✓ Generate SQL schema
-// ✓ Create API endpoints
-// ✓ Validate requests
-// ✓ Render UI
-```
-
-### 3. Type-Safe by Default
-
-All schemas are Zod + TypeScript:
-
-```typescript
-// Source: Zod schema
-export const TaskSchema = z.object({ ... });
-
-// Derived: TypeScript type
-type Task = z.infer;
-
-// Derived: JSON Schema
-const jsonSchema = zodToJsonSchema(TaskSchema);
-```
-
-### 4. Database Agnostic
-
-ObjectQL compiles to any backend:
-
-```
-ObjectQL Query → AST → Driver Translates
- ↓
- SQL | NoSQL | API
-```
-
-## Versioning & Compatibility
-
-ObjectStack follows **Semantic Versioning** (semver):
-
-```
-MAJOR.MINOR.PATCH
- 1 . 0 . 0
-```
-
-- **MAJOR:** Breaking changes to protocol
-- **MINOR:** New features (backward compatible)
-- **PATCH:** Bug fixes
-
-### Compatibility Guarantee
-
-- **Same MAJOR version:** 100% compatible
-- **Different MAJOR:** May require migration
-
-Example:
-- Schema written for **v1.x.x** works on **v1.5.0** ✅
-- Schema written for **v1.x.x** may need updates for **v2.0.0** ⚠️
-
-## Contributing to Specifications
-
-Want to propose changes or additions?
-
-1. **Read:** [Contributing Guide](https://github.com/objectstack-ai/spec/blob/main/CONTRIBUTING.md)
-2. **Discuss:** [GitHub Issues](https://github.com/objectstack-ai/spec/issues)
-3. **Propose:** [Submit an RFC](https://github.com/objectstack-ai/spec/issues/new)
-
-## Next Steps
-
-
-
-
-
-
diff --git a/content/docs/protocols/meta.json b/content/docs/protocols/meta.json
deleted file mode 100644
index 10bba84f1..000000000
--- a/content/docs/protocols/meta.json
+++ /dev/null
@@ -1,8 +0,0 @@
-{
- "title": "📜 Protocols",
- "pages": [
- "objectql",
- "objectui",
- "objectos"
- ]
-}
diff --git a/content/docs/references/ai/meta.cn.json b/content/docs/references/ai/meta.cn.json
index bca6e77a2..b8e9669ad 100644
--- a/content/docs/references/ai/meta.cn.json
+++ b/content/docs/references/ai/meta.cn.json
@@ -1,6 +1,6 @@
{
"title": "AI 协议",
- "root": true,
+
"pages": [
"agent",
"conversation",
diff --git a/content/docs/references/ai/meta.json b/content/docs/references/ai/meta.json
index 460ee83f8..b5f80df39 100644
--- a/content/docs/references/ai/meta.json
+++ b/content/docs/references/ai/meta.json
@@ -1,6 +1,5 @@
{
"title": "AI Protocol",
- "root": true,
"pages": [
"agent",
"conversation",
diff --git a/content/docs/references/api/meta.cn.json b/content/docs/references/api/meta.cn.json
index 1bdc375f1..f3c51fbcb 100644
--- a/content/docs/references/api/meta.cn.json
+++ b/content/docs/references/api/meta.cn.json
@@ -1,6 +1,6 @@
{
"title": "API 协议",
- "root": true,
+
"pages": [
"contract",
"discovery",
diff --git a/content/docs/references/api/meta.json b/content/docs/references/api/meta.json
index f6bea3c2f..8510d7f2f 100644
--- a/content/docs/references/api/meta.json
+++ b/content/docs/references/api/meta.json
@@ -1,6 +1,5 @@
{
"title": "API Protocol",
- "root": true,
"pages": [
"contract",
"discovery",
diff --git a/content/docs/references/auth/meta.cn.json b/content/docs/references/auth/meta.cn.json
index e0687a146..120501946 100644
--- a/content/docs/references/auth/meta.cn.json
+++ b/content/docs/references/auth/meta.cn.json
@@ -1,6 +1,6 @@
{
"title": "认证协议",
- "root": true,
+
"pages": [
"config",
"identity",
diff --git a/content/docs/references/auth/meta.json b/content/docs/references/auth/meta.json
index d4dc1c775..0f5a885d0 100644
--- a/content/docs/references/auth/meta.json
+++ b/content/docs/references/auth/meta.json
@@ -1,6 +1,6 @@
{
"title": "Auth Protocol",
- "root": true,
+
"pages": [
"config",
"identity",
diff --git a/content/docs/references/automation/meta.cn.json b/content/docs/references/automation/meta.cn.json
index 244a5ae0c..e503e567d 100644
--- a/content/docs/references/automation/meta.cn.json
+++ b/content/docs/references/automation/meta.cn.json
@@ -1,6 +1,6 @@
{
"title": "自动化协议",
- "root": true,
+
"pages": [
"flow",
"webhook",
diff --git a/content/docs/references/automation/meta.json b/content/docs/references/automation/meta.json
index 93ad32903..c3c7324c9 100644
--- a/content/docs/references/automation/meta.json
+++ b/content/docs/references/automation/meta.json
@@ -1,6 +1,6 @@
{
"title": "Automation Protocol",
- "root": true,
+
"pages": [
"flow",
"webhook",
diff --git a/content/docs/references/data/meta.cn.json b/content/docs/references/data/meta.cn.json
index abc239871..f7e0169ac 100644
--- a/content/docs/references/data/meta.cn.json
+++ b/content/docs/references/data/meta.cn.json
@@ -1,6 +1,6 @@
{
"title": "数据协议",
- "root": true,
+
"pages": [
"dataset",
"field",
diff --git a/content/docs/references/data/meta.json b/content/docs/references/data/meta.json
index 4536873a1..e8ddf6160 100644
--- a/content/docs/references/data/meta.json
+++ b/content/docs/references/data/meta.json
@@ -1,6 +1,6 @@
{
"title": "Data Protocol",
- "root": true,
+
"pages": [
"dataset",
"field",
diff --git a/content/docs/references/driver/meta.cn.json b/content/docs/references/driver/meta.cn.json
index e409e0b4b..1934be99f 100644
--- a/content/docs/references/driver/meta.cn.json
+++ b/content/docs/references/driver/meta.cn.json
@@ -1,6 +1,6 @@
{
"title": "驱动协议",
- "root": true,
+
"pages": [
"datasource",
"driver",
diff --git a/content/docs/references/driver/meta.json b/content/docs/references/driver/meta.json
index 1462e7b4f..1c4cfef06 100644
--- a/content/docs/references/driver/meta.json
+++ b/content/docs/references/driver/meta.json
@@ -1,6 +1,6 @@
{
"title": "Driver Protocol",
- "root": true,
+
"pages": [
"datasource",
"driver",
diff --git a/content/docs/references/hub/meta.json b/content/docs/references/hub/meta.json
index 244486f3c..22c0988fc 100644
--- a/content/docs/references/hub/meta.json
+++ b/content/docs/references/hub/meta.json
@@ -1,6 +1,6 @@
{
"title": "Hub Protocol",
- "root": true,
+
"pages": [
"composer",
"license",
diff --git a/content/docs/references/kernel/meta.json b/content/docs/references/kernel/meta.json
index 17300c701..2fbbaef1e 100644
--- a/content/docs/references/kernel/meta.json
+++ b/content/docs/references/kernel/meta.json
@@ -1,6 +1,6 @@
{
"title": "Kernel Protocol",
- "root": true,
+
"pages": [
"context",
"logger",
diff --git a/content/docs/references/meta.cn.json b/content/docs/references/meta.cn.json
deleted file mode 100644
index 360bef3ad..000000000
--- a/content/docs/references/meta.cn.json
+++ /dev/null
@@ -1,16 +0,0 @@
-{
- "title": "API 参考",
- "pages": [
- "data",
- "ui",
- "auth",
- "automation",
- "system",
- "permission",
- "ai",
- "api",
- "driver",
- "client-sdk",
- "misc"
- ]
-}
diff --git a/content/docs/references/meta.json b/content/docs/references/meta.json
index b6090c385..514629b1f 100644
--- a/content/docs/references/meta.json
+++ b/content/docs/references/meta.json
@@ -1,6 +1,6 @@
{
"label": "Protocol Reference",
- "order": 100,
+ "root": true,
"pages": [
"data",
"ui",
diff --git a/content/docs/references/permission/meta.cn.json b/content/docs/references/permission/meta.cn.json
index 4ac353db5..f69494975 100644
--- a/content/docs/references/permission/meta.cn.json
+++ b/content/docs/references/permission/meta.cn.json
@@ -1,6 +1,6 @@
{
"title": "权限协议",
- "root": true,
+
"pages": [
"permission",
"sharing",
diff --git a/content/docs/references/permission/meta.json b/content/docs/references/permission/meta.json
index a9c5246c8..8fb5e622d 100644
--- a/content/docs/references/permission/meta.json
+++ b/content/docs/references/permission/meta.json
@@ -1,6 +1,6 @@
{
"title": "Permission Protocol",
- "root": true,
+
"pages": [
"permission",
"sharing",
diff --git a/content/docs/references/system/meta.cn.json b/content/docs/references/system/meta.cn.json
index 5933351df..1691e979e 100644
--- a/content/docs/references/system/meta.cn.json
+++ b/content/docs/references/system/meta.cn.json
@@ -1,6 +1,6 @@
{
"title": "系统协议",
- "root": true,
+
"pages": [
"audit",
"events",
diff --git a/content/docs/references/system/meta.json b/content/docs/references/system/meta.json
index 5e0498ff1..94222d72a 100644
--- a/content/docs/references/system/meta.json
+++ b/content/docs/references/system/meta.json
@@ -1,6 +1,6 @@
{
"title": "System Protocol",
- "root": true,
+
"pages": [
"audit",
"events",
diff --git a/content/docs/references/ui/meta.cn.json b/content/docs/references/ui/meta.cn.json
index 23a89ae7d..5541cb5b6 100644
--- a/content/docs/references/ui/meta.cn.json
+++ b/content/docs/references/ui/meta.cn.json
@@ -1,6 +1,6 @@
{
"title": "UI 协议",
- "root": true,
+
"pages": [
"action",
"app",
diff --git a/content/docs/references/ui/meta.json b/content/docs/references/ui/meta.json
index dc61ce85a..151a5ad98 100644
--- a/content/docs/references/ui/meta.json
+++ b/content/docs/references/ui/meta.json
@@ -1,6 +1,6 @@
{
"title": "UI Protocol",
- "root": true,
+
"pages": [
"action",
"app",
diff --git a/content/docs/specifications/architecture/data-layer.mdx b/content/docs/specifications/architecture/data-layer.mdx
deleted file mode 100644
index f5f8f138f..000000000
--- a/content/docs/specifications/architecture/data-layer.mdx
+++ /dev/null
@@ -1,285 +0,0 @@
----
-title: ObjectQL - Data Layer Architecture
-description: Deep dive into the ObjectQL (Object Query Language) data protocol architecture
----
-
-# ObjectQL - Data Layer Architecture
-
-> Deep dive into the ObjectQL (Object Query Language) data protocol architecture
-
-## Overview
-
-ObjectQL is the **data abstraction layer** of ObjectStack. It defines how data structures are expressed, queried, and manipulated across different storage backends.
-
-## Key Components
-
-### 1. Schema Definition (`src/data/`)
-
-#### Object Schema
-Defines business entities (tables/collections):
-
-```typescript
-const CustomerAccount = {
- name: 'customer_account',
- label: 'Customer Account',
- fields: { /* field definitions */ },
- enableHistory: true,
- enableSharing: true,
-};
-```
-
-#### Field Schema
-Defines data properties with 35 types:
-
-- **Basic**: text, textarea, number, boolean, date, datetime
-- **Advanced**: lookup, master_detail, formula, summary, autonumber
-- **Rich**: email, phone, url, currency, percent, markdown, html, richtext
-- **Complex**: address, location (aka geolocation), file, image, avatar
-- **Enhanced**: code, color, rating, slider, signature, qrcode
-
-### 2. Query Protocol (`src/data/query/`)
-
-Abstract Syntax Tree (AST) for unified data access:
-
-```typescript
-const query = {
- select: ['name', 'email', 'revenue'],
- from: 'customer_account',
- where: {
- and: [
- { field: 'industry', operator: 'eq', value: 'technology' },
- { field: 'revenue', operator: 'gt', value: 500000 }
- ]
- },
- orderBy: [{ field: 'revenue', direction: 'desc' }],
- limit: 10,
-};
-```
-
-### 3. Validation Rules (`src/data/validation.zod.ts`)
-
-Business logic validation:
-
-- **Format Validation**: Email, phone, URL patterns
-- **Range Validation**: Min/max for numbers and dates
-- **Uniqueness**: Field-level and composite keys
-- **Cross-Field**: Conditional validation based on other fields
-- **Custom**: Script-based validation logic
-
-### 4. Automation (`src/data/automation/`)
-
-#### Workflows
-State-based automation rules:
-
-```typescript
-const workflowRule = {
- name: 'high_value_alert',
- object: 'customer_account',
- triggerType: 'on_create_or_update',
- criteria: { field: 'annual_revenue', operator: 'gt', value: 1000000 },
- actions: [
- { type: 'email_alert', template: 'notify_sales_manager' },
- { type: 'field_update', field: 'priority', value: 'high' }
- ],
-};
-```
-
-#### Flows
-Visual logic orchestration:
-
-- **Screen Flows**: User-interactive wizards
-- **Autolaunched Flows**: Backend automation
-- **Scheduled Flows**: Time-based execution
-
-### 5. Security (`src/data/security/`)
-
-#### Permissions
-Fine-grained access control:
-
-```typescript
-const permissionSet = {
- name: 'sales_user',
- objectPermissions: {
- customer_account: {
- read: true,
- create: true,
- edit: true,
- delete: false,
- }
- },
- fieldPermissions: {
- customer_account: {
- annual_revenue: { read: true, edit: false }
- }
- }
-};
-```
-
-#### Sharing Rules
-Row-level security:
-
-- **OWD Model**: Organization-wide defaults
-- **Sharing Rules**: Criteria-based sharing
-- **Manual Sharing**: User-granted access
-- **Role Hierarchy**: Inheritance-based access
-
-## Data Flow
-
-```
-┌─────────────────────────────────────────────────────────┐
-│ Application Layer (UI, API, CLI) │
-└─────────────────────────────────────────────────────────┘
- ↓
-┌─────────────────────────────────────────────────────────┐
-│ ObjectQL Query Builder │
-│ - Validates schema references │
-│ - Checks permissions │
-│ - Applies business rules │
-└─────────────────────────────────────────────────────────┘
- ↓
-┌─────────────────────────────────────────────────────────┐
-│ Query Optimizer │
-│ - Optimizes AST │
-│ - Plans execution │
-│ - Caches metadata │
-└─────────────────────────────────────────────────────────┘
- ↓
-┌─────────────────────────────────────────────────────────┐
-│ Driver Layer │
-│ - Translates AST to native queries │
-│ - Handles driver-specific features │
-│ - Manages connections │
-└─────────────────────────────────────────────────────────┘
- ↓
-┌─────────────────────────────────────────────────────────┐
-│ Storage Backend (PostgreSQL, MongoDB, MySQL, etc.) │
-└─────────────────────────────────────────────────────────┘
-```
-
-## Driver Interface
-
-Drivers translate ObjectQL to native storage formats:
-
-```typescript
-interface DriverInterface {
- // CRUD Operations
- create(object: string, data: Record): Promise;
- read(object: string, id: string): Promise;
- update(object: string, id: string, data: Record): Promise;
- delete(object: string, id: string): Promise;
-
- // Query Operations
- query(query: Query): Promise;
- count(query: Query): Promise;
-
- // Schema Operations
- describeObject(object: string): Promise;
- listObjects(): Promise;
-}
-```
-
-## Advanced Features
-
-### Formulas
-
-Computed fields with expression language:
-
-```typescript
-{
- name: 'total_value',
- type: 'formula',
- returnType: 'number',
- expression: 'quantity * unit_price * (1 - discount_percent / 100)'
-}
-```
-
-### Rollup Summaries
-
-Aggregate related records:
-
-```typescript
-{
- name: 'total_opportunities',
- type: 'rollup',
- relationshipField: 'account_id',
- relatedObject: 'opportunity',
- aggregateFunction: 'SUM',
- aggregateField: 'amount'
-}
-```
-
-### Lookup Relationships
-
-Reference other objects:
-
-```typescript
-{
- name: 'account_id',
- type: 'lookup',
- reference: 'customer_account',
- displayField: 'account_name',
- cascadeDelete: false
-}
-```
-
-## Performance Considerations
-
-### Indexing
-
-Define indexes for query optimization:
-
-```typescript
-const indexes = [
- { fields: ['email'], unique: true },
- { fields: ['industry', 'revenue'] },
- { fields: ['created_date'] }
-];
-```
-
-### Query Optimization
-
-- Use field selection to limit data transfer
-- Apply filters early in the query
-- Use pagination for large result sets
-- Leverage database indexes
-
-### Caching
-
-- Cache object metadata
-- Cache permission sets
-- Use query result caching for reports
-
-## Best Practices
-
-1. **Schema Design**
- - Use appropriate field types
- - Define relationships clearly
- - Add validation rules early
- - Index frequently queried fields
-
-2. **Query Design**
- - Select only needed fields
- - Use efficient filters
- - Implement pagination
- - Avoid N+1 queries
-
-3. **Security**
- - Define OWD models
- - Set field-level security
- - Use sharing rules appropriately
- - Audit access patterns
-
-4. **Performance**
- - Add database indexes
- - Use formula fields sparingly
- - Optimize rollup calculations
- - Monitor query performance
-
-## Related Documentation
-
-- [Field Types Guide](/docs/guides/field-types.mdx)
-- [Query Protocol Guide](/docs/packages/spec/QUERY_PROTOCOL_GUIDE.md)
-- [Schema Definition Specification](/docs/specifications/data/schema-definition.mdx)
-- [Driver Interface](/docs/references/system/DriverInterface.mdx)
-
-For complete API reference, see [Data Protocol References](/docs/references/data/).
diff --git a/content/docs/specifications/architecture/index.mdx b/content/docs/specifications/architecture/index.mdx
deleted file mode 100644
index 59953818d..000000000
--- a/content/docs/specifications/architecture/index.mdx
+++ /dev/null
@@ -1,38 +0,0 @@
----
-title: Architecture
-description: Deep dive into the ObjectStack Protocol Architecture
----
-
-# Architecture
-
-The ObjectStack Protocol is built on three core layers that work together to provide a complete metadata-driven platform.
-
-## Core Layers
-
-### [Data Layer (ObjectQL)](/docs/specifications/architecture/data-layer)
-The Data Layer defines the "Shape of Data" and business logic. It includes:
-- **Schema**: Objects and Fields with 35 field types
-- **Logic**: Workflows, Triggers, Validation Rules, Formulas
-- **Security**: Permissions and Sharing Rules
-- **Query**: Abstract Syntax Tree (AST) for unified data access
-
-### [UI Layer (ObjectUI)](/docs/specifications/architecture/ui-layer)
-The UI Layer defines the "Shape of Interaction" for rendering interfaces:
-- **Views**: Grid, Kanban, Calendar, Gantt, List configurations
-- **Pages**: FlexiPage layouts with regions and components
-- **Navigation**: App menus and navigation structures
-- **Analytics**: Reports and Dashboards with widgets
-
-### [System Layer (ObjectOS)](/docs/specifications/architecture/system-layer)
-The System Layer defines the "Runtime Environment":
-- **Manifest**: Application packaging
-- **Identity**: Authentication, Roles, Licenses
-- **Integration**: Webhooks, API contracts, ETL Mappings
-- **Datasource**: Driver definitions for SQL, NoSQL, SaaS connectors
-
-## Design Principles
-
-1. **Data as Code**: All configurations are expressed as declarative metadata
-2. **Intent over Implementation**: Describe what you want, not how to build it
-3. **Local-First**: Works offline, syncs when connected
-4. **Driver Agnostic**: Abstract away storage implementation details
diff --git a/content/docs/specifications/architecture/meta.json b/content/docs/specifications/architecture/meta.json
deleted file mode 100644
index 98843bb95..000000000
--- a/content/docs/specifications/architecture/meta.json
+++ /dev/null
@@ -1,9 +0,0 @@
-{
- "title": "Architecture",
- "pages": [
- "index",
- "data-layer",
- "ui-layer",
- "system-layer"
- ]
-}
diff --git a/content/docs/specifications/architecture/system-layer.mdx b/content/docs/specifications/architecture/system-layer.mdx
deleted file mode 100644
index ca3ee1708..000000000
--- a/content/docs/specifications/architecture/system-layer.mdx
+++ /dev/null
@@ -1,454 +0,0 @@
----
-title: ObjectOS - System Layer Architecture
-description: Deep dive into the ObjectOS (Operating System) runtime architecture
----
-
-# ObjectOS - System Layer Architecture
-
-> Deep dive into the ObjectOS (Operating System) runtime architecture
-
-## Overview
-
-ObjectOS is the **runtime kernel** that orchestrates the entire ObjectStack ecosystem. It manages application lifecycle, plugins, identity, and system resources.
-
-## Key Components
-
-### 1. Manifest & Packaging (`src/system/manifest.zod.ts`)
-
-Application packaging and dependencies:
-
-```typescript
-// objectstack.config.ts
-export default {
- name: 'sales_crm',
- version: '1.0.0',
- label: 'Sales CRM',
- description: 'Customer relationship management system',
-
- dependencies: {
- '@objectstack/core': '^1.0.0',
- '@objectstack/plugin-analytics': '^0.5.0',
- },
-
- objects: ['./src/objects/**/*.object.ts'],
- flows: ['./src/flows/**/*.flow.ts'],
- apps: ['./src/apps/**/*.app.ts'],
-
- features: ['workflows', 'reports', 'ai_assistant'],
-
- license: 'MIT',
-};
-```
-
-### 2. Plugin Architecture (`src/system/plugin.zod.ts`)
-
-Extensibility through plugins:
-
-```typescript
-interface Plugin {
- name: string;
- version: string;
-
- // Lifecycle hooks
- onLoad?(context: PluginContext): Promise;
- onUnload?(): Promise;
- onActivate?(): Promise;
- onDeactivate?(): Promise;
-
- // Extension points
- registerRoutes?(router: Router): void;
- registerDrivers?(): Driver[];
- registerWidgets?(): FieldWidget[];
- registerValidators?(): Validator[];
-}
-
-// Example plugin
-export class AnalyticsPlugin implements Plugin {
- name = 'analytics';
- version = '1.0.0';
-
- async onLoad(context: PluginContext) {
- // Initialize analytics service
- const analytics = new AnalyticsService(context.ql);
- context.services.set('analytics', analytics);
- }
-
- registerRoutes(router: Router) {
- router.get('/analytics/reports', this.listReports);
- router.post('/analytics/query', this.executeQuery);
- }
-}
-```
-
-### 3. Identity & Authentication (`src/system/identity/`)
-
-User authentication and authorization:
-
-#### Authentication Strategies
-
-```typescript
-const authConfig = {
- providers: [
- {
- type: 'email_password',
- enabled: true,
- requireEmailVerification: true,
- passwordPolicy: {
- minLength: 12,
- requireUppercase: true,
- requireLowercase: true,
- requireNumbers: true,
- requireSpecialChars: true,
- },
- },
- {
- type: 'oauth',
- provider: 'google',
- clientId: process.env.GOOGLE_CLIENT_ID,
- clientSecret: process.env.GOOGLE_CLIENT_SECRET,
- },
- {
- type: 'saml',
- entityId: 'https://myapp.com/saml',
- ssoUrl: 'https://idp.example.com/sso',
- certificate: process.env.SAML_CERT,
- },
- ],
-
- session: {
- lifetime: 86400, // 24 hours
- extendOnActivity: true,
- singleSessionPerUser: false,
- },
-
- twoFactor: {
- enabled: true,
- methods: ['totp', 'sms'],
- },
-};
-```
-
-#### Role-Based Access Control
-
-```typescript
-const role = {
- name: 'sales_manager',
- label: 'Sales Manager',
- permissionSets: ['sales_user', 'report_viewer'],
- inheritsFrom: 'sales_user',
-};
-```
-
-### 4. Driver System (`src/system/driver.zod.ts`)
-
-Database abstraction layer:
-
-```typescript
-interface DriverInterface {
- name: string;
- type: 'sql' | 'nosql' | 'rest' | 'graphql';
-
- capabilities: {
- transactions: boolean;
- queryFilters: boolean;
- queryAggregations: boolean;
- querySorting: boolean;
- queryPagination: boolean;
- queryWindowFunctions: boolean;
- querySubqueries: boolean;
- };
-
- // CRUD operations
- create(params: CreateParams): Promise;
- read(params: ReadParams): Promise;
- update(params: UpdateParams): Promise;
- delete(params: DeleteParams): Promise;
-
- // Query operations
- query(params: QueryParams): Promise;
-
- // Schema operations
- syncSchema(objects: Object[]): Promise;
-}
-
-// Example: PostgreSQL driver
-export class PostgreSQLDriver implements DriverInterface {
- name = 'postgresql';
- type = 'sql' as const;
-
- capabilities = {
- transactions: true,
- queryFilters: true,
- queryAggregations: true,
- querySorting: true,
- queryPagination: true,
- queryWindowFunctions: true,
- querySubqueries: true,
- };
-
- async query(params: QueryParams): Promise {
- const sql = this.buildSQL(params.query);
- return this.execute(sql);
- }
-}
-```
-
-### 5. API Gateway (`src/system/integration/`)
-
-External integrations and webhooks:
-
-```typescript
-const webhook = {
- name: 'salesforce_sync',
- url: 'https://api.salesforce.com/webhook',
- events: ['record.created', 'record.updated'],
- objects: ['customer_account', 'opportunity'],
- headers: {
- 'Authorization': 'Bearer ${SALESFORCE_TOKEN}',
- 'Content-Type': 'application/json',
- },
- retryPolicy: {
- maxRetries: 3,
- backoffStrategy: 'exponential',
- },
-};
-```
-
-### 6. Multi-Tenancy (`src/system/organization/`)
-
-Tenant isolation and management:
-
-```typescript
-const organization = {
- id: 'org_123',
- name: 'Acme Corporation',
- subdomain: 'acme',
-
- limits: {
- maxUsers: 100,
- maxStorage: 10 * 1024 * 1024 * 1024, // 10 GB
- maxAPICallsPerDay: 100000,
- },
-
- features: ['workflows', 'ai_assistant', 'advanced_analytics'],
-
- datasources: [
- {
- name: 'primary',
- driver: 'postgresql',
- connectionString: process.env.DATABASE_URL,
- }
- ],
-};
-```
-
-## System Architecture
-
-```
-┌─────────────────────────────────────────────────────────┐
-│ API Gateway │
-│ REST, GraphQL, WebSocket endpoints │
-└─────────────────────────────────────────────────────────┘
- ↓
-┌─────────────────────────────────────────────────────────┐
-│ ObjectOS Kernel │
-│ ┌───────────────────────────────────────────────────┐ │
-│ │ Plugin Manager │ │
-│ │ - Plugin discovery and loading │ │
-│ │ - Dependency resolution │ │
-│ │ - Lifecycle management │ │
-│ └───────────────────────────────────────────────────┘ │
-│ ┌───────────────────────────────────────────────────┐ │
-│ │ Identity Service │ │
-│ │ - Authentication │ │
-│ │ - Authorization │ │
-│ │ - Session management │ │
-│ └───────────────────────────────────────────────────┘ │
-│ ┌───────────────────────────────────────────────────┐ │
-│ │ Data Access Layer (ObjectQL) │ │
-│ │ - Query building │ │
-│ │ - Permission checking │ │
-│ │ - Validation │ │
-│ └───────────────────────────────────────────────────┘ │
-│ ┌───────────────────────────────────────────────────┐ │
-│ │ Driver Manager │ │
-│ │ - Driver registration │ │
-│ │ - Connection pooling │ │
-│ │ - Query translation │ │
-│ └───────────────────────────────────────────────────┘ │
-└─────────────────────────────────────────────────────────┘
- ↓
-┌─────────────────────────────────────────────────────────┐
-│ Storage Layer (Drivers) │
-│ PostgreSQL | MongoDB | MySQL | Redis | etc. │
-└─────────────────────────────────────────────────────────┘
-```
-
-## Plugin System
-
-### Plugin Discovery
-
-1. **Static Registration**: Import and register plugins explicitly
-2. **Auto-Discovery**: Scan `node_modules/@objectstack/plugin-*`
-3. **Remote Registry**: Fetch plugins from marketplace
-
-### Plugin Lifecycle
-
-```
-┌────────────┐
-│ Installed │ ──register──> ┌──────────┐
-└────────────┘ │ Loaded │
- └──────────┘
- │
- activate │
- ↓
- ┌──────────┐
- │ Active │
- └──────────┘
- │
- deactivate │
- ↓
- ┌──────────┐
- │ Inactive │
- └──────────┘
- │
- unload │
- ↓
- ┌──────────┐
- │ Unloaded │
- └──────────┘
-```
-
-### Extension Points
-
-Plugins can extend:
-
-- **Routes**: Add custom API endpoints
-- **Drivers**: Add database/API connectors
-- **Widgets**: Add custom field widgets
-- **Validators**: Add validation logic
-- **Workflows**: Add workflow actions
-- **Reports**: Add chart types
-- **Themes**: Add UI themes
-
-## Security Features
-
-### 1. Authentication
-
-- Email/Password
-- OAuth 2.0 (Google, GitHub, etc.)
-- SAML 2.0
-- LDAP/Active Directory
-- Magic Links
-- Passkeys (WebAuthn)
-
-### 2. Authorization
-
-- Role-Based Access Control (RBAC)
-- Permission Sets
-- Organization-Wide Defaults (OWD)
-- Sharing Rules
-- Field-Level Security
-
-### 3. Audit & Compliance
-
-```typescript
-const auditPolicy = {
- enabled: true,
- retention: 90, // days
- events: [
- 'user.login',
- 'user.logout',
- 'record.created',
- 'record.updated',
- 'record.deleted',
- 'permission.changed',
- ],
- storage: {
- driver: 'postgresql',
- table: 'audit_logs',
- },
-};
-```
-
-### 4. Rate Limiting
-
-```typescript
-const rateLimit = {
- enabled: true,
- limits: {
- api: {
- window: 60, // seconds
- max: 100, // requests
- },
- login: {
- window: 300, // 5 minutes
- max: 5, // attempts
- },
- },
-};
-```
-
-## Performance Optimizations
-
-### 1. Caching
-
-- **Metadata Cache**: Object/field definitions
-- **Permission Cache**: User permissions
-- **Query Cache**: Frequently accessed data
-- **Session Cache**: User sessions
-
-### 2. Connection Pooling
-
-```typescript
-const datasource = {
- driver: 'postgresql',
- pool: {
- min: 2,
- max: 10,
- idleTimeoutMillis: 30000,
- connectionTimeoutMillis: 2000,
- },
-};
-```
-
-### 3. Lazy Loading
-
-- Load plugins on-demand
-- Defer non-critical initialization
-- Stream large datasets
-
-## Best Practices
-
-1. **Plugin Development**
- - Keep plugins focused and modular
- - Declare all dependencies
- - Handle errors gracefully
- - Provide clear documentation
-
-2. **Security**
- - Use environment variables for secrets
- - Implement rate limiting
- - Enable audit logging
- - Regular security updates
-
-3. **Performance**
- - Use connection pooling
- - Implement caching strategies
- - Monitor resource usage
- - Optimize database queries
-
-4. **Multi-Tenancy**
- - Isolate tenant data
- - Enforce quota limits
- - Monitor per-tenant metrics
- - Scale horizontally
-
-## Related Documentation
-
-- [Plugin Architecture](/docs/concepts/plugin-architecture.mdx)
-- [Kernel Architecture](/docs/specifications/server/kernel-architecture.mdx)
-- [Authentication Standard](/docs/specifications/AUTHENTICATION_STANDARD.md)
-- [System Protocol References](/docs/references/system/)
-
-For complete API reference, see [System Protocol References](/docs/references/system/).
diff --git a/content/docs/specifications/architecture/ui-layer.mdx b/content/docs/specifications/architecture/ui-layer.mdx
deleted file mode 100644
index a51ab9f14..000000000
--- a/content/docs/specifications/architecture/ui-layer.mdx
+++ /dev/null
@@ -1,367 +0,0 @@
----
-title: ObjectUI - UI Layer Architecture
-description: Deep dive into the ObjectUI (Server-Driven UI) protocol architecture
----
-
-# ObjectUI - UI Layer Architecture
-
-> Deep dive into the ObjectUI (Server-Driven UI) protocol architecture
-
-## Overview
-
-ObjectUI is the **presentation protocol** that defines how user interfaces are configured and rendered. It enables building dynamic UIs without hardcoding components.
-
-## Key Components
-
-### 1. Application Structure (`src/ui/app.zod.ts`)
-
-Defines the top-level application configuration:
-
-```typescript
-const app = {
- name: 'sales_app',
- label: 'Sales CRM',
- branding: {
- logo: '/assets/logo.png',
- primaryColor: '#0066CC',
- secondaryColor: '#FF6B00',
- },
- navigation: [
- { type: 'object', object: 'customer_account', label: 'Accounts' },
- { type: 'object', object: 'opportunity', label: 'Opportunities' },
- { type: 'dashboard', dashboard: 'sales_dashboard', label: 'Dashboard' },
- ],
-};
-```
-
-### 2. View Configuration (`src/ui/view.zod.ts`)
-
-#### List Views
-Display collections of records:
-
-**Grid View** - Tabular data display:
-```typescript
-{
- type: 'grid',
- columns: ['name', 'email', 'revenue', 'status'],
- filters: ['status:active'],
- sortBy: 'revenue:desc',
- pageSize: 25,
-}
-```
-
-**Kanban View** - Card-based workflow:
-```typescript
-{
- type: 'kanban',
- groupByField: 'status',
- cardTitle: 'name',
- cardFields: ['email', 'revenue'],
-}
-```
-
-**Calendar View** - Time-based display:
-```typescript
-{
- type: 'calendar',
- dateField: 'event_date',
- titleField: 'name',
- defaultView: 'month',
-}
-```
-
-**Gantt View** - Timeline and dependencies:
-```typescript
-{
- type: 'gantt',
- startDateField: 'start_date',
- endDateField: 'end_date',
- titleField: 'task_name',
- parentField: 'parent_task',
-}
-```
-
-#### Form Views
-Display/edit single records:
-
-**Simple Form** - Basic layout:
-```typescript
-{
- type: 'simple',
- sections: [
- {
- title: 'Basic Information',
- columns: 2,
- fields: ['name', 'email', 'phone'],
- }
- ],
-}
-```
-
-**Tabbed Form** - Organized by tabs:
-```typescript
-{
- type: 'tabbed',
- tabs: [
- { title: 'Details', fields: ['name', 'email'] },
- { title: 'Address', fields: ['street', 'city', 'country'] },
- ],
-}
-```
-
-**Wizard Form** - Multi-step process:
-```typescript
-{
- type: 'wizard',
- steps: [
- { title: 'Step 1', fields: ['name', 'email'] },
- { title: 'Step 2', fields: ['company', 'role'] },
- ],
-}
-```
-
-### 3. Analytics (`src/ui/analytics/`)
-
-#### Reports
-Data analysis and visualization:
-
-```typescript
-const report = {
- type: 'tabular',
- object: 'customer_account',
- columns: ['name', 'industry', 'revenue'],
- groupBy: ['industry'],
- aggregations: [
- { field: 'revenue', function: 'SUM' },
- { field: 'id', function: 'COUNT' },
- ],
- filters: [{ field: 'status', operator: 'eq', value: 'active' }],
- sortBy: [{ field: 'revenue', direction: 'desc' }],
-};
-```
-
-#### Dashboards
-Multiple widgets in a grid layout:
-
-```typescript
-const dashboard = {
- name: 'sales_dashboard',
- label: 'Sales Dashboard',
- layout: [
- { x: 0, y: 0, w: 6, h: 4, widget: 'revenue_chart' },
- { x: 6, y: 0, w: 6, h: 4, widget: 'pipeline_summary' },
- { x: 0, y: 4, w: 12, h: 6, widget: 'top_accounts' },
- ],
- widgets: [
- {
- id: 'revenue_chart',
- type: 'chart',
- chartType: 'line',
- report: 'monthly_revenue',
- },
- {
- id: 'pipeline_summary',
- type: 'metric',
- label: 'Pipeline Value',
- aggregation: { field: 'amount', function: 'SUM' },
- },
- ],
-};
-```
-
-### 4. Theming (`src/ui/theme.zod.ts`)
-
-Consistent design system:
-
-```typescript
-const theme = {
- colors: {
- primary: '#0066CC',
- secondary: '#FF6B00',
- success: '#28A745',
- warning: '#FFC107',
- error: '#DC3545',
- background: '#FFFFFF',
- surface: '#F8F9FA',
- text: '#212529',
- },
- typography: {
- fontFamily: 'Inter, sans-serif',
- fontSize: {
- xs: '0.75rem',
- sm: '0.875rem',
- base: '1rem',
- lg: '1.125rem',
- xl: '1.25rem',
- },
- },
- spacing: {
- xs: '0.25rem',
- sm: '0.5rem',
- md: '1rem',
- lg: '1.5rem',
- xl: '2rem',
- },
- borderRadius: {
- sm: '0.25rem',
- md: '0.5rem',
- lg: '1rem',
- },
-};
-```
-
-### 5. Actions (`src/ui/action.zod.ts`)
-
-User-triggered operations:
-
-```typescript
-const action = {
- name: 'approve_record',
- label: 'Approve',
- type: 'flow',
- flowName: 'approval_flow',
- confirmMessage: 'Are you sure you want to approve this record?',
- successMessage: 'Record approved successfully',
- icon: 'check',
- variant: 'primary',
-};
-```
-
-## Rendering Flow
-
-```
-┌─────────────────────────────────────────────────────────┐
-│ User Action (Navigate, Click, Edit) │
-└─────────────────────────────────────────────────────────┘
- ↓
-┌─────────────────────────────────────────────────────────┐
-│ UI Protocol Resolver │
-│ - Resolves view configuration │
-│ - Fetches object metadata │
-│ - Checks user permissions │
-└─────────────────────────────────────────────────────────┘
- ↓
-┌─────────────────────────────────────────────────────────┐
-│ Data Fetcher (ObjectQL) │
-│ - Builds query from view config │
-│ - Executes query via driver │
-│ - Returns data with metadata │
-└─────────────────────────────────────────────────────────┘
- ↓
-┌─────────────────────────────────────────────────────────┐
-│ Renderer (React, Vue, etc.) │
-│ - Renders components from protocol │
-│ - Applies theme configuration │
-│ - Binds data to UI elements │
-└─────────────────────────────────────────────────────────┘
- ↓
-┌─────────────────────────────────────────────────────────┐
-│ Browser / Mobile App │
-└─────────────────────────────────────────────────────────┘
-```
-
-## Field Widget System
-
-Custom field rendering:
-
-```typescript
-interface FieldWidgetProps {
- value: any;
- onChange: (value: any) => void;
- field: Field;
- readonly: boolean;
- required: boolean;
- error?: string;
-}
-
-// Example: Custom email field widget
-const EmailWidget: React.FC = (props) => {
- return (
- props.onChange(e.target.value)}
- disabled={props.readonly}
- required={props.required}
- className={props.error ? 'error' : ''}
- />
- );
-};
-```
-
-## Page Layouts (FlexiPage)
-
-Flexible page composition:
-
-```typescript
-const page = {
- name: 'account_detail',
- label: 'Account Details',
- regions: [
- {
- name: 'header',
- components: [
- { type: 'record_header', showActions: true },
- ],
- },
- {
- name: 'main',
- columns: [
- {
- components: [
- { type: 'record_detail', layout: 'two_column' },
- { type: 'related_list', relatedObject: 'opportunity' },
- ],
- },
- {
- components: [
- { type: 'activity_timeline' },
- { type: 'chatter_feed' },
- ],
- },
- ],
- },
- ],
-};
-```
-
-## Best Practices
-
-1. **View Configuration**
- - Keep views focused and simple
- - Use appropriate view types for data
- - Optimize column count for readability
- - Provide meaningful default filters
-
-2. **Form Design**
- - Group related fields in sections
- - Use 2-column layouts for efficiency
- - Show only necessary fields
- - Provide clear labels and help text
-
-3. **Dashboard Design**
- - Limit widgets to 6-8 per dashboard
- - Use consistent chart types
- - Provide drill-down capabilities
- - Update data in real-time or near-real-time
-
-4. **Theme Consistency**
- - Use design tokens
- - Maintain color contrast ratios
- - Follow accessibility guidelines
- - Test on multiple screen sizes
-
-5. **Performance**
- - Lazy load components
- - Paginate large lists
- - Cache view configurations
- - Minimize re-renders
-
-## Related Documentation
-
-- [View Configuration Guide](/docs/guides/view-configuration.mdx)
-- [SDUI Protocol Specification](/docs/specifications/ui/sdui-protocol.mdx)
-- [Component Schema](/docs/specifications/ui/component-schema.mdx)
-- [UI Protocol References](/docs/references/ui/)
-
-For complete API reference, see [UI Protocol References](/docs/references/ui/).
diff --git a/content/docs/specifications/data/advanced-types.mdx b/content/docs/specifications/data/advanced-types.mdx
deleted file mode 100644
index 1dcfad9ce..000000000
--- a/content/docs/specifications/data/advanced-types.mdx
+++ /dev/null
@@ -1,72 +0,0 @@
----
-title: Advanced Types
-description: "Detailed specification of complex data types: Lookups, Master-Detail, Formulas, and Summaries."
----
-
-Beyond standard scalars (string, boolean, number), ObjectQL supports semantic enterprise types.
-
-## 1. Relationship Types
-
-Relationships form the graph of the data model.
-
-### Lookup
-A loose link to another object. Comparable to a standard Foreign Key.
-* **Behavior:** The source field stores the `_id` of the target record.
-* **Deletion:** If target is deleted, the field is either set to `null` or the deletion is blocked (configurable).
-
-```yaml
-manager:
- type: lookup
- reference_to: user
- multiple: false
-```
-
-### Master-Detail
-A strong parent-child relationship.
-* **Ownership:** The Child (Detail) cannot exist without the Parent (Master).
-* **Cascading Delete:** If Master is deleted, all Details are deleted.
-* **Sharing:** Child implementation inherits permissions from the Master.
-
-```yaml
-project_id:
- type: master_detail
- reference_to: project
-```
-
-## 2. Computed Types
-
-Computed types are calculated at runtime (read-time) or compile-time (write-time), depending on the backend capability.
-
-### Formula
-Calculates a value based on other fields in the *same* record (or parent records).
-* **Syntax:** Excel-like syntax or JavaScript expression.
-* **Storage:** Usually virtual (calculated on `SELECT`), but can be persisted.
-
-```yaml
-total_price:
- type: formula
- formula: "amount * quantity"
- data_type: currency
-```
-
-### Summary (Rollup)
-Calculates a value based on *child* records.
-* **Operations:** `COUNT`, `SUM`, `MIN`, `MAX`.
-* **Context:** Only available on the master side of a Master-Detail relationship.
-
-```yaml
-total_tasks:
- type: summary
- summary_object: project_task
- summary_field: id
- summary_type: count
-```
-
-## 3. Polymorphic Types
-
-### Any / Variant
-Allows storage of unstructured JSON data.
-* **Driver Support:** Uses JSONB in Postgres, native JSON in Mongo.
-
-### Grid / Table
-A "Mini-Table" inside a record. Useful for simple line items (e.g., Expense Lines) without creating a full child object.
diff --git a/content/docs/specifications/data/analytics-protocol.mdx b/content/docs/specifications/data/analytics-protocol.mdx
deleted file mode 100644
index 5b868b68e..000000000
--- a/content/docs/specifications/data/analytics-protocol.mdx
+++ /dev/null
@@ -1,57 +0,0 @@
----
-title: Analytics Protocol
-description: Specification for Analytical Queries (OLAP), Datasets, and Aggregation types.
----
-
-ObjectQL distinguishes between Transactional (OLTP) and Analytical (OLAP) workloads.
-The Analytics Specification defines how to define **Datasets** (Cubes) and query them efficiently.
-
-## 1. Datasets
-
-A Dataset is a semantic layer over one or more Objects, optimized for aggregation.
-
-```yaml
-# opportunity.dataset.yml
-name: opportunity_analysis
-label: Opportunity Analysis
-root_object: opportunity
-measures:
- - name: sum_amount
- function: sum
- field: amount
-dimensions:
- - field: account.industry
- - field: close_date
- granularity: month
-```
-
-## 2. Aggregation Queries
-
-Analytical queries return grouped data rather than record lines.
-
-```json
-// POST /api/v4/analytics/query
-{
- "dataset": "opportunity_analysis",
- "dimensions": ["account.industry"],
- "measures": ["sum_amount"],
- "filters": [
- ["stage", "=", "Closed Won"]
- ]
-}
-```
-
-### Response Format
-```json
-[
- { "account.industry": "Technology", "sum_amount": 5000000 },
- { "account.industry": "Finance", "sum_amount": 2500000 }
-]
-```
-
-## 3. Visualization Mapping
-
-The protocol includes hints for UI rendering.
-
-* `chartType`: Default visualization (bar, line, pie).
-* `colorScale`: Semantic coloring rules.
diff --git a/content/docs/specifications/data/architecture.cn.mdx b/content/docs/specifications/data/architecture.cn.mdx
deleted file mode 100644
index f3e5ded7a..000000000
--- a/content/docs/specifications/data/architecture.cn.mdx
+++ /dev/null
@@ -1,59 +0,0 @@
----
-title: 编译器架构
-description: ObjectQL 的高级架构。数据库编译器如何将声明性意图转换为物理执行。
----
-
-import { Database, FileJson, ServerCog, ArrowRight } from 'lucide-react';
-
-**ObjectQL** 决定数据层的行为。它被设计为一个**编译器**,将通用 JSON 中间表示(IR)转换为特定数据库的指令(SQL、NoSQL 等)。
-
-## 架构管道
-
-ObjectStack 数据引擎在四个不同的阶段运行。这种关注点分离使系统能够在保持原生性能的同时与数据库无关。
-
-### 1. 定义阶段(Schema)
-**输入:** YAML/JSON Schema 文件(`*.object.yml`)
-**角色:** 定义数据的"形状"和"规则"。
-**产物:**
-* **对象定义:** 表/集合。
-* **字段定义:** 列/属性。
-* **验证规则:** 完整性约束。
-
-### 2. 组合阶段(AST)
-**输入:** API 请求 / SDK 调用
-**角色:** 将传入的意图解析为规范化的**抽象语法树(AST)**。
-**关键操作:**
-* **验证:** 确保查询与 Schema 匹配。
-* **权限注入:** 基于 ACL 自动添加过滤器(例如,`AND owner = 'me'`)。
-* **规范化:** 将语法糖转换为严格的逻辑表达式。
-
-### 3. 编译阶段(驱动程序)
-**输入:** 规范化查询 AST
-**角色:** 底层**驱动程序**(Postgres、SQLite、Mongo)接收 AST 并将其编译为数据库的原生语言。
-**示例:**
-* *Postgres 驱动程序:* `SELECT * FROM accounts WHERE type = 'customer'`
-* *Mongo 驱动程序:* `db.accounts.find({ type: 'customer' })`
-
-### 4. 执行阶段(结果)
-**输入:** 原生游标
-**角色:** 执行物理查询并将输出格式化回标准 JSON 协议。
-
----
-
-## 协议三位一体
-
-ObjectQL 由三个核心规范组成:
-
-| 规范 | 范围 | 职责 |
-| :--- | :--- | :--- |
-| **[Schema 定义](/docs/specifications/data/schema-definition)** | 静态 | 如何定义对象、字段和关系。 |
-| **[AST 结构](/docs/specifications/data/ast-structure)** | 运行时 | JSON 查询对象("IR")的结构。 |
-| **[传输协议](/docs/specifications/data/wire-protocol)** | 传输 | 客户端和服务器如何通过 HTTP 交换这些结构。 |
-
-## 设计约束
-
-为了维护"一次编写,随处运行"的承诺,ObjectQL 强制执行以下约束:
-
-1. **无泄漏抽象:** 你不能执行原始 SQL 字符串。所有访问都必须通过 AST。
-2. **幂等 Schema:** 应用两次 Schema 定义必须产生相同的数据库状态。
-3. **原子事务:** 所有变更操作(插入/更新/删除)默认必须是事务性的。
diff --git a/content/docs/specifications/data/architecture.mdx b/content/docs/specifications/data/architecture.mdx
deleted file mode 100644
index b88cd7bf0..000000000
--- a/content/docs/specifications/data/architecture.mdx
+++ /dev/null
@@ -1,59 +0,0 @@
----
-title: Compiler Architecture
-description: The High-Level Architecture of ObjectQL. How the Database Compiler transforms declarative intent into physical execution.
----
-
-import { Database, FileJson, ServerCog, ArrowRight } from 'lucide-react';
-
-**ObjectQL** determines the behavior of the Data Layer. It is designed as a **Compiler** that translates a universal JSON-Intermediate Representation (IR) into database-specific instructions (SQL, NoSQL, etc.).
-
-## The Architecture Pipeline
-
-The ObjectStack Data Engine operates in four distinct stages. This separation of concerns is what allows the system to be database-agnostic while maintaining native performance.
-
-### 1. Definition Phase (The Schema)
-**Input:** YAML/JSON Schema Files (`*.object.yml`)
-**Role:** Defines the "Shape" and "Rules" of the data.
-**Artifacts:**
-* **Object Definition:** Tables/Collections.
-* **Field Definition:** Columns/Properties.
-* **Validation Rules:** Integrity constraints.
-
-### 2. Composition Phase (The AST)
-**Input:** API Request / SDK Call
-**Role:** Parses the incoming intent into a normalized **Abstract Syntax Tree (AST)**.
-**Key Operations:**
-* **Validation:** Ensuring the query matches the Schema.
-* **Permission Injection:** Automatically adding filters (e.g., `AND owner = 'me'`) based on ACLs.
-* **Normalization:** Converting syntactic sugar into strict logical expressions.
-
-### 3. Compilation Phase (The Driver)
-**Input:** Normalized Query AST
-**Role:** An underlying **Driver** (Postgres, SQLite, Mongo) takes the AST and compiles it into the native language of the database.
-**Examples:**
-* *Postgres Driver:* `SELECT * FROM accounts WHERE type = 'customer'`
-* *Mongo Driver:* `db.accounts.find({ type: 'customer' })`
-
-### 4. Execution Phase (The Result)
-**Input:** Native Cursor
-**Role:** Executes the physical query and formats the output back into standard JSON Protocol.
-
----
-
-## The Trinity of Protocols
-
-ObjectQL is comprised of three core specifications:
-
-| Specification | Scope | Responsibility |
-| :--- | :--- | :--- |
-| **[Schema Definition](/docs/specifications/data/schema-definition)** | Static | How to define Objects, Fields, and Relationships. |
-| **[AST Structure](/docs/specifications/data/ast-structure)** | Runtime | The structure of the JSON Query Object (The "IR"). |
-| **[Wire Protocol](/docs/specifications/data/wire-protocol)** | Transport | How Clients and Servers exchange these structures over HTTP. |
-
-## Design Constraints
-
-To maintain the "Write Once, Run Anywhere" promise, ObjectQL enforces the following constraints:
-
-1. **No Leaky Abstractions:** You cannot execute raw SQL strings. All access must be via the AST.
-2. **Idempotent Schema:** Applying a Schema definition twice must result in the same database state.
-3. **Atomic Transactions:** All mutation operations (Insert/Update/Delete) must be transactional by default.
diff --git a/content/docs/specifications/data/ast-structure.mdx b/content/docs/specifications/data/ast-structure.mdx
deleted file mode 100644
index 6e43e3ecc..000000000
--- a/content/docs/specifications/data/ast-structure.mdx
+++ /dev/null
@@ -1,85 +0,0 @@
----
-title: AST Structure
-description: The JSON Intermediate Representation (IR) for ObjectQL Queries. The language spoken by the Database Compiler.
----
-
-The **ObjectQL Abstract Syntax Tree (AST)** is the runtime specification for data access. When you use the OQL SDK or GraphQL API, your request is parsed into this normalized JSON structure before it touches the database driver.
-
-## The Query Object
-
-Every standard retrieval operation resolves to this structure:
-
-```typescript
-interface QueryAST {
- fields?: string[]; // Projection (SELECT)
- filters?: FilterNode; // Predicates (WHERE)
- sort?: string; // Ordering (ORDER BY)
- top?: number; // Limit (LIMIT)
- skip?: number; // Offset (OFFSET)
- expand?: string[]; // Joins (JOIN / $lookup)
-}
-```
-
-## 1. Filters (The WHERE Clause)
-
-The filtering logic uses LISP-like nested arrays (or simplified JSON syntax) to represent logical trees.
-
-### Syntax
-`[ field, operator, value ]` or `[ clause, logic, clause ]`
-
-### Example
-```json
-// WHERE (category = 'electronics') AND (price > 1000 OR featured = true)
-[
- ["category", "=", "electronics"],
- "and",
- [
- ["price", ">", 1000],
- "or",
- ["featured", "=", true]
- ]
-]
-```
-
-### Supported Operators
-| Operator | Suffix | Example |
-| :--- | :--- | :--- |
-| `=` | `eq` | Equals |
-| `<>` | `ne` | Not Equals |
-| `>` | `gt` | Greater Than |
-| `contains` | `like` | String matching |
-| `between` | - | Range check |
-
-## 2. Projection (The SELECT Clause)
-
-Defines which fields to return.
-* **Default:** Returns all fields if omitted.
-* **Specific:** `["name", "email", "company"]`
-
-## 3. Expansion (The JOIN Clause)
-
-ObjectQL handles relationships via `expand`. It supports deep compilation strategies (performing standard SQL `JOIN` or multiple fetches based on performance optimization).
-
-```json
-// Get Project and its related Manager info
-{
- "expand": ["manager", "customer.name"]
-}
-```
-
-## 4. Sorting
-
-Standard SQL-like sort string.
-* `"created_at desc"`
-* `"priority desc, due_date asc"`
-
-## The Mutation AST
-
-For modifications, the AST structure changes slightly:
-
-```typescript
-interface MutationAST {
- id?: string | number; // Primary Key for Update/Delete
- doc?: Record; // The payload for Insert/Update
-}
-```
diff --git a/content/docs/specifications/data/index.mdx b/content/docs/specifications/data/index.mdx
deleted file mode 100644
index 0f15f9dac..000000000
--- a/content/docs/specifications/data/index.mdx
+++ /dev/null
@@ -1,149 +0,0 @@
----
-title: Data Protocol (ObjectQL)
-description: Comprehensive specification for the ObjectStack Data Layer - defining schemas, queries, and business logic.
----
-
-import { Database, GitBranch, Shield, Zap } from 'lucide-react';
-
-The **Data Protocol (ObjectQL)** is the foundation of ObjectStack. It defines how to:
-- Express data structures (Objects, Fields)
-- Query data (AST-based abstraction)
-- Implement business logic (Formulas, Workflows, Validation)
-- Secure data (Permissions, Sharing Rules)
-
-## Core Components
-
-
- }
- title="Architecture"
- href="/docs/specifications/data/architecture"
- description="High-level overview of the Data Layer design and philosophy"
- />
- }
- title="Schema Definition"
- href="/docs/specifications/data/schema-definition"
- description="How to define Objects, Fields, and Relationships"
- />
- }
- title="Query AST Structure"
- href="/docs/specifications/data/ast-structure"
- description="Abstract Syntax Tree for database-agnostic queries"
- />
- }
- title="Advanced Types"
- href="/docs/specifications/data/advanced-types"
- description="Complex field types and their implementations"
- />
-
-
-## Specifications
-
-### Core Specifications
-
-1. **[Architecture Overview](/docs/specifications/data/architecture)**
- - Design principles
- - Layer responsibilities
- - Driver model
-
-2. **[Schema Definition](/docs/specifications/data/schema-definition)**
- - Object schema structure
- - Field type definitions
- - Relationship modeling
-
-3. **[Advanced Types](/docs/specifications/data/advanced-types)**
- - Formula fields
- - Lookup relationships
- - Master-detail relationships
- - Junction objects (many-to-many)
-
-### Query Layer
-
-4. **[AST Structure](/docs/specifications/data/ast-structure)**
- - Query Abstract Syntax Tree
- - Filter expressions
- - Aggregations
- - Joins and includes
-
-5. **[Analytics Protocol](/docs/specifications/data/analytics-protocol)**
- - Grouping and aggregation
- - Calculated fields
- - Time-series queries
-
-### System Specifications
-
-6. **[Transaction Model](/docs/specifications/data/transaction-model)**
- - ACID guarantees
- - Isolation levels
- - Distributed transactions
-
-7. **[Wire Protocol](/docs/specifications/data/wire-protocol)**
- - Data serialization format
- - Network protocol
- - Compression and optimization
-
-## Quick Links
-
-### For Implementers
-
-Building a driver for ObjectStack? Start here:
-- [Driver Interface](/docs/references/system/Driver)
-- [Query Compiler](/docs/guides/custom-driver)
-- [Test Suite](/docs/guides/driver-testing)
-
-### For Users
-
-Using ObjectStack to build applications? See:
-- [Field Types Guide](/docs/guides/field-types)
-- [Query Examples](/docs/guides/querying-data)
-- [Business Logic](/docs/guides/workflows-validation)
-
-## Design Principles
-
-The Data Protocol follows these core principles:
-
-### 1. Database Agnostic
-
-ObjectQL queries compile to **any** backend:
-```
-ObjectQL Query → AST → Driver Translates → SQL/NoSQL/API
-```
-
-### 2. Type-Safe
-
-All schemas are Zod schemas with TypeScript inference:
-```typescript
-export const TaskSchema = ObjectSchema.create({ ... });
-type Task = z.infer;
-```
-
-### 3. Declarative
-
-Express **what you want**, not **how to get it**:
-```typescript
-// Declarative query
-Query.create({
- object: 'task',
- filters: { status: { eq: 'open' } },
-});
-
-// Driver handles: SELECT * FROM tasks WHERE status = 'open'
-```
-
-### 4. Composable
-
-Build complex queries from simple building blocks:
-```typescript
-const baseQuery = { object: 'task' };
-const withFilter = { ...baseQuery, filters: { ... } };
-const withSort = { ...withFilter, sort: [...] };
-```
-
-## Related Documentation
-
-- **[UI Protocol](/docs/specifications/ui/sdui-protocol)** - How to render data
-- **[System Protocol](/docs/specifications/server/kernel-architecture)** - Runtime environment
-- **[API Protocol](/docs/references/api/envelopes/BaseResponse)** - REST/GraphQL contracts
diff --git a/content/docs/specifications/data/meta.cn.json b/content/docs/specifications/data/meta.cn.json
deleted file mode 100644
index 0fb086efa..000000000
--- a/content/docs/specifications/data/meta.cn.json
+++ /dev/null
@@ -1,12 +0,0 @@
-{
- "title": "ObjectQL",
- "pages": [
- "architecture",
- "schema-definition",
- "advanced-types",
- "ast-structure",
- "analytics-protocol",
- "transaction-model",
- "wire-protocol"
- ]
-}
diff --git a/content/docs/specifications/data/meta.json b/content/docs/specifications/data/meta.json
deleted file mode 100644
index 0fde0b361..000000000
--- a/content/docs/specifications/data/meta.json
+++ /dev/null
@@ -1,13 +0,0 @@
-{
- "title": "ObjectQL",
- "pages": [
- "index",
- "architecture",
- "schema-definition",
- "advanced-types",
- "ast-structure",
- "analytics-protocol",
- "transaction-model",
- "wire-protocol"
- ]
-}
diff --git a/content/docs/specifications/data/schema-definition.mdx b/content/docs/specifications/data/schema-definition.mdx
deleted file mode 100644
index 2246297cc..000000000
--- a/content/docs/specifications/data/schema-definition.mdx
+++ /dev/null
@@ -1,87 +0,0 @@
----
-title: Schema Definition
-description: The core of ObjectQL. How to define Objects, Fields, and Relationships using declarative protocols.
----
-
-In ObjectStack, data structure is defined via **Configuration**, not Code.
-The Schema Definition Protocol governs how you declare your Data Model (`Objects`) and your Data Dictionary (`Fields`).
-
-> **Single Source of Truth:** This schema drives Database DDL, API Generation, UI Form Layouts, and Permission Scopes.
-
-## 1. The Object Definition
-
-An Object represents a business entity (like a Table in SQL or Collection in NoSQL).
-
-```yaml
-# project.object.yml
-name: project # Machine Name (snake_case, unique)
-label: Project # Human Label
-icon: standard:case # Icon from SLDS or standard set
-bucket: main # Database connection/shard key
-enable: # Capabilities
- audit: true # Track field history
- workflow: true # Allow process builder
- full_text_search: true # Index for global search
-description: "A business project or initiative."
-fields:
- name:
- type: text
- label: Project Name
- required: true
- status:
- type: select
- options:
- - label: Draft
- value: draft
- - label: Active
- value: active
-```
-
-### Key Properties
-
-| Property | Type | Description |
-| :--- | :--- | :--- |
-| `name` | `string` | **Required.** Unique identifier. Must be `snake_case`. |
-| `label` | `string` | **Required.** Display label for UI. |
-| `fields` | `Map` | Dictionary of fields. |
-| `datasource` | `string` | The external datasource ID (if not storing in default DB). |
-
-## 2. The Field Definition
-
-Fields define the columns or attributes of the Object.
-
-```yaml
-# In-line definition or separate .field.yml
-type: number
-scale: 2
-precision: 18
-defaultValue: 0
-required: true
-index: true # Create DB Index
-unique: false # Enforce Uniqueness
-```
-
-### Core Field Types
-See [Advanced Types](/docs/specifications/data/advanced-types) for the full list.
-* `text`, `textarea`, `html`
-* `number`, `currency`, `percent`
-* `date`, `datetime`
-* `boolean`
-* `select` (Picklist)
-* `lookup`, `master_detail` (Foreign Keys)
-* `formula`, `summary` (Derived)
-
-## 3. The Validation Protocol
-
-Validation logic is declarative and runs on the server (and compiled to client-side logic where possible).
-
-```yaml
-validation_rules:
- - name: start_before_end
- condition: "end_date < start_date"
- message: "End Date must be after Start Date"
-```
-
-## 4. Derived Schemas
-
-The Protocol allows for **Schema Derivation**. You can define a base object and extend it, though ObjectStack prefers **Composition** via mixins or separate relation tables over classical OOP inheritance.
diff --git a/content/docs/specifications/data/transaction-model.mdx b/content/docs/specifications/data/transaction-model.mdx
deleted file mode 100644
index d940168e9..000000000
--- a/content/docs/specifications/data/transaction-model.mdx
+++ /dev/null
@@ -1,39 +0,0 @@
----
-title: Transaction Model
-description: ACID definitions and the Trigger Execution Pipeline.
----
-
-ObjectStack guarantees **Atomic** operations for all mutations.
-
-## 1. Isolation Levels
-* **Default:** `Read Committed`.
-* ObjectQL drivers map this to the underlying database transaction capabilities.
-
-## 2. The Execution Pipeline (Trigger Order)
-
-When a record is saved, the Kernel executes the following idempotent steps.
-
-1. **System Validation:** Check primitive types (string length, number format).
-2. **Before Triggers:**
- * Execute `beforeInsert` / `beforeUpdate` scripts.
- * Useful for setting explicit default values or manipulating input.
-3. **User Validation:**
- * Execute custom `Validation Rules` (declarative).
- * Execute `validate` scripts.
-4. **Database Commit:**
- * The record is written to the DB.
- * Locks are held.
-5. **After Triggers:**
- * Execute `afterInsert` / `afterUpdate` scripts.
- * Useful for updating related records (Rollups).
-6. **Workflow & Automation:**
- * Evaluate Workflow Rules.
- * Launch Processes (Flows).
- * Enqueue Asynchronous Jobs.
-7. **Final Commit:** Transaction complete.
-
-## 3. Atomic Batching
-
-If you send an array of 100 records to be inserted, strict atomicity applies:
-* **All or Nothing:** If record #99 fails validation, records #1-#98 are rolled back.
-* **Exception:** If `allOrNone: false` header is set, partial success is allowed (common for bulk data loading).
diff --git a/content/docs/specifications/data/wire-protocol.mdx b/content/docs/specifications/data/wire-protocol.mdx
deleted file mode 100644
index e0b1589c9..000000000
--- a/content/docs/specifications/data/wire-protocol.mdx
+++ /dev/null
@@ -1,56 +0,0 @@
----
-title: Wire Protocol
-description: The HTTP Interface for ObjectQL. Standard Request/Response envelopes for REST and GraphQL.
----
-
-ObjectStack assumes a **Stateless, JSON-over-HTTP** transport layer.
-
-## 1. The Standard Envelope
-
-All ObjectQL API responses follow a strict OData-inspired envelope structure to ensure consistency across success and error states.
-
-### Success Response
-```json
-{
- "@odata.context": "$metadata#accounts",
- "@odata.count": 250,
- "value": [
- { "_id": "1", "name": "Acme Corp" },
- { "_id": "2", "name": "Wayne Enterprises" }
- ]
-}
-```
-
-### Error Response
-```json
-{
- "error": {
- "code": "VALIDATION_ERROR",
- "message": "Start Date cannot be after End Date",
- "details": [
- { "field": "end_date", "reason": "Date out of range" }
- ]
- }
-}
-```
-
-## 2. URL Conventions
-
-### Record Retrieval
-`GET /api/v4/{object_name}/{record_id}`
-
-### Query (List)
-`GET /api/v4/{object_name}`
-* `$filter`: OData style filter string (e.g. `title eq 'CEO'`).
-* `$select`: Projection `name,email`.
-* `$expand`: Joins `company`.
-
-### Mutation
-* `POST /api/v4/{object_name}` (Create)
-* `PUT /api/v4/{object_name}/{record_id}` (Update)
-* `DELETE /api/v4/{object_name}/{record_id}` (Delete)
-
-## 3. Metadata Exchange
-
-The client can request schema definitions dynamically.
-* `GET /api/v4/metadata/objects/{object_name}`: Returns the JSON Schema for the object, allowing the UI to render forms dynamically.
diff --git a/content/docs/specifications/index.mdx b/content/docs/specifications/index.mdx
deleted file mode 100644
index 1e040cddc..000000000
--- a/content/docs/specifications/index.mdx
+++ /dev/null
@@ -1,245 +0,0 @@
----
-title: Protocol Specifications
-description: Complete technical specifications for the ObjectStack Protocol - the "constitution" of the metadata-driven platform.
----
-
-import { Database, Layout, Server } from 'lucide-react';
-
-The ObjectStack Protocol is defined through three core specifications that work together to create a complete metadata-driven platform.
-
-## The Three-Layer Architecture
-
-
- }
- title="Data Protocol (ObjectQL)"
- href="/docs/specifications/data"
- description="Define data structures, queries, and business logic. Database-agnostic abstraction layer."
- />
- }
- title="UI Protocol (ObjectUI)"
- href="/docs/specifications/ui"
- description="Server-driven UI definitions. Express interfaces as JSON, not code."
- />
- }
- title="System Protocol (ObjectOS)"
- href="/docs/specifications/server"
- description="Runtime kernel, plugins, security, and integration. The platform foundation."
- />
-
-
-## What Are Specifications?
-
-These documents define the **ObjectStack Protocol** - the rules and standards that all implementations must follow.
-
-Think of them as:
-- **The SQL Specification** → Defines what SQL should do
-- **The HTTP Specification** → Defines how web communication works
-- **The ObjectStack Specification** → Defines how metadata-driven platforms work
-
-## Who Should Read These?
-
-### Protocol Implementers
-
-Building an ObjectStack implementation?
-
-- **Kernel Developers:** Implement the runtime engine
-- **Driver Developers:** Connect new databases (PostgreSQL, MongoDB, etc.)
-- **Renderer Developers:** Build UI renderers (React, Vue, Flutter)
-
-Start with:
-1. [System Protocol - Kernel Architecture](/docs/specifications/server/kernel-architecture)
-2. [Data Protocol - Architecture](/docs/specifications/data/architecture)
-3. [UI Protocol - SDUI Protocol](/docs/specifications/ui/sdui-protocol)
-
-### Platform Architects
-
-Evaluating ObjectStack for your organization?
-
-- **CTOs:** Understand architectural decisions
-- **Tech Leads:** Evaluate scalability and security
-- **Solution Architects:** Design integration patterns
-
-Start with:
-1. [Data Protocol - Architecture](/docs/specifications/data/architecture)
-2. [System Protocol - Permission Governance](/docs/specifications/server/permission-governance)
-3. [UI Protocol - Component Schema](/docs/specifications/ui/component-schema)
-
-### Advanced Users
-
-Building complex applications with ObjectStack?
-
-- **Power Users:** Understand limits and capabilities
-- **Custom Plugin Developers:** Extend the platform
-- **Integration Engineers:** Connect external systems
-
-Start with:
-1. [Data Protocol - AST Structure](/docs/specifications/data/ast-structure)
-2. [System Protocol - Plugin Manifest](/docs/specifications/server/plugin-manifest)
-3. [UI Protocol - Action Triggers](/docs/specifications/ui/action-triggers)
-
-## Specification Structure
-
-Each specification follows a consistent structure:
-
-### 1. Overview
-
-- **Purpose:** What problem does this solve?
-- **Design Principles:** What are the guiding principles?
-- **Architecture Diagram:** Visual representation
-
-### 2. Core Concepts
-
-- **Schemas:** Zod definitions
-- **Types:** TypeScript interfaces
-- **Examples:** Real-world usage
-
-### 3. Implementation Notes
-
-- **Driver Responsibilities:** What must drivers implement?
-- **Renderer Responsibilities:** What must renderers handle?
-- **Kernel Integration:** How does it fit into the system?
-
-### 4. Reference
-
-- **API Documentation:** Complete type reference
-- **Test Suite:** Compliance tests
-- **Migration Guide:** Version upgrade paths
-
-## Key Design Principles
-
-### 1. Protocol Over Framework
-
-ObjectStack is a **protocol**, not a framework:
-
-```
-Protocol Definition (Zod schemas)
- ↓
-Multiple Implementations
- • Node.js Kernel
- • Go Kernel
- • Python Kernel
- • Custom Kernel
-```
-
-### 2. Declarative Over Imperative
-
-Express **intent**, not **implementation**:
-
-```typescript
-// What you want (declarative)
-const Task = ObjectSchema.create({
- fields: {
- title: Field.text({ required: true }),
- }
-});
-
-// How to do it (handled by kernel)
-// ✓ Generate SQL schema
-// ✓ Create API endpoints
-// ✓ Validate requests
-// ✓ Render UI
-```
-
-### 3. Type-Safe by Default
-
-All schemas are Zod + TypeScript:
-
-```typescript
-// Source: Zod schema
-export const TaskSchema = z.object({ ... });
-
-// Derived: TypeScript type
-type Task = z.infer;
-
-// Derived: JSON Schema
-const jsonSchema = zodToJsonSchema(TaskSchema);
-```
-
-### 4. Database Agnostic
-
-ObjectQL compiles to any backend:
-
-```
-ObjectQL Query → AST → Driver Translates
- ↓
- SQL | NoSQL | API
-```
-
-### 5. Extensible by Design
-
-Plugin architecture for unlimited extensibility:
-
-```typescript
-// Core is minimal
-const kernel = new Kernel();
-
-// Add capabilities via plugins
-kernel.loadPlugin(PostgresDriver);
-kernel.loadPlugin(AuthPlugin);
-kernel.loadPlugin(AnalyticsPlugin);
-```
-
-## Versioning & Compatibility
-
-ObjectStack follows **Semantic Versioning** (semver):
-
-```
-MAJOR.MINOR.PATCH
- 1 . 0 . 0
-```
-
-- **MAJOR:** Breaking changes to protocol
-- **MINOR:** New features (backward compatible)
-- **PATCH:** Bug fixes
-
-### Compatibility Guarantee
-
-- **Same MAJOR version:** 100% compatible
-- **Different MAJOR:** May require migration
-
-Example:
-- Schema written for **v1.x.x** works on **v1.5.0** ✅
-- Schema written for **v1.x.x** may need updates for **v2.0.0** ⚠️
-
-## Specification Roadmap
-
-### Current (v0.x)
-
-- ✅ Data Protocol (ObjectQL) - Core schemas
-- ✅ UI Protocol (ObjectUI) - View definitions
-- ✅ System Protocol (ObjectOS) - Kernel architecture
-- 🚧 AI Protocol - Agent definitions
-- 🚧 API Protocol - REST/GraphQL contracts
-
-### Future (v1.x)
-
-- 📋 Real-time Protocol - WebSocket/SSE specifications
-- 📋 Offline Protocol - Sync and conflict resolution
-- 📋 Search Protocol - Full-text search abstraction
-- 📋 Analytics Protocol - Advanced reporting
-
-## Contributing to Specifications
-
-Want to propose changes or additions?
-
-1. **Read:** [Contributing Guide](https://github.com/objectstack-ai/spec/blob/main/CONTRIBUTING.md)
-2. **Discuss:** [GitHub Issues](https://github.com/objectstack-ai/spec/issues)
-3. **Propose:** [Submit an RFC](https://github.com/objectstack-ai/spec/issues/new?template=rfc.md)
-
-### RFC Process
-
-1. **Draft:** Write RFC document
-2. **Discussion:** Community feedback (2 weeks)
-3. **Review:** Core team review
-4. **Decision:** Accept, Reject, or Iterate
-5. **Implementation:** Update specs + reference implementation
-
-## Related Documentation
-
-- **[Concepts](/docs/concepts/architecture)** - High-level philosophy
-- **[Guides](/docs/guides/getting-started)** - Practical how-to guides
-- **[References](/docs/references/data/core/Object)** - Complete API documentation
-- **[Examples](https://github.com/objectstack-ai/spec/tree/main/examples)** - Reference implementations
diff --git a/content/docs/specifications/meta.cn.json b/content/docs/specifications/meta.cn.json
deleted file mode 100644
index 198387a96..000000000
--- a/content/docs/specifications/meta.cn.json
+++ /dev/null
@@ -1,11 +0,0 @@
-{
- "title": "规范",
- "root": true,
- "pages": [
- "index",
- "architecture",
- "data",
- "ui",
- "server"
- ]
-}
diff --git a/content/docs/specifications/meta.json b/content/docs/specifications/meta.json
deleted file mode 100644
index 3e94b804d..000000000
--- a/content/docs/specifications/meta.json
+++ /dev/null
@@ -1,11 +0,0 @@
-{
- "title": "Specifications",
- "root": true,
- "pages": [
- "index",
- "architecture",
- "data",
- "ui",
- "server"
- ]
-}
diff --git a/content/docs/specifications/server/audit-compliance.mdx b/content/docs/specifications/server/audit-compliance.mdx
deleted file mode 100644
index e3a6a3233..000000000
--- a/content/docs/specifications/server/audit-compliance.mdx
+++ /dev/null
@@ -1,23 +0,0 @@
----
-title: Audit & Compliance
-description: The Protocol for Accountability and Forensic Logging.
----
-
-For enterprise software, "Who did what and when" is non-negotiable.
-
-## 1. Field History Tracking
-Configured per-field in the Object Schema.
-* **Track Old/New:** Records the previous and new value.
-* **Retention:** Definitions for how long to keep history (e.g., "10 Years").
-
-## 2. Setup Audit Trail
-Logs all changes to **Metadata** (Schema).
-* "User A changed the validation rule on Project."
-* "User B deleted the 'Salary' field."
-
-## 3. Login History
-Logs every authentication attempt.
-* **Context:** IP Address, Browser, Location, Status (Success/Fail).
-
-## 4. System Log
-Debug logs for developers (Triggers, Flows).
diff --git a/content/docs/specifications/server/automation-rules.mdx b/content/docs/specifications/server/automation-rules.mdx
deleted file mode 100644
index 05d671c27..000000000
--- a/content/docs/specifications/server/automation-rules.mdx
+++ /dev/null
@@ -1,31 +0,0 @@
----
-title: Automation Rules
-description: The Protocol for Lightweight, Event-Driven Logic.
----
-
-Automation Rules differ from Workflows in that they are typically strictly **Event-Driven** and stateless.
-
-## 1. Triggers (Code)
-Server-side scripts (TypeScript/Python) that run in the transaction transaction.
-
-```typescript
-// project.trigger.ts
-export const beforeInsert = async (ctx) => {
- if (ctx.doc.amount > 10000) {
- ctx.doc.status = 'High Value';
- }
-}
-```
-
-## 2. Validation Rules (No-Code)
-Boolean expressions that block a save if they return `true`.
-Defined in the Object Schema (`validation` property).
-
-## 3. Auto-Response Rules
-Logic for sending immediate email replies (e.g., "Thanks for your Ticket").
-
-## 4. Assignment Rules
-Logic for changing the `owner` of a record (e.g., "Round Robin" assignment for Leads).
-
-## 5. Escalation Rules
-Logic for time-based updates (e.g., "If Case not solved in 4h, notify Manager").
diff --git a/content/docs/specifications/server/index.mdx b/content/docs/specifications/server/index.mdx
deleted file mode 100644
index e1b4c5da6..000000000
--- a/content/docs/specifications/server/index.mdx
+++ /dev/null
@@ -1,382 +0,0 @@
----
-title: System Protocol (ObjectOS)
-description: Comprehensive specification for the ObjectStack System Layer - kernel architecture, plugins, and runtime environment.
----
-
-import { Cpu, Package, Shield, Zap } from 'lucide-react';
-
-The **System Protocol (ObjectOS)** defines the runtime environment for ObjectStack applications. It specifies:
-- Kernel architecture and lifecycle
-- Plugin discovery and loading
-- Authentication and authorization
-- Integration and webhooks
-- Audit and compliance
-
-## Core Components
-
-
- }
- title="Kernel Architecture"
- href="/docs/specifications/server/kernel-architecture"
- description="Core runtime engine that orchestrates all components"
- />
- }
- title="Plugin Manifest"
- href="/docs/specifications/server/plugin-manifest"
- description="Package structure and plugin loading mechanism"
- />
- }
- title="Permission Governance"
- href="/docs/specifications/server/permission-governance"
- description="Multi-layered access control and security"
- />
- }
- title="REST API"
- href="/docs/specifications/server/rest-api"
- description="Auto-generated API specification"
- />
-
-
-## Specifications
-
-### Core System
-
-1. **[Kernel Architecture](/docs/specifications/server/kernel-architecture)**
- - Kernel design and responsibilities
- - Component lifecycle
- - Event system
- - Dependency injection
-
-2. **[Plugin Manifest](/docs/specifications/server/plugin-manifest)**
- - Manifest structure (`objectstack.config.ts`)
- - Plugin metadata
- - Dependencies and versioning
-
-3. **[Workflow Engine](/docs/specifications/server/workflow-engine)**
- - Trigger types (before/after insert/update/delete)
- - Action execution
- - Error handling
-
-### Security & Compliance
-
-4. **[Permission Governance](/docs/specifications/server/permission-governance)**
- - Object-level permissions
- - Field-level security
- - Row-level sharing
- - Territory management
-
-5. **[Audit & Compliance](/docs/specifications/server/audit-compliance)**
- - Field history tracking
- - Login history
- - API usage logs
- - Compliance reports (GDPR, SOC2)
-
-### Integration
-
-6. **[Automation Rules](/docs/specifications/server/automation-rules)**
- - Field updates
- - Email alerts
- - Process automation
-
-7. **[Integration & ETL](/docs/specifications/server/integration-etl)**
- - Webhook definitions
- - External API calls
- - Data transformation
- - Batch processing
-
-### API Layer
-
-8. **[REST API](/docs/specifications/server/rest-api)**
- - Endpoint structure
- - Request/Response format
- - Authentication
- - Rate limiting
-
-## Kernel Architecture
-
-The Kernel is the central orchestrator of an ObjectStack application:
-
-```
-┌─────────────────────────────────────────┐
-│ Kernel │
-├─────────────────────────────────────────┤
-│ • Plugin Registry │
-│ • Driver Registry │
-│ • Event Bus │
-│ • Permission Engine │
-│ • Workflow Engine │
-└─────────────────────────────────────────┘
- ↓ ↓ ↓
- [Plugins] [Drivers] [Extensions]
-```
-
-### Kernel Responsibilities
-
-1. **Plugin Management:**
- - Load and initialize plugins
- - Resolve dependencies
- - Hot-reload support
-
-2. **Request Routing:**
- - API request handling
- - Query execution
- - Response formatting
-
-3. **Security:**
- - Authentication verification
- - Permission checking
- - Data encryption
-
-4. **Event Coordination:**
- - Publish/subscribe events
- - Trigger workflow actions
- - Audit logging
-
-## Plugin System
-
-ObjectStack uses a **plugin architecture** inspired by Eclipse RCP and Kubernetes Operators.
-
-### Plugin Structure
-
-```typescript
-export const MyPlugin: Plugin = {
- name: 'my-plugin',
- version: '1.0.0',
-
- // Dependencies
- requires: ['core-plugin@^1.0.0'],
-
- // Lifecycle hooks
- onLoad(kernel: IKernel) {
- // Register components
- kernel.registerDriver('custom', new CustomDriver());
- },
-
- onUnload() {
- // Cleanup
- },
-
- // Provided capabilities
- provides: {
- drivers: [CustomDriver],
- apis: [CustomAPI],
- },
-};
-```
-
-### Plugin Types
-
-| Plugin Type | Purpose | Examples |
-| :--- | :--- | :--- |
-| **Driver** | Database connectivity | PostgreSQL, MongoDB, Redis |
-| **Auth Provider** | Authentication | OAuth, SAML, LDAP |
-| **Renderer** | UI rendering | React, Vue, Flutter |
-| **Integration** | External systems | Stripe, SendGrid, Twilio |
-| **Analytics** | Reporting engines | Metabase, Superset |
-
-## Permission System
-
-Multi-layered access control:
-
-### Layer 1: Object Permissions
-
-```typescript
-Permission.create({
- profile: 'sales_user',
- object: 'opportunity',
- create: true,
- read: true,
- update: { criteria: 'OwnerId = $User.Id' },
- delete: false,
-});
-```
-
-### Layer 2: Field Security
-
-```typescript
-FieldPermission.create({
- profile: 'sales_user',
- object: 'account',
- field: 'annual_revenue',
- read: false,
- edit: false,
-});
-```
-
-### Layer 3: Record Sharing
-
-```typescript
-SharingRule.create({
- object: 'account',
- sharedTo: 'sales_team',
- accessLevel: 'read',
- criteria: { region: 'US' },
-});
-```
-
-## Workflow Engine
-
-Execute business logic automatically:
-
-```typescript
-Workflow.create({
- name: 'notify_manager',
- object: 'opportunity',
- trigger: 'after_insert',
-
- condition: 'Amount > 100000',
-
- actions: [
- WorkflowAction.sendEmail({
- to: '{Owner.Manager.Email}',
- subject: 'Large opportunity created',
- }),
-
- WorkflowAction.updateField({
- field: 'Status',
- value: 'Requires Approval',
- }),
- ],
-});
-```
-
-### Trigger Types
-
-- `before_insert` - Before creating record
-- `after_insert` - After creating record
-- `before_update` - Before updating record
-- `after_update` - After updating record
-- `before_delete` - Before deleting record
-- `after_delete` - After deleting record
-
-## REST API Structure
-
-Auto-generated RESTful API:
-
-```http
-# CRUD Operations
-POST /api/v1/objects/:object # Create
-GET /api/v1/objects/:object/:id # Read
-PATCH /api/v1/objects/:object/:id # Update
-DELETE /api/v1/objects/:object/:id # Delete
-
-# List & Query
-GET /api/v1/objects/:object
- ?filter[field][operator]=value
- &sort=field:direction
- &limit=20
- &offset=0
- &include=related_object
-
-# Bulk Operations
-POST /api/v1/objects/:object/bulk # Bulk create/update
-DELETE /api/v1/objects/:object/bulk # Bulk delete
-
-# Metadata
-GET /api/v1/metadata/objects # List all objects
-GET /api/v1/metadata/objects/:object # Object schema
-```
-
-## Audit & Compliance
-
-### Field History Tracking
-
-```typescript
-Object.create({
- name: 'opportunity',
- enable: {
- trackHistory: true,
- trackedFields: ['Amount', 'Stage', 'CloseDate'],
- },
-});
-```
-
-**Captures:**
-- Who changed the field
-- When it was changed
-- Old value
-- New value
-
-### Login History
-
-Track user authentication events:
-- Login timestamp
-- IP address
-- User agent
-- Login status (success/failure)
-- MFA verification
-
-### API Usage Logs
-
-Monitor API consumption:
-- Endpoint called
-- Request/response size
-- Execution time
-- User context
-- Rate limit status
-
-## Design Principles
-
-### 1. Modularity
-
-Kernel is minimal. Everything else is a plugin:
-
-```
-Minimal Kernel + Plugins = Full Platform
-```
-
-### 2. Hot-Swappable
-
-Plugins can be loaded/unloaded at runtime:
-
-```typescript
-kernel.loadPlugin('analytics-plugin');
-kernel.unloadPlugin('old-integration');
-```
-
-### 3. Event-Driven
-
-Components communicate via events:
-
-```typescript
-kernel.on('record.created', (event) => {
- // React to record creation
-});
-```
-
-### 4. Dependency Injection
-
-Kernel provides services to plugins:
-
-```typescript
-onLoad(kernel: IKernel) {
- const logger = kernel.getLogger();
- const cache = kernel.getCache();
-}
-```
-
-## Quick Links
-
-### For Implementers
-
-Building a kernel implementation? Start here:
-- [Kernel Interface](/docs/references/types/IKernel)
-- [Plugin Development](/docs/guides/plugin-development)
-- [Test Suite](/docs/guides/kernel-testing)
-
-### For Users
-
-Deploying ObjectStack applications? See:
-- [Installation Guide](/docs/guides/installation)
-- [Configuration Reference](/docs/guides/configuration)
-- [Deployment Guide](/docs/guides/deployment)
-
-## Related Documentation
-
-- **[Data Protocol](/docs/specifications/data/architecture)** - Data layer
-- **[UI Protocol](/docs/specifications/ui/sdui-protocol)** - UI layer
-- **[System Reference](/docs/references/system/config/Manifest)** - Configuration API
diff --git a/content/docs/specifications/server/integration-etl.mdx b/content/docs/specifications/server/integration-etl.mdx
deleted file mode 100644
index b5920f8e2..000000000
--- a/content/docs/specifications/server/integration-etl.mdx
+++ /dev/null
@@ -1,26 +0,0 @@
----
-title: Integration & ETL
-description: The Protocol for Data Synchronization and External Connectivity.
----
-
-ObjectOS is designed to prevent "Data Silos".
-
-## 1. External Data Sources (Virtual Objects)
-You can define an Object that maps to an external API instead of the local database.
-
-```yaml
-# stripe_customer.object.yml
-datasource: stripe_api
-name: stripe_customer
-fields: ...
-```
-
-When you query `stripe_customer`, the Kernel translates the ObjectQL AST into a Stripe API call in real-time.
-
-## 2. API Mapping
-A declarative way to map incoming Webhooks or REST calls to internal Objects.
-
-## 3. Data Loader (ETL)
-Standard protocol for Bulk Import/Export.
-* **Format:** CSV, JSONL.
-* **Mode:** Insert, Update, Upsert (match by External ID).
diff --git a/content/docs/specifications/server/kernel-architecture.cn.mdx b/content/docs/specifications/server/kernel-architecture.cn.mdx
deleted file mode 100644
index d79aa2b77..000000000
--- a/content/docs/specifications/server/kernel-architecture.cn.mdx
+++ /dev/null
@@ -1,29 +0,0 @@
----
-title: 内核架构
-description: ObjectOS 内核的设计。用于身份、安全和同步的集中式引擎。
----
-
-import { Cpu, ShieldCheck, RefreshCw, Zap } from 'lucide-react';
-
-**ObjectOS** 是堆栈的"操作系统"。ObjectQL 处理*数据*,而 ObjectOS 处理*控制*。
-
-它充当位于 API 和数据库驱动程序之间的中间件内核,确保每次数据访问都经过身份验证、授权并符合业务规则。
-
-## 架构组件
-
-```mermaid
-graph TD
- A[外部 API 请求] --> B(Host / Adapter Layer);
- B --> C{ObjectStack Kernel};
- C --> D[Plugin: Identity Provider];
- C --> E[Plugin: Authorization Engine];
- C --> F[ObjectQL Engine];
- F --> G[Schema Registry];
- F --> H[Driver Layer];
-```
-
-* **Host (Adapter)**: 适配不同的运行环境(Hono/Node, Next.js/Edge, Electron)。
-* **Kernel**: 核心控制器,负责加载插件、管理上下文。
-* **Plugins**: 可插拔的能力模块(如 Auth, Audit, Workflow)。
-* **ObjectQL**: 纯逻辑引擎,负责数据查询解析与验证。
-* **Driver**: 实际的 I/O 执行者。
diff --git a/content/docs/specifications/server/kernel-architecture.mdx b/content/docs/specifications/server/kernel-architecture.mdx
deleted file mode 100644
index 3a483d728..000000000
--- a/content/docs/specifications/server/kernel-architecture.mdx
+++ /dev/null
@@ -1,36 +0,0 @@
----
-title: Kernel Architecture
-description: The Design of the ObjectOS Kernel. The centralized engine for Identity, Security, and Sync.
----
-
-import { Cpu, ShieldCheck, RefreshCw, Zap } from 'lucide-react';
-
-**ObjectOS** is the "Operating System" of the stack. While ObjectQL deals with *Data*, ObjectOS deals with *Control*.
-
-It acts as a middleware kernel that sits between the API and the Database Driver, ensuring that every data access is authenticated, authorized, and compliant with business rules.
-
-## The Kernel Layers
-
-### 1. The Identity Layer (Who?)
-Before any logic runs, the Kernel resolves the actor.
-* **Authentication:** OIDC, SAML, or LDAP.
-* **Session Management:** Stateless JWT or Session Store.
-* **Context Injection:** Loading `userId`, `role`, and `organization` into the request context.
-
-### 2. The Policy Layer (Can they?)
-The Kernel enforces the **"Defense in Depth"** security model.
-* **Profile Check:** Does this user have license to use this App?
-* **Object Permission:** Can they `READ` the `Contract` object?
-* **Field Level Security (FLS):** Are they allowed to see `contract_value`?
-* **Sharing Rules:** Do they have access to *this specific record*?
-
-### 3. The Logic Layer (What happens?)
-This is the "Business Logic" container.
-* **Triggers:** Synchronous logic (`beforeInsert`).
-* **Flows:** Visual orchestration (`Approval Process`).
-* **Jobs:** Asynchronous tasks (`Send Email`).
-
-### 4. The Sync Layer (Where is it?)
-ObjectOS is designed for **Local-First** operation.
-* **Change Data Capture (CDC):** Tracking the "Delta" of every transaction.
-* **Replication:** Syncing these deltas to edge devices (SQLite) or data warehouses (Snowflake).
diff --git a/content/docs/specifications/server/meta.cn.json b/content/docs/specifications/server/meta.cn.json
deleted file mode 100644
index 661a1dafe..000000000
--- a/content/docs/specifications/server/meta.cn.json
+++ /dev/null
@@ -1,13 +0,0 @@
-{
- "title": "ObjectOS",
- "pages": [
- "kernel-architecture",
- "permission-governance",
- "workflow-engine",
- "automation-rules",
- "audit-compliance",
- "integration-etl",
- "rest-api",
- "plugin-manifest"
- ]
-}
diff --git a/content/docs/specifications/server/meta.json b/content/docs/specifications/server/meta.json
deleted file mode 100644
index 6fc6da8d4..000000000
--- a/content/docs/specifications/server/meta.json
+++ /dev/null
@@ -1,14 +0,0 @@
-{
- "title": "ObjectOS",
- "pages": [
- "index",
- "kernel-architecture",
- "permission-governance",
- "workflow-engine",
- "automation-rules",
- "audit-compliance",
- "integration-etl",
- "rest-api",
- "plugin-manifest"
- ]
-}
diff --git a/content/docs/specifications/server/permission-governance.mdx b/content/docs/specifications/server/permission-governance.mdx
deleted file mode 100644
index 9de4de892..000000000
--- a/content/docs/specifications/server/permission-governance.mdx
+++ /dev/null
@@ -1,36 +0,0 @@
----
-title: Permission Governance
-description: The specification for the 3-Layer Security Model.
----
-
-ObjectStack enforces a strict security model that cannot be bypassed by client-side code.
-
-## 1. Profiles & Permission Sets (Functional Access)
-Controls *what* a user can do.
-
-### Permission Set
-A collection of booleans and grants.
-* **Object Permissions:** `allow_read`, `allow_create`, `allow_edit`, `allow_delete`, `view_all`, `modify_all`.
-* **Field Permissions:** `read`, `edit` (per field).
-* **System Permissions:** `export_data`, `manage_users`.
-
-### Profile
-A user can only have **one** Profile (Base), but multiple Permission Sets (Extensions).
-
-## 2. Organization-Wide Defaults (OWD)
-Controls the *baseline* visibility of data.
-* **Private:** Users can only see records they own.
-* **Public Read Only:** Users can see everything, but only edit their own.
-* **Public Read/Write:** Open access.
-
-## 3. Sharing Rules (Record Access)
-Opens up access to specific subsets of data beyond the OWD.
-
-### Criteria-Based Sharing
-"Share all `Deals` where `Amount > 1M` with the `VP_Finance` role."
-
-### Manual Sharing
-Ad-hoc sharing of a single record (e.g., "Add John to the Sales Team for this deal").
-
-## 4. Territory Management
-A complex sharing model based on geometric or matrix hierarchies (e.g., "North America Sales" vs "Enterprise Sales").
diff --git a/content/docs/specifications/server/plugin-manifest.mdx b/content/docs/specifications/server/plugin-manifest.mdx
deleted file mode 100644
index b97e3a196..000000000
--- a/content/docs/specifications/server/plugin-manifest.mdx
+++ /dev/null
@@ -1,29 +0,0 @@
----
-title: Plugin Manifest
-description: The Standard for Extending the Kernel with Packages.
----
-
-ObjectStack is modular. The core kernel is minimal; everything else is a **Package**.
-
-## 1. The Package Protocol
-Configured via `package.service.yml`.
-
-```yaml
-name: @objectlabs/crm
-version: 1.2.0
-dependencies:
- - @objectlabs/core
-objects:
- - src/objects/*.object.yml
- - src/objects/leads/*.object.yml
-triggers:
- - src/triggers/*.trigger.ts
-```
-
-## 2. Metadata Deployment
-The Kernel supports a "Deploy" operation which takes a zipped package and applies it to the running instance idempotently.
-* **Diffing:** Only changes are applied.
-* **Destructive Changes:** Explicit `destructiveChanges.xml` required to delete metadata.
-
-## 3. Dependency Management
-Packages can depend on other packages. The Kernel enforces version compatibility and load order.
diff --git a/content/docs/specifications/server/rest-api.cn.mdx b/content/docs/specifications/server/rest-api.cn.mdx
deleted file mode 100644
index c2bc9d335..000000000
--- a/content/docs/specifications/server/rest-api.cn.mdx
+++ /dev/null
@@ -1,100 +0,0 @@
----
-title: REST API Protocol
-description: 标准 Data API 与 Metadata API 接口规范
----
-
-# REST API Protocol
-
-ObjectStack 遵循 "Protocol First" 原则,提供了一套标准化的 RESTful API,用于前端与 ObjectOS 内核进行交互。
-
-为了解决硬编码 URL 路径的问题,ObjectStack 引入了 **Discovery Protocol(发现协议)**。客户端应首先请求发现端点,获取当前环境的所有服务入口。
-
-## 1. Discovery (入口发现)
-
-客户端启动时(如 `App.init`),应首先请求此端点。
-
-- **Endpoint**: `GET /.well-known/objectstack` 或 `GET /api/v1/discovery`
-- **Response Type**: `DiscoveryResponse`
-
-```json
-{
- "name": "Acme CRM Production",
- "version": "1.0.0",
- "environment": "production",
- "routes": {
- "data": "/api/v1/data",
- "metadata": "/api/v1/meta",
- "auth": "/api/v1/auth",
- "actions": "/api/v1/actions",
- "storage": "/api/v1/storage",
- "graphql": "/api/v1/graphql"
- },
- "features": {
- "graphql": true,
- "search": true,
- "files": true
- },
- "locale": {
- "default": "zh-CN",
- "supported": ["en-US", "zh-CN"],
- "timezone": "Asia/Shanghai"
- }
-}
-```
-
-## 2. Standard Data API (数据操作)
-
-基于 `routes.data` 返回的基路径(默认为 `/api/v1/data`)。
-
-### 查询对象记录 (Query)
-
-- **Method**: `GET /:objectName`
-- **Params**:
- - `select`: 字段列表(逗号分隔)
- - `filter`: 过滤条件(JSON string, try `filters` in QuerySchema)
- - `sort`: 排序(如 `created_at desc`)
- - `page`: 页码
- - `pageSize`: 每页数量
-
-### 获取单条记录 (Retrieve)
-
-- **Method**: `GET /:objectName/:recordId`
-
-### 创建记录 (Create)
-
-- **Method**: `POST /:objectName`
-- **Body**: Record data object
-
-### 更新记录 (Update)
-
-- **Method**: `PATCH /:objectName/:recordId`
-- **Body**: Changed fields
-
-### 删除记录 (Delete)
-
-- **Method**: `DELETE /:objectName/:recordId`
-
-## 3. Standard Metadata API (元数据)
-
-基于 `routes.metadata` 返回的基路径(默认为 `/api/v1/meta`)。
-
-### 获取所有对象定义
-
-- **Method**: `GET /objects`
-- **Response**: List of `ObjectSchema` (summary)
-
-### 获取特定对象定义
-
-- **Method**: `GET /objects/:objectName`
-- **Response**: Full `ObjectSchema` (incl. fields, validation)
-
-### 获取应用导航菜单
-
-- **Method**: `GET /menus`
-- **Response**: `MenuItem[]`
-
-## 4. Custom API Endpoints
-
-开发者可以通过 `ApiEndpointSchema` 定义自定义的 API 接口,这些接口通常挂载在 `/api/v1/custom` 下或自定义路径。
-
-详见 [Custom API Guide](/docs/specifications/server/custom-api).
diff --git a/content/docs/specifications/server/rest-api.mdx b/content/docs/specifications/server/rest-api.mdx
deleted file mode 100644
index ce5f5db2d..000000000
--- a/content/docs/specifications/server/rest-api.mdx
+++ /dev/null
@@ -1,100 +0,0 @@
----
-title: REST API Protocol
-description: Standard Data API and Metadata API Specification
----
-
-# REST API Protocol
-
-ObjectStack follows the "Protocol First" principle, providing a set of standardized RESTful APIs for interaction between the frontend and the ObjectOS kernel.
-
-To solve the problem of hardcoded URL paths, ObjectStack introduces the **Discovery Protocol**, Clients should first request the discovery endpoint to obtain service entry points for the current environment.
-
-## 1. Discovery
-
-When the client starts (e.g., `App.init`), it should first request this endpoint.
-
-- **Endpoint**: `GET /.well-known/objectstack` or `GET /api/v1/discovery`
-- **Response Type**: `DiscoveryResponse`
-
-```json
-{
- "name": "Acme CRM Production",
- "version": "1.0.0",
- "environment": "production",
- "routes": {
- "data": "/api/v1/data",
- "metadata": "/api/v1/meta",
- "auth": "/api/v1/auth",
- "actions": "/api/v1/actions",
- "storage": "/api/v1/storage",
- "graphql": "/api/v1/graphql"
- },
- "features": {
- "graphql": true,
- "search": true,
- "files": true
- },
- "locale": {
- "default": "en-US",
- "supported": ["en-US", "zh-CN"],
- "timezone": "America/Los_Angeles"
- }
-}
-```
-
-## 2. Standard Data API
-
-Based on the base path returned by `routes.data` (default is `/api/v1/data`).
-
-### Query Objects (Query)
-
-- **Method**: `GET /:objectName`
-- **Params**:
- - `select`: List of fields (comma separated)
- - `filter`: Filter criteria (JSON string, see `filters` in QuerySchema)
- - `sort`: Sorting (e.g. `created_at desc`)
- - `page`: Page number
- - `pageSize`: Items per page
-
-### Get Single Record (Retrieve)
-
-- **Method**: `GET /:objectName/:recordId`
-
-### Create Record (Create)
-
-- **Method**: `POST /:objectName`
-- **Body**: Record data object
-
-### Update Record (Update)
-
-- **Method**: `PATCH /:objectName/:recordId`
-- **Body**: Changed fields
-
-### Delete Record (Delete)
-
-- **Method**: `DELETE /:objectName/:recordId`
-
-## 3. Standard Metadata API
-
-Based on the base path returned by `routes.metadata` (default is `/api/v1/meta`).
-
-### Get All Object Definitions
-
-- **Method**: `GET /objects`
-- **Response**: List of `ObjectSchema` (summary)
-
-### Get Specific Object Definition
-
-- **Method**: `GET /objects/:objectName`
-- **Response**: Full `ObjectSchema` (incl. fields, validation)
-
-### Get App Navigation Menus
-
-- **Method**: `GET /menus`
-- **Response**: `MenuItem[]`
-
-## 4. Custom API Endpoints
-
-Developers can define custom API interfaces via `ApiEndpointSchema`, which are typically mounted under `/api/v1/custom` or a custom path.
-
-See [Custom API Guide](/docs/specifications/server/custom-api).
diff --git a/content/docs/specifications/server/workflow-engine.mdx b/content/docs/specifications/server/workflow-engine.mdx
deleted file mode 100644
index cf59df0fe..000000000
--- a/content/docs/specifications/server/workflow-engine.mdx
+++ /dev/null
@@ -1,29 +0,0 @@
----
-title: Workflow Engine
-description: The Protocol for Long-Running Processes and State Machines.
----
-
-The Workflow Engine manages stateful business processes.
-
-## 1. Flows
-A Flow is a directed graph of steps.
-* **Screen Flow:** Interactive wizard (with UI).
-* **Auto-Launched Flow:** Background process (No UI).
-
-## 2. Process Elements
-
-### Logic Nodes
-* **Decision:** Branching based on variables.
-* **Loop:** Iterate over a collection.
-* **Wait:** Pause execution until a time or event.
-
-### Data Nodes
-* **Get Records:** Query ObjectQL.
-* **Create/Update Records:** Mutate ObjectQL.
-
-### Interaction Nodes
-* **Screen:** Render a form (in Screen Flows).
-* **Action:** Call an Email, Slack, or Apex Action.
-
-## 3. State Management
-The Engine persists the state of every running flow instance, allowing for "Long-Running" processes that can pause for days (e.g., waiting for Approval).
diff --git a/content/docs/specifications/ui/action-triggers.mdx b/content/docs/specifications/ui/action-triggers.mdx
deleted file mode 100644
index ec36327c2..000000000
--- a/content/docs/specifications/ui/action-triggers.mdx
+++ /dev/null
@@ -1,39 +0,0 @@
----
-title: Action Triggers
-description: How user interactions trigger Server-Side logic or Client-Side transitions.
----
-
-Actions are the verbs of the system (Save, Submit, Approve).
-
-## 1. Action Types
-
-### Standard Actions
-Built-in CRUD operations.
-* `standard_new`
-* `standard_edit`
-* `standard_delete`
-
-### Flow Actions
-Launches a Screen Flow (Wizard).
-* **Target:** `flow:approval_wizard`
-* **Input:** Passes current `recordId`.
-
-### API Actions
-Calls a REST endpoint directly.
-* **Target:** `api:sync_with_erp`
-* **Feedback:** Shows toast message on success/failure.
-
-### URL Actions
-Navigates to an external link.
-* **Target:** `url:https://google.com?q={name}`
-
-## 2. Parameter Mapping
-You can map context data to action parameters.
-
-```yaml
-actions:
- - name: google_search
- label: Search on Google
- type: url
- url: "https://google.com/search?q={name}"
-```
diff --git a/content/docs/specifications/ui/component-schema.mdx b/content/docs/specifications/ui/component-schema.mdx
deleted file mode 100644
index 4317a426d..000000000
--- a/content/docs/specifications/ui/component-schema.mdx
+++ /dev/null
@@ -1,34 +0,0 @@
----
-title: Component Schema
-description: The Standard Component Library definitions embedded in ObjectUI.
----
-
-The Component Schema defines the available "Lego Blocks" that can be used to construct a page.
-
-## 1. Field Components
-These render individual data points.
-* `input`: Text inputs.
-* `textarea`: Multi-line text.
-* `select`: Dropdowns.
-* `lookup`: Modal search or combobox.
-* `boolean`: Checkboxes or toggles.
-
-## 2. Container Components
-These organize layout.
-* `section`: Collapsible accordion.
-* `tabs`: Tabbed interface.
-* `card`: Box with header and footer.
-* `grid`: Columnar layout system.
-
-## 3. Data Components
-These render collections of data.
-* `list_view`: Standard data table.
-* `kanban`: Drag-and-drop board.
-* `calendar`: Event view.
-* `chart`: Visualizations.
-
-## 4. Action Components
-These trigger logic.
-* `button`: Standard click action.
-* `menu_item`: Dropdown action.
-* `smart_action`: AI-suggested next step.
diff --git a/content/docs/specifications/ui/index.mdx b/content/docs/specifications/ui/index.mdx
deleted file mode 100644
index b5b2a0ed1..000000000
--- a/content/docs/specifications/ui/index.mdx
+++ /dev/null
@@ -1,278 +0,0 @@
----
-title: UI Protocol (ObjectUI)
-description: Comprehensive specification for the ObjectStack UI Layer - server-driven UI definitions and rendering.
----
-
-import { Layout, Monitor, Palette, Zap } from 'lucide-react';
-
-The **UI Protocol (ObjectUI)** defines how user interfaces are expressed as metadata. Instead of hardcoding React/Vue components, you define UI as JSON configurations that renderers interpret.
-
-## Core Concept: Server-Driven UI (SDUI)
-
-```
-Traditional: Code UI → Build → Deploy → Update Requires Rebuild
-ObjectUI: Define JSON → Instant Update → No Rebuild Needed
-```
-
-## Core Components
-
-
- }
- title="SDUI Protocol"
- href="/docs/specifications/ui/sdui-protocol"
- description="Server-Driven UI architecture and philosophy"
- />
- }
- title="Component Schema"
- href="/docs/specifications/ui/component-schema"
- description="How UI components are defined and composed"
- />
- }
- title="View Protocol"
- href="/docs/specifications/ui/view-protocol"
- description="List views, forms, and data visualization"
- />
- }
- title="Layout System"
- href="/docs/specifications/ui/layout-system"
- description="Grid-based responsive layout engine"
- />
-
-
-## Specifications
-
-### View Types
-
-1. **[SDUI Protocol](/docs/specifications/ui/sdui-protocol)**
- - Server-Driven UI philosophy
- - JSON-based component definitions
- - Renderer architecture
-
-2. **[View Protocol](/docs/specifications/ui/view-protocol)**
- - ListView (Grid, Kanban, Calendar, Gantt)
- - FormView (Simple, Tabbed, Wizard)
- - DetailView (Record pages)
-
-3. **[Component Schema](/docs/specifications/ui/component-schema)**
- - Button, Input, Select components
- - Custom component registration
- - Component props and events
-
-### Layout & Styling
-
-4. **[Layout System](/docs/specifications/ui/layout-system)**
- - Grid-based layouts
- - Responsive breakpoints
- - Flexbox patterns
-
-5. **[Action Triggers](/docs/specifications/ui/action-triggers)**
- - Button actions
- - URL navigation
- - Flow launches
- - Custom actions
-
-### Analytics & Reporting
-
-6. **[Report Template](/docs/specifications/ui/report-template)**
- - Report types (Tabular, Summary, Matrix)
- - Chart configurations
- - Dashboard widgets
-
-## View Types Overview
-
-### ListView
-
-Display collections of records in various formats:
-
-```typescript
-ListView.create({
- viewType: 'grid', // or 'kanban' | 'calendar' | 'gantt'
- columns: [...],
- filters: {...},
- sorting: [...],
-});
-```
-
-**Supported View Types:**
-- **Grid:** Traditional table with sorting, filtering, pagination
-- **Kanban:** Drag-and-drop board with swimlanes
-- **Calendar:** Timeline view with date-based events
-- **Gantt:** Project timeline with dependencies
-
-### FormView
-
-Edit individual records with custom layouts:
-
-```typescript
-FormView.create({
- layout: {
- sections: [
- {
- label: 'Basic Info',
- columns: 2,
- fields: ['name', 'email'],
- },
- ],
- },
-});
-```
-
-**Features:**
-- Multi-section layouts
-- Conditional field visibility
-- Read-only fields
-- Custom validation
-
-### Dashboard
-
-Compose widgets for analytics:
-
-```typescript
-Dashboard.create({
- layout: {
- rows: [
- {
- widgets: [
- Widget.metric({ ... }),
- Widget.chart({ ... }),
- ],
- },
- ],
- },
-});
-```
-
-**Widget Types:**
-- Metric cards (KPIs)
-- Charts (Bar, Line, Pie, etc.)
-- Embedded list views
-- Custom widgets
-
-## Theming System
-
-ObjectUI includes a comprehensive theming system:
-
-```typescript
-Theme.create({
- colors: {
- primary: '#3B82F6',
- secondary: '#8B5CF6',
- },
- typography: {
- fontFamily: 'Inter, sans-serif',
- },
- spacing: {
- unit: 8, // 8px grid
- },
-});
-```
-
-**Customizable:**
-- Color palettes
-- Typography (fonts, sizes, weights)
-- Spacing and sizing
-- Border radius
-- Shadows
-- Z-index layers
-
-## Navigation
-
-Define app navigation structure:
-
-```typescript
-App.create({
- navigation: [
- NavigationItem.object({ label: 'Tasks', object: 'task' }),
- NavigationItem.dashboard({ label: 'Home', dashboard: 'overview' }),
- NavigationItem.group({
- label: 'Reports',
- items: [...],
- }),
- ],
-});
-```
-
-## Design Principles
-
-### 1. Declarative Over Imperative
-
-```typescript
-// ❌ Imperative (React)
-function TaskList() {
- const [tasks, setTasks] = useState([]);
- useEffect(() => { /* fetch */ }, []);
- return ;
-}
-
-// ✅ Declarative (ObjectUI)
-ListView.create({
- object: 'task',
- columns: [{ field: 'title' }],
-});
-```
-
-### 2. Configuration Over Code
-
-UI changes should not require rebuilding:
-
-```
-Change Config → Refresh Page → New UI ✅
-Change Code → Rebuild → Redeploy → New UI ❌
-```
-
-### 3. Responsive by Default
-
-All layouts use a 12-column grid system that adapts to screen size:
-
-```typescript
-Widget.metric({
- width: 12, // Mobile: Full width
- // Tablet: Auto-adjust
- // Desktop: 1/4 width
-});
-```
-
-### 4. Accessible by Default
-
-WCAG 2.1 AA compliance out of the box:
-- Keyboard navigation
-- Screen reader support
-- Color contrast ratios
-- Focus indicators
-
-## Renderer Implementations
-
-ObjectUI is a protocol. Multiple renderers can implement it:
-
-| Renderer | Status | Platform |
-| :--- | :--- | :--- |
-| `@objectstack/react-renderer` | 🚧 In Progress | Web (React) |
-| `@objectstack/vue-renderer` | 📋 Planned | Web (Vue) |
-| `@objectstack/flutter-renderer` | 📋 Planned | Mobile (Flutter) |
-| `@objectstack/native-renderer` | 📋 Planned | Mobile (React Native) |
-
-## Quick Links
-
-### For Implementers
-
-Building a renderer for ObjectUI? Start here:
-- [Renderer Interface](/docs/references/ui/Renderer)
-- [Component Registry](/docs/guides/custom-components)
-- [Test Suite](/docs/guides/renderer-testing)
-
-### For Users
-
-Using ObjectUI to build interfaces? See:
-- [View Configuration Guide](/docs/guides/view-configuration)
-- [Theming Guide](/docs/guides/theming)
-- [Dashboard Examples](/docs/specifications/ui/dashboard)
-
-## Related Documentation
-
-- **[Data Protocol](/docs/specifications/data/architecture)** - How to query data
-- **[System Protocol](/docs/specifications/server/kernel-architecture)** - Runtime environment
-- **[UI Reference](/docs/references/ui/views/View)** - Complete API reference
diff --git a/content/docs/specifications/ui/layout-system.mdx b/content/docs/specifications/ui/layout-system.mdx
deleted file mode 100644
index a7a5c1616..000000000
--- a/content/docs/specifications/ui/layout-system.mdx
+++ /dev/null
@@ -1,39 +0,0 @@
----
-title: Layout System
-description: Understanding the flexible grid and region-based layout engine of ObjectUI.
----
-
-ObjectUI uses a responsive, region-based layout system that adapts to screen size.
-
-## 1. Page Templates
-Top-level structures that define the macro-layout.
-
-### Standard Template
-* **Header:** Title, Actions, Highlights.
-* **Main:** The primary content.
-* **Sidebar:** Secondary widgets.
-
-### Console Template
-Optimized for high-density work.
-* **Split View:** List on left, Detail on right.
-* **Sub-tabs:** Multiple records open at once.
-
-## 2. Flex Grid
-Within a region, components are arranged using a 12-column grid system.
-
-```json
-{
- "type": "grid",
- "columns": 2,
- "children": [
- { "span": 1, "component": "field_name" },
- { "span": 1, "component": "field_status" }
- ]
-}
-```
-
-## 3. Responsive Rules
-Procotol allows defining visibility rules based on device type.
-
-* `formFactor: "Large"` (Desktop)
-* `formFactor: "Small"` (Mobile)
diff --git a/content/docs/specifications/ui/meta.cn.json b/content/docs/specifications/ui/meta.cn.json
deleted file mode 100644
index 609d4c55b..000000000
--- a/content/docs/specifications/ui/meta.cn.json
+++ /dev/null
@@ -1,11 +0,0 @@
-{
- "title": "ObjectUI",
- "pages": [
- "sdui-protocol",
- "component-schema",
- "view-protocol",
- "layout-system",
- "action-triggers",
- "report-template"
- ]
-}
diff --git a/content/docs/specifications/ui/meta.json b/content/docs/specifications/ui/meta.json
deleted file mode 100644
index 5718e2700..000000000
--- a/content/docs/specifications/ui/meta.json
+++ /dev/null
@@ -1,12 +0,0 @@
-{
- "title": "ObjectUI",
- "pages": [
- "index",
- "sdui-protocol",
- "component-schema",
- "view-protocol",
- "layout-system",
- "action-triggers",
- "report-template"
- ]
-}
diff --git a/content/docs/specifications/ui/report-template.mdx b/content/docs/specifications/ui/report-template.mdx
deleted file mode 100644
index 891b4c357..000000000
--- a/content/docs/specifications/ui/report-template.mdx
+++ /dev/null
@@ -1,25 +0,0 @@
----
-title: Report Template
-description: Specification for Analytics Visualization and Reporting Layouts.
----
-
-Reports in ObjectStack are just another type of View.
-
-## 1. Report Definitions
-Defined in JSON/YAML, similar to Objects.
-
-```yaml
-type: report
-dataset: opportunity_analysis
-chart:
- type: bar
- x_axis: close_date
- y_axis: amount
-table:
- columns: [name, account, amount, stage]
- grouping: [account]
-```
-
-## 2. Dashboard Layout
-A Dashboard is a page containing multiple Report Widgets.
-Reference `Layout System` for grid structure.
diff --git a/content/docs/specifications/ui/sdui-protocol.cn.mdx b/content/docs/specifications/ui/sdui-protocol.cn.mdx
deleted file mode 100644
index 5b05fc063..000000000
--- a/content/docs/specifications/ui/sdui-protocol.cn.mdx
+++ /dev/null
@@ -1,54 +0,0 @@
----
-title: SDUI 协议
-description: 服务器驱动 UI 架构。ObjectStack 如何将"界面作为数据"来实现无限定制。
----
-
-import { LayoutTemplate, Layers, Blocks, Smartphone } from 'lucide-react';
-
-**ObjectUI** 是视图层规范。它建立在**服务器驱动 UI(SDUI)**的原则之上。
-
-在传统的前端中,布局在 React/Vue 组件中硬编码(``)。
-在 ObjectStack 中,前端是一个通用**渲染器**。它从服务器下载 JSON 布局定义并即时绘制。
-
-## UI 管道
-
-### 1. 布局请求
-客户端询问:*"给我编辑发票 #1024 的表单"*。
-```http
-GET /api/v4/ui/layouts/invoice/edit
-```
-
-### 2. 解析引擎
-服务器提供布局,合并三层定制:
-1. **基础协议:** 在 `invoice.object.yml` 中定义的默认字段。
-2. **管理员配置:** 通过页面构建器添加的自定义部分和字段。
-3. **用户偏好:** 用户个性化的列宽和隐藏字段。
-
-### 3. 布局 JSON(响应)
-服务器响应组件树描述,而不是 HTML。
-```json
-{
- "type": "page",
- "layout": "two_column",
- "regions": {
- "main": [
- { "type": "field_group", "label": "Basics", "children": ["name", "date"] },
- { "type": "related_list", "object": "invoice_line", "label": "Line Items" }
- ],
- "sidebar": [
- { "type": "widget", "component": "approval_history" }
- ]
- }
-}
-```
-
-### 4. 渲染器(客户端)
-通用 `PageRenderer` 组件遍历此 JSON 并实例化映射的组件(`FieldGroup`、`RelatedList`、`Widget`)。
-
----
-
-## 为什么选择 SDUI?
-
-1. **即时更新:** 在 Schema 中更改字段标签或移动部分,每个用户(Web、移动、外部门户)都会立即看到它,无需应用更新。
-2. **平台原生:** 相同的 JSON 可以在 React 中渲染为 DOM 节点,在 SwiftUI/Kotlin 中渲染为原生视图,或在 TUI 中渲染为命令行。
-3. **个性化:** 因为布局是按请求生成的,我们可以根据用户的角色或记录的状态隐藏整个部分(例如,如果状态为"草稿",则隐藏"批准"按钮)。
diff --git a/content/docs/specifications/ui/sdui-protocol.mdx b/content/docs/specifications/ui/sdui-protocol.mdx
deleted file mode 100644
index 5c0fc3606..000000000
--- a/content/docs/specifications/ui/sdui-protocol.mdx
+++ /dev/null
@@ -1,54 +0,0 @@
----
-title: SDUI Protocol
-description: The Server-Driven UI Architecture. How ObjectStack treats "Interface as Data" to deliver infinite customization.
----
-
-import { LayoutTemplate, Layers, Blocks, Smartphone } from 'lucide-react';
-
-**ObjectUI** is the View Layer specification. It is built on the principle of **Server-Driven UI (SDUI)**.
-
-In a traditional frontend, the layout is hardcoded in React/Vue components (``).
-In ObjectStack, the frontend is a generic **Renderer**. It downloads a JSON layout definition from the server and paints it on the fly.
-
-## The UI Pipeline
-
-### 1. The Layout Request
-The client asks: *"Give me the form for editing Invoice #1024"*.
-```http
-GET /api/v4/ui/layouts/invoice/edit
-```
-
-### 2. The Resolution Engine
-The server provides the layout, merging three layers of customization:
-1. **Base Protocol:** The default fields defined in `invoice.object.yml`.
-2. **Admin Config:** Custom sections and fields added via the Page Builder.
-3. **User Preference:** Column widths and hidden fields personalized by the user.
-
-### 3. The Layout JSON (The Response)
-The server responds with a component tree description, not HTML.
-```json
-{
- "type": "page",
- "layout": "two_column",
- "regions": {
- "main": [
- { "type": "field_group", "label": "Basics", "children": ["name", "date"] },
- { "type": "related_list", "object": "invoice_line", "label": "Line Items" }
- ],
- "sidebar": [
- { "type": "widget", "component": "approval_history" }
- ]
- }
-}
-```
-
-### 4. The Renderer (The Client)
-The generic `PageRenderer` component traverses this JSON and instantiates the mapped components (`FieldGroup`, `RelatedList`, `Widget`).
-
----
-
-## Why SDUI?
-
-1. **Instant Updates:** Change a field label or move a section in the Schema, and every user (Web, Mobile, External Portal) sees it instantly without an app update.
-2. **Platform Native:** The same JSON can be rendered as DOM nodes in React, native Views in SwiftUI/Kotlin, or command lines in a TUI.
-3. **Personalization:** Because the layout is generated per-request, we can hide entire sections based on the user's role or the record's status (e.g., Hide "Approve" button if status is "Draft").
diff --git a/content/docs/specifications/ui/view-protocol.mdx b/content/docs/specifications/ui/view-protocol.mdx
deleted file mode 100644
index af28b76a5..000000000
--- a/content/docs/specifications/ui/view-protocol.mdx
+++ /dev/null
@@ -1,43 +0,0 @@
----
-title: View Protocol
-description: Specification for List Views, Form Views, and Related Lists.
----
-
-A "View" in ObjectStack is a preset configuration for displaying data.
-
-## 1. List Views
-Defines how to display a collection of records.
-
-```yaml
-# all_active_projects.listview.yml
-name: all_active
-object: project
-label: All Active Projects
-filter:
- - ["status", "=", "Active"]
-columns:
- - name
- - manager
- - due_date
- - status
-sort: due_date desc
-```
-
-## 2. Form Views
-Defines the layout for creating or editing a single record.
-
-### Modes
-* **Edit:** Standard input form.
-* **Read:** Read-only detail view.
-* **Create:** Simplified creation wizard.
-
-## 3. Related Lists
-Embeds a List View of child records inside a parent record's Detail View.
-
-```yaml
-# In project.page.yml
-- type: related_list
- object: project_task
- relation_field: project_id
- columns: [subject, priority, status]
-```
diff --git a/docs-structure-proposal.md b/docs-structure-proposal.md
new file mode 100644
index 000000000..f2979db99
--- /dev/null
+++ b/docs-structure-proposal.md
@@ -0,0 +1,90 @@
+# ObjectStack Protocol Docs Structure Proposal
+
+Based on the audit of existing content and the "Metamodel Standards," here is the recommended structure for the official documentation.
+
+## 1. High-Level Goals
+- **Eliminate Redundancy**: Merge `concepts`, `core-concepts`, `specifications`, and `protocols` into a unified hierarchy.
+- **Align with Architecture**: Structure explicitly around the three pillars: **ObjectQL (Data)**, **ObjectUI (UI)**, and **ObjectOS (System)**.
+- **Reference-Driven**: Ensure documentation maps directly to the Zod schemas (`field.zod.ts`, `view.zod.ts`, etc.).
+
+## 2. Proposed Directory Structure
+
+```text
+content/docs/
+├── index.mdx (Landing Page)
+├── introduction/ (Was: concepts, core-concepts)
+│ ├── index.mdx
+│ ├── manifesto.mdx (From concepts/manifesto.mdx)
+│ ├── architecture.mdx (From core-concepts/the-stack.mdx)
+│ ├── metadata-driven.mdx (From core-concepts/metadata-driven.mdx)
+│ └── terminology.mdx
+├── objectql/ (The Data Protocol)
+│ ├── index.mdx (Overview)
+│ ├── schema/
+│ │ ├── object.mdx (Maps to src/data/object.zod.ts)
+│ │ ├── field.mdx (Maps to src/data/field.zod.ts)
+│ │ ├── validation.mdx
+│ │ └── relationships.mdx
+│ ├── query/
+│ │ ├── index.mdx (Query syntax)
+│ │ └── drivers.mdx
+│ └── flow/
+│ └── logic.mdx (Maps to src/data/flow.zod.ts)
+├── objectui/ (The UI Protocol)
+│ ├── index.mdx
+│ ├── app.mdx (Maps to src/ui/app.zod.ts)
+│ ├── views/
+│ │ ├── index.mdx
+│ │ ├── list-view.mdx (Maps to src/ui/view.zod.ts)
+│ │ └── form-view.mdx
+│ ├── components/ (Widgets, Dashboard)
+│ └── actions.mdx (Maps to src/ui/action.zod.ts)
+├── objectos/ (The System Protocol)
+│ ├── index.mdx
+│ ├── manifest.mdx (Maps to src/system/manifest.zod.ts)
+│ ├── authentication.mdx
+│ ├── api-reference.mdx (Maps to src/system/api.zod.ts)
+│ └── plugins.mdx
+└── developers/ (Guides & Tooling)
+ ├── quick-start.mdx
+ ├── cli.mdx
+ ├── testing.mdx
+ └── extensions.mdx
+```
+
+## 3. Detailed Actions
+
+### A. Cleanup & Consolidation
+1. **Delete** `content/docs/specifications` folder (content is redundant with `protocols`).
+2. **Delete** `content/docs/core-concepts` folder (move unique content to `introduction`).
+3. **Archive** `content/docs/concepts` folder (it contains a flat list of protocols; move content to specific `object*` folders and then remove).
+
+### B. Rename & Move
+1. Rename `content/docs/protocols` -> Explode this.
+ * Move `content/docs/protocols/objectql` -> `content/docs/objectql`
+ * Move `content/docs/protocols/objectui` -> `content/docs/objectui`
+ * Move `content/docs/protocols/objectos` -> `content/docs/objectos`
+ * *Reason*: These are the top-level products/protocols. They deserve root-level visibility in the docs URI (e.g., `docs/objectql/schema`).
+
+### C. Navigation Update (`meta.json`)
+Update `content/docs/meta.json` to reflect the new simplified hierarchy:
+
+```json
+{
+ "title": "Documentation",
+ "pages": [
+ "introduction",
+ "objectql",
+ "objectui",
+ "objectos",
+ "developers",
+ "references"
+ ]
+}
+```
+
+## 4. Content Gaps to Fill
+Based on `copilot-instructions.md`, ensure the following specific pages exist and map to their Zod definitions:
+- [ ] **ObjectQL**: Ensure `field.mdx` documents all types (text, lookup, formula) defined in `field.zod.ts`.
+- [ ] **ObjectUI**: Ensure `layout.mdx` covers the Grid/Kanban options defined in `view.zod.ts`.
+- [ ] **ObjectOS**: Ensure `manifest.mdx` clearly documents `objectstack.config.ts`.
From 9f4fae163137e893cd135028ef62c86e5e505650 Mon Sep 17 00:00:00 2001
From: Jack Zhuang <50353452+hotlong@users.noreply.github.com>
Date: Mon, 26 Jan 2026 21:31:40 +0800
Subject: [PATCH 08/22] Clean up meta.json files and update build-docs script
Removed unnecessary whitespace and the 'root' property from protocol meta.json files. Also removed the 'order' property from the root meta.json and updated the build-docs script to reflect these changes for consistency and clarity in documentation structure.
---
content/docs/references/auth/meta.json | 1 -
content/docs/references/automation/meta.json | 1 -
content/docs/references/data/meta.json | 1 -
content/docs/references/driver/meta.json | 1 -
content/docs/references/hub/meta.json | 1 -
content/docs/references/kernel/meta.json | 1 -
content/docs/references/permission/meta.json | 1 -
content/docs/references/system/meta.json | 1 -
content/docs/references/ui/meta.json | 1 -
packages/spec/scripts/build-docs.ts | 3 +--
10 files changed, 1 insertion(+), 11 deletions(-)
diff --git a/content/docs/references/auth/meta.json b/content/docs/references/auth/meta.json
index 0f5a885d0..2c7a0bddc 100644
--- a/content/docs/references/auth/meta.json
+++ b/content/docs/references/auth/meta.json
@@ -1,6 +1,5 @@
{
"title": "Auth Protocol",
-
"pages": [
"config",
"identity",
diff --git a/content/docs/references/automation/meta.json b/content/docs/references/automation/meta.json
index c3c7324c9..cf59844b6 100644
--- a/content/docs/references/automation/meta.json
+++ b/content/docs/references/automation/meta.json
@@ -1,6 +1,5 @@
{
"title": "Automation Protocol",
-
"pages": [
"flow",
"webhook",
diff --git a/content/docs/references/data/meta.json b/content/docs/references/data/meta.json
index e8ddf6160..6b613d272 100644
--- a/content/docs/references/data/meta.json
+++ b/content/docs/references/data/meta.json
@@ -1,6 +1,5 @@
{
"title": "Data Protocol",
-
"pages": [
"dataset",
"field",
diff --git a/content/docs/references/driver/meta.json b/content/docs/references/driver/meta.json
index 1c4cfef06..3e600a52a 100644
--- a/content/docs/references/driver/meta.json
+++ b/content/docs/references/driver/meta.json
@@ -1,6 +1,5 @@
{
"title": "Driver Protocol",
-
"pages": [
"datasource",
"driver",
diff --git a/content/docs/references/hub/meta.json b/content/docs/references/hub/meta.json
index 22c0988fc..e3a0b24fb 100644
--- a/content/docs/references/hub/meta.json
+++ b/content/docs/references/hub/meta.json
@@ -1,6 +1,5 @@
{
"title": "Hub Protocol",
-
"pages": [
"composer",
"license",
diff --git a/content/docs/references/kernel/meta.json b/content/docs/references/kernel/meta.json
index 2fbbaef1e..671c71a79 100644
--- a/content/docs/references/kernel/meta.json
+++ b/content/docs/references/kernel/meta.json
@@ -1,6 +1,5 @@
{
"title": "Kernel Protocol",
-
"pages": [
"context",
"logger",
diff --git a/content/docs/references/permission/meta.json b/content/docs/references/permission/meta.json
index 8fb5e622d..bbd9ada65 100644
--- a/content/docs/references/permission/meta.json
+++ b/content/docs/references/permission/meta.json
@@ -1,6 +1,5 @@
{
"title": "Permission Protocol",
-
"pages": [
"permission",
"sharing",
diff --git a/content/docs/references/system/meta.json b/content/docs/references/system/meta.json
index 94222d72a..e808b79d6 100644
--- a/content/docs/references/system/meta.json
+++ b/content/docs/references/system/meta.json
@@ -1,6 +1,5 @@
{
"title": "System Protocol",
-
"pages": [
"audit",
"events",
diff --git a/content/docs/references/ui/meta.json b/content/docs/references/ui/meta.json
index 151a5ad98..5e08646e6 100644
--- a/content/docs/references/ui/meta.json
+++ b/content/docs/references/ui/meta.json
@@ -1,6 +1,5 @@
{
"title": "UI Protocol",
-
"pages": [
"action",
"app",
diff --git a/packages/spec/scripts/build-docs.ts b/packages/spec/scripts/build-docs.ts
index 2df5b7ccc..bcb81120b 100644
--- a/packages/spec/scripts/build-docs.ts
+++ b/packages/spec/scripts/build-docs.ts
@@ -168,7 +168,6 @@ Object.entries(CATEGORIES).forEach(([key, title]) => {
// Create top-level meta.json for the protocol
const meta: any = {
title,
- root: true // Mark as root to display folders nicely
};
// Sort zod files alphabetically for consistent ordering
@@ -232,7 +231,7 @@ Object.keys(CATEGORIES).forEach(category => {
// We want references to list categories in specific order
const rootMetaProps = {
label: "Protocol Reference",
- order: 100,
+ root: true,
pages: [
"data",
"ui",
From 2009b9412504bd7be78b39cf62a9417797a93180 Mon Sep 17 00:00:00 2001
From: Jack Zhuang <50353452+hotlong@users.noreply.github.com>
Date: Mon, 26 Jan 2026 21:52:16 +0800
Subject: [PATCH 09/22] Add Layout import to Action Protocol documentation
---
content/docs/objectui/actions.mdx | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/content/docs/objectui/actions.mdx b/content/docs/objectui/actions.mdx
index 8f239305c..e3d3722fa 100644
--- a/content/docs/objectui/actions.mdx
+++ b/content/docs/objectui/actions.mdx
@@ -3,7 +3,7 @@ title: Action Protocol
description: Buttons, triggers, navigation, and user interaction definitions
---
-import { MousePointer, Zap, ExternalLink, Workflow, GitBranch, Play, Component } from 'lucide-react';
+import { MousePointer, Zap, ExternalLink, Workflow, GitBranch, Play, Component, Layout } from 'lucide-react';
# Action Protocol: Defining User Interactions
From 8cf2590f6da066c47548bab551f02444500c12ff Mon Sep 17 00:00:00 2001
From: Jack Zhuang <50353452+hotlong@users.noreply.github.com>
Date: Mon, 26 Jan 2026 22:00:50 +0800
Subject: [PATCH 10/22] Update docs navigation and homepage links
Updated internal documentation links in the homepage and hero section to reflect new URL structure and improved navigation. Revised the main docs index to focus on the three core ObjectStack protocols, streamlined resource cards, and removed outdated quick links and module descriptions for clarity.
---
apps/docs/app/[lang]/page.tsx | 18 +++---
apps/docs/components/hero-section.tsx | 6 --
content/docs/index.mdx | 90 +++++++++------------------
3 files changed, 38 insertions(+), 76 deletions(-)
diff --git a/apps/docs/app/[lang]/page.tsx b/apps/docs/app/[lang]/page.tsx
index 864e36453..472339154 100644
--- a/apps/docs/app/[lang]/page.tsx
+++ b/apps/docs/app/[lang]/page.tsx
@@ -38,37 +38,37 @@ export default async function HomePage({
}
title={t.features.objectql.title}
- href="/docs/specifications/data/architecture"
+ href="/docs/objectql"
description={t.features.objectql.description}
/>
}
title={t.features.objectui.title}
- href="/docs/specifications/ui/sdui-protocol"
+ href="/docs/objectui"
description={t.features.objectui.description}
/>
}
title={t.features.objectos.title}
- href="/docs/specifications/server/kernel-architecture"
+ href="/docs/objectos"
description={t.features.objectos.description}
/>
}
title={t.features.security.title}
- href="/docs/specifications/server/permission-governance"
+ href="/docs/objectql/security"
description={t.features.security.description}
/>
}
title={t.features.zodFirst.title}
- href="/docs/specifications/data/schema-definition"
+ href="/docs/objectql/schema"
description={t.features.zodFirst.description}
/>
}
title={t.features.universal.title}
- href="/docs/concepts/architecture"
+ href="/docs/introduction/architecture"
description={t.features.universal.description}
/>
@@ -83,21 +83,21 @@ export default async function HomePage({
icon={}
title={t.personas.architect.title}
description={t.personas.architect.description}
- href="/docs/concepts/enterprise-patterns"
+ href="/docs/introduction/architecture"
action={t.personas.architect.action}
/>
}
title={t.personas.aiEngineer.title}
description={t.personas.aiEngineer.description}
- href="/docs/concepts/ai-codex"
+ href="/docs/introduction/metadata-driven"
action={t.personas.aiEngineer.action}
/>
}
title={t.personas.frameworkBuilder.title}
description={t.personas.frameworkBuilder.description}
- href="/docs/specifications/data/architecture"
+ href="/docs/developers"
action={t.personas.frameworkBuilder.action}
/>
diff --git a/apps/docs/components/hero-section.tsx b/apps/docs/components/hero-section.tsx
index 8133cbc2b..2d8ba3bee 100644
--- a/apps/docs/components/hero-section.tsx
+++ b/apps/docs/components/hero-section.tsx
@@ -51,12 +51,6 @@ export function HeroSection({ badge, title, subtitle, cta, className }: HeroSect
{/* CTA Buttons */}
-
- {cta.primary}
-
}
- title="Quick Start"
- href="/docs/quick-start"
- description="Get started in under 5 minutes. Choose your learning path based on your role."
- />
- }
- title="Tutorials"
- href="/docs/tutorials"
- description="Hands-on step-by-step tutorials to build real applications and learn by doing."
+ icon={}
+ title="ObjectQL"
+ href="/docs/objectql"
+ description="The Data Protocol. Define your Data Model (Objects, Fields) and query it abstractly."
/>
}
- title="Concepts"
- href="/docs/concepts/manifesto"
- description="Understand the philosophy of 'Intent over Implementation' and the 'Local-First' architecture."
+ icon={}
+ title="ObjectUI"
+ href="/docs/objectui"
+ description="The UI Protocol. Define your User Interfaces (Views, Actions) as pure data."
/>
}
- title="Specifications"
- href="/docs/specifications"
- description="The Architecture Blueprints. Deep dive into ObjectQL (Data), ObjectUI (View), and ObjectOS (Control)."
+ icon={}
+ title="ObjectOS"
+ href="/docs/objectos"
+ description="The System Protocol. The Kernel that handles Identity, Transport, and Plugins."
/>
-## Additional Resources
+## Getting Started
}
- title="Developer Guides"
- href="/docs/guides/getting-started"
- description="Comprehensive guides for building with ObjectStack. Field types, views, workflows, and more."
- />
- }
- title="API Reference"
- href="/docs/references/data/core/Object"
- description="Complete API documentation for every schema, field type, and configuration option."
- />
- }
- title="FAQ"
- href="/docs/faq"
- description="Frequently asked questions about ObjectStack and how to use it."
+ icon={}
+ title="Introduction"
+ href="/docs/introduction"
+ description="Understand the philosophy: 'Intent over Implementation' and Metadata-Driven Architecture."
/>
}
- title="Troubleshooting"
- href="/docs/troubleshooting"
- description="Common issues and how to resolve them."
+ icon={}
+ title="Developers"
+ href="/docs/developers"
+ description="Guides for writing plugins, creating custom widgets, and using the CLI tools."
/>
-## Quick Links
-
-### Essential Guides
-- **[Field Types](/docs/guides/field-types)** - 35 field types with examples (text, number, select, lookup, formula, etc.)
-- **[View Configuration](/docs/guides/view-configuration)** - Grid, Kanban, Calendar, Gantt, and Form layouts
-- **[Workflows & Validation](/docs/guides/workflows-validation)** - Business rules and automation
-- **[Project Structure](/docs/guides/project-structure)** - Best practices for organizing your code
-
-### Examples
-- **[CRM Example](https://github.com/objectstack-ai/spec/tree/main/examples/crm)** - Full-featured application with 6 objects, workflows, views, dashboards
-- **[Todo Example](https://github.com/objectstack-ai/spec/tree/main/examples/todo)** - Quick-start minimal example
-
-## The "Trinity" Architecture
-
-ObjectStack is built on five core modules that work in unison:
+## Why ObjectStack?
| Module | Protocol | Responsibility |
| :--- | :--- | :--- |
-| **Data Layer** | **[ObjectQL](/docs/specifications/data/architecture)** | Defines the shape of data (`Object`, `Field`) and how to access it (`Query AST`). Agnostic to SQL/NoSQL. |
-| **UI Layer** | **[ObjectUI](/docs/specifications/ui/sdui-protocol)** | The Projection. Defines User Interfaces as abstract JSON layouts (Views, Dashboards, Actions). |
-| **Control Layer** | **[ObjectOS](/docs/specifications/server/kernel-architecture)** | The Kernel. Handles Identity, Security, Sync, and Automation. |
-| **AI Layer** | **AI Protocol** | AI agent definitions, tools, knowledge bases, and model configurations. |
-| **API Layer** | **API Protocol** | Standardized REST/GraphQL contracts with request/response envelopes. |
+| **Data Layer** | **[ObjectQL](/docs/objectql)** | Defines the shape of data (`Object`, `Field`) and how to access it. Agnostic to SQL/NoSQL. |
+| **UI Layer** | **[ObjectUI](/docs/objectui)** | The Projection. Defines User Interfaces as abstract JSON layouts (Views, Forms). |
+| **System Layer** | **[ObjectOS](/docs/objectos)** | The Kernel. Handles Identity, Security, Sync, and Lifecycle. |
## For whom is this?
From a1ae0defac36a146551a4ace69ada1b6cc55de56 Mon Sep 17 00:00:00 2001
From: Jack Zhuang <50353452+hotlong@users.noreply.github.com>
Date: Mon, 26 Jan 2026 22:07:08 +0800
Subject: [PATCH 11/22] Add primary CTA link to HeroSection and update version
in package.json
---
apps/docs/components/hero-section.tsx | 6 ++++++
apps/docs/lib/homepage-i18n.ts | 2 +-
package.json | 2 +-
3 files changed, 8 insertions(+), 2 deletions(-)
diff --git a/apps/docs/components/hero-section.tsx b/apps/docs/components/hero-section.tsx
index 2d8ba3bee..4c93c63bc 100644
--- a/apps/docs/components/hero-section.tsx
+++ b/apps/docs/components/hero-section.tsx
@@ -51,6 +51,12 @@ export function HeroSection({ badge, title, subtitle, cta, className }: HeroSect
{/* CTA Buttons */}