Lukasz Boryn 6441d0f425 feat(sound): add verified recon before a blueprint locks
New `skills/loop/sound/` — a three-step spine run in order: read the OKF
pages the question touches, query the nostos MCP server when one is
configured, then confirm both against live code, because either can have
gone stale. A claim with no internal owner is followed to its primary
source; nothing else leaves the repo.

Two mouths, per 019. Reached by name it refines the blueprint it sounded
and stamps `sounded: <date>`; self-fired it reports and writes nothing —
a stamp a self-fire cannot make is a stamp a lock can trust. It is the
loop's only model-invoked skill, so README's "All loop skills are
user-invoked" and ARCHITECTURE's invocation seam both stop being true
and are corrected here.

Sounding becomes a precondition of lock: okf-check warns `locked without
sounded:` on a locked blueprint carrying no stamp — never at draft
(not-yet-sounded is correct there) nor at implemented (it would
retro-flag 002-006). Warning, not error, so exit status stays 0.

Implements blueprint 007. The script leg of its Verify is green; the
four session checks need fresh sessions and stay open in ROADMAP.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-22 13:23:18 +02:00

251 lines
8.8 KiB
Python
Executable File

#!/usr/bin/env python3
"""Validate an OKF bundle. Usage: okf-check <okf-dir>
Errors (exit 1): missing type, missing warrant, duplicate answer,
unresolvable cite, malformed `okf:derived` fence, page unreachable from
index.md, register index line disagreeing with its decision file, moored
ferry with a malformed `sealed:` pin or a surviving directory. Warnings
(exit 0): page over the 110-line cap, page with no cites, blueprint
locked without a `sounded:` stamp.
Pin *shape* only — whether the change id still resolves needs the repo in
hand, which is write-OKF refresh's job, not a validator that must exit 0
on an OKF tree copied outside its jj repo.
"""
import re
import sys
from pathlib import Path
CAP = 110
def frontmatter(text):
"""Parse the leading --- block. Returns {} when absent.
Handles scalars, inline lists (`answers: [a, b]`) and block lists
(`answers:` followed by indented `- ` items).
"""
if not text.startswith("---\n"):
return {}
end = text.find("\n---", 3)
if end == -1:
return {}
fields, key = {}, None
for line in text[4:end].splitlines():
item = re.match(r"\s+-\s+(.*)", line)
if item and key:
fields[key].append(unquote(item.group(1)))
continue
pair = re.match(r"([A-Za-z_-]+):\s*(.*)", line)
if not pair:
continue
key, raw = pair.group(1), pair.group(2).strip()
if raw.startswith("[") and raw.endswith("]"):
fields[key] = [unquote(v) for v in raw[1:-1].split(",") if v.strip()]
elif raw:
fields[key] = unquote(raw)
key = None
else:
fields[key] = []
return fields
def unquote(value):
value = value.strip()
if len(value) > 1 and value[0] == value[-1] and value[0] in "\"'":
return value[1:-1]
return value
def links(text):
"""Markdown link targets, minus anchors and external URLs."""
out = []
for target in re.findall(r"\]\(([^)]+)\)", text):
target = target.split("#")[0].strip()
if target and "://" not in target:
out.append(target)
return out
def reachable(okf, pages):
"""Pages reachable from index.md, transitively through index pages.
A ferry's decision files are covered by their MAP.md, which is the
single home for them by layout contract.
"""
seen, frontier = set(), [okf / "index.md"]
while frontier:
page = frontier.pop()
if page in seen or not page.exists():
continue
seen.add(page)
if page.name not in ("index.md", "MAP.md"):
continue
for target in links(page.read_text()):
frontier.append((page.parent / target).resolve())
for page in pages:
parent_map = page.parent / "MAP.md"
if parent_map in seen:
seen.add(page)
return seen
def cite_resolves(cite, page, okf):
"""`path` and `path:line` need the path; `path:symbol` needs both.
The symbol is matched as a literal substring — no language awareness,
no tags file. A `:suffix` that parses as an integer is a reading aid,
never validated: a check that cannot fail is not a check.
"""
path, _, symbol = cite.split("#")[0].partition(":")
path, symbol = path.strip(), symbol.strip()
if not path:
return False
if symbol.isdigit():
symbol = ""
for root in (page.parent, okf, okf.parent):
target = root / path
if not target.exists():
continue
if not symbol:
return True
if target.is_file() and symbol in target.read_text():
return True
return False
def fence_error(text):
"""Shape of the derived zone: at most one region, begin before end.
A fence owns its whole line, so a page that merely *mentions* the
markers in prose or in a command is not fenced.
"""
marks = re.findall(r"^<!-- okf:derived (begin|end) -->$", text, re.M)
if marks and marks != ["begin", "end"]:
return f"malformed okf:derived fence: {' '.join(marks)}"
return None
def pin(text):
"""Fields of `sealed:`, the one nested block the frontmatter carries."""
head = text.partition("\n---")[0] if text.startswith("---\n") else ""
block = re.search(r"^sealed:\n((?:[ \t]+.*\n?)+)", head, re.M)
return dict(re.findall(r"([a-z]+):\s*(\S+)", block.group(1))) if block else {}
def check_ferries(okf, errors):
"""A page directly under ferries/ is a moored ferry: pinned, collapsed."""
ferries = okf / "ferries"
if not ferries.is_dir():
return
for page in sorted(ferries.glob("*.md")):
rel = page.relative_to(okf.parent)
if (ferries / page.stem).is_dir():
errors.append(f"{rel}: coexists with ferries/{page.stem}/ — open or moored, never both")
fields = pin(page.read_text())
missing = [f for f in ("change", "commit", "date") if f not in fields]
if missing:
errors.append(f"{rel}: sealed: missing {', '.join(missing)}")
continue
if not re.fullmatch(r"[0-9a-f]{8,64}", fields["commit"]):
errors.append(f"{rel}: sealed: commit is not a hex hash: {fields['commit']}")
if not re.fullmatch(r"\d{4}-\d{2}-\d{2}", fields["date"]):
errors.append(f"{rel}: sealed: date is not ISO 8601: {fields['date']}")
def check_register(okf, warrants, errors):
"""Register index lines must quote their decision's own question."""
index = okf / "decisions" / "index.md"
if not index.exists():
return
for line in index.read_text().splitlines():
if not line.startswith("- "):
continue
target = links(line)
fields = line.split(" — ")
if not target or len(fields) < 2:
errors.append(f"{index}: malformed register line: {line}")
continue
page = (index.parent / target[0]).resolve()
answers = warrants.get(page, {}).get("answers") or []
if not answers:
errors.append(f"{index}: line points at a page with no answers: {target[0]}")
elif fields[1].strip() != answers[0]:
errors.append(
f"{index}: line question disagrees with {target[0]}: "
f"{fields[1].strip()!r} vs {answers[0]!r}"
)
def main(argv):
if len(argv) != 2:
print("usage: okf-check <okf-dir>", file=sys.stderr)
return 2
okf = Path(argv[1]).resolve()
if not okf.is_dir():
print(f"not a directory: {okf}", file=sys.stderr)
return 2
pages = sorted(p.resolve() for p in okf.rglob("*.md"))
index = okf / "index.md"
errors, warnings, warrants, answered = [], [], {}, {}
seen = reachable(okf, pages)
for page in pages:
text = page.read_text()
fields = frontmatter(text)
warrants[page] = fields
rel = page.relative_to(okf.parent)
if page not in seen:
errors.append(f"{rel}: not reachable from index.md")
fence = fence_error(text)
if fence:
errors.append(f"{rel}: {fence}")
if page == index:
continue
if not fields.get("type"):
errors.append(f"{rel}: missing type:")
if len(text.splitlines()) > CAP:
warnings.append(f"{rel}: over the {CAP}-line cap")
# Sounding is a precondition of lock. Only at `locked`: `draft` is
# not-yet-sounded, and `implemented` would retro-flag 002-006.
if ("blueprints" in rel.parts and fields.get("status") == "locked"
and not fields.get("sounded")):
warnings.append(f"{rel}: locked without sounded:")
# The warrant contract covers durable synthesis pages; blueprints
# and ferries carry their own frontmatter contracts.
if {"blueprints", "ferries"} & set(rel.parts) or page.name == "index.md":
continue
if not fields.get("purpose"):
errors.append(f"{rel}: missing purpose:")
if not fields.get("answers"):
errors.append(f"{rel}: missing answers:")
for answer in fields.get("answers") or []:
if answer in answered:
errors.append(f"{rel}: answers a question {answered[answer]} owns: {answer}")
else:
answered[answer] = rel
cites = fields.get("cites") or []
if not cites:
warnings.append(f"{rel}: no cites:")
for cite in cites:
if not cite_resolves(cite, page, okf):
errors.append(f"{rel}: unresolvable cite: {cite}")
check_ferries(okf, errors)
check_register(okf, warrants, errors)
for line in warnings:
print(f"WARN {line}")
for line in errors:
print(f"ERROR {line}")
print(f"{len(errors)} error(s), {len(warnings)} warning(s)")
return 1 if errors else 0
if __name__ == "__main__":
sys.exit(main(sys.argv))