# Verixa — User Requirements Specification

# Module 12: Document Control / SOP / Controlled Documents

| Field | Value |
|---|---|
| Document ID | VRX-URS-12 |
| Version | 1.0 |
| Status | Final — ready for QA, Validation, Regulatory Affairs, Information Security, Document Control Manager, and Founder approval. URS approval is separate from validation execution. This document becomes "Approved Controlled URS — released for engineering implementation and validation planning" only after signature capture in the Document Approval block. It becomes "Released for validation execution" only after the module migration evidence gate (URS-12-VAL-008) and validation evidence pack are satisfied. |
| Document Type | User Requirements Specification (URS) |
| GAMP 5 Category | Category 5 — Custom Application |
| Code Modules | Target implementation binding: expected primary code modules `documents`, `document-review`, `document-library`, with read-side surfaces from `regulatory`. Expected API mounts: `/api/v1/documents`, `/api/v1/document-reviews`, `/api/v1/document-library`, `/api/v1/regulatory`. Expected route / service / schema / type / migration ownership per the four named code modules. Implementation evidence remains subject to repository verification and validation evidence. |
| Architecture Bindings | This module is subject to **ARCH-AI-001 AI Optionality and Manual Continuity**. AI-assisted document review, AI classification, AI metadata extraction, and RAG retrieval are advisory under EU AI Act Article 13. Confirmed in-code AI surfaces on the document layer include the RAG service (`packages/backend/src/modules/document-library/rag.service.ts`, which consumes `AiGatewayService` for OpenAI `text-embedding-3-small` embeddings). Every AI-assisted document surface (AI document classification, AI metadata extraction, AI review-finding suggestion, AI retention disposition suggestion, RAG semantic retrieval, MIRA document copilot) shall provide a fully functional manual document control path; document creation, review routing, reviewer sign-off, approval, publication, retention disposition, and keyword retrieval shall be executable when AI services are disabled, degraded, or overridden. AI-generated classifications and review suggestions shall be visibly labelled as advisory and shall not overwrite system-of-record metadata without explicit human confirmation. RAG retrieval shall degrade gracefully to keyword search when the embedding service is unavailable. No AI service shall be the sole path to approve, publish, retire, or retrieve a controlled document. This module binds ARCH-AI-001 AC-1, AC-2, AC-3, AC-4, AC-5, AC-6, and AC-7. |
| Regulatory Classification | Critical infrastructure substrate — operates the canonical document master registry, the document type / lifecycle / versioning / approval / distribution / retention engine, the controlled-copy watermarking / export, the controlled document review workflow, and the controlled-document organisation sub-domains (Regulatory Library, Process Library, Project Library) with RAG ingestion, retrieval, and provenance. Module 12 owns controlled documents, SOPs, document versions, document review, approval, effectiveness, distribution, read receipts, controlled-copy exports, document periodic review, and document retirement. URS-13 owns enterprise Change Control. Document revisions requiring formal change control link to URS-13 change-control records before affected document versions become effective. |
| Date of Issue | 2026-05-06 |
| Module Owner (Engineering) | Document Control / Document Review / Document Library Squad |
| Module Owner (Quality Validation) | CSV / CSA Lead — Document Control |
| Module Owner (Compliance) | Quality Assurance, Regulatory Affairs, Document Control Manager, Knowledge Library Steward |
| Approving Authority | Founder / Chairman & MD; QA Head; Validation Head; RA Head; Information Security Head; Document Control Manager |

---

## 0. Document Framing

### 0.1 Purpose of this document

This URS defines the target expected state for Verixa's Document Control / Document Review / Knowledge Libraries module (Module 12). It is the binding contract between product, engineering, quality validation, regulatory affairs, document control, the Knowledge Library steward function, information security, and the executive authority for the design, implementation, validation, release, and on-going periodic review of three interconnected substrates: **(a) Document Control** — the canonical document master registry covering every controlled document type (SOPs, work instructions, policies, forms, templates, specifications, protocols, reports, memos, manuals, master files including TMF/PMF/VMF/SMF, evidence packages, signed agreements), the document lifecycle state machine, the versioning scheme, the per-type approval workflow matrix, the periodic review cadence, the distribution and read-receipt apparatus, and the controlled-copy watermarking and export; **(b) Document Review** — the controlled review workflow with checklisting, assignments, comments, revision-review cycles, segregation-of-duties between initiator and approver, and reviewer-attributable e-signature; and **(c) Knowledge Libraries** — three controlled subdomains (Regulatory Library, Process Library, Project Library) with explicit governed classification, RAG-ready ingestion and indexing, citation-grade retrieval with provenance, governed entitlements beyond direct user grants, and retention/disposition workflows. Compliance with this URS is mandatory.

### 0.2 Audience

Engineering, QA, Validation, Regulatory Affairs, Document Control management, Knowledge Library Stewards, Information Security, executive authority, the platform's Implementation team, internal and external auditors, and inspectors from regulatory bodies (FDA, EMA, MHRA, Health Canada, CDSCO, PIC/S, PMDA). The plain-language primer (§0.4) and worked examples (§3.5) make Module 12 accessible to non-domain engineers, product owners, validation engineers, document control specialists, and library curators.

### 0.3 How to read this document

Each requirement has a unique identifier. "MUST" denotes a mandatory requirement; "SHOULD" denotes a strong recommendation; "MAY" denotes an option. The document is self-contained: front end (§5), back end (§6), data model (§6.2), application programming interface (§6.3), workflow (§6.4), business rules (§6.5), audit (§6.6), security (§12), regulatory mapping (§14), test cases (§16), and validation evidence (§17) are all in this single file. Every requirement is mandatory unless explicitly marked SHOULD (strong recommendation) or MAY (option).

### 0.4 Plain-language primer for non-domain readers

In a regulated pharmaceutical operation, **two things are true at once**: every action the company takes must be traceable to a written procedure or specification, and the procedural and regulatory knowledge that informs those actions must be retrievable, attributable, and trustworthy. Module 12 owns both — the documents themselves and the knowledge libraries that organise, retrieve, and reference them.

A **document** in regulatory speak is anything that defines what a person should do, how a process should run, what a specification looks like, what a finding states, what an attestation captures, or what a signed agreement contains. The launch document types include **Standard Operating Procedures (SOPs)** — the written procedures that operators follow; **Work Instructions (WIs)** — more granular than SOPs, often equipment-specific; **Policies** — high-level statements of intent; **Forms** — blank templates that become records when filled in; **Templates** — for protocols, reports, memos; **Specifications** — quality acceptance criteria for materials, intermediates, and finished products; **Protocols** — structured plans for studies, validations, qualifications; **Reports** — summaries of executed activity; **Memos** — formal communications with regulatory significance; **Manuals** — comprehensive reference documents; **Master Files** — Trial Master File (TMF) for clinical, Product Master File (PMF) for manufacturing, Validation Master File (VMF) for validation, Study Master File (SMF) for general studies; **Evidence Packages** — bundles of records supporting a regulatory claim; **Signed Agreements** — quality agreements, master service agreements, data processing agreements, contracts.

Every document has a **lifecycle**: starts as `draft`, moves to `in_review` when an author submits for review, becomes `approved` when the named approver(s) sign, becomes `effective` from the effective-from date, and ultimately becomes `superseded` (when a new version replaces it) or `retired` (when the document is no longer in use). Every transition is electronically signed. Module 12 owns this lifecycle and the per-document-type approval workflow matrix that defines who must approve which type of document.

Documents are **versioned** with a major.minor scheme: minor revisions (e.g., 1.0 → 1.1) capture editorial / non-substantive changes; major revisions (e.g., 1.0 → 2.0) capture substantive changes that affect intent, scope, or regulatory commitments. Major revisions to GxP-significant documents (SOPs, specifications, master file components) are linked to a referenceable record raised under URS-13.

Documents are **periodically reviewed**: SOPs and work instructions are reviewed every 2 years by default (tenants may configure shorter intervals; tenants may not extend beyond the default without controlled regulatory justification and approved change control); policies every 3 years; specifications on cadence aligned with the URS-10 product specification cycle; master file components on the master file's own cadence. Failure to review on cadence triggers `regulatory_concern` document suspension.

Documents are **distributed and acknowledged**: when a document becomes `effective`, the named distribution list (typically operator role / department) receives a read-acknowledgement task; users acknowledge through the Controlled Approval Modal; URS-28 training records are updated where the document is training-required. Read-acknowledgement is the platform's compliance evidence that the document has been seen by the people who need to follow it.

Documents are **exported as controlled copies** with watermarks indicating "Controlled Copy — for use only at [tenant.site]" and the timestamp of export. Uncontrolled copies (unwatermarked) are also available but clearly labelled "Uncontrolled — for reference only".

Document Review is a **separate workflow** from authoring. When an author submits a document for review, the platform creates a controlled review object distinct from the document itself: assignments to named reviewers per the document type's approval matrix, a checklist of review items (regulatory completeness, scientific rigour, clarity, internal consistency, link integrity), a comment thread that supports inline and document-level comments, a revision-review cycle for re-review after the author revises, and reviewer-attributable e-signature on completion. DOC-009, Verixa enforces a hard **segregation-of-duties** rule at the service layer: the review initiator cannot also be the approver, and a completed review cannot be modified. The review workflow is owned by code module `document-review` (`packages/backend/src/modules/document-review/`).

The **Knowledge Libraries** are three controlled subdomains: the **Regulatory Library** (global regulations, guidance documents, ICH/FDA/EMA/MHRA/Health Canada/PIC/S documents, monographs, classification taxonomies); the **Process Library** (internal SOPs, work instructions, policies, methods, templates, organised by process domain); and the **Project Library** (project- and study-linked working records, references, and project deliverables). Each library has its own classification taxonomy, governance, and entitlement model. DOC-018, the Regulatory Library and the generic document library are not merged in the retrieval-trust model — regulatory knowledge remains source-distinct even when search is federated across libraries.

The libraries are **RAG-ready**: every document and library entry, when ingested, is chunked, embedded (using OpenAI `text-embedding-3-small` via the AI Gateway service), indexed, and made retrievable by semantic search. Retrieval is **citation-grade**: every retrieved chunk carries provenance (source document ID, version, library, chunk position, confidence score) so that downstream AI use (MIRA copilot, Mira Findings Suggester, Module 32 agent orchestration) can attribute every reference. RAG retrieval is **advisory** under EU AI Act Article 13 and is bound by ARCH-AI-001: it is not the sole retrieval path; keyword search remains as a graceful-degradation fallback when the embedding service is unavailable.

ARCH-AI-001 — **AI Optionality and Manual Continuity** — is the platform-level architecture binding that requires every AI surface in Verixa to provide a non-AI manual continuity path. For Module 12, this means: AI document classification is advisory and never overwrites system-of-record metadata without explicit human confirmation; AI review-finding suggestions are advisory and never replace reviewer attribution; RAG retrieval degrades to keyword search when embeddings are unavailable; no AI service is the sole path to approve, publish, retire, or retrieve a controlled document. This is not optional. The platform refuses to lock the user out of any document workflow because an AI service is degraded.

Module 12 is the **substrate that every other module's evidence and knowledge flows through**. URS-08 onboarding documents (MSA, DPA, KYC, executive authority memos), URS-09 site licences and inspection findings, URS-10 specifications and registration dossiers, URS-11 quality agreements and audit findings, URS-07 protocols and final reports — all are stored as Module 12 controlled documents with their own lifecycle, classified into the appropriate Knowledge Library, and made retrievable by RAG.

### 0.5 Document and Document Review lifecycle diagrams

```mermaid
stateDiagram-v2
  state "Document Lifecycle" as DocLC {
    [*] --> draft : Author creates document
    draft --> in_review : Author submits for review
    in_review --> approved : Approver(s) sign per DEC-12-06 matrix
    in_review --> draft : Returned for correction
    approved --> effective : Effective-from date reached
    effective --> superseded : New version supersedes
    effective --> retired : Retirement workflow signed
    superseded --> [*]
    retired --> [*]
    draft --> withdrawn : Author withdraws (terminal)
    withdrawn --> [*]
  }
```

```mermaid
stateDiagram-v2
  state "Document Review Lifecycle" as DRLC {
    [*] --> initiated : Reviewer assignments created
    initiated --> in_progress : Reviewer opens checklist
    in_progress --> revision_requested : Reviewer requests author revision
    revision_requested --> in_progress : Author submits revision; new review cycle
    in_progress --> approved : All checklist items resolved; reviewer e-signs approval
    in_progress --> rejected : Reviewer e-signs rejection (terminal for this cycle)
    approved --> [*]
    rejected --> [*]
    note right of in_progress
      SoD: review initiator cannot be approver
      (DOC-009 service-layer rule)
    end note
  }
```

Diagram 0.5-A — Document and Document Review lifecycles. Both are electronically signed at each transition; the document approval workflow is per-type per the launch matrices; the review workflow is owned by the `document-review` code module and enforces SoD at the service layer.

### 0.6 Glossary of key terms used in this document

| Term | Definition |
|---|---|
| Approved (document) | Document state after named approver(s) have signed; not yet effective if `effective_from` is in the future. |
| Approved (review) | Review-cycle state after reviewer has e-signed approval of the under-review document. |
| ARCH-AI-001 | Platform architecture binding that requires every AI surface to provide manual continuity (AC-1..AC-7); see §6.7. |
| Advisory (AI) | EU AI Act Art. 13 classification for AI suggestions that do not autonomously act on system-of-record records; requires user transparency and human override. |
| Citation-grade retrieval | Retrieval that returns source provenance (document ID, version, library, chunk position, confidence) sufficient to attribute every quoted or summarised passage. |
| Controlled Copy | An exported document copy with watermark indicating its controlled status and the export context. |
| Distribution | The act of making an effective document available to its intended audience and capturing read-receipts. |
| Document | Any controlled artefact in the registry (SOP, WI, policy, form, template, specification, protocol, report, memo, manual, master file component, evidence package, signed agreement). |
| Document Library | The library/catalog/storage-metadata layer (`document-library` code module) over which documents are classified, indexed, retrieved, and entitled. |
| Document Review | The separate review workflow (`document-review` code module) that runs over documents in `in_review` state, with checklisting, comments, SoD-enforced reviewer assignment, and e-signed completion. |
| Draft | Document state during authoring; not yet submitted for review. |
| Effective | Document state after `effective_from` date; the document is in force. |
| Embedding | Vector representation of a chunk of document content produced by an embedding model (launch model: OpenAI `text-embedding-3-small` via AI Gateway). |
| Knowledge Library | Generic term for any of the three controlled subdomains (Regulatory / Process / Project) governed by their own classification taxonomy, governance, and entitlement model. |
| Master File | Aggregated controlled-document set (TMF / PMF / VMF / SMF) per study or product. |
| Periodic review | Scheduled review of a document at a defined cadence; refresh of effective date and content currency. |
| Process Library | The Knowledge Library subdomain governing internal procedural documents (SOPs, WIs, policies, methods, templates) by process domain. |
| Project Library | The Knowledge Library subdomain governing project- and study-linked working records, references, and project deliverables. |
| Provenance | The attribution metadata attached to every retrieved chunk: source document ID, version, library, chunk position, confidence score, retrieval mode. |
| RAG | Retrieval-Augmented Generation. The pattern by which an AI system retrieves chunks from a knowledge corpus before generating an answer; in Verixa, retrieval is advisory and provenance-bearing. |
| Read-receipt | The electronically-signed acknowledgement by a recipient that they have read and understood the effective document. |
| Regulatory Library | The Knowledge Library subdomain governing global regulations, guidance, ICH/FDA/EMA/MHRA documents, monographs; source-distinct from internal documents per DOC-018. |
| Retention Class | The retention-policy classification that drives `retention_period_years`, `disposition_method`, and legal-hold eligibility. |
| Retired | Terminal document state; no longer in use; preserved for audit. |
| Revision Review | A review cycle initiated when an author submits a revision following a `revision_requested` state. |
| SOP | Standard Operating Procedure. |
| Superseded | Document state after a new version replaces it; the superseded version is preserved. |
| WI | Work Instruction. |
| Withdrawn | Terminal pre-approval state; document cancelled before effectiveness. |

### 0.7 Module 12 architectural picture

