Skip to content
context-witness logo

Context Witness Pattern

context-witness

Decide between Context Tag witness and capability patterns for dependency injection, understanding coupling trade-offs

SKILL.md

Full skill instructions

Context Witness Pattern

Choose between witness (existence) and capability (behavior) patterns for Context Tags.

Coupling: Hard vs Soft

Some coupling is necessary and good - but move it from hard to soft coupling.

Hard Coupling (Schema)

Field exists in the schema - tightly coupled to domain model:

// ❌ HARD COUPLING - Serial is part of the schema
export const PaymentIntent = Schema.Struct({
  id: Schema.String,
  serial: Schema.String,  // In schema = hard coupled
  amount: Schema.BigInt
})

// Every PaymentIntent MUST have a serial
// Serialization/​validation requires serial
// Cannot create without providing serial
// Schema change needed to remove/​change serial

Soft Coupling (Witness)

Field removed from schema, only injected in code:

// ✅ SOFT COUPLING - Serial not in schema
export const PaymentIntent = Schema.Struct({
  id: Schema.String,
  amount: Schema.BigInt
  // No serial field!
})

// Serial is a witness - required but injected via Context
class Serial extends Context.Tag("Serial")<Serial, string>() {}

const createPaymentIntent = (amount: bigint) =>
  Effect.gen(function* () {
    const serial = yield* Serial  // Injected from context

    // Use serial in business logic, logging, etc.
    // but it's not part of the persisted data
    yield* Logger.info(`Creating payment intent ${serial}`)

    return PaymentIntent.make({ id: generateId(), amount })
  })

// Type: Effect<PaymentIntent, never, Serial>

Key insight: schema (hard coupling) => witness (soft coupling)

By removing the field from the schema and injecting it only where needed, you:

  • Keep domain models minimal
  • Avoid unnecessary persistence
  • Easy to test (provide test serial)
  • Easy to remove/​change (just change injection)
  • Explicit dependencies in type signature

When to use witnesses:

  • Correlation IDs (for tracing, not persistence)
  • Request IDs (for logging, not data)
  • Transaction contexts (for coordination, not storage)
  • Tenant/​Region markers (for routing, not schema)

Witness: Existence Only

Use when you only need to know something exists in the environment:

// Witness - a serial number exists
export class Serial extends Context.Tag("Serial")<Serial, string>() {}

const createPaymentIntent = Effect.gen(function* () {
  const serial = yield* Serial  // Pull from environment
  return PaymentIntent.make({ serial, ...other })
})

// Type: Effect<PaymentIntent, never, Serial>

Capability: Behavior

Use when you need operations:

// Capability - can generate/​validate
export class SerialService extends Context.Tag("SerialService")<
  SerialService,
  {
    readonly next: () => string
    readonly validate: (s: string) => boolean
  }
>() {}

const createPaymentIntent = Effect.gen(function* () {
  const svc = yield* SerialService
  const serial = svc.next()  // Behavior
  return PaymentIntent.make({ serial, ...other })
})

// Type: Effect<PaymentIntent, never, SerialService>

Decision Framework

NeedPattern
Just presence/​valueWitness
Operations/​generationCapability
Precondition markerWitness
Side effectsCapability
Multiple implementationsCapability
Mocking behaviorCapability
Correlation IDWitness
Transaction contextWitness
LoggerCapability
DatabaseCapability

When to Use Witness

Good fits:

  • Request ID - must exist for tracing
  • Transaction context - must be established
  • Tenant/​Region - required for data boundary
  • Pre-validated tokens - already verified

When to Use Capability

Good fits:

  • Serial generation - create/​validate operations
  • Clock - now() operation
  • Logger - structured logging methods
  • Database - query/​transact operations
  • HTTP clients - fetch/​post operations

Testing Implications

Witnesses are trivial to provide:

const test = myProgram.pipe(
  Effect.provideService(Serial, "test-serial-123")
)

Capabilities need implementation:

const test = myProgram.pipe(
  Effect.provideService(SerialService, {
    next: () => "test-serial-123",
    validate: () => true
  })
)

Coupling Strategy

Rule of thumb: Remove non-essential fields from schema, inject via witness instead.

Ask yourself: Does this need to be persisted/​serialized?

  • No → Remove from schema, inject via witness
  • Yes → Keep in schema
