Something went wrong. Try again.
Architecture research toward an agent-native operating system; rigorous, pre-prototype, and intentionally self-aware.
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275#!/usr/bin/env python3"""Read-only structural validator for the AOS three-document distillation."""
from __future__ import annotations
import hashlibimport reimport sysfrom pathlib import Pathfrom urllib.parse import unquote
ROOT = Path(__file__).resolve().parentARCHIVE = "AOS-0_Architecture_Handoff.md"DOCS = ("CORE.md", "DECISIONS.md", "BOOTSTRAP-1.md")EXPECTED_ARCHIVE_SHA256 = "38620371db7efa05ce3fcfc1b94876c732c3efeed850ac995dd6aece96f01112"LIMITS = {"CORE.md": 1000, "DECISIONS.md": 1200, "BOOTSTRAP-1.md": 1300}AGGREGATE_LIMIT = 3500TERMS = ( "Actor", "Execution", "Capability", "State Revision", "World", "Commitment", "Budget", "Resource", "Channel", "Effect", "Principal", "Promotion",)REQUIRED_HEADINGS = { "CORE.md": ( "Status and authority", "Thesis", "Proof target", "Non-goals and native boundary", "Semantic concepts", "Invariants", "Trusted-boundary rule", "Litmus test", ), "DECISIONS.md": ("Status and use", "Entry schema", "Ordered decisions", "Original brief disposition"), "BOOTSTRAP-1.md": ( "Status and authority", "Hosted profile", "Roles and separation of powers", "Authoritative records", "Generation loop", "Observability contract", "Acceptance scenarios", "Exit condition", "Deferred after Bootstrap-1", ),}SCENARIO_ASSERTIONS = { "B1-01": (("observation", "same measured generation"), ("observation", "canonical root")), "B1-02": ("destroy all executions", "same actor id", "new activation"), "B1-03": ("distinct source/build/verify/promote grants", "self-promotion", "typed denials"), "B1-04": ("immutable revision", "predecessor", "payload identity", "commitment"), "B1-05": ("canonical root remains byte-identical", "world confinement"), "B1-06": (("setup", "sealed artifact hashes"), ("setup", "challenge selection"), ("setup", "repair/expected delta withheld"), ("observation", "previously absent delta"), ("observation", "sealed-input audit")), "B1-07": ("pinned verifier", "binds exact image", "suite"), "B1-08": (("setup", "missing, invalid"), ("setup", "image-mismatched"), ("setup", "suite-mismatched"), ("setup", "unauthorized-verifier"), ("setup", "stale/replayed"), ("observation", "every request rejected")), "B1-09": ("fresh complete", "one authorized canonical transition", "duplicate"), "B1-10": ("commitment", "diagnosis", "revision", "build", "evidence", "decision", "generation"), "B1-11": (("setup", "subsystem, failure mode, delta shape"), ("setup", "repair withheld"), ("observation", "previously absent aos-2 delta"), ("observation", "new scoped grants/budgets/evidence/nonces"), ("observation", "replay each aos-0 item/parent/policy rejects")), "B1-12": (("setup", "model bridge unavailable"), ("action", "boot selection/actor restore/evidence validation/denial/rollback"), ("action", "forged grant/budget/evidence"), ("observation", "creates no authority/budget/evidence")), "B1-13": (("setup", "requested"), ("setup", "root_prepared"), ("setup", "root_committed"), ("setup", "authorized"), ("setup", "dispatching"), ("setup", "acknowledged"), ("setup", "settled"), ("observation", "unknown"), ("observation", "withholds redispatch")), "B1-14": (("setup", "known-good"), ("action", "pre-boot failure"), ("action", "watchdog timeout"), ("action", "post-boot health failure"), ("observation", "recovery root"), ("observation", "rollback transition")),}
class ValidationError(Exception): pass
def read(name: str) -> str: path = ROOT / name if not path.is_file(): raise ValidationError(f"missing {name}") return path.read_text(encoding="utf-8")
def words(text: str) -> int: return len(re.findall(r"\b[\w'-]+\b", text, flags=re.UNICODE))
def headings(text: str) -> list[str]: return [m.group(1).strip() for m in re.finditer(r"^#{1,6}\s+(.+?)\s*$", text, re.MULTILINE)]
def slug(value: str) -> str: value = re.sub(r"<[^>]+>", "", value).strip().lower() value = re.sub(r"[^\w\- ]", "", value, flags=re.UNICODE) return re.sub(r"[ -]+", "-", value).strip("-")
def table_rows(text: str) -> list[list[str]]: rows = [] for line in text.splitlines(): if not line.startswith("|") or re.match(r"^\|[-:| ]+\|$", line): continue rows.append([cell.strip() for cell in line.strip().strip("|").split("|")]) return rows
def check_original_unchanged() -> None: data = (ROOT / ARCHIVE).read_bytes() actual = hashlib.sha256(data).hexdigest() if actual != EXPECTED_ARCHIVE_SHA256: raise ValidationError(f"archive SHA-256 {actual}, expected {EXPECTED_ARCHIVE_SHA256}")
def check_document_set() -> None: normative_md = set(DOCS) | {ARCHIVE} expected_md = normative_md | {"README.md"} actual_md = {p.name for p in ROOT.glob("*.md")} if actual_md != expected_md: raise ValidationError(f"Markdown set {sorted(actual_md)}, expected {sorted(expected_md)}") for name in DOCS: text = read(name) for target in normative_md - {name}: if f"]({target}" not in text: raise ValidationError(f"{name} does not link to {target}") if "archiv" not in text.lower() or "not normative" not in text.lower(): raise ValidationError(f"{name} does not mark archive non-normative")
def check_word_budget() -> None: counts = {name: words(read(name)) for name in DOCS} failures = [f"{name}={count}>{LIMITS[name]}" for name, count in counts.items() if count > LIMITS[name]] if sum(counts.values()) > AGGREGATE_LIMIT: failures.append(f"aggregate={sum(counts.values())}>{AGGREGATE_LIMIT}") if failures: raise ValidationError(", ".join(failures)) print(" words: " + ", ".join(f"{name}={count}" for name, count in counts.items()) + f", total={sum(counts.values())}")
def check_required_structure() -> None: for name, required in REQUIRED_HEADINGS.items(): present = set(headings(read(name))) missing = [heading for heading in required if heading not in present] if missing: raise ValidationError(f"{name} missing headings: {missing}") working = "\n".join(read(name) for name in DOCS) forbidden = ("cap_derive(", "actor_activate(", "world_merge(", "effect_prepare(", "effect_commit(") found = [token for token in forbidden if token in working] if found: raise ValidationError(f"provisional syscall block reintroduced: {found}")
def check_unique_definitions() -> None: core = read("CORE.md") concept_rows = {cells[0].replace("**", ""): cells[1] for cells in table_rows(core) if len(cells) == 2 and cells[0].startswith("**")} if set(concept_rows) != set(TERMS): raise ValidationError(f"canonical terms {sorted(concept_rows)}, expected {sorted(TERMS)}") for term, definition in concept_rows.items(): if not definition or definition.endswith("?"): raise ValidationError(f"invalid definition for {term}") for name in ("DECISIONS.md", "BOOTSTRAP-1.md"): text = read(name) if "## Semantic concepts" in text or re.search(r"^\|\s*\*\*(?:" + "|".join(map(re.escape, TERMS)) + r")\*\*\s*\|", text, re.MULTILINE): raise ValidationError(f"{name} redefines canonical terms")
def parse_decisions(text: str) -> dict[str, str]: matches = list(re.finditer(r"^### (D-\d{3})\s*$", text, re.MULTILINE)) result = {} for index, match in enumerate(matches): end = matches[index + 1].start() if index + 1 < len(matches) else text.find("\n## ", match.end()) if end < 0: end = len(text) result[match.group(1)] = text[match.end():end] return result
def check_decision_schema() -> None: decisions = parse_decisions(read("DECISIONS.md")) expected = {f"D-{i:03d}" for i in range(1, 16)} if set(decisions) != expected: raise ValidationError(f"decision IDs {sorted(decisions)}, expected {sorted(expected)}") fields = ("Question", "Blocks", "Options", "Inclination", "Evidence", "Depends", "Status") for decision_id, body in decisions.items(): missing = [field for field in fields if f"**{field}:**" not in body] statuses = re.findall(r"\*\*Status:\*\*\s*`(\w+)`", body) allowed = {"OPEN", "DEFERRED", "RESOLVED"} status_valid = len(statuses) == 1 and statuses[0] in allowed deferred_valid = decision_id not in {"D-013", "D-014", "D-015"} or statuses == ["DEFERRED"] if missing or not status_valid or not deferred_valid: raise ValidationError( f"{decision_id}: missing={missing}, statuses={statuses}, allowed={sorted(allowed)}" ) if statuses == ["RESOLVED"]: number = decision_id.removeprefix("D-") adr_links = re.findall(r"\((decisions/ADR-" + re.escape(number) + r"-[^)]+\.md)\)", body) if len(adr_links) != 1 or not (ROOT / adr_links[0]).is_file(): raise ValidationError(f"{decision_id}: resolved entry requires one existing matching ADR link") valid = set(decisions) for name in ("CORE.md", "BOOTSTRAP-1.md"): refs = set(re.findall(r"D-\d{3}", read(name))) invalid = refs - valid if invalid: raise ValidationError(f"{name} has invalid decisions {sorted(invalid)}")
def check_source_disposition() -> None: rows = {} for cells in table_rows(read("DECISIONS.md")): if len(cells) == 3 and cells[0].isdigit(): section = int(cells[0]) if section in rows: raise ValidationError(f"duplicate disposition section {section}") rows[section] = cells[1:] if set(rows) != set(range(1, 27)): raise ValidationError(f"disposition sections {sorted(rows)}, expected 1..26") for section, (disposition, rationale) in rows.items(): classes = ("settled", "open", "milestone", "roles", "sketches", "candidate", "goal", "protocol examples", "direction", "later phases", "document suite", "activation rule", "deferred", "repository sketch", "rule", "mission", "research links", "differentiation", "terms", "identity ambiguities", "unresolved") if not any(f"{kind} →" in disposition for kind in classes): raise ValidationError(f"section {section} lacks classified disposition") if not (re.search(r"\[[^]]+\]\([^)]+#[^)]+\)", disposition) or re.search(r"D-\d{3}", disposition) or "archive-only" in disposition): raise ValidationError(f"section {section} lacks concrete anchor/decision/archive destination") if not rationale: raise ValidationError(f"section {section} lacks rationale")
def check_bootstrap_scenarios() -> None: scenarios = {} for cells in table_rows(read("BOOTSTRAP-1.md")): if len(cells) == 5: match = re.fullmatch(r"\*\*(B1-\d{2})\*\*", cells[0]) if match: scenarios[match.group(1)] = cells expected = {f"B1-{i:02d}" for i in range(1, 15)} if set(scenarios) != expected: raise ValidationError(f"scenario IDs {sorted(scenarios)}, expected {sorted(expected)}") for scenario_id, cells in scenarios.items(): if any(not cell for cell in cells[1:]) or len(cells[4].split()) < 2: raise ValidationError(f"{scenario_id} lacks setup/action/observation/invariants") fields = dict(zip(("setup", "action", "observation", "invariants"), (cell.lower().replace("`", "") for cell in cells[1:]))) assertions = SCENARIO_ASSERTIONS[scenario_id] if assertions and isinstance(assertions[0], str): assertions = tuple(("any", phrase) for phrase in assertions) missing = [] for column, phrase in assertions: haystack = " ".join(fields.values()) if column == "any" else fields[column] if phrase not in haystack: missing.append(f"{column}:{phrase}") if missing: raise ValidationError(f"{scenario_id} missing assertions {missing}")
def check_links() -> None: for source_name in DOCS: text = read(source_name) for match in re.finditer(r"\[[^]]+\]\(([^)]+)\)", text): target = unquote(match.group(1)) if re.match(r"^[a-z]+://", target) or target.startswith("mailto:"): continue path_text, separator, anchor = target.partition("#") target_path = ROOT / path_text if path_text else ROOT / source_name if not target_path.is_file(): raise ValidationError(f"{source_name}: missing link target {target}") if separator: available = {slug(heading) for heading in headings(target_path.read_text(encoding="utf-8"))} if anchor not in available: raise ValidationError(f"{source_name}: missing anchor #{anchor} in {path_text or source_name}")
CHECKS = ( check_original_unchanged, check_document_set, check_word_budget, check_required_structure, check_unique_definitions, check_decision_schema, check_source_disposition, check_bootstrap_scenarios, check_links,)
def main() -> int: failed = False for check in CHECKS: try: check() print(f"PASS {check.__name__}") except (ValidationError, OSError, UnicodeError) as error: failed = True print(f"FAIL {check.__name__}: {error}") return 1 if failed else 0
if __name__ == "__main__": sys.exit(main())