Skip to main content

Work Order QMS Module — Domain Event Catalog

Classification: Internal — Engineering
Date: 2026-02-13
Artifact: 73 of WO System Series
Status: Proposed
Source Artifacts: 13-tdd.md §1.2, 26-agent-message-contracts.md §5, 67-integration-api-strategy.md §4, 71-api-endpoint-specification.md §10


1. Event Architecture Overview

The WO system is event-driven. Every state mutation emits a domain event to the NATS JetStream event bus. Events serve five purposes: audit trail generation, agent orchestration dispatch, webhook delivery to integrations, real-time UI updates, and observability instrumentation.

1.1 Event Flow

Producer (API / Agent / Scheduler)


NATS JetStream (persistent, ordered per subject)

├──► Audit Trail Writer (mandatory consumer — never skips)
├──► Agent Orchestrator (dispatch agent tasks)
├──► Webhook Dispatcher (outbound to integrations)
├──► Notification Service (UI + email)
├──► Compliance Engine (policy evaluation)
└──► Metrics Collector (observability)

1.2 Event Envelope

Every event follows a standard envelope:

interface DomainEvent<T> {
id: string; // UUID v7 (time-ordered)
type: string; // e.g., "work_order.status_changed"
version: string; // Schema version (e.g., "1.0")
timestamp: string; // ISO 8601, server UTC
source: string; // "wo-api" | "wo-agents" | "wo-scheduler" | "wo-compliance"
tenantId: string; // Tenant isolation key
correlationId: string; // Request trace ID
causationId: string; // ID of the event or command that caused this event
actor: {
id: string; // User or agent ID
type: "HUMAN" | "AGENT" | "SYSTEM";
role: string; // RBAC role at time of action
};
data: T; // Event-specific payload
metadata: {
dataClassification: "L0" | "L1" | "L2" | "L3" | "L4";
regulatory: boolean; // Whether this event is compliance-relevant
auditRequired: boolean; // Whether audit trail entry is mandatory
};
}

1.3 NATS Subject Hierarchy

wo.{tenant_id}.workorder.{event_type}
wo.{tenant_id}.approval.{event_type}
wo.{tenant_id}.compliance.{event_type}
wo.{tenant_id}.agent.{event_type}
wo.{tenant_id}.resource.{event_type}
wo.{tenant_id}.system.{event_type}

Examples:
wo.tenant_abc.workorder.created
wo.tenant_abc.workorder.status_changed
wo.tenant_abc.approval.decision_submitted
wo.tenant_abc.agent.task_dispatched
wo.tenant_abc.compliance.violation_detected

1.4 Delivery Guarantees

PropertyGuaranteeImplementation
OrderingPer-subject (per tenant + entity type)NATS JetStream stream per subject
DeliveryAt-least-onceConsumer acknowledgment required
DurabilityPersistent (survives NATS restart)JetStream file storage backend
DeduplicationBy event.id (UUID v7)Consumer-side idempotency check
Retention7 days in stream; indefinite in audit trailStream config + audit writer
Dead letterAfter 5 retries with exponential backoffDLQ subject + alerting

2. Work Order Events

2.1 work_order.created

PropertyValue
Producerwo-api, wo-scheduler, wo-agents
ConsumersAudit Writer, Agent Orchestrator, Webhook Dispatcher, Notification Service
Data ClassificationL2 (Internal) or L3 (Confidential) if regulatory
Audit RequiredYes
ComplianceFDA §11.10(e) — audit trail for record creation
interface WorkOrderCreated {
workOrderId: string;
type: WorkOrderType;
regulatory: boolean;
priority: Priority;
title: string;
assetId: string | null;
masterId: string | null;
dependsOn: string[];
scheduledStart: string | null;
scheduledEnd: string | null;
}

2.2 work_order.status_changed

PropertyValue
Producerwo-api, wo-agents
ConsumersAll consumers
Data ClassificationL2/L3
Audit RequiredYes
ComplianceFDA §11.10(e)(f) — audit trail + sequencing enforcement
interface WorkOrderStatusChanged {
workOrderId: string;
previousStatus: WorkOrderStatus;
newStatus: WorkOrderStatus;
reason: string | null; // Required if regulatory
guardsEvaluated: string[]; // Guard names that passed
guardsFailed: string[]; // Empty if transition succeeded
version: number; // Post-transition version
}

2.3 work_order.updated

PropertyValue
Producerwo-api
ConsumersAudit Writer, Notification Service, Webhook Dispatcher
Audit RequiredYes
interface WorkOrderUpdated {
workOrderId: string;
changedFields: Array<{
field: string;
previousValue: any;
newValue: any;
}>;
version: number;
}

2.4 work_order.blocked

