Skip to main content

Track C: Technical Foundation

Priority: MEDIUM — Begins Sprint 3 after presentation proves interest Agent: senior-architect, backend-development Sprint Range: S3-S6


Status Summary

Progress: 100% (42/42 tasks)

SectionTitleStatusTasks
C.1Backend API Scaffold (NestJS/Prisma)Complete8/8
C.2State Machine Engine ImplementationComplete11/11
C.3Agent Orchestration FrameworkComplete8/8
C.4E-Signature & Crypto FoundationComplete5/5
C.5Integration & API LayerComplete10/10

C.1: Backend API Scaffold (NestJS/Prisma)

Sprint: S3-S4 | Priority: P0 | Depends On: None (begins after Sprint 2 presentation validation) Goal: Production-ready API framework with multi-tenant data model Reference: docs/architecture/16-prisma-data-model.md, docs/compliance/21-rbac-model.md, docs/compliance/22-rbac-permissions-matrix.md

  • C.1.1: Initialize NestJS project with TypeScript strict mode
    • Structure: Monorepo with apps/api, libs/shared, libs/qms-core
    • Config: ESLint, Prettier, Jest, Docker Compose for local dev
    • Packages: @nestjs/core, @nestjs/config, @nestjs/swagger, class-validator
    • Evidence: 31 files scaffolded, npm install 755 packages, 0 vulnerabilities
  • C.1.2: Configure Prisma ORM with PostgreSQL schema
    • Schema: 22 entities from 16-prisma-data-model.md (4 enums, 22 models)
    • Models: WorkOrder, ChangeItem, Party, JobPlan, Person, Team, Asset, Tool, AuditTrail, etc.
    • Multi-tenant: tenant_id + RLS on all tables
    • Evidence: prisma format + prisma generate pass cleanly
  • C.1.3: Implement authentication module (JWT + OAuth2)
    • Integration: auth.coditect.ai IdP (TODO stub), local JWT issuance
    • Tokens: Access (15min/900s) + refresh (7d/604800s), HS256 signing
    • Guards: JwtAuthGuard (global), @Public() exemptions
    • Evidence: 7 auth files, tsc --noEmit clean
  • C.1.4: Implement RBAC authorization system
    • Roles: 8 human + 6 agent roles from RBAC model
    • Permissions: 17 resource-based permissions with scope checks
    • Decorators: @Roles(), @RequirePermissions(), @CurrentUser()
    • SOD: 5 hard + 3 soft Separation of Duty rules enforced via SodGuard
    • Evidence: 5 guard/middleware files, tsc --noEmit clean
  • C.1.5: Create base CRUD module with audit trail
    • Pattern: Generic BaseCrudService<TCreate, TUpdate, TEntity>
    • Audit: Every mutation logged with performer, timestamp, old/new values (Part 11)
    • Pagination: Cursor-based with CursorPaginatedResult
    • Evidence: AuditService + BaseCrudService, barrel exports updated
  • C.1.6: Set up database migrations and seeding
    • Migrations: Prisma Migrate + post-migration RLS/triggers SQL
    • Seeds: Demo tenant with 4 persons, 1 team, 1 vendor, 4 experiences, 1 work order
    • Triggers: Immutable audit trail, auto-versioning, DAG cycle detection
    • Evidence: seed.ts + 00_rls_and_triggers.sql, db:setup script in package.json
  • C.1.7: Configure OpenAPI/Swagger documentation
    • Generation: Automatic from NestJS decorators (@ApiProperty, @ApiOperation, @ApiResponse)
    • UI: Swagger UI at /api/docs with JWT auth persist
    • Versioning: URI versioning /api/v1/
    • Evidence: main.ts DocumentBuilder + DTOs with @ApiProperty
  • C.1.8: Set up testing framework (unit + integration)
    • Unit: Jest with ts-jest, moduleNameMapper for @bio-qms/* paths
    • Integration: Supertest for E2E, jest-e2e.json config
    • Coverage: 80% threshold configured
    • Evidence: 32 tests pass (3 suites: health, RBAC permissions, SOD rules), tsc --noEmit clean

C.2: State Machine Engine Implementation

Sprint: S4 | Priority: P0 | Depends On: C.1 Goal: XState-powered workflow engine for QMS document lifecycles Reference: docs/state-machine/18-state-machine-specification.md, docs/state-machine/19-state-machine-with-guards.md, docs/operations/74-capa-workflow.md

  • C.2.1: Implement XState workflow engine core (80/80 tests pass, 5 suites)
    • Package: xstate v5 with TypeScript strict actors
    • Architecture: State machine definitions as JSON configs, runtime interpreter service
    • Persistence: State snapshots stored in PostgreSQL for resume/audit
    • Files: workflow.types.ts, guards.ts, work-order.machine.ts, workflow-engine.service.ts, workflow.module.ts, guards.spec.ts (32 tests), workflow-engine.service.spec.ts (16 tests)
    • Evidence: 9-state WO lifecycle, 8 named transitions, composable guard framework, FDA Part 11 audit trail, Prisma transaction persistence
  • C.2.2: Define CAPA state machine (54/54 tests pass)
    • States: INITIATED → ROOT_CAUSE_ANALYSIS → ACTION_PLANNING → IN_PROGRESS → EFFECTIVENESS_PENDING → CLOSED / CLOSED_INEFFECTIVE
    • Guards: 7 composable guards (role, classification, root cause, action plan, implementation, effectiveness)
    • Events: 7 events including REOPEN loop from CLOSED_INEFFECTIVE → INITIATED
    • Files: capa.types.ts, capa.machine.ts, capa.guards.ts, capa.guards.spec.ts (54 tests)
  • C.2.3: Define Deviation state machine (44/44 tests pass)
    • States: DETECTED → CLASSIFIED → INVESTIGATED → CAPA_LINKED → RESOLVED → CLOSED (linear workflow)
    • Guards: 5 composable guards (role, severity classification, investigation, CAPA link, resolution)
    • Events: 5 sequential transitions, strict linear progression
    • Files: deviation.types.ts, deviation.machine.ts, deviation.guards.ts, deviation.guards.spec.ts (44 tests)
  • C.2.4: Define Change Control state machine (50/50 tests pass, 196/196 full regression)
    • States: REQUEST → IMPACT_ASSESSMENT → REVIEW_BOARD → APPROVED/REJECTED → IMPLEMENTATION → VERIFICATION → CLOSED
    • Guards: 7 composable guards (role, impact assessment, review board, implementation, verification)
    • Change types: MINOR, MAJOR, EMERGENCY with risk levels LOW/MEDIUM/HIGH/CRITICAL
    • Files: change-control.types.ts, change-control.machine.ts, change-control.guards.ts, change-control.guards.spec.ts (50 tests)
  • C.2.5: Implement state transition API endpoints (239/239 tests pass)
    • POST /api/v1/workflows/:id/transition — Trigger state transition with FDA Part 11 audit
    • GET /api/v1/workflows/:id/state — Current state and available transitions
    • GET /api/v1/workflows/:id/history — Full transition history with audit trail
    • Files: workflow.controller.ts, workflow-api.service.ts, dto/transition.dto.ts, workflow.controller.spec.ts (11 tests)
    • Note: CAPA/Deviation/ChangeControl dispatch stubs pending Prisma models (C.3 dependency)
  • C.2.6: Add state machine visualization endpoint (264/264 tests pass)
    • GET /api/v1/workflows/diagram?entityType=WORK_ORDER — Mermaid stateDiagram-v2
    • Format: Mermaid markdown with state counts, transition counts, readable labels
    • Coverage: All 4 entity types (WORK_ORDER, CAPA, DEVIATION, CHANGE_CONTROL)
    • Files: diagram.ts, diagram.spec.ts (25 tests), updated index.ts barrel, workflow.controller.ts
  • C.2.7: Implement change control regulatory classification (284/284 tests pass, 70 change control tests)
    • Types: RegulatoryClassification (GXP_IMPACTING, COMPLIANCE_ADJACENT, NON_REGULATED), RiskAssessment with 3 required dimensions
    • Guards: requireRegulatoryClassification, requireRegulatoryClassificationMatchesCategory, requireRiskAssessmentForGxp, requireRegulatoryFlagForGxp
    • Registry: TC1 now 7 guards (was 4), TC2 now 5 guards (was 4)
    • FDA Ref: §820.70(b) risk assessment, auto-derive regulatoryClassification from CATEGORY_REGULATORY_MAP
  • C.2.8: Build deviation-to-change linking (306/306 tests pass, 22 cross-entity linking tests)
    • Link: Bi-directional deviation ↔ change control via linkedChangeControlIds + rootCauseChangeControlId
    • Auto-create: shouldAutoCreateInvestigation() for CRITICAL/MAJOR deviations with change links, generateInvestigationTask() with priority and description
    • Dashboard: calculateChangeEffectiveness() with 30-day observation period, baseline/current rate comparison, severity breakdown
    • Validation: validateEntityLink() enforces same-tenant constraint, isDeviationFromRecentChange() detects causal links
    • Files: cross-entity-linking.ts, cross-entity-linking.spec.ts (22 tests), updated deviation.types.ts, index.ts
  • C.2.9: Implement change effectiveness verification workflow ✅ 336/336 tests, 30 new
    • Observation: isObservationPeriodComplete(), daysRemainingInObservation() with configurable period (default 30d, min 14d, max 90d)
    • Evaluation: evaluateEffectiveness() returns EFFECTIVE/INEFFECTIVE/EXTEND_OBSERVATION with rationale based on deviation rate vs baseline, severity analysis
    • Gates: requireObservationPeriodComplete() (30-day gate), requireComplianceOfficerSignoff() (CO role check), requireEffectivenessVerified() (status gate)
    • Types: VerificationStatus, EffectivenessVerification, ComplianceSignoff
    • Files: effectiveness-verification.ts, effectiveness-verification.spec.ts (30 tests), updated index.ts
  • C.2.10: Create change communication engine ✅ 360/360 tests, 24 new
    • Stakeholders: resolveRecipients() filters by notification matrix (9 event types × role mappings), getRequiredRecipientRoles() for role lookup
    • Notification: generateNotificationSubject() + generateNotificationBody() with change details, affected systems, rollback plan for implementation events, URGENT flag for rollback
    • Audit trail: createNotificationRecord() with delivery status tracking, calculateDeliveryMetrics() with delivery/read rates, findUnacknowledgedNotifications() for compliance follow-up
    • Files: change-communication.ts, change-communication.spec.ts (24 tests), updated index.ts
  • C.2.11: Design rollback testing per change type ✅ 386/386 tests, 26 new
    • Major: requiresStagingTest: true, 60-min RTO, 4 verification checks (system restored, data integrity, no data loss, dependent systems), 3 evidence types (test report, config diff, system state)
    • Emergency: requiresProductionDrillTest: true, 15-min RTO, 5 verification checks (adds rto_within_window), 3 evidence types (test report, log file, system state)
    • Guards: requireRollbackTestPassed() validates test result meets change-type requirements, requireRollbackPlanDocumented() ensures plan exists
    • Validation: validateRollbackTestResult() checks status, environment, duration vs RTO, verification checks, evidence, step completion
    • Files: rollback-testing.ts, rollback-testing.spec.ts (26 tests), updated index.ts

C.3: Agent Orchestration Framework

Sprint: S5 | Priority: P1 | Depends On: C.1, C.2 Goal: AI agent framework for intelligent QMS assistance Reference: docs/agents/24-agent-orchestration-mapping.md, docs/agents/25-agent-orchestration-spec.md, docs/agents/26-agent-message-contracts.md

  • C.3.1: Implement agent execution engine ✅ 2026-02-15
    • Framework: Custom TypeScript engine with typed message routing
    • Files: agent.types.ts, agent-registry.ts, circuit-breaker.ts, message-router.ts, token-budget.ts
    • Tests: 77 tests passing (agents.spec.ts), 463 total
    • Context: Organization-scoped knowledge base per tenant
  • C.3.2: Create Document Analysis Agent ✅ 2026-02-15
    • File: agents/bio-qms-document-analysis.md (CODITECT-standard)
    • Capability: Analyze QMS documents for completeness, regulatory gaps
    • Coverage: FDA 21 CFR Part 11.10, 11.50, ISO 13485 4.2.3, 4.2.4, 7.5.1
    • Output: Structured analysis report (CRITICAL/MAJOR/MINOR/OBSERVATION severity)
  • C.3.3: Create CAPA Investigation Agent ✅ 2026-02-15
    • File: agents/bio-qms-capa-investigation.md (CODITECT-standard)
    • Capability: Guide root cause analysis (5-Why, Fishbone, Fault Tree, Is/Is-Not)
    • Classification: Class I/II/III with timeline (30/60/90 days)
    • Output: Investigation report draft with evidence references
  • C.3.4: Create Compliance Monitoring Agent ✅ 2026-02-15
    • File: agents/bio-qms-compliance-monitoring.md (CODITECT-standard)
    • Capability: Continuous monitoring for compliance drift
    • Coverage: FDA 21 CFR Part 11, Part 820, ISO 13485, EU MDR, ICH Q10
    • Output: Compliance dashboard with risk scoring (CRITICAL/HIGH/MEDIUM/LOW)
  • C.3.5: Implement agent API and scheduling ✅ 2026-02-15
    • Endpoints: /api/v1/agents/:type/execute, /api/v1/agents/results/:id
    • Async: Bull queue for long-running agent tasks
    • Rate limiting: Per-organization agent execution limits
    • Evidence: agent-scheduler.ts — job queue, priority ordering, rate limiting (3 concurrent/tenant, 10/min, 100/hr), job lifecycle (PENDING→RUNNING→COMPLETED/FAILED/TIMED_OUT), retry logic, timeout detection, scheduler metrics
  • C.3.6: Implement tenant-scoped context isolation ✅ 2026-02-15
    • Isolation: agent knowledge base scoped to organization, no cross-tenant data leakage
    • Validation: automated test verifying tenant A agent cannot access tenant B data
    • Vectorstore: per-tenant vector index partitioning
    • Evidence: tenant-context.ts — TenantContext creation, RLS filter generation, vector partition keys, cross-tenant attempt blocking/audit, defense-in-depth query validation, knowledge base collection scoping
  • C.3.7: Build agent decision audit trail ✅ 2026-02-15
    • Recording: every agent invocation logged with input, output, model version, confidence
    • Linkage: agent decisions linked to workflow state transitions
    • Retention: 7 years per FDA Part 11 alignment
    • Integration: feeds into Q.1.3 (AI decision audit trail)
    • Evidence: agent-audit.ts — 11 audit event types, invocation/response/system audit creation, FDA 7-year retention, workflow state transition linkage, query/filter/summary analytics, retention expiry tracking
  • C.3.8: Create coditect-core registry components for BIO-QMS agents ✅ 2026-02-15
    • Pattern: Product Registry — thin entries in coditect-core, SSOT in BIO-QMS
    • Components: 10 thin agent entries + 1 skill + 1 command + 1 hook + 1 workflow = 14 total
    • Convention: ssot: product, ssot_path: frontmatter fields
    • Analysis: internal/analysis/component-sharing-architecture/component-sharing-architecture-analysis-2026-02-15.md
    • Evidence: 14 files created in coditect-core — agents/bio-qms-*.md (10), skills/bio-qms-agent-framework/SKILL.md, commands/bio-qms-agent.md, hooks/bio-qms-agent-audit.md, docs/workflows/bio-qms-agent-workflow.md

C.4: E-Signature & Crypto Foundation

Sprint: S4 | Priority: P0 | Depends On: C.1, D.1 (gap closure) Goal: FDA 21 CFR Part 11 compliant electronic signatures Reference: docs/architecture/17-e-signature-architecture.md, docs/operations/64-security-architecture.md

  • C.4.1: Implement cryptographic signing module
    • Algorithm: ECDSA P-256 for digital signatures, SHA-256 for hashing
    • Key management: Per-user key pairs, HSM-backed for production
    • Library: Node.js crypto module or @peculiar/webcrypto
    • Evidence: 30 tests pass — crypto/hash.service.ts, crypto/local-key-provider.ts
  • C.4.2: Create electronic signature service
    • Flow: Intent confirmation → password re-auth → signature generation → timestamping
    • Meaning: Configurable signature meanings (Author, Reviewer, Approver)
    • Non-repudiation: Signed payload includes document hash, user ID, timestamp, meaning
    • Evidence: 39 tests pass — signature/signature.service.ts, signature/signature.types.ts
  • C.4.3: Implement document integrity verification
    • Hash chain: Each document version linked to previous via SHA-256
    • Verification: API endpoint to verify signature chain integrity
    • Tamper detection: Alert on any hash mismatch in chain
    • Evidence: 16 tests pass — integrity/integrity.service.ts, integrity/integrity.types.ts
  • C.4.4: Create timestamping authority integration
    • TSA: RFC 3161 compliant timestamping
    • Fallback: Internal NTP-synced timestamp if external TSA unavailable
    • Audit: All timestamps stored with source attribution
    • Evidence: 25 tests pass — timestamp/timestamp.service.ts, timestamp/timestamp.types.ts
  • C.4.5: Build signature verification UI components
    • Display: Signature status badges (valid/invalid/pending)
    • Detail: Click to see full signature chain, signer info, timestamps
    • Export: Signature verification report for auditors
    • Evidence: 21 tests pass — verification/verification.service.ts, shared/types/signature.types.ts

C.5: Integration & API Layer

Sprint: S5-S6 | Priority: P1 | Depends On: C.1-C.4 Goal: External system integrations for enterprise deployment Reference: docs/operations/67-integration-api-strategy.md

  • C.5.1: Implement webhook event system
    • Events: Document created/updated/signed, workflow transitioned, CAPA opened/closed
    • Delivery: At-least-once with exponential backoff retry
    • Management: Webhook registration API, delivery logs, test endpoint
    • Evidence: 42 tests pass — webhook.types.ts, webhook.service.ts, webhook.service.spec.ts
  • C.5.2: Create ERP integration adapter
    • Target systems: NetSuite, Odoo (adapter pattern — extensible to SAP, Oracle)
    • Data: Material master sync, batch records, quality holds
    • Protocol: REST API with configurable field mappings
    • Evidence: 51 tests pass — erp.types.ts, erp.service.ts, erp.service.spec.ts
    • Research: internal/analysis/erp-adapters/netsuite-odoo-api-comparison-2026-02-15.md
  • C.5.3: Create LIMS integration adapter
    • Target systems: LabWare, STARLIMS, Benchling (adapter pattern — extensible)
    • Data: Test results, specifications, out-of-spec events
    • Trigger: OOS results auto-create deviations in QMS via DeviationCreator callback
    • Features: Configurable field mappings with transforms, OOS severity classification, OOT warning detection
    • Evidence: 77 tests pass — lims.types.ts, lims.service.ts, lims.service.spec.ts
  • C.5.4: Create document management integration
    • Target systems: SharePoint, Google Drive, Box (adapter pattern — extensible)
    • Features: Bi-directional sync, version tracking, metadata mapping with transforms
    • Controlled copies: Generate read-only PDF with watermark/signature via ControlledCopyGenerator callback
    • Evidence: 67 tests pass — docmgmt.types.ts, docmgmt.service.ts, docmgmt.service.spec.ts
  • C.5.5: Implement API rate limiting and quotas
    • Limits: Per-organization, per-endpoint rate limits with sliding window counters
    • Quotas: Monthly API call quotas per subscription tier (free/starter/professional/enterprise)
    • Headers: Standard rate limit headers (X-RateLimit-Limit/Remaining/Reset/Policy, Retry-After)
    • Features: IP allowlist bypass, endpoint-specific overrides with wildcard patterns, blocked endpoints, quota alert levels (normal/warning/critical/exceeded), days-remaining estimation
    • Evidence: 58 tests pass — ratelimit.types.ts, ratelimit.service.ts, ratelimit.service.spec.ts
  • C.5.6: Create integration testing suite
    • Mocks: Mock adapters for all external systems (webhook, ERP, LIMS, DMS, rate-limit stores + HTTP clients)
    • Contract tests: Consumer-driven contract verification engine with 5 matcher types (exact, type, regex, includes, array_contains), JSON path resolution
    • E2E: Full integration flow tests with test sandbox — webhook→ERP sync, rate-limited LIMS, DMS+webhook flows
    • Utilities: Test sandbox with HTTP call logging and event tracking, mock stats calculator
    • Evidence: 54 tests pass, 943/943 full regression — integration.types.ts, integration.service.ts, integration.service.spec.ts, index.ts
  • C.5.7: Implement HL7 FHIR data exchange
    • Standard: HL7 FHIR R4 for clinical data exchange
    • Resources: Patient, Observation, DiagnosticReport, MedicationAdministration
    • Format: JSON FHIR bundles with validation against US Core profiles
    • Integration: Bi-directional sync with EHR systems (Epic, Cerner, Allscripts, Meditech)
    • Features: SMART on FHIR + OAuth2 + Basic auth, connection management, resource CRUD, incremental sync with tokens, profile-based validation
    • Evidence: 67 tests pass, 1010/1010 full regression — fhir.types.ts, fhir.service.ts, fhir.service.spec.ts, index.ts
  • C.5.8: Build batch record traceability — 57 tests pass, 1067/1067 full regression
    • Tracking: full traceability from raw material → in-process → finished product (MaterialType taxonomy, BatchStatus state machine)
    • Integration: material master sync from ERP with type mapping and auto-create/update
    • Genealogy: batch genealogy tree with forward/backward BFS tracing, cycle detection, maxDepth
    • Alerts: quality hold propagation across linked batches with configurable direction and depth
  • C.5.9: Create Electronic Batch Record (EBR) generation — 41 tests pass, 1108/1108 full regression
    • Template: configurable EBR templates per product/process, draft→active→retired lifecycle
    • Data capture: real-time data from LIMS, MES, equipment (manual + automatic), field validation (number/text/select)
    • Review: sequential approval workflow with Part 11 e-signatures, role-based steps (operator→supervisor→QA)
    • Export: JSON export with full audit trail, deviation links, content hash for integrity
  • C.5.10: Implement quality hold automation — 35 tests pass, 1143/1143 full regression
    • Trigger: configurable rules (7 event types × 3 severity thresholds), auto-hold on OOS/deviation/inspection
    • Scope: batch-level, lot-level, or material-level holds with propagation
    • Notification: notification groups with multi-channel dispatch (email/SMS/in-app/webhook), acknowledgment tracking
    • Release: formal release workflow with investigation closure gate, dual approval (QA + Production), conditional release

Updated: 2026-02-17 Compliance: CODITECT Track Nomenclature Standard (ADR-054)