.do
DesignBusiness-as-Code

Business Modeling

Model your business using semantic patterns and the $ SDK

Business Modeling with Business-as-Code

Business modeling is the process of expressing your business structure, operations, and workflows using semantic patterns. This guide shows you how to model different business aspects using the $ SDK.

Business Model Canvas

The traditional Business Model Canvas has 9 building blocks. Here's how to model each using Business-as-Code:

1. Customer Segments

Define who your customers are using semantic types:

import $ from 'sdk.do'
import type { Person, Organization } from 'schema.org.ai'

// Define customer segments
const B2CCustomer = {
  $type: $.Person,
  segment: 'consumer',
  characteristics: {
    age: '25-45',
    income: '>$50k',
    interests: ['technology', 'productivity'],
  },
}

const B2BCustomer = {
  $type: $.Organization,
  segment: 'enterprise',
  characteristics: {
    size: '50-500',
    industry: 'software',
    budget: '>$100k/year',
  },
}

// Track customer lifecycle
on($.Person.visits.Website, async (visitor) => {
  await send($.Lead.created, { visitor })
})

on($.Lead.qualified, async (lead) => {
  await send($.Customer.registered, { lead })
})

2. Value Propositions

Define what value you provide:

// Product/Service definition
const SaaSProduct = {
  $type: $.SoftwareApplication,
  $id: 'business-automation-platform',
  name: 'Business Automation Platform',
  valueProposition: {
    benefits: ['80% faster time to market', '90% reduction in operational overhead', 'AI-powered automation'],
    features: ['Semantic business modeling', 'AI agent orchestration', 'Serverless deployment'],
  },
}

// Value delivery through semantic operations
on($.Customer.registered, async (customer) => {
  // Onboard customer and deliver value
  await send($.Account.provision, { customer })
  await send($.Demo.schedule, { customer })
  await send($.Training.provide, { customer })
})

3. Channels

Model how you reach and serve customers:

// Marketing channels
const Channels = {
  acquisition: [
    { type: $.Website, traffic: 'organic' },
    { type: $.Blog, traffic: 'content' },
    { type: $.SocialMedia, platforms: ['twitter', 'linkedin'] },
    { type: $.PaidAds, channels: ['google', 'facebook'] },
  ],
  sales: [
    { type: $.SelfService, flow: 'signup' },
    { type: $.SalesCall, team: 'inside-sales' },
    { type: $.Demo, format: 'video' },
  ],
  delivery: [
    { type: $.WebApplication, deployment: 'cloud' },
    { type: $.API, access: 'programmatic' },
    { type: $.MobileApp, platforms: ['ios', 'android'] },
  ],
  support: [
    { type: $.Documentation, location: 'docs.example.com' },
    { type: $.ChatSupport, availability: '24/7' },
    { type: $.Community, platform: 'discord' },
  ],
}

// Channel automation
on($.Visitor.arrives.from($.Google), async (visitor) => {
  await send($.Analytics.track, {
    event: 'acquisition',
    channel: 'google',
    visitor,
  })
})

4. Customer Relationships

Define how you interact with customers:

// Relationship types
const CustomerRelationships = {
  automated: {
    // Self-service onboarding
    onboarding: on($.Customer.registered, async (customer) => {
      await send($.Email.welcome, customer)
      await send($.Tutorial.start, customer)
    }),

    // Automated support
    support: on($.Customer.asks.Question, async (question) => {
      const answer = await ai.generate({
        prompt: question.text,
        schema: $.Answer,
        context: 'documentation',
      })
      await send($.Answer.provide, { question, answer })
    }),
  },

  personal: {
    // Account management
    management: on($.Customer.upgrades.to('enterprise'), async (customer) => {
      await send($.AccountManager.assign, customer)
      await send($.Onboarding.schedule, { customer, type: 'white-glove' })
    }),

    // Success management
    success: every($.Quarterly, async () => {
      const customers = await db.list($.Customer, {
        where: { plan: 'enterprise' },
      })
      for (const customer of customers) {
        await send($.Review.schedule, { customer, type: 'QBR' })
      }
    }),
  },
}

5. Revenue Streams

Model your monetization strategy:

