Skip to content

plumbus-framework/plumbus

Repository files navigation

Plumbus Framework

Plumbus

AI-native, contract-driven TypeScript application framework

Quick StartCore ConceptsProject StructureCLIAgent IntegrationFull Documentation


What is Plumbus?

Plumbus is a contract-driven, AI-native TypeScript framework for building modern applications that are safe, auditable, and explainable by default.

Instead of writing loosely organized code, you define your system using six composable primitives:

Primitive Purpose Defined with
Entity Data models with classification and retention defineEntity()
Capability Discrete business operations (query, action, job, eventHandler) defineCapability()
Flow Multi-step workflows orchestrating capabilities defineFlow()
Event Domain facts emitted by capabilities defineEvent()
Prompt Structured AI interactions with typed I/O definePrompt()
Translation Type-safe i18n message catalogs with ICU MessageFormat defineTranslation()

The framework provides:

  • Deny-by-default security — every capability declares an access policy
  • Advisory governance — warnings (not blockers) for risky patterns
  • Built-in audit trails — automatic structured logging of all operations
  • Managed AI integration — cost tracking, output validation, RAG pipelines
  • Compliance profiles — GDPR, PCI-DSS, SOC2, HIPAA policy assessment
  • Full code generation — typed API clients, React hooks, Next.js scaffolds

Optional add-on packages extend the core:

  • MCP agent surface — expose capabilities to AI agents over the Model Context Protocol (@plumbus/mcp)
  • Conversational runtimedefineChat with policy guards and context sources (@plumbus/chat, plus @plumbus/chat-ui for React clients)
  • Knowledge sources — scoped, registry-backed grounding for chat, capabilities, and search UIs (@plumbus/knowledge-base)

Quick Start

Prerequisites

  • Node.js ≥ 20
  • pnpm ≥ 10
  • PostgreSQL (for persistence)
  • Redis (for queues, optional)

Create a New Application

# Install the CLI globally
pnpm add -g @plumbus/core

# Scaffold a new project
plumbus create my-app --auth jwt --ai openai --compliance GDPR

# Navigate into your project
cd my-app

# Check environment readiness
plumbus doctor

# Start development server
plumbus dev

Install in an Existing Project

pnpm add @plumbus/core zod
pnpm add -D typescript vitest @types/node

Core Concepts

Capabilities

Capabilities are the atomic units of business logic. Every HTTP route, background job, and event handler is a capability:

import { defineCapability } from "@plumbus/core";
import { z } from "zod";

export const getUser = defineCapability({
  name: "getUser",
  kind: "query",
  domain: "users",
  description: "Retrieve a user by ID",
  input: z.object({ userId: z.string().uuid() }),
  output: z.object({ id: z.string(), name: z.string(), email: z.string() }),
  access: { roles: ["admin", "user"], scopes: ["users:read"] },
  effects: { reads: ["User"] },
  handler: async (ctx, input) => {
    const user = await ctx.data.User.findById(input.userId);
    if (!user) throw ctx.errors.notFound("User not found");
    return user;
  },
});

Entities

Entities define your data models with field-level classification:

import { defineEntity, field } from "@plumbus/core";

export const User = defineEntity({
  name: "User",
  description: "Application user",
  tenantScoped: true,
  fields: {
    id: field.id(),
    name: field.string({ classification: "personal" }),
    email: field.string({ classification: "personal", maskedInLogs: true }),
    role: field.enum({ values: ["admin", "user", "guest"] }),
    createdAt: field.timestamp({ defaultNow: true }),
  },
});

Flows

Flows orchestrate capabilities into multi-step workflows:

import { defineFlow } from "@plumbus/core";

