From a2ebb1b69f57077cb13f8688d055e2ff89a0dcdf Mon Sep 17 00:00:00 2001 From: ZacxDev Date: Wed, 5 Aug 2026 20:04:06 -0500 Subject: [PATCH 1/6] feat(validate): tell existing page apps they never post BLOCK_READY (#206) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 4018e2c fixed the `static` and `page-vite` templates, which declared a `page` surface and never acked the host. Every app scaffolded before that commit is still broken and nothing tells its author: it renders perfectly everywhere you can look locally and is replaced by a failure card in the real host after ~37s. This closes that gap in two tiers, deliberately different in strength. 1. `internal/antipattern` gains `resize-iframe-page`. `hostHandlerParity.ts` marks RESIZE_IFRAME N/A for PageBlockHost, so a page app posting it is dead code — and both raw templates demoed it until #206. This is a GATE (it fails scaffold-currency) because it fires on a literal that is present in the file, with no inference. It matches only the '/"-quoted form, never the backtick one: this repo's README and both scaffold READMEs name RESIZE_IFRAME in markdown backticks precisely to say don't post it, and failing the documentation of a rule is a false positive. 2. `civitai app validate` gains a page-without-ack advisory. Unlike the lockfile rule next door — where the platform build provably dies — this infers runtime behaviour from static text and can be wrong, so it is a WARNING and must stay one; --strict already gives anyone who wants a gate one. The dependency is evidence and is checked FIRST: on @civitai/blocks-react the ack comes from IframeTransport and the literal never appears in src/ (measured: zero occurrences in a rendered page-money outside node_modules), so a source-only scan would false-warn at every correct money-path app. It reads source only — never outputDir, node_modules, or markdown — and strips comments, which is load-bearing: both SDK-free templates carry a comment naming BLOCK_READY that survives deleting civitai-host.js. Reading zero source files reports "no finding", because a zero-hit scan over a zero-file tree is indistinguishable from a scanner wired to nothing. It sits in the projectState branch beside lockfileChecks, not in warningChecks, which also runs under ManifestOnly where `app init` self-checks its own template. Measured on a scaffold reconstructed from the templates at 4018e2c^: validate warns and the antipattern gate flags app.js:18. On today's three scaffolds both are silent; deleting civitai-host.js from a fresh static or page-vite scaffold makes the warning fire. Neither check proves the ack FIRES — only the real host can. --- AGENTS.md | 70 ++- README.md | 28 +- internal/antipattern/antipattern.go | 36 ++ internal/antipattern/antipattern_test.go | 57 +++ .../testdata/resize-iframe-doc/README.md | 7 + .../resize-iframe-doc/civitai-host.js | 11 + .../testdata/resize-iframe/src/App.jsx | 22 + internal/cmd/app_validate.go | 13 +- internal/validate/readyack.go | 322 +++++++++++++ internal/validate/readyack_test.go | 455 ++++++++++++++++++ internal/validate/validate.go | 8 + 11 files changed, 1024 insertions(+), 5 deletions(-) create mode 100644 internal/antipattern/testdata/resize-iframe-doc/README.md create mode 100644 internal/antipattern/testdata/resize-iframe-doc/civitai-host.js create mode 100644 internal/antipattern/testdata/resize-iframe/src/App.jsx create mode 100644 internal/validate/readyack.go create mode 100644 internal/validate/readyack_test.go diff --git a/AGENTS.md b/AGENTS.md index 6726ea84..79ea911b 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -154,7 +154,9 @@ func newWhoAmICmd() *cobra.Command { Items 1–3, 10 and 11 are deliberate mirrors of the platform (items 4 and 8 are deliberate *non*-mirrors); items 5–9 cover `civitai app metrics`, the CLI's only -analytics read path. The durable fix for the mirroring is a server-side +analytics read path; item 12 covers the two checks that tell an author their +EXISTING app is missing the item-11 handshake. 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. @@ -502,6 +504,72 @@ neither one's. no correctness gain. If you reconsider, note the init-fragment fast path ships gated off and refuses `surface === 'dev-tunnel'` by construction. +12. **The ready-ack checks for EXISTING apps are two deliberately different + tiers, and neither is allowed to be a hard failure.** #206 fixed the + templates; every app scaffolded before `4018e2c` is still broken and nothing + told its author. These close that gap, and the tier split is the whole + design: + - **`internal/antipattern`'s `resize-iframe-page` rule is a GATE** (it fails + the scaffold-currency job), because it fires on a *literal that is present + in the file* — no inference. It is the first non-REST entry in that + denylist: the package's original doctrine was "dead REST route behind a + host bridge", and this is a dead host MESSAGE, marked N/A for + `PageBlockHost` by `hostHandlerParity.ts`. It matches only a `'`/`"`-quoted + literal, deliberately NOT the backtick form, because this repo's README, + both scaffold READMEs and item 11 all name `RESIZE_IFRAME` in markdown + backticks precisely to tell authors not to post it — a gate that fails the + documentation of its own rule is a false positive. It also assumes a page + surface rather than reading a manifest: `Rule` is a per-line regex with no + manifest context, and every template this CLI ships declares `page`. A + non-page template would need that assumption revisited, not the rule + deleted. + - 🔴 **`validate`'s page-without-ack check is a WARNING and must stay one** + (`internal/validate/readyack.go`). It is the mirror image of item 3's + reasoning: `lockfile.go` earns hard-error status because the platform + *provably* fails (`npm ci` dies), whereas this infers RUNTIME behaviour + from STATIC TEXT and there are correct projects it cannot read — an ack + from a bundled dependency, a framework wrapper, a code-split chunk, an + extension the scan does not open. Hard-failing on a heuristic is the + false-warning-at-a-correct-project failure item 10 spent four measured + corrections avoiding, and `--strict` already lets anyone who wants a gate + have one. + - **The dependency is evidence, and it is checked FIRST.** For a project on + `@civitai/blocks-react` the ack comes from `IframeTransport` and the + literal `BLOCK_READY` NEVER appears in `src/` — measured on a rendered + `page-money` (zero occurrences outside `node_modules`). A source-only scan + therefore warns at every correct money-path app, which is the worst + outcome for advisory output. `sdkDependency` mirrors `civitaiSDKDeps` in + `ready_ack_contract_test.go` on purpose: the two answer the same question, + and disagreeing would mean the CLI warns at a shape its own scaffold guard + calls correct. `TestSDKTemplateIsQuietOnlyBecauseOfTheDependency` pins that + the dep gate is the ONLY reason page-money is accepted. + - **Comments are stripped, and that is load-bearing rather than tidy.** Both + SDK-free templates carry a source comment reading "The ONE message a page + app must send is `BLOCK_READY`", and it SURVIVES deleting + `civitai-host.js` — so without the strip the check is inert on the exact + population it was written for. Measured both ways. `.md` is excluded from + the scan for the same reason: a README describing the handshake is not an + implementation of it. + - 🔴 **Reading NOTHING is not finding nothing.** `emitsReadyAck` reports "no + finding" when it opened ZERO source files — a zero-hit scan over a + zero-file tree is indistinguishable from a scanner wired to nothing (a + broken extension table, an over-eager skip list, or `validate` pointed at a + directory holding a manifest and no checkout, which is the shape of every + manifest-only fixture in that package). This is not defensive padding: it + is what a manifest-only fixture in `warnings_test.go` failed on, and + removing it re-breaks that test. + - **Placement is a real constraint, not style.** `warningChecks` runs + unconditionally *including under `ManifestOnly`*, which `app init` uses to + self-check the template it just wrote. A check that reads `src/` must live + in the `projectState` branch beside `lockfileChecks`, or init's + self-validation starts reading files that are not its business. + `TestReadyAckSkippedByManifestOnly` pins it, with a `Dir()` positive + control so a green there cannot mean "the check never fires at all". + - **What it does NOT prove:** that the ack fires. Only that the message is + mentioned in code. The runtime proof is Guard B (item 11), and there is + none at all for an app the author already has — which is why this is + advisory and says so in its own message. + **When you change a validation rule, keep both vendored mirrors (`schema/` + the ported Go checks in `internal/validate/`, including the slot registry) in sync with the server, and update `examples_test.go` (asserts shipped examples diff --git a/README.md b/README.md index b467e577..23a7acd9 100644 --- a/README.md +++ b/README.md @@ -282,7 +282,9 @@ Two rules it encodes, which apply to every message you add afterwards: page block full-viewport, so it does not size to content and ignores the message. (`useBlockResize` is surface-agnostic and page-money still calls it — on a page surface it is simply a no-op, which is why the SDK templates can share -component code across surfaces.) +component code across surfaces.) A **raw** `postMessage` of `RESIZE_IFRAME` is +flagged by the scaffold-currency gate as dead code — the pre-#206 templates +demoed it, so a project scaffolded before that fix still carries it. ### Local dev loop (harness: mock vs live) @@ -620,6 +622,30 @@ mismatch or a missing lockfile is a hard `validate` error; an *extra* unused lockfile is a warning. Apps with no `package.json` are static — the platform never installs for them and they are never flagged. +Finally it emits one **advisory** about the +[host handshake](#the-host-handshake-block_ready): if your manifest declares a +`page` surface and **nothing in your source posts `BLOCK_READY`**, `validate` +says so. That is the shape of an app scaffolded before the templates were fixed +(#206) — it renders perfectly everywhere you can look locally and is replaced by +a failure card in the real host. It is a **warning, never an error**: unlike the +lockfile rule (where the platform build provably dies), this one infers +*runtime* behaviour from *static text* and can be wrong, so it must not fail a +correct project. Two things follow: + +- **An `@civitai/*` dependency ends the check.** `@civitai/blocks-react`'s + transport acks internally and the literal never appears in your `src/`, so a + `page-money` app is never flagged. +- **It reads source only** — never `outputDir` (not built yet, and gitignored), + never `node_modules`, and never a `.md` file: a README *describing* the + handshake is not an implementation of it. Comments are stripped too, so a + comment naming `BLOCK_READY` does not satisfy it. + +If it fires on a project you know is correct — your ack arrives from a bundled +dependency, or from a file type this scan doesn't open — it is a false alarm, and +it never blocks (exit 0) unless you pass `--strict`. What it proves is narrow: +that the message is *mentioned* in code. It cannot prove the ack ever **fires**; +only the real host can. + The **durable fix** is a server-side `civitai app validate` endpoint that calls the real `BlockManifestValidator` (the faithful contract), with this schema published as the syntactic half. See [`AGENTS.md`](AGENTS.md) for the full diff --git a/internal/antipattern/antipattern.go b/internal/antipattern/antipattern.go index 58d476fc..e549d1c0 100644 --- a/internal/antipattern/antipattern.go +++ b/internal/antipattern/antipattern.go @@ -38,6 +38,12 @@ // Flagging any of those would false-fail a correct scaffold, so they are // deliberately absent from the denylist. We only flag routes that are REMOVED or // whose bridge has fully superseded the REST shape (buzz, shared-storage). +// +// A SECOND FAMILY: DEAD HOST MESSAGES. The denylist is not only about REST. The +// same "compiles, installs, ships an app that is broken or inert" failure has a +// postMessage shape: a block -> host message type the page host does not handle. +// `RESIZE_IFRAME` is the first of those (see the rule below) — the raw page +// templates demoed it until #206, and on a `page` surface the host marks it N/A. package antipattern import ( @@ -105,6 +111,36 @@ func Rules() []Rule { Pattern: regexp.MustCompile("@civitai/blocks-cli(?:[@/'\"\\x60\\s),;]|$)"), Replacement: "use the Go civitai CLI (`civitai app `); the @civitai/blocks-cli npm package is deprecated", }, + { + // DEAD MESSAGE (not a route). `hostHandlerParity.ts` marks + // RESIZE_IFRAME **N/A for PageBlockHost** — "a page block fills the + // surface and does NOT size to content" — so a page app that posts it + // is posting into a handler that does not exist. It is inert rather + // than broken, which is exactly why it survives every local check and + // teaches the next message the author writes to look like this one. + // Both raw page templates demoed it until #206 removed them; anything + // scaffolded before that still carries it. + // + // SCOPE (read before widening): this package scans SCAFFOLDED APP + // TREES, and every template this CLI ships declares a `page` surface + // (scaffold.Template.ReadyAckPath's doc, and the manifest evidence in + // ready_ack_contract_test.go). The rule therefore assumes a page + // surface rather than reading the manifest — Rule is a per-line regex + // with no manifest context by construction. If a non-page (model-slot) + // template ever ships, this rule needs manifest awareness, because + // RESIZE_IFRAME is honoured on the surfaces that DO size to content. + // + // The pattern requires a MATCHING ' or " pair, deliberately excluding + // the backtick form. Prose discusses this message by name in markdown + // backticks — our own scaffold READMEs will say "don't post + // RESIZE_IFRAME" — and flagging the doc that tells an author not to + // use it is a false positive at a correct project. A JS template + // literal for a constant message type is the (vanishingly rare) cost. + ID: "resize-iframe-page", + What: "postMessage of RESIZE_IFRAME, which the page host does not handle", + Pattern: regexp.MustCompile(`'RESIZE_IFRAME'|"RESIZE_IFRAME"`), + Replacement: "delete it — hostHandlerParity.ts marks RESIZE_IFRAME N/A for PageBlockHost (a page block fills the host surface and does NOT size to content), so the message is dead code. The one message a page app must send is BLOCK_READY: keep the vendored civitai-host.js emitter `civitai app init` ships, or adopt @civitai/blocks-react (whose transport acks internally) — never both", + }, } } diff --git a/internal/antipattern/antipattern_test.go b/internal/antipattern/antipattern_test.go index 6725dade..9da17253 100644 --- a/internal/antipattern/antipattern_test.go +++ b/internal/antipattern/antipattern_test.go @@ -53,6 +53,22 @@ func TestScanDir(t *testing.T) { wantFile: "README.md", wantInMsg: "civitai app", }, + { + // The pre-#206 page template shape: an app that sizes itself to + // content on a surface that does not size to content. + name: "RESIZE_IFRAME posted from a page app fails", + dir: "resize-iframe", + wantRule: "resize-iframe-page", + wantFile: "App.jsx", + wantInMsg: "BLOCK_READY", + }, + { + // The false-positive direction, which matters more: docs that TELL an + // author not to post RESIZE_IFRAME must not be flagged for saying so, + // and neither must an app whose only host message is the ready ack. + name: "docs naming RESIZE_IFRAME in backticks are not flagged", + dir: "resize-iframe-doc", + }, } for _, tt := range tests { @@ -159,6 +175,47 @@ func TestBlocksCliBoundary(t *testing.T) { } } +// TestResizeIframeBoundary is the resize-iframe-page rule's control pair. The +// rule exists to catch a DEAD HOST MESSAGE, and the population it must never +// touch is prose: this repo's own README and both scaffold READMEs discuss +// `RESIZE_IFRAME` by name precisely to tell authors not to post it, and a gate +// that fails the documentation of its own rule is a false positive at a correct +// project. +func TestResizeIframeBoundary(t *testing.T) { + var rule Rule + for _, r := range Rules() { + if r.ID == "resize-iframe-page" { + rule = r + } + } + if rule.Pattern == nil { + t.Fatal("resize-iframe-page rule not found") + } + + cases := []struct { + line string + want bool + }{ + // The real emitting shapes, single- and double-quoted. + {`window.parent.postMessage({ type: 'RESIZE_IFRAME', height: h }, '*');`, true}, + {`window.parent.postMessage({ type: "RESIZE_IFRAME", height: h }, "*");`, true}, + {`if (msg.type === 'RESIZE_IFRAME') return;`, true}, + {`const RESIZE = 'RESIZE_IFRAME';`, true}, + // Prose — the direction that must stay silent. + {"`RESIZE_IFRAME` is **not** part of a page app's protocol.", false}, + {"Do not post RESIZE_IFRAME from a page app.", false}, + {`// RESIZE_IFRAME is N/A for PageBlockHost — do not send it.`, false}, + // Neighbouring identifiers must not be dragged in. + {`useBlockResize();`, false}, + {`"description": "Whether the host honours RESIZE_IFRAME messages."`, false}, + } + for _, c := range cases { + if got := rule.Pattern.MatchString(c.line); got != c.want { + t.Errorf("match(%q) = %v, want %v (pattern %s)", c.line, got, c.want, rule.Pattern) + } + } +} + // TestScanDirFromEnv is the CI entrypoint. The scaffold-currency job scaffolds a // template to disk, sets CIVITAI_ANTIPATTERN_SCAN_DIR to it, and runs this test; // any finding fails the job. It SKIPS when the env var is unset so the default diff --git a/internal/antipattern/testdata/resize-iframe-doc/README.md b/internal/antipattern/testdata/resize-iframe-doc/README.md new file mode 100644 index 00000000..5c85942a --- /dev/null +++ b/internal/antipattern/testdata/resize-iframe-doc/README.md @@ -0,0 +1,7 @@ +# Sample Block + +`RESIZE_IFRAME` is **not** part of a page app's protocol: the host renders a +page block full-viewport, so it does not size to content and ignores the +message. Do not post RESIZE_IFRAME from a page app. + +The one message a page app must send is `BLOCK_READY`. diff --git a/internal/antipattern/testdata/resize-iframe-doc/civitai-host.js b/internal/antipattern/testdata/resize-iframe-doc/civitai-host.js new file mode 100644 index 00000000..8c65396e --- /dev/null +++ b/internal/antipattern/testdata/resize-iframe-doc/civitai-host.js @@ -0,0 +1,11 @@ +// The ready-ack emitter. It answers BLOCK_INIT with BLOCK_READY and never +// posts RESIZE_IFRAME. +window.addEventListener('message', function (event) { + if (event.source !== window.parent) return; + var data = event.data; + if (!data || data.type !== 'BLOCK_INIT') return; + window.parent.postMessage( + { type: 'BLOCK_READY', payload: { height: 0 } }, + event.origin + ); +}); diff --git a/internal/antipattern/testdata/resize-iframe/src/App.jsx b/internal/antipattern/testdata/resize-iframe/src/App.jsx new file mode 100644 index 00000000..89b1987f --- /dev/null +++ b/internal/antipattern/testdata/resize-iframe/src/App.jsx @@ -0,0 +1,22 @@ +import { useEffect, useState } from 'react'; + +// A page app that sizes itself to content. This is the shape the `page-vite` +// template shipped before #206: the host renders a page block full-viewport and +// marks RESIZE_IFRAME N/A, so this effect runs forever into nothing. +export default function App() { + const [count, setCount] = useState(0); + + useEffect(() => { + function reportHeight() { + window.parent.postMessage( + { type: 'RESIZE_IFRAME', height: document.documentElement.scrollHeight }, + '*' + ); + } + reportHeight(); + window.addEventListener('resize', reportHeight); + return () => window.removeEventListener('resize', reportHeight); + }); + + return
count is {count}
; +} diff --git a/internal/cmd/app_validate.go b/internal/cmd/app_validate.go index 4f0f7960..1f22767d 100644 --- a/internal/cmd/app_validate.go +++ b/internal/cmd/app_validate.go @@ -42,9 +42,16 @@ plus the ported semantic rules and structural checks: lockfile is a guaranteed build failure. Only applies when package.json exists — a static app never installs. -It also emits non-fatal WARNINGS for money-path footguns the schema can't catch -as hard errors (e.g. a budgeted page with no page.buzzBudgetPerGen). Warnings do -NOT fail validation (exit 0) unless --strict is passed. +It also emits non-fatal WARNINGS the schema can't catch as hard errors: + - money-path footguns (e.g. a budgeted page with no page.buzzBudgetPerGen) + - a "page" app whose source never posts BLOCK_READY. The host will not reveal + a page app until it acks BLOCK_INIT, so such an app renders fine locally and + is replaced by a failure card in the real host — the shape of anything + scaffolded before that was fixed. Advisory ONLY: it infers runtime behaviour + from static text. A project depending on @civitai/* is never flagged (the + SDK transport acks internally), and it reads source only — never outputDir, + node_modules, markdown, or comments. +Warnings do NOT fail validation (exit 0) unless --strict is passed. Defaults to the current directory.`, Example: ` civitai app validate # the current directory diff --git a/internal/validate/readyack.go b/internal/validate/readyack.go new file mode 100644 index 00000000..2186ddd1 --- /dev/null +++ b/internal/validate/readyack.go @@ -0,0 +1,322 @@ +package validate + +// readyack.go implements the PAGE-APP READY-ACK advisory. +// +// WHY THIS EXISTS. A `page` app is not revealed by the host until it posts +// `BLOCK_READY` — that handler in `PageBlockHost.tsx` is the only transition +// into the host's `ready` state. An app that never posts it renders perfectly +// everywhere you can look locally and is replaced by a visible failure card in +// the real host once the bounded init retries run out (~37s). That is issue +// #206, and `4018e2c` fixed the `static` and `page-vite` TEMPLATES — but every +// app scaffolded before that commit is still broken, and nothing tells its +// author. This check is the thing that tells them. +// +// 🔴 IT IS A WARNING, NOT AN ERROR, AND THAT IS DELIBERATE. +// The lockfile check next door (lockfile.go) earns hard-error status because the +// platform PROVABLY fails: the build recipe runs `npm ci` and dies. Nothing here +// is provable. This check infers RUNTIME behaviour from STATIC TEXT, and there +// are real, correct projects it cannot read: an ack that arrives through a +// bundled dependency, a framework wrapper, a code-split chunk, a generated file, +// or simply a file extension this scan does not open. Hard-failing on a +// heuristic is the exact false-warning-at-a-correct-project failure the +// dev-tunnel preflight (AGENTS.md item 10) spent four measured corrections +// avoiding — and unlike that one, `--strict` here would turn it into a build +// break in somebody's CI. `Result.Warnings` costs an author nothing to ignore +// and still puts the sentence in front of them. +// +// EVIDENCE ORDER — THE DEPENDENCY IS CHECKED FIRST, AND THAT IS LOAD-BEARING. +// For a project depending on `@civitai/blocks-react`, the ack comes from the +// SDK's `IframeTransport` and the literal `BLOCK_READY` NEVER APPEARS in `src/`. +// A source scan alone therefore warns at every correct page-money app on the +// platform, which is the worst possible outcome for advisory output: it teaches +// authors that this warning is noise. So package.json is read first and an +// `@civitai/*` dependency ENDS the check. +// +// WHAT IT DOES NOT PROVE. That the ack FIRES. No static check can — an emitter +// with an inverted `event.source` guard satisfies every assertion here (that is +// what the scaffold's Guard B exists for, see AGENTS.md item 11). This check +// answers one narrower question: does anything in this project's source so much +// as MENTION the message, outside a comment. A "no" is strong evidence of the +// #206 shape; a "yes" is weak evidence of correctness, and is treated as +// conclusive anyway, because being generous here costs a missed warning while +// being strict costs a false one. +// +// SCOPE — IT ONLY FIRES WHERE IT CAN OBSERVE. Mirroring lockfile.go's early-out +// shape: no `page` surface, no check. Unreadable package.json, no check. +// Unwalkable tree, no check. And it reads SOURCE only — never `outputDir`, +// which does not exist before the first build and is gitignored, so its absence +// says nothing. A check that cannot observe returns NO findings rather than +// manufacturing advice. + +import ( + "encoding/json" + "io/fs" + "os" + "path/filepath" + "strings" + + "github.com/civitai/cli/internal/blockproto" + "github.com/civitai/cli/internal/manifest" +) + +// readyAckType is the message the page host waits for. It is the same literal +// blockproto's emitter posts; the emitter is the authority for the SHAPE, this +// is only the token we look for. +const readyAckType = "BLOCK_READY" + +// civitaiDepPrefix marks a first-party package. Any of them is taken as +// evidence that a real transport is in play — `@civitai/blocks-react` is the +// one that acks today, but a project pulling `@civitai/app-sdk` is on the SDK +// path too, and a false negative is the cheap direction. +// +// This deliberately mirrors `civitaiSDKDeps` in +// internal/scaffold/ready_ack_contract_test.go, which decides the same question +// for the templates. Keep them agreeing: they answer "does this project's ack +// come from the SDK", and disagreeing would mean the CLI warns at a shape its +// own scaffold guard considers correct. +const civitaiDepPrefix = "@civitai/" + +// readyAckSourceExts are the extensions a hand-written emitter can live in. +// Deliberately CODE ONLY — `.md` is excluded because a README that explains the +// handshake is not an implementation of it, and both shipped scaffold READMEs +// describe `BLOCK_READY` at length. Including docs would silence the check for +// exactly the apps it exists to find. +var readyAckSourceExts = map[string]bool{ + ".js": true, ".jsx": true, ".mjs": true, ".cjs": true, + ".ts": true, ".tsx": true, ".mts": true, ".cts": true, + ".html": true, ".htm": true, + ".vue": true, ".svelte": true, ".astro": true, +} + +// readyAckSkipDirs are never descended into: dependencies, VCS metadata, and +// build output. The manifest's own outputDir is skipped on top of these. +var readyAckSkipDirs = map[string]bool{ + "node_modules": true, ".git": true, "dist": true, "build": true, + "out": true, "coverage": true, ".vite": true, ".next": true, + ".svelte-kit": true, ".output": true, +} + +// readyAckChecks returns the ready-ack advisory for the project in dir, or nil. +// +// It runs in the projectState branch of validateDir (beside lockfileChecks) and +// NOT in warningChecks: warningChecks is reached under ManifestOnly, which +// `civitai app init` uses to self-check the template it just wrote, and a check +// that reads `src/` has no business running there. +func readyAckChecks(dir string, generic any, m *manifest.Manifest) []string { + if !declaresPage(generic) { + return nil + } + // The dependency is checked FIRST — see the file header. `unknown` means the + // package.json is there but unreadable, i.e. we cannot answer the question + // that decides whether a source scan is even meaningful. + switch sdkDependency(dir) { + case sdkPresent, sdkUnknown: + return nil + } + if emitsReadyAck(dir, m.OutputDir) { + return nil + } + return []string{readyAckAdvice} +} + +// declaresPage reports whether the manifest declares a non-null `page` surface. +// `"page": null` is not a page app; an absent key is not either. +func declaresPage(generic any) bool { + m, ok := generic.(map[string]any) + if !ok { + return false + } + v, present := m["page"] + return present && v != nil +} + +// sdkState is the three-valued answer to "does this project depend on a +// first-party package". The third value is the point: "we could not tell" must +// not be collapsed into "no", which is what would warn at a project whose +// package.json this CLI simply failed to parse. +type sdkState int + +const ( + sdkAbsent sdkState = iota + sdkPresent + sdkUnknown +) + +func sdkDependency(dir string) sdkState { + raw, err := os.ReadFile(filepath.Join(dir, "package.json")) + if err != nil { + if os.IsNotExist(err) { + // No package.json at all: a static, no-build app. It installs + // nothing, so it cannot be acking through a dependency — the source + // scan is the whole answer for it. + return sdkAbsent + } + return sdkUnknown + } + // json.RawMessage values, not strings: a package.json with an unusual + // (non-string) version entry must not make the whole decode fail and warn. + var pkg struct { + Dependencies map[string]json.RawMessage `json:"dependencies"` + DevDependencies map[string]json.RawMessage `json:"devDependencies"` + PeerDependencies map[string]json.RawMessage `json:"peerDependencies"` + } + if err := json.Unmarshal(raw, &pkg); err != nil { + return sdkUnknown + } + for _, set := range []map[string]json.RawMessage{pkg.Dependencies, pkg.DevDependencies, pkg.PeerDependencies} { + for name := range set { + if strings.HasPrefix(name, civitaiDepPrefix) { + return sdkPresent + } + } + } + return sdkAbsent +} + +// emitsReadyAck reports whether any source file under dir mentions the ready-ack +// message OUTSIDE a comment. +// +// 🔴 READING NOTHING IS NOT THE SAME AS FINDING NOTHING, and this returns TRUE +// (no finding) when it opened ZERO source files. That is this check's own +// positive control, inlined: a zero-hit scan over a zero-file tree is +// indistinguishable from a scanner wired to nothing — a broken extension table, +// an over-eager skip list, or `validate` pointed at a directory that holds a +// manifest and no checkout (which is exactly the shape of every manifest-only +// fixture in this package). Concluding "this app never acks" from a scan that +// never read a line is manufacturing advice from an absence. +// +// 🔴 The comment strip is load-bearing, not tidiness. Both shipped SDK-free +// templates carry a source COMMENT naming `BLOCK_READY` +// (`static/app.js`, `page-vite/src/App.jsx`: "The ONE message a page app must +// send is `BLOCK_READY`"), and those comments SURVIVE deleting `civitai-host.js`. +// Without stripping, the exact repair this check exists to demand — restore the +// emitter — would already look satisfied, and the check would be inert on the +// one population it was written for. Measured: with the strip, deleting +// civitai-host.js from a freshly scaffolded static app makes the warning fire; +// without it, it does not. +// +// An unwalkable/unreadable tree reports TRUE (i.e. "no finding"): we could not +// observe, so we say nothing. +func emitsReadyAck(dir, outputDir string) bool { + skipOut := "" + if out := strings.TrimSpace(outputDir); out != "" { + skipOut = filepath.Clean(filepath.Join(dir, filepath.FromSlash(out))) + } + + found := false + scanned := 0 + err := filepath.WalkDir(dir, func(path string, d fs.DirEntry, err error) error { + if err != nil { + return err + } + if d.IsDir() { + if readyAckSkipDirs[d.Name()] || (skipOut != "" && filepath.Clean(path) == skipOut) { + return fs.SkipDir + } + return nil + } + if !readyAckSourceExts[strings.ToLower(filepath.Ext(d.Name()))] { + return nil + } + data, readErr := os.ReadFile(path) + if readErr != nil { + return readErr + } + scanned++ + if strings.Contains(stripComments(string(data)), readyAckType) { + found = true + return fs.SkipAll + } + return nil + }) + if err != nil { + // Could not observe the tree — do not manufacture advice. + return true + } + if scanned == 0 { + return true + } + return found +} + +// stripComments removes HTML comments and then JS line/block comments, leaving +// string and template literals intact (so `'https://x'` is not read as the start +// of a comment, and an emitter that posts from inside a string still counts). +func stripComments(src string) string { + return stripJSComments(stripHTMLComments(src)) +} + +func stripHTMLComments(src string) string { + var b strings.Builder + b.Grow(len(src)) + for i := 0; i < len(src); { + if strings.HasPrefix(src[i:], "") + if end < 0 { + return b.String() + } + i += 4 + end + 3 + continue + } + b.WriteByte(src[i]) + i++ + } + return b.String() +} + +func stripJSComments(src string) string { + var b strings.Builder + b.Grow(len(src)) + for i := 0; i < len(src); { + c := src[i] + switch { + case c == '/' && i+1 < len(src) && src[i+1] == '/': + for i < len(src) && src[i] != '\n' { + i++ + } + case c == '/' && i+1 < len(src) && src[i+1] == '*': + i += 2 + for i+1 < len(src) && !(src[i] == '*' && src[i+1] == '/') { + i++ + } + i = min(i+2, len(src)) + case c == '\'' || c == '"' || c == '`': + quote := c + b.WriteByte(c) + i++ + for i < len(src) { + if src[i] == '\\' && i+1 < len(src) { + b.WriteString(src[i : i+2]) + i += 2 + continue + } + b.WriteByte(src[i]) + if src[i] == quote { + i++ + break + } + i++ + } + default: + b.WriteByte(c) + i++ + } + } + return b.String() +} + +// readyAckAdvice names the concrete next command, per the house rule that a +// message must tell the author what to run. It also states its own evidentiary +// limit — an author who knows their ack comes from a bundled dependency needs to +// be able to recognise this as a false alarm without reading the source of the +// CLI. +var readyAckAdvice = "the manifest declares a \"page\" surface but nothing in this project's source posts " + + readyAckType + " — the host will not reveal a page app until it acks the host's BLOCK_INIT, so an app " + + "that never sends it renders fine locally and is replaced by a failure card in the real host once the " + + "bounded init retries run out (issue #206). Apps scaffolded before that fix ship no emitter: run " + + "`civitai app init` into a scratch directory and copy its `" + blockproto.ReadyAckFilename + "` " + + "into this project, loading it from index.html (a `, + "app.js": `document.title = 'hi';`, + }, + wantWarn: true, + why: "this is exactly the #206 shape the check exists to find", + }, + { + name: "page app shipping the real emitter does not warn", + manifest: ackManifest(false), + files: map[string]string{ + "index.html": ``, + "civitai-host.js": realEmitter(), + "unrelated.txt": "BLOCK_READY", + "src/component.js": `export const x = 1;`, + }, + wantWarn: false, + }, + { + // 🔴 THE REGRESSION THAT WOULD HURT MOST. The SDK's IframeTransport + // acks internally and the literal never appears in src/, so a + // source-only check warns at EVERY correct page-money app. + name: "page app depending on @civitai/blocks-react does not warn", + manifest: ackManifest(true), + files: map[string]string{ + "package.json": `{"dependencies": {"react": "^19.0.0", "@civitai/blocks-react": "^0.39.0"}}`, + "index.html": ``, + "src/main.tsx": `import { BlockProvider } from '@civitai/blocks-react';`, + }, + wantWarn: false, + }, + { + name: "the SDK dep counts from devDependencies too", + manifest: ackManifest(true), + files: map[string]string{ + "package.json": `{"devDependencies": {"@civitai/app-sdk": "^0.31.0"}}`, + "src/main.ts": `export const x = 1;`, + }, + wantWarn: false, + }, + { + // The dep gate must be about @civitai/*, not about "has a + // package.json". Without this, adding any dependency would silence + // the check. + name: "a package.json with no @civitai dep still warns", + manifest: ackManifest(true), + files: map[string]string{ + "package.json": `{"dependencies": {"react": "^19.0.0", "react-dom": "^19.0.0"}}`, + "index.html": ``, + "src/main.jsx": `import App from './App';`, + }, + wantWarn: true, + }, + { + name: "a non-page app never warns", + manifest: nonPageManifest, + files: map[string]string{ + "index.html": ``, + "app.js": `document.title = 'hi';`, + }, + wantWarn: false, + why: "the ready contract pinned here is the PAGE host's", + }, + { + // 🔴 The comment strip. Both shipped SDK-free templates carry this + // exact sentence in a source comment, and it SURVIVES deleting the + // emitter — so without stripping, the check is inert on the very + // apps it was written for. + name: "an ack named only in a comment warns", + manifest: ackManifest(false), + files: map[string]string{ + "index.html": ``, + "app.js": "// The ONE message a page app must send is `BLOCK_READY`; without it the host\n" + + "// shows a failure card.\ndocument.title = 'hi';\n", + }, + wantWarn: true, + }, + { + name: "an ack named only in an HTML comment warns", + manifest: ackManifest(false), + files: map[string]string{ + "index.html": "\n\n", + "app.js": `document.title = 'hi';`, + }, + wantWarn: true, + }, + { + name: "an ack described only in the README warns", + manifest: ackManifest(false), + files: map[string]string{ + "index.html": ``, + "app.js": `document.title = 'hi';`, + "README.md": "The host waits for a `BLOCK_READY` message before it will show your app.", + }, + wantWarn: true, + why: "docs are not an implementation; both scaffold READMEs describe the handshake", + }, + { + // outputDir is never read: it does not exist before the first build + // and is gitignored, so a hit there says nothing about what is + // submitted... and its ABSENCE must not be read as evidence either. + name: "an ack present only in outputDir warns", + manifest: ackManifest(true), + files: map[string]string{ + "package.json": `{"dependencies": {"react": "^19.0.0"}}`, + "index.html": ``, + "src/main.jsx": `import App from './App';`, + "dist/assets/x.js": `window.parent.postMessage({type:'BLOCK_READY',payload:{}},o)`, + }, + wantWarn: true, + }, + { + name: "an ack in node_modules does not count", + manifest: ackManifest(true), + files: map[string]string{ + "package.json": `{"dependencies": {"react": "^19.0.0"}}`, + "src/main.jsx": `import App from './App';`, + "node_modules/dep/idx.js": `postMessage({type:'BLOCK_READY'})`, + }, + wantWarn: true, + }, + { + name: "an inline ack in index.html does not warn", + manifest: ackManifest(false), + files: map[string]string{ + "index.html": "", + }, + wantWarn: false, + }, + { + name: "an ack in a .vue single-file component does not warn", + manifest: ackManifest(true), + files: map[string]string{ + "package.json": `{"dependencies": {"vue": "^3.5.0"}}`, + "src/App.vue": "", + "package-x.txt": "ignored", + }, + wantWarn: false, + }, + { + // A URL inside a string must not be read as the start of a comment — + // otherwise everything after it is stripped and a real ack below it + // disappears. + name: "a URL literal does not swallow the rest of the file", + manifest: ackManifest(false), + files: map[string]string{ + "index.html": ``, + "app.js": "var docs = 'https://civitai.com/docs';\n" + + "window.parent.postMessage({ type: 'BLOCK_READY', payload: {} }, o);\n", + }, + wantWarn: false, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + wantAckWarning(t, ackProject(t, tt.manifest, tt.files), tt.wantWarn) + if tt.why != "" { + t.Logf("%s — %s", tt.name, tt.why) + } + }) + } +} + +// TestReadyAckCannotObserve pins the early-outs. Each of these is a project the +// check cannot answer for, and "cannot answer" must produce NO finding rather +// than a guess — the false-warning-at-a-correct-project failure AGENTS.md item +// 10 exists to prevent. +func TestReadyAckCannotObserve(t *testing.T) { + t.Run("an unparseable package.json silences the check", func(t *testing.T) { + dir := ackProject(t, ackManifest(true), map[string]string{ + "package.json": `{"dependencies": {`, // truncated + "src/main.jsx": `import App from './App';`, + }) + wantAckWarning(t, dir, false) + }) + + t.Run("a directory holding only a manifest silences the check", func(t *testing.T) { + // Zero source files READ. A zero-hit scan over a zero-file tree says + // nothing about the app — it is the same observation a scanner wired to + // nothing would produce. + dir := ackProject(t, ackManifest(false), nil) + wantAckWarning(t, dir, false) + }) + + t.Run("a tree of only unscanned file types silences the check", func(t *testing.T) { + dir := ackProject(t, ackManifest(false), map[string]string{ + "README.md": "no code here", + "notes.txt": "nor here", + "logo.svg": "", + "styles.css": "body{}", + }) + wantAckWarning(t, dir, false) + }) + + t.Run("one scannable file is enough to conclude", func(t *testing.T) { + // The positive control for the two cases above: as soon as the scanner + // really reads a line of code, a missing ack IS a finding. Without this, + // "scanned == 0 means silence" is indistinguishable from silence always. + dir := ackProject(t, ackManifest(false), map[string]string{ + "README.md": "no code here", + "index.html": `

hi

`, + }) + wantAckWarning(t, dir, true) + }) + + t.Run("an unreadable package.json silences the check", func(t *testing.T) { + dir := ackProject(t, ackManifest(true), map[string]string{ + "src/main.jsx": `import App from './App';`, + }) + // A DIRECTORY where package.json belongs: os.ReadFile fails with + // something that is NOT os.IsNotExist, on every platform and as any + // user (a chmod-based fixture is a no-op for root). + if err := os.Mkdir(filepath.Join(dir, "package.json"), 0o755); err != nil { + t.Fatal(err) + } + wantAckWarning(t, dir, false) + }) +} + +// TestReadyAckIsAdvisoryOnly pins the tier. The check must never reach Errors — +// it infers runtime behaviour from static text, and a hard failure on a +// heuristic breaks correct projects. +func TestReadyAckIsAdvisoryOnly(t *testing.T) { + dir := ackProject(t, ackManifest(false), map[string]string{ + "index.html": ``, + "app.js": `document.title = 'hi';`, + }) + res := wantAckWarning(t, dir, true) + for _, e := range res.Errors { + if e == readyAckAdvice { + t.Fatalf("the ready-ack advisory reached Errors — it must stay a warning") + } + } + if !res.OK() { + t.Fatalf("a page app missing the ack must still VALIDATE (exit 0 without --strict); errors: %v", res.Errors) + } +} + +// TestReadyAckSkippedByManifestOnly pins the PLACEMENT. warningChecks runs +// unconditionally, including under ManifestOnly — which `civitai app init` uses +// to self-check the template it just wrote. A check that reads src/ placed there +// would make init's self-validation depend on files that are not its business. +func TestReadyAckSkippedByManifestOnly(t *testing.T) { + dir := ackProject(t, ackManifest(false), map[string]string{ + "index.html": ``, + "app.js": `document.title = 'hi';`, + }) + + // Positive control: the same directory DOES warn through Dir. Without it, a + // green below is indistinguishable from a check that never fires at all. + wantAckWarning(t, dir, true) + + res, err := ManifestOnly(dir) + if err != nil { + t.Fatalf("ManifestOnly: %v", err) + } + if hasReadyAckWarning(res) { + t.Fatalf("ManifestOnly emitted the ready-ack advisory; it must stay in the projectState branch\nwarnings: %v", res.Warnings) + } +} + +// --------------------------------------------------------------------------- +// The seam guard: the CHECK against the real TEMPLATES. +// --------------------------------------------------------------------------- + +// TestShippedTemplatesDoNotTripTheReadyAckWarning is the guard that matters +// most. Every unit case above builds a synthetic project; this one renders the +// REAL templates and requires the CLI's own check to accept them, so drift on +// EITHER side (a template that stops shipping the emitter, or a check that +// stops recognising it) fails loudly. It mirrors the seam guards in +// internal/scaffold/dev_embed_contract_test.go. +// +// It deliberately ignores validation ERRORS: a freshly rendered page-vite has +// no lockfile yet, which is a legitimate hard error and not this test's subject. +func TestShippedTemplatesDoNotTripTheReadyAckWarning(t *testing.T) { + examined := 0 + for _, tmpl := range scaffold.AllTemplates() { + t.Run(string(tmpl), func(t *testing.T) { + dest := filepath.Join(t.TempDir(), string(tmpl)) + if _, err := scaffold.Render(tmpl, dest, scaffold.Data{Slug: "ack-block", Name: "Ack Block"}); err != nil { + t.Fatalf("render %s: %v", tmpl, err) + } + wantAckWarning(t, dest, false) + }) + examined++ + } + // COUNT POSITIVE CONTROL: a zero here is otherwise indistinguishable from an + // enumeration that returned nothing. + if examined < 3 { + t.Fatalf("examined only %d template(s), expected at least 3 — the enumeration stopped OBSERVING", examined) + } +} + +// TestSDKTemplateIsQuietOnlyBecauseOfTheDependency is the positive control for +// the dep gate. page-money is accepted above; this proves WHY. If its source +// ever did contain the literal, the case above would pass for a reason that has +// nothing to do with the branch it is meant to cover, and deleting the dep gate +// would go unnoticed — which is precisely the regression that false-warns at +// every correct money-path app. +func TestSDKTemplateIsQuietOnlyBecauseOfTheDependency(t *testing.T) { + dest := filepath.Join(t.TempDir(), "page-money") + if _, err := scaffold.Render(scaffold.PageMoney, dest, scaffold.Data{Slug: "ack-block", Name: "Ack Block"}); err != nil { + t.Fatal(err) + } + if emitsReadyAck(dest, "dist") { + t.Fatalf("page-money's SOURCE mentions %s — the dep gate is no longer the reason it is accepted, "+ + "so nothing in this suite covers that branch any more", readyAckType) + } + if got := sdkDependency(dest); got != sdkPresent { + t.Fatalf("sdkDependency(page-money) = %v, want sdkPresent — the rendered package.json must depend on %s*", + got, civitaiDepPrefix) + } + wantAckWarning(t, dest, false) +} + +// TestDeletingTheEmitterMakesTheWarningFire is the NEGATIVE CONTROL for the +// guard above: it takes a correct scaffold, breaks it exactly the way a +// pre-4018e2c app is broken, and requires the warning. Without it, +// "no template warns" is satisfied by a check that never warns about anything. +func TestDeletingTheEmitterMakesTheWarningFire(t *testing.T) { + for _, tmpl := range []scaffold.Template{scaffold.Static, scaffold.PageVite} { + t.Run(string(tmpl), func(t *testing.T) { + dest := filepath.Join(t.TempDir(), string(tmpl)) + if _, err := scaffold.Render(tmpl, dest, scaffold.Data{Slug: "ack-block", Name: "Ack Block"}); err != nil { + t.Fatal(err) + } + wantAckWarning(t, dest, false) + + rel := tmpl.ReadyAckPath() + if rel == "" { + t.Fatalf("%s no longer declares a ReadyAckPath — this control has nothing to delete", tmpl) + } + if err := os.Remove(filepath.Join(dest, filepath.FromSlash(rel))); err != nil { + t.Fatal(err) + } + wantAckWarning(t, dest, true) + + // The advisory must name the file the author has to restore. + if !strings.Contains(readyAckAdvice, blockproto.ReadyAckFilename) { + t.Errorf("the advisory does not name %s — an author cannot act on it", blockproto.ReadyAckFilename) + } + }) + } +} diff --git a/internal/validate/validate.go b/internal/validate/validate.go index d3d516a0..115c4173 100644 --- a/internal/validate/validate.go +++ b/internal/validate/validate.go @@ -145,6 +145,14 @@ func validateDir(dir string, projectState bool) (Result, error) { lockErrs, lockWarns := lockfileChecks(dir, m) res.Errors = append(res.Errors, lockErrs...) res.Warnings = append(res.Warnings, lockWarns...) + + // Project state: a `page` app whose source never posts BLOCK_READY is + // invisible in the real host (issue #206). ADVISORY, not fatal — it + // infers runtime behaviour from static text and can be wrong. It lives + // HERE rather than in warningChecks because it reads src/, and + // warningChecks also runs under ManifestOnly, where `civitai app init` + // self-checks a template it just wrote. See readyack.go. + res.Warnings = append(res.Warnings, readyAckChecks(dir, generic, m)...) } // Non-fatal advisories: real money-path footguns the schema can't catch as From 111804449d6faae9c1bf5120e875abf1b8630e02 Mon Sep 17 00:00:00 2001 From: ZacxDev Date: Wed, 5 Aug 2026 20:27:33 -0500 Subject: [PATCH 2/6] test(validate): close four branches the first mutation sweep left unproven MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A 24-mutant sweep found four guards that no test could distinguish from their absence. Three were real gaps, one was a weak mutant: - `"page": null` — nothing covered it, so declaresPage's `v != nil` half was indistinguishable from a presence-only test. `encoding/json` decodes an explicit null to a PRESENT key holding nil, so the two disagree on exactly one input and no fixture had it. - the comment stripper's string handling — the URL fixture put the URL and the ack on DIFFERENT lines, so deleting the quote case only ate the rest of the URL's own line and the ack below it survived. Same line now. - the outputDir skip — the fixture used `dist`, which is ALSO in the name-based skip list, so an EARLIER check always won and the manifest-driven branch never executed. A non-standard outputDir (`public`) is the only way in; the mutation disabling it survived the entire suite until this case existed. - the walk-error branch — first written off as unreachable by any fixture (chmod is a no-op for root). It is not: a dangling symlink with a scanned extension fails os.ReadFile deterministically for any user. The "expected to survive" was a rationalisation for an untested branch. Re-run: 11/11 attributed kills plus a surviving null mutant, and every mutation verified to have actually changed the tree. --- internal/validate/readyack_test.go | 81 +++++++++++++++++++++++++++--- 1 file changed, 73 insertions(+), 8 deletions(-) diff --git a/internal/validate/readyack_test.go b/internal/validate/readyack_test.go index a22138f8..e9d50f82 100644 --- a/internal/validate/readyack_test.go +++ b/internal/validate/readyack_test.go @@ -17,10 +17,16 @@ import ( // ackManifest is an otherwise-valid PAGE manifest. `build` splices in the // buildCommand + outputDir pair the schema couples, so the outputDir-is-never- // scanned case has a real outputDir to be ignored. -func ackManifest(build bool) string { +func ackManifest(build bool) string { return ackManifestOut(build, "dist") } + +// ackManifestOut is ackManifest with an explicit outputDir. `dist` is ALSO in +// readyAckSkipDirs, so a fixture using it can never reach the outputDir branch — +// the name-based skip always wins first. A non-standard outputDir is the only +// way to exercise that branch, which is why this exists. +func ackManifestOut(build bool, outputDir string) string { extra := "" if build { - extra = `, "buildCommand": "npm run build", "outputDir": "dist"` + extra = `, "buildCommand": "npm run build", "outputDir": "` + outputDir + `"` } return `{ "blockId": "ack-block", "version": "0.1.0", "name": "Ack Block", @@ -37,6 +43,15 @@ const nonPageManifest = `{ "iframe": {"minHeight": 400, "resizable": true, "sandbox": "allow-scripts"} }` +// nullPageManifest sets the key EXPLICITLY to null. `encoding/json` decodes that +// to a present key holding a nil value, so a presence-only test ("is the key +// there") reads it as a page app and a `v != nil` test does not. +const nullPageManifest = `{ + "blockId": "null-page", "version": "0.1.0", "name": "Null Page", + "contentRating": "g", "scopes": [], "page": null, + "iframe": {"minHeight": 400, "resizable": true, "sandbox": "allow-scripts"} +}` + // realEmitter is what a correctly scaffolded SDK-free page app ships. Taken // from blockproto rather than retyped, so this fixture cannot drift away from // the thing the CLI actually writes. @@ -167,6 +182,18 @@ func TestReadyAckWarning(t *testing.T) { wantWarn: false, why: "the ready contract pinned here is the PAGE host's", }, + { + // An explicit null is not a page surface. Pins the `v != nil` half of + // declaresPage: a presence-only test passes every other case in this + // table, so without this the two halves are indistinguishable. + name: `an explicit "page": null does not warn`, + manifest: nullPageManifest, + files: map[string]string{ + "index.html": ``, + "app.js": `document.title = 'hi';`, + }, + wantWarn: false, + }, { // 🔴 The comment strip. Both shipped SDK-free templates carry this // exact sentence in a source comment, and it SURVIVES deleting the @@ -205,7 +232,7 @@ func TestReadyAckWarning(t *testing.T) { // outputDir is never read: it does not exist before the first build // and is gitignored, so a hit there says nothing about what is // submitted... and its ABSENCE must not be read as evidence either. - name: "an ack present only in outputDir warns", + name: "an ack present only in dist/ warns", manifest: ackManifest(true), files: map[string]string{ "package.json": `{"dependencies": {"react": "^19.0.0"}}`, @@ -214,6 +241,24 @@ func TestReadyAckWarning(t *testing.T) { "dist/assets/x.js": `window.parent.postMessage({type:'BLOCK_READY',payload:{}},o)`, }, wantWarn: true, + why: "killed by the NAME skip list (dist), not by the outputDir branch — see the case below", + }, + { + // 🔴 The one that actually reaches the outputDir branch. `dist` is in + // readyAckSkipDirs, so the case above is decided by an EARLIER check + // and leaves the manifest-driven skip untested — a mutation that + // disabled it survived the whole suite until this case existed. A + // non-standard outputDir is the only way in. + name: "an ack present only in a NON-STANDARD outputDir warns", + manifest: ackManifestOut(true, "public"), + files: map[string]string{ + "package.json": `{"dependencies": {"react": "^19.0.0"}}`, + "index.html": ``, + "src/main.jsx": `import App from './App';`, + "public/app.js": `window.parent.postMessage({type:'BLOCK_READY',payload:{}},o)`, + "public/x/y.mjs": `window.parent.postMessage({type:'BLOCK_READY',payload:{}},o)`, + }, + wantWarn: true, }, { name: "an ack in node_modules does not count", @@ -248,14 +293,17 @@ func TestReadyAckWarning(t *testing.T) { wantWarn: false, }, { - // A URL inside a string must not be read as the start of a comment — - // otherwise everything after it is stripped and a real ack below it - // disappears. - name: "a URL literal does not swallow the rest of the file", + // A URL inside a string must not be read as the start of a comment. + // The ack is on the SAME LINE as the URL on purpose: with quote + // handling defeated, the `//` in `https://` starts a line comment and + // swallows everything after it — including the ack. Split across two + // lines this case passes with the string handling deleted, which is + // how the first version of it left that branch unproven. + name: "a URL literal does not swallow the ack after it", manifest: ackManifest(false), files: map[string]string{ "index.html": ``, - "app.js": "var docs = 'https://civitai.com/docs';\n" + + "app.js": "var docs = 'https://civitai.com/docs'; " + "window.parent.postMessage({ type: 'BLOCK_READY', payload: {} }, o);\n", }, wantWarn: false, @@ -314,6 +362,23 @@ func TestReadyAckCannotObserve(t *testing.T) { wantAckWarning(t, dir, true) }) + t.Run("an unreadable source file silences the check", func(t *testing.T) { + // A DANGLING SYMLINK with a scanned extension: WalkDir hands it over as a + // non-directory, os.ReadFile fails, and the walk aborts. We then know + // nothing about the rest of the tree — including whatever we had not + // reached yet — so the only honest answer is silence. Without this + // fixture that branch is unreachable: chmod is a no-op for root, so a + // permissions-based fixture proves nothing on a root CI runner. + dir := ackProject(t, ackManifest(false), map[string]string{ + "index.html": ``, + "app.js": `document.title = 'hi';`, + }) + if err := os.Symlink(filepath.Join(dir, "gone.js"), filepath.Join(dir, "broken.js")); err != nil { + t.Skipf("symlinks unavailable here: %v", err) + } + wantAckWarning(t, dir, false) + }) + t.Run("an unreadable package.json silences the check", func(t *testing.T) { dir := ackProject(t, ackManifest(true), map[string]string{ "src/main.jsx": `import App from './App';`, From 8ce87e32b756e0bf0b5e13e85aa24410505f978a Mon Sep 17 00:00:00 2001 From: ZacxDev Date: Wed, 5 Aug 2026 21:27:56 -0500 Subject: [PATCH 3/6] fix(validate): the ack evidence was the @civitai scope, not the packages that ack MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit An adversarial audit falsified two headline claims this PR had written into AGENTS.md. Both reproduced live before fixing, both fixed here. 🔴 1. "The dependency is evidence" was false for four of the six published first-party packages. The gate tested the `@civitai/` PREFIX. Measured from fresh npm tarballs: only @civitai/blocks-react@0.39.0 acks (dist/internal/iframeTransport.js:311). @civitai/app-sdk@0.31.0 ships 17 runtime .js files and NONE contains BLOCK_READY — the only hits are a .d.ts type and the README — and it declares no dependencies, so it cannot ack transitively. @civitai/theme, @civitai/components, @civitai/components-react and @civitai/cli contain none at all. theme and components are exactly what a hand-written no-build page app installs, so the scope test went SILENT on a genuinely broken app: verified by adding @civitai/theme to a static scaffold with civitai-host.js deleted, i.e. the literal #206 shape. The predicate is now an exact set in blockproto, with the per-package evidence, used by BOTH validate and the scaffold contract guard — which had the identical hole: a future template depending on @civitai/theme would have been classified SDK-backed and excused from shipping an emitter, a born-broken template passing its own guard. 🔴 2. Three reachable shapes false-warned at a CORRECT project — the outcome this check's own doc names as the worst possible. (a) stripHTMLComments discarded everything after an unterminated ``) reScriptSrc = regexp.MustCompile(`(?is)]*\bsrc\s*=\s*["']([^"']+)["']`) diff --git a/internal/validate/readyack.go b/internal/validate/readyack.go index 2186ddd1..8dbc4543 100644 --- a/internal/validate/readyack.go +++ b/internal/validate/readyack.go @@ -29,8 +29,16 @@ package validate // SDK's `IframeTransport` and the literal `BLOCK_READY` NEVER APPEARS in `src/`. // A source scan alone therefore warns at every correct page-money app on the // platform, which is the worst possible outcome for advisory output: it teaches -// authors that this warning is noise. So package.json is read first and an -// `@civitai/*` dependency ENDS the check. +// authors that this warning is noise. So package.json is read first and a +// dependency that ACKS ends the check. +// +// 🔴 "A dependency that acks" is an EXACT SET (blockproto.PackageAcksReady), not +// the `@civitai/` scope. Four of the six published first-party packages do not +// ack at all — `@civitai/theme` and `@civitai/components` are plain CSS, and are +// exactly what a hand-written no-build page app installs — so a scope test goes +// SILENT on a genuinely broken app. Measured per package in blockproto, and +// reproduced live on a `static` scaffold with the emitter deleted. Do not +// re-widen this to a prefix. // // WHAT IT DOES NOT PROVE. That the ack FIRES. No static check can — an emitter // with an inverted `event.source` guard satisfies every assertion here (that is @@ -41,22 +49,34 @@ package validate // conclusive anyway, because being generous here costs a missed warning while // being strict costs a false one. // -// SCOPE — IT ONLY FIRES WHERE IT CAN OBSERVE. Mirroring lockfile.go's early-out -// shape: no `page` surface, no check. Unreadable package.json, no check. -// Unwalkable tree, no check. And it reads SOURCE only — never `outputDir`, -// which does not exist before the first build and is gitignored, so its absence -// says nothing. A check that cannot observe returns NO findings rather than -// manufacturing advice. +// SCOPE — IT ONLY FIRES WHERE IT CAN OBSERVE, AND "OBSERVE" MEANS THE WHOLE +// TREE. Mirroring lockfile.go's early-out shape: no `page` surface, no check; +// unreadable package.json, no check. Beyond that, the scan concludes "this app +// never acks" ONLY if it read every source file it could reach and found +// nothing. Anything that leaves a gap — an unresolvable symlink, a read error, a +// file over the size cap, the file-count budget — reports UNOBSERVABLE and stays +// silent. A partial scan that says "absent" is manufacturing advice from a gap. +// +// 🔴 SKIPPING IS A COST DECISION, NEVER A CORRECTNESS ONE, because this is a +// PRESENCE check: scanning an extra directory can only ever ADD ack evidence, +// while skipping one can only ever CREATE a false warning. That asymmetry is why +// the manifest's `outputDir` is NOT skipped (it was, and it was wrong — a +// perfectly valid `"outputDir": "src"` on a page-vite app skipped the directory +// holding the emitter and warned at a correct project; `"outputDir": "."` +// skipped the entire tree). What remains is a fixed list of names that are +// never source — dependencies, VCS metadata, and the conventional build +// directories — chosen for cost. The residual trade is accepted and stated: a +// stale committed build under a NON-conventional output directory can retain an +// ack the source has lost, silencing a genuinely broken app. That is a false +// negative, and false negatives are the cheap direction here. import ( "encoding/json" - "io/fs" "os" "path/filepath" "strings" "github.com/civitai/cli/internal/blockproto" - "github.com/civitai/cli/internal/manifest" ) // readyAckType is the message the page host waits for. It is the same literal @@ -64,18 +84,6 @@ import ( // is only the token we look for. const readyAckType = "BLOCK_READY" -// civitaiDepPrefix marks a first-party package. Any of them is taken as -// evidence that a real transport is in play — `@civitai/blocks-react` is the -// one that acks today, but a project pulling `@civitai/app-sdk` is on the SDK -// path too, and a false negative is the cheap direction. -// -// This deliberately mirrors `civitaiSDKDeps` in -// internal/scaffold/ready_ack_contract_test.go, which decides the same question -// for the templates. Keep them agreeing: they answer "does this project's ack -// come from the SDK", and disagreeing would mean the CLI warns at a shape its -// own scaffold guard considers correct. -const civitaiDepPrefix = "@civitai/" - // readyAckSourceExts are the extensions a hand-written emitter can live in. // Deliberately CODE ONLY — `.md` is excluded because a README that explains the // handshake is not an implementation of it, and both shipped scaffold READMEs @@ -88,21 +96,52 @@ var readyAckSourceExts = map[string]bool{ ".vue": true, ".svelte": true, ".astro": true, } -// readyAckSkipDirs are never descended into: dependencies, VCS metadata, and -// build output. The manifest's own outputDir is skipped on top of these. +// readyAckMarkupExts are the subset whose comments are ``. HTML comment +// stripping is applied ONLY to these. +// +// 🔴 Applying it to `.js`/`.ts` was a false-warning source: `stripHTMLComments` +// has no string awareness, so a perfectly ordinary `var OPEN = '") if end < 0 { + // 🔴 UNTERMINATED. Keep the remainder VERBATIM rather than + // discarding it. Dropping the tail is lossy in the expensive + // direction — everything below an unclosed `` in strings must not swallow what is + // between them either — the reason HTML stripping is gated to markup. + name: "a matched pair in .js strings does not eat the emitter", + manifest: ackManifest(false), + files: map[string]string{ + "index.html": ``, + "app.js": "var OPEN = '';\n", + }, + wantWarn: false, + }, + { + // A real HTML comment in a markup file must STILL be stripped — the + // positive control for the gate above. Without it, "don't strip HTML + // in .js" is indistinguishable from "don't strip HTML at all". + name: "an HTML comment in .html is still stripped", + manifest: ackManifest(false), + files: map[string]string{ + "index.html": "\n\n", + "app.js": `document.title = 'hi';`, + }, + wantWarn: true, + }, + { + // A block comment naming the message is still a comment. There was no + // /* */ fixture at all before. + name: "an ack named only in a /* */ block comment warns", + manifest: ackManifest(false), + files: map[string]string{ + "index.html": ``, + "app.js": "/*\n * We should post BLOCK_READY at some point.\n */\ndocument.title = 'hi';\n", }, wantWarn: true, }, @@ -393,6 +553,145 @@ func TestReadyAckCannotObserve(t *testing.T) { }) } +// TestReadyAckFollowsSymlinkedSource pins the monorepo shape. filepath.WalkDir +// does NOT follow symlinks and does not even report them as directories, so a +// project whose `src` is a symlink into a shared package had its entire source +// tree silently skipped and warned at a correct project — reproduced live on a +// page-vite scaffold before this existed. +func TestReadyAckFollowsSymlinkedSource(t *testing.T) { + root := t.TempDir() + shared := filepath.Join(root, "shared") + proj := filepath.Join(root, "app") + + for _, d := range []string{shared, proj} { + if err := os.MkdirAll(d, 0o755); err != nil { + t.Fatal(err) + } + } + write := func(p, body string) { + t.Helper() + if err := os.MkdirAll(filepath.Dir(p), 0o755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(p, []byte(body), 0o600); err != nil { + t.Fatal(err) + } + } + write(filepath.Join(proj, "block.manifest.json"), ackManifest(true)) + write(filepath.Join(proj, "package.json"), `{"dependencies": {"react": "^19.0.0"}}`) + write(filepath.Join(proj, "package-lock.json"), `{"lockfileVersion":3}`) + write(filepath.Join(proj, "index.html"), ``) + write(filepath.Join(shared, "main.jsx"), `import './civitai-host.js';`) + write(filepath.Join(shared, "civitai-host.js"), realEmitter()) + + // Positive control FIRST: with the emitter reachable only through the link, + // a green below could otherwise mean the scanner found it somewhere else. + if err := os.Symlink(filepath.Join("..", "shared"), filepath.Join(proj, "src")); err != nil { + t.Skipf("symlinks unavailable here: %v", err) + } + wantAckWarning(t, proj, false) + + // Negative control: break the symlinked tree the same way #206 breaks an + // app, and the warning must come back — otherwise "does not warn" above is + // satisfied by a scanner that silently gave up on the symlink. + if err := os.Remove(filepath.Join(shared, "civitai-host.js")); err != nil { + t.Fatal(err) + } + wantAckWarning(t, proj, true) +} + +// TestReadyAckSymlinkCycleTerminates pins the cost of following symlinks. A +// self-referential link is the obvious way a followed walk never returns. +func TestReadyAckSymlinkCycleTerminates(t *testing.T) { + dir := ackProject(t, ackManifest(false), map[string]string{ + "index.html": ``, + "src/app.js": `document.title = 'hi';`, + "src/nested/x.js": `document.title = 'hi';`, + }) + if err := os.Symlink("..", filepath.Join(dir, "src", "loop")); err != nil { + t.Skipf("symlinks unavailable here: %v", err) + } + // The assertion is that this RETURNS at all; the verdict is secondary. + done := make(chan bool, 1) + go func() { + res, err := Dir(dir) + if err != nil { + t.Error(err) + } + done <- hasReadyAckWarning(res) + }() + select { + case <-done: + case <-time.After(20 * time.Second): + t.Fatal("the scan did not terminate on a symlink cycle — the visited set is not doing its job") + } +} + +// TestReadyAckCapsAreUnobservable pins that hitting a cap stays SILENT. A scan +// that stopped early has a gap in it, and a gap is not evidence of absence. +func TestReadyAckCapsAreUnobservable(t *testing.T) { + t.Run("a file over the size cap silences the check", func(t *testing.T) { + dir := ackProject(t, ackManifest(false), map[string]string{ + "index.html": ``, + "app.js": `document.title = 'hi';`, + }) + // Positive control: without the oversized file this project warns. + wantAckWarning(t, dir, true) + big := strings.Repeat("x", maxAckFileBytes+1) + if err := os.WriteFile(filepath.Join(dir, "bundle.js"), []byte(big), 0o600); err != nil { + t.Fatal(err) + } + wantAckWarning(t, dir, false) + }) + + t.Run("exceeding the file budget silences the check", func(t *testing.T) { + dir := ackProject(t, ackManifest(false), map[string]string{ + "index.html": ``, + "app.js": `document.title = 'hi';`, + }) + wantAckWarning(t, dir, true) + for i := 0; i <= maxAckScanFiles; i++ { + p := filepath.Join(dir, "gen", fmt.Sprintf("f%05d.js", i)) + if err := os.MkdirAll(filepath.Dir(p), 0o755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(p, []byte("var x=1;\n"), 0o600); err != nil { + t.Fatal(err) + } + } + wantAckWarning(t, dir, false) + }) +} + +// TestReadyAckAdviceIsActionable pins the message CONTENT. hasReadyAckWarning +// compares against the readyAckAdvice variable, which is self-referential — +// replacing the whole advisory with "something may be wrong" passes every other +// test in this file. AGENTS.md requires a message to name what to do, so assert +// the parts an author acts on. +func TestReadyAckAdviceIsActionable(t *testing.T) { + required := []struct{ substr, why string }{ + {"page", "the author has to know WHICH manifest field put them here"}, + {readyAckType, "the message that is missing"}, + {"civitai app init", "the concrete command that produces a correct emitter"}, + {blockproto.ReadyAckFilename, "the file to copy in"}, + {"index.html", "where the emitter has to be referenced from"}, + {"@civitai/blocks-react", "the alternative to hand-writing it"}, + {"never both", "adopting the SDK without deleting the emitter is strictly worse"}, + {"#206", "the issue an author can read for the full story"}, + {"--strict", "so nobody thinks this blocks them today"}, + } + for _, r := range required { + if !strings.Contains(readyAckAdvice, r.substr) { + t.Errorf("the advisory does not mention %q — %s\ngot: %s", r.substr, r.why, readyAckAdvice) + } + } + // A message that says nothing useful is short. This is a crude floor, but it + // is the one thing a "something may be wrong" rewrite cannot satisfy. + if len(readyAckAdvice) < 400 { + t.Errorf("the advisory is %d chars — too short to carry a diagnosis and a remedy", len(readyAckAdvice)) + } +} + // TestReadyAckIsAdvisoryOnly pins the tier. The check must never reach Errors — // it infers runtime behaviour from static text, and a hard failure on a // heuristic breaks correct projects. @@ -478,17 +777,44 @@ func TestSDKTemplateIsQuietOnlyBecauseOfTheDependency(t *testing.T) { if _, err := scaffold.Render(scaffold.PageMoney, dest, scaffold.Data{Slug: "ack-block", Name: "Ack Block"}); err != nil { t.Fatal(err) } - if emitsReadyAck(dest, "dist") { - t.Fatalf("page-money's SOURCE mentions %s — the dep gate is no longer the reason it is accepted, "+ - "so nothing in this suite covers that branch any more", readyAckType) + if got := scanForReadyAck(dest); got != ackAbsent { + t.Fatalf("scanForReadyAck(page-money) = %v, want ackAbsent — the dep gate is no longer the reason "+ + "it is accepted, so nothing in this suite covers that branch any more", got) } if got := sdkDependency(dest); got != sdkPresent { - t.Fatalf("sdkDependency(page-money) = %v, want sdkPresent — the rendered package.json must depend on %s*", - got, civitaiDepPrefix) + t.Fatalf("sdkDependency(page-money) = %v, want sdkPresent — the rendered package.json must depend "+ + "on one of %v", got, blockproto.AckingPackages()) } wantAckWarning(t, dest, false) } +// TestSDKTemplateDepsAreNotJustAnyCivitaiPackage pins that page-money is +// accepted because of the package that ACKS, not merely because it has +// `@civitai/*` dependencies. It depends on BOTH `@civitai/app-sdk` (which does +// not ack) and `@civitai/blocks-react` (which does), so a scope test and an +// exact test agree on this template — which is exactly why the template alone +// could never have caught the widening. +func TestSDKTemplateDepsAreNotJustAnyCivitaiPackage(t *testing.T) { + dest := filepath.Join(t.TempDir(), "page-money") + if _, err := scaffold.Render(scaffold.PageMoney, dest, scaffold.Data{Slug: "ack-block", Name: "Ack Block"}); err != nil { + t.Fatal(err) + } + raw, err := os.ReadFile(filepath.Join(dest, "package.json")) + if err != nil { + t.Fatal(err) + } + acking := 0 + for _, name := range blockproto.AckingPackages() { + if strings.Contains(string(raw), `"`+name+`"`) { + acking++ + } + } + if acking == 0 { + t.Fatalf("page-money depends on no acking package (%v) — it must, or the SDK branch of the check "+ + "has no real-template coverage at all", blockproto.AckingPackages()) + } +} + // TestDeletingTheEmitterMakesTheWarningFire is the NEGATIVE CONTROL for the // guard above: it takes a correct scaffold, breaks it exactly the way a // pre-4018e2c app is broken, and requires the warning. Without it, diff --git a/internal/validate/validate.go b/internal/validate/validate.go index 115c4173..04c30583 100644 --- a/internal/validate/validate.go +++ b/internal/validate/validate.go @@ -152,7 +152,7 @@ func validateDir(dir string, projectState bool) (Result, error) { // HERE rather than in warningChecks because it reads src/, and // warningChecks also runs under ManifestOnly, where `civitai app init` // self-checks a template it just wrote. See readyack.go. - res.Warnings = append(res.Warnings, readyAckChecks(dir, generic, m)...) + res.Warnings = append(res.Warnings, readyAckChecks(dir, generic)...) } // Non-fatal advisories: real money-path footguns the schema can't catch as From 7cbc03b70f2d009756592b6b5897ce4dc5ffd03b Mon Sep 17 00:00:00 2001 From: ZacxDev Date: Wed, 5 Aug 2026 21:45:16 -0500 Subject: [PATCH 4/6] test(validate): pin that no skip rule can remove the project ROOT MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Found by a surviving mutant, not by reading the code: adding `if readyAckSkipDirs[filepath.Base(dir)] { return }` to the top of the walk passed the ENTIRE suite. Every fixture's project root is a random t.TempDir() name, so nothing exercised the claim that the skip list is applied to entries only. A project directory called `build`, `out` or `dist` is perfectly ordinary. Under that mutant such a project scanned nothing, reported "no files read", and went silent — the same whole-tree removal that `"outputDir": "."` used to cause and that the entries-only rule exists to make impossible. Each case carries its own positive control: the same tree goes silent once the emitter is added, so "warns" cannot be satisfied by a scan that warns unconditionally. --- internal/validate/readyack_test.go | 38 ++++++++++++++++++++++++++++++ 1 file changed, 38 insertions(+) diff --git a/internal/validate/readyack_test.go b/internal/validate/readyack_test.go index d7e0960d..b5057811 100644 --- a/internal/validate/readyack_test.go +++ b/internal/validate/readyack_test.go @@ -553,6 +553,44 @@ func TestReadyAckCannotObserve(t *testing.T) { }) } +// TestReadyAckSkipListNeverRemovesTheRoot pins the "applied to ENTRIES only" +// half of the skip rule. +// +// Found by a surviving mutant: adding `if readyAckSkipDirs[filepath.Base(dir)] +// { return }` to the top of the walk passed the ENTIRE suite, because every +// fixture's project root is a random t.TempDir() name. A project whose own +// directory is called `build`, `out` or `dist` is perfectly ordinary, and under +// that mutant it scanned nothing, reported "no files read", and went silent — +// the same whole-tree removal that `"outputDir": "."` used to cause. +func TestReadyAckSkipListNeverRemovesTheRoot(t *testing.T) { + for _, name := range []string{"dist", "build", "out", "node_modules"} { + t.Run("project directory named "+name, func(t *testing.T) { + root := filepath.Join(t.TempDir(), name) + if err := os.MkdirAll(root, 0o755); err != nil { + t.Fatal(err) + } + write := func(p, body string) { + t.Helper() + if err := os.WriteFile(filepath.Join(root, p), []byte(body), 0o600); err != nil { + t.Fatal(err) + } + } + write("block.manifest.json", ackManifest(false)) + write("index.html", ``) + write("app.js", `document.title = 'hi';`) + // The #206 shape: it must still be REPORTED even though the project + // happens to live in a directory whose name is on the skip list. + wantAckWarning(t, root, true) + + // Positive control on the same tree: with an emitter it goes silent, + // so the assertion above cannot be satisfied by a scan that warns + // unconditionally. + write("civitai-host.js", realEmitter()) + wantAckWarning(t, root, false) + }) + } +} + // TestReadyAckFollowsSymlinkedSource pins the monorepo shape. filepath.WalkDir // does NOT follow symlinks and does not even report them as directories, so a // project whose `src` is a symlink into a shared package had its entire source From 41a1e49220b3912d5127594feb4fa92388ce1d73 Mon Sep 17 00:00:00 2001 From: ZacxDev Date: Wed, 5 Aug 2026 21:49:47 -0500 Subject: [PATCH 5/6] test(validate): count files to pin the visited set, which the cycle test did not MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Second surviving mutant from the post-audit battery: deleting the visited set entirely passed the suite, cycle test included. That test was proving the wrong thing — a self-referential symlink terminates anyway, because Linux gives up with ELOOP after ~40 resolutions and the resulting error makes the scan partial. So the OS guarantees termination and the visited set's real job is avoiding DUPLICATE WORK: without it, two links to one directory read every file in it twice, inflating the count toward a budget whose only effect is silencing the check. Counting files is the only thing that can see that, so the new test walks ackScanner directly and asserts three routes to one directory read its files once. The cycle test stays as a backstop, relabelled to say what it does not prove. --- internal/validate/readyack_test.go | 53 ++++++++++++++++++++++++++++-- 1 file changed, 51 insertions(+), 2 deletions(-) diff --git a/internal/validate/readyack_test.go b/internal/validate/readyack_test.go index b5057811..96773eca 100644 --- a/internal/validate/readyack_test.go +++ b/internal/validate/readyack_test.go @@ -638,8 +638,57 @@ func TestReadyAckFollowsSymlinkedSource(t *testing.T) { wantAckWarning(t, proj, true) } -// TestReadyAckSymlinkCycleTerminates pins the cost of following symlinks. A -// self-referential link is the obvious way a followed walk never returns. +// TestReadyAckScannerVisitsEachDirectoryOnce pins the visited set DIRECTLY, by +// counting files read. +// +// Found by a surviving mutant: deleting the visited set entirely passed the +// suite, including the cycle test below. That test was proving the wrong thing — +// a self-referential symlink terminates anyway, because Linux gives up with +// ELOOP after ~40 resolutions and the resulting error makes the scan partial. So +// termination is guaranteed by the OS, and the visited set's real job is +// avoiding DUPLICATE WORK: without it, two links to the same directory read +// every file in it twice, inflating the file count toward a budget whose only +// effect is to silence the check. +// +// Asserting the count is the only thing that can see that. This walks the +// scanner directly rather than through Dir(), because the number of files read +// is the observable and the verdict is not. +func TestReadyAckScannerVisitsEachDirectoryOnce(t *testing.T) { + dir := t.TempDir() + shared := filepath.Join(dir, "shared") + if err := os.MkdirAll(shared, 0o755); err != nil { + t.Fatal(err) + } + const nFiles = 3 + for i := 0; i < nFiles; i++ { + p := filepath.Join(shared, fmt.Sprintf("m%d.js", i)) + if err := os.WriteFile(p, []byte("var x=1;\n"), 0o600); err != nil { + t.Fatal(err) + } + } + // Two more routes to the same directory. A walk with no visited set reads + // each file three times. + for _, link := range []string{"link1", "link2"} { + if err := os.Symlink("shared", filepath.Join(dir, link)); err != nil { + t.Skipf("symlinks unavailable here: %v", err) + } + } + + s := &ackScanner{visited: map[string]bool{}} + s.walk(dir) + if s.partial { + t.Fatalf("the scan reported partial on a readable tree — it should have read all %d files", nFiles) + } + if s.files != nFiles { + t.Fatalf("scanner read %d files, want %d — three paths reach the same directory, so a walk that "+ + "does not record RESOLVED paths reads each file once per route", s.files, nFiles) + } +} + +// TestReadyAckSymlinkCycleTerminates pins that a self-referential link does not +// hang. Note what it does NOT prove: the OS's own ELOOP limit terminates this +// even with the visited set deleted, so this is a backstop assertion and +// TestReadyAckScannerVisitsEachDirectoryOnce is what actually covers the guard. func TestReadyAckSymlinkCycleTerminates(t *testing.T) { dir := ackProject(t, ackManifest(false), map[string]string{ "index.html": ``, From 9b4e5f695b738a6a4ce9ed08bde7b98c07cddd81 Mon Sep 17 00:00:00 2001 From: ZacxDev Date: Wed, 5 Aug 2026 22:22:31 -0500 Subject: [PATCH 6/6] docs: four comments outlived the facts they asserted MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Each is a claim a maintainer would act on, and each is now false. `AGENTS.md` item 11 and the `ready-ack-runtime` note in ci.yml both said no ready-ack check gates a merge, and named adding the required contexts as an outstanding decision. That decision was since taken: `gh api .../branches/main/protection` now returns pins-vs-published, scaffold-currency, build-test, ready-ack-runtime and template-page-vite. Both now state what the API returns, keep the record that an earlier revision claimed "BLOCKS the merge" while it did not, and say the claim is true now only because the contexts were added — not because the job runs. `readyack_test.go` said its dangling-symlink fixture makes os.ReadFile fail. It does not: the walk stops at the os.Stat guard above it. Measured — mutating that ReadFile branch to `continue` fails nothing in the suite, and the same holds for os.ReadDir. Both are reachable only via permissions, and chmod is a no-op for root, so neither can be pinned on a root CI runner. The comment now records the gap instead of implying coverage; shipped behaviour for both was checked by hand and stays silent. `ready_ack_contract_test.go` told a template author it "carries no @civitai/* SDK" — false since the acking set narrowed from the @civitai scope to the packages that actually post BLOCK_READY. A template can carry @civitai/theme and still never ack. `generate.go` cited AGENTS.md items 11-16; the generate items renumbered to 12-17 when this branch took item 18. Comment-only apart from one t.Errorf message string. actionlint clean on the changed workflow, verified against a positive control. Co-Authored-By: Claude Opus 5 (1M context) --- .github/workflows/ci.yml | 12 ++++++----- AGENTS.md | 22 ++++++++++---------- internal/cmd/generate.go | 2 +- internal/scaffold/ready_ack_contract_test.go | 2 +- internal/validate/readyack_test.go | 18 ++++++++++------ 5 files changed, 32 insertions(+), 24 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 37fe25ba..45d2a2a6 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -103,11 +103,13 @@ jobs: # workflow nobody watches — running it per-PR puts the result in front of a # reviewer while the change is still open. # - # 🔴 NOTE: this REPORTS, it does not GATE. `main`'s required contexts are - # exactly `pins-vs-published` and `scaffold-currency` (no rulesets), so a red - # run here does not block a merge — `build-test` doesn't either. Adding this - # to the required contexts is the outstanding maintainer decision recorded in - # AGENTS.md item 11. + # 🔴 NOTE: this both reports AND gates. `main`'s required contexts are + # `pins-vs-published`, `scaffold-currency`, `build-test`, `ready-ack-runtime` + # and `template-page-vite` (no rulesets), so a red run here blocks the merge. + # That was a policy change made after this job landed — it did NOT gate when + # it shipped. Re-measure with + # `gh api repos/civitai/cli/branches/main/protection` before calling any job + # here a gate; see AGENTS.md item 11. # # -v so the run REPORTS its controls (an inert emitter and a naive ack are # driven through the same assertions and must be rejected) rather than just an diff --git a/AGENTS.md b/AGENTS.md index 82108684..21d262aa 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -504,18 +504,18 @@ neither one's. thing that BUILDS an SDK-free template, and it asserts the ack survives bundling (Guard A pins the source tree; Vite output is what the platform serves). - 🔴 **REPORTING IS NOT GATING — no ready-ack check currently blocks a - merge.** Measured, not assumed, via + 🔴 **REPORTING VS GATING — measure it, never infer it from the job + existing.** These jobs now gate. Measured via `gh api repos/civitai/cli/branches/main/protection`: the required contexts - are exactly `pins-vs-published` and `scaffold-currency`, with no rulesets. - So `ready-ack-runtime`, `template-page-vite` and even `build-test` all - report and stop nothing. **Outstanding step:** adding `ready-ack-runtime` - (and arguably `build-test`) to the required contexts is what converts - reporting into gating. That is a repo-policy change touching every open - PR, so it is the maintainer's call and was deliberately not taken by the - agent that wrote this. Until it is, do not describe any of these jobs as a - gate — an earlier revision of this item, and of - `ready_ack_runtime_test.go`, claimed one "BLOCKS the merge". It was false. + are `pins-vs-published`, `scaffold-currency`, `build-test`, + `ready-ack-runtime` and `template-page-vite`, with no rulesets. That was a + deliberate repo-policy change made AFTER this item first shipped; until + then all of these reported and stopped nothing — including `build-test`, + so the suite itself did not gate. Re-measure before describing any job + here as a gate: an earlier revision of this item, and of + `ready_ack_runtime_test.go`, claimed one "BLOCKS the merge" while it did + not. That claim was false when written and is true now only because the + contexts were added — not because the job runs. If you add a template, add nothing — Guard A picks it up automatically and fails until `ReadyAckPath()` is set. - **`BLOCK_HELLO` now exists host-side, and the emitter deliberately does diff --git a/internal/cmd/generate.go b/internal/cmd/generate.go index 66c91d0a..7bfa640c 100644 --- a/internal/cmd/generate.go +++ b/internal/cmd/generate.go @@ -929,7 +929,7 @@ func printOutputURLs(out, errw io.Writer, kept []genapi.Output) { // // 🔴 It must print the REALIZED charge whenever the server reported one. The // user approved an ESTIMATE, and this command's whole spend story is that the -// realized cost can exceed it with no refund (AGENTS.md items 11-16) — so the +// realized cost can exceed it with no refund (AGENTS.md items 12-17) — so the // one number that settles what actually happened cannot be visible only on the // --no-wait branch. `cost` is nil when the server sent none; say nothing then // rather than printing a fabricated 0. diff --git a/internal/scaffold/ready_ack_contract_test.go b/internal/scaffold/ready_ack_contract_test.go index 815d0b6a..e4c3d1a4 100644 --- a/internal/scaffold/ready_ack_contract_test.go +++ b/internal/scaffold/ready_ack_contract_test.go @@ -419,7 +419,7 @@ func TestScaffoldedPageTemplatesShipTheReadyAck(t *testing.T) { rel := tmpl.ReadyAckPath() if rel == "" { - t.Errorf("template %q declares a `page` surface and carries no @civitai/* SDK, but "+ + t.Errorf("template %q declares a `page` surface and depends on no package that acks, but "+ "ReadyAckPath() is empty — a page app that never posts BLOCK_READY is replaced by a "+ "failure card in the real host (issue #206). Give it a path in scaffold.go so "+ "Render ships blockproto's emitter.", tmpl) diff --git a/internal/validate/readyack_test.go b/internal/validate/readyack_test.go index 96773eca..7c7d216b 100644 --- a/internal/validate/readyack_test.go +++ b/internal/validate/readyack_test.go @@ -523,12 +523,18 @@ func TestReadyAckCannotObserve(t *testing.T) { }) t.Run("an unreadable source file silences the check", func(t *testing.T) { - // A DANGLING SYMLINK with a scanned extension: WalkDir hands it over as a - // non-directory, os.ReadFile fails, and the walk aborts. We then know - // nothing about the rest of the tree — including whatever we had not - // reached yet — so the only honest answer is silence. Without this - // fixture that branch is unreachable: chmod is a no-op for root, so a - // permissions-based fixture proves nothing on a root CI runner. + // A DANGLING SYMLINK with a scanned extension: os.Stat cannot resolve it, + // so the walk stops there. We then know nothing about the rest of the + // tree — including whatever we had not reached yet — so the only honest + // answer is silence. + // + // 🔴 This fixture reaches the os.Stat guard, NOT the os.ReadFile one + // below it. Measured: mutating that ReadFile branch to `continue` fails + // NOTHING in the suite, and the same is true of the os.ReadDir branch. + // Both are reachable only via permissions (a mode-0000 file, a mode-0111 + // dir), and chmod is a no-op for root, so neither can be pinned on a root + // CI runner. Shipped behaviour for both was verified by hand — they stay + // silent — but do not read this case as covering them. dir := ackProject(t, ackManifest(false), map[string]string{ "index.html": ``, "app.js": `document.title = 'hi';`,