Skip to main content

Work Order QMS Module — Versioning, Evolution & Deprecation Strategy

Classification: Internal — Architecture & Engineering
Date: 2026-02-13
Artifact: 69 of WO System Series
Status: Proposed
Source Artifacts: 13-tdd.md §1, 16-prisma-data-model.md, 23-architecture-decision-records.md, 59-coditect-system-prompt-v8.md §14.9, 67-integration-api-strategy.md §3


1. API Versioning Strategy

1.1 Versioning Model

The WO system uses a two-level versioning scheme:

LevelMechanismScopeWhen to Bump
MajorURL path (/api/v1/, /api/v2/)Breaking changes that cannot be backward-compatibleRemoving fields, changing types, removing endpoints, altering state machine transitions
MinorDate-based header (API-Version: 2026-03-15)Non-breaking additive changes within a major versionNew optional fields, new endpoints, new event types, new enum values
Request:
GET /api/v1/work-orders/wo-2024-0042
API-Version: 2026-03-15
Authorization: Bearer ...

Response:
HTTP/1.1 200 OK
API-Version: 2026-03-15
API-Version-Latest: 2026-06-01

If no API-Version header is sent, the API defaults to the earliest GA version of the major version (preserving backward compatibility for clients that never upgrade).

1.2 Breaking Change Definition (WO-Specific)

In a regulated environment, "breaking change" has stricter boundaries than typical SaaS:

Change TypeBreaking?Reason
Remove a response fieldYesClients may rely on field for compliance evidence
Change field type (string → int)YesParsing failures
Remove endpointYesIntegration failure
Rename fieldYesEquivalent to remove + add
Change validation rules (stricter)YesPreviously valid requests fail
Change state machine transitionsYes — CRITICALCompliance workflows depend on transition paths; changing these requires IQ/OQ/PQ revalidation
Change audit trail formatYes — CRITICALFDA auditors reference specific audit formats
Add optional request fieldNoBackward-compatible
Add response fieldNoClients ignore unknown fields
Add new endpointNoNo existing behavior changes
Add new enum valueNo (if client handles unknown values)Requires "open enum" client pattern
Relax validation rulesNoPreviously valid requests still valid

1.3 Parallel Version Support

PolicyValueRationale
Active versionsN and N-1 (fully supported)Enterprise customers need stability
Extended supportN-2 (security patches only)Regulated environments can't upgrade instantly
SunsetN-3 returns 410 GonePrevent indefinite legacy burden
Maximum parallel versions3 active at any timeEngineering bandwidth constraint
Minimum notice before sunset12 monthsPer 67-integration-api-strategy.md §3.3

1.4 Version Compatibility Matrix

v1 (current GA)  ──── Fully supported, all features
v2 (future) ──── Will be introduced when state machine v2 ships
v1→v2 migration guide published 6 months before v2 GA
v1 enters deprecated 3 months after v2 GA
v1 sunset 12 months after deprecation

Compliance constraint:
Customers with validated systems on v1 need a validation protocol
to migrate to v2. CODITECT provides migration validation toolkit
including automated IQ/OQ test suites for v2 (per 65-testing-strategy.md §5).

2. Feature Flag Architecture

2.1 Why Feature Flags in Regulated Environments

In a typical SaaS: "ship fast, roll back if broken."
In a regulated SaaS: "ship incrementally, validate before enabling, never break validated workflows."

Feature flags enable:

  • Gradual rollout without full deployment
  • A/B testing for UX improvements (non-regulatory features only)
  • Emergency kill switch for problematic features
  • Per-tenant enablement for beta participants
  • Compliance gate: features that affect validated systems require IQ/OQ before GA

2.2 Feature Flag Schema