// Pricing models
const PricingModels = {
  subscription: {
    starter: {
      $type: $.Offer,
      name: 'Starter Plan',
      price: { value: 29, currency: 'USD', period: 'month' },
      features: ['Basic features', '1 user', '10GB storage'],
    },
    professional: {
      $type: $.Offer,
      name: 'Professional Plan',
      price: { value: 99, currency: 'USD', period: 'month' },
      features: ['Advanced features', '10 users', '100GB storage'],
    },
    enterprise: {
      $type: $.Offer,
      name: 'Enterprise Plan',
      price: { value: 499, currency: 'USD', period: 'month' },
      features: ['All features', 'Unlimited users', '1TB storage'],
    },
  },

  usage: {
    apiCalls: {
      price: { value: 0.01, currency: 'USD', per: 'api-call' },
      tiers: [
        { from: 0, to: 10000, price: 0.01 },
        { from: 10001, to: 100000, price: 0.008 },
        { from: 100001, to: Infinity, price: 0.005 },
      ],
    },
  },
}

// Revenue recognition
on($.Invoice.paid, async (invoice) => {
  await send($.Revenue.recognize, {
    amount: invoice.amount,
    period: invoice.period,
    customer: invoice.customer,
  })

  await send($.Analytics.track, {
    event: 'revenue',
    amount: invoice.amount,
    plan: invoice.plan,
  })
})

6. Key Resources

Identify and manage critical resources:

// Resource types
const KeyResources = {
  intellectual: {
    platform: {
      $type: $.SoftwareSourceCode,
      repository: 'github.com/company/platform',
      license: 'proprietary',
    },
    brand: {
      $type: $.Brand,
      name: 'Company Name',
      trademark: 'registered',
    },
  },

  physical: {
    infrastructure: {
      $type: $.ComputeResource,
      provider: 'cloudflare',
      type: 'serverless',
    },
  },

  human: {
    team: await db.list($.Person, {
      where: { role: { $in: ['engineer', 'designer', 'sales'] } },
    }),
  },

  financial: {
    capital: {
      raised: 1000000,
      runway: 18, // months
      burn: 50000, // per month
    },
  },
}

// Resource allocation
on($.Project.started, async (project) => {
  // Allocate team members
  const team = await db.list($.Person, {
    where: {
      skills: { $in: project.requiredSkills },
      available: true,
    },
  })

  await send($.Team.assign, { project, team })
})

7. Key Activities

Define core business activities:

// Product development activities
const ProductActivities = {
  development: {
    planning: every($.Weekly, async () => {
      await send($.Sprint.plan, {
        duration: '2 weeks',
        team: 'engineering',
      })
    }),

    deployment: on($.Code.merged.to('main'), async (commit) => {
      await send($.Tests.run, commit)
      await send($.Deploy.production, commit)
      await send($.Monitoring.alert, { deployment: commit.id })
    }),
  },

  marketing: {
    content: every($.Daily, async () => {
      const topic = await ai.generate({
        prompt: 'Suggest blog topic about Business-as-Code',
        schema: $.Topic,
      })

      await send($.Content.create, { topic })
    }),

    distribution: on($.BlogPost.published, async (post) => {
      await send($.Social.share, { post, platforms: ['twitter', 'linkedin'] })
      await send($.Newsletter.include, { post })
    }),
  },

  sales: {
    outbound: every($.Daily, async () => {
      const leads = await db.list($.Lead, {
        where: {
          score: { $gt: 80 },
          contacted: false,
        },
      })

      for (const lead of leads) {
        await send($.Email.send, {
          to: lead.email,
          template: 'outbound-sales',
          personalization: await ai.generate({
            prompt: `Personalize email for ${lead.company}`,
            context: lead,
          }),
        })
      }
    }),
  },
}

8. Key Partnerships

Model strategic partnerships:

// Partner types
const Partnerships = {
  technology: [
    {
      $type: $.Organization,
      name: 'Cloudflare',
      partnership: 'infrastructure',
      value: 'global edge network',
    },
    {
      $type: $.Organization,
      name: 'Stripe',
      partnership: 'payments',
      value: 'payment processing',
    },
  ],

  distribution: [
    {
      $type: $.Organization,
      name: 'AWS Marketplace',
      partnership: 'channel',
      value: 'enterprise reach',
    },
  ],

  strategic: [
    {
      $type: $.Organization,
      name: 'AI Research Lab',
      partnership: 'R&D',
      value: 'AI capabilities',
    },
  ],
}

