.do

Semantic Patterns

Master the $.Subject.predicate.Object pattern for Business-as-Code

The .do platform uses the $.Subject.predicate.Object pattern as the foundation for all business logic. This semantic approach provides clarity, consistency, and meaning to every operation.

The Triple Pattern

Every operation follows the semantic triple pattern:

$.Subject.predicate.Object

Where:

  • Subject = The entity performing or experiencing the action (noun)
  • predicate = The relationship or action (verb)
  • Object = The entity receiving the action or related entity (noun)

Basic Examples

Creating Entities

// Subject: User, predicate: create, Object: Account
await $.User.create.Account({
  email: '[email protected]',
  name: 'John Doe',
})

// Subject: Organization, predicate: register, Object: Business
await $.Organization.register.Business({
  name: 'Acme Inc',
  industry: 'Software',
})

// Subject: Product, predicate: add, Object: Inventory
await $.Product.add.Inventory({
  productId: 'prod-123',
  quantity: 100,
})

Relationships

// Subject: User, predicate: joins, Object: Organization
await $.User.joins.Organization({
  userId: 'user-123',
  organizationId: 'org-456',
  role: 'member',
})

// Subject: Product, predicate: belongsTo, Object: Category
await $.Product.belongsTo.Category({
  productId: 'prod-123',
  categoryId: 'cat-789',
})

// Subject: Person, predicate: worksFor, Object: Organization
await $.Person.worksFor.Organization({
  personId: 'person-123',
  organizationId: 'org-456',
  jobTitle: 'Engineer',
})

Actions

// Subject: Email, predicate: send, Object: Message
await $.Email.send.Message({
  to: '[email protected]',
  subject: 'Welcome!',
  body: 'Welcome to our platform',
})

// Subject: Order, predicate: process, Object: Payment
await $.Order.process.Payment({
  orderId: 'order-123',
  amount: 99.99,
  method: 'card',
})

// Subject: Invoice, predicate: generate, Object: PDF
await $.Invoice.generate.PDF({
  invoiceId: 'inv-123',
  format: 'A4',
})

Pattern Categories

1. Creation Patterns

Creating new entities:

// Basic creation
await $.User.create({
  email: '[email protected]',
})

// Creation with relationship
await $.User.create.Account({
  email: '[email protected]',
})

// Nested creation
await $.Organization.create.with.Members({
  name: 'Acme Inc',
  members: [{ email: '[email protected]' }, { email: '[email protected]' }],
})

2. Relationship Patterns

Defining relationships between entities:

// One-to-one
await $.User.has.Profile({ userId, profileId })

// One-to-many
await $.Organization.employs.Person({ organizationId, personId })

// Many-to-many
await $.Person.hasMembership.Organization({ personId, organizationId })

// Hierarchical
await $.Category.hasSubcategory.Category({ parentId, childId })

3. Action Patterns

Performing operations:

// Simple actions
await $.Email.send({ to, subject, body })
await $.Payment.process({ amount, method })
await $.Report.generate({ type, format })

// Chained actions
await $.Order.validate.and.Process({ orderId })
await $.User.verify.and.Activate({ userId })

// Conditional actions
await $.Product.check.Inventory.then.Reserve({ productId, quantity })

4. Query Patterns

Retrieving data:

// Basic query
await $.User.find({ email: '[email protected]' })

// Related query
await $.Organization.list.Members({ organizationId })

// Filtered query
await $.Product.find.by.Category({ categoryId, inStock: true })

// Aggregated query
await $.Order.count.by.Status({ status: 'completed' })

5. State Transition Patterns

Changing entity state:

// Status changes
await $.Order.transition.to.Confirmed({ orderId })
await $.User.transition.from.Inactive.to.Active({ userId })

// Lifecycle events
await $.Subscription.renew({ subscriptionId })
await $.Subscription.cancel({ subscriptionId })
await $.Subscription.upgrade.to.Pro({ subscriptionId })

6. Event Patterns

Responding to events:

// Event handlers
on($.Order.created, async (order) => {
  await $.Email.send.Confirmation({ orderId: order.id })
})

on($.User.registered, async (user) => {
  await $.User.send.WelcomeEmail({ userId: user.id })
})

