Lesson 13 · 50 minutes
Build a governance pack for one AI system and check it with one command
- Assemble the files of the course into one governance pack for LoanScore
- Check the pack with one command that runs every checker and the cross-checks
- Prove that the check catches a broken pack
The lab folder as it stands after this lesson. Unzip it in ~/krlab.
More
The zip holds every file that the course has printed up to here. To start this lesson with the files of the earlier lessons only, take the zip of the lesson before. Type the code yourself first: you learn more.
Scenario
LoanScore goes to the approval meeting on Friday. The approver wants one folder that holds the evidence, and one command that says whether the evidence is complete and consistent. A pack that depends on a person to remember each check will fail the one time that person is away. You have the files of lessons 1 to 12. Your task is to assemble them into a pack, write the command that checks them all, and break the pack on purpose to prove that the command notices.
Recall
Lesson 10: what makes an approval of a model card stop counting?
A change of the card after the approval. The approval stores the fingerprint of the card, and the check fails when the fingerprint no longer matches. A person must approve the new text.
Lesson 7: what does the framework plan check for each function?
That at least one artefact exists as a non-empty file, that each artefact has an owner, and that a done artefact has its file.
The idea
A governance pack is the set of files that shows, for one system, that it is owned, listed, assessed, measured, explained, classified, planned for, supplied safely, documented and governed by named people. You made one file or more for each of these in the earlier lessons. The pack check runs the checker of each lesson on those files and adds cross-checks: facts that two files must agree on. Here one cross-check says that each system named in the RACI table, the classification table or the incident log must be in the inventory. Another computes the selection-rate ratio from the raw decisions and compares it with the limit that the pack states and with the ratio that the model card states, so that a number is never taken on trust. A third reads the cut-offs in the explanation records and asks who approved a group cut-off.
| Part | Files | Made in lesson | Check |
|---|---|---|---|
| Accountability | raci.csv, policy.md | 1 | raci_check, policy_check |
| Inventory | inventory.csv | 2 | inventory, and the cross-check |
| Risk register | register.csv | 3 | register |
| Fairness | decisions.csv, fairness_report.txt | 4, 5 | ratio against the limit |
| Explanations | explanations.jsonl | 5 | explain_check |
| Classification | systems.csv, aiact_rules.json | 6 | classify |
| Framework plan | rmf_plan.csv, context.md, response.md, oversight.md | 7 | plan_check |
| Incident log | incidents.csv | 7 | incident_check |
| Management system | ams_records.csv | 8 | overdue |
| Vendor and location | vendor.json, flows.csv, location_rules.json | 9 | vendor |
| Data protection | dpia.md | 9 | dpia_check |
| Model card | model_card.json, datasheet.json, approvals.jsonl | 10 | card |
| Governance body | people.csv, controls.csv, jobs.json, and the evidence files that controls.csv names | 11, 12 | people_check, controls_check |
- Evidence files → Checkers: one checker for each of 13 parts
- Evidence files → Cross-checks: do the files agree?
- pack.json → Cross-checks: the system and the limit
- Checkers → Report: ok, or a list of problems
- Cross-checks → Report: ok, or a list of problems
- Report → Approver: decides go or no-go
The check proves that the evidence is complete and consistent. It does not prove that the system is safe, fair or lawful, or that the evidence is good. It checks that a named person approved the group cut-off of lesson 4, and it cannot judge whether that approval is lawful. Those are judgements for the approver, and lesson 14 asks you to make one.
Worked example
Work in ~/krlab/ai-governance with the environment on. The pack is the lab folder itself, with the files of the earlier lessons in it.
1. Refresh the evidence that code makes
The decisions, the explanation records and the fairness report come from code. Run the commands again, so that the pack holds the current output. The two principles of lesson 12 that code proves (a noisy release and a repeat run) need fresh files too. If you joined with kr-lab.sh, run python makedata.py first: explain.py reads its loan data.
python explain.py
python mitigate.py > fairness_report.txt
python dp_count.py data/loans.csv B > dp_release.txt
sha256sum decisions.csv | cut -c1-16 > consistency.txt
python explain.py > /dev/null
sha256sum decisions.csv | cut -c1-16 >> consistency.txtincome 0.22
debt_ratio 0.12
history_years 0.07
wrote decisions.csv and explanations.jsonl, 300 decisions2. Save the pack settings
pack.json says which system the pack is about, the fairness limit that people chose (lesson 4), the person who approved the group cut-off, and the date of the check. The date is fixed, as in lesson 8. The approver is empty for now: step 4 shows why that matters. The other files of the pack were printed whole in their own lessons, and the zip of this course holds their last printing.
pack.json
{"system": "LoanScore", "fairness_threshold": 0.80, "group_cut_off_approved_by": "", "today": "2026-11-21"}3. Write the pack check
Path(__file__).parent is the folder of the script, where the rules files stay. The function run(folder) returns one entry for each part: its name and its list of problems. Each checker of the earlier lessons has a function problems that gives that list, so the pack check imports them and adds nothing new to them. inventory_gaps, selection_ratio and cut_offs feed the cross-checks. dpia_check.problems takes the system from pack.json, so the pack decides by the inventory whether it needs dpia.md. The part governance body joins the two checks of lessons 11 and 12, and gives the people check the date of the pack. jobs.json is a rules file, so it stays in the lab folder next to the script. sys.exit("text") prints the text and ends with exit code 1. A malformed cell (an empty date, a missing column) makes a checker raise ValueError, KeyError or TypeError. The main block catches these and stops with one line, not a traceback. dict.get(key, default) gives the value of a key, or the default when the key is missing. " and ".join(list) joins texts with a separator. The part fairness has three tests: the limit, the ratio that the card states, and the approval of a group cut-off.
check_pack.py
"""check_pack.py: run every check of the course on one folder, the governance pack of one system.
python3 check_pack.py [folder] (the folder defaults to the current one)
The rules files stay in the lab folder, next to this script. The exit code is 1 when anything fails.
"""
import csv
import json
import sys
from datetime import date
from pathlib import Path
import card
import classify
import controls_check
import dpia_check
import explain_check
import incident_check
import inventory
import overdue
import people_check
import plan_check
import policy_check
import raci_check
import register
import vendor
LAB = Path(__file__).parent
def selection_ratio(path):
"""The lower selection rate divided by the higher one, from the raw decisions."""
seen = {}
with open(path, newline="") as f:
for row in csv.DictReader(f):
chosen, total = seen.get(row["group"], (0, 0))
seen[row["group"]] = (chosen + int(row["approved"]), total + 1)
rates = [chosen / total for chosen, total in seen.values()]
return min(rates) / max(rates)
def cut_offs(path):
"""The different cut-offs that the explanation records show."""
with open(path) as f:
return sorted({json.loads(line)["cut"] for line in f if line.strip()})
def inventory_gaps(folder):
"""Systems that other files name but the inventory does not list."""
listed = {row["name"] for row in inventory.load(folder / "inventory.csv")}
named = {row["system"] for row in inventory.load(folder / "raci.csv")}
named |= {row["name"] for row in inventory.load(folder / "systems.csv")}
named |= {row["system"] for row in inventory.load(folder / "incidents.csv")}
return [f"{name} is named in a file but not in the inventory" for name in sorted(named - listed)]
def run(folder):
folder = Path(folder)
settings = json.loads((folder / "pack.json").read_text())
rules = json.loads((LAB / "aiact_rules.json").read_text())
places = json.loads((LAB / "location_rules.json").read_text())
vendor_record = json.loads((folder / "vendor.json").read_text())
today = date.fromisoformat(settings["today"])
ratio = selection_ratio(folder / "decisions.csv")
fairness = []
if ratio < settings["fairness_threshold"]:
fairness.append(f"selection-rate ratio {ratio:.2f} is below the limit {settings['fairness_threshold']:.2f}")
card_says = json.loads((folder / "model_card.json").read_text()).get("metrics", {}).get("selection_rate_ratio")
if card_says is not None and card_says != f"{ratio:.2f}":
fairness.append(f"the model card says ratio {card_says}, the decisions give {ratio:.2f}")
cuts = cut_offs(folder / "explanations.jsonl")
people = {row["person"] for row in inventory.load(folder / "people.csv")}
if len(cuts) > 1 and settings.get("group_cut_off_approved_by") not in people:
fairness.append(f"the decisions use the cut-offs {' and '.join(str(c) for c in cuts)}, "
"and no person in people.csv approved a group cut-off")
return [
("accountability", raci_check.problems(folder / "raci.csv") + policy_check.problems(folder / "policy.md")),
("inventory", inventory.problems(folder / "inventory.csv") + inventory_gaps(folder)),
("risk register", register.problems(folder / "register.csv")),
("fairness", fairness),
("explanations", explain_check.problems(folder / "decisions.csv", folder / "explanations.jsonl")),
("classification", classify.problems(folder / "systems.csv", rules)),
("framework plan", plan_check.problems(folder / "rmf_plan.csv", folder)),
("incident log", incident_check.problems(folder / "incidents.csv")),
("management system", overdue.problems(folder / "ams_records.csv", today)),
("vendor and location", vendor.vendor_problems(vendor_record, places) + vendor.flow_problems(folder / "flows.csv", places)),
("data protection", dpia_check.problems(folder, settings["system"])),
("model card", card.problems(folder / "model_card.json", folder / "datasheet.json", folder / "approvals.jsonl")),
("governance body", people_check.problems(folder / "people.csv", folder / "raci.csv", LAB / "jobs.json", today)
+ controls_check.problems(folder / "controls.csv", folder / "people.csv", folder / "register.csv", folder)),
]
if __name__ == "__main__":
try:
results = run(sys.argv[1] if len(sys.argv) > 1 else ".")
except FileNotFoundError as error:
sys.exit(f"missing file: {error.filename}")
except (ValueError, KeyError, TypeError) as error:
sys.exit(f"the pack check could not read a file of the pack: {type(error).__name__}: {error}")
total = 0
for part, found in results:
print(f"{part:<20}{'ok' if not found else str(len(found)) + ' problem(s)'}")
for line in found:
print(" ", line)
total += len(found)
print(f"pack: {total} problem(s)")
sys.exit(1 if total else 0)4. Run it
python check_pack.py
echo "exit code $?"accountability ok
inventory ok
risk register ok
fairness 1 problem(s)
the decisions use the cut-offs 0.36 and 0.5, and no person in people.csv approved a group cut-off
explanations ok
classification ok
framework plan ok
incident log ok
management system ok
vendor and location ok
data protection ok
model card ok
governance body ok
pack: 1 problem(s)
exit code 1Twelve parts are ok and one fails, so the exit code is 1. It finds a real gap at once. The decisions of lesson 5 use two cut-offs, 0.50 and 0.36, and the model card itself says that the group cut-off needs legal approval. Nothing in the pack says who approved it.
5. Record who approved the group cut-off
The check does not decide that the group cut-off is wrong. It asks for a name. In a company the name is the person whom your legal team names, after a written approval that the pack links to. In the lab, Hugo, the CoE lead of lesson 11, stands in. A name written only to turn the check green is worth nothing. Save pack.json again, whole, and run the check.
pack.json
{"system": "LoanScore", "fairness_threshold": 0.80, "group_cut_off_approved_by": "Hugo", "today": "2026-11-21"}grep -E "a|b" keeps the lines that hold a or b. Show only the fairness line and the total.
python check_pack.py | grep -E "fairness|pack:"fairness ok
pack: 0 problem(s)All thirteen parts are ok now, and the exit code is 0.
6. Break a copy of the pack
A check that has never failed is not proven. Copy the pack into a folder, make four changes, and run the check on the copy. The changes: raise the fairness limit to 0.85, change a word in the approved model card, remove the owner of risk R3, and delete the consistency row of controls.csv. cp *.csv *.json ... copy/ copies the files by pattern. The register copy is the original without the line of R3, plus a new line of R3 with an empty owner. grep -v keeps the lines that do not match.
mkdir copy
cp *.csv *.json *.jsonl *.md *.txt copy/
sed -i 's/0.80/0.85/' copy/pack.json
sed -i 's/Group B has a lower income on average/Group B is poorer/' copy/model_card.json
grep -v "R3,Accuracy drifts" register.csv > copy/register.csv
echo "R3,Accuracy drifts as the customer mix changes,The model is not retrained,3,4,,Monthly accuracy report on fresh outcomes,3,2" >> copy/register.csv
grep -v "^consistency" controls.csv > copy/controls.csv
python check_pack.py copy
echo "exit code $?"accountability ok
inventory ok
risk register 1 problem(s)
R3: no owner
fairness 1 problem(s)
selection-rate ratio 0.80 is below the limit 0.85
explanations ok
classification ok
framework plan ok
incident log ok
management system ok
vendor and location ok
data protection ok
model card 1 problem(s)
the card changed after its approval: approve it again
governance body 1 problem(s)
consistency: no row in the controls file
pack: 4 problem(s)
exit code 1The command finds all four, and the exit code is 1, so a build job would stop.
Your turn
Test your own pack check. Make five copies of the pack in five folders, each with one change, run check_pack.py on each and note the number of problems. There are no steps. The changes:
pack.json: the limit 0.80 becomes 0.85.explanations.jsonl: delete the third line.systems.csv: the declared class of LoanScore becomesminimal.pack.json: the date 2026-11-21 becomes 2027-06-01.model_card.json: the ratio"0.80"inmetricsbecomes"0.56".
Last, find one thing that the pack check does not test and that an approver would want to see. Write it as the sentence that you would add to the approval memo.
Check yourself
Why does the pack check compute the selection-rate ratio from the decisions and not read it from a report?
A report is a claim. The raw decisions are the evidence, and the code that computes the ratio is short enough to read. If a person edits the report, the check does not notice. If a person edits the decisions, the explanation check and the ratio notice. The ratio on the model card is also a claim, so the check compares it with the computed one. (An edit of the card also breaks its approval. That is why change 5 of the Your turn reports two problems and not one.)
The change of the date to 2027-06-01 gives ten problems and the other changes give one. Is the pack then wrong?
No. The date change makes ten reviews fall due, as the management records say. It shows what the pack will report on that day if nobody does the reviews. A pack ages. The check takes the date from the pack file, and a real run uses today's date.
Which check would you add first: one that finds more problems, or one that makes a current problem harder to hide?
The second. A check for a new kind of gap is useful, but a check that closes a way to cheat protects every existing check.
Field notes
- Keep the pack in version control with the code and the model files. A tag at each approval gives you the pack as it was.
- Keep the rules files (the AI Act rules, the region rules, the job rules, the scoring tables) apart from the pack, with owners and review dates. The pack shows evidence. The rules are a decision of the organisation.
- Make one pack for each system. A folder of its own gives it its own owner, dates and go or no-go.
- Do not let the check become the goal. People who only want a green result will edit the file that turns it red. Review the pack as a person, and sample the evidence: recompute one explanation record.
- The check says nothing about law. Give your legal and compliance people the pack and the classification table, and ask them to read the current text.