export const refundApproval = defineFlow({
  name: "refundApproval",
  domain: "billing",
  description: "Route refund requests through validation and approval",
  trigger: { type: "event", event: "refund.requested" },
  steps: [
    { name: "validate", capability: "validateRefund" },
    {
      name: "decide",
      type: "conditional",
      condition: "ctx.state.amount > 100",
      ifTrue: "managerApproval",
      ifFalse: "autoApprove",
    },
    { name: "managerApproval", capability: "requestManagerApproval" },
    { name: "autoApprove", capability: "approveRefund" },
    { name: "notify", capability: "sendRefundNotification" },
  ],
  retry: { maxAttempts: 3, backoff: "exponential" },
});

Events

Events represent domain facts:

import { defineEvent } from "@plumbus/core";
import { z } from "zod";

export const orderPlaced = defineEvent({
  name: "order.placed",
  schema: z.object({ orderId: z.string(), customerId: z.string(), total: z.number() }),
  description: "Emitted when a new order is successfully placed",
});

Prompts

Prompts provide structured AI interactions:

import { definePrompt } from "@plumbus/core";
import { z } from "zod";

export const classifyTicket = definePrompt({
  name: "classifyTicket",
  description: "Classify support tickets by category, priority, and sentiment",
  model: "gpt-4o-mini",
  input: z.object({ ticketText: z.string() }),
  output: z.object({
    category: z.enum(["billing", "technical", "general"]),
    priority: z.enum(["low", "medium", "high"]),
    sentiment: z.enum(["positive", "neutral", "negative"]),
  }),
  systemPrompt: "You are a support ticket classifier. Analyze the ticket and return structured JSON.",
});

Translations

Translations provide type-safe i18n message catalogs with ICU MessageFormat:

import { defineTranslation } from "@plumbus/core";

export const commonTranslation = defineTranslation({
  name: "common",
  defaultLocale: "en",
  locales: ["en", "he"],
  messages: {
    en: {
      greeting: "Hello {name}",
      items: "{count, plural, one {# item} other {# items}}",
    },
    he: {
      greeting: "שלום {name}",
      items: "{count, plural, one {פריט #} two {# פריטים} other {# פריטים}}",
    },
  },
});

Translation catalogs are validated at import time — all locales must have the same key set. The framework provides a server-side resolver (ctx.translations.t()) for backend messages and generates next-intl modules for the frontend via plumbus ui generate.

Execution Context

Every capability handler receives ctx — the scoped runtime context:

ctx.auth       → Authenticated identity (userId, roles, scopes, tenantId)
ctx.data       → Entity repositories (ctx.data.User.findById(id))
ctx.events     → Event emission (ctx.events.emit("order.placed", payload))
ctx.flows      → Flow orchestration (ctx.flows.start("processRefund", input))
ctx.ai         → AI operations (generate, extract, classify, retrieve)
ctx.audit      → Audit logging (ctx.audit.record("user.updated", meta))
ctx.security   → Security helpers (hasRole, hasScope, requireRole, requireScope)
ctx.errors     → Structured errors (validation, notFound, forbidden, conflict)
ctx.logger     → Structured logging (info, warn, error)
ctx.time       → Time utilities (ctx.time.now())
ctx.config     → Read-only application configuration
ctx.translations → Translation resolver (ctx.translations.t("errors.notFound"))

Project Structure

my-app/
├── app/
│   ├── capabilities/        # Business logic (defineCapability)
│   │   └── billing/
│   │       └── approve-refund/
│   │           ├── capability.ts
│   │           ├── impl.ts
│   │           └── tests/
│   ├── entities/            # Data models (defineEntity)
│   │   └── user.entity.ts
│   ├── flows/               # Workflows (defineFlow)
│   │   └── billing/
│   │       └── refund-approval/
│   │           └── flow.ts
│   ├── events/              # Domain events (defineEvent)
│   │   └── order-placed.event.ts
│   └── prompts/             # AI prompts (definePrompt)
│       └── classify-ticket.prompt.ts
│   └── translations/        # i18n catalogs (defineTranslation)
│       └── common.translation.ts
├── config/
│   ├── app.config.ts        # Framework configuration
│   └── ai.config.ts         # AI provider configuration
├── .plumbus/
│   └── generated/           # Auto-generated (do not edit)
├── .github/
│   └── copilot-instructions.md  # GitHub Copilot wiring
├── AGENTS.md                # Agent context file
└── package.json

