.do

Introduction to Semantic Patterns

Why $.Subject.predicate.Object patterns matter for Business-as-Code

TL;DR: Semantic patterns let you write code that reads like natural language, making it self-documenting and AI-understandable. The $.Subject.predicate.Object pattern is the foundation of everything in the .do platform.

The Problem with Traditional APIs

Traditional APIs require developers to learn arbitrary naming conventions, endpoint structures, and parameter formats. Consider these three different ways to express the same concept:

REST API

// POST /api/v1/organizations/{orgId}/employees
fetch('/api/v1/organizations/org-123/employees', {
  method: 'POST',
  body: JSON.stringify({
    person_id: 'per-456',
    job_title: 'Engineer',
    start_date: '2025-01-01',
  }),
})

Issues:

  • URL structure is arbitrary (/organizations/{id}/employees vs /employees?organization={id})
  • HTTP verb meanings are overloaded (POST for create vs trigger)
  • Parameter naming is inconsistent (person_id vs personId vs employeeId)
  • Intent is not immediately clear

GraphQL

mutation AddEmployee($input: AddEmployeeInput!) {
  addEmployee(input: $input) {
    employee {
      id
      person {
        name
      }
      organization {
        name
      }
    }
  }
}

Issues:

  • Requires separate schema definition
  • Mutation names are arbitrary (addEmployee vs createEmployee vs employPerson)
  • Relationship structure is implicit
  • No semantic meaning beyond field names

Traditional Function Call

// Traditional imperative code
const result = await employeeService.createEmployment({
  organizationId: 'org-123',
  personId: 'per-456',
  role: 'Engineer',
  startDate: new Date('2025-01-01'),
})

Issues:

  • Service and method names are arbitrary
  • No standard vocabulary
  • Relationship between concepts is hidden in parameter names
  • Not self-documenting

The Semantic Pattern Solution

With semantic patterns, the code expresses the business relationship directly:

// Semantic pattern
await $.Organization.employs.Person({
  organization: orgId,
  person: personId,
  jobTitle: 'Engineer',
  startDate: new Date('2025-01-01'),
})

Benefits:

  • ✅ Reads like English: "Organization employs Person"
  • ✅ Self-documenting: The pattern itself explains what it does
  • ✅ Type-safe: TypeScript validates subjects, predicates, and objects
  • ✅ AI-understandable: Based on RDF semantic web standards
  • ✅ Discoverable: Autocomplete suggests valid predicates
  • ✅ Consistent: Same pattern everywhere in your codebase

How Semantic Patterns Work

The Semantic Triple

Every semantic pattern is a triple consisting of three parts:

Subject --predicate--> Object

This structure comes from:

  1. Linguistics: Subject-Verb-Object sentence structure (used in 87%+ of languages)
  2. Semantic Web: RDF (Resource Description Framework) triples
  3. Knowledge Graphs: How information is represented for AI reasoning

Real-World Example: E-Commerce

Let's model a simple e-commerce scenario using semantic patterns:

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

// 1. Create entities
const customer = await db.create($.Person, {
  givenName: 'Alice',
  familyName: 'Smith',
  email: '[email protected]',
})

const product = await db.create($.Product, {
  name: 'Widget Pro',
  price: 29.99,
  brand: 'Acme',
})

// 2. Customer places order
const order = await db.create($.Order, {
  orderNumber: 'ORD-001',
  orderDate: new Date(),
})

// 3. Create relationships using semantic predicates
await db.relate(customer, $.places, order)
await db.relate(order, $.contains, product)

// 4. React to events using semantic patterns
on.Order.created, async (order) => {
  // Send confirmation email
  send.Email.sent, {
    to: order.customer.email,
    template: 'order-confirmation',
    data: { order },
  })

  // Update inventory
  send.Inventory.decremented, {
    product: order.items[0].product,
    quantity: order.items[0].quantity,
  })

  // Create shipment
  send.Shipment.created, {
    order: order.id,
    carrier: 'USPS',
  })
})

Notice how every operation uses semantic patterns:

  • $.Person, $.Product, $.Order - Entities (Subjects/Objects)
  • $.places, $.contains - Relationships (Predicates)
  • $.Order.created, $.Email.sent - Events (Subject.pastVerb)
  • $.Inventory.decremented, $.Shipment.created - State changes