```mermaid
graph LR
  subgraph M12 [Module 12 — Document Control / Document Review / Knowledge Libraries]
    DOC[Document Registry<br/>code: documents]
    DLC[Document Lifecycle]
    DAPP[Document Approval Workflows]
    DDIST[Distribution / Read-Receipt]
    DEXP[Controlled-Copy Export]
    DR[Document Review Workflow<br/>code: document-review]
    DLIB[Document Library / Catalog<br/>code: document-library]
    REG[Regulatory Library<br/>read-side: regulatory]
    PROC[Process Library]
    PROJ[Project Library]
    RAG[RAG Ingestion + Retrieval<br/>code: document-library/rag.service.ts]
    AIBIND[ARCH-AI-001 Binding<br/>AC-1..AC-7]
  end

  M3[URS-03 Active Scope] <--> DOC
  M4[URS-04 Workflow / E-Sign] --> DLC
  M4 --> DR
  M5[URS-05 Authority] --> DAPP
  M6[URS-06 Audit Substrate] --> DLC
  M6 --> DR
  M7[URS-07 Study] <--> DOC
  M7 <--> PROJ
  M8[URS-08 Tenant Lifecycle] --> DOC
  M9[URS-09 Site] <--> DOC
  M10[URS-10 Product] <--> DOC
  M10 <--> REG
  M11[URS-11 Supplier] <--> DOC
  M13[URS-13] --> DOC
  M27[URS-27 Regulatory Intelligence] --> REG
  M28[URS-28 Training] <--> DDIST
  M30[URS-30 Notifications] --> DLC
  M30 --> DR
  M32[URS-32 MIRA Copilot] --> RAG
  AIBIND -.governs.-> RAG
  AIBIND -.governs.-> DR
  DOC --> ALL[All other URS modules consume documents]
  RAG --> ALL2[All other modules retrieve via citation-grade RAG]
```

Diagram 0.7-A — Module 12 architectural picture. Three connected code modules (`documents`, `document-review`, `document-library`) plus a regulatory read-side surface, with three Knowledge Library subdomains and the RAG service, all governed by ARCH-AI-001.

---

## 1. Module Purpose

Module 12 establishes Document Control / Document Review / Knowledge Libraries as the canonical substrate for "what is the written rule" and "how do I find and reference the relevant procedure or regulation" in Verixa. It owns three interconnected substrates — the Document Master Registry (covering every controlled document type), the Document Review workflow (controlling how documents are reviewed before approval), and the three Knowledge Libraries (Regulatory, Process, Project) with RAG-ready ingestion and citation-grade retrieval — sharing common lifecycle / signature / audit / scope / discovery substrate. Module 12 is consumed by URS-08 (onboarding documents), URS-09 (site licences, inspection findings), URS-10 (specifications, registration dossiers), URS-11 (quality agreements, MSAs, audit findings), URS-07 (protocols, final reports, master file components), URS-13 (governs document revisions linked to platform-level lifecycle records), URS-27 (regulatory intelligence feeds into the Regulatory Library), URS-28 (training-required documents), URS-32 (MIRA copilot retrieves from RAG), URS-14 onward (deviation findings, CAPAs reference and update controlled documents), and every regulated module that produces or retrieves a controlled record.

Module 12 is the **single source of truth for "show me the procedure" and "show me the relevant regulation, with citation"** — the inspector's and the operator's two most common requests beyond the audit trail itself.

---

## 2. Scope

### 2.1 In scope

#### Document Control register

- The document master registry per DEC-12-01: per-tenant registry of every controlled document with `id`, `tenant_id`, `display_id`, `title`, `document_type`, `document_subtype`, `gxp_classification` (`gmp` / `glp` / `gcp` / `gdp` / `multi` / `non_gxp`), `parent_document_id` (nullable; for documents in document sets), `scope_jsonb` (per URS-05 §6.2.1 canonical authority scope dimension registry), `current_version_id`, `lifecycle_state`, `created_by`, `created_at`, `effective_from`, `effective_to` (nullable), `next_review_due_at`, `retention_class`, `confidentiality_classification` (`public` / `internal` / `confidential` / `restricted`), `vertical_classification_jsonb`. 
- Document types at launch: `sop` (Standard Operating Procedure), `wi` (Work Instruction), `policy`, `form`, `template`, `specification`, `protocol`, `report`, `memo`, `manual`, `master_file_component` (with sub-types `tmf` / `pmf` / `vmf` / `smf` / `general`), `evidence_package`, `signed_agreement` (with sub-types `quality_agreement` / `master_service_agreement` / `dpa` / `nda` / `licence` / `kyc_pack_component`), `regulatory_dossier_component`, `audit_finding_register`, `audit_response_register`, `risk_register`, `qualification_protocol`, `qualification_report`, `validation_protocol`, `validation_report`, `analytical_method`, `monograph_reference`, `consent_form` (clinical), `informed_consent` (clinical), `inspection_findings_letter` (e.g., FDA Form 483), `inspection_response_letter`, `cleanroom_certificate`, `licence_evidence`, `dmf_authorisation_letter`, `bioequivalence_study_evidence`, `gcp_readiness_pack` (clinical activation), `vertical_specific_risk_register` (high-risk vertical activation), `founder_activation_review_memo`, `founder_offboarding_memo`. Adding a type or sub-type is a Class 1 change. 
- Document lifecycle state machine per DEC-12-02: `draft → in_review → approved → effective → superseded | retired`; plus terminal pre-approval `withdrawn`. 
- Document versioning per DEC-12-03: major.minor scheme; section-level checkout/checkin; `document_versions` table records each section check-in. 
- Document approval per DEC-12-04: per-type approval workflow matrix; approvals via the controlled e-signature path with the ControlledApprovalModal contract (password + meaningOfSignature + reasonForChange). 
- Effective / supersede / retire control per DEC-12-05: `effective_from`-date-driven activation; supersede chain with explicit predecessor link; retirement workflow with retention-class compliance. 
- Distribution and read-receipt per DEC-12-08: when a document becomes `effective`, named recipients receive a controlled read-acknowledgement task; URS-30 notifications drive delivery; URS-28 training records are updated where the document is training-required.
- Controlled-copy export per DEC-12-12: watermarked exports with tenant + site + timestamp + user identity + document version watermark; uncontrolled-copy exports clearly labelled.
- Periodic review per DEC-12-09: SOPs and WIs every 2 years (default); policies every 3 years; specifications aligned with URS-10 product specification cycle; master file components on the master file's own cadence; missed review triggers `regulatory_concern` document suspension.

#### Document Review workflow

- Document Review is a **separate workflow** distinct from document authoring, with its own routes (`/api/v1/document-reviews`), service, and contract objects. 
- Review initiation: when an author submits a document for review, the platform creates a controlled review object with reviewer assignments per the document type's approval matrix, a checklist of review items, and a status of `initiated`.
- Checklist management: the review checklist supports launch checklist items (regulatory completeness, scientific rigour, clarity, internal consistency, link integrity); checklist items are submitted with reviewer attribution.
- Comment management: inline and document-level comments are supported with add / list / resolve operations; comments are reviewer-attributable and timestamped.
- Assignment management: assignments to named reviewers; current user sees their open review assignments; reviewers initiated by current user are listed for tracking.
- Revision review cycle: when a reviewer requests revision, the document returns to `draft`; on author resubmission, the prior review object is closed and a new revision review cycle is initiated; comments and checklist results from prior cycles are preserved for audit.
- Completion: review completion supports approve / reject; completion with e-signature uses the ControlledApprovalModal contract (password + meaningOfSignature + reasonForChange); completed reviews are immutable.
- **Segregation-of-Duties**:, the service layer enforces that the review initiator cannot also be the approver. 

#### Knowledge Libraries

- Three controlled subdomains, each with its own classification taxonomy, governance, and entitlement model.
  - **Regulatory Library** — global regulations and guidance, ICH guidelines, FDA / EMA / MHRA / Health Canada / PIC/S / PMDA / CDSCO documents, monographs (USP / EP / JP / IP), regulatory commitments. Source-distinct from internal documents. Connected via the `regulatory` code module (`/api/v1/regulatory`) which exposes feed intake (regulatory feeds, items), submissions, milestones, commitments, regulatory calendar events, inspection records, and observations. 
  - **Process Library** — internal SOPs, work instructions, policies, methods, templates, organised by process domain (manufacturing, QC, QA, RA, clinical, distribution, vendor management, IT/security). 
  - **Project Library** — project- and study-linked working records, references, and project deliverables. Connected via `ProjectDocument` shared type. 
- Library classification: explicit governed classification, not heuristic. The target implementation MUST classify via explicit reviewer-confirmed metadata with AI advisory suggestions (ARCH-AI-001 AC-3); heuristic-only classification on title / MIME is NOT permitted. 
- Library access: governed entitlements via role / group / scope policy beyond direct user grants. The target implementation MUST support role-, group-, and scope-policy-based entitlements in addition to any direct user grants. 
- Retention, disposition, legal hold: retention metadata fields exist; full disposition workflow with legal-hold logic and reviewer-confirmed disposal e-signature is MUST.

#### RAG ingestion, retrieval, and provenance

- RAG ingestion: every document and library entry, on transition to `effective` or on explicit ingest, is chunked, embedded via `AiGatewayService` using OpenAI `text-embedding-3-small` (evidence in `document-library/rag.service.ts`), and indexed in `document_embeddings`. 
- RAG retrieval: chunk-level semantic retrieval with citation-grade provenance (source document ID, version, library, chunk position, confidence score, retrieval mode). 
- Graceful degradation: when the embedding service is unavailable, RAG retrieval degrades to keyword search across `document_library` title and description; the retrieval response carries a `retrieval_mode` field (`semantic` / `keyword_fallback`) so downstream consumers can label the result appropriately. 
- Reviewable AI/reference use: every RAG retrieval that downstream feeds an AI-generated answer (MIRA, Findings Suggester, etc.) is logged with: query, retrieved chunks (IDs + provenance), model used, response, user, timestamp, accepted/modified/rejected. Logged in `ai_requests` / `llm_audit_log` (URS-06 substrate). 

#### ARCH-AI-001 binding (Architecture binding; AC-1..AC-7)

- Every AI surface in Module 12 (AI document classification, AI metadata extraction, AI review-finding suggestion, AI retention disposition suggestion, RAG semantic retrieval, MIRA document copilot) shall provide a fully functional manual document control path; all AI-generated content shall be visibly labelled as advisory and shall not overwrite system-of-record metadata without explicit human confirmation. RAG retrieval shall degrade gracefully to keyword search when the embedding service is unavailable. No AI service shall be the sole path to approve, publish, retire, or retrieve a controlled document. AC-1 (manual primary path), AC-2 (advisory secondary), AC-3 (visible advisory labelling), AC-4 (no autonomous write to system of record), AC-5 (full AI audit trail), AC-6 (override capability), AC-7 (graceful degradation) all bind on this module. 

#### Cross-module wiring

- Documents are referenced by every consuming module (URS-07, URS-08, URS-09, URS-10, URS-11, URS-13, URS-14 forward, URS-22, URS-28).
- Library entries are referenced for procedural and regulatory guidance by every operating module.
- Regulatory Library connects to URS-27 Regulatory Intelligence feed/item ingestion.
- Process Library connects to URS-28 Training Management (training-required documents derive from Process Library SOPs/WIs).
- Project Library connects to URS-07 Study Management.
- Document linkage from URS-13 — Module 12 exposes the document reference for URS-13 to consume; URS-13 owns its own lifecycle.
- MIRA copilot (URS-32) consumes RAG retrieval from Module 12.

### 2.2 Out of scope

The following are NOT in Module 12 scope:

- **URS-13 register, lifecycle, impact assessment, review, effectiveness check, closure** — these belong to URS-13 (standalone module). Module 12 documents may be referenced by an open URS-13 record, but Module 12 does not own any URS-13 entity, route, or workflow.
- **Training records, training assignments, training effectiveness checks** — these belong to URS-28 (Training Management and Qualification). Module 12 supplies the training-required document; URS-28 owns the training record.
- **Regulatory submissions to authorities** — URS-27 owns submission lifecycle. Module 12 supplies the submission-component documents.
- **Inspection findings register, response register, CAPA workflow** — URS-21 owns Findings; URS-18 owns CAPA. Module 12 supplies the document type but not the workflow.
- **Authentication, session management, RBAC** — URS-01 / URS-02. Module 12 consumes the authenticated user identity and role-permission grants.
- **Audit trail substrate** — URS-06 owns the hash-chained audit log. Module 12 writes to it.
- **MIRA copilot orchestration logic** — URS-32 owns MIRA. Module 12 supplies RAG.
- **The AI Gateway (`AiGatewayService`)** — URS-32-related infrastructure. Module 12 consumes via `rag.service.ts`.

### 2.3 Closed launch decisions

The following decisions are **closed** for launch and recorded in §18.1 with their rationale:

| ID | Decision | Disposition |
|---|---|---|
| DEC-12-01 | Document master registry shape and per-tenant scoping | Locked. |
| DEC-12-02 | Document lifecycle state machine | Locked: `draft → in_review → approved → effective → superseded | retired`; plus terminal `withdrawn`. DOC-001 lifecycle in `lifecycle.ts`. |
| DEC-12-03 | Versioning scheme | Locked: major.minor; section-level checkout/checkin records to `document_versions`. |
| DEC-12-04 | Approval workflow per document type | Locked: per-type matrix governed by URS-04 / URS-05. |
| DEC-12-05 | Effective / supersede / retire chain | Locked: explicit supersede route added. |
| DEC-12-06 | Approver matrix at launch | Locked: SOPs, WIs, policies, specifications, protocols, master file components, signed agreements all carry per-type approver lists in DOC-004 detail. |
| DEC-12-07 | Periodic review cadence defaults | Locked: SOP/WI = 2 years; policy = 3 years; specification = aligned with URS-10 cadence; master file = aligned with master file cadence. |
| DEC-12-08 | Distribution + read-receipt mechanism | Locked: URS-30 notifications + Controlled Approval Modal acknowledgement. |
| DEC-12-09 | Periodic review missed-cadence behaviour | Locked: `regulatory_concern` suspension auto-applied; published banner; URS-30 notification; remediation requires document owner + QA co-sign. |
| DEC-12-10 | Document review separate workflow | Locked: target `document-review` code module is the expected owner of the review workflow; ownership is target binding and remains subject to repository verification and validation evidence. |
| DEC-12-11 | Document review SoD rule | Locked: review initiator cannot be approver; service-layer rule. |
| DEC-12-12 | Controlled-copy export watermark | Locked: tenant + site + timestamp + user + document version watermark. |
| DEC-12-13 | Knowledge Library subdomains at launch | Locked: Regulatory, Process, Project — three distinct controlled subdomains/008/009. |
| DEC-12-14 | Regulatory and document library retrieval-trust separation | Locked: regulatory knowledge remains source-distinct in retrieval-trust model. |
| DEC-12-15 | Library classification model | Locked: explicit governed classification with reviewer-confirmed metadata; AI advisory suggestion bound by ARCH-AI-001 AC-3. |
| DEC-12-16 | Library entitlement model | Locked: role + group + scope-policy entitlements in addition to direct user grants. |
| DEC-12-17 | RAG embedding model at launch | Locked: OpenAI `text-embedding-3-small` via `AiGatewayService`. evidence in `document-library/rag.service.ts`. |
| DEC-12-18 | Major-revision-to-URS-13 linkage | Locked: a major revision to a GxP-significant document creates a referenceable URS-13 link; the URS-13 record itself is owned by URS-13. |
| DEC-12-19 | RAG graceful degradation | Locked: retrieval falls back to keyword search when embedding service unavailable; `retrieval_mode` field carries the indicator. Per ARCH-AI-001 AC-7. |
| DEC-12-20 | Advisory AI labelling | Locked: every AI-generated classification, metadata extraction, review suggestion, retention disposition is visibly labelled as advisory and requires human confirmation before being written to system of record. Per ARCH-AI-001 AC-3, AC-4. |
| DEC-12-21 | RAG provenance fields | Locked: every retrieved chunk carries source document ID, version, library, chunk position, confidence, retrieval mode. |
| DEC-12-22 | AI request audit trail | Locked: every RAG retrieval used in a downstream AI-generated answer is logged in `ai_requests` / `llm_audit_log` (URS-06 substrate) with query, chunks (IDs + provenance), model, response, accept/modify/reject. Per ARCH-AI-001 AC-5. |
| DEC-12-23 | Retention class catalog at launch | Locked: per-type retention classes aligned to `21 CFR §211.180` (GMP), `21 CFR §312.62/§820.180` (clinical/devices), `21 CFR Part 11` electronic record retention, EU GMP Chapter 4 + Annex 11, ICH E6(R3). |
| DEC-12-24 | Confidentiality classifications | Locked: `public`, `internal`, `confidential`, `restricted`. |
| DEC-12-25 | Tenant offboarding cascade | Locked: per URS-08 offboarding contract, documents transition to terminal preserved-for-audit state; library entries are detached from active retrieval but preserved for retention. |

---

## 3. User Roles and Permissions

### 3.1 Architecture

