.do
DesignBusiness-as-Code

Business-as-Code

Explaining from first principles how to build autonomous businesses programmatically

Business-as-Code: From First Principles

Documentation Status: This documentation describes the planned API design for the .do platform. Code examples represent the intended interface and may not reflect the current implementation state. See roadmap for implementation status.

What is Business-as-Code?

Business-as-Code is a paradigm shift where entire businesses—their operations, workflows, decision-making, and automation—are defined, deployed, and scaled through code using semantic patterns that both humans and AI can understand.

Traditional software requires you to build applications. Business-as-Code allows you to build entire businesses.

The Core Insight

Every business, at its foundation, is a system of:

  1. Entities (customers, products, orders, invoices)
  2. Relationships (customer places order, order contains products)
  3. Events (order created, payment received, item shipped)
  4. Workflows (when order created → send confirmation → process payment → fulfill order)
  5. Decisions (if high-value customer → priority shipping, if stock low → reorder)

Traditional programming treats these as implementation details hidden in application code. Business-as-Code treats them as first-class semantic constructs that can be understood, automated, and orchestrated by AI.

First Principles

Principle 1: Everything is Semantic

Instead of writing imperative code that tells computers how to do something, Business-as-Code uses semantic patterns that declare what things mean.

Traditional Code (Imperative - "How"):

// How to create an order
const order = {
  id: generateId(),
  customer_id: '123',
  items: [{ product_id: '456', qty: 2, price: 29.99 }],
  total: 59.98,
  status: 'pending',
  created_at: new Date(),
}
db.orders.insert(order)

Business-as-Code (Semantic - "What it means"):

// What this order represents
const order = await $.Order.create({
  customer: $.Customer['123'],
  orderedItem: [
    {
      orderItem: $.Product['456'],
      orderQuantity: 2,
    },
  ],
  orderStatus: $.OrderStatus.pending,
})

// AI understands this is an Order with a Customer and Products
// and can automatically:
// - Calculate total price
// - Send confirmation email
// - Update inventory
// - Track analytics

The semantic pattern $.Subject.predicate.Object comes from RDF (Resource Description Framework), the foundation of the semantic web. It's how knowledge graphs represent information that both humans and machines can reason about.

Principle 2: Types Come from Shared Vocabularies

Instead of inventing your own data structures, Business-as-Code uses standardized vocabularies that AI models already understand:

  • Schema.org: 800+ types for general business entities (Organization, Person, Product, Order, Event)
  • GS1: Supply chain and logistics (EPCIS events, product identifiers)
  • O*NET: Occupations, skills, and workforce

These aren't arbitrary choices—they're the same vocabularies that AI models were trained on. When you use $.Organization or $.Product, the AI already knows what these mean and how they relate.

import { $ } from 'sdk.do'

// Schema.org types with full TypeScript autocomplete
$.Organization // knows: name, email, address, employees, founder
$.Person // knows: givenName, familyName, email, jobTitle
$.Product // knows: name, price, description, manufacturer
$.Order // knows: customer, orderedItem, orderStatus, orderDate

Principle 3: The $ is a Semantic Proxy

The $ symbol is a TypeScript Proxy that creates semantic paths dynamically:

// Under the hood (simplified)
const $ = new Proxy(
  {},
  {
    get(target, subject) {
      return new Proxy(
        {},
        {
          get(_, predicate) {
            return new Proxy(
              {},
              {
                get(__, object) {
                  return `${subject}.${predicate}.${object}`
                },
              }
            )
          },
        }
      )
    },
  }
)

// Creates semantic references
$.Order.customer.Person // → "Order.customer.Person"
$.Product.manufacturer.Organization // → "Product.manufacturer.Organization"
$.Event.location.Place // → "Event.location.Place"

This provides:

  • Type Safety: Full TypeScript autocomplete for 800+ Schema.org types
  • Composability: Build complex semantic paths naturally
  • Readability: Code reads like natural language

Principle 4: Events Drive Workflows

Business-as-Code uses event-driven architecture where business operations are triggered by semantic events:

import { on, send } from 'sdk.do'

// Define workflow: when Order is created
on($.Order.created, async (order) => {
  // Send confirmation email
  await send($.Email.send, {
    to: order.customer.email,
    subject: 'Order Confirmation',
    template: 'order-confirmation',
    data: { order },
  })

  // Update inventory
  for (const item of order.orderedItem) {
    await send($.Inventory.decrement, {
      product: item.orderItem,
      quantity: item.orderQuantity,
    })
  }

  // Create invoice
  await send($.Invoice.generate, {
    order: order.$id,
    dueDate: new Date(Date.now() + 30 * 24 * 60 * 60 * 1000),
  })
})

