diff --git a/AGENTS.md b/AGENTS.md index 2fbd99fc..d4646777 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -479,6 +479,26 @@ neither one's. Don't reintroduce it as a "minimal example". Note `iframe.resizable` in the vendored `schema/` still describes itself in size-to-content terms; that is a schema-side wording issue, not a licence to re-add the message. + - **The entry-graph resolver moved OUT of Guard A and into + `internal/blockproto`** (`entrygraph.go` + `wiring.go`, with the comment + stripper in `comments.go`), because `internal/validate` needed the same + question answered for an AUTHOR's project and had answered it with a + whole-tree grep instead β€” see item 20 for the false pass that produced. + Guard A now calls `blockproto.ReadyAckWiring`; its control corpus moved + with the predicate, into `internal/blockproto/entrygraph_test.go`. + πŸ”΄ **Guard A's REJECTION set is unchanged, but its ACCEPTANCE set moved β€” + state both, because "nothing changed" was the claim an audit falsified.** + It now also accepts an emitter imported by an INLINE + `` in `index.html`, `page-vite` +with `import './civitai-host.js';` as the first line of `src/main.jsx`. +`civitai app validate` checks that reference where it can resolve your entry +point, and tells you when it can't. > ⚠️ **If you adopt `@civitai/blocks-react`, delete `civitai-host.js` in the > same change.** This is the one situation where removing it is correct, and @@ -671,14 +676,36 @@ 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` +`page` surface and **nothing your app loads 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. Three things follow: - +correct project. + +> ⚠️ **Copying `civitai-host.js` in is only half the fix.** A browser never +> fetches a file nothing references, so the emitter has to be *loaded* too β€” a +> `` in `index.html`, or an +> `import './civitai-host.js';` at the top of the entry module `index.html` +> loads. Earlier releases of this check looked only for the *text* +> `BLOCK_READY` anywhere in your tree, so an unreferenced copy silenced it and a +> still-broken app validated clean. It now resolves what your `index.html` +> actually loads. + +Four things follow: + +- **It checks REACHABILITY where it can, and says when it can't.** Starting at + `index.html` it follows every `" + if got := StripCommentsForExt(html, ".html"); contains(got, "BLOCK_READY") { + t.Fatalf(".html kept a real HTML comment: %q", got) + } + // The extension match is case-insensitive β€” an `.HTML` file is markup. + if got := StripCommentsForExt(html, ".HTML"); contains(got, "BLOCK_READY") { + t.Fatalf(".HTML was not treated as markup: %q", got) + } +} + +func contains(s, sub string) bool { + for i := 0; i+len(sub) <= len(s); i++ { + if s[i:i+len(sub)] == sub { + return true + } + } + return false +} diff --git a/internal/blockproto/entrygraph.go b/internal/blockproto/entrygraph.go new file mode 100644 index 00000000..615ef6ec --- /dev/null +++ b/internal/blockproto/entrygraph.go @@ -0,0 +1,683 @@ +package blockproto + +// entrygraph.go resolves THE SET OF FILES A BROWSER ACTUALLY LOADS for a block +// project: index.html, the scripts it references, and the modules those import. +// +// WHY IT LIVES HERE. It started as test-only code in +// `internal/scaffold/ready_ack_contract_test.go`, where Guard A uses it to prove +// a scaffolded template's vendored emitter is REACHED and not merely present. +// `internal/validate`'s page-without-ack advisory needed exactly the same +// question answered for an AUTHOR's project β€” and while it was answered by a +// whole-tree grep instead, an author who copied `civitai-host.js` in without +// referencing it from index.html got a green `validate` for an app that was +// still completely broken. That is the same "presence is not reachability" hole +// Guard A had before it was rewritten, regenerated at a second call site, which +// is precisely the shape `PackageAcksReady` was consolidated here to avoid. +// +// πŸ”΄ AN HTML `src` IS A URL. A JS SPECIFIER IS A MODULE SPECIFIER. THEY ARE +// RESOLVED BY DIFFERENT RULES, AND CONFLATING THEM PRODUCED THREE SEPARATE BUGS. +// The first version of this file ran every reference through one resolver +// written for module specifiers. Measured consequences, each on a project one +// character away from a shipped template: +// +// ` would resolve + // to a graph that "completely" misses the emitter β€” a false finding at a + // correct project. Their specifiers are MODULE syntax, resolved against the + // document's directory (the project root). + for _, m := range reScriptBlock.FindAllStringSubmatch(html, -1) { + if _, ok := srcAttrValue(m[1]); ok { + continue // external: already queued above + } + for _, im := range reJSImport.FindAllStringSubmatch(StripJSComments(m[2]), -1) { + queue = append(queue, pending{spec: strings.Clone(im[1]), from: dir, via: 0, depth: 1, + what: "inline ` so an INLINE + // module's imports can be read. Group 1 is the attribute list, group 2 the + // body. The close tag allows trailing whitespace (``, which a + // browser accepts) but NOT arbitrary characters β€” `` closes + // nothing, and widening to `]*>` would make it close an inline + // module that is still open. + reScriptBlock = regexp.MustCompile(`(?is)]*)?>(.*?)`) + // reSrcAttr captures a src value in any of HTML's three quoting forms. The + // leading `[\s/]` is the attribute-name boundary `\b` could not be. + // + // There is deliberately no `^` alternative: reScriptOpen's capture is + // `([\s/][^>]*)?`, so an attribute list is either EMPTY (no src to find) or + // begins with whitespace or `/`. An `^` arm was there and was UNREACHABLE β€” + // a mutation sweep removing it survived, which is the tell. It was dropped + // rather than left as a branch nothing can exercise. + reSrcAttr = regexp.MustCompile(`(?is)[\s/]src\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s"'` + "`" + `=<>]+))`) + // reJSImport captures the SPECIFIER of an import / re-export / require, so + // it can be resolved. Matching a basename inside the specifier is what let + // `import '../nonexistent/civitai-host.js'` through. + reJSImport = regexp.MustCompile(`(?:\bimport\s*\(?\s*|\bfrom\s+|\brequire\(\s*)['"]([^'"]+)['"]`) +) diff --git a/internal/blockproto/entrygraph_test.go b/internal/blockproto/entrygraph_test.go new file mode 100644 index 00000000..5a506ed9 --- /dev/null +++ b/internal/blockproto/entrygraph_test.go @@ -0,0 +1,1022 @@ +package blockproto + +import ( + "os" + "path/filepath" + "strings" + "testing" +) + +type gfile struct{ path, body string } + +func writeTree(t *testing.T, files []gfile) string { + t.Helper() + dir := t.TempDir() + for _, f := range files { + p := filepath.Join(dir, filepath.FromSlash(f.path)) + if err := os.MkdirAll(filepath.Dir(p), 0o755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(p, []byte(f.body), 0o644); err != nil { + t.Fatal(err) + } + } + return dir +} + +// --------------------------------------------------------------------------- +// The wiring predicate's control pair. MOVED here from +// internal/scaffold/ready_ack_contract_test.go along with the predicate itself: +// `internal/validate` needs the same resolution for an author's project, and a +// predicate open-coded at two sites is wrong at one of them. +// +// It exists because the first version of this check matched a BASENAME, which +// accepted every "wrong directory" shape. Each reject case below is a shape that +// check accepted while shipping a broken app; the accept cases are the two real +// templates' shapes. Ask of any future edit: can it pass while the emitter is +// somewhere the browser will not find it? +// --------------------------------------------------------------------------- + +func TestReadyAckWiringPredicate(t *testing.T) { + const ackRel = "src/civitai-host.js" + + cases := []struct { + name string + ack string // where the emitter really is + files []gfile + wantAccept bool + // wantErr, when set, must appear in the rejection message. It pins WHICH + // branch rejected β€” without it a case can be green because some other + // check happened to reject first. + wantErr string + }{ + { + name: "accept: index.html loads it directly (the static shape)", + ack: "civitai-host.js", + files: []gfile{ + {"index.html", ``}, + {"app.js", "// app"}, + }, + wantAccept: true, + }, + { + name: "accept: the entry module imports it (the page-vite shape)", + ack: ackRel, + files: []gfile{ + {"index.html", ``}, + {"src/main.jsx", "import './civitai-host.js';\nimport React from 'react';"}, + }, + wantAccept: true, + }, + { + // NEW: an inline module in index.html executes exactly like an + // external one. Without reading inline blocks the graph would report + // itself COMPLETE while missing the emitter, which is a false finding + // at a correct project. + name: "accept: an inline module in index.html imports it", + ack: "civitai-host.js", + files: []gfile{ + {"index.html", ""}, + }, + wantAccept: true, + }, + { + // NEW: extensionless specifiers are what a bundler resolves. Pins the + // extension-candidate branch. + name: "accept: an extensionless import resolves to the emitter", + ack: ackRel, + files: []gfile{ + {"index.html", ``}, + {"src/main.jsx", "import './civitai-host';"}, + }, + wantAccept: true, + }, + { + name: "reject: right basename, wrong directory in the script tag", + ack: "civitai-host.js", + files: []gfile{ + {"index.html", ``}, + {"app.js", "// app"}, + }, + }, + { + name: "reject: right basename, unresolvable relative import", + ack: ackRel, + files: []gfile{ + {"index.html", ``}, + {"src/main.jsx", "import '../nonexistent/civitai-host.js';"}, + }, + }, + { + name: "reject: a BARE specifier that would resolve to a package", + ack: ackRel, + files: []gfile{ + {"index.html", ``}, + {"src/main.jsx", "import 'civitai-host.js';"}, + }, + }, + { + name: "reject: referenced only from an HTML comment", + ack: "civitai-host.js", + files: []gfile{ + {"index.html", "\n"}, + {"app.js", "// app"}, + }, + }, + { + name: "reject: the import is commented out but still greppable", + ack: ackRel, + files: []gfile{ + {"index.html", ``}, + {"src/main.jsx", "// import './civitai-host.js';\nimport React from 'react';"}, + }, + }, + { + name: "reject: imported by a file nothing loads", + ack: ackRel, + files: []gfile{ + {"index.html", ``}, + {"src/main.jsx", "import React from 'react';"}, + {"src/orphan.js", "import './civitai-host.js';"}, + }, + }, + { + // Pins the ErrNoScriptTags EARLY RETURN specifically. Without the + // wantErr the case passes either way β€” the fallthrough at the end + // also returns an error β€” so deleting that early return would go + // unnoticed. + name: "reject: no script tags at all", + ack: "civitai-host.js", + files: []gfile{{"index.html", "