Module 12 consumes the URS-01 authenticated identity, the URS-02 RBAC permission grants, the URS-03 active scope, the URS-04 workflow / e-signature substrate, and the URS-05 Authority Profile registry. Module 12 does not maintain an independent user identity model; it consumes the platform's three-guard hierarchy — RoleGuard, PermissionGuard, AuthorityGuard — and exposes role-permission-authority matrices for each Module 12 surface.

### 3.2 Role definitions

| Role | Purpose | Module 12 ownership |
|---|---|---|
| `viewer` | Read-only access to documents within scope | Read controlled documents; read library entries; perform RAG queries |
| `reviewer` | Document review participation | All `viewer` + perform review checklist items + submit comments + revision-review cycles |
| `quality_lead` | Quality oversight; document approver for QA-owned types | All `reviewer` + approve QA-owned documents + co-sign Process Library curation + approve retention disposition |
| `document_owner` | Per-document authoring authority | All `reviewer` + create/draft documents within owned types + initiate review + propose retirement |
| `library_steward` | Knowledge Library curation | All `quality_lead` + classify library entries + maintain Regulatory Library / Process Library / Project Library taxonomies + curate RAG ingestion catalogues |
| `regulatory_affairs_lead` | Regulatory submissions and Regulatory Library curation | All `quality_lead` + co-sign regulatory dossier components + curate Regulatory Library + approve regulatory feed item ingestion |
| `admin` | Tenant-level administration | All `quality_lead` + manage tenant document type configuration + manage retention classes + manage entitlement policy |
| `platform_admin` | Verixa platform administration | Tenant-scoped Module 12 actions are support / break-glass only (with reason, support-ticket reference, electronic signature, `PLATFORM_TENANT_ACCESS_USED` audit emit, SOC alert). Routine tenant document administration is the responsibility of tenant `admin` users. |
| `super_admin` | Verixa super-admin | All platform admin + emergency platform-level actions (executive break-glass) |

### 3.3 Authority Profiles consumed by Module 12

| Authority Profile | Description |
|---|---|
| `controlled_document_approval` | E-signature authority to approve a document version (the per-type approval matrix governs who may hold this authority for which type) |
| `controlled_document_retirement` | E-signature authority to retire a document |
| `controlled_document_supersede` | E-signature authority to supersede a document with a new version |
| `document_review_approval` | E-signature authority to approve completion of a Document Review cycle |
| `document_review_rejection` | E-signature authority to reject completion of a Document Review cycle |
| `library_classification` | Authority to confirm the controlled classification of a library entry (overrides AI advisory) |
| `library_entitlement_grant` | Authority to grant role-/group-/scope-based entitlement to a library subdomain |
| `library_disposition` | Authority to e-sign retention disposition for a library entry |
| `regulatory_library_ingestion` | Authority to confirm regulatory feed item ingestion into the Regulatory Library |
| `executive_break_glass_document_hold` | Executive-authority-level authority to place an emergency hold on a document or library subdomain (executive authority only) |

### 3.4 Segregation-of-Duties rules

| SoD Rule | Description |
|---|---|
| SoD-12-01 | The author of a document cannot also be the document approver. |
| SoD-12-02 | The initiator of a Document Review cannot also be the review approver. (DOC-009 — service-layer enforced in `document-review/service.ts`.) |
| SoD-12-03 | The user who classifies a library entry cannot also be the user who approves the library entitlement policy that governs that entry. |
| SoD-12-04 | The user who approves a regulatory feed item ingestion cannot also be the user who authored the feed item (relevant when a regulated user manually imports a regulatory document). |
| SoD-12-05 | The user who confirms a retention disposition cannot also be the user who originally authored the document being disposed of. |
| SoD-12-06 | The user who places a executive break-glass document hold cannot be the user who released the hold (separate executive authority e-signature). |

### 3.5 Worked examples

**Example 1: Manufacturing SOP revision and review.** A document owner (Process Library steward) creates v2.0 of `SOP-MFG-014` to incorporate a process change. The author submits for review; the platform creates a review object with reviewers `quality_lead` (QA), `manufacturing_lead` (process owner), and `regulatory_affairs_lead` (regulatory check). Per SoD-12-02 the author cannot self-approve. Reviewers complete checklist items, leave inline comments. The QA reviewer requests a revision to clarify the cleaning verification step. The author updates and resubmits; a new review cycle initiates with prior comments preserved. All reviewers then approve via Controlled Approval Modal e-signature. The approver-of-record (per the approval matrix) e-signs the document approval. The document moves `approved → effective` on the configured `effective_from` date. URS-30 distributes the controlled document; URS-28 issues a re-training task to all operators with the prior version in their training record.

**Example 2: Regulatory Library ingestion.** A Regulatory Affairs analyst pulls a new FDA Draft Guidance via the URS-27 Regulatory Intelligence feed. The platform's AI advisory service classifies the feed item as "FDA Guidance — clinical safety" with a 0.84 confidence score; the classification is visibly labelled as advisory (ARCH-AI-001 AC-3). The `regulatory_affairs_lead` reviews the suggested classification and confirms it (or overrides — ARCH-AI-001 AC-6). The feed item is e-signed-confirmed for ingestion into the Regulatory Library. The `RegulatoryDocumentLink` is created back to internal Module 12 documents that reference the underlying topic (e.g., `SOP-CLIN-001` for clinical safety reporting). RAG ingests the new entry; embeddings are computed; future MIRA copilot retrievals over "FDA clinical safety reporting" return this entry with provenance.

**Example 3: Process Library SOP retrieval via RAG.** A QA analyst opens the Document Library search and queries "cleaning validation acceptance criteria for solid oral dosage". The RAG retrieval returns chunks from `SOP-QC-021` (cleaning validation), `WI-MFG-031` (cleaning verification at line), and `SPEC-CLEAN-002` (cleaning specification), each with provenance: source document ID, version, library subdomain, chunk position, confidence, retrieval mode (`semantic`). The analyst clicks through to the source document for full context. The retrieval is logged in `ai_requests` (per ARCH-AI-001 AC-5) with query, retrieved chunk IDs + provenance, retrieval mode, user, timestamp. No AI-generated answer is produced from this query — RAG retrieval alone is in the request.

**Example 4: RAG graceful degradation.** The AI Gateway is unavailable due to an upstream OpenAI outage. A user issues the same retrieval query. The RAG service detects the embedding service unavailability and falls back to keyword search across `document_library` title, description, and tag fields. The response carries `retrieval_mode: keyword_fallback` and a banner in the frontend visibly indicates "RAG semantic retrieval unavailable — keyword search results shown". The user retrieves results — same UX, lower retrieval quality. ARCH-AI-001 AC-7 satisfied. No user is locked out of document retrieval because of an AI service degradation.

**Example 5: AI advisory classification override.** A library steward reviews a newly uploaded internal report. The AI advisory service suggests classification as `LibraryTier=process / domain=qc`. The steward disagrees — the report is project-linked to a specific stability study and properly belongs in the Project Library. The steward selects "Override AI advisory" (ARCH-AI-001 AC-6); the override is logged in `ai_requests` with the reason ("project-linked to STAB-2026-014"); the entry is classified to `LibraryTier=project`. The AI advisory output is preserved in the audit trail; the human override is the system of record.

**Example 6: executive break-glass document hold.** A regulatory authority issues an inquiry that may require freezing a class of documents pending response. Executive authority invokes `executive_break_glass_document_hold` authority (a Tier-1 global authority). All matching documents transition to a `held` lifecycle modifier (still readable, distribution paused). The hold is logged in URS-06 audit substrate; URS-30 notifies the document owners and QA. Release of the hold requires a separate executive authority e-signature per SoD-12-06.

### 3.6 Role-permission matrix (Module 12 administrative surface only)

| Permission | viewer | reviewer | document_owner | quality_lead | library_steward | regulatory_affairs_lead | admin | platform_admin |
|---|---|---|---|---|---|---|---|---|
| `documents:read` | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | support / break-glass only |
| `documents:create` | ✗ | ✗ | ✓ | ✓ | ✓ | ✓ | ✓ | support / break-glass only |
| `documents:update_draft` | ✗ | ✗ | ✓ | ✓ | ✓ | ✓ | ✓ | support / break-glass only |
| `documents:submit_for_review` | ✗ | ✗ | ✓ | ✓ | ✓ | ✓ | ✓ | support / break-glass only |
| `documents:approve` (with authority) | ✗ | ✗ | ✗ | ✓ | ✓ | ✓ | ✓ | support / break-glass only |
| `documents:effective` (with authority) | ✗ | ✗ | ✗ | ✓ | ✓ | ✓ | ✓ | support / break-glass only |
| `documents:supersede` (with authority) | ✗ | ✗ | ✗ | ✓ | ✓ | ✓ | ✓ | support / break-glass only |
| `documents:retire` (with authority) | ✗ | ✗ | ✗ | ✓ | ✓ | ✓ | ✓ | support / break-glass only |
| `documents:read_audit` | ✗ | ✗ | ✗ | ✓ | ✓ | ✓ | ✓ | support / break-glass only |
| `document-review:initiate` | ✗ | ✗ | ✓ | ✓ | ✓ | ✓ | ✓ | support / break-glass only |
| `document-review:checklist_submit` | ✗ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | support / break-glass only |
| `document-review:comment` | ✗ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | support / break-glass only |
| `document-review:request_revision` | ✗ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | support / break-glass only |
| `document-review:complete` (with authority + SoD) | ✗ | ✗ | ✗ | ✓ | ✓ | ✓ | ✓ | support / break-glass only |
| `document-library:read` | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | support / break-glass only |
| `document-library:upload` | ✗ | ✗ | ✓ | ✓ | ✓ | ✓ | ✓ | support / break-glass only |
| `document-library:classify` | ✗ | ✗ | ✗ | ✓ | ✓ | ✓ | ✓ | support / break-glass only |
| `document-library:rag_query` | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | support / break-glass only |
| `document-library:entitlement_grant` | ✗ | ✗ | ✗ | ✗ | ✓ | ✓ | ✓ | support / break-glass only |
| `document-library:retention_disposition` (with authority) | ✗ | ✗ | ✗ | ✓ | ✓ | ✓ | ✓ | support / break-glass only |
| `regulatory:feed_ingest` (with authority) | ✗ | ✗ | ✗ | ✗ | ✓ | ✓ | ✓ | support / break-glass only |
| `regulatory:link_to_document` | ✗ | ✗ | ✗ | ✓ | ✓ | ✓ | ✓ | support / break-glass only |
| `documents:executive_break_glass_hold` | ✗ | ✗ | ✗ | ✗ | ✗ | ✗ | ✗ | ✗ (executive authority only) |

---

## 4. End-to-End User Journeys

The 28 launch user journeys cover Document Control authoring and lifecycle, Document Review separate-workflow operations, Knowledge Library ingestion and retrieval, RAG advisory use under ARCH-AI-001, and executive break-glass governance. Each journey is end-to-end: from the user's first action to the final audit-trail entry. In-scope journeys cover Document Review SoD, Knowledge Library curation, RAG retrieval, and AI advisory override under ARCH-AI-001.

### J-01 — Document creation from template

A `document_owner` selects the appropriate template from the Process Library (e.g., SOP template). The platform creates a `draft` document with the template body and prefilled metadata (`document_type`, `gxp_classification`, `tenant_id`, `scope_jsonb` from URS-03 active scope). The author edits content and selects sections requiring section-level checkout. URS-06 audit substrate records the creation event.

### J-02 — Submit for review

The author clicks "Submit for review". The platform validates draft completeness, creates the Document Review object with reviewer assignments per the document type's approval matrix, and transitions the document `draft → in_review`. URS-30 notifies reviewers. URS-06 records the transition.

### J-03 — Review checklist and signatures

A reviewer opens their review queue (`/api/v1/document-reviews/me/assignments`). They open the under-review document, view the checklist, complete each item with attribution, leave inline and document-level comments. On final approval the reviewer e-signs via the Controlled Approval Modal (password + meaningOfSignature + reasonForChange). The platform enforces SoD-12-02 (initiator ≠ approver) at the service layer. The review object transitions `in_progress → approved`. URS-06 records the review e-signature.

### J-04 — Document return-for-correction

A reviewer requests revision via the review interface. The platform transitions the review `in_progress → revision_requested` and the document `in_review → draft`. The author addresses the comments and resubmits. The platform creates a new review cycle (closing the prior cycle with `revision_requested` terminal state and preserving its comments and checklist results). URS-30 notifies prior reviewers of the revision cycle.

### J-05 — Document becomes effective

After all approvers e-sign, the document moves to `approved`. On the configured `effective_from` date, an automated job transitions it to `effective`. URS-30 issues distribution notifications to the named distribution list. URS-28 issues training-required tasks where applicable. The document is visible in the Process Library / Project Library / Regulatory Library per its classification. RAG ingestion is triggered.

### J-06 — Read-receipt acknowledgement

A user receives a distribution notification. They open the document in the Document Library. They click "I have read and understood". The platform displays the Controlled Approval Modal; the user enters password + reason. URS-06 records the read-receipt as an attributable e-signature. URS-28 updates the user's training record where the document is training-required.

### J-07 — Periodic review cycle initiated

The cron-driven periodic review scheduler detects `next_review_due_at` within the configured warning window (default 90 days). URS-30 notifies the document owner and QA lead. The owner initiates a review-only cycle (no content change) or a revision cycle (content change → new version). The cycle goes through the standard review workflow.

### J-08 — Periodic review missed — auto-suspension

`next_review_due_at` passes without an initiated review. The platform automatically applies a `regulatory_concern` lifecycle modifier; the document is shown with a banner "OVERDUE FOR REVIEW — review must complete by [date]". URS-30 notifies the owner, QA, and `quality_lead`. Remediation requires the document owner + QA co-sign of either a deferral memo or a completed review. URS-06 records the auto-suspension and remediation events.

### J-09 — Document Review SoD enforcement

A `document_owner` initiates a Document Review and attempts to also act as the review approver. The `document-review` service rejects with HTTP 403 and error code `DOCUMENT_REVIEW_SOD_VIOLATION`; the response includes the prohibited combination (reviewerUserId == initiatorUserId) and a remediation hint. URS-06 records the SoD-violation attempt as an `auth_audit` entry. The platform offers the user a re-assign action that transfers the review approval slot to a different qualified reviewer.

### J-10 — Document retirement

A `document_owner` proposes retirement (e.g., the document is being superseded by a new SOP). The platform creates a retirement workflow: QA review of retention compliance, retention-class-driven evaluation of disposal vs. preservation, e-signature by the retirement authority. The document transitions `effective → retired`. Retention class drives whether the document content is preserved for audit (default for GxP) or disposed of (rare; non-GxP types only). URS-06 records the retirement chain.

### J-11 — Distribution and read-receipt compliance dashboard

A QA lead opens the distribution-compliance dashboard for a Process Library SOP. The dashboard shows: distribution list size, read-receipts received, % compliance, pending recipients, overdue recipients (past the read-by-date). The lead initiates a follow-up campaign via URS-30 to overdue recipients. The campaign is logged to URS-06.

### J-12 — Controlled-copy export

An auditor requests a copy of an SOP for inspection review. A `quality_lead` exports a controlled copy. The platform applies a watermark to every page indicating: tenant, site, timestamp (ISO 8601), exporting user, document version, and a unique export ID. The export event is logged in URS-06 with the export ID for traceability. The controlled copy carries an explicit footer line "Controlled Copy — for use only at [tenant.site]".

### J-13 — Uncontrolled-copy export (clearly labelled)

A user exports an uncontrolled copy for offline reference. Every page is watermarked "Uncontrolled — for reference only" and the export event is logged. Uncontrolled copies are explicitly outside the controlled-document audit chain.

### J-14 — Restricted document access denied

A `viewer` attempts to retrieve a `restricted` confidentiality-classification document. The platform's PermissionGuard + library entitlement check denies with HTTP 403 and error code `LIBRARY_ENTITLEMENT_DENIED`. URS-06 records the access-denied event. The user sees a sanitised denial message; the audit log captures the user, document ID, attempted action, and policy that denied.

### J-15 — Cross-references update on document version increment

`SOP-MFG-014` increments to v2.0. The platform identifies all controlled cross-references (URS-13 records referencing v1.x; URS-28 training records assigned at v1.x; URS-21 Findings referencing v1.x; URS-22 Inspection records referencing v1.x). The platform issues notifications to the owners of those cross-referencing records and offers a "review at new version" action. The cross-reference table preserves the version reference at the time of citation; the audit trail preserves the link history.

### J-16 — Knowledge Library entry classification

A library steward uploads a new internal document. The AI advisory service suggests classification (`LibraryTier=process / domain=qc / sub-tier=cleaning`) with a confidence score, visibly labelled "AI-generated — requires human review" (ARCH-AI-001 AC-3). The steward reviews the suggestion, accepts or overrides, and e-signs the classification via the Controlled Approval Modal. The classification is system-of-record only after human confirmation (ARCH-AI-001 AC-4). URS-06 records the AI advisory output, the human decision, and the override reason if applicable.

