diff --git a/.github/workflows/validate.yml b/.github/workflows/validate.yml index 809ea66f..9bfdccc8 100644 --- a/.github/workflows/validate.yml +++ b/.github/workflows/validate.yml @@ -148,6 +148,31 @@ jobs: # the real `views/view_extension.js` under the `node` the runner already # has (skipped, never failed, where node is absent), exactly as # `tests/test_view_registry.py` and `tests/test_split_route_tails.py` do. + # § 3.4 SLICE S7 adds `tests/test_display_facet.py`, on the same footing as + # its seven neighbours. S7 is "parameterize class C": every governance word + # in the fourteen class-C files and the four declared class-A tails becomes + # a read of the registered domain's DISPLAY facet BY ROLE (RULED Q1/Q2/Q7, + # openxFactory#656 comment `5648049748`; openXdox-spec + # `docs/domain-profile-design-note.md` § 6's rule and its reason). + # `tests/test_web_boundary.py`'s assertion 4 measures the BOUNDARY — that + # no governance word survives as a literal — and would be just as green if + # every word had been DELETED. This file measures the other half: that the + # words come from somewhere, that the somewhere is the ONE registered + # profile, that the two halves of the facet (`src/opendox/display_profile.py` + # and `src/opendox/web/views/display.js`) declare the same roles in the same + # order and the same neutral words, that a declared facet is read or refused + # rather than guessed at, and — the slice's own success test — that a + # STUDENT INSTALL, whose profile declares no facet, renders openDox's own + # neutral vocabulary and no word of openxFactory's anywhere in the payload. + # § 4.3 point 5 names the failure it guards: "a fallback to TODAY'S WORDS is + # how the literals survive the refactor invisibly." + # + # `--noconftest` safe and needs no consumer: it imports `opendox`'s own + # `display_profile` alone, reads bundle files as text, and drives the real + # `views/display.js`, `views/model.js`, `views/wheel-model.js` and + # `views/staging-workbench-model.js` under the `node` the runner already has + # (skipped, never failed, where node is absent), exactly as + # `tests/test_view_registry.py` and `tests/test_split_route_tails.py` do. - name: pytest run: >- python -m pytest -q @@ -160,4 +185,5 @@ jobs: tests/test_split_route_tails.py tests/test_source_core_arm.py tests/test_gate_loop_contributed.py + tests/test_display_facet.py --noconftest diff --git a/src/opendox/canvas_drafts.py b/src/opendox/canvas_drafts.py index 5c8e022b..efc04e11 100644 --- a/src/opendox/canvas_drafts.py +++ b/src/opendox/canvas_drafts.py @@ -53,8 +53,46 @@ def supersede_reason(chosen_id: str) -> str: """The one wording shared with canvas-model.js `supersedeReason` (locked by a - cross-check in test_canvas.py).""" - return f"Option-set sibling {chosen_id} was chosen at the cluster canvas." + cross-check in test_canvas.py). + + PARAMETERIZED AT § 3.4 SLICE S7. The sentence names the GROUPING station, and + that station's word is the registered domain's. Both sides now read it from + the same display facet — the browser from `ctx.display`, this side from + `display_profile` — so the two stay byte-identical under any vocabulary + instead of being locked to one domain's spelling in two places. + """ + return (f"Option-set sibling {chosen_id} was chosen at the " + f"{_facet()['stages']['grouping']['one']} canvas.") + + +def _facet() -> dict: + """The registered domain's display facet, resolved at CALL time. + + Never at import time, and never cached: the whole value of the lazy profile + proxy is that importing this module cannot fail for want of a host, and a + module-level read would give it back. + """ + from opendox import display_profile + return display_profile.display_manifest(display_profile.host_display()) + + +def register_state(role: str) -> str: + """The wire value `possibles[].state` carries for `role` (slice S7, + Copilot round 3). + + THE DRAFT BUILDERS WRITE THE SAME ENUM THE BROWSER MATCHES ON. `states` + below used to be the literals `"superseded"` and `"latent"`, which is the + one place a host override of `values.register_state` would have split the + two halves apart: the browser would match the declared vocabulary while + this side wrote openDox's, and a newly drafted possible would be invisible + to the very install that created it. Both ends read one facet now. + """ + values = _facet()["values"]["register_state"] + if role not in values: + raise KeyError( + f"no register state is declared for the role {role!r}; the declared " + f"roles are {tuple(values)!r}") + return values[role] # --------------------------- snapshot lookups --------------------------- @@ -143,7 +181,7 @@ def build_supersede_draft(snapshot: dict, option_set_id: str, chosen_id: str) -> "id": p.get("id"), "title": p.get("title") or p.get("id"), "claim": p.get("claim") or p.get("title") or p.get("id"), - "state": "superseded", + "state": register_state("superseded"), "reason": supersede_reason(chosen_id), "citation": chosen_id, "provenance": provenance, @@ -186,7 +224,7 @@ def build_composer_draft( "id": id.strip(), "title": title.strip(), "claim": claim.strip(), - "state": "latent", + "state": register_state("captured"), "provenance": provenance, "claiming_clusters": [cluster_id], "supporting_evidence": pins or None, diff --git a/src/opendox/display_profile.py b/src/opendox/display_profile.py new file mode 100644 index 00000000..dd7ab314 --- /dev/null +++ b/src/opendox/display_profile.py @@ -0,0 +1,709 @@ +"""THE DISPLAY FACET: the host's rendered vocabulary, resolved by ROLE. + +WHY THIS FILE EXISTS. `docs/front-end-package-boundary.md` § 2.1 puts fourteen +files of `src/opendox/web/` in **class C** — *"the file's STRUCTURE is neutral — +a wheel, a funnel, a bullseye, a column strip, a sectioned outline — and its +NAMES are one domain's mapping … A class-C file stays in `openDox-code` and is +PARAMETERIZED: its vocabulary comes from the registered domain profile, never +from a literal."* That is RULING C2 applied one tier out — *"a clinician using +`MedxDox` never sees the word 'requirement'"* — and § 4.3 names the mechanism in +five steps: + + 1. The host registers its profile at process start, unchanged. + 2. `serve.py` exposes the profile's DISPLAY FACET — the stage keys with + their labels, the status vocabulary, the artifact-folder words — on the + existing `/capabilities` payload … so no new route and no second fetch. + 3. `app.js` puts that facet in the context object every binding already + receives. + 4. A class-C module resolves BY ROLE, NOT BY STRING. + 5. Refusal, not a default. + +This module is step 2's server half; `views/display.js` is its client half. Both +carry `STAGE_FIELDS` / `SNAPSHOT_FIELDS`, which is § 2.2 rule 3's OTHER half — +the snapshot's own field names, openDox's schema and not a domain's vocabulary, +declared once so that no class-C file has to spell one. + +RESOLVE BY ROLE, NOT BY STRING — the rule this module exists to make possible. +openXdox-spec `docs/domain-profile-design-note.md` § 6 states it for the Python +engine and it is unchanged here: *"`STAGED_STATUS` is not 'the string `staged`'; +it is 'the status this domain's documents carry while ORGANIZED'. A profile +whose organized status is spelled `triaged` must work with no engine change, +which a `profile.statuses["staged"]` lookup would not deliver."* Every key in +the payload below is therefore a ROLE — a neutral word naming a POSITION in the +pipeline — and every VALUE is the registered domain's own spelling of it. + +WHAT A ROLE IS HERE. Two families, and they are not the same question: + +* `STAGE_ROLES` — the six stations of the realization funnel the shell renders + (`views/model.js`'s columns, `views/wheel-model.js`'s reels, + `views/repo-selector-model.js`'s stations). A stage is a POSITION in a + pipeline: raw material, grouped material, a candidate, a selection, a + submission, a completion. openxFactory spells those `docs`, `clusters`, + `possibles`, `staged`, `proposals`, `realized`; a clinical descendant would + spell them something else and the geometry would not move. +* `STATUS_ROLES` — the lifecycle-state column of the registered profile's own + vocabulary, verbatim from openXdox-spec's design note § 6: *"the + lifecycle-state column of `document-lifecycle.md`'s own table (`captured | + organized | proposed | ratified | promoted | superseded | retired | out of + band`) is the neutral role vocabulary that makes this possible, and it is why + the schema carries a `role:` per status."* openxFactory's real profile + (`contracts/domain-profiles/openxfactory-engineering.yaml`:151-159) declares + exactly those roles against exactly those words, so a host that already has a + profile has already answered this question and the facet is a projection of an + answer rather than a second declaration. + + A status vocabulary is per ARTIFACT KIND in the profile (a governance + document, an OpenSpec change and a register possible each carry their own + closed word list), so the facet keeps that shape: `statuses[][]`. Collapsing them would make `proposed` mean `draft` and `picked` at + once, which is exactly the collision the per-kind vocabulary exists to avoid. + +ABSENT IS NEUTRAL, NOT OPENXFACTORY'S WORDS — and this is the one place this +module departs from § 4.3's point 5 ("refusal, not a default"), deliberately and +with the reason stated, because the note's own argument for that point is +narrower than its wording: + + A fallback to TODAY'S WORDS is how the literals survive the refactor + invisibly. (§ 4.3 point 5) + +The defect the point guards against is a fallback to `docs` / `clusters` / +`possibles` / `staged` / `proposals` / `realized` — openxFactory's spelling, +reappearing when no profile answers, so that nobody ever notices the +parameterization did not happen. `NEUTRAL_DISPLAY` below is the opposite of +that: it is openDox's OWN vocabulary, the neutral product's plain words for +the neutral product's own shape, and a shell that renders it is VISIBLY not +rendering a domain's. A student who installs openDox alone gets a working +funnel that says `sources → groups → candidates → selections → submissions → +completions`, which is RULING OQ-2's student install and § 2.1's own test for +class C — *"replace every governance word in it with a placeholder and the file +still renders correctly"* — performed by the product rather than asserted about +it. + +The asymmetry with `ROUTE_EXTENSIONS` is `view_extension.host_view_extensions`' +own and is argued there at length: a server missing its contributed ROUTES looks +exactly like a working one until a path 404s, whereas a shell rendering neutral +words is self-evidently rendering neutral words. **AND THE ABSENCE IS NAMED, +NEVER SILENT** — `display_manifest` carries `host_facet` = `"declared"` or +`"absent"` with the facet name and the registered profile's name, so a host +debugging a funnel that says `groups` reads the reason out of the payload the +page already fetches instead of inferring it. + +MALFORMED FAILS CLOSED. An absent facet is neutral; a facet that IS declared and +does not conform is a `DisplayFacetError` at `build_server()` time, naming the +role, the field and the value. That is `collect_view_bindings`' stance for the +same reason: a contributed declaration checked where the server is built cannot +become a browser-side mystery, and "the host meant well" is not a vocabulary. + +A CREATED FILE: no row in openxFactory's `docs/opendox-carve-manifest.yaml`, +because the manifest declares what LEAVES openxFactory and never what a +destination assembles (RULED OQ-C). +""" + +from __future__ import annotations + +import re +from typing import Any, Iterable, Mapping + +__all__ = [ + "AREA_ROLES", + "ARTIFACT_ROLES", + "DISPLAY_KIND", + "DISPLAY_SCHEMA_VERSION", + "NEUTRAL_DISPLAY", + "PROFILE_FACET", + "SECTION_ORDER", + "SNAPSHOT_VALUES", + "STAGE_FIELDS", + "STAGE_ROLES", + "STATUS_ROLES", + "TOKEN_ROLES", + "DisplayFacetError", + "display_manifest", + "host_display", + "normalize_display", +] + + +#: The facet name a host's profile carries, beside `ROUTE_EXTENSIONS`, +#: `SUBCOMMAND_EXTENSIONS` and `VIEW_EXTENSIONS` — ONE composite profile, one +#: registration, four facets, all resolved through the SAME lazy proxy (RULED +#: ASK-2 option (2), openxFactory#656 comment `5628886636`). +PROFILE_FACET = "DISPLAY" + +DISPLAY_KIND = "opendox.display-facet" +DISPLAY_SCHEMA_VERSION = 1 + +#: THE SIX STAGE ROLES, in spine order. A ROLE, never a word: `source` is "the +#: raw material this domain works from", not "the string `docs`". The order is +#: part of the declaration — `views/model.js` renders six columns left to right +#: and `views/wheel-model.js` six reels in the same order, so a renderer that +#: had to invent the axis would be inventing domain knowledge. +STAGE_ROLES: tuple[str, ...] = ( + "source", + "grouping", + "candidate", + "selection", + "submission", + "completion", +) + +#: THE NEUTRAL ROLE VOCABULARY FOR A STATUS, verbatim from the lifecycle-state +#: column openXdox-spec's design note § 6 names (`captured | organized | +#: proposed | ratified | promoted | superseded | retired | out of band`), with +#: the out-of-band pair spelled as one hyphenated role because that is how +#: openxFactory's own profile spells it +#: (`contracts/domain-profiles/openxfactory-engineering.yaml`:158-159). +STATUS_ROLES: tuple[str, ...] = ( + "captured", + "organized", + "proposed", + "ratified", + "promoted", + "superseded", + "retired", + "out-of-band", +) + +#: THE CORPUS AREAS a document may live in, by role. `views/docs.js`:18's +#: `AREA_ORDER` hardcodes `ideation/brainstorm` and `ideation/staging` — which +#: is openxFactory's own corpus layout, and RULED Q1 (openxFactory#656 comment +#: `5642758731`) is *"openDox, class A, with the area map parameterized"*. The +#: roles are the pipeline positions the folders hold, not the folders. +#: +#: `reference` is the terminal bucket — everything the declared areas do not +#: claim — and it is openDox's own, so it carries a label and never a prefix. +AREA_ROLES: tuple[str, ...] = ("captured", "organized", "proposed", "reference") + +#: THE FOUR DESIGN TOKENS, by role. `styles.css` used to define +#: `--st-brainstorm` / `--st-staged` / `--st-proposal` / `--st-realized` — four +#: names that spelled one domain's stages into the ONE styling surface RULED Q7 +#: (openxFactory#656 comment `5648049748`) calls stable: *"openDox's declared +#: design tokens (the `--st-*` family, S7) are the one stable styling surface; +#: nothing else in `styles.css` is."* Slice S7 renamed them `--st-` for +#: each of the four below. The names become roles; the VALUES stay +#: openDox's, because a colour is not a domain's word — a host may override +#: them and none has to. +TOKEN_ROLES: tuple[str, ...] = ("captured", "organized", "proposed", "completion") + +#: THE SNAPSHOT'S OWN FIELD NAMES, per stage role — § 2.2 rule 3's other half, +#: declared HERE and nowhere else on this side of the process boundary: *"A +#: SNAPSHOT SCHEMA KEY is not a stage name; a RENDERED WORD or a CORPUS PATH +#: is."* These names are openDox's schema, not a domain's vocabulary: the +#: renderer reads `snapshot.json`, a document this leg's own generator contract +#: fixes, and a descendant that renamed `clusters` would be shipping a different +#: snapshot rather than a different domain. They travel on the payload so the +#: CLIENT's schema map and this one cannot drift — the same reason +#: `view_manifest` carries `regions`. +#: +#: `status` is the closed VALUE the two change stations split on +#: (`changes[].status`), not a word anyone renders; `null` where a station reads +#: a whole collection. +STAGE_FIELDS: tuple[tuple[str, str, str | None], ...] = ( + ("source", "documents", None), + ("grouping", "clusters", None), + ("candidate", "possibles", None), + ("selection", "staged_topics", None), + ("submission", "changes", "active"), + ("completion", "changes", "archived"), +) + +#: THE SNAPSHOT'S CLOSED ENUM VALUES, by role — the rest of § 2.2 rule 3's +#: schema half, and the reason it is here rather than in the vocabulary above. +#: +#: `documents[].stage` and `possibles[].state` are VALUES the renderer MATCHES +#: (which column a card belongs in, which dot a candidate wears); they are never +#: VALUES IT RENDERS — every word a human reads comes from `statuses` above, +#: through `display.status(vocabulary, role)`. That distinction is exactly +#: § 2.2 rule 3's ("a class-A file MAY read a schema key; it may NOT carry a +#: word it renders"), read over a closed enum rather than over a field name, and +#: it is what keeps the product working: `build_server()` refuses without a +#: registered profile, but every profile in the estate today registers WITHOUT a +#: `DISPLAY` facet, so a board that filtered on the facet's neutral word would +#: show an empty first column against the very snapshot it was built to render. +#: +#: A HOST MAY STILL OVERRIDE THEM, on the `values` block of the facet, for the +#: descendant whose generator writes different words into the same schema. The +#: default is openDox's declaration, not a domain's silence. +SNAPSHOT_VALUES: dict[str, dict[str, str]] = { + # `documents[].stage` — which pipeline column a source document sits in. + "document_stage": {"captured": "brainstorm", "organized": "staged"}, + # `possibles[].state` — the candidate register's own four-state enum. + "register_state": {"captured": "latent", "proposed": "picked", + "retired": "rejected", "superseded": "superseded"}, +} + +#: THE STAGING TEMPLATE'S CANONICAL HEADING ORDER — the last member of § 2.2 +#: rule 3's schema family, and here for the same reason `SNAPSHOT_VALUES` is. +#: `views/outline-model.js` MATCHES these needles against the headings a human +#: already wrote, to decide which existing section a new one goes next to; it +#: never renders one. A domain whose staging template is shaped differently +#: overrides the list on the facet, and openDox ships the order it has always +#: shipped so that no install loses its outline ordering to a facet nobody has +#: declared yet. +SECTION_ORDER: tuple[str, ...] = ( + "last proposal attempt", "claims", "why", "what changes", "impact", + "idea notes", "conflicts", "open questions", "exit", +) + +#: openDox's OWN words — the neutral product's plain vocabulary for its own +#: shape, rendered when no host declares a `DISPLAY` facet. NOT openxFactory's +#: words, deliberately: see the module docstring's "ABSENT IS NEUTRAL" for the +#: argument, and `tests/test_display_facet.py` for the assertion that holds it +#: (no word of openxFactory's stage or status vocabulary appears here). +NEUTRAL_DISPLAY: dict[str, Any] = { + "stages": { + "source": {"one": "source item", "many": "source items", + "short": "sources", "label": "source items", + "gate": "declared topics"}, + "grouping": {"one": "group", "many": "groups", + "short": "groups", "label": "groups", "gate": None}, + "candidate": {"one": "candidate", "many": "candidates", + "short": "candidates", "label": "candidates", + "gate": "→ select gate"}, + "selection": {"one": "selection", "many": "selections", + "short": "selections", "label": "selections", + "gate": "→ submit gate"}, + "submission": {"one": "submission", "many": "submissions", + "short": "submissions", "label": "open submissions", + "gate": "→ complete gate"}, + "completion": {"one": "completed item", "many": "completed items", + "short": "completed", "label": "completed", + "gate": None}, + }, + "statuses": { + "document": { + "captured": "captured", + "organized": "organized", + "proposed": "proposed", + }, + "change": { + "proposed": "open", + "ratified": "accepted", + "promoted": "completed", + "superseded": "replaced", + }, + "candidate": { + "captured": "unselected", + "proposed": "selected", + "retired": "declined", + "superseded": "replaced", + }, + }, + "areas": { + "captured": {"prefix": None, "label": "captured material"}, + "organized": {"prefix": None, "label": "organized material"}, + "proposed": {"prefix": None, "label": "submissions"}, + "reference": {"prefix": None, "label": "other (read-only reference)"}, + }, + "tokens": { + "captured": "#7A5AD0", + "organized": "#0D9488", + "proposed": "#B96A1B", + "completion": "#3B6FD4", + }, + "acts": { + "derive": "derive candidates", + "brief": "research brief", + "promote": "promote to selection", + "propose": "start a submission", + # THE FIFTH ACT (Copilot review). `ACT_IDS` declares five verb seam + # keys and this table declared four, so `display.act("demote")` could + # not resolve, the wheel had to keep a hardcoded word, and a host that + # declared `acts.demote` was REFUSED as an unknown role. All five now. + "demote": "return to the previous station", + }, + "artifacts": { + "root": {"prefix": None, "label": "submission folder"}, + "packet": {"prefix": None, "label": "packet files", + "order": []}, + "delta": {"prefix": None, "label": "detail files"}, + "supporting": {"prefix": None, "label": "supporting files"}, + }, +} + +#: THE ARTIFACT-FOLDER VOCABULARY, by role — the axis RULED Q1's own argument +#: names ("the profile already has to carry an artifact-vocabulary axis for +#: `outline-model.js`") and the one § 2.1 says is `views/explorer.js`'s "only +#: domain content". `root` is the folder prefix a submission's files live under; +#: `packet` is its ORDERED front matter (openxFactory: `proposal.md`, +#: `design.md`, `tasks.md`); `delta` and `supporting` are the two subfolders the +#: explorer groups by. Every prefix is `None` in the neutral vocabulary, because +#: a product told no corpus layout has none — the explorer then groups by folder +#: and says so, which is the honest answer. +ARTIFACT_ROLES: tuple[str, ...] = ("root", "packet", "delta", "supporting") + +#: A design token's value: an explicit six-digit hex colour. Narrow on purpose — +#: the value is written into a CSS custom property on `:root` at boot, so a +#: permissive one is a declared injection point into the shell's own stylesheet. +_COLOUR = re.compile(r"^#[0-9A-Fa-f]{6}$") + +#: The status vocabularies the shell reads, by the ARTIFACT-KIND role each +#: belongs to. openxFactory's profile declares one closed word list per artifact +#: kind (`governance-document`, `openspec-change`, `register-possible`, …), and +#: the three the front end actually renders are these. +_STATUS_VOCABULARIES: tuple[str, ...] = ("document", "change", "candidate") + +_STAGE_FIELDS_REQUIRED: tuple[str, ...] = ("one", "many", "short", "label") + + +class DisplayFacetError(ValueError): + """A host DECLARED a `DISPLAY` facet and it does not conform. + + Distinct from the ABSENCE of the facet, which is neutral and named (see the + module docstring): this is a declaration that cannot be read, and it is + raised where the server is built rather than discovered as a column + rendering `undefined`. `ViewBindingError` is the same stance for the same + reason, and the message carries the same three things: the role, the field + and the value. + """ + + +def host_display(profile: Any = None) -> Any: + """The host's declared `DISPLAY` facet, or `None`. + + TWO ABSENCES, TWO ANSWERS, exactly as `view_extension.host_view_extensions` + documents for `VIEW_EXTENSIONS`: + + * **NO HOST REGISTERED -> REFUSES.** `domain_profile.current()` raises + `ProfileNotRegistered` naming the registration call and the runbook, and + this function lets it through untouched (ASK-2's "REFUSAL, NOT A + DEFAULT"). `build_server()` has already refused at its own read of + `ROUTE_EXTENSIONS` long before anything asks for a word. + * **HOST REGISTERED, NO `DISPLAY` FACET -> `None`,** which + `display_manifest` renders as `NEUTRAL_DISPLAY` with `host_facet: + "absent"` and the profile NAMED. Every host today is in this state — no + profile in the estate declares the facet yet — so refusing would be a flag + day imposed by the seam that exists to avoid one. + + `profile` is the seam a test injects through; absent, the module resolves the + real proxy at CALL time (never at import time — the whole value of the lazy + proxy is that importing it cannot fail for want of a host). + """ + if profile is None: + from opendox.profile_proxy import profile_openxfactory + profile = profile_openxfactory + return getattr(profile, PROFILE_FACET, None) + + +def _text(value: Any, *, where: str, allow_none: bool = False) -> str | None: + if value is None and allow_none: + return None + if not isinstance(value, str) or not value.strip(): + raise DisplayFacetError( + f"the host profile's {PROFILE_FACET} facet gives {where} the value " + f"{value!r}; a rendered word is a non-empty string. openDox reads " + "this facet BY ROLE and renders what it is handed, so a blank is a " + "blank surface rather than a refusal anyone can see.") + return value + + +def _corpus_prefix(value: Any, *, where: str) -> str | None: + """A declared corpus-path prefix, or `None`. + + MUST END IN `/` (Copilot review). A prefix is compared with `startsWith` + and composed into a path, so `"ideation/staging"` without the separator + both claims `ideation/stagingfoo/x.md` for the staging area and composes + `ideation/staging` where a folder was meant. Refused at the declaration + rather than normalised silently, because a profile that meant one of those + two things should say which, and a shell that guessed would be inventing a + corpus layout — the one thing this facet exists to stop it doing. + """ + prefix = _text(value, where=where, allow_none=True) + if prefix is not None and not prefix.endswith("/"): + raise DisplayFacetError( + f"the host profile's {PROFILE_FACET} facet gives {where} the value " + f"{prefix!r}, which does not end in `/`. A corpus prefix is matched " + "with a prefix test and composed into a path, so without the " + "separator it claims sibling folders that merely start with the " + "same letters and composes a path where a folder was meant. Declare " + f"{prefix + '/'!r}.") + return prefix + + +def _mapping(value: Any, *, where: str) -> Mapping[str, Any]: + if not isinstance(value, Mapping): + raise DisplayFacetError( + f"the host profile's {PROFILE_FACET} facet gives {where} " + f"{value!r}; a role table is a mapping of ROLE -> declaration. " + "Resolve by role, not by string (openXdox-spec " + "docs/domain-profile-design-note.md § 6).") + return value + + +def _unknown_roles(declared: Iterable[str], known: Iterable[str], + *, where: str) -> None: + extra = [role for role in declared if role not in tuple(known)] + if extra: + raise DisplayFacetError( + f"the host profile's {PROFILE_FACET} facet declares {extra!r} under " + f"{where}, which openDox does not read. The declared roles are " + f"{tuple(known)!r}: a role openDox has never heard of renders " + "nowhere, so declaring one is a silent no-op and is refused here " + "instead.") + + +def normalize_display(declared: Any) -> dict[str, Any]: + """Read a host's declared facet into the payload shape, or refuse it. + + PARTIAL IS LEGAL, AND IT IS THE POINT. A host declares the roles it has + words for and openDox fills the rest from `NEUTRAL_DISPLAY`, per role and + per field — so a descendant that has renamed only its candidate stage + declares one entry rather than a whole vocabulary, and a facet written + against a later revision of this module keeps working for the roles both + ends know. An UNKNOWN role is still refused: it renders nowhere, so + accepting it would be accepting a silent no-op. + """ + if declared is None: + return _copy_display(NEUTRAL_DISPLAY) + table = _mapping(declared, where="the facet itself") + _unknown_roles(table.keys(), + ("stages", "statuses", "areas", "tokens", "acts", + "artifacts", "values", "sections"), + where="the facet itself") + out = _copy_display(NEUTRAL_DISPLAY) + + stages = _mapping(table.get("stages", {}), where="stages") + _unknown_roles(stages.keys(), STAGE_ROLES, where="stages") + for role, entry in stages.items(): + fields = _mapping(entry, where=f"stages.{role}") + _unknown_roles(fields.keys(), + _STAGE_FIELDS_REQUIRED + ("gate",), + where=f"stages.{role}") + for field in _STAGE_FIELDS_REQUIRED: + if field in fields: + out["stages"][role][field] = _text( + fields[field], where=f"stages.{role}.{field}") + if "gate" in fields: + out["stages"][role]["gate"] = _text( + fields["gate"], where=f"stages.{role}.gate", allow_none=True) + + statuses = _mapping(table.get("statuses", {}), where="statuses") + _unknown_roles(statuses.keys(), _STATUS_VOCABULARIES, where="statuses") + for vocabulary, entry in statuses.items(): + words = _mapping(entry, where=f"statuses.{vocabulary}") + _unknown_roles(words.keys(), STATUS_ROLES, + where=f"statuses.{vocabulary}") + for role, word in words.items(): + out["statuses"][vocabulary][role] = _text( + word, where=f"statuses.{vocabulary}.{role}") + + areas = _mapping(table.get("areas", {}), where="areas") + _unknown_roles(areas.keys(), AREA_ROLES, where="areas") + for role, entry in areas.items(): + fields = _mapping(entry, where=f"areas.{role}") + _unknown_roles(fields.keys(), ("prefix", "label"), + where=f"areas.{role}") + if "label" in fields: + out["areas"][role]["label"] = _text( + fields["label"], where=f"areas.{role}.label") + if "prefix" in fields: + prefix = _corpus_prefix(fields["prefix"], + where=f"areas.{role}.prefix") + if role == "reference" and prefix is not None: + raise DisplayFacetError( + "the host profile's DISPLAY facet gives areas.reference a " + f"prefix ({prefix!r}). `reference` is the TERMINAL bucket — " + "every document the declared areas do not claim — so a " + "prefix on it would leave the documents outside every " + "declared area with nowhere to be listed.") + out["areas"][role]["prefix"] = prefix + + tokens = _mapping(table.get("tokens", {}), where="tokens") + _unknown_roles(tokens.keys(), TOKEN_ROLES, where="tokens") + for role, value in tokens.items(): + if not isinstance(value, str) or not _COLOUR.match(value): + raise DisplayFacetError( + f"the host profile's {PROFILE_FACET} facet gives tokens.{role} " + f"the value {value!r}; a design token is an explicit " + "`#rrggbb` colour. The value is written into a CSS custom " + "property on `:root` at boot, so anything wider is a declared " + "injection point into the shell's own stylesheet.") + out["tokens"][role] = value + + artifacts = _mapping(table.get("artifacts", {}), where="artifacts") + _unknown_roles(artifacts.keys(), ARTIFACT_ROLES, where="artifacts") + for role, entry in artifacts.items(): + fields = _mapping(entry, where=f"artifacts.{role}") + _unknown_roles(fields.keys(), ("prefix", "label", "order"), + where=f"artifacts.{role}") + if "label" in fields: + out["artifacts"][role]["label"] = _text( + fields["label"], where=f"artifacts.{role}.label") + if "prefix" in fields: + out["artifacts"][role]["prefix"] = _corpus_prefix( + fields["prefix"], where=f"artifacts.{role}.prefix") + if "order" in fields: + order = fields["order"] + if not isinstance(order, (list, tuple)): + raise DisplayFacetError( + f"the host profile's {PROFILE_FACET} facet gives " + f"artifacts.{role}.order {order!r}; an ORDER is a list of " + "file names, read left to right.") + out["artifacts"][role]["order"] = [ + _text(name, where=f"artifacts.{role}.order") for name in order] + + acts = _mapping(table.get("acts", {}), where="acts") + _unknown_roles(acts.keys(), tuple(NEUTRAL_DISPLAY["acts"]), where="acts") + for role, word in acts.items(): + out["acts"][role] = _text(word, where=f"acts.{role}") + return out + + +def _copy_display(source: Mapping[str, Any]) -> dict[str, Any]: + """A deep-enough copy: the payload is two levels of plain mappings. + + Written out rather than `copy.deepcopy`d so that the shape this module + promises is visible in this module, and so that a future third level fails + loudly here instead of being aliased into every served payload. + """ + return { + "stages": {role: dict(entry) + for role, entry in source["stages"].items()}, + "statuses": {vocabulary: dict(words) + for vocabulary, words in source["statuses"].items()}, + "areas": {role: dict(entry) + for role, entry in source["areas"].items()}, + "tokens": dict(source["tokens"]), + "acts": dict(source["acts"]), + "artifacts": {role: dict(entry) + for role, entry in source["artifacts"].items()}, + } + + +def _section_order(declared: Any) -> list[str]: + """The staging template's heading order, host-overridden where declared.""" + if declared is None: + return list(SECTION_ORDER) + table = _mapping(declared, where="the facet itself") + order = table.get("sections") + if order is None: + return list(SECTION_ORDER) + if not isinstance(order, (list, tuple)): + raise DisplayFacetError( + f"the host profile's {PROFILE_FACET} facet gives sections " + f"{order!r}; the staging template's heading order is a list of " + "lowercase needles, read left to right.") + return [_text(needle, where="sections") for needle in order] + + +def _snapshot_values(declared: Any) -> dict[str, dict[str, str]]: + """The snapshot's enum values, host-overridden per role where declared. + + Refuses an unknown enum or an unknown role for the same reason every other + role table does: a value openDox never matches on changes nothing, so + declaring one is a silent no-op. + """ + out = {name: dict(values) for name, values in SNAPSHOT_VALUES.items()} + if declared is None: + return out + table = _mapping(declared, where="the facet itself") + values = _mapping(table.get("values", {}), where="values") + _unknown_roles(values.keys(), tuple(SNAPSHOT_VALUES), where="values") + for name, entry in values.items(): + words = _mapping(entry, where=f"values.{name}") + _unknown_roles(words.keys(), tuple(SNAPSHOT_VALUES[name]), + where=f"values.{name}") + for role, word in words.items(): + out[name][role] = _text(word, where=f"values.{name}.{role}") + for name, words in out.items(): + _refuse_duplicate_enum_values(name, words) + return out + + +def _refuse_duplicate_enum_values(name: str, words: Mapping[str, str]) -> None: + """Two roles may not share one enum value (Copilot round 4). + + THE REVERSE LOOKUP IS WHY. `views/display.js`'s `registerRole(value)` and + `documentStageRole(value)` answer the FIRST role whose declared value + matches — which is how a view resolves a snapshot value to the word and the + class it renders. A host that mapped two roles to one value would therefore + have one role's cards silently classified as the other's: the wrong word, + the wrong `cstate-` hook, and nothing anywhere saying so. + + Checked AFTER the merge, not on the declaration alone, because the collision + that matters is between a declared value and one openDox still ships for + another role — a partial override is legal and is exactly how this arises. + """ + seen: dict[str, str] = {} + for role, word in words.items(): + if word in seen: + raise DisplayFacetError( + f"the host profile's {PROFILE_FACET} facet gives values.{name} " + f"the value {word!r} for BOTH the {seen[word]!r} and {role!r} " + "roles. The shell resolves a snapshot value back to its role to " + "decide which word and which style hook to render, and that " + "lookup answers one role — so a shared value silently renders " + "one role's items as the other's. Declare a distinct value for " + "each role, or leave the one you do not mean to override " + "undeclared (a partial declaration is legal, and the roles you " + "omit keep openDox's own values).") + seen[word] = role + + +def _declared_token_roles(declared: Any) -> list[str]: + """WHICH of the four design tokens the HOST itself declared. + + The one place in this payload where "declared" and "in effect" must be told + apart. Every other table here is a merge — the host's words over openDox's, + per role — and the shell simply renders what it is handed. The tokens are + not rendered: `views/display.js`'s `applyTokens` writes them as INLINE + custom properties on `:root`, and `styles.css` restates all four PER THEME + (light, the dark media query, and the two explicit `data-theme` choices). An + inline property on `:root` outranks every one of those rules, so writing a + token that only LOOKS declared — because the merge filled it from + `NEUTRAL_DISPLAY` — pins one theme's palette onto the install and silently + ends dark mode there. + + The browser cannot recover this from the payload alone: after the merge the + `tokens` table always carries all four keys, whether the host declared four, + one, or none. So the provenance travels WITH the words, the way + `host_facet`'s named absence does, rather than being inferred from a shape + that no longer records it (Copilot round 6). + """ + if declared is None: + return [] + table = _mapping(declared, where="the facet itself") + tokens = _mapping(table.get("tokens", {}), where="tokens") + return [role for role in TOKEN_ROLES if role in tokens] + + +def display_manifest(declared: Any, *, host_profile: str | None = None + ) -> dict[str, Any]: + """The `display` block of `/capabilities` — the ONE crossing of the boundary. + + Carries `schema_version` and `kind` because every declared document in this + estate does (openxFactory `CLAUDE.md` working rule 4), and because a payload + the shell must be able to REFUSE needs to be identifiable before it is + trusted — `view_manifest`'s own argument, applied to the vocabulary. + + `stage_order` and `fields` travel WITH the words so the client's schema map + and this one cannot drift: the client reads the snapshot through the field + names declared here, exactly as it reads the shell's regions through the + `regions` table `view_manifest` publishes rather than through a second copy. + + `host_facet` / `host_profile` are the NAMED ABSENCE: `"absent"` plus the + profile's name says a host IS registered and simply does not declare a + vocabulary, which is a different fact from no host at all, and the shell + then renders openDox's own neutral words rather than a domain's. + + `declared_tokens` is that same named absence at ROLE grain, and only the + tokens need it: see `_declared_token_roles`. + """ + merged = normalize_display(declared) + return { + "schema_version": DISPLAY_SCHEMA_VERSION, + "kind": DISPLAY_KIND, + "facet": PROFILE_FACET, + "host_facet": "declared" if declared is not None else "absent", + "host_profile": host_profile, + "stage_order": list(STAGE_ROLES), + "fields": {role: {"field": field, "status": status} + for role, field, status in STAGE_FIELDS}, + "values": _snapshot_values(declared), + "area_order": list(AREA_ROLES), + "sections": _section_order(declared), + "artifact_roles": list(ARTIFACT_ROLES), + "token_roles": list(TOKEN_ROLES), + "declared_tokens": _declared_token_roles(declared), + **merged, + } diff --git a/src/opendox/serve.py b/src/opendox/serve.py index 7803719b..07c728fd 100644 --- a/src/opendox/serve.py +++ b/src/opendox/serve.py @@ -149,6 +149,9 @@ # `/capabilities`, the one line slice S3 built both ends of and left for the # slice at which a contribution first exists to deliver. from opendox import view_extension # noqa: E402 +# § 3.4 slice S7: and the DISPLAY FACET beside it, on the same payload and for +# the same stated reason — § 4.3 step 2, "no new route and no second fetch". +from opendox import display_profile # noqa: E402 registry_mod = consumer_reach.snapshot_registry # noqa: E402 # THE BY-FUNCTION SPLIT (`split-opendox-two-layer-product` § 2.4, PRs 2 and 3 @@ -1767,6 +1770,42 @@ def build_server( host_profile=view_extension.host_profile_name(profile_openxfactory), ) + # ---- THE DISPLAY FACET, PUBLISHED (§ 3.4 slice S7) ---------------------- + # + # § 4.3 STEP 2, VERBATIM: "`serve.py` exposes the profile's DISPLAY FACET — + # the stage keys with their labels, the status vocabulary, the + # artifact-folder words — on the existing `/capabilities` payload (already + # fetched once at load by `views/notebook.js`'s `probeCapabilities`), so no + # new route and no second fetch." One more facet of the ONE registered + # profile, read through the SAME lazy proxy as `ROUTE_EXTENSIONS` and + # `VIEW_EXTENSIONS` three statements above. + # + # WHY IT RIDES BESIDE `views` RATHER THAN INSIDE IT: the two answer + # different questions of the same host. `views` is WHICH PANELS a consumer + # column contributes; `display` is WHAT THIS DOMAIN CALLS THINGS, which + # every class-C file in openDox's OWN core arm reads whether or not any + # column is contributed. A student install has no `views` and still has a + # funnel to label. + # + # ABSENT IS NEUTRAL AND NAMED, never openxFactory's words: a host with no + # `DISPLAY` facet gets `host_facet: "absent"` with its profile NAMED and + # openDox's own neutral vocabulary in the payload, so the shell comes up + # saying `sources → groups → candidates → …` — visibly un-domained rather + # than invisibly re-domained. `display_profile`'s module docstring carries + # the argument for departing from § 4.3 point 5's "refusal, not a default" + # here and nowhere else. MALFORMED still fails closed: a facet that IS + # declared and does not conform raises `DisplayFacetError` HERE, where the + # server is built, naming the role, the field and the value. + capabilities["display"] = display_profile.display_manifest( + display_profile.host_display(profile_openxfactory), + # THE NAME THROUGH THE HELPER, not a dunder (Copilot round 3 on S5 leg + # B, applied to the display block for the same reason): the lazy proxy + # refuses every dunder by design, so this read could only ever answer + # `None` and `host_facet: "absent"` was never NAMED — which is the one + # fact the named absence exists to carry. + host_profile=view_extension.host_profile_name(profile_openxfactory), + ) + bound = type("BoundDashboardHandler", (DashboardHandler,), { "checkout_root": checkout_root, "snapshot_path": snapshot_path, diff --git a/src/opendox/view_extension.py b/src/opendox/view_extension.py index 3fc3ad53..6d9804df 100644 --- a/src/opendox/view_extension.py +++ b/src/opendox/view_extension.py @@ -99,6 +99,7 @@ from typing import Any, Iterable, Protocol, runtime_checkable __all__ = [ + "CTX_KEYS", "MANIFEST_KIND", "MANIFEST_SCHEMA_VERSION", "REGIONS", @@ -211,6 +212,29 @@ #: ago) and on this table's own argument: "Declaring a region costs nothing and #: refuses nothing; an undeclared one is what costs a slice." +#: THE CONTEXT OBJECT'S DECLARED KEYS — what a binding mounted at a region may +#: read off the third argument of `mount(host, snapshot, ctx)` (RULED Q3, +#: openxFactory#656 comment `5648044785`). Mirrored in +#: `web/views/view_extension.js` and held against it by +#: `tests/test_display_facet.py`, exactly as REGIONS is. +#: +#: `display` is SLICE S7's ONE ADDITION — § 4.3 step 3, "`app.js` puts that +#: facet in the context object every binding already receives". It is the +#: vocabulary reader of `web/views/display.js`, built from the `display` block +#: `serve.build_server()` publishes on `/capabilities`, and every read on it is +#: BY ROLE: `.label(role)`, `.one(role)`, `.many(role)`, `.status(vocabulary, +#: role)`, `.area(role)`, `.token(role)`, `.items(snapshot, role)`. A +#: contributed column reads the registered domain's words the same way openDox's +#: own class-C views do, and inherits openDox's neutral words when no host +#: declares any. +CTX_KEYS: dict[str, str] = { + "caps": "the capability probe, composed-stripped where the render is composed", + "views": "the collected view registry — `lookupView(ctx.views, id)`", + "nav": "the shell's cross-view navigation verbs, or null outside a tab", + "display": "the registered domain's vocabulary, resolved BY ROLE (slice S7)", + "signal": "the render's AbortSignal, for any listener bound outside own root", +} + #: The facet name a host's profile carries, beside `ROUTE_EXTENSIONS` and #: `SUBCOMMAND_EXTENSIONS` — ONE composite profile, one registration, three #: facets, all resolved through the SAME lazy proxy (RULED ASK-2 option (2), diff --git a/src/opendox/web/app.js b/src/opendox/web/app.js index 6925f1c9..d6f5c740 100644 --- a/src/opendox/web/app.js +++ b/src/opendox/web/app.js @@ -54,6 +54,13 @@ import { ViewBindingError, collectViewBindings, contributedViewBindings, manifestRoutes, mountContributedViews, resolveView, } from "./views/view_extension.js"; +// THE VOCABULARY, resolved once per render and handed down through `ctx` +// (§ 3.4 slice S7, § 4.3 step 3). Every class-C view in this bundle reads its +// stage names, status words, corpus areas and design tokens off this object BY +// ROLE, so none of them carries one domain's word as a literal. Absent host +// facet — which is every host today, and every static served image — gives +// openDox's own neutral vocabulary, not openxFactory's words. +import { readDisplay, STAGE_ROLES } from "./views/display.js"; import { mountStagingWorkbench } from "./views/staging-workbench.js"; // THE SECOND CLASS-A -> CLASS-B IMPORT IS GONE TOO (§ 3.4 slice S5, RULED Q10). // This line was `import { firstEditTransport } from ./views/swb-session.js` — @@ -530,17 +537,66 @@ function initTheme() { // `onOpenTile` is the funnel/board tiles' drill-down entrypoint (T017): // staged/proposal/realized cards call it with (kind, id); the explorer // resolves the snapshot-only folder listing and renders the overlay. +// THE SHELL'S OWN CHROME, IN THE REGISTERED DOMAIN'S WORDS (§ 3.4 slice S7). +// `index.html` ships every one of these EMPTY: a static default beside a +// dynamic setter is two authorities for one string, and the one that renders +// first is the one that survives a domain rename unnoticed. Five of the seven +// tabs name openDox's own instruments and read the same in any domain; two name +// a STATION and are spelled by the profile. +// +// This is the whole of the shell's vocabulary surface. Every other word on the +// page is a view's, and every view takes the facet through `ctx.display`. +function applyShellVocabulary(display) { + const [SOURCE, GROUPING, CANDIDATE, , SUBMISSION] = STAGE_ROLES; + const labels = { + "tab-funnel": "realization funnel", + "tab-wheel": "the wheel", + "tab-board": "pipeline board", + "tab-canvas": display.one(GROUPING) + " canvas", + "tab-lens": "keyword lens", + "tab-docs": display.short(SOURCE) + " list", + "tab-lineage": "lineage & readiness", + }; + for (const [id, text] of Object.entries(labels)) { + const node = document.getElementById(id); + if (node) node.textContent = text; + } + // The global search reaches three stations, so it names all three. + const search = document.getElementById("globalsearch"); + if (search) { + const caption = "search " + [SOURCE, GROUPING, SUBMISSION] + .map((role) => display.short(role)).join(", ") + "…"; + search.placeholder = caption; + search.setAttribute("aria-label", caption); + } + // The one sentence in the About dialog that names stations. The rest of that + // paragraph is about `snapshot.json` and is the same in every domain. + const about = document.getElementById("aboutlinks"); + if (about) { + about.textContent = + display.one(GROUPING) + "↔" + display.one(CANDIDATE) + " links are " + + "many-to-many: one document's `Topics:` list feeds several " + + display.many(GROUPING) + " and one " + display.one(CANDIDATE) + + " can be claimed by several " + display.many(GROUPING) + + " (dashed violet edges)."; + } +} + const CORE_VIEWS = [ { id: "funnel.realization", control: "tab-funnel", region: "view-funnel", module: "./views/funnel.js", entry: "renderFunnel", view_class: "C", mount: (root, snap, ctx) => renderFunnel(root, snap, { onOpenTile: ctx.explorer.openTile, notebook: ctx.notebook, + // THE VOCABULARY (§ 3.4 slice S7) — every class-C view below takes it + // the same way, off the one context object the shell builds per render. + display: ctx.display, signal: ctx.signal }) }, { id: "wheel.deck", control: "tab-wheel", region: "view-wheel", module: "./views/wheel.js", entry: "renderWheel", view_class: "C", mount: (root, snap, ctx) => renderWheel(root, snap, { caps: ctx.caps, nav: ctx.nav, notebook: ctx.notebook, sourceBase: ctx.sourceBase, composed: ctx.composed, + display: ctx.display, // THE CONTRIBUTED DISPOSE COLUMN, already resolved (§ 3.4 slice S5). // `views/wheel.js` is class C and imported eight names out of // `views/dispose.js` — one of § 4.5 assertion 3's four breaches; it @@ -549,10 +605,16 @@ const CORE_VIEWS = [ signal: ctx.signal }) }, { id: "board.pipeline", control: "tab-board", region: "view-board", module: "./views/board.js", entry: "renderBoard", view_class: "C", - mount: (root, snap, ctx) => renderBoard(root, snap, { onOpenTile: ctx.explorer.openTile, notebook: ctx.notebook }) }, + mount: (root, snap, ctx) => renderBoard(root, snap, { + onOpenTile: ctx.explorer.openTile, notebook: ctx.notebook, + // the board's ONE cross-view jump, performed by the shell rather than by + // the view reaching for another view's tab button by DOM id (slice S7) + onOpenDocList: ctx.nav.openDocList, + display: ctx.display }) }, { id: "canvas.cluster", control: "tab-canvas", region: "view-canvas", module: "./views/canvas.js", entry: "renderCanvas", view_class: "C", - mount: (root, snap, ctx) => renderCanvas(root, snap, { notebook: ctx.notebook }) }, + mount: (root, snap, ctx) => renderCanvas(root, snap, { + notebook: ctx.notebook, display: ctx.display }) }, { id: "lens.keyword", control: "tab-lens", region: "view-lens", module: "./views/lens.js", entry: "renderLens", view_class: "?", // D21: the lens receives the UNNARROWED composed snapshot as well as the @@ -588,6 +650,7 @@ const CORE_VIEWS = [ // the `gate.lens` binding's entry, or null where no gate column is // registered — the plan panel then stays plan-only (§ 3.4 slice S4) mountLensGate: ctx.mountLensGate, + display: ctx.display, }) }, // The doc list's rows open the SAME read-only explorer/viewer overlay the // wheel's `read` verb and the workbench's docs rows open (T092 acceptance @@ -596,10 +659,12 @@ const CORE_VIEWS = [ // calls back here; `ctx.nav.openDoc` is the one entry point. { id: "docs.list", control: "tab-docs", region: "view-docs", module: "./views/docs.js", entry: "renderDocs", view_class: "A", - mount: (root, snap, ctx) => renderDocs(root, snap, { onOpenDoc: ctx.nav.openDoc }) }, + mount: (root, snap, ctx) => renderDocs(root, snap, { + onOpenDoc: ctx.nav.openDoc, display: ctx.display }) }, { id: "lineage.readiness", control: "tab-lineage", region: "view-lineage", module: "./views/lineage.js", entry: "renderLineage", view_class: "C", - mount: (root, snap) => renderLineage(root, snap) }, + mount: (root, snap, ctx) => renderLineage(root, snap, + { display: ctx.display }) }, // THE THREE CLASS-B BINDINGS ARE GONE FROM HERE — § 3.4 slice S5, and this // is the test of whether the seam was drawn in the right place. // @@ -995,7 +1060,14 @@ async function render() { // view-model module remains available to any view that wants a roll-up, // and the retired-everywhere guard in test_grouping.py pins that no // mount returns. - renderStats(document.getElementById("stats"), snapshot); + // THE STATS STRIP IS RENDERED AFTER THE FACET RESOLVES, not here (§ 3.4 + // slice S7, Copilot round 3). It used to draw in this synchronous block — + // before `probeCapabilities()` is awaited and therefore before + // `readDisplay` — so the ONE always-visible surface in the shell kept + // openDox's neutral words for the life of the page however the host spelled + // its stations, while every other view (all of which mount after the probe) + // read the declared vocabulary. It now mounts on the same footing as its + // neighbours; see `renderStats(...)` below `applyShellVocabulary`. const explorerRoot = document.getElementById("explorer-root"); // The explorer (T017) has no compile-time dependency on the viewer // (T018); app.js is what wires a selected file to renderViewer (D15 @@ -1053,6 +1125,25 @@ async function render() { // are the same object, so the list is one object named twice — harmless, // and cheaper than deciding which of the two this render produced. const consoleRepair = createConsoleRepair([probedCaps, caps]); + // THE VOCABULARY, READ ONCE PER RENDER (§ 3.4 slice S7, § 4.3 steps 2-4). + // The display facet rides on the payload already fetched two statements + // above — "no new route and no second fetch" — and is handed to every view + // through `ctx.display` below. A view asks for a stage, a status, a corpus + // area or a design token BY ROLE and is given the registered domain's own + // word for it; with no host facet it is given openDox's neutral one. + // + // THE FOUR DESIGN TOKENS ARE SET HERE, ON `:root`, BEFORE ANYTHING MOUNTS. + // § 4.3 point 4: "`styles.css`'s four `--st-*` tokens become profile-keyed + // custom properties set on `:root` at boot." `styles.css` declares + // `--st-` for each of the four roles and this line supplies the + // values, so the stylesheet names a position and the profile names a + // colour. Before `render()` is re-entered the values are simply set again. + const display = readDisplay(probedCaps); + display.applyTokens(document.documentElement); + applyShellVocabulary(display); + // …and the always-visible stats strip, on the same footing as every other + // view: after the probe, with the vocabulary handed down (Copilot round 3). + renderStats(document.getElementById("stats"), snapshot, { display }); // THE VIEW REGISTRY, COLLECTED ONCE PER RENDER (§ 3.4 slice S3, § 4.1). // The core arm openDox supplies, then the consumer column the host // contributed — the same order and the same single collection @@ -1164,13 +1255,15 @@ async function render() { // `mountStagingWorkbench`, and by the tab router's `onRegionRendered` hook // on each tab's first render. // THE CONTEXT IS THE SAME MINIMAL ONE THE PASS ALWAYS HANDED DOWN — RULED - // Q3's `mount(host, snapshot, ctx)` with the capability probe and the - // registry, and nothing of this shell's internals. What changed here is - // WHEN the pass runs, not what a contributed binding is given. + // Q3's `mount(host, snapshot, ctx)` with the capability probe, the registry + // and (slice S7) the REGISTERED DOMAIN'S VOCABULARY, and nothing of this + // shell's internals. A contributed panel renders words beside this bundle's + // own and must spell them the same way, which is the whole of why `display` + // is a declared `CTX_KEYS` entry rather than something a column re-derives. const contributedMounts = []; const mountContributedInto = async (regions) => { const mounted = await mountContributedViews( - views, snapshot, { caps, nav: null, views }, + views, snapshot, { caps, nav: null, views, display }, // `signal` is THIS render's scope (Copilot round 3): a pass started // from a tab's first render can still be loading a module when a // repository switch begins the next render, and a stale pass must not @@ -1180,7 +1273,7 @@ async function render() { return mounted; }; const explorer = mountExplorer(explorerRoot, snapshot, { - signal, + signal, display, onOpenFile: (entry, pane, tile) => { const sourceKey = sourceKeyFor(entry); return renderViewer(pane, { @@ -1395,7 +1488,7 @@ async function render() { document.getElementById("staging-workbench-root"), snapshot, { onOpenDoc: (path, doc) => explorer.openDoc(path, doc, workbenchSourceKey), - caps, active, index, signal, + caps, active, index, signal, display, // the unstripped probe, read by the workbench's `openDraft` alone createCaps: probedCaps, // the console-token re-read, forwarded to the two write transports so a @@ -1456,6 +1549,9 @@ async function render() { // composed tiles -> the tile's member repository (D10's one verb): store // the key at the member's own ref and reload — the ratified selector // posture, after which every verb works as on any single-repo view. + // board -> the doc list. The board's "open the doc list" footer used to + // click `#tab-docs` itself; app.js owns every cross-view jump. + openDocList: () => { tabs?.goto("view-docs"); }, openRepository: (repository) => { storeKey({ repository, ref: memberRef(rawSnapshot, repository) }); render(); @@ -1463,6 +1559,11 @@ async function render() { }; tabs = initTabs(snapshot, { explorer, notebook, caps, nav, composed, sourceBase: sourceBaseFor(active), + // THE ONE KEY SLICE S7 ADDS TO `ctx` (§ 4.3 step 3). Declared in + // `view_extension.js`'s CTX_KEYS beside the regions table, so a + // contributed binding reads the shell's vocabulary through the contract + // rather than through this file. Every class-C view below reads it. + display, // THE COLLECTED REGISTRY, handed to every view (§ 3.4 slice S3). The tab // router derives the tab strip from it, and a view that needs an OPTIONAL // contributed panel asks for it by id — `lookupView(ctx.views, "…")`, @@ -1540,7 +1641,7 @@ async function render() { // refresh reloads it too (the data changed, so every view must re-derive); a // FAILED refresh reports inline and leaves this view exactly as it is. repoSelector = mountRepoSelector(document.getElementById("repopicker"), { - index, active, snapshot, caps, projects, + index, active, snapshot, caps, projects, display, // the `gate.projects` binding's entry, or null where no gate column is // registered — the selector then renders picker + refresh only, which is // the whole of what § 3.4 slice S4 leaves in class A diff --git a/src/opendox/web/index.html b/src/opendox/web/index.html index 90686b79..cc41fc86 100644 --- a/src/opendox/web/index.html +++ b/src/opendox/web/index.html @@ -25,8 +25,12 @@ left EMPTY when the serving side offers no index — a static image then renders exactly today's dashboard. --> - + + @@ -52,14 +56,22 @@ aria-controls="accountmenu">👤 +
- - - - - - - + + + + + + +
\n\nBecause.\n") why = [s for s in model["sections"] if s["title"] == "Why"][0] - assert why["role"] == "proposal-element" + assert why["role"] == "marked-element" assert why["marked"] is True diff --git a/tests/test_outline_tab.py b/tests/test_outline_tab.py index bf693547..1d186ecf 100644 --- a/tests/test_outline_tab.py +++ b/tests/test_outline_tab.py @@ -782,7 +782,7 @@ def test_the_index_header_says_it_describes_the_stored_bytes(tab): def test_a_pre_template_fragment_renders_what_it_has(tab): assert [r["title"] for r in tab["pre"]["rows"]] == ["Background", "Why"] # its `xspec:`-fenced section is classified from the marker, not sniffed - assert [r["chip"] for r in tab["pre"]["rows"]] == ["added", "proposal element"] + assert [r["chip"] for r in tab["pre"]["rows"]] == ["added", "marked element"] assert tab["pre"]["viewerBody"] == 1 @@ -861,9 +861,21 @@ def test_this_slice_added_no_write_verb_and_no_transport(): assert "fetch(" not in source assert "/actions/" not in source assert "edit-apply" not in source - # the pure model stays standalone-importable for the node harness (the same - # rule staging-workbench-model.js keeps): it imports nothing at all - assert not re.findall(r"^\s*import\s", model, re.MULTILINE) + # THE PURE MODEL STAYS STANDALONE-IMPORTABLE for the node harness -- the + # same rule `staging-workbench-model.js` keeps, AMENDED AT § 3.4 SLICE S7 to + # the shape `views/helpers.js`'s own scope note now records: the five pure + # models import EXACTLY ONE sibling, `./display.js`, which is import-free by + # design. A harness that copies one of them copies display.js beside it, + # which is a two-file closure rather than a one-file one; the property this + # assertion exists to hold -- that the model pulls in no DOM, no transport + # and no view -- is unchanged and is now stated as the rule rather than as + # "nothing at all". + imports = re.findall(r'^\s*import\s[^;]*?from\s+"([^"]+)";', model, + re.MULTILINE | re.DOTALL) + assert imports == ["./display.js"], ( + f"outline-model.js imports {imports}; the pure models may import " + f"./display.js and nothing else (slice S7, views/helpers.js's scope " + f"note).") # --------------------------------------------------------------------------- diff --git a/tests/test_web_boundary.py b/tests/test_web_boundary.py index dd3722ca..080a8ecb 100644 --- a/tests/test_web_boundary.py +++ b/tests/test_web_boundary.py @@ -81,10 +81,34 @@ presence rather than a declaration, and the fixture's row-level `exempt:` not being cross-checked against `declared_exemptions` -- belong to assertion 4's own scope and are left to S7, which is the slice that - discharges it.) + discharges it -- and did; see the S7 block below.) 4. THE CENSUS DECLARES ITS TOTALS and this module re-derives them, so the class arithmetic in the fixture's header cannot drift from its rows. +SLICE S7 (`build/s7-parameterize-class-c`) closes ASSERTION 4 and, with it, the +last two of S1's four register nits -- the ones item 3 above leaves to "the +slice that discharges it". Three things changed: + + a. THE ASSERTION IS REWRITTEN TO THE RULE, not to a word search. S1's own + "NOT FIXED HERE" note asked for exactly this: "a bare identifier or + property access that only READS a snapshot schema key still trips this + sweep, even though note § 2.2 rule 3 treats a schema key as distinct from + a rendered word ... left for S7 to decide against the real vocabulary + sites it is parameterizing." The rule and its three per-language positions + are stated above `_js_spans` below, with a REGEX-LITERAL-AWARE scanner + replacing the quote-tracking strip for the sweep that has to reach zero. + Two declared, checked exemption classes carry what is left: `style_hooks` + and `prose_exemptions`, both DATA in the fixture beside their reasons. + b. THE EXEMPTION TEST CHECKS A DECLARATION (nit 3): `_declares_identifier` + demands `const`/`let`/`var`/`function`/`class` at the head of a line, so an + identifier that survives only in a comment -- or as part of a longer name + -- no longer answers for one that is gone. + c. THE ROW-LEVEL `exempt:` IS CROSS-CHECKED (nit 4): held to SET EQUALITY + against `declared_exemptions` per path, with `exempt:` accepting a list + because `views/display.js` carries eleven declared seam tables and a + scalar would have made ten of them invisible to the check that was + supposed to be watching them. + A CREATED file (this module and its fixture): no carve-manifest row (RULED OQ-C) -- the front end's package boundary did not exist before this note, so there is nothing for either file to have been carved FROM. @@ -113,9 +137,41 @@ class arithmetic in the fixture's header cannot drift from its rows. TRANSITIONAL_CLASSES = {"?", "SPLIT"} +class _NoDuplicateKeys(yaml.SafeLoader): + """`yaml.safe_load` with duplicate mapping keys REFUSED (Copilot round 3). + + The standard loader silently keeps the LAST value for a repeated key, so a + fixture that declared `"?"` twice under `totals:` read as unambiguous while + carrying two different claims — and a future drift between them could hide + behind whichever one the loader happened to keep. This census is a + DECLARATION; a declaration that says two things is worse than one that says + nothing, which is the same argument § 2.2 rule 3 makes about a silent + exemption. It happened twice on this branch, both times as a merge + artefact, which is exactly the class of defect a loader can catch and a + reviewer cannot. + """ + + +def _refuse_duplicate_keys(loader, node, deep=False): + seen = set() + for key_node, _ in node.value: + key = loader.construct_object(key_node, deep=deep) + if key in seen: + raise yaml.constructor.ConstructorError( + "while constructing a mapping", node.start_mark, + f"found a duplicate key {key!r}", key_node.start_mark) + seen.add(key) + return yaml.SafeLoader.construct_mapping(loader, node, deep=deep) + + +_NoDuplicateKeys.add_constructor( + yaml.resolver.BaseResolver.DEFAULT_MAPPING_TAG, + lambda loader, node: _refuse_duplicate_keys(loader, node)) + + def _load_census() -> dict: with CENSUS_PATH.open(encoding="utf-8") as fh: - return yaml.safe_load(fh) + return yaml.load(fh, Loader=_NoDuplicateKeys) _CENSUS = _load_census() @@ -132,6 +188,20 @@ def _load_census() -> dict: # instead, so a duplicate row is still caught rather than swallowed by this # convenience lookup. _ROWS_BY_PATH: dict[str, dict] = {row["path"]: row for row in _ROWS} +# SLICE S7's two declared exemption classes for assertion 4 (§ 4.5 point 4's +# "an exemption that is silence is how a literal survives a vocabulary sweep", +# read the other way round: an exemption that is DECLARED and CHECKED is how a +# sweep reaches zero honestly). Both are DATA in the fixture, beside a reason, +# for the same cause as the two lists above. +# +# `prose_exemptions` is keyed by (path, literal) rather than by (path, line), +# which is where openXdox-code's `PROSE_EXEMPT` -- (module, lineno) -- has to +# be re-audited on every edit that moves a line. A literal is stable under +# reflow and cannot silently start covering a DIFFERENT string. +_PROSE_EXEMPTIONS: list[dict] = _CENSUS["prose_exemptions"] +_PROSE_EXEMPT_BY_PATH: dict[str, set[str]] = {} +for _row in _PROSE_EXEMPTIONS: + _PROSE_EXEMPT_BY_PATH.setdefault(_row["path"], set()).add(_row["literal"]) def _real_web_files() -> set[str]: @@ -655,66 +725,304 @@ def _strip_html_comments(text: str) -> str: ) +# --------------------------------------------------------------------------- +# THE RULE (slice S7). Assertion 4 was a WORD SEARCH over the whole file with +# comments stripped; it is now a sweep over the positions a governance word can +# actually reach a human or a domain from, one rule per language. The reason is +# the one S1's own "NOT FIXED HERE" note left open: "a bare identifier or +# property access that only READS a snapshot schema key (`s.documents`, +# `s.clusters`) still trips this sweep, even though note § 2.2 rule 3 treats a +# schema key as distinct from a rendered word ... left for S7 to decide against +# the real vocabulary sites it is parameterizing." S7 parameterized them, and +# this is that decision, written as the rule rather than as a list. +# +# THE RULE, in the note's own terms (§ 2.2 rules 2 and 3): a class-C file may +# carry no governance word in a position a HUMAN READS, and no governance word +# in a NAME that would have to change if the domain's word changed. Everything +# else in these files -- an identifier, a property access, a DOM id, a CSS +# selector, a media feature -- is machinery, and machinery is what § 2.2 rule 3 +# distinguishes from vocabulary in the first place. +# +# `.js` STRING LITERALS ONLY, with comments AND regex literals excluded, +# minus three declared classes: a string in KEY POSITION (it names a +# seam, not a word -- openXdox-code's `test_no_hardcoded_status_words` +# excludes dict keys for exactly this reason), a declared STYLE HOOK, +# and a declared PROSE exemption. +# `.html` TEXT NODES plus the five RENDERED attributes. `id`, `class`, +# `aria-controls`, `aria-labelledby`, `for`, `name`, `data-*` and +# `href` are DOM hooks by construction: `id="tab-docs"` is the handle +# `app.js` reaches the button by, and renaming it would rename a seam, +# not a word. +# `.css` CUSTOM PROPERTY NAMES and `content:` values, and nothing else -- +# RULED Q7 (openxFactory#656 comment `5648049748`) in as many words: +# *"openDox's declared design tokens (the `--st-*` family, S7) are the +# one stable styling surface; nothing else in `styles.css` is."* A +# selector is the other end of a class string in a `.js` file and is +# held by the STYLE HOOK rule there, at the end that carries the word. +# +# WHY A REGEX-LITERAL-AWARE SCANNER. `_strip_comments_for_scan` below tracks +# quotes but not regex literals, so a `/` inside a character class or a division +# that looks like one can desynchronise the walk and blank real code or leave a +# comment unblanked. It survived S1 because S1 only ever asked "does this file +# still carry a word", which no desynchronisation could make false. A sweep that +# must reach ZERO cannot be built on it, so the span walk below is the scanner, +# and `_strip_comments_for_scan` stays exactly where it was, for the assertion +# that still uses it. + +_JS_REGEX_PREFIX = re.compile( + r"(?:[=(,:;!&|?{}\[\+\-*%<>~^]|^|\breturn\b|\btypeof\b|\bcase\b|\bin\b|\bof\b" + r"|\bnew\b|\bdelete\b|\bvoid\b|\binstanceof\b|\bdo\b|\belse\b|\byield\b" + r"|\bawait\b)\s*$" +) + + +def _js_spans(text: str) -> list[tuple[str, int, int]]: + """Every comment, string and regex-literal span in `text`, in order. + + `kind` is one of `comment`, `string`, `regex`; code between spans is not + reported. A template literal's `${...}` substitutions are walked THROUGH + rather than swallowed, so a governance word interpolated into a template is + read as the code it is and a word in the template's own text is read as the + string it is. + """ + spans: list[tuple[str, int, int]] = [] + i, n = 0, len(text) + while i < n: + c = text[i] + nxt = text[i + 1] if i + 1 < n else "" + if c == "/" and nxt == "/": + j = text.find("\n", i) + j = n if j < 0 else j + spans.append(("comment", i, j)) + i = j + continue + if c == "/" and nxt == "*": + j = text.find("*/", i + 2) + j = n if j < 0 else j + 2 + spans.append(("comment", i, j)) + i = j + continue + if c in "\"'`": + quote, j = c, i + 1 + while j < n: + if text[j] == "\\": + j += 2 + continue + if text[j] == quote: + break + if quote == "`" and text[j] == "$" and j + 1 < n and text[j + 1] == "{": + depth, k = 1, j + 2 + while k < n and depth: + if text[k] == "{": + depth += 1 + elif text[k] == "}": + depth -= 1 + k += 1 + j = k + continue + j += 1 + end = min(j + 1, n) + spans.append(("string", i, end)) + i = end + continue + if c == "/": + before = text[max(0, i - 40):i] + if _JS_REGEX_PREFIX.search(before): + j, in_class = i + 1, False + while j < n: + ch = text[j] + if ch == "\\": + j += 2 + continue + if ch == "[": + in_class = True + elif ch == "]": + in_class = False + elif ch == "/" and not in_class: + break + elif ch == "\n": + break + j += 1 + if j < n and text[j] == "/": + spans.append(("regex", i, j + 1)) + i = j + 1 + continue + i += 1 + return spans + + +#: A string literal is in KEY POSITION when the first non-space character after +#: its closing quote is a `:` AND the last non-space character before its +#: opening quote is not `?`. The first half covers every object-literal key and +#: every computed-property key in this bundle; the second excludes a ternary's +#: first branch (`cond ? "a" : "b"`), which is a value a human reads and whose +#: `:` would otherwise read as a key's. Checked against the real tree: no +#: in-scope file carries a labelled statement or a `case "x":`, the two other +#: productions a bare `:` could close. +#: +#: openXdox-code's `tests/test_no_hardcoded_status_words.py` makes the same +#: exclusion for the same reason -- there over an `ast` walk, here over text, +#: because there is no JS parser in this leg's dependency set and § 4.5's own +#: test is written to that constraint. +def _in_key_position(text: str, start: int, end: int) -> bool: + j = end + while j < len(text) and text[j] in " \t\n\r": + j += 1 + if j >= len(text) or text[j] != ":": + return False + before = text[:start].rstrip() + return not before.endswith("?") + + +def _style_hook_tokens() -> set[str]: + """Every COMPOUND class token declared in `styles.css` as a real selector. + + Compound -- it carries a `-` -- because a bare governance word is ambiguous + between a class and a value and the sweep must not guess: `"staged"` could + be a class name or the word a card renders, and only one of those is legal. + `.lchip-selection` cannot be either. + """ + css = (WEB_ROOT / "styles.css").read_text(encoding="utf-8") + return {t for t in re.findall(r"\.([A-Za-z_][A-Za-z0-9_-]*)", css) if "-" in t} + + +def _is_declared_style_hook(value: str, hooks: set[str]) -> bool: + """True when EVERY governance-word-bearing token of `value` is a declared + compound style hook. A class attribute is often several tokens + (`"swb-pane swb-pane-docs"`), and a leading `.` makes it a selector string + (`".swb-pane-docs"`, handed to `querySelector`); both are the same hook. + """ + tokens = value.split() + if not tokens: + return False + for token in tokens: + bare = token[1:] if token.startswith(".") else token + if not _GOVERNANCE_WORD_PATTERN.search(token): + continue + if bare not in hooks: + return False + return True + + +_HTML_RENDERED_ATTRS = ("placeholder", "title", "alt", "aria-label", "value") + + +def _html_read_positions(text: str) -> list[tuple[int, str]]: + """(offset, text) for every TEXT NODE and every rendered attribute value.""" + out: list[tuple[int, str]] = [] + stripped = _strip_html_comments(text) + for m in re.finditer(r">([^<]*)<", stripped): + out.append((m.start(1), m.group(1))) + attrs = "|".join(_HTML_RENDERED_ATTRS) + for m in re.finditer(rf'\b(?:{attrs})\s*=\s*"([^"]*)"', stripped): + out.append((m.start(1), m.group(1))) + return out + + +def _css_read_positions(text: str) -> list[tuple[int, str]]: + """(offset, text) for every custom-property NAME and every `content:` value.""" + stripped = _strip_comments_for_scan(text, "styles.css") + out = [(m.start(), m.group(0)) for m in re.finditer(r"--[A-Za-z0-9_-]+", stripped)] + out += [(m.start(1), m.group(1)) for m in re.finditer(r"content\s*:\s*([^;]*);", stripped)] + return out + + def _governance_literal_violations() -> list[str]: + hooks = _style_hook_tokens() violations = [] for row in _assertion_4_scope(): path = row["path"] - text = _strip_comments_for_scan( - (WEB_ROOT / path).read_text(encoding="utf-8"), path - ) - for m in _GOVERNANCE_WORD_PATTERN.finditer(text): - violations.append(f"{path}:{_line_of(text, m.start())} carries {m.group(1)!r}") + raw = (WEB_ROOT / path).read_text(encoding="utf-8") + prose = _PROSE_EXEMPT_BY_PATH.get(path, set()) + if path.endswith(".js"): + for kind, start, end in _js_spans(raw): + if kind != "string": + continue + value = raw[start + 1:end - 1] + if not _GOVERNANCE_WORD_PATTERN.search(value): + continue + if _in_key_position(raw, start, end): + continue + if _is_declared_style_hook(value, hooks): + continue + if value in prose: + continue + violations.append( + f"{path}:{_line_of(raw, start)} carries {value[:70]!r}") + elif path.endswith(".html"): + for offset, value in _html_read_positions(raw): + if not _GOVERNANCE_WORD_PATTERN.search(value): + continue + if value in prose: + continue + violations.append( + f"{path}:{_line_of(raw, offset)} renders {value.strip()[:70]!r}") + elif path.endswith(".css"): + for offset, value in _css_read_positions(raw): + if not _GOVERNANCE_WORD_PATTERN.search(value): + continue + if value in prose: + continue + violations.append( + f"{path}:{_line_of(raw, offset)} names {value.strip()[:70]!r}") + else: # pragma: no cover -- the census admits only these three kinds + raise AssertionError(f"no assertion-4 rule for {path}") return violations -@pytest.mark.xfail( - strict=True, - raises=AssertionError, - reason=( - "docs/front-end-package-boundary.md § 2.2 rule 2 / § 4.5 point 4 " - "(opensoft/openDox-spec #8 -> a44ac06d): the 14 class-C files (13 in " - "the note's own § 3.1 count, +1 for views/explorer.js under Q2's " - "ruling) and the FOUR declared class-A tails (views/docs.js, " - "views/grouping.js, views/repo-selector-model.js, and -- added by " - "slice S4 -- views/staging-workbench-model.js, whose class-C substance " - "STATUS_BRAINSTORM / BRAINSTORM_AREA / STAGING_AREA is what § 3.2's " - "own row says is left once its six class-B route constants travel; a " - "tail rather than a reclassification, so the file enters this sweep " - "for S7 instead of escaping it unremarked) carry the " - "registered profile's vocabulary as LITERALS -- COLUMN_KEYS, " - "WHEEL_KEYS/WHEEL_LABELS, board.js's four columns, styles.css's " - "four --st-* tokens, and more (every in-scope file trips at least " - "one hit today IN CODE, once `//`/`/* */`/`` prose comments " - "are excluded from the sweep by `_strip_comments_for_scan` -- added " - "on this PR's review, opensoft/openDox-code#13, after Copilot caught " - "the unstripped sweep counting explanatory comments too, e.g. " - "views/model.js's own \"docs -> clusters -> possibles -> staged " - "picks -> proposals -> realized\" pipeline sentence). The note " - "assigns closure to slice S7 (parameterize class C from the " - "registered domain profile). A bare identifier or property access " - "that only reads a snapshot schema key (`s.documents`, `s.clusters` " - "and their kind) still trips this sweep and is NOT excluded here -- " - "left for S7 (or a further amendment) to decide against the real " - "sites it parameterizes, the same fidelity-over-tidiness call " - "assertions 2 and 3 already make about their own scope." - ), -) +# S1's ORIGINAL INSTRUMENT, kept and still measured. It is the coarse word +# search this assertion used to BE, and `test_the_rule_and_the_instrument_agree` +# below holds the two together: the rule may only ever be narrower than the +# instrument, never blind to a file the instrument still sees nothing in. +def _instrument_hits(path: str) -> int: + text = _strip_comments_for_scan( + (WEB_ROOT / path).read_text(encoding="utf-8"), path) + return len(_GOVERNANCE_WORD_PATTERN.findall(text)) + + def test_no_class_c_file_carries_a_governance_literal() -> None: + """ASSERTION 4, CLOSED BY SLICE S7 -- the `xfail(strict=True)` marker came + off in the commit that closed it, which is what `strict=True` is for. + + Every governance word a class-C file used to spell is now a read of the + display facet BY ROLE (`docs/front-end-package-boundary.md` § 4.3), and the + two positions where a word survives are DECLARED in the census fixture and + checked by the two tests below: `style_hooks` (compound class tokens, each + proven a real selector) and `prose_exemptions` (keyed by path and by the + exact literal, each proven present). + """ violations = _governance_literal_violations() assert not violations, ( f"{len(violations)} governance-literal violation(s) (showing up to 20 of them):\n" + "\n".join(violations[:20]) - ) + + "\n\nEach of these is a word a human reads. Ask the display facet for " + "it BY ROLE -- `display.one(role)`, `display.status(vocabulary, role)`, " + "`display.area(role)` -- or, if it really is plain English that happens " + "to spell a watched word, declare it under `prose_exemptions` in " + "tests/fixtures/web_boundary_census.yaml beside its reason.") # --------------------------------------------------------------------------- -# Companion check -- the two declared exemptions are REAL and OUT OF SCOPE -# (note § 2.2 rule 3: "an exemption that is silence is how a literal -# survives a vocabulary sweep"). NOT one of the note's four numbered -# assertions; passes today and stays unmarked -- it is bookkeeping on the -# fixture, not a measurement of the boundary defect. +# Companion checks -- the declared exemptions are REAL, and the sweep above is +# narrower than S1's instrument without being blind. NOT among the note's four +# numbered assertions; they pass today and stay unmarked -- bookkeeping on the +# fixture and on the rule, not a measurement of the boundary defect. # --------------------------------------------------------------------------- +#: `const X`, `let X`, `var X`, `export const X`, `function X` or a class field +#: `X:` at the head of a line -- the productions that DECLARE a name in this +#: bundle. S1's own REGISTER entry names this as defect (a): "the exemption test +#: checks TEXT PRESENCE, not a DECLARATION", so an exemption naming an +#: identifier that only appears inside a comment -- or inside the word +#: `SNAPSHOT_FIELDS_OLD` -- passed. It does not now. +def _declares_identifier(text: str, identifier: str) -> bool: + pattern = re.compile( + r"^\s*(?:export\s+)?(?:const|let|var|function|class)\s+" + + re.escape(identifier) + r"\b", + re.M) + return bool(pattern.search(text)) + + def test_declared_governance_literal_exemptions_are_real_and_out_of_scope() -> None: in_scope_paths = {row["path"] for row in _assertion_4_scope()} for exemption in _EXEMPTIONS: @@ -727,7 +1035,137 @@ def test_declared_governance_literal_exemptions_are_real_and_out_of_scope() -> N ) assert exemption.get("reason"), f"declared exemption for {path} carries no reason" text = (WEB_ROOT / path).read_text(encoding="utf-8") - assert exemption["identifier"] in text, ( - f"declared exemption names {exemption['identifier']!r}, which does not " - f"appear in {path} -- the exemption is stale" + assert _declares_identifier(text, exemption["identifier"]), ( + f"declared exemption names {exemption['identifier']!r}, which {path} does " + f"not DECLARE -- only mentioning it (in a comment, or as part of a longer " + f"name) is not an exemption, it is a stale one. S1's REGISTER, defect (a)." ) + + +def test_every_row_level_exempt_matches_the_declared_exemptions_for_that_path() -> None: + """S1's REGISTER, defect (b): the census row's own `exempt:` was never + cross-checked against `declared_exemptions`, so the row could name one + identifier while the list named another -- or none -- and both halves of + the fixture would read as if the file were accounted for. + + They are held to SET EQUALITY per path here. `exempt:` accepts a list, + because `views/display.js` carries eleven declared seam tables and a scalar + would have made ten of them invisible to this check. + """ + declared: dict[str, set[str]] = {} + for exemption in _EXEMPTIONS: + declared.setdefault(exemption["path"], set()).add(exemption["identifier"]) + rows: dict[str, set[str]] = {} + for row in _ROWS: + if "exempt" not in row: + continue + value = row["exempt"] + names = set(value) if isinstance(value, list) else {value} + rows[row["path"]] = names + assert rows == declared, ( + "the census rows' `exempt:` and `declared_exemptions` disagree:\n" + + "\n".join( + f" {path}: row {sorted(rows.get(path, set()))} " + f"vs list {sorted(declared.get(path, set()))}" + for path in sorted(set(rows) | set(declared)) + if rows.get(path, set()) != declared.get(path, set()))) + + +def test_every_declared_style_hook_is_a_real_selector() -> None: + """The census enumerates the hooks that carry a governance word so a + reviewer can see them; the sweep derives the legal set from `styles.css`. + This holds the enumeration honest -- a hook that stops being a selector + stops being legal whether or not anyone remembers to edit the list.""" + hooks = _style_hook_tokens() + declared = _CENSUS["style_hooks"]["carrying_a_governance_word"] + missing = [h for h in declared if h not in hooks] + assert not missing, ( + f"{missing} are declared as style hooks carrying a governance word, but " + f"styles.css declares no `.` selector for them -- the hook is gone " + f"and the exemption it justified is stale.") + assert all(_GOVERNANCE_WORD_PATTERN.search(h) for h in declared), ( + "a hook that carries no governance word does not belong on this list: it " + "is exempt by construction and listing it makes the list read as longer " + "than the surface it describes.") + + +def test_every_prose_exemption_is_present_and_in_scope() -> None: + """Keyed by (path, literal) and checked PRESENT, so a reflow cannot move an + exemption onto a different string and a deleted sentence cannot leave a + standing licence behind.""" + in_scope_paths = {row["path"] for row in _assertion_4_scope()} + for exemption in _PROSE_EXEMPTIONS: + path, literal = exemption["path"], exemption["literal"] + assert path in in_scope_paths, ( + f"{path} is not in assertion 4's scope, so a prose exemption for it " + f"licenses nothing and only makes the fixture read as if it did.") + assert exemption.get("reason"), f"prose exemption for {path} carries no reason" + assert _GOVERNANCE_WORD_PATTERN.search(literal), ( + f"{literal!r} carries no governance word, so it needs no exemption.") + text = (WEB_ROOT / path).read_text(encoding="utf-8") + assert literal in text, ( + f"{path} no longer carries {literal!r} -- the prose exemption is stale, " + f"and a stale exemption is a standing licence for a string nobody wrote.") + + +def test_the_rule_and_the_instrument_agree() -> None: + """The rule may be NARROWER than S1's instrument -- that is the whole point + of S7 rewriting it -- but it may not be blind: a file the instrument still + sees hits in must be a file the rule has a POSITION rule for, and every + in-scope file must still be reachable by both. This is what stops a future + edit narrowing the rule until it measures nothing, which is the failure a + sweep that reaches zero is most exposed to. + """ + scope = _assertion_4_scope() + assert scope, "assertion 4's scope is empty -- the census lost its class-C rows" + assert len(scope) == 18, ( + f"assertion 4 scopes {len(scope)} files; the note's § 3.2 count is 18 " + f"(14 class-C + 4 declared class-A tails)") + # every in-scope file is one of the three languages the rule speaks + for row in scope: + assert row["path"].endswith((".js", ".html", ".css")), row["path"] + # and the instrument still finds the words -- in comments, in identifiers, + # in selectors -- which is exactly what the rule now declines to count. + still_seen = [row["path"] for row in scope if _instrument_hits(row["path"])] + assert len(still_seen) >= 14, ( + f"only {len(still_seen)} of {len(scope)} in-scope files still trip S1's " + f"coarse instrument. If the words have genuinely left the tree the rule " + f"is no longer measuring anything and this companion should be retired " + f"deliberately, not discovered later.") + + +def test_every_in_scope_file_reads_the_display_facet() -> None: + """§ 4.3's own success condition, stated as a test: a class-C file that + carries no governance literal AND asks the facet for nothing has not been + parameterized -- it has been emptied, or it never rendered a word at all + and should not be in this scope. + + The two files the rule reaches through another end are named here with + their reason: `styles.css` has no import mechanism and takes its four token + VALUES from `app.js`'s `applyTokens`, and `index.html` ships its labels + empty and takes them from `app.js`'s `applyShellVocabulary`. Both are the + shell reaching IN, which is § 4.3 step 3's own shape. + """ + through_the_shell = { + "styles.css": "--st-", + "index.html": 'id="tab-', + } + missing = [] + for row in _assertion_4_scope(): + path = row["path"] + text = (WEB_ROOT / path).read_text(encoding="utf-8") + if path in through_the_shell: + assert through_the_shell[path] in text, path + continue + # THE SIBLING IMPORT, NOT THE WORD (Copilot round 2). An `or "display" + # in text` fallback treated a comment -- or an identifier like + # `displayVocabulary` -- as proof that a file reads the facet, which is + # the exact class of "an exemption that is silence" this module exists + # to refuse. Every in-scope file that is not one of the two the shell + # reaches INTO must import `./display.js` itself. + if 'from "./display.js"' not in text: + missing.append(path) + assert not missing, ( + f"{missing} carry no governance literal and read no display facet -- a " + f"file in assertion 4's scope renders a station's words or does not " + f"belong in it (docs/front-end-package-boundary.md § 4.3 step 4).") diff --git a/tests/test_wheel_paint_and_reach.py b/tests/test_wheel_paint_and_reach.py index 03e7bed3..48aecb84 100644 --- a/tests/test_wheel_paint_and_reach.py +++ b/tests/test_wheel_paint_and_reach.py @@ -130,6 +130,13 @@ def _run(cases, tmp_path): if NODE is None: pytest.skip("node not available for the JS derivation probe") shutil.copy(WHEEL_MODEL_JS, tmp_path / "wheel-model.mjs") + # § 3.4 slice S7: `wheel-model.js` imports `./display.js` for the vocabulary + # it no longer spells. The copy keeps that sibling's OWN name (the import + # specifier is `./display.js`) and the throwaway directory declares + # `type: module`, so node reads the `.js` file as the ES module it is + # rather than falling back to CommonJS and failing on `export const`. + shutil.copy(WHEEL_MODEL_JS.parent / "display.js", tmp_path / "display.js") + (tmp_path / "package.json").write_text('{"type":"module"}', encoding="utf-8") harness = (_NODE_HARNESS .replace("TILE_H_", str(TILE_H)) .replace("TILE_W_", str(TILE_W))) diff --git a/tests/test_wheel_verbs_dom.py b/tests/test_wheel_verbs_dom.py index 49cdddbf..e2822103 100644 --- a/tests/test_wheel_verbs_dom.py +++ b/tests/test_wheel_verbs_dom.py @@ -307,7 +307,9 @@ def _run(tmp_path): # (add-ideation-intent-plane task 4.4: the tray's hosted transport). This # probe drives the LOCAL path only — no `opts.intent` is ever passed — so # the module is present purely to make the import resolve. - for name in ("dispose.js", "helpers.js", "wheel-model.js", "intent-feed.js"): + # `display.js` joins at § 3.4 slice S7 (the wheel model's vocabulary). + for name in ("dispose.js", "helpers.js", "wheel-model.js", "intent-feed.js", + "display.js"): shutil.copy(WEB / "views" / name, views / name) harness = views / "wheel-verbs.js" harness.write_text(_HARNESS, encoding="utf-8")