"""Read the AIM diary example: its Records, its fixed Rows and its Entries files, with every linkchecked and every line keeping who put it there."""from __future__ import annotationsimport argparsefrom dataclasses import dataclass, fieldfrom datetime import datefrom decimal import Decimalimport jsonfrom pathlib import Pathimport reimport sysfrom urllib.parse import unquoteROOT = Path(__file__).resolve().parent / "aim" / "diary"ID = 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.]*"RECORD = rf"{INTENT}#Record:{NAME}"HEADING = re.compile(r" {0,3}(#{1,6})[ \t]+(.+?)\s*")FENCE = re.compile(r" {0,3}(`{3,}|~{3,})(.*)")FIELD = re.compile(rf"- ({NAME}):[ \t]*(.*?)\s*")NESTED_ITEM = re.compile(r"([ \t]+)-[ \t]+(.*?)\s*")REF = re.compile(rf"ref\(({INTENT})#({NAME})\.({NAME})\)")REF_LIST = re.compile(rf"list\(({INTENT})#({NAME})\)")LINK = re.compile(rf"\[(.*)\]\(aim:({RECORD})\[([^\]\s]+)\]\)")LINK_HEAD = re.compile(r"\[[^\]]*\]\(aim:[^()\s]*\)")ROW_ADDRESS = re.compile(rf"({RECORD})\[([^\]\s]+)\]")ENTRY_HEADING = re.compile(rf"({NAME}|{RECORD}): ({ID})")TRAILER_START = re.compile(r"(?:^|[ \t])— from(?=:|[ \t]*\[)")TRAILER = re.compile(r"— from(?:: (\S(?:.*\S)?)|[ \t]*\[(.+)\])")PROPOSED = re.compile(r"proposed(?: by (\S(?:.*\S)?), (\d{4}-\d{2}-\d{2}))?")NUMBER = re.compile(r"-?(?:0|[1-9][0-9]*)")class DiaryError(Exception): pass@dataclass(frozen=True)class Origin: """Who put a line there: words (`from: ...`) or an address (`from [...]`).""" text: str = "" address: str = "" proposed: bool = False def __str__(self) -> str: return f" — from [{self.address}]" if self.address else f" — from: {self.text}"@dataclassclass Source: path: Path lines: list[str] @classmethod def open(cls, path: Path) -> Source: return cls(path, path.read_text(encoding="utf-8").splitlines()) def location(self, line: int) -> str: return f"{self.path}:{line + 1}" def fail(self, line: int, message: str) -> DiaryError: return DiaryError(f"{self.location(line)}: {message}") def frontmatter(self) -> tuple[dict[str, str], int]: if not self.lines or self.lines[0] != "---": raise self.fail(0, "Expected AIM frontmatter.") header = {} for index, line in enumerate(self.lines[1:], 1): if line == "---": return header, index + 1 if not line.strip() or line.lstrip().startswith("#"): continue match = re.fullmatch(r"([a-z][a-z_]*)[ \t]*:[ \t]*(.+?)\s*", line) if not match or match[1] in header: raise self.fail(index, "Expected one value per frontmatter key.") value = match[2] if value.startswith(('"', "'")): value = text_literal(self, index, value, allow_single_quotes=True) header[match[1]] = value raise self.fail(0, "Unclosed AIM frontmatter.") def sections(self, start: int, stop: int, level: int): found = [] fence = "" for index in range(start, stop): line = self.lines[index] marker = FENCE.fullmatch(line) if fence: if marker and marker[1].startswith(fence) and not marker[2].strip(): fence = "" continue if marker: fence = marker[1] continue heading = HEADING.fullmatch(line) if heading and len(heading[1]) == level: found.append((re.sub(r"[ \t]+#+$", "", heading[2]), index)) for (title, index), (_, end) in zip(found, found[1:] + [("", stop)]): yield title, index, end def nonblank(self, start: int, stop: int) -> list[int]: return [index for index in range(start, stop) if self.lines[index].strip()]@dataclass(frozen=True)class SchemaField: kind: str # string, date, integer, link, links required: bool unique: bool key: bool minimum: int | None target: tuple[str, str | None] | None = None # (Record address, field or None for the key)@dataclass(frozen=True)class Link: record: str key: str label: str line: int origin: Origin | None@dataclass(frozen=True)class Value: content: str | Decimal | Link | list[Link] line: int origin: Origin | None = None@dataclassclass Row: address: str key: str source: Source line: int values: dict[str, Value] origin: Origin | None = None@dataclassclass Record: address: str name: str schema: dict[str, SchemaField] line: int stated: bool = False # the rows are fixed in the model's `### Rows` listed: Source | None = None # the Record's one list file rows: dict[str, Row] = field(default_factory=dict) @property def key(self) -> str | None: keys = [name for name, schema in self.schema.items() if schema.key] return keys[0] if len(keys) == 1 else None def add(self, row: Row) -> None: if row.key in self.rows: first = self.rows[row.key] raise row.source.fail(row.line, f"Duplicate entry {row.address}. First written at {first.source.location(first.line)}.") if self.key in row.values: raise row.source.fail(row.values[self.key].line, f"The heading supplies '{self.key}'.") row.values[self.key] = Value(row.key, row.line, row.origin) for name, schema in self.schema.items(): if schema.required and name not in row.values: raise row.source.fail(row.line, f"{row.address} is missing required field '{name}'.") self.rows[row.key] = row@dataclassclass Diary: intent: str records: dict[str, Record] # by Record address nodes: set[str] # addresses of the model's own headings waiting: int = 0 def record(self, name: str) -> Record: return self.records[f"{self.intent}#Record:{name}"] def rows(self): return (row for record in self.records.values() for row in record.rows.values())def text_literal(source: Source, line: int, literal: str, *, allow_single_quotes: bool = False) -> str: if literal.startswith('"'): try: value = json.loads(literal) except json.JSONDecodeError: raise source.fail(line, "Invalid quoted text.") from None if isinstance(value, str): return value if allow_single_quotes and len(literal) >= 2 and literal[0] == literal[-1] == "'": return literal[1:-1].replace("''", "'") if literal and literal != "null" and not literal.startswith(("[", '"', "'")): return literal raise source.fail(line, "Use a bare value or put the text in double quotes.")def split_origin(source: Source, line: int, text: str) -> tuple[str, Origin | None]: """Take the one origin trailer off the end of a line. A quoted value and a link are read to their own end first, so their words are never taken for a trailer.""" head = "" if text.startswith('"'): end = 1 while end < len(text) and text[end] != '"': end += 2 if text[end] == "\\" else 1 head = text[: end + 1] elif (link := LINK_HEAD.match(text)) and LINK.fullmatch(text[: link.end()]): head = text[: link.end()] else: start = TRAILER_START.search(text) head = text[: start.start()] if start else text rest = text[len(head):].strip() if not rest: return head.rstrip(), None trailer = TRAILER.fullmatch(rest) words = trailer[1] if trailer else None if not trailer or (words and TRAILER_START.search(words)): raise source.fail(line, "Expected one origin trailer, ' — from: <words>' or ' — from [<address>]', at the end of the line.") if words is None: return head.rstrip(), Origin(address=trailer[2]) if words.startswith("proposed"): if not PROPOSED.fullmatch(words): raise source.fail(line, 'A suggestion is marked "proposed" or "proposed by <name>, <YYYY-MM-DD>".') return head.rstrip(), Origin(text=words, proposed=True) return head.rstrip(), Origin(text=words)def read_schema(source: Source, intent: str, heading: int, end: int) -> dict[str, SchemaField]: lines = source.nonblank(heading + 1, end) if len(lines) < 3 or source.lines[lines[0]].strip() != "```schema" or source.lines[lines[-1]].strip() != "```": raise source.fail(heading, "Expected a schema fence.") schema = {} for index in lines[1:-1]: match = re.fullmatch(rf"({NAME}):\s+(\S+)(?:\s+(.*))?", source.lines[index]) if not match or match[1] in schema: raise source.fail(index, "Malformed or repeated schema field.") name, kind, modifiers = match.groups() target = None if reference := REF.fullmatch(kind): kind, target = "link", (f"{reference[1]}#Record:{reference[2]}", reference[3]) elif reference := REF_LIST.fullmatch(kind): kind, target = "links", (f"{reference[1]}#Record:{reference[2]}", None) elif kind.startswith("list(ref("): raise source.fail(index, "A list of references is written list(<intent>#<Record>).") if kind not in {"string", "date", "integer", "link", "links"}: raise source.fail(index, f"Unsupported field type '{kind}' in the diary example.") flags = (modifiers or "").split() minimum = None for flag in flags: if flag in {"required", "optional", "unique", "key"}: continue bound = re.fullmatch(r"min\(([0-9]+)\)", flag) if not bound or kind not in {"string", "integer"} or minimum is not None: raise source.fail(index, f"Unsupported schema modifier '{flag}'.") minimum = int(bound[1]) if "key" in flags and not ("required" in flags and "unique" in flags and kind in {"string", "integer"}): raise source.fail(index, "A key is a required unique string or integer field.") schema[name] = SchemaField(kind, "required" in flags, "unique" in flags, "key" in flags, minimum, target) return schemadef read_link(source: Source, line: int, literal: str, origin: Origin | None) -> Link: match = LINK.fullmatch(literal) if not match: raise source.fail(line, "Use [label](aim:<intent>#Record:<Record>[<ID>]) for a typed link.") return Link(match[2], unquote(match[3]), match[1], line, origin)def read_value(source: Source, line: int, schema: SchemaField, inline: str, nested: list[tuple[int, str]], inherited: Origin | None) -> Value: inline, own = split_origin(source, line, inline) origin = own or inherited if schema.kind == "links": if inline == "[]" and not nested: return Value([], line, origin) if inline or not nested: raise source.fail(line, "Use indented link bullets or [] for a list of references.") links = [] for index, item in nested: item, mark = split_origin(source, index, item) links.append(read_link(source, index, item, mark or origin)) return Value(links, line, origin) if nested: raise source.fail(nested[0][0], "Only a list field accepts nested bullets.") if schema.kind == "link": if schema.target[1] is not None and LINK.fullmatch(inline) is None and not inline.startswith("["): raise source.fail(line, "In an Entries file a reference to a key is written as a link.") return Value(read_link(source, line, inline, origin), line, origin) if schema.kind == "integer": if NUMBER.fullmatch(inline): return Value(Decimal(inline), line, origin) raise source.fail(line, "Expected an integer.") value = text_literal(source, line, inline) if schema.kind == "date": try: if re.fullmatch(r"[0-9]{4}-[0-9]{2}-[0-9]{2}", value): return Value(date.fromisoformat(value).isoformat(), line, origin) except ValueError: pass raise source.fail(line, "Expected a valid date in YYYY-MM-DD form.") return Value(value, line, origin)def read_fields(source: Source, record: Record, start: int, end: int, indent: str = "", inherited: Origin | None = None) -> dict[str, Value]: values = {} index = start while index < end: raw = source.lines[index] if not raw.strip(): index += 1 continue match = FIELD.fullmatch(raw[len(indent):]) if raw.startswith(indent) else None if not match: raise source.fail(index, "Expected a field bullet such as '- date: 2026-11-28'.") name, inline = match.groups() if name not in record.schema or name in values: raise source.fail(index, f"Unknown or repeated field '{name}' on {record.name}.") field_line = index index += 1 nested = [] while index < end: item = source.lines[index] if item.strip(): match = NESTED_ITEM.fullmatch(item[len(indent):]) if item.startswith(indent) else None if not match or len((indent + match[1]).expandtabs(4)) < len(indent) + 2: break nested.append((index, match[2])) index += 1 values[name] = read_value(source, field_line, record.schema[name], inline, nested, inherited) return valuesdef read_stated_rows(source: Source, record: Record, heading: int, end: int) -> None: lines = source.nonblank(heading + 1, end) if lines and re.match(r"- key:", source.lines[lines[0]]): raise source.fail(lines[0], "The key is declared in the Schema with the 'key' modifier. Remove the 'key' bullet from Rows.") if record.key is None: raise source.fail(heading, f"{record.address} needs exactly one Schema field with the 'key' modifier.") starts = [index for index in lines if source.lines[index].startswith("- ")] if lines and (not starts or starts[0] != lines[0]): raise source.fail(lines[0], "Expected a stated row key.") record.stated = True for index, stop in zip(starts, starts[1:] + [end]): match = re.fullmatch(r"- \*\*(.+?)\*\*(?: — .+)?", source.lines[index]) if not match or (record.schema[record.key].kind == "integer" and not NUMBER.fullmatch(match[1])): raise source.fail(index, "Expected '- **<key>**' for a stated row.") values = read_fields(source, record, index + 1, stop, indent=" ") record.add(Row(f"{record.address}[{match[1]}]", match[1], source, index, values))def read_model(source: Source) -> Diary: header, start = source.frontmatter() intent = header.get("aim", "") if not re.fullmatch(INTENT, intent) or header.get("kind") != "intent": raise source.fail(0, "Expected an intent file.") diary = Diary(intent, {}, set()) for title, heading, end in source.sections(start, len(source.lines), 2): node = re.fullmatch(rf"({NAME}): ({NAME})", title) if node: diary.nodes.add(f"{intent}#{node[1]}:{node[2]}") if not node or node[1] != "Record": continue address = f"{intent}#Record:{node[2]}" blocks = list(source.sections(heading + 1, end, 3)) sections = {title: (first, last) for title, first, last in blocks} if address in diary.records or "Schema" not in sections or len(blocks) != len(sections): raise source.fail(heading, "A Record needs a unique name, one Schema, and distinct section headings.") record = Record(address, node[2], read_schema(source, intent, *sections["Schema"]), heading) if sum(schema.key for schema in record.schema.values()) > 1: raise source.fail(heading, f"{address} names more than one key.") if "Rows" in sections: read_stated_rows(source, record, *sections["Rows"]) diary.records[address] = record return diarydef read_entries(source: Source, diary: Diary) -> None: header, start = source.frontmatter() if header.get("aim") != diary.intent or header.get("kind") != "entries": raise source.fail(0, f"Expected an Entries file of the intent '{diary.intent}'.") if "key" in header: raise source.fail(0, "The key is declared in the Record's Schema with the 'key' modifier. Remove 'key' from the frontmatter.") listed = diary.records.get(header.get("record", "")) subject = ROW_ADDRESS.fullmatch(header.get("subject", "")) if ("record" in header) == ("subject" in header) or not (listed or (subject and subject[1] in diary.records)): raise source.fail(0, "Expected either 'record', the address of a Record, or 'subject', the row address of one entry.") name = source.path.name if listed: if name != f"{diary.intent}.{listed.name}.entries.aim": raise source.fail(0, f"Expected the list of {listed.address} in {diary.intent}.{listed.name}.entries.aim.") if listed.listed: raise source.fail(0, f"{listed.address} already has a list.") listed.listed = source elif not re.fullmatch(rf"{re.escape(diary.intent)}\.{ID}\.entries\.aim", name): raise source.fail(0, f"Expected a document named {diary.intent}.<label>.entries.aim.") titles = list(source.sections(start, len(source.lines), 1)) if len(titles) != 1: raise source.fail(start, "Expected one H1 title in the Entries file.") entries = list(source.sections(start, len(source.lines), 2)) first_entry = entries[0][1] if entries else len(source.lines) title_line = titles[0][1] if title_line >= first_entry or source.nonblank(start, title_line) or source.nonblank(title_line + 1, first_entry): raise source.fail(start, "Place the Entries title directly before the entry blocks.") written = [] for title, heading, end in entries: title, origin = split_origin(source, heading, title) match = ENTRY_HEADING.fullmatch(title) if not match: raise source.fail(heading, "Expected '## <Record>: <ID>' with letters, digits, hyphens or underscores in the ID.") address = match[1] if "#" in match[1] else f"{diary.intent}#Record:{match[1]}" record = diary.records.get(address) if not record: raise source.fail(heading, f"No Record '{match[1]}' in the model.") if listed and record is not listed: raise source.fail(heading, f"This file is the list of {listed.address}. Expected ## {listed.name}: <ID>.") if record.stated: raise source.fail(heading, f"{record.address} has its rows fixed in the model and takes no entries.") key = record.schema.get(record.key or "") if not key or key.kind != "string": raise source.fail(heading, f"{record.address} needs exactly one Schema field with the 'key' modifier, and for entries it is a string.") blocks = list(source.sections(heading + 1, end, 3)) fields_end = blocks[0][1] if blocks else end values = read_fields(source, record, heading + 1, fields_end, inherited=origin) for block, first, last in blocks: block, mark = split_origin(source, first, block) field_name = block.removeprefix("Text: ") schema = record.schema.get(field_name) if not block.startswith("Text: ") or not schema or schema.kind != "string" or field_name in values: raise source.fail(first, "A Text block must name an unused string field.") body = source.nonblank(first + 1, last) text = "\n".join(source.lines[body[0]:body[-1] + 1]) if body else "" values[field_name] = Value(text, first, mark or origin) row = Row(f"{address}[{match[2]}]", match[2], source, heading, values, origin) record.add(row) written.append(row) if subject: target = subject[0] if all(row.address != target for row in written): raise source.fail(0, f"Expected the subject {target} as an entry of this document.") for row in written: names = any(f"{link.record}[{link.key}]" == target for value in row.values.values() for link in links_in(value)) if row.address != target and not names: raise source.fail(row.line, f"{row.address} does not belong to this document. None of its references names {target}.")def links_in(value: Value) -> list[Link]: if isinstance(value.content, Link): return [value.content] if isinstance(value.content, list): return value.content return []def origins_in(row: Row): if row.origin: yield row.line, row.origin for value in row.values.values(): if value.origin: yield value.line, value.origin for link in links_in(value): if link.origin: yield link.line, link.origindef validate(diary: Diary) -> None: addresses = diary.nodes | {row.address for row in diary.rows()} waiting = set() for record in diary.records.values(): unique = {name: {} for name, schema in record.schema.items() if schema.unique} for row in record.rows.values(): for line, origin in origins_in(row): if origin.address and origin.address not in addresses: raise row.source.fail(line, f"The origin trailer names {origin.address}, which does not resolve.") if origin.proposed: waiting.add((row.source.path, line)) for name, value in row.values.items(): schema = record.schema[name] content = value.content if schema.minimum is not None: measure = len(content) if isinstance(content, str) else content if measure < schema.minimum: raise row.source.fail(value.line, f"Field '{name}' must satisfy min({schema.minimum}).") if name in unique and content != "": if not isinstance(content, (str, Decimal)): raise row.source.fail(value.line, "The example supports unique scalar fields only.") if content in unique[name]: raise row.source.fail(value.line, f"Duplicate value for '{name}' on {record.name}.") unique[name][content] = row.key for link in links_in(value): target_address, key_field = schema.target target = diary.records.get(target_address) if link.record != target_address: raise row.source.fail(link.line, f"'{name}' must link to {target_address}, got {link.record}.") if not target or (key_field is not None and target.key != key_field): raise row.source.fail(link.line, f"'{name}' must name the key of {target_address}.") if link.key not in target.rows: raise row.source.fail(link.line, f"'{name}' points to missing {link.record}[{link.key}].") diary.waiting = len(waiting)def confirmed(diary: Diary) -> Diary: """The same collection without anything that is still a suggestion.""" dropped = {row.address for row in diary.rows() if row.origin and row.origin.proposed} def keep(link: Link) -> bool: return not (link.origin and link.origin.proposed) and f"{link.record}[{link.key}]" not in dropped result = Diary(diary.intent, {}, diary.nodes) for address, record in diary.records.items(): copy = Record(record.address, record.name, record.schema, record.line, record.stated, record.listed) for row in record.rows.values(): if row.address in dropped: continue values = {} for name, value in row.values.items(): if isinstance(value.content, list): values[name] = Value([link for link in value.content if keep(link)], value.line, value.origin) elif isinstance(value.content, Link): if keep(value.content): values[name] = value elif not (value.origin and value.origin.proposed): values[name] = value copy.rows[row.key] = Row(row.address, row.key, row.source, row.line, values, row.origin) result.records[address] = copy return resultdef load_diary() -> Diary: intent = Source.open(ROOT / "diary.aim") diary = read_model(intent) for name in ("DiaryEntry", "Person", "Mood"): if f"{diary.intent}#Record:{name}" not in diary.records: raise intent.fail(0, f"The example needs Record: {name}.") for path in sorted(ROOT.glob("*.entries.aim")): read_entries(Source.open(path), diary) validate(diary) return diarydef mark(origin: Origin | None) -> str: return str(origin) if origin else ""def matching_entries(diary: Diary, field_name: str, address: str) -> list[tuple[Row, Link]]: result = [] for row in diary.record("DiaryEntry").rows.values(): value = row.values.get(field_name) for link in links_in(value) if value else []: if f"{link.record}[{link.key}]" == address: result.append((row, link)) return resultdef print_entry_list(found: list[tuple[Row, Link]]) -> None: for row, link in sorted(found, key=lambda pair: (pair[0].values["date"].content, pair[0].key)): print(f" {row.key} ({row.values['date'].content}) {row.source.location(row.line)}{mark(link.origin)}") if not found: print(" None")def show_entry(diary: Diary, key: str) -> None: row = diary.record("DiaryEntry").rows.get(key) if not row: raise DiaryError(f"No diary entry with ID '{key}'.") print(f"{row.key} ({row.values['date'].content}){mark(row.origin)}") print(row.source.location(row.line)) body = row.values.get("body") if body: print(f"\n{body.content}{mark(body.origin)}\n") for name, value in row.values.items(): for link in links_in(value): target = diary.records[link.record].rows[link.key] print(f"{name}: {link.record}[{link.key}] {target.source.location(target.line)}{mark(link.origin)}") print("\nFollowed up by:") print_entry_list(matching_entries(diary, "followsUpOn", row.address))def show_mentions(diary: Diary, key: str) -> None: person = diary.record("Person").rows.get(key) if not person: raise DiaryError(f"No person with ID '{key}'.") print(f"Entries mentioning {person.values['name'].content} [{key}]:") print_entry_list(matching_entries(diary, "mentions", person.address))def main() -> int: parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--confirmed", action="store_true", help="leave out every line that is still a suggestion") commands = parser.add_subparsers(dest="command") commands.add_parser("check", help="validate the diary files") commands.add_parser("entry", help="show an entry and its links").add_argument("id") commands.add_parser("person", help="find entries mentioning someone").add_argument("id") args = parser.parse_args() try: diary = load_diary() waiting = diary.waiting if args.confirmed: diary = confirmed(diary) if args.command == "entry": show_entry(diary, args.id) elif args.command == "person": show_mentions(diary, args.id) else: entries = diary.record("DiaryEntry").rows people = diary.record("Person").rows link_count = sum(len(links_in(value)) for row in entries.values() for value in row.values.values()) entry_label = "entry" if len(entries) == 1 else "entries" people_label = "person" if len(people) == 1 else "people" link_label = "typed link" if link_count == 1 else "typed links" print(f"Diary is valid. {len(entries)} {entry_label}, {len(people)} {people_label}, {link_count} {link_label}." + (f" {waiting} proposed, waiting for confirmation." if waiting and not args.confirmed else "")) except (DiaryError, OSError, UnicodeError) as error: print(error, file=sys.stderr) return 1 return 0if __name__ == "__main__": sys.exit(main())