From 17356ab94da66abf2eb8ad3132f51c43c806651c Mon Sep 17 00:00:00 2001 From: ZacxDev Date: Wed, 5 Aug 2026 14:01:19 -0500 Subject: [PATCH 1/9] fix(scaffold): the static and page-vite templates never said BLOCK_READY (#206) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 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` (civitai@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 --- internal/blockproto/blockproto.go | 44 +++++++++++++ internal/blockproto/ready-ack.js | 63 +++++++++++++++++++ internal/scaffold/scaffold.go | 43 +++++++++++++ internal/scaffold/scaffold_test.go | 3 + .../templates/page-vite/src/App.jsx.tmpl | 23 +++---- .../templates/page-vite/src/main.jsx.tmpl | 5 ++ .../scaffold/templates/static/app.js.tmpl | 32 +++++----- .../scaffold/templates/static/index.html.tmpl | 6 +- 8 files changed, 186 insertions(+), 33 deletions(-) create mode 100644 internal/blockproto/blockproto.go create mode 100644 internal/blockproto/ready-ack.js diff --git a/internal/blockproto/blockproto.go b/internal/blockproto/blockproto.go new file mode 100644 index 00000000..f6e3f499 --- /dev/null +++ b/internal/blockproto/blockproto.go @@ -0,0 +1,44 @@ +// Package blockproto is the CLI's single authority for the block -> host +// postMessage contract that scaffolded, SDK-free apps must implement +// themselves. +// +// It exists so the handshake code has exactly ONE copy in this repo. The +// templates do not each carry their own `.tmpl` of it — `scaffold.Render` +// writes these bytes verbatim into every template that needs it, and +// `internal/scaffold/ready_ack_contract_test.go` asserts the rendered copies +// are byte-identical to what `ReadyAckSource` returns. Two hand-maintained +// copies would drift, and the failure mode of drift is invisible: the app +// renders locally and dies only inside the real host. +// +// This is a VENDORED MIRROR of a server-side contract (civitai/civitai -> +// src/components/AppBlocks/PageBlockHost.tsx and src/hooks/usePostMessage.ts), +// in the same sense as `schema/`, the slot registry in +// `internal/validate/targets.go`, and the dev-embed mirror in +// `internal/devtunnel`. When the platform changes the handshake, this file +// changes with it. See AGENTS.md, "Intentional decisions that look wrong". +package blockproto + +import _ "embed" + +// readyAck is the canonical ready-ack emitter. It is plain, dependency-free, +// ES5-safe JavaScript so the no-build `static` template can load it with a +// bare From a456c9565125732b28a9db4a13a6fd08d7d1a64f Mon Sep 17 00:00:00 2001 From: ZacxDev Date: Wed, 5 Aug 2026 14:01:48 -0500 Subject: [PATCH 2/9] test(scaffold): two guards for the ready-ack, because neither one is enough MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 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 `}, + {"app.js", "// app"}, + }, + wantAccept: true, + }, + { + name: "accept: the entry module imports it (the page-vite shape)", + ack: ackRel, + files: []file{ + {"index.html", ``}, + {"src/main.jsx", "import './civitai-host.js';\nimport React from 'react';"}, + }, + wantAccept: true, + }, + { + name: "reject: right basename, wrong directory in the script tag", + ack: "civitai-host.js", + files: []file{ + {"index.html", ``}, + {"app.js", "// app"}, + }, + }, + { + name: "reject: right basename, unresolvable relative import", + ack: ackRel, + files: []file{ + {"index.html", ``}, + {"src/main.jsx", "import '../nonexistent/civitai-host.js';"}, + }, + }, + { + name: "reject: a BARE specifier that would resolve to a package", + ack: ackRel, + files: []file{ + {"index.html", ``}, + {"src/main.jsx", "import 'civitai-host.js';"}, + }, + }, + { + name: "reject: referenced only from an HTML comment", + ack: "civitai-host.js", + files: []file{ + {"index.html", "\n"}, + {"app.js", "// app"}, + }, + }, + { + name: "reject: the import is commented out but still greppable", + ack: ackRel, + files: []file{ + {"index.html", ``}, + {"src/main.jsx", "// import './civitai-host.js';\nimport React from 'react';"}, + }, + }, + { + name: "reject: imported by a file nothing loads", + ack: ackRel, + files: []file{ + {"index.html", ``}, + {"src/main.jsx", "import React from 'react';"}, + {"src/orphan.js", "import './civitai-host.js';"}, + }, + }, + { + name: "reject: no script tags at all", + ack: "civitai-host.js", + files: []file{{"index.html", "

hi

"}}, + }, + { + name: "reject: loaded from a CDN URL that merely ends in the name", + ack: "civitai-host.js", + files: []file{ + {"index.html", ``}, + {"app.js", "// app"}, + }, + }, + } + + for _, c := range cases { + t.Run(c.name, func(t *testing.T) { + dir := t.TempDir() + // The emitter itself always exists where `ack` says — so a + // rejection can only come from the REFERENCE, never from a missing + // file. + all := append([]file{{c.ack, "// emitter"}}, c.files...) + for _, f := range all { + p := filepath.Join(dir, filepath.FromSlash(f.path)) + if err := os.MkdirAll(filepath.Dir(p), 0o755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(p, []byte(f.body), 0o644); err != nil { + t.Fatal(err) + } + } + chain, err := readyAckWiring(dir, c.ack) + if c.wantAccept { + if err != nil { + t.Fatalf("wiring check REJECTED a correctly wired project: %v", err) + } + t.Logf("accepted: %s", chain) + return + } + if err == nil { + t.Fatalf("wiring check ACCEPTED a project the browser cannot load the emitter in: %q\n"+ + "this is the basename-matching class — the reference must RESOLVE to the emitter's real path", chain) + } + t.Logf("rejected: %v", err) + }) + } +} + // --------------------------------------------------------------------------- // The per-template contract. // --------------------------------------------------------------------------- @@ -351,6 +486,10 @@ func civitaiSDKDeps(t *testing.T, dir string) []string { var ( reHTMLComment = regexp.MustCompile(`(?s)`) reScriptSrc = regexp.MustCompile(`(?is)]*\bsrc\s*=\s*["']([^"']+)["']`) + // Captures the SPECIFIER of an import / re-export / require, so it can be + // resolved. Matching a basename inside the specifier is what let + // `import '../nonexistent/civitai-host.js'` through. + reJSImport = regexp.MustCompile(`(?:\bimport\s*\(?\s*|\bfrom\s+|\brequire\(\s*)['"]([^'"]+)['"]`) ) // readyAckWiring walks the rendered entry chain and returns a description of @@ -360,8 +499,21 @@ var ( // (for a module entry) that module's imports — rather than grepping the whole // tree, so an emitter referenced only from a README, a comment, or a file // nothing loads does not satisfy it. +// +// 🔴 Every reference is RESOLVED to a path and compared with where the emitter +// actually IS. It is deliberately NOT a basename match. A basename match is a +// SPELLED check rather than a structural one, and it passes while the hazard +// exists in a different shape — both of these were MEASURED surviving the +// entire suite before this was rewritten: +// +// static/index.html src="./vendor/civitai-host.js" -> ships a 404 +// page-vite/main.jsx import '../nonexistent/civitai-host.js' -> build fails +// +// Both reproduce #206 with every check green, which is why the first version of +// this guard did not deserve the claim that it proved the entry point REACHES +// the emitter. func readyAckWiring(dir, ackRel string) (string, error) { - base := filepath.Base(filepath.FromSlash(ackRel)) + want := filepath.Clean(filepath.Join(dir, filepath.FromSlash(ackRel))) htmlRaw, err := os.ReadFile(filepath.Join(dir, "index.html")) if err != nil { @@ -369,34 +521,98 @@ func readyAckWiring(dir, ackRel string) (string, error) { } html := reHTMLComment.ReplaceAllString(string(htmlRaw), "") + // Every reference considered, with what it resolved to and whether that + // file exists — reported verbatim on failure so a near-miss (right + // basename, wrong directory) names itself instead of reading as "nothing + // references it at all". + var tried []string + note := func(what, spec, resolved string) { + if resolved == "" { + tried = append(tried, fmt.Sprintf("%s %q -> not a path in this project (bare specifier or URL)", what, spec)) + return + } + state := "exists" + if _, err := os.Stat(resolved); err != nil { + state = "DOES NOT EXIST" + } + rel, relErr := filepath.Rel(dir, resolved) + if relErr != nil { + rel = resolved + } + tried = append(tried, fmt.Sprintf("%s %q -> %s (%s)", what, spec, filepath.ToSlash(rel), state)) + } + var entries []string for _, m := range reScriptSrc.FindAllStringSubmatch(html, -1) { src := m[1] - if filepath.Base(src) == base { - return "index.html loads " + src + " directly", nil + // A `}, {"app.js", "// app"}, }, + wantErr: "not a path in this project", + }, + { + // 🔴 Pins the `//` half of the URL guard, which IS load-bearing: + // without it the leading slash is stripped, filepath.Join cleans the + // `..`, and this resolves to EXACTLY the emitter's path — an + // off-project URL would be accepted as the emitter. + name: "reject: protocol-relative URL that cleans back to the emitter path", + ack: "civitai-host.js", + files: []file{ + {"index.html", ``}, + {"app.js", "// app"}, + }, + wantErr: "not a path in this project", + }, + { + // Pins the `?`/`#` suffix stripping: Vite's `?url` / `?raw` suffixes + // are not part of the path, and the emitter is still the emitter. + name: "accept: entry module imports it with a Vite ?url suffix", + ack: ackRel, + files: []file{ + {"index.html", ``}, + {"src/main.jsx", "import './civitai-host.js?url';"}, + }, + wantAccept: true, }, } @@ -313,6 +350,11 @@ func TestReadyAckWiringPredicate(t *testing.T) { t.Fatalf("wiring check ACCEPTED a project the browser cannot load the emitter in: %q\n"+ "this is the basename-matching class — the reference must RESOLVE to the emitter's real path", chain) } + if c.wantErr != "" && !strings.Contains(err.Error(), c.wantErr) { + t.Fatalf("rejected for the wrong reason — want an error mentioning %q, got:\n%v\n"+ + "a rejection from a different branch would leave the one this case exists to pin untested", + c.wantErr, err) + } t.Logf("rejected: %v", err) }) } @@ -595,11 +637,23 @@ func readyAckWiring(dir, ackRel string) (string, error) { // makes `import 'civitai-host.js'` (a bare specifier that would resolve to a // PACKAGE, not this file) a rejection rather than a match. func resolveProjectRef(projectDir, fromDir, spec string) (string, bool) { - if strings.Contains(spec, "://") || strings.HasPrefix(spec, "//") { + // A protocol-relative URL only LOOKS root-relative. Without this, the `/` + // case below strips one slash and `filepath.Join` cleans the rest, so + // `//evil.example.com/../civitai-host.js` resolves to EXACTLY the emitter's + // path and is accepted — measured. This half is load-bearing and pinned by + // the "protocol-relative URL that cleans back" corpus case. + // + // There is deliberately no `strings.Contains(spec, "://")` companion: an + // `https://…` specifier already fails the switch below and returns the + // identical `("", false)`, so that half decided nothing for any input. It + // was removed rather than left as a branch no mutation can reach — the + // CDN-URL corpus case is rejected by the fallthrough, and says so. + if strings.HasPrefix(spec, "//") { return "", false } // Vite allows query/hash suffixes (`?raw`, `?url`); they are not part of - // the path. + // the path, and an emitter imported as `./civitai-host.js?url` is still the + // emitter. Pinned by the "?url suffix" accept case. if i := strings.IndexAny(spec, "?#"); i >= 0 { spec = spec[:i] } diff --git a/internal/scaffold/ready_ack_runtime_test.go b/internal/scaffold/ready_ack_runtime_test.go index d777c557..c4545e82 100644 --- a/internal/scaffold/ready_ack_runtime_test.go +++ b/internal/scaffold/ready_ack_runtime_test.go @@ -32,16 +32,25 @@ import ( // // It needs node, so it is env-gated exactly like the network guard in // pins_guard_test.go: `make ci` / `go test ./...` stays Go-only and offline. -// It has TWO runners, and the per-PR one is the load-bearing half: -// - .github/workflows/ci.yml, job `ready-ack-runtime` — runs on every pull -// request, so a regression BLOCKS the merge. The first version of this -// guard had only the scheduled runner below, which meant the very failure -// the PR advertised it caught (inverting the `event.source` check) would -// have merged green and been reported up to 24h later, with nothing gated -// on the result. +// It has TWO runners: +// - .github/workflows/ci.yml, job `ready-ack-runtime` — runs and REPORTS on +// every pull request. The first version had only the scheduled runner +// below, so the failure this guard exists to catch (inverting the +// `event.source` check) would have surfaced up to 24h after a merge, on a +// workflow nobody watches. // - .github/workflows/bump-scaffold-pins.yml, job `ready-ack-runtime` — the // daily sweep, which catches drift on `main` between PRs. // +// 🔴 REPORTING IS NOT GATING — this job does NOT currently block a merge. +// Measured, not assumed: `gh api repos/civitai/cli/branches/main/protection` +// lists exactly two required contexts, `pins-vs-published` and +// `scaffold-currency`, with no rulesets. `ready-ack-runtime` is not among them +// — and neither is `build-test` — so a red run here is visible on the PR and +// stops nothing. Adding it to the required contexts is the outstanding step +// that would turn reporting into gating; that is a repo-policy change +// affecting every PR, so it is the maintainer's call and has not been taken +// here. Until it is, do not describe this job as a gate. +// // WHAT IT STILL DOES NOT PROVE: that the REAL host accepts the ack. The stub // is this repo's reading of the contract, not the contract. The end-to-end // evidence is a browser run against the real PageBlockHost, recorded in the @@ -148,7 +157,7 @@ func handshakeProblems(r driverResult) []string { p = append(p, "BLOCK_READY puts `height` at the TOP LEVEL — it belongs inside `payload`") } if m.TargetOrigin == "*" { - p = append(p, "BLOCK_READY was broadcast to '*' — BLOCK_INIT hands over the real host origin, use it") + p = append(p, "BLOCK_READY was broadcast to '*' — BLOCK_INIT carries the sender's origin, use it") } else if m.TargetOrigin != r.HostOrigin { p = append(p, "BLOCK_READY was addressed at "+m.TargetOrigin+", want the host origin "+r.HostOrigin) } From 7b4bf8ec87dc8f5f9938ee1ce578ba9d005da27b Mon Sep 17 00:00:00 2001 From: ZacxDev Date: Wed, 5 Aug 2026 19:09:23 -0500 Subject: [PATCH 8/9] docs(agents): record how the "intentional decisions" list is numbered MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 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 --- AGENTS.md | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/AGENTS.md b/AGENTS.md index a29af6ff..c1d27e3c 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -158,6 +158,16 @@ analytics read path. The durable fix for the mirroring is a server-side `civitai app validate` endpoint that calls the real `BlockManifestValidator` — until that exists, vendoring is on purpose. +**Maintaining this list:** items are append-only and numbered by arrival — a PR +adding items takes the next free numbers, and when two PRs collide the one +merging **second** renumbers **its own** new items. Never renumber an existing +item: other items, the Layout section, and code comments all cross-reference +them by number. After any renumber, re-grep every `item N` / `items N–M` in this +file and confirm each still points at what it means — the range clauses in the +paragraph above are the first thing to break, and both sides of a collision tend +to have edited them differently, so the correct merged sentence is usually +neither one's. + 1. **`civitai app validate` is a best-effort LOCAL mirror, not the authority.** The server-side `BlockManifestValidator` (`civitai/civitai → src/server/services/block-manifest-validator.service.ts`) From ab8d43db3149e62707d406ecbe65c496e7dade73 Mon Sep 17 00:00:00 2001 From: ZacxDev Date: Wed, 5 Aug 2026 19:35:52 -0500 Subject: [PATCH 9/9] docs: two comments claimed more than had been measured MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 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) --- AGENTS.md | 6 ++++-- internal/scaffold/ready_ack_contract_test.go | 17 ++++++++++++----- 2 files changed, 16 insertions(+), 7 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index c1d27e3c..6726ea84 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -161,8 +161,10 @@ until that exists, vendoring is on purpose. **Maintaining this list:** items are append-only and numbered by arrival — a PR adding items takes the next free numbers, and when two PRs collide the one merging **second** renumbers **its own** new items. Never renumber an existing -item: other items, the Layout section, and code comments all cross-reference -them by number. After any renumber, re-grep every `item N` / `items N–M` in this +item: other items, workflow YAML (`.github/workflows/ci.yml`) and Go test +comments cross-reference them by number today, and prose elsewhere in this file +(the Layout section) picks them up as items are added. After any renumber, +re-grep every `item N` / `items N–M` in this file and confirm each still points at what it means — the range clauses in the paragraph above are the first thing to break, and both sides of a collision tend to have edited them differently, so the correct merged sentence is usually diff --git a/internal/scaffold/ready_ack_contract_test.go b/internal/scaffold/ready_ack_contract_test.go index 6d3d9f54..6219c44c 100644 --- a/internal/scaffold/ready_ack_contract_test.go +++ b/internal/scaffold/ready_ack_contract_test.go @@ -643,11 +643,18 @@ func resolveProjectRef(projectDir, fromDir, spec string) (string, bool) { // path and is accepted — measured. This half is load-bearing and pinned by // the "protocol-relative URL that cleans back" corpus case. // - // There is deliberately no `strings.Contains(spec, "://")` companion: an - // `https://…` specifier already fails the switch below and returns the - // identical `("", false)`, so that half decided nothing for any input. It - // was removed rather than left as a branch no mutation can reach — the - // CDN-URL corpus case is rejected by the fallthrough, and says so. + // There is deliberately no `strings.Contains(spec, "://")` companion: no URI + // scheme can begin with `/`, `./` or `../`, so an `https://…` specifier + // already fails the switch below and returns the identical `("", false)` — + // it decided nothing for any URL, which is all it claimed to guard. It was + // removed rather than left as a branch no mutation can reach; the CDN-URL + // corpus case is rejected by the fallthrough, and says so. + // + // It did change the answer for a handful of NON-URLs that merely contain + // `://` — `/x://../civitai-host.js`, `./civitai-host.js?u=https://evil.com` + // — which it rejected and which now resolve to the emitter. That is the + // correct outcome (it is how a browser resolves them), so the removal fixes + // a latent false rejection rather than widening what is accepted. if strings.HasPrefix(spec, "//") { return "", false }