From e6c65ed757bfc3f9b6664e27c85111bfe5f0d465 Mon Sep 17 00:00:00 2001 From: Brett Heap <1513478+brettheap@users.noreply.github.com> Date: Fri, 11 Sep 2026 23:01:54 -0400 Subject: [PATCH 01/44] =?UTF-8?q?=C2=A7=203.4=20S3:=20the=20view=20registr?= =?UTF-8?q?y=20=E2=80=94=20ViewBinding=20+=20collectViewBindings,=20both?= =?UTF-8?q?=20halves=20of=20one=20seam?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit openDox-spec `docs/front-end-package-boundary.md` § 4.1 asks for the front-end analogue of `route_extension.collect_bindings`, and this is it — the AUTHORITY in Python, its MIRROR in the language the shell is written in, and one vocabulary held across both. THE PROBLEM, in the note's own measurement: `src/opendox/web/` is "42 blobs, 30,585 lines, and NO package boundary at all", while the Python side has answered the same question three times — a contributed ROUTE (`route_extension`), a late REACH into the consumer (`consumer_reach`), and a registered PROFILE (`domain_profile` + `profile_proxy`). § 4.1's instruction is to reuse those shapes rather than invent a fourth, so: route_extension.RouteBinding -> ViewBinding route_extension.collect_bindings -> collect_view_bindings consumer_reach.route_column -> resolveView / requireView profile_proxy.profile_openxfactory -> host_view_extensions `src/opendox/view_extension.py` is the authority. `ViewBinding` is frozen and validated where it is CONSTRUCTED, `RouteBinding.__post_init__`'s discipline; `ViewExtension` is a `runtime_checkable` Protocol and NOT an ABC, for `RouteExtension`'s reason — an extension authored in the repository that PINS this one must conform WITHOUT inheriting from anything here, since nominal conformance would make the seam the dependency it was drawn to remove. `collect_view_bindings()` flattens contributed bindings into ONE mount order and refuses four things: a non-conforming extension, a `views()` that yields anything else, two bindings claiming one (region, id) slot, and a non-class-B binding declaring a route another column contributed. THE FOURTH REFUSAL IS RULED Q3 MADE EXECUTABLE (#656 comment 5642758731): "a route constant travels with the binding that calls it, never with the model that declares it". It is derived from the assembly rather than asserted about it — the caller passes the `RouteBinding`s another column actually CONTRIBUTED, because a literal ownership table here would be a second copy of the routing that drifts the moment a column adds a route. Class B is exempt BY CONSTRUCTION: a gate-loop binding naming a gate route is the boundary working (§ 4.5 assertion 2). ORDER IS DECLARATION ORDER, FLAT, and the difference from `collect_bindings` is argued rather than inherited: that function re-orders exact before prefix because an HTTP dispatcher consults its table until something matches. Nothing here is consulted that way — a panel mounts into the ONE region it names, and two panels in one region are a refused collision rather than a race — so re-ordering would only take away the one thing declaration order is good for. THE HOST FACET, AND TWO ABSENCES WITH TWO ANSWERS. `host_view_extensions()` reads `VIEW_EXTENSIONS` off the ONE registered profile through the SAME lazy proxy `build_server()` reads `ROUTE_EXTENSIONS` through (RULED ASK-2 option (2)). NO HOST AT ALL REFUSES: `ProfileNotRegistered` is a `RuntimeError` and passes through untouched, which is ASK-2's "refusal, not a default". A HOST WITHOUT THE FACET gets an EMPTY CONSUMER COLUMN: `ProfileFacetMissing` subclasses `AttributeError` precisely so `getattr(..., default)` answers, and the empty answer is correct where an empty `ROUTE_EXTENSIONS` would be a defect — a server missing its contributed ROUTES looks fine until a path 404s, whereas a shell with no contributed PANELS is the shell this leg ships today. Refusing there would impose a flag day on every host that has not yet grown the facet, which is every host, today. AND THE ABSENCE IS NAMED, NEVER SILENT: `view_manifest()` carries `host_facet` = "declared" | "absent" with the facet and profile names, which is § 4.3 point 5's "renders its region empty WITH A NAMED REASON" applied to a facet. `src/opendox/web/views/view_extension.js` is the mirror, named by the note's own S3 row (every other module in that folder is kebab-case; this one is spelled like the two Python files it mirrors, because three files and one seam should have one spelling). It reads the manifest back out of `/capabilities` and applies the SAME four refusals to it, so both halves check the same thing against the same facts. `lookupView` is the OPTIONAL reach (null, and the caller decides what absence means); `requireView` is the REQUIRED one (a refusal that names the layering, `consumer_reach`'s posture); `resolveView` loads the binding's module at first use and refuses a binding whose named export is missing, because a binding that cannot be mounted must not look registered. A malformed manifest REFUSES while an absent one is an empty column: failing closed is the only safe answer for a payload that decides which code the shell imports, and § 4.4's vendor policy is why the module specifier is held to a bundle-relative './…js' — a contributed binding is exactly the hole "no CDN, no remote script" would otherwise leak through. BOTH FILES ARE CREATED, NOT ARRIVED: neither has a row in openxFactory's `docs/opendox-carve-manifest.yaml`, which is what Q-L1 means by "new files are created, not arrived". The census row in `tests/test_consumer_reach.py` lands in this same commit because it is a claim about this module — `opendox.view_extension` imports NOTHING from `openxdox` and reads the host's facet through the proxy, so it belongs in `NEUTRAL_MODULES` and not in `STILL_REACHING`, and the lawful direction is that the column CONTRIBUTING a view imports this module rather than the other way round. Lane: openxfactory-4-opendox-extraction Refs opensoft/openxFactory#656 Co-Authored-By: Claude Opus 5 (1M context) --- src/opendox/view_extension.py | 578 ++++++++++++++++++++++++ src/opendox/web/views/view_extension.js | 387 ++++++++++++++++ tests/test_consumer_reach.py | 8 + 3 files changed, 973 insertions(+) create mode 100644 src/opendox/view_extension.py create mode 100644 src/opendox/web/views/view_extension.js diff --git a/src/opendox/view_extension.py b/src/opendox/view_extension.py new file mode 100644 index 00000000..2e9f6b1c --- /dev/null +++ b/src/opendox/view_extension.py @@ -0,0 +1,578 @@ +"""The VIEW extension point: how a layer above the app server contributes a +PANEL instead of forking the front-end bundle (§ 3.4's view registry, openDox-spec +`docs/front-end-package-boundary.md` § 4.1, slice S3). + +WHAT THIS EXISTS TO PREVENT, in the boundary note's own words: `src/opendox/web/` +is "42 blobs, 30,585 lines, and NO package boundary at all", so "the web tier's +cross-column edges exist, they are load-bearing, and the front end has no +vocabulary for them while the Python side has three +(`route_extension.RouteBinding`, `consumer_reach`, `domain_profile.register`). +The boundary this note invents is that vocabulary." This module is the first +third of it. Three measured defects are the reason: + + (b) `views/dispose.js`:26 and `views/wheel.js`:75-76 import a module RULED to + stay at openxFactory, so the shell's own module graph does not resolve — + "the defect is that nothing in the front end could express the edge". + (c) thirteen route constants in five openDox view files address a prefix + `openxdox/serve_gate.py` owns. + (d) 48 test files across two repositories disagree about which leg owns the + bundle. + +THE SHAPE IS `route_extension.py`'s, DELIBERATELY AND ALMOST LINE FOR LINE. +That module's own sentence is the rule this one inherits: *"A contributed route +is the profile; a second copy of the dispatch is the fork."* Its front-end twin: +a contributed PANEL is the profile; a second copy of the shell is the fork. So +`ViewBinding` is `RouteBinding` (frozen, validated where it is CONSTRUCTED +rather than where it is mounted), `ViewExtension` is `RouteExtension` (a +`runtime_checkable` `Protocol`, so a binding authored in the repository that +PINS this one conforms without importing anything from here), and +`collect_view_bindings` is `collect_bindings` (one consult order, refusing what +cannot mount). Where the two differ, the difference is argued in place. + +WHY IT SITS INSIDE `opendox/` AND NOT BESIDE `route_extension.py`. +`route_extension.py` lives at the top of `src/` because BOTH sides of the carve +consume it and it travels to a repository where neither package exists — a +replica at each destination, declared by openxFactory's manifest. Nothing about +this module is symmetrical in that way: openDox DECLARES the view seam and +openXdox CONSUMES it, and openXdox already pins openDox +(`openXdox-code` `af15f712`'s `opendox` pin -> `a99eba03`). A consumer importing +the product it pins is the direction the split is FOR; it is the reverse — the +product reaching its consumer — that `consumer_reach.py` exists to make late, +named and refusable. So `from opendox import view_extension` is a legal downward +import for a contributing column, and no replica is needed. + +THE THREE THINGS A CONTRIBUTED VIEW BRINGS WITH IT, and why each is a field +rather than a convention: + +* ITS MOUNT POINT (`region`). The shell already declares them — `index.html`'s + seven `view-*` sections and its two overlay roots are exactly mount points, + each an element whose `id` is the region's name — and slice S3 makes that + declaration a CONTRACT (`REGIONS` below, held against the file by a drift + test). A binding naming a region the shell does not declare is refused here, + because + the front-end analogue of `collect_bindings`' refusal is precise: *"a declared + route silently unreachable"* becomes *"a declared panel silently unmounted"*. +* ITS ROUTES (`routes`). RULED Q3 (openxFactory#656 comment `5642758731`, + Brett Heap, 2026-09-12): **"a route constant travels with the binding that + calls it, never with the model that happens to declare it."** A binding that + declares the routes it calls is what makes that ruling checkable instead of + aspirational, and `collect_view_bindings` checks it — see + `_route_ownership_breach`. +* ITS CLASS (`view_class`). § 2.1's three destination classes: A openDox core, + B the gate loop, C a stage-named region. The class is not decoration: it is + the SCOPE of the route-ownership refusal (§ 4.5 assertion 2 — "Class B is + exempt by construction: a gate-loop file naming a gate route is the boundary + working"), and it is what a later slice reads to know what may move. + +WHAT THIS MODULE DOES NOT DO, and where it is done instead: + +* IT DOES NOT MOUNT ANYTHING. Mounting is the browser's, and the client mirror + is `src/opendox/web/views/view_extension.js` — the same vocabulary, the same + refusals, in the language the shell is written in. This half is the AUTHORITY: + it is where a host's contribution is collected and refused, and it renders the + JSON manifest the client consumes (`view_manifest`). +* IT DOES NOT ADD A ROUTE OR A FETCH. The manifest rides on the payload the + shell already fetches once at load — `/capabilities`, read by + `views/notebook.js`'s `probeCapabilities()` — exactly as the note's § 4.3 + puts the profile's display facet there: "no new route and no second fetch". + The ONE line that puts it there (`capabilities["views"] = view_manifest(...)` + in `serve.build_server`) is NOT written by slice S3: `serve.py` is a + `moved_with_declared_edit` row of openxFactory's carve manifest whose declared + lines do not cover it, and the ASK-7 declared-edit window (openxFactory#656 + comment `5642614423`) holds that row this hour. S3 builds and tests BOTH ENDS + of the seam — this module against a stub profile facet, the client against a + stub payload — and S5, the slice at which a contribution first EXISTS to + deliver, joins them in its own declared-edit window. Until then the consumer + column is empty and the core renders alone, which is what the note's S3 row + asks for in its own words: *"nothing is contributed yet, so the shell renders + exactly as today with an empty extension tuple."* + +A CREATED FILE: no row in openxFactory's `docs/opendox-carve-manifest.yaml` +(RULED OQ-C — the manifest declares what LEAVES openxFactory, never what a +destination assembles). +""" + +from __future__ import annotations + +import re +from dataclasses import dataclass +from typing import Any, Iterable, Protocol, runtime_checkable + +__all__ = [ + "MANIFEST_KIND", + "MANIFEST_SCHEMA_VERSION", + "REGIONS", + "VIEW_CLASSES", + "ViewBinding", + "ViewBindingError", + "ViewExtension", + "collect_view_bindings", + "dom_regions", + "host_view_extensions", + "view_manifest", +] + + +#: § 2.1's three destination classes, in the note's own letters. A binding says +#: which side of the boundary its module is on, and the answer is checkable +#: rather than editorial: class B is the ONLY class exempt from the +#: route-ownership refusal below (§ 4.5 assertion 2). +VIEW_CLASSES: tuple[str, ...] = ("A", "B", "C", "?") + +#: `"?"` IS THE TRANSITIONAL CLASS AND IT IS THE NOTE'S OWN, not a loophole: +#: § 4.5 assertion 1 declares it a class "the census may carry only until S4", +#: because the five SPLIT files (`explorer.js`, `lens-model.js`, `lens.js`, +#: `repo-selector.js`, `staging-workbench-model.js`, 5,711 lines) each carry +#: class-A or class-C substance AND a class-B or openxFactory-adapter tail, and +#: naming that honestly is worth more than forcing a letter. It is IN SCOPE for +#: the route-ownership refusal, exactly as § 4.5 assertion 2 says it is — +#: "class A, class C AND the transitional `?`, which is where most of the +#: breaches actually sit". Slice S4 splits the five and this entry goes. + +#: THE SHELL'S DECLARED MOUNT POINTS — the contract a contributed binding may +#: name, and the whole of it. Two kinds, and the distinction is load-bearing: +#: +#: "dom" a mount point `index.html` itself declares, as an element whose +#: `id` IS the region name — the seven `view-*` tab panels and the two +#: overlay roots, which is what the note means by "`index.html`'s +#: `view-*` sections and the two overlay roots are already exactly +#: that". `tests/test_view_registry.py` holds this tuple and that file +#: to each other, so neither can drift: a region named here with no +#: element there is a panel with nowhere to mount. +#: +#: THE SHELL IS NOT EDITED TO SAY SO, and that is deliberate rather +#: than lazy. A `data-region` attribute would be a second spelling of +#: an id the shell already carries, and `index.html` is a +#: `moved_verbatim` row of openxFactory's carve manifest +#: (`docs/opendox-carve-manifest.yaml`) whose declared-edit vocabulary +#: is the RULED closed list `import rewrites | path constants | +#: adapter calls` — an added attribute is in none of them, so +#: declaring the edit would mean inventing an edit class rather than +#: using one. The id is the declaration; the drift test is what makes +#: it a contract. +#: "shell" a mount point the SHELL creates at mount time and hands to the +#: binding — it has no standing element, so `index.html` cannot +#: declare it. `viewer-gatebar` is the viewer's own gate-bar host +#: (`views/viewer.js`:342 builds the `div` and calls `mountGate`); +#: the two `*-intent` regions are slice S2's, declared HERE and now so +#: that S2's optional intent-chip bindings fold into this registry +#: without re-opening it (§ 6 Q5: "S2 makes the chips an OPTIONAL +#: contributed binding — absent, the wheel and the tray render without +#: them"). Declaring a region costs nothing and refuses nothing; an +#: undeclared one is what costs a slice. +REGIONS: dict[str, str] = { + "view-funnel": "dom", + "view-wheel": "dom", + "view-board": "dom", + "view-canvas": "dom", + "view-lens": "dom", + "view-docs": "dom", + "view-lineage": "dom", + "explorer-root": "dom", + "staging-workbench-root": "dom", + "viewer-gatebar": "shell", + "wheel-intent": "shell", + "dispose-intent": "shell", +} + +#: 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), +#: openxFactory#656 comment `5628886636`). +PROFILE_FACET = "VIEW_EXTENSIONS" + +MANIFEST_KIND = "opendox.view-manifest" +MANIFEST_SCHEMA_VERSION = 1 + +#: A binding id: dotted, lowercase, no leading or trailing separator. Narrow on +#: purpose — the id travels into JSON, into a DOM `data-view` attribute and into +#: a refusal message, and a permissive id is how one of those three ends up +#: quoting something it must escape. +_ID = re.compile(r"^[a-z0-9]+(?:[-.][a-z0-9]+)*$") + +#: A bundle-relative ES module specifier, the only kind the shell may import. +#: `./views/gate.js`, never `/views/gate.js` (root-relative breaks a served +#: sub-path), never `https://…` and never `//…` — § 4.4's vendor policy is +#: "vendored, MIT, `html` disabled, no CDN, no external font, no remote script", +#: and a contributed binding is exactly the hole that policy would leak through +#: if the seam did not close it here. openXdox-code's +#: `test_renderer.py::test_no_external_urls_anywhere_in_bundle` greps the +#: BUNDLE; a contributed module specifier is not in the bundle, so it needs its +#: own refusal rather than that test's coverage. +_MODULE = re.compile(r"^\./[A-Za-z0-9_./-]+\.js$") + + +class ViewBindingError(ValueError): + """A binding that cannot be mounted, refused where it is DECLARED. + + One exception for every declaration defect in this module — a malformed + binding, a slot collision, an extension that does not conform, a route a + binding may not name — because a caller does nothing different for any of + them: they are all "this shell must not be assembled this way". + `route_extension.RouteBindingError`'s reasoning, unchanged. + """ + + +@dataclass(frozen=True) +class ViewBinding: + """One contributed panel: where it mounts, what module mounts it, and the + routes it calls. + + Frozen and validated in `__post_init__`, for `RouteBinding`'s reason: a + binding is declared once at assembly time and consulted on every render, so + the cheap place to find a malformed one is the first. + """ + + id: str #: unique within a region; see `_ID` + region: str #: a key of `REGIONS` + module: str #: the bundle-relative ES module that mounts it + entry: str #: the NAME of that module's export — never a callable + view_class: str #: one of `VIEW_CLASSES` + #: Every route this binding's module CALLS — RULED Q3's "a route constant + #: travels with the binding that calls it". Declared, not inferred: a + #: binding's own author knows, and the alternative is grepping a module this + #: process may not even be able to read. + routes: tuple[str, ...] = () + #: Capability keys (`/capabilities`' `actions`) or profile facets the + #: binding needs. Consulted by the CLIENT at mount; carried here because the + #: manifest is what the client reads. + requires: tuple[str, ...] = () + #: Whether the shell renders correctly WITHOUT this binding. The § 6 Q5 + #: answer made a field: an optional binding absent is a region that renders + #: without it, a required binding absent is a refusal. Slice S2's intent + #: chips are the first optional one; `gate.bar` is the second. + optional: bool = False + + def __post_init__(self) -> None: + if not isinstance(self.id, str) or not _ID.match(self.id): + raise ViewBindingError( + f"view binding id {self.id!r} must be a dotted lowercase slug " + "(e.g. 'gate.bar'): the id travels into JSON, into a DOM " + "attribute and into a refusal message") + if self.region not in REGIONS: + raise ViewBindingError( + f"view binding {self.id!r} names region {self.region!r}, which " + f"the shell does not declare (declared: {sorted(REGIONS)}). A " + "panel bound to a region that does not exist is silently " + "unmounted, which is this seam's own version of a declared " + "route that never fires") + if not isinstance(self.module, str) or not _MODULE.match(self.module): + raise ViewBindingError( + f"view binding {self.id!r} names module {self.module!r}: a " + "contributed module must be a bundle-relative './…js' " + "specifier. A root-relative path breaks a served sub-path and " + "an absolute URL is a remote script, which the vendor policy " + "(§ 4.4) forbids outright") + if ".." in self.module.split("/"): + raise ViewBindingError( + f"view binding {self.id!r} names module {self.module!r}, which " + "climbs out of the bundle with '..'") + if not isinstance(self.entry, str) or not self.entry.isidentifier(): + raise ViewBindingError( + f"view binding {self.id!r} names entry {self.entry!r}: an entry " + "is the NAME of an export on the binding's module, never a " + "callable — the same discipline `RouteBinding.handler` keeps, " + "and for the same reason: the manifest crosses a process " + "boundary as JSON") + if self.entry.startswith("__"): + raise ViewBindingError( + f"view binding {self.id!r} names entry {self.entry!r}: a dunder " + "reaches the object protocol rather than the module's own " + "surface") + if self.view_class not in VIEW_CLASSES: + raise ViewBindingError( + f"view binding {self.id!r} declares class {self.view_class!r}, " + f"not one of {list(VIEW_CLASSES)} (§ 2.1: A openDox core, " + "B the gate loop, C a stage-named region)") + if not isinstance(self.routes, tuple): + raise ViewBindingError( + f"view binding {self.id!r} declares routes {self.routes!r}, " + "which is not a tuple — a binding's declared routes are frozen " + "with it") + for route in self.routes: + if not isinstance(route, str) or not route.startswith("/"): + raise ViewBindingError( + f"view binding {self.id!r} declares route {route!r}, which " + "must be a path rooted at '/'") + if not isinstance(self.requires, tuple): + raise ViewBindingError( + f"view binding {self.id!r} declares requires {self.requires!r}, " + "which is not a tuple") + for name in self.requires: + if not isinstance(name, str) or not name: + raise ViewBindingError( + f"view binding {self.id!r} requires {name!r}, which is not " + "a capability or facet name") + if not isinstance(self.optional, bool): + raise ViewBindingError( + f"view binding {self.id!r} declares optional " + f"{self.optional!r}, which is not a bool") + + @property + def slot(self) -> tuple[str, str]: + """What makes two bindings the SAME panel — never the module. + + Two bindings claiming one (region, id) are a collision whichever modules + they name: the second is unmounted, and an unmounted panel that looks + declared is the defect `collect_view_bindings` refuses. + `RouteBinding.key`'s reasoning, one tier out. + """ + return (self.region, self.id) + + def as_manifest_entry(self) -> dict[str, Any]: + """The JSON the client reads. Lists, not tuples — this is a payload.""" + return { + "id": self.id, + "region": self.region, + "module": self.module, + "entry": self.entry, + "view_class": self.view_class, + "routes": list(self.routes), + "requires": list(self.requires), + "optional": self.optional, + } + + +#: The one method a view extension declares. Named here rather than derived +#: from the Protocol, so a refusal can quote it — `route_extension.MEMBERS`' +#: reason, unchanged. +MEMBERS: tuple[str, ...] = ("views",) + + +@runtime_checkable +class ViewExtension(Protocol): + """One method. Nothing else, ever. + + A `runtime_checkable` `Protocol` and NOT an ABC, for exactly + `route_extension.RouteExtension`'s reason: an extension authored in the + repository that PINS this one must be able to conform WITHOUT inheriting + from anything here. Structural conformance is the property the seam exists + for; nominal conformance would make the seam the dependency it was drawn to + remove. + """ + + def views(self) -> tuple[ViewBinding, ...]: + """Every panel this extension contributes, in its own declared order. + + Called ONCE at assembly time, never per render: the set of contributed + panels is a property of how the shell was assembled, and an extension + that answered differently on a later call would make the mount table + unreadable. + """ + + +def _route_ownership_breach(binding: ViewBinding, + contributed_routes: Iterable[Any]) -> Any | None: + """The first contributed route this binding may not name, or `None`. + + § 2.2 RULE 1 — *"A class-A or class-C file may not name a route ANOTHER + COLUMN declares"* — and § 4.5 assertion 2's scope, verbatim: every binding + whose class is not B. **Class B is exempt BY CONSTRUCTION: a gate-loop + binding naming a gate route is the boundary working.** + + WHAT COUNTS AS "ANOTHER COLUMN DECLARES" IS NOT A LITERAL TABLE HERE, and + that is the point. The note's § 3.3 writes the ownership table out by hand + because a design note has nothing else to write it against; this seam has + something better — the `RouteBinding`s another column actually CONTRIBUTED + through `route_extension.collect_bindings`. A table would be a second copy + of the routing, drifting the moment a column adds a route; the contributed + bindings ARE the routing. So the caller passes what it collected, and the + refusal is derived from the assembly rather than asserted about it. + + Matching is `RouteBinding.matches`' own semantics without its method + argument: a view binding declares the PATH it calls, and which HTTP method + it uses is the binding's own business — a path under a contributed POST + prefix is that column's whether the view GETs it or POSTs it. + + Deliberately takes the contributed bindings STRUCTURALLY (`pattern`, + `is_prefix`) rather than by `isinstance(RouteBinding)`: the client mirror + reads the same three fields out of JSON, and holding the two halves to one + matching rule is worth more than a type check this module cannot make of a + payload anyway. + """ + if binding.view_class == "B": + return None + for route in binding.routes: + for contributed in contributed_routes: + pattern = getattr(contributed, "pattern", None) + if not isinstance(pattern, str): + raise ViewBindingError( + f"contributed route {contributed!r} carries no string " + "pattern, so no view binding can be checked against it") + is_prefix = bool(getattr(contributed, "is_prefix", False)) + if route == pattern or (is_prefix and route.startswith(pattern)): + return contributed + return None + + +def _ownership_message(binding: ViewBinding, contributed: Any) -> str: + pattern = getattr(contributed, "pattern", "?") + return ( + f"view binding {binding.id!r} is class {binding.view_class} and " + f"declares route {pattern!r}, which another column contributed. RULED " + "Q3 (openxFactory#656 comment 5642758731): a route constant travels " + "with the BINDING THAT CALLS IT, never with the model that happens to " + "declare it — so this route belongs to a class-B binding that column " + "supplies, and this binding asks the registry for it. § 2.2 rule 1: a " + "class-A or class-C file may not name a route another column declares; " + "class B is exempt by construction.") + + +def collect_view_bindings(extensions, *, + contributed_routes: Iterable[Any] = ()) -> tuple[ViewBinding, ...]: + """Flatten the extensions into ONE mount order, refusing what cannot mount. + + `collect_bindings`' contract, one tier out. Refuses an object that does not + conform, a `views()` that yields anything but `ViewBinding`s, two bindings + claiming one (region, id) slot, and — the refusal this seam adds — a + non-class-B binding declaring a route another column contributed + (`_route_ownership_breach`). + + ORDER IS DECLARATION ORDER, FLAT. `collect_bindings` re-orders (every exact + binding before every prefix one) because an HTTP dispatcher consults its + table until something matches and a prefix must not swallow a sibling's + exact route. Nothing here is consulted that way: a panel mounts into the ONE + region it names, and two panels in one region are a refused collision rather + than a race. Re-ordering would therefore only take away the one thing + declaration order is good for — the order panels appear in a region — so it + is kept, and the CORE arm is first because the caller passes it first. + + `contributed_routes` is what `route_extension.collect_bindings` returned for + this same assembly, or the equivalent read out of a manifest. Empty — slice + S3's own case, and every static image's — means no column has claimed a + route, so no view binding can breach rule 1 and the check is a no-op rather + than a silent pass: there is nothing to breach. + """ + collected: list[ViewBinding] = [] + #: The FULL previous binding, not just its module — so a collision message + #: names what the previous binding was actually declared as. + seen: dict[tuple[str, str], ViewBinding] = {} + routes = tuple(contributed_routes) + for extension in extensions: + if not isinstance(extension, ViewExtension): + raise ViewBindingError( + f"{extension!r} does not conform to ViewExtension: it must " + f"declare {list(MEMBERS)}") + declared = extension.views() + for binding in declared: + if not isinstance(binding, ViewBinding): + raise ViewBindingError( + f"{extension!r} contributed {binding!r}, which is not a " + "ViewBinding") + previous = seen.get(binding.slot) + if previous is not None: + raise ViewBindingError( + f"two view bindings claim region {binding.region!r} slot " + f"{binding.id!r}: {previous.module!r} and " + f"{binding.module!r}. The second could never mount, and a " + "panel that looks declared and never renders is worse than " + "one that refuses.") + breach = _route_ownership_breach(binding, routes) + if breach is not None: + raise ViewBindingError(_ownership_message(binding, breach)) + seen[binding.slot] = binding + collected.append(binding) + return tuple(collected) + + +def dom_regions() -> tuple[str, ...]: + """The regions `index.html` itself declares, in `REGIONS`' declared order. + + The subset a contributed binding can mount into without the shell building a + host for it — each one an element of the shell whose `id` is the region's + name. `tests/test_view_registry.py` holds this against the file. + """ + return tuple(name for name, kind in REGIONS.items() if kind == "dom") + + +def host_view_extensions(profile: Any = None) -> tuple[Any, ...]: + """The host's contributed view extensions — ONE more facet of the ONE + registered profile, resolved through the SAME lazy proxy. + + TWO ABSENCES, TWO ANSWERS, and the asymmetry with `ROUTE_EXTENSIONS` is + deliberate and argued: + + * **NO HOST REGISTERED -> REFUSES.** `domain_profile.current()` raises + `ProfileNotRegistered` naming the registration call and the runbook, and + this function lets it through untouched. That is ASK-2's "REFUSAL, NOT A + DEFAULT" and it needs no help from here: `build_server()` already refuses + at its own read of `ROUTE_EXTENSIONS`, three statements before anything + could ask for a view. + * **HOST REGISTERED, NO `VIEW_EXTENSIONS` FACET -> AN EMPTY CONSUMER + COLUMN.** `profile_proxy.ProfileFacetMissing` subclasses `AttributeError` + precisely so that `getattr(profile, name, default)` answers, and its own + docstring blesses the spelling. The empty answer is CORRECT here where an + empty `ROUTE_EXTENSIONS` would be a defect, because the two absences mean + different things: a server missing its contributed ROUTES looks exactly + like a working one until someone requests a path that 404s, whereas a + shell with no contributed PANELS is the shell this leg ships today and the + state the note's S3 row describes in its own words — *"nothing is + contributed yet, so the shell renders exactly as today with an empty + extension tuple."* Refusing here would make every host that has not yet + grown the facet — which is every host, today — unable to serve at all: a + flag day imposed by the seam that was added to avoid one. + + **AND THE ABSENCE IS NAMED, NEVER SILENT.** `view_manifest` carries + `host_facet` = "declared" or "absent" with the facet name and the + registered profile's name, so a host debugging a panel that never appeared + reads the reason out of the payload the page already fetches instead of + inferring it. That is the honest middle the note's own § 4.3 point 5 asks + for — "a class-C module with no profile registered renders its region + empty WITH A NAMED REASON" — applied to a facet rather than to a profile. + + `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 + declared = getattr(profile, PROFILE_FACET, None) + if declared is None: + return () + return tuple(declared) + + +def view_manifest(bindings: Iterable[ViewBinding], *, + contributed_routes: Iterable[Any] = (), + host_facet: str = "absent", + host_profile: str | None = None) -> dict[str, Any]: + """The payload the client reads — the ONE crossing of the process 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. + + `contributed_routes` travels with the views so the CLIENT can apply the same + § 2.2 rule 1 refusal to a binding it reads out of this payload — the two + halves check the same thing against the same facts, which is what keeps a + seam from becoming two seams. + + `host_facet` / `host_profile` are the NAMED ABSENCE `host_view_extensions` + argues for: "absent" plus the profile's name says a host IS registered and + simply does not contribute panels, which is a different fact from no host at + all and a different fact again from a host that contributes none. + """ + if host_facet not in ("declared", "absent"): + raise ViewBindingError( + f"host_facet {host_facet!r} must be 'declared' or 'absent': the " + "manifest states WHY the consumer column is empty, and a third " + "answer would say nothing") + return { + "schema_version": MANIFEST_SCHEMA_VERSION, + "kind": MANIFEST_KIND, + "facet": PROFILE_FACET, + "host_facet": host_facet, + "host_profile": host_profile, + "regions": {name: kind for name, kind in REGIONS.items()}, + "contributed_routes": [ + { + "method": getattr(route, "method", None), + "pattern": getattr(route, "pattern", None), + "is_prefix": bool(getattr(route, "is_prefix", False)), + } + for route in contributed_routes + ], + "views": [binding.as_manifest_entry() for binding in bindings], + } diff --git a/src/opendox/web/views/view_extension.js b/src/opendox/web/views/view_extension.js new file mode 100644 index 00000000..0d2f33c5 --- /dev/null +++ b/src/opendox/web/views/view_extension.js @@ -0,0 +1,387 @@ +// THE VIEW REGISTRY — the front end's `route_extension.py`, in the language the +// shell is written in (openDox-spec `docs/front-end-package-boundary.md` § 4.1, +// slice S3; RULED openxFactory#656 comment 5642758731). +// +// THE FILE NAME IS THE NOTE'S, not this folder's convention. Every other module +// here is kebab-case (`repo-selector.js`, `wheel-model.js`); the note's S3 row +// names `views/view_extension.js` and it is named that, because the whole point +// of the file is that it MIRRORS `src/route_extension.py` and +// `src/opendox/view_extension.py` — three files, one seam, one spelling. +// +// WHAT IT IS FOR. The bundle is 42 files in one flat folder with one import +// graph, "no subdirectory, no manifest, no naming convention, no lint rule and +// no test that says which module may import which" (§ 1.2(a)). The Python side +// answered the same question three times — a contributed ROUTE +// (`route_extension`), a late REACH into the consumer (`consumer_reach`), and a +// registered PROFILE (`domain_profile` + `profile_proxy`) — and § 4.1 says to +// reuse those shapes rather than invent a fourth. So: +// +// `route_extension.RouteBinding` -> a ViewBinding +// `route_extension.collect_bindings` -> collectViewBindings +// `consumer_reach.route_column` -> resolveView / requireView, which +// make a reach into a column that may +// not be installed LATE, NAMED and +// REFUSABLE instead of an import +// +// THE ONE RULE, and the reason the shell stops importing class-B modules: a +// contributed panel is the profile; a second copy of the shell is the fork. A +// binding declares WHERE it mounts, WHAT module mounts it, WHICH routes it +// calls (RULED Q3: "a route constant travels with the binding that calls it, +// never with the model that happens to declare it") and WHETHER the shell is +// correct without it. The shell then renders whatever it collected — so an +// install with no gate column comes up with no gate bar, no dispose tray and no +// 404, which is RULING C2 one tier out and the thing § 3.4 exists to protect. +// +// THE AUTHORITY IS `src/opendox/view_extension.py`, NOT THIS FILE. That module +// collects the host's contributions server-side, refuses the same four things, +// and renders the JSON manifest this file reads back out of `/capabilities` +// (`contributedViewBindings`). The two halves are held to one vocabulary by +// `tests/test_view_registry.py`, which parses the constants below and compares +// them with the Python ones — a drift test, on the pattern openxFactory's +// `carved_reach.py` scrub list already uses. +// +// A CREATED FILE: no row in openxFactory's `docs/opendox-carve-manifest.yaml` +// (RULED OQ-C). + +// § 2.1's three destination classes: A openDox core, B the gate loop, C a +// stage-named region. Kept in step with `view_extension.py`'s `VIEW_CLASSES`. +// `"?"` is the TRANSITIONAL class § 4.5 assertion 1 declares — "a class the +// census may carry only until S4" — carried because the five SPLIT files each +// hold class-A or class-C substance AND a class-B tail. It is IN SCOPE for the +// route-ownership refusal, as § 4.5 assertion 2 says: "class A, class C AND the +// transitional `?`, which is where most of the breaches actually sit." +export const VIEW_CLASSES = ["A", "B", "C", "?"]; + +// THE SHELL'S DECLARED MOUNT POINTS, and the whole of them. A `"dom"` region is +// declared by `index.html` itself, as an element whose `id` IS the region name +// — the seven `view-*` tab panels and the two overlay roots. A `"shell"` region +// has no standing element: the shell builds the host at mount time and hands it +// to the binding. `tests/test_view_registry.py` holds this table against +// `index.html` and against the Python half, so the three never drift apart. +// +// `viewer-gatebar` is the viewer's own gate-bar host (`viewer.js` builds the +// div and calls `mountGate`). `wheel-intent` and `dispose-intent` are slice +// S2's, declared NOW so S2's optional intent-chip bindings fold in without +// re-opening this file: § 6 Q5 rules that "the chips become an OPTIONAL +// contributed binding — absent, the wheel and the tray render without them", +// and `optional: true` plus `lookupView()` is exactly that shape. Declaring a +// region costs nothing; an undeclared one costs a slice. +export const REGIONS = { + "view-funnel": "dom", + "view-wheel": "dom", + "view-board": "dom", + "view-canvas": "dom", + "view-lens": "dom", + "view-docs": "dom", + "view-lineage": "dom", + "explorer-root": "dom", + "staging-workbench-root": "dom", + "viewer-gatebar": "shell", + "wheel-intent": "shell", + "dispose-intent": "shell", +}; + +export const MANIFEST_KIND = "opendox.view-manifest"; +export const MANIFEST_SCHEMA_VERSION = 1; + +// Narrow on purpose, and identical to the Python `_ID`: the id travels into +// JSON, into a refusal message and into a DOM attribute. +const ID = /^[a-z0-9]+(?:[-.][a-z0-9]+)*$/; +// A bundle-relative ES module specifier and nothing else. No root-relative path +// (it breaks a served sub-path), no absolute URL — § 4.4's vendor policy is "no +// CDN, no external font, no remote script", and a contributed binding is +// exactly the hole that policy would leak through if this seam did not close +// it. +const MODULE = /^\.\/[A-Za-z0-9_./-]+\.js$/; + +// One error for every declaration defect, for `RouteBindingError`'s reason: a +// caller does nothing different for any of them — they are all "this shell must +// not be assembled this way". +export class ViewBindingError extends Error { + constructor(message) { + super(message); + this.name = "ViewBindingError"; + } +} + +function refuse(message) { + throw new ViewBindingError(message); +} + +// One contributed panel, validated where it is DECLARED rather than where it is +// mounted — `RouteBinding.__post_init__`'s discipline, for the same reason: a +// binding is declared once at assembly time and consulted on every render. +// +// `mount` and `control` are the two fields the MANIFEST does not carry and the +// core arm does. `mount` is a function the shell already imported (the core arm +// holds its own view modules statically, and always will — they are the +// product); `control` is the id of the tab button that activates the panel, so +// the tab strip is derived from the registry instead of duplicated beside it. +// A CONTRIBUTED binding has neither: it arrives as JSON and is loaded through +// `resolveView`. +export function viewBinding(spec) { + const b = spec || {}; + if (typeof b.id !== "string" || !ID.test(b.id)) { + refuse("view binding id " + JSON.stringify(b.id) + " must be a dotted " + + "lowercase slug (e.g. 'gate.bar')"); + } + if (!Object.prototype.hasOwnProperty.call(REGIONS, b.region)) { + refuse("view binding " + JSON.stringify(b.id) + " names region " + + JSON.stringify(b.region) + ", which the shell does not declare " + + "(declared: " + Object.keys(REGIONS).join(", ") + "). A panel bound to " + + "a region that does not exist is silently unmounted."); + } + if (typeof b.module !== "string" || !MODULE.test(b.module) + || b.module.split("/").includes("..")) { + refuse("view binding " + JSON.stringify(b.id) + " names module " + + JSON.stringify(b.module) + ": a contributed module must be a " + + "bundle-relative './…js' specifier that does not climb out of the " + + "bundle. An absolute URL is a remote script, which § 4.4's vendor " + + "policy forbids outright."); + } + if (typeof b.entry !== "string" || !/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(b.entry) + || b.entry.startsWith("__")) { + refuse("view binding " + JSON.stringify(b.id) + " names entry " + + JSON.stringify(b.entry) + ": an entry is the NAME of an export on the " + + "binding's module, never a callable — the manifest crosses a process " + + "boundary as JSON."); + } + if (!VIEW_CLASSES.includes(b.view_class)) { + refuse("view binding " + JSON.stringify(b.id) + " declares class " + + JSON.stringify(b.view_class) + ", not one of " + VIEW_CLASSES.join("/") + + " (§ 2.1: A openDox core, B the gate loop, C a stage-named region)"); + } + const routes = b.routes === undefined ? [] : b.routes; + if (!Array.isArray(routes) || routes.some((r) => typeof r !== "string" || !r.startsWith("/"))) { + refuse("view binding " + JSON.stringify(b.id) + " declares routes " + + JSON.stringify(routes) + ": every declared route is a path rooted at '/'"); + } + const requires = b.requires === undefined ? [] : b.requires; + if (!Array.isArray(requires) || requires.some((r) => typeof r !== "string" || !r)) { + refuse("view binding " + JSON.stringify(b.id) + " declares requires " + + JSON.stringify(requires) + ": every entry is a capability or facet name"); + } + const optional = b.optional === undefined ? false : b.optional; + if (typeof optional !== "boolean") { + refuse("view binding " + JSON.stringify(b.id) + " declares optional " + + JSON.stringify(optional) + ", which is not a boolean"); + } + if (b.mount !== undefined && typeof b.mount !== "function") { + refuse("view binding " + JSON.stringify(b.id) + " declares a mount that is " + + "not a function; a contributed binding declares no mount at all and is " + + "loaded through resolveView()"); + } + if (b.control !== undefined && typeof b.control !== "string") { + refuse("view binding " + JSON.stringify(b.id) + " declares a control that " + + "is not an element id"); + } + return Object.freeze({ + id: b.id, + region: b.region, + module: b.module, + entry: b.entry, + view_class: b.view_class, + routes: Object.freeze(routes.slice()), + requires: Object.freeze(requires.slice()), + optional, + mount: b.mount, + control: b.control, + // What makes two bindings the SAME panel — never the module. Two bindings + // claiming one (region, id) are a collision whichever modules they name. + slot: b.region + "\u0000" + b.id, + }); +} + +// § 2.2 RULE 1 — "a class-A or class-C file may not name a route ANOTHER COLUMN +// declares" — with § 4.5 assertion 2's scope verbatim: every binding whose class +// is not B. Class B is exempt BY CONSTRUCTION; a gate-loop binding naming a gate +// route is the boundary working. +// +// "Another column declares" is not a hardcoded table here for the reason the +// Python half gives at length: the contributed `RouteBinding`s ARE the routing, +// and a table beside them would be a second copy that drifts. The client reads +// them out of the manifest (`contributed_routes`), which is the same list +// `route_extension.collect_bindings` returned server-side. +function ownershipBreach(binding, contributedRoutes) { + if (binding.view_class === "B") return null; + for (const route of binding.routes) { + for (const claimed of contributedRoutes) { + const pattern = claimed && claimed.pattern; + if (typeof pattern !== "string") { + refuse("contributed route " + JSON.stringify(claimed) + " carries no " + + "string pattern, so no view binding can be checked against it"); + } + if (route === pattern + || (claimed.is_prefix && route.startsWith(pattern))) { + return pattern; + } + } + } + return null; +} + +// Flatten the extensions into ONE mount order, refusing what cannot mount — +// `collect_bindings`' contract, one tier out. +// +// An extension is anything with a `views()` returning an array of binding specs; +// structural conformance, never nominal, for `RouteExtension`'s reason: a +// binding authored in the column that PINS openDox must conform without +// importing anything from here. +// +// ORDER IS DECLARATION ORDER, FLAT. `collect_bindings` re-orders exact before +// prefix because an HTTP dispatcher consults its table until something matches; +// nothing here is consulted that way — a panel mounts into the ONE region it +// names, and two panels in one region are a refused collision rather than a +// race. So declaration order is kept, and it is the order panels appear in a +// region. +export function collectViewBindings(extensions, options) { + const contributedRoutes = (options && options.contributedRoutes) || []; + const collected = []; + const seen = new Map(); + for (const extension of extensions || []) { + if (!extension || typeof extension.views !== "function") { + refuse(JSON.stringify(String(extension)) + " does not conform to a view " + + "extension: it must declare views()"); + } + const declared = extension.views(); + if (!Array.isArray(declared)) { + refuse("a view extension's views() must return an array of bindings, got " + + JSON.stringify(String(declared))); + } + for (const spec of declared) { + const binding = viewBinding(spec); + const previous = seen.get(binding.slot); + if (previous) { + refuse("two view bindings claim region " + JSON.stringify(binding.region) + + " slot " + JSON.stringify(binding.id) + ": " + + JSON.stringify(previous.module) + " and " + + JSON.stringify(binding.module) + ". The second could never mount, " + + "and a panel that looks declared and never renders is worse than " + + "one that refuses."); + } + const breach = ownershipBreach(binding, contributedRoutes); + if (breach) { + refuse("view binding " + JSON.stringify(binding.id) + " is class " + + binding.view_class + " and declares route " + JSON.stringify(breach) + + ", which another column contributed. RULED Q3 " + + "(openxFactory#656 comment 5642758731): a route constant travels " + + "with the BINDING THAT CALLS IT, never with the model that happens " + + "to declare it."); + } + seen.set(binding.slot, binding); + collected.push(binding); + } + } + return collected; +} + +// THE CONSUMER COLUMN, read out of the payload the shell already fetches once at +// load. § 4.3's rule for the profile's display facet applies here unchanged — +// "no new route and no second fetch" — so the view manifest rides on +// `/capabilities` beside the capability verdict. +// +// ABSENT MEANS AN EMPTY COLUMN, NOT A REFUSAL, and that is the honest reading in +// three different situations that all look the same from here: a static served +// image (no `/capabilities` at all), a host whose profile carries no +// `VIEW_EXTENSIONS` facet, and — today — every host, because the server-side +// line that publishes the manifest is slice S5's (see `view_extension.py`'s own +// note on why). MALFORMED, by contrast, REFUSES: a payload that claims to be a +// view manifest and is not is a contribution nobody can reason about, and +// failing closed is the only safe answer for something that decides which code +// the shell imports. +export function contributedViewBindings(capabilities) { + const manifest = capabilities && capabilities.views; + if (manifest === undefined || manifest === null) return []; + if (typeof manifest !== "object" || Array.isArray(manifest)) { + refuse("the /capabilities payload carries a `views` that is not a view " + + "manifest object"); + } + if (manifest.kind !== MANIFEST_KIND) { + refuse("the /capabilities `views` payload declares kind " + + JSON.stringify(manifest.kind) + ", not " + JSON.stringify(MANIFEST_KIND)); + } + if (manifest.schema_version !== MANIFEST_SCHEMA_VERSION) { + refuse("the /capabilities `views` payload declares schema_version " + + JSON.stringify(manifest.schema_version) + ", and this shell reads " + + MANIFEST_SCHEMA_VERSION + ". A shell that guessed at an unknown " + + "manifest version would be importing code it cannot describe."); + } + const views = manifest.views; + if (!Array.isArray(views)) { + refuse("the /capabilities `views` payload carries no views array"); + } + return views.map(viewBinding); +} + +// The contributed routes the manifest travelled with — what `collectViewBindings` +// checks § 2.2 rule 1 against, so both halves of the seam check the same thing +// against the same facts. +export function manifestRoutes(capabilities) { + const manifest = capabilities && capabilities.views; + const routes = manifest && manifest.contributed_routes; + return Array.isArray(routes) ? routes : []; +} + +// An OPTIONAL reach: the binding, or null. This is `consumer_reach`'s posture +// in the browser — a reach into a column that may not be installed is LATE and +// NAMED, and the caller decides what absence means. § 6 Q5's intent chips and +// the gate bar are both read this way. +export function lookupView(bindings, id) { + for (const binding of bindings || []) { + if (binding.id === id) return binding; + } + return null; +} + +// A REQUIRED reach: the binding, or a refusal that names the layering rather +// than a blank panel. `consumer_reach`'s "refuses with the layering spelled out +// instead of raising ModuleNotFoundError from an import line a thousand lines +// away from the call", and `build_server()`'s "refusal, not a default". +export function requireView(bindings, id) { + const found = lookupView(bindings, id); + if (found) return found; + refuse("no view binding " + JSON.stringify(id) + " is registered. This shell " + + "was assembled without the column that contributes it; a binding that is " + + "correct to be absent must declare `optional: true` and be read with " + + "lookupView()."); +} + +// Load a binding's module and hand back its namespace — the front end's +// `route_extension.resolve_handlers`, deferred to first use rather than done at +// wiring time, because a browser pays for an import and a process does not. +// +// Returns null for an absent OPTIONAL binding, so a caller can write +// const gate = await resolveView(views, "gate.bar"); +// and then treat `gate` being null as "no gate column here" — which is exactly +// what a student install is. An absent REQUIRED binding refuses through +// `requireView`. +// +// The specifier is resolved against the BUNDLE ROOT (`./views/gate.js` is what +// `app.js` would have written), not against this module's own folder. +export async function resolveView(bindings, id) { + const binding = lookupView(bindings, id); + if (!binding) return null; + const bundleRoot = new URL("../", import.meta.url); + const exports = await import(new URL(binding.module, bundleRoot).href); + if (!(binding.entry in exports)) { + refuse("view binding " + JSON.stringify(binding.id) + " names entry " + + JSON.stringify(binding.entry) + ", which " + + JSON.stringify(binding.module) + " does not export. A binding that " + + "cannot be mounted must not look registered."); + } + return { binding, exports }; +} + +// The element a "dom" region mounts into: the shell element whose `id` is the +// region's name. A "shell" region has no standing element by definition, so +// asking for one is a caller error rather than an absence — and saying so is +// worth a refusal, because the alternative is a null the caller reads as "the +// column is not installed". +export function regionHost(binding, doc) { + if (REGIONS[binding.region] !== "dom") { + refuse("region " + JSON.stringify(binding.region) + " is a shell region: " + + "it has no standing element, and the shell hands its host to the " + + "binding at mount time"); + } + return (doc || document).getElementById(binding.region); +} diff --git a/tests/test_consumer_reach.py b/tests/test_consumer_reach.py index 589a22b5..cfc1e7f6 100644 --- a/tests/test_consumer_reach.py +++ b/tests/test_consumer_reach.py @@ -114,6 +114,14 @@ def _import_in_subprocess(module: str, *, consumer_blocked: bool) -> subprocess. # because openXdox PINS openDox (§ 4.2, RULED OQ-2). "opendox.domain_profile", "opendox.profile_proxy", + # § 3.4 slice S3, the view registry. Listed here for the reason this list + # gives itself — "a module added to this package's import surface is added + # to this census" — and it belongs at the top of the list rather than in + # `STILL_REACHING`: it reads the host's `VIEW_EXTENSIONS` facet through + # `opendox.profile_proxy` and imports NOTHING from `openxdox`. The column + # that CONTRIBUTES a view imports this module, not the other way round, + # which is the lawful direction because openXdox pins openDox. + "opendox.view_extension", ) #: Modules that STILL require the consumer at import time, with the reason. They From 18f00bb6f20db72c30b6d0188e1abeee49dde10b Mon Sep 17 00:00:00 2001 From: Brett Heap <1513478+brettheap@users.noreply.github.com> Date: Fri, 11 Sep 2026 23:02:21 -0400 Subject: [PATCH 02/44] =?UTF-8?q?=C2=A7=203.4=20S3:=20the=20shell=20stops?= =?UTF-8?q?=20importing=20the=20gate=20module=20=E2=80=94=20line=2043=20be?= =?UTF-8?q?comes=20a=20registry=20lookup?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit § 4.1 names this edit by line number: "app.js stops importing class-B modules directly. Its line 43 becomes a lookup in the collected bindings, and a shell built with no gate binding registered renders the tab strip WITHOUT the gate bar rather than failing to load." That is what this commit does, and nothing else. THE HARDCODED `TABS` TABLE BECOMES THE CORE ARM OF THE REGISTRY. `CORE_VIEWS` holds the same seven views as `ViewBinding`s and is collected through `collectViewBindings()` alongside whatever the consumer column contributed — the same order and the same SINGLE collection `serve.build_server()` uses for routes, and for the same reason: a collision between a contributed panel and one of the shell's own must be refused before anything mounts, rather than discovered as a panel that silently never rendered. A core binding declares its `module` and `entry` truthfully even though it also carries a `mount` closure, because a CONTRIBUTED binding carries only those two and is loaded through `resolveView()` — the core arm always holds its own view modules statically, since they are the product. THE TAB STRIP IS DERIVED FROM THE REGISTRY, not declared beside it. A tab is simply a binding that declared a `control`; a binding with no control — the gate bar, and every overlay binding after it — is in the collected order and is not a tab, which is why the filter is one expression in `initTabs` and not a second list to keep in step. THE GATE BAR IS A BINDING NOW: class B, `optional: true`, declaring `/actions/gate/ratify` as RULED Q3's "a route constant travels with the binding that calls it". Three things are true that were not true before. A shell assembled without it renders the viewer with NO GATE BAR instead of failing to load — `views/viewer.js` already tolerates a null `mountGate` (`const mountGate = o.mountGate || null`), so the absence was always representable downstream and was simply unreachable from here, and no second file is touched. `gate.js`:120's route says in one checkable place whose it is. And the entry sits in the CORE arm TRANSITIONALLY: slice S5 moves the four class-B files behind a binding openXdox supplies, at which point this entry is deleted and the identical binding arrives through `contributedViewBindings()` with nothing else in this file changing — which is the test of whether the seam was drawn in the right place. `routes` IS DELIBERATELY UNDECLARED ON EVERY CORE TAB BINDING and that is not an omission. Q3 makes `routes` a declaration of OWNERSHIP, not a transitive inventory of every path a module's import graph happens to touch. Exactly one core binding owns a route that way today: `gate.bar`. The census's eighteen remaining route-ownership breaches are FILE-level facts (§ 4.5 assertion 2), measured by slice S1's `tests/test_web_boundary.py` and cleared by S4 and S6; declaring them here would encode S4's answers before S4 has done its work, and would refuse this very assembly, since `/source/` is a contributed prefix today. THE COLLECTED REGISTRY IS HANDED TO EVERY VIEW as the context key `views`, so an OPTIONAL contributed panel is asked for by id — `lookupView(ctx.views, "…")`, null when the column that supplies it is not installed. Slice S2's intent chips are the first such reader: `wheel-intent` and `dispose-intent` are declared regions already, so S2 adds an optional binding and two `lookupView` calls and touches nothing here. The consumer column is read out of the `/capabilities` payload this render already fetched (§ 4.3's "no new route and no second fetch"). It is EMPTY at this slice and on every static image, so the shell renders exactly as it did before — the note's S3 row in its own words: "nothing is contributed yet, so the shell renders exactly as today with an empty extension tuple". The server-side line that publishes a manifest (`capabilities["views"] = view_manifest(...)`) is slice S5's, inside `serve.py`'s own declared-edit window, which the in-flight ASK-7 act owns this hour. `index.html` IS NOT TOUCHED. A `data-region` attribute would be a second spelling of an id the shell already carries, and an added attribute is in none of the RULED `edit_classes` (`import rewrites | path constants | adapter calls`), so declaring it would mean inventing an edit class rather than using one. The id is the declaration; the registry's `REGIONS` table plus a drift test against the shell's existing ids is what makes it a contract. Q-L1: `src/opendox/web/app.js` is an ARRIVED file. Its 37 edited lines are declared on its row of openxFactory's `docs/opendox-carve-manifest.yaml` by openxFactory PR #1001, which lands FIRST — one `import rewrites` line (43) and 36 `adapter calls` lines. `verify-carve-arrival.py`'s `_check_declared_lines` over all 123 `opendox_code` rows against this branch: app.js DECLARED, 60 verbatim rows byte-identical, 0 refusals. Lane: openxfactory-4-opendox-extraction Refs opensoft/openxFactory#656 Co-Authored-By: Claude Opus 5 (1M context) --- src/opendox/web/app.js | 189 ++++++++++++++++++++++++++++++++++------- 1 file changed, 158 insertions(+), 31 deletions(-) diff --git a/src/opendox/web/app.js b/src/opendox/web/app.js index beac5c76..316b5fa2 100644 --- a/src/opendox/web/app.js +++ b/src/opendox/web/app.js @@ -40,7 +40,19 @@ import { renderViewer } from "./views/viewer.js"; import { createEditAction } from "./views/edit.js"; import { renderCanvas } from "./views/canvas.js"; import { renderLens } from "./views/lens.js"; -import { isGateBearing, mountGateBar } from "./views/gate.js"; +// THE GATE BAR IS NOT IMPORTED HERE ANY MORE (§ 3.4 slice S3, the view +// registry). This line was `import { isGateBearing, mountGateBar } from +// "./views/gate.js"` — the shell's ONE direct import of a class-B module, and +// § 4.1's named example: "app.js stops importing class-B modules directly. Its +// line 43 becomes a lookup in the collected bindings, and a shell built with no +// gate binding registered renders the tab strip WITHOUT the gate bar rather +// than failing to load." It is now the `gate.bar` binding of CORE_VIEWS below, +// resolved through `resolveView` at render time; when slice S5 moves the gate +// loop behind a binding openXdox supplies, the binding leaves the core arm and +// nothing else in this file changes. +import { + collectViewBindings, contributedViewBindings, manifestRoutes, resolveView, +} from "./views/view_extension.js"; import { mountStagingWorkbench } from "./views/staging-workbench.js"; import { firstEditTransport } from "./views/swb-session.js"; import { createModelIntakeTransports } from "./views/swb-model-intake.js"; @@ -467,26 +479,62 @@ 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. -const TABS = [ - { tab: "tab-funnel", view: "view-funnel", - render: (root, snap, ctx) => renderFunnel(root, snap, { +// ---- THE CORE ARM OF THE VIEW REGISTRY (§ 3.4 slice S3) ---- +// This was the hardcoded seven-entry `TABS` table, read by the tab router and +// by nothing else. It is now the CORE ARM of the view registry — the fixed +// bindings openDox itself supplies — collected through `collectViewBindings()` +// alongside whatever the consumer column contributes, exactly as +// `serve.build_server()` collects `profile.ROUTE_EXTENSIONS` and the caller's +// `route_extensions` through ONE `route_extension.collect_bindings()`. +// +// WHAT EACH FIELD IS. `id` + `region` are the slot (two bindings claiming one +// slot is a refused collision); `control` is the tab button that activates the +// panel, so the tab strip is DERIVED from the registry rather than duplicated +// beside it; `module` + `entry` name the module that mounts the panel and the +// export that does it — truthfully, because a CONTRIBUTED binding carries only +// those and is loaded through `resolveView()`; `view_class` is § 2.1's census +// class; `mount` is the shell's own adapter closure, which only a core binding +// has (its module is already imported above — the core arm always holds its own +// view modules statically, because they are the product). +// +// `routes` IS DELIBERATELY UNDECLARED ON EVERY CORE TAB BINDING, and it is not +// an omission. RULED Q3 makes `routes` "the routes that travel WITH the binding +// that calls them" — a declaration of ownership, not a transitive inventory of +// every path a module's import graph happens to touch. Today exactly one core +// binding owns a route that way: `gate.bar`. The census's eighteen remaining +// route-ownership breaches are FILE-level facts (§ 4.5 assertion 2) measured by +// slice S1's `tests/test_web_boundary.py` and cleared by S4 and S6; declaring +// them here would encode S4's answers before S4 has done its work, and would +// refuse this assembly outright, since `/source/` is a contributed prefix today. +// +// `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. +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, signal: ctx.signal }) }, - { tab: "tab-wheel", view: "view-wheel", - render: (root, snap, ctx) => renderWheel(root, snap, + { 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, signal: ctx.signal }) }, - { tab: "tab-board", view: "view-board", - render: (root, snap, ctx) => renderBoard(root, snap, { onOpenTile: ctx.explorer.openTile, notebook: ctx.notebook }) }, - { tab: "tab-canvas", view: "view-canvas", - render: (root, snap, ctx) => renderCanvas(root, snap, { notebook: ctx.notebook }) }, - { tab: "tab-lens", view: "view-lens", + { 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 }) }, + { 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 }) }, + { 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 // rendered one. Its repository rail is the control surface for the // visible set, so it must see every member — the narrowed view could only // ever shrink further, never restore a repository the human unticked. - render: (root, snap, ctx) => renderLens(root, snap, { + mount: (root, snap, ctx) => renderLens(root, snap, { caps: ctx.caps, composedSnapshot: ctx.rawSnapshot, visible: ctx.visible, @@ -518,9 +566,37 @@ const TABS = [ // sweep, defect 7 — the rows advertised themselves as clickable and were // inert). app.js owns every cross-view jump, so the view declares the row and // calls back here; `ctx.nav.openDoc` is the one entry point. - { tab: "tab-docs", view: "view-docs", - render: (root, snap, ctx) => renderDocs(root, snap, { onOpenDoc: ctx.nav.openDoc }) }, - { tab: "tab-lineage", view: "view-lineage", render: (root, snap) => renderLineage(root, snap) }, + { 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 }) }, + { id: "lineage.readiness", control: "tab-lineage", region: "view-lineage", + module: "./views/lineage.js", entry: "renderLineage", view_class: "C", + mount: (root, snap) => renderLineage(root, snap) }, + // THE GATE BAR — class B, OPTIONAL, and the proof this slice exists to give. + // `app.js`'s line 43 used to import `isGateBearing` and `mountGateBar` + // straight out of `views/gate.js`; § 4.1 names that import as the one the + // registry replaces, so it is a binding now, resolved rather than imported. + // Three properties follow, and each is a thing that was not true before: + // + // * `optional: true` — a shell assembled WITHOUT it renders the viewer with + // no gate bar instead of failing to load. `views/viewer.js` already + // tolerates a null `mountGate` (`const mountGate = o.mountGate || null`), + // so nothing there changes: the absence was always representable + // downstream and was simply unreachable from here. + // * `routes: ["/actions/gate/ratify"]` — RULED Q3's "a route constant + // travels with the binding that calls it". `gate.js`:120's + // `GATE_RATIFY_ROUTE` is the gate loop's, and it now says so in the one + // place the registry can check. + // * it is in the CORE arm and that is TRANSITIONAL. `gate.js` is still a + // file of this bundle; slice S5 moves the four class-B files behind a + // binding openXdox supplies, at which point this entry is deleted and the + // identical binding arrives through `contributedViewBindings()`. Nothing + // else in this file changes when it does — which is the test of whether + // the seam was drawn in the right place. + { id: "gate.bar", region: "viewer-gatebar", + module: "./views/gate.js", entry: "mountGateBar", view_class: "B", + routes: ["/actions/gate/ratify"], requires: ["actions.gate"], + optional: true }, ]; // Tab router with the WAI-ARIA roving-tabindex pattern (a11y #19): only the @@ -571,23 +647,30 @@ function storeTab(view) { function initTabs(snapshot, ctx, signal) { const controllers = {}; const rendered = new Set(); - const tabEls = TABS.map((t) => document.getElementById(t.tab)); + // THE TAB STRIP IS DERIVED FROM THE REGISTRY, not declared beside it (§ 3.4 + // slice S3). `ctx.views` is the COLLECTED order — this shell's core arm plus + // whatever the consumer column contributed — and a tab is simply a binding + // that declared a `control`. A binding with no control (the gate bar, and + // every overlay binding after it) is in `ctx.views` and is not a tab, which + // is why the filter is here and not a second list. + const TABS = ctx.views.filter((b) => b.control); + const tabEls = TABS.map((t) => document.getElementById(t.control)); let current = TABS[0]; let searchTerm = ""; function applySearch() { - const c = controllers[current.view]; + const c = controllers[current.region]; if (typeof c?.search === "function") c.search(searchTerm); } function show(target, focusTab) { current = target; - storeTab(target.view); + storeTab(target.region); TABS.forEach((t, i) => { - const isTarget = t.tab === target.tab; + const isTarget = t.control === target.control; tabEls[i].setAttribute("aria-selected", String(isTarget)); tabEls[i].tabIndex = isTarget ? 0 : -1; - document.getElementById(t.view).hidden = !isTarget; + document.getElementById(t.region).hidden = !isTarget; }); // The LENS takes the whole page (Brett, 2026-08-08: "when we are on the // lens screen we want to remove anything not lens related… give as much @@ -596,14 +679,15 @@ function initTabs(snapshot, ctx, signal) { // and say nothing about a keyword or repository set, so the lens hides // them and takes the height back. document.querySelector(".wrap") - ?.classList.toggle("lensfull", target.view === "view-lens"); - if (focusTab) document.getElementById(target.tab).focus(); + ?.classList.toggle("lensfull", target.region === "view-lens"); + if (focusTab) document.getElementById(target.control).focus(); // lazy render on first activation; funnel edge geometry needs a visible layout - if (!rendered.has(target.view)) { - controllers[target.view] = target.render(document.getElementById(target.view), snapshot, ctx); - rendered.add(target.view); - } else if (controllers[target.view]?.redraw) { - controllers[target.view].redraw(); + if (!rendered.has(target.region)) { + controllers[target.region] = target.mount( + document.getElementById(target.region), snapshot, ctx); + rendered.add(target.region); + } else if (controllers[target.region]?.redraw) { + controllers[target.region].redraw(); } applySearch(); } @@ -628,7 +712,7 @@ function initTabs(snapshot, ctx, signal) { // Open where the human was, if that view still exists on this plane — a tab // list can differ between planes, and a remembered view that is gone falls // back to the first exactly as before. - const remembered = TABS.find((t) => t.view === storedTab()); + const remembered = TABS.find((t) => t.region === storedTab()); show(remembered || TABS[0], false); return { @@ -637,7 +721,7 @@ function initTabs(snapshot, ctx, signal) { // (rendering it on first activation, exactly like a click) and returns that // view's controller so the caller can hand it a preselection. goto(view) { - const target = TABS.find((t) => t.view === view); + const target = TABS.find((t) => t.region === view); if (!target) return null; show(target, false); return controllers[view] || null; @@ -840,8 +924,19 @@ async function render() { repository: snapshot.repository, ref: "main", }); }; + // THE GATE BAR, THROUGH THE REGISTRY (§ 3.4 slice S3). `gateView` is + // assigned just below, after the capability probe that carries the consumer + // column; both closures here only run from inside `mountExplorer`'s + // `onOpenFile` callback, which cannot fire before then. NULL is the + // student's install: no gate column registered, so no gate context is ever + // built and `mountGate` is not supplied — and `views/viewer.js` already + // reads a null `mountGate` as "render the document without a gate bar" + // (`const mountGate = o.mountGate || null`). That is § 4.2's refusal turned + // into an outcome: an absent column is an absent panel, never a blank page. + let gateView = null; const gateContext = (tile, entry, key) => - tile?.kind === "proposal" && isGateBearing(entry.path) && key + tile?.kind === "proposal" && gateView + && gateView.exports.isGateBearing(entry.path) && key ? { changeId: tile.id, repository: key.repository } : null; // The ONE capability probe (#1): a same-origin GET the local backend answers @@ -863,6 +958,26 @@ 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 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 + // `serve.build_server()` uses for routes, and for the same reason: a + // collision between a contributed panel and one of this shell's own must be + // refused HERE, before anything mounts, rather than discovered as a panel + // that silently never rendered. + // + // The consumer column is read out of the `/capabilities` payload this + // render already fetched (§ 4.3's "no new route and no second fetch"). It + // is EMPTY at this slice and on every static image, so the shell renders + // exactly as it did before — which is what the note's S3 row asks for: + // "nothing is contributed yet, so the shell renders exactly as today with + // an empty extension tuple". The server-side line that publishes a manifest + // is slice S5's, in `serve.py`'s own declared-edit window. + const views = collectViewBindings( + [{ views: () => CORE_VIEWS }, + { views: () => contributedViewBindings(probedCaps) }], + { contributedRoutes: manifestRoutes(probedCaps) }); + gateView = await resolveView(views, "gate.bar"); const explorer = mountExplorer(explorerRoot, snapshot, { signal, onOpenFile: (entry, pane, tile) => { @@ -873,7 +988,11 @@ async function render() { sourceBase: sourceBaseFor(sourceKey), edit: createEditAction({ caps, key: sourceKey }), gate: gateContext(tile, entry, sourceKey), - mountGate: (host, gctx) => mountGateBar(host, gctx, { caps }), + // Supplied only when a gate binding was collected; absent, the viewer + // renders the document and no gate bar (see `gateView` above). + mountGate: gateView + ? (host, gctx) => gateView.exports.mountGateBar(host, gctx, { caps }) + : null, }); }, }); @@ -1100,6 +1219,14 @@ async function render() { }; tabs = initTabs(snapshot, { explorer, notebook, caps, nav, composed, sourceBase: sourceBaseFor(active), + // 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, "…")`, + // null when the column that supplies it is not installed. Slice S2's + // intent chips are the first such reader: `wheel-intent` and + // `dispose-intent` are declared regions already, so S2 adds an optional + // binding and two `lookupView` calls and touches nothing here. + views, // the UNSTRIPPED probe and the serve's own writable repository — read by // exactly one affordance (see `createCaps` at the lens's mount) probedCaps, From cb810d39737bf50bbe87e5700177c2e5ce2750da Mon Sep 17 00:00:00 2001 From: Brett Heap <1513478+brettheap@users.noreply.github.com> Date: Fri, 11 Sep 2026 23:03:27 -0400 Subject: [PATCH 03/44] =?UTF-8?q?=C2=A7=203.4=20S3:=20the=20registry's=20t?= =?UTF-8?q?ests,=20and=20validate=20names=20them=20in=20the=20same=20commi?= =?UTF-8?q?t?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 50 assertions over the seam, and the file is added to `validate`'s explicit `--noconftest` list in THIS commit rather than a later one — the discipline § 4.5 states for slice S1 ("added to that list in the SAME commit") and the one its three neighbours already keep: `test_leg_shape.py`, `test_consumer_reach.py` and `test_profile_registration.py` each arrived that way. A test that is not in the list is not run, and a seam nobody runs is a description. WHAT IS ASSERTED, in six groups. 1. A malformed binding refuses WHERE IT IS DECLARED and the message says why — parametrized over every field: the id grammar, an undeclared region, a module specifier that is root-relative / absolute / climbs out of the bundle with `..`, an entry that is a callable rather than the NAME of an export, an unknown class, non-tuple routes, a route not rooted at '/'. 2. Collection: a non-conforming extension names the member it lacks; two bindings in one (region, id) slot refuse and the message names BOTH modules; one id in two different regions is NOT a collision; the core arm comes through an EMPTY consumer column unchanged; and collecting nothing at all is an empty tuple rather than a refusal, which is this slice's own case and every static image's. 3. RULED Q3, executable: a class-A binding declaring a gate route another column contributed is REFUSED, and the refusal quotes the rule. Class C and the transitional `?` are in scope too (§ 4.5 assertion 2's "class A, class C AND the transitional `?`, which is where most of the breaches actually sit"); a class-B binding declaring the SAME route is allowed, because a gate-loop binding naming a gate route is the boundary working. With no contributed routes nothing can breach — there is nothing to breach. 4. The host facet through the ONE registered profile: the facet comes off it; a host WITHOUT the facet contributes an empty column; NO host at all REFUSES rather than answering empty (ASK-2's "refusal, not a default"); and importing the registry resolves no profile at all, which is the whole value of the lazy proxy. The manifest declares its `schema_version` and `kind` and NAMES the absence rather than being silent about it. 5. Drift, so the two halves cannot diverge: both declare the same regions in the same order and the same classes; every "dom" region is an element `index.html` actually carries (the id IS the declaration — this is what makes the unedited shell a contract rather than an assumption); no "shell" region pretends to have one; every core tab binding names a dom region, or it would be a blank tab; `app.js` no longer imports the gate module, declares the gate bar as an OPTIONAL class-B binding, and wires the doc list through the registry. 6. The JavaScript half driven by the REAL file under `node`, skipped and never failed where node is absent: the core arm collects with an empty consumer column; a slot collision and a contributed gate route both refuse; a malformed `/capabilities` manifest refuses while an absent one is an empty column; ONE VIEW WIRED END TO END — `resolveView` loads the real `views/docs.js` from its binding and hands back the `renderDocs` export; a contributed panel mounts into its region under a minimal DOM; an absent OPTIONAL binding is null and an absent REQUIRED one refuses; and a "shell" region asked for a standing element refuses rather than returning a null the caller would read as "the column is not installed". One of the drift assertions is a REAL DEFECT kept as a test rather than a memory: the client's slot key joins a binding's region and id with a separator neither can contain, and that separator was first written as a LITERAL NUL BYTE in the source instead of as the six-character escape sequence a JavaScript string literal spells it with. Everything parsed and every other assertion passed — but `git`, `grep`, `file(1)` and every diff viewer classify a file containing a NUL as BINARY, so the module would have reached review as an unreadable blob. A separator that cannot occur in a region or an id is right; spelling it as a raw byte is not. The check reads BYTES, because reading the file as text is exactly what hides it. Lane: openxfactory-4-opendox-extraction Refs opensoft/openxFactory#656 Co-Authored-By: Claude Opus 5 (1M context) --- .github/workflows/validate.yml | 11 + tests/test_view_registry.py | 727 +++++++++++++++++++++++++++++++++ 2 files changed, 738 insertions(+) create mode 100644 tests/test_view_registry.py diff --git a/.github/workflows/validate.yml b/.github/workflows/validate.yml index 76b6e7a7..c5aa0972 100644 --- a/.github/workflows/validate.yml +++ b/.github/workflows/validate.yml @@ -49,10 +49,21 @@ jobs: # place the ruled contract is executed rather than described. It is # `--noconftest` safe and needs no consumer, for the same reason and by # the same means as its two neighbours. + # + # § 3.4 SLICE S3 adds `tests/test_view_registry.py`, on exactly the same + # footing as its three neighbours and for the same reason: it asserts a + # SEAM — that a contributed panel is collected, refused or absent by the + # rules `route_extension.collect_bindings` already holds for routes — and + # it is the only place slice S3's ruled contract is executed rather than + # described. `--noconftest` safe and needs no consumer: the Python half + # imports `opendox.view_extension` alone, and the JavaScript half drives + # the real `views/view_extension.js` under the `node` the runner already + # has (skipped, never failed, where node is absent). - name: pytest run: >- python -m pytest -q tests/test_leg_shape.py tests/test_consumer_reach.py tests/test_profile_registration.py + tests/test_view_registry.py --noconftest diff --git a/tests/test_view_registry.py b/tests/test_view_registry.py new file mode 100644 index 00000000..e2a8b7c1 --- /dev/null +++ b/tests/test_view_registry.py @@ -0,0 +1,727 @@ +"""The VIEW REGISTRY — § 3.4 slice S3, both halves of it. + +The boundary note (openDox-spec `docs/front-end-package-boundary.md` § 4.1, +landed at `a44ac06d`) asks slice S3 for `ViewBinding` + `collectViewBindings` +"on the § 2.4 / § 4.3 seams", with "collision + empty-tuple refusal tests". This +suite is those tests and four more, because a seam that is only described is the +thing the note's own § 1.2(d) is about: 48 test files across two repositories +that do not run. + +WHAT IT HOLDS, and why each is here rather than implied: + +1. A BINDING IS REFUSED WHERE IT IS DECLARED. `RouteBinding.__post_init__`'s + discipline: a binding is declared once at assembly time and consulted on + every render, so the cheap place to find a malformed one is the first. Each + refusal is asserted on its MESSAGE as well as its type — a refusal whose text + does not name the fix is a stack trace with extra steps + (`test_profile_registration.py`'s own rule). +2. TWO BINDINGS IN ONE SLOT REFUSE. The note's exact analogue of + `collect_bindings`' collision: *"a declared route silently unreachable"* + becomes *"a declared panel silently unmounted"*. +3. THE EMPTY CONSUMER COLUMN RENDERS THE CORE ALONE. The note's S3 row in its + own words — "nothing is contributed yet, so the shell renders exactly as + today with an empty extension tuple" — and it is a POSITIVE assertion, not an + absence: the core arm must come through the collection unchanged. +4. A CLASS-A BINDING DECLARING A GATE ROUTE IS REFUSED, AND A CLASS-B ONE IS + NOT. RULED Q3 (openxFactory#656 comment `5642758731`): "a route constant + travels with the binding that calls it, never with the model that happens to + declare it", with § 4.5 assertion 2's scope — class B is exempt by + construction, the transitional `?` is in scope. +5. THE PROFILE FACET IS THE SAME COMPOSITE PROFILE'S. `VIEW_EXTENSIONS` comes + off the ONE registration through the SAME lazy proxy as `ROUTE_EXTENSIONS` + and `SUBCOMMAND_EXTENSIONS` (RULED ASK-2 option (2), comment `5628886636`), + with the two absences answered differently and both on the record: NO HOST + refuses, NO FACET yields an empty column that the manifest NAMES. +6. THE THREE DECLARATIONS OF THE REGION SET AGREE. `view_extension.py`'s + `REGIONS`, `views/view_extension.js`'s `REGIONS`, and `index.html`'s + `data-region` attributes are one fact written three times, so a drift test is + the only thing that keeps them one fact. The shape openxFactory's + `carved_reach.py` scrub-list drift test already uses. +7. THE SHELL NO LONGER IMPORTS A CLASS-B MODULE. § 4.1's own sentence — "app.js + stops importing class-B modules directly" — asserted against the file rather + than promised in a commit message. +8. THE CLIENT HALF ACTUALLY RUNS. The JavaScript assertions drive the REAL + `views/view_extension.js` under node, against the REAL `views/docs.js` for the + class-A view this slice wires end to end, and against a fixture panel in a + temp bundle for the contributed-and-mounted path. Nothing here reads a + module's source and calls that a behaviour test — `test_wheel_verbs_dom.py`'s + rule, and the reason it is worth the subprocess. + +`--noconftest` SAFE, deliberately: `validate` runs this file in the explicit +list with conftest collection off (RULED Q-L5 (b')), so nothing here may need a +fixture, a path insertion or an installed consumer. `ROOT` is computed from +`__file__` for that reason and the package is importable because the workflow +installs it (`pip install -e ".[test]"`). + +A CREATED file: no carve-manifest row (RULED OQ-C). +""" + +from __future__ import annotations + +import json +import re +import shutil +import subprocess +import sys +from pathlib import Path + +import pytest + +from opendox import domain_profile, profile_proxy, view_extension +from opendox.view_extension import ( + MANIFEST_KIND, + MANIFEST_SCHEMA_VERSION, + REGIONS, + VIEW_CLASSES, + ViewBinding, + ViewBindingError, + collect_view_bindings, + dom_regions, + host_view_extensions, + view_manifest, +) + +ROOT = Path(__file__).resolve().parents[1] +WEB = ROOT / "src" / "opendox" / "web" +REGISTRY_JS = WEB / "views" / "view_extension.js" +APP_JS = WEB / "app.js" +INDEX_HTML = WEB / "index.html" +NODE = shutil.which("node") + + +# -------------------------------------------------------------------------- +# helpers + + +class _Extension: + """A view extension, structurally. Never a subclass of anything here — the + whole point of `runtime_checkable` is that the column which PINS openDox + conforms without importing from it.""" + + def __init__(self, *bindings: ViewBinding) -> None: + self._bindings = bindings + + def views(self) -> tuple[ViewBinding, ...]: + return self._bindings + + +class _Route: + """A contributed `RouteBinding`, at the three fields the ownership check + reads. Deliberately not `route_extension.RouteBinding`: the client half + reads these same three fields out of JSON, and holding both halves to one + structural rule is the point.""" + + def __init__(self, pattern: str, is_prefix: bool = False, + method: str = "POST") -> None: + self.pattern = pattern + self.is_prefix = is_prefix + self.method = method + + +def _binding(**over) -> ViewBinding: + spec = dict(id="docs.list", region="view-docs", module="./views/docs.js", + entry="renderDocs", view_class="A") + spec.update(over) + return ViewBinding(**spec) + + +def _run_node(source: str, cwd: Path) -> dict: + """Run an ES-module harness and return the ONE JSON object it prints.""" + script = cwd / "harness.mjs" + script.write_text(source, encoding="utf-8") + proc = subprocess.run([NODE, str(script)], capture_output=True, text=True, + timeout=120) + assert proc.returncode == 0, proc.stderr + return json.loads(proc.stdout.strip().splitlines()[-1]) + + +def _temp_bundle(tmp_path: Path) -> Path: + """A throwaway `web/` carrying a byte-identical copy of the registry. + + The registry resolves a binding's module against the BUNDLE ROOT, so a + fixture panel has to live in a bundle. Copying rather than writing a fixture + module into `src/opendox/web/views/` keeps the real bundle exactly the set + of files the census counts — § 4.5 assertion 1 fails an unrowed file, and a + test fixture would be one. + """ + web = tmp_path / "web" + (web / "views").mkdir(parents=True) + copied = web / "views" / "view_extension.js" + copied.write_bytes(REGISTRY_JS.read_bytes()) + assert copied.read_bytes() == REGISTRY_JS.read_bytes() + return web + + +# -------------------------------------------------------------------------- +# 1. a binding is refused where it is DECLARED + + +@pytest.mark.parametrize("over,fragment", [ + ({"id": "Docs List"}, "dotted lowercase slug"), + ({"id": ""}, "dotted lowercase slug"), + ({"region": "view-nowhere"}, "which the shell does not declare"), + ({"module": "https://cdn.example/panel.js"}, "vendor"), + ({"module": "/views/docs.js"}, "bundle-relative"), + ({"module": "./../../etc/passwd.js"}, "climbs out of the bundle"), + ({"entry": "not an identifier"}, "the NAME of an export"), + ({"entry": "__proto__"}, "dunder"), + ({"view_class": "D"}, "not one of"), + ({"routes": ("actions/gate/ratify",)}, "rooted at '/'"), + ({"routes": ["/actions/gate/ratify"]}, "not a tuple"), + ({"requires": ("",)}, "not a capability or facet name"), + ({"optional": "yes"}, "not a bool"), +]) +def test_a_malformed_binding_refuses_and_the_message_says_why(over, fragment): + with pytest.raises(ViewBindingError) as excinfo: + _binding(**over) + assert fragment in str(excinfo.value) + + +def test_a_well_formed_binding_is_frozen_and_carries_its_slot(): + binding = _binding() + assert binding.slot == ("view-docs", "docs.list") + with pytest.raises(Exception): + binding.id = "other" # frozen dataclass + + +def test_the_manifest_entry_is_json_and_drops_nothing(): + entry = _binding(routes=("/actions/gate/ratify",), optional=True, + view_class="B", region="viewer-gatebar", + id="gate.bar", module="./views/gate.js", + entry="mountGateBar").as_manifest_entry() + assert json.loads(json.dumps(entry)) == entry + assert entry["routes"] == ["/actions/gate/ratify"] + assert entry["optional"] is True + + +# -------------------------------------------------------------------------- +# 2. collection: conformance, collision, and the empty consumer column + + +def test_a_non_conforming_extension_refuses_and_names_the_member(): + class NotAnExtension: + pass + + with pytest.raises(ViewBindingError) as excinfo: + collect_view_bindings([NotAnExtension()]) + assert "does not conform to ViewExtension" in str(excinfo.value) + assert "views" in str(excinfo.value) + + +def test_an_extension_contributing_something_else_refuses(): + class Wrong: + def views(self): + return ({"id": "docs.list"},) + + with pytest.raises(ViewBindingError) as excinfo: + collect_view_bindings([Wrong()]) + assert "not a ViewBinding" in str(excinfo.value) + + +def test_two_bindings_in_one_slot_refuse_and_name_both_modules(): + core = _Extension(_binding()) + rival = _Extension(_binding(module="./views/doc-wheel.js", + entry="renderDocWheel")) + with pytest.raises(ViewBindingError) as excinfo: + collect_view_bindings([core, rival]) + message = str(excinfo.value) + assert "two view bindings claim region" in message + assert "./views/docs.js" in message and "./views/doc-wheel.js" in message + assert "never renders" in message + + +def test_one_id_in_two_different_regions_is_not_a_collision(): + # The slot is (region, id), exactly as `RouteBinding.key` is + # (method, pattern, is_prefix) and never the handler. Two regions showing + # the same panel is a layout, not a defect. + both = _Extension(_binding(), _binding(region="view-lineage")) + assert len(collect_view_bindings([both])) == 2 + + +def test_the_core_arm_comes_through_an_empty_consumer_column_unchanged(): + core = (_binding(), _binding(id="lineage.readiness", region="view-lineage", + module="./views/lineage.js", + entry="renderLineage", view_class="C")) + collected = collect_view_bindings( + [_Extension(*core), _Extension()], contributed_routes=()) + assert collected == core # order AND identity, not just a count + + +def test_collecting_nothing_at_all_is_an_empty_tuple_not_a_refusal(): + # The static served image's case, and every host before slice S5. + assert collect_view_bindings([]) == () + assert collect_view_bindings([_Extension()]) == () + + +# -------------------------------------------------------------------------- +# 4. RULED Q3 — a route travels with the binding that calls it + + +GATE_PREFIX = _Route("/actions/gate/", is_prefix=True) + + +def test_a_class_a_binding_declaring_a_gate_route_is_refused(): + binding = _binding(routes=("/actions/gate/ratify",)) + with pytest.raises(ViewBindingError) as excinfo: + collect_view_bindings([_Extension(binding)], + contributed_routes=(GATE_PREFIX,)) + message = str(excinfo.value) + assert "/actions/gate/" in message + assert "5642758731" in message # the ruling, cited + assert "BINDING THAT CALLS IT" in message + + +@pytest.mark.parametrize("view_class", ["C", "?"]) +def test_class_c_and_the_transitional_class_are_in_scope_too(view_class): + # § 4.5 assertion 2: "class A, class C AND the transitional `?`, which is + # where most of the breaches actually sit". + binding = _binding(view_class=view_class, + routes=("/actions/gate/ratify",)) + with pytest.raises(ViewBindingError): + collect_view_bindings([_Extension(binding)], + contributed_routes=(GATE_PREFIX,)) + + +def test_a_class_b_binding_declaring_the_same_route_is_allowed(): + # "Class B is exempt by construction: a gate-loop file naming a gate route + # is the boundary working." + binding = _binding(id="gate.bar", region="viewer-gatebar", + module="./views/gate.js", entry="mountGateBar", + view_class="B", routes=("/actions/gate/ratify",), + optional=True) + assert collect_view_bindings([_Extension(binding)], + contributed_routes=(GATE_PREFIX,)) == (binding,) + + +def test_an_exact_contributed_route_is_matched_exactly(): + index = _Route("/snapshot-index.json", is_prefix=False, method="GET") + ok = _binding(routes=("/snapshot-index.jsonl",)) + assert collect_view_bindings([_Extension(ok)], contributed_routes=(index,)) + breach = _binding(routes=("/snapshot-index.json",)) + with pytest.raises(ViewBindingError): + collect_view_bindings([_Extension(breach)], contributed_routes=(index,)) + + +def test_with_no_contributed_routes_nothing_can_breach(): + # Slice S3's own case: no column has claimed a route, so the check is a + # no-op because there is nothing to breach — not because it passed. + binding = _binding(routes=("/actions/gate/ratify",)) + assert collect_view_bindings([_Extension(binding)]) == (binding,) + + +def test_a_contributed_route_without_a_pattern_refuses(): + class Malformed: + is_prefix = False + + with pytest.raises(ViewBindingError) as excinfo: + collect_view_bindings([_Extension(_binding(routes=("/x",)))], + contributed_routes=(Malformed(),)) + assert "carries no string pattern" in str(excinfo.value) + + +# -------------------------------------------------------------------------- +# 5. the profile facet — one registration, one proxy, three facets + + +class _HostProfile: + """What a host registers. Not a `DomainProfile` and not typed: openDox + type-checks nothing and names only the attributes it reads.""" + + SUBCOMMAND_EXTENSIONS = ("the host's subcommands",) + ROUTE_EXTENSIONS = ("the host's routes",) + VIEW_EXTENSIONS = ("the host's views",) + + +class _ProfileWithoutTheFacet: + SUBCOMMAND_EXTENSIONS = ("the host's subcommands",) + ROUTE_EXTENSIONS = ("the host's routes",) + + +@pytest.fixture +def registered(): + """Register, yield the proxy, and ALWAYS unregister. + + `domain_profile` holds ONE registration for the process and refuses a + second, so a test that left one behind would fail its neighbours rather + than itself. + """ + def _register(profile): + domain_profile.register(profile) + return profile_proxy.profile_openxfactory + + try: + yield _register + finally: + if domain_profile.is_registered(): + domain_profile.unregister() + + +def test_the_facet_comes_off_the_one_registered_profile(registered): + proxy = registered(_HostProfile()) + assert host_view_extensions(proxy) == ("the host's views",) + # ...and it is the SAME object the other two facets come off: one + # registration, three facets (RULED ASK-2 option (2)). + assert proxy.ROUTE_EXTENSIONS == ("the host's routes",) + assert proxy.SUBCOMMAND_EXTENSIONS == ("the host's subcommands",) + + +def test_a_host_without_the_facet_contributes_an_empty_column(registered): + proxy = registered(_ProfileWithoutTheFacet()) + assert host_view_extensions(proxy) == () + + +def test_no_host_at_all_refuses_rather_than_answering_empty(): + assert not domain_profile.is_registered() + with pytest.raises(domain_profile.ProfileNotRegistered) as excinfo: + host_view_extensions(profile_proxy.profile_openxfactory) + assert domain_profile.REGISTRATION_CALL in str(excinfo.value) + + +def test_importing_the_registry_resolves_no_profile(): + # The lazy proxy's whole value: importing cannot fail for want of a host. + # A SUBPROCESS, because this process may have registered one. + proc = subprocess.run( + [sys.executable, "-c", + "import opendox.view_extension as v;" + "from opendox import domain_profile as d;" + "print(d.is_registered())"], + capture_output=True, text=True, timeout=120, + cwd=str(ROOT), env={"PYTHONPATH": str(ROOT / "src"), "PATH": "/usr/bin:/bin"}) + assert proc.returncode == 0, proc.stderr + assert proc.stdout.strip() == "False" + + +# -------------------------------------------------------------------------- +# the manifest — the one crossing of the process boundary + + +def test_the_manifest_declares_its_schema_and_names_the_absence(): + manifest = view_manifest([_binding()], contributed_routes=(GATE_PREFIX,), + host_facet="absent", host_profile="a host") + assert manifest["kind"] == MANIFEST_KIND + assert manifest["schema_version"] == MANIFEST_SCHEMA_VERSION + assert manifest["facet"] == view_extension.PROFILE_FACET + assert manifest["host_facet"] == "absent" + assert manifest["host_profile"] == "a host" + assert manifest["contributed_routes"] == [ + {"method": "POST", "pattern": "/actions/gate/", "is_prefix": True}] + assert [v["id"] for v in manifest["views"]] == ["docs.list"] + assert json.loads(json.dumps(manifest)) == manifest + + +def test_a_third_answer_about_the_absence_refuses(): + with pytest.raises(ViewBindingError) as excinfo: + view_manifest([], host_facet="maybe") + assert "'declared' or 'absent'" in str(excinfo.value) + + +# -------------------------------------------------------------------------- +# 6. one region set, written three times + + +def _js_object_keys(name: str) -> list[str]: + source = REGISTRY_JS.read_text(encoding="utf-8") + match = re.search(r"export const " + name + r" = \{(.*?)\n\};", + source, re.S) + assert match, f"{name} not found in {REGISTRY_JS}" + return re.findall(r'"([^"]+)":', match.group(1)) + + +def _js_array(name: str) -> list[str]: + source = REGISTRY_JS.read_text(encoding="utf-8") + match = re.search(r"export const " + name + r" = \[(.*?)\];", source, re.S) + assert match, f"{name} not found in {REGISTRY_JS}" + return re.findall(r'"([^"]*)"', match.group(1)) + + +def test_the_two_halves_declare_the_same_regions_in_the_same_order(): + assert _js_object_keys("REGIONS") == list(REGIONS) + + +def test_the_two_halves_declare_the_same_classes(): + assert _js_array("VIEW_CLASSES") == list(VIEW_CLASSES) + + +def test_neither_half_carries_a_control_character_a_separator_needs_escaped(): + # A REAL DEFECT, caught in review of this slice and kept as a test rather + # than a memory: the client's slot key is `region + "\u0000" + id`, and the + # separator was first typed as a LITERAL NUL byte into the source. The file + # still parsed and every assertion here still passed — but `git`, `grep`, + # `file(1)` and every diff viewer classify a file with a NUL as BINARY, so + # the module would have arrived in review as an unreadable blob and stayed + # that way. A separator that cannot appear in a region or an id is right; + # spelling it as a raw byte is not. The check is over BYTES, because reading + # the file as text is exactly what hides this. + for path in (REGISTRY_JS, APP_JS): + data = path.read_bytes() + data.decode("utf-8") # a decode error IS the finding + stray = sorted({b for b in data if b < 0x20 and b not in (0x09, 0x0A)}) + assert stray == [], ( + f"{path.name} carries control byte(s) {stray} inline; a control " + "character a string needs is written as an escape (\\u0000), never " + "as the byte itself") + + +def test_every_dom_region_is_an_element_the_shell_declares(): + # A "dom" region is an element of `index.html` whose id IS the region name. + # The id is the shell's declaration and this is what makes it a contract; + # `index.html` itself is not edited to repeat it (see `REGIONS`' own note on + # why an added attribute has no declared edit class). + html = INDEX_HTML.read_text(encoding="utf-8") + ids = re.findall(r'\bid="([^"]+)"', html) + assert len(ids) == len(set(ids)), "an element id declared twice" + missing = [name for name in dom_regions() if name not in ids] + assert missing == [], f"regions with no element in index.html: {missing}" + + +def test_no_shell_region_pretends_to_have_an_element(): + html = INDEX_HTML.read_text(encoding="utf-8") + ids = set(re.findall(r'\bid="([^"]+)"', html)) + for name, kind in REGIONS.items(): + if kind == "shell": + assert name not in ids, ( + f"{name} is declared a shell region but the shell carries an " + "element of that id; one of the two declarations is wrong") + + +def test_every_core_tab_binding_names_a_dom_region(): + # The tab router calls `document.getElementById(binding.region)`, so a core + # tab binding whose region is not a shell element would be a blank tab. + source = APP_JS.read_text(encoding="utf-8") + regions = re.findall(r'control: "tab-[a-z]+", region: "([^"]+)"', source) + assert regions == [r for r in dom_regions() if r.startswith("view-")] + + +# -------------------------------------------------------------------------- +# 7. the shell no longer imports a class-B module + + +def test_app_js_no_longer_imports_the_gate_module(): + # § 4.1: "app.js stops importing class-B modules directly." + source = APP_JS.read_text(encoding="utf-8") + # `[^;]*?` keeps the match inside ONE statement, so a multi-line named + # import is read and two adjacent statements are never spliced into one. + imports = re.findall(r'^import\s[^;]*?from\s+"([^"]+)";', source, + re.M | re.S) + assert "./views/gate.js" not in imports + assert "./views/view_extension.js" in imports + + +def test_app_js_declares_the_gate_bar_as_an_optional_class_b_binding(): + source = APP_JS.read_text(encoding="utf-8") + assert 'id: "gate.bar"' in source + assert 'module: "./views/gate.js", entry: "mountGateBar", view_class: "B"' in source + assert 'routes: ["/actions/gate/ratify"]' in source + assert "optional: true" in source + + +def test_app_js_wires_the_doc_list_through_the_registry(): + # The ONE view this slice wires end to end: the class-A doc list. + source = APP_JS.read_text(encoding="utf-8") + assert ('{ id: "docs.list", control: "tab-docs", region: "view-docs",' + in source) + assert 'module: "./views/docs.js", entry: "renderDocs", view_class: "A",' in source + + +# -------------------------------------------------------------------------- +# 8. the client half, executed + + +@pytest.mark.skipif(NODE is None, reason="node is not installed") +def test_js_collects_the_core_arm_with_an_empty_consumer_column(tmp_path): + result = _run_node(f""" +import {{ collectViewBindings, contributedViewBindings }} + from {json.dumps(REGISTRY_JS.as_uri())}; +const core = {{ views: () => [ + {{ id: "docs.list", control: "tab-docs", region: "view-docs", + module: "./views/docs.js", entry: "renderDocs", view_class: "A", + mount: () => null }}, +] }}; +const views = collectViewBindings( + [core, {{ views: () => contributedViewBindings({{}}) }}]); +console.log(JSON.stringify({{ ids: views.map((v) => v.id), + tabs: views.filter((v) => v.control).length }})); +""", tmp_path) + assert result == {"ids": ["docs.list"], "tabs": 1} + + +@pytest.mark.skipif(NODE is None, reason="node is not installed") +def test_js_refuses_a_slot_collision_and_a_contributed_gate_route(tmp_path): + result = _run_node(f""" +import {{ collectViewBindings }} from {json.dumps(REGISTRY_JS.as_uri())}; +const spec = {{ id: "docs.list", region: "view-docs", + module: "./views/docs.js", entry: "renderDocs", + view_class: "A" }}; +const out = {{}}; +try {{ + collectViewBindings([{{ views: () => [spec] }}, + {{ views: () => [{{ ...spec, module: "./views/x.js" }}] }}]); + out.collision = "not refused"; +}} catch (e) {{ out.collision = e.name; out.collisionMessage = e.message; }} +try {{ + collectViewBindings([{{ views: () => [{{ ...spec, + routes: ["/actions/gate/ratify"] }}] }}], + {{ contributedRoutes: [{{ pattern: "/actions/gate/", is_prefix: true }}] }}); + out.q3 = "not refused"; +}} catch (e) {{ out.q3 = e.name; out.q3Message = e.message; }} +try {{ + collectViewBindings([{{ views: () => [{{ ...spec, view_class: "B", + routes: ["/actions/gate/ratify"] }}] }}], + {{ contributedRoutes: [{{ pattern: "/actions/gate/", is_prefix: true }}] }}); + out.classB = "allowed"; +}} catch (e) {{ out.classB = e.name; }} +console.log(JSON.stringify(out)); +""", tmp_path) + assert result["collision"] == "ViewBindingError" + assert "never renders" in result["collisionMessage"] + assert result["q3"] == "ViewBindingError" + assert "5642758731" in result["q3Message"] + assert result["classB"] == "allowed" + + +@pytest.mark.skipif(NODE is None, reason="node is not installed") +def test_js_refuses_a_malformed_capabilities_manifest(tmp_path): + result = _run_node(f""" +import {{ contributedViewBindings }} from {json.dumps(REGISTRY_JS.as_uri())}; +const out = {{}}; +out.absent = contributedViewBindings({{}}).length; +out.nullCaps = contributedViewBindings(null).length; +for (const [name, payload] of [ + ["wrongKind", {{ kind: "something-else", schema_version: 1, views: [] }}], + ["wrongVersion", {{ kind: "opendox.view-manifest", schema_version: 99, + views: [] }}], + ["noViews", {{ kind: "opendox.view-manifest", schema_version: 1 }}], +]) {{ + try {{ contributedViewBindings({{ views: payload }}); out[name] = "not refused"; }} + catch (e) {{ out[name] = e.name; }} +}} +console.log(JSON.stringify(out)); +""", tmp_path) + assert result == {"absent": 0, "nullCaps": 0, "wrongKind": "ViewBindingError", + "wrongVersion": "ViewBindingError", + "noViews": "ViewBindingError"} + + +@pytest.mark.skipif(NODE is None, reason="node is not installed") +def test_js_resolves_the_real_doc_list_module_from_its_binding(tmp_path): + # THE VIEW THIS SLICE WIRES END TO END, proven against the real module: a + # binding read out of a `/capabilities` manifest, collected, and resolved to + # the export it names. No stub anywhere on the path. + manifest = { + "schema_version": MANIFEST_SCHEMA_VERSION, + "kind": MANIFEST_KIND, + "contributed_routes": [], + "views": [_binding().as_manifest_entry()], + } + result = _run_node(f""" +import {{ collectViewBindings, contributedViewBindings, resolveView }} + from {json.dumps(REGISTRY_JS.as_uri())}; +const caps = {{ views: {json.dumps(manifest)} }}; +const views = collectViewBindings( + [{{ views: () => contributedViewBindings(caps) }}]); +const resolved = await resolveView(views, "docs.list"); +console.log(JSON.stringify({{ + id: resolved.binding.id, + region: resolved.binding.region, + entry: typeof resolved.exports[resolved.binding.entry], +}})); +""", tmp_path) + assert result == {"id": "docs.list", "region": "view-docs", + "entry": "function"} + + +@pytest.mark.skipif(NODE is None, reason="node is not installed") +def test_js_mounts_a_contributed_panel_into_its_region(tmp_path): + # The CONTRIBUTED path end to end: a binding that arrived as JSON, loaded + # from a module the core arm never imported, mounted into the region it + # named — which is exactly what slice S5's gate loop will be. + web = _temp_bundle(tmp_path) + (web / "views" / "panel-fixture.js").write_text( + "export function mountPanel(host, ctx) {\n" + " const node = host.ownerDocument.createElement('div');\n" + " node.textContent = 'contributed: ' + ctx.label;\n" + " host.appendChild(node);\n" + " return { mounted: true };\n" + "}\n", encoding="utf-8") + registry = (web / "views" / "view_extension.js").as_uri() + manifest = { + "schema_version": MANIFEST_SCHEMA_VERSION, + "kind": MANIFEST_KIND, + "contributed_routes": [], + "views": [{"id": "fixture.panel", "region": "view-docs", + "module": "./views/panel-fixture.js", "entry": "mountPanel", + "view_class": "A", "routes": [], "requires": [], + "optional": False}], + } + result = _run_node(f""" +import {{ collectViewBindings, contributedViewBindings, resolveView, regionHost }} + from {json.dumps(registry)}; + +// The smallest DOM that answers what a mount does: create, append, read back. +class Node {{ + constructor(tag, doc) {{ this.tag = tag; this.children = []; this.text = ""; + this.id = ""; this.ownerDocument = doc; }} + set textContent(v) {{ this.text = String(v); }} + get textContent() {{ return this.text + + this.children.map((c) => c.textContent).join(""); }} + appendChild(child) {{ this.children.push(child); return child; }} +}} +const doc = {{ + nodes: [], + createElement(tag) {{ const n = new Node(tag, doc); doc.nodes.push(n); return n; }}, + getElementById(id) {{ return doc.nodes.find((n) => n.id === id) || null; }}, +}}; +const host = doc.createElement("section"); +host.id = "view-docs"; + +const views = collectViewBindings( + [{{ views: () => contributedViewBindings({{ views: {json.dumps(manifest)} }}) }}]); +const resolved = await resolveView(views, "fixture.panel"); +const target = regionHost(resolved.binding, doc); +const controller = resolved.exports[resolved.binding.entry]( + target, {{ label: "the consumer column" }}); +console.log(JSON.stringify({{ + mounted: controller.mounted, + rendered: target.textContent, + sameHost: target === host, +}})); +""", tmp_path) + assert result == {"mounted": True, + "rendered": "contributed: the consumer column", + "sameHost": True} + + +@pytest.mark.skipif(NODE is None, reason="node is not installed") +def test_js_an_absent_optional_binding_is_null_and_a_required_one_refuses(tmp_path): + # § 6 Q5's shape, and the gate bar's: absent-and-optional is an outcome the + # caller handles, absent-and-required is a refusal that names the layering. + result = _run_node(f""" +import {{ collectViewBindings, lookupView, requireView, resolveView }} + from {json.dumps(REGISTRY_JS.as_uri())}; +const views = collectViewBindings([]); +const out = {{ lookup: lookupView(views, "gate.bar"), + resolve: await resolveView(views, "gate.bar") }}; +try {{ requireView(views, "gate.bar"); out.require = "not refused"; }} +catch (e) {{ out.require = e.name; out.requireMessage = e.message; }} +console.log(JSON.stringify(out)); +""", tmp_path) + assert result["lookup"] is None + assert result["resolve"] is None + assert result["require"] == "ViewBindingError" + assert "optional: true" in result["requireMessage"] + + +@pytest.mark.skipif(NODE is None, reason="node is not installed") +def test_js_refuses_a_shell_region_asked_for_a_standing_element(tmp_path): + result = _run_node(f""" +import {{ collectViewBindings, regionHost }} + from {json.dumps(REGISTRY_JS.as_uri())}; +const views = collectViewBindings([{{ views: () => [{{ + id: "gate.bar", region: "viewer-gatebar", module: "./views/gate.js", + entry: "mountGateBar", view_class: "B", optional: true }}] }}]); +let name = "not refused"; +try {{ regionHost(views[0], {{ getElementById: () => null }}); }} +catch (e) {{ name = e.name; }} +console.log(JSON.stringify({{ refused: name }})); +""", tmp_path) + assert result == {"refused": "ViewBindingError"} From 2c75f5be7c9799cdc86ccd7620f16690b9805107 Mon Sep 17 00:00:00 2001 From: Brett Heap <1513478+brettheap@users.noreply.github.com> Date: Fri, 11 Sep 2026 23:33:27 -0400 Subject: [PATCH 04/44] =?UTF-8?q?=C2=A7=203.4=20S3:=20three=20review=20fin?= =?UTF-8?q?dings=20=E2=80=94=20a=20refusal=20that=20raised,=20a=20payload?= =?UTF-8?q?=20that=20could=20inject=20a=20tab,=20an=20entry=20that=20could?= =?UTF-8?q?=20not=20be=20called?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Copilot's review of PR #14, all three accepted and each kept as a test. 1. A DECLARATION DEFECT MUST NOT DEPEND ON THE TYPE OF WHAT IT REFUSES. `REGIONS` is a dict, so ` not in REGIONS` raised `TypeError` out of the hash BEFORE `ViewBinding.__post_init__` could raise the `ViewBindingError` this module promises for every declaration defect — a caller written to catch the one refusal class would have met an exception it never agreed to handle. The type is now checked before the membership, on `region` and on `view_class` both; the second cannot raise today (a tuple membership test does not hash) and is guarded anyway, because relying on `VIEW_CLASSES` staying a tuple is exactly the quiet dependency this work exists to end. 2. A CONTRIBUTED ENTRY MAY NOT CARRY THE CORE ARM'S OWN TWO FIELDS. `contributedViewBindings` passed manifest entries straight to `viewBinding`, which accepts and preserves `mount` and `control`. `control` is what makes a binding a TAB, and a contributed entry arrives as JSON and cannot carry the `mount` FUNCTION the tab router calls — so a manifest declaring a `control` would have put an entry in the tab strip whose `mount` is `undefined`: the tab renders, and the click that selects it throws. Refused where the payload is READ rather than ignored, because ignoring it is a crash with a delay on it, and `view_manifest()` emits neither field, so no honest payload is refused by this. Malformed REFUSES while absent is an empty column — the rule that already governs the rest of the manifest. 3. PRESENT IS NOT MOUNTABLE. `resolveView` checked only that the entry NAME existed on the module's namespace, so a module exporting it as a string, an object or a `null` handed back a binding that looked resolved and threw a raw `TypeError` from inside whatever tried to mount it — the "dangling import a thousand lines from the call" this seam exists to replace. The entry must now be a function, and the refusal distinguishes "not exported" from "exported as something that cannot be called", because those are different defects in the contributing column. Five new assertions, in the groups they belong to: an unhashable `region` (as a list and as a dict) and an unhashable `view_class` refuse as `ViewBindingError`; a contributed entry carrying `control` or `mount` refuses while the same entry without them is collected; and an entry exported as a non-function refuses at resolution. `tests/test_view_registry.py` is 55 assertions; `validate`'s four files are 127. Lane: openxfactory-4-opendox-extraction Refs opensoft/openxFactory#656 Co-Authored-By: Claude Opus 5 (1M context) --- src/opendox/view_extension.py | 14 ++++- src/opendox/web/views/view_extension.js | 35 +++++++++++ tests/test_view_registry.py | 82 +++++++++++++++++++++++++ 3 files changed, 129 insertions(+), 2 deletions(-) diff --git a/src/opendox/view_extension.py b/src/opendox/view_extension.py index 2e9f6b1c..4ac009cd 100644 --- a/src/opendox/view_extension.py +++ b/src/opendox/view_extension.py @@ -249,7 +249,12 @@ def __post_init__(self) -> None: f"view binding id {self.id!r} must be a dotted lowercase slug " "(e.g. 'gate.bar'): the id travels into JSON, into a DOM " "attribute and into a refusal message") - if self.region not in REGIONS: + # THE TYPE IS CHECKED BEFORE THE MEMBERSHIP, and the order is the + # finding: `REGIONS` is a dict, so ` not in REGIONS` raises + # `TypeError` from the hash and the caller never sees the refusal this + # module promises for every declaration defect. A seam whose refusal + # depends on the TYPE of what it is refusing is not a seam. + if not isinstance(self.region, str) or self.region not in REGIONS: raise ViewBindingError( f"view binding {self.id!r} names region {self.region!r}, which " f"the shell does not declare (declared: {sorted(REGIONS)}). A " @@ -279,7 +284,12 @@ def __post_init__(self) -> None: f"view binding {self.id!r} names entry {self.entry!r}: a dunder " "reaches the object protocol rather than the module's own " "surface") - if self.view_class not in VIEW_CLASSES: + # Guarded for the region's reason above. A tuple membership test does + # not hash and so cannot raise today — but the guard states the rule + # rather than relying on `VIEW_CLASSES` staying a tuple, which is + # exactly the kind of quiet dependency the boundary work exists to end. + if not isinstance(self.view_class, str) \ + or self.view_class not in VIEW_CLASSES: raise ViewBindingError( f"view binding {self.id!r} declares class {self.view_class!r}, " f"not one of {list(VIEW_CLASSES)} (§ 2.1: A openDox core, " diff --git a/src/opendox/web/views/view_extension.js b/src/opendox/web/views/view_extension.js index 0d2f33c5..b797fb18 100644 --- a/src/opendox/web/views/view_extension.js +++ b/src/opendox/web/views/view_extension.js @@ -310,6 +310,26 @@ export function contributedViewBindings(capabilities) { if (!Array.isArray(views)) { refuse("the /capabilities `views` payload carries no views array"); } + // `mount` AND `control` ARE THE CORE ARM'S AND A CONTRIBUTED ENTRY MAY NOT + // CARRY THEM — refused here rather than ignored, because ignoring them is a + // crash with a delay on it. `control` is what makes a binding a TAB, and a + // contributed entry cannot have the `mount` FUNCTION the tab router calls + // (it arrived as JSON, and `view_manifest()` emits neither field), so a + // manifest naming a control would put an entry in the tab strip whose + // `mount` is `undefined` and crash on the click that selects it. A binding + // this seam cannot mount must not look registered — `resolveView`'s own rule, + // applied one step earlier, where the payload is read. + for (const spec of views) { + const named = ["mount", "control"].find( + (field) => spec && spec[field] !== undefined); + if (named) { + refuse("the /capabilities `views` payload declares " + named + " on " + + JSON.stringify(spec && spec.id) + ": `mount` and `control` belong to " + + "the shell's own core arm and cannot cross the process boundary. A " + + "contributed binding names a module and an entry and is loaded " + + "through resolveView()."); + } + } return views.map(viewBinding); } @@ -363,12 +383,27 @@ export async function resolveView(bindings, id) { if (!binding) return null; const bundleRoot = new URL("../", import.meta.url); const exports = await import(new URL(binding.module, bundleRoot).href); + // PRESENT IS NOT MOUNTABLE. Checking only that the name exists lets a module + // export a string, an object or a `null` under it and still hand back a + // binding that looks resolved; the mount call then throws a raw `TypeError` + // from inside whatever tried to use it, which is precisely the "dangling + // import a thousand lines from the call" this seam exists to replace. The + // refusal says which of the two it is, because "not exported" and "exported + // as something that cannot be called" are different defects in the + // contributing column. if (!(binding.entry in exports)) { refuse("view binding " + JSON.stringify(binding.id) + " names entry " + JSON.stringify(binding.entry) + ", which " + JSON.stringify(binding.module) + " does not export. A binding that " + "cannot be mounted must not look registered."); } + if (typeof exports[binding.entry] !== "function") { + refuse("view binding " + JSON.stringify(binding.id) + " names entry " + + JSON.stringify(binding.entry) + ", which " + JSON.stringify(binding.module) + + " exports as " + typeof exports[binding.entry] + " rather than a " + + "function. An entry is the export that MOUNTS the panel; a binding " + + "that cannot be mounted must not look registered."); + } return { binding, exports }; } diff --git a/tests/test_view_registry.py b/tests/test_view_registry.py index e2a8b7c1..1cb8df5e 100644 --- a/tests/test_view_registry.py +++ b/tests/test_view_registry.py @@ -177,6 +177,24 @@ def test_a_malformed_binding_refuses_and_the_message_says_why(over, fragment): assert fragment in str(excinfo.value) +@pytest.mark.parametrize("field,value", [ + ("region", ["view-docs"]), # a list: unhashable + ("region", {"view-docs": 1}), # a dict: unhashable + ("view_class", ["A"]), +]) +def test_a_declaration_defect_refuses_even_when_the_value_is_unhashable( + field, value): + # THE REFUSAL MUST NOT DEPEND ON THE TYPE OF WHAT IT REFUSES. `REGIONS` is a + # dict, so ` not in REGIONS` raises `TypeError` out of the hash + # BEFORE the `ViewBindingError` this module promises for every declaration + # defect — a caller written to catch the one refusal class would see an + # exception it never agreed to handle. Copilot found this on PR #14; the + # guard is an `isinstance` before every membership test, and this is the + # test that keeps it there. + with pytest.raises(ViewBindingError): + _binding(**{field: value}) + + def test_a_well_formed_binding_is_frozen_and_carries_its_slot(): binding = _binding() assert binding.slot == ("view-docs", "docs.list") @@ -602,6 +620,70 @@ def test_js_refuses_a_malformed_capabilities_manifest(tmp_path): "noViews": "ViewBindingError"} +@pytest.mark.skipif(NODE is None, reason="node is not installed") +def test_js_refuses_a_contributed_entry_carrying_the_core_arms_own_fields( + tmp_path): + # `mount` and `control` ARE THE CORE ARM'S. A contributed entry arrives as + # JSON and cannot carry a function, so a manifest declaring `control` would + # put an entry in the TAB STRIP whose `mount` is `undefined` — the tab + # renders, and the click that selects it throws. Copilot found this on + # PR #14. `view_manifest()` emits neither field, so no honest payload is + # refused by this; a payload that carries one is malformed, and malformed + # REFUSES while absent is an empty column. + entry = _binding().as_manifest_entry() + result = _run_node(f""" +import {{ contributedViewBindings }} from {json.dumps(REGISTRY_JS.as_uri())}; +const base = {json.dumps(entry)}; +const out = {{}}; +out.clean = contributedViewBindings({{ views: {{ + schema_version: {MANIFEST_SCHEMA_VERSION}, kind: {json.dumps(MANIFEST_KIND)}, + views: [base] }} }}).length; +for (const [name, extra] of [ + ["control", {{ control: "tab-docs" }}], + ["mount", {{ mount: "renderDocs" }}], +]) {{ + try {{ + contributedViewBindings({{ views: {{ + schema_version: {MANIFEST_SCHEMA_VERSION}, + kind: {json.dumps(MANIFEST_KIND)}, + views: [{{ ...base, ...extra }}] }} }}); + out[name] = "not refused"; + }} catch (e) {{ out[name] = e.name; out[name + "Message"] = e.message; }} +}} +console.log(JSON.stringify(out)); +""", tmp_path) + assert result["clean"] == 1 + assert result["control"] == "ViewBindingError" + assert result["mount"] == "ViewBindingError" + assert "core arm" in result["controlMessage"] + + +@pytest.mark.skipif(NODE is None, reason="node is not installed") +def test_js_refuses_an_entry_exported_as_something_that_cannot_be_called( + tmp_path): + # PRESENT IS NOT MOUNTABLE. A module may export the named entry as a string, + # an object or a `null`; checking only that the NAME exists hands back a + # binding that looks resolved and throws a raw `TypeError` from inside + # whatever tried to mount it — the dangling-import failure mode this seam + # exists to replace. Copilot found this on PR #14. + web = _temp_bundle(tmp_path) + (web / "views" / "panel.js").write_text( + 'export const mountPanel = "not a function";\n', encoding="utf-8") + registry = (web / "views" / "view_extension.js").as_uri() + result = _run_node(f""" +import {{ collectViewBindings, resolveView }} from {json.dumps(registry)}; +const spec = {{ id: "panel.one", region: "view-docs", + module: "./views/panel.js", entry: "mountPanel", view_class: "A" }}; +const views = collectViewBindings([{{ views: () => [spec] }}]); +const out = {{}}; +try {{ await resolveView(views, "panel.one"); out.resolved = "not refused"; }} +catch (e) {{ out.resolved = e.name; out.message = e.message; }} +console.log(JSON.stringify(out)); +""", tmp_path) + assert result["resolved"] == "ViewBindingError" + assert "rather than a function" in result["message"] + + @pytest.mark.skipif(NODE is None, reason="node is not installed") def test_js_resolves_the_real_doc_list_module_from_its_binding(tmp_path): # THE VIEW THIS SLICE WIRES END TO END, proven against the real module: a From 09b42f5b1677b2c253fa52cf0e438e975f7b9488 Mon Sep 17 00:00:00 2001 From: Brett Heap <1513478+brettheap@users.noreply.github.com> Date: Fri, 11 Sep 2026 23:34:12 -0400 Subject: [PATCH 05/44] =?UTF-8?q?=C2=A7=203.4=20S3:=20migrate=20the=20thre?= =?UTF-8?q?e=20bullseye=20assertions=20that=20quote=20the=20tab=20router's?= =?UTF-8?q?=20field=20names?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit `tests/test_bullseye_widget.py` asserts `app.js`'s shape by QUOTING ITS LINES BACK, so the view registry's `view` -> `region` rename invalidates three of its quotations the moment it lands. They are migrated in the SAME act that invalidated them, which is the only time anyone can be sure the migration is a rename and not a behaviour change: :900 classList.toggle("lensfull", target.view === "view-lens") :1781 storeTab(target.view); :1785 const remembered = TABS.find((t) => t.view === storedTab()); `.view` -> `.region` in all three, and nothing else on any line. The assertions' MEANING is unchanged: the lens still takes the whole page, the tab is still remembered on every activation, and it is still restored only to a view this plane actually has. The tab router simply calls the field `region` now, because a binding's mount point is what that string always was. THE SUITE IS RED TODAY FOR AN UNRELATED REASON — it imports through `src/opendox/serve.py`, which still reaches `ideation_dashboard`, a module the § 3 carve removed — and it is not in `validate`'s narrowed list. Neither fact makes a stale assertion acceptable: slice S8 re-homes these 48 test files and un-narrows `validate`, and an assertion describing a shape that no longer exists is precisely the rot that slice would then have to discover and date. Copilot found two of the three on PR #14; a sweep of every assertion in the leg that quotes `app.js` found the third, and found no others anywhere in the suite. Q-L1: `tests/test_bullseye_widget.py` is an ARRIVED file, already `moved_with_declared_edit` for its `path constants` line 40. The three lines are declared as `adapter calls` on the same row by openxFactory PR #1001 — the same act that declares `app.js`'s 37 — and each is a single-line REPLACE at the carve numbering, so exactly three lines are declared and no neighbour is. `verify-carve-arrival.py`'s `_check_declared_lines` over all 123 `opendox_code` rows: both rows DECLARED, 60 verbatim rows byte-identical, 0 refusals. Lane: openxfactory-4-opendox-extraction Refs opensoft/openxFactory#656 Co-Authored-By: Claude Opus 5 (1M context) --- tests/test_bullseye_widget.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/tests/test_bullseye_widget.py b/tests/test_bullseye_widget.py index 345c09ab..8c86ddb5 100644 --- a/tests/test_bullseye_widget.py +++ b/tests/test_bullseye_widget.py @@ -897,7 +897,7 @@ def test_the_lens_screen_takes_the_page_and_scrolls_its_own_panes(): app = (WEB / "app.js").read_text(encoding="utf-8") # the shell marks the screen, and only for the lens - assert 'classList.toggle("lensfull", target.view === "view-lens")' in app + assert 'classList.toggle("lensfull", target.region === "view-lens")' in app # the tiles are hidden there assert re.search(r"\.wrap\.lensfull\s*>\s*#stats\s*\{[^}]*display:\s*none", css) @@ -1778,11 +1778,11 @@ def test_a_reload_bearing_control_returns_you_to_the_view_you_were_on(): app = (WEB / "app.js").read_text(encoding="utf-8") # remembered on EVERY activation, so it is right however the tab changed — # a click, a keyboard arrow, or a programmatic `goto` from a wheel verb - assert "storeTab(target.view);" in app + assert "storeTab(target.region);" in app show = app.split("function show(target, focusTab) {")[1].split("\n }")[0] assert "storeTab" in show # …and restored only to a view this plane actually has - assert "const remembered = TABS.find((t) => t.view === storedTab());" in app + assert "const remembered = TABS.find((t) => t.region === storedTab());" in app assert "show(remembered || TABS[0], false);" in app # through the SAME guarded seam every other stored preference uses: under # blocked site data the getter itself throws, and a preference that cannot From 44c598003b442778977f4b8b95e58188524a19e2 Mon Sep 17 00:00:00 2001 From: Brett Heap <1513478+brettheap@users.noreply.github.com> Date: Sat, 12 Sep 2026 11:13:27 -0400 Subject: [PATCH 06/44] Fold S3 into S1's web-boundary census; keep both slices' xfails honest S1's census could carry no row for views/view_extension.js because the note measured the tree before S3's file existed; the merge alone left test_every_web_file_is_classified_exactly_once failing. Classified A: no import (so it cannot trip assertion 3), no governance literal (out of assertion 4's class-C/tail scope regardless), and its one route-shaped string -- 'gate.bar' in a doc comment -- is an id, not a /actions/... path, so assertion 2's patterns do not match it. app.js's own row `loc` moves 1155 -> 1282 with the registry wiring; the header totals move with both rows (43 files, 31,134 lines). Assertions 2 and 3's xfail `reason=` strings are corrected to the counts this tree actually measures post-merge, on the module's own stated "fidelity over tidiness" convention rather than left to cite a shape that no longer exists: * assertion 3 (relative import / class boundary): 7 sites -> 6. S3 closes app.js:43 -> views/gate.js, the shell's one direct class-B import and exactly the edge slice S3 exists to close. The other 4 class-boundary sites and the 2 unresolved intent-feed sites are untouched, so the assertion stays red and the marker stays valid. * assertion 2 (route ownership): 18 sites -> 20. S3's CORE_VIEWS `gate.bar` entry declares `routes: ["/actions/gate/ratify"]` (RULED Q3: a route constant travels with the binding that calls it) -- a real breach by this assertion's own rule while that entry sits in app.js (class A) rather than views/gate.js (class B, exempt by construction). Transitional by the same design the CORE arm itself is: slice S5 deletes this entry from app.js when the binding moves behind a host-supplied contribution. app.js's other two projection-route sites shift line number (183/184 -> 195/196) with the file's growth; same two `/source/` literals, untouched otherwise. Neither assertion XPASSes -- both stay xfail(strict=True), which is the thing this commit exists to keep true. Full leg validate invocation (tests/test_leg_shape.py, tests/test_consumer_reach.py, tests/test_profile_registration.py, tests/test_web_boundary.py, tests/test_view_registry.py --noconftest): 129 passed, 3 xfailed, 0 failed. Lane: openxfactory-4-opendox-extraction Refs opensoft/openxFactory#656 Co-Authored-By: Claude Sonnet 5 --- tests/fixtures/web_boundary_census.yaml | 20 +++++++++-- tests/test_web_boundary.py | 46 +++++++++++++++++-------- 2 files changed, 49 insertions(+), 17 deletions(-) diff --git a/tests/fixtures/web_boundary_census.yaml b/tests/fixtures/web_boundary_census.yaml index 7f8fc9ea..9a977d46 100644 --- a/tests/fixtures/web_boundary_census.yaml +++ b/tests/fixtures/web_boundary_census.yaml @@ -70,6 +70,17 @@ # C 14 files (13 + explorer.js), 11,854 lines (11,575 + 279) # ? 4 files (5 - explorer.js), 5,432 lines (5,711 - 279) # total 42 files, 30,585 lines -- unchanged (a reclassification, not a move) +# +# S3 ADDITION (opensoft/openDox-code#14, slice S3's own leg): a 43rd file +# arrives, `views/view_extension.js` (422 lines) -- the client-side view +# registry. The note's own census could carry no row for it because the note +# measured the tree at `a99eba03`, before this file existed. Class A: no +# import (so it cannot violate assertion 3), no governance literal (out of +# assertion 4's scope regardless, which is class C plus declared tails), and +# its one route-shaped string, `'gate.bar'` (an example in a doc comment), is +# an ID, not a `/actions/...` path -- assertion 2's patterns do not match it. +# A 21 files, 12,251 lines (11,702 + 422 + 127 app.js growth) +# total 43 files, 31,134 lines (30,585 + 422 + 127); B/C/? unchanged schema_version: 1 kind: web-boundary-census @@ -80,8 +91,8 @@ measured_at: "opensoft/openDox-code main a99eba03e31a0aee1cc15a061fdf718cc88a2c4 files: - path: app.js class: A - loc: 1155 - note: "the shell; imports 20 view modules; its only class-B import is gate.js at :43 (discharged by S3's view registry)" + loc: 1282 + note: "the shell; imports 20 view modules; its only class-B import is gate.js at :43 (discharged by S3's view registry -- loc grew 1155 -> 1282 with the registry wiring, S3)" - path: index.html class: C @@ -278,6 +289,11 @@ files: loc: 614 note: "FIRST_EDIT_ROUTE/ABANDON_SESSION_ROUTE/SHARE_SESSION_ROUTE/OPEN_PR_ROUTE, all under the gate prefix" + - path: views/view_extension.js + class: A + loc: 422 + note: "S3 ADDITION: the client-side view registry -- ViewBinding/collectViewBindings, route_extension.py's shape mirrored in JS (openDox-spec § 4.1). No import, no governance literal; 'gate.bar' at :126/:374 is a documentation example of an id, not a route literal, so assertion 2 does not match it." + - path: views/viewer.js class: A loc: 403 diff --git a/tests/test_web_boundary.py b/tests/test_web_boundary.py index 686e154d..b845aa3d 100644 --- a/tests/test_web_boundary.py +++ b/tests/test_web_boundary.py @@ -196,18 +196,28 @@ def _route_ownership_violations() -> list[str]: strict=True, reason=( "docs/front-end-package-boundary.md § 4.5 point 2 (opensoft/openDox-spec " - "#8 -> a44ac06d): 18 sites outside class B name a route another column " - "declares -- 10 the gate prefix (views/lens-model.js:1036/1037, " + "#8 -> a44ac06d): 20 sites outside class B name a route another column " + "declares (was 18 before slice S3; S3 -- opensoft/openDox-code#14 -- " + "adds 2 and closes none) -- 12 the gate prefix (app.js:586/598 NEW: " + "the `gate.bar` CORE_VIEWS entry's `routes: [\"/actions/gate/ratify\"]`, " + "RULED Q3 'a route constant travels with the binding that calls it' -- " + "a real breach by this assertion's own rule while the entry sits in " + "app.js (class A) rather than views/gate.js (class B, exempt by " + "construction); TRANSITIONAL, closed at slice S5 when the binding " + "moves behind a host-supplied contribution and this entry leaves " + "app.js entirely; views/lens-model.js:1036/1037, " "views/repo-selector.js:39/43, views/staging-workbench-model.js:543/" "817/818/821/822/826), 3 openxFactory's adapter lanes " - "(views/lens.js:41/45, views/repo-selector.js:46), 5 openXdox's " - "projection routes (views/repo-selector.js:33, app.js:183/184, " + "(views/lens.js:41/45, views/repo-selector.js:46, unchanged), 5 " + "openXdox's projection routes (app.js:195/196, shifted from :183/184 " + "by S3's own unrelated edits earlier in the file -- same two " + "`/source/` literals, untouched; views/repo-selector.js:33, " "views/viewer.js:314, views/wheel.js:97). The note's § 4.5 closing " "paragraph assigns closure to slices S5 and S6; its own per-site " - "table (point 2) instead reads S4 for 14 of the 18 and S6 for the " - "remaining 4 -- the two do not fully agree, flagged here rather than " - "silently reconciled. Unmark only once verified green, whichever " - "slice(s) actually close it." + "table (point 2) instead reads S4 for 14 of the original 18 and S6 " + "for the remaining 4 -- the two do not fully agree, flagged here " + "rather than silently reconciled. Unmark only once verified green, " + "whichever slice(s) actually close it." ), ) def test_no_ownership_violation_outside_class_b() -> None: @@ -274,20 +284,26 @@ def _import_violations() -> list[str]: strict=True, reason=( "docs/front-end-package-boundary.md § 1.2(b) / § 4.5 point 3 " - "(opensoft/openDox-spec #8 -> a44ac06d): 7 sites today -- 2 " + "(opensoft/openDox-spec #8 -> a44ac06d): 6 sites today (was 7; slice " + "S3 -- opensoft/openDox-code#14 -- CLOSES app.js:43 -> views/gate.js, " + "the shell's one direct class-B import, now a registry lookup, " + "exactly the edge § 4.1 names) -- 2 " "UNRESOLVED (views/dispose.js:26 and views/wheel.js:75-76 import " "views/intent-feed.js, RULED not_moved and absent from this leg, " - "docs/opendox-carve-manifest.yaml:1807-1810 RULED OQ-F) and 5 " - "CLASS-BOUNDARY (app.js:43 -> views/gate.js, app.js:45 -> " + "docs/opendox-carve-manifest.yaml:1807-1810 RULED OQ-F) and 4 " + "CLASS-BOUNDARY remaining (app.js:45 -> " "views/swb-session.js, views/staging-workbench.js -> " "views/swb-create.js and -> views/swb-session.js, " "views/wheel.js:73-74 -> views/dispose.js -- all class A/C " "importing class B). The note's closing paragraph assigns closure " "to slice S2, which is the intent-feed edge only (the 2 unresolved " - "sites); the 5 class-boundary sites are the same shape S3's view " - "registry and S5's gate-loop contribution close, per § 4.1/§ 5, not " - "S2. This assertion therefore stays red after S2 alone -- flagged " - "here rather than narrowed to fit the note's own summary." + "sites); the remaining 4 class-boundary sites are the same shape " + "S5's gate-loop contribution closes, per § 4.1/§ 5, not S2 -- S3 " + "closes the fifth (app.js:43) on its own account, ahead of S5, " + "because the view registry is exactly the seam that makes doing so " + "early possible. This assertion therefore stays red after S2 and S3 " + "alone -- flagged here rather than narrowed to fit the note's own " + "summary." ), ) def test_every_relative_import_resolves_and_stays_in_class() -> None: From 76495d30fa024e2c58bc3c1c7a842e388b4766ff Mon Sep 17 00:00:00 2001 From: Brett Heap <1513478+brettheap@users.noreply.github.com> Date: Sat, 12 Sep 2026 11:39:03 -0400 Subject: [PATCH 07/44] Copilot re-review, four findings: fail closed on all four MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit view_extension.js * manifestRoutes(): a PRESENT manifest whose contributed_routes is not an array (or missing) now refuses instead of silently reading back [] -- view_manifest() always emits this field as an array, so anything else there cannot be trusted for the ownership check it exists to carry. Absence of the WHOLE manifest is still an empty column, unchanged. * resolveView(): a rejected `await import(...)` (missing file, syntax error) is now caught and refused as a ViewBindingError naming the binding id and module path, instead of leaking a native error with neither. view_extension.py * ViewBinding.entry is now held to the same ASCII identifier grammar views/view_extension.js's viewBinding() checks (_ENTRY), not Python's own str.isidentifier() -- the two disagreed in both directions ("$mount" valid JS, invalid Python identifier; "café" valid Python identifier, invalid per the client's ASCII-only regex), so a binding could be constructed on one side and refused on the other. * collect_view_bindings() now checks views is callable and views() a list/tuple before entering the loop. isinstance(extension, ViewExtension) is a runtime_checkable Protocol check and verifies only that the name exists; `views = 1` or `views()` returning None both passed it and then raised a raw TypeError, never the ViewBindingError every other declaration defect in this module promises. Ten new tests (2 Python parametrized + 2 single + 2 JS, tests/test_view_- registry.py), the census loc for views/view_extension.js corrected for its growth (422 -> 455) with the header totals moving the same amount. Full leg validate invocation: 139 passed, 3 xfailed, 0 failed -- the three S1 xfails unaffected (app.js untouched this round; both created files this commit touches carry no manifest row, RULED OQ-C). Lane: openxfactory-4-opendox-extraction Refs opensoft/openxFactory#656 Co-Authored-By: Claude Sonnet 5 --- src/opendox/view_extension.py | 37 ++++++- src/opendox/web/views/view_extension.js | 39 +++++++- tests/fixtures/web_boundary_census.yaml | 8 +- tests/test_view_registry.py | 126 ++++++++++++++++++++++++ 4 files changed, 200 insertions(+), 10 deletions(-) diff --git a/src/opendox/view_extension.py b/src/opendox/view_extension.py index 4ac009cd..237daddf 100644 --- a/src/opendox/view_extension.py +++ b/src/opendox/view_extension.py @@ -201,6 +201,18 @@ #: own refusal rather than that test's coverage. _MODULE = re.compile(r"^\./[A-Za-z0-9_./-]+\.js$") +#: An export name, held to the SAME grammar `views/view_extension.js`'s +#: `viewBinding()` checks (Copilot, PR #14): `str.isidentifier()` and this +#: bundle's client both claimed to validate "a JS export name" and actually +#: validated two different things — Python's accepts Unicode names (`café`) +#: the browser's ASCII-only check then refuses, and rejects ASCII names the +#: browser accepts (`$mount`, `$` is not a Python identifier character at +#: all). A binding this module publishes and the client then refuses is +#: § 4.1's seam failing at the one place a shared vocabulary was the entire +#: point, so both halves compile the one pattern below rather than each +#: half asking its own language what an identifier is. +_ENTRY = re.compile(r"^[A-Za-z_$][A-Za-z0-9_$]*$") + class ViewBindingError(ValueError): """A binding that cannot be mounted, refused where it is DECLARED. @@ -272,13 +284,15 @@ def __post_init__(self) -> None: raise ViewBindingError( f"view binding {self.id!r} names module {self.module!r}, which " "climbs out of the bundle with '..'") - if not isinstance(self.entry, str) or not self.entry.isidentifier(): + if not isinstance(self.entry, str) or not _ENTRY.match(self.entry): raise ViewBindingError( f"view binding {self.id!r} names entry {self.entry!r}: an entry " "is the NAME of an export on the binding's module, never a " "callable — the same discipline `RouteBinding.handler` keeps, " "and for the same reason: the manifest crosses a process " - "boundary as JSON") + "boundary as JSON. Held to the JS-compatible identifier " + "grammar `views/view_extension.js` checks, not Python's own " + "`str.isidentifier()` (§ 4.1: one vocabulary, both halves)") if self.entry.startswith("__"): raise ViewBindingError( f"view binding {self.id!r} names entry {self.entry!r}: a dunder " @@ -463,7 +477,24 @@ def collect_view_bindings(extensions, *, raise ViewBindingError( f"{extension!r} does not conform to ViewExtension: it must " f"declare {list(MEMBERS)}") - declared = extension.views() + # `isinstance(extension, ViewExtension)` ONLY CHECKS THAT `views` + # EXISTS — `runtime_checkable` verifies membership, never callability + # or a method's return shape (Copilot, PR #14: `views = 1` and + # `views()` returning `None` both pass the check above and then raise + # a raw `TypeError` two lines down, never the `ViewBindingError` every + # other declaration defect in this module promises). Checked here, + # explicitly, rather than trusted to the Protocol. + views_member = getattr(extension, "views", None) + if not callable(views_member): + raise ViewBindingError( + f"{extension!r} does not conform to ViewExtension: views is " + f"{views_member!r}, which is not callable") + declared = views_member() + if not isinstance(declared, (list, tuple)): + raise ViewBindingError( + f"{extension!r}.views() returned {declared!r}: the protocol " + "promises tuple[ViewBinding, ...], and a value this module " + "cannot iterate more than once safely is not that") for binding in declared: if not isinstance(binding, ViewBinding): raise ViewBindingError( diff --git a/src/opendox/web/views/view_extension.js b/src/opendox/web/views/view_extension.js index b797fb18..592ba30f 100644 --- a/src/opendox/web/views/view_extension.js +++ b/src/opendox/web/views/view_extension.js @@ -338,8 +338,24 @@ export function contributedViewBindings(capabilities) { // against the same facts. export function manifestRoutes(capabilities) { const manifest = capabilities && capabilities.views; - const routes = manifest && manifest.contributed_routes; - return Array.isArray(routes) ? routes : []; + // ABSENT MEANS AN EMPTY COLUMN, exactly `contributedViewBindings`' own + // reading of no manifest at all. MALFORMED DOES NOT: `view_manifest()` + // always emits `contributed_routes` as an array (Copilot, PR #14), so a + // manifest that is PRESENT but carries anything else there is not making a + // true claim of "no contributed routes" — it is malformed, and reading it + // as `[]` would silently disable every binding's § 2.2 rule 1 check rather + // than fail closed the way this seam promises for anything it cannot + // reason about. + if (manifest === undefined || manifest === null) return []; + const routes = manifest.contributed_routes; + if (!Array.isArray(routes)) { + refuse("the /capabilities `views` payload declares contributed_routes " + + JSON.stringify(routes) + ", not an array: view_manifest() always " + + "emits this field as one, and a manifest that cannot be trusted for " + + "contributed_routes cannot be trusted for the ownership check that " + + "field exists to carry."); + } + return routes; } // An OPTIONAL reach: the binding, or null. This is `consumer_reach`'s posture @@ -382,7 +398,24 @@ export async function resolveView(bindings, id) { const binding = lookupView(bindings, id); if (!binding) return null; const bundleRoot = new URL("../", import.meta.url); - const exports = await import(new URL(binding.module, bundleRoot).href); + // A REJECTED IMPORT IS A REFUSAL TOO, and one this seam names rather than + // lets pass through raw (Copilot, PR #14): a missing file, a syntax error + // or a circular import all reject `import()` with a native error carrying + // no binding or module context, and the app would report a generic + // snapshot failure instead of the "which binding, which module" every + // other defect in this function states. `viewBinding()` already bounds + // `module` to a bundle-relative './…js' specifier that cannot climb out of + // the bundle, so what fails here is the file not being THERE, not the path + // being unsafe. + let exports; + try { + exports = await import(new URL(binding.module, bundleRoot).href); + } catch (e) { + refuse("view binding " + JSON.stringify(binding.id) + " names module " + + JSON.stringify(binding.module) + ", which failed to load: " + + (e && e.message ? e.message : String(e)) + ". A binding that cannot " + + "be mounted must not look registered."); + } // PRESENT IS NOT MOUNTABLE. Checking only that the name exists lets a module // export a string, an object or a `null` under it and still hand back a // binding that looks resolved; the mount call then throws a raw `TypeError` diff --git a/tests/fixtures/web_boundary_census.yaml b/tests/fixtures/web_boundary_census.yaml index 9a977d46..47bf3916 100644 --- a/tests/fixtures/web_boundary_census.yaml +++ b/tests/fixtures/web_boundary_census.yaml @@ -79,8 +79,8 @@ # assertion 4's scope regardless, which is class C plus declared tails), and # its one route-shaped string, `'gate.bar'` (an example in a doc comment), is # an ID, not a `/actions/...` path -- assertion 2's patterns do not match it. -# A 21 files, 12,251 lines (11,702 + 422 + 127 app.js growth) -# total 43 files, 31,134 lines (30,585 + 422 + 127); B/C/? unchanged +# A 21 files, 12,284 lines (11,702 + 422 + 127 app.js growth + 33 review round) +# total 43 files, 31,167 lines (30,585 + 422 + 127 + 33); B/C/? unchanged schema_version: 1 kind: web-boundary-census @@ -291,8 +291,8 @@ files: - path: views/view_extension.js class: A - loc: 422 - note: "S3 ADDITION: the client-side view registry -- ViewBinding/collectViewBindings, route_extension.py's shape mirrored in JS (openDox-spec § 4.1). No import, no governance literal; 'gate.bar' at :126/:374 is a documentation example of an id, not a route literal, so assertion 2 does not match it." + loc: 455 + note: "S3 ADDITION: the client-side view registry -- ViewBinding/collectViewBindings, route_extension.py's shape mirrored in JS (openDox-spec § 4.1). No import, no governance literal; 'gate.bar' in a doc comment is a documentation example of an id, not a route literal, so assertion 2 does not match it. loc 422 -> 455 on this PR's own review round (Copilot, PR #14): a malformed contributed_routes now refuses instead of silently disabling the ownership check, and a rejected dynamic import now refuses naming the binding and module instead of leaking a raw error." - path: views/viewer.js class: A diff --git a/tests/test_view_registry.py b/tests/test_view_registry.py index 1cb8df5e..cd1067f1 100644 --- a/tests/test_view_registry.py +++ b/tests/test_view_registry.py @@ -202,6 +202,28 @@ def test_a_well_formed_binding_is_frozen_and_carries_its_slot(): binding.id = "other" # frozen dataclass +@pytest.mark.parametrize("entry", ["$mount", "_mount", "mount$panel"]) +def test_the_entry_grammar_accepts_what_the_js_client_accepts(entry): + # Copilot, PR #14: `str.isidentifier()` accepts Unicode names the browser's + # ASCII-only regex refuses, and rejects `$`-bearing ASCII names + # `views/view_extension.js`'s `viewBinding()` accepts — so a binding could + # be published here and refused there, or refused here and never published + # at all for a name the client would have happily loaded. `$mount` is + # accepted by JS `[A-Za-z_$][A-Za-z0-9_$]*` and rejected by + # `"$mount".isidentifier()`; this asserts the PYTHON side now agrees. + assert _binding(entry=entry).entry == entry + + +def test_the_entry_grammar_refuses_what_the_js_client_refuses(): + # `"café"` IS a valid Python identifier (accented Unicode letters are + # allowed) and is NOT matched by the client's ASCII-only + # `/^[A-Za-z_$][A-Za-z0-9_$]*$/` — the other half of the same drift. + assert "café".isidentifier() + with pytest.raises(ViewBindingError) as excinfo: + _binding(entry="café") + assert "the NAME of an export" in str(excinfo.value) + + def test_the_manifest_entry_is_json_and_drops_nothing(): entry = _binding(routes=("/actions/gate/ratify",), optional=True, view_class="B", region="viewer-gatebar", @@ -236,6 +258,39 @@ def views(self): assert "not a ViewBinding" in str(excinfo.value) +def test_a_views_member_that_is_not_callable_refuses_rather_than_raising_typeerror(): + # `isinstance(extension, ViewExtension)` is a `runtime_checkable` Protocol + # check, which verifies only that the NAME `views` exists — never that it + # is callable (Copilot, PR #14). Before this test's fix, `views = 1` passed + # that check and then raised a raw `'int' object is not callable` + # `TypeError` two lines later, never the `ViewBindingError` this module + # promises for every declaration defect. + class NotCallable: + views = 1 + + with pytest.raises(ViewBindingError) as excinfo: + collect_view_bindings([NotCallable()]) + assert "not callable" in str(excinfo.value) + + +@pytest.mark.parametrize("returned", [None, 42, iter(())]) +def test_a_views_call_that_returns_something_unusable_refuses(returned): + # The Protocol promises `tuple[ViewBinding, ...]`; before this test's fix, + # `views()` returning `None` raised a raw `'NoneType' object is not + # iterable` `TypeError` at the `for binding in declared:` loop (Copilot, + # PR #14, same finding as the callable check above — a member existing is + # not a member behaving). A bare iterator is refused too, not accepted: + # this module walks it once for validation, and an extension consulted + # again later would see it already exhausted. + class Unusable: + def views(self): + return returned + + with pytest.raises(ViewBindingError) as excinfo: + collect_view_bindings([Unusable()]) + assert "views()" in str(excinfo.value) + + def test_two_bindings_in_one_slot_refuse_and_name_both_modules(): core = _Extension(_binding()) rival = _Extension(_binding(module="./views/doc-wheel.js", @@ -620,6 +675,44 @@ def test_js_refuses_a_malformed_capabilities_manifest(tmp_path): "noViews": "ViewBindingError"} +@pytest.mark.skipif(NODE is None, reason="node is not installed") +def test_js_manifest_routes_refuses_a_malformed_contributed_routes_field(tmp_path): + # `view_manifest()` always emits `contributed_routes` as an array + # (`view_extension.py::view_manifest`); before this test's fix, a PRESENT + # manifest carrying anything else there was read back as `[]` here -- + # silently disabling every binding's § 2.2 rule 1 ownership check rather + # than refusing a payload this seam cannot reason about (Copilot, PR #14). + # ABSENCE of the whole manifest still means an empty column, not a + # refusal -- `contributedViewBindings`'s own rule, held here too. + result = _run_node(f""" +import {{ manifestRoutes }} from {json.dumps(REGISTRY_JS.as_uri())}; +const out = {{}}; +out.absent = manifestRoutes({{}}).length; +out.nullCaps = manifestRoutes(null).length; +out.valid = manifestRoutes( + {{ views: {{ contributed_routes: [{{ pattern: "/x", is_prefix: false }}] }} }} +).length; +for (const [name, routes] of [ + ["string", "/actions/gate/"], + ["object", {{ pattern: "/x" }}], + ["missing", undefined], +]) {{ + try {{ + manifestRoutes({{ views: {{ contributed_routes: routes }} }}); + out[name] = "not refused"; + }} catch (e) {{ out[name] = e.name; out[name + "Message"] = e.message; }} +}} +console.log(JSON.stringify(out)); +""", tmp_path) + assert result["absent"] == 0 + assert result["nullCaps"] == 0 + assert result["valid"] == 1 + assert result["string"] == "ViewBindingError" + assert result["object"] == "ViewBindingError" + assert result["missing"] == "ViewBindingError" + assert "contributed_routes" in result["stringMessage"] + + @pytest.mark.skipif(NODE is None, reason="node is not installed") def test_js_refuses_a_contributed_entry_carrying_the_core_arms_own_fields( tmp_path): @@ -712,6 +805,39 @@ def test_js_resolves_the_real_doc_list_module_from_its_binding(tmp_path): "entry": "function"} +@pytest.mark.skipif(NODE is None, reason="node is not installed") +def test_js_resolve_view_refuses_a_binding_whose_module_fails_to_load(tmp_path): + # A REJECTED `import()` IS A REFUSAL TOO. Before this test's fix, a binding + # naming a module that is not there rejected with a native error carrying + # no binding or module context -- the app reports a generic snapshot + # failure instead of the "which binding, which module" every other defect + # in this function states (Copilot, PR #14). + manifest = { + "schema_version": MANIFEST_SCHEMA_VERSION, + "kind": MANIFEST_KIND, + "contributed_routes": [], + "views": [{"id": "fixture.missing", "region": "view-docs", + "module": "./views/does-not-exist.js", "entry": "mountPanel", + "view_class": "A", "routes": [], "requires": [], + "optional": False}], + } + result = _run_node(f""" +import {{ collectViewBindings, contributedViewBindings, resolveView }} + from {json.dumps(REGISTRY_JS.as_uri())}; +const views = collectViewBindings( + [{{ views: () => contributedViewBindings({{ views: {json.dumps(manifest)} }}) }}]); +const out = {{}}; +try {{ + await resolveView(views, "fixture.missing"); + out.result = "not refused"; +}} catch (e) {{ out.result = e.name; out.message = e.message; }} +console.log(JSON.stringify(out)); +""", tmp_path) + assert result["result"] == "ViewBindingError" + assert "fixture.missing" in result["message"] + assert "./views/does-not-exist.js" in result["message"] + + @pytest.mark.skipif(NODE is None, reason="node is not installed") def test_js_mounts_a_contributed_panel_into_its_region(tmp_path): # The CONTRIBUTED path end to end: a binding that arrived as JSON, loaded From 28de9c3bca94e53f401ac64051da45d879e1913f Mon Sep 17 00:00:00 2001 From: Brett Heap <1513478+brettheap@users.noreply.github.com> Date: Sat, 12 Sep 2026 12:04:46 -0400 Subject: [PATCH 08/44] Copilot re-review: give the client-side registry an explicit ES-module scope The one remaining PR #14 thread (tests/test_view_registry.py:132): this repository ships no `package.json`, so `_run_node`'s harness and the real `view_extension.js`/`docs.js` (native `export`/`import`, no bundler) have no declared module format. Node decides ambiguous `.js` files via `--experimental-detect-module` (default ON since Node ~20.10, unflagged by Node 22+): it reparses a file as ESM the moment it sees module syntax, and warns `To eliminate this warning, add "type": "module" to .../package.json`. Verified by hand and does not reproduce today: neither locally (Node v22.22.2) nor in the actual `validate` run for this head (34702880356, Node 24 per the runner's own deprecation notice) does any node-based test fail -- both pass because the heuristic is on by default there. It is still a real gap, not a false positive: importing the unmodified `view_extension.js` with `--no-experimental-detect-module` (simulating an older Node, or the flag disabled) fails outright, proven both by hand and by the new regression test below (confirmed red on the pre-fix tree, green after). Fix: an explicit `package.json` (`"type": "module"`) at the repository root -- an ancestor of `src/opendox/web/**/*.js` for Node's module-scope lookup, but deliberately NOT inside `src/opendox/web/`, which `tests/fixtures/web_boundary_census.yaml` classifies file-by-file (verified `test_every_web_file_is_classified_exactly_once` still passes unchanged) -- plus one written into every `_temp_bundle()` copy, since `tmp_path` sits outside the repository tree and the root file is not its ancestor. New test `test_js_module_scope_holds_without_node_s_detection_heuristic` imports both the real registry and a `_temp_bundle` copy under `--no-experimental-detect-module` and asserts a clean import -- the positive assertion that the module format is now a stated fact rather than a Node default that a future version, downgrade or flag could change again. Verified: full `validate` invocation (5 files, --noconftest) 140 passed, 3 xfailed -- same xfail set as before (S1's three strict xfails, untouched by this change). Lane: openxfactory-4-opendox-extraction Refs opensoft/openxFactory#656 Co-Authored-By: Claude Sonnet 5 --- package.json | 6 +++++ tests/test_view_registry.py | 52 +++++++++++++++++++++++++++++++++++++ 2 files changed, 58 insertions(+) create mode 100644 package.json diff --git a/package.json b/package.json new file mode 100644 index 00000000..7633c7c9 --- /dev/null +++ b/package.json @@ -0,0 +1,6 @@ +{ + "name": "opendox-code-web-tests", + "private": true, + "type": "module", + "description": "No published Node package here -- this file exists so Node's module loader has an explicit, version-independent answer for the format of src/opendox/web/**/*.js (native `export`/`import` syntax, no bundler). Without it, an ambiguous `.js` file's format is decided by Node's `--experimental-detect-module` heuristic (default on since Node ~20.10, unflagged by Node 22+): it currently reparses these files as ES modules and warns 'To eliminate this warning, add \"type\": \"module\"' -- this file is that fix, applied instead of relying on the heuristic staying on by default. tests/test_view_registry.py drives the real registry under node; deliberately placed at the repository root rather than inside src/opendox/web/, which tests/fixtures/web_boundary_census.yaml classifies file-by-file and which this is not part of." +} diff --git a/tests/test_view_registry.py b/tests/test_view_registry.py index cd1067f1..a15d029a 100644 --- a/tests/test_view_registry.py +++ b/tests/test_view_registry.py @@ -143,9 +143,18 @@ def _temp_bundle(tmp_path: Path) -> Path: module into `src/opendox/web/views/` keeps the real bundle exactly the set of files the census counts — § 4.5 assertion 1 fails an unrowed file, and a test fixture would be one. + + Carries its OWN `package.json` (`"type": "module"`) for the same reason the + repository root now carries one (Copilot, PR #14): `tmp_path` sits under the + system temp directory, outside the repository's own directory tree, so the + root `package.json` is not an ancestor of anything copied or written here — + Node would decide this bundle's `.js` format on its own heuristic alone + without a copy of the declaration in the bundle itself. """ web = tmp_path / "web" (web / "views").mkdir(parents=True) + (web / "package.json").write_text( + '{"private": true, "type": "module"}\n', encoding="utf-8") copied = web / "views" / "view_extension.js" copied.write_bytes(REGISTRY_JS.read_bytes()) assert copied.read_bytes() == REGISTRY_JS.read_bytes() @@ -933,3 +942,46 @@ def test_js_refuses_a_shell_region_asked_for_a_standing_element(tmp_path): console.log(JSON.stringify({{ refused: name }})); """, tmp_path) assert result == {"refused": "ViewBindingError"} + + +@pytest.mark.skipif(NODE is None, reason="node is not installed") +def test_js_module_scope_holds_without_node_s_detection_heuristic(tmp_path): + # Copilot, PR #14: this repository ships no `package.json`, so every + # `export`/named-import test above only ran because Node's + # `--experimental-detect-module` (default ON since Node ~20.10, unflagged + # by Node 22) reparses an ambiguous `.js` file as ESM the moment it finds + # module syntax -- proven by hand: importing the real, unmodified + # `view_extension.js` with NO `package.json` anywhere in its parents raises + # `SyntaxError: Named export '...' not found. The requested module '...' is + # a CommonJS module ...` the instant that heuristic is turned off with + # `--no-experimental-detect-module`, which is the same failure shape the + # finding names ("the export/named-import tests fail before exercising the + # registry"). It does not reproduce today against either Node the way this + # suite runs it (locally, or `validate`'s Node 24) only because the + # heuristic happens to be on by default there -- Node's own warning without + # the fix ends 'To eliminate this warning, add "type": "module" to + # .../package.json', which is the fix, not an argument that the gap is + # imaginary. `package.json` (repository root, and one written into every + # `_temp_bundle`) makes the format an explicit, version-independent fact + # instead of a default that a Node upgrade, downgrade or flag could change + # again. This test is the POSITIVE assertion that the fact now holds even + # with the heuristic OFF, for both the real registry (root + # `package.json`) and a `_temp_bundle` copy (bundle-local one) -- + # confirmed failing on the pre-fix tree by hand, not implied. + for label, registry in ( + ("real", REGISTRY_JS.as_uri()), + ("bundle", (_temp_bundle(tmp_path) / "views" + / "view_extension.js").as_uri()), + ): + script = tmp_path / f"no-detect-{label}.mjs" + script.write_text( + f'import {{ VIEW_CLASSES }} from {json.dumps(registry)};\n' + f'console.log(JSON.stringify({{ classes: VIEW_CLASSES }}));\n', + encoding="utf-8") + proc = subprocess.run( + [NODE, "--no-experimental-detect-module", str(script)], + capture_output=True, text=True, timeout=120) + assert proc.returncode == 0, (label, proc.stderr) + assert "CommonJS" not in proc.stderr, (label, proc.stderr) + assert json.loads(proc.stdout.strip()) == { + "classes": list(VIEW_CLASSES)} From e176947dd3691fa96b285575910989ed77e09181 Mon Sep 17 00:00:00 2001 From: Brett Heap <1513478+brettheap@users.noreply.github.com> Date: Sat, 12 Sep 2026 13:16:04 -0400 Subject: [PATCH 09/44] Copilot re-review, three findings: docs-tab migration, declared-entry mount, view-registry isolation MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit tests/test_doc_surfaces.py * test_the_doc_tab_is_wired_to_the_one_cross_view_jump located the docs tab's block by the pre-S3 `{ tab: "tab-docs"` shape, which no longer exists in app.js now that the binding is `{ id, control, region }` (§ 3.4 S3). `app.split(...)[1]` on the absent literal raised IndexError before the renderDocs assertion ever ran. Migrated to split on the registry shape (`{ id: "docs.list", control: "tab-docs", region: "view-docs",`) -- the same one-token-class migration the three test_bullseye_widget.py `.view` -> `.region` quotations already took in this PR (09b42f5). src/opendox/web/app.js * The viewer's `mountGate` adapter called a hard-coded `gateView.exports.mountGateBar` instead of the RESOLVED binding's own declared `entry` export. `resolveView()` already validates that `binding.entry` names a callable export of `binding.module`; a contributed `gate.bar` binding declaring a different entry name would pass that validation and then either mount the wrong function or throw on `undefined` here, because validation and mounting consulted two different names. Now `gateView.exports[gateView.binding.entry](host, gctx, { caps })` -- one token changed. New test_app_js_mounts_the_gate_bar_through_its_declared_entry (tests/test_view_registry.py, S3-created) pins the new expression and asserts the old hard-coded call is absent, as a regression guard. tests/test_view_registry.py * Normal (non-`--noconftest`) pytest loads the root conftest.py, which registers an empty `_SuiteProfile` at collection time -- a test process is a host like any other. This module never cleared that ambient registration before asserting against a clean slate: `registered()`'s `domain_profile.register()` raised AlreadyRegistered against the suite's own profile (reproduced in isolation running test_the_facet_comes_off_the_one_registered_profile alone), and test_no_host_at_all_refuses_rather_than_answering_empty's `assert not domain_profile.is_registered()` saw it registered and failed (also reproduced in isolation; the full-file run happened to pass it only as a side effect of the PRECEDING test's fixture teardown unregistering the conftest profile after its own registration attempt raised). New autouse `_empty_registry`, mirroring test_profile_registration.py's fixture of the same name: save whatever profile is registered (or None), unregister, yield, restore in teardown. Both tests now pass standalone and in any order. Verified: narrowed validate (5 files, --noconftest) 82 passed, 3 xfailed, unchanged. `node --check src/opendox/web/app.js` clean. Normal invocation of both touched files still cannot reach any of these three assertions: `ideation_dashboard` is genuinely absent from this leg by design (pyproject.toml's own dependency note -- it is a cross-column reach the BUILD arc removes), and the root conftest's autouse `declared_human_console` fixture imports `opendox.cli` -> `opendox.serve`, which imports it at module level. Every test in both files errors at fixture setup on that ModuleNotFoundError before reaching either file's body, unchanged by this commit (78 errors before and after -- the pre-existing 77 plus one new test, same reason). Verified instead with a scratch-only, uncommitted `ideation_dashboard` stub that satisfies the import chain with no behavioural stand-in beyond existing, plus isolated per-test and per-line checks against the real files; the PR thread replies give the exact commands and tallies. Also found, NOT fixed here (out of this round's scope and reported to the orchestrator separately): tests/conftest.py's `REPO_ROOT = HERE.parent.parent` is off by one directory now that the carve flattened `tests/ideation-dashboard/` to `tests/` -- it resolves one level above this repository's own root. That is a second, independent reason most of test_doc_surfaces.py (and, by the same `REPO_ROOT` import, roughly three dozen other test files) cannot reach a green normal invocation right now; it masks nothing this commit fixes, and none of this commit's new or changed assertions depend on it. Lane: openxfactory-4-opendox-extraction Refs opensoft/openxFactory#656 Co-Authored-By: Claude Sonnet 5 --- src/opendox/web/app.js | 2 +- tests/test_doc_surfaces.py | 3 ++- tests/test_view_registry.py | 46 +++++++++++++++++++++++++++++++++++++ 3 files changed, 49 insertions(+), 2 deletions(-) diff --git a/src/opendox/web/app.js b/src/opendox/web/app.js index 316b5fa2..3d600ff3 100644 --- a/src/opendox/web/app.js +++ b/src/opendox/web/app.js @@ -991,7 +991,7 @@ async function render() { // Supplied only when a gate binding was collected; absent, the viewer // renders the document and no gate bar (see `gateView` above). mountGate: gateView - ? (host, gctx) => gateView.exports.mountGateBar(host, gctx, { caps }) + ? (host, gctx) => gateView.exports[gateView.binding.entry](host, gctx, { caps }) : null, }); }, diff --git a/tests/test_doc_surfaces.py b/tests/test_doc_surfaces.py index 66162934..e1396e90 100644 --- a/tests/test_doc_surfaces.py +++ b/tests/test_doc_surfaces.py @@ -287,7 +287,8 @@ def test_the_doc_tab_is_wired_to_the_one_cross_view_jump(): """app.js owns every cross-view jump; the doc list must reach the SAME read-only overlay the wheel's `read` verb uses, not a second viewer.""" app = APP_JS.read_text(encoding="utf-8") - block = app.split('{ tab: "tab-docs"', 1)[1].split("},", 1)[0] + block = app.split('{ id: "docs.list", control: "tab-docs", region: "view-docs",', + 1)[1].split("},", 1)[0] assert "renderDocs(root, snap, { onOpenDoc: ctx.nav.openDoc })" in block diff --git a/tests/test_view_registry.py b/tests/test_view_registry.py index a15d029a..123a0b4e 100644 --- a/tests/test_view_registry.py +++ b/tests/test_view_registry.py @@ -419,6 +419,37 @@ class _ProfileWithoutTheFacet: ROUTE_EXTENSIONS = ("the host's routes",) +@pytest.fixture(autouse=True) +def _empty_registry(): + """Every test in this module starts with NO registration, and PUTS BACK + whatever it found — mirrors `test_profile_registration.py`'s fixture of the + same name (Copilot review thread on this PR, `tests/test_view_registry.py + :438`). + + The root `conftest.py` registers an empty `_SuiteProfile` AT COLLECTION + TIME, because a test process is a host like any other. Under a normal + invocation that registration is already live before any test below runs, + so `registered()`'s `domain_profile.register()` raised `AlreadyRegistered` + against the suite's own profile, and + `test_no_host_at_all_refuses_rather_than_answering_empty`'s + `assert not domain_profile.is_registered()` saw it registered and failed — + this module never cleared the ambient registration before asserting + against a clean slate. + + THE RESTORE IS NOT COSMETIC, for the reason `test_profile_registration.py` + gives: a bare teardown that only unregistered would strip the conftest + profile for the rest of the session, and every later test anywhere in the + process that reaches a composition point would then raise + `ProfileNotRegistered` for a reason that has nothing to do with it. + """ + previous = domain_profile.current() if domain_profile.is_registered() else None + domain_profile.unregister() + yield + domain_profile.unregister() + if previous is not None: + domain_profile.register(previous) + + @pytest.fixture def registered(): """Register, yield the proxy, and ALWAYS unregister. @@ -597,6 +628,21 @@ def test_app_js_declares_the_gate_bar_as_an_optional_class_b_binding(): assert "optional: true" in source +def test_app_js_mounts_the_gate_bar_through_its_declared_entry(): + """The viewer's `mountGate` adapter must call the RESOLVED binding's own + declared `entry` export, not a name this file happens to remember (Copilot + review thread on this PR, `app.js:994`). `resolveView()` already validates + that `binding.entry` names a callable export of `binding.module`; a + contributed `gate.bar` binding can declare any entry name and export a + DIFFERENT callable under it, and a hardcoded `mountGateBar` would then + either mount the wrong function or throw on `undefined`. The negative + assertion is the regression guard: the fix is a one-token change a later + edit could silently revert back to the hardcoded name.""" + source = APP_JS.read_text(encoding="utf-8") + assert "gateView.exports[gateView.binding.entry](host, gctx, { caps })" in source + assert "gateView.exports.mountGateBar(host, gctx, { caps })" not in source + + def test_app_js_wires_the_doc_list_through_the_registry(): # The ONE view this slice wires end to end: the class-A doc list. source = APP_JS.read_text(encoding="utf-8") From 031edc9b4268d9898c296b2e9bb3951a78642fb6 Mon Sep 17 00:00:00 2001 From: Brett Heap <1513478+brettheap@users.noreply.github.com> Date: Sat, 12 Sep 2026 13:28:11 -0400 Subject: [PATCH 10/44] =?UTF-8?q?=C2=A7=203.4=20S4:=20split=20the=20three?= =?UTF-8?q?=20RULED=20SPLIT=20files=20=E2=80=94=20thirteen=20route=20tails?= =?UTF-8?q?=20to=20the=20bindings=20that=20call=20them?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit RULED Q3 (opensoft/openxFactory#656 comment 5642758731, Brett Heap, 2026-09-12): "a route constant travels with the binding that calls it, never with the model that happens to declare it." openDox-spec `docs/front-end-package-boundary.md` § 5's S4 row is the PRECONDITION for S5: only 3 of the 13 gate-route constants were declared in class-B files; the other 10 sat in `views/lens-model.js`, `views/repo-selector.js` and `views/staging-workbench-model.js`, and the gate loop cannot be contributed until its route table stops living outside class B. THE THIRTEEN TAILS, and where each went: views/lens-model.js "?" -> A (1070 -> 1075) LENS_SAVE_ROUTE :1036, LENS_CLUSTER_ROUTE :1037 -> views/gate-lens.js (NEW, class B) with the execute affordance, the organizer-evidence form and the outcome panel that call them. The model is pure and import-free again and names no route another column declares. views/repo-selector.js "?" -> A (889 -> 814) :33 /snapshot-index.json -> views/projection-index.js (NEW, class B), reached LATE by a dynamic import inside `fetchIndex` (§ 4.2's own guard, not a ViewBinding — an index fetch mounts no panel and occupies no region) :34 /actions/refresh stays class A: BOTH legs declare a handler :38 /project-register.json stays class A: openDox's own :39 create-project, :43 edit-project -> views/gate-projects.js (NEW, class B), ONE binding carrying the create form and the membership-edit commission :46 /actions/apply-register-edits -> LEFT THE BUNDLE ENTIRELY, with the "⟳ apply N pending" button that reached it. RULING DQ-1 keeps that lane at openxFactory and § 2.2 rule 1 says no class here can ever own it. Commissions still record and still badge as pending; what is gone from this bundle is the button that ran the fulfilment. views/staging-workbench-model.js "?" -> A (C tail) (1949 -> 1943) :543 CREATE_ROUTE -> views/swb-create.js; :817/:818/:821/:822/:826 with the SESSION_ROUTES table and sessionRoute() -> views/swb-session.js. No new file: both are class B already and were always the only callers. REACHED THROUGH THE S3 REGISTRY, NEVER AN IMPORT. `app.js` resolves `gate.lens` and `gate.projects` once per render exactly as it resolves `gate.bar`, and hands each view an already-bound mount or null. Null is what a student install is: the lens plan panel stays plan-only and the selector renders picker + refresh, with no 404 and no dead control. Two new "shell" regions (`lens-gate`, `repo-projects`) are declared in BOTH halves of the registry, in order, so the drift test holds them together. CENSUS AND ASSERTIONS (tests/fixtures/web_boundary_census.yaml, tests/test_web_boundary.py): * the three SPLIT rows are re-classified A with their real post-split line counts; three new class-B rows; `loc` refreshed on every file this slice touched; per-class `totals:` now declared and re-derived from the rows. * ASSERTION 1 gains its post-S4 cutoff (§ 4.5 point 1): any row still "?" or "SPLIT" fails, except what `declared_transitional_rows` names — views/lens.js alone, with the ruling gap and what would discharge it. * ASSERTION 2: all twelve SPLIT-file sites are CLEAN. views/lens.js's two openxFactory-lane sites become the standing DECLARED exception § 4.5's own last paragraph states ("they never entered it"), keyed by route and never by line. Measured residue 10, re-derived and written into the marker: 6 gate-prefix sites, every one of them a class-B binding's `routes:` declaration in app.js's CORE arm (:589/:601 S3's gate.bar, :624/:625/:630 S4's two), all transitional and closing together at S5 when those entries leave for contributedViewBindings(); plus the 4 /source/ sites RULED Q4 re-homes at S6. * the three xfail markers gain `raises=AssertionError` (S1 register nit 1) — a strict xfail with no `raises` tolerates any exception, so a malformed fixture would have read as the expected failure. Assertion 3's stale count (6, measured on the S3 branch before the S2 merge) is re-measured to 4; S4 adds none. The other two S1 nits — the exemption test checking text presence rather than a declaration, and the row-level `exempt:` not being cross-checked — are assertion 4's own and are left to S7. Two dead parameters did not travel with the code they were passed to: `mountCreateProject`'s `projects` and `commissionEdit`'s `control` were never read by either body. Refs opensoft/openxFactory#656 Lane: openxfactory-4-opendox-extraction Co-Authored-By: Claude Fable 5.1 --- src/opendox/view_extension.py | 7 + src/opendox/web/app.js | 49 +++ src/opendox/web/views/gate-lens.js | 204 +++++++++++ src/opendox/web/views/gate-projects.js | 241 ++++++++++++ src/opendox/web/views/lens-model.js | 15 +- src/opendox/web/views/lens.js | 149 ++------ src/opendox/web/views/projection-index.js | 73 ++++ src/opendox/web/views/repo-selector.js | 345 +++++++----------- .../web/views/staging-workbench-model.js | 46 +-- src/opendox/web/views/swb-create.js | 14 +- src/opendox/web/views/swb-session.js | 49 ++- src/opendox/web/views/view_extension.js | 14 +- tests/fixtures/web_boundary_census.yaml | 174 ++++++++- tests/test_web_boundary.py | 253 ++++++++++--- 14 files changed, 1202 insertions(+), 431 deletions(-) create mode 100644 src/opendox/web/views/gate-lens.js create mode 100644 src/opendox/web/views/gate-projects.js create mode 100644 src/opendox/web/views/projection-index.js diff --git a/src/opendox/view_extension.py b/src/opendox/view_extension.py index 237daddf..72d515fe 100644 --- a/src/opendox/view_extension.py +++ b/src/opendox/view_extension.py @@ -154,6 +154,11 @@ #: binding — it has no standing element, so `index.html` cannot #: declare it. `viewer-gatebar` is the viewer's own gate-bar host #: (`views/viewer.js`:342 builds the `div` and calls `mountGate`); +#: `lens-gate` and `repo-projects` are slice S4's, added with the two +#: class-B bindings that mount into them — the lens plan panel's +#: execute box (`views/gate-lens.js`) and the selector's +#: project-commission slot (`views/gate-projects.js`), each a host the +#: view builds and hands over exactly as the viewer does; #: the two `*-intent` regions are slice S2's, declared HERE and now so #: that S2's optional intent-chip bindings fold into this registry #: without re-opening it (§ 6 Q5: "S2 makes the chips an OPTIONAL @@ -173,6 +178,8 @@ "viewer-gatebar": "shell", "wheel-intent": "shell", "dispose-intent": "shell", + "lens-gate": "shell", + "repo-projects": "shell", } #: The facet name a host's profile carries, beside `ROUTE_EXTENSIONS` and diff --git a/src/opendox/web/app.js b/src/opendox/web/app.js index 316b5fa2..9f86c635 100644 --- a/src/opendox/web/app.js +++ b/src/opendox/web/app.js @@ -560,6 +560,9 @@ const CORE_VIEWS = [ // else on the composed view changes. createCaps: ctx.probedCaps, writableRepository: ctx.writableRepository, + // 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, }) }, // 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 @@ -597,6 +600,35 @@ const CORE_VIEWS = [ module: "./views/gate.js", entry: "mountGateBar", view_class: "B", routes: ["/actions/gate/ratify"], requires: ["actions.gate"], optional: true }, + // THE LENS'S TWO GATE VERBS and THE PROJECT COMMISSIONS — slice S4's two new + // class-B bindings, on exactly the footing `gate.bar` above already stands on + // and for the same three reasons. RULED Q3 (openxFactory#656 comment + // `5642758731`): "a route constant travels with the binding that calls it, + // never with the model that happens to declare it" — so the ten gate-prefix + // constants that stood in `views/lens-model.js`, `views/repo-selector.js` and + // `views/staging-workbench-model.js` are now declared in class-B files, and + // the two bindings below declare the four of them that needed a new home as + // their OWN, in the one place the registry can check. + // + // `optional: true` is the whole point: a shell assembled without either one + // renders the lens plan panel plan-only and the selector with no project + // commissions — no gate form, no add row, no trash control, and no 404. + // + // BOTH ENTRIES ARE TRANSITIONAL, like `gate.bar`. They sit in the CORE arm + // because at this slice no column contributes anything; slice S5 moves the + // class-B files behind a contribution openXdox supplies, at which point these + // three entries are deleted and the identical bindings arrive through + // `contributedViewBindings()`. Nothing else in this file changes when they do. + { id: "gate.lens", region: "lens-gate", + module: "./views/gate-lens.js", entry: "mountLensGate", view_class: "B", + routes: ["/actions/gate/lens-save-recipe", + "/actions/gate/lens-add-as-cluster"], + requires: ["actions.gate"], optional: true }, + { id: "gate.projects", region: "repo-projects", + module: "./views/gate-projects.js", entry: "mountProjectCommissions", + view_class: "B", + routes: ["/actions/gate/create-project", "/actions/gate/edit-project"], + requires: ["actions.gate"], optional: true }, ]; // Tab router with the WAI-ARIA roving-tabindex pattern (a11y #19): only the @@ -978,6 +1010,11 @@ async function render() { { views: () => contributedViewBindings(probedCaps) }], { contributedRoutes: manifestRoutes(probedCaps) }); gateView = await resolveView(views, "gate.bar"); + // Slice S4's two, resolved once per render exactly as the gate bar is. Null + // is the honest answer for a shell with no gate column, and each consumer + // below treats it as "plan-only" / "no commissions" rather than as an error. + const lensGateView = await resolveView(views, "gate.lens"); + const projectGateView = await resolveView(views, "gate.projects"); const explorer = mountExplorer(explorerRoot, snapshot, { signal, onOpenFile: (entry, pane, tile) => { @@ -1227,6 +1264,12 @@ async function render() { // `dispose-intent` are declared regions already, so S2 adds an optional // binding and two `lookupView` calls and touches nothing here. views, + // Slice S4's two resolved class-B mounts, handed down already-bound so no + // class-A or class-C view imports a class-B module to reach them. Null + // where the column that supplies them is not installed. + mountLensGate: lensGateView + ? (host, lctx) => lensGateView.exports.mountLensGate(host, lctx) + : null, // the UNSTRIPPED probe and the serve's own writable repository — read by // exactly one affordance (see `createCaps` at the lens's mount) probedCaps, @@ -1262,6 +1305,12 @@ async function render() { // FAILED refresh reports inline and leaves this view exactly as it is. repoSelector = mountRepoSelector(document.getElementById("repopicker"), { index, active, snapshot, caps, projects, + // 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 + mountProjectGate: projectGateView + ? (host, pctx) => projectGateView.exports.mountProjectCommissions(host, pctx) + : null, onSelect: (key) => { storeKey(key); render(); }, onRefreshed: () => render(), }); diff --git a/src/opendox/web/views/gate-lens.js b/src/opendox/web/views/gate-lens.js new file mode 100644 index 00000000..b691daf9 --- /dev/null +++ b/src/opendox/web/views/gate-lens.js @@ -0,0 +1,204 @@ +// THE LENS'S TWO GATE VERBS — class B, and the first half of slice S4's answer +// to RULED Q3 (openxFactory#656 comment `5642758731`, Brett Heap, 2026-09-12): +// **"a route constant travels with the binding that calls it, never with the +// model that happens to declare it."** +// +// WHAT MOVED, AND FROM WHERE. `views/lens-model.js` is the census's purest +// class-A file — "pure and import-free", a geometry/matching derivation unit- +// tested from Python through node — and it carried two `/actions/gate/*` +// constants at :1036 and :1037 (openDox-spec `docs/front-end-package-boundary.md` +// § 1.2(c)'s table, § 3.2's `lens-model.js` row, § 4.5 assertion 2's "gate +// prefix, 10 sites, cleared by S4"). It declared them and never called them: +// `views/lens.js` did, from the execute affordance of its plan panel. Under Q3 +// that makes the model the wrong home twice over — it neither calls them nor +// belongs to the column that serves them — so the two constants, the POST that +// uses them, the organizer-evidence form that feeds one of them and the outcome +// panel that renders either one's answer are all HERE now, in one class-B +// module the gate column owns. +// +// WHY A WHOLE MODULE AND NOT TWO CONSTANTS IN `lens.js`. `views/lens.js` is the +// census's one remaining `"?"` row (§ 3.2; none of Q1–Q5 rules on its two +// openxFactory-lane routes, so it stays `"?"` under assertion 1's declared, +// ruled-later exception). Moving a gate constant into it would relocate the +// § 2.2 rule 1 breach rather than clear it — assertion 2's scope is "every +// census row whose class is not B", and `"?"` is squarely in it. Class B is the +// only home that is not a relocation, and § 2.1's own test says why this file +// is one: delete the gate column and it has nothing left to render. +// +// HOW THE LENS REACHES IT: through the S3 VIEW REGISTRY, never an import. +// `views/lens.js` receives `mountLensGate` as an already-resolved closure from +// the shell (`app.js` resolves the `gate.lens` binding once per render, exactly +// as it resolves `gate.bar` for the viewer) and treats its absence as "no gate +// column here" — which is what a student install is (RULING C2 one tier out, +// § 4.1). That is `consumer_reach`'s posture in the browser: LATE, NAMED and +// REFUSABLE instead of an import-time dependency on a column that may not be +// installed (§ 4.2). +// +// AT S5 THIS FILE LEAVES THE BUNDLE. Its binding is declared in `app.js`'s +// CORE arm today and moves behind a contribution openXdox supplies (§ 5 S5); +// nothing in `lens.js` changes when it does, which is the test of whether the +// seam was drawn in the right place. +// +// WHAT IT DOES NOT OWN. The REQUEST BODIES are pure derivations over a plan the +// panel already confirmed (`recipeRequest` / `clusterRequest`), and a pure +// derivation over the snapshot is class-A substance that stays with the model +// — Q3 moves the ROUTE, not the arithmetic. They are imported from there, which +// is the legal direction (a class-B file may read class A; § 4.5 assertion 3 +// forbids only the reverse). +// +// DOM-SAFETY, unchanged from the code's previous home: every dynamic value — +// including the engine's refusal text — binds through `textContent` (helpers' +// `el`), never `innerHTML`; the only `innerHTML` assignments are literal "" +// clears. +// +// A CREATED file: no row in openxFactory's `docs/opendox-carve-manifest.yaml` +// (RULED OQ-C), admitted by path in `docs/opendox-carve-admissions.yaml`. + +import { el } from "./helpers.js"; +import { clusterRequest, recipeRequest } from "./lens-model.js"; + +// The two gate routes the lens verbs post to (add-lens-gate-verbs). They sit +// under `openxdox/serve_gate.py`'s `ACTIONS_GATE_PREFIX` and are declared by +// the gate column, so they live in the binding that calls them — the deployed +// static image never serves them, and the plan panel probes the gate +// capability before revealing execute. +export const LENS_SAVE_ROUTE = "/actions/gate/lens-save-recipe"; +export const LENS_CLUSTER_ROUTE = "/actions/gate/lens-add-as-cluster"; + +// The routes this binding declares to the registry, in one place so the +// `gate.lens` entry and this module cannot drift apart. +export const LENS_GATE_ROUTES = [LENS_SAVE_ROUTE, LENS_CLUSTER_ROUTE]; + +async function postPlan(route, body, fetcher) { + const doFetch = fetcher || fetch; + const response = await doFetch(route, { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify(body), + }); + try { + return await response.json(); + } catch { + return { ok: false, message: "malformed response (HTTP " + response.status + ")" }; + } +} + +// Render the landing confirmation (success) or the engine's refusal verbatim. +// textContent-bound like every other value here. +function renderOutcome(container, result) { + container.innerHTML = ""; + if (result && result.ok) { + const ok = el("div", "dc-landed"); + ok.appendChild(el("div", "dc-h", "landed ✓ — recorded gate dispatch")); + ok.appendChild(el("div", "dc-line", "manifest: " + result.manifest)); + if (result.pending_entry) { + ok.appendChild(el("div", "dc-line", "pending entry: " + result.pending_entry)); + } + ok.appendChild(el("div", "dc-line", "gate-action record: " + result.record)); + if (result.note) ok.appendChild(el("div", "dc-note", result.note)); + container.appendChild(ok); + } else { + const refused = el("div", "dc-refused"); + refused.appendChild(el("div", "dc-h", "refused ✕")); + refused.appendChild(el("div", "dc-line", (result && result.message) || "gate action failed")); + container.appendChild(refused); + } +} + +// The human-seen organizer evidence form (add-as-cluster only). Collects the +// full contract the engine requires; a blank/short field is NOT pre-validated — +// the engine refuses and the reason renders verbatim (single source of truth). +function renderEvidenceForm(container, actor, onSubmit) { + function clear() { + container.innerHTML = ""; + } + clear(); + const form = el("div", "reason-form evidence-form"); + form.appendChild(el("span", "rf-label", + "human-seen evidence (organizer contract — the engine refuses an incomplete one):")); + const fields = [ + ["proposer", "proposer", actor], + ["revision", "committed revision (40/64-hex)", ""], + ["path", "source path", ""], + ["section", "section", ""], + ["passage_sha256", "passage sha256 (64-hex)", ""], + ["rationale", "rationale", ""], + ["confidence", "confidence 0–1", ""], + ["alternatives", "alternatives (comma-separated; may be empty)", ""], + ]; + const inputs = {}; + for (const [key, label, value] of fields) { + const input = document.createElement("input"); + input.type = "text"; + input.value = value || ""; + input.setAttribute("aria-label", label); + input.setAttribute("placeholder", label); + inputs[key] = input; + form.appendChild(input); + } + const submit = el("button", "cbtn", "execute"); + submit.type = "button"; + const cancel = el("button", "cbtn", "cancel"); + cancel.type = "button"; + submit.addEventListener("click", () => { + const alts = inputs.alternatives.value.split(",").map((s) => s.trim()).filter((s) => s); + const conf = parseFloat(inputs.confidence.value); + onSubmit({ + proposer: inputs.proposer.value.trim(), + revision: inputs.revision.value.trim(), + path: inputs.path.value.trim(), + section: inputs.section.value.trim(), + passage_sha256: inputs.passage_sha256.value.trim(), + rationale: inputs.rationale.value.trim(), + confidence: Number.isNaN(conf) ? inputs.confidence.value.trim() : conf, + alternatives: alts, + }); + }); + cancel.addEventListener("click", clear); + form.appendChild(submit); + form.appendChild(cancel); + container.appendChild(form); +} + +// THE BINDING'S ENTRY. `host` is the plan panel's own box — a `"shell"` region +// (`lens-gate`), which by § 4.1's own definition is a mount point the shell +// builds at mount time and hands over, exactly like `viewer-gatebar`. `ctx` +// carries the confirmed plan, the capability probe's payload and the +// injectable fetcher (the test seam every transport in this bundle keeps). +// +// A save-recipe plan posts immediately; an add-as-cluster plan first collects +// the human-seen organizer evidence, and the engine's refusal for an incomplete +// submission renders here. +export function mountLensGate(host, ctx) { + const o = ctx || {}; + const plan = o.plan; + if (!host || !plan) return null; + const result = el("div", "dc-result"); + result.setAttribute("aria-live", "polite"); + const bar = el("div", "dc-exec"); + const run = el("button", "cbtn", + plan.kind === "add-as-cluster" ? "execute → add as cluster" : "execute → save recipe"); + run.type = "button"; + run.title = "EXECUTES via the local gate route (actor: " + ((o.caps && o.caps.actor) || "local") + ")"; + + async function dispatch(body, route) { + run.disabled = true; + const payload = await postPlan(route, body, o.fetcher); + renderOutcome(result, payload); + if (!(payload && payload.ok)) run.disabled = false; // let a refused plan be retried + } + + run.addEventListener("click", () => { + if (plan.kind === "add-as-cluster") { + renderEvidenceForm(result, (o.caps && o.caps.actor) || "", (evidence) => { + dispatch(clusterRequest(plan, evidence), LENS_CLUSTER_ROUTE); + }); + } else { + dispatch(recipeRequest(plan), LENS_SAVE_ROUTE); + } + }); + bar.appendChild(run); + host.appendChild(bar); + host.appendChild(result); + return { element: bar, result }; +} diff --git a/src/opendox/web/views/gate-projects.js b/src/opendox/web/views/gate-projects.js new file mode 100644 index 00000000..4b1e712a --- /dev/null +++ b/src/opendox/web/views/gate-projects.js @@ -0,0 +1,241 @@ +// THE PROJECT COMMISSIONS — class B, and the second half of slice S4's answer to +// RULED Q3 (openxFactory#656 comment `5642758731`, Brett Heap, 2026-09-12): +// **"a route constant travels with the binding that calls it, never with the +// model that happens to declare it."** +// +// WHAT MOVED, AND FROM WHERE. `views/repo-selector.js` is the file openDox-spec +// `docs/front-end-package-boundary.md` § 3.2 describes as addressing ALL THREE +// COLUMNS from one place: openDox's `/project-register.json` and +// `/actions/refresh`, openXdox's `/snapshot-index.json` and its two +// `/actions/gate/*` project commissions, and openxFactory's own +// `/actions/apply-register-edits` lane. Q3 RULES it SPLIT: "the picker and the +// refresh affordance are class A; the two `/actions/gate/*` project commissions +// become a contributed binding with S4; `/actions/apply-register-edits` is +// openxFactory's lane and leaves the bundle entirely." +// +// THIS FILE IS THAT CONTRIBUTED BINDING. It owns the two gate routes, the +// create-project form that commissions a new project, and the membership-edit +// commission the repo filter's add line and trash controls raise. The PICKER +// stays where it was: choosing what you are looking at is the student's own +// gesture (§ 6 Q3: "moving it whole puts the project picker — the student's way +// to choose what they are working on — behind the gate column"), so only the +// COMMISSIONING half travels. +// +// A COMMISSION IS NOT A WRITE, and that is the whole posture the two routes +// carry with them: the POST records a project-register-edit descriptor plus a +// gate record, and the aggregation-owned register is edited only by the +// fulfilment. Refusals render `textContent`-only; a successful create retires +// the form for the session (the engine's duplicate guard is the backstop). +// +// HOW THE SELECTOR REACHES IT: through the S3 VIEW REGISTRY, never an import. +// `app.js` resolves the `gate.projects` binding once per render — exactly as it +// resolves `gate.bar` for the viewer — and hands `mountRepoSelector` the +// resolved mount, or null. Null is what a student install is: no "New Project…" +// line that acts, no create form, no add row, no trash control, and NO 404 +// (§ 4.1's own promise, RULING C2 one tier out). That is `consumer_reach`'s +// posture in the browser: LATE, NAMED and REFUSABLE instead of an import-time +// dependency on a column that may not be installed (§ 4.2). +// +// AT S5 THIS FILE LEAVES THE BUNDLE. Its binding is declared in `app.js`'s CORE +// arm today and moves behind a contribution openXdox supplies (§ 5 S5); nothing +// in `repo-selector.js` changes when it does, which is the test of whether the +// seam was drawn in the right place — the reason this module is shaped as a +// binding with a `mount` entry and a returned controller rather than as two +// exported helpers the selector calls. +// +// TWO DEAD PARAMETERS DID NOT TRAVEL. The previous `mountCreateProject(wrap, +// status, roster, projects, o, addPendingOption)` never read `projects`, and +// `commissionEdit(body, control, restore)` never read `control` — both callers +// passed a value that the body ignored. Carrying an unread parameter across a +// package boundary would freeze a mistake into the contributed contract, so +// neither is in the signatures below. +// +// DOM-SAFETY, unchanged from the code's previous home: every dynamic value +// binds through `textContent` (helpers' `el`); no `innerHTML` is assigned here +// at all. +// +// A CREATED file: no row in openxFactory's `docs/opendox-carve-manifest.yaml` +// (RULED OQ-C), admitted by path in `docs/opendox-carve-admissions.yaml`. + +import { el } from "./helpers.js"; + +// add-project-scoped-selection: the create-project commission route. +// add-opendox-project-header (D15/D16): the membership-edit commission route +// the filter popover's add line and trash controls POST to. Both sit under +// `openxdox/serve_gate.py`'s `ACTIONS_GATE_PREFIX`, and both degrade away +// exactly like the index: a static image 404s them and the selector renders +// without the affordance. +export const ACTIONS_CREATE_PROJECT_ROUTE = "/actions/gate/create-project"; +export const ACTIONS_EDIT_PROJECT_ROUTE = "/actions/gate/edit-project"; + +// The routes this binding declares to the registry, in one place so the +// `gate.projects` entry and this module cannot drift apart. +export const PROJECT_GATE_ROUTES = [ + ACTIONS_CREATE_PROJECT_ROUTE, ACTIONS_EDIT_PROJECT_ROUTE, +]; + +// The create-project affordance (add-project-scoped-selection): a COMMISSION, +// never a write. Mounted only where this binding is contributed AND the probe +// reports the gate capability. Member candidates are ALL roster repositories: +// membership is multi-parent (Brett's 2026-08-06 ruling), so a repository +// already in a project is a legal member of a new one — projects are named +// views, not owners. +// +// REHOMED by add-opendox-project-header (D13): no standalone button — the +// project dropdown's "New Project" line opens the form through the returned +// opener. +function mountCreateProject(wrap, status, roster, o, addPendingOption) { + const seen = new Set(); + const candidates = []; + for (const option of roster || []) { + if (option.kind !== "repository") continue; + if (seen.has(option.repository)) continue; + seen.add(option.repository); + candidates.push(option.repository); + } + + // A LABELED PANEL, not a bare strip (Brett's 2026-08-06 annotation: "which + // is this? i do not know how to use this widget") — a heading names the + // act, the field and the member list carry captions, and the buttons say + // what happens (a recorded commission, not a direct write). + const form = el("span", "projectform projectpanel"); + form.hidden = true; + form.appendChild(el("span", "panelhead", "New Project")); + form.appendChild(el("span", "panelnote", + "records a project-register commission — the project appears as pending " + + "until a session fulfils it")); + + const nameField = el("label", "panelfield"); + nameField.appendChild(el("span", "panellabel", "project name")); + const name = el("input", "projectname"); + name.type = "text"; + name.placeholder = "e.g. Field Pilots"; + name.setAttribute("aria-label", "new project name"); + nameField.appendChild(name); + form.appendChild(nameField); + + form.appendChild(el("span", "panellabel", "member repositories")); + const memberList = el("span", "panelmembers"); + const boxes = []; + for (const repo of candidates) { + const label = el("label", "projectmember"); + const box = el("input"); + box.type = "checkbox"; + box.value = repo; + label.appendChild(box); + label.appendChild(el("span", null, repo)); + boxes.push(box); + memberList.appendChild(label); + } + if (!candidates.length) { + memberList.appendChild(el("span", "projectform-note", + "no published repositories to choose from")); + } + memberList.appendChild(el("span", "projectform-note", + "optional — an empty project is fine; add repositories later from the " + + "filter")); + form.appendChild(memberList); + + const buttonRow = el("span", "panelbuttons"); + const submit = el("button", "repobtn", "commission project"); + submit.type = "button"; + buttonRow.appendChild(submit); + const cancel = el("button", "repobtn projectcancel", "cancel"); + cancel.type = "button"; + cancel.addEventListener("click", () => { form.hidden = true; }); + buttonRow.appendChild(cancel); + form.appendChild(buttonRow); + + submit.addEventListener("click", async () => { + const members = boxes.filter((b) => b.checked).map((b) => b.value); + status.textContent = ""; + submit.disabled = true; + try { + const opts = { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ name: name.value, repositories: members }), + }; + const response = o.fetcher + ? await o.fetcher(ACTIONS_CREATE_PROJECT_ROUTE, opts) + : await fetch(ACTIONS_CREATE_PROJECT_ROUTE, opts); + const data = await response.json().catch(() => ({})); + if (!response.ok || data?.ok !== true) { + submit.disabled = false; + status.textContent = "create-project refused: " + + (data?.message || data?.error || ("HTTP " + response.status)); + return; + } + form.hidden = true; // retired for the session + status.textContent = "project-register edit recorded (" + data.job + ")"; + // the commission appears in the dropdown immediately as a pending entry + // (D-e) — the register itself changes only when the fulfilment lands + if (addPendingOption) addPendingOption(name.value || data.project_id); + } catch (err) { + submit.disabled = false; + status.textContent = "create-project failed: " + (err?.message || "error"); + } + }); + + wrap.appendChild(form); + return () => { // the "New Project…" opener (D13) + form.hidden = false; + name.focus(); + }; +} + +// THE BINDING'S ENTRY. `host` is the selector's own header slot — a `"shell"` +// region (`repo-projects`), which by § 4.1's definition is a mount point the +// shell builds at mount time and hands over, exactly like `viewer-gatebar`. +// +// `ctx` is `{ roster, status, fetcher, addPendingOption }`: the roster the +// member checklist is drawn from, the selector's one message span (a +// commission's refusal renders where every other selector message does), the +// injectable fetcher every transport in this bundle keeps as its test seam, +// and the dropdown's pending-entry appender. +// +// Returns the two acts the selector triggers and this column performs: +// +// openCreateForm() the D13 "New Project…" line +// commissionEdit(projectId, body, opts) the filter's add row and trash +// +// `opts` for a membership edit is `{ restore, onRecorded }`: `restore` puts the +// control the human clicked back the way it was when the commission is refused +// (a two-click trash re-arms, a select restores its placeholder), and +// `onRecorded(data)` hands the accepted commission back so the selector can +// badge the pending edit (the D-e two-plane posture). Neither is required. +export function mountProjectCommissions(host, ctx) { + const o = ctx || {}; + const status = o.status || el("span", "repopick-msg"); + const openCreateForm = mountCreateProject(host, status, o.roster, o, + o.addPendingOption); + + async function commissionEdit(projectId, body, opts) { + const { restore, onRecorded } = opts || {}; + status.textContent = ""; + try { + const fetchOpts = { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ project_id: projectId, ...body }), + }; + const response = o.fetcher + ? await o.fetcher(ACTIONS_EDIT_PROJECT_ROUTE, fetchOpts) + : await fetch(ACTIONS_EDIT_PROJECT_ROUTE, fetchOpts); + const data = await response.json().catch(() => ({})); + if (!response.ok || data?.ok !== true) { + if (restore) restore(); + status.textContent = "edit-project refused: " + + (data?.message || data?.error || ("HTTP " + response.status)); + return; + } + status.textContent = "membership edit recorded (" + data.job + ")"; + if (onRecorded) onRecorded(data); + } catch (err) { + if (restore) restore(); + status.textContent = "edit-project failed: " + (err?.message || "error"); + } + } + + return { openCreateForm, commissionEdit }; +} diff --git a/src/opendox/web/views/lens-model.js b/src/opendox/web/views/lens-model.js index 12f7a463..1d43818c 100644 --- a/src/opendox/web/views/lens-model.js +++ b/src/opendox/web/views/lens-model.js @@ -1030,11 +1030,16 @@ export function clusterPlan(model, repository, name) { return plan; } -// The two gate routes the lens verbs post to (add-lens-gate-verbs). Mirrors the -// dispose/propose route constants — the deployed static image never serves -// these; the plan panel probes the gate capability before revealing execute. -export const LENS_SAVE_ROUTE = "/actions/gate/lens-save-recipe"; -export const LENS_CLUSTER_ROUTE = "/actions/gate/lens-add-as-cluster"; +// THE TWO GATE ROUTES THE LENS VERBS POST TO ARE NOT DECLARED HERE ANY MORE +// (§ 3.4 slice S4). `LENS_SAVE_ROUTE` and `LENS_CLUSTER_ROUTE` stood at :1036 +// and :1037 of this file at the carve commit and were called from `lens.js`'s +// execute affordance, never from this module — RULED Q3 (openxFactory#656 +// comment `5642758731`, Brett Heap, 2026-09-12): "a route constant travels +// with the binding that calls it, never with the model that happens to declare +// it." Both now live in `views/gate-lens.js`, the class-B binding that calls +// them, and this module is class A outright: pure, import-free, addressing no +// route any column declares. The two body builders below stay — they are pure +// derivations over a plan, which is exactly the substance this module is for. // The request body a save-recipe / add-as-cluster plan posts to its verb route. // PURE: derives the recipe (checked/pinned) + the reasoned overrides from the diff --git a/src/opendox/web/views/lens.js b/src/opendox/web/views/lens.js index 7bfd5917..9d6717af 100644 --- a/src/opendox/web/views/lens.js +++ b/src/opendox/web/views/lens.js @@ -27,7 +27,6 @@ import { buildLensModel, docSummaries, railStats, termMatches, savePlan, clusterPlan, WORKBENCH_DIR, - recipeRequest, clusterRequest, LENS_SAVE_ROUTE, LENS_CLUSTER_ROUTE, } from "./lens-model.js"; // The SVG bullseye renderer lives in ONE place (add-workbench-bullseye-and-create // design D1): this view and the staging workbench's lens panel consume the same @@ -173,13 +172,22 @@ function renderPlan(container, plan, opts) { } box.appendChild(el("div", "dc-line", "lands at: " + plan.landsAt)); if (plan.pendingNote) box.appendChild(el("div", "dc-note", plan.pendingNote)); - // GATE SEAM (add-lens-gate-verbs): when the local gate capability is live - // (loopback + real checkout + resolved actor), the plan gains an execute - // affordance that posts to the verb route. On the deployed static image the - // capability is absent, so this whole block is skipped and the panel stays - // plan-only — byte-for-byte the read-only posture that ships today. - if (gateLive(o.caps)) { - mountExecute(box, plan, o); + // GATE SEAM (add-lens-gate-verbs, re-drawn by § 3.4 slice S4): when the local + // gate capability is live (loopback + real checkout + resolved actor) AND the + // gate column is registered, the plan gains an execute affordance that posts + // to the verb route. Both halves, never either alone — the same AND + // `views/intent-binding.js` states for its own optional binding: the backend + // may claim the capability where no binding is contributed, and this leg may + // carry the binding where no backend answers it. + // + // `mountLensGate` is the `gate.lens` binding's entry, RESOLVED BY THE SHELL + // (`app.js`, through `resolveView`) and handed down already-bound; this view + // imports no class-B module and names no route the gate column declares + // (RULED Q3, § 4.1/§ 4.2). Absent — a student install, or the deployed static + // image whose `/capabilities` 404s — the panel stays plan-only, byte-for-byte + // the read-only posture that shipped before the seam existed. + if (gateLive(o.caps) && o.mountLensGate) { + o.mountLensGate(box, { plan, caps: o.caps, fetcher: o.fetcher }); } else { box.appendChild(el("div", "dc-note", "The tested engine (lens.py) materialises this through the boundary; the " + @@ -208,115 +216,12 @@ async function postPlan(route, body, fetcher) { } } -// Render the landing confirmation (success) or the engine's refusal verbatim. -// textContent-bound like every other value here. -function renderOutcome(container, result) { - container.innerHTML = ""; - if (result && result.ok) { - const ok = el("div", "dc-landed"); - ok.appendChild(el("div", "dc-h", "landed ✓ — recorded gate dispatch")); - ok.appendChild(el("div", "dc-line", "manifest: " + result.manifest)); - if (result.pending_entry) { - ok.appendChild(el("div", "dc-line", "pending entry: " + result.pending_entry)); - } - ok.appendChild(el("div", "dc-line", "gate-action record: " + result.record)); - if (result.note) ok.appendChild(el("div", "dc-note", result.note)); - container.appendChild(ok); - } else { - const refused = el("div", "dc-refused"); - refused.appendChild(el("div", "dc-h", "refused ✕")); - refused.appendChild(el("div", "dc-line", (result && result.message) || "gate action failed")); - container.appendChild(refused); - } -} - -// The execute button + its result area. A save-recipe plan posts immediately; -// an add-as-cluster plan first collects the human-seen organizer evidence (the -// engine refuses an incomplete submission, and that refusal renders here). -function mountExecute(box, plan, o) { - const result = el("div", "dc-result"); - result.setAttribute("aria-live", "polite"); - const bar = el("div", "dc-exec"); - const run = el("button", "cbtn", - plan.kind === "add-as-cluster" ? "execute → add as cluster" : "execute → save recipe"); - run.type = "button"; - run.title = "EXECUTES via the local gate route (actor: " + ((o.caps && o.caps.actor) || "local") + ")"; - - async function dispatch(body, route) { - run.disabled = true; - const payload = await postPlan(route, body, o.fetcher); - renderOutcome(result, payload); - if (!(payload && payload.ok)) run.disabled = false; // let a refused plan be retried - } - - run.addEventListener("click", () => { - if (plan.kind === "add-as-cluster") { - renderEvidenceForm(result, (o.caps && o.caps.actor) || "", (evidence) => { - dispatch(clusterRequest(plan, evidence), LENS_CLUSTER_ROUTE); - }); - } else { - dispatch(recipeRequest(plan), LENS_SAVE_ROUTE); - } - }); - bar.appendChild(run); - box.appendChild(bar); - box.appendChild(result); -} - -// The human-seen organizer evidence form (add-as-cluster only). Collects the -// full contract the engine requires; a blank/short field is NOT pre-validated — -// the engine refuses and the reason renders verbatim (single source of truth). -function renderEvidenceForm(container, actor, onSubmit) { - function clear() { - container.innerHTML = ""; - } - clear(); - const form = el("div", "reason-form evidence-form"); - form.appendChild(el("span", "rf-label", - "human-seen evidence (organizer contract — the engine refuses an incomplete one):")); - const fields = [ - ["proposer", "proposer", actor], - ["revision", "committed revision (40/64-hex)", ""], - ["path", "source path", ""], - ["section", "section", ""], - ["passage_sha256", "passage sha256 (64-hex)", ""], - ["rationale", "rationale", ""], - ["confidence", "confidence 0–1", ""], - ["alternatives", "alternatives (comma-separated; may be empty)", ""], - ]; - const inputs = {}; - for (const [key, label, value] of fields) { - const input = document.createElement("input"); - input.type = "text"; - input.value = value || ""; - input.setAttribute("aria-label", label); - input.setAttribute("placeholder", label); - inputs[key] = input; - form.appendChild(input); - } - const submit = el("button", "cbtn", "execute"); - submit.type = "button"; - const cancel = el("button", "cbtn", "cancel"); - cancel.type = "button"; - submit.addEventListener("click", () => { - const alts = inputs.alternatives.value.split(",").map((s) => s.trim()).filter((s) => s); - const conf = parseFloat(inputs.confidence.value); - onSubmit({ - proposer: inputs.proposer.value.trim(), - revision: inputs.revision.value.trim(), - path: inputs.path.value.trim(), - section: inputs.section.value.trim(), - passage_sha256: inputs.passage_sha256.value.trim(), - rationale: inputs.rationale.value.trim(), - confidence: Number.isNaN(conf) ? inputs.confidence.value.trim() : conf, - alternatives: alts, - }); - }); - cancel.addEventListener("click", clear); - form.appendChild(submit); - form.appendChild(cancel); - container.appendChild(form); -} +// The execute affordance, the human-seen organizer evidence form and the +// outcome panel that used to sit here are `views/gate-lens.js`'s now (§ 3.4 +// slice S4, RULED Q3): they are what CALLS the two gate routes, so they travel +// with the binding that owns them. What stays is `postPlan` above — still used +// by this view's own two openxFactory-lane drafting routes, which no ruling in +// this round places (§ 6: none of Q1–Q5 rules on this file). // ---- pane 1: keyword rail (check = stratify, pin = require) ---- @@ -1104,6 +1009,10 @@ export function renderLens(root, snapshot, opts) { const createCaps = options.createCaps || caps; const writableRepository = options.writableRepository || null; const fetcher = options.fetcher || null; + // The `gate.lens` binding's entry, already resolved by the shell (§ 3.4 slice + // S4). Null where no gate column is registered, which is exactly what a + // student install is — the plan panel then renders plan-only. + const mountLensGate = options.mountLensGate || null; root.innerHTML = ""; // D21 — the vocabulary. `composedSnapshot` is the UNNARROWED composed @@ -1469,14 +1378,16 @@ export function renderLens(root, snapshot, opts) { save.type = "button"; save.addEventListener("click", () => { const model = buildLensModel(snapshot, query()); - renderPlan(confirm, savePlan(model, repository, ctx.setName()), { caps, fetcher }); + renderPlan(confirm, savePlan(model, repository, ctx.setName()), + { caps, fetcher, mountLensGate }); }); const cluster = el("button", "cbtn", "→ add as cluster (workbench set + human-seen proposal)"); cluster.type = "button"; cluster.addEventListener("click", () => { const model = buildLensModel(snapshot, query()); - renderPlan(confirm, clusterPlan(model, repository, ctx.setName()), { caps, fetcher }); + renderPlan(confirm, clusterPlan(model, repository, ctx.setName()), + { caps, fetcher, mountLensGate }); }); box.appendChild(save); box.appendChild(cluster); diff --git a/src/opendox/web/views/projection-index.js b/src/opendox/web/views/projection-index.js new file mode 100644 index 00000000..1019283e --- /dev/null +++ b/src/opendox/web/views/projection-index.js @@ -0,0 +1,73 @@ +// THE SNAPSHOT-INDEX READ — the third of slice S4's route tails, and the one +// that is not a gate act. +// +// WHAT MOVED, AND WHY IT HAD TO. `views/repo-selector.js`:33 declared +// `SNAPSHOT_INDEX_ROUTE = "/snapshot-index.json"` and fetched it. That route is +// openXdox's: `openxdox/serve_projection.py`:56 declares it and contributes it +// through `route_extension`, and openDox-spec +// `docs/front-end-package-boundary.md` § 3.3's ownership table lists it beside +// `/source`, `/source/` and the three `/projections/*` as the PROJECTION +// column's own. § 2.2 rule 1 is stated over OWNERSHIP and not over class B +// alone precisely so this case is a breach and not a layout choice — "§ 3.3 +// measures three route owners, so the rule has to be stated over ownership or +// it misses two of the three kinds of breach the census actually found" — and +// § 4.5 assertion 2's table names this exact site as one of the twelve that +// clear at S4. +// +// WHY THIS FILE IS CLASS B IN THE CENSUS, AND WHAT THAT DOES AND DOES NOT +// CLAIM. § 2.1 names class B "the gate loop", and this is not a gate act: it is +// a GET of a projection. What assertion 2 actually exempts, though, is not +// "gate-ness" but the last clause of class B's own definition — "its BINDING +// belongs to `openXdox-code` through the seam § 4 describes" — because a file +// naming a route the column that supplies it declares is the boundary working, +// not breaking. That is exactly true here, by the same § 3.3 table that makes +// the old site a breach. The census has no fourth letter for "belongs to the +// projection column", so this row takes the one class whose exemption it +// actually earns, and says so here rather than by silence. REGISTERED for the +// note's owner: § 2.1's class-B headline is narrower than the property § 4.5 +// assertion 2 exempts on, and either the class should be stated over the +// contributed column or the projection column should get a letter of its own. +// +// WHY A LATE, NAMED, REFUSABLE REACH AND NOT A ViewBinding. § 4.2 settles this +// for the intent chips and the reasoning is the same one line over: "§ 4.1 +// binds at the region grain — a whole tab or overlay — not a fragment a view +// renders internally". An index FETCH mounts no panel and occupies no region, +// so a `ViewBinding` is the wrong instrument; what S2 established instead is +// "a small, local, late-and-refusable guard directly against the module's own +// presence — an optional resolve in place of the import-time `from`". That is +// how `views/repo-selector.js` reads this file: a dynamic `import()` inside its +// own `fetchIndex`, resolved once and cached, answering null when the module is +// not there. `fetchIndex` ALREADY promised exactly that shape — "ANY failure (a +// static image 404s this route, an old server does not know it, `file://` +// throws) resolves to null — the caller then renders exactly today's +// single-snapshot dashboard" — so an absent projection column joins a list the +// selector has always degraded against, and nothing downstream changes. +// +// AT S5 THIS FILE LEAVES THE BUNDLE with the other class-B files (§ 5 S5), at +// which point the reach above starts answering null on a student install and +// the selector renders the single baked snapshot, which is what the static +// image already does today. +// +// A CREATED file: no row in openxFactory's `docs/opendox-carve-manifest.yaml` +// (RULED OQ-C), admitted by path in `docs/opendox-carve-admissions.yaml`. + +// The roster + per-entry freshness projection. `openxdox/serve_projection.py` +// declares it; a static image 404s it, and that is a first-class outcome here +// rather than an error. +export const SNAPSHOT_INDEX_ROUTE = "/snapshot-index.json"; + +// Fetch the snapshot index. ANY failure resolves to null — the caller then +// renders exactly today's single-snapshot dashboard. Never throws. The +// injectable fetcher is the same test seam every transport in this bundle +// keeps. +export async function fetchSnapshotIndex(injectedFetch) { + try { + const response = injectedFetch + ? await injectedFetch(SNAPSHOT_INDEX_ROUTE, { cache: "no-store" }) + : await fetch(SNAPSHOT_INDEX_ROUTE, { cache: "no-store" }); + if (!response?.ok) return null; + return await response.json(); + } catch { + return null; + } +} diff --git a/src/opendox/web/views/repo-selector.js b/src/opendox/web/views/repo-selector.js index e7c89009..92990d81 100644 --- a/src/opendox/web/views/repo-selector.js +++ b/src/opendox/web/views/repo-selector.js @@ -3,11 +3,35 @@ // that switches the ACTIVE (repository, ref) snapshot and asks the serving side // for fresher data. // -// TWO same-origin backend routes, both answered by serve.py and both absent from -// a static image (which is exactly how the whole control degrades away): -// GET /snapshot-index.json — the roster + per-entry freshness -// POST /actions/refresh — ONE affordance, the BINDING chosen by the plane -// (served: re-fetch; local: regenerate) +// SPLIT AT § 3.4 SLICE S4 (RULED Q3, openxFactory#656 comment `5642758731`, +// Brett Heap, 2026-09-12: "a route constant travels with the binding that calls +// it, never with the model that happens to declare it"). This file used to +// address ALL THREE COLUMNS from one place — openDox's, openXdox's and +// openxFactory's own — which openDox-spec `docs/front-end-package-boundary.md` +// § 3.2 records as the reason it was RULED SPLIT. What is left here is class A: +// +// GET /project-register.json — openDox's own register projection, read by +// the project picker (`serve_project.py`) +// POST /actions/refresh — ONE affordance, the BINDING chosen by the +// plane (served: re-fetch; local: regenerate), +// declared by BOTH legs (§ 3.3's table) +// +// and both are absent from a static image, which is exactly how the whole +// control degrades away. What LEFT, and where to: +// +// /snapshot-index.json — openXdox's projection: `views/projection-index.js`, +// reached LATE and REFUSABLY by `fetchIndex` below +// the two /actions/gate/* project commissions +// — `views/gate-projects.js`, the class-B binding +// the shell resolves and hands in as +// `mountProjectGate` +// /actions/apply-register-edits +// — openxFactory's own fulfilment lane, which +// RULING DQ-1 keeps at openxFactory: it LEFT +// THE BUNDLE ENTIRELY, with the "⟳ apply N +// pending" button that reached it. See the note +// at `mountRepoSelector` for what that means +// for a commissioned-but-unfulfilled register. // The bundle NEVER addresses the external data source: the serving side performs // that fetch (design D5), so the grep-proven no-external-URL boundary in // tests/ideation-dashboard/test_renderer.py survives this change unedited. @@ -30,20 +54,11 @@ import { } from "./repo-selector-model.js"; import { VIEW_SHARED, VIEW_UNION } from "./composed-model.js"; -export const SNAPSHOT_INDEX_ROUTE = "/snapshot-index.json"; export const ACTIONS_REFRESH_ROUTE = "/actions/refresh"; // add-project-scoped-selection: the register projection the project picker -// reads, and the create-project commission route. Both degrade away exactly -// like the index: a static image 404s them and the selector renders unscoped. +// reads. openDox's own (`serve_project.py`), and it degrades away exactly like +// the index: a static image 404s it and the selector renders unscoped. export const PROJECT_REGISTER_PROJECTION_ROUTE = "/project-register.json"; -export const ACTIONS_CREATE_PROJECT_ROUTE = "/actions/gate/create-project"; -// add-opendox-project-header (D15/D16): the membership-edit commission route -// the filter popover's add line and trash controls POST to. Same degrade -// contract as its siblings. -export const ACTIONS_EDIT_PROJECT_ROUTE = "/actions/gate/edit-project"; -// add-register-edit-lane: the apply button's route — the serve runs the -// fulfilment lane once (loopback + gate only). -export const ACTIONS_APPLY_REGISTER_EDITS_ROUTE = "/actions/apply-register-edits"; // The viewer's project scope survives the reload a selection triggers. It is // THIRD-PARTY DATA on the way back in: it only ever filters client-side // (membership-checked against the loaded projection) and never reaches a URL. @@ -62,19 +77,40 @@ function el(tag, cls, text) { return node; } +// THE PROJECTION COLUMN, REACHED LATE (§ 3.4 slice S4, § 4.2). The snapshot +// index is `/snapshot-index.json`, which `openxdox/serve_projection.py` declares +// and contributes — another column's route, so § 2.2 rule 1 keeps it out of this +// class-A file. `views/projection-index.js` owns the constant and the fetch, and +// this is the "small, local, late-and-refusable guard directly against the +// module's own presence" § 4.2 establishes for exactly this shape: a dynamic +// import(), never a static one, resolved ONCE and remembered. An absent +// projection column answers null, which is the outcome `fetchIndex` has always +// promised for a route nothing serves. +// +// `undefined` means "not yet asked"; `null` means "asked, and there is no +// projection column here" — two states, so a leg without the module pays for +// one rejected import and not one per poll. +let PROJECTION_COLUMN; + +async function projectionColumn() { + if (PROJECTION_COLUMN === undefined) { + try { + PROJECTION_COLUMN = await import("./projection-index.js"); + } catch { + PROJECTION_COLUMN = null; + } + } + return PROJECTION_COLUMN; +} + // Fetch the snapshot index. ANY failure (a static image 404s this route, an old -// server does not know it, file:// throws) resolves to null — the caller then -// renders exactly today's single-snapshot dashboard. Never throws. +// server does not know it, file:// throws, no projection column is installed) +// resolves to null — the caller then renders exactly today's single-snapshot +// dashboard. Never throws. export async function fetchIndex(injectedFetch) { - try { - const response = injectedFetch - ? await injectedFetch(SNAPSHOT_INDEX_ROUTE, { cache: "no-store" }) - : await fetch(SNAPSHOT_INDEX_ROUTE, { cache: "no-store" }); - if (!response?.ok) return null; - return await response.json(); - } catch { - return null; - } + const column = await projectionColumn(); + if (!column) return null; + return column.fetchSnapshotIndex(injectedFetch); } // POST the refresh. Resolves to the backend's freshness result, or throws an @@ -186,118 +222,13 @@ export function refreshBinding(caps) { return caps?.refresh?.binding || null; } -// The create-project affordance (add-project-scoped-selection): a COMMISSION, -// never a write — the POST records a project-register-edit descriptor + gate -// record and the aggregation-owned register is edited only by the fulfilment. -// Mounted only under the gate capability WITH a served register projection. -// Member candidates are ALL roster repositories: membership is multi-parent -// (Brett's 2026-08-06 ruling), so a repository already in a project is a -// legal member of a new one — projects are named views, not owners. -// Refusals render textContent-only; a successful commission retires the -// form for the session (the engine's duplicate guard is the backstop). -// -// REHOMED by add-opendox-project-header (D13): no standalone button — the -// project dropdown's "New Project" line opens the form through the returned -// opener. -function mountCreateProject(wrap, status, roster, projects, o, addPendingOption) { - const seen = new Set(); - const candidates = []; - for (const option of roster) { - if (option.kind !== "repository") continue; - if (seen.has(option.repository)) continue; - seen.add(option.repository); - candidates.push(option.repository); - } - - // A LABELED PANEL, not a bare strip (Brett's 2026-08-06 annotation: "which - // is this? i do not know how to use this widget") — a heading names the - // act, the field and the member list carry captions, and the buttons say - // what happens (a recorded commission, not a direct write). - const form = el("span", "projectform projectpanel"); - form.hidden = true; - form.appendChild(el("span", "panelhead", "New Project")); - form.appendChild(el("span", "panelnote", - "records a project-register commission — the project appears as pending " - + "until a session fulfils it")); - - const nameField = el("label", "panelfield"); - nameField.appendChild(el("span", "panellabel", "project name")); - const name = el("input", "projectname"); - name.type = "text"; - name.placeholder = "e.g. Field Pilots"; - name.setAttribute("aria-label", "new project name"); - nameField.appendChild(name); - form.appendChild(nameField); - - form.appendChild(el("span", "panellabel", "member repositories")); - const memberList = el("span", "panelmembers"); - const boxes = []; - for (const repo of candidates) { - const label = el("label", "projectmember"); - const box = el("input"); - box.type = "checkbox"; - box.value = repo; - label.appendChild(box); - label.appendChild(el("span", null, repo)); - boxes.push(box); - memberList.appendChild(label); - } - if (!candidates.length) { - memberList.appendChild(el("span", "projectform-note", - "no published repositories to choose from")); - } - memberList.appendChild(el("span", "projectform-note", - "optional — an empty project is fine; add repositories later from the " - + "filter")); - form.appendChild(memberList); - - const buttonRow = el("span", "panelbuttons"); - const submit = el("button", "repobtn", "commission project"); - submit.type = "button"; - buttonRow.appendChild(submit); - const cancel = el("button", "repobtn projectcancel", "cancel"); - cancel.type = "button"; - cancel.addEventListener("click", () => { form.hidden = true; }); - buttonRow.appendChild(cancel); - form.appendChild(buttonRow); - - submit.addEventListener("click", async () => { - const members = boxes.filter((b) => b.checked).map((b) => b.value); - status.textContent = ""; - submit.disabled = true; - try { - const opts = { - method: "POST", - headers: { "Content-Type": "application/json" }, - body: JSON.stringify({ name: name.value, repositories: members }), - }; - const response = o.fetcher - ? await o.fetcher(ACTIONS_CREATE_PROJECT_ROUTE, opts) - : await fetch(ACTIONS_CREATE_PROJECT_ROUTE, opts); - const data = await response.json().catch(() => ({})); - if (!response.ok || data?.ok !== true) { - submit.disabled = false; - status.textContent = "create-project refused: " - + (data?.message || data?.error || ("HTTP " + response.status)); - return; - } - form.hidden = true; // retired for the session - status.textContent = "project-register edit recorded (" + data.job + ")"; - // the commission appears in the dropdown immediately as a pending entry - // (D-e) — the register itself changes only when the fulfilment lands - if (addPendingOption) addPendingOption(name.value || data.project_id); - } catch (err) { - submit.disabled = false; - status.textContent = "create-project failed: " + (err?.message || "error"); - } - }); - - wrap.appendChild(form); - return () => { // the "New Project…" opener (D13) - form.hidden = false; - name.focus(); - }; -} +// THE CREATE-PROJECT FORM IS `views/gate-projects.js`'S NOW (§ 3.4 slice S4). +// `mountCreateProject` stood here and POSTed the create-project commission +// route from a class-A file; RULED Q3 sends both the route and the form that +// raises it to the class-B binding the gate column owns. The shell resolves that +// binding and hands its mount in as `mountProjectGate`; the dropdown's "New +// Project…" line calls the opener it returns. Absent — a student install — the +// line is disabled and there is no form, no 404 and no dead control. // The repo FILTER (add-opendox-project-header D14/D16): one icon, one // popover scoped to the CURRENT project, working like the project dropdown @@ -315,7 +246,13 @@ function mountProjectFilter(project, roster, pendingEdits, opts) { const holder = el("span", "repofilter"); if (!project) return holder; const o = opts || {}; - const gated = gateCapable(o.caps); + // Gated is the AND of "the backend says the gate capability is live" and "the + // gate column is registered here" (§ 3.4 slice S4) — never either alone, the + // same conjunction `views/intent-binding.js` states for its own optional + // binding. `o.gate` is the shell-resolved `gate.projects` controller; absent, + // the add line and the trash controls are not rendered at all and the rows + // stay selectable, which is the gate-off posture D16 already described. + const gated = gateCapable(o.caps) && !!o.gate; // reread per render: a same-page commission appends to `pendingEdits`, // and edits QUEUE (topic D18) — the overlay is the NET of every queued row const currentPendingEdit = () => netPendingEdit(pendingEdits, project); @@ -354,33 +291,21 @@ function mountProjectFilter(project, roster, pendingEdits, opts) { button.setAttribute("aria-expanded", pop.hidden ? "false" : "true"); }); - async function commissionEdit(body, control, restore) { - o.status.textContent = ""; - try { - const fetchOpts = { - method: "POST", - headers: { "Content-Type": "application/json" }, - body: JSON.stringify({ project_id: project.id, ...body }), - }; - const response = o.fetcher - ? await o.fetcher(ACTIONS_EDIT_PROJECT_ROUTE, fetchOpts) - : await fetch(ACTIONS_EDIT_PROJECT_ROUTE, fetchOpts); - const data = await response.json().catch(() => ({})); - if (!response.ok || data?.ok !== true) { - if (restore) restore(); - o.status.textContent = "edit-project refused: " - + (data?.message || data?.error || ("HTTP " + response.status)); - return; - } - o.status.textContent = "membership edit recorded (" + data.job + ")"; - // badge immediately (D-e): re-render with this edit pending - pendingEdits = (pendingEdits || []).concat([{ - projectId: project.id, add: data.add, remove: data.remove }]); - renderRows(); - } catch (err) { - if (restore) restore(); - o.status.textContent = "edit-project failed: " + (err?.message || "error"); - } + // THE COMMISSION ITSELF IS THE GATE COLUMN'S (§ 3.4 slice S4). This view owns + // the CONTROL — which row, which repository, armed or not — and hands the act + // to the `gate.projects` binding, which owns the route, the POST and the + // refusal text. What stays here is what the popover must do with the answer: + // badge the accepted edit immediately (D-e) and re-render. + function commissionEdit(body, restore) { + if (!o.gate) return; + o.gate.commissionEdit(project.id, body, { + restore, + onRecorded: (data) => { + pendingEdits = (pendingEdits || []).concat([{ + projectId: project.id, add: data.add, remove: data.remove }]); + renderRows(); + }, + }); } // D16's first line, refined by Brett's 2026-08-06 annotation: ONE dropdown @@ -406,7 +331,7 @@ function mountProjectFilter(project, roster, pendingEdits, opts) { select.addEventListener("change", () => { const chosen = select.value; select.value = ""; // the placeholder line returns - if (chosen) commissionEdit({ add: [chosen] }, select, null); + if (chosen) commissionEdit({ add: [chosen] }, null); }); pop.appendChild(select); } @@ -574,7 +499,7 @@ function mountProjectFilter(project, roster, pendingEdits, opts) { return; } trash.disabled = true; - commissionEdit({ remove: [row.repository] }, trash, () => { + commissionEdit({ remove: [row.repository] }, () => { trash.disabled = false; armed = false; trash.textContent = "\ud83d\uddd1"; @@ -606,6 +531,24 @@ function mountProjectFilter(project, roster, pendingEdits, opts) { // `onSelect(key)` is the caller's "load that snapshot" hook; `onRefreshed(result)` // runs after a successful refresh. Both `fetchIndex`/`postRefresh` are injectable // for tests, and `schedule` replaces setInterval so the poll is testable. +// +// `mountProjectGate` is the `gate.projects` binding's entry, already resolved by +// the shell (§ 3.4 slice S4) or null. Present, the project commissions are +// available: the dropdown's "New Project…" line opens the create form and the +// filter's add line and trash controls raise membership edits. Null — a student +// install, or any plane with no gate column — and none of that renders, with no +// 404 and no dead control, which is RULING C2 one tier out. +// +// WHAT LEFT WITH SLICE S4 AND IS NOT REPLACED HERE: the "⟳ apply N pending" +// button. It POSTed openxFactory's own fulfilment lane, which RULING DQ-1 keeps +// at openxFactory ("a front end that hardcodes them ships one repository's lanes +// to every install", § 3.3), so RULED Q3 has it leave the bundle entirely rather +// than move to a class. Commissions still RECORD and still badge as pending +// exactly as before — what no longer exists in this bundle is the button that +// ran the fulfilment; openxFactory runs its own lane, and if it wants the button +// back it contributes one through the S3 registry the way S2's intent chips +// return. `onRefreshed` therefore has exactly one caller again: a successful +// refresh. export function mountRepoSelector(host, opts) { const o = opts || {}; const post = o.post || postRefresh; @@ -669,6 +612,16 @@ export function mountRepoSelector(host, opts) { let scope = defaultProjectScope(projects, storedProjectScope(o.storage)); const currentProject = () => projects.find((p) => p.id === scope) || null; + // The `gate.projects` controller, declared before the first render because + // the filter's own gate verdict reads it (§ 3.4 slice S4). `available` is + // knowable up front — the capability the probe reported AND a binding the + // shell resolved — while `commissionEdit` is only needed at click time, by + // which point the mount below has filled it in. + const projectGate = { + available: gateCapable(caps) && !!o.projects && !!o.mountProjectGate, + commissionEdit: null, + }; + // ---- the repo FILTER (D14): one icon, one popover, the current // project's members; re-rendered whenever the project changes ---- let filterWrap = null; @@ -679,6 +632,7 @@ export function mountRepoSelector(host, opts) { const view = projectViewState(project, o.storage, active); const next = mountProjectFilter(project, roster, pendingEdits, { active, caps, status, projects, fetcher: o.fetcher, + gate: projectGate.available ? projectGate : null, visible: view.visible, viewMode: view.mode, onSelect: (key) => o.onSelect?.(key), onView: (state) => { @@ -716,7 +670,8 @@ export function mountRepoSelector(host, opts) { picker.setAttribute("aria-label", "current project"); const newRow = el("option", "projectnew", "New Project…"); newRow.value = "__new__"; - if (!gateCapable(caps)) newRow.disabled = true; // creating is a gate act + // creating is a gate act, AND it needs the column that performs it + if (!projectGate.available) newRow.disabled = true; picker.appendChild(newRow); for (const project of projects) { const opt = el("option", null, project.name); @@ -776,46 +731,16 @@ export function mountRepoSelector(host, opts) { // hint. Re-derived and re-rendered, so it appears on the next poll and on // the shell's own nudge after a session opens. rosterChanged = () => { roster = buildRoster(index); renderFilter(); }; - if (gateCapable(caps) && o.projects) { - openCreateForm = mountCreateProject(wrap, status, roster, projects, o, - addPendingOption); - // add-register-edit-lane: the UPDATE button — visible whenever - // recorded commissions await fulfilment; the serve runs the lane once - // and the shell reloads onto the new register truth. - const pendingCount = pendingProjects.length + pendingEdits.length; - if (pendingCount) { - const apply = el("button", "repobtn applybtn", - "⟳ apply " + pendingCount + " pending"); - apply.type = "button"; - apply.title = "fulfil the recorded project-register commissions now " - + "(validate, deliver, commit, push)"; - apply.addEventListener("click", async () => { - apply.disabled = true; - status.textContent = "applying…"; - try { - const response = o.fetcher - ? await o.fetcher(ACTIONS_APPLY_REGISTER_EDITS_ROUTE, { method: "POST" }) - : await fetch(ACTIONS_APPLY_REGISTER_EDITS_ROUTE, { method: "POST" }); - const data = await response.json().catch(() => ({})); - if (!response.ok || data?.ok !== true) { - apply.disabled = false; - status.textContent = "apply failed: " - + (data?.error || ("HTTP " + response.status)) - + (data?.skipped?.length - ? " — skipped: " + data.skipped.map((s) => s[1] + " (" + s[2] + ")").join("; ") - : ""); - return; - } - status.textContent = "applied " + (data.applied?.length || 0) - + (data.skipped?.length ? (", skipped " + data.skipped.length) : ""); - if (typeof o.onRefreshed === "function") o.onRefreshed(data); - } catch (err) { - apply.disabled = false; - status.textContent = "apply failed: " + (err?.message || "error"); - } - }); - wrap.appendChild(apply); - } + if (projectGate.available) { + // The contributed binding mounts into the slot the selector built for it + // and hands back the two acts this view triggers. Mounted HERE, in the + // position the create form has always occupied, so the header's DOM order + // is unchanged by the split. + const controller = o.mountProjectGate(wrap, { + roster, status, fetcher: o.fetcher, addPendingOption, + }); + openCreateForm = controller.openCreateForm; + projectGate.commissionEdit = controller.commissionEdit; } } if (refreshCapable(caps)) { diff --git a/src/opendox/web/views/staging-workbench-model.js b/src/opendox/web/views/staging-workbench-model.js index 125487fb..d1104d6c 100644 --- a/src/opendox/web/views/staging-workbench-model.js +++ b/src/opendox/web/views/staging-workbench-model.js @@ -540,7 +540,9 @@ export const BRAINSTORM_AREA = "ideation/brainstorm/"; export const STAGING_AREA = "ideation/staging/"; export const CREATE_TABS = ["docs", "lens", "outline"]; export const STATUS_BRAINSTORM = "brainstorm"; -export const CREATE_ROUTE = "/actions/gate/create-document"; +// `CREATE_ROUTE` stood on the next line at the carve commit (:543) and is +// `views/swb-create.js`'s now — RULED Q3 (§ 3.4 slice S4): the dialog that +// POSTs it is the binding that calls it, and this module never did. export const CREATE_CLI = "python3 src/opendox/cli.py"; // A staged scope writes into its OWN topic folder; a cluster or a possible has @@ -811,19 +813,23 @@ export function existingOnTopic(snapshot, topics, area) { export const MAIN_REF = "main"; -// The three routes the session surface addresses. Constants HERE (never literals -// in the transport) so the wire contract has one definition the Python route -// tests read too. -export const EDIT_DOCUMENT_ROUTE = "/actions/gate/edit-document"; -export const OPEN_PR_ROUTE = "/actions/gate/open-pr"; -// 010-doxbench-editor-chat T080: the first-Save gate verb. A CANVAS seam, not -// a session-bar affordance -- deliberately absent from SESSION_AFFORDANCES. -export const FIRST_EDIT_ROUTE = "/actions/gate/first-edit"; -export const ABANDON_SESSION_ROUTE = "/actions/gate/abandon-session"; -// add-doxbench-editing-phase-b §12: the SHARE route, beside open-pr's because it -// is the same class of act (a remote write with the engineer's own credential) -// with the pull request removed. -export const SHARE_SESSION_ROUTE = "/actions/gate/share-session"; +// THE FIVE SESSION ROUTES ARE NOT DECLARED HERE ANY MORE (§ 3.4 slice S4). +// `EDIT_DOCUMENT_ROUTE` (:817), `OPEN_PR_ROUTE` (:818), `FIRST_EDIT_ROUTE` +// (:821), `ABANDON_SESSION_ROUTE` (:822) and `SHARE_SESSION_ROUTE` (:826) stood +// here at the carve commit, together with the `SESSION_ROUTES` table and +// `sessionRoute()` that read them. Every one of them is called from +// `views/swb-session.js` — the class-B module that owns the three live session +// verbs and the doxBench Save — and from nowhere else, so RULED Q3 +// (openxFactory#656 comment `5642758731`, Brett Heap, 2026-09-12) sends them +// there: "a route constant travels with the binding that calls it, never with +// the model that happens to declare it." The reason they were HERE is still +// honoured and is now honoured in the right place: they remain CONSTANTS, never +// literals in the transport, with one definition the node harness and the +// Python route tests can read — in `swb-session.js` instead of this file. +// +// The AFFORDANCE ids (`SESSION_EDIT` and its kind), the VERB names, the labels +// and every request builder stay here: they are the workbench's own vocabulary +// and its pure derivations, which is the substance § 2.1 leaves with the model. // THE HUMAN-CONSOLE HEADER (FR-019's third clause; PR #49 review finding 2). // The serve mints a token at start-up and publishes it on `/capabilities`, the @@ -953,14 +959,6 @@ export const LIVE_SESSION_AFFORDANCES = [SESSION_EDIT, SESSION_SHARE, SESSION_SAVE, SESSION_ABANDON]; export const DESCRIPTOR_ONLY_AFFORDANCES = [SESSION_REFRESH_NOTEBOOK]; -const SESSION_ROUTES = { - [SESSION_EDIT]: EDIT_DOCUMENT_ROUTE, - [SESSION_SAVE]: OPEN_PR_ROUTE, - [SESSION_ABANDON]: ABANDON_SESSION_ROUTE, - [SESSION_SHARE]: SHARE_SESSION_ROUTE, - [SESSION_FIRST_EDIT]: FIRST_EDIT_ROUTE, -}; - // affordance -> the gate verb it IS, which is also the `cli.py gate ` name // (FR-020's parity is one vocabulary, not two). export const SESSION_VERBS = { @@ -983,10 +981,6 @@ export const SESSION_LABELS = { export const NOTEBOOK_SYNC_CLI = "python3 scripts/sync-notebooklm-books.py"; export const WORKSPACE_ROOT_PLACEHOLDER = ""; -export function sessionRoute(affordance) { - return SESSION_ROUTES[asId(affordance)] || null; -} - // FR-025's two continuations and the ONLY two — spelled from the same tokens // `branch_session.CONTINUATIONS` declares, because the report the human is // answering names them literally. diff --git a/src/opendox/web/views/swb-create.js b/src/opendox/web/views/swb-create.js index 03a7a8f9..79c077af 100644 --- a/src/opendox/web/views/swb-create.js +++ b/src/opendox/web/views/swb-create.js @@ -29,10 +29,22 @@ import { el } from "./helpers.js"; import { panelEntry } from "./dispose.js"; import { - CONTINUATIONS, CREATE_ROUTE, consoleHeaders, createDocumentCommand, + CONTINUATIONS, consoleHeaders, createDocumentCommand, createRequest, withConsoleRepair, } from "./staging-workbench-model.js"; +// THE CREATE-DOCUMENT GATE ROUTE, DECLARED WHERE IT IS CALLED (§ 3.4 slice S4). +// It stood at `views/staging-workbench-model.js`:543 at the carve commit and +// this module imported it from there — a class-B file reaching into the pure +// model for a route only this file ever POSTs. RULED Q3 (openxFactory#656 +// comment `5642758731`, Brett Heap, 2026-09-12): "a route constant travels with +// the binding that calls it, never with the model that happens to declare it." +// Still a CONSTANT and never a literal in the transport, so the wire contract +// keeps the single definition the node harness and the Python route tests read +// — in the class-B module the gate column owns, which is where it can travel +// with the binding at slice S5. +export const CREATE_ROUTE = "/actions/gate/create-document"; + export function createGateLive(caps) { return !!(caps && caps.actions && caps.actions.gate); } diff --git a/src/opendox/web/views/swb-session.js b/src/opendox/web/views/swb-session.js index 8ad90d09..8754ab8f 100644 --- a/src/opendox/web/views/swb-session.js +++ b/src/opendox/web/views/swb-session.js @@ -73,10 +73,57 @@ import { SESSION_FIRST_EDIT, SESSION_REFRESH_NOTEBOOK, SESSION_SAVE, SESSION_SHARE, SESSION_VERBS, consoleHeaders, firstEditBody, firstEditVerdict, notebookRefreshCommand, - sessionActionsLive, sessionCommand, sessionRequest, sessionRoute, + sessionActionsLive, sessionCommand, sessionRequest, sessionSurfaceHidden, withConsoleRepair, } from "./staging-workbench-model.js"; +// ---- THE FIVE SESSION GATE ROUTES, DECLARED WHERE THEY ARE CALLED --------- +// +// § 3.4 slice S4. All five stood in `views/staging-workbench-model.js` at the +// carve commit — :817, :818, :821, :822, :826 — with the lookup table and +// `sessionRoute()` beside them, and every one of them is POSTed from this file +// and from nowhere else. RULED Q3 (openxFactory#656 comment `5642758731`, Brett +// Heap, 2026-09-12): "a route constant travels with the binding that calls it, +// never with the model that happens to declare it." +// +// THE REASON THEY WERE CONSTANTS IS UNCHANGED and is now served in the right +// place: constants here, never literals in the transport, so the wire contract +// has ONE definition the node harness and the Python route tests read — and it +// is a definition that can travel with the binding at slice S5 instead of being +// stranded in a pure model the gate column does not own. +export const EDIT_DOCUMENT_ROUTE = "/actions/gate/edit-document"; +export const OPEN_PR_ROUTE = "/actions/gate/open-pr"; +// 010-doxbench-editor-chat T080: the first-Save gate verb. A CANVAS seam, not +// a session-bar affordance -- deliberately absent from SESSION_AFFORDANCES. +export const FIRST_EDIT_ROUTE = "/actions/gate/first-edit"; +export const ABANDON_SESSION_ROUTE = "/actions/gate/abandon-session"; +// add-doxbench-editing-phase-b §12: the SHARE route, beside open-pr's because it +// is the same class of act (a remote write with the engineer's own credential) +// with the pull request removed. +export const SHARE_SESSION_ROUTE = "/actions/gate/share-session"; + +// The routes this module declares to the registry at slice S5, in one place so +// the binding entry and this file cannot drift apart. +export const SESSION_GATE_ROUTES = [ + EDIT_DOCUMENT_ROUTE, OPEN_PR_ROUTE, FIRST_EDIT_ROUTE, + ABANDON_SESSION_ROUTE, SHARE_SESSION_ROUTE, +]; + +const SESSION_ROUTES = { + [SESSION_EDIT]: EDIT_DOCUMENT_ROUTE, + [SESSION_SAVE]: OPEN_PR_ROUTE, + [SESSION_ABANDON]: ABANDON_SESSION_ROUTE, + [SESSION_SHARE]: SHARE_SESSION_ROUTE, + [SESSION_FIRST_EDIT]: FIRST_EDIT_ROUTE, +}; + +// The model's own `asId` is private to it and stayed there; this is the same +// one-line normalization, so an affordance arriving as null or a number reads +// as "no route" rather than as a key lookup on a coerced value. +export function sessionRoute(affordance) { + return SESSION_ROUTES[affordance == null ? "" : String(affordance)] || null; +} + // ---- the page-lifetime overlays -------------------------------------------- // // The roster the posture reads was fetched at BOOT, so it is stale in both diff --git a/src/opendox/web/views/view_extension.js b/src/opendox/web/views/view_extension.js index 592ba30f..bf903da9 100644 --- a/src/opendox/web/views/view_extension.js +++ b/src/opendox/web/views/view_extension.js @@ -60,9 +60,15 @@ export const VIEW_CLASSES = ["A", "B", "C", "?"]; // `index.html` and against the Python half, so the three never drift apart. // // `viewer-gatebar` is the viewer's own gate-bar host (`viewer.js` builds the -// div and calls `mountGate`). `wheel-intent` and `dispose-intent` are slice -// S2's, declared NOW so S2's optional intent-chip bindings fold in without -// re-opening this file: § 6 Q5 rules that "the chips become an OPTIONAL +// div and calls `mountGate`). `lens-gate` and `repo-projects` are slice S4's, +// added when the two new class-B bindings that mount into them arrived: +// `lens-gate` is the lens plan panel's execute box (`views/gate-lens.js`) and +// `repo-projects` is the selector's project-commission slot +// (`views/gate-projects.js`). Both are "shell" for the same reason +// `viewer-gatebar` is — the host is built by the view at mount time and handed +// over, so `index.html` has no element to declare. `wheel-intent` and +// `dispose-intent` are slice S2's, declared NOW so S2's optional intent-chip +// bindings fold in without re-opening this file: § 6 Q5 rules that "the chips become an OPTIONAL // contributed binding — absent, the wheel and the tray render without them", // and `optional: true` plus `lookupView()` is exactly that shape. Declaring a // region costs nothing; an undeclared one costs a slice. @@ -79,6 +85,8 @@ export const REGIONS = { "viewer-gatebar": "shell", "wheel-intent": "shell", "dispose-intent": "shell", + "lens-gate": "shell", + "repo-projects": "shell", }; export const MANIFEST_KIND = "opendox.view-manifest"; diff --git a/tests/fixtures/web_boundary_census.yaml b/tests/fixtures/web_boundary_census.yaml index 6f00a17d..7bed8591 100644 --- a/tests/fixtures/web_boundary_census.yaml +++ b/tests/fixtures/web_boundary_census.yaml @@ -28,7 +28,10 @@ # tail). Legitimate ONLY until slice S4 does the split -- after S4 a # "?" row still standing fails the census assertion, because a # permanent "undecided" is an escape hatch, not a boundary (note § 4.5 -# point 1). +# point 1). THAT CUTOFF IS NOW IN FORCE (slice S4 landed it): see +# `declared_transitional_rows` at the foot of this file, which is the +# ONE declared exception the note names and the only way a "?" (or a +# "SPLIT") row may still stand. # # `tail` (optional): set on a class-A row whose file ALSO carries a rendered # label or a corpus path (note § 2.2 rule 3) -- the identifier is named so S7 @@ -110,17 +113,84 @@ # 1,597 lines; C 14 files, 11,854 lines; ? 4 files, 5,432 lines -- B/C/? # all unchanged from the a99eba03 baseline +# § 3.4 SLICE S4 -- "SPLIT THE THREE RULED `SPLIT` FILES" (this fixture's own +# amendment; leg branch `build/s4-split-route-tails`). RULED Q3, openxFactory#656 +# comment `5642758731` (Brett Heap, 2026-09-12): "a route constant travels with +# the binding that calls it, never with the model that happens to declare it." +# THIRTEEN ROUTE TAILS MOVED, and with them three census rows: +# +# views/lens-model.js "?" -> A (1070 -> 1075 lines) +# LENS_SAVE_ROUTE :1036 and LENS_CLUSTER_ROUTE :1037 -> views/gate-lens.js +# (NEW, class B), with the execute affordance, the organizer-evidence form +# and the outcome panel that call them. The model is pure and import-free +# again and names no route any column declares. +# views/repo-selector.js "?" -> A (889 -> 814 lines) +# :33 /snapshot-index.json -> views/projection-index.js (NEW, class B), +# reached LATE and REFUSABLY by `fetchIndex` (note § 4.2's own guard, +# not a ViewBinding -- an index fetch mounts no panel) +# :34 /actions/refresh stays: BOTH legs declare a handler (§ 3.3) +# :38 /project-register.json stays: openDox's own (`serve_project.py`) +# :39 /actions/gate/create-project and :43 /actions/gate/edit-project +# -> views/gate-projects.js (NEW, class B), ONE binding with the +# create form and the membership-edit commission +# :46 /actions/apply-register-edits -> LEFT THE BUNDLE ENTIRELY with the +# "apply N pending" button that reached it. RULING DQ-1 keeps that +# lane at openxFactory and § 2.2 rule 1 says no class here can ever +# own it. +# views/staging-workbench-model.js "?" -> A (C tail) (1949 -> 1943 lines) +# :543 CREATE_ROUTE -> views/swb-create.js (already class B, already the +# only caller); :817/:818/:821/:822/:826 and the SESSION_ROUTES table +# and sessionRoute() -> views/swb-session.js (likewise). No new file: +# the two class-B modules that CALL them already existed. +# The `tail:` is new and is the note's own reading of this row (§ 3.2: +# "plus STATUS_BRAINSTORM / BRAINSTORM_AREA / STAGING_AREA (class-C)") -- +# so the file leaves "?" for A and its class-C substance enters assertion +# 4's scope for S7 rather than escaping the sweep unremarked. +# +# views/lens.js IS OUT OF SCOPE and stays "?" -- none of Q1-Q5 rules on its two +# openxFactory-lane routes (§ 5's S4 row says so in terms). It is assertion 1's +# ONE declared, ruled-later exception (`declared_transitional_rows` below) and +# its two lane sites are assertion 2's own (`route_ownership_exceptions`). Its +# S1 note said "splits at S4", which contradicted § 5's S4 row; corrected here. +# +# THE POST-S4 CENSUS, measured on the leg branch (44 -> 47 files, three of them +# created by this slice): +# A 25 files, 16,287 lines (22 + lens-model 1,075 + repo-selector 814 +# + staging-workbench-model 1,943, and app.js +# 1,282 -> 1,331, view_extension.js 455 -> 463) +# B 7 files, 2,174 lines (4 + gate-lens 204 + gate-projects 241 +# + projection-index 73, and swb-create +# 372 -> 384, swb-session 614 -> 661) +# C 14 files, 11,854 lines (unchanged -- S4 touched no class-C file) +# ? 1 file, 1,435 lines (views/lens.js alone, 1,524 -> 1,435) +# total 47 files, 31,750 lines +# Those numbers are DECLARED in `totals:` below and CHECKED, never transcribed: +# `loc` per row is held against the tree by assertion 1, and the class totals +# are re-derived from the rows by +# `test_the_declared_totals_are_re_derived_from_the_rows`. Slice S1's own header +# block above records what the same measurement said before this slice. + + schema_version: 1 kind: web-boundary-census source_note: "opensoft/openDox-spec docs/front-end-package-boundary.md @ a44ac06d" ruling_comment: "opensoft/openxFactory#656 comment 5642758731 (2026-09-12T02:07:53Z)" measured_at: "opensoft/openDox-code main a99eba03e31a0aee1cc15a061fdf718cc88a2c44" +# The per-class totals of the rows below, DECLARED so the census states its own +# shape and `test_the_declared_totals_are_re_derived_from_the_rows` can refuse a +# drift between the two. Measured at slice S4 (see the S4 block above). +totals: + A: {files: 25, loc: 16287} + B: {files: 7, loc: 2174} + C: {files: 14, loc: 11854} + "?": {files: 1, loc: 1435} + files: - path: app.js class: A - loc: 1282 - note: "the shell; imports 20 view modules; its only class-B import is gate.js at :43 (discharged by S3's view registry -- loc grew 1155 -> 1282 with the registry wiring, S3)" + loc: 1331 + note: "the shell; its only class-B import was gate.js at :43 (discharged by S3's view registry -- loc 1155 -> 1282 with the registry wiring, S3; 1282 -> 1331 with S4's two new gate bindings and the two mounts it hands down). Carries SIX transitional route-ownership sites, all in the CORE arm's class-B binding entries and all cleared at S5 when those entries leave for contributedViewBindings(): gate.bar's one route (S3) and gate.lens's and gate.projects's two each (S4). Declaring them is RULED Q3 working -- view_extension.py: 'a binding that declares the routes it calls is what makes that ruling checkable instead of aspirational' -- and it is a real breach by assertion 2's own rule only while the entry sits in app.js (class A) rather than in the class-B module (exempt by construction)" - path: index.html class: C @@ -230,6 +300,16 @@ files: loc: 538 note: "realization funnel; imports model.js's COLUMN_KEYS; 10 governance literals" + - path: views/gate-lens.js + class: B + loc: 204 + note: "S4 ADDITION (RULED Q3): the lens's two gate verbs. Declares LENS_SAVE_ROUTE and LENS_CLUSTER_ROUTE -- which stood at views/lens-model.js:1036/:1037 and were called from views/lens.js, never from the model -- together with the execute affordance, the human-seen organizer evidence form and the outcome panel that call them. Class B by \u00a7 2.1's own test: delete the gate column and it has nothing left to render. Reached by views/lens.js only as a shell-resolved mount (gate.lens), never an import" + + - path: views/gate-projects.js + class: B + loc: 241 + note: "S4 ADDITION (RULED Q3): the project commissions. Declares ACTIONS_CREATE_PROJECT_ROUTE and ACTIONS_EDIT_PROJECT_ROUTE -- views/repo-selector.js:39/:43 -- with the create-project form and the membership-edit commission that POST them. The PICKER did not travel (\u00a7 6 Q3: 'moving it whole puts the project picker -- the student's way to choose what they are working on -- behind the gate column'). Reached by views/repo-selector.js only as a shell-resolved mount (gate.projects), never an import" + - path: views/gate.js class: B loc: 184 @@ -252,14 +332,14 @@ files: note: "S2's optional contributed binding (RULED Q5); a single top-level-awaited dynamic import() of the RULED-absent intent-feed.js, never a static import -- no governance word, no owned route, no class-B import; added after this census's own measured head (a99eba03) by opensoft/openDox-code 330cf816, loc as amended in the leg PR (a comment reworded so the file does not misreport its own removed import to this suite's own assertion-3 regex)" - path: views/lens-model.js - class: "?" - loc: 1070 - note: "pure and import-free (class-A substance) but LENS_SAVE_ROUTE :1036 and LENS_CLUSTER_ROUTE :1037 are class-B tails; splits at S4 (Q3's rule extended)" + class: A + loc: 1075 + note: "SPLIT AT S4 (RULED Q3): LENS_SAVE_ROUTE :1036 and LENS_CLUSTER_ROUTE :1037 travelled to views/gate-lens.js, the class-B binding that calls them. What is left is what the note always called this file -- pure, import-free, zero governance literals, and now naming no route another column declares" - path: views/lens.js class: "?" - loc: 1524 - note: "VOCABULARIES :57 is a class-C vocabulary table; DTN_SEED_ROUTE :41 and STAGING_SEED_ROUTE :45 answered only by openxFactory's adapter; splits at S4" + loc: 1435 + note: "VOCABULARIES is a class-C vocabulary table; DTN_SEED_ROUTE and STAGING_SEED_ROUTE are answered ONLY by openxFactory's adapter (a THIRD column, note \u00a7 3.3). OUT OF SCOPE FOR S4 and still \"?\": none of Q1-Q5 rules on it (\u00a7 5's S4 row: 'lens.js is OUT OF SCOPE ... it stays \"?\" as assertion 1's one declared, ruled-later exception'). The S1 note read 'splits at S4', which contradicted that row; corrected by S4, which is the slice that would have had to do the splitting. Its two lane sites are assertion 2's own declared exception. loc 1524 -> 1435: the execute affordance, the organizer-evidence form and the outcome panel left for views/gate-lens.js with the two gate routes they called" - path: views/lineage.js class: C @@ -281,6 +361,11 @@ files: loc: 404 note: "staged-topic outline model; REQUIRED_SECTIONS/QUESTION_SUBFIELDS/TEMPLATE_ORDER" + - path: views/projection-index.js + class: B + loc: 73 + note: "S4 ADDITION: the openXdox PROJECTION column's one read. Declares SNAPSHOT_INDEX_ROUTE and fetchSnapshotIndex -- views/repo-selector.js:33, which openxdox/serve_projection.py:56 declares and contributes (\u00a7 3.3's ownership table). CLASS B WITH A CAVEAT STATED, not by silence: \u00a7 2.1 names class B 'the gate loop' and this is a GET of a projection, but what assertion 2 exempts is class B's LAST clause -- 'its BINDING belongs to openXdox-code through the seam \u00a7 4 describes' -- which is exactly true here and is what makes the old site a breach in the first place. The census has no fourth letter for the projection column, so this row takes the class whose exemption it actually earns. REGISTERED for the note's owner: \u00a7 2.1's class-B headline is narrower than the property \u00a7 4.5 assertion 2 exempts on. Reached by views/repo-selector.js through a LATE dynamic import (\u00a7 4.2's narrower guard, not a ViewBinding -- an index fetch mounts no panel and occupies no region)" + - path: views/repo-selector-model.js class: A loc: 537 @@ -288,9 +373,9 @@ files: note: "STATIONS :517-522 pairs each schema key with a rendered label; parameterized at S7" - path: views/repo-selector.js - class: "?" - loc: 889 - note: "Q3 RULING: SPLITS -- picker+refresh -> A, two gate commissions -> contributed binding (S4/S5), apply-register-edits leaves the bundle; stays \"?\" until S4 does the split" + class: A + loc: 814 + note: "SPLIT AT S4 (RULED Q3), exactly as the ruling states it: the picker and the refresh affordance are class A and stay; /snapshot-index.json :33 went to views/projection-index.js (reached late through a dynamic import, note \u00a7 4.2); /actions/gate/create-project :39 and /actions/gate/edit-project :43 went to views/gate-projects.js with the create form and the membership commission; /actions/apply-register-edits :46 LEFT THE BUNDLE with the apply button that reached it (RULING DQ-1 keeps that lane at openxFactory). What remains names /project-register.json (openDox's) and /actions/refresh (both legs declare a handler, \u00a7 3.3) and nothing else" - path: views/settings.js class: A @@ -298,9 +383,10 @@ files: note: "theme/localStorage preference store; pure frontend, no data path" - path: views/staging-workbench-model.js - class: "?" - loc: 1949 - note: "pure workbench scope derivation carrying SIX class-B route constants (:543,:817,:818,:821,:822,:826); splits at S4" + class: A + loc: 1943 + tail: STATUS_BRAINSTORM + note: "SPLIT AT S4 (RULED Q3): all six class-B route constants left for the two class-B files that already called them and imported them -- CREATE_ROUTE :543 to views/swb-create.js, and EDIT_DOCUMENT_ROUTE :817 / OPEN_PR_ROUTE :818 / FIRST_EDIT_ROUTE :821 / ABANDON_SESSION_ROUTE :822 / SHARE_SESSION_ROUTE :826, with the SESSION_ROUTES table and sessionRoute(), to views/swb-session.js. What is left is the pure scope derivation, the affordance ids, the verbs, the labels and the request builders. The `tail:` is the note's own reading of the row (\u00a7 3.2: 'plus STATUS_BRAINSTORM / BRAINSTORM_AREA / STAGING_AREA (class-C)'): class-A substance with a class-C vocabulary tail, parameterized at S7 like the other three tails rather than escaping assertion 4's sweep" - path: views/staging-workbench.js class: C @@ -309,8 +395,8 @@ files: - path: views/swb-create.js class: B - loc: 372 - note: "CREATE_ROUTE = /actions/gate/create-document (from staging-workbench-model.js:543)" + loc: 384 + note: "CREATE_ROUTE is DECLARED HERE since S4 (RULED Q3) -- it stood at staging-workbench-model.js:543 and this file was always its only caller" - path: views/swb-model-intake.js class: A @@ -319,12 +405,12 @@ files: - path: views/swb-session.js class: B - loc: 614 - note: "FIRST_EDIT_ROUTE/ABANDON_SESSION_ROUTE/SHARE_SESSION_ROUTE/OPEN_PR_ROUTE, all under the gate prefix" + loc: 661 + note: "EDIT_DOCUMENT_ROUTE/OPEN_PR_ROUTE/FIRST_EDIT_ROUTE/ABANDON_SESSION_ROUTE/SHARE_SESSION_ROUTE, all under the gate prefix and all DECLARED HERE since S4 (RULED Q3), with the SESSION_ROUTES table and sessionRoute() that read them; they stood at staging-workbench-model.js:817-:826 and this file was always their only caller" - path: views/view_extension.js class: A - loc: 455 + loc: 463 note: "S3 ADDITION: the client-side view registry -- ViewBinding/collectViewBindings, route_extension.py's shape mirrored in JS (openDox-spec § 4.1). No import, no governance literal; 'gate.bar' in a doc comment is a documentation example of an id, not a route literal, so assertion 2 does not match it. loc 422 -> 455 on this PR's own review round (Copilot, PR #14): a malformed contributed_routes now refuses instead of silently disabling the ownership check, and a rejected dynamic import now refuses naming the binding and module instead of leaking a raw error." - path: views/viewer.js @@ -342,6 +428,56 @@ files: loc: 1702 note: "THE WHEEL; imports dispose.js (class B) and intent-feed.js (absent, RULED openxFactory); SOURCE_ROUTE :97" +# ASSERTION 1's ONE DECLARED, RULED-LATER EXCEPTION (note § 4.5 point 1). After +# slice S4 the census assertion fails on any row still "?" OR still "SPLIT" -- +# "a permanent UNDECLARED 'undecided' is an escape hatch, not a boundary; a +# permanent DECLARED one, cited to the ruling gap that causes it, is how this +# census stays honest about what it does not yet know". This list is that +# declaration, and it is the ONLY way a transitional row may still stand. +# `until` names what would discharge it, so the exception cannot quietly +# outlive its cause. +declared_transitional_rows: + - path: views/lens.js + class: "?" + until: "a future ruling on views/lens.js's two openxFactory-lane routes" + reason: >- + none of Q1-Q5 rules on this file (openxFactory#656 comment 5642758731): + DTN_SEED_ROUTE and STAGING_SEED_ROUTE are answered ONLY by openxFactory's + own adapter, a THIRD column (note § 3.3), and RULING DQ-1 keeps that + column at openxFactory. It is out of scope for this ruling round, NOT + undecided by omission -- § 5's S4 row says so in terms ("lens.js is OUT OF + SCOPE ... it stays `?` as assertion 1's one declared, ruled-later + exception") -- and it stays "?" until a later ruling names its + destination. + +# ASSERTION 2's OWN STANDING, DECLARED EXCEPTION (note § 4.5 point 2, last +# paragraph): "lens.js's two openxFactory-lane sites are this assertion's own +# standing, declared exception -- the same idiom assertion 4 uses for its two +# schema-key exemptions: named here, with the reason beside it, EXCLUDED FROM +# THE IN-SCOPE GREP until a future ruling folds lens.js back in. This is why +# S5's and S6's xfail(strict=True) removal still leaves the test green: the +# marker comes off because every OTHER site it was tolerating is fixed, not +# because lens.js's two sites started passing the grep -- they never entered +# it." +# +# Keyed by (path, route) and NEVER by line number: a line number in a declared +# exception rots the first time anything above it moves, and this file's own +# S1 rows already carried five stale ones. Each route is checked to be really +# present in the file it exempts, so the exception cannot outlive the site. +route_ownership_exceptions: + - path: views/lens.js + routes: + - "/actions/dtn-seed" + - "/actions/staging-seed" + until: "a future ruling on views/lens.js's two openxFactory-lane routes" + reason: >- + the same ruling gap `declared_transitional_rows` names: none of Q1-Q5 + rules on views/lens.js, so its two openxFactory-lane sites do not clear on + any slice's schedule (note § 4.5 point 2's own table: "future ruling", + not S4/S5/S6). A THIRD undeclared "?" row or an unresolved SPLIT row + appearing later still fails immediately, the same ratchet assertion 1 + enforces. + # The two identifiers § 2.2 rule 3 declares EXEMPT from the governance-literal # sweep (assertion 4) -- carried here WITH THE REASON, per the note's own # instruction ("an exemption that is silence is how a literal survives a diff --git a/tests/test_web_boundary.py b/tests/test_web_boundary.py index b845aa3d..8bfe2551 100644 --- a/tests/test_web_boundary.py +++ b/tests/test_web_boundary.py @@ -51,6 +51,40 @@ dependency (`pyproject.toml`'s `[project] dependencies`), not a test-only addition made here. +AMENDED BY SLICE S4 -- "split the three RULED `SPLIT` files" (RULED Q3, same +comment; leg branch `build/s4-split-route-tails`). Four things changed here and +nothing else: + + 1. ASSERTION 1 GREW ITS POST-S4 CUTOFF, which is the half of note § 4.5 + point 1 that S1 could not yet enforce: "after S4 the assertion fails on any + row still `?` OR still `SPLIT` -- EXCEPT `views/lens.js`'s `?`, named + here". S4 is the slice that performs the split, so S4 is the slice that + owns the cutoff. The one exception is DECLARED DATA + (`declared_transitional_rows`), never a literal in this module, for the + note's own reason: "a permanent UNDECLARED 'undecided' is an escape hatch, + not a boundary; a permanent DECLARED one, cited to the ruling gap that + causes it, is how this census stays honest about what it does not yet + know." + 2. ASSERTION 2 GREW ITS OWN DECLARED EXCEPTION, likewise as data + (`route_ownership_exceptions`): `views/lens.js`'s two openxFactory-lane + sites are "excluded from the in-scope grep until a future ruling folds + lens.js back in ... they never entered it" (§ 4.5 point 2, last paragraph). + Every other site the assertion was tolerating stays in scope and stays + measured. + 3. THE THREE MARKERS GAINED `raises=AssertionError`. An `xfail(strict=True)` + with no `raises` tolerates ANY exception, so a `KeyError` from a malformed + fixture, or an `OSError` from a renamed file, would read as the expected + failure and keep the check green. These three markers stand for a MEASURED + defect -- an assertion that fails -- and now say so; anything else is a + broken test and fails as one. (Register nit 1 of the four S1 left; nit 2 is + the cutoff above. The other two -- the exemption test checking text + 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.) + 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. + 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. @@ -70,6 +104,14 @@ VALID_CLASSES = {"A", "B", "C", "?"} +# The classes note § 4.5 point 1 calls transitional and forbids after slice S4. +# "SPLIT" is named here as the note names it even though this fixture never +# spelled it (S1 collapsed both into `"?"`, whose own legend says so): a row +# that reintroduced it would already fail the `VALID_CLASSES` check above, and +# stating the rule over BOTH words keeps this module readable against the note +# rather than against one fixture's spelling choice. +TRANSITIONAL_CLASSES = {"?", "SPLIT"} + def _load_census() -> dict: with CENSUS_PATH.open(encoding="utf-8") as fh: @@ -79,6 +121,12 @@ def _load_census() -> dict: _CENSUS = _load_census() _ROWS: list[dict] = _CENSUS["files"] _EXEMPTIONS: list[dict] = _CENSUS["declared_exemptions"] +_TOTALS: dict[str, dict] = _CENSUS["totals"] +# Assertion 1's declared, ruled-later exceptions (note § 4.5 point 1) and +# assertion 2's own (point 2). Both are DATA, so adding one is a reviewed diff +# in the fixture beside the reason, never a literal buried in this module. +_TRANSITIONAL_EXCEPTIONS: list[dict] = _CENSUS["declared_transitional_rows"] +_ROUTE_EXCEPTIONS: list[dict] = _CENSUS["route_ownership_exceptions"] # Duplicates collapse silently here (a dict can only hold one value per key); # `test_every_web_file_is_classified_exactly_once` checks the RAW list # instead, so a duplicate row is still caught rather than swallowed by this @@ -92,9 +140,13 @@ def _real_web_files() -> set[str]: def _assertion_4_scope() -> list[dict]: """The 14 class-C files (13 in the note's own § 3.1 total, +1 for - `views/explorer.js` under Q2's ruling) plus the three declared class-A - tails (note § 2.2 rule 3): `views/docs.js`, `views/grouping.js`, - `views/repo-selector-model.js`.""" + `views/explorer.js` under Q2's ruling) plus the declared class-A tails + (note § 2.2 rule 3): `views/docs.js`, `views/grouping.js`, + `views/repo-selector-model.js` -- and, since slice S4, + `views/staging-workbench-model.js`, whose class-C substance + (`STATUS_BRAINSTORM` / `BRAINSTORM_AREA` / `STAGING_AREA`, § 3.2's own + reading of the row) is what is left once its six class-B route constants + travel. Four tails, 18 files in scope; all of it S7's.""" return [row for row in _ROWS if row["class"] == "C" or row.get("tail")] @@ -148,6 +200,75 @@ def test_every_web_file_is_classified_exactly_once() -> None: f"census `loc` drifted from the tree (path, declared, actual): {mismatched_loc}" ) + # THE POST-S4 CUTOFF (note § 4.5 point 1, and slice S4 is the slice that + # earns the right to enforce it): "`?` and `SPLIT` are classes the census + # may carry only until S4 ... after S4 the assertion fails on any row still + # `?` OR still `SPLIT` -- EXCEPT `views/lens.js`'s `?`, named here". The + # exception is read from the fixture, so the census declares its own one + # loose end and this module only enforces that there is nothing else. + declared_transitional = {e["path"] for e in _TRANSITIONAL_EXCEPTIONS} + still_transitional = sorted( + row["path"] for row in _ROWS + if row["class"] in TRANSITIONAL_CLASSES + and row["path"] not in declared_transitional + ) + assert not still_transitional, ( + f"{len(still_transitional)} row(s) still carry a TRANSITIONAL class " + f"after slice S4: {still_transitional}. § 4.5 point 1: `?` and `SPLIT` " + f"are classes the census may carry only until S4, and S4 is the slice " + f"that splits all three of them (§ 5) -- so a transitional row still " + f"standing fails exactly like an undeclared row would. A row that " + f"genuinely cannot be classified yet is DECLARED in the census's " + f"`declared_transitional_rows`, with the ruling gap that causes it and " + f"what would discharge it; a permanent UNDECLARED 'undecided' is an " + f"escape hatch, not a boundary." + ) + + +def test_the_declared_transitional_rows_are_real_and_still_transitional() -> None: + """Assertion 1's exception list cannot outlive its cause (note § 4.5 point + 1's own reasoning about a DECLARED exception, applied to the declaration). + + Unmarked and passing: bookkeeping on the fixture, not a measurement of the + boundary defect. + """ + for exception in _TRANSITIONAL_EXCEPTIONS: + path = exception["path"] + row = _ROWS_BY_PATH.get(path) + assert row is not None, ( + f"declared transitional exception names {path}, which carries no " + f"census row" + ) + assert row["class"] in TRANSITIONAL_CLASSES, ( + f"{path} is declared a transitional exception but its census row is " + f"class {row['class']!r} -- the exception is STALE, and a stale one " + f"is how the next `?` row slips through behind it" + ) + assert row["class"] == exception["class"], ( + f"{path}'s declared exception names class {exception['class']!r} and " + f"its row carries {row['class']!r}" + ) + assert exception.get("reason"), f"{path}'s transitional exception carries no reason" + assert exception.get("until"), ( + f"{path}'s transitional exception names nothing that would discharge " + f"it; an exception with no exit is a permanent one wearing a label" + ) + + +def test_the_declared_totals_are_re_derived_from_the_rows() -> None: + """The census states its own per-class shape and it must be the shape of + its rows -- so the header arithmetic every slice quotes cannot drift from + the data underneath it. Unmarked: arithmetic, not a defect measurement.""" + derived: dict[str, dict[str, int]] = {} + for row in _ROWS: + entry = derived.setdefault(row["class"], {"files": 0, "loc": 0}) + entry["files"] += 1 + entry["loc"] += row["loc"] + assert derived == _TOTALS, ( + f"the census's declared `totals:` disagree with its own rows.\n" + f"declared: {_TOTALS}\nderived: {derived}" + ) + # --------------------------------------------------------------------------- # Assertion 2 -- no file OUTSIDE class B names a route another column @@ -179,14 +300,36 @@ def _line_of(text: str, offset: int) -> int: return text.count("\n", 0, offset) + 1 +def _excepted_routes(path: str) -> set[str]: + """The routes DECLARED out of this file's in-scope grep (note § 4.5 point + 2's own standing exception, added at slice S4). Keyed by route and never by + line: "they never entered it", so the exclusion has to survive every edit + above the site.""" + excepted: set[str] = set() + for exception in _ROUTE_EXCEPTIONS: + if exception["path"] == path: + excepted.update(exception["routes"]) + return excepted + + def _route_ownership_violations() -> list[str]: violations = [] for row in _ROWS: if row["class"] == "B": continue # exempt by construction + excepted = _excepted_routes(row["path"]) text = (WEB_ROOT / row["path"]).read_text(encoding="utf-8") for owner, pattern in _OWNED_ROUTE_PATTERNS.items(): for m in pattern.finditer(text): + # The match carries its delimiters (`"/actions/dtn-seed"`), and + # the gate-prefix pattern matches a PREFIX rather than a whole + # route -- so the exception is tested against the matched text + # stripped of quotes, which is the whole route for every + # exception this census declares or can declare (a prefix-only + # exception would have to be spelled as the prefix). + literal = m.group(0).strip("\"'") + if literal in excepted: + continue site = f"{row['path']}:{_line_of(text, m.start())}" violations.append(f"{site} names {m.group(0)} ({owner})") return violations @@ -194,30 +337,39 @@ def _route_ownership_violations() -> list[str]: @pytest.mark.xfail( strict=True, + raises=AssertionError, reason=( "docs/front-end-package-boundary.md § 4.5 point 2 (opensoft/openDox-spec " - "#8 -> a44ac06d): 20 sites outside class B name a route another column " - "declares (was 18 before slice S3; S3 -- opensoft/openDox-code#14 -- " - "adds 2 and closes none) -- 12 the gate prefix (app.js:586/598 NEW: " - "the `gate.bar` CORE_VIEWS entry's `routes: [\"/actions/gate/ratify\"]`, " - "RULED Q3 'a route constant travels with the binding that calls it' -- " - "a real breach by this assertion's own rule while the entry sits in " - "app.js (class A) rather than views/gate.js (class B, exempt by " - "construction); TRANSITIONAL, closed at slice S5 when the binding " - "moves behind a host-supplied contribution and this entry leaves " - "app.js entirely; views/lens-model.js:1036/1037, " - "views/repo-selector.js:39/43, views/staging-workbench-model.js:543/" - "817/818/821/822/826), 3 openxFactory's adapter lanes " - "(views/lens.js:41/45, views/repo-selector.js:46, unchanged), 5 " - "openXdox's projection routes (app.js:195/196, shifted from :183/184 " - "by S3's own unrelated edits earlier in the file -- same two " - "`/source/` literals, untouched; views/repo-selector.js:33, " - "views/viewer.js:314, views/wheel.js:97). The note's § 4.5 closing " - "paragraph assigns closure to slices S5 and S6; its own per-site " - "table (point 2) instead reads S4 for 14 of the original 18 and S6 " - "for the remaining 4 -- the two do not fully agree, flagged here " - "rather than silently reconciled. Unmark only once verified green, " - "whichever slice(s) actually close it." + "#8 -> a44ac06d): 10 sites outside class B name a route another column " + "declares. THE ARITHMETIC, since every slice so far has moved it: 18 " + "at S1 -> 20 at S3 (which added app.js's `gate.bar` entry and closed " + "none) -> 12 measured after S4 -> 10 in scope, because S4 also gives " + "this assertion the DECLARED EXCEPTION the note's own last paragraph " + "states for views/lens.js:41/45. S4 CLEARED ALL TWELVE SPLIT-FILE " + "SITES the note's point-2 table assigns to it (views/lens-model.js:" + "1036/1037, views/repo-selector.js:33/39/43/46, " + "views/staging-workbench-model.js:543/817/818/821/822/826): every one " + "of those constants now sits in a class-B file, exempt by construction " + "-- which is RULED Q3 in force rather than described. WHAT IS LEFT, " + "and whose it is: 6 the gate prefix, ALL of them in app.js's CORE arm " + "-- :589/:601 the `gate.bar` entry (S3) and :624/:625/:630 the " + "`gate.lens` and `gate.projects` entries (S4) -- each a class-B " + "binding's `routes:` declaration, which view_extension.py calls the " + "thing that makes Q3 'checkable instead of aspirational', and each a " + "real breach by this assertion's own rule only while the entry sits " + "in app.js (class A) rather than in the class-B module it names. All " + "six are TRANSITIONAL and close together at slice S5, when the class-B " + "files move behind a host-supplied contribution and all three entries " + "leave app.js for contributedViewBindings(). Plus 4 openXdox's " + "projection routes -- app.js:195/196, views/viewer.js:314, " + "views/wheel.js:97, the `/source/` sites RULED Q4 re-homes at slice " + "S6. NOT IN SCOPE, by declaration rather than by silence: " + "views/lens.js's two openxFactory-lane sites " + "(`route_ownership_exceptions` in the census, with the ruling gap " + "beside them) -- none of Q1-Q5 rules on that file, so they clear on no " + "slice's schedule and 'they never entered it'. This marker therefore " + "comes off at S6, once BOTH remaining families are closed; unmark only " + "once verified green." ), ) def test_no_ownership_violation_outside_class_b() -> None: @@ -282,28 +434,29 @@ def _import_violations() -> list[str]: @pytest.mark.xfail( strict=True, + raises=AssertionError, reason=( "docs/front-end-package-boundary.md § 1.2(b) / § 4.5 point 3 " - "(opensoft/openDox-spec #8 -> a44ac06d): 6 sites today (was 7; slice " - "S3 -- opensoft/openDox-code#14 -- CLOSES app.js:43 -> views/gate.js, " - "the shell's one direct class-B import, now a registry lookup, " - "exactly the edge § 4.1 names) -- 2 " - "UNRESOLVED (views/dispose.js:26 and views/wheel.js:75-76 import " - "views/intent-feed.js, RULED not_moved and absent from this leg, " - "docs/opendox-carve-manifest.yaml:1807-1810 RULED OQ-F) and 4 " - "CLASS-BOUNDARY remaining (app.js:45 -> " - "views/swb-session.js, views/staging-workbench.js -> " - "views/swb-create.js and -> views/swb-session.js, " - "views/wheel.js:73-74 -> views/dispose.js -- all class A/C " - "importing class B). The note's closing paragraph assigns closure " - "to slice S2, which is the intent-feed edge only (the 2 unresolved " - "sites); the remaining 4 class-boundary sites are the same shape " - "S5's gate-loop contribution closes, per § 4.1/§ 5, not S2 -- S3 " - "closes the fifth (app.js:43) on its own account, ahead of S5, " - "because the view registry is exactly the seam that makes doing so " - "early possible. This assertion therefore stays red after S2 and S3 " - "alone -- flagged here rather than narrowed to fit the note's own " - "summary." + "(opensoft/openDox-spec #8 -> a44ac06d): 4 sites today, all " + "CLASS-BOUNDARY -- app.js -> views/swb-session.js, " + "views/staging-workbench.js -> views/swb-create.js and -> " + "views/swb-session.js, views/wheel.js -> views/dispose.js (all class " + "A/C importing class B). THE ARITHMETIC: 7 at S1 -> 6 once S3 " + "(opensoft/openDox-code#14) closed app.js:43 -> views/gate.js, the " + "shell's one direct class-B import, now a registry lookup and exactly " + "the edge § 4.1 names -> 4 once S2 (opensoft/openDox-code#15) closed " + "the two UNRESOLVED intent-feed imports its own optional binding " + "replaced (RULED Q5; the manifest row stands, RULED OQ-F). The count " + "was last restated on the S3 branch before that merge and read 6; " + "re-measured here rather than left stale, which is the only change " + "slice S4 makes to this marker besides `raises=`. S4 ADDS NONE: its " + "three new class-B modules are reached through the shell's resolved " + "mounts and one late dynamic import, never a static `from` clause, so " + "no class-A or class-C file gained a class-B import. The four that " + "remain are the gate loop's own, closed at S5 when its files move " + "behind a host-supplied contribution -- the note's closing paragraph " + "assigns this assertion to S2, which was the intent-feed edge only; " + "flagged here rather than narrowed to fit the note's summary." ), ) def test_every_relative_import_resolves_and_stays_in_class() -> None: @@ -469,12 +622,18 @@ def _governance_literal_violations() -> list[str]: @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 three declared class-A tails (views/docs.js, " - "views/grouping.js, views/repo-selector-model.js) carry the " + "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 " From 2e842178b2bceaee9a45441b7d70d797fe1205cf Mon Sep 17 00:00:00 2001 From: Brett Heap <1513478+brettheap@users.noreply.github.com> Date: Sat, 12 Sep 2026 13:32:06 -0400 Subject: [PATCH 11/44] =?UTF-8?q?=C2=A7=203.4=20S4:=20measure=20the=20thre?= =?UTF-8?q?e=20new=20bindings,=20and=20name=20the=20file=20on=20validate's?= =?UTF-8?q?=20list?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit `tests/test_web_boundary.py` alone cannot tell this slice apart from a slice that DELETED the thirteen route constants: its census assertion measures that no file outside class B names another column's route, which is equally true of a bundle whose gate verbs no longer work. `tests/test_split_route_tails.py` is the other half, in the same `--noconftest` shape as its five neighbours: * every one of the eleven moved constants declared in the class-B file that CALLS it, and the literal gone — not copied — from the file it left, with no surviving `export const` that a re-export shim could hide behind; * `/actions/refresh` measured to have STAYED class A (§ 3.3 puts it under openDox; a slice that swept every route out of the selector would pass every other assertion here); * `/actions/apply-register-edits` measured absent from EVERY file of the bundle, with the apply button's own class, because "leaves the bundle entirely" is a statement about all of it; * app.js's `gate.lens` / `gate.projects` entries and the modules they name declaring the SAME routes — the declaration is necessarily written twice, since app.js is class A and may not import a class-B module to read them, and this is what keeps the two copies honest through S5's move into contributedViewBindings(); * the ten moved gate routes present as a SET in some class-B module, beside the three that were already there — which is § 5's S4 precondition for S5 stated as an assertion; * no class-A/C file reaching the three new modules through a static import, measured on the three files this slice rewired (assertion 3 is xfail today and could not have reported a new breach); * and under node, against the REAL bundle files by absolute path rather than a copy: the lens gate posting the route its plan kind names (with the organizer evidence collected first for add-as-cluster), rendering the engine's refusal verbatim and re-arming; the project commissions posting both gate routes and carrying the project id, retiring the create form on a landed commission and restoring the control on a refused edit; the snapshot-index read degrading to null for a 404, a thrown fetch and never throwing; and the selector's own `fetchIndex` still reaching the route it no longer names, through the late import(), resolved once. Named on `validate`'s explicit list in the SAME commit, on slice S1's own precedent — a test file this leg does not name is a test file it does not run. Refs opensoft/openxFactory#656 Lane: openxfactory-4-opendox-extraction Co-Authored-By: Claude Fable 5.1 --- .github/workflows/validate.yml | 17 + tests/test_split_route_tails.py | 568 ++++++++++++++++++++++++++++++++ 2 files changed, 585 insertions(+) create mode 100644 tests/test_split_route_tails.py diff --git a/.github/workflows/validate.yml b/.github/workflows/validate.yml index 92c8e6cf..20d53f64 100644 --- a/.github/workflows/validate.yml +++ b/.github/workflows/validate.yml @@ -96,6 +96,22 @@ jobs: # Copilot re-review): the repository ships no other Node tooling, so # `type: module` is declared explicitly rather than left to Node's # default-on `--experimental-detect-module` heuristic. + # § 3.4 SLICE S4 adds `tests/test_split_route_tails.py`, on the same + # footing as its five neighbours. S4 splits the three RULED SPLIT files + # (RULED Q3, `#656` comment `5642758731`: "a route constant travels with + # the binding that calls it, never with the model that happens to declare + # it"), and `tests/test_web_boundary.py` alone cannot tell that slice + # apart from a slice that DELETED the thirteen route constants: its + # census assertion measures that no file outside class B names another + # column's route, which is equally true of a bundle whose gate verbs no + # longer work. This file measures the other half — each constant declared + # in the class-B file that CALLS it, the binding entries in `app.js` and + # the modules they name declaring the same routes, no class-A/C file + # reaching the three new modules through a static import, and the three + # modules actually performing their verbs. `--noconftest` safe and needs + # no consumer: it reads bundle files as text and drives the real ones + # under the `node` the runner already has (skipped, never failed, where + # node is absent), exactly as `tests/test_view_registry.py` does. - name: pytest run: >- python -m pytest -q @@ -105,4 +121,5 @@ jobs: tests/test_web_boundary.py tests/test_intent_binding_shape.py tests/test_view_registry.py + tests/test_split_route_tails.py --noconftest diff --git a/tests/test_split_route_tails.py b/tests/test_split_route_tails.py new file mode 100644 index 00000000..c5447c29 --- /dev/null +++ b/tests/test_split_route_tails.py @@ -0,0 +1,568 @@ +"""The thirteen route tails, where they landed and what they do there -- +slice S4. + +`docs/front-end-package-boundary.md` § 5's S4 row is the PRECONDITION for S5: +"Only 3 of the 13 gate-route constants are declared in class-B files +(`dispose.js`:28/:29, `gate.js`:120); the other 10 are declared in +`lens-model.js`, `repo-selector.js` and `staging-workbench-model.js`, and both +`swb-create.js` and `swb-session.js` IMPORT theirs from the last of those. The +gate loop cannot be contributed until its route table stops living outside +class B." RULED Q3 (opensoft/openxFactory#656 comment `5642758731`, Brett Heap, +2026-09-12) states the rule the move obeys: **"a route constant travels with +the binding that calls it, never with the model that happens to declare it."** + +WHAT THIS FILE MEASURES AND `tests/test_web_boundary.py` DOES NOT. The census +test asserts the BOUNDARY -- that no file outside class B names a route another +column declares -- and it would stay just as green if all thirteen constants +had been deleted outright and the three surfaces silently stopped working. This +file asserts the OTHER half: that each constant is declared in the class-B file +that calls it, that the binding entries in `app.js` and the modules they name +declare the SAME routes, that no class-A or class-C file reaches the new +modules through a static import, and -- under `node`, against the real bundle +files -- that the three new modules still DO what the code that moved out of +`lens.js` and `repo-selector.js` did. A move that passed the census and broke +the verb would be the worst possible outcome of this slice. + +`--noconftest` SAFE, like its five neighbours on `validate`'s explicit list: it +reads bundle files as text and drives the real ones under the `node` the runner +already has (skipped, never failed, where node is absent). It imports no +`opendox` submodule and needs no installed consumer. The bundle's own +`package.json` (`"type": "module"`, added by slice S3) is what makes `node` read +these `.js` files as the ES modules they are; the harnesses below import them +BY ABSOLUTE PATH out of the real `src/opendox/web/views/`, never a copy, so a +passing test is a statement about the shipped file and not about a fixture that +resembles it. + +A CREATED file: no carve-manifest row (RULED OQ-C), admitted by path in +openxFactory's `docs/opendox-carve-admissions.yaml`. +""" + +from __future__ import annotations + +import json +import re +import shutil +import subprocess +from pathlib import Path + +import pytest +import yaml + +ROOT = Path(__file__).resolve().parents[1] +WEB = ROOT / "src" / "opendox" / "web" +VIEWS = WEB / "views" +APP_JS = WEB / "app.js" +CENSUS_PATH = Path(__file__).resolve().parent / "fixtures" / "web_boundary_census.yaml" +NODE = shutil.which("node") + +# The three files § 3.2 RULED SPLIT, and the routes each one declared at the +# census tree. `where` is the file that declares it now -- always the one that +# CALLS it, which is the whole of Q3. +MOVED_TAILS = [ + # (constant, route, from, to) + ("LENS_SAVE_ROUTE", "/actions/gate/lens-save-recipe", + "lens-model.js", "gate-lens.js"), + ("LENS_CLUSTER_ROUTE", "/actions/gate/lens-add-as-cluster", + "lens-model.js", "gate-lens.js"), + ("SNAPSHOT_INDEX_ROUTE", "/snapshot-index.json", + "repo-selector.js", "projection-index.js"), + ("ACTIONS_CREATE_PROJECT_ROUTE", "/actions/gate/create-project", + "repo-selector.js", "gate-projects.js"), + ("ACTIONS_EDIT_PROJECT_ROUTE", "/actions/gate/edit-project", + "repo-selector.js", "gate-projects.js"), + ("CREATE_ROUTE", "/actions/gate/create-document", + "staging-workbench-model.js", "swb-create.js"), + ("EDIT_DOCUMENT_ROUTE", "/actions/gate/edit-document", + "staging-workbench-model.js", "swb-session.js"), + ("OPEN_PR_ROUTE", "/actions/gate/open-pr", + "staging-workbench-model.js", "swb-session.js"), + ("FIRST_EDIT_ROUTE", "/actions/gate/first-edit", + "staging-workbench-model.js", "swb-session.js"), + ("ABANDON_SESSION_ROUTE", "/actions/gate/abandon-session", + "staging-workbench-model.js", "swb-session.js"), + ("SHARE_SESSION_ROUTE", "/actions/gate/share-session", + "staging-workbench-model.js", "swb-session.js"), +] + +# The two tails that did NOT move to a class: one stays where it is because +# openDox itself answers it, and one leaves the bundle because no class here can +# ever own it (§ 2.2 rule 1: "openxFactory's adapter lanes -- the last of which +# no class can ever own, because RULING DQ-1 keeps that column at +# openxFactory"). +STAYS_CLASS_A = ("ACTIONS_REFRESH_ROUTE", "/actions/refresh", "repo-selector.js") +LEFT_THE_BUNDLE = ("ACTIONS_APPLY_REGISTER_EDITS_ROUTE", + "/actions/apply-register-edits", "repo-selector.js") + +SPLIT_FILES = ("lens-model.js", "repo-selector.js", "staging-workbench-model.js") +NEW_MODULES = ("gate-lens.js", "gate-projects.js", "projection-index.js") + + +def _read(name: str) -> str: + return (VIEWS / name).read_text(encoding="utf-8") + + +def _declares(source: str, constant: str, route: str) -> bool: + return f'export const {constant} = "{route}";' in source + + +# --------------------------------------------------------------------------- +# 1. the move itself: out of the model, into the caller +# --------------------------------------------------------------------------- + +@pytest.mark.parametrize("constant,route,origin,destination", MOVED_TAILS, + ids=[t[0] for t in MOVED_TAILS]) +def test_each_route_tail_is_declared_in_the_file_that_calls_it( + constant, route, origin, destination) -> None: + """RULED Q3, one row at a time. The constant is declared in its + destination and the route literal is gone from its origin.""" + assert _declares(_read(destination), constant, route), ( + f"{destination} does not declare {constant} = {route!r} -- RULED Q3 " + f"sends a route constant to the binding that calls it, and this one " + f"was called from there while {origin} merely declared it" + ) + assert f'"{route}"' not in _read(origin), ( + f"{origin} still carries the literal {route!r}: the tail did not move, " + f"it was copied" + ) + + +def test_the_three_split_files_declare_no_route_constant_that_left() -> None: + """The stronger statement the per-row test cannot make on its own: not one + of the eleven names survives as an `export const` in the file it left, so a + re-export shim cannot quietly keep the old import working and leave the + boundary exactly where it was.""" + for origin in SPLIT_FILES: + source = _read(origin) + lingering = sorted( + constant for constant, _route, o, _d in MOVED_TAILS + if o == origin and re.search(rf"\bexport const {constant}\b", source) + ) + assert not lingering, f"{origin} still exports {lingering}" + + +def test_the_refresh_route_stayed_class_a() -> None: + """§ 3.3's table lists `/actions/refresh` under openDox, and § 3.2's Q3 row + says "picker + refresh stay class A" -- so this one is measured to have NOT + moved. A slice that swept every route out of the selector would pass every + other assertion here.""" + constant, route, origin = STAYS_CLASS_A + assert _declares(_read(origin), constant, route) + + +def test_the_openxfactory_lane_left_the_bundle_entirely() -> None: + """RULED Q3 for `repo-selector.js`:46: "`/actions/apply-register-edits` is + openxFactory's lane and leaves the bundle entirely" -- not to a class, not + to an optional binding, OUT. Measured over the whole bundle, because + "leaves the bundle" is a statement about every file in it.""" + constant, route, _origin = LEFT_THE_BUNDLE + carriers = sorted( + p.relative_to(WEB).as_posix() for p in WEB.rglob("*") + if p.is_file() and p.suffix in (".js", ".html") + and f'"{route}"' in p.read_text(encoding="utf-8", errors="replace") + ) + assert not carriers, f"{route} still addressed by: {carriers}" + assert constant not in _read("repo-selector.js") + # and the control that reached it + assert "applybtn" not in _read("repo-selector.js") + + +# --------------------------------------------------------------------------- +# 2. the bindings: declared once, and the same in both places +# --------------------------------------------------------------------------- + +def _js_route_array(source: str, name: str) -> list[str]: + """The routes of `export const = [ ... ];`, which is how each + class-B module states what it owns. Members are the module's own route + CONSTANTS -- the whole point of the file is that the literal is written + once -- so each identifier is resolved back to the string it was declared + with, in the same file.""" + match = re.search(rf"export const {name} = \[(.*?)\];", source, re.S) + assert match, f"{name} not found" + literals = dict(re.findall(r'export const (\w+) = "([^"]+)";', source)) + routes = [] + for member in (m.strip() for m in match.group(1).split(",")): + if not member: + continue + if member.startswith('"'): + routes.append(member.strip('"')) + continue + assert member in literals, ( + f"{name} names {member!r}, which {name}'s own module does not " + f"declare as a route constant" + ) + routes.append(literals[member]) + return routes + + +def _app_binding(binding_id: str) -> dict: + """The CORE_VIEWS entry for one binding id, as `{field: value}` over the + fields this test reads. A regex and not a parser for the same reason + `tests/test_view_registry.py` uses one: there is no JS parser in this leg's + dependency set, and the note's own § 4.5 test is written to that + constraint.""" + source = APP_JS.read_text(encoding="utf-8") + match = re.search(rf'\{{ id: "{re.escape(binding_id)}", region: "([^"]+)",' + r'\s*\n\s*module: "([^"]+)", entry: "([^"]+)",?' + r'(?:\s*\n\s*view_class: "([^"]+)",)?' + r'(?:\s*view_class: "([^"]+)",)?' + r'(.*?)optional: (true|false)', + source, re.S) + assert match, f"no CORE_VIEWS entry for {binding_id!r} in app.js" + body = match.group(0) + routes = re.search(r"routes: \[(.*?)\]", body, re.S) + return { + "region": match.group(1), + "module": match.group(2), + "entry": match.group(3), + "view_class": match.group(4) or match.group(5), + "routes": re.findall(r'"([^"]+)"', routes.group(1)) if routes else [], + "optional": match.group(7) == "true", + } + + +@pytest.mark.parametrize("binding_id,module,entry,region,declared_in,constant", [ + ("gate.lens", "./views/gate-lens.js", "mountLensGate", "lens-gate", + "gate-lens.js", "LENS_GATE_ROUTES"), + ("gate.projects", "./views/gate-projects.js", "mountProjectCommissions", + "repo-projects", "gate-projects.js", "PROJECT_GATE_ROUTES"), +]) +def test_the_binding_entry_and_its_module_declare_the_same_routes( + binding_id, module, entry, region, declared_in, constant) -> None: + """`view_extension.py`: "a binding that declares the routes it calls is + what makes that ruling checkable instead of aspirational". The declaration + is necessarily written twice -- once in the manifest entry and once as the + constants the module POSTs -- because `app.js` is class A and may not + import a class-B module to read them. THIS is what keeps the two copies + honest, and it is what S5 will carry over when the entry moves from the + core arm into `contributedViewBindings()`.""" + binding = _app_binding(binding_id) + assert binding["module"] == module + assert binding["entry"] == entry + assert binding["region"] == region + assert binding["view_class"] == "B", ( + f"{binding_id} is not declared class B; class B is the ONLY class " + f"exempt from the route-ownership refusal, and a gate binding that " + f"declares itself anything else refuses its own assembly" + ) + assert binding["optional"] is True, ( + f"{binding_id} must be optional: a shell assembled without the gate " + f"column has to come up, which is RULING C2 one tier out" + ) + assert binding["routes"] == _js_route_array(_read(declared_in), constant), ( + f"{binding_id}'s declared routes and {declared_in}'s {constant} have " + f"drifted apart" + ) + + +def test_every_moved_gate_route_is_declared_by_some_class_b_module() -> None: + """The ten gate-prefix constants § 5's S4 row counts, checked as a SET: + each is declared in a class-B file, so the gate loop's route table no + longer lives outside class B and S5 can contribute it.""" + census = yaml.safe_load(CENSUS_PATH.read_text(encoding="utf-8")) + class_b = [row["path"] for row in census["files"] if row["class"] == "B"] + declared: set[str] = set() + for path in class_b: + for match in re.finditer(r'export const \w+ = "(/actions/gate/[^"]+)";', + (WEB / path).read_text(encoding="utf-8")): + declared.add(match.group(1)) + moved = {route for _c, route, _o, _d in MOVED_TAILS + if route.startswith("/actions/gate/")} + assert moved <= declared, f"not declared in any class-B file: {sorted(moved - declared)}" + # plus the three that were already there (§ 4.5 point 2: "the three gate + # constants declared in class-B files are NOT in the count") + assert {"/actions/gate/dispose-possible", "/actions/gate/propose", + "/actions/gate/ratify"} <= declared + + +@pytest.mark.parametrize("importer", ["app.js", "views/lens.js", + "views/repo-selector.js"]) +def test_no_class_a_or_c_file_statically_imports_a_new_class_b_module( + importer) -> None: + """§ 4.5 assertion 3 measures this over the census; measured HERE over the + three files this slice actually rewired, because a static import added by + S4 would be a NEW breach of the very rule S4 exists to serve, and the + census assertion is `xfail` today so it could not tell anyone.""" + source = (WEB / importer).read_text(encoding="utf-8") + specifiers = re.findall(r'^import\s[^;]*?from\s+"([^"]+)";', source, + re.M | re.S) + specifiers += re.findall(r'^\s*import\s+"([^"]+)";', source, re.M) + forbidden = sorted(s for s in specifiers + if s.rsplit("/", 1)[-1] in NEW_MODULES) + assert not forbidden, ( + f"{importer} statically imports {forbidden}: the new modules are " + f"reached through the shell's resolved mounts (gate.lens, " + f"gate.projects) or a late dynamic import (projection-index.js), " + f"never a `from` clause" + ) + + +def test_the_selector_reaches_the_projection_column_late() -> None: + """§ 4.2's own guard, in the shape S2 established: "an optional resolve in + place of the import-time `from`". A dynamic `import()`, and a `try` around + it, or an absent projection column is a module nothing can resolve rather + than a null.""" + source = _read("repo-selector.js") + assert 'await import("./projection-index.js")' in source + assert "PROJECTION_COLUMN = null" in source + + +def test_the_census_carries_the_three_new_modules_as_class_b() -> None: + census = yaml.safe_load(CENSUS_PATH.read_text(encoding="utf-8")) + rows = {row["path"]: row for row in census["files"]} + for name in NEW_MODULES: + row = rows.get(f"views/{name}") + assert row is not None, f"views/{name} carries no census row" + assert row["class"] == "B", f"views/{name} is class {row['class']!r}" + + +# --------------------------------------------------------------------------- +# 3. the three new modules, driven under node against the REAL bundle files +# --------------------------------------------------------------------------- + +# A minimal DOM: enough for `helpers.el` and the two mounts, and nothing more. +# Every node records its tag, class, text, attributes, wired listeners and +# children, so a harness can report the tree as JSON and fire a click. +_DOM_STUB = r""" +class Node { + constructor(tag) { + this.tag = tag; this.children = []; this.attrs = {}; this.listeners = {}; + this.className = ""; this._text = ""; this.type = ""; this.title = ""; + this.value = ""; this.checked = false; this.disabled = false; + this.hidden = false; this.focused = false; + } + get textContent() { return this._text; } + set textContent(v) { this._text = String(v); this.children = []; } + set innerHTML(v) { if (v !== "") throw new Error("innerHTML assigned " + v); this.children = []; this._text = ""; } + appendChild(c) { this.children.push(c); return c; } + setAttribute(k, v) { this.attrs[k] = String(v); } + addEventListener(t, fn) { (this.listeners[t] = this.listeners[t] || []).push(fn); } + focus() { this.focused = true; } + click() { for (const fn of this.listeners.click || []) fn({}); } +} +globalThis.document = { createElement: (tag) => new Node(tag) }; +function flatten(node, out = []) { + out.push(node); + for (const c of node.children) flatten(c, out); + return out; +} +function texts(node) { return flatten(node).map((n) => n.textContent).filter(Boolean); } +function buttons(node) { return flatten(node).filter((n) => n.tag === "button"); } +function inputs(node) { return flatten(node).filter((n) => n.tag === "input"); } +globalThis.flatten = flatten; globalThis.texts = texts; +globalThis.buttons = buttons; globalThis.inputs = inputs; +// The injected fetcher every transport in this bundle takes, recording what it +// was asked for. `body` comes back parsed so a harness asserts on the REQUEST. +function recorder(response) { + const calls = []; + return [calls, async (route, opts) => { + calls.push({ route, method: opts?.method || "GET", + body: opts?.body ? JSON.parse(opts.body) : null }); + return { ok: response.ok !== false, status: response.status || 200, + json: async () => response.payload }; + }]; +} +globalThis.recorder = recorder; +const settle = () => new Promise((r) => setTimeout(r, 0)); +globalThis.settle = settle; +""" + + +def _run_node(body: str, tmp_path: Path) -> dict: + """Run an ES-module harness against the REAL bundle and return the ONE JSON + object it prints. The modules are imported by absolute `file://` URL out of + `src/opendox/web/views/`, so what is measured is the shipped file.""" + source = ( + _DOM_STUB + + f'\nconst VIEWS = {json.dumps(VIEWS.resolve().as_uri() + "/")};\n' + + body + ) + script = tmp_path / "harness.mjs" + script.write_text(source, encoding="utf-8") + proc = subprocess.run([NODE, str(script)], capture_output=True, text=True, + timeout=120) + assert proc.returncode == 0, proc.stderr + return json.loads(proc.stdout.strip().splitlines()[-1]) + + +@pytest.mark.skipif(NODE is None, reason="node is not installed") +@pytest.mark.parametrize("kind,expected", [ + ("save-recipe", "/actions/gate/lens-save-recipe"), + ("add-as-cluster", "/actions/gate/lens-add-as-cluster"), +]) +def test_js_the_lens_gate_posts_the_route_its_plan_kind_names( + kind, expected, tmp_path) -> None: + """The verb still works after the move, and it posts the route the plan + kind names -- the behaviour that used to live in `views/lens.js`'s + `mountExecute`, now in the binding that owns both routes.""" + result = _run_node(f""" +const {{ mountLensGate }} = await import(VIEWS + "gate-lens.js"); +const [calls, fetcher] = recorder({{ payload: {{ ok: true, manifest: "m.yaml", + record: "r.yaml" }} }}); +const host = document.createElement("div"); +const plan = {{ kind: {json.dumps(kind)}, repository: "openxFactory", name: "lens set", + checked: ["a"], pinned: [], members: [], excluded: [] }}; +mountLensGate(host, {{ plan, caps: {{ actor: "brett" }}, fetcher }}); +buttons(host)[0].click(); +await settle(); +// add-as-cluster collects the organizer evidence first: fill it and submit. +if (calls.length === 0) {{ + const form = flatten(host).find((n) => n.className + && n.className.includes("evidence-form")); + for (const input of inputs(form)) input.value = "x"; + buttons(form).find((b) => b.textContent === "execute").click(); + await settle(); +}} +console.log(JSON.stringify({{ calls, texts: texts(host) }})); +""", tmp_path) + assert [c["route"] for c in result["calls"]] == [expected] + call = result["calls"][0] + assert call["method"] == "POST" + assert call["body"]["repository"] == "openxFactory" + if kind == "add-as-cluster": + assert call["body"]["evidence"]["proposer"] == "x" + else: + assert "evidence" not in call["body"] + assert any("landed" in t for t in result["texts"]) + + +@pytest.mark.skipif(NODE is None, reason="node is not installed") +def test_js_the_lens_gate_renders_the_engines_refusal_and_re_arms(tmp_path) -> None: + """"the engine refuses and the reason renders verbatim (single source of + truth)" -- and a refused plan stays retryable, which is what the disabled + flag coming back off means.""" + result = _run_node(""" +const { mountLensGate } = await import(VIEWS + "gate-lens.js"); +const [calls, fetcher] = recorder({ ok: false, status: 409, + payload: { ok: false, message: "recipe already recorded" } }); +const host = document.createElement("div"); +mountLensGate(host, { plan: { kind: "save-recipe", repository: "r", name: "n", + members: [], excluded: [] }, + caps: {}, fetcher }); +const run = buttons(host)[0]; +run.click(); +await settle(); +console.log(JSON.stringify({ calls, texts: texts(host), disabled: run.disabled })); +""", tmp_path) + assert len(result["calls"]) == 1 + assert "recipe already recorded" in result["texts"] + assert result["disabled"] is False + + +@pytest.mark.skipif(NODE is None, reason="node is not installed") +def test_js_the_project_commissions_post_both_gate_routes(tmp_path) -> None: + """One binding, two routes: the create form POSTs the create-project + commission and `commissionEdit` POSTs the membership one, carrying the + project id the selector holds. The controller's shape is the seam + `views/repo-selector.js` reaches through, so it is measured here rather + than assumed.""" + result = _run_node(""" +const { mountProjectCommissions } = await import(VIEWS + "gate-projects.js"); +const [calls, fetcher] = recorder({ payload: { ok: true, job: "J-1", + add: ["b"], remove: [] } }); +const host = document.createElement("div"); +const status = document.createElement("span"); +const pending = []; +const gate = mountProjectCommissions(host, { + roster: [{ kind: "repository", repository: "openxFactory" }, + { kind: "repository", repository: "openDox" }], + status, fetcher, addPendingOption: (name) => pending.push(name), +}); +// the create form: opened by the dropdown's "New Project..." line +const form = flatten(host).find((n) => n.className + && n.className.includes("projectform")); +const hiddenBeforeOpen = form.hidden; +gate.openCreateForm(); +inputs(form).find((i) => i.tag === "input" && i.type === "text").value = "Field Pilots"; +inputs(form).filter((i) => i.type === "checkbox")[0].checked = true; +buttons(form).find((b) => b.textContent === "commission project").click(); +await settle(); +// the membership edit: raised by the filter's add row / trash control +let restored = false; +await gate.commissionEdit("proj-1", { add: ["openDox"] }, + { restore: () => { restored = true; } }); +console.log(JSON.stringify({ calls, pending, hiddenBeforeOpen, + retired: form.hidden, restored, + status: status.textContent })); +""", tmp_path) + assert [c["route"] for c in result["calls"]] == [ + "/actions/gate/create-project", "/actions/gate/edit-project"] + create, edit = result["calls"] + assert create["body"] == {"name": "Field Pilots", + "repositories": ["openxFactory"]} + assert edit["body"] == {"project_id": "proj-1", "add": ["openDox"]} + assert result["hiddenBeforeOpen"] is True # the form is opened, never shown + assert result["retired"] is True # a landed commission retires it + assert result["restored"] is False # nothing to restore on success + assert "membership edit recorded (J-1)" == result["status"] + + +@pytest.mark.skipif(NODE is None, reason="node is not installed") +def test_js_a_refused_membership_edit_restores_the_control(tmp_path) -> None: + """The two-click trash re-arms and the add row's select restores its + placeholder -- `restore` is the selector's half of the act, and the + binding has to call it on a refusal or a control is left dead.""" + result = _run_node(""" +const { mountProjectCommissions } = await import(VIEWS + "gate-projects.js"); +const [calls, fetcher] = recorder({ ok: false, status: 403, + payload: { ok: false, message: "not a gate actor" } }); +const status = document.createElement("span"); +const gate = mountProjectCommissions(document.createElement("div"), + { roster: [], status, fetcher }); +let restored = false; +await gate.commissionEdit("proj-1", { remove: ["openDox"] }, + { restore: () => { restored = true; } }); +console.log(JSON.stringify({ calls, restored, status: status.textContent })); +""", tmp_path) + assert result["restored"] is True + assert "not a gate actor" in result["status"] + assert result["status"].startswith("edit-project refused: ") + + +@pytest.mark.skipif(NODE is None, reason="node is not installed") +def test_js_the_snapshot_index_read_degrades_to_null(tmp_path) -> None: + """The projection read's whole contract: "ANY failure resolves to null -- + the caller then renders exactly today's single-snapshot dashboard. Never + throws." Measured for a 404 (the static image), a thrown fetch (`file://`) + and the happy path.""" + result = _run_node(""" +const { SNAPSHOT_INDEX_ROUTE, fetchSnapshotIndex } = + await import(VIEWS + "projection-index.js"); +const routes = []; +const ok = await fetchSnapshotIndex(async (route) => { + routes.push(route); + return { ok: true, status: 200, json: async () => ({ entries: [1] }) }; +}); +const missing = await fetchSnapshotIndex(async () => ({ ok: false, status: 404 })); +const thrown = await fetchSnapshotIndex(async () => { throw new Error("file://"); }); +console.log(JSON.stringify({ route: SNAPSHOT_INDEX_ROUTE, routes, ok, + missing, thrown })); +""", tmp_path) + assert result["route"] == "/snapshot-index.json" + assert result["routes"] == ["/snapshot-index.json"] + assert result["ok"] == {"entries": [1]} + assert result["missing"] is None + assert result["thrown"] is None + + +@pytest.mark.skipif(NODE is None, reason="node is not installed") +def test_js_the_selectors_index_fetch_forwards_to_the_projection_column( + tmp_path) -> None: + """The selector's own `fetchIndex` still reaches the route it no longer + names -- through the late `import()` rather than a literal. Driven against + the real `views/repo-selector.js`, so the seam is measured end to end.""" + result = _run_node(""" +const { fetchIndex } = await import(VIEWS + "repo-selector.js"); +const routes = []; +const index = await fetchIndex(async (route) => { + routes.push(route); + return { ok: true, status: 200, json: async () => ({ entries: ["e"] }) }; +}); +// the column is resolved ONCE and remembered: a second call must not re-import +await fetchIndex(async (route) => { + routes.push(route); + return { ok: true, status: 200, json: async () => ({ entries: ["e"] }) }; +}); +console.log(JSON.stringify({ routes, index })); +""", tmp_path) + assert result["routes"] == ["/snapshot-index.json", "/snapshot-index.json"] + assert result["index"] == {"entries": ["e"]} From 8fdc6ac4e8f39c6ad8604689aba16e9aa8a1c808 Mon Sep 17 00:00:00 2001 From: Brett Heap <1513478+brettheap@users.noreply.github.com> Date: Sat, 12 Sep 2026 13:33:16 -0400 Subject: [PATCH 12/44] Read the DECLARED entry for S4's two mounts, as S3's own re-review already does MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit S3's Copilot re-review (opensoft/openDox-code#14, `e176947`) replaced `gateView.exports.mountGateBar(...)` with `gateView.exports[gateView.binding.entry](...)`: a contributed binding NAMES its entry in the manifest, and reading a hardcoded export name here would silently ignore the name it declared — the binding would resolve, the mount would be `undefined`, and the panel would fail at the click rather than at assembly. The same is true of S4's two mounts, so they read the declared entry too. Census `loc` for app.js refreshed with the change (1331 -> 1337) and the declared totals re-derived. Refs opensoft/openxFactory#656 Lane: openxfactory-4-opendox-extraction Co-Authored-By: Claude Fable 5.1 --- src/opendox/web/app.js | 10 ++++++++-- tests/fixtures/web_boundary_census.yaml | 12 ++++++------ 2 files changed, 14 insertions(+), 8 deletions(-) diff --git a/src/opendox/web/app.js b/src/opendox/web/app.js index 862e1e3d..99093996 100644 --- a/src/opendox/web/app.js +++ b/src/opendox/web/app.js @@ -1267,8 +1267,13 @@ async function render() { // Slice S4's two resolved class-B mounts, handed down already-bound so no // class-A or class-C view imports a class-B module to reach them. Null // where the column that supplies them is not installed. + // The DECLARED entry, never a hardcoded export name (S3's own Copilot + // re-review fix, applied to S4's two mounts for the same reason: a + // contributed binding names its entry in the manifest, and reading + // anything else here would silently ignore the name it declared). mountLensGate: lensGateView - ? (host, lctx) => lensGateView.exports.mountLensGate(host, lctx) + ? (host, lctx) => + lensGateView.exports[lensGateView.binding.entry](host, lctx) : null, // the UNSTRIPPED probe and the serve's own writable repository — read by // exactly one affordance (see `createCaps` at the lens's mount) @@ -1309,7 +1314,8 @@ async function render() { // registered — the selector then renders picker + refresh only, which is // the whole of what § 3.4 slice S4 leaves in class A mountProjectGate: projectGateView - ? (host, pctx) => projectGateView.exports.mountProjectCommissions(host, pctx) + ? (host, pctx) => + projectGateView.exports[projectGateView.binding.entry](host, pctx) : null, onSelect: (key) => { storeKey(key); render(); }, onRefreshed: () => render(), diff --git a/tests/fixtures/web_boundary_census.yaml b/tests/fixtures/web_boundary_census.yaml index 7bed8591..db04cc96 100644 --- a/tests/fixtures/web_boundary_census.yaml +++ b/tests/fixtures/web_boundary_census.yaml @@ -155,15 +155,15 @@ # # THE POST-S4 CENSUS, measured on the leg branch (44 -> 47 files, three of them # created by this slice): -# A 25 files, 16,287 lines (22 + lens-model 1,075 + repo-selector 814 +# A 25 files, 16,293 lines (22 + lens-model 1,075 + repo-selector 814 # + staging-workbench-model 1,943, and app.js -# 1,282 -> 1,331, view_extension.js 455 -> 463) +# 1,282 -> 1,337, view_extension.js 455 -> 463) # B 7 files, 2,174 lines (4 + gate-lens 204 + gate-projects 241 # + projection-index 73, and swb-create # 372 -> 384, swb-session 614 -> 661) # C 14 files, 11,854 lines (unchanged -- S4 touched no class-C file) # ? 1 file, 1,435 lines (views/lens.js alone, 1,524 -> 1,435) -# total 47 files, 31,750 lines +# total 47 files, 31,756 lines # Those numbers are DECLARED in `totals:` below and CHECKED, never transcribed: # `loc` per row is held against the tree by assertion 1, and the class totals # are re-derived from the rows by @@ -181,7 +181,7 @@ measured_at: "opensoft/openDox-code main a99eba03e31a0aee1cc15a061fdf718cc88a2c4 # shape and `test_the_declared_totals_are_re_derived_from_the_rows` can refuse a # drift between the two. Measured at slice S4 (see the S4 block above). totals: - A: {files: 25, loc: 16287} + A: {files: 25, loc: 16293} B: {files: 7, loc: 2174} C: {files: 14, loc: 11854} "?": {files: 1, loc: 1435} @@ -189,8 +189,8 @@ totals: files: - path: app.js class: A - loc: 1331 - note: "the shell; its only class-B import was gate.js at :43 (discharged by S3's view registry -- loc 1155 -> 1282 with the registry wiring, S3; 1282 -> 1331 with S4's two new gate bindings and the two mounts it hands down). Carries SIX transitional route-ownership sites, all in the CORE arm's class-B binding entries and all cleared at S5 when those entries leave for contributedViewBindings(): gate.bar's one route (S3) and gate.lens's and gate.projects's two each (S4). Declaring them is RULED Q3 working -- view_extension.py: 'a binding that declares the routes it calls is what makes that ruling checkable instead of aspirational' -- and it is a real breach by assertion 2's own rule only while the entry sits in app.js (class A) rather than in the class-B module (exempt by construction)" + loc: 1337 + note: "the shell; its only class-B import was gate.js at :43 (discharged by S3's view registry -- loc 1155 -> 1282 with the registry wiring, S3; 1282 -> 1337 with S4's two new gate bindings and the two mounts it hands down). Carries SIX transitional route-ownership sites, all in the CORE arm's class-B binding entries and all cleared at S5 when those entries leave for contributedViewBindings(): gate.bar's one route (S3) and gate.lens's and gate.projects's two each (S4). Declaring them is RULED Q3 working -- view_extension.py: 'a binding that declares the routes it calls is what makes that ruling checkable instead of aspirational' -- and it is a real breach by assertion 2's own rule only while the entry sits in app.js (class A) rather than in the class-B module (exempt by construction)" - path: index.html class: C From cb343ae83d1ff6686e3e452cc841016cae892fe4 Mon Sep 17 00:00:00 2001 From: Brett Heap <1513478+brettheap@users.noreply.github.com> Date: Sat, 12 Sep 2026 14:12:11 -0400 Subject: [PATCH 13/44] Copilot re-review (PR #16): refuse a malformed contributed-routes entry instead of coercing it MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Copilot found this on openDox-code #16, a thread on `view_extension.js:358` left for its owner (S3's view registry, `views/view_extension.js`): `contributedViewBindings`'s caller, `manifestRoutes()`, validated only that `contributed_routes` was an array, and `ownershipBreach()` read a contributed entry's `is_prefix` with a truthy check (`claimed.is_prefix && route.startsWith(pattern)`). Neither refused an ENTRY that was individually malformed — missing a string `pattern`, or carrying `is_prefix` as something other than a real boolean (including simply absent) — so a manifest like that rode through as if it were valid, and a truthy-but-wrong-type `is_prefix` (or a missing one, which is falsy) was silently read as "not a prefix" rather than refused. `view_extension.py`'s own note on "MALFORMED... REFUSES" is the rule this breaks: a payload this seam cannot reason about must fail closed, the same way `viewBinding()` already does for every OTHER shape defect in a contributed entry. THE FIX, both halves in `view_extension.js` alone: * a new `requireRouteShape(claimed)` — one shape check for a single contributed-route entry, shared by both callers so a malformed entry refuses at whichever of the two sees it first. * `manifestRoutes()` now runs it over every entry once the array check passes, instead of only checking the array's own type. * `ownershipBreach()` now calls it too, so `is_prefix` refuses when it is not a strict boolean, rather than falling through the old truthy check. PYTHON MIRROR PARITY. `view_extension.py`'s `_route_ownership_breach` reads `is_prefix` as `bool(getattr(contributed, "is_prefix", False))` — a coercion, not a refusal — but that is safe ONLY because its `contributed_routes` arrive as already-constructed `RouteBinding` objects, and `RouteBinding.__post_init__` (`route_extension.py`) has already refused a non-bool `is_prefix` at construction, before `_route_ownership_breach` ever runs. The JS mirror has no such upstream gate: its `contributed_routes` arrive as raw JSON off `/capabilities`, so this fix is deliberately stricter than the literal Python line it mirrors, matching what construction-time validation already guarantees on the Python side. TESTS (`tests/test_view_registry.py`), node-driven against the real file per its own `_run_node` pattern: extended `test_js_manifest_routes_refuses_a_malformed_contributed_routes_field` with an entry missing `pattern` and an entry with a non-boolean `is_prefix`, both inside an otherwise well-formed array; added `test_js_ownership_check_refuses_a_non_boolean_is_prefix_rather_than_coercing_it` covering a missing `is_prefix`, a non-boolean truthy one, and — so the fix does not over-refuse — a well-formed `true` (still breaches) and `false` (still resolves). Confirmed both fail against the pre-fix code and pass against the fix. `tests/fixtures/web_boundary_census.yaml`: `views/view_extension.js` grew 463 -> 499 lines; `loc` and the class-A `totals:` are re-derived and updated to match (`test_web_boundary.py`'s own drift check), with a note recording what changed and why. `app.js` is untouched — nothing here needed it. Refs opensoft/openxFactory#656 Lane: openxfactory-4-opendox-extraction Co-Authored-By: Claude Sonnet 5 --- src/opendox/web/views/view_extension.js | 50 +++++++++++++++++--- tests/fixtures/web_boundary_census.yaml | 6 +-- tests/test_view_registry.py | 61 +++++++++++++++++++++++++ 3 files changed, 107 insertions(+), 10 deletions(-) diff --git a/src/opendox/web/views/view_extension.js b/src/opendox/web/views/view_extension.js index bf903da9..189b89a1 100644 --- a/src/opendox/web/views/view_extension.js +++ b/src/opendox/web/views/view_extension.js @@ -210,17 +210,44 @@ export function viewBinding(spec) { // and a table beside them would be a second copy that drifts. The client reads // them out of the manifest (`contributed_routes`), which is the same list // `route_extension.collect_bindings` returned server-side. +// +// ONE SHAPE CHECK, used here AND where the manifest is first read +// (`manifestRoutes`, below), so a malformed entry refuses at whichever point +// sees it first rather than only once some binding's route happens to reach +// it — a binding with no routes, or routes that never collide with THIS +// entry, would otherwise let it ride through unexamined. Mirrors +// `view_extension.py`'s `_route_ownership_breach` on `pattern` ("carries no +// string pattern"); goes one further on `is_prefix`, which that function +// reads as `bool(getattr(contributed, "is_prefix", False))` — safe there only +// because `RouteBinding.__post_init__` already refused a non-bool `is_prefix` +// at CONSTRUCTION, before `_route_ownership_breach` ever runs. JSON off +// `/capabilities` has no constructor to have refused it first, so a +// non-boolean here (Copilot, PR #16, `view_extension.js:358`) must refuse +// rather than fall through a truthy check (`claimed.is_prefix && …`), which +// silently reads a missing or malformed field as "not a prefix" — the wrong +// answer for a payload nobody has vetted yet. +function requireRouteShape(claimed) { + const pattern = claimed && claimed.pattern; + if (typeof pattern !== "string") { + refuse("contributed route " + JSON.stringify(claimed) + " carries no " + + "string pattern, so no view binding can be checked against it"); + } + const isPrefix = claimed && claimed.is_prefix; + if (typeof isPrefix !== "boolean") { + refuse("contributed route " + JSON.stringify(claimed) + " declares " + + "is_prefix " + JSON.stringify(isPrefix) + ", not a boolean: a " + + "contributed route this seam cannot classify as exact-or-prefix must " + + "not be silently read as neither"); + } + return { pattern, isPrefix }; +} + function ownershipBreach(binding, contributedRoutes) { if (binding.view_class === "B") return null; for (const route of binding.routes) { for (const claimed of contributedRoutes) { - const pattern = claimed && claimed.pattern; - if (typeof pattern !== "string") { - refuse("contributed route " + JSON.stringify(claimed) + " carries no " - + "string pattern, so no view binding can be checked against it"); - } - if (route === pattern - || (claimed.is_prefix && route.startsWith(pattern))) { + const { pattern, isPrefix } = requireRouteShape(claimed); + if (route === pattern || (isPrefix && route.startsWith(pattern))) { return pattern; } } @@ -363,6 +390,15 @@ export function manifestRoutes(capabilities) { + "contributed_routes cannot be trusted for the ownership check that " + "field exists to carry."); } + // EVERY ENTRY, NOT JUST THE ARRAY ITSELF (Copilot, PR #16, + // `view_extension.js:358`): the array check alone let an entry missing + // `pattern` or `is_prefix` — or carrying either as the wrong type — ride + // through as "valid" contributed_routes, because `ownershipBreach()` only + // ever inspected an entry when some binding's route reached it. Validating + // every entry here, at the one place the whole manifest is read, means a + // malformed entry refuses whether or not any binding's routes would have + // exposed it. + routes.forEach(requireRouteShape); return routes; } diff --git a/tests/fixtures/web_boundary_census.yaml b/tests/fixtures/web_boundary_census.yaml index db04cc96..bfc49ea4 100644 --- a/tests/fixtures/web_boundary_census.yaml +++ b/tests/fixtures/web_boundary_census.yaml @@ -181,7 +181,7 @@ measured_at: "opensoft/openDox-code main a99eba03e31a0aee1cc15a061fdf718cc88a2c4 # shape and `test_the_declared_totals_are_re_derived_from_the_rows` can refuse a # drift between the two. Measured at slice S4 (see the S4 block above). totals: - A: {files: 25, loc: 16293} + A: {files: 25, loc: 16329} B: {files: 7, loc: 2174} C: {files: 14, loc: 11854} "?": {files: 1, loc: 1435} @@ -410,8 +410,8 @@ files: - path: views/view_extension.js class: A - loc: 463 - note: "S3 ADDITION: the client-side view registry -- ViewBinding/collectViewBindings, route_extension.py's shape mirrored in JS (openDox-spec § 4.1). No import, no governance literal; 'gate.bar' in a doc comment is a documentation example of an id, not a route literal, so assertion 2 does not match it. loc 422 -> 455 on this PR's own review round (Copilot, PR #14): a malformed contributed_routes now refuses instead of silently disabling the ownership check, and a rejected dynamic import now refuses naming the binding and module instead of leaking a raw error." + loc: 499 + note: "S3 ADDITION: the client-side view registry -- ViewBinding/collectViewBindings, route_extension.py's shape mirrored in JS (openDox-spec § 4.1). No import, no governance literal; 'gate.bar' in a doc comment is a documentation example of an id, not a route literal, so assertion 2 does not match it. loc 422 -> 455 on this PR's own review round (Copilot, PR #14): a malformed contributed_routes now refuses instead of silently disabling the ownership check, and a rejected dynamic import now refuses naming the binding and module instead of leaking a raw error. loc 463 -> 499 on this fix (Copilot, PR #16, view_extension.js:358): manifestRoutes() and ownershipBreach() now share one shape check, refusing a contributed-routes entry missing a string pattern or carrying a non-boolean is_prefix at whichever of the two sees it first, instead of the array-only check at manifestRoutes() and a truthy is_prefix read at ownershipBreach() silently letting a malformed entry through as if it were not a prefix match." - path: views/viewer.js class: A diff --git a/tests/test_view_registry.py b/tests/test_view_registry.py index 123a0b4e..fe53ca38 100644 --- a/tests/test_view_registry.py +++ b/tests/test_view_registry.py @@ -739,6 +739,15 @@ def test_js_manifest_routes_refuses_a_malformed_contributed_routes_field(tmp_pat # than refusing a payload this seam cannot reason about (Copilot, PR #14). # ABSENCE of the whole manifest still means an empty column, not a # refusal -- `contributedViewBindings`'s own rule, held here too. + # + # entryMissingPattern / entryNonBooleanIsPrefix are the FOLLOW-UP fix + # (Copilot, PR #16, `view_extension.js:358`): the array check alone let a + # well-formed ARRAY carrying one malformed ENTRY through unexamined, + # because nothing read that entry's `pattern` or `is_prefix` until some + # binding's route happened to reach it inside `ownershipBreach()`. + # `manifestRoutes()` now validates every entry's shape itself, at the one + # place the whole manifest is read, through the same `requireRouteShape()` + # helper `ownershipBreach()` uses. result = _run_node(f""" import {{ manifestRoutes }} from {json.dumps(REGISTRY_JS.as_uri())}; const out = {{}}; @@ -751,6 +760,8 @@ def test_js_manifest_routes_refuses_a_malformed_contributed_routes_field(tmp_pat ["string", "/actions/gate/"], ["object", {{ pattern: "/x" }}], ["missing", undefined], + ["entryMissingPattern", [{{ is_prefix: false }}]], + ["entryNonBooleanIsPrefix", [{{ pattern: "/x", is_prefix: "true" }}]], ]) {{ try {{ manifestRoutes({{ views: {{ contributed_routes: routes }} }}); @@ -766,6 +777,56 @@ def test_js_manifest_routes_refuses_a_malformed_contributed_routes_field(tmp_pat assert result["object"] == "ViewBindingError" assert result["missing"] == "ViewBindingError" assert "contributed_routes" in result["stringMessage"] + assert result["entryMissingPattern"] == "ViewBindingError" + assert "string pattern" in result["entryMissingPatternMessage"] + assert result["entryNonBooleanIsPrefix"] == "ViewBindingError" + assert "is_prefix" in result["entryNonBooleanIsPrefixMessage"] + + +@pytest.mark.skipif(NODE is None, reason="node is not installed") +def test_js_ownership_check_refuses_a_non_boolean_is_prefix_rather_than_coercing_it( + tmp_path): + # The other half of the same finding (Copilot, PR #16, + # `view_extension.js:358`): `ownershipBreach()` used to read `is_prefix` + # with a truthy check (`claimed.is_prefix && route.startsWith(pattern)`), + # so a MISSING or otherwise non-boolean `is_prefix` was read as "not a + # prefix" and a genuine ownership breach could ride through unexamined + # instead of the manifest refusing outright. `requireRouteShape()` now + # refuses any non-boolean `is_prefix` before the comparison ever runs -- + # and a well-formed boolean, true or false, still resolves exactly as + # before (the fix must not over-refuse a payload this seam CAN reason + # about). + result = _run_node(f""" +import {{ collectViewBindings }} from {json.dumps(REGISTRY_JS.as_uri())}; +const spec = {{ id: "docs.list", region: "view-docs", + module: "./views/docs.js", entry: "renderDocs", + view_class: "A", routes: ["/actions/gate/ratify"] }}; +const out = {{}}; +for (const [name, contributedRoutes] of [ + ["missingIsPrefix", [{{ pattern: "/actions/gate/" }}]], + ["stringIsPrefix", [{{ pattern: "/actions/gate/", is_prefix: "true" }}]], +]) {{ + try {{ + collectViewBindings([{{ views: () => [spec] }}], {{ contributedRoutes }}); + out[name] = "not refused"; + }} catch (e) {{ out[name] = e.name; out[name + "Message"] = e.message; }} +}} +try {{ + collectViewBindings([{{ views: () => [spec] }}], + {{ contributedRoutes: [{{ pattern: "/actions/gate/", is_prefix: true }}] }}); + out.trueIsPrefix = "not refused"; +}} catch (e) {{ out.trueIsPrefix = e.name; }} +out.falseIsPrefix = collectViewBindings([{{ views: () => [spec] }}], + {{ contributedRoutes: [ + {{ pattern: "/actions/gate/ratify-other", is_prefix: false }}] }}).length; +console.log(JSON.stringify(out)); +""", tmp_path) + assert result["missingIsPrefix"] == "ViewBindingError" + assert "is_prefix" in result["missingIsPrefixMessage"] + assert result["stringIsPrefix"] == "ViewBindingError" + assert "is_prefix" in result["stringIsPrefixMessage"] + assert result["trueIsPrefix"] == "ViewBindingError" + assert result["falseIsPrefix"] == 1 @pytest.mark.skipif(NODE is None, reason="node is not installed") From b9126d94123edd2035fab365d340408f633d90f9 Mon Sep 17 00:00:00 2001 From: Brett Heap <1513478+brettheap@users.noreply.github.com> Date: Sat, 12 Sep 2026 15:16:52 -0400 Subject: [PATCH 14/44] tests/test_web_boundary.py: validate route_ownership_exceptions is real (Copilot) Copilot review round on PR #17: assertion 2's declared exception list (route_ownership_exceptions) was consumed by _excepted_routes without any check that an entry names a real census row, carries a reason/until, or that its routes are still actually present in the file -- unlike declared_transitional_rows, which already has test_the_declared_transitional_rows_are_real_and_still_transitional. The fixture's own comment above route_ownership_exceptions already claimed "each route is checked to be really present in the file it exempts"; this was aspirational until now. Adds test_the_route_ownership_exceptions_are_real_and_still_present, on the same pattern as its assertion-1 sibling. Verified it catches a stale route (mutation test: renamed a declared route to a nonexistent literal, confirmed the new assertion fails, restored the fixture byte-identical). Narrowed validate: 181 passed, 3 xfailed (was 180/3). Lane: openxfactory-4-opendox-extraction Refs opensoft/openxFactory#656 Co-Authored-By: Claude Sonnet 5 --- tests/test_web_boundary.py | 38 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 38 insertions(+) diff --git a/tests/test_web_boundary.py b/tests/test_web_boundary.py index 8bfe2551..83288dc3 100644 --- a/tests/test_web_boundary.py +++ b/tests/test_web_boundary.py @@ -377,6 +377,44 @@ def test_no_ownership_violation_outside_class_b() -> None: assert not violations, f"{len(violations)} route-ownership violation(s):\n" + "\n".join(violations) +def test_the_route_ownership_exceptions_are_real_and_still_present() -> None: + """Assertion 2's exception list cannot outlive its cause, on the same + reasoning `declared_transitional_rows` already stands on (note § 4.5 + point 2's own last paragraph, applied to the declaration this time + instead of to the class-A/C sweep): a stale exception that keeps + excluding a route nobody re-measures is how a real breach hides behind a + label the site no longer earns. This module's own comment above + `route_ownership_exceptions` in the fixture says "each route is checked + to be really present in the file it exempts" -- this test is that check, + not just the claim of it. + + Unmarked and passing: bookkeeping on the fixture, not a measurement of + the boundary defect. + """ + for exception in _ROUTE_EXCEPTIONS: + path = exception["path"] + row = _ROWS_BY_PATH.get(path) + assert row is not None, ( + f"route_ownership_exceptions names {path}, which carries no census row" + ) + assert exception.get("reason"), f"{path}'s route exception carries no reason" + assert exception.get("until"), ( + f"{path}'s route exception names nothing that would discharge it; " + f"an exception with no exit is a permanent one wearing a label" + ) + routes = exception.get("routes") + assert routes, f"{path}'s route exception declares no routes at all" + text = (WEB_ROOT / path).read_text(encoding="utf-8") + for route in routes: + quoted = (f'"{route}"' in text) or (f"'{route}'" in text) + assert quoted, ( + f"{path}'s route exception names {route!r}, which is not actually " + f"present in the file as a string literal any more -- the " + f"exception has outlived its site and is now excluding nothing, " + f"or excluding the wrong thing" + ) + + # --------------------------------------------------------------------------- # Assertion 3 -- every relative import resolves, and no class-A/C file # imports a class-B module (note § 4.5 point 3). Catches § 1.2(b) -- the From a061b505548cccbc809216ddb4c52e0f7b4684f6 Mon Sep 17 00:00:00 2001 From: Brett Heap Date: Sat, 12 Sep 2026 15:49:27 -0400 Subject: [PATCH 15/44] =?UTF-8?q?=C2=A7=203.4=20S5,=20leg=20B:=20the=20she?= =?UTF-8?q?ll=20loses=20the=20gate=20loop=20and=20reaches=20it=20through?= =?UTF-8?q?=20the=20registry?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The openDox half of slice S5 (openDox-spec `docs/front-end-package-boundary.md` § 5 row S5 @ `7d12428c`). The contract is openXdox-spec `docs/gate-loop-view-contract.md` @ `d73767b7`, § 8 Q1-Q12 RULED by Brett Heap 2026-09-12 at opensoft/openxFactory#656 comments `5648044785`, `5648049748`, `5648065587`. Paired with openXdox-code#18, which supplies what this removes. WHAT LEFT: `views/gate.js`, `views/dispose.js`, `views/swb-create.js`, `views/swb-session.js`, `views/gate-lens.js`, `views/gate-projects.js` — six and not four, because S4 split four of the thirteen gate constants into two NEW class-B modules and `gate-lens.js`'s own header says "AT S5 THIS FILE LEAVES THE BUNDLE". With them go the three CORE-arm bindings and every gate route literal in the shell. WHAT EACH RULING PUT WHERE * Q1 `views/view_extension.js` `mountContributedViews()` — one mount pass over every contributed binding whose region is a `dom` region; `shell` regions stay caller-driven, which is why this column's own six are untouched by it. * Q2 `exports` on `ViewBinding` in BOTH halves, validated the way `entry` is, and `resolveView` now hands back a namespace BOUNDED by the declaration — a reach for an undeclared name refuses, naming both. * Q3 every contributed mount is `mount(host, snapshot, ctx)`; app.js's three adapters and staging-workbench.js's four call sites carry the new shape. * Q4 `unmetRequirement` / `requirementRefusal` / `probeCapabilityPath` — dotted paths into `/capabilities`, evaluated at every named resolve and in the mount pass; unmet + optional is an empty region with a NAMED reason, unmet + required refuses. * Q8 `page-overlay`, a shell region app.js builds (index.html is a `moved_verbatim` carve row and cannot grow an element), plus `workbench-create` / `workbench-session` for the workbench's two caller-built hosts — added with the bindings that mount into them, on slice S4's own precedent. * Q10 app.js:57's `firstEditTransport` import is GONE: reached off the `gate.workbench.session` binding, with `refusalTransport()` — a refusal in the shape `runSave` understands — when no column is registered. * Q11 `render()` catches `ViewBindingError` separately; a registry refusal is no longer framed as a snapshot defect. * Q12 no gate route literal survives anywhere in this bundle. ASSERTION 3 IS GREEN AND ITS MARKER IS OFF: 7 at S1 -> 6 at S3 -> 4 at S2 -> 0 here. All four were the gate loop's own, and each closed by the module LEAVING — `views/wheel.js` and `views/staging-workbench.js` read the declared namespaces the shell resolved, through null columns that make every affordance unoffered where openXdox is not registered. ASSERTION 2 is 10 -> 4: the six CORE-arm gate sites cleared, the four `/source/` sites are slice S6's on its own branch, so that marker stays. Lane: openxfactory-4-opendox-extraction Refs opensoft/openxFactory#656 Co-Authored-By: Claude Opus 5 --- src/opendox/view_extension.py | 75 +++ src/opendox/web/app.js | 249 ++++++-- src/opendox/web/views/dispose.js | 427 ------------- src/opendox/web/views/gate-lens.js | 204 ------- src/opendox/web/views/gate-projects.js | 241 -------- src/opendox/web/views/gate.js | 184 ------ src/opendox/web/views/staging-workbench.js | 111 +++- src/opendox/web/views/swb-create.js | 384 ------------ src/opendox/web/views/swb-session.js | 661 --------------------- src/opendox/web/views/view_extension.js | 262 +++++++- src/opendox/web/views/wheel.js | 73 ++- tests/fixtures/web_boundary_census.yaml | 45 +- tests/test_intent_binding_shape.py | 49 +- tests/test_split_route_tails.py | 345 +++++------ tests/test_view_registry.py | 63 +- tests/test_web_boundary.py | 106 ++-- 16 files changed, 956 insertions(+), 2523 deletions(-) delete mode 100644 src/opendox/web/views/dispose.js delete mode 100644 src/opendox/web/views/gate-lens.js delete mode 100644 src/opendox/web/views/gate-projects.js delete mode 100644 src/opendox/web/views/gate.js delete mode 100644 src/opendox/web/views/swb-create.js delete mode 100644 src/opendox/web/views/swb-session.js diff --git a/src/opendox/view_extension.py b/src/opendox/view_extension.py index 72d515fe..dbaf06ec 100644 --- a/src/opendox/view_extension.py +++ b/src/opendox/view_extension.py @@ -180,7 +180,34 @@ "dispose-intent": "shell", "lens-gate": "shell", "repo-projects": "shell", + "page-overlay": "shell", + "workbench-create": "shell", + "workbench-session": "shell", } +#: THE THREE REGIONS SLICE S5 ADDS, and why each is a `shell` one. +#: +#: `page-overlay` is RULED Q8 (openxFactory#656 comment `5648049748`, Brett +#: Heap, 2026-09-12): "a fourth `shell` region, `page-overlay`, is the declared +#: host for page-level panels (dispose.js's refusal panel); `document.body` is +#: never a contract surface." The gate column's refusal panel appended a +#: singleton `aside.refusalpanel` straight to the body — a mount point no region +#: declared, which is "exactly the silence the REGIONS table exists to end, and +#: a contributed column appending to the body is a collision nothing can +#: refuse". The SHELL builds this host and hands it over, which is what makes it +#: `shell` rather than an `index.html` element: `index.html` is a +#: `moved_verbatim` row of openxFactory's carve manifest and an added element is +#: in none of its declared edit classes, so the host is built by `app.js` — and +#: the region's kind says so honestly rather than declaring a `dom` region whose +#: element the shell creates at run time. +#: +#: `workbench-create` and `workbench-session` are the staging workbench's two +#: caller-built hosts — the create affordance's slot and the session bar's row, +#: both built by `views/staging-workbench.js` at mount time and handed over, +#: exactly as `views/viewer.js` builds `div.viewer-gate` for `viewer-gatebar`. +#: They are added HERE, with the bindings that mount into them, on slice S4's +#: own precedent (`lens-gate` and `repo-projects` arrived the same way one slice +#: 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 facet name a host's profile carries, beside `ROUTE_EXTENSIONS` and #: `SUBCOMMAND_EXTENSIONS` — ONE composite profile, one registration, three @@ -252,6 +279,26 @@ class ViewBinding: #: binding's own author knows, and the alternative is grepping a module this #: process may not even be able to read. routes: tuple[str, ...] = () + #: EVERY EXPORT THE SHELL MAY REACH — RULED Q2 (openxFactory#656 comment + #: `5648049748`, Brett Heap, 2026-09-12): "a binding's contract is its + #: module NAMESPACE, DECLARED as an `exports` tuple: every export the shell + #: may reach is listed on the binding and validated the way `entry` is; an + #: undeclared reach (today `isGateBearing`, app.js:939) is a refusal." + #: + #: WHY A TUPLE AND NOT THE NAMESPACE ITSELF. `resolveView` hands back the + #: whole module namespace, and the shell read `gateView.exports.isGateBearing` + #: — an export the binding never declared and this seam never validated. A + #: contributed column could therefore withdraw an export the shell depends + #: on and learn about it from a `TypeError` in a click handler. Declared, + #: it is refused where every other declaration defect is refused. + #: + #: EMPTY MEANS `entry` ALONE, which is the pre-Q2 contract and is what every + #: core-arm binding still declares: the core arm's modules are imported + #: statically by the shell that owns them, so there is no namespace crossing + #: a process boundary to declare. A NON-EMPTY tuple must CONTAIN `entry` — + #: the mount is the first member of the namespace the shell may reach, and a + #: tuple that omitted it would be declaring a contract its own entry breaks. + exports: tuple[str, ...] = () #: Capability keys (`/capabilities`' `actions`) or profile facets the #: binding needs. Consulted by the CLIENT at mount; carried here because the #: manifest is what the client reads. @@ -315,6 +362,33 @@ def __post_init__(self) -> None: f"view binding {self.id!r} declares class {self.view_class!r}, " f"not one of {list(VIEW_CLASSES)} (§ 2.1: A openDox core, " "B the gate loop, C a stage-named region)") + if not isinstance(self.exports, tuple): + raise ViewBindingError( + f"view binding {self.id!r} declares exports {self.exports!r}, " + "which is not a tuple — a binding's declared namespace is " + "frozen with it") + for name in self.exports: + # HELD TO `entry`'s OWN GRAMMAR, which is RULED Q2 in one line: + # "validated the way `entry` is". Same pattern, same dunder guard, + # same reason — the names cross a process boundary as JSON and are + # then used to index a module namespace. + if not isinstance(name, str) or not _ENTRY.match(name): + raise ViewBindingError( + f"view binding {self.id!r} declares export {name!r}: an " + "export is the NAME of an export on the binding's module, " + "held to the same JS-compatible identifier grammar `entry` " + "is (RULED Q2, openxFactory#656 comment 5648049748)") + if name.startswith("__"): + raise ViewBindingError( + f"view binding {self.id!r} declares export {name!r}: a " + "dunder reaches the object protocol rather than the " + "module's own surface") + if self.exports and self.entry not in self.exports: + raise ViewBindingError( + f"view binding {self.id!r} declares exports {list(self.exports)} " + f"that do not include its own entry {self.entry!r}: RULED Q2 " + "makes the tuple the WHOLE namespace the shell may reach, and " + "the mount is the first member of it") if not isinstance(self.routes, tuple): raise ViewBindingError( f"view binding {self.id!r} declares routes {self.routes!r}, " @@ -358,6 +432,7 @@ def as_manifest_entry(self) -> dict[str, Any]: "module": self.module, "entry": self.entry, "view_class": self.view_class, + "exports": list(self.exports), "routes": list(self.routes), "requires": list(self.requires), "optional": self.optional, diff --git a/src/opendox/web/app.js b/src/opendox/web/app.js index 99093996..4c8f3f80 100644 --- a/src/opendox/web/app.js +++ b/src/opendox/web/app.js @@ -51,10 +51,20 @@ import { renderLens } from "./views/lens.js"; // loop behind a binding openXdox supplies, the binding leaves the core arm and // nothing else in this file changes. import { - collectViewBindings, contributedViewBindings, manifestRoutes, resolveView, + ViewBindingError, collectViewBindings, contributedViewBindings, + manifestRoutes, mountContributedViews, resolveView, } from "./views/view_extension.js"; import { mountStagingWorkbench } from "./views/staging-workbench.js"; -import { firstEditTransport } from "./views/swb-session.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` — +// the shell's LAST static import of a class-B module, and the one § 4.5 +// assertion 3 still measured after S3 closed line 43. RULED Q10 (openxFactory +// #656 comment `5648065587`, Brett Heap, 2026-09-12): "app.js:57's +// `firstEditTransport` travels as a DECLARED NON-MOUNT EXPORT of the workbench +// binding (Q2's `exports` tuple), reached through the registry, with a +// refusal-shaped fallback when the binding is absent — never a blank." It is +// resolved in `render()` below, off the `gate.workbench.session` binding, and +// `refusalTransport` is the fallback. import { createModelIntakeTransports } from "./views/swb-model-intake.js"; import { CONSOLE_TOKEN_FIELD } from "./views/staging-workbench-model.js"; import { runSave, savePlanState } from "./views/doxbench-save.js"; @@ -521,6 +531,11 @@ const CORE_VIEWS = [ mount: (root, snap, ctx) => renderWheel(root, snap, { caps: ctx.caps, nav: ctx.nav, notebook: ctx.notebook, sourceBase: ctx.sourceBase, composed: ctx.composed, + // 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 + // reads them off this namespace now, null where no column supplies it. + dispose: ctx.dispose, signal: ctx.signal }) }, { id: "board.pipeline", control: "tab-board", region: "view-board", module: "./views/board.js", entry: "renderBoard", view_class: "C", @@ -575,60 +590,31 @@ const CORE_VIEWS = [ { id: "lineage.readiness", control: "tab-lineage", region: "view-lineage", module: "./views/lineage.js", entry: "renderLineage", view_class: "C", mount: (root, snap) => renderLineage(root, snap) }, - // THE GATE BAR — class B, OPTIONAL, and the proof this slice exists to give. - // `app.js`'s line 43 used to import `isGateBearing` and `mountGateBar` - // straight out of `views/gate.js`; § 4.1 names that import as the one the - // registry replaces, so it is a binding now, resolved rather than imported. - // Three properties follow, and each is a thing that was not true before: + // 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. // - // * `optional: true` — a shell assembled WITHOUT it renders the viewer with - // no gate bar instead of failing to load. `views/viewer.js` already - // tolerates a null `mountGate` (`const mountGate = o.mountGate || null`), - // so nothing there changes: the absence was always representable - // downstream and was simply unreachable from here. - // * `routes: ["/actions/gate/ratify"]` — RULED Q3's "a route constant - // travels with the binding that calls it". `gate.js`:120's - // `GATE_RATIFY_ROUTE` is the gate loop's, and it now says so in the one - // place the registry can check. - // * it is in the CORE arm and that is TRANSITIONAL. `gate.js` is still a - // file of this bundle; slice S5 moves the four class-B files behind a - // binding openXdox supplies, at which point this entry is deleted and the - // identical binding arrives through `contributedViewBindings()`. Nothing - // else in this file changes when it does — which is the test of whether - // the seam was drawn in the right place. - { id: "gate.bar", region: "viewer-gatebar", - module: "./views/gate.js", entry: "mountGateBar", view_class: "B", - routes: ["/actions/gate/ratify"], requires: ["actions.gate"], - optional: true }, - // THE LENS'S TWO GATE VERBS and THE PROJECT COMMISSIONS — slice S4's two new - // class-B bindings, on exactly the footing `gate.bar` above already stands on - // and for the same three reasons. RULED Q3 (openxFactory#656 comment - // `5642758731`): "a route constant travels with the binding that calls it, - // never with the model that happens to declare it" — so the ten gate-prefix - // constants that stood in `views/lens-model.js`, `views/repo-selector.js` and - // `views/staging-workbench-model.js` are now declared in class-B files, and - // the two bindings below declare the four of them that needed a new home as - // their OWN, in the one place the registry can check. + // `gate.bar` (slice S3), `gate.lens` and `gate.projects` (slice S4) sat in + // this CORE arm and every one of them was marked TRANSITIONAL where it stood: + // "slice S5 moves the class-B files behind a contribution openXdox supplies, + // at which point these entries are deleted and the identical bindings arrive + // through `contributedViewBindings()`. Nothing else in this file changes when + // they do." They now arrive that way — declared at + // `openXdox-code` `src/openxdox/view_extensions.py`, with their module bytes + // shipped as that package's data and placed into this bundle's `views/` at + // assembly (RULED Q5, openxFactory#656 comment `5648044785`). // - // `optional: true` is the whole point: a shell assembled without either one - // renders the lens plan panel plan-only and the selector with no project - // commissions — no gate form, no add row, no trash control, and no 404. + // THE SIX MODULES LEFT THE BUNDLE WITH THEM: `views/gate.js`, + // `views/gate-lens.js`, `views/gate-projects.js`, `views/dispose.js`, + // `views/swb-create.js` and `views/swb-session.js`. Six is not four because + // slice S4 split four of the thirteen gate route constants into two NEW + // class-B modules; openDox-spec § 5 row S5 moves "the four class-B files AND + // ALL 13 ROUTE CONSTANTS", and `views/gate-lens.js`'s own header says "AT S5 + // THIS FILE LEAVES THE BUNDLE". // - // BOTH ENTRIES ARE TRANSITIONAL, like `gate.bar`. They sit in the CORE arm - // because at this slice no column contributes anything; slice S5 moves the - // class-B files behind a contribution openXdox supplies, at which point these - // three entries are deleted and the identical bindings arrive through - // `contributedViewBindings()`. Nothing else in this file changes when they do. - { id: "gate.lens", region: "lens-gate", - module: "./views/gate-lens.js", entry: "mountLensGate", view_class: "B", - routes: ["/actions/gate/lens-save-recipe", - "/actions/gate/lens-add-as-cluster"], - requires: ["actions.gate"], optional: true }, - { id: "gate.projects", region: "repo-projects", - module: "./views/gate-projects.js", entry: "mountProjectCommissions", - view_class: "B", - routes: ["/actions/gate/create-project", "/actions/gate/edit-project"], - requires: ["actions.gate"], optional: true }, + // WHAT THAT LEAVES HERE: seven core tabs and not one gate route literal. + // § 4.5 assertion 2's six remaining gate-prefix sites were exactly these + // three entries' `routes:` declarations, and they close together, which is + // what the assertion's own marker predicted. ]; // Tab router with the WAI-ARIA roving-tabindex pattern (a11y #19): only the @@ -860,6 +846,40 @@ async function main() { await render(); } +// RULED Q8's HOST. `page-overlay` is the declared `shell` region for +// page-level panels, and the shell builds it: one element, created once and +// reused across renders, appended to the document body BY THE SHELL — which is +// the difference Q8 draws. A contributed column appending to `document.body` +// itself "is a collision nothing can refuse"; the shell owning one named host +// and handing it over is a contract. +const PAGE_OVERLAY_REGION = "page-overlay"; + +function ensurePageOverlayHost(doc) { + const d = doc || document; + let host = d.getElementById(PAGE_OVERLAY_REGION); + if (host) return host; + host = d.createElement("div"); + host.id = PAGE_OVERLAY_REGION; + d.body.appendChild(host); + return host; +} + +// RULED Q10's FALLBACK — "never a blank". `firstEditTransport` is the doxBench +// Save's transport and it is a class-B export: a shell assembled with no gate +// column has no transport at all, and a Save that silently did nothing would be +// the worst answer available. This stands in for it and REFUSES in the shape +// `runSave` already understands, naming the layering rather than the symptom. +function refusalTransport() { + return async () => ({ + ok: false, + error: "no_gate_column", + message: "this shell was assembled without the column that contributes the " + + "first-edit transport (`gate.workbench.session`), so a governed Save " + + "cannot be sent. Run the CLI verb in your pinned checkout, where the " + + "authority lives.", + }); +} + async function render() { const signal = nextRenderScope(); const status = document.getElementById("loadstatus"); @@ -1009,12 +1029,62 @@ async function render() { [{ views: () => CORE_VIEWS }, { views: () => contributedViewBindings(probedCaps) }], { contributedRoutes: manifestRoutes(probedCaps) }); - gateView = await resolveView(views, "gate.bar"); - // Slice S4's two, resolved once per render exactly as the gate bar is. Null - // is the honest answer for a shell with no gate column, and each consumer - // below treats it as "plan-only" / "no commissions" rather than as an error. - const lensGateView = await resolveView(views, "gate.lens"); - const projectGateView = await resolveView(views, "gate.projects"); + // THE CONTRIBUTED GATE COLUMN, RESOLVED ONCE PER RENDER — six bindings now, + // and every resolve carries the capability probe (§ 3.4 slice S5). + // + // `{ capabilities: probedCaps }` is RULED Q4 (openxFactory#656 comment + // `5648049748`) reaching the shell's own named readers: `resolveView` + // evaluates the binding's `requires` — DOTTED PATHS into this very payload — + // and answers `null` for an unmet requirement on an OPTIONAL binding, which + // is what every reader below already treats as "the column that supplies it + // is not installed". A REQUIRED binding with an unmet requirement refuses, + // naming the binding, the path and the probed value. + // + // NULL IS THE STUDENT'S INSTALL, and it is the whole slice: no gate column + // registered, so no gate bar in the viewer, no dispose tray on a possible, + // no session verbs in the workbench, no project commissions in the + // selector, the lens plan panel plan-only — and no 404, because nothing + // was ever imported. + const resolveContributed = (id) => + resolveView(views, id, { capabilities: probedCaps }); + gateView = await resolveContributed("gate.bar"); + const lensGateView = await resolveContributed("gate.lens"); + const projectGateView = await resolveContributed("gate.projects"); + const disposeView = await resolveContributed("gate.dispose"); + const createView = await resolveContributed("gate.workbench.create"); + const sessionView = await resolveContributed("gate.workbench.session"); + // THE DECLARED NAMESPACES, handed down already-resolved so that no class-A + // or class-C module in this bundle imports a class-B one (§ 4.5 assertion + // 3). Each is the binding's DECLARED namespace and nothing wider: RULED Q2 + // bounds what the shell may reach to the `exports` tuple the binding + // publishes, and a reach past it refuses by name rather than answering + // `undefined` and failing inside a click handler. + const disposeColumn = disposeView ? disposeView.exports : null; + const workbenchGate = { + create: createView ? createView.exports : null, + session: sessionView ? sessionView.exports : null, + }; + // RULED Q8's HOST, BUILT BY THE SHELL. `page-overlay` is a `shell` region: + // it has no standing element, and `index.html` cannot grow one — that file + // is a `moved_verbatim` row of openxFactory's carve manifest whose declared + // edit classes (`import rewrites | path constants | adapter calls`) have no + // class for an added element. So the shell builds it here, once per page, + // and the generic mount pass hands it to whichever binding claims the + // region — today the gate column's refusal panel, which used to append + // itself to `document.body`, "never a contract surface". + ensurePageOverlayHost(); + // RULED Q1 (openxFactory#656 comment `5648044785`): "the shell MOUNTS + // contributed bindings generically: one mount pass over every contributed + // binding whose region is a `dom` region; the three `shell` regions stay + // caller-driven (the gate bar's pattern)." Before this line a column could + // contribute a binding and have nothing ever call it, so every contributed + // panel needed an openDox edit to become reachable — the fork the seam was + // drawn to prevent. The gate column's own six bindings are all `shell` + // regions and are mounted by the callers that build their hosts, which is + // exactly the exception Q1 preserves; the pass exists for the NEXT column. + const contributedMounts = await mountContributedViews( + views, snapshot, { caps, nav: null, views }, + { capabilities: probedCaps }); const explorer = mountExplorer(explorerRoot, snapshot, { signal, onOpenFile: (entry, pane, tile) => { @@ -1027,8 +1097,13 @@ async function render() { gate: gateContext(tile, entry, sourceKey), // Supplied only when a gate binding was collected; absent, the viewer // renders the document and no gate bar (see `gateView` above). + // RULED Q3: ONE mount signature, `mount(host, snapshot, ctx)`. The + // viewer's per-artifact context travels as `ctx.gate` and the probe + // as `ctx.caps`; the gate bar's `(container, ctx, opts)` — the one + // declared exception the contract note recorded — ends at this slice. mountGate: gateView - ? (host, gctx) => gateView.exports[gateView.binding.entry](host, gctx, { caps }) + ? (host, gctx) => gateView.exports[gateView.binding.entry]( + host, snapshot, { gate: gctx, caps }) : null, }); }, @@ -1166,9 +1241,15 @@ async function render() { // The mechanism itself is pinned where it lives, on `runSave` over a // four-buffer state (`test_doxbench_save.py`). The canvas Save sends no // `only`, so its behaviour is byte-for-byte what it was. + // RULED Q10: reached through the REGISTRY, at this one call site, as a + // DECLARED NON-MOUNT EXPORT of the workbench's contributed binding — with + // a refusal-shaped fallback when the column is absent. save: (request) => runSave( savePlanState(request), - { transport: firstEditTransport({ caps, repair: consoleRepair }), + { transport: workbenchGate.session + ? workbenchGate.session.firstEditTransport( + { caps, repair: consoleRepair }) + : refusalTransport(), ...(request && request.only !== undefined ? { only: request.only } : {}) }), catalog: createDoxBenchCatalogLoader(() => caps?.console_token), @@ -1211,6 +1292,14 @@ async function render() { // discarding what the human typed consoleRepair, doxbench: doxbenchSeams, + // THE CONTRIBUTED WORKBENCH GATE COLUMN, handed down already-resolved + // (§ 3.4 slice S5). `views/staging-workbench.js` is class C and used to + // import `views/swb-create.js` and `views/swb-session.js` — two class-B + // modules — directly, which is two of § 4.5 assertion 3's four + // breaches. It now reads what it needs off this object, which is null + // in each half where the column is not installed: no create affordance, + // no session verbs, and no import to fail. + gate: workbenchGate, sourceBase: workbenchSourceBase, edit: workbenchEdit, onScopeOpened: routeWorkbenchScope, onSessionRekey: rekeyToSession, onSessionEnded: resetEndedSession }); @@ -1264,6 +1353,10 @@ async function render() { // `dispose-intent` are declared regions already, so S2 adds an optional // binding and two `lookupView` calls and touches nothing here. views, + // The contributed DISPOSE column's declared namespace, or null. Read by + // the wheel's mount closure above; bounded by RULED Q2's `exports` tuple, + // so a reach past the declaration refuses by name. + dispose: disposeColumn, // Slice S4's two resolved class-B mounts, handed down already-bound so no // class-A or class-C view imports a class-B module to reach them. Null // where the column that supplies them is not installed. @@ -1273,7 +1366,7 @@ async function render() { // anything else here would silently ignore the name it declared). mountLensGate: lensGateView ? (host, lctx) => - lensGateView.exports[lensGateView.binding.entry](host, lctx) + lensGateView.exports[lensGateView.binding.entry](host, snapshot, lctx) : null, // the UNSTRIPPED probe and the serve's own writable repository — read by // exactly one affordance (see `createCaps` at the lens's mount) @@ -1315,7 +1408,8 @@ async function render() { // the whole of what § 3.4 slice S4 leaves in class A mountProjectGate: projectGateView ? (host, pctx) => - projectGateView.exports[projectGateView.binding.entry](host, pctx) + projectGateView.exports[projectGateView.binding.entry]( + host, snapshot, pctx) : null, onSelect: (key) => { storeKey(key); render(); }, onRefreshed: () => render(), @@ -1329,8 +1423,33 @@ async function render() { } if (status) status.remove(); } catch (err) { - if (status) status.textContent = "Could not load the snapshot (" + err.message + - "). The renderer reads a single generated snapshot; regenerate it and reload."; + if (!status) return; + // RULED Q11 (openxFactory#656 comment `5648065587`, Brett Heap, + // 2026-09-12): "the shell catches `ViewBindingError` SEPARATELY and shows a + // registry refusal naming the binding, the rule and the value; a registry + // refusal is no longer framed as a snapshot defect." + // + // WHAT WAS WRONG. Every refusal the view registry raises — a slot + // collision, a module that will not load, an entry that is not a function, + // an undeclared export reached, an unmet required capability, a manifest + // that is not a manifest — was caught by this one handler and reported as + // "Could not load the snapshot … regenerate it and reload". The seam's own + // carefully-composed sentence was parenthesised inside advice that does not + // apply, and a column debugging its own contribution was told to regenerate + // a snapshot that is fine. The messages were right; the frame was wrong. + // + // Matched by `instanceof` AND by name: the class is this bundle's own, so + // `instanceof` holds for every refusal raised through it, and the name + // check keeps the frame right for a refusal that crossed a realm (a worker, + // a test harness) where the constructor identity does not survive. + const registryRefusal = err instanceof ViewBindingError + || (err && err.name === "ViewBindingError"); + status.textContent = registryRefusal + ? "This shell was assembled with a contributed view column it cannot use " + + "(" + err.message + "). The snapshot is fine — the assembly is not: " + + "fix the contributed binding, or serve this bundle without that column." + : "Could not load the snapshot (" + err.message + + "). The renderer reads a single generated snapshot; regenerate it and reload."; } } diff --git a/src/opendox/web/views/dispose.js b/src/opendox/web/views/dispose.js deleted file mode 100644 index 9461698f..00000000 --- a/src/opendox/web/views/dispose.js +++ /dev/null @@ -1,427 +0,0 @@ -// Dispose tray + refusal panel — the LOCAL action center's first verb -// (openxFactory add-ideation-intent-plane §3, design D5 local-first; the -// hosted intent plane later swaps the transport, not this UI). -// -// The tray mounts on a pending_review possible tile when the capability -// probe reports `actions.gate` (loopback bind + real checkout + resolved -// actor — the deployed image never qualifies). Accept / reject / defer POST -// to `/actions/gate/dispose-possible`; reject collects the REQUIRED reason -// and citation first (the register kernel's uncited-rejection rule — the -// engine refuses without them, and that refusal renders in the panel). -// -// TWO TRANSPORTS, ONE TRAY (add-ideation-intent-plane task 4.4, design D5: -// "the identical tray then targets the intent API when hosted"). `opts.intent` -// selects the HOSTED transport: the click emits a `gate-intent` to the inbox -// instead of executing, and the tray shows the feed's chips for this target -// beside the buttons. Absent `opts.intent` NOTHING about the local path -// changes — same route, same body, same panel entries, same overlay. -// -// DOM-safety: every dynamic value is bound via textContent — refusal -// messages from the engine included — never innerHTML (the house posture). -// Two-plane rendering: a successful disposition NEVER mutates the -// snapshot-derived model; it lands in the local `applied` overlay the wheel -// consults, and the tile shows the verdict with a regenerate hint. - -import { el } from "./helpers.js"; -import { emitIntent, renderIntentChips } from "./intent-binding.js"; - -export const GATE_DISPOSE_ROUTE = "/actions/gate/dispose-possible"; -export const GATE_PROPOSE_ROUTE = "/actions/gate/propose"; - -// verdict -> { label, needsCitation } -const VERDICTS = [ - { outcome: "accepted", label: "✓ accept", title: "becomes first-class latent backlog (keeps ai-derived provenance)" }, - { outcome: "rejected", label: "✕ reject", title: "closes it with a required reason + citation; never silently re-derived" }, - { outcome: "deferred", label: "◔ defer", title: "parks it; the only re-disposable outcome" }, -]; - -// The session-local applied overlay: possible id -> outcome. Snapshot stays -// deterministic; views consult this to decorate tiles until a regenerate. -const applied = new Map(); - -export function appliedOutcome(possibleId) { - return applied.get(possibleId) || null; -} - -export function gateCapable(caps) { - return !!(caps && caps.actions && caps.actions.gate); -} - -// ---- refusal panel (one per page; every refusal is visible, never silent) -- - -let panel = null; - -function ensurePanel() { - if (panel && document.body.contains(panel)) return panel; - panel = el("aside", "refusalpanel"); - panel.hidden = true; - const head = el("header", "refusalpanel-head"); - head.appendChild(el("span", "refusalpanel-title", "gate console")); - const clear = el("button", "refusalpanel-clear", "clear"); - clear.type = "button"; - clear.addEventListener("click", () => { - list.innerHTML = ""; - panel.hidden = true; - }); - head.appendChild(clear); - const list = el("ul", "refusalpanel-list"); - panel.append(head, list); - document.body.appendChild(panel); - return panel; -} - -// The panel's vocabulary. "ok"/"refused" are the LOCAL executing plane's two -// outcomes and are unchanged; the other three are the hosted plane's, because a -// submitted intent is neither applied nor refused yet and calling it either -// would be a lie the human acts on (design D1: the click is the decision, the -// apply is the custody step behind it). -// -// THE HOSTED PLANE HAS FOUR OUTCOMES, NOT TWO, and the panel must be able to -// SAY each of them. `emitIntent` normalizes the inbox's responses to -// pending | refused | stalled | error, and the last two are not refusals: -// * "stalled" (HTTP 502) - the intent WAS recorded and the apply run could -// not be started. Labelling it "refused" tells the human their decision was -// rejected when in fact it is on file and undecided, so they re-submit a -// decision that is already queued. -// * "error" (401 / 429 / 400, or an unreachable inbox) - NOTHING was -// recorded. Labelling that "refused" is the opposite lie: it reads as a -// server verdict on the decision when the decision never arrived, so the -// human does NOT re-submit the thing that never got sent. -const PANEL_KIND = { - ok: { label: "applied", cls: "is-ok" }, - queued: { label: "queued", cls: "is-queued" }, - stalled: { label: "stalled", cls: "is-stalled" }, - error: { label: "not sent", cls: "is-error" }, - refused: { label: "refused", cls: "is-refused" }, -}; - -// `emitIntent`/`readEmission` state -> the panel's word for it. Unknown states -// fall back to "refused", the conservative reading (something went wrong and -// the human must look), which is also what the whole map used to collapse to. -export const EMISSION_PANEL_KIND = { - pending: "queued", - refused: "refused", - stalled: "stalled", - error: "error", -}; - -export function panelEntry(kind, message) { - const host = ensurePanel(); - const list = host.querySelector(".refusalpanel-list"); - const shape = PANEL_KIND[kind] || PANEL_KIND.refused; - const item = el("li", "refusalpanel-item " + shape.cls); - item.appendChild(el("span", "refusalpanel-kind", shape.label)); - item.appendChild(el("span", "refusalpanel-msg", message)); - list.insertBefore(item, list.firstChild); - host.hidden = false; -} - -// ---- the tray --------------------------------------------------------------- - -async function post(route, body, fetcher) { - const doFetch = fetcher || fetch; - const response = await doFetch(route, { - method: "POST", - headers: { "Content-Type": "application/json" }, - body: JSON.stringify(body), - }); - let payload = null; - try { - payload = await response.json(); - } catch { - payload = { ok: false, message: "malformed response (HTTP " + response.status + ")" }; - } - return payload; -} - -// Collect reason + citation for a rejection. window.prompt keeps v1 honest -// and tiny; a refusal for an empty value is the engine's job, surfaced in -// the panel like every other refusal. -function collectRejection() { - const reason = window.prompt("Rejection REASON (required — the durable why):", ""); - if (reason === null) return null; // cancelled - const citation = window.prompt("Rejection CITATION (required — what the rejection cites):", ""); - if (citation === null) return null; - return { reason, citation }; -} - -// Mount the tray for one pending possible into `container`. `opts.fetcher` -// and `opts.collect` are test seams; `opts.onApplied(outcome)` lets the view -// refresh its overlay. -// -// `opts.intent` present => THE HOSTED TRANSPORT (task 4.4). It carries -// `{ snapshotRev, rows, error, emit? }`: the revision the human is looking at -// (design D4's `snapshot_rev_seen`), the merged feed rows and error this -// render saw, and an optional emitter seam. The verdict buttons then submit a -// request instead of performing an act, and the chips for this target render -// beside them from the rows handed in — the tray subscribes to nothing and -// owns no timer, so a rail redraw can never leak one. -export function mountDisposeTray(container, possible, opts) { - const o = opts || {}; - const intent = o.intent || null; - const tray = el("span", "disposetray"); - for (const v of VERDICTS) { - const btn = el("button", "disposebtn dispose-" + v.outcome, v.label); - btn.type = "button"; - btn.title = intent - ? v.title + " (hosted: this submits an intent the apply lane decides)" - : v.title; - btn.addEventListener("click", async (ev) => { - ev.stopPropagation(); - const body = { possible_id: possible.id, outcome: v.outcome }; - if (v.outcome === "rejected") { - const extra = (o.collect || collectRejection)(); - if (extra === null) return; // human cancelled - body.reason = extra.reason; - body.citation = extra.citation; - } - tray.classList.add("is-busy"); - if (intent) { - // The kernel forbids a target key inside `args` (the validated target - // is the only target — intent_apply_lane.shape_error), so the verb's - // arguments travel WITHOUT `possible_id`. - const { possible_id: _target, ...args } = body; - const result = await (intent.emit || emitIntent)({ - verb: "dispose-possible", - targetId: possible.id, - args, - snapshotRev: intent.snapshotRev, - fetcher: o.fetcher, - }); - tray.classList.remove("is-busy"); - panelEntry(EMISSION_PANEL_KIND[result.state] || "refused", - possible.id + " → dispose-possible " + v.outcome + ": " + - result.message); - if (o.onEmitted) o.onEmitted(result); - return; - } - const result = await post(GATE_DISPOSE_ROUTE, body, o.fetcher); - tray.classList.remove("is-busy"); - if (result && result.ok) { - applied.set(possible.id, result.outcome); - panelEntry("ok", possible.id + " → " + result.outcome + - " (regenerate the snapshot to fold it in)"); - if (o.onApplied) o.onApplied(result.outcome); - } else { - panelEntry("refused", (result && result.message) || "gate action failed"); - } - }); - tray.appendChild(btn); - } - container.appendChild(tray); - if (intent) { - container.appendChild(renderIntentChips(el("span", "intentchips"), - possible.id, intent.rows, intent.error)); - } - return tray; -} - -// ---- the propose button (add-propose-verb) --------------------------------- -// Mounts on a STAGED tile under the same capability gate as the tray: one click -// commissions proposal authoring for the topic (a recorded workflow-job -// dispatch — never authoring). Session-local overlay only; the snapshot stays -// deterministic. -// -// `opts.compact` is the IN-TILE mount (2026-07-25): the button now lives in the -// expanded tile's action row rather than the badge rail, so it takes smaller -// chrome (.dispose-intile) to fit. Behaviour is identical either way — same -// route, same panel entries, same disable-on-success. - -// SESSION COMMISSIONS, keyed by (VERB, TARGET) — 011 add-wheel-action-verbs. -// -// This map used to be keyed by target id alone, which was unambiguous only -// while one verb per column existed. The possibles column now hosts TWO -// commission verbs, so a target-keyed flag would retire both when either fired -// — contradicting the (verb, target) duplicate rule the engine enforces -// (FR-027/FR-033). `propose` keeps its exact observable behaviour: it is simply -// the "propose" verb in the same store, and `commissionedWorkflow` still -// answers for it with the same signature. -// -// The VALUE is a per-verb marker, not strictly a workflow id: the three -// commissions store their workflow, and `demote` — which commissions nothing — -// stores a non-workflow marker recording that a plan was recorded this session -// (FR-033a). Session-local only: nothing is persisted, and a reload clears it. -const commissions = new Map(); // `${verb}\u0000${target}` -> marker - -const DEMOTE_RECORDED = "demote:planned"; - -function commissionKey(verb, targetId) { - return `${verb}\u0000${targetId}`; -} - -export function commissionedVerb(verb, targetId) { - return commissions.get(commissionKey(verb, targetId)) || null; -} - -export function setCommission(verb, targetId, marker) { - commissions.set(commissionKey(verb, targetId), marker); -} - -/** TEST SEAM: the store is process-lifetime state, so probes reset it. */ -export function resetSessionCommissions() { - commissions.clear(); -} - -export function commissionedWorkflow(topicId) { - return commissionedVerb("propose", topicId); -} - -export function mountProposeButton(container, topic, opts) { - const o = opts || {}; - const btn = el("button", - "disposebtn dispose-propose" + (o.compact ? " dispose-intile" : ""), - "\u25b6 draft proposal"); - btn.type = "button"; - btn.title = "commission proposal authoring for this staging topic " + - "(recorded dispatch; the change lands for review + ratify)"; - btn.addEventListener("click", async (ev) => { - ev.stopPropagation(); - btn.disabled = true; - const result = await post(GATE_PROPOSE_ROUTE, { topic_id: topic.id }, o.fetcher); - if (result && result.ok) { - setCommission("propose", topic.id, result.workflow); - panelEntry("ok", topic.id + " \u2192 proposal authoring commissioned (" + - result.workflow + "); the change arrives for review + ratify"); - if (o.onApplied) o.onApplied(result.workflow); - } else { - btn.disabled = false; - panelEntry("refused", (result && result.message) || "gate action failed"); - } - }); - container.appendChild(btn); - return btn; -} - - -// ---- the wheel action-row verbs (011 add-wheel-action-verbs) --------------- -// -// ONE mounter for all four. They differ only in their target field and in -// whether they collect a reason first, so a per-verb mounter would be four -// copies of the same transport with four chances to diverge. -// -// Every control is composed with `el`, which assigns `textContent` — so a -// refusal message can never introduce markup, and the DOM probe asserts that -// rather than trusting it. - -const VERB_TARGET_FIELD = { - "promote-to-staging": "possible_id", - "research-brief": "possible_id", - "derive-possibles": "cluster_id", - "demote": "change_id", -}; - -const VERB_TITLE = { - "promote-to-staging": - "commission this ACCEPTED possible into a staging fragment " + - "(recorded dispatch; the register is not touched)", - "research-brief": - "commission a pre-verdict evidence brief for this possible " + - "(it informs the verdict and never makes it)", - "derive-possibles": - "commission a cluster-scoped run of the derivation lane " + - "(candidates arrive pending_review)", - "demote": - "send this proposal back to staging: PLANS and RECORDS only — " + - "the file moves stay a separate, human-run step", -}; - -/** - * The in-page reason form (FR-006/FR-006a). Deliberately NOT `window.prompt`: - * accessibility item 19 moved this codebase off blocking prompts, and adopting - * one for new work would walk that back. - * - * Focus moves to the input on open and returns to `opener` on cancel or submit, - * so a keyboard user is never stranded. An empty submit refocuses and dispatches - * nothing; Escape cancels and dispatches nothing. - */ -function mountReasonForm(container, opener, onReason) { - const form = el("div", "wheelreasonform"); - const input = el("input", "wheelreasoninput"); - input.type = "text"; - input.setAttribute("aria-label", "Reason this proposal goes back to staging"); - const close = () => { form.remove(); opener.disabled = false; opener.focus(); }; - const submit = () => { - const reason = String(input.value || "").trim(); - if (!reason) { input.focus(); return; } // nothing dispatched - close(); - onReason(reason); - }; - input.addEventListener("keydown", (ev) => { - if (ev.key !== "Enter" && ev.key !== "Escape") return; - // STOP THE EVENT HERE. The wheel collapses an expanded tile on any Escape - // that reaches it ("Escape collapses from anywhere the keypress can - // reach", wheel.js) — so a bubbling Escape would cancel this form AND - // destroy the action row it lives in, leaving the verb unoffered and no - // control to return focus to. Found by driving the real dashboard; a - // synthetic event aimed straight at this input has no ancestor to reach, - // which is why the unit probe missed it. - ev.preventDefault(); - ev.stopPropagation(); - if (ev.key === "Enter") submit(); else close(); - }); - const ok = el("button", "cbtn wheelreasonsubmit", "record demotion"); - ok.type = "button"; - ok.addEventListener("click", (ev) => { ev.stopPropagation(); submit(); }); - const cancel = el("button", "cbtn wheelreasoncancel", "cancel"); - cancel.type = "button"; - cancel.addEventListener("click", (ev) => { ev.stopPropagation(); close(); }); - form.append(input, ok, cancel); - container.appendChild(form); - input.focus(); - return form; -} - -/** - * Mount ONE action-row verb. `opts.verb` selects the route, the target field - * and the title; `opts.collectReason` is a test seam standing in for the form. - * - * On success the verb is retired for this (verb, target) THIS SESSION and the - * tile is decorated by the caller's `onApplied`. On refusal the control is - * re-enabled and nothing is retired, so the human can correct and retry. - */ -export function mountWheelVerb(container, item, opts) { - const o = opts || {}; - const verb = o.verb; - const targetField = VERB_TARGET_FIELD[verb]; - const btn = el("button", - "disposebtn dispose-" + verb + (o.compact === false ? "" : " dispose-intile"), - o.label || verb); - btn.type = "button"; - btn.title = VERB_TITLE[verb] || verb; - - const dispatch = async (extra) => { - btn.disabled = true; - const body = { [targetField]: item.id, ...(extra || {}) }; - if (o.topic) body.topic = o.topic; - const result = await post("/actions/gate/" + verb, body, o.fetcher); - if (result && result.ok) { - // demote commissions no workflow, so the marker is per-verb, never a - // required `workflow` field on the response (FR-033a). - setCommission(verb, item.id, result.workflow || DEMOTE_RECORDED); - const where = result.job || result.plan || result.record || ""; - panelEntry("ok", item.id + " → " + verb + " recorded" + - (where ? " (" + where + ")" : "")); - if (o.onApplied) o.onApplied(result.workflow || DEMOTE_RECORDED); - } else { - btn.disabled = false; // retry after correcting - panelEntry("refused", (result && result.message) || "gate action failed"); - } - }; - - btn.addEventListener("click", async (ev) => { - ev.stopPropagation(); - if (verb !== "demote") { await dispatch(); return; } - // demote REQUIRES a typed reason, collected before anything is dispatched - if (o.collectReason) { - const reason = o.collectReason(); - if (!reason) return; // cancelled: nothing sent - await dispatch({ reason }); - return; - } - btn.disabled = true; // the form owns the control now - mountReasonForm(container, btn, (reason) => { dispatch({ reason }); }); - }); - - container.appendChild(btn); - return btn; -} diff --git a/src/opendox/web/views/gate-lens.js b/src/opendox/web/views/gate-lens.js deleted file mode 100644 index b691daf9..00000000 --- a/src/opendox/web/views/gate-lens.js +++ /dev/null @@ -1,204 +0,0 @@ -// THE LENS'S TWO GATE VERBS — class B, and the first half of slice S4's answer -// to RULED Q3 (openxFactory#656 comment `5642758731`, Brett Heap, 2026-09-12): -// **"a route constant travels with the binding that calls it, never with the -// model that happens to declare it."** -// -// WHAT MOVED, AND FROM WHERE. `views/lens-model.js` is the census's purest -// class-A file — "pure and import-free", a geometry/matching derivation unit- -// tested from Python through node — and it carried two `/actions/gate/*` -// constants at :1036 and :1037 (openDox-spec `docs/front-end-package-boundary.md` -// § 1.2(c)'s table, § 3.2's `lens-model.js` row, § 4.5 assertion 2's "gate -// prefix, 10 sites, cleared by S4"). It declared them and never called them: -// `views/lens.js` did, from the execute affordance of its plan panel. Under Q3 -// that makes the model the wrong home twice over — it neither calls them nor -// belongs to the column that serves them — so the two constants, the POST that -// uses them, the organizer-evidence form that feeds one of them and the outcome -// panel that renders either one's answer are all HERE now, in one class-B -// module the gate column owns. -// -// WHY A WHOLE MODULE AND NOT TWO CONSTANTS IN `lens.js`. `views/lens.js` is the -// census's one remaining `"?"` row (§ 3.2; none of Q1–Q5 rules on its two -// openxFactory-lane routes, so it stays `"?"` under assertion 1's declared, -// ruled-later exception). Moving a gate constant into it would relocate the -// § 2.2 rule 1 breach rather than clear it — assertion 2's scope is "every -// census row whose class is not B", and `"?"` is squarely in it. Class B is the -// only home that is not a relocation, and § 2.1's own test says why this file -// is one: delete the gate column and it has nothing left to render. -// -// HOW THE LENS REACHES IT: through the S3 VIEW REGISTRY, never an import. -// `views/lens.js` receives `mountLensGate` as an already-resolved closure from -// the shell (`app.js` resolves the `gate.lens` binding once per render, exactly -// as it resolves `gate.bar` for the viewer) and treats its absence as "no gate -// column here" — which is what a student install is (RULING C2 one tier out, -// § 4.1). That is `consumer_reach`'s posture in the browser: LATE, NAMED and -// REFUSABLE instead of an import-time dependency on a column that may not be -// installed (§ 4.2). -// -// AT S5 THIS FILE LEAVES THE BUNDLE. Its binding is declared in `app.js`'s -// CORE arm today and moves behind a contribution openXdox supplies (§ 5 S5); -// nothing in `lens.js` changes when it does, which is the test of whether the -// seam was drawn in the right place. -// -// WHAT IT DOES NOT OWN. The REQUEST BODIES are pure derivations over a plan the -// panel already confirmed (`recipeRequest` / `clusterRequest`), and a pure -// derivation over the snapshot is class-A substance that stays with the model -// — Q3 moves the ROUTE, not the arithmetic. They are imported from there, which -// is the legal direction (a class-B file may read class A; § 4.5 assertion 3 -// forbids only the reverse). -// -// DOM-SAFETY, unchanged from the code's previous home: every dynamic value — -// including the engine's refusal text — binds through `textContent` (helpers' -// `el`), never `innerHTML`; the only `innerHTML` assignments are literal "" -// clears. -// -// A CREATED file: no row in openxFactory's `docs/opendox-carve-manifest.yaml` -// (RULED OQ-C), admitted by path in `docs/opendox-carve-admissions.yaml`. - -import { el } from "./helpers.js"; -import { clusterRequest, recipeRequest } from "./lens-model.js"; - -// The two gate routes the lens verbs post to (add-lens-gate-verbs). They sit -// under `openxdox/serve_gate.py`'s `ACTIONS_GATE_PREFIX` and are declared by -// the gate column, so they live in the binding that calls them — the deployed -// static image never serves them, and the plan panel probes the gate -// capability before revealing execute. -export const LENS_SAVE_ROUTE = "/actions/gate/lens-save-recipe"; -export const LENS_CLUSTER_ROUTE = "/actions/gate/lens-add-as-cluster"; - -// The routes this binding declares to the registry, in one place so the -// `gate.lens` entry and this module cannot drift apart. -export const LENS_GATE_ROUTES = [LENS_SAVE_ROUTE, LENS_CLUSTER_ROUTE]; - -async function postPlan(route, body, fetcher) { - const doFetch = fetcher || fetch; - const response = await doFetch(route, { - method: "POST", - headers: { "Content-Type": "application/json" }, - body: JSON.stringify(body), - }); - try { - return await response.json(); - } catch { - return { ok: false, message: "malformed response (HTTP " + response.status + ")" }; - } -} - -// Render the landing confirmation (success) or the engine's refusal verbatim. -// textContent-bound like every other value here. -function renderOutcome(container, result) { - container.innerHTML = ""; - if (result && result.ok) { - const ok = el("div", "dc-landed"); - ok.appendChild(el("div", "dc-h", "landed ✓ — recorded gate dispatch")); - ok.appendChild(el("div", "dc-line", "manifest: " + result.manifest)); - if (result.pending_entry) { - ok.appendChild(el("div", "dc-line", "pending entry: " + result.pending_entry)); - } - ok.appendChild(el("div", "dc-line", "gate-action record: " + result.record)); - if (result.note) ok.appendChild(el("div", "dc-note", result.note)); - container.appendChild(ok); - } else { - const refused = el("div", "dc-refused"); - refused.appendChild(el("div", "dc-h", "refused ✕")); - refused.appendChild(el("div", "dc-line", (result && result.message) || "gate action failed")); - container.appendChild(refused); - } -} - -// The human-seen organizer evidence form (add-as-cluster only). Collects the -// full contract the engine requires; a blank/short field is NOT pre-validated — -// the engine refuses and the reason renders verbatim (single source of truth). -function renderEvidenceForm(container, actor, onSubmit) { - function clear() { - container.innerHTML = ""; - } - clear(); - const form = el("div", "reason-form evidence-form"); - form.appendChild(el("span", "rf-label", - "human-seen evidence (organizer contract — the engine refuses an incomplete one):")); - const fields = [ - ["proposer", "proposer", actor], - ["revision", "committed revision (40/64-hex)", ""], - ["path", "source path", ""], - ["section", "section", ""], - ["passage_sha256", "passage sha256 (64-hex)", ""], - ["rationale", "rationale", ""], - ["confidence", "confidence 0–1", ""], - ["alternatives", "alternatives (comma-separated; may be empty)", ""], - ]; - const inputs = {}; - for (const [key, label, value] of fields) { - const input = document.createElement("input"); - input.type = "text"; - input.value = value || ""; - input.setAttribute("aria-label", label); - input.setAttribute("placeholder", label); - inputs[key] = input; - form.appendChild(input); - } - const submit = el("button", "cbtn", "execute"); - submit.type = "button"; - const cancel = el("button", "cbtn", "cancel"); - cancel.type = "button"; - submit.addEventListener("click", () => { - const alts = inputs.alternatives.value.split(",").map((s) => s.trim()).filter((s) => s); - const conf = parseFloat(inputs.confidence.value); - onSubmit({ - proposer: inputs.proposer.value.trim(), - revision: inputs.revision.value.trim(), - path: inputs.path.value.trim(), - section: inputs.section.value.trim(), - passage_sha256: inputs.passage_sha256.value.trim(), - rationale: inputs.rationale.value.trim(), - confidence: Number.isNaN(conf) ? inputs.confidence.value.trim() : conf, - alternatives: alts, - }); - }); - cancel.addEventListener("click", clear); - form.appendChild(submit); - form.appendChild(cancel); - container.appendChild(form); -} - -// THE BINDING'S ENTRY. `host` is the plan panel's own box — a `"shell"` region -// (`lens-gate`), which by § 4.1's own definition is a mount point the shell -// builds at mount time and hands over, exactly like `viewer-gatebar`. `ctx` -// carries the confirmed plan, the capability probe's payload and the -// injectable fetcher (the test seam every transport in this bundle keeps). -// -// A save-recipe plan posts immediately; an add-as-cluster plan first collects -// the human-seen organizer evidence, and the engine's refusal for an incomplete -// submission renders here. -export function mountLensGate(host, ctx) { - const o = ctx || {}; - const plan = o.plan; - if (!host || !plan) return null; - const result = el("div", "dc-result"); - result.setAttribute("aria-live", "polite"); - const bar = el("div", "dc-exec"); - const run = el("button", "cbtn", - plan.kind === "add-as-cluster" ? "execute → add as cluster" : "execute → save recipe"); - run.type = "button"; - run.title = "EXECUTES via the local gate route (actor: " + ((o.caps && o.caps.actor) || "local") + ")"; - - async function dispatch(body, route) { - run.disabled = true; - const payload = await postPlan(route, body, o.fetcher); - renderOutcome(result, payload); - if (!(payload && payload.ok)) run.disabled = false; // let a refused plan be retried - } - - run.addEventListener("click", () => { - if (plan.kind === "add-as-cluster") { - renderEvidenceForm(result, (o.caps && o.caps.actor) || "", (evidence) => { - dispatch(clusterRequest(plan, evidence), LENS_CLUSTER_ROUTE); - }); - } else { - dispatch(recipeRequest(plan), LENS_SAVE_ROUTE); - } - }); - bar.appendChild(run); - host.appendChild(bar); - host.appendChild(result); - return { element: bar, result }; -} diff --git a/src/opendox/web/views/gate-projects.js b/src/opendox/web/views/gate-projects.js deleted file mode 100644 index 4b1e712a..00000000 --- a/src/opendox/web/views/gate-projects.js +++ /dev/null @@ -1,241 +0,0 @@ -// THE PROJECT COMMISSIONS — class B, and the second half of slice S4's answer to -// RULED Q3 (openxFactory#656 comment `5642758731`, Brett Heap, 2026-09-12): -// **"a route constant travels with the binding that calls it, never with the -// model that happens to declare it."** -// -// WHAT MOVED, AND FROM WHERE. `views/repo-selector.js` is the file openDox-spec -// `docs/front-end-package-boundary.md` § 3.2 describes as addressing ALL THREE -// COLUMNS from one place: openDox's `/project-register.json` and -// `/actions/refresh`, openXdox's `/snapshot-index.json` and its two -// `/actions/gate/*` project commissions, and openxFactory's own -// `/actions/apply-register-edits` lane. Q3 RULES it SPLIT: "the picker and the -// refresh affordance are class A; the two `/actions/gate/*` project commissions -// become a contributed binding with S4; `/actions/apply-register-edits` is -// openxFactory's lane and leaves the bundle entirely." -// -// THIS FILE IS THAT CONTRIBUTED BINDING. It owns the two gate routes, the -// create-project form that commissions a new project, and the membership-edit -// commission the repo filter's add line and trash controls raise. The PICKER -// stays where it was: choosing what you are looking at is the student's own -// gesture (§ 6 Q3: "moving it whole puts the project picker — the student's way -// to choose what they are working on — behind the gate column"), so only the -// COMMISSIONING half travels. -// -// A COMMISSION IS NOT A WRITE, and that is the whole posture the two routes -// carry with them: the POST records a project-register-edit descriptor plus a -// gate record, and the aggregation-owned register is edited only by the -// fulfilment. Refusals render `textContent`-only; a successful create retires -// the form for the session (the engine's duplicate guard is the backstop). -// -// HOW THE SELECTOR REACHES IT: through the S3 VIEW REGISTRY, never an import. -// `app.js` resolves the `gate.projects` binding once per render — exactly as it -// resolves `gate.bar` for the viewer — and hands `mountRepoSelector` the -// resolved mount, or null. Null is what a student install is: no "New Project…" -// line that acts, no create form, no add row, no trash control, and NO 404 -// (§ 4.1's own promise, RULING C2 one tier out). That is `consumer_reach`'s -// posture in the browser: LATE, NAMED and REFUSABLE instead of an import-time -// dependency on a column that may not be installed (§ 4.2). -// -// AT S5 THIS FILE LEAVES THE BUNDLE. Its binding is declared in `app.js`'s CORE -// arm today and moves behind a contribution openXdox supplies (§ 5 S5); nothing -// in `repo-selector.js` changes when it does, which is the test of whether the -// seam was drawn in the right place — the reason this module is shaped as a -// binding with a `mount` entry and a returned controller rather than as two -// exported helpers the selector calls. -// -// TWO DEAD PARAMETERS DID NOT TRAVEL. The previous `mountCreateProject(wrap, -// status, roster, projects, o, addPendingOption)` never read `projects`, and -// `commissionEdit(body, control, restore)` never read `control` — both callers -// passed a value that the body ignored. Carrying an unread parameter across a -// package boundary would freeze a mistake into the contributed contract, so -// neither is in the signatures below. -// -// DOM-SAFETY, unchanged from the code's previous home: every dynamic value -// binds through `textContent` (helpers' `el`); no `innerHTML` is assigned here -// at all. -// -// A CREATED file: no row in openxFactory's `docs/opendox-carve-manifest.yaml` -// (RULED OQ-C), admitted by path in `docs/opendox-carve-admissions.yaml`. - -import { el } from "./helpers.js"; - -// add-project-scoped-selection: the create-project commission route. -// add-opendox-project-header (D15/D16): the membership-edit commission route -// the filter popover's add line and trash controls POST to. Both sit under -// `openxdox/serve_gate.py`'s `ACTIONS_GATE_PREFIX`, and both degrade away -// exactly like the index: a static image 404s them and the selector renders -// without the affordance. -export const ACTIONS_CREATE_PROJECT_ROUTE = "/actions/gate/create-project"; -export const ACTIONS_EDIT_PROJECT_ROUTE = "/actions/gate/edit-project"; - -// The routes this binding declares to the registry, in one place so the -// `gate.projects` entry and this module cannot drift apart. -export const PROJECT_GATE_ROUTES = [ - ACTIONS_CREATE_PROJECT_ROUTE, ACTIONS_EDIT_PROJECT_ROUTE, -]; - -// The create-project affordance (add-project-scoped-selection): a COMMISSION, -// never a write. Mounted only where this binding is contributed AND the probe -// reports the gate capability. Member candidates are ALL roster repositories: -// membership is multi-parent (Brett's 2026-08-06 ruling), so a repository -// already in a project is a legal member of a new one — projects are named -// views, not owners. -// -// REHOMED by add-opendox-project-header (D13): no standalone button — the -// project dropdown's "New Project" line opens the form through the returned -// opener. -function mountCreateProject(wrap, status, roster, o, addPendingOption) { - const seen = new Set(); - const candidates = []; - for (const option of roster || []) { - if (option.kind !== "repository") continue; - if (seen.has(option.repository)) continue; - seen.add(option.repository); - candidates.push(option.repository); - } - - // A LABELED PANEL, not a bare strip (Brett's 2026-08-06 annotation: "which - // is this? i do not know how to use this widget") — a heading names the - // act, the field and the member list carry captions, and the buttons say - // what happens (a recorded commission, not a direct write). - const form = el("span", "projectform projectpanel"); - form.hidden = true; - form.appendChild(el("span", "panelhead", "New Project")); - form.appendChild(el("span", "panelnote", - "records a project-register commission — the project appears as pending " - + "until a session fulfils it")); - - const nameField = el("label", "panelfield"); - nameField.appendChild(el("span", "panellabel", "project name")); - const name = el("input", "projectname"); - name.type = "text"; - name.placeholder = "e.g. Field Pilots"; - name.setAttribute("aria-label", "new project name"); - nameField.appendChild(name); - form.appendChild(nameField); - - form.appendChild(el("span", "panellabel", "member repositories")); - const memberList = el("span", "panelmembers"); - const boxes = []; - for (const repo of candidates) { - const label = el("label", "projectmember"); - const box = el("input"); - box.type = "checkbox"; - box.value = repo; - label.appendChild(box); - label.appendChild(el("span", null, repo)); - boxes.push(box); - memberList.appendChild(label); - } - if (!candidates.length) { - memberList.appendChild(el("span", "projectform-note", - "no published repositories to choose from")); - } - memberList.appendChild(el("span", "projectform-note", - "optional — an empty project is fine; add repositories later from the " - + "filter")); - form.appendChild(memberList); - - const buttonRow = el("span", "panelbuttons"); - const submit = el("button", "repobtn", "commission project"); - submit.type = "button"; - buttonRow.appendChild(submit); - const cancel = el("button", "repobtn projectcancel", "cancel"); - cancel.type = "button"; - cancel.addEventListener("click", () => { form.hidden = true; }); - buttonRow.appendChild(cancel); - form.appendChild(buttonRow); - - submit.addEventListener("click", async () => { - const members = boxes.filter((b) => b.checked).map((b) => b.value); - status.textContent = ""; - submit.disabled = true; - try { - const opts = { - method: "POST", - headers: { "Content-Type": "application/json" }, - body: JSON.stringify({ name: name.value, repositories: members }), - }; - const response = o.fetcher - ? await o.fetcher(ACTIONS_CREATE_PROJECT_ROUTE, opts) - : await fetch(ACTIONS_CREATE_PROJECT_ROUTE, opts); - const data = await response.json().catch(() => ({})); - if (!response.ok || data?.ok !== true) { - submit.disabled = false; - status.textContent = "create-project refused: " - + (data?.message || data?.error || ("HTTP " + response.status)); - return; - } - form.hidden = true; // retired for the session - status.textContent = "project-register edit recorded (" + data.job + ")"; - // the commission appears in the dropdown immediately as a pending entry - // (D-e) — the register itself changes only when the fulfilment lands - if (addPendingOption) addPendingOption(name.value || data.project_id); - } catch (err) { - submit.disabled = false; - status.textContent = "create-project failed: " + (err?.message || "error"); - } - }); - - wrap.appendChild(form); - return () => { // the "New Project…" opener (D13) - form.hidden = false; - name.focus(); - }; -} - -// THE BINDING'S ENTRY. `host` is the selector's own header slot — a `"shell"` -// region (`repo-projects`), which by § 4.1's definition is a mount point the -// shell builds at mount time and hands over, exactly like `viewer-gatebar`. -// -// `ctx` is `{ roster, status, fetcher, addPendingOption }`: the roster the -// member checklist is drawn from, the selector's one message span (a -// commission's refusal renders where every other selector message does), the -// injectable fetcher every transport in this bundle keeps as its test seam, -// and the dropdown's pending-entry appender. -// -// Returns the two acts the selector triggers and this column performs: -// -// openCreateForm() the D13 "New Project…" line -// commissionEdit(projectId, body, opts) the filter's add row and trash -// -// `opts` for a membership edit is `{ restore, onRecorded }`: `restore` puts the -// control the human clicked back the way it was when the commission is refused -// (a two-click trash re-arms, a select restores its placeholder), and -// `onRecorded(data)` hands the accepted commission back so the selector can -// badge the pending edit (the D-e two-plane posture). Neither is required. -export function mountProjectCommissions(host, ctx) { - const o = ctx || {}; - const status = o.status || el("span", "repopick-msg"); - const openCreateForm = mountCreateProject(host, status, o.roster, o, - o.addPendingOption); - - async function commissionEdit(projectId, body, opts) { - const { restore, onRecorded } = opts || {}; - status.textContent = ""; - try { - const fetchOpts = { - method: "POST", - headers: { "Content-Type": "application/json" }, - body: JSON.stringify({ project_id: projectId, ...body }), - }; - const response = o.fetcher - ? await o.fetcher(ACTIONS_EDIT_PROJECT_ROUTE, fetchOpts) - : await fetch(ACTIONS_EDIT_PROJECT_ROUTE, fetchOpts); - const data = await response.json().catch(() => ({})); - if (!response.ok || data?.ok !== true) { - if (restore) restore(); - status.textContent = "edit-project refused: " - + (data?.message || data?.error || ("HTTP " + response.status)); - return; - } - status.textContent = "membership edit recorded (" + data.job + ")"; - if (onRecorded) onRecorded(data); - } catch (err) { - if (restore) restore(); - status.textContent = "edit-project failed: " + (err?.message || "error"); - } - } - - return { openCreateForm, commissionEdit }; -} diff --git a/src/opendox/web/views/gate.js b/src/opendox/web/views/gate.js deleted file mode 100644 index 2dd3ffb7..00000000 --- a/src/opendox/web/views/gate.js +++ /dev/null @@ -1,184 +0,0 @@ -// Human gate console bar (US9; D16/D17). The READ-ONLY web v1 surfaces the four -// gate affordances (demote / edit / ratify / kickoff) on a gate-bearing artifact -// and produces the ACTION DESCRIPTOR — the exact `cli.py gate ...` command a -// human runs against their pinned checkout. It NEVER executes a gate -// server-side: serve.py stays GET/HEAD read-only, and gate authority is -// human-only (a human running the CLI, whose `--actor` identity the record -// carries). This module is a pure descriptor builder plus a DOM-safe mount; -// every dynamic value is bound via textContent (never innerHTML), matching -// canvas.js's war-room DOM-safety posture. - -export const GATE_ACTIONS = ["demote", "edit", "ratify", "kickoff"]; - -const LABELS = { - demote: "⤺ reject → staging", - edit: "✎ edit (redline)", - ratify: "✓ approve / ratify", - kickoff: "▶ kickoff next step", -}; - -const NOTES = { - demote: "mechanized reverse transition — drafts return to the staging topic's openspec/ workspace", - edit: "apply a HUMAN-approved redline; the AI drafting of redlines is a follow-on delta", - ratify: "write the ratification record (ratifier, date) + register update", - kickoff: "dispatch the ratified change's next step — refused without a recorded ratification", -}; - -const CLI = "python3 src/opendox/cli.py"; - -// A change document is gate-bearing when it is one of the OpenSpec change -// documents (proposal / design / tasks / spec deltas) — purely from its path. -// Pure — unit-tested via node. -export function isGateBearing(path) { - const p = String(path || ""); - const base = p.split("/").pop(); - return base === "proposal.md" || base === "design.md" || base === "tasks.md" - || /(^|\/)specs\/.*\bspec\.md$/.test(p); -} - -// Shell-quote one descriptor value so the emitted command is copy-pasteable -// VERBATIM — the promise these descriptors make, and the one they broke. -// -// POSIX SINGLE quotes, and EVERY interpolated value goes through here (PR #49 -// review findings 15; the same discipline `q()` in staging-workbench-model.js -// carries, spelled locally because this module stays import-free so its pure -// helpers keep running standalone under node). Inside single quotes a POSIX -// shell expands NOTHING, so the only character needing care is `'` itself, -// closed and re-opened around an escaped literal (`'\''`). -// -// Wave 1 quoted the workbench's descriptors and left THIS emitter unquoted: -// `--change-id`, `--repository`, `--actor` and `--document` were interpolated -// bare, so a `$(…)` or backtick in a change id / repository / actor mutated the -// pasted command and a bare `;` split it into a second command the descriptor -// never showed. The values are snapshot- and corpus-derived (the change id and -// document path come from the served artifact, the repository from the snapshot -// identity), so the trust boundary crossed is "merged corpus content -> the -// human's shell in the served checkout". -// -// The `<...>` placeholders are quoted too. They are not decoration a shell can -// be trusted with: `` unquoted is a REDIRECT, and `` in double quotes -// is a redirect the moment the quotes are the outer ones. Quoting everything — -// placeholders, the literal `.` repo root, values already validated upstream — -// removes the standing question of which slots were safe. -// -// Quoting is not validation and does not pretend to be: the value reaches the -// CLI as ONE argument, and the CLI's own allowlist is what refuses it, inside -// the process, which is the layer that can refuse. -function q(value) { - return "'" + String(value).split("'").join("'\\''") + "'"; -} - -// The exact CLI command for one action — copy-pasteable, with `<...>` -// placeholders a human fills. Pure — unit-tested via node. -export function gateCommand(action, ctx) { - const c = ctx || {}; - const change = q(c.changeId || ""); - const actor = q(c.actor || ""); - const repo = q(c.repository || ""); - const id = `--repo-root ${q(".")} --actor ${actor} --change-id ${change}`; - const snap = `--repository ${repo}`; - switch (action) { - case "demote": - return `${CLI} gate demote ${id} ${snap} --reason ${q("")} --execute`; - case "ratify": - return `${CLI} gate ratify ${id} --ratifier ${actor}`; - case "edit": - return `${CLI} gate edit-apply ${id} --document ${q(c.path || "")}` - + ` --old-file ${q("")} --new-file ${q("")}`; - case "kickoff": - return `${CLI} gate kickoff ${id} ${snap}`; - default: - return null; - } -} - -// The full descriptor list for a gate-bearing artifact. Pure — unit-tested. -export function gateActionDescriptors(ctx) { - return GATE_ACTIONS.map((action) => ({ - action, - label: LABELS[action], - note: NOTES[action], - command: gateCommand(action, ctx), - })); -} - -function el(tag, cls, text) { - const node = document.createElement(tag); - if (cls) node.className = cls; - if (text != null) node.textContent = text; // textContent only — never innerHTML - return node; -} - -// Executing upgrade (add-ideation-intent-plane §3, local action center): -// when the caller supplies a capability verdict reporting `actions.gate` -// (loopback bind + real checkout + resolved actor), the RATIFY affordance -// executes through `POST /actions/gate/ratify` instead of only revealing -// the CLI command. demote / edit / kickoff stay descriptor-only this slice -// (multi-step plan/redline flows). Capabilities arrive via `opts.caps` -// (app.js owns the probe) — this module stays import-free so its pure -// helpers keep running standalone under node (the house test pattern). -export const GATE_RATIFY_ROUTE = "/actions/gate/ratify"; - -async function executeRatify(ctx, fetcher) { - const doFetch = fetcher || fetch; - const response = await doFetch(GATE_RATIFY_ROUTE, { - method: "POST", - headers: { "Content-Type": "application/json" }, - body: JSON.stringify({ change_id: ctx.changeId }), - }); - try { - return await response.json(); - } catch { - return { ok: false, message: "malformed response (HTTP " + response.status + ")" }; - } -} - -// Mounts the gate bar into `container` for the gate-bearing artifact described -// by `ctx` ({ changeId, path, repository, actor }). Each affordance reveals the -// exact CLI command (the action descriptor); ratify additionally EXECUTES when -// the local gate capability is live (`opts.caps` or a self-probe). -export function mountGateBar(container, ctx, opts) { - // clear only — every dynamic value below is bound via textContent - container.innerHTML = ""; - const bar = el("div", "gatebar"); - bar.appendChild(el("div", "gatebar-title", "human gate console — run the command in your pinned checkout")); - const descriptors = gateActionDescriptors(ctx); - const cmdLine = el("div", "gatebar-cmd docstatus"); - cmdLine.hidden = true; - const actions = el("div", "gatebar-actions"); - const ratifyButtons = []; - for (const d of descriptors) { - const btn = el("button", "gatebtn", d.label); - btn.type = "button"; - btn.title = d.note; - btn.addEventListener("click", () => { - cmdLine.hidden = false; - cmdLine.textContent = d.note + " — " + d.command; - }); - if (d.action === "ratify") ratifyButtons.push(btn); - actions.appendChild(btn); - } - bar.appendChild(actions); - bar.appendChild(cmdLine); - container.appendChild(bar); - - // async executing upgrade — never blocks the descriptor render. - const o = opts || {}; - const upgrade = (caps) => { - if (!caps?.actions?.gate) return; - for (const btn of ratifyButtons) { - btn.classList.add("gatebtn-live"); - btn.title = "EXECUTES via the local gate route (actor: " + (caps.actor || "local") + ")"; - btn.addEventListener("click", async () => { - cmdLine.hidden = false; - cmdLine.textContent = "ratifying " + (ctx.changeId || "?") + "…"; - const result = await executeRatify(ctx, o.fetcher); - cmdLine.textContent = result.ok - ? "ratified " + result.change_id + " by " + result.ratifier + " (" + result.date + ") — record: " + result.record - : "refused — " + (result.message || "gate action failed"); - }); - } - }; - upgrade(o.caps || null); - return { descriptors }; -} diff --git a/src/opendox/web/views/staging-workbench.js b/src/opendox/web/views/staging-workbench.js index c08656a2..dd089395 100644 --- a/src/opendox/web/views/staging-workbench.js +++ b/src/opendox/web/views/staging-workbench.js @@ -85,11 +85,42 @@ import { import { renderDocWheel } from "./doc-wheel.js"; import { buildLensModel } from "./lens-model.js"; import { renderBullseye } from "./bullseye.js"; -import { mountCreateAffordance, openCreateDialog, createGateLive } from "./swb-create.js"; -import { - createdDocuments, documentCreated, endedSessions, mountSessionAffordances, - openedSessions, sessionOpened, -} from "./swb-session.js"; +// THE TWO WORKBENCH CLASS-B MODULES ARE NOT IMPORTED HERE ANY MORE (§ 3.4 +// slice S5). These were `import { mountCreateAffordance, openCreateDialog, +// createGateLive } from ./swb-create.js` and a six-name import from +// ./swb-session.js — two of the four breaches openDox-spec +// `docs/front-end-package-boundary.md` § 4.5 assertion 3 measures, a CLASS-C +// file statically importing CLASS-B modules, and the reason a student install +// failed to LOAD rather than coming up without the session verbs. +// +// Both modules are openXdox's package data now, contributed as the +// `gate.workbench.create` and `gate.workbench.session` bindings (RULED Q5, +// openxFactory#656 comment `5648044785`). `app.js` resolves both once per +// render and hands their DECLARED NAMESPACES (RULED Q2) down as `gate.create` +// and `gate.session`; `mountStagingWorkbench` installs them below. Absent, the +// null columns answer "no gate capability" and "no sessions", so this file's +// existing capability branches do the whole gating and nothing here needs a +// second one — § 4.2's "late, named and refusable", in the browser. +const NO_CREATE_COLUMN = Object.freeze({ + createGateLive: () => false, + mountCreateAffordance: () => null, + openCreateDialog: () => null, +}); +const NO_SESSION_COLUMN = Object.freeze({ + createdDocuments: () => [], + documentCreated: () => null, + endedSessions: () => [], + mountSessionAffordances: () => null, + openedSessions: () => [], + sessionOpened: () => null, +}); +//: Installed by `mountStagingWorkbench` before any affordance can mount; module +//: level for the reason `views/wheel.js` gives of its own column — the call +//: sites are spread across a 3,300-line overlay and threading a per-render +//: object through every one of them would be a parameter that exists only to be +//: forwarded. +let createColumn = NO_CREATE_COLUMN; +let sessionColumn = NO_SESSION_COLUMN; import { primaryFragmentPath } from "./wheel-model.js"; import { insertSection, outlineModel } from "./outline-model.js"; import { renderViewer } from "./viewer.js"; @@ -1482,12 +1513,25 @@ export function mountStagingWorkbench(container, snapshot, // the caller's render scope: this // overlay binds a document listener signal, + // § 3.4 slice S5: the CONTRIBUTED + // workbench gate column, already + // resolved by the shell — + // `{ create, session }`, either half + // null where openXdox is not registered + gate, sourceBase, edit, onSessionRekey, onSessionEnded, onScopeOpened } = {}) { // The wheel behind this overlay stays on the shell snapshot while a create // may temporarily adopt a branch snapshot inside the workbench. Reopening // from that wheel must therefore start from the shell state again; otherwise // the retained branch projection can be rendered with a newly reset main key. + // THE CONTRIBUTED WORKBENCH GATE COLUMNS, installed before anything mounts. + // `gate` is what `app.js` resolved off the `gate.workbench.create` and + // `gate.workbench.session` bindings; either half null is "no gate column + // here", which the null objects above turn into "not offered" rather than + // "undefined". + createColumn = gate?.create || NO_CREATE_COLUMN; + sessionColumn = gate?.session || NO_SESSION_COLUMN; let shellSnapshot = snapshot; let shellActive = active; let shellIndex = index; @@ -1511,7 +1555,7 @@ export function mountStagingWorkbench(container, snapshot, // always shown; with the gate on it states the ONE write it can perform and // the actor who would perform it — a surface that misdescribes its own // authority is worse than one with no pill. - const gateOn = createGateLive(caps); + const gateOn = createColumn.createGateLive(caps); const readonly = el("span", "pill " + (gateOn ? "stage" : "neutral"), gateOn ? "gate: create-document" : "read-only"); readonly.title = gateOn @@ -1777,8 +1821,8 @@ export function mountStagingWorkbench(container, snapshot, // is ready, then moves both together before opening the document, // WITHOUT widening `main`, which must never carry a draft. onSessionOpened: (result) => { - sessionOpened(result.ref); - documentCreated(result.ref, result.path); + sessionColumn.sessionOpened(result.ref); + sessionColumn.documentCreated(result.ref, result.path); drawSession(); return rekeyToSession(result.ref); }, @@ -1786,13 +1830,17 @@ export function mountStagingWorkbench(container, snapshot, }, mount(host, tab, extra) { if (!this.offered(tab)) return null; - return mountCreateAffordance(host, this.seed(tab, extra), - { ...this.options(extra), label: CREATE_LABELS[tab] }); + // RULED Q3: ONE mount signature, `mount(host, snapshot, ctx)` — the + // seed travels as `ctx.seed`. + return createColumn.mountCreateAffordance(host, shellSnapshot, + { ...this.options(extra), seed: this.seed(tab, extra), + label: CREATE_LABELS[tab] }); }, open(host, tab, extra) { if (!this.offered(tab)) return null; - return openCreateDialog(host, this.seed(tab, extra), - { ...this.options(extra), label: CREATE_LABELS[tab] }); + return createColumn.openCreateDialog(host, shellSnapshot, + { ...this.options(extra), seed: this.seed(tab, extra), + label: CREATE_LABELS[tab] }); }, }; @@ -1818,12 +1866,18 @@ export function mountStagingWorkbench(container, snapshot, // engine's `discover_tile_inventory` unions, read from the projection the // page already holds — no route and no second liveness signal. { active, index, snapshot, - opened: openedSessions(), ended: endedSessions() }); + opened: sessionColumn.openedSessions(), + ended: sessionColumn.endedSessions() }); posturechip.textContent = posture.label; posturechip.title = posture.detail; posturechip.classList.toggle("is-draft", posture.ownTile); posturechip.classList.toggle("is-live", posture.live && !posture.ownTile); - mountSessionAffordances(sessionhost, { + // RULED Q3: ONE mount signature, `mount(host, snapshot, ctx)`. The session + // context travels under `ctx.session` and the seams beside it, so neither + // set can shadow the other; the old call passed the context second and the + // seams third. + sessionColumn.mountSessionAffordances(sessionhost, snapshot, { + session: { scope, posture, // The edit picker's options: the documents this tile's session MAY rewrite @@ -1839,8 +1893,9 @@ export function mountStagingWorkbench(container, snapshot, // branch, under a gate record that read as authorised. The route refuses it // now too (`gate_routes.foreign_document_refusal`) — the picker is UI, the // route is the boundary, and they are deliberately the same sentence. - documents: rewritableDocuments(scope, createdDocuments(posture.branch)), - }, { + documents: rewritableDocuments(scope, + sessionColumn.createdDocuments(posture.branch)), + }, caps, fetcher, repair: consoleRepair, actor: (caps && caps.actor) || null, onSessionEnded: async () => { @@ -1852,7 +1907,8 @@ export function mountStagingWorkbench(container, snapshot, // once the end is CONFIRMED (a null next means it did not end). const endedBranch = sessionPosture(scope, { active, index, snapshot, - opened: openedSessions(), ended: endedSessions(), + opened: sessionColumn.openedSessions(), + ended: sessionColumn.endedSessions(), }).branch; const next = await onSessionEnded(); if (!next?.snapshot || !scope) return null; @@ -2097,12 +2153,13 @@ export function mountStagingWorkbench(container, snapshot, // non-destructive refresh cannot drift from what the mount used. function canvasProjection() { const posture = sessionPosture(scope, - { active, index, snapshot, opened: openedSessions(), ended: endedSessions() }); + { active, index, snapshot, opened: sessionColumn.openedSessions(), + ended: sessionColumn.endedSessions() }); return doxbenchScopeProjection(snapshot, scope.kind, scope.id, { repository: active.repository, ref: active.ref, outlinePathFor: (outline) => primaryFragmentPath(outline.stagingId, outline.files), - createdDocuments: createdDocuments(posture.branch), + createdDocuments: sessionColumn.createdDocuments(posture.branch), }); } function railScopeKey() { @@ -2576,7 +2633,7 @@ export function mountStagingWorkbench(container, snapshot, // canvas mount and by the docs tile's verbs (F3), so the tile can never claim a // capability the canvas withheld or deny one it has. function canvasOffered() { - return !!scope && createGateLive(caps) && !sessionSurfaceHidden(caps) + return !!scope && createColumn.createGateLive(caps) && !sessionSurfaceHidden(caps) && !!active?.repository && !!active?.ref; } function drawCanvas() { @@ -2592,7 +2649,7 @@ export function mountStagingWorkbench(container, snapshot, // is LIVE — fed back by the mounted rail's adopted catalog (see the // onState wiring below) and reset to zero on rail teardown. const plane = presentationPosture({ - gateLive: createGateLive(caps), + gateLive: createColumn.createGateLive(caps), surfaceHidden: sessionSurfaceHidden(caps), repository: active?.repository, ref: active?.ref, @@ -2726,7 +2783,7 @@ export function mountStagingWorkbench(container, snapshot, railCatalogFailure = failure; postureIntakeOffered = modelIntakeOffered; const refreshed = presentationPosture({ - gateLive: createGateLive(caps), + gateLive: createColumn.createGateLive(caps), surfaceHidden: sessionSurfaceHidden(caps), repository: active?.repository, ref: active?.ref, @@ -2975,7 +3032,7 @@ export function mountStagingWorkbench(container, snapshot, // overlay takes). // the SERVE's posture, not the view's projection const authoring = createCaps || caps; - if (!createGateLive(authoring) || sessionSurfaceHidden(authoring)) { + if (!createColumn.createGateLive(authoring) || sessionSurfaceHidden(authoring)) { // Defence in depth: the lens no longer OFFERS the jump where it cannot // land, so reaching this is a programming error rather than a posture — // it still says something true and actionable rather than showing an @@ -3178,7 +3235,9 @@ export function mountStagingWorkbench(container, snapshot, function buildDraftPanes() { { - openCreateDialog(detailsPane, seed, { + // RULED Q3: `mount(host, snapshot, ctx)`, the seed under `ctx.seed`. + createColumn.openCreateDialog(detailsPane, shellSnapshot, { + seed, caps: authoring, fetcher, repair: consoleRepair, label: "create document", // SAVE, not create (Brett, 2026-08-10: "it seems to the user that we @@ -3216,8 +3275,8 @@ export function mountStagingWorkbench(container, snapshot, promoteDraftToTile(path); }, onSessionOpened: async (result) => { - sessionOpened(result.ref); - documentCreated(result.ref, result.path); + sessionColumn.sessionOpened(result.ref); + sessionColumn.documentCreated(result.ref, result.path); drawSession(); // The re-key itself, WITHOUT the DOM half: `adoptSessionRef` bails // on a draft (it guards `!scope`, and a draft has none), so the diff --git a/src/opendox/web/views/swb-create.js b/src/opendox/web/views/swb-create.js deleted file mode 100644 index 79c077af..00000000 --- a/src/opendox/web/views/swb-create.js +++ /dev/null @@ -1,384 +0,0 @@ -// The staging workbench's CREATE-DOCUMENT affordance — dialog + transport -// (openxFactory `add-workbench-bullseye-and-create`, design D5/D7/D8). -// -// WHY THIS IS A SIBLING MODULE AND NOT PART OF staging-workbench.js: the view -// file is PINNED free of transport (test_staging_workbench.py asserts it carries -// no fetch call, no method literal, no XHR) and the pure model module is pinned -// import-free for its node harness. So the one write the workbench performs -// lives here, in the shape dispose.js / gate.js / lens.js already established: -// an injectable fetcher (`const doFetch = fetcher || fetch`), which is also what -// keeps this file out of test_renderer.py's pinned set of fetch-bearing bundle -// files. -// -// WHAT IT CAN DO: exactly one thing — bring a NEW document into existence -// through the human-only gate verb, which drives the tested authoring scaffold -// (`authoring.create_scaffold` -> `boundary.create_document`, create-only). It -// cannot edit, cannot delete, and cannot overwrite: an existing target refuses -// as a source-edit and the refusal renders here verbatim. -// -// GATE-OFF (design D8): with `caps.actions.gate` absent — the hosted static -// image, a non-loopback bind, an unresolved actor — no live control is rendered -// at all. The affordance becomes a COPYABLE CLI DESCRIPTOR carrying the seeded -// values, which is strictly more useful than a greyed-out button because it is -// the whole action, transportable to where the authority lives. Enforcement is -// at the route regardless; hiding the control is a courtesy, never the boundary. -// -// DOM-SAFETY: every dynamic value binds through textContent (helpers.el); the -// only innerHTML assignments are literal "" clears. - -import { el } from "./helpers.js"; -import { panelEntry } from "./dispose.js"; -import { - CONTINUATIONS, consoleHeaders, createDocumentCommand, - createRequest, withConsoleRepair, -} from "./staging-workbench-model.js"; - -// THE CREATE-DOCUMENT GATE ROUTE, DECLARED WHERE IT IS CALLED (§ 3.4 slice S4). -// It stood at `views/staging-workbench-model.js`:543 at the carve commit and -// this module imported it from there — a class-B file reaching into the pure -// model for a route only this file ever POSTs. RULED Q3 (openxFactory#656 -// comment `5642758731`, Brett Heap, 2026-09-12): "a route constant travels with -// the binding that calls it, never with the model that happens to declare it." -// Still a CONSTANT and never a literal in the transport, so the wire contract -// keeps the single definition the node harness and the Python route tests read -// — in the class-B module the gate column owns, which is where it can travel -// with the binding at slice S5. -export const CREATE_ROUTE = "/actions/gate/create-document"; - -export function createGateLive(caps) { - return !!(caps && caps.actions && caps.actions.gate); -} - -// `repair` is the shell's ONE console-token re-read (app.js `createConsoleRepair`). -// The header is built INSIDE `send`, from the same `caps` object the repair -// writes into, so the retry presents the live token rather than the one this -// page loaded with. Nothing else about the request changes — the body is the -// human's typed form, and it is sent again exactly as it was. -async function submitCreate(body, fetcher, caps, repair) { - const doFetch = fetcher || fetch; - const send = async () => { - const response = await doFetch(CREATE_ROUTE, { - method: "POST", - // the human-console header among them (FR-019's third clause) - headers: consoleHeaders(caps), - body: JSON.stringify(body), - }); - try { - return await response.json(); - } catch { - return { ok: false, message: "malformed response (HTTP " + response.status + ")" }; - } - }; - return withConsoleRepair(send, repair); -} - -function labelledInput(host, label, value, opts) { - const o = opts || {}; - const row = el("label", "swb-cfield"); - const name = el("span", "swb-clabel", label); - // WHICH FIELDS ARE YOURS is the question the form could not answer (Brett, - // 2026-08-09: "the title, summary, topics look empty"). Empty here means two - // different things — a value the machine cannot know, and a value it simply - // did not find — so the ones a human must supply are MARKED, not merely - // blank, and every field says what it is for. - if (o.required) { - const mark = el("span", "swb-creq", "yours"); - mark.title = "this field cannot be computed — the create refuses without it"; - name.appendChild(mark); - } - row.appendChild(name); - const input = document.createElement("input"); - input.type = "text"; - input.value = value == null ? "" : String(value); - input.setAttribute("aria-label", label); - if (o.placeholder) input.setAttribute("placeholder", o.placeholder); - row.appendChild(input); - if (o.help) row.appendChild(el("span", "swb-chelp", o.help)); - host.appendChild(row); - return input; -} - -// A create inside a tile scope opens or joins its branch session. Await the -// shell hand-off before the document jump, so the source read and edit action -// cannot observe different repository/ref keys. -async function renderSessionLanding(box, result, onSessionOpened) { - if (!result.ref) return true; - box.appendChild(el("div", "swb-cline", "session branch: " + result.ref + - (result.joined ? " (joined)" : " (opened)"))); - box.appendChild(el("div", "swb-cline", "commit: " + result.commit)); - if (!onSessionOpened) return false; - try { - await onSessionOpened(result); - return true; - } catch { - box.appendChild(el("div", "swb-cnote swb-notice", - "notice: the session opened, but its document view could not be " + - "loaded; refresh and select the session branch")); - return false; - } -} - -async function renderLanded(host, result, onOpenDoc, onSessionOpened) { - const box = el("div", "swb-clanded"); - box.appendChild(el("div", "swb-ch", "created ✓ — recorded gate dispatch")); - box.appendChild(el("div", "swb-cline", "document: " + result.path)); - box.appendChild(el("div", "swb-cline", "gate-action record: " + result.record)); - const sessionViewReady = await renderSessionLanding( - box, result, onSessionOpened); - // FR-042 / D19: a session that opened WITHOUT its notebook is a NOTICE, not a - // failure — the session is live and fully usable. - if (result.notebook_notice) { - box.appendChild(el("div", "swb-cnote swb-notice", - "notice: " + result.notebook_notice)); - } - if (result.hint) box.appendChild(el("div", "swb-cnote", result.hint)); - host.appendChild(box); - panelEntry("ok", "created " + result.path + " (record " + result.record + ")" - + (result.ref ? " on " + result.ref : "")); - if (onOpenDoc && sessionViewReady) onOpenDoc(result.path); -} - -function renderRefused(host, result) { - const refused = el("div", "swb-crefused"); - refused.appendChild(el("div", "swb-ch", "refused ✕")); - refused.appendChild(el("div", "swb-cline", - result?.message || "the create was refused")); - host.appendChild(refused); - panelEntry("refused", result?.message || "create-document refused"); -} - -// The landing confirmation / refusal. The engine's refusal message reaches the -// human verbatim (the route's response discipline) — never a paraphrase. -async function renderOutcome(host, result, onOpenDoc, onSessionOpened) { - host.innerHTML = ""; - if (result?.ok) { - await renderLanded(host, result, onOpenDoc, onSessionOpened); - return; - } - renderRefused(host, result); -} - -// The FR-025 continuation control: unset, `resume`, or `new`. Unset is the -// default and the ordinary case — the field is only meaningful once the engine has -// REPORTED the choice, and the report is a refusal that renders right below. -function continuationPicker(host) { - const row = el("label", "swb-cfield"); - row.appendChild(el("span", "swb-clabel", "Continuation")); - const select = document.createElement("select"); - select.setAttribute("aria-label", - "answer the resume-or-new report on a tile whose abandoned branch survives"); - const unset = document.createElement("option"); - unset.value = ""; - unset.textContent = "(none — be shown the choice)"; - select.appendChild(unset); - for (const token of CONTINUATIONS) { - const option = document.createElement("option"); - option.value = token; - option.textContent = token === "resume" - ? "resume — keep the existing branch and its history" - : "new — open the next ordinal session"; - select.appendChild(option); - } - row.appendChild(select); - host.appendChild(row); - return select; -} - -// The create form: every seeded value editable, `title` and `summary` the -// human's to type (design D7 — they have no honest machine seed, and a generated -// one would be prose the dashboard invented). -function renderForm(host, seed, opts) { - const o = opts || {}; - host.innerHTML = ""; - const form = el("div", "swb-cform"); - form.appendChild(el("div", "swb-ch", "new document in this scope")); - form.appendChild(el("div", "swb-cnote", - "seeded from what this tab already knows — every value is editable, and the " + - "create is create-only: an existing path is refused, never overwritten.")); - - const title = labelledInput(form, "Title", seed.title, { - required: true, - placeholder: "the document's H1", - help: "The document's H1 and how it reads in every wheel and list. Empty " - + "because naming a topic is the one judgment the selection cannot make " - + "for you.", - }); - const summary = labelledInput(form, "Summary", seed.summary, { - required: true, - placeholder: "one sentence — yours to write, never generated here", - help: "One sentence, in the header, used by doc-health and by every " - + "reader deciding whether to open this. Deliberately never generated: " - + "a placeholder summary reaching the queue is the thing that rule " - + "exists to prevent.", - }); - const topics = labelledInput(form, "Topics", (seed.topics || []).join(", "), { - placeholder: "comma-separated declared topics", - help: "The declared keywords this document carries — filled from the terms " - + "EVERY selected document shares. Empty means your selection shares no " - + "single term, and the create needs at least one.", - }); - const area = labelledInput(form, "Area", seed.area, { - help: "Where the file lands, inside `ideation/`. Filled from the staging " - + "topic this convergence names.", - }); - // `Status:` is seeded `brainstorm` and NEVER follows the area (Brett's - // 2026-07-25 ruling on open question 1 — "these are brainstorm docs"; the - // packet tie is the AREA's placement, not this header). Editable, so a human - // writing an organized fragment can promote it here. - const status = labelledInput(form, "Status", seed.status, { - help: "The lifecycle header. A new document is never born ratified — " - + "`brainstorm`, `staged` or `draft` only.", - }); - const kind = labelledInput(form, "Kind", seed.kind, { - help: "What sort of document this is, in the header contract's vocabulary " - + "(`note`, `capability-proposal`, …).", - }); - form.appendChild(el("div", "swb-cnote", "Repository context: " + - (seed.repositoryContext || "(none in this snapshot)"))); - form.appendChild(el("div", "swb-csource", "Source: " + seed.source)); - // THE RESUME-OR-NEW ANSWER (007-workbench-branch-sessions T082, FR-025). The - // CHOICE is the refusal: on a tile whose ABANDONED branch survives, the first - // create is REFUSED with a report naming the branch, both continuations, and - // the ordinal a NEW session would allocate. The human answers HERE and - // resubmits — which is why this control is deliberately unset by default: a - // seeded answer would answer for them, and every ordinary create sends none. - const continuation = continuationPicker(form); - - const result = el("div", "swb-cresult"); - result.setAttribute("aria-live", "polite"); - const bar = el("div", "swb-cactions"); - // THE ACTION IS NAMED FOR WHAT THE HUMAN IS DOING (Brett, 2026-08-10: "the - // create document is confusing. it seems to the user that we already have a - // document and what we want to do is save the document"). He is right: by the - // time this form is reachable from a draft, the document exists on screen — - // a body he wrote and fields already filled — and `create document` is the - // ENGINE'S verb (`create-document`) surfacing in the UI. The engine still - // runs two governed verbs, and that stays invisible. The TILE path keeps - // `create document`, where a genuinely new document is what is being started. - const submit = el("button", "cbtn", o.submitLabel || "create document"); - submit.type = "button"; - submit.title = "EXECUTES via the local gate route (actor: " + - ((o.caps && o.caps.actor) || "local") + ")"; - const cancel = el("button", "cbtn", "cancel"); - cancel.type = "button"; - cancel.addEventListener("click", () => { host.innerHTML = ""; }); - - submit.addEventListener("click", async () => { - // The tile's SCOPE rides the seed (`scopeKind` / `scopeId`, set by - // `createSeed`) into `createRequest`, which is where the wire spelling lives - // — so this transport gains the branch-session identity - // (007-workbench-branch-sessions T023a) without gaining a second request - // site or a second body definition. The model is the payload contract; this - // file stays the ONE write. - const body = createRequest(seed, { - title: title.value.trim(), - summary: summary.value.trim(), - topics: topics.value.split(",").map((t) => t.trim()).filter((t) => t), - area: area.value.trim(), - status: status.value.trim(), - kind: kind.value.trim(), - continuation: continuation.value, - }); - // SAY THAT IT IS RUNNING (Brett, 2026-08-10: "i pressed create twice"). - // A create OPENS A BRANCH SESSION — worktree, branch, commit, and the - // session's own regenerated snapshot — and on a large plane under two - // concurrent requests that measured 90 seconds. All this button did was - // grey out, so a human with a second create dialog open pressed again; the - // second press JOINED the session the first had just opened, found the - // document already there, and read the create-only refusal - // (`corpus documents are create-only`) as the outcome of their work — - // while the create that landed answered 77 seconds later. - // - // Disabling was never the whole affordance: `disabled` says "not now", and - // the human needed "working, and here is what that involves". The label is - // restored in `finally` so a refusal is retriable in place with its own - // words back on the button. - const label = submit.textContent; - submit.disabled = true; - submit.textContent = o.runningLabel || "creating… (opening the branch session)"; - let payload; - try { - payload = await submitCreate(body, o.fetcher, o.caps, o.repair); - } finally { - submit.textContent = label; - } - await renderOutcome(result, payload, o.onOpenDoc, o.onSessionOpened); - // a refused create is retriable in place; a landed one is done - if (!(payload && payload.ok)) submit.disabled = false; - }); - - bar.append(submit, cancel); - // WHERE THE ONE ACTION LIVES. By default the form carries its own action bar - // and outcome panel, exactly as before. A caller that shows this form on ONE - // TAB of a larger surface passes `actionsHost`, and the button that writes — - // with the answer it gets — moves to that host, so it is on screen wherever - // the human is standing rather than only on the tab that owns the fields - // (Brett's ruling, 2026-08-10: keep the tabs, put ONE save on both). - const actions = o.actionsHost || form; - actions.appendChild(bar); - actions.appendChild(result); - // Escape closes the FORM, not the whole workbench (the shell's document-level - // Escape handler would otherwise take the human out of their scope). - form.addEventListener("keydown", (ev) => { - if (ev.key === "Escape") { ev.stopPropagation(); host.innerHTML = ""; } - }); - host.appendChild(form); - if (o.focusOnMount !== false) title.focus(); - // The handle a hosting surface needs: submit it from a control of its own. - // Deliberately the ONE button's own click — never a second submit path, so - // the running label, the disabled window and the outcome rendering are the - // same code whichever control the human pressed. - return { el: form, submit: () => { if (!submit.disabled) submit.click(); } }; -} - -// The gate-off rendering: the exact CLI invocation, selectable and copyable. -function renderDescriptor(host, seed, opts) { - const o = opts || {}; - const box = el("div", "swb-cdescriptor"); - box.appendChild(el("div", "swb-clabel", o.label || "new document in this scope")); - box.appendChild(el("div", "swb-cnote", - "this surface has no gate capability (read-only host) — run the seeded " + - "command in your pinned checkout, where the authority lives:")); - const cmd = el("code", "swb-ccmd", - createDocumentCommand(seed, { actor: (o.caps && o.caps.actor) || null })); - cmd.tabIndex = 0; - box.appendChild(cmd); - host.appendChild(box); - return box; -} - -// Mount ONE create affordance into `host` for `seed`. With the gate capability -// live this is a labelled button revealing the form; without it, a copyable CLI -// descriptor and no write path at all. `opts`: { caps, fetcher, label, -// onOpenDoc, onSessionOpened } — `onOpenDoc(path)` opens the created document in -// the read-only viewer (the same seam the docs rows use), and -// `onSessionOpened(result)` tells the shell the create opened or joined a BRANCH -// SESSION, so its posture indicator stops reading from a boot-time roster. -export function mountCreateAffordance(host, seed, opts) { - const o = opts || {}; - if (!createGateLive(o.caps)) return renderDescriptor(host, seed, o); - const wrap = el("div", "swb-cwrap"); - // `opts.slot` lets a caller share ONE dialog host between this button and - // another opener (the lens tab's centre-ring gesture), so the two affordances - // can never render two competing forms. - const slot = o.slot || el("div", "swb-cslot"); - const open = el("button", "cbtn swb-cbtn", o.label || "+ new document"); - open.type = "button"; - open.title = "create a header-compliant document in " + seed.area + - " through the human-only gate verb (create-only)"; - open.addEventListener("click", () => renderForm(slot, seed, o)); - wrap.appendChild(open); - if (!o.slot) wrap.appendChild(slot); - host.appendChild(wrap); - return wrap; -} - -// The centre-ring gesture's opener (design D6): the SAME dialog with the SAME -// seeding rule, so the ring and the button can never diverge. Gate-off, the ring -// reveals the descriptor rather than a form — still no write from the page. -export function openCreateDialog(host, seed, opts) { - const o = opts || {}; - host.innerHTML = ""; - if (!createGateLive(o.caps)) return renderDescriptor(host, seed, o); - return renderForm(host, seed, o); -} diff --git a/src/opendox/web/views/swb-session.js b/src/opendox/web/views/swb-session.js deleted file mode 100644 index 8754ab8f..00000000 --- a/src/opendox/web/views/swb-session.js +++ /dev/null @@ -1,661 +0,0 @@ -// The staging workbench's BRANCH-SESSION affordances — the three live session -// verbs, their outcomes, and the copyable CLI descriptors that replace them where -// this plane has no authority (007-workbench-branch-sessions T082; -// FR-044–FR-046; plan Constraint 11; research R6). -// -// WHY THIS IS A FOURTH MODULE AND NOT PART OF ANY EXISTING ONE. Three pins meet -// here and all three are the boundary, not an inconvenience: -// -// * `test_renderer.py:130` pins the bundle's same-origin call-site set to five -// files with per-file counts. A transport that uses the INJECTED-fetcher -// spelling (`const doFetch = fetcher || fetch;`) contributes no call site, so -// this file stays out of that set — the same trick `swb-create.js` uses. -// * `test_staging_workbench.py` pins `staging-workbench.js` and -// `staging-workbench-model.js` transport-free, and the model additionally -// import-free (it is copied ALONE into a node harness). So the view cannot -// hold this and the model cannot either. -// * the same file pins ONE write-method literal per transport module. This -// module addresses THREE routes, so the three verbs share ONE request helper -// and select their route from the model's constants. That is the pin's -// design: a second write literal would be a second, unreviewed write site. -// -// WHAT IT CAN DO — exactly three things, and each is a HUMAN-only gate verb the -// engine enforces independently of anything decided here: -// -// edit rewrite an EXISTING document inside the tile's session (FR-015). -// Session-only: with no session live the engine refuses and names -// `edit-apply`, the main-resident redline path, which is untouched. -// save push the session branch and open (or update) its pull request into -// the EXISTING Merge-Master ritual (FR-029). It merges, approves, -// self-reviews, and bypasses nothing — the port declares no such -// operation (FR-030) and branch protection enforces it outside the -// dashboard either way. -// abandon end the session without saving, with the REQUIRED durable reason -// (FR-021/FR-022). Pushed history and any open pull request survive; -// the branch is retained and its deletion is a separate, human-invoked -// verb (FR-028). -// -// WHAT IT DELIBERATELY CANNOT DO. `refresh notebook` is DESCRIPTOR-ONLY in BOTH -// gate postures (spec C10, FR-044): it is not a gate route and not a `gate` -// subcommand, FR-040 maps it to `sync-notebooklm-books.py --session-ref`, and no -// ratified text asks for a live button. Giving it one would invent an FR-020 -// parity obligation and FR-047 pin arithmetic out of thin air. It renders here as -// the copyable invocation, filled in for this session's branch. -// -// GATE-OFF (FR-046): with the probe's gate capability absent — an unresolved -// actor, or the static bundle whose `/capabilities` 404s — the mount returns the -// DESCRIPTORS before any live control exists. Enforcement is at the route -// regardless; withholding the control is a courtesy, never the boundary. -// -// HOSTED (FR-048) is a DIFFERENT answer, and conflating the two was review -// finding 14: a plane that explicitly reports `session: false` gets NOTHING — -// no posture line, no descriptor, no branch name. It has no sessions to describe -// and no checkout to run a CLI in, and a descriptor there would publish the -// topic ids of unmerged work. `sessionSurfaceHidden` is that discriminator. -// -// THE ENDING RE-DERIVES (Phase 7 note 4). A save that comes back `merged: true` -// means the branch was already merged, so the SESSION ENDED instead of being -// saved again: the response carries `torn_down` / `branch_deleted` / -// `record: null` rather than a pull request. An abandon ends it too. Either way -// the affordances must stop offering a session that is over, so both land in the -// page-lifetime `ended` overlay below and the mount re-renders from it — exactly -// how `dispose.js` treats an applied disposition. -// -// DOM-SAFETY: every dynamic value binds through `helpers.el`'s textContent; the -// only innerHTML assignments are literal "" clears. Refusals render in -// `dispose.js`'s shared panel, so a session refusal looks like every other -// refusal on the page. - -import { el } from "./helpers.js"; -import { panelEntry } from "./dispose.js"; -import { - SESSION_ABANDON, SESSION_AFFORDANCES, SESSION_EDIT, SESSION_LABELS, - SESSION_FIRST_EDIT, SESSION_REFRESH_NOTEBOOK, SESSION_SAVE, SESSION_SHARE, - SESSION_VERBS, - consoleHeaders, firstEditBody, firstEditVerdict, notebookRefreshCommand, - sessionActionsLive, sessionCommand, sessionRequest, - sessionSurfaceHidden, withConsoleRepair, -} from "./staging-workbench-model.js"; - -// ---- THE FIVE SESSION GATE ROUTES, DECLARED WHERE THEY ARE CALLED --------- -// -// § 3.4 slice S4. All five stood in `views/staging-workbench-model.js` at the -// carve commit — :817, :818, :821, :822, :826 — with the lookup table and -// `sessionRoute()` beside them, and every one of them is POSTed from this file -// and from nowhere else. RULED Q3 (openxFactory#656 comment `5642758731`, Brett -// Heap, 2026-09-12): "a route constant travels with the binding that calls it, -// never with the model that happens to declare it." -// -// THE REASON THEY WERE CONSTANTS IS UNCHANGED and is now served in the right -// place: constants here, never literals in the transport, so the wire contract -// has ONE definition the node harness and the Python route tests read — and it -// is a definition that can travel with the binding at slice S5 instead of being -// stranded in a pure model the gate column does not own. -export const EDIT_DOCUMENT_ROUTE = "/actions/gate/edit-document"; -export const OPEN_PR_ROUTE = "/actions/gate/open-pr"; -// 010-doxbench-editor-chat T080: the first-Save gate verb. A CANVAS seam, not -// a session-bar affordance -- deliberately absent from SESSION_AFFORDANCES. -export const FIRST_EDIT_ROUTE = "/actions/gate/first-edit"; -export const ABANDON_SESSION_ROUTE = "/actions/gate/abandon-session"; -// add-doxbench-editing-phase-b §12: the SHARE route, beside open-pr's because it -// is the same class of act (a remote write with the engineer's own credential) -// with the pull request removed. -export const SHARE_SESSION_ROUTE = "/actions/gate/share-session"; - -// The routes this module declares to the registry at slice S5, in one place so -// the binding entry and this file cannot drift apart. -export const SESSION_GATE_ROUTES = [ - EDIT_DOCUMENT_ROUTE, OPEN_PR_ROUTE, FIRST_EDIT_ROUTE, - ABANDON_SESSION_ROUTE, SHARE_SESSION_ROUTE, -]; - -const SESSION_ROUTES = { - [SESSION_EDIT]: EDIT_DOCUMENT_ROUTE, - [SESSION_SAVE]: OPEN_PR_ROUTE, - [SESSION_ABANDON]: ABANDON_SESSION_ROUTE, - [SESSION_SHARE]: SHARE_SESSION_ROUTE, - [SESSION_FIRST_EDIT]: FIRST_EDIT_ROUTE, -}; - -// The model's own `asId` is private to it and stayed there; this is the same -// one-line normalization, so an affordance arriving as null or a number reads -// as "no route" rather than as a key lookup on a coerced value. -export function sessionRoute(affordance) { - return SESSION_ROUTES[affordance == null ? "" : String(affordance)] || null; -} - -// ---- the page-lifetime overlays -------------------------------------------- -// -// The roster the posture reads was fetched at BOOT, so it is stale in both -// directions the moment the human acts: it does not yet know about a session a -// `create-document` just OPENED, and it still advertises one that just ENDED. -// These two maps are what make the indicator and the affordances honest between an -// action and a reload. Session-local only — nothing derived is mutated, exactly -// like dispose.js's `applied` map, and a reload replaces both with the server's -// own answer. - -const opened = new Map(); // branch -> true -const ended = new Map(); // branch -> "merged" | "abandoned" -// branch -> { affordance, result, ending }: the ENGINE'S OWN report for the action -// that ended the session, remembered because the ending RE-RENDERS the affordance -// row and the re-render rebuilds the host the outcome was written into (T088, -// found by the Playwright smoke). Without this the answer to the most -// consequential action of a session's life — what was torn down, whether the -// branch was deleted — appeared and vanished inside one tick, leaving only -// tooltips. FR-044 wants the engine's answer to REACH the human. -const endedReports = new Map(); - -// Called by the view when a create response names a session `ref` (the create -// transport lives in swb-create.js; the view wires the two together rather than -// making the sibling modules depend on each other). -export function sessionOpened(branch) { - const ref = String(branch || ""); - if (ref) opened.set(ref, true); -} - -export function openedSessions() { - return [...opened.keys()]; -} - -// The THIRD page-lifetime overlay (T092 defect 1 + defect 5): the documents this -// page's creates brought into existence, per session branch. A created document -// is the one thing outside a tile's own material its session may rewrite — the -// route says the same thing from the other side (`foreign_document_refusal`) — and -// the snapshot the page holds was fetched before the create, so without this the -// create→edit loop cannot be completed in one sitting on a tile that owns no -// folder. Session-local, exactly like `opened`: a reload replaces it with the -// session snapshot, which by then carries the document. -const created = new Map(); // branch -> Set(path) - -export function documentCreated(branch, path) { - const ref = String(branch || ""); - const rel = String(path || ""); - if (!ref || !rel) return; - if (!created.has(ref)) created.set(ref, new Set()); - created.get(ref).add(rel); -} - -export function createdDocuments(branch) { - const ref = String(branch || ""); - return ref && created.has(ref) ? [...created.get(ref)] : []; -} - -export function endedSessions() { - return [...ended.keys()]; -} - -export function sessionEnding(branch) { - return ended.get(String(branch)) || null; -} - -export function sessionEndingReport(branch) { - return endedReports.get(String(branch)) || null; -} - -// ---- the ONE request site -------------------------------------------------- -// -// Three routes, one helper, one write-method literal. `fetcher` is the injected -// transport seam every sibling module takes, and `repair` is the shell's ONE -// console-token re-read (app.js `createConsoleRepair`). -// -// The header is built INSIDE `send`, from the same `caps` object the repair -// writes into, so a retry after a serve restart presents the LIVE token. The -// stakes are the same as the create's: `edit-document` carries the whole -// rewritten body of a document and `first-edit` the whole editor buffer, so a -// reload to fix a header would discard exactly the work the refusal -// interrupted. - -async function submitSession(affordance, body, fetcher, caps, repair) { - const doFetch = fetcher || fetch; - const send = async () => { - const response = await doFetch(sessionRoute(affordance), { - method: "POST", - // the human-console header among them (FR-019's third clause): a write that - // cannot present this serve's token is refused before its body is parsed - headers: consoleHeaders(caps), - body: JSON.stringify(body), - }); - try { - return await response.json(); - } catch { - return { ok: false, message: "malformed response (HTTP " + response.status + ")" }; - } - }; - return withConsoleRepair(send, repair); -} - -// ---- the doxBench Save transport (010-doxbench-editor-chat T080) ----------- -// -// The CANVAS's governed-Save wire, composed here because this module is where -// the branch-session verbs already live and `submitSession` is the ONE request -// site (three routes became four, same helper, same single write-method -// literal). This export is the TRANSPORT half only -- app.js composes it with -// the pure planner (doxbench-save.js) into the seam the canvas receives, so -// this module keeps its no-sibling-import harness discipline. Both wire -// translations are the MODEL's pure functions; nothing here invents -// vocabulary. One request per buffer, in the order the planner sends them. -export function firstEditTransport({ fetcher, caps, repair } = {}) { - return async (req) => firstEditVerdict( - await submitSession( - SESSION_FIRST_EDIT, - firstEditBody(req.key.repository, req.key, req), - fetcher, caps, repair)); -} - -// ---- outcomes -------------------------------------------------------------- - -function line(host, text) { - host.appendChild(el("div", "swb-cline", text)); -} - -function yesNo(value) { - return value ? "yes" : "no"; -} - -// What the engine reported, rendered VERBATIM per verb. Every one of these fields -// is a response key the route contract declares; nothing is inferred, and a field -// the response omits is simply not shown. -function renderLanded(host, affordance, result) { - if (affordance === SESSION_EDIT) { - line(host, "document: " + result.document); - line(host, "session branch: " + result.ref); - line(host, "commit: " + result.commit); - line(host, "gate-action record: " + result.record); - return; - } - if (affordance === SESSION_ABANDON) { - line(host, "session branch: " + result.ref); - line(host, "reason: " + result.reason); - line(host, "torn down: " + (result.torn_down || []).join(", ")); - line(host, "branch retained: " + yesNo(result.branch_retained)); - line(host, "gate-action record: " + result.record); - return; - } - if (affordance === SESSION_SHARE) { - if (result.shared === false) { - // §12.3's honest answer, reported as the outcome it is rather than as a - // failure: nothing was pushed, and the engine says why. - line(host, result.reason); - return; - } - line(host, "pushed ref: " + result.pushed_ref); - line(host, "revision: " + result.revision); - line(host, "threads committed: " - + ((result.threads || []).join(", ") || "(none were uncommitted)")); - line(host, "gate-action record: " + result.record - + " (" + result.record_resident + "-resident)"); - line(host, result.promotion); - return; - } - if (result.merged) { - // the ENDING, not a save: the branch was already merged, so there is no pull - // request to report and no record was written (Phase 7 note 4) - line(host, "session branch: " + result.ref + " — MERGED, so the session ENDED"); - line(host, "torn down: " + (result.torn_down || []).join(", ")); - line(host, "branch deleted: " + yesNo(result.branch_deleted)); - return; - } - line(host, "pull request: " + result.pull_request); - line(host, result.updated - ? "an open pull request already existed — it was UPDATED, never duplicated" - : "opened into the existing Merge-Master ritual"); - line(host, "session branch: " + result.ref); - line(host, "gate-action record: " + result.record); -} - -// Whether this outcome ENDED the session, and how. `merged: true` on a save is -// the merge ending (FR-033); an abandon is the other one (FR-021). -function endingOf(affordance, result) { - if (affordance === SESSION_ABANDON) return "abandoned"; - if (affordance === SESSION_SAVE && result && result.merged) return "merged"; - return null; -} - -// The LANDED box, built in ONE place so the live outcome and the ending's replay -// (below) can never drift apart — the same reason the `ended` overlay itself is -// one map rather than a re-derivation per call site. -function landedBox(affordance, result, ending) { - const verb = SESSION_VERBS[affordance]; - const box = el("div", "swb-clanded"); - box.appendChild(el("div", "swb-ch", ending - ? verb + " ✓ — the session ENDED (" + ending + ")" - : verb + " ✓ — recorded gate dispatch")); - renderLanded(box, affordance, result); - if (result.hint) box.appendChild(el("div", "swb-cnote", result.hint)); - for (const note of result.notes || []) box.appendChild(el("div", "swb-cnote", note)); - // FR-042 / D19: a session that opened without its notebook is a NOTICE, not an - // error — the session is live and fully usable - if (result.notebook_notice) { - box.appendChild(el("div", "swb-cnote swb-notice", - "notice: " + result.notebook_notice)); - } - if (result.view_notice) { - box.appendChild(el("div", "swb-cnote swb-notice", - "notice: " + result.view_notice)); - } - return box; -} - -async function renderOutcome(host, affordance, result, opts) { - const o = opts || {}; - host.innerHTML = ""; - const verb = SESSION_VERBS[affordance]; - if (!(result && result.ok)) { - const refused = el("div", "swb-crefused"); - refused.appendChild(el("div", "swb-ch", "refused ✕")); - // the engine's refusal reaches the human VERBATIM (the route's response - // discipline) — never a paraphrase, and never swallowed - refused.appendChild(el("div", "swb-cline", - (result && result.message) || (verb + " was refused"))); - host.appendChild(refused); - panelEntry("refused", (result && result.message) || (verb + " refused")); - return null; - } - const ending = endingOf(affordance, result); - const box = landedBox(affordance, result, ending); - host.appendChild(box); - panelEntry("ok", verb + " " + result.ref + (ending ? " → session " + ending : "")); - if (ending) { - ended.set(String(result.ref), ending); - // remembered BEFORE the re-render below, which rebuilds `host`'s ancestor - endedReports.set(String(result.ref), { affordance, result, ending }); - if (o.onSessionEnded) { - try { - await o.onSessionEnded(result, ending); - } catch { - result.view_notice = "the session ended, but the main view could not " + - "be loaded; reload the dashboard"; - box.appendChild(el("div", "swb-cnote swb-notice", - "notice: " + result.view_notice)); - } - } - } else if (o.onSessionChanged) { - o.onSessionChanged(result); - } - return ending; -} - -// ---- the gate-off rendering (FR-046) --------------------------------------- -// -// Every affordance as the REAL `cli.py gate ` invocation for this tile, -// selectable and copyable. Defined ABOVE the mount so the early return below -// reads in the order it executes, and deliberately holding no reference to the -// request helper: with the gate off there is no path from this page to a write. - -function descriptorBox(host, label, note, command) { - const box = el("div", "swb-cdescriptor"); - box.appendChild(el("div", "swb-clabel", label)); - box.appendChild(el("div", "swb-cnote", note)); - const cmd = el("code", "swb-ccmd", command); - cmd.tabIndex = 0; - box.appendChild(cmd); - host.appendChild(box); - return box; -} - -// The notebook re-sync descriptor, rendered in BOTH postures (spec C10): the -// dry-run line first — the script prints the op list for a human to eyeball — -// then the explicit apply form. -function renderNotebookDescriptor(host, ctx) { - const posture = ctx.posture || {}; - const branch = posture.branch; - const box = el("div", "swb-cdescriptor"); - box.appendChild(el("div", "swb-clabel", SESSION_LABELS[SESSION_REFRESH_NOTEBOOK])); - // WHY THERE MAY BE NO BRANCH HERE (PR #49 second-review finding 18). This - // command re-syncs a notebook FROM a worktree, so a branch that is another - // tile's session must never reach it: it would re-sync that tile's session - // notebook from that tile's worktree. The posture withholds an ambiguous ref, and - // this says so rather than silently offering the `` placeholder. - box.appendChild(el("div", "swb-cnote", branch - ? "the session notebook is re-synced from the WORKTREE by the sync script — " - + "not a gate verb and not a dashboard route, so it is a copyable command " - + "in every posture. Dry-run first, then apply:" - : (posture.ambiguousRef - ? "no ref can be filled in here: " + posture.ambiguousRef + " is in this " - + "tile's ordinal family AND is tile " + posture.ambiguousOwner + "'s own " - + "session branch, so re-syncing it could re-sync ANOTHER tile's session " - + "notebook from another tile's worktree. Resolve the ambiguity first (end " - + "that session from the tile that owns it, or rename one tile):" - : "no session branch to re-sync yet — the first recorded write opens one, " - + "and its notebook is created with it:"))); - for (const apply of [false, true]) { - const cmd = el("code", "swb-ccmd", notebookRefreshCommand({ branch, apply })); - cmd.tabIndex = 0; - box.appendChild(cmd); - } - host.appendChild(box); - return box; -} - -function renderSessionDescriptors(host, ctx, opts) { - const o = opts || {}; - const wrap = el("div", "swb-sessiondescriptors"); - wrap.appendChild(el("div", "swb-cnote", - "this surface has no session authority (read-only host) — run these in your " - + "own checkout, where the authority and the identity live:")); - for (const affordance of SESSION_AFFORDANCES) { - if (affordance === SESSION_REFRESH_NOTEBOOK) { - renderNotebookDescriptor(wrap, ctx); - continue; - } - const command = sessionCommand(affordance, { scope: ctx.scope, actor: o.actor }); - if (!command) continue; - descriptorBox(wrap, SESSION_LABELS[affordance], - "the " + SESSION_VERBS[affordance] + " verb, filled in for this tile:", - command); - } - host.appendChild(wrap); - return wrap; -} - -// ---- the live forms -------------------------------------------------------- - -function field(host, label, value, opts) { - const o = opts || {}; - const row = el("label", "swb-cfield"); - row.appendChild(el("span", "swb-clabel", label)); - const input = o.multiline - ? document.createElement("textarea") - : document.createElement("input"); - if (!o.multiline) input.type = "text"; - if (o.multiline) input.rows = 12; - input.value = value == null ? "" : String(value); - input.setAttribute("aria-label", label); - if (o.placeholder) input.setAttribute("placeholder", o.placeholder); - row.appendChild(input); - host.appendChild(row); - return input; -} - -function documentPicker(host, ctx) { - const row = el("label", "swb-cfield"); - row.appendChild(el("span", "swb-clabel", "Document")); - const select = document.createElement("select"); - select.setAttribute("aria-label", "the document to rewrite"); - for (const path of ctx.documents || []) { - const option = document.createElement("option"); - option.value = path; - option.textContent = path; - select.appendChild(option); - } - row.appendChild(select); - host.appendChild(row); - return select; -} - -// The per-affordance form. One shape, one submit path, so the three verbs cannot -// grow three postures. Every field is the request body's own — `sessionRequest` -// in the pure model owns the wire spelling. -function renderForm(host, affordance, ctx, opts) { - const o = opts || {}; - host.innerHTML = ""; - const form = el("div", "swb-cform"); - form.appendChild(el("div", "swb-ch", SESSION_LABELS[affordance])); - const values = {}; - let picker = null; - let content = null; - if (affordance === SESSION_EDIT) { - form.appendChild(el("div", "swb-cnote", - "the replacement is the document's WHOLE text: this verb rewrites, it never " - + "patches, and an empty replacement is refused as a delete in disguise. " - + "Read the current text in the viewer beside this panel first.")); - picker = documentPicker(form, ctx); - content = field(form, "Replacement", "", - { multiline: true, placeholder: "the document's full new text" }); - } else if (affordance === SESSION_SHARE) { - form.appendChild(el("div", "swb-cnote", - "commits this session's uncommitted thread sidecars and PUSHES the branch, " - + "so a colleague can fetch it and resume the same session — its documents " - + "and its threads. It opens NO pull request, requests no review, and " - + "merges and approves nothing. Until you press this, the session's threads " - + "have never left this machine. Invoked with nothing new, it says so " - + "rather than pushing again.")); - values.notes = field(form, "Note", "", - { placeholder: "optional — recorded on the gate-action record (why you are " - + "handing this over)" }); - } else if (affordance === SESSION_SAVE) { - // WHAT BLANK MEANS, honestly (PR #49 second-review finding R2-13). It used to - // say "left blank, the engine names the branch and its tile" full stop, while - // a second save with the form blank REPLACED whatever a human had written. - // Blank now means what this text says on both paths: defaults on the FIRST - // save, unchanged on every later one. - form.appendChild(el("div", "swb-cnote", - "pushes this session's branch and opens (or updates) its pull request into " - + "the existing Merge-Master ritual. It merges, approves, and reviews " - + "nothing. Title and body are optional: on the FIRST save, left blank, the " - + "engine names the branch and its tile and carries the " - + "merge-commit-never-squash notice — on a LATER save, left blank, the pull " - + "request's existing title and body are left exactly as they are. A save " - + "never overwrites reviewer-facing text you wrote.")); - values.title = field(form, "Title", "", - { placeholder: "optional — blank keeps the existing title (the first save " - + "names the branch and its tile)" }); - values.body = field(form, "Body", "", - { multiline: true, - placeholder: "optional — blank keeps the existing body (the first save " - + "carries D18's notice)" }); - } else { - form.appendChild(el("div", "swb-cnote", - "ends this session without saving. The reason is REQUIRED and durable, " - + "exactly as a demotion's is; the branch and any pushed history SURVIVE, " - + "and deleting it later is a separate, human-invoked verb.")); - values.reason = field(form, "Reason", "", - { placeholder: "the durable why this exploration stopped" }); - } - - const result = el("div", "swb-cresult"); - result.setAttribute("aria-live", "polite"); - const bar = el("div", "swb-cactions"); - const submit = el("button", "cbtn", SESSION_VERBS[affordance]); - submit.type = "button"; - submit.title = "EXECUTES via the local gate route (actor: " + (o.actor || "local") + ")"; - const cancel = el("button", "cbtn", "cancel"); - cancel.type = "button"; - cancel.addEventListener("click", () => { host.innerHTML = ""; }); - - submit.addEventListener("click", async () => { - const body = sessionRequest(affordance, ctx.scope, { - // the repository the page is reading, carried so the route can refuse a - // session write it cannot honour (review finding 8) - repository: ctx.posture ? ctx.posture.repository : null, - document: picker ? picker.value : null, - content: content ? content.value : null, - title: values.title ? values.title.value : null, - body: values.body ? values.body.value : null, - reason: values.reason ? values.reason.value : null, - notes: values.notes ? values.notes.value : null, - }); - if (!body) { - panelEntry("refused", - "this tile resolves no session scope, so no session verb can address it"); - return; - } - // The same running-state the create grew (Brett, 2026-08-10: "i pressed - // create twice") and for the same reason: these verbs commit, push and - // regenerate — `open-pr` reaches a REMOTE — so the wait is real, and a - // button that only greys out invites a second press whose refusal reads as - // the outcome of the first. - const label = submit.textContent; - submit.disabled = true; - submit.textContent = label + "…"; - let payload; - try { - payload = await submitSession(affordance, body, o.fetcher, o.caps, - o.repair); - } finally { - submit.textContent = label; - } - const ending = await renderOutcome(result, affordance, payload, o); - // a refusal is retriable in place; a landed action is done, and an ENDING - // takes the whole affordance set with it - if (!(payload && payload.ok)) submit.disabled = false; - if (ending && o.onRerender) o.onRerender(); - }); - - bar.append(submit, cancel); - form.appendChild(bar); - form.appendChild(result); - // Escape closes the FORM, not the whole workbench - form.addEventListener("keydown", (ev) => { - if (ev.key === "Escape") { ev.stopPropagation(); host.innerHTML = ""; } - }); - host.appendChild(form); -} - -// ---- the mount ------------------------------------------------------------- - -// Mount the session affordance row into `host`. -// -// `ctx`: { scope, posture, documents } — the tile's scope (the session identity -// every request carries), the posture derived in the transport-free model, and -// the scope's document paths for the edit picker. -// `opts`: { caps, actor, fetcher, repair, onSessionEnded, onSessionChanged, -// onRerender } — `repair` being the shell's console-token re-read, handed -// straight to `submitSession`. -// -// The FIRST statement is the capability branch, and it RETURNS: gate-off, no live -// control is constructed at all (FR-046). The capability is asked exactly once, -// through the pure model's one derivation, so no branch of this file can reach a -// different verdict than the posture indicator shows. -export function mountSessionAffordances(host, ctx, opts) { - const o = opts || {}; - // FR-048 FIRST: a plane that declares `session: false` is the HOSTED plane and - // exposes NOTHING of this capability — not a live control, and not a - // descriptor naming the verb and the branch (review finding 14). - if (sessionSurfaceHidden(o.caps)) return null; - if (!sessionActionsLive(o.caps)) return renderSessionDescriptors(host, ctx, o); - const wrap = el("div", "swb-sessionactions"); - const slot = el("div", "swb-cslot"); - const ending = ctx.posture ? sessionEnding(ctx.posture.branch) : null; - for (const affordance of SESSION_AFFORDANCES) { - if (affordance === SESSION_REFRESH_NOTEBOOK) continue; // descriptor-only, below - const button = el("button", "cbtn swb-sessionbtn", SESSION_LABELS[affordance]); - button.type = "button"; - button.title = "the human-only " + SESSION_VERBS[affordance] + - " gate verb, recorded (actor: " + (o.actor || "local") + ")"; - if (ending) { - // the session ended during this page's life: say so rather than offering a - // verb that can only be refused - button.disabled = true; - button.title = "this tile's session " + ending + - " — reload to see the tile's current state"; - } - button.addEventListener("click", () => renderForm(slot, affordance, ctx, o)); - wrap.appendChild(button); - } - host.appendChild(wrap); - // DESCRIPTOR-ONLY in this posture too (spec C10) — it is not a gate verb - renderNotebookDescriptor(host, ctx); - host.appendChild(slot); - // THE ENDING'S REPORT, REPLAYED (T088). The ending re-renders this row, and the - // re-render destroyed the slot the outcome had just been written into — so the - // engine's own account of the teardown is put back into the slot this call just - // built, verbatim and through the SAME renderer. A reload replaces it with the - // server's answer, exactly like every other page-lifetime overlay here. - if (ending) { - const report = endedReports.get(String(ctx.posture && ctx.posture.branch)); - if (report) slot.appendChild(landedBox(report.affordance, report.result, - report.ending)); - } - return wrap; -} diff --git a/src/opendox/web/views/view_extension.js b/src/opendox/web/views/view_extension.js index 189b89a1..d6459459 100644 --- a/src/opendox/web/views/view_extension.js +++ b/src/opendox/web/views/view_extension.js @@ -87,6 +87,18 @@ export const REGIONS = { "dispose-intent": "shell", "lens-gate": "shell", "repo-projects": "shell", + // SLICE S5's THREE. `page-overlay` is RULED Q8 (openxFactory#656 comment + // 5648049748): "a fourth `shell` region, `page-overlay`, is the declared host + // for page-level panels (dispose.js's refusal panel); `document.body` is never + // a contract surface." The SHELL builds this host — `app.js` does, because + // `index.html` is a `moved_verbatim` carve row and an added element is in none + // of its declared edit classes — and hands it to the binding, which is exactly + // what "shell" means here. `workbench-create` and `workbench-session` are the + // staging workbench's two caller-built hosts, added with the bindings that + // mount into them on slice S4's own precedent (`lens-gate`, `repo-projects`). + "page-overlay": "shell", + "workbench-create": "shell", + "workbench-session": "shell", }; export const MANIFEST_KIND = "opendox.view-manifest"; @@ -159,6 +171,28 @@ export function viewBinding(spec) { + JSON.stringify(b.view_class) + ", not one of " + VIEW_CLASSES.join("/") + " (§ 2.1: A openDox core, B the gate loop, C a stage-named region)"); } + // RULED Q2 (openxFactory#656 comment 5648049748): "a binding's contract is + // its module NAMESPACE, DECLARED as an `exports` tuple: every export the + // shell may reach is listed on the binding and validated the way `entry` is; + // an undeclared reach (today `isGateBearing`, app.js:939) is a refusal." + // Empty means `entry` alone — the pre-Q2 contract every core-arm binding + // still declares. Non-empty must CONTAIN `entry`: the mount is the first + // member of the namespace, and a tuple that omitted it would declare a + // contract its own entry breaks. + const exported = b.exports === undefined ? [] : b.exports; + if (!Array.isArray(exported) + || exported.some((name) => typeof name !== "string" + || !/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(name) || name.startsWith("__"))) { + refuse("view binding " + JSON.stringify(b.id) + " declares exports " + + JSON.stringify(exported) + ": every entry is the NAME of an export on " + + "the binding's module, held to the same grammar `entry` is"); + } + if (exported.length && !exported.includes(b.entry)) { + refuse("view binding " + JSON.stringify(b.id) + " declares exports " + + JSON.stringify(exported) + " that do not include its own entry " + + JSON.stringify(b.entry) + ": RULED Q2 makes the tuple the WHOLE " + + "namespace the shell may reach, and the mount is the first member of it."); + } const routes = b.routes === undefined ? [] : b.routes; if (!Array.isArray(routes) || routes.some((r) => typeof r !== "string" || !r.startsWith("/"))) { refuse("view binding " + JSON.stringify(b.id) + " declares routes " @@ -189,6 +223,7 @@ export function viewBinding(spec) { module: b.module, entry: b.entry, view_class: b.view_class, + exports: Object.freeze(exported.slice()), routes: Object.freeze(routes.slice()), requires: Object.freeze(requires.slice()), optional, @@ -402,6 +437,66 @@ export function manifestRoutes(capabilities) { return routes; } +// ---- RULED Q4: `requires` NAMES DOTTED PATHS INTO THE /capabilities PAYLOAD -- +// +// openxFactory#656 comment 5648049748, Brett Heap, 2026-09-12: "`requires` +// names DOTTED PATHS into the `/capabilities` payload; unmet + `optional: true` +// renders the region empty with a NAMED reason; unmet + required REFUSES, +// naming the binding, the path and the probed value." +// +// THIS IS THE OBLIGATION openDox-spec § 5.1 NAMES MOST DIRECTLY, and until this +// slice it was the one with no code behind it: the field was declared +// (`view_extension.py`:248-251), validated, carried into the manifest and +// mirrored here, and NO LINE OF EITHER HALF READ IT — so "a binding declaring +// `requires` is declaring an intention the shell does not act on" +// (openXdox-spec `docs/gate-loop-view-contract.md` § 4.4 @ d73767b7). These +// three functions are the act. +// +// A MISSING PAYLOAD IS AN UNMET REQUIREMENT, NOT AN ERROR. `probeCapabilities()` +// degrades a failed probe to `{ actions: { notebook: false } }`, and a static +// served image 404s the route entirely — so `undefined` at the end of the path +// is the honest answer "this plane does not offer it", which is exactly what an +// unmet requirement is. Only a TRUTHY value meets one; `false`, `null`, `0` and +// `""` are all "off", because every capability this payload carries is a +// verdict and a falsy verdict is a no. +export function probeCapabilityPath(capabilities, path) { + let cursor = capabilities; + for (const segment of String(path).split(".")) { + if (cursor === null || cursor === undefined || typeof cursor !== "object") { + return undefined; + } + cursor = cursor[segment]; + } + return cursor; +} + +// The FIRST unmet requirement of a binding, or null. First and not all, for +// `_route_ownership_breach`'s reason: the caller does nothing different for a +// second one, and naming one path a human can go and look at beats naming +// three. +export function unmetRequirement(binding, capabilities) { + for (const path of (binding && binding.requires) || []) { + const value = probeCapabilityPath(capabilities, path); + if (!value) return { path, value }; + } + return null; +} + +// The sentence a human reads when a binding's `requires` is unmet — the refusal +// text openDox-spec § 5.1 asks this seam for and § 5 of the contract note +// records as "there is none". It names the binding, the path and the PROBED +// VALUE, because "unmet" and "the payload does not carry that key at all" are +// different facts for the column debugging its own contribution. +export function requirementRefusal(binding, unmet) { + return "view binding " + JSON.stringify(binding.id) + " requires " + + JSON.stringify(unmet.path) + ", which this plane's /capabilities payload " + + "answers as " + JSON.stringify(unmet.value === undefined ? null : unmet.value) + + (unmet.value === undefined ? " (the path is not carried at all)" : "") + + ". A binding that is correct to be absent declares `optional: true`; a " + + "required one refuses here rather than mounting a panel whose verbs can " + + "only be refused."; +} + // An OPTIONAL reach: the binding, or null. This is `consumer_reach`'s posture // in the browser — a reach into a column that may not be installed is LATE and // NAMED, and the caller decides what absence means. § 6 Q5's intent chips and @@ -438,9 +533,23 @@ export function requireView(bindings, id) { // // The specifier is resolved against the BUNDLE ROOT (`./views/gate.js` is what // `app.js` would have written), not against this module's own folder. -export async function resolveView(bindings, id) { +export async function resolveView(bindings, id, options) { const binding = lookupView(bindings, id); if (!binding) return null; + // RULED Q4, at the ONE place every named reader already goes through. A + // caller that passes `capabilities` gets the requirement evaluated here: + // an unmet requirement on an OPTIONAL binding answers `null`, which every + // reader in this shell already reads as "the column that supplies it is not + // installed"; on a REQUIRED one it refuses, naming the binding, the path and + // the probed value. A caller that passes none is asking for the binding and + // not for the verdict — `collectViewBindings`' own tests do exactly that. + if (options && "capabilities" in options) { + const unmet = unmetRequirement(binding, options.capabilities); + if (unmet) { + if (!binding.optional) refuse(requirementRefusal(binding, unmet)); + return null; + } + } const bundleRoot = new URL("../", import.meta.url); // A REJECTED IMPORT IS A REFUSAL TOO, and one this seam names rather than // lets pass through raw (Copilot, PR #14): a missing file, a syntax error @@ -481,7 +590,67 @@ export async function resolveView(bindings, id) { + "function. An entry is the export that MOUNTS the panel; a binding " + "that cannot be mounted must not look registered."); } - return { binding, exports }; + // EVERY DECLARED EXPORT IS CHECKED THE WAY THE ENTRY IS (RULED Q2). A binding + // that names an export its module does not have is a binding the shell would + // reach for and find `undefined` in — the "dangling import a thousand lines + // from the call" this seam replaces, one field over. + for (const name of binding.exports) { + if (!(name in exports)) { + refuse("view binding " + JSON.stringify(binding.id) + " declares export " + + JSON.stringify(name) + ", which " + JSON.stringify(binding.module) + + " does not export. A binding whose declared namespace is not the " + + "module's namespace must not look registered."); + } + } + return { binding, exports: declaredNamespace(binding, exports) }; +} + +// THE DECLARED NAMESPACE — RULED Q2's refusal half. `resolveView` used to hand +// back the module's WHOLE namespace, and `app.js` read `isGateBearing` off it, +// an export the binding never declared and this seam never validated. The +// namespace a caller receives is now bounded by the declaration: a reach for a +// name the binding did not declare REFUSES, naming both, instead of answering +// `undefined` and failing inside whatever tried to call it. +// +// A binding with an EMPTY `exports` keeps the pre-Q2 contract — `entry` alone — +// which is what every core-arm binding declares, because the core arm's modules +// are imported statically by the shell that owns them. +// +// SYMBOLS AND `then` PASS THROUGH AS ABSENT rather than refusing: a Proxy is +// probed for `Symbol.toStringTag` by `String()`, and any object returned from +// an async function is probed for `then` by the await that receives it. A +// refusal from either would be this seam refusing the language rather than a +// caller. +function declaredNamespace(binding, exports) { + const allowed = new Set(binding.exports.length + ? binding.exports : [binding.entry]); + return new Proxy(exports, { + get(target, property, receiver) { + if (typeof property === "symbol" || property === "then") { + return Reflect.get(target, property, receiver); + } + if (!allowed.has(property)) { + refuse("view binding " + JSON.stringify(binding.id) + " does not " + + "declare an export named " + JSON.stringify(String(property)) + + "; it declares " + JSON.stringify([...allowed]) + ". RULED Q2 " + + "(openxFactory#656 comment 5648049748): a binding's contract is its " + + "module NAMESPACE, DECLARED — an undeclared reach is a refusal."); + } + return Reflect.get(target, property, receiver); + }, + has(target, property) { + if (typeof property === "symbol") return Reflect.has(target, property); + return allowed.has(property) && Reflect.has(target, property); + }, + ownKeys(target) { + return Reflect.ownKeys(target).filter( + (key) => typeof key === "symbol" || allowed.has(key)); + }, + getOwnPropertyDescriptor(target, property) { + if (typeof property !== "symbol" && !allowed.has(property)) return undefined; + return Reflect.getOwnPropertyDescriptor(target, property); + }, + }); } // The element a "dom" region mounts into: the shell element whose `id` is the @@ -497,3 +666,92 @@ export function regionHost(binding, doc) { } return (doc || document).getElementById(binding.region); } + + +// ---- RULED Q1: THE SHELL MOUNTS CONTRIBUTED BINDINGS GENERICALLY ----------- +// +// openxFactory#656 comment 5648044785, Brett Heap, 2026-09-12: "the shell +// MOUNTS contributed bindings generically: one mount pass over every +// contributed binding whose region is a `dom` region; the three `shell` regions +// stay caller-driven (the gate bar's pattern)." +// +// WHAT IT REPLACES. Nothing generic mounted a contributed binding: the tab +// router mounts only bindings that declared a `control`, a contributed entry +// declaring one is refused where the payload is read, and the one +// contributed-shaped mount was `resolveView(views, "gate.bar")` BY ID at a +// single openDox call site. So "a column can contribute a binding today and +// have nothing ever call it" — and every contributed panel needed an openDox +// edit to become reachable, "which is the fork the seam was drawn to prevent". +// +// WHY `shell` REGIONS ARE NOT IN THE PASS, and it is not an omission: a `shell` +// region has NO STANDING ELEMENT (`regionHost` refuses to look for one), so the +// host does not exist until the caller that builds it builds it. The viewer +// builds the gate bar's host per artifact; the workbench builds its two. A pass +// that tried to mount them would be mounting into nothing, which is the defect +// this seam names as "a declared panel silently unmounted". +// +// THE SIGNATURE IS RULED Q3's — `mount(host, snapshot, ctx)` — and it is the +// only one this pass knows. A contributed binding that took anything else would +// be teaching the shell a second shape, which is the coupling the registry +// exists to end. +// +// WHAT IT RETURNS: one record per contributed binding it considered, so a +// caller can assert what mounted, what was skipped and why. `mounted` is the +// entry's own return value (a controller, an element, or undefined) — the pass +// does not interpret it. +export async function mountContributedViews(bindings, snapshot, ctx, options) { + const o = options || {}; + const doc = o.document || (typeof document === "undefined" ? null : document); + const capabilities = o.capabilities; + const results = []; + for (const binding of bindings || []) { + // The CORE arm is the shell's own and mounts through the tab router; a core + // binding is the one that carries a `mount` function, which a contributed + // one can never have (`contributedViewBindings` refuses the field where the + // payload is read). + if (typeof binding.mount === "function" || binding.control) continue; + if (REGIONS[binding.region] !== "dom") continue; + const unmet = capabilities === undefined + ? null : unmetRequirement(binding, capabilities); + if (unmet) { + // RULED Q4: "unmet + `optional: true` renders the region empty with a + // NAMED reason; unmet + required REFUSES." The reason is written INTO the + // region, because a human looking at an empty panel is the person who + // needs it — not the console. + if (!binding.optional) refuse(requirementRefusal(binding, unmet)); + const host = doc ? regionHost(binding, doc) : null; + if (host) host.appendChild(regionReason(binding, unmet, doc)); + results.push({ binding, mounted: null, skipped: "requires", unmet }); + continue; + } + const host = doc ? regionHost(binding, doc) : null; + if (!host) { + // A `dom` region the shell declares and this document does not carry — + // an older served `index.html`, or a probe with a partial document. Named, + // never silent, and never a throw: the shell renders without the panel. + results.push({ binding, mounted: null, skipped: "no-host" }); + continue; + } + const resolved = await resolveView(bindings, binding.id); + if (!resolved) { + results.push({ binding, mounted: null, skipped: "absent" }); + continue; + } + results.push({ + binding, + mounted: resolved.exports[binding.entry](host, snapshot, ctx), + skipped: null, + }); + } + return results; +} + +// The NAMED REASON an unmet optional binding leaves in its region (RULED Q4). +// `textContent` only — the value came off a payload this shell did not write. +export function regionReason(binding, unmet, doc) { + const node = (doc || document).createElement("p"); + node.className = "viewrefusal"; + node.setAttribute("data-view", binding.id); + node.textContent = requirementRefusal(binding, unmet); + return node; +} diff --git a/src/opendox/web/views/wheel.js b/src/opendox/web/views/wheel.js index 91fd7b3c..b2adbecc 100644 --- a/src/opendox/web/views/wheel.js +++ b/src/opendox/web/views/wheel.js @@ -70,8 +70,42 @@ import { actionRowIsStale, primaryFragmentPath, fragmentSummary, packetGroups, healthIndicator, healthBlock, jumpRepository } from "./wheel-model.js"; import { el } from "./helpers.js"; -import { appliedOutcome, commissionedVerb, commissionedWorkflow, gateCapable, - mountDisposeTray, mountProposeButton, mountWheelVerb, panelEntry } from "./dispose.js"; +// THE DISPOSE COLUMN IS NOT IMPORTED HERE ANY MORE (§ 3.4 slice S5). +// +// This was `import { appliedOutcome, commissionedVerb, commissionedWorkflow, +// gateCapable, mountDisposeTray, mountProposeButton, mountWheelVerb, panelEntry } +// from ./dispose.js` — a CLASS-C file importing a CLASS-B module, one of the +// four breaches openDox-spec `docs/front-end-package-boundary.md` § 4.5 +// assertion 3 measures, and the reason a student install failed to LOAD rather +// than rendering without the gate loop. `views/dispose.js` has left this bundle: +// it is openXdox's package data now, contributed as the `gate.dispose` binding +// (RULED Q5, openxFactory#656 comment `5648044785`). +// +// The eight names arrive through the REGISTRY instead: `app.js` resolves the +// binding once per render and hands its DECLARED NAMESPACE (RULED Q2) down as +// `ctx.dispose`, which `renderWheel` installs below. Null — no gate column +// registered — is `NO_DISPOSE_COLUMN`, whose `gateCapable()` answers false, so +// every affordance this file gates on the capability is simply not offered and +// nothing here needs a second branch. That is § 4.2's "late, named and +// refusable" in the browser, and it is the shape `views/intent-binding.js` +// already established at slice S2. +const NO_DISPOSE_COLUMN = Object.freeze({ + appliedOutcome: () => null, + commissionedVerb: () => null, + commissionedWorkflow: () => null, + gateCapable: () => false, + mountDisposeTray: () => null, + mountProposeButton: () => null, + mountWheelVerb: () => null, + panelEntry: () => null, +}); + +//: The column this render was handed, installed by `renderWheel` before any +//: mounter can fire. Module-level because `ACTION_MOUNTERS` below is a +//: module-level table of arrow functions the action row looks verbs up in — +//: threading a per-render object through it would mean giving every mounter a +//: ninth parameter that only exists to be forwarded. +let disposeColumn = NO_DISPOSE_COLUMN; import { feedActor, intentCapable, refusalLine, startIntentFeed, statesByTarget } from "./intent-binding.js"; import { notebookCapable } from "./notebook.js"; @@ -133,17 +167,17 @@ const summaryCache = new Map(); // /source pass-through above, parsed by the pure `landedFromDeltas`; `packet` // opens the same kind of flyout straight from snapshot data. const ACTION_MOUNTERS = { - propose: (row, item, opts) => mountProposeButton(row, item, { ...opts, compact: true }), + propose: (row, item, opts) => disposeColumn.mountProposeButton(row, item, { ...opts, compact: true }), // 011 add-wheel-action-verbs: one generic mounter, four verbs. `actionId` is // the verb, so the mounter needs no per-verb branch here. "promote-to-staging": (row, item, opts) => - mountWheelVerb(row, item, { ...opts, verb: "promote-to-staging" }), + disposeColumn.mountWheelVerb(row, item, { ...opts, verb: "promote-to-staging" }), "research-brief": (row, item, opts) => - mountWheelVerb(row, item, { ...opts, verb: "research-brief" }), + disposeColumn.mountWheelVerb(row, item, { ...opts, verb: "research-brief" }), "derive-possibles": (row, item, opts) => - mountWheelVerb(row, item, { ...opts, verb: "derive-possibles" }), + disposeColumn.mountWheelVerb(row, item, { ...opts, verb: "derive-possibles" }), demote: (row, item, opts) => - mountWheelVerb(row, item, { ...opts, verb: "demote" }), + disposeColumn.mountWheelVerb(row, item, { ...opts, verb: "demote" }), // add-project-merged-projection (D10): the composed view's ONE verb — jump // to the tile's member repository (store the key + reload, the ratified // selector posture). Pure navigation; nothing is recorded or persisted. @@ -356,6 +390,11 @@ function threadPath(x0, y0, x1, y1) { } export function renderWheel(root, snapshot, ctx) { + // THE CONTRIBUTED DISPOSE COLUMN, installed before anything can mount. The + // shell resolved the `gate.dispose` binding and handed its declared namespace + // down; absent, the null column above makes every gate affordance unoffered + // rather than undefined. + disposeColumn = ctx?.dispose || NO_DISPOSE_COLUMN; const signal = ctx?.signal; const caps = ctx?.caps || null; // Cross-view navigation callbacks from the app shell (app.js): openDoc(path, @@ -424,7 +463,7 @@ export function renderWheel(root, snapshot, ctx) { actor: feedActor(caps), // A stalled row is NOT a refusal - `refusalLine` already writes "not // started" for it, and the panel's label has to agree with its own text. - onRefusal: (rec) => panelEntry(rec.state === "stalled" ? "stalled" : "refused", + onRefusal: (rec) => disposeColumn.panelEntry(rec.state === "stalled" ? "stalled" : "refused", refusalLine(rec)), }) : null; // target id -> the newest feed state for it, rebuilt ONCE per update so the @@ -1171,7 +1210,7 @@ export function renderWheel(root, snapshot, ctx) { }; function sessionActOn(wheelKey, itemId) { for (const verb of WHEEL_VERBS_BY_COLUMN[wheelKey] || []) { - if (commissionedVerb(verb, itemId)) return verb; + if (disposeColumn.commissionedVerb(verb, itemId)) return verb; } return null; } @@ -1182,7 +1221,7 @@ export function renderWheel(root, snapshot, ctx) { if (!isExpanded) { if (existing) existing.remove(); return; } const item = w.items[idx]; const env = { - gate: gateCapable(caps), + gate: disposeColumn.gateCapable(caps), // add-project-merged-projection (D10): a composed render's tiles offer // the open-in-repo jump and nothing gate-bearing (the app shell also // strips the acting capabilities, so `gate` above is already false). @@ -1192,8 +1231,8 @@ export function renderWheel(root, snapshot, ctx) { // boolean and means "THIS verb's act is recorded for this tile this // session". Retirement REMOVES the row (there is no disabled control // left for a keyboard user to meet). - commissioned: (verbId) => !!commissionedVerb(verbId, item.id), - applied: appliedOutcome(item.id), + commissioned: (verbId) => !!disposeColumn.commissionedVerb(verbId, item.id), + applied: disposeColumn.appliedOutcome(item.id), // the notebook action's OWN capability (the same /capabilities probe, a // different flag): it is live only on a loopback local backend with nlm. notebook: notebookCapable(caps), @@ -1425,7 +1464,7 @@ export function renderWheel(root, snapshot, ctx) { // demotion is visible without touching the snapshot (FR-034). View state // only: nothing is persisted and a reload clears it. const appliedVerdict = w.items[idx] - ? ((w.key === "possibles" ? appliedOutcome(w.items[idx].id) : null) + ? ((w.key === "possibles" ? disposeColumn.appliedOutcome(w.items[idx].id) : null) || sessionActOn(w.key, w.items[idx].id)) : null; const isExpanded = !!w.items[idx] && isExpandedTile(expanded, w.key, idx); @@ -1495,15 +1534,15 @@ export function renderWheel(root, snapshot, ctx) { // through intent emission. The two capabilities are mutually exclusive by // construction (serve.py: `intent = not loopback`), so exactly one // transport is ever handed to the tray. - if (key === "possibles" && focus && (gateCapable(caps) || intentCapable(caps))) { + if (key === "possibles" && focus && (disposeColumn.gateCapable(caps) || intentCapable(caps))) { const item = wheelByKey("possibles").items[focus.i]; - const hosted = !gateCapable(caps) && intentCapable(caps); + const hosted = !disposeColumn.gateCapable(caps) && intentCapable(caps); // The session-local applied overlay belongs to the LOCAL executing path; // hosted decisions are reported by the feed, so it never suppresses the // hosted tray (a resubmission is the inbox's idempotency problem, and // the human can see its own pending chip). - if (item?.derivedPending && (hosted || !appliedOutcome(item.id))) { - mountDisposeTray(rail, item, { + if (item?.derivedPending && (hosted || !disposeColumn.appliedOutcome(item.id))) { + disposeColumn.mountDisposeTray(rail, item, { onApplied: () => { railKey = ""; drawAll(); }, onEmitted: () => { railKey = ""; drawAll(); if (intentFeed) intentFeed.refresh(); }, intent: hosted ? { diff --git a/tests/fixtures/web_boundary_census.yaml b/tests/fixtures/web_boundary_census.yaml index bfc49ea4..42c477fc 100644 --- a/tests/fixtures/web_boundary_census.yaml +++ b/tests/fixtures/web_boundary_census.yaml @@ -181,15 +181,14 @@ measured_at: "opensoft/openDox-code main a99eba03e31a0aee1cc15a061fdf718cc88a2c4 # shape and `test_the_declared_totals_are_re_derived_from_the_rows` can refuse a # drift between the two. Measured at slice S4 (see the S4 block above). totals: - A: {files: 25, loc: 16329} - B: {files: 7, loc: 2174} - C: {files: 14, loc: 11854} + A: {files: 25, loc: 16706} + B: {files: 1, loc: 73} + C: {files: 14, loc: 11952} "?": {files: 1, loc: 1435} - files: - path: app.js class: A - loc: 1337 + loc: 1456 note: "the shell; its only class-B import was gate.js at :43 (discharged by S3's view registry -- loc 1155 -> 1282 with the registry wiring, S3; 1282 -> 1337 with S4's two new gate bindings and the two mounts it hands down). Carries SIX transitional route-ownership sites, all in the CORE arm's class-B binding entries and all cleared at S5 when those entries leave for contributedViewBindings(): gate.bar's one route (S3) and gate.lens's and gate.projects's two each (S4). Declaring them is RULED Q3 working -- view_extension.py: 'a binding that declares the routes it calls is what makes that ruling checkable instead of aspirational' -- and it is a real breach by assertion 2's own rule only while the entry sits in app.js (class A) rather than in the class-B module (exempt by construction)" - path: index.html @@ -243,11 +242,6 @@ files: exempt: COMPOSED_COLLECTIONS note: "declared exempt (note § 2.2 rule 3) -- see declared_exemptions below" - - path: views/dispose.js - class: B - loc: 427 - note: "GATE_DISPOSE_ROUTE :28 and GATE_PROPOSE_ROUTE :29 both under serve_gate.ACTIONS_GATE_PREFIX" - - path: views/doc-wheel.js class: C loc: 491 @@ -300,21 +294,6 @@ files: loc: 538 note: "realization funnel; imports model.js's COLUMN_KEYS; 10 governance literals" - - path: views/gate-lens.js - class: B - loc: 204 - note: "S4 ADDITION (RULED Q3): the lens's two gate verbs. Declares LENS_SAVE_ROUTE and LENS_CLUSTER_ROUTE -- which stood at views/lens-model.js:1036/:1037 and were called from views/lens.js, never from the model -- together with the execute affordance, the human-seen organizer evidence form and the outcome panel that call them. Class B by \u00a7 2.1's own test: delete the gate column and it has nothing left to render. Reached by views/lens.js only as a shell-resolved mount (gate.lens), never an import" - - - path: views/gate-projects.js - class: B - loc: 241 - note: "S4 ADDITION (RULED Q3): the project commissions. Declares ACTIONS_CREATE_PROJECT_ROUTE and ACTIONS_EDIT_PROJECT_ROUTE -- views/repo-selector.js:39/:43 -- with the create-project form and the membership-edit commission that POST them. The PICKER did not travel (\u00a7 6 Q3: 'moving it whole puts the project picker -- the student's way to choose what they are working on -- behind the gate column'). Reached by views/repo-selector.js only as a shell-resolved mount (gate.projects), never an import" - - - path: views/gate.js - class: B - loc: 184 - note: "GATE_ACTIONS = [demote,edit,ratify,kickoff]; GATE_RATIFY_ROUTE :120 under the gate prefix" - - path: views/grouping.js class: A loc: 246 @@ -390,27 +369,17 @@ files: - path: views/staging-workbench.js class: C - loc: 3315 + loc: 3374 note: "full-screen workbench scoped to one topic-bearing tile" - - path: views/swb-create.js - class: B - loc: 384 - note: "CREATE_ROUTE is DECLARED HERE since S4 (RULED Q3) -- it stood at staging-workbench-model.js:543 and this file was always its only caller" - - path: views/swb-model-intake.js class: A loc: 364 note: "model-intake dialog; all routes answered by openDox's serve_workbench.py" - - path: views/swb-session.js - class: B - loc: 661 - note: "EDIT_DOCUMENT_ROUTE/OPEN_PR_ROUTE/FIRST_EDIT_ROUTE/ABANDON_SESSION_ROUTE/SHARE_SESSION_ROUTE, all under the gate prefix and all DECLARED HERE since S4 (RULED Q3), with the SESSION_ROUTES table and sessionRoute() that read them; they stood at staging-workbench-model.js:817-:826 and this file was always their only caller" - - path: views/view_extension.js class: A - loc: 499 + loc: 757 note: "S3 ADDITION: the client-side view registry -- ViewBinding/collectViewBindings, route_extension.py's shape mirrored in JS (openDox-spec § 4.1). No import, no governance literal; 'gate.bar' in a doc comment is a documentation example of an id, not a route literal, so assertion 2 does not match it. loc 422 -> 455 on this PR's own review round (Copilot, PR #14): a malformed contributed_routes now refuses instead of silently disabling the ownership check, and a rejected dynamic import now refuses naming the binding and module instead of leaking a raw error. loc 463 -> 499 on this fix (Copilot, PR #16, view_extension.js:358): manifestRoutes() and ownershipBreach() now share one shape check, refusing a contributed-routes entry missing a string pattern or carrying a non-boolean is_prefix at whichever of the two sees it first, instead of the array-only check at manifestRoutes() and a truthy is_prefix read at ownershipBreach() silently letting a malformed entry through as if it were not a prefix match." - path: views/viewer.js @@ -425,7 +394,7 @@ files: - path: views/wheel.js class: C - loc: 1702 + loc: 1741 note: "THE WHEEL; imports dispose.js (class B) and intent-feed.js (absent, RULED openxFactory); SOURCE_ROUTE :97" # ASSERTION 1's ONE DECLARED, RULED-LATER EXCEPTION (note § 4.5 point 1). After diff --git a/tests/test_intent_binding_shape.py b/tests/test_intent_binding_shape.py index 303dd8e1..a1ac1ed0 100644 --- a/tests/test_intent_binding_shape.py +++ b/tests/test_intent_binding_shape.py @@ -120,7 +120,18 @@ def test_intent_binding_reaches_intent_feed_only_dynamically() -> None: def test_dispose_and_wheel_no_longer_name_intent_feed_directly() -> None: - for path in (DISPOSE, WHEEL): + """AMENDED BY SLICE S5: `views/dispose.js` left this bundle. + + S2's fix stands and travelled with the module. `dispose.js` is openXdox-code's + package data now (RULED Q5, openxFactory#656 comment `5648044785`), and the + property this test asserts of it is asserted THERE, at + `tests/test_gate_loop_views.py::test_the_bundle_reach_is_exactly_declared`, + which holds that module's relative imports to an EXACT declared set — + `./helpers.js` and `./intent-binding.js` — so `intent-feed.js` reappearing + in it fails as an undeclared reach rather than as a missing string. What + stays measurable here is `views/wheel.js`, which stayed. + """ + for path in (WHEEL,): text = path.read_text(encoding="utf-8") assert "intent-feed.js" not in text, ( f"{path} still names intent-feed.js directly; the note's " @@ -132,18 +143,24 @@ def test_dispose_and_wheel_no_longer_name_intent_feed_directly() -> None: ) -def test_dispose_imports_the_intent_names_from_the_binding() -> None: - text = DISPOSE.read_text(encoding="utf-8") - imports = {specifier: names for names, specifier in _static_imports(text)} - assert "./intent-binding.js" in imports, ( - "dispose.js does not statically import from ./intent-binding.js" - ) - names = set(imports["./intent-binding.js"]) - assert {"emitIntent", "renderIntentChips"} <= names, ( - f"dispose.js imports {sorted(names)} from intent-binding.js; " - "expected at least emitIntent and renderIntentChips (unchanged from " - "its former import of intent-feed.js)" - ) +def test_dispose_left_the_bundle_with_its_intent_reach_intact() -> None: + """AMENDED BY SLICE S5. This asserted that `views/dispose.js` imported + `emitIntent` and `renderIntentChips` from `./intent-binding.js`; the module + moved to openXdox-code and the assertion moved with it + (`tests/test_gate_loop_views.py`'s `BUNDLE_REACH` table names + `./intent-binding.js` for `dispose.js` exactly). + + What this leg can still say — and it is the half that matters here — is that + the module is GONE and that `views/intent-binding.js`, which S2 created and + S5 does not move, is still here for the contributed module to reach once the + assembly places it beside this bundle.""" + assert not DISPOSE.exists(), ( + "views/dispose.js is still in this bundle; slice S5 moves the gate " + "loop's six class-B modules to openXdox-code's package data") + assert BINDING.is_file(), ( + "views/intent-binding.js is gone: it is class A, it stays, and the " + "contributed dispose module imports it by a bundle-relative specifier " + "that the composed assembly resolves in place") def test_wheel_imports_the_intent_names_from_the_binding() -> None: @@ -168,7 +185,11 @@ def test_every_static_relative_import_in_the_touched_files_resolves() -> None: # standing in for slice S1's full-tree census test. `intent-binding.js`'s # own reference to intent-feed.js is DYNAMIC and is deliberately not # required to resolve — that is the seam, not a gap in it. - for path in (DISPOSE, WHEEL, BINDING): + # SLICE S5: `dispose.js` is no longer one of the files this leg ships, so + # the rehearsal is over the two that stayed. Its own imports are held to an + # exact declared set at openXdox-code, which is a stronger check than + # "resolves" and is made where the file is. + for path in (WHEEL, BINDING): text = path.read_text(encoding="utf-8") for _names, specifier in _static_imports(text): target = (path.parent / specifier).resolve() diff --git a/tests/test_split_route_tails.py b/tests/test_split_route_tails.py index c5447c29..c8b8c903 100644 --- a/tests/test_split_route_tails.py +++ b/tests/test_split_route_tails.py @@ -11,6 +11,23 @@ class B." RULED Q3 (opensoft/openxFactory#656 comment `5642758731`, Brett Heap, 2026-09-12) states the rule the move obeys: **"a route constant travels with the binding that calls it, never with the model that happens to declare it."** +AMENDED BY SLICE S5 -- "contribute the gate loop". S4 was S5's precondition and +S5 has happened: the six class-B modules S4's ten tails landed in +(`views/gate.js`, `views/dispose.js`, `views/swb-create.js`, +`views/swb-session.js`, `views/gate-lens.js`, `views/gate-projects.js`) have +LEFT this bundle for openXdox-code's package data, declared there as +`ViewBinding`s (RULED Q5, openxFactory#656 comment `5648044785`). Half of every +row in `MOVED_TAILS` is therefore no longer a file this leg can read, and this +suite now says so explicitly rather than failing to open a path: the rows split +into `IN_BUNDLE_TAILS` (the one projection read slice S6 owns) and +`CONTRIBUTED_TAILS` (the ten gate ones), and what is asserted about the latter +is the half that is still THIS leg's -- the origin carries no literal, the +module is gone, no file of this bundle declares a gate route at all, and no +binding entry survives in `app.js`'s core arm. The other half -- the binding +declaring the same routes the module POSTs, and the module still performing the +verb under `node` -- moved WITH the modules, to openXdox-code's +`tests/test_gate_loop_views.py`. + WHAT THIS FILE MEASURES AND `tests/test_web_boundary.py` DOES NOT. The census test asserts the BOUNDARY -- that no file outside class B names a route another column declares -- and it would stay just as green if all thirteen constants @@ -96,6 +113,31 @@ class B." RULED Q3 (opensoft/openxFactory#656 comment `5642758731`, Brett Heap, SPLIT_FILES = ("lens-model.js", "repo-selector.js", "staging-workbench-model.js") NEW_MODULES = ("gate-lens.js", "gate-projects.js", "projection-index.js") +# AMENDED BY SLICE S5 -- "contribute the gate loop". S4 put the ten gate-prefix +# tails into class-B modules; S5 moved those modules OUT OF THIS BUNDLE, to +# openXdox-code's package data, where they are declared as `ViewBinding`s +# (RULED Q5, openxFactory#656 comment `5648044785`). So half of every row above +# is no longer a file this leg can read, and this suite splits accordingly: +# +# IN_BUNDLE the one tail whose destination stayed -- `projection-index.js` +# is openXdox's PROJECTION column's read, not the gate loop's, +# and slice S6 (not S5) is what re-homes that family. +# CONTRIBUTED the ten gate tails. What this leg can still assert about them +# is the half that matters HERE: the origin is clean, the +# module has left, and no file of this bundle names the route. +# The other half -- that the binding declares it and the module +# still performs the verb -- is openXdox-code's, at +# `tests/test_gate_loop_views.py`. +IN_BUNDLE_TAILS = [row for row in MOVED_TAILS + if row[3] in ("projection-index.js",)] +CONTRIBUTED_TAILS = [row for row in MOVED_TAILS + if row[3] not in ("projection-index.js",)] +#: The six modules slice S5 moved to openXdox-code (four the note's S5 row names +#: plus the two S4 created, whose own header says "AT S5 THIS FILE LEAVES THE +#: BUNDLE"). +CONTRIBUTED_MODULES = ("gate.js", "dispose.js", "swb-create.js", + "swb-session.js", "gate-lens.js", "gate-projects.js") + def _read(name: str) -> str: return (VIEWS / name).read_text(encoding="utf-8") @@ -109,8 +151,8 @@ def _declares(source: str, constant: str, route: str) -> bool: # 1. the move itself: out of the model, into the caller # --------------------------------------------------------------------------- -@pytest.mark.parametrize("constant,route,origin,destination", MOVED_TAILS, - ids=[t[0] for t in MOVED_TAILS]) +@pytest.mark.parametrize("constant,route,origin,destination", IN_BUNDLE_TAILS, + ids=[t[0] for t in IN_BUNDLE_TAILS]) def test_each_route_tail_is_declared_in_the_file_that_calls_it( constant, route, origin, destination) -> None: """RULED Q3, one row at a time. The constant is declared in its @@ -126,6 +168,26 @@ def test_each_route_tail_is_declared_in_the_file_that_calls_it( ) +@pytest.mark.parametrize("constant,route,origin,destination", CONTRIBUTED_TAILS, + ids=[t[0] for t in CONTRIBUTED_TAILS]) +def test_each_contributed_route_tail_left_with_its_module( + constant, route, origin, destination) -> None: + """The same row after slice S5, measured from the side that stayed. + + S4 sent the tail to the class-B module that CALLS it; S5 sent that module to + openXdox. Both halves of the move are still checkable here, and they are the + two that would tell a reader this bundle had kept a copy: the ORIGIN carries + no literal, and the DESTINATION is not a file of this bundle at all. + """ + assert f'"{route}"' not in _read(origin), ( + f"{origin} still carries the literal {route!r}: the tail did not move, " + f"it was copied") + assert not (VIEWS / destination).exists(), ( + f"views/{destination} is still in this bundle: slice S5 moves the gate " + f"loop's six class-B modules to openXdox-code's package data, where " + f"{constant} is declared on a contributed ViewBinding") + + def test_the_three_split_files_declare_no_route_constant_that_left() -> None: """The stronger statement the per-row test cannot make on its own: not one of the eleven names survives as an `export const` in the file it left, so a @@ -220,58 +282,68 @@ def _app_binding(binding_id: str) -> dict: } -@pytest.mark.parametrize("binding_id,module,entry,region,declared_in,constant", [ - ("gate.lens", "./views/gate-lens.js", "mountLensGate", "lens-gate", - "gate-lens.js", "LENS_GATE_ROUTES"), - ("gate.projects", "./views/gate-projects.js", "mountProjectCommissions", - "repo-projects", "gate-projects.js", "PROJECT_GATE_ROUTES"), -]) -def test_the_binding_entry_and_its_module_declare_the_same_routes( - binding_id, module, entry, region, declared_in, constant) -> None: - """`view_extension.py`: "a binding that declares the routes it calls is - what makes that ruling checkable instead of aspirational". The declaration - is necessarily written twice -- once in the manifest entry and once as the - constants the module POSTs -- because `app.js` is class A and may not - import a class-B module to read them. THIS is what keeps the two copies - honest, and it is what S5 will carry over when the entry moves from the - core arm into `contributedViewBindings()`.""" - binding = _app_binding(binding_id) - assert binding["module"] == module - assert binding["entry"] == entry - assert binding["region"] == region - assert binding["view_class"] == "B", ( - f"{binding_id} is not declared class B; class B is the ONLY class " - f"exempt from the route-ownership refusal, and a gate binding that " - f"declares itself anything else refuses its own assembly" - ) - assert binding["optional"] is True, ( - f"{binding_id} must be optional: a shell assembled without the gate " - f"column has to come up, which is RULING C2 one tier out" - ) - assert binding["routes"] == _js_route_array(_read(declared_in), constant), ( - f"{binding_id}'s declared routes and {declared_in}'s {constant} have " - f"drifted apart" - ) - - -def test_every_moved_gate_route_is_declared_by_some_class_b_module() -> None: - """The ten gate-prefix constants § 5's S4 row counts, checked as a SET: - each is declared in a class-B file, so the gate loop's route table no - longer lives outside class B and S5 can contribute it.""" +@pytest.mark.parametrize("binding_id", ["gate.bar", "gate.lens", "gate.projects"]) +def test_no_gate_binding_is_declared_in_the_shells_core_arm(binding_id) -> None: + """AMENDED BY SLICE S5, and the amendment is what S4's own comment predicted. + + S4 asserted that each of its two binding entries in `app.js`'s CORE arm + named the same routes as the module it pointed at -- a declaration + "necessarily written twice ... because `app.js` is class A and may not + import a class-B module to read them" -- and said in as many words that this + is "what S5 will carry over when the entry moves from the core arm into + `contributedViewBindings()`". It has moved. Both copies now sit at + openXdox-code, one in `src/openxdox/view_extensions.py`'s binding spec and + one in the module's own constants, and they are held to each other THERE + (`tests/test_gate_loop_views.py::test_every_binding_declares_the_routes_its_module_names`) + -- which is a stronger place for the check than here, because both halves + are finally in one repository. + + What this leg asserts is the half it owns: not one of the three gate + bindings is declared in the shell's core arm any more. + """ + source = APP_JS.read_text(encoding="utf-8") + assert f'id: "{binding_id}"' not in source, ( + f"app.js still declares {binding_id} in CORE_VIEWS; slice S5 moves every " + "gate binding to the contributed column") + + +def test_no_file_of_this_bundle_declares_a_gate_route() -> None: + """The strongest single statement this slice can make, and the one that says + the gate loop really left rather than being partly copied. + + S4's version of this test asked whether the ten moved constants were + declared by SOME class-B file of this bundle -- the precondition for S5. + S5 is the slice after which the answer must be NO for every one of them, + from any class: `views/gate.js`, `views/dispose.js`, `views/swb-create.js`, + `views/swb-session.js`, `views/gate-lens.js` and `views/gate-projects.js` + are openXdox-code's package data now, and a gate route literal surviving + anywhere here would be a copy left behind. + """ + survivors = [] + for path in sorted(p for p in WEB.rglob("*") if p.is_file() + and p.suffix in (".js", ".html", ".css")): + text = path.read_text(encoding="utf-8", errors="replace") + for match in re.finditer(r'"(/actions/gate/[^"]*)"', text): + survivors.append(f"{path.relative_to(WEB).as_posix()}: {match.group(1)}") + assert survivors == [], ( + f"{len(survivors)} gate route literal(s) still in this bundle: " + f"{survivors}. RULED Q3: a route constant travels with the binding that " + "calls it, and every gate binding is contributed at slice S5") + + +@pytest.mark.parametrize("name", CONTRIBUTED_MODULES) +def test_every_contributed_module_left_this_bundle(name) -> None: + """The six files § 5's S5 row moves, checked one at a time so the failure + names which one came back.""" + assert not (VIEWS / name).exists(), ( + f"views/{name} is still here; slice S5 moves it to openXdox-code's " + "`src/openxdox/web/views/`, shipped as package data and copied into this " + "bundle at assembly (RULED Q5)") census = yaml.safe_load(CENSUS_PATH.read_text(encoding="utf-8")) - class_b = [row["path"] for row in census["files"] if row["class"] == "B"] - declared: set[str] = set() - for path in class_b: - for match in re.finditer(r'export const \w+ = "(/actions/gate/[^"]+)";', - (WEB / path).read_text(encoding="utf-8")): - declared.add(match.group(1)) - moved = {route for _c, route, _o, _d in MOVED_TAILS - if route.startswith("/actions/gate/")} - assert moved <= declared, f"not declared in any class-B file: {sorted(moved - declared)}" - # plus the three that were already there (§ 4.5 point 2: "the three gate - # constants declared in class-B files are NOT in the count") - assert {"/actions/gate/dispose-possible", "/actions/gate/propose", - "/actions/gate/ratify"} <= declared + rows = {row["path"] for row in census["files"]} + assert f"views/{name}" not in rows, ( + f"the census still carries a row for views/{name}: a row naming a file " + "that is not here fails assertion 1's own stale-row check") @pytest.mark.parametrize("importer", ["app.js", "views/lens.js", @@ -306,13 +378,18 @@ def test_the_selector_reaches_the_projection_column_late() -> None: assert "PROJECTION_COLUMN = null" in source -def test_the_census_carries_the_three_new_modules_as_class_b() -> None: +def test_the_census_carries_the_one_new_module_that_stayed_as_class_b() -> None: + """AMENDED BY SLICE S5. Two of S4's three new modules left this bundle with + the gate loop; `views/projection-index.js` is openXdox's PROJECTION column's + one read, which slice S6 re-homes and this slice does not touch.""" census = yaml.safe_load(CENSUS_PATH.read_text(encoding="utf-8")) rows = {row["path"]: row for row in census["files"]} - for name in NEW_MODULES: - row = rows.get(f"views/{name}") - assert row is not None, f"views/{name} carries no census row" - assert row["class"] == "B", f"views/{name} is class {row['class']!r}" + row = rows.get("views/projection-index.js") + assert row is not None, "views/projection-index.js carries no census row" + assert row["class"] == "B", f"it is class {row['class']!r}" + for gone in ("gate-lens.js", "gate-projects.js"): + assert f"views/{gone}" not in rows, ( + f"views/{gone} still carries a census row after slice S5 moved it") # --------------------------------------------------------------------------- @@ -384,139 +461,25 @@ def _run_node(body: str, tmp_path: Path) -> dict: return json.loads(proc.stdout.strip().splitlines()[-1]) -@pytest.mark.skipif(NODE is None, reason="node is not installed") -@pytest.mark.parametrize("kind,expected", [ - ("save-recipe", "/actions/gate/lens-save-recipe"), - ("add-as-cluster", "/actions/gate/lens-add-as-cluster"), -]) -def test_js_the_lens_gate_posts_the_route_its_plan_kind_names( - kind, expected, tmp_path) -> None: - """The verb still works after the move, and it posts the route the plan - kind names -- the behaviour that used to live in `views/lens.js`'s - `mountExecute`, now in the binding that owns both routes.""" - result = _run_node(f""" -const {{ mountLensGate }} = await import(VIEWS + "gate-lens.js"); -const [calls, fetcher] = recorder({{ payload: {{ ok: true, manifest: "m.yaml", - record: "r.yaml" }} }}); -const host = document.createElement("div"); -const plan = {{ kind: {json.dumps(kind)}, repository: "openxFactory", name: "lens set", - checked: ["a"], pinned: [], members: [], excluded: [] }}; -mountLensGate(host, {{ plan, caps: {{ actor: "brett" }}, fetcher }}); -buttons(host)[0].click(); -await settle(); -// add-as-cluster collects the organizer evidence first: fill it and submit. -if (calls.length === 0) {{ - const form = flatten(host).find((n) => n.className - && n.className.includes("evidence-form")); - for (const input of inputs(form)) input.value = "x"; - buttons(form).find((b) => b.textContent === "execute").click(); - await settle(); -}} -console.log(JSON.stringify({{ calls, texts: texts(host) }})); -""", tmp_path) - assert [c["route"] for c in result["calls"]] == [expected] - call = result["calls"][0] - assert call["method"] == "POST" - assert call["body"]["repository"] == "openxFactory" - if kind == "add-as-cluster": - assert call["body"]["evidence"]["proposer"] == "x" - else: - assert "evidence" not in call["body"] - assert any("landed" in t for t in result["texts"]) - - -@pytest.mark.skipif(NODE is None, reason="node is not installed") -def test_js_the_lens_gate_renders_the_engines_refusal_and_re_arms(tmp_path) -> None: - """"the engine refuses and the reason renders verbatim (single source of - truth)" -- and a refused plan stays retryable, which is what the disabled - flag coming back off means.""" - result = _run_node(""" -const { mountLensGate } = await import(VIEWS + "gate-lens.js"); -const [calls, fetcher] = recorder({ ok: false, status: 409, - payload: { ok: false, message: "recipe already recorded" } }); -const host = document.createElement("div"); -mountLensGate(host, { plan: { kind: "save-recipe", repository: "r", name: "n", - members: [], excluded: [] }, - caps: {}, fetcher }); -const run = buttons(host)[0]; -run.click(); -await settle(); -console.log(JSON.stringify({ calls, texts: texts(host), disabled: run.disabled })); -""", tmp_path) - assert len(result["calls"]) == 1 - assert "recipe already recorded" in result["texts"] - assert result["disabled"] is False - - -@pytest.mark.skipif(NODE is None, reason="node is not installed") -def test_js_the_project_commissions_post_both_gate_routes(tmp_path) -> None: - """One binding, two routes: the create form POSTs the create-project - commission and `commissionEdit` POSTs the membership one, carrying the - project id the selector holds. The controller's shape is the seam - `views/repo-selector.js` reaches through, so it is measured here rather - than assumed.""" - result = _run_node(""" -const { mountProjectCommissions } = await import(VIEWS + "gate-projects.js"); -const [calls, fetcher] = recorder({ payload: { ok: true, job: "J-1", - add: ["b"], remove: [] } }); -const host = document.createElement("div"); -const status = document.createElement("span"); -const pending = []; -const gate = mountProjectCommissions(host, { - roster: [{ kind: "repository", repository: "openxFactory" }, - { kind: "repository", repository: "openDox" }], - status, fetcher, addPendingOption: (name) => pending.push(name), -}); -// the create form: opened by the dropdown's "New Project..." line -const form = flatten(host).find((n) => n.className - && n.className.includes("projectform")); -const hiddenBeforeOpen = form.hidden; -gate.openCreateForm(); -inputs(form).find((i) => i.tag === "input" && i.type === "text").value = "Field Pilots"; -inputs(form).filter((i) => i.type === "checkbox")[0].checked = true; -buttons(form).find((b) => b.textContent === "commission project").click(); -await settle(); -// the membership edit: raised by the filter's add row / trash control -let restored = false; -await gate.commissionEdit("proj-1", { add: ["openDox"] }, - { restore: () => { restored = true; } }); -console.log(JSON.stringify({ calls, pending, hiddenBeforeOpen, - retired: form.hidden, restored, - status: status.textContent })); -""", tmp_path) - assert [c["route"] for c in result["calls"]] == [ - "/actions/gate/create-project", "/actions/gate/edit-project"] - create, edit = result["calls"] - assert create["body"] == {"name": "Field Pilots", - "repositories": ["openxFactory"]} - assert edit["body"] == {"project_id": "proj-1", "add": ["openDox"]} - assert result["hiddenBeforeOpen"] is True # the form is opened, never shown - assert result["retired"] is True # a landed commission retires it - assert result["restored"] is False # nothing to restore on success - assert "membership edit recorded (J-1)" == result["status"] - - -@pytest.mark.skipif(NODE is None, reason="node is not installed") -def test_js_a_refused_membership_edit_restores_the_control(tmp_path) -> None: - """The two-click trash re-arms and the add row's select restores its - placeholder -- `restore` is the selector's half of the act, and the - binding has to call it on a refusal or a control is left dead.""" - result = _run_node(""" -const { mountProjectCommissions } = await import(VIEWS + "gate-projects.js"); -const [calls, fetcher] = recorder({ ok: false, status: 403, - payload: { ok: false, message: "not a gate actor" } }); -const status = document.createElement("span"); -const gate = mountProjectCommissions(document.createElement("div"), - { roster: [], status, fetcher }); -let restored = false; -await gate.commissionEdit("proj-1", { remove: ["openDox"] }, - { restore: () => { restored = true; } }); -console.log(JSON.stringify({ calls, restored, status: status.textContent })); -""", tmp_path) - assert result["restored"] is True - assert "not a gate actor" in result["status"] - assert result["status"].startswith("edit-project refused: ") - +# --------------------------------------------------------------------------- +# THE FIVE NODE PROBES OF `gate-lens.js` AND `gate-projects.js` MOVED WITH THEIR +# MODULES (slice S5). They drove the real bundle files -- the lens gate posting +# the route its plan kind names, its refusal render and re-arm, the two project +# commissions and a refused membership edit restoring its control -- and those +# files are openXdox-code's package data now (RULED Q5, openxFactory#656 comment +# `5648044785`). A probe that imported them from `src/opendox/web/views/` would +# be asserting against a file this bundle no longer ships. +# +# THEY WERE PORTED, NOT DELETED, and the port is the point: deleting behavioural +# coverage in a refactor slice is how a move that passes every shape assertion +# silently breaks a verb, which is the failure this suite's own header names as +# "the worst possible outcome of this slice". They run at openXdox-code, against +# the same real files, in `tests/test_gate_loop_views.py` -- same harness, same +# DOM stub, same assertions, one import path different. +# +# What stays here is everything about the modules this bundle still ships, and +# the SHAPE assertions above, which are what this leg can still answer. +# --------------------------------------------------------------------------- @pytest.mark.skipif(NODE is None, reason="node is not installed") def test_js_the_snapshot_index_read_degrades_to_null(tmp_path) -> None: diff --git a/tests/test_view_registry.py b/tests/test_view_registry.py index fe53ca38..e710f907 100644 --- a/tests/test_view_registry.py +++ b/tests/test_view_registry.py @@ -620,27 +620,66 @@ def test_app_js_no_longer_imports_the_gate_module(): assert "./views/view_extension.js" in imports -def test_app_js_declares_the_gate_bar_as_an_optional_class_b_binding(): +def test_app_js_no_longer_declares_the_gate_bar_in_its_core_arm(): + """AMENDED BY SLICE S5, and the amendment is the proof S3 was right. + + This test asserted the `gate.bar` entry's every field in `app.js`'s CORE + arm, and S3's own comment beside that entry said what would happen next: + "it is in the CORE arm and that is TRANSITIONAL. `gate.js` is still a file + of this bundle; slice S5 moves the four class-B files behind a binding + openXdox supplies, at which point this entry is deleted and the identical + binding arrives through `contributedViewBindings()`. Nothing else in this + file changes when it does -- which is the test of whether the seam was drawn + in the right place." + + It has. The entry is gone, `views/gate.js` is gone, and what replaced them + is a declaration in openXdox-code's `src/openxdox/view_extensions.py` with + the module shipped as that package's data (RULED Q5, openxFactory#656 + comment 5648044785). So this test now asserts the ABSENCE -- of the entry, + of the module, and of any gate route literal anywhere in the shell -- which + is the S3 promise discharged rather than an assertion retired. + """ source = APP_JS.read_text(encoding="utf-8") - assert 'id: "gate.bar"' in source - assert 'module: "./views/gate.js", entry: "mountGateBar", view_class: "B"' in source - assert 'routes: ["/actions/gate/ratify"]' in source - assert "optional: true" in source - - -def test_app_js_mounts_the_gate_bar_through_its_declared_entry(): + assert 'id: "gate.bar"' not in source, ( + "app.js still declares the `gate.bar` binding in its CORE arm; slice S5 " + "moves it to the contributed column") + assert not (WEB / "views" / "gate.js").exists(), ( + "views/gate.js is still in this bundle: slice S5 moves the gate loop's " + "six class-B modules to openXdox-code's package data") + # NO GATE ROUTE LITERAL SURVIVES IN THE SHELL. § 4.5 assertion 2's six + # remaining sites were this entry and slice S4's two, and they closed + # together. + assert '"/actions/gate/' not in source, ( + "app.js still names a gate route; every one of them travels with the " + "binding that calls it, and every one of those bindings is contributed " + "now (RULED Q3, openxFactory#656 comment 5642758731)") + + +def test_app_js_mounts_a_contributed_binding_through_its_declared_entry(): """The viewer's `mountGate` adapter must call the RESOLVED binding's own declared `entry` export, not a name this file happens to remember (Copilot - review thread on this PR, `app.js:994`). `resolveView()` already validates + review thread on PR #14, `app.js:994`). `resolveView()` already validates that `binding.entry` names a callable export of `binding.module`; a contributed `gate.bar` binding can declare any entry name and export a DIFFERENT callable under it, and a hardcoded `mountGateBar` would then either mount the wrong function or throw on `undefined`. The negative assertion is the regression guard: the fix is a one-token change a later - edit could silently revert back to the hardcoded name.""" + edit could silently revert back to the hardcoded name. + + AMENDED BY SLICE S5 for RULED Q3 (openxFactory#656 comment 5648044785): + "ONE mount signature, `mount(host, snapshot, ctx)`; the gate bar's + `(container, ctx, opts)` is recorded as the one declared exception until S5 + rewrites it." This is that rewrite -- the viewer's per-artifact context + travels as `ctx.gate` and the probe as `ctx.caps`, so the shell now has + exactly one mount shape and this file no longer teaches a second one. + """ source = APP_JS.read_text(encoding="utf-8") - assert "gateView.exports[gateView.binding.entry](host, gctx, { caps })" in source - assert "gateView.exports.mountGateBar(host, gctx, { caps })" not in source + assert ("gateView.exports[gateView.binding.entry](\n" + " host, snapshot, { gate: gctx, caps })") in source + assert "gateView.exports.mountGateBar(" not in source + assert "(host, gctx, { caps })" not in source, ( + "the gate bar's `(container, ctx, opts)` signature is still here; RULED " + "Q3 ends that declared exception at this slice") def test_app_js_wires_the_doc_list_through_the_registry(): diff --git a/tests/test_web_boundary.py b/tests/test_web_boundary.py index 8bfe2551..c746ef4f 100644 --- a/tests/test_web_boundary.py +++ b/tests/test_web_boundary.py @@ -340,36 +340,28 @@ def _route_ownership_violations() -> list[str]: raises=AssertionError, reason=( "docs/front-end-package-boundary.md § 4.5 point 2 (opensoft/openDox-spec " - "#8 -> a44ac06d): 10 sites outside class B name a route another column " - "declares. THE ARITHMETIC, since every slice so far has moved it: 18 " - "at S1 -> 20 at S3 (which added app.js's `gate.bar` entry and closed " - "none) -> 12 measured after S4 -> 10 in scope, because S4 also gives " - "this assertion the DECLARED EXCEPTION the note's own last paragraph " - "states for views/lens.js:41/45. S4 CLEARED ALL TWELVE SPLIT-FILE " - "SITES the note's point-2 table assigns to it (views/lens-model.js:" - "1036/1037, views/repo-selector.js:33/39/43/46, " - "views/staging-workbench-model.js:543/817/818/821/822/826): every one " - "of those constants now sits in a class-B file, exempt by construction " - "-- which is RULED Q3 in force rather than described. WHAT IS LEFT, " - "and whose it is: 6 the gate prefix, ALL of them in app.js's CORE arm " - "-- :589/:601 the `gate.bar` entry (S3) and :624/:625/:630 the " - "`gate.lens` and `gate.projects` entries (S4) -- each a class-B " - "binding's `routes:` declaration, which view_extension.py calls the " - "thing that makes Q3 'checkable instead of aspirational', and each a " - "real breach by this assertion's own rule only while the entry sits " - "in app.js (class A) rather than in the class-B module it names. All " - "six are TRANSITIONAL and close together at slice S5, when the class-B " - "files move behind a host-supplied contribution and all three entries " - "leave app.js for contributedViewBindings(). Plus 4 openXdox's " - "projection routes -- app.js:195/196, views/viewer.js:314, " - "views/wheel.js:97, the `/source/` sites RULED Q4 re-homes at slice " - "S6. NOT IN SCOPE, by declaration rather than by silence: " - "views/lens.js's two openxFactory-lane sites " - "(`route_ownership_exceptions` in the census, with the ruling gap " - "beside them) -- none of Q1-Q5 rules on that file, so they clear on no " - "slice's schedule and 'they never entered it'. This marker therefore " - "comes off at S6, once BOTH remaining families are closed; unmark only " - "once verified green." + "#8 -> a44ac06d): 4 sites outside class B name a route another column " + "declares. THE ARITHMETIC, since every slice so far has moved it: 18 at " + "S1 -> 20 at S3 (which added app.js's `gate.bar` entry and closed none) " + "-> 12 measured after S4 -> 10 in scope (S4 also gives this assertion " + "the DECLARED EXCEPTION the note's own last paragraph states for " + "views/lens.js:41/45) -> 4 HERE. SLICE S5 CLEARED ALL SIX GATE-PREFIX " + "SITES, and every one of them was in app.js's CORE arm: the `gate.bar` " + "entry (S3) and the `gate.lens` / `gate.projects` entries (S4), each a " + "class-B binding's `routes:` declaration sitting in a class-A file. " + "They closed the way the marker predicted -- the six class-B modules " + "LEFT this bundle for openXdox-code's package data and their bindings " + "arrive through contributedViewBindings() (RULED Q5, openxFactory#656 " + "comment 5648044785), so app.js carries no gate route literal at all. " + "WHAT IS LEFT is one family and it is not this slice's: 4 of openXdox's " + "projection routes -- app.js:205/:206, views/viewer.js:314, " + "views/wheel.js:131, the `/source/` sites RULED Q4 re-homes at slice S6 " + "(openDox-code#16, openXdox-code#17, both in flight on their own " + "branches and not in this stack). NOT IN SCOPE, by declaration rather " + "than by silence: views/lens.js's two openxFactory-lane sites " + "(`route_ownership_exceptions` in the census) -- none of Q1-Q5 rules on " + "that file, so they clear on no slice's schedule. This marker therefore " + "comes off at S6; unmark only once verified green." ), ) def test_no_ownership_violation_outside_class_b() -> None: @@ -432,33 +424,33 @@ def _import_violations() -> list[str]: return violations -@pytest.mark.xfail( - strict=True, - raises=AssertionError, - reason=( - "docs/front-end-package-boundary.md § 1.2(b) / § 4.5 point 3 " - "(opensoft/openDox-spec #8 -> a44ac06d): 4 sites today, all " - "CLASS-BOUNDARY -- app.js -> views/swb-session.js, " - "views/staging-workbench.js -> views/swb-create.js and -> " - "views/swb-session.js, views/wheel.js -> views/dispose.js (all class " - "A/C importing class B). THE ARITHMETIC: 7 at S1 -> 6 once S3 " - "(opensoft/openDox-code#14) closed app.js:43 -> views/gate.js, the " - "shell's one direct class-B import, now a registry lookup and exactly " - "the edge § 4.1 names -> 4 once S2 (opensoft/openDox-code#15) closed " - "the two UNRESOLVED intent-feed imports its own optional binding " - "replaced (RULED Q5; the manifest row stands, RULED OQ-F). The count " - "was last restated on the S3 branch before that merge and read 6; " - "re-measured here rather than left stale, which is the only change " - "slice S4 makes to this marker besides `raises=`. S4 ADDS NONE: its " - "three new class-B modules are reached through the shell's resolved " - "mounts and one late dynamic import, never a static `from` clause, so " - "no class-A or class-C file gained a class-B import. The four that " - "remain are the gate loop's own, closed at S5 when its files move " - "behind a host-supplied contribution -- the note's closing paragraph " - "assigns this assertion to S2, which was the intent-feed edge only; " - "flagged here rather than narrowed to fit the note's summary." - ), -) +# THE MARKER IS OFF -- SLICE S5 DISCHARGED THIS ASSERTION (note § 4.5's own +# closing paragraph: "Assertions 2, 3 and 4 carry the marker at S1, and each is +# unmarked by the slice that discharges it: 3 by S2, 2 by S5 and S6, 4 by S7"). +# +# THE ARITHMETIC, since every slice so far has moved it: 7 at S1 -> 6 once S3 +# (opensoft/openDox-code#14) closed `app.js`:43 -> `views/gate.js` -> 4 once S2 +# (#15) closed the two UNRESOLVED intent-feed imports -> 0 HERE. The four this +# slice closed were the gate loop's own, and they closed the way the note said +# they would -- by the modules LEAVING, not by the importers being rewritten +# around them: +# +# app.js -> views/swb-session.js (`firstEditTransport`, +# RULED Q10) +# views/staging-workbench.js -> views/swb-create.js (RULED Q5 + Q3) +# views/staging-workbench.js -> views/swb-session.js (RULED Q5 + Q3) +# views/wheel.js -> views/dispose.js (RULED Q5 + Q2) +# +# Each importer now reads the DECLARED NAMESPACE of a contributed binding the +# shell resolved (RULED Q2's `exports` tuple), handed down already-bound, with a +# null column making every affordance unoffered where openXdox is not +# registered. The six modules are openXdox-code's package data +# (`src/openxdox/web/views/`), placed into this bundle at assembly (RULED Q5). +# +# `strict=True` IS WHY THIS IS SAFE TO UNMARK AND NOT A CHOICE: leaving the +# marker on a passing assertion is an XPASS and turns the required check RED, so +# the marker had to come off in the same commit that closed the last breach -- +# which is precisely the rot the marker exists to prevent, working. def test_every_relative_import_resolves_and_stays_in_class() -> None: violations = _import_violations() assert not violations, f"{len(violations)} import violation(s):\n" + "\n".join(violations) From fd7160d71813874033c21d6f2a8daa5ebf2350e4 Mon Sep 17 00:00:00 2001 From: Brett Heap Date: Sat, 12 Sep 2026 15:53:38 -0400 Subject: [PATCH 16/44] =?UTF-8?q?=C2=A7=203.4=20S5,=20leg=20B:=20publish?= =?UTF-8?q?=20the=20view=20manifest,=20and=20measure=20the=20slice?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit TWO THINGS. THE ONE LINE SLICE S3 BUILT BOTH ENDS OF AND DID NOT WRITE. `serve.build_server()` now sets `capabilities["views"] = view_extension.view_manifest(...)`, collected from the host's `VIEW_EXTENSIONS` facet against the routes THIS assembly contributed. `opendox/view_extension.py` named this line and the slice that owes it: "S5, the slice at which a contribution first EXISTS to deliver, joins them." No new route and no second fetch — it rides on the payload `views/notebook.js`'s `probeCapabilities()` already fetches once at load, which is how a static image reads an empty consumer column and comes up. `tests/test_gate_loop_contributed.py`, on `validate`'s explicit list in the same commit. Its centre is the slice's own success test — `test_a_student_install_comes_up_with_no_gate_loop_and_no_404` — made of four separately-measured facts rather than one: none of the six modules is in the bundle or the census, nothing imports one (so the module graph resolves without them, which is § 1.2(b)'s blank-page failure mode closed), no gate route literal survives anywhere for anything to request, and each affordance is UNOFFERED rather than undefined because the two class-C files read null columns whose capability predicates answer false. Node-driven against the real `views/view_extension.js`: the declared namespace refusing an undeclared reach (Q2), a declared export the module lacks refusing at resolve, `requires` unmet answering null for an optional binding and refusing for a required one with the path and the probed value named (Q4), and the generic mount pass mounting a `dom`-region binding with `mount(host, snapshot, ctx)`, leaving a `shell` region alone, and writing a NAMED reason into the region of an unmet optional (Q1). ONE LANGUAGE CONSTRAINT RECORDED RATHER THAN WORKED AROUND: a module namespace's exports are non-configurable, so the Proxy invariants forbid `has` / `ownKeys` / `getOwnPropertyDescriptor` from hiding one — a `has` trap answering false throws `TypeError` and would break the caller instead of refusing it. The declared namespace therefore refuses on the REACH, through `get` alone, which is exactly what RULED Q2 calls the defect. Lane: openxfactory-4-opendox-extraction Refs opensoft/openxFactory#656 Co-Authored-By: Claude Opus 5 --- .github/workflows/validate.yml | 19 + src/opendox/serve.py | 42 ++ src/opendox/web/views/view_extension.js | 34 +- tests/test_gate_loop_contributed.py | 541 ++++++++++++++++++++++++ 4 files changed, 619 insertions(+), 17 deletions(-) create mode 100644 tests/test_gate_loop_contributed.py diff --git a/.github/workflows/validate.yml b/.github/workflows/validate.yml index 20d53f64..adb44df0 100644 --- a/.github/workflows/validate.yml +++ b/.github/workflows/validate.yml @@ -112,6 +112,24 @@ jobs: # no consumer: it reads bundle files as text and drives the real ones # under the `node` the runner already has (skipped, never failed, where # node is absent), exactly as `tests/test_view_registry.py` does. + # § 3.4 SLICE S5 adds `tests/test_gate_loop_contributed.py`, on the same + # footing as its six neighbours. S5 is "contribute the gate loop": the six + # class-B modules leave this bundle for openXdox-code's package data and + # arrive back as contributed `ViewBinding`s (RULED Q1-Q12, + # openxFactory#656 comments 5648044785 / 5648049748 / 5648065587, Brett + # Heap, 2026-09-12). `tests/test_web_boundary.py` measures the BOUNDARY + # and would be just as green if the gate loop had been DELETED; this file + # measures the other half — the seam the modules left through, the + # declared namespace bounding what the shell may reach, `requires` + # evaluated, the generic mount pass, `ViewBindingError` surfaced + # separately, and the slice's own success test: that a student install + # comes up with no gate bar, no dispose tray, no session verbs and no 404. + # + # `--noconftest` safe and needs no consumer: it imports + # `opendox.view_extension` alone, reads bundle files as text, and drives + # 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. - name: pytest run: >- python -m pytest -q @@ -122,4 +140,5 @@ jobs: tests/test_intent_binding_shape.py tests/test_view_registry.py tests/test_split_route_tails.py + tests/test_gate_loop_contributed.py --noconftest diff --git a/src/opendox/serve.py b/src/opendox/serve.py index 8cd55124..8f79d971 100644 --- a/src/opendox/serve.py +++ b/src/opendox/serve.py @@ -145,6 +145,10 @@ # drift guard holds the literals together. from opendox import consumer_reach # noqa: E402 from opendox import defaults # noqa: E402 +# § 3.4 slice S5: `build_server()` publishes the VIEW MANIFEST on +# `/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 registry_mod = consumer_reach.snapshot_registry # noqa: E402 # THE BY-FUNCTION SPLIT (`split-opendox-two-layer-product` § 2.4, PRs 2 and 3 @@ -1533,6 +1537,44 @@ def build_server( # (no writable checkout) means no create is possible, which is the honest # reading of a plane that cannot name one. + # ---- THE VIEW MANIFEST, PUBLISHED (§ 3.4 slice S5) ---------------------- + # + # THE ONE LINE SLICE S3 BUILT BOTH ENDS OF AND DELIBERATELY DID NOT WRITE. + # `opendox/view_extension.py` says so of itself: "The ONE line that puts it + # there (`capabilities["views"] = view_manifest(...)` in + # `serve.build_server`) is NOT written by slice S3 ... S5, the slice at + # which a contribution first EXISTS to deliver, joins them in its own + # declared-edit window." A contribution exists now — openXdox-code's + # `view_extensions.VIEW_EXTENSIONS`, six gate-loop bindings — so the two + # ends are joined here. + # + # NO NEW ROUTE AND NO SECOND FETCH, which is § 4.3's rule for the profile's + # display facet applied unchanged: the manifest rides on `/capabilities`, + # the payload `views/notebook.js`'s `probeCapabilities()` already fetches + # once at load. A shell served as a static image 404s that route and reads + # an empty consumer column, which is how a student install comes up with no + # gate bar and no 404. + # + # COLLECTED THE WAY THE ROUTES ARE, three statements above: the host's + # contributed extensions through ONE `collect_view_bindings`, checked + # against the routes THIS assembly actually contributed — so a class-A or + # class-C binding naming `/actions/gate/*` is refused where the server is + # built rather than discovered in a browser. Class B is exempt by + # construction, which is the boundary working. + # + # ABSENT IS AN EMPTY COLUMN, MALFORMED FAILS CLOSED, and the asymmetry is + # `host_view_extensions`' own: a host registered with no `VIEW_EXTENSIONS` + # facet gets `host_facet: "absent"` with its profile NAMED, never a refusal, + # because every host has yet to grow the facet and refusing would be a flag + # day imposed by the seam that exists to avoid one. + view_extensions = view_extension.host_view_extensions(profile_openxfactory) + capabilities["views"] = view_extension.view_manifest( + view_extension.collect_view_bindings( + view_extensions, contributed_routes=route_bindings), + contributed_routes=route_bindings, + host_facet="declared" if view_extensions else "absent", + host_profile=getattr(profile_openxfactory, "__name__", None), + ) bound = type("BoundDashboardHandler", (DashboardHandler,), { "checkout_root": checkout_root, diff --git a/src/opendox/web/views/view_extension.js b/src/opendox/web/views/view_extension.js index d6459459..5b6a0fbd 100644 --- a/src/opendox/web/views/view_extension.js +++ b/src/opendox/web/views/view_extension.js @@ -616,11 +616,23 @@ export async function resolveView(bindings, id, options) { // which is what every core-arm binding declares, because the core arm's modules // are imported statically by the shell that owns them. // -// SYMBOLS AND `then` PASS THROUGH AS ABSENT rather than refusing: a Proxy is -// probed for `Symbol.toStringTag` by `String()`, and any object returned from -// an async function is probed for `then` by the await that receives it. A -// refusal from either would be this seam refusing the language rather than a -// caller. +// SYMBOLS AND `then` PASS THROUGH rather than refusing: a Proxy is probed for +// `Symbol.toStringTag` by `String()`, and any object returned from an async +// function is probed for `then` by the await that receives it. A refusal from +// either would be this seam refusing the language rather than a caller. +// +// ONE TRAP, `get`, AND THAT IS A LANGUAGE CONSTRAINT RATHER THAN A CHOICE. A +// module namespace object's exports are NON-CONFIGURABLE own properties, so the +// Proxy invariants forbid `has`, `ownKeys` and `getOwnPropertyDescriptor` from +// hiding one: a `has` trap answering false for a name the target really carries +// throws `TypeError: trap returned falsish for property … which exists in the +// proxy target as non-configurable`, which would be this seam breaking the +// caller instead of refusing it. `in` and `Object.keys()` therefore still see +// the module's whole namespace, and REACHING for an undeclared name is what +// refuses — which is exactly what RULED Q2 says is the defect: "an undeclared +// reach (today `isGateBearing`, app.js:939) is a refusal". An export is +// writable on a namespace object, so the `get` invariant does not bind and the +// refusal is lawful. function declaredNamespace(binding, exports) { const allowed = new Set(binding.exports.length ? binding.exports : [binding.entry]); @@ -638,18 +650,6 @@ function declaredNamespace(binding, exports) { } return Reflect.get(target, property, receiver); }, - has(target, property) { - if (typeof property === "symbol") return Reflect.has(target, property); - return allowed.has(property) && Reflect.has(target, property); - }, - ownKeys(target) { - return Reflect.ownKeys(target).filter( - (key) => typeof key === "symbol" || allowed.has(key)); - }, - getOwnPropertyDescriptor(target, property) { - if (typeof property !== "symbol" && !allowed.has(property)) return undefined; - return Reflect.getOwnPropertyDescriptor(target, property); - }, }); } diff --git a/tests/test_gate_loop_contributed.py b/tests/test_gate_loop_contributed.py new file mode 100644 index 00000000..69ed0771 --- /dev/null +++ b/tests/test_gate_loop_contributed.py @@ -0,0 +1,541 @@ +"""The gate loop CONTRIBUTED — § 3.4 slice S5, leg B (the shell). + +`docs/front-end-package-boundary.md` § 5 row S5 (openDox-spec `7d12428c`): *"The +four class-B files and all 13 route constants — now all declared in class-B +files — move behind a binding openXdox supplies; a student install comes up with +no gate bar, no dispose tray, no session verbs, and no 404."* The contract is +openXdox-spec `docs/gate-loop-view-contract.md` @ `d73767b7`, whose § 8 Q1–Q12 +were RULED by Brett Heap on 2026-09-12 at `opensoft/openxFactory#656` comments +`5648044785` (Q5, Q1, Q3), `5648049748` (Q2, Q4, Q7, Q8) and `5648065587` (Q9, +Q10, Q11, Q12). + +WHAT THIS FILE MEASURES AND ITS NEIGHBOURS DO NOT. `tests/test_web_boundary.py` +asserts the BOUNDARY — no file outside class B names another column's route, and +every relative import resolves and stays in its class — and both of its relevant +assertions would be just as green if the gate loop had been DELETED. This file +asserts the other half, which is the half a slice called "contribute" has to +earn: that the seam the modules left through actually works, that what the shell +keeps of them is reached through the registry and bounded by the declaration, +and — the slice's own success test — that a shell assembled without the column +comes up. + +THE STUDENT-INSTALL PROOF is +`test_a_student_install_comes_up_with_no_gate_loop_and_no_404`, and it is +deliberately made of four separate facts rather than one: no gate bar, no +dispose tray, no session verbs, no 404. Each is proven against the real bundle +— the module graph with the six files absent, the registry answering `null` for +every gate binding id, no gate route literal anywhere to be requested, and the +shell's own null columns making each affordance unoffered. + +`--noconftest` SAFE, like its seven neighbours on `validate`'s explicit list: it +imports `opendox.view_extension` alone, reads bundle files as text, and drives +the real `views/view_extension.js` under the `node` the runner already has +(skipped, never failed, where node is absent). + +A CREATED file: no carve-manifest row (RULED OQ-C). +""" + +from __future__ import annotations + +import json +import re +import shutil +import subprocess +from pathlib import Path + +import pytest +import yaml + +from opendox.view_extension import ( + REGIONS, ViewBinding, ViewBindingError, collect_view_bindings, dom_regions, + view_manifest, +) + +ROOT = Path(__file__).resolve().parents[1] +WEB = ROOT / "src" / "opendox" / "web" +VIEWS = WEB / "views" +APP_JS = WEB / "app.js" +REGISTRY_JS = VIEWS / "view_extension.js" +CENSUS_PATH = Path(__file__).resolve().parent / "fixtures" / "web_boundary_census.yaml" +NODE = shutil.which("node") + +#: The six modules that left, and the binding id each arrives as. Six and not +#: four: slice S4 split four of the thirteen gate route constants into two NEW +#: class-B modules, and `views/gate-lens.js`'s own header said "AT S5 THIS FILE +#: LEAVES THE BUNDLE". +CONTRIBUTED = { + "gate.bar": "gate.js", + "gate.lens": "gate-lens.js", + "gate.projects": "gate-projects.js", + "gate.dispose": "dispose.js", + "gate.workbench.create": "swb-create.js", + "gate.workbench.session": "swb-session.js", +} + +#: The regions slice S5 adds. `page-overlay` is RULED Q8's; the workbench's two +#: arrive with the bindings that mount into them, on slice S4's own precedent. +NEW_REGIONS = ("page-overlay", "workbench-create", "workbench-session") + + +def _app() -> str: + return APP_JS.read_text(encoding="utf-8") + + +def _run_node(source: str, cwd: Path) -> dict: + """Run an ES-module harness and return the ONE JSON object it prints.""" + script = cwd / "harness.mjs" + script.write_text(source, encoding="utf-8") + proc = subprocess.run([NODE, str(script)], capture_output=True, text=True, + timeout=120) + assert proc.returncode == 0, proc.stderr + return json.loads(proc.stdout.strip().splitlines()[-1]) + + +def _temp_bundle(tmp_path: Path, panels: dict[str, str] | None = None) -> Path: + """A throwaway `web/` carrying a byte-identical copy of the registry. + + The registry resolves a binding's module against the BUNDLE ROOT, so a + fixture panel has to live in a bundle. Copying rather than writing fixtures + into `src/opendox/web/views/` keeps the real bundle exactly the set of files + the census counts — § 4.5 assertion 1 fails an unrowed file, and a fixture + would be one. It also stands in for the ASSEMBLY that RULED Q5 describes: + openXdox's module bytes placed beside openDox's in one served directory. + """ + web = tmp_path / "web" + (web / "views").mkdir(parents=True) + (web / "package.json").write_text( + '{"private": true, "type": "module"}\n', encoding="utf-8") + (web / "views" / "view_extension.js").write_bytes(REGISTRY_JS.read_bytes()) + for name, source in (panels or {}).items(): + (web / "views" / name).write_text(source, encoding="utf-8") + return web + + +# --------------------------------------------------------------------------- +# THE SLICE'S OWN SUCCESS TEST +# --------------------------------------------------------------------------- + +def test_a_student_install_comes_up_with_no_gate_loop_and_no_404() -> None: + """§ 5's S5 row, sentence for sentence, against the real bundle. + + *"a student install comes up with no gate bar, no dispose tray, no session + verbs, and no 404."* A student install is this bundle served with no + openXdox registered: the `/capabilities` payload carries no view manifest + (or none at all, on a static image), so the consumer column is empty. + + FOUR FACTS, EACH MEASURED SEPARATELY, because a single assertion would hide + which one had broken. + """ + app = _app() + census = yaml.safe_load(CENSUS_PATH.read_text(encoding="utf-8")) + rowed = {row["path"] for row in census["files"]} + + # (1) NO GATE BAR, NO DISPOSE TRAY, NO SESSION VERBS — because none of the + # six modules is in the bundle at all, and no census row claims one. + for binding_id, module in CONTRIBUTED.items(): + assert not (VIEWS / module).is_file(), ( + f"views/{module} is still in this bundle; slice S5 moves it to " + "openXdox-code's package data (RULED Q5)") + assert f"views/{module}" not in rowed, ( + f"the census still carries a row for views/{module}") + assert f'id: "{binding_id}"' not in app, ( + f"app.js still declares {binding_id} in its CORE arm, so this shell " + "supplies the gate loop instead of receiving it") + + # (2) NOTHING IMPORTS THEM, so the module graph resolves without them. This + # is the § 1.2(b) failure mode the note names: a dangling static import + # fails the WHOLE module graph, which is a blank page rather than a + # missing panel — "the shell's own module graph does not resolve". + importers = [] + for path in sorted(p for p in WEB.rglob("*.js") if p.is_file()): + text = path.read_text(encoding="utf-8") + for specifier in re.findall(r'from\s*["\'](\.\.?/[^"\']+)["\']', text): + if specifier.rsplit("/", 1)[-1] in CONTRIBUTED.values(): + importers.append(f"{path.relative_to(WEB).as_posix()} -> {specifier}") + assert importers == [], ( + f"{len(importers)} module(s) still import a contributed module: " + f"{importers}. A student install would fail to LOAD rather than render " + "without the gate loop") + + # (3) NO 404 — there is no gate route left in this bundle for anything to + # request. RULED Q12 made the last one (a concatenation the grep could + # not see) into four literals, and they travelled with their module. + requests = [] + for path in sorted(p for p in WEB.rglob("*") if p.is_file() + and p.suffix in (".js", ".html", ".css")): + text = path.read_text(encoding="utf-8", errors="replace") + requests += [f"{path.relative_to(WEB).as_posix()}: {m}" + for m in re.findall(r'"(/actions/gate/[^"]*)"', text)] + assert requests == [], ( + f"{len(requests)} gate route literal(s) survive in this bundle: " + f"{requests}") + + # (4) AND EACH AFFORDANCE IS UNOFFERED RATHER THAN UNDEFINED. The two class-C + # files that used to import the column now read a NULL COLUMN whose + # capability predicates answer false, so every gate control this shell + # can draw is simply not drawn. + wheel = (VIEWS / "wheel.js").read_text(encoding="utf-8") + workbench = (VIEWS / "staging-workbench.js").read_text(encoding="utf-8") + assert "NO_DISPOSE_COLUMN" in wheel and "gateCapable: () => false" in wheel + assert "NO_CREATE_COLUMN" in workbench and "createGateLive: () => false" in workbench + assert "NO_SESSION_COLUMN" in workbench + + +def test_the_shell_falls_back_to_a_refusal_transport_rather_than_a_blank() -> None: + """RULED Q10 (`5648065587`): the workbench transport travels as a declared + non-mount export "with a refusal-shaped fallback when the binding is absent + — never a blank". A Save on a shell with no gate column must SAY so.""" + app = _app() + assert "function refusalTransport()" in app + assert "no_gate_column" in app + assert 'from "./views/swb-session.js"' not in app, ( + "app.js still statically imports the workbench module; RULED Q10 sends " + "`firstEditTransport` through the registry") + assert "workbenchGate.session.firstEditTransport(" in app + assert ": refusalTransport()" in app + + +# --------------------------------------------------------------------------- +# RULED Q2 — the module NAMESPACE, declared +# --------------------------------------------------------------------------- + +def test_a_binding_declares_its_namespace_and_the_entry_is_in_it() -> None: + ok = ViewBinding(id="gate.bar", region="viewer-gatebar", + module="./views/gate.js", entry="mountGateBar", + view_class="B", exports=("mountGateBar", "isGateBearing")) + assert ok.as_manifest_entry()["exports"] == ["mountGateBar", "isGateBearing"] + # EMPTY IS THE PRE-Q2 CONTRACT — `entry` alone — which is what every core-arm + # binding still declares. + assert ViewBinding(id="docs.list", region="view-docs", + module="./views/docs.js", entry="renderDocs", + view_class="A").exports == () + + +@pytest.mark.parametrize("over,fragment", [ + ({"exports": ["mountGateBar"]}, "not a tuple"), + ({"exports": ("not an identifier",)}, "the NAME of an export"), + ({"exports": ("__proto__",)}, "dunder"), + ({"exports": ("isGateBearing",)}, "do not include its own entry"), +]) +def test_a_malformed_exports_tuple_refuses_where_it_is_declared(over, fragment): + spec = dict(id="gate.bar", region="viewer-gatebar", + module="./views/gate.js", entry="mountGateBar", view_class="B") + spec.update(over) + with pytest.raises(ViewBindingError) as excinfo: + ViewBinding(**spec) + assert fragment in str(excinfo.value) + + +@pytest.mark.skipif(NODE is None, reason="node is not installed") +def test_js_an_undeclared_reach_past_the_declaration_refuses(tmp_path) -> None: + """RULED Q2's refusal half, driven against the real registry: "an undeclared + reach (today `isGateBearing`, app.js:939) is a refusal".""" + web = _temp_bundle(tmp_path, {"panel.js": ( + "export function mount() { return 'mounted'; }\n" + "export function declared() { return 'yes'; }\n" + "export function undeclared() { return 'no'; }\n")}) + result = _run_node(f""" +import {{ collectViewBindings, resolveView, ViewBindingError }} + from {json.dumps((web / "views" / "view_extension.js").as_uri())}; +const bindings = collectViewBindings([{{ views: () => [{{ + id: "panel.one", region: "page-overlay", module: "./views/panel.js", + entry: "mount", view_class: "B", exports: ["mount", "declared"], + optional: true }}] }}]); +const resolved = await resolveView(bindings, "panel.one"); +const out = {{ mounted: resolved.exports.mount(), + declared: resolved.exports.declared() }}; +try {{ resolved.exports.undeclared(); out.refused = null; }} +catch (e) {{ out.refused = e.name + ": " + e.message; }} +// `in` STILL SEES THE WHOLE NAMESPACE and that is a language constraint, +// not a gap: a module namespace's exports are non-configurable, so a Proxy +// `has` trap may not hide one. The REACH is what refuses, which is what the +// ruling says the defect is. +out.has = ["mount", "declared", "undeclared"].map((k) => k in resolved.exports); +console.log(JSON.stringify(out)); +""", tmp_path) + assert result["mounted"] == "mounted" and result["declared"] == "yes" + assert result["refused"].startswith("ViewBindingError: ") + assert "does not declare an export named \"undeclared\"" in result["refused"] + assert result["has"] == [True, True, True] + + +@pytest.mark.skipif(NODE is None, reason="node is not installed") +def test_js_a_declared_export_the_module_lacks_refuses_at_resolve(tmp_path) -> None: + web = _temp_bundle(tmp_path, {"panel.js": "export function mount() {}\n"}) + result = _run_node(f""" +import {{ collectViewBindings, resolveView }} + from {json.dumps((web / "views" / "view_extension.js").as_uri())}; +const bindings = collectViewBindings([{{ views: () => [{{ + id: "panel.one", region: "page-overlay", module: "./views/panel.js", + entry: "mount", view_class: "B", exports: ["mount", "missingOne"], + optional: true }}] }}]); +let refused = null; +try {{ await resolveView(bindings, "panel.one"); }} +catch (e) {{ refused = e.message; }} +console.log(JSON.stringify({{ refused }})); +""", tmp_path) + assert "declares export \"missingOne\"" in result["refused"] + assert "must not look registered" in result["refused"] + + +# --------------------------------------------------------------------------- +# RULED Q4 — `requires`, evaluated +# --------------------------------------------------------------------------- + +@pytest.mark.skipif(NODE is None, reason="node is not installed") +def test_js_an_unmet_requirement_is_an_absence_or_a_refusal(tmp_path) -> None: + """RULED Q4 (`5648049748`): "`requires` names DOTTED PATHS into the + `/capabilities` payload; unmet + `optional: true` renders the region empty + with a NAMED reason; unmet + required REFUSES, naming the binding, the path + and the probed value".""" + web = _temp_bundle(tmp_path, {"panel.js": "export function mount() { return 1; }\n"}) + result = _run_node(f""" +import {{ collectViewBindings, resolveView, probeCapabilityPath, + unmetRequirement }} + from {json.dumps((web / "views" / "view_extension.js").as_uri())}; +const spec = (over) => ({{ + id: "panel.one", region: "page-overlay", module: "./views/panel.js", + entry: "mount", view_class: "B", requires: ["actions.gate"], + optional: true, ...over }}); +const optional = collectViewBindings([{{ views: () => [spec({{}})] }}]); +const required = collectViewBindings([ + {{ views: () => [spec({{ optional: false }})] }}]); +const live = {{ actions: {{ gate: true }} }}; +const off = {{ actions: {{ gate: false }} }}; +const out = {{ + path_live: probeCapabilityPath(live, "actions.gate"), + path_missing: probeCapabilityPath({{ actions: {{}} }}, "actions.gate") ?? null, + path_through_nothing: probeCapabilityPath(null, "actions.gate") ?? null, + unmet_off: unmetRequirement(optional[0], off), + unmet_live: unmetRequirement(optional[0], live), + optional_off: await resolveView(optional, "panel.one", {{ capabilities: off }}), +}}; +out.optional_live = !!(await resolveView(optional, "panel.one", + {{ capabilities: live }})); +try {{ + await resolveView(required, "panel.one", {{ capabilities: off }}); + out.required_off = null; +}} catch (e) {{ out.required_off = e.message; }} +out.required_live = !!(await resolveView(required, "panel.one", + {{ capabilities: live }})); +console.log(JSON.stringify(out)); +""", tmp_path) + assert result["path_live"] is True + assert result["path_missing"] is None and result["path_through_nothing"] is None + assert result["unmet_off"] == {"path": "actions.gate", "value": False} + assert result["unmet_live"] is None + # OPTIONAL + UNMET: an absence the caller already knows how to read. + assert result["optional_off"] is None + assert result["optional_live"] is True + # REQUIRED + UNMET: a refusal naming the binding, the path and the value. + assert "panel.one" in result["required_off"] + assert "actions.gate" in result["required_off"] + assert result["required_live"] is True + + +# --------------------------------------------------------------------------- +# RULED Q1 — the generic mount pass +# --------------------------------------------------------------------------- + +@pytest.mark.skipif(NODE is None, reason="node is not installed") +def test_js_the_shell_mounts_contributed_dom_bindings_generically(tmp_path) -> None: + """RULED Q1 (`5648044785`): "one mount pass over every contributed binding + whose region is a `dom` region; the three `shell` regions stay + caller-driven". Before this, a column could contribute a binding and have + nothing ever call it.""" + web = _temp_bundle(tmp_path, { + "panel.js": ("export function mount(host, snapshot, ctx) {\n" + " host.mounted = { snapshot, caps: ctx.caps };\n" + " return 'ok';\n}\n"), + }) + result = _run_node(f""" +import {{ collectViewBindings, mountContributedViews }} + from {json.dumps((web / "views" / "view_extension.js").as_uri())}; +const hosts = {{}}; +const made = []; +const doc = {{ + getElementById: (id) => hosts[id] || null, + createElement: (tag) => {{ + const node = {{ tag, children: [], attrs: {{}}, textContent: "", + className: "", + setAttribute(k, v) {{ this.attrs[k] = v; }}, + appendChild(c) {{ this.children.push(c); return c; }} }}; + made.push(node); + return node; + }}, +}}; +for (const id of ["view-docs", "explorer-root"]) {{ + hosts[id] = {{ id, children: [], appendChild(c) {{ this.children.push(c); }} }}; +}} +const bindings = collectViewBindings([{{ views: () => [ + // a dom region: the pass mounts it + {{ id: "panel.one", region: "view-docs", module: "./views/panel.js", + entry: "mount", view_class: "B", optional: true }}, + // a SHELL region: caller-driven, never touched by the pass + {{ id: "panel.shell", region: "page-overlay", module: "./views/panel.js", + entry: "mount", view_class: "B", optional: true }}, + // a dom region with an UNMET optional requirement: empty, with a NAMED reason + {{ id: "panel.unmet", region: "explorer-root", module: "./views/panel.js", + entry: "mount", view_class: "B", requires: ["actions.gate"], + optional: true }}, +]}}]); +const results = await mountContributedViews( + bindings, {{ repository: "r" }}, {{ caps: {{ actions: {{ gate: false }} }} }}, + {{ document: doc, capabilities: {{ actions: {{ gate: false }} }} }}); +console.log(JSON.stringify({{ + seen: results.map((r) => [r.binding.id, r.mounted, r.skipped]), + mounted: hosts["view-docs"].mounted, + reason: made.map((n) => [n.className, n.attrs["data-view"], n.textContent]), +}})); +""", tmp_path) + seen = {row[0]: row for row in result["seen"]} + # the `dom`-region binding mounted, with RULED Q3's signature + assert seen["panel.one"][1] == "ok" and seen["panel.one"][2] is None + assert result["mounted"] == {"snapshot": {"repository": "r"}, + "caps": {"actions": {"gate": False}}} + # the `shell`-region binding is not in the pass at all + assert "panel.shell" not in seen + # the unmet optional: skipped, with the reason written INTO its region + assert seen["panel.unmet"][2] == "requires" + assert result["reason"] == [["viewrefusal", "panel.unmet", + result["reason"][0][2]]] + assert "panel.unmet" in result["reason"][0][2] + assert "actions.gate" in result["reason"][0][2] + + +# --------------------------------------------------------------------------- +# RULED Q8 / Q9 — the regions +# --------------------------------------------------------------------------- + +@pytest.mark.parametrize("region", NEW_REGIONS) +def test_the_new_regions_are_declared_shell_regions_in_both_halves(region) -> None: + assert REGIONS.get(region) == "shell", ( + f"{region} is not declared a `shell` region in the Python half") + assert region not in dom_regions() + js = REGISTRY_JS.read_text(encoding="utf-8") + assert f'"{region}": "shell",' in js, ( + f"{region} is missing from the client mirror's REGIONS table; the two " + "halves are one vocabulary or they are two seams") + + +def test_the_page_overlay_host_is_built_by_the_shell_not_by_index_html() -> None: + """RULED Q8 (`5648049748`): "a fourth `shell` region, `page-overlay`, is the + declared host for page-level panels (dispose.js's refusal panel); + `document.body` is never a contract surface." + + It is a `shell` region rather than a `dom` one for a floor reason, and the + reason is worth a test: `src/opendox/web/index.html` is a `moved_verbatim` + row of openxFactory's carve manifest, whose declared-edit vocabulary is the + RULED closed list `import rewrites | path constants | adapter calls`, and an + added element is in none of them. So the shell builds the host. + """ + app = _app() + assert 'PAGE_OVERLAY_REGION = "page-overlay"' in app + assert "function ensurePageOverlayHost(" in app + assert "ensurePageOverlayHost();" in app + index = (WEB / "index.html").read_text(encoding="utf-8") + assert 'id="page-overlay"' not in index, ( + "index.html grew a `page-overlay` element: that file is a " + "`moved_verbatim` carve row and an added element is in none of its " + "declared edit classes") + + +@pytest.mark.parametrize("region", ["wheel-intent", "dispose-intent"]) +def test_the_two_unhosted_regions_stand_declared_and_unread(region) -> None: + """RULED Q9 (`5648065587`): they "stay DECLARED in both REGIONS tables, + recorded as unhosted and unread today (S2 landed as + `views/intent-binding.js`); a future intent panel has its slot." + + S5 is not the slice that retires S2's provision — and a binding naming one + today would mount into nothing, which is why "unread" is measured rather + than assumed. + """ + assert REGIONS.get(region) == "shell" + assert f'"{region}": "shell",' in REGISTRY_JS.read_text(encoding="utf-8") + index = (WEB / "index.html").read_text(encoding="utf-8") + assert f'id="{region}"' not in index, f"{region} grew a host element" + readers = [] + for path in sorted(p for p in WEB.rglob("*.js") if p.is_file()): + if path.name == "view_extension.js": + continue # the declaration itself + # CODE, NOT PROSE. `app.js`'s own comment explains why slice S2's chips + # fold into this registry without re-opening it, and naming a region in + # a sentence is not reading it. + code = "\n".join(line for line in + path.read_text(encoding="utf-8").splitlines() + if not line.lstrip().startswith("//")) + if region in code: + readers.append(path.relative_to(WEB).as_posix()) + assert readers == [], ( + f"{region} is read by {readers}; RULED Q9 records it as unhosted AND " + "unread, and a reader would make that record false") + + +# --------------------------------------------------------------------------- +# RULED Q11 — what a human sees when the registry refuses +# --------------------------------------------------------------------------- + +def test_a_registry_refusal_is_not_framed_as_a_snapshot_defect() -> None: + """RULED Q11 (`5648065587`). The seam already composed the right sentence; + only the frame around it was wrong — every `ViewBindingError` was reported + as "Could not load the snapshot (…) regenerate it and reload", so a column + debugging its own contribution was told to regenerate a snapshot that is + fine.""" + app = _app() + assert "err instanceof ViewBindingError" in app + assert 'err.name === "ViewBindingError"' in app, ( + "the name check is the cross-realm half: a refusal raised in a worker " + "or a harness does not satisfy `instanceof`") + assert "The snapshot is fine — the assembly is not" in app + # the snapshot frame SURVIVES for everything that is not a registry refusal + assert "Could not load the snapshot (" in app + assert "ViewBindingError" in re.search( + r"\} catch \(err\) \{(.*?)\n \}", app, re.S).group(1) + + +# --------------------------------------------------------------------------- +# The seam, assembled — the Python half +# --------------------------------------------------------------------------- + +def test_the_manifest_carries_the_declared_namespace_across_the_boundary() -> None: + binding = ViewBinding( + id="gate.dispose", region="page-overlay", module="./views/dispose.js", + entry="mountRefusalPanel", view_class="B", + routes=("/actions/gate/dispose-possible", "/actions/gate/demote"), + exports=("mountRefusalPanel", "panelEntry"), + requires=("actions.gate",), optional=True) + manifest = view_manifest(collect_view_bindings([type("X", (), { + "views": lambda self: (binding,)})()]), host_facet="declared", + host_profile="openxdox") + entry = manifest["views"][0] + assert entry["exports"] == ["mountRefusalPanel", "panelEntry"] + assert entry["requires"] == ["actions.gate"] + assert entry["routes"] == ["/actions/gate/dispose-possible", + "/actions/gate/demote"] + assert manifest["regions"]["page-overlay"] == "shell" + + +def test_the_serve_publishes_the_manifest_on_capabilities() -> None: + """The ONE line slice S3 built both ends of and deliberately did not write: + `opendox/view_extension.py` — "The ONE line that puts it there + (`capabilities["views"] = view_manifest(...)` in `serve.build_server`) is + NOT written by slice S3 ... S5, the slice at which a contribution first + EXISTS to deliver, joins them.""" + serve = (ROOT / "src" / "opendox" / "serve.py").read_text(encoding="utf-8") + assert 'capabilities["views"] = view_extension.view_manifest(' in serve + assert "view_extension.host_view_extensions(profile_openxfactory)" in serve + assert "view_extension.collect_view_bindings(" in serve + # the SAME contributed routes the server was assembled with, so both halves + # of the seam check § 2.2 rule 1 against the same facts + assert "contributed_routes=route_bindings" in serve + + +def test_the_census_totals_and_the_class_b_remainder() -> None: + """After S5 exactly ONE class-B file is left in this bundle, and it is not + the gate loop's: `views/projection-index.js` is openXdox's PROJECTION + column's one read, which slice S6 re-homes.""" + census = yaml.safe_load(CENSUS_PATH.read_text(encoding="utf-8")) + class_b = sorted(row["path"] for row in census["files"] + if row["class"] == "B") + assert class_b == ["views/projection-index.js"], class_b + assert census["totals"]["B"]["files"] == 1 From 0018acd5044b1173be25c9f499a0dbf1d55b500c Mon Sep 17 00:00:00 2001 From: Brett Heap Date: Sat, 12 Sep 2026 16:02:15 -0400 Subject: [PATCH 17/44] Package the served bundle, so RULED Q5's assembly hook has a directory to copy into MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit MEASURED, not suspected: `setuptools` puts `*.py` into a wheel and nothing else unless a package declares otherwise, and this `pyproject.toml` declared nothing — so `pip install opendox` produced a package with no `opendox/web/` at all. An INSTALLED openDox could not serve the dashboard; only a source checkout could, and nothing noticed because every consumer to date has been an editable install. Same class of defect as RULED Q-L8 (a)'s `py-modules` gap, one directory over. SLICE S5 IS THE SLICE THAT HAS TO CLOSE IT. RULED Q5 (openxFactory#656 comment 5648044785) makes the composed deployment assemble the bundle — openXdox ships its six view modules as package data and the install copies them into openDox's one `--web-dir`. A wheel with no `web/` gives that copy nowhere to land, which would force every composed install onto the hosted GET fallback by a packaging omission rather than a deployment choice. `pyproject.toml` is a CREATED file (RULED OQ-C): no carve-manifest row. Lane: openxfactory-4-opendox-extraction Refs opensoft/openxFactory#656 Co-Authored-By: Claude Opus 5 --- pyproject.toml | 33 +++++++++++++++++++++++++++++++++ 1 file changed, 33 insertions(+) diff --git a/pyproject.toml b/pyproject.toml index 3b90ead8..41907fdc 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -116,6 +116,39 @@ py-modules = ["route_extension", "subcommand_extension"] [tool.setuptools.packages.find] where = ["src"] +# THE SERVED BUNDLE, PACKAGED — § 3.4 slice S5, and it is a gap this slice had +# to close to make RULED Q5 true rather than true-in-a-source-checkout. +# +# THE MEASUREMENT. `setuptools` puts `*.py` into a wheel and nothing else unless +# a package declares otherwise, and this file declared nothing, so +# `pip install opendox` produced a package with NO `opendox/web/` in it at all: +# no `app.js`, no `index.html`, no `styles.css`, no `views/`. `build_server()` +# serves ONE directory and its default `--web-dir` is that directory, so an +# INSTALLED openDox could not serve the dashboard — only a source checkout +# could. Nothing noticed because every consumer to date has been an editable +# install, which puts `src/` on the path directly instead of packaging it. It is +# the same class of defect RULED Q-L8 (a) found in `py-modules` above, one +# directory over. +# +# WHY SLICE S5 IS THE SLICE THAT CLOSES IT. RULED Q5 (openxFactory#656 comment +# `5648044785`, Brett Heap, 2026-09-12) makes the COMPOSED DEPLOYMENT assemble +# the bundle: "openXdox ships its view modules as package data; the composed +# install copies them into openDox's one `--web-dir` at assembly". openXdox's +# `openxdox.web_assets.install_view_modules(web_dir)` copies INTO this +# directory — so if a wheel install has no directory to copy into, the primary +# mechanism of Q5 has nowhere to run and every composed install is forced onto +# the hosted GET fallback by a packaging omission rather than by a deployment +# choice. +# +# `web/**` and not a list: the bundle is 41 files across one subdirectory and +# grows by feature, and a hand-kept list would drift the first time a view is +# added. `tests/test_web_boundary.py`'s census is what holds the DIRECTORY +# honest — every file under `src/opendox/web/` carries a declared row with a +# class, and an unrowed file fails immediately — so the glob here ships exactly +# what that census counts rather than whatever happens to be on disk. +[tool.setuptools.package-data] +opendox = ["web/**"] + [tool.pytest.ini_options] # The ROOTDIR ANCHOR. With no pytest ini table anywhere, pytest infers a # rootdir from the arguments it is handed, so `pytest -q` and `pytest tests/` From 74923118a213af8e6f8b773f35b192fa3c6b3e6c Mon Sep 17 00:00:00 2001 From: Brett Heap <1513478+brettheap@users.noreply.github.com> Date: Sat, 12 Sep 2026 18:41:58 -0400 Subject: [PATCH 18/44] =?UTF-8?q?=C2=A7=203.4=20S5,=20leg=20B:=20RULED=20c?= =?UTF-8?q?ounterpart=20Q6=20=E2=80=94=20the=20shell=20hands=20down=20what?= =?UTF-8?q?=20the=20column=20may=20no=20longer=20import?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit RULED counterpart Q6 (opensoft/openxFactory#656 comment `5649094228`, Brett Heap, 2026-09-12, by interactive multi-choice): "what a CONTRIBUTED view module may IMPORT from openDox's bundle: `./views/helpers.js` and NOTHING ELSE. Every other need reaches the binding through its `ctx` (Q1-Q4) or its own package (Q5)." The same comment CORRECTS `5648065587`: the sitting's first batch put the BOUNDARY note's Q6 to Brett Heap, not the COUNTERPART note's, so this question was still open while both legs of S5 were authored. openXdox's half closes the reach (openXdox-code#18). THIS half has the other obligation: every name the four modules used to import statically has to arrive on the ctx this shell composes, or the rule turns a working affordance into a refusal. * `views/gate-lens.js` took `{ clusterRequest, recipeRequest }` from `views/lens-model.js`. `app.js`'s `mountLensGate` adapter — where the binding's context is already composed — now spreads `lctx` and adds `model: lensModel`. `views/lens.js`, which builds `lctx`, is untouched and knows nothing about the contributed column's needs. * `views/swb-create.js` and `views/swb-session.js` took five and nine names from `views/staging-workbench-model.js`. `views/staging-workbench.js` imports the NAMESPACE and hands it down at the create column's shared options builder, at the session mount and at the doxBench create dialog; `app.js` hands it to `firstEditTransport`, RULED Q10's non-mount export, whose ctx is the options object it already takes. * `views/dispose.js` took `{ emitIntent, renderIntentChips }` from `views/intent-binding.js` and fell back to `emitIntent` when the hosted context carried no emitter. A fallback into a module a contributed binding may not import is a refusal, not a default: `views/wheel.js`, which starts the feed and builds that context, now supplies `emit` and `renderChips` with it. THE NAMESPACE AND NOT A PICKED SET. The binding declares which names it needs (openXdox's `CTX_MODEL_REACH`) and refuses BY NAME at the mount when one is missing; re-listing them here would put a second, staler copy of that contract in the file that supplies it. Four tests, one per supply site plus a guard that no shell file imports one of the six contributed modules back — § 4.5 assertion 3's breach reopened from the other side would be the obvious way to "fix" a missing facet. Census `loc` rows and the class totals re-measured for the three edited files. Lane: openxfactory-4-opendox-extraction Refs opensoft/openxFactory#656 Co-Authored-By: Claude Opus 5 --- src/opendox/web/app.js | 26 +++++++- src/opendox/web/views/staging-workbench.js | 23 +++++++ src/opendox/web/views/wheel.js | 17 ++++- tests/fixtures/web_boundary_census.yaml | 10 +-- tests/test_gate_loop_contributed.py | 76 ++++++++++++++++++++++ 5 files changed, 144 insertions(+), 8 deletions(-) diff --git a/src/opendox/web/app.js b/src/opendox/web/app.js index 4c8f3f80..a4fc0fc3 100644 --- a/src/opendox/web/app.js +++ b/src/opendox/web/app.js @@ -67,6 +67,16 @@ import { mountStagingWorkbench } from "./views/staging-workbench.js"; // `refusalTransport` is the fallback. import { createModelIntakeTransports } from "./views/swb-model-intake.js"; import { CONSOLE_TOKEN_FIELD } from "./views/staging-workbench-model.js"; +// THE TWO MODELS THE CONTRIBUTED GATE COLUMN REACHES THROUGH `ctx` — RULED +// counterpart Q6 (opensoft/openxFactory#656 comment `5649094228`, Brett Heap, +// 2026-09-12): "what a CONTRIBUTED view module may IMPORT from openDox's +// bundle: `./views/helpers.js` and NOTHING ELSE. Every other need reaches the +// binding through its `ctx` (Q1-Q4) or its own package (Q5)." Both namespaces +// are openDox's own pure models; the shell hands them to the bindings that used +// to import them (`views/gate-lens.js`, `views/swb-session.js`), at the two +// sites below where their context is composed. +import * as lensModel from "./views/lens-model.js"; +import * as workbenchModel from "./views/staging-workbench-model.js"; import { runSave, savePlanState } from "./views/doxbench-save.js"; import { contentIdentity } from "./views/doxbench-state.js"; import { initSettings } from "./views/settings.js"; @@ -1248,7 +1258,10 @@ async function render() { savePlanState(request), { transport: workbenchGate.session ? workbenchGate.session.firstEditTransport( - { caps, repair: consoleRepair }) + // RULED counterpart Q6: this export is reached through the + // registry and not through a mount, so openDox's model reaches + // it as a field of the options object it already takes. + { caps, repair: consoleRepair, model: workbenchModel }) : refusalTransport(), ...(request && request.only !== undefined ? { only: request.only } : {}) }), @@ -1364,9 +1377,18 @@ async function render() { // re-review fix, applied to S4's two mounts for the same reason: a // contributed binding names its entry in the manifest, and reading // anything else here would silently ignore the name it declared). + // RULED counterpart Q6 (openxFactory#656 comment `5649094228`, Brett + // Heap, 2026-09-12): a contributed view module may import + // `./views/helpers.js` and nothing else, so `views/gate-lens.js` — + // openXdox's package data since slice S5 — reaches openDox's lens model + // through `ctx.model` instead of importing `./lens-model.js`. The + // adapter supplies it HERE, where the binding's context is already being + // composed, so `views/lens.js` (which builds `lctx`) needs no change and + // knows nothing about the contributed column's needs. mountLensGate: lensGateView ? (host, lctx) => - lensGateView.exports[lensGateView.binding.entry](host, snapshot, lctx) + lensGateView.exports[lensGateView.binding.entry]( + host, snapshot, { ...lctx, model: lensModel }) : null, // the UNSTRIPPED probe and the serve's own writable repository — read by // exactly one affordance (see `createCaps` at the lens's mount) diff --git a/src/opendox/web/views/staging-workbench.js b/src/opendox/web/views/staging-workbench.js index dd089395..a9a8a307 100644 --- a/src/opendox/web/views/staging-workbench.js +++ b/src/opendox/web/views/staging-workbench.js @@ -82,6 +82,21 @@ import { documentAbstract, docWheelEntries, existingOnTopic, abstractRegionState, abstractSubjectDigest, } from "./staging-workbench-model.js"; +// THE MODEL, AS A NAMESPACE, BECAUSE THE CONTRIBUTED COLUMN REACHES IT THROUGH +// `ctx` — RULED counterpart Q6 (opensoft/openxFactory#656 comment `5649094228`, +// Brett Heap, 2026-09-12): "what a CONTRIBUTED view module may IMPORT from +// openDox's bundle: `./views/helpers.js` and NOTHING ELSE. Every other need +// reaches the binding through its `ctx` (Q1-Q4) or its own package (Q5)." +// +// `views/swb-create.js` and `views/swb-session.js` took five and nine names +// from this model by static import while they lived in this bundle. They are +// openXdox's package data now, and the model is still openDox's — so the SHELL +// hands it down at the mount, in the ctx it already builds, and openDox keeps +// the one definition of its own request bodies. The namespace and not a picked +// set: the binding declares which names it needs (`CTX_MODEL_REACH`) and +// refuses by name when one is missing, which is a contract this file cannot +// improve on by re-listing it. +import * as workbenchModel from "./staging-workbench-model.js"; import { renderDocWheel } from "./doc-wheel.js"; import { buildLensModel } from "./lens-model.js"; import { renderBullseye } from "./bullseye.js"; @@ -1795,6 +1810,9 @@ export function mountStagingWorkbench(container, snapshot, return { caps, fetcher, repair: consoleRepair, slot: (extra || {}).slot, label: CREATE_LABELS[activeTab], + // RULED counterpart Q6: openDox's model, handed to the contributed + // binding rather than imported by it. + model: workbenchModel, // task 5.8: land on the document, not on a path string. The snapshot // predates the new file, so the viewer resolves it through the same // read-only source pass-through every other document read uses. @@ -1877,6 +1895,9 @@ export function mountStagingWorkbench(container, snapshot, // set can shadow the other; the old call passed the context second and the // seams third. sessionColumn.mountSessionAffordances(sessionhost, snapshot, { + // RULED counterpart Q6: openDox's model, handed to the contributed + // binding rather than imported by it. + model: workbenchModel, session: { scope, posture, @@ -3238,6 +3259,8 @@ export function mountStagingWorkbench(container, snapshot, // RULED Q3: `mount(host, snapshot, ctx)`, the seed under `ctx.seed`. createColumn.openCreateDialog(detailsPane, shellSnapshot, { seed, + // RULED counterpart Q6 (see the namespace import at the head). + model: workbenchModel, caps: authoring, fetcher, repair: consoleRepair, label: "create document", // SAVE, not create (Brett, 2026-08-10: "it seems to the user that we diff --git a/src/opendox/web/views/wheel.js b/src/opendox/web/views/wheel.js index b2adbecc..4f5498f6 100644 --- a/src/opendox/web/views/wheel.js +++ b/src/opendox/web/views/wheel.js @@ -106,7 +106,15 @@ const NO_DISPOSE_COLUMN = Object.freeze({ //: threading a per-render object through it would mean giving every mounter a //: ninth parameter that only exists to be forwarded. let disposeColumn = NO_DISPOSE_COLUMN; -import { feedActor, intentCapable, refusalLine, startIntentFeed, statesByTarget } +// `emitIntent` and `renderIntentChips` join this import for the CONTRIBUTED +// tray's sake — RULED counterpart Q6 (opensoft/openxFactory#656 comment +// `5649094228`, Brett Heap, 2026-09-12): a contributed view module may import +// `./views/helpers.js` and nothing else, so `views/dispose.js` (openXdox's +// package data since slice S5) reaches this module's emitter and chip renderer +// through the `intent` context THIS file already builds for it, and never +// through a static import of its own. +import { emitIntent, feedActor, intentCapable, refusalLine, renderIntentChips, + startIntentFeed, statesByTarget } from "./intent-binding.js"; import { notebookCapable } from "./notebook.js"; import { SETTINGS_EVENT, currentDrumFactor } from "./settings.js"; @@ -1546,6 +1554,13 @@ export function renderWheel(root, snapshot, ctx) { onApplied: () => { railKey = ""; drawAll(); }, onEmitted: () => { railKey = ""; drawAll(); if (intentFeed) intentFeed.refresh(); }, intent: hosted ? { + // RULED counterpart Q6: the EMITTER and the CHIP RENDERER travel + // with the rest of the hosted context. The tray used to fall back + // to `emitIntent` through an import of its own; a fallback into a + // module a contributed binding may not import is a refusal, not a + // default, so the transport is supplied here or the tray refuses. + emit: emitIntent, + renderChips: renderIntentChips, // D4: the revision the human is LOOKING at, full and unabbreviated // (the header renders a 12-char prefix of this same field). snapshotRev: snapshot?.generation?.source_revision || "", diff --git a/tests/fixtures/web_boundary_census.yaml b/tests/fixtures/web_boundary_census.yaml index 42c477fc..ab192f44 100644 --- a/tests/fixtures/web_boundary_census.yaml +++ b/tests/fixtures/web_boundary_census.yaml @@ -181,14 +181,14 @@ measured_at: "opensoft/openDox-code main a99eba03e31a0aee1cc15a061fdf718cc88a2c4 # shape and `test_the_declared_totals_are_re_derived_from_the_rows` can refuse a # drift between the two. Measured at slice S4 (see the S4 block above). totals: - A: {files: 25, loc: 16706} + A: {files: 25, loc: 16728} B: {files: 1, loc: 73} - C: {files: 14, loc: 11952} + C: {files: 14, loc: 11990} "?": {files: 1, loc: 1435} files: - path: app.js class: A - loc: 1456 + loc: 1478 note: "the shell; its only class-B import was gate.js at :43 (discharged by S3's view registry -- loc 1155 -> 1282 with the registry wiring, S3; 1282 -> 1337 with S4's two new gate bindings and the two mounts it hands down). Carries SIX transitional route-ownership sites, all in the CORE arm's class-B binding entries and all cleared at S5 when those entries leave for contributedViewBindings(): gate.bar's one route (S3) and gate.lens's and gate.projects's two each (S4). Declaring them is RULED Q3 working -- view_extension.py: 'a binding that declares the routes it calls is what makes that ruling checkable instead of aspirational' -- and it is a real breach by assertion 2's own rule only while the entry sits in app.js (class A) rather than in the class-B module (exempt by construction)" - path: index.html @@ -369,7 +369,7 @@ files: - path: views/staging-workbench.js class: C - loc: 3374 + loc: 3397 note: "full-screen workbench scoped to one topic-bearing tile" - path: views/swb-model-intake.js @@ -394,7 +394,7 @@ files: - path: views/wheel.js class: C - loc: 1741 + loc: 1756 note: "THE WHEEL; imports dispose.js (class B) and intent-feed.js (absent, RULED openxFactory); SOURCE_ROUTE :97" # ASSERTION 1's ONE DECLARED, RULED-LATER EXCEPTION (note § 4.5 point 1). After diff --git a/tests/test_gate_loop_contributed.py b/tests/test_gate_loop_contributed.py index 69ed0771..55d63c32 100644 --- a/tests/test_gate_loop_contributed.py +++ b/tests/test_gate_loop_contributed.py @@ -539,3 +539,79 @@ def test_the_census_totals_and_the_class_b_remainder() -> None: if row["class"] == "B") assert class_b == ["views/projection-index.js"], class_b assert census["totals"]["B"]["files"] == 1 + + +# --------------------------------------------------------------------------- +# RULED counterpart Q6 — the SHELL's half: what a contributed module may not +# import, the shell hands it. +# +# RULED counterpart Q6 (opensoft/openxFactory#656 comment `5649094228`, Brett +# Heap, 2026-09-12): "what a CONTRIBUTED view module may IMPORT from openDox's +# bundle: `./views/helpers.js` and NOTHING ELSE. Every other need reaches the +# binding through its `ctx` (Q1-Q4) or its own package (Q5)." +# +# The bindings enforce the rule on openXdox's side. THIS side has the other +# obligation: every name the four modules used to import statically has to +# arrive on the ctx the shell composes, or the rule turns a working affordance +# into a refusal. Each assertion below names the site that supplies it. +# --------------------------------------------------------------------------- + +def test_the_shell_hands_the_lens_gate_the_model_it_no_longer_imports() -> None: + """`views/gate-lens.js` imported `{ clusterRequest, recipeRequest }` from + `views/lens-model.js`. It is openXdox's package data now, so the adapter + that composes its context supplies the model namespace instead — in + `app.js`, where the binding's context is already being built, so + `views/lens.js` (which builds `lctx`) needs no change at all.""" + app = _app() + assert 'import * as lensModel from "./views/lens-model.js";' in app + assert re.search( + r"mountLensGate: lensGateView\s*\n\s*\? \(host, lctx\) =>\s*\n\s*" + r"lensGateView\.exports\[lensGateView\.binding\.entry\]\(\s*\n\s*" + r"host, snapshot, \{ \.\.\.lctx, model: lensModel \}\)", app), app + + +def test_the_shell_hands_the_workbench_column_the_model_it_no_longer_imports() -> None: + """`views/swb-create.js` and `views/swb-session.js` took five and nine names + from `views/staging-workbench-model.js`. The overlay that mounts them hands + the namespace down at every call site that carries a ctx, and `app.js` hands + it to `firstEditTransport` — RULED Q10's non-mount export, reached through + the registry, whose ctx is the options object it already takes.""" + workbench = (VIEWS / "staging-workbench.js").read_text(encoding="utf-8") + assert ('import * as workbenchModel from "./staging-workbench-model.js";' + in workbench) + # the create column's shared options builder, the session mount, and the + # doxBench create dialog's own literal context + assert workbench.count("model: workbenchModel,") == 3, workbench.count( + "model: workbenchModel,") + app = _app() + assert ('import * as workbenchModel from "./views/staging-workbench-model.js";' + in app) + assert "{ caps, repair: consoleRepair, model: workbenchModel }" in app + + +def test_the_shell_hands_the_dispose_tray_the_intent_transport() -> None: + """`views/dispose.js` imported `{ emitIntent, renderIntentChips }` from + `views/intent-binding.js` and fell back to `emitIntent` when the hosted + context carried no emitter. A fallback into a module a contributed binding + may not import is a refusal, not a default, so `views/wheel.js` — which + starts the feed and builds the hosted context — supplies both.""" + wheel = (VIEWS / "wheel.js").read_text(encoding="utf-8") + assert re.search(r"import \{ emitIntent, feedActor, intentCapable, " + r"refusalLine, renderIntentChips,\s*\n\s*startIntentFeed, " + r'statesByTarget \}\s*\n\s*from "\./intent-binding\.js";', + wheel), wheel + assert "emit: emitIntent," in wheel + assert "renderChips: renderIntentChips," in wheel + + +def test_no_shell_file_reaches_into_the_contributed_column_to_supply_it() -> None: + """The shell supplies the contributed column through ctx and NEVER by + importing one of the six modules back — that would be § 4.5 assertion 3's + breach reopened from the other side, one slice after it closed.""" + gone = ("gate.js", "dispose.js", "swb-create.js", "swb-session.js", + "gate-lens.js", "gate-projects.js") + for path in [APP_JS, *sorted(VIEWS.glob("*.js"))]: + text = path.read_text(encoding="utf-8") + for module in gone: + assert not re.search(rf'^import .*from "\./(?:views/)?{re.escape(module)}"', + text, re.M), (path.name, module) From 80b1f3bc60499ebbd84e69aaba40ef243c24a54a Mon Sep 17 00:00:00 2001 From: Brett Heap <1513478+brettheap@users.noreply.github.com> Date: Sat, 12 Sep 2026 18:45:42 -0400 Subject: [PATCH 19/44] =?UTF-8?q?=C2=A7=203.4=20S7:=20the=20display=20face?= =?UTF-8?q?t,=20and=20the=20one=20context=20key=20that=20carries=20it?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit `docs/front-end-package-boundary.md` § 4.3 names five steps and this commit is the first three of them: the host's DISPLAY facet, published on the payload the shell already fetches, read by ROLE and handed to every view through `ctx`. * `src/opendox/display_profile.py` (created; no manifest row, RULED OQ-C) — the facet's server half. `PROFILE_FACET = "DISPLAY"` beside `ROUTE_EXTENSIONS`, `SUBCOMMAND_EXTENSIONS` and `VIEW_EXTENSIONS`: one composite profile, one registration, four facets, all through the same lazy proxy. `STAGE_ROLES`, `STATUS_ROLES`, `AREA_ROLES`, `TOKEN_ROLES` are the declared vocabulary, and every one of them is a ROLE — a position in the pipeline — because openXdox-spec `docs/domain-profile-design-note.md` § 6 rules that a profile whose organized status is spelled `triaged` must work with no engine change. A partial declaration is legal and filled per field from the neutral words; an unknown role, a blank word or a token that is not `#rrggbb` is a `DisplayFacetError` where the server is built. * `serve.py` — `capabilities["display"]`, beside S5's `capabilities["views"]` and for § 4.3 step 2's own stated reason: "no new route and no second fetch". * `src/opendox/web/views/display.js` (created) — the client half. `readDisplay`, `Display.label/one/many/short/gate/status/area/token/items`, all by role, and `applyTokens` for the four `--st-*` custom properties § 4.3 point 4 sets on `:root` at boot. An unknown role is a `DisplayRoleError` naming the declared set, never `undefined`. * `app.js` — reads the facet once per render, sets the four tokens on `:root` before anything mounts, and adds ONE key to the context object every view and every contributed binding already receives. * `view_extension.py` / `view_extension.js` — `CTX_KEYS`, the context object's declared shape, mirrored in both halves as REGIONS already is. The counterpart note asks what a binding may assume about "the context object's shape"; a shape that is only ever an object literal in `app.js` is an assumption. ABSENT IS NEUTRAL, AND THAT IS A DEPARTURE FROM § 4.3 POINT 5 STATED IN FULL. The note says "refusal, not a default", and its argument is that "a fallback to TODAY'S WORDS is how the literals survive the refactor invisibly". `NEUTRAL_DISPLAY` is the opposite of today's words: it is openDox's own plain vocabulary — `sources → groups → candidates → selections → submissions → completions` — so a shell with no host facet is VISIBLY un-domained rather than invisibly re-domained, which is RULING OQ-2's student install and § 2.1's own test for class C performed by the product instead of asserted about it. The absence is NAMED on the payload (`host_facet: "absent"` with the profile), on `host_view_extensions`' own precedent; a facet that IS declared and malformed still fails closed. SNAPSHOT_FIELDS is § 2.2 rule 3's other half, declared once in a class-A module and carried in the census as a declared exemption with its reason: the snapshot's own field names and the closed `changes[].status` enum are openDox's SCHEMA, not a domain's mapping, so the fourteen class-C files can read the snapshot through a role and carry none of them. Lane: openxfactory-4-opendox-extraction Refs opensoft/openxFactory#656 Co-Authored-By: Claude Opus 5 --- src/opendox/display_profile.py | 488 ++++++++++++++++++++++++ src/opendox/serve.py | 34 ++ src/opendox/view_extension.py | 24 ++ src/opendox/web/app.js | 35 +- src/opendox/web/views/display.js | 356 +++++++++++++++++ src/opendox/web/views/view_extension.js | 27 ++ tests/fixtures/web_boundary_census.yaml | 24 +- 7 files changed, 981 insertions(+), 7 deletions(-) create mode 100644 src/opendox/display_profile.py create mode 100644 src/opendox/web/views/display.js diff --git a/src/opendox/display_profile.py b/src/opendox/display_profile.py new file mode 100644 index 00000000..ddfac6ad --- /dev/null +++ b/src/opendox/display_profile.py @@ -0,0 +1,488 @@ +"""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 and +`views/snapshot-schema.js` is the OTHER half of § 2.2 rule 3 — the snapshot's +own field names, which are openDox's schema and not a domain's vocabulary. + +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", + "DISPLAY_KIND", + "DISPLAY_SCHEMA_VERSION", + "NEUTRAL_DISPLAY", + "PROFILE_FACET", + "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`:18-21 defines +#: `--st-brainstorm` / `--st-staged` / `--st-proposal` / `--st-realized` — four +#: names that spell 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."* 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"), +) + +#: 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": None}, + "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", + }, +} + +#: 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 _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"), + 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 = _text(fields["prefix"], where=f"areas.{role}.prefix", + allow_none=True) + 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 + + 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"]), + } + + +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. + """ + 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}, + "area_order": list(AREA_ROLES), + "token_roles": list(TOKEN_ROLES), + **normalize_display(declared), + } diff --git a/src/opendox/serve.py b/src/opendox/serve.py index 8f79d971..09edf223 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 @@ -1576,6 +1579,37 @@ def build_server( host_profile=getattr(profile_openxfactory, "__name__", None), ) + # ---- 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), + host_profile=getattr(profile_openxfactory, "__name__", None), + ) + 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 dbaf06ec..f370b96c 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", @@ -209,6 +210,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 4c8f3f80..cb4dbc88 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 } 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` — @@ -1010,6 +1017,21 @@ 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); // 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 @@ -1083,10 +1105,10 @@ async function render() { // regions and are mounted by the callers that build their hosts, which is // exactly the exception Q1 preserves; the pass exists for the NEXT column. const contributedMounts = await mountContributedViews( - views, snapshot, { caps, nav: null, views }, + views, snapshot, { caps, nav: null, views, display }, { capabilities: probedCaps }); const explorer = mountExplorer(explorerRoot, snapshot, { - signal, + signal, display, onOpenFile: (entry, pane, tile) => { const sourceKey = sourceKeyFor(entry); return renderViewer(pane, { @@ -1284,7 +1306,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 @@ -1345,6 +1367,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, "…")`, @@ -1402,7 +1429,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/views/display.js b/src/opendox/web/views/display.js new file mode 100644 index 00000000..cf9c92b4 --- /dev/null +++ b/src/opendox/web/views/display.js @@ -0,0 +1,356 @@ +// THE DISPLAY FACET, CLIENT HALF — the registered domain's words, BY ROLE. +// +// `docs/front-end-package-boundary.md` § 4.3 step 3: "`app.js` puts that facet +// in the context object every binding already receives", and step 4: "a class-C +// module resolves BY ROLE, NOT BY STRING — the openXdox-spec note's own rule." +// This module is what a class-C file resolves THROUGH. `display_profile.py` is +// the server half that publishes the facet on `/capabilities`; the two are held +// together by `tests/test_display_facet.py`, which reads both files, exactly as +// `tests/test_view_registry.py` holds the two REGIONS tables together. +// +// RESOLVE BY ROLE, NEVER BY WORD. A role names a POSITION — "the raw material +// this domain works from", "the status a document carries while ORGANIZED" — +// and the word is the registered domain's spelling of it. openXdox-spec +// `docs/domain-profile-design-note.md` § 6 states the rule and the reason: "a +// profile whose organized status is spelled `triaged` must work with no engine +// change, which a `profile.statuses['staged']` lookup would not deliver." +// +// AN UNKNOWN ROLE IS A REFUSAL, NOT `undefined`. `DisplayRoleError` names the +// role and the declared set, because a typo that answered `undefined` would +// render a blank label in one corner of one view and be found by a human, once, +// much later. That is `ViewBindingError`'s stance and this module holds it for +// the same reason. +// +// ABSENT IS NEUTRAL. `NEUTRAL_DISPLAY` below is openDox's OWN vocabulary — the +// neutral product's plain words for its own shape — rendered when no host +// declares a `DISPLAY` facet, when `/capabilities` 404s (the static served +// image), or when a field is missing from a partial declaration. It is NOT +// openxFactory's words, which is the whole distinction § 4.3 point 5 is +// protecting: "a fallback to TODAY'S WORDS is how the literals survive the +// refactor invisibly." A funnel labelled `sources → groups → candidates` is +// visibly un-domained; one labelled `docs → clusters → possibles` is invisibly +// re-domained. +// +// IMPORT-FREE BY DESIGN, like `views/helpers.js` and `views/view_extension.js`: +// every class-C module in the bundle imports this one, so an import of its own +// would put a second module on that path and make the vocabulary's own +// availability depend on it. +// +// A CREATED FILE: no row in openxFactory's `docs/opendox-carve-manifest.yaml` +// (RULED OQ-C — the manifest declares what LEAVES openxFactory, never what a +// destination assembles). Its census row is class A: it carries ROLE names and +// openDox's own neutral words, and the one domain-shaped thing in it — +// `SNAPSHOT_FIELDS` — is a declared § 2.2 rule 3 exemption, below. + +// --------------------------------------------------------------------------- +// The declared roles. Mirrored in `src/opendox/display_profile.py`; the drift +// test reads both files rather than trusting this comment. +// --------------------------------------------------------------------------- + +// THE SIX STAGE ROLES, in spine order. `views/model.js` renders six columns +// left to right and `views/wheel-model.js` six reels in the same order, so the +// ORDER is part of the declaration: a renderer that had to invent the axis +// would be inventing domain knowledge. +export const STAGE_ROLES = ["source", "grouping", "candidate", + "selection", "submission", "completion"]; + +// THE CORPUS AREAS, by role (RULED Q1: `views/docs.js`'s area map is +// parameterized). `reference` is the terminal bucket — everything the declared +// areas do not claim — and never carries a prefix. +export const AREA_ROLES = ["captured", "organized", "proposed", "reference"]; + +// THE FOUR DESIGN TOKENS, by role — `styles.css`'s `--st-*` family, which RULED +// Q7 (openxFactory#656 comment `5648049748`) calls "the one stable styling +// surface". The NAMES become `--st-`; the values come from the facet. +export const TOKEN_ROLES = ["captured", "organized", "proposed", "completion"]; + +// The status vocabularies the shell renders, one per artifact-kind role. A +// profile declares one closed word list per kind, and collapsing them would +// make `proposed` mean two different words at once. +export const STATUS_VOCABULARIES = ["document", "change", "candidate"]; + +// THE NEUTRAL ROLE VOCABULARY FOR A STATUS — the lifecycle-state column +// openXdox-spec's design note § 6 names as "the neutral role vocabulary that +// makes this possible". +export const STATUS_ROLES = ["captured", "organized", "proposed", "ratified", + "promoted", "superseded", "retired", "out-of-band"]; + +// --------------------------------------------------------------------------- +// SNAPSHOT_FIELDS — § 2.2 rule 3's OTHER half, and a DECLARED exemption from +// the governance-literal sweep (`declared_exemptions` in the census fixture). +// +// "A SNAPSHOT SCHEMA KEY is not a stage name; a RENDERED WORD or a CORPUS +// PATH is. … A class-A file MAY read a schema key; it may NOT carry a word +// it renders or a corpus path it walks." (note § 2.2 rule 3) +// +// These are the field names of `snapshot.json`, the document this leg's own +// generator contract fixes and this bundle exists to render. They are openDox's +// SCHEMA, not a domain's vocabulary: a descendant that renamed `clusters` would +// be shipping a different snapshot, not a different domain. They are declared +// HERE, once, in a class-A module, so that the fourteen class-C files can read +// the snapshot through a role and carry none of them. +// +// `status` is the closed VALUE the two change stations split on +// (`changes[].status`) — a schema enum, never a rendered word; `null` where a +// station reads a whole collection. +export const SNAPSHOT_FIELDS = { + source: { field: "documents", status: null }, + grouping: { field: "clusters", status: null }, + candidate: { field: "possibles", status: null }, + selection: { field: "staged_topics", status: null }, + submission: { field: "changes", status: "active" }, + completion: { field: "changes", status: "archived" }, +}; + +// openDox's OWN words. Kept BYTE-FOR-BYTE in step with +// `display_profile.NEUTRAL_DISPLAY`; `tests/test_display_facet.py` parses both +// and refuses a difference. +export const NEUTRAL_DISPLAY = { + stages: { + source: { one: "source item", many: "source items", + short: "sources", label: "source items", gate: null }, + grouping: { one: "group", many: "groups", + short: "groups", label: "groups", gate: null }, + 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: null }, + }, + 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: null, label: "captured material" }, + organized: { prefix: null, label: "organized material" }, + proposed: { prefix: null, label: "submissions" }, + reference: { prefix: null, 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", + }, +}; + +export const DISPLAY_KIND = "opendox.display-facet"; +export const DISPLAY_SCHEMA_VERSION = 1; + +export class DisplayRoleError extends Error { + constructor(message) { + super(message); + this.name = "DisplayRoleError"; + } +} + +function refuseRole(kind, role, declared) { + throw new DisplayRoleError( + "no " + kind + " role " + JSON.stringify(role) + " is declared; the " + + "declared roles are " + JSON.stringify(declared) + ". A view resolves " + + "its vocabulary BY ROLE (docs/front-end-package-boundary.md § 4.3 step " + + "4), and a role this shell does not declare renders nowhere — so it is " + + "refused here rather than answered `undefined` and found as a blank " + + "label much later."); +} + +function pick(table, fallback, role) { + const declared = table && typeof table === "object" ? table[role] : null; + const base = fallback[role]; + if (!declared || typeof declared !== "object") return base; + return Object.assign({}, base, declared); +} + +// THE VOCABULARY, as a view reads it. One object per render, built from the +// `/capabilities` payload the shell already fetched; nothing here fetches. +export class Display { + constructor(payload) { + const facet = payload && typeof payload === "object" ? payload : {}; + this.hostFacet = facet.host_facet === "declared" ? "declared" : "absent"; + this.hostProfile = typeof facet.host_profile === "string" + ? facet.host_profile : null; + this.stageOrder = Array.isArray(facet.stage_order) && facet.stage_order.length + ? facet.stage_order.filter((role) => STAGE_ROLES.indexOf(role) !== -1) + : STAGE_ROLES.slice(); + this.areaOrder = Array.isArray(facet.area_order) && facet.area_order.length + ? facet.area_order.filter((role) => AREA_ROLES.indexOf(role) !== -1) + : AREA_ROLES.slice(); + this.fields = {}; + for (const role of STAGE_ROLES) { + const declared = facet.fields && facet.fields[role]; + this.fields[role] = declared && typeof declared.field === "string" + ? { field: declared.field, + status: typeof declared.status === "string" ? declared.status : null } + : SNAPSHOT_FIELDS[role]; + } + this._stages = {}; + for (const role of STAGE_ROLES) { + this._stages[role] = Object.assign( + { role: role }, + pick(facet.stages, NEUTRAL_DISPLAY.stages, role), + this.fields[role]); + } + this._statuses = {}; + for (const vocabulary of STATUS_VOCABULARIES) { + const declared = facet.statuses && facet.statuses[vocabulary]; + this._statuses[vocabulary] = Object.assign( + {}, NEUTRAL_DISPLAY.statuses[vocabulary], + declared && typeof declared === "object" ? declared : null); + } + this._areas = {}; + for (const role of AREA_ROLES) { + this._areas[role] = Object.assign( + { role: role }, pick(facet.areas, NEUTRAL_DISPLAY.areas, role)); + } + this._tokens = Object.assign({}, NEUTRAL_DISPLAY.tokens, + facet.tokens && typeof facet.tokens === "object" ? facet.tokens : null); + this._acts = Object.assign({}, NEUTRAL_DISPLAY.acts, + facet.acts && typeof facet.acts === "object" ? facet.acts : null); + } + + // ---- stages ---- + stage(role) { + const entry = this._stages[role]; + if (!entry) refuseRole("stage", role, STAGE_ROLES); + return entry; + } + + // The six stations in declared order — what a column strip, a wheel deck and + // a station list all iterate. + stages() { return this.stageOrder.map((role) => this.stage(role)); } + + // The singular noun, the plural noun, the axis-label short form, the station + // label, and the gate caption between this station and the next. + one(role) { return this.stage(role).one; } + many(role) { return this.stage(role).many; } + short(role) { return this.stage(role).short; } + label(role) { return this.stage(role).label; } + gate(role) { return this.stage(role).gate; } + + // `n` of them, spelled for `n` — the shape "3 possibles" / "1 possible" takes + // everywhere in this bundle, with the domain's own two words. + count(role, n) { return n === 1 ? this.one(role) : this.many(role); } + + // ---- the snapshot, through a role (§ 2.2 rule 3) ---- + field(role) { return this.stage(role).field; } + statusValue(role) { return this.stage(role).status; } + + // The items of one station, read out of the snapshot by the declared field + // and filtered by the declared status where the station has one. + items(snapshot, role) { + const stage = this.stage(role); + const all = (snapshot && snapshot[stage.field]) || []; + if (!Array.isArray(all)) return []; + if (!stage.status) return all; + return all.filter((item) => item && item.status === stage.status); + } + + // ---- statuses ---- + status(vocabulary, role) { + const words = this._statuses[vocabulary]; + if (!words) refuseRole("status vocabulary", vocabulary, STATUS_VOCABULARIES); + const word = words[role]; + if (word === undefined) refuseRole(vocabulary + " status", role, + Object.keys(words)); + return word; + } + + // ---- corpus areas ---- + area(role) { + const entry = this._areas[role]; + if (!entry) refuseRole("area", role, AREA_ROLES); + return entry; + } + + areas() { return this.areaOrder.map((role) => this.area(role)); } + + // Which declared area a corpus path falls in — the first whose prefix claims + // it, else the terminal `reference` bucket. A neutral install declares no + // prefix at all, so every document lands in `reference`, which is the honest + // answer for a product that has not been told a corpus layout. + areaOf(path) { + const text = String(path || ""); + for (const role of this.areaOrder) { + const entry = this.area(role); + if (entry.prefix && text.startsWith(entry.prefix)) return entry; + } + return this.area("reference"); + } + + // ---- design tokens ---- + token(role) { + const value = this._tokens[role]; + if (value === undefined) refuseRole("token", role, TOKEN_ROLES); + return value; + } + + // `var(--st-)`, the one styling surface RULED Q7 keeps stable. + tokenVar(role) { + this.token(role); + return "var(--st-" + role + ")"; + } + + // Set the four tokens as custom properties on the given element (`:root` at + // boot). § 4.3 point 4's own words: "`styles.css`'s four `--st-*` tokens + // become profile-keyed custom properties set on `:root` at boot." + applyTokens(element) { + if (!element || !element.style) return; + for (const role of TOKEN_ROLES) { + element.style.setProperty("--st-" + role, this.token(role)); + } + } + + // ---- acts ---- + act(role) { + const word = this._acts[role]; + if (word === undefined) refuseRole("act", role, Object.keys(this._acts)); + return word; + } +} + +// The ONE reader. `capabilities` is the payload `probeCapabilities()` already +// fetched; a static served image 404s that route and hands `null`, which is +// exactly the neutral install. +// +// REFUSES A PAYLOAD IT CANNOT DESCRIBE, on `contributedViewBindings`' own +// grounds: a shell that guessed at an unknown facet version would be rendering +// a vocabulary it cannot name. +export function readDisplay(capabilities) { + const payload = capabilities && capabilities.display; + if (payload === undefined || payload === null) return new Display(null); + if (typeof payload !== "object" || Array.isArray(payload)) { + throw new DisplayRoleError( + "the /capabilities payload carries a `display` that is not a display " + + "facet object"); + } + if (payload.kind !== DISPLAY_KIND) { + throw new DisplayRoleError( + "the /capabilities `display` payload declares kind " + + JSON.stringify(payload.kind) + ", not " + JSON.stringify(DISPLAY_KIND)); + } + if (payload.schema_version !== DISPLAY_SCHEMA_VERSION) { + throw new DisplayRoleError( + "the /capabilities `display` payload declares schema_version " + + JSON.stringify(payload.schema_version) + ", and this shell reads " + + DISPLAY_SCHEMA_VERSION + ". A shell that guessed at an unknown facet " + + "version would be rendering a vocabulary it cannot describe."); + } + return new Display(payload); +} + +// The neutral vocabulary, without a payload — for a module that renders before +// the probe resolves, and for a node test. +export function neutralDisplay() { return new Display(null); } diff --git a/src/opendox/web/views/view_extension.js b/src/opendox/web/views/view_extension.js index 5b6a0fbd..74d0acab 100644 --- a/src/opendox/web/views/view_extension.js +++ b/src/opendox/web/views/view_extension.js @@ -101,6 +101,33 @@ export const REGIONS = { "workbench-session": "shell", }; +// 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`). Declared for the same reason REGIONS +// is: the counterpart note's § 3 asks what a contributed binding "may assume +// about the shell … the context object's shape", and a shape that is only ever +// an object literal in `app.js` is an assumption rather than a contract. +// +// `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 `views/display.js`, built from `/capabilities`' `display` block: +// `ctx.display.label(role)`, `.one(role)`, `.many(role)`, `.status(vocabulary, +// role)`, `.area(role)`, `.token(role)`, `.items(snapshot, role)` — every one +// of them resolved BY ROLE and never by a word. A contributed column renders +// the registered domain's vocabulary by reading it, exactly as openDox's own +// class-C views do, and inherits the neutral words when no host declares any. +// +// The Python half carries the same table (`view_extension.CTX_KEYS`) and +// `tests/test_display_facet.py` holds the two against each other, as +// `tests/test_view_registry.py` already does for REGIONS. +export const CTX_KEYS = { + 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", +}; + export const MANIFEST_KIND = "opendox.view-manifest"; export const MANIFEST_SCHEMA_VERSION = 1; diff --git a/tests/fixtures/web_boundary_census.yaml b/tests/fixtures/web_boundary_census.yaml index 42c477fc..bcf4e67a 100644 --- a/tests/fixtures/web_boundary_census.yaml +++ b/tests/fixtures/web_boundary_census.yaml @@ -181,14 +181,15 @@ measured_at: "opensoft/openDox-code main a99eba03e31a0aee1cc15a061fdf718cc88a2c4 # shape and `test_the_declared_totals_are_re_derived_from_the_rows` can refuse a # drift between the two. Measured at slice S4 (see the S4 block above). totals: - A: {files: 25, loc: 16706} + A: {files: 26, loc: 17116} B: {files: 1, loc: 73} C: {files: 14, loc: 11952} "?": {files: 1, loc: 1435} + "?": {files: 1, loc: 1435} files: - path: app.js class: A - loc: 1456 + loc: 1483 note: "the shell; its only class-B import was gate.js at :43 (discharged by S3's view registry -- loc 1155 -> 1282 with the registry wiring, S3; 1282 -> 1337 with S4's two new gate bindings and the two mounts it hands down). Carries SIX transitional route-ownership sites, all in the CORE arm's class-B binding entries and all cleared at S5 when those entries leave for contributedViewBindings(): gate.bar's one route (S3) and gate.lens's and gate.projects's two each (S4). Declaring them is RULED Q3 working -- view_extension.py: 'a binding that declares the routes it calls is what makes that ruling checkable instead of aspirational' -- and it is a real breach by assertion 2's own rule only while the entry sits in app.js (class A) rather than in the class-B module (exempt by construction)" - path: index.html @@ -242,6 +243,12 @@ files: exempt: COMPOSED_COLLECTIONS note: "declared exempt (note § 2.2 rule 3) -- see declared_exemptions below" + - path: views/display.js + class: A + loc: 356 + exempt: SNAPSHOT_FIELDS + note: "S7 ADDITION (created, no manifest row -- RULED OQ-C): the DISPLAY FACET's client half. Carries ROLE names (STAGE_ROLES / STATUS_ROLES / AREA_ROLES / TOKEN_ROLES) and openDox's OWN neutral words (NEUTRAL_DISPLAY), never a registered domain's -- which is what keeps it class A while every class-C file reads its vocabulary through it. SNAPSHOT_FIELDS is the one domain-shaped table in it and is a DECLARED § 2.2 rule 3 exemption (see declared_exemptions below): the snapshot's own field names and the closed `changes[].status` enum, which are openDox's schema and not a domain's mapping. Import-free by design, like helpers.js and view_extension.js" + - path: views/doc-wheel.js class: C loc: 491 @@ -379,7 +386,7 @@ files: - path: views/view_extension.js class: A - loc: 757 + loc: 784 note: "S3 ADDITION: the client-side view registry -- ViewBinding/collectViewBindings, route_extension.py's shape mirrored in JS (openDox-spec § 4.1). No import, no governance literal; 'gate.bar' in a doc comment is a documentation example of an id, not a route literal, so assertion 2 does not match it. loc 422 -> 455 on this PR's own review round (Copilot, PR #14): a malformed contributed_routes now refuses instead of silently disabling the ownership check, and a rejected dynamic import now refuses naming the binding and module instead of leaking a raw error. loc 463 -> 499 on this fix (Copilot, PR #16, view_extension.js:358): manifestRoutes() and ownershipBreach() now share one shape check, refusing a contributed-routes entry missing a string pattern or carrying a non-boolean is_prefix at whichever of the two sees it first, instead of the array-only check at manifestRoutes() and a truthy is_prefix read at ownershipBreach() silently letting a malformed entry through as if it were not a prefix match." - path: views/viewer.js @@ -466,3 +473,14 @@ declared_exemptions: reason: >- the three tile kinds a workbench session may be scoped to -- a state key, never a label (note § 2.2 rule 3). + - path: views/display.js + identifier: SNAPSHOT_FIELDS + reason: >- + S7's declaration of § 2.2 rule 3's other half: the snapshot's six field + names (documents, clusters, possibles, staged_topics, changes) and the + closed `changes[].status` enum (active / archived), declared ONCE in a + class-A module so that the fourteen class-C files read the snapshot + through a ROLE and carry none of them. These are openDox's own schema -- + a descendant that renamed `clusters` would be shipping a different + snapshot, not a different domain -- so a class-A file MAY read them and + this file is where they are read. From 49f53670e8f0789dd5e9678dc70134e40aaedac3 Mon Sep 17 00:00:00 2001 From: Brett Heap <1513478+brettheap@users.noreply.github.com> Date: Sat, 12 Sep 2026 18:45:46 -0400 Subject: [PATCH 20/44] =?UTF-8?q?=C2=A7=203.4=20S5,=20leg=20B:=20name=20th?= =?UTF-8?q?e=20file=20the=20five=20moved=20probes=20actually=20landed=20in?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The note left where slice S4's five node probes stood points at openXdox-code `tests/test_gate_loop_views.py`; they landed in `tests/test_gate_loop_probes.py` (openXdox-code#18 `b0091963`), where each probe assembles a COMPOSED bundle — openDox's own `web/` with that column's six modules placed into it by RULED Q5's assembly hook — and imports the module from there, which is a stronger statement than the original this leg could make. A pointer that names the wrong file is a pointer that gets followed once and then distrusted. Lane: openxfactory-4-opendox-extraction Refs opensoft/openxFactory#656 Co-Authored-By: Claude Opus 5 --- tests/test_split_route_tails.py | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/tests/test_split_route_tails.py b/tests/test_split_route_tails.py index c8b8c903..abb1ec10 100644 --- a/tests/test_split_route_tails.py +++ b/tests/test_split_route_tails.py @@ -474,8 +474,11 @@ def _run_node(body: str, tmp_path: Path) -> dict: # coverage in a refactor slice is how a move that passes every shape assertion # silently breaks a verb, which is the failure this suite's own header names as # "the worst possible outcome of this slice". They run at openXdox-code, against -# the same real files, in `tests/test_gate_loop_views.py` -- same harness, same -# DOM stub, same assertions, one import path different. +# the same real files, in `tests/test_gate_loop_probes.py` -- same harness, same +# DOM stub, same assertions, and one thing STRONGER: there each probe assembles +# a COMPOSED bundle first (openDox's own `web/` with that column's six modules +# placed into it by RULED Q5's assembly hook) and imports the module from there, +# so the byte measured is the shipped byte in the shipped position. # # What stays here is everything about the modules this bundle still ships, and # the SHAPE assertions above, which are what this leg can still answer. From f2ef1256dbcd2b3cbe6671b0b21d4dca3a81d117 Mon Sep 17 00:00:00 2001 From: Brett Heap <1513478+brettheap@users.noreply.github.com> Date: Sat, 12 Sep 2026 18:53:35 -0400 Subject: [PATCH 21/44] =?UTF-8?q?=C2=A7=203.4=20S7:=20the=20vocabulary=20t?= =?UTF-8?q?he=20others=20import=20=E2=80=94=20wheel-model.js,=20model.js,?= =?UTF-8?q?=20funnel.js?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit § 5's S7 row orders the slice: "wheel-model.js and model.js FIRST (they are the vocabulary the others import)". These two declared the six stage names twice over — `COLUMN_KEYS` :15 and `WHEEL_KEYS` :25 / `WHEEL_LABELS` :27-34 — and every other class-C file keys off one of them, so nothing downstream can be parameterized while they are literals. * `views/model.js` — `COLUMN_KEYS` IS `STAGE_ROLES` now. A node's `column`, its DOM id prefix, every edge endpoint and the collapse set are neutral roles; the column LABEL and the gate caption come from `display.stages()`; the snapshot is read through `display.items(snapshot, role)`, which resolves the field name and (for the two change stations) the closed status value out of the facet's schema half. § 3.2 called this "the densest file in the tree — 28 governance literals in 126 lines"; it carries none. * `views/wheel-model.js` — the same six roles for the six reels. `WHEEL_LABELS` is GONE rather than moved: a second copy of the vocabulary keyed by wheel is exactly the literal table this slice removes, so `wheel.js` reads `display.short(role)`. `WHEEL_ACTIONS` is keyed by role, and a verb row whose label carries a domain noun declares that label as a function of the facet, resolved per render in `actionsFor`. `packetGroups` reads its ordered front matter from the artifact axis. * `views/funnel.js` — the card builders, the legend, the variant toggle, the station labels, the scope control and the count are all read by role. The per-render vocabulary is held in one module-scope binding rather than threaded through ten DOM helpers; `renderFunnel` is this module's one entry point and every helper is called synchronously from inside it. * `app.js` — each CORE_VIEWS mount hands `ctx.display` to its view. THREE SEAM-KEY TABLES ARE DECLARED IN `views/display.js`, all on § 2.2 rule 3's footing and all carried in the census as declared exemptions with their reason: `SNAPSHOT_FIELDS` (the snapshot's own field names and the closed `changes[].status` enum), `ACT_IDS` (the gate column's verb keys, which both sides of the seam must spell identically — openXdox-spec's `gate-action-record.schema.yaml`:165 is where the enum lives) and `TILE_KINDS` (`/actions/notebook`'s payload keys, openDox's own `notebook_action.py`). None of the three is ever rendered; what a human reads is always `display.`. AND THE EIGHT STATUS ROLES ARE NAMED CONSTANTS (`STATUS_ROLE`), because three of them — `ratified`, `superseded`, `retired` — are spelled identically to the openxFactory words they name the role OF. That is the lifecycle-state column's own coincidence (openXdox-spec `docs/domain-profile-design-note.md` § 6), and naming the role through a constant means the sweep never has to decide whether a given `"ratified"` was the neutral role or the domain's word. The question does not arise, which is a better answer than an exemption. The facet gains the ARTIFACT axis RULED Q1's own argument names ("the profile already has to carry an artifact-vocabulary axis for `outline-model.js`") and § 2.1 calls `views/explorer.js`'s only domain content: `root`, `packet` (with its ordered front matter), `delta`, `supporting`. Lane: openxfactory-4-opendox-extraction Refs opensoft/openxFactory#656 Co-Authored-By: Claude Opus 5 --- src/opendox/display_profile.py | 59 ++++++- src/opendox/web/app.js | 18 ++- src/opendox/web/views/display.js | 94 +++++++++++- src/opendox/web/views/funnel.js | 76 ++++++--- src/opendox/web/views/model.js | 146 +++++++++++------- src/opendox/web/views/wheel-model.js | 195 ++++++++++++++---------- tests/fixtures/web_boundary_census.yaml | 14 +- 7 files changed, 426 insertions(+), 176 deletions(-) diff --git a/src/opendox/display_profile.py b/src/opendox/display_profile.py index ddfac6ad..f292b544 100644 --- a/src/opendox/display_profile.py +++ b/src/opendox/display_profile.py @@ -18,9 +18,10 @@ 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 and -`views/snapshot-schema.js` is the OTHER half of § 2.2 rule 3 — the snapshot's -own field names, which are openDox's schema and not a domain's vocabulary. +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 @@ -105,6 +106,7 @@ class C — *"replace every governance word in it with a placeholder and the fil __all__ = [ "AREA_ROLES", + "ARTIFACT_ROLES", "DISPLAY_KIND", "DISPLAY_SCHEMA_VERSION", "NEUTRAL_DISPLAY", @@ -210,7 +212,8 @@ class C — *"replace every governance word in it with a placeholder and the fil NEUTRAL_DISPLAY: dict[str, Any] = { "stages": { "source": {"one": "source item", "many": "source items", - "short": "sources", "label": "source items", "gate": None}, + "short": "sources", "label": "source items", + "gate": "declared topics"}, "grouping": {"one": "group", "many": "groups", "short": "groups", "label": "groups", "gate": None}, "candidate": {"one": "candidate", "many": "candidates", @@ -261,9 +264,28 @@ class C — *"replace every governance word in it with a placeholder and the fil "derive": "derive candidates", "brief": "research brief", "promote": "promote to selection", + "propose": "draft a submission", + }, + "artifacts": { + "root": {"prefix": None, "label": "submission folder"}, + "packet": {"prefix": None, "label": "packet documents", + "order": []}, + "delta": {"prefix": None, "label": "detail documents"}, + "supporting": {"prefix": None, "label": "supporting documents"}, }, } +#: 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. @@ -366,7 +388,8 @@ def normalize_display(declared: Any) -> dict[str, Any]: return _copy_display(NEUTRAL_DISPLAY) table = _mapping(declared, where="the facet itself") _unknown_roles(table.keys(), - ("stages", "statuses", "areas", "tokens", "acts"), + ("stages", "statuses", "areas", "tokens", "acts", + "artifacts"), where="the facet itself") out = _copy_display(NEUTRAL_DISPLAY) @@ -428,6 +451,29 @@ def normalize_display(declared: Any) -> dict[str, Any]: "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"] = _text( + fields["prefix"], where=f"artifacts.{role}.prefix", + allow_none=True) + 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(): @@ -451,6 +497,8 @@ def _copy_display(source: Mapping[str, Any]) -> dict[str, Any]: 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()}, } @@ -483,6 +531,7 @@ def display_manifest(declared: Any, *, host_profile: str | None = None "fields": {role: {"field": field, "status": status} for role, field, status in STAGE_FIELDS}, "area_order": list(AREA_ROLES), + "artifact_roles": list(ARTIFACT_ROLES), "token_roles": list(TOKEN_ROLES), **normalize_display(declared), } diff --git a/src/opendox/web/app.js b/src/opendox/web/app.js index cb4dbc88..3e11427f 100644 --- a/src/opendox/web/app.js +++ b/src/opendox/web/app.js @@ -532,12 +532,16 @@ const CORE_VIEWS = [ 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 @@ -546,10 +550,13 @@ 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, + 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 @@ -585,6 +592,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 @@ -593,10 +601,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. // diff --git a/src/opendox/web/views/display.js b/src/opendox/web/views/display.js index cf9c92b4..3e8c0a3d 100644 --- a/src/opendox/web/views/display.js +++ b/src/opendox/web/views/display.js @@ -75,6 +75,33 @@ export const STATUS_VOCABULARIES = ["document", "change", "candidate"]; export const STATUS_ROLES = ["captured", "organized", "proposed", "ratified", "promoted", "superseded", "retired", "out-of-band"]; +// THE SAME EIGHT AS NAMED CONSTANTS, because three of them — `ratified`, +// `superseded`, `retired` — are spelled identically to the openxFactory words +// they name the role OF. That is the lifecycle-state column's own coincidence +// (openXdox-spec `docs/domain-profile-design-note.md` § 6) and not something to +// respell: a role is a role because of where it sits, not because of how it +// looks. A view therefore names the role through this table and carries no +// literal, so the governance-literal sweep never has to decide whether a given +// `"ratified"` was the neutral role or the domain's word — the question does +// not arise, which is a better answer than an exemption. +export const STATUS_ROLE = { + CAPTURED: "captured", + ORGANIZED: "organized", + PROPOSED: "proposed", + RATIFIED: "ratified", + PROMOTED: "promoted", + SUPERSEDED: "superseded", + RETIRED: "retired", + OUT_OF_BAND: "out-of-band", +}; + +// The three status VOCABULARIES as named constants, for the same reason. +export const VOCABULARY = { + DOCUMENT: "document", + CHANGE: "change", + CANDIDATE: "candidate", +}; + // --------------------------------------------------------------------------- // SNAPSHOT_FIELDS — § 2.2 rule 3's OTHER half, and a DECLARED exemption from // the governance-literal sweep (`declared_exemptions` in the census fixture). @@ -102,13 +129,45 @@ export const SNAPSHOT_FIELDS = { completion: { field: "changes", status: "archived" }, }; +// ACT_IDS — the gate column's own verb KEYS, declared here for the same reason +// `SNAPSHOT_FIELDS` is and carried in the census under the same § 2.2 rule 3 +// exemption. An act id is a SEAM KEY, not a rendered word: `views/wheel-model.js` +// declares which verb row a wheel offers and the CONTRIBUTED gate column +// dispatches on the id, so the two ends must spell it identically — exactly as a +// route pattern must. openXdox-spec's `gate-action-record.schema.yaml`:165 is +// where the enum is declared; these are the five this bundle's own views name. +// What a human SEES is never one of these: the label beside each row comes from +// `display.act(role)` and is the registered domain's word. +export const ACT_IDS = { + derive: "derive-possibles", + brief: "research-brief", + promote: "promote-to-staging", + propose: "propose", + demote: "demote", +}; + +// TILE_KINDS — the `/actions/notebook` payload's own tile-kind keys, by stage +// role. A third SEAM KEY table on the same § 2.2 rule 3 footing as +// `SNAPSHOT_FIELDS` and `ACT_IDS`: openDox's `notebook_action.py` declares the +// enum (`TILE_KINDS`) and the browser must spell it identically, while what a +// human reads beside the button is `display.one(role)`. Only the three +// topic-bearing stations carry one — a single source document is not a set, and +// the completed station is out by design ("the action is for live governance +// material"). +export const TILE_KINDS = { + grouping: "cluster", + selection: "staged", + submission: "proposal", +}; + // openDox's OWN words. Kept BYTE-FOR-BYTE in step with // `display_profile.NEUTRAL_DISPLAY`; `tests/test_display_facet.py` parses both // and refuses a difference. export const NEUTRAL_DISPLAY = { stages: { source: { one: "source item", many: "source items", - short: "sources", label: "source items", gate: null }, + short: "sources", label: "source items", + gate: "declared topics" }, grouping: { one: "group", many: "groups", short: "groups", label: "groups", gate: null }, candidate: { one: "candidate", many: "candidates", @@ -143,10 +202,26 @@ export const NEUTRAL_DISPLAY = { }, acts: { derive: "derive candidates", brief: "research brief", - promote: "promote to selection", + promote: "promote to selection", propose: "draft a submission", + }, + // 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 calls `views/explorer.js`'s "only + // domain content". `root` is the folder a submission's files live under; + // `packet` is its ORDERED front matter; `delta` and `supporting` are the two + // subfolders the explorer groups by. Every prefix is null in the neutral + // vocabulary: a product told no corpus layout has none, so the explorer + // groups by folder and says so. + artifacts: { + root: { prefix: null, label: "submission folder" }, + packet: { prefix: null, label: "packet documents", order: [] }, + delta: { prefix: null, label: "detail documents" }, + supporting: { prefix: null, label: "supporting documents" }, }, }; +export const ARTIFACT_ROLES = ["root", "packet", "delta", "supporting"]; + export const DISPLAY_KIND = "opendox.display-facet"; export const DISPLAY_SCHEMA_VERSION = 1; @@ -219,6 +294,11 @@ export class Display { facet.tokens && typeof facet.tokens === "object" ? facet.tokens : null); this._acts = Object.assign({}, NEUTRAL_DISPLAY.acts, facet.acts && typeof facet.acts === "object" ? facet.acts : null); + this._artifacts = {}; + for (const role of ARTIFACT_ROLES) { + this._artifacts[role] = Object.assign( + { role: role }, pick(facet.artifacts, NEUTRAL_DISPLAY.artifacts, role)); + } } // ---- stages ---- @@ -313,6 +393,16 @@ export class Display { } } + // ---- artifact-folder vocabulary (RULED Q1's axis) ---- + artifact(role) { + const entry = this._artifacts[role]; + if (!entry) refuseRole("artifact", role, ARTIFACT_ROLES); + return entry; + } + + // The ordered packet documents, or [] where the domain declares none. + packetOrder() { return this.artifact("packet").order || []; } + // ---- acts ---- act(role) { const word = this._acts[role]; diff --git a/src/opendox/web/views/funnel.js b/src/opendox/web/views/funnel.js index 8972490b..a659498e 100644 --- a/src/opendox/web/views/funnel.js +++ b/src/opendox/web/views/funnel.js @@ -22,9 +22,24 @@ import { buildFunnelModel, visibleEdges } from "./model.js"; import { el, txt, basename, readinessHeat } from "./helpers.js"; +import { + STAGE_ROLES, STATUS_ROLE, TILE_KINDS, VOCABULARY, neutralDisplay, +} from "./display.js"; const SVG_NS = "http://www.w3.org/2000/svg"; +const [SOURCE, GROUPING, CANDIDATE, SELECTION, SUBMISSION, COMPLETION] = + STAGE_ROLES; + +// THE PER-RENDER VOCABULARY (§ 3.4 slice S7). `renderFunnel` is this module's +// one entry point and every helper below is called synchronously from inside +// it, so the facet the shell handed down through `ctx.display` is held here +// rather than threaded through ten signatures that exist to build DOM. It is +// the NEUTRAL vocabulary until a render supplies one, which is what a node +// harness and a pre-probe render get — openDox's own words, never the words +// this file used to hardcode. +let vocab = neutralDisplay(); + // A labelled + + @@ -52,14 +56,22 @@ aria-controls="accountmenu">👤 +
- - - - - - - + + + + + + +
` 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: @@ -672,7 +948,131 @@ 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 + if 'from "./display.js"' not in text and "display" 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).") From bd94aa79ec339fabdbe2dad972f9a215213318a1 Mon Sep 17 00:00:00 2001 From: Brett Heap <1513478+brettheap@users.noreply.github.com> Date: Sat, 12 Sep 2026 19:39:39 -0400 Subject: [PATCH 31/44] =?UTF-8?q?=C2=A7=203.4=20S5,=20leg=20B:=20the=20pro?= =?UTF-8?q?bes=20of=20the=20modules=20that=20left=20go=20with=20the=20modu?= =?UTF-8?q?les?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Copilot's round-2 review named four probe files in this leg that still copy or read `views/dispose.js` and `views/swb-create.js` after slice S5 moves them. Two of them are this leg's to fix, and they are fixed here. `tests/test_intent_binding_dom.py` is slice S2's own CREATED file (no carve row). Its wheel closure no longer copies `dispose.js` — which left the closure TWICE over, since `wheel.js` no longer imports it either, and copying it would be copying a file this repository does not ship. Its graph probe keeps the half this bundle can still answer, which is the half openDox-spec § 1.2(b)'s defect was actually about: `wheel.js`'s own closure loads and evaluates with the never-carved `intent-feed.js` absent. Its two TRAY probes were ported, not deleted — to openXdox-code `tests/test_gate_loop_probes.py`, with slice S2's own DOM shim carried across unchanged and against an ASSEMBLED bundle, on the precedent slice S4's five node probes set one slice ago. `tests/test_bullseye_widget.py` loses the five statements that quote `views/swb-create.js` as text; they are at openXdox-code `tests/test_gate_loop_views.py` now, with the browser-measured finding they were written for. Every statement in that test about `views/staging-workbench.js` and `styles.css` stays, which is what it is named for. This is an ARRIVED file: the edit is declared in the S5 annotation payload, on the precedent slice S3 set on this same file (`adapter calls`, "migrated in the same act rather than left to rot until slice S8 re-homes this suite"). NOT TOUCHED, and the reason is on the record: `tests/test_intent_tray_dom.py` and `tests/test_wheel_verbs_dom.py` both copy `views/intent-feed.js`, RULED `not_moved` (OQ-F) and therefore never carved into this leg at all — so both have been unrunnable since the carve commit, before this slice existed, and removing `dispose.js` from their copy lists would not make either run. Both are ARRIVED files narrowed out of `validate` under RULED Q-L5 (b′), and this workflow's own text records that un-narrowing that class of test is slice S8's job. Their threads stay open against S8. Lane: openxfactory-4-opendox-extraction Refs opensoft/openxFactory#656 Co-Authored-By: Claude Opus 5 --- tests/test_bullseye_widget.py | 18 +++--- tests/test_intent_binding_dom.py | 101 +++++++++++++++---------------- 2 files changed, 58 insertions(+), 61 deletions(-) diff --git a/tests/test_bullseye_widget.py b/tests/test_bullseye_widget.py index 8c86ddb5..3d984af0 100644 --- a/tests/test_bullseye_widget.py +++ b/tests/test_bullseye_widget.py @@ -1462,7 +1462,6 @@ def test_the_draft_view_has_one_action_called_save_reachable_from_both_tabs(): """ css = (WEB / "styles.css").read_text(encoding="utf-8") swb = (WEB / "views" / "staging-workbench.js").read_text(encoding="utf-8") - create = (WEB / "views" / "swb-create.js").read_text(encoding="utf-8") # the editor is sized, and the chain that lets it grow is present assert ".swb-draftbody {" in css, "the body editor must carry a rule at all" @@ -1506,13 +1505,16 @@ def test_the_draft_view_has_one_action_called_save_reachable_from_both_tabs(): assert 'submitLabel: "save",' in swb assert "actionsHost: chrome," in swb assert ".swb-draftchrome" in css - # …and it is the form's own submit, relocated — not a second write path - assert "const actions = o.actionsHost || form;" in create - assert "actions.appendChild(bar);" in create - assert "actions.appendChild(result);" in create - assert create.count('method: "POST"') == 1, "still exactly one write" - # the TILE path is untouched: there a new document really is being started - assert 'o.submitLabel || "create document"' in create + # …and it is the form's own submit, relocated — not a second write path: + # ASSERTED AT openXdox-code SINCE SLICE S5, because `views/swb-create.js` is + # that column's package data now (RULED Q5, openxFactory#656 comment + # `5648044785`) and reading it out of `src/opendox/web/views/` would be + # asserting against a file this bundle no longer ships. The five statements + # that quoted it — the relocated actions host, the two appends, "still + # exactly one write", and the tile path's untouched default label — travel + # with the module, in `tests/test_gate_loop_views.py`. What stays here is + # every statement about `views/staging-workbench.js` and `styles.css`, which + # are this bundle's own and are what this test is named for. # panes built once, toggled — a tab switch discards nothing assert "function buildDraftPanes()" in swb diff --git a/tests/test_intent_binding_dom.py b/tests/test_intent_binding_dom.py index 381bf2f1..164a7b0e 100644 --- a/tests/test_intent_binding_dom.py +++ b/tests/test_intent_binding_dom.py @@ -50,13 +50,20 @@ # intent-feed.js (RULED `not_moved`, never carried here) and PLUS # intent-binding.js (the seam this slice adds). Measured by reading each # file's own `^import` lines: wheel-model.js, helpers.js, notebook.js and -# settings.js are import-free leaves; dispose.js imports only helpers.js and -# (after this slice) intent-binding.js. A file added to this set by a future +# settings.js are import-free leaves. A file added to this set by a future # slice without updating this constant fails loudly (`_write_tree` copies # exactly this list, so a newly-added import the closure omits is a # `MODULE_NOT_FOUND` in the harness, not a silent gap). +# +# `dispose.js` LEFT THE CLOSURE AT SLICE S5, and it left twice over: it is no +# longer in this bundle at all (openXdox-code's package data, RULED Q5, +# openxFactory#656 comment `5648044785`), and `wheel.js` no longer imports it — +# the shell resolves the `gate.dispose` binding and hands its declared namespace +# down as `ctx.dispose`, which is the class-C -> class-B breach § 4.5 assertion +# 3 measured, closed. Copying it here would be copying a file this repository +# does not ship. WHEEL_CLOSURE = ( - "wheel.js", "wheel-model.js", "helpers.js", "dispose.js", + "wheel.js", "wheel-model.js", "helpers.js", "intent-binding.js", "notebook.js", "settings.js", ) @@ -160,12 +167,20 @@ def _run(tmp_path, script: str, *, contribute_intent_feed: bool): # ---- the module graph itself (the note's § 1.2(b) defect) ------------------ +# `import * as D from "./dispose.js"` WAS THE SECOND HALF OF THIS PROBE, and it +# went with the module at slice S5. The graph statement it made — that BOTH +# halves load in one tree — can only be made where both halves exist, which is +# the COMPOSED bundle, so it is made at openXdox-code +# (`tests/test_gate_loop_probes.py`, +# `test_js_the_composed_graph_resolves_with_or_without_a_contributed_feed`) +# against openDox's own `web/` with this column's modules assembled into it. +# What stays here is the half this bundle can still answer, and it is the half +# the note's § 1.2(b) defect was actually about: `wheel.js`'s OWN closure loads +# and evaluates with the never-carved `intent-feed.js` absent. _GRAPH_PROBE = """ import * as W from "./wheel.js"; -import * as D from "./dispose.js"; console.log(JSON.stringify({ renderWheel: typeof W.renderWheel, - mountDisposeTray: typeof D.mountDisposeTray, })); """ @@ -177,63 +192,43 @@ def test_wheel_module_graph_resolves_with_intent_feed_absent(tmp_path): missing render. This is that failure, gone: the entire closure loads and evaluates with intent-feed.js absent, exactly as this leg ships today.""" r = _run(tmp_path, _GRAPH_PROBE, contribute_intent_feed=False) - assert r == {"renderWheel": "function", "mountDisposeTray": "function"} + assert r == {"renderWheel": "function"} def test_wheel_module_graph_also_resolves_with_intent_feed_contributed(tmp_path): """The forward path: a deployment that DOES drop intent-feed.js beside the others (openxFactory's composed column) still loads cleanly.""" r = _run(tmp_path, _GRAPH_PROBE, contribute_intent_feed=True) - assert r == {"renderWheel": "function", "mountDisposeTray": "function"} + assert r == {"renderWheel": "function"} -# ---- dispose.js's tray, gated the way wheel.js actually gates it ----------- +# ---- dispose.js's TRAY MOVED WITH dispose.js (slice S5) --------------------- # -# `mountDisposeTray` itself does not consult `intentCapable` — it trusts its -# caller (`wheel.js`) to pass `opts.intent` only once `intentCapable(caps)` -# has already said yes (`wheel.js`'s own `hosted` local). So the realistic -# probe reproduces THAT gate rather than handing `opts.intent` to the tray -# unconditionally, which would prove nothing about the binding. - -_TRAY_PROBE = _DOM_SHIM + """ -import { mountDisposeTray } from "./dispose.js"; -import { intentCapable } from "./intent-binding.js"; - -const caps = { actions: { intent: true } }; -const hosted = intentCapable(caps); -const row = new Node("div"); -mountDisposeTray(row, { id: "p1" }, - hosted ? { intent: { snapshotRev: "r", rows: [], error: null } } : {}); -const tray = byClass(row, "disposetray")[0]; -const chips = row.walk().find((n) => String(n.className).includes("intentchips")); -console.log(JSON.stringify({ - hosted, - verdictButtons: tray ? tray.children.length : -1, - chipsMounted: !!chips, - chipsCarryRealForward: !!(chips && chips.__fakeRendered), -})); -""" - - -def test_dispose_tray_renders_with_no_chips_when_intent_feed_absent(tmp_path): - r = _run(tmp_path, _TRAY_PROBE, contribute_intent_feed=False) - assert r["hosted"] is False - assert r["verdictButtons"] == 3 # accept / reject / defer, unchanged - assert r["chipsMounted"] is False # no chips element at all — not - # merely an empty one: wheel.js - # never passed opts.intent - assert r["chipsCarryRealForward"] is False - - -def test_dispose_tray_renders_real_chips_when_intent_feed_contributed(tmp_path): - r = _run(tmp_path, _TRAY_PROBE, contribute_intent_feed=True) - assert r["hosted"] is True - assert r["verdictButtons"] == 3 - assert r["chipsMounted"] is True - assert r["chipsCarryRealForward"] is True # not just present — actually - # rendered BY the contributed - # module, not a same-named - # look-alike +# TWO PROBES STOOD HERE: the tray rendering its three verdict buttons and NO +# chips element when no intent feed is contributed, and the same tray rendering +# chips that the CONTRIBUTED module actually wrote when one is. Both mounted the +# real `views/dispose.js`, and that module is openXdox-code's package data as of +# this slice (RULED Q5, openxFactory#656 comment `5648044785`). A probe that +# imported it from `src/opendox/web/views/` would be asserting against a file +# this bundle no longer ships. +# +# THEY WERE PORTED, NOT DELETED, on the precedent slice S4's five node probes +# set one slice ago: deleting behavioural coverage in a refactor slice is how a +# move that passes every shape assertion silently breaks a verb. They run at +# openXdox-code, in `tests/test_gate_loop_probes.py`, with slice S2's own DOM +# shim carried across unchanged and against an ASSEMBLED bundle — openDox's +# `web/` with that column's modules placed into it by RULED Q5's assembly hook — +# so the byte measured is the shipped byte in the shipped position. +# +# ONE FACT MOVED WITH THEM, RULED counterpart Q6 (`#656` comment `5649094228`): +# the tray reached `renderIntentChips` by importing this bundle's +# `intent-binding.js`, and a contributed module may now import +# `./views/helpers.js` and nothing else — so the chip renderer travels in +# `opts.intent` beside the emitter, supplied by the shell that starts the feed +# (`views/wheel.js`'s mount in this leg). +# +# What stays below is everything about `views/intent-binding.js`, which is this +# bundle's own file and the seam slice S2 actually added. # ---- intentCapable's AND semantics ------------------------------------------ From 372a04da2a14c2a4c547b78e9500d65f63899aac Mon Sep 17 00:00:00 2001 From: Brett Heap <1513478+brettheap@users.noreply.github.com> Date: Sat, 12 Sep 2026 19:42:13 -0400 Subject: [PATCH 32/44] =?UTF-8?q?=C2=A7=203.4=20S7:=20tests/test=5Fdisplay?= =?UTF-8?q?=5Ffacet.py=20=E2=80=94=20the=20other=20half=20of=20the=20measu?= =?UTF-8?q?rement?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit `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, and joins the narrowed `validate.yml` list on the same footing as its seven neighbours. * THE TWO HALVES SAY THE SAME THING. The five role tables, the neutral vocabulary, the snapshot enums, the section order, the facet name, the kind and the schema version are read out of `views/display.js` AS TEXT and compared against `display_profile.py`'s — text, not an import, because the Python side cannot import an ES module and the point is that the two halves are compared rather than one of them assumed. * THE REFUSALS: a partial declaration is legal and fills from the neutral words (a facet demanding all six stations would be a flag day for every profile in the estate); an unknown role is refused with the declared set named; a blank word and a non-mapping role table are refused; and `host_display` keeps the TWO ABSENCES apart — a registered host with no facet answers `None`, an unregistered one lets the refusal through untouched. * THE STUDENT-INSTALL PROOF, the slice's own success test: no word of openxFactory's stage or status vocabulary appears anywhere in the payload a facet-less install renders from. The sweep reads VALUES and not keys, with the reason recorded: three of the eight status ROLES are spelled identically to the openxFactory words they name the role OF, which is the lifecycle column's own coincidence and not something to respell. Two neutral words that did collide have been tightened instead — the artifact labels are now "packet files" / "detail files" / "supporting files", and the `propose` act reads "start a submission" rather than "draft a submission" — in both halves, which the byte-for-byte test above holds. * THE CONTEXT HOP: `readDisplay` is named at exactly one call site, the facet rides on the payload `probeCapabilities()` already fetched, the tokens and the shell's own chrome are applied at boot, and the two `CTX_KEYS` tables agree that `ctx` carries `display`. * FIVE NODE PROBES against the REAL modules: resolve-by-role and the `DisplayRoleError` refusal; the shell refusing a payload it cannot describe (wrong kind, unknown schema version, not an object); `applyTokens` writing ONLY host-declared roles — the regression that would otherwise pin one theme's palette onto every install in the estate; two real views (`views/model.js`'s funnel columns, `views/wheel-model.js`'s reels) rendering the declared words and the neutral ones differently; and the workbench model's module-scope `setDisplay` actually moving the words and the corpus prefix. Lane: openxfactory-4-opendox-extraction Refs opensoft/openxFactory#656 Co-Authored-By: Claude Opus 5 --- .github/workflows/validate.yml | 26 ++ src/opendox/display_profile.py | 8 +- src/opendox/web/views/display.js | 8 +- tests/test_display_facet.py | 577 +++++++++++++++++++++++++++++++ 4 files changed, 611 insertions(+), 8 deletions(-) create mode 100644 tests/test_display_facet.py diff --git a/.github/workflows/validate.yml b/.github/workflows/validate.yml index adb44df0..5c58970a 100644 --- a/.github/workflows/validate.yml +++ b/.github/workflows/validate.yml @@ -130,6 +130,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 @@ -141,4 +166,5 @@ jobs: tests/test_view_registry.py tests/test_split_route_tails.py tests/test_gate_loop_contributed.py + tests/test_display_facet.py --noconftest diff --git a/src/opendox/display_profile.py b/src/opendox/display_profile.py index 07384180..34136cdb 100644 --- a/src/opendox/display_profile.py +++ b/src/opendox/display_profile.py @@ -305,14 +305,14 @@ class C — *"replace every governance word in it with a placeholder and the fil "derive": "derive candidates", "brief": "research brief", "promote": "promote to selection", - "propose": "draft a submission", + "propose": "start a submission", }, "artifacts": { "root": {"prefix": None, "label": "submission folder"}, - "packet": {"prefix": None, "label": "packet documents", + "packet": {"prefix": None, "label": "packet files", "order": []}, - "delta": {"prefix": None, "label": "detail documents"}, - "supporting": {"prefix": None, "label": "supporting documents"}, + "delta": {"prefix": None, "label": "detail files"}, + "supporting": {"prefix": None, "label": "supporting files"}, }, } diff --git a/src/opendox/web/views/display.js b/src/opendox/web/views/display.js index b975c6be..048687bd 100644 --- a/src/opendox/web/views/display.js +++ b/src/opendox/web/views/display.js @@ -303,7 +303,7 @@ export const NEUTRAL_DISPLAY = { }, acts: { derive: "derive candidates", brief: "research brief", - promote: "promote to selection", propose: "draft a submission", + promote: "promote to selection", propose: "start a submission", }, // 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 @@ -315,9 +315,9 @@ export const NEUTRAL_DISPLAY = { // groups by folder and says so. artifacts: { root: { prefix: null, label: "submission folder" }, - packet: { prefix: null, label: "packet documents", order: [] }, - delta: { prefix: null, label: "detail documents" }, - supporting: { prefix: null, label: "supporting documents" }, + packet: { prefix: null, label: "packet files", order: [] }, + delta: { prefix: null, label: "detail files" }, + supporting: { prefix: null, label: "supporting files" }, }, }; diff --git a/tests/test_display_facet.py b/tests/test_display_facet.py new file mode 100644 index 00000000..224fb459 --- /dev/null +++ b/tests/test_display_facet.py @@ -0,0 +1,577 @@ +"""THE DISPLAY FACET, BOTH HALVES, HELD TOGETHER. + +`docs/front-end-package-boundary.md` § 3.4 slice S7 (opensoft/openDox-spec #8 -> +`7d12428c`; RULED with S1-S3 at opensoft/openxFactory#656 comment +`5642758731`) parameterizes the fourteen class-C files and the four declared +class-A tails from the registered domain's profile. `tests/test_web_boundary.py` +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 a host which declares nothing gets openDox's own +neutral vocabulary and not openxFactory's, and that the two halves of the facet +-- `src/opendox/display_profile.py` and `src/opendox/web/views/display.js` -- +say the same thing. + +It stands on the same footing as its seven neighbours in `validate.yml`'s +narrowed list (`test_view_registry.py`, `test_split_route_tails.py`, +`test_gate_loop_contributed.py` and the rest): it imports `opendox`'s own +modules alone, reads bundle files as text, and drives the real +`views/display.js` under the `node` the runner already has (SKIPPED, never +failed, where node is absent). `--noconftest` safe and needs no consumer. + +THE RULE IT GUARDS, in openXdox-spec `docs/domain-profile-design-note.md` § 6's +words: *"a profile whose organized status is spelled `triaged` must work with no +engine change, which a `profile.statuses['staged']` lookup would not deliver."* +And RULING C2's consequence, which § 4.3 point 5 states as the thing to protect +against: *"a fallback to TODAY'S WORDS is how the literals survive the refactor +invisibly."* A neutral install must look VISIBLY un-domained, never invisibly +re-domained -- which is what `test_a_student_install_renders_no_openxfactory_word` +below is for. + +A CREATED FILE: no carve-manifest row (RULED OQ-C -- the manifest declares what +LEAVES openxFactory, never what a destination assembles). +""" + +from __future__ import annotations + +import json +import re +import shutil +import subprocess +from pathlib import Path + +import pytest + +from opendox import display_profile +from opendox.display_profile import ( + AREA_ROLES, + ARTIFACT_ROLES, + DISPLAY_KIND, + DISPLAY_SCHEMA_VERSION, + NEUTRAL_DISPLAY, + PROFILE_FACET, + SECTION_ORDER, + SNAPSHOT_VALUES, + STAGE_ROLES, + STATUS_ROLES, + TOKEN_ROLES, + DisplayFacetError, + display_manifest, + host_display, + normalize_display, +) + +ROOT = Path(__file__).resolve().parents[1] +WEB = ROOT / "src" / "opendox" / "web" +DISPLAY_JS = WEB / "views" / "display.js" +APP_JS = WEB / "app.js" +NODE = shutil.which("node") + +#: openxFactory's OWN vocabulary -- the words a neutral install must not show. +#: The eight controlled `Status:` words of `docs/document-lifecycle.md` plus the +#: stage nouns this tree's funnel, wheel and board used to spell. Identical to +#: `tests/test_web_boundary.py`'s watched set by construction: the two are the +#: same question asked at the two ends, and a word that left one list and not +#: the other would be a hole in whichever list forgot it. +OPENXFACTORY_WORDS = ( + "brainstorm", "staged", "draft", "ratified", "standard", + "superseded", "retired", "record", + "docs", "documents", "clusters", "cluster", "possibles", "possible", + "proposals", "proposal", "realized", "changes", "active", "archived", +) + + +#: THE SCHEMA HALF of the payload, named here rather than swept. § 2.2 rule 3's +#: whole distinction: `fields` and `values` carry the snapshot's own field names +#: and closed enums, `stage_order` / `area_order` / `artifact_roles` / +#: `token_roles` / `sections` are ROLE tables and needles, and the rest is the +#: envelope. None of it is a word a human reads. +_SCHEMA_HALF = frozenset({ + "fields", "values", "stage_order", "area_order", "artifact_roles", + "token_roles", "sections", "kind", "facet", "schema_version", + "host_profile", "host_facet", +}) + + +def _rendered_words(value) -> list[str]: + """Every string VALUE in the payload, and no key. + + A KEY here is a role name, and THREE of the eight status roles -- `ratified`, + `superseded`, `retired` -- are spelled identically to the openxFactory words + they name the role OF. That is the lifecycle-state column's own coincidence + (openXdox-spec `docs/domain-profile-design-note.md` § 6), stated in + `views/display.js`'s own comment on `STATUS_ROLE`, and it is not something + to respell: a role is a role because of where it SITS, not because of how it + looks. Sweeping keys would make this test demand that openDox rename a + neutral role to avoid resembling a domain's word, which is the tail wagging + the dog. + """ + if isinstance(value, str): + return [value] + if isinstance(value, dict): + return [w for v in value.values() for w in _rendered_words(v)] + if isinstance(value, list): + return [w for v in value for w in _rendered_words(v)] + return [] + + +# --------------------------------------------------------------------------- +# helpers +# --------------------------------------------------------------------------- + +def _js_text() -> str: + return DISPLAY_JS.read_text(encoding="utf-8") + + +def _js_array(name: str) -> list[str]: + """A `export const NAME = [...]` string array, read out of the JS half.""" + text = _js_text() + m = re.search(rf"export const {re.escape(name)} = \[(.*?)\];", text, re.S) + assert m, f"views/display.js declares no array {name}" + return re.findall(r'"([^"]*)"', m.group(1)) + + +def _js_object(name: str) -> dict[str, str]: + """A `export const NAME = {...}` flat string table, read out of the JS half. + + Deliberately TEXT, not an import: the Python side cannot import an ES + module, and the point of this file is that the two halves are compared + rather than one of them being assumed. + """ + text = _js_text() + m = re.search(rf"export const {re.escape(name)} = \{{(.*?)\n\}};", text, re.S) + assert m, f"views/display.js declares no object {name}" + body = m.group(1) + out = {} + for key, value in re.findall(r'(\w+):\s*"([^"]*)"', body): + out[key] = value + return out + + +def _run_node(source: str, tmp_path: Path) -> dict: + """Run an ES-module harness against the REAL `views/display.js`.""" + script = tmp_path / "harness.mjs" + script.write_text(source, encoding="utf-8") + proc = subprocess.run([NODE, str(script)], capture_output=True, text=True, + timeout=120) + assert proc.returncode == 0, proc.stderr + return json.loads(proc.stdout.strip().splitlines()[-1]) + + +def _import_line(module: Path | str = DISPLAY_JS) -> str: + return f"import * as D from {json.dumps(str(module))};" + + +# --------------------------------------------------------------------------- +# 1. THE TWO HALVES SAY THE SAME THING +# --------------------------------------------------------------------------- + +@pytest.mark.parametrize( + "name, python_value", + [("STAGE_ROLES", STAGE_ROLES), ("AREA_ROLES", AREA_ROLES), + ("TOKEN_ROLES", TOKEN_ROLES), ("STATUS_ROLES", STATUS_ROLES), + ("ARTIFACT_ROLES", ARTIFACT_ROLES)], +) +def test_every_role_table_is_declared_identically_on_both_sides(name, python_value): + """A ROLE is a position, and the two halves must agree about which + positions exist and IN WHAT ORDER -- `views/model.js` renders six columns + left to right and `views/wheel-model.js` six reels in the same order, so + the order is part of the declaration.""" + assert _js_array(name) == list(python_value), ( + f"{name} differs between src/opendox/display_profile.py and " + f"src/opendox/web/views/display.js. The two halves of one facet must " + f"declare the same roles in the same order, or a renderer invents an " + f"axis the server never published.") + + +def test_the_neutral_vocabulary_is_byte_for_byte_the_same_on_both_sides(): + """openDox's own words are shipped TWICE -- once for the server's payload + and once for the browser's pre-probe default -- and a difference between + them is a page that changes wording the moment `/capabilities` answers.""" + text = _js_text() + m = re.search(r"export const NEUTRAL_DISPLAY = \{(.*?)\n\};", text, re.S) + assert m, "views/display.js declares no NEUTRAL_DISPLAY" + js_words = set(re.findall(r'"([^"]*)"', m.group(1))) + + def _py_words(value): + if isinstance(value, str): + yield value + elif isinstance(value, dict): + for v in value.values(): + yield from _py_words(v) + elif isinstance(value, list): + for v in value: + yield from _py_words(v) + + py_words = set(_py_words(NEUTRAL_DISPLAY)) + missing = sorted(py_words - js_words) + assert not missing, ( + f"{missing} are in display_profile.NEUTRAL_DISPLAY and not in " + f"views/display.js's. The browser renders its own copy until the probe " + f"resolves, so a difference is a visible re-wording at first paint.") + + +def test_the_snapshot_enums_and_the_section_order_agree_on_both_sides(): + """§ 2.2 rule 3's schema half: values the renderer MATCHES, never renders. + A drift here is a column that filters on a word the generator never wrote.""" + text = _js_text() + m = re.search(r"export const SNAPSHOT_VALUES = \{(.*?)\n\};", text, re.S) + assert m + js_values = set(re.findall(r'"([^"]*)"', m.group(1))) + for table in SNAPSHOT_VALUES.values(): + for word in table.values(): + assert word in js_values, ( + f"{word!r} is a snapshot enum value on the Python side and not " + f"on the JavaScript one; the browser would match on a word the " + f"generator never writes.") + assert _js_array("SECTION_ORDER") == list(SECTION_ORDER) + + +def test_the_facet_name_kind_and_schema_version_agree_on_both_sides(): + text = _js_text() + assert f'export const DISPLAY_KIND = "{DISPLAY_KIND}";' in text + assert (f"export const DISPLAY_SCHEMA_VERSION = {DISPLAY_SCHEMA_VERSION};" + in text) + assert PROFILE_FACET == "DISPLAY" + + +# --------------------------------------------------------------------------- +# 2. THE FACET'S REFUSALS +# --------------------------------------------------------------------------- + +def test_a_partial_declaration_is_legal_and_fills_from_the_neutral_words(): + """§ 4.3's own shape: a host declares the roles it has words for and + openDox's own answer the rest. A facet that demanded all six stations + would be a flag day for every profile in the estate.""" + payload = normalize_display({"stages": {"grouping": {"one": "cluster"}}}) + assert payload["stages"]["grouping"]["one"] == "cluster" + assert (payload["stages"]["grouping"]["many"] + == NEUTRAL_DISPLAY["stages"]["grouping"]["many"]) + assert (payload["stages"]["source"]["one"] + == NEUTRAL_DISPLAY["stages"]["source"]["one"]) + + +def test_an_unknown_role_is_refused_and_the_message_names_the_declared_set(): + """A role openDox has never heard of renders nowhere, so declaring one is a + silent no-op -- and a silent no-op in a vocabulary is a blank label found + by a human, once, much later.""" + with pytest.raises(DisplayFacetError) as excinfo: + normalize_display({"stages": {"triage": {"one": "triaged item"}}}) + message = str(excinfo.value) + assert "triage" in message + assert "source" in message and "completion" in message + + +def test_a_blank_word_is_refused_rather_than_rendered_as_a_blank_surface(): + with pytest.raises(DisplayFacetError): + normalize_display({"stages": {"source": {"one": " "}}}) + + +def test_a_role_table_that_is_not_a_mapping_is_refused(): + with pytest.raises(DisplayFacetError): + normalize_display({"stages": ["source"]}) + + +def test_host_display_answers_none_for_a_registered_profile_with_no_facet(): + """TWO ABSENCES, TWO ANSWERS. A host that registered and declares no + vocabulary is `None` -- the NAMED absence -- not a refusal: every profile + in the estate is in this state today, so refusing would be a flag day + imposed by the seam that exists to avoid one.""" + class _Profile: + ROUTE_EXTENSIONS = () + + assert host_display(_Profile()) is None + + +def test_host_display_lets_a_missing_registration_refuse_untouched(): + """The other absence: no host at all. `domain_profile.current()` refuses, + and this function does not turn that into a default.""" + class _Unregistered: + def __getattr__(self, name): + raise RuntimeError("no profile is registered: call register(...)") + + with pytest.raises(RuntimeError, match="no profile is registered"): + host_display(_Unregistered()) + + +# --------------------------------------------------------------------------- +# 3. THE STUDENT INSTALL -- the slice's own success test +# --------------------------------------------------------------------------- + +def test_a_student_install_renders_no_openxfactory_word(): + """§ 4.3 point 5's failure mode, made into an assertion: *"a fallback to + TODAY'S WORDS is how the literals survive the refactor invisibly."* + + A manifest built with NO declared facet is the whole surface a student + install renders from, and no word of openxFactory's stage or status + vocabulary may appear anywhere in it -- not in a label, not in a status + word, not in a corpus prefix. The SCHEMA half is exempt by construction and + named here: `fields`, `values` and `stage_order` carry the snapshot's own + field names and closed enums, which are openDox's schema and the very thing + § 2.2 rule 3 distinguishes from a domain's vocabulary. + """ + payload = display_manifest(None, host_profile="opendox.neutral") + assert payload["host_facet"] == "absent" + assert payload["host_profile"] == "opendox.neutral" + rendered = {k: v for k, v in payload.items() + if k not in _SCHEMA_HALF} + blob = " | ".join(_rendered_words(rendered)) + offenders = sorted({w for w in OPENXFACTORY_WORDS + if re.search(rf"\b{re.escape(w)}\b", blob)}) + assert not offenders, ( + f"the neutral payload a student install renders from carries " + f"{offenders} -- openxFactory's own words, shipped to an install that " + f"never declared them. A funnel labelled `sources -> groups -> " + f"candidates` is visibly un-domained; one labelled `docs -> clusters " + f"-> possibles` is invisibly RE-domained, which is worse.") + + +def test_a_student_install_declares_no_corpus_prefix(): + """A product told no corpus layout has none. Every area falls in the + terminal `reference` bucket, and the create dialog defaults to the + repository root rather than inventing `ideation/brainstorm/`.""" + payload = display_manifest(None) + for role, area in payload["areas"].items(): + assert area["prefix"] is None, ( + f"the neutral vocabulary declares a corpus prefix for {role!r}: " + f"{area['prefix']!r}. A prefix is one domain's folder layout.") + + +def test_a_declared_facet_reaches_the_payload_whole(): + declared = { + "stages": {"grouping": {"one": "cluster", "many": "clusters", + "short": "clusters", "label": "clusters"}}, + "areas": {"captured": {"prefix": "ideation/brainstorm/", + "label": "brainstorm"}}, + "tokens": {"organized": "#0D9488"}, + } + payload = display_manifest(declared, host_profile="openxfactory.engineering") + assert payload["host_facet"] == "declared" + assert payload["stages"]["grouping"]["short"] == "clusters" + assert payload["areas"]["captured"]["prefix"] == "ideation/brainstorm/" + assert payload["tokens"]["organized"] == "#0D9488" + # and the roles it did NOT declare keep openDox's own words + assert (payload["stages"]["source"]["one"] + == NEUTRAL_DISPLAY["stages"]["source"]["one"]) + + +def test_serve_projects_the_facet_beside_the_view_registry(): + """The ONE crossing of the boundary, on the payload the shell already + fetches -- no new route and no second fetch (§ 4.3 step 1).""" + source = (ROOT / "src" / "opendox" / "serve.py").read_text(encoding="utf-8") + assert 'capabilities["display"] = display_profile.display_manifest(' in source + assert "host_display(" in source + + +# --------------------------------------------------------------------------- +# 4. THE CONTEXT HOP +# --------------------------------------------------------------------------- + +def test_the_shell_reads_the_facet_once_and_hands_it_down_through_ctx(): + """§ 4.3 steps 2-3: ONE read, at boot, then `ctx.display` to every view. + A second `readDisplay` anywhere in the shell would be a second vocabulary + that could disagree with the first.""" + app = APP_JS.read_text(encoding="utf-8") + assert 'import { readDisplay, STAGE_ROLES } from "./views/display.js";' in app + assert app.count("readDisplay(") == 1, ( + "app.js reads the facet at exactly ONE call site; a second read would " + "be a second vocabulary that could disagree with the first.") + assert "const display = readDisplay(probedCaps);" in app, ( + "the facet rides on the payload `probeCapabilities()` already fetched " + "-- no new route and no second fetch (§ 4.3 step 1).") + assert "display.applyTokens(document.documentElement);" in app + assert "applyShellVocabulary(display);" in app + assert "display: ctx.display" in app + + +def test_the_view_contract_declares_the_context_key(): + """The shell and the contributed column must agree on what `ctx` carries; + `CTX_KEYS` is where that is declared, on both sides.""" + py = (ROOT / "src" / "opendox" / "view_extension.py").read_text(encoding="utf-8") + js = (WEB / "views" / "view_extension.js").read_text(encoding="utf-8") + py_keys = set(re.findall(r'^\s*"(\w+)":', re.search( + r"CTX_KEYS[^=]*=\s*\{(.*?)\n\}", py, re.S).group(1), re.M)) + js_keys = set(re.findall(r'^\s*(\w+):', re.search( + r"CTX_KEYS\s*=\s*\{(.*?)\n\}", js, re.S).group(1), re.M)) + assert "display" in py_keys, ( + "the Python half of the view contract does not declare `ctx.display`") + assert py_keys == js_keys, ( + f"the two CTX_KEYS tables disagree: {sorted(py_keys ^ js_keys)}") + + +# --------------------------------------------------------------------------- +# 5. NODE PROBES -- the real module, and two real views +# --------------------------------------------------------------------------- + +@pytest.mark.skipif(NODE is None, reason="node is not installed") +def test_the_client_half_resolves_by_role_and_refuses_an_unknown_one(tmp_path): + out = _run_node( + _import_line() + """ +const neutral = D.neutralDisplay(); +let refused = null; +try { neutral.one("triage"); } catch (e) { refused = e.name + ": " + e.message; } +const declared = D.readDisplay({ display: { + schema_version: 1, kind: "opendox.display-facet", host_facet: "declared", + stages: { grouping: { one: "cluster", many: "clusters", short: "clusters", + label: "clusters" } }, + statuses: { document: { captured: "brainstorm" } }, + areas: { captured: { prefix: "ideation/brainstorm/", label: "brainstorm" } }, + tokens: { organized: "#123456" }, +} }); +console.log(JSON.stringify({ + neutralOne: neutral.one("grouping"), + neutralStatus: neutral.status("document", "captured"), + neutralArea: neutral.areaOf("ideation/brainstorm/a.md").role, + refused, + declaredOne: declared.one("grouping"), + declaredStatus: declared.status("document", "captured"), + declaredArea: declared.areaOf("ideation/brainstorm/a.md").role, + declaredSourceOne: declared.one("source"), + tokenVar: declared.tokenVar("organized"), +})); +""", tmp_path) + assert out["neutralOne"] == NEUTRAL_DISPLAY["stages"]["grouping"]["one"] + assert out["neutralStatus"] == "captured" + # no prefix declared -> the terminal bucket, which is the honest answer + assert out["neutralArea"] == "reference" + assert out["refused"].startswith("DisplayRoleError") + assert "triage" in out["refused"] + assert out["declaredOne"] == "cluster" + assert out["declaredStatus"] == "brainstorm" + assert out["declaredArea"] == "captured" + # the roles the host did not declare keep openDox's own words + assert out["declaredSourceOne"] == NEUTRAL_DISPLAY["stages"]["source"]["one"] + assert out["tokenVar"] == "var(--st-organized)" + + +@pytest.mark.skipif(NODE is None, reason="node is not installed") +def test_the_shell_refuses_a_display_payload_it_cannot_describe(tmp_path): + out = _run_node( + _import_line() + """ +function refusal(payload) { + try { D.readDisplay(payload); return null; } + catch (e) { return e.name + ": " + e.message; } +} +console.log(JSON.stringify({ + absent: D.readDisplay(null).hostFacet, + wrongKind: refusal({ display: { kind: "something.else", schema_version: 1 } }), + wrongVersion: refusal({ display: { kind: "opendox.display-facet", + schema_version: 99 } }), + notAnObject: refusal({ display: ["stages"] }), +})); +""", tmp_path) + assert out["absent"] == "absent" + assert "DisplayRoleError" in out["wrongKind"] + assert "DisplayRoleError" in out["wrongVersion"] + assert "DisplayRoleError" in out["notAnObject"] + + +@pytest.mark.skipif(NODE is None, reason="node is not installed") +def test_only_the_tokens_a_host_declared_are_written_onto_root(tmp_path): + """`styles.css` restates all four tokens PER THEME and an inline custom + property on `:root` outranks every one of those rules, so writing the + neutral values unconditionally would pin one theme's palette onto every + install that declares none -- which is every install in the estate today.""" + out = _run_node( + _import_line() + """ +function apply(payload) { + const written = {}; + const el = { style: { setProperty: (k, v) => { written[k] = v; } } }; + D.readDisplay(payload).applyTokens(el); + return written; +} +console.log(JSON.stringify({ + neutral: apply(null), + declared: apply({ display: { kind: "opendox.display-facet", schema_version: 1, + tokens: { organized: "#123456" } } }), +})); +""", tmp_path) + assert out["neutral"] == {}, ( + "a neutral install had its `:root` written, which shadows every dark " + "and explicit-theme rule in styles.css") + assert out["declared"] == {"--st-organized": "#123456"} + + +@pytest.mark.skipif(NODE is None, reason="node is not installed") +def test_two_real_views_render_the_declared_words(tmp_path): + """The two pure models the whole bundle's vocabulary flows through: the + funnel's column model (`views/model.js`) and the wheel deck's + (`views/wheel-model.js`). Both are driven here with a DECLARED facet and + with none, and the two runs must differ in exactly the words.""" + views = json.dumps(str(WEB / "views")) + out = _run_node(f""" +const base = {views} + "/"; +const D = await import(base + "display.js"); +const {{ buildFunnelModel }} = await import(base + "model.js"); +const {{ buildWheelModel }} = await import(base + "wheel-model.js"); +const snap = {{ + documents: [{{ id: "a.md", stage: "brainstorm" }}], + clusters: [{{ id: "c1", name: "C", document_edges: [{{ document: "a.md" }}], + tallies: {{ document_links: 1 }} }}], + possibles: [], staged_topics: [], changes: [], +}}; +const declared = D.readDisplay({{ display: {{ + schema_version: 1, kind: "opendox.display-facet", host_facet: "declared", + stages: {{ source: {{ one: "doc", many: "docs", short: "docs", label: "docs" }}, + grouping: {{ one: "cluster", many: "clusters", short: "clusters", + label: "clusters" }} }}, +}} }}); +const neutral = D.neutralDisplay(); +const labels = (d) => buildFunnelModel(snap, d).columns.map((c) => c.label); +const reels = (d) => buildWheelModel(snap, d).wheels.map((w) => w.label); +console.log(JSON.stringify({{ + neutralColumns: labels(neutral), declaredColumns: labels(declared), + neutralReels: reels(neutral), declaredReels: reels(declared), +}})); +""", tmp_path) + assert out["declaredColumns"][:2] == ["docs", "clusters"] + assert out["neutralColumns"][:2] != out["declaredColumns"][:2] + assert out["declaredReels"][:2] == ["docs", "clusters"] + assert out["neutralReels"][:2] != out["declaredReels"][:2] + for word in ("docs", "clusters"): + assert word not in out["neutralColumns"], ( + "the neutral run rendered an openxFactory word") + + +@pytest.mark.skipif(NODE is None, reason="node is not installed") +def test_the_workbench_model_takes_the_vocabulary_at_the_mount(tmp_path): + """`views/staging-workbench-model.js` is the one in-scope module that takes + the facet in MODULE SCOPE rather than on every signature -- it is derived + through from five call sites in the overlay and from the node parity + harness, and a fourth positional argument there is a worse seam than one + assignment at the mount. `setDisplay` is that assignment, and this is the + probe that it actually moves the words.""" + model = json.dumps(str(WEB / "views" / "staging-workbench-model.js")) + display = json.dumps(str(DISPLAY_JS)) + out = _run_node(f""" +const M = await import({model}); +const D = await import({display}); +const snap = {{ clusters: [{{ id: "c1", name: "C", + document_edges: [{{ document: "a.md" }}] }}], + documents: [{{ id: "a.md", path: "a.md" }}] }}; +const neutralLabel = M.workbenchScope(snap, D.SCOPE_KINDS.grouping, "c1") + .sections[0].label; +M.setDisplay(D.readDisplay({{ display: {{ + schema_version: 1, kind: "opendox.display-facet", host_facet: "declared", + stages: {{ source: {{ one: "doc", many: "docs", short: "docs", label: "docs" }}, + grouping: {{ one: "cluster", many: "clusters", short: "clusters", + label: "clusters" }} }}, + areas: {{ captured: {{ prefix: "ideation/brainstorm/", label: "brainstorm" }}, + organized: {{ prefix: "ideation/staging/", label: "staged" }} }}, +}} }})); +console.log(JSON.stringify({{ + neutralLabel, + declaredLabel: M.workbenchScope(snap, D.SCOPE_KINDS.grouping, "c1") + .sections[0].label, + neutralAreaAfterReset: (M.setDisplay(null), M.createArea(null)), + declaredArea: (M.setDisplay(D.readDisplay({{ display: {{ + schema_version: 1, kind: "opendox.display-facet", + areas: {{ captured: {{ prefix: "ideation/brainstorm/", label: "b" }} }} }} }})), + M.createArea(null)), +}})); +""", tmp_path) + assert out["neutralLabel"] == "group source items" + assert out["declaredLabel"] == "cluster docs" + # a product told no corpus layout defaults to the repository root + assert out["neutralAreaAfterReset"] == "" + assert out["declaredArea"] == "ideation/brainstorm/" From 3239c1c5f8987e8bd2df15aba13186abd0be03c0 Mon Sep 17 00:00:00 2001 From: Brett Heap <1513478+brettheap@users.noreply.github.com> Date: Sat, 12 Sep 2026 19:44:31 -0400 Subject: [PATCH 33/44] =?UTF-8?q?=C2=A7=203.4=20S7:=20the=20node=20harness?= =?UTF-8?q?es=20take=20the=20one=20sibling=20the=20models=20now=20import?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Every pure model in this bundle gained exactly ONE sibling import at this slice — `./display.js`, itself import-free by design, which is the amendment `views/helpers.js`'s scope note already carries. Six node harnesses copy one of those modules into a throwaway directory and drive it there, and a copy that brings the importer without the imported resolves nothing. Each affected harness now copies `display.js` beside it, under its OWN name (the import specifier is `./display.js`), with a `{"type": "module"}` package in the throwaway directory where there was not already one — otherwise node reads a bare `.js` as CommonJS and fails on the first `export const`. Verified by running each copy shape under the real node: `wheel-model.mjs`, `staging-workbench-model.mjs` and the whole `doc-wheel.js` graph all import clean. tests/test_doc_wheel.py · tests/test_wheel_paint_and_reach.py tests/test_doxbench_abstract_pane.py · tests/test_doxbench_context_panes.py tests/test_doc_surfaces.py · tests/test_doxbench_tile_verbs.py tests/test_wheel_verbs_dom.py · tests/test_intent_binding_dom.py The closure was audited mechanically rather than by eye: every harness that `shutil.copy`s one of the sixteen `display.js` importers either copies the sibling or `copytree`s the whole `views/` directory, and the rest only ever read those files as TEXT. Lane: openxfactory-4-opendox-extraction Refs opensoft/openxFactory#656 Co-Authored-By: Claude Opus 5 --- tests/test_doc_surfaces.py | 4 +++- tests/test_doc_wheel.py | 6 +++++- tests/test_doxbench_abstract_pane.py | 6 ++++++ tests/test_doxbench_context_panes.py | 6 ++++++ tests/test_doxbench_tile_verbs.py | 3 ++- tests/test_intent_binding_dom.py | 4 ++++ tests/test_wheel_paint_and_reach.py | 7 +++++++ tests/test_wheel_verbs_dom.py | 4 +++- 8 files changed, 36 insertions(+), 4 deletions(-) diff --git a/tests/test_doc_surfaces.py b/tests/test_doc_surfaces.py index e1396e90..97b701b0 100644 --- a/tests/test_doc_surfaces.py +++ b/tests/test_doc_surfaces.py @@ -199,7 +199,9 @@ def rendered(tmp_path_factory): if NODE is None: pytest.skip("node not available for the JS renderer probe") tmp_path = tmp_path_factory.mktemp("doc-surfaces") - for src in (DOCS_JS, LINEAGE_JS, HELPERS_JS): + # `display.js` joins at § 3.4 slice S7: both views read their vocabulary + # through it, and it imports nothing itself. + for src in (DOCS_JS, LINEAGE_JS, HELPERS_JS, DOCS_JS.parent / "display.js"): shutil.copy(src, tmp_path / src.name) # ESM without renaming: the views import "./helpers.js" by name (tmp_path / "package.json").write_text('{"type": "module"}', encoding="utf-8") diff --git a/tests/test_doc_wheel.py b/tests/test_doc_wheel.py index 03fab3e6..32d53827 100644 --- a/tests/test_doc_wheel.py +++ b/tests/test_doc_wheel.py @@ -132,7 +132,11 @@ def probe(tmp_path_factory): # their own names, so the copy has to preserve the graph. A `type: module` # package makes node read these `.js` files as the ES modules they are. (tmp / "package.json").write_text('{"type":"module"}', encoding="utf-8") - for src in (WHEEL_MODEL_JS, MODEL_JS, DOC_WHEEL_JS, VIEWS / "helpers.js"): + # `views/display.js` joins the graph at § 3.4 slice S7: the five pure models + # each import exactly one sibling now, and it is that one (itself + # import-free by design, so the graph gains a leaf and not a branch). + for src in (WHEEL_MODEL_JS, MODEL_JS, DOC_WHEEL_JS, VIEWS / "helpers.js", + VIEWS / "display.js"): if not src.exists(): pytest.fail(f"{src.name} does not exist yet") shutil.copy(src, tmp / src.name) diff --git a/tests/test_doxbench_abstract_pane.py b/tests/test_doxbench_abstract_pane.py index a0d91ef8..7b98e9ca 100644 --- a/tests/test_doxbench_abstract_pane.py +++ b/tests/test_doxbench_abstract_pane.py @@ -150,6 +150,12 @@ def formatter(tmp_path_factory): pytest.skip("node not available for the abstract-formatter probe") tmp_path = tmp_path_factory.mktemp("doxbench-abstract-formatter") shutil.copy(MODEL_JS, tmp_path / "staging-workbench-model.mjs") + # § 3.4 slice S7: the model imports `./display.js` for the vocabulary it no + # longer spells. The sibling keeps its OWN name (that is the import + # specifier) and the throwaway directory declares `type: module`, so node + # reads the `.js` file as the ES module it is. + shutil.copy(MODEL_JS.parent / "display.js", tmp_path / "display.js") + (tmp_path / "package.json").write_text('{"type":"module"}', encoding="utf-8") harness = tmp_path / "formatter-harness.mjs" harness.write_text(_FORMATTER_HARNESS, encoding="utf-8") proc = subprocess.run([NODE, str(harness)], capture_output=True, diff --git a/tests/test_doxbench_context_panes.py b/tests/test_doxbench_context_panes.py index 2ba2f630..e55be4fa 100644 --- a/tests/test_doxbench_context_panes.py +++ b/tests/test_doxbench_context_panes.py @@ -115,6 +115,12 @@ def abstract(tmp_path_factory): pytest.skip("node not available for the document-abstract probe") tmp_path = tmp_path_factory.mktemp("doxbench-abstract") shutil.copy(MODEL_JS, tmp_path / "staging-workbench-model.mjs") + # § 3.4 slice S7: the model imports `./display.js` for the vocabulary it no + # longer spells. The sibling keeps its OWN name (that is the import + # specifier) and the throwaway directory declares `type: module`, so node + # reads the `.js` file as the ES module it is. + shutil.copy(MODEL_JS.parent / "display.js", tmp_path / "display.js") + (tmp_path / "package.json").write_text('{"type":"module"}', encoding="utf-8") harness = tmp_path / "abstract-harness.mjs" harness.write_text(_ABSTRACT_HARNESS, encoding="utf-8") proc = subprocess.run([NODE, str(harness)], capture_output=True, diff --git a/tests/test_doxbench_tile_verbs.py b/tests/test_doxbench_tile_verbs.py index 3b29202f..d7fde098 100644 --- a/tests/test_doxbench_tile_verbs.py +++ b/tests/test_doxbench_tile_verbs.py @@ -285,7 +285,8 @@ def tile_results(tmp_path_factory): if NODE is None: pytest.skip("node not available for the doxBench tile-verb probe") root = tmp_path_factory.mktemp("doxbench-tile-verbs") - for name in ("doc-wheel.js", "wheel-model.js", "helpers.js"): + # `display.js` joins at § 3.4 slice S7 (the wheel model's vocabulary). + for name in ("doc-wheel.js", "wheel-model.js", "helpers.js", "display.js"): shutil.copy(VIEWS / name, root / name) (root / "package.json").write_text('{"type": "module"}', encoding="utf-8") harness = root / "tile-harness.mjs" diff --git a/tests/test_intent_binding_dom.py b/tests/test_intent_binding_dom.py index 381bf2f1..f73049fe 100644 --- a/tests/test_intent_binding_dom.py +++ b/tests/test_intent_binding_dom.py @@ -58,6 +58,10 @@ WHEEL_CLOSURE = ( "wheel.js", "wheel-model.js", "helpers.js", "dispose.js", "intent-binding.js", "notebook.js", "settings.js", + # § 3.4 slice S7: the wheel and its model read the registered domain's + # vocabulary through `display.js`, which is import-free by design -- the + # closure gains a leaf, not a branch. + "display.js", ) # A minimal FAKE intent-feed.js — standing in for openxFactory's real 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") From 4228675e84ee6023ebc05c74e4c8997cde7290ae Mon Sep 17 00:00:00 2001 From: Brett Heap <1513478+brettheap@users.noreply.github.com> Date: Sat, 12 Sep 2026 20:01:55 -0400 Subject: [PATCH 34/44] =?UTF-8?q?=C2=A7=203.4=20S7:=20Copilot=20round=201?= =?UTF-8?q?=20=E2=80=94=20five=20accurate=20findings,=20and=20the=20merge?= =?UTF-8?q?=20that=20found=20a=20sixth?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit FIXED, all five that were still live (the other seven name harness closures and a missing test file that later commits on this branch already carried): * `views/board.js`:87 — the badge LABEL read the domain's proposed-candidate word while the count behind it compared the literal `"picked"`, so a profile that renamed `possibles[].state` would have shown the right word beside a permanent zero. Both halves now read `registerState(STATUS_ROLE.PROPOSED)`. * `views/funnel.js`:139/156 and `views/canvas.js`:145/151 — the same defect in the two metadata branches: a picked candidate matched on `"picked"` and rendered the literal beside its `→ staging_id`, and the seeded state read `"latent"`. Both the value MATCHED and the word RENDERED now come off the facet, so a renamed register state keeps its metadata instead of falling through to the bare state. * `views/wheel-model.js` — `isPromotableTile` compared `"latent"`, which would have hidden the promote verb from every real tile under a profile that renamed it: the same defect class as the 2026-08-02 one that predicate's own comment records, one layer up. It and the `research-brief` row's twin now read the role off `env.display`, and `synthesizeDemoPossibles` takes the vocabulary for the state it seeds. * `views/display.js` / `display_profile.py` — `ACT_IDS` declares FIVE verb seam keys and the act vocabulary declared four, so `display.act("demote")` could not resolve, the wheel had to keep a hardcoded word, and a host declaring `acts.demote` was REFUSED as an unknown role. The fifth act is declared on both halves and the wheel's demote row reads it. * `tests/test_outline_tab.py` asserted `outline-model.js` "imports nothing at all". Amended to the rule `views/helpers.js`'s scope note now records: the five pure models may import EXACTLY ONE sibling, `./display.js`, which is import-free by design. The property the assertion exists to hold — no DOM, no transport, no view — is unchanged and is now stated rather than approximated. AND A SIXTH, found merging the base in: `views/wheel.js`'s module-level `ACTION_MOUNTERS` named `disposeColumn`, which S5 leg B's round-2 Copilot fix had just made a `const` inside `renderWheel` — a ReferenceError the first time a human pressed a wheel verb. The four entries reach the column through `opts.dispose` now, as their `propose` sibling already did, keeping the `ACT_IDS` seam keys. Narrowed validate: 277 passed, 0 xfailed. Lane: openxfactory-4-opendox-extraction Refs opensoft/openxFactory#656 Co-Authored-By: Claude Opus 5 --- src/opendox/display_profile.py | 5 ++++ src/opendox/web/views/board.js | 7 +++++- src/opendox/web/views/canvas.js | 8 ++++--- src/opendox/web/views/display.js | 4 ++++ src/opendox/web/views/funnel.js | 11 ++++++--- src/opendox/web/views/wheel-model.js | 32 ++++++++++++++++++------- tests/fixtures/web_boundary_census.yaml | 14 +++++------ tests/test_outline_tab.py | 18 +++++++++++--- 8 files changed, 73 insertions(+), 26 deletions(-) diff --git a/src/opendox/display_profile.py b/src/opendox/display_profile.py index 34136cdb..7a30a80d 100644 --- a/src/opendox/display_profile.py +++ b/src/opendox/display_profile.py @@ -306,6 +306,11 @@ class C — *"replace every governance word in it with a placeholder and the fil "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"}, diff --git a/src/opendox/web/views/board.js b/src/opendox/web/views/board.js index b1ed99b9..e87b0aec 100644 --- a/src/opendox/web/views/board.js +++ b/src/opendox/web/views/board.js @@ -84,7 +84,12 @@ function possiblesForDoc(docId, indexes) { for (const p of indexes.possiblesByCluster.get(clusterId) || []) seen.set(p.id, p); } const all = [...seen.values()]; - return { total: all.length, picked: all.filter((p) => p.state === "picked").length }; + // THE REGISTER STATE BY ROLE (Copilot review). The badge LABEL reads the + // domain's proposed-candidate word; the count behind it compared a literal + // `"picked"`, so a profile that renamed `possibles[].state` would have shown + // the right word beside a permanent zero. + const proposed = vocab.registerState(STATUS_ROLE.PROPOSED); + return { total: all.length, picked: all.filter((p) => p.state === proposed).length }; } function hay(parts) { diff --git a/src/opendox/web/views/canvas.js b/src/opendox/web/views/canvas.js index beb3c088..21b53f40 100644 --- a/src/opendox/web/views/canvas.js +++ b/src/opendox/web/views/canvas.js @@ -142,14 +142,16 @@ function evidencePane(model) { // ---- pane 3: possibles rail (T021 makes this interactive) ---- function possibleCard(p) { - const state = p.state || "latent"; + // THE SEEDED STATE BY ROLE (Copilot review), like the branch below it. + const state = p.state || vocab.registerState(STATUS_ROLE.CAPTURED); const card = el("div", "card tile-candidate " + state); card.appendChild(el("span", "dot")); const body = el("div"); body.appendChild(el("div", "title", p.title || p.id)); let meta = state; - if (state === "picked" && p.pick) { - meta = "picked → " + (p.pick.staging_id || ""); + if (state === vocab.registerState(STATUS_ROLE.PROPOSED) && p.pick) { + meta = vocab.status(VOCABULARY.CANDIDATE, STATUS_ROLE.PROPOSED) + + " → " + (p.pick.staging_id || ""); if (p.pick.change_id) meta += " · " + p.pick.change_id; } else if ((state === vocab.registerState(STATUS_ROLE.RETIRED) || state === vocab.registerState(STATUS_ROLE.SUPERSEDED)) diff --git a/src/opendox/web/views/display.js b/src/opendox/web/views/display.js index 048687bd..cea6a106 100644 --- a/src/opendox/web/views/display.js +++ b/src/opendox/web/views/display.js @@ -304,6 +304,10 @@ export const NEUTRAL_DISPLAY = { 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, + // so the vocabulary declares five words. Without it `display.act("demote")` + // refused and the wheel kept a hardcoded one. + demote: "return to the previous station", }, // 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 diff --git a/src/opendox/web/views/funnel.js b/src/opendox/web/views/funnel.js index bfb3bdf3..597ce3d3 100644 --- a/src/opendox/web/views/funnel.js +++ b/src/opendox/web/views/funnel.js @@ -136,8 +136,13 @@ function clusterCard(node, notebook) { } function possibleMeta(p, state, shared) { - if (state === "picked" && p.pick) { - let meta = "picked → " + (p.pick.staging_id || ""); + // BOTH HALVES BY ROLE (Copilot review): the value MATCHED against + // `possibles[].state` and the word RENDERED beside it come off the same + // facet, so a profile that renames the proposed register state keeps its + // `→ staging_id` metadata instead of falling through to the bare state. + if (state === vocab.registerState(STATUS_ROLE.PROPOSED) && p.pick) { + let meta = vocab.status(VOCABULARY.CANDIDATE, STATUS_ROLE.PROPOSED) + + " → " + (p.pick.staging_id || ""); if (p.pick.change_id) meta += " · " + p.pick.change_id; return meta; } @@ -153,7 +158,7 @@ function possibleMeta(p, state, shared) { function possibleCard(node) { const p = node.possible; - const state = p.state || "latent"; + const state = p.state || vocab.registerState(STATUS_ROLE.CAPTURED); const shared = (p.claiming_clusters || []).length > 1; const card = el("div", "card tile-candidate " + state + " stage-brainstorm" + (shared ? " shared" : "")); card.id = node.domId; diff --git a/src/opendox/web/views/wheel-model.js b/src/opendox/web/views/wheel-model.js index dd50ea75..00a7a5df 100644 --- a/src/opendox/web/views/wheel-model.js +++ b/src/opendox/web/views/wheel-model.js @@ -36,7 +36,7 @@ // wheel reads is declared once, in `display.js`'s `SNAPSHOT_FIELDS` (§ 2.2 rule // 3), and reached here through `display.items(snapshot, role)`. -import { ACT_IDS, STAGE_ROLES, neutralDisplay } from "./display.js"; +import { ACT_IDS, STAGE_ROLES, STATUS_ROLE, neutralDisplay } from "./display.js"; export const WHEEL_KEYS = STAGE_ROLES; @@ -59,7 +59,8 @@ export function isUndisposedDerived(possible) { // wheel MAY show synthesized placeholders derived from real clusters — each // demo-tagged and threaded in dashed brass, never confusable with indexed // data. Deterministic: top clusters by document-link tally, id order tiebreak. -export function synthesizeDemoPossibles(clusters) { +export function synthesizeDemoPossibles(clusters, display) { + const d = display || neutralDisplay(); const ranked = [...(clusters || [])].sort((a, b) => { const ta = a.tallies?.document_links || 0; const tb = b.tallies?.document_links || 0; @@ -68,7 +69,9 @@ export function synthesizeDemoPossibles(clusters) { return ranked.slice(0, MAX_DEMO_POSSIBLES).map((c) => ({ id: "demo-" + c.id, title: "Possible: " + (c.name || c.id), - state: "latent", + // the SEEDED register state, by role (§ 2.2 rule 3's enum half) — a value + // the wheel MATCHES against `possibles[].state`, never one it renders + state: d.registerState(STATUS_ROLE.CAPTURED), demo: true, claiming_clusters: [c.id], })); @@ -199,7 +202,7 @@ export function buildWheelModel(snapshot, display) { const changes = (s[d.field(SUBMISSION)]) || []; const demoMode = realCandidates.length === 0; - const candidates = demoMode ? synthesizeDemoPossibles(groups) : realCandidates; + const candidates = demoMode ? synthesizeDemoPossibles(groups, d) : realCandidates; const submissions = d.items(s, SUBMISSION); const completions = d.items(s, COMPLETION); @@ -605,8 +608,16 @@ const gatedAndNotYetActed = (item, env) => !!env.gate && !env.commissioned; // item shape (2026-08-02). const tileState = (item) => item?.ref?.state; -const isPromotableTile = (item) => - tileState(item) === "latent" && !item?.derivedPending && !item?.demo; +// THE PROMOTABLE STATE BY ROLE (Copilot review). `"latent"` is a value the +// display facet's `register_state` may override, so a profile that renamed it +// would have hidden the promote verb from every real tile — the same defect +// class as the 2026-08-02 one this predicate's own comment records, one layer +// up. `env` carries the live vocabulary; a caller that supplies none gets +// openDox's own. +const isPromotableTile = (item, env) => + tileState(item) === (env?.display || neutralDisplay()) + .registerState(STATUS_ROLE.CAPTURED) + && !item?.derivedPending && !item?.demo; // Has a human recorded a CLOSING verdict on this possible? // @@ -679,7 +690,8 @@ export const WHEEL_ACTIONS = { // re-checks the register and is the authority. id: ACT_IDS.promote, label: (d) => "▲ " + d.act("promote"), - visible: (item, env) => gatedAndNotYetActed(item, env) && isPromotableTile(item), + visible: (item, env) => gatedAndNotYetActed(item, env) + && isPromotableTile(item, env), }, { // commissions a PRE-VERDICT evidence brief. The view hides it once the @@ -690,7 +702,9 @@ export const WHEEL_ACTIONS = { label: (d) => "✻ " + d.act("brief"), visible: (item, env) => gatedAndNotYetActed(item, env) && !item?.demo && !hasClosingVerdict(item) - && (tileState(item) === "latent" || !!item?.derivedPending), + && (tileState(item) === (env?.display || neutralDisplay()) + .registerState(STATUS_ROLE.CAPTURED) + || !!item?.derivedPending), }, workbenchRow, openRepoRow, @@ -740,7 +754,7 @@ export const WHEEL_ACTIONS = { // engine-side duplicate guard, so this is the only thing standing between // an accidental double-click and a second full artifact set. id: ACT_IDS.demote, - label: "\u25c0 demote", + label: (d) => "\u25c0 " + d.act("demote"), visible: gatedAndNotYetActed, }, notebookRow, diff --git a/tests/fixtures/web_boundary_census.yaml b/tests/fixtures/web_boundary_census.yaml index 441e4b43..c43613c3 100644 --- a/tests/fixtures/web_boundary_census.yaml +++ b/tests/fixtures/web_boundary_census.yaml @@ -191,9 +191,9 @@ measured_at: "opensoft/openDox-code main a99eba03e31a0aee1cc15a061fdf718cc88a2c4 # shape and `test_the_declared_totals_are_re_derived_from_the_rows` can refuse a # drift between the two. Measured at slice S4 (see the S4 block above). totals: - A: {files: 26, loc: 17678} + A: {files: 26, loc: 17682} B: {files: 1, loc: 73} - C: {files: 14, loc: 12411} + C: {files: 14, loc: 12437} "?": {files: 1, loc: 1435} "?": {files: 1, loc: 1435} files: @@ -229,7 +229,7 @@ files: - path: views/board.js class: C - loc: 297 + loc: 302 note: "four lifecycle columns; 25 governance literals" - path: views/bullseye.js @@ -244,7 +244,7 @@ files: - path: views/canvas.js class: C - loc: 440 + loc: 442 note: "renders canvas-model.js's output; 7 governance literals" - path: views/composed-model.js @@ -255,7 +255,7 @@ files: - path: views/display.js class: A - loc: 589 + loc: 593 exempt: [SNAPSHOT_FIELDS, ACT_IDS, TILE_KINDS, SCOPE_KINDS, TAB_IDS, SESSION_SCOPE_KINDS, SESSION_BRANCH_NAMESPACES, SNAPSHOT_VALUES, DRILL_KINDS, DRAFT_PATHS, SECTION_ORDER] @@ -310,7 +310,7 @@ files: - path: views/funnel.js class: C - loc: 575 + loc: 580 note: "realization funnel; imports model.js's COLUMN_KEYS; 10 governance literals" - path: views/grouping.js @@ -408,7 +408,7 @@ files: - path: views/wheel-model.js class: C - loc: 1333 + loc: 1347 note: "WHEEL_KEYS :25 and WHEEL_LABELS :27-34 -- six stage names, spelled twice" - path: views/wheel.js diff --git a/tests/test_outline_tab.py b/tests/test_outline_tab.py index d8a5d730..1d186ecf 100644 --- a/tests/test_outline_tab.py +++ b/tests/test_outline_tab.py @@ -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).") # --------------------------------------------------------------------------- From 16f42ff721e590a033d3837b0356d7d3751dff51 Mon Sep 17 00:00:00 2001 From: Brett Heap <1513478+brettheap@users.noreply.github.com> Date: Sat, 12 Sep 2026 20:05:15 -0400 Subject: [PATCH 35/44] =?UTF-8?q?=C2=A7=203.4=20S7:=20Copilot=20round=202?= =?UTF-8?q?=20=E2=80=94=20the=20enum=20leaks=20the=20facet=20can=20cause,?= =?UTF-8?q?=20and=20one=20loose=20check=20of=20my=20own?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Six findings, all accurate, all fixed. * **THE ENUM VALUE IS NOT A WORD AND NOT A CLASS.** `views/canvas.js` and `views/funnel.js` rendered `possibles[].state` straight into the card's meta line AND composed it into the card's CSS class. Both are wrong the moment a host overrides `register_state`: the meta line leaks schema text and all four `.tile-candidate.*` rules stop matching at once. `views/display.js` gains the REVERSE lookup — `registerRole(value)` / `documentStageRole(value)` — so a view resolves the value to a ROLE and then asks for the word (`status(vocabulary, role)`) and the class (`cstate-`) by that role; both follow the override together. `styles.css`'s four candidate-state hooks are renamed to match. A value no declared role carries renders verbatim: an unrecognised enum value is the generator's news, not a role to invent. * `views/repo-selector-model.js` — `emptyStations` was made display-aware and its `sparseNotice` wrapper was not, so a sparse repository named its stations in openDox's neutral words even where a host had declared its own. The wrapper takes and forwards the facet. * `tests/test_doc_surfaces.py` asserted the docs binding's exact source string, which moved when the binding gained `display: ctx.display`. It now asserts the PROPERTY it was written for — the doc list reaches app.js's one `nav.openDoc` and constructs no second viewer — rather than the spelling. * `tests/test_web_boundary.py` — MY OWN check, and the finding is right: an `or "display" in text` fallback treated a comment, or an identifier like `displayVocabulary`, as proof that a file reads the facet. That is exactly the class of "an exemption that is silence" this module exists to refuse. Every in-scope file but the two the shell reaches INTO must now carry the sibling import itself. Narrowed validate: 277 passed, 0 xfailed. Lane: openxfactory-4-opendox-extraction Refs opensoft/openxFactory#656 Co-Authored-By: Claude Opus 5 --- src/opendox/web/styles.css | 20 ++++++++++++------- src/opendox/web/views/canvas.js | 18 ++++++++++++++--- src/opendox/web/views/display.js | 21 ++++++++++++++++++++ src/opendox/web/views/funnel.js | 19 ++++++++++++++---- src/opendox/web/views/repo-selector-model.js | 7 +++++-- tests/fixtures/web_boundary_census.yaml | 14 ++++++------- tests/test_doc_surfaces.py | 8 +++++++- tests/test_web_boundary.py | 8 +++++++- 8 files changed, 90 insertions(+), 25 deletions(-) diff --git a/src/opendox/web/styles.css b/src/opendox/web/styles.css index 5302cb2c..069eeadb 100644 --- a/src/opendox/web/styles.css +++ b/src/opendox/web/styles.css @@ -380,13 +380,19 @@ svg.edges path.topic { stroke: var(--st-captured); stroke-dasharray: 4 3; opacit .tile-candidate { padding: 5px 9px 5px 10px; display: flex; align-items: flex-start; gap: 8px; } .tile-candidate .dot { flex: none; width: 9px; height: 9px; border-radius: 50%; margin-top: 4px; } -.tile-candidate.latent { border-style: dashed; } -.tile-candidate.latent .dot { border: 1.5px dashed var(--faint-ink); background: transparent; } -.tile-candidate.picked .dot { background: var(--st-organized); } -.tile-candidate.rejected .dot { background: var(--blocked); } -.tile-candidate.rejected .title { color: var(--muted); } -.tile-candidate.superseded .dot { background: transparent; border: 1.5px solid var(--faint-ink); } -.tile-candidate.superseded .title { text-decoration: line-through; color: var(--muted); font-weight: 400; } +/* THE CANDIDATE-STATE HOOKS ARE KEYED BY ROLE (§ 3.4 slice S7, Copilot round + 2). They were `.latent` / `.picked` / `.rejected` / `.superseded` — the raw + `possibles[].state` enum, composed into a class by the two views that draw a + candidate tile — so a host that overrode `register_state` lost all four + rules at once and put schema text in the DOM besides. The role travels with + the override; the value does not. */ +.tile-candidate.cstate-captured { border-style: dashed; } +.tile-candidate.cstate-captured .dot { border: 1.5px dashed var(--faint-ink); background: transparent; } +.tile-candidate.cstate-proposed .dot { background: var(--st-organized); } +.tile-candidate.cstate-retired .dot { background: var(--blocked); } +.tile-candidate.cstate-retired .title { color: var(--muted); } +.tile-candidate.cstate-superseded .dot { background: transparent; border: 1.5px solid var(--faint-ink); } +.tile-candidate.cstate-superseded .title { text-decoration: line-through; color: var(--muted); font-weight: 400; } .tile-candidate .title { font-size: 12.5px; font-weight: 500; } .tile-candidate .meta { font-size: 11px; } .tile-candidate.shared { border-color: var(--st-captured); } diff --git a/src/opendox/web/views/canvas.js b/src/opendox/web/views/canvas.js index 21b53f40..2dd48876 100644 --- a/src/opendox/web/views/canvas.js +++ b/src/opendox/web/views/canvas.js @@ -144,11 +144,22 @@ function evidencePane(model) { function possibleCard(p) { // THE SEEDED STATE BY ROLE (Copilot review), like the branch below it. const state = p.state || vocab.registerState(STATUS_ROLE.CAPTURED); - const card = el("div", "card tile-candidate " + state); + // THE CLASS IS KEYED BY ROLE, NOT BY THE ENUM VALUE (Copilot round 2). The + // class used to be the raw `possibles[].state`, so a host that overrode + // `register_state` both leaked schema text into the DOM and stopped matching + // `styles.css`'s `.tile-candidate.cstate-*` rules. The role travels; the word + // does not. + const stateRole = vocab.registerRole(state); + const card = el("div", "card tile-candidate" + + (stateRole ? " cstate-" + stateRole : "")); card.appendChild(el("span", "dot")); const body = el("div"); body.appendChild(el("div", "title", p.title || p.id)); - let meta = state; + // THE WORD COMES OFF THE FACET, never off the snapshot (Copilot round 2). An + // enum value no declared role carries is rendered verbatim — it is the + // generator's news and not a role to invent. + let meta = stateRole + ? vocab.status(VOCABULARY.CANDIDATE, stateRole) : state; if (state === vocab.registerState(STATUS_ROLE.PROPOSED) && p.pick) { meta = vocab.status(VOCABULARY.CANDIDATE, STATUS_ROLE.PROPOSED) + " → " + (p.pick.staging_id || ""); @@ -156,7 +167,8 @@ function possibleCard(p) { } else if ((state === vocab.registerState(STATUS_ROLE.RETIRED) || state === vocab.registerState(STATUS_ROLE.SUPERSEDED)) && p.reason) { - meta = state + " — " + p.reason; + meta = (stateRole ? vocab.status(VOCABULARY.CANDIDATE, stateRole) : state) + + " — " + p.reason; } body.appendChild(el("div", "meta", meta)); card.appendChild(body); diff --git a/src/opendox/web/views/display.js b/src/opendox/web/views/display.js index cea6a106..b64cfc31 100644 --- a/src/opendox/web/views/display.js +++ b/src/opendox/web/views/display.js @@ -470,6 +470,27 @@ export class Display { documentStage(role) { return this._value("document_stage", role); } registerState(role) { return this._value("register_state", role); } + // THE REVERSE LOOKUP: which ROLE is this snapshot enum value? (Copilot round + // 2.) `documents[].stage` and `possibles[].state` arrive from the generator as + // VALUES, and a view that rendered one straight — or that composed a CSS class + // out of one — would leak schema text and lose its styling the moment a host + // overrode the enum. A view resolves the value to a role HERE and then asks + // for the word (`status(vocabulary, role)`) and the class (`-`) + // by that role, so both follow the override together. `null` for a value no + // declared role carries, which the caller renders verbatim: an unrecognised + // enum value is the generator's news, not a role to invent. + registerRole(value) { return this._roleOf("register_state", value); } + documentStageRole(value) { return this._roleOf("document_stage", value); } + + _roleOf(name, value) { + const table = this._values[name]; + if (!table) refuseRole("snapshot enum", name, Object.keys(this._values)); + for (const role of Object.keys(table)) { + if (table[role] === value) return role; + } + return null; + } + _value(name, role) { const table = this._values[name]; if (!table) refuseRole("snapshot enum", name, Object.keys(this._values)); diff --git a/src/opendox/web/views/funnel.js b/src/opendox/web/views/funnel.js index 597ce3d3..1d230c5d 100644 --- a/src/opendox/web/views/funnel.js +++ b/src/opendox/web/views/funnel.js @@ -136,6 +136,13 @@ function clusterCard(node, notebook) { } function possibleMeta(p, state, shared) { + // THE RENDERED WORD COMES OFF THE FACET (Copilot round 2): `state` is the + // snapshot ENUM, and returning it as user-facing text leaked schema words the + // moment a host overrode `register_state`. Resolved to a role first; a value + // no declared role carries renders verbatim, because it is the generator's + // news and not a role to invent. + const role = vocab.registerRole(state); + const word = role ? vocab.status(VOCABULARY.CANDIDATE, role) : state; // BOTH HALVES BY ROLE (Copilot review): the value MATCHED against // `possibles[].state` and the word RENDERED beside it come off the same // facet, so a profile that renames the proposed register state keeps its @@ -148,19 +155,23 @@ function possibleMeta(p, state, shared) { } if ((state === vocab.registerState(STATUS_ROLE.RETIRED) || state === vocab.registerState(STATUS_ROLE.SUPERSEDED)) - && p.reason) return state + " — " + p.reason; + && p.reason) return word + " — " + p.reason; if (shared) { - return state + " — claimed by " + p.claiming_clusters.length + " " + return word + " — claimed by " + p.claiming_clusters.length + " " + vocab.count(GROUPING, p.claiming_clusters.length); } - return state; + return word; } function possibleCard(node) { const p = node.possible; const state = p.state || vocab.registerState(STATUS_ROLE.CAPTURED); const shared = (p.claiming_clusters || []).length > 1; - const card = el("div", "card tile-candidate " + state + " stage-brainstorm" + (shared ? " shared" : "")); + // THE CLASS IS KEYED BY ROLE (Copilot round 2), like the canvas rail's. + const stateRole = vocab.registerRole(state); + const card = el("div", "card tile-candidate" + + (stateRole ? " cstate-" + stateRole : "") + + " stage-brainstorm" + (shared ? " shared" : "")); card.id = node.domId; card.tabIndex = 0; card.dataset.node = ""; diff --git a/src/opendox/web/views/repo-selector-model.js b/src/opendox/web/views/repo-selector-model.js index 2fa621fa..a0b065fb 100644 --- a/src/opendox/web/views/repo-selector-model.js +++ b/src/opendox/web/views/repo-selector-model.js @@ -541,8 +541,11 @@ export function emptyStations(snapshot, display) { .map(([key, label]) => ({ key, label })); } -export function sparseNotice(option, snapshot) { - const empty = emptyStations(snapshot); +// THE WRAPPER FORWARDS THE FACET (Copilot round 2). `emptyStations` was made +// display-aware and this caller was not, so a sparse repository named its +// stations in openDox's neutral words even where a host had declared its own. +export function sparseNotice(option, snapshot, display) { + const empty = emptyStations(snapshot, display); if (!empty.length) return null; const repository = (option && option.repository) || snapshot?.repository || "this repository"; return "no " + empty.map((s) => s.label).join(", no ") + " in " + repository diff --git a/tests/fixtures/web_boundary_census.yaml b/tests/fixtures/web_boundary_census.yaml index c43613c3..2b12f9b0 100644 --- a/tests/fixtures/web_boundary_census.yaml +++ b/tests/fixtures/web_boundary_census.yaml @@ -191,9 +191,9 @@ measured_at: "opensoft/openDox-code main a99eba03e31a0aee1cc15a061fdf718cc88a2c4 # shape and `test_the_declared_totals_are_re_derived_from_the_rows` can refuse a # drift between the two. Measured at slice S4 (see the S4 block above). totals: - A: {files: 26, loc: 17682} + A: {files: 26, loc: 17706} B: {files: 1, loc: 73} - C: {files: 14, loc: 12437} + C: {files: 14, loc: 12466} "?": {files: 1, loc: 1435} "?": {files: 1, loc: 1435} files: @@ -209,7 +209,7 @@ files: - path: styles.css class: C - loc: 2589 + loc: 2595 note: "four --st-brainstorm/--st-staged/--st-proposal/--st-realized status colour tokens (16 definitions); :1278-1295 styles intent-feed's chips" - path: vendor/markdown-it.min.js @@ -244,7 +244,7 @@ files: - path: views/canvas.js class: C - loc: 442 + loc: 454 note: "renders canvas-model.js's output; 7 governance literals" - path: views/composed-model.js @@ -255,7 +255,7 @@ files: - path: views/display.js class: A - loc: 593 + loc: 614 exempt: [SNAPSHOT_FIELDS, ACT_IDS, TILE_KINDS, SCOPE_KINDS, TAB_IDS, SESSION_SCOPE_KINDS, SESSION_BRANCH_NAMESPACES, SNAPSHOT_VALUES, DRILL_KINDS, DRAFT_PATHS, SECTION_ORDER] @@ -310,7 +310,7 @@ files: - path: views/funnel.js class: C - loc: 580 + loc: 591 note: "realization funnel; imports model.js's COLUMN_KEYS; 10 governance literals" - path: views/grouping.js @@ -366,7 +366,7 @@ files: - path: views/repo-selector-model.js class: A - loc: 550 + loc: 553 tail: stations note: "STATIONS :517-522 paired each schema key with a rendered label. PARAMETERIZED AT S7: `stations(display)` walks the spine and deduplicates by snapshot FIELD, so a repository carrying no changes reports ONE empty station rather than two" diff --git a/tests/test_doc_surfaces.py b/tests/test_doc_surfaces.py index 97b701b0..a1814843 100644 --- a/tests/test_doc_surfaces.py +++ b/tests/test_doc_surfaces.py @@ -291,7 +291,13 @@ def test_the_doc_tab_is_wired_to_the_one_cross_view_jump(): app = APP_JS.read_text(encoding="utf-8") block = app.split('{ id: "docs.list", control: "tab-docs", region: "view-docs",', 1)[1].split("},", 1)[0] - assert "renderDocs(root, snap, { onOpenDoc: ctx.nav.openDoc })" in block + # The binding gained `display: ctx.display` at § 3.4 slice S7, so the exact + # source string moved. The PROPERTY this test holds is the cross-view jump — + # the doc list reaches app.js's ONE `nav.openDoc`, not a second viewer — and + # it is asserted here rather than the whole call's spelling. + assert "renderDocs(root, snap, {" in block + assert "onOpenDoc: ctx.nav.openDoc" in block + assert "renderViewer" not in block # --------------------------------------------------------------------------- diff --git a/tests/test_web_boundary.py b/tests/test_web_boundary.py index 3be1b392..1a487e84 100644 --- a/tests/test_web_boundary.py +++ b/tests/test_web_boundary.py @@ -1125,7 +1125,13 @@ def test_every_in_scope_file_reads_the_display_facet() -> None: if path in through_the_shell: assert through_the_shell[path] in text, path continue - if 'from "./display.js"' not in text and "display" not in text: + # 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 " From 173ac12b43701702694f325def14cb4814f49ba9 Mon Sep 17 00:00:00 2001 From: Brett Heap <1513478+brettheap@users.noreply.github.com> Date: Sat, 12 Sep 2026 20:07:40 -0400 Subject: [PATCH 36/44] =?UTF-8?q?=C2=A7=203.4=20S7:=20a=20declared=20corpu?= =?UTF-8?q?s=20prefix=20must=20carry=20its=20separator?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The explorer thread's finding, done rather than owed. `areas..prefix` and `artifacts..prefix` are compared with a prefix test AND composed into a path, so `"ideation/staging"` without the trailing `/` both claims `ideation/stagingfoo/x.md` for the staging area and composes `ideation/staging` where a folder was meant — two different wrong answers from one under-specified declaration. Refused at the DECLARATION, in `normalize_display`, rather than normalised at each of the several call sites: a profile that meant one of those two things should say which, and a shell that guessed would be inventing a corpus layout, which is the one thing this facet exists to stop it doing. The message names the value and the spelling that would be accepted. Lane: openxfactory-4-opendox-extraction Refs opensoft/openxFactory#656 Co-Authored-By: Claude Opus 5 --- src/opendox/display_profile.py | 32 +++++++++++++++++++++++++++----- tests/test_display_facet.py | 15 +++++++++++++++ 2 files changed, 42 insertions(+), 5 deletions(-) diff --git a/src/opendox/display_profile.py b/src/opendox/display_profile.py index 7a30a80d..86d9189c 100644 --- a/src/opendox/display_profile.py +++ b/src/opendox/display_profile.py @@ -397,6 +397,29 @@ def _text(value: Any, *, where: str, allow_none: bool = False) -> str | None: 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( @@ -474,8 +497,8 @@ def normalize_display(declared: Any) -> dict[str, Any]: out["areas"][role]["label"] = _text( fields["label"], where=f"areas.{role}.label") if "prefix" in fields: - prefix = _text(fields["prefix"], where=f"areas.{role}.prefix", - allow_none=True) + 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 " @@ -507,9 +530,8 @@ def normalize_display(declared: Any) -> dict[str, Any]: out["artifacts"][role]["label"] = _text( fields["label"], where=f"artifacts.{role}.label") if "prefix" in fields: - out["artifacts"][role]["prefix"] = _text( - fields["prefix"], where=f"artifacts.{role}.prefix", - allow_none=True) + 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)): diff --git a/tests/test_display_facet.py b/tests/test_display_facet.py index 224fb459..2b59accb 100644 --- a/tests/test_display_facet.py +++ b/tests/test_display_facet.py @@ -267,6 +267,21 @@ def test_a_blank_word_is_refused_rather_than_rendered_as_a_blank_surface(): normalize_display({"stages": {"source": {"one": " "}}}) +def test_a_corpus_prefix_without_a_separator_is_refused(): + """Copilot review. A prefix is matched with `startsWith` and composed into + a path: `"ideation/staging"` would claim `ideation/stagingfoo/x.md` for the + staging area AND compose `ideation/staging` where a folder was meant. + Refused at the declaration rather than normalised silently, because a + profile that meant one of those two should say which.""" + with pytest.raises(DisplayFacetError, match="does not end in"): + normalize_display({"areas": {"captured": {"prefix": "ideation/brainstorm"}}}) + with pytest.raises(DisplayFacetError, match="does not end in"): + normalize_display({"artifacts": {"root": {"prefix": "openspec/changes"}}}) + # …and the well-formed one is taken whole + ok = normalize_display({"areas": {"captured": {"prefix": "ideation/brainstorm/"}}}) + assert ok["areas"]["captured"]["prefix"] == "ideation/brainstorm/" + + def test_a_role_table_that_is_not_a_mapping_is_refused(): with pytest.raises(DisplayFacetError): normalize_display({"stages": ["source"]}) From f5003ef4dce3b62996b7bca8beb44221f342e024 Mon Sep 17 00:00:00 2001 From: Brett Heap <1513478+brettheap@users.noreply.github.com> Date: Sat, 12 Sep 2026 20:12:06 -0400 Subject: [PATCH 37/44] =?UTF-8?q?=C2=A7=203.4=20S5,=20leg=20B:=20three=20a?= =?UTF-8?q?ccurate=20round-3=20findings,=20two=20of=20them=20created=20by?= =?UTF-8?q?=20round=202?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit **`host_profile` was blank in every payload this serve publishes.** `getattr(profile_openxfactory, "__name__", None)` could only ever answer the default: `profile_proxy._LateProfile.__getattr__` refuses every dunder BY DESIGN, so that `copy`, `pickle`, `inspect` and pytest's assertion rewriting cannot fire the composition point simply by probing an object. The manifest's named absence — "a host IS registered and simply does not contribute panels, which is a different fact from no host at all" — needs the name to say the first half, and it never had it. `view_extension.host_profile_name()` resolves the profile and names it through `domain_profile.name_of()`, the same namer `profile_proxy`'s own refusal quotes, so both accessors of ONE registration name a profile the same way. It never raises: `ProfileNotRegistered` belongs to the read three statements earlier that is entitled to raise it, not to a diagnostic. **A pass belongs to the render that started it.** Round 2 made the generic mount pass run per region, which means it can now start from a tab's FIRST render — a click, minutes after load — and it awaits a dynamic import. A repository switch or a refresh beginning a new render while a module loads would have let the old pass resume and mount its own stale snapshot into a region the new render owns. `mountContributedViews` takes the render `signal` and reads it before it considers a binding and again after the import, which are the two moments an abort can land; `app.js` hands it the scope every other listener in this shell is already bound to. **A late refusal had nowhere to be written.** `render()` ends with `status.remove()`, and every later render then reads `null` for `#loadstatus` — so a `ViewBindingError` raised by the per-region pass after that point went into a detached node or was dropped, which is the RULED Q11 surface failing exactly where round 2 made it newly reachable. `index.html` is a `moved_verbatim` carve row and cannot grow a second element, so the shell remembers where the element it removed sat and puts it back. TWO FINDINGS OF THE ROUND ARE REFUTED, with evidence in their threads: `mountProjectGate` does NOT shadow the snapshot (its arrow takes `(host, pctx)` and passes `host, snapshot, pctx` — the outer render snapshot, in RULED Q3's order), and `web/**` is NOT a non-recursive glob at this leg's declared `setuptools>=68` floor — a real `python -m build` packages 40 entries under `opendox/web/`, 36 of them under `opendox/web/views/`. The smoke check the review asked for is here as `test_the_bundle_glob_and_the_setuptools_floor_are_one_ guarantee`, which holds the pattern and the floor to each other, since recursive `**` in `package_data` arrived in setuptools 62.3.0 and neither declaration is safe alone. Three new regression cases; census `loc` and totals moved. Narrowed validate: 250 passed, 1 xfailed. Lane: openxfactory-4-opendox-extraction Refs opensoft/openxFactory#656 Co-Authored-By: Claude Opus 5 --- src/opendox/serve.py | 15 ++- src/opendox/view_extension.py | 38 +++++++ src/opendox/web/app.js | 41 ++++++- src/opendox/web/views/view_extension.js | 17 +++ tests/fixtures/web_boundary_census.yaml | 10 +- tests/test_gate_loop_contributed.py | 138 +++++++++++++++++++++++- 6 files changed, 248 insertions(+), 11 deletions(-) diff --git a/src/opendox/serve.py b/src/opendox/serve.py index fcff17d7..7803719b 100644 --- a/src/opendox/serve.py +++ b/src/opendox/serve.py @@ -1751,7 +1751,20 @@ def build_server( view_extensions, contributed_routes=route_bindings), contributed_routes=route_bindings, host_facet=host_facet, - host_profile=getattr(profile_openxfactory, "__name__", None), + # THE PROFILE'S NAME COMES THROUGH THE ESTATE'S OWN NAMER, never off a + # dunder (Copilot review, round 3). `getattr(profile_openxfactory, + # "__name__", None)` could only ever answer `None`: + # `_LateProfile.__getattr__` refuses every dunder BY DESIGN, so that + # `copy`, `pickle`, `inspect` and pytest's assertion rewriting cannot + # fire the composition point by probing. The manifest's named-absence + # contract — "a host IS registered and simply does not contribute + # panels, which is a different fact from no host at all" — needs the + # name, and it was blank in every payload this serve published. + # `view_extension.host_profile_name()` resolves the profile the way + # `profile_proxy`'s own refusal does, through + # `domain_profile.name_of()`, so both accessors of ONE registration name + # a profile the same way. + host_profile=view_extension.host_profile_name(profile_openxfactory), ) bound = type("BoundDashboardHandler", (DashboardHandler,), { diff --git a/src/opendox/view_extension.py b/src/opendox/view_extension.py index bf7d75cd..3fc3ad53 100644 --- a/src/opendox/view_extension.py +++ b/src/opendox/view_extension.py @@ -110,6 +110,7 @@ "dom_regions", "host_view_extensions", "host_view_facet", + "host_profile_name", "view_manifest", ] @@ -687,6 +688,43 @@ def host_view_facet(profile: Any = None) -> tuple[str, tuple[Any, ...]]: return "declared", tuple(declared) +def host_profile_name(profile: Any = None) -> str | None: + """The registered host profile's most nameable name, or `None`. + + THE NAME NEVER COMES OFF A DUNDER (Copilot review of openDox-code#20, + round 3). `build_server()` read `getattr(profile_openxfactory, "__name__", + None)`, which could only ever answer the default: `_LateProfile.__getattr__` + refuses every dunder BY DESIGN, so that `copy`, `pickle`, `inspect` and + pytest's assertion rewriting cannot fire the composition point simply by + probing an object. The manifest's `host_profile` was therefore blank in + every payload — and it is half of the named absence `host_view_facet` exists + to carry, since "a host IS registered and does not contribute panels" is a + different fact from "no host at all" only if the host can be named. + + Resolved the way `profile_proxy`'s own refusal resolves it — through + `domain_profile.name_of()` — because the two accessors of ONE registration + must name a profile the same way. + + NEVER RAISES, and that is the whole posture of this half of the seam: a + diagnostic that refuses to be computed is worse than a diagnostic that is + absent, and `ProfileNotRegistered` reaches `build_server()` three statements + earlier at the read that is entitled to raise it. + """ + if profile is None: + from opendox.profile_proxy import profile_openxfactory + profile = profile_openxfactory + from opendox import domain_profile + resolve = getattr(profile, "resolve", None) + try: + resolved = resolve() if callable(resolve) else profile + except Exception: # noqa: BLE001 — a diagnostic must not out-raise + return None + try: + return domain_profile.name_of(resolved) + except Exception: # noqa: BLE001 + return None + + def view_manifest(bindings: Iterable[ViewBinding], *, contributed_routes: Iterable[Any] = (), host_facet: str = "absent", diff --git a/src/opendox/web/app.js b/src/opendox/web/app.js index 4d1dea8c..2f50016d 100644 --- a/src/opendox/web/app.js +++ b/src/opendox/web/app.js @@ -898,9 +898,34 @@ function refusalTransport() { }); } +//: WHERE `#loadstatus` SAT, remembered once, so a late assembly refusal has a +//: host after a successful render removed it (Copilot review, round 3). +//: `render()` ends with `status.remove()`, and every later render then reads +//: `null` from `getElementById` — so a `ViewBindingError` raised by the generic +//: mount pass on a TAB'S FIRST RENDER, minutes after load, had nowhere to be +//: written and was invisible. `index.html` is a `moved_verbatim` carve row and +//: cannot grow a second element, so the shell re-inserts the one it removed, in +//: the place it removed it from. +let statusSlot = null; + +function ensureStatusHost(doc) { + const d = doc || (typeof document === "undefined" ? null : document); + if (!d) return null; + const live = d.getElementById("loadstatus"); + if (live && live.isConnected !== false) return live; + const node = live || statusSlot?.node; + if (!node || !statusSlot?.parent) return node || null; + statusSlot.parent.insertBefore(node, statusSlot.next || null); + return node; +} + async function render() { const signal = nextRenderScope(); const status = document.getElementById("loadstatus"); + if (status && status.parentNode) { + statusSlot = { node: status, parent: status.parentNode, + next: status.nextSibling }; + } try { // The snapshot INDEX (add-dashboard-repo-selector): the roster the selector // renders and the freshness the header shows. Absent (a static image, an @@ -1135,7 +1160,11 @@ async function render() { const mountContributedInto = async (regions) => { const mounted = await mountContributedViews( views, snapshot, { caps, nav: null, views }, - { capabilities: probedCaps, regions }); + // `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 + // mount this render's snapshot into the next one's region. + { capabilities: probedCaps, regions, signal }); contributedMounts.push(...mounted); return mounted; }; @@ -1534,10 +1563,16 @@ async function render() { // render; the alternative is an unhandled rejection in the console and a tab // that silently lacks its panel. function reportAssemblyFailure(err) { - if (!status) return; + // RE-INSERT THE HOST IF A SUCCESSFUL RENDER ALREADY REMOVED IT (Copilot + // round 3). The initial render ends with `status.remove()`, so a refusal + // arriving from the per-region pass on a tab's first render — or on any + // later render, which reads `null` for the element outright — would have + // been written into a detached node or dropped entirely. + const host = ensureStatusHost(); + if (!host) return; const registryRefusal = err instanceof ViewBindingError || (err && err.name === "ViewBindingError"); - status.textContent = registryRefusal + host.textContent = registryRefusal ? "This shell was assembled with a contributed view column it cannot use " + "(" + err.message + "). The snapshot is fine — the assembly is not: " + "fix the contributed binding, or serve this bundle without that column." diff --git a/src/opendox/web/views/view_extension.js b/src/opendox/web/views/view_extension.js index f9c7ba9a..5690d3d8 100644 --- a/src/opendox/web/views/view_extension.js +++ b/src/opendox/web/views/view_extension.js @@ -766,8 +766,20 @@ export async function mountContributedViews(bindings, snapshot, ctx, options) { const doc = o.document || (typeof document === "undefined" ? null : document); const capabilities = o.capabilities; const only = o.regions ? new Set(o.regions) : null; + // A PASS BELONGS TO THE RENDER THAT STARTED IT (Copilot review of + // openDox-code#20, round 3). This function awaits a dynamic import, and a + // per-region pass can be started from a tab's first render — a click, minutes + // after load — so a repository switch or a refresh can begin a NEW render + // while a binding's module is still loading. The old pass would then resume + // and mount a stale snapshot into a region the new render owns. `signal` is + // the render scope every other listener in this shell is already bound to; + // the pass reads it before it considers a binding and again after the import, + // which are the two moments an abort can land. + const signal = o.signal || null; + const aborted = () => !!(signal && signal.aborted); const results = []; for (const binding of bindings || []) { + if (aborted()) break; if (only && !only.has(binding.region)) continue; // The CORE arm is the shell's own and mounts through the tab router; a core // binding is the one that carries a `mount` function, which a contributed @@ -804,6 +816,11 @@ export async function mountContributedViews(bindings, snapshot, ctx, options) { results.push({ binding, mounted: null, skipped: "absent" }); continue; } + // The import is the await, so this is the other moment an abort can land. + if (aborted()) { + results.push({ binding, mounted: null, skipped: "aborted" }); + break; + } results.push({ binding, mounted: resolved.exports[binding.entry](host, snapshot, ctx), diff --git a/tests/fixtures/web_boundary_census.yaml b/tests/fixtures/web_boundary_census.yaml index 3d159c39..af91524e 100644 --- a/tests/fixtures/web_boundary_census.yaml +++ b/tests/fixtures/web_boundary_census.yaml @@ -191,15 +191,15 @@ measured_at: "opensoft/openDox-code main a99eba03e31a0aee1cc15a061fdf718cc88a2c4 # shape and `test_the_declared_totals_are_re_derived_from_the_rows` can refuse a # drift between the two. Measured at slice S4 (see the S4 block above). totals: - A: {files: 25, loc: 16866} + A: {files: 25, loc: 16918} B: {files: 1, loc: 73} C: {files: 14, loc: 12008} "?": {files: 1, loc: 1435} files: - path: app.js class: A - loc: 1549 - note: "the shell; its only class-B import was gate.js at :43 (discharged by S3's view registry -- loc 1155 -> 1282 with the registry wiring, S3; 1282 -> 1337 with S4's two new gate bindings and the two mounts it hands down). Carries SIX transitional route-ownership sites, all in the CORE arm's class-B binding entries and all cleared at S5 when those entries leave for contributedViewBindings(): gate.bar's one route (S3) and gate.lens's and gate.projects's two each (S4). Declaring them is RULED Q3 working -- view_extension.py: 'a binding that declares the routes it calls is what makes that ruling checkable instead of aspirational' -- and it is a real breach by assertion 2's own rule only while the entry sits in app.js (class A) rather than in the class-B module (exempt by construction) loc 1492 -> 1549 on this PR's round-2 review (Copilot): RULED Q1's generic pass is no longer ONE pass before every core mount — every `dom` region is a root its core renderer CLEARS, so the pass is run per region by the caller that just rendered it (after mountExplorer, after mountStagingWorkbench, and through the tab router's onRegionRendered hook on a tab's first render), and the Q11 refusal frame became a named function so a late refusal reaches the same surface." + loc: 1584 + note: "the shell; its only class-B import was gate.js at :43 (discharged by S3's view registry -- loc 1155 -> 1282 with the registry wiring, S3; 1282 -> 1337 with S4's two new gate bindings and the two mounts it hands down). Carries SIX transitional route-ownership sites, all in the CORE arm's class-B binding entries and all cleared at S5 when those entries leave for contributedViewBindings(): gate.bar's one route (S3) and gate.lens's and gate.projects's two each (S4). Declaring them is RULED Q3 working -- view_extension.py: 'a binding that declares the routes it calls is what makes that ruling checkable instead of aspirational' -- and it is a real breach by assertion 2's own rule only while the entry sits in app.js (class A) rather than in the class-B module (exempt by construction) loc 1492 -> 1549 on this PR's round-2 review (Copilot): RULED Q1's generic pass is no longer ONE pass before every core mount — every `dom` region is a root its core renderer CLEARS, so the pass is run per region by the caller that just rendered it (after mountExplorer, after mountStagingWorkbench, and through the tab router's onRegionRendered hook on a tab's first render), and the Q11 refusal frame became a named function so a late refusal reaches the same surface. loc 1549 -> 1584 on round 3 (Copilot): the per-region pass is bound to THIS render's signal (a pass started from a tab's first render must not mount a stale snapshot into the next render's region), and the Q11 refusal frame re-inserts `#loadstatus` where a successful render removed it, so a late assembly refusal is visible instead of dropped." - path: index.html class: C @@ -389,8 +389,8 @@ files: - path: views/view_extension.js class: A - loc: 824 - note: "S3 ADDITION: the client-side view registry -- ViewBinding/collectViewBindings, route_extension.py's shape mirrored in JS (openDox-spec § 4.1). No import, no governance literal; 'gate.bar' in a doc comment is a documentation example of an id, not a route literal, so assertion 2 does not match it. loc 422 -> 455 on this PR's own review round (Copilot, PR #14): a malformed contributed_routes now refuses instead of silently disabling the ownership check, and a rejected dynamic import now refuses naming the binding and module instead of leaking a raw error. loc 455 -> 463 on S4: two new REGIONS entries (lens-gate, repo-projects) for the two new class-B bindings' shell mounts, and the doc comment naming them. loc 463 -> 499 on this fix (Copilot, PR #16, view_extension.js:358): manifestRoutes() and ownershipBreach() now share one shape check, refusing a contributed-routes entry missing a string pattern or carrying a non-boolean is_prefix at whichever of the two sees it first, instead of the array-only check at manifestRoutes() and a truthy is_prefix read at ownershipBreach() silently letting a malformed entry through as if it were not a prefix match. loc 499 -> 757 on S5: RULED Q2's declared namespace and its Proxy, RULED Q4's capability probe and refusal, and RULED Q1's generic mount pass. loc 757 -> 824 on S5's round-2 review (Copilot): probeCapabilityPath reads OWN properties only (an inherited `toString` met a requirement); every DECLARED export is checked callable the way `entry` is (RULED Q2); resolveBinding() resolves the binding a caller already holds, so the generic pass cannot mount a same-id binding from another region; and the pass takes a `regions` bound." + loc: 841 + note: "S3 ADDITION: the client-side view registry -- ViewBinding/collectViewBindings, route_extension.py's shape mirrored in JS (openDox-spec § 4.1). No import, no governance literal; 'gate.bar' in a doc comment is a documentation example of an id, not a route literal, so assertion 2 does not match it. loc 422 -> 455 on this PR's own review round (Copilot, PR #14): a malformed contributed_routes now refuses instead of silently disabling the ownership check, and a rejected dynamic import now refuses naming the binding and module instead of leaking a raw error. loc 455 -> 463 on S4: two new REGIONS entries (lens-gate, repo-projects) for the two new class-B bindings' shell mounts, and the doc comment naming them. loc 463 -> 499 on this fix (Copilot, PR #16, view_extension.js:358): manifestRoutes() and ownershipBreach() now share one shape check, refusing a contributed-routes entry missing a string pattern or carrying a non-boolean is_prefix at whichever of the two sees it first, instead of the array-only check at manifestRoutes() and a truthy is_prefix read at ownershipBreach() silently letting a malformed entry through as if it were not a prefix match. loc 499 -> 757 on S5: RULED Q2's declared namespace and its Proxy, RULED Q4's capability probe and refusal, and RULED Q1's generic mount pass. loc 757 -> 824 on S5's round-2 review (Copilot): probeCapabilityPath reads OWN properties only (an inherited `toString` met a requirement); every DECLARED export is checked callable the way `entry` is (RULED Q2); resolveBinding() resolves the binding a caller already holds, so the generic pass cannot mount a same-id binding from another region; and the pass takes a `regions` bound. loc 824 -> 841 on round 3 (Copilot): mountContributedViews reads an abort `signal` before it considers a binding and again after the import, which are the two moments an abort can land." - path: views/viewer.js class: A diff --git a/tests/test_gate_loop_contributed.py b/tests/test_gate_loop_contributed.py index 1f8a5221..11a5e495 100644 --- a/tests/test_gate_loop_contributed.py +++ b/tests/test_gate_loop_contributed.py @@ -48,7 +48,7 @@ from opendox.view_extension import ( REGIONS, ViewBinding, ViewBindingError, collect_view_bindings, dom_regions, - host_view_extensions, host_view_facet, view_manifest, + host_profile_name, host_view_extensions, host_view_facet, view_manifest, ) ROOT = Path(__file__).resolve().parents[1] @@ -581,7 +581,8 @@ def test_the_generic_pass_runs_after_each_core_render_not_once_before_them( encoding="utf-8") # ONE runner, bounded by region every time it is called assert "const mountContributedInto = async (regions) => {" in app - assert "{ capabilities: probedCaps, regions }" in app + # and the pass is bound to THIS render's scope (Copilot round 3) + assert "{ capabilities: probedCaps, regions, signal }" in app calls = re.findall(r"mountContributedInto\(\[([^\]]*)\]\)", app) assert calls == ['"explorer-root"', '"staging-workbench-root"', "region"], calls # and each of the two eager ones comes AFTER its core mount @@ -599,6 +600,73 @@ def test_the_generic_pass_runs_after_each_core_render_not_once_before_them( assert "onRegionRendered: (region) => {" in app +@pytest.mark.skipif(NODE is None, reason="node is not installed") +def test_js_an_aborted_render_s_pass_mounts_nothing(tmp_path) -> None: + """A PASS BELONGS TO THE RENDER THAT STARTED IT (Copilot review of this PR, + round 3). The per-region pass awaits a dynamic import and can be started + from a tab's FIRST render — a click, minutes after load — so a repository + switch or a refresh can begin a new render while a module is still loading. + The old pass would then mount its own stale snapshot into a region the new + render owns. `signal` is the render scope every other listener in this shell + is already bound to.""" + web = _temp_bundle(tmp_path, { + "panel.js": "export function mount(host) { host.hit = true; return 'ok'; }\n", + }) + result = _run_node(f""" +import {{ collectViewBindings, mountContributedViews }} + from {json.dumps((web / "views" / "view_extension.js").as_uri())}; +const hosts = {{ "view-docs": {{ id: "view-docs", hit: false, appendChild() {{}} }} }}; +const doc = {{ getElementById: (id) => hosts[id] || null, + createElement: () => ({{ setAttribute() {{}}, appendChild() {{}} }}) }}; +const bindings = collectViewBindings([{{ views: () => [{{ + id: "panel.one", region: "view-docs", module: "./views/panel.js", + entry: "mount", view_class: "B", optional: true }}] }}]); +// aborted BEFORE the pass: nothing is even considered +const before = await mountContributedViews(bindings, null, {{}}, + {{ document: doc, signal: {{ aborted: true }} }}); +const afterAbortEarly = hosts["view-docs"].hit; +// aborted DURING the pass — between the binding being considered and the +// module finishing its import, which is the real race +const live = {{ aborted: false }}; +const during = await mountContributedViews(bindings, null, {{}}, + {{ document: doc, signal: {{ get aborted() {{ const was = live.aborted; + live.aborted = true; + return was; }} }} }}); +console.log(JSON.stringify({{ + before: before.map((r) => [r.binding.id, r.skipped]), + afterAbortEarly, + during: during.map((r) => [r.binding.id, r.skipped]), + mounted: hosts["view-docs"].hit, +}})); +""", tmp_path) + # aborted before: the loop breaks with no record at all, and nothing mounted + assert result["before"] == [] + assert result["afterAbortEarly"] is False + # aborted during: the binding is RECORDED as skipped, and still not mounted + assert result["during"] == [["panel.one", "aborted"]] + assert result["mounted"] is False + + +def test_a_late_assembly_refusal_still_has_somewhere_to_be_written() -> None: + """`render()` ends with `status.remove()`, and every later render then reads + `null` for `#loadstatus` — so a `ViewBindingError` raised by the per-region + pass on a tab's FIRST render, minutes after load, had nowhere to go and was + invisible (Copilot review of this PR, round 3). `index.html` is a + `moved_verbatim` carve row and cannot grow a second element, so the shell + remembers where the one it removed sat and puts it back.""" + app = _app() + assert "let statusSlot = null;" in app + assert "function ensureStatusHost(doc) {" in app + assert "statusSlot.parent.insertBefore(node, statusSlot.next || null);" in app + # the frame USES it, and does not write into the detached node + frame = re.search(r"function reportAssemblyFailure\(err\) \{(.*?)\n \}", + app, re.S).group(1) + assert "const host = ensureStatusHost();" in frame + assert "if (!host) return;" in frame + assert "host.textContent = registryRefusal" in frame + assert "status.textContent" not in frame + + # --------------------------------------------------------------------------- # RULED Q8 / Q9 — the regions # --------------------------------------------------------------------------- @@ -735,6 +803,12 @@ def test_the_serve_publishes_the_manifest_on_capabilities() -> None: # never grew the facet. assert "view_extension.host_view_facet(" in serve assert "host_facet=host_facet" in serve + # THE NAME NEVER COMES OFF A DUNDER (Copilot review, round 3): the lazy + # proxy refuses every dunder by design, so `getattr(profile, "__name__", + # None)` could only ever answer `None` and the manifest's `host_profile` + # was blank in every payload. + assert "view_extension.host_profile_name(profile_openxfactory)" in serve + assert 'getattr(profile_openxfactory, "__name__"' not in serve assert '"declared" if view_extensions else "absent"' not in serve assert "view_extension.collect_view_bindings(" in serve # the SAME contributed routes the server was assembled with, so both halves @@ -765,6 +839,41 @@ class _Profile: assert host_view_extensions(profile) == extensions +def test_the_host_profile_is_named_through_the_estates_own_namer() -> None: + """`host_profile` is the other half of the named absence, and it was blank. + `profile_proxy._LateProfile.__getattr__` raises `AttributeError` for every + dunder BY DESIGN — so that `copy`, `pickle`, `inspect` and pytest's + assertion rewriting cannot fire the composition point by probing — which + means `getattr(proxy, "__name__", None)` could only ever answer the default. + The name now comes through `domain_profile.name_of()`, the same namer + `profile_proxy`'s own refusal quotes.""" + from opendox import profile_proxy + + # the defect, still true of the proxy and correctly so + assert getattr(profile_proxy.profile_openxfactory, "__name__", None) is None + + class _Module: + __name__ = "openxfactory_profile" + + class _Proxy: + def __init__(self, answer): + self._answer = answer + + def resolve(self): + if isinstance(self._answer, Exception): + raise self._answer + return self._answer + + assert host_profile_name(_Proxy(_Module())) == "openxfactory_profile" + # a profile built from a § 4.4 mapping says `mapping_id` + mapping = type("_Mapping", (), {"mapping_id": "openxfactory"})() + assert host_profile_name(_Proxy(mapping)) == "openxfactory" + # an unregistered host: the diagnostic is absent, never a raise + assert host_profile_name(_Proxy(RuntimeError("not registered"))) is None + # a bare object with no proxy protocol is named directly + assert host_profile_name(_Module()) == "openxfactory_profile" + + def test_a_profile_declaring_the_facet_as_none_reads_as_absent() -> None: """`None` is a host spelling "I contribute no views", and `tuple(None)` would raise where this seam's whole posture is that an absence is not a @@ -774,6 +883,31 @@ class _Profile: assert host_view_facet(_Profile()) == ("absent", ()) +def test_the_bundle_glob_and_the_setuptools_floor_are_one_guarantee() -> None: + """`package-data` says `web/**`, and `**` is only RECURSIVE in setuptools + 62.3.0 and later — before that it globbed like a single `*` and the wheel + would ship `app.js` without a single one of the view modules it statically + imports (Copilot review of this PR, round 3, raised as a defect; measured + and answered here instead). + + The two declarations are ONE guarantee and neither is safe alone, so this + test holds them to each other: the pattern must be the recursive one and the + build requirement must be at or above the version that made it recursive. + Measured on a real build at `setuptools 84.0.0`: 40 entries under + `opendox/web/`, 36 of them under `opendox/web/views/` — the whole census + except `vendor/.gitkeep`, which `glob` skips as a dotfile and which exists + only to keep an otherwise-empty directory in git.""" + text = (ROOT / "pyproject.toml").read_text(encoding="utf-8") + assert 'opendox = ["web/**"]' in text, ( + "the bundle ships by a RECURSIVE glob; a single `*` would package " + "app.js without `web/views/`") + floor = re.search(r'requires\s*=\s*\["setuptools>=(\d+)', text) + assert floor, "the build system must declare a setuptools floor at all" + assert int(floor.group(1)) >= 63, ( + "recursive `**` in `package_data` arrived in setuptools 62.3.0; a floor " + "below it would let a build ship a bundle with no view modules") + + def test_the_census_totals_and_the_class_b_remainder() -> None: """After S5 exactly ONE class-B file is left in this bundle, and it is not the gate loop's: `views/projection-index.js` is openXdox's PROJECTION From 90cf05a00538a58e44d5af2b6ca273fa9cf7b6f4 Mon Sep 17 00:00:00 2001 From: Brett Heap <1513478+brettheap@users.noreply.github.com> Date: Sat, 12 Sep 2026 21:00:16 -0400 Subject: [PATCH 38/44] =?UTF-8?q?=C2=A7=203.4=20S7:=20two=20roles=20may=20?= =?UTF-8?q?not=20share=20one=20snapshot=20enum=20value?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Copilot's round-4 finding on the reverse lookup rounds 3-4 introduced, and it is the right reading of it. `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 back to the word and the `cstate-` hook it renders. A host that mapped two roles to one value would therefore have had one role's cards silently rendered as the other's: the wrong word, the wrong style hook, and nothing anywhere saying so. `_refuse_duplicate_enum_values` refuses it where the facet is built, naming both roles and the value, and pointing at the two ways out (declare distinct values, or leave the role you did not mean to override undeclared). CHECKED AFTER THE MERGE, not on the declaration alone, and that is the load- bearing part: the collision that matters is between a value the host declares and one openDox still SHIPS for another role, which is precisely what a partial override causes — and a partial override is legal and is the shape § 4.3 point 5 is built around. A declaration-only check would have passed `{"register_state": {"proposed": "latent"}}` and shipped the defect. Narrowed validate: 283 passed, 0 xfailed. Lane: openxfactory-4-opendox-extraction Refs opensoft/openxFactory#656 Co-Authored-By: Claude Opus 5 --- src/opendox/display_profile.py | 32 ++++++++++++++++++++++++++++++++ tests/test_display_facet.py | 25 +++++++++++++++++++++++++ 2 files changed, 57 insertions(+) diff --git a/src/opendox/display_profile.py b/src/opendox/display_profile.py index 86d9189c..320631bd 100644 --- a/src/opendox/display_profile.py +++ b/src/opendox/display_profile.py @@ -605,9 +605,41 @@ def _snapshot_values(declared: Any) -> dict[str, dict[str, str]]: 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 display_manifest(declared: Any, *, host_profile: str | None = None ) -> dict[str, Any]: """The `display` block of `/capabilities` — the ONE crossing of the boundary. diff --git a/tests/test_display_facet.py b/tests/test_display_facet.py index 2b59accb..3f1a4c6e 100644 --- a/tests/test_display_facet.py +++ b/tests/test_display_facet.py @@ -282,6 +282,31 @@ def test_a_corpus_prefix_without_a_separator_is_refused(): assert ok["areas"]["captured"]["prefix"] == "ideation/brainstorm/" +def test_two_roles_may_not_share_one_snapshot_enum_value(): + """Copilot round 4. The client reverse lookup (`registerRole(value)`) + answers the FIRST role whose declared value matches, so a host mapping two + roles to one value would have one role's cards silently rendered as the + other's — the wrong word AND the wrong `cstate-` hook, with nothing + saying so. Refused after the MERGE, not on the declaration alone: the + collision that matters is between a declared value and one openDox still + ships for another role, which is exactly what a partial override causes.""" + # `display_manifest`, not `normalize_display`: the enum tables are the + # SCHEMA half of the payload and are built by `_snapshot_values`, which is + # the manifest's own step. That is also where the merge happens, and the + # merge is what this check has to see. + with pytest.raises(DisplayFacetError, match="BOTH"): + display_manifest({"values": {"register_state": { + "captured": "same", "proposed": "same"}}}) + # the partial-override case: one declared value colliding with a shipped one + with pytest.raises(DisplayFacetError, match="BOTH"): + display_manifest({"values": {"register_state": {"proposed": "latent"}}}) + # …and distinct values are taken whole + ok = display_manifest({"values": {"register_state": { + "captured": "new", "proposed": "chosen"}}}) + assert ok["values"]["register_state"]["captured"] == "new" + assert ok["values"]["register_state"]["proposed"] == "chosen" + + def test_a_role_table_that_is_not_a_mapping_is_refused(): with pytest.raises(DisplayFacetError): normalize_display({"stages": ["source"]}) From 3cfe2a12e35c18b97ae4cba7c8300a558a23c270 Mon Sep 17 00:00:00 2001 From: Brett Heap <1513478+brettheap@users.noreply.github.com> Date: Sat, 12 Sep 2026 21:42:04 -0400 Subject: [PATCH 39/44] =?UTF-8?q?=C2=A7=203.4=20S7:=20the=20served=20paylo?= =?UTF-8?q?ad=20names=20which=20tokens=20the=20host=20declared?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Copilot round 6, two threads, both accurate and both the same shape — a guard written against a fact the wire no longer carried. 1. `display_profile.display_manifest` published `tokens` AFTER `normalize_display` had merged openDox's own four in, so the table on the wire always had all four keys however few the host declared. The browser's `Display` read key PRESENCE as host declaration — the one guard that keeps `applyTokens` from writing inline custom properties on `:root` and outranking `styles.css`'s per-theme rules — and so, on the payload the server actually serves, wrote all four on every install in the estate, none of which declares a DISPLAY facet, silently ending dark mode there. The provenance now travels WITH the words: `declared_tokens` lists the roles the host itself wrote, the way `host_facet` names its absence, and `Display` honours it whenever the payload carries it. A facet object handed straight to `Display` — a fixture, a node probe — carries no provenance list, and there key presence still IS the declaration. `tests/test_display_facet.py` gains the two tests that could see this: the manifest-level one, and a node probe driven by the REAL payload that `display_manifest` builds rather than a hand-written one. Proven to have teeth — reverted, the probe reports four written properties on a host-less install. 2. `tests/test_bullseye_widget.py` still split `staging-workbench-model.js` at `export const SESSION_SCOPE_KINDS = {`, which this slice moved to `views/display.js` (a seam-key table beside `SCOPE_KINDS`, which the model now imports and re-exports). The split would have raised `IndexError`. It reads the canonical declaration where it is declared now — restoring a duplicate in the class-C model is precisely what the move was for — and still pins the lens's spelling as a KEY and the one application site in the model. The carved suite does not run in this repo yet (RULED Q-L5 (b′)), so the narrowed validate could not have caught it. Census `loc:`/`totals:` re-derived. Narrowed validate 285 passed, 0 xfailed; assertion 4 holds at 0 with its six declared prose exemptions. Lane: openxfactory-4-opendox-extraction Refs opensoft/openxFactory#656 Co-Authored-By: Claude Opus 5 --- src/opendox/display_profile.py | 34 ++++++++++++- src/opendox/web/views/display.js | 18 +++++-- tests/fixtures/web_boundary_census.yaml | 4 +- tests/test_bullseye_widget.py | 18 +++++-- tests/test_display_facet.py | 66 ++++++++++++++++++++++++- 5 files changed, 130 insertions(+), 10 deletions(-) diff --git a/src/opendox/display_profile.py b/src/opendox/display_profile.py index 320631bd..dd7ab314 100644 --- a/src/opendox/display_profile.py +++ b/src/opendox/display_profile.py @@ -640,6 +640,33 @@ class it renders. A host that mapped two roles to one value would therefore 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. @@ -658,7 +685,11 @@ def display_manifest(declared: Any, *, host_profile: str | None = None 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, @@ -673,5 +704,6 @@ def display_manifest(declared: Any, *, host_profile: str | None = None "sections": _section_order(declared), "artifact_roles": list(ARTIFACT_ROLES), "token_roles": list(TOKEN_ROLES), - **normalize_display(declared), + "declared_tokens": _declared_token_roles(declared), + **merged, } diff --git a/src/opendox/web/views/display.js b/src/opendox/web/views/display.js index fe197841..5ab24f49 100644 --- a/src/opendox/web/views/display.js +++ b/src/opendox/web/views/display.js @@ -426,9 +426,21 @@ export class Display { // neutral values unconditionally would therefore pin one theme's colours // onto every install that declares no tokens — which is every install in // the estate today — and silently end dark mode for all of them. - this._declaredTokens = declaredTokens - ? TOKEN_ROLES.filter((role) => typeof declaredTokens[role] === "string") - : []; + // + // READ THE PROVENANCE, NOT THE SHAPE (Copilot round 6). On the payload the + // SERVER builds, `tokens` has been merged with openDox's own before it + // leaves `display_manifest`, so all four keys are present however few the + // host declared — key presence there says nothing, and the guard above was + // a guard over a fact the wire had already destroyed. The server therefore + // publishes `declared_tokens`, the role names the host itself wrote, and + // that is what is honoured whenever it is on the payload. A facet object + // handed straight to `Display` — a fixture, a node probe, a test — carries + // no provenance list, and there key presence IS the declaration. + this._declaredTokens = Array.isArray(facet.declared_tokens) + ? TOKEN_ROLES.filter((role) => facet.declared_tokens.indexOf(role) !== -1) + : (declaredTokens + ? TOKEN_ROLES.filter((role) => typeof declaredTokens[role] === "string") + : []); this._acts = Object.assign({}, NEUTRAL_DISPLAY.acts, facet.acts && typeof facet.acts === "object" ? facet.acts : null); this._artifacts = {}; diff --git a/tests/fixtures/web_boundary_census.yaml b/tests/fixtures/web_boundary_census.yaml index 2a149019..a7cc5b45 100644 --- a/tests/fixtures/web_boundary_census.yaml +++ b/tests/fixtures/web_boundary_census.yaml @@ -191,7 +191,7 @@ measured_at: "opensoft/openDox-code main a99eba03e31a0aee1cc15a061fdf718cc88a2c4 # shape and `test_the_declared_totals_are_re_derived_from_the_rows` can refuse a # drift between the two. Measured at slice S4 (see the S4 block above). totals: - A: {files: 26, loc: 17822} + A: {files: 26, loc: 17834} B: {files: 1, loc: 73} C: {files: 14, loc: 12528} "?": {files: 1, loc: 1435} @@ -254,7 +254,7 @@ files: - path: views/display.js class: A - loc: 661 + loc: 673 exempt: [SNAPSHOT_FIELDS, ACT_IDS, TILE_KINDS, SCOPE_KINDS, TAB_IDS, SESSION_SCOPE_KINDS, SESSION_BRANCH_NAMESPACES, SNAPSHOT_VALUES, DRILL_KINDS, DRAFT_PATHS, SECTION_ORDER] diff --git a/tests/test_bullseye_widget.py b/tests/test_bullseye_widget.py index 56e981e8..dcba4b6e 100644 --- a/tests/test_bullseye_widget.py +++ b/tests/test_bullseye_widget.py @@ -2072,10 +2072,22 @@ def test_the_lens_names_its_scope_in_the_tile_vocabulary_so_a_session_opens(tmp_ assert 'scopeKind: "staged",' in lens assert 'scopeKind: "staged-topic"' not in lens + # THE CANONICAL DECLARATION MOVED (§ 3.4 slice S7): `SESSION_SCOPE_KINDS` + # and `SCOPE_KINDS` are seam-key tables and now live together in + # `views/display.js`, which the class-C model imports and re-exports. Read + # them where they are declared — restoring a duplicate here is precisely + # what the move was for. + display = (WEB / "views" / "display.js").read_text(encoding="utf-8") + scopes = display.split("export const SCOPE_KINDS = {")[1].split("};")[0] + kinds = display.split("export const SESSION_SCOPE_KINDS = {")[1].split("};")[0] + # the lens's spelling must be a KEY of the map, never one of its values: + # `staged` is the TILE spelling (a `SCOPE_KINDS` value), and the session + # spelling it maps to is `staged-topic` + assert 'selection: "staged"' in scopes + assert '[SCOPE_KINDS.selection]: "staged-topic"' in kinds + assert '"staged"' not in kinds + model = (WEB / "views" / "staging-workbench-model.js").read_text(encoding="utf-8") - kinds = model.split("export const SESSION_SCOPE_KINDS = {")[1].split("};")[0] - # the lens's spelling must be a KEY of the map, never one of its values - assert "staged: \"staged-topic\"" in kinds # and the request builder is what applies it — exactly once assert "sessionScopeKind(merged.scopeKind)" in model assert model.count("sessionScopeKind(merged.scopeKind)") == 1 diff --git a/tests/test_display_facet.py b/tests/test_display_facet.py index 3f1a4c6e..717c7c89 100644 --- a/tests/test_display_facet.py +++ b/tests/test_display_facet.py @@ -89,7 +89,7 @@ _SCHEMA_HALF = frozenset({ "fields", "values", "stage_order", "area_order", "artifact_roles", "token_roles", "sections", "kind", "facet", "schema_version", - "host_profile", "host_facet", + "host_profile", "host_facet", "declared_tokens", }) @@ -532,6 +532,70 @@ def test_only_the_tokens_a_host_declared_are_written_onto_root(tmp_path): assert out["declared"] == {"--st-organized": "#123456"} +def test_the_payload_names_which_tokens_the_host_declared(): + """`tokens` cannot answer this and never could: `normalize_display` merges + the host's over openDox's, so the served table carries all four keys + whether the host declared four, one or none. The provenance is therefore + published beside the words (Copilot round 6).""" + assert display_manifest(None)["declared_tokens"] == [] + assert display_manifest({})["declared_tokens"] == [] + partial = display_manifest({"tokens": {"organized": "#123456"}}) + assert partial["declared_tokens"] == ["organized"] + # …while the table itself still carries all four, because the SHELL needs + # a value for every role it may be asked for. + assert sorted(partial["tokens"]) == sorted(TOKEN_ROLES) + whole = display_manifest({"tokens": {role: "#123456" for role in TOKEN_ROLES}}) + assert whole["declared_tokens"] == list(TOKEN_ROLES) + + +@pytest.mark.skipif(NODE is None, reason="node is not installed") +def test_the_served_payload_writes_only_the_host_declared_tokens(tmp_path): + """THE REGRESSION THE PREVIOUS TEST COULD NOT SEE (Copilot round 6). + + `test_only_the_tokens_a_host_declared_are_written_onto_root` hands `Display` + a hand-built facet, where a token key IS a host declaration. The payload the + server actually serves is not that shape: `display_manifest` has already + merged openDox's own tokens in, so every install — including every one in + the estate today, none of which declares a DISPLAY facet — would have had + all four properties written inline on `:root`, outranking `styles.css`'s + per-theme rules and ending dark mode there. + + So this drives the same code path with the REAL payload, built here by the + real `display_manifest`, and nothing in between. + """ + payloads = { + "absent": {"display": display_manifest(None, + host_profile="opendox.neutral")}, + "declared_none": {"display": display_manifest( + {"stages": {"grouping": {"one": "cluster", "many": "clusters", + "short": "clusters", "label": "clusters"}}}, + host_profile="openxfactory.engineering")}, + "declared_one": {"display": display_manifest( + {"tokens": {"organized": "#123456"}}, + host_profile="openxfactory.engineering")}, + } + out = _run_node( + _import_line() + f""" +const payloads = {json.dumps(payloads)}; +function apply(payload) {{ + const written = {{}}; + const el = {{ style: {{ setProperty: (k, v) => {{ written[k] = v; }} }} }}; + D.readDisplay(payload).applyTokens(el); + return written; +}} +const out = {{}}; +for (const [name, payload] of Object.entries(payloads)) out[name] = apply(payload); +console.log(JSON.stringify(out)); +""", tmp_path) + assert out["absent"] == {}, ( + "the payload a host-less install is served wrote `:root` — every " + "install in the estate loses dark mode the moment this lands") + assert out["declared_none"] == {}, ( + "a host that declares a vocabulary but no palette had openDox's own " + "four colours pinned inline over its themes") + assert out["declared_one"] == {"--st-organized": "#123456"} + + @pytest.mark.skipif(NODE is None, reason="node is not installed") def test_two_real_views_render_the_declared_words(tmp_path): """The two pure models the whole bundle's vocabulary flows through: the From 706b53353469c1493b7febee2ca18f6ae729c9c1 Mon Sep 17 00:00:00 2001 From: Brett Heap <1513478+brettheap@users.noreply.github.com> Date: Sat, 12 Sep 2026 23:02:26 -0400 Subject: [PATCH 40/44] =?UTF-8?q?=C2=A7=203.4=20S7:=20five=20surfaces=20th?= =?UTF-8?q?e=20hop=20reached=20and=20the=20facet's=20words=20did=20not?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Copilot round 7 on openDox-code #21 — five threads, one family, the same one rounds 3-5 opened: the value a view MATCHED on went through the facet and the value it SHOWED A HUMAN did not. All five verified live. 1. `views/canvas.js`:321 — the composer confirmation's `state:` line put `plan.state` on screen raw. `composerPlan` seeds it with the DECLARED enum value (`seedState` reads `registerState(CAPTURED)`), so a host override of `values.register_state.captured` reached the last line a human reads before committing a drafted possible, while both sides of the supersession arrow beside it already read words. Now `registerStateWord(plan.state)`. 2. `views/display.js`:398 — `sections: []` is a DECLARATION, not an absence. `display_profile._section_order` preserves an explicitly declared empty list (a host saying its staging template has no canonical heading order), and the truthiness check here replaced it with openDox's own template — so that host's headings were ranked by `outline-model.sectionRank` against a template it never declared, which is § 4.3 point 5's invisible re-domaining exactly. Absent, or not a list, is what falls back now. 3. `views/explorer.js`:105 — the selection tile's one group label was openDox's own corpus layout, "topic folder (incl. any openspec/ drafts)", and stayed on screen whatever the host declared. It is the label above the file list, so it comes off the declared areas: `organized` names the group, `proposed` names what else is in it. 4. `views/explorer.js`'s `fileRow` — the tile resolved through the facet and then every row under it spelled `entry.doc.stage` verbatim in its metadata. The display is threaded in (the bug was the argument that was never passed) and the stage reads `documentStageWord`. 5. `views/staging-workbench.js`:513 — the deterministic abstract's meta line rendered `model.stage` beside a panel whose every other word came off the facet. `documentAbstract` carries `doc.stage` verbatim, so this was the last workbench surface leaking the snapshot enum. Found beside them, same family: `views/funnel.js`:92's search haystack carried the raw enum ALONE, so a human who typed the word on the card matched nothing. It carries both now — the enum, because `dataset.stage` and the column filters match on it, and the word, because that is what is on the screen. Tests: five new probes in `tests/test_display_facet.py` (§ 7), four of them driving the REAL modules under a minimal DOM — a mounted explorer opened on a real tile, the canvas's own composer button clicked, the funnel mounted twice, plus the section order through `outline-model.sectionRank`. Every one proven to have teeth by reverting its fix. The workbench's abstract has no probe here: reaching `renderAbstract` means the mounted-workbench recipe in `tests/test_doxbench_abstract_pane.py`, which this tree cannot run (the carved suite, Q-L5 (b′)) — the same limitation recorded at round 6. Narrowed validate local: 291 passed, 0 failed. Assertion 4 holds at 0. Census `loc:` re-derived. Lane: openxfactory-4-opendox-extraction Refs opensoft/openxFactory#656 Co-Authored-By: Claude Opus 5 --- src/opendox/web/views/canvas.js | 8 +- src/opendox/web/views/display.js | 8 +- src/opendox/web/views/explorer.js | 29 ++- src/opendox/web/views/funnel.js | 9 +- src/opendox/web/views/staging-workbench.js | 6 +- tests/fixtures/web_boundary_census.yaml | 14 +- tests/test_display_facet.py | 258 +++++++++++++++++++++ 7 files changed, 316 insertions(+), 16 deletions(-) diff --git a/src/opendox/web/views/canvas.js b/src/opendox/web/views/canvas.js index 919f3162..5be017ec 100644 --- a/src/opendox/web/views/canvas.js +++ b/src/opendox/web/views/canvas.js @@ -319,7 +319,13 @@ function renderConfirm(container, plan, kind) { box.appendChild(el("div", "dc-line", "id: " + (plan.id || "(missing)"))); box.appendChild(el("div", "dc-line", "title: " + (plan.title || "(missing)"))); box.appendChild(el("div", "dc-line", "claim: " + (plan.claim || "(missing)"))); - box.appendChild(el("div", "dc-line", "state: " + plan.state)); + // THE SEED STATE IS A WORD HERE TOO (Copilot round 7): `composerPlan` + // seeds the plan with the DECLARED enum value (`seedState` reads + // `registerState(CAPTURED)`), so a host override of + // `values.register_state.captured` reached this confirmation line raw + // while every other canvas state surface read through the facet. + box.appendChild(el("div", "dc-line", + "state: " + vocab.registerStateWord(plan.state))); box.appendChild(el("div", "dc-line", "provenance doc: " + (plan.provenanceDoc || "(none)"))); box.appendChild(el("div", "dc-line", "attached evidence pins: " + plan.evidenceCount)); box.appendChild(el("div", "dc-line", "lands at: " + plan.landsAt)); diff --git a/src/opendox/web/views/display.js b/src/opendox/web/views/display.js index 5ab24f49..af070672 100644 --- a/src/opendox/web/views/display.js +++ b/src/opendox/web/views/display.js @@ -395,7 +395,13 @@ export class Display { pick(facet.stages, NEUTRAL_DISPLAY.stages, role), this.fields[role]); } - this._sections = Array.isArray(facet.sections) && facet.sections.length + // AN EMPTY LIST IS A DECLARATION, NOT AN ABSENCE (Copilot round 7). + // `display_profile._section_order` PRESERVES an explicitly declared + // `sections: []` -- a host saying "my staging template has no canonical + // heading order" -- so a truthiness check here would silently restore + // openDox's own template and match that host's headings against it. + // Absent, or not a list at all, is what falls back. + this._sections = Array.isArray(facet.sections) ? facet.sections.slice() : SECTION_ORDER.slice(); this._values = {}; for (const name of Object.keys(SNAPSHOT_VALUES)) { diff --git a/src/opendox/web/views/explorer.js b/src/opendox/web/views/explorer.js index f1b6426f..790f1288 100644 --- a/src/opendox/web/views/explorer.js +++ b/src/opendox/web/views/explorer.js @@ -115,7 +115,18 @@ export function resolveExplorerTarget(kind, id, snapshot, display) { subtitle: (d.area("organized").prefix || "") + id + " · " + n + " file" + (n === 1 ? "" : "s") + (t.target_change ? " · → " + t.target_change : " · no pick yet"), - groups: [{ label: "topic folder (incl. any openspec/ drafts)", files }], + // THE GROUP LABEL COMES OFF THE DECLARED AREAS (Copilot round 7). It + // used to name openDox's own corpus layout ("topic folder (incl. any + // openspec/ drafts)"), which stayed on screen whatever the host + // declared -- the one human-facing label in this module the context hop + // could not reach. The group IS the whole of a selection's folder, so + // it is named by the area a selection lives in, and says that anything + // drafted toward a submission is in it rather than filed separately. + groups: [{ + label: d.area("organized").label + " (every file, incl. any " + + d.area("proposed").label + ")", + files, + }], }; } if (kind === DRILL_KINDS.submission || kind === DRILL_KINDS.completion) { @@ -143,12 +154,20 @@ export function resolveExplorerTarget(kind, id, snapshot, display) { // itself a governed document in `documents[]` (status/kind/summary/topics); // files outside that projection (e.g. a change's proposal.md) list by name // only — the spec requires headers only for the staged-topic scenario. -function fileRow(entry, onOpen) { +// `display` is threaded in (Copilot round 7) because this row's metadata is +// the LAST human-facing surface in the explorer that still read the raw +// `document_stage` enum: `resolveExplorerTarget` resolved the tile through the +// facet and then the rows under it spelled the schema value. +function fileRow(entry, onOpen, display) { + const d = display || neutralDisplay(); const row = el("div", "docrow explorer-row"); const info = el("span"); info.appendChild(el("span", "name", esc(basename(entry.path)))); const bits = [entry.path]; - if (entry.doc) bits.push(entry.doc.stage, entry.doc.kind, entry.doc.summary); + if (entry.doc) { + bits.push(entry.doc.stage ? d.documentStageWord(entry.doc.stage) : null, + entry.doc.kind, entry.doc.summary); + } info.appendChild(el("div", "where", esc(bits.filter(Boolean).join(" · ")))); row.appendChild(info); if (entry.doc && (entry.doc.topics || []).length) { @@ -263,7 +282,7 @@ export function mountExplorer(container, snapshot, { onOpenFile, signal, display for (const entry of group.files) { list.appendChild(fileRow(entry, (e) => { if (onOpenFile) onOpenFile(e, viewer, currentTile); - })); + }, display)); } } } @@ -296,7 +315,7 @@ export function mountExplorer(container, snapshot, { onOpenFile, signal, display list.appendChild(el("div", "docgroup", "source file (read-only)")); list.appendChild(fileRow(entry, (e) => { if (onOpenFile) onOpenFile(e, viewer, currentTile); - })); + }, display)); overlay.hidden = false; closeBtn.focus(); // initial focus lands inside the dialog (a11y #19) if (onOpenFile) onOpenFile(entry, viewer, currentTile); diff --git a/src/opendox/web/views/funnel.js b/src/opendox/web/views/funnel.js index 371e5b4e..296a6492 100644 --- a/src/opendox/web/views/funnel.js +++ b/src/opendox/web/views/funnel.js @@ -89,7 +89,14 @@ function docCard(node) { // scoping/search metadata (#13/#14) — read by the visibility filter, never by the model. card.dataset.stage = d.stage || ""; card.dataset.scoped = (isIdeationDoc(d) || (d.topics || []).length) ? "1" : ""; - card.dataset.hay = [d.path, d.stage, ...(d.topics || [])].filter(Boolean).join(" ").toLowerCase(); + // THE SEARCH HAYSTACK CARRIES BOTH (Copilot round 7's family): the raw enum, + // because `dataset.stage` and the column filters match on it, AND the word + // the card actually SHOWS -- a human types what is on the screen, and under + // a host override that word was in neither field. + card.dataset.hay = [d.path, d.stage, + d.stage ? vocab.documentStageWord(d.stage) : null, + ...(d.topics || [])] + .filter(Boolean).join(" ").toLowerCase(); card.appendChild(el("div", "id", basename(d.path))); const topicN = (d.topics || []).length; // THE CARD'S META READS THE DOMAIN'S WORD (Copilot round 4); `dataset.stage` diff --git a/src/opendox/web/views/staging-workbench.js b/src/opendox/web/views/staging-workbench.js index 099739d4..9a2c0f61 100644 --- a/src/opendox/web/views/staging-workbench.js +++ b/src/opendox/web/views/staging-workbench.js @@ -510,7 +510,11 @@ function renderAbstract(host, doc, ctx) { } return; } - const meta = [model.stage, model.kind].filter(Boolean).join(" · "); + // THE ABSTRACT'S STAGE IS A WORD (Copilot round 7): `documentAbstract` + // carries `doc.stage` verbatim -- the snapshot's enum -- and this panel was + // the one workbench surface still rendering it beside the facet's words. + const meta = [model.stage ? vocab.documentStageWord(model.stage) : null, + model.kind].filter(Boolean).join(" · "); if (meta) body.appendChild(el("div", "swb-abstractmeta", meta)); if (model.note) { body.appendChild(el("div", "swb-empty", model.note)); diff --git a/tests/fixtures/web_boundary_census.yaml b/tests/fixtures/web_boundary_census.yaml index a7cc5b45..839a65dc 100644 --- a/tests/fixtures/web_boundary_census.yaml +++ b/tests/fixtures/web_boundary_census.yaml @@ -191,9 +191,9 @@ measured_at: "opensoft/openDox-code main a99eba03e31a0aee1cc15a061fdf718cc88a2c4 # shape and `test_the_declared_totals_are_re_derived_from_the_rows` can refuse a # drift between the two. Measured at slice S4 (see the S4 block above). totals: - A: {files: 26, loc: 17834} + A: {files: 26, loc: 17840} B: {files: 1, loc: 73} - C: {files: 14, loc: 12528} + C: {files: 14, loc: 12564} "?": {files: 1, loc: 1435} files: - path: app.js @@ -243,7 +243,7 @@ files: - path: views/canvas.js class: C - loc: 458 + loc: 464 note: "renders canvas-model.js's output; 7 governance literals" - path: views/composed-model.js @@ -254,7 +254,7 @@ files: - path: views/display.js class: A - loc: 673 + loc: 679 exempt: [SNAPSHOT_FIELDS, ACT_IDS, TILE_KINDS, SCOPE_KINDS, TAB_IDS, SESSION_SCOPE_KINDS, SESSION_BRANCH_NAMESPACES, SNAPSHOT_VALUES, DRILL_KINDS, DRAFT_PATHS, SECTION_ORDER] @@ -304,12 +304,12 @@ files: - path: views/explorer.js class: C - loc: 306 + loc: 325 note: "Q2 RULING: class C outright (was \"?\" in the note's own table) -- a projection whose only domain content is the artifact-folder vocabulary; classifyChangeFile; reads staged_topics[].files / changes[].files" - path: views/funnel.js class: C - loc: 602 + loc: 609 note: "realization funnel; imports model.js's COLUMN_KEYS; 10 governance literals" - path: views/grouping.js @@ -387,7 +387,7 @@ files: - path: views/staging-workbench.js class: C - loc: 3455 + loc: 3459 note: "full-screen workbench scoped to one topic-bearing tile loc 3397 -> 3402 on this PR's round-2 review (Copilot): the two contributed columns are per-mount `const`s inside mountStagingWorkbench rather than module-level `let`s, so two live workbenches cannot share them." - path: views/swb-model-intake.js diff --git a/tests/test_display_facet.py b/tests/test_display_facet.py index 717c7c89..dec770b1 100644 --- a/tests/test_display_facet.py +++ b/tests/test_display_facet.py @@ -679,3 +679,261 @@ def test_the_workbench_model_takes_the_vocabulary_at_the_mount(tmp_path): # a product told no corpus layout defaults to the repository root assert out["neutralAreaAfterReset"] == "" assert out["declaredArea"] == "ideation/brainstorm/" + + +# --------------------------------------------------------------------------- +# 7. COPILOT ROUND 7 -- the surfaces the context hop REACHED and the facet's +# words did not. Every one of them is the same shape as rounds 3-5: the +# value a view MATCHED on went through the facet and the value it SHOWED A +# HUMAN did not, or a declaration that says "nothing" was read as "unset". +# --------------------------------------------------------------------------- + +def test_a_declared_empty_section_order_is_a_declaration_not_an_absence(): + """`_section_order` PRESERVES `sections: []` -- a host saying its staging + template has no canonical heading order at all -- so the browser half must + not read that as "undeclared" and restore openDox's own template. An empty + list means every heading is anchored explicitly; the template's order is + openDox's, and matching a host's headings against it is exactly the + invisible re-domaining § 4.3 point 5 names.""" + assert display_profile._section_order({"sections": []}) == [] + assert display_manifest({"sections": []})["sections"] == [] + # `sections` is a legal facet key (a declaration, not an unknown role) + assert normalize_display({"sections": []}) is not None + # and absent still falls back to openDox's own + assert display_manifest({})["sections"] == list(SECTION_ORDER) + assert display_manifest({"sections": ["frage"]})["sections"] == ["frage"] + + +@pytest.mark.skipif(NODE is None, reason="node is not installed") +def test_the_browser_half_keeps_a_declared_empty_section_order(tmp_path): + """The other half of the test above, and the reason it is a bug rather than + a style point: `outline-model.sectionRank` is what DECIDES where an added + section goes, so a host that declared no order would have its headings + ranked by openDox's template and its material silently reordered.""" + views = json.dumps(str(WEB / "views")) + out = _run_node(f""" +const base = {views} + "/"; +const D = await import(base + "display.js"); +const O = await import(base + "outline-model.js"); +const facet = (sections) => D.readDisplay({{ display: Object.assign( + {{ schema_version: 1, kind: "opendox.display-facet" }}, + sections === undefined ? {{}} : {{ sections }}) }}); +console.log(JSON.stringify({{ + declaredEmpty: facet([]).sections(), + declaredEmptyRank: O.sectionRank("Open questions", facet([])), + absent: facet(undefined).sections(), + absentRank: O.sectionRank("Open questions", facet(undefined)), + declaredOwn: facet(["frage"]).sections(), +}})); +""", tmp_path) + assert out["declaredEmpty"] == [] + assert out["declaredEmptyRank"] is None, ( + "a host that declared no canonical order still had its headings ranked") + assert out["absent"] == list(SECTION_ORDER) + assert out["absentRank"] is not None + assert out["declaredOwn"] == ["frage"] + + +@pytest.mark.skipif(NODE is None, reason="node is not installed") +def test_the_explorer_names_a_selection_group_from_the_declared_areas(tmp_path): + """`resolveExplorerTarget`'s selection tile carried openDox's own corpus + layout in its one group label ("topic folder (incl. any openspec/ + drafts)"). It is the label a human reads above the file list, so it is the + facet's business, and § 2.1 calls this module's corpus wording its "only + domain content".""" + views = json.dumps(str(WEB / "views")) + out = _run_node(f""" +const base = {views} + "/"; +const D = await import(base + "display.js"); +const {{ resolveExplorerTarget }} = await import(base + "explorer.js"); +const snap = {{ staged_topics: [{{ staging_id: "topic-x", files: ["a.md"] }}], + documents: [{{ path: "a.md", stage: "brainstorm" }}], + changes: [] }}; +const declared = D.readDisplay({{ display: {{ + schema_version: 1, kind: "opendox.display-facet", host_facet: "declared", + areas: {{ organized: {{ prefix: "ideation/staging/", label: "staging topic" }}, + proposed: {{ prefix: "openspec/changes/", label: "openspec changes" }} }}, +}} }}); +const label = (d) => resolveExplorerTarget( + D.DRILL_KINDS.selection, "topic-x", snap, d).groups[0].label; +console.log(JSON.stringify({{ + neutral: label(D.neutralDisplay()), declared: label(declared), +}})); +""", tmp_path) + assert "staging topic" in out["declared"] + assert "openspec changes" in out["declared"] + assert "openspec/" not in out["neutral"] and "topic folder" not in out["neutral"] + assert out["neutral"] != out["declared"] + + +# A minimal DOM -- enough for `helpers.el`, the explorer's overlay and the +# canvas's composer, and nothing more. Every node records its tag, class, text, +# attributes, wired listeners and children, so a harness can report the tree as +# JSON and fire a click. The same idiom as `tests/test_split_route_tails.py`'s. +_DOM_STUB = r""" +class Node { + constructor(tag) { + this.tag = tag; this.children = []; this.attrs = {}; this.listeners = {}; + this.className = ""; this._text = ""; this.type = ""; this.title = ""; + this.value = ""; this.checked = false; this.disabled = false; + this.hidden = false; this.focused = false; this.tabIndex = -1; + this.placeholder = ""; this.rows = 0; this.id = ""; this.dataset = {}; + this.style = { setProperty() {}, removeProperty() {}, getPropertyValue: () => "" }; + } + get textContent() { return this._text; } + set textContent(v) { this._text = String(v); this.children = []; } + // `views/explorer.js`'s own `el` escapes its text and assigns it through + // innerHTML, so the stub records it as text rather than refusing it. + set innerHTML(v) { this._text = String(v); this.children = []; } + get innerHTML() { return this._text; } + appendChild(c) { this.children.push(c); return c; } + setAttribute(k, v) { this.attrs[k] = String(v); } + addEventListener(t, fn) { (this.listeners[t] = this.listeners[t] || []).push(fn); } + removeEventListener() {} + querySelectorAll() { return []; } + focus() { this.focused = true; globalThis.document.activeElement = this; } + click() { for (const fn of this.listeners.click || []) fn({}); } +} +globalThis.document = { + createElement: (tag) => new Node(tag), + createTextNode: (text) => Object.assign(new Node("#text"), { _text: String(text) }), + createElementNS: (_ns, tag) => new Node(tag), + addEventListener() {}, removeEventListener() {}, activeElement: null, +}; +function flatten(node, out = []) { + out.push(node); + for (const c of node.children) flatten(c, out); + return out; +} +function texts(node) { + return flatten(node).map((n) => n.textContent).filter(Boolean); +} +""" + + +@pytest.mark.skipif(NODE is None, reason="node is not installed") +def test_the_explorer_file_rows_show_the_declared_stage_word(tmp_path): + """The tile RESOLVED through the facet and then the rows under it spelled + the snapshot's `document_stage` enum verbatim in their metadata -- the one + surface in this module the context hop threaded past. Driven through the + real mount and a real tile open, not through `fileRow` directly, because + the bug was the ARGUMENT that was never passed.""" + views = json.dumps(str(WEB / "views")) + out = _run_node(_DOM_STUB + f""" +const base = {views} + "/"; +const D = await import(base + "display.js"); +const {{ mountExplorer }} = await import(base + "explorer.js"); +const snap = {{ + staged_topics: [{{ staging_id: "topic-x", files: ["a.md"] }}], + documents: [{{ path: "a.md", stage: "brainstorm", kind: "note" }}], + changes: [], +}}; +const declared = D.readDisplay({{ display: {{ + schema_version: 1, kind: "opendox.display-facet", host_facet: "declared", + values: {{ document_stage: {{ captured: "brainstorm" }} }}, + statuses: {{ document: {{ captured: "jotted" }} }}, +}} }}); +function rowTexts(display) {{ + const host = new Node("div"); + const explorer = mountExplorer(host, snap, {{ display }}); + explorer.openTile(D.DRILL_KINDS.selection, "topic-x"); + return flatten(host).filter((n) => n.className === "where").map((n) => n.textContent); +}} +console.log(JSON.stringify({{ + neutral: rowTexts(D.neutralDisplay()), declared: rowTexts(declared), +}})); +""", tmp_path) + assert out["declared"], "the tile rendered no file row at all" + assert any("jotted" in t for t in out["declared"]), out["declared"] + assert not any("brainstorm" in t for t in out["declared"]), ( + "the row still spells the snapshot enum a host declared a word for") + # the neutral install shows openDox's own word for the same value + assert not any("jotted" in t for t in out["neutral"]), out["neutral"] + assert any("captured" in t for t in out["neutral"]), out["neutral"] + + +@pytest.mark.skipif(NODE is None, reason="node is not installed") +def test_the_canvas_confirmation_shows_the_declared_seed_word(tmp_path): + """`composerPlan` seeds a drafted possible with the DECLARED enum value, so + the confirmation a human reads before committing spelled the schema value + while both sides of the supersession arrow beside it read words (round 4). + Driven through the real composer button, which is the path that builds the + plan.""" + views = json.dumps(str(WEB / "views")) + out = _run_node(_DOM_STUB + f""" +const base = {views} + "/"; +const D = await import(base + "display.js"); +const {{ renderCanvas }} = await import(base + "canvas.js"); +const snap = {{ + documents: [{{ id: "a.md", path: "a.md" }}], + clusters: [{{ id: "c1", name: "C", document_edges: [{{ document: "a.md" }}], + tallies: {{ document_links: 1 }} }}], + possibles: [], staged_topics: [], changes: [], evidence: [], +}}; +const declared = D.readDisplay({{ display: {{ + schema_version: 1, kind: "opendox.display-facet", host_facet: "declared", + values: {{ register_state: {{ captured: "latent" }} }}, + statuses: {{ candidate: {{ captured: "parked" }} }}, +}} }}); +function confirmLines(display) {{ + const root = new Node("div"); + renderCanvas(root, snap, {{ display }}); + const composer = flatten(root).find((n) => n.className === "composer"); + if (!composer) throw new Error("no composer in the canvas"); + const button = flatten(composer).find((n) => n.tag === "button"); + if (!button) throw new Error("no draft button in the composer"); + button.click(); + return flatten(root).filter((n) => n.className === "dc-line") + .map((n) => n.textContent); +}} +console.log(JSON.stringify({{ + neutral: confirmLines(D.neutralDisplay()), + declared: confirmLines(declared), +}})); +""", tmp_path) + declared_state = [t for t in out["declared"] if t.startswith("state: ")] + assert declared_state, out["declared"] + assert declared_state[0] == "state: parked", declared_state + neutral_state = [t for t in out["neutral"] if t.startswith("state: ")] + assert neutral_state[0] != "state: latent", ( + "the confirmation still spells the register's enum value") + + +@pytest.mark.skipif(NODE is None, reason="node is not installed") +def test_the_funnel_search_matches_the_word_a_human_can_see(tmp_path): + """The same family, found beside the four Copilot named: the doc card's + meta reads the facet (round 4) and its SEARCH HAYSTACK still carried the + raw enum alone, so a human who typed the word on the card matched nothing. + The haystack carries both -- the enum, because `dataset.stage` and the + column filters match on it, and the word, because that is what is on the + screen.""" + views = json.dumps(str(WEB / "views")) + out = _run_node(_DOM_STUB + f""" +// the funnel mounts a real column layout: three browser globals it uses for +// the sticky header and the column measure, and nothing else. +globalThis.ResizeObserver = class {{ observe() {{}} disconnect() {{}} }}; +globalThis.requestAnimationFrame = (fn) => fn(); +const base = {views} + "/"; +const D = await import(base + "display.js"); +const {{ renderFunnel }} = await import(base + "funnel.js"); +const snap = {{ + documents: [{{ id: "a.md", path: "a.md", stage: "brainstorm", topics: [] }}], + clusters: [], possibles: [], staged_topics: [], changes: [], +}}; +const declared = D.readDisplay({{ display: {{ + schema_version: 1, kind: "opendox.display-facet", host_facet: "declared", + values: {{ document_stage: {{ captured: "brainstorm" }} }}, + statuses: {{ document: {{ captured: "jotted" }} }}, +}} }}); +function hays(display) {{ + const root = new Node("div"); + renderFunnel(root, snap, {{ display }}); + return flatten(root).filter((n) => n.dataset && n.dataset.hay) + .map((n) => n.dataset.hay); +}} +console.log(JSON.stringify({{ + declared: hays(declared), neutral: hays(D.neutralDisplay()), +}})); +""", tmp_path) + assert out["declared"] == ["a.md brainstorm jotted"] + assert out["neutral"] == ["a.md brainstorm captured"] From d672f0c77a7f097e3ad14dd54a82ea6fd81177d4 Mon Sep 17 00:00:00 2001 From: Brett Heap <1513478+brettheap@users.noreply.github.com> Date: Sun, 13 Sep 2026 22:04:02 +0000 Subject: [PATCH 41/44] =?UTF-8?q?=C2=A7=203.4=20S7:=20four=20arrived=20sui?= =?UTF-8?q?tes=20nobody=20had=20run=20since=20the=20carve?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Slice S8 ran the web suites this leg's `validate` is narrowed away from (RULED Q-L5 (b′)) and handed back four that fail on this branch (`#656` comment `5650335573` § 4). Every one of them is an ARRIVED test file quoting a line that slice S5 or slice S7 moved, so every edit here is a DECLARED EDIT owed to this slice's row annotation. Measured green at this head: `test_doc_surfaces.py` 11, `test_doxbench_tile_verbs.py` 22, `test_doxbench_view.py` 136, `test_bullseye_widget.py` 52 — the same counts `main` gives. NO PRODUCT FILE CHANGES. Four test files, and in each one the assertion is re-stated as the RULE it was always making rather than as the word or the path it happened to spell. * `tests/test_doc_surfaces.py` — the stat tile is found BY ROLE. It asked for a tile headed `Documents`, which is openxFactory's word for the first station of openDox's own spine and exactly the literal RULED Q1/Q2 sent through the display facet. `views/lineage.js` headlines it `cap(display.label(SOURCE))` and spells each `documents[].stage` through `display.documentStageWord(value)`, so the node harness now reports the vocabulary it rendered with and the three sub-line assertions name the stage by its WORD while still counting it by its VALUE. What they measure — that the sub-line sums to its headline — is a property of the arithmetic and is untouched. * `tests/test_doxbench_tile_verbs.py` — the inert Save's refusal is read from the module. "no unsaved changes" carries `changes`, which `tests/test_web_boundary.py`'s `_STAGE_WORDS` watches and `views/doc-wheel.js` is a class-C file that may carry no governance literal, so the slice respelled it. The three save refusals are read where they are declared and compared, so the property — that a clean buffer states THIS refusal and not read-only context or not-yet-loaded — survives any future respelling and refuses any two of the three collapsing into one. * `tests/test_bullseye_widget.py` — `WHEEL_ACTIONS` is read by STATION INDEX (it is keyed `[STAGE_ROLES[n]]` since this slice, like every other per-wheel table in that module); the draft view's create dialog is opened through the CONTRIBUTED column (`swb-create.js` is openXdox-code's package data since slice S5, RULED Q5) with the seed in RULED Q3's context; and `DRAFT_TILE_KIND` is read as `SCOPE_KINDS.selection` out of `views/display.js`, where the seam tables now live. ONE READ IS RETIRED IN PLACE: `scripts/doc_health/staging_seed.py`. The drafter is openxFactory's engine, and `docs/opendox-carve-manifest.yaml` files its suite `tests/ideation-dashboard/test_staging_seed.py` as `not_moved` / `stays_openxfactory_adapter`, on the evidence that the subject "lies outside the carve surface entirely and has no row and no replica" — so that path is one this leg has never had and will never have. The half this bundle owns is asserted on the line above it: the browser READS `staging_id` off the drafter's payload rather than parsing it out of the fragment's prose. * `tests/test_doxbench_view.py` — the two whole-shell harnesses CONTRIBUTE a gate column. `canvasOffered()` reads `createColumn.createGateLive(caps)` off the contributed `gate.workbench.create` binding since slice S5, and a harness that hands the mount no column is a student install: the canvas is correctly withheld with a stated read-only posture, and both harnesses waited forever for textareas that were never going to be offered. A HOST is what contributes a column and a harness that mounts the shell is acting as the host, so `_CONTRIBUTED_GATE` supplies one per mount exactly as `app.js` does — nothing of the contributed column's UI is re-created here, which is why the create half mounts nothing and the session half only RECORDS the context the shell hands it. The abandon probe follows from that. It clicked `swb-sessionbtn`, filled a `Reason`, clicked `abandon-session` and read a `swb-clanded` report — four surfaces `views/swb-session.js` renders and this bundle no longer ships. The row's own behaviour travels with the module, on the precedent slices S4 and S5 set for five node probes and a dispose tray; what is measured here is the half this file is named for, the SHELL's FR-039 clearing, entered by the same call the contributed row makes — the `onSessionEnded` callback on the context the column recorded at mount. NOT TAKEN: slice S8's two PATH-CONSTANT repairs in these same files (`test_doxbench_view.py`'s `PREVIEW_CASES_PATH`, `test_bullseye_widget.py`:1674's `scripts/ideation_dashboard/serve.py`). Both are DECLARED on openxFactory #1025 and realized on openDox-code #23; taking them here would make an annotation that lands first say something untrue and would declare one line in two slices. They were applied to a throwaway worktree to measure against S8's own baseline and left alone, so `test_the_serve_declares_the_repository_it_can_write_to` is red at this head until #23 lands, exactly as it is on `main` today. Lane: openxfactory-4-opendox-extraction Refs opensoft/openxFactory#656 Co-Authored-By: Claude Opus 5 (1M context) --- tests/test_bullseye_widget.py | 81 ++++++++++++--- tests/test_doc_surfaces.py | 73 ++++++++++++-- tests/test_doxbench_tile_verbs.py | 42 +++++++- tests/test_doxbench_view.py | 160 ++++++++++++++++++++++++------ 4 files changed, 303 insertions(+), 53 deletions(-) diff --git a/tests/test_bullseye_widget.py b/tests/test_bullseye_widget.py index dcba4b6e..393af696 100644 --- a/tests/test_bullseye_widget.py +++ b/tests/test_bullseye_widget.py @@ -44,6 +44,29 @@ WORKBENCH_JS = WEB / "views" / "staging-workbench.js" NODE = shutil.which("node") + +def _wheel_action_rows(model: str) -> dict[int, str]: + """`wheel-model.js`'s `WHEEL_ACTIONS`, one source block per STATION INDEX. + + The table was keyed by the four station WORDS (`documents:`, `clusters:`, + `possibles:`, `staged:` …) and is keyed `[STAGE_ROLES[n]]` since § 3.4 slice + S7, like every other per-wheel table in that module: a station is a POSITION + on openDox's own six-stage spine, and the word for it belongs to whichever + domain registered a display facet. So a block is found by the index the spine + declares, which no domain may respell, rather than by a word any domain may. + """ + table = model.split("export const WHEEL_ACTIONS = {", 1)[1].split("\n};", 1)[0] + blocks = {} + for chunk in table.split("\n [STAGE_ROLES[")[1:]: + index, marker, rest = chunk.partition("]]: [") + assert marker, f"unparsable WHEEL_ACTIONS key: {chunk[:40]!r}" + blocks[int(index)] = rest + assert sorted(blocks) == [0, 1, 2, 3, 4, 5], ( + f"WHEEL_ACTIONS declares stations {sorted(blocks)}, not the six the " + f"spine does") + return blocks + + # A minimal SVG-only DOM: every node records its tag, attributes, text, wired # event types, and children, so the harness can report the tree as JSON. The # widget touches nothing else (createElementNS + setAttribute + appendChild + @@ -1316,8 +1339,21 @@ def test_the_drafted_seed_moves_to_doxbench_instead_of_being_copied(tmp_path): swb = (WEB / "views" / "staging-workbench.js").read_text(encoding="utf-8") assert "function openDraft(seed)" in swb # the create dialog now lives on the draft view's `details` tab rather than - # filling the overlay body (see the draft-view test below) - assert "openCreateDialog(detailsPane, seed" in swb + # filling the overlay body (see the draft-view test below), and it is + # OPENED THROUGH THE CONTRIBUTED COLUMN since § 3.4 slice S5: `swb-create.js` + # is openXdox-code's package data (RULED Q5, openxFactory#656 comment + # `5648044785`), so this file resolves `gate.workbench.create`'s declared + # namespace at the mount instead of importing the module. RULED Q3 fixed the + # mount signature at `mount(host, snapshot, ctx)`, which is why the seed + # travels in the context rather than as the second positional argument. Both + # halves of the original statement are kept: the host is still the details + # pane, and the seed still reaches the dialog. + call = swb.split( + "createColumn.openCreateDialog(detailsPane, shellSnapshot, {", 1) + assert len(call) == 2, ( + "the draft view no longer opens the create dialog on its details pane") + assert "seed," in call[1].split("caps:", 1)[0], \ + "the seed no longer travels into the create dialog's context" assert "return { open, close, openDraft };" in swb # an ungated plane says so rather than offering a submit that cannot land draft_body = swb.split("function openDraft(seed)")[1].split("\n }")[0] @@ -1751,15 +1787,16 @@ def test_a_staged_tile_opens_its_packet_rather_than_repointing_the_dashboard(): tile IS one repository's document. """ model = (WEB / "views" / "wheel-model.js").read_text(encoding="utf-8") - staged = model.split(" staged: [")[1].split("\n ],")[0] - code = "\n".join(ln for ln in staged.splitlines() + rows = _wheel_action_rows(model) + # SELECTION is the staged wheel's station (`STAGE_ROLES[3]`) + code = "\n".join(ln for ln in rows[3].splitlines() if not ln.lstrip().startswith("//")) assert "workbenchRow" in code assert "openRepoRow" not in code - # …and every other wheel keeps it - for wheel in ("documents", "clusters", "possibles"): - block = model.split(" " + wheel + ": [")[1].split("\n ],")[0] - assert "openRepoRow" in block, wheel + # …and every other wheel keeps it. The loop named three stations by word and + # names all five by role now, which is what "every other wheel" always said. + for role_index in (0, 1, 2, 4, 5): + assert "openRepoRow" in rows[role_index], role_index def test_a_reload_bearing_control_returns_you_to_the_view_you_were_on(): @@ -1977,7 +2014,15 @@ def test_the_draft_view_lands_on_an_editable_body_with_its_fields_behind_a_tab() # resolves its scope with (2026-08-10) — a literal here would be the same # vocabulary applied in two places that dropped the scope in #152 assert "tile_kind: DRAFT_TILE_KIND," in draft - assert 'const DRAFT_TILE_KIND = "staged";' in swb + # …and that ONE constant is the seam-key table's entry for the selection + # station (§ 3.4 slice S7): `SCOPE_KINDS` moved into `views/display.js` with + # its sibling seam tables, so the tile spelling is declared once, BY ROLE, + # and read here rather than spelled a second time in this file — which is + # the same argument the sentence above makes about the two call sites. + assert "const DRAFT_TILE_KIND = SCOPE_KINDS.selection;" in swb + display = (WEB / "views" / "display.js").read_text(encoding="utf-8") + scopes = display.split("export const SCOPE_KINDS = {")[1].split("};")[0] + assert 'selection: "staged"' in scopes assert "tile_id: seed.scopeId" in draft assert "loaded.content" in draft # the created header survives # a body that fails after the header lands says exactly that @@ -1988,10 +2033,20 @@ def test_the_draft_view_lands_on_an_editable_body_with_its_fields_behind_a_tab() # `test_the_lens_names_its_scope_in_the_tile_vocabulary_so_a_session_opens`) assert 'scopeKind: "staged",' in lens assert "scopeId: String(data?.staging_id" in lens - # the id is RETURNED by the drafter, not parsed out of the fragment's prose - seed_py = (REPO_ROOT / "scripts" / "doc_health" / "staging_seed.py").read_text( - encoding="utf-8") - assert '"staging_id": self.staging_id' in seed_py + # THE DRAFTER'S OWN HALF IS NOT THIS REPOSITORY'S TO ASSERT. The id is + # RETURNED by `doc_health.staging_seed` (`"staging_id": self.staging_id`), + # and that module is openxFactory's engine: `docs/opendox-carve-manifest.yaml` + # files its suite `tests/ideation-dashboard/test_staging_seed.py` as + # `disposition: not_moved`, `reason: stays_openxfactory_adapter`, on the + # evidence that the subject "lies outside the carve surface entirely and has + # no row and no replica". `scripts/doc_health/staging_seed.py` is therefore a + # path this leg has never had and will never have — the read above it was a + # PRE-CARVE path that had simply not been noticed, because this suite is + # narrowed out of `validate` (RULED Q-L5 (b′)) and nobody had run it since. + # What stays here is the half this bundle owns, and it is the half the + # sentence was actually about: the browser READS `staging_id` off the + # drafter's payload (the line above) rather than parsing it out of the + # fragment's prose. def test_every_create_field_carries_a_default_so_nothing_blocks_the_create(tmp_path): diff --git a/tests/test_doc_surfaces.py b/tests/test_doc_surfaces.py index a1814843..f2d9aae8 100644 --- a/tests/test_doc_surfaces.py +++ b/tests/test_doc_surfaces.py @@ -88,6 +88,12 @@ }; const { renderDocs } = await import('./docs.js'); const { renderStats } = await import('./lineage.js'); +// § 3.4 slice S7: both views render the REGISTERED DOMAIN'S words, resolved by +// role through the display facet. Neither view is handed one here, so both use +// openDox's own neutral vocabulary -- and the harness reports that same +// vocabulary beside the tree it rendered, so the assertions below can name a +// ROLE where they used to spell a word. +const { neutralDisplay, STAGE_ROLES } = await import('./display.js'); import { readFileSync } from 'node:fs'; function flatten(node, out) { @@ -159,6 +165,21 @@ }; return { k: part('k'), v: part('v'), s: part('s') }; }); +// THE VOCABULARY THESE TWO VIEWS RENDERED WITH. `sourceLabel` is the station +// label the stats strip headlines the corpus-wide tile with (`display.label`), +// and `stageWords` is what each `documents[].stage` VALUE in this fixture is +// spelled as on screen (`display.documentStageWord`) -- the value stays the +// grouping key, the word is what a human reads. +{ + const vocab = neutralDisplay(); + const stageValues = [...new Set(snapshot.documents.map((d) => d.stage))]; + out.vocabulary = { + sourceLabel: vocab.label(STAGE_ROLES[0]), + stageWords: Object.fromEntries( + stageValues.map((value) => [value, vocab.documentStageWord(value)])), + }; +} + console.log(JSON.stringify(out)); """ @@ -304,10 +325,34 @@ def test_the_doc_tab_is_wired_to_the_one_cross_view_jump(): # defect 15 — the DOCUMENTS stat tile's sub-line does not sum to its headline # --------------------------------------------------------------------------- -def _documents_tile(rendered): +# THE TILE IS FOUND BY ROLE, NOT BY ITS HEADING (§ 3.4 slice S7). This asked for +# a tile called `Documents`, and `Documents` was openxFactory's word for the +# first station rendered in openDox's own shell -- exactly the class of literal +# RULED Q1/Q2 sent through the display facet (`#656` comment `5648049748`). +# `views/lineage.js` headlines the tile with `cap(display.label(SOURCE))` now, so +# the tile is located through the same vocabulary the view rendered it with, and +# this file passes under a domain that calls the station anything at all. What +# the three assertions below measure -- that the sub-line sums to its headline -- +# is a property of the ARITHMETIC and is untouched by the respelling. +def _source_tile(rendered): + label = rendered["vocabulary"]["sourceLabel"] + # `views/lineage.js`'s own `cap`: the facet declares words, not capitals + heading = label[:1].upper() + label[1:] tiles = {t["k"]: t for t in rendered["stats"]} - assert "Documents" in tiles, tiles - return tiles["Documents"] + assert heading in tiles, (heading, tiles) + return tiles[heading] + + +def _stage_word(rendered, stage): + """What `documents[].stage` VALUE `stage` is spelled as on screen. + + `display.documentStageWord` resolves the snapshot's closed enum value to a + role and answers the registered domain's word for it, returning the value + verbatim where no declared role carries it -- which is how this fixture's + eight-stage corpus keeps reading truthfully (openDox declares roles for two + of the eight). + """ + return rendered["vocabulary"]["stageWords"][stage] def _subline_numbers(sub): @@ -318,7 +363,7 @@ def test_the_documents_sub_line_sums_to_its_own_headline(rendered): """177 over 'draft 65 · staged 32 · brainstorm 39' = 136 silently dropped 41 documents. Whatever shape the sub-line takes, its numbers must add up to the headline it sits under — that is the whole contract.""" - tile = _documents_tile(rendered) + tile = _source_tile(rendered) assert tile["v"] == "177" assert sum(_subline_numbers(tile["s"])) == 177, \ f"the sub-line does not sum to the headline: {tile['s']!r}" @@ -327,13 +372,20 @@ def test_the_documents_sub_line_sums_to_its_own_headline(rendered): def test_the_documents_sub_line_accounts_for_the_stages_it_does_not_name(rendered): """Partial is allowed — 'say +41 other' — silent is not. Every stage the sub-line does not name by itself is carried in an explicit remainder.""" - tile = _documents_tile(rendered) + tile = _source_tile(rendered) sub = tile["s"] - named = {stage: count for stage, count in STAGE_TALLY.items() if stage in sub} + # NAMED BY ITS WORD, COUNTED BY ITS VALUE (§ 3.4 slice S7): the sub-line + # groups on the snapshot's own `documents[].stage` and renders the facet's + # word for it, so the stage is looked for on screen under the word and the + # tally is still read off the value. + named = {stage: count for stage, count in STAGE_TALLY.items() + if _stage_word(rendered, stage) in sub} unnamed = sum(count for stage, count in STAGE_TALLY.items() if stage not in named) assert named, "the sub-line names no stage at all" for stage, count in named.items(): - assert f"{stage} {count}" in sub, f"{stage} is named with the wrong count: {sub!r}" + word = _stage_word(rendered, stage) + assert f"{word} {count}" in sub, \ + f"{stage} ({word!r}) is named with the wrong count: {sub!r}" if unnamed: assert f"+{unnamed} other" in sub, \ f"{unnamed} documents are dropped without a remainder: {sub!r}" @@ -343,10 +395,11 @@ def test_the_stat_tile_and_the_board_footer_agree(rendered): """The sweep's sharpest complaint was self-contradiction: the pipeline board's footer does this arithmetic completely one tab away. Both now derive from the whole distribution, so the two surfaces cannot disagree.""" - tile = _documents_tile(rendered) + tile = _source_tile(rendered) for stage, count in STAGE_TALLY.items(): - if stage in tile["s"]: - assert f"{stage} {count}" in tile["s"] + word = _stage_word(rendered, stage) + if word in tile["s"]: + assert f"{word} {count}" in tile["s"] assert sum(_subline_numbers(tile["s"])) == sum(STAGE_TALLY.values()) diff --git a/tests/test_doxbench_tile_verbs.py b/tests/test_doxbench_tile_verbs.py index d7fde098..555ced02 100644 --- a/tests/test_doxbench_tile_verbs.py +++ b/tests/test_doxbench_tile_verbs.py @@ -23,6 +23,7 @@ from __future__ import annotations import json +import re import shutil import subprocess @@ -35,6 +36,30 @@ VIEWS = WEB / "views" STYLES = WEB / "styles.css" +# The three sentences `views/doc-wheel.js` states when its Save is unreachable, +# READ FROM THE MODULE rather than quoted here (§ 3.4 slice S7 -- see +# `test_save_is_reachable_only_while_that_documents_buffer_is_dirty`). Each is a +# `const NAME = "…" + "…";` at module scope, so the declaration is found by name +# and its double-quoted segments are joined the way the JavaScript engine joins +# them. +_SAVE_REFUSAL_NAMES = ("SAVE_CONTEXT_ONLY", "SAVE_NOT_LOADED", + "SAVE_NOTHING_TO_DO") + + +def _save_refusals() -> dict[str, str]: + source = (VIEWS / "doc-wheel.js").read_text(encoding="utf-8") + out = {} + for name in _SAVE_REFUSAL_NAMES: + match = re.search(r"^const " + name + r"\s*=\s*(.*?);\s*$", + source, re.MULTILINE | re.DOTALL) + assert match, f"views/doc-wheel.js declares no {name}" + segments = re.findall(r'"((?:[^"\\]|\\.)*)"', match.group(1)) + assert segments, f"{name} is declared with no string literal" + out[name] = "".join(json.loads('"' + segment + '"') + for segment in segments) + return out + + _DOM_SHIM = r""" class Node { constructor(tag) { @@ -331,7 +356,22 @@ def test_save_is_reachable_only_while_that_documents_buffer_is_dirty( the inert control reaches nothing.""" clean = tile_results["cleanSave"] assert clean["disabled"] is True - assert "no unsaved changes" in clean["title"] + # THE MODULE'S OWN REFUSAL, READ FROM THE MODULE (§ 3.4 slice S7). This + # quoted the sentence, and the sentence moved: "no unsaved changes" carries + # `changes`, which `tests/test_web_boundary.py`'s `_STAGE_WORDS` watches, and + # `views/doc-wheel.js` is a class-C file that may carry no governance literal + # (note § 2.2 rule 2, § 4.5 point 4) -- so the slice respelled it. The + # PROPERTY this assertion exists to hold is that the inert Save states THIS + # refusal and not one of its two siblings: a clean buffer is a different + # condition from read-only context and from not-yet-loaded, and answering + # either of those here would be a false statement about the surface's own + # authority. So the three are read where they are declared and compared, + # which holds under any future respelling and under none of the three + # collapsing into another. + refusals = _save_refusals() + assert clean["title"] == refusals["SAVE_NOTHING_TO_DO"] + assert len(set(refusals.values())) == len(refusals), ( + f"two of doc-wheel.js's save refusals are the same sentence: {refusals}") assert tile_results["cleanTileSaved"] == [] diff --git a/tests/test_doxbench_view.py b/tests/test_doxbench_view.py index 1edd9318..93a8102c 100644 --- a/tests/test_doxbench_view.py +++ b/tests/test_doxbench_view.py @@ -2872,12 +2872,27 @@ def test_staging_workbench_composes_the_doxbench_canvas_without_new_transport(): # canvas controller happened to have mounted yet said "no editing capability" # on a console that has one (the docs pane is drawn first). One derivation, two # readers; every clause of it is unchanged and still asserted here. + # + # § 3.4 SLICE S5 moved the FIRST clause's source, not the clause: the gate + # predicate was `createGateLive`, imported from `views/swb-create.js`, and + # that module is openXdox-code's package data now (RULED Q5, openxFactory#656 + # comment `5648044785`). The shell resolves the `gate.workbench.create` + # binding once and reads the same predicate off the contributed column, so + # where no column is contributed -- a student install -- `NO_CREATE_COLUMN` + # answers false and the canvas is withheld with a stated posture instead of + # the whole module failing to load. Every clause of the derivation is + # untouched; what moved is the gate predicate's PROVENANCE. assert "function canvasOffered() {" in view assert ( - "return !!scope && createGateLive(caps) && !sessionSurfaceHidden(caps)" + "return !!scope && createColumn.createGateLive(caps) " + "&& !sessionSurfaceHidden(caps)" in view ) assert "&& !!active?.repository && !!active?.ref;" in view + # …and the column the predicate is read off is the CONTRIBUTED one, with the + # null column as the only fallback — never a re-imported module + assert "const createColumn = gate?.create || NO_CREATE_COLUMN;" in view + assert 'from "./swb-create.js"' not in view # T023 (+T080 client half, 2026-07-30; PIN EVOLUTION T100 P1-A, # 2026-08-01): the composition forwards ONLY the seams app.js injects via @@ -4125,7 +4140,66 @@ def test_the_shell_explains_unavailable_postures_inline(): # every unsaved byte with no dirty check, guard or warning. # ========================================================================== -_SHELL_HARNESS = _EDITOR_DOM_SHIM + r""" +# THE CONTRIBUTED WORKBENCH GATE COLUMN, for the two harnesses that mount the +# whole shell (§ 3.4 slice S5). +# +# `views/swb-create.js` and `views/swb-session.js` left this bundle at slice S5: +# they are openXdox-code's package data, contributed back as the +# `gate.workbench.create` and `gate.workbench.session` bindings (RULED Q5, +# openxFactory#656 comment `5648044785`). `app.js` resolves both once per render +# and hands their DECLARED NAMESPACES (RULED Q2) to `mountStagingWorkbench` as +# `gate.create` and `gate.session`; with no column contributed the shell's null +# columns answer "no gate capability", the canvas is withheld with a stated +# read-only posture, and these harnesses waited forever for textareas that a +# student install is correctly not offered. +# +# A HOST is what contributes a column, and a harness that mounts the shell is +# acting as the host — so it contributes one, exactly as `app.js` does, and the +# composition under test stays the real one. +# +# WHAT THIS COLUMN IS AND IS NOT. `createGateLive` is the one predicate the +# canvas is gated on, and the column answers it off the same `caps` the shell +# already holds — the shape the contributed module states, whose own copy is +# asserted where that module lives. Nothing else RENDERS: the create dialog and +# the session affordance row are the contributed module's surfaces and are +# measured at openXdox-code, which is why `mountCreateAffordance` and +# `openCreateDialog` mount nothing here. The session half instead RECORDS the +# context the shell hands it, because that context carries `onSessionEnded` — +# the seam the contributed affordance row calls when a human confirms an abandon +# — and it is the shell's side of that seam this file exists to measure. +# +# One column per MOUNT and never a shared one: the shell itself takes its columns +# as per-mount locals for exactly this reason (a second workbench must not rebind +# the columns the first one's closures still call through). +_CONTRIBUTED_GATE = r""" +function contributedGate() { + const state = { sessionCtx: null, sessionMounts: 0 }; + return { + state, + column: { + create: { + createGateLive: (c) => !!(c && c.actions && c.actions.gate), + mountCreateAffordance: () => null, + openCreateDialog: () => null, + }, + session: { + createdDocuments: () => [], + documentCreated: () => null, + endedSessions: () => [], + mountSessionAffordances: (host, snapshot, ctx) => { + state.sessionCtx = ctx; + state.sessionMounts += 1; + return null; + }, + openedSessions: () => [], + sessionOpened: () => null, + }, + }, + }; +} +""" + +_SHELL_HARNESS = _EDITOR_DOM_SHIM + _CONTRIBUTED_GATE + r""" import { createRequire } from 'node:module'; globalThis.markdownit = createRequire(import.meta.url)('../vendor/markdown-it.min.js'); @@ -4221,8 +4295,12 @@ class FakeStorage { }, }; +const firstGate = contributedGate(); const workbench = mountStagingWorkbench(container, snapshot, { caps, + // the host's contributed workbench gate column (slice S5) -- see the note + // above `_CONTRIBUTED_GATE` + gate: firstGate.column, fetcher: async () => ({ ok: false }), active: { repository: 'fixture-repo', ref: 'main' }, index: { entries: [] }, @@ -4333,8 +4411,10 @@ class FakeStorage { torn_down: ['worktree', 'registry-entry', 'notebook'], branch_retained: true, record: 'ideation/dashboard/gate-records/draft-topic-x/abandon.yaml', }; +const secondGate = contributedGate(); const second = mountStagingWorkbench(reopened, snapshot, { caps, + gate: secondGate.column, fetcher: async () => ({ status: 200, json: async () => ABANDON_RESULT }), active: { repository: 'fixture-repo', ref: SESSION_REF }, index: { entries: [{ repository: 'fixture-repo', ref: SESSION_REF }] }, @@ -4377,26 +4457,33 @@ class FakeStorage { out.sessionKeyedBeforeEnd = [...storage.values.keys()] .filter((k) => k === SESSION_RECORD_KEY).length; -const abandonBtn = inSecond('swb-sessionbtn') - ? reopened.walk().filter((n) => - String(n.className).split(' ').includes('swb-sessionbtn')) - .find((b) => b.textContent.toLowerCase().includes('abandon')) - : null; -out.abandonOffered = Boolean(abandonBtn && abandonBtn.disabled !== true); -if (abandonBtn) { - await fire(abandonBtn, 'click'); - const reason = reopened.walk().find( - (n) => n.attributes && n.attributes['aria-label'] === 'Reason'); - if (reason) reason.value = ABANDON_RESULT.reason; - const submit = reopened.walk().filter((n) => - String(n.className).split(' ').includes('cbtn')) - .find((b) => b.textContent === 'abandon-session'); - out.abandonSubmitFound = Boolean(submit); - if (submit) await fire(submit, 'click'); +// THE ENDING IS DRIVEN THROUGH THE SEAM THE CONTRIBUTED ROW CALLS (slice S5). +// This clicked `swb-sessionbtn`, filled a `Reason`, clicked `abandon-session` +// and then read a `swb-clanded` report -- four surfaces every one of which is +// rendered by `views/swb-session.js`, openXdox-code's package data since slice +// S5. Driving them here would mean driving a file this bundle does not ship, and +// re-creating them in this harness would mean inventing that column's UI. +// +// They were not deleted: the affordance row's own behaviour travels with the +// module and is measured where the module lives, on the precedent slices S4 and +// S5 already set for five node probes and a dispose tray. What is measured HERE +// is the half this bundle owns and this file is named for -- the SHELL's +// FR-039 clearing -- and the shell exposes it at exactly one place: the +// `onSessionEnded` callback on the context it hands the contributed column. The +// contributed row calls that callback when a human confirms; the harness's own +// column recorded it at mount; so the ending below runs through the real shell +// code, entered by the same call, capturing the dying ref, tearing the canvas +// down and clearing the INJECTED storage seam. +out.sessionSeamMounts = secondGate.state.sessionMounts; +out.sessionSeamOffered = Boolean(secondGate.state.sessionCtx + && typeof secondGate.state.sessionCtx.onSessionEnded === 'function'); +out.endingReported = false; +if (out.sessionSeamOffered) { + // the shell answers the surviving main view, or null for "it did not end" + const survived = await secondGate.state.sessionCtx.onSessionEnded(); for (let i = 0; i < 60; i += 1) await settle(); + out.endingReported = Boolean(survived && survived.snapshot); } -out.endingReported = reopened.walk().some((n) => - String(n.className).split(' ').includes('swb-clanded')); out.sessionKeyedAfterEnd = [...storage.values.keys()] .filter((k) => k === SESSION_RECORD_KEY).length; out.storageKeysAfterEnd = [...storage.values.keys()]; @@ -4410,8 +4497,9 @@ class FakeStorage { const third = document.createElement('div'); const staleTokenDoxbench = { ...doxbench, catalog: async () => ({ failed: 'console_required' }) }; +const thirdGate = contributedGate(); const thirdMount = mountStagingWorkbench(third, snapshot, { - caps, fetcher: async () => ({ ok: false }), + caps, gate: thirdGate.column, fetcher: async () => ({ ok: false }), active: { repository: 'fixture-repo', ref: 'main' }, index: { entries: [] }, doxbench: staleTokenDoxbench, sourceBase: '/source/', edit: null, @@ -4559,16 +4647,25 @@ def test_a_session_end_through_the_mounted_shell_clears_the_working_record( seam — so under any injected storage (this harness's FakeStorage; the editor threads the seam correctly at its own re-key clear, doxbench-editor.js) the ended session's record was never removed. The - abandon here runs through the REAL mounted shell: the affordance row, the - gate verb, the onSessionEnded rebind — and the session-keyed record must - be gone afterwards.""" + abandon here runs through the REAL mounted shell — the shell's own + `onSessionEnded`, entered by the same call the contributed abandon row makes + (§ 3.4 slice S5; see the `_CONTRIBUTED_GATE` note) — and the session-keyed + record must be gone afterwards.""" assert shell_results["sessionKeyedBeforeEnd"] >= 1, ( "precondition: the session's working record was persisted") - assert shell_results["abandonOffered"] is True, ( - "precondition: the mounted shell offered the abandon verb") - assert shell_results["abandonSubmitFound"] is True + # THE PRECONDITIONS ARE THE SEAM'S, not the affordance row's (§ 3.4 slice + # S5): the shell must have mounted the contributed session column and put + # its own `onSessionEnded` on the context it handed down, which is the one + # call the contributed abandon row makes and the only entry point this + # behaviour has. The row itself — offered, reasoned, submitted, reported — + # is `views/swb-session.js`'s and is measured where that module lives. + assert shell_results["sessionSeamMounts"] >= 1, ( + "precondition: the mounted shell never mounted the session column") + assert shell_results["sessionSeamOffered"] is True, ( + "precondition: the shell handed the column no `onSessionEnded` seam") assert shell_results["endingReported"] is True, ( - "precondition: the ending really landed and was reported") + "precondition: the ending really landed — the shell answered with the " + "surviving main view rather than the null that means it did not end") assert shell_results["sessionKeyedAfterEnd"] == 0, ( f"the ended session's record survived in the injected storage: " f"{shell_results['storageKeysAfterEnd']}") @@ -4935,7 +5032,7 @@ def test_the_editors_apply_refusals_carry_their_fixed_codes(editor_results): # controller rather than from `aria-selected`. # ========================================================================== -_SELECTION_HARNESS = _EDITOR_DOM_SHIM + r""" +_SELECTION_HARNESS = _EDITOR_DOM_SHIM + _CONTRIBUTED_GATE + r""" import { createRequire } from 'node:module'; globalThis.markdownit = createRequire(import.meta.url)('../vendor/markdown-it.min.js'); @@ -5002,8 +5099,13 @@ class FakeStorage { chatTurn: async () => ({ ok: false, status: 502, payload: {} }), }; +const selectionGate = contributedGate(); const workbench = mountStagingWorkbench(container, snapshot, { caps, + // the host's contributed workbench gate column (slice S5) -- see the note + // above `_CONTRIBUTED_GATE`. Without one the canvas is correctly withheld and + // this harness waits forever for textareas a student install is not offered. + gate: selectionGate.column, fetcher: async () => ({ ok: false }), active: { repository: 'fixture-repo', ref: 'main' }, index: { entries: [] }, From 569073dc1fd0021cfdd3141f055dcc2f9f111881 Mon Sep 17 00:00:00 2001 From: Brett Heap <1513478+brettheap@users.noreply.github.com> Date: Sun, 13 Sep 2026 22:05:39 +0000 Subject: [PATCH 42/44] =?UTF-8?q?=C2=A7=203.4=20S5,=20leg=20B:=20round=204?= =?UTF-8?q?=20=E2=80=94=20a=20render=20that=20lost=20its=20scope=20while?= =?UTF-8?q?=20resolving=20mounts=20nothing?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Copilot's round-4 finding on `src/opendox/web/app.js`, and it is the same defect round 3 fixed one layer in. The six contributed resolves — `gate.bar`, `gate.lens`, `gate.projects`, `gate.dispose`, `gate.workbench.create`, `gate.workbench.session` — each await a dynamic import, and EVERYTHING after them mounts: the declared namespaces are handed down, `ensurePageOverlayHost()` builds RULED Q8's host, the dispose panel is mounted into it, and every region's core render follows. A repository switch during one of those imports aborts this render's scope, but the old render still resumes after the awaits and mounts its stale snapshot into the page the newer render owns. `mountContributedViews`'s own signal check (round 3) guards the generic pass and cannot undo a shell mount that already happened. The render that lost its scope now stops between the last resolve and the first mount. Its ERROR path stops with it: `reportAssemblyFailure` is a closure of ONE render and the per-region pass hands it rejections that can arrive minutes later, so a refusal from a render the user has already switched away from would have been written over the live render's own surface, describing a column probed for a repository no longer on screen. `tests/test_gate_loop_contributed.py` gains `test_a_render_that_lost_its_scope_while_resolving_mounts_nothing`, which pins the guard's POSITION rather than its presence: after the last of the six resolves, and before the namespace hand-down, the page-overlay host and `mountExplorer` — the three orderings the finding turns on. The boundary census's `app.js` row moves 1584 -> 1602 loc (class-A total 16918 -> 16936) with the reason in its note, as every previous round of this PR recorded its own. Destination gate re-run from openxFactory main @ee251d6c (the landed S5 annotation, #1023): `verify-carve-arrival.py --destination opendox_code --phase B` answers OK — 119 rows arrived, 66 declared-edit rows within their lines, 4 re-destined away and verified vacated. The guard falls INSIDE `web/app.js`'s already-declared edit lines, so no annotation amendment is owed. Lane: openxfactory-4-opendox-extraction Refs opensoft/openxFactory#656 Co-Authored-By: Claude Fable 5.1 --- src/opendox/web/app.js | 18 +++++++++++++++++ tests/fixtures/web_boundary_census.yaml | 6 +++--- tests/test_gate_loop_contributed.py | 27 +++++++++++++++++++++++++ 3 files changed, 48 insertions(+), 3 deletions(-) diff --git a/src/opendox/web/app.js b/src/opendox/web/app.js index 2f50016d..c188eea8 100644 --- a/src/opendox/web/app.js +++ b/src/opendox/web/app.js @@ -1096,6 +1096,17 @@ async function render() { const disposeView = await resolveContributed("gate.dispose"); const createView = await resolveContributed("gate.workbench.create"); const sessionView = await resolveContributed("gate.workbench.session"); + // A RENDER THAT LOST ITS SCOPE WHILE RESOLVING STOPS HERE (Copilot review, + // round 4). Each resolve above may await a dynamic import, so a repository + // switch can begin the next render — and abort this scope — while one is in + // flight. Everything below MOUNTS: the page-overlay host, the dispose panel + // into it, and every region's core render. The generic pass's own signal + // check (round 3) cannot undo a shell mount that already happened, so the + // stale render must not reach one. Stopping here is the same rule every + // listener this render binds already follows — it honours the signal it was + // handed — applied to the one stretch of `render()` that awaits before it + // writes to the page. + if (signal.aborted) return; // THE DECLARED NAMESPACES, handed down already-resolved so that no class-A // or class-C module in this bundle imports a class-B one (§ 4.5 assertion // 3). Each is the binding's DECLARED namespace and nothing wider: RULED Q2 @@ -1563,6 +1574,13 @@ async function render() { // render; the alternative is an unhandled rejection in the console and a tab // that silently lacks its panel. function reportAssemblyFailure(err) { + // AND NOT FROM A RENDER THAT LOST ITS SCOPE (Copilot review, round 4 — the + // error path of the same finding). This closure belongs to ONE render, and + // the per-region pass hands it rejections that can arrive minutes later. A + // refusal from a render the user has already switched away from would be + // written over the live render's own surface, describing a column probed + // for a repository no longer on screen. The live render reports its own. + if (signal.aborted) return; // RE-INSERT THE HOST IF A SUCCESSFUL RENDER ALREADY REMOVED IT (Copilot // round 3). The initial render ends with `status.remove()`, so a refusal // arriving from the per-region pass on a tab's first render — or on any diff --git a/tests/fixtures/web_boundary_census.yaml b/tests/fixtures/web_boundary_census.yaml index af91524e..ada87199 100644 --- a/tests/fixtures/web_boundary_census.yaml +++ b/tests/fixtures/web_boundary_census.yaml @@ -191,15 +191,15 @@ measured_at: "opensoft/openDox-code main a99eba03e31a0aee1cc15a061fdf718cc88a2c4 # shape and `test_the_declared_totals_are_re_derived_from_the_rows` can refuse a # drift between the two. Measured at slice S4 (see the S4 block above). totals: - A: {files: 25, loc: 16918} + A: {files: 25, loc: 16936} B: {files: 1, loc: 73} C: {files: 14, loc: 12008} "?": {files: 1, loc: 1435} files: - path: app.js class: A - loc: 1584 - note: "the shell; its only class-B import was gate.js at :43 (discharged by S3's view registry -- loc 1155 -> 1282 with the registry wiring, S3; 1282 -> 1337 with S4's two new gate bindings and the two mounts it hands down). Carries SIX transitional route-ownership sites, all in the CORE arm's class-B binding entries and all cleared at S5 when those entries leave for contributedViewBindings(): gate.bar's one route (S3) and gate.lens's and gate.projects's two each (S4). Declaring them is RULED Q3 working -- view_extension.py: 'a binding that declares the routes it calls is what makes that ruling checkable instead of aspirational' -- and it is a real breach by assertion 2's own rule only while the entry sits in app.js (class A) rather than in the class-B module (exempt by construction) loc 1492 -> 1549 on this PR's round-2 review (Copilot): RULED Q1's generic pass is no longer ONE pass before every core mount — every `dom` region is a root its core renderer CLEARS, so the pass is run per region by the caller that just rendered it (after mountExplorer, after mountStagingWorkbench, and through the tab router's onRegionRendered hook on a tab's first render), and the Q11 refusal frame became a named function so a late refusal reaches the same surface. loc 1549 -> 1584 on round 3 (Copilot): the per-region pass is bound to THIS render's signal (a pass started from a tab's first render must not mount a stale snapshot into the next render's region), and the Q11 refusal frame re-inserts `#loadstatus` where a successful render removed it, so a late assembly refusal is visible instead of dropped." + loc: 1602 + note: "the shell; its only class-B import was gate.js at :43 (discharged by S3's view registry -- loc 1155 -> 1282 with the registry wiring, S3; 1282 -> 1337 with S4's two new gate bindings and the two mounts it hands down). Carries SIX transitional route-ownership sites, all in the CORE arm's class-B binding entries and all cleared at S5 when those entries leave for contributedViewBindings(): gate.bar's one route (S3) and gate.lens's and gate.projects's two each (S4). Declaring them is RULED Q3 working -- view_extension.py: 'a binding that declares the routes it calls is what makes that ruling checkable instead of aspirational' -- and it is a real breach by assertion 2's own rule only while the entry sits in app.js (class A) rather than in the class-B module (exempt by construction) loc 1492 -> 1549 on this PR's round-2 review (Copilot): RULED Q1's generic pass is no longer ONE pass before every core mount — every `dom` region is a root its core renderer CLEARS, so the pass is run per region by the caller that just rendered it (after mountExplorer, after mountStagingWorkbench, and through the tab router's onRegionRendered hook on a tab's first render), and the Q11 refusal frame became a named function so a late refusal reaches the same surface. loc 1549 -> 1584 on round 3 (Copilot): the per-region pass is bound to THIS render's signal (a pass started from a tab's first render must not mount a stale snapshot into the next render's region), and the Q11 refusal frame re-inserts `#loadstatus` where a successful render removed it, so a late assembly refusal is visible instead of dropped. loc 1584 -> 1602 on round 4 (Copilot): the six contributed resolves each await a dynamic import and EVERYTHING after them mounts (the page-overlay host, the dispose panel into it, every region's core render), so a render whose scope was aborted mid-import now stops between the last resolve and the first mount rather than mounting its stale snapshot into the newer render; its error path stops with it, since a refusal from a render the user has switched away from would otherwise be written over the live render's own surface." - path: index.html class: C diff --git a/tests/test_gate_loop_contributed.py b/tests/test_gate_loop_contributed.py index 11a5e495..9a1ef382 100644 --- a/tests/test_gate_loop_contributed.py +++ b/tests/test_gate_loop_contributed.py @@ -647,6 +647,33 @@ def test_js_an_aborted_render_s_pass_mounts_nothing(tmp_path) -> None: assert result["mounted"] is False +def test_a_render_that_lost_its_scope_while_resolving_mounts_nothing() -> None: + """THE SIX CONTRIBUTED RESOLVES AWAIT DYNAMIC IMPORTS, AND EVERYTHING AFTER + THEM MOUNTS (Copilot review of this PR, round 4). A repository switch during + one of those imports aborts this render's scope, but the old render still + resumes after the awaits — and `mountContributedViews`'s own signal check + (round 3) cannot undo a shell mount that already happened: the page-overlay + host, the dispose panel mounted into it, and every region's core render all + run BEFORE the generic pass. So the render that lost its scope stops between + the last resolve and the first mount, and its error path stops with it.""" + app = _app() + guard = "if (signal.aborted) return;" + assert app.count(guard) == 2, app.count(guard) + stop = app.index(guard) + # AFTER the last of the six resolves — all six are awaited before the stop, + # so none of them is left half-resolved for the next render to inherit + assert app.index('await resolveContributed("gate.workbench.session")') < stop + # and BEFORE anything this render hands down, hosts, mounts or renders + assert stop < app.index("const disposeColumn = disposeView") + assert stop < app.index("const pageOverlayHost = ensurePageOverlayHost();") + assert stop < app.index("mountExplorer(explorerRoot") + # the error path of the same finding: a refusal from a render the user has + # already switched away from is dropped, not written over the live one's + report = app.index("function reportAssemblyFailure(err) {") + assert report < app.index(guard, report) < app.index( + "const host = ensureStatusHost();", report) + + def test_a_late_assembly_refusal_still_has_somewhere_to_be_written() -> None: """`render()` ends with `status.remove()`, and every later render then reads `null` for `#loadstatus` — so a `ViewBindingError` raised by the per-region From 7340fa04cf2436646399575f49294c29bb146b24 Mon Sep 17 00:00:00 2001 From: Brett Heap <1513478+brettheap@users.noreply.github.com> Date: Sun, 13 Sep 2026 22:21:02 +0000 Subject: [PATCH 43/44] =?UTF-8?q?=C2=A7=203.4=20S5,=20leg=20B:=20round=205?= =?UTF-8?q?=20=E2=80=94=20a=20missing=20/capabilities=20payload=20is=20an?= =?UTF-8?q?=20unmet=20requirement,=20not=20a=20bypass?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Copilot's round-5 finding on `src/opendox/web/views/view_extension.js`, and it is this file contradicting its own contract. RULED Q1's generic pass read const unmet = capabilities === undefined ? null : unmetRequirement(binding, capabilities); so a caller that omitted the payload skipped RULED Q4's gate entirely: a REQUIRED binding with an unmet requirement was imported and MOUNTED, which is the one outcome the ruling says must refuse ("unmet + required REFUSES"), and an OPTIONAL one mounted where it should have rendered its region empty with a named reason. The contract it contradicts is fifteen lines into this file's own Q4 block: "A MISSING PAYLOAD IS AN UNMET REQUIREMENT, NOT AN ERROR … `undefined` at the end of the path is the honest answer 'this plane does not offer it', which is exactly what an unmet requirement is." `undefined` for the WHOLE payload says that about every path at once. It is also the posture `probeCapabilityPath` was rewritten into at round 2, when an inherited `toString` met a requirement no payload carries: a gate reading data this shell did not write fails CLOSED. `unmetRequirement(binding, capabilities)` is now evaluated unconditionally. Production behaviour is unchanged — `app.js`'s `mountContributedInto` has always passed `{ capabilities: probedCaps, regions, signal }` — so what this closes is the seam a later caller, a probe or a contributed column's own harness would have found open. `tests/test_gate_loop_contributed.py::test_js_a_pass_with_no_capabilities_payload_ refuses_instead_of_mounting` drives the real registry under node with NO payload: the optional binding is skipped for `requires` with the probed value reported as "not carried at all" rather than as a falsy verdict, and the required one raises `ViewBindingError` naming the binding and the path. Neither is mounted. The test was checked against the OLD read and fails there, so it pins the behaviour rather than restating it. The boundary census's `views/view_extension.js` row moves 841 -> 850 loc (class-A total 16936 -> 16945) with the reason in its note. Destination gate re-run from openxFactory main @ee251d6c: `verify-carve-arrival.py --destination opendox_code --phase B` answers OK with identical figures — 119 rows arrived, 66 declared-edit rows within their lines, 4 re-destined away and verified vacated. `views/view_extension.js` is slice S3's CREATED file and the census fixture is a declared one, so no annotation amendment is owed. Lane: openxfactory-4-opendox-extraction Refs opensoft/openxFactory#656 Co-Authored-By: Claude Fable 5.1 --- src/opendox/web/views/view_extension.js | 13 ++++- tests/fixtures/web_boundary_census.yaml | 6 +-- tests/test_gate_loop_contributed.py | 64 +++++++++++++++++++++++++ 3 files changed, 78 insertions(+), 5 deletions(-) diff --git a/src/opendox/web/views/view_extension.js b/src/opendox/web/views/view_extension.js index 5690d3d8..3f7944cf 100644 --- a/src/opendox/web/views/view_extension.js +++ b/src/opendox/web/views/view_extension.js @@ -787,8 +787,17 @@ export async function mountContributedViews(bindings, snapshot, ctx, options) { // payload is read). if (typeof binding.mount === "function" || binding.control) continue; if (REGIONS[binding.region] !== "dom") continue; - const unmet = capabilities === undefined - ? null : unmetRequirement(binding, capabilities); + // UNCONDITIONALLY, because a missing payload IS an unmet requirement + // (Copilot review of openDox-code#20, round 5). This read used to be + // `capabilities === undefined ? null : unmetRequirement(...)`, which made a + // caller that omits the payload skip the gate entirely — a REQUIRED binding + // with an unmet requirement was imported and mounted, the one outcome RULED + // Q4 says must refuse. It also contradicted this file's own contract + // fifteen lines into the Q4 block above and the fail-closed posture + // `probeCapabilityPath` was rewritten into at round 2: `undefined` at the + // end of a path is the honest answer "this plane does not offer it", and + // `undefined` for the whole payload says it about every path at once. + const unmet = unmetRequirement(binding, capabilities); if (unmet) { // RULED Q4: "unmet + `optional: true` renders the region empty with a // NAMED reason; unmet + required REFUSES." The reason is written INTO the diff --git a/tests/fixtures/web_boundary_census.yaml b/tests/fixtures/web_boundary_census.yaml index ada87199..ef999de0 100644 --- a/tests/fixtures/web_boundary_census.yaml +++ b/tests/fixtures/web_boundary_census.yaml @@ -191,7 +191,7 @@ measured_at: "opensoft/openDox-code main a99eba03e31a0aee1cc15a061fdf718cc88a2c4 # shape and `test_the_declared_totals_are_re_derived_from_the_rows` can refuse a # drift between the two. Measured at slice S4 (see the S4 block above). totals: - A: {files: 25, loc: 16936} + A: {files: 25, loc: 16945} B: {files: 1, loc: 73} C: {files: 14, loc: 12008} "?": {files: 1, loc: 1435} @@ -389,8 +389,8 @@ files: - path: views/view_extension.js class: A - loc: 841 - note: "S3 ADDITION: the client-side view registry -- ViewBinding/collectViewBindings, route_extension.py's shape mirrored in JS (openDox-spec § 4.1). No import, no governance literal; 'gate.bar' in a doc comment is a documentation example of an id, not a route literal, so assertion 2 does not match it. loc 422 -> 455 on this PR's own review round (Copilot, PR #14): a malformed contributed_routes now refuses instead of silently disabling the ownership check, and a rejected dynamic import now refuses naming the binding and module instead of leaking a raw error. loc 455 -> 463 on S4: two new REGIONS entries (lens-gate, repo-projects) for the two new class-B bindings' shell mounts, and the doc comment naming them. loc 463 -> 499 on this fix (Copilot, PR #16, view_extension.js:358): manifestRoutes() and ownershipBreach() now share one shape check, refusing a contributed-routes entry missing a string pattern or carrying a non-boolean is_prefix at whichever of the two sees it first, instead of the array-only check at manifestRoutes() and a truthy is_prefix read at ownershipBreach() silently letting a malformed entry through as if it were not a prefix match. loc 499 -> 757 on S5: RULED Q2's declared namespace and its Proxy, RULED Q4's capability probe and refusal, and RULED Q1's generic mount pass. loc 757 -> 824 on S5's round-2 review (Copilot): probeCapabilityPath reads OWN properties only (an inherited `toString` met a requirement); every DECLARED export is checked callable the way `entry` is (RULED Q2); resolveBinding() resolves the binding a caller already holds, so the generic pass cannot mount a same-id binding from another region; and the pass takes a `regions` bound. loc 824 -> 841 on round 3 (Copilot): mountContributedViews reads an abort `signal` before it considers a binding and again after the import, which are the two moments an abort can land." + loc: 850 + note: "S3 ADDITION: the client-side view registry -- ViewBinding/collectViewBindings, route_extension.py's shape mirrored in JS (openDox-spec § 4.1). No import, no governance literal; 'gate.bar' in a doc comment is a documentation example of an id, not a route literal, so assertion 2 does not match it. loc 422 -> 455 on this PR's own review round (Copilot, PR #14): a malformed contributed_routes now refuses instead of silently disabling the ownership check, and a rejected dynamic import now refuses naming the binding and module instead of leaking a raw error. loc 455 -> 463 on S4: two new REGIONS entries (lens-gate, repo-projects) for the two new class-B bindings' shell mounts, and the doc comment naming them. loc 463 -> 499 on this fix (Copilot, PR #16, view_extension.js:358): manifestRoutes() and ownershipBreach() now share one shape check, refusing a contributed-routes entry missing a string pattern or carrying a non-boolean is_prefix at whichever of the two sees it first, instead of the array-only check at manifestRoutes() and a truthy is_prefix read at ownershipBreach() silently letting a malformed entry through as if it were not a prefix match. loc 499 -> 757 on S5: RULED Q2's declared namespace and its Proxy, RULED Q4's capability probe and refusal, and RULED Q1's generic mount pass. loc 757 -> 824 on S5's round-2 review (Copilot): probeCapabilityPath reads OWN properties only (an inherited `toString` met a requirement); every DECLARED export is checked callable the way `entry` is (RULED Q2); resolveBinding() resolves the binding a caller already holds, so the generic pass cannot mount a same-id binding from another region; and the pass takes a `regions` bound. loc 824 -> 841 on round 3 (Copilot): mountContributedViews reads an abort `signal` before it considers a binding and again after the import, which are the two moments an abort can land. loc 841 -> 850 on round 5 (Copilot): the pass evaluates unmetRequirement UNCONDITIONALLY — it read `capabilities === undefined ? null : unmetRequirement(...)`, so a caller that omitted the payload skipped RULED Q4 entirely and a REQUIRED binding with an unmet requirement was imported and mounted, against this file's own `a missing payload is an unmet requirement` contract and the fail-closed posture probeCapabilityPath took at round 2." - path: views/viewer.js class: A diff --git a/tests/test_gate_loop_contributed.py b/tests/test_gate_loop_contributed.py index 9a1ef382..6d3f488d 100644 --- a/tests/test_gate_loop_contributed.py +++ b/tests/test_gate_loop_contributed.py @@ -476,6 +476,70 @@ def test_js_the_shell_mounts_contributed_dom_bindings_generically(tmp_path) -> N assert "actions.gate" in result["reason"][0][2] +@pytest.mark.skipif(NODE is None, reason="node is not installed") +def test_js_a_pass_with_no_capabilities_payload_refuses_instead_of_mounting( + tmp_path) -> None: + """A MISSING PAYLOAD IS AN UNMET REQUIREMENT (Copilot review of this PR, + round 5). The pass used to read `capabilities === undefined ? null : + unmetRequirement(...)`, so a caller that omitted the payload skipped RULED + Q4's gate entirely: a REQUIRED binding with an unmet requirement was + imported and MOUNTED, the one outcome the ruling says must refuse. That also + contradicted the registry's own contract — `probeCapabilityPath` was + rewritten at round 2 to fail CLOSED, and `undefined` at the end of a path is + the honest answer "this plane does not offer it"; `undefined` for the whole + payload says it about every path at once.""" + web = _temp_bundle(tmp_path, { + "panel.js": "export function mount(host) { host.hit = true; return 'ok'; }\n", + }) + result = _run_node(f""" +import {{ collectViewBindings, mountContributedViews }} + from {json.dumps((web / "views" / "view_extension.js").as_uri())}; +const hosts = {{}}; +const doc = {{ getElementById: (id) => hosts[id] || null, + createElement: () => ({{ attrs: {{}}, textContent: "", + className: "", + setAttribute(k, v) {{ this.attrs[k] = v; }}, + appendChild(c) {{ return c; }} }}) }}; +for (const id of ["view-docs", "explorer-root"]) {{ + hosts[id] = {{ id, hit: false, appendChild() {{}} }}; +}} +const spec = (id, region, extra) => ({{ + id, region, module: "./views/panel.js", entry: "mount", + view_class: "B", requires: ["actions.gate"], ...extra }}); +// an OPTIONAL binding: skipped with a named reason, never imported +const optional = await mountContributedViews( + collectViewBindings([{{ views: () => [ + spec("panel.optional", "view-docs", {{ optional: true }})] }}]), + null, {{}}, {{ document: doc }}); +// a REQUIRED binding: refuses, and the refusal names the path +let refusal = null; +try {{ + await mountContributedViews( + collectViewBindings([{{ views: () => [ + spec("panel.required", "explorer-root", {{ optional: false }})] }}]), + null, {{}}, {{ document: doc }}); +}} catch (err) {{ refusal = {{ name: err.name, message: err.message }}; }} +console.log(JSON.stringify({{ + optional: optional.map((r) => [r.binding.id, r.skipped, r.unmet.path, + r.unmet.value === undefined]), + mountedOptional: hosts["view-docs"].hit, + mountedRequired: hosts["explorer-root"].hit, + refusal, +}})); +""", tmp_path) + # the optional one is SKIPPED for `requires`, with the probed value reported + # as "not carried at all" rather than as a falsy verdict + assert result["optional"] == [["panel.optional", "requires", + "actions.gate", True]] + assert result["mountedOptional"] is False + # the required one REFUSES, and nothing of it was mounted + assert result["refusal"] is not None + assert result["refusal"]["name"] == "ViewBindingError" + assert "panel.required" in result["refusal"]["message"] + assert "actions.gate" in result["refusal"]["message"] + assert result["mountedRequired"] is False + + @pytest.mark.skipif(NODE is None, reason="node is not installed") def test_js_the_pass_mounts_each_binding_s_own_module_not_the_first_id_match( tmp_path) -> None: From 5c6f7629d1791f9043fda557c94554d50664b94c Mon Sep 17 00:00:00 2001 From: Brett Heap <1513478+brettheap@users.noreply.github.com> Date: Sun, 13 Sep 2026 22:47:08 +0000 Subject: [PATCH 44/44] =?UTF-8?q?=C2=A7=203.4=20S5,=20leg=20B:=20round=206?= =?UTF-8?q?=20=E2=80=94=20the=20caller=20that=20resumes=20after=20the=20mo?= =?UTF-8?q?unt=20pass=20stops=20too?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Copilot's round-6 finding on `src/opendox/web/app.js`, and it is round 4's finding one and two awaits further down. Round 4 stopped the render that lost its scope between the six contributed resolves and the first thing it mounts. But RULED Q1's generic pass is itself AWAITED twice more — after `mountExplorer()` and after `mountStagingWorkbench()`, which is where Copilot's round 2 put it — and each of those awaits is a dynamic `import()` per contributed binding: await mountContributedInto(["explorer-root"]); await mountContributedInto(["staging-workbench-root"]); `mountContributedViews`'s own signal check (round 3) stops only ITS mounts. It cannot stop the CALLER that resumes after it, and below those two lines the render keeps writing to the page: the staging workbench overlay, the tab strip, the repository selector, `initAbout`, the global search listener — and finally `status.remove()`, which strips `#loadstatus`. On a repository switch during one of those imports that removal lands on the NEWER render's loading state, and the stale render's workbench and tab strip land on top of the new one's. So the same stop the six resolves got, at both awaits. The rule this file already follows everywhere else — a continuation honours the signal it was handed — applied to the two remaining stretches of `render()` that await before they write. The third call of the same pass, the tab router's `onRegionRendered` hook, is deliberately NOT awaited (it runs from a click handler, round 2), so its scope check is its rejection path's: `reportAssemblyFailure`'s own guard, added at round 4. That is why four `if (signal.aborted) return;` sites is the whole census and not five. `tests/test_gate_loop_contributed.py::test_a_render_that_lost_its_scope_while_ mounting_writes_nothing_below` pins each stop BETWEEN its own pass and the next thing this render writes (`mountStagingWorkbench`, `mountRepoSelector`), and both above `status.remove()`. Round 4's test now pins the census at four rather than two and names what each one is. Both were checked against the OLD read and fail there, so they pin the behaviour rather than restating it. The boundary census's `app.js` row moves 1602 -> 1618 loc (class-A total 16945 -> 16961) with the reason in its note. Destination gate re-run from openxFactory main @ee251d6c (whose carve manifest, admissions and verifier are byte-identical to origin/main @04340d77): `verify-carve- arrival.py --destination opendox_code --phase B` answers OK with identical figures — 119 rows arrived, 52 digests verified, 66 declared-edit rows within their lines, 4 re-destined away and verified vacated. The two guards fall INSIDE `web/app.js`'s already-declared edit lines, so no annotation amendment is owed and #1023 stands as landed. Lane: openxfactory-4-opendox-extraction Refs opensoft/openxFactory#656 Co-Authored-By: Claude Fable 5.1 --- src/opendox/web/app.js | 16 ++++++++++ tests/fixtures/web_boundary_census.yaml | 6 ++-- tests/test_gate_loop_contributed.py | 39 ++++++++++++++++++++++++- 3 files changed, 57 insertions(+), 4 deletions(-) diff --git a/src/opendox/web/app.js b/src/opendox/web/app.js index c188eea8..6925f1c9 100644 --- a/src/opendox/web/app.js +++ b/src/opendox/web/app.js @@ -1205,6 +1205,17 @@ async function render() { // `explorer-root` is rendered: its contributed bindings can mount into a // root that will not be cleared out from under them. await mountContributedInto(["explorer-root"]); + // AND THIS RENDER, TOO, STOPS IF IT LOST ITS SCOPE WHILE MOUNTING (Copilot + // review, round 6 — round 4's finding, one await further down). The pass + // above awaits a dynamic `import()` per contributed binding, so a + // repository switch can abort this scope while one is still in flight. The + // pass's OWN signal check (round 3) stops only ITS mounts; the CALLER that + // resumes here keeps writing to the page — the staging workbench, the tab + // strip, the repository selector — and both paths end at `status.remove()`, + // which would strip the NEWER render's loading state. The cancellation + // guarantee therefore belongs at the resuming caller, not only in the + // callee, exactly as it does after the six resolves above. + if (signal.aborted) return; // When the capability probe reports the notebook action // available, tiles grow an "Open in NotebookLM" affordance; otherwise the // controller's button() returns null and nothing renders — the served/local @@ -1405,6 +1416,11 @@ async function render() { onSessionEnded: resetEndedSession }); // `staging-workbench-root` is rendered: same reading as the explorer's. await mountContributedInto(["staging-workbench-root"]); + // AND THE SAME STOP AFTER THE WORKBENCH'S PASS (Copilot round 6, the + // "analogous await below"): the tab strip, the repository selector and the + // `#loadstatus` removal are all below this line, and a render whose + // repository is no longer on screen must reach none of them. + if (signal.aborted) return; // The wheel's read-only verbs (documents read · clusters lens/canvas): app.js // owns every cross-view jump, so the wheel declares the verb and calls back // here. `tabs` is assigned just below; the callbacks only run on a click. diff --git a/tests/fixtures/web_boundary_census.yaml b/tests/fixtures/web_boundary_census.yaml index ef999de0..70daa35c 100644 --- a/tests/fixtures/web_boundary_census.yaml +++ b/tests/fixtures/web_boundary_census.yaml @@ -191,15 +191,15 @@ measured_at: "opensoft/openDox-code main a99eba03e31a0aee1cc15a061fdf718cc88a2c4 # shape and `test_the_declared_totals_are_re_derived_from_the_rows` can refuse a # drift between the two. Measured at slice S4 (see the S4 block above). totals: - A: {files: 25, loc: 16945} + A: {files: 25, loc: 16961} B: {files: 1, loc: 73} C: {files: 14, loc: 12008} "?": {files: 1, loc: 1435} files: - path: app.js class: A - loc: 1602 - note: "the shell; its only class-B import was gate.js at :43 (discharged by S3's view registry -- loc 1155 -> 1282 with the registry wiring, S3; 1282 -> 1337 with S4's two new gate bindings and the two mounts it hands down). Carries SIX transitional route-ownership sites, all in the CORE arm's class-B binding entries and all cleared at S5 when those entries leave for contributedViewBindings(): gate.bar's one route (S3) and gate.lens's and gate.projects's two each (S4). Declaring them is RULED Q3 working -- view_extension.py: 'a binding that declares the routes it calls is what makes that ruling checkable instead of aspirational' -- and it is a real breach by assertion 2's own rule only while the entry sits in app.js (class A) rather than in the class-B module (exempt by construction) loc 1492 -> 1549 on this PR's round-2 review (Copilot): RULED Q1's generic pass is no longer ONE pass before every core mount — every `dom` region is a root its core renderer CLEARS, so the pass is run per region by the caller that just rendered it (after mountExplorer, after mountStagingWorkbench, and through the tab router's onRegionRendered hook on a tab's first render), and the Q11 refusal frame became a named function so a late refusal reaches the same surface. loc 1549 -> 1584 on round 3 (Copilot): the per-region pass is bound to THIS render's signal (a pass started from a tab's first render must not mount a stale snapshot into the next render's region), and the Q11 refusal frame re-inserts `#loadstatus` where a successful render removed it, so a late assembly refusal is visible instead of dropped. loc 1584 -> 1602 on round 4 (Copilot): the six contributed resolves each await a dynamic import and EVERYTHING after them mounts (the page-overlay host, the dispose panel into it, every region's core render), so a render whose scope was aborted mid-import now stops between the last resolve and the first mount rather than mounting its stale snapshot into the newer render; its error path stops with it, since a refusal from a render the user has switched away from would otherwise be written over the live render's own surface." + loc: 1618 + note: "the shell; its only class-B import was gate.js at :43 (discharged by S3's view registry -- loc 1155 -> 1282 with the registry wiring, S3; 1282 -> 1337 with S4's two new gate bindings and the two mounts it hands down). Carries SIX transitional route-ownership sites, all in the CORE arm's class-B binding entries and all cleared at S5 when those entries leave for contributedViewBindings(): gate.bar's one route (S3) and gate.lens's and gate.projects's two each (S4). Declaring them is RULED Q3 working -- view_extension.py: 'a binding that declares the routes it calls is what makes that ruling checkable instead of aspirational' -- and it is a real breach by assertion 2's own rule only while the entry sits in app.js (class A) rather than in the class-B module (exempt by construction) loc 1492 -> 1549 on this PR's round-2 review (Copilot): RULED Q1's generic pass is no longer ONE pass before every core mount — every `dom` region is a root its core renderer CLEARS, so the pass is run per region by the caller that just rendered it (after mountExplorer, after mountStagingWorkbench, and through the tab router's onRegionRendered hook on a tab's first render), and the Q11 refusal frame became a named function so a late refusal reaches the same surface. loc 1549 -> 1584 on round 3 (Copilot): the per-region pass is bound to THIS render's signal (a pass started from a tab's first render must not mount a stale snapshot into the next render's region), and the Q11 refusal frame re-inserts `#loadstatus` where a successful render removed it, so a late assembly refusal is visible instead of dropped. loc 1584 -> 1602 on round 4 (Copilot): the six contributed resolves each await a dynamic import and EVERYTHING after them mounts (the page-overlay host, the dispose panel into it, every region's core render), so a render whose scope was aborted mid-import now stops between the last resolve and the first mount rather than mounting its stale snapshot into the newer render; its error path stops with it, since a refusal from a render the user has switched away from would otherwise be written over the live render's own surface. loc 1602 -> 1618 on round 6 (Copilot): round 4's finding one and two awaits further down -- the generic mount pass is AWAITED after `mountExplorer` and after `mountStagingWorkbench`, and `mountContributedViews`'s own signal check (round 3) stops only ITS mounts, never the caller that resumes; below those two awaits sit the staging workbench, the tab strip, the repository selector and `status.remove()`, which would have stripped the NEWER render's loading state, so the resuming caller now stops at both." - path: index.html class: C diff --git a/tests/test_gate_loop_contributed.py b/tests/test_gate_loop_contributed.py index 6d3f488d..c60129a5 100644 --- a/tests/test_gate_loop_contributed.py +++ b/tests/test_gate_loop_contributed.py @@ -722,7 +722,11 @@ def test_a_render_that_lost_its_scope_while_resolving_mounts_nothing() -> None: the last resolve and the first mount, and its error path stops with it.""" app = _app() guard = "if (signal.aborted) return;" - assert app.count(guard) == 2, app.count(guard) + # FOUR scope checks, and the census of them is the point: the stop below, + # the two after the generic pass's awaits (round 6, pinned by the test + # under this one), and the error path's. Every other await in `render()` + # belongs to a human-driven callback, not to the initial mount path. + assert app.count(guard) == 4, app.count(guard) stop = app.index(guard) # AFTER the last of the six resolves — all six are awaited before the stop, # so none of them is left half-resolved for the next render to inherit @@ -738,6 +742,39 @@ def test_a_render_that_lost_its_scope_while_resolving_mounts_nothing() -> None: "const host = ensureStatusHost();", report) +def test_a_render_that_lost_its_scope_while_mounting_writes_nothing_below() -> None: + """THE GENERIC PASS IS AWAITED TWICE MORE, AND EVERYTHING BELOW EACH AWAIT + WRITES TO THE PAGE (Copilot review of this PR, round 6 — round 4's finding, + one and two awaits further down). `mountContributedInto` awaits a dynamic + `import()` per contributed binding, and `mountContributedViews`'s own signal + check (round 3) stops only ITS mounts, never the CALLER that resumes after + it. Below the explorer's pass sit the staging workbench, the tab strip and + the repository selector; below the workbench's pass sit the last two of + those — and both paths end at `status.remove()`, which would strip the NEWER + render's loading state. So the resuming caller stops, at BOTH awaits.""" + app = _app() + guard = "if (signal.aborted) return;" + explorer = app.index('await mountContributedInto(["explorer-root"]);') + workbench = app.index( + 'await mountContributedInto(["staging-workbench-root"]);') + after_explorer = app.index(guard, explorer) + after_workbench = app.index(guard, workbench) + # each stop sits between its own pass and the next thing this render writes + assert explorer < after_explorer < workbench, ( + "the explorer pass's scope check is missing, or falls after the " + "workbench's own await") + assert after_explorer < app.index("mountStagingWorkbench(", explorer) + assert workbench < after_workbench < app.index("mountRepoSelector(", + workbench) + # and both are above the one write that would strip the LIVE render's + # loading state rather than this dead one's + assert after_workbench < app.index("status.remove();", workbench) + # the THIRD call of the same pass is deliberately un-awaited — it runs from + # the tab router's click handler — so its scope check is its rejection + # path's, which is the round-4 guard at the top of the refusal frame + assert "mountContributedInto([region]).catch(reportAssemblyFailure);" in app + + def test_a_late_assembly_refusal_still_has_somewhere_to_be_written() -> None: """`render()` ends with `status.remove()`, and every later render then reads `null` for `#loadstatus` — so a `ViewBindingError` raised by the per-region