interface FeatureFlag {
key: string; // e.g., 'wo.partial-completion-policy'
description: string;
type: 'BOOLEAN' | 'PERCENTAGE' | 'TENANT_LIST';
defaultValue: boolean; // Value when no override matches

overrides: {
tenantIds?: string[]; // Specific tenant enablement
roleIds?: string[]; // Role-based rollout
percentage?: number; // Gradual rollout (0-100)
};

compliance: {
affectsValidatedWorkflows: boolean; // If true, requires IQ/OQ before GA
affectsAuditTrail: boolean; // If true, flag evaluation logged in audit
regulatoryScope: ('FDA' | 'HIPAA' | 'SOC2')[];
validationStatus: 'NOT_REQUIRED' | 'PENDING' | 'VALIDATED';
};

lifecycle: {
createdAt: DateTime;
createdBy: string;
status: 'ACTIVE' | 'GA' | 'DEPRECATED' | 'REMOVED';
staleAfter: DateTime; // Auto-alert if flag still active after this date
};
}

2.3 Flag Evaluation Rules

Evaluation Order (first match wins):
1. Kill switch override (emergency disable — highest priority)
2. Tenant-specific override (beta customers)
3. Role-specific override (internal testing)
4. Percentage rollout (gradual enablement)
5. Default value (typically false for new features)

Compliance Rules:
- Flag evaluation is LOGGED when affectsAuditTrail=true
- Features behind flags that affect validated systems:
→ Cannot be enabled for production tenants until validationStatus=VALIDATED
→ IQ/OQ executed in staging with flag enabled
→ OQ results attached to feature flag record
- Flags can only ADD capabilities, NEVER bypass compliance guards
- Disabling a flag never removes audit trail entries created while enabled

2.4 Flag Lifecycle

CREATED → DEVELOPMENT → STAGING → BETA → GA → CLEANUP
↓ ↓ ↓ ↓ ↓ ↓
Flag in Code uses QA tests Select Flag Code
config flag check with flag tenants removed, paths
store (if/else) enabled enabled always cleaned
"on"

Stale Flag Policy:
- Flags older than 90 days: auto-generated cleanup PR
- Flags older than 180 days: P3 engineering ticket
- Flags older than 365 days: P2 tech debt, blocking new flags
- Exception: regulatory-gated flags (validationStatus=PENDING) exempt until validated

2.5 Flag Inventory (Current)

Flag KeyTypeStatusRegulatoryDescription
wo.agent-auto-assignmentBOOLEANBetaFDA (audit trail)AI agent auto-assigns WOs based on Experience Matcher
wo.vendor-portal-v2TENANT_LISTDevelopmentNoRedesigned vendor portal with drag-drop upload
wo.partial-completion-policyBOOLEANStagingFDA (state machine)Master WO completion with configurable policies (Gap G19)
wo.phi-scannerBOOLEANDevelopmentHIPAAPHI detection scanner on WO fields (Gap G09)
wo.break-glassBOOLEANDevelopmentHIPAA, SOC2Emergency access bypass with enhanced audit (Gap G10)
wo.hash-chain-verificationBOOLEANStagingFDA §11.70Audit trail hash chain integrity checks (Gap G03)

3. Schema Evolution Strategy

3.1 Migration Philosophy

Five Principles of Schema Evolution in Multi-Tenant Regulated Systems:

1. ALWAYS ADDITIVE
Add columns, never remove or rename in the same migration.
Old and new code must coexist during rolling deployments.

2. ZERO-DOWNTIME
Use expand-contract pattern. Never lock tables.
Migrations execute with minimal locks (< 100ms for ALTER TABLE).

3. BACKWARD COMPATIBLE
Old application version works with new schema for release N-1.
Old application version works with new schema for release N.

4. FORWARD COMPATIBLE
New application version works with old schema during rollout.
Nullable new columns, default values, code handles missing columns.

5. AUDITED
Every migration logged: migration ID, timestamp, operator, schema hash.
Every migration reversible (tested down migration).
Every schema change tied to an ADR or feature flag.

3.2 Expand-Contract Pattern

For any non-trivial schema change (rename column, change type, split table):

Release N:   EXPAND
- Add new column (nullable or with default)
- Application writes to BOTH old and new columns
- Application reads from OLD column
- Migration: ALTER TABLE ADD COLUMN (fast, minimal lock)

Release N+1: MIGRATE
- Backfill new column from old column (batch job, not migration)
- Application reads from NEW column
- Application still writes to BOTH (backward compat)
- Verify: new column matches old for all rows