// Partner integration
on($.Customer.subscribes.via('aws-marketplace'), async (customer) => {
  await send($.Revenue.share, {
    customer,
    partner: 'aws',
    percentage: 0.2,
  })
})

9. Cost Structure

Model your costs and expenses:

// Cost categories
const CostStructure = {
  fixed: {
    salaries: {
      engineering: 300000, // per month
      sales: 150000,
      operations: 100000,
    },
    software: {
      tools: 10000, // per month
      licenses: 5000,
    },
    office: {
      rent: 20000, // per month (if not remote)
    },
  },

  variable: {
    infrastructure: {
      compute: 0.0001, // per request
      storage: 0.023, // per GB per month
      bandwidth: 0.085, // per GB
    },
    payments: {
      stripe: 0.029, // percentage + $0.30 per transaction
      paypal: 0.0349,
    },
  },
}

// Cost tracking
on($.Invoice.paid, async (invoice) => {
  // Calculate cost of goods sold
  const cogs = {
    infrastructure: invoice.usage.compute + invoice.usage.storage,
    payment_processing: invoice.amount * 0.029 + 0.3,
    support: calculateSupportCost(invoice.customer),
  }

  await send($.Cost.record, {
    invoice,
    costs: cogs,
    margin: invoice.amount - Object.values(cogs).reduce((a, b) => a + b, 0),
  })
})

Industry-Specific Models

SaaS Business

// SaaS metrics and operations
const SaaSBusiness = {
  metrics: {
    mrr: 0,
    arr: 0,
    churn: 0,
    ltv: 0,
    cac: 0,
  },

  operations: {
    // Calculate MRR
    calculateMRR: every($.Daily, async () => {
      const subscriptions = await db.list($.Subscription, {
        where: { status: 'active' },
      })

      const mrr = subscriptions.reduce((sum, sub) => {
        return sum + sub.amount / (sub.interval === 'year' ? 12 : 1)
      }, 0)

      await send($.Metric.update, { name: 'MRR', value: mrr })
    }),

    // Monitor churn
    trackChurn: on($.Subscription.cancelled, async (subscription) => {
      await send($.Churn.record, {
        customer: subscription.customer,
        reason: subscription.cancellationReason,
        value: subscription.amount,
      })

      // Attempt to save the customer
      if (subscription.cancellationReason !== 'price') {
        await send($.Email.send, {
          to: subscription.customer.email,
          template: 'win-back',
          offer: { discount: 0.2, duration: '3 months' },
        })
      }
    }),
  },
}

E-commerce Business