// Event composition
on([$.User.verified, $.User.paid], async (user) => {
  await $.User.activate({ userId: user.id })
})

Advanced Patterns

Compound Predicates

Chain multiple predicates:

// Multiple actions
await $.Order.validate.and.Process.and.Notify({
  orderId: 'order-123',
})

// Conditional chain
await $.Product.check.Availability.then.Reserve.Inventory.and.Create.Shipment({
  productId: 'prod-123',
  quantity: 5,
})

Contextual Patterns

Add context to operations:

// With context
await $.Email.send.via.SendGrid({
  to: '[email protected]',
  template: 'welcome',
})

// With conditions
await $.Order.process.if.Validated({
  orderId: 'order-123',
})

// With timing
await $.Report.generate.at.EndOfDay({
  type: 'sales',
})

Aggregation Patterns

Aggregate data:

// Counting
await $.Order.count.by.Status({ status: 'completed' })

// Summing
await $.Order.sum.TotalValue.by.Customer({ customerId })

// Averaging
await $.Order.average.Value.by.Month()

// Grouping
await $.User.group.by.Country()

Transformation Patterns

Transform data:

// Format conversion
await $.Invoice.convert.to.PDF({ invoiceId })
await $.Data.export.as.CSV({ datasetId })

// Data enrichment
await $.Lead.enrich.with.CompanyData({ leadId })

// Data processing
await $.Image.resize.to.Thumbnail({ imageId, size: '200x200' })

Naming Conventions

Subject Names

Use singular, capitalized nouns from established vocabularies:

// ✅ Good: Standard Schema.org types
;($.Person, $.Organization, $.Product, $.Order, $.Invoice)

// ✅ Good: Domain-specific types
;($.Subscription, $.Campaign, $.Workflow, $.Agent)

// ❌ Bad: Plural or lowercase
;($.users, $.products, $.orders)

Predicate Names

Use camelCase verbs or relationships:

// ✅ Good: Clear verbs
;($.User.create, $.Email.send, $.Order.process)

// ✅ Good: Relationships
;($.User.belongsTo, $.Product.hasMany, $.Organization.employs)

// ❌ Bad: Unclear or generic
;($.User.do, $.Email.execute, $.Order.handle)

Object Names

Use singular, capitalized nouns:

// ✅ Good: Specific objects
$.Email.send.Message
$.Order.process.Payment
$.User.create.Account

// ❌ Bad: Vague objects
$.Email.send.Thing
$.Order.process.Stuff

Type Safety

Leverage TypeScript for type-safe patterns:

import { Person, Organization } from 'schema.org.ai'

// Type-safe creation
const user: Person = await $.Person.create({
  name: 'John Doe',
  email: '[email protected]',
  jobTitle: 'Engineer',
})

// Type-safe relationships
await $.Person.worksFor.Organization({
  person: user.$id,
  organization: org.$id,
  // TypeScript knows valid properties
  jobTitle: 'Senior Engineer',
  startDate: new Date(),
})

// Type-safe queries
const employees: Person[] = await $.Organization.list.Employees({
  organizationId: org.$id,
})

Pattern Composition

Combine patterns for complex operations:

// Sequential composition
const workflow = $.compose([$.Order.validate, $.Payment.process, $.Inventory.reserve, $.Shipment.create, $.Email.send.Confirmation])

// Parallel composition
const enrichment = $.compose.parallel([$.Lead.verify.Email, $.Lead.lookup.Company, $.Lead.find.SocialProfiles])

// Conditional composition
const approval = $.compose.if((order) => order.total > 1000, $.Order.require.Approval, $.Order.process.Immediately)

Best Practices

Do's

  1. Use established vocabularies

    // ✅ Good: Schema.org types
    $.Person.create({ name: 'John' })
    
    // ❌ Bad: Custom types when standard exists
    $.Human.create({ name: 'John' })
  2. Be explicit and semantic

    // ✅ Good: Clear intent
    $.User.verify.Email({ userId, code })
    
    // ❌ Bad: Vague intent
    $.User.check({ userId, code })
  3. Follow the triple pattern

    // ✅ Good: Subject.predicate.Object
    $.Order.process.Payment({ orderId })
    
    // ❌ Bad: Breaking pattern
    $.processOrderPayment({ orderId })
  4. Use meaningful relationships

    // ✅ Good: Clear relationship
    $.Person.worksFor.Organization
    
    // ❌ Bad: Vague relationship
    $.Person.has.Organization