### J-17 — Knowledge Library entitlement grant

A library steward grants role-based entitlement to the Process Library subdomain `qa-internal-policies` to the `quality_lead` role. The grant is e-signed via Controlled Approval Modal. SoD-12-03 enforced (the steward who classifies cannot also approve the entitlement policy that governs that classification). URS-06 records the entitlement grant. The PermissionGuard / entitlement service evaluates the new policy on subsequent access requests.

### J-18 — Regulatory Library feed item ingestion

A regulatory feed (URS-27) delivers a new FDA Draft Guidance. The AI advisory service classifies (e.g., "FDA Guidance — clinical safety", confidence 0.84). A `regulatory_affairs_lead` reviews and confirms (or overrides). On confirmation, the feed item is ingested into the Regulatory Library; a `RegulatoryDocumentLink` is created back to internal Module 12 documents that reference the underlying topic. RAG ingestion is triggered. URS-06 records the ingestion + link creation.

### J-19 — Project Library project-link record

A study manager attaches a working report to a study (URS-07). The platform creates a `ProjectDocument` linkage record (canonical shared type `ProjectDocument`); the document is classified into the Project Library subdomain `study-{studyId}`; entitlements default to study team plus QA. The project link is reviewable in the study record and in the Project Library subdomain view. URS-06 records the link.

### J-20 — RAG semantic retrieval with citation-grade provenance

A QA analyst issues a retrieval query "cleaning validation acceptance criteria for solid oral dosage" via the Document Library search. The RAG service computes an embedding via `AiGatewayService` (OpenAI `text-embedding-3-small`), retrieves top-K chunks with provenance, and returns them with `retrieval_mode: semantic`, source document IDs + versions, library subdomain, chunk position, confidence score. The frontend renders results with "Source: SOP-QC-021 v1.3 (Process Library, chunk 4 of 12, confidence 0.91)" labelling. The retrieval is logged in `ai_requests` with query + chunk IDs + provenance + user + timestamp.

### J-21 — RAG graceful degradation to keyword search (canonical ARCH-AI-001 AC-7, DOC-019)

The AI Gateway is unavailable due to upstream outage. The user issues the same retrieval query. The RAG service detects the embedding service unavailability, falls back to keyword search across `document_library` title, description, and tag fields. The response carries `retrieval_mode: keyword_fallback`. The frontend renders a banner "RAG semantic retrieval unavailable — keyword search results shown". The user retrieves results and is not locked out. URS-06 records the degraded retrieval mode.

### J-22 — AI advisory classification override (canonical ARCH-AI-001 AC-6)

A library steward reviews an AI advisory classification suggestion they disagree with. They select "Override AI advisory" and provide a reason. The platform records the AI suggestion, the human override, the reason, the user, and the timestamp in `ai_requests` and URS-06 audit trail. The classification of record is the human override; the AI suggestion is preserved as advisory metadata.

### J-23 — Citation-grade reference from MIRA copilot (canonical ARCH-AI-001 AC-5, DOC-012)

A user asks the MIRA copilot (URS-32) "What is our cleaning validation acceptance criterion for tablets?". MIRA invokes RAG retrieval (Module 12); receives chunks with provenance; generates an answer that cites every source with document ID + version + library + confidence. The user can click the citation to retrieve the source. The full request — query, retrieved chunks (IDs + provenance), AI model, answer, user, timestamp, accept/modify/reject — is logged in `llm_audit_log`. The answer is visibly labelled "AI-generated — verify citations" (ARCH-AI-001 AC-3).

### J-24 — Library retention disposition

A retention-policy schedule identifies a class of documents reaching `effective_to + retention_period_years`. The platform initiates a disposition workflow: a library steward + QA reviewer evaluate each document; legal-hold checks are run; the disposition decision (dispose / extend retention / preserve permanently) is e-signed. SoD-12-05 enforced (steward + reviewer cannot be the original author). URS-06 records the disposition chain.

### J-25 — Auditor reads document and library evidence pack

An external auditor (FDA, EMA) requests evidence on the procedural control of cleaning validation. The platform exports a controlled evidence pack: SOP-QC-021 (current effective version + version history + approval signatures), the Document Review records for the latest revision, the read-receipt log, the related URS-13 cross-reference links, the Regulatory Library citations to relevant guidance (USP <1058>, FDA Cleaning Validation Guidance), and the RAG retrieval audit trail. The pack is watermarked, e-signed by `quality_lead`, and downloaded as a zipped PDF bundle. URS-06 records the export.

### J-26 — Master File / document set maintenance

A document set (e.g., a TMF for a clinical study) accumulates child documents over the study lifecycle. The platform shows the master file with hierarchical view: parent_document → child documents with their lifecycle states. A `document_owner` updates a child document; the master file's `last_updated` propagates; the master file's effective version is recomputed; URS-06 records the master file update.

### J-27 — executive break-glass document hold

Executive authority receives a regulatory inquiry that may require freezing a class of documents pending response. Executive authority invokes `executive_break_glass_document_hold` authority. All matching documents (per scope filter) transition to a `held` lifecycle modifier (still readable, distribution paused, edits paused). URS-30 notifies document owners and QA. URS-06 records the hold. Release of the hold requires a separate executive authority e-signature (SoD-12-06).

### J-28 — Tenant offboarding cascades to Module 12

The tenant lifecycle (URS-08) transitions to `offboarding`. Module 12 receives the cascade signal: documents transition to `archived_for_audit`; library entries are detached from active retrieval; RAG indices are removed from active retrieval but the underlying documents are preserved per retention class; entitlements are revoked; controlled-copy export is restricted to the offboarding extract pack only. URS-06 records the cascade.

---

## 5. Front-End Expected State

### 5.1 Routes

| Route | Purpose |
|---|---|
| `/documents` | Document Library landing — search, filter by library subdomain, RAG query |
| `/documents/library/regulatory` | Regulatory Library subdomain view |
| `/documents/library/process` | Process Library subdomain view |
| `/documents/library/project` | Project Library subdomain view |
| `/documents/:id` | Document detail (versions, lifecycle, distribution, audit) |
| `/documents/:id/version/:versionId` | Version detail with section-by-section view |
| `/documents/:id/review` | Document Review interface (active reviews) |
| `/documents/:id/audit` | Per-document audit trail view |
| `/documents/new` | Create draft from template |
| `/documents/templates` | Template selector |
| `/document-reviews` | Document Review queue (assigned to me) |
| `/document-reviews/initiated-by-me` | Reviews I have initiated |
| `/document-reviews/:reviewId` | Review detail with checklist + comments |
| `/document-reviews/:reviewId/complete` | Controlled Approval Modal for review e-signature |
| `/library/classify/:entryId` | Library entry classification (AI advisory + human confirm) |
| `/library/entitlements` | Entitlement policy management (`library_steward+`) |
| `/library/disposition` | Retention disposition workflow |
| `/regulatory` | Regulatory Library subdomain (read-only for most; ingest for `regulatory_affairs_lead`) |
| `/regulatory/feeds` | Regulatory feed configuration |
| `/regulatory/items/:itemId` | Regulatory feed item detail with ingest action |
| `/distribution-compliance` | Distribution + read-receipt compliance dashboard |
| `/executive/document-holds` | executive break-glass holds (executive authority only) |

### 5.2 Component requirements

- **DocumentList / DocumentCard** — display lifecycle state, library subdomain badge, classification, last-modified, due-for-review indicator. AI advisory metadata shown with "AI-suggested" pill (ARCH-AI-001 AC-3).
- **VersionHistoryPanel** — timeline of versions with approval signatures and effective dates.
- **DocumentReviewCard** — assigned to me, due-by, reviewer status, checklist progress.
- **ReviewChecklistComponent** — checklist items with attribution and completion state.
- **CommentThread** — inline + document-level comments, resolve action.
- **ControlledApprovalModal** — password + meaningOfSignature + reasonForChange. NEVER ip / userAgent / timestamp / performedBy (those are server-side).
- **RAGSearchBar** — query input + advanced filters (library subdomain, GxP class, document type, version date range).
- **RAGResultCard** — chunk text + provenance (source document ID + version + library + chunk position + confidence + retrieval mode badge).
- **RetrievalModeBanner** — visible banner when `retrieval_mode = keyword_fallback` indicating RAG semantic retrieval is unavailable (ARCH-AI-001 AC-7).
- **AIAdvisoryBanner** — visible "AI-generated — requires human review" banner over any AI-generated classification, suggestion, or summary (ARCH-AI-001 AC-3).
- **EntitlementPolicyEditor** — role / group / scope policy editor for library entitlement.
- **DispositionDashboard** — documents reaching retention threshold; disposition action queue.
- **AuditTrailViewer** — per-document chronological event view.
- **WatermarkPreview** — preview the watermark that will be applied to controlled-copy export.

### 5.3 Accessibility and internationalisation

- WCAG 2.1 AA compliance for all components.
- Keyboard navigation: every interactive element reachable via tab; the Controlled Approval Modal is fully keyboard-operable.
- Screen reader: every action has an `aria-label`; AI advisory pills are announced explicitly ("AI-generated suggestion, requires review").
- Internationalisation: all UI strings in resource files; date/time per user locale; numeric per locale.
- Colour contrast: AI advisory pill, retrieval-mode banner, lifecycle state badges all meet 4.5:1 contrast.

---

## 6. Back-End Expected State

### 6.1 Domain entities

| Entity | Purpose | Code module |
|---|---|---|
| `documents` | Master document registry | `documents` |
| `document_versions` | Per-version content + section history | `documents` |
| `document_sections` | Section-level checkout/checkin | `documents` |
| `document_lifecycle_events` | State-transition audit substrate | `documents` |
| `document_signatures` | E-signature records (approval / retirement / supersede) | `documents` |
| `document_distribution_lists` | Distribution-list configuration | `documents` |
| `document_read_receipts` | Read-receipt records | `documents` |
| `document_reviews` | Review workflow objects | `document-review` |
| `document_review_assignments` | Reviewer assignments per review | `document-review` |
| `document_review_checklist_items` | Checklist + completion records | `document-review` |
| `document_review_comments` | Inline + doc-level comments | `document-review` |
| `document_review_signatures` | Reviewer e-signature records | `document-review` |
| `document_library` | Library catalog (across subdomains) | `document-library` |
| `document_library_classification` | Classification (subdomain + sub-tier + domain) | `document-library` |
| `document_library_entitlements` | Role / group / scope entitlement policy | `document-library` |
| `document_embeddings` | RAG chunk embeddings + provenance | `document-library` |
| `document_retention_policies` | Retention class definitions | `document-library` |
| `document_dispositions` | Disposition workflow records | `document-library` |
| `regulatory_feeds` | Regulatory feed configuration | `regulatory` |
| `regulatory_items` | Ingested regulatory feed items | `regulatory` |
| `regulatory_document_links` | Linkage from regulatory items to internal documents | `regulatory` |
| `regulatory_submissions` | Submission lifecycle records (consumed read-only here) | `regulatory` |
| `regulatory_commitments` | Commitment register (consumed read-only here) | `regulatory` |
| `ai_requests` | AI request audit substrate (URS-06) | shared |
| `llm_audit_log` | LLM-specific audit substrate (URS-06) | shared |
| `auth_audit_log` | Auth-related audit substrate (URS-06) | shared |

### 6.1.1 Diagram 6.1-A — Module 12 entity-relationship overview

```mermaid
erDiagram
  DOCUMENTS ||--o{ DOCUMENT_VERSIONS : has
  DOCUMENTS ||--o{ DOCUMENT_SECTIONS : has
  DOCUMENTS ||--o{ DOCUMENT_LIFECYCLE_EVENTS : emits
  DOCUMENTS ||--o{ DOCUMENT_SIGNATURES : carries
  DOCUMENTS ||--o{ DOCUMENT_DISTRIBUTION_LISTS : assigned_to
  DOCUMENT_DISTRIBUTION_LISTS ||--o{ DOCUMENT_READ_RECEIPTS : produces
  DOCUMENTS ||--o{ DOCUMENT_REVIEWS : reviewed_by
  DOCUMENT_REVIEWS ||--o{ DOCUMENT_REVIEW_ASSIGNMENTS : assigns
  DOCUMENT_REVIEWS ||--o{ DOCUMENT_REVIEW_CHECKLIST_ITEMS : checklist
  DOCUMENT_REVIEWS ||--o{ DOCUMENT_REVIEW_COMMENTS : comments
  DOCUMENT_REVIEWS ||--o{ DOCUMENT_REVIEW_SIGNATURES : e_signed_with
  DOCUMENTS ||--o{ DOCUMENT_LIBRARY : indexed_in
  DOCUMENT_LIBRARY ||--o{ DOCUMENT_LIBRARY_CLASSIFICATION : classified_as
  DOCUMENT_LIBRARY ||--o{ DOCUMENT_LIBRARY_ENTITLEMENTS : governed_by
  DOCUMENT_LIBRARY ||--o{ DOCUMENT_EMBEDDINGS : embedded_into
  DOCUMENT_LIBRARY ||--o{ DOCUMENT_RETENTION_POLICIES : retained_under
  DOCUMENT_LIBRARY ||--o{ DOCUMENT_DISPOSITIONS : disposed_by
  REGULATORY_FEEDS ||--o{ REGULATORY_ITEMS : ingests
  REGULATORY_ITEMS ||--o{ REGULATORY_DOCUMENT_LINKS : links_to
  DOCUMENTS ||--o{ REGULATORY_DOCUMENT_LINKS : linked_from
  DOCUMENT_EMBEDDINGS ||--o{ AI_REQUESTS : retrieved_for
  AI_REQUESTS ||--o{ LLM_AUDIT_LOG : audited_in
  DOCUMENTS ||--o{ AUTH_AUDIT_LOG : access_logged
```

Diagram 6.1-A — entity-relationship overview. Three connected code modules (`documents`, `document-review`, `document-library`) plus a regulatory linkage layer. AI substrate tables (`ai_requests`, `llm_audit_log`) are URS-06 shared substrate consumed for ARCH-AI-001 AC-5 audit.

### 6.1.2 Diagram 6.1-B — Document lifecycle state machine

```mermaid
stateDiagram-v2
  [*] --> draft : create / template
  draft --> in_review : submit_for_review
  draft --> withdrawn : withdraw
  in_review --> draft : revision_requested (returns)
  in_review --> approved : approver_e_signs (per type matrix)
  approved --> effective : effective_from reached
  effective --> superseded : new version supersedes
  effective --> retired : retirement_workflow_e_signed
  effective --> held : founder_break_glass_hold
  held --> effective : founder_break_glass_release
  superseded --> [*]
  retired --> [*]
  withdrawn --> [*]
  note right of in_review
    Document Review (separate workflow, code:document-review)
    runs in parallel with document state in_review.
    SoD: review initiator ≠ approver (DOC-009).
  end note
```

Diagram 6.1-B — document lifecycle state machine including the `held` modifier reachable via executive break-glass and reverting only via separate executive authority e-signature (SoD-12-06).

### 6.1.3 Diagram 6.1-C — Knowledge Library subdomain governance and entitlement model

```mermaid
flowchart TB
  subgraph DocumentLibrary [Document Library — code: document-library]
    direction TB
    subgraph Reg [Regulatory Library]
      RegItems[Regulatory feed items / global guidance]
      RegLink[RegulatoryDocumentLink to internal docs]
    end
    subgraph Proc [Process Library]
      ProcSOP[SOPs / WIs / Policies / Methods / Templates]
      ProcDom[Process domain taxonomy]
    end
    subgraph Proj [Project Library]
      ProjDoc[ProjectDocument linkage]
      ProjStudy[Study/Project working records]
    end
  end
  subgraph Entitlement [Entitlement Policy Layer]
    Role[Role-based]
    Group[Group-based]
    Scope[Scope-policy-based]
    Direct[Direct-user grants — legacy]
  end
  Reg --> Entitlement
  Proc --> Entitlement
  Proj --> Entitlement
  Entitlement --> AccessDecision[Access decision per request]
  RegSrc[URS-27 Regulatory Intelligence feeds] --> Reg
  InternalAuth[Internal authoring path] --> Proc
  ProjLink[URS-07 Study Management linkage] --> Proj
  RegLink -.cross-link.-> Proc
  RegLink -.cross-link.-> Proj
  Reg -.retrieval-trust:source-distinct.-> RAGTrust[RAG retrieval trust separation - DOC-018]
```

Diagram 6.1-C — Knowledge Library subdomain governance. Three subdomains (Regulatory / Process / Project), each governed by an entitlement policy layer that combines role-, group-, and scope-policy-based grants with direct-user grants (legacy). Regulatory remains source-distinct in the retrieval-trust model even though search may federate across subdomains.