// E-commerce operations
const EcommerceBusiness = {
  catalog: {
    products: await db.list($.Product),
    categories: await db.list($.Category),
    inventory: await db.list($.InventoryItem),
  },

  operations: {
    // Order fulfillment
    fulfillment: on($.Order.paid, async (order) => {
      // Reserve inventory
      await send($.Inventory.reserve, {
        items: order.items,
        order: order.id,
      })

      // Create shipment
      const shipment = await send($.Shipment.create, {
        order,
        carrier: 'fedex',
        service: 'ground',
      })

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

    // Inventory management
    inventorySync: every($.Hourly, async () => {
      const lowStock = await db.list($.Product, {
        where: { inventory: { $lt: 10 } },
      })

      for (const product of lowStock) {
        await send($.PurchaseOrder.create, {
          product,
          quantity: 100,
          supplier: product.supplier,
        })
      }
    }),
  },
}

Marketplace Business

// Two-sided marketplace
const MarketplaceBusiness = {
  sides: {
    supply: {
      type: $.Person,
      role: 'seller',
      onboarding: on($.Seller.applies, async (seller) => {
        // Verify seller
        const verification = await send($.Verification.run, {
          type: 'identity',
          subject: seller,
        })

        if (verification.approved) {
          await send($.Seller.approve, seller)
          await send($.Email.send, {
            to: seller.email,
            template: 'seller-approved',
          })
        }
      }),
    },

    demand: {
      type: $.Person,
      role: 'buyer',
      matching: on($.Buyer.searches, async (search) => {
        // Find matching sellers
        const matches = await db.list($.Seller, {
          where: {
            skills: { $in: search.requirements },
            rating: { $gte: 4.0 },
            available: true,
          },
        })

        await send($.Matches.show, {
          buyer: search.buyer,
          sellers: matches,
        })
      }),
    },
  },

  operations: {
    // Transaction management
    transaction: on($.Transaction.initiated, async (transaction) => {
      // Hold payment in escrow
      await send($.Payment.escrow, {
        amount: transaction.amount,
        from: transaction.buyer,
        to: 'platform',
      })

      // Release on completion
      on($.Service.completed, async (service) => {
        if (service.transaction === transaction.id) {
          await send($.Payment.release, {
            amount: transaction.amount * 0.85, // 15% platform fee
            to: transaction.seller,
          })
        }
      })
    }),
  },
}

Workflow Modeling

Sequential Workflows

// Linear process flow
const OnboardingWorkflow = {
  stages: [
    { name: 'signup', action: $.Customer.signup },
    { name: 'verify', action: $.Email.verify },
    { name: 'profile', action: $.Profile.complete },
    { name: 'payment', action: $.Payment.add },
    { name: 'activate', action: $.Account.activate },
  ],

  implement: function () {
    this.stages.forEach((stage, index) => {
      if (index < this.stages.length - 1) {
        const nextStage = this.stages[index + 1]

        on(stage.action.completed, async (data) => {
          await send(nextStage.action.start, data)
        })
      }
    })
  },
}

Parallel Workflows

// Concurrent operations
on($.Customer.registered, async (customer) => {
  // Execute in parallel
  await Promise.all([
    send($.Email.welcome, customer),
    send($.CRM.create, customer),
    send($.Analytics.track, { event: 'signup', customer }),
    send($.Slack.notify, { channel: 'sales', message: `New signup: ${customer.email}` }),
  ])
})

Conditional Workflows

// Decision-based routing
on($.Lead.qualified, async (lead) => {
  // Route based on lead score
  if (lead.score > 90) {
    await send($.Sales.assign, { lead, team: 'enterprise' })
  } else if (lead.score > 70) {
    await send($.Sales.assign, { lead, team: 'smb' })
  } else {
    await send($.Nurture.add, { lead, campaign: 'education' })
  }

  // Route based on company size
  if (lead.company.size > 500) {
    await send($.Demo.schedule, { lead, type: 'custom' })
  } else {
    await send($.Demo.schedule, { lead, type: 'standard' })
  }
})

Semantic Business Modeling

Using $.BusinessModel

Define your business model semantically using the Business Model Canvas pattern:

import $ from 'sdk.do'
import type { BusinessModel } from 'schema.org.ai'

// Complete Business Model Canvas as semantic entity
const businessModel: BusinessModel = await db.create($.BusinessModel, {
  $type: $.BusinessModel,
  $id: 'acme-saas-model',
  name: 'Acme SaaS Business Model',

  // Customer Segments
  customerSegments: [
    {
      $type: $.Audience,
      name: 'Small Business Owners',
      size: 'large',
      characteristics: {
        employees: '1-50',
        revenue: '$100k-$5M',
        industry: [$.NAICS['541512']], // Computer Systems Design
        painPoints: ['Manual processes', 'Inefficiency', 'Lack of automation'],
      },
    },
    {
      $type: $.Audience,
      name: 'Enterprise IT Teams',
      size: 'medium',
      characteristics: {
        employees: '500+',
        revenue: '$50M+',
        industry: [$.NAICS['541511']], // Custom Computer Programming
        painPoints: ['Integration complexity', 'Legacy systems', 'Scalability'],
      },
    },
  ],

  // Value Propositions
  valuePropositions: [
    {
      $type: $.ValueProposition,
      name: 'Business Automation',
      description: 'Automate business operations using AI-powered workflows',
      benefits: [
        '80% reduction in manual processes',
        '10x faster deployment',
        'Zero infrastructure management',
      ],
      differentiators: ['Semantic modeling', 'AI-native', 'Code-first approach'],
    },
  ],

  // Channels
  channels: [
    {
      $type: $.Channel,
      channelType: 'online',
      name: 'Website',
      purpose: ['awareness', 'acquisition', 'sales'],
      metrics: {
        visitors: 50000,
        conversion: 0.02,
      },
    },
    {
      $type: $.Channel,
      channelType: 'direct',
      name: 'Sales Team',
      purpose: ['sales', 'support'],
      metrics: {
        deals: 20,
        closeRate: 0.3,
      },
    },
  ],

  // Revenue Streams
  revenueStreams: [
    {
      $type: $.RevenueStream,
      name: 'Subscription Revenue',
      type: 'recurring',
      pricingModel: 'tiered',
      tiers: [
        { name: 'Starter', price: 29, volume: 100 },
        { name: 'Professional', price: 99, volume: 500 },
        { name: 'Enterprise', price: 499, volume: 200 },
      ],
      projectedAnnual: 1200000, // $1.2M ARR
    },
    {
      $type: $.RevenueStream,
      name: 'Usage Revenue',
      type: 'variable',
      pricingModel: 'usage-based',
      unitPrice: 0.01,
      projectedAnnual: 300000, // $300K ARR
    },
  ],

  // Cost Structure
  costStructure: {
    fixed: {
      salaries: 500000, // Annual
      software: 120000,
      office: 240000,
    },
    variable: {
      infrastructure: 0.0001, // per API call
      support: 0.05, // per customer
    },
    totalAnnual: 860000,
  },

  // Key Resources
  keyResources: [
    {
      $type: $.Resource,
      resourceType: 'intellectual',
      name: 'Platform Technology',
      description: 'Proprietary semantic business modeling platform',
    },
    {
      $type: $.Resource,
      resourceType: 'human',
      name: 'Engineering Team',
      headcount: 15,
      occupations: [
        $.ONET['15-1252.00'], // Software Developers
        $.ONET['15-1244.00'], // Network Architects
      ],
    },
  ],

  // Key Activities
  keyActivities: [
    {
      $type: $.Action,
      name: 'Product Development',
      description: 'Build and enhance platform features',
      effort: '60%',
    },
    {
      $type: $.Action,
      name: 'Customer Support',
      description: 'Provide technical support and training',
      effort: '20%',
    },
  ],

  // Key Partnerships
  keyPartnerships: [
    {
      $type: $.Partnership,
      partner: $.Organization['cloudflare'],
      partnershipType: 'technology',
      value: 'Global edge infrastructure',
    },
    {
      $type: $.Partnership,
      partner: $.Organization['stripe'],
      partnershipType: 'service',
      value: 'Payment processing',
    },
  ],

  // Customer Relationships
  customerRelationships: [
    {
      $type: $.CustomerRelationship,
      segmentTarget: 'Small Business',
      type: 'self-service',
      touchpoints: ['email', 'chat', 'documentation'],
    },
    {
      $type: $.CustomerRelationship,
      segmentTarget: 'Enterprise',
      type: 'dedicated',
      touchpoints: ['account-manager', 'phone', 'custom-onboarding'],
    },
  ],

  // Metrics & KPIs
  metrics: {
    mrr: 100000, // $100K MRR
    arr: 1200000, // $1.2M ARR
    customerCount: 800,
    churnRate: 0.05,
    ltv: 5000,
    cac: 1200,
    ltvCacRatio: 4.17,
  },
})

// Use the business model to guide operations
on($.Customer.registered, async (customer) => {
  // Determine customer segment
  const segment = await determineSegment(customer, businessModel.customerSegments)

  // Apply appropriate relationship strategy
  const relationship = businessModel.customerRelationships.find(
    (r) => r.segmentTarget === segment.name
  )

  if (relationship.type === 'dedicated') {
    await send($.AccountManager.assign, { customer })
  }
})

NAICS Industry Modeling

Model businesses using NAICS industry classifications:

import { NAICS } from 'naics.org.ai'

// Map business to NAICS code
const business = await db.create($.Organization, {
  $type: $.Organization,
  name: 'Tech Consulting LLC',

  // Primary NAICS code
  naics: $.NAICS['541512'], // Computer Systems Design Services

  // Industry characteristics from NAICS
  industry: {
    code: '541512',
    title: 'Computer Systems Design Services',
    description: 'Custom computer programming services',
    sector: '54', // Professional, Scientific, and Technical Services
    examples: [
      'Computer systems integration design consulting services',
      'Computer systems integration design services',
      'Computer software consulting services',
    ],
  },

  // Service offerings aligned with NAICS
  services: [
    {
      $type: $.Service,
      name: 'Systems Integration',
      naicsActivity: 'Computer systems integration design',
      pricing: { type: 'project', range: [50000, 500000] },
    },
    {
      $type: $.Service,
      name: 'Software Consulting',
      naicsActivity: 'Computer software consulting',
      pricing: { type: 'hourly', rate: 150 },
    },
  ],
})

// Query businesses by NAICS code
const techConsultants = await db.list($.Organization, {
  where: {
    naics: { $in: [$.NAICS['541512'], $.NAICS['541511']] },
  },
})

// Industry benchmarking
const industryMetrics = {
  naics: '541512',
  averageRevenue: 2500000,
  averageEmployees: 25,
  averageProfit: 0.15,
  growthRate: 0.08,
}

// Compare business to industry standards
on($.Metrics.quarterly, async (metrics) => {
  const performance = {
    revenue: metrics.revenue / industryMetrics.averageRevenue,
    employees: metrics.headcount / industryMetrics.averageEmployees,
    profitMargin: metrics.profitMargin / industryMetrics.averageProfit,
  }

  if (performance.revenue < 0.8) {
    await send($.Alert.performance, {
      type: 'below-industry-average',
      metric: 'revenue',
      gap: 1 - performance.revenue,
    })
  }
})

O*NET Occupation & Skills Modeling

Model workforce and skills using O*NET:

import { ONET } from 'onet.org.ai'

// Define roles with O*NET occupation codes
const team = {
  engineering: {
    $type: $.Team,
    name: 'Engineering',
    roles: [
      {
        $type: $.Role,
        title: 'Software Developer',
        onet: $.ONET['15-1252.00'], // Software Developers
        count: 10,
        skills: [
          { skill: 'Programming', level: 4.5, importance: 95 },
          { skill: 'Systems Analysis', level: 4.0, importance: 85 },
          { skill: 'Database Management', level: 3.5, importance: 75 },
        ],
        tools: [
          $.Tools['JavaScript'],
          $.Tools['Python'],
          $.Tools['TypeScript'],
        ],
        technologies: [
          $.Tech['Cloud Computing'],
          $.Tech['API Development'],
          $.Tech['Database Systems'],
        ],
      },
      {
        $type: $.Role,
        title: 'DevOps Engineer',
        onet: $.ONET['15-1252.00'],
        count: 3,
        skills: [
          { skill: 'Systems Administration', level: 4.5, importance: 90 },
          { skill: 'Automation', level: 4.0, importance: 85 },
          { skill: 'Monitoring', level: 3.5, importance: 75 },
        ],
      },
    ],
  },

  sales: {
    $type: $.Team,
    name: 'Sales',
    roles: [
      {
        $type: $.Role,
        title: 'Sales Representative',
        onet: $.ONET['41-4011.00'], // Sales Representatives, Wholesale and Manufacturing
        count: 5,
        skills: [
          { skill: 'Persuasion', level: 4.0, importance: 90 },
          { skill: 'Active Listening', level: 4.0, importance: 85 },
          { skill: 'Negotiation', level: 3.5, importance: 80 },
        ],
      },
    ],
  },
}

// Hiring workflow based on O*NET data
on($.Job.posted, async (job) => {
  // Get O*NET occupation data
  const occupation = await db.get($.Occupation, job.onet)

  // Generate job description from O*NET
  const description = await ai.generate({
    prompt: `Create a job description for ${occupation.title}`,
    schema: $.JobPosting,
    context: {
      tasks: occupation.tasks,
      skills: occupation.skills,
      knowledge: occupation.knowledge,
      abilities: occupation.abilities,
    },
  })

  await db.update($.JobPosting, job.id, {
    description: description.description,
    responsibilities: description.responsibilities,
    qualifications: description.qualifications,
  })
})

// Skills gap analysis
const skillsGapAnalysis = every($.Quarterly, async () => {
  const currentTeam = await db.list($.Person, {
    where: { status: 'active' },
  })

  // Aggregate current skills
  const currentSkills = currentTeam.flatMap((person) => person.skills)

  // Compare to required skills from O*NET
  const requiredSkills = team.engineering.roles.flatMap((role) => role.skills)

  const gaps = requiredSkills.filter((required) => {
    const current = currentSkills.find((s) => s.skill === required.skill)
    return !current || current.level < required.level
  })

  if (gaps.length > 0) {
    await send($.Training.plan, {
      gaps,
      priority: gaps.filter((g) => g.importance > 80),
    })
  }
})

Advanced Modeling Patterns

Multi-Sided Platform

// Marketplace with multiple participant types
const marketplaceModel = await db.create($.BusinessModel, {
  $type: $.BusinessModel,
  name: 'Freelance Platform',

  // Multiple customer segments (sides)
  customerSegments: [
    {
      side: 'supply',
      $type: $.Audience,
      name: 'Freelancers',
      role: 'service-provider',
      value: 'Find clients and get paid',
      acquisition: ['organic', 'referral'],
    },
    {
      side: 'demand',
      $type: $.Audience,
      name: 'Businesses',
      role: 'service-buyer',
      value: 'Find skilled talent quickly',
      acquisition: ['ads', 'sales'],
    },
  ],

  // Platform dynamics
  networkEffects: {
    type: 'cross-side',
    strength: 'strong',
    formula: 'value = suppliers × demanders',
  },

  // Matching algorithm
  matching: {
    factors: ['skills', 'availability', 'price', 'rating', 'history'],
    algorithm: 'ai-powered',
  },
})

// Implement platform dynamics
on($.Freelancer.joins, async (freelancer) => {
  // Increase value for demand side
  await updatePlatformValue('demand', +1)

  // Find initial matches
  const matches = await ai.match('projects', {
    freelancer,
    criteria: ['skills', 'availability'],
  })

  await send($.Notification.opportunities, {
    freelancer,
    matches,
  })
})

Subscription + Marketplace Hybrid

// Combine subscription and marketplace models
const hybridModel = await db.create($.BusinessModel, {
  $type: $.BusinessModel,
  name: 'Premium Content Platform',

  revenueStreams: [
    {
      $type: $.RevenueStream,
      name: 'Consumer Subscriptions',
      type: 'recurring',
      pricing: { monthly: 9.99, annual: 99 },
      target: 'consumers',
    },
    {
      $type: $.RevenueStream,
      name: 'Creator Marketplace',
      type: 'commission',
      rate: 0.2, // 20% platform fee
      target: 'creators',
    },
    {
      $type: $.RevenueStream,
      name: 'Premium Creator Tools',
      type: 'recurring',
      pricing: { monthly: 29.99 },
      target: 'creators',
    },
  ],

  valuePropositions: [
    {
      for: 'consumers',
      value: 'Unlimited access to premium content',
    },
    {
      for: 'creators',
      value: 'Monetize your content + premium tools',
    },
  ],
})

Freemium SaaS with Usage Tiers

const freemiumModel = await db.create($.BusinessModel, {
  $type: $.BusinessModel,
  name: 'API Platform',

  pricingStrategy: {
    model: 'freemium',
    conversionGoal: 0.05, // 5% free to paid

    tiers: [
      {
        name: 'Free',
        price: 0,
        limits: {
          apiCalls: 1000,
          storage: 1000000000, // 1GB
          users: 1,
        },
        features: ['basic-api', 'community-support'],
        conversionTriggers: [
          'limit-reached',
          'advanced-feature-attempt',
          'time-based',
        ],
      },
      {
        name: 'Starter',
        price: 29,
        limits: {
          apiCalls: 100000,
          storage: 10000000000, // 10GB
          users: 5,
        },
        features: ['basic-api', 'advanced-api', 'email-support'],
      },
      {
        name: 'Pro',
        price: 99,
        limits: {
          apiCalls: 1000000,
          storage: 100000000000, // 100GB
          users: 25,
        },
        features: ['all-api', 'priority-support', 'sla'],
      },
    ],
  },

  // Conversion automation
  conversionStrategy: {
    limitReached: {
      trigger: 'usage >= 80% of limit',
      action: 'show-upgrade-modal',
      timing: 'immediate',
    },
    trialEnd: {
      trigger: 'trial expiring in 3 days',
      action: 'send-upgrade-email',
      timing: 'scheduled',
    },
    featureRequest: {
      trigger: 'access-premium-feature',
      action: 'show-feature-paywall',
      timing: 'immediate',
    },
  },
})

// Implement conversion triggers
on($.Usage.exceeds(0.8), async ({ account, resource }) => {
  const strategy = freemiumModel.conversionStrategy.limitReached

  await send($.Modal.show, {
    user: account.user,
    type: 'upgrade',
    message: `You've used 80% of your ${resource} limit`,
    cta: {
      text: 'Upgrade Now',
      action: $.Subscription.upgrade,
      benefit: `Get ${getNextTierLimit(account.plan, resource)}x more ${resource}`,
    },
  })
})

Advanced Workflow Patterns

State Machine Workflows

// Define complex state machine for order processing
const OrderStateMachine = {
  states: {
    draft: {
      on: { submit: 'pending_payment' },
    },
    pending_payment: {
      on: {
        payment_success: 'paid',
        payment_failed: 'payment_failed',
        timeout: 'expired',
      },
    },
    paid: {
      on: {
        fulfill: 'fulfilling',
        cancel: 'cancelled',
      },
    },
    fulfilling: {
      on: {
        ship: 'shipped',
        out_of_stock: 'backorder',
      },
    },
    shipped: {
      on: {
        deliver: 'delivered',
        return: 'returning',
      },
    },
    delivered: {
      on: {
        return: 'returning',
      },
    },
    returning: {
      on: {
        receive_return: 'returned',
      },
    },
    returned: {
      on: {
        refund: 'refunded',
      },
    },
  },

  // Implement state machine
  transition: async (order, event) => {
    const currentState = order.state
    const nextState = OrderStateMachine.states[currentState]?.on[event]

    if (!nextState) {
      throw new Error(`Invalid transition: ${currentState} -> ${event}`)
    }

    // Update state
    await db.update($.Order, order.id, {
      state: nextState,
      stateHistory: [...order.stateHistory, { from: currentState, to: nextState, event, timestamp: new Date() }],
    })

    // Trigger state-specific actions
    await send($[`Order.${nextState}`], order)

    return nextState
  },
}

// Use state machine
on($.Payment.succeeded, async (payment) => {
  const order = await db.get($.Order, payment.order)
  await OrderStateMachine.transition(order, 'payment_success')
})

Saga Pattern for Distributed Transactions

// Multi-service transaction coordination
const OrderSaga = {
  steps: [
    {
      name: 'reserve_inventory',
      action: async (order) => {
        return await send($.Inventory.reserve.in('inventory-service'), {
          items: order.items,
        })
      },
      compensate: async (order, result) => {
        await send($.Inventory.release.in('inventory-service'), {
          reservation: result.id,
        })
      },
    },
    {
      name: 'process_payment',
      action: async (order) => {
        return await send($.Payment.process.in('payment-service'), {
          order: order.id,
          amount: order.total,
        })
      },
      compensate: async (order, result) => {
        await send($.Payment.refund.in('payment-service'), {
          payment: result.id,
        })
      },
    },
    {
      name: 'create_shipment',
      action: async (order, context) => {
        return await send($.Shipment.create.in('fulfillment-service'), {
          order: order.id,
          inventory: context.reserve_inventory.id,
        })
      },
      compensate: async (order, result) => {
        await send($.Shipment.cancel.in('fulfillment-service'), {
          shipment: result.id,
        })
      },
    },
  ],

  execute: async (order) => {
    const context = {}
    const completed = []

    try {
      // Execute each step
      for (const step of OrderSaga.steps) {
        const result = await step.action(order, context)
        context[step.name] = result
        completed.push({ step, result })
      }

      return { success: true, context }
    } catch (error) {
      // Compensate in reverse order
      for (const { step, result } of completed.reverse()) {
        await step.compensate(order, result)
      }

      return { success: false, error }
    }
  },
}

// Use saga
on($.Order.confirmed, async (order) => {
  const result = await OrderSaga.execute(order)

  if (result.success) {
    await send($.Order.processing, { order, context: result.context })
  } else {
    await send($.Order.failed, { order, error: result.error })
  }
})

Next Steps


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.