Don'ts

  1. Don't use generic terms

    // ❌ Bad
    $.Thing.do.Stuff
    
    // ✅ Good
    $.Order.process.Payment
  2. Don't mix abstractions

    // ❌ Bad: Mixing business and technical
    $.User.executeQuery.Database
    
    // ✅ Good: Business-focused
    $.User.find.by.Email
  3. Don't create deep nesting

    // ❌ Bad: Too complex
    $.User.has.Profile.with.Settings.for.Notifications.via.Email
    
    // ✅ Good: Simplified
    $.User.update.EmailNotificationSettings

Pattern Library

Common patterns for reference:

// User management
$.User.create
$.User.update
$.User.delete
$.User.find
$.User.verify.Email
$.User.reset.Password
$.User.activate
$.User.deactivate

// Organization management
$.Organization.create
$.Organization.add.Member
$.Organization.remove.Member
$.Organization.list.Members
$.Organization.update.Settings

// E-commerce
$.Product.create
$.Product.update.Price
$.Product.check.Inventory
$.Order.create
$.Order.process.Payment
$.Order.create.Shipment
$.Cart.add.Item
$.Cart.remove.Item

// Content management
$.BlogPost.create
$.BlogPost.publish
$.BlogPost.unpublish
$.Comment.add.to.BlogPost
$.Image.upload
$.Image.optimize

// Communication
$.Email.send
$.SMS.send
$.Notification.send
$.Newsletter.subscribe

Industry-Specific Patterns

Healthcare Patterns

// Patient management
await $.Patient.register({ name, dateOfBirth, medicalRecordNumber })
await $.Patient.schedule.Appointment({ patientId, providerId, date })
await $.Patient.update.MedicalHistory({ patientId, records })

// Clinical workflows
await $.Provider.prescribe.Medication({ patientId, medication, dosage })
await $.Lab.order.Test({ patientId, testType })
await $.Lab.process.Result({ testId, results })

// Insurance and billing
await $.Insurance.verify.Coverage({ patientId, procedure })
await $.Claim.submit.to.Insurance({ patientId, services })
await $.Payment.process.Copay({ patientId, amount })

// Compliance
await $.Record.access.log({ userId, patientId, action })
await $.Data.encrypt.PHI({ data })
await $.Audit.report.generate({ startDate, endDate })

Financial Services Patterns

// Account management
await $.Account.open({ customerId, accountType, initialDeposit })
await $.Account.transfer.Funds({ from, to, amount })
await $.Account.calculate.Interest({ accountId })

// Transactions
await $.Transaction.authorize({ accountId, amount, merchant })
await $.Transaction.settle({ transactionId })
await $.Transaction.dispute({ transactionId, reason })

// Compliance and risk
await $.Transaction.screen.for.Fraud({ transactionId })
await $.Customer.perform.KYC({ customerId })
await $.Report.file.SAR({ transactionId, reason })

// Investments
await $.Portfolio.add.Security({ portfolioId, symbol, shares })
await $.Portfolio.rebalance({ portfolioId, strategy })
await $.Trade.execute({ symbol, quantity, orderType })

Manufacturing Patterns

// Production planning
await $.WorkOrder.create({ productId, quantity, dueDate })
await $.WorkOrder.schedule.on.Line({ workOrderId, lineId })
await $.Material.allocate.to.WorkOrder({ workOrderId, materials })

// Quality control
await $.Inspection.perform({ workOrderId, inspectionType })
await $.Defect.record({ workOrderId, defectType, severity })
await $.Product.quarantine({ productId, reason })

// Inventory management
await $.RawMaterial.receive({ purchaseOrderId, quantity })
await $.FinishedGoods.transfer.to.Warehouse({ workOrderId })
await $.Inventory.adjust({ itemId, quantity, reason })

// Equipment maintenance
await $.Equipment.schedule.Maintenance({ equipmentId, maintenanceType })
await $.Equipment.record.Downtime({ equipmentId, duration, reason })
await $.Equipment.track.Performance({ equipmentId, metrics })