// Trigger the workflow
await send($.Order.created, order)

The power: AI can understand and extend these workflows because they're expressed semantically.

Principle 5: AI is a First-Class Participant

In Business-as-Code, AI isn't an add-on—it's built into the platform's fabric:

import { $, ai } from 'sdk.do'

// AI automatically helps with business operations
on($.SupportTicket.created, async (ticket) => {
  // AI analyzes the ticket
  const analysis = await ai.analyze(ticket, {
    sentiment: 'positive | neutral | negative',
    urgency: 'low | medium | high | critical',
    category: 'billing | technical | feature-request | bug',
    suggestedResponse: 'string',
  })

  // Update ticket with AI insights
  await $.SupportTicket.update(ticket.$id, {
    sentiment: analysis.sentiment,
    urgency: analysis.urgency,
    category: analysis.category,
  })

  // Route to appropriate team
  if (analysis.urgency === 'critical') {
    await send($.Notification.urgent, {
      team: 'support-tier-3',
      ticket: ticket.$id,
    })
  }

  // AI-suggested response ready for human review
  await $.Comment.create({
    ticket: ticket.$id,
    author: $.Agent.AI,
    content: analysis.suggestedResponse,
    status: 'draft',
  })
})

The Architecture

Business-as-Code is built on three layers:

1. Semantic Layer (Foundation)

The semantic layer provides the vocabulary and graph structure:

// Everything has semantic meaning
const business = await $.Organization.create({
  $type: 'Organization',
  name: 'Acme Corp',
  industry: $.Industry.Technology,
  employees: 50,
  founder: $.Person['john-doe'],
})

// Stored as a knowledge graph
// Queryable semantically
// Understood by AI

2. Event Layer (Coordination)

The event layer coordinates workflows and business processes:

// Business operations as events
await send($.Order.created, order)
await send($.Payment.processed, payment)
await send($.Shipment.dispatched, shipment)

// Handlers react to events
on($.Payment.processed, async (payment) => {
  await send($.Order.fulfill, { orderId: payment.order })
})

on($.Order.fulfilled, async (order) => {
  await send($.Shipment.create, { order })
})

3. AI Layer (Intelligence)

The AI layer adds intelligence and automation:

// AI-powered decision making
const decision = await ai.decide('pricing-strategy', {
  customer: customer,
  product: product,
  context: {
    seasonality: 'high',
    competition: 'moderate',
    inventory: 'low',
  },
})

// AI-generated content
const description = await ai.generate('product-description', {
  product: product,
  tone: 'professional',
  length: 'medium',
  keywords: ['sustainable', 'innovative', 'premium'],
})

// AI workflow orchestration
const workflow = await ai.orchestrate('customer-onboarding', {
  customer: customer,
  plan: 'enterprise',
  requirements: ['setup-account', 'configure-integrations', 'schedule-training', 'assign-success-manager'],
})

Building a Business with Code

Let's build a complete e-commerce business from scratch:

Step 1: Define Your Business

import { $, db } from 'sdk.do'

// Create your business entity
const business = await db.create($.Organization, {
  name: 'Artisan Marketplace',
  description: 'Handcrafted goods from local artisans',
  industry: $.Industry.Ecommerce,
  legalName: 'Artisan Marketplace LLC',
  taxID: '12-3456789',
  address: {
    $type: 'PostalAddress',
    streetAddress: '123 Main St',
    addressLocality: 'Austin',
    addressRegion: 'TX',
    postalCode: '78701',
    addressCountry: 'US',
  },
})

Step 2: Define Your Products

// Create product catalog
const products = await db.createMany($.Product, [
  {
    name: 'Handwoven Basket',
    description: 'Beautiful handwoven basket made from sustainable materials',
    category: $.ProductCategory.HomeGoods,
    brand: business,
    offers: {
      $type: 'Offer',
      price: 45.0,
      priceCurrency: 'USD',
      availability: $.InStock,
    },
    image: 'https://cdn.artisan.com/basket-001.jpg',
  },
  {
    name: 'Ceramic Coffee Mug',
    description: 'Hand-thrown ceramic mug, microwave and dishwasher safe',
    category: $.ProductCategory.Tableware,
    brand: business,
    offers: {
      $type: 'Offer',
      price: 28.0,
      priceCurrency: 'USD',
      availability: $.InStock,
    },
    image: 'https://cdn.artisan.com/mug-001.jpg',
  },
])