hi

"}}, + wantErr: "no `}, + {"app.js", "// app"}, + }, + wantErr: "not a path in this project", + }, + { + // πŸ”΄ Pins the `//` half of the URL guard, which IS load-bearing: + // without it the leading slash is stripped, filepath.Join cleans the + // `..`, and this resolves to EXACTLY the emitter's path β€” an + // off-project URL would be accepted as the emitter. + name: "reject: protocol-relative URL that cleans back to the emitter path", + ack: "civitai-host.js", + files: []gfile{ + {"index.html", ``}, + {"app.js", "// app"}, + }, + wantErr: "not a path in this project", + }, + { + // Pins the `?`/`#` suffix stripping: Vite's `?url` / `?raw` suffixes + // are not part of the path, and the emitter is still the emitter. + name: "accept: entry module imports it with a Vite ?url suffix", + ack: ackRel, + files: []gfile{ + {"index.html", ``}, + {"src/main.jsx", "import './civitai-host.js?url';"}, + }, + wantAccept: true, + }, + { + // πŸ”΄ THE HEADLINE DEFECT'S SECOND LIFE. ``}, + {"app.js", "// app"}, + }, + wantAccept: true, + }, + { + // πŸ”΄ UNQUOTED ATTRIBUTE VALUES ARE LEGAL HTML. The src regex required + // quotes, so the tag was dropped, then re-classified as an INLINE + // script with an empty body β€” the reference vanished with `Complete` + // still true, and a correct `static` scaffold got the strong tier's + // warning plus --strict rc=1. A false warning at a correct project. + name: "accept: an unquoted src attribute", + ack: "civitai-host.js", + files: []gfile{ + {"index.html", ``}, + {"app.js", "// app"}, + }, + wantAccept: true, + }, + { + name: "accept: a single-quoted src attribute", + ack: "civitai-host.js", + files: []gfile{ + {"index.html", ``}, + }, + wantAccept: true, + }, + { + // πŸ”΄ A URL IS FETCHED LITERALLY. Extension guessing belongs to a + // bundler resolving a MODULE specifier, never to an HTML src: on the + // no-build `static` template the browser asks for `/civitai-host` + // and gets a 404. This was REJECTED at e800129 and accepted by the + // first version of this resolver β€” the exact "ships a 404" shape + // wiring.go claims to reject. + name: "reject: an extensionless src is a 404, not an extension to guess", + ack: "civitai-host.js", + files: []gfile{ + {"index.html", ``}, + {"app.js", "// app"}, + }, + wantErr: "no `}, + {"src/main.jsx", "import './civitai-host';"}, + }, + wantAccept: true, + }, + { + // A scheme-qualified src is a URL even without `//`. Under URL rules + // the default branch is document-relative, so without the scheme + // check `foo:bar` would resolve to a path inside the project. + name: "reject: a scheme-qualified src is a URL, not a relative path", + ack: "civitai-host.js", + files: []gfile{ + {"index.html", ``}, + {"app.js", "// app"}, + }, + wantErr: "not a path in this project", + }, + { + // πŸ”΄ `\b` IS NOT AN HTML ATTRIBUTE-NAME BOUNDARY. It matches between + // `-` and `s`, so `data-src=` was read as `src=` and the WRONG + // reference resolved β€” with `Complete` still true, so the STRONG + // tier fired. Measured on a correct `static` scaffold: `--strict` + // rc=1. `data-src` on a ``}, + {"app.js", "// app"}, + }, + wantAccept: true, + }, + { + name: "accept: x-src before the real src does not hijack it", + ack: "civitai-host.js", + files: []gfile{ + {"index.html", ``}, + {"app.js", "// app"}, + }, + wantAccept: true, + }, + { + // The inverse control: a tag carrying ONLY `data-src` has no src at + // all, so it loads nothing and cannot satisfy the wiring check. + // Without this, "do not match data-src" is indistinguishable from + // "match any attribute whose name ends in src". + name: "reject: data-src alone is not a load", + ack: "civitai-host.js", + files: []gfile{ + {"index.html", ``}, + {"app.js", "// app"}, + }, + wantErr: "no `}, + {"app.js", "// app"}, + }, + wantErr: "no ` β€” trailing whitespace before the `>` β€” is a + // valid close tag and a browser accepts it. This commit changed the + // close pattern to `` and shipped it unpinned; without + // the `\s*` the block never matches, so the inline module's imports + // are never read and a correctly wired project is rejected. + name: "accept: an inline module closed by ``", + ack: "civitai-host.js", + files: []gfile{ + {"index.html", ""}, + }, + wantAccept: true, + }, + { + // 🟑 F2, the other direction: `` closes NOTHING β€” a browser + // keeps parsing the script until a real ``, so code AFTER + // the bogus tag still executes. Widening the close pattern to + // `]*>` ends the block early and loses exactly that code. + // (My first draft of this case asserted the opposite and was simply + // wrong about HTML: it is an ACCEPT, and the accept is what + // discriminates the widening.) + name: "accept: an inline module continues past a bogus ``", + ack: "civitai-host.js", + files: []gfile{ + {"index.html", ""}, + }, + wantAccept: true, + }, + { + // 🟑 F2: the TAG boundary again, this time for the inline path. A + // `` custom element's body is never executed, so an + // import inside it is not a load. Reverting the tag boundary makes + // this element an inline script and accepts it. + name: "reject: an import inside a body is not a load", + ack: "civitai-host.js", + files: []gfile{ + {"index.html", "import './civitai-host.js';\n"}, + {"app.js", "// app"}, + }, + wantErr: "no \n"}, + {"app.js", "// app"}, + }, + wantErr: "no `}, + {"app.js", "// app"}, + }, + wantErr: "not a path in this project", + }, + { + name: "reject: an uppercase scheme is still a URL", + ack: "civitai-host.js", + files: []gfile{ + {"index.html", ``}, + {"app.js", "// app"}, + }, + wantErr: "not a path in this project", + }, + { + // πŸ”΄ The scheme regex is ANCHORED, and THE ANCHOR is what is + // load-bearing here: an unanchored pattern matches a `https:` + // sitting in a QUERY STRING and throws away a perfectly ordinary + // local reference. Dropping the `^` survived the previous sweep. + // (An earlier comment credited the ORDER of the scheme check and + // the `?`/`#` strip. It does not: two independent sweeps swapped + // them and nothing failed, because a scheme-qualified specifier + // stays scheme-qualified once its query is removed.) + name: "accept: a local src whose query string contains a URL", + ack: "civitai-host.js", + files: []gfile{ + {"index.html", ``}, + }, + wantAccept: true, + }, + { + // The `../` arm of the module resolver, which nothing pinned: an + // emitter one directory ABOVE the importing module is still inside + // the project and must resolve. + name: "accept: the entry module imports the emitter from a parent directory", + ack: "civitai-host.js", + files: []gfile{ + {"index.html", ``}, + {"src/main.jsx", "import '../civitai-host.js';"}, + }, + wantAccept: true, + }, + { + // Dynamic import with a literal specifier is a real load. + name: "accept: a dynamic import() with a literal specifier", + ack: ackRel, + files: []gfile{ + {"index.html", ``}, + {"src/main.jsx", "if (x) { import('./civitai-host.js'); }"}, + }, + wantAccept: true, + }, + { + // NEW: pins readyAckWiringDepth. Found by a SURVIVING mutant β€” + // widening Guard A's bound from 2 to 99 passed the entire suite, so + // nothing was holding the "one level of imports" contract at all. A + // TEMPLATE's emitter is meant to be loaded by the entry itself; + // burying it behind a helper module is a template smell, and this is + // the only case that can tell the two bounds apart. (`validate` uses + // the deeper default for an author's project β€” see + // TestEntryGraphBudgetsAreGaps for that bound.) + name: "reject: the emitter is two import levels below the entry", + ack: ackRel, + files: []gfile{ + {"index.html", ``}, + {"src/main.jsx", "import './helper.js';"}, + {"src/helper.js", "import './civitai-host.js';"}, + }, + wantErr: "no `}, + {"src/main.jsx", "import '../../civitai-host.js';"}, + }, + wantErr: "not a path in this project", + }, + } + + for _, c := range cases { + t.Run(c.name, func(t *testing.T) { + // The emitter itself always exists where `ack` says β€” so a rejection + // can only come from the REFERENCE, never from a missing file. + dir := writeTree(t, append([]gfile{{c.ack, "// emitter"}}, c.files...)) + chain, err := ReadyAckWiring(dir, c.ack) + if c.wantAccept { + if err != nil { + t.Fatalf("wiring check REJECTED a correctly wired project: %v", err) + } + t.Logf("accepted: %s", chain) + return + } + if err == nil { + t.Fatalf("wiring check ACCEPTED a project the browser cannot load the emitter in: %q\n"+ + "this is the basename-matching class β€” the reference must RESOLVE to the emitter's real path", chain) + } + if c.wantErr != "" && !strings.Contains(err.Error(), c.wantErr) { + t.Fatalf("rejected for the wrong reason β€” want an error mentioning %q, got:\n%v\n"+ + "a rejection from a different branch would leave the one this case exists to pin untested", + c.wantErr, err) + } + t.Logf("rejected: %v", err) + }) + } +} + +// --------------------------------------------------------------------------- +// Completeness β€” the half `internal/validate` branches on. +// +// πŸ”΄ These are the cases where the graph must admit it did not see everything. +// A caller reads `Complete == false` as "this says nothing", so a bug that +// reports a partial graph as complete converts every one of these into a +// confident false warning at a correct project. +// --------------------------------------------------------------------------- + +func TestEntryGraphCompleteness(t *testing.T) { + deps := map[string]bool{"react": true, "react-dom": true, "@civitai/blocks-react": true} + + cases := []struct { + name string + files []gfile + deps map[string]bool + opts *EntryGraphOptions + wantComplete bool + wantFiles []string // Rel paths that must be in the graph + wantGap string // substring of the reason, when incomplete + }{ + { + name: "the page-vite shape resolves completely", + files: []gfile{ + {"index.html", ``}, + {"src/main.jsx", "import './civitai-host.js';\nimport React from 'react';\n" + + "import { createRoot } from 'react-dom/client';\nimport App from './App.jsx';\nimport './index.css';"}, + {"src/civitai-host.js", "// emitter"}, + {"src/App.jsx", "import React from 'react';"}, + {"src/index.css", "body{}"}, + }, + deps: deps, + wantComplete: true, + wantFiles: []string{"index.html", "src/main.jsx", "src/civitai-host.js", "src/App.jsx", "src/index.css"}, + }, + { + // πŸ”΄ THE ALIAS CASE. A bare specifier that is not a declared + // dependency is a real file behind a bundler alias we cannot follow. + // Reporting this graph complete would warn at a correct project. + name: "a bundler alias makes the graph incomplete", + files: []gfile{ + {"index.html", ``}, + {"src/main.jsx", "import '@/civitai-host.js';"}, + {"src/civitai-host.js", "// emitter"}, + }, + deps: deps, + wantComplete: false, + wantGap: "bundler alias", + }, + { + // The positive control for the case above: the SAME shape with the + // specifier declared as a dependency is accounted for, so "a bare + // specifier is a gap" cannot be satisfied by a resolver that treats + // every bare specifier as one. + name: "a declared dependency is accounted for, not a gap", + files: []gfile{ + {"index.html", ``}, + {"src/main.jsx", "import 'react';\nimport 'react-dom/client';\nimport '@civitai/blocks-react';"}, + }, + deps: deps, + wantComplete: true, + wantFiles: []string{"index.html", "src/main.jsx"}, + }, + { + name: "no index.html at the project root is a gap, not an empty answer", + files: []gfile{ + {"src/main.jsx", "import './civitai-host.js';"}, + }, + deps: deps, + wantComplete: false, + wantGap: "index.html", + }, + { + // A reference that points at nothing means the resolver's model + // disagrees with a project that presumably builds. That is a gap, not + // evidence the browser 404s it. + name: "a reference to a file that is not there is a gap", + files: []gfile{ + {"index.html", ``}, + }, + deps: deps, + wantComplete: false, + wantGap: "does not exist", + }, + { + name: "an off-project URL is a gap", + files: []gfile{ + {"index.html", ``}, + }, + deps: deps, + wantComplete: false, + wantGap: "could not resolve", + }, + { + // πŸ”΄ A dependency name is matched at a PATH SEPARATOR, never at a + // character offset. `reactive-ui` starts with `react` and is a + // different package; accepting it would classify a real project file + // as a dependency, turning a gap into a confident wrong finding. The + // audit's finer-grained prefix mutant survived the old corpus. + name: "a bare specifier that merely starts like a dependency is still a gap", + files: []gfile{ + {"index.html", ``}, + {"src/main.jsx", "import 'reactive-ui';"}, + }, + deps: deps, + wantComplete: false, + wantGap: "bundler alias", + }, + { + // The positive control for the boundary: a real SUBPATH of a + // declared dependency is accounted for. + name: "a subpath of a declared dependency is accounted for", + files: []gfile{ + {"index.html", ``}, + {"src/main.jsx", "import 'react-dom/client';\nimport '@civitai/blocks-react/dist/x.js';"}, + }, + deps: deps, + wantComplete: true, + wantFiles: []string{"index.html", "src/main.jsx"}, + }, + { + // πŸ”΄ TRUNCATION IS A GAP. Before this, `continue`-ing at MaxDepth + // left Complete TRUE, so a CORRECT project whose ack sat below the + // bound got the strong tier's warning and --strict rc=1 β€” a finding + // built on a graph we had stopped walking. Measured at depth 10. + name: "an import below MaxDepth is a gap, not an absence", + files: []gfile{ + {"index.html", ``}, + {"a.js", "import './b.js';"}, + {"b.js", "import './c.js';"}, + {"c.js", "// end"}, + }, + deps: deps, + opts: &EntryGraphOptions{MaxDepth: 2}, + wantComplete: false, + wantGap: "stopped at import depth 2", + }, + { + // πŸ”΄ A DIAMOND AT THE BOUND IS NOT TRUNCATION, AND CALLING IT ONE + // SILENCED THE DEFECT THIS CHECK EXISTS FOR. The deepest module + // re-imports a file the walk ALREADY READ, so nothing is unseen β€” + // but the first version gapped anyway, with a message that was + // literally false about a file sitting in g.Files, and dropped the + // project to the presence tier. Measured end-to-end: an orphaned + // emitter went from `unwired`/rc=1 to SILENT/rc=0. A diamond is the + // normal shape of any real module graph, so this is not an edge + // case. A gap that over-fires is the false pass wearing a hat. + name: "a diamond at the depth bound is not truncation", + files: []gfile{ + {"index.html", ``}, + {"a.js", "import './shared.js';\nimport './b.js';"}, + {"b.js", "import './shared.js';"}, + {"shared.js", "export const s = 1;"}, + }, + deps: deps, + opts: &EntryGraphOptions{MaxDepth: 2}, + wantComplete: true, + wantFiles: []string{"index.html", "a.js", "shared.js", "b.js"}, + }, + { + // The same rule for a self-cycle: `b.js` importing itself at the + // bound leaves nothing unseen either. + name: "a self-cycle at the depth bound is not truncation", + files: []gfile{ + {"index.html", ``}, + {"a.js", "import './b.js';"}, + {"b.js", "import './b.js';"}, + }, + deps: deps, + opts: &EntryGraphOptions{MaxDepth: 2}, + wantComplete: true, + wantFiles: []string{"index.html", "a.js", "b.js"}, + }, + { + // πŸ”΄ F1: THE ANSWER MUST NOT DEPEND ON THE TEXTUAL ORDER OF TWO + // IMPORT STATEMENTS. `g.Files` records files that have been POPPED, + // so a target already ENQUEUED is absent from it β€” and evaluating + // truncation mid-walk therefore gapped, or did not, according to + // which of two same-depth imports was written first. Measured + // end-to-end on real scaffolds, flat and nested: in the losing order + // an orphaned emitter shipped SILENTLY. The check is now deferred to + // the end of the walk. These two cases are the SAME GRAPH with the + // two imports swapped, and they must agree. + name: "the bound is order-independent (import A then B)", + files: []gfile{ + {"index.html", ``}, + {"a.js", "import './b.js';\nimport './sib.js';"}, + {"b.js", "import './sib.js';"}, + {"sib.js", "export const s = 1;"}, + }, + deps: deps, + opts: &EntryGraphOptions{MaxDepth: 2}, + wantComplete: true, + wantFiles: []string{"index.html", "a.js", "b.js", "sib.js"}, + }, + { + name: "the bound is order-independent (import B then A)", + files: []gfile{ + {"index.html", ``}, + {"a.js", "import './sib.js';\nimport './b.js';"}, + {"b.js", "import './sib.js';"}, + {"sib.js", "export const s = 1;"}, + }, + deps: deps, + opts: &EntryGraphOptions{MaxDepth: 2}, + wantComplete: true, + wantFiles: []string{"index.html", "a.js", "sib.js", "b.js"}, + }, + { + // 🟑 F3: truncatedBelow resolves against the IMPORTING MODULE's + // directory, not the project root. Every other fixture here is + // root-flat, where the two coincide β€” so only a NESTED one can tell + // them apart. Resolving against the root would look for + // `/sib.js`, miss the file, and gap at a complete graph. + name: "the bound resolves against the importing module's directory", + files: []gfile{ + {"index.html", ``}, + {"src/deep/a.js", "import './b.js';\nimport './sib.js';"}, + {"src/deep/b.js", "import './sib.js';"}, + {"src/deep/sib.js", "export const s = 1;"}, + }, + deps: deps, + opts: &EntryGraphOptions{MaxDepth: 2}, + wantComplete: true, + wantFiles: []string{"index.html", "src/deep/a.js", "src/deep/b.js", "src/deep/sib.js"}, + }, + { + // 🟑 F3: the refUnresolved arm. A bundler alias at the bound is + // something we genuinely cannot follow, so it MUST gap β€” otherwise + // the strong tier fires on a graph with a hole in it. + name: "a bundler alias at the depth bound is a gap", + files: []gfile{ + {"index.html", ``}, + {"a.js", "import './b.js';"}, + {"b.js", "import '@/civitai-host.js';"}, + }, + deps: deps, + opts: &EntryGraphOptions{MaxDepth: 2}, + wantComplete: false, + wantGap: "stopped at import depth 2", + }, + { + // 🟑 F3: the resolveRefPath-error arm. A dangling import at the + // bound is the same model disagreement the normal path gaps on. + name: "a dangling import at the depth bound is a gap", + files: []gfile{ + {"index.html", ``}, + {"a.js", "import './b.js';"}, + {"b.js", "import './nope.js';"}, + }, + deps: deps, + opts: &EntryGraphOptions{MaxDepth: 2}, + wantComplete: false, + wantGap: "stopped at import depth 2", + }, + { + // The counterpart: a leaf at the bound that imports only a declared + // PACKAGE has nothing left to see, so it is NOT a gap. Without this + // the rule above degenerates into "any project as deep as the bound + // is unobservable". + name: "a package import at the depth bound is not truncated content", + files: []gfile{ + {"index.html", ``}, + {"a.js", "import './b.js';"}, + {"b.js", "import 'react';"}, + }, + deps: deps, + opts: &EntryGraphOptions{MaxDepth: 2}, + wantComplete: true, + wantFiles: []string{"index.html", "a.js", "b.js"}, + }, + { + // πŸ”΄ `entryModuleExts` decides what can PULL files into the graph. A + // browser never follows imports out of a stylesheet, so widening this + // set would let a `.css` add reachable files β€” and silence the check + // on the strength of something that is never executed. + name: "a stylesheet's imports are not followed", + files: []gfile{ + {"index.html", ``}, + {"src/main.js", "import './theme.css';"}, + {"src/theme.css", "/* x */ import './civitai-host.js';"}, + {"src/civitai-host.js", "// emitter"}, + }, + deps: deps, + wantComplete: true, + wantFiles: []string{"index.html", "src/main.js", "src/theme.css"}, + }, + { + // An index.html with nothing to load is a COMPLETE graph of one file. + // It is the shape a `validate` finding is allowed to rest on, so it + // must not be confused with "we could not look". + name: "an index.html that loads nothing is complete", + files: []gfile{{"index.html", "