// ✅ Domain model - only persisted data
export const Order = Schema.Struct({
  id: Schema.String,
  items: Schema.Array(LineItem),
  total: Schema.BigInt
  // No correlationId - not persisted!
  // No timestamp - derived from system!
})

// Witnesses for runtime context
class CorrelationId extends Context.Tag("CorrelationId")<CorrelationId, string>() {}
class RequestId extends Context.Tag("RequestId")<RequestId, string>() {}

// Use in code, not in data
const createOrder = (items: Array<LineItem>) =>
  Effect.gen(function* () {
    const correlationId = yield* CorrelationId  // For tracing
    const requestId = yield* RequestId          // For logging
    const clock = yield* Clock                  // For timestamp

    yield* Logger.info({
      message: "Creating order",
      correlationId,    // Used for tracing
      requestId,        // Used for logging
      timestamp: Clock.currentTimeMillis(clock)
    })

    // Data only contains what's persisted
    return Order.make({
      id: generateId(),
      items,
      total: calculateTotal(items)
    })
  })

// Type: Effect<Order, never, CorrelationId | RequestId | Clock>

Benefits:

  • Minimal schemas (only persisted data)
  • Context values available when needed
  • Easy to test with different context
  • Can add/​remove context without schema changes
  • Explicit dependencies in type signatures

Choose witness for simplicity, capability for flexibility.

More skills from majiayu000

xiaohongshu logo
majiayu000/claude-arsenal

xiaohongshu

xiaohongshu

286 148
View
agent-task-conductor logo
majiayu000/claude-skill-registry

agent-task-conductor

Conduct multi-agent task orchestration and workflow coordination.

663 1
View
conductor-setup logo
majiayu000/claude-skill-registry

conductor-setup

Initialize project with Conductor artifacts (product definition,

663 1
View
animation-designer logo
majiayu000/claude-skill-registry

animation-designer

Expert in web animations, transitions, and motion design using Framer Motion and CSS

663 1
View
diagramming logo
majiayu000/claude-skill-registry

diagramming

Creates Mermaid and ASCII diagrams for flowcharts, architecture, ERDs, state machines, mindmaps, and more. Use when user mentions diagram, flowchart, mermaid, ASCII diagram, text diagram, terminal diagram, visualize, C4, mindmap, architecture diagram, sequence diagram, ERD, or needs visual docume...

663 1
View
h3-pg logo
majiayu000/claude-skill-registry-data

h3-pg

PostgreSQL bindings for H3 hexagonal grid system. Use when working with H3 cells in Postgres, including spatial indexing, geometry/geography integration, and raster analysis.

23 1
View
conductor-development logo
majiayu000/claude-skill-registry

conductor-development

Context-Driven Development skill for projects using Conductor. Use this skill when you detect a `conductor/` directory in the project, when working on tasks defined in a `plan.md` file, or when the user asks about tracks, specs, or plans. Automatically applies TDD workflow, tracks task completion...

663 1
View
conductor-status logo
majiayu000/claude-skill-registry

conductor-status

Display project status, active tracks, and next actions

663 1
View
dockerization logo
majiayu000/claude-skill-registry

dockerization

Official Stakpak application containerization standard operating procedure, a step-by-step guidline to properly dockerize applications. This is a rule book curated by the Stakpak Team.

663 1
View

Popular AI tools

Kaiber logo
Video

Kaiber

Generate, edit, and beat-sync AI video with leading models in one workspace.

Paid
View
Vimcal logo
Productivity

Vimcal

The world's fastest calendar for remote work

Free
View

Transform Your Design with AI Designer by ImgCreator.ai

Freemium
View
Akool AI logo
Content & writing

Akool AI

Revolutionizing Video Production with AI-Powered Creativity

Paid
View

Extend an image past the frame and let AI fill the new aspect ratio.

Freemium
View
StarByFace logo
Security

StarByFace

Discover your celebrity doppelgänger with StarByFace!

Free
View
C

ChainClarity explains 700+ crypto whitepapers in plain English, with layered summaries, comparisons, research tools, alerts, and a $4.99 Pro plan.

Freemium
View
Opus Clip logo
Coding & apps

Opus Clip

Opus.ai: Revolutionize Your Web Experience

Free
View