homemaker-layout/experiments/migrate_usage_key.py

114 lines
3.8 KiB
Python
Raw Permalink Normal View History

§39.7: access requirements become a declared `usage:` attribute (homemaker-py-sel) Closes the second namespace sharing a first character with programme codes: the usage prefixes b/t/l/k, under which a room silently inherited another room's connectivity rules from its spelling. usage is a plain, MANDATORY attribute of the space definition -- not a lookup table. An interim design proposed a top-level usage_classes: table binding author-coined names to behaviour; withdrawn, because an indirect name->behaviour mapping living apart from the thing it describes is exactly the shape of the prefix rule §39 exists to remove, it would be the only such table in a schema where every other space property is a plain attribute, and the need it served was already met -- "building specific" is about what a room is CALLED, and name: is already free text. Rule that settles it: a usage value exists iff the engine treats it differently somewhere. Config selects among behaviours; it cannot invent them. - programme.USAGES (living/kitchen/bedroom/toilet/utility/none) plus the behaviour groupings PRIVATE_USAGES / PRIVATE_STRIPS / TOILET_STRIPS / SOCIABLE_USAGES. Missing or unknown usage is a load error naming the code, from BOTH parse paths. - Code-level, never leaf-level: usage_of(leaf.type) is looked up fresh, so a retype changes the class automatically. 51 sites assign leaf.type, and share/share_type plus the r5a resurrection are the precedent for why leaf-level attributes rot. - graph.has_circulation takes the usage map and trims on declared class; fitness.access and the public-access check likewise. fitness._t0 is DELETED -- no first-character type test remains anywhere in the codebase. - utility is distinct from bedroom (same access requirements today) because it is a different use and gives derive_interchange_classes an axis to relax on. - A toilet now keeps its edge to a terminal room -- the Brand adjacency, which the old b-before-t loop ordering severed. - All 107 corpus entries migrated by experiments/migrate_usage_key.py, comments and layout preserved. MEASURED -- the connectivity model was ~4x too permissive. `none` is not neutral: nothing is trimmed, so the graph may route THROUGH the room, and 34 of 52 codes had no class (Dental Surgery, Records Room, Utilities Closet all served as corridors). Edges trimmed, prefix-inferred vs declared, 3 seeds each: harbor-house 18 (9%) -> 79 (39%) inaccessible fails 0 -> 4 health-centre 12 (8%) -> 59 (40%) inaccessible fails 2 -> 3 maple-court 53 (17%) -> 123 (39%) inaccessible fails 1 -> 5 Re-baseline (seed 1, 20k, harbor): 58 fails (15h/43s) -> 61 (16h/45s), now reporting 1-inaccessible-usable-space x2 plus level 0 and level 1 not connected. The count rose because the objective got honest -- those failures were always true of the layout and the old model could not see them. Every harbor number before this was measured against a graph crediting routes through store cupboards. Sharpens §38.2: the objective pays x60-85 to delete circulation, and until now the deleted corridors were not missed because storage stood in for them. With that substitution gone, homemaker-py-2v1 is the remaining half -- and now measurable, because the fails it should prevent actually fire. 350 passed (+5 new), same 7 pre-existing fixture failures, lint unchanged. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01MJ84Feep79Hhm3E4zZJmnB
2026-08-26 13:39:41 +00:00
"""Write the agreed `usage:` attribute into every corpus `patterns.config`.
One-shot migration for `homemaker-py-sel` (DESIGN.md §39.7). Reads the reviewed
assignments in ``usage_map_proposal.yaml`` and inserts a ``usage:`` line into
each space definition, in place, preserving comments and formatting (the file
is edited as text, not round-tripped through the YAML emitter, which would strip
every comment in the corpus).
Idempotent: a space that already declares ``usage:`` is left alone unless
``--force`` is given, in which case the existing value is rewritten.
Usage::
python experiments/migrate_usage_key.py --check # dry run, report only
python experiments/migrate_usage_key.py # apply
"""
from __future__ import annotations
import argparse
import re
import sys
from pathlib import Path
import yaml
PROPOSAL = Path(__file__).with_name("usage_map_proposal.yaml")
CORPUS = Path(__file__).resolve().parent.parent / "examples"
def load_assignments() -> dict[str, str]:
"""code -> usage, from the reviewed proposal (its top-level keys ARE the
usage classes; every other key in the file is a comment)."""
doc = yaml.safe_load(PROPOSAL.read_text()) or {}
out: dict[str, str] = {}
for usage, codes in doc.items():
for code in (codes or {}):
out[code] = usage
return out
def migrate(path: Path, assign: dict[str, str], check: bool,
force: bool) -> tuple[int, int, list[str]]:
"""Insert ``usage:`` as the first property of each space definition.
Returns ``(written, skipped, unknown_codes)``. Edits the file as text so the
corpus keeps its comments and layout.
"""
text = path.read_text()
spaces = (yaml.safe_load(text) or {}).get("spaces") or {}
space_key = re.compile(r"^ ([A-Za-z_][\w-]*):\s*$")
written = skipped = 0
unknown: list[str] = []
out: list[str] = []
for line in text.splitlines(keepends=True):
m = space_key.match(line)
code = m.group(1) if m and m.group(1) in spaces else None
# drop a pre-existing usage line when rewriting
if force and re.match(r"^ usage:\s", line):
continue
out.append(line)
if code is None:
continue
usage = assign.get(code)
if usage is None:
unknown.append(code)
elif "usage" in spaces[code] and not force:
skipped += 1
else:
out.append(f" usage: {usage}\n")
written += 1
if not check and written:
path.write_text("".join(out))
return written, skipped, unknown
def main() -> int:
ap = argparse.ArgumentParser(description=__doc__,
formatter_class=argparse.RawDescriptionHelpFormatter)
ap.add_argument("--check", action="store_true", help="dry run")
ap.add_argument("--force", action="store_true",
help="rewrite a usage: that is already present")
args = ap.parse_args()
assign = load_assignments()
print(f"{len(assign)} code -> usage assignments loaded from "
f"{PROPOSAL.name}\n")
total_unknown: list[tuple[str, str]] = []
for cfg in sorted(CORPUS.glob("*/patterns.config")):
written, skipped, unknown = migrate(cfg, assign, args.check, args.force)
total_unknown += [(cfg.parent.name, c) for c in unknown]
verb = "would write" if args.check else "wrote"
print(f" {cfg.parent.name:<20} {verb} {written:>3}, "
f"already present {skipped:>3}"
+ (f", UNKNOWN {unknown}" if unknown else ""))
if total_unknown:
print(f"\n{len(total_unknown)} code(s) have no assignment — "
"add them to the proposal first:", file=sys.stderr)
for d, c in total_unknown:
print(f" {d}: {c}", file=sys.stderr)
return 1
return 0
if __name__ == "__main__":
raise SystemExit(main())