You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@juneau.apache.org by ja...@apache.org on 2026/09/06 20:25:37 UTC

(juneau) branch master updated: WORK-J0522d: Wire the host enrolment walk into the real card/panel/detail callers (juneau-cards.js enhanceOneCard->regions.enrolIn, new juneau-pages.js activatePanelRegions, juneau-views.js expandDetailRow), the 5-row removal-path teardown table incl. B3 teardownTable reinit, and the barrier ready()/registerRuntime() protocol.

This is an automated email from the ASF dual-hosted git repository.

jamesbognar pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/juneau.git


The following commit(s) were added to refs/heads/master by this push:
     new fef7ddc26f WORK-J0522d: Wire the host enrolment walk into the real card/panel/detail callers (juneau-cards.js enhanceOneCard->regions.enrolIn, new juneau-pages.js activatePanelRegions, juneau-views.js expandDetailRow), the 5-row removal-path teardown table incl. B3 teardownTable reinit, and the barrier ready()/registerRuntime() protocol.
fef7ddc26f is described below

commit fef7ddc26f7191b4e315049998bd3b5b5f7685cd
Author: James Bognar <ja...@apache.org>
AuthorDate: Sun Sep 6 16:25:11 2026 -0400

    WORK-J0522d: Wire the host enrolment walk into the real card/panel/detail callers (juneau-cards.js enhanceOneCard->regions.enrolIn, new juneau-pages.js activatePanelRegions, juneau-views.js expandDetailRow), the 5-row removal-path teardown table incl. B3 teardownTable reinit, and the barrier ready()/registerRuntime() protocol.
---
 .../org/apache/juneau/views/juneau-pages.js        |  83 +++++++-
 .../org/apache/juneau/views/juneau-views.js        |  52 ++++-
 .../rest/server/views/JuneauPagesJs_Test.java      |  54 +++++
 .../views/ViewsJs_RegionEnrolmentWalk_Test.java    | 218 +++++++++++++++++++++
 .../org/apache/juneau/widgets/juneau-cards.js      | 112 +++++++++--
 .../rest/server/widgets/WidgetsJs_Cards_Test.java  |  50 +++++
 .../src/test/js/cards-browser.cjs                  |  86 +++++++-
 7 files changed, 641 insertions(+), 14 deletions(-)

diff --git a/juneau-rest/juneau-rest-server-views/src/main/resources/org/apache/juneau/views/juneau-pages.js b/juneau-rest/juneau-rest-server-views/src/main/resources/org/apache/juneau/views/juneau-pages.js
index 5ca8f4bcc8..52cf4cfd84 100644
--- a/juneau-rest/juneau-rest-server-views/src/main/resources/org/apache/juneau/views/juneau-pages.js
+++ b/juneau-rest/juneau-rest-server-views/src/main/resources/org/apache/juneau/views/juneau-pages.js
@@ -58,6 +58,18 @@
 
 	const NS = window.JuneauViews = window.JuneauViews || {};
 
+	/**
+	 * The region container marker - MUST equal RegionDef's REGION_ATTR constant on the server
+	 * (juneau-rest-server-views).  Duplicated locally per juneau-views.js's own PANEL_SELECTOR-style convention
+	 * rather than reaching into juneau-regions.js's export for a string literal it already carries: this file may
+	 * run before that module's IIFE has (this file's own docstring already documents the analogous case for
+	 * juneau-views.js's `NS.init` not yet existing).
+	 */
+	const REGION_MARKER = "data-juneau-region";
+
+	/** This runtime's own name, for the barrier's ready()/registerRuntime() protocol and for a missing-runtime error. */
+	const RUNTIME_TOKEN = "juneau-pages.js";
+
 	// ==================================================================================================================
 	// PURE LOGIC LAYER  (no DOM)
 	// ==================================================================================================================
@@ -196,6 +208,63 @@
 		});
 	}
 
+	/**
+	 * Design §9.3's missing-runtime failure mode, at the panel enrolment site: a `[data-juneau-region]` node with
+	 * no `juneau-regions.js` loaded to run it renders loud, not blank - mirrors juneau-cards.js's own
+	 * `reportRegionsWithoutRuntime`, duplicated rather than shared for the same reason `activatePanelViews`'s
+	 * `warn()` helper above isn't shared with juneau-cards.js: no cross-module JS dependency exists to carry it.
+	 */
+	function reportRegionsWithoutRuntime(nodes) {
+		Array.prototype.forEach.call(nodes, function (el) {
+			error(RUNTIME_TOKEN + ": juneau-regions.js is not loaded; the region '"
+				+ (el.getAttribute(REGION_MARKER) || "") + "' cannot populate.");
+			el.setAttribute("data-juneau-region-state", "error");
+			const message = "This region could not be populated: juneau-regions.js is not loaded.";
+			const render = NS.init?.renderAsyncStatus;
+			if (typeof render === "function") render(el, "error", message);
+			else el.textContent = message;
+		});
+	}
+
+	/**
+	 * Region-container equivalent of `activatePanelViews` above (design §9.3's round-4 fix, caller #2 of 3): walks
+	 * `panel` for `[data-juneau-region]` nodes and enrols each one exactly once via `initRegion` directly (NOT
+	 * `enrolIn`, which re-derives its own `querySelectorAll` from `panel` - calling it here would re-walk a set this
+	 * function has already filtered, undoing the filtering).  This existed because the ORIGINAL two call sites -
+	 * `initCard` (never reached by a static, action-less card) and `activatePanelViews` (a table-only walk) - never
+	 * covered a table-free panel's region at all; this function IS the fix, not a supplement to it.
+	 *
+	 * Four exclusions decide ownership, the first three mirroring `activatePanelViews`'s own table exclusions
+	 * exactly (same rationale, same selectors, applied to `[data-juneau-region]` instead of
+	 * `table[data-juneau-view]`):
+	 *   1. `closest(PANEL_SELECTOR) !== panel` - a region belonging to a nested sub-panel is that sub-panel's own;
+	 *      it enrols when ITS OWN panel is activated, not when its sub-tab-agnostic ancestor is.
+	 *   2. `closest("[data-juneau-nested]")` - a region inside a nested/read-only table body is that table's own
+	 *      lazy-init concern, not this runtime's.
+	 *   3. `closest(".juneau-view-detail-panel")` - a row-detail panel's regions are the detail expander's
+	 *      (juneau-views.js's `expandDetailRow`), enrolled/torn-down on that panel's own open/close.
+	 *   4. `closest("[data-juneau-card]")` - the new exclusion this fix adds: a card-body region is
+	 *      juneau-cards.js's own (`enhanceOneCard`'s `enrolIn(card)` call); a page composing cards inside a tab
+	 *      must not double-enrol what the cards runtime already owns.  `initRegion` is idempotent per node, so a
+	 *      double-enrol would be harmless in isolation - the exclusion is about OWNERSHIP (which runtime's removal
+	 *      path tears it down), not merely about avoiding a redundant call.
+	 */
+	function activatePanelRegions(panel) {
+		const api = window.JuneauViews?.regions;
+		const nodes = panel.querySelectorAll("[" + REGION_MARKER + "]");
+		if (!api) {
+			if (nodes.length) reportRegionsWithoutRuntime(nodes);
+			return;
+		}
+		Array.prototype.forEach.call(nodes, function (el) {
+			if (el.closest(PANEL_SELECTOR) !== panel) return;
+			if (el.closest("[data-juneau-nested]")) return;
+			if (el.closest(".juneau-view-detail-panel")) return;
+			if (el.closest("[data-juneau-card]")) return;
+			api.initRegion(el);
+		});
+	}
+
 	/** Applies the resolved (tabId, subtabId) to `root`: toggles active classes, shows/hides panels, lazy-inits. */
 	function showActive(root, tabId, subtabId) {
 		const tabs = root.querySelectorAll(".jc-tab");
@@ -215,7 +284,10 @@
 		Array.prototype.forEach.call(panels, function (p) {
 			const active = panelMatches(p, tabId, subtabId);
 			p.classList.toggle("jc-active", active);
-			if (active) activatePanelViews(p);
+			if (active) {
+				activatePanelViews(p);
+				activatePanelRegions(p);
+			}
 		});
 	}
 