PropertyValue
Producerwo-api, wo-agents
ConsumersAgent Orchestrator (escalation), Notification Service (alert), Webhook Dispatcher
Audit RequiredYes
interface WorkOrderBlocked {
workOrderId: string;
masterId: string | null;
blockReason: string;
blockedBy: string[]; // Dependency WO IDs if dependency-blocked
estimatedUnblockDate: string | null;
}

2.5 work_order.completed

PropertyValue
Producerwo-api
ConsumersAll consumers
ComplianceTriggers Master WO progress recalculation if linked
interface WorkOrderCompleted {
workOrderId: string;
masterId: string | null;
completedAt: string;
actualDurationHours: number;
estimatedDurationHours: number;
variancePercent: number;
}

2.6 work_order.closed

PropertyValue
Producerwo-api
ConsumersAudit Writer, Metrics Collector, Webhook Dispatcher
ComplianceFinal compliance summary generated; record becomes immutable
interface WorkOrderClosed {
workOrderId: string;
closedAt: string;
totalDurationHours: number;
approvalCount: number;
linkedWOCount: number;
complianceSummary: {
auditEntries: number;
signatures: number;
deviations: number;
capaRequired: boolean;
};
}

3. Approval Events

3.1 approval.requested

interface ApprovalRequested {
approvalId: string;
workOrderId: string;
approverId: string;
role: ApprovalRole;
dueDate: string;
escalationDate: string | null;
}

Consumers: Notification Service (sends approval request notification), Agent Orchestrator (if agent-assigned approval)

3.2 approval.decision_submitted

interface ApprovalDecisionSubmitted {
approvalId: string;
workOrderId: string;
approverId: string;
decision: "APPROVED" | "REJECTED" | "RETURNED_FOR_REVISION";
comments: string | null;
signatureId: string | null; // Present for regulatory WOs
signatureVerified: boolean;
}

Compliance: FDA §11.50/§11.70 — signature manifestation and record linking verified.

3.3 approval.escalated

interface ApprovalEscalated {
approvalId: string;
workOrderId: string;
originalApproverId: string;
escalatedToId: string;
reason: "OVERDUE" | "DELEGATION" | "RISK_ESCALATION";
originalDueDate: string;
}

4. Compliance Events

4.1 compliance.violation_detected

PropertyValue
Producerwo-compliance
ConsumersAudit Writer, Notification Service (immediate alert), Agent Orchestrator (auto-remediation)
Data ClassificationL4 (Regulated)
Audit RequiredYes
ComplianceTriggers CAPA assessment if severity ≥ HIGH
interface ComplianceViolationDetected {
violationId: string;
workOrderId: string | null;
regulation: "FDA_21_CFR_11" | "HIPAA" | "SOC2" | "GDPR";
requirement: string; // e.g., "§11.10(e)"
severity: "LOW" | "MEDIUM" | "HIGH" | "CRITICAL";
description: string;
recommendedAction: string;
autoRemediable: boolean;
}

4.2 compliance.audit_trail_integrity_check

interface AuditTrailIntegrityCheck {
checkId: string;
scope: "FULL" | "INCREMENTAL";
entriesVerified: number;
chainIntact: boolean;
brokenLinks: Array<{
entryId: string;
expectedHash: string;
actualHash: string;
}>;
verifiedAt: string;
}

If chainIntact: false: P0 incident triggered per 66-operational-readiness.md §9.4.

4.3 compliance.signature_verified

interface SignatureVerified {
signatureId: string;
workOrderId: string;
signerId: string;
verificationResult: "VALID" | "INVALID" | "EXPIRED_KEY";
hashMatch: boolean;
certificateValid: boolean;
}

4.4 compliance.phi_detected

interface PHIDetected {
detectionId: string;
entityType: string;
entityId: string;
fieldPath: string; // e.g., "description", "metadata.notes"
confidence: number; // 0.0–1.0
phiType: "NAME" | "MRN" | "DOB" | "SSN" | "ADDRESS" | "PHONE" | "EMAIL" | "OTHER";
action: "BLOCKED" | "FLAGGED_FOR_REVIEW";
}

5. Agent Events

5.1 agent.task_dispatched

interface AgentTaskDispatched {
taskId: string;
workOrderId: string;
agentNode: string; // Per 25-agent-orchestration-spec.md
modelAssignment: string; // "haiku" | "sonnet" | "opus"
tokenBudget: number;
pattern: "CHAIN" | "ROUTE" | "PARALLEL" | "ORCH_WORKERS" | "EVAL_OPT";
}

5.2 agent.task_completed

interface AgentTaskCompleted {
taskId: string;
workOrderId: string;
agentNode: string;
tokensConsumed: number;
durationMs: number;
result: "SUCCESS" | "PARTIAL" | "FAILED";
outputSummary: string;
}

5.3 agent.circuit_breaker_state_changed

