Skip to content

DO NOT MERGE — temporary: prove the ready-ack CI gate goes red - #211

Closed
ZacxDev wants to merge 7 commits into
mainfrom
test/ready-ack-gate-proof
Closed

ZacxDev wants to merge 7 commits into
mainfrom
test/ready-ack-gate-proof

Conversation

@ZacxDev

@ZacxDev ZacxDev commented Aug 5, 2026

Copy link
Copy Markdown
Contributor

Temporary draft, opened only to watch ci.yml's new ready-ack-runtime job FAIL on a pull request, then closed immediately.

The commit inverts event.source !== window.parent in the vendored emitter, making it completely inert. Measured locally: go test ./... is fully green with this mutation — it is invisible to every offline check. If ready-ack-runtime does not go red here, the gate added in #208 does not gate.

Evidence for #208. Closing as soon as the job reports.

ZacxDev added 7 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
…e fails

Do not merge. This branch exists only to watch ci.yml's ready-ack-runtime job
go RED on a pull request. The mutation makes the emitter completely inert while
passing every offline assertion (measured: whole Go suite green).

Will be closed and deleted immediately.
@ZacxDev

ZacxDev commented Aug 5, 2026

Copy link
Copy Markdown
Contributor Author

Purpose served: ready-ack-runtime went red here — the only failing check, with Guard B's own assertions (the emitter answered a foreign window and addressed the ack at the wrong origin) — while build-test (the entire offline Go suite) passed, exactly as measured locally.

That is the evidence for #208: the per-PR gate added there really does block this class of regression. Closing; never mergeable.

@ZacxDev ZacxDev closed this Aug 5, 2026
@ZacxDev
ZacxDev deleted the test/ready-ack-gate-proof branch August 5, 2026 23:16
ZacxDev added a commit that referenced this pull request Aug 6, 2026
…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
ZacxDev added a commit that referenced this pull request Aug 6, 2026
…READY (#206)

* fix(scaffold): the static and page-vite templates never said BLOCK_READY (#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

* test(scaffold): two guards for the ready-ack, because neither one is 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

* docs: the host handshake is a contract authors must not delete

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

* docs(readme): page-vite ships no dev harness and wires no SDK

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.

* fix(scaffold): the wiring guard matched a basename, and Guard B gated 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

* docs: the emitter pins a window, not an identity — and the mirror moved

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

* fix(scaffold): "blocks the merge" was false, and the SDK control was 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

* docs(agents): record how the "intentional decisions" list is numbered

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

* docs: two comments claimed more than had been measured

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>

---------

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.

1 participant