Education Patterns

// Student management
await $.Student.enroll.in.Course({ studentId, courseId })
await $.Student.submit.Assignment({ studentId, assignmentId, submission })
await $.Student.take.Exam({ studentId, examId })

// Grading and assessment
await $.Assignment.grade({ assignmentId, studentId, score, feedback })
await $.Exam.score({ examId, studentId, answers })
await $.Student.calculate.GPA({ studentId, semester })

// Course management
await $.Course.create({ title, description, credits })
await $.Course.assign.Instructor({ courseId, instructorId })
await $.Course.publish.Schedule({ courseId, meetings })

// Learning analytics
await $.Student.track.Progress({ studentId, courseId })
await $.Course.analyze.Completion({ courseId })
await $.Institution.generate.Report({ type, period })

Real Estate Patterns

// Property management
await $.Property.list({ address, price, features })
await $.Property.schedule.Showing({ propertyId, date, agentId })
await $.Property.receive.Offer({ propertyId, buyerId, amount })

// Transactions
await $.Offer.accept({ offerId })
await $.Inspection.schedule({ propertyId, inspectorId })
await $.Title.search({ propertyId })

// Lease management
await $.Lease.create({ propertyId, tenantId, terms })
await $.Rent.collect({ leaseId, amount })
await $.Maintenance.request({ propertyId, issue })

// Market analysis
await $.Property.estimate.Value({ propertyId, method })
await $.Market.analyze.Trends({ area, period })
await $.Comparable.find({ propertyId, criteria })

Anti-Patterns

What to Avoid

// ❌ Bad: Technical implementation details
$.executeQuery.Database
$.sendHTTPRequest.API
$.writeFile.Filesystem

// ✅ Good: Business operations
$.Customer.find
$.Order.process
$.Invoice.generate

// ❌ Bad: Ambiguous operations
$.Thing.do
$.Item.handle
$.Data.process

// ✅ Good: Specific operations
$.Order.validate
$.Payment.process
$.Email.send

// ❌ Bad: Mixing abstractions
$.User.saveToDatabase
$.Order.serializeToJSON
$.Product.renderHTML

// ✅ Good: Consistent abstraction level
$.User.save
$.Order.create
$.Product.display

// ❌ Bad: Redundant information
$.Customer.createCustomer
$.Order.processOrder
$.User.deleteUser

// ✅ Good: Concise patterns
$.Customer.create
$.Order.process
$.User.delete

// ❌ Bad: Language-specific patterns
$.users.forEach
$.orders.map
$.products.filter

// ✅ Good: Domain-focused patterns
$.User.list
$.Order.findAll
$.Product.filter

Pattern Evolution

Version Migration

Handle pattern evolution gracefully:

// Version 1.0: Original pattern
await $.Order.create({ items, customer })

// Version 2.0: Enhanced pattern
await $.Order.create.with.Validation({ items, customer })

// Maintain backward compatibility
const createOrder = async (data: any, options?: any) => {
  if (options?.validate) {
    return await $.Order.create.with.Validation(data)
  }
  return await $.Order.create(data)
}

// Deprecation strategy
/**
 * @deprecated Use $.Order.create.with.Validation instead
 * Will be removed in version 3.0
 */
const legacyCreateOrder = async (data: any) => {
  console.warn('$.Order.create is deprecated. Use $.Order.create.with.Validation')
  return await $.Order.create.with.Validation(data)
}

Pattern Refactoring

Refactor patterns while maintaining compatibility:

// Old pattern (v1.x)
await $.User.sendEmail({ userId, subject, body })

// New pattern (v2.x)
await $.Email.send.to.User({ userId, subject, body })

// Compatibility layer
const v1Compat = {
  User: {
    sendEmail: (data: any) => {
      return $.Email.send.to.User(data)
    },
  },
}

// Gradual migration
if (config.useV1Patterns) {
  await v1Compat.User.sendEmail(data)
} else {
  await $.Email.send.to.User(data)
}

Pattern Documentation

Self-Documenting Patterns

Make patterns self-explanatory:

// ✅ Good: Intent is clear
$.Invoice.mark.as.Paid
$.Subscription.cancel.with.Refund
$.Product.apply.Discount.of.Percentage