Release N+2: CONTRACT
- Application only reads/writes NEW column
- Old column ignored but still exists
- Monitor: no queries reference old column (pg_stat_statements)

Release N+3: CLEANUP (optional)
- DROP old column (only if not referenced)
- For L4 regulated tables: NEVER drop — mark as deprecated

3.3 Migration Execution

# Migration file naming convention
# YYYYMMDDHHMMSS_description.ts

20260213143000_add_signature_hash_to_electronic_signature.ts
20260215090000_add_break_glass_session_model.ts
20260220100000_add_phi_scan_record_model.ts

# Execution in CI/CD pipeline
prisma migrate deploy # Runs pending migrations
prisma migrate status # Checks migration state
prisma migrate diff # Shows schema diff (review before merge)

3.4 Migration Safety Checks

CheckToolGateAction on Failure
No destructive operations on L4 tablesCustom linterPR merge blockedMust use expand-contract
Migration < 100ms on largest tablepg_bench simulationPR merge blockedRewrite migration or use background job
Down migration exists and testedCI test suitePR merge blockedWrite reverse migration
RLS policies preservedRLS verification queryPR merge blockedEnsure new tables have tenant_id + RLS
Schema hash recordedMigration frameworkDeployment blockedAuto-generated, verify not null
Backup taken before executionPre-deploy hookDeployment blockedAutomated pg_basebackup

3.5 Sensitive Table Rules

TableClassificationSchema Change Policy
audit_trailL4 — Never modifyAdditive only, forever. Never ALTER existing columns. New versions get new columns.
electronic_signatureL4 — Never modifySame as audit_trail. Signature records are immutable legal documents.
approvalL4 — RestrictedAdditive only. Cannot modify columns referenced by signature hash.
work_orderL3 — CarefulExpand-contract required. State machine columns need ADR before change.
job_planL2 — StandardStandard expand-contract. JSONB fields evolve via JSON Schema versioning.
person, team, vendorL3 — CarefulStandard expand-contract. PII fields require DPIA review.

4. Deprecation Policy

4.1 What Gets Deprecated

ArtifactDeprecation PolicyNotice PeriodCommunication
API endpoints12 months minimumSunset header + docs + emailPer 67-integration-api-strategy.md §3.3
API fields6 months minimumdeprecated: true in OpenAPI spec; response header warningChangelog + migration guide
Webhook event types6 months minimumNew event type published alongside; old type marked deprecatedChangelog + migration guide
Feature flags (removal)30 days after GAFlag key removed from config; code path cleaned upInternal engineering communication
Database columnsNever for L4; 3 releases + backcompat period for othersInternal migration ticketEngineering changelog
State machine transitionsNever removed — only supersededNew version with migrationADR + customer communication + revalidation toolkit
Plugin interfaces6 months minimumNew interface version published alongsideDeveloper portal + email

4.2 Deprecation Communication

Deprecation Announcement Template:

Subject: [Deprecation Notice] {feature_name} — Action Required by {deadline}

What's changing:
{feature_name} is being deprecated in favor of {replacement}.

Timeline:
{date}: Deprecation announced (this notice)
{date + 3mo}: Deprecation warnings begin (response headers, dashboard banners)
{date + 9mo}: Feature enters maintenance mode (bug fixes only)
{date + 12mo}: Feature sunset (returns 410 Gone / disabled)

Migration guide: {url}
Automated migration tool: {url} (if applicable)
Support: Contact us at support@coditect.ai with questions.

Compliance note:
If this feature is part of your validated system configuration,
plan for revalidation using our migration validation toolkit.
Estimated revalidation effort: {estimate}.

4.3 Regulated Environment Special Rules

RuleRationaleImplementation
Audit trail format changes get 18 months notice (not 12)FDA auditors reference specific formats; audits can span 2+ yearsExtended deprecation timeline for audit-related APIs
E-signature endpoints are never sunset — only supersededLegal liability for historical signaturesOld signature verification always available
State machine versions maintained indefinitely in read modeHistorical WOs must remain navigable in their original state modelState machine version embedded in WO record
Compliance evidence packages include API version usedAudit trail must show which API version generated each recordapi_version field in audit trail metadata

5. Architecture Fitness Functions

