Skip to main content

Work Order QMS Module — Data Architecture & Privacy

Classification: Internal — Architecture Date: 2026-02-13 Artifact: 63 of WO System Series Prompt Section: v8.0 §4 — Data Architecture & Privacy


1. Data Classification Map

Every entity in the WO system's 22-table Prisma schema is classified below. Classification drives encryption policy, access control, retention period, and residency rules.

1.1 Classification Taxonomy

LevelLabelEncryptionAccessRetentionWO System Applicability
L0PublicOptionalUnrestrictedIndefiniteNone — no WO data is public
L1InternalAt restAuthenticated tenant users3 yearsAsset names, tool catalog, team structure
L2ConfidentialAt rest + in transitRole-based (need-to-know)5 yearsWO details, job plans, schedules, time entries, change items
L3RestrictedAt rest + in transit + field-levelNamed individuals + audit7 years or legal holdPerson PII (email, phone), vendor credentials, e-signature records
L4RegulatedAt rest + in transit + field-level + key rotationNamed individuals + regulatory audit + consentPer regulation + legal holdAudit trails, electronic signatures, approval chains, compliance evidence

1.2 Entity Classification

EntityTableClassificationRationaleSensitive Fields
WorkOrderwork_ordersL2 ConfidentialContains change control details, system references, regulatory flagsdescription, regulatory, systemCategoryId
ChangeItemchange_itemsL2 ConfidentialDescribes specific changes to validated systemsdetail, systemCategoryId
JobPlanjob_plansL2 ConfidentialExecution details including tool/material requirementscredentials (L3 if contains secrets → must use vault refs)
JobPlanToolRequirementjob_plan_tool_requirementsL1 InternalReferences tool catalog, no sensitive dataNone
JobPlanExperienceRequirementjob_plan_experience_requirementsL1 InternalExperience level requirementsNone
JobPlanPersonRequirementjob_plan_person_requirementsL2 ConfidentialLinks persons to plans (staffing info)personId
JobPlanMaterialRequirementjob_plan_material_requirementsL1 InternalMaterial specificationsNone
WorkOrderMinimumRequirementwo_minimum_requirementsL1 InternalThreshold rules for WO completenessNone
WorkOrderDependencywo_dependenciesL2 ConfidentialDAG structure reveals execution strategyNone
PersonpersonsL3 RestrictedContains PII: name, email, phone, employment detailsemail, phone, displayName, status
TeamteamsL1 InternalOrganizational structureNone
TeamMemberteam_membersL2 ConfidentialLinks persons to teams (org reporting)personId, role
VendorvendorsL2 ConfidentialBusiness relationship detailscontactEmail, contractDetails
AssetassetsL1 InternalEquipment/system catalogserialNumber (L2 if traceable to patient)
TooltoolsL1 InternalTool catalogNone
ExperienceexperiencesL1 InternalSkill/certification definitionsNone
PersonExperienceperson_experiencesL2 ConfidentialIndividual qualification recordspersonId, expiresAt, rating
MaterialmaterialsL1 InternalMaterial catalogNone
ScheduleschedulesL2 ConfidentialExecution timing and resource allocationassigneeId, startDate, endDate
TimeEntrytime_entriesL2 ConfidentialLabor records with cost implicationspersonId, hours, notes
ApprovalapprovalsL4 RegulatedRegulatory decision records with signature bindingapproverId, decision, signatureId
ElectronicSignatureelectronic_signaturesL4 RegulatedFDA Part 11 mandated, immutable, legally bindingsignerId, signedAt, meaning, authMethod, signatureHash
AuditTrailaudit_trailL4 RegulatedImmutable compliance evidenceperformedBy, previousValue, newValue, entryHash, previousHash