Step 3: Define Your Business Logic

import { on, send, every } from 'sdk.do'

// Order processing workflow
on($.Order.created, async (order) => {
  // Validate order
  const validation = await ai.validate('order', order)
  if (!validation.valid) {
    await send($.Order.cancel, {
      orderId: order.$id,
      reason: validation.reason,
    })
    return
  }

  // Process payment
  await send($.Payment.process, {
    order: order.$id,
    amount: order.totalPrice,
    method: order.paymentMethod,
  })
})

// Payment processing
on($.Payment.processed, async (payment) => {
  if (payment.status === 'succeeded') {
    // Update order status
    await db.update($.Order, payment.order, {
      orderStatus: $.OrderStatus.processing,
    })

    // Notify seller
    await send($.Notification.send, {
      recipient: payment.seller,
      type: 'order-received',
      data: { payment },
    })

    // Generate shipping label
    await send($.Shipment.create, {
      order: payment.order,
    })
  } else {
    // Handle payment failure
    await send($.Order.cancel, {
      orderId: payment.order,
      reason: 'payment-failed',
    })
  }
})

// Shipping automation
on($.Shipment.created, async (shipment) => {
  // AI picks optimal carrier
  const carrier = await ai.decide('shipping-carrier', {
    origin: shipment.origin,
    destination: shipment.destination,
    weight: shipment.weight,
    priority: shipment.priority,
  })

  // Create label
  await send($.ShippingLabel.generate, {
    shipment: shipment.$id,
    carrier: carrier,
  })

  // Notify customer
  await send($.Email.send, {
    to: shipment.customer.email,
    template: 'order-shipped',
    data: { shipment, tracking: shipment.trackingNumber },
  })
})

// Inventory management
every('daily at 9am', async () => {
  // Check low stock
  const lowStock = await db.list($.Product, {
    where: {
      'offers.inventory': { $lt: 10 },
    },
  })

  // AI generates reorder recommendations
  for (const product of lowStock) {
    const recommendation = await ai.analyze('reorder', {
      product,
      salesHistory: await db.related(product, 'orders', { limit: 90 }),
      seasonality: true,
    })

    if (recommendation.shouldReorder) {
      await send($.PurchaseOrder.create, {
        product: product.$id,
        quantity: recommendation.quantity,
        supplier: product.supplier,
      })
    }
  }
})

Step 4: Add Customer Intelligence

// Customer behavior analysis
on($.Customer.activity, async (activity) => {
  // AI analyzes customer behavior
  const insights = await ai.analyze('customer-segment', {
    customer: activity.customer,
    recentOrders: await db.related(activity.customer, 'orders', { limit: 10 }),
    browsing: activity.pages,
    engagement: activity.interactions,
  })

  // Update customer profile
  await db.update($.Customer, activity.customer.$id, {
    segment: insights.segment, // 'high-value' | 'regular' | 'at-risk' | 'new'
    preferences: insights.preferences,
    lifetime_value: insights.ltv,
  })

  // Personalized recommendations
  if (insights.segment === 'high-value') {
    const recommendations = await ai.recommend('products', {
      customer: activity.customer,
      context: 'vip-treatment',
      limit: 5,
    })

    await send($.Email.send, {
      to: activity.customer.email,
      template: 'personalized-picks',
      data: { recommendations },
    })
  }
})

Step 5: Deploy Your Business

// Everything is ready to deploy
import { deploy } from 'sdk.do'

// Deploy to production
await deploy({
  business: business.$id,
  environment: 'production',
  regions: ['us-east', 'us-west', 'eu-west'],
  services: {
    api: { workers: 5, memory: '512MB' },
    events: { workers: 10, memory: '256MB' },
    ai: { workers: 3, memory: '1GB', gpu: true },
  },
})

// Your business is now live and autonomous!

The Power of Business-as-Code

1. AI-Native from the Start

Because everything is semantic, AI can:

  • Understand your business logic without training
  • Extend workflows with intelligent automation
  • Optimize operations based on data
  • Recommend improvements to business processes

2. Composable Business Operations

Build complex businesses by composing simple semantic operations:

// Compose marketplace business
const marketplace = compose(
  $.ecommerce.storefront,
  $.payments.stripe,
  $.shipping.multi_carrier,
  $.inventory.auto_reorder,
  $.analytics.real_time,
  $.support.ai_powered
)

// Launch in minutes
await marketplace.deploy()

3. Autonomous Decision Making

Business-as-Code enables true autonomy:

