#!/usr/bin/env python3"""Checks the AIM 7 example models in this directory. python3 examples/check.py [dir ...] check the examples (default: the five whole models) python3 examples/check.py --self-test break the examples in memory and expect each errorIt reads `aim/**/*.aim` of an example and checks what AIM 7 adds below the facets: the Schemaof every Record (types, `key`, `rough`, `unit`), stated rows, `### Period`, `### Replaces`,`### Complete`, a requirement's strength, precedence and source, and every Entries file withits values, texts, typed links, origin trailers, files and fingerprints. It does not check thebehavioral graph (edges and the facets other than Record). Python 3, standard library only."""import hashlibimport jsonimport osimport reimport sysfrom datetime import date, datetimefrom decimal import Decimal, InvalidOperationfrom urllib.parse import unquoteID = r'[A-Za-z0-9][A-Za-z0-9_-]*'NAME = r'[A-Za-z][A-Za-z0-9_]*'INTENT = r'[a-z][a-z0-9_]*(?:\.[a-z][a-z0-9_]*)*'MODEL = r'(?:[a-z][a-z0-9-]*/)?'RECORD = INTENT + r'#Record:' + NAMEROW_ADDRESS = re.compile(r'(' + MODEL + RECORD + r')\[(.+)\]')REQ_ADDRESS = re.compile(r'(' + INTENT + r')#Requirements\[(.+)\]')FACET_ADDRESS = re.compile(r'(' + INTENT + r')#(' + NAME + r'):(' + NAME + r')')LINK = re.compile(r'\[(.*)\]\(aim:([^)]+)\)')TRAILER = re.compile(r'(?:^|[ \t])— from(?=:|[ \t]*\[)')AT = re.compile(r'\s+at\s+(#' + ID + r'|"(?:[^"\\]|\\.)*"|page \d+|\d{1,2}:\d{2}(?::\d{2})?)')PROPOSED = re.compile(r'proposed(?: by (\S(?:.*\S)?), (\d{4}-\d{2}-\d{2}))?')BARE = re.compile(r'[A-Za-z0-9._-]+')NUMBER = re.compile(r'-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+-]?\d+)?')DATETIME = re.compile(r'\d{4}-\d\d-\d\dT\d\d:\d\d(?::\d\d(?:\.\d+)?)?(?:Z|[+-]\d\d:\d\d)')ROUGH = re.compile(r'(?:\d{4}-\d\d-\d\d|\d{4}-\d\d|\d{4}|\d{1,3}X{1,3})[~?]?')DURATION = re.compile(r'(\d+) (minutes|hours|days|business-days|weeks|months|years)')POSITION = re.compile(r'(-?\d+(?:\.\d+)?),\s*(-?\d+(?:\.\d+)?)')FINGERPRINT = re.compile(r'([a-z0-9]+):([0-9a-f]+)')SCALARS = {'string', 'number', 'integer', 'decimal', 'boolean', 'date', 'datetime', 'email', 'url', 'phone', 'file', 'duration', 'position'}FACETS = {'Record', 'Operation', 'Process', 'Persona', 'View', 'Event', 'Trigger', 'Capability', 'Style', 'State', 'Knowledge', 'Organisation', 'Project', 'Software', 'Service', 'Output'}EXAMPLES = ['diary', 'board', 'scheduling', 'claims', 'incidents']class Field: def __init__(self, name, line): self.name, self.line = name, line self.kind = 'scalar' # scalar, enum, ref, reflist, modelref, fingerprint, other self.scalar = 'string' self.values = [] # enum values self.target = None # (Record address, field) of a ref or a reference list self.arg = None # modelref type, or the file field a fingerprint names self.mods = set() self.min = self.max = self.default = None self.units = []class Record: def __init__(self, intent, name, path, line): self.intent, self.name, self.path, self.line = intent, name, path, line self.address = f'{intent}#Record:{name}' self.fields = {} self.key = None self.rows = {} # typed key -> Row, stated rows and entries alike self.stated = False # has a ### Rows block self.entries = False # has a list or appears in a document self.list_path = None self.period = None # (start, end, one at a time, per field) self.replaces = None self.immutable = set()class Row: def __init__(self, record, key, keytext, path, line, entry): self.record, self.key, self.keytext, self.path, self.line, self.entry = record, key, keytext, path, line, entry self.address = f'{record.address}[{keytext}]' self.values = {} # field -> (value, line, origin) self.links = [] # dicts: field, address, line, origin, at, model self.texts = {} # field -> [(language, text, line, origin)] self.origin = None self.words = ''def tokens(text): """Split a schema line's right side on spaces outside brackets and quotes.""" out, depth, quote, cur = [], 0, False, '' for ch in text: if ch == '"': quote = not quote if not quote: depth += ch == '(' depth -= ch == ')' if ch in ' \t' and not depth and not quote: if cur: out.append(cur) cur = '' else: cur += ch return out + ([cur] if cur else [])def call(token, word): return token[len(word) + 1:-1] if token.startswith(word + '(') and token.endswith(')') else Nonedef frontmatter(text): lines = text.split('\n') meta = {} if not lines or lines[0].strip() != '---': return None, lines, 0 for i in range(1, len(lines)): if lines[i].strip() == '---': return meta, lines, i + 1 m = re.match(r'([A-Za-z_]+):\s*(.*)$', lines[i]) if m: value = m.group(2).strip() meta[m.group(1)] = (json.loads(value) if value.startswith('"') else value, i + 1) return None, lines, 0def sections(lines, start): """-> [(h2 title, h2 line, {h3 title or None: [(line number, line, in fence)]})]""" out, fence = [], None cur = None h3 = None for i in range(start, len(lines)): line, no = lines[i], i + 1 stripped = line.strip() if fence: if stripped and set(stripped) == {fence[0]} and len(stripped) >= len(fence): fence = None elif cur: cur[2].setdefault(h3, []).append((no, line, True)) continue m = re.match(r'\s*(`{3,}|~{3,})', line) if m: fence = m.group(1) continue if line.startswith('## '): cur, h3 = (line[3:].strip(), no, {}), None out.append(cur) elif line.startswith('### ') and cur: h3 = line[4:].strip() cur[2].setdefault(h3, []) elif cur: cur[2].setdefault(h3, []).append((no, line, False)) return outdef parse_date(text): return date.fromisoformat(text)class Checker: def __init__(self, base, files): self.base, self.files = base, files self.errors, self.notes = [], [] self.intents, self.facets, self.records, self.reqs = set(), set(), {}, {} self.documents = [] # (path, line, subject address, [rows]) self.pending = [] # origin addresses to resolve: (path, line, address) self.req_sources = [] self.proposed = 0 def err(self, path, line, message): self.errors.append((path, line, message)) def note(self, path, line, message): self.notes.append((path, line, message)) # ---- literals ------------------------------------------------------------------------- def text(self, raw, pattern=BARE): if raw.startswith('"'): try: value = json.loads(raw) except ValueError: raise ValueError(f'{raw} is not a quoted text.') if not isinstance(value, str): raise ValueError(f'{raw} is not a text.') return value if not pattern.fullmatch(raw): raise ValueError(f'{raw!r} is neither a quoted text nor a bare token.') return raw def literal(self, field, raw): """The typed value of a literal for this field. Raises ValueError with the reason.""" raw = raw.strip() if raw in ('', 'null'): raise ValueError('A blank value or a bare null states nothing.') if field.kind == 'ref': target = self.target_field(field) return self.literal(target, raw) if target else self.text(raw) if field.kind == 'enum': value = self.text(raw) if value not in field.values: raise ValueError(f"'{value}' is not one of {', '.join(field.values)}.") return value if field.kind == 'fingerprint': if not FINGERPRINT.fullmatch(raw): raise ValueError('A fingerprint is written <algorithm>:<hex digits>.') return raw kind = field.scalar if kind in ('integer', 'number', 'decimal'): number, unit = raw, None if len(field.units) > 1: number, _, unit = raw.partition(' ') if unit not in field.units: raise ValueError(f"The value names its unit, one of {', '.join(field.units)}.") if not NUMBER.fullmatch(number) or (kind == 'integer' and not re.fullmatch(r'-?\d+', number)): raise ValueError(f'{raw!r} is not {"an integer" if kind == "integer" else "a number"}' + (' with its unit.' if field.units else '.')) try: value = Decimal(number) except InvalidOperation: raise ValueError(f'{raw!r} is not a number.') if field.min is not None and value < field.min: raise ValueError(f'{raw} is below min({field.min}).') if field.max is not None and value > field.max: raise ValueError(f'{raw} is above max({field.max}).') return (value, unit) if unit else value if kind == 'boolean': if raw not in ('true', 'false'): raise ValueError('A boolean is true or false.') return raw == 'true' if kind == 'date': if 'rough' in field.mods: if not ROUGH.fullmatch(raw) or len(raw.rstrip('~?')) not in (4, 7, 10): raise ValueError(f'{raw!r} is not a date in the spelling of ISO 8601-2.') if len(raw.rstrip('~?')) < 10 or raw[-1] in '~?': return raw try: return parse_date(raw.rstrip('~?')) if 'rough' in field.mods else parse_date(raw) except ValueError: raise ValueError(f'{raw!r} is not a calendar date.') if kind == 'datetime': if not DATETIME.fullmatch(raw): raise ValueError(f'{raw!r} is not a moment with a time zone or offset.') try: return datetime.fromisoformat(raw.replace('Z', '+00:00')) except ValueError: raise ValueError(f'{raw!r} is not a moment.') if kind == 'duration': m = DURATION.fullmatch(raw) if not m: raise ValueError(f'{raw!r} is not a length of time: a whole number and a unit.') return (int(m.group(1)), m.group(2)) if kind == 'position': m = POSITION.fullmatch(raw) if not m or not -90 <= float(m.group(1)) <= 90 or not -180 <= float(m.group(2)) <= 180: raise ValueError(f'{raw!r} is not a position: latitude, then longitude.') return (m.group(1), m.group(2)) if kind == 'file': return self.text(raw, re.compile(r'[A-Za-z0-9._/-]+')) value = self.text(raw) if kind == 'url' and not re.match(r'https?://\S+$', value): raise ValueError(f'{value!r} is not an absolute web address.') if kind == 'email' and not re.fullmatch(r'[^@\s]+@[^@\s]+\.[^@\s]+', value): raise ValueError(f'{value!r} is not an e-mail address.') if kind == 'phone' and not re.fullmatch(r'\+[\d ().-]{7,}', value): raise ValueError(f'{value!r} is not a telephone number in international form.') if field.min is not None and len(value) < field.min: raise ValueError(f'The text is shorter than min({field.min}).') if field.max is not None and len(value) > field.max: raise ValueError(f'The text is longer than max({field.max}).') return value def target_field(self, field): record = self.records.get(field.target[0]) return record.fields.get(field.target[1]) if record else None def to_key(self, record, keytext): """The typed key a row address names. A text key stands without quotes.""" key = record.key if key.kind == 'scalar' and key.scalar in ('integer', 'number', 'decimal', 'boolean', 'date', 'datetime', 'duration', 'position'): try: return self.literal(key, keytext) except ValueError: return None return keytext def find_row(self, address): m = ROW_ADDRESS.fullmatch(address) record = self.records.get(m.group(1)) if m else None if not record or not record.key: return None return record.rows.get(self.to_key(record, unquote(m.group(2)))) def resolve(self, address): """-> 'row', 'requirement', 'positional', 'facet:<Type>', 'intent', 'unverifiable' or None""" if re.match(r'[a-z][a-z0-9-]*/', address): return 'unverifiable' if ROW_ADDRESS.fullmatch(address): return 'row' if self.find_row(address) else None m = REQ_ADDRESS.fullmatch(address) if m: if m.group(2).isdigit(): return 'positional' return 'requirement' if (m.group(1), m.group(2)) in self.reqs else None m = FACET_ADDRESS.fullmatch(address) if m: return f'facet:{m.group(2)}' if m.groups() in self.facets else None return 'intent' if address in self.intents else None # ---- the model: Records and Requirements ---------------------------------------------- def read_schema(self, record, lines): for no, line, fenced in lines: if not fenced or not line.strip(): continue m = re.match(r'\s*(' + NAME + r'):\s*(\S.*)$', line) if not m: self.err(record.path, no, 'Expected <name>: <type> <modifier>*.') continue field = Field(m.group(1), no) if field.name in record.fields: self.err(record.path, no, f"Field '{field.name}' is declared twice.") record.fields[field.name] = field first, *rest = tokens(m.group(2)) self.read_type(record, field, first, no) for token in rest: if token in ('required', 'optional', 'unique', 'key', 'rough', 'owner', '!owner'): field.mods.add(token) elif call(token, 'min') is not None or call(token, 'max') is not None: try: setattr(field, token[:3], Decimal(token[4:-1])) except InvalidOperation: self.err(record.path, no, f'{token} needs a number.') elif call(token, 'default') is not None: field.default = call(token, 'default') elif call(token, 'label') is not None: pass elif call(token, 'unit') is not None: field.units = [unit.strip() for unit in call(token, 'unit').split(',') if unit.strip()] if not field.units or field.kind != 'scalar' or field.scalar not in ('number', 'integer', 'decimal'): self.err(record.path, no, 'unit(...) names what a number field measures.') elif call(token, 'ref') is not None or call(token, 'enum') is not None or call(token, 'list') is not None: self.read_type(record, field, token, no) else: self.err(record.path, no, f"Unknown modifier '{token}'.") if 'rough' in field.mods and not (field.kind == 'scalar' and field.scalar == 'date'): self.err(record.path, no, "'rough' stands on a date field.") if {'required', 'optional'} <= field.mods: self.err(record.path, no, "'required' together with 'optional'.") keys = [field for field in record.fields.values() if 'key' in field.mods] for field in keys[1:]: self.err(record.path, field.line, f'{record.address} has more than one key field.') if keys: key = keys[0] plain = key.kind == 'enum' or (key.kind == 'scalar' and key.scalar != 'file') if not plain or not {'required', 'unique'} <= key.mods: self.err(record.path, key.line, "The key is a 'required unique' enum or non-file scalar field.") else: record.key = key for field in record.fields.values(): if field.kind == 'fingerprint': named = record.fields.get(field.arg) if not named or named.kind != 'scalar' or named.scalar != 'file': self.err(record.path, field.line, f"fingerprint({field.arg}) names no file field of {record.address}.") def read_type(self, record, field, token, no): if token in SCALARS: field.kind, field.scalar = 'scalar', token elif call(token, 'enum') is not None: field.kind = 'enum' field.values = [re.sub(r'\s*".*"$', '', value.strip()) for value in re.split(r',(?=(?:[^"]*"[^"]*")*[^"]*$)', call(token, 'enum'))] elif call(token, 'ref') is not None: m = re.fullmatch(r'(' + INTENT + r')#(' + NAME + r')\.(' + NAME + r')', call(token, 'ref')) if not m: self.note(record.path, no, f'{token} is not a reference to a Record facet and is not checked.') field.kind = 'other' else: field.kind, field.target = 'ref', (f'{m.group(1)}#Record:{m.group(2)}', m.group(3)) elif call(token, 'list') is not None: inner = call(token, 'list') m = re.fullmatch(r'(' + INTENT + r')#(' + NAME + r')', inner) or re.fullmatch(r'ref\((' + INTENT + r')#(' + NAME + r')\.' + NAME + r'\)', inner) if m: field.kind, field.target = 'reflist', (f'{m.group(1)}#Record:{m.group(2)}', None) else: field.kind = 'other' elif call(token, 'part') is not None or call(token, 'map') is not None: field.kind = 'other' elif call(token, 'modelref') is not None: field.kind, field.arg = 'modelref', call(token, 'modelref') if field.arg != 'Requirement' and field.arg not in FACETS: self.err(record.path, no, f'modelref({field.arg}) names neither Requirement nor a facet type.') elif call(token, 'fingerprint') is not None: field.kind, field.arg = 'fingerprint', call(token, 'fingerprint') else: self.note(record.path, no, f"Unknown type '{token}', read as string.") def read_intent(self, path, meta, lines, start): intent = meta['aim'][0] todo = [] for title, line, blocks in sections(lines, start): m = re.fullmatch(r'(' + NAME + r'): (.+)', title) if title == 'Requirements': self.read_requirements(path, intent, blocks.get(None, [])) elif m and m.group(1) in FACETS: self.facets.add((intent, m.group(1), m.group(2))) if m.group(1) == 'Record': record = Record(intent, m.group(2), path, line) self.records[record.address] = record self.read_schema(record, blocks.get('Schema', [])) todo.append((record, blocks)) return todo def read_requirements(self, path, intent, lines): for no, line, fenced in lines: if fenced or not line.startswith('- '): continue body = line[2:].strip() m = re.match(r'\*\*(.+?)\*\*\s*', body) label = m.group(1) if m else None body = body[m.end():] if m else body should = body.startswith('(should)') if should and not label: self.err(path, no, 'The mark (should) needs a requirement with a label.') source = re.search(r'\s—\s+from(?::\s*(.+)|\s*\[(.+)\])$', body) if source: body = body[:source.start()] if source.group(2): for address in re.split(r',\s*', source.group(2)): self.req_sources.append((path, no, address.strip())) over = re.search(r'\s—\s+over\s*\[(.+)\]$', body) names = re.split(r',\s*', over.group(1)) if over else [] if label: if (intent, label) in self.reqs: self.err(path, no, f"Duplicate requirement label '{label}'.") self.reqs[(intent, label)] = {'should': should, 'over': names, 'path': path, 'line': no} elif over: self.err(path, no, "'over' stands on a requirement with a label.") def check_requirements(self): for (intent, label), req in self.reqs.items(): for address in req['over']: m = REQ_ADDRESS.fullmatch(address) other = self.reqs.get((m.group(1), m.group(2))) if m else None if not req['should']: self.err(req['path'], req['line'], f"'over' stands on a \"must\". Only \"should\" requirements are ranked.") elif not other: self.err(req['path'], req['line'], f"'over' names {address}, which is no labelled requirement.") elif not other['should']: self.err(req['path'], req['line'], f"'over' names {address}, which is a \"must\". A \"must\" never gives way.") seen, stack = set(), [(intent, label)] while stack: for address in self.reqs.get(stack.pop(), {}).get('over', []): m = REQ_ADDRESS.fullmatch(address) node = (m.group(1), m.group(2)) if m else None if node == (intent, label): self.err(req['path'], req['line'], f"'over' closes a circle at {label}.") stack = [] break if node and node not in seen: seen.add(node) stack.append(node) for path, no, address in self.req_sources: kind = self.resolve(address) if kind == 'unverifiable': self.note(path, no, f'The source {address} lies in another model and is not checked here.') elif kind not in ('row', 'requirement', 'facet:Knowledge', 'facet:Event'): self.err(path, no, f'The source {address} does not resolve to a Knowledge facet, a requirement, an Event or a row.') # ---- blocks of a Record ---------------------------------------------------------------- def read_blocks(self, record, blocks): path = record.path for no, line, fenced in blocks.get('Immutable', []): m = re.match(r'- `(' + NAME + r')`', line) if m: record.immutable.add(m.group(1)) bullets = lambda name: [(no, line[2:].strip()) for no, line, fenced in blocks.get(name, []) if line.startswith('- ')] if 'Period' in blocks: start = end = per = None one = False for no, text in bullets('Period'): m = re.fullmatch(r'from `(' + NAME + r')` until `(' + NAME + r')`', text) p = re.fullmatch(r'one at a time(?: per `(' + NAME + r')`)?', text) if m: start, end = record.fields.get(m.group(1)), record.fields.get(m.group(2)) kinds = {field.scalar if field and field.kind == 'scalar' else None for field in (start, end)} if kinds not in ({'date'}, {'datetime'}): self.err(path, no, 'A period names two date or two datetime fields of the Record.') start = end = None elif p: one, per = True, p.group(1) if per and per not in record.fields: self.err(path, no, f"'{per}' is no field of {record.address}.") else: self.err(path, no, "Expected - from `<start>` until `<end>` or - one at a time [per `<field>`].") if start: record.period = (start.name, end.name, one, per) elif not self.errors or self.errors[-1][0] != path: self.err(path, record.line, 'The Period block names no start and end.') if 'Replaces' in blocks: items = bullets('Replaces') m = re.fullmatch(r'`(' + NAME + r')`', items[0][1]) if len(items) == 1 else None field = record.fields.get(m.group(1)) if m else None if not field or field.kind not in ('ref', 'reflist') or field.target[0] != record.address: self.err(path, items[0][0] if items else record.line, "The Replaces block names one field that references the Record's own key.") else: record.replaces = field.name for no, text in bullets('Complete'): m = re.fullmatch(r'`(' + NAME + r')`', text) field = record.fields.get(m.group(1)) if m else None if text != 'the collection' and not (field and (field.kind == 'reflist' or field.kind == 'other')): self.err(path, no, 'A Complete bullet is `the collection` or a list field of the Record.') if 'Rows' in blocks: record.stated = True if not record.key: self.err(path, record.line, f"{record.address} has Rows and needs exactly one Schema field with the 'key' modifier.") else: self.read_rows(record, blocks['Rows']) def read_rows(self, record, lines): path, row = record.path, None for no, line, fenced in lines: if not line.strip(): continue if line.startswith('- '): row = None body = line[2:] if body.startswith('**"'): try: _, end = json.JSONDecoder().raw_decode(body[2:]) except ValueError: end = -1 keytext, rest = body[2:2 + end], body[2 + end:] ok = end > 0 and rest.startswith('**') rest = rest[2:] else: m = re.match(r'\*\*(.+?)\*\*', body) ok = bool(m) keytext, rest = (m.group(1), body[m.end():]) if m else ('', '') words = re.fullmatch(r'(?:\s+—\s+(.*))?\s*', rest) if not ok or not words: self.err(path, no, 'Expected - **<key>** or - **<key>** — <words>.') continue try: key = self.literal(record.key, keytext) except ValueError as e: self.err(path, no, f'Invalid key: {e}') continue shown = json.loads(keytext) if keytext.startswith('"') else keytext if key in record.rows: self.err(path, no, f'Duplicate stated key {record.address}[{shown}].') continue row = record.rows[key] = Row(record, key, shown, path, no, False) row.words = words.group(1) or '' row.values[record.key.name] = (key, no, None) continue m = re.match(r'\s+- (' + NAME + r'):\s*(.*)$', line) if not row or (not m and not line.startswith(' ')): self.err(path, no, 'Malformed row.') elif m: name, raw = m.group(1), m.group(2) field = record.fields.get(name) if not field: self.err(path, no, f"'{name}' is no Schema field of {record.address}.") elif name in row.values or any(link['field'] == name for link in row.links): self.err(path, no, f"'{name}' is stated twice in this row." if field is not record.key else 'A value bullet repeats the key.') elif field.kind not in ('scalar', 'enum', 'ref') or (field.kind == 'scalar' and field.scalar == 'file'): self.err(path, no, f"'{name}' has a type that Rows do not state.") elif field.kind == 'ref' and LINK.fullmatch(raw.strip()): row.links.append({'field': name, 'address': LINK.fullmatch(raw.strip()).group(2), 'line': no, 'origin': None, 'at': None}) else: try: row.values[name] = (self.literal(field, raw), no, None) except ValueError as e: self.err(path, no, f"'{name}': {e}") # ---- Entries files --------------------------------------------------------------------- def origin(self, rest, path, no): rest = rest.strip() if not rest: return None m = re.fullmatch(r'— from:\s*(\S.*)', rest) a = re.fullmatch(r'— from\s*\[(.+)\]', rest) if m and not TRAILER.search(' ' + m.group(1)): words = m.group(1).strip() if words.startswith('proposed'): p = PROPOSED.fullmatch(words) if not p: self.err(path, no, 'A suggestion is marked "proposed" or "proposed by <name>, <YYYY-MM-DD>".') return None return {'proposed': True, 'text': words, 'by': p.group(1), 'date': p.group(2)} return {'proposed': False, 'text': words} if a and not m: self.pending.append((path, no, a.group(1).strip())) return {'proposed': False, 'address': a.group(1).strip()} self.err(path, no, 'Expected one origin trailer, "— from: <words>" or "— from [<address>]".') return None def split(self, text, path, no): """-> (value, where a link points inside, origin)""" s, at = text.strip(), None if s.startswith('"'): try: _, end = json.JSONDecoder().raw_decode(s) except ValueError: end = len(s) value, rest = s[:end], s[end:] elif s.startswith('[') and '](aim:' in s: end = s.find(')', s.index('](aim:')) end = len(s) - 1 if end < 0 else end value, rest = s[:end + 1], s[end + 1:] m = AT.match(rest) if m: at, rest = m.group(1), rest[m.end():] else: m = TRAILER.search(s) value, rest = (s[:m.start()], s[m.start():]) if m else (s, '') return value.strip(), at, self.origin(rest, path, no) def read_entries(self, path, meta, lines, start): intent = meta['aim'][0] name = os.path.basename(path) if intent not in self.intents: return self.err(path, meta['aim'][1], f"'aim' names {intent}, which is no intent of this model.") if 'key' in meta: return self.err(path, meta['key'][1], "The key is declared in the Record's Schema with the 'key' modifier. Remove 'key' from the frontmatter.") if ('record' in meta) == ('subject' in meta): return self.err(path, 1, "Expected either 'record', for a list, or 'subject', for a document.") listed = subject = None if 'record' in meta: listed = self.records.get(meta['record'][0]) if not listed: return self.err(path, meta['record'][1], f"'record' names {meta['record'][0]}, which is no Record of the model.") if listed.list_path: return self.err(path, meta['record'][1], f'{listed.address} already has a list.') listed.list_path, listed.entries = path, True if name != f'{intent}.{listed.name}.entries.aim': self.err(path, 1, f'Expected the list of {listed.address} in {intent}.{listed.name}.entries.aim.') else: subject = meta['subject'][0] m = ROW_ADDRESS.fullmatch(subject) if not m or m.group(1) not in self.records: return self.err(path, meta['subject'][1], f"'subject' names {subject}, which is no row address of the model.") if not re.fullmatch(re.escape(intent) + r'\.' + ID + r'\.entries\.aim', name): self.err(path, 1, f'Expected a document named {intent}.<label>.entries.aim.') rows, row, text, fence, listing = [], None, None, None, None for i in range(start, len(lines)): line, no = lines[i], i + 1 stripped = line.strip() if fence: if stripped and set(stripped) == {fence[0]} and len(stripped) >= len(fence): fence = None if text: text[1].append(line) continue m = re.match(r'\s*(`{3,}|~{3,})', line) if m and text: fence = m.group(1) text[1].append(line) continue if line.startswith('## '): row = text = listing = None t = TRAILER.search(line) head = line[3:t.start()] if t else line[3:] origin = self.origin(line[t.start():], path, no) if t else None m = re.fullmatch(r'(?:(' + RECORD + r')|(' + NAME + r')): (\S+)', head.strip()) if not m: self.err(path, no, 'Expected ## <Record>: <ID>.') continue record = self.records.get(m.group(1) or f'{intent}#Record:{m.group(2)}') if not record: self.err(path, no, f"No Record '{m.group(1) or m.group(2)}' in the model.") elif listed and record is not listed: self.err(path, no, f'This file is the list of {listed.address}. Expected ## {listed.name}: <ID>.') elif not re.fullmatch(ID, m.group(3)): self.err(path, no, f"Invalid ID '{m.group(3)}'.") elif not record.key or record.key.kind != 'scalar' or record.key.scalar != 'string': self.err(path, no, f"{record.address} needs exactly one Schema field with the 'key' modifier, a string, to have Entries.") elif m.group(3) in record.rows: self.err(path, no, f'Duplicate entry {record.address}[{m.group(3)}].' if record.rows[m.group(3)].entry else f'{record.address} has Rows and takes no Entries.') else: record.entries = True row = record.rows[m.group(3)] = Row(record, m.group(3), m.group(3), path, no, True) row.origin = origin row.values[record.key.name] = (m.group(3), no, None) rows.append(row) elif line.startswith('### '): text = listing = None if not row: continue t = TRAILER.search(line) head = line[4:t.start()] if t else line[4:] origin = self.origin(line[t.start():], path, no) if t else None m = re.fullmatch(r'Text: (' + NAME + r')(?: \(([A-Za-z]{2,3}(?:-[A-Za-z0-9]+)*)\))?', head.strip()) field = row.record.fields.get(m.group(1)) if m else None if not m: self.err(path, no, 'Expected ### Text: <field> or ### Text: <field> (<language>).') elif not field or field.kind != 'scalar' or field.scalar != 'string' or field is row.record.key: self.err(path, no, f"'{m.group(1)}' is no string field of {row.record.address}.") elif field.name in row.values: self.err(path, no, f"'{field.name}' is given as a value and as a text.") else: blocks = row.texts.setdefault(field.name, []) if any(language == m.group(2) for language, *_ in blocks): self.err(path, no, f"'{field.name}' has two texts" + (f' in {m.group(2)}.' if m.group(2) else ' and names no language.')) elif blocks and (m.group(2) is None or blocks[0][0] is None): self.err(path, no, f"'{field.name}' has several texts, and one names no language.") else: text = (field.name, []) blocks.append((m.group(2), text[1], no, origin)) elif text: text[1].append(line) elif not stripped or not row: if stripped and not line.startswith('# '): self.err(path, no, 'Expected an entry heading, ## <Record>: <ID>.') elif listing and re.match(r'\s+- ', line): value, at, origin = self.split(line.strip()[2:], path, no) self.read_link(row, listing[0], value, at, origin or listing[1], path, no) else: listing = None m = re.match(r'- (' + NAME + r'):(.*)$', line) field = row.record.fields.get(m.group(1)) if m else None if not m: self.err(path, no, 'Expected - <field>: <value>.') elif not field: self.err(path, no, f"'{m.group(1)}' is no Schema field of {row.record.address}.") elif field is row.record.key: self.err(path, no, 'The key comes from the heading and is not assigned again.') elif field.name in row.values or field.name in row.texts or any(link['field'] == field.name for link in row.links) or field.name in getattr(row, 'lists', ()): self.err(path, no, f"'{field.name}' occurs twice in this entry.") else: value, at, origin = self.split(m.group(2), path, no) target_key = field.kind == 'ref' and self.is_key(field) if field.kind == 'reflist': row.lists = getattr(row, 'lists', set()) | {field.name} if value == '': listing = (field, origin) elif value != '[]': self.err(path, no, f"'{field.name}' is a reference list: one nested link per line, or [].") elif field.kind == 'modelref' or target_key: self.read_link(row, field, value, at, origin, path, no) elif field.kind == 'other': self.err(path, no, f"'{field.name}' has a type with no source form in an entry.") elif at: self.err(path, no, "'at' follows a link.") else: try: row.values[field.name] = (self.literal(field, value), no, origin) except ValueError as e: self.err(path, no, f"'{field.name}': {e}") if subject: self.documents.append((path, meta['subject'][1], subject, rows)) def is_key(self, field): record = self.records.get(field.target[0]) return bool(record and record.key and record.key.name == field.target[1]) def read_link(self, row, field, value, at, origin, path, no): m = LINK.fullmatch(value) if not m: return self.err(path, no, f"'{field.name}' is written as a link, [<label>](aim:<address>).") row.links.append({'field': field.name, 'address': m.group(2), 'line': no, 'origin': origin, 'at': at, 'model': field.kind == 'modelref'}) # ---- the collection as a whole --------------------------------------------------------- def check_rows(self): entries = links = stated = 0 for record in self.records.values(): if record.stated and record.entries: self.err(record.list_path or record.path, 1, f'{record.address} has Rows and takes no Entries.') seen = {} for row in record.rows.values(): entries += row.entry stated += not row.entry given = set(row.values) | set(row.texts) | {link['field'] for link in row.links} | getattr(row, 'lists', set()) if row.entry: for field in record.fields.values(): if field.name in given: continue if field.default is not None: try: row.values[field.name] = (self.literal(field, field.default), row.line, None) except ValueError: pass elif 'required' in field.mods: self.err(row.path, row.line, f"{row.address} lacks the required field '{field.name}'.") for name, blocks in row.texts.items(): field = record.fields[name] body = '\n'.join(blocks[0][1]).strip() if field.min is not None and len(body) < field.min: self.err(row.path, blocks[0][2], f"'{name}': the text is shorter than min({field.min}).") marked = [value for name, value in row.values.items() if name != record.key.name] for *_, origin in marked + [block[1:] for blocks in row.texts.values() for block in blocks]: self.proposed += bool((origin or row.origin or {}).get('proposed')) for name, (value, line, _) in row.values.items(): field = record.fields[name] if 'unique' in field.mods and field is not record.key: if (name, value) in seen: self.err(row.path, line, f"'{name}' is unique, and {seen[(name, value)]} already holds this value.") seen[(name, value)] = row.address if field.kind == 'ref' and not row.entry: self.check_literal_ref(row, field, value, line) for link in row.links: links += row.entry self.proposed += row.entry and bool((link['origin'] or row.origin or {}).get('proposed')) self.check_link(row, record.fields[link['field']], link) self.check_files(row) self.check_time(record) return entries, stated, links def check_literal_ref(self, row, field, value, line): target = self.records.get(field.target[0]) if not target or not target.rows or not (target.stated or target.entries): return name = field.target[1] if target.key and target.key.name == name: if value not in target.rows: self.err(row.path, line, f"'{field.name}' points to missing {target.address}[{value}].") elif target.stated and all(name in other.values for other in target.rows.values()): if not any(other.values[name][0] == value for other in target.rows.values()): self.err(row.path, line, f"'{field.name}' matches no row of {target.address}.") def check_link(self, row, field, link): path, line, address = row.path, link['line'], link['address'] if re.match(r'[a-z][a-z0-9-]*/', address): return self.note(path, line, f'{address} lies in another model and is not checked here.') if link.get('model'): kind = self.resolve(address) wanted = 'requirement' if field.arg == 'Requirement' else f'facet:{field.arg}' if kind == 'positional': self.err(path, line, f"'{field.name}' addresses a requirement by position. An authored model reference needs a label.") elif kind is None: self.err(path, line, f"'{field.name}' points to missing {address}.") elif kind != wanted: self.err(path, line, f"'{field.name}' must link to a {field.arg}, got {address}.") return m = ROW_ADDRESS.fullmatch(address) if not m: return self.err(path, line, f"'{field.name}' is a link to a row, <Record address>[<key>].") if m.group(1) != field.target[0]: return self.err(path, line, f"'{field.name}' must link to {field.target[0]}, got {m.group(1)}.") target = self.find_row(address) if not target: return self.err(path, line, f"'{field.name}' points to missing {address}.") if link['at']: self.check_inside(row, field, link, target) def read_file(self, relative): try: with open(os.path.join(self.base, relative), 'rb') as handle: return handle.read() except OSError: return None def fingerprinted(self, row): """-> [(file field, path, fingerprint or None)] for the file fields of a row""" out = [] for field in row.record.fields.values(): if field.kind == 'scalar' and field.scalar == 'file' and field.name in row.values: mark = next((other.name for other in row.record.fields.values() if other.kind == 'fingerprint' and other.arg == field.name), None) out.append((field.name, row.values[field.name][0], row.values.get(mark, (None,))[0] if mark else None)) return out def check_files(self, row): for name, relative, fingerprint in self.fingerprinted(row): line = row.values[name][1] content = self.read_file(relative) if content is None: self.err(row.path, line, f"'{name}': the file {relative} is missing.") elif fingerprint: algorithm, digest = fingerprint.split(':', 1) if algorithm not in hashlib.algorithms_available: self.note(row.path, line, f'The fingerprint algorithm {algorithm} is not available here.') elif hashlib.new(algorithm, content).hexdigest() != digest: self.err(row.path, line, f"'{name}': the file {relative} no longer fits its fingerprint.") def check_inside(self, row, field, link, target): path, line, at = row.path, link['line'], link['at'] texts = {name: '\n'.join(blocks[0][1]) for name, blocks in target.texts.items()} texts.update({name: value for name, (value, *_) in target.values.items() if isinstance(value, str) and target.record.fields[name].kind == 'scalar' and target.record.fields[name].scalar == 'string'}) files = [(relative, self.read_file(relative)) for _, relative, fingerprint in self.fingerprinted(target) if fingerprint] if at.startswith('#'): if not any(re.search(r'\{' + re.escape(at) + r'\}\s*$', body, re.M) for blocks in target.texts.values() for _, body_lines, *_ in blocks for body in ['\n'.join(body_lines)]): self.err(path, line, f"'{field.name}' names the anchor {at}, which is not in the text of {target.address}.") elif at.startswith('"'): words = json.loads(at) fixed = [body for name, body in texts.items() if name in target.record.immutable] fixed += [content.decode('utf-8', 'replace') for _, content in files if content is not None] if not fixed: self.err(path, line, f"'{field.name}' points at words in {target.address}, whose text can change. Point at an anchor.") elif not any(words in body for body in fixed): self.err(path, line, f"'{field.name}': the quoted words are not in {target.address}.") elif not files: self.err(path, line, f"'{field.name}' points at {at} in {target.address}, which holds no file with a fingerprint.") else: self.note(path, line, f"'{field.name}' at {at}: not checkable here.") def check_time(self, record): rows = list(record.rows.values()) if record.replaces: older = {} for row in rows: for link in row.links: if link['field'] == record.replaces and self.find_row(link['address']): older.setdefault(row.address, []).append(self.find_row(link['address']).address) replaced = {} for newer, targets in older.items(): for target in targets: replaced.setdefault(target, []).append(newer) for row in rows: seen, stack = set(), list(older.get(row.address, [])) while stack: address = stack.pop() if address == row.address: self.err(row.path, row.line, f'{row.address} replaces itself through a chain.') break if address not in seen: seen.add(address) stack.extend(older.get(address, [])) if len(replaced.get(row.address, [])) > 1: self.note(row.path, row.line, f'{row.address} is replaced by several rows and may have been split.') if record.period and record.period[2]: start, end, _, per = record.period groups = {} for row in rows: group = row.values.get(per, (None,))[0] if per else None if per and group is None: group = next((link['address'] for link in row.links if link['field'] == per), None) first = row.values.get(start, (None,))[0] if isinstance(first, (date, datetime)): groups.setdefault(group, []).append((first, row)) for group in groups.values(): group.sort(key=lambda pair: pair[0]) for (a, older_row), (b, newer_row) in zip(group, group[1:]): last = older_row.values.get(end, (None,))[0] if a == b: self.err(newer_row.path, newer_row.line, f'{newer_row.address} and {older_row.address} hold on the same day, and only one at a time may.') elif isinstance(last, (date, datetime)) and last >= b: self.note(older_row.path, older_row.line, f'The written end of {older_row.address} disagrees with the start of {newer_row.address}.') def check_documents(self): for path, line, subject, rows in self.documents: if not any(row.address == subject for row in rows): self.err(path, line, f'Expected the subject {subject} as an entry of this document.') for row in rows: if row.address != subject and not any(link['address'] == subject for link in row.links): self.err(path, row.line, f'{row.address} does not belong to this document. None of its references names {subject}.') def run(self): parsed = [] for path in sorted(self.files): meta, lines, start = frontmatter(self.files[path]) if meta is None or 'aim' not in meta or 'kind' not in meta: self.err(path, 1, "Missing frontmatter with 'aim' and 'kind'.") else: parsed.append((path, meta, lines, start)) if meta['kind'][0] == 'intent': self.intents.add(meta['aim'][0]) todo = [] for path, meta, lines, start in parsed: if meta['kind'][0] == 'intent': todo += self.read_intent(path, meta, lines, start) for record, blocks in todo: self.read_blocks(record, blocks) for path, meta, lines, start in parsed: if meta['kind'][0] == 'entries': self.read_entries(path, meta, lines, start) counts = self.check_rows() self.check_documents() self.check_requirements() for path, line, address in self.pending: kind = self.resolve(address) if kind == 'unverifiable': self.note(path, line, f'The origin {address} lies in another model and is not checked here.') elif kind is None or kind == 'positional': self.err(path, line, f'The origin trailer names {address}, which does not resolve.') self.errors = sorted(set(self.errors), key=lambda e: (e[0], e[1])) return countsdef load(base): files = {} for folder, _, names in os.walk(os.path.join(base, 'aim')): for name in names: if name.endswith('.aim'): full = os.path.join(folder, name) with open(full, encoding='utf-8') as handle: files[os.path.relpath(full, base)] = handle.read() return filesdef check(base, files=None): checker = Checker(base, load(base) if files is None else files) return checker, checker.run()def report(base, notes): checker, (entries, stated, links) = check(base) name = os.path.basename(os.path.normpath(base)) if not checker.files: print(f'{name}: no .aim files under {os.path.join(base, "aim")}') return False for path, line, message in checker.errors: print(f'{os.path.join(base, path)}:{line}: {message}') if not checker.errors: print(f'{name}: valid. {entries} entries, {stated} stated rows, {links} typed links, {checker.proposed} proposed lines waiting.') if notes: for path, line, message in checker.notes: print(f' note {path}:{line}: {message}') return not checker.errors# ---- self-test: break the examples in memory and expect each error ---------------------------def self_test(root): def sub(path, old, new, count=1): def change(files): assert old in files[path], f'{old!r} not in {path}' files[path] = files[path].replace(old, new, count) return change def add(path, content): return lambda files: files.__setitem__(path, content) def drop_entry(path, heading): def change(files): before, _, after = files[path].partition(heading) assert after, heading nxt = after.find('\n## ') files[path] = before + (after[nxt + 1:] if nxt >= 0 else '') return change def both(*changes): return lambda files: [change(files) for change in changes] journal = 'aim/diary/diary.DiaryEntry.entries.aim' minutes = 'aim/board/board.2026-11-28.entries.aim' notes = 'aim/scheduling/scheduling.ContextNote.entries.aim' incident = 'aim/incidents/incidents.2026-11-17-checkout.entries.aim' december = ('---\naim: board\nkind: entries\nsubject: "board#Record:Meeting[2026-12-12]"\n---\n\n# Board meeting, 12 December 2026\n\n' '## Meeting: 2026-12-12\n\n- date: 2026-12-12\n- chair: [Anna](aim:board#Record:Person[Anna])\n') decision = '## Decision: 2026-11-28-1\n\n- meeting: [28 November](aim:board#Record:Meeting[2026-11-28])\n\n### Text: body\n\nThe launch moves to 1 March.\n\n' pair = ''.join(f'\n## Decision: x{a}\n\n- meeting: [12 December](aim:board#Record:Meeting[2026-12-12])\n- replaces: [other](aim:board#Record:Decision[x{b}])\n\n### Text: body\n\nNames only the other.\n' for a, b in ((1, 2), (2, 1))) cases = [ ('diary', 'the mood link replaced by the link to Anna', sub(journal, '[Calm](aim:diary#Record:Mood[calm])', '[Anna](aim:diary#Record:Person[Anna])'), "'mood' must link to diary#Record:Mood, got diary#Record:Person."), ('diary', 'an entry deleted while another links to it', drop_entry(journal, '## DiaryEntry: 2026-11-21'), "'followsUpOn' points to missing diary#Record:DiaryEntry[2026-11-21]."), ('diary', 'a proposed mention confirmed', sub(journal, 'Person[Anna]) — from: proposed by Claude, 2026-11-28', 'Person[Anna]) — from: Mia, 2026-12-01, proposed by Claude, 2026-11-28'), ('valid', 1)), ('diary', 'a link to a missing stated row', sub(journal, 'Mood[calm]', 'Mood[sad]'), "'mood' points to missing diary#Record:Mood[sad]."), ('diary', 'a duplicate stated key', sub('aim/diary/diary.aim', '- **restless**', '- **calm**'), 'Duplicate stated key diary#Record:Mood[calm].'), ('diary', 'the retired key line in the header', sub(journal, 'kind: entries\n', 'kind: entries\nkey: id\n'), "Remove 'key' from the frontmatter."), ('diary', 'a second trailer on one line', sub(journal, '— from: proposed by Claude, 2026-11-28', '— from: Mia — from: proposed'), 'Expected one origin trailer'), ('diary', 'Rows together with Entries', add('aim/diary/diary.Mood.entries.aim', '---\naim: diary\nkind: entries\nrecord: "diary#Record:Mood"\n---\n\n# Moods\n\n## Mood: glad\n\n- label: Glad\n- order: 3\n'), 'diary#Record:Mood has Rows and takes no Entries.'), ('board', 'an action of another meeting that follows a decision here', both(add('aim/board/board.2026-12-12.entries.aim', december), sub(minutes, '## Action: 2026-11-28-a1 — from: proposed by Claude, 2026-11-28\n\n- meeting: [28 November](aim:board#Record:Meeting[2026-11-28])', '## Action: 2026-12-12-a1\n\n- meeting: [12 December](aim:board#Record:Meeting[2026-12-12])')), 'board#Record:Action[2026-12-12-a1] does not belong to this document.'), ('board', 'two entries that name only each other', both(add('aim/board/board.2026-12-12.entries.aim', december), lambda files: files.__setitem__(minutes, files[minutes] + pair)), ['board#Record:Decision[x1] does not belong to this document.', 'board#Record:Decision[x2] does not belong to this document.', 'replaces itself through a chain']), ('board', 'the decision moved into a list', both(sub(minutes, decision, ''), add('aim/board/board.Decision.entries.aim', '---\naim: board\nkind: entries\nrecord: "board#Record:Decision"\n---\n\n# Decisions\n\n' + decision)), ('valid', 0)), ('scheduling', 'a cited entry deleted', both(drop_entry(notes, '## ContextNote: OvernightShift'),), 'The source scheduling#Record:ContextNote[OvernightShift] does not resolve'), ('scheduling', 'an Operation address in explainsRequirement', sub(notes, 'aim:scheduling#Requirements[OVERNIGHT-DATE]', 'aim:scheduling#Operation:ListShiftsForDate'), "'explainsRequirement' must link to a Requirement"), ('scheduling', 'a requirement addressed by position', sub(notes, 'Requirements[OVERNIGHT-DATE]', 'Requirements[1]'), 'needs a label'), ('incidents', 'a tampered fingerprint', lambda files: files.__setitem__(incident, re.sub(r'sha256:[0-9a-f]{4}', 'sha256:0000', files[incident])), 'no longer fits its fingerprint'), ('incidents', 'quoted words that are not there', sub(incident, 'at "The pool is full"', 'at "The pool was empty"'), 'the quoted words are not in incidents#Record:Observation[checkout-2].'), ('incidents', 'quoted words that are not in the file', sub(incident, 'at "remaining connection slots are reserved"', 'at "out of memory"'), 'the quoted words are not in incidents#Record:Exhibit[db-log].'), ('incidents', 'a length of time without a known unit', sub('aim/incidents/incidents.aim', 'answerWithin: 15 minutes', 'answerWithin: 15 moments'), 'is not a length of time'), ('incidents', 'a (should) without a label', sub('aim/incidents/incidents.aim', '- **POOL-ALERT** (should)', '- (should)'), 'The mark (should) needs a requirement with a label.'), ('incidents', 'a source row that does not exist', sub('aim/incidents/incidents.aim', 'Incident[2026-11-17-checkout]]', 'Incident[2026-11-18-search]]'), 'does not resolve to a Knowledge facet, a requirement, an Event or a row.'), ('claims', "an 'over' that names a must", sub('aim/claims/claims.aim', 'Every line of a claim has a receipt.', 'Every line of a claim has a receipt — over [claims#Requirements[FAIR]]'), 'A "must" never gives way.'), ('claims', "an 'over' on a must", sub('aim/claims/claims.aim', 'is the sum of its lines.', 'is the sum of its lines — over [claims#Requirements[RECEIPTS]]', 1), 'Only "should" requirements are ranked.'), ] failed = 0 for name, what, change, expected in cases: base = os.path.join(root, name) files = load(base) before, _ = check(base, dict(files)) change(files) checker, _ = check(base, files) messages = [message for _, _, message in checker.errors] if isinstance(expected, tuple): ok = not messages and before.proposed - checker.proposed == expected[1] else: ok = all(any(want in message for message in messages) for want in ([expected] if isinstance(expected, str) else expected)) failed += not ok print(f"{'ok ' if ok else 'FAIL'} {name}: {what}") if not ok: print(f' expected {expected!r}, got {messages!r}') print(f'{len(cases) - failed} of {len(cases)} self-tests passed.') return not faileddef main(argv): root = os.path.dirname(os.path.abspath(__file__)) if '--self-test' in argv: return 0 if self_test(root) else 1 notes = '--notes' in argv dirs = [arg for arg in argv if not arg.startswith('--')] or [os.path.join(root, name) for name in EXAMPLES] return 0 if all([report(base, notes) for base in dirs]) else 1if __name__ == '__main__': sys.exit(main(sys.argv[1:]))