From 94c804500118add3ac75b511186100ef78e1c9dd Mon Sep 17 00:00:00 2001 From: ZacxDev Date: Wed, 5 Aug 2026 23:43:38 -0500 Subject: [PATCH 1/7] fix(validate): the ready-ack advisory passed an emitter nothing loads MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit `civitai app validate`'s page-without-ack advisory told authors to do two things — copy `civitai-host.js` in, and LOAD it from index.html or the entry module — and verified only the first. Measured on a genuinely pre-fix scaffold (built from the CLI at 0ce0025): with the emitter copied in and never referenced, `civitai app validate --strict` printed `✓ … is valid` and exited 0 for an app that was still exactly as broken as before #206. An orphan file containing the literal anywhere in the tree passed identically. The check now resolves the ENTRY GRAPH — index.html, its ``) + reSrcAttr = regexp.MustCompile(`(?is)\bsrc\s*=\s*["']`) + // Captures the SPECIFIER of an import / re-export / require, so it can be + // resolved. Matching a basename inside the specifier is what let + // `import '../nonexistent/civitai-host.js'` through. + reJSImport = regexp.MustCompile(`(?:\bimport\s*\(?\s*|\bfrom\s+|\brequire\(\s*)['"]([^'"]+)['"]`) +) diff --git a/internal/blockproto/entrygraph_test.go b/internal/blockproto/entrygraph_test.go new file mode 100644 index 00000000..e14ce013 --- /dev/null +++ b/internal/blockproto/entrygraph_test.go @@ -0,0 +1,456 @@ +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, + }, + { + // NEW: pins the ROOT CONTAINMENT guard. Without it the `..` climbs out + // of the project and — if a same-named file happens to sit beside it — + // a sibling checkout's emitter would satisfy this project's wiring. + name: "reject: an import that escapes the project root", + ack: "civitai-host.js", + files: []gfile{ + {"index.html", ``}, + {"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 + 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", + }, + { + // 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) { + g := ResolveEntryGraph(writeTree(t, c.files), EntryGraphOptions{Dependencies: c.deps}) + 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)) + } + }) +} + +// TestEntryGraphCommentsAreStripped pins that the graph's Code 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"}, + }) + g := ResolveEntryGraph(dir, EntryGraphOptions{}) + for _, f := range g.Files { + if strings.Contains(f.Code, "BLOCK_READY") { + t.Fatalf("%s kept a commented-out mention: %q", f.Rel, f.Code) + } + } + i := g.FileAt(filepath.Join(dir, "app.js")) + if i < 0 || !strings.Contains(g.Files[i].Code, "KEPT_IN_A_STRING") { + t.Fatal("the strip ate code outside a comment — string literals must survive") + } +} + +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 ` in `index.html`, or an > `import './civitai-host.js';` at the top of the entry module `index.html` -> loads. Until v0.1.90 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. +> 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: @@ -700,7 +701,8 @@ Four things follow: resolution is complete you get a precise finding — including "you have an emitter, but nothing loads it". When it *isn't* — no `index.html` at your project root, a bundler alias (`import '@/…'`), a reference to a file that - isn't there — it falls back to scanning your whole tree for the text, and the + isn't there, an import chain deeper than it follows — it falls back to + scanning your whole tree for the text, and the warning **says so in as many words**: *"it did NOT check that the file is loaded"*. Read that sentence as it is written; in that mode, adding the emitter without referencing it will silence the warning and leave the app broken. diff --git a/internal/blockproto/comments.go b/internal/blockproto/comments.go index 4e3322fc..1b01d00b 100644 --- a/internal/blockproto/comments.go +++ b/internal/blockproto/comments.go @@ -77,11 +77,19 @@ func StripJSComments(src string) string { i++ } case c == '/' && i+1 < len(src) && src[i+1] == '*': - i += 2 - for i+1 < len(src) && !(src[i] == '*' && src[i+1] == '/') { - i++ + // 🔴 UNTERMINATED — the same rule StripHTMLComments carries, for the + // same reason, which used to be documented only on that half. An + // unclosed `/*` swallowed the rest of the file: lossy in the + // EXPENSIVE direction, because everything below it disappears — + // including an emitter — and the author gets a warning about a + // correct project. Text after an unclosed marker is not evidence of + // a comment, it is evidence the file is not what we assumed. + end := strings.Index(src[i+2:], "*/") + if end < 0 { + b.WriteString(src[i:]) + return b.String() } - i = min(i+2, len(src)) + i += 2 + end + 2 case c == '\'' || c == '"' || c == '`': quote := c b.WriteByte(c) diff --git a/internal/blockproto/comments_test.go b/internal/blockproto/comments_test.go new file mode 100644 index 00000000..5a2b6861 --- /dev/null +++ b/internal/blockproto/comments_test.go @@ -0,0 +1,147 @@ +package blockproto + +import "testing" + +// The comment stripper decides whether a mention of a token is EVIDENCE or just +// prose. Both directions are expensive: +// +// strip too little -> a comment naming BLOCK_READY silences the check at a +// genuinely broken app (false negative) +// strip too much -> real code disappears and a correct project is warned at +// (false positive, the one AGENTS.md item 10 exists for) +// +// These cases are built so a widening or narrowing of each internal branch +// changes the ANSWER, not just the whitespace. Several exist because the audit's +// sweep found the branch unpinned. + +func TestStripHTMLComments(t *testing.T) { + cases := []struct{ name, src, want string }{ + { + // 🔴 The TERMINATOR is `-->`, three characters. Widening it to `->` + // ends the comment early, so everything after the arrow becomes + // "code" — a commented-out mention turns into evidence and the check + // goes silently quiet at a broken app. An `->` inside a comment is + // ordinary prose (and an arrow function's `=>` is one keystroke away). + name: "an arrow inside a comment does not terminate it", + src: "after", + want: "after", + }, + { + name: "a normal comment is removed", + src: "ac", + want: "ac", + }, + { + // 🔴 UNTERMINATED: keep the tail verbatim. Dropping it is lossy in + // the expensive direction — everything below an unclosed marker + // disappears, including an emitter. + name: "an unterminated comment keeps the rest of the file", + src: "abc", + want: "abc", + }, + } + for _, c := range cases { + t.Run(c.name, func(t *testing.T) { + if got := StripHTMLComments(c.src); got != c.want { + t.Fatalf("StripHTMLComments(%q) = %q, want %q", c.src, got, c.want) + } + }) + } +} + +func TestStripJSComments(t *testing.T) { + cases := []struct{ name, src, want string }{ + { + name: "a line comment goes, the code after it stays", + src: "// BLOCK_READY\nkeep;", + want: "\nkeep;", + }, + { + name: "a block comment goes", + src: "a;/* BLOCK_READY */b;", + want: "a;b;", + }, + { + // 🔴 UNTERMINATED `/*` — the same rule the HTML half carries, which + // used to be documented and implemented only there. Swallowing the + // tail deletes an emitter and warns at a correct project. + name: "an unterminated block comment keeps the rest of the file", + src: "a;/* oops\nBLOCK_READY;", + want: "a;/* oops\nBLOCK_READY;", + }, + { + // The string branch: a URL is not a comment. The ack is on the SAME + // LINE on purpose — with quote handling defeated the `//` in + // `https://` swallows everything after it. + name: "a URL in a string does not open a comment", + src: "var u = 'https://x'; BLOCK_READY;", + want: "var u = 'https://x'; BLOCK_READY;", + }, + { + // The BACKTICK branch, which nothing pinned: a template literal is a + // string too, and a `//` inside one is not a comment. + name: "a template literal protects its contents", + src: "var u = `https://x`; BLOCK_READY;", + want: "var u = `https://x`; BLOCK_READY;", + }, + { + // The BACKSLASH-ESCAPE branch, which nothing pinned. Without it the + // escaped quote is read as the string's END, so the rest of the line + // is parsed as code — and the `//` that follows becomes a comment + // that eats the ack. + name: "an escaped quote does not end the string early", + src: `var s = 'it\'s // not a comment'; BLOCK_READY;`, + want: `var s = 'it\'s // not a comment'; BLOCK_READY;`, + }, + { + // The inverse control for the branch above: an escape must not make + // the stripper run past a string that really does end. + name: "an escaped backslash still ends the string", + src: `var s = 'x\\'; // gone` + "\nBLOCK_READY;", + want: `var s = 'x\\'; ` + "\nBLOCK_READY;", + }, + } + for _, c := range cases { + t.Run(c.name, func(t *testing.T) { + if got := StripJSComments(c.src); got != c.want { + t.Fatalf("StripJSComments(%q) = %q, want %q", c.src, got, c.want) + } + }) + } +} + +// TestStripCommentsForExtGate pins the extension gate in BOTH directions. +// +// 🔴 Running StripHTMLComments over `.js` made an ordinary `var OPEN = '';\n" + if got := StripCommentsForExt(js, ".js"); !contains(got, "BLOCK_READY") { + t.Fatalf(".js lost code between two HTML markers in strings: %q", got) + } + const html = "\n" + 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 index b9609ed0..5f384092 100644 --- a/internal/blockproto/entrygraph.go +++ b/internal/blockproto/entrygraph.go @@ -14,16 +14,47 @@ package blockproto // 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. + // correct project. Their specifiers are MODULE syntax, resolved against the + // document's directory (the project root). for _, m := range reScriptBlock.FindAllStringSubmatch(html, -1) { - if reSrcAttr.MatchString(m[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: 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. + // reScriptOpen captures a `` so an INLINE + // module's imports can be read. Group 1 is the attribute list, group 2 the + // body. reScriptBlock = regexp.MustCompile(`(?is)]*)>(.*?)`) - reSrcAttr = regexp.MustCompile(`(?is)\bsrc\s*=\s*["']`) - // Captures the SPECIFIER of an import / re-export / require, so it can be - // resolved. Matching a basename inside the specifier is what let + // reSrcAttr captures a src value in any of HTML's three quoting forms. + reSrcAttr = regexp.MustCompile(`(?is)\bsrc\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 index cd57a100..2bab2ba6 100644 --- a/internal/blockproto/entrygraph_test.go +++ b/internal/blockproto/entrygraph_test.go @@ -187,6 +187,118 @@ func TestReadyAckWiringPredicate(t *testing.T) { }, 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", + }, + { + // 🔴 The scheme regex is ANCHORED, and the anchor is load-bearing: + // the scheme check runs BEFORE the `?`/`#` strip, so 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. A cache-busting or proxy query with a + // URL in it is ordinary. + 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 @@ -262,6 +374,7 @@ func TestEntryGraphCompleteness(t *testing.T) { 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 @@ -338,6 +451,82 @@ func TestEntryGraphCompleteness(t *testing.T) { 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", + }, + { + // 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 @@ -352,7 +541,12 @@ func TestEntryGraphCompleteness(t *testing.T) { for _, c := range cases { t.Run(c.name, func(t *testing.T) { - g := ResolveEntryGraph(writeTree(t, c.files), EntryGraphOptions{Dependencies: c.deps}) + 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 ")) @@ -436,26 +630,89 @@ func TestEntryGraphBudgetsAreGaps(t *testing.T) { }) } -// TestEntryGraphCommentsAreStripped pins that the graph's Code 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. +// 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"}, }) - g := ResolveEntryGraph(dir, EntryGraphOptions{}) - for _, f := range g.Files { - if strings.Contains(f.Code, "BLOCK_READY") { - t.Fatalf("%s kept a commented-out mention: %q", f.Rel, f.Code) + _, 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) } } - i := g.FileAt(filepath.Join(dir, "app.js")) - if i < 0 || !strings.Contains(g.Files[i].Code, "KEPT_IN_A_STRING") { + 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 the memory contract STRUCTURALLY. +// +// 🔴 The first version stored every graph file's stripped contents on EntryFile +// and peaked 410 MB RSS on a 200-module graph entirely INSIDE the file-count and +// size budgets — against ~17 MB before the graph existed, and past the 316 MB +// event those budgets were sized against in the first place. A benchmark would +// drift; this asserts the type itself cannot hold contents, which is the +// property that made the regression possible. +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) + } + } + } +} + func graphRels(g *EntryGraph) []string { out := make([]string, 0, len(g.Files)) for _, f := range g.Files { diff --git a/internal/validate/readyack.go b/internal/validate/readyack.go index acad6c6a..17c94a17 100644 --- a/internal/validate/readyack.go +++ b/internal/validate/readyack.go @@ -199,13 +199,9 @@ func readyAckChecks(dir string, generic any) []string { return nil } - graph := blockproto.ResolveEntryGraph(dir, blockproto.EntryGraphOptions{ - MaxFiles: maxAckGraphFiles, - MaxFileBytes: maxAckFileBytes, - Dependencies: deps, - }) + graph, loadedPostsAck := resolveLoadedFiles(dir, deps) if graph.Complete { - if graphPostsReadyAck(graph) { + if loadedPostsAck { return nil } // Reachability tier: nothing the browser loads posts the message. @@ -222,19 +218,36 @@ func readyAckChecks(dir string, generic any) []string { return []string{readyAckAdvicePresenceOnly} } -// graphPostsReadyAck reports whether any file the browser loads mentions the -// message outside a comment. blockproto has already stripped comments per -// extension; readyAckSourceExts decides what counts as code. -func graphPostsReadyAck(g *blockproto.EntryGraph) bool { - for _, f := range g.Files { - if !readyAckSourceExts[strings.ToLower(filepath.Ext(f.Rel))] { - continue - } - if strings.Contains(f.Code, readyAckType) { - return true - } - } - return false +// resolveLoadedFiles walks the entry graph and reports whether any file the +// BROWSER LOADS mentions the message outside a comment. +// +// 🔴 The answer is accumulated through `Inspect`, not read off a retained field. +// The graph hands each file's contents over while they are in hand and keeps +// none of them, so this costs ONE file of memory — the same discipline the tree +// scan above follows. The first version stored every graph file's stripped +// contents on the EntryFile and peaked 410 MB RSS on a 200-module graph entirely +// INSIDE these budgets, against ~17 MB before the graph existed: a check whose +// caps exist precisely so `validate` cannot become a memory event, exceeding the +// 316 MB figure those caps were sized against. `app submit` pays this too. +func resolveLoadedFiles(dir string, deps map[string]bool) (*blockproto.EntryGraph, bool) { + found := false + g := blockproto.ResolveEntryGraph(dir, blockproto.EntryGraphOptions{ + MaxFiles: maxAckGraphFiles, + MaxFileBytes: maxAckFileBytes, + Dependencies: deps, + Inspect: func(f blockproto.EntryFile, code string) { + // readyAckSourceExts gates BOTH tiers: a `.css` an entry module + // imports really is loaded by the browser and really cannot + // implement a handshake, so it is in the graph but is not evidence. + if !readyAckSourceExts[strings.ToLower(filepath.Ext(f.Rel))] { + return + } + if strings.Contains(code, readyAckType) { + found = true + } + }, + }) + return g, found } // declaresPage reports whether the manifest declares a non-null `page` surface. diff --git a/internal/validate/readyack_test.go b/internal/validate/readyack_test.go index f6f75ad4..58f23837 100644 --- a/internal/validate/readyack_test.go +++ b/internal/validate/readyack_test.go @@ -753,9 +753,44 @@ func TestReadyAckSymlinkCycleTerminates(t *testing.T) { } } +// TestReadyAckCapValues pins the caps INDEPENDENTLY of the code under test. +// +// 🔴 TestReadyAckCapsAreUnobservable below sizes its fixtures FROM these +// constants, so a mutant that raises one does not fail — it just allocates. An +// audit mutant setting maxAckFileBytes to 1<<40 hung the suite twice instead of +// going red. A literal here is the only thing that can see that, and it is also +// the only record that these numbers are a deliberate cost decision rather than +// whatever the code happens to say. +func TestReadyAckCapValues(t *testing.T) { + if maxAckFileBytes != 2<<20 { + t.Errorf("maxAckFileBytes = %d, want %d (2 MiB) — these caps exist because `validate` must not "+ + "become a memory event; raising one silently makes every cap fixture allocate instead of fail", + maxAckFileBytes, 2<<20) + } + if maxAckScanFiles != 5000 { + t.Errorf("maxAckScanFiles = %d, want 5000", maxAckScanFiles) + } + if maxAckGraphFiles != 200 { + t.Errorf("maxAckGraphFiles = %d, want 200", maxAckGraphFiles) + } +} + // 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. +// +// It sizes its fixtures from the constants on purpose (a hardcoded 2 MiB would +// silently stop exercising the branch if the cap moved); TestReadyAckCapValues +// is what makes that safe. func TestReadyAckCapsAreUnobservable(t *testing.T) { + // 🔴 Sizing a fixture from the constant under test turns a raised cap into an + // ALLOCATION rather than a failure: a 1<<40 mutant hung this suite twice + // instead of going red. TestReadyAckCapValues is the real guard; this bound + // makes the hang a fast, readable failure instead. + if maxAckFileBytes > 8<<20 || maxAckScanFiles > 20000 { + t.Fatalf("the caps are too large to exercise (maxAckFileBytes=%d, maxAckScanFiles=%d) — this test "+ + "builds fixtures from them, so it would allocate instead of testing. See TestReadyAckCapValues.", + maxAckFileBytes, maxAckScanFiles) + } 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": ``, @@ -833,24 +868,65 @@ func TestReadyAckAdviceIsActionable(t *testing.T) { // the reachability tier tells an author their app is checked when it is not — // which is how "copy the emitter in" became a green check for a broken app. So // each tier must name what it did, and the weak one must name what it did not. +// 🔴 AN EARLIER VERSION OF THIS TEST WAS HALF VACUOUS, and an audit mutant +// proved it. It asserted the two strong advisories contain "index.html loads" — +// but that phrase comes from the SHARED `readyAckRemedy` fragment, which EVERY +// advisory carries, including the weak one. So replacing the unwired advisory's +// entire headline with "but something is off" PASSED. That is the spelled-guard +// class: a check satisfied by a different feature's text. +// +// Every literal below appears in exactly ONE tier's own diagnosis, and each is +// paired with an INVERSE assertion that no other tier carries it — so a rewrite +// that blurs two tiers together fails in both directions. func TestReadyAckAdvisoriesStateTheirOwnStrength(t *testing.T) { - if !strings.Contains(readyAckAdvicePresenceOnly, "did NOT check that the file is loaded") { - t.Errorf("the presence-only advisory does not disclose that it cannot see wiring — an author who "+ - "reads it as the reachability tier will copy the emitter in, be silenced, and stay broken:\n%s", - readyAckAdvicePresenceOnly) - } - // And the two reachability advisories must NOT carry that disclaimer: they - // really did resolve the entry graph, and disclaiming it would train authors - // to ignore the one message that is strong. - for name, advice := range map[string]string{ - "unwired": readyAckAdviceUnwired, - "missing": readyAckAdviceMissing, - } { - if strings.Contains(advice, "did NOT check that the file is loaded") { - t.Errorf("the %s advisory (reachability tier) disclaims a check it DID perform:\n%s", name, advice) - } - if !strings.Contains(advice, "index.html loads") { - t.Errorf("the %s advisory does not say it resolved what index.html loads:\n%s", name, advice) + const disclosure = "did NOT check that the file is loaded" + // The operative half of the weak tier's disclosure: without this sentence an + // author reads "add the emitter", stops, and stays broken — which is the + // defect. Deleting it was a surviving mutant. + const operative = "will silence this warning" + + perTier := []struct { + name string + advice string + // own are literals this tier's DIAGNOSIS must carry, and which no other + // tier may carry. + own []string + }{ + {"unwired", readyAckAdviceUnwired, []string{ + "DOES contain", // it found the message… + "nothing index.html loads reaches it", // …and nothing loads it + "orphan", // named for what it is + }}, + {"missing", readyAckAdviceMissing, []string{ + "nothing index.html loads posts it either", // resolved, and absent + }}, + {"presence-only", readyAckAdvicePresenceOnly, []string{ + disclosure, + operative, + "could not resolve the files your", + }}, + } + + for _, tier := range perTier { + for _, lit := range tier.own { + if !strings.Contains(tier.advice, lit) { + t.Errorf("the %s advisory no longer says %q — that literal is this tier's whole diagnosis, "+ + "and without it the message does not tell an author WHAT WAS FOUND:\n%s", + tier.name, lit, tier.advice) + } + // The inverse control: no OTHER tier may claim it. This is what + // makes the assertion above a statement about THIS tier rather than + // about the shared remedy fragment every advisory carries. + for _, other := range perTier { + if other.name == tier.name { + continue + } + if strings.Contains(other.advice, lit) { + t.Errorf("the %s advisory carries %q, which belongs to the %s tier — the tiers are no "+ + "longer distinguishable by their text, so a reader cannot tell which check ran:\n%s", + other.name, lit, tier.name, other.advice) + } + } } } } diff --git a/internal/validate/readyack_wiring_test.go b/internal/validate/readyack_wiring_test.go index 13be686c..31fc8ebe 100644 --- a/internal/validate/readyack_wiring_test.go +++ b/internal/validate/readyack_wiring_test.go @@ -12,6 +12,7 @@ package validate // the near-miss shapes that made the old check look green. import ( + "fmt" "os" "path/filepath" "strings" @@ -172,6 +173,103 @@ func TestWiredEmitterIsSilent(t *testing.T) { }) } +// TestHTMLSrcIsAURLNotAModuleSpecifier is the end-to-end guard for the audit's +// root cause: ``, "") + wantAckKind(t, dir, "unwired") + }) + } + + t.Run("an extensionless src is a 404, not an extension to guess", func(t *testing.T) { + // 🔴 A browser fetches the literal path. On the no-build `static` + // template ``, "") + editFile(t, dir, "index.html", ``, ``) + const depth = blockproto.DefaultEntryMaxDepth + 3 + for i := 0; i < depth; i++ { + next := fmt.Sprintf("./m%d.js", i+1) + if i == depth-1 { + next = "./" + blockproto.ReadyAckFilename + } + if err := os.WriteFile(filepath.Join(dir, fmt.Sprintf("m%d.js", i)), + []byte("import '"+next+"';\n"), 0o600); err != nil { + t.Fatal(err) + } + } + g, _ := resolveLoadedFiles(dir, nil) + if g.Complete { + t.Fatalf("the walk stopped at the depth bound and still reported a COMPLETE graph — every finding "+ + "built on it is a claim about files we chose not to read\ngaps: %v", g.Gaps) + } + // The observable consequence: no strong-tier warning at a project that works. + wantAckKind(t, dir, "") +} + // --------------------------------------------------------------------------- // THE DECIDABILITY BOUNDARY, asserted explicitly. // From 6288c88340ad8e8543eb132f80e655f2154c2dd9 Mon Sep 17 00:00:00 2001 From: ZacxDev Date: Thu, 6 Aug 2026 14:31:51 -0500 Subject: [PATCH 4/7] fix(validate): HTML name boundaries, an over-firing gap, and the other half of the memory fix MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Round-2 delta audit found two REGRESSIONS from the previously-audited tip and one claim I had marked fixed that was only half fixed. All reproduced locally before any change. N2 — `\b` is not an HTML attribute-name boundary. It matches between `-` and `s`, so `\bsrc\s*=` read `data-src=`/`x-src=` as `src=`, and `` as a script. Measured on a CORRECT static scaffold with `` so an INLINE // module's imports can be read. Group 1 is the attribute list, group 2 the // body. - reScriptBlock = regexp.MustCompile(`(?is)]*)>(.*?)`) - // reSrcAttr captures a src value in any of HTML's three quoting forms. - reSrcAttr = regexp.MustCompile(`(?is)\bsrc\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s"'` + "`" + `=<>]+))`) + 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. + 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. diff --git a/internal/blockproto/entrygraph_test.go b/internal/blockproto/entrygraph_test.go index 2bab2ba6..eda8ab87 100644 --- a/internal/blockproto/entrygraph_test.go +++ b/internal/blockproto/entrygraph_test.go @@ -264,12 +264,96 @@ func TestReadyAckWiringPredicate(t *testing.T) { wantErr: "not a path in this project", }, { - // 🔴 The scheme regex is ANCHORED, and the anchor is load-bearing: - // the scheme check runs BEFORE the `?`/`#` strip, so 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. A cache-busting or proxy query with a - // URL in it is ordinary. + // 🔴 `\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 \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{ @@ -495,6 +579,42 @@ func TestEntryGraphCompleteness(t *testing.T) { 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"}, + }, { // 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 @@ -686,14 +806,19 @@ func TestEntryGraphInspectSeesEveryFile(t *testing.T) { } } -// TestEntryGraphRetainsNoContents pins the memory contract STRUCTURALLY. +// TestEntryGraphRetainsNoContents pins ONE HALF of the memory contract. // -// 🔴 The first version stored every graph file's stripped contents on EntryFile -// and peaked 410 MB RSS on a 200-module graph entirely INSIDE the file-count and -// size budgets — against ~17 MB before the graph existed, and past the 316 MB -// event those budgets were sized against in the first place. A benchmark would -// drift; this asserts the type itself cannot hold contents, which is the -// property that made the regression possible. +// 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", ``}, @@ -713,6 +838,49 @@ func TestEntryGraphRetainsNoContents(t *testing.T) { } } +// 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 { diff --git a/internal/validate/readyack.go b/internal/validate/readyack.go index 17c94a17..61293abb 100644 --- a/internal/validate/readyack.go +++ b/internal/validate/readyack.go @@ -221,14 +221,17 @@ func readyAckChecks(dir string, generic any) []string { // resolveLoadedFiles walks the entry graph and reports whether any file the // BROWSER LOADS mentions the message outside a comment. // -// 🔴 The answer is accumulated through `Inspect`, not read off a retained field. -// The graph hands each file's contents over while they are in hand and keeps -// none of them, so this costs ONE file of memory — the same discipline the tree -// scan above follows. The first version stored every graph file's stripped -// contents on the EntryFile and peaked 410 MB RSS on a 200-module graph entirely -// INSIDE these budgets, against ~17 MB before the graph existed: a check whose -// caps exist precisely so `validate` cannot become a memory event, exceeding the -// 316 MB figure those caps were sized against. `app submit` pays this too. +// 🔴 The answer is accumulated through `Inspect`, not read off a retained field, +// so this costs O(one file) rather than O(graph) — the same discipline the tree +// scan above follows. Getting there took TWO fixes, and the intermediate state +// is why this comment now carries numbers instead of an adjective: storing every +// file's stripped contents on EntryFile peaked 421-439 MB on a 200-module graph +// entirely INSIDE these budgets, and dropping that field still left 558-628 MB +// because an un-cloned import specifier pins its whole file's backing array. +// Both fixed: 31.4-33.3 MB, against 26.4-27.8 MB at e800129 before the graph +// existed. See blockproto's Inspect doc for the fixture — a tree padded with +// COMMENTS, or whose leaves carry no imports, does not exercise either hazard. +// `app submit` pays this too. func resolveLoadedFiles(dir string, deps map[string]bool) (*blockproto.EntryGraph, bool) { found := false g := blockproto.ResolveEntryGraph(dir, blockproto.EntryGraphOptions{ diff --git a/internal/validate/readyack_test.go b/internal/validate/readyack_test.go index 58f23837..4ef2f8b9 100644 --- a/internal/validate/readyack_test.go +++ b/internal/validate/readyack_test.go @@ -907,6 +907,32 @@ func TestReadyAckAdvisoriesStateTheirOwnStrength(t *testing.T) { }}, } + // 🔴 THE SHARED OPENING DIAGNOSIS, and the reason this test needed a second + // round. `own` literals can only pin a tier that has something UNIQUE to + // say — and the presence tier's three unique literals ALL live in its + // trailing disclosure, so replacing its OPENING ("…but nothing in this + // project's source posts BLOCK_READY") with vague prose survived everything + // below. That is the identical half-vacuous shape this test's own header + // records catching last round, one tier over. + // + // The sentence is shared with the `missing` tier by design — both report an + // absence — so it is asserted as SET MEMBERSHIP: present in exactly those + // two, absent from the tier that fires because the message IS present. + const foundNothing = "nothing in this project's source posts " + for _, tier := range perTier { + wantShared := tier.name != "unwired" + if got := strings.Contains(tier.advice, foundNothing); got != wantShared { + if wantShared { + t.Errorf("the %s advisory no longer opens by saying WHAT WAS FOUND (%q) — every other literal "+ + "this test pins for it lives in the trailing disclosure, so the diagnosis itself was "+ + "unguarded:\n%s", tier.name, foundNothing, tier.advice) + } else { + t.Errorf("the unwired advisory says nothing in the source posts the message, but that tier "+ + "fires precisely because something DOES:\n%s", tier.advice) + } + } + } + for _, tier := range perTier { for _, lit := range tier.own { if !strings.Contains(tier.advice, lit) { diff --git a/internal/validate/readyack_wiring_test.go b/internal/validate/readyack_wiring_test.go index 31fc8ebe..eddf0ed1 100644 --- a/internal/validate/readyack_wiring_test.go +++ b/internal/validate/readyack_wiring_test.go @@ -239,6 +239,110 @@ func TestHTMLSrcIsAURLNotAModuleSpecifier(t *testing.T) { }) } +// TestAttributeNameBoundary is the end-to-end guard for a regression the fix +// round introduced in the class it had just closed: `\b` is not an HTML +// attribute-name boundary, so `data-src=` was read as `src=`. +// +// 🔴 Every case is a CORRECT `static` scaffold. The failure was a false warning +// with `--strict` rc=1, from the STRONG tier — `Complete` stayed true because a +// reference really was found, just the wrong one, so no disclosure engaged. +// `data-src` on a ``, "") + editFile(t, dir, "index.html", ``, + ``) + if err := os.WriteFile(filepath.Join(dir, "shared.js"), []byte("export const s = 1;\n"), 0o600); err != nil { + t.Fatal(err) + } + for i := 0; i < depth; i++ { + body := "" + if i == 0 { + body = "import './shared.js';\n" + } + if i < depth-1 { + body += fmt.Sprintf("import './m%d.js';\n", i+1) + } else { + body += deepest + } + if err := os.WriteFile(filepath.Join(dir, fmt.Sprintf("m%d.js", i)), []byte(body), 0o600); err != nil { + t.Fatal(err) + } + } + // The emitter really is still there — otherwise `unwired` below would be + // the wrong verdict for the right-looking reason. + if _, err := os.Stat(filepath.Join(dir, blockproto.ReadyAckFilename)); err != nil { + t.Fatalf("fixture lost the orphan emitter: %v", err) + } + return dir + } + + t.Run("diamond: the deepest module re-imports an already-walked file", func(t *testing.T) { + wantAckKind(t, build(t, "import './shared.js';\n"), "unwired") + }) + t.Run("self-cycle at the bound", func(t *testing.T) { + wantAckKind(t, build(t, fmt.Sprintf("import './m%d.js';\n", depth-1)), "unwired") + }) + t.Run("control: the deepest module imports nothing", func(t *testing.T) { + // This one has genuinely nothing below the bound, so it must ALSO warn — + // proving the two above are not green merely because the fixture warns + // unconditionally. + wantAckKind(t, build(t, ""), "unwired") + }) + t.Run("negative control: a real truncation still gaps", func(t *testing.T) { + // And something genuinely unseen below the bound must STILL drop to the + // presence tier, or the dedupe check has simply disabled the gap. + dir := build(t, "import './deeper.js';\n") + if err := os.WriteFile(filepath.Join(dir, "deeper.js"), []byte("export const d = 1;\n"), 0o600); err != nil { + t.Fatal(err) + } + g, _ := resolveLoadedFiles(dir, nil) + if g.Complete { + t.Fatalf("a genuinely unwalked module below the bound must still be a gap; gaps=%v", g.Gaps) + } + }) +} + // TestAckBelowTheDepthBoundIsAGapNotAFinding pins the third root-cause bug: the // depth bound truncated the walk WITHOUT clearing Complete, so a correct project // whose emitter sits below it got the strong tier's warning and `--strict` rc=1. From fd8cf9b1af72fa6d4145f21b9a9e79770a5a6117 Mon Sep 17 00:00:00 2001 From: ZacxDev Date: Thu, 6 Aug 2026 15:24:12 -0500 Subject: [PATCH 5/7] fix(validate): the depth-bound check asked g.Files a question it could not answer yet MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Round-3 audit: the truncation dedupe consulted `g.Files`, but files enter there when POPPED, not when QUEUED. A target already enqueued therefore looked absent, so two modules at exactly MaxDepth where the first-enqueued imports the second gapped — or did not — according to THE TEXTUAL ORDER OF TWO IMPORT STATEMENTS. In the losing order an orphaned emitter shipped silently. Reproduced on real scaffolds, flat and nested: 518e514 6288c88 HEAD deepest imports nothing warns warns warns diamond silent warns warns deepest imports its not-yet-walked sibling silent SILENT warns same graph, imports textually swapped silent warns warns The check is now DEFERRED to the end of the walk: once the queue drains, `g.Files` is final and the answer cannot depend on ordering. Pinned by two copies of one graph with the imports swapped, plus a nested variant — the base directory argument was only ever proven where root and module dir coincide. Also pinned (all survived the previous sweep): - both reScriptBlock changes from the last commit: `` must close an inline module, `` must not, and a body is not a script. My first draft of the `` case asserted the opposite and was wrong about HTML — a browser keeps parsing past a bogus close tag, so it is an ACCEPT, and the accept is what discriminates the widening. - truncatedBelow's refUnresolved and resolveRefPath-error arms: a bundler alias or a dangling import at the bound must still gap, or the STRONG tier fires at a correct project. Dropped the unreachable `^` alternative in reSrcAttr rather than leaving a branch no mutation can exercise: reScriptOpen's capture is `([\s/][^>]*)?`, so an attribute list is either empty or starts with whitespace or `/`. AGENTS.md: every memory row now names its fixture (the `e800129` row is the whole-tree grep, so it moves with the tree — an independent measurement on a smaller tree put it at 17.6-17.8 MB; both are right about their own fixture, and the durable fact is the ~18x ratio). Adds an explicit RESIDUALS list: the extensionless-src false negative, large graphs falling to the presence tier more often than the caps suggest, the aliasing property guarded by a measurement rather than a test, the pre-existing ` src=`-inside-an-attribute- value hijack, and computed import(expr) being unmatched. Battery: 57 mutants, 54 killed with attributed failures, 2 null survived as required, 1 declared survivor (strings.Clone, unobservable to any unit test). Co-Authored-By: Claude Opus 5 (1M context) --- AGENTS.md | 44 +++++++++ internal/blockproto/entrygraph.go | 72 +++++++++++---- internal/blockproto/entrygraph_test.go | 123 +++++++++++++++++++++++++ 3 files changed, 221 insertions(+), 18 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 0abd7201..d4646777 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -1050,6 +1050,15 @@ neither one's. Measured; a self-cycle at the bound did the same. A gap that over-fires is not "conservative", it is the false pass wearing a different hat. See `truncatedBelow`. + 🔴 **And the question is DEFERRED to the end of the walk, because + `g.Files` cannot answer it while the walk is running.** Files enter + `g.Files` when POPPED, not when QUEUED, so a target already enqueued looks + absent. Two modules at exactly `MaxDepth` where the first-enqueued imports + the second therefore gapped or did not according to THE TEXTUAL ORDER OF + TWO IMPORT STATEMENTS — and in the losing order an orphaned emitter + shipped silently. Measured flat and nested. Do not move the check back + inline; the fixture pair that pins it is two copies of one graph with the + imports swapped. - 🔴 **THE GRAPH MUST STAY O(ONE FILE), AND THAT TOOK TWO FIXES — THE FIRST ONE ALONE WAS CLAIMED AS COMPLETE AND WAS NOT.** `EntryFile` must not grow a `Code` field again, AND every import specifier must be `strings.Clone`d: @@ -1066,6 +1075,15 @@ neither one's. | `Code` dropped, specifiers aliased | 558 – 628 MB | | both fixed | 31.4 – 33.3 MB | + 🔴 **EVERY ROW IS FIXTURE-DEPENDENT; QUOTE THE FIXTURE WITH THE NUMBER.** + These four are one 400 MB tree of 200 modules (`~2 MiB` each, real code, + each carrying an import). The `e800129` row is the WHOLE-TREE GREP, not + the graph, so it moves with the tree rather than with the entry graph — an + independent measurement on a smaller tree put it at 17.6 – 17.8 MB, and + both are right about their own fixture. The three graph rows reproduce + independently. The ratio is the durable fact: the aliased build is ~18× + the fixed one. + 🔴 **THE FIXTURE SHAPE IS THE MEASUREMENT.** A tree padded with COMMENTS leaves almost nothing after stripping, and a tree whose leaves carry no imports has no specifier to alias — both report a reassuring number while @@ -1101,6 +1119,32 @@ neither one's. the stronger tier does not change that: reachability is still inference from static text, and `--strict` already gives anyone who wants a gate one. + - 🔴 **THE RESIDUALS THIS CHECK KNOWINGLY SHIPS WITH.** Written down because + every one of them was found by an audit rather than by the author, and a + residual nobody records is indistinguishable from a bug nobody noticed: + - **An extensionless `src`** (`` so an INLINE // module's imports can be read. Group 1 is the attribute list, group 2 the - // body. + // 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. - reSrcAttr = regexp.MustCompile(`(?is)(?:^|[\s/])src\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s"'` + "`" + `=<>]+))`) + // 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. diff --git a/internal/blockproto/entrygraph_test.go b/internal/blockproto/entrygraph_test.go index eda8ab87..5a506ed9 100644 --- a/internal/blockproto/entrygraph_test.go +++ b/internal/blockproto/entrygraph_test.go @@ -311,6 +311,47 @@ func TestReadyAckWiringPredicate(t *testing.T) { }, 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 `}, + {"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 From 3aef1ee8ea507dadac6a4c12616f1f6508f11971 Mon Sep 17 00:00:00 2001 From: ZacxDev Date: Thu, 6 Aug 2026 17:56:28 -0500 Subject: [PATCH 6/7] chore: re-trigger CI MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The CI workflow run for 6288c88 and fd8cf9b was never created — GitHub dropped the workflow_run during a repo-wide Actions outage (CodeQL runs for the same commits were created and executed, so the pull_request event itself arrived). No workflow_dispatch trigger on ci.yml, so an empty commit is the way to fire a fresh synchronize. Squash-merge collapses this. Co-Authored-By: Claude Opus 5 (1M context) From ca4d41ec5b4a25351dfadc9e38d29bcc0a357ced Mon Sep 17 00:00:00 2001 From: audit Date: Thu, 6 Aug 2026 18:06:23 -0500 Subject: [PATCH 7/7] chore: re-trigger CI (Actions did not dispatch during the 2026-08-06 outage)