hi

"}}, + deps: deps, + wantComplete: true, + wantFiles: []string{"index.html"}, + }, + } + + for _, c := range cases { + t.Run(c.name, func(t *testing.T) { + o := EntryGraphOptions{} + if c.opts != nil { + o = *c.opts + } + o.Dependencies = c.deps + g := ResolveEntryGraph(writeTree(t, c.files), o) + if g.Complete != c.wantComplete { + t.Fatalf("Complete = %v, want %v (gaps: %v)\ntrace:\n %s", + g.Complete, c.wantComplete, g.Gaps, strings.Join(g.Trace, "\n ")) + } + if !c.wantComplete && !strings.Contains(strings.Join(g.Gaps, "\n"), c.wantGap) { + t.Fatalf("gap reason does not mention %q β€” got %v\n"+ + "a gap recorded by a different branch leaves the one this case pins untested", c.wantGap, g.Gaps) + } + for _, want := range c.wantFiles { + if !graphHasRel(g, want) { + t.Fatalf("graph is missing %q; it has %v", want, graphRels(g)) + } + } + if c.wantFiles != nil && len(g.Files) != len(c.wantFiles) { + t.Fatalf("graph has %v, want exactly %v β€” an EXTRA file is as wrong as a missing one: "+ + "it means the walk reached something the browser does not load", graphRels(g), c.wantFiles) + } + }) + } +} + +// TestEntryGraphBudgetsAreGaps pins that exhausting a budget is UNOBSERVABLE +// rather than "nothing more is there". Both are silent-by-default outcomes for +// callers, and reporting either as a complete graph manufactures a finding. +func TestEntryGraphBudgetsAreGaps(t *testing.T) { + t.Run("a file over the size cap is a gap", func(t *testing.T) { + dir := writeTree(t, []gfile{ + {"index.html", ``}, + {"app.js", strings.Repeat("x", 4096)}, + }) + if g := ResolveEntryGraph(dir, EntryGraphOptions{}); !g.Complete { + t.Fatalf("positive control failed: a 4 KiB entry must resolve completely, gaps %v", g.Gaps) + } + // 64 bytes: index.html (32) still reads, app.js (4096) does not β€” so the + // gap is the ENTRY being unreadable, not the root. + g := ResolveEntryGraph(dir, EntryGraphOptions{MaxFileBytes: 64}) + if g.Complete { + t.Fatal("a file the resolver refused to read was reported as a complete graph") + } + if !strings.Contains(strings.Join(g.Gaps, "\n"), "could not read") { + t.Fatalf("gaps do not name the unread file: %v", g.Gaps) + } + }) + + t.Run("the file budget is a gap", func(t *testing.T) { + files := []gfile{{"index.html", ``}} + for i := 0; i < 5; i++ { + files = append(files, gfile{ + path: "a" + string(rune('0'+i)) + ".js", + body: "import './a" + string(rune('0'+i+1)) + ".js';", + }) + } + files = append(files, gfile{"a5.js", "// end"}) + dir := writeTree(t, files) + if g := ResolveEntryGraph(dir, EntryGraphOptions{}); !g.Complete { + t.Fatalf("positive control failed: a 7-file chain must resolve completely, gaps %v", g.Gaps) + } + g := ResolveEntryGraph(dir, EntryGraphOptions{MaxFiles: 3}) + if g.Complete { + t.Fatal("a walk that stopped at its file budget was reported as a complete graph") + } + if !strings.Contains(strings.Join(g.Gaps, "\n"), "stopped after") { + t.Fatalf("gaps do not name the budget: %v", g.Gaps) + } + }) + + t.Run("the depth bound is a gap only when there is more to see", func(t *testing.T) { + dir := writeTree(t, []gfile{ + {"index.html", ``}, + {"a.js", "import './b.js';"}, + {"b.js", "import './c.js';"}, + {"c.js", "// end"}, + }) + g := ResolveEntryGraph(dir, EntryGraphOptions{MaxDepth: 2}) + if graphHasRel(g, "c.js") { + t.Fatal("MaxDepth=2 reached a depth-3 file β€” the bound does nothing") + } + if !graphHasRel(g, "b.js") { + t.Fatalf("MaxDepth=2 did not reach the depth-2 file; graph is %v", graphRels(g)) + } + }) +} + +// inspectAll collects every file the walk read, keyed by Rel, using the same +// Inspect callback production uses. There is no retained `Code` field to read β€” +// see TestEntryGraphRetainsNoContents. +func inspectAll(t *testing.T, dir string, opts EntryGraphOptions) (*EntryGraph, map[string]string) { + t.Helper() + seen := map[string]string{} + opts.Inspect = func(f EntryFile, code string) { seen[f.Rel] = code } + return ResolveEntryGraph(dir, opts), seen +} + +// TestEntryGraphCommentsAreStripped pins that the code handed to Inspect carries +// no comments β€” the check built on it asks whether a file MENTIONS a token, and +// a comment naming it is not an implementation of it. +func TestEntryGraphCommentsAreStripped(t *testing.T) { + dir := writeTree(t, []gfile{ + {"index.html", "\n"}, + {"app.js", "// TODO: post BLOCK_READY\nvar marker = 'KEPT_IN_A_STRING';\n"}, + }) + _, code := inspectAll(t, dir, EntryGraphOptions{}) + for rel, c := range code { + if strings.Contains(c, "BLOCK_READY") { + t.Fatalf("%s kept a commented-out mention: %q", rel, c) + } + } + if !strings.Contains(code["app.js"], "KEPT_IN_A_STRING") { + t.Fatal("the strip ate code outside a comment β€” string literals must survive") + } +} + +// TestEntryGraphInspectSeesEveryFile is Inspect's POSITIVE CONTROL. Every +// assertion built on Inspect reports a NEGATIVE ("no file mentions the token"), +// and a zero from a callback wired to nothing is indistinguishable from a zero +// that means something. This asserts the callback fires once per graph file, in +// a shape where the count must be non-zero. +func TestEntryGraphInspectSeesEveryFile(t *testing.T) { + dir := writeTree(t, []gfile{ + {"index.html", ``}, + {"src/main.js", "import './a.js';\nimport './style.css';"}, + {"src/a.js", "var a = 1;"}, + {"src/style.css", "body{}"}, + }) + g, code := inspectAll(t, dir, EntryGraphOptions{}) + if !g.Complete { + t.Fatalf("fixture should resolve completely: %v", g.Gaps) + } + want := []string{"index.html", "src/main.js", "src/a.js", "src/style.css"} + if len(code) != len(want) { + t.Fatalf("Inspect fired for %v, want exactly %v", graphRels(g), want) + } + for _, rel := range want { + if _, ok := code[rel]; !ok { + t.Fatalf("Inspect never saw %s β€” a callback that misses files reports a silent false negative", rel) + } + } +} + +// TestEntryGraphRetainsNoContents pins ONE HALF of the memory contract. +// +// It asserts no graph field holds a file's contents β€” the property whose absence +// let a 200-module graph inside both budgets peak 421-439 MB. +// +// πŸ”΄ WHAT IT CANNOT SEE, STATED BECAUSE IT WAS ONCE CITED AS IF IT COULD: the +// ALIASING half. A Go substring shares its parent's backing array, so an +// un-cloned import specifier pins its whole file (measured: 558-628 MB with +// `Code` already gone). `strings.Contains` below reads the LOGICAL string, so it +// passes identically at 558 MB and at 33 MB. Only `strings.Clone` in the walk +// prevents that, and only a live RSS measurement on a fixture whose modules are +// large AND carry imports can observe it β€” see the table in +// EntryGraphOptions.Inspect. Do not read a green here as "memory is fine". +func TestEntryGraphRetainsNoContents(t *testing.T) { + dir := writeTree(t, []gfile{ + {"index.html", ``}, + {"app.js", "var UNIQUE_TOKEN_NOT_IN_ANY_FIELD = 1;"}, + }) + g, code := inspectAll(t, dir, EntryGraphOptions{}) + if !strings.Contains(code["app.js"], "UNIQUE_TOKEN_NOT_IN_ANY_FIELD") { + t.Fatal("positive control failed: Inspect did not receive the file's contents") + } + for _, f := range g.Files { + for _, field := range []string{f.Path, f.Rel, f.Spec} { + if strings.Contains(field, "UNIQUE_TOKEN_NOT_IN_ANY_FIELD") { + t.Fatalf("%s retains file CONTENTS in a graph field (%q) β€” the graph must hold one file's "+ + "bytes at a time, like the tree scan", f.Rel, field) + } + } + } +} + +// TestEntryGraphRootContainment pins BOTH arms of the containment check. +// +// 🟒 Dropping only the `rel == ".."` arm admits a file OUTSIDE the project with +// `Complete` still true β€” the project's own emitter would then be "satisfied" by +// a same-named file in a sibling checkout. It is reachable through directory- +// index resolution: `import '..'` resolves to the parent DIRECTORY, and the +// module resolver will happily take `/index.js`. +func TestEntryGraphRootContainment(t *testing.T) { + base := t.TempDir() + // A file that exists OUTSIDE the project root, reachable only by escaping it. + if err := os.WriteFile(filepath.Join(base, "index.js"), []byte("// outside\n"), 0o644); err != nil { + t.Fatal(err) + } + root := filepath.Join(base, "proj") + for _, f := range []gfile{ + {"index.html", ``}, + {"src/main.js", "import '../..';"}, + } { + p := filepath.Join(root, filepath.FromSlash(f.path)) + if err := os.MkdirAll(filepath.Dir(p), 0o755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(p, []byte(f.body), 0o644); err != nil { + t.Fatal(err) + } + } + // Positive control: the escape target really is resolvable, so a green below + // cannot mean "there was nothing to admit". + if _, err := os.Stat(filepath.Join(base, "index.js")); err != nil { + t.Fatalf("fixture missing its off-project target: %v", err) + } + g := ResolveEntryGraph(root, EntryGraphOptions{}) + for _, f := range g.Files { + if !strings.HasPrefix(f.Path, root) { + t.Fatalf("the graph admitted %s, which is OUTSIDE the project root %s β€” a same-named file in a "+ + "sibling checkout would satisfy this project's wiring check", f.Path, root) + } + } + if g.Complete { + t.Fatal("a reference escaping the project root must be a GAP: we stopped modelling there") + } +} + +func graphRels(g *EntryGraph) []string { + out := make([]string, 0, len(g.Files)) + for _, f := range g.Files { + out = append(out, f.Rel) + } + return out +} + +func graphHasRel(g *EntryGraph, rel string) bool { + for _, f := range g.Files { + if f.Rel == rel { + return true + } + } + return false +} diff --git a/internal/blockproto/wiring.go b/internal/blockproto/wiring.go new file mode 100644 index 00000000..0fced14f --- /dev/null +++ b/internal/blockproto/wiring.go @@ -0,0 +1,64 @@ +package blockproto + +// wiring.go answers "is the vendored emitter at ackRel actually LOADED by this +// project?" on top of the entry graph. +// +// πŸ”΄ Every reference is RESOLVED to a path and compared with where the emitter +// actually IS. It is deliberately NOT a basename match. A basename match is a +// SPELLED check rather than a structural one, and it passes while the hazard +// exists in a different shape β€” both of these were MEASURED surviving the +// entire suite before the original (test-only) version of this was rewritten: +// +// static/index.html src="./vendor/civitai-host.js" -> ships a 404 +// page-vite/main.jsx import '../nonexistent/civitai-host.js' -> build fails +// +// Both reproduce #206 with every check green. + +import ( + "os" + "path/filepath" + "strings" +) + +// readyAckWiringDepth keeps Guard A's original reach: index.html's ``}, - {"app.js", "// app"}, - }, - wantAccept: true, - }, - { - name: "accept: the entry module imports it (the page-vite shape)", - ack: ackRel, - files: []file{ - {"index.html", ``}, - {"src/main.jsx", "import './civitai-host.js';\nimport React from 'react';"}, - }, - wantAccept: true, - }, - { - name: "reject: right basename, wrong directory in the script tag", - ack: "civitai-host.js", - files: []file{ - {"index.html", ``}, - {"app.js", "// app"}, - }, - }, - { - name: "reject: right basename, unresolvable relative import", - ack: ackRel, - files: []file{ - {"index.html", ``}, - {"src/main.jsx", "import '../nonexistent/civitai-host.js';"}, - }, - }, - { - name: "reject: a BARE specifier that would resolve to a package", - ack: ackRel, - files: []file{ - {"index.html", ``}, - {"src/main.jsx", "import 'civitai-host.js';"}, - }, - }, - { - name: "reject: referenced only from an HTML comment", - ack: "civitai-host.js", - files: []file{ - {"index.html", "\n"}, - {"app.js", "// app"}, - }, - }, - { - name: "reject: the import is commented out but still greppable", - ack: ackRel, - files: []file{ - {"index.html", ``}, - {"src/main.jsx", "// import './civitai-host.js';\nimport React from 'react';"}, - }, - }, - { - name: "reject: imported by a file nothing loads", - ack: ackRel, - files: []file{ - {"index.html", ``}, - {"src/main.jsx", "import React from 'react';"}, - {"src/orphan.js", "import './civitai-host.js';"}, - }, - }, - { - // Pins the errNoScriptTags EARLY RETURN specifically. Without the - // wantErr the case passes either way β€” the fallthrough at the end - // also returns an error β€” so deleting that early return would go - // unnoticed. - name: "reject: no script tags at all", - ack: "civitai-host.js", - files: []file{{"index.html", "

