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 2d01f4ab..21d262aa 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -161,9 +161,11 @@ 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; items 12–17 cover `civitai generate`, the CLI's only path -that **spends the user's money irreversibly**. 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. +that **spends the user's money irreversibly**; item 18 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. The generate items pull in the opposite direction from the mirror items, and that is deliberate: `validate` mirrors the platform because a local answer is @@ -502,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 @@ -695,6 +697,129 @@ neither one's. `deps.downloadBlob = reader.DownloadPresigned`; if you ever see that wired to `DownloadFile`, it is a credential leak, not a cleanup. +18. **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 adds a THIRD family to that denylist: not a + dead REST route, and not a dead TOOL (`deprecated-blocks-cli` already + covered that one), but a dead host MESSAGE — marked N/A for + `PageBlockHost` by `hostHandlerParity.ts`. + 🔴 **A message NAME needs tighter scoping than a route or a package name, + because it is far more quotable, and both devices were earned by a false + positive.** `Exts: codeExts` keeps it out of `.md`/`.txt`/`.json`, where + naming the message in a sentence or using it as a JSON handler-table key is + ordinary writing — unscoped, the rule flagged its own documentation, and + this repo's README plus both scaffold READMEs exist to say "don't post + RESIZE_IFRAME". And it matches only a MATCHING `'` or `"` pair — + deliberately not the backtick form (markdown), and not a mismatched pair, + which is not a string literal in any language. `What` reads "reference to", + not "postMessage of": the regex matches the quoted token anywhere in code + (a dispatch-table key, a comparison, a constant — all equally dead on a + page surface), and saying "postMessage" would be a claim the pattern does + not make. 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 evidence is an EXACT SET OF PACKAGES THAT ACK — never the + `@civitai/` scope.** This is the claim an audit falsified, so it is stated + with its measurement. Of the six published first-party packages, exactly + ONE acks: `@civitai/blocks-react@0.39.0` + (`dist/internal/iframeTransport.js:311`, `this.dispatch('BLOCK_READY', …)`). + `@civitai/app-sdk@0.31.0` does **not** — 17 runtime `.js` files, zero + containing the literal, the only hits a `.d.ts` type and the README, and it + declares no dependencies so it cannot ack transitively either. + `@civitai/theme`, `@civitai/components`, `@civitai/components-react` and + `@civitai/cli` contain none at all. A scope test is therefore wrong for + FOUR of six, and wrong in the expensive direction: `theme` and `components` + are framework-agnostic CSS, exactly what a hand-written no-build page app + installs, so the check went **silent on a genuinely broken app** — verified + live by adding `@civitai/theme` to a `static` scaffold with + `civitai-host.js` deleted. + The predicate lives in `blockproto.PackageAcksReady` with the per-package + evidence, and is used by BOTH `internal/validate/readyack.go` and + `civitaiSDKDeps` in `ready_ack_contract_test.go` — one rule, one place, + because Guard A 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). The + match is EXACT; a prefix or substring test accepts a sibling + (`@civitai/blocks-react-native`) or a fork, and that widening class is what + `TestAckingPackagePredicate` exists to pin. Adding a package there is a + claim about its RUNTIME code — verify against the tarball, not the README + or the types, and record the version. + - **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. + 🔴 **HTML comment stripping is gated to MARKUP extensions, and an + unterminated ``) reScriptSrc = regexp.MustCompile(`(?is)]*\bsrc\s*=\s*["']([^"']+)["']`) diff --git a/internal/validate/readyack.go b/internal/validate/readyack.go new file mode 100644 index 00000000..8dbc4543 --- /dev/null +++ b/internal/validate/readyack.go @@ -0,0 +1,438 @@ +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 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 +// 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, 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" + "os" + "path/filepath" + "strings" + + "github.com/civitai/cli/internal/blockproto" +) + +// 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" + +// 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, +} + +// 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 `\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. + // The conventional build directories are skipped BY NAME, for cost. + // A stale `dist` therefore cannot supply ack evidence the source + // lacks — the one correctness benefit of skipping, and the reason + // the name list keeps these entries. + name: "an ack present only in dist/ 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, + }, + { + // 🔴 THE FALSIFIED CLAIM, HALF ONE. `outputDir` used to be skipped + // from the MANIFEST, which meant a perfectly valid `"outputDir": + // "src"` skipped the directory holding the emitter and warned at a + // correct project — reproduced live on a page-vite scaffold whose + // manifest had ZERO validation errors. Skipping is a cost decision, + // never a correctness one: for a presence check, scanning extra can + // only ADD evidence while skipping can only CREATE a false warning. + name: `"outputDir": "src" must not hide the emitter that lives there`, + manifest: ackManifestOut(true, "src"), + files: map[string]string{ + "package.json": `{"dependencies": {"react": "^19.0.0"}}`, + "index.html": ``, + "src/main.jsx": `import './civitai-host.js';`, + "src/civitai-host.js": realEmitter(), + }, + wantWarn: false, + }, + { + // 🔴 HALF TWO. `"outputDir": "."` resolved to the project root, so the + // manifest-driven skip removed the ENTIRE tree, `scanned == 0`, and a + // genuinely broken app was silenced. No skip rule may ever be able to + // remove the root: the list is applied to ENTRIES, never to the root + // the scanner was handed. + name: `"outputDir": "." must not skip the whole project`, + manifest: ackManifestOut(true, "."), + files: map[string]string{ + "package.json": `{"dependencies": {"react": "^19.0.0"}}`, + "index.html": ``, + "app.js": `document.title = 'hi';`, + }, + wantWarn: true, + }, + { + // A non-conventional output directory is now SCANNED. That is the + // accepted residual trade: a stale build under `public/` can retain + // an ack the source lost and silence the check. A false negative, + // deliberately preferred over false-warning at every project whose + // outputDir happens to hold source (Vite's `public/` is a SOURCE + // directory, which is what made this the realistic shape). + name: "a non-conventional outputDir is scanned rather than skipped", + 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)`, + }, + wantWarn: false, + }, + { + // 🔴 An unterminated `` 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, + }, + { + 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. + // 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'; " + + "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 source file silences the check", func(t *testing.T) { + // 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';`, + }) + 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';`, + }) + // 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) + }) +} + +// 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 +// 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) +} + +// 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": ``, + "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. +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 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 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, +// "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..04c30583 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)...) } // Non-fatal advisories: real money-path footguns the schema can't catch as