### 6.1.4 Diagram 6.1-D — RAG ingestion, retrieval, provenance, and graceful degradation

```mermaid
sequenceDiagram
  participant Author
  participant DocLib as document-library service
  participant RAG as rag.service.ts
  participant AIGW as AiGatewayService
  participant Embed as OpenAI text-embedding-3-small
  participant DB as document_embeddings
  participant User
  participant Audit as ai_requests / llm_audit_log

  Note over Author,DB: --- Ingestion path ---
  Author->>DocLib: upload document / transition to effective
  DocLib->>RAG: indexDocument(documentId, version)
  RAG->>RAG: chunk content
  RAG->>AIGW: embed(chunk)
  AIGW->>Embed: text-embedding-3-small
  Embed-->>AIGW: vector
  AIGW-->>RAG: vector
  RAG->>DB: persist chunk + vector + provenance
  RAG->>Audit: log ingestion event

  Note over User,Audit: --- Retrieval path: semantic ---
  User->>DocLib: rag_query("cleaning validation criteria")
  DocLib->>RAG: retrieve(query)
  RAG->>AIGW: embed(query)
  AIGW->>Embed: text-embedding-3-small
  Embed-->>AIGW: vector
  AIGW-->>RAG: vector
  RAG->>DB: cosine top-K
  DB-->>RAG: chunks + provenance
  RAG->>Audit: log retrieval (query, chunk_ids, provenance, mode=semantic)
  RAG-->>User: results with retrieval_mode=semantic

  Note over User,Audit: --- Retrieval path: graceful degradation ---
  User->>DocLib: rag_query (during AI Gateway outage)
  DocLib->>RAG: retrieve(query)
  RAG->>AIGW: embed(query)
  AIGW-->>RAG: ERROR / unavailable
  RAG->>DB: keyword search across title, description, tags
  DB-->>RAG: keyword matches
  RAG->>Audit: log retrieval (query, results, mode=keyword_fallback)
  RAG-->>User: results with retrieval_mode=keyword_fallback + UI banner
```

Diagram 6.1-D — RAG ingestion + retrieval flow with provenance and graceful degradation per ARCH-AI-001 AC-7. The retrieval path always logs to `ai_requests` and (if downstream LLM use) `llm_audit_log` with full provenance per ARCH-AI-001 AC-5.

### 6.2 Data model requirements

| Requirement | Statement |
|---|---|
| URS-12-DATA-001 | `documents` table with `id`, `tenant_id`, `display_id`, `title`, `document_type`, `document_subtype`, `gxp_classification`, `parent_document_id`, `scope_jsonb`, `current_version_id`, `lifecycle_state`, `created_by`, `created_at`, `updated_at`, `effective_from`, `effective_to`, `next_review_due_at`, `retention_class`, `confidentiality_classification`, `vertical_classification_jsonb`. |
| URS-12-DATA-002 | `documents.scope_jsonb` consistent with `document.schema.ts` (must persist `site_id` and `product_id` when present).  |
| URS-12-DATA-003 | `document_versions` with `version_number` (major.minor), `content`, `created_by`, `created_at`, `signed_by`, `signed_at`.  |
| URS-12-DATA-004 | `document_sections` for section-level checkout/checkin with `version_id`, `section_id`, `checked_out_by`, `checked_in_at`. |
| URS-12-DATA-005 | `document_lifecycle_events` append-only with `from_state`, `to_state`, `actor_user_id`, `at_timestamp`, `signature_id` (nullable).  |
| URS-12-DATA-006 | `document_signatures` records meaningOfSignature, reasonForChange, password proof reference; never persists raw password. |
| URS-12-DATA-007 | `document_distribution_lists` per-document distribution list with role / group / user attribution.  |
| URS-12-DATA-008 | `document_read_receipts` with `user_id`, `document_id`, `version_id`, `acknowledged_at`, `signature_id`. |
| URS-12-DATA-009 | `document_reviews` with `id`, `document_id`, `initiator_user_id`, `status`, `created_at`, `closed_at`. |
| URS-12-DATA-010 | `document_review_assignments` with `review_id`, `reviewer_user_id`, `assigned_at`, `status`. |
| URS-12-DATA-011 | `document_review_checklist_items` with `review_id`, `checklist_item_id`, `result`, `submitter_user_id`, `submitted_at`. |
| URS-12-DATA-012 | `document_review_comments` with `review_id`, `comment_type` (inline / document), `selection_anchor` (nullable for inline), `body`, `author_user_id`, `created_at`, `resolved_at` (nullable), `resolved_by` (nullable). |
| URS-12-DATA-013 | `document_review_signatures` with `review_id`, `signature_id`, `signing_user_id`, `signed_at`, `outcome` (`approve` / `reject`).  |
| URS-12-DATA-014 | `document_library` with `document_id`, `library_subdomain` (`regulatory` / `process` / `project`), `subdomain_classification_jsonb`, `tags`, `description`, `text_extracted`, `content_hash`.  |
| URS-12-DATA-015 | `document_library_classification` controlled classification record with `library_id`, `classifier_user_id`, `ai_advisory_value` (nullable), `ai_advisory_confidence` (nullable), `human_confirmed_value`, `confirmed_at`, `signature_id`.  |
| URS-12-DATA-016 | `document_library_entitlements` with `library_id` (nullable for subdomain-level), `subdomain` (nullable), `policy_type` (`role` / `group` / `scope` / `direct_user`), `policy_value_jsonb`, `granted_by`, `granted_at`, `signature_id`.  |
| URS-12-DATA-017 | `document_embeddings` with `library_id`, `chunk_id`, `chunk_text`, `embedding_vector`, `embedding_model` (e.g., `text-embedding-3-small`), `embedding_model_version`, `chunk_position`, `provenance_jsonb`.  |
| URS-12-DATA-018 | `document_retention_policies` with `retention_class`, `retention_period_years`, `disposition_method`, `legal_hold_supported`.  |
| URS-12-DATA-019 | `document_dispositions` with `library_id`, `disposition_decision` (`dispose` / `extend` / `preserve_permanent`), `decided_by`, `co_signed_by`, `decided_at`, `signature_id`.  |
| URS-12-DATA-020 | `regulatory_document_links` with `regulatory_item_id`, `document_id`, `link_type`, `created_by`, `signature_id`.  |
| URS-12-DATA-021 | All Module 12 tables have RLS enabled with `tenant_id = current_setting('app.current_tenant_id')::uuid` policy per QS-6. |
| URS-12-DATA-022 | All mutations record to URS-06 audit substrate via `auditTrailService.log()` per QS-1. |

### 6.3 API requirements

| Endpoint | Method | Purpose | Priority |
|---|---|---|---|
| `/api/v1/documents` | GET | List documents within tenant + scope | MUST |
| `/api/v1/documents` | POST | Create draft | MUST |
| `/api/v1/documents/:id` | GET | Get document | MUST |
| `/api/v1/documents/:id` | PATCH | Update draft | MUST |
| `/api/v1/documents/:id/submit-for-review` | POST | Transition to in_review | MUST |
| `/api/v1/documents/:id/approve` | POST (with authority) | Approver e-sign | MUST |
| `/api/v1/documents/:id/effective` | POST (with authority) | Move to effective | MUST |
| `/api/v1/documents/:id/supersede` | POST (with authority) | Explicit supersede route | MUST |
| `/api/v1/documents/:id/retire` | POST (with authority) | Retirement | MUST |
| `/api/v1/documents/:id/sign` | POST | Document e-signature | MUST |
| `/api/v1/documents/:id/sections/:sectionId/checkout` | POST | Section checkout | MUST |
| `/api/v1/documents/:id/sections/:sectionId/checkin` | POST | Section checkin | MUST |
| `/api/v1/documents/:id/audit` | GET | Per-document audit trail | MUST |
| `/api/v1/documents/:id/executive-hold` | POST (executive authority) | executive break-glass hold | MUST |
| `/api/v1/documents/:id/executive-release` | POST (executive authority + SoD) | executive break-glass release | MUST |
| `/api/v1/document-reviews` | POST | Initiate review | MUST |
| `/api/v1/document-reviews/:reviewId` | GET | Get review | MUST |
| `/api/v1/document-reviews/:reviewId/checklist` | GET | List checklist items | MUST |
| `/api/v1/document-reviews/:reviewId/checklist/:itemId` | POST | Submit checklist result | MUST |
| `/api/v1/document-reviews/:reviewId/comments` | GET, POST | List, add comments | MUST |
| `/api/v1/document-reviews/:reviewId/comments/:commentId/resolve` | POST | Resolve comment | MUST |
| `/api/v1/document-reviews/:reviewId/request-revision` | POST | Request revision | MUST |
| `/api/v1/document-reviews/:reviewId/complete` | POST | Complete approve/reject | MUST |
| `/api/v1/document-reviews/:reviewId/complete-with-esig` | POST | Complete with e-signature (Controlled Approval Modal) | MUST |
| `/api/v1/document-reviews/me/assignments` | GET | My open review assignments | MUST |
| `/api/v1/document-reviews/initiated-by-me` | GET | Reviews I initiated | MUST |
| `/api/v1/document-library` | GET | List library entries | MUST |
| `/api/v1/document-library/upload` | POST | Upload library entry | MUST |
| `/api/v1/document-library/:libraryId/classify` | POST (with authority) | Confirm classification (with AI advisory metadata) | MUST |
| `/api/v1/document-library/:libraryId/entitlements` | POST | Grant entitlement | MUST |
| `/api/v1/document-library/search` | GET | Keyword search | MUST |
| `/api/v1/document-library/rag-query` | POST | RAG semantic retrieval | MUST |
| `/api/v1/document-library/:libraryId/rag-index` | POST | Re-index library entry | MUST |
| `/api/v1/document-library/:libraryId/dispose` | POST (with authority + SoD) | Retention disposition | MUST |
| `/api/v1/document-library/me/accessible` | GET | Accessible library entries (entitlement-evaluated) | MUST |
| `/api/v1/regulatory/feeds` | GET, POST | Feed configuration | MUST |
| `/api/v1/regulatory/items` | GET | Feed items | MUST |
| `/api/v1/regulatory/items/:itemId/ingest` | POST (with authority) | Confirm ingestion to Regulatory Library | MUST |
| `/api/v1/regulatory/items/:itemId/link-document` | POST | Create RegulatoryDocumentLink | MUST |

### 6.4 Workflow / lifecycle requirements

- URS-12-WF-001: Document state transitions follow the canonical state machine in `documents/lifecycle.ts`; unauthorised transitions are rejected with HTTP 422 and error code `DOCUMENT_INVALID_TRANSITION`.
- URS-12-WF-002: Document approval requires both RBAC permission (`documents:approve`) AND Authority Profile (`controlled_document_approval`). DOC-008.
- URS-12-WF-003: Document Review SoD-12-02 (initiator ≠ approver) is enforced at the service layer in `document-review/service.ts`. DOC-009.
- URS-12-WF-004: Document Review revision cycle preserves prior comments and checklist results for audit; closes the prior review with terminal `revision_requested` state and creates a new cycle.
- URS-12-WF-005: A document on lifecycle `effective` can transition to `held` via executive break-glass; `held → effective` requires a separate executive authority e-signature (SoD-12-06).
- URS-12-WF-006: Library classification requires both AI advisory output (if available) AND human confirmation (ARCH-AI-001 AC-3, AC-4); AI alone never writes to system of record.
- URS-12-WF-007: Library entitlement grant requires SoD-12-03 (the user who classifies an entry cannot also be the user who approves the entitlement that governs that entry).
- URS-12-WF-008: RAG ingestion is best-effort non-blocking; failure to embed does not block the document's transition to `effective`. Failure is logged for retry.
- URS-12-WF-009: RAG retrieval falls back to keyword search when embedding service is unavailable; the response carries `retrieval_mode = keyword_fallback`. Per ARCH-AI-001 AC-7.
- URS-12-WF-010: Retention disposition requires SoD-12-05 (steward + reviewer cannot be the original author).

### 6.5 Business rules

- BR-12-01: Major-revision-to-URS-13 linkage: a major revision (X.0) to a GxP-significant document type creates a referenceable URS-13 link; the URS-13 record itself is owned by URS-13. Module 12 does not create a URS-13 record; it allows referencing one.
- BR-12-02: Tenant-offboarding cascade: documents transition to `archived_for_audit`; library entries are detached from active retrieval; entitlements are revoked; controlled-copy export is restricted to the offboarding extract pack.
- BR-12-03: Periodic-review missed-cadence auto-suspension applies `regulatory_concern` modifier; remediation requires owner + QA co-sign.
- BR-12-04: Read-receipt is mandatory for distribution lists where the document is `training-required` (URS-28 dependency) or where the per-type matrix flags `read-receipt-required`.
- BR-12-05: Watermark on controlled-copy export is mandatory; uncontrolled-copy export carries explicit "Uncontrolled — for reference only" watermark.
- BR-12-06: AI advisory output is preserved in audit trail even when overridden by human (ARCH-AI-001 AC-6 audit completeness).
- BR-12-07: Regulatory Library remains source-distinct in retrieval-trust model from internal libraries (DOC-018); RAG retrieval response identifies the source library subdomain.
- BR-12-08: Library entitlement evaluation is hierarchical: direct user grant → group → role → scope policy. Most-permissive grant wins for read; most-restrictive applies for write.
- BR-12-09: A document in `held` state is readable but its distribution is paused and edits are paused; effective documents under hold remain in force for compliance reading.
- BR-12-10: Cross-references between documents preserve the version reference at the time of citation; updates to source documents do not retroactively re-version cross-references.

### 6.6 Audit trail requirements

- Every Module 12 mutation calls `auditTrailService.log()` with `tenantId`, `userId`, `action`, `resourceType`, `resourceId`, `details` (before-state + after-state for updates), `ipAddress`, `timestamp`. Per QS-1.
- Document lifecycle transitions log to `document_lifecycle_events` AND to URS-06 audit substrate (dual write for compliance redundancy).
- Document Review events log to `document_review_*` tables AND to URS-06.
- AI advisory output, human confirmation, and override (with reason) all log to `ai_requests`. Per ARCH-AI-001 AC-5.
- LLM-driven RAG-supported answers log to `llm_audit_log` with model, prompt hash, retrieved chunks (IDs + provenance), response, accept/modify/reject. Per ARCH-AI-001 AC-5.
- Auth-related events (entitlement check denials, SoD violations, executive break-glass) log to `auth_audit_log`. Per QS-1.
- Audit log is append-only; no UPDATE or DELETE on audit tables. Per QS-1.

### 6.7 Architecture binding — ARCH-AI-001 AI Optionality and Manual Continuity

This section is the explicit binding of Module 12 to the platform-level architecture constraint ARCH-AI-001 (per Architecture Bindings row). Every AI surface in Module 12 is governed by AC-1 through AC-7 of ARCH-AI-001:

| AC | Statement | Module 12 application |
|---|---|---|
| AC-1 | Manual primary path | Document creation, review routing, reviewer sign-off, approval, publication, retention disposition, and keyword retrieval are executable when AI services are disabled, degraded, or overridden. |
| AC-2 | AI is advisory secondary | AI document classification, AI metadata extraction, AI review-finding suggestion, AI retention disposition suggestion, and RAG semantic retrieval are advisory only. |
| AC-3 | Visible advisory labelling | Every AI-generated artefact in Module 12 carries an "AI-generated — requires human review" label in the UI and a corresponding flag in the data model. |
| AC-4 | No autonomous write to system of record | AI advisory outputs do not overwrite system-of-record metadata without explicit human confirmation and e-signature. |
| AC-5 | Full AI audit trail | Every AI request, response, and downstream human acceptance/modification/rejection is logged to `ai_requests` and (for LLM-driven outputs) `llm_audit_log` with full prompt/response/provenance. |
| AC-6 | Override capability | Reviewers and stewards can override every AI advisory output with a captured reason; the override is the system of record. |
| AC-7 | Graceful degradation | RAG retrieval degrades to keyword search; AI classification degrades to manual classification; AI review suggestion degrades to absence of suggestion. The user is never locked out. |

 The target implementation MUST meet the full ARCH-AI-001 AC-1..AC-7 architectural reference for RAG indexing, retrieval, and AI advisory surfaces.

---

## 7. Cross-Module Wiring and Change-Impact

### 7.1 Cross-module wiring