CLI Reference

plumbus create <app-name>       # Scaffold a new project
plumbus dev                     # Start development server with hot reload
plumbus doctor                  # Check environment readiness (Node, DB, Redis)
plumbus generate                # Regenerate all artifacts from contracts
plumbus verify                  # Run governance rules
plumbus certify <profile>       # Run compliance profile assessment
plumbus migrate generate        # Generate database migration
plumbus migrate apply           # Apply pending migrations
plumbus rag ingest <path>       # Ingest documents into RAG pipeline
plumbus init                    # Generate AI agent wiring files
plumbus agent sync              # Sync project brief for coding agents

# MCP — serve capabilities to AI agents (requires @plumbus/mcp for `serve`)
plumbus mcp serve               # Start an MCP server (stdio / HTTP) for capabilities with exposeAs: ["mcp"]
plumbus mcp generate            # Generate MCP manifest and skill files
plumbus mcp list-tools          # List MCP-exposed tools from the current app contracts

# Translation management
plumbus translation new <name>  # Scaffold a new translation catalog
plumbus translation export      # Export translations for translators (JSON/XLIFF)
plumbus translation import      # Import translated files back
plumbus translation status      # Report translation coverage per locale

plumbus create

plumbus create my-app \
  --database postgresql \
  --auth jwt \
  --ai openai \
  --compliance "GDPR,PCI-DSS" \
  --git                         # Initialize git repo (opt-in)

plumbus init

Generates configuration files that help AI coding agents understand your project:

plumbus init --agent copilot    # GitHub Copilot instructions
plumbus init --agent cursor     # Cursor rules
plumbus init --agent agents-md  # AGENTS.md
plumbus init --agent all        # All formats (default)

AI Agent Integration

Plumbus is designed to work seamlessly with AI coding agents (GitHub Copilot, Cursor, Cline, Windsurf, etc.).

How Agents Discover Framework Knowledge

The framework ships with comprehensive instruction files inside the @plumbus/core package:

node_modules/@plumbus/core/instructions/
├── guardrails.md     # Mandatory framework boundaries and git safety
├── framework.md      # Core abstractions, execution context, project structure
├── capabilities.md   # Capability definitions, handlers, effects, access policies
├── entities.md       # Entity fields, classifications, relations, repositories
├── events.md         # Event emission, outbox pattern, consumers, idempotency
├── flows.md          # Workflow steps, triggers, retry, state management
├── ai.md             # AI prompts, generation, RAG, cost tracking, security
├── security.md       # Access policies, auth, tenant isolation, field classification
├── governance.md     # Advisory rules, compliance profiles, policy assessment
├── testing.md        # Test utilities (runCapability, simulateFlow, mockAI)
├── translations.md   # Translation catalogs, server resolver, frontend i18n
└── patterns.md       # Naming conventions, best practices, common patterns

The @plumbus/ui package also ships instructions:

node_modules/@plumbus/ui/instructions/
├── framework.md         # UI package overview, exports, concepts
├── client-generator.md  # Typed fetch clients, React hooks, flow triggers
├── auth-generator.md    # Auth types, token utils, hooks, route guard
├── form-generator.md    # Zod schema → form field metadata extraction
├── nextjs-template.md   # Full Next.js project scaffold
├── patterns.md          # UI conventions, do's/don'ts, workflows
└── testing.md           # UI test setup, strategy, patterns

Non-Negotiable Guardrails

Generated agent wiring is expected to tell models that:

  • business logic belongs in Plumbus primitives, not ad hoc service layers or raw routes
  • ctx.* subsystems should be used instead of bypassing the framework with custom infrastructure code
  • destructive git commands require explicit user approval before execution

If an agent starts implementing around the framework, rerun plumbus init --patch after upgrading and verify the generated instruction file still contains the guardrails section.

Wiring Agents to Your Project