// AI makes business decisions
every('hourly', async () => {
  // Analyze business metrics
  const metrics = await analytics.current()

  // AI decides on pricing adjustments
  if (metrics.conversion_rate < targets.conversion) {
    const strategy = await ai.decide('pricing-optimization', {
      current: metrics,
      target: targets,
      constraints: { min_margin: 0.2 },
    })

    // Automatically adjust prices
    await strategy.execute()
  }

  // AI decides on marketing spend
  const marketing = await ai.decide('ad-budget', {
    performance: metrics.marketing,
    budget: budgets.monthly,
    remaining: budgets.remaining,
  })

  // Automatically allocate budget
  await marketing.allocate()
})

4. Rapid Iteration

Change business logic in real-time:

// Update workflow without downtime
on($.Order.created, async (order) => {
  // New: AI-powered fraud detection
  const fraudCheck = await ai.analyze('fraud-risk', {
    order,
    customer: order.customer,
    history: await db.related(order.customer, 'orders'),
  })

  if (fraudCheck.risk === 'high') {
    await send($.Order.hold, {
      orderId: order.$id,
      reason: 'fraud-review',
    })
    await send($.Alert.fraud, { order, analysis: fraudCheck })
    return
  }

  // Continue normal flow
  await send($.Payment.process, { order })
})

Comparison: Traditional vs Business-as-Code

AspectTraditional DevelopmentBusiness-as-Code
Time to Launch6-12 monthsDays to weeks
Code Complexity100,000+ lines1,000-5,000 lines
AI IntegrationComplex, customNative, automatic
ScalingManual infrastructureAutomatic
ChangesDeploy cyclesReal-time updates
InteroperabilityCustom APIsStandard semantics
UnderstandingDomain experts + developersCode is the documentation

Real-World Examples

Example 1: SaaS Business

// Define SaaS business
const saas = await $.SaaS.create({
  name: 'ProjectFlow',
  product: $.SoftwareApplication,
  pricing: {
    free: { price: 0, features: ['basic'] },
    pro: { price: 29, features: ['basic', 'advanced'] },
    enterprise: { price: 99, features: ['all'] },
  },
  billing: 'monthly',
})

// Automatic subscription management
on($.Subscription.created, async (sub) => {
  await $.User.provision({ subscription: sub })
  await $.Email.welcome({ subscription: sub })
  await $.Analytics.track({ event: 'signup', subscription: sub })
})

on($.Subscription.cancelled, async (sub) => {
  await $.User.deprovision({ subscription: sub })
  await $.Email.exit_survey({ subscription: sub })
})

Example 2: Marketplace Business

// Two-sided marketplace
const marketplace = await $.Marketplace.create({
  name: 'FreelanceHub',
  sellers: $.Person.freelancer,
  buyers: $.Organization.startup,
  commission: 0.15,
  escrow: true,
})

// Automated matching
on($.Project.posted, async (project) => {
  const matches = await ai.match('freelancers', {
    project,
    criteria: {
      skills: project.required_skills,
      experience: project.experience_level,
      availability: project.timeline,
      budget: project.budget,
    },
  })

  for (const freelancer of matches.top5) {
    await send($.Notification.opportunity, {
      freelancer,
      project,
      match_score: freelancer.score,
    })
  }
})

Example 3: Service Business

// Service-based business
const service = await $.ServiceBusiness.create({
  name: 'CleanCo',
  service: $.Service.cleaning,
  coverage: $.City['austin-tx'],
  pricing: 'per_hour',
  rate: 45,
})

// Booking automation
on($.Booking.requested, async (booking) => {
  // AI schedules optimally
  const schedule = await ai.schedule('cleaners', {
    booking,
    preferences: booking.customer.preferences,
    availability: await db.list($.Cleaner, {
      where: { available: true, area: booking.location.area },
    }),
  })

  await send($.Booking.confirm, {
    booking: booking.$id,
    cleaner: schedule.assigned,
    time: schedule.optimal_time,
  })
})

Getting Started

  1. Install the SDK
npm install sdk.do
  1. Define your business
import { $, db, on, send } from 'sdk.do'

const business = await db.create($.Organization, {
  name: 'Your Business',
  industry: $.Industry.YourIndustry,
})
  1. Add business logic
on($.YourEvent.happened, async (event) => {
  // Your business logic
})
  1. Deploy
npx sdk.do deploy
  • SDK Overview - The unified $ interface
  • Semantic Graph - Understanding semantic patterns
  • Event System - Building event-driven workflows
  • AI Services - Integrating AI into your business

Questions? Join the Discord community or check out more examples.