Skip to content

fix(scaffold): the static and page-vite templates never posted BLOCK_READY (#206) - #208

Merged
ZacxDev merged 9 commits into
mainfrom
fix/block-ready-ack
Aug 6, 2026
Merged

ZacxDev merged 9 commits into
mainfrom
fix/block-ready-ack

Conversation

@ZacxDev

@ZacxDev ZacxDev commented Aug 5, 2026

Copy link
Copy Markdown
Contributor

Fixes #206.

What was broken

A page app is not shown by the Civitai host until it posts BLOCK_READY —
that handler (PageBlockHost.tsx:864-871) is the only transition into
ready. All three templates declare page, but only page-money ever sent
it, and only because @civitai/blocks-react's IframeTransport acks
internally (dist/internal/iframeTransport.js:311). static — the
civitai app init default — and page-vite are deliberately SDK-free, so
they had to say hello themselves and did not. BLOCK_READY appeared nowhere in
this repo.

Original omission, not a regression: git log --follow shows both template
files declared page from their first commit.

Two knock-on problems, fixed in the same commit:

  • Both templates modelled the wrong envelope. The host dispatches
    event.data.payload to its subscribers (usePostMessage.ts:189), so every
    block→host message is { type, payload }. Both templates put fields at the
    top level. The host ignores the BLOCK_READY payload, so this would not have
    broken the ack itself — it teaches the wrong shape for every message an
    author adds next.
  • RESIZE_IFRAME is N/A for a page surface (hostHandlerParity.ts:100-110:
    the page renders the iframe full-viewport and does not size to content). Both
    templates demoed it as "the minimal useful thing an app can do". Removed.

Two corrections to the issue text

The issue is right about the bug and wrong about the symptom, both times in the
direction of making it look milder than it is:

  1. It does not collapse the slot silently. pageBlockHostLogic.ts:476-479
    is explicit: "a FULL-PAGE surface that collapses is just a blank viewport.
    So a failed page renders a message INSIDE the trust frame instead."
    The user
    sees "This app didn't load in time … We already retried 2 times
    automatically."
  2. It is ~37s, not 10s. MAX_AUTO_RETRIES = 2 with
    AUTO_RETRY_BACKOFF_MS = [2000, 5000] → 10+2+10+5+10.

Also: the snippet the issue suggests as the fix reproduces the envelope bug
(top-level fields, payload: undefined at the host).

Measured control matrix

Real PageBlockHost from civitai@851f759c20, real Chromium, apps served over
HTTP into an iframe with the manifest's own allow-scripts allow-forms sandbox
(no allow-same-origin ⇒ opaque null origin). "after" apps re-scaffolded from
this branch's binary and rebuilt, not hand-edited.

case before after (2 runs)
static (default template) never ready → failure card ~37s ready 453 / 459 ms
page-vite never ready → failure card ~37s ready 477 / 434 ms
page-money (regression check) ready 431–472 ms ready 489 / 435 ms
inert page, no script (negative control) timeout ~37s still times out ~38.7s
naive BLOCK_READY poster (positive control) ready ready 269 / 218 ms

Both templates also verified at trustTier: 'internal' (pinned origin rather
than opaque null): ready in 470–531 ms. After the fix each block frame posts
exactly one BLOCK_READY and zero RESIZE_IFRAME; before, it posted
RESIZE_IFRAME ≥1 and no BLOCK_READY — which is what separates "the JS never
ran" from "the JS ran and said the wrong thing".

The negative control still failing is what makes the four greens readable.

Why ack on BLOCK_INIT, not on load

On-load is not broken. An on-load poster was measured working in the same
harness (ready in 178–265 ms). Ack-on-INIT is a robustness choice, and the
comments in the emitter say so rather than claiming otherwise:

  • No race. The host registers its BLOCK_READY subscriber inside an effect
    and silently drops a message whose type has no subscriber yet, with no
    retry (usePostMessage.ts:152-153). It re-posts BLOCK_INIT every 400 ms
    until acked (iframeInitController.ts:51), so answering INIT cannot be early.
  • No '*'. The init event carries event.origin, so the ack is addressed
    at the host instead of broadcast.
  • Correct timing. The host fades its launch overlay and enables
    pointerEvents on ready, so acking too early reveals an empty interactive
    frame.
  • It is what the SDK does, so both paths behave alike.

Repeats are a no-op (mirroring iframeTransport.js:293-296), which matters
because the host's inbound channel is rate-limited to 30 msg/sec across all
types
, with the budget consumed after subscriber lookup — re-acking every
retry could starve BLOCK_ERROR.

Structure: one authority, copied verbatim

internal/blockproto holds the emitter as embedded bytes;
scaffold.Render copies them with no text/template pass into the path
Template.ReadyAckPath() names (civitai-host.js / src/civitai-host.js).
No per-template .tmpl copy, because two hand-maintained copies drift and drift
here is invisible locally: the app renders fine and dies only inside the real
host. static stays no-build (a bare <script src>, no package.json);
page-vite stays SDK-free (a side-effect import).

This is the fourth vendored mirror in the CLI, alongside schema/, the slot
registry, and the dev-embed dotenv mirror. AGENTS.md item 11 records it and
item 10's "third vendored mirror" is amended.

What the two guards prove — and what they don't

Guard A (ready_ack_contract_test.go, in make ci) enumerates
AllTemplates() and decides subject-hood from evidence in the rendered
output
, never a list in the test: subject if the rendered manifest declares
page; expected to ship the emitter unless the rendered package.json depends
on @civitai/*. It asserts byte-equality with blockproto.ReadyAckSource() and
that the entry point actually reaches the file (index.html <script src>,
or an import in the module index.html loads) — as independent sub-tests, after
stripping comments. Plus a count positive control (≥2 SDK-free page templates
examined) and a shape predicate with a negative corpus (comment / README prose /
wrong envelope / untriggered post / '*' target), each required to be rejected
by the expected rule.

Guard A does not prove the ack fires. No Go static check can prove
JavaScript executes.

Guard B (ready_ack_runtime_test.go) loads each shipped emitter in node
under a window stub, plays the host's side, and reads the outbound message:
exactly one, only after a real BLOCK_INIT,
{type:'BLOCK_READY',payload:{height:0}}, addressed at the host origin and not
'*', with a second BLOCK_INIT producing no second ack. Env-gated
(CIVITAI_CHECK_SCAFFOLD_RUNTIME=1, mirroring pins_guard_test.go) so
make ci stays Go-only and offline, and wired into the daily
bump-scaffold-pins workflow as its own job — a gated test with no scheduled
runner is a meaningless green. It validates its own harness first: an inert
fixture and a naive-ack fixture go through the same assertions and must be
faulted, and the naive one doubles as the count positive control (it posts on
every message, so the driver's counter is watched moving off zero).

Guard B does not prove the real host accepts the ack — the stub is this
repo's reading of the contract. The browser matrix above is that evidence.

Mutation results

Each failure confirmed to come from that assertion's own error message, with
go test ./... otherwise clean:

mutation outcome
delete the <script> tag from static/index.html A wiring fails; A byte-equality passes
render an emitter one byte off canonical A byte-equality fails; A wiring passes
drop "page" from static's manifest static skipped and the count control fails
emitter posts {type,height} with no payload A shape and B fail
emitter acks on load instead of BLOCK_INIT A shape and B fail
invert event.source !== window.parent A passes entirely, whole Go module green, B fails

The last row is the reason Guard B exists: the emitter keeps every structural
feature Guard A can see and is completely inert. (The brief predicted
ack-on-load would play that role; measured, Guard A's shape rules catch that one
too — the inverted source check is the real blind spot. Reported as measured,
not as predicted.)

Verification

  • make ci green: 16 packages ok, 1545 === RUN / 1542 --- PASS / 0
    --- FAIL / 3 --- SKIP
    , no panic: test timed out, gofmt -s -l .
    silent, go mod tidy a no-op.
  • golangci-lint v2.12.2: 0 issues.
  • actionlint clean on the changed workflow, with a positive control (it
    rejects runs-on: ubuntu-lates, so its acceptance is a real green).
  • CIVITAI_CHECK_SCAFFOLD_RUNTIME=1 go test -run TestScaffoldedReadyAckActuallyFires
    green, controls reported.

Deliberately deferred

  • The internal/antipattern rule for a page manifest with no ready-ack, and
  • a civitai app validate warning for already-scaffolded apps.

Both are the right follow-ups — an author who scaffolded last week still has a
broken app and nothing tells them. They are not in this PR because landing them
now would turn the scaffolds' own self-validation red before the templates that
satisfy them have shipped.

Note for the schema owners (not touched here)

schema/app-block.manifest.schema.json describes iframe.resizable in
size-to-content terms, which is arguably wrong for a page app — the host
renders those full-viewport and RESIZE_IFRAME is marked N/A for
PageBlockHost. All three templates still set "resizable": true. That file is
a vendored mirror and ask-first per AGENTS.md, so it is left alone; flagging it
rather than fixing it.

🤖 Generated with Claude Code

ZacxDev added 6 commits August 5, 2026 14:01
…ADY (#206)

A `page` app is not shown by the Civitai host until it posts `BLOCK_READY` —
that handler in `PageBlockHost.tsx` is the only transition into `ready`. All
three templates declare `page`, but only `page-money` ever sent it, and only
because `@civitai/blocks-react`'s `IframeTransport` acks internally. `static`
(the `civitai app init` DEFAULT) and `page-vite` are deliberately SDK-free, so
they had to say hello themselves and did not. `BLOCK_READY` appeared nowhere in
this repo.

Measured against the REAL `PageBlockHost` (851f759c20) in Chromium,
apps scaffolded from the unfixed CLI and served over HTTP into a sandboxed
iframe with the manifest's own `allow-scripts allow-forms`:

  static     never ready -> visible failure card at ~37s
  page-vite  never ready -> visible failure card at ~37s
  page-money ready in 431-472ms

Same at both trust tiers. The ~37s is `MAX_AUTO_RETRIES = 2` with
`AUTO_RETRY_BACKOFF_MS = [2000, 5000]`. This was an original omission, not a
regression: `git log --follow` shows both template files declared `page` from
their first commit.

The fix vendors one canonical emitter in `internal/blockproto` and has
`scaffold.Render` copy it VERBATIM (no `text/template` pass) into the path
`Template.ReadyAckPath()` names — so there is exactly one authority and both
templates ship byte-identical bytes. Two hand-maintained copies would drift,
and drift here is invisible locally: the app renders fine and dies only inside
the real host.

Ack on BLOCK_INIT, not on load — and on INIT only. Not because on-load is
broken: an on-load poster was MEASURED WORKING in the same harness (ready in
178-265ms). On-INIT is chosen for robustness. The host registers its
BLOCK_READY subscriber inside an effect and silently DROPS a message whose type
has no subscriber yet, with no retry, while it re-posts BLOCK_INIT every ~400ms
until acked — so answering INIT removes the race. It also hands over
`event.origin`, so nothing posts to `'*'`; it is late enough not to reveal an
empty interactive frame (the host fades its launch overlay and enables
pointerEvents on ready); and it is what the SDK's own transport does. Repeats
are a no-op, because the host's inbound channel is rate-limited across all
types.

Also fixes the envelope both templates were teaching. Every block->host message
is `{ type, payload }` — the host dispatches `data.payload` — so the demo posts
with top-level fields modelled the wrong shape for every message an author adds
next. And `RESIZE_IFRAME` is removed outright: `hostHandlerParity.ts` marks it
N/A for `PageBlockHost` (a page block fills the surface and does not size to
content), so it was inert advice. `static/app.js`'s "the minimal useful thing an
app can do is tell the host how tall it is" was simply false for a page app.

After the fix, re-scaffolded from this CLI and re-measured in the same harness
(2 runs, stable): static ready in 453/459ms, page-vite in 477/434ms, page-money
still 489/435ms, and the inert negative control still times out at ~38s.

Refs #206
…enough

Guard A (`ready_ack_contract_test.go`, runs in `make ci`) enumerates
`AllTemplates()` and decides subject-hood from EVIDENCE in the rendered output,
never a list in the test: a template is subject to the page-host readiness
contract if its rendered `block.manifest.json` declares `page`, and it is
expected to ship the vendored emitter unless its rendered `package.json`
depends on `@civitai/*` (whose transport acks for it). It then asserts, as
INDEPENDENT sub-tests with distinct messages:

  - byte-equality of the rendered emitter with `blockproto.ReadyAckSource()`;
  - that the emitter is actually REACHED from the entry point — index.html's
    <script src>, or an import in the module index.html loads — checked after
    stripping comments, so the HTML comment above the script tag cannot
    satisfy it.

Plus a count positive control (>= 2 SDK-free page templates examined, with the
page/SDK split printed) so a guard that stopped observing cannot report a
serene pass, and a shape predicate with a negative corpus: a comment mentioning
BLOCK_READY, the string in a README, `{type:'BLOCK_READY', height:0}`, an
untriggered post, and a correct ack broadcast to `'*'` — each asserted to be
rejected BY THE EXPECTED RULE, not merely rejected.

Guard A cannot prove the ack FIRES. No Go static check can prove JavaScript
executes. Guard B (`ready_ack_runtime_test.go`) therefore loads each shipped
emitter in node under a `window` stub, plays the host's side of the handshake
at it, and reads what came out: exactly one message, only after a real
BLOCK_INIT, `{type:'BLOCK_READY',payload:{height:0}}`, addressed at the host
origin and not `'*'`, with a second BLOCK_INIT producing no second ack. It is
env-gated (CIVITAI_CHECK_SCAFFOLD_RUNTIME=1, mirroring the network guard in
pins_guard_test.go) so `make ci` stays Go-only and offline, and it is wired
into the daily `bump-scaffold-pins` workflow as its own job — an env-gated test
with no scheduled runner is a meaningless green.

Guard B validates its own harness before reading its verdict: two known-bad
fixtures (an inert emitter, and a naive ack with the wrong envelope, a `'*'`
target, no gate and no dedupe) go through the SAME assertions and must be
faulted, and the naive one doubles as the count positive control — it posts on
every message, so the driver's counter is watched moving off zero before any
zero it reports elsewhere is believed.

Mutation results (each failure confirmed to come from THIS guard's own
assertion, with the rest of `go test ./...` clean):

  delete the <script> tag from static/index.html   -> A wiring FAILS, A
                                                      byte-equality PASSES
  render an emitter one byte off canonical         -> A byte-equality FAILS,
                                                      A wiring PASSES
  drop "page" from static's manifest               -> static skipped AND the
                                                      count control FAILS
  emitter posts {type,height} with no payload      -> A shape + B FAIL
  emitter acks on load instead of BLOCK_INIT       -> A shape + B FAIL
  invert `event.source !== window.parent`          -> A passes ENTIRELY, whole
                                                      Go module green, B FAILS

That last one is the point of Guard B: the emitter keeps every structural
feature Guard A can see and is completely inert. (The brief predicted the
ack-on-load mutation would play that role; measured, Guard A's shape rules
catch that one too — the inverted source check is the real blind spot.)

Refs #206
The templates now ship `civitai-host.js`, and nothing told anyone what it is or
why it looks like it does nothing locally. Four surfaces:

- `static` / `page-vite` READMEs get a "The host handshake — don't delete it"
  section: what BLOCK_READY is for, that the envelope is `{type,payload}`, that
  the ack answers BLOCK_INIT rather than announcing, and the no-local-host
  caveat only page-money's README carried ("`npm run dev` alone shows a blank
  screen — there's no host to send BLOCK_INIT"). Without that caveat the
  emitter's silence during local preview reads as a bug and the file reads as
  deletable.
- `civitai app init`'s next-steps output says the same thing for the two
  templates that ship the emitter. The NeedsHarness branch already covered it;
  the static/page-vite branches said "open index.html" / "npm run dev" with no
  hint that what you see locally is not what the host does.
- README.md gains a "The host handshake (BLOCK_READY)" section under Templates,
  including that RESIZE_IFRAME is not part of a page app's protocol.
- AGENTS.md item 11 records the decision: what it mirrors, why ack-on-INIT
  (with the honest note that on-load was MEASURED working — it is a robustness
  choice, not a bug fix), why `{type,payload}` even though the host ignores this
  particular payload, why `event.origin` and not `'*'`, that RESIZE_IFRAME is
  deliberately ABSENT from page templates, and what each of the two guards does
  and does not prove. Item 10's "third vendored mirror" is amended — this makes
  four (schema/, the slot registry, the dev-embed dotenv mirror, and this).

Refs #206
Two pre-existing claims, unrelated to #206 and wrong on inspection of the
templates:

- "The `page-money` / `page-vite` templates ship a dev **harness**" — only
  page-money does. `templates/page-vite/` has no `Harness.tsx.tmpl`, and its
  package.json declares neither `dev:harness` nor `dev:live`. An author
  following that sentence runs a script that does not exist.
- "the code your app actually imports lives in two published npm packages (the
  `page-money` / `page-vite` templates wire them for you)" — page-vite's
  package.json depends on react, react-dom and vite only. Being SDK-free is the
  point of that template, not an oversight.

Also states the reason `npm run dev` shows nothing of the protocol (no host to
send BLOCK_INIT) rather than describing it as a blank screen, which is no longer
true now that the templates render their own UI.
… nothing

Audit round on #206. No 🔴 findings — the shipped emitter is correct and the
browser matrix held — but two of the guards were weaker than the PR claimed.

**The wiring check matched a BASENAME, not a path.** Two mutants shipped a
broken app past the ENTIRE suite, both measured green, both reproducing #206:

  static/index.html   src="./vendor/civitai-host.js"          -> ships a 404
  page-vite/main.jsx  import '../nonexistent/civitai-host.js' -> build fails

So the claim that the guard proved the entry point REACHES the emitter was not
true. Every reference is now RESOLVED — a <script src> against the document
root, an import against the importing module's directory — and compared with
where the emitter actually is; a bare specifier or a URL is not a project path
at all. On failure it prints every reference with what it resolved to and
whether that file exists, so a near-miss names itself. Backed by a 10-case
corpus on synthetic trees (wrong subdir, unresolvable relative, bare specifier,
HTML comment, commented-out import, orphan module, no script tags, CDN URL that
merely ends in the name) — the accept cases are the two real template shapes.

**Guard B never ran on a PR.** ci.yml never set CIVITAI_CHECK_SCAFFOLD_RUNTIME,
so it skipped on every pull request and ran only on a daily schedule, on the
default branch, with no dependent job. The failure the PR advertised it caught —
inverting `event.source !== window.parent` — would have merged green and been
reported up to 24h later. It is now a `ready-ack-runtime` job in ci.yml; the
daily copy stays, relabelled as the drift runner it actually is. Measured, this
is not theoretical: FOUR mutations are invisible to the whole offline suite and
caught only here (inverted source check, inverted type check, latch-before-post,
listener attached inside a setTimeout).

**Nothing in CI built page-vite.** Only page-money was ever scaffolded and
built (template-page-money, scaffold-currency). Since this PR its entry module
has a hard resolution dependency on ./civitai-host.js, so the second mutant
above would have shipped a template that cannot `npm run build` at all. New
`template-page-vite` job builds it and asserts the ack SURVIVES BUNDLING —
Guard A pins the source tree, Vite output is what the platform serves. Control
pair measured locally: with the import the bundle carries BLOCK_INIT/BLOCK_READY,
with it commented out it carries neither, while the positive control (the app's
display name) matches either way, proving the grep reads the bundle.

**`acked` latched before a post that can throw.** `postMessage` rejects a
targetOrigin it cannot parse as a URL, and `event.origin` is the string "null"
when the sender is at an opaque origin — so one throw would silence the emitter
forever while the host kept retrying. Measured in Chromium 1228 rather than
taken from the spec: `postMessage(msg, 'null')` throws
`SyntaxError: Invalid target origin 'null'`. The latch now sets after the post.
Not reachable through today's PageBlockHost, and the comment says so rather than
claiming a live bug. Pinned by a new `--throw-first-post` mode in the driver,
which also models a browser's per-listener exception isolation (previously a
throwing emitter would have killed the driver instead of being observed).

Also: `app init`'s three handshake lines had no test, unlike every sibling
caveat — added, with a control asserting page-money does NOT get them, and
proven to fail when the block is deleted. And the provenance path was wrong in
two comments: usePostMessage.ts is under src/components/AppBlocks/, never
src/hooks/.

Full battery re-run, 16 mutations, ZERO survivors — including the classes the
first battery missed (inverted condition, swapped operands, wrong bind,
commented-out-but-greppable). The battery now also has a positive control that
each mutation APPLIED: one regex silently no-op'd on the `}` inside
`{{ .Name }}` and read as a surviving mutant until that check existed.

Refs #206
Four corrections from the audit round, plus mirror currency.

**The emitter checks the sender WINDOW, not the sender ORIGIN.** It answers
`window.parent` and replies to whatever origin that window sent from — which
establishes "our embedder", not "Civitai". The comment said "only the framing
host" and the README said "the host's real origin"; both overstated it. That is
sound for THIS message (the ack carries `{height:0}` and discloses nothing a
page that chose to frame us doesn't already know) and insufficient for anything
else — and both scaffold READMEs explicitly invite authors to add more messages.
All four surfaces now say what it actually establishes, and carry an explicit
warning that an origin allowlist is required before handling any message that
carries data.

Decision recorded in AGENTS.md rather than left implicit: we deliberately do NOT
vendor an allowlist into the emitter. The real set (production, preview
subdomains, dev-*.civit.ai tunnels) is platform state that moves without notice,
so it would become a FIFTH mirror needing lockstep, and getting it wrong
silently breaks the dev tunnel — while @civitai/blocks-react already maintains
exactly that list from VITE_BLOCK_ALLOWED_PARENT_ORIGINS. Keep the emitter
minimal; make adopting the SDK the documented prerequisite for handling data.

**The upgrade path could wedge the host into a fake-ready state.** "If you later
adopt @civitai/blocks-react, delete it" was the one line reversing the
"don't delete it" instruction repeated in four other places, and it was a
parenthetical. If an author adds the SDK and KEEPS the emitter, whichever
handshake answers the first BLOCK_INIT calls notifyReady() -> stop(), clearing
the retry interval AND the readiness timeout; the SDK's waitForInit then rejects
at its own 10s and the host sits "ready" showing an app that never started, with
no retry and no card. Worse than #206, and silent. Now a callout with the
mechanism, in both template READMEs, the main README, and the emitter header.

**useBlockResize was described as "for the non-page block surfaces"**, but
page-money — a page template — calls it (src/App.tsx.tmpl:140). The accurate
statement is that RESIZE_IFRAME is ignored on a page surface and the hook is
surface-agnostic, so calling it there is a harmless no-op that lets SDK
component code move between surfaces.

**Mirror currency: the reference moved from 851f759c20 to 35a9598dc9.** Two
intervening commits touch this contract. BLOCK_HELLO now EXISTS host-side
(iframeInitController.notifyHello, hostHandlerParity.ts, host browser tests) —
the earlier "zero host references" note was true when measured and is now stale.
Re-verified independently rather than taken on report: notifyHello() leaves the
retry interval and readiness timeout armed by start() untouched, and its own
comment forbids it becoming a precondition for sending init, so a block that
never announces is served by the unchanged retry loop — exactly what this
emitter relies on. Recorded that the emitter deliberately does not send it
(scaffolded apps forgo the fast path, cost: one retry tick of latency) and that
the init-fragment path ships gated off and refuses surface === 'dev-tunnel'.
Emitting BLOCK_HELLO remains out of scope.

Also corrects the provenance path (usePostMessage.ts lives under
src/components/AppBlocks/, never src/hooks/) and documents the three guards,
including why the wiring check must resolve paths and must never go back to a
basename or strings.Contains match.

Refs #206
@ZacxDev

ZacxDev commented Aug 5, 2026

Copy link
Copy Markdown
Contributor Author

Audit round — corrections to this PR's body, and what changed

An independent blind audit found no 🔴 findings (the shipped emitter is correct and the browser matrix held up), but it falsified two claims I made in the description above. Correcting them here rather than quietly editing the body, plus the fixes in eddaa44 and 738ecb6.

❌ Correction 1 — the wiring guard did NOT prove what I said it proved

The body says Guard A asserts "that the entry point actually reaches the file". That was not true as written. It matched a basename, so two mutants shipped a broken app past the entire suite — both measured green, both reproducing #206:

mutant what it ships
static/index.html → src="./vendor/civitai-host.js" a 404; the app never says hello
page-vite/main.jsx → import '../nonexistent/civitai-host.js' npm run build fails outright

This is the "spelled rather than structural" class: the check could pass while the hazard existed in a different shape.

Fixed. Every reference is now resolved — a <script src> against the document root, an import against the importing module's directory — and compared with where the emitter actually is; a bare specifier or a URL is not a project path at all. On failure it prints each reference with what it resolved to and whether that file exists. Backed by a 10-case corpus on synthetic trees (wrong subdir, unresolvable relative, bare specifier, HTML comment, commented-out import, orphan module, no script tags, CDN URL ending in the name). The claim now holds; AGENTS.md item 11 records that a basename or strings.Contains match must never come back.

❌ Correction 2 — Guard B ran on nothing that could block a merge

The body presents Guard B as the thing that catches an inverted event.source check. It was env-gated with no PR runner: ci.yml never set CIVITAI_CHECK_SCAFFOLD_RUNTIME, so it skipped on every pull request and ran only on a daily schedule, on the default branch, with no dependent job. The exact failure I advertised it catching would have merged green and surfaced up to 24h later.

Fixed. ready-ack-runtime is now a job in ci.yml (per-PR, gating); the daily copy stays, relabelled as the drift runner it actually is.

This matters more than it sounds: four of sixteen mutations are invisible to the entire offline suite and are caught only by Guard B — inverted source check, inverted type check, latch-before-post, and a listener attached inside a setTimeout.

Gate proven, not assumed — #211 was opened as a temporary draft carrying the inverted source check (a mutation go test ./... passes cleanly), purely to watch ready-ack-runtime go red on a pull request. It did. That PR is closed and its branch deleted; it was never mergeable and exists only as evidence.

Also fixed in this round

  • Nothing in CI built page-vite — only page-money was ever scaffolded and built. Since this PR its entry module has a hard resolution dependency on ./civitai-host.js, so mutant Open-source readiness: README, help, CLAUDE.md, release flow, tests, LICENSE #2 above would have shipped a template that cannot build. New template-page-vite job builds it and asserts the ack survives bundling (Guard A pins the source tree; Vite output is what the platform serves). Control pair measured: with the import the bundle carries BLOCK_INIT/BLOCK_READY, with it commented out it carries neither, while the positive control (the app's display name) matches either way.
  • acked latched before a post that can throw. Now measured rather than spec-derived: in Chromium 1228, postMessage(msg, 'null') throws SyntaxError: Invalid target origin 'null', and event.origin is the string "null" when the sender is at an opaque origin. Latching first would silence the emitter forever after one throw. The latch now sets after the post; pinned by a new --throw-first-post driver mode (which also models a browser's per-listener exception isolation — previously a throwing emitter would have killed the driver rather than being observed). Not reachable through today's PageBlockHost, and the comment says so.
  • The emitter pins the sender WINDOW, not the sender ORIGIN. The comment said "only the framing host" and the README said "the host's real origin" — both overstated it. It establishes our embedder, not Civitai. Sound for this message (the ack carries no data); insufficient for anything you add next, which both scaffold READMEs explicitly invite. All four surfaces corrected, with an explicit warning that an origin allowlist is required before handling any message carrying data. Decision recorded, not left implicit: no allowlist is vendored into the emitter — the real set (prod, preview subdomains, dev-*.civit.ai) is platform state that moves without notice, would become a fifth mirror needing lockstep, and breaks the dev tunnel when wrong, while @civitai/blocks-react already maintains it from VITE_BLOCK_ALLOWED_PARENT_ORIGINS.
  • The documented upgrade path could wedge the host into a fake-ready state. "If you later adopt @civitai/blocks-react, delete it" was a parenthetical, and the only line reversing "don't delete it". Keeping both means whichever handshake answers the first BLOCK_INIT clears the host's retry loop and readiness timeout; the SDK's waitForInit then rejects at 10s and the host sits "ready" showing an app that never started — no retry, no card. Worse than Scaffolded 'static' (default) and 'page-vite' apps never send BLOCK_READY — the host times out and collapses them #206 and silent. Now a callout with the mechanism in four places.
  • useBlockResize doc was self-inconsistent — described as "for the non-page block surfaces" while page-money (a page template) calls it. Corrected: RESIZE_IFRAME is ignored on a page surface and the hook is surface-agnostic, so calling it there is a harmless no-op.
  • Provenance path was wrong in two comments and in the body above: usePostMessage.ts is at src/components/AppBlocks/, not src/hooks/ — it never lived there.
  • app init's handshake lines had no test, unlike every sibling caveat. Added, with a control asserting page-money does not get them, and proven to fail when the block is deleted.

Mirror currency — the reference moved

The platform checkout moved 851f759c20 → 35a9598dc9. BLOCK_HELLO now exists host-side (iframeInitController.notifyHello, hostHandlerParity.ts, host browser tests); the body's "zero host references" was true when measured and is now stale.

Re-verified independently rather than taken on report: notifyHello() leaves the retry interval and readiness timeout armed by start() untouched, and its own comment forbids it becoming a precondition for sending init — so a block that never announces is served by the unchanged retry loop, which is exactly what this emitter relies on. This PR is unaffected. The emitter deliberately does not send BLOCK_HELLO (cost: one retry tick of latency; benefit: no second vendored message), and that is now recorded in AGENTS.md along with the fact that the init-fragment fast path ships gated off and refuses surface === 'dev-tunnel'. Emitting it stays out of scope.

Re-verification (the fix round resets the gate)

Full mutant battery re-run — 16 mutations, ZERO survivors, including the classes the first battery missed:

mutation offline suite Guard B
wrong subdir in <script src> FAIL pass
unresolvable relative import FAIL pass
<script> tag deleted FAIL pass
import commented out (still greppable) FAIL pass
bare specifier FAIL pass
rendered emitter drifts one byte FAIL pass
static manifest drops "page" FAIL pass
wrong envelope (no payload) FAIL FAIL
acks on load instead of BLOCK_INIT FAIL FAIL
wrong bind: listener on document FAIL FAIL
swapped operands (origin, message) FAIL FAIL
inverted source check pass FAIL
inverted type check pass FAIL
latch before post pass FAIL
listener inside a setTimeout pass FAIL
app init drops the handshake caveat FAIL pass

Each offline failure was attributed to the specific test that killed it (four other tests render these same templates, so "something went red" would not be attribution).

⚠️ One process note worth recording: the first battery run reported static manifest drops "page" as a survivor. It wasn't — my mutation regex stopped at the } inside {{ .Name }}, so the mutation silently never applied and a no-op read exactly like a guard gap. The battery now has a positive control that each mutation actually changed the tree, and the real mutation is killed by the count control.

Browser matrix re-run (real PageBlockHost, real Chromium, apps re-scaffolded and rebuilt from this branch), 2 runs:

case result
static ready 459 / 483 ms
page-vite ready 453 / 491 ms
page-money (regression) ready 152 / 458 ms
inert control still times out ~38.6 s ✅

Both templates also verified at trustTier: internal (413–456 ms), and each posts exactly one BLOCK_READY and zero RESIZE_IFRAME. The inert control still failing is what makes the rest readable. (Incidentally visible in the tap: page-money now posts BLOCK_HELLO, independently confirming the mirror-currency finding above.)

make ci: 16 packages ok, 1560 === RUN / 1557 --- PASS / 0 --- FAIL / 3 --- SKIP, no timeout panic, gofmt -s -l . silent. golangci-lint v2.12.2: 0 issues. actionlint (with shellcheck) clean on both changed workflows, with a positive control proving it can go red on them.

Still deferred, unchanged

The internal/antipattern rule and the civitai app validate warning for already-scaffolded apps; and "resizable": true in the manifests / the schema/ resizable wording (vendored, ask-first).

🤖 Generated with Claude Code

ZacxDev added 2 commits August 5, 2026 19:08
…vacuous

Round 3 on #206, from a delta re-audit of 4bc88ad..738ecb6 (which cleared the
previous round's ten findings by mutation).

**The gating claim was false.** `ready_ack_runtime_test.go` and AGENTS.md said
the per-PR ready-ack job BLOCKS the merge. Measured:

  $ gh api repos/civitai/cli/branches/main/protection --jq .required_status_checks.contexts
  ["pins-vs-published","scaffold-currency"]
  $ gh api repos/civitai/cli/rulesets
  []

`ready-ack-runtime` is not a required context. Neither is `template-page-vite`,
and neither is `build-test`. A red run reports and stops nothing — so #211's red
job proved the check DETECTS the regression, not that it would have BLOCKED it.

Corrected in the wording, not in branch protection: making these contexts
required is the honest alternative but it is a repo-policy change affecting
every open PR, so it is the maintainer's call and is recorded as the outstanding
step instead of taken unilaterally. The measurement is inline at each site so
the next reader can re-check rather than trust it.

**Every ::error:: in the bundle assertion was unreachable.** `set -euo pipefail`
plus `n=$(grep -rlF … | wc -l)`: grep exits 1 on no match, pipefail propagates,
`set -e` kills the step AT THE ASSIGNMENT. Reproduced — it exited 1 having
printed only the positive-control line, so the log could not distinguish "the
harness isn't reading the bundle" from "the ack didn't survive the build", which
is the exact ambiguity the positive control exists to remove. It failed CLOSED,
so this was diagnosis, not safety. Each grep now carries `|| true`, the loop
accumulates rc instead of dying, and the needles are scoped to the JS files
actually counted — previously a match in dist/index.html or a public/
passthrough would have satisfied them. Watched in both directions with a decoy
planted in dist/index.html: annotations print, the step still fails rc=1, and
the decoy does not satisfy the assertions.

**The SDK-template control test was vacuous.** Replacing the guard at
app_init.go:238 with `if true` survived the ENTIRE suite: page-money's
ReadyAckPath() is "", so the line printed with an empty filename ("   performs
the host handshake — keep it. …") and the "civitai-host.js is absent" assertion
was satisfied BY THE BUG it should have caught. An assertion spelled on a value
the failure mode erases can only ever pass. Now asserted on the phrase
"performs the host handshake", shared as a constant with the positive test, and
watched going red on that exact mutation.

Checked the conjunct question rather than assuming: NEITHER half should go.
They are coextensive across today's three templates but guard different
failures — `ReadyAckPath() != ""` stops the empty-filename line, `!NeedsHarness()`
stops "there's no host to send BLOCK_INIT" being printed at a template whose
dev:harness mounts one. Recorded at the site.

**Dead branch removed, three live ones pinned.** The `://` half of the URL guard
was unconditionally dead — verified by resolving candidate specifiers with each
half toggled, it changes the outcome for no input — so it is gone rather than
left as a branch no mutation can reach, and the CDN corpus case now says it is
rejected by the fallthrough. The `//` half is NOT dead: without it
`//evil.example.com/../civitai-host.js` has its leading slash stripped,
filepath.Join cleans the `..`, and it resolves to EXACTLY the emitter's path and
is accepted. Pinned, along with the `?`/`#` suffix stripping and the
errNoScriptTags early return, via a new optional `wantErr` on the corpus so a
rejection must come from the branch the case exists to exercise.

Also sweeps two leftover "the real host origin" overclaims from a456c95 that the
round-2 sweep missed (contract_test.go:92, runtime_test.go:151).

Battery: 20 mutations, ZERO survivors, each attributed to the specific test that
killed it, with the apply-verification and null-mutant controls in place.

Refs #206
PR #210 (`feat/generate`) adds items 11–16 to this same list while this PR adds
item 11, and `git merge-tree --write-tree` exits 1 on AGENTS.md — a real
textual conflict. Both PRs also independently corrected the intro's stale
"items 5–8 cover `civitai app metrics`" to "5–9" while adding a different
clause, so the correct merged sentence is neither side's and a naive
take-one-side resolution silently loses the other's range.

Nothing about that is discoverable from the file, so whoever resolves the next
collision re-derives the rule under time pressure. Writing it down: append-only,
numbered by arrival, the PR merging SECOND renumbers its OWN items, never an
existing one — because items cross-reference each other by number (item 10
points at item 11, item 9 points at item 6) and so do code comments.

Applied the new rule to the file as it stands: all four `item N` / `items N–M`
references resolve correctly (items 4 and 8 as non-mirrors, items 5–9 as
metrics, item 6 as `notOwned`, item 11 as the ready-ack). The Layout section
carries no item references in this branch.

No code change; the mutation battery is unaffected.

Refs #206
@ZacxDev

ZacxDev commented Aug 6, 2026

Copy link
Copy Markdown
Contributor Author

Round 3 — a false claim about gating, an unreachable diagnostic, and a vacuous control

A delta re-audit of 4bc88ad..738ecb6 came back safe to merge, no 🔴 — the ten prior findings verified fixed by mutation. It then found three more 🟡 in the delta plus leftovers. All verified against the code before implementing; all were real, and one of them falsifies a claim in my previous comment on this PR.

❌ Correction — "a PR check is what makes it a guard" was false

My last comment and ready_ack_runtime_test.go both said the per-PR ready-ack-runtime job blocks the merge. It does not.

$ gh api repos/civitai/cli/branches/main/protection --jq .required_status_checks.contexts
["pins-vs-published","scaffold-currency"]
$ gh api repos/civitai/cli/rulesets
[]

ready-ack-runtime is not a required context. Neither is template-page-vite. Neither is build-test. A red run reports on the PR and stops nothing — so #211's red job was evidence the check detects the regression, not evidence it would have blocked it. That distinction was mine to make and I got it wrong.

Fixed by correcting the wording, not by changing branch protection. Making these contexts required is the honest alternative, but it is a repo-policy change affecting every open PR including #210, and that is the maintainer's decision — it has not been given, so I did not take it. ready_ack_runtime_test.go, ci.yml and AGENTS.md item 11 now say what is true (runs and reports on every PR; not a required context) and record making it required as the outstanding step, with the measurement inline so the next reader can re-check it.

🟡 Every ::error:: in the bundle assertion was unreachable

set -euo pipefail + n=$(grep -rlF "$needle" dist/ | wc -l): grep exits 1 on no match, pipefail propagates, set -e kills the step at the assignment. Reproduced — the step exited 1 having printed only the positive-control line, never the count and never the annotation.

It failed closed, so this was a diagnosis bug, not a safety one — but the log could not distinguish "the harness isn't reading the bundle" from "the ack didn't survive the build", which is exactly the ambiguity the positive control exists to remove. Each grep now carries || true, the loop accumulates rc instead of dying, and the needles are scoped to the JS files actually counted (previously a match in dist/index.html or a public/ passthrough would have satisfied them).

Watched working, both directions, with a decoy planted in dist/index.html:

=== ack survives (expect rc=0) ===          === ack MISSING + decoy (expect rc=1) ===
JS files emitted into dist/: 1              JS files emitted into dist/: 1
positive control: 1 file(s)                 positive control: 1 file(s)
BLOCK_INIT: 1 file(s)                       BLOCK_INIT: 0 file(s)
BLOCK_READY: 1 file(s)                      ::error::BLOCK_INIT is absent …
--- step rc=0 ---                           BLOCK_READY: 0 file(s)
                                            ::error::BLOCK_READY is absent …
                                            --- step rc=1 ---

The decoy is the scoping proof: the strings are present in dist/index.html and the counts are still 0.

🟡 The new app_init control test was vacuous

Replacing the guard at app_init.go:238 with if true survived the entire suite. page-money's ReadyAckPath() is "", so the line printed with an empty filename — performs the host handshake — keep it. … — and my assertion, which checked that civitai-host.js was absent, was satisfied by the very bug it should have caught. Spelling an assertion on a value the failure mode erases can only ever pass.

Now asserted on the phrase "performs the host handshake", which an empty path cannot erase, and shared as a constant between the positive and negative tests. Watched going red on the exact mutation that survived.

On the conjunct question: I checked, and neither half should go — they're coextensive across today's three templates but each guards a different failure. ReadyAckPath() != "" is what stops the empty-filename line (demonstrated above); !NeedsHarness() is what keeps "there's no host to send BLOCK_INIT" from being printed at a template whose dev:harness mounts one. A future template shipping both needs the wording reconsidered, not a conjunct deleted. Recorded as a comment at the site.

🟡 Dead branch removed, three live branches pinned

  • :// half of the URL guard: genuinely dead, removed. Verified by exhaustively resolving candidate specifiers with each half toggled: dropping :// changes the accept/reject outcome for no input, including https://x/../civitai-host.js. The CDN corpus case is rejected by the fallthrough and now says so instead of appearing to exercise a guard it never reached.
  • // half: NOT dead — load-bearing, and now pinned. Without it, //evil.example.com/../civitai-host.js has its leading slash stripped, filepath.Join cleans the .., and it resolves to exactly the emitter's path and is accepted. New corpus case; deleting the guard now fails.
  • errNoScriptTags early return and ?/# suffix stripping (N6) were both correct but deletable without any test failing. Pinned: the corpus gained an optional wantErr so a rejection has to come from the expected branch (previously the no-script-tags case was green via the fallthrough either way), plus an accept case for import './civitai-host.js?url'.

Leftover sweep

Two sites still carried the "the real host origin" overclaim I corrected everywhere else in round 2 — ready_ack_contract_test.go:92 and ready_ack_runtime_test.go:151, both introduced in a456c95 and missed by that sweep. Both now say "BLOCK_INIT carries the sender's origin". Re-grepped: zero remaining occurrences across internal/, README.md and AGENTS.md.

Not taken

N5 (resolver over-strict on layouts no shipped template uses — fail-closed and documented), N7 (residual accept-shapes: string-literal-only import, type="text/plain", <script> inside <template>), branch protection, and the still-deferred antipattern rule / validate warning — all out of scope by agreement.

🤖 Generated with Claude Code

Addendum — AGENTS.md item numbering (prose only)

#210 (feat/generate) adds items 11–16 to the same list while this PR adds item 11; git merge-tree --write-tree exits 1 on AGENTS.md. Both PRs also independently corrected the intro's stale "items 5–8 cover civitai app metrics" to "5–9" while adding a different clause, so the correct merged sentence is neither side's and a take-one-side resolution silently drops the other's range.

Per agreement this PR does not resolve that conflict, renumber, or touch #210 — item 11 stays item 11, and #210 renumbers to 12–17 on its next rebase. What's added is three sentences recording the convention so the next collision doesn't re-derive it: append-only, numbered by arrival, the PR merging second renumbers its own items, never an existing one (items cross-reference each other by number — item 10 → item 11, item 9 → item 6 — and so do code comments), and re-grep every item N after any renumber.

Applied the rule to the file as it stands: all four references resolve correctly. The Layout section carries no item references in this branch.

Both are claims this PR itself introduced, in text a future maintainer would
read as evidence.

`resolveProjectRef` said the removed `strings.Contains(spec, "://")` half
"decided nothing for any input". Measured, five inputs disagree — among them
`/x://../civitai-host.js` and `./civitai-host.js?u=https://evil.com`, which it
rejected and which now resolve to the emitter. None is a URL and the new
answer is what a browser gives, so the removal fixes a latent false rejection;
but the comment justified deleting a guard on a stronger claim than the
measurement supports. It now states the scope it was actually measured at.

The numbering note said the Layout section cross-references items by number.
It does not — the coupling today is other items, `ci.yml` and a Go test
comment. Left as-is it points a maintainer doing a renumber at a section with
nothing to fix, while understating where the real references live.

Comment-only: 17 changed lines in the Go file, none outside a comment.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Scaffolded 'static' (default) and 'page-vite' apps never send BLOCK_READY — the host times out and collapses them

1 participant