@@ -253,6 +325,10 @@
 	function initAllPages() {
 		const pages = document.querySelectorAll("[data-juneau-page]");
 		Array.prototype.forEach.call(pages, function (p) { initPage(p); });
+
+		// Design §10.11.1 rule 4: every page's synchronous showActive()->activatePanelRegions() walk above has
+		// already run by the time this line executes, so this runtime can truthfully declare its walk complete.
+		window.JuneauViews?.regions?.ready?.(RUNTIME_TOKEN);
 	}
 
 	// ==================================================================================================================
@@ -265,9 +341,14 @@
 		findById: findById,
 		resolveInitial: resolveInitial,
 		hashFor: hashFor,
+		activatePanelRegions: activatePanelRegions,
 		initAllPages: initAllPages
 	};
 
+	// Design §10.11.1 rule 4: presence is established by the asset loading and registering itself at parse time.
+	// Guarded so a page that never loads juneau-regions.js (a pages-only page with no region on it) loses nothing.
+	window.JuneauViews?.regions?.registerRuntime?.(RUNTIME_TOKEN);
+
 	if (document.readyState === "loading") {
 		document.addEventListener("DOMContentLoaded", initAllPages);
 	} else {
diff --git a/juneau-rest/juneau-rest-server-views/src/main/resources/org/apache/juneau/views/juneau-views.js b/juneau-rest/juneau-rest-server-views/src/main/resources/org/apache/juneau/views/juneau-views.js
index 14f88aace1..96e6195c73 100644
--- a/juneau-rest/juneau-rest-server-views/src/main/resources/org/apache/juneau/views/juneau-views.js
+++ b/juneau-rest/juneau-rest-server-views/src/main/resources/org/apache/juneau/views/juneau-views.js
@@ -129,6 +129,12 @@
 	 */
 	const CARD_MARKER = "data-juneau-card";
 
+	// The region container marker - MUST equal RegionDef's REGION_ATTR constant, and juneau-cards.js's/
+	// juneau-pages.js's own REGION_MARKER copies, on the server and in each sibling asset respectively.  Used only
+	// at the detail-expand enrolment call site below (expandDetailRow); this file is not itself a region-hosting
+	// runtime and never registers with the ready()/registerRuntime() barrier.
+	const REGION_MARKER = "data-juneau-region";
+
 	// DT1 table-overflow-wrap discipline: the DT1 "Approach B" single-node wrap (the DT2 dogfood path uses the
 	// CSS-only "Approach D" overflow box on the flex .dt-layout-cell instead - see juneau-views.css).
 	const TABLE_SCROLL_CLASS = "juneau-view-table-scroll";
@@ -2532,6 +2538,11 @@
 		if (!parentTr) return true;
 		const row = dt.row(parentTr);
 		if (row?.child?.isShown()) {
+			// Removal path 1/5 (design §9.3's teardown table): tear down any enrolled regions in this panel
+			// BEFORE the child row DOM is discarded, same reason as the nested-DataTables teardown right below -
+			// a torn-down region's in-flight fetch is aborted and its bus subscription released while the panel
+			// is still attached, never left to leak with the detached nodes.
+			NS.regions?.teardownRegionsIn(panel);
 			// Destroy any nested DataTables in this panel BEFORE the child row DOM is discarded (otherwise
 			// their listeners/timers leak with the detached nodes).
 			teardownNestedTables(panel);
@@ -2573,8 +2584,11 @@
 		const row = dt.row(tr);
 		if (!row || !row.length) return;
 		if (row.child.isShown()) {
-			// Tear down nested DataTables before hiding (their child-row DOM is about to be detached).
+			// Removal path 2/5: tear down enrolled regions + nested DataTables before hiding (their child-row
+			// DOM is about to be detached).  Region teardown ordered first, matching handleDetailSafeCollapseClick's
+			// own collapse branch above.
 			if (tr._juneauDetailPanel) {
+				NS.regions?.teardownRegionsIn(tr._juneauDetailPanel);
 				teardownNestedTables(tr._juneauDetailPanel);
 				teardownDetailBarSlot(tr._juneauDetailPanel);
 			}
@@ -2608,7 +2622,9 @@
 		openRows.forEach(function (tr) {
 			const row = dt.row(tr);
 			if (!row || !row.length || !row.child.isShown()) return;
+			// Removal path 3/5: same region-teardown-first ordering as toggleDetailRow's own collapse branch.
 			if (tr._juneauDetailPanel) {
+				NS.regions?.teardownRegionsIn(tr._juneauDetailPanel);
 				teardownNestedTables(tr._juneauDetailPanel);
 				teardownDetailBarSlot(tr._juneauDetailPanel);
 			}
@@ -3074,6 +3090,24 @@
 		});
 	}
 
+	/**
+	 * Design §9.3's missing-runtime failure mode, at the detail-panel enrolment site: a `[data-juneau-region]`
+	 * node with no `juneau-regions.js` loaded to run it renders loud, not blank - mirrors juneau-cards.js's and
+	 * juneau-pages.js's own `reportRegionsWithoutRuntime`, duplicated for the same reason those two don't share
+	 * it with each other: no cross-module JS dependency exists to carry it, and this file itself uses its own
+	 * already-local `renderAsyncStatus` rather than reaching through `NS.init` for a function this very module
+	 * defines.
+	 */
+	function reportRegionsWithoutRuntime(nodes) {
+		for (const el of nodes) {
+			if (window.console && console.error)
+				console.error("juneau-views.js: juneau-regions.js is not loaded; the region '"
+					+ (el.getAttribute(REGION_MARKER) || "") + "' cannot populate.");
+			el.setAttribute("data-juneau-region-state", "error");
+			renderAsyncStatus(el, "error", "This region could not be populated: juneau-regions.js is not loaded.");
+		}
+	}
+
 	function expandDetailRow(table, ctx, viewDef, tpl, dt, tr, row) {
 		const gen = (ctx._detailGeneration.get(tr) || 0) + 1;
 		ctx._detailGeneration.set(tr, gen);
@@ -3115,6 +3149,12 @@
 		notifyPollPausedChange(ctx);
 		// Enhance-on-insert: only now is the clone in the document, so chrome can find and enhance its bar slot.
 		enhanceChromeInPanel(panel);
+		// Enrolment call site 3/3 (design §9.3): only now is the clone in the document, so a detail-panel region
+		// can find its host and its data-* declaration.  Runtime-agnostic like juneau-cards.js's own
+		// `enrolCardRegions`: `enrolIn` itself is idempotent per node and a no-op walk when the template carried
+		// no region at all, so this call is unconditional rather than gated on the template being known to have one.
+		if (NS.regions) NS.regions.enrolIn(panel);
+		else reportRegionsWithoutRuntime(panel.querySelectorAll("[" + REGION_MARKER + "]"));
 
 		function stillCurrent() {
 			return ctx._detailGeneration.get(tr) === gen && row.child.isShown();
@@ -5605,6 +5645,11 @@
 	}
 
 	function teardownTable(table, ctx) {
+		// Removal path 5/5 (B3, design §9.3): the reinit/destroy path.  First and unguarded - unlike the preDraw.dt
+		// guard below, there is no in-flight redraw to protect against here, and every region this table (or any
+		// open row-detail panel beneath it) still owns must be torn down before the DataTable instance is
+		// destroyed a few lines down, discarding the DOM structure regions were enrolled against.
+		NS.regions?.teardownRegionsIn(table);
 		if (ctx._pollTimers) {
 			ctx._pollTimers.forEach(function (id) { clearInterval(id); });
 			ctx._pollTimers = [];
@@ -5800,6 +5845,11 @@
 			// tearing down now would leave the still-open panel holding dead nested tables.  Same predicate the
 			// cancelling handler uses, so it does not matter which of the two jQuery runs first.
 			if (ctx._shouldCancelPollDraw?.()) return;
+			// Removal path 4/5: enrolled regions inside a still-open detail panel share the nested-table's own
+			// fate here - a redraw this handler does NOT cancel is about to discard the child-row DOM, so any
+			// region living in it is torn down in the same guarded branch, right before the nested-table teardown
+			// it has always run alongside.
+			NS.regions?.teardownRegionsIn(table);
 			teardownNestedTables(table);
 		});
 	}
diff --git a/juneau-rest/juneau-rest-server-views/src/test/java/org/apache/juneau/rest/server/views/JuneauPagesJs_Test.java b/juneau-rest/juneau-rest-server-views/src/test/java/org/apache/juneau/rest/server/views/JuneauPagesJs_Test.java
index 511007c305..c00f945649 100644
--- a/juneau-rest/juneau-rest-server-views/src/test/java/org/apache/juneau/rest/server/views/JuneauPagesJs_Test.java
+++ b/juneau-rest/juneau-rest-server-views/src/test/java/org/apache/juneau/rest/server/views/JuneauPagesJs_Test.java
@@ -165,4 +165,58 @@ class JuneauPagesJs_Test extends TestBase {
 		assertTrue(body.contains("querySelectorAll(\"[data-juneau-page]\")"), body);
 		assertTrue(body.contains("DOMContentLoaded"), body);
 	}
+
+	//------------------------------------------------------------------------------------------------------------------
+	// WORK-J0522d: activatePanelRegions - real caller #2 of the design §9.3 enrolment walk, + the barrier's
+	// ready()/registerRuntime() protocol.  Source-shape only, matching this file's existing pattern for this
+	// module (activatePanelViews above gets the same treatment); the behavioral proof of the walk itself against
+	// the real juneau-regions.js runtime lives in the views module's Regions_* Node-harness tests.
+	//------------------------------------------------------------------------------------------------------------------
+
+	@Test void c01_activatePanelRegionsWalksRegionMarkerAndCallsInitRegionDirectly() throws Exception {
+		var body = pagesJs();
+		var fn = functionBody(body, "activatePanelRegions");
+		assertTrue(fn.contains("querySelectorAll(\"[\" + REGION_MARKER + \"]\")"), fn);
+		// initRegion, NOT enrolIn - enrolIn re-derives its own querySelectorAll from the scope, which would re-walk
+		// (and un-filter) the set this function has already applied its four exclusions to.
+		assertTrue(fn.contains("api.initRegion(el)"), fn);
+		assertFalse(fn.contains("enrolIn("), fn);
+	}
+
+	@Test void c02_activatePanelRegionsAppliesAllFourOwnershipExclusions() throws Exception {
+		var body = pagesJs();
+		var fn = functionBody(body, "activatePanelRegions");
+		// 1: nested sub-panel ownership (same selector activatePanelViews's own table exclusion uses).
+		assertTrue(fn.contains("el.closest(PANEL_SELECTOR) !== panel"), fn);
+		// 2: a nested/read-only table body's own region.
+		assertTrue(fn.contains("el.closest(\"[data-juneau-nested]\")"), fn);
+		// 3: a row-detail panel's region is the detail expander's, not this runtime's.
+		assertTrue(fn.contains("el.closest(\".juneau-view-detail-panel\")"), fn);
+		// 4 (the NEW exclusion this fix adds): a card-body region is juneau-cards.js's own.
+		assertTrue(fn.contains("el.closest(\"[data-juneau-card]\")"), fn);
+	}
+
+	@Test void c03_activatePanelRegionsReportsLoudWhenRuntimeMissing() throws Exception {
+		var body = pagesJs();
+		var fn = functionBody(body, "activatePanelRegions");
+		assertTrue(fn.contains("reportRegionsWithoutRuntime(nodes)"), fn);
+		var report = functionBody(body, "reportRegionsWithoutRuntime");
+		assertTrue(report.contains("juneau-regions.js is not loaded"), report);
+		assertTrue(report.contains("data-juneau-region-state"), report);
+	}
+
+	@Test void c04_showActiveCallsActivatePanelRegionsAlongsideActivatePanelViews() throws Exception {
+		var body = pagesJs();
+		var fn = functionBody(body, "showActive");
+		assertTrue(fn.contains("activatePanelViews(p)"), fn);
+		assertTrue(fn.contains("activatePanelRegions(p)"), fn);
+		assertTrue(body.contains("activatePanelRegions: activatePanelRegions"), body);
+	}
+
+	@Test void c05_barrierProtocolWired() throws Exception {
+		var body = pagesJs();
+		assertTrue(body.contains("RUNTIME_TOKEN = \"juneau-pages.js\""), body);
+		assertTrue(body.contains("registerRuntime?.(RUNTIME_TOKEN)"), body);
+		assertTrue(body.contains("ready?.(RUNTIME_TOKEN)"), body);
+	}
 }
diff --git a/juneau-rest/juneau-rest-server-views/src/test/java/org/apache/juneau/rest/server/views/ViewsJs_RegionEnrolmentWalk_Test.java b/juneau-rest/juneau-rest-server-views/src/test/java/org/apache/juneau/rest/server/views/ViewsJs_RegionEnrolmentWalk_Test.java
new file mode 100644
index 0000000000..94e4c78460
--- /dev/null
+++ b/juneau-rest/juneau-rest-server-views/src/test/java/org/apache/juneau/rest/server/views/ViewsJs_RegionEnrolmentWalk_Test.java
@@ -0,0 +1,218 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.juneau.rest.server.views;
+
+import static java.nio.charset.StandardCharsets.*;
+import static org.junit.jupiter.api.Assertions.*;
+
+import java.io.*;
+
+import org.apache.juneau.*;
+import org.junit.jupiter.api.*;
+
+/**
+ * WORK-J0522d: source-shape pins for {@code juneau-views.js}'s ONE real enrolment call site (caller #3 of 3,
+ * {@code expandDetailRow}) and all FIVE region removal paths (design §9.3's teardown table, including the B3
+ * {@code teardownTable} reinit row) - the {@code juneau-views.js} slice of the design's round-4 region-enrolment
+ * fix.
+ *
+ * <p>Mirrors {@link ViewsJs_Reinit_Test}'s own balanced-brace {@code functionBody} extractor and its
+ * source-shape-pin style for {@code teardownTable} et al., rather than driving a full DataTables+row-detail
+ * click simulation through a from-scratch fake (that harness - see {@code row-detail.cjs} - is 1300+ lines for
+ * ONE subject): a source-shape pin on the exact call, its argument, and its ordering relative to the
+ * already-tested neighboring call it was added beside is what actually catches a future edit deleting or
+ * misordering one of these five calls, and is far cheaper to keep correct than a sixth full DOM harness.
+ *
+ * <p>The real BEHAVIORAL proof that {@code enrolIn}/{@code teardownRegionsIn} do what they claim against a live
+ * region lives in the {@code Regions_*} Node-harness tests (loading the real {@code juneau-regions.js}); this
+ * class only proves that {@code juneau-views.js} calls them, with the right argument, in the right place.
+ */
+class ViewsJs_RegionEnrolmentWalk_Test extends TestBase {
+
+	private static String viewsJs() throws IOException {
+		try (var in = ViewsMixin.class.getResourceAsStream(ViewsMixin.VIEWS_JS_RESOURCE)) {
+			assertNotNull(in, () -> "missing classpath resource: " + ViewsMixin.VIEWS_JS_RESOURCE);
+			return new String(in.readAllBytes(), UTF_8);
+		}
+	}
+
+	private static String regionsJs() throws IOException {
+		try (var in = ViewsMixin.class.getResourceAsStream(ViewsMixin.REGIONS_JS_RESOURCE)) {
+			assertNotNull(in, () -> "missing classpath resource: " + ViewsMixin.REGIONS_JS_RESOURCE);
+			return new String(in.readAllBytes(), UTF_8);
+		}
+	}
+
+	/** Balanced-brace extractor (nested functions/object literals would fool a plain {@code \n\t}} scan). */
+	private static String functionBody(String body, String signature) {
+		var start = body.indexOf(signature);
+		assertTrue(start >= 0, () -> "'" + signature + "' not found:\n" + body);
+		var i = body.indexOf('{', start);
+		assertTrue(i >= 0, () -> "'" + signature + "' has no opening brace:\n" + body);
+		var depth = 0;
+		var j = i;
+		for (; j < body.length(); j++) {
+			var c = body.charAt(j);
+			if (c == '{') {
+				depth++;
+			} else if (c == '}') {
+				depth--;
+				if (depth == 0) { j++; break; }
+			} else if (c == '"' || c == '\'' || c == '`') {
+				var quote = c;
+				j++;
+				while (j < body.length() && body.charAt(j) != quote) { if (body.charAt(j) == '\\') j++; j++; }
+			} else if (c == '/' && j + 1 < body.length() && body.charAt(j + 1) == '/') {
+				while (j < body.length() && body.charAt(j) != '\n') j++;
+			} else if (c == '/' && j + 1 < body.length() && body.charAt(j + 1) == '*') {
+				j = body.indexOf("*/", j) + 1;
+			}
+		}
+		return body.substring(start, j);
+	}
+
+	//------------------------------------------------------------------------------------------------------------------
+	// a) The REGION_MARKER copy - a JS-to-JS pin against juneau-regions.js's own REGION_ATTR, since RegionDef has
+	// no emitter yet (that's out of this narrowed slice's scope) to pin a Java constant against.
+	//------------------------------------------------------------------------------------------------------------------
+
+	@Test void a01_regionMarkerConstantMatchesRegionsJsOwnAttr() throws Exception {
+		var views = viewsJs();
+		var regions = regionsJs();
+		assertTrue(views.contains("const REGION_MARKER = \"data-juneau-region\";"), views);
+		assertTrue(regions.contains("const REGION_ATTR = \"data-juneau-region\";"), regions);
+	}
+
+	//------------------------------------------------------------------------------------------------------------------
+	// b) Enrolment call site 3/3: expandDetailRow, right after the existing enhance-on-insert call.
+	//------------------------------------------------------------------------------------------------------------------
+
+	@Test void b01_expandDetailRow_enrolsRegionsRightAfterEnhanceChromeInPanel() throws Exception {
+		var fn = functionBody(viewsJs(), "function expandDetailRow(");
+		var chromeIdx = fn.indexOf("enhanceChromeInPanel(panel)");
+		var enrolIdx = fn.indexOf("NS.regions.enrolIn(panel)");
+		assertTrue(chromeIdx >= 0, fn);
+		assertTrue(enrolIdx > chromeIdx, "enrolIn(panel) must run AFTER the panel is enhanced-on-insert:\n" + fn);
+		assertTrue(fn.contains("if (NS.regions) NS.regions.enrolIn(panel);"), fn);
+		assertTrue(fn.contains("reportRegionsWithoutRuntime(panel.querySelectorAll(\"[\" + REGION_MARKER + \"]\"))"), fn);
+	}
+
+	//------------------------------------------------------------------------------------------------------------------
+	// c) Removal path 1/5: handleDetailSafeCollapseClick's collapse branch.
+	//------------------------------------------------------------------------------------------------------------------
+
+	@Test void c01_handleDetailSafeCollapseClick_tearsDownRegionsBeforeNestedTablesAndHide() throws Exception {
+		var fn = functionBody(viewsJs(), "function handleDetailSafeCollapseClick(");
+		var teardownRegionsIdx = fn.indexOf("NS.regions?.teardownRegionsIn(panel)");
+		var teardownNestedIdx = fn.indexOf("teardownNestedTables(panel)");
+		var hideIdx = fn.indexOf("row.child.hide()");
+		assertTrue(teardownRegionsIdx >= 0, fn);
+		assertTrue(teardownRegionsIdx < teardownNestedIdx, fn);
+		assertTrue(teardownNestedIdx < hideIdx, fn);
+	}
+
+	//------------------------------------------------------------------------------------------------------------------
+	// d) Removal path 2/5: toggleDetailRow's collapse branch.
+	//------------------------------------------------------------------------------------------------------------------
+
+	@Test void d01_toggleDetailRow_tearsDownRegionsBeforeNestedTablesAndHide() throws Exception {
+		var fn = functionBody(viewsJs(), "function toggleDetailRow(");
+		var teardownRegionsIdx = fn.indexOf("NS.regions?.teardownRegionsIn(tr._juneauDetailPanel)");
+		var teardownNestedIdx = fn.indexOf("teardownNestedTables(tr._juneauDetailPanel)");
+		var hideIdx = fn.indexOf("row.child.hide()");
+		assertTrue(teardownRegionsIdx >= 0, fn);
+		assertTrue(teardownRegionsIdx < teardownNestedIdx, fn);
+		assertTrue(teardownNestedIdx < hideIdx, fn);
+		// Guarded the same way the nested-table teardown already is: only when a panel actually exists on tr.
+		var guardIdx = fn.indexOf("if (tr._juneauDetailPanel) {");
+		assertTrue(guardIdx >= 0 && guardIdx < teardownRegionsIdx, fn);
+	}
+
+	//------------------------------------------------------------------------------------------------------------------
+	// e) Removal path 3/5: collapseAllDetailRows, per open row.
+	//------------------------------------------------------------------------------------------------------------------
+
+	@Test void e01_collapseAllDetailRows_tearsDownRegionsPerOpenRowBeforeHide() throws Exception {
+		var fn = functionBody(viewsJs(), "function collapseAllDetailRows(");
+		var teardownRegionsIdx = fn.indexOf("NS.regions?.teardownRegionsIn(tr._juneauDetailPanel)");
+		var teardownNestedIdx = fn.indexOf("teardownNestedTables(tr._juneauDetailPanel)");
+		var hideIdx = fn.indexOf("row.child.hide()");
+		assertTrue(teardownRegionsIdx >= 0, fn);
+		assertTrue(teardownRegionsIdx < teardownNestedIdx, fn);
+		assertTrue(teardownNestedIdx < hideIdx, fn);
+	}
+
+	//------------------------------------------------------------------------------------------------------------------
+	// f) Removal path 4/5: bindDetailInflightDrawGuards's preDraw.dt hook, guarded by _shouldCancelPollDraw.
+	//------------------------------------------------------------------------------------------------------------------
+
+	@Test void f01_preDrawGuard_tearsDownRegionsOnlyWhenNotCancelling_beforeNestedTeardown() throws Exception {
+		var fn = functionBody(viewsJs(), "function bindDetailInflightDrawGuards(");
+		var cancelGuardIdx = fn.indexOf("if (ctx._shouldCancelPollDraw?.()) return;");
+		var teardownRegionsIdx = fn.indexOf("NS.regions?.teardownRegionsIn(table)");
+		var teardownNestedIdx = fn.indexOf("teardownNestedTables(table)");
+		assertTrue(cancelGuardIdx >= 0, fn);
+		assertTrue(teardownRegionsIdx > cancelGuardIdx,
+			"region teardown must be AFTER the cancel guard (never run on a redraw this handler cancels):\n" + fn);
+		assertTrue(teardownRegionsIdx < teardownNestedIdx, fn);
+	}
+
+	//------------------------------------------------------------------------------------------------------------------
+	// g) Removal path 5/5 (B3): teardownTable's reinit/destroy path - first AND unguarded.
+	//------------------------------------------------------------------------------------------------------------------
+
+	@Test void g01_teardownTable_tearsDownRegionsFirstAndUnguarded() throws Exception {
+		var fn = functionBody(viewsJs(), "function teardownTable(");
+		var openBrace = fn.indexOf('{');
+		var teardownRegionsIdx = fn.indexOf("NS.regions?.teardownRegionsIn(table)");
+		var pollTimersIdx = fn.indexOf("_pollTimers");
+		var destroyIdx = fn.indexOf("ctx.dataTable.destroy()");
+		assertTrue(teardownRegionsIdx >= 0, fn);
+		// "First": strip `//` line comments from what precedes it - nothing but comment lines (and whitespace)
+		// may remain, i.e. no intervening statement/conditional of any kind.
+		var between = fn.substring(openBrace + 1, teardownRegionsIdx);
+		var codeOnly = between.replaceAll("//[^\n]*", "").trim();
+		assertTrue(codeOnly.isEmpty(), () -> "expected ONLY leading comments before the region teardown, got:\n" + between);
+		assertTrue(teardownRegionsIdx < pollTimersIdx, fn);
+		assertTrue(pollTimersIdx < destroyIdx, fn);
+	}
+
+	//------------------------------------------------------------------------------------------------------------------
+	// h) Missing-runtime failure mode: loud, not blank.
+	//------------------------------------------------------------------------------------------------------------------
+
+	@Test void h01_missingRuntimeReportsLoudNotBlank() throws Exception {
+		var fn = functionBody(viewsJs(), "function reportRegionsWithoutRuntime(");
+		assertTrue(fn.contains("juneau-regions.js is not loaded"), fn);
+		assertTrue(fn.contains("data-juneau-region-state"), fn);
+		assertTrue(fn.contains("renderAsyncStatus(el, \"error\""), fn);
+	}
+
+	//------------------------------------------------------------------------------------------------------------------
+	// i) This file is NOT a barrier runtime: no registerRuntime()/ready() call anywhere in it.
+	//------------------------------------------------------------------------------------------------------------------
+
+	@Test void i01_viewsJsNeverRegistersOrDeclaresReady() throws Exception {
+		// juneau-views.js is not a boot-time region runtime (the detail expander enrols on demand, not via a
+		// document-wide walk) - it must never call the barrier's registerRuntime()/ready() itself, only
+		// enrolIn/teardownRegionsIn.  Checked as actual CALLS (regions.xxx(), regions?.xxx(...)) rather than a
+		// bare substring match, since this file's own doc comments above legitimately name both by prose.
+		var views = viewsJs();
+		assertFalse(views.contains("regions.registerRuntime(") || views.contains("regions?.registerRuntime("), views);
+		assertFalse(views.contains("regions.ready(") || views.contains("regions?.ready("), views);
+	}
+}
diff --git a/juneau-rest/juneau-rest-server-widgets/src/main/resources/org/apache/juneau/widgets/juneau-cards.js b/juneau-rest/juneau-rest-server-widgets/src/main/resources/org/apache/juneau/widgets/juneau-cards.js
index 3a379e0db2..ff9ece3f74 100644
--- a/juneau-rest/juneau-rest-server-widgets/src/main/resources/org/apache/juneau/widgets/juneau-cards.js
+++ b/juneau-rest/juneau-rest-server-widgets/src/main/resources/org/apache/juneau/widgets/juneau-cards.js
@@ -55,6 +55,17 @@
 	const CARD_FIELD_ATTR = "data-juneau-card-field";
 	const CARD_REFRESH_TRIGGER_ATTR = "data-juneau-card-refresh-trigger";
 
+	/**
+	 * The region container marker - MUST equal RegionDef's REGION_ATTR constant on the server (juneau-rest-server-views).
+	 * This module never depends on that module (see this file's own header), so the identity attribute is a small,
+	 * deliberate copy rather than an import - the same convention CARD_MARKER/GRID_MARKER already follow for the
+	 * server-side constants they mirror.
+	 */
+	const REGION_MARKER = "data-juneau-region";
+
+	/** This runtime's own name, for the barrier's ready()/registerRuntime() protocol and for a missing-runtime error. */
+	const RUNTIME_TOKEN = "juneau-cards.js";
+
 	/**
 	 * Per-card action attributes - MUST equal AppHeaderTable's constants of the same names on the server, because a
 	 * card action IS a header action: `Card.actions` reuses that vocabulary rather than minting a second one.  This
@@ -257,6 +268,48 @@
 		return !!card?.querySelector?.("[" + ACTION_MARKER + "]");
 	}
 
+	/**
+	 * Resolves the region runtime, or null when juneau-regions.js is not loaded.  Deliberately read fresh on every
+	 * call rather than cached at module scope: this module's own IIFE may run before juneau-regions.js's does if a
+	 * page ever got the load order wrong, and a load-time cache would freeze that mistake in permanently.
+	 */
+	function regionsApi() {
+		return window.JuneauViews?.regions || null;
+	}
+
+	/**
+	 * Design §9.3's missing-runtime failure mode, at the card enrolment site: a `[data-juneau-region]` node with no
+	 * `juneau-regions.js` loaded to run it must not render as a silent blank card - it renders as a loud one.  One
+	 * console error naming the missing asset, per node, plus that node's own visible error state (the same
+	 * treatment an unknown populator name gets once the runtime IS present).  A card with no region pays nothing:
+	 * this is called only when at least one `[data-juneau-region]` node was actually found under the card.
+	 */
+	function reportRegionsWithoutRuntime(nodes) {
+		for (const el of nodes) {
+			window.console?.error?.(RUNTIME_TOKEN + ": juneau-regions.js is not loaded; the region '"
+				+ (el.getAttribute(REGION_MARKER) || "") + "' cannot populate.");
+			el.setAttribute("data-juneau-region-state", "error");
+			const message = "This region could not be populated: juneau-regions.js is not loaded.";
+			const render = window.JuneauViews?.init?.renderAsyncStatus;
+			if (typeof render === "function") render(el, "error", message);
+			else el.textContent = message;
+		}
+	}
+
+	/**
+	 * Enrols a card's region body/bodies (design §9.3: card-body regions enrol from `enhanceOneCard`, NOT from
+	 * `initCard` - a static card never reaches `initCard` at all).  Returns the minted handles so the caller can
+	 * push them onto its own group record; this function stays runtime-agnostic and owns no group of its own.
+	 */
+	function enrolCardRegions(card) {
+		const api = regionsApi();
+		if (!api) {
+			reportRegionsWithoutRuntime(card.querySelectorAll("[" + REGION_MARKER + "]"));
+			return [];
+		}
+		return api.enrolIn(card);
+	}
+
 	/**
 	 * Enhances one card's declared actions, scoped to that card: icon hydration, SAFE host-dispatch wiring, and MENU
 	 * triggers bound to the shared layer stack.  Idempotent (the chrome helpers mark what they wire).  With chrome
@@ -386,19 +439,32 @@
 
 	/**
 	 * Installs a MutationObserver so a card's poll timers stop when it is hidden/removed and restart on re-show (no
-	 * juneau-pages.js hook).  It watches the grid subtree (own `hidden` / `style` / `class`) AND every ancestor pages
-	 * tab panel's `class`: a pages tab hide toggles `.jc-active` on an ancestor `.jc-panel` / `.jc-subpanel` that sits
-	 * ABOVE the grid, so a grid-subtree-only observer would never see it.  With no panel ancestor the grid watch is the
-	 * sole fallback (a card hidden by its own `hidden` / inline `style`).
+	 * juneau-pages.js hook), AND runs the deferred first populate for an enrolled region that has just become
+	 * visible (design §9.3 rule 5's cards-runtime half: a region enrolled hidden defers its first populate until
+	 * `reason:"activate"`, and this observer is the only signal the cards runtime has for "my panel just activated").
+	 * It watches the grid subtree (own `hidden` / `style` / `class`) AND every ancestor pages tab panel's `class`: a
+	 * pages tab hide toggles `.jc-active` on an ancestor `.jc-panel` / `.jc-subpanel` that sits ABOVE the grid, so a
+	 * grid-subtree-only observer would never see it.  With no panel ancestor the grid watch is the sole fallback (a
+	 * card hidden by its own `hidden` / inline `style`).
+	 *
+	 * <p>The two loops are independent and neither may short-circuit the other: a grid with both a polling card and
+	 * a static region-only card runs both on every tick.  `region.el.isConnected && !isElementHidden(region.el)` is
+	 * stated positively rather than borrowed from `controls`' own predicate, which is missing the `isConnected`
+	 * conjunct and would otherwise run a deferred POPULATE (not merely restart a timer) against a detached host.
 	 */
-	function observeGrid(grid, controls) {
+	function observeGrid(grid, controls, regions) {
 		if (window.MutationObserver === undefined) return null;
+		const regionList = regions || [];
 		const obs = new window.MutationObserver(function () {
 			for (const c of controls) {
 				if (!c || !c.intervalMs) continue;
 				if (isElementHidden(c.card) || window.document?.hidden) c.stop();
 				else c.start();
 			}
+			for (const r of regionList) {
+				if (!r || !r.el) continue;
+				if (r.el.isConnected && !isElementHidden(r.el)) regionsApi()?.activateRegion?.(r);
+			}
 		});
 		obs.observe(grid, { attributes: true, attributeFilter: ["hidden", "style", "class"], subtree: true, childList: true });
 		const panels = ancestorPanels(grid);
@@ -407,24 +473,38 @@
 		return obs;
 	}
 
-	/** Resolves (creating if absent) the group record for a card's enclosing grid, or the card itself when grid-less. */
+	/**
+	 * Resolves (creating if absent) the group record for a card's enclosing grid, or the card itself when grid-less.
+	 * `regions` is the enrolled-region list this card's grid owns (design §9.3's round-6/round-7 correction): it is
+	 * a real field written by `enhanceOneCard` after `enrolIn` returns, not a `querySelectorAll` re-derived on every
+	 * observer tick - which would both re-derive a set `enrolIn` already computed synchronously and reach region
+	 * nodes this grid does not own (e.g. one inside a cloned row-detail panel, which is the expander's).
+	 */
 	function groupFor(card, groups) {
 		const grid = typeof card.closest === "function" ? card.closest("[" + GRID_MARKER + "]") : null;
 		const root = grid || card;
 		for (const group of groups)
 			if (group.root === root) return group;
-		const g = { root: root, controls: [] };
+		const g = { root: root, controls: [], regions: [] };
 		groups.push(g);
 		return g;
 	}
 
-	/** Enhances one card (refresh handshake + declared actions); a refreshable card also joins its group's controls. */
+	/**
+	 * Enhances one card (refresh handshake + declared actions + its region body/bodies); a refreshable card also
+	 * joins its group's controls.  `groupFor` runs UNCONDITIONALLY (design §9.3 round-5 correction) - a static
+	 * card's region is exactly the kind of per-card capability, unrelated to refreshability, that a declared action
+	 * catalog already is, and the observer install predicate below depends on `group.regions` being populated for
+	 * a grid of all-static cards too.
+	 */
 	function enhanceOneCard(card, groups) {
 		const refreshable = !!card.getAttribute(CARD_REFRESH_ATTR);
 		const ctl = refreshable ? initCard(card) : null;
-		if (refreshable && !ctl) return;                          // refused at the handshake - enhance nothing
+		if (refreshable && !ctl) return;                          // refused at the handshake - enhance nothing, regions included
 		enhanceCardActions(card);
-		if (ctl) groupFor(card, groups).controls.push(ctl);
+		const group = groupFor(card, groups);
+		if (ctl) group.controls.push(ctl);
+		for (const handle of enrolCardRegions(card)) group.regions.push(handle);
 	}
 
 	/**
@@ -444,7 +524,11 @@
 			enhanceOneCard(card, groups);
 
 		for (const group of groups)
-			if (group.controls.length) observeGrid(group.root, group.controls);
+			if (group.controls.length || group.regions.length) observeGrid(group.root, group.controls, group.regions);
+
+		// Design §10.11.1 rule 4: enrolment is synchronous and every card above has already been walked by the time
+		// this line runs, so declaring readiness here is a statement this runtime can make truthfully.
+		regionsApi()?.ready?.(RUNTIME_TOKEN);
 	}
 
 	NS.init = {
@@ -463,10 +547,16 @@
 		hasCardActions: hasCardActions,
 		enhanceCardActions: enhanceCardActions,
 		initCard: initCard,
+		enhanceOneCard: enhanceOneCard,
 		observeGrid: observeGrid,
 		initAll: initAll
 	};
 
+	// Design §10.11.1 rule 4: presence is established by the asset loading and registering itself at parse time,
+	// not by a document scan - so there is no list to keep in sync and a page that never enrols a region never
+	// arms the barrier this call feeds.  Guarded so a page that never loads juneau-regions.js loses nothing.
+	regionsApi()?.registerRuntime?.(RUNTIME_TOKEN);
+
 	if (window.document?.readyState === "loading") {
 		window.document.addEventListener("DOMContentLoaded", initAll);
 	} else if (window.document) {
diff --git a/juneau-rest/juneau-rest-server-widgets/src/test/java/org/apache/juneau/rest/server/widgets/WidgetsJs_Cards_Test.java b/juneau-rest/juneau-rest-server-widgets/src/test/java/org/apache/juneau/rest/server/widgets/WidgetsJs_Cards_Test.java
index a202076c49..43de7cad7c 100644
--- a/juneau-rest/juneau-rest-server-widgets/src/test/java/org/apache/juneau/rest/server/widgets/WidgetsJs_Cards_Test.java
+++ b/juneau-rest/juneau-rest-server-widgets/src/test/java/org/apache/juneau/rest/server/widgets/WidgetsJs_Cards_Test.java
@@ -67,12 +67,23 @@ class WidgetsJs_Cards_Test extends TestBase {
 			"isElementHidden: isElementHidden",
 			"renderStatus: renderStatus",
 			"initCard: initCard",
+			"enhanceOneCard: enhanceOneCard",
 			"observeGrid: observeGrid",
 			"initAll: initAll"
 		})
 			assertTrue(body.contains(name), () -> "missing export '" + name + "'");
 	}
 
+	@Test void a05_regionEnrolmentCallSitesPresent() throws Exception {
+		// WORK-J0522d: design §9.3's card-body enrolment call site + barrier ready()/registerRuntime() protocol.
+		var body = cardsJs();
+		assertTrue(body.contains("enrolCardRegions(card)"), "enhanceOneCard must enrol a card's own regions");
+		assertTrue(body.contains("api.enrolIn(card)"), "region enrolment must go through the real regions.enrolIn");
+		assertTrue(body.contains("registerRuntime?.(RUNTIME_TOKEN)"), "must register with the barrier at load");
+		assertTrue(body.contains("ready?.(RUNTIME_TOKEN)"), "must declare ready() once the card walk completes");
+		assertTrue(body.contains("RUNTIME_TOKEN = \"juneau-cards.js\""));
+	}
+
 	@Test void a02_namespaceIsCardsNotViews() throws Exception {
 		var body = cardsJs();
 		assertTrue(body.contains("window.JuneauCards"), "runtime must be namespaced as window.JuneauCards");
@@ -347,4 +358,43 @@ class WidgetsJs_Cards_Test extends TestBase {
 		assertEquals(true, r.get("i_shownWhenActive"));
 		assertEquals(true, r.get("i_stoppedWhenDeactivated"));      // pages removes .jc-active -> timers stop
 	}
+
+	//------------------------------------------------------------------------------------------------------------------
+	// Region enrolment (WORK-J0522d, design §9.3 round-5/round-6 fix) - driven against a fake JuneauViews.regions,
+	// since this module never depends on juneau-rest-server-views (see this module's pom.xml); the real region
+	// runtime's own contract is proven in the views module's Regions_* tests.
+	//------------------------------------------------------------------------------------------------------------------
+
+	@Test void d01_registerRuntimeCalledAtModuleLoad() {
+		var r = dom();
+		assertEquals(true, r.get("regionsRegisterRuntimeCalledAtLoad"));
+	}
+
+	@Test void d02_enhanceOneCardEnrolsCardRegionsEvenWhenStatic() {
+		// A static card (no refresh attr) never reaches initCard at all - this is exactly the gap the round-5/6
+		// fix closes: groupFor now runs unconditionally, and the region still gets enrolled.
+		var r = dom();
+		assertEquals(true, r.get("j_enrolInCalledWithCard"));
+		assertEquals(true, r.get("j_groupHasRegion"));
+		assertEquals(true, r.get("j_staticCardStillNoControls"));
+	}
+
+	@Test void d03_missingRegionRuntimeFailsLoudNotBlank() {
+		var r = dom();
+		assertEquals(true, r.get("k_errorReported"));
+		assertEquals(true, r.get("k_stateError"));
+		assertEquals(true, r.get("k_hasErrorText"));
+	}
+
+	@Test void d04_observeGridActivatesConnectedVisibleRegionsOnly() {
+		var r = dom();
+		assertEquals(true, r.get("l_observerInstalledForRegionsOnly"));
+		assertEquals(true, r.get("l_visibleActivated"));
+		assertEquals(true, r.get("l_detachedNotActivated"));
+	}
+
+	@Test void d05_initAllDeclaresReadyOnceItsWalkCompletes() {
+		var r = dom();
+		assertEquals(true, r.get("m_readyCalledWithToken"));
+	}
 }
diff --git a/juneau-rest/juneau-rest-server-widgets/src/test/js/cards-browser.cjs b/juneau-rest/juneau-rest-server-widgets/src/test/js/cards-browser.cjs
index 67626759ff..0134493188 100644
--- a/juneau-rest/juneau-rest-server-widgets/src/test/js/cards-browser.cjs
+++ b/juneau-rest/juneau-rest-server-widgets/src/test/js/cards-browser.cjs
@@ -157,6 +157,31 @@ function fakeClear(id) { delete timers[id]; }
 let observerCallback = null;
 function FakeMutationObserver(cb) { observerCallback = cb; this.observe = function () {}; this.disconnect = function () {}; }
 
+// A fake JuneauViews.regions - juneau-cards.js never depends on the real juneau-regions.js (widgets never depends
+// on views; see this module's pom.xml), so its region-enrolment call sites are proven against a stand-in that
+// records every call, the same division of labour the fake fetch/MutationObserver above already use.  `enrolIn`
+// mints a plain handle per `[data-juneau-region]` node under the given scope and marks it, mirroring the real
+// runtime's `el._juneauRegion` idempotency mark closely enough for these tests (this file does not re-prove
+// juneau-regions.js's own contract - that lives in the views module's Regions_* tests).
+const regionCalls = { enrolIn: [], activateRegion: [], teardownRegionsIn: [], registerRuntime: [], ready: [] };
+let nextRegionId = 1;
+function makeFakeRegions() {
+	return {
+		enrolIn: function (scopeEl) {
+			regionCalls.enrolIn.push(scopeEl);
+			return scopeEl.querySelectorAll('[data-juneau-region]').map(function (regionEl) {
+				const handle = { el: regionEl, key: regionEl.getAttribute('data-juneau-region'), deferred: false, torn: false, id: nextRegionId++ };
+				regionEl._juneauRegion = handle;
+				return handle;
+			});
+		},
+		activateRegion: function (region) { regionCalls.activateRegion.push(region); },
+		teardownRegionsIn: function (root) { regionCalls.teardownRegionsIn.push(root); },
+		registerRuntime: function (token) { regionCalls.registerRuntime.push(token); },
+		ready: function (token) { regionCalls.ready.push(token); }
+	};
+}
+
 const iconsResolved = [];
 const document = {
 	readyState: 'loading',
@@ -168,7 +193,10 @@ const window = {
 	document: document,
 	console: console,
 	MutationObserver: FakeMutationObserver,
-	JuneauViews: { icons: { resolveIcon: function (n) { iconsResolved.push(n); return '<svg data-icon="' + n + '"></svg>'; } } },
+	JuneauViews: {
+		icons: { resolveIcon: function (n) { iconsResolved.push(n); return '<svg data-icon="' + n + '"></svg>'; } },
+		regions: makeFakeRegions()
+	},
 	setTimeout: fakeSetTimeout, setInterval: fakeSetInterval, clearTimeout: fakeClear, clearInterval: fakeClear
 };
 window.fetch = makeFetch({ contractVersion: '1', fields: { k: 'FRESH' } });
@@ -184,6 +212,9 @@ vm.runInNewContext(fs.readFileSync(path.resolve(cardsJsPath), 'utf8'), sandbox,
 
 const I = window.JuneauCards?.init;
 const out = { hasInit: typeof I?.initCard === 'function' };
+// Captured immediately: registerRuntime() runs once at IIFE top level, during the vm.runInNewContext load above,
+// not from any test action below.
+out.regionsRegisterRuntimeCalledAtLoad = regionCalls.registerRuntime.indexOf('juneau-cards.js') >= 0;
 
 (async function () {
 	if (!out.hasInit) { process.stdout.write(JSON.stringify(out)); return; }
@@ -301,5 +332,58 @@ const out = { hasInit: typeof I?.initCard === 'function' };
 	observerCallback();
 	out.i_stoppedWhenDeactivated = ctlI.running === false;
 
+	// J) Region enrolment (design §9.3 round-5/round-6 fix): a STATIC card (no refresh attr - never reaches
+	// initCard) with a region body still gets its region enrolled, and `groupFor` runs unconditionally so the
+	// group record exists with `regions` populated even though `controls` stays empty.
+	regionCalls.enrolIn = [];
+	const cardJ = buildCard({ contract: null, refresh: null });
+	const regionElJ = el('div'); regionElJ.setAttribute('data-juneau-region', 'stats');
+	cardJ._parts.body.appendChild(regionElJ);
+	const groupsJ = [];
+	I.enhanceOneCard(cardJ, groupsJ);
+	out.j_enrolInCalledWithCard = regionCalls.enrolIn.length === 1 && regionCalls.enrolIn[0] === cardJ;
+	out.j_groupHasRegion = groupsJ.length === 1 && groupsJ[0].regions.length === 1
+		&& groupsJ[0].regions[0].el === regionElJ;
+	out.j_staticCardStillNoControls = groupsJ[0].controls.length === 0;
+
+	// K) Missing region runtime (design §9.3's failure mode): with no `JuneauViews.regions` loaded, a
+	// `[data-juneau-region]` node renders LOUD (one console.error naming the missing asset + a visible error
+	// state), never silently blank.
+	const cardK = buildCard({ contract: null, refresh: null });
+	const regionElK = el('div'); regionElK.setAttribute('data-juneau-region', 'missing');
+	cardK._parts.body.appendChild(regionElK);
+	const errorsK = [];
+	const savedRegions = window.JuneauViews.regions;
+	const origError = window.console.error;
+	window.console.error = function (msg) { errorsK.push(String(msg)); };
+	window.JuneauViews.regions = null;
+	I.enhanceOneCard(cardK, []);
+	window.JuneauViews.regions = savedRegions;
+	window.console.error = origError;
+	out.k_errorReported = errorsK.some(function (m) { return m.indexOf('juneau-regions.js is not loaded') >= 0; });
+	out.k_stateError = regionElK.getAttribute('data-juneau-region-state') === 'error';
+	out.k_hasErrorText = regionElK.textContent.indexOf('juneau-regions.js is not loaded') >= 0;
+
+	// L) observeGrid's region loop (design §9.3 rule 5's cards-runtime half): a connected, visible enrolled region
+	// gets activateRegion() called on it every tick; a detached one never does.
+	regionCalls.activateRegion = [];
+	const visibleRegionEl = el('div'); visibleRegionEl.isConnected = true;
+	const detachedRegionEl = el('div'); detachedRegionEl.isConnected = false;
+	const rVisible = { el: visibleRegionEl, deferred: true, torn: false };
+	const rDetached = { el: detachedRegionEl, deferred: true, torn: false };
+	const gridL = el('section'); gridL.dataset.juneauCardGrid = '1';
+	observerCallback = null;
+	const obsL = I.observeGrid(gridL, [], [rVisible, rDetached]);
+	out.l_observerInstalledForRegionsOnly = obsL != null && observerCallback != null;
+	observerCallback();
+	out.l_visibleActivated = regionCalls.activateRegion.indexOf(rVisible) >= 0;
+	out.l_detachedNotActivated = regionCalls.activateRegion.indexOf(rDetached) < 0;
+
+	// M) ready() protocol: initAll()'s card walk in this harness sees no cards (document.querySelectorAll is
+	// stubbed to return []), but that walk still completes synchronously, so ready() must fire regardless.
+	regionCalls.ready = [];
+	I.initAll();
+	out.m_readyCalledWithToken = regionCalls.ready.indexOf('juneau-cards.js') >= 0;
+
 	process.stdout.write(JSON.stringify(out));
 })();