Map company controls to a framework.
Done by an agent. Checked twice.
Every framework item marked covered, partly or gap, backed by the company's own words, with each gap written up.
Real files in
- company_controls.md
A company's list of 23 security controls with status, owner, date of last evidence and old reference codes. Two are drafts, two are retired, four have old or missing evidence and two are about things outside the excerpt. 192 lines, 8 KB. - framework_excerpt.md
The Protect function from Appendix A of the Cybersecurity Framework 2.0, published in February 2024 by the United States National Institute of Standards and Technology. Trimmed to that one function, which is 5 of the framework's 22 categories and 22 of its 106 subcategories. The wording is unchanged and only the layout differs. 53 lines, 4 KB.
A mix of real public documents and sample data. Each file says which.
Three steps
- 1.Read the framework and the controls
- 2.Map every framework item
- 3.Write the map and the gaps
Claude Sonnet 5.5, 1 min 21 s. No web. It never saw the check.
Checked twice
- Passed: 22 of 22 framework items have one row in control_map.csv in the order of the excerpt, with 0 ids from outside it
- Passed: 21 of 21 control ids cited in the map are active controls in the company list, with 0 draft, retired or unknown
- Passed: 15 of 15 evidence quotes appear word for word in the text of a control cited on the same row
- Passed: 22 of 22 statuses fit the written rule: the 3 items whose controls have only old or missing evidence are not marked covered and no gap cites a control or carries a quote
- Passed: 3 of 3 counts in gaps.md equal the counts in control_map.csv
- Passed: 7 of 7 gaps are in gaps.md with the framework wording copied word for word
- Passed: 23 of 23 company controls are accounted for: 17 cited in the map and 6 of 6 others listed in gaps.md
- Passed: 7 of 7 partly covered items are listed in gaps.md and 4 of 4 draft or retired controls are named there on a line with that reason
- Passed: 21 of 21 dates and numbers in gaps.md and in the notes match the control they sit beside, the list date or the counts
Second review by Claude Opus 5.5: pass.
Then we broke a copy of the output 4 ways on purpose. The check caught 4.
- **PR.AA-04**: "Identity assertions are protected, conveyed, and verified" - Missing: No active control speaks to identity assertions, and no draft or retired control touches this item. - **PR.AA-06**: "Physical access to assets is managed, monitored, and enforced commensurate with risk" - Missing: No active control manages, monitors or enforces physical access, because the retired door-badge control CTL-05 ended on 2026-02-27 and nothing replaced it at the new site. - **PR.AT-02**: "Individuals in specialized roles are provided with awareness and training so that they possess the knowledge and skills to perform relevant tasks with cybersecurity risks in mind" - Missing: No active control trains people in specialised roles, because the role based course CTL-16 is still a draft with no evidence. - **PR.DS-10**: "The confidentiality, integrity, and availability of data-in-use are protected" - Missing: No active control speaks to protecting data in use, and no draft or retired control touches this item. - **PR.PS-06**: "Secure software development practices are integrated, and their performance is monitored throughout the software development life cycle" - Missing: No active control covers secure software development, because the secure coding standard CTL-18 is still a draft not yet agreed with the web agency. - **PR.IR-02**: "The organization’s technology assets are protected from environmental threats" - Missing: No active control speaks to environmental threats such as fire, flood or power, and no draft or retired control touches this item. - **PR.IR-04**: "Adequate resource capacity to ensure availability is maintained" - Missing: No active control speaks to resource capacity, and no draft or retired control touches this item.
How this was run
An AI agent on Claude Sonnet 5.5 was given a folder with the files below and a three-step flow, and nothing else. It had no web access and never saw the check. The check was written before the run and made stricter after it. It works the answer out again from the input files. Then Claude Opus 5.5 reviewed the result against the inputs. Some input files are real public documents and some are sample data written by Atris. Each file says which.
Run 2 of 2 on 1 December 2026. The agent took 1 min 21 s. Run 1 passed both checks and the job was run again later. Each run starts clean. Between runs the written flow was made clearer, or a check was corrected or made stricter. Nobody edits the output.
What the second review verified
- All 22 framework items have one row each, in the excerpt's order, and the counts match the CSV: covered 8, partly 7, gap 7. Every gap's wording in gaps.md matches the excerpt exactly, including the curly apostrophe in PR.IR-02.
- Each evidence quote appears word for word in a control cited on its row, for example 'Backups are kept for 35 days and cannot be changed or deleted in that time' (CTL-10) and 'switches to the second zone on its own when the first fails' (CTL-20). No draft or retired control is cited as support.
- Freshness is measured from the list date 2026-11-30, so evidence counts if dated 2025-11-30 or later. CTL-02 (2025-06-02), CTL-09 (2025-08-21) and CTL-14 (2024-12-09) are each the only control on their item and are stale, so PR.AA-02, PR.DS-02 and PR.PS-03 are correctly 'partly'.
- The six controls not cited in the map are CTL-05 (retired), CTL-16 (draft), CTL-18 (draft), CTL-21 and CTL-22 (outside this excerpt) and CTL-23 (retired). All six are listed in gaps.md with the right reason, and the CTL-05, CTL-16 and CTL-18 gap write-ups each name the control in a single sentence.
What this run does not show
- Which company control answers which framework item is a matter of judgement that only the second review reads.
- Two runs of the same job split covered and partly differently: 9 and 6 on the first run, 8 and 7 on the second.
- The check tests that quotes are real, that cited controls are active and that old evidence never counts as covered.
Would the check catch a wrong answer?
A check that cannot fail proves nothing. After the run we took a copy of the output, broke it one small way at a time and ran the check again. It caught 4 of 4. The check was made stricter after the first try at this, and the same untouched output was graded again.
Open every file
flow.md · the three steps the agent followed
# Map company controls to a framework function: it for: the IT manager who must show an auditor what the company's controls cover goal: Every item in the framework excerpt is marked covered, partly covered or a gap. Each claim rests on the company's own words and every gap is written up. ## 1. Read the framework and the controls Read input/framework_excerpt.md and input/company_controls.md. The framework excerpt lists items, each with an id and one sentence of wording. The control list gives each company control an id, a status, the date of its last evidence and its text. Old reference codes in the control list come from an earlier version of the framework. Do not copy them. Map by what the control text says. ## 2. Map every framework item For each framework item find the company controls that do what the item asks. Only controls with status `active` count. A draft or retired control never counts and is never cited as support. Evidence is fresh when its date falls in the 12 months before the date of the control list. A control with no evidence date has no fresh evidence. Give each item one status: - `covered`: active controls do all of what the item asks and at least one of them has fresh evidence. - `partly`: active controls do only part of what the item asks, or they do all of it but none of them has fresh evidence. - `gap`: no active control does any part of what the item asks. One control may support more than one item. Do not stretch a control to cover an item its text does not speak to. When in doubt between covered and partly choose partly and say what is missing. ## 3. Write the map and the gaps Write output/control_map.csv with columns framework_id,status,control_ids,evidence_quote,note. One row for every item in the excerpt, in the order of the excerpt. control_ids holds the ids of the active controls that support the item, joined with `;`. It is blank for a gap. evidence_quote is one unbroken run of at least five words copied word for word from the text of one control cited in that row. It is blank for a gap. note says in one sentence what is covered and what is missing. Write output/gaps.md for the IT manager. Start with three lines in the form `status: count` for covered, partly and gap. Then list every gap with its framework id, the framework's wording for that item copied word for word and what is missing. Say what is missing in one sentence and only one. Name any draft or retired control that touches the item inside that same sentence. Then list every partly item with what is missing. End with every company control that is not cited anywhere in the map, each with its id and the reason: draft, retired or about something outside this excerpt. ## Done looks like - Every framework item has one row and one status in control_map.csv. - Every evidence quote can be found word for word in a control cited on its row. - Every company control is either cited in the map or listed in gaps.md as not used.
input/company_controls.md · 192 lines, 8 KB
# Larkmoor Outfitters security control list List as of 2026-11-30. Kept by the IT Manager. 23 controls. Each control has a status. `active` means the control is in force. `draft` means it is written but not yet approved or in use. `retired` means it is no longer in force. "last evidence" is the date of the newest proof on file that the control was carried out. "old reference" is a code from the 2021 mapping, which used an earlier version of the framework. ### CTL-01 Joiner and leaver accounts - status: active - owner: IT Manager - last evidence: 2026-10-14 - old reference: PR.AC-1 Every account is opened from a joiner ticket raised by HR and closed within one working day of a leaver ticket. Shared accounts are not allowed. Service accounts and company devices each have a named owner and are listed in the account register. ### CTL-02 Identity check before first sign-in - status: active - owner: HR Lead - last evidence: 2025-06-02 - old reference: PR.AC-6 Before a new starter is given a password, the hiring manager confirms on a video call that the person matches the photo ID held by HR. The first password is handed over on that call and nowhere else. ### CTL-03 Sign-in with a second step - status: active - owner: IT Manager - last evidence: 2026-11-03 - old reference: PR.AC-7 All staff sign in through the company sign-in page with a password and a second step from an authenticator app or a security key. Codes sent by text message are not accepted. ### CTL-04 Quarterly access review - status: active - owner: IT Manager - last evidence: 2026-10-30 - old reference: PR.AC-4 Access to each system follows the written role matrix, so each person gets the least access the job needs. System owners review who has access every quarter and remove what is not needed. Nobody may both raise and approve the same payment. ### CTL-05 Office and stock room doors - status: retired - owner: Office Manager - last evidence: 2026-01-19 - old reference: PR.AC-2 Staff open the office and stock room doors with a badge, and the door log is reviewed each month. Retired on 2026-02-27 when the company left the Dunmore Street office. Nothing has replaced it at the new site. ### CTL-06 Security basics for all staff - status: active - owner: HR Lead - last evidence: 2026-09-18 - old reference: PR.AT-1 Every employee completes the security basics course in the first week and again each year. Practice phishing mails go out each quarter and people who click are given a short refresher. ### CTL-07 Laptop and phone encryption - status: active - owner: IT Manager - last evidence: 2026-11-10 - old reference: PR.DS-1 All company laptops and phones use full disk encryption. The device management tool reports any device where encryption is off, and that device is blocked from company mail until it is fixed. ### CTL-08 Database encryption - status: active - owner: IT Manager - last evidence: 2025-04-11 - old reference: PR.DS-1 The customer and order databases and their backups are encrypted where they are stored, with keys held in the cloud provider's key service. ### CTL-09 Encrypted connections - status: active - owner: IT Manager - last evidence: 2025-08-21 - old reference: PR.DS-2 The company websites, the shop checkout and all internal web tools accept only encrypted connections using TLS 1.2 or newer. Mail to and from the payment provider is sent over forced TLS. ### CTL-10 Nightly backups - status: active - owner: IT Manager - last evidence: 2026-11-01 - old reference: PR.DS-1 The shop database, the ledger and the shared drive are backed up every night to a second region. Backups are kept for 35 days and cannot be changed or deleted in that time. Restore tests are not on a schedule and the last one was in March 2024. ### CTL-11 Standard builds and change tickets - status: active - owner: IT Manager - last evidence: 2026-07-22 - old reference: PR.IP-1 Laptops and servers are built from a standard image with the agreed settings. Any change to the image, to a server setting or to a firewall rule needs a change ticket approved by the IT Manager before it is made. ### CTL-12 Device certificates and service keys - status: active - owner: IT Manager - last evidence: 2026-08-05 - old reference: none Company laptops and servers hold a device certificate and are refused on the office network and the VPN without one. Services talk to each other with keys kept in the secrets vault and changed every 90 days. ### CTL-13 Software updates - status: active - owner: IT Manager - last evidence: 2026-11-12 - old reference: PR.IP-12 Operating system and application updates are installed within 14 days of release, or within 3 days when the maker rates them critical. Software the maker no longer supports is removed or replaced within 90 days. ### CTL-14 Hardware life and disposal - status: active - owner: IT Manager - last evidence: 2024-12-09 - old reference: PR.DS-3 Laptops are replaced after four years and servers after six. Before any device leaves the company its drive is wiped and the wipe certificate is kept on file. ### CTL-15 Central logs - status: active - owner: IT Manager - last evidence: 2026-10-02 - old reference: PR.PT-1 Sign-in, administrator and firewall logs from every system are sent to the central log store and kept for 12 months. The IT team is alerted when a burst of failed sign-ins is seen. ### CTL-16 Training for administrators and developers - status: draft - owner: IT Manager - last evidence: none on file - old reference: PR.AT-2 People with administrator rights and people who write code for the web shop take a role based security course each year. Draft written in September 2026 and waiting for budget approval. ### CTL-17 Approved apps only - status: active - owner: IT Manager - last evidence: 2026-06-30 - old reference: PR.PT-3 Staff do not have local administrator rights on company laptops. Only apps from the company app catalogue can be installed, and anything else is blocked from running. ### CTL-18 Secure coding standard - status: draft - owner: Web Lead - last evidence: none on file - old reference: PR.IP-2 Every change to the web shop code is reviewed by a second developer and scanned for known weaknesses before release. Draft, not yet agreed with the web agency. ### CTL-19 Network separation - status: active - owner: IT Manager - last evidence: 2026-09-09 - old reference: PR.AC-5 The office network, the guest wifi, the warehouse handhelds and the shop servers sit on separate network segments. The firewall blocks all inbound traffic except to the web shop, and remote access is only through the VPN. ### CTL-20 Standby for the web shop - status: active - owner: Web Lead - last evidence: none on file - old reference: PR.PT-5 The web shop runs in two zones and switches to the second zone on its own when the first fails. A switch over drill is meant to be run twice a year. ### CTL-21 Incident response plan - status: active - owner: IT Manager - last evidence: 2026-05-20 - old reference: RS.RP-1 The incident response plan names who leads, who speaks to customers and when the owners are told. The plan is rehearsed once a year with a made up incident. ### CTL-22 Supplier security review - status: active - owner: Operations Lead - last evidence: 2026-08-28 - old reference: ID.SC-2 Before a new supplier is given customer data, IT reviews the supplier's answers to the security questions and the contract names who must report a breach and how fast. ### CTL-23 Password change every 90 days - status: retired - owner: IT Manager - last evidence: 2025-06-30 - old reference: PR.AC-1 All staff must change their password every 90 days. Retired on 2025-07-01 when the new sign-in policy came in.
input/framework_excerpt.md · 53 lines, 4 KB
# The NIST Cybersecurity Framework (CSF) 2.0: the PROTECT function Excerpt from NIST CSWP 29, February 26, 2024, Appendix A (CSF Core). Only the PROTECT function is shown: 5 categories and 22 subcategories. The wording of every line is unchanged. Only the layout differs. PROTECT (PR): Safeguards to manage the organization’s cybersecurity risks are used ## PR.AA: Identity Management, Authentication, and Access Control Access to physical and logical assets is limited to authorized users, services, and hardware and managed commensurate with the assessed risk of unauthorized access - PR.AA-01: Identities and credentials for authorized users, services, and hardware are managed by the organization - PR.AA-02: Identities are proofed and bound to credentials based on the context of interactions - PR.AA-03: Users, services, and hardware are authenticated - PR.AA-04: Identity assertions are protected, conveyed, and verified - PR.AA-05: Access permissions, entitlements, and authorizations are defined in a policy, managed, enforced, and reviewed, and incorporate the principles of least privilege and separation of duties - PR.AA-06: Physical access to assets is managed, monitored, and enforced commensurate with risk ## PR.AT: Awareness and Training The organization’s personnel are provided with cybersecurity awareness and training so that they can perform their cybersecurity-related tasks - PR.AT-01: Personnel are provided with awareness and training so that they possess the knowledge and skills to perform general tasks with cybersecurity risks in mind - PR.AT-02: Individuals in specialized roles are provided with awareness and training so that they possess the knowledge and skills to perform relevant tasks with cybersecurity risks in mind ## PR.DS: Data Security Data are managed consistent with the organization’s risk strategy to protect the confidentiality, integrity, and availability of information - PR.DS-01: The confidentiality, integrity, and availability of data-at-rest are protected - PR.DS-02: The confidentiality, integrity, and availability of data-in-transit are protected - PR.DS-10: The confidentiality, integrity, and availability of data-in-use are protected - PR.DS-11: Backups of data are created, protected, maintained, and tested ## PR.PS: Platform Security The hardware, software (e.g., firmware, operating systems, applications), and services of physical and virtual platforms are managed consistent with the organization’s risk strategy to protect their confidentiality, integrity, and availability - PR.PS-01: Configuration management practices are established and applied - PR.PS-02: Software is maintained, replaced, and removed commensurate with risk - PR.PS-03: Hardware is maintained, replaced, and removed commensurate with risk - PR.PS-04: Log records are generated and made available for continuous monitoring - PR.PS-05: Installation and execution of unauthorized software are prevented - PR.PS-06: Secure software development practices are integrated, and their performance is monitored throughout the software development life cycle ## PR.IR: Technology Infrastructure Resilience Security architectures are managed with the organization’s risk strategy to protect asset confidentiality, integrity, and availability, and organizational resilience - PR.IR-01: Networks and environments are protected from unauthorized logical access and usage - PR.IR-02: The organization’s technology assets are protected from environmental threats - PR.IR-03: Mechanisms are implemented to achieve resilience requirements in normal and adverse situations - PR.IR-04: Adequate resource capacity to ensure availability is maintained
output/control_map.csv · written by the agent, 23 lines
framework_id,status,control_ids,evidence_quote,note PR.AA-01,covered,CTL-01;CTL-12,Service accounts and company devices each have a named owner,"Joiner/leaver accounts, service accounts and devices are owned and registered (CTL-01) and device certificates and service keys are managed (CTL-12), both with fresh evidence." PR.AA-02,partly,CTL-02,the hiring manager confirms on a video call,"New starters are matched to photo ID before their first password (CTL-02), but its last evidence is 2025-06-02 so none is fresh, and it speaks only to new starters, not to services or hardware." PR.AA-03,covered,CTL-03;CTL-12,a password and a second step from an authenticator app or a security key,"Users sign in with a second step (CTL-03) and devices and services authenticate with certificates and keys (CTL-12), both with fresh evidence." PR.AA-04,gap,,,"No active control speaks to protecting, conveying or verifying identity assertions." PR.AA-05,covered,CTL-04,System owners review who has access every quarter and remove what is not needed,"A written role matrix, least access, quarterly review and payment separation of duties are all stated (CTL-04) with evidence from 2026-10-30." PR.AA-06,gap,,,No active control manages physical access; the door control CTL-05 is retired and nothing replaced it at the new site. PR.AT-01,covered,CTL-06,Every employee completes the security basics course in the first week,"Yearly security basics course plus quarterly phishing practice for all employees (CTL-06), evidence 2026-09-18." PR.AT-02,gap,,,No active control trains people in specialised roles; the role based course CTL-16 is only a draft. PR.DS-01,partly,CTL-07;CTL-08,All company laptops and phones use full disk encryption,"Laptops and phones (CTL-07, fresh) and customer/order databases and their backups (CTL-08, evidence 2025-04-11) are encrypted, but the ledger and shared drive are not stated as encrypted where stored." PR.DS-02,partly,CTL-09,accept only encrypted connections using TLS 1.2 or newer,"TLS is required for websites, checkout, internal web tools and payment-provider mail (CTL-09), but its last evidence is 2025-08-21 so none is fresh, and other traffic (wifi, handhelds) is not addressed." PR.DS-10,gap,,,No active control speaks to protecting data while it is in use. PR.DS-11,partly,CTL-10;CTL-08,Backups are kept for 35 days and cannot be changed or deleted in that time,"Nightly, second-region, tamper-proof backups are made and kept (CTL-10, fresh) and the database backups are encrypted (CTL-08), but restore tests are unscheduled and the last was in March 2024." PR.PS-01,covered,CTL-11,Laptops and servers are built from a standard image with the agreed settings,"Standard builds and approved change tickets for image, server and firewall changes (CTL-11), evidence 2026-07-22." PR.PS-02,covered,CTL-13,Software the maker no longer supports is removed or replaced within 90 days,"Patch deadlines and removal of unsupported software are set (CTL-13), evidence 2026-11-12." PR.PS-03,partly,CTL-14,Laptops are replaced after four years and servers after six,"Replacement ages and wiping before disposal are set (CTL-14), but its last evidence is 2024-12-09 so none is fresh, and hardware maintenance is not addressed." PR.PS-04,covered,CTL-15,are sent to the central log store and kept for 12 months,"Sign-in, administrator and firewall logs go to a central store for 12 months with failed-sign-in alerts (CTL-15), evidence 2026-10-02." PR.PS-05,partly,CTL-17,Only apps from the company app catalogue can be installed,"Unapproved apps are blocked on company laptops (CTL-17, fresh), but servers are not mentioned." PR.PS-06,gap,,,No active control covers secure software development; the secure coding standard CTL-18 is only a draft. PR.IR-01,covered,CTL-19;CTL-12,The firewall blocks all inbound traffic except to the web shop,"Separate network segments, a default-deny inbound firewall and VPN-only remote access (CTL-19) plus device certificates required on the network and VPN (CTL-12), both fresh." PR.IR-02,gap,,,No active control speaks to protecting technology assets from environmental threats. PR.IR-03,partly,CTL-20;CTL-10,switches to the second zone on its own when the first fails,"Automatic web shop failover (CTL-20) and second-region backups (CTL-10) exist, but CTL-20 has no evidence on file, no drill is recorded, and restores are untested." PR.IR-04,gap,,,No active control speaks to keeping adequate resource capacity.
output/gaps.md · written by the agent, 41 lines
covered: 8 partly: 7 gap: 7 Control list dated 2026-11-30; evidence counts as fresh if dated 2025-11-30 or later. ## Gaps - **PR.AA-04**: "Identity assertions are protected, conveyed, and verified" - Missing: No active control speaks to identity assertions, and no draft or retired control touches this item. - **PR.AA-06**: "Physical access to assets is managed, monitored, and enforced commensurate with risk" - Missing: No active control manages, monitors or enforces physical access, because the retired door-badge control CTL-05 ended on 2026-02-27 and nothing replaced it at the new site. - **PR.AT-02**: "Individuals in specialized roles are provided with awareness and training so that they possess the knowledge and skills to perform relevant tasks with cybersecurity risks in mind" - Missing: No active control trains people in specialised roles, because the role based course CTL-16 is still a draft with no evidence. - **PR.DS-10**: "The confidentiality, integrity, and availability of data-in-use are protected" - Missing: No active control speaks to protecting data in use, and no draft or retired control touches this item. - **PR.PS-06**: "Secure software development practices are integrated, and their performance is monitored throughout the software development life cycle" - Missing: No active control covers secure software development, because the secure coding standard CTL-18 is still a draft not yet agreed with the web agency. - **PR.IR-02**: "The organization’s technology assets are protected from environmental threats" - Missing: No active control speaks to environmental threats such as fire, flood or power, and no draft or retired control touches this item. - **PR.IR-04**: "Adequate resource capacity to ensure availability is maintained" - Missing: No active control speaks to resource capacity, and no draft or retired control touches this item. ## Partly covered - **PR.AA-02** (CTL-02): New starters are matched to photo ID before their first password (CTL-02), but its last evidence is 2025-06-02 so none is fresh, and it speaks only to new starters, not to services or hardware. - **PR.DS-01** (CTL-07;CTL-08): Laptops and phones (CTL-07, fresh) and customer/order databases and their backups (CTL-08, evidence 2025-04-11) are encrypted, but the ledger and shared drive are not stated as encrypted where stored. - **PR.DS-02** (CTL-09): TLS is required for websites, checkout, internal web tools and payment-provider mail (CTL-09), but its last evidence is 2025-08-21 so none is fresh, and other traffic (wifi, handhelds) is not addressed. - **PR.DS-11** (CTL-10;CTL-08): Nightly, second-region, tamper-proof backups are made and kept (CTL-10, fresh) and the database backups are encrypted (CTL-08), but restore tests are unscheduled and the last was in March 2024. - **PR.PS-03** (CTL-14): Replacement ages and wiping before disposal are set (CTL-14), but its last evidence is 2024-12-09 so none is fresh, and hardware maintenance is not addressed. - **PR.PS-05** (CTL-17): Unapproved apps are blocked on company laptops (CTL-17, fresh), but servers are not mentioned. - **PR.IR-03** (CTL-20;CTL-10): Automatic web shop failover (CTL-20) and second-region backups (CTL-10) exist, but CTL-20 has no evidence on file, no drill is recorded, and restores are untested. ## Controls not cited in the map - CTL-05: retired (door badges, ended 2026-02-27). - CTL-16: draft (role based training, waiting for budget approval). - CTL-18: draft (secure coding standard, not yet agreed). - CTL-21: about something outside this excerpt (incident response plan). - CTL-22: about something outside this excerpt (supplier security review). - CTL-23: retired (90-day password change, ended 2025-07-01).
check.py · the check, written before the run
"""Verifies the control map against the framework excerpt and the company's control list."""
import csv, re, sys
from datetime import date, timedelta
from pathlib import Path
NUM = re.compile(r"(?<![\w.-])\d(?:[\d,]*\d)?(?:\.\d+)?(?![\w-])")
DAY = re.compile(r"\d{4}-\d{2}-\d{2}")
def norm(s):
s = (s or "").replace("’", "'").replace("‘", "'").replace("“", '"').replace("”", '"')
return re.sub(r"\s+", " ", s).strip()
def load(root):
inp = root / "input"
items = dict(re.findall(r"^- ([A-Z]{2}\.[A-Z]{2}-\d\d): (.+)$", (inp / "framework_excerpt.md").read_text(), re.M))
raw = (inp / "company_controls.md").read_text()
as_of = date.fromisoformat(re.search(r"List as of (\d{4}-\d{2}-\d{2})", raw).group(1))
controls = {}
for part in re.split(r"^### ", raw, flags=re.M)[1:]:
head, _, body = part.partition("\n")
cid = head.split()[0]
fields = dict(re.findall(r"^- ([a-z ]+): (.+)$", body, re.M))
text = norm(" ".join(ln for ln in body.splitlines() if ln.strip() and not ln.startswith("- ")))
ev = fields.get("last evidence", "").strip()
fresh = bool(re.fullmatch(r"\d{4}-\d{2}-\d{2}", ev)) and as_of - timedelta(days=365) <= date.fromisoformat(ev) <= as_of
controls[cid] = {"status": fields["status"].strip(), "fresh": fresh, "text": text, "dates": set(DAY.findall(body)),
"nums": {float(x) for x in re.findall(r"(?<![\w.-])\d+(?:\.\d+)?(?![\w-])", DAY.sub(" ", body))}}
try: cutoff = as_of.replace(year=as_of.year - 1)
except ValueError: cutoff = as_of - timedelta(days=365)
controls["_list"] = {"dates": {as_of.isoformat(), cutoff.isoformat(), (as_of - timedelta(days=365)).isoformat()}}
return items, controls
def main():
root = Path(sys.argv[1]); ok = True
def say(passed, text):
nonlocal ok
ok = ok and passed; print(("PASS " if passed else "FAIL ") + text)
items, controls = load(root)
general = controls.pop("_list")
path = root / "output/control_map.csv"
if not path.exists():
say(False, "output/control_map.csv was not written"); sys.exit(1)
with path.open(newline="") as fh:
got = [{k: (v or "").strip() for k, v in r.items() if k} for r in csv.DictReader(fh)]
ids = [r.get("framework_id", "") for r in got]
n = len(items)
say(ids == list(items), f"{len(set(ids) & set(items))} of {n} framework items have one row in control_map.csv in the order of the excerpt, with {len([i for i in ids if i not in items])} ids from outside it")
cited_rows = [(r, re.findall(r"CTL-\d+", r.get("control_ids", ""))) for r in got]
cited = [c for _, cs in cited_rows for c in cs]
good = sum(1 for c in cited if controls.get(c, {}).get("status") == "active")
say(bool(cited) and good == len(cited), f"{good} of {len(cited)} control ids cited in the map are active controls in the company list, with {len(cited) - good} draft, retired or unknown")
backed = [(r, cs) for r, cs in cited_rows if r.get("status", "").lower() != "gap"]
q_ok = 0
for r, cs in backed:
q = norm(r.get("evidence_quote", "")).strip('"\'').rstrip(".")
if len(q.split()) >= 5 and any(q in controls[c]["text"] for c in cs if c in controls): q_ok += 1
say(bool(backed) and q_ok == len(backed), f"{q_ok} of {len(backed)} evidence quotes appear word for word in the text of a control cited on the same row")
def allowed(r, cs):
act = [c for c in cs if controls.get(c, {}).get("status") == "active"]
st = r.get("status", "").lower()
if st == "gap": return not cs and not r.get("evidence_quote", "") and not r.get("control_ids", "")
if st == "partly": return bool(act)
if st == "covered": return any(controls[c]["fresh"] for c in act)
return False
a_ok = sum(1 for r, cs in cited_rows if allowed(r, cs))
stale_only = sum(1 for r, cs in cited_rows if cs and not any(controls.get(c, {}).get("fresh") for c in cs))
say(len(got) == n and a_ok == n, f"{a_ok} of {n} statuses fit the written rule: the {stale_only} items whose controls have only old or missing evidence are not marked covered and no gap cites a control or carries a quote")
gaps_md = norm((root / "output/gaps.md").read_text()) if (root / "output/gaps.md").exists() else ""
tally = {s: sum(1 for r in got if r.get("status", "").lower() == s) for s in ("covered", "partly", "gap")}
c_ok = 0
for name, val in tally.items():
m = re.search(r"(?<![a-z_])" + name + r"[`*\s]*:[`*\s]*(\d+)", gaps_md)
if m and int(m.group(1)) == val: c_ok += 1
say(c_ok == 3, f"{c_ok} of 3 counts in gaps.md equal the counts in control_map.csv")
gaps = [r["framework_id"] for r in got if r.get("status", "").lower() == "gap" and r.get("framework_id") in items]
g_ok = sum(1 for g in gaps if g in gaps_md and norm(items[g]) in gaps_md)
say(bool(gaps) and g_ok == len(gaps), f"{g_ok} of {len(gaps)} gaps are in gaps.md with the framework wording copied word for word")
unused = [c for c in controls if c not in cited]
u_ok = sum(1 for c in unused if re.search(c + r"(?!\d)", gaps_md))
say(u_ok == len(unused), f"{len(controls) - len(unused) + u_ok} of {len(controls)} company controls are accounted for: {len(controls) - len(unused)} cited in the map and {u_ok} of {len(unused)} others listed in gaps.md")
raw = (root / "output/gaps.md").read_text() if (root / "output/gaps.md").exists() else ""
lines = raw.splitlines()
partly = [r["framework_id"] for r in got if r.get("status", "").lower() == "partly"]
p_ok = sum(1 for f in partly if re.search(re.escape(f) + r"(?!\d)", raw))
off = [c for c, v in controls.items() if v["status"] in ("draft", "retired")]
o_ok = sum(1 for c in off if any(re.search(c + r"(?!\d)", ln) and controls[c]["status"] in ln.lower() for ln in lines))
say(p_ok == len(partly) and o_ok == len(off), f"{p_ok} of {len(partly)} partly covered items are listed in gaps.md and {o_ok} of {len(off)} draft or retired controls are named there on a line with that reason")
tally_all = {float(v) for v in tally.values()} | {float(n), float(len(controls)), float(len(unused)), float(len(controls) - len(unused)), 12.0, 365.0}
seen = bad = 0
def judge(text, row_controls):
nonlocal seen, bad
named = [c for c in re.findall(r"CTL-\d+", text) if c in controls] + row_controls
days = set(general["dates"]); nums = set(tally_all)
for c in named: days |= controls[c]["dates"]; nums |= controls[c]["nums"]
if not named: nums = set(tally_all)
for d in DAY.findall(text):
seen += 1; bad += d not in days
bare = DAY.sub(" ", text)
for fid in items: bare = bare.replace(fid, " ")
for m in NUM.finditer(re.sub(r"CTL-\d+", " ", bare)):
if len(m.group(0)) >= 2:
seen += 1; bad += float(m.group(0).replace(",", "")) not in nums
for ln in lines: judge(ln, [])
for r, cs in cited_rows: judge(r.get("note", ""), [c for c in cs if c in controls])
say(bad == 0, f"{seen - bad} of {seen} dates and numbers in gaps.md and in the notes match the control they sit beside, the list date or the counts")
sys.exit(0 if ok else 1)
if __name__ == "__main__":
main()
company_controls.md: sample data written by Atris. Fingerprint e22e6ad7e373.
framework_excerpt.md: public document. Fingerprint 1ec85c0c1d01.
control_map.csv: written by the agent. Fingerprint 0b2ac86dc5ca.
gaps.md: written by the agent. Fingerprint 5032373f427a.