Key Advantages

1. Self-Documenting Code

// What does this do? You have to read the implementation.
await processUserOrder(userId, orderId, options)

// vs.

// Crystal clear: Customer places Order
await $.Customer.places.Order({
  customer: userId,
  order: orderId,
})

2. Natural Language Alignment

// How humans think:
// "A warehouse receives products from a supplier"

// How you code it:
await $.Warehouse.receives.Product.from.Supplier({
  warehouse: warehouseId,
  product: productId,
  supplier: supplierId,
  quantity: 500,
})

// The code reads exactly like the business requirement!

3. AI Understanding

AI models are trained on trillions of tokens of text that use subject-verb-object structure. When you use semantic patterns:

  • ChatGPT/Claude can understand your code without custom training
  • GitHub Copilot suggests semantically correct completions
  • AI Agents can reason about your business logic
  • Code generation produces semantically consistent patterns

4. Type Safety & Autocomplete

TypeScript's type system combined with the $ proxy provides:

import $ from 'sdk.do'

// Autocomplete shows all Schema.org types
$.Person.     // ← suggests: worksFor, knows, owns, memberOf, etc.
$.Organization.  // ← suggests: employs, owns, publishes, sponsors, etc.
$.Product.    // ← suggests: manufacturer, brand, offers, etc.

// Compile-time validation
await $.Organization.employs.Person({  // ✓ Valid
  organization: orgId,
  person: personId
})

await $.Organization.employs.Product({  // ✗ Type error!
  // Error: Product cannot be employed by Organization
})

5. Discoverability

With semantic patterns, discovering API capabilities is natural:

// Traditional: Have to read docs or search codebase
orderService.???  // What methods are available?

// Semantic: Explore through natural language
$.Order.      // suggests: create, update, cancel, fulfill, ship, etc.
$.Order.contains.   // suggests: Product, Service, Offer, etc.
$.Order.sentTo.     // suggests: Person, Organization, PostalAddress, etc.

Comparison with Alternatives

FeatureRESTGraphQLSPARQLSemantic Patterns
Learning CurveLowMediumHighVery Low
Self-DocumentingNoPartialPartialYes
Type SafetyRuntimeSchemaRuntimeCompile-time
Natural LanguageNoNoNoYes
AI-UnderstandablePartialPartialYesYes
Tooling SupportOpenAPIGraphQL toolsRDF toolsNative TS
Semantic WebNoNoYesYes
Developer ExperienceGoodGoodPoorExcellent

When to Use Semantic Patterns

Perfect For

Business-as-Code - Modeling business entities and their relationships ✅ AI-Native Applications - Code that AI agents can understand and generate ✅ Domain-Driven Design - Expressing domain concepts clearly ✅ Event-Driven Architectures - Semantic events are self-describing ✅ Knowledge Graphs - Building interconnected data models ✅ Multi-System Integration - Shared vocabulary across systems

Less Ideal For

⚠️ Low-Level System Code - Use traditional functions for bit manipulation, etc. ⚠️ Performance-Critical Paths - The proxy adds minimal overhead, but measure first ⚠️ Purely Mathematical Operations - Math.sqrt() is clearer than $.Number.sqrt

Getting Started

Installation

npm install sdk.do
# or
pnpm add sdk.do

Basic Usage

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

// Create entities
const org = await db.create($.Organization, {
  name: 'Acme Inc',
  industry: 'Technology',
})

const person = await db.create($.Person, {
  givenName: 'Bob',
  familyName: 'Johnson',
  email: '[email protected]',
})

// Create relationship
await db.relate(org, $.employs, person)

// Query relationships
const employees = await db.related(org, $.employs, $.Person)
console.log(employees) // [{ givenName: 'Bob', ... }]

Next Steps

  1. Learn Linguistic Foundations - Understand SVO structure and parts of speech (coming soon - issue #7035)
  2. Explore GraphDL Basics - Master the $ proxy and casing conventions (coming soon - issue #7037)
  3. Try Pattern Types - Discover 10 core pattern categories (coming soon - issue #7040)
  4. See Real Examples - Hands-on tutorials and use cases (coming soon)

Community & Support


Philosophy: Good semantic patterns are like good sentences - clear, concise, and meaningful. When in doubt, choose the pattern that best expresses the business intent.