Courses3 levels
Level 1 · Foundations11 courses
Level 2 · Core5 courses
Level 3 · Advanced5 courses
Labs8 topics
Library Practice exams AI Range Pricing Start free

Lesson 09 · 40 minutes

Govern your knowledge base with a catalogue and a checker

After this lesson you can
  • Keep a data catalogue as a CSV file with an owner, a review cycle and a retention period for each document
  • Run a checker that reports the gaps of a catalogue and exits with code 1
  • Apply a written rule for adding a new source and test a proposal against it
Lab files of this lesson (45)

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

Marlowe Outdoor has a working, controlled assistant. Six months from now, nobody will remember who owns the finance pages, when anyone last read the returns policy, or why the helpdesk is a source. "Technology controls do not last without ownership," says the auditor. "I want a list of what is in the knowledge base, who answers for each item, and a program that tells me where the list is wrong." You build the catalogue and the checker.

Recall

Lesson 8: which stage owns the deletion of a document from the index, and what keeps it honest?

The indexing stage owns it, with a rebuild on every delete. A test (and a nightly reconciliation of the ids in the source with the ids in the index) keeps it honest, because a deletion bug comes back when someone changes the pipeline.

Lesson 3: what are the three fields of provenance, and where does the list of allowed sources sit?

The source, the owner and the date. The allowed sources are the set SOURCES in provenance.py. This lesson gives that set a written rule: how a new name gets into it.

The idea

Knowledge governance is the set of rules and records that keep a knowledge base accurate, owned and lawful over time. The controls of lessons 3 to 8 are code. Governance is what makes people keep them true. The NIST AI Risk Management Framework (AI 100-1) puts this under its Govern function: roles, accountability and policy come first, and the technical work follows from them.

Four things make the base governable.

ItemWhat it isWhy it matters
OwnerA named team that answers for a document or a sourceWhen the text is wrong or leaks, someone must fix it.
Review cycleThe most days allowed between two reviewsAn old policy is as risky as a poisoned one.
RetentionHow long the document may stayOld data has risk and little value (lesson 6).
Rule for a new sourceThe checks that a source must pass before it feeds the indexEvery source is a new writer (lesson 1).

A data catalogue is a table that lists each document or source with those facts. Keep it as a plain CSV file in version control: a pull request shows who changed what. The checker compares the catalogue with the real knowledge base and reports each gap, a place where the record and the facts differ or where a fact is missing.

How a new source gets in
ProposalRule checkSecond personCatalogueAllowed sourcesthe checker reports gapsa reviewer who is not the ownera row for each documentone line in provenance.pyProposalRule checkSecond personCatalogueAllowed sources1234
  1. Proposal → Rule check: the checker reports gaps
  2. Rule check → Second person: a reviewer who is not the owner
  3. Second person → Catalogue: a row for each document
  4. Catalogue → Allowed sources: one line in provenance.py

Worked example

1. Save the catalogue

Save catalogue-start.csv. CSV means comma-separated values: the first line holds the column names, and each next line is a document. It has the twelve documents of kb.json and some errors that are typical after a few months: a missing owner, an unknown source, a level, a source and an owner that disagree with the knowledge base, a review that is overdue, a page without a row and a row without a page.

catalogue-start.csv

id,title,source,owner,level,reviewed,review_days,retention_days
pub-returns,Returns,shop-wiki,web-team,public,2026-09-01,180,730
pub-shipping,Shipping,shop-wiki,web-team,public,2026-09-01,180,730
pub-warranty,Warranty,gdrive,web-team,public,2026-08-15,180,730
pub-hours,Opening hours,shop-wiki,web-team,public,2025-04-01,365,730
stf-holiday,Holiday,hr-share,hr,staff,2026-06-10,365,1095
stf-vpn,VPN,shop-wiki,,staff,2026-06-03,180,365
stf-discount,Staff discount,hr-share,hr,staff,2026-02-18,365,1095
stf-old-rota,Old rota,hr-share,hr,staff,2025-01-10,365,365
fin-salary,Salary bands,finance-share,finance,finance,2026-03-01,365,2555
fin-q3,Q3 results,finance-share,finance,staff,2026-10-28,90,2555
fin-supplier,Supplier prices,finance-share,finance,finance,2026-04-22,180,
fin-payroll,Payroll,finance-share,finance,finance,2026-02-27,365,2555
One row of the catalogue, fin-q3
fin-q3idQ3 resultstitlefinance-sharesourcefinanceownerstafflevel: wrong, must be finance2026-10-28last review90days between reviews2555days to keep itfin-q3idQ3 resultstitlefinance-sharesourcefinanceownerstafflevel: wrong, must be finance2026-10-28last review90days between reviews2555days to keep it

2. Write the checker