Automated checks that the system still meets its architectural principles as it evolves.

5.1 Fitness Function Catalog

Fitness FunctionWhat It ChecksThresholdFrequencyEnforcement
Audit trail completenessEvery state transition has a corresponding audit trail entry100%Every CI runPR merge blocked
RLS coverageEvery table with tenant_id has RLS policy enabled100%Every CI runPR merge blocked
SOD enforcementNo single user can both create and approve the same WO (in test scenarios)100%Every CI runPR merge blocked
Signature integrityHash of (signer + timestamp + WO version + meaning) matches stored hash100%Nightly jobP0 alert
Hash chain continuityAudit trail entries form an unbroken hash chain100%Nightly jobP0 alert
API backward compatibilityNew API version passes all previous version's contract tests100%Every CI runPR merge blocked
Schema safetyNo destructive operations on L4 tables in migration files100%Every CI runPR merge blocked
Token budget complianceNo single agent execution exceeds 2× allocated token budget95%Real-time monitoringCircuit breaker
Performance budgetP95 API latency < 500ms95th percentileContinuousP2 alert (P1 if sustained)
Dependency freshnessNo dependency with known critical CVE older than 7 days100%Daily scanPR merge blocked for new PRs
Test coverageCritical path coverage (state machine, guards, RBAC)100%Every CI runPR merge blocked
AccessibilityLighthouse accessibility score≥ 95Every PR with UI changesPR merge blocked
Data classificationEvery new Prisma model has @map + data classification comment100%Every CI runPR merge blocked
Feature flag stalenessNo active flag older than 90 days without exception0 stale flagsWeekly scanAuto-generated cleanup PR

5.2 Fitness Function Implementation

// Example: Audit trail completeness fitness function
// Runs as part of integration test suite

describe('Fitness: Audit Trail Completeness', () => {
for (const transition of ALL_VALID_TRANSITIONS) {
it(`transition ${transition.from}${transition.to} generates audit entry`, async () => {
const wo = await createWO({ state: transition.from });
const auditCountBefore = await countAuditEntries(wo.id);

await transitionWO(wo.id, transition.to, {
actor: transition.requiredRole,
reason: 'Fitness function test'
});

const auditCountAfter = await countAuditEntries(wo.id);
expect(auditCountAfter).toBe(auditCountBefore + 1);

const latestAudit = await getLatestAuditEntry(wo.id);
expect(latestAudit.action).toBe('STATUS_TRANSITION');
expect(latestAudit.previousValue).toContain(transition.from);
expect(latestAudit.newValue).toContain(transition.to);
expect(latestAudit.performedBy).toBeDefined();
expect(latestAudit.performedAt).toBeDefined();
});
}
});
// Example: Schema safety fitness function (custom Prisma migration linter)

function validateMigration(sql: string): ValidationResult {
const L4_TABLES = ['audit_trail', 'electronic_signature', 'approval'];
const DESTRUCTIVE_OPS = ['DROP COLUMN', 'ALTER COLUMN', 'DROP TABLE', 'RENAME'];

for (const table of L4_TABLES) {
for (const op of DESTRUCTIVE_OPS) {
if (sql.includes(op) && sql.includes(table)) {
return {
valid: false,
error: `Destructive operation "${op}" on L4 table "${table}" is prohibited. Use expand-contract pattern.`,
rule: 'SCHEMA_SAFETY_L4',
};
}
}
}
return { valid: true };
}

5.3 Fitness Function Dashboard

Fitness functions report to a dashboard (consumed by 32-tech-architecture-analyzer.jsx) with real-time status:

Architecture Health Score: 97/100

🟢 Audit Trail Completeness: 100% (last checked: 2 min ago)
🟢 RLS Coverage: 100% (last checked: 2 min ago)
🟢 SOD Enforcement: 100% (last checked: 2 min ago)
🟢 Signature Integrity: 100% (last checked: 6 hours ago)
🟢 Hash Chain Continuity: 100% (last checked: 6 hours ago)
🟢 API Backward Compat: 100% (last checked: 15 min ago)
🟢 Schema Safety: 100% (last checked: 15 min ago)
🟡 Token Budget Compliance: 96.2% (3 executions over budget this week)
🟢 Performance Budget: P95 = 287ms (target: <500ms)
🟢 Dependency Freshness: 0 critical CVEs
🟢 Test Coverage (critical): 100%
🟢 Accessibility: Lighthouse 97
🟢 Data Classification: 100%
🟡 Feature Flag Staleness: 1 flag at 87 days (approaching 90-day limit)