interface CircuitBreakerStateChanged {
agentNode: string;
previousState: "CLOSED" | "OPEN" | "HALF_OPEN";
newState: "CLOSED" | "OPEN" | "HALF_OPEN";
failureCount: number;
lastFailureReason: string;
}

5.4 agent.checkpoint_reached

interface AgentCheckpointReached {
taskId: string;
workOrderId: string;
checkpointType: "ARCHITECTURE_DECISION" | "COMPLIANCE_GATE" | "SECURITY_FINDING" | "BLOCKER";
description: string;
requiresHumanApproval: boolean;
context: Record<string, any>;
}

6. Resource Events

6.1 resource.assigned

interface ResourceAssigned {
workOrderId: string;
resourceType: "PERSON" | "TEAM" | "VENDOR";
resourceId: string;
role: "ASSIGNEE" | "VENDOR";
scheduledStart: string;
scheduledEnd: string;
}

6.2 resource.certification_expiring

interface CertificationExpiring {
personId: string;
experienceId: string;
expirationDate: string;
daysUntilExpiry: number;
affectedWorkOrders: string[];
}

6.3 resource.tool_calibration_due

interface ToolCalibrationDue {
toolId: string;
calibrationDueDate: string;
daysUntilDue: number;
affectedWorkOrders: string[];
autoGenerateWO: boolean;
}

7. System Events

7.1 system.tenant_provisioned

interface TenantProvisioned {
tenantId: string;
complianceFrameworks: string[];
dataResidencyRegion: string;
tier: "STARTER" | "PROFESSIONAL" | "ENTERPRISE";
}

7.2 system.feature_flag_changed

interface FeatureFlagChanged {
flagId: string;
tenantId: string | null; // null = global
previousValue: any;
newValue: any;
changedBy: string;
}

Compliance: Feature flag changes affecting regulatory functions require audit trail (69-versioning-evolution-strategy.md §2).

7.3 system.backup_completed

interface BackupCompleted {
backupId: string;
type: "FULL" | "WAL" | "SNAPSHOT";
sizeBytes: number;
durationSeconds: number;
verificationResult: "VERIFIED" | "FAILED";
}

8. Consumer Matrix

ConsumerEvents SubscribedProcessingFailure Mode
Audit Trail WriterAll events where metadata.auditRequired: trueSynchronous write to append-only tableMUST NOT FAIL — DLQ + P0 alert
Agent Orchestratorwork_order.*, approval.*, agent.*Dispatch agent tasks, update stateCircuit breaker; retry from checkpoint
Webhook DispatcherAll events matching customer webhook subscriptionsHTTP POST with HMAC signatureExponential backoff, 48hr max, DLQ
Notification Serviceapproval.requested, work_order.blocked, compliance.violation_detectedEmail + in-app pushRetry 3×, then Slack fallback
Compliance Enginework_order.status_changed, approval.*, agent.*Policy evaluation, guard pre-checkBlock transition if engine unavailable
Metrics CollectorAll eventsCounter/histogram updates in PrometheusDrop silently (metrics are eventual)

9. Event Versioning

Events follow semantic versioning per 69-versioning-evolution-strategy.md §1:

Change TypeVersion ImpactConsumer Impact
Add optional fieldMinor (1.0 → 1.1)No breaking change; consumers ignore unknown fields
Rename/remove fieldMajor (1.x → 2.0)12-month parallel support; old version + new version published
Change field typeMajor (1.x → 2.0)Same as rename
Add new event typeN/ANew subject; existing consumers unaffected

Schema registry: Event schemas stored in Git (events/schemas/) and validated at build time. Consumer contract tests verify compatibility (65-testing-strategy.md §1 — contract tests).


10. Cross-Reference

ConcernSpecification Source
Agent message contracts26-agent-message-contracts.md (agent-specific, maps to §5 events)
NATS topic mapping26-agent-message-contracts.md §5
Webhook delivery67-integration-api-strategy.md §4
API webhook subscription71-api-endpoint-specification.md §10
Audit trail immutability20-regulatory-compliance-matrix.md §1
Event-driven state machine19-state-machine-with-guards.md
Data classification per event63-data-architecture.md §1
Consumer alerting66-operational-readiness.md §9.3
Contract testing65-testing-strategy.md §1 (10% contract tests)
Event schema evolution69-versioning-evolution-strategy.md §1

Events are the nervous system of the WO platform. If the state machine is the brain and the API is the mouth, events are how every organ knows what happened. The audit trail writer is the one consumer that must never fail — a missed audit event in a regulated environment is a compliance finding.


Copyright 2026 AZ1.AI Inc. All rights reserved. Developer: Hal Casteel, CEO/CTO Product: CODITECT-BIO-QMS | Part of the CODITECT Product Suite Classification: Internal - Confidential