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
| Level | Label | Encryption | Access | Retention | WO System Applicability |
|---|---|---|---|---|---|
| L0 | Public | Optional | Unrestricted | Indefinite | None — no WO data is public |
| L1 | Internal | At rest | Authenticated tenant users | 3 years | Asset names, tool catalog, team structure |
| L2 | Confidential | At rest + in transit | Role-based (need-to-know) | 5 years | WO details, job plans, schedules, time entries, change items |
| L3 | Restricted | At rest + in transit + field-level | Named individuals + audit | 7 years or legal hold | Person PII (email, phone), vendor credentials, e-signature records |
| L4 | Regulated | At rest + in transit + field-level + key rotation | Named individuals + regulatory audit + consent | Per regulation + legal hold | Audit trails, electronic signatures, approval chains, compliance evidence |
1.2 Entity Classification
| Entity | Table | Classification | Rationale | Sensitive Fields |
|---|---|---|---|---|
| WorkOrder | work_orders | L2 Confidential | Contains change control details, system references, regulatory flags | description, regulatory, systemCategoryId |
| ChangeItem | change_items | L2 Confidential | Describes specific changes to validated systems | detail, systemCategoryId |
| JobPlan | job_plans | L2 Confidential | Execution details including tool/material requirements | credentials (L3 if contains secrets → must use vault refs) |
| JobPlanToolRequirement | job_plan_tool_requirements | L1 Internal | References tool catalog, no sensitive data | None |
| JobPlanExperienceRequirement | job_plan_experience_requirements | L1 Internal | Experience level requirements | None |
| JobPlanPersonRequirement | job_plan_person_requirements | L2 Confidential | Links persons to plans (staffing info) | personId |
| JobPlanMaterialRequirement | job_plan_material_requirements | L1 Internal | Material specifications | None |
| WorkOrderMinimumRequirement | wo_minimum_requirements | L1 Internal | Threshold rules for WO completeness | None |
| WorkOrderDependency | wo_dependencies | L2 Confidential | DAG structure reveals execution strategy | None |
| Person | persons | L3 Restricted | Contains PII: name, email, phone, employment details | email, phone, displayName, status |
| Team | teams | L1 Internal | Organizational structure | None |
| TeamMember | team_members | L2 Confidential | Links persons to teams (org reporting) | personId, role |
| Vendor | vendors | L2 Confidential | Business relationship details | contactEmail, contractDetails |
| Asset | assets | L1 Internal | Equipment/system catalog | serialNumber (L2 if traceable to patient) |
| Tool | tools | L1 Internal | Tool catalog | None |
| Experience | experiences | L1 Internal | Skill/certification definitions | None |
| PersonExperience | person_experiences | L2 Confidential | Individual qualification records | personId, expiresAt, rating |
| Material | materials | L1 Internal | Material catalog | None |
| Schedule | schedules | L2 Confidential | Execution timing and resource allocation | assigneeId, startDate, endDate |
| TimeEntry | time_entries | L2 Confidential | Labor records with cost implications | personId, hours, notes |
| Approval | approvals | L4 Regulated | Regulatory decision records with signature binding | approverId, decision, signatureId |
| ElectronicSignature | electronic_signatures | L4 Regulated | FDA Part 11 mandated, immutable, legally binding | signerId, signedAt, meaning, authMethod, signatureHash |
| AuditTrail | audit_trail | L4 Regulated | Immutable compliance evidence | performedBy, 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.credentialsJSONB 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
| Phase | L1 Internal | L2 Confidential | L3 Restricted | L4 Regulated |
|---|---|---|---|---|
| Creation | Tenant tag, schema validation | + Creator identity logged | + Field-level encryption, consent check | + Immutability flag, hash chain entry |
| Processing | Standard transforms | + Transformation logged | + Access audit on every read | + Every operation generates audit trail entry |
| Active Use | RBAC gate | + RLS enforcement | + Named-individual access list | + Dual control for modifications (impossible for L4 — append-only) |
| Archival | Compress after 1 year inactive | + Encrypt archived partition | + Separate encryption key per archive | + Retain indefinitely per regulation, separate keys |
| Deletion | Soft delete, purge after retention | + Deletion audit entry | + Deletion certificate generated | + Cannot delete — retention overrides. Legal hold check mandatory |
2.3 Retention Policies
| Data Category | Minimum Retention | Regulatory Driver | Deletion Permitted | Archive Strategy |
|---|---|---|---|---|
| Audit trail entries | Indefinite (while system active) + 10 years post-decommission | FDA §11.10(c), HIPAA §164.530(j) | Never during active use; archival only | Monthly partition rotation to cold storage |
| Electronic signatures | Same as audit trail | FDA §11.70, §11.50 | Never | Co-located with audit trail |
| Approval records | 10 years minimum | FDA §11.10(e), SOC 2 CC7.1 | After retention + no legal hold | Quarterly archival |
| Work orders (completed) | 7 years | SOC 2, business records | After retention + no legal hold + no active references | Annual archival of WOs closed >3 years |
| Work orders (cancelled) | 3 years | Business records | After retention | Annual purge eligible |
| Person records (active) | Duration of employment + 3 years | HIPAA §164.530(j), business records | Anonymize after retention (do not hard-delete) | N/A while active |
| Person records (terminated) | 7 years post-termination | Employment law, regulatory | Anonymize after retention | Annual archival |
| Time entries | 5 years | Business records, labor law | After retention + payroll reconciliation | Annual archival |
| Asset/tool catalog | Duration of system use + 3 years | Configuration management | After decommission + retention | N/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
| Jurisdiction | Applicable Regulations | WO System Impact | Implementation |
|---|---|---|---|
| United States | FDA 21 CFR Part 11, HIPAA, state privacy laws (CCPA/CPRA) | Primary deployment target; all L4 data must reside in US for FDA-regulated customers | US region default for pharma/biotech tenants |
| European Union | GDPR, EU Annex 11 (GMP) | Person PII (L3) subject to GDPR; cross-border transfer requires SCCs or adequacy | EU region deployment option; Person entity fields encrypted with EU-managed keys |
| Brazil | LGPD (Lei Geral de Proteção de Dados) | Person PII subject to LGPD; data officer (encarregado) role required | Brazil region option for LATAM customers |
| Japan | APPI, PMDA electronic records guidance | Similar to FDA Part 11 requirements | APAC region deployment option |
| Multi-jurisdictional | Most restrictive applies per data element | Global pharma tenants may have persons in multiple jurisdictions | Tenant-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:
- Transfer Impact Assessment — documented before first transfer
- Legal mechanism — SCCs (Standard Contractual Clauses) or adequacy decision on file
- Technical safeguard — encryption in transit with region-specific keys
- Audit logging — every cross-region data access logged with source/destination region
- 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:
| Query | Target Response | Implementation |
|---|---|---|
| "Show all transformations for WO-12345" | < 100ms | Index on (sourceEntityType, sourceEntityId) + (destinationEntityType, destinationEntityId) |
| "What AI agent produced this job plan?" | < 50ms | Index on (destinationEntityType, destinationEntityId, actorType) |
| "Show full chain from change item to signature" | < 500ms | Recursive CTE traversal with depth limit (10) |
| "All L4 data accessed by agent X in last 24h" | < 200ms | Index on (actorId, timestamp, classification) |
5. Consent & Data Subject Rights
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.
| Right | GDPR Article | WO System Implementation |
|---|---|---|
| Right of access | Art. 15 | API endpoint: GET /api/v1/data-subjects/:id/export — returns all Person-linked records in JSON |
| Right to rectification | Art. 16 | Standard PATCH /api/v1/persons/:id — audit trail records correction |
| Right to erasure | Art. 17 | Anonymization procedure (§2.4) — cannot hard-delete if regulatory retention applies. Response explains retention override |
| Right to portability | Art. 20 | Export in JSON + CSV format via data subject export endpoint |
| Right to restriction | Art. 18 | Set Person.processingRestricted = true — blocks new WO assignments, preserves existing records |
| Right to object | Art. 21 | Processed per tenant DPIA; may result in processing restriction |
5.2 Consent vs. Legal Basis
| Processing Activity | Legal Basis | Consent Required? |
|---|---|---|
| WO assignment (employment context) | Legitimate interest / Contract | No (employment relationship) |
| E-signature capture | Legal obligation (FDA Part 11) | No (regulatory requirement) |
| Audit trail retention | Legal obligation (FDA, HIPAA, SOC 2) | No (regulatory requirement) |
| Experience/certification tracking | Legitimate interest (quality management) | No (quality system requirement) |
| Vendor contact data processing | Contract | No (vendor agreement) |
| Performance analytics (time entries) | Legitimate interest | Notification 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
| Activity | Risk Level | Mitigation | Status |
|---|---|---|---|
| AI agent processing Person data for resource matching | High | Agent sees only anonymized IDs during matching; de-anonymized only at assignment | Implemented |
| Cross-tenant data isolation | Critical | PostgreSQL RLS on all tables; penetration tested quarterly | Implemented |
| Vendor portal access to WO data | Medium | Scoped to assigned WOs only; no access to Person PII of non-vendor personnel | Implemented |
| Audit trail containing PII (performer names) | Medium | Justified by regulatory requirement; access restricted to QA + ADMIN + AUDITOR | Implemented |
| Long-term retention of L4 data | Low | Regulatory requirement overrides deletion rights; documented in privacy policy | Documented |
| AI model processing regulated data | High | No training on customer data; API calls use ephemeral context; no data retained by model provider | Contractual (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
| Control | Implementation | Compliance Link |
|---|---|---|
| Every migration tied to ADR | Migration file header references ADR number | SOC 2 CC8.1 (Change Management) |
| Reversibility required | Every up migration has a tested down migration | FDA §11.10(a) (System Validation) |
| Pre-migration backup | Automated snapshot before migration execution | Business continuity |
| Migration audit trail | Migration ID, timestamp, operator, schema hash recorded | FDA §11.10(e) |
| No destructive migrations on L4 tables | Audit trail and signature tables: additive only, forever | FDA §11.10(c) |
| Multi-tenant safety | Migrations run at infrastructure level, not tenant level; RLS remains active throughout | Tenant isolation |
7.3 Sensitive Field Changes
When adding, modifying, or removing fields classified L3 or L4:
- DPIA update required before migration approval
- Classification review by compliance engineering
- Encryption key management plan (new fields may need new KMS keys)
- Lineage graph update (new fields need lineage tracking configuration)
- Audit trail schema extended if new fields are audit-relevant
- 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.