6. Release Management in Regulated Environments

6.1 Release Types

TypeFrequencyScopeValidation RequiredDeployment
HotfixAs neededCritical bug or security patch, no feature changesRegression test suite onlyImmediate (off-cycle)
PatchBi-weeklyBug fixes, dependency updates, no feature changesFull CI/CD suiteScheduled maintenance window
MinorMonthlyNew features (behind flags), additive API changesCI/CD + integration tests + flag-gated IQ/OQScheduled with 1-week notice
MajorQuarterlyBreaking changes, state machine evolution, API version bumpFull IQ/OQ/PQ + customer migration toolkitScheduled with 3-month notice

6.2 Release Checklist

## Release Checklist v1.0

### Pre-Release
- [ ] All fitness functions passing (green dashboard)
- [ ] Changelog generated (auto + manual review)
- [ ] Migration tested in staging (up AND down)
- [ ] Feature flags reviewed (any becoming GA? any stale?)
- [ ] API contract tests passing for current + N-1 versions
- [ ] Performance regression test passing (< 5% degradation)
- [ ] Accessibility audit passing (Lighthouse ≥ 95)
- [ ] Security scan clean (0 critical, 0 high CVEs)
- [ ] Compliance validation for any regulatory-affecting changes

### Deployment
- [ ] Database backup verified (pre-deployment)
- [ ] Migration executed (schema hash recorded)
- [ ] Application deployed (rolling, zero-downtime)
- [ ] Health checks passing on all instances
- [ ] Smoke test suite passing in production

### Post-Release
- [ ] Monitoring dashboards reviewed (no anomalies for 30 min)
- [ ] Error rate within budget (< 0.05%)
- [ ] Latency within budget (P95 < 500ms)
- [ ] Audit trail integrity verified
- [ ] Release notes published
- [ ] Customer notification sent (if applicable)

6.3 Rollback Strategy

Rollback Decision Tree:

Error rate > 1% for > 5 min?
YES → Immediate rollback
NO → Monitor

Compliance violation detected?
YES → Immediate rollback + P0 incident
NO → Continue monitoring

Performance degradation > 50%?
YES → Rollback within 15 min
NO → Investigate, optional rollback

Rollback Procedure:
1. Deploy previous container image (tag: release-N-1)
2. Run down migration (if schema change was applied)
3. Verify: audit trail integrity, signature chain, RLS policies
4. Notify: status page update, customer communication if impacted
5. Post-mortem: PIR within 3 business days

7. Cross-Reference to Other Artifacts

TopicPrimary ArtifactThis Document Section
API endpoint definitions13-tdd.md §1§1 (versioning layer on top of endpoints)
API lifecycle & deprecation67-integration-api-strategy.md §3§1, §4 (extended with regulated constraints)
Database schema16-prisma-data-model.md§3 (evolution strategy for the schema)
State machine transitions19-state-machine-with-guards.md§1.2, §4.3 (versioning of state machine)
Gap closure items behind flags58-gap-closure-prompts.md§2.5 (flag inventory for gap items)
Testing validation (IQ/OQ/PQ)65-testing-strategy.md §5§2.3, §6.1 (validation gating for flags and releases)
ADRs for schema decisions23-architecture-decision-records.md§3.1 (migrations tied to ADRs)
Fitness functions → dashboards32-tech-architecture-analyzer.jsx§5.3 (fitness function dashboard integration)
Operational release procedures66-operational-readiness.md§6 (release management complements runbooks)

A system that cannot evolve safely is a system that becomes legacy. In regulated environments, "safely" means: every change audited, every migration reversible, every deprecated feature given a graceful exit, and every architectural principle continuously verified by automated fitness functions. This document is the temporal dimension of the architecture — it answers "how does this system change over time without breaking compliance?"


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