Save govcheck.py. csv.DictReader reads a CSV file and gives each row as a dictionary with the column names as keys. timedelta is a length of time, so reviewed + timedelta(days=review_days) is the date by which the next review is due. For each document it compares the level, the source and the owner of the catalogue with those of the knowledge base. The checker takes "today" as an argument: a check that depends on the real date gives other results tomorrow. It has two modes: catalogue for the table and source for a proposal.

govcheck.py

"""govcheck.py: report the gaps in the governance of a knowledge base.

    python3 govcheck.py catalogue catalogue.csv kb.json [YYYY-MM-DD]     gaps in the data catalogue
    python3 govcheck.py source proposal.json                              gaps in a proposal for a new source

The date is "today" (default: the real date). The exit code is 1 when there is any gap.
"""
import csv
import json
import sys
from datetime import date, timedelta

from access import LEVEL
from provenance import SOURCES


def catalogue_gaps(rows, chunks, today):
    gaps = []
    by_id = {r["id"]: r for r in rows}
    for c in chunks:
        if c["id"] not in by_id:
            gaps.append(f"{c['id']}: in the knowledge base, not in the catalogue")
    for r in rows:
        who = r["id"]
        chunk = next((c for c in chunks if c["id"] == who), None)
        if chunk is None:
            gaps.append(f"{who}: in the catalogue, not in the knowledge base")
        else:
            for field in ("level", "source", "owner"):
                if chunk[field] != r[field]:
                    gaps.append(f"{who}: {field}: catalogue says {r[field] or 'nothing'}, the knowledge base says {chunk[field]}")
        if not r["owner"]:
            gaps.append(f"{who}: no owner")
        if r["source"] not in SOURCES:
            gaps.append(f"{who}: unknown source {r['source']}")
        if r["level"] not in LEVEL:
            gaps.append(f"{who}: unknown level {r['level']}")
        if not r["retention_days"]:
            gaps.append(f"{who}: no retention period")
        if date.fromisoformat(r["reviewed"]) + timedelta(days=int(r["review_days"])) < today:
            gaps.append(f"{who}: review overdue")
    return gaps


def source_gaps(p):
    """The rule for a new source: an owner, a level, a review cycle of at most a year, a retention period,
    a reviewer who is not the owner, and a check for personal data."""
    gaps = []
    if not p.get("owner"):
        gaps.append("no owner")
    if p.get("level") not in LEVEL:
        gaps.append("no valid level")
    if not 0 < p.get("review_days", 0) <= 365:
        gaps.append("review cycle must be 1 to 365 days")
    if not p.get("retention_days"):
        gaps.append("no retention period")
    if not p.get("reviewer") or p.get("reviewer") == p.get("owner"):
        gaps.append("the reviewer must be a second person")
    if p.get("pii_checked") is not True:
        gaps.append("not checked for personal data")
    return gaps


if __name__ == "__main__":
    if sys.argv[1] == "catalogue":
        today = date.fromisoformat(sys.argv[4]) if len(sys.argv) > 4 else date.today()
        gaps = catalogue_gaps(list(csv.DictReader(open(sys.argv[2]))), json.load(open(sys.argv[3])), today)
    else:
        gaps = source_gaps(json.load(open(sys.argv[2])))
    for g in gaps:
        print("GAP", g)
    print(f"gaps: {len(gaps)}")
    sys.exit(1 if gaps else 0)

3. Find the gaps

python3 govcheck.py catalogue catalogue-start.csv kb.json 2026-11-21
echo "exit code $?"
GAP stf-expenses: in the knowledge base, not in the catalogue
GAP pub-warranty: source: catalogue says gdrive, the knowledge base says shop-wiki
GAP pub-warranty: unknown source gdrive
GAP pub-hours: review overdue
GAP stf-vpn: owner: catalogue says nothing, the knowledge base says it
GAP stf-vpn: no owner
GAP stf-old-rota: in the catalogue, not in the knowledge base
GAP stf-old-rota: review overdue
GAP fin-q3: level: catalogue says staff, the knowledge base says finance
GAP fin-supplier: no retention period
GAP fin-supplier: review overdue
gaps: 11
exit code 1

The checker found eleven gaps in seven documents. Two of them are the kind that causes harm: the finance results are catalogued as staff, and a page of the knowledge base has no owner row at all.

4. Fix the catalogue

Copy catalogue-start.csv to catalogue.csv. Each fix is a decision of a person and not a formality. Make these changes in catalogue.csv.

  • stf-expenses: add a row. You are the owner of this lab, so you review it now: reviewed 2026-11-21.
  • pub-warranty: the knowledge base says shop-wiki, so the catalogue was wrong. Correct the source.
  • pub-hours, fin-supplier: review the page, then set reviewed to 2026-11-21.
  • stf-vpn: the owner is it, as in kb.json.
  • stf-old-rota: no page exists any more. Delete the row.
  • fin-q3: the knowledge base says finance. A wrong level is the dangerous direction, so correct the catalogue and check why it was wrong.
  • fin-supplier: add a retention period of 2555 days.