// ❌ Bad: Requires explanation
$.Invoice.update({ status: 'paid' })
$.Subscription.delete({ refund: true })
$.Product.modify({ discount: '10%' })

// Document with types
interface CreateOrderParams {
  /** Customer who is placing the order */
  customerId: string

  /** Line items in the order */
  items: OrderItem[]

  /** Shipping address for the order */
  shippingAddress: Address

  /** Optional promotional code */
  promoCode?: string
}

await $.Order.create(params: CreateOrderParams)

Pattern Discovery

Help developers discover patterns:

// Pattern registry
const PatternRegistry = {
  // User patterns
  user: {
    lifecycle: [
      '$.User.create',
      '$.User.activate',
      '$.User.suspend',
      '$.User.delete',
    ],
    authentication: [
      '$.User.login',
      '$.User.logout',
      '$.User.reset.Password',
      '$.User.verify.Email',
    ],
  },

  // Order patterns
  order: {
    lifecycle: [
      '$.Order.create',
      '$.Order.confirm',
      '$.Order.fulfill',
      '$.Order.complete',
      '$.Order.cancel',
    ],
    operations: [
      '$.Order.add.Item',
      '$.Order.remove.Item',
      '$.Order.update.Quantity',
      '$.Order.apply.Discount',
    ],
  },
}

// Pattern search
const findPatterns = (category: string, subcategory: string) => {
  return PatternRegistry[category]?.[subcategory] || []
}

// Usage
const userLifecyclePatterns = findPatterns('user', 'lifecycle')

Pattern Generation

AI-Assisted Pattern Creation

Generate patterns from natural language:

const generatePattern = async (description: string) => {
  const prompt = `
    Convert this business operation into a semantic pattern:
    "${description}"

    Format: $.Subject.predicate.Object

    Examples:
    - "Send an email to a customer" -> $.Email.send.to.Customer
    - "Create a new order for a user" -> $.Order.create.for.User
    - "Process a payment for an invoice" -> $.Payment.process.for.Invoice
  `

  const pattern = await ai.generate({
    model: 'gpt-5',
    prompt,
    temperature: 0,
  })

  return pattern
}

// Usage
const pattern = await generatePattern('Calculate shipping cost for an order')
// Returns: $.Shipping.calculate.Cost.for.Order

Pattern Validation

Validate patterns for consistency:

const validatePattern = (pattern: string): ValidationResult => {
  const parts = pattern.split('.')

  // Check format
  if (!parts[0] === '$') {
    return { valid: false, error: 'Pattern must start with $' }
  }

  // Check capitalization
  if (parts[1] && parts[1][0] !== parts[1][0].toUpperCase()) {
    return { valid: false, error: 'Subject must be capitalized' }
  }

  // Check predicate
  if (parts[2] && parts[2][0] !== parts[2][0].toLowerCase()) {
    return { valid: false, error: 'Predicate must be lowercase' }
  }

  // Check object
  if (parts[3] && parts[3][0] !== parts[3][0].toUpperCase()) {
    return { valid: false, error: 'Object must be capitalized' }
  }

  return { valid: true }
}

// Usage
validatePattern('$.User.create.Account') // ✅ valid
validatePattern('$.user.Create.account') // ❌ invalid

Pattern Performance

Optimizing Pattern Execution

Cache pattern resolution:

const patternCache = new Map()

const executePattern = async (pattern: string, data: any) => {
  // Check cache
  let handler = patternCache.get(pattern)

  if (!handler) {
    // Resolve pattern to handler
    handler = resolvePattern(pattern)
    patternCache.set(pattern, handler)
  }

  // Execute handler
  return await handler(data)
}

// Pattern resolution
const resolvePattern = (pattern: string) => {
  const parts = pattern.split('.')

  // Navigate pattern tree
  let current = $
  for (const part of parts.slice(1)) {
    current = current[part]
  }

  return current
}

Batch Pattern Execution

Execute multiple patterns efficiently:

const executeBatch = async (operations: Array<{ pattern: string; data: any }>) => {
  // Group by pattern
  const grouped = operations.reduce((acc, op) => {
    if (!acc[op.pattern]) acc[op.pattern] = []
    acc[op.pattern].push(op.data)
    return acc
  }, {} as Record<string, any[]>)

  // Execute each pattern with all its data
  const results = await Promise.all(
    Object.entries(grouped).map(async ([pattern, dataArray]) => {
      const handler = resolvePattern(pattern)

      // Batch execution if supported
      if (handler.batch) {
        return await handler.batch(dataArray)
      }

      // Fall back to individual execution
      return await Promise.all(dataArray.map((data) => handler(data)))
    })
  )

  return results.flat()
}

// Usage
await executeBatch([
  { pattern: '$.Email.send', data: { to: '[email protected]', subject: 'Welcome' } },
  { pattern: '$.Email.send', data: { to: '[email protected]', subject: 'Welcome' } },
  { pattern: '$.SMS.send', data: { to: '+1234567890', message: 'Hello' } },
])

Pattern Analytics

Track Pattern Usage

Monitor pattern usage:

const PatternAnalytics = {
  usage: new Map<string, number>(),

  track: (pattern: string) => {
    const count = PatternAnalytics.usage.get(pattern) || 0
    PatternAnalytics.usage.set(pattern, count + 1)
  },

  getTopPatterns: (limit: number = 10) => {
    return Array.from(PatternAnalytics.usage.entries())
      .sort((a, b) => b[1] - a[1])
      .slice(0, limit)
  },

  getPatternStats: () => {
    const total = Array.from(PatternAnalytics.usage.values()).reduce(
      (sum, count) => sum + count,
      0
    )

    return {
      totalPatterns: PatternAnalytics.usage.size,
      totalExecutions: total,
      averageExecutions: total / PatternAnalytics.usage.size,
      topPatterns: PatternAnalytics.getTopPatterns(),
    }
  },
}

// Middleware to track patterns
const withTracking = (pattern: string, handler: Function) => {
  return async (...args: any[]) => {
    PatternAnalytics.track(pattern)
    return await handler(...args)
  }
}

Pattern Coverage

Measure pattern coverage:

const PatternCoverage = {
  defined: new Set<string>(),
  used: new Set<string>(),

  register: (pattern: string) => {
    PatternCoverage.defined.add(pattern)
  },

  use: (pattern: string) => {
    PatternCoverage.used.add(pattern)
  },

  getCoverage: () => {
    const coverage = (PatternCoverage.used.size / PatternCoverage.defined.size) * 100

    return {
      defined: PatternCoverage.defined.size,
      used: PatternCoverage.used.size,
      unused: PatternCoverage.defined.size - PatternCoverage.used.size,
      coverage: `${coverage.toFixed(2)}%`,
      unusedPatterns: Array.from(PatternCoverage.defined).filter(
        (p) => !PatternCoverage.used.has(p)
      ),
    }
  },
}

Pattern Testing

Test Pattern Behavior

Ensure patterns work correctly:

import { describe, it, expect } from 'vitest'

describe('Semantic Patterns', () => {
  describe('$.User.create', () => {
    it('should create a new user', async () => {
      const user = await $.User.create({
        email: '[email protected]',
        name: 'Test User',
      })

      expect(user).toHaveProperty('$id')
      expect(user.$type).toBe('Person')
      expect(user.email).toBe('[email protected]')
    })

    it('should validate required fields', async () => {
      await expect(
        $.User.create({
          // Missing email
          name: 'Test User',
        })
      ).rejects.toThrow('Email is required')
    })
  })

  describe('$.Order.process.Payment', () => {
    it('should process payment for valid order', async () => {
      const order = await $.Order.create({
        items: [{ productId: 'prod-1', quantity: 1 }],
        total: 99.99,
      })

      const payment = await $.Order.process.Payment({
        orderId: order.$id,
        method: 'credit_card',
      })

      expect(payment.status).toBe('success')
    })

    it('should handle payment failures', async () => {
      const order = await $.Order.create({
        items: [],
        total: 0,
      })

      const payment = await $.Order.process.Payment({
        orderId: order.$id,
        method: 'invalid_method',
      })

      expect(payment.status).toBe('failed')
    })
  })
})

Next Steps


Pattern Tip: Great semantic patterns are clear, consistent, and meaningful. When in doubt, choose the pattern that best expresses the business intent.