Chapter 1 · Sessions 1–2
What the old tool holds, and the tables that replace it
A file on a shared drive is a document. A controlled document also has an owner, a number, a revision, an approval and a list of people who must follow it, so only the current approved revision is in use. Session 1 finds out, from the old tool's own reports and bills, what you control today and what it costs. Session 2 adds the nine tables that will hold it, tried on the development project before anything reaches production.
35 min5 stepsSessions 1 and 2About 7 hours hands-on across six sessions
By the end of this chapter you can
- Inventory the old document tool from its own reports and invoices: places, counts, approvers, bill, export.
- Take one measured starting number: minutes to find the current revision of a real document.
- Check the spine tables the module points at, and add only the missing ones, in their own migration.
- Have Claude Code write the nine doc_ tables with their rules, seed and tests in one pull request, and try them on the development project.
What a controlled document is, and what this module replaces
Document Control keeps SOPs, work instructions, specifications, forms and policies under control: only the current approved revision is in use, every change is reviewed, approved and signed, the people affected are trained before it takes effect, and the history is ready for an audit. It replaces the controlled-document tools a business usually pays for (MasterControl Documents, Veeva Vault QualityDocs, Qualio, Intelex Document Control, Ideagen) and a SharePoint library used as a controlled library [5].
| Standard | Used in this module for |
|---|---|
| ISO 9001:2015 clause 7.5 [1] | Creating, updating and controlling documented information |
| ISO 13485:2016 clauses 4.2.4 and 4.2.5 [2] | Control of documents and of records, for medical device makers |
| 21 CFR Part 11, sections 11.10, 11.50, 11.70 [3] | Audit trails; a signature that shows name, date and time and meaning; a signature linked to its record |
| EU GMP Annex 11 [4] | Computerised systems in GMP manufacturing |
| ISO 15489-1:2016 | Records management principles and retention (Session 6) |
| ISO 19005 (PDF/A) | A long-term archive copy of each effective revision (Session 6) |
Session 1: Inventory the old tool from its own reports and bills
45 minutesWhy
The module replaces real things, so it starts from real numbers: where controlled documents live today, how many there are, who approves them and what the tool costs. Numbers read from the tool's own reports and invoices survive a challenge from finance; guessed numbers do not, and a guessed saving is the fastest way to lose the argument for switching the old tool off.
Do this
Collect these yourself, from the old tool and your own invoices (Claude Code never logs in to the old tool):
- Every place a controlled document lives: the document tool, a SharePoint library, a shared drive, binders in a cabinet. The owner of each.
- The document count by type (SOP, work instruction, specification, form, policy), from the tool's own register report. If there is no register, count one folder by hand and say so.
- The bill: amount, number of users and renewal date, as printed on the vendor's billing page or your last invoice. If you cannot see it, write who can.
- The export page: can you export documents with their metadata, their revision history and the files? Note what it says, word for word.
- Which rules you are held to (ISO 9001, ISO 13485, Part 11), in your quality lead's words.
Then open Claude Code in your repository and give it your notes:
cd ~/code/acme-platform && git switch main && git pull && claudeOn a new branch documents/inventory, write docs/documents-inventory.md from my notes below. It is for the owner of the old document tool and for finance, so plain English.
Sections:
1. Places and tools: a table with name, owner, how people sign in, bill per year, users, renewal date, export available (documents / metadata / revision history / files).
2. Document counts by type, and where each count came from (a report name, or "counted by hand in <folder>").
3. Rules we are held to, in the quality lead's words.
4. Workarounds people use today.
Rules:
- Use only the numbers in my notes. Never estimate, round or fill a gap. Where a number is missing write "not yet read: <who can read it>".
- No document content, no personal names except the tool owners'.
Then open a pull request titled "Documents inventory" and show me the link.
My notes:
<paste your notes here>You will see recreated screen
- Note the plan name exactly: the export rights and the cancellation terms depend on it.
- The renewal date sets your deadline: Session 6 must finish, and the export be safe, before it.
You will see recreated screen
- Each figure says where it came from. A figure with no source is a guess.
- A gap is written as a gap, with who can fill it.
Check it worked
The pull request has one file, docs/documents-inventory.md. Every number in it names its source, and every missing number says who can read it. Nothing is estimated.
Fastest path
Ask the tool's administrator for three reports in one email before the session: documents by type, users, and the last invoice. Then this step is one sitting.
If it goes wrong
You cannot see the bill
Write who can (finance, the tool's administrator) in the inventory and send them one line: "Please send the last invoice for the document tool, and the renewal date." Do not use a list price from the vendor's website: your contract may differ.
The export page does not mention revision history
Ask the vendor in writing what an export contains. A tool that cannot export history changes Session 5: you may import the current revisions and keep the old tool's history read-only. Find out now, not in Session 5.
Claude Code wrote a figure you did not give it
Say: Remove every number that is not in my notes and mark it 'not yet read'. We have seen agents fill empty places so a page looks finished; in an inventory that becomes a saving nobody can prove.
Session 1: Classify three real documents and time the baseline
30 minutesWhy
Three real documents test the module before it exists: if their approval route or training rule does not fit the tables, you find out now, not after the import. The baseline (how long a new operator takes to find the current revision, and how many copies they meet on the way) is the number Session 6 measures again to show what changed.
Do this
Pick three documents of three different types that people use every week. For each, write: who writes it, who reviews it, who approves it, how approval is recorded today (wet ink, typed name, email reply, e-signature), how often it is meant to be reviewed, and who must be trained when it changes.
Then take the baseline. Pretend to be a new operator: start where people normally look and find the current approved revision of one of the three. Time it, and count every different copy or revision you meet (folders, email attachments, binder copies).
Add a section "Three documents and the baseline" to docs/documents-inventory.md on the same branch, from my notes below:
- a table with document number, type, writer, reviewer, approver, how approval is recorded today, review period in months, who must be trained;
- the baseline: document, minutes to find the current revision, number of copies found, date and who timed it;
- "First documents to move": the type I chose and one sentence why.
Use my words. Do not add anything I did not write. Push to the same pull request.
My notes:
<paste your notes here>Ask the approver you named to read the section. Then owner two approves and the pull request merges.
You will see recreated screen
- Each document's route and training rule: the module's tables must be able to hold exactly this.
- The baseline, with the date and who timed it. Session 6 repeats it on a phone.
Check it worked
docs/documents-inventory.md on main lists three real documents with their full route, the baseline in minutes and copies, and the first type to move, read by its approver.
If it goes wrong
A document names people
Use job roles in the inventory ("press supervisor"), not names. The module stores people in core_person later, under access rules; the inventory is read by more people than that.
Nobody knows the review period
Write "not set" and ask the quality lead. A review period nobody knows is one of the workarounds Session 4 fixes; record it, do not invent one.
Nine tables on the shared spine
Every module table carries the standard columns of the module library's spine: id, site_id (in place of the specification's tenant_id, as docs/spine-map.md records), created_at, created_by, updated_at, updated_by, row_version, archived_at and ext. The module has no people table, site list, role list or file store of its own: it points at the spine's core_person, core_site, core_job_role, core_attachment and core_e_signature, which the shared spine map names on your platform (core_site is your sites table). Its own tables share the prefix doc_.
| Table | One row is | Columns (req = required) and allowed values |
|---|---|---|
| doc_doc_type | A document type | code req, unique; name req; numbering_prefix req; review_period_months; requires_training req; training_mode: read_and_understood, course, none; approval_route json req |
| doc_controlled_document | The header of one controlled document | doc_no req, unique; title req; doc_type_id req; owner_id req (core_person); site_id (core_site); current_revision_id; effective_revision_id; status req: draft, in_review, approved, effective, superseded, obsolete; confidentiality req: public, internal, confidential, restricted; next_review_due |
| doc_revision | One revision, with its file and fingerprint | document_id req; revision_label req; major req; minor req; change_summary; change_control_ref (soft link to M08); source_attachment_id; pdfa_attachment_id; sha256; status req: draft, in_review, approved, effective, superseded, withdrawn; effective_at; superseded_at |
| doc_review_task | One reviewer's or approver's task | revision_id req; reviewer_id req; role req: reviewer, approver, qa_approver, owner; step_no req; due_at; decision req: pending, approve, reject, comment; comments; decided_at; signature_id |
| doc_document_link | A link to another document or record | document_id req; linked_type req; linked_id req; relation req: references, implements, supersedes, training_for, form_for, procedure_for |
| doc_distribution | Who must follow a revision, and their acknowledgement | revision_id req; person_id; job_role_id (one of the two is required); ack_required req; acknowledged_at; signature_id |
| doc_controlled_print | One numbered controlled copy | revision_id req; copy_no req; printed_by req; printed_at req; location_text; reconciled_at; reconciled_by |
| doc_periodic_review | One scheduled periodic review | document_id req; due_at req; completed_at; reviewer_id; outcome req: pending, no_change, revise, obsolete; note |
| doc_external_document | One external standard or regulation | title req; issuer req; designation; edition; url; monitored req; last_checked_at; owner_id |
Session 2: Check the spine the module points at
20 minutesWhy
The doc_ tables point at people, sites, job roles, files, signatures, number sequences, action items, an event outbox and an audit log. If one of those is missing, the module's migration fails in CI; if Claude Code quietly invents one inside the module's migration, the next module that needs it gets a different shape. Checking first, and adding only what is missing in its own migration, keeps one spine for every module.
Do this
Read docs/SCHEMA-PLAN.md, docs/spine-map.md if another module has written it, and every file in supabase/migrations. Do not write anything yet.
Module M06 (document control) points at these spine tables: core_person, core_site, core_job_role, core_attachment, core_e_signature, core_number_sequence, core_action_item, core_event_outbox and core_audit_log, with the helper functions core_current_actor(), core_touch_row() and core_audit_row(). They are defined in the CivOps module library's spine (00_core_spine.sql); every one has the standard columns id, tenant_id, created_at, created_by, updated_at, updated_by, row_version, archived_at, ext. We are one company: on our platform site_id replaces tenant_id, because site_id is the scope the access rules of Session 8 use.
Tell me in a table: which exist already, under the specification's name or ours (sites for core_site; the sign-in users with memberships for core_person), and in which migration; which are missing; and for any that exist with a different shape, what differs. Say which doc_ tables belong to no site (company-wide).
Then propose, and wait for my yes:
- a Documents section in the one shared docs/spine-map.md (create it if no module has yet; never a second map file): each core_ name and our table for it, site_id in place of tenant_id, and any doc_ table that is company-wide;
- one new migration (npx supabase migration new spine_for_documents) that adds only the missing spine tables and helpers, with their exact columns and check constraints, site_id where a row belongs to a site;
- row-level security on, but NOT the spine's own tenant_isolation policies: access on our platform comes only from docs/matrix.json through scripts/gen-policies.mjs.
Never put a spine table inside a module migration, and never build a second sites or people list.You will see recreated screen
- The report comes first. If it starts writing straight away, stop it and ask for the report.
- The scope column decides every access rule. Agree it before any table exists.
Check it worked
You have a table of the nine spine tables marked exists (with our name) or missing, and the Documents section of docs/spine-map.md that you agreed. After your yes, a pull request "Spine for documents" is green, with row-level security on and no tenant_isolation policies.
Fastest path
If you built another module already, most of the spine is there. Say: Reuse every spine table that exists; add only what M06 needs that is missing.
If it goes wrong
Claude Code adds a tenant_id column or a core_tenant table
Say: We are one company: module tables carry site_id, as docs/spine-map.md records. Remove tenant_id and core_tenant. A second scope column means a second access rule nobody generated.
The migration copies the spine's tenant_isolation policies
Say: Remove every hand-written policy. Access comes only from docs/matrix.json through scripts/gen-policies.mjs. A tenant_isolation policy lets every signed-in person do everything inside the company, which silently overrides the matrix.
Claude Code proposes core_person as a copy of memberships
Ask it to keep one source: core_person.auth_user_id points at the signed-in account, and memberships keeps roles per site. Two copies of the same people drift apart within weeks.
Session 2: One prompt: the nine tables, their rules, the seed, the hand-worked fixture and the tests
40 minutesWhy
Writing the tables, the rules the database keeps, the made-up data and the tests that try to break the rules in one pull request means the proof arrives with the change. The made-up library is small on purpose: Session 4 counts it by hand and the KPIs must agree. It is kept twice: on its fixed dates as a test fixture the tests count, and shifted onto today as the seed the screens show.
Do this
Read docs/documents-inventory.md, docs/naming-standard.md, docs/spine-map.md and the spine migration. On a new branch documents/tables:
1. npx supabase migration new create_documents. In it, create these nine tables with the standard spine columns (site_id where docs/spine-map.md says a row belongs to a site, with an index; the core_touch_row() update trigger and the core_audit_row() trigger on every table). Required means not null; listed values are check constraints. Foreign keys only to spine tables (by docs/spine-map.md) and to each other.
- doc_doc_type: code req; name req; numbering_prefix req; review_period_months int; requires_training bool req; training_mode in (read_and_understood, course, none); approval_route jsonb req. unique (code).
- doc_controlled_document: doc_no req; title req; doc_type_id req; owner_id req -> core_person; site_id -> core_site; current_revision_id uuid; effective_revision_id uuid (both plain uuid, no foreign key); status req in (draft, in_review, approved, effective, superseded, obsolete); confidentiality req in (public, internal, confidential, restricted); next_review_due date. unique (doc_no).
- doc_revision: document_id req; revision_label req (must read major.minor); major int req; minor int req; change_summary; change_control_ref uuid (soft link, no foreign key); source_attachment_id, pdfa_attachment_id -> core_attachment; sha256 text; status req in (draft, in_review, approved, effective, superseded, withdrawn); effective_at, superseded_at timestamptz. unique (document_id, major, minor).
- doc_review_task: revision_id req; reviewer_id req -> core_person; role req in (reviewer, approver, qa_approver, owner); step_no int req; due_at; decision req in (pending, approve, reject, comment); comments; decided_at; signature_id -> core_e_signature. Check: a reject must have non-empty comments.
- doc_document_link: document_id req; linked_type req; linked_id uuid req; relation req in (references, implements, supersedes, training_for, form_for, procedure_for).
- doc_distribution: revision_id req; person_id -> core_person; job_role_id -> core_job_role; ack_required bool req; acknowledged_at; signature_id. Check: person_id or job_role_id is set.
- doc_controlled_print: revision_id req; copy_no int req; printed_by req; printed_at req; location_text; reconciled_at; reconciled_by. unique (revision_id, copy_no).
- doc_periodic_review: document_id req; due_at date req; completed_at; reviewer_id; outcome req in (pending, no_change, revise, obsolete); note.
- doc_external_document: title req; issuer req; designation; edition; url; monitored bool req; last_checked_at; owner_id.
Row-level security on for all nine, no policies.
2. Add the nine tables to docs/matrix.json with no rights yet (Session 3 fills them), and run scripts/gen-policies.mjs so it does not refuse a table missing from the matrix.
3. Write supabase/seeds/documents.sql, made up, marked SYNTHETIC, safe to run twice, and list it under [db.seed] sql_paths in supabase/config.toml so CI loads it after the Foundation seed (never in supabase/seed.sql). Every date below moves by the same number of days so that 2026-06-30 falls on the day the seed runs. Types: SOP (prefix SOP, review 24 months, read_and_understood), WI (prefix WI, 12 months, read_and_understood), SPEC (prefix SPEC, no review period, requires_training false, none). Five documents: A, a SOP: 1.0 and 2.0 superseded, 3.0 effective from 2026-01-15. B, a WI: 1.0 effective from 2026-02-15; 1.1 in review with two pending tasks (step 1 reviewer, step 2 approver). C, a SOP: one draft. D, a WI: 1.0 effective from 2025-06-01. E, a SPEC: one withdrawn revision, document obsolete. Approved review tasks with signatures (meaning approved, role in comment): A 3.0 submitted 2026-01-05, approved 2026-01-12; B 1.0 submitted 2026-02-02, approved 2026-02-10; D 1.0 submitted 2025-05-12, approved 2025-05-14. Distribution with ack_required true: A 3.0 to four people, all acknowledged before 2026-01-15; B 1.0 to three, two before 2026-02-15 and one after; D 1.0 to two, both before 2025-06-01. Periodic reviews, all pending: D due 2026-06-01, B 2027-02-15, A 2028-01-15. One core_number_sequence row per prefix (padding 4, reset_rule never), next_value one above the highest seeded number. A small made-up text file per revision. Write the same rows, on exactly these dates, to tests/fixtures/documents-library.json: the hand-worked example the KPI and overdue tests load into a made-up site of their own; no test counts on the seed's dates.
4. pgTAP tests in supabase/tests/documents.test.sql: every doc_ table exists with row-level security on; the database refuses a document with a status outside the list, a revision with no document, a distribution row with neither person nor job role, a second revision with the same major and minor, and a reject with empty comments. After seeding: 5 documents, 8 revisions (3 effective, 2 superseded, 1 in review, 1 draft, 1 withdrawn).
5. Do not connect to any Supabase project. Push, open a pull request titled "Documents: tables", wait for every check, and tell me the result in plain words with the number of tests. If a check fails, fix it and wait again before reporting.You will see recreated screen
- A new migration with its own time. The spine migration from the last step is untouched.
- A rule kept by the database itself: no screen, import or agent can store a reject without a reason.
- Counts you can check against the seed you asked for.
Check it worked
Pull request Documents: tables is green on GitHub (not only in the summary), and the summary gives 5 documents and 8 revisions after the seed.
Fastest path
"Wait for every check and fix it before reporting" saves a round trip: Claude Code reads its own failures while you do something else.
If it goes wrong
CI fails: table doc_doc_type is not in docs/matrix.json
The generator from Session 8 is doing its job. Say: Add the nine doc_ tables to docs/matrix.json with no rights, rerun gen-policies and push.
The summary says all tests pass but the check on GitHub is red
Say: Show me the exact command, its exit code and the last 20 lines of the failed check log, then fix the cause. A summary is a claim; the check on the pull request is the evidence.
The seed's counts are off by one
Fix the seed and the fixture, not the test. Every later count in this module (the KPIs in Session 4, the overdue count in Session 6) is checked against this library, and we have seen later steps written against counts the made-up data never created.
Claude Code tries to run supabase db push
The settings from Foundation Session 1 refuse it. Say: Do not touch any Supabase project. I apply it to the development project myself.
Session 2: Try it on the development project, then merge
15 minutesWhy
CI proves the files build a database from nothing. Applying them to the development project, which already holds the Foundation's made-up data, proves they also apply on top of a real history of migrations, the way production will. You do it yourself because it changes a database; after merge, the deploy workflow from Foundation Session 11 applies the same files to production, so nobody runs db push against production by hand.
Do this
In your own terminal (not inside Claude Code), on the pull request's branch:
cd ~/code/acme-platform && git fetch && git switch documents/tablesnpx supabase link --project-ref tsrqponmlkjihgfedcbanpx supabase db push --include-seedIt asks for the development database password: copy it from the password manager entry for acme-platform-dev. --include-seed loads the module's made-up rows the first time; after that, reload them with npm run seed:dev. Then run the count below in the SQL editor.
https://supabase.com/dashboard/project/tsrqponmlkjihgfedcba/sql/new
The development project's SQL editor. Check the project name at the top says acme-platform-dev before you run anything.
-- Expect: effective 3, superseded 2, in_review 1, draft 1, withdrawn 1
select status, count(*) from doc_revision group by status order by status;When the counts match, owner two approves and you merge. Then watch the deploy run apply the migration to production:
https://github.com/acme-ops/acme-platform/actions
GitHub Actions: the deploy run for your merge must be green.
You will see recreated screen
- Only the new files. If it lists something you do not expect, answer n and ask in Claude Code why.
You will see recreated screen
- The pipeline, not a person, changes production.
- Made-up rows never enter production.
Check it worked
On acme-platform-dev the count query returns effective 3, superseded 2, in_review 1, draft 1, withdrawn 1. After merge, the deploy run is green, and the next daily production-freshness check from Session 11 shows production matches main.
If it goes wrong
db push lists migrations you did not write
The development project is behind main. Answer n. Switch to main, pull, push main's migrations first, then switch back to the branch.
The deploy run fails at migrate
Production is unchanged: the deploy stops before new code goes live. Open the run's log, copy the error into Claude Code and say: The production migrate step failed with this error. Explain it in plain words and propose a fix as a new migration. Do not touch production.
You ran the seed on production by mistake
Stop and tell owner two. Every seeded row says synthetic, so it can be found. Ask Claude Code for a script that lists, then deletes, only rows marked synthetic, and run it with owner two watching.
Knowledge check
Where do the bill and the renewal date in docs/documents-inventory.md come from?
Knowledge check
Claude Code proposes copying the spine's tenant_isolation policies into the spine migration. Why refuse?
References
- ISO 9001:2015 Quality management systems: requirements (clause 7.5, documented information). https://www.iso.org/standard/62085.html
- ISO 13485:2016 Medical devices: quality management systems (clauses 4.2.4 and 4.2.5). https://www.iso.org/standard/59752.html
- eCFR: Title 21, Part 11, Electronic records; electronic signatures. https://www.ecfr.gov/current/title-21/chapter-I/subchapter-A/part-11
- European Commission: EudraLex Volume 4, EU GMP guidelines (includes Annex 11, computerised systems). https://health.ec.europa.eu/medicinal-products/eudralex/eudralex-volume-4_en
- Prezent: QMS platforms for life sciences (the MasterControl and Veeva modules). https://www.prezent.ai/blog/qms-for-life-sciences
- Supabase Docs: Database migrations. https://supabase.com/docs/guides/deployment/database-migrations
Chapter 2 · Sessions 3–4
Who may do what, the screens, and the signed workflow
Session 3 writes every right the module needs into the role matrix once, regenerates the database rules, route guards and tests from it, and builds the five screens. Session 4 runs a document from draft to effective: numbered, reviewed, rejected with a reason, signed with a re-entered password, held until its people are trained, and made the only effective revision.
40 min5 stepsSessions 3 and 4Part 11 signatures
By the end of this chapter you can
- Write the module's roles, rights and rules into docs/matrix.json, and regenerate policies, route guards and tests from it.
- Build the register, the revision editor with redline compare, the inbox, the read-and-understood list and the admin page.
- Run the revision lifecycle with serial or parallel routing and reject with a reason.
- Sign with re-authentication, bind each signature to the file's sha256, and prove the binding fails on a changed copy.
- Gate the effective date on training, and prove the database allows one effective revision per document.
Roles are jobs, and every right is written once
The rights below are the module's rows in the role matrix from Foundation Session 7. Nobody writes a policy by hand: scripts/gen-policies.mjs (Session 8) turns each cell into a database rule and a test, and the route list (Session 9) turns the screens into route guards. Two rights are common to every role: read doc_doc_type, core_site, core_job_role and people's names (not contact details), and read the signatures on any revision they can read. Nobody gets delete: a correction is a new revision, a withdrawn revision or an obsolete document.
| Role | Reads | Writes | Never |
|---|---|---|---|
| Owner (own documents) | Their documents, revisions, tasks, links, distribution, prints, reviews, files; their own action items | Title, site, confidentiality; new draft revisions (holds the author role on them); distribution rows by job role; controlled prints; periodic review outcome; signs owner steps | Sign a step that is not theirs |
| Author | Their own drafts and the tasks on them; every effective revision and its file | Draft documents and revisions, check-out and check-in, links, distribution by job role, file uploads | Sign anything; hold a review task on their own revision |
| Reviewer, approver, QA approver | Revisions assigned to them in review, every effective revision, their own tasks; the QA approver also reads every doc_ table and the audit log | Their own pending task while its step is open (decision, comments, signature); the QA approver withdraws a revision when a periodic review says obsolete | Change a revision; decide another person's task |
| Reader | The effective revision of public and internal documents, and of others distributed to them; an approved revision only through their own distribution row | Their own acknowledgement, with a signature | See a draft, in-review or superseded revision |
| Administrator | Every doc_ table, the audit log and the event outbox | Types, the external register, number sequences, owner and site of a document, reconciling prints, reassigning a pending task (never to themselves) | Sign, approve, or change an effective revision |
| doc_scheduler (machine) | What the effective-date gate, overdue escalation and archive jobs need | Revision status approved to effective and effective to superseded; header pointers; periodic reviews; action items; outbox events; archive files | Anything a person does; it is refused any person's sign-in |
| doc_importer (machine, Sessions 5–6) | Types, documents, revisions, people's emails (to match owners), sites | Inserts only: imported documents and revisions with ext.imported true, and their files | Update anything; insert a signature, a review task or a training assignment; sign in after cut-over |
Session 3: Write the roles and rights into the matrix, and regenerate everything
35 minutesWhy
Access decided in one file is access you can review in one place. Every right Sessions 4 to 6 need is written now, because the database refuses anything the matrix does not grant: a right forgotten here shows up later as a button that reports success while nothing changes. Generating policies, route guards and tests from the same file means they cannot drift apart.
Do this
Read docs/matrix.json, scripts/gen-policies.mjs, lib/access/routes.ts and docs/access-review.md. On a new branch documents/access, add module M06 to the matrix:
Roles (jobs, not people; keep every Foundation role): doc_owner, doc_author, doc_reviewer, doc_approver, doc_qa_approver, doc_reader, doc_admin, and two machine accounts: doc_scheduler and doc_importer (each signs in with its own account, never the service-role key; a request carrying a person's sign-in is refused for them).
Cells: exactly the rights in the M06 table I paste below. Every role reads doc_doc_type, core_site, core_job_role and people's names; every role that can read a revision reads its core_e_signature rows. Nobody gets delete on any doc_ table.
Rules (restrictive, so no other grant can override them):
- an author never holds a review task on a revision they created;
- a reader sees only effective revisions, plus an approved revision when a doc_distribution row names them or their job role;
- a reviewer updates only their own pending task, and only while every lower step_no is done;
- doc_importer can never insert core_e_signature, doc_review_task or trn_assignment.
For every update a role makes, make sure its read rule also covers the row after the change, or the update will silently change nothing.
Screens: /documents (all M06 roles), /documents/revision (author, owner, reviewer, approver, QA approver), /documents/review (reviewer, approver, QA approver, owner), /documents/read (reader), /documents/admin (admin, QA approver). Routes: /api/documents/submit, /decide, /acknowledge, /print, /verify (all M06 roles), /scheduler (doc_scheduler only). doc_importer has no screen and no route: it signs in only from the import workflow, and only inserts.
Run scripts/gen-policies.mjs and scripts/gen-routes.mjs (which writes lib/access/routes.ts), regenerate docs/access-review.md, and extend supabase/tests/access.test.sql with one allowed and one refused test per cell, plus: an author reviewing their own revision is refused, a reader cannot see a draft, a person's sign-in is refused by /api/documents/scheduler, doc_importer cannot insert a signature, nobody can delete. Each update test checks the row really changed in the database.
Push, open a pull request titled "Documents: access", wait for every check, and tell me the result.
The M06 table:
<paste the "Roles are jobs" table from element M06, chapter 2>You will see recreated screen
- The only hand edit: the matrix. The policies are generated from it.
- Allowed and refused, for every cell.
You will see recreated screen
- Owner two reads one section per role and approves only if each matches the job.
Check it worked
Pull request Documents: access is green, docs/access-review.md has a section for each of the nine new roles, and owner two has read it before approving.
If it goes wrong
A Publish or Approve button reports success but the status does not change
The role can update the row but its read rule does not cover the row after the change, so Postgres finds nothing to update. We hit this in three module builds. Say: For each role that updates doc_ rows, check its read rule covers the row before and after the change; add a test that the row really changed.
The generator refuses: role used in screens but not defined
A screen names a role the roles section does not have. Say: List every role used in screens and data but missing from roles, and add them.
Claude Code checks only that the user is signed in on a route
Signed in is not allowed. Say: Every /api/documents route must decide by the matrix role for what it does (submit, decide, print, import), not by sign-in alone, with a refused-role test per route.
Session 3: Build the five screens, and test them on a phone
45 minutesWhy
The screens are where people meet the rules. A reader acknowledging a procedure on a phone at the press is the main case, so the phone check is part of done, not a polish step. Building against the made-up seed means every screen can be checked against numbers you already know.
Do this
Before writing any page or route, read the guides in node_modules/next/dist/docs/ for routing and for proxy.ts (this Next.js version differs from older guides), and lib/access/routes.ts.
On a new branch documents/screens, build against the seed:
- /documents: the register. Number, title, type, owner, status, revision label. Search on number and title, filters on type, owner, site and status, and full-text search of title and change summary (a Postgres text index). Readers see effective revisions only.
- /documents/revision: metadata, check-out on a draft, and a redline compare of two chosen revisions: added words underlined and in one style, removed words struck through, never colour alone. Name the diff library you use and its licence.
- /documents/review: the signed-in person's pending tasks, oldest first, and for an owner their own open action items.
- /documents/read: the revisions this reader must acknowledge.
- /documents/admin: types, number sequences, the KPIs (Session 4) and, for admin and QA approver, their own open action items.
Take the signed-in person from the session on the server, never from the page. Every screen follows the operator-surface rules from Foundation Session 12: 44 px targets, 16 px form fields, no sideways scrolling.
Add screen tests per role (allowed and refused, and signed out lands on sign-in) and phone-size tests at 360 and 390 px. Push, open a pull request titled "Documents: screens", wait for every check, and give me the preview address.You will see recreated screen
| Number | Title | Type | Rev | Status |
|---|---|---|---|---|
| WI-0031 | Flange height gauge check | WI | 1.0 | effective |
| SOP-0012 | Die change and first-piece approval | SOP | 3.0 | effective |
- Two documents match the search. A reader never sees a revision that is still in review.
- Readers see what is in force, not what is in work.
You will see recreated screen
- The reason for the change, which the reviewer reads with the difference.
Check it worked
Every check on the pull request is green. On the preview, signed in as each test role, each screen shows what the matrix says and nothing more, and the read list works on your phone without sideways scrolling.
Fastest path
Open the preview on your own phone while CI runs. Then sit the approver in front of the inbox and a reader in front of the read list for ten minutes this week, without explaining, and note where each one stops.
If it goes wrong
A link opens a blank 404
A link that compiles is not a link that resolves. Say: Start the production build, visit every page and every link as each role, and report every 404 and error page.
Every record says it was created by the same person
The page is sending the user's name and the server trusts it. Say: Take the user's identity from the session on the server and ignore what the page sends; add a test with two users.
The redline uses red and green only
Say: Mark added and removed words with underline and strike-through as well as colour. About one man in twelve cannot tell red from green.
The life of a revision
A document does not change; it gets revisions. In this course 1.0 is the first effective revision, 1.1 a small change and 2.0 a big one. While 2.0 is in review the document stays effective: effective_revision_id still names 1.0, which readers see, and current_revision_id names 2.0, the one in work.
| Revision status | Means | Can it be edited? |
|---|---|---|
| draft | Being written; check-out and check-in apply | Yes, by its author |
| in_review | Submitted; the file's sha256 is fixed and review tasks are open | No |
| approved | Every step signed; waiting for its effective date and its trainees | No |
| effective | The one revision readers use | No |
| superseded | Replaced by a newer effective revision; kept for the record | No |
| withdrawn | Taken out of use with no successor; kept for the record | No |
Each type's approval_route is a list of steps. Steps with the same step_no run in parallel; a step opens when every lower one is done. A reject needs a reason, returns the revision to draft and closes the round; resubmitting opens a new round.
{ "steps": [
{ "step_no": 1, "role": "reviewer" },
{ "step_no": 1, "role": "reviewer" },
{ "step_no": 2, "role": "approver" },
{ "step_no": 3, "role": "qa_approver" }
] }What a signature must show, and what it is bound to
21 CFR Part 11 section 11.50 asks that a signed record show the signer's printed name, the date and time and the meaning of the signature; section 11.70 asks that the signature be linked to its record so it cannot be copied to another [1]. The module meets both: the signer re-enters their password at the moment of signing, the server writes a core_e_signature with meaning (reviewed, approved or acknowledged, the words the spine allows), the server's time and a record_hash equal to the revision's sha256, and the screen shows name, time and meaning beside it.
Session 4: Number, submit, review, and reject with a reason
40 minutesWhy
This is the heart of control: a document gets a number nobody types, a revision is frozen the moment it is submitted, and every reviewer's decision is recorded with a reason. Freezing at submit is what makes redline compare and signatures meaningful: the reviewer signs exactly what they read.
Do this
Read docs/matrix.json and the M06 tables. On a new branch documents/workflow, write docs/doc-rules.md (revision labels major.minor, the round rule, the signature meanings reviewed, approved, acknowledged with the role in comment) and build:
1. Create a document: doc_no issued from core_number_sequence with the type's numbering_prefix (never typed); first revision 0.1 in draft; file uploaded to Supabase Storage as a core_attachment. A storage rule lets a file be added but never replaced or deleted by any role.
2. Check-out and check-in on a draft (ext.checked_out_by, ext.checked_out_at); refuse an edit or a second check-out by anyone else.
3. /api/documents/submit, acting as the author: relabel a first revision 1.0 if needed; compute the sha256 of the stored file on the server (never accept one from the browser); set in_review; one doc_review_task per route step with due_at only on the open step; increment ext.round. A trigger refuses any change to revision_label, major, minor, change_summary, source_attachment_id and sha256 once a revision leaves draft.
4. /api/documents/decide: a reject needs a reason (the database already refuses an empty one), returns the revision to draft and closes every still-pending task of that round with decision comment and the note "round closed by rejection". The inbox lists only the current round.
5. Tests: the numbering issues SOP-0003 after the seed; a change to a submitted revision is refused; a reject without a reason is refused; after a rejection and resubmission, round 2 has new tasks and round 1 none pending.
For each new test, show me it failing with the rule removed, then passing.
Push, open a pull request titled "Documents: review", wait for every check, and report.You will see recreated screen
- Frozen by the database, not by the screen: no route or import can change a submitted revision.
- Red first, then green. A test that has never failed has not proved anything.
Check it worked
Pull request Documents: review is green. On its preview, as the test author, you created a document, submitted it, had the test reviewer reject it with a reason, resubmitted it and saw round 2 in the inbox.
If it goes wrong
The submit route takes the hash from the browser
Say: Compute sha256 on the server from the stored file; ignore any hash the page sends. A hash sent by the browser could be anything; one computed where the file is stored is a fact about that file.
A second person can check out a draft that is already checked out
Say: Make check-out a single update that succeeds only when ext.checked_out_by is empty, and test two check-outs at once: exactly one wins.
An old round's tasks still show in the inbox
Say: The inbox lists only pending tasks whose ext.round equals the revision's current round. Add a test.
Session 4: Sign with a re-entered password, and prove the binding
30 minutesWhy
A signature must mean one person decided, at that moment, about exactly that file. Re-entering the password stops a screen left open from signing. Binding the signature to the file's fingerprint, and checking it, proves years later that what was signed is what is stored. Showing the check fail on a changed copy is the only way to know it works.
Do this
On the same branch, finish /api/documents/decide for approvals:
- Before writing a signature, check the signer's password again with Supabase Auth on the server. Never store or log the password. Show me which Supabase Auth call you use and why, before writing it.
- Insert core_e_signature: signer_id, meaning (reviewed on a reviewer step, approved on approver, QA approver and owner steps), record_type doc_revision, record_id, record_hash = the revision's sha256, signed_at from the server clock, auth_method password_reauth, printed_name, comment = the step's role. Store its id on the task.
- Open the next step when every task of the current step is approve. On the last approval: status approved and the effective_at the QA approver chose (not before today).
- Show printed name, date and time and meaning beside every signature on the revision screen.
- /api/documents/verify: recompute the stored file's sha256 and compare it with doc_revision.sha256 and every signature's record_hash; answer match or mismatch.
- Tests: an author cannot sign their own revision; a wrong password writes no signature; verify reports mismatch for a copy of the file with one byte changed.
Push to the same pull request, wait for every check, and report.You will see recreated screen
| Signed by | Date and time | Meaning | Step |
|---|---|---|---|
| J. Ortiz | 2026-10-24 09:41 EDT | reviewed | reviewer |
| M. Chen | 2026-10-24 11:02 EDT | approved | approver |
| R. Patel | 2026-10-24 14:15 EDT | approved | qa_approver |
- The three things section 11.50 asks for, on the screen.
- The binding of section 11.70, checked on demand.
Check it worked
On the preview, approval asks for the password again; a wrong password writes no signature; the revision shows name, time and meaning; Verify says match, and the test that changes one byte of a copy reports mismatch.
If it goes wrong
Claude Code proposes storing the password, or a token, to sign later
Refuse. Say: Check the password at the moment of signing and forget it; nothing about it is stored or logged.
Someone could replace the file in storage and the screen would still say signed
This is the pitfall the specification names. Say: Show me the storage rule. No role may update or delete a document file; add a test that tries to replace one and expects a refusal. Then the verify route is the second line of defence.
Verify always says match, even on a changed file
A check that can only say yes is no check. Say: Show me verify failing on a copy with one byte changed, with the two fingerprints printed.
| Key or secret | What it unlocks | Where it lives | Who holds it | Never |
|---|---|---|---|---|
| CRON_SECRET | Lets Vercel's timer call /api/documents/scheduler; any other caller is refused | Vercel project environment variables (Production) | Owner one types it in Vercel; nobody else sees it | Pasted into Claude Code, a file or a chat |
| doc_scheduler account password | The scheduler's own sign-in, so the database applies the matrix to its work | Vercel environment variables, and the password manager | Owners one and two | Shared with a person's account, or replaced by the service-role key |
Session 4: Gate the effective date on training, and allow one effective revision
45 minutesWhy
A procedure that is effective on Monday while the crew learns of it on Wednesday means two days of work to a rule nobody had read. The gate makes the date a plan and the training count the decision. The one-effective rule in the database makes "which revision is in force?" impossible to answer two ways.
Do this
First, as a person: create the doc_scheduler account in Supabase Authentication (development project, then production), give it the doc_scheduler role in memberships, and type its password and a new CRON_SECRET into Vercel's environment variables. Make the secret in your own terminal:
openssl rand -hex 32https://vercel.com/acme-ops/acme-platform/settings/environment-variables
Vercel environment variables: add CRON_SECRET, DOC_SCHEDULER_EMAIL and DOC_SCHEDULER_PASSWORD (Production and Preview). Add their names, never values, to docs/KEYS.md.
On the same branch:
1. On the last approval, expand the distribution: one doc_distribution row per person holding each mapped job role, ack_required true only when the type is read_and_understood. For course, insert trn_assignment rows if module M07 is installed, otherwise one core_action_item for the training lead. The /api/documents/acknowledge route signs with meaning acknowledged, comment read_and_understood, record_hash the revision's sha256.
2. /api/documents/scheduler: refuse any call without the CRON_SECRET header from process.env, then sign in as the doc_scheduler account (never the service-role key). For each approved revision whose effective_at has passed: count required trainees against complete ones. Nobody required: it becomes effective. All complete: in one transaction supersede the old effective revision, make the new one effective, set the header pointers and status, set next_review_due from the type's review period, insert a pending doc_periodic_review, and write doc.revision.superseded and doc.revision.effective to core_event_outbox. Anyone missing: leave it approved and insert one core_action_item for the owner naming who, only if no open item exists for that revision. Skip revisions with ext.imported.
3. Add the Vercel cron entry for the scheduler (read Vercel's cron docs for our plan's limits first, and tell me the schedule you chose).
4. A partial unique index: one effective revision per document_id. A trigger refuses changes to effective, superseded and withdrawn revisions except the scheduler's and QA approver's status changes.
5. The KPIs on /documents/admin: review cycle time (median days submit to approval) and training readiness at the effective date (complete / required; "no training required" when nobody is).
6. Tests, each shown red first: a second effective revision is refused; a revision with one trainee missing stays approved with one action item after two runs; a call without CRON_SECRET or with a person's sign-in is refused; on tests/fixtures/documents-library.json the KPIs read 7 days and 8 of 9.
Push, wait for every check, and report.You will see recreated screen
- Idempotent: a job that runs every day must not add an item every day.
- The KPIs match the hand count of the seed. If they do not, fix the query, not the count.
You will see recreated screen
- Hand count of the seed: 4 + 2 + 2 of 4 + 3 + 2.
- Held, not forced: the old revision stays in use until the gate passes.
Check it worked
Every check is green; the KPIs on the preview read 7 days and 8 of 9; a held revision has exactly one action item after two scheduler runs; the database refuses a second effective revision. Then owner two approves and you merge; the deploy applies the migrations to production.
If it goes wrong
Claude Code says "done, all tests pass" and the gate test is not in the run
Say: Show me the exact command, its exit code and the last 20 lines of output, from a fresh terminal. If something could not run, say could not measure.
The scheduler uses the service-role key "to make it simpler"
Refuse. The service-role key skips every access rule, so a bug in the job could change any row. Say: Sign in as the doc_scheduler account so the matrix applies to the job too.
Training readiness shows 0 of 0 for a SPEC
A type with no training must say "no training required" and be left out of the total. A number nobody measured is worse than an honest empty state.
The cron does not run on the preview
Vercel runs cron jobs on production deployments only. Test the route on the preview by calling it as the tests do, and check the first production run in Vercel's cron page after merge.
Knowledge check
Revision 2.0 is in review while 1.0 is effective. What does a reader see?
Knowledge check
Why is the sha256 computed on the server from the stored file?
References
- eCFR: 21 CFR Part 11, sections 11.10, 11.50 and 11.70. https://www.ecfr.gov/current/title-21/chapter-I/subchapter-A/part-11
- Supabase Docs: Row Level Security. https://supabase.com/docs/guides/database/postgres/row-level-security
- Supabase Docs: Storage access control. https://supabase.com/docs/guides/storage/security/access-control
- Vercel Docs: Cron jobs. https://vercel.com/docs/cron-jobs
- PostgreSQL Documentation: Partial indexes. https://www.postgresql.org/docs/current/indexes-partial.html
Chapter 3 · Sessions 5–6
Move the records in, then switch the old tool off
Session 5 maps the old tool's export, builds an import that never re-signs history, and rehearses it on the development project with a copy IT approved. Session 6 adds controlled print, periodic review and the PDF/A archive, runs old and new side by side, imports the real library into production through the pipeline, and cancels the old subscription with the saving written down.
30 min4 stepsSessions 5 and 6Ends with the module gate
By the end of this chapter you can
- Map the old tool's export and import history as superseded revisions at their original dates, never re-signed.
- Rehearse the import on the development project with an approved copy, and check counts and fingerprints.
- Add controlled print with reconciliation, periodic review with overdue escalation, and the PDF/A archive check.
- Import into production through the pipeline, compare a side-by-side week, cut over and cancel with the saving recorded.
Never re-sign history
An imported library arrives as history: earlier revisions as superseded at their original effective dates, the current revision as effective. Signatures made in the old tool are kept as text in ext.legacy_signatures and as the old tool's own signature report, never recreated: a new signature would claim a decision made today that nobody made. Imported effective revisions create no training, or the import would assign every course at once. The doc_importer account cannot insert a signature, so the database enforces this, not a promise.
| Old tool says | Arrives as | Why |
|---|---|---|
| Earlier revision | superseded, original effective_at, superseded_at = next revision's date | The history of what was in force, and when |
| Current revision | effective, ext.imported true | Readers see it at once; no training, no events |
| Obsolete | revision withdrawn, document obsolete | Kept for the record, never in use |
| Approver name, date, meaning | Text in ext.legacy_signatures, plus the old tool's report as a file | Evidence of the old decision, not a new one |
| File | Stored once, sha256 computed while storing | Checkable for as long as you keep it |
Session 5: Map the export and build an import that runs dry first
40 minutesWhy
An import that writes as it goes leaves half a library when row 900 fails. Mapping every column first, stopping on anything unmapped, and running dry before any write means the first real run is a formality. Running it as a pipeline job, signed in as the doc_importer account, means the database refuses anything the import should never do.
Do this
Take the export yourself from the old tool's export page (CSV plus files). Keep it in a private folder outside the repository. Then give Claude Code only the column headings:
On a new branch documents/import:
1. Write docs/documents-mapping.md mapping each heading below to an M06 column (document number to doc_no, owner email to core_person, type to doc_doc_type.code, and so on), listing headings that map to nothing and what happens to them (approver names and dates go to ext.legacy_signatures).
2. Write scripts/import-documents.mjs: reads the CSV and files from the private Supabase Storage bucket imports; signs in as the doc_importer account, which only inserts; stops before writing anything if any row cannot be mapped, and lists those rows; with --dry-run writes nothing and prints counts by type and status; otherwise inserts with ext.imported true, on conflict do nothing on doc_no and on (document, major, minor), so a second run changes nothing. Earlier revisions superseded at their original dates, current revision effective, obsolete as withdrawn; no core_e_signature, doc_review_task or trn_assignment; files stored once with sha256 computed while storing; the highest imported number per prefix printed in the summary, so the administrator sets each core_number_sequence after the run; next_review_due from the CSV or the effective date plus the review period, with a pending periodic review.
3. Write .github/workflows/import-documents.yml, run by hand only (workflow_dispatch) from main, with inputs target (dev or production) and dry_run. Before writing, it computes the sha256 of the export file in the bucket and refuses unless that value and the expected counts (documents, revisions, files) are recorded in docs/imports/documents-approved.md on main. It fails on any count mismatch and prints the counts as the job summary.
4. Tests on made-up data: a second run adds nothing; an unmapped row stops the run before any write; the importer's attempt to insert a signature is refused.
Push, open a pull request titled "Documents: import", wait for every check, and report. Do not connect to any project.
The headings:
<paste the first line of the CSV only, never a data row>You will see recreated screen
- The old signatures have a home that is not a signature.
- Three refusals, each one a promise kept by the system, not by care.
Check it worked
Pull request Documents: import is green, and docs/documents-mapping.md maps every export heading or says why it is left out.
If it goes wrong
Claude Code asks for a sample of the data to test with
Give it made-up rows that follow the headings, never real ones. Real records go only through the workflow.
The script uses the service-role key
Say: Sign in as the doc_importer account so the database refuses signatures, review tasks and training for the import. With the service-role key those refusals disappear.
The old tool's revision labels are not major.minor (for example A, B, C or 03)
Agree a rule with the quality lead (A becomes 1.0, B 2.0) and write it in docs/documents-mapping.md before the dry run. Do not let the script guess.
Session 5: Rehearse on the development project with an approved copy
35 minutesWhy
The rehearsal finds the surprises (a type nobody mapped, a missing file, an owner who left) on a project where nothing depends on the result. Real records go into the development project only here, only with IT's written approval of that copy, and they are removed the same day: the Foundation rule that real data stays out of development is broken once, on purpose, and on the record.
Do this
As a person, create the doc_importer account in the development project's Authentication, give it the doc_importer role, and type its email and password, with the development project's address and publishable key, into the GitHub Actions secrets the workflow names (never into a file or Claude Code). Add the names to docs/KEYS.md.
https://github.com/acme-ops/acme-platform/settings/secrets/actions
GitHub Actions secrets: the importer's sign-in for the development project now, for production in Session 6.
Get IT's written approval to load a copy of the export into acme-platform-dev for one rehearsal, removed the same day. Documents that hold personal, injury or pay data (an incident report, a training record) are redacted or left out of the copy. Then, as a person: upload the export into the private bucket imports in the development project, and work out its fingerprint in your own terminal:
https://supabase.com/dashboard/project/tsrqponmlkjihgfedcba/storage/buckets
Development project Storage: create the private bucket imports and upload the CSV and the files.
shasum -a 256 documents-export.csvcertutil -hashfile documents-export.csv SHA256Write docs/imports/documents-approved.md on a new branch documents/import-approval: export file documents-export.csv, sha256 <paste the value>, expected counts <documents, revisions, files>, taken from the old tool on <date> by <role>, IT approval for one rehearsal on acme-platform-dev, redacted, removed the same day, given on <date> by <role>. Open a pull request titled "Documents: approve import file".Owner two approves and you merge. Then run the workflow from main: target dev, dry run first, then for real. The same day, remove the rehearsal rows (Claude Code gives you the statements by ext.imported; you run them in the development project's SQL editor) and the files in the bucket, and record the date in docs/documents-mapping.md.
https://github.com/acme-ops/acme-platform/actions/workflows/import-documents.yml
Run workflow: target dev, dry_run true. Read the summary. Then again with dry_run false.
You will see recreated screen
| In export | Imported | Skipped | |
|---|---|---|---|
| Documents | 312 | 311 | 1 (type MEMO, listed) |
| Revisions | 927 | 924 | 3 (files missing, listed) |
- The gate: only the file owner two approved can be imported.
- Every skipped row is listed with its reason. Unexplained differences mean not ready.
You will see recreated screen
- Compare with the revision screen's fingerprint, and with Verify.
Check it worked
The summary's imported plus skipped equals the export, by documents and by revisions, and every skipped row has a reason. Three files hash to the same value on your computer and on the platform. A second run adds nothing. The same day, the rehearsal rows are removed from the development project, the date is in docs/documents-mapping.md, and IT is told, in writing.
Fastest path
Fix every skipped row in the mapping or the export, not by hand in the database, and rehearse again. The production run in Session 6 should then hold no surprises.
If it goes wrong
The workflow refuses: export sha256 not approved
The file changed since you recorded its fingerprint (re-exported, opened and saved in a spreadsheet). Record the new value through a pull request, or upload the approved file again.
Owners do not match
The export uses names or old emails. Add the mapping (old email to current person) to docs/documents-mapping.md, reviewed by the quality lead, and rehearse again.
Imported revisions trigger training for hundreds of people
The scheduler is not skipping ext.imported. Stop the scheduler on the development project, and say: Imported revisions must create no distribution, training or events. Add a test.
Session 6: Controlled print, periodic review and the PDF/A archive
40 minutesWhy
Paper copies that nobody collects are how an old revision stays in use at the press. Periodic review stops documents going stale unnoticed. A PDF/A copy with a checked fingerprint means the effective file can be read and trusted in ten years. Each has a test that proves it can fail, because an archive check that has never failed has not been tested.
Do this
On a new branch documents/print-review-archive:
1. /api/documents/print: as owner or admin, stamp each page of the effective revision's PDF/A copy with CONTROLLED COPY, copy number, doc_no and revision label, and insert doc_controlled_print (next copy_no for that revision). A reader's print is stamped UNCONTROLLED COPY with the print time and writes no row. Stamp on the fly; never store the stamped file. When the scheduler supersedes a revision with unreconciled copies, it adds one action item for the admin; the admin page lists copies still out.
2. Periodic review: the owner completes the pending review with no_change (next review scheduled), revise (a new draft) or obsolete (the QA approver signs meaning approved, comment qa_approver: approved_for_withdrawal; revision withdrawn, document obsolete). The scheduler escalates a review past due once: an action item for the owner and a doc.review.overdue event; after the days set in docs/doc-rules.md, one item for the QA approver.
3. PDF/A: render a PDF/A copy of each revision as it becomes effective with LibreOffice and check it with veraPDF, as a GitHub Actions job (both free; a web host's functions rarely carry them). Store it as a core_attachment, set pdfa_attachment_id, keep both fingerprints in ext. Render once for every imported effective revision.
4. The archive check: a scheduled job re-hashes every effective source file and PDF/A copy and reports mismatches and, separately, missing copies.
5. Tests, each shown red first: copy numbers count 1, 2, 3; the overdue count on tests/fixtures/documents-library.json as of 2026-06-30 is 1 (document D); escalation runs twice and adds one item; the archive check fails on a copy with one byte changed.
Push, open a pull request titled "Documents: print, review, archive", wait for every check, and report.You will see recreated screen
- A mismatch and a missing copy are reported separately, so a missing copy is never mistaken for tampering.
- Free tools first. A paid conversion service is the other way: read its price on its own page before choosing it.
Check it worked
The pull request is green; on its preview you printed controlled copy 1 of an effective revision and saw its row on the admin page; the overdue count reads 1 on the seed.
If it goes wrong
The print route writes the stamped PDF to a folder in the project
On Vercel the project's folders are read-only and each server copy is separate, so it works on your machine and silently fails live. Say: Stamp in memory and stream the result; never write to the project folder.
The PDF/A job fails on a Word file with unusual fonts
veraPDF reports why. Ask Claude Code to show you the validator's message in plain words; usually the fix is embedding fonts in the conversion. Record any file that cannot be made valid on the admin page rather than skipping it silently.
Retention: Claude Code proposes a number of years
Do not accept a guessed period. Write in docs/doc-rules.md the period your regulator, contract or ISO 15489-1 sets, and which source set it.
Session 6: Side by side, the real import, cut over and cancel
60 minutes over a weekWhy
A week of old and new side by side, compared number by number, is what lets you switch the old tool off without a leap of faith. The real import goes into production through the same workflow you rehearsed, approved by owner two, so production is changed by the pipeline and never by a laptop. The saving is written from invoices, because that is what finance will check.
Do this
Create the doc_importer account on production too, and type its sign-in into the production secrets the workflow names. Record the production export's fingerprint and expected counts in docs/imports/documents-approved.md through a pull request owner two approves (target production, date). Upload the export to the private imports bucket in production, then run the workflow from main with target production: dry run, read it, then for real. As administrator, set each number sequence to the highest imported number plus 1, from the summary.
https://github.com/acme-ops/acme-platform/actions/workflows/import-documents.yml
Run workflow: target production, dry_run true, then false. Save the summary.
The production import is done. On a new branch documents/close-importer: remove doc_importer's rights from docs/matrix.json and regenerate with scripts/gen-policies.mjs and scripts/gen-routes.mjs; add a migration that sets the doc_importer role to NOLOGIN, applied by the deploy workflow; disable import-documents.yml; add a test that the importer can neither sign in nor insert; mark its secrets retired in docs/KEYS.md and tell me which GitHub secrets to delete. Open a pull request titled "Documents: close the importer", wait for every check, and report.Write docs/cutover.md on a new branch documents/cutover from my notes below:
1. The side-by-side week: for each of documents effective, reviews overdue, tasks waiting for a decision and people who have not acknowledged, the old tool's count (read by me), the platform's count (read it from production with a query I run, and show me the query), and the explanation of every difference.
2. The definition of done: one effective revision per document (the test name), a signature shows name, time and meaning and verifies (the test name), a new effective revision creates training for every mapped role (the test name).
3. The baseline again: minutes and copies found, on a phone, beside Session 1's.
4. The cutover date, who tells the floor, when the old tool goes read-only, who keeps its final export and where, the date after which an old-tool approval is not accepted, and the rollback plan.
5. The saving: the old bill from the invoice, minus what the module adds to services we already pay for, as arithmetic.
Use only my numbers. Open a pull request titled "Documents: cutover".
My notes:
<paste your notes here>On the cutover date, read the cancellation terms on the vendor's account page (notice period, export window), cancel, and update docs/documents-inventory.md: each place and tool replaced, retired or kept, with the date.
You will see recreated screen
| Count | Old tool | Platform | Difference |
|---|---|---|---|
| Documents effective | 311 | 311 | none |
| Reviews overdue | 6 | 7 | WI-0044 due 2026-11-01: old tool counts from the next day |
| Waiting for a decision | 4 | 4 | none |
| Not acknowledged | 19 | 19 | none |
- A difference with a reason is fine; a difference without one means not ready.
- The number Session 1 promised to move.
- Arithmetic from invoices, not estimates.
Check it worked
Production holds the imported library with counts that match the export, and the importer is NOLOGIN the same day; docs/cutover.md is on main with the week compared, the definition of done shown, the baseline repeated, the cutover date and rollback plan, and the saving from invoices; the old tool is cancelled or its end date written.
If it goes wrong
A difference in the side-by-side week has no explanation
You are not ready to cut over. Find the cause (a mapping, a rule, a timing difference) and run the week again. Cancelling first means you cannot check later.
The vendor's export window ends on cancellation
Take and store the final export before you cancel. Write where it lives and who keeps it in docs/cutover.md.
Someone approves a revision in the old tool after cutover
That approval is not accepted. The owner raises a new revision on the platform. Put the date in docs/cutover.md and tell the floor the week before.
Knowledge check
How do signatures made in the old tool arrive in the platform?
Knowledge check
Why does the import workflow check the export's sha256 against a file on main?
References
- ISO 19005-1:2005 Document management: electronic document file format for long-term preservation (PDF/A). https://www.iso.org/standard/38920.html
- ISO 15489-1:2016 Records management: concepts and principles. https://www.iso.org/standard/62542.html
- veraPDF: the open-source PDF/A validator. https://verapdf.org/
- GitHub Docs: Manually running a workflow. https://docs.github.com/en/actions/managing-workflow-runs-and-deployments/managing-workflow-runs/manually-running-a-workflow
- Supabase Docs: Storage. https://supabase.com/docs/guides/storage
Chapter 4 · 12 questions · 80% passes
Final assessment
Twelve questions across the module. Score 80% (10 of 12) to pass. Your LMS records your score and each answer; you can review the chapters and try again.
15 min12 questions≈ 15 minutesRetake allowed
Your result
CivOps AI Academy
Documents and E-Signature: Controlled Documents, Revisions and Approval
Element M06 complete · Learner
Your LMS records this completion. For the CivOps Foundation certificate, finish the Foundation Course at https://civops.io/learn.