Here is the finished file.

The finished file: catalogue.csv

catalogue.csv

id,title,source,owner,level,reviewed,review_days,retention_days
pub-returns,Returns,shop-wiki,web-team,public,2026-09-01,180,730
pub-shipping,Shipping,shop-wiki,web-team,public,2026-09-01,180,730
pub-warranty,Warranty,shop-wiki,web-team,public,2026-08-15,180,730
pub-hours,Opening hours,shop-wiki,web-team,public,2026-11-21,365,730
stf-holiday,Holiday,hr-share,hr,staff,2026-06-10,365,1095
stf-expenses,Expenses,hr-share,hr,staff,2026-11-21,180,1095
stf-vpn,VPN,shop-wiki,it,staff,2026-06-03,180,365
stf-discount,Staff discount,hr-share,hr,staff,2026-02-18,365,1095
fin-salary,Salary bands,finance-share,finance,finance,2026-03-01,365,2555
fin-q3,Q3 results,finance-share,finance,finance,2026-10-28,90,2555
fin-supplier,Supplier prices,finance-share,finance,finance,2026-11-21,180,2555
fin-payroll,Payroll,finance-share,finance,finance,2026-02-27,365,2555
python3 govcheck.py catalogue catalogue.csv kb.json 2026-11-21
echo "exit code $?"
gaps: 0
exit code 0

Put this command in the build. A new page without a row, or a review that passes its date, then stops the build.

5. Test a proposal for a new source

The sales team wants to add a customer export as a source. The rule of source_gaps has six parts: an owner, a valid level, a review cycle of 1 to 365 days, a retention period, a reviewer who is a different person from the owner, and a check for personal data. Save proposal.json.

proposal.json

{"name": "crm-export", "owner": "sales", "level": "staff", "review_days": 400, "retention_days": 0, "reviewer": "sales", "pii_checked": false}
The proposal, proposal.json
crm-exportnamesalesownerstafflevel400cycle: 365 at most0no retentionsalesreviewer is the ownerfalseno personal-data checkcrm-exportnamesalesownerstafflevel400cycle: 365 at most0no retentionsalesreviewer is the ownerfalseno personal-data check
python3 govcheck.py source proposal.json
echo "exit code $?"
GAP review cycle must be 1 to 365 days
GAP no retention period
GAP the reviewer must be a second person
GAP not checked for personal data
gaps: 4
exit code 1

Only a proposal with no gap may become a line in the set SOURCES of provenance.py. That change goes through review like any code change, so the list of writers of lesson 1 stays short and known.

Your turn

Finance asks for a stricter rule: a source of level finance needs a review cycle of at most 90 days. Save the file proposal-fin.json and run it against the checker as it is. Then add the rule to source_gaps, with the reason text finance sources need a review cycle of 90 days or less, and run it again. Last, fix proposal.json so that the checker passes it with exit code 0, and write in notes-09.txt what you changed and who you asked, as the reviewer, to read it. The page does not check the notes.

proposal-fin.json

{"name": "budget-export", "owner": "finance", "level": "finance", "review_days": 180, "retention_days": 1095, "reviewer": "hr", "pii_checked": true}

Check yourself

The catalogue said `fin-q3` was `staff`, and the knowledge base said `finance`. Which of the two is safer to trust until a person decides?

The higher level, finance. Treat a disagreement as the stricter value until it is resolved, because the cost of hiding a document for a day is lower than the cost of showing it. The checker reports the gap so that a person decides.

Why is the source rule written as code and not only as a policy document?

A policy that nobody runs is forgotten. As code, the rule gives the same answer to every proposal, it shows the reason for each refusal, and it fails a build. A person still decides, but the rule removes the easy mistakes.

Why must the reviewer of a new source be a second person?

The owner wants the source in. The reviewer checks the risk. If one person does both, nobody checks. The rule from lesson 3 (one party writes, another approves) holds here too.

What does the catalogue not tell you?

Whether the content is true, and whether the text of a page changed since the review. The checker reads only the records. Lesson 3's hashes cover changes of text, level, source and owner, and a person must still read the page at each review.

Field notes

  • Give each source one owner who is a team and not a person, so that the owner does not leave with a job. Put the contact in the catalogue.
  • Set review cycles by risk: short for policies and prices that change, longer for stable text. An overdue review should lower trust: a service can mark old answers with the date of the source.
  • Keep the catalogue, the allowed sources and the approvals in version control with required review. The history is your audit trail when someone asks who allowed a source and when.
  • Add the legal basis to the catalogue for any source with personal data, and the contact of the privacy lead. Retention, access and deletion requests all start from that record.
  • Make a short offboarding rule: when a source is retired, remove its row, its chunks, its index files and its cache entries, and run the checker. Lesson 8 covers the deletion.