```mermaid
flowchart LR
  M01[URS-01 Auth] --> M12[Module 12]
  M02[URS-02 RBAC] --> M12
  M03[URS-03 Active Scope] --> M12
  M04[URS-04 Workflow / E-Sign] --> M12
  M05[URS-05 Authority Profiles] --> M12
  M06[URS-06 Audit Substrate] <-- M12
  M07[URS-07 Study] <--> M12
  M08[URS-08 Tenant Lifecycle] --> M12
  M09[URS-09 Site] <--> M12
  M10[URS-10 Product] <--> M12
  M11[URS-11 Supplier] <--> M12
  M12 --> M13[URS-13]
  M12 <--> M14[URS-14 Complaints]
  M12 <--> M15[URS-15 OOS/OOT]
  M12 <--> M16[URS-16 Deviations]
  M12 <--> M17[URS-17 RCA]
  M12 <--> M18[URS-18 CAPA]
  M12 <--> M21[URS-21 Findings]
  M12 <--> M22[URS-22 Inspection Mgmt]
  M12 <--> M23[URS-23 Batch Records]
  M12 <--> M27[URS-27 Reg Intelligence]
  M12 --> M28[URS-28 Training]
  M12 --> M30[URS-30 Notifications]
  M12 --> M32[URS-32 MIRA]
  ARCHAI[ARCH-AI-001] -.governs.-> M12
```

Diagram 7.1-A — Module 12 cross-module wiring. Module 12 receives identity (M01), RBAC (M02), scope (M03), workflow/e-sign (M04), authority (M05); writes to audit (M06); is consumed by every operating module for documents and library retrieval; supplies RAG to MIRA (M32); is governed at platform level by ARCH-AI-001.

### 7.2 Change-Impact Matrix (CIM)

| Module 12 capability | Affects | Direction | URS-13 trigger if modified |
|---|---|---|---|
| Document type enum | URS-08, URS-09, URS-10, URS-11, URS-13, URS-22, URS-28 | Outbound | Class 1 (URS-13) |
| Document lifecycle state machine | All consuming modules | Outbound | Class 1 (URS-13) |
| Per-type approver matrix | URS-04, URS-05 | Bidirectional | Class 2 (URS-13) |
| Retention class catalogue | All consuming modules | Outbound | Class 1 (URS-13) |
| Library subdomain taxonomy | URS-27, URS-28, URS-32 | Outbound | Class 2 (URS-13) |
| RAG embedding model | URS-32 (MIRA), every consuming retrieval surface | Outbound | Class 1 (URS-13) — ARCH-AI-001 ML model change |
| RegulatoryDocumentLink schema | URS-27 | Bidirectional | Class 2 (URS-13) |
| ProjectDocument schema | URS-07 | Bidirectional | Class 2 (URS-13) |
| Entitlement policy types | URS-02 | Outbound | Class 2 (URS-13) |

### 7.3 Cross-module dependencies (consumed by Module 12)

- URS-01 — Authentication and session.
- URS-02 — RBAC permission grants (`documents:*`, `document-review:*`, `document-library:*`, `regulatory:*`).
- URS-03 — Active scope (tenant + site + product + study + region) for context-filtered queries.
- URS-04 — Workflow / e-signature substrate (HITL service, Controlled Approval Modal).
- URS-05 — Authority Profile registry (`controlled_document_approval`, `controlled_document_retirement`, `library_classification`, etc.).
- URS-06 — Audit trail substrate (`audit_trail`, `auth_audit_log`, `ai_requests`, `llm_audit_log`).
- URS-07 — Study Management (Project Library linkage).
- URS-08 — Tenant lifecycle (offboarding cascade).
- URS-27 — Regulatory Intelligence (Regulatory Library feed input).
- URS-28 — Training Management (training-required documents).
- URS-30 — Notifications (distribution + read-receipt + review assignment + auto-suspension).
- URS-32 — MIRA Copilot (RAG consumer).
- ARCH-AI-001 — AI Optionality and Manual Continuity (platform binding).

---

## 8. AI / Automation / Human-in-the-Loop Controls

Per ARCH-AI-001 AC-1..AC-7 and EU AI Act Art. 13 (advisory transparency), every Module 12 AI surface is advisory and bound to manual continuity:

| AI Surface | Advisory Output | Required Human Action | Audit Substrate | Priority |
|---|---|---|---|---|
| AI document classification | Suggested `library_subdomain` + `subdomain_classification` + confidence | Steward confirms or overrides via Controlled Approval Modal | `ai_requests` | MUST |
| AI metadata extraction | Suggested title, document type, GxP class, related-doc set | Author confirms or overrides | `ai_requests` | MUST |
| AI review-finding suggestion | Suggested checklist findings to flag | Reviewer confirms or overrides on the review checklist | `ai_requests` | MUST |
| AI retention disposition suggestion | Suggested disposition (`dispose` / `extend` / `preserve_permanent`) with rationale | Steward + QA reviewer confirm via SoD-12-05 e-signature | `ai_requests` | MUST |
| RAG semantic retrieval | Top-K chunks with provenance + confidence | User reviews citations; on AI-generated answer downstream, full audit per AC-5 | `ai_requests`, `llm_audit_log` (for downstream LLM use) | MUST |
| MIRA document copilot | AI-generated answer with citations | User reviews citations; can click through to source; can mark accept/modify/reject | `llm_audit_log` | MUST |

All advisory outputs are visibly labelled "AI-generated — requires human review" in the UI per ARCH-AI-001 AC-3. All advisory outputs are preserved in audit trail even when overridden per ARCH-AI-001 AC-6 (the override is the system of record; the advisory is preserved as metadata). All AI surfaces have a non-AI manual continuity path per ARCH-AI-001 AC-1, AC-2, AC-7. No AI service is the sole path to approve, publish, retire, or retrieve a controlled document.

---

## 9. Reports, Dashboards, and Exports

| Report / Dashboard | Purpose | Audience |
|---|---|---|
| Document inventory dashboard | All documents by type, state, GxP class, library subdomain | QA, RA, Document Control |
| Documents due for periodic review | Documents with `next_review_due_at` within 90 days | QA, document owners |
| Document review queue | Active reviews and assignments | Reviewers |
| Distribution + read-receipt compliance | Per-document or aggregate read-receipt compliance | QA, document owners, distribution leads |
| Library subdomain inventory | Per-subdomain library entry counts, classification status, entitlement coverage | Library stewards |
| RAG retrieval audit | Recent RAG retrievals with mode (semantic/keyword_fallback), top users, top queries | Library steward, AI governance |
| AI advisory acceptance dashboard | AI advisory outputs vs. human confirmations vs. overrides (with reasons) | AI governance, QA |
| Retention disposition queue | Documents reaching retention threshold; disposition status | Library steward, QA |
| executive break-glass holds | Active holds; release status | Executive authority, QA |
| Cross-tenant audit indices (platform admin only) | Aggregate Module 12 events across tenants for platform-level compliance | `platform_admin` |

Exports:

- Controlled-copy PDF export (watermarked).
- Uncontrolled-copy PDF export (clearly labelled).
- Document evidence pack (zipped: document + version history + approvals + reviews + read-receipts + cross-references + RAG audit excerpt).
- Library evidence pack (subdomain export with classification + entitlements + retention metadata).
- Audit trail export (URS-06 substrate; date-range scoped; signed export).

---

## 10. Notifications and Queues

| Event | Trigger | Recipients | Channel |
|---|---|---|---|
| Document submitted for review | `documents:submit_for_review` | Reviewers per assignment | URS-30 in-app + email |
| Review revision requested | `document-reviews/:id/request-revision` | Document author | URS-30 in-app + email |
| Review approved | `document-reviews/:id/complete-with-esig` (approve) | Author + approver-of-record | URS-30 in-app + email |
| Review rejected | `document-reviews/:id/complete-with-esig` (reject) | Author | URS-30 in-app + email |
| Document approved | `documents/:id/approve` | Author + approver | URS-30 in-app |
| Document effective | Effective_from job | Distribution list | URS-30 in-app + email |
| Read-receipt overdue | Periodic check vs. read-by-date | Pending recipients + document owner | URS-30 reminder cadence |
| Periodic review due | Scheduler at next_review_due_at - 90 days | Document owner + QA | URS-30 in-app + email |
| Periodic review missed (auto-suspension) | Scheduler at next_review_due_at | Document owner + QA + `quality_lead` | URS-30 critical |
| Library entitlement granted | `document-library/:id/entitlements` | Affected role/group members | URS-30 in-app |
| Regulatory feed item ingested | `regulatory/items/:id/ingest` | Regulatory Affairs team + linked-document owners | URS-30 in-app |
| RAG retrieval mode degraded | First fallback after 5 minutes of healthy | AI governance + platform admin | URS-30 critical |
| executive break-glass hold applied | `documents/:id/executive-hold` | Document owner + QA + RA | URS-30 critical |
| executive break-glass hold released | `documents/:id/executive-release` | Document owner + QA + RA | URS-30 critical |

---

## 11. Error Handling and Negative Paths

### 11.1 Error envelope

All Module 12 errors return the `AppError` envelope per QS-9: `{ error: string, code: string, details?: unknown }`. No stack traces, SQL errors, table names, or internal paths in API responses.

### 11.2 Error-code catalogue

| Code | HTTP | Meaning |
|---|---|---|
| `DOCUMENT_NOT_FOUND` | 404 | Document ID not in tenant scope |
| `DOCUMENT_INVALID_TRANSITION` | 422 | Lifecycle transition not allowed from current state |
| `DOCUMENT_AUTHORITY_REQUIRED` | 403 | Authority Profile required for transition |
| `DOCUMENT_REVIEW_NOT_FOUND` | 404 | Review ID not in scope |
| `DOCUMENT_REVIEW_SOD_VIOLATION` | 403 | Review initiator cannot also be approver (DOC-009 / SoD-12-02) |
| `DOCUMENT_REVIEW_IMMUTABLE` | 422 | Completed reviews cannot be modified |
| `DOCUMENT_REVIEW_INVALID_TRANSITION` | 422 | Review state transition not allowed |
| `LIBRARY_ENTITLEMENT_DENIED` | 403 | User lacks entitlement to library entry |
| `LIBRARY_CLASSIFICATION_MISSING_HUMAN_CONFIRM` | 422 | AI advisory cannot be system-of-record without human confirmation (ARCH-AI-001 AC-4) |
| `LIBRARY_DISPOSITION_SOD_VIOLATION` | 403 | Disposition steward + reviewer cannot be original author (SoD-12-05) |
| `LIBRARY_RETENTION_LEGAL_HOLD` | 422 | Cannot dispose: under legal hold |
| `RAG_RETRIEVAL_DEGRADED` | 200 (with header) | RAG semantic retrieval unavailable; result returned with `retrieval_mode = keyword_fallback` |
| `REGULATORY_LINK_DOCUMENT_NOT_FOUND` | 404 | Linked document missing |
| `REGULATORY_INGEST_AUTHORITY_REQUIRED` | 403 | Authority Profile required for feed ingest |
| `EXECUTIVE_BREAK_GLASS_AUTHORITY_REQUIRED` | 403 | executive authority required |
| `EXECUTIVE_BREAK_GLASS_RELEASE_SOD_VIOLATION` | 403 | Release executive authority must be different from hold executive authority (SoD-12-06) |
| `VALIDATION_FAILED` | 400 | Zod schema validation failed |
| `SCOPE_MISMATCH` | 403 | Active scope does not include this resource |

### 11.3 Negative-path catalogue

- Author attempts to approve own document → `DOCUMENT_AUTHORITY_REQUIRED` if not authorised, or SoD-12-01 violation if authorised but is the author.
- Reviewer attempts to be the approver after initiating → `DOCUMENT_REVIEW_SOD_VIOLATION`.
- User without entitlement attempts to read `restricted` document → `LIBRARY_ENTITLEMENT_DENIED`.
- User attempts to override AI advisory without providing a reason → `VALIDATION_FAILED` (reason required).
- User attempts to dispose a document under legal hold → `LIBRARY_RETENTION_LEGAL_HOLD`.
- User attempts to retire a document without retention compliance → `DOCUMENT_INVALID_TRANSITION`.
- AI Gateway timeout during RAG → `RAG_RETRIEVAL_DEGRADED` with `retrieval_mode = keyword_fallback`.
- Executive authority attempts to release own break-glass hold → `EXECUTIVE_BREAK_GLASS_RELEASE_SOD_VIOLATION`.

---

## 12. Security, Privacy, and Tenant Isolation

### 12.1 Authentication dependency

All Module 12 routes require a valid URS-01 authenticated session; anonymous access is prohibited. Service-to-service calls use platform-issued JWT.

### 12.2 Authorisation pipeline

Three-guard hierarchy on every Module 12 mutation: RoleGuard → PermissionGuard → AuthorityGuard. Per QS-7. `requirePermission('documents:approve')` checks RBAC; `withAuthority('controlled_document_approval')` checks Authority Profile.

### 12.3 Tenant isolation

Every database operation goes through TDAL (`tdal.withTenant(tenantId, ...)`); raw `db.query` calls outside TDAL are prohibited per QS-5. Every Module 12 table has RLS enabled per QS-6 with `tenant_id = current_setting('app.current_tenant_id')::uuid`.

### 12.4 Encryption

Documents and library entries at rest are encrypted via the platform's standard at-rest-encryption substrate. Embeddings are stored alongside metadata. TLS 1.2+ in transit. AI Gateway calls to OpenAI use TLS 1.2+; embeddings are sent over the wire and not retained by OpenAI per the AI Gateway contract.

### 12.5 Logging hygiene

No PHI / PII / passwords / API keys / raw document content in operational logs per QS-19. Document content is referenced by ID + version only in logs. RAG retrieval audit logs chunk IDs + provenance, not the chunk text (chunk text is in `document_embeddings` table).

### 12.6 Privacy and data residency

Module 12 documents and library entries inherit the tenant's data residency configuration (US / EU / India / UK / Canada / Japan). Cross-region replication only as configured. RAG embeddings are stored in the same region as the source document.

### 12.7 Periodic access review

Per QS-7 and URS-02 cadence: per-tenant entitlement review every 6 months by `quality_lead` + `library_steward`; cross-tenant entitlement review every 12 months by `platform_admin`. Findings logged to URS-21.

### 12.8 Periodic audit-trail review

Per QS-19 and URS-06 cadence: monthly Module 12 audit-trail sample review by `quality_lead`; quarterly tenant-wide audit-trail integrity check (hash chain validation) by `platform_admin`.

### 12.9 Security-operations alert thresholds

| Alert | Threshold |
|---|---|
| Failed authority checks on document approval | >5 in 1 hour for one user |
| RAG retrieval failure rate | >10% over 5 minutes |
| AI advisory override rate | >40% over 7 days (signal of advisory quality issue) |
| SoD violations | Any (SoD-12-02, 12-03, 12-05, 12-06) |
| executive break-glass hold | Any |
| Bulk document download | >20 documents in 1 hour for one user |

### 12.10 Self-modification block

Module 12 services cannot modify their own audit trail entries or configuration tables; QA-only configuration via dedicated admin routes.

### 12.11 Secure export

Controlled-copy exports are watermarked, audit-logged, and downloaded over TLS. The export file is named with the document ID + version + export ID. Bulk exports require additional authority.

### 12.12 Cross-tenant confidentiality envelope

Module 12 enforces the cross-tenant envelope: tenant A cannot read tenant B's documents under any RBAC permission; only `platform_admin` operating in `tdal.withPlatformContext()` can do cross-tenant operations, and those are exclusively read-only for audit indexing.

---

## 13. Data Integrity and ALCOA+ Controls