# Generate all agent configuration files
plumbus init --agent all

# Refresh Plumbus-managed sections without replacing surrounding notes
plumbus init --patch

# Replace existing generated wiring files outright
plumbus init --force

# This creates:
# .github/copilot-instructions.md  — Points Copilot to framework docs
# .cursor/rules/plumbus.mdc        — Cursor rules with SDK references
# AGENTS.md                        — Universal agent context
# .plumbus/briefs/project.md       — Project-specific brief

plumbus init is non-destructive by default: it creates missing wiring files and skips existing ones. Use --patch to update Plumbus-managed blocks in generated files, and use --force only when you want a full replacement.

Manual Agent Setup

If you're configuring an agent manually, point it to the instruction files:

# In your agent instructions:
When working with Plumbus, read these files for SDK reference:
- node_modules/@plumbus/core/instructions/guardrails.md
- node_modules/@plumbus/core/instructions/framework.md
- node_modules/@plumbus/core/instructions/capabilities.md
- node_modules/@plumbus/core/instructions/entities.md
- node_modules/@plumbus/core/instructions/flows.md
- node_modules/@plumbus/core/instructions/events.md
- node_modules/@plumbus/core/instructions/ai.md
- node_modules/@plumbus/core/instructions/security.md
- node_modules/@plumbus/core/instructions/testing.md

For a fuller explanation of the framework-first policy and destructive git safety, see docs/agents/guardrails.md.


Packages

Package Description
@plumbus/core Core framework — types, SDK, runtime, execution engine, CLI, test utilities
@plumbus/ui UI code generation — typed clients, React hooks, auth helpers, Next.js scaffolds
@plumbus/mcp Optional — MCP runtime; expose capabilities to AI agents over the Model Context Protocol
@plumbus/chat Optional — chat primitive; defineChat, policy guards, context sources, budgets, evals
@plumbus/chat-ui Optional — React hooks and <ChatPanel /> for the @plumbus/chat turn protocol
@plumbus/knowledge-base Optional — scoped knowledge providers and registry for registry-backed grounding

The optional packages are version-locked peer add-ons — install them explicitly only when you need them (see docs/README.md).


Development

# Clone the repository
git clone https://github.com/plumbus-framework/plumbus.git
cd plumbus

# Install dependencies
pnpm install

# Run all tests (1717 tests across 126 files)
pnpm test

# Type check
pnpm typecheck

# Build all packages
pnpm build

Monorepo Structure

plumbus/
├── packages/
│   ├── plumbus-core/           # @plumbus/core — core framework package
│   │   ├── src/               # 165 source files
│   │   ├── instructions/      # 15 AI agent instruction files
│   │   └── package.json
│   ├── ui/                    # @plumbus/ui — UI generation package
│   │   ├── src/               # 9 source files
│   │   ├── instructions/      # 7 AI agent instruction files
│   │   └── package.json
│   ├── mcp/                   # @plumbus/mcp — optional MCP runtime
│   ├── chat/                  # @plumbus/chat — optional chat primitive
│   ├── chat-ui/               # @plumbus/chat-ui — optional React chat UI
│   └── knowledge-base/        # @plumbus/knowledge-base — optional knowledge providers
├── design/                    # Architecture design documents
├── docs/                      # Documentation
├── turbo.json                 # Turborepo configuration
├── pnpm-workspace.yaml        # pnpm workspace definition
└── tsconfig.base.json         # Shared TypeScript configuration

Tech Stack

Layer Technology
Language TypeScript 5.x (strict, ESM)
Runtime Node.js ≥ 20
HTTP Server Fastify 5
Database PostgreSQL via Drizzle ORM
Validation Zod
CLI Commander.js
Testing Vitest
i18n next-intl (frontend) + built-in ICU resolver (backend)
Build Turborepo + pnpm workspaces
AI Providers OpenAI, Anthropic (pluggable)

Documentation

Comprehensive documentation is available in the docs/ directory:


License

MIT

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Packages

 
 
 

Contributors