hi

"}}, - wantErr: "no `}, - {"app.js", "// app"}, - }, - wantErr: "not a path in this project", - }, - { - // πŸ”΄ Pins the `//` half of the URL guard, which IS load-bearing: - // without it the leading slash is stripped, filepath.Join cleans the - // `..`, and this resolves to EXACTLY the emitter's path β€” an - // off-project URL would be accepted as the emitter. - name: "reject: protocol-relative URL that cleans back to the emitter path", - ack: "civitai-host.js", - files: []file{ - {"index.html", ``}, - {"app.js", "// app"}, - }, - wantErr: "not a path in this project", - }, - { - // Pins the `?`/`#` suffix stripping: Vite's `?url` / `?raw` suffixes - // are not part of the path, and the emitter is still the emitter. - name: "accept: entry module imports it with a Vite ?url suffix", - ack: ackRel, - files: []file{ - {"index.html", ``}, - {"src/main.jsx", "import './civitai-host.js?url';"}, - }, - wantAccept: true, - }, - } - - for _, c := range cases { - t.Run(c.name, func(t *testing.T) { - dir := t.TempDir() - // The emitter itself always exists where `ack` says β€” so a - // rejection can only come from the REFERENCE, never from a missing - // file. - all := append([]file{{c.ack, "// emitter"}}, c.files...) - for _, f := range all { - p := filepath.Join(dir, filepath.FromSlash(f.path)) - if err := os.MkdirAll(filepath.Dir(p), 0o755); err != nil { - t.Fatal(err) - } - if err := os.WriteFile(p, []byte(f.body), 0o644); err != nil { - t.Fatal(err) - } - } - chain, err := readyAckWiring(dir, c.ack) - if c.wantAccept { - if err != nil { - t.Fatalf("wiring check REJECTED a correctly wired project: %v", err) - } - t.Logf("accepted: %s", chain) - return - } - if err == nil { - t.Fatalf("wiring check ACCEPTED a project the browser cannot load the emitter in: %q\n"+ - "this is the basename-matching class β€” the reference must RESOLVE to the emitter's real path", chain) - } - if c.wantErr != "" && !strings.Contains(err.Error(), c.wantErr) { - t.Fatalf("rejected for the wrong reason β€” want an error mentioning %q, got:\n%v\n"+ - "a rejection from a different branch would leave the one this case exists to pin untested", - c.wantErr, err) - } - t.Logf("rejected: %v", err) - }) - } -} - // --------------------------------------------------------------------------- // The per-template contract. // --------------------------------------------------------------------------- @@ -449,7 +275,7 @@ func TestScaffoldedPageTemplatesShipTheReadyAck(t *testing.T) { // ASSERTION 2 β€” the copy is actually LOADED. Byte-equality of an // orphan file proves nothing about the running app. t.Run("reached from the rendered entry point", func(t *testing.T) { - chain, err := readyAckWiring(dest, rel) + chain, err := blockproto.ReadyAckWiring(dest, rel) if err != nil { t.Fatalf("%s ships %s but nothing loads it: %v\n"+ "Reference it from index.html (a