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/08/26 14:05:32 UTC

(juneau) branch master updated (d5096f835d -> 350abd8baf)

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

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


    from d5096f835d Remove the Salesforce Sans font name from theme docs and CSS value test data.
     new 83e0a34fdf Add a side-clone reset tool and fix push.py reporting success without pushing.
     new c8bf5b330c Land the shared chrome scale contract and three disjoint views slices.
     new 171654d3ed Add a >= floor operator to the counts grammar so an invariant count can say "must never drop below N" instead of being forced into equality.
     new 6eee434b0d Invert push.py's staging guard: commit only what's staged, and refuse when anything else in the tree is unreviewed.
     new a66664bef2 Add a test asserting RawContentSinkScanner's real-tree scan actually reaches the sibling widgets module, and stop the javadoc overclaiming that guarantee.
     new 350abd8baf Remove an unused java.util.stream import from Widgets_ModuleBoundary_Test.

The 6 revisions listed above as "new" are entirely new to this
repository and will be described in separate emails.  The revisions
listed as "add" were already present in the repository and have only
been added to this reference.


Summary of changes:
 .../rest/server/console/ConsoleChromeMixin.java    |   34 +-
 .../apache/juneau/rest/server/console/Theme.java   |    4 +-
 .../resources/org/apache/juneau/console/chrome.css |   10 +-
 .../server/console/ConsoleChromeMixin_Test.java    |   43 +
 .../juneau/rest/server/views/CardGridTable.java    |   36 +-
 .../org/apache/juneau/views/juneau-ribbon.js       |   43 +-
 .../org/apache/juneau/views/juneau-views.css       |  142 ++-
 .../rest/server/views/CardGridTable_Emit_Test.java |   38 +-
 .../views/CardGridTable_ViewCardBody_Test.java     |   25 +-
 .../rest/server/views/ChromeScaleScanner.java      |  358 +++++++
 .../views/ChromeScale_ContractScan_Test.java       |  144 +++
 .../rest/server/views/RawContentSinkScanner.java   |   66 +-
 .../views/RawContentSink_SecurityScan_Test.java    |   25 +
 .../server/views/SymbolSprite_StemIds_Test.java    |   86 ++
 .../server/views/ViewsJs_RibbonNormalize_Test.java |  232 ++++
 .../rest/server/views/ViewsMixin_Serving_Test.java |   12 +-
 .../src/test/js/ribbon-normalize.cjs               |  207 ++++
 .../juneau/rest/server/widgets/CardBody.java       |   10 +-
 .../juneau/rest/server/widgets/CardContent.java    |   88 ++
 .../rest/server/widgets/CardContent_Test.java      |   61 ++
 .../widgets/Widgets_ModuleBoundary_Test.java       |    1 -
 scripts/push.py                                    |  590 ++++++----
 scripts/reset-side-clones.py                       | 1124 ++++++++++++++++++++
 scripts/tests/README.md                            |   40 +-
 scripts/tests/test_push.py                         |  729 ++++++++++++-
 scripts/tests/test_reset_side_clones.py            |  960 +++++++++++++++++
 scripts/tests/test_todo_status_audit.py            |   99 ++
 scripts/todo-status-audit.py                       |   91 +-
 28 files changed, 4970 insertions(+), 328 deletions(-)
 create mode 100644 juneau-rest/juneau-rest-server-views/src/test/java/org/apache/juneau/rest/server/views/ChromeScaleScanner.java
 create mode 100644 juneau-rest/juneau-rest-server-views/src/test/java/org/apache/juneau/rest/server/views/ChromeScale_ContractScan_Test.java
 create mode 100644 juneau-rest/juneau-rest-server-views/src/test/java/org/apache/juneau/rest/server/views/SymbolSprite_StemIds_Test.java
 create mode 100644 juneau-rest/juneau-rest-server-views/src/test/java/org/apache/juneau/rest/server/views/ViewsJs_RibbonNormalize_Test.java
 create mode 100644 juneau-rest/juneau-rest-server-views/src/test/js/ribbon-normalize.cjs
 create mode 100644 juneau-rest/juneau-rest-server-widgets/src/main/java/org/apache/juneau/rest/server/widgets/CardContent.java
 create mode 100644 juneau-rest/juneau-rest-server-widgets/src/test/java/org/apache/juneau/rest/server/widgets/CardContent_Test.java
 create mode 100755 scripts/reset-side-clones.py
 create mode 100644 scripts/tests/test_reset_side_clones.py


(juneau) 01/06: Add a side-clone reset tool and fix push.py reporting success without pushing.

Posted by ja...@apache.org.
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

commit 83e0a34fdf1538197e7903690b1315950b64ad24
Author: James Bognar <ja...@apache.org>
AuthorDate: Wed Aug 26 08:28:49 2026 -0400

    Add a side-clone reset tool and fix push.py reporting success without pushing.
    
    Two pieces of scripts/ tooling hygiene, committed together because they share a
    single documentation seam rather than because they happened to be dirty at the
    same time. scripts/tests/README.md's "what is covered here" section had to be
    rewritten once to name both reset-side-clones.py and push.py's tracker-audit
    gate, and to restate the hermeticity rule now that the suite builds real
    temporary git repositories instead of only synthetic fixture files. Splitting
    these would mean either duplicating that edit or leaving one commit describing a
    harness that does not exist yet -- the same self-correcting-reference problem
    a04af69856 and its follow-up already worked through once.
    
    reset-side-clones.py automates the wave-boundary reset that was previously done
    by hand across nine working trees. Its value is the guards, not the keystrokes:
    it refuses canonical trees by resolved real path (so a symlink or a .. path
    cannot slip through), refuses any clone the board marks in-flight, aborts on a
    dirty, staged or untracked tree, fails closed on an unreadable or unparseable
    board before touching anything, and cannot reach git clean -x or git config on
    any code path. Verification compares file content against the canonical blob
    rather than trusting a commit id.
    
    push.py had two defects, both surfaced by a real push. It reported success
    without pushing: the push step sat downstream of the commit step, so a clean
    working tree took the "no changes, skip commit and push" path and returned 0
    even with unpushed commits on the branch, telling the operator their work had
    reached the remote when it had not. A clean tree now skips only the commit and
    still pushes when the branch is ahead of its upstream; a genuine no-op says
    "nothing to commit or push", which cannot be misread as a push having happened.
    Separately, its unconditional git add . swept the whole working tree into the
    commit, so it now refuses when the index already holds staged changes it did not
    stage itself, and names them. Refusing was chosen over quietly narrowing what
    gets staged: silently committing less than a long-time user expects fails in the
    same direction as the bug being fixed.
    
    Both scripts are tested against real temporary git repositories with a bare
    remote rather than mocks, because in both cases the entire risk is what real git
    does. The false-success regression asserts the remote ref actually advances, and
    was confirmed to fail against the previous logic rather than merely to pass
    against the new one. Suite goes 282 to 300.
    
    push.py is juneau-only and deliberately not triplicated like todo-next-id.py and
    todo-status-audit.py; release-manager's same-named script is an unrelated
    gate-free helper and the console has none. The identical clean-tree pattern still
    exists in run_docs_only() and in the juneau-docs follow-up inside main(); both
    are out of scope here and carry the same latent risk.
---
 scripts/push.py                         |  472 ++++++++-----
 scripts/reset-side-clones.py            | 1124 +++++++++++++++++++++++++++++++
 scripts/tests/README.md                 |   40 +-
 scripts/tests/test_push.py              |  314 ++++++++-
 scripts/tests/test_reset_side_clones.py |  960 ++++++++++++++++++++++++++
 5 files changed, 2713 insertions(+), 197 deletions(-)

diff --git a/scripts/push.py b/scripts/push.py
index 0e82c83e2d..37d2b74cd5 100755
--- a/scripts/push.py
+++ b/scripts/push.py
@@ -381,14 +381,49 @@ def check_git_status(repo_dir):
         return True
 
 
+def check_preexisting_staged_changes(repo_dir):
+    """
+    List paths with changes already staged in the index, before this script's own `git add .`.
+
+    `git commit` commits whatever is in the index regardless of which step staged it, so
+    content staged by something else before push.py runs (e.g. a concurrent session sharing
+    this working tree) would be folded into this push's commit whether or not `git add .` ran.
+    Checking this before add/commit lets the caller refuse rather than silently absorb it.
+
+    Returns:
+        list[str]: staged paths (possibly empty). Fails open (returns []) if the check itself
+        can't run -- the add/commit steps immediately following will surface any real git
+        problem on their own.
+    """
+    try:
+        result = subprocess.run(
+            ["git", "diff", "--cached", "--name-only"],
+            cwd=repo_dir,
+            capture_output=True,
+            text=True,
+            check=True
+        )
+        return [line for line in result.stdout.splitlines() if line.strip()]
+    except Exception as e:
+        print(f"⚠ Warning: Could not check for pre-existing staged changes: {e}")
+        return []
+
+
 def check_upstream_changes(repo_dir):
     """
-    Check if local branch is behind upstream/remote branch.
-    
+    Fetch from the remote and compare the local branch to its upstream tracking branch.
+
     Returns:
-        tuple: (is_behind, error_message)
-        - is_behind: True if local is behind remote, False otherwise
-        - error_message: Error message if check failed, None otherwise
+        tuple: (ahead, behind, error_message)
+        - ahead: commits on the local branch not yet on the upstream branch, or None if there
+          is no upstream branch configured
+        - behind: commits on the upstream branch not yet on the local branch, or None if there
+          is no upstream branch configured
+        - error_message: Error message if the check failed, None otherwise
+
+    ahead/behind are None (not 0) when there's no upstream branch configured, so callers can
+    tell "nothing to push because there's no remote to compare against" apart from "checked,
+    and there's genuinely nothing ahead".
     """
     try:
         # Get current branch name
@@ -421,7 +456,7 @@ def check_upstream_changes(repo_dir):
         
         if result.returncode != 0:
             # No upstream branch configured, skip check
-            return (False, None)
+            return (None, None, None)
         
         upstream_branch = result.stdout.strip()
         
@@ -437,15 +472,16 @@ def check_upstream_changes(repo_dir):
         # Output format: "X\tY" where X is commits ahead, Y is commits behind
         counts = result.stdout.strip().split('\t')
         if len(counts) != 2:
-            return (False, "Could not parse upstream comparison")
+            return (None, None, "Could not parse upstream comparison")
         
+        commits_ahead = int(counts[0])
         commits_behind = int(counts[1])
-        return (commits_behind > 0, None)
+        return (commits_ahead, commits_behind, None)
         
     except subprocess.CalledProcessError as e:
-        return (False, f"Git command failed: {e}")
+        return (None, None, f"Git command failed: {e}")
     except Exception as e:
-        return (False, f"Error checking upstream changes: {e}")
+        return (None, None, f"Error checking upstream changes: {e}")
 
 
 def current_branch(repo_dir):
@@ -549,6 +585,159 @@ def verify_starter_repos(step_num):
     return True
 
 
+def commit_and_push(
+    repo_dir,
+    message,
+    step_num,
+    *,
+    label="",
+    pull_hint="git pull",
+    pre_flight_hook=None,
+    pre_commit_hook=None,
+):
+    """
+    Commit any local changes and push, treating "clean working tree" and "nothing to push" as
+    two different things (the bug this replaces reported success without ever pushing).
+
+    A clean working tree means there is nothing NEW to commit -- it does NOT mean there is
+    nothing to push. A prior run could have committed successfully and then been interrupted (or
+    failed) before the push step, leaving unpushed commits sitting on the branch; treating a
+    clean tree as "nothing to do" in that situation is a false success, since the caller would
+    believe their work reached the remote when it did not. So a clean tree here skips the
+    COMMIT, not the push: if the branch is already ahead of its upstream, that gets pushed. Only
+    a clean tree with nothing already ahead (or no upstream to compare against) is truly a
+    no-op, and that is reported with text that is never confusable with an actual push having
+    happened.
+
+    Also refuses to stage/commit if the index already has staged changes before this call's own
+    `git add .` -- e.g. from a concurrent session sharing this working tree -- since `git commit`
+    would fold pre-existing staged content into this push's commit regardless of what `git add .`
+    stages in this run. `git add .` itself is deliberately left unconditional for genuinely
+    unstaged/untracked changes: that is this script's documented, long-standing behavior (commit
+    everything in the tree under one message), and narrowing it further without being asked would
+    risk surprising an existing caller just as badly as the bug it would replace.
+
+    Shared by all three sites in this file that make this same commit-or-push decision (the
+    default juneau flow, the juneau-docs follow-up in main()'s Step 6, and --docs-only's
+    juneau-docs flow) -- this decision is exactly what the false-success bug duplicated three
+    times over, so the two hooks below exist to let each site's genuinely different surrounding
+    behavior (an identity gate, a pre-commit smoke check) plug into ONE copy of the decision
+    logic instead of re-implementing it.
+
+    Args:
+        repo_dir: Repository root.
+        message: Commit message to use if a commit is made.
+        step_num: The current step number (for output formatting).
+        label: Optional text identifying which repo this is, appended to output messages (e.g.
+            " (juneau-docs)") so a caller running this against more than one repo per invocation
+            can tell them apart in the log. Empty by default.
+        pull_hint: The `git pull` command shown in the behind-upstream error message. Callers
+            operating outside the repo's own directory (e.g. main() running against the
+            juneau-docs sibling while cwd is juneau) can pass a `-C <path>`-qualified form.
+        pre_flight_hook: Optional zero-arg callable invoked once it's established that there is
+            something to commit and/or push (i.e. NOT the nothing_to_do case), before any git
+            state is mutated. Must return True to proceed or False to abort (and is responsible
+            for printing its own error and playing the failure sound before returning False).
+            Used for checks that must run before ANY push, including a push-only run with
+            nothing new to commit -- e.g. the juneau-docs Apache-identity gate in main()'s Step 6
+            follow-up. None (the default) means no such check is needed.
+        pre_commit_hook: Optional zero-arg callable invoked only when there ARE local changes to
+            commit, immediately before `git add .`. Same True/False contract as pre_flight_hook.
+            Used for checks that have nothing new to validate when nothing changed -- e.g. the
+            juneau-docs Docusaurus smoke build, which only needs to run before a commit that
+            actually contains new docs content. None (the default) means no such check is needed.
+
+    Returns:
+        tuple: (status, step_num)
+        - status: "ok" (proceed with the rest of the flow), "nothing_to_do" (nothing was
+          committed or pushed -- caller should exit 0 immediately, matching the pre-existing
+          no-op shortcut), or "error" (caller should exit 1 immediately).
+        - step_num: the input step_num, advanced past whichever of the commit/push steps
+          actually ran (unchanged for "nothing_to_do"/"error").
+    """
+    print(f"\nšŸ” Checking for upstream changes{label}...")
+    commits_ahead, commits_behind, error_msg = check_upstream_changes(repo_dir)
+    if error_msg:
+        print(f"\n⚠ Warning: Could not check upstream changes{label}: {error_msg}")
+        print("Continuing anyway...")
+    elif commits_behind:
+        print(f"\nāŒ ERROR: Local branch{label} is behind upstream/remote branch.")
+        print("Please pull/merge upstream changes before pushing.")
+        print(f"Run: {pull_hint}")
+        play_sound(success=False)
+        return ("error", step_num)
+
+    # A clean tree skips the commit, not the push -- see docstring above.
+    has_changes = check_git_status(repo_dir)
+    if not has_changes and not commits_ahead:
+        if error_msg:
+            print(f"\nℹ Nothing to commit locally{label}, and the upstream comparison could not "
+                  "be verified (see warning above) -- assuming nothing to push.")
+        else:
+            print(f"\nℹ Nothing to commit and no unpushed commits{label}.")
+        print(f"šŸŽ‰ Push{label} completed successfully (nothing to commit or push)!")
+        play_sound(success=True)
+        return ("nothing_to_do", step_num)
+
+    if pre_flight_hook is not None and not pre_flight_hook():
+        return ("error", step_num)
+
+    if has_changes:
+        preexisting_staged = check_preexisting_staged_changes(repo_dir)
+        if preexisting_staged:
+            print(f"\nāŒ ERROR: The Git index already has staged changes{label} from before this run:")
+            for path in preexisting_staged:
+                print(f"   {path}")
+            print("   Refusing to stage/commit over them -- they may belong to a concurrent")
+            print("   session sharing this working tree. Review, commit, or unstage them first,")
+            print("   then re-run push.py.")
+            play_sound(success=False)
+            return ("error", step_num)
+
+        if pre_commit_hook is not None and not pre_commit_hook():
+            return ("error", step_num)
+
+        # Step N: Git add and commit
+        print(f"\nšŸ“ Step {step_num}: Committing changes to Git{label}...")
+        if not run_command(
+            ["git", "add", "."],
+            f"  {step_num}.1: Staging all changes...",
+            repo_dir
+        ):
+            print(f"\nāŒ git add failed{label} -- aborting.")
+            play_sound(success=False)
+            return ("error", step_num)
+
+        if not run_command(
+            ["git", "commit", "-m", message],
+            f"  {step_num}.2: Creating commit...",
+            repo_dir
+        ):
+            print(f"\nāŒ git commit failed{label} -- aborting.")
+            play_sound(success=False)
+            return ("error", step_num)
+        print(f"āœ… Step {step_num}: Git commit completed{label}.")
+        step_num += 1
+    else:
+        print(f"\nℹ No new changes to commit{label} -- {commits_ahead} unpushed commit(s) "
+              "already on this branch will be pushed now.")
+
+    # Step N (or N+1): Push to remote
+    if not run_command(
+        ["git", "push"],
+        f"šŸš€ Step {step_num}: Pushing changes to remote repository{label}...",
+        repo_dir
+    ):
+        print(f"\nāŒ git push failed{label}.")
+        print(f"⚠ Local commits exist but were not pushed{label}.")
+        play_sound(success=False)
+        return ("error", step_num)
+    print(f"āœ… Step {step_num}: Changes pushed to remote{label}.")
+    step_num += 1
+
+    return ("ok", step_num)
+
+
 def run_docs_only(args, juneau_root):  # NOSONAR python:S3776 -- Cognitive complexity is acceptable for this function
     """
     --docs-only mode: operate ONLY on the sibling juneau-docs repo.
@@ -606,76 +795,42 @@ def run_docs_only(args, juneau_root):  # NOSONAR python:S3776 -- Cognitive compl
         return 1
     print("āœ… Step 1: Git identity verified")
 
-    # Step 2: Check if local juneau-docs branch is behind upstream.
-    print("\nšŸ” Checking for upstream changes on juneau-docs...")
-    is_behind, error_msg = check_upstream_changes(docs_root)
-    if error_msg:
-        print(f"\n⚠ Warning: Could not check upstream changes: {error_msg}")
-        print("Continuing anyway...")
-    elif is_behind:
-        print("\nāŒ ERROR: juneau-docs local branch is behind upstream/remote branch.")
-        print("Please pull/merge upstream changes before pushing.")
-        print("Run: git -C ../juneau-docs pull")
-        play_sound(success=False)
-        return 1
-
-    # Step 3: No-op check — mirror the default flow's no-changes messaging style.
-    if not check_git_status(docs_root):
-        print("\n⚠ Warning: No docs changes detected. Skipping commit and push.")
-        print("šŸŽ‰ Docs-only push completed successfully (nothing to commit)!")
-        play_sound(success=True)
-        return 0
-
-    # Step 4: Docs verification gate (Docusaurus smoke build; runs verify-docs.py internally).
-    print("\nšŸ“š Step 4: juneau-docs has changes — running Docusaurus smoke check first...")
-    docs_build_script = docs_root / "scripts" / "build-docs.py"
-    try:
-        result = subprocess.run(
-            [sys.executable, str(docs_build_script), "--skip-maven"],
-            cwd=docs_root,
-            check=False
-        )
-        if result.returncode != 0:
-            print("\nāŒ Docs smoke check failed — fix the Docusaurus build before pushing juneau-docs.")
+    # Steps 2-6: upstream check, no-op detection, docs smoke check, commit, and push -- all
+    # delegated to commit_and_push() (shared with main()'s Step 6 follow-up) so the clean-tree-
+    # vs-nothing-to-push fix and the pre-existing-staged-changes guard live in one place. The
+    # Docusaurus smoke build only has anything new to validate when there IS a commit about to
+    # be made, so it's wired in as commit_and_push()'s pre_commit_hook rather than running
+    # unconditionally.
+    def _docs_smoke_check():
+        print("\nšŸ“š juneau-docs has changes — running Docusaurus smoke check first...")
+        docs_build_script = docs_root / "scripts" / "build-docs.py"
+        try:
+            result = subprocess.run(
+                [sys.executable, str(docs_build_script), "--skip-maven"],
+                cwd=docs_root,
+                check=False
+            )
+            if result.returncode != 0:
+                print("\nāŒ Docs smoke check failed — fix the Docusaurus build before pushing juneau-docs.")
+                play_sound(success=False)
+                return False
+            print("āœ… Docs smoke check passed")
+            return True
+        except Exception as e:
+            print(f"\nāŒ Docs smoke check failed: {e}")
             play_sound(success=False)
-            return 1
-        print("āœ… Step 4: Docs smoke check passed")
-    except Exception as e:
-        print(f"\nāŒ Docs smoke check failed: {e}")
-        play_sound(success=False)
-        return 1
-
-    # Step 5: Git add and commit
-    print("\nšŸ“ Step 5: Committing changes to Git (juneau-docs)...")
-    if not run_command(
-        ["git", "add", "."],
-        "  5.1: Staging juneau-docs changes...",
-        docs_root
-    ):
-        print("\nāŒ Docs-only push aborted due to juneau-docs git add failure.")
-        play_sound(success=False)
-        return 1
-
-    if not run_command(
-        ["git", "commit", "-m", args.message],
-        "  5.2: Creating commit...",
-        docs_root
-    ):
-        print("\nāŒ Docs-only push aborted due to juneau-docs git commit failure.")
-        play_sound(success=False)
-        return 1
-    print("āœ… Step 5: Git commit completed.")
+            return False
 
-    # Step 6: Push to remote
-    if not run_command(
-        ["git", "push"],
-        "šŸš€ Step 6: Pushing juneau-docs changes to remote repository...",
-        docs_root
-    ):
-        print("\nāŒ Docs-only push aborted due to git push failure.")
-        print("⚠ Your juneau-docs changes have been committed locally but not pushed.")
-        play_sound(success=False)
+    status, _ = commit_and_push(
+        docs_root, args.message, 5,
+        label=" (juneau-docs)",
+        pull_hint="git -C ../juneau-docs pull",
+        pre_commit_hook=_docs_smoke_check,
+    )
+    if status == "error":
         return 1
+    if status == "nothing_to_do":
+        return 0
 
     print("\n" + "=" * 70)
     print("šŸŽ‰ Docs-only push completed successfully!")
@@ -968,120 +1123,67 @@ Examples:
         return 1
     step_num += 1
     
-    # Check if local branch is behind upstream
-    print("\nšŸ” Checking for upstream changes...")
-    is_behind, error_msg = check_upstream_changes(juneau_root)
-    if error_msg:
-        print(f"\n⚠ Warning: Could not check upstream changes: {error_msg}")
-        print("Continuing anyway...")
-    elif is_behind:
-        print("\nāŒ ERROR: Local branch is behind upstream/remote branch.")
-        print("Please pull/merge upstream changes before pushing.")
-        print("Run: git pull")
-        play_sound(success=False)
+    # Step 4/5: Commit (if there's anything new) and push (if there's anything ahead) --
+    # extracted into commit_and_push() so the "clean tree != nothing to push" fix and the
+    # pre-existing-staged-changes guard are unit-testable against real git without invoking the
+    # mvn build/test steps above.
+    push_status, step_num = commit_and_push(juneau_root, args.message, step_num)
+    if push_status == "error":
         return 1
-    
-    # Check if there are changes to commit
-    if not check_git_status(juneau_root):
-        print("\n⚠ Warning: No changes detected. Skipping commit and push.")
-        print("šŸŽ‰ Build completed successfully (nothing to commit)!")
-        play_sound(success=True)
+    if push_status == "nothing_to_do":
         return 0
-    
-    # Step 4: Git add and commit
-    print(f"\nšŸ“ Step {step_num}: Committing changes to Git...")
-    if not run_command(
-        ["git", "add", "."],
-        f"  {step_num}.1: Staging all changes...",
-        juneau_root
-    ):
-        print("\nāŒ Build process aborted due to git add failure.")
-        play_sound(success=False)
-        return 1
-    
-    if not run_command(
-        ["git", "commit", "-m", args.message],
-        f"  {step_num}.2: Creating commit...",
-        juneau_root
-    ):
-        print("\nāŒ Build process aborted due to git commit failure.")
-        play_sound(success=False)
-        return 1
-    print(f"āœ… Step {step_num}: Git commit completed.")
-    step_num += 1
-    
-    # Step 5: Push to remote
-    if not run_command(
-        ["git", "push"],
-        f"šŸš€ Step {step_num}: Pushing changes to remote repository...",
-        juneau_root
-    ):
-        print("\nāŒ Build process aborted due to git push failure.")
-        print("⚠ Your changes have been committed locally but not pushed.")
-        play_sound(success=False)
-        return 1
-    
-    step_num += 1
 
-    # Step 6 (optional): juneau-docs follow-up — smoke check + commit + push
+    # Step 6 (optional): juneau-docs follow-up — smoke check + commit + push. Guarded only by
+    # docs_root existing (NOT by check_git_status(docs_root) as before): a clean juneau-docs
+    # tree can still have unpushed commits from an earlier interrupted run, and this follow-up
+    # has to run for that case too, or it silently never pushes them (the same false-success
+    # shape as the defect commit_and_push() exists to fix). Delegated to the same
+    # commit_and_push() as the default juneau flow and --docs-only, via two hooks: the identity
+    # gate must run before ANY push (including a push-only run with no new commit), and the
+    # smoke check only has anything to validate when there IS a commit about to be made.
     docs_root = juneau_root.parent / "juneau-docs"
-    if docs_root.exists() and check_git_status(docs_root):
-        print("\nšŸ” Verifying git identity (apache.org email) on juneau-docs...")
-        if not verify_apache_identity(docs_root):
-            play_sound(success=False)
-            return 1
-        print("āœ… Git identity verified")
-
-        print(f"\nšŸ“š Step {step_num}: juneau-docs has changes — running Docusaurus smoke check first...")
-
-        docs_build_script = docs_root / "scripts" / "build-docs.py"
-        docs_smoke_start = time.time()
-        try:
-            result = subprocess.run(
-                [sys.executable, str(docs_build_script), "--skip-maven"],
-                cwd=docs_root,
-                check=False
-            )
-            docs_smoke_elapsed = time.time() - docs_smoke_start
-            if result.returncode != 0:
-                print(f"\nāŒ Docs smoke check failed — fix the Docusaurus build before pushing juneau-docs.")
+    if docs_root.exists():
+        def _verify_docs_identity():
+            print("\nšŸ” Verifying git identity (apache.org email) on juneau-docs...")
+            if not verify_apache_identity(docs_root):
                 play_sound(success=False)
-                return 1
-            print(f"āœ… Docs smoke check passed ({docs_smoke_elapsed:.1f}s)")
-        except Exception as e:
-            print(f"\nāŒ Docs smoke check failed: {e}")
-            play_sound(success=False)
-            return 1
-
-        if not run_command(
-            ["git", "add", "."],
-            f"  {step_num}.1: Staging juneau-docs changes...",
-            docs_root
-        ):
-            print("\nāŒ Build process aborted due to juneau-docs git add failure.")
-            play_sound(success=False)
-            return 1
-
-        if not run_command(
-            ["git", "commit", "-m", args.message],
-            f"  {step_num}.2: Committing juneau-docs changes...",
-            docs_root
-        ):
-            print("\nāŒ Build process aborted due to juneau-docs git commit failure.")
-            play_sound(success=False)
-            return 1
-
-        if not run_command(
-            ["git", "push"],
-            f"  {step_num}.3: Pushing juneau-docs changes...",
-            docs_root
-        ):
-            print("\nāŒ juneau-docs push failed.")
-            print("⚠ juneau-docs changes have been committed locally but not pushed.")
-            play_sound(success=False)
+                return False
+            print("āœ… Git identity verified")
+            return True
+
+        def _docs_smoke_check():
+            print(f"\nšŸ“š juneau-docs has changes — running Docusaurus smoke check first...")
+            docs_build_script = docs_root / "scripts" / "build-docs.py"
+            docs_smoke_start = time.time()
+            try:
+                result = subprocess.run(
+                    [sys.executable, str(docs_build_script), "--skip-maven"],
+                    cwd=docs_root,
+                    check=False
+                )
+                docs_smoke_elapsed = time.time() - docs_smoke_start
+                if result.returncode != 0:
+                    print("\nāŒ Docs smoke check failed — fix the Docusaurus build before pushing juneau-docs.")
+                    play_sound(success=False)
+                    return False
+                print(f"āœ… Docs smoke check passed ({docs_smoke_elapsed:.1f}s)")
+                return True
+            except Exception as e:
+                print(f"\nāŒ Docs smoke check failed: {e}")
+                play_sound(success=False)
+                return False
+
+        docs_status, step_num = commit_and_push(
+            docs_root, args.message, step_num,
+            label=" (juneau-docs)",
+            pull_hint="git -C ../juneau-docs pull",
+            pre_flight_hook=_verify_docs_identity,
+            pre_commit_hook=_docs_smoke_check,
+        )
+        if docs_status == "error":
             return 1
-
-        print(f"āœ… Step {step_num}: juneau-docs pushed successfully.")
+        # "nothing_to_do" here just means juneau-docs itself had nothing going on -- the juneau
+        # push above already succeeded, so fall through to the overall success block below.
 
     # Success!
     print("\n" + "=" * 70)
diff --git a/scripts/reset-side-clones.py b/scripts/reset-side-clones.py
new file mode 100755
index 0000000000..318a46b22d
--- /dev/null
+++ b/scripts/reset-side-clones.py
@@ -0,0 +1,1124 @@
+#!/usr/bin/env python3
+# ***************************************************************************************************************************
+# * 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.
+# ***************************************************************************************************************************
+"""
+Post-harvest side-clone reset, automating the "After harvest (reset the side clone)" procedure
+in ~/Project Work/skills/todo-and-waves/SKILL.md.
+
+That skill is the authority for this procedure. Where this script and the skill disagree, the
+skill wins and this script is the bug. The seven numbered steps below are the skill's, in the
+skill's order:
+
+  1. Confirm the clone is not `in-flight` in repos.md and not a canonical tree.
+  2. git fetch the clone's own origin.
+  3. git checkout master (Juneau / IRS) or main (Console).
+  4. git reset --hard to the canonical remote-tracking branch.
+  5. Delete leftover local cu/* branches if skill-safe.
+  6. git clean -fd for untracked non-ignored files. Never git clean -x (preserve .work/).
+  7. Update repos.md: branch = master/main, WAVE / session empty, status idle.
+
+WHY THIS EXISTS. It is not a keystroke saver. It runs at a wave boundary -- the exact moment a
+hand-run drops a guard -- and it performs `reset --hard` plus `clean` across up to nine working
+trees. Its whole value is that the guards below cannot be skipped, so every one of them is a
+REFUSAL (nothing destructive is attempted on that clone) rather than a warning.
+
+GUARDS
+  * Canonical trees are refused by RESOLVED REAL PATH, so a symlink, a relative invocation, or a
+    board row pointing at one cannot slip past. Belt and braces: the hardcoded CANONICAL_TREES
+    list, plus any repos.md row whose role says "canonical", plus a refusal inside the git
+    wrapper itself so no code path can run git in a canonical tree at all.
+  * Only clones the board knows about can be selected. An arbitrary path is refused.
+  * `in-flight` (and `do-not-use`) rows are refused.
+  * An unreadable or unparseable repos.md aborts everything before any clone is touched. Treating
+    a board we could not read as "nothing is in flight" is the fail-open version of that check,
+    so a missing file, a decode error, a missing table, an unexpected header, or a malformed row
+    all exit 2 having done nothing.
+  * A clone with uncommitted, staged, or untracked-non-ignored work is refused and reported, not
+    reset over.
+  * A remote whose URL is a local path resolving into ANOTHER project's canonical tree is refused.
+    That is the "never cross IRS with Apache remotes" rule made mechanical. Fetches never pass a
+    URL or a remote outside the clone's own configured remotes, so a crossing cannot originate
+    here; this guard catches one that was configured elsewhere.
+  * `.work/` is copied out before the clone is touched and restored after, and the copy is only
+    deleted once the post-reset `.work/` verifies byte-identical to it.
+  * `git clean` can only ever run as GIT_CLEAN_ARGV == ("clean", "-fd"). There is deliberately no
+    flag, parameter, or code path that can add -x: _git_clean() takes no flag argument, and _git()
+    refuses a `clean` argv that is not exactly GIT_CLEAN_ARGV as well as any -x/-X style token in
+    any argv. `git clean -x` is the one unrecoverable mistake in this procedure (it deletes the
+    gitignored .work/ brainstorm tree), so it is unreachable by construction rather than by
+    remembering not to pass it.
+  * `git config` is refused by the wrapper in every form, including a read-only --get.
+
+DEFAULT IS A DRY RUN. Acting requires --apply. The safe mode is the one you get by typing the
+command wrong, forgetting a flag, or hitting Enter early. A dry run performs no fetch either --
+it stays entirely read-only -- so the target commit it prints is the CURRENT remote-tracking sha
+and is labelled as such; the real target is resolved after the fetch in step 2.
+
+VERIFICATION compares actual file CONTENT against the canonical blob rather than trusting the
+commit hash: after the reset, `git hash-object` over the real working-tree file is compared with
+the blob id that the fetched canonical commit records for that path (`git rev-parse <ref>:<path>`).
+A matching HEAD sha only proves the ref moved; it says nothing about what is on disk, which is
+precisely the confusion this check exists to remove. SENTINEL_PATHS are checked when the target
+ref carries them, and a deterministic sample of the target tree is used when it does not, so
+"nothing to verify" can never be reported as a pass.
+
+POOLS come from the board, not from this file -- the only per-pool knowledge here is the default
+branch, mirroring the skill's pool table (Juneau master, IRS master, Console main). --all covers
+the juneau and console pools; the IRS pool must be named explicitly with --pool irs, because the
+skill isolates IRS as a separate hat and one command that resets Apache and IRS trees together
+mixes them. The exclusion is printed, never silent.
+
+Usage:
+    ./scripts/reset-side-clones.py --all                          # dry run (default)
+    ./scripts/reset-side-clones.py --all --apply
+    ./scripts/reset-side-clones.py --pool juneau --apply
+    ./scripts/reset-side-clones.py --pool irs --apply
+    ./scripts/reset-side-clones.py --clones juneau-2,juneau-7 --apply
+
+Options:
+    --all                Every side clone in the juneau and console pools (IRS excluded; see above).
+    --pool <name>        juneau | console | irs. Repeatable.
+    --clones <list>      Comma-separated board basenames or paths. Repeatable.
+    --apply              Actually perform the reset. Without this, nothing is written or run.
+    --board <path>       repos.md to read (default: ~/Project Work/repos.md).
+    --no-board-update    Do the reset but only REPORT the repos.md row change (step 7 by hand).
+    --help, -h           Show this help message.
+
+Exit status:
+    0   Everything requested completed (or a dry run produced a plan with no refusals).
+    1   At least one clone was refused by a guard. Nothing destructive was attempted on it.
+    2   repos.md could not be read or parsed. NOTHING was done to any clone.
+    3   A reset or a post-reset verification failed. Read the report; that clone needs attention.
+    4   Usage error (no selection given, unknown pool, unknown or ambiguous clone name).
+    5   Resets completed but one or more repos.md rows could not be written safely. The needed
+        change is printed; apply it by hand. Reported rather than risking a mangled board.
+    When several apply, the most severe is returned in the order 3, 5, 1.
+"""
+
+from __future__ import annotations
+
+import argparse
+import filecmp
+import os
+import re
+import shutil
+import subprocess
+import sys
+import tempfile
+from dataclasses import dataclass, field
+from pathlib import Path
+
+# ---------------------------------------------------------------------------------------
+# Canonical trees. Refused by resolved real path -- never by string comparison against the
+# spelling the caller happened to use. These are the three the skill names as canonical
+# ("Never reset canonical juneau / irs-1 / sandbox-support-console"); board rows whose role
+# says "canonical" are refused too, so a canonical tree added to the board later is covered
+# without a code change here.
+# ---------------------------------------------------------------------------------------
+CANONICAL_TREES = (
+    Path.home() / "git" / "apache" / "juneau",
+    Path.home() / "git" / "central-routing" / "irs-1",
+    Path.home() / "git" / "sandbox" / "sandbox-support-console",
+)
+
+BOARD_DEFAULT = Path.home() / "Project Work" / "repos.md"
+
+# The board's own vocabulary. A row is a candidate only if its project and role match EXACTLY --
+# an allowlist, not a substring test, which is what keeps "IRS-only (workspace)" (irs-1) and
+# "IRS-only (FIT)" (irs-falcon-6) out while letting plain "IRS-only" side clones in.
+PROJECT_TO_POOL = {"Juneau": "juneau", "Console": "console", "IRS": "irs"}
+SELECTABLE_ROLES = frozenset({"worker clone", "IRS-only"})
+
+# The skill's pool table. The only per-pool knowledge in this file.
+POOL_DEFAULT_BRANCH = {"juneau": "master", "console": "main", "irs": "master"}
+
+# --all deliberately omits irs; see the module docstring.
+POOLS_IN_ALL = ("juneau", "console")
+
+BOARD_COLUMNS = ("path", "project", "role", "branch", "wave / session", "status")
+
+# ---------------------------------------------------------------------------------------
+# git clean, in the only shape it is ever allowed to take. -x deletes gitignored files, which
+# in a side clone means the .work/ brainstorm tree -- unrecoverable, and the reason this is a
+# constant rather than a parameter. _git_clean() below has no flag argument at all, and _git()
+# refuses any clean argv that is not exactly this tuple.
+# ---------------------------------------------------------------------------------------
+GIT_CLEAN_ARGV = ("clean", "-fd")
+
+# Never run, in any form, including a read-only `git config --get user.email`.
+FORBIDDEN_GIT_SUBCOMMANDS = frozenset({"config"})
+
+# Content-verified after the reset when the target ref carries them (see verify_content()).
+SENTINEL_PATHS = ("scripts/todo-next-id.py", "scripts/todo-status-audit.py")
+SENTINEL_SAMPLE_SIZE = 5
+
+WAVE_TOKEN_RE = re.compile(r"\bWAVE-\d{4}\b")
+CU_BRANCH_PREFIX = "cu/"
+
+
+class GitGuardViolation(RuntimeError):
+    """A git invocation was refused before it ran. Always a bug in this script, never input."""
+
+
+class BoardError(RuntimeError):
+    """repos.md could not be read or parsed. Fail closed: nothing is touched."""
+
+
+class ResetFailed(RuntimeError):
+    """A step of the reset, or its verification, failed for one clone."""
+
+
+def _real(path: Path | str) -> Path:
+    """Resolve to a real path (expanding ~, following symlinks, collapsing '..')."""
+    return Path(os.path.realpath(os.path.expanduser(str(path))))
+
+
+CANONICAL_REAL = frozenset(_real(p) for p in CANONICAL_TREES)
+
+
+# ---------------------------------------------------------------------------------------
+# The single git choke point.
+# ---------------------------------------------------------------------------------------
+def _git(clone: Path, argv: list[str], *, check: bool = True) -> subprocess.CompletedProcess:
+    """
+    Run `git -C <clone> <argv>` after the guards that must hold for EVERY git invocation.
+
+    Every git call in this script goes through here, which is what makes the guards properties
+    of the script rather than habits of its callers:
+
+      * a canonical tree is never the working directory of any git command,
+      * `git config` never runs, in any form,
+      * `git clean` runs only as GIT_CLEAN_ARGV,
+      * no argv carries an -x/-X style token (redundant with the clean rule on purpose).
+
+    A violation raises rather than returning an error, because every one of them is a
+    programming mistake in this file, not a condition to recover from.
+    """
+    if not argv:
+        raise GitGuardViolation("empty git argv")
+
+    subcommand = argv[0]
+    if subcommand in FORBIDDEN_GIT_SUBCOMMANDS:
+        raise GitGuardViolation(f"refusing to run `git {subcommand}`: forbidden by the wave skill")
+
+    if subcommand == "clean" and tuple(argv) != GIT_CLEAN_ARGV:
+        raise GitGuardViolation(
+            f"refusing `git {' '.join(argv)}`: clean may only run as `git {' '.join(GIT_CLEAN_ARGV)}`"
+        )
+
+    for token in argv:
+        if _is_untracked_ignored_flag(token):
+            raise GitGuardViolation(
+                f"refusing `git {' '.join(argv)}`: that flag reaches gitignored files (.work/)"
+            )
+
+    real = _real(clone)
+    if real in CANONICAL_REAL:
+        raise GitGuardViolation(f"refusing to run git in a canonical tree: {real}")
+
+    return subprocess.run(
+        ["git", "-C", str(clone), *argv],
+        check=check,
+        capture_output=True,
+        text=True,
+    )
+
+
+def _is_untracked_ignored_flag(token: str) -> bool:
+    """
+    True for the flags that would widen a git command onto gitignored files.
+
+    Spelled as a character test rather than a literal list so that a bundled short form
+    (-fdx, -fdX) is caught as well as the standalone flag.
+    """
+    ignored_letters = {"x", "X"}
+    if token in {f"-{letter}" for letter in ignored_letters}:
+        return True
+    if token.startswith("-") and not token.startswith("--"):
+        return bool(set(token[1:]) & ignored_letters)
+    return False
+
+
+def _git_clean(clone: Path) -> subprocess.CompletedProcess:
+    """
+    Step 6. Takes no flag argument BY DESIGN -- there is no parameter through which a caller
+    could pass -x, which is why this is a function rather than an inline _git() call.
+    """
+    return _git(clone, list(GIT_CLEAN_ARGV))
+
+
+def _git_out(clone: Path, argv: list[str]) -> str:
+    return _git(clone, argv).stdout.strip()
+
+
+# ---------------------------------------------------------------------------------------
+# The board.
+# ---------------------------------------------------------------------------------------
+@dataclass(frozen=True)
+class BoardRow:
+    index: int  # 0-based index into the board's lines, so a row can be rewritten in place
+    raw: str
+    path_cell: str
+    path: Path
+    real: Path
+    project: str
+    role: str
+    branch: str
+    session: str
+    status: str
+
+    @property
+    def name(self) -> str:
+        return self.path.name
+
+    @property
+    def pool(self) -> str | None:
+        return PROJECT_TO_POOL.get(self.project)
+
+    @property
+    def is_canonical_row(self) -> bool:
+        return "canonical" in self.role.lower()
+
+
+def _cells(line: str) -> list[str] | None:
+    """Split a markdown table row into its cells, or None if the line is not a table row."""
+    stripped = line.strip()
+    if not stripped.startswith("|") or not stripped.endswith("|"):
+        return None
+    return [cell.strip() for cell in stripped[1:-1].split("|")]
+
+
+def parse_board(text: str) -> list[BoardRow]:
+    """
+    Parse the clone-assignment table out of repos.md.
+
+    Fails closed on anything unexpected. An unreadable or surprising board must never be
+    interpreted as an empty one: "no rows" would read as "no clone is in flight", which is the
+    fail-open version of the in-flight guard.
+    """
+    lines = text.splitlines()
+    header_index = None
+    for i, line in enumerate(lines):
+        cells = _cells(line)
+        if cells and tuple(cell.lower() for cell in cells) == BOARD_COLUMNS:
+            header_index = i
+            break
+
+    if header_index is None:
+        raise BoardError(
+            "no clone-assignment table found: expected a header row "
+            f"| {' | '.join(BOARD_COLUMNS)} |"
+        )
+
+    separator = _cells(lines[header_index + 1]) if header_index + 1 < len(lines) else None
+    if not separator or not all(set(cell) <= set("-: ") and cell for cell in separator):
+        raise BoardError("clone-assignment table header is not followed by a separator row")
+
+    rows: list[BoardRow] = []
+    for i in range(header_index + 2, len(lines)):
+        cells = _cells(lines[i])
+        if cells is None:
+            break  # the table ends at the first non-table line
+        if len(cells) != len(BOARD_COLUMNS):
+            raise BoardError(
+                f"repos.md line {i + 1} has {len(cells)} cells, expected {len(BOARD_COLUMNS)}: {lines[i]!r}"
+            )
+        path_cell = cells[0]
+        bare = path_cell.strip().strip("`").strip()
+        if not bare:
+            raise BoardError(f"repos.md line {i + 1} has an empty path cell")
+        path = Path(os.path.expanduser(bare))
+        rows.append(
+            BoardRow(
+                index=i,
+                raw=lines[i],
+                path_cell=path_cell,
+                path=path,
+                real=_real(path),
+                project=cells[1],
+                role=cells[2],
+                branch=cells[3].strip("`"),
+                session=cells[4],
+                status=cells[5],
+            )
+        )
+
+    if not rows:
+        raise BoardError("clone-assignment table has no rows")
+    return rows
+
+
+def load_board(board_path: Path) -> tuple[str, list[BoardRow]]:
+    try:
+        text = board_path.read_text(encoding="utf-8")
+    except OSError as exc:
+        raise BoardError(f"cannot read {board_path}: {exc}") from exc
+    except UnicodeDecodeError as exc:
+        raise BoardError(f"cannot decode {board_path} as UTF-8: {exc}") from exc
+    return text, parse_board(text)
+
+
+# ---------------------------------------------------------------------------------------
+# Assessment: every guard, evaluated before anything is touched.
+# ---------------------------------------------------------------------------------------
+@dataclass
+class Assessment:
+    row: BoardRow
+    pool: str | None = None
+    branch: str | None = None
+    refusals: list[tuple[str, str]] = field(default_factory=list)  # (code, detail)
+    remotes: dict[str, str] = field(default_factory=dict)
+    canonical_remotes: list[str] = field(default_factory=list)
+    dirty: list[str] = field(default_factory=list)
+    cu_branches: list[str] = field(default_factory=list)
+    current_branch: str | None = None
+    current_target_sha: str | None = None  # remote-tracking sha BEFORE any fetch
+
+    @property
+    def ok(self) -> bool:
+        return not self.refusals
+
+    def refuse(self, code: str, detail: str) -> None:
+        self.refusals.append((code, detail))
+
+
+def assess_static(row: BoardRow, canonical_real: frozenset[Path]) -> Assessment:
+    """Guards that need no git and no filesystem writes. Ordered cheapest-and-hardest first."""
+    a = Assessment(row=row)
+
+    if row.real in CANONICAL_REAL:
+        a.refuse("canonical_tree", f"{row.real} is a canonical tree (hardcoded); never reset")
+    if row.real in canonical_real:
+        a.refuse("canonical_row", f"repos.md marks {row.path_cell} role={row.role!r}")
+
+    pool = row.pool
+    if pool is None or row.role not in SELECTABLE_ROLES:
+        a.refuse(
+            "not_a_side_clone",
+            f"project={row.project!r} role={row.role!r} is not a selectable side clone",
+        )
+    else:
+        a.pool = pool
+        a.branch = POOL_DEFAULT_BRANCH[pool]
+
+    status = row.status.strip().lower()
+    if status == "in-flight":
+        a.refuse("in_flight", "repos.md marks this clone in-flight; a subagent is using it")
+    if status == "do-not-use":
+        a.refuse("do_not_use", "repos.md marks this clone do-not-use")
+
+    wave = WAVE_TOKEN_RE.search(row.session)
+    if wave:
+        a.refuse(
+            "board_inconsistent",
+            f"session cell still carries a wave assignment ({wave.group(0)}) while status is "
+            f"{row.status!r}; clear the assignment on the board first",
+        )
+
+    if not row.path.is_dir():
+        a.refuse("missing_directory", f"{row.path} does not exist")
+
+    return a
+
+
+def assess_git(a: Assessment) -> Assessment:
+    """Read-only git guards. Not reached if a static guard already refused."""
+    row = a.row
+    try:
+        toplevel = _git_out(row.path, ["rev-parse", "--show-toplevel"])
+    except (subprocess.CalledProcessError, GitGuardViolation) as exc:
+        a.refuse("not_a_git_worktree", f"{row.path}: {exc}")
+        return a
+
+    if _real(toplevel) != row.real:
+        a.refuse(
+            "not_worktree_root",
+            f"{row.path} is inside {toplevel}, not its own worktree root",
+        )
+        return a
+
+    a.current_branch = _git_out(row.path, ["rev-parse", "--abbrev-ref", "HEAD"])
+
+    for line in _git_out(row.path, ["remote"]).splitlines():
+        remote = line.strip()
+        if not remote:
+            continue
+        a.remotes[remote] = _git_out(row.path, ["remote", "get-url", remote])
+
+    _check_remote_crossing(a)
+    if not a.ok:
+        return a
+
+    a.canonical_remotes = _canonical_remote_candidates(a)
+    if not a.canonical_remotes:
+        a.refuse("no_remote", "clone has no remotes to fetch from")
+        return a
+
+    a.dirty = [line for line in _git_out(row.path, ["status", "--porcelain"]).splitlines() if line]
+    if a.dirty:
+        staged = sum(1 for line in a.dirty if line[:1] not in {" ", "?"})
+        a.refuse(
+            "dirty",
+            f"{len(a.dirty)} uncommitted path(s), {staged} staged -- reporting instead of "
+            "resetting over them",
+        )
+        return a
+
+    a.cu_branches = [
+        b.strip()
+        for b in _git_out(row.path, ["for-each-ref", "--format=%(refname:short)", f"refs/heads/{CU_BRANCH_PREFIX}*"]).splitlines()
+        if b.strip()
+    ]
+
+    a.current_target_sha = _existing_remote_tracking_sha(a)
+    return a
+
+
+def _check_remote_crossing(a: Assessment) -> None:
+    """
+    Refuse a clone whose remote is a local path inside another project's canonical tree.
+
+    This is "IRS clones must never be crossed with Apache remotes" made mechanical, in both
+    directions. A crossing cannot originate in this script -- fetches only ever name a remote
+    the clone already has, and `git config` never runs, so no remote is ever created or
+    repointed here -- but one configured by hand elsewhere would be silently honoured by a
+    fetch, so it is refused instead.
+    """
+    own_canonical = _canonical_for_pool(a.pool)
+    for remote, url in a.remotes.items():
+        local = _local_remote_path(url)
+        if local is None:
+            continue
+        for pool, canonical in _pool_canonicals().items():
+            if local == canonical or canonical in local.parents:
+                if own_canonical is None or canonical != own_canonical:
+                    a.refuse(
+                        "remote_crossing",
+                        f"remote {remote!r} -> {url} resolves into the {pool} canonical tree "
+                        f"while this clone is in the {a.pool} pool",
+                    )
+                break
+
+
+def _pool_canonicals() -> dict[str, Path]:
+    """Pool -> canonical tree real path, derived from CANONICAL_TREES by pool default branch."""
+    by_name = {p.name: p for p in CANONICAL_TREES}
+    return {
+        "juneau": _real(by_name["juneau"]),
+        "irs": _real(by_name["irs-1"]),
+        "console": _real(by_name["sandbox-support-console"]),
+    }
+
+
+def _canonical_for_pool(pool: str | None) -> Path | None:
+    return _pool_canonicals().get(pool) if pool else None
+
+
+def _local_remote_path(url: str) -> Path | None:
+    """Real path of a remote URL that names a local directory, else None (an ssh/https URL)."""
+    if "://" in url or re.match(r"^[^/]+@[^/]+:", url):
+        return None
+    candidate = Path(os.path.expanduser(url))
+    if not candidate.is_absolute():
+        return None
+    real = _real(candidate)
+    if real.name == ".git":
+        real = real.parent
+    return real
+
+
+def _canonical_remote_candidates(a: Assessment) -> list[str]:
+    """
+    The remotes that could carry the canonical branch, in preference order.
+
+    `origin` always counts (step 2 names it). Console clones also carry a second remote pointing
+    at the local canonical console tree, which the skill mentions as "the local-canonical remote
+    if present" -- included here so a disagreement between the two is detected rather than
+    silently resolved in favour of whichever this script happened to prefer.
+    """
+    own_canonical = _canonical_for_pool(a.pool)
+    candidates = ["origin"] if "origin" in a.remotes else []
+    for remote, url in sorted(a.remotes.items()):
+        if remote == "origin":
+            continue
+        local = _local_remote_path(url)
+        if local is not None and own_canonical is not None and local == own_canonical:
+            candidates.append(remote)
+    return candidates
+
+
+def _existing_remote_tracking_sha(a: Assessment) -> str | None:
+    """Current (pre-fetch) sha of <origin>/<branch>, for the dry-run report only."""
+    for remote in a.canonical_remotes:
+        try:
+            return _git_out(a.row.path, ["rev-parse", "--verify", f"{remote}/{a.branch}"])
+        except subprocess.CalledProcessError:
+            continue
+    return None
+
+
+# ---------------------------------------------------------------------------------------
+# .work/ preservation.
+# ---------------------------------------------------------------------------------------
+@dataclass
+class WorkBackup:
+    src: Path
+    dest: Path
+    root: Path
+    files: int
+
+
+def backup_work(clone: Path) -> WorkBackup | None:
+    """
+    Copy the clone's .work/ out of the tree before anything touches it (the skill's git-safety
+    rule: back up .work/ before checkout/reset, restore after).
+
+    The copy lands in the system temp directory -- outside the clone -- so it cannot itself be
+    reached by anything running inside the clone.
+    """
+    src = clone / ".work"
+    if not src.is_dir():
+        return None
+    root = Path(tempfile.mkdtemp(prefix="reset-side-clones-work-"))
+    dest = root / ".work"
+    shutil.copytree(src, dest, symlinks=True)
+    return WorkBackup(src=src, dest=dest, root=root, files=_count_files(dest))
+
+
+def _count_files(root: Path) -> int:
+    return sum(1 for p in root.rglob("*") if p.is_file())
+
+
+def _relative_files(root: Path) -> list[Path]:
+    return sorted(p.relative_to(root) for p in root.rglob("*") if p.is_file())
+
+
+def restore_work(backup: WorkBackup | None) -> tuple[list[Path], bool]:
+    """
+    Put back anything under .work/ that did not survive, then verify.
+
+    Returns (restored paths, verified). `git clean -fd` leaves gitignored files alone, so in
+    practice nothing needs restoring and this is the check that proves it rather than assuming
+    it. The backup directory is deleted only when the post-reset .work/ is byte-identical to it;
+    otherwise it is kept and its location reported.
+    """
+    if backup is None:
+        return [], True
+
+    restored: list[Path] = []
+    for rel in _relative_files(backup.dest):
+        target = backup.src / rel
+        if not target.exists():
+            target.parent.mkdir(parents=True, exist_ok=True)
+            shutil.copy2(backup.dest / rel, target)
+            restored.append(rel)
+
+    verified = _trees_identical(backup.dest, backup.src)
+    if verified:
+        shutil.rmtree(backup.root, ignore_errors=True)
+    return restored, verified
+
+
+def _trees_identical(a: Path, b: Path) -> bool:
+    files_a, files_b = _relative_files(a), _relative_files(b)
+    if files_a != files_b:
+        return False
+    return all(filecmp.cmp(a / rel, b / rel, shallow=False) for rel in files_a)
+
+
+# ---------------------------------------------------------------------------------------
+# The reset itself (steps 2-6) and its verification.
+# ---------------------------------------------------------------------------------------
+@dataclass
+class ResetResult:
+    target_ref: str
+    target_sha: str
+    fetched: list[str]
+    deleted_cu: list[str]
+    kept_cu: list[str]
+    work_restored: list[Path]
+    verified_paths: list[str]
+    verify_note: str
+
+
+def reset_clone(a: Assessment) -> ResetResult:
+    """Steps 2-6 in the skill's order, then verification. Raises ResetFailed on any problem."""
+    clone, branch = a.row.path, a.branch
+    assert branch is not None  # guaranteed by assess_static
+
+    backup = backup_work(clone)
+
+    try:
+        # Step 2 -- fetch. Only ever a remote name the clone already has; never a URL, so this
+        # cannot introduce a remote or cross two projects' remotes.
+        fetched = []
+        for remote in a.canonical_remotes:
+            try:
+                _git(clone, ["fetch", remote])
+            except subprocess.CalledProcessError as exc:
+                raise ResetFailed(f"git fetch {remote} failed: {_stderr(exc)}") from exc
+            fetched.append(remote)
+
+        target_ref, target_sha = _resolve_target(a)
+
+        # Step 3 -- checkout the pool's default branch.
+        if _branch_exists(clone, branch):
+            try:
+                _git(clone, ["checkout", branch])
+            except subprocess.CalledProcessError as exc:
+                raise ResetFailed(f"git checkout {branch} failed: {_stderr(exc)}") from exc
+        else:
+            try:
+                _git(clone, ["checkout", "-b", branch, target_ref])
+            except subprocess.CalledProcessError as exc:
+                raise ResetFailed(f"git checkout -b {branch} {target_ref} failed: {_stderr(exc)}") from exc
+
+        # Step 4 -- reset --hard to the canonical remote-tracking branch.
+        try:
+            _git(clone, ["reset", "--hard", target_ref])
+        except subprocess.CalledProcessError as exc:
+            raise ResetFailed(f"git reset --hard {target_ref} failed: {_stderr(exc)}") from exc
+
+        # Step 5 -- leftover cu/* branches, only when provably safe (see _delete_cu_branches).
+        deleted_cu, kept_cu = _delete_cu_branches(a, target_ref, branch)
+
+        # Step 6 -- clean, in its only permitted form.
+        try:
+            _git_clean(clone)
+        except subprocess.CalledProcessError as exc:
+            raise ResetFailed(f"git clean failed: {_stderr(exc)}") from exc
+
+    finally:
+        work_restored, work_verified = restore_work(backup)
+
+    if backup is not None and not work_verified:
+        raise ResetFailed(f".work/ did not survive byte-identical; backup kept at {backup.dest}")
+
+    head = _git_out(clone, ["rev-parse", "HEAD"])
+    if head != target_sha:
+        raise ResetFailed(f"HEAD is {head}, expected {target_sha}")
+
+    residue = [line for line in _git_out(clone, ["status", "--porcelain"]).splitlines() if line]
+    if residue:
+        raise ResetFailed(f"working tree still not clean after reset: {residue[:5]}")
+
+    verified_paths, note = verify_content(clone, target_ref)
+
+    return ResetResult(
+        target_ref=target_ref,
+        target_sha=target_sha,
+        fetched=fetched,
+        deleted_cu=deleted_cu,
+        kept_cu=kept_cu,
+        work_restored=work_restored,
+        verified_paths=verified_paths,
+        verify_note=note,
+    )
+
+
+def _stderr(exc: subprocess.CalledProcessError) -> str:
+    """Last meaningful line of a failed git command, for a one-line report."""
+    lines = ((exc.stderr or "") + "\n" + (exc.stdout or "")).strip().splitlines()
+    return lines[-1].strip() if lines else str(exc)
+
+
+def _resolve_target(a: Assessment) -> tuple[str, str]:
+    """
+    The ref to reset to, and its sha.
+
+    A Console clone can have both `origin` (the remote) and a local-canonical remote. The skill
+    says to reset to "origin/main or the local-canonical remote's main" without saying which
+    wins, so when the two disagree this refuses and reports both shas rather than picking one.
+    Choosing silently is exactly the kind of guess that makes a wave boundary untrustworthy.
+    """
+    seen: dict[str, str] = {}
+    for remote in a.canonical_remotes:
+        ref = f"{remote}/{a.branch}"
+        try:
+            seen[ref] = _git_out(a.row.path, ["rev-parse", "--verify", ref])
+        except subprocess.CalledProcessError:
+            continue
+
+    if not seen:
+        raise ResetFailed(
+            f"no canonical remote-tracking branch found (looked for "
+            f"{', '.join(f'{r}/{a.branch}' for r in a.canonical_remotes)})"
+        )
+
+    if len(set(seen.values())) > 1:
+        detail = ", ".join(f"{ref}={sha[:10]}" for ref, sha in sorted(seen.items()))
+        raise ResetFailed(
+            f"canonical remotes disagree on {a.branch} ({detail}); which one is canonical is an "
+            "operator decision, so nothing was reset"
+        )
+
+    # They agree, so any of them names the same commit; report the one step 4 names first.
+    ref = next(f"{remote}/{a.branch}" for remote in a.canonical_remotes if f"{remote}/{a.branch}" in seen)
+    return ref, seen[ref]
+
+
+def _branch_exists(clone: Path, branch: str) -> bool:
+    try:
+        _git(clone, ["rev-parse", "--verify", f"refs/heads/{branch}"])
+        return True
+    except subprocess.CalledProcessError:
+        return False
+
+
+def _delete_cu_branches(a: Assessment, target_ref: str, branch: str) -> tuple[list[str], list[str]]:
+    """
+    Step 5, restricted to the part a script can prove.
+
+    The skill permits deleting a leftover cu/* branch when it is "already harvested". No script
+    can determine that -- harvest lands as UNSTAGED files on canonical, so a harvested slice is
+    not reachable from any ref. What is mechanically provable is containment: a cu/* branch whose
+    tip is an ancestor of the target ref holds nothing unique, so deleting it cannot lose work.
+    Anything else is reported and left alone for a human, because `git branch -D` on a branch
+    with unique commits is unrecoverable in the way this script exists to prevent.
+    """
+    deleted: list[str] = []
+    kept: list[str] = []
+    worktree_branches = _branches_in_other_worktrees(a.row.path)
+
+    for cu in a.cu_branches:
+        if cu == branch or cu in worktree_branches:
+            kept.append(f"{cu} (checked out)")
+            continue
+        try:
+            _git(a.row.path, ["merge-base", "--is-ancestor", cu, target_ref])
+        except subprocess.CalledProcessError:
+            kept.append(f"{cu} (has commits not in {target_ref}; cannot prove it was harvested)")
+            continue
+        try:
+            _git(a.row.path, ["branch", "-d", cu])
+        except subprocess.CalledProcessError as exc:
+            kept.append(f"{cu} (delete refused: {_stderr(exc)})")
+            continue
+        deleted.append(cu)
+
+    return deleted, kept
+
+
+def _branches_in_other_worktrees(clone: Path) -> set[str]:
+    out = _git_out(clone, ["worktree", "list", "--porcelain"])
+    return {
+        line.split(" ", 1)[1].strip().removeprefix("refs/heads/")
+        for line in out.splitlines()
+        if line.startswith("branch ")
+    }
+
+
+def verify_content(clone: Path, target_ref: str) -> tuple[list[str], str]:
+    """
+    Compare real file CONTENT against the canonical blob, not the commit hash.
+
+    `git hash-object` re-hashes the bytes actually on disk; `git rev-parse <ref>:<path>` is the
+    blob id the fetched canonical commit records for that path. Equal ids mean the file on disk
+    IS the canonical file. A matching HEAD proves only that a ref moved, which is why the manual
+    version of this check was what made the nine-clone report trustworthy.
+
+    SENTINEL_PATHS are used when the target ref carries them. When it carries none, a
+    deterministic sample of the tree is used instead -- "there was nothing to verify" must never
+    be reportable as a pass.
+    """
+    present = [p for p in SENTINEL_PATHS if _blob_id(clone, target_ref, p) is not None]
+    note = "declared sentinels"
+    if not present:
+        listing = _git_out(clone, ["ls-tree", "-r", "--name-only", target_ref]).splitlines()
+        present = sorted(listing)[:SENTINEL_SAMPLE_SIZE]
+        note = f"no declared sentinel in {target_ref}; deterministic sample of the tree"
+
+    if not present:
+        raise ResetFailed(f"{target_ref} is empty: nothing could be content-verified")
+
+    for path in present:
+        expected = _blob_id(clone, target_ref, path)
+        actual = _git_out(clone, ["hash-object", "--", path])
+        if expected != actual:
+            raise ResetFailed(
+                f"content mismatch for {path}: on disk {actual[:10]}, canonical {str(expected)[:10]}"
+            )
+    return present, note
+
+
+def _blob_id(clone: Path, ref: str, path: str) -> str | None:
+    try:
+        return _git_out(clone, ["rev-parse", "--verify", f"{ref}:{path}"])
+    except subprocess.CalledProcessError:
+        return None
+
+
+# ---------------------------------------------------------------------------------------
+# Step 7 -- the board row.
+# ---------------------------------------------------------------------------------------
+def render_row(raw: str, branch: str, status: str) -> str:
+    """
+    Rewrite one board row's branch / session / status cells, leaving every other byte alone.
+
+    Operates on the original line's own `|` split so the surrounding prose, the other columns,
+    and the file's spacing style are untouched.
+    """
+    parts = raw.split("|")
+    if len(parts) != len(BOARD_COLUMNS) + 2:
+        raise BoardError(f"cannot rewrite malformed row: {raw!r}")
+    parts[4] = f" `{branch}` "
+    parts[5] = " "
+    parts[6] = f" {status} "
+    return "|".join(parts)
+
+
+def write_board(board_path: Path, updates: dict[int, str]) -> None:
+    """
+    Install row rewrites atomically, refusing anything that would mangle the board.
+
+    Concurrency: a sibling lock file created with O_CREAT|O_EXCL. A held lock is NOT stolen and
+    no stale-lock heuristic is applied -- the caller reports the needed change instead, because a
+    mangled shared board is worse than a row someone has to fix by hand.
+
+    Safety: the rewritten text is re-parsed and compared line by line against the original, and
+    the write is refused unless exactly the intended lines changed.
+    """
+    lock = board_path.with_name(board_path.name + ".lock")
+    try:
+        fd = os.open(str(lock), os.O_CREAT | os.O_EXCL | os.O_WRONLY, 0o644)
+    except FileExistsError as exc:
+        raise BoardError(f"{lock} is held by another writer; not touching the board") from exc
+    try:
+        os.write(fd, f"{os.getpid()}\n".encode())
+        os.close(fd)
+
+        original = board_path.read_text(encoding="utf-8")
+        lines = original.splitlines(keepends=True)
+        for index, new_line in updates.items():
+            if index >= len(lines):
+                raise BoardError("board changed under us: row index out of range")
+            ending = "\n" if lines[index].endswith("\n") else ""
+            lines[index] = new_line + ending
+
+        updated = "".join(lines)
+        _assert_only_intended_lines_changed(original, updated, set(updates))
+        parse_board(updated)  # a rewrite that no longer parses is never installed
+
+        tmp = board_path.with_name(board_path.name + f".tmp.{os.getpid()}")
+        tmp.write_text(updated, encoding="utf-8")
+        os.replace(tmp, board_path)
+    finally:
+        lock.unlink(missing_ok=True)
+
+
+def _assert_only_intended_lines_changed(original: str, updated: str, intended: set[int]) -> None:
+    before, after = original.splitlines(), updated.splitlines()
+    if len(before) != len(after):
+        raise BoardError("refusing to write: line count changed")
+    changed = {i for i, (b, a) in enumerate(zip(before, after)) if b != a}
+    if not changed <= intended:
+        raise BoardError(f"refusing to write: unintended lines would change: {sorted(changed - intended)}")
+
+
+# ---------------------------------------------------------------------------------------
+# Selection.
+# ---------------------------------------------------------------------------------------
+def select_rows(rows: list[BoardRow], *, all_pools: bool, pools: list[str], names: list[str]) -> list[BoardRow]:
+    """Resolve the requested selection to board rows. Raises SystemExit(4) on a usage error."""
+    selected: dict[int, BoardRow] = {}
+
+    wanted_pools = list(POOLS_IN_ALL) if all_pools else []
+    for pool in pools:
+        if pool not in POOL_DEFAULT_BRANCH:
+            _usage_error(f"unknown pool {pool!r}; known pools: {', '.join(sorted(POOL_DEFAULT_BRANCH))}")
+        if pool not in wanted_pools:
+            wanted_pools.append(pool)
+
+    for row in rows:
+        if row.pool in wanted_pools and row.role in SELECTABLE_ROLES:
+            selected[row.index] = row
+
+    for name in names:
+        matches = [r for r in rows if r.name == name or r.real == _real(name) or r.path_cell.strip("`") == name]
+        if not matches:
+            _usage_error(
+                f"{name!r} is not a row in the board. Only clones the board knows about can be "
+                "selected; add it there first."
+            )
+        if len(matches) > 1:
+            _usage_error(f"{name!r} matches {len(matches)} board rows; use the full path")
+        selected[matches[0].index] = matches[0]
+
+    return [selected[i] for i in sorted(selected)]
+
+
+def _usage_error(message: str) -> None:
+    print(f"error: {message}", file=sys.stderr)
+    raise SystemExit(4)
+
+
+# ---------------------------------------------------------------------------------------
+# Reporting.
+# ---------------------------------------------------------------------------------------
+def print_plan(a: Assessment) -> None:
+    row = a.row
+    print(f"\n{row.name}  ({row.path})  pool={a.pool}")
+    if not a.ok:
+        for code, detail in a.refusals:
+            print(f"  REFUSED [{code}] {detail}")
+        if a.dirty:
+            for line in a.dirty[:10]:
+                print(f"    {line}")
+            if len(a.dirty) > 10:
+                print(f"    ... {len(a.dirty) - 10} more")
+        return
+
+    target = f"{a.canonical_remotes[0]}/{a.branch}"
+    sha = a.current_target_sha[:10] if a.current_target_sha else "(unknown until fetched)"
+    print(f"  on branch:  {a.current_branch}   clean")
+    for remote in a.canonical_remotes:
+        print(f"  would run:  git -C {row.name} fetch {remote}")
+    print(f"  would run:  git -C {row.name} checkout {a.branch}")
+    print(f"  would run:  git -C {row.name} reset --hard {target}     (currently {sha}, re-resolved after fetch)")
+    print(f"  would run:  git -C {row.name} {' '.join(GIT_CLEAN_ARGV)}     (never -x; .work/ preserved)")
+    if a.cu_branches:
+        print(f"  cu/* branches:  {', '.join(a.cu_branches)}  (deleted only if contained in the target ref)")
+    else:
+        print("  cu/* branches:  none")
+    work = row.path / ".work"
+    print(f"  .work/:  {'backed up and verified after' if work.is_dir() else 'absent'}")
+    print(f"  would verify content of:  {', '.join(SENTINEL_PATHS)}  (blob hash vs canonical)")
+    print(f"  would set board row:  branch=`{a.branch}`  session=(empty)  status=idle")
+    if row.session.strip():
+        print(f"  NOTE: clearing a non-empty session cell: {row.session.strip()!r}")
+
+
+def print_result(a: Assessment, result: ResetResult) -> None:
+    row = a.row
+    print(f"\n{row.name}  ({row.path})  pool={a.pool}")
+    print(f"  fetched:   {', '.join(result.fetched)}")
+    print(f"  reset to:  {result.target_ref}  {result.target_sha[:10]}")
+    print(f"  cleaned:   git {' '.join(GIT_CLEAN_ARGV)}")
+    print(f"  .work/:    preserved and verified"
+          f"{f' ({len(result.work_restored)} entries restored)' if result.work_restored else ''}")
+    if result.deleted_cu:
+        print(f"  cu/* deleted (contained in target): {', '.join(result.deleted_cu)}")
+    for kept in result.kept_cu:
+        print(f"  cu/* KEPT for a human: {kept}")
+    print(f"  content verified ({result.verify_note}): {', '.join(result.verified_paths)}")
+
+
+# ---------------------------------------------------------------------------------------
+def main(argv: list[str] | None = None) -> int:
+    parser = argparse.ArgumentParser(
+        prog="reset-side-clones.py",
+        description="Reset harvested WAVE side clones to a fresh default branch (dry run unless --apply).",
+        formatter_class=argparse.RawDescriptionHelpFormatter,
+        epilog=f"Pools: {', '.join(sorted(POOL_DEFAULT_BRANCH))}. --all covers {', '.join(POOLS_IN_ALL)}.",
+    )
+    parser.add_argument("--all", action="store_true", help=f"every side clone in the {', '.join(POOLS_IN_ALL)} pools")
+    parser.add_argument("--pool", action="append", default=[], metavar="NAME", help="pool to reset (repeatable)")
+    parser.add_argument("--clones", action="append", default=[], metavar="LIST", help="comma-separated board names (repeatable)")
+    parser.add_argument("--apply", action="store_true", help="actually perform the reset (default: dry run)")
+    parser.add_argument("--board", type=Path, default=BOARD_DEFAULT, help=f"repos.md to read (default: {BOARD_DEFAULT})")
+    parser.add_argument("--no-board-update", action="store_true", help="report the repos.md row change instead of writing it")
+    args = parser.parse_args(argv)
+
+    names = [n.strip() for group in args.clones for n in group.split(",") if n.strip()]
+    if not (args.all or args.pool or names):
+        _usage_error("nothing selected; pass --all, --pool <name>, or --clones <list>")
+
+    # Fail closed on the board BEFORE anything else. An unreadable board must never be read as
+    # "nothing is in flight".
+    try:
+        _, rows = load_board(args.board)
+    except BoardError as exc:
+        print(f"error: {exc}", file=sys.stderr)
+        print("Nothing was touched. The board is the in-flight guard; it must be readable.", file=sys.stderr)
+        return 2
+
+    canonical_real = frozenset(r.real for r in rows if r.is_canonical_row)
+    selection = select_rows(rows, all_pools=args.all, pools=args.pool, names=names)
+
+    mode = "APPLY" if args.apply else "DRY RUN (no flag given; nothing will be changed)"
+    print(f"reset-side-clones: {mode}")
+    print(f"board: {args.board}")
+    if args.all and "irs" not in args.pool:
+        print("note: --all covers the juneau and console pools. IRS clones are excluded; pass "
+              "--pool irs to include them (the skill keeps IRS a separate hat).")
+    if not selection:
+        print("no clones selected.")
+        return 0
+
+    assessments = []
+    for row in selection:
+        a = assess_static(row, canonical_real)
+        if a.ok:
+            a = assess_git(a)
+        assessments.append(a)
+
+    refused = [a for a in assessments if not a.ok]
+    actionable = [a for a in assessments if a.ok]
+
+    if not args.apply:
+        for a in assessments:
+            print_plan(a)
+        print(f"\n{len(actionable)} clone(s) would be reset, {len(refused)} refused. "
+              f"Re-run with --apply to act.")
+        return 1 if refused else 0
+
+    for a in refused:
+        print_plan(a)
+
+    failures: list[tuple[Assessment, str]] = []
+    board_updates: dict[int, str] = {}
+    succeeded: list[Assessment] = []
+
+    for a in actionable:
+        try:
+            result = reset_clone(a)
+        except (ResetFailed, GitGuardViolation) as exc:
+            print(f"\n{a.row.name}  ({a.row.path})")
+            print(f"  FAILED: {exc}")
+            failures.append((a, str(exc)))
+            continue
+        print_result(a, result)
+        succeeded.append(a)
+        assert a.branch is not None
+        board_updates[a.row.index] = render_row(a.row.raw, a.branch, "idle")
+
+    board_deferred = False
+    if board_updates and not args.no_board_update:
+        try:
+            write_board(args.board, board_updates)
+            print(f"\nboard: updated {len(board_updates)} row(s) in {args.board}")
+        except BoardError as exc:
+            board_deferred = True
+            print(f"\nboard: NOT updated -- {exc}")
+    elif board_updates:
+        board_deferred = True
+        print("\nboard: --no-board-update given; not written")
+
+    if board_deferred:
+        print("Apply these rows by hand (step 7):")
+        for index in sorted(board_updates):
+            print(f"  line {index + 1}: {board_updates[index]}")
+
+    print(f"\nsummary: {len(succeeded)} reset, {len(refused)} refused, {len(failures)} failed.")
+
+    if failures:
+        return 3
+    if board_deferred:
+        return 5
+    if refused:
+        return 1
+    return 0
+
+
+if __name__ == "__main__":
+    sys.exit(main())
diff --git a/scripts/tests/README.md b/scripts/tests/README.md
index 7f997dd6db..472708badf 100644
--- a/scripts/tests/README.md
+++ b/scripts/tests/README.md
@@ -1,8 +1,11 @@
 # scripts/tests/
 
-Pytest harness for `scripts/todo-next-id.py` and `scripts/todo-status-audit.py`. These two
-scripts have no other automated coverage today; everything here is hermetic (temp
-directories, synthetic fixture files) and never touches the real `~/Project Work` trackers.
+Pytest harness for the `scripts/` Python that has no other automated coverage:
+`todo-next-id.py`, `todo-status-audit.py`, and the two juneau-only scripts noted below
+(`push.py`'s tracker-audit gate and `reset-side-clones.py`). Everything here is hermetic --
+temp directories, synthetic fixture files, and real temporary git repositories built in
+fixtures -- and never touches the real `~/Project Work` trackers, the real `repos.md`, or the
+real side clones.
 
 ## Running
 
@@ -50,7 +53,30 @@ Do **not** `pip install --user pytest` / `pip install pytest` on a Homebrew-mana
   reaches `subprocess.run` at all -- not just that it returns early -- which is the strongest
   available proof the gate cannot affect push behavior, including runtime, while disabled.
 
-Every OTHER file in this directory (i.e. all of the above except `test_push.py`) is intended
-to be byte-for-byte identical across every repo that carries `todo-next-id.py` /
-`todo-status-audit.py` -- the tests derive the project's id letter and tracker slug from the
-scripts themselves rather than hardcoding them, so nothing here needs to differ between copies.
+- `test_reset_side_clones.py` -- **juneau-only exception** for the same reason: unlike the two
+  tracker scripts, `reset-side-clones.py` is not a per-project script. It reads the one global
+  `~/Project Work/repos.md` and drives clones by absolute path, so a single copy resets the
+  juneau, console, and IRS pools and there is nothing for a second copy to specialize. The
+  tests are about the guards, since that is where the script's value is: canonical-tree
+  refusal by resolved real path (including via a symlink and via a `..` path), `in-flight`
+  refusal, dirty/staged/untracked abort, fail-closed behavior on an unreadable or unparseable
+  board, and the unreachability of `git clean -x` and of `git config`. Those two are asserted
+  four ways -- the argv constant, a helper with no flag parameter at all, the wrapper refusing
+  every other spelling, and an audit of every argv from a real end-to-end apply. Refusals are
+  proven by monkeypatching `subprocess.run` to raise, so "it refused" means "no git ran"
+  rather than "the exit code was 1". Everything else builds real temporary git repositories
+  and lets real git run against them: a mocked test of a script whose entire risk is real git
+  behavior would prove almost nothing. Temp repos get their identity and config isolation from
+  environment variables, never `git config`, which is the same rule the script enforces.
+
+Every OTHER file in this directory (i.e. all of the above except `test_push.py` and
+`test_reset_side_clones.py`) is intended to be byte-for-byte identical across every repo that
+carries `todo-next-id.py` / `todo-status-audit.py` -- the tests derive the project's id letter
+and tracker slug from the scripts themselves rather than hardcoding them, so nothing here
+needs to differ between copies.
+
+**Intended** is not **actual**: the three copies of this README have diverged. Which repo is
+ahead of which, by exactly what text, and what restoring identity requires is recorded in
+`~/agents/AGENTS.md` under "Carried scripts (the three-repo set)" -- kept there rather than
+here because it is a fact about all three copies at once, and because a note in this file
+would itself be one of the things out of sync.
diff --git a/scripts/tests/test_push.py b/scripts/tests/test_push.py
index ed48d1167d..e676fcfc41 100644
--- a/scripts/tests/test_push.py
+++ b/scripts/tests/test_push.py
@@ -11,7 +11,8 @@
 # * specific language governing permissions and limitations under the License.
 # ***************************************************************************************************************************
 """
-Tests for the --tracker-audit opt-in gate in scripts/push.py.
+Tests for scripts/push.py: the --tracker-audit opt-in gate, and commit_and_push()'s
+clean-tree-vs-nothing-to-push distinction and pre-existing-staged-changes guard.
 
 Juneau-specific exception to this directory's usual byte-for-byte-identical-across-repos rule
 (see README.md): push.py's --sonarqube-style opt-in gate pattern only exists in juneau's
@@ -19,16 +20,25 @@ push.py (release-manager's push.py is a bare add/commit/push helper with no gate
 sandbox-support-console has no push.py). This file is therefore NOT copied to the other two
 repos, unlike everything else in scripts/tests/.
 
-The central property under test is the one the task explicitly demands: when --tracker-audit
-is not passed, the gate must be IMPOSSIBLE to observe at runtime -- not just "returns early",
-but never even reaches subprocess.run. test_off_path_never_invokes_subprocess pins that all
-the way down to the subprocess boundary.
+The --tracker-audit central property under test is the one the task that introduced it
+explicitly demanded: when --tracker-audit is not passed, the gate must be IMPOSSIBLE to observe
+at runtime -- not just "returns early", but never even reaches subprocess.run.
+test_off_path_never_invokes_subprocess pins that all the way down to the subprocess boundary.
+
+commit_and_push()'s tests build REAL temporary git repositories (a bare repo standing in for
+the GitHub remote, and a real clone of it) and let real git run against them, following the
+same pattern as test_reset_side_clones.py and for the same reason: this function's entire risk
+is real git behavior (does a push actually move the remote ref? does a refused commit actually
+leave the index untouched?), which a mocked subprocess would let pass while proving nothing.
+Temp repos get their identity and config isolation from environment variables, never `git
+config`. Nothing here ever touches the real juneau checkout or a real remote.
 """
 
 from __future__ import annotations
 
 import argparse
 import importlib.util
+import os
 import subprocess
 from pathlib import Path
 
@@ -57,6 +67,82 @@ def _args(tracker_audit: bool) -> argparse.Namespace:
     return argparse.Namespace(tracker_audit=tracker_audit)
 
 
+# ---------------------------------------------------------------------------------------
+# Real-git fixtures for commit_and_push() / check_upstream_changes() /
+# check_preexisting_staged_changes(). Mirrors test_reset_side_clones.py's hermetic_git_env
+# and _run/_commit helpers.
+# ---------------------------------------------------------------------------------------
+@pytest.fixture(autouse=True)
+def hermetic_git_env(monkeypatch):
+    """Isolate every git subprocess from the developer's real git configuration and identity."""
+    monkeypatch.setenv("GIT_CONFIG_GLOBAL", os.devnull)
+    monkeypatch.setenv("GIT_CONFIG_SYSTEM", os.devnull)
+    monkeypatch.setenv("GIT_AUTHOR_NAME", "Push Test")
+    monkeypatch.setenv("GIT_AUTHOR_EMAIL", "push-test@example.invalid")
+    monkeypatch.setenv("GIT_COMMITTER_NAME", "Push Test")
+    monkeypatch.setenv("GIT_COMMITTER_EMAIL", "push-test@example.invalid")
+    monkeypatch.setenv("GIT_TERMINAL_PROMPT", "0")
+
+
+def _run(cwd: Path, *argv: str) -> str:
+    result = subprocess.run(argv, cwd=str(cwd), check=True, capture_output=True, text=True)
+    return result.stdout.strip()
+
+
+def _commit(repo: Path, message: str) -> str:
+    _run(repo, "git", "add", "-A")
+    _run(repo, "git", "commit", "-m", message)
+    return _run(repo, "git", "rev-parse", "HEAD")
+
+
+@pytest.fixture
+def remote_repo(tmp_path: Path) -> Path:
+    """A bare repo standing in for the GitHub remote, so a real `git push` behaves like the real thing."""
+    bare = tmp_path / "remote.git"
+    _run(tmp_path, "git", "init", "--bare", "-b", "master", str(bare))
+    return bare
+
+
+@pytest.fixture
+def repo(tmp_path: Path, remote_repo: Path) -> Path:
+    """
+    A real clone of remote_repo on `master`, tracking origin/master, seeded with one commit
+    that is already pushed -- i.e. exactly the state a working tree is in right after a normal,
+    successful push: clean, and not ahead of its upstream.
+    """
+    seed = tmp_path / "seed"
+    seed.mkdir()
+    _run(seed, "git", "init", "-b", "master", ".")
+    (seed / "README.md").write_text("first\n", encoding="utf-8")
+    _commit(seed, "initial")
+    _run(seed, "git", "remote", "add", "origin", str(remote_repo))
+    _run(seed, "git", "push", "origin", "master")
+
+    work = tmp_path / "work"
+    _run(tmp_path, "git", "clone", str(remote_repo), str(work))
+    return work
+
+
+def _local_only_commit(repo_dir: Path, filename: str = "local.txt", message: str = "local work") -> str:
+    """Commit directly to `repo_dir` without pushing -- a branch ahead of its upstream."""
+    (repo_dir / filename).write_text("committed but never pushed\n", encoding="utf-8")
+    return _commit(repo_dir, message)
+
+
+@pytest.fixture
+def git_spy(push_module, monkeypatch):
+    """Record every argv passed to push_module.subprocess.run while still running real git."""
+    calls: list[list[str]] = []
+    real_run = subprocess.run
+
+    def _spy(cmd, *args, **kwargs):
+        calls.append(list(cmd) if isinstance(cmd, (list, tuple)) else [cmd])
+        return real_run(cmd, *args, **kwargs)
+
+    monkeypatch.setattr(push_module.subprocess, "run", _spy)
+    return calls
+
+
 class TestArgparseWiring:
     """The --tracker-audit / --todo-audit flag itself: default OFF, both spellings work."""
 
@@ -170,3 +256,221 @@ class TestRunTrackerAuditGateExitCodeMapping:
         assert captured["check"] is False
         assert captured["cmd"][0] == push_module.sys.executable
         assert captured["cmd"][1] == str(SCRIPTS_DIR / "todo-status-audit.py")
+
+
+class TestCheckUpstreamChangesAheadBehind:
+    """
+    check_upstream_changes() against real git: the ahead count is the fix, so it needs to be
+    right, not just the pre-existing behind count.
+    """
+
+    def test_clean_and_synced_is_zero_and_zero(self, push_module, repo):
+        ahead, behind, error = push_module.check_upstream_changes(repo)
+        assert (ahead, behind, error) == (0, 0, None)
+
+    def test_a_local_only_commit_is_one_ahead_zero_behind(self, push_module, repo):
+        _local_only_commit(repo)
+        ahead, behind, error = push_module.check_upstream_changes(repo)
+        assert (ahead, behind, error) == (1, 0, None)
+
+    def test_an_upstream_only_commit_is_zero_ahead_one_behind(self, push_module, tmp_path, repo, remote_repo):
+        other = tmp_path / "other-clone"
+        _run(tmp_path, "git", "clone", str(remote_repo), str(other))
+        _local_only_commit(other, filename="from-elsewhere.txt", message="pushed by someone else")
+        _run(other, "git", "push", "origin", "master")
+
+        ahead, behind, error = push_module.check_upstream_changes(repo)
+
+        assert (ahead, behind, error) == (0, 1, None)
+
+    def test_no_upstream_configured_is_none_none_none(self, push_module, tmp_path):
+        lone = tmp_path / "lone"
+        lone.mkdir()
+        _run(lone, "git", "init", "-b", "master", ".")
+        (lone / "f.txt").write_text("x\n", encoding="utf-8")
+        _commit(lone, "no remote at all")
+
+        ahead, behind, error = push_module.check_upstream_changes(lone)
+
+        assert (ahead, behind, error) == (None, None, None)
+
+
+class TestCheckPreexistingStagedChanges:
+    """The pre-flight check commit_and_push() uses to refuse committing over someone else's index state."""
+
+    def test_a_clean_index_reports_nothing(self, push_module, repo):
+        assert push_module.check_preexisting_staged_changes(repo) == []
+
+    def test_a_staged_file_is_reported(self, push_module, repo):
+        (repo / "staged.txt").write_text("staged by someone else\n", encoding="utf-8")
+        _run(repo, "git", "add", "staged.txt")
+
+        assert push_module.check_preexisting_staged_changes(repo) == ["staged.txt"]
+
+    def test_an_unstaged_modification_alone_is_not_reported(self, push_module, repo):
+        """Unstaged dirt is not what this guard is about -- only what's already IN the index."""
+        (repo / "README.md").write_text("unstaged edit\n", encoding="utf-8")
+        assert push_module.check_preexisting_staged_changes(repo) == []
+
+
+class TestCommitAndPushFalseSuccessRegression:
+    """
+    The defect: a clean working tree with unpushed local commits used to be reported as
+    "nothing to commit and push" (returning success) without ever running `git push`.
+
+    This is the test that fails against the pre-fix code: the pre-fix push.py checked only
+    `check_git_status()` (a clean tree) and returned success without consulting how far ahead
+    of upstream the branch was, so it would report success here while the remote never moved.
+    A test that only checked the return status/exit code would pass against that bug -- the
+    assertion that matters is that the remote ref ACTUALLY ADVANCED.
+    """
+
+    def test_clean_tree_with_unpushed_commits_actually_pushes(self, push_module, repo, remote_repo, git_spy):
+        local_head = _local_only_commit(repo)
+        assert push_module.check_git_status(repo) is False, "tree must be clean for this to be the regression case"
+
+        status, _ = push_module.commit_and_push(repo, "irrelevant message", 4)
+
+        assert status == "ok"
+        remote_head = _run(remote_repo, "git", "rev-parse", "master")
+        assert remote_head == local_head, "the remote must actually have moved, not just returned success"
+        assert any(argv[:2] == ["git", "push"] for argv in git_spy), "git push must actually have run"
+
+    def test_clean_tree_with_unpushed_commits_does_not_re_add_or_re_commit(self, push_module, repo, remote_repo, git_spy):
+        """A clean tree skips the COMMIT step -- there is nothing new to stage or commit."""
+        head_before = _local_only_commit(repo)
+        git_spy.clear()  # discard the setup commit above; only commit_and_push()'s own git calls matter here
+
+        status, _ = push_module.commit_and_push(repo, "irrelevant message", 4)
+
+        assert status == "ok"
+        assert _run(repo, "git", "rev-parse", "HEAD") == head_before, "no new commit should have been created"
+        assert not any(argv[:2] == ["git", "add"] for argv in git_spy)
+        assert not any(argv[:2] == ["git", "commit"] for argv in git_spy)
+
+    def test_reports_distinguishable_text_from_an_actual_no_op(self, push_module, repo, remote_repo, capsys):
+        """The output must never let a real push read like a no-op, or vice versa."""
+        _local_only_commit(repo)
+        push_module.commit_and_push(repo, "irrelevant message", 4)
+        pushed_output = capsys.readouterr().out
+
+        status, _ = push_module.commit_and_push(repo, "irrelevant message", 4)
+        noop_output = capsys.readouterr().out
+
+        assert status == "nothing_to_do"
+        assert "nothing to commit or push" in noop_output.lower()
+        assert "nothing to commit or push" not in pushed_output.lower()
+
+
+class TestCommitAndPushGenuineNoOp:
+    """Clean tree AND nothing ahead of upstream is the one case that is truly a no-op."""
+
+    def test_returns_nothing_to_do_and_touches_nothing(self, push_module, repo, remote_repo, git_spy):
+        remote_before = _run(remote_repo, "git", "rev-parse", "master")
+
+        status, step_num = push_module.commit_and_push(repo, "irrelevant message", 4)
+
+        assert status == "nothing_to_do"
+        assert step_num == 4, "step_num must be unchanged when nothing happened"
+        assert _run(remote_repo, "git", "rev-parse", "master") == remote_before
+        assert not any(argv[:2] == ["git", "push"] for argv in git_spy)
+        assert not any(argv[:2] == ["git", "add"] for argv in git_spy)
+
+
+class TestCommitAndPushDirtyTree:
+    """The ordinary path must keep working: a dirty tree still gets committed and pushed."""
+
+    def test_a_dirty_tree_is_committed_with_the_given_message_and_pushed(self, push_module, repo, remote_repo):
+        (repo / "README.md").write_text("new content\n", encoding="utf-8")
+
+        status, step_num = push_module.commit_and_push(repo, "the commit message", 4)
+
+        assert status == "ok"
+        assert step_num == 6, "one step for the commit, one for the push"
+        assert _run(repo, "git", "log", "-1", "--format=%s") == "the commit message"
+        assert _run(remote_repo, "git", "rev-parse", "master") == _run(repo, "git", "rev-parse", "HEAD")
+
+    def test_an_untracked_file_is_picked_up_too(self, push_module, repo, remote_repo):
+        """`git add .` staging genuinely-new untracked work is unchanged, documented behavior."""
+        (repo / "new-file.txt").write_text("brand new\n", encoding="utf-8")
+
+        status, _ = push_module.commit_and_push(repo, "add new file", 4)
+
+        assert status == "ok"
+        assert _run(remote_repo, "git", "show", "HEAD:new-file.txt") == "brand new"
+
+
+class TestCommitAndPushPreexistingStagedGuard:
+    """
+    Defect 2: `git add .` was unconditional, so anything unrelated already dirty (or, more
+    precisely, already staged -- since `git commit` commits the whole index regardless of what
+    THIS run's `git add .` stages) got swept into the commit. commit_and_push() now refuses
+    outright rather than guessing whether pre-existing staged content belongs to this push.
+    """
+
+    def test_preexisting_staged_content_aborts_before_any_add_commit_or_push(
+        self, push_module, repo, remote_repo, git_spy
+    ):
+        (repo / "unrelated.txt").write_text("staged by a concurrent session\n", encoding="utf-8")
+        _run(repo, "git", "add", "unrelated.txt")
+        (repo / "mine.txt").write_text("my own unstaged work\n", encoding="utf-8")
+        head_before = _run(repo, "git", "rev-parse", "HEAD")
+        remote_before = _run(remote_repo, "git", "rev-parse", "master")
+        git_spy.clear()  # discard the setup `git add` above; only commit_and_push()'s own git calls matter here
+
+        status, _ = push_module.commit_and_push(repo, "my commit message", 4)
+
+        assert status == "error"
+        assert _run(repo, "git", "rev-parse", "HEAD") == head_before, "nothing should have been committed"
+        assert _run(remote_repo, "git", "rev-parse", "master") == remote_before, "the remote must not move"
+        assert not any(argv[:2] == ["git", "add"] for argv in git_spy)
+        assert not any(argv[:2] == ["git", "commit"] for argv in git_spy)
+        assert not any(argv[:2] == ["git", "push"] for argv in git_spy)
+
+    def test_the_staged_file_remains_staged_and_the_unstaged_file_remains_unstaged(self, push_module, repo):
+        (repo / "unrelated.txt").write_text("staged by a concurrent session\n", encoding="utf-8")
+        _run(repo, "git", "add", "unrelated.txt")
+        (repo / "mine.txt").write_text("my own unstaged work\n", encoding="utf-8")
+
+        push_module.commit_and_push(repo, "my commit message", 4)
+
+        assert _run(repo, "git", "diff", "--cached", "--name-only") == "unrelated.txt"
+        status_lines = _run(repo, "git", "status", "--porcelain").splitlines()
+        assert "?? mine.txt" in status_lines
+
+    def test_the_error_message_names_the_staged_paths(self, push_module, repo, capsys):
+        (repo / "secret-in-progress.txt").write_text("do not touch\n", encoding="utf-8")
+        _run(repo, "git", "add", "secret-in-progress.txt")
+
+        push_module.commit_and_push(repo, "message", 4)
+
+        assert "secret-in-progress.txt" in capsys.readouterr().out
+
+    def test_a_clean_index_with_only_unstaged_dirt_is_not_refused(self, push_module, repo, remote_repo):
+        """The guard is about the INDEX, not about dirtiness in general -- ordinary dirty trees must still work."""
+        (repo / "mine.txt").write_text("my own unstaged work\n", encoding="utf-8")
+
+        status, _ = push_module.commit_and_push(repo, "message", 4)
+
+        assert status == "ok"
+        assert _run(remote_repo, "git", "show", "HEAD:mine.txt") == "my own unstaged work"
+
+
+class TestCommitAndPushBehindUpstream:
+    """The pre-existing behind-upstream guard must still block, unchanged, ahead of the new logic."""
+
+    def test_behind_upstream_aborts_without_touching_anything(self, push_module, tmp_path, repo, remote_repo, git_spy):
+        other = tmp_path / "other-clone"
+        _run(tmp_path, "git", "clone", str(remote_repo), str(other))
+        _local_only_commit(other, filename="from-elsewhere.txt", message="pushed by someone else")
+        _run(other, "git", "push", "origin", "master")
+        head_before = _run(repo, "git", "rev-parse", "HEAD")
+        git_spy.clear()  # discard the setup commit/push above; only commit_and_push()'s own git calls matter here
+
+        status, _ = push_module.commit_and_push(repo, "message", 4)
+
+        assert status == "error"
+        assert _run(repo, "git", "rev-parse", "HEAD") == head_before
+        assert not any(argv[:2] == ["git", "add"] for argv in git_spy)
+        assert not any(argv[:2] == ["git", "commit"] for argv in git_spy)
+        assert not any(argv[:2] == ["git", "push"] for argv in git_spy)
diff --git a/scripts/tests/test_reset_side_clones.py b/scripts/tests/test_reset_side_clones.py
new file mode 100644
index 0000000000..770da907c7
--- /dev/null
+++ b/scripts/tests/test_reset_side_clones.py
@@ -0,0 +1,960 @@
+# ***************************************************************************************************************************
+# * 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.
+# ***************************************************************************************************************************
+"""
+Tests for scripts/reset-side-clones.py -- the post-harvest side-clone reset.
+
+Juneau-only, like test_push.py: this script exists in juneau only (see README.md), so unlike
+conftest.py / test_todo_next_id.py / test_todo_status_audit.py this file is NOT one of the
+byte-for-byte-identical-across-repos set, and reset-side-clones.py is loaded here rather than
+from a conftest fixture for exactly that reason.
+
+WHAT IS ACTUALLY WORTH ASSERTING HERE. The script's entire risk is real git behavior on real
+working trees, so almost everything below builds REAL temporary git repositories -- init, commit,
+clone, diverge -- and lets the script drive real git against them. A mocked git would let every
+one of these tests pass while the script did something catastrophic to an actual clone, which is
+the opposite of proof. Mocking appears in exactly two shapes, both deliberate:
+
+  * subprocess.run is monkeypatched to RAISE, to prove a guard fires before any git runs at all
+    (the strongest available form of "it refused"), and
+  * subprocess.run is wrapped in a recording spy that still calls the real subprocess.run, so an
+    end-to-end apply can be audited for a forbidden argv.
+
+HERMETICITY. Every test passes an explicit --board pointing at a temp file, so the real
+~/Project Work/repos.md is never read and never written. The real side clones are never touched:
+the only tests that mention a real path are the canonical-refusal ones, which name the real
+canonical trees on purpose -- the guard has to be tested against the real constant to mean
+anything -- and they assert that NO git command ran, so naming the path is all they do to it.
+Temp repos get their identity and config isolation from environment variables (never `git config`,
+which the wave skill forbids outright and which this script refuses to run).
+"""
+
+from __future__ import annotations
+
+import importlib.util
+import inspect
+import os
+import subprocess
+import sys
+from pathlib import Path
+
+import pytest
+
+SCRIPTS_DIR = Path(__file__).resolve().parent.parent
+
+BOARD_HEADER = "| path | project | role | branch | WAVE / session | status |"
+BOARD_SEPARATOR = "|---|---|---|---|---|---|"
+
+# The real canonical trees, spelled here so the canonical guard is tested against the real
+# constant. Nothing in this file ever runs a command against them.
+REAL_CANONICAL_JUNEAU = Path.home() / "git" / "apache" / "juneau"
+
+
+def _load_reset_module():
+    """
+    Load scripts/reset-side-clones.py as a fresh module object (mirrors conftest.py).
+
+    Registered in sys.modules before exec_module, unlike conftest.py's loader: this script uses
+    `from __future__ import annotations` together with @dataclass, and dataclasses resolves the
+    string annotations by looking the defining module up in sys.modules.
+    """
+    path = SCRIPTS_DIR / "reset-side-clones.py"
+    spec = importlib.util.spec_from_file_location("_undertest_reset_side_clones", path)
+    module = importlib.util.module_from_spec(spec)
+    sys.modules[spec.name] = module
+    try:
+        spec.loader.exec_module(module)
+    except Exception:
+        sys.modules.pop(spec.name, None)
+        raise
+    return module
+
+
+@pytest.fixture
+def mod():
+    """A fresh scripts/reset-side-clones.py module object, one per test."""
+    return _load_reset_module()
+
+
+@pytest.fixture(autouse=True)
+def hermetic_git_env(monkeypatch):
+    """
+    Isolate every git subprocess from the developer's real git configuration and identity.
+
+    Done entirely with environment variables because `git config` must never run -- the wave
+    skill forbids it and the script under test refuses it, so a test that reached for it would
+    be violating the very rule it is here to check.
+    """
+    monkeypatch.setenv("GIT_CONFIG_GLOBAL", os.devnull)
+    monkeypatch.setenv("GIT_CONFIG_SYSTEM", os.devnull)
+    monkeypatch.setenv("GIT_AUTHOR_NAME", "Reset Test")
+    monkeypatch.setenv("GIT_AUTHOR_EMAIL", "reset-test@example.invalid")
+    monkeypatch.setenv("GIT_COMMITTER_NAME", "Reset Test")
+    monkeypatch.setenv("GIT_COMMITTER_EMAIL", "reset-test@example.invalid")
+    monkeypatch.setenv("GIT_TERMINAL_PROMPT", "0")
+
+
+# ---------------------------------------------------------------------------------------
+# Real-git fixtures.
+# ---------------------------------------------------------------------------------------
+def _run(cwd: Path, *argv: str) -> str:
+    result = subprocess.run(argv, cwd=str(cwd), check=True, capture_output=True, text=True)
+    return result.stdout.strip()
+
+
+def _commit(repo: Path, message: str) -> str:
+    _run(repo, "git", "add", "-A")
+    _run(repo, "git", "commit", "-m", message)
+    return _run(repo, "git", "rev-parse", "HEAD")
+
+
+@pytest.fixture
+def origin_repo(tmp_path: Path) -> Path:
+    """
+    A real git repository standing in for a canonical tree, on `master` (the juneau pool's
+    default branch), carrying one of the script's declared sentinel paths.
+    """
+    repo = tmp_path / "canonical"
+    repo.mkdir()
+    _run(repo, "git", "init", "-b", "master", ".")
+    (repo / "scripts").mkdir()
+    (repo / "scripts" / "todo-next-id.py").write_text("# v1\n", encoding="utf-8")
+    (repo / "README.md").write_text("first\n", encoding="utf-8")
+    (repo / ".gitignore").write_text(".work/\n", encoding="utf-8")
+    _commit(repo, "initial")
+    return repo
+
+
+@pytest.fixture
+def side_clone(tmp_path: Path, origin_repo: Path) -> Path:
+    """A real clone of origin_repo, with a gitignored .work/ tree like a real side clone."""
+    clone = tmp_path / "clone-2"
+    _run(tmp_path, "git", "clone", str(origin_repo), str(clone))
+    work = clone / ".work"
+    work.mkdir()
+    (work / "brainstorm.md").write_text("do not lose me\n", encoding="utf-8")
+    (work / "nested").mkdir()
+    (work / "nested" / "deep.md").write_text("nor me\n", encoding="utf-8")
+    return clone
+
+
+def advance_origin(origin_repo: Path) -> str:
+    """Put a new commit on the canonical tree so the clone is genuinely behind."""
+    (origin_repo / "scripts" / "todo-next-id.py").write_text("# v2 -- the fix that mattered\n", encoding="utf-8")
+    (origin_repo / "NEW.md").write_text("added upstream\n", encoding="utf-8")
+    return _commit(origin_repo, "second")
+
+
+def board_file(
+    tmp_path: Path,
+    rows: list[tuple[str, str, str, str, str, str]],
+    *,
+    name: str = "repos.md",
+    prose: str = "Living assignment table. Never reset canonical trees.",
+) -> Path:
+    """Write a temp repos.md whose table matches the real board's shape."""
+    lines = ["# Clone board", "", prose, "", BOARD_HEADER, BOARD_SEPARATOR]
+    lines += ["| " + " | ".join(cells) + " |" for cells in rows]
+    lines += ["", "Skill: ~/Project Work/skills/todo-and-waves/SKILL.md."]
+    path = tmp_path / name
+    path.write_text("\n".join(lines) + "\n", encoding="utf-8")
+    return path
+
+
+def juneau_row(clone: Path, *, session: str = " ", status: str = "idle", branch: str = "master"):
+    return (f"`{clone}`", "Juneau", "worker clone", f"`{branch}`", session, status)
+
+
+@pytest.fixture
+def no_git_allowed(mod, monkeypatch):
+    """
+    Make ANY subprocess invocation an immediate failure.
+
+    Used by the refusal tests: "the guard fired" is proven far more strongly by "git was never
+    invoked" than by "the exit code was 1".
+    """
+    def _boom(*args, **kwargs):
+        raise AssertionError(f"no subprocess may run here, but got: {args!r}")
+
+    monkeypatch.setattr(mod.subprocess, "run", _boom)
+
+
+@pytest.fixture
+def git_spy(mod, monkeypatch):
+    """Record every git argv while still running real git."""
+    calls: list[list[str]] = []
+    real_run = subprocess.run
+
+    def _spy(cmd, *args, **kwargs):
+        calls.append(list(cmd))
+        return real_run(cmd, *args, **kwargs)
+
+    monkeypatch.setattr(mod.subprocess, "run", _spy)
+    return calls
+
+
+# ---------------------------------------------------------------------------------------
+class TestGitWrapperRefusesConfig:
+    """`git config` must be unreachable in every form, including a read-only --get."""
+
+    @pytest.mark.parametrize(
+        "argv",
+        [
+            ["config", "user.email", "x@y.z"],
+            ["config", "--get", "user.email"],
+            ["config", "--global", "user.email", "x@y.z"],
+            ["config", "--local", "--unset", "user.email"],
+        ],
+    )
+    def test_config_is_refused(self, mod, side_clone, argv, no_git_allowed):
+        with pytest.raises(mod.GitGuardViolation, match="forbidden"):
+            mod._git(side_clone, argv)
+
+    def test_forbidden_subcommand_set_contains_config(self, mod):
+        assert "config" in mod.FORBIDDEN_GIT_SUBCOMMANDS
+
+    def test_no_git_config_anywhere_in_a_full_apply(self, mod, tmp_path, origin_repo, side_clone, git_spy):
+        advance_origin(origin_repo)
+        board = board_file(tmp_path, [juneau_row(side_clone)])
+
+        assert mod.main(["--clones", str(side_clone), "--board", str(board), "--apply"]) == 0
+
+        assert git_spy, "the apply path must actually have run git"
+        for argv in git_spy:
+            assert "config" not in argv, f"forbidden `git config` in {argv}"
+
+
+class TestGitCleanCannotReachIgnoredFiles:
+    """
+    `git clean -x` is the unrecoverable mistake in this procedure (it deletes .work/), so the
+    tests below are about UNREACHABILITY, not about remembering to avoid it.
+    """
+
+    def test_clean_argv_constant_is_exactly_fd(self, mod):
+        assert mod.GIT_CLEAN_ARGV == ("clean", "-fd")
+
+    def test_git_clean_helper_has_no_flag_parameter(self, mod):
+        """There is no parameter through which a caller could pass -x."""
+        params = list(inspect.signature(mod._git_clean).parameters)
+        assert params == ["clone"]
+
+    @pytest.mark.parametrize(
+        "argv",
+        [
+            ["clean", "-fdx"],
+            ["clean", "-fdX"],
+            ["clean", "-xfd"],
+            ["clean", "-fd", "-x"],
+            ["clean", "-fd", "-X"],
+            ["clean", "-f"],  # not exactly GIT_CLEAN_ARGV either
+            ["clean", "-fd", "--", "."],
+        ],
+    )
+    def test_any_other_clean_argv_is_refused(self, mod, side_clone, argv, no_git_allowed):
+        with pytest.raises(mod.GitGuardViolation):
+            mod._git(side_clone, argv)
+
+    @pytest.mark.parametrize("argv", [["log", "-x"], ["checkout", "-fx", "master"], ["reset", "-X"]])
+    def test_ignored_file_flags_are_refused_in_any_subcommand(self, mod, side_clone, argv, no_git_allowed):
+        with pytest.raises(mod.GitGuardViolation):
+            mod._git(side_clone, argv)
+
+    def test_clean_helper_actually_runs_the_permitted_form(self, mod, side_clone, git_spy):
+        mod._git_clean(side_clone)
+        cleans = [argv for argv in git_spy if "clean" in argv]
+        assert cleans == [["git", "-C", str(side_clone), "clean", "-fd"]]
+
+    def test_work_dir_survives_a_real_clean(self, mod, side_clone):
+        """The point of -fd over -fdx, checked against real git rather than argued about."""
+        (side_clone / "untracked.txt").write_text("remove me\n", encoding="utf-8")
+        mod._git_clean(side_clone)
+        assert not (side_clone / "untracked.txt").exists()
+        assert (side_clone / ".work" / "brainstorm.md").read_text(encoding="utf-8") == "do not lose me\n"
+
+    def test_no_ignored_file_flag_anywhere_in_a_full_apply(self, mod, tmp_path, origin_repo, side_clone, git_spy):
+        advance_origin(origin_repo)
+        board = board_file(tmp_path, [juneau_row(side_clone)])
+
+        assert mod.main(["--clones", str(side_clone), "--board", str(board), "--apply"]) == 0
+
+        for argv in git_spy:
+            for token in argv:
+                assert not mod._is_untracked_ignored_flag(token), f"ignored-file flag {token!r} in {argv}"
+
+
+class TestCanonicalTreesAreRefused:
+    """
+    Refusal by RESOLVED REAL PATH, so a symlink or a relative invocation cannot slip past.
+
+    These tests name the real canonical trees on purpose -- testing the guard against a
+    substituted constant would prove nothing -- and assert that no git command runs, so naming
+    the path is the only thing that happens to it.
+    """
+
+    def test_git_wrapper_refuses_a_canonical_tree_outright(self, mod, no_git_allowed):
+        with pytest.raises(mod.GitGuardViolation, match="canonical tree"):
+            mod._git(REAL_CANONICAL_JUNEAU, ["status", "--porcelain"])
+
+    def test_all_three_skill_named_canonical_trees_are_listed(self, mod):
+        names = {p.name for p in mod.CANONICAL_TREES}
+        assert names == {"juneau", "irs-1", "sandbox-support-console"}
+
+    def test_dry_run_refuses_a_canonical_row_without_running_git(self, mod, tmp_path, no_git_allowed, capsys):
+        board = board_file(tmp_path, [(f"`{REAL_CANONICAL_JUNEAU}`", "Juneau", "worker clone", "`master`", " ", "idle")])
+
+        exit_code = mod.main(["--clones", str(REAL_CANONICAL_JUNEAU), "--board", str(board)])
+
+        assert exit_code == 1
+        assert "canonical_tree" in capsys.readouterr().out
+
+    def test_apply_also_refuses_a_canonical_row_without_running_git(self, mod, tmp_path, no_git_allowed, capsys):
+        """--apply must not be a way around this. The guard is not a dry-run-only courtesy."""
+        board = board_file(tmp_path, [(f"`{REAL_CANONICAL_JUNEAU}`", "Juneau", "worker clone", "`master`", " ", "idle")])
+
+        exit_code = mod.main(["--clones", str(REAL_CANONICAL_JUNEAU), "--board", str(board), "--apply"])
+
+        assert exit_code == 1
+        out = capsys.readouterr().out
+        assert "canonical_tree" in out
+        assert "0 reset" in out
+
+    def test_a_symlink_to_a_canonical_tree_is_refused(self, mod, tmp_path, no_git_allowed, capsys):
+        """Creating a symlink does not touch its target; resolving it is what the guard does."""
+        link = tmp_path / "innocent-looking-clone"
+        link.symlink_to(REAL_CANONICAL_JUNEAU)
+        board = board_file(tmp_path, [(f"`{link}`", "Juneau", "worker clone", "`master`", " ", "idle")])
+
+        exit_code = mod.main(["--clones", str(link), "--board", str(board), "--apply"])
+
+        assert exit_code == 1
+        assert "canonical_tree" in capsys.readouterr().out
+
+    def test_a_dot_dot_path_into_a_canonical_tree_is_refused(self, mod, tmp_path, no_git_allowed, capsys):
+        sneaky = REAL_CANONICAL_JUNEAU.parent / "juneau-2" / ".." / "juneau"
+        board = board_file(tmp_path, [(f"`{sneaky}`", "Juneau", "worker clone", "`master`", " ", "idle")])
+
+        exit_code = mod.main(["--clones", str(sneaky), "--board", str(board), "--apply"])
+
+        assert exit_code == 1
+        assert "canonical_tree" in capsys.readouterr().out
+
+    def test_a_board_row_marked_canonical_is_refused_even_for_a_temp_repo(
+        self, mod, tmp_path, side_clone, capsys
+    ):
+        """The board's own `canonical` role is honoured, so a new canonical tree needs no code change."""
+        board = board_file(tmp_path, [(f"`{side_clone}`", "Juneau", "canonical", "`master`", " ", "idle")])
+
+        exit_code = mod.main(["--clones", str(side_clone), "--board", str(board), "--apply"])
+
+        assert exit_code == 1
+        assert "canonical_row" in capsys.readouterr().out
+
+    def test_a_path_not_on_the_board_cannot_be_selected(self, mod, tmp_path, side_clone, no_git_allowed):
+        board = board_file(tmp_path, [juneau_row(tmp_path / "some-other-clone")])
+        with pytest.raises(SystemExit) as exc:
+            mod.main(["--clones", str(side_clone), "--board", str(board), "--apply"])
+        assert exc.value.code == 4
+
+
+class TestInFlightIsRefused:
+    """A clone another subagent is using must never be reset out from under it."""
+
+    def test_in_flight_row_is_refused_and_no_git_runs(self, mod, tmp_path, side_clone, no_git_allowed, capsys):
+        board = board_file(tmp_path, [juneau_row(side_clone, session="WAVE-0004 slice a", status="in-flight")])
+
+        exit_code = mod.main(["--clones", str(side_clone), "--board", str(board), "--apply"])
+
+        assert exit_code == 1
+        assert "in_flight" in capsys.readouterr().out
+
+    def test_in_flight_clone_is_bit_for_bit_untouched(self, mod, tmp_path, origin_repo, side_clone):
+        advance_origin(origin_repo)
+        (side_clone / ".work" / "brainstorm.md").write_text("still here\n", encoding="utf-8")
+        head_before = _run(side_clone, "git", "rev-parse", "HEAD")
+        board = board_file(tmp_path, [juneau_row(side_clone, status="in-flight")])
+        board_before = board.read_bytes()
+
+        assert mod.main(["--clones", str(side_clone), "--board", str(board), "--apply"]) == 1
+
+        assert _run(side_clone, "git", "rev-parse", "HEAD") == head_before
+        assert (side_clone / ".work" / "brainstorm.md").read_text(encoding="utf-8") == "still here\n"
+        assert board.read_bytes() == board_before
+
+    def test_do_not_use_row_is_refused_on_status_alone(self, mod, tmp_path, side_clone, no_git_allowed, capsys):
+        """
+        A clone holding the operator's own branch is marked `do-not-use` on the board, and that
+        status has to be the whole protection by itself.
+
+        The clone here is CLEAN, and no git may run (no_git_allowed), so neither the dirty check
+        nor anything else about the tree can be what saved it -- the board said so and that was
+        enough. This is the property that matters for a clone whose working tree is dirty today:
+        the moment its owner commits, a dirty-tree check stops firing, and only the status is
+        left. The assertion that `dirty` is absent from the report is the other half of the
+        proof: the dirty check lives past this guard and was never reached.
+        """
+        board = board_file(tmp_path, [juneau_row(side_clone, status="do-not-use")])
+
+        assert mod.main(["--clones", str(side_clone), "--board", str(board), "--apply"]) == 1
+
+        out = capsys.readouterr().out
+        assert "do_not_use" in out
+        assert "dirty" not in out
+
+    def test_do_not_use_is_a_static_guard_evaluated_before_any_git(self, mod, tmp_path, side_clone):
+        """Same property one level down, at the function that decides it."""
+        row = mod.parse_board(
+            board_file(tmp_path, [juneau_row(side_clone, status="do-not-use")]).read_text(encoding="utf-8")
+        )[0]
+
+        assessment = mod.assess_static(row, frozenset())
+
+        assert not assessment.ok
+        assert [code for code, _ in assessment.refusals] == ["do_not_use"]
+        assert assessment.dirty == [], "the dirty check must not even have been consulted"
+
+    def test_an_idle_row_still_carrying_a_wave_assignment_is_refused(self, mod, tmp_path, side_clone, capsys):
+        """
+        A self-contradicting board -- status idle but a WAVE still assigned -- is refused rather
+        than believed. Harvest is supposed to clear that cell before the reset, so its presence
+        means the board and reality have diverged.
+        """
+        board = board_file(tmp_path, [juneau_row(side_clone, session="WAVE-0004")])
+        assert mod.main(["--clones", str(side_clone), "--board", str(board), "--apply"]) == 1
+        assert "board_inconsistent" in capsys.readouterr().out
+
+    def test_a_free_form_session_note_is_cleared_not_refused(self, mod, tmp_path, origin_repo, side_clone, capsys):
+        """
+        The skill's step 7 says the reset empties the session cell, so a plain note must not be a
+        refusal -- but it is echoed so nothing a human wrote disappears silently.
+        """
+        advance_origin(origin_repo)
+        board = board_file(tmp_path, [juneau_row(side_clone, session="stash: some WIP")])
+
+        assert mod.main(["--clones", str(side_clone), "--board", str(board)]) == 0
+
+        assert "stash: some WIP" in capsys.readouterr().out
+
+
+class TestDirtyTreesAbort:
+    """
+    Uncommitted work is reported, never reset over. All nine clones were clean the night this was
+    written; the check exists for the night one is not.
+    """
+
+    def test_unstaged_modification_aborts_and_survives(self, mod, tmp_path, origin_repo, side_clone, capsys):
+        advance_origin(origin_repo)
+        (side_clone / "README.md").write_text("precious local edit\n", encoding="utf-8")
+        board = board_file(tmp_path, [juneau_row(side_clone)])
+
+        exit_code = mod.main(["--clones", str(side_clone), "--board", str(board), "--apply"])
+
+        assert exit_code == 1
+        assert "dirty" in capsys.readouterr().out
+        assert (side_clone / "README.md").read_text(encoding="utf-8") == "precious local edit\n"
+
+    def test_staged_work_aborts_and_stays_staged(self, mod, tmp_path, origin_repo, side_clone, capsys):
+        advance_origin(origin_repo)
+        (side_clone / "README.md").write_text("staged edit\n", encoding="utf-8")
+        _run(side_clone, "git", "add", "README.md")
+        board = board_file(tmp_path, [juneau_row(side_clone)])
+
+        exit_code = mod.main(["--clones", str(side_clone), "--board", str(board), "--apply"])
+
+        assert exit_code == 1
+        out = capsys.readouterr().out
+        assert "dirty" in out and "1 staged" in out
+        assert _run(side_clone, "git", "diff", "--cached", "--name-only") == "README.md"
+
+    def test_untracked_file_aborts(self, mod, tmp_path, origin_repo, side_clone, capsys):
+        """Untracked non-ignored work is uncommitted work, and `git clean -fd` would delete it."""
+        advance_origin(origin_repo)
+        (side_clone / "scratch.txt").write_text("not committed anywhere\n", encoding="utf-8")
+        board = board_file(tmp_path, [juneau_row(side_clone)])
+
+        assert mod.main(["--clones", str(side_clone), "--board", str(board), "--apply"]) == 1
+        assert "dirty" in capsys.readouterr().out
+        assert (side_clone / "scratch.txt").exists()
+
+    def test_a_gitignored_work_tree_is_not_dirt(self, mod, tmp_path, origin_repo, side_clone):
+        """.work/ must not itself trip the dirty guard, or nothing would ever be resettable."""
+        advance_origin(origin_repo)
+        board = board_file(tmp_path, [juneau_row(side_clone)])
+        assert mod.main(["--clones", str(side_clone), "--board", str(board)]) == 0
+
+
+class TestUnreadableBoardFailsClosed:
+    """
+    An unreadable board must never be interpreted as "nothing is in flight". That is the
+    fail-open version of the in-flight guard, so every one of these exits 2 having run no git.
+    """
+
+    def test_missing_board_exits_2_without_running_git(self, mod, tmp_path, no_git_allowed, capsys):
+        exit_code = mod.main(["--all", "--board", str(tmp_path / "nope.md"), "--apply"])
+        assert exit_code == 2
+        assert "Nothing was touched" in capsys.readouterr().err
+
+    def test_undecodable_board_exits_2(self, mod, tmp_path, no_git_allowed):
+        board = tmp_path / "repos.md"
+        board.write_bytes(b"| path | project |\n\xff\xfe\x00 not utf-8")
+        assert mod.main(["--all", "--board", str(board), "--apply"]) == 2
+
+    def test_board_with_no_table_exits_2(self, mod, tmp_path, no_git_allowed):
+        board = tmp_path / "repos.md"
+        board.write_text("# Clone board\n\nAll the prose and no table at all.\n", encoding="utf-8")
+        assert mod.main(["--all", "--board", str(board), "--apply"]) == 2
+
+    def test_board_with_unexpected_columns_exits_2(self, mod, tmp_path, no_git_allowed):
+        board = tmp_path / "repos.md"
+        board.write_text("| path | project | status |\n|---|---|---|\n| `a` | Juneau | idle |\n", encoding="utf-8")
+        assert mod.main(["--all", "--board", str(board), "--apply"]) == 2
+
+    def test_board_with_a_malformed_row_exits_2(self, mod, tmp_path, no_git_allowed):
+        board = tmp_path / "repos.md"
+        board.write_text(
+            f"{BOARD_HEADER}\n{BOARD_SEPARATOR}\n| `a` | Juneau | worker clone | `master` | idle |\n",
+            encoding="utf-8",
+        )
+        assert mod.main(["--all", "--board", str(board), "--apply"]) == 2
+
+    def test_board_with_a_header_but_no_rows_exits_2(self, mod, tmp_path, no_git_allowed):
+        board = tmp_path / "repos.md"
+        board.write_text(f"{BOARD_HEADER}\n{BOARD_SEPARATOR}\n\nprose\n", encoding="utf-8")
+        assert mod.main(["--all", "--board", str(board), "--apply"]) == 2
+
+    def test_header_without_a_separator_row_exits_2(self, mod, tmp_path, no_git_allowed):
+        board = tmp_path / "repos.md"
+        board.write_text(
+            f"{BOARD_HEADER}\n| `a` | Juneau | worker clone | `master` |  | idle |\n", encoding="utf-8"
+        )
+        assert mod.main(["--all", "--board", str(board), "--apply"]) == 2
+
+    def test_a_board_shaped_like_the_real_one_parses(self, mod):
+        """
+        A parser that fails closed is only useful if it accepts the real board's shape -- without
+        this, every test above would still pass if parse_board rejected everything.
+
+        The header and a representative row are pinned as literals copied from
+        ~/Project Work/repos.md rather than read from it, so the suite stays hermetic. If the real
+        board's column spelling ever drifts from BOARD_COLUMNS, this is the test that says so.
+        """
+        text = (
+            "# Clone board\n\nProse, and a table that starts with a pipe-free paragraph.\n\n"
+            "| path | project | role | branch | WAVE / session | status |\n"
+            "|---|---|---|---|---|---|\n"
+            "| `~/git/apache/juneau` | Juneau | canonical | `master` | at `d9f87f97f8` | dirty-unstaged |\n"
+            "| `~/git/apache/juneau-2` | Juneau | worker clone | `master` | | idle |\n"
+            "| `~/git/sandbox/sandbox-support-console-1` | Console | worker clone | `main` | | idle |\n"
+            "| `~/git/apache/juneau-9.2.1` | Juneau 9.2.1 | maintenance | `x` | | do-not-use |\n"
+            "\nSkill: ~/Project Work/skills/todo-and-waves/SKILL.md.\n"
+        )
+
+        rows = mod.parse_board(text)
+
+        assert len(rows) == 4
+        assert [r.pool for r in rows] == ["juneau", "juneau", "console", None]
+        assert rows[0].is_canonical_row
+        assert rows[1].role == "worker clone" and rows[1].status == "idle"
+        assert rows[2].branch == "main"
+
+
+class TestDefaultIsADryRun:
+    """The safe mode has to be the one you get by typing the command wrong."""
+
+    def test_no_selection_is_a_usage_error_not_an_everything_run(self, mod, tmp_path, side_clone, no_git_allowed):
+        board = board_file(tmp_path, [juneau_row(side_clone)])
+        with pytest.raises(SystemExit) as exc:
+            mod.main(["--board", str(board)])
+        assert exc.value.code == 4
+
+    def test_dry_run_changes_nothing_at_all(self, mod, tmp_path, origin_repo, side_clone):
+        advance_origin(origin_repo)
+        board = board_file(tmp_path, [juneau_row(side_clone)])
+        head_before = _run(side_clone, "git", "rev-parse", "HEAD")
+        board_before = board.read_bytes()
+
+        assert mod.main(["--clones", str(side_clone), "--board", str(board)]) == 0
+
+        assert _run(side_clone, "git", "rev-parse", "HEAD") == head_before
+        assert board.read_bytes() == board_before
+
+    def test_dry_run_does_not_even_fetch(self, mod, tmp_path, origin_repo, side_clone, git_spy):
+        """A dry run stays read-only, so it cannot move remote-tracking refs either."""
+        advance_origin(origin_repo)
+        board = board_file(tmp_path, [juneau_row(side_clone)])
+
+        mod.main(["--clones", str(side_clone), "--board", str(board)])
+
+        assert not any("fetch" in argv for argv in git_spy)
+
+    def test_dry_run_prints_the_commands_it_would_run(self, mod, tmp_path, side_clone, capsys):
+        board = board_file(tmp_path, [juneau_row(side_clone)])
+        mod.main(["--clones", str(side_clone), "--board", str(board)])
+        out = capsys.readouterr().out
+        assert "DRY RUN" in out
+        assert "fetch origin" in out
+        assert "checkout master" in out
+        assert "reset --hard origin/master" in out
+        assert "clean -fd" in out
+
+
+class TestApplyActuallyResets:
+    """The happy path, against real git, since that is the only kind of proof that counts."""
+
+    def test_clone_is_brought_to_the_canonical_commit(self, mod, tmp_path, origin_repo, side_clone, capsys):
+        target = advance_origin(origin_repo)
+        board = board_file(tmp_path, [juneau_row(side_clone)])
+
+        assert mod.main(["--clones", str(side_clone), "--board", str(board), "--apply"]) == 0
+
+        assert _run(side_clone, "git", "rev-parse", "HEAD") == target
+        assert (side_clone / "scripts" / "todo-next-id.py").read_text(encoding="utf-8") == (
+            "# v2 -- the fix that mattered\n"
+        )
+        assert "content verified" in capsys.readouterr().out
+
+    def test_a_leftover_branch_checkout_is_returned_to_master(self, mod, tmp_path, origin_repo, side_clone):
+        target = advance_origin(origin_repo)
+        _run(side_clone, "git", "checkout", "-b", "cu/leftover")
+        board = board_file(tmp_path, [juneau_row(side_clone, branch="cu/leftover")])
+
+        assert mod.main(["--clones", str(side_clone), "--board", str(board), "--apply"]) == 0
+
+        assert _run(side_clone, "git", "rev-parse", "--abbrev-ref", "HEAD") == "master"
+        assert _run(side_clone, "git", "rev-parse", "HEAD") == target
+
+    def test_untracked_files_are_cleaned_but_work_is_preserved(self, mod, tmp_path, origin_repo, side_clone):
+        advance_origin(origin_repo)
+        board = board_file(tmp_path, [juneau_row(side_clone)])
+        # Committed then reverted upstream is not the case here; this file arrives during the
+        # reset window, after the dirty check, the way a build artifact would.
+        assert mod.main(["--clones", str(side_clone), "--board", str(board), "--apply"]) == 0
+        assert (side_clone / ".work" / "brainstorm.md").read_text(encoding="utf-8") == "do not lose me\n"
+        assert (side_clone / ".work" / "nested" / "deep.md").exists()
+
+    def test_apply_is_idempotent(self, mod, tmp_path, origin_repo, side_clone):
+        advance_origin(origin_repo)
+        board = board_file(tmp_path, [juneau_row(side_clone)])
+        assert mod.main(["--clones", str(side_clone), "--board", str(board), "--apply"]) == 0
+        assert mod.main(["--clones", str(side_clone), "--board", str(board), "--apply"]) == 0
+
+
+class TestWorkDirectoryPreservation:
+    """.work/ is backed up before the clone is touched and verified after."""
+
+    def test_backup_and_restore_round_trip(self, mod, side_clone):
+        backup = mod.backup_work(side_clone)
+        assert backup is not None and backup.files == 2
+
+        (side_clone / ".work" / "brainstorm.md").unlink()
+        restored, verified = mod.restore_work(backup)
+
+        assert [str(p) for p in restored] == ["brainstorm.md"]
+        assert verified
+        assert (side_clone / ".work" / "brainstorm.md").read_text(encoding="utf-8") == "do not lose me\n"
+
+    def test_backup_lands_outside_the_clone(self, mod, side_clone):
+        """A backup inside the clone could be reached by the very commands it protects against."""
+        backup = mod.backup_work(side_clone)
+        assert side_clone not in backup.dest.parents
+
+    def test_absent_work_dir_is_not_an_error(self, mod, tmp_path, origin_repo):
+        clone = tmp_path / "no-work"
+        _run(tmp_path, "git", "clone", str(origin_repo), str(clone))
+        assert mod.backup_work(clone) is None
+        assert mod.restore_work(None) == ([], True)
+
+
+class TestContentVerification:
+    """Compare file CONTENT against the canonical blob, not the commit hash."""
+
+    def test_tampered_content_is_caught_while_head_still_matches(self, mod, tmp_path, origin_repo, side_clone):
+        """
+        The whole argument for this check in one test: HEAD is correct, and the file is wrong.
+        Anything that trusted the commit id would call this a clean reset.
+        """
+        advance_origin(origin_repo)
+        board = board_file(tmp_path, [juneau_row(side_clone)])
+        assert mod.main(["--clones", str(side_clone), "--board", str(board), "--apply"]) == 0
+
+        (side_clone / "scripts" / "todo-next-id.py").write_text("# tampered\n", encoding="utf-8")
+
+        with pytest.raises(mod.ResetFailed, match="content mismatch"):
+            mod.verify_content(side_clone, "origin/master")
+
+    def test_declared_sentinels_are_used_when_present(self, mod, side_clone):
+        paths, note = mod.verify_content(side_clone, "origin/master")
+        assert paths == ["scripts/todo-next-id.py"]
+        assert note == "declared sentinels"
+
+    def test_a_tree_without_sentinels_still_verifies_something(self, mod, tmp_path):
+        """
+        "Nothing to verify" must never be reportable as a pass -- an IRS clone carries none of
+        the declared sentinel paths, so the fallback sample is the real code path there.
+        """
+        repo = tmp_path / "sentinel-free"
+        repo.mkdir()
+        _run(repo, "git", "init", "-b", "master", ".")
+        for name in ("a.txt", "b.txt", "c.txt"):
+            (repo / name).write_text(f"{name}\n", encoding="utf-8")
+        _commit(repo, "no sentinels here")
+        clone = tmp_path / "sentinel-free-clone"
+        _run(tmp_path, "git", "clone", str(repo), str(clone))
+
+        paths, note = mod.verify_content(clone, "origin/master")
+
+        assert paths == ["a.txt", "b.txt", "c.txt"]
+        assert "deterministic sample" in note
+
+    def test_an_empty_target_tree_is_a_failure_not_a_pass(self, mod, tmp_path):
+        repo = tmp_path / "empty"
+        repo.mkdir()
+        _run(repo, "git", "init", "-b", "master", ".")
+        _run(repo, "git", "commit", "--allow-empty", "-m", "empty")
+        with pytest.raises(mod.ResetFailed, match="nothing could be content-verified"):
+            mod.verify_content(repo, "HEAD")
+
+
+class TestCuBranchDeletionIsConservative:
+    """
+    Step 5 only where a script can prove safety. "Already harvested" is not mechanically
+    knowable -- harvest lands unstaged on canonical, reachable from no ref -- so containment in
+    the target ref is the substitute, and everything else is left for a human.
+    """
+
+    def test_a_contained_branch_is_deleted(self, mod, tmp_path, origin_repo, side_clone):
+        advance_origin(origin_repo)
+        _run(side_clone, "git", "fetch", "origin")
+        _run(side_clone, "git", "branch", "cu/contained", "origin/master")
+        board = board_file(tmp_path, [juneau_row(side_clone)])
+
+        assert mod.main(["--clones", str(side_clone), "--board", str(board), "--apply"]) == 0
+
+        branches = _run(side_clone, "git", "for-each-ref", "--format=%(refname:short)", "refs/heads")
+        assert "cu/contained" not in branches.split()
+
+    def test_a_branch_with_unique_commits_is_kept_and_reported(self, mod, tmp_path, origin_repo, side_clone, capsys):
+        advance_origin(origin_repo)
+        _run(side_clone, "git", "checkout", "-b", "cu/unharvested")
+        (side_clone / "unique.txt").write_text("only here\n", encoding="utf-8")
+        _commit(side_clone, "unique work")
+        _run(side_clone, "git", "checkout", "master")
+        board = board_file(tmp_path, [juneau_row(side_clone)])
+
+        assert mod.main(["--clones", str(side_clone), "--board", str(board), "--apply"]) == 0
+
+        out = capsys.readouterr().out
+        assert "cu/* KEPT for a human" in out
+        assert "cu/unharvested" in out
+        branches = _run(side_clone, "git", "for-each-ref", "--format=%(refname:short)", "refs/heads")
+        assert "cu/unharvested" in branches.split()
+
+
+class TestRemoteCrossingAndDisagreement:
+    """The IRS/Apache crossing rule, and the one genuinely ambiguous step in the skill."""
+
+    def test_a_remote_pointing_into_another_projects_canonical_tree_is_refused(
+        self, mod, tmp_path, origin_repo, capsys
+    ):
+        """An IRS-pool clone whose remote resolves into the Apache canonical tree is refused."""
+        clone = tmp_path / "crossed"
+        _run(tmp_path, "git", "clone", str(origin_repo), str(clone))
+        _run(clone, "git", "remote", "add", "apache", str(REAL_CANONICAL_JUNEAU))
+        board = board_file(tmp_path, [(f"`{clone}`", "IRS", "IRS-only", "`master`", " ", "idle")])
+
+        exit_code = mod.main(["--clones", str(clone), "--board", str(board), "--apply"])
+
+        assert exit_code == 1
+        out = capsys.readouterr().out
+        assert "remote_crossing" in out
+        assert "juneau canonical tree" in out
+
+    def test_disagreeing_canonical_remotes_refuse_rather_than_pick_one(self, mod, tmp_path, origin_repo, side_clone):
+        """
+        The skill says to reset to "origin/main or the local-canonical remote's main" without
+        saying which wins, so a disagreement is an operator decision, not a coin flip.
+        """
+        other = tmp_path / "other-canonical"
+        other.mkdir()
+        _run(other, "git", "init", "-b", "master", ".")
+        (other / "different.txt").write_text("divergent history\n", encoding="utf-8")
+        _commit(other, "different")
+        _run(side_clone, "git", "remote", "add", "second", str(other))
+        _run(side_clone, "git", "fetch", "second")
+
+        assessment = mod.Assessment(
+            row=mod.parse_board(
+                board_file(tmp_path, [juneau_row(side_clone)]).read_text(encoding="utf-8")
+            )[0],
+            pool="juneau",
+            branch="master",
+        )
+        assessment.canonical_remotes = ["origin", "second"]
+
+        with pytest.raises(mod.ResetFailed, match="disagree"):
+            mod._resolve_target(assessment)
+
+    def test_all_excludes_the_irs_pool_and_says_so(self, mod, tmp_path, side_clone, capsys):
+        """The exclusion is printed, never silent."""
+        irs = tmp_path / "irs-clone"
+        _run(tmp_path, "git", "clone", str(side_clone), str(irs))
+        board = board_file(
+            tmp_path,
+            [juneau_row(side_clone), (f"`{irs}`", "IRS", "IRS-only", "`master`", " ", "idle")],
+        )
+
+        mod.main(["--all", "--board", str(board)])
+
+        out = capsys.readouterr().out
+        assert "IRS clones are excluded" in out
+        assert str(irs) not in out
+
+    def test_pool_irs_includes_them(self, mod, tmp_path, side_clone, capsys):
+        irs = tmp_path / "irs-clone"
+        _run(tmp_path, "git", "clone", str(side_clone), str(irs))
+        board = board_file(tmp_path, [(f"`{irs}`", "IRS", "IRS-only", "`master`", " ", "idle")])
+
+        mod.main(["--pool", "irs", "--board", str(board)])
+
+        assert str(irs) in capsys.readouterr().out
+
+    def test_pool_defaults_match_the_skills_table(self, mod):
+        assert mod.POOL_DEFAULT_BRANCH == {"juneau": "master", "console": "main", "irs": "master"}
+
+
+class TestBoardRowUpdate:
+    """Step 7, and the concurrency question it raises."""
+
+    def test_successful_reset_updates_only_its_own_row(self, mod, tmp_path, origin_repo, side_clone):
+        advance_origin(origin_repo)
+        other = tmp_path / "clone-3"
+        _run(tmp_path, "git", "clone", str(origin_repo), str(other))
+        board = board_file(
+            tmp_path,
+            [
+                juneau_row(side_clone, session="harvested, notes elsewhere", status="dirty-unstaged"),
+                juneau_row(other, status="in-flight"),
+            ],
+        )
+        before = board.read_text(encoding="utf-8").splitlines()
+
+        assert mod.main(["--clones", str(side_clone), "--board", str(board), "--apply"]) == 0
+
+        after = board.read_text(encoding="utf-8").splitlines()
+        assert len(before) == len(after)
+        changed = [i for i, (b, a) in enumerate(zip(before, after)) if b != a]
+        assert len(changed) == 1
+        row = after[changed[0]]
+        assert "`master`" in row and row.rstrip().endswith("idle |")
+        assert "harvested, notes elsewhere" not in row
+
+    def test_a_held_lock_reports_the_change_instead_of_writing(self, mod, tmp_path, origin_repo, side_clone, capsys):
+        """A mangled shared board is worse than a row someone has to paste in by hand."""
+        advance_origin(origin_repo)
+        board = board_file(tmp_path, [juneau_row(side_clone)])
+        lock = board.with_name(board.name + ".lock")
+        lock.write_text("99999\n", encoding="utf-8")
+        before = board.read_bytes()
+
+        exit_code = mod.main(["--clones", str(side_clone), "--board", str(board), "--apply"])
+
+        assert exit_code == 5
+        assert board.read_bytes() == before
+        out = capsys.readouterr().out
+        assert "Apply these rows by hand" in out
+        assert lock.exists(), "someone else's lock must not be removed"
+
+    def test_no_board_update_flag_reports_instead_of_writing(self, mod, tmp_path, origin_repo, side_clone, capsys):
+        advance_origin(origin_repo)
+        board = board_file(tmp_path, [juneau_row(side_clone)])
+        before = board.read_bytes()
+
+        exit_code = mod.main(
+            ["--clones", str(side_clone), "--board", str(board), "--apply", "--no-board-update"]
+        )
+
+        assert exit_code == 5
+        assert board.read_bytes() == before
+        assert "Apply these rows by hand" in capsys.readouterr().out
+
+    def test_render_row_leaves_the_other_columns_alone(self, mod):
+        """Matches the real board's own spacing for an emptied cell (`| |`)."""
+        raw = "| `~/git/apache/juneau-2` | Juneau | worker clone | `cu/x` | WAVE-0004 | in-flight |"
+        out = mod.render_row(raw, "master", "idle")
+        assert out == "| `~/git/apache/juneau-2` | Juneau | worker clone | `master` | | idle |"
+
+    def test_write_refuses_a_rewrite_that_no_longer_parses(self, mod, tmp_path, side_clone):
+        """A rewrite that would leave an unparseable board is never installed."""
+        board = board_file(tmp_path, [juneau_row(side_clone)])
+        before = board.read_bytes()
+        rows = mod.parse_board(board.read_text(encoding="utf-8"))
+
+        with pytest.raises(mod.BoardError):
+            mod.write_board(board, {rows[0].index: "| totally | different | number | of | cells | here | oops |"})
+
+        assert board.read_bytes() == before
+        assert not board.with_name(board.name + ".lock").exists()
+
+    def test_a_board_that_changed_under_us_refuses_the_write(self, mod, tmp_path):
+        """
+        The case _assert_only_intended_lines_changed exists for: another writer edited a
+        different row between the read that produced the plan and this write.
+        """
+        original = "a\nb\nc\n"
+        updated = "a\nB-CHANGED\nc-also-changed\n"
+        with pytest.raises(mod.BoardError, match="unintended lines"):
+            mod._assert_only_intended_lines_changed(original, updated, {1})
+
+    def test_a_write_that_changes_line_count_is_refused(self, mod):
+        with pytest.raises(mod.BoardError, match="line count"):
+            mod._assert_only_intended_lines_changed("a\nb\n", "a\nb\nc\n", {1})
+
+    def test_lock_is_released_after_a_successful_write(self, mod, tmp_path, side_clone):
+        board = board_file(tmp_path, [juneau_row(side_clone)])
+        rows = mod.parse_board(board.read_text(encoding="utf-8"))
+        mod.write_board(board, {rows[0].index: mod.render_row(rows[0].raw, "master", "idle")})
+        assert not board.with_name(board.name + ".lock").exists()
+
+
+class TestSelectionErrors:
+    def test_unknown_pool_is_a_usage_error(self, mod, tmp_path, side_clone, no_git_allowed):
+        board = board_file(tmp_path, [juneau_row(side_clone)])
+        with pytest.raises(SystemExit) as exc:
+            mod.main(["--pool", "nonesuch", "--board", str(board)])
+        assert exc.value.code == 4
+
+    def test_ambiguous_clone_name_is_a_usage_error(self, mod, tmp_path, origin_repo, no_git_allowed):
+        a = tmp_path / "a" / "clone-2"
+        b = tmp_path / "b" / "clone-2"
+        a.parent.mkdir()
+        b.parent.mkdir()
+        board = board_file(tmp_path, [juneau_row(a), juneau_row(b)])
+        with pytest.raises(SystemExit) as exc:
+            mod.main(["--clones", "clone-2", "--board", str(board)])
+        assert exc.value.code == 4
+
+    def test_a_missing_directory_is_refused_not_crashed(self, mod, tmp_path, capsys):
+        board = board_file(tmp_path, [juneau_row(tmp_path / "gone")])
+        assert mod.main(["--clones", str(tmp_path / "gone"), "--board", str(board), "--apply"]) == 1
+        assert "missing_directory" in capsys.readouterr().out
+
+    def test_a_non_git_directory_is_refused(self, mod, tmp_path, capsys):
+        plain = tmp_path / "not-a-repo"
+        plain.mkdir()
+        board = board_file(tmp_path, [juneau_row(plain)])
+        assert mod.main(["--clones", str(plain), "--board", str(board), "--apply"]) == 1
+        assert "not_a_git_worktree" in capsys.readouterr().out
+
+    def test_a_subdirectory_of_a_clone_is_refused(self, mod, tmp_path, side_clone, capsys):
+        inner = side_clone / "scripts"
+        board = board_file(tmp_path, [juneau_row(inner)])
+        assert mod.main(["--clones", str(inner), "--board", str(board), "--apply"]) == 1
+        assert "not_worktree_root" in capsys.readouterr().out


(juneau) 02/06: Land the shared chrome scale contract and three disjoint views slices.

Posted by ja...@apache.org.
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

commit c8bf5b330cd8a68cabe5bdf6d4a1561ca6f733ad
Author: James Bognar <ja...@apache.org>
AuthorDate: Wed Aug 26 08:48:51 2026 -0400

    Land the shared chrome scale contract and three disjoint views slices.
    
    Four slices developed independently in separate clones, each green on its own gate,
    then run together here for the first time: widgets 355, views 1321 (142
    browser-tagged skips, pre-existing), console-ui 179, zero failures throughout.
    
    The scale contract is why the other three were held to disjoint lanes.
    juneau-views.css now defines one named step set -- --jc-chrome-control-height and
    -control-height-compact, -control-padding-x and -control-padding-x-wide,
    -font-size-*, -glyph-size and -glyph-size-small, -line-height -- and the hardcoded
    32px / 10px / 16px values that had drifted apart across the ribbon, the console
    chrome and the theme now reference it. chrome.css, ConsoleChromeMixin and Theme
    consume the same tokens. ChromeScaleScanner and ChromeScale_ContractScan_Test pin
    the contract so a step cannot be silently re-valued: each assertion checks both
    that a declaration references the token and that the token still carries its
    declared value, which is what makes the pin resistant to a later edit that keeps
    the reference but moves the number.
    
    CardContent adds a deliberate raw-markup card body -- div(rawText(...)), never
    escaped -- mirroring the existing Tab/Subtab "trusted, first-party template"
    contract instead of inventing a second one. Its javadoc names stored XSS as the
    risk explicitly and points at CardFieldList as the live-data alternative, and
    CardBody dispatch stays closed and fail-closed on an unknown body, with the
    message naming all three known bodies. RawContentSinkScanner was widened to cross
    into the widgets module so the new sink is actually covered; the widening was
    verified by executing the scanner (32 sinks, 0 violations, 2 of them in widgets)
    rather than by reading it, because a wrong relative path would have scanned
    nothing and still passed.
    
    The ribbon change normalizes a refresh action into its own trailing group when the
    author left it ungrouped. It keys on the pre-existing type === "refresh"
    discriminator so no new marker field was invented, and gates on group == null,
    which is what makes an explicit .group() opt-out fall out for free rather than
    being special-cased. The dangling-divider cleanup runs only when a refresh
    actually moves, so a divider already trailing in the author's own declaration is
    left alone. The helper is DOM-free and sits above the binding layer, with a Node
    harness covering it directly.
    
    SymbolSprite_StemIds_Test pins the sprite's 20 stem ids by set equality ahead of
    the glyph redraw, preserving the existing hyphen/underscore inconsistency verbatim
    so the guard describes the sprite as it is rather than as it ought to be.
    
    ViewsMixin_Serving_Test.java carries two of these slices at once. The scale
    assertions and the ribbon-grouping comment were written in different clones and
    merged here by applying the first onto the second rather than overwriting it, so
    neither was ever momentarily discarded -- and this commit is the first time that
    file has executed with both present.
---
 .../rest/server/console/ConsoleChromeMixin.java    |  34 +-
 .../apache/juneau/rest/server/console/Theme.java   |   4 +-
 .../resources/org/apache/juneau/console/chrome.css |  10 +-
 .../server/console/ConsoleChromeMixin_Test.java    |  43 +++
 .../juneau/rest/server/views/CardGridTable.java    |  36 ++-
 .../org/apache/juneau/views/juneau-ribbon.js       |  43 ++-
 .../org/apache/juneau/views/juneau-views.css       | 142 ++++++--
 .../rest/server/views/CardGridTable_Emit_Test.java |  38 ++-
 .../views/CardGridTable_ViewCardBody_Test.java     |  25 +-
 .../rest/server/views/ChromeScaleScanner.java      | 358 +++++++++++++++++++++
 .../views/ChromeScale_ContractScan_Test.java       | 144 +++++++++
 .../rest/server/views/RawContentSinkScanner.java   |  52 ++-
 .../server/views/SymbolSprite_StemIds_Test.java    |  86 +++++
 .../server/views/ViewsJs_RibbonNormalize_Test.java | 232 +++++++++++++
 .../rest/server/views/ViewsMixin_Serving_Test.java |  12 +-
 .../src/test/js/ribbon-normalize.cjs               | 207 ++++++++++++
 .../juneau/rest/server/widgets/CardBody.java       |  10 +-
 .../juneau/rest/server/widgets/CardContent.java    |  88 +++++
 .../rest/server/widgets/CardContent_Test.java      |  61 ++++
 19 files changed, 1529 insertions(+), 96 deletions(-)

diff --git a/juneau-rest/juneau-rest-server-console-ui/src/main/java/org/apache/juneau/rest/server/console/ConsoleChromeMixin.java b/juneau-rest/juneau-rest-server-console-ui/src/main/java/org/apache/juneau/rest/server/console/ConsoleChromeMixin.java
index e378989ba8..5acd178b21 100644
--- a/juneau-rest/juneau-rest-server-console-ui/src/main/java/org/apache/juneau/rest/server/console/ConsoleChromeMixin.java
+++ b/juneau-rest/juneau-rest-server-console-ui/src/main/java/org/apache/juneau/rest/server/console/ConsoleChromeMixin.java
@@ -39,8 +39,8 @@ import org.apache.juneau.rest.server.util.*;
  * {@code DataTablesMixin} in the {@code juneau-rest-server-datatables} module for the identical asset-serving
  * pattern this mirrors &mdash; not linked here since that module is not a dependency of this one). The served
  * response is the static
- * structural {@code chrome.css} (shipped in this module's classpath) with the active theme's tokens appended as a
- * {@code :root{}} block.
+ * structural {@code chrome.css} (shipped in this module's classpath) with the active theme's tokens appended as an
+ * {@code html:root{}} block.
  *
  * <h5 class='section'>Mount styles:</h5>
  * <p>
@@ -355,10 +355,21 @@ public class ConsoleChromeMixin {
 		return req.getContext().getBeanStore().getBean(ThemeSettings.class).orElse(ThemeSettings.DEFAULT).getTheme();
 	}
 
-	/** Renders one theme's tokens as an appended {@code :root{ ... }} block, escaping every value at the declaration boundary. */
+	/**
+	 * Renders one theme's tokens as an appended {@code html:root{ ... }} block, escaping every value at the
+	 * declaration boundary.
+	 *
+	 * <p>
+	 * The selector is {@code html:root} rather than a bare {@code :root} so the block scores {@code (0,0,1,1)}
+	 * instead of {@code (0,0,1,0)}. A separately-linked stylesheet that declares the same token names in its own
+	 * {@code :root} would tie a bare {@code :root} on specificity, and the cascade would then fall through to
+	 * source order &mdash; which across two stylesheets is the order the consumer's {@code <link>} elements
+	 * happen to appear in, something this framework neither sets nor can observe. The extra type selector makes
+	 * the theme's tokens out-rank such a declaration in either link order.
+	 */
 	private static String rootBlock(Theme theme) {
 		var sb = new StringBuilder();
-		sb.append(":root{");
+		sb.append("html:root{");
 		for (var e : theme.getTokens().entrySet())
 			sb.append(e.getKey()).append(':').append(CssValueEscaper.escape(e.getValue())).append(';');
 		sb.append('}');
@@ -366,16 +377,17 @@ public class ConsoleChromeMixin {
 	}
 
 	/**
-	 * Renders {@link Theme#OPEN}'s {@code :root{}} block with the framework-authored role-token alias derivations
-	 * ({@link #OPEN_ROLE_ALIASES}) appended inside the same block, immediately after the leaf tokens. The aliases
-	 * are appended as trusted framework literal text (not routed through {@code CssValueEscaper}, which is for
-	 * consumer-supplied values); folding them into {@code Theme.OPEN}'s block keeps the served response at exactly
-	 * one {@code :root{}} block for the default theme while still placing every derived default before any
-	 * active-theme override block.
+	 * Renders {@link Theme#OPEN}'s {@code html:root{}} block with the framework-authored role-token alias
+	 * derivations ({@link #OPEN_ROLE_ALIASES}) appended inside the same block, immediately after the leaf tokens.
+	 * The aliases are appended as trusted framework literal text (not routed through {@code CssValueEscaper},
+	 * which is for consumer-supplied values); folding them into {@code Theme.OPEN}'s block keeps the served
+	 * response at exactly one {@code html:root{}} block for the default theme while still placing every derived
+	 * default before any active-theme override block. See {@link #rootBlock(Theme)} for why the selector carries
+	 * the {@code html} type prefix.
 	 */
 	private static String openRootBlock() {
 		var sb = new StringBuilder();
-		sb.append(":root{");
+		sb.append("html:root{");
 		for (var e : Theme.OPEN.getTokens().entrySet())
 			sb.append(e.getKey()).append(':').append(CssValueEscaper.escape(e.getValue())).append(';');
 		sb.append(OPEN_ROLE_ALIASES);
diff --git a/juneau-rest/juneau-rest-server-console-ui/src/main/java/org/apache/juneau/rest/server/console/Theme.java b/juneau-rest/juneau-rest-server-console-ui/src/main/java/org/apache/juneau/rest/server/console/Theme.java
index 04812b5af8..ce7212d783 100644
--- a/juneau-rest/juneau-rest-server-console-ui/src/main/java/org/apache/juneau/rest/server/console/Theme.java
+++ b/juneau-rest/juneau-rest-server-console-ui/src/main/java/org/apache/juneau/rest/server/console/Theme.java
@@ -27,8 +27,8 @@ import java.util.regex.*;
  * <p>
  * A {@link Theme} is pure data &mdash; it carries no classpath assets (fonts/logos/background images; that is a
  * fast-follow, see the design's P3) &mdash; just a name and a map of {@code --jc-*} token names to CSS values.
- * {@code ConsoleChromeMixin} appends the active theme's tokens to the served {@code chrome.css} response as a
- * {@code :root{}} block, on top of {@link #OPEN}'s own block.
+ * {@code ConsoleChromeMixin} appends the active theme's tokens to the served {@code chrome.css} response as an
+ * {@code html:root{}} block, on top of {@link #OPEN}'s own block.
  *
  * <h5 class='section'>Security:</h5>
  * <p>
diff --git a/juneau-rest/juneau-rest-server-console-ui/src/main/resources/org/apache/juneau/console/chrome.css b/juneau-rest/juneau-rest-server-console-ui/src/main/resources/org/apache/juneau/console/chrome.css
index 4dc5f5c9a7..fac062af5d 100644
--- a/juneau-rest/juneau-rest-server-console-ui/src/main/resources/org/apache/juneau/console/chrome.css
+++ b/juneau-rest/juneau-rest-server-console-ui/src/main/resources/org/apache/juneau/console/chrome.css
@@ -22,8 +22,14 @@
    its own. Every --jc-* token is defined by the DYNAMIC part of the served
    response: ConsoleChromeMixin always appends Theme.OPEN's token block, then
    (if a non-default theme is active) a second block of that theme's
-   overrides. Appended blocks win by CSS cascade order, so a consumer never
-   needs to out-rank a token defined in this static file.
+   overrides. Those blocks are emitted at html:root, specificity (0,0,1,1), so
+   they out-rank a same-named token declared at :root (0,0,1,0) by a
+   separately linked stylesheet — juneau-views.css, which declares its own
+   token set, included — whichever order the consumer links the two in. Do
+   not read this as "later text always wins": two :root blocks in separately
+   linked files tie on specificity and are resolved by <link> order, which
+   this framework neither sets nor can observe. The type prefix is what makes
+   the theme's value win rather than the append position.
 
    SECURITY - SINK-PROPERTY DISCIPLINE (do not casually add a new var(--jc-*)
    reference without re-reading this):
diff --git a/juneau-rest/juneau-rest-server-console-ui/src/test/java/org/apache/juneau/rest/server/console/ConsoleChromeMixin_Test.java b/juneau-rest/juneau-rest-server-console-ui/src/test/java/org/apache/juneau/rest/server/console/ConsoleChromeMixin_Test.java
index 19373fb185..3526a8ab15 100644
--- a/juneau-rest/juneau-rest-server-console-ui/src/test/java/org/apache/juneau/rest/server/console/ConsoleChromeMixin_Test.java
+++ b/juneau-rest/juneau-rest-server-console-ui/src/test/java/org/apache/juneau/rest/server/console/ConsoleChromeMixin_Test.java
@@ -881,6 +881,49 @@ class ConsoleChromeMixin_Test extends TestBase {
 		assertFalse(body.contains("--jc-tag-red-text:var("), () -> "unresolved var() reference leaked into the served declaration:\n" + body);
 	}
 
+	//-----------------------------------------------------------------------------------------------------------------
+	// q) Emitted token blocks carry the html:root type prefix, so a theme token out-ranks a same-named token
+	//    declared at :root by a separately linked stylesheet regardless of <link> order
+	//-----------------------------------------------------------------------------------------------------------------
+
+	/**
+	 * Both emission sites must carry the {@code html} type prefix, not just one.
+	 *
+	 * <p>
+	 * Two blocks at plain {@code :root} in separately linked stylesheets tie at specificity {@code (0,0,1,0)} and
+	 * are resolved by the order the consumer's {@code <link>} elements appear in &mdash; which this framework
+	 * neither sets nor can observe, so a theme override is silently defeated whenever a consumer links the other
+	 * way round. {@code html:root} scores {@code (0,0,1,1)} and wins in either order.
+	 *
+	 * <p>
+	 * Deliberately asserted as an <i>anchored</i> prefix rather than a {@code contains("html:root{")}: the
+	 * pre-existing helpers in this class match {@code :root\{} as a substring, and {@code html:root{} contains
+	 * that, so every one of them stays green whether or not the prefix is emitted. A substring assertion here
+	 * would inherit exactly that blind spot and pass against the unfixed emitter.
+	 */
+	@Test void q01_bothEmittedTokenBlocks_carryTheHtmlTypePrefix() throws Exception {
+		var body = bodyOf(MockRestClient.buildLax(ThemeSettingsHost.class));
+		assertEquals(2, countRootBlocks(body), () -> "expected Theme.OPEN block + THEME_A's override block, body:\n" + body);
+		var m = Pattern.compile("(.{0,5}):root\\{").matcher(body);
+		var n = 0;
+		while (m.find()) {
+			n++;
+			assertEquals("html", m.group(1), () -> "token block emitted without the html type prefix, body:\n" + body);
+		}
+		assertEquals(2, n, () -> "expected both emission sites to be checked, body:\n" + body);
+	}
+
+	/**
+	 * The static {@code chrome.css} must keep shipping no token block of its own, which is what makes appending
+	 * one work at all. Guards the other half of (q01): a {@code :root} appearing in the static file would be
+	 * counted by (q01)'s matcher and would not carry the prefix.
+	 */
+	@Test void q02_staticChromeCss_shipsNoTokenBlockOfItsOwn() throws IOException {
+		var css = readChromeCss();
+		var m = Pattern.compile("^\\s*+(html)?+:root\\s*+\\{", Pattern.MULTILINE).matcher(css);
+		assertFalse(m.find(), () -> "static chrome.css must ship no :root block of its own");
+	}
+
 	//-----------------------------------------------------------------------------------------------------------------
 	// Test helpers
 	//-----------------------------------------------------------------------------------------------------------------
diff --git a/juneau-rest/juneau-rest-server-views/src/main/java/org/apache/juneau/rest/server/views/CardGridTable.java b/juneau-rest/juneau-rest-server-views/src/main/java/org/apache/juneau/rest/server/views/CardGridTable.java
index 2cad1a8955..3204a532d4 100644
--- a/juneau-rest/juneau-rest-server-views/src/main/java/org/apache/juneau/rest/server/views/CardGridTable.java
+++ b/juneau-rest/juneau-rest-server-views/src/main/java/org/apache/juneau/rest/server/views/CardGridTable.java
@@ -49,12 +49,15 @@ import org.apache.juneau.rest.server.widgets.*;
  *
  * <h5 class='section'>Closed body dispatch (fail-closed):</h5>
  * <p>
- * The body dispatch is a <b>closed</b>, enumerated set: {@link CardFieldList} and {@link ViewCardBody}.  Any other
- * {@link CardBody} implementation throws at emit rather than being silently dropped, so a body type nobody taught
- * this emitter about can never reach the page.  In particular there is no raw-markup body: the toolkit has no
- * markup sanitizer, so a body that would pour author markup into a card is refused here rather than emitted
- * un-neutralized.  Each known body brings its <b>own</b> data path &mdash; {@link ViewCardBody} inherits the hosted
- * table's ajax/refresh and does not reuse the {@code CardFieldList} refresh envelope.
+ * The body dispatch is a <b>closed</b>, enumerated set: {@link CardFieldList}, {@link ViewCardBody}, and
+ * {@link CardContent}.  Any other {@link CardBody} implementation throws at emit rather than being silently
+ * dropped, so a body type nobody taught this emitter about can never reach the page.  {@link CardContent} is the
+ * one raw-markup body: it carries the "template engine, trusted / first-party content only" ownership contract
+ * documented on its own javadoc &mdash; the caller pre-sanitizes, this emitter writes {@link CardContent#content}
+ * verbatim via {@code rawText(...)}, and a build-gating scanner in this module's test tree checks that only
+ * compile-time literals reach its setter.  Each known body brings its <b>own</b> data path &mdash; {@link
+ * ViewCardBody} inherits the hosted table's ajax/refresh and does not reuse the {@code CardFieldList} refresh
+ * envelope; {@link CardContent} carries no data path at all.
  *
  * <h5 class='section'>Request-aware emit:</h5>
  * <p>
@@ -316,13 +319,15 @@ public class CardGridTable {
 	}
 
 	/**
-	 * Closed body dispatch: {@link CardFieldList} and {@link ViewCardBody}; any other {@link CardBody} fails closed
-	 * at emit.  A {@link ViewCardBody} on the request-free path also fails closed rather than emitting a hosted
-	 * table stripped of the token and server values it was declared with.
+	 * Closed body dispatch: {@link CardFieldList}, {@link ViewCardBody}, and {@link CardContent}; any other
+	 * {@link CardBody} fails closed at emit.  A {@link ViewCardBody} on the request-free path also fails closed
+	 * rather than emitting a hosted table stripped of the token and server values it was declared with.
 	 */
 	private static HtmlElement<?> emitBody(CardBody body, HttpServletRequest req, String idScope) {
 		if (body instanceof CardFieldList fl)
 			return emitFieldList(fl);
+		if (body instanceof CardContent cc)
+			return emitContent(cc);
 		if (body instanceof ViewCardBody vcb) {
 			if (req == null)
 				throw iaex("CardGridTable cannot emit a ViewCardBody without a request: the hosted table needs one "
@@ -331,7 +336,7 @@ public class CardGridTable {
 			return ViewTable.of(req, vcb.view, idScope);
 		}
 		throw iaex("CardGridTable does not know how to emit CardBody type '%s'; the known card bodies are "
-			+ "CardFieldList and ViewCardBody.", body == null ? "null" : body.getClass().getName());
+			+ "CardFieldList, ViewCardBody, and CardContent.", body == null ? "null" : body.getClass().getName());
 	}
 
 	/**
@@ -351,6 +356,17 @@ public class CardGridTable {
 			.attr("style", "grid-template-columns:repeat(" + fl.columns + ",minmax(0,1fr))");
 	}
 
+	/**
+	 * Emits a {@link CardContent} as a single {@code <div class="card-content">} whose child is the body's
+	 * {@link CardContent#content} written <b>verbatim</b>, via {@code rawText(...)} &mdash; the raw-markup
+	 * ownership contract documented on {@link CardContent}.  Unlike every other human string this emitter paints
+	 * (title, field label, field value), this one is never entity-escaped; the caller is responsible for having
+	 * pre-sanitized it.
+	 */
+	private static Div emitContent(CardContent cc) {
+		return div(rawText(cc.content)).class_("card-content");
+	}
+
 	/**
 	 * Emits one {@link Card#actions} entry, in the same DOM vocabulary an {@link AppHeaderTable} action uses: the
 	 * marker + behavior attributes the client enhancement selects on, the tooltip as both {@code aria-label} and
diff --git a/juneau-rest/juneau-rest-server-views/src/main/resources/org/apache/juneau/views/juneau-ribbon.js b/juneau-rest/juneau-rest-server-views/src/main/resources/org/apache/juneau/views/juneau-ribbon.js
index 174fb4008d..307e1d163c 100644
--- a/juneau-rest/juneau-rest-server-views/src/main/resources/org/apache/juneau/views/juneau-ribbon.js
+++ b/juneau-rest/juneau-rest-server-views/src/main/resources/org/apache/juneau/views/juneau-ribbon.js
@@ -169,6 +169,37 @@
 		return "tune";
 	}
 
+	/**
+	 * Moves every ungrouped {@code refresh} action to the end of the list, in one trailing cluster keyed by the
+	 * reserved synthetic group {@code __refresh} (mirroring this file's {@code __ungrouped} convention), so a
+	 * refresh control reads as a self-contained control at the far right of the toolbar regardless of where a
+	 * view declared it.  Pure and DOM-free; {@link #buildRibbon} is the only caller.
+	 *
+	 * <ul>
+	 * 	<li>No {@code refresh} action - returns {@code actions} unchanged (identity no-op).
+	 * 	<li>One or more ungrouped {@code refresh} actions - all of them are removed from their declared position(s)
+	 * 		and re-appended at the end, in their original relative order, sharing the {@code __refresh} group id
+	 * 		(so {@link #buildRibbon}'s adjacent-group clustering renders them as ONE cluster, not several).
+	 * 	<li>A {@code refresh} action that already carries an explicit {@code group} opts OUT completely - it is
+	 * 		left exactly where its neighbours put it, ungrouped by this function.  This is a consumer's escape
+	 * 		hatch: a deliberate {@code .group(...)} on refresh means "I clustered this on purpose".
+	 * 	<li>A {@code divider} left dangling in trailing position by the move (nothing left to divide once refresh
+	 * 		is gone) is dropped rather than rendered as an empty seam.
+	 * </ul>
+	 *
+	 * <p>As with {@code __ungrouped}, a consumer literally naming a group {@code "__refresh"} collides with this
+	 * reserved key; that risk is tolerated here for the same reason it already is for {@code __ungrouped}.
+	 */
+	function normalizeRibbon(actions) {
+		actions = actions || [];
+		const moving = actions.filter(function (a) { return a.type === "refresh" && a.group == null; });
+		if (!moving.length) return actions;
+		const kept = actions.filter(function (a) { return !(a.type === "refresh" && a.group == null); });
+		while (kept.length && kept[kept.length - 1].type === "divider") kept.pop();
+		const moved = moving.map(function (a) { return Object.assign({}, a, { group: "__refresh" }); });
+		return kept.concat(moved);
+	}
+
 	// ==================================================================================================================
 	// DOM / JQUERY BINDING LAYER  (thin shim; not exercised by the pure unit tests)
 	// ==================================================================================================================
@@ -226,17 +257,22 @@
 	 * <p>Adjacent actions sharing a non-null {@code group} id (visual-parity design doc §4.A, item 2/5) are
 	 * clustered into ONE segmented {@code .juneau-view-ribbon-group} wrapper (shared borders, rounded only on the
 	 * outer ends - see juneau-views.css) via the local {@code place(el, groupId)} helper below.  Actions with no
-	 * explicit {@code group} (including an {@code export} action's resolved buttons) share the synthetic
-	 * {@code __ungrouped} id so consecutive icon buttons — refresh + copy/csv/excel/pdf — render as one connected
+	 * explicit {@code group} (excluding {@code refresh}, see below) share the synthetic {@code __ungrouped} id so
+	 * consecutive icon buttons — e.g. {@code columnSearchToggle} + copy/csv/excel/pdf — render as one connected
 	 * ribbon rather than orphan glyphs.  A {@code divider} always closes any open cluster; an explicit
 	 * {@code group} id still splits clusters the way the caller declared.
+	 *
+	 * <p>Before any of that, {@link #normalizeRibbon} moves every ungrouped {@code refresh} action into its own
+	 * trailing {@code __refresh} cluster at the far right, regardless of where the view declared it - a refresh
+	 * control reads as self-contained rather than welded to whatever ungrouped buttons happen to sit beside it.
+	 * A {@code refresh} with an explicit {@code group} opts out of that move entirely.
 	 */
 	// NOSONAR javascript:S3776 -- one dispatch branch per RibbonAction.type (design doc §4.A); each branch is a
 	// few lines and several are pinned verbatim by the wiring canary tests below `functionBody(body, "function
 	// buildRibbon(")`, so splitting them into further helpers would reduce test/code locality without reducing
 	// real complexity.
 	function buildRibbon(viewDef, ctx) {
-		const actions = viewDef.ribbon || [];
+		const actions = normalizeRibbon(viewDef.ribbon || []);
 		if (!actions.length) return null;
 
 		const $ = window.jQuery;
@@ -390,6 +426,7 @@
 		resolveExportButtons: resolveExportButtons,
 		ribbonStorageKey: ribbonStorageKey,
 		resolveButtonIcon: resolveButtonIcon,
+		normalizeRibbon: normalizeRibbon,
 		// binding
 		loadPersistedState: loadPersistedState,
 		build: buildRibbon
diff --git a/juneau-rest/juneau-rest-server-views/src/main/resources/org/apache/juneau/views/juneau-views.css b/juneau-rest/juneau-rest-server-views/src/main/resources/org/apache/juneau/views/juneau-views.css
index b0c14ece09..ac0f23c06d 100644
--- a/juneau-rest/juneau-rest-server-views/src/main/resources/org/apache/juneau/views/juneau-views.css
+++ b/juneau-rest/juneau-rest-server-views/src/main/resources/org/apache/juneau/views/juneau-views.css
@@ -86,6 +86,70 @@
 	--jc-card-gap: 1rem;
 	--jc-card-min: 280px;
 	--jc-card-shadow: 0 1px 3px rgba(0, 0, 0, 0.08);
+	/*
+	 * Shared chrome scale (merged here for the same reason the card tokens are - one :root selector).  This is
+	 * the single set of named steps every chrome surface spends, so a toolbar, a detail panel and a dialog
+	 * cannot each derive their own.  Coverage is DIMENSIONAL AND TYPE STEPS ONLY: control heights, control
+	 * horizontal padding, spacing, type sizes, line-height and glyph sizes.  The currentColor / no-palette rule
+	 * this file's header states is a SEPARATE contract and is deliberately not a member - it has no step
+	 * structure, so it could not be extended the way a step can.  The 1px border weight and the 0.25em corner
+	 * radius are likewise out: a shape value is not a density value.
+	 *
+	 * A later surface MAY add a step.  Declare it in this group, name it <family>-<role> (spelled out, never
+	 * abbreviated), and give it a one-line comment naming the surface that needed it.  What a surface may
+	 * never do:
+	 *   1. Write a literal inline that duplicates an existing step.  If a value equals a step, spend the step.
+	 *   2. Re-value or rename an existing step to suit itself.  A surface needing a different number adds a
+	 *      NEW step; it does not move one out from under the other surfaces.
+	 *   3. Introduce a surface-prefixed name for a chrome-wide value that another surface could legitimately
+	 *      spend.
+	 *   4. Declare a step anywhere but here.  A step declared only in a consumer's stylesheet is invisible to
+	 *      the themeless render this file's header exists to guarantee.
+	 *
+	 * Spacing ladder - the same six names and the same values as the console chrome's own spacing seam,
+	 * re-declared here rather than referenced so this file stays dependency-free and all three layers share one
+	 * spacing vocabulary instead of forking a second ladder.  -5 and -6 have no consumer in this file yet and
+	 * are declared anyway: the ladder is declared whole, as its upstream counterpart is.
+	 */
+	--jc-space-1: 4px;
+	--jc-space-2: 8px;
+	--jc-space-3: 12px;
+	--jc-space-4: 16px;
+	--jc-space-5: 24px;
+	--jc-space-6: 32px;
+	/*
+	 * Control heights.  BOTH are first-class steps, not a default plus a deviation - a surface spending the
+	 * compact step is not deviating from the full-height one.  Neither name mentions a surface: `compact` is a
+	 * density word, so a compact toolbar control and a full-height detail control are each expressible without
+	 * a new token.
+	 */
+	--jc-chrome-control-height: 32px;
+	--jc-chrome-control-height-compact: 28px;
+	/*
+	 * Control horizontal padding.  Deliberately OFF the 4px ladder: rounding 10px to 8px or 12px would be a
+	 * visual change no surface asked for.  Vertical padding is deliberately NOT a step - both control heights
+	 * are stated directly and `box-sizing: border-box` is already in force, so padding-y is a derived value
+	 * rather than an independent one.
+	 */
+	--jc-chrome-control-padding-x: 10px;
+	--jc-chrome-control-padding-x-wide: 14px;    /* PROVISIONAL - fixed when the detail action button first renders. */
+	/*
+	 * Type steps.  A label-smaller-than-value pairing is expressed as the STEP PAIR (-font-size-1 for the
+	 * label, -font-size-3 for the value, 0.857x) rather than as a ratio token: no CSS property could consume a
+	 * ratio, and nothing would stop a surface setting two sizes that ignore it, whereas two named steps are the
+	 * only two values on offer.  The ratio is therefore provisional for as long as -font-size-3 is.
+	 */
+	--jc-chrome-font-size-1: 0.75rem;
+	--jc-chrome-font-size-2: 0.8125rem;          /* PROVISIONAL - fixed when the detail action button first renders. */
+	--jc-chrome-font-size-3: 0.875rem;           /* PROVISIONAL - fixed when the detail field value first renders. */
+	--jc-chrome-line-height: 1.2;                /* PROVISIONAL - fixed with --jc-chrome-font-size-2. */
+	/*
+	 * Glyph sizes, one per role, stated once rather than repeated per selector.  These are chrome-wide glyph
+	 * ROLES; a widget's own internal proportions (a pill dot, a toggle knob) are sized to their own text and
+	 * are deliberately not enrolled here.
+	 */
+	--jc-chrome-glyph-size: 16px;
+	--jc-chrome-glyph-size-small: 12px;
 }
 
 .jc-progress {
@@ -167,7 +231,7 @@
 	flex-wrap: wrap;
 	align-items: center;
 	gap: 1.25em;
-	margin: 0 0 0.5em;
+	margin: 0 0 var(--jc-space-2);
 }
 
 .jc-stat {
@@ -275,10 +339,19 @@ table.dataTable {
 	border-top-width: 2px;        /* accented top rule */
 }
 
+/*
+ * The cell font-size is PINNED here, not merely inherited from the table rule above, because everything the
+ * DataTables child row renders (the whole detail-panel family) sizes its `em` spacing against it.  Left to
+ * inheritance, a host theme that set a cell font-size on a views table would silently re-resolve every one of
+ * those declarations.  `rem`, never `em`: at cell level an `em` would COMPOUND, so a nested views table would
+ * render its cells at 9px and its own nested cells at 6.75px.  A theme that legitimately should win can still
+ * win by matching this selector's specificity and coming later.
+ */
 table[data-juneau-view] > thead > tr > th,
 table[data-juneau-view] > thead > tr > td,
 table.dataTable > thead > tr > th,
 table.dataTable > thead > tr > td {
+	font-size: 0.75rem;
 	padding: 4px 5px;
 	font-weight: normal;
 	text-align: left;
@@ -291,6 +364,7 @@ table[data-juneau-view] > tbody > tr > th,
 table[data-juneau-view] > tbody > tr > td,
 table.dataTable > tbody > tr > th,
 table.dataTable > tbody > tr > td {
+	font-size: 0.75rem;
 	padding: 4px 5px;
 	vertical-align: middle;
 	border: 1px solid;
@@ -342,8 +416,8 @@ table.dataTable thead .sorting_desc_disabled:after {
 	justify-content: center;
 	box-sizing: border-box;
 	min-width: 32px;
-	height: 32px;
-	padding: 0 10px;              /* ribbon-button horizontal padding between glyphs */
+	height: var(--jc-chrome-control-height);
+	padding: 0 var(--jc-chrome-control-padding-x);   /* ribbon-button horizontal padding between glyphs */
 	border: 1px solid;            /* currentColor - no palette color set here */
 	border-radius: 0.25em;
 	background: transparent;
@@ -351,7 +425,7 @@ table.dataTable thead .sorting_desc_disabled:after {
 	cursor: pointer;
 }
 
-.juneau-view-ribbon-btn svg { width: 16px; height: 16px; fill: currentColor; }
+.juneau-view-ribbon-btn svg { width: var(--jc-chrome-glyph-size); height: var(--jc-chrome-glyph-size); fill: currentColor; }
 
 .juneau-view-ribbon-btn:disabled { opacity: 0.4; cursor: not-allowed; }
 
@@ -478,7 +552,7 @@ table.dataTable thead .sorting_desc_disabled:after {
  * NEUTRAL - shape only; chrome.css themes the track wash and selected accent pill.
  */
 .juneau-view-ribbon-group.juneau-view-detail-tabs[data-juneau-strip-mode="tab"] {
-	gap: 0.25em;
+	gap: var(--jc-space-1);
 	width: 100%;
 	margin: 0 0 0.75em;
 	padding: 0.25em;
@@ -582,7 +656,7 @@ table.dataTable thead .sorting_desc_disabled:after {
 	display: inline-flex;
 	align-items: stretch;
 	box-sizing: border-box;
-	height: 32px;
+	height: var(--jc-chrome-control-height);
 	border: 1px solid;            /* currentColor - no palette color set here */
 	border-radius: 0.25em;
 	font-family: inherit;         /* <button> UA font otherwise; apps theme via body font */
@@ -608,7 +682,7 @@ table.dataTable thead .sorting_desc_disabled:after {
 }
 .juneau-view-pagingpill-btn:last-child { border-right: none; }
 .juneau-view-pagingpill-btn:disabled { opacity: 0.4; cursor: not-allowed; }
-.juneau-view-pagingpill-btn svg { width: 12px; height: 12px; fill: currentColor; }
+.juneau-view-pagingpill-btn svg { width: var(--jc-chrome-glyph-size-small); height: var(--jc-chrome-glyph-size-small); fill: currentColor; }
 
 /*
  * The pill's central segment (visual-parity follow-up): BOTH the compact "n-n of n" range summary AND the
@@ -637,7 +711,7 @@ table.dataTable thead .sorting_desc_disabled:after {
 
 .juneau-view-pagingpill-info { white-space: nowrap; font-family: inherit; }
 
-.juneau-view-pagingpill-caret svg { width: 12px; height: 12px; fill: currentColor; }
+.juneau-view-pagingpill-caret svg { width: var(--jc-chrome-glyph-size-small); height: var(--jc-chrome-glyph-size-small); fill: currentColor; }
 
 /* The popup itself - absolutely positioned below the menu button; `[hidden]` (set/cleared by juneau-views.js)
    is enough to show/hide it, so no explicit `display` toggle rule is needed here. */
@@ -688,9 +762,9 @@ table.dataTable thead .sorting_desc_disabled:after {
 	flex-wrap: nowrap;
 	justify-content: space-between;
 	align-items: center;
-	gap: 0.5em;
-	margin: 0 0 0.5em 0;
-	font-size: 0.75rem;           /* same type size as the table / paging+search */
+	gap: var(--jc-space-2);
+	margin: 0 0 var(--jc-space-2) 0;
+	font-size: var(--jc-chrome-font-size-1);   /* same type size as the table / paging+search */
 }
 
 .juneau-view-toolbar-left,
@@ -698,7 +772,7 @@ table.dataTable thead .sorting_desc_disabled:after {
 	display: flex;
 	flex-wrap: nowrap;
 	align-items: center;
-	gap: 0.5em;
+	gap: var(--jc-space-2);
 }
 
 /* Native DT search box, once relocated into the right cluster: inline with the icon ribbon, not a
@@ -715,7 +789,7 @@ table.dataTable thead .sorting_desc_disabled:after {
 .juneau-view-toolbar-right .dataTables_filter input,
 .juneau-view-toolbar-right .dt-search input {
 	box-sizing: border-box;
-	height: 32px;
+	height: var(--jc-chrome-control-height);
 	margin: 0;
 	padding: 0 0.5em;
 	border: 1px solid;            /* currentColor - no palette color set here */
@@ -785,14 +859,14 @@ table.dataTable thead .sorting_desc_disabled:after {
 	overflow-x: auto;
 	white-space: nowrap;
 	gap: 0.5em;
-	margin: 0 0 0.5em 0;
+	margin: 0 0 var(--jc-space-2) 0;
 }
 
 .jc-tab,
 .jc-subtab {
 	flex: 0 0 auto;
 	display: inline-block;
-	padding: 0.35em 0.75em;
+	padding: 0.35em var(--jc-space-3);
 	text-decoration: none;
 	border: 1px solid;            /* currentColor - no palette color set here */
 	border-radius: 0.25em;
@@ -819,8 +893,8 @@ table.dataTable thead .sorting_desc_disabled:after {
 /* Fail-loud PAGE_META contract-version-mismatch banner - neutral, no palette color (mirrors .juneau-view-error). */
 .jc-page-error {
 	display: block;
-	padding: 0.5em 0.75em;
-	margin: 0.25em 0;
+	padding: var(--jc-space-2) var(--jc-space-3);
+	margin: var(--jc-space-1) 0;
 	border: 1px solid;            /* currentColor - no palette color set here */
 	border-radius: 0.25em;
 	font-weight: bold;
@@ -867,8 +941,8 @@ table.dataTable thead .sorting_desc_disabled:after {
 	display: flex;
 	align-items: center;
 	flex-wrap: wrap;
-	gap: 0.5em;
-	margin: 0 0 0.5em 0;
+	gap: var(--jc-space-2);
+	margin: 0 0 var(--jc-space-2) 0;
 }
 
 .jc-bar-text,
@@ -937,11 +1011,11 @@ table.dataTable thead .sorting_desc_disabled:after {
 /* The expanded detail body itself - DataTables' native child row (juneau-views.js `row.child(...).show()`). */
 .juneau-view-detail-panel {
 	margin: 0;
-	padding: 0.5em 1em;
+	padding: var(--jc-space-2) var(--jc-space-3);
 }
 
 .juneau-view-detail-section {
-	margin: 0 0 1em;
+	margin: 0 0 var(--jc-space-3);
 }
 
 .juneau-view-detail-section-title {
@@ -958,7 +1032,7 @@ table.dataTable thead .sorting_desc_disabled:after {
 
 .juneau-view-detail-fields {
 	display: grid;
-	gap: 0.5em 1em;
+	gap: var(--jc-space-2) var(--jc-space-3);
 }
 
 .juneau-view-detail-field-title {
@@ -1016,7 +1090,7 @@ table.dataTable thead .sorting_desc_disabled:after {
 	max-width: 90vw;
 	max-height: 90vh;
 	overflow: auto;
-	padding: 1em 1.25em;
+	padding: var(--jc-space-4) 1.25em;
 	border: 1px solid;
 	border-radius: 6px;
 	background: #fff;
@@ -1044,7 +1118,7 @@ table.dataTable thead .sorting_desc_disabled:after {
 }
 
 .juneau-view-dialog-fields {
-	margin: 0 0 1em;
+	margin: 0 0 var(--jc-space-4);
 }
 
 .juneau-view-dialog-fields dt {
@@ -1059,10 +1133,10 @@ table.dataTable thead .sorting_desc_disabled:after {
 }
 
 .juneau-view-dialog-form {
-	margin: 0 0 1em;
+	margin: 0 0 var(--jc-space-4);
 	display: flex;
 	flex-direction: column;
-	gap: 0.75em;
+	gap: var(--jc-space-3);
 }
 
 /*
@@ -1072,10 +1146,10 @@ table.dataTable thead .sorting_desc_disabled:after {
  * NEUTRAL - shape only; chrome.css themes the track wash and selected accent pill.
  */
 .juneau-view-ribbon-group.juneau-view-dialog-sections[data-juneau-strip-mode="tab"] {
-	gap: 0.25em;
+	gap: var(--jc-space-1);
 	width: 100%;
 	margin: 0;
-	padding: 0.25em;
+	padding: var(--jc-space-1);
 	border-bottom: none;
 }
 
@@ -1089,7 +1163,7 @@ table.dataTable thead .sorting_desc_disabled:after {
 .juneau-view-dialog-form-section {
 	display: flex;
 	flex-direction: column;
-	gap: 0.75em;
+	gap: var(--jc-space-3);
 }
 
 /*
@@ -1103,7 +1177,7 @@ table.dataTable thead .sorting_desc_disabled:after {
 .juneau-view-dialog-form-row label {
 	display: block;
 	font-weight: 600;
-	margin-bottom: 0.25em;
+	margin-bottom: var(--jc-space-1);
 }
 
 .juneau-view-dialog-form-row input,
@@ -1178,7 +1252,7 @@ table.dataTable thead .sorting_desc_disabled:after {
 
 .juneau-view-dialog-actions {
 	display: flex;
-	gap: 0.5em;
+	gap: var(--jc-space-2);
 	justify-content: flex-end;
 }
 
@@ -1190,7 +1264,7 @@ table.dataTable thead .sorting_desc_disabled:after {
 .juneau-view-action-menu {
 	position: fixed;
 	margin: 0;
-	padding: 0.25em 0;
+	padding: var(--jc-space-1) 0;
 	list-style: none;
 	min-width: 10em;
 	border: 1px solid var(--jc-popover-border);
@@ -1417,7 +1491,7 @@ table.dataTable thead .sorting_desc_disabled:after {
 .juneau-view-card-header {
 	display: flex;
 	align-items: center;
-	gap: 0.5em;
+	gap: var(--jc-space-2);
 	padding: 0.5rem 0.75rem;
 	border-bottom: 1px solid var(--jc-card-border, #dddddd);
 }
@@ -1447,7 +1521,7 @@ table.dataTable thead .sorting_desc_disabled:after {
 .juneau-view-card-actions {
 	margin-left: auto;
 	display: flex;
-	gap: 0.25em;
+	gap: var(--jc-space-1);
 }
 
 .juneau-view-card-refresh {
diff --git a/juneau-rest/juneau-rest-server-views/src/test/java/org/apache/juneau/rest/server/views/CardGridTable_Emit_Test.java b/juneau-rest/juneau-rest-server-views/src/test/java/org/apache/juneau/rest/server/views/CardGridTable_Emit_Test.java
index 33a4a745f6..be9f411c03 100644
--- a/juneau-rest/juneau-rest-server-views/src/test/java/org/apache/juneau/rest/server/views/CardGridTable_Emit_Test.java
+++ b/juneau-rest/juneau-rest-server-views/src/test/java/org/apache/juneau/rest/server/views/CardGridTable_Emit_Test.java
@@ -214,11 +214,43 @@ class CardGridTable_Emit_Test extends TestBase {
 	}
 
 	//------------------------------------------------------------------------------------------------------------------
-	// No CardContent this child (i2)
+	// CardContent: the raw-markup body, verbatim/unescaped (opposite of every field value)
 	//------------------------------------------------------------------------------------------------------------------
 
-	@Test void a19_noCardContentEmit() {
-		assertFalse(html(grid()).contains("card-content"), "no CardContent markup this child (i2)");
+	@Test void a19_fieldListOnlyGrid_emitsNoCardContentWrapper() {
+		// The card-content wrapper is conditioned on an actual CardContent body being present, not stamped
+		// unconditionally onto every card.
+		assertFalse(html(grid()).contains("card-content"), "no card-content wrapper without a CardContent body");
+	}
+
+	@Test void a20_cardContentBodyEmitsRawMarkupVerbatim() {
+		var g = CardGrid.create("g1").cards(
+			Card.create("c1", "T").body(CardContent.create().content("<p>Raw <b>markup</b>.</p>")));
+		var h = html(g);
+		assertTrue(h.contains("class=\"card-content\""), h);
+		assertTrue(h.contains("<p>Raw <b>markup</b>.</p>"),
+			() -> "raw content must appear byte-for-byte verbatim (no escaping):\n" + h);
+	}
+
+	@Test void a21_cardContentIsNeverHtmlEntityEscaped_unlikeFieldValues() {
+		var g = CardGrid.create("g1").cards(
+			Card.create("c1", "T").body(CardContent.create().content("<script>alert(1)</script>")));
+		var h = html(g);
+		// The card TITLE is escaped (existing contract, a14) ... but CardContent's body is emitted verbatim - this
+		// is the template-engine ownership contract, not a bug.
+		assertTrue(h.contains("<script>alert(1)</script>"),
+			() -> "content must be emitted verbatim per its documented ownership contract:\n" + h);
+	}
+
+	@Test void a22_cardContentBodyCarriesNoRefreshWire() {
+		// CardContent brings no data path of its own (unlike CardFieldList); none of the refresh attributes may
+		// appear on a card whose only body is raw content.
+		var g = CardGrid.create("g1").cards(
+			Card.create("c1", "T").body(CardContent.create().content("<p>x</p>")));
+		var h = html(g);
+		assertFalse(h.contains(CardGridTable.CARD_REFRESH_ATTR), h);
+		assertFalse(h.contains(CardGridTable.CARD_CONTRACT_ATTR), h);
+		assertFalse(h.contains(CardGridTable.CARD_REFRESH_TRIGGER_ATTR), h);
 	}
 
 	private static int countOf(String haystack, String needle) {
diff --git a/juneau-rest/juneau-rest-server-views/src/test/java/org/apache/juneau/rest/server/views/CardGridTable_ViewCardBody_Test.java b/juneau-rest/juneau-rest-server-views/src/test/java/org/apache/juneau/rest/server/views/CardGridTable_ViewCardBody_Test.java
index 5ea2c1a3e1..01479bdc24 100644
--- a/juneau-rest/juneau-rest-server-views/src/test/java/org/apache/juneau/rest/server/views/CardGridTable_ViewCardBody_Test.java
+++ b/juneau-rest/juneau-rest-server-views/src/test/java/org/apache/juneau/rest/server/views/CardGridTable_ViewCardBody_Test.java
@@ -291,13 +291,13 @@ class CardGridTable_ViewCardBody_Test extends TestBase {
 	}
 
 	//------------------------------------------------------------------------------------------------------------------
-	// e) Unknown bodies still fail closed (including a raw-content body, which this child does not ship)
+	// e) Unknown bodies still fail closed; a ViewCardBody card does not spuriously emit another body's markers
 	//------------------------------------------------------------------------------------------------------------------
 
-	/** A raw-markup body shape.  There is no sanitizer in the toolkit, so the emitter must refuse it. */
-	static class CardContent implements CardBody {
+	/** A {@link CardBody} implementation this emitter has never been taught about; pins the fail-closed default. */
+	static class UnknownCardBody implements CardBody {
 		@SuppressWarnings({
-			"unused"   // The field exists to make this stand-in look exactly like the body type it stands in for.
+			"unused"   // The field exists to make this stand-in look like a real body type carrying data.
 		})
 		String html = "<b>hi</b>";
 
@@ -305,21 +305,26 @@ class CardGridTable_ViewCardBody_Test extends TestBase {
 		@Override public void validate() {}
 	}
 
-	@Test void e01_rawContentBodyFailsClosedOnTheRequestAwarePath() {
-		var c = Card.create("c1", "T").body(new CardContent());
+	@Test void e01_unknownCardBodyFailsClosedOnTheRequestAwarePath() {
+		var c = Card.create("c1", "T").body(new UnknownCardBody());
 		var req = tokenRequest();
 		var e = assertThrows(IllegalArgumentException.class, () -> CardGridTable.of(req, c));
 		assertTrue(e.getMessage().contains("CardFieldList"), e::getMessage);
-		assertTrue(e.getMessage().contains(CardContent.class.getName()), e::getMessage);
+		assertTrue(e.getMessage().contains(UnknownCardBody.class.getName()), e::getMessage);
 	}
 
-	@Test void e02_rawContentBodyFailsClosedOnTheGridPathToo() {
-		var g = CardGrid.create("g1").cards(Card.create("c1", "T").body(new CardContent()));
+	@Test void e02_unknownCardBodyFailsClosedOnTheGridPathToo() {
+		var g = CardGrid.create("g1").cards(Card.create("c1", "T").body(new UnknownCardBody()));
 		var e = assertThrows(IllegalArgumentException.class, () -> CardGridTable.of(g));
 		assertTrue(e.getMessage().contains("CardFieldList"), e::getMessage);
 	}
 
-	@Test void e03_noRawContentMarkupIsEverEmitted() {
+	/**
+	 * Scenario-scoped, not a framework-wide guarantee: {@link CardContent} is a real body type with its own
+	 * positive coverage (see {@code CardGridTable_Emit_Test}).  This only pins that a card hosting a
+	 * {@link ViewCardBody} does not spuriously pick up the {@code card-content} marker that body type owns.
+	 */
+	@Test void e03_viewCardBodyDoesNotEmitTheCardContentMarker() {
 		var h = Html.of(CardGridTable.of(tokenRequest(), viewCard("c1", view())));
 		assertFalse(h.contains("card-content"), h);
 	}
diff --git a/juneau-rest/juneau-rest-server-views/src/test/java/org/apache/juneau/rest/server/views/ChromeScaleScanner.java b/juneau-rest/juneau-rest-server-views/src/test/java/org/apache/juneau/rest/server/views/ChromeScaleScanner.java
new file mode 100644
index 0000000000..6881194c71
--- /dev/null
+++ b/juneau-rest/juneau-rest-server-views/src/test/java/org/apache/juneau/rest/server/views/ChromeScaleScanner.java
@@ -0,0 +1,358 @@
+/*
+ * 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 java.util.*;
+import java.util.regex.*;
+
+/**
+ * Test-only, <b>private</b> stylesheet scanner enforcing the shared chrome scale contract on
+ * {@code juneau-views.css}: the named dimensional and type steps every chrome surface spends.
+ *
+ * <p>
+ * Not shipped and deliberately not public API, mirroring the discipline of the {@link RawContentSinkScanner}
+ * test-only guard this class is modeled on and sits beside.
+ *
+ * <h5 class='section'>What it enforces</h5>
+ * <ol>
+ * 	<li><b>Declaration.</b> Every step in {@link #scale()} is declared exactly once in the file. A step declared
+ * 		twice has two values in flight; a step declared zero times cannot be spent.
+ * 	<li><b>No literal that duplicates a step.</b> On the properties a chrome surface actually sizes with, a
+ * 		literal whose value equals a declared step is a violation &mdash; if a value equals a step, spend the
+ * 		step. This is the half that turns the contract's own "never write a literal that duplicates a step" rule
+ * 		from advice into a build failure.
+ * </ol>
+ *
+ * <h5 class='section'>Why the second half is narrower than it first looks, and deliberately so</h5>
+ * <p>
+ * The prohibition binds <b>computed</b> values, not written ones, and an {@code em} value can only be computed
+ * once you know its declaration's font-size context. That context is <i>not</i> uniform in this file &mdash; it
+ * runs from a UA/system control font through 10.2px, 12px, 16px and up &mdash; so a checker that assumed one
+ * context would reproduce, in test form, exactly the defect this contract exists to close. Two consequences,
+ * both intentional:
+ * <ul>
+ * 	<li><b>{@code em} values are never evaluated here.</b> Only absolute {@code px}/{@code rem} literals are
+ * 		compared. In particular a form control that sets no {@code font-size} of its own resolves its {@code em}
+ * 		against a UA/system font that varies by browser and platform, so a computation against one engine's
+ * 		value would report a violation on that engine and pass on every other. This scanner must never do that.
+ * 	<li><b>{@code rem} is normalised to px at 16px per rem.</b> That is safe in a way {@code em} is not: nothing
+ * 		in this file, and nothing in the console chrome that themes it, sets a {@code font-size} on
+ * 		{@code html}/{@code body}, so the root context is the browser default in both a themeless and a themed
+ * 		render.
+ * </ul>
+ *
+ * <h5 class='section'>Provisional steps are excluded from the second half</h5>
+ * <p>
+ * A step whose value is still provisional has not been rendered on a views surface yet. Binding the file's
+ * existing declarations to it would tie unrelated surfaces to a number the surface that owns it is going to
+ * re-decide &mdash; which is the "re-value a step out from under the other surfaces" failure, arrived at from
+ * the other direction. Provisional steps are still checked for {@link #scale() declaration}.
+ *
+ * <h5 class='section'>Why there is a recorded-exception table rather than a clean sheet</h5>
+ * <p>
+ * {@link #recordedLiterals()} lists every literal that stays a literal, each with a reason. It exists so the
+ * check is a <b>ratchet</b>: the recorded set is what the file looks like today, and anything new is a failure.
+ * An entry is not an excuse &mdash; a reader can see precisely which declarations have not been routed onto the
+ * ladder and why. The table is asserted to be non-vacuous by the accompanying test: an entry matching nothing is
+ * itself a failure, so the list cannot rot into a silent allow-everything.
+ */
+final class ChromeScaleScanner {
+
+	private ChromeScaleScanner() {}
+
+	/** The family a step belongs to, which decides the properties it can legitimately be spent on. */
+	enum Family { SPACE, CONTROL_HEIGHT, CONTROL_PADDING_X, FONT_SIZE, LINE_HEIGHT, GLYPH }
+
+	/**
+	 * One named step.
+	 *
+	 * @param token The custom-property name.
+	 * @param value The declared value, exactly as written in the stylesheet.
+	 * @param confirmed Whether the value is settled (as opposed to provisional pending a surface that renders it).
+	 * @param family The step's family.
+	 */
+	record Step(String token, String value, boolean confirmed, Family family) {}
+
+	/**
+	 * One literal that deliberately stays a literal.
+	 *
+	 * @param selector A substring of the owning rule's selector text.
+	 * @param property The property name.
+	 * @param value The literal value, exactly as written.
+	 * @param reason Why it is not spending a step.
+	 */
+	record RecordedLiteral(String selector, String property, String value, String reason) {}
+
+	/** One declaration parsed out of the stylesheet. */
+	record Decl(String selector, String property, String value) {}
+
+	/** The scan outcome. */
+	record Result(List<String> violations, List<Decl> checked, Set<RecordedLiteral> matchedRecords) {}
+
+	private static final List<Step> SCALE = List.of(
+		new Step("--jc-space-1", "4px", true, Family.SPACE),
+		new Step("--jc-space-2", "8px", true, Family.SPACE),
+		new Step("--jc-space-3", "12px", true, Family.SPACE),
+		new Step("--jc-space-4", "16px", true, Family.SPACE),
+		new Step("--jc-space-5", "24px", true, Family.SPACE),
+		new Step("--jc-space-6", "32px", true, Family.SPACE),
+		new Step("--jc-chrome-control-height", "32px", true, Family.CONTROL_HEIGHT),
+		new Step("--jc-chrome-control-height-compact", "28px", true, Family.CONTROL_HEIGHT),
+		new Step("--jc-chrome-control-padding-x", "10px", true, Family.CONTROL_PADDING_X),
+		new Step("--jc-chrome-control-padding-x-wide", "14px", false, Family.CONTROL_PADDING_X),
+		new Step("--jc-chrome-font-size-1", "0.75rem", true, Family.FONT_SIZE),
+		new Step("--jc-chrome-font-size-2", "0.8125rem", false, Family.FONT_SIZE),
+		new Step("--jc-chrome-font-size-3", "0.875rem", false, Family.FONT_SIZE),
+		new Step("--jc-chrome-line-height", "1.2", false, Family.LINE_HEIGHT),
+		new Step("--jc-chrome-glyph-size", "16px", true, Family.GLYPH),
+		new Step("--jc-chrome-glyph-size-small", "12px", true, Family.GLYPH)
+	);
+
+	/**
+	 * Every literal that deliberately stays a literal, with the reason it is not spending a step.
+	 *
+	 * <p>
+	 * Grouped by reason rather than by file order, so a reader can see how many distinct reasons there actually
+	 * are. Three, at present.
+	 */
+	private static final List<RecordedLiteral> RECORDED_LITERALS = List.of(
+		// (1) The table cell type context. This value is what every `em` in the DataTables child row resolves
+		// against, so it is deliberately NOT a token: a theme that overrode the token would silently re-resolve
+		// the whole detail-panel family, which is the exact dependency pinning it was meant to remove.
+		new RecordedLiteral("table[data-juneau-view], table.dataTable", "font-size", "0.75rem",
+			"anchors the table type context; a token here would be overridable and the pin would stop pinning"),
+		new RecordedLiteral("> thead > tr > th", "font-size", "0.75rem",
+			"pins the cell type context; a token here would be overridable and the pin would stop pinning"),
+		new RecordedLiteral("> tbody > tr > th", "font-size", "0.75rem",
+			"pins the cell type context; a token here would be overridable and the pin would stop pinning"),
+
+		// (2) The card grid sizes itself in `rem`. The membership sweep behind the spacing ladder evaluated
+		// `em`-valued declarations only, so these were never assessed against a step and routing them now would
+		// be a card-grid density decision this contract does not own.
+		new RecordedLiteral(".juneau-view-card-status", "font-size", "0.75rem",
+			"card-grid rem sizing, never assessed by the em-valued membership sweep"),
+		new RecordedLiteral(".juneau-view-card-field dt", "font-size", "0.75rem",
+			"card-grid rem sizing, never assessed by the em-valued membership sweep"),
+		new RecordedLiteral(".juneau-view-card-fields", "gap", "0.4rem 0.75rem",
+			"card-grid rem sizing, never assessed by the em-valued membership sweep"),
+
+		// (3) A third glyph site at the small glyph size, in a widget the glyph-role naming enumerated only two
+		// consumers for. Routing it is pixel-neutral but adds a consumer to a named role, which is a decision
+		// for whoever owns the row-detail control rather than one to take in passing.
+		new RecordedLiteral(".juneau-view-detail-control svg", "width", "12px",
+			"a third small-glyph consumer; enrolling it widens a named glyph role and is not this contract's call"),
+		new RecordedLiteral(".juneau-view-detail-control svg", "height", "12px",
+			"a third small-glyph consumer; enrolling it widens a named glyph role and is not this contract's call")
+	);
+
+	/** Properties a chrome surface sizes with, and the step families each may legitimately spend. */
+	private static final Map<String,Set<Family>> CHECKED_PROPERTIES = Map.of(
+		"height", Set.of(Family.CONTROL_HEIGHT, Family.SPACE, Family.GLYPH),
+		"min-height", Set.of(Family.CONTROL_HEIGHT, Family.SPACE),
+		"font-size", Set.of(Family.FONT_SIZE),
+		"gap", Set.of(Family.SPACE),
+		"line-height", Set.of(Family.LINE_HEIGHT),
+		"width", Set.of(Family.GLYPH)
+	);
+
+	/** {@code width} is only a scale property on an SVG glyph; elsewhere it is a content measure. */
+	private static final String SVG_SELECTOR_SUFFIX = "svg";
+
+	/** Matches one {@code selector { ... }} rule block. */
+	private static final Pattern RULE = Pattern.compile("([^{}]+)\\{([^{}]*)\\}");
+
+	/** Matches a {@code var(...)} reference, including any fallback, so a fallback is not read as a bare literal. */
+	private static final Pattern VAR_REF = Pattern.compile("var\\([^()]*(?:\\([^()]*\\)[^()]*)*\\)");
+
+	/** Matches an absolute length/size token. */
+	private static final Pattern ABSOLUTE = Pattern.compile("(?<![\\w.-])(\\d*\\.?\\d+)(px|rem)(?![\\w-])");
+
+	/** The steps this contract declares. */
+	static List<Step> scale() {
+		return SCALE;
+	}
+
+	/** Every literal deliberately left as a literal, with its reason. */
+	static List<RecordedLiteral> recordedLiterals() {
+		return RECORDED_LITERALS;
+	}
+
+	/**
+	 * Reports any step not declared exactly once in the stylesheet.
+	 *
+	 * @param css The stylesheet text.
+	 * @return One message per step that is missing or declared more than once; empty when every step is sound.
+	 */
+	static List<String> checkDeclaredExactlyOnce(String css) {
+		var code = stripComments(css);
+		var out = new ArrayList<String>();
+		for (var s : SCALE) {
+			var m = Pattern.compile(Pattern.quote(s.token()) + "\\s*:\\s*([^;}]+)").matcher(code);
+			var found = new ArrayList<String>();
+			while (m.find())
+				found.add(m.group(1).trim());
+			if (found.size() != 1) {
+				out.add(s.token() + ": expected exactly one declaration, found " + found.size() + " " + found);
+			} else if (!found.get(0).equals(s.value())) {
+				out.add(s.token() + ": declared as '" + found.get(0) + "', contract says '" + s.value() + "'");
+			}
+		}
+		return out;
+	}
+
+	/**
+	 * Scans for literals that duplicate a declared step on a property the scale covers.
+	 *
+	 * @param css The stylesheet text.
+	 * @return The violations, the declarations actually examined, and which recorded exceptions were matched.
+	 */
+	static Result scan(String css) {
+		var violations = new ArrayList<String>();
+		var checked = new ArrayList<Decl>();
+		var matched = new LinkedHashSet<RecordedLiteral>();
+		var code = stripComments(css);
+
+		var rules = RULE.matcher(code);
+		while (rules.find()) {
+			var selector = normalise(rules.group(1));
+			if (selector.startsWith("@") || selector.isEmpty())
+				continue;
+			for (var d : declarations(selector, rules.group(2))) {
+				var families = CHECKED_PROPERTIES.get(d.property());
+				if (families == null)
+					continue;
+				if ("width".equals(d.property()) && !isSvgSelector(selector))
+					continue;
+				checked.add(d);
+				var hit = findDuplicatedStep(d, families);
+				if (hit == null)
+					continue;
+				var record = findRecord(d);
+				if (record != null) {
+					matched.add(record);
+					continue;
+				}
+				violations.add(d.selector() + " { " + d.property() + ": " + d.value() + " } duplicates the step "
+					+ hit.token() + " (" + hit.value() + "). If a value equals a step, spend the step - or add a "
+					+ "recorded exception with the reason it cannot.");
+			}
+		}
+		return new Result(violations, checked, matched);
+	}
+
+	/**
+	 * The confirmed step of an eligible family whose value the declaration writes out as a literal.
+	 *
+	 * <p>
+	 * Role-named families are searched before the spacing ladder, so a 32px {@code height} is reported against
+	 * {@code --jc-chrome-control-height} rather than against the numerically-identical {@code --jc-space-6}. Both
+	 * are violations either way; naming the apter one is what makes the message actionable.
+	 */
+	private static Step findDuplicatedStep(Decl d, Set<Family> families) {
+		var literals = absoluteValues(d.value());
+		if (literals.isEmpty())
+			return null;
+		for (var roleNamed : List.of(true, false)) {
+			for (var s : SCALE) {
+				if (!s.confirmed() || !families.contains(s.family()) || (s.family() == Family.SPACE) == roleNamed)
+					continue;
+				var stepPx = toPx(s.value());
+				if (stepPx != null && literals.contains(stepPx))
+					return s;
+			}
+		}
+		return null;
+	}
+
+	private static RecordedLiteral findRecord(Decl d) {
+		for (var r : RECORDED_LITERALS)
+			if (d.selector().contains(r.selector()) && r.property().equals(d.property()) && r.value().equals(d.value()))
+				return r;
+		return null;
+	}
+
+	/** True if any comma-separated selector in the group targets an {@code svg} element. */
+	private static boolean isSvgSelector(String selector) {
+		for (var s : selector.split(","))
+			if (s.trim().endsWith(SVG_SELECTOR_SUFFIX))
+				return true;
+		return false;
+	}
+
+	/**
+	 * Every absolute value in a declaration, normalised to px. {@code var(...)} expressions are removed first, so
+	 * a token's own fallback (e.g. {@code var(--jc-card-gap, 1rem)}) is not mistaken for a bare literal - the
+	 * declaration is already spending a token, which is the thing the rule asks for.
+	 */
+	private static Set<Double> absoluteValues(String value) {
+		var out = new LinkedHashSet<Double>();
+		var m = ABSOLUTE.matcher(VAR_REF.matcher(value).replaceAll(" "));
+		while (m.find())
+			out.add(px(Double.parseDouble(m.group(1)), m.group(2)));
+		return out;
+	}
+
+	private static Double toPx(String value) {
+		var m = ABSOLUTE.matcher(value);
+		return m.find() ? px(Double.parseDouble(m.group(1)), m.group(2)) : null;
+	}
+
+	/** Normalises to px. {@code rem} resolves at the browser default because nothing here sets a root font-size. */
+	private static double px(double n, String unit) {
+		return "rem".equals(unit) ? n * 16.0 : n;
+	}
+
+	private static List<Decl> declarations(String selector, String body) {
+		var out = new ArrayList<Decl>();
+		for (var raw : body.split(";")) {
+			var colon = raw.indexOf(':');
+			if (colon < 0)
+				continue;
+			var property = raw.substring(0, colon).trim().toLowerCase(Locale.ROOT);
+			var value = normalise(raw.substring(colon + 1));
+			if (property.isEmpty() || property.startsWith("--") || value.isEmpty())
+				continue;
+			out.add(new Decl(selector, property, value));
+		}
+		return out;
+	}
+
+	private static String normalise(String s) {
+		return s.replaceAll("\\s+", " ").trim();
+	}
+
+	/** Blanks out comment content so a value mentioned in a comment is not read as a declaration. */
+	private static String stripComments(String s) {
+		var out = new StringBuilder(s.length());
+		var i = 0;
+		while (i < s.length()) {
+			if (s.charAt(i) == '/' && i + 1 < s.length() && s.charAt(i + 1) == '*') {
+				i += 2;
+				while (i + 1 < s.length() && !(s.charAt(i) == '*' && s.charAt(i + 1) == '/')) {
+					if (s.charAt(i) == '\n')
+						out.append('\n');
+					i++;
+				}
+				i = Math.min(s.length(), i + 2);
+				continue;
+			}
+			out.append(s.charAt(i));
+			i++;
+		}
+		return out.toString();
+	}
+}
diff --git a/juneau-rest/juneau-rest-server-views/src/test/java/org/apache/juneau/rest/server/views/ChromeScale_ContractScan_Test.java b/juneau-rest/juneau-rest-server-views/src/test/java/org/apache/juneau/rest/server/views/ChromeScale_ContractScan_Test.java
new file mode 100644
index 0000000000..9fe6181832
--- /dev/null
+++ b/juneau-rest/juneau-rest-server-views/src/test/java/org/apache/juneau/rest/server/views/ChromeScale_ContractScan_Test.java
@@ -0,0 +1,144 @@
+/*
+ * 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 org.junit.jupiter.api.Assertions.*;
+
+import java.io.*;
+import java.nio.charset.*;
+
+import org.apache.juneau.*;
+import org.junit.jupiter.api.*;
+
+/**
+ * Guards the shared chrome scale contract on the served {@code juneau-views.css}: the steps are declared once
+ * each, and no surface writes a literal that duplicates one.
+ *
+ * <p>
+ * Driven by {@link ChromeScaleScanner}, which carries the contract's own step table and the reasoning behind
+ * what it does and does not evaluate.
+ */
+class ChromeScale_ContractScan_Test extends TestBase {
+
+	private static String viewsCss() throws IOException {
+		try (var in = ChromeScale_ContractScan_Test.class.getResourceAsStream("/org/apache/juneau/views/juneau-views.css")) {
+			assertNotNull(in, "juneau-views.css not found on the test classpath");
+			return new String(in.readAllBytes(), StandardCharsets.UTF_8);
+		}
+	}
+
+	//-----------------------------------------------------------------------------------------------------------------
+	// a) Every step is declared exactly once, at the value the contract states
+	//-----------------------------------------------------------------------------------------------------------------
+
+	@Test void a01_everyStepIsDeclaredExactlyOnce() throws IOException {
+		var problems = ChromeScaleScanner.checkDeclaredExactlyOnce(viewsCss());
+		assertTrue(problems.isEmpty(), () -> "chrome scale declaration problems:\n  " + String.join("\n  ", problems));
+	}
+
+	/**
+	 * The ladders are declared whole, so a step with no consumer today is still declared. Asserting the count
+	 * pins that: a future edit that prunes an "unused" step has to come through this test.
+	 */
+	@Test void a02_ladderIsDeclaredWhole_includingStepsWithNoConsumerYet() throws IOException {
+		var css = viewsCss();
+		assertTrue(css.contains("--jc-space-5: 24px;"), "the spacing ladder is declared whole, unused steps included");
+		assertTrue(css.contains("--jc-space-6: 32px;"), "the spacing ladder is declared whole, unused steps included");
+		assertEquals(16, ChromeScaleScanner.scale().size());
+	}
+
+	//-----------------------------------------------------------------------------------------------------------------
+	// b) No literal duplicates a declared step
+	//-----------------------------------------------------------------------------------------------------------------
+
+	@Test void b01_noLiteralDuplicatesADeclaredStep() throws IOException {
+		var r = ChromeScaleScanner.scan(viewsCss());
+		assertTrue(r.violations().isEmpty(), () -> "literals duplicating a declared step:\n  "
+			+ String.join("\n  ", r.violations()));
+	}
+
+	/**
+	 * A scanner that silently stops matching reads as a passing test, which is worse than no scanner. The scan
+	 * must actually reach a meaningful number of declarations on the properties the scale covers.
+	 */
+	@Test void b02_scanIsNotVacuous() throws IOException {
+		var r = ChromeScaleScanner.scan(viewsCss());
+		assertTrue(r.checked().size() > 20, () -> "scan examined only " + r.checked().size()
+			+ " declarations - it has probably stopped matching rather than found a clean file");
+	}
+
+	/**
+	 * The recorded-exception table is a ratchet, not an allowlist that may rot: an entry matching nothing means
+	 * the declaration it excused has moved or been fixed, and the entry must go rather than sit there quietly
+	 * widening what the scan will tolerate.
+	 */
+	@Test void b03_everyRecordedExceptionStillMatchesSomething() throws IOException {
+		var r = ChromeScaleScanner.scan(viewsCss());
+		var stale = ChromeScaleScanner.recordedLiterals().stream()
+			.filter(x -> !r.matchedRecords().contains(x))
+			.map(x -> x.selector() + " { " + x.property() + ": " + x.value() + " }")
+			.toList();
+		assertTrue(stale.isEmpty(), () -> "recorded exceptions that no longer match any declaration - remove them:\n  "
+			+ String.join("\n  ", stale));
+	}
+
+	/** Every recorded exception states why it is not spending a step; a bare entry is not auditable. */
+	@Test void b04_everyRecordedExceptionCarriesAReason() {
+		ChromeScaleScanner.recordedLiterals()
+			.forEach(x -> assertFalse(x.reason() == null || x.reason().isBlank(),
+				() -> "recorded exception with no reason: " + x.selector() + " { " + x.property() + " }"));
+	}
+
+	/**
+	 * Proves the scan can actually fail. Without this, (b01) passing tells you nothing about whether the check
+	 * works or merely never fires.
+	 */
+	@Test void b05_syntheticDuplicateLiteralIsCaught() {
+		var r = ChromeScaleScanner.scan(".synthetic-surface { height: 32px; }");
+		assertEquals(1, r.violations().size(), () -> "expected the synthetic duplicate to be caught: " + r.violations());
+		assertTrue(r.violations().get(0).contains("--jc-chrome-control-height"), r.violations().get(0));
+	}
+
+	/**
+	 * An {@code em} value must never be treated as a step match. Its computed value depends on a font-size
+	 * context this file does not have one of, and on form controls that context is a UA/system font that differs
+	 * by browser - so an engine-specific computation would fail on one platform and pass on another.
+	 */
+	@Test void b06_emValuesAreNeverTreatedAsAStepMatch() {
+		// 0.9em computes to exactly 12px against Chrome's form-control font and to nothing near a step elsewhere.
+		var r = ChromeScaleScanner.scan(".synthetic-toggle::after { width: 0.9em; height: 0.9em; }");
+		assertTrue(r.violations().isEmpty(), () -> "an em value was evaluated as a step match: " + r.violations());
+	}
+
+	/** A provisional step has no rendered consumer yet, so an existing literal must not be bound to its value. */
+	@Test void b07_provisionalStepValuesDoNotTriggerAViolation() {
+		var r = ChromeScaleScanner.scan(".synthetic-label { font-size: 0.8125rem; }");
+		assertTrue(r.violations().isEmpty(), () -> "a provisional step value was enforced: " + r.violations());
+	}
+
+	/** A declaration already spending a token is compliant, fallback and all. */
+	@Test void b08_tokenFallbackIsNotReadAsABareLiteral() {
+		var r = ChromeScaleScanner.scan(".synthetic-grid { gap: var(--jc-card-gap, 1rem); }");
+		assertTrue(r.violations().isEmpty(), () -> "a var() fallback was read as a bare literal: " + r.violations());
+	}
+
+	/** {@code width} is a scale property on an SVG glyph and a content measure everywhere else. */
+	@Test void b09_widthIsOnlyCheckedOnGlyphs() {
+		assertTrue(ChromeScaleScanner.scan(".synthetic-cell { width: 16px; }").violations().isEmpty());
+		assertEquals(1, ChromeScaleScanner.scan(".synthetic-btn svg { width: 16px; }").violations().size());
+	}
+}
diff --git a/juneau-rest/juneau-rest-server-views/src/test/java/org/apache/juneau/rest/server/views/RawContentSinkScanner.java b/juneau-rest/juneau-rest-server-views/src/test/java/org/apache/juneau/rest/server/views/RawContentSinkScanner.java
index e08555b76e..5bcba01157 100644
--- a/juneau-rest/juneau-rest-server-views/src/test/java/org/apache/juneau/rest/server/views/RawContentSinkScanner.java
+++ b/juneau-rest/juneau-rest-server-views/src/test/java/org/apache/juneau/rest/server/views/RawContentSinkScanner.java
@@ -31,7 +31,11 @@ import java.util.regex.*;
  * modeled on. It scans this module's own Java sources (both {@code src/main/java} and {@code src/test/java}, since
  * unlike the {@code <script>}-JSON sink this is a brand-new, forward-looking guardrail with no pre-existing
  * "known-good" callers to anchor a main-source-only scan to &mdash; see the accompanying test's anti-vacuous
- * checks) and fails the build if any call to the {@link Tab#content(String)}/{@link Subtab#content(String)}
+ * checks) &mdash; <b>and also</b> the sibling widgets module's Java sources, the same way {@link #scanShippedJs}
+ * already follows the card/calendar/chrome JS assets across the module boundary (see {@link #WIDGETS_MODULE_DIR}):
+ * a raw-markup sink is a raw-markup sink regardless of which of the two card-widget modules declares it. It fails
+ * the build if any call to the {@link Tab#content(String)}/{@link Subtab#content(String)}/
+ * {@link org.apache.juneau.rest.server.widgets.CardContent#content(String) CardContent#content(String)}
  * fluent-setter passes an argument that is not a compile-time string literal (or a {@code +}-concatenation of
  * literals).
  *
@@ -51,12 +55,13 @@ import java.util.regex.*;
  * <h5 class='section'>What counts as a sink</h5>
  * <p>
  * A sink is any source-level call whose method name is exactly {@code content} (i.e. {@code .content(...)}) &mdash;
- * scoped to this module's own tree, where (verified before this scanner was written) the only such calls are the
- * {@link Tab}/{@link Subtab} fluent setters this item adds; nothing else in this module declares or calls a
+ * scoped to this module's own tree plus the sibling widgets module's tree (see {@link #scanTree}), where (verified
+ * when each of the two callers was added) the only such calls are the {@link Tab}/{@link Subtab} fluent setters and
+ * the widgets module's {@code CardContent} fluent setter; nothing else in either tree declares or calls a
  * {@code content(...)} method. This scanner does not attempt receiver-type resolution and does not scan outside
- * this module (other Juneau modules declare unrelated {@code content(...)} methods, e.g.
- * {@code RestRequest.content(Object)}, which are out of scope by construction because they are never on this
- * module's classpath of scanned files).
+ * these two modules (other Juneau modules declare unrelated {@code content(...)} methods, e.g.
+ * {@code RestRequest.content(Object)}, which are out of scope by construction because they are never on the
+ * scanned trees).
  *
  * <h5 class='section'>Why it must also assert it is not vacuous</h5>
  * <p>
@@ -106,6 +111,14 @@ final class RawContentSinkScanner {
 	private static final String WIDGETS_JS_DIR =
 		"../juneau-rest-server-widgets/src/main/resources/org/apache/juneau/widgets";
 
+	/**
+	 * The widgets module's root, relative to this module's root &mdash; the Java-source counterpart of
+	 * {@link #WIDGETS_JS_DIR}.  The card body beans (including the raw-markup {@code CardContent}) live there, so
+	 * {@link #scanTree} follows this path to keep scanning the file that declares the sink rather than stopping at
+	 * the module boundary the test happens to run in.
+	 */
+	private static final String WIDGETS_MODULE_DIR = "../juneau-rest-server-widgets";
+
 	/** First-party icon-registry SVG assignments; never request/app/renderer text. */
 	private static final List<AllowedJsSink> SHIPPED_JS_ALLOWLIST = List.of(
 		new AllowedJsSink(VIEWS_JS_DIR + "/juneau-views.js", "b.innerHTML = markup;"),
@@ -287,17 +300,31 @@ final class RawContentSinkScanner {
 	}
 
 	/**
-	 * Walks the specified module root and scans every {@code src/main/java} and {@code src/test/java} Java
-	 * source under it (both trees, per this class's javadoc: this guardrail has no pre-existing main-source-only
-	 * "known-good" anchor to lean on the way {@code ScriptJsonSinkScanner} does).
+	 * Walks the specified module root <b>and</b> the sibling widgets module root ({@link #WIDGETS_MODULE_DIR}),
+	 * scanning every {@code src/main/java} and {@code src/test/java} Java source under each (both trees per
+	 * module, per this class's javadoc: this guardrail has no pre-existing main-source-only "known-good" anchor to
+	 * lean on the way {@code ScriptJsonSinkScanner} does).  The widgets module is included because it declares its
+	 * own {@code content(...)} sink ({@code CardContent}) and this guardrail follows the sink, not the module the
+	 * test happens to run in.
 	 *
-	 * @param moduleRoot The module root (e.g. {@code juneau-rest/juneau-rest-server-views}).
-	 * @return The aggregated sinks and violations across the tree.
-	 * @throws IOException If the tree cannot be walked.
+	 * @param moduleRoot The views module root (e.g. {@code juneau-rest/juneau-rest-server-views}).
+	 * @return The aggregated sinks and violations across both trees.
+	 * @throws IOException If either tree cannot be walked.
 	 */
 	static Result scanTree(Path moduleRoot) throws IOException {
 		var sinks = new ArrayList<Sink>();
 		var violations = new ArrayList<String>();
+		scanJavaSources(moduleRoot, sinks, violations);
+		scanJavaSources(moduleRoot.resolve(WIDGETS_MODULE_DIR), sinks, violations);
+		return new Result(sinks, violations);
+	}
+
+	/**
+	 * Scans one module root's {@code src/main/java} and {@code src/test/java} trees, appending every sink and
+	 * violation found to {@code sinks}/{@code violations}.  Extracted from {@link #scanTree} so that method can
+	 * walk both this module and the sibling widgets module with identical logic.
+	 */
+	private static void scanJavaSources(Path moduleRoot, List<Sink> sinks, List<String> violations) throws IOException {
 		var target = File.separator + "target" + File.separator;
 		for (var sourceDir : List.of("main", "test")) {
 			var srcRoot = moduleRoot.resolve("src").resolve(sourceDir).resolve("java");
@@ -317,7 +344,6 @@ final class RawContentSinkScanner {
 				}
 			}
 		}
-		return new Result(sinks, violations);
 	}
 
 	/**
diff --git a/juneau-rest/juneau-rest-server-views/src/test/java/org/apache/juneau/rest/server/views/SymbolSprite_StemIds_Test.java b/juneau-rest/juneau-rest-server-views/src/test/java/org/apache/juneau/rest/server/views/SymbolSprite_StemIds_Test.java
new file mode 100644
index 0000000000..d673b6e344
--- /dev/null
+++ b/juneau-rest/juneau-rest-server-views/src/test/java/org/apache/juneau/rest/server/views/SymbolSprite_StemIds_Test.java
@@ -0,0 +1,86 @@
+/*
+ * 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 java.util.*;
+import java.util.regex.*;
+
+import org.apache.juneau.*;
+import org.junit.jupiter.api.*;
+
+/**
+ * Pins the exact set of {@code <symbol>} stem ids shipped in {@code juneau-symbols.svg}.
+ *
+ * <p>
+ * A third-party host page can override one of these glyphs by looking the stem id up by name and swapping in a
+ * replacement drawing for it. That lookup is name-based only, so if a stem id here is renamed - or quietly added
+ * or removed - without a matching change on the consuming side, the override stops finding its target. The
+ * result is not an error: the glyph simply renders as nothing, with no signal anywhere in this module. Guarding
+ * against that silent failure is the entire point of this test, so the check below is set equality rather than a
+ * one-directional containment check - a containment check would happily let a new id slip in unnoticed.
+ */
+class SymbolSprite_StemIds_Test extends TestBase {
+
+	/**
+	 * The complete set of stem ids as of the time this guard was written. This set is intentionally frozen:
+	 * any difference from what is actually shipped must be a deliberate, reviewed decision, not an accident of
+	 * an artwork or naming change.
+	 */
+	private static final Set<String> EXPECTED_IDS = Set.of(
+		"juneau-sym-cancel", "juneau-sym-check", "juneau-sym-chevrondown", "juneau-sym-chevronright",
+		"juneau-sym-close", "juneau-sym-collapse_all", "juneau-sym-columns", "juneau-sym-copy", "juneau-sym-csv",
+		"juneau-sym-download", "juneau-sym-edit", "juneau-sym-filter", "juneau-sym-new", "juneau-sym-pdf",
+		"juneau-sym-refresh", "juneau-sym-search", "juneau-sym-settings", "juneau-sym-spreadsheet",
+		"juneau-sym-toggle-deleted", "juneau-sym-toggle_column_search"
+	);
+
+	private static final Pattern SYMBOL_ID_PATTERN = Pattern.compile("<symbol\\s+id=\"([^\"]+)\"");
+
+	private static Set<String> actualIds() throws IOException {
+		String svg;
+		try (var in = ViewsMixin.class.getResourceAsStream(ViewsMixin.SYMBOLS_SVG_RESOURCE)) {
+			assertNotNull(in, () -> "missing classpath resource: " + ViewsMixin.SYMBOLS_SVG_RESOURCE);
+			svg = new String(in.readAllBytes(), UTF_8);
+		}
+		var ids = new LinkedHashSet<String>();
+		var m = SYMBOL_ID_PATTERN.matcher(svg);
+		while (m.find())
+			ids.add(m.group(1));
+		return ids;
+	}
+
+	@Test void a01_stemIdSetIsPinned() throws Exception {
+		var actual = actualIds();
+		if (actual.equals(EXPECTED_IDS))
+			return;
+
+		var removed = new TreeSet<>(EXPECTED_IDS);
+		removed.removeAll(actual);
+		var added = new TreeSet<>(actual);
+		added.removeAll(EXPECTED_IDS);
+
+		fail("juneau-symbols.svg <symbol> stem ids no longer match the pinned set - removed: " + removed
+			+ ", added: " + added + ". A stem id is a lookup key a host page can override a glyph by; changing,"
+			+ " adding, or removing one here (even one renamed to something equivalent-looking) breaks that"
+			+ " lookup silently, with no error on either side. If this change is intentional, update"
+			+ " EXPECTED_IDS to match.");
+	}
+}
diff --git a/juneau-rest/juneau-rest-server-views/src/test/java/org/apache/juneau/rest/server/views/ViewsJs_RibbonNormalize_Test.java b/juneau-rest/juneau-rest-server-views/src/test/java/org/apache/juneau/rest/server/views/ViewsJs_RibbonNormalize_Test.java
new file mode 100644
index 0000000000..c3a05a5da7
--- /dev/null
+++ b/juneau-rest/juneau-rest-server-views/src/test/java/org/apache/juneau/rest/server/views/ViewsJs_RibbonNormalize_Test.java
@@ -0,0 +1,232 @@
+/*
+ * 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 static org.junit.jupiter.api.Assumptions.*;
+
+import java.io.*;
+import java.nio.file.*;
+import java.util.*;
+import java.util.concurrent.*;
+
+import org.apache.juneau.*;
+import org.apache.juneau.marshall.marshaller.*;
+import org.junit.jupiter.api.*;
+
+/**
+ * The module's first behavioral DOM harness for {@code buildRibbon(...)} in {@code juneau-ribbon.js}, covering the
+ * refresh-to-trailing-cluster normalization.
+ *
+ * <p>
+ * The existing wiring canaries in {@code ViewsMixin_Serving_Test} (e.g. {@code f04_...}) assert only source
+ * substrings - {@code function place(}, {@code juneau-view-ribbon-group}, {@code __ungrouped} - every one of which
+ * survives this normalizer landing, so they stay green regardless of whether refresh actually moves. This class
+ * asserts the rendered DOM shape instead: which buttons land in which {@code .juneau-view-ribbon-group} cluster,
+ * and in what order, for each of the normalizer's specified cases.
+ */
+class ViewsJs_RibbonNormalize_Test extends TestBase {
+
+	private static String ribbonJs() throws IOException {
+		try (var in = ViewsMixin.class.getResourceAsStream(ViewsMixin.RIBBON_JS_RESOURCE)) {
+			assertNotNull(in);
+			return new String(in.readAllBytes(), UTF_8);
+		}
+	}
+
+	//------------------------------------------------------------------------------------------------------------------
+	// Behavioral harness
+	//------------------------------------------------------------------------------------------------------------------
+
+	private static Map<?,?> report;
+
+	@BeforeAll
+	static void probeIfNodeAvailable() throws Exception {
+		if (!nodeAvailable())
+			return;
+		var harness = locateHarness();
+		if (harness == null)
+			return;
+		var ribbonFile = Files.createTempFile("juneau-ribbon-", ".js");
+		try {
+			Files.writeString(ribbonFile, ribbonJs(), UTF_8);
+			report = Json.to(runNode(harness, ribbonFile), Map.class);
+		} finally {
+			Files.deleteIfExists(ribbonFile);
+		}
+	}
+
+	private static boolean nodeAvailable() {
+		try {
+			var p = new ProcessBuilder("node", "--version").redirectErrorStream(true).start();
+			if (!p.waitFor(5, TimeUnit.SECONDS)) {
+				p.destroyForcibly();
+				return false;
+			}
+			return p.exitValue() == 0;
+		} catch (Exception e) {
+			return false;
+		}
+	}
+
+	private static Path locateHarness() {
+		var basedir = System.getProperty("basedir");
+		if (basedir != null) {
+			var p = Path.of(basedir, "src/test/js/ribbon-normalize.cjs");
+			if (Files.isRegularFile(p)) return p.toAbsolutePath().normalize();
+		}
+		for (var rel : List.of(
+			"src/test/js/ribbon-normalize.cjs",
+			"juneau-rest/juneau-rest-server-views/src/test/js/ribbon-normalize.cjs"
+		)) {
+			var p = Path.of(rel);
+			if (Files.isRegularFile(p)) return p.toAbsolutePath().normalize();
+		}
+		return null;
+	}
+
+	private static String runNode(Path harness, Path ribbonJs) throws Exception {
+		var stdout = Files.createTempFile("ribbon-normalize-stdout-", ".json");
+		var stderr = Files.createTempFile("ribbon-normalize-stderr-", ".txt");
+		try {
+			var pb = new ProcessBuilder(List.of("node", harness.toString(), ribbonJs.toString()))
+				.redirectOutput(stdout.toFile())
+				.redirectError(stderr.toFile());
+			var p = pb.start();
+			if (!p.waitFor(30, TimeUnit.SECONDS)) {
+				p.destroyForcibly();
+				fail("ribbon-normalize.cjs did not finish within 30s; stderr:\n" + quietRead(stderr));
+			}
+			if (p.exitValue() != 0)
+				fail("ribbon-normalize.cjs exited " + p.exitValue() + "; stderr:\n" + quietRead(stderr)
+					+ "\nstdout:\n" + quietRead(stdout));
+			return Files.readString(stdout, UTF_8);
+		} finally {
+			Files.deleteIfExists(stdout);
+			Files.deleteIfExists(stderr);
+		}
+	}
+
+	private static String quietRead(Path p) {
+		try { return Files.readString(p, UTF_8); }
+		catch (IOException e) { return "(unreadable: " + e.getMessage() + ")"; }
+	}
+
+	private static Map<?,?> report() {
+		assumeTrue(report != null, "node not available or ribbon-normalize.cjs not found — behavioral layer skipped");
+		return report;
+	}
+
+	@Test void a01_harnessLoadedTheRibbonRuntime() {
+		assertEquals(true, report().get("hasBuild"), report()::toString);
+		assertEquals(true, report().get("hasNormalizeRibbon"), () -> "normalizeRibbon must be exported on NS.ribbon: " + report());
+	}
+
+	//------------------------------------------------------------------------------------------------------------------
+	// Pure function: normalizeRibbon(actions) - DOM-free
+	//------------------------------------------------------------------------------------------------------------------
+
+	@Test void b01_noRefreshAction_isAnIdentityNoOp() {
+		var r = report();
+		assertEquals(true, r.get("pure_noRefresh_isSameReference"),
+			() -> "with no refresh action, normalizeRibbon must return the SAME array reference, unperturbed: " + r);
+	}
+
+	@Test void b02_oneRefreshAction_movesLastIntoItsOwnGroup() {
+		var r = report();
+		assertEquals("export,refresh", r.get("pure_oneRefresh_order"), r::toString);
+		assertEquals("__refresh", r.get("pure_oneRefresh_lastGroup"), r::toString);
+		assertEquals(true, r.get("pure_oneRefresh_exportGroupUnset"),
+			() -> "the export action itself must be untouched by the move: " + r);
+	}
+
+	@Test void b03_twoOrMoreRefreshActions_allMoveTogetherPreservingRelativeOrder() {
+		var r = report();
+		assertEquals("export,refresh:first,refresh:second", r.get("pure_twoRefresh_order"), r::toString);
+		assertEquals(true, r.get("pure_twoRefresh_bothInRefreshGroup"),
+			() -> "both refresh actions must land in the SAME trailing __refresh cluster: " + r);
+		assertEquals(true, r.get("pure_twoRefresh_relativeOrderPreserved"), r::toString);
+	}
+
+	@Test void b04_explicitGroupOnRefresh_optsOutCompletely() {
+		var r = report();
+		assertEquals("refresh,export", r.get("pure_explicitGroup_order"),
+			() -> "an explicitly-grouped refresh must NOT be relocated to the end: " + r);
+		assertEquals(true, r.get("pure_explicitGroup_groupUnchanged"),
+			() -> "an explicitly-grouped refresh must not be re-grouped into __refresh: " + r);
+	}
+
+	@Test void b05_danglingTrailingDividerIsDropped() {
+		var r = report();
+		assertEquals("export,refresh", r.get("pure_trailingDivider_order"),
+			() -> "a divider stranded in trailing position by the move must be dropped: " + r);
+		assertEquals(true, r.get("pure_trailingDivider_dropped"), r::toString);
+		// A NON-trailing divider (still separating two other actions once refresh is gone) must survive.
+		assertEquals("divider,export,refresh", r.get("pure_nonTrailingDivider_order"), r::toString);
+	}
+
+	//------------------------------------------------------------------------------------------------------------------
+	// DOM behavior: buildRibbon(viewDef, ctx), through the full render path
+	//------------------------------------------------------------------------------------------------------------------
+
+	@Test void c01_noRefreshAction_domIsUnaffected() {
+		var r = report();
+		assertEquals(1L, ((Number)r.get("dom_noRefresh_groupCount")).longValue(), r::toString);
+		assertEquals(2L, ((Number)r.get("dom_noRefresh_onlyGroupButtonCount")).longValue(), r::toString);
+	}
+
+	@Test void c02_oneRefreshDeclaredFirst_rendersAsTwoClustersWithRefreshAloneAndLast() {
+		var r = report();
+		assertEquals(2L, ((Number)r.get("dom_oneRefresh_groupCount")).longValue(),
+			() -> "must render TWO clusters (exports, refresh) - not one merged cluster: " + r);
+		assertEquals(2L, ((Number)r.get("dom_oneRefresh_firstGroupButtonCount")).longValue(),
+			() -> "the first cluster must be the two export buttons: " + r);
+		assertEquals(1L, ((Number)r.get("dom_oneRefresh_lastGroupButtonCount")).longValue(),
+			() -> "the last cluster must hold refresh ALONE: " + r);
+		assertEquals(true, r.get("dom_oneRefresh_lastGroupIsRefreshGlyph"), r::toString);
+		assertEquals(true, r.get("dom_oneRefresh_lastGroupIsLastChildOfBar"),
+			() -> "the refresh cluster must be the rightmost element of the bar: " + r);
+	}
+
+	@Test void c03_twoRefreshActions_bothLandInOneTrailingClusterInRelativeOrder() {
+		var r = report();
+		assertEquals(2L, ((Number)r.get("dom_twoRefresh_groupCount")).longValue(), r::toString);
+		assertEquals(2L, ((Number)r.get("dom_twoRefresh_lastGroupButtonCount")).longValue(),
+			() -> "both refresh buttons must share ONE trailing cluster: " + r);
+		assertEquals("A,B", r.get("dom_twoRefresh_lastGroupTitles"),
+			() -> "relative order of the moved refresh actions must be preserved: " + r);
+	}
+
+	@Test void c04_explicitGroupOnRefresh_staysWithItsDeclaredNeighbourNotRelocated() {
+		var r = report();
+		assertEquals(2L, ((Number)r.get("dom_explicitGroup_groupCount")).longValue(), r::toString);
+		assertEquals(2L, ((Number)r.get("dom_explicitGroup_firstGroupButtonCount")).longValue(), r::toString);
+		assertEquals("Refresh,Column search", r.get("dom_explicitGroup_firstGroupTitles"),
+			() -> "refresh must stay clustered with its declared group-mate, in declared order: " + r);
+		assertEquals(true, r.get("dom_explicitGroup_isNotLastChildOfBar"),
+			() -> "an opted-out refresh must NOT be relocated to the far right: " + r);
+	}
+
+	@Test void c05_danglingTrailingDivider_isDroppedFromTheRenderedBar() {
+		var r = report();
+		assertEquals(2L, ((Number)r.get("dom_trailingDivider_groupCount")).longValue(), r::toString);
+		assertEquals(0L, ((Number)r.get("dom_trailingDivider_dividerCount")).longValue(),
+			() -> "a divider stranded before the moved refresh must not render as an empty seam: " + r);
+		assertEquals(1L, ((Number)r.get("dom_trailingDivider_lastGroupButtonCount")).longValue(), r::toString);
+	}
+}
diff --git a/juneau-rest/juneau-rest-server-views/src/test/java/org/apache/juneau/rest/server/views/ViewsMixin_Serving_Test.java b/juneau-rest/juneau-rest-server-views/src/test/java/org/apache/juneau/rest/server/views/ViewsMixin_Serving_Test.java
index 599bea4219..5125435175 100644
--- a/juneau-rest/juneau-rest-server-views/src/test/java/org/apache/juneau/rest/server/views/ViewsMixin_Serving_Test.java
+++ b/juneau-rest/juneau-rest-server-views/src/test/java/org/apache/juneau/rest/server/views/ViewsMixin_Serving_Test.java
@@ -426,7 +426,11 @@ class ViewsMixin_Serving_Test extends TestBase {
 		var body = cWithMixin.get(ViewsMixin.VIEWS_CSS_PATH).run().assertStatus(200).getContent().asString();
 		assertTrue(body.contains(".juneau-view-ribbon-btn {"), body);
 		assertTrue(body.contains("min-width: 32px"), body);
-		assertTrue(body.contains("height: 32px"), body);
+		// The button's height now spends the shared control-height step rather than repeating its literal, so the
+		// shape is pinned by asserting BOTH halves - the reference here and the step's declared value - rather
+		// than dropping to the reference alone, which would pass even if the step were re-valued.
+		assertTrue(body.contains("height: var(--jc-chrome-control-height)"), body);
+		assertTrue(body.contains("--jc-chrome-control-height: 32px"), body);
 		assertTrue(body.contains("display: flex"), body);
 		assertTrue(body.contains("border: 1px solid"), body);
 		assertTrue(body.contains(".juneau-view-ribbon-btn svg {"), body);
@@ -498,8 +502,10 @@ class ViewsMixin_Serving_Test extends TestBase {
 		var fnBody = functionBody(body, "function buildRibbon(");
 		assertTrue(fnBody.contains("function place("), fnBody);
 		assertTrue(fnBody.contains("juneau-view-ribbon-group"), fnBody);
-		// Ungrouped icon buttons (refresh + export, etc.) share one synthetic cluster so they render as a
-		// connected ribbon rather than orphan glyphs.  An explicit .group() still splits clusters.
+		// Ungrouped icon buttons (export, columnSearchToggle, etc.) share one synthetic cluster so they render as
+		// a connected ribbon rather than orphan glyphs.  refresh is excluded from that cluster by default - it is
+		// normalized into its own trailing group instead (see normalizeRibbon) - unless it declares an explicit
+		// .group() of its own, in which case it joins that group like any other action.
 		assertTrue(fnBody.contains("__ungrouped"), fnBody);
 		assertTrue(fnBody.contains("place("), fnBody);
 		// A divider always closes any open cluster (a divider is a deliberate visual break, not a grouping seam).
diff --git a/juneau-rest/juneau-rest-server-views/src/test/js/ribbon-normalize.cjs b/juneau-rest/juneau-rest-server-views/src/test/js/ribbon-normalize.cjs
new file mode 100644
index 0000000000..e93cf1ebf0
--- /dev/null
+++ b/juneau-rest/juneau-rest-server-views/src/test/js/ribbon-normalize.cjs
@@ -0,0 +1,207 @@
+/*
+ * 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.
+ */
+
+/*
+ * ribbon-normalize.cjs - the module's first always-on DOM harness for buildRibbon(...) in juneau-ribbon.js, built
+ * to prove the refresh-to-trailing-cluster normalization against real rendered DOM structure rather than source
+ * text (the existing wiring canaries in ViewsMixin_Serving_Test only assert substrings that survive this change
+ * unchanged).
+ *
+ * Covers, each as its own case:
+ *
+ *   1. No refresh action - normalizeRibbon is an identity no-op, and buildRibbon's output is unaffected.
+ *   2. Exactly one (ungrouped) refresh - it is removed from its declared position and rendered alone, last, in
+ *      its own one-button ".juneau-view-ribbon-group" cluster; the export cluster ahead of it is untouched.
+ *   3. Two or more ungrouped refresh actions - ALL of them move, preserving their relative order, into the SAME
+ *      trailing cluster (not split across two clusters, not left behind).
+ *   4. A refresh action carrying an explicit `group` opts out entirely: it is not moved and does not join the
+ *      synthetic `__refresh` cluster - it stays exactly where its neighbours put it.
+ *   5. A `divider` left dangling in trailing position by the move (nothing follows it once refresh is gone) is
+ *      dropped, not rendered as an empty seam; a NON-trailing divider (still separating two other actions)
+ *      survives untouched.
+ *
+ * Usage:  node ribbon-normalize.cjs <juneau-ribbon.js>
+ *
+ * Prints ONE JSON object to stdout; every assertion lives in the Java test.
+ */
+'use strict';
+
+const fs = require('node:fs');
+const path = require('node:path');
+const vm = require('node:vm');
+const { makeEnv } = require(path.join(__dirname, 'views-dom-shim.cjs'));
+
+const ribbonJsPath = process.argv[2];
+if (!ribbonJsPath) {
+	console.error('usage: node ribbon-normalize.cjs <juneau-ribbon.js>');
+	process.exit(2);
+}
+const ribbonJsSource = fs.readFileSync(path.resolve(ribbonJsPath), 'utf8');
+
+/**
+ * Loads a fresh copy of juneau-ribbon.js into its own env/sandbox.  `withExportFeature` installs a minimal
+ * jQuery-with-DataTables-Buttons stand-in so the `export` branch of buildRibbon actually resolves and renders
+ * its buttons (feature-detection would otherwise degrade export to nothing, per the file's own design).
+ */
+function loadRibbon(withExportFeature) {
+	const env = makeEnv();
+	if (withExportFeature)
+		env.window.jQuery = { fn: { dataTable: { Buttons: function () {} } } };
+	const sandbox = {
+		window: env.window, document: env.document, console: console,
+		setTimeout: function () { return 0; }, clearTimeout: function () {},
+		setInterval: function () { return 0; }, clearInterval: function () {}
+	};
+	vm.runInNewContext(ribbonJsSource, sandbox, { filename: 'juneau-ribbon.js' });
+	return { env: env, NS: env.window.JuneauViews };
+}
+
+const out = {};
+const first = loadRibbon(false);
+out.hasBuild = !!(first.NS && first.NS.ribbon && typeof first.NS.ribbon.build === 'function');
+out.hasNormalizeRibbon = !!(first.NS && first.NS.ribbon && typeof first.NS.ribbon.normalizeRibbon === 'function');
+if (!out.hasBuild) { process.stdout.write(JSON.stringify(out)); process.exit(0); }
+
+/** A minimal RibbonAction-shaped action literal, mirroring the RibbonAction wire shape. */
+function action(type, extra) { return Object.assign({ type: type }, extra || {}); }
+
+// ------------------------------------------------------------------------------------------------------------------
+// Pure function: normalizeRibbon(actions) - DOM-free, run only when the export exists (pre-fix it does not).
+// ------------------------------------------------------------------------------------------------------------------
+
+if (out.hasNormalizeRibbon) {
+	const normalizeRibbon = first.NS.ribbon.normalizeRibbon;
+
+	// 1) No refresh action - identity no-op (same array reference back).
+	const noRefresh = [action('export', { buttons: ['copy', 'csv'] }), action('columnSearchToggle')];
+	out.pure_noRefresh_isSameReference = normalizeRibbon(noRefresh) === noRefresh;
+
+	// 2) Exactly one refresh - moved last, into '__refresh'; the export action itself is untouched.
+	const oneRefresh = [action('refresh'), action('export', { buttons: ['copy', 'csv'] })];
+	const oneRefreshResult = normalizeRibbon(oneRefresh);
+	out.pure_oneRefresh_order = oneRefreshResult.map(function (x) { return x.type; }).join(',');
+	out.pure_oneRefresh_lastGroup = oneRefreshResult[oneRefreshResult.length - 1].group;
+	out.pure_oneRefresh_exportGroupUnset = oneRefreshResult[0].type === 'export' && oneRefreshResult[0].group == null;
+
+	// 3) Two refresh actions - BOTH move, preserving relative order, into the SAME trailing group.
+	const twoRefresh = [
+		action('refresh', { title: 'first' }), action('export', { buttons: ['copy'] }), action('refresh', { title: 'second' })
+	];
+	const twoRefreshResult = normalizeRibbon(twoRefresh);
+	out.pure_twoRefresh_order = twoRefreshResult.map(function (x) { return x.type + (x.title ? ':' + x.title : ''); }).join(',');
+	out.pure_twoRefresh_bothInRefreshGroup = twoRefreshResult[1].group === '__refresh' && twoRefreshResult[2].group === '__refresh';
+	out.pure_twoRefresh_relativeOrderPreserved = twoRefreshResult[1].title === 'first' && twoRefreshResult[2].title === 'second';
+
+	// 4) Explicit group on refresh - opts out entirely: stays in place, group left exactly as declared.
+	const explicitGroup = [action('refresh', { group: 'filters' }), action('export', { buttons: ['copy'] })];
+	const explicitGroupResult = normalizeRibbon(explicitGroup);
+	out.pure_explicitGroup_order = explicitGroupResult.map(function (x) { return x.type; }).join(',');
+	out.pure_explicitGroup_groupUnchanged = explicitGroupResult[0].group === 'filters';
+
+	// 5a) Trailing divider dropped: '..., divider(), refresh()' leaves no dangling divider once refresh moves.
+	const trailingDivider = [action('export', { buttons: ['copy'] }), action('divider'), action('refresh')];
+	const trailingDividerResult = normalizeRibbon(trailingDivider);
+	out.pure_trailingDivider_order = trailingDividerResult.map(function (x) { return x.type; }).join(',');
+	out.pure_trailingDivider_dropped = trailingDividerResult.every(function (x) { return x.type !== 'divider'; });
+
+	// 5b) A NON-trailing divider (still separating two other actions once refresh is gone) survives untouched.
+	const nonTrailingDivider = [action('refresh'), action('divider'), action('export', { buttons: ['copy'] })];
+	const nonTrailingDividerResult = normalizeRibbon(nonTrailingDivider);
+	out.pure_nonTrailingDivider_order = nonTrailingDividerResult.map(function (x) { return x.type; }).join(',');
+}
+
+// ------------------------------------------------------------------------------------------------------------------
+// DOM behavior: buildRibbon(viewDef, ctx), through the full render path (the real deliverable - the canaries in
+// ViewsMixin_Serving_Test only assert source substrings, none of which change shape when this normalizer lands).
+// ------------------------------------------------------------------------------------------------------------------
+
+function groupsOf(bar) {
+	return bar.childNodes.filter(function (c) { return c.className === 'juneau-view-ribbon-group'; });
+}
+
+function dividersOf(bar) {
+	return bar.childNodes.filter(function (c) { return c.className === 'juneau-view-ribbon-divider'; });
+}
+
+function buildBar(NS, ribbon) {
+	return NS.ribbon.build({ ribbon: ribbon }, { dataTable: {}, redraw: function () {} });
+}
+
+// Case 1 - no refresh action: unaffected. One export cluster, nothing trailing added.
+{
+	const { NS } = loadRibbon(true);
+	const bar = buildBar(NS, [action('export', { buttons: ['copy', 'csv'] })]);
+	const groups = groupsOf(bar);
+	out.dom_noRefresh_groupCount = groups.length;
+	out.dom_noRefresh_onlyGroupButtonCount = groups.length ? groups[0].childNodes.length : -1;
+}
+
+// Case 2 - exactly one refresh, declared FIRST (the console's actual today-shape): two groups after the fix,
+// exports first, refresh alone and last.
+{
+	const { NS } = loadRibbon(true);
+	const bar = buildBar(NS, [action('refresh'), action('export', { buttons: ['copy', 'csv'] })]);
+	const groups = groupsOf(bar);
+	out.dom_oneRefresh_groupCount = groups.length;
+	out.dom_oneRefresh_firstGroupButtonCount = groups.length > 0 ? groups[0].childNodes.length : -1;
+	out.dom_oneRefresh_lastGroupButtonCount = groups.length > 0 ? groups[groups.length - 1].childNodes.length : -1;
+	const lastGroupBtn = groups.length > 0 ? groups[groups.length - 1].childNodes[0] : null;
+	out.dom_oneRefresh_lastGroupIsRefreshGlyph = lastGroupBtn != null && lastGroupBtn.title === 'Refresh';
+	out.dom_oneRefresh_lastGroupIsLastChildOfBar = groups.length > 0 && bar.lastElementChild === groups[groups.length - 1];
+}
+
+// Case 3 - two refresh actions around an export cluster: both move into ONE trailing group, in relative order.
+{
+	const { NS } = loadRibbon(true);
+	const bar = buildBar(NS, [
+		action('refresh', { title: 'A' }), action('export', { buttons: ['copy'] }), action('refresh', { title: 'B' })
+	]);
+	const groups = groupsOf(bar);
+	out.dom_twoRefresh_groupCount = groups.length;
+	const lastGroup = groups.length > 0 ? groups[groups.length - 1] : null;
+	out.dom_twoRefresh_lastGroupButtonCount = lastGroup ? lastGroup.childNodes.length : -1;
+	out.dom_twoRefresh_lastGroupTitles = lastGroup ? lastGroup.childNodes.map(function (b) { return b.title; }).join(',') : null;
+}
+
+// Case 4 - refresh carries an explicit group shared with a neighbour: opts out completely, stays put (here,
+// declared FIRST) rather than relocating to the end.
+{
+	const { NS } = loadRibbon(true);
+	const bar = buildBar(NS, [
+		action('refresh', { group: 'filters' }), action('columnSearchToggle', { group: 'filters' }),
+		action('export', { buttons: ['copy'] })
+	]);
+	const groups = groupsOf(bar);
+	out.dom_explicitGroup_groupCount = groups.length;
+	const firstGroup = groups.length > 0 ? groups[0] : null;
+	out.dom_explicitGroup_firstGroupButtonCount = firstGroup ? firstGroup.childNodes.length : -1;
+	out.dom_explicitGroup_firstGroupTitles = firstGroup ? firstGroup.childNodes.map(function (b) { return b.title; }).join(',') : null;
+	out.dom_explicitGroup_isNotLastChildOfBar = groups.length > 0 && bar.lastElementChild !== groups[0];
+}
+
+// Case 5 - a divider immediately before a trailing refresh is dropped (no dangling seam); export cluster and the
+// refresh cluster both survive.
+{
+	const { NS } = loadRibbon(true);
+	const bar = buildBar(NS, [action('export', { buttons: ['copy'] }), action('divider'), action('refresh')]);
+	const groups = groupsOf(bar);
+	out.dom_trailingDivider_groupCount = groups.length;
+	out.dom_trailingDivider_dividerCount = dividersOf(bar).length;
+	out.dom_trailingDivider_lastGroupButtonCount = groups.length > 0 ? groups[groups.length - 1].childNodes.length : -1;
+}
+
+process.stdout.write(JSON.stringify(out));
diff --git a/juneau-rest/juneau-rest-server-widgets/src/main/java/org/apache/juneau/rest/server/widgets/CardBody.java b/juneau-rest/juneau-rest-server-widgets/src/main/java/org/apache/juneau/rest/server/widgets/CardBody.java
index 3ffe018fd1..16a75e3769 100644
--- a/juneau-rest/juneau-rest-server-widgets/src/main/java/org/apache/juneau/rest/server/widgets/CardBody.java
+++ b/juneau-rest/juneau-rest-server-widgets/src/main/java/org/apache/juneau/rest/server/widgets/CardBody.java
@@ -20,11 +20,11 @@ package org.apache.juneau.rest.server.widgets;
  * The body-slot contract for a {@link Card}: the single, heterogeneous content a card hosts.
  *
  * <p>
- * This marker is the extension point future body types implement.  The v1 emitter dispatches over a <b>closed</b>
- * set of known implementations (v1: {@link CardFieldList} only) and <b>fails closed</b> on any unknown
- * {@code CardBody}; a later body type is added by implementing this interface, patching the emitter's closed
- * dispatch set, and bringing its <b>own</b> server-render and (if stateful) its <b>own</b> data path &mdash; it does
- * not share {@link CardFieldList}'s refresh envelope.
+ * This marker is the extension point future body types implement.  The emitter (in the views module,
+ * {@code CardGridTable}) dispatches over a <b>closed</b> set of known implementations and <b>fails closed</b> on
+ * any unknown {@code CardBody}; a new body type is added by implementing this interface, patching the emitter's
+ * closed dispatch set, and bringing its <b>own</b> server-render and (if stateful) its <b>own</b> data path
+ * &mdash; it does not share {@link CardFieldList}'s refresh envelope.
  *
  * @since 10.0.0
  */
diff --git a/juneau-rest/juneau-rest-server-widgets/src/main/java/org/apache/juneau/rest/server/widgets/CardContent.java b/juneau-rest/juneau-rest-server-widgets/src/main/java/org/apache/juneau/rest/server/widgets/CardContent.java
new file mode 100644
index 0000000000..89333370a6
--- /dev/null
+++ b/juneau-rest/juneau-rest-server-widgets/src/main/java/org/apache/juneau/rest/server/widgets/CardContent.java
@@ -0,0 +1,88 @@
+/*
+ * 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.widgets;
+
+import static org.apache.juneau.commons.utils.Shorts.*;
+
+/**
+ * A raw-markup {@link CardBody} &mdash; first-party prose or already-rendered markup hosted inside a card, emitted
+ * verbatim rather than escaped.
+ *
+ * <h5 class='section'>Ownership contract: template engine, trusted / first-party content only</h5>
+ * <p>
+ * This framework is a <b>template engine</b> on this path: <b>the caller is responsible for sanitizing
+ * {@link #content} before setting it; the framework performs no sanitization and emits the string exactly as
+ * given.</b> Nothing in this framework neutralizes {@code <script>}, {@code <style>}, inline event handlers, or
+ * {@code url(...)} sinks in this value &mdash; this is the same raw-panel-body contract this toolkit already ships
+ * for a page's tab/sub-tab panel content, applied here to a card body.
+ *
+ * <p>
+ * Accordingly, {@link #content} MUST carry <b>trusted, first-party content only</b> &mdash; markup the application
+ * itself authored or rendered from a trusted, non-attacker-controlled source (e.g. hand-written card prose, or
+ * HTML rendered from a first-party markdown document). {@link #content} MUST NOT carry live/remote/attacker-
+ * influenceable data (a request parameter, a third-party API response, any value derived from something an
+ * untrusted party can influence). Pouring such data into this sink is stored XSS in the page's own trusted origin.
+ * A card built from live data must use {@link CardFieldList} instead, whose field values are emitted as escaped
+ * text children, never through this body &mdash; a build-gating scanner enforces that separation for this
+ * framework's own sources (see the {@code RawContentSinkScanner} test-only guard in the views module's test tree).
+ *
+ * @since 10.0.0
+ */
+@SuppressWarnings({
+	"java:S1845" // Fluent-builder setters intentionally mirror field names (Juneau DSL convention).
+})
+public class CardContent implements CardBody {
+
+	/**
+	 * The raw markup body. Emitted <b>verbatim</b> &mdash; unescaped &mdash; by the card emitter via the html5
+	 * {@code rawText(...)} primitive (a plain {@code String} child would instead be entity-escaped and would
+	 * break markup-bearing prose). See this class's javadoc for the full ownership contract.
+	 */
+	public String content;
+
+	/**
+	 * Creates an empty raw-markup body.
+	 *
+	 * @return A new {@link CardContent}.
+	 */
+	public static CardContent create() {
+		return new CardContent();
+	}
+
+	/**
+	 * Sets the raw markup body (see this class's javadoc for the full ownership contract &mdash; trusted /
+	 * first-party content only, emitted verbatim).
+	 *
+	 * @param value The raw markup.  Must not be <jk>null</jk>.
+	 * @return This object.
+	 */
+	public CardContent content(String value) {
+		content = value;
+		return this;
+	}
+
+	/**
+	 * Fail-closed bean validation.
+	 *
+	 * @throws IllegalArgumentException If {@link #content} is not set.
+	 */
+	@Override /* CardBody */
+	public void validate() {
+		if (content == null)
+			throw iaex("CardContent must declare content.");
+	}
+}
diff --git a/juneau-rest/juneau-rest-server-widgets/src/test/java/org/apache/juneau/rest/server/widgets/CardContent_Test.java b/juneau-rest/juneau-rest-server-widgets/src/test/java/org/apache/juneau/rest/server/widgets/CardContent_Test.java
new file mode 100644
index 0000000000..fddbae5d70
--- /dev/null
+++ b/juneau-rest/juneau-rest-server-widgets/src/test/java/org/apache/juneau/rest/server/widgets/CardContent_Test.java
@@ -0,0 +1,61 @@
+/*
+ * 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.widgets;
+
+import static org.junit.jupiter.api.Assertions.*;
+
+import java.nio.file.*;
+
+import org.apache.juneau.*;
+import org.junit.jupiter.api.*;
+
+/**
+ * {@link CardContent} bean contract: the raw-markup {@link CardBody}.  This widgets test must never import
+ * {@code ViewDef} (no widgets&rarr;views), mirroring {@code CardFieldList_Test}'s equivalent check.
+ */
+class CardContent_Test extends TestBase {
+
+	@Test void a01_builder_roundTrip() {
+		var c = CardContent.create().content("<p>Hello, <b>world</b>.</p>");
+		assertEquals("<p>Hello, <b>world</b>.</p>", c.content);
+		c.validate();
+	}
+
+	@Test void a02_nullContent_rejected() {
+		var c = CardContent.create();
+		var e = assertThrows(IllegalArgumentException.class, c::validate);
+		assertTrue(e.getMessage().contains("content"), e::getMessage);
+	}
+
+	@Test void a03_blankContent_isAccepted() {
+		// Mirrors the Tab/Subtab raw-content contract: a blank (non-null) body is not an error, only an absent one.
+		var c = CardContent.create().content("  ");
+		c.validate();
+		assertEquals("  ", c.content);
+	}
+
+	@Test void a04_source_doesNotImportViewsModule() throws Exception {
+		var root = Path.of("").toAbsolutePath();
+		var src = root;
+		if (!Files.isDirectory(src.resolve("src/main/java")))
+			src = root.resolve("juneau-rest/juneau-rest-server-widgets");
+		var f = src.resolve("src/main/java/org/apache/juneau/rest/server/widgets/CardContent.java");
+		for (var line : Files.readAllLines(f))
+			if (line.stripLeading().startsWith("import "))
+				assertFalse(line.contains("rest.server.views"), () -> "CardContent must not import any views type: " + line);
+	}
+}


(juneau) 06/06: Remove an unused java.util.stream import from Widgets_ModuleBoundary_Test.

Posted by ja...@apache.org.
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

commit 350abd8baf4722da6868ec611cee7aab286f39f1
Author: James Bognar <ja...@apache.org>
AuthorDate: Wed Aug 26 10:05:00 2026 -0400

    Remove an unused java.util.stream import from Widgets_ModuleBoundary_Test.
---
 .../apache/juneau/rest/server/widgets/Widgets_ModuleBoundary_Test.java   | 1 -
 1 file changed, 1 deletion(-)

diff --git a/juneau-rest/juneau-rest-server-widgets/src/test/java/org/apache/juneau/rest/server/widgets/Widgets_ModuleBoundary_Test.java b/juneau-rest/juneau-rest-server-widgets/src/test/java/org/apache/juneau/rest/server/widgets/Widgets_ModuleBoundary_Test.java
index 646d856b93..fba4275305 100644
--- a/juneau-rest/juneau-rest-server-widgets/src/test/java/org/apache/juneau/rest/server/widgets/Widgets_ModuleBoundary_Test.java
+++ b/juneau-rest/juneau-rest-server-widgets/src/test/java/org/apache/juneau/rest/server/widgets/Widgets_ModuleBoundary_Test.java
@@ -23,7 +23,6 @@ import java.nio.file.*;
 import java.util.*;
 import java.util.function.*;
 import java.util.regex.*;
-import java.util.stream.*;
 
 import org.apache.juneau.*;
 import org.junit.jupiter.api.*;


(juneau) 03/06: Add a >= floor operator to the counts grammar so an invariant count can say "must never drop below N" instead of being forced into equality.

Posted by ja...@apache.org.
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

commit 171654d3ed78c96385fa49e999b345da94b87628
Author: James Bognar <ja...@apache.org>
AuthorDate: Wed Aug 26 09:48:57 2026 -0400

    Add a >= floor operator to the counts grammar so an invariant count can say "must never drop below N" instead of being forced into equality.
    
    An equality-only `Counts:` declaration over a population that can legitimately grow flags on benign growth as counts_mismatch, and the fix operators reach for is to re-baseline the number -- which is exactly how a regression guard gets deleted by accident. `>=` declares the floor instead: counts_below_floor only fires on an actual decrease, and growth above the floor stays green. `>= 0` is refused at parse time since it holds for every derivation and asserts nothing; scope-empty is st [...]
---
 scripts/tests/test_todo_status_audit.py | 99 +++++++++++++++++++++++++++++++++
 scripts/todo-status-audit.py            | 91 +++++++++++++++++++++++++-----
 2 files changed, 176 insertions(+), 14 deletions(-)

diff --git a/scripts/tests/test_todo_status_audit.py b/scripts/tests/test_todo_status_audit.py
index e1f54ead2f..97a8f2b9ce 100644
--- a/scripts/tests/test_todo_status_audit.py
+++ b/scripts/tests/test_todo_status_audit.py
@@ -912,6 +912,14 @@ class TestDeclaredCountsGrammar:
             "  `console:matches:../outside/*.java:foo` = 1",
             "  `console:matches::foo` = 1",
             "  `console:matches:src/**/*.java:[unclosed` = 1",
+            # Operator forms that are NOT the two supported ones. Listed because a near-miss operator
+            # is the likeliest way to write a floor wrong, and tolerating any of them would mean
+            # guessing which comparison the author meant.
+            "  `console:matches:src/**/*.java:foo` >= twelve",
+            "  `console:matches:src/**/*.java:foo` > 5",
+            "  `console:matches:src/**/*.java:foo` <= 5",
+            "  `console:matches:src/**/*.java:foo` => 5",
+            "  `console:matches:src/**/*.java:foo` >= 5 or so",
         ],
     )
     def test_malformed_values_are_reported_as_malformed(self, audit_module, value):
@@ -934,6 +942,43 @@ class TestDeclaredCountsGrammar:
         for token in ["board", *audit_module.REPO_TOKENS]:
             assert token in detail
 
+    def test_floor_form_parses_and_records_its_operator(self, audit_module):
+        """`>=` declares an invariant: "must never drop below N". Equality over a population that
+        can legitimately grow flags on benign growth, which invites correcting the number -- and
+        correcting an invariant is how a guard gets deleted."""
+        outcome, claim = audit_module.parse_counts_value(r"  `juneau:matches:src/**/*.java:foo\(` >= 36")
+        assert outcome == "claim"
+        assert (claim.operator, claim.expected, claim.is_floor) == (">=", 36, True)
+
+    def test_equality_is_the_default_and_is_not_a_floor(self, audit_module):
+        _, claim = audit_module.parse_counts_value(r"  `juneau:matches:src/**/*.java:foo\(` = 36")
+        assert (claim.operator, claim.is_floor) == ("=", False)
+
+    def test_floor_of_zero_is_refused(self, audit_module):
+        """The one decorative floor catchable without inventing a slack threshold: `>= 0` holds for
+        every possible derivation, so it looks like a guard while asserting nothing. Refused for the
+        same reason `paths ... = 0` is."""
+        outcome, detail = audit_module.parse_counts_value("  `juneau:matches:src/**/*.java:foo` >= 0")
+        assert outcome == "malformed"
+        assert "asserts nothing" in detail
+
+    def test_equality_may_still_declare_zero(self, audit_module):
+        """Refusing `>= 0` must not take `= 0` with it -- "no call sites remain" is a real claim."""
+        assert audit_module.parse_counts_value("  `juneau:matches:src/**/*.java:foo` = 0")[0] == "claim"
+
+    def test_rendered_shows_the_operator_actually_applied(self, audit_module):
+        """A detail message that printed `= 36` for a claim evaluated as a floor would be unactionable
+        in exactly the case where the operator response depends on knowing which it was."""
+        _, floor = audit_module.parse_counts_value("  `juneau:paths:src/*.java` >= 2")
+        _, exact = audit_module.parse_counts_value("  `juneau:paths:src/*.java` = 2")
+        assert floor.rendered().endswith(">= 2")
+        assert exact.rendered().endswith("= 2") and ">=" not in exact.rendered()
+
+    def test_malformed_detail_mentions_the_floor_form(self, audit_module):
+        """An author who wrote the operator wrong has to be told the floor form exists."""
+        _, detail = audit_module.parse_counts_value("  ten call sites")
+        assert ">=" in detail
+
 
 class TestGlobToRegex:
     def test_single_star_does_not_cross_a_slash(self, audit_module):
@@ -1179,6 +1224,60 @@ class TestDeclaredCountsFlags:
         lines = ["Counts:  `juneau:matches:renamed/**/*.java:foo` = 0"]
         assert self._flags(audit_module, tmp_path, next_id_module, lines, resolver) == {"counts_scope_empty"}
 
+    def test_floor_that_holds_flags_nothing(self, audit_module, next_id_module, tmp_path):
+        repo = _make_repo(tmp_path / "repo", {"src/A.java": "foo()\nfoo()\n"})
+        resolver = audit_module.CountsResolver({"juneau": str(repo)})
+        lines = [r"Counts:  `juneau:matches:src/**/*.java:foo\(\)` >= 2"]
+        assert self._flags(audit_module, tmp_path, next_id_module, lines, resolver) == set()
+
+    def test_floor_breached_by_a_decrease_is_flagged(self, audit_module, next_id_module, tmp_path):
+        """The regression a floor exists to catch: the population shrank."""
+        repo = _make_repo(tmp_path / "repo", {"src/A.java": "foo()\n"})
+        resolver = audit_module.CountsResolver({"juneau": str(repo)})
+        lines = [r"Counts:  `juneau:matches:src/**/*.java:foo\(\)` >= 2"]
+        assert self._flags(audit_module, tmp_path, next_id_module, lines, resolver) == {"counts_below_floor"}
+
+    def test_growth_above_a_floor_stays_green_where_equality_goes_red(self, audit_module, next_id_module, tmp_path):
+        """The whole point of the operator, asserted as a contrast rather than two separate tests:
+        identical source, identical pattern, and the only difference is `>=` versus `=`. The floor
+        passes because nothing was lost; the equality form flags because the number moved. Under the
+        equality-only grammar this benign growth is what invited an operator to 'correct' an
+        invariant."""
+        repo = _make_repo(tmp_path / "repo", {"src/A.java": "foo()\nfoo()\nfoo()\nfoo()\nfoo()\n"})
+        resolver = audit_module.CountsResolver({"juneau": str(repo)})
+        floor = [r"Counts:  `juneau:matches:src/**/*.java:foo\(\)` >= 2"]
+        exact = [r"Counts:  `juneau:matches:src/**/*.java:foo\(\)` = 2"]
+        assert self._flags(audit_module, tmp_path, next_id_module, floor, resolver) == set()
+        assert self._flags(audit_module, tmp_path, next_id_module, exact, resolver) == {"counts_mismatch"}
+
+    def test_empty_scope_under_a_floor_is_scope_empty_not_a_breach(self, audit_module, next_id_module, tmp_path):
+        """A rotted pathspec derives 0, which is below any floor -- so without the ordering in
+        _flag_declared_counts it would be reported as a regression and send the operator hunting in
+        code that is fine. It must be neither a breach nor a pass."""
+        repo = _make_repo(tmp_path / "repo", {"src/A.java": "foo()\nfoo()\n"})
+        resolver = audit_module.CountsResolver({"juneau": str(repo)})
+        lines = ["Counts:  `juneau:matches:renamed/**/*.java:foo` >= 2"]
+        assert self._flags(audit_module, tmp_path, next_id_module, lines, resolver) == {"counts_scope_empty"}
+
+    def test_breach_and_mismatch_details_are_distinguishable(self, audit_module, next_id_module, tmp_path):
+        """The operator response differs -- investigate a regression versus possibly re-baseline -- so
+        the two details must not read alike."""
+        repo = _make_repo(tmp_path / "repo", {"src/A.java": "foo()\n"})
+        resolver = audit_module.CountsResolver({"juneau": str(repo)})
+        todo_dir = tmp_path / "todos"
+        todo_dir.mkdir(exist_ok=True)
+
+        floor_path = todo_dir / _plan_filename(next_id_module, "TODO", 3, name="floored")
+        _write_plan(floor_path, status="In progress.", source=r"Counts:  `juneau:matches:src/**/*.java:foo\(\)` >= 4", body="## Goal\n\nx\n")
+        breach = dict(audit_module.audit_file(floor_path, frozenset(), resolver))["counts_below_floor"]
+
+        exact_path = todo_dir / _plan_filename(next_id_module, "TODO", 4, name="exact")
+        _write_plan(exact_path, status="In progress.", source=r"Counts:  `juneau:matches:src/**/*.java:foo\(\)` = 4", body="## Goal\n\nx\n")
+        mismatch = dict(audit_module.audit_file(exact_path, frozenset(), resolver))["counts_mismatch"]
+
+        assert ">= 4" in breach and "BREACHED" in breach and "Do NOT lower" in breach
+        assert "= 4" in mismatch and "BREACHED" not in mismatch and "floor" not in mismatch
+
     def test_unreachable_repo_is_flagged_as_unverifiable(self, audit_module, next_id_module, tmp_path):
         resolver = audit_module.CountsResolver({"juneau": str(tmp_path / "absent")})
         lines = ["Counts:  `juneau:paths:src/*.java` = 1"]
diff --git a/scripts/todo-status-audit.py b/scripts/todo-status-audit.py
index 76b8b0a29e..921b7ecdb8 100755
--- a/scripts/todo-status-audit.py
+++ b/scripts/todo-status-audit.py
@@ -76,7 +76,13 @@ Checks performed (each file may accumulate multiple flags):
                                  Kept distinct from an absent line for the same reason the Key-symbols
                                  tri-state is: "the author wrote nothing" and "the author wrote something
                                  that did not parse" are different facts.
-  - counts_mismatch             A declared count does not equal the count re-derived from source THIS RUN.
+  - counts_mismatch             A declared count written with '=' does not equal the count re-derived
+                                 from source THIS RUN. Often routine re-baselining: an '=' declaration is
+                                 usually a BASELINE, and the item's own work is what changed the number.
+  - counts_below_floor          A declared count written with '>=' re-derived BELOW its floor. Kept
+                                 distinct from counts_mismatch because the operator response differs: a
+                                 floor breach is a regression to investigate and never a number to
+                                 correct, where an equality mismatch frequently is exactly that.
   - counts_scope_empty          A declared count's pathspec resolves to ZERO files, so the declaration is
                                  no longer anchored to anything and its number cannot be tested. Flagged
                                  loudly rather than passing vacuously -- this is the specific defence
@@ -203,8 +209,13 @@ its new symbols, and the audit does the counting. A declaration is a `Counts:` h
 
     Counts:  `console:files:src/main/java/**/rest/**/*.java:requiredConfirmation\(|armPhrase\(` = 10
 
-read as "<repo token>:<kind>:<pathspec>[:<regex>] = <expected integer>". The field may repeat, one
-declaration per line; the literal value `None.` declares "nothing here is mechanically countable".
+read as "<repo token>:<kind>:<pathspec>[:<regex>] <op> <expected integer>", where <op> is `=` or
+`>=`. Equality is the default and is the right shape for a BASELINE -- a fact about the state before
+the item's work, which the item exists to change. `>=` declares a FLOOR ("this must never drop below
+N'"), which is what an INVARIANT actually means. The floor form exists because an equality test over a
+growable population is actively harmful: benign growth flags, and the operator is then invited to
+"correct" the number, which is how a regression guard gets deleted by accident. The field may repeat,
+one declaration per line; the literal value `None.` declares "nothing here is mechanically countable".
 Kinds: `matches` (total regex occurrences), `files` (files with at least one occurrence), `paths`
 (files matching the pathspec, no regex). Repo tokens: the three tracker repos plus `board` for
 ~/Project Work itself. Full grammar and rationale: the "Declared counts" section of @todo-and-waves.
@@ -228,6 +239,16 @@ designed against -- a declaration nobody re-checks is no better than the sentenc
   3. The grammar is strict, so a half-edited declaration becomes counts_malformed rather than being
      skipped. A line that no longer parses is reported, never quietly ignored.
 
+DELIBERATE NON-GOAL: a floor set far below reality is NOT detected. `>= 1` over a population of 500
+never fails, and nothing here reports that. Detecting it would need a threshold on how much slack is
+legitimate, and any such threshold recreates the exact failure the floor form was added to remove --
+it would flag populations that had merely grown, and invite raising the floor to match reality, which
+is re-baselining a guard. The one unambiguous case IS refused: `>= 0` is rejected at parse time,
+because it holds for every possible derivation and so asserts nothing. Past that, a floor's slack is
+a judgment the author makes and the audit does not second-guess it. What still protects a floor is
+property 2 above: a pathspec that has rotted to zero matches is counts_scope_empty -- never a pass,
+and never the misreading "well, 0 is below the floor, so it fails as a regression".
+
 Counts resolve against COMMITTED CONTENT (`HEAD`) in the named repo, never the working tree. Two
 reasons, one of them paid for the hard way: a plan file citing working-tree-only files (three .py
 files present locally and in nobody's HEAD) produced a blocked item on 2026-08-25 that two
@@ -401,10 +422,12 @@ COUNTS_LINE_RE = re.compile(r"^\s*Counts:(.*)$", re.IGNORECASE | re.MULTILINE)
 # convention, one way to say "nothing", so a reader never has to learn a second spelling.
 COUNTS_NONE_VALUE = "none."
 
-# `<descriptor>` = <integer>, and nothing else on the line. Strict on purpose: a trailing human
+# `<descriptor>` <op> <integer>, and nothing else on the line. Strict on purpose: a trailing human
 # label or a second claim on the same line would have to be tolerated by ignoring text, and
 # ignoring text is how a half-edited declaration passes. Anything unparseable is counts_malformed.
-COUNT_CLAIM_RE = re.compile(r"^`([^`]+)`\s*=\s*(\d+)$")
+# '>=' is listed before '=' in the alternation so the two-character operator is never read as a
+# bare '=' with a stray '>' in front of it.
+COUNT_CLAIM_RE = re.compile(r"^`([^`]+)`\s*(>=|=)\s*(\d+)$")
 
 # matches = total regex occurrences; files = files with at least one occurrence; paths = files
 # matching the pathspec (no regex). These three are not a guess at what items might want to count:
@@ -442,6 +465,13 @@ SELF_REPO_ROOT = Path(__file__).resolve().parent.parent
 
 GIT_TIMEOUT_SECONDS = 60
 
+# The two comparison forms. '=' is the default and the right shape for a baseline; '>=' declares a
+# floor, which is what an invariant means. Two operators rather than a separate `kind` because the
+# thing being counted is unchanged -- only the assertion about the number differs.
+COUNT_OP_EQ = "="
+COUNT_OP_FLOOR = ">="
+COUNT_OPS = (COUNT_OP_EQ, COUNT_OP_FLOOR)
+
 # Derivation outcomes, distinguished for the same reason the tri-state is: a number that could not
 # be derived must never be reported as a number that matched.
 COUNT_OK = "ok"
@@ -450,15 +480,29 @@ COUNT_UNVERIFIABLE = "unverifiable"
 
 
 class CountClaim:
-    """One parsed `Counts:` declaration: what to count, where, and the expected total."""
+    """One parsed `Counts:` declaration: what to count, where, the operator, and the expected total."""
 
-    def __init__(self, repo: str, kind: str, pathspec: str, pattern: "re.Pattern | None", expected: int, descriptor: str):
+    def __init__(self, repo: str, kind: str, pathspec: str, pattern: "re.Pattern | None", expected: int, descriptor: str, operator: str = COUNT_OP_EQ):
         self.repo = repo
         self.kind = kind
         self.pathspec = pathspec
         self.pattern = pattern
         self.expected = expected
         self.descriptor = descriptor
+        self.operator = operator
+
+    @property
+    def is_floor(self) -> bool:
+        return self.operator == COUNT_OP_FLOOR
+
+    def rendered(self) -> str:
+        """The declaration as the author wrote it, for every flag detail.
+
+        Built from the parsed parts rather than the raw line so a detail message can never show an
+        operator the checker did not actually apply -- reporting '= 36' for a claim evaluated as a
+        floor would make the flag unactionable in the one case where the response depends on it.
+        """
+        return f"`{self.descriptor}` {self.operator} {self.expected}"
 
 
 def glob_to_regex(pathspec: str) -> "re.Pattern":
@@ -517,9 +561,9 @@ def parse_counts_value(value: str) -> tuple:
 
     claim_match = COUNT_CLAIM_RE.match(stripped)
     if claim_match is None:
-        return ("malformed", f"expected `<repo>:<kind>:<pathspec>[:<regex>]` = <integer>, got: {stripped}")
+        return ("malformed", f"expected `<repo>:<kind>:<pathspec>[:<regex>]` = <integer> (or >= <integer> for a floor), got: {stripped}")
 
-    descriptor, expected = claim_match.group(1), int(claim_match.group(2))
+    descriptor, operator, expected = claim_match.group(1), claim_match.group(2), int(claim_match.group(3))
     # maxsplit=3 so a regex containing ':' stays intact; the pathspec therefore may not contain one,
     # which also excludes git's magic-pathspec syntax (":(glob)...") -- documented, not accidental.
     fields = descriptor.split(":", 3)
@@ -556,7 +600,13 @@ def parse_counts_value(value: str) -> tuple:
         except re.error as exc:
             return ("malformed", f"regex does not compile ({exc}): {pattern_source}")
 
-    return ("claim", CountClaim(repo, kind, pathspec, pattern, expected, descriptor))
+    # A floor of 0 holds for every possible derivation, so it asserts nothing while looking like a
+    # guard -- the one decorative-floor case that can be caught without inventing a slack threshold
+    # (see the module docstring's DELIBERATE NON-GOAL). Refused for the same reason `paths ... = 0` is.
+    if operator == COUNT_OP_FLOOR and expected == 0:
+        return ("malformed", "a floor of 0 asserts nothing -- every derivation satisfies `>= 0`. Declare the floor you actually mean, or use '=' if the claim is that the count is exactly 0.")
+
+    return ("claim", CountClaim(repo, kind, pathspec, pattern, expected, descriptor, operator))
 
 
 class CountsResolver:
@@ -946,7 +996,8 @@ def _flag_status_prefix_transitions(prefix: str, status: str, normalized_status:
 
 def _flag_declared_counts(text: str, counts_resolver: "CountsResolver | None", flags: list) -> None:
     """
-    Appends counts_malformed / counts_mismatch / counts_scope_empty / counts_unverifiable.
+    Appends counts_malformed / counts_mismatch / counts_below_floor / counts_scope_empty /
+    counts_unverifiable.
 
     An ABSENT `Counts:` line produces nothing, which is the whole reason this check can be turned on
     over an existing corpus: a file that makes no declaration is making no claim. Grammar errors are
@@ -967,19 +1018,31 @@ def _flag_declared_counts(text: str, counts_resolver: "CountsResolver | None", f
         if derived_outcome == COUNT_UNVERIFIABLE:
             flags.append((
                 "counts_unverifiable",
-                f"declared count `{parsed.descriptor}` = {parsed.expected} could not be re-derived: {detail}. "
+                f"declared count {parsed.rendered()} could not be re-derived: {detail}. "
                 f"An unverified count is not a verified one -- fix the repo token/path, or pass --repo-root.",
             ))
         elif derived_outcome == COUNT_SCOPE_EMPTY:
+            # Checked BEFORE either comparison, and that ordering is load-bearing for floors: a
+            # pathspec that has rotted to nothing would otherwise derive 0 and be reported as a floor
+            # breach, sending the operator to hunt a regression in code that is fine. An unanchored
+            # declaration is its own failure whichever operator it was written with.
             flags.append((
                 "counts_scope_empty",
-                f"declared count `{parsed.descriptor}` = {parsed.expected} is no longer anchored: {detail} "
+                f"declared count {parsed.rendered()} is no longer anchored: {detail} "
                 f"at {COUNTS_REV}. The number cannot be tested, so it is flagged rather than passed.",
             ))
+        elif parsed.is_floor:
+            if derived < parsed.expected:
+                flags.append((
+                    "counts_below_floor",
+                    f"declared floor {parsed.rendered()} BREACHED -- re-derived {derived} "
+                    f"from {parsed.repo} at {COUNTS_REV}. A floor is an invariant: investigate the drop. "
+                    f"Do NOT lower the floor to match -- that deletes the guard.",
+                ))
         elif derived != parsed.expected:
             flags.append((
                 "counts_mismatch",
-                f"declared count `{parsed.descriptor}` = {parsed.expected} but re-derived {derived} "
+                f"declared count {parsed.rendered()} but re-derived {derived} "
                 f"from {parsed.repo} at {COUNTS_REV}.",
             ))
 


(juneau) 05/06: Add a test asserting RawContentSinkScanner's real-tree scan actually reaches the sibling widgets module, and stop the javadoc overclaiming that guarantee.

Posted by ja...@apache.org.
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

commit a66664bef23a18521809bacd95c22ca2857126af
Author: James Bognar <ja...@apache.org>
AuthorDate: Wed Aug 26 10:04:56 2026 -0400

    Add a test asserting RawContentSinkScanner's real-tree scan actually reaches the sibling widgets module, and stop the javadoc overclaiming that guarantee.
    
    scanTree reaches the widgets module through a relative path, and scanJavaSources skips a
    missing directory with a silent continue -- so renaming or relocating the widgets module
    would drop its sinks from every scan, with no exception thrown and zero violations still
    reported, while the detection logic stayed perfectly correct. The suite's other real-tree
    assertions are all floors or universals that a smaller sink set satisfies more easily, so
    none of them would have caught the module quietly falling out of scope.
    
    b05_realModuleTree_alsoCoversTheSiblingWidgetsModule asserts the crossing itself, keyed on
    the widgets package directory rather than a specific filename so it survives an in-widgets
    rename. The javadoc gains the same caveat the test enforces: "in a tree it actually walks"
    is now explicit rather than implied.
---
 .../rest/server/views/RawContentSinkScanner.java   | 14 +++++++++++-
 .../views/RawContentSink_SecurityScan_Test.java    | 25 ++++++++++++++++++++++
 2 files changed, 38 insertions(+), 1 deletion(-)

diff --git a/juneau-rest/juneau-rest-server-views/src/test/java/org/apache/juneau/rest/server/views/RawContentSinkScanner.java b/juneau-rest/juneau-rest-server-views/src/test/java/org/apache/juneau/rest/server/views/RawContentSinkScanner.java
index 5bcba01157..18e0ac08e5 100644
--- a/juneau-rest/juneau-rest-server-views/src/test/java/org/apache/juneau/rest/server/views/RawContentSinkScanner.java
+++ b/juneau-rest/juneau-rest-server-views/src/test/java/org/apache/juneau/rest/server/views/RawContentSinkScanner.java
@@ -37,7 +37,19 @@ import java.util.regex.*;
  * the build if any call to the {@link Tab#content(String)}/{@link Subtab#content(String)}/
  * {@link org.apache.juneau.rest.server.widgets.CardContent#content(String) CardContent#content(String)}
  * fluent-setter passes an argument that is not a compile-time string literal (or a {@code +}-concatenation of
- * literals).
+ * literals) <b>in a tree it actually walks</b>.
+ *
+ * <p>
+ * That qualifier is not pedantry, and it is the reason the sentence above used to overstate this guard. The
+ * widgets tree is reached through a <i>relative</i> path ({@link #WIDGETS_MODULE_DIR}) and
+ * {@code scanJavaSources} skips a directory that is not there with a silent {@code continue}. So renaming or
+ * relocating the widgets module would drop its sinks from every scan while the detection logic stayed perfectly
+ * correct, no exception would be thrown, and zero violations would still be reported &mdash; coverage of
+ * {@link org.apache.juneau.rest.server.widgets.CardContent} would simply cease, quietly. <b>Do not read "it
+ * scans both modules" as a guarantee that it still does.</b> The guarantee lives in the accompanying test, which
+ * asserts the crossing itself ({@code b05_realModuleTree_alsoCoversTheSiblingWidgetsModule}); it has to be
+ * asserted separately because every other real-tree check there is a floor or a universal, and both of those are
+ * satisfied <i>more</i> easily by a smaller set of sinks than by a larger one.
  *
  * <h5 class='section'>Why "is the argument a literal" is the enforcement mechanism</h5>
  * <p>
diff --git a/juneau-rest/juneau-rest-server-views/src/test/java/org/apache/juneau/rest/server/views/RawContentSink_SecurityScan_Test.java b/juneau-rest/juneau-rest-server-views/src/test/java/org/apache/juneau/rest/server/views/RawContentSink_SecurityScan_Test.java
index 90257db2a7..790b16cd23 100644
--- a/juneau-rest/juneau-rest-server-views/src/test/java/org/apache/juneau/rest/server/views/RawContentSink_SecurityScan_Test.java
+++ b/juneau-rest/juneau-rest-server-views/src/test/java/org/apache/juneau/rest/server/views/RawContentSink_SecurityScan_Test.java
@@ -247,6 +247,31 @@ class RawContentSink_SecurityScan_Test extends TestBase {
 				+ "strings would otherwise register as false-positive sinks): " + r.sinks());
 	}
 
+	/**
+	 * Anti-vacuous, module-crossing half: {@link RawContentSinkScanner#scanTree} walks the sibling widgets module
+	 * as well as this one, and without this test nothing here would notice if it stopped. The widgets root is
+	 * reached through a <i>relative</i> path and the walk skips a missing directory with a silent {@code
+	 * continue}, so a renamed or relocated module drops those sinks without erroring - and every other real-tree
+	 * assertion in this section keeps passing, because they are all floors or universals that a <i>smaller</i> set
+	 * satisfies more easily: {@code b01}'s "no violations", {@code b02}'s "all literal-only", and {@code b02}'s
+	 * {@code >= 10} floor, which today's views-only sinks clear on their own. The suite would stay green while no
+	 * longer covering {@link org.apache.juneau.rest.server.widgets.CardContent} at all.
+	 *
+	 * <p>
+	 * Asserted by <b>package directory</b> rather than by filename deliberately: naming a specific widgets test
+	 * would buy precision and pay for it with a test that breaks on a rename that harms nothing. Sink paths are
+	 * recorded relative to whichever module root produced them, so the module name is not in the path - the
+	 * package directory is the durable discriminator between the two trees.
+	 */
+	@Test void b05_realModuleTree_alsoCoversTheSiblingWidgetsModule() throws Exception {
+		var widgetsPackageDir = "org/apache/juneau/rest/server/widgets/";
+		var r = RawContentSinkScanner.scanTree(requireModuleRoot());
+		assertTrue(r.sinks().stream().anyMatch(s -> s.file().replace('\\', '/').contains(widgetsPackageDir)),
+			() -> "scanTree must reach the sibling widgets module, but no sink was found under "
+				+ widgetsPackageDir + " - the widgets half of the walk is silently scanning nothing, so the "
+				+ "CardContent raw-markup sink is unguarded even with this suite green: " + r.sinks());
+	}
+
 	// -----------------------------------------------------------------------------------------------------------
 	// c: juneau-config.js HTML-sink gate (innerHTML = / .html() never in the chooser)
 	// -----------------------------------------------------------------------------------------------------------


(juneau) 04/06: Invert push.py's staging guard: commit only what's staged, and refuse when anything else in the tree is unreviewed.

Posted by ja...@apache.org.
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

commit 6eee434b0d7b411b85ad805800756045c1918f92
Author: James Bognar <ja...@apache.org>
AuthorDate: Wed Aug 26 10:04:48 2026 -0400

    Invert push.py's staging guard: commit only what's staged, and refuse when anything else in the tree is unreviewed.
    
    James stages a path as his record of having reviewed it, not as a mechanical step right
    before committing -- so pre-existing staged content, which the previous guard refused
    over, is actually his NORMAL state. This inverts the check: get_staged_paths() (renamed
    from check_preexisting_staged_changes) is now the sole definition of what gets committed,
    `git add .` is gone entirely, and the new check_unreviewed_changes() refuses the whole
    run -- commit AND push -- if anything in the tree is unstaged or untracked-and-not-
    gitignored, since that means the review pass isn't finished. The refusal prints a
    copy-pasteable `git stash push -- <paths>` / `git stash pop` recovery hint with the
    actual offending paths filled in, so partial review (some files staged, others mid-edit)
    has a documented way out without an override flag that would let something unreviewed
    through.
    
    Also extracts main()'s Step 6 juneau-docs follow-up into run_docs_followup() so it is
    unit-testable against real git without invoking the mvn build/test steps first, mirroring
    commit_and_push()'s own extraction. Full suite (340 tests) passes with this change.
---
 scripts/push.py            | 392 +++++++++++++++++++++--------------
 scripts/tests/test_push.py | 503 +++++++++++++++++++++++++++++++++++++++++----
 2 files changed, 695 insertions(+), 200 deletions(-)

diff --git a/scripts/push.py b/scripts/push.py
index 37d2b74cd5..f7072356d8 100755
--- a/scripts/push.py
+++ b/scripts/push.py
@@ -40,6 +40,7 @@ LINUX_FAILURE_SOUND = "/usr/share/sounds/freedesktop/stereo/dialog-error.oga"
 import argparse
 import os
 import platform
+import shlex
 import shutil
 import subprocess
 import sys
@@ -365,48 +366,72 @@ def verify_apache_identity(repo_dir):
     return True
 
 
-def check_git_status(repo_dir):
-    """Check if there are any changes to commit."""
-    try:
-        result = subprocess.run(
-            ["git", "status", "--porcelain"],
-            cwd=repo_dir,
-            capture_output=True,
-            text=True,
-            check=True
-        )
-        return len(result.stdout.strip()) > 0
-    except Exception as e:
-        print(f"⚠ Warning: Could not check git status: {e}")
-        return True
+def get_staged_paths(repo_dir):
+    """
+    List paths currently staged in the index.
 
+    This is the sole definition of "what push.py is about to commit": a staged path is the
+    operator's record that they reviewed it and it's good (see commit_and_push()'s docstring),
+    so this script commits the index exactly as it finds it rather than deciding what belongs
+    in the commit itself.
 
-def check_preexisting_staged_changes(repo_dir):
+    Returns:
+        list[str]: staged paths (possibly empty).
+
+    Raises:
+        subprocess.CalledProcessError, OSError: if the check itself can't run. Deliberately not
+        caught here -- unlike the ahead/behind upstream check (a network operation that can
+        legitimately fail), an error running `git diff --cached` almost always means something
+        is fundamentally wrong with the repo, and this check exists specifically to protect an
+        invariant, so the caller should fail closed (abort) rather than silently proceed.
     """
-    List paths with changes already staged in the index, before this script's own `git add .`.
+    result = subprocess.run(
+        ["git", "diff", "--cached", "--name-only"],
+        cwd=repo_dir,
+        capture_output=True,
+        text=True,
+        check=True
+    )
+    return [line for line in result.stdout.splitlines() if line.strip()]
+
 
-    `git commit` commits whatever is in the index regardless of which step staged it, so
-    content staged by something else before push.py runs (e.g. a concurrent session sharing
-    this working tree) would be folded into this push's commit whether or not `git add .` ran.
-    Checking this before add/commit lets the caller refuse rather than silently absorb it.
+def check_unreviewed_changes(repo_dir):
+    """
+    List paths that have NOT been staged: tracked files with unstaged modifications/deletions,
+    plus untracked files that are not gitignored.
+
+    Staging is how this script knows something has been reviewed (see commit_and_push()'s
+    docstring); this is the other half of that invariant. Its presence alongside staged content
+    means the operator's review pass isn't finished, so nothing should be committed or pushed
+    yet -- not even the already-staged part -- until the tree is fully resolved one way or
+    another (staged, committed separately, stashed, or discarded).
+
+    Gitignored untracked files are deliberately excluded (via `git ls-files --exclude-standard`):
+    build output and similar noise was never going to be staged or reviewed, and flagging it
+    would make this refusal fire on essentially every real run.
 
     Returns:
-        list[str]: staged paths (possibly empty). Fails open (returns []) if the check itself
-        can't run -- the add/commit steps immediately following will surface any real git
-        problem on their own.
+        list[str]: unreviewed paths (possibly empty).
+
+    Raises:
+        subprocess.CalledProcessError, OSError: see get_staged_paths() -- same fail-closed
+        reasoning applies here.
     """
-    try:
-        result = subprocess.run(
-            ["git", "diff", "--cached", "--name-only"],
-            cwd=repo_dir,
-            capture_output=True,
-            text=True,
-            check=True
-        )
-        return [line for line in result.stdout.splitlines() if line.strip()]
-    except Exception as e:
-        print(f"⚠ Warning: Could not check for pre-existing staged changes: {e}")
-        return []
+    unstaged = subprocess.run(
+        ["git", "diff", "--name-only"],
+        cwd=repo_dir,
+        capture_output=True,
+        text=True,
+        check=True
+    ).stdout.splitlines()
+    untracked = subprocess.run(
+        ["git", "ls-files", "--others", "--exclude-standard"],
+        cwd=repo_dir,
+        capture_output=True,
+        text=True,
+        check=True
+    ).stdout.splitlines()
+    return [line for line in (*unstaged, *untracked) if line.strip()]
 
 
 def check_upstream_changes(repo_dir):
@@ -596,26 +621,35 @@ def commit_and_push(
     pre_commit_hook=None,
 ):
     """
-    Commit any local changes and push, treating "clean working tree" and "nothing to push" as
-    two different things (the bug this replaces reported success without ever pushing).
-
-    A clean working tree means there is nothing NEW to commit -- it does NOT mean there is
-    nothing to push. A prior run could have committed successfully and then been interrupted (or
-    failed) before the push step, leaving unpushed commits sitting on the branch; treating a
-    clean tree as "nothing to do" in that situation is a false success, since the caller would
-    believe their work reached the remote when it did not. So a clean tree here skips the
-    COMMIT, not the push: if the branch is already ahead of its upstream, that gets pushed. Only
-    a clean tree with nothing already ahead (or no upstream to compare against) is truly a
-    no-op, and that is reported with text that is never confusable with an actual push having
-    happened.
-
-    Also refuses to stage/commit if the index already has staged changes before this call's own
-    `git add .` -- e.g. from a concurrent session sharing this working tree -- since `git commit`
-    would fold pre-existing staged content into this push's commit regardless of what `git add .`
-    stages in this run. `git add .` itself is deliberately left unconditional for genuinely
-    unstaged/untracked changes: that is this script's documented, long-standing behavior (commit
-    everything in the tree under one message), and narrowing it further without being asked would
-    risk surprising an existing caller just as badly as the bug it would replace.
+    Commit whatever is already staged and push, treating "nothing staged" and "nothing to push"
+    as two different things (the bug this replaces reported success without ever pushing).
+
+    Nothing staged means there is nothing NEW to commit -- it does NOT mean there is nothing to
+    push. A prior run could have committed successfully and then been interrupted (or failed)
+    before the push step, leaving unpushed commits sitting on the branch; treating a clean index
+    as "nothing to do" in that situation is a false success, since the caller would believe their
+    work reached the remote when it did not. So an empty index here skips the COMMIT, not the
+    push: if the branch is already ahead of its upstream, that gets pushed. Only a clean index
+    with nothing already ahead (or no upstream to compare against) is truly a no-op, and that is
+    reported with text that is never confusable with an actual push having happened.
+
+    A staged path is the operator's record that they've reviewed it and it's good -- staging as
+    they review, not as a mechanical step right before committing. So this function commits the
+    index exactly as it finds it (no `git add .`, anywhere, ever): it does not decide what
+    belongs in the commit, because the index already says. And it refuses outright -- commits
+    and pushes NOTHING -- if the working tree has any unstaged modification or any untracked,
+    non-gitignored file, since their presence means the review pass isn't finished, and this
+    script has no way to tell "safe to commit around" apart from "someone forgot to stage it."
+    That refusal applies even to a push-only run (nothing staged, only pushing prior commits):
+    unreviewed content sitting in the tree at push time isn't safe to assume away, even though
+    it isn't literally what's being pushed. This is deliberately strict with no override flag --
+    even a flag that names the exact paths being overridden is still a way to push something
+    nobody reviewed, which is the one thing this refusal exists to prevent. For genuinely partial
+    work (some files reviewed and staged, others still mid-edit), the sanctioned way out is
+    `git stash push -- <paths>` before running push.py and `git stash pop` after; the refusal
+    message itself prints that command with the actual offending paths already filled in, so the
+    recovery is discoverable at the moment of refusal rather than something the operator has to
+    already know.
 
     Shared by all three sites in this file that make this same commit-or-push decision (the
     default juneau flow, the juneau-docs follow-up in main()'s Step 6, and --docs-only's
@@ -635,14 +669,15 @@ def commit_and_push(
             operating outside the repo's own directory (e.g. main() running against the
             juneau-docs sibling while cwd is juneau) can pass a `-C <path>`-qualified form.
         pre_flight_hook: Optional zero-arg callable invoked once it's established that there is
-            something to commit and/or push (i.e. NOT the nothing_to_do case), before any git
-            state is mutated. Must return True to proceed or False to abort (and is responsible
-            for printing its own error and playing the failure sound before returning False).
-            Used for checks that must run before ANY push, including a push-only run with
-            nothing new to commit -- e.g. the juneau-docs Apache-identity gate in main()'s Step 6
-            follow-up. None (the default) means no such check is needed.
-        pre_commit_hook: Optional zero-arg callable invoked only when there ARE local changes to
-            commit, immediately before `git add .`. Same True/False contract as pre_flight_hook.
+            something to commit and/or push (i.e. NOT the nothing_to_do case) and that the tree
+            has nothing unreviewed in it, before any git state is mutated. Must return True to
+            proceed or False to abort (and is responsible for printing its own error and playing
+            the failure sound before returning False). Used for checks that must run before ANY
+            push, including a push-only run with nothing new to commit -- e.g. the juneau-docs
+            Apache-identity gate in main()'s Step 6 follow-up. None (the default) means no such
+            check is needed.
+        pre_commit_hook: Optional zero-arg callable invoked only when there ARE staged changes to
+            commit, immediately before `git commit`. Same True/False contract as pre_flight_hook.
             Used for checks that have nothing new to validate when nothing changed -- e.g. the
             juneau-docs Docusaurus smoke build, which only needs to run before a commit that
             actually contains new docs content. None (the default) means no such check is needed.
@@ -667,50 +702,60 @@ def commit_and_push(
         play_sound(success=False)
         return ("error", step_num)
 
-    # A clean tree skips the commit, not the push -- see docstring above.
-    has_changes = check_git_status(repo_dir)
-    if not has_changes and not commits_ahead:
+    try:
+        has_staged = bool(get_staged_paths(repo_dir))
+    except (subprocess.CalledProcessError, OSError) as e:
+        print(f"\nāŒ ERROR: Could not check the Git index{label}: {e}")
+        play_sound(success=False)
+        return ("error", step_num)
+
+    # Nothing staged skips the commit, not the push -- see docstring above.
+    if not has_staged and not commits_ahead:
         if error_msg:
-            print(f"\nℹ Nothing to commit locally{label}, and the upstream comparison could not "
-                  "be verified (see warning above) -- assuming nothing to push.")
+            print(f"\nℹ Nothing staged{label}, and the upstream comparison could not be "
+                  "verified (see warning above) -- assuming nothing to push.")
         else:
-            print(f"\nℹ Nothing to commit and no unpushed commits{label}.")
+            print(f"\nℹ Nothing staged and no unpushed commits{label}.")
         print(f"šŸŽ‰ Push{label} completed successfully (nothing to commit or push)!")
         play_sound(success=True)
         return ("nothing_to_do", step_num)
 
-    if pre_flight_hook is not None and not pre_flight_hook():
+    # There is something to commit and/or push -- refuse if any of it (or anything else in the
+    # tree) hasn't been reviewed (staged) yet. See docstring above for why this applies even to
+    # a push-only run.
+    try:
+        unreviewed_paths = check_unreviewed_changes(repo_dir)
+    except (subprocess.CalledProcessError, OSError) as e:
+        print(f"\nāŒ ERROR: Could not check for unreviewed changes{label}: {e}")
+        play_sound(success=False)
+        return ("error", step_num)
+    if unreviewed_paths:
+        print(f"\nāŒ ERROR: The working tree{label} has unreviewed changes -- staging is how "
+              "this script knows something has been reviewed, and these paths are not staged:")
+        for path in unreviewed_paths:
+            print(f"   {path}")
+        print("   Why: everything this pushes should be something you've read, not just")
+        print("   something that happened to be in the tree.")
+        print("\n   Nothing was committed or pushed. Stage each path above if you've reviewed")
+        print("   it, or set it aside for this run and restore it after:")
+        quoted_paths = " ".join(shlex.quote(path) for path in unreviewed_paths)
+        print(f"     git stash push -- {quoted_paths}")
+        print("     git stash pop")
+        play_sound(success=False)
         return ("error", step_num)
 
-    if has_changes:
-        preexisting_staged = check_preexisting_staged_changes(repo_dir)
-        if preexisting_staged:
-            print(f"\nāŒ ERROR: The Git index already has staged changes{label} from before this run:")
-            for path in preexisting_staged:
-                print(f"   {path}")
-            print("   Refusing to stage/commit over them -- they may belong to a concurrent")
-            print("   session sharing this working tree. Review, commit, or unstage them first,")
-            print("   then re-run push.py.")
-            play_sound(success=False)
-            return ("error", step_num)
+    if pre_flight_hook is not None and not pre_flight_hook():
+        return ("error", step_num)
 
+    if has_staged:
         if pre_commit_hook is not None and not pre_commit_hook():
             return ("error", step_num)
 
-        # Step N: Git add and commit
+        # Step N: Commit the index as-is -- see docstring above for why there is no `git add .`.
         print(f"\nšŸ“ Step {step_num}: Committing changes to Git{label}...")
-        if not run_command(
-            ["git", "add", "."],
-            f"  {step_num}.1: Staging all changes...",
-            repo_dir
-        ):
-            print(f"\nāŒ git add failed{label} -- aborting.")
-            play_sound(success=False)
-            return ("error", step_num)
-
         if not run_command(
             ["git", "commit", "-m", message],
-            f"  {step_num}.2: Creating commit...",
+            f"  Creating commit{label}...",
             repo_dir
         ):
             print(f"\nāŒ git commit failed{label} -- aborting.")
@@ -719,7 +764,7 @@ def commit_and_push(
         print(f"āœ… Step {step_num}: Git commit completed{label}.")
         step_num += 1
     else:
-        print(f"\nℹ No new changes to commit{label} -- {commits_ahead} unpushed commit(s) "
+        print(f"\nℹ Nothing staged to commit{label} -- {commits_ahead} unpushed commit(s) "
               "already on this branch will be pushed now.")
 
     # Step N (or N+1): Push to remote
@@ -738,6 +783,83 @@ def commit_and_push(
     return ("ok", step_num)
 
 
+def run_docs_followup(juneau_root, message, step_num):
+    """
+    juneau-docs follow-up to a default-flow juneau push: smoke check + commit + push, via
+    commit_and_push() (shared with --docs-only's run_docs_only()).
+
+    Extracted out of main() -- like run_tracker_audit_gate()/commit_and_push() -- so it's
+    independently testable without running main()'s mvn build/test steps first.
+
+    Guarded only by the juneau-docs sibling existing, NOT by whether it has local changes: a
+    clean juneau-docs tree can still have unpushed commits left over from an earlier
+    interrupted run, and this follow-up has to run for that case too or it silently never
+    pushes them -- the same false-success shape commit_and_push() exists to fix, one level up.
+
+    Uses two commit_and_push() hooks: the Apache-identity gate must run before ANY push
+    (including a push-only run with no new commit to make), so it's the pre_flight_hook; the
+    Docusaurus smoke check only has anything new to validate when there IS a commit about to be
+    made, so it's the pre_commit_hook.
+
+    Args:
+        juneau_root: The juneau repo root (used only to locate the juneau-docs sibling).
+        message: Commit message to use if a juneau-docs commit is made.
+        step_num: The current step number (for output formatting).
+
+    Returns:
+        tuple: (status, step_num)
+        - status: "ok" (juneau-docs was pushed, committed-then-pushed, or genuinely had nothing
+          to do -- caller should continue), "no_docs_root" (the juneau-docs sibling doesn't
+          exist -- a pure skip, not a failure, caller should continue), or "error" (caller
+          should exit 1 immediately).
+        - step_num: commit_and_push()'s returned step_num, unchanged for "no_docs_root".
+    """
+    docs_root = juneau_root.parent / "juneau-docs"
+    if not docs_root.exists():
+        return ("no_docs_root", step_num)
+
+    def _verify_docs_identity():
+        print("\nšŸ” Verifying git identity (apache.org email) on juneau-docs...")
+        if not verify_apache_identity(docs_root):
+            play_sound(success=False)
+            return False
+        print("āœ… Git identity verified")
+        return True
+
+    def _docs_smoke_check():
+        print("\nšŸ“š juneau-docs has changes — running Docusaurus smoke check first...")
+        docs_build_script = docs_root / "scripts" / "build-docs.py"
+        docs_smoke_start = time.time()
+        try:
+            result = subprocess.run(
+                [sys.executable, str(docs_build_script), "--skip-maven"],
+                cwd=docs_root,
+                check=False
+            )
+            docs_smoke_elapsed = time.time() - docs_smoke_start
+            if result.returncode != 0:
+                print("\nāŒ Docs smoke check failed — fix the Docusaurus build before pushing juneau-docs.")
+                play_sound(success=False)
+                return False
+            print(f"āœ… Docs smoke check passed ({docs_smoke_elapsed:.1f}s)")
+            return True
+        except Exception as e:
+            print(f"\nāŒ Docs smoke check failed: {e}")
+            play_sound(success=False)
+            return False
+
+    docs_status, step_num = commit_and_push(
+        docs_root, message, step_num,
+        label=" (juneau-docs)",
+        pull_hint="git -C ../juneau-docs pull",
+        pre_flight_hook=_verify_docs_identity,
+        pre_commit_hook=_docs_smoke_check,
+    )
+    if docs_status == "error":
+        return ("error", step_num)
+    return ("ok", step_num)
+
+
 def run_docs_only(args, juneau_root):  # NOSONAR python:S3776 -- Cognitive complexity is acceptable for this function
     """
     --docs-only mode: operate ONLY on the sibling juneau-docs repo.
@@ -783,7 +905,8 @@ def run_docs_only(args, juneau_root):  # NOSONAR python:S3776 -- Cognitive compl
         print("  2. Check for upstream changes on juneau-docs (git fetch + compare to upstream)")
         print("  3. Check juneau-docs git status (exit 0 with a no-changes message if clean)")
         print("  4. Run docs verification gate: python3 scripts/build-docs.py --skip-maven (runs verify-docs.py)")
-        print(f"  5. Commit changes: git add . && git commit -m \"{args.message}\"  (in juneau-docs)")
+        print(f"  5. Commit whatever is already staged: git commit -m \"{args.message}\"  (in juneau-docs; "
+              "refuses if anything is unstaged/untracked-and-not-gitignored)")
         print("  6. Push to remote: git push  (in juneau-docs)")
         print("\nDry run complete. Use without --dry-run to execute.")
         return 0
@@ -795,12 +918,12 @@ def run_docs_only(args, juneau_root):  # NOSONAR python:S3776 -- Cognitive compl
         return 1
     print("āœ… Step 1: Git identity verified")
 
-    # Steps 2-6: upstream check, no-op detection, docs smoke check, commit, and push -- all
-    # delegated to commit_and_push() (shared with main()'s Step 6 follow-up) so the clean-tree-
-    # vs-nothing-to-push fix and the pre-existing-staged-changes guard live in one place. The
-    # Docusaurus smoke build only has anything new to validate when there IS a commit about to
-    # be made, so it's wired in as commit_and_push()'s pre_commit_hook rather than running
-    # unconditionally.
+    # Steps 2-6: upstream check, no-op detection, unreviewed-changes guard, docs smoke check,
+    # commit, and push -- all delegated to commit_and_push() (shared with main()'s Step 6
+    # follow-up) so the nothing-staged-vs-nothing-to-push fix and the unreviewed-changes guard
+    # live in one place. The Docusaurus smoke build only has anything new to validate when there
+    # IS a commit about to be made, so it's wired in as commit_and_push()'s pre_commit_hook
+    # rather than running unconditionally.
     def _docs_smoke_check():
         print("\nšŸ“š juneau-docs has changes — running Docusaurus smoke check first...")
         docs_build_script = docs_root / "scripts" / "build-docs.py"
@@ -960,7 +1083,8 @@ Examples:
         step_num += 1
         print(f"  {step_num}. Verify external starter repos against local SNAPSHOT (./mvnw -q verify; missing paths skipped)")
         step_num += 1
-        print(f"  {step_num}. Commit changes: git add . && git commit -m \"{args.message}\"")
+        print(f"  {step_num}. Commit whatever is already staged: git commit -m \"{args.message}\" "
+              "(refuses if anything is unstaged/untracked-and-not-gitignored -- stage or discard it first)")
         step_num += 1
         print(f"  {step_num}. Push to remote: git push")
         print("\nDry run complete. Use without --dry-run to execute.")
@@ -1123,67 +1247,23 @@ Examples:
         return 1
     step_num += 1
     
-    # Step 4/5: Commit (if there's anything new) and push (if there's anything ahead) --
-    # extracted into commit_and_push() so the "clean tree != nothing to push" fix and the
-    # pre-existing-staged-changes guard are unit-testable against real git without invoking the
-    # mvn build/test steps above.
+    # Step 4/5: Commit (whatever is staged) and push (if there's anything ahead) --
+    # extracted into commit_and_push() so the "nothing staged != nothing to push" fix and the
+    # unreviewed-changes guard are unit-testable against real git without invoking the mvn
+    # build/test steps above.
     push_status, step_num = commit_and_push(juneau_root, args.message, step_num)
     if push_status == "error":
         return 1
     if push_status == "nothing_to_do":
         return 0
 
-    # Step 6 (optional): juneau-docs follow-up — smoke check + commit + push. Guarded only by
-    # docs_root existing (NOT by check_git_status(docs_root) as before): a clean juneau-docs
-    # tree can still have unpushed commits from an earlier interrupted run, and this follow-up
-    # has to run for that case too, or it silently never pushes them (the same false-success
-    # shape as the defect commit_and_push() exists to fix). Delegated to the same
-    # commit_and_push() as the default juneau flow and --docs-only, via two hooks: the identity
-    # gate must run before ANY push (including a push-only run with no new commit), and the
-    # smoke check only has anything to validate when there IS a commit about to be made.
-    docs_root = juneau_root.parent / "juneau-docs"
-    if docs_root.exists():
-        def _verify_docs_identity():
-            print("\nšŸ” Verifying git identity (apache.org email) on juneau-docs...")
-            if not verify_apache_identity(docs_root):
-                play_sound(success=False)
-                return False
-            print("āœ… Git identity verified")
-            return True
-
-        def _docs_smoke_check():
-            print(f"\nšŸ“š juneau-docs has changes — running Docusaurus smoke check first...")
-            docs_build_script = docs_root / "scripts" / "build-docs.py"
-            docs_smoke_start = time.time()
-            try:
-                result = subprocess.run(
-                    [sys.executable, str(docs_build_script), "--skip-maven"],
-                    cwd=docs_root,
-                    check=False
-                )
-                docs_smoke_elapsed = time.time() - docs_smoke_start
-                if result.returncode != 0:
-                    print("\nāŒ Docs smoke check failed — fix the Docusaurus build before pushing juneau-docs.")
-                    play_sound(success=False)
-                    return False
-                print(f"āœ… Docs smoke check passed ({docs_smoke_elapsed:.1f}s)")
-                return True
-            except Exception as e:
-                print(f"\nāŒ Docs smoke check failed: {e}")
-                play_sound(success=False)
-                return False
-
-        docs_status, step_num = commit_and_push(
-            docs_root, args.message, step_num,
-            label=" (juneau-docs)",
-            pull_hint="git -C ../juneau-docs pull",
-            pre_flight_hook=_verify_docs_identity,
-            pre_commit_hook=_docs_smoke_check,
-        )
-        if docs_status == "error":
-            return 1
-        # "nothing_to_do" here just means juneau-docs itself had nothing going on -- the juneau
-        # push above already succeeded, so fall through to the overall success block below.
+    # Step 6 (optional): juneau-docs follow-up — see run_docs_followup() for why the guard is
+    # "does juneau-docs exist" rather than "does it have local changes".
+    docs_status, step_num = run_docs_followup(juneau_root, args.message, step_num)
+    if docs_status == "error":
+        return 1
+    # "no_docs_root" or "ok" (including juneau-docs itself having had nothing to do) both fall
+    # through -- the juneau push above already succeeded either way.
 
     # Success!
     print("\n" + "=" * 70)
diff --git a/scripts/tests/test_push.py b/scripts/tests/test_push.py
index e676fcfc41..a63ef52bd3 100644
--- a/scripts/tests/test_push.py
+++ b/scripts/tests/test_push.py
@@ -12,7 +12,10 @@
 # ***************************************************************************************************************************
 """
 Tests for scripts/push.py: the --tracker-audit opt-in gate, and commit_and_push()'s
-clean-tree-vs-nothing-to-push distinction and pre-existing-staged-changes guard.
+nothing-staged-vs-nothing-to-push distinction and unreviewed-changes guard (refuses to commit
+or push while anything in the tree is unstaged or untracked-and-not-gitignored -- staging is
+the operator's record of having reviewed a path, so this script commits the index exactly as
+it finds it and never runs `git add .`).
 
 Juneau-specific exception to this directory's usual byte-for-byte-identical-across-repos rule
 (see README.md): push.py's --sonarqube-style opt-in gate pattern only exists in juneau's
@@ -68,9 +71,9 @@ def _args(tracker_audit: bool) -> argparse.Namespace:
 
 
 # ---------------------------------------------------------------------------------------
-# Real-git fixtures for commit_and_push() / check_upstream_changes() /
-# check_preexisting_staged_changes(). Mirrors test_reset_side_clones.py's hermetic_git_env
-# and _run/_commit helpers.
+# Real-git fixtures for commit_and_push() / check_upstream_changes() / get_staged_paths() /
+# check_unreviewed_changes(). Mirrors test_reset_side_clones.py's hermetic_git_env and
+# _run/_commit helpers.
 # ---------------------------------------------------------------------------------------
 @pytest.fixture(autouse=True)
 def hermetic_git_env(monkeypatch):
@@ -129,6 +132,61 @@ def _local_only_commit(repo_dir: Path, filename: str = "local.txt", message: str
     return _commit(repo_dir, message)
 
 
+@pytest.fixture
+def docs_remote_repo(tmp_path: Path) -> Path:
+    """
+    A SEPARATE bare repo standing in for the juneau-docs remote -- deliberately distinct from
+    remote_repo/repo (the juneau ones), since run_docs_only()/run_docs_followup() push to the
+    juneau-docs sibling's own remote, not juneau's. A test that only reused the juneau fixtures
+    unchanged could pass by accident even if a fix wired the wrong repo_dir/remote together.
+    """
+    bare = tmp_path / "docs-remote.git"
+    _run(tmp_path, "git", "init", "--bare", "-b", "master", str(bare))
+    return bare
+
+
+@pytest.fixture
+def docs_repo(tmp_path: Path, docs_remote_repo: Path, push_module) -> Path:
+    """
+    A real clone of docs_remote_repo, seeded with a stub scripts/build-docs.py that exits 0 (so
+    tests can exercise the real pre_commit_hook smoke-check wiring without a real Docusaurus
+    site), living at <tmp_path>/juneau-docs so juneau_root.parent / "juneau-docs" resolves to
+    it. Also configures the repo-local (never global) git identity commit_and_push()'s
+    verify_apache_identity() check reads, since that check is real, pre-existing behavior this
+    task doesn't touch and unrelated tests still need it satisfied.
+    """
+    seed = tmp_path / "docs-seed"
+    seed.mkdir()
+    _run(seed, "git", "init", "-b", "master", ".")
+    (seed / "README.md").write_text("docs first\n", encoding="utf-8")
+    (seed / "scripts").mkdir()
+    (seed / "scripts" / "build-docs.py").write_text("import sys\nsys.exit(0)\n", encoding="utf-8")
+    _commit(seed, "initial docs")
+    _run(seed, "git", "remote", "add", "origin", str(docs_remote_repo))
+    _run(seed, "git", "push", "origin", "master")
+
+    work = tmp_path / "juneau-docs"
+    _run(tmp_path, "git", "clone", str(docs_remote_repo), str(work))
+    _run(work, "git", "config", "user.email", push_module.REQUIRED_GIT_EMAIL)
+    _run(work, "git", "config", "user.name", "Push Test")
+    return work
+
+
+@pytest.fixture
+def juneau_root(tmp_path: Path, docs_repo: Path) -> Path:
+    """
+    A juneau_root whose PARENT holds docs_repo at `<parent>/juneau-docs` -- the sibling-checkout
+    layout run_docs_only()/run_docs_followup() expect. Does not need to exist itself: neither
+    function dereferences juneau_root directly, only juneau_root.parent.
+    """
+    return tmp_path / "juneau"
+
+
+def _docs_args(message: str = "docs message") -> argparse.Namespace:
+    """Just enough of push.py's parsed-args surface for run_docs_only()."""
+    return argparse.Namespace(message=message, dry_run=False, skip_tests=False, sonarqube=False)
+
+
 @pytest.fixture
 def git_spy(push_module, monkeypatch):
     """Record every argv passed to push_module.subprocess.run while still running real git."""
@@ -295,31 +353,68 @@ class TestCheckUpstreamChangesAheadBehind:
         assert (ahead, behind, error) == (None, None, None)
 
 
-class TestCheckPreexistingStagedChanges:
-    """The pre-flight check commit_and_push() uses to refuse committing over someone else's index state."""
+class TestGetStagedPaths:
+    """
+    The sole definition of "what push.py will commit" now that `git add .` is gone: whatever
+    is already in the index, because a staged path is the operator's record of having reviewed
+    it.
+    """
 
     def test_a_clean_index_reports_nothing(self, push_module, repo):
-        assert push_module.check_preexisting_staged_changes(repo) == []
+        assert push_module.get_staged_paths(repo) == []
 
     def test_a_staged_file_is_reported(self, push_module, repo):
-        (repo / "staged.txt").write_text("staged by someone else\n", encoding="utf-8")
-        _run(repo, "git", "add", "staged.txt")
+        (repo / "reviewed.txt").write_text("staged by the operator\n", encoding="utf-8")
+        _run(repo, "git", "add", "reviewed.txt")
 
-        assert push_module.check_preexisting_staged_changes(repo) == ["staged.txt"]
+        assert push_module.get_staged_paths(repo) == ["reviewed.txt"]
 
     def test_an_unstaged_modification_alone_is_not_reported(self, push_module, repo):
-        """Unstaged dirt is not what this guard is about -- only what's already IN the index."""
         (repo / "README.md").write_text("unstaged edit\n", encoding="utf-8")
-        assert push_module.check_preexisting_staged_changes(repo) == []
+        assert push_module.get_staged_paths(repo) == []
+
+
+class TestCheckUnreviewedChanges:
+    """
+    The other half of the invariant: anything NOT staged. Unstaged modifications to tracked
+    files and untracked, non-gitignored files are both "unreviewed"; gitignored untracked
+    files are not (see check_unreviewed_changes()'s docstring for why).
+    """
+
+    def test_a_clean_tree_reports_nothing(self, push_module, repo):
+        assert push_module.check_unreviewed_changes(repo) == []
+
+    def test_an_unstaged_modification_to_a_tracked_file_is_reported(self, push_module, repo):
+        (repo / "README.md").write_text("unstaged edit\n", encoding="utf-8")
+        assert push_module.check_unreviewed_changes(repo) == ["README.md"]
+
+    def test_an_untracked_non_ignored_file_is_reported(self, push_module, repo):
+        (repo / "scratch.txt").write_text("brand new, not staged\n", encoding="utf-8")
+        assert push_module.check_unreviewed_changes(repo) == ["scratch.txt"]
+
+    def test_a_gitignored_untracked_file_is_not_reported(self, push_module, repo):
+        (repo / ".gitignore").write_text("ignored.log\n", encoding="utf-8")
+        _commit(repo, "add gitignore")
+        (repo / "ignored.log").write_text("noise\n", encoding="utf-8")
+
+        assert push_module.check_unreviewed_changes(repo) == []
+
+    def test_a_staged_file_alone_is_not_reported(self, push_module, repo):
+        """Staged content is reviewed content -- it's the other function's (get_staged_paths()) job."""
+        (repo / "reviewed.txt").write_text("staged and reviewed\n", encoding="utf-8")
+        _run(repo, "git", "add", "reviewed.txt")
+
+        assert push_module.check_unreviewed_changes(repo) == []
 
 
 class TestCommitAndPushFalseSuccessRegression:
     """
-    The defect: a clean working tree with unpushed local commits used to be reported as
-    "nothing to commit and push" (returning success) without ever running `git push`.
+    The defect: a working tree with nothing staged but unpushed local commits used to be
+    reported as "nothing to commit and push" (returning success) without ever running
+    `git push`.
 
     This is the test that fails against the pre-fix code: the pre-fix push.py checked only
-    `check_git_status()` (a clean tree) and returned success without consulting how far ahead
+    whether the working tree was clean and returned success without consulting how far ahead
     of upstream the branch was, so it would report success here while the remote never moved.
     A test that only checked the return status/exit code would pass against that bug -- the
     assertion that matters is that the remote ref ACTUALLY ADVANCED.
@@ -327,7 +422,8 @@ class TestCommitAndPushFalseSuccessRegression:
 
     def test_clean_tree_with_unpushed_commits_actually_pushes(self, push_module, repo, remote_repo, git_spy):
         local_head = _local_only_commit(repo)
-        assert push_module.check_git_status(repo) is False, "tree must be clean for this to be the regression case"
+        assert push_module.get_staged_paths(repo) == [], "index must be clean for this to be the regression case"
+        assert push_module.check_unreviewed_changes(repo) == [], "tree must be clean too, or this proves nothing"
 
         status, _ = push_module.commit_and_push(repo, "irrelevant message", 4)
 
@@ -363,7 +459,7 @@ class TestCommitAndPushFalseSuccessRegression:
 
 
 class TestCommitAndPushGenuineNoOp:
-    """Clean tree AND nothing ahead of upstream is the one case that is truly a no-op."""
+    """Nothing staged AND nothing ahead of upstream is the one case that is truly a no-op."""
 
     def test_returns_nothing_to_do_and_touches_nothing(self, push_module, repo, remote_repo, git_spy):
         remote_before = _run(remote_repo, "git", "rev-parse", "master")
@@ -374,14 +470,42 @@ class TestCommitAndPushGenuineNoOp:
         assert step_num == 4, "step_num must be unchanged when nothing happened"
         assert _run(remote_repo, "git", "rev-parse", "master") == remote_before
         assert not any(argv[:2] == ["git", "push"] for argv in git_spy)
-        assert not any(argv[:2] == ["git", "add"] for argv in git_spy)
+        assert not any(argv[:2] == ["git", "commit"] for argv in git_spy)
+
+    def test_unstaged_dirt_alone_with_nothing_ahead_is_still_a_no_op_not_a_refusal(
+        self, push_module, repo, remote_repo, git_spy
+    ):
+        """
+        Nothing staged and nothing ahead means nothing is about to be committed or pushed, so
+        stray unstaged/untracked content sitting in the tree can't taint a push that isn't
+        happening -- the unreviewed-changes guard only fires once there's actually something
+        to commit and/or push (see commit_and_push()'s docstring). Deliberate scoping choice,
+        not an oversight: an unconditional refusal here would fire on essentially any run where
+        ANY file anywhere in the repo has a stray edit, whether or not that run would push
+        anything at all.
+        """
+        (repo / "mid-edit.txt").write_text("still being worked on, nothing staged, nothing ahead\n", encoding="utf-8")
+        remote_before = _run(remote_repo, "git", "rev-parse", "master")
+
+        status, _ = push_module.commit_and_push(repo, "irrelevant message", 4)
+
+        assert status == "nothing_to_do"
+        assert _run(remote_repo, "git", "rev-parse", "master") == remote_before
+        assert not any(argv[:2] == ["git", "push"] for argv in git_spy)
+        assert not any(argv[:2] == ["git", "commit"] for argv in git_spy)
 
 
 class TestCommitAndPushDirtyTree:
-    """The ordinary path must keep working: a dirty tree still gets committed and pushed."""
+    """
+    The ordinary path must keep working: content the operator has reviewed and staged still
+    gets committed and pushed. Unlike before, staging is now the caller's job -- push.py
+    commits the index as it finds it (see commit_and_push()'s docstring) -- so every test here
+    stages explicitly rather than relying on an (now removed) `git add .`.
+    """
 
-    def test_a_dirty_tree_is_committed_with_the_given_message_and_pushed(self, push_module, repo, remote_repo):
+    def test_staged_changes_are_committed_with_the_given_message_and_pushed(self, push_module, repo, remote_repo):
         (repo / "README.md").write_text("new content\n", encoding="utf-8")
+        _run(repo, "git", "add", "README.md")
 
         status, step_num = push_module.commit_and_push(repo, "the commit message", 4)
 
@@ -390,30 +514,45 @@ class TestCommitAndPushDirtyTree:
         assert _run(repo, "git", "log", "-1", "--format=%s") == "the commit message"
         assert _run(remote_repo, "git", "rev-parse", "master") == _run(repo, "git", "rev-parse", "HEAD")
 
-    def test_an_untracked_file_is_picked_up_too(self, push_module, repo, remote_repo):
-        """`git add .` staging genuinely-new untracked work is unchanged, documented behavior."""
+    def test_a_staged_untracked_file_is_committed_too(self, push_module, repo, remote_repo):
         (repo / "new-file.txt").write_text("brand new\n", encoding="utf-8")
+        _run(repo, "git", "add", "new-file.txt")
 
         status, _ = push_module.commit_and_push(repo, "add new file", 4)
 
         assert status == "ok"
         assert _run(remote_repo, "git", "show", "HEAD:new-file.txt") == "brand new"
 
+    def test_git_add_is_never_invoked(self, push_module, repo, remote_repo, git_spy):
+        """push.py no longer decides what to stage -- the index already says (see docstring)."""
+        (repo / "README.md").write_text("new content\n", encoding="utf-8")
+        _run(repo, "git", "add", "README.md")
+        git_spy.clear()  # discard the setup `git add` above; only commit_and_push()'s own git calls matter here
 
-class TestCommitAndPushPreexistingStagedGuard:
+        push_module.commit_and_push(repo, "the commit message", 4)
+
+        assert not any(argv[:2] == ["git", "add"] for argv in git_spy)
+
+
+class TestCommitAndPushUnreviewedChangesGuard:
     """
-    Defect 2: `git add .` was unconditional, so anything unrelated already dirty (or, more
-    precisely, already staged -- since `git commit` commits the whole index regardless of what
-    THIS run's `git add .` stages) got swept into the commit. commit_and_push() now refuses
-    outright rather than guessing whether pre-existing staged content belongs to this push.
+    Defect 2, redesigned per a workflow fact that inverts the original fix: James stages files
+    as he reviews them, so a staged path is his record that he's read it and it's good. The
+    original fix refused when the index already held staged content -- which is his NORMAL
+    state, and would have fired on essentially every real run. The corrected rule refuses on
+    the opposite condition: anything UNSTAGED (an unstaged modification, or an untracked file
+    that isn't gitignored) anywhere in the tree, once there's something to commit and/or push.
+    That makes "everything committed or pushed has been reviewed" true by construction, and it
+    also means push.py no longer runs `git add .` at all -- it commits the index exactly as it
+    finds it.
     """
 
-    def test_preexisting_staged_content_aborts_before_any_add_commit_or_push(
+    def test_unstaged_modification_alongside_staged_work_aborts_before_commit_or_push(
         self, push_module, repo, remote_repo, git_spy
     ):
-        (repo / "unrelated.txt").write_text("staged by a concurrent session\n", encoding="utf-8")
-        _run(repo, "git", "add", "unrelated.txt")
-        (repo / "mine.txt").write_text("my own unstaged work\n", encoding="utf-8")
+        (repo / "reviewed.txt").write_text("staged and reviewed\n", encoding="utf-8")
+        _run(repo, "git", "add", "reviewed.txt")
+        (repo / "README.md").write_text("mid-edit, not staged\n", encoding="utf-8")
         head_before = _run(repo, "git", "rev-parse", "HEAD")
         remote_before = _run(remote_repo, "git", "rev-parse", "master")
         git_spy.clear()  # discard the setup `git add` above; only commit_and_push()'s own git calls matter here
@@ -423,37 +562,122 @@ class TestCommitAndPushPreexistingStagedGuard:
         assert status == "error"
         assert _run(repo, "git", "rev-parse", "HEAD") == head_before, "nothing should have been committed"
         assert _run(remote_repo, "git", "rev-parse", "master") == remote_before, "the remote must not move"
-        assert not any(argv[:2] == ["git", "add"] for argv in git_spy)
         assert not any(argv[:2] == ["git", "commit"] for argv in git_spy)
         assert not any(argv[:2] == ["git", "push"] for argv in git_spy)
 
+    def test_untracked_non_ignored_file_alongside_staged_work_aborts(self, push_module, repo, remote_repo):
+        (repo / "reviewed.txt").write_text("staged and reviewed\n", encoding="utf-8")
+        _run(repo, "git", "add", "reviewed.txt")
+        (repo / "scratch.txt").write_text("brand new, not staged\n", encoding="utf-8")
+
+        status, _ = push_module.commit_and_push(repo, "message", 4)
+
+        assert status == "error"
+        assert _run(remote_repo, "git", "rev-parse", "master") == _run(repo, "git", "rev-parse", "HEAD")
+
+    def test_a_gitignored_untracked_file_does_not_trip_the_guard(self, push_module, repo, remote_repo):
+        (repo / ".gitignore").write_text("build.log\n", encoding="utf-8")
+        _run(repo, "git", "add", ".gitignore")
+        (repo / "build.log").write_text("noise\n", encoding="utf-8")
+
+        status, _ = push_module.commit_and_push(repo, "add gitignore", 4)
+
+        assert status == "ok"
+        assert _run(remote_repo, "git", "rev-parse", "master") == _run(repo, "git", "rev-parse", "HEAD")
+
     def test_the_staged_file_remains_staged_and_the_unstaged_file_remains_unstaged(self, push_module, repo):
-        (repo / "unrelated.txt").write_text("staged by a concurrent session\n", encoding="utf-8")
-        _run(repo, "git", "add", "unrelated.txt")
-        (repo / "mine.txt").write_text("my own unstaged work\n", encoding="utf-8")
+        (repo / "reviewed.txt").write_text("staged and reviewed\n", encoding="utf-8")
+        _run(repo, "git", "add", "reviewed.txt")
+        (repo / "mine.txt").write_text("mid-edit, not staged\n", encoding="utf-8")
 
         push_module.commit_and_push(repo, "my commit message", 4)
 
-        assert _run(repo, "git", "diff", "--cached", "--name-only") == "unrelated.txt"
+        assert _run(repo, "git", "diff", "--cached", "--name-only") == "reviewed.txt"
         status_lines = _run(repo, "git", "status", "--porcelain").splitlines()
         assert "?? mine.txt" in status_lines
 
-    def test_the_error_message_names_the_staged_paths(self, push_module, repo, capsys):
-        (repo / "secret-in-progress.txt").write_text("do not touch\n", encoding="utf-8")
-        _run(repo, "git", "add", "secret-in-progress.txt")
+    def test_the_error_message_names_the_unreviewed_paths(self, push_module, repo, capsys):
+        (repo / "reviewed.txt").write_text("staged and reviewed\n", encoding="utf-8")
+        _run(repo, "git", "add", "reviewed.txt")
+        (repo / "secret-in-progress.txt").write_text("do not push yet\n", encoding="utf-8")
 
         push_module.commit_and_push(repo, "message", 4)
 
         assert "secret-in-progress.txt" in capsys.readouterr().out
 
-    def test_a_clean_index_with_only_unstaged_dirt_is_not_refused(self, push_module, repo, remote_repo):
-        """The guard is about the INDEX, not about dirtiness in general -- ordinary dirty trees must still work."""
-        (repo / "mine.txt").write_text("my own unstaged work\n", encoding="utf-8")
+    def test_the_error_message_includes_a_copy_pasteable_stash_recovery_hint(self, push_module, repo, capsys):
+        """
+        The recovery hint has to be discoverable at the moment of refusal, and it has to be the
+        REAL command for THIS refusal -- with the actual offending paths already filled in --
+        not a generic template, so this pins the exact paths into the emitted `git stash push`
+        command rather than just checking that a stash mention exists somewhere in the output.
+        """
+        (repo / "reviewed.txt").write_text("staged and reviewed\n", encoding="utf-8")
+        _run(repo, "git", "add", "reviewed.txt")
+        (repo / "one.txt").write_text("mid-edit one\n", encoding="utf-8")
+        (repo / "two.txt").write_text("mid-edit two\n", encoding="utf-8")
+
+        push_module.commit_and_push(repo, "message", 4)
+        out = capsys.readouterr().out
+
+        assert "git stash push -- one.txt two.txt" in out
+        assert "git stash pop" in out
+
+    def test_the_error_message_says_why_the_refusal_exists(self, push_module, repo, capsys):
+        (repo / "reviewed.txt").write_text("staged and reviewed\n", encoding="utf-8")
+        _run(repo, "git", "add", "reviewed.txt")
+        (repo / "mid-edit.txt").write_text("still being worked on\n", encoding="utf-8")
+
+        push_module.commit_and_push(repo, "message", 4)
+
+        assert "should be something you've read" in capsys.readouterr().out.lower()
+
+
+class TestCommitAndPushPartialReviewIsRefused:
+    """
+    The exact scenario the task named: some files reviewed and staged, others still mid-edit.
+    The strict rule refuses the WHOLE run rather than pushing just the reviewed part -- this is
+    the deliberate, current behavior (see commit_and_push()'s docstring for the reasoning, and
+    the task report for the escape-hatch question raised but not built).
+    """
+
+    def test_reviewed_and_staged_work_is_not_pushed_while_other_files_are_mid_edit(
+        self, push_module, repo, remote_repo, git_spy
+    ):
+        (repo / "reviewed-a.txt").write_text("reviewed a\n", encoding="utf-8")
+        (repo / "reviewed-b.txt").write_text("reviewed b\n", encoding="utf-8")
+        _run(repo, "git", "add", "reviewed-a.txt", "reviewed-b.txt")
+        (repo / "mid-edit.txt").write_text("still being worked on\n", encoding="utf-8")
+        remote_before = _run(remote_repo, "git", "rev-parse", "master")
+        git_spy.clear()
+
+        status, _ = push_module.commit_and_push(repo, "reviewed work", 4)
+
+        assert status == "error"
+        assert _run(remote_repo, "git", "rev-parse", "master") == remote_before
+        assert not any(argv[:2] == ["git", "commit"] for argv in git_spy)
+        assert not any(argv[:2] == ["git", "push"] for argv in git_spy)
+
+
+class TestCommitAndPushAheadOnlyBlockedByUnreviewedChanges:
+    """
+    The false-success fix's "a clean tree with nothing staged and commits ahead must still
+    push" guarantee is specifically scoped to a CLEAN tree. If the tree isn't clean -- even
+    though nothing currently staged is what would be pushed -- the ahead-only push is refused
+    too, the same as the has-staged-work case.
+    """
+
+    def test_an_ahead_only_push_is_blocked_by_unstaged_dirt(self, push_module, repo, remote_repo, git_spy):
+        _local_only_commit(repo)  # ahead by 1, index clean
+        (repo / "mid-edit.txt").write_text("still being worked on\n", encoding="utf-8")
+        remote_before = _run(remote_repo, "git", "rev-parse", "master")
+        git_spy.clear()
 
         status, _ = push_module.commit_and_push(repo, "message", 4)
 
-        assert status == "ok"
-        assert _run(remote_repo, "git", "show", "HEAD:mine.txt") == "my own unstaged work"
+        assert status == "error"
+        assert _run(remote_repo, "git", "rev-parse", "master") == remote_before
+        assert not any(argv[:2] == ["git", "push"] for argv in git_spy)
 
 
 class TestCommitAndPushBehindUpstream:
@@ -474,3 +698,194 @@ class TestCommitAndPushBehindUpstream:
         assert not any(argv[:2] == ["git", "add"] for argv in git_spy)
         assert not any(argv[:2] == ["git", "commit"] for argv in git_spy)
         assert not any(argv[:2] == ["git", "push"] for argv in git_spy)
+
+
+class TestRunDocsOnlyFalseSuccessRegression:
+    """
+    The same defect, replayed against run_docs_only() specifically rather than assumed to carry
+    over from the main-path test: juneau-docs pushes to ITS OWN remote (docs_remote_repo, a
+    separate bare repo from the juneau one), so this exercises commit_and_push() wired to a
+    genuinely different repo_dir/remote pair, not just a second call with the same fixture.
+
+    Manually replayed against the OLD run_docs_only() logic (Step 3's `check_git_status()`-only
+    check) before writing this test -- see the shell replay in the task history -- and confirmed
+    the old code would report success (return 0) while docs_remote_repo's `master` never moved.
+    """
+
+    def test_clean_tree_with_unpushed_docs_commits_actually_pushes(
+        self, push_module, docs_repo, docs_remote_repo, juneau_root, git_spy
+    ):
+        local_head = _local_only_commit(docs_repo)
+        git_spy.clear()  # discard the setup commit above
+
+        exit_code = push_module.run_docs_only(_docs_args(), juneau_root)
+
+        assert exit_code == 0
+        remote_head = _run(docs_remote_repo, "git", "rev-parse", "master")
+        assert remote_head == local_head, "the juneau-docs remote must actually have moved"
+        assert any(argv[:2] == ["git", "push"] for argv in git_spy), "git push must actually have run"
+
+    def test_clean_tree_with_unpushed_docs_commits_skips_the_smoke_check(
+        self, push_module, docs_repo, docs_remote_repo, juneau_root, capsys
+    ):
+        """
+        The stub build-docs.py in docs_repo always exits 0, so a passing smoke check alone
+        wouldn't prove it was skipped -- check for its own announcement text instead.
+        """
+        _local_only_commit(docs_repo)
+        capsys.readouterr()
+
+        exit_code = push_module.run_docs_only(_docs_args(), juneau_root)
+
+        assert exit_code == 0
+        assert "smoke check" not in capsys.readouterr().out.lower()
+
+
+class TestRunDocsOnlyGenuineNoOp:
+    def test_returns_zero_and_touches_nothing(self, push_module, docs_repo, docs_remote_repo, juneau_root, git_spy):
+        remote_before = _run(docs_remote_repo, "git", "rev-parse", "master")
+
+        exit_code = push_module.run_docs_only(_docs_args(), juneau_root)
+
+        assert exit_code == 0
+        assert _run(docs_remote_repo, "git", "rev-parse", "master") == remote_before
+        assert not any(argv[:2] == ["git", "push"] for argv in git_spy)
+        assert not any(argv[:2] == ["git", "add"] for argv in git_spy)
+
+
+class TestRunDocsOnlyUnreviewedChangesGuard:
+    def test_unstaged_docs_content_aborts_before_any_commit_or_push(
+        self, push_module, docs_repo, docs_remote_repo, juneau_root, git_spy
+    ):
+        (docs_repo / "reviewed.md").write_text("reviewed and staged\n", encoding="utf-8")
+        _run(docs_repo, "git", "add", "reviewed.md")
+        (docs_repo / "mid-edit.md").write_text("still being worked on\n", encoding="utf-8")
+        head_before = _run(docs_repo, "git", "rev-parse", "HEAD")
+        remote_before = _run(docs_remote_repo, "git", "rev-parse", "master")
+        git_spy.clear()
+
+        exit_code = push_module.run_docs_only(_docs_args(), juneau_root)
+
+        assert exit_code == 1
+        assert _run(docs_repo, "git", "rev-parse", "HEAD") == head_before
+        assert _run(docs_remote_repo, "git", "rev-parse", "master") == remote_before
+        assert not any(argv[:2] == ["git", "commit"] for argv in git_spy)
+        assert not any(argv[:2] == ["git", "push"] for argv in git_spy)
+
+
+class TestRunDocsOnlyDirtyTree:
+    """
+    The ordinary --docs-only path (a real, staged docs change, smoke check included) must keep
+    working.
+    """
+
+    def test_staged_changes_run_the_smoke_check_commit_and_push(
+        self, push_module, docs_repo, docs_remote_repo, juneau_root, capsys
+    ):
+        (docs_repo / "README.md").write_text("updated docs\n", encoding="utf-8")
+        _run(docs_repo, "git", "add", "README.md")
+
+        exit_code = push_module.run_docs_only(_docs_args("docs update"), juneau_root)
+
+        assert exit_code == 0
+        assert "smoke check" in capsys.readouterr().out.lower()
+        assert _run(docs_repo, "git", "log", "-1", "--format=%s") == "docs update"
+        assert _run(docs_remote_repo, "git", "rev-parse", "master") == _run(docs_repo, "git", "rev-parse", "HEAD")
+
+
+class TestRunDocsFollowup:
+    """main()'s Step 6, extracted as run_docs_followup() so it's testable without mvn."""
+
+    def test_no_docs_root_is_a_pure_skip(self, push_module, tmp_path):
+        lone_juneau_root = tmp_path / "juneau"
+        status, step_num = push_module.run_docs_followup(lone_juneau_root, "message", 6)
+        assert (status, step_num) == ("no_docs_root", 6)
+
+    def test_clean_tree_with_unpushed_docs_commits_actually_pushes(
+        self, push_module, docs_repo, docs_remote_repo, juneau_root, git_spy
+    ):
+        """
+        Same false-success regression as TestRunDocsOnlyFalseSuccessRegression, replayed at the
+        OTHER call site (main()'s Step 6 -- previously gated on a clean-working-tree check,
+        which would have skipped this entire follow-up, never even attempting a push).
+        """
+        local_head = _local_only_commit(docs_repo)
+        git_spy.clear()
+
+        status, _ = push_module.run_docs_followup(juneau_root, "message", 6)
+
+        assert status == "ok"
+        remote_head = _run(docs_remote_repo, "git", "rev-parse", "master")
+        assert remote_head == local_head, "the juneau-docs remote must actually have moved"
+        assert any(argv[:2] == ["git", "push"] for argv in git_spy)
+
+    def test_identity_gate_still_runs_for_an_ahead_only_push(
+        self, push_module, docs_repo, docs_remote_repo, juneau_root
+    ):
+        """
+        The identity gate is the pre_flight_hook specifically because it must run even when
+        there's nothing to commit -- only something to push. Breaking the repo-local identity
+        AFTER the commit (env vars, not this config, are what let the commit itself succeed)
+        proves the gate is consulted on this path, not bypassed because has_changes is False.
+        """
+        local_head = _local_only_commit(docs_repo)
+        _run(docs_repo, "git", "config", "--unset", "user.email")
+
+        status, _ = push_module.run_docs_followup(juneau_root, "message", 6)
+
+        assert status == "error"
+        assert _run(docs_remote_repo, "git", "rev-parse", "master") != local_head
+
+    def test_smoke_check_does_not_run_for_an_ahead_only_push(
+        self, push_module, docs_repo, docs_remote_repo, juneau_root, capsys
+    ):
+        _local_only_commit(docs_repo)
+        capsys.readouterr()
+
+        status, _ = push_module.run_docs_followup(juneau_root, "message", 6)
+
+        assert status == "ok"
+        assert "smoke check" not in capsys.readouterr().out.lower()
+
+    def test_genuine_no_op_returns_ok_and_touches_nothing(
+        self, push_module, docs_repo, docs_remote_repo, juneau_root, git_spy
+    ):
+        remote_before = _run(docs_remote_repo, "git", "rev-parse", "master")
+
+        status, _ = push_module.run_docs_followup(juneau_root, "message", 6)
+
+        assert status == "ok"
+        assert _run(docs_remote_repo, "git", "rev-parse", "master") == remote_before
+        assert not any(argv[:2] == ["git", "push"] for argv in git_spy)
+
+    def test_unstaged_docs_content_aborts_before_any_commit_or_push(
+        self, push_module, docs_repo, docs_remote_repo, juneau_root, git_spy
+    ):
+        (docs_repo / "reviewed.md").write_text("reviewed and staged\n", encoding="utf-8")
+        _run(docs_repo, "git", "add", "reviewed.md")
+        (docs_repo / "mid-edit.md").write_text("still being worked on\n", encoding="utf-8")
+        head_before = _run(docs_repo, "git", "rev-parse", "HEAD")
+        remote_before = _run(docs_remote_repo, "git", "rev-parse", "master")
+        git_spy.clear()
+
+        status, _ = push_module.run_docs_followup(juneau_root, "message", 6)
+
+        assert status == "error"
+        assert _run(docs_repo, "git", "rev-parse", "HEAD") == head_before
+        assert _run(docs_remote_repo, "git", "rev-parse", "master") == remote_before
+        assert not any(argv[:2] == ["git", "commit"] for argv in git_spy)
+        assert not any(argv[:2] == ["git", "push"] for argv in git_spy)
+
+    def test_staged_changes_run_the_smoke_check_commit_and_push(
+        self, push_module, docs_repo, docs_remote_repo, juneau_root, capsys
+    ):
+        (docs_repo / "README.md").write_text("updated docs via step 6\n", encoding="utf-8")
+        _run(docs_repo, "git", "add", "README.md")
+
+        status, step_num = push_module.run_docs_followup(juneau_root, "step 6 message", 6)
+
+        assert status == "ok"
+        assert step_num == 8, "one step for the commit, one for the push"
+        assert "smoke check" in capsys.readouterr().out.lower()
+        assert _run(docs_repo, "git", "log", "-1", "--format=%s") == "step 6 message"
+        assert _run(docs_remote_repo, "git", "rev-parse", "master") == _run(docs_repo, "git", "rev-parse", "HEAD")