| ALCOA+ Principle | Module 12 Implementation |
|---|---|
| Attributable | Every document, version, review, library entry, classification, entitlement, disposition, and AI request carries `created_by` (URS-01 user ID) and signature attribution. Per QS-2. |
| Legible | Documents, versions, comments, and audit entries are stored in human-readable form; binary attachments are extracted to text where possible (the `text_extracted` column) for retrieval. |
| Contemporaneous | Server-generated timestamps via `NOW()` / `CURRENT_TIMESTAMP`; `created_at` columns immutable; client timestamps not trusted. Per QS-3. |
| Original | Documents preserve full version history; original drafts preserved on supersede; AI advisory output preserved when overridden. Per QS-4. |
| Accurate | Schema and Zod validation at boundary (per QS-8); referential integrity enforced (per QS-14); per-type approval matrix prevents incorrect approver. |
| Complete | All required fields enforced at validation; review checklist completion required; approval requires all assigned reviewers complete. |
| Consistent | Document context model is internally consistent (MUST|
| Enduring | Documents preserved per retention class; audit trail append-only per QS-1; legal-hold supported. |
| Available | Tenant-scoped retrieval available to authorised users; controlled-copy export and audit export available; offline reading via uncontrolled-copy export. |
| Traceable | Hash-chained URS-06 audit trail; per-document audit view; cross-module reference chain; RAG retrieval provenance. |

---

## 14. Regulatory Mapping

### 14.1 Predicate-rule applicability matrix

| Regulatory authority | Predicate | Module 12 obligation |
|---|---|---|
| FDA | 21 CFR Part 11 §11.10(a) — System validation | Module 12 must be validated per QS-15, QS-16; URS-12-VAL-* gates |
| FDA | 21 CFR Part 11 §11.10(d) — Limit access to authorised individuals | Three-guard RBAC + library entitlement |
| FDA | 21 CFR Part 11 §11.10(e) — Audit trail | URS-06 hash-chained audit substrate, append-only |
| FDA | 21 CFR Part 11 §11.50 — Signature manifestation | Controlled Approval Modal captures meaningOfSignature + reasonForChange |
| FDA | 21 CFR Part 11 §11.70 — Signature/record link | Document signatures linked to specific document version |
| FDA | 21 CFR Part 11 §11.100 — General requirements for e-signature | Per ControlledApprovalModal contract |
| FDA | 21 CFR Part 11 §11.200 — Identification components | Password + biometric option supported |
| FDA | 21 CFR Part 11 §11.300 — Controls for identification codes | Per URS-01 password policy |
| EMA | EU GMP Annex 11 §4 — Validation | Module 12 validation per §17 |
| EMA | EU GMP Annex 11 §9 — Audit trails | URS-06 hash-chained audit |
| EMA | EU GMP Annex 11 §12 — Security | Three-guard + RLS + entitlement |
| EMA | EU GMP Annex 11 §16 — Incident management | Error envelope + SOD-violation alerts |
| EMA / PIC/S | EU GMP Chapter 4 — Documentation | Document Control register, retention, version control |
| Internal architectural control (forward-looking; not enacted predicate rule) | EU GMP Annex 22 Draft 2025 §7 — HITL for AI-assisted document review (treated as internal forward-looking control; jurisdiction-specific legal enforceability subject to future legal assessment) | Internal forward-looking AI governance evidence (ARCH-AI-001 AC-1..AC-7 architectural reference) |
| EU | EU AI Act Art. 13 — Transparency for advisory AI | Visible advisory labelling (AC-3) |
| MHRA | MHRA Data Integrity Guidance — ALCOA+ | Per §13 |
| Health Canada | C.02.020 — GMP records | Document Control register + retention |
| ICH | ICH Q10 — Pharmaceutical QMS | Module 12 supports QMS document control |
| ICH | ICH Q12 — Lifecycle management / Established Conditions | EC reference linkage to URS-13 |
| ICH | ICH GCP E6(R3) — Good Clinical Practice | TMF master file support; clinical document types |
| GAMP | GAMP 5 Cat 5 — Custom application | Validation per §17 |
| WHO | TRS 996 Annex 5 — Good data management | ALCOA+ implementation |
| India CDSCO (per applicable scope) | India Drugs and Cosmetics Act 1940 + Drugs Rules 1945 + Revised Schedule M (documentation, master records, batch records, SOPs, retention) + Schedule M-III (where distribution-document scope) + New Drugs and Clinical Trials Rules 2019 (where clinical / TMF document scope) + Medical Devices Rules 2017 (where device-document scope) — Applicable per India tenant operation and jurisdictional regulatory assessment | Document Control register, controlled SOPs, batch / master record templates, TMF (clinical), retention per regulatory framework; external jurisdictional legal / RA confirmation required for clause applicability per India document scope |

---

## 15. URS Requirements Register

### 15.1 Front-end (FE)

| ID | Requirement | Priority |
|---|---|---|
| URS-12-FE-001 | Document Library landing route at `/documents` | MUST |
| URS-12-FE-002 | Library subdomain views at `/documents/library/{regulatory|process|project}` | MUST |
| URS-12-FE-003 | Document detail at `/documents/:id` | MUST |
| URS-12-FE-004 | Document Review queue at `/document-reviews` | MUST |
| URS-12-FE-005 | Controlled Approval Modal contract enforced | MUST |
| URS-12-FE-006 | RAG search bar with retrieval_mode banner | MUST |
| URS-12-FE-007 | RAG result card with provenance | MUST |
| URS-12-FE-008 | AI advisory banner on every AI-generated artefact | MUST |
| URS-12-FE-009 | Entitlement policy editor for library | MUST |
| URS-12-FE-010 | Disposition dashboard | MUST |
| URS-12-FE-011 | Distribution-compliance dashboard | MUST |
| URS-12-FE-012 | Executive authority document holds view (executive authority only) | MUST |
| URS-12-FE-013 | WCAG 2.1 AA across all routes | MUST |
| URS-12-FE-014 | i18n / l10n across all UI strings | MUST |
| URS-12-FE-015 | ErrorBoundary on every page-level component per QS-17 | MUST |
| URS-12-FE-016 | Loading + empty + error states for all async ops per QS-17 | MUST |
| URS-12-FE-017 | Keyboard navigation on all interactive elements | MUST |
| URS-12-FE-018 | Screen-reader labelling on all controls + AI advisory pills | MUST |
| URS-12-FE-019 | RetrievalModeBanner visible during keyword_fallback | MUST |
| URS-12-FE-020 | Watermark preview on controlled-copy export | MUST |
| URS-12-FE-021 | RAG retrieval audit visible to AI governance + library steward | MUST |
| URS-12-FE-022 | AI advisory override UI with reason capture | MUST |
| URS-12-FE-023 | Document version history panel | MUST |
| URS-12-FE-024 | Cross-reference panel showing in-bound and out-bound document references | MUST |
| URS-12-FE-025 | Periodic-review-due indicator on document cards | MUST |

### 15.2 Back-end (BE)

| ID | Requirement | Priority |
|---|---|---|
| URS-12-BE-001 | `documents` REST surface per §6.3 | MUST |
| URS-12-BE-002 | `document-reviews` REST surface per §6.3 | MUST |
| URS-12-BE-003 | `document-library` REST surface per §6.3 | MUST |
| URS-12-BE-004 | `regulatory` REST surface per §6.3 | MUST |
| URS-12-BE-005 | `documents/lifecycle.ts` state machine matches §6.4 | MUST |
| URS-12-BE-006 | `document-review/service.ts` enforces SoD-12-02 (DOC-009) | MUST |
| URS-12-BE-007 | `document-library/rag.service.ts` ingestion using OpenAI text-embedding-3-small via AiGatewayService | MUST |
| URS-12-BE-008 | RAG retrieval with citation-grade provenance | MUST |
| URS-12-BE-009 | RAG graceful degradation to keyword search per ARCH-AI-001 AC-7 | MUST |
| URS-12-BE-010 | Library classification with AI advisory + human confirmation per ARCH-AI-001 AC-3, AC-4 | MUST |
| URS-12-BE-011 | Library entitlement policy (role / group / scope) per DOC-013 | MUST |
| URS-12-BE-012 | Retention disposition workflow with SoD-12-05 per DOC-014 | MUST |
| URS-12-BE-013 | RegulatoryDocumentLink route/service per DOC-015 | MUST |
| URS-12-BE-014 | ProjectDocument route/service per DOC-017 | MUST |
| URS-12-BE-015 | Document context model consistent across schema + service + filter per DOC-014 | MUST |
| URS-12-BE-016 | Document supersede route per DOC-010 | MUST |
| URS-12-BE-017 | executive break-glass hold + release routes (with SoD-12-06) | MUST |
| URS-12-BE-018 | Per-document audit trail route (`/documents/:id/audit`) | MUST |
| URS-12-BE-019 | Authority gate (`withAuthority(...)`) on all controlled lifecycle transitions per DOC-008 | MUST |
| URS-12-BE-020 | Read-receipt routes (collection + acknowledge + audit) | MUST |

### 15.3 Workflow (WF)

| ID | Requirement | Priority |
|---|---|---|
| URS-12-WF-101 | Document state transitions per §6.4 | MUST |
| URS-12-WF-102 | Document Review SoD per DOC-009 | MUST |
| URS-12-WF-103 | Revision-review cycle preserves prior comments | MUST |
| URS-12-WF-104 | executive break-glass hold/release SoD-12-06 | MUST |
| URS-12-WF-105 | Library classification AI-advisory → human-confirm flow | MUST |
| URS-12-WF-106 | Library entitlement grant SoD-12-03 | MUST |
| URS-12-WF-107 | RAG ingestion best-effort non-blocking | MUST |
| URS-12-WF-108 | RAG retrieval graceful degradation per ARCH-AI-001 AC-7 | MUST |
| URS-12-WF-109 | Retention disposition SoD-12-05 | MUST |
| URS-12-WF-110 | Periodic review missed-cadence auto-suspension | MUST |

### 15.4 Data (DATA)

| ID | Requirement | Priority |
|---|---|---|
| URS-12-DATA-001..022 | Per §6.2 | MUST |

### 15.5 Security (SEC)

| ID | Requirement | Priority |
|---|---|---|
| URS-12-SEC-001 | RoleGuard + PermissionGuard + AuthorityGuard pipeline | MUST |
| URS-12-SEC-002 | TDAL on every DB op per QS-5 | MUST |
| URS-12-SEC-003 | RLS on every Module 12 table per QS-6 | MUST per migration |
| URS-12-SEC-004 | Library entitlement evaluation hierarchical per BR-12-08 | MUST |
| URS-12-SEC-005 | Cross-tenant envelope enforcement | MUST |
| URS-12-SEC-006 | Watermarked controlled-copy export | MUST |
| URS-12-SEC-007 | Bulk export authority gate | MUST |
| URS-12-SEC-008 | Self-modification block | MUST |
| URS-12-SEC-009 | Periodic access review cadence | MUST |
| URS-12-SEC-010 | Periodic audit-trail integrity check | MUST to Module 12 indices |

### 15.6 Audit (AUD)

| ID | Requirement | Priority |
|---|---|---|
| URS-12-AUD-001 | Every mutation calls `auditTrailService.log()` per QS-1 | MUST |
| URS-12-AUD-002 | Document lifecycle events logged to `document_lifecycle_events` AND URS-06 | MUST |
| URS-12-AUD-003 | Document Review events logged dual-write | MUST |
| URS-12-AUD-004 | AI requests logged to `ai_requests` | MUST |
| URS-12-AUD-005 | LLM-driven RAG-supported answers logged to `llm_audit_log` | MUST |
| URS-12-AUD-006 | Auth-related events logged to `auth_audit_log` | MUST |
| URS-12-AUD-007 | Audit log append-only per QS-1 | MUST |
| URS-12-AUD-008 | Per-document audit view `/documents/:id/audit` | MUST |
| URS-12-AUD-009 | AI advisory output preserved when overridden per ARCH-AI-001 AC-6 | MUST |
| URS-12-AUD-010 | Hash-chained URS-06 audit integrity validated periodically | MUST |

### 15.7 AI / HITL (AI)

| ID | Requirement | Priority |
|---|---|---|
| URS-12-AI-001 | Every AI surface bound to ARCH-AI-001 AC-1..AC-7 | MUST |
| URS-12-AI-002 | AI advisory visible labelling per AC-3 | MUST |
| URS-12-AI-003 | AI no-autonomous-write per AC-4 | MUST |
| URS-12-AI-004 | AI override capability with reason capture per AC-6 | MUST |
| URS-12-AI-005 | RAG graceful degradation to keyword search per AC-7 | MUST |
| URS-12-AI-006 | RAG embedding model: OpenAI text-embedding-3-small via AiGatewayService | MUST |
| URS-12-AI-007 | RAG model change governed by URS-13 Class 1 trigger | MUST |
| URS-12-AI-008 | AI request audit trail per AC-5 | MUST |
| URS-12-AI-009 | RAG retrieval provenance fields per DOC-007/012 | MUST |
| URS-12-AI-010 | Internal forward-looking AI governance evidence (EU AI Act Art. 13 transparency principles) | MUST |

### 15.8 Integration (INT)

| ID | Requirement | Priority |
|---|---|---|
| URS-12-INT-001 | URS-01 authentication consumed | MUST |
| URS-12-INT-002 | URS-02 RBAC consumed | MUST |
| URS-12-INT-003 | URS-03 active scope consumed | MUST |
| URS-12-INT-004 | URS-04 e-signature consumed | MUST |
| URS-12-INT-005 | URS-05 Authority Profile consumed | MUST |
| URS-12-INT-006 | URS-06 audit substrate consumed | MUST |
| URS-12-INT-007 | URS-07 Project Library linkage to Studies | MUST |
| URS-12-INT-008 | URS-08 tenant offboarding cascade | MUST |
| URS-12-INT-009 | URS-13 linkage from Module 12 documents (URS-13 owns its own lifecycle) | MUST |
| URS-12-INT-010 | URS-27 Regulatory Library feed ingestion | MUST |
| URS-12-INT-011 | URS-28 Training-required document distribution | MUST |
| URS-12-INT-012 | URS-30 Notifications wired for all events per §10 | MUST |
| URS-12-INT-013 | URS-32 MIRA RAG consumption | MUST |
| URS-12-INT-014 | ARCH-AI-001 platform binding | MUST |

### 15.9 Reporting (REP)

| ID | Requirement | Priority |
|---|---|---|
| URS-12-REP-001..010 | Per §9 reports/dashboards | MUST |

### 15.10 Notifications (NOTIF)

| ID | Requirement | Priority |
|---|---|---|
| URS-12-NOTIF-001..014 | Per §10 notifications | MUST |

### 15.11 Validation (VAL)

| ID | Requirement | Priority |
|---|---|---|
| URS-12-VAL-001 | URS approval (this document) | Pending Founder + signatories |
| URS-12-VAL-002 | Functional Specification approved | Pending |
| URS-12-VAL-003 | IQ / OQ / PQ executed | Pending |
| URS-12-VAL-004 | Traceability matrix complete (URS → spec → code → test) | Pending |
| URS-12-VAL-005 | Risk-based testing per FDA CSA | Pending |
| URS-12-VAL-006 | RLS enforcement verified | Pending |
| URS-12-VAL-007 | Audit trail integrity (hash chain) verified | Pending |
| URS-12-VAL-008 | Migration evidence gate (data migration validated) | Pending |
| URS-12-VAL-009 | ARCH-AI-001 AC-1..AC-7 compliance evidence pack | Pending |
| URS-12-VAL-010 | RAG model version + acceptance criteria documented | Pending |
| URS-12-VAL-011 | Internal forward-looking AI governance evidence (EU AI Act Art. 13 transparency principles) | Pending |

---

## 16. Acceptance Criteria and Test Cases

### 16.1 Plain-language test cases

| TC | Plain-language test |
|---|---|
| TC-12-01 | Author creates a draft from template; submits for review; reviewer approves with e-signature; document becomes effective on the configured date; all distribution recipients receive notifications. |
| TC-12-02 | Author attempts to also approve own document; the platform blocks via SoD-12-01 / SoD-12-02. |
| TC-12-03 | Reviewer requests revision; author resubmits; new review cycle initiates with prior comments preserved. |
| TC-12-04 | Document reaches `effective_from`; auto-job transitions to effective; URS-30 distribution sent; URS-28 training tasks created where applicable. |
| TC-12-05 | User without entitlement attempts to read restricted document; access denied with `LIBRARY_ENTITLEMENT_DENIED`; audit log captures the attempt. |
| TC-12-06 | Library steward classifies a new entry; AI advisory suggests; human confirms; entry is system-of-record only after human confirmation per ARCH-AI-001 AC-4. |
| TC-12-07 | RAG semantic retrieval returns chunks with provenance; retrieval mode logged as `semantic`; result audited in `ai_requests`. |
| TC-12-08 | AI Gateway is unavailable; RAG falls back to keyword search; result returned with `retrieval_mode = keyword_fallback`; UI banner visible. |
| TC-12-09 | User overrides AI advisory classification; reason captured; override logged; AI advisory preserved; human override is system of record. |
| TC-12-10 | Executive authority invokes break-glass document hold; documents transition to `held`; release requires separate executive authority e-signature (SoD-12-06). |
| TC-12-11 | Periodic review missed; document auto-suspends with `regulatory_concern` modifier; remediation requires owner + QA co-sign. |
| TC-12-12 | Regulatory feed item ingested with AI advisory classification; `regulatory_affairs_lead` confirms; RegulatoryDocumentLink created; RAG ingests. |
| TC-12-13 | Tenant offboarding cascade transitions documents to `archived_for_audit`; library entries detached from active retrieval; retention preserved. |
| TC-12-14 | Read-receipt overdue triggers reminder cadence; QA dashboard shows compliance %. |
| TC-12-15 | Controlled-copy export carries watermark with tenant + site + timestamp + user + version + export ID; audit logged. |

### 16.2 Technical test cases

| TC | Test technique |
|---|---|
| TC-12-T01 | Unit test on `document-review/service.ts` SoD-12-02 enforcement; assert HTTP 403 + `DOCUMENT_REVIEW_SOD_VIOLATION`. |
| TC-12-T02 | Integration test on document approval with authority gate; assert `withAuthority('controlled_document_approval')` enforced. |
| TC-12-T03 | Integration test on RAG retrieval semantic path; assert chunks returned with provenance; assert `ai_requests` log entry. |
| TC-12-T04 | Integration test on RAG retrieval graceful degradation; mock AI Gateway failure; assert keyword_fallback returned. |
| TC-12-T05 | Unit test on library classification with AI advisory; assert no system-of-record write without human confirmation (AC-4). |
| TC-12-T06 | RLS test: tenant A user cannot read tenant B documents under any role. |
| TC-12-T07 | Audit test: every mutation produces an URS-06 audit entry with full attribution. |
| TC-12-T08 | E2E test (Playwright): author creates draft → submits → reviewer approves with e-sign → effective transition → distribution notification received. |
| TC-12-T09 | E2E test: AI advisory pill visible in UI; override modal collects reason; override stored. |
| TC-12-T10 | Performance test: RAG retrieval P95 latency ≤ 500ms semantic / ≤ 200ms keyword fallback for top-10 chunks. |
| TC-12-T11 | Security test: bulk export >20 docs triggers authority gate. |
| TC-12-T12 | Tenant-isolation test: TDAL violation blocked; raw `db.query` outside TDAL detected by lint per Gate 4. |

### 16.3 Acceptance criteria

| AC | Statement |
|---|---|
| AC-12-01 | Document Control register supports all launch document types with full lifecycle. |
| AC-12-02 | Document Review workflow enforces SoD-12-02 at the service layer. |
| AC-12-03 | Library classification requires human confirmation per ARCH-AI-001 AC-4. |
| AC-12-04 | RAG retrieval returns citation-grade provenance. |
| AC-12-05 | RAG retrieval degrades gracefully to keyword search per ARCH-AI-001 AC-7. |
| AC-12-06 | All AI surfaces visibly labelled per ARCH-AI-001 AC-3. |
| AC-12-07 | Per-tenant entitlement policies hierarchically evaluated per BR-12-08. |
| AC-12-08 | All Module 12 tables have RLS enabled per QS-6. |
| AC-12-09 | Every mutation produces an audit-trail entry per QS-1. |
| AC-12-10 | All routes protected by RoleGuard + PermissionGuard + AuthorityGuard per QS-7. |
| AC-12-11 | executive break-glass hold/release SoD-12-06 enforced. |
| AC-12-12 | Retention disposition SoD-12-05 enforced. |
| AC-12-13 | Tenant offboarding cascade preserves audit retention. |
| AC-12-14 | Watermarked controlled-copy export carries full attribution. |
| AC-12-15 | Internal forward-looking AI governance evidence (EU AI Act Art. 13 transparency principles) maintained for all AI surfaces. |

```mermaid
sequenceDiagram
  participant Author
  participant DocSvc as documents/service
  participant ReviewSvc as document-review/service
  participant Approver
  participant ESign as HITL E-Sign
  participant Dist as distribution
  participant Audit as URS-06 audit
  Author->>DocSvc: create draft
  DocSvc->>Audit: log create
  Author->>DocSvc: submit_for_review
  DocSvc->>ReviewSvc: initiate review
  ReviewSvc->>Audit: log review init
  Approver->>ReviewSvc: complete_with_esig (SoD check)
  ReviewSvc->>ESign: ControlledApprovalModal contract
  ESign-->>ReviewSvc: signature record
  ReviewSvc->>Audit: log review approved
  ReviewSvc->>DocSvc: mark approved
  DocSvc->>Audit: log document approved
  Note over DocSvc: effective_from reached
  DocSvc->>Dist: distribute
  Dist->>Audit: log distribution
```

Diagram 16-A — End-to-end acceptance test sequence: draft → submit → review (SoD enforced) → approve with e-signature → distribution. Used as the canonical test fixture for AC-12-01..05.

### 16.4 Requirements-to-test traceability

| Requirement ID | Test Case ID | AC ID |
|---|---|---|
| URS-12-FE-001..025 | TC-12-T08, TC-12-T09 | AC-12-01..15 |
| URS-12-BE-001..020 | TC-12-T01..07, TC-12-T10..12 | AC-12-01..15 |
| URS-12-WF-101..110 | TC-12-T01, TC-12-T04, TC-12-T05 | AC-12-02..05, AC-12-11..12 |
| URS-12-DATA-001..022 | TC-12-T06 | AC-12-08, AC-12-09 |
| URS-12-SEC-001..010 | TC-12-T06, TC-12-T11, TC-12-T12 | AC-12-08, AC-12-10 |
| URS-12-AUD-001..010 | TC-12-T07 | AC-12-09 |
| URS-12-AI-001..010 | TC-12-T03..05, TC-12-T09 | AC-12-03..06, AC-12-15 |
| URS-12-INT-001..014 | TC-12-T08 | AC-12-13 |

---

## 17. Validation and CSV/CSA Evidence Expectations

### 17.1 Supplier and service-provider qualification pack

- AI Gateway / OpenAI subprocessor qualification (per URS-11): SOC 2 Type II, DPA, sub-processor agreement, model retention policy, EU AI Act + GDPR Art. 28 compliance.
- Storage subprocessor qualification (per URS-11).
- Hosting region qualification per tenant data residency.

### 17.2 Inspection-ready evidence index

- URS approval pack (this document + signatories).
- Functional specification per code module (`documents`, `document-review`, `document-library`, `regulatory`).
- IQ / OQ / PQ scripts and execution evidence.
- Traceability matrix (URS → spec → code → test).
- Risk-based testing pack per FDA CSA.
- RLS enforcement test evidence per QS-6.
- Audit trail integrity (hash chain) evidence per QS-1.
- Migration evidence (URS-12-VAL-008).
- ARCH-AI-001 AC-1..AC-7 evidence pack.
- RAG model version evidence + acceptance criteria.
- Internal forward-looking AI governance evidence (EU AI Act Art. 13 transparency principles).
- Periodic review configuration evidence.
- Library entitlement policy evidence.
- executive break-glass procedural evidence.

---

## 18. Closed Decision and Dependency Register

### 18.1 Closed Launch Decisions Register

DEC-12-01..25 per §2.3 are all closed for launch. Each carries its rationale and target evidence reference. Detailed dispositions:

| ID | Disposition |
|---|---|
| DEC-12-01..03 | Locked; target binding — `documents/service.ts` + `documents/lifecycle.ts` + `document_versions` table. |
| DEC-12-04..06 | Locked; URS-04/URS-05 substrate — target route-level authority gates required per DEC-12-04. |
| DEC-12-07 | Locked; + DEC-12-09. |
| DEC-12-08 | Locked; + URS-30 wiring. |
| DEC-12-09 | Locked; periodic-review missed-cadence behaviour formalised; target requirement for auto-suspension + remediation co-sign. |
| DEC-12-10..11 | Locked; SoD enforced at service layer in `document-review/service.ts`. |
| DEC-12-12 | Locked; watermark contract specified. |
| DEC-12-13..14 | Locked; three subdomains — regulatory source-distinct in retrieval-trust model. |
| DEC-12-15 | Locked; bound to ARCH-AI-001 AC-3 + AC-4. |
| DEC-12-16 | Locked. |
| DEC-12-17 | Locked; OpenAI `text-embedding-3-small` via `AiGatewayService` evidence in `document-library/rag.service.ts`. |
| DEC-12-18 | Locked; major-revision-to-CC linkage; CC owned by URS-13. |
| DEC-12-19 | Locked; RAG keyword fallback per ARCH-AI-001 AC-7. |
| DEC-12-20 | Locked; advisory labelling per ARCH-AI-001 AC-3, AC-4. |
| DEC-12-21..22 | Locked; provenance fields + AI request audit per ARCH-AI-001 AC-5. |
| DEC-12-23..24 | Locked; retention class catalog + confidentiality classifications. |
| DEC-12-25 | Locked; tenant offboarding cascade per URS-08. |

### 18.2 Dependencies

| Dependency | Direction | Source |
|---|---|---|
| URS-01 authentication | Inbound | URS-01 module URS |
| URS-02 RBAC | Inbound | URS-02 module URS |
| URS-03 active scope | Inbound | URS-03 module URS |
| URS-04 workflow / e-signature | Inbound | URS-04 module URS |
| URS-05 Authority Profile registry | Inbound | URS-05 module URS |
| URS-06 audit substrate (incl. `ai_requests`, `llm_audit_log`, `auth_audit_log`) | Inbound | URS-06 module URS |
| URS-07 Study Management — Project Library linkage | Bidirectional | URS-07 module URS |
| URS-08 Tenant lifecycle — offboarding cascade | Inbound | URS-08 module URS |
| URS-13 — major-revision linkage | Outbound (M12 raises link, URS-13 owns its own lifecycle) | URS-13 module URS |
| URS-27 Regulatory Intelligence — Regulatory Library feed | Inbound | URS-27 module URS |
| URS-28 Training Management — training-required documents | Outbound | URS-28 module URS |
| URS-30 Notifications — distribution + review + library events | Outbound | URS-30 module URS |
| URS-32 MIRA Copilot — RAG consumer | Outbound | URS-32 module URS |
| ARCH-AI-001 AI Optionality and Manual Continuity | Architectural binding | ARCH-AI-001 platform binding |

---

## 19. Completeness Checklist

| Item | Priority |
|---|---|
| Header + mapping + Code Modules Mapped + Architecture Bindings | ✓ |
| Plain-language primer + glossary + architectural picture | ✓ |
| Lifecycle diagrams (Document Lifecycle + Document Review Lifecycle) | ✓ |
| Module Purpose | ✓ |
| Scope (in scope / out of scope / closed launch decisions) | ✓ |
| User Roles + Authority Profiles + SoD rules + worked examples + role-permission matrix | ✓ |
| 28 end-to-end user journeys | ✓ |
| Front-end expected state (routes + components + a11y/i18n) | ✓ |
| Back-end expected state (entities + ER diagram + state machines + Library subdomain governance + RAG flow + data model + API + workflow + business rules + audit) | ✓ |
| ARCH-AI-001 binding section | ✓ |
| Cross-module wiring + CIM + dependencies | ✓ |
| AI / Automation / HITL controls | ✓ |
| Reports / dashboards / exports | ✓ |
| Notifications and queues | ✓ |
| Error envelope + error-code catalogue + negative paths | ✓ |
| Security, privacy, tenant isolation | ✓ |
| ALCOA+ controls | ✓ |
| Regulatory mapping | ✓ |
| URS Requirements Register (FE / BE / WF / DATA / SEC / AUD / AI / INT / REP / NOTIF / VAL) | ✓ |
| Acceptance Criteria + Test Cases + traceability | ✓ |
| Validation evidence expectations | ✓ |
| Closed decisions + dependencies | ✓ |
| 10 mermaid diagrams (Doc Lifecycle, Doc Review Lifecycle, Architectural picture, ER overview, Doc Lifecycle state machine, Library subdomain governance, RAG ingestion+retrieval flow, Cross-module wiring, AC sequence) | ✓ |
| Version 1.0 only — no internal change-history scaffolding | ✓ |
| Module scoped strictly to Document Control / Document Review / Knowledge Libraries; cross-module integrations to URS-13 use module-number references only | ✓ |

---

## 20. Final Module Output Quality Gate

**URS approval is separate from validation execution.** This document becomes "Approved Controlled URS — released for engineering implementation and validation planning" upon signature capture; it becomes "Released for validation execution" only after URS-12-VAL-008 (Migration Evidence Gate) and the §17 validation evidence pack are satisfied. **No Module 12 internal open questions remain.**

- **Specification ready for engineering review?** Yes — every requirement is traceable to the controlled requirements register, requirements-to-test matrix, and module traceability basis in this URS.
- **Specification ready for quality validation review?** Yes — IQ/OQ/PQ + RLS evidence + audit chain integrity + ARCH-AI-001 AC-1..AC-7 evidence + RAG model acceptance criteria + Internal forward-looking AI governance evidence (EU AI Act Art. 13 transparency principles) are itemised in §17.
- **Specification ready for compliance review?** Yes — enacted predicate rules covered: ALCOA+, 21 CFR Part 11 §11.10(a/d/e/g) §11.50/11.70/11.100/11.200/11.300, EU GMP Annex 11 §4/9/12/16, EU GMP Chapter 4, ICH Q10, ICH Q12, ICH GCP E6(R3), MHRA ALCOA+, GAMP 5 Cat 5, Health Canada C.02.020, WHO TRS 996 Annex 5 — all mapped in §14. EU GMP Annex 22 Draft §7 and EU AI Act Article 13 are treated as internal forward-looking AI governance references unless jurisdiction-specific legal assessment determines otherwise. Binding predicate-rule obligations remain those listed in §14.
- **Specification ready for inspector / client review?** Yes — 28 end-to-end journeys (§4), full requirements register (§15), evidence pack index (§17.2).
- **Specification ready for Founder approval?** Yes.
- **Blocking gaps?** None internal. Cross-module dependencies (§18.2) are owned by named companion modules. Forward dependencies (URS-13 linkage, URS-27 Regulatory Library feed, URS-28 training-required document distribution, URS-32 MIRA RAG consumption) documented but not blocking for launch.
- **Two-step release path:**
  1. **Approved Controlled URS — released for engineering implementation and validation planning.** Reached upon signature capture.
  2. **Released for validation execution.** Reached after URS-12-VAL-008 is satisfied and the §17 evidence pack is complete.

---

## Appendix A — Module 12 End-to-End Composite (Author → Review → Approve → Effective → Library → RAG → Retrieval)

```mermaid
flowchart TD
  A([document_owner creates draft from template]) --> B[DRAFT state document]
  B --> C[Section-level checkout/checkin to document_versions]
  C --> D[Author submits for review]
  D --> E[document-review/service initiates review per type matrix]
  E --> F[reviewer assignments + checklist + comment thread + SoD-12-02 enforced]
  F --> G{Review outcome?}
  G -- revision requested --> H[document returns to DRAFT; new review cycle preserves prior comments]
  H --> D
  G -- approved with e-signature --> I[document state APPROVED]
  I --> J{effective_from reached?}
  J -- yes --> K[document state EFFECTIVE]
  K --> L[URS-30 distribution to named recipients with read-receipt task]
  L --> M[URS-28 training-required tasks issued where applicable]
  K --> N[document-library indexes entry into appropriate Knowledge Library subdomain]
  N --> O{Library subdomain}
  O -- regulatory --> P[Regulatory Library — source-distinct retrieval-trust per DOC-018]
  O -- process --> Q[Process Library — process domain taxonomy]
  O -- project --> R[Project Library — ProjectDocument linkage to URS-07 Study]
  P --> S[document-library entitlement policy evaluated: role / group / scope / direct]
  Q --> S
  R --> S
  N --> T[rag.service.ts ingests: chunk + embed via AiGatewayService text-embedding-3-small + persist to document_embeddings with provenance]
  T --> U[entry retrievable via RAG semantic + keyword fallback per ARCH-AI-001 AC-7]
  U --> V{Retrieval mode}
  V -- semantic --> W[citation-grade chunks returned with source + version + library + chunk position + confidence]
  V -- keyword_fallback (AI Gateway unavailable) --> X[keyword search results returned with retrieval_mode banner]
  W --> Y[ai_requests log: query + chunk IDs + provenance + user]
  X --> Y
  Y --> Z{Downstream LLM use?}
  Z -- yes (e.g., MIRA) --> AA[llm_audit_log: model + prompt + retrieved chunks + answer + accept/modify/reject]
  Z -- no --> AB[direct retrieval render to user with provenance UI]
  K --> AC{Lifecycle event}
  AC -- new version --> AD[supersede route — predecessor preserved]
  AC -- retirement --> AE[retirement workflow — retention class + e-signature]
  AC -- executive hold --> AF[HELD modifier — read-only; release requires SoD-12-06 second executive authority e-sign]
  AC -- periodic review due --> AG[review cycle initiated 90 days before next_review_due_at]
  AC -- periodic review missed --> AH[regulatory_concern auto-suspension; remediation = owner + QA co-sign]
  AD --> [*]
  AE --> [*]
```

Diagram Appendix A — Module 12 End-to-End Composite. Single composite flow showing author → submit → review (with SoD) → approve → effective → distribution + training + library indexing + RAG ingestion → retrieval (with graceful degradation + provenance + advisory labelling) → downstream LLM audit → lifecycle events (supersede / retire / executive break-glass / periodic review / auto-suspension). Every transition is electronically signed and audited per URS-06; every AI surface is bound to ARCH-AI-001 AC-1..AC-7.

— End of Module 12 User Requirements Specification —