1.3 Classification Rules for the WO System

  • Default L2: any new entity or field added to the WO schema defaults to L2 Confidential unless explicitly classified lower or higher
  • Aggregation escalation: L1 asset data becomes L2 when combined with L2 schedule data (reveals operational plans); L2 WO data becomes L4 when combined with approval/signature records (creates compliance evidence)
  • Agent-generated data: inherits the highest classification of any input the agent consumed. If an agent reads L4 audit trail data to generate a report, that report is L4
  • Credential fields: the job_plans.credentials JSONB field is classified L3 minimum — per gap closure G01, this field must contain only vault references (vault://path), never plaintext secrets
  • Vendor data boundary: vendor-visible data is scoped to their assigned WOs only, but the vendor entity itself is L2 (business relationship)

2. Data Lifecycle Management

2.1 Lifecycle Phases

CREATION → PROCESSING → ACTIVE USE → ARCHIVAL → DELETION/RETENTION
↓ ↓ ↓ ↓ ↓
Classify Validate Access Compress Verify policy
Tag tenant Audit log Control Index Check legal hold
Assign RLS Lineage Monitor Cold store Certify deletion
Encrypt Transform Backup Retain Audit log

2.2 Phase Controls by Classification

PhaseL1 InternalL2 ConfidentialL3 RestrictedL4 Regulated
CreationTenant tag, schema validation+ Creator identity logged+ Field-level encryption, consent check+ Immutability flag, hash chain entry
ProcessingStandard transforms+ Transformation logged+ Access audit on every read+ Every operation generates audit trail entry
Active UseRBAC gate+ RLS enforcement+ Named-individual access list+ Dual control for modifications (impossible for L4 — append-only)
ArchivalCompress after 1 year inactive+ Encrypt archived partition+ Separate encryption key per archive+ Retain indefinitely per regulation, separate keys
DeletionSoft delete, purge after retention+ Deletion audit entry+ Deletion certificate generated+ Cannot delete — retention overrides. Legal hold check mandatory

2.3 Retention Policies

Data CategoryMinimum RetentionRegulatory DriverDeletion PermittedArchive Strategy
Audit trail entriesIndefinite (while system active) + 10 years post-decommissionFDA §11.10(c), HIPAA §164.530(j)Never during active use; archival onlyMonthly partition rotation to cold storage
Electronic signaturesSame as audit trailFDA §11.70, §11.50NeverCo-located with audit trail
Approval records10 years minimumFDA §11.10(e), SOC 2 CC7.1After retention + no legal holdQuarterly archival
Work orders (completed)7 yearsSOC 2, business recordsAfter retention + no legal hold + no active referencesAnnual archival of WOs closed >3 years
Work orders (cancelled)3 yearsBusiness recordsAfter retentionAnnual purge eligible
Person records (active)Duration of employment + 3 yearsHIPAA §164.530(j), business recordsAnonymize after retention (do not hard-delete)N/A while active
Person records (terminated)7 years post-terminationEmployment law, regulatoryAnonymize after retentionAnnual archival
Time entries5 yearsBusiness records, labor lawAfter retention + payroll reconciliationAnnual archival
Asset/tool catalogDuration of system use + 3 yearsConfiguration managementAfter decommission + retentionN/A while active

2.4 Deletion Procedure

Deletion in a regulated environment is not DELETE FROM. It's a controlled process:

1. Deletion Request
├── Source: retention policy trigger, data subject request, decommission
├── Validation: check retention policy, legal hold register, active references
└── If blocked → log denial reason, notify requestor

2. Pre-Deletion Verification
├── Scan for active FK references (prevent orphans)
├── Verify no open legal holds on entity or related records
├── Verify retention period satisfied
└── Generate pre-deletion snapshot (for audit)

3. Execution
├── L1–L2: Soft delete (set deleted_at, exclude from queries)
├── L3: Anonymize PII fields (replace with hash), retain structure
├── L4: NEVER delete — archive to cold storage with integrity verification
└── Generate deletion certificate (entity ID, timestamp, method, operator, authorization)

4. Post-Deletion
├── Audit trail entry (ironic: deleting data creates audit data)
├── Verify entity no longer appears in queries
├── Update data lineage graph
└── Notify downstream systems if applicable

3. Data Residency & Sovereignty

3.1 Jurisdiction Map

JurisdictionApplicable RegulationsWO System ImpactImplementation
United StatesFDA 21 CFR Part 11, HIPAA, state privacy laws (CCPA/CPRA)Primary deployment target; all L4 data must reside in US for FDA-regulated customersUS region default for pharma/biotech tenants
European UnionGDPR, EU Annex 11 (GMP)Person PII (L3) subject to GDPR; cross-border transfer requires SCCs or adequacyEU region deployment option; Person entity fields encrypted with EU-managed keys
BrazilLGPD (Lei Geral de Proteção de Dados)Person PII subject to LGPD; data officer (encarregado) role requiredBrazil region option for LATAM customers
JapanAPPI, PMDA electronic records guidanceSimilar to FDA Part 11 requirementsAPAC region deployment option
Multi-jurisdictionalMost restrictive applies per data elementGlobal pharma tenants may have persons in multiple jurisdictionsTenant-level residency config, per-field jurisdiction tagging

3.2 Residency Enforcement

-- Tenant-level residency configuration
CREATE TABLE tenant_data_residency (
tenant_id TEXT NOT NULL REFERENCES tenants(id),
data_region TEXT NOT NULL, -- 'us-east', 'eu-west', 'br-south', 'ap-northeast'
allowed_regions TEXT[] NOT NULL, -- Where data CAN be processed
restricted_fields JSONB, -- Field-level restrictions (e.g., Person.email → eu-west only)
created_at TIMESTAMPTZ DEFAULT now(),
updated_at TIMESTAMPTZ DEFAULT now()
);

-- Query-time enforcement via RLS
CREATE POLICY residency_enforcement ON persons
USING (
tenant_id IN (
SELECT tenant_id FROM tenant_data_residency
WHERE data_region = current_setting('app.data_region')
)
);

3.3 Cross-Border Transfer Controls

For multi-region customers, data transfers between regions require:

  1. Transfer Impact Assessment — documented before first transfer
  2. Legal mechanism — SCCs (Standard Contractual Clauses) or adequacy decision on file
  3. Technical safeguard — encryption in transit with region-specific keys
  4. Audit logging — every cross-region data access logged with source/destination region
  5. Minimization — transfer only the minimum necessary fields

4. Data Lineage

4.1 Lineage Model

Every data transformation in the WO system is recorded in a lineage graph. This is critical for regulated environments where auditors ask: "where did this value come from?"

interface LineageRecord {
id: string; // UUID v7
tenantId: string;
sourceEntityType: string; // 'WorkOrder', 'Approval', 'AuditTrail', etc.
sourceEntityId: string;
sourceField?: string; // Specific field if field-level lineage
transformationType: TransformationType;
transformationDetails: Record<string, unknown>;
destinationEntityType: string;
destinationEntityId: string;
destinationField?: string;
actorId: string; // Person ID or Agent ID
actorType: 'HUMAN' | 'AGENT' | 'SYSTEM';
agentSessionId?: string; // If agent-initiated
modelId?: string; // If AI model was involved
promptHash?: string; // Hash of prompt if AI-generated
confidence?: number; // If AI-generated, confidence score
timestamp: string; // ISO 8601 UTC
classification: DataClassification; // Inherited from highest-classified input
}

type TransformationType =
| 'CREATE' // New data created
| 'DERIVE' // Calculated/transformed from source
| 'COPY' // Direct copy (e.g., WO → linked WO)
| 'AGGREGATE' // Combined from multiple sources
| 'ANONYMIZE' // PII removed/replaced
| 'ARCHIVE' // Moved to cold storage
| 'AI_GENERATE' // Generated by AI agent
| 'AI_TRANSFORM' // Transformed by AI agent
| 'APPROVE' // Approval decision (source: WO, destination: Approval record)
| 'SIGN' // E-signature applied (source: Approval, destination: ElectronicSignature)
;

4.2 Key Lineage Chains in the WO System

Chain 1: WO Creation → Approval → Signature
ChangeItem (source)
→ WorkOrder.create [DERIVE, by ORIGINATOR or AGENT_ORCHESTRATOR]
→ JobPlan.create [DERIVE, by ASSIGNER or AGENT_ORCHESTRATOR]
→ Schedule.create [DERIVE, by AGENT_SCHEDULER]
→ Approval.create [CREATE, by SYSTEM_OWNER]
→ ElectronicSignature.create [SIGN, by SYSTEM_OWNER]
→ AuditTrail.append [CREATE, by SYSTEM]

Chain 2: Master WO → Linked WO Decomposition
MasterWorkOrder (source)
→ SubWorkOrderIntent [AI_GENERATE, by AGENT_ORCHESTRATOR, model: sonnet]
→ LinkedWorkOrder_1.create [DERIVE]
→ LinkedWorkOrder_2.create [DERIVE]
→ LinkedWorkOrder_N.create [DERIVE]
→ WorkOrderDependency.create [DERIVE, DAG edges]

Chain 3: Resource Matching
PersonExperience[] + JobPlanExperienceRequirement[] (sources)
→ ExperienceMatchResult [AI_TRANSFORM, by AGENT_EXPERIENCE_MATCHER, model: haiku]
→ Schedule.assigneeId [DERIVE, assignment decision]
→ AuditTrail.append [CREATE, by SYSTEM]

4.3 Lineage Query Performance

Compliance queries against the lineage graph must be fast:

QueryTarget ResponseImplementation
"Show all transformations for WO-12345"< 100msIndex on (sourceEntityType, sourceEntityId) + (destinationEntityType, destinationEntityId)
"What AI agent produced this job plan?"< 50msIndex on (destinationEntityType, destinationEntityId, actorType)
"Show full chain from change item to signature"< 500msRecursive CTE traversal with depth limit (10)
"All L4 data accessed by agent X in last 24h"< 200msIndex on (actorId, timestamp, classification)

5.1 Applicability

The WO system processes Person records (L3 Restricted) which contain PII. For tenants subject to GDPR, LGPD, or CCPA, data subject rights apply to Person entities.

RightGDPR ArticleWO System Implementation
Right of accessArt. 15API endpoint: GET /api/v1/data-subjects/:id/export — returns all Person-linked records in JSON
Right to rectificationArt. 16Standard PATCH /api/v1/persons/:id — audit trail records correction
Right to erasureArt. 17Anonymization procedure (§2.4) — cannot hard-delete if regulatory retention applies. Response explains retention override
Right to portabilityArt. 20Export in JSON + CSV format via data subject export endpoint
Right to restrictionArt. 18Set Person.processingRestricted = true — blocks new WO assignments, preserves existing records
Right to objectArt. 21Processed per tenant DPIA; may result in processing restriction
Processing ActivityLegal BasisConsent Required?
WO assignment (employment context)Legitimate interest / ContractNo (employment relationship)
E-signature captureLegal obligation (FDA Part 11)No (regulatory requirement)
Audit trail retentionLegal obligation (FDA, HIPAA, SOC 2)No (regulatory requirement)
Experience/certification trackingLegitimate interest (quality management)No (quality system requirement)
Vendor contact data processingContractNo (vendor agreement)
Performance analytics (time entries)Legitimate interestNotification required; opt-out for non-essential analytics

5.3 Data Subject Request Workflow

Request Received (via portal or email)
→ Verify identity (minimum: email match + second factor)
→ Classify request type (access, rectification, erasure, portability, restriction)
→ Check regulatory retention overrides
→ If retention applies: respond within 30 days explaining override + retention period
→ If no override: execute within 30 days
→ Generate compliance certificate
→ Audit trail entry for the DSR itself

6. Privacy Impact Assessment Summary

6.1 High-Risk Processing Activities

ActivityRisk LevelMitigationStatus
AI agent processing Person data for resource matchingHighAgent sees only anonymized IDs during matching; de-anonymized only at assignmentImplemented
Cross-tenant data isolationCriticalPostgreSQL RLS on all tables; penetration tested quarterlyImplemented
Vendor portal access to WO dataMediumScoped to assigned WOs only; no access to Person PII of non-vendor personnelImplemented
Audit trail containing PII (performer names)MediumJustified by regulatory requirement; access restricted to QA + ADMIN + AUDITORImplemented
Long-term retention of L4 dataLowRegulatory requirement overrides deletion rights; documented in privacy policyDocumented
AI model processing regulated dataHighNo training on customer data; API calls use ephemeral context; no data retained by model providerContractual (BAA/DPA with model providers)

6.2 Data Protection Officer Integration

For GDPR-subject tenants:

  • DPO role added to RBAC model (read access to all Person data + audit trails, no modification rights)
  • DPO receives automated alerts for: new data subject requests, breach detection events, cross-border transfer requests
  • DPO dashboard in compliance reporting shows: open DSRs with deadlines, retention policy compliance, consent register status

7. Schema Evolution Strategy

7.1 Migration Philosophy

All WO schema changes follow the expand-contract pattern for zero-downtime deployments:

Release N:   Add new column (nullable) + write to both old and new
Release N+1: Backfill new column + read from new + write to both
Release N+2: Remove old column reads + cleanup
Release N+3: Drop old column (if no longer needed)

7.2 Migration Controls

ControlImplementationCompliance Link
Every migration tied to ADRMigration file header references ADR numberSOC 2 CC8.1 (Change Management)
Reversibility requiredEvery up migration has a tested down migrationFDA §11.10(a) (System Validation)
Pre-migration backupAutomated snapshot before migration executionBusiness continuity
Migration audit trailMigration ID, timestamp, operator, schema hash recordedFDA §11.10(e)
No destructive migrations on L4 tablesAudit trail and signature tables: additive only, foreverFDA §11.10(c)
Multi-tenant safetyMigrations run at infrastructure level, not tenant level; RLS remains active throughoutTenant isolation

7.3 Sensitive Field Changes

When adding, modifying, or removing fields classified L3 or L4:

  1. DPIA update required before migration approval
  2. Classification review by compliance engineering
  3. Encryption key management plan (new fields may need new KMS keys)
  4. Lineage graph update (new fields need lineage tracking configuration)
  5. Audit trail schema extended if new fields are audit-relevant
  6. Data subject export updated if new PII fields added

Data architecture is not optional in regulated environments — it's the foundation that compliance, security, and privacy build on. Every new feature, every new field, every new agent capability must pass through this classification and lifecycle framework before implementation.